/
ItemHelper.cs
1590 lines (1423 loc) · 70.9 KB
/
ItemHelper.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
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Project: Daggerfall Unity
// Copyright: Copyright (C) 2009-2023 Daggerfall Workshop
// Web Site: http://www.dfworkshop.net
// License: MIT License (http://www.opensource.org/licenses/mit-license.php)
// Source Code: https://github.com/Interkarma/daggerfall-unity
// Original Author: Gavin Clayton (interkarma@dfworkshop.net)
// Contributors: Numidium
//
// Notes:
//
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using DaggerfallConnect;
using DaggerfallConnect.Save;
using DaggerfallConnect.Arena2;
using DaggerfallConnect.FallExe;
using DaggerfallWorkshop.Game.Entity;
using DaggerfallWorkshop.Game.MagicAndEffects;
using DaggerfallWorkshop.Game.Questing;
using DaggerfallWorkshop.Game.Player;
using DaggerfallWorkshop.Game.Serialization;
using DaggerfallWorkshop.Game.UserInterfaceWindows;
using DaggerfallWorkshop.Utility;
using DaggerfallWorkshop.Utility.AssetInjection;
using DaggerfallWorkshop.Game.Utility;
using DaggerfallWorkshop.Game.Formulas;
namespace DaggerfallWorkshop.Game.Items
{
/// <summary>
/// Helper class for working with items.
/// </summary>
public class ItemHelper
{
#region Fields
// This array is in order of ItemEnums.ArtifactsSubTypes
// Each element in array is the texture record index to use for that artifact in TEXTURE.432, TEXTURE.433
// The actual equip placement and whether a left and right hand image exist is derived from item group/groupIndex from usual template data
readonly int[] artifactTextureIndexMappings = { 12, 13, 10, 8, 19, 16, 25, 18, 21, 2, 24, 26, 0, 15, 3, 9, 23, 17, 7, 1, 22, 20, 5 };
const string itemTemplatesFilename = "ItemTemplates";
const string magicItemTemplatesFilename = "MagicItemTemplates";
const string containerIconsFilename = "INVE16I0.CIF";
const string bookMappingFilename = "books";
const int artifactMaleTextureArchive = 432;
const int artifactFemaleTextureArchive = 433;
// Last template index for vanilla DF items, any higher index is a custom item
public const int LastDFTemplate = 287;
public static int WagonKgLimit = 750;
List<ItemTemplate> itemTemplates = new List<ItemTemplate>();
List<MagicItemTemplate> allMagicItemTemplates = new List<MagicItemTemplate>();
List<MagicItemTemplate> artifactItemTemplates = new List<MagicItemTemplate>();
readonly Dictionary<int, ImageData> itemImages = new Dictionary<int, ImageData>();
readonly Dictionary<InventoryContainerImages, ImageData> containerImages = new Dictionary<InventoryContainerImages, ImageData>();
readonly Dictionary<int, String> bookIDNameMapping = new Dictionary<int, String>();
readonly Dictionary<int, String> localizedBookIDNameMapping = new Dictionary<int, string>();
public delegate bool ItemUseHandler(DaggerfallUnityItem item, ItemCollection collection);
Dictionary<int, ItemUseHandler> itemUseHandlers = new Dictionary<int, ItemUseHandler>();
Dictionary<int, Type> customItemTypes = new Dictionary<int, Type>();
Dictionary<ItemGroups, List<int>> customItemGroups = new Dictionary<ItemGroups, List<int>>();
#endregion
#region Properties
/// <summary>
/// Array of all mundane item templates. Does not include magic item data.
/// </summary>
public ItemTemplate[] ItemTemplates => itemTemplates.ToArray();
/// <summary>
/// Array of all magic item templates including artifact data.
/// Data is loaded from MagicItemTemplates.txt, a JSON dump of fixed MAGIC.DEF.
/// </summary>
public MagicItemTemplate[] MagicItemTemplates => allMagicItemTemplates.ToArray();
/// <summary>
/// Array of magic item templates filtered to just artifact data.
/// </summary>
public MagicItemTemplate[] ArtifactItemTemplates => artifactItemTemplates.ToArray();
#endregion
#region Constructors
public ItemHelper()
{
LoadItemTemplates();
LoadMagicItemTemplates();
LoadBookIDNameMapping();
}
#endregion
#region Public Methods
/// <summary>
/// Registers a custom usage handler for a given item template index.
/// Not required for custom items with implementing classes, override UseItem() instead.
/// </summary>
/// <param name="templateIndex">Template index of the item, can be either a classic or custom item</param>
/// <param name="itemUseHander">Implementation of ItemUseHandler delegate to call when item is used</param>
public void RegisterItemUseHandler(int templateIndex, ItemUseHandler itemUseHandler)
{
DaggerfallUnity.LogMessage("RegisterItemUseHandler: TemplateIndex=" + templateIndex);
itemUseHandlers[templateIndex] = itemUseHandler;
}
public bool GetItemUseHandler(int templateIndex, out ItemUseHandler itemUseHandler)
{
return itemUseHandlers.TryGetValue(templateIndex, out itemUseHandler);
}
/// <summary>
/// Registers a custom item defined by an item template entry for in-game generation and with a custom implementation class if required.
/// </summary>
/// <param name="templateIndex">Template index to use for the item, must match entry in item templates</param>
/// <param name="itemGroup">Set to assign the item to a group for purposes of loot generation and shop stocking</param>
/// <param name="itemClassType">Provide the Type of a custom implementation class to be used, which must extend DaggerfallUnityItem</param>
public void RegisterCustomItem(int templateIndex, ItemGroups itemGroup = ItemGroups.None, Type itemClassType = null)
{
if (templateIndex <= LastDFTemplate)
throw new Exception("RegisterCustomItem: Template index must not be of an existing DF item.");
if (itemGroup == ItemGroups.None && itemClassType == null)
throw new Exception("RegisterCustomItem: Nothing specified to register the item .");
DaggerfallUnity.LogMessage("RegisterCustomItem: TemplateIndex=" + templateIndex + ", Class=" + itemClassType + ", Group=" + itemGroup, true);
// Register custom item class
if (itemClassType != null)
{
// Register with item collection for de-serialization, no conflicts allowed here
string itemClassName = itemClassType.ToString();
if (!ItemCollection.RegisterCustomItem(itemClassName, itemClassType))
throw new Exception("RegisterCustomItem: Unable to register the item for de-serialization.");
customItemTypes[templateIndex] = itemClassType;
DaggerfallUnity.LogMessage("RegisterCustomItem: TemplateIndex=" + templateIndex + ", Class=" + itemClassType, true);
}
// Register custom item group
if (itemGroup != ItemGroups.None)
{
List<int> itemTemplateIndexes;
if (!customItemGroups.TryGetValue(itemGroup, out itemTemplateIndexes))
{
itemTemplateIndexes = new List<int>();
customItemGroups[itemGroup] = itemTemplateIndexes;
}
if (!itemTemplateIndexes.Contains(templateIndex))
{
itemTemplateIndexes.Add(templateIndex);
}
DaggerfallUnity.LogMessage("RegisterCustomItem: TemplateIndex=" + templateIndex + ", Class=" + itemClassType + ", Group=" + itemGroup, true);
}
}
public bool GetCustomItemClass(int templateIndex, out Type itemClassType)
{
return customItemTypes.TryGetValue(templateIndex, out itemClassType);
}
public int[] GetCustomItemsForGroup(ItemGroups itemGroup)
{
if (customItemGroups.ContainsKey(itemGroup))
return customItemGroups[itemGroup].ToArray();
return new int[0];
}
/// <summary>
/// Gets item template data using group and index.
/// </summary>
public ItemTemplate GetItemTemplate(ItemGroups itemGroup, int groupIndex)
{
// Items added by mods are after last DF template, with groupIndex == templateIndex
if (groupIndex > LastDFTemplate)
return GetItemTemplate(groupIndex);
Array values = GetEnumArray(itemGroup);
if (groupIndex < 0 || groupIndex >= values.Length)
{
string message = string.Format("Item index out of range: Group={0} Index={1}", itemGroup.ToString(), groupIndex);
Debug.Log(message);
return new ItemTemplate();
}
int templateIndex = Convert.ToInt32(values.GetValue(groupIndex));
return itemTemplates[templateIndex];
}
/// <summary>
/// Gets item template from direct template index.
/// </summary>
public ItemTemplate GetItemTemplate(int templateIndex)
{
// Items added by mods are after last DF template
if (templateIndex > LastDFTemplate)
{
for (int i = LastDFTemplate; i < itemTemplates.Count; i++)
if (itemTemplates[i].index == templateIndex)
return itemTemplates[i];
}
if (templateIndex < 0 || templateIndex >= itemTemplates.Count)
{
string message = string.Format("Item template index out of range: TemplateIndex={0}", templateIndex);
Debug.Log(message);
return new ItemTemplate();
}
return itemTemplates[templateIndex];
}
/// <summary>
/// Gets artifact template from magic item template data.
/// </summary>
public MagicItemTemplate GetArtifactTemplate(int artifactIndex)
{
if (artifactIndex < 0 || artifactIndex >= artifactItemTemplates.Count)
{
string message = string.Format("Artifact template index out of range: ArtifactIndex={0}", artifactIndex);
Debug.Log(message);
return new MagicItemTemplate();
}
return artifactItemTemplates[artifactIndex];
}
/// <summary>
/// Gets item group index from group and template index.
/// </summary>
/// <returns>Item group index, or -1 if not found.</returns>
public int GetGroupIndex(ItemGroups itemGroup, int templateIndex)
{
// Items added by mods are after last DF template, and groupIndex == templateIndex
if (templateIndex > LastDFTemplate)
return templateIndex;
Array values = GetEnumArray(itemGroup);
for (int i = 0; i < values.Length; i++)
{
int checkTemplateIndex = Convert.ToInt32(values.GetValue(i));
if (checkTemplateIndex == templateIndex)
return i;
}
return -1;
}
/// <summary>
/// Resolves full item name using parameters like %it.
/// </summary>
public string ResolveItemName(DaggerfallUnityItem item)
{
// Get item template and localized template name
ItemTemplate template = item.ItemTemplate;
string templateName = TextManager.Instance.GetLocalizedItemName(template.index, template.name);
// Return just the template name if item is unidentified.
if (!item.IsIdentified)
return templateName;
// Return the shortName if item is an artifact
if (item.IsArtifact)
return item.shortName;
// Books are handled differently
if (item.ItemGroup == ItemGroups.Books)
return DaggerfallUnity.Instance.ItemHelper.GetBookTitle(item.message, item.shortName);
// Start with base name
string result = item.shortName;
// Resolve %it parameter
if (!string.IsNullOrEmpty(templateName))
result = result.Replace("%it", templateName);
else
Debug.LogErrorFormat("Item template index {0} has a null templateName", template.index);
return result;
}
/// <summary>
/// Resolves full item name using parameters like %it and material type.
/// </summary>
public string ResolveItemLongName(DaggerfallUnityItem item, bool differentiatePlantIngredients = true)
{
string result = ResolveItemName(item);
// Return result without material prefix if item is unidentified or an Artifact.
if (!item.IsIdentified || item.IsArtifact)
return result;
// Differentiate plant ingredients with 2 variants
if (differentiatePlantIngredients)
{
if (item.ItemGroup == ItemGroups.PlantIngredients1 && item.TemplateIndex < 18)
return string.Format(TextManager.Instance.GetLocalizedText("ingredientFormatString"), result, TextManager.Instance.GetLocalizedText("northern"));
if (item.ItemGroup == ItemGroups.PlantIngredients2 && item.TemplateIndex < 18)
return string.Format(TextManager.Instance.GetLocalizedText("ingredientFormatString"), result, TextManager.Instance.GetLocalizedText("southern"));
}
// Resolve weapon material
if (item.ItemGroup == ItemGroups.Weapons && item.TemplateIndex != (int)Weapons.Arrow)
{
WeaponMaterialTypes weaponMaterial = (WeaponMaterialTypes)item.nativeMaterialValue;
string materialName = DaggerfallUnity.Instance.TextProvider.GetWeaponMaterialName(weaponMaterial);
result = string.Format(TextManager.Instance.GetLocalizedText("longWeaponNameFormatString"), materialName, result);
}
// Resolve armor material
if (item.ItemGroup == ItemGroups.Armor && ArmorShouldShowMaterial(item))
{
ArmorMaterialTypes armorMaterial = (ArmorMaterialTypes)item.nativeMaterialValue;
string materialName = DaggerfallUnity.Instance.TextProvider.GetArmorMaterialName(armorMaterial);
result = string.Format(TextManager.Instance.GetLocalizedText("longArmorNameFormatString"), materialName, result);
}
// Resolve potion names
if (item.IsPotion)
return MacroHelper.GetValue("%po", item);
// Resolve quest letters, get last 2 lines which should be the signoff
if (item.ItemGroup == ItemGroups.UselessItems2 && item.TemplateIndex == (int)UselessItems2.Parchment && item.IsQuestItem)
{
// Get the Item resource from quest
Quest quest = QuestMachine.Instance.GetQuest(item.QuestUID);
if (quest != null)
{
Item questItem = quest.GetItem(item.QuestItemSymbol);
if (questItem.UsedMessageID >= 0)
{
Message msg = quest.GetMessage(questItem.UsedMessageID);
TextFile.Token[] tokens = msg.GetTextTokens(expandMacros:false);
string signoff = "";
int lines = 0;
for (int i = tokens.Length-1; i >= 0; i--)
{
TextFile.Token token = tokens[i];
if (!string.IsNullOrEmpty(token.text))
{
signoff = token.text.Trim() + " " + signoff;
lines++;
}
if (lines >= 1)
return TextManager.Instance.GetLocalizedText("letterPrefix") + signoff;
}
}
}
}
// Show trapped soul name if any
if (item.ItemGroup == ItemGroups.MiscItems && item.TemplateIndex == (int)MiscItems.Soul_trap)
{
if (item.TrappedSoulType != MobileTypes.None)
{
MobileEnemy soul;
if (EnemyBasics.GetEnemy(item.TrappedSoulType, out soul))
{
MobileEnemy mobileEnemy = GameObjectHelper.EnemyDict[(int)item.TrappedSoulType];
result += string.Format(" ({0})", TextManager.Instance.GetLocalizedEnemyName(soul.ID));
}
}
//else
//{
// // Considering showing (empty) for empty soul traps
//}
}
return result;
}
// Gets inventory image
public ImageData GetInventoryImage(DaggerfallUnityItem item)
{
if (item.TemplateIndex == (int)Transportation.Small_cart)
{
// Handle small cart - the template image for this is not correct
// Correct image actually in CIF files
return GetContainerImage(InventoryContainerImages.Wagon);
}
else
{
// Get inventory image
return GetItemImage(item, true, false, true);
}
}
/// <summary>
/// Gets inventory/equip image for specified item.
/// Image will be cached based on material and hand for faster subsequent fetches.
/// Animated item images do not support dyes.
/// </summary>
/// <param name="item">Item to fetch image for.</param>
/// <param name="removeMask">Removes mask index (e.g. around helmets) from final image.</param>
/// <param name="forPaperDoll">Image is for paper doll.</param>
/// <param name="allowAnimation">Read animated textures.</param>
/// <returns>ImageData.</returns>
public ImageData GetItemImage(DaggerfallUnityItem item, bool removeMask = false, bool forPaperDoll = false, bool allowAnimation = false)
{
// Get colour
int color = (int)item.dyeColor;
// Get archive and record indices
int archive = item.InventoryTextureArchive;
int record = item.InventoryTextureRecord;
// Paper doll handling
if (forPaperDoll)
{
// 1H Weapons in right hand need record + 1
if (item.ItemGroup == ItemGroups.Weapons && item.EquipSlot == EquipSlots.RightHand &&
ItemEquipTable.GetItemHands(item) == ItemHands.Either)
record += 1;
}
else
{
// Katanas need +1 for inventory image as they use right-hand image instead of left
if (item.IsOfTemplate(ItemGroups.Weapons, (int)Weapons.Katana))
record += 1;
}
// Use world texture archive if inventory texture not set
// Examples are gold pieces and wayrest painting
if (archive == 0 && record == 0)
{
archive = item.ItemTemplate.worldTextureArchive;
record = item.ItemTemplate.worldTextureRecord;
}
// Get unique key
int key = MakeImageKey(color, archive, record, removeMask);
// Get existing icon if in cache
if (itemImages.ContainsKey(key))
return itemImages[key];
// Load image data
string filename = TextureFile.IndexToFileName(archive);
ImageData data = ImageReader.GetImageData(filename, record, 0, true, false, allowAnimation);
if (data.type == ImageTypes.None)
throw new Exception("GetItemImage() could not load image data.");
// Fix items with known incorrect paper doll offsets
if (archive == 237 && (record == 52 || record == 54))
{
// "Short shirt" template index 202 variants 2 and 5 for human female
data.offset = new DaggerfallConnect.Utility.DFPosition(237, 43);
}
// Get mask texture where alpha 0 is umasked areas of image and alpha 1 are masked areas of image
Texture2D maskTexture;
if (TextureReplacement.TryImportTexture(archive, record, 0, item.dyeColor, TextureMap.Mask, out maskTexture))
data.maskTexture = maskTexture;
else
ImageReader.UpdateMaskTexture(ref data);
Texture2D tex;
if (TextureReplacement.TryImportTexture(archive, record, 0, item.dyeColor, TextureMap.Albedo, out tex))
{
// Assign imported texture
data.texture = tex;
}
else
{
// Remove mask if requested
if (removeMask)
data.dfBitmap = ImageProcessing.ChangeMask(data.dfBitmap);
// Change dye or just update texture
ItemGroups group = item.ItemGroup;
DyeColors dye = (DyeColors)color;
if ((group == ItemGroups.Weapons || group == ItemGroups.Armor) && !item.IsArtifact)
data = ChangeDye(data, dye, DyeTargets.WeaponsAndArmor);
else if (item.ItemGroup == ItemGroups.MensClothing || item.ItemGroup == ItemGroups.WomensClothing)
data = ChangeDye(data, dye, DyeTargets.Clothing);
else
ImageReader.UpdateTexture(ref data);
}
// Add to cache
itemImages.Add(key, data);
return data;
}
/// <summary>
/// Gets item image with custom mask colour.
/// </summary>
/// <param name="item">Item to fetch image for.</param>
/// <param name="maskColor">New mask colour.</param>
/// <param name="forPaperDoll">Image is for paper doll.</param>
/// <returns>ImageData.</returns>
public ImageData GetItemImage(DaggerfallUnityItem item, Color maskColor, bool forPaperDoll = false)
{
// Get base item with mask intact
ImageData result = GetItemImage(item, false, forPaperDoll);
ImageReader.UpdateTexture(ref result, maskColor);
return result;
}
/// <summary>
/// Gets name of artifact.
/// </summary>
/// <param name="type">Artifact subtype.</param>
/// <returns>Artifact name.</returns>
public string GetArtifactName(ArtifactsSubTypes type)
{
return artifactItemTemplates[(int)type].name;
}
/// <summary>
/// Gets artifact texture indices
/// </summary>
/// <param name="type">Artifact subtype.</param>
/// <param name="textureArchiveOut">Texture archive out.</param>
/// <param name="textureRecordOut">Texture record out.</param>
public void GetArtifactTextureIndices(ArtifactsSubTypes type, out int textureArchiveOut, out int textureRecordOut)
{
textureArchiveOut = (GameManager.Instance.PlayerEntity.Gender == Genders.Male) ? artifactMaleTextureArchive : artifactFemaleTextureArchive;
textureRecordOut = artifactTextureIndexMappings[(int)type];
}
/// <summary>
/// Gets artifact sub type by converting short name to enum type.
/// Not compatible with localized artifact names.
/// Should only be used when importing classic saves or older save data where artifactIndexBitfield is not present.
/// </summary>
/// <param name="itemShortName">Item short name.</param>
/// <returns>Artifact sub type or ArtifactsSubTypes.None.</returns>
public static ArtifactsSubTypes LegacyGetArtifactSubType(string itemShortName)
{
itemShortName = itemShortName.Replace("\'", "").Replace(' ', '_');
foreach (var artifactName in Enum.GetNames(typeof(ArtifactsSubTypes)))
{
if (itemShortName.Contains(artifactName))
return (ArtifactsSubTypes)Enum.Parse(typeof(ArtifactsSubTypes), artifactName);
}
return ArtifactsSubTypes.None;
}
/// <summary>
/// Gets artifact sub type using ArtifactIndexBitfield on item.
/// This method is compatible with localized artifact names.
/// Throws exception if not an artifact or item's ArtifactIndexBitfield not properly set.
/// </summary>
/// <param name="item">DaggerfalUnityItem.</param>
/// <returns>ArtifactsSubTypes.</returns>
public static ArtifactsSubTypes GetArtifactSubType(DaggerfallUnityItem item)
{
if (!item.IsArtifact)
throw new Exception("GetArtifactSubType() item is not an artifact.");
if ((item.ArtifactIndexBitfield & 1) == 0)
throw new Exception("GetArtifactSubType() item does not have an artifact index. Item most likely imported from old save data where item shortName was changed.");
return (ArtifactsSubTypes)(item.ArtifactIndexBitfield >> 1);
}
/// <summary>
/// Gets the title of a book from its ID.
/// </summary>
/// <param name="id">The book's ID</param>
/// <param name="defaultBookTitle">The name the book should default to if the lookup fails. (Usually the Item's LongName..."Book" or "Parchment")</param>
/// <returns>The title of the bookd or defaultBookName if no name was found.</returns>
public string GetBookTitle(int id, string defaultBookTitle)
{
// Get cached localized book title if previously read
if (localizedBookIDNameMapping.ContainsKey(id))
return localizedBookIDNameMapping[id];
// Get book title from localized book file as first preference
// Localized title will be cached so file is only read once
string filename = GetBookFileName(id);
LocalizedBook localizedBook = new LocalizedBook();
if (localizedBook.OpenLocalizedBookFile(filename))
{
localizedBookIDNameMapping.Add(id, localizedBook.Title);
return localizedBook.Title;
}
// Fallback to legacy data
string title;
return bookIDNameMapping.TryGetValue(id, out title) ? title : defaultBookTitle;
}
/// <summary>
/// Gets the filename for a book (classic or imported).
/// </summary>
/// <param name="id">The book's ID</param>
/// <returns>The filename of the book or null.</returns>
internal string GetBookFileName(int id)
{
// Map ID 10000 back to correct value of 5 for "Ark'ay The God" to ensure same book file used for both IDs
// This ID is present in some legacy save data and is retained for backwards compatibility only
if (id == 10000)
id = 5;
// Get name for custom book
BookMappingEntry entry;
if (BookReplacement.BookMappingEntries.TryGetValue(id, out entry))
return entry.Name;
// Check if classic book and make name from id
if (bookIDNameMapping.ContainsKey(id))
return BookFile.messageToBookFilename(id);
Debug.LogWarningFormat("ID {0} is not assigned to any known book; a mod that provides books was probably removed.", id);
return null;
}
/// <summary>
/// Obtaining a random book ID is useful for generating books in loot drops, store inventories, etc.
/// If custom books are available, they are chosen only if specified conditions are met.
/// </summary>
/// <returns>A random book ID</returns>
public int GetRandomBookID()
{
const int attempts = 6;
int[] keys = bookIDNameMapping.Keys.ToArray();
for (int i = 0; i < attempts; i++)
{
int id = keys[UnityEngine.Random.Range(0, keys.Length)];
// Localized book conditions have overriding priority
if (LocalizedBook.Exists(id))
{
if (LocalizedBookMeetsConditions(id))
return id;
continue;
}
if (BookReplacement.BookMeetsConditions(id))
return id;
}
return keys.First(x => !BookReplacement.BookMappingEntries.ContainsKey(x));
}
/// <summary>
/// Checks if a localized book defines any conditions for distribution.
/// </summary>
/// <param name="id">ID of localized book.</param>
/// <returns>True if localized book exists and conditions met, otherise false.</returns>
public bool LocalizedBookMeetsConditions(int id)
{
// Read localized book file - unknown localized books are considered to not meet conditions
string filename = GetBookFileName(id);
LocalizedBook book = new LocalizedBook();
if (!book.OpenLocalizedBookFile(filename))
return false;
// Resolve global var - invalid global vars not matching table will be ignored
int globalVar = -1;
bool globalVarSet = false;
if (!string.IsNullOrEmpty(book.WhenVarSet) && QuestMachine.Instance.GlobalVarsTable.HasValue(book.WhenVarSet))
{
globalVar = int.Parse(QuestMachine.Instance.GlobalVarsTable.GetValue("id", book.WhenVarSet));
globalVarSet = GameManager.Instance.PlayerEntity.GlobalVars.GetGlobalVar(globalVar);
}
return !book.IsUnique && (globalVar == -1 || globalVarSet);
}
/// <summary>
/// Gets icon for a container object, such as the wagon.
/// </summary>
/// <param name="type">Container type.</param>
/// <returns>ImageData.</returns>
public ImageData GetContainerImage(InventoryContainerImages type)
{
// Get existing icon if in cache
if (containerImages.ContainsKey(type))
return containerImages[type];
// Load image data
ImageData data = ImageReader.GetImageData(containerIconsFilename, (int)type, 0, true, true);
// Add to cache
containerImages.Add(type, data);
return data;
}
/// <summary>
/// Helper to get interior parts of cloak.
/// This is not cached as only seen on paper doll during refresh.
/// </summary>
/// <param name="item">Item - must be a formal or casual cloak.</param>
/// <returns>ImageData.</returns>
public ImageData GetCloakInteriorImage(DaggerfallUnityItem item)
{
// Must be a formal or casual cloak
if (!IsCloak(item))
return new ImageData();
// Get colour
int color = (int)item.dyeColor;
// Cloak interior source is combination of player texture archive index and template record index
int archive = item.InventoryTextureArchive;
int record = item.ItemTemplate.playerTextureRecord;
// Load image data
string filename = TextureFile.IndexToFileName(archive);
ImageData data = ImageReader.GetImageData(filename, record, 0, true, false);
if (data.type == ImageTypes.None)
throw new Exception("GetCloakBackImage() could not load image data.");
Texture2D tex;
if (TextureReplacement.TryImportTexture(archive, record, 0, item.dyeColor, TextureMap.Albedo, out tex))
{
// Assign imported texture
data.texture = tex;
}
else
{
// Change dye
data = ChangeDye(data, (DyeColors)color, DyeTargets.Clothing);
}
return data;
}
/// <summary>
/// Checks if this item is a formal or casual cloak.
/// </summary>
/// <param name="item">Item to check.</param>
/// <returns>True if formal or casual cloak.</returns>
public bool IsCloak(DaggerfallUnityItem item)
{
// Must be a formal or casual cloak
switch (item.TemplateIndex)
{
case (int)MensClothing.Formal_cloak:
case (int)MensClothing.Casual_cloak:
case (int)WomensClothing.Formal_cloak:
case (int)WomensClothing.Casual_cloak:
return true;
default:
return false;
}
}
public static TextFile.Token[] GetItemInfo(DaggerfallUnityItem item, ITextProvider textProvider)
{
const int paintingTextId = 250;
const int armorTextId = 1000;
const int weaponTextId = 1001;
const int miscTextId = 1003;
const int soulTrapTextId = 1004;
const int letterOfCreditTextId = 1007;
const int potionTextId = 1008;
const int bookTextId = 1009;
const int arrowTextId = 1011;
const int weaponNoMaterialTextId = 1012;
const int armorNoMaterialTextId = 1014;
const int oghmaInfiniumTextId = 1015;
const int houseDeedTextId = 1073;
// Handle by item group
switch (item.ItemGroup)
{
case ItemGroups.Armor:
if (ArmorShouldShowMaterial(item))
return textProvider.GetRSCTokens(armorTextId); // Handle armor showing material
else
return textProvider.GetRSCTokens(armorNoMaterialTextId); // Handle armor not showing material
case ItemGroups.Weapons:
if (item.TemplateIndex == (int)Weapons.Arrow)
return textProvider.GetRSCTokens(arrowTextId); // Handle arrows
else if (item.IsArtifact)
return textProvider.GetRSCTokens(weaponNoMaterialTextId); // Handle artifacts
else
return textProvider.GetRSCTokens(weaponTextId); // Handle weapons
case ItemGroups.Books:
if (item.legacyMagic != null && item.legacyMagic[0].type == EnchantmentTypes.SpecialArtifactEffect)
return textProvider.GetRSCTokens(oghmaInfiniumTextId); // Handle Oghma Infinium
else
return textProvider.GetRSCTokens(bookTextId); // Handle other books
case ItemGroups.Paintings:
// Show painting. (Uses file paint.dat)
return item.InitPaintingInfo(paintingTextId);
case ItemGroups.MiscItems:
// A few items in the MiscItems group have their own text display
if (item.IsPotionRecipe)
return GetPotionRecipeTokens(); // Handle potion recipes
else if (item.TemplateIndex == (int)MiscItems.House_Deed)
return textProvider.GetRSCTokens(houseDeedTextId); // Handle house deeds
else if (item.TemplateIndex == (int)MiscItems.Soul_trap)
return textProvider.GetRSCTokens(soulTrapTextId); // Handle soul traps
else if (item.TemplateIndex == (int)MiscItems.Letter_of_credit)
return textProvider.GetRSCTokens(letterOfCreditTextId); // Handle letters of credit
else
return textProvider.GetRSCTokens(miscTextId); // Default misc items
default:
// Handle potions in glass bottles
// In classic, the check is whether RecordRoot.SublistHead is non-null and of PotionMix type.
if (item.IsPotion)
return textProvider.GetRSCTokens(potionTextId);
// Handle Azura's Star
if (item.legacyMagic != null && item.legacyMagic[0].type == EnchantmentTypes.SpecialArtifactEffect && item.legacyMagic[0].param == 9)
return textProvider.GetRSCTokens(soulTrapTextId);
// Default fallback if none of the above applied
return textProvider.GetRSCTokens(miscTextId);
}
}
/// <summary>
/// Returns whether an armor item should show its material in info popups and tooltips
/// </summary>
private static bool ArmorShouldShowMaterial(DaggerfallUnityItem item)
{
// HelmAndShieldMaterialDisplay setting for showing material for helms and shields:
// 0 : Don't show (classic behavior)
// 1 : Show for all but leather and chain
// 2 : Show for all but leather
// 3 : Show for all
if (item.IsArtifact)
return false;
else if (item.IsShield || item.TemplateIndex == (int)Armor.Helm)
{
if ((DaggerfallUnity.Settings.HelmAndShieldMaterialDisplay == 1)
&& ((ArmorMaterialTypes)item.nativeMaterialValue >= ArmorMaterialTypes.Iron))
return true;
else if ((DaggerfallUnity.Settings.HelmAndShieldMaterialDisplay == 2)
&& ((ArmorMaterialTypes)item.nativeMaterialValue >= ArmorMaterialTypes.Chain))
return true;
else if (DaggerfallUnity.Settings.HelmAndShieldMaterialDisplay == 3)
return true;
else
return false;
}
else
return true;
}
private static TextFile.Token[] GetPotionRecipeTokens()
{
TextFile.Token[] tokens = new TextFile.Token[4];
tokens[0] = TextFile.CreateTextToken(TextManager.Instance.GetLocalizedText("potionRecipeFor"));
tokens[1] = TextFile.CreateFormatToken(TextFile.Formatting.JustifyCenter);
tokens[2] = TextFile.CreateTextToken(TextManager.Instance.GetLocalizedText("potionRecipeWeight"));
tokens[3] = TextFile.CreateFormatToken(TextFile.Formatting.JustifyCenter);
return tokens;
}
/// <summary>
/// Converts Daggerfall weapon to generic API WeaponType.
/// </summary>
/// <param name="item">Weapon to convert.</param>
/// <returns>WeaponTypes.</returns>
public WeaponTypes ConvertItemToAPIWeaponType(DaggerfallUnityItem item)
{
// Must be a weapon
if (item.ItemGroup != ItemGroups.Weapons)
return WeaponTypes.None;
// Find FPS animation set for this weapon type
// Daggerfall re-uses the same animations for many different weapons
// Check for a custom item weapon type, if None then continue
WeaponTypes result = item.GetWeaponType();
if (result != WeaponTypes.None)
return result;
switch (item.TemplateIndex)
{
case (int)Weapons.Dagger:
result = WeaponTypes.Dagger;
break;
case (int)Weapons.Staff:
result = WeaponTypes.Staff;
break;
case (int)Weapons.Tanto:
case (int)Weapons.Shortsword:
case (int)Weapons.Wakazashi:
case (int)Weapons.Broadsword:
case (int)Weapons.Saber:
case (int)Weapons.Longsword:
case (int)Weapons.Katana:
case (int)Weapons.Claymore:
case (int)Weapons.Dai_Katana:
result = WeaponTypes.LongBlade;
break;
case (int)Weapons.Mace:
result = WeaponTypes.Mace;
break;
case (int)Weapons.Flail:
result = WeaponTypes.Flail;
break;
case (int)Weapons.Warhammer:
result = WeaponTypes.Warhammer;
break;
case (int)Weapons.Battle_Axe:
case (int)Weapons.War_Axe:
result = WeaponTypes.Battleaxe;
break;
case (int)Weapons.Short_Bow:
case (int)Weapons.Long_Bow:
result = WeaponTypes.Bow;
break;
default:
return WeaponTypes.None;
}
// Handle enchanted weapons
if (item.IsEnchanted)
{
switch (result)
{
case WeaponTypes.Dagger:
result = WeaponTypes.Dagger_Magic;
break;
case WeaponTypes.Staff:
result = WeaponTypes.Staff_Magic;
break;
case WeaponTypes.LongBlade:
result = WeaponTypes.LongBlade_Magic;
break;
case WeaponTypes.Mace:
result = WeaponTypes.Mace_Magic;
break;
case WeaponTypes.Flail:
result = WeaponTypes.Flail_Magic;
break;
case WeaponTypes.Warhammer:
result = WeaponTypes.Warhammer_Magic;
break;
case WeaponTypes.Battleaxe:
result = WeaponTypes.Battleaxe_Magic;
break;
default:
break;
}
}
return result;
}
/// <summary>
/// Converts native Daggerfall weapon and armor material types to generic Daggerfall Unity MetalType.
/// The old metal type enum may be retired as true materials become better integrated.
/// </summary>
/// <param name="item">Item to convert material to metal type.</param>
/// <returns>MetalTypes.</returns>
public MetalTypes ConvertItemMaterialToAPIMetalType(DaggerfallUnityItem item)
{
// Determine metal type
if (item.ItemGroup == ItemGroups.Weapons)
{
// Overrides for artifacts whose dyes do not match their materials
if (item.IsArtifact)
{
foreach (DaggerfallEnchantment enchantment in item.LegacyEnchantments)
{
if (enchantment.type == EnchantmentTypes.SpecialArtifactEffect)
{
switch (enchantment.param)
{
case (int)ArtifactsSubTypes.Mehrunes_Razor: // Different from classic but Elven matches the paper doll more closely
return MetalTypes.Elven;
case (int)ArtifactsSubTypes.Mace_of_Molag_Bal:
return MetalTypes.Ebony;
case (int)ArtifactsSubTypes.Wabbajack:
return MetalTypes.Dwarven;
default:
break;
}
}
}
// Artifact weapons with no unique effects
if (item.ItemName == "Chrysamere")
return MetalTypes.Mithril;
if (item.ItemName == "Staff of Magnus")
return MetalTypes.Mithril;
}
WeaponMaterialTypes weaponMaterial = (WeaponMaterialTypes)item.nativeMaterialValue;
switch (weaponMaterial)