-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathManastormManager.lua
More file actions
4315 lines (3805 loc) · 170 KB
/
ManastormManager.lua
File metadata and controls
4315 lines (3805 loc) · 170 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
-- Manastorm Manager - Automatically opens Manastorm Caches
-- Compatible with WoW 3.3.5a and Lua 5.1
local addonName = "ManastormManager"
local version = "1.0"
-- Addon variables
local isOpening = false
local isProcessingQueue = false -- Prevent multiple ProcessQueue calls
local openQueue = {}
local currentlyOpening = 0
local totalCaches = 0
local initialCacheCount = 0 -- Track how many we started with
local bonusMessageShown = false
local lastScanResults = {} -- Track what we found in last scan for comparison
local noItemsFoundCount = 0 -- Track how many times in a row we found no items
-- UI references for status updates
local dockOpenButton = nil
local mainOpenButton = nil
-- Vendor variables
local isVendoring = false
local vendorQueue = {}
local currentlyVendoring = 0
local totalVendorItems = 0
local totalGoldEarned = 0
local sessionGoldEarned = 0 -- Track total gold across all vendor sessions
-- Auto-open timer variables
local autoOpenTimer = nil
local lastCacheCount = 0
local bagCheckTimer = nil
-- NPC Detection variables
local npcScanTimer = nil
local lastNPCAlert = 0 -- Timestamp of last alert to prevent spam
local alertCooldown = 30 -- Cooldown in seconds between alerts for same NPC
local detectedNPCs = {} -- Track detected NPCs with timestamps
local detectedGUIDs = {} -- Track specific NPC instances by GUID
local flashFrame = nil -- Frame for screen flash effect
local toastFrame = nil -- Frame for NPC toast notification
local currentToastUnit = nil -- Currently displayed NPC unit ID
-- GUI variables
local optionsFrame = nil
local mainFrame = nil
local dockFrame = nil
-- Forward declarations for GUI functions
local ShowOptionsGUI
local ShowMainUI
local ShowProtectedItemsGUI
local ShowAutoVendingGUI
-- Default settings
local defaultSettings = {
delay = 0.7, -- Delay between opening caches (seconds) - enough time for loot window
verbose = false, -- Show detailed messages
vendorDelay = 0.2, -- Delay between vendoring items (seconds)
-- Sell gear by rarity (true = sell, false = keep)
sellTrash = true, -- Gray items (quality 0)
sellCommon = true, -- White items (quality 1)
sellUncommon = true, -- Green items (quality 2)
sellRare = true, -- Blue items (quality 3) - changed to true
sellEpic = false, -- Purple items (quality 4)
protectedItems = {}, -- List of item names to never sell
autoSellItems = {}, -- List of item names to always sell
autoOpen = false, -- Automatically open caches when found
adventureMode = false, -- Adventure Mode: open Adventurer's Caches and manage Hearthstones
showDock = true, -- Show the main UI dock
dockTheme = "blizzard", -- Dock theme: "blizzard" or "elvui"
dockLocked = false, -- Whether the dock is locked from moving
dockPoint = "CENTER", -- Dock anchor point
dockRelativePoint = "CENTER", -- Dock relative anchor point
dockX = 200, -- Dock X offset
dockY = 200, -- Dock Y offset
-- NPC Detection settings
npcDetection = true, -- Enable NPC detection for rare spawns
npcScanInterval = 2.0, -- Scan interval in seconds
npcAlertSound = true, -- Play alert sound when NPC found
npcFlashScreen = true, -- Flash screen edges when NPC found
npcMarkTarget = true, -- Place raid target marker on detected NPC
npcLightMode = true -- Use light scanning mode for better performance
}
-- Initialize settings with defaults
local function InitializeSettings()
ManastormManagerDB = ManastormManagerDB or {}
-- Add any missing settings from defaults
for key, value in pairs(defaultSettings) do
if ManastormManagerDB[key] == nil then
ManastormManagerDB[key] = value
end
end
-- Special handling for tables to preserve existing data
ManastormManagerDB.protectedItems = ManastormManagerDB.protectedItems or {}
ManastormManagerDB.autoSellItems = ManastormManagerDB.autoSellItems or {}
end
-- Print function with addon prefix
local function Print(msg)
print("|cff00ff00[Millhouse Manastorm]|r " .. msg)
end
-- Debug print function (only for verbose mode)
local function DebugPrint(msg)
if ManastormManagerDB.verbose then
Print("|cffcccccc" .. msg .. "|r")
end
end
-- Wildcard matching function (supports * wildcards)
local function MatchesPattern(itemName, pattern)
if not itemName or not pattern then
if ManastormManagerDB and ManastormManagerDB.verbose then
DebugPrint("MatchesPattern: itemName='" .. (itemName or "nil") .. "', pattern='" .. (pattern or "nil") .. "' - returning false")
end
return false
end
-- Convert to lowercase for case-insensitive matching
local lowerItem = string.lower(itemName)
local lowerPattern = string.lower(pattern)
if ManastormManagerDB and ManastormManagerDB.verbose then
DebugPrint("MatchesPattern: Testing '" .. lowerItem .. "' against pattern '" .. lowerPattern .. "'")
end
-- If no wildcards, do exact match
if not string.find(lowerPattern, "*", 1, true) then
local result = lowerItem == lowerPattern
if ManastormManagerDB and ManastormManagerDB.verbose then
DebugPrint("MatchesPattern: Exact match = " .. tostring(result))
end
return result
end
-- Convert wildcard pattern to Lua pattern
-- Escape special Lua pattern characters except *
local luaPattern = string.gsub(lowerPattern, "([%^%$%(%)%%%.%[%]%+%-%?])", "%%%1")
-- Replace * with .*
luaPattern = string.gsub(luaPattern, "%*", ".*")
-- Anchor the pattern to match the entire string
luaPattern = "^" .. luaPattern .. "$"
local result = string.find(lowerItem, luaPattern) ~= nil
if ManastormManagerDB and ManastormManagerDB.verbose then
DebugPrint("MatchesPattern: Lua pattern = '" .. luaPattern .. "', result = " .. tostring(result))
end
return result
end
-- Update button texts to show opening status
local function UpdateButtonStatus()
local buttonText = "Open Caches"
if isOpening then
local remaining = totalCaches - currentlyOpening
if remaining > 0 then
buttonText = "Opening... (" .. remaining .. " left)"
elseif table.getn(openQueue) > 0 then
buttonText = "Processing..."
else
buttonText = "Finishing..."
end
end
-- Update dock button if it exists
if dockOpenButton then
dockOpenButton:SetText(buttonText)
end
-- Update main UI button if it exists
if mainOpenButton then
mainOpenButton:SetText(buttonText)
end
end
-- Find all Manastorm Caches (and Adventurer's Caches in Adventure Mode) in bags
-- More reliable cache finding with detailed counting
local function FindManastormCaches(forceRescan, includeLocked)
local caches = {}
local bonusCaches = 0
local totalCount = 0
-- If we're not forcing a rescan and isOpening is true, be more thorough
local thoroughScan = forceRescan or isOpening
-- Scan all bags (0-4: backpack + 4 bags)
for bag = 0, 4 do
local numSlots = GetContainerNumSlots(bag)
if numSlots then
for slot = 1, numSlots do
local itemLink = GetContainerItemLink(bag, slot)
if itemLink then
local itemName = GetItemInfo(itemLink)
local isManastormCache = itemName and string.find(itemName, "Manastorm") and string.find(itemName, "Cache")
local isAdventurerCache = ManastormManagerDB.adventureMode and itemName and string.find(itemName, "Adventurer") and string.find(itemName, "Cache")
if isManastormCache or isAdventurerCache then
local texture, itemCount, locked, quality, readable = GetContainerItemInfo(bag, slot)
-- More thorough validation during opening process
if thoroughScan then
DebugPrint("Found cache: " .. itemName .. " at bag " .. bag .. " slot " .. slot ..
" count=" .. (itemCount or 0) .. " locked=" .. tostring(locked))
end
-- Include locked items if requested (for re-scanning during processing)
if (not locked or includeLocked) and itemCount and itemCount > 0 then
-- Check if this is a Bonus Manastorm Cache (only applies to Manastorm caches)
if isManastormCache and string.find(itemName, "Bonus") then
bonusCaches = bonusCaches + itemCount
else
-- Regular cache that can be opened
table.insert(caches, {
bag = bag,
slot = slot,
count = itemCount,
name = itemName,
id = bag .. ":" .. slot, -- Unique identifier
locked = locked, -- Track lock status
type = isManastormCache and "manastorm" or "adventurer"
})
totalCount = totalCount + itemCount
end
end
end
end
end
end
end
-- If we found bonus caches, inform the player (but only once per session)
if bonusCaches > 0 and not bonusMessageShown then
Print("I detect " .. bonusCaches .. " Bonus Manastorm Cache" .. (bonusCaches > 1 and "s" or "") .. " in your possession!")
print("|cffff8800Even my incredible magical abilities have limits - these special caches resist my power! You must open them yourself, mortal.|r")
bonusMessageShown = true
end
if thoroughScan then
DebugPrint("Cache scan complete: " .. table.getn(caches) .. " slots with " .. totalCount .. " total caches")
end
return caches, totalCount
end
-- Adventure Mode: Find and clean up multiple Hearthstones
local function CleanupExtraHearthstones()
if not ManastormManagerDB.adventureMode then
return
end
local hearthstones = {}
-- Scan all bags for Hearthstone items
for bag = 0, 4 do
local numSlots = GetContainerNumSlots(bag)
if numSlots then
for slot = 1, numSlots do
local itemLink = GetContainerItemLink(bag, slot)
if itemLink then
local itemName = GetItemInfo(itemLink)
if itemName and string.find(itemName, "Hearthstone") then
local texture, itemCount, locked = GetContainerItemInfo(bag, slot)
if not locked and itemCount and itemCount > 0 then
table.insert(hearthstones, {
bag = bag,
slot = slot,
count = itemCount,
name = itemName
})
end
end
end
end
end
end
-- If we have multiple hearthstones, destroy the extras
if table.getn(hearthstones) > 1 then
print(" ") -- Blank line before
print("|cffff8800I'm detecting an anomaly in time! You have multiple hearthstones and some seem to be from alternate timelines!|r")
print("|cffff8800Stand back, I, Millhouse the Magnificent will untangle these threads of fate and restore order!|r")
print("|cffff8800...Tell Chromie I said to stop meddling in Magic so obviously beyond them. Leave it to a professional!|r")
print(" ") -- Blank line after
-- Keep the first one, destroy the rest
for i = 2, table.getn(hearthstones) do
local hs = hearthstones[i]
DebugPrint("Destroying extra " .. hs.name .. " at bag " .. hs.bag .. " slot " .. hs.slot)
PickupContainerItem(hs.bag, hs.slot)
DeleteCursorItem()
end
end
end
-- NPC Detection Functions
-- Create screen flash effect
local function CreateFlashEffect()
if flashFrame then
return flashFrame
end
flashFrame = CreateFrame("Frame", "ManastormFlashFrame", UIParent)
flashFrame:SetAllPoints()
flashFrame:SetFrameStrata("FULLSCREEN_DIALOG")
flashFrame:Hide()
-- Create border textures for flashing effect
local borders = {}
local borderSize = 8
-- Top border
borders.top = flashFrame:CreateTexture(nil, "OVERLAY")
borders.top:SetTexture(1, 1, 0, 0.7) -- Yellow with transparency
borders.top:SetPoint("TOPLEFT", flashFrame, "TOPLEFT")
borders.top:SetPoint("TOPRIGHT", flashFrame, "TOPRIGHT")
borders.top:SetHeight(borderSize)
-- Bottom border
borders.bottom = flashFrame:CreateTexture(nil, "OVERLAY")
borders.bottom:SetTexture(1, 1, 0, 0.7)
borders.bottom:SetPoint("BOTTOMLEFT", flashFrame, "BOTTOMLEFT")
borders.bottom:SetPoint("BOTTOMRIGHT", flashFrame, "BOTTOMRIGHT")
borders.bottom:SetHeight(borderSize)
-- Left border
borders.left = flashFrame:CreateTexture(nil, "OVERLAY")
borders.left:SetTexture(1, 1, 0, 0.7)
borders.left:SetPoint("TOPLEFT", flashFrame, "TOPLEFT")
borders.left:SetPoint("BOTTOMLEFT", flashFrame, "BOTTOMLEFT")
borders.left:SetWidth(borderSize)
-- Right border
borders.right = flashFrame:CreateTexture(nil, "OVERLAY")
borders.right:SetTexture(1, 1, 0, 0.7)
borders.right:SetPoint("TOPRIGHT", flashFrame, "TOPRIGHT")
borders.right:SetPoint("BOTTOMRIGHT", flashFrame, "BOTTOMRIGHT")
borders.right:SetWidth(borderSize)
flashFrame.borders = borders
return flashFrame
end
-- Flash the screen edges
local function FlashScreen()
if not ManastormManagerDB or not ManastormManagerDB.npcFlashScreen then
return
end
local frame = CreateFlashEffect()
frame:Show()
-- Animate the flash
local elapsed = 0
local duration = 0.8
local pulses = 3
frame:SetScript("OnUpdate", function(self, dt)
elapsed = elapsed + dt
local progress = elapsed / duration
if progress >= 1 then
self:Hide()
self:SetScript("OnUpdate", nil)
return
end
-- Calculate alpha for pulsing effect
local pulseProgress = (progress * pulses) % 1
local alpha = 0.7 * (1 - pulseProgress)
-- Update all border alphas
for _, border in pairs(self.borders) do
border:SetTexture(1, 1, 0, alpha)
end
end)
end
-- Play alert sound
local function PlayAlertSound()
if not ManastormManagerDB or not ManastormManagerDB.npcAlertSound then
return
end
-- Play a notification sound - using RaidWarning sound
PlaySound("RaidWarning")
end
-- Create NPC toast notification
local function CreateToastNotification()
if toastFrame then
return toastFrame
end
toastFrame = CreateFrame("Frame", "ManastormNPCToast", UIParent)
toastFrame:SetSize(220, 140)
-- Load saved position or use default
if ManastormManagerDB.toastPoint then
toastFrame:SetPoint(
ManastormManagerDB.toastPoint,
UIParent,
ManastormManagerDB.toastRelativePoint or "CENTER",
ManastormManagerDB.toastX or 0,
ManastormManagerDB.toastY or 0
)
else
-- Default position above dock
toastFrame:SetPoint("BOTTOM", dockFrame, "TOP", 0, 10)
end
toastFrame:SetFrameStrata("HIGH")
toastFrame:EnableMouse(true)
toastFrame:SetMovable(true)
toastFrame:RegisterForDrag("LeftButton")
toastFrame:Hide()
-- Drag functionality
toastFrame:SetScript("OnDragStart", function(self)
if not IsShiftKeyDown() then
return -- Only allow dragging with Shift held
end
self:StartMoving()
end)
toastFrame:SetScript("OnDragStop", function(self)
self:StopMovingOrSizing()
-- Save the position
local point, _, relativePoint, x, y = self:GetPoint()
ManastormManagerDB.toastPoint = point
ManastormManagerDB.toastRelativePoint = relativePoint
ManastormManagerDB.toastX = x
ManastormManagerDB.toastY = y
Print("Toast position saved! Future notifications will appear here.")
end)
-- Background
local bg = toastFrame:CreateTexture(nil, "BACKGROUND")
bg:SetAllPoints()
bg:SetTexture(0, 0, 0, 0.8)
-- Border
local border = CreateFrame("Frame", nil, toastFrame)
border:SetAllPoints()
border:SetBackdrop({
edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
edgeSize = 12,
insets = {left = 2, right = 2, top = 2, bottom = 2}
})
border:SetBackdropBorderColor(1, 0.8, 0, 1) -- Gold border
-- Title
local title = toastFrame:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
title:SetPoint("TOP", 0, -8)
title:SetTextColor(1, 0, 0, 1) -- Red
title:SetText("RARE SPAWN!")
toastFrame.title = title
-- NPC Name
local npcName = toastFrame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
npcName:SetPoint("TOP", title, "BOTTOM", 0, -4)
npcName:SetTextColor(1, 1, 0, 1) -- Yellow
npcName:SetText("")
toastFrame.npcName = npcName
-- 3D Model Frame
local modelFrame = CreateFrame("PlayerModel", nil, toastFrame)
modelFrame:SetSize(80, 80)
modelFrame:SetPoint("LEFT", 10, -10)
modelFrame:SetCamera(0)
toastFrame.modelFrame = modelFrame
-- Click to target button using SecureActionButton to avoid taint
local targetButton = CreateFrame("Button", nil, toastFrame, "SecureActionButtonTemplate")
targetButton:SetAllPoints(modelFrame)
targetButton:SetAttribute("type", "macro")
-- We'll set the macro text when we show the toast
toastFrame.targetButton = targetButton
-- Close button
local closeButton = CreateFrame("Button", nil, toastFrame)
closeButton:SetSize(16, 16)
closeButton:SetPoint("TOPRIGHT", -4, -4)
closeButton:SetNormalTexture("Interface\\Buttons\\UI-Panel-MinimizeButton-Up")
closeButton:SetPushedTexture("Interface\\Buttons\\UI-Panel-MinimizeButton-Down")
closeButton:SetHighlightTexture("Interface\\Buttons\\UI-Panel-MinimizeButton-Highlight")
closeButton:SetScript("OnClick", function()
toastFrame:Hide()
currentToastUnit = nil
end)
toastFrame.closeButton = closeButton
-- Instructions text
local instructions = toastFrame:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
instructions:SetPoint("BOTTOMLEFT", 10, 8)
instructions:SetPoint("BOTTOMRIGHT", -30, 8)
instructions:SetHeight(30)
instructions:SetJustifyH("LEFT")
instructions:SetTextColor(0.8, 0.8, 0.8, 1)
instructions:SetText("Click model to target\nShift+Drag to move • X to close")
toastFrame.instructions = instructions
-- Auto-hide timer
local autoHideTimer = nil
toastFrame.StartAutoHide = function(self, duration)
if autoHideTimer then
autoHideTimer:SetScript("OnUpdate", nil)
end
autoHideTimer = CreateFrame("Frame")
local elapsed = 0
autoHideTimer:SetScript("OnUpdate", function(timer, dt)
elapsed = elapsed + dt
if elapsed >= (duration or 10) then
timer:SetScript("OnUpdate", nil)
self:Hide()
currentToastUnit = nil
end
end)
end
return toastFrame
end
-- Show toast notification for detected NPC
local function ShowNPCToast(unitId, npcName)
if not ManastormManagerDB or not ManastormManagerDB.npcDetection then
return
end
local toast = CreateToastNotification()
currentToastUnit = unitId
-- Set NPC name
toast.npcName:SetText(npcName)
-- Try to set the model - this might not work perfectly in 3.3.5a
if toast.modelFrame and UnitExists(unitId) then
-- Method 1: Try to set model from unit
toast.modelFrame:SetUnit(unitId)
-- Method 2: Fallback - try to set by creature display ID (if available)
-- This would need specific display IDs for each NPC, which we don't have
-- So we'll rely on SetUnit working
-- Set camera position
toast.modelFrame:SetCamera(0)
toast.modelFrame:SetPosition(0, 0, 0)
toast.modelFrame:SetFacing(0)
end
-- Set up the secure targeting macro for the button
if toast.targetButton then
-- Use /targetexact to avoid partial name matches
local macroText = "/targetexact " .. npcName
toast.targetButton:SetAttribute("macrotext", macroText)
end
-- Show the toast
toast:Show()
-- Auto-hide after 15 seconds
toast:StartAutoHide(15)
DebugPrint("Showing toast notification for: " .. npcName)
end
-- Mark target with raid icon
local function MarkNPCTarget(unitId)
if not ManastormManagerDB or not ManastormManagerDB.npcMarkTarget or not unitId then
return
end
-- Check if target already has a raid icon
local existingMark = GetRaidTargetIndex(unitId)
if existingMark and existingMark > 0 then
DebugPrint("Target already has raid mark " .. existingMark .. ", not overriding")
return
end
-- Set raid target icon 7 (cross/X) on the NPC
-- Only works if player has raid/party lead or assist
SetRaidTarget(unitId, 7)
DebugPrint("Marked target with cross (7) raid icon")
end
-- Scan for target NPCs
local function ScanForTargetNPCs()
if not ManastormManagerDB or not ManastormManagerDB.npcDetection then
return
end
local currentTime = GetTime()
local targetNPCs = {
"Clepto the Cardnapper",
"Greedy Demon"
}
-- Helper function to check and alert for target NPC
local function CheckUnit(unitId, unitName)
if not unitName then return end
-- Get unit GUID for tracking specific instances
local unitGUID = UnitGUID(unitId)
-- Check if unit is dead
if UnitIsDead(unitId) then
-- If this specific NPC instance was tracked, remove it
if unitGUID and detectedGUIDs[unitGUID] then
DebugPrint("Detected NPC with GUID " .. unitGUID .. " is dead, removing from tracking")
detectedGUIDs[unitGUID] = nil
end
-- Also clear the name-based cooldown for this NPC type
for _, targetName in ipairs(targetNPCs) do
if unitName == targetName and detectedNPCs[targetName] then
DebugPrint("Detected NPC " .. targetName .. " is dead, clearing cooldown")
detectedNPCs[targetName] = nil -- Clear cooldown so new spawns are detected immediately
end
end
return false
end
-- Check if unit is attackable (not already tapped by another player)
if not UnitCanAttack("player", unitId) then
DebugPrint("Unit " .. unitName .. " cannot be attacked, skipping")
return false
end
for _, targetName in ipairs(targetNPCs) do
if unitName == targetName then
-- Check if we've already alerted for this specific NPC instance
if unitGUID and detectedGUIDs[unitGUID] then
-- We've already alerted for this specific NPC
return false
end
-- This is a new instance of the NPC (different GUID or no GUID available)
-- Mark this specific instance as detected
if unitGUID then
detectedGUIDs[unitGUID] = currentTime
end
-- Also track by name for fallback (in case GUID isn't available)
detectedNPCs[targetName] = currentTime
-- Alert the player
Print("|cffff0000RARE SPAWN DETECTED:|r |cffffee00" .. targetName .. "|r has been found!")
Print("The magnificent Millhouse has marked this creature for your convenience!")
-- Flash screen
FlashScreen()
-- Play sound
PlayAlertSound()
-- Show toast notification with NPC model
ShowNPCToast(unitId, targetName)
-- Mark with raid target (only if not already marked)
MarkNPCTarget(unitId)
DebugPrint("Detected and marked: " .. targetName .. " (unit: " .. unitId .. ", GUID: " .. (unitGUID or "unknown") .. ")")
return true
end
end
return false
end
-- Check target
if UnitExists("target") then
local targetName = UnitName("target")
CheckUnit("target", targetName)
end
-- Check mouseover
if UnitExists("mouseover") then
local mouseoverName = UnitName("mouseover")
CheckUnit("mouseover", mouseoverName)
end
-- Check party/raid targets
if GetNumPartyMembers() > 0 then
for i = 1, GetNumPartyMembers() do
local unitId = "party" .. i .. "target"
if UnitExists(unitId) then
local unitName = UnitName(unitId)
CheckUnit(unitId, unitName)
end
end
end
-- Check raid targets if in raid
if GetNumRaidMembers() > 0 then
for i = 1, GetNumRaidMembers() do
local unitId = "raid" .. i .. "target"
if UnitExists(unitId) then
local unitName = UnitName(unitId)
CheckUnit(unitId, unitName)
end
end
end
-- Try to scan nameplates
for i = 1, 40 do
local unitId = "nameplate" .. i
if UnitExists(unitId) then
local unitName = UnitName(unitId)
CheckUnit(unitId, unitName)
end
end
end
-- Start NPC detection timer
local function StartNPCDetection()
-- Ensure settings are initialized
if not ManastormManagerDB then
InitializeSettings()
end
if not ManastormManagerDB.npcDetection then
StopNPCDetection()
return
end
if npcScanTimer then
return -- Already running
end
-- Default scan interval if not set
local scanInterval = ManastormManagerDB.npcScanInterval or 2.0
npcScanTimer = CreateFrame("Frame")
local elapsed = 0
npcScanTimer:SetScript("OnUpdate", function(self, dt)
elapsed = elapsed + dt
if elapsed >= scanInterval then
elapsed = 0
ScanForTargetNPCs()
end
end)
DebugPrint("NPC Detection started (scan interval: " .. scanInterval .. "s)")
end
-- Stop NPC detection timer
local function StopNPCDetection()
if npcScanTimer then
npcScanTimer:SetScript("OnUpdate", nil)
npcScanTimer = nil
DebugPrint("NPC Detection stopped")
end
end
-- Open a single cache
local function OpenCache(bag, slot, isAutoOpen)
-- Get item info before opening
local itemLink = GetContainerItemLink(bag, slot)
local itemName = itemLink and GetItemInfo(itemLink) or "Unknown Cache"
-- Safety check: Verify this is actually a cache before using it
if itemLink and itemName then
local isManastormCache = string.find(itemName, "Manastorm") and string.find(itemName, "Cache")
local isAdventurerCache = ManastormManagerDB.adventureMode and string.find(itemName, "Adventurer") and string.find(itemName, "Cache")
if not (isManastormCache or isAdventurerCache) then
DebugPrint("WARNING: Attempted to open non-cache item: " .. itemName .. " at bag " .. bag .. " slot " .. slot)
return -- Don't open non-cache items
end
end
DebugPrint("Opening " .. itemName .. " at bag " .. bag .. " slot " .. slot)
UseContainerItem(bag, slot)
currentlyOpening = currentlyOpening + 1
-- Update button status to show progress
UpdateButtonStatus()
-- No more chat spam - completion message is handled in ProcessQueue
end
-- Count empty bag slots
local function GetEmptyBagSlots()
local emptySlots = 0
for bag = 0, 4 do
local numSlots = GetContainerNumSlots(bag)
if numSlots and numSlots > 0 then
for slot = 1, numSlots do
local texture = GetContainerItemInfo(bag, slot)
if not texture then
emptySlots = emptySlots + 1
end
end
end
end
return emptySlots
end
-- Process the opening queue
local function ProcessQueue(isAutoOpen)
if not isOpening then
DebugPrint("ProcessQueue: Stopping because isOpening is false")
return
end
if isProcessingQueue then
DebugPrint("ProcessQueue: Already processing, skipping")
return
end
isProcessingQueue = true
local queueSize = table.getn(openQueue)
DebugPrint("ProcessQueue: Queue has " .. queueSize .. " items")
-- Check bag space before continuing
local emptySlots = GetEmptyBagSlots()
if emptySlots <= 1 then
Print("|cffff0000Stopping cache opening - bags are full! (" .. emptySlots .. " slots remaining)|r")
Print("|cffffee00Clear some bag space and use /ms open to continue.|r")
isProcessingQueue = false -- Clear this before StopOpening
StopOpening()
return
end
-- Get next cache from queue
if queueSize > 0 then
local cache = table.remove(openQueue, 1)
DebugPrint("Processing cache at bag " .. cache.bag .. " slot " .. cache.slot)
-- Verify the cache is still there and is actually a cache
local texture, itemCount, locked = GetContainerItemInfo(cache.bag, cache.slot)
if texture then
-- Double-check that this is still a cache item
local itemLink = GetContainerItemLink(cache.bag, cache.slot)
local isStillCache = false
if itemLink then
local itemName = GetItemInfo(itemLink)
if itemName then
local isManastormCache = string.find(itemName, "Manastorm") and string.find(itemName, "Cache")
local isAdventurerCache = ManastormManagerDB.adventureMode and string.find(itemName, "Adventurer") and string.find(itemName, "Cache")
isStillCache = isManastormCache or isAdventurerCache
end
end
if not isStillCache then
-- Item in this slot is no longer a cache (probably got replaced by loot)
DebugPrint("Item at bag " .. cache.bag .. " slot " .. cache.slot .. " is no longer a cache, skipping")
-- Continue immediately
local timer = CreateFrame("Frame")
local elapsed = 0
timer:SetScript("OnUpdate", function(self, elapsedTime)
elapsed = elapsed + elapsedTime
if elapsed >= 0.1 then
timer:SetScript("OnUpdate", nil)
isProcessingQueue = false
ProcessQueue(isAutoOpen)
end
end)
elseif locked then
-- Check if we've tried too many times (level-restricted caches)
cache.retries = (cache.retries or 0) + 1
if cache.retries >= 3 then
-- Skip this cache after 3 failed attempts
local itemLink = GetContainerItemLink(cache.bag, cache.slot)
local itemName = itemLink and GetItemInfo(itemLink) or "Unknown Cache"
Print("|cffff0000Cannot open " .. itemName .. " - may require level 70. Skipping after 3 attempts.|r")
DebugPrint("Cache at bag " .. cache.bag .. " slot " .. cache.slot .. " failed 3 times, skipping")
else
-- If locked, put it back at the end of the queue and continue with next
DebugPrint("Cache is locked (attempt " .. cache.retries .. "), requeueing and continuing")
table.insert(openQueue, cache)
end
-- Process next with a small delay to avoid freezing
local timer = CreateFrame("Frame")
local elapsed = 0
timer:SetScript("OnUpdate", function(self, elapsedTime)
elapsed = elapsed + elapsedTime
if elapsed >= 0.1 then -- Small delay to prevent freezing
timer:SetScript("OnUpdate", nil)
isProcessingQueue = false
ProcessQueue(isAutoOpen)
end
end)
else
-- Open the cache
OpenCache(cache.bag, cache.slot, isAutoOpen)
noItemsFoundCount = 0 -- Reset counter since we opened something
-- Wait before processing the next one to ensure loot window has time
local timer = CreateFrame("Frame")
local elapsed = 0
timer:SetScript("OnUpdate", function(self, elapsedTime)
elapsed = elapsed + elapsedTime
if elapsed >= ManastormManagerDB.delay then
timer:SetScript("OnUpdate", nil)
-- Continue processing next cache
isProcessingQueue = false
ProcessQueue(isAutoOpen)
end
end)
end
else
-- Cache no longer exists, continue with small delay
DebugPrint("Cache no longer exists at bag " .. cache.bag .. " slot " .. cache.slot)
local timer = CreateFrame("Frame")
local elapsed = 0
timer:SetScript("OnUpdate", function(self, elapsedTime)
elapsed = elapsed + elapsedTime
if elapsed >= 0.1 then -- Small delay to prevent freezing
timer:SetScript("OnUpdate", nil)
isProcessingQueue = false
ProcessQueue(isAutoOpen)
end
end)
end
else
-- Queue is empty, rescan for more caches (include locked ones since they might be mid-loot)
local caches, totalCount = FindManastormCaches(true, true)
if table.getn(caches) > 0 then
-- Found caches, reset counter and rebuild queue
noItemsFoundCount = 0
DebugPrint("Found " .. table.getn(caches) .. " caches (including locked), adding to queue")
for i, cache in ipairs(caches) do
table.insert(openQueue, {bag = cache.bag, slot = cache.slot, retries = 0})
end
-- Continue processing with small delay to avoid freezing
local timer = CreateFrame("Frame")
local elapsed = 0
timer:SetScript("OnUpdate", function(self, elapsedTime)
elapsed = elapsed + elapsedTime
if elapsed >= 0.1 then
timer:SetScript("OnUpdate", nil)
isProcessingQueue = false
ProcessQueue(isAutoOpen)
end
end)
else
-- No caches found
noItemsFoundCount = noItemsFoundCount + 1
DebugPrint("No caches found (attempt " .. noItemsFoundCount .. ")")
-- Only give up after 3 consecutive attempts with no caches found
if noItemsFoundCount < 3 then
-- Wait and try again with shorter delay
local timer = CreateFrame("Frame")
local elapsed = 0
timer:SetScript("OnUpdate", function(self, elapsedTime)
elapsed = elapsed + elapsedTime
if elapsed >= 0.5 then -- Wait 0.5 seconds between retries
timer:SetScript("OnUpdate", nil)
isProcessingQueue = false
ProcessQueue(isAutoOpen)
end
end)
else
-- We've tried 3 times with no caches, we're really done
isOpening = false
isProcessingQueue = false
-- Update UI immediately after setting isOpening to false
UpdateButtonStatus()
if mainFrame then
mainFrame.UpdateStatus()
end
print(" ") -- Blank line before
if currentlyOpening > 0 then
print("|cffff8800Successfully opened " .. currentlyOpening .. " Manastorm Cache" .. (currentlyOpening > 1 and "s" or "") .. "!|r")
end
print("|cffff8800If you have any excess priceless artifacts that were lost in time, I'm making a collection.|r")
print(" ") -- Blank line after
-- Reset all counters
currentlyOpening = 0
totalCaches = 0
initialCacheCount = 0
noItemsFoundCount = 0
end
end
end
end
-- Main function to start opening caches
local function OpenManastormCaches(isAutoOpen, isRestart)
if isOpening then