/
InventoryPanel.cs
529 lines (447 loc) · 23.1 KB
/
InventoryPanel.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
using EndlessClient.Dialogs.Actions;
using EndlessClient.HUD.Inventory;
using EOLib;
using EOLib.Config;
using EOLib.Domain.Character;
using EOLib.Domain.Item;
using EOLib.Domain.Login;
using EOLib.Graphics;
using EOLib.IO;
using EOLib.IO.Extensions;
using EOLib.IO.Pub;
using EOLib.IO.Repositories;
using EOLib.Localization;
using Microsoft.Win32;
using Microsoft.Xna.Framework;
using Optional;
using Optional.Collections;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using XNAControls;
namespace EndlessClient.HUD.Panels
{
public class InventoryPanel : XNAPanel, IHudPanel
{
public const int InventoryRowSlots = 14;
private readonly ICharacterActions _characterActions;
private readonly IStatusLabelSetter _statusLabelSetter;
private readonly IItemStringService _itemStringService;
private readonly IInventoryService _inventoryService;
private readonly IPlayerInfoProvider _playerInfoProvider;
private readonly ICharacterProvider _characterProvider;
private readonly IPaperdollProvider _paperdollProvider;
private readonly ICharacterInventoryProvider _characterInventoryProvider;
private readonly IPubFileProvider _pubFileProvider;
// todo: move slot state to provider/repository pattern so it can be referenced by InventorySpaceValidator
private readonly bool[,] _usedSlots = new bool[4, InventoryRowSlots];
private readonly Dictionary<int, int> _itemSlotMap;
private readonly List<InventoryPanelItem> _childItems = new List<InventoryPanelItem>();
private readonly IXNALabel _weightLabel;
private readonly IXNAButton _drop, _junk, _paperdoll;
//private readonly ScrollBar _scrollBar;
private Option<ICharacterStats> _cachedStats;
private HashSet<IInventoryItem> _cachedInventory;
public INativeGraphicsManager NativeGraphicsManager { get; }
public InventoryPanel(INativeGraphicsManager nativeGraphicsManager,
IInGameDialogActions inGameDialogActions,
ICharacterActions characterActions,
IStatusLabelSetter statusLabelSetter,
IItemStringService itemStringService,
IInventoryService inventoryService,
IPlayerInfoProvider playerInfoProvider,
ICharacterProvider characterProvider,
IPaperdollProvider paperdollProvider,
ICharacterInventoryProvider characterInventoryProvider,
IPubFileProvider pubFileProvider)
{
NativeGraphicsManager = nativeGraphicsManager;
_characterActions = characterActions;
_statusLabelSetter = statusLabelSetter;
_itemStringService = itemStringService;
_inventoryService = inventoryService;
_playerInfoProvider = playerInfoProvider;
_characterProvider = characterProvider;
_paperdollProvider = paperdollProvider;
_characterInventoryProvider = characterInventoryProvider;
_pubFileProvider = pubFileProvider;
_weightLabel = new XNALabel(Constants.FontSize08pt5)
{
DrawArea = new Rectangle(385, 37, 88, 18),
ForeColor = ColorConstants.LightGrayText,
TextAlign = LabelAlignment.MiddleCenter,
Visible = true,
AutoSize = false
};
_itemSlotMap = GetItemSlotMap(_playerInfoProvider.LoggedInAccountName, _characterProvider.MainCharacter.Name);
var weirdOffsetSheet = NativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 27);
_paperdoll = new XNAButton(weirdOffsetSheet, new Vector2(385, 9), new Rectangle(39, 385, 88, 19), new Rectangle(126, 385, 88, 19));
_paperdoll.OnMouseEnter += MouseOverButton;
_paperdoll.OnClick += (_, _) => inGameDialogActions.ShowPaperdollDialog(characterProvider.MainCharacter, isMainCharacter: true);
_drop = new XNAButton(weirdOffsetSheet, new Vector2(389, 68), new Rectangle(0, 15, 38, 37), new Rectangle(0, 52, 38, 37));
_drop.OnMouseEnter += MouseOverButton;
_junk = new XNAButton(weirdOffsetSheet, new Vector2(431, 68), new Rectangle(0, 89, 38, 37), new Rectangle(0, 126, 38, 37));
_junk.OnMouseEnter += MouseOverButton;
_cachedStats = Option.None<ICharacterStats>();
_cachedInventory = new HashSet<IInventoryItem>();
BackgroundImage = NativeGraphicsManager.TextureFromResource(GFXTypes.PostLoginUI, 44);
DrawArea = new Rectangle(102, 330, BackgroundImage.Width, BackgroundImage.Height);
Game.Exiting += SaveInventoryFile;
}
public bool NoItemsDragging() => _childItems.All(x => !x.IsDragging);
public override void Initialize()
{
_weightLabel.Initialize();
_weightLabel.SetParentControl(this);
_paperdoll.Initialize();
_paperdoll.SetParentControl(this);
_drop.Initialize();
_drop.SetParentControl(this);
_junk.Initialize();
_junk.SetParentControl(this);
base.Initialize();
}
protected override void OnUpdateControl(GameTime gameTime)
{
_cachedStats.Match(
some: stats =>
{
stats.SomeWhen(s => s != _characterProvider.MainCharacter.Stats)
.MatchSome(s =>
{
_cachedStats = Option.Some(_characterProvider.MainCharacter.Stats);
_weightLabel.Text = $"{stats[CharacterStat.Weight]} / {stats[CharacterStat.MaxWeight]}";
});
},
none: () =>
{
var stats = _characterProvider.MainCharacter.Stats;
_cachedStats = Option.Some(stats);
_weightLabel.Text = $"{stats[CharacterStat.Weight]} / {stats[CharacterStat.MaxWeight]}";
});
if (!_cachedInventory.SetEquals(_characterInventoryProvider.ItemInventory))
{
var added = _characterInventoryProvider.ItemInventory.Where(i => !_cachedInventory.Any(j => i.ItemID == j.ItemID));
var removed = _cachedInventory.Where(i => !_characterInventoryProvider.ItemInventory.Any(j => i.ItemID == j.ItemID));
var updated = _characterInventoryProvider.ItemInventory.Except(added);
foreach (var item in removed)
{
var matchedItem = _childItems.SingleOrNone(x => x.InventoryItem.ItemID == item.ItemID);
matchedItem.MatchSome(childItem =>
{
childItem.SetControlUnparented();
childItem.Dispose();
_childItems.Remove(childItem);
var itemData = _pubFileProvider.EIFFile[item.ItemID];
_inventoryService.ClearSlots(_usedSlots, childItem.Slot, itemData.Size);
});
}
foreach (var item in updated)
{
var itemData = _pubFileProvider.EIFFile[item.ItemID];
var matchedItem = _childItems.SingleOrNone(x => x.InventoryItem.ItemID == item.ItemID);
matchedItem.MatchSome(childItem =>
{
childItem.InventoryItem = item;
childItem.Text = _itemStringService.GetStringForMapDisplay(itemData, item.Amount);
});
}
foreach (var item in added)
{
var itemData = _pubFileProvider.EIFFile[item.ItemID];
var preferredSlot = _itemSlotMap.SingleOrNone(x => x.Value == item.ItemID).Map(x => x.Key);
var actualSlot = _inventoryService.GetNextOpenSlot(_usedSlots, itemData.Size, preferredSlot);
actualSlot.MatchSome(slot =>
{
_inventoryService.SetSlots(_usedSlots, slot, itemData.Size);
var newItem = new InventoryPanelItem(this, slot, item, itemData);
newItem.Initialize();
newItem.SetParentControl(this);
newItem.Text = _itemStringService.GetStringForMapDisplay(itemData, item.Amount);
newItem.OnMouseEnter += (_, _) => _statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ITEM, newItem.Text);
newItem.DoubleClick += HandleItemDoubleClick;
newItem.DoneDragging += HandleItemDoneDragging;
// side-effect of calling newItem.SetParentControl(this) is that the draw order gets reset
// setting the slot manually here resets it so the item labels render appropriately
newItem.Slot = slot;
_childItems.Add(newItem);
});
}
_cachedInventory = _characterInventoryProvider.ItemInventory.ToHashSet();
}
base.OnUpdateControl(gameTime);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_paperdoll.OnMouseEnter -= MouseOverButton;
_drop.OnMouseEnter -= MouseOverButton;
_junk.OnMouseEnter -= MouseOverButton;
Game.Exiting -= SaveInventoryFile;
SaveInventoryFile(null, EventArgs.Empty);
}
base.Dispose(disposing);
}
private void MouseOverButton(object sender, EventArgs e)
{
var id = sender == _paperdoll
? EOResourceID.STATUS_LABEL_INVENTORY_SHOW_YOUR_PAPERDOLL
: sender == _drop
? EOResourceID.STATUS_LABEL_INVENTORY_DROP_BUTTON
: EOResourceID.STATUS_LABEL_INVENTORY_JUNK_BUTTON;
_statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_BUTTON, id);
}
private static Dictionary<int, int> GetItemSlotMap(string accountName, string characterName)
{
var map = new Dictionary<int, int>();
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && !File.Exists(Constants.InventoryFile))
{
using var inventoryKey = TryGetCharacterRegistryKey(accountName, characterName);
if (inventoryKey != null)
{
for (int i = 0; i < InventoryRowSlots * 4; ++i)
{
if (int.TryParse(inventoryKey.GetValue($"item{i}")?.ToString() ?? string.Empty, out var id))
map[i] = id;
}
}
}
var inventory = new IniReader(Constants.InventoryFile);
if (inventory.Load() && inventory.Sections.ContainsKey(accountName))
{
var section = inventory.Sections[accountName];
foreach (var key in section.Keys.Where(x => x.Contains(characterName, StringComparison.OrdinalIgnoreCase)))
{
if (!key.Contains("."))
continue;
var slot = key.Split(".")[1];
if (!int.TryParse(slot, out var slotIndex))
continue;
if (int.TryParse(section[key], out var id))
map[slotIndex] = id;
}
}
return map;
}
[SupportedOSPlatform("Windows")]
private static RegistryKey TryGetCharacterRegistryKey(string accountName, string characterName)
{
using RegistryKey currentUser = Registry.CurrentUser;
var pathSegments = $"Software\\EndlessClient\\{accountName}\\{characterName}\\inventory".Split('\\');
var currentPath = string.Empty;
RegistryKey retKey = null;
foreach (var segment in pathSegments)
{
retKey?.Dispose();
currentPath = Path.Combine(currentPath, segment);
retKey = currentUser.CreateSubKey(currentPath, RegistryKeyPermissionCheck.ReadSubTree);
}
return retKey;
}
private void SaveInventoryFile(object sender, EventArgs e)
{
var inventory = new IniReader(Constants.InventoryFile);
var section = inventory.Load() && inventory.Sections.ContainsKey(_playerInfoProvider.LoggedInAccountName)
? inventory.Sections[_playerInfoProvider.LoggedInAccountName]
: new SortedList<string, string>();
foreach (var item in _childItems)
section[$"{_characterProvider.MainCharacter.Name}.{item.Slot}"] = $"{item.InventoryItem.ItemID}";
inventory.Sections[_playerInfoProvider.LoggedInAccountName] = section;
inventory.Save();
base.UnloadContent();
}
private void HandleItemDoubleClick(object sender, EIFRecord itemData)
{
var c = _characterProvider.MainCharacter;
if (!_paperdollProvider.VisibleCharacterPaperdolls.ContainsKey(c.ID))
return;
var isAlternateEquipLocation = false;
switch (itemData.Type)
{
case ItemType.Armlet:
case ItemType.Bracer:
case ItemType.Ring:
var paperdoll = _paperdollProvider.VisibleCharacterPaperdolls[c.ID].Paperdoll;
var equipLocation = itemData.GetEquipLocation();
if (paperdoll[equipLocation] != 0)
{
isAlternateEquipLocation = true;
if (paperdoll[equipLocation + 1] != 0)
{
_statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_ITEM_EQUIP_TYPE_ALREADY_EQUIPPED);
return;
}
}
goto case ItemType.Weapon;
case ItemType.Armor:
if (c.RenderProperties.Gender != itemData.Gender)
{
_statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_ITEM_EQUIP_DOES_NOT_FIT_GENDER);
return;
}
goto case ItemType.Weapon;
case ItemType.Accessory:
case ItemType.Belt:
case ItemType.Boots:
case ItemType.Gloves:
case ItemType.Hat:
case ItemType.Necklace:
case ItemType.Shield:
case ItemType.Weapon:
var reqs = new int[6];
var reqNames = new[] { "STR", "INT", "WIS", "AGI", "CON", "CHA" };
if ((reqs[0] = itemData.StrReq) > c.Stats[CharacterStat.Strength] || (reqs[1] = itemData.IntReq) > c.Stats[CharacterStat.Intelligence]
|| (reqs[2] = itemData.WisReq) > c.Stats[CharacterStat.Wisdom] || (reqs[3] = itemData.AgiReq) > c.Stats[CharacterStat.Agility]
|| (reqs[4] = itemData.ConReq) > c.Stats[CharacterStat.Constituion] || (reqs[5] = itemData.ChaReq) > c.Stats[CharacterStat.Charisma])
{
var req = reqs.Select((i, n) => new { Req = n, Ndx = i }).First(x => x.Req > 0);
_statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION,
EOResourceID.STATUS_LABEL_ITEM_EQUIP_THIS_ITEM_REQUIRES,
$" {reqs[req.Ndx]} {reqNames[req.Ndx]}");
return;
}
if (itemData.ClassReq > 0 && itemData.ClassReq != c.ClassID)
{
_statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION,
EOResourceID.STATUS_LABEL_ITEM_EQUIP_CAN_ONLY_BE_USED_BY,
_pubFileProvider.ECFFile[itemData.ClassReq].Name);
return;
}
paperdoll = _paperdollProvider.VisibleCharacterPaperdolls[c.ID].Paperdoll;
equipLocation = itemData.GetEquipLocation();
if (paperdoll[equipLocation] != 0 && !isAlternateEquipLocation)
{
_statusLabelSetter.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_INFORMATION, EOResourceID.STATUS_LABEL_ITEM_EQUIP_TYPE_ALREADY_EQUIPPED);
return;
}
_characterActions.EquipItem((short)itemData.ID, isAlternateEquipLocation);
break;
//usable items
case ItemType.Teleport:
//if (!OldWorld.Instance.ActiveMapRenderer.MapRef.Properties.CanScroll)
//{
// EOGame.Instance.Hud.SetStatusLabel(EOResourceID.STATUS_LABEL_TYPE_ACTION, EOResourceID.STATUS_LABEL_NOTHING_HAPPENED);
// break;
//}
//if (m_itemData.ScrollMap == OldWorld.Instance.MainPlayer.ActiveCharacter.CurrentMap &&
// m_itemData.ScrollX == OldWorld.Instance.MainPlayer.ActiveCharacter.X &&
// m_itemData.ScrollY == OldWorld.Instance.MainPlayer.ActiveCharacter.Y)
break; //already there - no need to scroll!
//useItem = true;
break;
case ItemType.Heal:
case ItemType.HairDye:
case ItemType.Beer:
//useItem = true;
break;
case ItemType.CureCurse:
//note: don't actually set the useItem bool here. Call API.UseItem if the dialog result is OK.
//if (c.PaperDoll.Select(id => OldWorld.Instance.EIF[id])
// .Any(rec => rec.Special == ItemSpecial.Cursed))
//{
// EOMessageBox.Show(DialogResourceID.ITEM_CURSE_REMOVE_PROMPT, EODialogButtons.OkCancel, EOMessageBoxStyle.SmallDialogSmallHeader,
// (o, e) =>
// {
// //if (e.Result == XNADialogResult.OK && !m_api.UseItem((short)m_itemData.ID))
// //{
// // ((EOGame)Game).DoShowLostConnectionDialogAndReturnToMainMenu();
// //}
// });
//}
break;
case ItemType.EXPReward:
//useItem = true;
break;
case ItemType.EffectPotion:
//useItem = true;
break;
//Not implemented server-side
//case ItemType.SkillReward:
// break;
//case ItemType.StatReward:
// break;
}
//if (useItem && !m_api.UseItem((short)m_itemData.ID))
// ((EOGame)Game).DoShowLostConnectionDialogAndReturnToMainMenu();
}
private void HandleItemDoneDragging(object sender, InventoryPanelItem.ItemDragCompletedEventArgs e)
{
var item = sender as InventoryPanelItem;
if (item == null)
return;
var oldSlot = item.Slot;
var newSlot = item.GetCurrentSlotBasedOnPosition();
// check overlapping items:
// 1. If there's multiple items under it, snap it back to the original slot
// 2. If there's only one item under it, start dragging that item
// 3. If there's nothing under it, make sure it fits in the inventory, otherwise snap back to original slot
var overlapped = GetOverlappingTakenSlots(newSlot, e.Data.Size, _childItems.Except(new[] { item }).Select(x => (x.Slot, x.Data.Size)))
.ToList();
if (overlapped.Count > 1)
{
e.RestoreOriginalSlot = true;
if (!_inventoryService.FitsInSlot(_usedSlots, oldSlot, e.Data.Size))
e.ContinueDrag = true;
}
else if (overlapped.Count == 1)
{
_inventoryService.ClearSlots(_usedSlots, oldSlot, e.Data.Size);
_inventoryService.SetSlots(_usedSlots, newSlot, e.Data.Size);
// start a chained drag on another item (see below comment)
_childItems.Single(x => x.Slot == overlapped[0]).StartDragging();
}
else if (oldSlot != newSlot)
{
if (!_inventoryService.FitsInSlot(_usedSlots, oldSlot, newSlot, e.Data.Size))
{
// if the original slot no longer fits (because this is a chained drag), don't stop dragging this item
if (!_inventoryService.FitsInSlot(_usedSlots, oldSlot, e.Data.Size))
e.ContinueDrag = true;
else
e.RestoreOriginalSlot = true;
}
else
{
_inventoryService.ClearSlots(_usedSlots, oldSlot, e.Data.Size);
_inventoryService.SetSlots(_usedSlots, newSlot, e.Data.Size);
}
}
// todo: handle drag to things (dialog, map, buttons)
}
private static IEnumerable<int> GetOverlappingTakenSlots(int newSlot, ItemSize size, IEnumerable<(int Slot, ItemSize Size)> items)
{
var slotX = newSlot % InventoryRowSlots;
var slotY = newSlot / InventoryRowSlots;
var slotItemDim = size.GetDimensions();
var newSlotCoords = new List<(int X, int Y)>();
for (int r = slotY; r < slotY + slotItemDim.Height; r++)
for (int c = slotX; c < slotX + slotItemDim.Width; c++)
newSlotCoords.Add((c, r));
foreach (var item in items)
{
var itemX = item.Slot % InventoryRowSlots;
var itemY = item.Slot / InventoryRowSlots;
var itemDim = item.Size.GetDimensions();
var @break = false;
for (int r = itemY; r < itemY + itemDim.Height; r++)
{
if (@break)
break;
for (int c = itemX; c < itemX + itemDim.Width; c++)
{
if (newSlotCoords.Contains((c, r)))
{
yield return item.Slot;
@break = true;
break;
}
}
}
}
}
}
}