-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathCore.lua
More file actions
1057 lines (903 loc) · 32.8 KB
/
Core.lua
File metadata and controls
1057 lines (903 loc) · 32.8 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
---------------------------------------------------------------------------------------
-- CORE LOGIC --
---------------------------------------------------------------------------------------
-- IMPORTS
local _G = _G
local AceAddon = _G.LibStub("AceAddon-3.0")
local AceDB = _G.LibStub("AceDB-3.0")
local AceConfig = _G.LibStub("AceConfig-3.0")
local AceConfigDialog = _G.LibStub("AceConfigDialog-3.0")
local AceConfigCmd = _G.LibStub("AceConfigCmd-3.0")
-- Check if running on Retail or Classic
local ON_RETAIL_CLIENT = (_G.WOW_PROJECT_ID == _G.WOW_PROJECT_MAINLINE)
-- CACHING GLOBAL VARIABLES
-- Slightly better performance than doing a global lookup every time
local CreateFrame = _G.CreateFrame
local CreateMacro = _G.CreateMacro
local DisableAddOn = _G.C_AddOns.DisableAddOn
local GetAddOnMetadata = _G.C_AddOns.GetAddOnMetadata
local GetPlayerAuraBySpellID = _G.C_UnitAuras.GetPlayerAuraBySpellID
local GameTooltip = _G.GameTooltip
local GetBindingKey = _G.GetBindingKey
local GetCurrentBindingSet = _G.GetCurrentBindingSet
local GetCursorPosition = _G.GetCursorPosition
local GetMacroInfo = _G.GetMacroInfo
local GetTime = _G.GetTime
local GetUIPanel = _G.GetUIPanel
local InCinematic = _G.InCinematic
local IsInCinematicScene = _G.IsInCinematicScene
local InCombatLockdown = _G.InCombatLockdown
local IsMounted = _G.IsMounted
local IsMouseButtonDown = _G.IsMouseButtonDown
local IsMouselooking = _G.IsMouselooking
local loadstring = _G.loadstring
local MouselookStart = _G.MouselookStart
local MouselookStop = _G.MouselookStop
local OpenToCategory = _G.Settings.OpenToCategory
local pcall = _G.pcall
local ReloadUI = _G.ReloadUI
local SaveBindings = _G.SaveBindings
local SetBinding = _G.SetBinding
local SetCVar = _G.C_CVar.SetCVar
local SetModifiedClick = _G.SetModifiedClick
local SetMouselookOverrideBinding = _G.SetMouselookOverrideBinding
local SpellIsTargeting = _G.SpellIsTargeting
local StaticPopupDialogs = _G.StaticPopupDialogs
local StaticPopup_Show = _G.StaticPopup_Show
local UIParent = _G.UIParent
local UnitAffectingCombat = _G.UnitAffectingCombat
local UnitCanAttack = _G.UnitCanAttack
local UnitExists = _G.UnitExists
local UnitGUID = _G.UnitGUID
local UnitIsGameObject = _G.UnitIsGameObject
local UnitReaction = _G.UnitReaction
local UnitIsPlayer = _G.UnitIsPlayer
local unpack = _G.unpack
-- INSTANTIATING ADDON & ENCAPSULATING NAMESPACE
local CM = AceAddon:NewAddon("CombatMode", "AceConsole-3.0", "AceEvent-3.0")
_G["CM"] = CM
-- INITIAL STATE VARIABLES
--[[
Changes when Free Look state is modified through user input
("Toggle" or "Press & Hold" keybinds and "/cm" cmd)
]] --
local FreeLookOverride = false
---------------------------------------------------------------------------------------
-- UTILITY FUNCTIONS --
---------------------------------------------------------------------------------------
local function FetchDataFromTOC()
local dataRetuned = {}
local keysToFetch = {
"Version",
"Title",
"Notes",
"Author",
"X-Discord",
"X-Curse",
"X-Contributors"
}
for _, key in ipairs(keysToFetch) do
dataRetuned[string.upper(key)] = GetAddOnMetadata("CombatMode", key)
end
return dataRetuned
end
CM.METADATA = FetchDataFromTOC()
function CM.DebugPrint(statement)
if CM.DB.global.debugMode then
print(CM.Constants.BasePrintMsg .. "|cff909090: " .. tostring(statement) .. "|r")
end
end
local LAST_PRINT_TIME = 0
local function PreventDebugSpam(msg)
local currentTime = GetTime()
if currentTime - LAST_PRINT_TIME > 3 then
CM.DebugPrint(msg)
LAST_PRINT_TIME = currentTime
end
end
local function OpenConfigPanel()
if InCombatLockdown() then
print(CM.Constants.BasePrintMsg .. "|cff909090: Cannot open settings while in combat.|r")
return
end
OpenToCategory(CM.METADATA["TITLE"])
end
local function UndoCMChanges()
if InCombatLockdown() then
print(CM.Constants.BasePrintMsg .. "|cff909090: Cannot run this cmd while in combat.|r")
return
end
CM:ResetCVarsToDefault()
DisableAddOn("CombatMode")
ReloadUI()
end
local function DisplayPopup()
if CM.DB.char.seenWarning then
return
end
local function OnClosePopup()
CM.DB.char.seenWarning = true
OpenConfigPanel()
end
StaticPopupDialogs["CombatMode Warning"] = {
text = CM.Constants.PopupMsg,
button1 = "Ok",
OnButton1 = OnClosePopup,
OnHide = OnClosePopup,
timeout = 0,
whileDead = true
}
StaticPopup_Show("CombatMode Warning")
end
function CM.MacroExists(name)
return GetMacroInfo(name) ~= nil
end
local function CreateTargetMacros()
local function createMacroIfNotExists(macroName, icon, macroText)
if not CM.MacroExists(macroName) then
CreateMacro(macroName, icon, macroText, false)
end
end
local macroIcon = "ability_hisek_aim"
for macroName, macroText in pairs(CM.Constants.Macros) do
createMacroIfNotExists(macroName, macroIcon, macroText)
end
end
-- This prevents the auto running bug.
local function IsDefaultMouseActionBeingUsed()
return IsMouseButtonDown("LeftButton") or IsMouseButtonDown("RightButton")
end
local tooltipHidden = false
local isTooltipHooked = false
local function HideTooltip(shouldHide)
tooltipHidden = shouldHide
if not isTooltipHooked then
GameTooltip:HookScript("OnShow", function(self)
if tooltipHidden then
self:Hide()
end
end)
isTooltipHooked = true
end
-- Hide it immediately in case there's a tooltip still fading while mouse locking
if tooltipHidden and GameTooltip:IsShown() then
GameTooltip:Hide()
end
end
--[[
Checking if DynamicCam is loaded so we can relinquish control of a few camera features
as DynamicCam allows fine-grained control of Mouselook Speed & Target Focus
]] --
local function IsDCLoaded()
local DC = AceAddon:GetAddon("DynamicCam", true)
CM.DynamicCam = DC ~= nil and true or false
if CM.DynamicCam and not CM.DB.global.silenceAlerts then
print(CM.Constants.BasePrintMsg ..
"|cff909090: |cffE52B50DynamicCam detected!|r Handing over control of |cffE37527• Camera Features|r.|r")
end
end
---------------------------------------------------------------------------------------
-- CVAR HANDLING FUNCTIONS --
---------------------------------------------------------------------------------------
local function LoadCVars(info)
local CVarType, CMValues, BlizzValues, FeatureName = info.CVarType, info.CMValues, info.BlizzValues, info.FeatureName
local CVarsToLoad
if CVarType == "combatmode" then
CVarsToLoad = CMValues
CM.DebugPrint(FeatureName .. " CVars LOADED")
elseif CVarType == "blizzard" then
CVarsToLoad = BlizzValues
CM.DebugPrint(FeatureName .. " CVars RESET")
else
CM.DebugPrint("Invalid CVarType specified in fn CM.ConfigCVars() for " .. FeatureName .. ": " .. tostring(CVarType))
return
end
for name, value in pairs(CVarsToLoad) do
SetCVar(name, value)
end
end
function CM.ConfigReticleTargeting(CVarType)
local info = {
CVarType = CVarType,
CMValues = CM.Constants.ReticleTargetingCVarValues,
BlizzValues = CM.Constants.BlizzardReticleTargetingCVarValues,
FeatureName = "Reticle Targeting"
}
LoadCVars(info)
end
function CM.ConfigActionCamera(CVarType)
if CM.DynamicCam then
return
end
local info = {
CVarType = CVarType,
CMValues = CM.Constants.ActionCameraCVarValues,
BlizzValues = CM.Constants.BlizzardActionCameraCVarValues,
FeatureName = "Action Camera"
}
LoadCVars(info)
if CVarType == "combatmode" then
CM.SetShoulderOffset()
end
-- Disable the Action Cam warning message.
UIParent:UnregisterEvent("EXPERIMENTAL_CVAR_CONFIRMATION_NEEDED")
end
function CM.ConfigStickyCrosshair(CVarType)
if CM.DynamicCam then
return
end
local info = {
CVarType = CVarType,
CMValues = CM.Constants.TagetFocusCVarValues,
BlizzValues = CM.Constants.BlizzardTagetFocusCVarValues,
FeatureName = "Sticky Crosshair"
}
LoadCVars(info)
end
function CM.SetMouseLookSpeed()
if CM.DynamicCam then
return
end
local XSpeed = CM.DB.global.mouseLookSpeed
local YSpeed = CM.DB.global.mouseLookSpeed / 2 -- Blizz wants pitch speed as 1/2 of yaw speed
SetCVar("cameraYawMoveSpeed", XSpeed)
SetCVar("cameraPitchMoveSpeed", YSpeed)
CM.DebugPrint("Setting Camera Turn Speed X to " .. XSpeed .. " and Y to " .. YSpeed)
end
function CM.SetShoulderOffset()
if CM.DynamicCam then
return
end
local offset = CM.DB.char.shoulderOffset
SetCVar("test_cameraOverShoulder", offset)
CM.DebugPrint("Setting Shoulder Offset to " .. offset)
end
function CM.SetCrosshairPriority(enabled)
if ON_RETAIL_CLIENT == false then
return
end
if enabled then
SetCVar("enableMouseoverCast", 1)
SetModifiedClick("MOUSEOVERCAST", "NONE")
SaveBindings(GetCurrentBindingSet())
CM.DebugPrint("Enabling Crosshair Priority")
else
SetCVar("enableMouseoverCast", 0)
CM.DebugPrint("Disabling Crosshair Priority")
end
end
function CM.SetFriendlyTargeting(enabled)
if enabled then
SetCVar("SoftTargetFriend", 3)
CM.DebugPrint("Enabling Friendly Targeting out of combat")
else
SetCVar("SoftTargetFriend", 0)
CM.DebugPrint("Disabling Friendly Targeting in combat")
end
end
-- Temporarily disable friendly targeting during combat
local function HandleFriendlyTargetingInCombat()
local CharConfig = CM.DB.char or {}
local isFriendlyTargetingInCombatOn = CharConfig.reticleTargeting and CharConfig.friendlyTargeting and
CharConfig.friendlyTargetingInCombat
if not isFriendlyTargetingInCombatOn then
return
end
local InCombat = UnitAffectingCombat("player")
if InCombat then
CM.SetFriendlyTargeting(false)
else
CM.SetFriendlyTargeting(true)
end
end
local function CenterCursor(shouldCenter)
if shouldCenter then
SetCVar("CursorFreelookCentering", 1)
CM.DebugPrint("Locking cursor to crosshair position.")
else
SetCVar("CursorFreelookCentering", 0)
CM.DebugPrint("Freeing cursor from crosshair position.")
end
end
function CM:ResetCVarsToDefault()
self.ConfigReticleTargeting("blizzard")
self.ConfigActionCamera("blizzard")
self.ConfigStickyCrosshair("blizzard")
self.SetCrosshairPriority(false)
self.SetFriendlyTargeting(false)
print(CM.Constants.BasePrintMsg .. "|cff909090: all changes have been reverted.|r")
end
---------------------------------------------------------------------------------------
-- CROSSHAIR HANDLING FUNCTIONS --
---------------------------------------------------------------------------------------
-- SETTING UP CROSSHAIR FRAME & ANIMATION
local CrosshairFrame = CreateFrame("Frame", "CombatModeCrosshairFrame", UIParent)
local CrosshairTexture = CrosshairFrame:CreateTexture(nil, "OVERLAY")
local CrosshairAnimation = CrosshairFrame:CreateAnimationGroup()
local ScaleAnimation = CrosshairAnimation:CreateAnimation("Scale")
local STARTING_SCALE = 1
local ENDING_SCALE = 0.9
local SCALE_DURATION = 0.15
ScaleAnimation:SetDuration(SCALE_DURATION)
ScaleAnimation:SetScaleFrom(STARTING_SCALE, STARTING_SCALE)
ScaleAnimation:SetScaleTo(ENDING_SCALE, ENDING_SCALE)
ScaleAnimation:SetSmoothProgress(SCALE_DURATION)
ScaleAnimation:SetSmoothing("IN_OUT")
local function HideCrosshairWhileMounted()
return CM.DB.global.crosshairMounted and IsMounted()
end
local function SetCrosshairAppearance(state)
local CrosshairAppearance = CM.DB.global.crosshairAppearance
local crosshairYPos = CM.DB.global.crosshairY
local r, g, b, a = unpack(CM.Constants.CrosshairReactionColors[state])
local textureToUse = state == "base" and CrosshairAppearance.Base or CrosshairAppearance.Active
local reverseAnimation = state == "base" and true or false
-- Sets new scale at the end of animation
CrosshairAnimation:SetScript("OnFinished", function()
if state ~= "base" then
CrosshairFrame:SetScale(ENDING_SCALE)
CrosshairFrame:SetPoint("CENTER", 0, crosshairYPos / ENDING_SCALE)
end
end)
CrosshairTexture:SetTexture(textureToUse)
CrosshairTexture:SetVertexColor(r, g, b, a)
CrosshairAnimation:Play(reverseAnimation)
if state == "base" then
CrosshairFrame:SetScale(STARTING_SCALE)
CrosshairFrame:SetPoint("CENTER", 0, crosshairYPos)
end
end
function CM.DisplayCrosshair(shouldShow)
if shouldShow then
CrosshairTexture:Show()
else
CrosshairTexture:Hide()
end
end
-- Adjusts centered cursor vertical positioning to match crosshair's
local function AdjustCenteredCursorYPos(crosshairYPos)
local cursorCenteredYpos = (crosshairYPos / 1000) + 0.5 -- adding 0.5 to prevent going below screen center
local adjustment = (crosshairYPos * 0.15) / 1000 -- lowering the cursor by 15% of YPos to keep it within xhair
cursorCenteredYpos = cursorCenteredYpos - adjustment
SetCVar("CursorCenteredYPos", cursorCenteredYpos)
end
function CM.CreateCrosshair()
local DefaultConfig = CM.Constants.DatabaseDefaults.global
local UserConfig = CM.DB.global or {}
local crosshairYPos = UserConfig.crosshairY or DefaultConfig.crosshairY
CrosshairTexture:SetAllPoints(CrosshairFrame)
CrosshairTexture:SetBlendMode("BLEND")
CrosshairFrame:SetPoint("CENTER", 0, crosshairYPos)
CrosshairFrame:SetSize(UserConfig.crosshairSize or DefaultConfig.crosshairSize,
UserConfig.crosshairSize or DefaultConfig.crosshairSize)
CrosshairFrame:SetAlpha(UserConfig.crosshairOpacity or DefaultConfig.crosshairOpacity)
SetCrosshairAppearance("base")
AdjustCenteredCursorYPos(crosshairYPos)
end
-- Track the last known unit under cursor and its reaction to update the crosshair appearance
local lastKnownUnit = nil
local lastKnownUnitReaction = nil
-- Get the unit under the cursor and its reaction type for crosshair reactions
local function GetUnitUnderCursor()
-- Check for game object interaction first using softinteract
local isTargetObject = UnitIsGameObject("softinteract")
if isTargetObject then
return "softinteract", "object"
end
-- If not a game object, check for regular units using mouseover
if UnitExists("mouseover") and UnitGUID("mouseover") then
local reaction = UnitReaction("player", "mouseover")
local reactionType
if reaction then
if UnitIsPlayer("mouseover") then
if UnitCanAttack("player", "mouseover") then
reactionType = "hostile"
else
reactionType = "friendly_player"
end
elseif reaction <= 4 then
reactionType = "hostile"
elseif reaction >= 5 then
reactionType = "friendly_npc"
else
reactionType = "neutral"
end
else
reactionType = "base"
end
PreventDebugSpam("Found mouseover unit (reaction: " .. reactionType .. ")")
return "mouseover", reactionType
end
-- no valid unit found (meaning it's not aiming at anything)
PreventDebugSpam("No unit under cursor, setting base appearance")
return nil, nil
end
-- Update crosshair appearance based on unit under cursor
local function UpdateCrosshairReaction()
if not CM.DB.global.crosshair or HideCrosshairWhileMounted() then
return
end
local currentUnit, currentReaction = GetUnitUnderCursor()
-- Update if unit changed OR if reaction type changed (for same unit)
if currentUnit ~= lastKnownUnit or currentReaction ~= lastKnownUnitReaction then
lastKnownUnit = currentUnit
lastKnownUnitReaction = currentReaction
if currentUnit then
SetCrosshairAppearance(currentReaction or "base")
else
SetCrosshairAppearance("base")
end
end
end
---------------------------------------------------------------------------------------
-- CURSOR PULSE EFFECT --
---------------------------------------------------------------------------------------
local PULSE_DURATION = 0.4; -- total duration of the effect
local PULSE_STARTING_ALPHA = 0.5; -- initial transparency
local PULSE_STARTING_SIZE = 256 -- initial size of texture
local PULSE_TOTAL_ELAPSED = -1;
local PulseFrame = CreateFrame("Frame", nil, UIParent)
local PulseTexture = PulseFrame:CreateTexture(nil, "BACKGROUND")
local function CreatePulse()
PulseFrame:SetSize(0, 0)
PulseFrame:Hide()
PulseTexture:SetAtlas(CM.Constants.PulseAtlas, true)
PulseTexture:SetVertexColor(1, 1, 1, 1)
PulseTexture:SetAllPoints()
end
local function UpdatePulse(_, elapsed)
if PULSE_TOTAL_ELAPSED == -1 then
return
end
PULSE_TOTAL_ELAPSED = PULSE_TOTAL_ELAPSED + elapsed
if PULSE_TOTAL_ELAPSED > PULSE_DURATION then
PULSE_TOTAL_ELAPSED = -1
PulseFrame:Hide()
return
end
local progress = PULSE_TOTAL_ELAPSED / PULSE_DURATION
local invertedProgress = 1 - progress * progress
local alpha = invertedProgress * PULSE_STARTING_ALPHA
PulseTexture:SetAlpha(alpha)
local size = invertedProgress * PULSE_STARTING_SIZE
PulseFrame:SetSize(size, size)
local cursorX, cursorY = GetCursorPosition()
local scale = UIParent:GetEffectiveScale()
PulseFrame:SetPoint("BOTTOMLEFT", UIParent, "BOTTOMLEFT", (cursorX / scale) - size / 2, (cursorY / scale) - size / 2)
end
local function ShowCursorPulse()
PULSE_TOTAL_ELAPSED = 0
PulseFrame:Show()
end
PulseFrame:SetScript("OnUpdate", UpdatePulse)
---------------------------------------------------------------------------------------
-- FRAME WATCHING / CURSOR UNLOCK FUNCTIONS --
---------------------------------------------------------------------------------------
local function CursorUnlockFrameVisible(frameArr)
local allowFrameWatching = CM.DB.global.frameWatching
if not allowFrameWatching then
return false
end
for _, frameName in pairs(frameArr) do
local curFrame = _G[frameName]
if curFrame and curFrame.IsVisible and curFrame:IsVisible() then
PreventDebugSpam(frameName .. " is visible, preventing re-locking.")
return true
end
end
end
local function CursorUnlockFrameGroupVisible(frameNameGroups)
for wildcardFrameName, frameNames in pairs(frameNameGroups) do
if CursorUnlockFrameVisible(frameNames) then
if wildcardFrameName == "OPieRT" then
-- Hiding crosshair because OPie runs MouselookStop() itself,
-- which skips UnlockCursor()'s checks to hide crosshair
if CM.DB.global.crosshair then
CM.DisplayCrosshair(false)
end
CenterCursor(false)
end
return true
end
end
end
local function IsCustomConditionTrue()
if not CM.DB.global.customCondition then
return false
end
local func, err = loadstring(CM.DB.global.customCondition)
if not func then
CM.DebugPrint("Invalid custom condition " .. err)
return false
else
-- Calling the fn() protected to check evaluation
local success, result = pcall(func)
if not success then
CM.DebugPrint("Error executing custom condition: " .. result)
return false
end
return result
end
end
local function IsVendorMountOut()
if not CM.DB.global.mountCheck then
return false
end
local function checkMount(mount)
return GetPlayerAuraBySpellID(mount) ~= nil
end
for _, mount in ipairs(CM.Constants.MountsToCheck) do
if checkMount(mount) then
return true
end
end
return false
end
local function IsFeignDeathActive()
return GetPlayerAuraBySpellID(5384) ~= nil
end
local function IsInPetBattle()
if ON_RETAIL_CLIENT then
return _G.C_PetBattles.IsInBattle()
else
return false
end
end
local function IsUnlockFrameVisible()
local isGenericPanelOpen = (GetUIPanel("left") or GetUIPanel("right") or GetUIPanel("center")) and true or false
return CursorUnlockFrameVisible(CM.Constants.FramesToCheck) or CursorUnlockFrameVisible(CM.DB.global.watchlist) or
CursorUnlockFrameGroupVisible(CM.Constants.WildcardFramesToCheck) or isGenericPanelOpen
end
local function IsHealingRadialActive()
return CM.HealingRadial and CM.HealingRadial.IsActive and CM.HealingRadial.IsActive()
end
local function ShouldFreeLookBeOff()
local evaluate = IsCustomConditionTrue() or
(FreeLookOverride or SpellIsTargeting() or InCinematic() or IsInCinematicScene() or
IsUnlockFrameVisible() or IsVendorMountOut() or IsInPetBattle() or IsFeignDeathActive() or
IsHealingRadialActive())
return evaluate
end
-- FRAME WATCHING FOR SERIALIZED FRAMES (Ex: Opie rings)
local function InitializeWildcardFrameTracking(frameArr)
CM.DebugPrint("Looking for wildcard frames...")
-- Initialise the table by going through ALL available globals once and keeping the ones that match
for _, frameNameToFind in pairs(frameArr) do
CM.Constants.WildcardFramesToCheck[frameNameToFind] = {}
for frameName in pairs(_G) do
if string.match(frameName, frameNameToFind) then
CM.DebugPrint("Matched " .. frameNameToFind .. " to frame " .. frameName)
local frameGroup = CM.Constants.WildcardFramesToCheck[frameNameToFind]
frameGroup[#frameGroup + 1] = frameName
end
end
end
CM.DebugPrint("Wildcard frames initialized")
end
---------------------------------------------------------------------------------------
-- BUTTON OVERRIDE FUNCTIONS --
---------------------------------------------------------------------------------------
function CM.GetBindingsLocation()
return CM.DB.char.useGlobalBindings and "global" or "char"
end
function CM.SetNewBinding(buttonSettings)
if not buttonSettings.enabled then
return
end
-- If healing radial is enabled, it manages its own bindings
if CM.DB.global.healingRadial and CM.DB.global.healingRadial.enabled then
return
end
local valueToUse
if buttonSettings.value == "MACRO" then
valueToUse = "MACRO " .. buttonSettings.macroName
elseif buttonSettings.value == "CLEARTARGET" then
valueToUse = "MACRO CM_ClearTarget"
elseif buttonSettings.value == "CLEARFOCUS" then
valueToUse = "MACRO CM_ClearFocus"
else
valueToUse = buttonSettings.value
end
SetMouselookOverrideBinding(buttonSettings.key, valueToUse)
CM.DebugPrint(buttonSettings.key .. "'s override binding is now " .. valueToUse)
end
function CM.OverrideDefaultButtons()
for _, button in pairs(CM.Constants.ButtonsToOverride) do
CM.SetNewBinding(CM.DB[CM.GetBindingsLocation()].bindings[button])
end
end
function CM.ResetBindingOverride(buttonSettings)
SetMouselookOverrideBinding(buttonSettings.key, nil)
CM.DebugPrint(buttonSettings.key .. "'s override binding is now cleared")
end
-- Unbinding MOVEANDSTEER to avoid potential bug when toggling free look with the same key
local function UnbindMoveAndSteer()
local key = GetBindingKey("MOVEANDSTEER")
if key then
SetBinding(key, "Combat Mode Toggle")
end
SaveBindings(GetCurrentBindingSet())
end
-- Matches the bindable actions values defined in Constants.ActionsToProcess with more readable names for the UI
local function RenameBindableActions()
for _, bindingAction in pairs(CM.Constants.ActionsToProcess) do
local bindingUiName = _G["BINDING_NAME_" .. bindingAction]
CM.Constants.OverrideActions[bindingAction] = bindingUiName or bindingAction
end
end
---------------------------------------------------------------------------------------
-- FREE LOOK STATE FUNCTIONS --
---------------------------------------------------------------------------------------
-- Helper function to handle UI state changes when toggling free look
local function HandleFreeLookUIState(isLocking, isPermanentUnlock)
if CM.DB.global.crosshair then
CM.DisplayCrosshair(isLocking)
end
if CM.DB.global.hideTooltip then
HideTooltip(isLocking)
end
-- Only reset Action Camera settings on permanent unlocks (user-initiated), not temporary ones (UI panels)
if CM.DB.global.actionCamera and CM.DB.global.actionCamMouselookDisable then
if isLocking or (not isLocking and isPermanentUnlock) then
CM.ConfigActionCamera(isLocking and "combatmode" or "blizzard")
end
end
if CM.DB.global.crosshair and CM.DB.char.stickyCrosshair then
CM.ConfigStickyCrosshair(isLocking and "combatmode" or "blizzard")
end
end
local function LockFreeLook()
if not IsMouselooking() then
MouselookStart()
CenterCursor(true)
HandleFreeLookUIState(true, false)
-- Notify Healing Radial of mouselook state change
if CM.HealingRadial and CM.HealingRadial.OnMouselookChanged then
CM.HealingRadial.OnMouselookChanged(true)
end
CM.DebugPrint("Free Look Enabled")
end
end
local function UnlockFreeLook()
if IsMouselooking() then
CenterCursor(false)
MouselookStop()
if CM.DB.global.pulseCursor then
ShowCursorPulse()
end
HandleFreeLookUIState(false, false)
-- Notify Healing Radial of mouselook state change
if CM.HealingRadial and CM.HealingRadial.OnMouselookChanged then
CM.HealingRadial.OnMouselookChanged(false)
end
CM.DebugPrint("Free Look Disabled")
end
end
local function UnlockFreeLookPermanent()
if IsMouselooking() then
CenterCursor(false)
MouselookStop()
if CM.DB.global.pulseCursor then
ShowCursorPulse()
end
HandleFreeLookUIState(false, true)
-- Notify Healing Radial of mouselook state change
if CM.HealingRadial and CM.HealingRadial.OnMouselookChanged then
CM.HealingRadial.OnMouselookChanged(false)
end
CM.DebugPrint("Free Look Disabled (Permanent)")
end
end
local function ToggleFreeLook(state)
if IsDefaultMouseActionBeingUsed() then
CM.DebugPrint("Cannot toggle Free Look while holding down your left or right click.")
return
end
-- the Override state change is enough to trigger a Free Look update, but we call the fns directly to bypass the OnUpdate throttle
if not state then
LockFreeLook()
FreeLookOverride = false
elseif state then
UnlockFreeLookPermanent()
FreeLookOverride = true
end
end
---------------------------------------------------------------------------------------
-- EVENT HANDLING --
---------------------------------------------------------------------------------------
-- Rematch is called after every reload and this is where we make sure our config persists
local function Rematch()
IsDCLoaded()
CM.SetMouseLookSpeed()
if CM.DB.global.actionCamera then
CM.ConfigActionCamera("combatmode")
end
if CM.DB.char.reticleTargeting then
CM.ConfigReticleTargeting("combatmode")
if CM.DB.char.crosshairPriority then
CM.SetCrosshairPriority(true)
end
if CM.DB.char.friendlyTargeting then
CM.SetFriendlyTargeting(true)
end
end
if CM.DB.global.crosshair then
SetCrosshairAppearance(HideCrosshairWhileMounted() and "mounted" or "base")
if CM.DB.char.stickyCrosshair then
CM.ConfigStickyCrosshair("combatmode")
end
elseif CM.DB.global.crosshair == false then
CM.DisplayCrosshair(false)
end
LockFreeLook()
end
--[[
Handle events based on their category.
You need to first register the event in the CM.Constants.BLIZZARD_EVENTS table before using it here.
Checks which category in the table the event that's been fired belongs to, and then calls the appropriate function.
]] --
local function HandleEventByCategory(category, event)
local eventHandlers = {
UNLOCK_EVENTS = function()
UnlockFreeLook()
end,
LOCK_EVENTS = function()
LockFreeLook()
end,
REMATCH_EVENTS = function()
Rematch()
end,
FRIENDLY_TARGETING_EVENTS = function()
HandleFriendlyTargetingInCombat()
-- Also handle combat end for healing radial pending updates
if event == "PLAYER_REGEN_ENABLED" and CM.HealingRadial and CM.HealingRadial.OnCombatEnd then
CM.HealingRadial.OnCombatEnd()
end
end,
UNCATEGORIZED_EVENTS = function()
SetCrosshairAppearance(HideCrosshairWhileMounted() and "mounted" or "base")
end,
HEALING_RADIAL_EVENTS = function()
if CM.HealingRadial and CM.HealingRadial.OnGroupRosterUpdate then
CM.HealingRadial.OnGroupRosterUpdate()
end
end,
}
if eventHandlers[category] then
eventHandlers[category]()
end
end
-- FIRES WHEN ONE OF OUR REGISTERED EVENTS HAPPEN IN GAME
function _G.CombatMode_OnEvent(event)
for category, registered_events in pairs(CM.Constants.BLIZZARD_EVENTS) do
for _, registered_event in ipairs(registered_events) do
if event == registered_event then
HandleEventByCategory(category, event)
end
end
end
end
---------------------------------------------------------------------------------------
-- GAME STATE LOOP --
---------------------------------------------------------------------------------------
--[[
The game engine will call the OnUpdate function once each frame.
This is (in most cases) extremely excessive, hence why we're adding a throttle.
]] --
local ON_UPDATE_INTERVAL = 0.15
local TIME_SINCE_LAST_UPDATE = 0
function _G.CombatMode_OnUpdate(_, elapsed)
-- Making this thread-safe by keeping track of the last update cycle
TIME_SINCE_LAST_UPDATE = TIME_SINCE_LAST_UPDATE + elapsed
-- As the frame watching doesn't need to perform a visibility check every frame, we're adding a stagger
if (TIME_SINCE_LAST_UPDATE >= ON_UPDATE_INTERVAL) then
TIME_SINCE_LAST_UPDATE = 0
if IsDefaultMouseActionBeingUsed() then
return
end
if ShouldFreeLookBeOff() then
UnlockFreeLook()
return
end
if not IsMouselooking() then
LockFreeLook()
end
-- Update crosshair appearance based on unit under cursor
UpdateCrosshairReaction()
end
end
---------------------------------------------------------------------------------------
-- KEYBIND FUNCTIONS & COMMANDS --
---------------------------------------------------------------------------------------
-- FUNCTIONS CALLED FROM BINDINGS.XML
function _G.CombatMode_ToggleKey()
local state = IsMouselooking()
ToggleFreeLook(state)
end
function _G.CombatMode_HoldKey(keystate)
local state = keystate == "down"
ToggleFreeLook(state)
end
-- CREATING /CM CHAT COMMAND
function CM:OpenConfigCMD(input)
if not input or input:trim() == "" then
OpenConfigPanel()
else
AceConfigCmd.HandleCommand(self, "mychat", CM.METADATA["TITLE"], input)
end
end
-- /CMRESET CHAT COMMAND
function CM:RunUndoCMD(input)
if not input or input:trim() == "" then
UndoCMChanges()
else
AceConfigCmd.HandleCommand(self, "mychat", CM.METADATA["TITLE"], input)
end
end
---------------------------------------------------------------------------------------
-- STANDARD ACE3 METHODS --
---------------------------------------------------------------------------------------
--[[
Do init tasks here, like loading the Saved Variables,
or setting up slash commands.
]] --
function CM:OnInitialize()
self.DB = AceDB:New("CombatModeDB", CM.Constants.DatabaseDefaults, true)
local parentTable = CM.METADATA["TITLE"]
-- REGISTERING SETTINGS TREE
-- main category
AceConfig:RegisterOptionsTable(parentTable, CM.Config.AboutOptions)
AceConfigDialog:AddToBlizOptions(parentTable)
-- subcategories
for _, option in ipairs(CM.Config.OptionCategories) do
AceConfig:RegisterOptionsTable(option.id, option.table)
AceConfigDialog:AddToBlizOptions(option.id, option.name, parentTable)