forked from IlliumIv/Stashie
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStashie.cs
1365 lines (1168 loc) · 54.3 KB
/
Stashie.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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using ExileCore;
using ExileCore.PoEMemory.Components;
using ExileCore.PoEMemory.Elements.InventoryElements;
using ExileCore.PoEMemory.MemoryObjects;
using ExileCore.Shared;
using ExileCore.Shared.Enums;
using ExileCore.Shared.Nodes;
using ImGuiNET;
using SharpDX;
using Vector4 = System.Numerics.Vector4;
namespace Stashie
{
public class StashieCore : BaseSettingsPlugin<StashieSettings>
{
private const string StashTabsNameChecker = "Stash Tabs Name Checker";
private const string FiltersConfigFilePrimary = "FiltersConfig.txt";
private const string FiltersConfigFileSecondary = "FiltersConfig2.txt";
private const int WhileDelay = 5;
private const int InputDelay = 15;
private const string CoroutineName = "Drop To Stash";
private readonly Stopwatch _debugTimer = new Stopwatch();
private readonly Stopwatch _stackItemTimer = new Stopwatch();
private readonly WaitTime _wait10Ms = new WaitTime(10);
private readonly WaitTime _wait3Ms = new WaitTime(3);
private Vector2 _clickWindowOffset;
private List<CustomFilter> _customFiltersPrimary;
private List<RefillProcessor> _customRefills;
private List<FilterResult> _dropItems;
private List<ListIndexNode> _settingsListNodes;
private uint _coroutineIteration;
private Coroutine _coroutineWorker;
private Action _filterTabs;
private string[] _stashTabNamesByIndex;
private Coroutine _stashTabNamesCoroutine;
private int _visibleStashIndex = -1;
private const int MaxShownSidebarStashTabs = 31;
private int _stashCount;
private bool secondaryFilterActive = false;
public StashieCore()
{
Name = "Stashie";
}
public override void ReceiveEvent(string eventId, object args)
{
if (!Settings.Enable.Value)
{
return;
}
switch (eventId)
{
case "switch_to_tab":
HandleSwitchToTabEvent(args);
break;
default:
break;
}
}
private void HandleSwitchToTabEvent(object tab)
{
switch (tab)
{
case int index:
_coroutineWorker = new Coroutine(ProcessSwitchToTab(index), this, CoroutineName);
break;
case string name:
if (!_renamedAllStashNames.Contains(name))
{
DebugWindow.LogMsg($"{Name}: can't find tab with name '{name}'.");
break;
}
var tempIndex = _renamedAllStashNames.IndexOf(name);
_coroutineWorker = new Coroutine(ProcessSwitchToTab(tempIndex), this, CoroutineName);
DebugWindow.LogMsg($"{Name}: Switching to tab with index: {tempIndex} ('{name}').");
break;
default:
DebugWindow.LogMsg("The received argument is not a string or an integer.");
break;
}
Core.ParallelRunner.Run(_coroutineWorker);
}
public override bool Initialise()
{
Settings.Enable.OnValueChanged += (sender, b) =>
{
if (b)
{
if (Core.ParallelRunner.FindByName(StashTabsNameChecker) == null) InitStashTabNameCoRoutine();
_stashTabNamesCoroutine?.Resume();
}
else
{
_stashTabNamesCoroutine?.Pause();
}
SetupOrClose();
};
InitStashTabNameCoRoutine();
SetupOrClose();
Input.RegisterKey(Settings.DropHotkey);
Settings.DropHotkey.OnValueChanged += () => { Input.RegisterKey(Settings.DropHotkey); };
Settings.SwitchFilterhotkey.OnValueChanged += () => { Input.RegisterKey(Settings.SwitchFilterhotkey); };
_stashCount = (int) GameController.Game.IngameState.IngameUi.StashElement.TotalStashes;
return true;
}
public override void AreaChange(AreaInstance area)
{
if (_stashTabNamesCoroutine == null) return;
if (_stashTabNamesCoroutine.Running)
{
if(!area.IsHideout && !area.IsTown &&
!area.DisplayName.Contains("Azurite Mine") &&
!area.DisplayName.Contains("Tane's Laboratory"))
_stashTabNamesCoroutine?.Pause();
}
else
{
if (area.IsHideout ||
area.IsTown ||
area.DisplayName.Contains("Azurite Mine") ||
area.DisplayName.Contains("Tane's Laboratory"))
_stashTabNamesCoroutine?.Resume();
}
}
private void InitStashTabNameCoRoutine()
{
_stashTabNamesCoroutine = new Coroutine(StashTabNamesUpdater_Thread(), this, StashTabsNameChecker);
Core.ParallelRunner.Run(_stashTabNamesCoroutine);
}
/// <summary>
/// Creates a new file and adds the content to it if the file doesn't exists.
/// If the file already exists, then no action is taken.
/// </summary>
/// <param name="path">The path to the file on disk</param>
/// <param name="content">The content it should contain</param>
private static void WriteToNonExistentFile(string path, string content)
{
if (File.Exists(path)) return;
using (var streamWriter = new StreamWriter(path, true))
{
streamWriter.Write(content);
streamWriter.Close();
}
}
private void SaveDefaultConfigsToDisk()
{
var path = $"{DirectoryFullName}\\GitUpdateConfig.txt";
const string gitUpdateConfig = "Owner:nymann\r\n" + "Name:Stashie\r\n" + "Release\r\n";
WriteToNonExistentFile(path, gitUpdateConfig);
path = $"{DirectoryFullName}\\RefillCurrency.txt";
const string refillCurrency = "//MenuName:\t\t\tClassName,\t\t\tStackSize,\tInventoryX,\tInventoryY\r\n" +
"Portal Scrolls:\t\tPortal Scroll,\t\t40,\t\t\t12,\t\t\t1\r\n" +
"Scrolls of Wisdom:\tScroll of Wisdom,\t40,\t\t\t12,\t\t\t2\r\n" +
"//Chances:\t\t\tOrb of Chance,\t\t20,\t\t\t12,\t\t\t3";
WriteToNonExistentFile(path, refillCurrency);
path = $"{DirectoryFullName}\\FiltersConfig.txt";
const string filtersConfig =
#region default config String
"//FilterName(menu name):\tfilters\t\t:ParentMenu(optionally, will be created automatically for grouping)\r\n" +
"//Filter parts should divided by coma or | (for OR operation(any filter part can pass))\r\n" +
"\r\n" +
"////////////\tAvailable properties:\t/////////////////////\r\n" +
"/////////\tString (name) properties:\r\n" +
"//classname\r\n" +
"//basename\r\n" +
"//path\r\n" +
"/////////\tNumerical properties:\r\n" +
"//itemquality\r\n" +
"//rarity\r\n" +
"//ilvl\r\n" +
"//tier\r\n" +
"//numberofsockets\r\n" +
"//numberoflinks\r\n" +
"//veiled\r\n" +
"//fractured\r\n" +
"/////////\tBoolean properties:\r\n" +
"//identified\r\n" +
"//fractured\r\n" +
"//corrupted\r\n" +
"//influenced\r\n" +
"//Elder\r\n" +
"//Shaper\r\n" +
"//Crusader\r\n" +
"//Hunter\r\n" +
"//Redeemer\r\n" +
"//Warlord\r\n" +
"//blightedMap\r\n" +
"//elderGuardianMap\r\n" +
"/////////////////////////////////////////////////////////////\r\n" +
"////////////\tAvailable operations:\t/////////////////////\r\n" +
"/////////\tString (name) operations:\r\n" +
"//!=\t(not equal)\r\n" +
"//=\t\t(equal)\r\n" +
"//^\t\t(contains)\r\n" +
"//!^\t(not contains)\r\n" +
"/////////\tNumerical operations:\r\n" +
"//!=\t(not equal)\r\n" +
"//=\t\t(equal)\r\n" +
"//>\t\t(bigger)\r\n" +
"//<\t\t(less)\r\n" +
"//<=\t(less or equal)\r\n" +
"//>=\t(greater or equal)\r\n" +
"/////////\tBoolean operations:\r\n" +
"//!\t\t(not/invert)\r\n" +
"/////////////////////////////////////////////////////////////\r\n" +
"\r\n" +
"//Default Tabs\r\n" +
"Currency:\t\t\tClassName=StackableCurrency,path!^Essence,BaseName!^Remnant,path!^CurrencyDelveCrafting,BaseName!^Splinter,Path!^CurrencyItemisedProphecy,Path!^CurrencyAfflictionOrb,Path!^Mushrune\t:Default Tabs\r\n" +
"Divination Cards:\t\t\tClassName=DivinationCard\t\t\t\t\t:Default Tabs\r\n" +
"Essences:\t\t\tBaseName^Essence|BaseName^Remnant,ClassName=StackableCurrency:Default Tabs\r\n" +
"Fragments:\t\t\tClassName=MapFragment|BaseName^Splinter,ClassName=StackableCurrency|ClassName=LabyrinthMapItem|BaseName^Scarab\t:Default Tabs\r\n" +
"Maps:\t\t\tClassName=Map,!blightedMap\t\t\t:Default Tabs\r\n" +
"Fossils/Resonators:\t\t\tpath^CurrencyDelveCrafting | path^DelveStackableSocketableCurrency\t:Default Tabs\r\n" +
"Gems:\t\t\t\tClassName^Skill Gem,ItemQuality=0\t\t\t:Default Tabs\r\n" +
"6-Socket:\t\t\tnumberofsockets=6,numberoflinks!=6\t\t\t:Default Tabs\r\n" +
"Prophecies:\t\t\tPath^CurrencyItemisedProphecy\t\t\t:Default Tabs\r\n" +
"Jewels:\t\t\t\tClassName=Jewel,Rarity != Unique\t\t\t\t\t\t\t\t:Default Tabs\r\n" +
"\r\n" +
"//Special Items\r\n" +
"Veiled:\t\t\tVeiled>0\t:Special items\r\n" +
"AnyInfluence:\t\t\tinfluenced\t:Special items\r\n" +
"\r\n" +
"//league Content\r\n" +
"Legion-Incubators:\t\t\tpath^CurrencyIncubation\t:League Items\r\n" +
"Delirium-Splinter:\t\t\tpath^CurrencyAfflictionShard\t:League Items\r\n" +
"Delirium-Simulacrum:\t\t\tpath^CurrencyAfflictionFragment\t:League Items\r\n" +
"Blight-AnnointOils:\t\t\tpath^Mushrune\t:League Items\r\n" +
"//Chance Items\r\n" +
"Sorcerer Boots:\tBaseName=Sorcerer Boots,Rarity=Normal\t:Chance Items\r\n" +
"Leather Belt:\tBaseName=Leather Belt,Rarity=Normal\t\t:Chance Items\r\n" +
"\r\n" +
"//Vendor Recipes\r\n" +
"Chisel Recipe:\t\tBaseName=Stone Hammer|BaseName=Rock Breaker,ItemQuality=20\t:Vendor Recipes\r\n" +
"Quality Gems:\t\tClassName^Skill Gem,ItemQuality>0\t\t\t\t\t\t\t:Vendor Recipes\r\n" +
"Quality Flasks:\t\tClassName^Flask,ItemQuality>0\t\t\t\t\t\t\t\t:Vendor Recipes\r\n" +
"\r\n" +
"//Chaos Recipe LVL 2 (unindentified and ilvl 60 or above)\r\n" +
"Weapons:\t\t!identified,Rarity=Rare,ilvl>=60,ClassName^Two Hand|ClassName^One Hand|ClassName=Bow|ClassName=Staff|ClassName=Sceptre|ClassName=Wand|ClassName=Dagger|ClassName=Claw|ClassName=Shield :Chaos Recipe\r\n" +
"Jewelry:\t\t!identified,Rarity=Rare,ilvl>=60,ClassName=Ring|ClassName=Amulet \t:Chaos Recipe\r\n" +
"Belts:\t\t\t!identified,Rarity=Rare,ilvl>=60,ClassName=Belt \t\t\t\t\t:Chaos Recipe\r\n" +
"Helms:\t\t\t!identified,Rarity=Rare,ilvl>=60,ClassName=Helmet \t\t\t\t\t:Chaos Recipe\r\n" +
"Body Armours:\t!identified,Rarity=Rare,ilvl>=60,ClassName=Body Armour \t\t\t\t:Chaos Recipe\r\n" +
"Boots:\t\t\t!identified,Rarity=Rare,ilvl>=60,ClassName=Boots \t\t\t\t\t:Chaos Recipe\r\n" +
"Gloves:\t\t\t!identified,Rarity=Rare,ilvl>=60,ClassName=Gloves \t\t\t\t\t:Chaos Recipe";
#endregion
WriteToNonExistentFile(path, filtersConfig);
}
public override void DrawSettings()
{
DrawReloadConfigButton();
DrawIgnoredCellsSettings();
base.DrawSettings();
foreach (var settingsCustomRefillOption in Settings.CustomRefillOptions)
{
var value = settingsCustomRefillOption.Value.Value;
ImGui.SliderInt(settingsCustomRefillOption.Key, ref value, settingsCustomRefillOption.Value.Min,
settingsCustomRefillOption.Value.Max);
settingsCustomRefillOption.Value.Value = value;
}
_filterTabs?.Invoke();
}
private void LoadCustomFilters()
{
string filter = FiltersConfigFilePrimary;
if (secondaryFilterActive)
{
filter = FiltersConfigFileSecondary;
}
var filterFilePath = Path.Combine(DirectoryFullName, filter);
var filterLines = File.ReadAllLines(filterFilePath);
_customFiltersPrimary = FilterParser.Parse(filterLines);
foreach (var customFilter in _customFiltersPrimary)
{
if (!Settings.CustomFilterOptions.TryGetValue(customFilter.Name, out var indexNodeS))
{
indexNodeS = new ListIndexNode {Value = "Ignore", Index = -1};
Settings.CustomFilterOptions.Add(customFilter.Name, indexNodeS);
}
customFilter.StashIndexNode = indexNodeS;
_settingsListNodes.Add(indexNodeS);
}
}
public void SaveIgnoredSLotsFromInventoryTemplate()
{
Settings.IgnoredCells = new[,]
{
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
};
try
{
var inventory = GameController.Game.IngameState.IngameUi.InventoryPanel[InventoryIndex.PlayerInventory];
foreach (var item in inventory.VisibleInventoryItems)
{
var baseC = item.Item.GetComponent<Base>();
var itemSizeX = baseC.ItemCellsSizeX;
var itemSizeY = baseC.ItemCellsSizeY;
var inventPosX = item.InventPosX;
var inventPosY = item.InventPosY;
for (var y = 0; y < itemSizeY; y++)
for (var x = 0; x < itemSizeX; x++)
Settings.IgnoredCells[y + inventPosY, x + inventPosX] = 1;
}
}
catch (Exception e)
{
LogError($"{e}", 5);
}
}
private void DrawReloadConfigButton()
{
if (ImGui.Button("Reload config"))
{
LoadCustomFilters();
GenerateMenu();
DebugWindow.LogMsg("Reloaded Stashie config", 2, Color.LimeGreen);
}
}
private void DrawIgnoredCellsSettings()
{
try
{
if (ImGui.Button("Copy Inventory")) SaveIgnoredSLotsFromInventoryTemplate();
ImGui.SameLine();
ImGui.TextDisabled("(?)");
if (ImGui.IsItemHovered())
ImGui.SetTooltip(
$"Checked = Item will be ignored{Environment.NewLine}UnChecked = Item will be processed");
}
catch (Exception e)
{
LogError(e.ToString(), 10);
}
var numb = 1;
for (var i = 0; i < 5; i++)
for (var j = 0; j < 12; j++)
{
var toggled = Convert.ToBoolean(Settings.IgnoredCells[i, j]);
if (ImGui.Checkbox($"##{numb}IgnoredCells", ref toggled)) Settings.IgnoredCells[i, j] ^= 1;
if ((numb - 1) % 12 < 11) ImGui.SameLine();
numb += 1;
}
}
private void GenerateMenu()
{
var font = GameController.Settings.CoreSettings.Font.Value;
var fontSize = int.Parse(font.Substring(font.Length - 2));
_stashTabNamesByIndex = _renamedAllStashNames.ToArray();
_filterTabs = null;
foreach (var customFilter in _customFiltersPrimary.GroupBy(x => x.SubmenuName, e => e))
_filterTabs += () =>
{
ImGui.TextColored(new Vector4(0f, 1f, 0.022f, 1f), customFilter.Key);
foreach (var filter in customFilter)
if (Settings.CustomFilterOptions.TryGetValue(filter.Name, out var indexNode))
{
var formattableString = $"{filter.Name} => {_renamedAllStashNames[indexNode.Index + 1]}";
ImGui.Columns(2, formattableString, true);
ImGui.SetColumnWidth(0, 300);
ImGui.SetColumnWidth(1, 160);
if (ImGui.Button(formattableString, new System.Numerics.Vector2(180, fontSize + 7)))
ImGui.OpenPopup(formattableString);
ImGui.SameLine();
ImGui.NextColumn();
var item = indexNode.Index + 1;
var filterName = filter.Name;
if (string.IsNullOrWhiteSpace(filterName))
filterName = "Null";
if (ImGui.Combo($"##{filterName}", ref item, _stashTabNamesByIndex,
_stashTabNamesByIndex.Length))
{
indexNode.Value = _stashTabNamesByIndex[item];
OnSettingsStashNameChanged(indexNode, _stashTabNamesByIndex[item]);
}
ImGui.NextColumn();
ImGui.Columns(1, "", false);
var pop = true;
if (!ImGui.BeginPopupModal(formattableString, ref pop,
ImGuiWindowFlags.NoResize | ImGuiWindowFlags.AlwaysAutoResize)) continue;
var x = 0;
foreach (var name in _renamedAllStashNames)
{
x++;
if (ImGui.Button($"{name}", new System.Numerics.Vector2(100, fontSize + 7)))
{
indexNode.Value = name;
OnSettingsStashNameChanged(indexNode, name);
ImGui.CloseCurrentPopup();
}
if (x % 10 != 0)
ImGui.SameLine();
}
ImGui.Spacing();
ImGuiNative.igIndent(350);
if (ImGui.Button("Close", new System.Numerics.Vector2(180, fontSize + 7)))
ImGui.CloseCurrentPopup();
ImGui.EndPopup();
}
else
{
indexNode = new ListIndexNode {Value = "Ignore", Index = -1};
}
};
}
private void LoadCustomRefills()
{
_customRefills = RefillParser.Parse(DirectoryFullName);
if (_customRefills.Count == 0) return;
foreach (var refill in _customRefills)
{
if (!Settings.CustomRefillOptions.TryGetValue(refill.MenuName, out var amountOption))
{
amountOption = new RangeNode<int>(15, 0, refill.StackSize);
Settings.CustomRefillOptions.Add(refill.MenuName, amountOption);
}
amountOption.Max = refill.StackSize;
refill.AmountOption = amountOption;
}
_settingsListNodes.Add(Settings.CurrencyStashTab);
}
public override Job Tick()
{
try
{
if (Core.ParallelRunner.FindByName("Stashie_DropItemsToStash") == null)
{
if (Settings.SwitchFilterhotkey.PressedOnce())
{
secondaryFilterActive = !secondaryFilterActive;
SetupOrClose();
LogMessage($"Stashie: Currently active Filter: {(!secondaryFilterActive ? "primary" : "secondary")}", 5);
}
}
if (!stashingRequirementsMet() && Core.ParallelRunner.FindByName("Stashie_DropItemsToStash") != null)
{
StopCoroutine("Stashie_DropItemsToStash");
return null;
}
}
catch (Exception e) { if (Settings.Debug) throw e; }
if (Settings.DropHotkey.PressedOnce())
{
if(Core.ParallelRunner.FindByName("Stashie_DropItemsToStash") == null)
{
StartDropItemsToStashCoroutine();
}
else
{
StopCoroutine("Stashie_DropItemsToStash");
}
}
return null;
}
private void StartDropItemsToStashCoroutine()
{
_debugTimer.Reset();
_debugTimer.Start();
Core.ParallelRunner.Run(new Coroutine(DropToStashRoutine(), this, "Stashie_DropItemsToStash"));
}
private void StopCoroutine(string routineName)
{
var routine = Core.ParallelRunner.FindByName(routineName);
routine?.Done();
_debugTimer.Stop();
_debugTimer.Reset();
CleanUp();
}
private IEnumerator DropToStashRoutine()
{
var cursorPosPreMoving = Input.ForceMousePosition; //saving cursorposition
//try stashing items 3 times
var originTab = GetIndexOfCurrentVisibleTab();
yield return ParseItems();
for (int tries = 0; tries < 3 && _dropItems.Count > 0; ++tries)
{
if (_dropItems.Count > 0)
yield return StashItemsIncrementer();
yield return ParseItems();
yield return new WaitTime(Settings.ExtraDelay);
}
//yield return ProcessRefills(); currently bugged
if (Settings.VisitTabWhenDone.Value)
{
if (Settings.BackToOriginalTab.Value)
{
yield return SwitchToTab(originTab);
}
else
{
yield return SwitchToTab(Settings.TabToVisitWhenDone.Value);
}
}
//restoring cursorposition
Input.SetCursorPos(cursorPosPreMoving);
Input.MouseMove();
StopCoroutine("Stashie_DropItemsToStash");
}
private void CleanUp()
{
Input.KeyUp(Keys.LControlKey);
Input.KeyUp(Keys.Shift);
}
private bool stashingRequirementsMet()
{
return GameController.Game.IngameState.IngameUi.InventoryPanel.IsVisible &&
GameController.Game.IngameState.IngameUi.StashElement.IsVisibleLocal;
}
private IEnumerator ProcessInventoryItems()
{
_debugTimer.Restart();
yield return ParseItems();
var cursorPosPreMoving = Input.ForceMousePosition;
if (_dropItems.Count > 0)
yield return StashItemsIncrementer();
yield return ProcessRefills();
yield return Input.SetCursorPositionSmooth(new Vector2(cursorPosPreMoving.X, cursorPosPreMoving.Y));
Input.MouseMove();
_coroutineWorker = Core.ParallelRunner.FindByName(CoroutineName);
_coroutineWorker?.Done();
_debugTimer.Restart();
_debugTimer.Stop();
}
private IEnumerator ProcessSwitchToTab(int index)
{
_debugTimer.Restart();
yield return SwitchToTab(index);
_coroutineWorker = Core.ParallelRunner.FindByName(CoroutineName);
_coroutineWorker?.Done();
_debugTimer.Restart();
_debugTimer.Stop();
}
private IEnumerator ParseItems()
{
var inventory = GameController.Game.IngameState.IngameUi.InventoryPanel[InventoryIndex.PlayerInventory];
var invItems = inventory.VisibleInventoryItems;
yield return new WaitFunctionTimed(() => invItems != null, true, 500); //, "Player inventory->VisibleInventoryItems is null!");
_dropItems = new List<FilterResult>();
_clickWindowOffset = GameController.Window.GetWindowRectangle().TopLeft;
foreach (var invItem in invItems)
{
if (invItem.Item == null || invItem.Address == 0) continue;
if (CheckIgnoreCells(invItem)) continue;
var baseItemType = GameController.Files.BaseItemTypes.Translate(invItem.Item.Path);
var testItem = new ItemData(invItem, baseItemType);
//LogMessage(testItem.ToString());
var result = CheckFilters(testItem);
if (result != null)
_dropItems.Add(result);
}
}
private bool CheckIgnoreCells(NormalInventoryItem inventItem)
{
var inventPosX = inventItem.InventPosX;
var inventPosY = inventItem.InventPosY;
if (Settings.RefillCurrency &&
_customRefills.Any(x => x.InventPos.X == inventPosX && x.InventPos.Y == inventPosY))
return true;
if (inventPosX < 0 || inventPosX >= 12) return true;
if (inventPosY < 0 || inventPosY >= 5) return true;
return Settings.IgnoredCells[inventPosY, inventPosX] != 0; //No need to check all item size
}
private FilterResult CheckFilters(ItemData itemData)
{
foreach (var filter in _customFiltersPrimary)
{
try
{
if (!filter.AllowProcess) continue;
if (filter.CompareItem(itemData)) return new FilterResult(filter, itemData);
}
catch (Exception ex)
{
DebugWindow.LogError($"Check filters error: {ex}");
}
}
return null;
}
private IEnumerator StashItemsIncrementer()
{
_coroutineIteration++;
yield return StashItems();
}
private IEnumerator StashItems()
{
PublishEvent("stashie_start_drop_items", null);
_visibleStashIndex = GetIndexOfCurrentVisibleTab();
if (_visibleStashIndex < 0)
{
LogMessage($"Stshie: VisibleStashIndex was invalid: {_visibleStashIndex}, stopping.");
yield break;
}
var itemsSortedByStash = _dropItems.OrderBy(x => x.SkipSwitchTab || x.StashIndex == _visibleStashIndex ? 0 : 1).ThenBy(x => x.StashIndex).ToList();
var waitedItems = new List<FilterResult>(8);
Input.KeyDown(Keys.LControlKey);
LogMessage($"Want to drop {itemsSortedByStash.Count} items.");
foreach(var stashresult in itemsSortedByStash)
{
_coroutineIteration++;
_coroutineWorker?.UpdateTicks(_coroutineIteration);
var maxTryTime = _debugTimer.ElapsedMilliseconds + 2000;
//move to correct tab
if (!stashresult.SkipSwitchTab)
yield return SwitchToTab(stashresult.StashIndex);
//this is shenanigans for items that take some time to get dumped like maps into maptab and divcards in divtab
/*
var waited = waitedItems.Count > 0;
while (waited)
{
waited = false;
var visibleInventoryItems = GameController.Game.IngameState.IngameUi
.InventoryPanel[InventoryIndex.PlayerInventory]
.VisibleInventoryItems;
foreach(var item in waitedItems)
{
if (!visibleInventoryItems.Contains(item.ItemData.InventoryItem)) continue;
yield return ClickElement(item.ClickPos);
waited = true;
}
yield return new WaitTime(Settings.ExtraDelay);
PublishEvent("stashie_finish_drop_items_to_stash_tab", null);
if (!waited) waitedItems.Clear();
if (_debugTimer.ElapsedMilliseconds > maxTryTime)
{
LogMessage($"Error while waiting for:{waitedItems.Count} items");
yield break;
}
yield return new WaitTime((int)GameController.IngameState.CurLatency); //maybe replace with Setting option
}*/
yield return new WaitFunctionTimed(() => GameController.IngameState.IngameUi.StashElement.AllInventories[_visibleStashIndex] != null,
true, 2000); //, $"Error while loading tab, Index: {_visibleStashIndex}"); //maybe replace waittime with Setting option
yield return new WaitFunctionTimed(() => GetTypeOfCurrentVisibleStash() != InventoryType.InvalidInventory,
true, 2000); //, $"Error with inventory type, Index: {_visibleStashIndex}"); //maybe replace waittime with Setting option
yield return StashItem(stashresult);
_debugTimer.Restart();
PublishEvent("stashie_finish_drop_items_to_stash_tab", null);
}
}
private IEnumerator StashItem(FilterResult stashresult)
{
Input.SetCursorPos(stashresult.ClickPos + _clickWindowOffset);
yield return new WaitTime(Settings.HoverItemDelay);
/*
//set cursor and update hoveritem
yield return Settings.HoverItemDelay;
var inventory = GameController.IngameState.IngameUi.InventoryPanel[InventoryIndex.PlayerInventory];
while (inventory.HoverItem == null)
{
if (_debugTimer.ElapsedMilliseconds > maxTryTime)
{
LogMessage($"Error while waiting for hover item. hoveritem is null, Index: {_visibleStashIndex}");
yield break;
}
Input.SetCursorPos(stashresult.ClickPos + _clickWindowOffset);
yield return Settings.HoverItemDelay;
}
if (lastHoverItem != null)
{
while (inventory.HoverItem == null || inventory.HoverItem.Address == lastHoverItem.Address)
{
if (_debugTimer.ElapsedMilliseconds > maxTryTime)
{
LogMessage($"Error while waiting for hover item. hoveritem is null, Index: {_visibleStashIndex}");
yield break;
}
Input.SetCursorPos(stashresult.ClickPos + _clickWindowOffset);
yield return Settings.HoverItemDelay;
}
}
lastHoverItem = inventory.HoverItem;
*/
//finally press the button
//additional shift to circumvent affinities
bool shiftused = false;
if (stashresult.ShiftForStashing)
{
Input.KeyDown(Keys.ShiftKey);
shiftused = true;
}
Input.Click(MouseButtons.Left);
if (shiftused)
{
Input.KeyUp(Keys.ShiftKey);
}
yield return new WaitTime(Settings.StashItemDelay);
}
#region Refill
private IEnumerator ProcessRefills()
{
if (!Settings.RefillCurrency.Value || _customRefills.Count == 0) yield break;
if (Settings.CurrencyStashTab.Index == -1)
{
LogError("Can't process refill: CurrencyStashTab is not set.", 5);
yield break;
}
var delay = (int) GameController.Game.IngameState.CurLatency + Settings.ExtraDelay.Value;
var currencyTabVisible = false;
var inventory = GameController.Game.IngameState.IngameUi.InventoryPanel[InventoryIndex.PlayerInventory];
var stashItems = inventory.VisibleInventoryItems;
if (stashItems == null)
{
LogError("Can't process refill: VisibleInventoryItems is null!", 5);
yield break;
}
_customRefills.ForEach(x => x.Clear());
var filledCells = new int[5, 12];
foreach (var inventItem in stashItems)
{
var item = inventItem.Item;
if (item == null) continue;
if (!Settings.AllowHaveMore.Value)
{
var iPosX = inventItem.InventPosX;
var iPosY = inventItem.InventPosY;
var iBase = item.GetComponent<Base>();
for (var x = iPosX; x <= iPosX + iBase.ItemCellsSizeX - 1; x++)
for (var y = iPosY; y <= iPosY + iBase.ItemCellsSizeY - 1; y++)
if (x >= 0 && x <= 11 && y >= 0 && y <= 4)
filledCells[y, x] = 1;
else
LogMessage($"Out of range: {x} {y}", 10);
}
if (!item.HasComponent<ExileCore.PoEMemory.Components.Stack>()) continue;
foreach (var refill in _customRefills)
{
var bit = GameController.Files.BaseItemTypes.Translate(item.Path);
if (bit.BaseName != refill.CurrencyClass) continue;
var stack = item.GetComponent<ExileCore.PoEMemory.Components.Stack>();
refill.OwnedCount = stack.Size;
refill.ClickPos = inventItem.GetClientRect().Center;
if (refill.OwnedCount < 0 || refill.OwnedCount > 40)
{
LogError(
$"Ignoring refill: {refill.CurrencyClass}: Stack size {refill.OwnedCount} not in range 0-40 ",
5);
refill.OwnedCount = -1;
}
break;
}
}
var inventoryRec = inventory.InventoryUIElement.GetClientRect();
var cellSize = inventoryRec.Width / 12;
var freeCellFound = false;
var freeCelPos = new Point();
if (!Settings.AllowHaveMore.Value)
for (var x = 0; x <= 11; x++)
{
for (var y = 0; y <= 4; y++)
{
if (filledCells[y, x] != 0) continue;
freeCellFound = true;
freeCelPos = new Point(x, y);
break;
}
if (freeCellFound) break;
}
foreach (var refill in _customRefills)
{
if (refill.OwnedCount == -1) continue;
if (refill.OwnedCount == refill.AmountOption.Value) continue;
if (refill.OwnedCount < refill.AmountOption.Value)
#region Refill
{
if (!currencyTabVisible)
{
if (Settings.CurrencyStashTab.Index != _visibleStashIndex)
{
yield return SwitchToTab(Settings.CurrencyStashTab.Index);
}
else
{
currencyTabVisible = true;
yield return new WaitTime(delay);
}
}
var moveCount = refill.AmountOption.Value - refill.OwnedCount;
var currentStashItems = GameController.Game.IngameState.IngameUi.StashElement.VisibleStash
.VisibleInventoryItems;
var foundSourceOfRefill = currentStashItems
.Where(x => GameController.Files.BaseItemTypes.Translate(x.Item.Path).BaseName ==
refill.CurrencyClass).ToList();
foreach (var sourceOfRefill in foundSourceOfRefill)
{
var stackSize = sourceOfRefill.Item.GetComponent<ExileCore.PoEMemory.Components.Stack>().Size;
var getCurCount = moveCount > stackSize ? stackSize : moveCount;
var destination = refill.ClickPos;
if (refill.OwnedCount == 0)
{
destination = GetInventoryClickPosByCellIndex(inventory, refill.InventPos.X,
refill.InventPos.Y, cellSize);
// If cells is not free then continue.
if (GameController.Game.IngameState.IngameUi.InventoryPanel[InventoryIndex.PlayerInventory][
refill.InventPos.X, refill.InventPos.Y, 12] != null)
{
moveCount--;
LogMessage(
$"Inventory ({refill.InventPos.X}, {refill.InventPos.Y}) is occupied by the wrong item!",
5);
continue;
}
}
yield return SplitStack(moveCount, sourceOfRefill.GetClientRect().Center, destination);
moveCount -= getCurCount;
if (moveCount == 0) break;
}
if (moveCount > 0)
LogMessage($"Not enough currency (need {moveCount} more) to fill {refill.CurrencyClass} stack",
5);
}
#endregion
else if (!Settings.AllowHaveMore.Value && refill.OwnedCount > refill.AmountOption.Value)
#region Devastate
{
if (!freeCellFound)
{
LogMessage("Can\'t find free cell in player inventory to move excess currency.", 5);
continue;
}
if (!currencyTabVisible)
{
if (Settings.CurrencyStashTab.Index != _visibleStashIndex)
{
yield return SwitchToTab(Settings.CurrencyStashTab.Index);
continue;
}
currencyTabVisible = true;
yield return new WaitTime(delay);
}
var destination = GetInventoryClickPosByCellIndex(inventory, freeCelPos.X, freeCelPos.Y, cellSize) +
_clickWindowOffset;
var moveCount = refill.OwnedCount - refill.AmountOption.Value;
yield return new WaitTime(delay);
yield return SplitStack(moveCount, refill.ClickPos, destination);
yield return new WaitTime(delay);
Input.KeyDown(Keys.LControlKey);
yield return Input.SetCursorPositionSmooth(destination + _clickWindowOffset);
yield return new WaitTime(Settings.ExtraDelay);
Input.Click(MouseButtons.Left);
Input.MouseMove();
Input.KeyUp(Keys.LControlKey);
yield return new WaitTime(delay);
}
#endregion
}
}
private static Vector2 GetInventoryClickPosByCellIndex(Inventory inventory, int indexX, int indexY,
float cellSize)
{
return inventory.InventoryUIElement.GetClientRect().TopLeft +
new Vector2(cellSize * (indexX + 0.5f), cellSize * (indexY + 0.5f));
}
private IEnumerator SplitStack(int amount, Vector2 from, Vector2 to)
{
var delay = (int) GameController.Game.IngameState.CurLatency * 2 + Settings.ExtraDelay;
Input.KeyDown(Keys.ShiftKey);
while (!Input.IsKeyDown(Keys.ShiftKey)) yield return new WaitTime(WhileDelay);
yield return Input.SetCursorPositionSmooth(from + _clickWindowOffset);
yield return new WaitTime(Settings.ExtraDelay);