Files
2026-11-16 01:00:42 +01:00

1832 lines
84 KiB
Lua

-- =============================================================================
-- ChronicleLog - Event-driven combat logging system
-- =============================================================================
---@class ChronicleLog
---@field enabled boolean Whether logging is currently active
---@field frame Frame Event listener frame
ChronicleLog = {
enabled = false,
frame = nil,
buffer = {}, -- In-memory buffer for log lines
bufferSize = 0, -- Current number of lines in buffer
raidGroupPayload = nil,
raidGroupCapturePending = false,
raidGroupCaptureAt = nil,
raidGroupCaptureReason = nil,
raidGroupForceCapture = false,
raidGroupRetryCount = 0,
}
-- Detect Turtle WoW (build 7272) vs vanilla 1.12 (build 5875).
-- Transmog and remote talent inspection are Turtle WoW-only. Extra unit-data
-- events detect Nampower, ClassicAPI, and SuperWoW independently.
ChronicleLog.isTurtleWow = Chronicle_IsUrsolClient()
-- Delimiter for log output format: TIMESTAMP|EVENT_TYPE|field1|field2|...
local LOG_SEP = "|"
-- PERF: lines written per frame by a deferred combat-end save
local FLUSH_CHUNK_LINES = 200
-- PERF: block writer.
-- table.concat builds its result through luaL_Buffer, which in Lua 5.0 (512
-- byte buffer on Windows) merges partial strings again and again: joining a
-- 1000-line chunk produced ~5.7 times its size in garbage. A single `..`
-- expression instead allocates its result once, so the lines are written in
-- blocks of FLUSH_BLOCK_LINES joined by a generated `t[i] .. "\n" .. t[i+1] ..`
-- function (one string per block, each line followed by "\n").
local FLUSH_BLOCK_LINES = 50
local blockWriters = {}
local function GetBlockWriter(count)
local fn = blockWriters[count]
if not fn then
local parts = {}
for k = 0, count - 1 do
parts[k + 1] = "t[i+" .. k .. "]"
end
fn = loadstring("return function(t, i) return " .. table.concat(parts, ' .. "\\n" .. ') .. ' .. "\\n" end')()
blockWriters[count] = fn
end
return fn
end
-- joins `count` block strings (no separator), used to write fewer, larger
-- pieces when a save has to finish at once (loading screen, logout...)
local blockJoiners = {}
local function GetBlockJoiner(count)
local fn = blockJoiners[count]
if not fn then
local parts = {}
for k = 1, count do
parts[k] = "t[" .. k .. "]"
end
fn = loadstring("return function(t) return " .. table.concat(parts, " .. ") .. " end")()
blockJoiners[count] = fn
end
return fn
end
local FINISH_JOIN_BLOCKS = 20
local joinScratch = {}
local RAID_GROUP_DEBOUNCE_DELAY = 0.25
local RAID_GROUP_RETRY_DELAY = 0.25
local RAID_GROUP_MAX_RETRIES = 8
-- A raid session keeps the same file (and date) as long as we come back to the
-- same instance within this delay. A raid starting at 23:00 and ending at 01:00
-- (or a /reload / disconnect in the middle) therefore stays in one file, dated
-- from the day the raid started.
local SESSION_TIMEOUT = 6 * 3600 -- seconds
-- "Raid day" starts at 06:00: anything between midnight and 06:00 belongs to the
-- previous evening (e.g. Onyxia entered at 00:30 after a Molten Core started at 21:00).
local DAY_START_OFFSET = 6 * 3600 -- seconds
--- Strips everything but letters and digits ("Zul'Gurub" -> "ZulGurub",
--- "Onyxia's Lair" -> "OnyxiasLair") so the name is safe in a filename.
local function SanitizeForFilename(text)
local clean = string.gsub(text or "", "[^%w]", "")
return clean
end
--- Returns the instance ID of the current zone from the saved instances list (0 if not saved).
local function GetCurrentInstanceId(zoneName)
local zoneLower = strlower(zoneName or "")
for i = 1, GetNumSavedInstances() do
local instanceName, savedId = GetSavedInstanceInfo(i)
if instanceName and zoneLower == strlower(instanceName) then
return savedId or 0
end
end
return 0
end
--- Base of every filename: Chronicle_<CharacterName> or Chronicle_<CharacterName>_<RealmName>
--- when the includeRealmInFilename setting is enabled (account-wide).
function ChronicleLog:GetFilenameBase()
local playerName = UnitName("player") or "Unknown"
if self:GetSetting("includeRealmInFilename") then
local realm = SanitizeForFilename(GetRealmName() or "Unknown")
return "Chronicle_" .. playerName .. "_" .. realm
end
return "Chronicle_" .. playerName
end
--- Computes the filename that matches the current location.
--- In a raid or dungeon: Chronicle_<Name>_<Instance>_<YYYY-MM-DD>.txt, where the date
--- is the day the session started (see SESSION_TIMEOUT).
--- Elsewhere: Chronicle_<Name>.txt (previous behaviour).
---@return string filename
function ChronicleLog:ComputeLogFilename()
local base = self:GetFilenameBase()
local inInstance = self:IsInInstance()
local zoneName = GetRealZoneText() or ""
local zoneKey = SanitizeForFilename(zoneName)
if not inInstance or zoneKey == "" then
return base .. ".txt"
end
if not ChronicleCompanionCharDB then ChronicleCompanionCharDB = {} end
local session = ChronicleCompanionCharDB.logSession
local now = time()
local instanceId = GetCurrentInstanceId(zoneName)
local sameSession = session
and session.zone == zoneKey
and session.date
and session.last
and (now - session.last) < SESSION_TIMEOUT
-- A different raid lockout means a different raid, even within the delay
and not (instanceId ~= 0 and session.instanceId and session.instanceId ~= 0 and session.instanceId ~= instanceId)
if not sameSession then
session = { zone = zoneKey, date = date("%Y-%m-%d", now - DAY_START_OFFSET), instanceId = instanceId }
ChronicleCompanionCharDB.logSession = session
end
session.last = now
if instanceId ~= 0 then
session.instanceId = instanceId
end
return base .. "_" .. zoneKey .. "_" .. session.date .. ".txt"
end
--- Keeps the session alive (called at every combat end) so that a long raid
--- is not split even if no zone change happens for hours.
function ChronicleLog:TouchLogSession()
local session = ChronicleCompanionCharDB and ChronicleCompanionCharDB.logSession
if session and self.currentLogFile and string.find(self.currentLogFile, "_" .. session.zone .. "_", 1, true) then
session.last = time()
end
end
--- Returns the file currently being written to.
--- The name is fixed when the zone changes (see ZONE_CHANGED_NEW_AREA), so lines
--- buffered in a raid are still written to that raid's file after a loading screen.
---@return string filename The log filename
function ChronicleLog:GetLogFilename()
if not self.currentLogFile then
self.currentLogFile = self:ComputeLogFilename()
end
return self.currentLogFile
end
--- Recomputes the target file for the current zone. If it changed, the buffer
--- is first flushed to the previous file.
function ChronicleLog:UpdateLogFilename()
local newFile = self:ComputeLogFilename()
local now = GetTime()
if self.currentLogFile and newFile ~= self.currentLogFile then
-- Right after a loading screen the client may still report the previous
-- zone name for a fraction of a second (e.g. "Stranglethorn Vale" flagged
-- as a raid before "Zul'Gurub"). A file selected less than a few seconds
-- ago is treated as transitional: its lines go to the new file instead.
local transitional = self.currentLogFileSince and (now - self.currentLogFileSince) < 5
if not transitional then
self:FlushToFile()
end
if self:IsEnabled() then
Chronicle:Print("Log file: " .. newFile)
end
end
if newFile ~= self.currentLogFile then
self.currentLogFileSince = now
end
self.currentLogFile = newFile
end
--- Wrapper for IsInInstance() that excludes battlegrounds.
--- Battlegrounds return instanceType "pvp" but we treat them as open world.
---@return boolean inInstance Whether player is in an instance (excluding BGs)
---@return string instanceType The instance type ("party", "raid", "pvp", "arena", or "none")
function ChronicleLog:IsInInstance()
local inInstance, instanceType = IsInInstance()
-- Treat battlegrounds as open world, not instances
if instanceType == "pvp" then
inInstance = false
end
return inInstance, instanceType
end
-- Events to listen for
ChronicleLog.events = {
-- "UNIT_CASTEVENT",
"UNIT_DIED",
-- "PLAYER_REGEN_DISABLED",
-- "PLAYER_REGEN_ENABLED",
"AUTO_ATTACK_SELF", -- Requires CVar NP_EnableAutoAttackEvents = 1
"AUTO_ATTACK_OTHER", -- Requires CVar NP_EnableAutoAttackEvents = 1
"SPELL_HEAL_BY_SELF", -- Requires CVar NP_EnableSpellHealEvents = 1
"SPELL_HEAL_BY_OTHER", -- Requires CVar NP_EnableSpellHealEvents = 1
"SPELL_HEAL_ON_SELF", -- Requires CVar NP_EnableSpellHealEvents = 1
"SPELL_ENERGIZE_BY_SELF", -- Requires CVar NP_EnableSpellEnergizeEvents = 1
"SPELL_ENERGIZE_BY_OTHER", -- Requires CVar NP_EnableSpellEnergizeEvents = 1
"SPELL_ENERGIZE_ON_SELF", -- Requires CVar NP_EnableSpellEnergizeEvents = 1
"SPELL_MISS_SELF", -- Your spells that missed/resisted/etc.
"SPELL_MISS_OTHER", -- Others' spells that missed/resisted/etc.
"SPELL_DISPEL_BY_SELF", -- You dispelled a spell from a unit
"SPELL_DISPEL_BY_OTHER", -- Someone else dispelled a spell from a unit
"ENVIRONMENTAL_DMG_SELF", -- Active player took environmental damage
"ENVIRONMENTAL_DMG_OTHER", -- Another unit took environmental damage
"DAMAGE_SHIELD_SELF", -- Active player's damage shield dealt damage
"DAMAGE_SHIELD_OTHER", -- Another unit's damage shield dealt damage
"AURA_CAST_ON_SELF", -- Requires CVar NP_EnableAuraCastEvents = 1
"AURA_CAST_ON_OTHER", -- Requires CVar NP_EnableAuraCastEvents = 1
"BUFF_UPDATE_DURATION_SELF", -- Buff duration refreshed on active player
"DEBUFF_UPDATE_DURATION_SELF", -- Debuff duration refreshed on active player
"BUFF_ADDED_SELF", -- Buff added to active player
"BUFF_REMOVED_SELF", -- Buff removed from active player
"BUFF_ADDED_OTHER", -- Buff added to another unit
"BUFF_REMOVED_OTHER", -- Buff removed from another unit
"DEBUFF_ADDED_SELF", -- Debuff added to active player
"DEBUFF_REMOVED_SELF", -- Debuff removed from active player
"DEBUFF_ADDED_OTHER", -- Debuff added to another unit
"DEBUFF_REMOVED_OTHER", -- Debuff removed from another unit
"SPELL_DAMAGE_EVENT_SELF", -- Spell damage dealt by active player
"SPELL_DAMAGE_EVENT_OTHER", -- Spell damage dealt by others
"SPELL_DELAYED_SELF", -- Your spell was delayed (pushback)
"SPELL_DELAYED_OTHER", -- Other's spell was delayed (currently non-functional)
"SPELL_CHANNEL_START", -- Active player started channeling
"SPELL_CHANNEL_UPDATE", -- Active player channel time updated
"SPELL_FAILED_SELF", -- Active player's spell failed
"SPELL_FAILED_OTHER", -- Other's spell failed (limited info)
"SPELL_GO_SELF", -- Requires CVar NP_EnableSpellGoEvents = 1
"SPELL_GO_OTHER", -- Requires CVar NP_EnableSpellGoEvents = 1
"SPELL_START_SELF", -- Requires CVar NP_EnableSpellStartEvents = 1
"SPELL_START_OTHER", -- Requires CVar NP_EnableSpellStartEvents = 1
-- Chat events
"CHAT_MSG_LOOT", -- Loot messages (arg1 = message)
"CHAT_MSG_SYSTEM", -- System messages (arg1 = message) - used for trade detection
"CHAT_MSG_ADDON", -- Addon messages (for transmog data from other players)
-- Session events
"PLAYER_LEAVING_WORLD", -- Flush logs on logout/disconnect/reload
-- Unit GUID events
"UNIT_INVENTORY_CHANGED_GUID", -- Unit equipment changed (emits COMBATANT_INFO)
-- Raid events
"RAID_ROSTER_UPDATE", -- Raid membership or subgroup assignment changed
"PARTY_MEMBERS_CHANGED", -- Covers raid conversion and disband transitions
-- "RAID_TARGET_UPDATE", -- Raid target icon changed on a unit (no payload, needs GetRaidTargetIndex)
}
-- =============================================================================
-- Core Setup
-- =============================================================================
--- Initializes the ChronicleLog system.
--- Creates the event frame and sets up the event dispatcher.
--- Must be called once during addon initialization.
function ChronicleLog:Init()
-- Initialize config (merge defaults into SavedVariables)
self:InitConfig()
-- Store time offset for millisecond timestamps
-- GetTime() returns session time with ms precision, time() returns unix seconds
self.timeOffset = time() - GetTime()
self.frame = CreateFrame("Frame", "ChronicleLogFrame")
local lastTransmogCheck = 0
self.frame:SetScript("OnUpdate", function()
local now = GetTime()
-- PERF: write a deferred combat-end save a few lines per frame
if ChronicleLog.pendingFlush then
ChronicleLog:DrainPendingFlush(FLUSH_CHUNK_LINES)
end
ChronicleLog:ProcessScheduledRaidGroupCapture(now)
-- Throttle transmog and talent work to every 0.5 seconds
if (now - lastTransmogCheck) < 0.5 then return end
lastTransmogCheck = now
if ChronicleLog.enabled then
if ChronicleLog.isTurtleWow then
-- Flush pending transmog data after timeout
ChronicleLog:FlushPendingTransmog()
-- Process talent inspection queue
ChronicleLog:ProcessTalentQueue()
-- Periodically queue raid/party members for talent refresh
ChronicleLog:QueueRaidTalentRefresh()
end
end
end)
self.frame:SetScript("OnEvent", function()
local autoSave = (event == "PLAYER_REGEN_ENABLED" and self:GetSetting("autoCombatSave"))
-- Always process zone changes (for auto-enable/disable even when logging is off)
if event == "PLAYER_ENTERING_WORLD" then
ChronicleLog:FlushToFile()
elseif autoSave then
-- PERF: spread over the next frames instead of one freeze
ChronicleLog:FlushToFile(true)
end
if event == "ZONE_CHANGED_NEW_AREA" or event == "PLAYER_ENTERING_WORLD" then
-- Flush buffer on loading screens to prevent data loss
ChronicleLog:ZONE_CHANGED_NEW_AREA()
return
end
-- Other events only when enabled
if ChronicleLog.enabled and ChronicleLog[event] then
ChronicleLog[event](ChronicleLog, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9)
end
end)
-- Always register zone events (needed for auto-enable even when logging is off)
self.frame:RegisterEvent("ZONE_CHANGED_NEW_AREA")
self.frame:RegisterEvent("PLAYER_ENTERING_WORLD")
self.frame:RegisterEvent("PLAYER_REGEN_ENABLED")
-- Restore logging state from last session
if self:GetSetting("enabled") then
self:Enable()
end
-- Check dependencies and warn if any issues
local problems = self:CheckDependencies()
if table.getn(problems) > 0 then
StaticPopup_Show("CHRONICLELOG_DEPENDENCY_WARNING", table.concat(problems, "\n"))
end
end
--- Enables combat logging and registers all events.
--- Does nothing if already enabled.
function ChronicleLog:Enable()
if self.enabled then return end
self.enabled = true
self:SetSetting("enabled", true)
-- Enable required CVars for extended events
SetCVar("NP_EnableAutoAttackEvents", 1)
SetCVar("NP_EnableSpellHealEvents", 1)
SetCVar("NP_EnableSpellEnergizeEvents", 1)
SetCVar("NP_EnableAuraCastEvents", 1)
SetCVar("NP_EnableSpellGoEvents", 1)
SetCVar("NP_EnableSpellStartEvents", 1)
for _, evt in ipairs(self.events) do
self.frame:RegisterEvent(evt)
end
-- Capture the current raid as a fresh logging-session baseline.
self:ResetRaidGroupCapture()
self:ScheduleRaidGroupCapture(0, "LOGGING_ENABLED")
-- Update minimap icon
if ChronicleMinimapButton then
ChronicleMinimapButton:UpdateIcon()
end
end
--- Disables combat logging, unregisters all events, and writes buffer to file.
--- Does nothing if already disabled.
--- Returns the number of lines written to file.
---@return number linesWritten Number of lines written to file
function ChronicleLog:Disable()
if not self.enabled then return 0 end
self.enabled = false
self:SetSetting("enabled", false)
for _, evt in ipairs(self.events) do
self.frame:UnregisterEvent(evt)
end
self:ResetRaidGroupCapture()
-- Write buffer to file on disable
local linesWritten = self:FlushToFile()
-- Update minimap icon
if ChronicleMinimapButton then
ChronicleMinimapButton:UpdateIcon()
end
return linesWritten
end
function ChronicleLog:Toggle()
if self.enabled then
self:Disable()
else
self:Enable()
end
end
--- Returns whether combat logging is currently enabled.
---@return boolean enabled True if logging is active
function ChronicleLog:IsEnabled()
return self.enabled
end
-- =============================================================================
-- Log Output
-- =============================================================================
--- Generates a header string with player and version metadata.
--- Format: HEADER|playerGuid|realm|zone|addonVer|superWowVer|namPowerVer|xp3Ver|wowVer|wowBuild|wowBuildDate|localTime|utcTime|combatLogRange|classicApi|threatMode
--- classicApi: ClassicAPI version ("X.Y.Z" from CLASSIC_API_VERSION), empty when not loaded.
--- threatMode: "query" (this addon asks the server for threat), "listen" (another
--- threat addon asks, this addon records the answers) or "" (threat logging off).
---@return string header Pipe-delimited header line
function ChronicleLog:GenerateHeader()
-- Player info
local _, playerGuid = UnitExists("player")
playerGuid = playerGuid or ""
local realm = GetRealmName() or ""
local zone = GetRealZoneText() or ""
-- Addon versions
local addonVersion = GetAddOnMetadata("ChronicleCompanion", "Version") or ""
local superWowVersion = SUPERWOW_VERSION or ""
local namPowerVersion = NAMPOWER_VERSION or ""
local xp3Version = ""
-- WoW client version
local wowVersion, wowBuild, wowBuildDate = GetBuildInfo()
wowVersion = wowVersion or ""
wowBuild = wowBuild or ""
wowBuildDate = wowBuildDate or ""
-- Clock info (local and UTC)
local ts = time()
local localTime = date("%d.%m.%y %H:%M:%S", ts)
local utcTime = date("!%d.%m.%y %H:%M:%S", ts)
-- Combat log range
local combatLogRange = GetCVar("CombatLogRangeCreature") or ""
-- Client mods and threat logging mode (see advancedlogging/ursol.lua)
local classicApi = Chronicle_ClassicAPIVersion()
local threatMode = ""
if ChronicleUrsol and ChronicleUrsol:Active("threat") then
threatMode = ChronicleUrsol:ThreatQueryActive() and "query" or "listen"
end
local parts = {
"HEADER",
playerGuid,
realm,
zone,
addonVersion,
superWowVersion,
namPowerVersion,
xp3Version,
wowVersion,
wowBuild,
wowBuildDate,
localTime,
utcTime,
combatLogRange,
classicApi,
threatMode
}
return table.concat(parts, LOG_SEP)
end
--- Writes the header line to the buffer.
--- Call this on zone changes to record session metadata.
function ChronicleLog:WriteHeader()
local header = "0" .. LOG_SEP .. self:GenerateHeader()
self.bufferSize = self.bufferSize + 1
self.buffer[self.bufferSize] = header
end
--- Formats a log line and appends it to the in-memory buffer.
--- Output format: TIMESTAMP|EVENT_TYPE|field1|field2|...
--- Uses Lua 5.0 vararg style (arg table) for Vanilla WoW compatibility.
--- Buffer is written to file when logging is disabled via ChronicleLog:Disable().
---@param eventType string Event type code (SWING, CAST, DEATH, COMBAT_START, COMBAT_END, RAW)
-- PERF: one reused table assembles every line (was a new table per line)
local writeParts = {}
function ChronicleLog:Write(eventType, ...)
-- Millisecond timestamp: combine GetTime() precision with unix offset
local timestamp = math.floor((GetTime() + self.timeOffset) * 1000)
local parts = writeParts
parts[1] = timestamp
parts[2] = eventType
local count = 2
for i = 1, arg.n do
local v = arg[i]
count = count + 1
parts[count] = v ~= nil and tostring(v) or ""
end
local line = table.concat(parts, LOG_SEP, 1, count)
-- Append to in-memory buffer
self.bufferSize = self.bufferSize + 1
self.buffer[self.bufferSize] = line
end
-- -----------------------------------------------------------------------------
-- Fixed-arity writers: ChronicleLog:WriteN(eventType, a1, ..., aN)
--
-- Same output as ChronicleLog:Write, byte for byte, but without the Lua 5.0
-- vararg table ("arg") that every call to a function declared with "..."
-- allocates, and without assembling the line in a table: the line is built
-- with a single ".." chain. Write() is kept for callers outside the hot paths.
-- N is the number of fields after the event type, counted exactly like
-- arg.n in Write: a trailing nil argument still writes an empty field.
-- -----------------------------------------------------------------------------
--- Text of one field, as Write() would produce it (nil -> "").
--- Strings and numbers are returned as they are: ".." formats numbers exactly
--- like tostring() does.
local function F(v)
if v == nil then return "" end
local t = type(v)
if t == "string" or t == "number" then return v end
return tostring(v)
end
local floor = math.floor
local function Push(self, line)
self.bufferSize = self.bufferSize + 1
self.buffer[self.bufferSize] = line
end
function ChronicleLog:Write0(eventType)
Push(self, floor((GetTime() + self.timeOffset) * 1000) .. LOG_SEP .. eventType)
end
function ChronicleLog:Write1(eventType, a1)
Push(self, floor((GetTime() + self.timeOffset) * 1000) .. LOG_SEP .. eventType .. LOG_SEP .. F(a1))
end
function ChronicleLog:Write2(eventType, a1, a2)
Push(self, floor((GetTime() + self.timeOffset) * 1000) .. LOG_SEP .. eventType .. LOG_SEP .. F(a1) .. LOG_SEP .. F(a2))
end
function ChronicleLog:Write3(eventType, a1, a2, a3)
Push(self, floor((GetTime() + self.timeOffset) * 1000) .. LOG_SEP .. eventType .. LOG_SEP .. F(a1) .. LOG_SEP .. F(a2) .. LOG_SEP .. F(a3))
end
function ChronicleLog:Write4(eventType, a1, a2, a3, a4)
Push(self, floor((GetTime() + self.timeOffset) * 1000) .. LOG_SEP .. eventType .. LOG_SEP .. F(a1) .. LOG_SEP .. F(a2) .. LOG_SEP .. F(a3) .. LOG_SEP .. F(a4))
end
function ChronicleLog:Write5(eventType, a1, a2, a3, a4, a5)
Push(self, floor((GetTime() + self.timeOffset) * 1000) .. LOG_SEP .. eventType .. LOG_SEP .. F(a1) .. LOG_SEP .. F(a2) .. LOG_SEP .. F(a3) .. LOG_SEP .. F(a4) .. LOG_SEP .. F(a5))
end
function ChronicleLog:Write6(eventType, a1, a2, a3, a4, a5, a6)
Push(self, floor((GetTime() + self.timeOffset) * 1000) .. LOG_SEP .. eventType .. LOG_SEP .. F(a1) .. LOG_SEP .. F(a2) .. LOG_SEP .. F(a3) .. LOG_SEP .. F(a4) .. LOG_SEP .. F(a5) .. LOG_SEP .. F(a6))
end
function ChronicleLog:Write7(eventType, a1, a2, a3, a4, a5, a6, a7)
Push(self, floor((GetTime() + self.timeOffset) * 1000) .. LOG_SEP .. eventType .. LOG_SEP .. F(a1) .. LOG_SEP .. F(a2) .. LOG_SEP .. F(a3) .. LOG_SEP .. F(a4) .. LOG_SEP .. F(a5) .. LOG_SEP .. F(a6) .. LOG_SEP .. F(a7))
end
function ChronicleLog:Write8(eventType, a1, a2, a3, a4, a5, a6, a7, a8)
Push(self, floor((GetTime() + self.timeOffset) * 1000) .. LOG_SEP .. eventType .. LOG_SEP .. F(a1) .. LOG_SEP .. F(a2) .. LOG_SEP .. F(a3) .. LOG_SEP .. F(a4) .. LOG_SEP .. F(a5) .. LOG_SEP .. F(a6) .. LOG_SEP .. F(a7) .. LOG_SEP .. F(a8))
end
function ChronicleLog:Write9(eventType, a1, a2, a3, a4, a5, a6, a7, a8, a9)
Push(self, floor((GetTime() + self.timeOffset) * 1000) .. LOG_SEP .. eventType .. LOG_SEP .. F(a1) .. LOG_SEP .. F(a2) .. LOG_SEP .. F(a3) .. LOG_SEP .. F(a4) .. LOG_SEP .. F(a5) .. LOG_SEP .. F(a6) .. LOG_SEP .. F(a7) .. LOG_SEP .. F(a8) .. LOG_SEP .. F(a9))
end
function ChronicleLog:Write10(eventType, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10)
Push(self, floor((GetTime() + self.timeOffset) * 1000) .. LOG_SEP .. eventType .. LOG_SEP .. F(a1) .. LOG_SEP .. F(a2) .. LOG_SEP .. F(a3) .. LOG_SEP .. F(a4) .. LOG_SEP .. F(a5) .. LOG_SEP .. F(a6) .. LOG_SEP .. F(a7) .. LOG_SEP .. F(a8) .. LOG_SEP .. F(a9) .. LOG_SEP .. F(a10))
end
function ChronicleLog:Write11(eventType, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11)
Push(self, floor((GetTime() + self.timeOffset) * 1000) .. LOG_SEP .. eventType .. LOG_SEP .. F(a1) .. LOG_SEP .. F(a2) .. LOG_SEP .. F(a3) .. LOG_SEP .. F(a4) .. LOG_SEP .. F(a5) .. LOG_SEP .. F(a6) .. LOG_SEP .. F(a7) .. LOG_SEP .. F(a8) .. LOG_SEP .. F(a9) .. LOG_SEP .. F(a10) .. LOG_SEP .. F(a11))
end
function ChronicleLog:Write12(eventType, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12)
Push(self, floor((GetTime() + self.timeOffset) * 1000) .. LOG_SEP .. eventType .. LOG_SEP .. F(a1) .. LOG_SEP .. F(a2) .. LOG_SEP .. F(a3) .. LOG_SEP .. F(a4) .. LOG_SEP .. F(a5) .. LOG_SEP .. F(a6) .. LOG_SEP .. F(a7) .. LOG_SEP .. F(a8) .. LOG_SEP .. F(a9) .. LOG_SEP .. F(a10) .. LOG_SEP .. F(a11) .. LOG_SEP .. F(a12))
end
--- Clears the in-memory buffer.
function ChronicleLog:ClearBuffer()
self.buffer = {}
self.bufferSize = 0
end
--- Returns the current buffer size (number of log lines).
---@return number size Number of lines in buffer
function ChronicleLog:GetBufferSize()
return self.bufferSize
end
--- Writes the in-memory buffer to a file and clears the buffer.
--- Appends to existing file content using native append mode.
--- Filename: see ChronicleLog:GetLogFilename()
---@return number linesWritten Number of new lines written
-- PERF: the file content is exactly the same as before, but
-- * the header and the lines are appended separately instead of building
-- header .. "\n" .. content .. "\n" (two extra copies of the whole buffer);
-- * a combat-end auto save (deferred = true) hands the buffer to a background
-- writer that appends FLUSH_CHUNK_LINES lines per frame. Any other save
-- (loading screen, logout, /reload, /chron save, file change...) first
-- finishes that pending write, so the order of the lines is unchanged.
function ChronicleLog:FlushToFile(deferred)
self:FinishPendingFlush()
if self.bufferSize == 0 then
return 0
end
-- Generate header line to prepend (timestamp 0 since it covers the whole flush)
local header = "0" .. LOG_SEP .. self:GenerateHeader()
-- Generate filename based on character name and realm
local filename = self:GetLogFilename()
local written = self.bufferSize
local ok, err = ChronicleFile:AppendToFile(filename, header .. "\n")
if ok then
-- the lines always go through the block writer; a non-deferred save
-- just finishes it right away
self.pendingFlush = { lines = self.buffer, n = written, pos = 1, filename = filename }
self.buffer = {}
self.bufferSize = 0
if not deferred then
self:FinishPendingFlush()
end
end
if ok then
Chronicle:DebugPrint("Appended " .. written .. " lines to " .. filename)
else
Chronicle:Print("Failed to write: " .. (err or "unknown error"))
self:ClearBuffer()
end
return written
end
--- Appends up to `maxLines` lines of the pending (deferred) save, one write
--- per block of FLUSH_BLOCK_LINES lines (or, with `join`, one write per
--- FINISH_JOIN_BLOCKS blocks).
function ChronicleLog:DrainPendingFlush(maxLines, join)
local p = self.pendingFlush
if not p then return end
local lines, pos = p.lines, p.pos
local stop = pos + maxLines - 1
if stop > p.n then stop = p.n end
local ok, err = true, nil
local nj = 0
while pos <= stop do
local count = stop - pos + 1
if count > FLUSH_BLOCK_LINES then count = FLUSH_BLOCK_LINES end
local block = GetBlockWriter(count)(lines, pos)
pos = pos + count
if join then
nj = nj + 1
joinScratch[nj] = block
if nj == FINISH_JOIN_BLOCKS or pos > stop then
block = GetBlockJoiner(nj)(joinScratch)
for k = 1, nj do joinScratch[k] = nil end
nj = 0
else
block = nil
end
end
if block then
local wok, werr = ChronicleFile:AppendToFile(p.filename, block)
if not wok and ok then ok, err = false, werr end
end
end
if not ok then
Chronicle:Print("Failed to write: " .. (err or "unknown error"))
end
p.pos = pos
if p.pos > p.n then
self.pendingFlush = nil
end
end
--- Writes what is left of a pending (deferred) save right away.
function ChronicleLog:FinishPendingFlush()
while self.pendingFlush do
self:DrainPendingFlush(1000000, true)
end
end
-- =============================================================================
-- Raid Group Composition
-- =============================================================================
--- Clears session-only raid composition state and cancels pending captures.
function ChronicleLog:ResetRaidGroupCapture()
self.raidGroupPayload = nil
self.raidGroupCapturePending = false
self.raidGroupCaptureAt = nil
self.raidGroupCaptureReason = nil
self.raidGroupForceCapture = false
self.raidGroupRetryCount = 0
end
--- Schedules a raid composition capture on this frame or after a short delay.
---@param delay number Delay in seconds
---@param reason string Event that requested the snapshot
---@param force boolean Whether to emit a complete raid snapshot even if unchanged
function ChronicleLog:ScheduleRaidGroupCapture(delay, reason, force)
if not self.enabled then return end
local captureAt = GetTime() + (delay or 0)
if not self.raidGroupCapturePending or not self.raidGroupCaptureAt or captureAt < self.raidGroupCaptureAt then
self.raidGroupCaptureAt = captureAt
end
self.raidGroupCapturePending = true
self.raidGroupCaptureReason = reason or self.raidGroupCaptureReason or "UNKNOWN"
if force then
self.raidGroupForceCapture = true
end
end
--- Debounces a burst of roster events until no new event arrives during the delay.
---@param delay number Delay in seconds
---@param reason string Event that requested the snapshot
function ChronicleLog:DebounceRaidGroupCapture(delay, reason)
if not self.enabled then return end
self.raidGroupCapturePending = true
self.raidGroupCaptureAt = GetTime() + (delay or 0)
self.raidGroupCaptureReason = reason or "UNKNOWN"
end
--- Runs a scheduled raid composition capture when its deadline is reached.
---@param now number Current GetTime() value
function ChronicleLog:ProcessScheduledRaidGroupCapture(now)
if not self.raidGroupCapturePending or not self.raidGroupCaptureAt then return end
if now < self.raidGroupCaptureAt then return end
local reason = self.raidGroupCaptureReason or "UNKNOWN"
local force = self.raidGroupForceCapture
self.raidGroupCapturePending = false
self.raidGroupCaptureAt = nil
self.raidGroupCaptureReason = nil
self.raidGroupForceCapture = false
self:CaptureRaidGroup(reason, force)
end
--- Builds a raid composition in ascending roster-index order.
---@return string payload Semicolon-separated guid,raidIndex,subgroup,rank mappings, or nil while incomplete
---@return number memberCount Current raid size
---@return boolean inRaid Whether the player currently has raid members
function ChronicleLog:BuildRaidGroupPayload()
local members = {}
local memberCount = GetNumRaidMembers() or 0
if memberCount <= 0 then
return "", 0, false
end
for raidIndex = 1, memberCount do
local name, rank, subgroup = GetRaidRosterInfo(raidIndex)
local guid = GetUnitGUID("raid" .. raidIndex)
if not name or rank == nil or not subgroup or subgroup < 1 or subgroup > 8 or not guid then
return nil, memberCount, true
end
members[raidIndex] = table.concat({ guid, raidIndex, subgroup, rank }, ",")
end
return table.concat(members, ";"), memberCount, true
end
--- Captures and emits the raid composition when changed or explicitly forced.
---@param reason string Event that requested the snapshot
---@param force boolean Whether to emit a complete raid snapshot even if unchanged
function ChronicleLog:CaptureRaidGroup(reason, force)
if not self.enabled then return end
local payload, memberCount, inRaid = self:BuildRaidGroupPayload()
if not payload then
if inRaid and self.raidGroupRetryCount < RAID_GROUP_MAX_RETRIES then
self.raidGroupRetryCount = self.raidGroupRetryCount + 1
self:ScheduleRaidGroupCapture(RAID_GROUP_RETRY_DELAY, reason, force)
end
return
end
self.raidGroupRetryCount = 0
local snapshot = memberCount .. LOG_SEP .. payload
-- Do not write an empty baseline when logging starts outside a raid. If a
-- previously logged raid disbands, the changed empty snapshot is emitted once.
if not inRaid and self.raidGroupPayload == nil then
self.raidGroupPayload = snapshot
return
end
if snapshot ~= self.raidGroupPayload or (force and inRaid) then
self:Write3("RAID_COMPOSITION", reason, memberCount, payload)
self.raidGroupPayload = snapshot
end
end
--- Debounces raid roster bursts so only the final stable composition is captured.
function ChronicleLog:RAID_ROSTER_UPDATE()
self.raidGroupRetryCount = 0
self:DebounceRaidGroupCapture(RAID_GROUP_DEBOUNCE_DELAY, "RAID_ROSTER_UPDATE")
end
--- Handles raid conversion and disband notifications through the same debounce path.
function ChronicleLog:PARTY_MEMBERS_CHANGED()
self.raidGroupRetryCount = 0
self:DebounceRaidGroupCapture(RAID_GROUP_DEBOUNCE_DELAY, "PARTY_MEMBERS_CHANGED")
end
-- =============================================================================
-- Event Handlers
-- =============================================================================
--- Handles ZONE_CHANGED_NEW_AREA events every time the zone changes.
--- Handles auto-enable/disable and reminder popups, then logs zone info.
function ChronicleLog:ZONE_CHANGED_NEW_AREA()
-- Close options panel on zone change (avoids stale state display)
if self.optionsPanel and self.optionsPanel:IsShown() then
self.optionsPanel:Hide()
end
-- Switch to the file of the new zone (per character / instance / day).
-- Lines buffered before the zone change are flushed to the previous file first.
self:UpdateLogFilename()
-- Get zone name and find instance ID from saved instances
local zoneName = GetRealZoneText() or ""
local zoneLower = strlower(zoneName)
local instanceId = 0
for i = 1, GetNumSavedInstances() do
local instanceName, savedId = GetSavedInstanceInfo(i)
if zoneLower == strlower(instanceName) then
instanceId = savedId
break
end
end
local inInstance, instanceType = self:IsInInstance()
local isInInstance = inInstance and true or false
local isRaid = instanceType == "raid"
local isDungeon = instanceType == "party"
-- Check auto-enable settings
local autoEnableRaid = self:GetSetting("autoEnableInRaid")
local autoEnableDungeon = self:GetSetting("autoEnableInDungeon")
local showReminder = self:GetSetting("showLogReminder")
local logging = self:IsEnabled()
-- Debug output
Chronicle:DebugPrint("Zone: " .. zoneName .. ", inInstance: " .. tostring(isInInstance) .. ", type: " .. tostring(instanceType))
Chronicle:DebugPrint("autoRaid: " .. tostring(autoEnableRaid) .. ", autoDungeon: " .. tostring(autoEnableDungeon) .. ", showReminder: " .. tostring(showReminder) .. ", logging: " .. tostring(logging))
if isInInstance then
-- Entering an instance
local shouldAutoEnable = (isRaid and autoEnableRaid) or (isDungeon and autoEnableDungeon)
if shouldAutoEnable then
if not logging then
self:Enable()
Chronicle:Print("ChronicleLog enabled (entered " .. (isRaid and "raid" or "dungeon") .. ")")
end
elseif showReminder and not logging then
-- Show reminder popup
StaticPopupDialogs["CHRONICLELOG_ENABLE_REMINDER"] = {
text = "You entered an instance but ChronicleLog is disabled. Enable logging?",
button1 = "Enable",
button2 = "No",
OnAccept = function()
ChronicleLog:Enable()
Chronicle:Print("ChronicleLog enabled.")
end,
timeout = 30,
whileDead = true,
hideOnEscape = true,
}
StaticPopup_Show("CHRONICLELOG_ENABLE_REMINDER")
end
else
-- Leaving an instance
local wasAutoEnabled = (autoEnableRaid or autoEnableDungeon)
if wasAutoEnabled and logging then
self:Disable()
Chronicle:Print("ChronicleLog disabled (left instance)")
elseif showReminder and logging then
-- Show reminder popup
StaticPopupDialogs["CHRONICLELOG_DISABLE_REMINDER"] = {
text = "You left the instance but ChronicleLog is still enabled. Disable logging?",
button1 = "Disable",
button2 = "No",
OnAccept = function()
ChronicleLog:Disable()
Chronicle:Print("ChronicleLog disabled.")
end,
timeout = 30,
whileDead = true,
hideOnEscape = true,
}
StaticPopup_Show("CHRONICLELOG_DISABLE_REMINDER")
end
end
-- Log zone info and purge units if enabled
self:WriteZoneInfo(true)
if self:IsEnabled() then
self:PurgeUnits()
self:PurgeTalentCache()
if isRaid then
-- Zone boundaries need a complete snapshot even when the roster is unchanged.
self:ScheduleRaidGroupCapture(0, "ZONE_CHANGED_NEW_AREA", true)
end
end
end
--- Writes zone info to the log buffer.
--- Call this after clearing logs to provide context for new entries.
function ChronicleLog:WriteZoneInfo(force)
if not force and not self:IsEnabled() then return end
local zoneName = GetRealZoneText() or ""
local zoneLower = strlower(zoneName)
local instanceId = 0
for i = 1, GetNumSavedInstances() do
local instanceName, savedId = GetSavedInstanceInfo(i)
if zoneLower == strlower(instanceName) then
instanceId = savedId
break
end
end
local inInstance, instanceType = self:IsInInstance()
local inInstanceNum = inInstance and 1 or 0
instanceType = instanceType or "none"
local isGhost = UnitIsGhost("player") and 1 or 0
if inInstance and instanceType == 'raid' then
-- Check for stale instance ID (different raid lockout)
local lastId = ChronicleCompanionCharDB.lastInstanceIds[zoneLower]
if lastId and lastId > 0 then
-- We are saved to something. Now detect if we are in that save, or a new one.
if instanceId ~= lastId then
StaticPopup_Show("CHRONICLELOG_STALE_INSTANCE", zoneName)
end
end
-- Always save the latest
ChronicleCompanionCharDB.lastInstanceIds[zoneLower] = instanceId
end
self:WriteHeader()
-- The value after zoneName is Chronicle's internal instance ID slot: keep it empty.
-- mapId (Map.dbc id, e.g. 309 for Zul'Gurub) is appended as a new last field.
-- Only ClassicAPI exposes it (GetInstanceInfo, 8th value); empty otherwise.
local mapId = ""
if GetInstanceInfo then
local ok, _, _, _, _, _, _, _, id = pcall(GetInstanceInfo)
if ok and id then mapId = id end
end
self:Write6("ZONE_INFO", zoneName, "", inInstanceNum, instanceType, isGhost, mapId)
end
--- Updates the saved instance ID for the current zone.
--- Called on combat end to pick up newly-acquired lockout IDs (e.g. after first boss kill).
--- No popup logic — just a silent DB write.
function ChronicleLog:UpdateInstanceId()
local inInstance, instanceType = self:IsInInstance()
if not inInstance or instanceType ~= 'raid' then return end
local zoneName = GetRealZoneText() or ""
local zoneLower = strlower(zoneName)
for i = 1, GetNumSavedInstances() do
local instanceName, savedId = GetSavedInstanceInfo(i)
if zoneLower == strlower(instanceName) then
ChronicleCompanionCharDB.lastInstanceIds[zoneLower] = savedId
return
end
end
end
--- Handles UNIT_CASTEVENT events.
--- Called when a unit starts, finishes, fails, or channels a cast.
--- Also fires for melee swings (MAINHAND/OFFHAND).
--- Writes a CAST event with caster, target, event type, spell ID, and duration.
---@param casterGUID string GUID of the caster
---@param targetGUID string GUID of the target (may be empty)
---@param eventType string "START", "CAST", "FAIL", "CHANNEL", "MAINHAND", "OFFHAND"
---@param spellId number Spell ID
---@param duration number Cast duration in milliseconds
function ChronicleLog:UNIT_CASTEVENT(casterGUID, targetGUID, eventType, spellId, duration)
self:Write5("CAST", casterGUID, targetGUID, eventType, spellId, duration)
end
--- Handles UNIT_DIED events.
--- Called when any unit dies.
--- Writes a DEATH event with the unit's GUID.
---@param guid string GUID of the unit that died
function ChronicleLog:UNIT_DIED(guid)
self:CheckUnit(guid)
self:Write1("DEATH", guid)
end
--- Handles RAID_TARGET_UPDATE events.
--- Called when raid target icons are set or removed on units.
--- Payload: No args. The event is just a signal. Use GetRaidTargetIndex(unit) to
--- query current marks on units (returns 1-8 for icons, nil for no mark).
--- TODO: Implement by scanning raid/party targets on fire, logging mark changes.
-- function ChronicleLog:RAID_TARGET_UPDATE()
-- self:Write("RAID_TARGET")
-- end
--- Handles PLAYER_REGEN_DISABLED events.
--- Called when the player enters combat (loses regen).
--- Writes a COMBAT_START event with no additional fields.
function ChronicleLog:PLAYER_REGEN_DISABLED()
self:Write0("COMBAT_START")
end
--- Handles PLAYER_REGEN_ENABLED events.
--- Called when the player leaves combat (regains regen).
--- Writes a COMBAT_END event with no additional fields.
function ChronicleLog:PLAYER_REGEN_ENABLED()
self:Write0("COMBAT_END")
self:UpdateInstanceId()
-- Keep the raid's log session alive (see SESSION_TIMEOUT)
self:TouchLogSession()
end
--- Handles AUTO_ATTACK_SELF events.
--- Called when the active player's auto attack damage is processed.
--- Requires CVar: /run SetCVar("NP_EnableAutoAttackEvents", 1)
--- Writes a SWING event with all attack details.
---@param attackerGuid string Attacker GUID (e.g., "0xF5300000000000A5")
---@param targetGuid string Target GUID
---@param totalDamage number Total damage dealt
---@param hitInfo number Bitfield containing hit flags (critical, glancing, crushing, etc.)
---@param victimState number State of victim after attack (dodged, parried, blocked, etc.)
---@param subDamageCount number Number of damage components (1-3, for elemental weapons)
---@param blockedAmount number Amount of damage blocked
---@param totalAbsorb number Total damage absorbed
---@param totalResist number Total damage resisted
function ChronicleLog:AUTO_ATTACK_SELF(attackerGuid, targetGuid, totalDamage, hitInfo, victimState, subDamageCount, blockedAmount, totalAbsorb, totalResist)
self:CheckUnit(attackerGuid)
self:CheckUnit(targetGuid)
self:Write9("SWING", attackerGuid, targetGuid, totalDamage, hitInfo, victimState, subDamageCount, blockedAmount, totalAbsorb, totalResist)
end
--- Handles AUTO_ATTACK_OTHER events.
--- Called when someone other than the active player's auto attack damage is processed.
--- Requires CVar: /run SetCVar("NP_EnableAutoAttackEvents", 1)
--- Writes a SWING event with all attack details.
--- https://gitea.com/avitasia/nampower/src/branch/master/EVENTS.md#auto_attack_self-and-auto_attack_other
---@param attackerGuid string Attacker GUID (e.g., "0xF5300000000000A5")
---@param targetGuid string Target GUID
---@param totalDamage number Total damage dealt
---@param hitInfo number Bitfield containing hit flags (critical, glancing, crushing, etc.)
---@param victimState number State of victim after attack (dodged, parried, blocked, etc.)
---@param subDamageCount number Number of damage components (1-3, for elemental weapons)
---@param blockedAmount number Amount of damage blocked
---@param totalAbsorb number Total damage absorbed
---@param totalResist number Total damage resisted
function ChronicleLog:AUTO_ATTACK_OTHER(attackerGuid, targetGuid, totalDamage, hitInfo, victimState, subDamageCount, blockedAmount, totalAbsorb, totalResist)
self:CheckUnit(attackerGuid)
self:CheckUnit(targetGuid)
self:Write9("SWING", attackerGuid, targetGuid, totalDamage, hitInfo, victimState, subDamageCount, blockedAmount, totalAbsorb, totalResist)
end
--- Handles SPELL_HEAL_BY_SELF events.
--- Called when the active player casts a heal on any target.
--- Requires CVar: SetCVar("NP_EnableSpellHealEvents", 1)
--- Writes a HEAL event with target, caster, spell, amount, and flags.
--- Note: Can fire alongside SPELL_HEAL_ON_SELF if you heal yourself.
--- https://gitea.com/avitasia/nampower/src/branch/master/EVENTS.md#spell_heal_by_self-spell_heal_by_other-and-spell_heal_on_self
---@param targetGuid string GUID of the heal target
---@param casterGuid string GUID of the healer (active player)
---@param spellId number Spell ID that caused the heal
---@param amount number Amount healed
---@param critical number 1 if critical heal, 0 otherwise
---@param periodic number 1 if from periodic aura (HoT tick), 0 otherwise
function ChronicleLog:SPELL_HEAL_BY_SELF(targetGuid, casterGuid, spellId, amount, critical, periodic)
self:CheckUnit(targetGuid)
self:CheckUnit(casterGuid)
self:Write6("HEAL", targetGuid, casterGuid, spellId, amount, critical, periodic)
end
--- Handles SPELL_HEAL_BY_OTHER events.
--- Called when someone other than the active player casts a heal.
--- Requires CVar: SetCVar("NP_EnableSpellHealEvents", 1)
--- Writes a HEAL event with target, caster, spell, amount, and flags.
--- https://gitea.com/avitasia/nampower/src/branch/master/EVENTS.md#spell_heal_by_self-spell_heal_by_other-and-spell_heal_on_self
---@param targetGuid string GUID of the heal target
---@param casterGuid string GUID of the healer
---@param spellId number Spell ID that caused the heal
---@param amount number Amount healed
---@param critical number 1 if critical heal, 0 otherwise
---@param periodic number 1 if from periodic aura (HoT tick), 0 otherwise
function ChronicleLog:SPELL_HEAL_BY_OTHER(targetGuid, casterGuid, spellId, amount, critical, periodic)
self:CheckUnit(targetGuid)
self:CheckUnit(casterGuid)
self:Write6("HEAL", targetGuid, casterGuid, spellId, amount, critical, periodic)
end
--- Handles SPELL_HEAL_ON_SELF events.
--- Called when the active player receives a heal from any source.
--- Requires CVar: SetCVar("NP_EnableSpellHealEvents", 1)
--- Writes a HEAL event with target, caster, spell, amount, and flags.
--- Note: Can fire alongside SPELL_HEAL_BY_SELF if you heal yourself.
--- https://gitea.com/avitasia/nampower/src/branch/master/EVENTS.md#spell_heal_by_self-spell_heal_by_other-and-spell_heal_on_self
---@param targetGuid string GUID of the heal target (active player)
---@param casterGuid string GUID of the healer
---@param spellId number Spell ID that caused the heal
---@param amount number Amount healed
---@param critical number 1 if critical heal, 0 otherwise
---@param periodic number 1 if from periodic aura (HoT tick), 0 otherwise
function ChronicleLog:SPELL_HEAL_ON_SELF(targetGuid, casterGuid, spellId, amount, critical, periodic)
-- self:CheckUnit(targetGuid)
-- self:CheckUnit(casterGuid)
-- Caught by the other
-- self:Write("HEAL", targetGuid, casterGuid, spellId, amount, critical, periodic)
end
--- Handles SPELL_ENERGIZE_BY_SELF events.
--- Called when the active player restores power (mana, rage, energy, etc.) to any target.
--- Requires CVar: SetCVar("NP_EnableSpellEnergizeEvents", 1)
--- Writes an ENERGIZE event with target, caster, spell, power type, amount, and flags.
--- Note: Can fire alongside SPELL_ENERGIZE_ON_SELF if you restore power to yourself.
--- Power types: 0=Mana, 1=Rage, 2=Focus, 3=Energy, 4=Happiness, -2=Health
--- https://gitea.com/avitasia/nampower/src/branch/master/EVENTS.md#spell_energize_by_self-spell_energize_by_other-and-spell_energize_on_self
---@param targetGuid string GUID of the power recipient
---@param casterGuid string GUID of the caster (active player)
---@param spellId number Spell ID that caused the energize
---@param powerType number Power type (0=Mana, 1=Rage, 2=Focus, 3=Energy, 4=Happiness, -2=Health)
---@param amount number Amount of power restored
---@param periodic number 1 if from periodic aura, 0 otherwise
function ChronicleLog:SPELL_ENERGIZE_BY_SELF(targetGuid, casterGuid, spellId, powerType, amount, periodic)
self:CheckUnit(targetGuid)
self:CheckUnit(casterGuid)
self:Write6("ENERGIZE", targetGuid, casterGuid, spellId, powerType, amount, periodic)
end
--- Handles SPELL_ENERGIZE_BY_OTHER events.
--- Called when someone other than the active player restores power.
--- Requires CVar: SetCVar("NP_EnableSpellEnergizeEvents", 1)
--- Writes an ENERGIZE event with target, caster, spell, power type, amount, and flags.
--- Power types: 0=Mana, 1=Rage, 2=Focus, 3=Energy, 4=Happiness, -2=Health
--- https://gitea.com/avitasia/nampower/src/branch/master/EVENTS.md#spell_energize_by_self-spell_energize_by_other-and-spell_energize_on_self
---@param targetGuid string GUID of the power recipient
---@param casterGuid string GUID of the caster
---@param spellId number Spell ID that caused the energize
---@param powerType number Power type (0=Mana, 1=Rage, 2=Focus, 3=Energy, 4=Happiness, -2=Health)
---@param amount number Amount of power restored
---@param periodic number 1 if from periodic aura, 0 otherwise
function ChronicleLog:SPELL_ENERGIZE_BY_OTHER(targetGuid, casterGuid, spellId, powerType, amount, periodic)
self:CheckUnit(targetGuid)
self:CheckUnit(casterGuid)
self:Write6("ENERGIZE", targetGuid, casterGuid, spellId, powerType, amount, periodic)
end
--- Handles SPELL_ENERGIZE_ON_SELF events.
--- Called when the active player receives power restoration from any source.
--- Requires CVar: SetCVar("NP_EnableSpellEnergizeEvents", 1)
--- Writes an ENERGIZE event with target, caster, spell, power type, amount, and flags.
--- Note: Can fire alongside SPELL_ENERGIZE_BY_SELF if you restore power to yourself.
--- Power types: 0=Mana, 1=Rage, 2=Focus, 3=Energy, 4=Happiness, -2=Health
--- https://gitea.com/avitasia/nampower/src/branch/master/EVENTS.md#spell_energize_by_self-spell_energize_by_other-and-spell_energize_on_self
---@param targetGuid string GUID of the power recipient (active player)
---@param casterGuid string GUID of the caster
---@param spellId number Spell ID that caused the energize
---@param powerType number Power type (0=Mana, 1=Rage, 2=Focus, 3=Energy, 4=Happiness, -2=Health)
---@param amount number Amount of power restored
---@param periodic number 1 if from periodic aura, 0 otherwise
function ChronicleLog:SPELL_ENERGIZE_ON_SELF(targetGuid, casterGuid, spellId, powerType, amount, periodic)
-- self:CheckUnit(targetGuid)
-- self:CheckUnit(casterGuid)
-- self:Write("ENERGIZE", targetGuid, casterGuid, spellId, powerType, amount, periodic)
end
--- Handles SPELL_MISS_SELF events.
--- Called when the active player's spell misses, is resisted, dodged, parried, etc.
--- Triggered by SMSG_SPELL_GO, SMSG_SPELLLOGMISS, SMSG_PROCRESIST, SMSG_SPELLORDAMAGE_IMMUNE.
--- Writes a MISS event with caster, target, spell ID, and miss type.
--- Miss types: 0=None, 1=Miss, 2=Resist, 3=Dodge, 4=Parry, 5=Block, 6=Evade,
--- 7=Immune, 8=Immune2, 9=Deflect, 10=Absorb, 11=Reflect
---@param casterGuid string GUID of the caster (active player)
---@param targetGuid string GUID of the target
---@param spellId number Spell ID that missed
---@param missInfo number Miss type (see SpellMissInfo constants)
function ChronicleLog:SPELL_MISS_SELF(casterGuid, targetGuid, spellId, missInfo)
self:CheckUnit(casterGuid)
self:CheckUnit(targetGuid)
self:Write4("MISS", casterGuid, targetGuid, spellId, missInfo)
end
--- Handles SPELL_MISS_OTHER events.
--- Called when someone other than the active player's spell misses, is resisted, etc.
--- Triggered by SMSG_SPELL_GO, SMSG_SPELLLOGMISS, SMSG_PROCRESIST, SMSG_SPELLORDAMAGE_IMMUNE.
--- Writes a MISS event with caster, target, spell ID, and miss type.
--- Miss types: 0=None, 1=Miss, 2=Resist, 3=Dodge, 4=Parry, 5=Block, 6=Evade,
--- 7=Immune, 8=Immune2, 9=Deflect, 10=Absorb, 11=Reflect
---@param casterGuid string GUID of the caster
---@param targetGuid string GUID of the target
---@param spellId number Spell ID that missed
---@param missInfo number Miss type (see SpellMissInfo constants)
function ChronicleLog:SPELL_MISS_OTHER(casterGuid, targetGuid, spellId, missInfo)
self:CheckUnit(casterGuid)
self:CheckUnit(targetGuid)
self:Write4("MISS", casterGuid, targetGuid, spellId, missInfo)
end
--- Handles SPELL_DISPEL_BY_SELF events.
--- Called when the active player dispels a spell from a unit.
--- Writes a DISPEL event with caster, target, and dispelled spell ID.
---@param casterGuid string GUID of the caster (active player) who performed the dispel
---@param targetGuid string GUID of the unit that was dispelled
---@param spellId number Spell ID of the spell that was dispelled
function ChronicleLog:SPELL_DISPEL_BY_SELF(casterGuid, targetGuid, spellId)
if not spellId or spellId == 0 then return end
self:CheckUnit(casterGuid)
self:CheckUnit(targetGuid)
self:Write3("DISPEL", casterGuid, targetGuid, spellId)
end
--- Handles SPELL_DISPEL_BY_OTHER events.
--- Called when someone other than the active player dispels a spell from a unit.
--- Writes a DISPEL event with caster, target, and dispelled spell ID.
---@param casterGuid string GUID of the unit that performed the dispel
---@param targetGuid string GUID of the unit that was dispelled
---@param spellId number Spell ID of the spell that was dispelled
function ChronicleLog:SPELL_DISPEL_BY_OTHER(casterGuid, targetGuid, spellId)
if not spellId or spellId == 0 then return end
self:CheckUnit(casterGuid)
self:CheckUnit(targetGuid)
self:Write3("DISPEL", casterGuid, targetGuid, spellId)
end
--- Handles ENVIRONMENTAL_DMG_SELF events.
--- Called when the active player takes environmental damage.
--- Writes an ENV_DMG event with unit, damage type, amount, absorb, and resist.
--- Damage types: 0=Exhausted/Fatigue, 1=Drowning, 2=Fall, 3=Lava, 4=Slime, 5=Fire, 6=FallToVoid
---@param unitGuid string GUID of the unit that took damage (active player)
---@param dmgType number Environmental damage type (see EnvironmentalDamageType)
---@param damage number Amount of damage taken
---@param absorb number Amount of damage absorbed
---@param resist number Amount of damage resisted
function ChronicleLog:ENVIRONMENTAL_DMG_SELF(unitGuid, dmgType, damage, absorb, resist)
self:CheckUnit(unitGuid)
self:Write5("ENV_DMG", unitGuid, dmgType, damage, absorb, resist)
end
--- Handles ENVIRONMENTAL_DMG_OTHER events.
--- Called when a unit other than the active player takes environmental damage.
--- Writes an ENV_DMG event with unit, damage type, amount, absorb, and resist.
--- Damage types: 0=Exhausted/Fatigue, 1=Drowning, 2=Fall, 3=Lava, 4=Slime, 5=Fire, 6=FallToVoid
---@param unitGuid string GUID of the unit that took damage
---@param dmgType number Environmental damage type (see EnvironmentalDamageType)
---@param damage number Amount of damage taken
---@param absorb number Amount of damage absorbed
---@param resist number Amount of damage resisted
function ChronicleLog:ENVIRONMENTAL_DMG_OTHER(unitGuid, dmgType, damage, absorb, resist)
self:CheckUnit(unitGuid)
self:Write5("ENV_DMG", unitGuid, dmgType, damage, absorb, resist)
end
--- Handles DAMAGE_SHIELD_SELF events.
--- Called when the active player's damage shield (e.g. Thorns, Fire Shield) deals damage.
--- Writes a DMG_SHIELD event with shield owner, attacker, damage, and spell school.
--- Spell schools: 0=Physical, 1=Holy, 2=Fire, 3=Nature, 4=Frost, 5=Shadow, 6=Arcane
---@param unitGuid string GUID of the unit whose shield dealt damage (active player)
---@param targetGuid string GUID of the attacker who took the shield damage
---@param damage number Amount of shield damage dealt
---@param spellSchool number School of the shield damage (see SpellSchool constants)
function ChronicleLog:DAMAGE_SHIELD_SELF(unitGuid, targetGuid, damage, spellSchool)
self:CheckUnit(unitGuid)
self:CheckUnit(targetGuid)
self:Write4("DMG_SHIELD", unitGuid, targetGuid, damage, spellSchool)
end
--- Handles DAMAGE_SHIELD_OTHER events.
--- Called when another unit's damage shield (e.g. Thorns, Fire Shield) deals damage.
--- Writes a DMG_SHIELD event with shield owner, attacker, damage, and spell school.
--- Spell schools: 0=Physical, 1=Holy, 2=Fire, 3=Nature, 4=Frost, 5=Shadow, 6=Arcane
---@param unitGuid string GUID of the unit whose shield dealt damage
---@param targetGuid string GUID of the attacker who took the shield damage
---@param damage number Amount of shield damage dealt
---@param spellSchool number School of the shield damage (see SpellSchool constants)
function ChronicleLog:DAMAGE_SHIELD_OTHER(unitGuid, targetGuid, damage, spellSchool)
self:CheckUnit(unitGuid)
self:CheckUnit(targetGuid)
self:Write4("DMG_SHIELD", unitGuid, targetGuid, damage, spellSchool)
end
--- Handles AURA_CAST_ON_SELF events.
--- Called when a spell cast applies an aura to the active player.
--- Includes cases where active player is caster with no explicit target.
--- Requires CVar: SetCVar("NP_EnableAuraCastEvents", 1)
--- Note: Some auras without spell effects won't trigger this; use BUFF/DEBUFF gain events instead.
--- Fires once per qualifying spell effect per target (AOE spells fire multiple times).
---@param spellId number Spell ID
---@param casterGuid string GUID of the caster
---@param targetGuid string GUID of the target (active player)
---@param effect number Aura-applying effect ID
---@param effectAuraName number Entry from EffectApplyAuraName
---@param effectAmplitude number EffectAmplitude for the aura effect
---@param effectMiscValue number EffectMiscValue for the aura effect
---@param durationMs number Spell duration in milliseconds (includes client modifiers if you're caster)
---@param auraCapStatus number Bitfield: 1=buff bar full, 2=debuff bar full, 3=both
function ChronicleLog:AURA_CAST_ON_SELF(spellId, casterGuid, targetGuid, effect, effectAuraName, effectAmplitude, effectMiscValue, durationMs, auraCapStatus)
self:CheckUnit(casterGuid)
self:CheckUnit(targetGuid)
self:Write9("AURA_CAST", spellId, casterGuid, targetGuid, effect, effectAuraName, effectAmplitude, effectMiscValue, durationMs, auraCapStatus)
end
--- Handles AURA_CAST_ON_OTHER events.
--- Called when a spell cast applies an aura to someone other than the active player.
--- Requires CVar: SetCVar("NP_EnableAuraCastEvents", 1)
--- Note: Some auras without spell effects won't trigger this; use BUFF/DEBUFF gain events instead.
--- Fires once per qualifying spell effect per target (AOE spells fire multiple times).
---@param spellId number Spell ID
---@param casterGuid string GUID of the caster
---@param targetGuid string GUID of the target
---@param effect number Aura-applying effect ID
---@param effectAuraName number Entry from EffectApplyAuraName
---@param effectAmplitude number EffectAmplitude for the aura effect
---@param effectMiscValue number EffectMiscValue for the aura effect
---@param durationMs number Spell duration in milliseconds (includes client modifiers if you're caster)
---@param auraCapStatus number Bitfield: 1=buff bar full, 2=debuff bar full, 3=both
function ChronicleLog:AURA_CAST_ON_OTHER(spellId, casterGuid, targetGuid, effect, effectAuraName, effectAmplitude, effectMiscValue, durationMs, auraCapStatus)
self:CheckUnit(casterGuid)
self:CheckUnit(targetGuid)
self:Write9("AURA_CAST", spellId, casterGuid, targetGuid, effect, effectAuraName, effectAmplitude, effectMiscValue, durationMs, auraCapStatus)
end
--- Handles BUFF_UPDATE_DURATION_SELF events.
--- Called when the client updates the duration of a buff on the active player.
--- Fires when server refreshes an aura's duration (e.g., reapplying existing buff).
--- Note: Fires before aura is added to unit fields, so spellId=0 for new auras.
--- Use BUFF_ADDED_SELF for tracking newly applied auras.
--- Aura slot range: 0-31 for buffs.
---@param auraSlot number Raw 0-based aura slot index (0-31 for buffs)
---@param durationMs number Updated duration in milliseconds
---@param expirationTimeMs number Calculated expiration time (GetWowTimeMs() + durationMs), or 0 if no duration
---@param spellId number Spell ID of aura in slot (0 for new auras, >0 for refreshed auras)
function ChronicleLog:BUFF_UPDATE_DURATION_SELF(auraSlot, durationMs, expirationTimeMs, spellId)
-- self:Write("BUFF_DURATION", auraSlot, durationMs, expirationTimeMs, spellId)
end
--- Handles DEBUFF_UPDATE_DURATION_SELF events.
--- Called when the client updates the duration of a debuff on the active player.
--- Fires when server refreshes an aura's duration (e.g., reapplying existing debuff).
--- Note: Fires before aura is added to unit fields, so spellId=0 for new auras.
--- Use DEBUFF_ADDED_SELF for tracking newly applied auras.
--- Aura slot range: 32-47 for debuffs.
---@param auraSlot number Raw 0-based aura slot index (32-47 for debuffs)
---@param durationMs number Updated duration in milliseconds
---@param expirationTimeMs number Calculated expiration time (GetWowTimeMs() + durationMs), or 0 if no duration
---@param spellId number Spell ID of aura in slot (0 for new auras, >0 for refreshed auras)
function ChronicleLog:DEBUFF_UPDATE_DURATION_SELF(auraSlot, durationMs, expirationTimeMs, spellId)
-- self:Write("DEBUFF_DURATION", auraSlot, durationMs, expirationTimeMs, spellId)
end
--- Handles BUFF_ADDED_SELF events.
--- Called when a buff is added to the active player.
--- State: 0=newly added, 2=modified (stack increased).
---@param guid string GUID of the unit (active player)
---@param luaSlot number 1-based Lua slot index (matches UnitBuff ordering)
---@param spellId number Spell ID of the buff
---@param stackCount number Current stack count
---@param auraLevel number Caster level from UnitFields.auraLevels
---@param auraSlot number Raw 0-based aura slot index (0-31 for buffs)
---@param state number 0=added, 1=removed, 2=modified (stack change)
function ChronicleLog:BUFF_ADDED_SELF(guid, luaSlot, spellId, stackCount, auraLevel, auraSlot, state)
self:CheckUnit(guid)
self:Write7("BUFF_ADD", guid, luaSlot, spellId, stackCount, auraLevel, auraSlot, state)
end
--- Handles BUFF_REMOVED_SELF events.
--- Called when a buff is removed from the active player.
--- State: 1=newly removed, 2=modified (stack decreased).
---@param guid string GUID of the unit (active player)
---@param luaSlot number 1-based Lua slot index (matches UnitBuff ordering)
---@param spellId number Spell ID of the buff
---@param stackCount number Current stack count
---@param auraLevel number Caster level from UnitFields.auraLevels
---@param auraSlot number Raw 0-based aura slot index (0-31 for buffs)
---@param state number 0=added, 1=removed, 2=modified (stack change)
function ChronicleLog:BUFF_REMOVED_SELF(guid, luaSlot, spellId, stackCount, auraLevel, auraSlot, state)
self:CheckUnit(guid)
self:Write7("BUFF_REM", guid, luaSlot, spellId, stackCount, auraLevel, auraSlot, state)
end
--- Handles BUFF_ADDED_OTHER events.
--- Called when a buff is added to a unit other than the active player.
--- State: 0=newly added, 2=modified (stack increased).
---@param guid string GUID of the unit
---@param luaSlot number 1-based Lua slot index (matches UnitBuff ordering)
---@param spellId number Spell ID of the buff
---@param stackCount number Current stack count
---@param auraLevel number Caster level from UnitFields.auraLevels
---@param auraSlot number Raw 0-based aura slot index (0-31 for buffs)
---@param state number 0=added, 1=removed, 2=modified (stack change)
function ChronicleLog:BUFF_ADDED_OTHER(guid, luaSlot, spellId, stackCount, auraLevel, auraSlot, state)
self:CheckUnit(guid)
self:Write7("BUFF_ADD", guid, luaSlot, spellId, stackCount, auraLevel, auraSlot, state)
end
--- Handles BUFF_REMOVED_OTHER events.
--- Called when a buff is removed from a unit other than the active player.
--- State: 1=newly removed, 2=modified (stack decreased).
---@param guid string GUID of the unit
---@param luaSlot number 1-based Lua slot index (matches UnitBuff ordering)
---@param spellId number Spell ID of the buff
---@param stackCount number Current stack count
---@param auraLevel number Caster level from UnitFields.auraLevels
---@param auraSlot number Raw 0-based aura slot index (0-31 for buffs)
---@param state number 0=added, 1=removed, 2=modified (stack change)
function ChronicleLog:BUFF_REMOVED_OTHER(guid, luaSlot, spellId, stackCount, auraLevel, auraSlot, state)
self:CheckUnit(guid)
self:Write7("BUFF_REM", guid, luaSlot, spellId, stackCount, auraLevel, auraSlot, state)
end
--- Handles DEBUFF_ADDED_SELF events.
--- Called when a debuff is added to the active player.
--- State: 0=newly added, 2=modified (stack increased).
---@param guid string GUID of the unit (active player)
---@param luaSlot number 1-based Lua slot index (matches UnitDebuff ordering)
---@param spellId number Spell ID of the debuff
---@param stackCount number Current stack count
---@param auraLevel number Caster level from UnitFields.auraLevels
---@param auraSlot number Raw 0-based aura slot index (32-47 for debuffs)
---@param state number 0=added, 1=removed, 2=modified (stack change)
function ChronicleLog:DEBUFF_ADDED_SELF(guid, luaSlot, spellId, stackCount, auraLevel, auraSlot, state)
self:CheckUnit(guid)
self:Write7("DEBUFF_ADD", guid, luaSlot, spellId, stackCount, auraLevel, auraSlot, state)
self:HandleTalentReset(guid, spellId)
end
--- Handles DEBUFF_REMOVED_SELF events.
--- Called when a debuff is removed from the active player.
--- State: 1=newly removed, 2=modified (stack decreased).
---@param guid string GUID of the unit (active player)
---@param luaSlot number 1-based Lua slot index (matches UnitDebuff ordering)
---@param spellId number Spell ID of the debuff
---@param stackCount number Current stack count
---@param auraLevel number Caster level from UnitFields.auraLevels
---@param auraSlot number Raw 0-based aura slot index (32-47 for debuffs)
---@param state number 0=added, 1=removed, 2=modified (stack change)
function ChronicleLog:DEBUFF_REMOVED_SELF(guid, luaSlot, spellId, stackCount, auraLevel, auraSlot, state)
self:CheckUnit(guid)
self:Write7("DEBUFF_REM", guid, luaSlot, spellId, stackCount, auraLevel, auraSlot, state)
end
--- Handles DEBUFF_ADDED_OTHER events.
--- Called when a debuff is added to a unit other than the active player.
--- State: 0=newly added, 2=modified (stack increased).
---@param guid string GUID of the unit
---@param luaSlot number 1-based Lua slot index (matches UnitDebuff ordering)
---@param spellId number Spell ID of the debuff
---@param stackCount number Current stack count
---@param auraLevel number Caster level from UnitFields.auraLevels
---@param auraSlot number Raw 0-based aura slot index (32-47 for debuffs)
---@param state number 0=added, 1=removed, 2=modified (stack change)
function ChronicleLog:DEBUFF_ADDED_OTHER(guid, luaSlot, spellId, stackCount, auraLevel, auraSlot, state)
self:CheckUnit(guid)
self:Write7("DEBUFF_ADD", guid, luaSlot, spellId, stackCount, auraLevel, auraSlot, state)
self:HandleTalentReset(guid, spellId)
end
--- Handles DEBUFF_REMOVED_OTHER events.
--- Called when a debuff is removed from a unit other than the active player.
--- State: 1=newly removed, 2=modified (stack decreased).
---@param guid string GUID of the unit
---@param luaSlot number 1-based Lua slot index (matches UnitDebuff ordering)
---@param spellId number Spell ID of the debuff
---@param stackCount number Current stack count
---@param auraLevel number Caster level from UnitFields.auraLevels
---@param auraSlot number Raw 0-based aura slot index (32-47 for debuffs)
---@param state number 0=added, 1=removed, 2=modified (stack change)
function ChronicleLog:DEBUFF_REMOVED_OTHER(guid, luaSlot, spellId, stackCount, auraLevel, auraSlot, state)
self:CheckUnit(guid)
self:Write7("DEBUFF_REM", guid, luaSlot, spellId, stackCount, auraLevel, auraSlot, state)
end
--- Handles SPELL_DAMAGE_EVENT_SELF events.
--- Called when the active player deals spell damage.
--- Writes a SPELL_DMG event with target, caster, spell, amount, mitigation, hit info, school, and effects.
--- hitInfo: 0=normal, 2=crit (see SpellDefines.h for full enum)
--- spellSchool: damage school of the spell (see SpellDefines.h)
--- mitigationStr: comma-separated "absorb,block,resist" amounts
--- effectAuraStr: comma-separated "effect1,effect2,effect3,auraType"
---@param targetGuid string GUID of the damage target
---@param casterGuid string GUID of the caster (active player)
---@param spellId number Spell ID
---@param amount number Damage dealt (or % health if auraType is 89/SPELL_AURA_PERIODIC_DAMAGE_PERCENT)
---@param mitigationStr string Comma-separated "absorb,block,resist" amounts
---@param hitInfo number Hit flags (0=normal, 2=crit)
---@param spellSchool number Damage school
---@param effectAuraStr string Comma-separated "effect1,effect2,effect3,auraType"
function ChronicleLog:SPELL_DAMAGE_EVENT_SELF(targetGuid, casterGuid, spellId, amount, mitigationStr, hitInfo, spellSchool, effectAuraStr)
self:CheckUnit(targetGuid)
self:CheckUnit(casterGuid)
self:Write8("SPELL_DMG", targetGuid, casterGuid, spellId, amount, mitigationStr, hitInfo, spellSchool, effectAuraStr)
end
--- Handles SPELL_DAMAGE_EVENT_OTHER events.
--- Called when someone other than the active player deals spell damage.
--- Writes a SPELL_DMG event with target, caster, spell, amount, mitigation, hit info, school, and effects.
--- hitInfo: 0=normal, 2=crit (see SpellDefines.h for full enum)
--- spellSchool: damage school of the spell (see SpellDefines.h)
--- mitigationStr: comma-separated "absorb,block,resist" amounts
--- effectAuraStr: comma-separated "effect1,effect2,effect3,auraType"
---@param targetGuid string GUID of the damage target
---@param casterGuid string GUID of the caster
---@param spellId number Spell ID
---@param amount number Damage dealt (or % health if auraType is 89/SPELL_AURA_PERIODIC_DAMAGE_PERCENT)
---@param mitigationStr string Comma-separated "absorb,block,resist" amounts
---@param hitInfo number Hit flags (0=normal, 2=crit)
---@param spellSchool number Damage school
---@param effectAuraStr string Comma-separated "effect1,effect2,effect3,auraType"
function ChronicleLog:SPELL_DAMAGE_EVENT_OTHER(targetGuid, casterGuid, spellId, amount, mitigationStr, hitInfo, spellSchool, effectAuraStr)
self:CheckUnit(targetGuid)
self:CheckUnit(casterGuid)
self:Write8("SPELL_DMG", targetGuid, casterGuid, spellId, amount, mitigationStr, hitInfo, spellSchool, effectAuraStr)
end
--- Handles SPELL_DELAYED_SELF events.
--- Called when the active player's spell is delayed (pushback from damage).
--- Writes a SPELL_DELAY event with caster GUID and delay amount.
---@param casterGuid string GUID of the caster (active player)
---@param delayMs number Delay in milliseconds
function ChronicleLog:SPELL_DELAYED_SELF(casterGuid, delayMs)
self:CheckUnit(casterGuid)
self:Write2("SPELL_DELAY", casterGuid, delayMs)
end
--- Handles SPELL_DELAYED_OTHER events.
--- Called when another player's spell is delayed (pushback from damage).
--- Note: Currently non-functional - server only sends packet to affected player.
--- Writes a SPELL_DELAY event with caster GUID and delay amount.
---@param casterGuid string GUID of the caster
---@param delayMs number Delay in milliseconds
function ChronicleLog:SPELL_DELAYED_OTHER(casterGuid, delayMs)
self:CheckUnit(casterGuid)
self:Write2("SPELL_DELAY", casterGuid, delayMs)
end
--- Handles SPELL_CHANNEL_START events.
--- Called when the active player starts channeling a spell.
--- Self-only event. Target GUID read from ChannelTargetGuid memory address.
--- Writes a CHANNEL_START event with spell ID, target, and duration.
---@param spellId number Spell ID being channeled
---@param targetGuid string Target GUID or "0x0000000000000000" if none
---@param durationMs number Channel duration in milliseconds
function ChronicleLog:SPELL_CHANNEL_START(spellId, targetGuid, durationMs)
self:CheckUnit(targetGuid)
self:Write3("CHANNEL_START", spellId, targetGuid, durationMs)
end
--- Handles SPELL_CHANNEL_UPDATE events.
--- Called when the active player's channel time is updated (e.g., after tick or pushback).
--- Self-only event. Target GUID read from ChannelTargetGuid memory address.
--- Writes a CHANNEL_UPDATE event with spell ID, target, and remaining time.
---@param spellId number Spell ID being channeled
---@param targetGuid string Target GUID or "0x0000000000000000" if none
---@param remainingMs number Remaining channel time in milliseconds
function ChronicleLog:SPELL_CHANNEL_UPDATE(spellId, targetGuid, remainingMs)
self:CheckUnit(targetGuid)
self:Write3("CHANNEL_UPDATE", spellId, targetGuid, remainingMs)
end
--- Handles SPELL_FAILED_SELF events.
--- Called when the active player's spell fails.
--- Fired from client spell failure hook with detailed failure info.
--- Writes a SPELL_FAIL event with spell ID, result code, and server flag.
---@param spellId number Spell ID that failed
---@param spellResult number SpellCastResult enum value
---@param failedByServer number 1 if failed by server, 0 if client-side failure
function ChronicleLog:SPELL_FAILED_SELF(spellId, spellResult, failedByServer)
local _, playerGuid = UnitExists("player")
-- Reordering parameters to keep the same as `SPELL_FAILED_OTHER`
self:Write4("SPELL_FAIL", playerGuid, spellId, failedByServer == 1, spellResult)
end
--- Handles SPELL_FAILED_OTHER events.
--- Called when another player's spell fails.
--- Fired from server handler with limited information (no failure reason).
--- Writes a SPELL_FAIL event with caster GUID and spell ID.
---@param casterGuid string GUID of the caster
---@param spellId number Spell ID that failed
function ChronicleLog:SPELL_FAILED_OTHER(casterGuid, spellId)
self:CheckUnit(casterGuid)
self:Write3("SPELL_FAIL", casterGuid, spellId, true)
end
--- Handles SPELL_GO_SELF events.
--- Called when the active player's spell go packet is received (spell completed casting).
--- Requires CVar: SetCVar("NP_EnableSpellGoEvents", 1)
--- Writes a SPELL_GO event with item, spell, caster, target, flags, and hit/miss counts.
--- Cast flags bitmask: 0=NONE, 1=HIDDEN_COMBATLOG, 32=AMMO, etc.
---@param itemId number Item ID that triggered spell, or 0 if not item-triggered
---@param spellId number Spell ID
---@param casterGuid string GUID of the caster (active player)
---@param targetGuid string Target GUID or "0x0000000000000000" if none
---@param castFlags number Bitmask of cast flags
---@param numTargetsHit number Number of targets hit
---@param numTargetsMissed number Number of targets missed
function ChronicleLog:SPELL_GO_SELF(itemId, spellId, casterGuid, targetGuid, castFlags, numTargetsHit, numTargetsMissed)
self:CheckUnit(casterGuid)
self:CheckUnit(targetGuid)
self:Write7("SPELL_GO", itemId, spellId, casterGuid, targetGuid, castFlags, numTargetsHit, numTargetsMissed)
end
--- Handles SPELL_GO_OTHER events.
--- Called when another unit's spell go packet is received (spell completed casting).
--- Requires CVar: SetCVar("NP_EnableSpellGoEvents", 1)
--- Writes a SPELL_GO event with item, spell, caster, target, flags, and hit/miss counts.
--- Cast flags bitmask: 0=NONE, 1=HIDDEN_COMBATLOG, 32=AMMO, etc.
---@param itemId number Item ID that triggered spell, or 0 if not item-triggered
---@param spellId number Spell ID
---@param casterGuid string GUID of the caster
---@param targetGuid string Target GUID or "0x0000000000000000" if none
---@param castFlags number Bitmask of cast flags
---@param numTargetsHit number Number of targets hit
---@param numTargetsMissed number Number of targets missed
function ChronicleLog:SPELL_GO_OTHER(itemId, spellId, casterGuid, targetGuid, castFlags, numTargetsHit, numTargetsMissed)
self:CheckUnit(casterGuid)
self:CheckUnit(targetGuid)
self:Write7("SPELL_GO", itemId, spellId, casterGuid, targetGuid, castFlags, numTargetsHit, numTargetsMissed)
end
--- Handles SPELL_START_SELF events.
--- Called when the active player's spell start packet is received (cast time spell begun).
--- Requires CVar: SetCVar("NP_EnableSpellStartEvents", 1)
--- Writes a SPELL_START event with item, spell, caster, target, flags, cast time, duration, and type.
--- spellType: 0=Normal, 1=Channeling, 2=Autorepeating
---@param itemId number Item ID that triggered spell, or 0 if not item-triggered
---@param spellId number Spell ID
---@param casterGuid string GUID of the caster (active player)
---@param targetGuid string Target GUID or "0x0000000000000000" if none
---@param castFlags number Bitmask of cast flags
---@param castTime number Cast time in milliseconds
---@param duration number Channel duration in ms (only for channeling spells, 0 otherwise)
---@param spellType number 0=Normal, 1=Channeling, 2=Autorepeating
function ChronicleLog:SPELL_START_SELF(itemId, spellId, casterGuid, targetGuid, castFlags, castTime, duration, spellType)
self:CheckUnit(casterGuid)
self:CheckUnit(targetGuid)
self:Write8("SPELL_START", itemId, spellId, casterGuid, targetGuid, castFlags, castTime, duration, spellType)
end
--- Handles SPELL_START_OTHER events.
--- Called when another unit's spell start packet is received (cast time spell begun).
--- Also fires for channeling spells by others (no separate SPELL_CHANNEL_START for others).
--- Use spellType to distinguish channeling spells.
--- Requires CVar: SetCVar("NP_EnableSpellStartEvents", 1)
--- Writes a SPELL_START event with item, spell, caster, target, flags, cast time, duration, and type.
--- spellType: 0=Normal, 1=Channeling, 2=Autorepeating
---@param itemId number Item ID that triggered spell, or 0 if not item-triggered
---@param spellId number Spell ID
---@param casterGuid string GUID of the caster
---@param targetGuid string Target GUID or "0x0000000000000000" if none
---@param castFlags number Bitmask of cast flags
---@param castTime number Cast time in milliseconds
---@param duration number Channel duration in ms (only for channeling spells, 0 otherwise)
---@param spellType number 0=Normal, 1=Channeling, 2=Autorepeating
function ChronicleLog:SPELL_START_OTHER(itemId, spellId, casterGuid, targetGuid, castFlags, castTime, duration, spellType)
self:CheckUnit(casterGuid)
self:CheckUnit(targetGuid)
self:Write8("SPELL_START", itemId, spellId, casterGuid, targetGuid, castFlags, castTime, duration, spellType)
end
-- =============================================================================
-- Chat Event Handlers
-- =============================================================================
--- Handles CHAT_MSG_LOOT events.
--- Covers multiple message formats:
--- "You receive loot: [Item]." / "PlayerName receives loot: [Item]."
--- "You won: [Item]" / "PlayerName won: [Item]"
--- "You receive item: [Item]." (pushed/auto-distributed loot)
--- "You create: [Item]." (crafted items)
--- Chinese (Simplified) equivalents:
--- "PlayerName获得了物品:[Item]。" (receive loot)
--- "PlayerName赢得了[Item]" (group loot rolls)
--- "PlayerName得到了物品:[Item]。" (pushed/distributed loot)
--- "PlayerName制造了:[Item]。" (crafted items)
--- Writes a LOOT event with unit name and item link.
---@param msg string The loot message
function ChronicleLog:CHAT_MSG_LOOT(msg)
if not msg then return end
local looter, itemLink
-- Pattern 1: "You receive loot: [Item]." / "PlayerName receives loot: [Item]."
_, _, looter, itemLink = strfind(msg, "^(.+) receives? loot: (.+)%.$")
-- Pattern 2: "You won: [Item]" / "PlayerName won: [Item]" (group loot rolls)
if not looter then
_, _, looter, itemLink = strfind(msg, "^(.+) won: (.+)")
if looter and itemLink then
-- Strip trailing no-spam annotation: " |cff818181(Need - 95)|r"
local _, _, cleanLink = strfind(itemLink, "^(.-) |cff818181")
if cleanLink then
itemLink = cleanLink
end
end
end
-- Pattern 3: "You receive item: [Item]." (pushed/distributed loot)
if not looter then
_, _, looter, itemLink = strfind(msg, "^(.+) receives? item: (.+)%.$")
end
-- Pattern 4: "You create: [Item]." (crafted items)
if not looter then
_, _, looter, itemLink = strfind(msg, "^(.+) creates?: (.+)%.$")
end
-- Pattern 5 (zhCN): "PlayerName获得了物品:[Item]。" (receive loot)
if not looter then
_, _, looter, itemLink = strfind(msg, "^(.+)获得了物品:(.+)。$")
end
-- Pattern 6 (zhCN): "PlayerName赢得了[Item]" (group loot rolls)
if not looter then
_, _, looter, itemLink = strfind(msg, "^(.+)赢得了(.+)")
if looter and itemLink then
-- Strip trailing no-spam annotation: " |cff818181(Need - 95)|r"
local _, _, cleanLink = strfind(itemLink, "^(.-) |cff818181")
if cleanLink then
itemLink = cleanLink
end
end
end
-- Pattern 7 (zhCN): "PlayerName得到了物品:[Item]。" (pushed/distributed loot)
if not looter then
_, _, looter, itemLink = strfind(msg, "^(.+)得到了物品:(.+)。$")
end
-- Pattern 8 (zhCN): "PlayerName制造了:[Item]。" (crafted items)
if not looter then
_, _, looter, itemLink = strfind(msg, "^(.+)制造了:(.+)。$")
end
if not looter then return end
-- Convert "You" / "你" to player name
if looter == "You" or looter == "你" then
looter = UnitName("player") or "You"
end
Chronicle:DebugPrint("LOOT: " .. looter .. " - " .. itemLink)
self:Write2("LOOT", looter, itemLink)
end
--- Handles CHAT_MSG_SYSTEM events.
--- Detects trade messages: "PlayerA trades item ItemName to PlayerB."
--- Writes a LOOT_TRADE event with the raw message.
---@param msg string The system message
function ChronicleLog:CHAT_MSG_SYSTEM(msg)
if not msg then return end
-- Check for trade pattern: "Iseut trades item Libram of the Faithful to Milkpress."
if strfind(msg, "^%w+ trades item") then
self:Write1("LOOT_TRADE", msg)
end
end
-- =============================================================================
-- Unit GUID Event Handlers
-- =============================================================================
--- Handles UNIT_INVENTORY_CHANGED_GUID events.
--- Emits COMBATANT_INFO when a player unit's equipment changes.
---@param guid string Unit GUID
---@param isPlayer number 1 if unit is active player, 0 otherwise
---@param isTarget number 1 if unit is current target, 0 otherwise
---@param isMouseover number 1 if unit is mouseover, 0 otherwise
---@param isPet number 1 if unit is player's pet, 0 otherwise
---@param partyIndex number Party slot (1-4) or 0
---@param raidIndex number Raid slot (1-40) or 0
function ChronicleLog:UNIT_INVENTORY_CHANGED_GUID(guid, isPlayer, isTarget, isMouseover, isPet, partyIndex, raidIndex)
-- Only emit for player units (NPCs don't have meaningful gear)
if UnitIsPlayer(guid) == 1 then
self:WriteCombatantInfo(guid)
end
end
-- =============================================================================
-- Session Event Handlers
-- =============================================================================
--- Handles PLAYER_LEAVING_WORLD events.
--- Flushes the log buffer to file on logout/disconnect/reload.
function ChronicleLog:PLAYER_LEAVING_WORLD()
if self.bufferSize > 0 or self.pendingFlush then
self:FlushToFile()
end
end