-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathPvpPerformanceTrackerPlugin.java
More file actions
1525 lines (1348 loc) · 51.2 KB
/
PvpPerformanceTrackerPlugin.java
File metadata and controls
1525 lines (1348 loc) · 51.2 KB
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
/*
* Copyright (c) 2021, Matsyir <https://github.com/Matsyir>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package matsyir.pvpperformancetracker;
import com.google.common.collect.ImmutableSet;
import com.google.gson.Gson;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializer;
import com.google.inject.Provides;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.Writer;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ScheduledExecutorService;
import java.util.stream.Collectors;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.time.temporal.ChronoUnit;
import javax.inject.Inject;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import matsyir.pvpperformancetracker.controllers.FightPerformance;
import matsyir.pvpperformancetracker.controllers.Fighter;
import matsyir.pvpperformancetracker.models.CombatLevels;
import matsyir.pvpperformancetracker.models.FightLogEntry;
import matsyir.pvpperformancetracker.models.HitsplatInfo;
import matsyir.pvpperformancetracker.models.RangeAmmoData;
import matsyir.pvpperformancetracker.models.oldVersions.FightPerformance__1_5_5;
import matsyir.pvpperformancetracker.utils.PvpPerformanceTrackerUtils;
import net.runelite.api.Actor;
import net.runelite.api.ChatMessageType;
import net.runelite.api.Client;
import net.runelite.api.GameState;
import net.runelite.api.HitsplatID;
import net.runelite.api.Player;
import net.runelite.api.PlayerComposition;
import net.runelite.api.Prayer;
import net.runelite.api.Skill;
import net.runelite.api.SpriteID;
import net.runelite.api.events.*;
import net.runelite.client.RuneLite;
import net.runelite.client.callback.ClientThread;
import net.runelite.client.chat.ChatMessageManager;
import net.runelite.client.chat.QueuedMessage;
import net.runelite.client.config.ConfigManager;
import net.runelite.client.config.RuneLiteConfig;
import net.runelite.client.eventbus.Subscribe;
import net.runelite.client.events.ClientShutdown;
import net.runelite.client.events.ConfigChanged;
import net.runelite.client.game.ItemManager;
import net.runelite.client.game.SpriteManager;
import net.runelite.client.hiscore.HiscoreEndpoint;
import net.runelite.client.hiscore.HiscoreManager;
import net.runelite.client.hiscore.HiscoreResult;
import net.runelite.client.hiscore.HiscoreSkill;
import net.runelite.client.plugins.Plugin;
import net.runelite.client.plugins.PluginDescriptor;
import net.runelite.client.task.Schedule;
import net.runelite.client.ui.ClientToolbar;
import net.runelite.client.ui.NavigationButton;
import net.runelite.client.ui.overlay.OverlayManager;
import net.runelite.client.util.AsyncBufferedImage;
import net.runelite.client.util.ImageUtil;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.tuple.Pair;
@Slf4j
@PluginDescriptor(
name = "PvP Performance Tracker"
)
public class PvpPerformanceTrackerPlugin extends Plugin
{
// static fields
public static final String PLUGIN_VERSION = "1.7.0";
public static final String CONFIG_KEY = "pvpperformancetracker";
// Data folder naming history:
// "pvp-performance-tracker": From release, until 1.5.9 update @ 2024-08-19
// "pvp-performance-tracker2": From 1.5.9 update, until present
public static final String DATA_FOLDER = "pvp-performance-tracker2";
public static final String FIGHT_HISTORY_DATA_FNAME = "FightHistoryData.json";
public static final File FIGHT_HISTORY_DATA_DIR;
public static PvpPerformanceTrackerConfig CONFIG;
public static PvpPerformanceTrackerPlugin PLUGIN;
public static Image PLUGIN_ICON;
public static AsyncBufferedImage DEFAULT_NONE_SYMBOL; // save bank filler image to display a generic "None" or N/A state.
public static Gson GSON;
// Last man standing map regions, including ferox enclave
private static final Set<Integer> LAST_MAN_STANDING_REGIONS = ImmutableSet.of(12344, 12600, 13658, 13659, 13660, 13914, 13915, 13916, 13918, 13919, 13920, 14174, 14175, 14176, 14430, 14431, 14432);
static
{
FIGHT_HISTORY_DATA_DIR = new File(RuneLite.RUNELITE_DIR, DATA_FOLDER);
FIGHT_HISTORY_DATA_DIR.mkdirs();
}
// "native"/core RL fields/injected fields
@Getter(AccessLevel.PACKAGE)
private NavigationButton navButton;
private boolean navButtonShown = false;
@Getter(AccessLevel.PACKAGE)
private PvpPerformanceTrackerPanel panel;
@Inject
private PvpPerformanceTrackerConfig config;
@Inject
private SpriteManager spriteManager;
@Inject
private ChatMessageManager chatMessageManager;
@Getter
@Inject
private Client client;
@Getter
@Inject
private ClientThread clientThread;
@Inject
private ClientToolbar clientToolbar;
@Inject
private ConfigManager configManager;
@Getter
@Inject
private RuneLiteConfig runeliteConfig;
@Inject
private OverlayManager overlayManager;
@Inject
private PvpPerformanceTrackerOverlay overlay;
@Getter
@Inject
private ItemManager itemManager;
@Inject
private ScheduledExecutorService executor;
@Inject
private Gson injectedGson;
@Inject
private HiscoreManager hiscoreManager; // Added injection
// custom fields/props
public ArrayList<FightPerformance> fightHistory;
@Getter
private FightPerformance currentFight;
private Map<Integer, ImageIcon> spriteCache; // sprite cache since a small amount of sprites is re-used a lot
// do not cache items in the same way since we could potentially cache a very large amount of them.
private final Map<Integer, List<HitsplatInfo>> hitsplatBuffer = new HashMap<>();
private final Map<Integer, List<HitsplatInfo>> incomingHitsplatsBuffer = new ConcurrentHashMap<>(); // Stores hitsplats *received* by players per tick.
private HiscoreEndpoint hiscoreEndpoint = HiscoreEndpoint.NORMAL; // Added field
// #################################################################################################################
// ##################################### Core RL plugin functions & RL Events ######################################
// #################################################################################################################
@Provides
PvpPerformanceTrackerConfig getConfig(ConfigManager configManager)
{
return configManager.getConfig(PvpPerformanceTrackerConfig.class);
}
@Override
protected void startUp() throws Exception
{
CONFIG = config; // save static instances of config/plugin to easily use in
PLUGIN = this; // other contexts without passing them all the way down or injecting
fightHistory = new ArrayList<>();
GSON = injectedGson.newBuilder()
.excludeFieldsWithoutExposeAnnotation()
.registerTypeAdapter(Double.class, (JsonSerializer<Double>) (value, theType, context) ->
value.isNaN() ? new JsonPrimitive(0) // Convert NaN to zero, otherwise, return as BigDecimal with scale of 3.
: new JsonPrimitive(BigDecimal.valueOf(value).setScale(3, RoundingMode.HALF_UP))
).create();
if (!config.pluginVersion().equals(PLUGIN_VERSION))
{
this.update(config.pluginVersion());
}
panel = injector.getInstance(PvpPerformanceTrackerPanel.class);
final BufferedImage icon = ImageUtil.getResourceStreamFromClass(getClass(), "/skull_red.png");
PLUGIN_ICON = new ImageIcon(icon).getImage();
navButton = NavigationButton.builder()
.tooltip("PvP Fight History")
.icon(icon)
.priority(6)
.panel(panel)
.build();
importFightHistoryData();
// add the panel's nav button depending on config
if (config.showFightHistoryPanel() &&
(!config.restrictToLms() || (client.getGameState() == GameState.LOGGED_IN && isAtLMS())))
{
navButtonShown = true;
clientToolbar.addNavigation(navButton);
}
overlayManager.add(overlay);
spriteCache = new HashMap<>(); // prepare sprite cache
// prepare default N/A or None symbol for eventual use.
clientThread.invokeLater(() -> DEFAULT_NONE_SYMBOL = itemManager.getImage(20594));
// Explicitly rebuild panel after all setup and import.
SwingUtilities.invokeLater(() -> {
if (panel != null) {
panel.rebuild();
}
});
}
@Override
protected void shutDown() throws Exception
{
saveFightHistoryData();
clientToolbar.removeNavigation(navButton);
overlayManager.remove(overlay);
}
@Subscribe
public void onConfigChanged(ConfigChanged event)
{
if (!event.getGroup().equals(CONFIG_KEY)) { return; }
switch(event.getKey())
{
// if a user enables the panel or restricts/unrestricts the location to LMS, hide/show the panel accordingly
case "showFightHistoryPanel":
case "restrictToLms":
boolean isAtLms = isAtLMS();
if (!navButtonShown && config.showFightHistoryPanel() &&
(!config.restrictToLms() || isAtLms))
{
SwingUtilities.invokeLater(() -> clientToolbar.addNavigation(navButton));
navButtonShown = true;
}
else if (navButtonShown && (!config.showFightHistoryPanel() || (config.restrictToLms() && !isAtLms)))
{
SwingUtilities.invokeLater(() -> clientToolbar.removeNavigation(navButton));
navButtonShown = false;
}
break;
// If a user makes any changes to the overlay configuration, reset the shown lines accordingly
case "showOverlayTitle":
case "showOverlayNames":
case "showOverlayOffPray":
case "showOverlayDeservedDmg":
case "showOverlayDmgDealt":
case "showOverlayMagicHits":
case "showOverlayOffensivePray":
case "showOverlayHpHealed":
case "showOverlayGhostBarrage":
overlay.setLines();
break;
// If the user updates the fight history limit, remove fights as necessary
case "fightHistoryLimit":
case "fightHistoryRenderLimit":
if (config.fightHistoryLimit() > 0 && fightHistory.size() > config.fightHistoryLimit())
{
int numToRemove = fightHistory.size() - config.fightHistoryLimit();
// Remove oldest fightHistory until the size is smaller than the limit.
// Should only remove one fight in most cases.
fightHistory.removeIf((FightPerformance f) -> fightHistory.indexOf(f) < numToRemove);
}
panel.rebuild();
break;
case "exactNameFilter":
panel.rebuild();
break;
case "settingsConfigured":
boolean enableConfigWarning = !config.settingsConfigured();
panel.setConfigWarning(enableConfigWarning);
break;
case "robeHitFilter":
recalculateAllRobeHits(true);
break;
// potential future code for level presets/dynamic config if RL ever supports it.
// case "attackLevel":
// case "strengthLevel":
// case "defenceLevel":
// case "rangedLevel":
// case "magicLevel":
// log.info("TEST-just set a level");
// configManager.setConfiguration(CONFIG_KEY, "levelPresetChoice", LevelConfigPreset.CUSTOM);
// break;
// case "levelPresetChoice":
// log.info("TEST- just chose level preset choice");
// LevelConfigPreset p = config.levelPresetChoice();
// switch (p)
// {
// case CUSTOM:
// break;
// case LMS_STATS:
// case NH_STAKE:
// configManager.setConfiguration(CONFIG_KEY, "attackLevel", p.getAtk());
// configManager.setConfiguration(CONFIG_KEY, "strengthLevel", p.getStr());
// configManager.setConfiguration(CONFIG_KEY, "defenceLevel", p.getDef());
// configManager.setConfiguration(CONFIG_KEY, "rangedLevel", p.getRange());
// configManager.setConfiguration(CONFIG_KEY, "magicLevel", p.getMage());
// break;
//
// }
// break;
}
}
// Keep track of a player's new target using this event.
// It's worth noting that if you aren't in a fight, all player interactions including
// trading & following will trigger a new fight and a new opponent. Due to this, set the lastFightTime
// (in FightPerformance) in the past to only be 5 seconds before the time NEW_FIGHT_DELAY would trigger
// and unset the opponent, in case the player follows a different player before actually starting
// a fight or getting attacked. In other words, remain skeptical of the validity of this event.
@Subscribe
public void onInteractingChanged(InteractingChanged event)
{
if (config.restrictToLms() && !isAtLMS())
{
return;
}
stopFightIfOver();
// if the client player already has a valid opponent AND the fight has started,
// or the event source/target aren't players, skip any processing.
if ((hasOpponent() && currentFight.fightStarted())
|| !(event.getSource() instanceof Player)
|| !(event.getTarget() instanceof Player))
{
return;
}
Actor opponent;
// If the event source is the player, then it is the player interacting with their potential opponent.
if (event.getSource().equals(client.getLocalPlayer()))
{
opponent = event.getTarget();
}
else if (event.getTarget().equals(client.getLocalPlayer()))
{
opponent = event.getSource();
}
else // if neither source or target was the player, skip
{
return;
}
// start a new fight with the new found opponent, if a new one.
if (!hasOpponent() || !currentFight.getOpponent().getName().equals(opponent.getName()))
{
currentFight = new FightPerformance(client.getLocalPlayer(), (Player)opponent, hiscoreManager);
overlay.setFight(currentFight);
hitsplatBuffer.clear();
incomingHitsplatsBuffer.clear();
}
}
@Subscribe
public void onGameStateChanged(GameStateChanged gameStateChanged)
{
if (gameStateChanged.getGameState() != GameState.LOGGED_IN)
{
return;
}
sendUpdateChatMessages();
hiscoreEndpoint = HiscoreEndpoint.fromWorldTypes(client.getWorldType()); // Update endpoint on login/world change
// hide or show panel depending if config is restricted to LMS and if player is at LMS
if (config.restrictToLms())
{
if (isAtLMS())
{
if (!navButtonShown && config.showFightHistoryPanel())
{
clientToolbar.addNavigation(navButton);
navButtonShown = true;
}
}
else
{
if (navButtonShown)
{
clientToolbar.removeNavigation(navButton);
navButtonShown = false;
}
}
}
}
@Subscribe
public void onAnimationChanged(AnimationChanged event)
{
stopFightIfOver();
// delay the animation processing, since we will also want to use equipment data for deserved
// damage, and equipment updates are loaded after the animation updates.
clientThread.invokeLater(() ->
{
if (hasOpponent() && event.getActor() instanceof Player && event.getActor().getName() != null)
{
currentFight.checkForAttackAnimations((Player)event.getActor(), new CombatLevels(client));
}
});
}
@Subscribe
// track damage dealt/taken
public void onHitsplatApplied(HitsplatApplied event)
{
int hitType = event.getHitsplat().getHitsplatType();
int amount = event.getHitsplat().getAmount();
Actor target = event.getActor();
// if there's no opponent, the target is not a player, or the hitsplat is not relevant to pvp damage,
// skip the hitsplat. Otherwise, add it to the fight, which will only include it if it is one of the
// Fighters in the fight being hit.
if (!hasOpponent() || !(target instanceof Player))
{
return;
}
// for non-zero hits, only process relevant hitsplat types
if (amount > 0)
{
if (!(hitType == HitsplatID.DAMAGE_ME
|| hitType == HitsplatID.DAMAGE_ME_ORANGE
|| hitType == HitsplatID.DAMAGE_OTHER_ORANGE
|| hitType == HitsplatID.DAMAGE_OTHER
|| hitType == HitsplatID.DAMAGE_MAX_ME
|| hitType == HitsplatID.DAMAGE_MAX_ME_ORANGE
|| hitType == HitsplatID.POISON
|| hitType == HitsplatID.VENOM
|| hitType == HitsplatID.BURN))
{
return;
}
}
currentFight.addDamageDealt(target.getName(), amount);
// Exclude certain hitsplat types (like heal, burn, poison, venom, disease)
// from the buffer used for HP-before-hit calculations.
boolean isExcludedType = hitType == HitsplatID.HEAL ||
hitType == HitsplatID.POISON ||
hitType == HitsplatID.VENOM ||
hitType == HitsplatID.BURN ||
hitType == HitsplatID.DISEASE;
if (isExcludedType)
{
return; // Don't buffer these types for HP calc / matching
}
// Store hitsplats received by competitor or opponent for potential vengeance trigger lookup
Player player = client.getLocalPlayer();
if (target == player || (hasOpponent() && target == currentFight.getOpponent().getPlayer()))
{
int currentTick = client.getTickCount();
incomingHitsplatsBuffer.computeIfAbsent(currentTick, k -> new CopyOnWriteArrayList<>()).add(new HitsplatInfo(event));
}
// Buffer the hitsplat event instead of processing immediately (unless excluded earlier)
// Vengeance damage hitsplats WILL be included here initially.
HitsplatInfo info = new HitsplatInfo(event);
int tick = client.getTickCount();
List<HitsplatInfo> tickEvents = hitsplatBuffer.computeIfAbsent(tick, k -> new ArrayList<>());
tickEvents.add(info);
// Get the HP of the actor on the client thread, after the hitsplat has been applied.
clientThread.invokeLater(() ->
{
Actor hitActor = info.getEvent().getActor();
if (hitActor != null)
{
info.setHp(hitActor.getHealthRatio(), hitActor.getHealthScale());
}
});
}
@Subscribe
// track hitpoints healed & ghost barrages for main competitor/client player
public void onStatChanged(StatChanged statChanged)
{
Skill skill = statChanged.getSkill();
if (!hasOpponent()) { return; }
if (skill == Skill.HITPOINTS)
{
currentFight.updateCompetitorHp(client.getBoostedSkillLevel(Skill.HITPOINTS));
}
if (skill == Skill.MAGIC)
{
int magicXp = client.getSkillExperience(Skill.MAGIC);
if (magicXp > currentFight.competitor.getLastGhostBarrageCheckedMageXp())
{
currentFight.competitor.setLastGhostBarrageCheckedMageXp(PLUGIN.getClient().getSkillExperience(Skill.MAGIC));
clientThread.invokeLater(this::checkForGhostBarrage);
}
}
}
@Subscribe
// track ghost barrages for main competitor/client player
public void onFakeXpDrop(FakeXpDrop fakeXpDrop)
{
if (!hasOpponent() || fakeXpDrop.getSkill() != Skill.MAGIC) { return; }
clientThread.invokeLater(this::checkForGhostBarrage);
}
// if the player gained magic xp but doesn't have a magic-attack animation, consider it as a ghost barrage.
// however this won't be added as a normal attack, it is for an extra ghost-barrage statistic as
// we can only detect this for the local player
private void checkForGhostBarrage()
{
if (!hasOpponent()) { return; }
currentFight.checkForLocalGhostBarrage(new CombatLevels(client), client.getLocalPlayer());
}
// When the config is reset, also reset the fight history data, as a way to restart
// if the current data is causing problems.
@Override
public void resetConfiguration()
{
super.resetConfiguration();
resetFightHistory();
}
// when the client shuts down, save the fight history data locally.
@Subscribe
public void onClientShutdown(ClientShutdown event)
{
event.waitFor(executor.submit(this::saveFightHistoryData));
}
@Subscribe
public void onGameTick(GameTick event)
{
// Process hitsplats from the previous tick
int currentTick = client.getTickCount();
int tickToProcess = currentTick - 1;
int maxWindow = 5;
List<HitsplatInfo> hitsplatsToProcess = hitsplatBuffer.remove(tickToProcess);
// --- START: New Pre-processing Logic ---
if (hitsplatsToProcess != null && !hitsplatsToProcess.isEmpty() && hasOpponent())
{
// 1. Calculate total expected hits from pending attacks for this tick
int totalExpectedAttackHits = 0;
Player player = client.getLocalPlayer();
// Assuming getOpponentName() and getOpponentActor() exist or accessing opponent/competitor directly
Actor opponentActor = currentFight.getOpponent().getPlayer();
// Sum expected hits from opponent's pending attacks targeting player
if (currentFight.getOpponent() != null)
{
totalExpectedAttackHits += currentFight.getOpponent().getPendingAttacks().stream()
.filter(e -> !e.isKoChanceCalculated() && e.isFullEntry() && !e.isSplash() && (tickToProcess - e.getTick() <= 5)) // Check if attack could land now
.mapToInt(FightLogEntry::getExpectedHits)
.sum();
}
// Sum expected hits from competitor's pending attacks targeting opponent
if (currentFight.getCompetitor() != null)
{
totalExpectedAttackHits += currentFight.getCompetitor().getPendingAttacks().stream()
.filter(e -> !e.isKoChanceCalculated() && e.isFullEntry() && !e.isSplash() && (tickToProcess - e.getTick() <= 5)) // Check if attack could land now
.mapToInt(FightLogEntry::getExpectedHits)
.sum();
}
// 2. Compare observed vs expected
if (hitsplatsToProcess.size() > totalExpectedAttackHits)
{
log.debug("Tick {}: Observed hits ({}) > Expected attack hits ({}). Checking for special hits...",
tickToProcess, hitsplatsToProcess.size(), totalExpectedAttackHits);
boolean removedHitInIteration;
int safetyBreakCounter = 0;
int maxIterations = hitsplatsToProcess.size() * 2; // Allow more iterations to be safe
// 3. Loop while observed > expected (or until no more candidates found)
while (hitsplatsToProcess.size() > totalExpectedAttackHits && safetyBreakCounter++ < maxIterations)
{
removedHitInIteration = false;
Iterator<HitsplatInfo> iterator = hitsplatsToProcess.iterator();
while (iterator.hasNext())
{
HitsplatInfo potentialSpecialHit = iterator.next();
Actor target = potentialSpecialHit.getEvent().getActor();
int hitAmount = potentialSpecialHit.getEvent().getHitsplat().getAmount();
boolean isCandidate = false;
// Determine who the 'other' player is (the one who might have *caused* veng/recoil)
Actor otherPlayer = null;
if (target == player)
{
otherPlayer = opponentActor;
}
else if (target == opponentActor)
{
otherPlayer = player;
}
// 4. Check Candidates (Vengeance/Recoil)
if (otherPlayer != null)
{
List<HitsplatInfo> incomingHitsOnOther = incomingHitsplatsBuffer.get(tickToProcess);
if (incomingHitsOnOther != null)
{
for (HitsplatInfo incomingHit : incomingHitsOnOther)
{
// Only check hits *received* by the other player
if (incomingHit.getEvent().getActor() == otherPlayer)
{
int incomingDamage = incomingHit.getEvent().getHitsplat().getAmount();
// Vengeance Check
int expectedVengeance = Math.max(1, (int) Math.floor(incomingDamage * 0.75));
if (hitAmount == expectedVengeance)
{
log.debug("Tick {}: Found potential Vengeance hit ({} damage) on {} based on {} incoming damage on {}",
tickToProcess, hitAmount, target.getName(), incomingDamage, otherPlayer.getName());
isCandidate = true;
break; // Found a reason, no need to check other incoming hits for this potentialSpecialHit
}
// Recoil Check
int expectedRecoil = Math.max(1, (int) Math.floor(incomingDamage * 0.10) + 1);
if (hitAmount == expectedRecoil)
{
log.debug("Tick {}: Found potential Recoil hit ({} damage) on {} based on {} incoming damage on {}",
tickToProcess, hitAmount, target.getName(), incomingDamage, otherPlayer.getName());
isCandidate = true;
break;
}
}
}
}
}
// Burn Check removed: burn hitsplats are excluded earlier in onHitsplatApplied
// 5. Remove if Candidate Found
if (isCandidate)
{
iterator.remove();
removedHitInIteration = true;
break; // Exit inner loop, re-check outer while condition
}
} // End inner iterator loop
// Safety break if no hits were removed in a full pass
if (!removedHitInIteration)
{
log.debug("Tick {}: No special hit candidates removed in iteration. Breaking pre-emptive removal.", tickToProcess);
break;
}
} // End outer while loop
} // End if (observed > expected)
}
// --- END: New Pre-processing Logic ---
// Cleanup happens regardless of whether hitsplats were processed this tick
// Check if hitsplatsToProcess became null or empty after pre-processing
if (hitsplatsToProcess == null || hitsplatsToProcess.isEmpty()) // Modified condition
{
// Cleanup old entries from buffers
hitsplatBuffer.keySet().removeIf(tick -> tick < currentTick - maxWindow);
incomingHitsplatsBuffer.keySet().removeIf(tick -> tick < currentTick - maxWindow);
return;
}
// --- Proceed with Regular Matching using the potentially modified hitsplatsToProcess ---
// Group hitsplats by the actor receiving them (remaining hitsplats after special removal)
final List<HitsplatInfo> finalHitsplatsToProcess = hitsplatsToProcess; // Create effectively final list
Map<Actor, List<HitsplatInfo>> hitsByActor = finalHitsplatsToProcess.stream()
.collect(Collectors.groupingBy((HitsplatInfo info) -> info.getEvent().getActor()));
List<FightLogEntry> processedEntriesThisTick = new ArrayList<>();
hitsByActor.forEach((opponent, hits) -> {
if (!(opponent instanceof Player)) return; // Only process hits on players
// Determine max HP to use (config, Hiscores, or LMS override)
int maxHpToUse;
if (isAtLMS())
{
maxHpToUse = 99;
}
else
{
maxHpToUse = CONFIG.opponentHitpointsLevel();
// Hiscores lookup should only happen if not in LMS
if (opponent instanceof Player && opponent.getName() != null)
{
final HiscoreResult hiscoreResult = hiscoreManager.lookupAsync(opponent.getName(), hiscoreEndpoint);
if (hiscoreResult != null)
{
final int hp = hiscoreResult.getSkill(HiscoreSkill.HITPOINTS).getLevel();
if (hp > 0)
{
maxHpToUse = hp; // Use Hiscores HP if available
}
}
}
}
// Determine attacker
String actorName = ((Player) opponent).getName();
Fighter attacker;
if (actorName.equals(currentFight.getOpponent().getName()))
{
attacker = currentFight.getCompetitor();
}
else if (actorName.equals(currentFight.getCompetitor().getName()))
{
attacker = currentFight.getOpponent();
}
else
{
return;
}
// Get all potentially relevant, unprocessed entries sorted by animation tick
List<FightLogEntry> candidateEntries = attacker.getPendingAttacks().stream()
.filter(e -> !e.isKoChanceCalculated() && e.isFullEntry() && !e.isSplash())
.filter(e -> (client.getTickCount() - e.getTick()) <= 5)
.sorted(Comparator.comparingInt(FightLogEntry::getTick))
.collect(Collectors.toList());
List<FightLogEntry> gmaulsMatchedThisTick = new ArrayList<>();
int totalGmaulHitsMatchedThisTick = 0;
// Iterate through candidate entries chronologically
for (FightLogEntry entry : candidateEntries)
{
// Apply specific lookback for the entry's style
int lookback;
switch (entry.getAnimationData().attackStyle)
{
case STAB: case SLASH: case CRUSH: lookback = 3; break;
case MAGIC: lookback = 5; break;
case RANGED: default: lookback = 3; break;
}
if (client.getTickCount() - entry.getTick() > lookback)
{
entry.setKoChanceCalculated(true);
attacker.getPendingAttacks().remove(entry);
continue;
}
int toMatch = entry.getExpectedHits() - entry.getMatchedHitsCount();
if (toMatch <= 0)
{
entry.setKoChanceCalculated(true);
attacker.getPendingAttacks().remove(entry);
continue;
}
boolean isInstantGmaulCheck = entry.isGmaulSpecial() && entry.getTick() == tickToProcess;
boolean isDelayedAttack = !isInstantGmaulCheck;
// Only try to match if it's either an instant GMaul or a delayed attack landing now
if (isInstantGmaulCheck || isDelayedAttack)
{
int matchedThisCycle = 0;
int damageThisCycle = 0;
HitsplatInfo lastMatchedInfo = null;
Iterator<HitsplatInfo> hitsIter = hits.iterator();
// Gmaul can hit twice, others match expected hits
int hitsToFind = entry.isGmaulSpecial() ? 2 : toMatch;
while (matchedThisCycle < hitsToFind && hitsIter.hasNext())
{
HitsplatInfo hInfo = hitsIter.next();
int amt = hInfo.getEvent().getHitsplat().getAmount();
damageThisCycle += amt;
matchedThisCycle++;
lastMatchedInfo = hInfo;
hitsIter.remove();
}
if (matchedThisCycle > 0)
{
entry.setActualDamageSum(entry.getActualDamageSum() + damageThisCycle);
entry.setMatchedHitsCount(entry.getMatchedHitsCount() + matchedThisCycle);
processedEntriesThisTick.add(entry);
if (entry.isGmaulSpecial())
{
gmaulsMatchedThisTick.add(entry);
totalGmaulHitsMatchedThisTick += matchedThisCycle;
}
if (entry.getHitsplatTick() < 0 && lastMatchedInfo != null)
{
entry.setHitsplatTick(tickToProcess);
}
// Calculate and set estimated HP Before using polled HP
int ratio = -1, scale = -1;
if (lastMatchedInfo != null)
{
ratio = lastMatchedInfo.getHealthRatio();
scale = lastMatchedInfo.getHealthScale();
}
// Fallback to current ratio/scale if polled is unavailable
if (ratio < 0 || scale <= 0) { ratio = opponent.getHealthRatio(); scale = opponent.getHealthScale(); }
int hpBefore = -1;
if (ratio >= 0 && scale > 0 && maxHpToUse > 0)
{
hpBefore = PvpPerformanceTrackerUtils.calculateHpBeforeHit(ratio, scale, maxHpToUse, entry.getActualDamageSum());
}
if (hpBefore > 0)
{
entry.setEstimatedHpBeforeHit(hpBefore);
entry.setOpponentMaxHp(maxHpToUse);
}
}
}
// Mark entry as fully processed if all expected hits are matched OR if it's an instant Gmaul (even if only 1 hit matched)
if (entry.getMatchedHitsCount() >= entry.getExpectedHits() || isInstantGmaulCheck)
{
entry.setKoChanceCalculated(true);
attacker.getPendingAttacks().remove(entry);
}
}
// Gmaul Damage Scaling (Applied after all matching for the tick)
boolean isMultiHitGmaul = totalGmaulHitsMatchedThisTick >= 2;
if (isMultiHitGmaul)
{
for (FightLogEntry gmaulEntry : gmaulsMatchedThisTick)
{
int originalMin = gmaulEntry.getMinHit();
int originalMax = gmaulEntry.getMaxHit();
double originalDeserved = gmaulEntry.getDeservedDamage();
gmaulEntry.setMaxHit(originalMax * totalGmaulHitsMatchedThisTick);
gmaulEntry.setMinHit(originalMin * totalGmaulHitsMatchedThisTick);
gmaulEntry.setDeservedDamage(originalDeserved * totalGmaulHitsMatchedThisTick);
}
}
});
// Post-processing for Display HP/KO Chance
if (!processedEntriesThisTick.isEmpty())
{
// Group processed entries by the tick they landed and the attacker
Map<Integer, Map<String, List<FightLogEntry>>> groupedByTickAndAttacker = processedEntriesThisTick.stream()
.filter(e -> e.getHitsplatTick() >= 0)
.collect(Collectors.groupingBy(
FightLogEntry::getHitsplatTick,
Collectors.groupingBy(
FightLogEntry::getAttackerName,
Collectors.toList()
)
));
groupedByTickAndAttacker.forEach((tick, attackerMap) -> {
attackerMap.forEach((attackerName, entries) -> {
if (entries.isEmpty()) return;
// Sort entries within the tick group by their original animation tick
entries.sort(Comparator.comparingInt(FightLogEntry::getTick));
boolean isGroup = entries.size() > 1;
// Calculate Correct Starting HP for Forward Cascade
Integer hpBeforeSequence = null;
FightLogEntry lastEntry = entries.get(entries.size() - 1);
Integer hpBeforeLastHit = lastEntry.getEstimatedHpBeforeHit();
Integer lastHitDamage = lastEntry.getActualDamageSum();
// Ensure we have the necessary values from the last hit to calculate final HP
if (hpBeforeLastHit != null && lastHitDamage != null)
{
Integer hpAfterSequence = hpBeforeLastHit - lastHitDamage;
// Calculate total damage for the sequence
int totalDamageInSequence = entries.stream()
.mapToInt((FightLogEntry e) -> e.getActualDamageSum() != null ? e.getActualDamageSum() : 0)
.sum();
// Calculate HP Before the entire sequence
hpBeforeSequence = hpAfterSequence + totalDamageInSequence;
}
// If hpBeforeSequence is still null (calculation failed), try fallback using first entry's estimate
if (hpBeforeSequence == null)
{
hpBeforeSequence = entries.get(0).getEstimatedHpBeforeHit();
}
// Forward Cascade for Display
Integer currentHp = hpBeforeSequence;
for (FightLogEntry entry : entries)
{
Integer hpBeforeCurrent = currentHp;
int damageCurrent = entry.getActualDamageSum() != null ? entry.getActualDamageSum() : 0;
Integer hpAfterCurrent = (hpBeforeCurrent != null) ? hpBeforeCurrent - damageCurrent : null;
entry.setDisplayHpBefore(hpBeforeCurrent);
entry.setDisplayHpAfter(hpAfterCurrent);
Double koChanceCurrent = (hpBeforeCurrent != null)
? PvpPerformanceTrackerUtils.calculateKoChance(entry.getAccuracy(), entry.getMinHit(), entry.getMaxHit(), hpBeforeCurrent)
: null;
entry.setDisplayKoChance(koChanceCurrent);
entry.setKoChance(koChanceCurrent);
currentFight.updateKoChanceStats(entry);
entry.setPartOfTickGroup(isGroup);
// Update HP for the next iteration
currentHp = hpAfterCurrent;
}
});
});
}
// Cleanup old entries from buffers at the end of the tick processing
hitsplatBuffer.keySet().removeIf(tick -> tick < currentTick - maxWindow);
incomingHitsplatsBuffer.keySet().removeIf(tick -> tick < currentTick - maxWindow);
}
// #################################################################################################################
// ################################## Plugin-specific functions & global helpers ###################################
// #################################################################################################################