-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathLibThreatClassic2.lua
1777 lines (1577 loc) · 57.4 KB
/
LibThreatClassic2.lua
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
--[[-----------------------------------------------------------------------------
Name: LibThreatClassic2
Revision: $Revision: 1$
Author(s): Dennis-Florian Herr (@dfherr)
Website: https://github.com/dfherr/LibThreatClassic2
Documentation: https://github.com/dfherr/LibThreatClassic2/wiki
Description: Tracks and communicates player and pet threat levels.
License: LGPL v2.1
Copyright (C) 2019 Dennis-Florian Herr
LibThreatClassic2 incorporates work covered by the following copyright and permission notice:
Copyright (C) 2019 Alexander Burt (Es / EsreverWoW)
Copyright (C) 2007 Chris Heald and the Threat-1.0/Threat-2.0 teams
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
-------------------------------------------------------------------------------]]
--[[-----------------------------------------------------------------------------
Name: ThreatClassic-1.0
Revision: $Revision: 10 $
Author(s): Es (EsreverWoW)
Website: https://github.com/EsreverWoW/LibThreatClassic
Documentation: https://github.com/EsreverWoW/LibThreatClassic/wiki
Description: Tracks and communicates player and pet threat levels.
License: LGPL v2.1
Copyright (C) 2019 Alexander Burt (Es / EsreverWoW)
ThreatClassic-1.0 incorporates work covered by the following copyright and permission notice:
Copyright (C) 2007 Chris Heald and the Threat-1.0/Threat-2.0 teams
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
-------------------------------------------------------------------------------]]
--[[-----------------------------------------------------------------------------
Name: Threat-2.0
Revision: $Revision: 7 $
Author(s): Antiarc (cheald at gmail)
Website: http://www.wowace.com/wiki/Threat-2.0
Documentation: http://www.wowace.com/wiki/Threat-2.0
SVN: http://svn.wowace.com/wowace/trunk/Threat-2.0/
Description: Tracks and communicates player and pet threat levels
License: LGPL v2.1
Copyright (C) 2007 Chris Heald and the Threat-1.0/Threat-2.0 teams
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
-------------------------------------------------------------------------------]]
-- Don't load if not WoW Classic
if _G.WOW_PROJECT_ID ~= _G.WOW_PROJECT_CLASSIC then return end
_G.THREATLIB_LOAD_MODULES = false -- don't load modules unless we update this file
local MAJOR, MINOR = "LibThreatClassic2", 12 -- Bump minor on changes, Major is constant lib identifier
assert(LibStub, MAJOR .. " requires LibStub")
-- if this version or a newer one is already installed, go no further
local __, minor = LibStub:GetLibrary(MAJOR, true)
if (minor and minor >= MINOR) then return end
-- Create ThreatLib as an AceAddon
local ThreatLib = LibStub("AceAddon-3.0"):GetAddon("LibThreatClassic2", true) or LibStub("AceAddon-3.0"):NewAddon("LibThreatClassic2")
-- embedd mixin libraries
LibStub("AceAddon-3.0"):EmbedLibraries(ThreatLib,
"AceComm-3.0",
"AceEvent-3.0",
"AceTimer-3.0",
"AceBucket-3.0",
"AceSerializer-3.0"
)
-- Manually inject ThreatLib into LibStub. similar to LibStub:NewLibrary but bypasses major == string assertion
LibStub.libs[MAJOR] = ThreatLib
LibStub.minors[MAJOR] = MINOR
_G.THREATLIB_LOAD_MODULES = true
-- Update this when backwards incompatible changes are made
local LAST_BACKWARDS_COMPATIBLE_REVISION = 2
local CBH = LibStub:GetLibrary("CallbackHandler-1.0")
ThreatLib.eventFrame = ThreatLib.eventFrame or CreateFrame("Frame")
ThreatLib.callbacks = ThreatLib.callbacks or CBH:New(ThreatLib, nil, nil, false)
ThreatLib.Classic = _G.WOW_PROJECT_ID == _G.WOW_PROJECT_CLASSIC
local _eventFrame = ThreatLib.frame
local _callbacks = ThreatLib.callbacks
local _G = _G
local error = _G.error
local floor, max, min = _G.math.floor, _G.math.max, _G.math.min
local tinsert, tremove, tconcat = _G.tinsert, _G.tremove, _G.table.concat
local table_sort = _G.table.sort
local tostring, tonumber, type = _G.tostring, _G.tonumber, _G.type
local string_gmatch = _G.string.gmatch
local UnitName = _G.UnitName
local UnitIsUnit = _G.UnitIsUnit
local UnitIsPlayer = _G.UnitIsPlayer
local setmetatable = _G.setmetatable
local GetRaidRosterInfo = _G.GetRaidRosterInfo
local GetNumGroupMembers = _G.GetNumGroupMembers
local UnitIsGroupLeader = _G.UnitIsGroupLeader
local GetInstanceInfo = _G.GetInstanceInfo
local IsInRaid = _G.IsInRaid
local select = _G.select
local next = _G.next
local pairs = _G.pairs
local strmatch = _G.string.match
local strsplit = _G.string.split
local strsub = _G.string.sub
local gsub, format = _G.string.gsub, _G.string.format
local InCombatLockdown = _G.InCombatLockdown
local IsInInstance = _G.IsInInstance
local IsResting = _G.IsResting
local UnitExists = _G.UnitExists
local IsInGuild = _G.IsInGuild
local GetTime = _G.GetTime
local UnitGUID = _G.UnitGUID
local UnitClass = _G.UnitClass
local UnitIsVisible = _G.UnitIsVisible
local CheckInteractDistance = _G.CheckInteractDistance
if not next(ThreatLib.modules) then
ThreatLib:SetDefaultModuleState(false)
end
ThreatLib.OnCommReceive = {}
ThreatLib.playerName = UnitName("player")
ThreatLib.partyMemberAgents = {}
ThreatLib.lastPublishedThreat = {player = {}, pet = {}}
ThreatLib.threatOffsets = {player = {}, pet = {}}
ThreatLib.publishInterval = nil
ThreatLib.lastPublishTime = 0
ThreatLib.dontPublishThreat = false
ThreatLib.partyMemberRevisions = {}
ThreatLib.threatTargets = {}
ThreatLib.latestSeenRevision = MINOR -- set later, to get the latest version of the whole lib
ThreatLib.isIncompatible = nil
ThreatLib.lastCompatible = LAST_BACKWARDS_COMPATIBLE_REVISION
ThreatLib.currentPartySize = 0
ThreatLib.latestSeenSender = nil
ThreatLib.partyUnits = {}
ThreatLib.GUIDNameLookup = setmetatable({}, { __index = function() return "<unknown>" end })
ThreatLib.threatLog = {}
local guidLookup = ThreatLib.GUIDNameLookup
local threatTargets = ThreatLib.threatTargets
local lastPublishedThreat = ThreatLib.lastPublishedThreat
local partyUnits = ThreatLib.partyUnits
local partyMemberAgents = ThreatLib.partyMemberAgents
local partyMemberRevisions = ThreatLib.partyMemberRevisions
local timers = {}
local inParty, inRaid = false, false
local lastPublishTime = ThreatLib.lastPublishTime
local new, del, newHash, newSet = ThreatLib.new, ThreatLib.del, ThreatLib.newHash, ThreatLib.newSet
-- For development
ThreatLib.DebugEnabled = false
ThreatLib.alwaysRunOnSolo = false
ThreatLib.LogThreat = false -- logs threat in ThreatLib.threatLog and enables ADD_THREAT debug
------------------------------------------------
-- Utility Functions
---------------------------------------------------------
local playerName = UnitName("player")
local tableCount, usedTableCount = 0, 0
-- #NODOC
function ThreatLib:Debug(msg, ...)
if self.DebugEnabled then
if _G.ChatFrame4 then
local a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p = ...
_G.ChatFrame4:AddMessage(("|cffffcc00ThreatLib-Debug: |r" .. msg):format(
tostring(a),
tostring(b),
tostring(c),
tostring(d),
tostring(e),
tostring(f),
tostring(g),
tostring(h),
tostring(i),
tostring(j),
tostring(k),
tostring(l),
tostring(m),
tostring(n),
tostring(o),
tostring(p)
))
else
_G.DEFAULT_CHAT_FRAME:AddMessage("|cffffcc00ThreatLib-Debug: |rPlease create ChatFrame4 for ThreatLib debug messages.")
end
end
end
ThreatLib:Debug("Loading modules revision %s", MINOR)
function ThreatLib:GroupDistribution()
if IsInGroup(LE_PARTY_CATEGORY_INSTANCE) then
return "INSTANCE_CHAT"
elseif GetNumGroupMembers() > 0 and IsInRaid() then
return "RAID"
else
return "PARTY"
end
end
function ThreatLib:toliteral(q)
if type(q) == "string" then
return ("%q"):format(q)
else
return tostring(q)
end
end
-- Table recycling
local new, newHash, newSet, del
do
local list = setmetatable({}, {__mode = 'k'})
function new(...)
usedTableCount = usedTableCount + 1
local t = next(list)
if t then
list[t] = nil
for i = 1, select('#', ...) do
t[i] = select(i, ...)
end
else
tableCount = tableCount + 1
t = {...}
end
return t
end
ThreatLib.new = new
function newHash(...)
usedTableCount = usedTableCount + 1
local t = next(list)
if t then
list[t] = nil
else
tableCount = tableCount + 1
t = {}
end
for i = 1, select('#', ...), 2 do
t[select(i, ...)] = select(i + 1, ...)
end
return t
end
ThreatLib.newHash = newHash
function newSet(...)
usedTableCount = usedTableCount + 1
local t = next(list)
if t then
list[t] = nil
else
tableCount = tableCount + 1
t = {}
end
for i = 1, select('#', ...) do
t[select(i, ...)] = true
end
return t
end
ThreatLib.newSet = newSet
function del(t)
usedTableCount = usedTableCount - 1
setmetatable(t, nil)
for k in pairs(t) do
t[k] = nil
end
t[''] = true
t[''] = nil
list[t] = true
return nil
end
ThreatLib.del = del
end
function ThreatLib:TableStats()
return usedTableCount, tableCount
end
function ThreatLib:IsGroupOfficer(unit)
if GetNumGroupMembers() == 0 then return unit == "player" end
if GetNumGroupMembers() > 0 and IsInRaid() then
for i = 1, GetNumGroupMembers() do
if UnitIsUnit("raid" .. i, unit) then
local _, rank = GetRaidRosterInfo(i)
if rank > 0 then
return true
end
end
end
elseif GetNumGroupMembers() > 0 then
if UnitIsGroupLeader("player") and unit == "player" then
return true
else
for i = 1, 4 do
if UnitIsGroupLeader("party" .. i) then
return UnitIsUnit(unit, "party" .. i)
end
end
end
end
return false
end
---------------------------------------------------------
-- Memoization
---------------------------------------------------------
ThreatLib.memoizations = ThreatLib.memoizations or {}
ThreatLib.reverse_memoizations = ThreatLib.reverse_memoizations or {}
local memoizations = ThreatLib.memoizations
local reverse_memoizations = ThreatLib.reverse_memoizations
function ThreatLib:RegisterMemoizations(t)
for k, v in pairs(t) do
memoizations[k] = v
reverse_memoizations[v] = k
end
end
function ThreatLib:Memoize(s)
if not memoizations[s] then
error(("Invalid memoization: %s"):format(s))
end
return memoizations[s]
end
function ThreatLib:Dememoize(b)
if not reverse_memoizations[b] then
error(("Invalid reverse memoization: %s"):format(b))
end
return reverse_memoizations[b]
end
function ThreatLib:OnCommReceived(prefix, message, distribution, sender)
if sender == playerName then return end
local isAce = strmatch(message, "^%^")
if not isAce then
local cmd, msg = strmatch(message, "^(..)(.*)$")
if msg then
local func = self.OnCommReceive[reverse_memoizations[cmd]]
if func then
func(self, sender, distribution, msg)
end
end
else
local success,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p = self:Deserialize(message)
if success then
self.OnCommReceive[reverse_memoizations[a]](self, sender, distribution, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p)
end
end
end
function ThreatLib:SendComm(distribution, command, ...)
self:SendCommMessage(self.prefix, self:Serialize(self:Memoize(command), ...), distribution)
end
function ThreatLib:SendCommRaw(distribution, command, data)
local str = self:Memoize(command) .. data
self:SendCommMessage(self.prefix, str, distribution)
end
function ThreatLib:SendCommWhisper(distribution, to, command, ...)
self:SendCommMessage(self.prefix, self:Serialize(self:Memoize(command), ...), distribution, to)
end
-- needs rework
local st = {}
function ThreatLib:SerializeThreatTable(pgid, t)
local l, nl = #st, 2
-- for i = 1, #st do tremove(st) end
st[1] = select(6, strsplit("-", pgid)) or select(3, strsplit("-", pgid))
st[2] = ":"
for k, v in pairs(t) do
nl = nl + 1
st[nl] = ("%s=%x,"):format(select(6, strsplit("-", k)) or select(3, strsplit("-", k)), v)
end
for i = nl + 1, l do
tremove(st)
end
return tconcat(st)
end
function ThreatLib:NPCID(guid)
if not guid or type(guid) ~= "string" then return end
local unitType, _, _, _, _, npcID = strsplit("-", guid)
if unitType ~= "Player" then
return tonumber(npcID)
end
end
function ThreatLib:Log(action, from, to, threat)
self.threatLog[from] = self.threatLog[from] or {}
local t = self.threatLog[from]
tinsert(t, GetTime())
tinsert(t, action)
tinsert(t, to)
tinsert(t, threat)
ThreatLib.callbacks:Fire(action, GetTime(), from, to, threat)
end
function ThreatLib:GetSpellID(spellName, unit, auraType)
-- get spellID from auras
if auraType and unit then
local spellId = nil
if auraType == AURA_TYPE_DEBUFF then
spellId = select(10, AuraUtil.FindAuraByName(spellName, unit, "HARMFUL"))
else
spellId = select(10, AuraUtil.FindAuraByName(spellName, unit))
end
if spellId then
return spellId
end
-- get spellID from cache/spellbook
end
-- eventually build a cache from UNIT_SPELLCAST_* events to track lower ranks
-- for now, we just assume max rank and get that spellID from the spellbook
return select(7, GetSpellInfo(spellName)) or 0
end
ThreatLib.prefix = "LTC2"
ThreatLib.userAgent = "LibThreatClassic2"
ThreatLib:RegisterMemoizations({
CLIENT_INFO = "CI",
LEFT_COMBAT = "LC",
MISDIRECT_THREAT = "MT",
RAID_MOB_THREAT_WIPE = "MW",
REQUEST_CLIENT_INFO = "RI",
THREAT_UPDATE = "TU",
WIPE_ALL_THREAT = "WT",
ACTIVATE_NPC_MODULE = "AM",
SET_NPC_MODULE_VALUE = "SV"
})
ThreatLib.WowVersion, ThreatLib.WowMajor, ThreatLib.WowMinor = strsplit(".", tostring(GetBuildInfo()))
ThreatLib.WowVersion, ThreatLib.WowMajor, ThreatLib.WowMinor = tonumber(ThreatLib.WowVersion), tonumber(ThreatLib.WowMajor), tonumber(ThreatLib.WowMinor)
ThreatLib.inCombat = InCombatLockdown
---------------------------------------------------------
-- NPC ID Blacklist
---------------------------------------------------------
--[[
NPC IDs to completely ignore all threat calculations on, in decimal.
This should be things like Crypt Scarabs, which do not have a death message after kamikaze-ing, or
other very-low-HP enemies that zerg players and for whom threat data is not important.
The reason for this is to eliminate unnecessary comms traffic gluts when these enemies are spawned, or to
prevent getting enemies that despawn (and not die) from getting "stuck" in the threat list for the duration
of the fight.
]]--
ThreatLib.BLACKLIST_MOB_IDS = {
[17967] = true, -- Crypt Scarabs, used by Crypt Fiends in Hyjal
[10577] = true, -- More scarabs
-- AQ40
[15630] = true, -- Spawn of Fankriss
-- BWL
[14022] = true, -- Corrupted Red Whelp
[14023] = true, -- Corrupted Green Whelp
[14024] = true, -- Corrupted Blue Whelp
[14025] = true, -- Corrupted Bronze Whelp
[14605] = true, -- Bone Construct
[14261] = true, -- Blue Drakonid
[14262] = true, -- Green Drakonid
[14263] = true, -- Bronze Drakonid
[14264] = true, -- Red Drakonid
[14265] = true, -- Black Drakonid
[14662] = true, -- Corrupted Fire Nova Totem
[14663] = true, -- Corrupted Stoneskin Totem
[14664] = true, -- Corrupted Healing Stream Totem
[14666] = true, -- Corrupted Winfury Totem
[14668] = true, -- Corrupted Infernal
-- Strathholme
[11197] = true, -- Mindless Skeleton
[11030] = true, -- Mindless Zombie
[10461] = true, -- Plagued Insect
[10536] = true, -- Plagued Maggot
[10441] = true, -- Plagued Rat
[10876] = true, -- Undead Scarab
-- World
[19833] = true, -- Snake Trap snakes
[19921] = true, -- Snake Trap snakes
-- [22144] = true, -- Test, comment out for production
}
function ThreatLib:IsMobBlacklisted(guid)
return ThreatLib.BLACKLIST_MOB_IDS[ThreatLib:NPCID(guid)] == true
end
---------------------------------------------------------
-- Threat Per Second (TPS)
---------------------------------------------------------
function ThreatLib:CancelTPSReset()
if timers.ResetTPSTimerTables ~= nil then self:CancelTimer(timers.ResetTPSTimerTables, true) end
if timers.ResetThreat ~= nil then self:CancelTimer(timers.ResetThreat, true) end
end
function ThreatLib:ScheduleTPSReset()
timers.ResetTPSTimerTables = self:ScheduleTimer("ResetTPS", 3)
timers.ResetThreat = self:ScheduleTimer("_clearAllThreat", 5)
end
ThreatLib.tpsSigma = ThreatLib.tpsSigma or {}
ThreatLib.tpsSamples = ThreatLib.tpsSamples or 25
local tpsSigma = ThreatLib.tpsSigma
local tpsSamples = ThreatLib.tpsSamples
function ThreatLib:UpdateTPS(source_guid, target_guid, targetThreat)
if not source_guid then
error("Invalid parameter #1 passed to UpdateTPS: expected string, got nil", 2)
end
if not target_guid then
error("Invalid parameter #2 passed to UpdateTPS: expected string, got nil", 2)
end
if not targetThreat then
error("Invalid parameter #3 passed to UpdateTPS: expected number, got nil", 2)
end
local playerTable = tpsSigma[source_guid]
if not playerTable then
playerTable = {}
tpsSigma[source_guid] = playerTable
playerTable["FIGHT_START"] = GetTime()
end
local sigma = playerTable[target_guid]
if not sigma then
-- average, last threat, avg sum, sample 1, sample time 1, ..., sample n, sample time n
sigma = {targetThreat, targetThreat, 0}
playerTable[target_guid] = sigma
end
local removedVal, removedTime, period, delta, total, tt = 0, nil, nil, targetThreat - sigma[2], 0, GetTime()
if targetThreat - sigma[2] == 0 then return end
tinsert(sigma, delta)
tinsert(sigma, tt)
local nPoints = (#sigma - 3) / 2
while nPoints >= tpsSamples do
removedVal = tremove(sigma, 4)
removedTime = tremove(sigma, 4)
sigma[3] = sigma[3] - removedVal
nPoints = (#sigma - 3) / 2
end
sigma[3] = sigma[3] + delta
period = tt - (removedTime or sigma[5])
period = period == 0 and 1 or period
sigma[1] = sigma[3] / period
sigma[2] = targetThreat
end
--[[----------------------------------------------------------
-- Returns:
-- The current number of threat samples used to calculate TPS
------------------------------------------------------------]]
function ThreatLib:GetTPSSamples()
return ThreatLib.tpsSamples
end
--[[----------------------------------------------------------
Arguments:
integer - number of threat events to consider for TPS calculations
Notes:
Default is 15
A larger sample size will produce a TPS reading for a longer slice of combat, which means that it'll be more stable, but won't reflect your TPS-at-the-moment as accurately.
------------------------------------------------------------]]
function ThreatLib:SetTPSSamples(samples)
ThreatLib.tpsSamples = tonumber(samples)
end
function ThreatLib:ResetPlayerTPSOnTarget(player, target)
local t = tpsSigma[player]
if t then
local tt = t[target]
if tt then
t[target] = nil
end
end
end
function ThreatLib:ResetTPS(resetOn, force)
if self.inCombat() and not force then return end
for k, v in pairs(tpsSigma) do
for k2, v2 in pairs(v) do
if resetOn then
if k2 == resetOn and type(v2) == "table" then
v[k2] = nil
v2 = nil
end
else
if type(v2) == "table" then
v[k2] = nil
v2 = nil
end
end
end
v["FIGHT_START"] = GetTime()
if not resetOn then
tpsSigma[k] = nil
v = nil
end
end
end
-------------------------------------------------------
-- Arguments:
-- string - name of the player to get TPS for
-- string - name of the target to get TPS on
-- Returns:
-- * Local TPS (float)
-- * Encounter TPS (float)
-------------------------------------------------------
function ThreatLib:GetTPS(source_guid, target_guid)
local pSigma = tpsSigma[source_guid]
if not pSigma then return 0, 0 end
-- self:Debug("Target is global: %s (%s, %s)", target == PUBLIC_GLOBAL_HASH, target, PUBLIC_GLOBAL_HASH)
local tt = GetTime()
local tTPS = pSigma[target_guid]
local td, ftd = 0, 0
if tTPS then
local ttd = tt - tTPS[#tTPS]
td = tTPS[1] * max(0, 1 - (ttd / 10))
ftd = tTPS[2] / (tt - pSigma["FIGHT_START"])
end
return td, ftd
end
---------------------------------------------------------
-- Boot
---------------------------------------------------------
local initialized = false -- hack for upgrading, is local so that each upgrade of the lib runs this
function ThreatLib:OnInitialize()
self:UnregisterAllComm()
self:RegisterComm(self.prefix)
-- self.latestSeenRevision = select(2, LibStub("LibThreatClassic2"))
-- MINOR = self.latestSeenRevision
initialized = true
end
function ThreatLib:OnEnable()
if not initialized then self:OnInitialize() end
ThreatLib:Debug("Enabling LibThreatClassic module revision %s", MINOR)
self:UnregisterAllEvents()
self:RegisterEvent("PLAYER_REGEN_DISABLED")
self:RegisterEvent("PLAYER_REGEN_ENABLED")
self:RegisterEvent("PLAYER_ENTERING_WORLD")
self:RegisterEvent("PLAYER_UPDATE_RESTING", "PLAYER_ENTERING_WORLD")
self:RegisterEvent("PLAYER_ALIVE")
self:RegisterEvent("PLAYER_LOGIN")
-- disable all modules including old revision for full reboot
for k in pairs(self.modules) do
self:DisableModule(k)
end
-- (re)boot the NPC core
self:EnableModule("NPCCore-r"..MINOR)
-- Do event registrations here, as a Blizzard bug seems to be causing lockups if these are registered too early
self:RegisterEvent("GROUP_ROSTER_UPDATE")
self:RegisterEvent("UNIT_PET")
self:RegisterEvent("UNIT_NAME_UPDATE", "GROUP_ROSTER_UPDATE")
self:RegisterEvent("PLAYER_LOGIN", "GROUP_ROSTER_UPDATE")
self:GROUP_ROSTER_UPDATE()
self:PLAYER_ENTERING_WORLD()
self:SendComm(self:GroupDistribution(), "REQUEST_CLIENT_INFO", MINOR, self.userAgent, LAST_BACKWARDS_COMPATIBLE_REVISION)
if IsInGuild() then
self:SendComm("GUILD", "REQUEST_CLIENT_INFO", MINOR, self.userAgent, LAST_BACKWARDS_COMPATIBLE_REVISION)
end
end
------------------------------------------------------------------------
-- Handled Events
------------------------------------------------------------------------
function ThreatLib:PLAYER_ENTERING_WORLD(force)
if UnitGUID("player") then
guidLookup[UnitGUID("player")] = UnitName("player")
end
local previousRunning = self.running
local inInstance, kind = IsInInstance()
local instance_id = select(8, GetInstanceInfo())
local ALTERAC_VALLEY_INSTANCE_ID = 30
if inInstance and (kind == "pvp" or kind == "arena") and instance_id ~= ALTERAC_VALLEY_INSTANCE_ID then
-- in a battleground that is not AV.
self:Debug("Disabling, in a PVP instance")
self.running = false
elseif IsResting() then
-- in a city/inn
self:Debug("Disabling, resting")
self.running = false
elseif not self.alwaysRunOnSolo and not UnitExists("pet") and GetNumGroupMembers() == 0 then
-- all alone
self:Debug("Disabling, so lonely :'(")
self.running = false
else
self:Debug("Activating revision %s... self.alwaysRunOnSolo: %s", MINOR, self.alwaysRunOnSolo)
self.running = true
end
if previousRunning ~= self.running or force then
self:Debug("Dispatching event...")
if self.running then
_callbacks:Fire("Activate")
self:EnableModule("Player-r"..MINOR)
if UnitExists("pet") then
self:EnableModule("Pet-r"..MINOR)
end
else
_callbacks:Fire("Deactivate")
self:DisableModule("Player-r"..MINOR)
self:DisableModule("Pet-r"..MINOR)
end
end
end
function ThreatLib:PLAYER_LOGIN()
self:DisableModule("Player-r"..MINOR)
self:DisableModule("Pet-r"..MINOR)
self:PLAYER_ENTERING_WORLD(true)
end
function ThreatLib:PLAYER_ALIVE()
if not self.booted then
self:DisableModule("Player-r"..MINOR)
self:DisableModule("Pet-r"..MINOR)
self.booted = true
self:PLAYER_ENTERING_WORLD(true)
end
end
function ThreatLib:PLAYER_REGEN_DISABLED()
self.publishInterval = self:GetPublishInterval()
-- self.inCombat = true
self:CancelTPSReset()
end
function ThreatLib:PLAYER_REGEN_ENABLED()
-- self.inCombat = false
self:ScheduleTPSReset()
end
-- #NODOC
function ThreatLib:ThreatUpdated(source_unit, target_guid, threat)
self:ThreatUpdatedForUnit(source_unit, target_guid, threat)
local t = GetTime()
if not self.publishInterval then
self.publishInterval = self:GetPublishInterval()
end
if t - lastPublishTime > self.publishInterval then
self:PublishThreat()
end
end
-- #NODOC
function ThreatLib:ThreatUpdatedForUnit(unit_id, target_guid, threat)
if type(unit_id) ~= "string" then
error(("Assertion failed: type(%s --[[unit_id]]) == %q, trace: %s"):format(self:toliteral(unit_id), "string", debugstack()))
end
if threat then
self:UpdateTPS(unit_id, target_guid, threat)
self:_setThreat(unit_id, target_guid, threat)
_callbacks:Fire("ThreatUpdated", unit_id, target_guid, threat)
end
end
-- #NODOC
function ThreatLib:UpdateParty()
for k in pairs(partyUnits) do
partyUnits[k] = nil
end
self.currentPartySize = self.currentPartySize or 0
local sizeBeforeUpdate = self.currentPartySize
local numRaid = IsInRaid() and GetNumGroupMembers() or 0
if numRaid > 0 then
inRaid = true
inParty = true
self.currentPartySize = numRaid
else
inRaid = false
local numParty = GetNumGroupMembers()
if numParty > 0 then
inParty = true
self.currentPartySize = numParty
else
inParty = false
self.currentPartySize = 0
end
end
self:Debug("currentPartySize: %s, sizeBeforeUpdate: %s", self.currentPartySize, sizeBeforeUpdate)
if self.currentPartySize > sizeBeforeUpdate and self.currentPartySize > 0 then
self:PublishVersion(self:GroupDistribution())
self:UpdatePartyGUIDs()
end
_callbacks:Fire("PartyChanged")
self:PLAYER_ENTERING_WORLD()
end
function ThreatLib:UpdatePartyGUIDs()
if not inRaid and not inParty then return end
local playerFmt = inRaid and "raid%d" or "party%d"
local petFmt = inRaid and "raidpet%d" or "partypet%d"
for i = 1, self.currentPartySize, 1 do
local unitID = format(playerFmt, i)
local pGUID = UnitGUID(unitID)
if pGUID then
guidLookup[pGUID] = UnitName(unitID)
-- lookup pet (if existing)
local petID = format(petFmt, i)
local petGUID = UnitGUID(petID)
if petGUID then
guidLookup[petGUID] = UnitName(petID)
end
end
end
end
function ThreatLib:UNIT_PET(event, unit)
if unit ~= "player" then return end
local exists = UnitExists("pet")
if exists and self.running then
self:DisableModule("Pet-r"..MINOR)
self:EnableModule("Pet-r"..MINOR)
else
self:DisableModule("Pet-r"..MINOR)
end
self:GROUP_ROSTER_UPDATE() --- Does gaining or losing a pet already fire this? Is this needed?
end
function ThreatLib:GROUP_ROSTER_UPDATE()
if timers.UpdateParty then
self:CancelTimer(timers.UpdateParty, true)
timers.UpdateParty = nil
end
timers.UpdateParty = self:ScheduleTimer("UpdateParty", 1.0)
end
------------------------------------------------------------------------
-- Handled Chat Messages
------------------------------------------------------------------------
local BLACKLIST_MOB_IDS = ThreatLib.BLACKLIST_MOB_IDS or {}
function ThreatLib.OnCommReceive:THREAT_UPDATE(sender, distribution, msg)
if not msg then return end
local unitGUID, threatUpdates = strsplit(":", msg)
if unitGUID then
for targetGUID, threatUpdate in string_gmatch(threatUpdates, "([^=:]+)=(%d+),") do
if targetGUID and threatUpdate then
self:ThreatUpdatedForUnit(unitGUID, targetGUID, tonumber(threatUpdate))
end
end
end
end
function ThreatLib.OnCommReceive:LEFT_COMBAT(sender, distribution, playerLeft, petLeft)
local sGUID = UnitGUID(sender)
if playerLeft and sGUID then
self:_clearThreat(sGUID)
end
if petLeft then
local pGUID = UnitGUID(sender .. "-pet")
if pGUID then
self:_clearThreat(pGUID)
end
end
end
do
local function wipeAllThreatFunc(self)
self:GetModule("Player-r"..MINOR):MultiplyThreat(0)
local petModule = self:GetModule("Pet-r"..MINOR)
if petModule:IsEnabled() then
petModule:MultiplyThreat(0)
end
self:ResetTPS(nil, true)
self:ClearStoredThreatTables()
_callbacks:Fire("ThreatCleared")
self:PublishThreat(true)
timers.ThreatWipe = nil
end
local lastWipe = 0
function ThreatLib.OnCommReceive:WIPE_ALL_THREAT(sender)
if self:IsGroupOfficer(sender) or UnitIsUnit(sender, "player") then
if GetTime() - lastWipe > 10 then
lastWipe = GetTime()
timers.ThreatWipe = self:ScheduleTimer(wipeAllThreatFunc, 0.35, self)
end
end
end
end
local cooldownTimes = {}
local function mobThreatWipeFunc(self, mob_id)
local IDs = self:GetModule("Player-r"..MINOR):GetGUIDsByNPCID(mob_id)
for i = 1, #IDs do
local id = IDs[i]
self:GetModule("Player-r"..MINOR):SetTargetThreat(id, 0)
self:ResetTPS(id, true)
self:ClearStoredThreatTables(id)
end
if UnitExists("pet") then
local IDs = self:GetModule("Pet-r"..MINOR):GetGUIDsByNPCID(mob_id)
for i = 1, #IDs do
local id = IDs[i]
self:GetModule("Pet-r"..MINOR):SetTargetThreat(id, 0)
self:ResetTPS(id, true)
self:ClearStoredThreatTables(id)
end
end
self:PublishThreat(true)
end
function ThreatLib.OnCommReceive:RAID_MOB_THREAT_WIPE(sender, distribution, mob_guid)
if BLACKLIST_MOB_IDS[ThreatLib:NPCID(mob_guid)] then return end
if GetTime() - (cooldownTimes[mob_guid] or 0) > 10 then
cooldownTimes[mob_guid] = GetTime()
mobThreatWipeFunc(ThreatLib, mob_guid) -- self:ScheduleTimer(mobThreatWipeFunc, 0.5, mob_guid)
end
end
function ThreatLib:ClearStoredThreatTables(mob_guid)
for k, v in pairs(threatTargets) do
for k2, v2 in pairs(v) do
if not mob_guid or mob_guid == k2 then
v[k2] = nil
end
end
end
end
function ThreatLib.OnCommReceive:MISDIRECT_THREAT(sender, distribution, target_player_guid, target_enemy_guid, amount)
if BLACKLIST_MOB_IDS[ThreatLib:NPCID(target_enemy_guid)] then return end
ThreatLib:Debug("Got misdirect from %s: give %s threat to %s on mob %s", sender, amount, target_player_guid, target_enemy_guid)
if select(2, UnitClass(sender)) ~= "HUNTER" then return end
ThreatLib:Debug("%s is a hunter, continuing", sender)