-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTalesOfToastPlugin.cs
1585 lines (1414 loc) · 67.8 KB
/
TalesOfToastPlugin.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 BepInEx;
using BepInEx.Configuration;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using UnityEngine;
namespace TheTaleOfToastPlugin
{
[BepInPlugin("net.mindphlux.plugins.thetaleoftoastplugin", "The Tale of Toast Plugin", "1.1.1")]
[BepInProcess("ToT.exe")]
public class TheTaleOfToastPlugin : BaseUnityPlugin
{
private ConfigEntry<int> pinnedTradeSkill;
private ConfigEntry<int> unknownLevelThreshold;
private ConfigEntry<int> lastSummonedPet;
private ConfigEntry<bool> showBagSpaceLabel;
private ConfigEntry<bool> combatLogging;
private float onDisplayLocationCounter;
private bool canLogin;
private Item dressingRoomItem;
private bool mailboxFixed = false;
private bool bagSpaceLabelAdded = false;
private UILabel bagSpaceLabel;
private bool discordInitialized = false;
private DiscordRpc.RichPresence discordRichPresence;
private string lastLocation;
private long sessionStartTime = 0;
private bool isFirewood = false;
private void Awake()
{
unknownLevelThreshold = Config.Bind("General", "UnknownLevelThreshold", 10, "Set the threshold for displaying ?? instead of a level.");
pinnedTradeSkill = Config.Bind("DoNotChange", "PinnedTradeSkill", -1, "The currently pinned trade skill (because the game doesn't save it)");
lastSummonedPet = Config.Bind("DoNotChange", "LastSummonedPet", -1, "The last summoned vanity pet");
showBagSpaceLabel = Config.Bind("General", "ShowBagSpaceLabel", true, "Displays free bag space near the button menu.");
combatLogging = Config.Bind("General", "EnableCombatLogging", true, "Enable combat logging.");
// hooks for quality of life fixes
// more fixes are applied in the Update() method
On.ContainerTradeSkills.PinSelectedTradeskill += SavePinnedTradeskill;
On.ContainerPinnedTradeskill.XpUpdate += PinnedTradeskillXpUpdate;
On.Map.DisplayLocation += OnDisplayLocation;
On.PlayerTargeting.SetTarget += OnSetTarget;
On.ContainerTargetInfo.Set_bool_bool_int_string_int_int_int_int_int_BaseStats_float_int += LevelConFix;
On.PanelLogin.OnRealmSelected += OnRealmSelected;
On.PanelLogin.Start += OnPanelLoginStart;
On.ContainerTradeSkills.ShowRecipe += OnContainerTradeSkillsShowRecipe;
On.ContainerMail.SetTab += OnContainerMailSetTab;
On.PlayerPets.Summon += OnPlayerPetsSummon;
On.PlayerPets.Dismiss += OnPlayerPetsDismiss;
On.PlayerMovement.SetFlightPath += OnPlayerMovementSetFlightPath;
if (showBagSpaceLabel.Value)
{
On.PlayerInventory.AddItem += OnPlayerInventoryAddItem;
On.PlayerInventory.RemoveItem += OnPlayerInventoryRemoveItem;
On.UIItemCursor.EquipVanityItem += OnUIItemCursorEquipVanityItem;
On.UIItemCursor.UnequipVanityItem += OnUIItemCursorUnequipVanityItem;
On.UIItemCursor.EquipItem += OnUIItemCursorEquipItem;
On.UIItemCursor.UnequipItem += OnUIItemCursorUnequipItem;
}
On.DiscordController.UpdateDiscord += OnDiscordControllerUpdateDiscord;
On.PlayerStats.LeveledUp += OnPlayerStatsLeveledUp;
On.Map.DisplayLocation += OnMapDisplayLocation;
On.ItemDatabase.Load_TextAsset += OnItemDatabaseLoadTextAsset;
On.SocialManager.RefreshFriendRequestList += OnSocialManagerRefreshFriendRequestList;
On.ContainerBuyDiamonds.BuyDiamonds += OnContainerBuyDiamondsBuyDiamonds;
On.PanelGame.OnShow += OnPanelGameOnShow;
On.PlayerStats.HPBReward += OnPlayerStatsHPBReward;
On.UIItemTooltip.GetTooltipText += OnUIItemTooltipGetTooltipText;
On.EnemyInit.Start += OnEnemyInitStart;
if (combatLogging.Value)
{
On.ChatManager.MessageFromServer += ChatManager_MessageFromServer;
}
sessionStartTime = (long)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
}
private void Update()
{
if (GameManager.Instance.State == GameState.Login)
{
PressEnterToLogin();
}
if (GameManager.Instance.State == GameState.CharacterSelection)
{
PressEnterToEnterWorld();
}
if (GameManager.Instance.State != GameState.Game) return;
if (!discordInitialized)
{
DiscordRpc.EventHandlers _handlers = new DiscordRpc.EventHandlers();
DiscordRpc.Initialize("851053235758432256", ref _handlers, true, "640150");
DiscordRpc.UpdatePresence(ref discordRichPresence);
discordInitialized = true;
}
ResetMovementLogoutTimer();
FixMinimapIcons();
if (showBagSpaceLabel.Value)
{
if (!bagSpaceLabelAdded)
{
bagSpaceLabelAdded = true;
StartCoroutine(BagSlotsOnButtonMenu());
}
}
if (Input.GetKeyDown(KeyCode.F2))
{
SettingsManager.Instance.ToggleLockActionBars();
bool _locked = SettingsManager.Instance.LockActionBars;
Chat.Instance.InfoMessage(ChatMessageType.Info, $"Action bars are now {(_locked ? "locked." : "unlocked.")}");
}
if (Input.GetKeyDown(KeyCode.F3))
{
if (showBagSpaceLabel.Value)
{
showBagSpaceLabel.Value = false;
bagSpaceLabel.enabled = false;
}
else
{
showBagSpaceLabel.Value = true;
bagSpaceLabel.enabled = true;
}
}
if (Input.GetKeyUp(KeyCode.F4))
{
BeautifyEffect.Beautify _beautify = FindObjectOfType<BeautifyEffect.Beautify>();
_beautify.sharpen = _beautify.sharpen == 3f ? 0f : 3f;
Chat.Instance.InfoMessage(ChatMessageType.Info, $"Sharpen effect is now {(_beautify.sharpen == 3 ? "enabled." : "disabled.")}");
}
}
#region Combat logging
private void ChatManager_MessageFromServer(On.ChatManager.orig_MessageFromServer orig, ChatManager self, int chatMessageType, string message, int chatTab)
{
if (chatTab == 2 || chatTab == 3)
{
AddCombatLogLine(string.Format("{0}\n", message));
}
orig.Invoke(self, chatMessageType, message, chatTab);
}
private void AddCombatLogLine(string _line)
{
DateTime _date = DateTime.Now;
Directory.CreateDirectory("Logs");
string _month = _date.Month < 10 ? string.Format("{0}{1}", "0", _date.Month) : _date.Month.ToString();
string _day = _date.Day < 10 ? string.Format("{0}{1}", "0", _date.Day) : _date.Day.ToString();
File.AppendAllText(string.Format("Logs\\Combat-{0}.log", string.Format("{0}-{1}-{2}", _date.Year, _month, _day)), string.Format("[{0}] {1}", _date.ToLongTimeString(), _line));
}
#endregion Combat logging
#region Bug fixes
#region Fix for broken mail box back button
private void OnContainerMailSetTab(On.ContainerMail.orig_SetTab orig, ContainerMail self, MailTab tab)
{
// the "Back" button on the Compose tab of the mailbox had a wrong (and not even existing) method bound to its
// onClick event. This fixes the problem and also unbinds the wrongly bound method so no more errors appear in the console.
orig.Invoke(self, tab);
if (mailboxFixed) return;
if (tab == MailTab.Compose)
{
UIButton[] _buttons = self.gameObject.GetComponentsInChildren<UIButton>();
UIButton _backButton = null;
for (int i = 0; i < _buttons.Length; i++)
{
if (_buttons[i].name == "Button_Back")
{
_backButton = _buttons[i];
}
}
if (_backButton != null)
{
EventDelegate MailBoxBackButtonFix = new EventDelegate(this, "MailBoxBackButtonFix");
_backButton.onClick.Clear();
_backButton.onClick.Add(MailBoxBackButtonFix);
mailboxFixed = true;
}
}
}
private void MailBoxBackButtonFix()
{
GuiManager.Instance.panelGame.containerMail.SetTab(MailTab.List);
}
#endregion Fix for broken mail box back button
#region Fix for missing item icons
private ItemDatabase OnItemDatabaseLoadTextAsset(On.ItemDatabase.orig_Load_TextAsset orig, TextAsset xmlFile)
{
// fixes the missing icon for item "Dusty Tome" (id 3675) and "Cooked Enriched Delicious Meat" (2488)
try
{
ItemDatabase _base = (ItemDatabase)new XmlSerializer(typeof(ItemDatabase)).Deserialize(new StringReader(xmlFile.text));
for (int i = 0; i < _base.Items.Count; i++)
{
if (_base.Items[i].id == 3675)
{
_base.Items[i].iconAtlas = "ItemAtlas_Parts";
_base.Items[i].icon = "pt_t_18";
}
if (_base.Items[i].id == 2488)
{
_base.Items[i].icon = "meat_f_03_magic";
}
if (_base.Items[i].id == 3048)
{
_base.Items[i].icon = "pt_t_06";
}
if (_base.Items[i].id == 3047)
{
_base.Items[i].icon = "pt_t_06";
}
}
return _base;
}
catch (Exception arg)
{
Debug.LogError("[ItemDatabase] Failed to load Item DB: " + arg);
ToastyTools.Quit();
}
return null;
}
#endregion Fix for missing item icons
#region Discord Rich Presence
private void CustomUpdateDiscord(string playerLevel, string playerName = null, string playerLocation = null)
{
if (playerName == null)
{
playerName = PlayerCommon.Instance.Init.PlayerName;
}
if (playerLocation == null)
{
playerLocation = "Astaria";
}
if (discordInitialized)
{
discordRichPresence.largeImageKey = "toastlogo";
discordRichPresence.largeImageText = "The Tale of Toast";
discordRichPresence.smallImageKey = "toastlogo";
discordRichPresence.smallImageText = "The Tale of Toast";
discordRichPresence.state = $"Adventuring in {playerLocation}";
discordRichPresence.details = $"{playerName}, level {playerLevel}";
discordRichPresence.startTimestamp = sessionStartTime;
DiscordRpc.UpdatePresence(ref discordRichPresence);
}
}
private void OnDiscordControllerUpdateDiscord(On.DiscordController.orig_UpdateDiscord orig, DiscordController self, string largeImage, string realm, string smallImage, string playerName, string playerLevel)
{
CustomUpdateDiscord(playerLevel, playerName, lastLocation);
}
private void OnMapDisplayLocation(On.Map.orig_DisplayLocation orig, Map self, string locationName, string subName, bool forcePvp, bool pvpAllowed, bool pardondedZone, int pvpLevelGap)
{
orig.Invoke(self, locationName, subName, forcePvp, pvpAllowed, pardondedZone, pvpLevelGap);
CustomUpdateDiscord(PlayerCommon.Instance.Stats.CurrentLevel.ToString(), null, locationName);
lastLocation = locationName;
}
private void OnPlayerStatsLeveledUp(On.PlayerStats.orig_LeveledUp orig, PlayerStats self, int level, int availablePoints, int pointsGained)
{
orig.Invoke(self, level, availablePoints, pointsGained);
CustomUpdateDiscord(level.ToString(), null, lastLocation);
}
#endregion Discord Rich Presence
#region Reposition enemy name plates relative to their model's height
private void OnEnemyInitStart(On.EnemyInit.orig_Start orig, EnemyInit self)
{
if (uLink.Network.isClient)
{
GameObject _go = Instantiate(self.nameplatePrefab);
_go.transform.SetParent(self.transform);
Renderer _renderer = self.GetComponentInChildren<Renderer>();
// for models that are wider than high we're moving the nameplate a bit higher
// as these models are usually used by flying enemies and the nameplate would otherwise
// clip into the animation
_go.transform.localPosition = new Vector3(0f, _renderer.bounds.size.y + (_renderer.bounds.size.y > _renderer.bounds.size.x ? 0.1f : 0.3f), 0f);
}
}
#endregion Reposition enemy name plates relative to their model's height
#endregion Bug fixes
#region Quality of Life Fixes
#region Bag space label
private void OnUIItemCursorUnequipItem(On.UIItemCursor.orig_UnequipItem orig, int itemId, bool vanity)
{
orig.Invoke(itemId, vanity);
UpdateBagSpaceLabel();
}
private void OnUIItemCursorEquipItem(On.UIItemCursor.orig_EquipItem orig)
{
orig.Invoke();
UpdateBagSpaceLabel();
}
private void OnUIItemCursorUnequipVanityItem(On.UIItemCursor.orig_UnequipVanityItem orig, int itemId)
{
orig.Invoke(itemId);
UpdateBagSpaceLabel();
}
private void OnUIItemCursorEquipVanityItem(On.UIItemCursor.orig_EquipVanityItem orig)
{
orig.Invoke();
UpdateBagSpaceLabel();
}
private IEnumerator BagSlotsOnButtonMenu()
{
yield return new WaitForSeconds(3f);
try
{
GameObject _go = FindObjectOfType<ContainerButtonMenu>().gameObject;
UILabel[] _label = _go.GetComponentsInChildren<UILabel>();
UILabel _labelToClone = null;
for (int i = 0; i < _label.Length; i++)
{
if (_label[i].name == "Label_Diamonds")
{
_labelToClone = _label[i];
}
}
if (_labelToClone != null)
{
Transform _parentTransform = null;
UISprite[] _sprites = _go.GetComponentsInChildren<UISprite>();
for (int i = 0; i < _sprites.Length; i++)
{
if (_sprites[i].name == "Button_ToggleMenu")
{
_parentTransform = _sprites[i].transform;
}
}
if (_parentTransform != null)
{
bagSpaceLabel = Instantiate(_labelToClone, _go.transform);
bagSpaceLabel.transform.localPosition = new Vector2(-112f, -73f);
bagSpaceLabel.name = "Label_BagSpace";
UpdateBagSpaceLabel();
}
}
}
catch (Exception)
{
}
}
private void UpdateBagSpaceLabel()
{
try
{
int _emptySlots = PlayerInventory.Instance.Inventory.EmptySlotCount();
bagSpaceLabel.text = $"{_emptySlots}/25";
if (_emptySlots < 3)
{
bagSpaceLabel.color = Color.red;
}
else if (_emptySlots > 3 && _emptySlots < 15)
{
bagSpaceLabel.color = Color.yellow;
}
else if (_emptySlots > 15)
{
bagSpaceLabel.color = Color.green;
}
}
catch (Exception) { }
}
private void OnPlayerInventoryRemoveItem(On.PlayerInventory.orig_RemoveItem orig, PlayerInventory self, int slot, int amount)
{
orig.Invoke(self, slot, amount);
UpdateBagSpaceLabel();
}
private void OnPlayerInventoryAddItem(On.PlayerInventory.orig_AddItem orig, PlayerInventory self, int itemId, int slot, int amount, string namePrefix, int craftQuality, int itemLevel, int adjective, int attribute, string seed, bool fromBank, bool broken)
{
orig.Invoke(self, itemId, slot, amount, namePrefix, craftQuality, itemLevel, adjective, attribute, seed, fromBank, broken);
UpdateBagSpaceLabel();
}
#endregion Bag space label
#region Fix for missing Alt-Click to preview crafted items
private void OnContainerTradeSkillsShowRecipe(On.ContainerTradeSkills.orig_ShowRecipe orig, ContainerTradeSkills self, string recipeName)
{
// on the original Trade Skills window it isn't possible to view the crafted item in the dressing room
// despite the tooltip claiming Alt+Click would preview it.
// to make this work we'll add an UIButton component to the item icon and route the onClick handler to our custom function
orig.Invoke(self, recipeName);
dressingRoomItem = ItemManager.Instance.GetItem(recipeName);
if (self.recipeIcon.gameObject.GetComponent<UIButton>()) return;
UIButton _button = self.recipeIcon.gameObject.AddComponent<UIButton>();
EventDelegate DressingRoomPreview = new EventDelegate(this, "ShowDressingRoom");
_button.onClick.Add(DressingRoomPreview);
}
private void ShowDressingRoom()
{
if (Input.GetKey(KeyCode.LeftAlt) || Input.GetKey(KeyCode.RightAlt))
{
GuiManager.Instance.panelGame.containerDressingRoom.Show();
// while there is a method calld DressingRoom.ShowEquipment(item) it doesn't work
// so we'll use DressingRoom.ShowVanity(item) which does work. No idea why ...
PlayerCommon.Instance.DressingRoom.ShowVanity(dressingRoomItem);
}
}
#endregion Fix for missing Alt-Click to preview crafted items
#region Add plugin version to the login screen
private void OnPanelLoginStart(On.PanelLogin.orig_Start orig, PanelLogin self)
{
canLogin = false;
orig.Invoke(self);
var _m = MetadataHelper.GetMetadata(this);
self.labelBuildVersion.width = 300;
self.labelBuildVersion.text += $" (Plugin v{_m.Version.Major}.{_m.Version.Minor}.{_m.Version.Build})";
}
#endregion Add plugin version to the login screen
#region Show error message when trying to buy Crumbs with the Steam Overlay not enabled
private void OnContainerBuyDiamondsBuyDiamonds(On.ContainerBuyDiamonds.orig_BuyDiamonds orig, ContainerBuyDiamonds self)
{
if (SteamManager.SteamClient.Overlay.Enabled)
{
orig.Invoke(self);
}
else
{
GuiManager.Instance.ShowMessage("Error", "You need to start the game via Steam to be able to buy Crumbs.");
}
}
#endregion Show error message when trying to buy Crumbs with the Steam Overlay not enabled
#region Level con fix
private void LevelConFix(On.ContainerTargetInfo.orig_Set_bool_bool_int_string_int_int_int_int_int_BaseStats_float_int orig, ContainerTargetInfo self, bool enabled, bool attackable, int playerLevel, string targetName, int targetLevel, int targetHealth, int targetMaxHealth, int targetMana, int targetMaxMana, BaseStats targetStats, float distance, int threat)
{
// set the threshold for displaying ?? as level to an user defined value instead of 6
// defaults to 10 levels like in most games
GameManager.Instance.unknownLevelThreshold = unknownLevelThreshold.Value;
orig.Invoke(self, enabled, attackable, playerLevel, targetName, targetLevel, targetHealth, targetMaxHealth, targetMana, targetMaxMana, targetStats, distance, threat);
}
#endregion Level con fix
#region Disable self-targeting
private void OnSetTarget(On.PlayerTargeting.orig_SetTarget orig, PlayerTargeting self, ITargetable newTarget)
{
// fixes the problem that right-clicking the player targets them
// which can cause issues in combat and is also rather irritating
if (newTarget.TargetName == PlayerCommon.Instance.Init.PlayerName) return;
/*
if(inspectWindow.activeInHierarchy && !dontInspectMe.Value)
{
ShowInspectWindow();
}
*/
orig.Invoke(self, newTarget);
}
#endregion Disable self-targeting
#region Hook for anything that needs the game to be initialized to work
private void OnDisplayLocation(On.Map.orig_DisplayLocation orig, Map self, string locationName, string subName, bool forcePvp, bool pvpAllowed, bool pardondedZone, int pvpLevelGap)
{
// we are hooking Map.DisplayLocation() because it's called rather late and everything is already initialized at this point
// because this method is actually called twice upon entering the world we only apply the fix on the first call
orig.Invoke(self, locationName, subName, forcePvp, pvpAllowed, pardondedZone, pvpLevelGap);
onDisplayLocationCounter++;
if (onDisplayLocationCounter == 1)
{
StartCoroutine(RestorePinnedTradeSkill());
ResummonPetAfterLogin();
}
}
#endregion Hook for anything that needs the game to be initialized to work
#region Save/restore pinned tradeskill
private void PinnedTradeskillXpUpdate(On.ContainerPinnedTradeskill.orig_XpUpdate orig, ContainerPinnedTradeskill self, TradeSkill skill, int level, uint levelXp, uint nextLevelXp, uint totalXp)
{
if (skill == (TradeSkill)pinnedTradeSkill.Value)
{
UILabel _label = GuiManager.Instance.panelGame.containerPinnedTradeskill.GetComponentInChildren<UILabel>();
_label.text = ((TradeSkill)pinnedTradeSkill.Value).ToString() + " " + level;
orig.Invoke(self, skill, level, levelXp, nextLevelXp, totalXp);
}
}
private void SavePinnedTradeskill(On.ContainerTradeSkills.orig_PinSelectedTradeskill orig, ContainerTradeSkills self)
{
// saves the currently pinned trade skill to the plugin's config file
orig.Invoke(self);
TradeSkill _tradeskill = GuiManager.Instance.panelGame.containerPinnedTradeskill.Skill;
pinnedTradeSkill.Value = (int)_tradeskill;
StartCoroutine(RestorePinnedTradeSkill(0.5f));
}
private IEnumerator RestorePinnedTradeSkill(float _delay = 5f)
{
// restores the pinned trade skill from the plugin's config file
// for safety reasons we defer the execution by 5 seconds to make sure all values are actually initialized
yield return new WaitForSeconds(_delay);
if (pinnedTradeSkill.Value != -1)
{
TradeSkill _tradeSkill = (TradeSkill)pinnedTradeSkill.Value;
int _level = PlayerCommon.Instance.TradeSkills.Level(_tradeSkill);
uint _xpNow = PlayerCommon.Instance.TradeSkills.Experience[_tradeSkill] - XpManager.Instance.ConvertLevelToXp(PlayerCommon.Instance.TradeSkills.Level(_tradeSkill));
uint _xpNext = XpManager.Instance.ConvertLevelToXp(PlayerCommon.Instance.TradeSkills.Level(_tradeSkill) + 1);
uint _totalNow = PlayerCommon.Instance.TradeSkills.Experience[_tradeSkill];
GuiManager.Instance.panelGame.containerPinnedTradeskill.Set((TradeSkill)pinnedTradeSkill.Value, _level, _xpNow, (_xpNext - _totalNow) + _xpNow, 0);
GuiManager.Instance.panelGame.containerPinnedTradeskill.gameObject.SetActive(true);
}
}
#endregion Save/restore pinned tradeskill
#region Scales minimap icons to about 65% of their original size on the highest zoom level
private void FixMinimapIcons()
{
// fixes the way too large minimap icons on the highest zoom level
GameObject[] _icons = GameObject.FindObjectsOfType<GameObject>();
for (int i = 0; i < _icons.Length; i++)
{
if (_icons[i].GetComponent<CraftStation>() ||
_icons[i].GetComponent<NpcCommon>() ||
_icons[i].GetComponent<Mailbox>() ||
_icons[i].GetComponent<LootableObject>() ||
_icons[i].GetComponent<NpcFlightMaster>()
)
{
if (!_icons[i].GetComponent<PhatRobit.MiniMapIcon>()) continue;
if (_icons[i].GetComponent<NpcCommon>() &&
(!_icons[i].GetComponent<NpcVendor>().isEnabled &&
!_icons[i].GetComponent<NpcFlightMaster>().isEnabled)) continue;
if (PhatRobit.MiniMap.Instance.CurrentZoom == PhatRobit.MiniMap.Instance.minDistance)
{
_icons[i].GetComponent<PhatRobit.MiniMapIcon>().SetScale(3f);
}
else
{
_icons[i].GetComponent<PhatRobit.MiniMapIcon>().SetScale(5f);
}
}
}
}
#endregion Scales minimap icons to about 65% of their original size on the highest zoom level
#region Enter/Return key to enter world on character selection screen
private void PressEnterToEnterWorld()
{
// adds the ability to enter the world by pressing Return or Enter on the character selection screen
// like World of Warcraft does it
if (Input.GetKeyDown(KeyCode.Return) || Input.GetKeyDown(KeyCode.KeypadEnter))
{
GuiManager.Instance.panelCharacterSelection.EnterWorld();
}
}
#endregion Enter/Return key to enter world on character selection screen
#region Enter/return key to log in
private void OnRealmSelected(On.PanelLogin.orig_OnRealmSelected orig, PanelLogin self)
{
orig.Invoke(self);
if (UserManager.Instance.Realm != "") canLogin = true;
}
private void PressEnterToLogin()
{
// adds the ability to login by pressing Return or Enter on the login screen
if (!canLogin) return;
if (Input.GetKeyDown(KeyCode.Return) || Input.GetKeyDown(KeyCode.KeypadEnter))
{
SteamManager.Instance.TryLogin();
}
}
#endregion Enter/return key to log in
#region Disable movement logout timer
private void ResetMovementLogoutTimer()
{
// disables the 10 second logout timer after the character has been moved
// the timer is completely pointless since you could just use Alt+F4 to exit instantly
try
{
PlayerMovement.Instance.Movement.LogoutTimer = 0f;
}
catch (Exception) { }
}
#endregion Disable movement logout timer
#region Resummon pet after flight/logout
private void OnPlayerPetsDismiss(On.PlayerPets.orig_Dismiss orig, PlayerPets self)
{
// resets the stored last summoned pet after the player dismisses his current pet
orig.Invoke(self);
lastSummonedPet.Value = -1;
}
private void OnPlayerPetsSummon(On.PlayerPets.orig_Summon orig, PlayerPets self, int itemID)
{
// saves the currently summoned pet after summoning it
orig.Invoke(self, itemID);
lastSummonedPet.Value = itemID;
}
private void OnPlayerMovementSetFlightPath(On.PlayerMovement.orig_SetFlightPath orig, PlayerMovement self, bool enabled)
{
orig.Invoke(self, enabled);
if (enabled)
{
StartCoroutine(ResummonPetAfterFlying(self));
}
}
private IEnumerator ResummonPetAfterFlying(PlayerMovement _movement)
{
// automatically resummons the last summoned pet after completing a flight path
while (_movement.isOnFlightPath)
{
yield return new WaitForEndOfFrame();
}
if (lastSummonedPet.Value != -1)
{
PlayerCommon.Instance.Pets.SendSummonRequest(lastSummonedPet.Value);
}
}
private void ResummonPetAfterLogin()
{
// automatically resummons the last summoned pet after logging in
if (lastSummonedPet.Value != -1)
{
PlayerCommon.Instance.Pets.SendSummonRequest(lastSummonedPet.Value);
}
}
#endregion Resummon pet after flight/logout
#region Friend request notification via chat message
private void OnSocialManagerRefreshFriendRequestList(On.SocialManager.orig_RefreshFriendRequestList orig, SocialManager self, string rawFriendList)
{
// notifies the player in chat if there's a friend request waiting for him
orig.Invoke(self, rawFriendList);
if (self.FriendRequestList.Count > 0)
{
if (SettingsManager.Instance.PlayerKeys.ToggleSocial.Bindings.Count > 0)
{
Chat.Instance.InfoMessage(ChatMessageType.Info, $"You have {self.FriendRequestList.Count} pending friend {(self.FriendRequestList.Count > 1 ? "requests." : "request.")}. Press {SettingsManager.Instance.PlayerKeys.ToggleSocial.Bindings[0].Name} to manage {(self.FriendRequestList.Count > 1 ? "them." : "it.")})");
}
else
{
Chat.Instance.InfoMessage(ChatMessageType.Info, $"You have {self.FriendRequestList.Count} pending friend {(self.FriendRequestList.Count > 1 ? "requests." : "request.")}");
}
}
}
#endregion Friend request notification via chat message
#region Adds plugin active message to chat
private void OnPanelGameOnShow(On.PanelGame.orig_OnShow orig, PanelGame self)
{
orig.Invoke(self);
var _m = MetadataHelper.GetMetadata(this);
Chat.Instance.InfoMessage(ChatMessageType.Info, $"TaleOfToastPlugin v{_m.Version.Major}.{_m.Version.Minor}.{_m.Version.Build} enabled.");
RemoveHPB();
}
#endregion Adds plugin active message to chat
#region Removes any remaining mention of the (defunct) HPB crypto currency system
private void RemoveHPB()
{
// Removes "HPB death cloud" effect on loot/kill
LightIntensityFade[] _go = FindObjectsOfType<LightIntensityFade>();
foreach (LightIntensityFade _o in _go)
{
if (_o.gameObject.name == "effectEnemyDeathCloudHPB")
{
Destroy(_o.gameObject);
break;
}
}
}
private void OnPlayerStatsHPBReward(On.PlayerStats.orig_HPBReward orig, PlayerStats self)
{
return;
}
#endregion Removes any remaining mention of the (defunct) HPB crypto currency system
#region Adds crafted item to crafting recipe tooltip, also adds actual effect to potions tooltip
private string OnUIItemTooltipGetTooltipText(On.UIItemTooltip.orig_GetTooltipText orig, UIItemTooltip self, Item item, int stackCount, bool isVendor, bool isSelling, bool isTrading, bool isInTradeWindow, bool multiple, bool isEquipped, bool isInChatWindow, bool isInCraftWindow)
{
return GetCustomItemTooltipText(item, stackCount, isVendor, isSelling, isTrading, isInTradeWindow, multiple, isEquipped, isInChatWindow, isInCraftWindow);
}
private string GetCustomItemTooltipText(Item item, int stackCount, bool isVendor = false, bool isSelling = false, bool isTrading = false, bool isInTradeWindow = false, bool multiple = false, bool isEquipped = false, bool isInChatWindow = false, bool isInCraftWindow = false, bool isInline = false)
{
StringBuilder stringBuilder = new StringBuilder();
string text = "[" + ItemManager.Instance.GetItemHex(item) + "]";
stringBuilder.Append(text + item.Name + "[-]");
string flavor = item.Flavor;
stringBuilder.Append(string.Concat(new object[]
{
"\n",
text,
(flavor.Length > 0) ? (flavor + " ") : "",
item.quality,
"[-]"
}));
if (item.itemType == ItemType.Armor)
{
stringBuilder.Append("\n");
if (!item.isDiamondItem && item.armorType != ArmorType.None)
{
stringBuilder.Append(item.armorType + " ");
}
else if (item.isDiamondItem && item.armorSlot != ArmorSlot.None)
{
stringBuilder.Append("Cosmetic ");
}
stringBuilder.Append(ToastyTools.AddSpacesNearUpper(item.armorSlot.ToString()));
if (item.Armor > 0)
{
if (item.craftQuality > 0)
{
stringBuilder.Append("[00FF00]");
}
stringBuilder.Append("\n" + item.Armor);
if (item.craftQuality > 0)
{
stringBuilder.Append("[-]");
}
stringBuilder.Append(" Armor");
}
if (item.MagicResist > 0)
{
if (item.craftQuality > 0)
{
stringBuilder.Append("[00FF00]");
}
stringBuilder.Append("\n" + item.MagicResist);
if (item.craftQuality > 0)
{
stringBuilder.Append("[-]");
}
stringBuilder.Append(" Magic Resist");
}
if (item.HitRating > 0)
{
stringBuilder.Append("\nHit Rating: ");
if (item.craftQuality > 0)
{
stringBuilder.Append("[00FF00]");
}
stringBuilder.Append(item.HitRating);
if (item.craftQuality > 0)
{
stringBuilder.Append("[-]");
}
}
if (isInCraftWindow)
{
stringBuilder.Append("\nRandom Attribute Chances:");
if (item.IsVitalityItem())
{
stringBuilder.Append("\n| Vitality");
}
if (item.IsDefenseItem())
{
stringBuilder.Append("\n| Defense");
}
if (item.IsStrongItem())
{
stringBuilder.Append("\n| Strength");
}
if (item.IsWiseItem())
{
stringBuilder.Append("\n| Wisdom");
}
if (item.IsRangedItem())
{
stringBuilder.Append("\n| Dexterity");
}
if (item.IsMagicItem())
{
stringBuilder.Append("\n| Magic");
}
if (item.IsCraftingItem())
{
stringBuilder.Append("\n| Crafting");
}
}
}
if (item.itemType == ItemType.Weapon)
{
stringBuilder.Append("\n" + ToastyTools.AddSpacesNearUpper(item.weaponSlot.ToString()));
if (item.WeaponSpeed > 0f)
{
stringBuilder.Append("\nSpeed: " + item.WeaponSpeed);
}
if (item.Armor > 0)
{
if (item.craftQuality > 0)
{
stringBuilder.Append("[00FF00]");
}
stringBuilder.Append("\n" + item.Armor + " Armor");
if (item.craftQuality > 0)
{
stringBuilder.Append("[-]");
}
}
if (item.weaponClass != WeaponClass.Shield)
{
stringBuilder.Append("\n" + ToastyTools.AddSpacesNearUpper(item.weaponType.ToString()));
if (item.rangedWeaponType != RangedWeaponType.None)
{
stringBuilder.Append(" " + item.rangedWeaponType);
}
stringBuilder.Append(" " + ToastyTools.AddSpacesNearUpper(item.weaponClass.ToString()));
}
if (item.CanShootProjectiles())
{
stringBuilder.Append("\nRange: " + item.Range + " meters");
}
if (item.weaponClass != WeaponClass.Shield && item.MinDamage != 0 && item.MaxDamage != 0)
{
if (item.craftQuality > 0)
{
stringBuilder.Append("[00FF00]");
}
stringBuilder.Append(string.Concat(new object[]
{
"\n",
item.MinDamage,
" - ",
item.MaxDamage,
" Damage"
}));
if (item.craftQuality > 0)
{
stringBuilder.Append("[-]");
}
}
if (item.HitRating > 0)
{
stringBuilder.Append("\n[00FF00]Hit Rating: " + item.HitRating + "[-]");
}
if (isInCraftWindow)
{
stringBuilder.Append("\nRandom Attribute Chances:");
if (item.IsVitalityItem())
{
stringBuilder.Append("\n| Vitality");
}
if (item.IsDefenseItem())
{
stringBuilder.Append("\n| Defense");
}
if (item.IsStrongItem())
{
stringBuilder.Append("\n| Strength");
}
if (item.IsWiseItem())
{
stringBuilder.Append("\n| Wisdom");
}
if (item.IsRangedItem())
{
stringBuilder.Append("\n| Dexterity");
}
if (item.IsMagicItem())
{
stringBuilder.Append("\n| Magic");
}
if (item.IsCraftingItem())
{
stringBuilder.Append("\n| Crafting");
}
}
}
if (item.itemType == ItemType.TradeTool)
{
stringBuilder.Append("\n" + ToastyTools.AddSpacesNearUpper(item.weaponClass.ToString()));
}
if (item.itemType == ItemType.Consumable)
{