-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDamageMeterService.lua
More file actions
2268 lines (2047 loc) · 97.5 KB
/
DamageMeterService.lua
File metadata and controls
2268 lines (2047 loc) · 97.5 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
local _, ns = ...
local Constants = ns.Constants
local ApiCompat = ns.ApiCompat
local Helpers = ns.Helpers
local DamageMeterService = {}
local UNATTRIBUTED_DAMAGE_SPELL_ID = -1
local DEFAULT_SPELL_ICON_ID = 134400
-- T048: Detect whether DeathRecap category exists in Enum.DamageMeterType.
local HAS_DEATH_RECAP = pcall(function() return Enum.DamageMeterType.DeathRecap end)
local function createSpellAggregate(spellId)
return {
spellId = spellId,
name = nil,
iconID = nil,
schoolMask = nil,
castCount = 0,
executeCount = 0,
hitCount = 0,
critCount = 0,
missCount = 0,
totalDamage = 0,
totalHealing = 0,
overkill = 0,
overhealing = 0,
absorbed = 0,
minHit = nil,
maxHit = 0,
minCrit = nil,
maxCrit = 0,
firstUse = nil,
lastUse = nil,
lastCastOffset = nil,
totalInterval = 0,
intervalCount = 0,
averageInterval = 0,
source = nil,
syntheticKind = nil,
estimated = false,
}
end
local function ensureSyntheticSpellAggregate(session, spellId, name, iconID, syntheticKind)
session.spells = session.spells or {}
session.spells[spellId] = session.spells[spellId] or createSpellAggregate(spellId)
local aggregate = session.spells[spellId]
aggregate.name = name or aggregate.name
aggregate.iconID = iconID or aggregate.iconID or DEFAULT_SPELL_ICON_ID
aggregate.syntheticKind = syntheticKind or aggregate.syntheticKind
aggregate.source = Constants.PROVENANCE_SOURCE.ESTIMATED
return aggregate
end
local function sortSessionsById(sessions)
table.sort(sessions, function(left, right)
return (left.sessionID or 0) < (right.sessionID or 0)
end)
return sessions
end
local function sortSessionsByIdDesc(sessions)
table.sort(sessions, function(left, right)
return (left.sessionID or 0) > (right.sessionID or 0)
end)
return sessions
end
local function isDamageMeterEnabled()
if GetCVarBool then
return GetCVarBool("damageMeterEnabled")
end
if GetCVar then
return GetCVar("damageMeterEnabled") == "1"
end
return true
end
local function getResolvedTotal(sessionSource, combatSource, combatSession)
if sessionSource and sessionSource.totalAmount ~= nil then
return sessionSource.totalAmount
end
if combatSource and combatSource.totalAmount ~= nil then
return combatSource.totalAmount
end
if combatSession and #(combatSession.combatSources or {}) == 1 and combatSession.totalAmount ~= nil then
return combatSession.totalAmount
end
return 0
end
local function countCombatSpells(combatSpells)
return #(combatSpells or {})
end
local function sumCombatSpellAmounts(combatSpells)
local total = 0
for _, combatSpell in ipairs(combatSpells or {}) do
total = total + (combatSpell.totalAmount or 0)
end
return total
end
local function mergeCombatSpell(spellsById, combatSpell)
local spellId = combatSpell and combatSpell.spellID
if spellId == nil then
return
end
local mergedSpell = spellsById[spellId]
if not mergedSpell then
mergedSpell = {
spellID = spellId,
totalAmount = 0,
amountPerSecond = 0,
creatureName = combatSpell.creatureName,
overkillAmount = 0,
isAvoidable = combatSpell.isAvoidable,
isDeadly = combatSpell.isDeadly,
combatSpellDetails = combatSpell.combatSpellDetails,
}
spellsById[spellId] = mergedSpell
end
mergedSpell.totalAmount = mergedSpell.totalAmount + (combatSpell.totalAmount or 0)
mergedSpell.amountPerSecond = mergedSpell.amountPerSecond + (combatSpell.amountPerSecond or 0)
mergedSpell.overkillAmount = mergedSpell.overkillAmount + (combatSpell.overkillAmount or 0)
end
local function buildMergedCombatSpellList(spellsById)
local result = {}
for _, combatSpell in pairs(spellsById or {}) do
result[#result + 1] = combatSpell
end
table.sort(result, function(left, right)
if (left.totalAmount or 0) == (right.totalAmount or 0) then
return (left.spellID or 0) < (right.spellID or 0)
end
return (left.totalAmount or 0) > (right.totalAmount or 0)
end)
return result
end
-- F1/B1: Resolve the player's own damage from the post-match scoreboard.
-- session.postMatchScores is captured secret-safely in
-- CombatTracker:HarvestPostMatchData (post-match, ApiCompat-sanitized). The
-- player row is the authoritative per-player figure; enemyDamageTaken includes
-- teammates' damage and must not be treated as the player's output in PvP.
local function getScoreboardPlayerDamage(session)
local scores = session and session.postMatchScores
if type(scores) ~= "table" then
return nil
end
local ApiCompat = ns.ApiCompat
local myGuid = ApiCompat and ApiCompat.GetPlayerGUID() or nil
local myName = ApiCompat and ApiCompat.GetPlayerName() or nil
for _, entry in ipairs(scores) do
local isPlayer = (myGuid ~= nil and entry.guid == myGuid)
or (entry.guid == nil and myName ~= nil and entry.name == myName)
if isPlayer then
local dmg = tonumber(entry.damageDone) or 0
if dmg > 0 then
return dmg
end
return nil
end
end
return nil
end
local function getExpectedDamageTotal(session, snapshot)
local directDamage = tonumber(snapshot and snapshot.damageDone) or 0
if directDamage > 0 then
if session then session.expectedDamageSource = "direct_snapshot" end
return directDamage
end
local enemyDamage = tonumber(snapshot and snapshot.enemyDamageTaken) or 0
if enemyDamage <= 0 or not session then
if session then session.expectedDamageSource = "none" end
return 0
end
if session.context == Constants.CONTEXT.TRAINING_DUMMY or session.context == Constants.CONTEXT.DUEL then
session.expectedDamageSource = "dummy_or_duel_enemy_taken"
return enemyDamage
end
-- Arena/BG: enemyDamageTaken is "all enemies' damage taken" and includes
-- damage dealt by the player's teammates. Anchor to the scoreboard player
-- row when available; otherwise fall back to the contaminated proxy and
-- record an explicit confidence downgrade.
if session.context == Constants.CONTEXT.ARENA or session.context == Constants.CONTEXT.BATTLEGROUND then
local scoreboardDamage = getScoreboardPlayerDamage(session)
if scoreboardDamage and scoreboardDamage > 0 then
session.expectedDamageSource = "scoreboard_player_row"
return scoreboardDamage
end
session.expectedDamageSource = "enemy_damage_taken_team_contaminated"
session.expectedDamageContaminated = true
return enemyDamage
end
local identity = session.identity or {}
local evidence = identity.evidence or {}
local opponent = session.primaryOpponent or {}
if (evidence.dummyScore or 0) >= 60 then
session.expectedDamageSource = "dummy_score_enemy_taken"
return enemyDamage
end
if opponent.guid and not opponent.isPlayer then
session.expectedDamageSource = "npc_opponent_enemy_taken"
return enemyDamage
end
-- Last resort: use session.totals.damageDone (may have been set by a
-- partial DM import or prior retry) when the snapshot itself had no total.
local sessionTotal = session and session.totals and tonumber(session.totals.damageDone) or 0
if sessionTotal > 0 then
session.expectedDamageSource = "session_total_fallback"
return sessionTotal
end
session.expectedDamageSource = "none"
return 0
end
local function getDurationMatchScore(expectedDuration, candidateDuration)
local left = tonumber(expectedDuration) or 0
local right = tonumber(candidateDuration) or 0
if left <= 0 or right <= 0 then
return 0
end
local delta = math.abs(left - right)
if delta <= 1 then
return 24
end
if delta <= 3 then
return 16
end
if delta <= 6 then
return 10
end
if delta <= 10 then
return 5
end
return 0
end
local function getDurationDelta(expectedDuration, candidateDuration)
local left = tonumber(expectedDuration) or 0
local right = tonumber(candidateDuration) or 0
if left <= 0 or right <= 0 then
return 0
end
return math.abs(left - right)
end
local function getImportConfidenceFromScore(score)
local numeric = tonumber(score) or 0
if numeric >= 150 then
return 96
end
if numeric >= 130 then
return 90
end
if numeric >= 110 then
return 84
end
if numeric >= 90 then
return 76
end
if numeric >= 70 then
return 68
end
if numeric >= 50 then
return 58
end
if numeric >= 30 then
return 46
end
return 30
end
-- Attempts to import a death recap from C_DeathRecap given a DM combatSource.
-- Returns a deathRecap table on success, nil if no data or API unavailable.
local function tryImportDeathRecap(deathCombatSource)
if not deathCombatSource then return nil end
local recapId = deathCombatSource.deathRecapID or 0
local deathTime = deathCombatSource.deathTimeSeconds or 0
if not recapId or recapId == 0 then return nil end
local recap = { timeSeconds = deathTime, recapID = recapId }
local okHp, maxHp = pcall(function()
return C_DeathRecap and C_DeathRecap.GetRecapMaxHealth and C_DeathRecap.GetRecapMaxHealth(recapId)
end)
recap.maxHealth = okHp and maxHp or nil
local okHas, hasEvents = pcall(function()
return C_DeathRecap and C_DeathRecap.HasRecapEvents and C_DeathRecap.HasRecapEvents(recapId)
end)
if okHas and hasEvents then
local okE, events = pcall(function()
return C_DeathRecap.GetRecapEvents(recapId)
end)
recap.events = okE and events or nil
end
return recap
end
local function snapshotHasMeaningfulData(snapshot)
if not snapshot then
return false
end
return (snapshot.damageDone or 0) > 0
or (snapshot.healingDone or 0) > 0
or (snapshot.damageTaken or 0) > 0
or countCombatSpells(snapshot.damageSpells) > 0
or countCombatSpells(snapshot.enemyDamageSpells) > 0
or (snapshot.enemyDamageTaken or 0) > 0
end
local function setAggregateDamageAmount(aggregate, amount)
local numeric = tonumber(amount) or 0
aggregate.totalDamage = numeric
aggregate.hitCount = numeric > 0 and math.max(aggregate.hitCount or 0, 1) or 0
aggregate.executeCount = numeric > 0 and math.max(aggregate.executeCount or 0, aggregate.hitCount or 0, 1) or 0
end
local function snapshotHasMeaningfulDamage(snapshot)
if not snapshot then
return false
end
return (snapshot.damageDone or 0) > 0
or (snapshot.enemyDamageTaken or 0) > 0
or (tonumber(snapshot.localDamageSpellTotal) or 0) > 0
or (tonumber(snapshot.enemyDamageSpellTotal) or 0) > 0
or countCombatSpells(snapshot.damageSpells) > 0
or countCombatSpells(snapshot.enemyDamageSpells) > 0
end
local function getDamageEvidenceScore(snapshot)
if not snapshot then
return 0
end
local localTotal = tonumber(snapshot.localDamageSpellTotal) or sumCombatSpellAmounts(snapshot.damageSpells)
local enemyTotal = tonumber(snapshot.enemyDamageSpellTotal) or sumCombatSpellAmounts(snapshot.enemyDamageSpells)
local score = 0
if (snapshot.damageDone or 0) > 0 then
score = score + 70
end
if (snapshot.enemyDamageTaken or 0) > 0 then
score = score + 55
end
if localTotal > 0 then
score = score + 40
end
if enemyTotal > 0 then
score = score + 40
end
score = score + math.min(countCombatSpells(snapshot.damageSpells), 6) * 4
score = score + math.min(countCombatSpells(snapshot.enemyDamageSpells), 6) * 4
return score
end
local function getLatestTrackedUnit(session)
for _, actor in pairs(session.actors or {}) do
if actor and actor.unitToken and actor.unitToken ~= "player" and actor.unitToken ~= "pet" then
return actor
end
end
return nil
end
-- collectExpectedOpponentGuids returns a keyed table of all known enemy GUIDs
-- for the given session. GUIDs are gathered from four sources:
-- 1. session.primaryOpponent.guid
-- 2. session.identity.opponentGuid
-- 3. session.arena.slots[*].guid (all persisted arena slots)
-- 4. ArenaRoundTracker:GetSlots() live state (current round slots)
local function collectExpectedOpponentGuids(session)
local guids = {}
local po = session and session.primaryOpponent
if po and po.guid then guids[po.guid] = true end
local identity = session and session.identity
if identity and identity.opponentGuid then guids[identity.opponentGuid] = true end
local arena = session and session.arena
if arena and arena.slots then
for _, slot in pairs(arena.slots) do
if slot.guid then guids[slot.guid] = true end
end
end
-- Pull live slots from ArenaRoundTracker for the current round.
local art = ns and ns.Addon and ns.Addon.GetModule and ns.Addon:GetModule("ArenaRoundTracker")
if art then
for _, slot in pairs(art:GetSlots()) do
if slot.guid then guids[slot.guid] = true end
end
end
return guids
end
function DamageMeterService:IsSupported()
return type(C_DamageMeter) == "table" and type(Enum) == "table" and type(Enum.DamageMeterType) == "table"
end
function DamageMeterService:IsAvailable()
if not self:IsSupported() then
return false, "missing_api"
end
local isAvailable, failureReason = ApiCompat.IsDamageMeterAvailable()
if not isAvailable then
return false, failureReason
end
if not isDamageMeterEnabled() then
return false, "damage_meter_disabled"
end
return true
end
function DamageMeterService:GetAvailableSessions()
return sortSessionsById(ApiCompat.GetAvailableCombatSessions() or {})
end
function DamageMeterService:GetLatestSessionId()
local latestSessionId = 0
for _, sessionInfo in ipairs(self:GetAvailableSessions()) do
latestSessionId = math.max(latestSessionId, sessionInfo.sessionID or 0)
end
return latestSessionId > 0 and latestSessionId or nil
end
-- Public accessor for the post-match scoreboard player-damage row. Returns the
-- player's own damageDone from session.postMatchScores, or nil when no usable
-- row exists. The terminal arena scoreboard anchor in CombatTracker uses this
-- when C_DamageMeter import produced no total.
function DamageMeterService:GetScoreboardPlayerDamage(session)
return getScoreboardPlayerDamage(session)
end
function DamageMeterService:Initialize()
local latestSessionId = self:GetLatestSessionId()
self.lastSeenSessionId = latestSessionId or 0
self.activeSessionBaselineId = nil
self.warnedUnavailable = false
self.latestUpdatedSessionIdByType = {}
self.currentSessionSnapshot = nil
self.sessionUpdateSignals = {}
-- Startup diagnostics: log C_DamageMeter availability and CVar state.
local isAvailable, failReason = self:IsAvailable()
local cvarEnabled = isDamageMeterEnabled()
local sessionCount = latestSessionId and 1 or 0
ns.Addon:Trace("damage_meter.init", {
isSupported = self:IsSupported(),
isAvailable = isAvailable,
failReason = failReason or "none",
cvarEnabled = cvarEnabled,
initialSessions = sessionCount,
baselineId = self.lastSeenSessionId,
})
-- Warn user if CVar is disabled — this is the #1 cause of zero damage.
if self:IsSupported() and not cvarEnabled then
C_Timer.After(5, function()
ns.Addon:Warn(
"Blizzard Damage Meter is DISABLED. CombatAnalytics cannot track damage without it. "
.. "Enable it: ESC > Options > Gameplay > Combat > Enable Damage Meter"
)
end)
end
end
function DamageMeterService:MarkSessionStart()
-- Preserve the earliest baseline for the current combat window. Late
-- session autodiscovery may call MarkSessionStart again after C_DamageMeter
-- has already advanced to the active fight session; resetting the baseline
-- then can make import selection skip the fight we are trying to import.
if self.activeSessionBaselineId ~= nil then
ns.Addon:Trace("damage_meter.session_start.reuse", {
baseline = self.activeSessionBaselineId or 0,
})
return self.activeSessionBaselineId
end
self.activeSessionBaselineId = self:GetLatestSessionId() or self.lastSeenSessionId or 0
self.currentSessionSnapshot = nil
self.sessionUpdateSignals = {}
ns.Addon:Trace("damage_meter.session_start", {
baseline = self.activeSessionBaselineId or 0,
})
return self.activeSessionBaselineId
end
function DamageMeterService:RecordSessionUpdateSignal(damageMeterType, sessionId)
if not sessionId or sessionId <= 0 then
return
end
self.sessionUpdateSignals = self.sessionUpdateSignals or {}
local signal = self.sessionUpdateSignals[sessionId]
if not signal then
signal = {
count = 0,
types = {},
lastUpdatedAt = 0,
}
self.sessionUpdateSignals[sessionId] = signal
end
signal.count = signal.count + 1
signal.types[damageMeterType] = true
signal.lastUpdatedAt = Helpers.Now()
end
function DamageMeterService:GetSessionUpdateSignal(sessionId)
return self.sessionUpdateSignals and self.sessionUpdateSignals[sessionId] or nil
end
function DamageMeterService:GetSessionSignalScore(sessionId)
local signal = self:GetSessionUpdateSignal(sessionId)
if not signal then
return 0, nil
end
local score = 0
if signal.types[Enum.DamageMeterType.DamageDone] then
score = score + 26
end
if signal.types[Enum.DamageMeterType.EnemyDamageTaken] then
score = score + 22
end
if signal.types[Enum.DamageMeterType.HealingDone] then
score = score + 6
end
score = score + math.min(signal.count or 0, 4) * 3
local ageSeconds = math.max(0, Helpers.Now() - (signal.lastUpdatedAt or 0))
if ageSeconds <= 0.5 then
score = score + 8
elseif ageSeconds <= 1.5 then
score = score + 5
elseif ageSeconds <= 3 then
score = score + 2
end
return score, signal
end
function DamageMeterService:GetContextFitScore(session, snapshot)
if not session or not snapshot then
return 0
end
local identity = session.identity or {}
local context = identity.kind or session.context
if context == Constants.CONTEXT.TRAINING_DUMMY then
local score = 0
if (snapshot.enemyDamageTaken or 0) > 0 then
score = score + 10
end
if (snapshot.enemyDamageSpellTotal or 0) > 0 then
score = score + 8
end
if (snapshot.damageTaken or 0) <= 0 then
score = score + 4
end
return score
end
if context == Constants.CONTEXT.DUEL or context == Constants.CONTEXT.WORLD_PVP then
local score = 0
if (snapshot.damageTaken or 0) > 0 then
score = score + 8
end
if (snapshot.enemyDamageTaken or 0) > 0 then
score = score + 6
end
if (snapshot.healingDone or 0) > 0 then
score = score + 3
end
return score
end
if context == Constants.CONTEXT.ARENA or context == Constants.CONTEXT.BATTLEGROUND then
local score = 0
if (snapshot.damageDone or 0) > 0 then
score = score + 10
end
if (snapshot.damageTaken or 0) > 0 then
score = score + 8
end
if (snapshot.enemyDamageTaken or 0) > 0 then
score = score + 6
end
if countCombatSpells(snapshot.damageSpells) > 0 then
score = score + 4
end
if (snapshot.healingDone or 0) > 0 then
score = score + 3
end
return score
end
return 0
end
-- GetOpponentFitScore scores how well a Damage Meter candidate's enemy source
-- list matches the known opponent roster for the given session.
--
-- Scoring:
-- +28 Primary opponent GUID found in candidate's enemy sources
-- +10 Per additional overlapping GUID (capped at +30 total overlap credit)
-- -18 Candidate has enemy sources but zero GUID overlap (wrong session penalty)
-- +10 Arena: candidate source count exactly matches expected bracket size
-- +6 Arena: candidate source count is off by one from expected bracket size
-- +14 Duel: candidate has exactly one enemy source
-- -8 Duel: candidate has more than one enemy source
--
-- Returns 0 safely when both the GUID set and enemy sources are empty.
function DamageMeterService:GetOpponentFitScore(session, enemySources)
if not session then return 0 end
local sources = enemySources or {}
if #sources == 0 then return 0 end
local expectedGuids = collectExpectedOpponentGuids(session)
local primaryGuid = session.primaryOpponent and session.primaryOpponent.guid
-- Count how many expected GUIDs we actually have.
local expectedCount = 0
for _ in pairs(expectedGuids) do expectedCount = expectedCount + 1 end
-- When no expected GUIDs are available (e.g. arena secret values that were
-- sanitized to nil), skip the overlap penalty — the candidate can still be
-- ranked by duration, signal score, and source count.
if expectedCount == 0 and not primaryGuid then
if session.context == Constants.CONTEXT.ARENA or session.context == Constants.CONTEXT.BATTLEGROUND then
-- Give a small positive score for having enemy sources at all.
return #sources > 0 and 8 or 0
end
return 0
end
local score = 0
local overlapCount = 0
local primaryFound = false
for _, entry in ipairs(sources) do
local sourceGuid = entry.combatSource and entry.combatSource.sourceGUID
if sourceGuid then
if primaryGuid and sourceGuid == primaryGuid then
if not primaryFound then
score = score + 28
primaryFound = true
end
elseif expectedGuids[sourceGuid] then
overlapCount = overlapCount + 1
end
end
end
-- Per-overlap credit, capped at +30.
score = score + math.min(overlapCount * 10, 30)
-- Zero-overlap penalty: penalize candidates with sources but no GUID match.
local totalOverlap = (primaryFound and 1 or 0) + overlapCount
if totalOverlap == 0 then
score = score - 18
end
-- Context source-count fit.
local identity = session.identity or {}
local context = identity.kind or session.context
local sourceCount = #sources
if context == Constants.CONTEXT.ARENA then
local bracket = session.bracket or (session.arena and session.arena.bracket)
if bracket and bracket > 0 then
local delta = math.abs(sourceCount - bracket)
if delta == 0 then
score = score + 10
elseif delta == 1 then
score = score + 6
end
end
elseif context == Constants.CONTEXT.DUEL then
if sourceCount == 1 then
score = score + 14
elseif sourceCount > 1 then
score = score - 8
end
elseif context == Constants.CONTEXT.TRAINING_DUMMY then
if sourceCount == 1 then
score = score + 14
elseif sourceCount > 1 then
score = score - 8
end
end
ns.Addon:Trace("damage_meter.opponent_fit", {
expectedGuidCount = expectedCount,
candidateSourceCount = #sources,
overlapCount = (primaryFound and 1 or 0) + overlapCount,
score = score,
context = session.context or "unknown",
})
return score
end
function DamageMeterService:HandleCombatSessionUpdated(damageMeterType, sessionId)
if not sessionId or sessionId <= 0 then
return
end
self.latestUpdatedSessionIdByType = self.latestUpdatedSessionIdByType or {}
self.latestUpdatedSessionIdByType[damageMeterType] = math.max(self.latestUpdatedSessionIdByType[damageMeterType] or 0, sessionId)
self:RecordSessionUpdateSignal(damageMeterType, sessionId)
ns.Addon:Trace("damage_meter.session_updated", {
sessionId = sessionId,
type = damageMeterType or 0,
})
end
function DamageMeterService:HandleCurrentSessionUpdated()
ns.Addon:Trace("damage_meter.current_updated", {})
end
function DamageMeterService:HandleReset()
self.lastSeenSessionId = self:GetLatestSessionId() or 0
self.latestUpdatedSessionIdByType = {}
self.activeSessionBaselineId = nil
self.currentSessionSnapshot = nil
self.sessionUpdateSignals = {}
end
function DamageMeterService:FindSessionsForImport()
local sessions = self:GetAvailableSessions()
local baseline = self.activeSessionBaselineId or self.lastSeenSessionId or 0
local candidates = {}
local seen = {}
local sessionInfoById = {}
for _, sessionInfo in ipairs(sessions) do
sessionInfoById[sessionInfo.sessionID or 0] = sessionInfo
end
local function addCandidate(sessionInfoOrId)
local sessionInfo = sessionInfoOrId
if type(sessionInfoOrId) == "number" then
sessionInfo = sessionInfoById[sessionInfoOrId] or { sessionID = sessionInfoOrId }
end
local sessionId = sessionInfo and sessionInfo.sessionID or 0
if sessionId <= baseline or seen[sessionId] then
return
end
seen[sessionId] = true
candidates[#candidates + 1] = sessionInfo
end
addCandidate(self.latestUpdatedSessionIdByType and self.latestUpdatedSessionIdByType[Enum.DamageMeterType.DamageDone] or nil)
addCandidate(self.latestUpdatedSessionIdByType and self.latestUpdatedSessionIdByType[Enum.DamageMeterType.EnemyDamageTaken] or nil)
if self.sessionUpdateSignals then
for sessionId in pairs(self.sessionUpdateSignals) do
addCandidate(sessionId)
end
end
for _, sessionInfo in ipairs(sessions) do
addCandidate(sessionInfo)
end
-- Fallback 1: include the session AT the baseline. Training dummy and
-- short PvE encounters may update an existing C_DamageMeter session
-- in-place rather than creating a new one. Arena matches use
-- DamageMeterCombineSessionType.Arena which creates the combined session
-- during the prep/loading phase — BEFORE MarkSessionStart fires — so the
-- arena session ID equals the baseline and gets filtered out above.
if #candidates == 0 and baseline > 0 then
for _, sessionInfo in ipairs(sessions) do
local sessionId = sessionInfo and sessionInfo.sessionID or 0
if sessionId == baseline and not seen[sessionId] then
seen[sessionId] = true
candidates[#candidates + 1] = sessionInfo
end
end
end
-- Fallback 2: for arena/BG matches, also include the session immediately
-- below baseline (baseline - 1). The combined arena DM session may have
-- been created during the queue pop or loading screen, giving it an ID
-- lower than the baseline captured at the first PLAYER_REGEN_DISABLED.
if #candidates == 0 and baseline > 1 then
for _, sessionInfo in ipairs(sessions) do
local sessionId = sessionInfo and sessionInfo.sessionID or 0
if sessionId == (baseline - 1) and not seen[sessionId] then
seen[sessionId] = true
candidates[#candidates + 1] = sessionInfo
end
end
end
-- Fallback 3: if still no candidates, consider the latest available
-- session regardless of baseline (long prep phases, Solo Shuffle round
-- transitions). F3/B3: do not accept it blindly — when both the importing
-- session's duration and the candidate's duration are known, reject a
-- latest-session whose duration is wildly different (a different
-- encounter, e.g. a 200s arena imported into a 12s skirmish). Stay
-- permissive when a duration is unavailable so training-dummy / duel
-- imports do not regress.
if #candidates == 0 and #sessions > 0 then
local latest = sessions[#sessions]
if latest and not seen[latest.sessionID or 0] then
local fits = true
local expectedDuration = self._importSession and self._importSession.duration
local candidateDuration = tonumber(latest.durationSeconds) or 0
if expectedDuration and expectedDuration > 0 and candidateDuration > 0 then
if getDurationDelta(expectedDuration, candidateDuration) > 15 then
fits = false
end
end
if fits then
candidates[#candidates + 1] = latest
end
end
end
return sortSessionsByIdDesc(candidates)
end
function DamageMeterService:GetCurrentPlayerSource(damageMeterType)
local combatSession = ApiCompat.GetCombatSessionFromType(Enum.DamageMeterSessionType.Current, damageMeterType)
if not combatSession then
return nil, nil, nil
end
local playerGuid = ApiCompat.GetPlayerGUID()
local playerName = ApiCompat.GetPlayerName()
local combatSource = nil
for _, source in ipairs(combatSession.combatSources or {}) do
if source and (source.isLocalPlayer or (playerGuid and source.sourceGUID == playerGuid) or (playerName and source.name == playerName)) then
combatSource = source
break
end
end
local sessionSource = nil
if combatSource then
sessionSource = ApiCompat.GetCombatSessionSourceFromType(
Enum.DamageMeterSessionType.Current,
damageMeterType,
combatSource.sourceGUID,
combatSource.sourceCreatureID
)
end
if not sessionSource and combatSource and combatSource.isLocalPlayer then
sessionSource = ApiCompat.GetCombatSessionSourceFromType(Enum.DamageMeterSessionType.Current, damageMeterType, nil, nil)
end
if not sessionSource and combatSource then
sessionSource = {
combatSpells = {},
maxAmount = combatSource.totalAmount or 0,
totalAmount = combatSource.totalAmount or 0,
}
end
return sessionSource, combatSource, combatSession
end
-- CollectEnemyDamageSnapshotForCurrent returns three values:
-- 1. totalAmount (number)
-- 2. flatSpellList — merged across all sources (backward-compatible for callers
-- that only need a global spell breakdown)
-- 3. sources — per-source list for SpellAttributionPipeline; each entry
-- is { combatSource = ..., sessionSource = ... }
-- The flat spell list is kept to avoid breaking existing UI consumers.
function DamageMeterService:CollectEnemyDamageSnapshotForCurrent()
local combatSession = ApiCompat.GetCombatSessionFromType(Enum.DamageMeterSessionType.Current, Enum.DamageMeterType.EnemyDamageTaken)
if not combatSession then
return 0, {}, {}
end
local spellsById = {}
local sources = {}
for _, combatSource in ipairs(combatSession.combatSources or {}) do
local sessionSource = ApiCompat.GetCombatSessionSourceFromType(
Enum.DamageMeterSessionType.Current,
Enum.DamageMeterType.EnemyDamageTaken,
combatSource.sourceGUID,
combatSource.sourceCreatureID
)
-- Build the flat merged list (legacy path — merges within source scope
-- only, so each source's spells do not collide across sources).
local sourceSpellsById = {}
for _, combatSpell in ipairs(sessionSource and sessionSource.combatSpells or {}) do
mergeCombatSpell(sourceSpellsById, combatSpell)
mergeCombatSpell(spellsById, combatSpell)
end
sources[#sources + 1] = { combatSource = combatSource, sessionSource = sessionSource }
end
return combatSession.totalAmount or 0, buildMergedCombatSpellList(spellsById), sources
end
-- Same as above but for a historical session id.
function DamageMeterService:CollectEnemyDamageSnapshotForSession(sessionId)
local combatSession = ApiCompat.GetCombatSessionFromID(sessionId, Enum.DamageMeterType.EnemyDamageTaken)
if not combatSession then
return 0, {}, {}
end
local spellsById = {}
local sources = {}
for _, combatSource in ipairs(combatSession.combatSources or {}) do
local sessionSource = ApiCompat.GetCombatSessionSourceFromID(
sessionId,
Enum.DamageMeterType.EnemyDamageTaken,
combatSource.sourceGUID,
combatSource.sourceCreatureID
)
local sourceSpellsById = {}
for _, combatSpell in ipairs(sessionSource and sessionSource.combatSpells or {}) do
mergeCombatSpell(sourceSpellsById, combatSpell)
mergeCombatSpell(spellsById, combatSpell)
end
sources[#sources + 1] = { combatSource = combatSource, sessionSource = sessionSource }
end
return combatSession.totalAmount or 0, buildMergedCombatSpellList(spellsById), sources
end
-- T049: Collect Death Recap rows from C_DamageMeter for a given session.
function DamageMeterService:CollectDeathRecapSnapshot(sessionId)
if not HAS_DEATH_RECAP then
return nil
end
local ok, combatSession = pcall(ApiCompat.GetCombatSessionFromID, sessionId, Enum.DamageMeterType.DeathRecap)
if not ok or not combatSession then
return { available = false }
end
local rows = {}
for _, combatSource in ipairs(combatSession.combatSources or {}) do
local sourceOk, sessionSource = pcall(
ApiCompat.GetCombatSessionSourceFromID,
sessionId,
Enum.DamageMeterType.DeathRecap,
combatSource.sourceGUID,
combatSource.sourceCreatureID
)
for _, combatSpell in ipairs(sourceOk and sessionSource and sessionSource.combatSpells or {}) do
rows[#rows + 1] = {
spellId = combatSpell.spellID,
amount = combatSpell.totalAmount or 0,
sourceGuid = combatSource.sourceGUID,
sourceName = combatSource.name,
sourceClassFile = combatSource.classFilename,
}
end
end
if #rows == 0 then
return { available = false }
end
return { available = true, rows = rows }
end
function DamageMeterService:BuildSnapshotFromSources(session, payload)
local enemyDamageTaken = tonumber(payload.enemyDamageTaken) or 0
local snapshot = {
duration = tonumber(payload.duration) or (session and session.duration) or 0,
damageDone = tonumber(payload.damageDone) or 0,
healingDone = tonumber(payload.healingDone) or 0,
damageTaken = tonumber(payload.damageTaken) or 0,
absorbed = tonumber(payload.absorbed) or 0,
interrupts = tonumber(payload.interrupts) or 0,
dispels = tonumber(payload.dispels) or 0,
deaths = tonumber(payload.deaths) or 0,