diff --git a/sql/playerbot_v2/0019_bot_texts.sql b/sql/playerbot_v2/0019_bot_texts.sql index 82669088e1..f9ee52c977 100644 --- a/sql/playerbot_v2/0019_bot_texts.sql +++ b/sql/playerbot_v2/0019_bot_texts.sql @@ -1,7 +1,7 @@ -- Migration: 0019_bot_texts -- Date: 2026-10-05 --- Purpose: The bots' speech, carried over from Karrz's ike3 playerbot build --- (ike3-based bots src/game/PlayerBots/sql/world/ai_playerbot_texts.sql). Loaded once at startup by +-- Purpose: The bots' speech, carried over from chris's ike3 playerbot build +-- (wow-1.12 src/game/PlayerBots/sql/world/ai_playerbot_texts.sql). Loaded once at startup by -- Bot/BotTextMgr.cpp, which picks a random line per key and fills its placeholders. -- -- playerbot_v2_bot_text diff --git a/sql/playerbot_v2/0031_world_gear_pending.sql b/sql/playerbot_v2/0031_world_gear_pending.sql index 9986549f71..35786b9038 100644 --- a/sql/playerbot_v2/0031_world_gear_pending.sql +++ b/sql/playerbot_v2/0031_world_gear_pending.sql @@ -1,6 +1,6 @@ -- Migration: 0031_world_gear_pending -- Date: 2026-10-18 --- Purpose: World bots made before this change wear a generated full set at level 1-9 (a level 1 wore rings, trinkets, neck and cloak). New world bots +-- Purpose: World bots made before build 109 wear a generated full set at level 1-9 (a level 1 wore rings, trinkets, neck and cloak). New world bots -- under level 10 keep the outfit their character was created with. Each existing world bot under level 10 is marked here; the world -- spawner strips it to its starter outfit once, on its next login, and clears the mark. -- diff --git a/sql/playerbot_v2/0033_bot_appearance_reroll.sql b/sql/playerbot_v2/0033_bot_appearance_reroll.sql new file mode 100644 index 0000000000..9397c773fe --- /dev/null +++ b/sql/playerbot_v2/0033_bot_appearance_reroll.sql @@ -0,0 +1,16 @@ +-- Migration: 0033_bot_appearance_reroll +-- Date: 2026-10-26 +-- Purpose: Bots took every appearance choice from the client-made characters of their race and gender, so a realm with one +-- client-made human woman gave every female human bot her face, hair and colours (same for any race/gender with a +-- single player character). Bots now roll from every choice the client offers. The appearances of all characters on +-- bot accounts are cleared here; at the same start, before any bot logs in, BotCharacterFactory::RepairAppearances +-- rolls a new one for each. +-- Reverts: no schema change (old appearances are not kept). + +DELETE cc FROM character_customizations cc + JOIN characters c ON c.guid = cc.guid + JOIN playerbot_v2_account a ON a.account_id = c.account; + +INSERT INTO playerbot_v2_schema_version (version, sha256) VALUES + (33, REPEAT('0', 64)) +ON DUPLICATE KEY UPDATE applied_at = CURRENT_TIMESTAMP; diff --git a/src/modules/PlayerbotV2/Addon/ForeverBots/Bindings.xml b/src/modules/PlayerbotV2/Addon/ForeverBots/Bindings.xml index 4dccfd7c59..c22a201f21 100644 --- a/src/modules/PlayerbotV2/Addon/ForeverBots/Bindings.xml +++ b/src/modules/PlayerbotV2/Addon/ForeverBots/Bindings.xml @@ -2,6 +2,7 @@ ForeverBots_ToggleWindow() + ForeverBots_ToggleStance() @@ -16,4 +17,5 @@ + diff --git a/src/modules/PlayerbotV2/Addon/ForeverBots/ForeverBots.lua b/src/modules/PlayerbotV2/Addon/ForeverBots/ForeverBots.lua index 34f0f8fdd8..1a601e9da9 100644 --- a/src/modules/PlayerbotV2/Addon/ForeverBots/ForeverBots.lua +++ b/src/modules/PlayerbotV2/Addon/ForeverBots/ForeverBots.lua @@ -11,6 +11,96 @@ frame as it does for typed commands. local ADDON = ... ForeverBotsDB = ForeverBotsDB or {} +-- Timing of every handler the add-on gives the client (frame scripts, timers, hooks, chat filters, menu callbacks): client 70630 +-- shows "Script from ForeverBots has exceeded its execution time limit" with an empty stack (BRS 2026-10-27), which names no +-- function. Each handler is wrapped once, where it is handed over, and keeps its count, total and slowest call under the file line +-- that set it. A call over PERF_SLOW_MS prints one line per handler; "/fb perf" lists the slowest, and the list is saved in +-- ForeverBotsDB.perf at logout for the SavedVariables file. Secure frames are left alone: their scripts are not ours to wrap. +local PERF = { stats = {}, said = {} } +local PERF_SLOW_MS = 15 +local clockMs = debugprofilestop +local function PerfLabel(kind, level) + local where = debugstack and debugstack(level or 3, 1, 0) + local line = type(where) == "string" and where:match(":(%d+):") or "?" + return kind .. "@" .. line +end +local function PerfWrap(label, fn) + if type(fn) ~= "function" or not clockMs then return fn end + local st = PERF.stats[label] + if not st then st = { n = 0, total = 0, max = 0 }; PERF.stats[label] = st end + return function(...) + local t0 = clockMs() + local outer = PERF.running + PERF.running = label + local r1, r2, r3, r4, r5 = fn(...) + PERF.running = outer + local ms = clockMs() - t0 + st.n = st.n + 1 + st.total = st.total + ms + if ms > st.max then st.max = ms end + if ms > PERF_SLOW_MS and not PERF.said[label] and DEFAULT_CHAT_FRAME then + PERF.said[label] = true + DEFAULT_CHAT_FRAME:AddMessage(string.format("|cff66ccffWoW Forever Bots|r: slow handler %s took %.1f ms (/fb perf lists all).", label, ms)) + end + return r1, r2, r3, r4, r5 + end +end +local function PerfFrame(f, tmpl) + if type(f) ~= "table" or (type(tmpl) == "string" and tmpl:find("Secure", 1, true)) then return f end + local set, hook = f.SetScript, f.HookScript + f.SetScript = function(self, what, fn) + return set(self, what, PerfWrap(PerfLabel(tostring(what)), fn)) + end + f.HookScript = function(self, what, fn, ...) + return hook(self, what, PerfWrap(PerfLabel("hook " .. tostring(what)), fn), ...) + end + return f +end +-- A handler the client stops for running too long never returns, so its timing above is never taken: the label it set stays in +-- PERF.running, and the next frame names it (also for the add-on's own file load, marked here and cleared at the end of the file). +PERF.running = "file load" +PERF.aborted = {} +do + local watchdog = _G.CreateFrame("Frame") + watchdog:SetScript("OnUpdate", function() + local label = PERF.running + if not label then return end + PERF.running = nil + PERF.aborted[label] = (PERF.aborted[label] or 0) + 1 + if PERF.aborted[label] == 1 and DEFAULT_CHAT_FRAME then + DEFAULT_CHAT_FRAME:AddMessage("|cff66ccffWoW Forever Bots|r: stopped by the client (or a Lua error) inside " .. label .. " (/fb perf lists all).") + end + end) +end +local CreateFrame = function(kind, name, parent, tmpl, ...) + return PerfFrame(_G.CreateFrame(kind, name, parent, tmpl, ...), tmpl) +end +local C_Timer = _G.C_Timer and { + After = function(sec, fn) return _G.C_Timer.After(sec, PerfWrap(PerfLabel("timer"), fn)) end, +} or nil +local hooksecurefunc = _G.hooksecurefunc and function(a, b, c) + if c ~= nil then return _G.hooksecurefunc(a, b, PerfWrap(PerfLabel("hook " .. tostring(b)), c)) end + return _G.hooksecurefunc(a, PerfWrap(PerfLabel("hook " .. tostring(a)), b)) +end or nil +local ChatFrame_AddMessageEventFilter = _G.ChatFrame_AddMessageEventFilter and function(ev, fn) + return _G.ChatFrame_AddMessageEventFilter(ev, PerfWrap(PerfLabel("filter " .. tostring(ev)), fn)) +end or nil + +function PERF.Report(top) + local rows = {} + for label, st in pairs(PERF.stats) do + if st.n > 0 then rows[#rows + 1] = { label = label, n = st.n, total = st.total, max = st.max } end + end + table.sort(rows, function(a, b) return a.max > b.max end) + local lines = {} + for label, n in pairs(PERF.aborted) do lines[#lines + 1] = "STOPPED BY CLIENT: " .. label .. " x" .. n end + for i = 1, math.min(top or 12, #rows) do + local r = rows[i] + lines[#lines + 1] = string.format("%s max %.1f ms total %.0f ms calls %d", r.label, r.max, r.total, r.n) + end + return lines +end + -- This client hands tainted addon code "secret" strings for some units (an enemy NPC in combat) and some chat. A secret -- value cannot be compared, concatenated or matched, so every name that comes from the game goes through SafeName / SafeStr -- first and a secret one is treated as "not a bot": nothing in the menu or panel path touches it. @@ -30,7 +120,7 @@ end local CLASSES = { { key = "warrior", label = "Warrior", token = "WARRIOR", roles = { "tank", "dps" } }, { key = "paladin", label = "Paladin", token = "PALADIN", roles = { "tank", "healer", "dps" } }, - { key = "shaman", label = "Shaman", token = "SHAMAN", roles = { "healer", "dps" }, faction = "Horde" }, + { key = "shaman", label = "Shaman", token = "SHAMAN", roles = { "healer", "dps" } }, { key = "hunter", label = "Hunter", token = "HUNTER", roles = { "dps" } }, { key = "rogue", label = "Rogue", token = "ROGUE", roles = { "dps" } }, { key = "priest", label = "Priest", token = "PRIEST", roles = { "healer", "dps" } }, @@ -219,7 +309,7 @@ end -- Deletes the targeted companion for good, after a confirmation. StaticPopupDialogs["FOREVERBOTS_DELETE"] = { - text = "Delete %s for good? Its character is removed.", + text = "Delete %s for good? Its character is removed. (Your own characters summoned as bots are never deleted: use Dismiss for them.)", button1 = YES, button2 = NO, OnAccept = function(_, name) ServerCommand(".bot delete " .. name) end, @@ -408,13 +498,41 @@ local function OwnListFilter(_, _, msg, author) local me = SafeName("player") return me ~= nil and author ~= nil and strmatch(author, "^[^-]+") == me end -if ChatFrame_AddMessageEventFilter then +-- Optional parts that run inside the client's own code (chat filters, the SetBinding hook, the issue reporter search): each can be +-- switched off with "/fb part off" and /reload, to find which one the client's time limit is about. They start once the +-- saved settings are loaded (ADDON_LOADED of this add-on). +local PARTS = { list = {}, start = {} } +function PARTS.On(name) return not (ForeverBotsDB.partsOff and ForeverBotsDB.partsOff[name]) end +PARTS.list[1] = "menu" -- the portrait menu entries (AddPopupEntry at login); listed here so /fb part knows the name +local function AddPart(name, fn) PARTS.list[#PARTS.list + 1] = name; PARTS.start[name] = fn end +do + local starter = CreateFrame("Frame") + starter:RegisterEvent("ADDON_LOADED") + starter:RegisterEvent("PLAYER_LOGOUT") + starter:SetScript("OnEvent", function(self, event, name) + if event == "PLAYER_LOGOUT" then + ForeverBotsDB.perf = PERF.Report(25) + return + end + if name ~= ADDON then return end + self:UnregisterEvent("ADDON_LOADED") + for _, part in ipairs(PARTS.list) do + if PARTS.On(part) then + local ok, err = pcall(PARTS.start[part]) + if not ok then Debug("part " .. part .. ": " .. tostring(err)) end + end + end + end) +end + +AddPart("filters", function() + if not ChatFrame_AddMessageEventFilter then return end ChatFrame_AddMessageEventFilter("CHAT_MSG_WHISPER", WhisperFilter) ChatFrame_AddMessageEventFilter("CHAT_MSG_WHISPER_INFORM", function(_, _, msg) return type(msg) == "string" and not IsSecret(msg) and msg == "assign list" end) for _, ev in ipairs({ "CHAT_MSG_PARTY", "CHAT_MSG_PARTY_LEADER", "CHAT_MSG_RAID", "CHAT_MSG_RAID_LEADER" }) do ChatFrame_AddMessageEventFilter(ev, OwnListFilter) end -end +end) local whisperFrame = CreateFrame("Frame") whisperFrame:RegisterEvent("CHAT_MSG_WHISPER") @@ -430,6 +548,7 @@ end) ------------------------------------------------------------------------------------------------------------- window local frame +local UI = {} -- window builders as table functions: BuildFrame alone captured over 60 file-level locals, a Lua 5.1 compile error local function MakeButton(parent, text, width, onClick, height) local b = CreateFrame("Button", nil, parent, "UIPanelButtonTemplate") @@ -514,6 +633,86 @@ for _, k in ipairs(KEY_ORDERS) do end RefreshOrderMacros() +-- A secure window key: it shows or hides the window in combat too (the plain toggle key and /fb wait for the end of combat). Its +-- reference to the window is set when the window is built, at login. +do + local ok, b = pcall(CreateFrame, "Button", "ForeverBotsKeyWindow", UIParent, "SecureHandlerClickTemplate") + if ok and b and b.SetFrameRef then + b:RegisterForClicks("AnyUp") + b:SetAttribute("_onclick", [[ + local w = self:GetFrameRef("fbwin") + if w then + if w:IsShown() then w:Hide() else w:Show() end + end + ]]) + UI.keyWindow = b + _G["BINDING_NAME_CLICK ForeverBotsKeyWindow:LeftButton"] = "Show / hide the bot window (works in combat)" + end +end + +-- Lazy lock (warlock): one key, the server picks the next spell (dots, curse, Shadow Bolt, cooldowns) and casts it on your target. +-- The client will not let an add-on choose spells in a fight, so the key clicks a secure button that runs the server command +-- ".playerbot lazy" as the player's own line, in combat too. Press it again for every cast. +do + local b = CreateFrame("Button", "ForeverBotsKeyLazy", UIParent, "SecureActionButtonTemplate") + b:RegisterForClicks("AnyUp", "AnyDown") + b:SetAttribute("type", "macro") + b:SetAttribute("macrotext", ".playerbot lazy") + _G["BINDING_NAME_CLICK ForeverBotsKeyLazy:LeftButton"] = "Lazy lock (warlock: next spell on your target)" +end + +-- Duplicate macros: a key bound to a macro ("bind ALT-E MACRO Corruption" in bindings-cache.wtf) runs the first macro of that +-- name. The client sorts the macro list by name, and copies with the same name come out in a different order at each login, +-- so it renumbers them and saves the list again at logout (live: Karrz's 59 account macros held 9 names two or three times, +-- and their numbers swapped between the 14:59 and 19:13 saves of 2026-10-24). Once one copy is edited, the key runs the old +-- copy after the next logout. Out of combat at login, copies that match an earlier macro in name, icon and text are deleted; +-- copies that differ are kept and named in chat so the player can rename or delete one. +local function RemoveDuplicateMacros() + if not (GetNumMacros and GetMacroInfo and DeleteMacro) then return end + if InCombatLockdown and InCombatLockdown() then return end + Step("duplicate macros") + local numAccount, numChar = GetNumMacros() + local charFirst = (MAX_ACCOUNT_MACROS or 120) + 1 + local function Scan(first, count) + local seen, drop, differ = {}, {}, {} + for i = first, first + count - 1 do + local name, icon, body = GetMacroInfo(i) + if name then + local kept = seen[name] + if not kept then + seen[name] = { icon = icon, body = body } + elseif kept.icon == icon and kept.body == body then + drop[#drop + 1] = i + else + differ[name] = true + end + end + end + for k = #drop, 1, -1 do DeleteMacro(drop[k]) end -- highest first: a delete moves every later macro down by one + return #drop, differ + end + local droppedA, differA = Scan(1, numAccount or 0) + local droppedC, differC = Scan(charFirst, numChar or 0) + if droppedA + droppedC > 0 then + Print("removed " .. (droppedA + droppedC) .. " duplicate macro(s) (same name and text as another), so macro keys stay on the same macro.") + end + for _, differ in ipairs({ differA, differC }) do + for name in pairs(differ) do + Print("two macros are named |cffffd100" .. name .. "|r but differ; a key bound to that name uses the first. Rename or delete one in /macro.") + end + end + Step("") +end + +local macroFrame = CreateFrame("Frame") +macroFrame:RegisterEvent("PLAYER_ENTERING_WORLD") +macroFrame:SetScript("OnEvent", function(self, _, isLogin, isReload) + if isLogin == false and isReload == false then return end -- zoning: the list has not changed + self:UnregisterEvent("PLAYER_ENTERING_WORLD") + -- the client fills the macro list during the login; a second later it is complete + if C_Timer and C_Timer.After then C_Timer.After(1, RemoveDuplicateMacros) else RemoveDuplicateMacros() end +end) + ------------------------------------------------------------------------------------------------------------- skin -- Own artwork in Textures\ (32-bit .tga, power-of-two sizes): wood body, bronze bead border, medallion, tabs. The buttons are the -- client's own red buttons (UIPanelButtonTemplate), so they look and behave like every other button in the game. @@ -604,11 +803,61 @@ local function SetGearChoice(g) SendGear() end --- One click for a ready party: a tank, a healer and three damage dealers, added a moment apart so each reads the gear word. -local QUICK_PARTY = { { "warrior", "tank" }, { "priest", "healer" }, { "mage", "dps" }, { "rogue", "dps" }, { "hunter", "dps" } } +-- One click for a ready group, sized to where you are: a party of five in the open world and in 5-player dungeons, the size the +-- instance holds in a bigger one (10 in Upper Blackrock Spire, 20 or 40 in a raid). The members already in the group count, so it +-- never adds past that size: a sixth member made an open-world party a raid, and a raid gets no credit for normal quests +-- (Discord report, 2026-10-27), while in Upper Blackrock Spire it stopped at six of ten. +local QUICK_DPS = { "mage", "rogue", "hunter", "warlock" } +local QUICK_HEALERS = { "priest", "druid" } +local PARTY_SIZE = 5 + +-- How many players the group should hold here. +local function QuickPartySize() + local okI, inInstance, kind = pcall(IsInInstance) + if not (okI and inInstance) or (kind ~= "party" and kind ~= "raid") then return PARTY_SIZE end + local maxPlayers = 0 + if GetInstanceInfo then + local okG, _, _, _, _, mp = pcall(GetInstanceInfo) + if okG and type(mp) == "number" then maxPlayers = mp end + end + if maxPlayers <= 0 then maxPlayers = (kind == "raid") and 40 or PARTY_SIZE end + return math.max(PARTY_SIZE, math.min(maxPlayers, 40)) +end + +-- The roles for a group of `size`, tanks first, then healers, then damage dealers; the first `count` are added. +-- 5: 1 tank, 1 healer, 2 damage (you are the fifth). 10: 2 tanks, 3 healers. 20: 2 and 5. 40: 4 and 10. +local function QuickPartyRoster(size, count) + local tanks = (size <= PARTY_SIZE) and 1 or (size <= 20 and 2 or 4) + local healers = (size <= PARTY_SIZE) and 1 or math.ceil(size / 4) + local roster = {} + for i = 1, count do + if i <= tanks then + roster[i] = { "warrior", "tank" } + elseif i <= tanks + healers then + roster[i] = { QUICK_HEALERS[(i - tanks - 1) % #QUICK_HEALERS + 1], "healer" } + else + roster[i] = { QUICK_DPS[(i - tanks - healers - 1) % #QUICK_DPS + 1], "dps" } + end + end + return roster +end + local function QuickParty() - for i, q in ipairs(QUICK_PARTY) do - AddBotWithGear(q[1], q[2]) + local members = 1 + if GetNumGroupMembers then members = math.max(GetNumGroupMembers(), 1) + elseif GetNumPartyMembers then members = GetNumPartyMembers() + 1 end + local size = QuickPartySize() + local free = size - members + if free <= 0 then + Print("quick party: your group is full (" .. members .. " of " .. size .. ").") + return + end + for i, q in ipairs(QuickPartyRoster(size, free)) do + if i == 1 or not (C_Timer and C_Timer.After) then + AddBotWithGear(q[1], q[2]) + else + C_Timer.After(0.4 * (i - 1), function() AddBotWithGear(q[1], q[2]) end) -- a moment apart, as one chat line each + end end end @@ -724,11 +973,58 @@ local function WindowScale() return math.max(SCALE_MIN, math.min(SCALE_MAX, n)) end +-- In combat the client refuses Show, Hide and moving for a protected frame, and the secure order buttons make the window and its +-- Orders and Form tabs protected: every refused call printed a "the client blocked Frame:Show()" line (Upper Blackrock Spire raid +-- 2026-10-26, a tab click and a drag in a fight). Such a change waits for the end of combat instead; the last one asked for wins. +UI.afterCombat = {} -- frame -> true (show) or false (hide), done on PLAYER_REGEN_ENABLED + +function UI.Locked(f) + if not (InCombatLockdown and InCombatLockdown()) then return false end + if f and f.IsProtected then return f:IsProtected() and true or false end + return true +end + +-- Shows or hides f now, or once combat ends when the client would refuse it. Returns false when it waits. +function UI.SetShown(f, show) + show = show and true or false + if UI.Locked(f) then + if f:IsShown() == show then UI.afterCombat[f] = nil else UI.afterCombat[f] = show end + return false + end + UI.afterCombat[f] = nil + if show then f:Show() else f:Hide() end + return true +end + +local shownTab, tabWaitSaid +function UI.TabShown(i) + UI.pendingTab = nil + shownTab = i + ForeverBotsDB.tab = i + for k, t in pairs(frameTabs) do t:SetChecked(k == i) end +end local function ShowTab(i) i = (framePanes[i] and i) or 1 + for k, pane in ipairs(framePanes) do + if pane:IsShown() ~= (k == i) and UI.Locked(pane) then + -- Bots and Marks still switch in a fight; a switch that shows or hides Orders or Form waits for the end of combat + UI.pendingTab = i + for n, t in pairs(frameTabs) do t:SetChecked(n == shownTab) end + if not tabWaitSaid then + tabWaitSaid = true + Print("that tab opens when combat ends (the client keeps the order buttons fixed in a fight).") + end + return + end + end + UI.pendingTab = nil + shownTab = i ForeverBotsDB.tab = i for k, pane in ipairs(framePanes) do - if k == i then pane:Show() else pane:Hide() end + -- only the panes that change: in a fight even a Show of a shown protected pane is a refused call + if pane:IsShown() ~= (k == i) then + if k == i then pane:Show() else pane:Hide() end + end if frameTabs[k] then frameTabs[k]:SetChecked(k == i) end end end @@ -778,9 +1074,11 @@ local function SetRoleTexture(tex, role) tex:SetTexCoord(c[1], c[2], c[3], c[4]) end -local UI = {} -- window builders as table functions: BuildFrame alone captured over 60 file-level locals, a Lua 5.1 compile error +-- Every pane is a protected frame (SecureFrameTemplate), so the secure tab click below may show and hide each of them in a fight: +-- restricted code only moves protected frames, and Orders and Form are protected anyway through their secure order buttons. function UI.NewPane() - local pane = CreateFrame("Frame", nil, frame) + local ok, pane = pcall(CreateFrame, "Frame", nil, frame, "SecureFrameTemplate") + if not (ok and pane) then pane = CreateFrame("Frame", nil, frame) end pane:SetSize(LAYOUT.CONTENT, LAYOUT.PANE_H) pane:SetPoint("TOPLEFT", frame, "TOPLEFT", 11, -LAYOUT.TOP) framePanes[#framePanes + 1] = pane @@ -843,9 +1141,9 @@ function UI.BuildOrders() Tip(stanceBtn, "Stance", "Passive (the start setting): bots start nothing, fight only what you pull or what attacks the group, and come back to follow you. Aggressive: they also attack anything hostile within about 10 yards of you. Shows what you last sent; it is sent again to every bot that joins.") RefreshStance() - -- Two on/off check boxes at the bottom (the client's own check box). AoE: the bots use their area spells whenever they can - -- (server: "aoe_all on|off", whispered to one of your bots, which applies it to every bot in the group). Crowd control: on (the - -- default) the bots crowd-control the mobs you mark. + -- Two on/off check boxes at the bottom (the client's own check box). Area spells: on (the server's start setting) the bots use + -- them as their rotations call for; off, nothing that hits more than one enemy (server: "aoe_all on|off", whispered to one of + -- your bots, which applies it to every bot in the group). Crowd control: on (the default) the bots crowd-control the mobs you mark. local function Switch(y, key, default, caption, onText, offText, send) local cb = CreateFrame("CheckButton", nil, ordersGrid, "UICheckButtonTemplate") cb:SetSize(26, 26) @@ -871,9 +1169,9 @@ function UI.BuildOrders() end) cb:SetScript("OnLeave", function() GameTooltip:Hide() end) end - Switch(LAYOUT.PANE_H - 56, "aoe", false, "Use area spells freely", - "The bots use their area spells whenever they can.", - "The bots use area spells only when several mobs are close together.", + Switch(LAYOUT.PANE_H - 56, "aoeOn", true, "Area spells", + "The bots use their area spells as their rotations call for.", + "No spell that hits more than one enemy (Blizzard, Consecration, Multi-Shot, Cleave...): keeps a sheep or sap safe.", function(on) local asker = ListAsker() if asker then SendChatMessage("aoe_all " .. (on and "on" or "off"), "WHISPER", nil, asker) @@ -890,11 +1188,8 @@ function UI.BuildBots() ---------------------------------------------------------------------------------------------- bots local botsPane = NewPane() Section(botsPane, 0, "Add a bot") - local faction = UnitFactionGroup("player") - local shown = {} - for _, class in ipairs(CLASSES) do - if not class.faction or class.faction == faction then shown[#shown + 1] = class end - end + -- Every class for both factions: Forever has Dwarf Shamans for the Alliance and Undead Paladins for the Horde. + local shown = CLASSES local selFS = botsPane:CreateFontString(nil, "OVERLAY", "GameFontNormal") selFS:SetPoint("TOPLEFT", botsPane, "TOPLEFT", 4, -68) selFS:SetWidth(86) @@ -969,7 +1264,7 @@ function UI.BuildBots() SelectClass(1) local quick = Btn(botsPane, 0, 106, 117, 24, "Quick party", {}) quick:SetScript("OnClick", QuickParty) - Tip(quick, "Quick party", "Adds a tank, a healer and three damage dealers at your level.") + Tip(quick, "Quick party", "Fills your group with bots at your level: to five in the open world and 5-player dungeons, to the size of a bigger instance (10 in Upper Blackrock Spire) or raid.") gearBtn = Btn(botsPane, 121, 106, 117, 24, "", {}) gearBtn:SetScript("OnClick", function() local cur = ForeverBotsDB.gear or "match" @@ -1102,7 +1397,7 @@ function UI.BuildMarks() statusFS:SetJustifyH("LEFT") for i = 1, MAX_LIST do local fs = marksPane:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall") - fs:SetPoint("TOPLEFT", marksPane, "TOPLEFT", 4, -120 - (i - 1) * 12) + fs:SetPoint("TOPLEFT", marksPane, "TOPLEFT", 4, -118 - (i - 1) * 11) fs:SetWidth(LAYOUT.CONTENT - 8) fs:SetJustifyH("LEFT") fs:SetWordWrap(false) @@ -1110,21 +1405,22 @@ function UI.BuildMarks() end RefreshList() - Section(marksPane, 180, "Tanks") + -- the five list lines end at 174; the Tanks block sits below them and clear of the footer buttons + Section(marksPane, 178, "Tanks") local markerBtn - local mt = Btn(marksPane, 0, 202, 117, 22, "Main tank", {}) + local mt = Btn(marksPane, 0, 200, 117, 22, "Main tank", {}) mt:SetScript("OnClick", function() GroupOrder("set main tank") end) Tip(mt, "Make main tank", "Sets the raid Main Tank flag on the raid member you target. Raid groups only.") - markerBtn = Btn(marksPane, 121, 202, 117, 22, "Mark: " .. TANK_MARKERS[tankMarker], {}) + markerBtn = Btn(marksPane, 121, 200, 117, 22, "Mark: " .. TANK_MARKERS[tankMarker], {}) markerBtn:SetScript("OnClick", function(self) tankMarker = tankMarker % #TANK_MARKERS + 1 self:SetText("Mark: " .. TANK_MARKERS[tankMarker]) end) Tip(markerBtn, "Marker", "Click to cycle the marker (skull, cross, star, circle, diamond, triangle, moon, square) the next button hands out.") - local give = Btn(marksPane, 0, 226, 117, 22, "Give to tank", {}) + local give = Btn(marksPane, 0, 224, 117, 22, "Give to tank", {}) give:SetScript("OnClick", function() GroupOrder("tank target " .. TANK_MARKERS[tankMarker]) end) Tip(give, "Give marker to tank", "The tank bot you target holds whichever mob carries this marker (mark the mob yourself with the raid icons).") - local clearTanks = Btn(marksPane, 121, 226, 117, 22, "Clear tanks", {}) + local clearTanks = Btn(marksPane, 121, 224, 117, 22, "Clear tanks", {}) clearTanks:SetScript("OnClick", function() GroupOrder("clear tanks") end) Tip(clearTanks, "Clear tanks", "Back to the automatic tank split.") end @@ -1157,8 +1453,28 @@ function UI.BuildTabs() form = "Interface\\Icons\\INV_Misc_Map_01", marks = "Interface\\TargetingFrame\\UI-RaidTargetingIcon_8", } + -- The tabs are secure click handlers: the client runs their pane switch as its own code, so they work in combat too (an add-on + -- function may not show or hide the Orders pane in a fight, 0.5.15 in UBRS 2026-10-26: Follow and Stop could not be reached). + -- Without the secure template (an older client) a tab is a plain button and a switch to or from Orders waits for the end of combat. + local switchSnippet = [[ + local want = self:GetAttribute("fbtab") + for k = 1, 4 do + local p = self:GetFrameRef("fbpane" .. k) + if p then + if k == want then p:Show() else p:Hide() end + end + end + ]] for i, def in ipairs(TAB_DEFS) do - local t = CreateFrame("CheckButton", nil, frame) + local okT, t = pcall(CreateFrame, "CheckButton", nil, frame, "SecureHandlerClickTemplate") + if okT and t and t.SetFrameRef then + t:SetAttribute("fbtab", i) + for k, pane in ipairs(framePanes) do t:SetFrameRef("fbpane" .. k, pane) end + t:SetAttribute("_onclick", switchSnippet) + t.fbSecure = true + else + t = CreateFrame("CheckButton", nil, frame) + end t:SetSize(32, 32) t:SetPoint("TOPLEFT", frame, "TOPRIGHT", -1, -(36 + (i - 1) * LAYOUT.TAB_STEP)) local border = t:CreateTexture(nil, "BACKGROUND") @@ -1177,7 +1493,12 @@ function UI.BuildTabs() -- which blacked out whichever tab was selected local ct = t:GetCheckedTexture() if ct and ct.SetBlendMode then ct:SetBlendMode("ADD") end - t:SetScript("OnClick", function() ShowTab(i) end) + if t.fbSecure then + -- after the secure switch: remember the tab and light it + t:HookScript("OnClick", function() UI.TabShown(i) end) + else + t:SetScript("OnClick", function() ShowTab(i) end) + end t:SetScript("OnEnter", function(self) GameTooltip:SetOwner(self, "ANCHOR_RIGHT") GameTooltip:SetText(def[2]) @@ -1200,12 +1521,13 @@ local function BuildFrame() frame:SetClampedToScreen(true) frame:EnableMouse(true) frame:RegisterForDrag("LeftButton") - frame:SetScript("OnDragStart", frame.StartMoving) - frame:SetScript("OnDragStop", function(self) - self:StopMovingOrSizing() - local point, _, relPoint, x, y = self:GetPoint() - ForeverBotsDB.pos = { point, relPoint, x, y } + -- no drag in a fight (the client refuses moving a protected frame); a drag still going when combat starts is ended then + frame:SetScript("OnDragStart", function(self) + if UI.Locked(self) then return end + self.fbMoving = true + self:StartMoving() end) + frame:SetScript("OnDragStop", function(self) UI.StopDrag(self) end) if ForeverBotsDB.pos then local p = ForeverBotsDB.pos frame:ClearAllPoints() @@ -1221,10 +1543,25 @@ local function BuildFrame() t:SetPoint("TOP", frame, "TOP", 0, -10) t:SetText("WoW Forever Bots") end - if not (native and frame.CloseButton) then - local close = CreateFrame("Button", nil, frame, "UIPanelCloseButton") + local close = native and frame.CloseButton + if not close then + close = CreateFrame("Button", nil, frame, "UIPanelCloseButton") close:SetPoint("TOPRIGHT", 2, 2) end + -- The template's close script is replaced by a secure one that hides the window in combat too (an add-on function may not). + -- The secure handler sits on its own button over the X, as the X itself was created without the template. + local okC, sc = pcall(CreateFrame, "Button", nil, close, "SecureHandlerClickTemplate") + if okC and sc and sc.SetFrameRef then + sc:SetAllPoints(close) + sc:SetFrameRef("fbwin", frame) + sc:SetAttribute("_onclick", [[ self:GetFrameRef("fbwin"):Hide() ]]) + sc:HookScript("OnEnter", function() local f = close:GetScript("OnEnter"); if f then f(close) end end) + close:SetScript("OnClick", nil) + else + close:SetScript("OnClick", function() UI.SetWindowShown(false) end) + end + -- the secure window key (Key Bindings: "Show / hide the bot window (works in combat)") + if UI.keyWindow and UI.keyWindow.SetFrameRef then UI.keyWindow:SetFrameRef("fbwin", frame) end -- dark inner panel under the contents, as in the client's own windows local inset = frame.Inset @@ -1265,11 +1602,12 @@ local function BuildFrame() -- Only /fb (or the X button) closes it, and the open state is remembered across /reload and relog. frame:SetScript("OnShow", function(self) ForeverBotsDB.open = true + UI.afterCombat[self] = nil -- shown by the secure window key: a waiting open is done self.fbTick = 0 RequestList() UpdateEmpty() end) - frame:SetScript("OnHide", function() ForeverBotsDB.open = false end) + frame:SetScript("OnHide", function(self) ForeverBotsDB.open = false; UI.afterCombat[self] = nil end) end @@ -1330,11 +1668,72 @@ distFrame:SetScript("OnEvent", function(self, event) OnGroupChanged() end) -local function Toggle() - if not frame then BuildFrame() end - if frame:IsShown() then frame:Hide() else frame:Show() end +function UI.StopDrag(self) + if not self.fbMoving then return end + self.fbMoving = nil + self:StopMovingOrSizing() + local point, _, relPoint, x, y = self:GetPoint() + ForeverBotsDB.pos = { point, relPoint, x, y } end +-- Opens or closes the window, or says it will once combat ends. The window is built out of combat only: it creates the secure +-- order buttons and sets their macros. +function UI.SetWindowShown(show) + if not frame then + if not show then UI.buildAfterCombat = nil; return end + if InCombatLockdown and InCombatLockdown() then + UI.buildAfterCombat = true + Print("the bot window opens when combat ends.") + return + end + BuildFrame() + end + if not UI.SetShown(frame, show) and UI.afterCombat[frame] ~= nil then + Print(show and "the bot window opens when combat ends." or "the bot window closes when combat ends.") + end +end + +local function Toggle() + local open + if frame then + open = frame:IsShown() + if UI.afterCombat[frame] ~= nil then open = UI.afterCombat[frame] end -- a second press undoes the one waiting + else + open = UI.buildAfterCombat and true or false + end + UI.SetWindowShown(not open) +end + +local combatFrame = CreateFrame("Frame") +combatFrame:RegisterEvent("PLAYER_REGEN_DISABLED") +combatFrame:RegisterEvent("PLAYER_REGEN_ENABLED") +combatFrame:SetScript("OnEvent", function(_, event) + if event == "PLAYER_REGEN_DISABLED" then + -- still allowed here, a moment before the lockdown starts + if frame then UI.StopDrag(frame) end + return + end + if UI.buildLater then + UI.buildLater = nil + if not frame then BuildFrame() end + end + if UI.buildAfterCombat then + UI.buildAfterCombat = nil + if not frame then BuildFrame() end + frame:Show() + end + if frame and UI.scaleAfterCombat then + UI.scaleAfterCombat = nil + frame:SetScale(WindowScale()) + end + if UI.pendingTab then ShowTab(UI.pendingTab) end + tabWaitSaid = nil + for f, show in pairs(UI.afterCombat) do + UI.afterCombat[f] = nil + if show then f:Show() else f:Hide() end + end +end) + function ForeverBots_ToggleWindow() Toggle() end ------------------------------------------------------------------------------------------------------------- minimap button @@ -1734,12 +2133,214 @@ end -- the box from those callbacks. That is chat-box access without a player action and is what the client blocks -- (2026-10-15), so the hooks are gone. The portrait menu's "Whisper (Forever Bots)" and typed /w are the supported ways. +-- The bot submenu of the unit right-click menu (a group member): orders and the bot's own picks, each a whisper to that bot. +-- Class entries appear from the level the spell is trained at; the server answers "I don't know ... yet" for one the bot lacks +-- (a talent such as Kings or Sanctity). The picks are the server's "prefer " (memory only there, and here), so the +-- marks below show what was sent in this session. +local MARKERS = { "star", "circle", "diamond", "triangle", "moon", "square", "cross", "skull" } +local MARKER_LABEL = { star = "Star", circle = "Circle", diamond = "Diamond", triangle = "Triangle", moon = "Moon", square = "Square", + cross = "Cross", skull = "Skull" } +-- slot word, menu title, class token, { word, label, level } (word = the server's first word for the choice, Bot/OwnerPicks.h) +local PICKS = { + { "blessing", "Blessing", "PALADIN", { + { "might", "Blessing of Might", 4 }, { "wisdom", "Blessing of Wisdom", 14 }, { "kings", "Blessing of Kings", 20 }, + { "salvation", "Blessing of Salvation", 26 }, { "light", "Blessing of Light", 40 }, { "sanctuary", "Blessing of Sanctuary", 30 } } }, + { "aura", "Aura", "PALADIN", { + { "devotion", "Devotion Aura", 1 }, { "retribution", "Retribution Aura", 16 }, { "concentration", "Concentration Aura", 22 }, + { "shadow", "Shadow Resistance Aura", 28 }, { "frost", "Frost Resistance Aura", 32 }, { "fire", "Fire Resistance Aura", 36 }, + { "sanctity", "Sanctity Aura", 20 } } }, + { "earth", "Earth totem", "SHAMAN", { + { "stoneskin", "Stoneskin Totem", 4 }, { "earthbind", "Earthbind Totem", 6 }, { "stoneclaw", "Stoneclaw Totem", 8 }, + { "strength", "Strength of Earth Totem", 10 }, { "tremor", "Tremor Totem", 18 } } }, + { "fire", "Fire totem", "SHAMAN", { + { "searing", "Searing Totem", 10 }, { "nova", "Fire Nova Totem", 12 }, { "frost", "Frost Resistance Totem", 24 }, + { "magma", "Magma Totem", 26 }, { "flametongue", "Flametongue Totem", 28 } } }, + { "water", "Water totem", "SHAMAN", { + { "healing", "Healing Stream Totem", 20 }, { "poison", "Poison Cleansing Totem", 22 }, { "mana", "Mana Spring Totem", 26 }, + { "fire", "Fire Resistance Totem", 28 }, { "disease", "Disease Cleansing Totem", 38 } } }, + { "air", "Air totem", "SHAMAN", { + { "grounding", "Grounding Totem", 30 }, { "nature", "Nature Resistance Totem", 30 }, { "windfury", "Windfury Totem", 32 }, + { "windwall", "Windwall Totem", 36 }, { "grace", "Grace of Air Totem", 42 }, { "tranquil", "Tranquil Air Totem", 50 } } }, + { "aspect", "Aspect", "HUNTER", { + { "monkey", "Aspect of the Monkey", 4 }, { "hawk", "Aspect of the Hawk", 10 }, { "cheetah", "Aspect of the Cheetah (out of combat)", 20 }, + { "pack", "Aspect of the Pack (out of combat)", 30 }, { "wild", "Aspect of the Wild", 46 } } }, + { "demon", "Demon", "WARLOCK", { + { "imp", "Imp", 1 }, { "voidwalker", "Voidwalker", 10 }, { "succubus", "Succubus", 20 }, { "felhunter", "Felhunter", 30 } } }, +} +local PORTALS = { + Alliance = { { "stormwind", "Stormwind" }, { "ironforge", "Ironforge" }, { "darnassus", "Darnassus" } }, + Horde = { { "orgrimmar", "Orgrimmar" }, { "undercity", "Undercity" }, { "thunder bluff", "Thunder Bluff" } }, +} +-- Crowd control the owner can say no to for a whole class (the server's "@ no ", CcDeny.h): kind word, label. +local DANGER = { + WARRIOR = { { "fear", "Intimidating Shout" } }, + PRIEST = { { "fear", "Psychic Scream" }, { "shackle", "Shackle Undead" } }, + WARLOCK = { { "fear", "Fear, Howl of Terror, Death Coil" }, { "banish", "Banish" }, { "seduce", "Seduction, Enslave Demon" } }, + MAGE = { { "sheep", "Polymorph" } }, + HUNTER = { { "fear", "Scare Beast" }, { "trap", "Freezing Trap" }, { "sleep", "Wyvern Sting" } }, + ROGUE = { { "sap", "Sap" } }, + DRUID = { { "sleep", "Hibernate" } }, + PALADIN = { { "fear", "Turn Undead" } }, +} +local sentPicks = {} -- [bot name][slot word] = choice word, this session + +local function MenuWhisper(who, text) + local ok, err = pcall(SendChatMessage, text, "WHISPER", nil, who) + if not ok then Print("could not whisper " .. who .. ": " .. tostring(err)) end +end + +-- The group members by name (yourself first), for the summon and soulstone lists. +local function GroupNames() + local names = {} + local me = SafeName("player") + if me then names[#names + 1] = me end + local raid = IsInRaid and IsInRaid() + local n = (GetNumGroupMembers and GetNumGroupMembers()) or 0 + for i = 1, raid and n or math.max(0, n - 1) do + local nm = SafeName((raid and "raid" or "party") .. i) + if nm and nm ~= me then names[#names + 1] = strtrim((strsplit("-", nm))) end + end + return names +end + +local function AddBotMenu(root, unit, who) + local token = select(2, UnitClass(unit)) + local level = UnitLevel(unit) or 0 + local function Send(text) MenuWhisper(who, text) end + local function Mark(on) return on and "|cff40ff40>|r " or "" end + local menu = root:CreateButton("WoW Forever Bots") + menu:CreateButton("Open the bot panel", function() + botForced = { name = who, token = token } + if not botPanel then BuildBotPanel() end + UpdateBotPanel() + end) + menu:CreateButton("Follow me", function() Send("follow") end) + menu:CreateButton("Stay here", function() Send("stay") end) + menu:CreateButton("Attack my target", function() Send("attack") end) + local mineAoe = sentPicks[who] and sentPicks[who].aoe + local aoe = menu:CreateButton("Area spells") + aoe:CreateButton(Mark(mineAoe ~= "off") .. "On", function() + sentPicks[who] = sentPicks[who] or {}; sentPicks[who].aoe = nil; Send("aoe on") + end) + aoe:CreateButton(Mark(mineAoe == "off") .. "Off: nothing that hits more than one enemy", function() + sentPicks[who] = sentPicks[who] or {}; sentPicks[who].aoe = "off"; Send("aoe off") + end) + + -- Role: the roles of the class (CLASSES), and auto (the spec decides again). + for _, c in ipairs(CLASSES) do + if c.token == token and #c.roles > 1 then + local roleMenu = menu:CreateButton("Role") + for _, r in ipairs(c.roles) do + roleMenu:CreateButton(ROLE_LABEL[r] or r, function() Send("setrole " .. r) end) + end + roleMenu:CreateButton("Auto (by spec)", function() Send("setrole clear") end) + end + end + + -- Raid icons: the bot follows the icon you put on a mob (the server's "assign [kill|cc|tank]"). + local icons = menu:CreateButton("Raid icon") + local function IconList(parent, role) + for _, m in ipairs(MARKERS) do + parent:CreateButton(MARKER_LABEL[m], function() Send("assign " .. m .. (role and (" " .. role) or "")) end) + end + end + IconList(icons:CreateButton("Kill it first"), "kill") + if token ~= "WARRIOR" and token ~= "SHAMAN" then IconList(icons:CreateButton("Crowd-control it"), "cc") end + if token == "WARRIOR" or token == "PALADIN" or token == "DRUID" then IconList(icons:CreateButton("Tank it"), "tank") end + icons:CreateButton("Clear", function() Send("assign clear " .. who) end) + + -- The bot's own picks for its class. + local mine = sentPicks[who] or {} + for _, slot in ipairs(PICKS) do + if slot[3] == token then + local sub + for _, ch in ipairs(slot[4]) do + if level >= ch[3] then + sub = sub or menu:CreateButton(slot[2]) + sub:CreateButton(Mark(mine[slot[1]] == ch[1]) .. ch[2], function() + sentPicks[who] = sentPicks[who] or {} + sentPicks[who][slot[1]] = ch[1] + Send("prefer " .. slot[1] .. " " .. ch[1]) + end) + end + end + if sub then + sub:CreateButton(Mark(mine[slot[1]] == nil) .. "Auto (the group plan)", function() + if sentPicks[who] then sentPicks[who][slot[1]] = nil end + Send("prefer " .. slot[1] .. " auto") + end) + end + end + end + if token == "HUNTER" or token == "WARLOCK" then + local pet = menu:CreateButton("Pet") + pet:CreateButton(Mark(mine.pet ~= "off") .. "Keep the pet out", function() + sentPicks[who] = sentPicks[who] or {}; sentPicks[who].pet = nil; Send("pet on") + end) + pet:CreateButton(Mark(mine.pet == "off") .. "Dismiss it and keep it away", function() + sentPicks[who] = sentPicks[who] or {}; sentPicks[who].pet = "off"; Send("pet off") + end) + end + if token == "ROGUE" then + local st = menu:CreateButton("Stealth") + st:CreateButton(Mark(mine.stealth ~= "off") .. "Open from Stealth", function() + sentPicks[who] = sentPicks[who] or {}; sentPicks[who].stealth = nil; Send("stealth on") + end) + st:CreateButton(Mark(mine.stealth == "off") .. "No Stealth (and no Sap)", function() + sentPicks[who] = sentPicks[who] or {}; sentPicks[who].stealth = "off"; Send("stealth off") + end) + end + if token == "WARLOCK" and level >= 20 then + local sm = menu:CreateButton("Summon a player") + for _, nm in ipairs(GroupNames()) do + if nm ~= who then sm:CreateButton(nm, function() Send("ritual " .. nm) end) end + end + sm:CreateButton("Help click the portal (party)", function() GroupOrder("use summoning") end) + end + if token == "WARLOCK" and level >= 18 then + local ss = menu:CreateButton("Soulstone") + for _, nm in ipairs(GroupNames()) do + ss:CreateButton(nm, function() Send("soulstone " .. nm) end) + end + end + -- Mage: conjured water and food are a craft order; the mage asks you to open a trade with it and hands them over. + if token == "MAGE" and level >= 4 then + menu:CreateButton("Conjure water", function() Send("craft water x20") end) + if level >= 6 then menu:CreateButton("Conjure food", function() Send("craft food x20") end) end + end + if token == "MAGE" and level >= 40 then + local ok, faction = pcall(UnitFactionGroup, unit) + local list = ok and PORTALS[faction] + if list then + local pm = menu:CreateButton("Open a portal") + for _, c in ipairs(list) do pm:CreateButton(c[2], function() Send("portal " .. c[1]) end) end + end + end + + -- No danger spells: the owner's crowd-control orders for the whole class (every bot of it, and ones that join later). + local danger = DANGER[token] + if danger then + local cls = strlower(token) + local dm = menu:CreateButton("Danger spells (all " .. cls .. "s)") + for _, d in ipairs(danger) do + dm:CreateButton("No " .. d[2], function() Send("@" .. cls .. " no " .. d[1]) end) + end + dm:CreateButton("No crowd control at all", function() Send("@" .. cls .. " off cc") end) + dm:CreateButton("Allow all again", function() Send("@" .. cls .. " on cc") end) + end + menu:CreateButton("What did I pick?", function() Send("prefer") end) + menu:CreateButton("Clear my picks", function() + sentPicks[who] = { aoe = sentPicks[who] and sentPicks[who].aoe } -- the area-spell switch is not a pick + Send("prefer clear") + end) +end + local function AddPopupEntry() Step("portrait menu entries") if not (Menu and Menu.ModifyMenu) then return end -- /fb menu off (then /reload) leaves the client's unit menus completely untouched: a menu we modified can taint the client's -- own menu actions ("ForeverBots has been blocked from an action only available to the Blizzard UI", reported 2026-10-15). - if ForeverBotsDB.menuEntries == false then return end + if ForeverBotsDB.menuEntries == false or not PARTS.On("menu") then return end -- Entries through the client's supported Menu.ModifyMenu only (no UnitPopup tables, no hooks). The client's own portrait -- Invite sends nothing for a bot on 70338 (playtest 2026-10-11: no CMSG_PARTY_INVITE from the menu, typed /invite works), so -- "Whisper (Forever Bots)" is added for every friendly player, "Invite (Forever Bots)" for one outside my group, and the @@ -1762,12 +2363,7 @@ local function AddPopupEntry() root:CreateDivider() root:CreateButton("Whisper (Forever Bots)", function() OpenWhisperBox(who) end) if grouped then - root:CreateButton("WoW Forever Bots", function() - local token = select(2, UnitClass(unit)) - botForced = { name = who, token = token } - if not botPanel then BuildBotPanel() end - UpdateBotPanel() - end) + AddBotMenu(root, unit, who) else -- The client's own Invite entry sends nothing on this build: point it at the working call instead of -- leaving a dead entry next to ours. Our own entry stays when the native one is not found. @@ -1791,6 +2387,7 @@ local function AddPopupEntry() end) if not ok then Debug("unit menu entry skipped") end end + modify = PerfWrap("menu", modify) for _, tag in ipairs({ "MENU_UNIT_PARTY", "MENU_UNIT_RAID_PLAYER", "MENU_UNIT_RAID", "MENU_UNIT_PLAYER", "MENU_UNIT_TARGET", "MENU_UNIT_FOCUS" }) do pcall(Menu.ModifyMenu, tag, modify) end @@ -1904,6 +2501,7 @@ SLASH_FOREVERBOTS1 = "/fb" SLASH_FOREVERBOTS2 = "/foreverbots" SlashCmdList.FOREVERBOTS = function(msg) local verb, class, role, extra = strsplit(" ", strlower(strtrim(msg or ""))) + verb = verb and verb:gsub("[%p]+$", "") -- "/fb perf." (dictated) is still perf if verb == "chat" then if class == "on" then ForeverBotsDB.showChat = true elseif class == "off" then ForeverBotsDB.showChat = false @@ -1923,11 +2521,37 @@ SlashCmdList.FOREVERBOTS = function(msg) local n = tonumber(class) if n then ForeverBotsDB.scale = math.max(SCALE_MIN, math.min(SCALE_MAX, n)) - if frame then frame:SetScale(WindowScale()) end + if frame and UI.Locked(frame) then UI.scaleAfterCombat = true elseif frame then frame:SetScale(WindowScale()) end end Print("window size: " .. string.format("%.2f", WindowScale()) .. " (/fb scale " .. SCALE_MIN .. "-" .. SCALE_MAX .. ", default " .. SCALE_DEFAULT .. ")") return end + if verb == "perf" then + if class == "reset" then + for _, st in pairs(PERF.stats) do st.n, st.total, st.max = 0, 0, 0 end + PERF.said = {} + Print("handler timings cleared.") + return + end + local lines = PERF.Report(12) + Print("slowest handlers since login (/fb perf reset clears; saved at logout):" .. (#lines == 0 and " none yet" or "")) + for _, l in ipairs(lines) do Print(" " .. l) end + return + end + if verb == "part" then + local known = {} + for _, part in ipairs(PARTS.list) do known[part] = true end + if known[class] and (role == "on" or role == "off") then + ForeverBotsDB.partsOff = ForeverBotsDB.partsOff or {} + ForeverBotsDB.partsOff[class] = (role == "off") or nil + Print(class .. " " .. role .. " after /reload.") + return + end + local states = {} + for _, part in ipairs(PARTS.list) do states[#states + 1] = part .. " " .. (PARTS.On(part) and "on" or "off") end + Print("parts: " .. table.concat(states, ", ") .. " (/fb part on|off, then /reload)") + return + end if verb == "debug" then if class == "on" then debugOn = true elseif class == "off" then debugOn = false @@ -1996,7 +2620,7 @@ SlashCmdList.FOREVERBOTS = function(msg) end if verb == "frames" then local list = ForeverBotsListIssueFrames and ForeverBotsListIssueFrames() or {} - Print("issue reporter frames hidden: " .. (#list > 0 and table.concat(list, ", ") or "none found")) + Print("issue reporter frames hidden: " .. (#list > 0 and table.concat(list, ", ") or "none found") .. " (a new search runs over the next second; type /fb frames again for its result)") return end if verb == "chattest" then @@ -2110,9 +2734,11 @@ SlashCmdList.FOREVERBOTS = function(msg) elseif verb == "" or verb == nil then Toggle() else - Print("/fb opens the window; /fb add [tank|healer|dps]; /fb raidready; /fb call|dismiss|save|unsave|regear [name|all]; /fb delete ; /fb list; /fb fallback; /fb pullback; /fb rally; /fb formation circle|arrow|line|none; /fb spacing tight|close|spread; /fb distance <1-20>; /fb maintank [name]; /fb bot on|off; /fb tank |clear; /fb assign [role]|clear|list; /fb minimap on|off|reset; /fb scale <0.7-1.5>; /fb resume; /fb flee; /fb quick; /fb debug on|off") + Print("unknown /fb word \"" .. tostring(verb) .. "\" (add-on " .. (UI.version or "?") .. ")") + Print("/fb opens the window; /fb add [tank|healer|dps]; /fb raidready; /fb call|dismiss|save|unsave|regear [name|all]; /fb delete ; /fb list; /fb fallback; /fb pullback; /fb rally; /fb formation circle|arrow|line|none; /fb spacing tight|close|spread; /fb distance <1-20>; /fb maintank [name]; /fb bot on|off; /fb tank |clear; /fb assign [role]|clear|list; /fb minimap on|off|reset; /fb scale <0.7-1.5>; /fb resume; /fb flee; /fb quick; /fb debug on|off; /fb perf [reset]; /fb part [name on|off]") end end +UI.slash = SlashCmdList.FOREVERBOTS -- Tells the server this client runs the add-on (a self-whisper under the order prefix), so it does not send the download hint. -- Tried a few times: the first send can be refused while the client is still loading. @@ -2137,16 +2763,30 @@ end local loader = CreateFrame("Frame") loader:RegisterEvent("PLAYER_LOGIN") loader:SetScript("OnEvent", function() - Print("type /fb for the bot window.") + -- the version in the greeting, so a screenshot shows which copy the client loaded + local getMeta = (C_AddOns and C_AddOns.GetAddOnMetadata) or GetAddOnMetadata + local okV, ver = pcall(getMeta, ADDON, "Version") + if okV and type(ver) == "string" then UI.version = ver end + Print("type /fb for the bot window." .. (UI.version and (" (" .. UI.version .. ")") or "")) + -- A second copy of this add-on under another folder name (an old one) sets /fb too, and the copy loaded last owns it: say which. + if SlashCmdList.FOREVERBOTS ~= UI.slash then + local okS, secure, who = pcall(issecurevariable, SlashCmdList, "FOREVERBOTS") + Print("|cffff4040/fb belongs to another add-on (" .. tostring(okS and not secure and who or "?") .. "), not to this " .. ADDON + .. " " .. (UI.version or "") .. ": remove the old copy from Interface\\AddOns.|r") + end if C_Timer and C_Timer.After then C_Timer.After(2, SayHello) else SayHello() end - AddPopupEntry() - BuildMinimapButton() + PerfWrap("login: menu entries", AddPopupEntry)() + PerfWrap("login: minimap button", BuildMinimapButton)() lastGroupSize = GroupSize() ShowDistance() if ForeverBotsDB.distance and lastGroupSize > 0 then distFrame.groupAt = Now() + 3 end - if ForeverBotsDB.open then - if not frame then BuildFrame() end - frame:Show() + -- built at login (hidden unless it was open), so the secure window key can show it in a fight + if InCombatLockdown and InCombatLockdown() then + UI.buildLater = true + if ForeverBotsDB.open then UI.buildAfterCombat = true end + else + if not frame then PerfWrap("login: build window", BuildFrame)() end + if ForeverBotsDB.open then frame:Show() end end end) @@ -2191,8 +2831,9 @@ end -- The beta client's "Issue Reporter" bug button (bottom right, also the "F6 to submit an issue" hint) is hidden (playtest 2026-10-12). -- The 70338 interface source is not at hand, so the frame is found by name: any global frame whose name contains "IssueReport" -- or "BugReport" (and the common names tried directly). Hide() plus a Show hook that hides it again: nothing is reparented or --- replaced, the frame is not protected, so there is no taint and it works in combat. Re-applied on PLAYER_ENTERING_WORLD and on --- every ADDON_LOADED (the button may belong to a load-on-demand Blizzard addon). "/fb frames" lists what was found. +-- replaced, the frame is not protected, so there is no taint and it works in combat. The known names are tried again on +-- PLAYER_ENTERING_WORLD and every ADDON_LOADED (the button may belong to a load-on-demand Blizzard addon). "/fb frames" lists +-- what was found. do local hooked, found = {}, {} local function HideFrame(name, f) @@ -2203,25 +2844,60 @@ do pcall(f.SetAlpha, f, 0) pcall(hooksecurefunc, f, "Show", function(self) pcall(self.SetAlpha, self, 0) end) end - local function Scan() + local KNOWN = { "IssueReporterButton", "IssueReporterFrame", "IssueReporter", "BetaIssueReporter", "BugReportButton", "BugReportFrame" } + local function ScanKnown() Step("issue reporter hide") - for _, name in ipairs({ "IssueReporterButton", "IssueReporterFrame", "IssueReporter", "BetaIssueReporter", "BugReportButton", "BugReportFrame" }) do + for _, name in ipairs(KNOWN) do local f = _G[name] if type(f) == "table" and f.Hide and f.GetObjectType then HideFrame(name, f) end end - for name, f in pairs(_G) do - if type(name) == "string" and not hooked[f] and (name:find("IssueReport", 1, true) or name:find("BugReport", 1, true)) then - if type(f) == "table" and f.Hide and f.GetObjectType and f.IsProtected then HideFrame(name, f) end - end + Step("") + end + local function Match(name, f) + if type(name) == "string" and not hooked[f] and (name:find("IssueReport", 1, true) or name:find("BugReport", 1, true)) then + if type(f) == "table" and f.Hide and f.GetObjectType and f.IsProtected then HideFrame(name, f) end end end - local watch = CreateFrame("Frame") - watch:RegisterEvent("PLAYER_ENTERING_WORLD") - watch:RegisterEvent("ADDON_LOADED") - watch:SetScript("OnEvent", function() pcall(Scan); Step("") end) - pcall(Scan) - Step("") - ForeverBotsListIssueFrames = function() pcall(Scan); return found end + -- The walk over every global name is spread over frames, SCAN_STEP names a frame: on client 70630 one walk per ADDON_LOADED + -- (about a hundred of them at login) raised "Script from ForeverBots has exceeded its execution time limit" (BRS 2026-10-27). + -- It runs once after login or /reload, and on "/fb frames"; ADDON_LOADED and zoning only try the known names. + local SCAN_STEP = 2000 + local walker = CreateFrame("Frame") + walker:Hide() + walker:SetScript("OnUpdate", function(self) + Step("issue reporter scan") + local ok, done = pcall(function() + local k, v = self.key, nil + for _ = 1, SCAN_STEP do + k, v = next(_G, k) + if k == nil then return true end + Match(k, v) + end + self.key = k + return false + end) + Step("") + if not ok or done then + self.key = nil + self:Hide() + end + end) + local function ScanAll() + ScanKnown() + walker.key = nil + walker:Show() + end + AddPart("reporter", function() + local watch = CreateFrame("Frame") + watch:RegisterEvent("PLAYER_ENTERING_WORLD") + watch:RegisterEvent("ADDON_LOADED") + watch:SetScript("OnEvent", function(_, event, isLogin, isReload) + pcall(ScanKnown) + if event == "PLAYER_ENTERING_WORLD" and (isLogin or isReload) then ScanAll() end + end) + pcall(ScanKnown) + end) + ForeverBotsListIssueFrames = function() ScanAll(); return found end end ------------------------------------------------------------------------------------------------------ forbidden-action guard @@ -2231,11 +2907,41 @@ end -- only part of the add-on that runs inside the client's own menus, the place such taint comes from (reported 2026-10-15 when -- interacting with a bot portrait). /fb menu on re-enables them. do + -- The add-on itself never calls SetBinding (its keys come from Bindings.xml and the player's own choice in Key Bindings), yet + -- Warsong Gulch 2026-10-25 showed "the client blocked SetBinding() for ForeverBots" four times: client code ran with our taint + -- and called it in a fight. A secure post-hook (it does not taint the caller) keeps who called it last, so the report names the + -- caller instead of a guess; ForeverBotsDB.lastForbidden.stack keeps it for the SavedVariables file. + local lastBinding, bindingPending + AddPart("bindhook", function() + if not (hooksecurefunc and SetBinding) then return end + pcall(hooksecurefunc, "SetBinding", function(key, action) + pcall(function() + lastBinding = { + key = SafeStr(key) or "?", action = SafeStr(action) or "nil", + combat = (InCombatLockdown and InCombatLockdown()) and true or false, + stack = debugstack and (SafeStr(debugstack(3, 6, 0)) or "") or "", + } + end) + end) + end) + local function BindingReport() + local b = lastBinding + if not b then return "no SetBinding call seen by the add-on" end + local callers = {} + for line in string.gmatch(b.stack, "[^\n]+") do + callers[#callers + 1] = (line:gsub("^%s+", ""):gsub("Interface\\AddOns\\", ""):gsub("Interface/AddOns/", "")) + if #callers == 3 then break end + end + return "SetBinding(" .. b.key .. ", " .. b.action .. ")" .. (b.combat and " in combat" or "") .. " from " .. + (#callers > 0 and table.concat(callers, " < ") or "?") + end + local guard = CreateFrame("Frame") guard:RegisterEvent("ADDON_ACTION_FORBIDDEN") pcall(guard.RegisterEvent, guard, "ADDON_ACTION_BLOCKED") guard:SetScript("OnEvent", function(_, event, addon, func) - func = type(func) == "string" and func or "?" + -- the client passes the name with its brackets ("SetBinding()"); every line below adds them itself + func = (type(func) == "string" and not IsSecret(func)) and func:gsub("%(%)$", "") or "?" -- "Interface action failed because of an AddOn" in the chat frame right after login: say which add-on and which call, for -- ours and for any other add-on, so the line can be read instead of guessed at (the pop-up names them only for a moment). if addon ~= ADDON then @@ -2243,8 +2949,22 @@ do return end if event == "ADDON_ACTION_BLOCKED" then - ForeverBotsDB.lastForbidden = { func = func, at = date and date("%Y-%m-%d %H:%M:%S") or "", blocked = true, step = currentStep } - Print("the client blocked " .. func .. "() for ForeverBots (blocked) during: " .. (currentStep ~= "" and currentStep or "no step marked")) + local rec = { func = func, at = date and date("%Y-%m-%d %H:%M:%S") or "", blocked = true, step = currentStep } + ForeverBotsDB.lastForbidden = rec + local step = currentStep ~= "" and currentStep or "no step marked" + if func == "SetBinding" then + -- the post-hook runs once the blocked call returns: read it a moment later, once per burst of blocked calls + if bindingPending then return end + bindingPending = true + local function Report() + bindingPending = nil + rec.stack = lastBinding and lastBinding.stack or "" + Print("the client blocked SetBinding() for ForeverBots during: " .. step .. ". " .. BindingReport() .. ". Please report this line.") + end + if C_Timer and C_Timer.After then C_Timer.After(0, Report) else Report() end + return + end + Print("the client blocked " .. func .. "() for ForeverBots (blocked) during: " .. step) return end ForeverBotsDB.lastForbidden = { func = func, at = date and date("%Y-%m-%d %H:%M:%S") or "" } @@ -2270,3 +2990,4 @@ do end) end +PERF.running = nil -- the file loaded to the end diff --git a/src/modules/PlayerbotV2/Addon/ForeverBots/ForeverBots.toc b/src/modules/PlayerbotV2/Addon/ForeverBots/ForeverBots.toc index bb84443a72..13d3b48569 100644 --- a/src/modules/PlayerbotV2/Addon/ForeverBots/ForeverBots.toc +++ b/src/modules/PlayerbotV2/Addon/ForeverBots/ForeverBots.toc @@ -2,7 +2,7 @@ ## Title: WoW Forever Bots ## Notes: One-click PlayerbotV2 companions: add a bot of any class and role, call, dismiss and command your bots. ## Author: Karrz -## Version: 0.5.12 +## Version: 0.5.23 ## IconTexture: Interface\AddOns\ForeverBots\Textures\mono_fb64.tga ## SavedVariables: ForeverBotsDB diff --git a/src/modules/PlayerbotV2/Addon/ForeverBots/README.md b/src/modules/PlayerbotV2/Addon/ForeverBots/README.md index 1c8851ecbc..095a286f2b 100644 --- a/src/modules/PlayerbotV2/Addon/ForeverBots/README.md +++ b/src/modules/PlayerbotV2/Addon/ForeverBots/README.md @@ -15,8 +15,8 @@ regroup, formation and spacing, tanks and markers), Assign a bot to an icon, You - "Add bots >" at the top opens a separate drop-down beside the window: "Select gear" (Match my gear, Best for their level, Best in slot, Tier 1, 2, 3; remembered; sent to the group as `gear match|best|bis|t1|t2|t3` before an add) and one button per class and role. -- Two switches beside it: AoE (whispers `aoe_all on|off` to one of your bots; it applies to the whole group) and CC (group - order `crowdcontrol on|off`). The icon shows the state last sent. +- Two switches beside it: Area spells (whispers `aoe_all on|off` to one of your bots; it applies to the whole group; off = no + spell that hits more than one enemy) and CC (group order `crowdcontrol on|off`). The icon shows the state last sent. - One button per class and role: adds that bot (`.bot add `). It joins you at your level, geared, in your group. - Orders to the group: Follow, Stay, Attack (your target), Resume; Pull (your tank bots open on your target, the @@ -90,17 +90,37 @@ the bot, right-click clears; the Role button picks tank/cc/kill for the next cli (your target), Pull back, Dist -/+ (this bot only), Dismiss, and a status line showing the bot's confirmation. The confirmation whispers are hidden from chat. `/fb bot on|off` toggles the panel (default on). The client cannot tell a bot from a human group member, so the panel shows for any friendly party/raid member (a `?` after the name until that player -has answered a whisper order); do not use it on real players. Unit right-click menu: an entry "ForeverBots" is added only -where the client offers `Menu.ModifyMenu` (untested here); the legacy UnitPopupMenus tables are deliberately not touched. +has answered a whisper order); do not use it on real players. Unit right-click menu: entries are added only through the +client's `Menu.ModifyMenu`; the legacy UnitPopupMenus tables are deliberately not touched (`/fb menu off` leaves the menus alone). +Right-clicking a member of your group shows "WoW Forever Bots" with a submenu, each entry a whisper to that bot: +- Open the bot panel, Follow me, Stay here, Attack my target; Area spells on / off for this bot (`aoe on|off`); Role (`setrole tank|healer|dps|clear`) for classes with more + than one role; Raid icon: kill it first, crowd-control it, tank it (`assign kill|cc|tank`), Clear. +- The bot's own picks (`prefer `, `prefer auto`): paladin Blessing and Aura, shaman Earth / Fire / Water / + Air totem, hunter Aspect (Cheetah and Pack only out of combat), warlock Demon. A pick replaces the group plan for that one + choice; the other paladins plan around a pinned blessing or aura. A mark shows what you picked in this session. +- Pet (hunter, warlock): keep it out or dismiss it and keep it away (`pet on|off`). Stealth (rogue): `stealth on|off`. +- Warlock: Summon a player (`ritual `, then "Help click the portal" sends `use summoning` to the party) and Soulstone + on a group member (`soulstone `). Mage: Open a portal to a city of the mage's faction (`portal `). + Mage: Conjure water / Conjure food (`craft water x20`, `craft food x20`): the mage conjures them and asks you to open a trade + with it, then puts them in the window (conjured items cannot go by mail). +- Danger spells (all bots of that class): the crowd-control orders `@ no `, `@ off cc`, `@ on cc`. +- What did I pick? (`prefer`) and Clear my picks (`prefer clear`). +Class entries appear from the level the spell is trained at; a talent spell the bot lacks gets "I don't know ... yet". The +picks are memory only on the server: a relog or restart clears them. `/fb add [tank|healer|dps]`, `/fb call|dismiss|save|unsave|regear [name|all]`, `/fb delete `, `/fb list`, The window stays where you put it and stays open (it is not closed by Escape, clicks, combat or target changes; its open state survives /reload and relog). `/fb` toggles it, or use the X button. +In a fight: the side tabs and the X are secure buttons, so every tab (Orders included) and closing work in combat. A second window key, "Show / hide the bot window (works in combat)" in Key Bindings, opens and closes it in combat too. `/fb`, the minimap button, the plain toggle key, dragging and `/fb scale` cannot touch the window in combat (the client keeps it fixed because of its secure order buttons): they wait until combat ends, with one chat line saying so (0.5.16). + `/fb fallback`, `/fb pullback`, `/fb rally`, `/fb formation circle|arrow|line|none`, `/fb spacing tight|close|spread`, `/fb distance <1-20>` and `/fb maintank [name]` and `/fb tank |clear` work without the window. The `.bot` commands for your own bots (add, call, dismiss, save, list, regear and the rest) work for every account; no GM account is needed. Only `.bot world`, `.bot bgstress`, `.bot bgsoak` and `.bot itemstats` are GM. +Timings (0.5.18): every handler the add-on gives the client is timed. A call over 15 ms prints one chat line naming it; `/fb perf` lists the slowest (`/fb perf reset` clears), and the list is saved as `perf` in the SavedVariables file at logout. `/fb part` lists the optional parts that run inside client code (menu, filters, reporter, bindhook); `/fb part off` and `/reload` switch one off. + Key bindings (0.2.2): Esc > Options > Key Bindings > AddOns > "WoW Forever Bots". Unbound by default; one entry each for Attack, Pull, Pull back, Follow, Stay, Resume, Stop attacking, Flee, Come, Fall back, Toggle stance and Show / hide the bot window. The order keys send the same line as the window buttons and work in combat. +Lazy lock key (0.2.4, warlocks): one key that does the right next thing on your target. Each press casts one spell at an enemy, never a pet summon: the curse (Curse of Tongues on mana users, Curse of Agony on the rest), Corruption, Immolate and Siphon Life kept up, Conflagrate, Shadow Bolt as the filler (the free instant bolt on a Shadow Trance proc), Life Tap when mana runs low, Death Coil / Drain Life when your health is low. An enemy hitting you in melee gets Death Coil, then Howl of Terror when two or more are on you, then Fear (not on bosses, and not on mobs in dungeons and raids). Both on-use trinkets and your racial go whenever ready on a long fight, in the same press as the next spell. The wand takes over when mana is dry. Press it with no enemy selected to put Demon Armor up and summon your pet. It also sends your pet at the target. Bind it under "Lazy lock" and tap or mash it; it runs the server command `.playerbot lazy`, which you can also type. Attack (mouseover) key: hover a mob and press it; the mob becomes your target and the bots attack it. Group pings (the ping wheel, if your client has one): an Attack ping on an enemy sends the bots in, an On my way ping on the ground sends them there. Needs a server with the ping hooks. ## 0.5.1 window @@ -109,5 +129,5 @@ Built on the client's own portrait window (the one its Raid and Looking For Grou - `/fb scale <0.7-1.5>` sets the window size (default 1.2, saved). - `/fb minimap on|off|reset` shows, hides or re-centres the minimap button. -- `/fb quick` adds a tank, a healer and three damage dealers; `/fb resume` and `/fb flee` send those two orders. +- `/fb quick` fills your group with bots: to five in the open world and 5-player dungeons, to the instance size in a bigger one (10 in Upper Blackrock Spire, 20 or 40 in a raid), with tanks, healers and damage dealers; `/fb resume` and `/fb flee` send those two orders. - When the client blocks an add-on call, one chat line names the add-on and the call. diff --git a/src/modules/PlayerbotV2/Addon/ForeverDots/ForeverDots.lua b/src/modules/PlayerbotV2/Addon/ForeverDots/ForeverDots.lua new file mode 100644 index 0000000000..9c5d867298 --- /dev/null +++ b/src/modules/PlayerbotV2/Addon/ForeverDots/ForeverDots.lua @@ -0,0 +1,507 @@ +-- ForeverDots: countdown bars for your damage-over-time spells, beside your +-- character, grouped per enemy. +-- +-- This client refuses enemy aura data to add-ons in combat, and add-ons cannot +-- read the combat log. So the bars are timed from your own casts instead: +-- when a damage-over-time spell of yours finishes casting on an enemy, a bar +-- starts with that spell's duration (read from its tooltip text), and a recast +-- on the same enemy restarts it. Nothing here touches aura data, so nothing +-- is refused and nothing is tainted. + +local ADDON = "ForeverDots" +local ROW_H, HEAD_H, GAP = 18, 14, 2 +local MAX_GROUPS = 8 + +local defaults = { locked = true, scale = 1.0, width = 200, red = 3, dur = {} } +local db +local root +local rows, heads = {}, {} +local groups = {} -- list of { key, name, mark, isTarget, dots = { [spellName] = dot } } +local known = {} -- spellID -> duration in seconds, or false when not a DoT +local slot = 0 -- counts target changes; used when GUIDs are hidden +local testMode = false +local dirty = true + +local BAR_COLOR = { 0.58, 0.40, 0.85 } +local RED = { 1.0, 0.12, 0.12 } + +local function pr(msg) DEFAULT_CHAT_FRAME:AddMessage("|cff9966ffForeverDots|r " .. msg) end + +local errors = {} +local function Guard(fn, ...) + local ok, err = pcall(fn, ...) + if not ok then + err = tostring(err) + if not errors[err] then + errors[err] = true + pr("error: " .. err) + end + end +end + +local function Secret(v) + return issecretvalue ~= nil and issecretvalue(v) +end + +-- ---------------------------------------------------------------- spells + +-- Duration of a damage-over-time spell from its tooltip, e.g. "over 18 sec" +-- or "every 3 sec for 30 sec". Returns false for anything else. +local function ReadDuration(spellID) + local name = C_Spell.GetSpellName(spellID) + if not name or Secret(name) then return nil end + if db.dur[name:lower()] then return db.dur[name:lower()] end + if C_Spell.IsSpellHarmful and not C_Spell.IsSpellHarmful(spellID) then return false end + local text = C_Spell.GetSpellDescription(spellID) + if not text or Secret(text) or text == "" then return nil end + local lower = text:lower() + if not (lower:find("damage") or lower:find("from the target")) then return false end + local best + for n in lower:gmatch("over (%d+%.?%d*) sec") do best = math.max(best or 0, tonumber(n)) end + for n in lower:gmatch("for (%d+%.?%d*) sec") do best = math.max(best or 0, tonumber(n)) end + for n in lower:gmatch("lasts (%d+%.?%d*) sec") do best = math.max(best or 0, tonumber(n)) end + for n in lower:gmatch("over (%d+%.?%d*) min") do best = math.max(best or 0, tonumber(n) * 60) end + if best and best >= 4 then return best end + return false +end + +local function Duration(spellID) + local name = C_Spell.GetSpellName(spellID) + if name and not Secret(name) and db.dur[name:lower()] then return db.dur[name:lower()] end + if known[spellID] == nil then + local ok, d = pcall(ReadDuration, spellID) + if ok and d ~= nil then known[spellID] = d end + if not ok then return nil end + end + return known[spellID] +end + +-- Reading every spellbook spell once makes the client load the tooltip +-- texts, so the first cast of a spell already has its duration. +-- +-- 1.2.0 read the whole spellbook in one go on PLAYER_LOGIN, on every +-- SPELLS_CHANGED and on every SPELL_TEXT_UPDATE. Reading the texts makes the +-- client send SPELL_TEXT_UPDATE for each one that arrives, so at login a few +-- hundred full scans ran back to back and client 70630 stopped it ("Script +-- from ForeverDots has exceeded its execution time limit", count 100, BRS +-- 2026-10-27). Now a scan is asked for at most once a second and reads +-- SCAN_STEP spellbook entries a frame; a text update only forgets that one +-- spell, which is read again at its next cast. +local SCAN_STEP = 15 +local scan = { want = false, wantAt = 0, line = nil, idx = nil, last = nil } + +local function RequestScan(delay) + scan.want = true + scan.wantAt = GetTime() + (delay or 1) +end + +-- Reads up to SCAN_STEP entries; returns true while the scan is not finished. +local function ScanStep() + if not (C_SpellBook and C_SpellBook.GetNumSpellBookSkillLines) then return false end + local bank = Enum and Enum.SpellBookSpellBank and Enum.SpellBookSpellBank.Player or 0 + local lines = C_SpellBook.GetNumSpellBookSkillLines() or 0 + local budget = SCAN_STEP + while scan.line <= lines do + if not scan.idx then + local li = C_SpellBook.GetSpellBookSkillLineInfo(scan.line) + if li then + local first = li.itemIndexOffset or 0 + scan.idx, scan.last = first + 1, first + (li.numSpellBookItems or 0) + else + scan.idx, scan.last = 1, 0 + end + end + while scan.idx <= scan.last do + if budget <= 0 then return true end + budget = budget - 1 + local info = C_SpellBook.GetSpellBookItemInfo(scan.idx, bank) + scan.idx = scan.idx + 1 + if info and info.spellID and not info.isPassive then Duration(info.spellID) end + end + scan.line, scan.idx = scan.line + 1, nil + end + return false +end + +-- Called from the frame tick: starts a requested scan once its delay is over +-- and runs a scan in progress one step further. +local function ScanTick() + if scan.line then + if not ScanStep() then scan.line, scan.idx = nil, nil end + return + end + if scan.want and GetTime() >= scan.wantAt then + scan.want = false + scan.line, scan.idx = 1, nil + end +end + +-- ---------------------------------------------------------------- enemies + +-- A key for the current target that can be compared: its GUID when the client +-- shows it, otherwise a number that changes every time the target changes. +local function TargetKey() + local ok, g = pcall(UnitGUID, "target") + if ok and not Secret(g) and g then return g end + return "slot" .. slot +end + +local function Hostile(unit) + local ok, v = pcall(function() + local h = UnitCanAttack("player", unit) + if Secret(h) then return true end + return h and true or false + end) + return not ok or v +end + +local function FindGroup(key) + for i, g in ipairs(groups) do + if g.key == key then return g, i end + end +end + +local function OnCast(spellID) + if Secret(spellID) then return end + if not UnitExists("target") or not Hostile("target") then return end + local d = Duration(spellID) + if not d then return end + local name = C_Spell.GetSpellName(spellID) + local key = TargetKey() + local g = FindGroup(key) + if not g then + g = { key = key, dots = {} } + table.insert(groups, 1, g) + while #groups > MAX_GROUPS do table.remove(groups) end + end + local okName, unitName = pcall(UnitName, "target") + g.name = okName and unitName or nil + local okMark, mark = pcall(GetRaidTargetIndex, "target") + g.mark = (okMark and not Secret(mark)) and mark or nil + g.dots[name] = { + name = name, + icon = C_Spell.GetSpellTexture(spellID), + start = GetTime(), + dur = d, + } + dirty = true +end + +local function Prune() + local now = GetTime() + for i = #groups, 1, -1 do + local g = groups[i] + local any = false + for n, dot in pairs(g.dots) do + if now >= dot.start + dot.dur then g.dots[n] = nil dirty = true else any = true end + end + if not any then table.remove(groups, i) dirty = true end + end +end + +-- The current target died: its bars go. +local function TargetDied() + local ok, dead = pcall(function() + local d = UnitIsDead("target") + if Secret(d) then return false end + return d and true or false + end) + if ok and dead then + local _, i = FindGroup(TargetKey()) + if i then table.remove(groups, i) dirty = true end + end +end + +-- ---------------------------------------------------------------- frames + +local function NewRow() + local r = CreateFrame("Frame", nil, root) + r:SetHeight(ROW_H) + r.icon = r:CreateTexture(nil, "ARTWORK") + r.icon:SetSize(ROW_H, ROW_H) + r.icon:SetPoint("LEFT", 0, 0) + r.icon:SetTexCoord(0.07, 0.93, 0.07, 0.93) + r.bar = CreateFrame("StatusBar", nil, r) + r.bar:SetPoint("LEFT", r.icon, "RIGHT", 2, 0) + r.bar:SetPoint("RIGHT", r, "RIGHT", 0, 0) + r.bar:SetHeight(ROW_H) + r.bar:SetStatusBarTexture("Interface\\TargetingFrame\\UI-StatusBar") + r.bg = r.bar:CreateTexture(nil, "BACKGROUND") + r.bg:SetAllPoints() + r.bg:SetColorTexture(0, 0, 0, 0.5) + r.name = r.bar:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall") + r.name:SetPoint("LEFT", 4, 0) + r.name:SetPoint("RIGHT", -34, 0) + r.name:SetJustifyH("LEFT") + r.time = r.bar:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall") + r.time:SetPoint("RIGHT", -4, 0) + r:Hide() + return r +end + +local function NewHead() + local h = CreateFrame("Frame", nil, root) + h:SetHeight(HEAD_H) + h.mark = h:CreateTexture(nil, "ARTWORK") + h.mark:SetSize(HEAD_H, HEAD_H) + h.mark:SetPoint("LEFT", 0, 0) + h.mark:SetTexture("Interface\\TargetingFrame\\UI-RaidTargetingIcons") + h.name = h:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall") + h.name:SetPoint("LEFT", h.mark, "RIGHT", 2, 0) + h.name:SetPoint("RIGHT", 0, 0) + h.name:SetJustifyH("LEFT") + h:Hide() + return h +end + +local nRow, nHead, y = 0, 0, 0 + +local function TakeHead() + nHead = nHead + 1 + local h = heads[nHead] + if not h then h = NewHead() heads[nHead] = h end + h:ClearAllPoints() + h:SetPoint("TOPLEFT", root, "TOPLEFT", 0, -y) + h:SetPoint("RIGHT", root, "RIGHT", 0, 0) + h:Show() + y = y + HEAD_H + 1 + return h +end + +local function TakeRow() + nRow = nRow + 1 + local r = rows[nRow] + if not r then r = NewRow() rows[nRow] = r end + r:ClearAllPoints() + r:SetPoint("TOPLEFT", root, "TOPLEFT", 0, -y) + r:SetPoint("RIGHT", root, "RIGHT", 0, 0) + r:Show() + y = y + ROW_H + GAP + return r +end + +local function SampleGroups() + local now = GetTime() + local function dot(n, icon, d, left) + return { name = n, icon = icon, dur = d, start = now - (d - left) } + end + return { + { key = "a", name = "Sample target", isTarget = true, dots = { + dot("Corruption", "Interface\\Icons\\Spell_Shadow_AbominationExplosion", 18, 14), + dot("Immolate", "Interface\\Icons\\Spell_Fire_Immolation", 15, 9), + dot("Curse of Agony", "Interface\\Icons\\Spell_Shadow_CurseOfSargeras", 24, 2.5) } }, + { key = "b", name = "Sample mob", dots = { + dot("Corruption", "Interface\\Icons\\Spell_Shadow_AbominationExplosion", 18, 6), + dot("Siphon Life", "Interface\\Icons\\Spell_Shadow_Requiem", 30, 22) } }, + } +end + +local shownGroups + +local function Layout() + nRow, nHead, y = 0, 0, 0 + shownGroups = testMode and SampleGroups() or groups + local targetKey = UnitExists("target") and TargetKey() or nil + for _, g in ipairs(shownGroups) do + local h = TakeHead() + if not pcall(function() h.name:SetText(g.name) end) then h.name:SetText("?") end + local isTarget = g.isTarget or (targetKey ~= nil and g.key == targetKey) + if isTarget then h.name:SetTextColor(1, 0.82, 0) else h.name:SetTextColor(0.75, 0.75, 0.75) end + h.mark:Hide() + if g.mark then + pcall(function() SetRaidTargetIconTexture(h.mark, g.mark) h.mark:Show() end) + end + local list = {} + for _, dot in pairs(g.dots) do list[#list + 1] = dot end + table.sort(list, function(a, b) return a.start + a.dur < b.start + b.dur end) + for _, dot in ipairs(list) do + local r = TakeRow() + r.dot = dot + r.icon:SetTexture(dot.icon) + r.name:SetText(dot.name) + r.bar:SetMinMaxValues(0, dot.dur) + end + end + for i = nRow + 1, #rows do rows[i]:Hide() rows[i].dot = nil end + for i = nHead + 1, #heads do heads[i]:Hide() end + root:SetHeight(math.max(y, 16)) +end + +local function Tick() + local now = GetTime() + for i = 1, nRow do + local r = rows[i] + local dot = r.dot + if dot then + local left = math.max(dot.start + dot.dur - now, 0) + r.bar:SetValue(left) + if left <= db.red then + r.bar:SetStatusBarColor(RED[1], RED[2], RED[3]) + else + r.bar:SetStatusBarColor(BAR_COLOR[1], BAR_COLOR[2], BAR_COLOR[3]) + end + if left >= 10 then + r.time:SetText(string.format("%d", left)) + else + r.time:SetText(string.format("%.1f", left)) + end + end + end +end + +local function PlaceRoot() + root:ClearAllPoints() + if db.point then + root:SetPoint(db.point, UIParent, db.relPoint or db.point, db.x or 0, db.y or 0) + else + -- just right of the middle of the screen, beside your character + root:SetPoint("LEFT", UIParent, "CENTER", 90, -60) + end +end + +local function ApplyLock() + if db.locked then + root.handle:Hide() root.label:Hide() root:EnableMouse(false) + else + root.handle:Show() root.label:Show() root:EnableMouse(true) + end +end + +local function Build() + root = CreateFrame("Frame", "ForeverDotsFrame", UIParent) + root:SetSize(db.width, 16) + root:SetMovable(true) + root:SetClampedToScreen(true) + root:RegisterForDrag("LeftButton") + root:SetScale(db.scale) + + root.handle = root:CreateTexture(nil, "BACKGROUND") + root.handle:SetAllPoints() + root.handle:SetColorTexture(0.6, 0.4, 1, 0.25) + root.label = root:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall") + root.label:SetPoint("BOTTOMLEFT", root, "TOPLEFT", 0, 2) + root.label:SetText("ForeverDots (drag, then /dots lock)") + + root:SetScript("OnDragStart", function(self) + if not db.locked then self:StartMoving() end + end) + root:SetScript("OnDragStop", function(self) + self:StopMovingOrSizing() + local p, _, rp, x, yy = self:GetPoint() + db.point, db.relPoint, db.x, db.y = p, rp, x, yy + end) + + PlaceRoot() + ApplyLock() + + local acc = 0 + root:SetScript("OnUpdate", function(_, dt) + acc = acc + dt + if acc < 0.05 then return end + acc = 0 + Guard(ScanTick) + if not testMode then Guard(Prune) end + if dirty then dirty = false Guard(Layout) end + Guard(Tick) + end) +end + +-- ---------------------------------------------------------------- events + +local ev = CreateFrame("Frame") +ev:RegisterEvent("ADDON_LOADED") +ev:RegisterEvent("PLAYER_LOGIN") +ev:RegisterEvent("PLAYER_TARGET_CHANGED") +ev:RegisterEvent("PLAYER_DEAD") +ev:RegisterEvent("SPELLS_CHANGED") +ev:RegisterEvent("SPELL_TEXT_UPDATE") +ev:RegisterUnitEvent("UNIT_SPELLCAST_SUCCEEDED", "player") +ev:RegisterUnitEvent("UNIT_HEALTH", "target") +ev:SetScript("OnEvent", function(_, event, arg1, arg2, arg3) + if event == "ADDON_LOADED" then + if arg1 ~= ADDON then return end + ForeverDotsDB = ForeverDotsDB or {} + db = ForeverDotsDB + for k, v in pairs(defaults) do + if db[k] == nil then db[k] = v end + end + elseif event == "PLAYER_LOGIN" then + Guard(Build) + RequestScan(2) + elseif not root then + return + elseif event == "UNIT_SPELLCAST_SUCCEEDED" then + Guard(OnCast, arg3) + elseif event == "PLAYER_TARGET_CHANGED" then + slot = slot + 1 + dirty = true + elseif event == "UNIT_HEALTH" then + Guard(TargetDied) + elseif event == "PLAYER_DEAD" then + wipe(groups) + dirty = true + elseif event == "SPELL_TEXT_UPDATE" then + -- this spell's text arrived or changed: read it again at its next cast + if arg1 and not Secret(arg1) then known[arg1] = nil end + else + -- SPELLS_CHANGED (new rank, talents): forget the durations, read the book again soon + wipe(known) + RequestScan(1) + end +end) + +-- ---------------------------------------------------------------- commands + +SLASH_FOREVERDOTS1 = "/dots" +SLASH_FOREVERDOTS2 = "/foreverdots" +SlashCmdList["FOREVERDOTS"] = function(msg) + if not root then return end + msg = msg or "" + local cmd, arg = msg:match("^(%S*)%s*(.-)$") + cmd = cmd:lower() + if cmd == "lock" then + db.locked = true ApplyLock() pr("locked") + elseif cmd == "unlock" then + db.locked = false ApplyLock() pr("unlocked: drag the purple box, then /dots lock") + elseif cmd == "reset" then + db.point, db.relPoint, db.x, db.y = nil, nil, nil, nil + PlaceRoot() pr("position reset") + elseif cmd == "test" then + testMode = not testMode + pr(testMode and "showing sample bars (/dots test again to stop)" or "sample bars off") + dirty = true + elseif cmd == "clear" then + wipe(groups) dirty = true pr("bars cleared") + elseif cmd == "red" then + local s = tonumber(arg) + if s and s >= 0 and s <= 30 then db.red = s pr("bars turn red at " .. s .. " s left") + else pr("usage: /dots red 0 to 30 (seconds)") end + elseif cmd == "scale" then + local s = tonumber(arg) + if s and s >= 0.5 and s <= 2 then db.scale = s root:SetScale(s) pr("scale " .. s) + else pr("usage: /dots scale 0.5 to 2") end + elseif cmd == "width" then + local w = tonumber(arg) + if w and w >= 100 and w <= 400 then db.width = w root:SetWidth(w) pr("width " .. w) + else pr("usage: /dots width 100 to 400") end + elseif cmd == "time" then + -- /dots time Corruption 18 (0 removes the override) + local name, sec = arg:match("^(.-)%s+(%d+%.?%d*)$") + if name and name ~= "" then + sec = tonumber(sec) + db.dur[name:lower()] = sec > 0 and sec or nil + wipe(known) + pr(name .. ": " .. (sec > 0 and (sec .. " s") or "back to the tooltip time")) + else + pr("usage: /dots time , e.g. /dots time Corruption 18") + end + elseif cmd == "spells" then + local n = 0 + for id, d in pairs(known) do + if d then n = n + 1 pr((C_Spell.GetSpellName(id) or id) .. ": " .. d .. " s") end + end + if n == 0 then pr("no damage-over-time spell cast yet this session") end + else + pr("/dots lock | unlock | reset | test | clear | red | scale <0.5-2> | width <100-400> | time | spells") + end +end diff --git a/src/modules/PlayerbotV2/Addon/ForeverDots/ForeverDots.toc b/src/modules/PlayerbotV2/Addon/ForeverDots/ForeverDots.toc new file mode 100644 index 0000000000..5d4d8d6aee --- /dev/null +++ b/src/modules/PlayerbotV2/Addon/ForeverDots/ForeverDots.toc @@ -0,0 +1,8 @@ +## Interface: 16001 +## Title: ForeverDots +## Notes: Countdown bars for your damage-over-time spells beside your character, grouped per enemy. /dots for options. +## Author: Karrz +## Version: 1.2.1 +## SavedVariables: ForeverDotsDB + +ForeverDots.lua diff --git a/src/modules/PlayerbotV2/Addon/ForeverDots/README.txt b/src/modules/PlayerbotV2/Addon/ForeverDots/README.txt new file mode 100644 index 0000000000..65633a20a9 --- /dev/null +++ b/src/modules/PlayerbotV2/Addon/ForeverDots/README.txt @@ -0,0 +1,38 @@ +ForeverDots 1.2.1 +================= + +Countdown bars for your own damage-over-time spells (Corruption, Immolate, +Siphon Life, Curse of Agony and so on, any class), beside your character, +grouped per enemy: the enemy's name (your current target in gold), then one +bar per spell with its icon and the seconds left. Bars turn red in the last +3 seconds. + +How it works: this client does not let add-ons read enemy debuffs in combat, +so each bar starts when your spell finishes casting on your target, using +the duration in the spell's tooltip. Casting it again on the same enemy +restarts the bar. Things it cannot know: a resist, a dispel, or an enemy +dying when it is not your target (its bars just run out). + +Install +------- +The WoW Forever Bots repack installs it together with ForeverBots (install, +update and every Play from the launcher replace the folder with a clean copy). +By hand: +1. Close the game (or be ready to /reload). +2. Unzip so this folder ends up as: + \_forever_\Interface\AddOns\ForeverDots\ForeverDots.toc + (replace the old ForeverDots folder) +3. Start the game, make sure ForeverDots is ticked in the AddOns list. + +Commands +-------- +/dots test sample bars, to place it +/dots unlock show the purple box, drag it where you want it +/dots lock lock it again +/dots reset back to the default spot (right of your character) +/dots red 3 seconds left when bars turn red +/dots scale 1.2 size (0.5 to 2) +/dots width 240 bar width (100 to 400) +/dots clear remove all bars +/dots spells the spells it has found and their durations +/dots time Corruption 18 set a spell's duration by hand (0 = use tooltip) diff --git a/src/modules/PlayerbotV2/Api/BotItemScorer.cpp b/src/modules/PlayerbotV2/Api/BotItemScorer.cpp index 7f2ac89a21..60e6f952d4 100644 --- a/src/modules/PlayerbotV2/Api/BotItemScorer.cpp +++ b/src/modules/PlayerbotV2/Api/BotItemScorer.cpp @@ -572,6 +572,33 @@ bool IsArmorPieceSlotType(uint8 inv) } // anonymous +int32 ResistPoints(ItemTemplate const* tpl, uint8 school, uint8 level) +{ + if (!tpl) + return 0; + int32 mod; + switch (school) + { + case SPELL_SCHOOL_HOLY: mod = ITEM_MOD_HOLY_RESISTANCE; break; + case SPELL_SCHOOL_FIRE: mod = ITEM_MOD_FIRE_RESISTANCE; break; + case SPELL_SCHOOL_NATURE: mod = ITEM_MOD_NATURE_RESISTANCE; break; + case SPELL_SCHOOL_FROST: mod = ITEM_MOD_FROST_RESISTANCE; break; + case SPELL_SCHOOL_SHADOW: mod = ITEM_MOD_SHADOW_RESISTANCE; break; + case SPELL_SCHOOL_ARCANE: mod = ITEM_MOD_ARCANE_RESISTANCE; break; + default: return 0; + } + uint32 const ilvl = uint32(std::max(1, EffectiveItemLevelForLevel(tpl, level))); + float points = 0.0f; + for (uint32 i = 0; i < MAX_ITEM_PROTO_STATS; ++i) + { + int32 const t = tpl->GetStatModifierBonusStat(i); + // Resistance to all schools is the five magic schools (Player::_ApplyItemBonuses), not holy. + if (t == mod || (t == ITEM_MOD_CLASSIC_RESISTANCE_ALL_SCHOOLS && school != SPELL_SCHOOL_HOLY)) + points += RaidStatValue(tpl, i, ilvl); + } + return int32(points + 0.5f); +} + int32 ScoreItemRaid(ItemTemplate const* tpl, uint8 cls, uint16 spec, uint8 level, uint8 slot) { if (!tpl) diff --git a/src/modules/PlayerbotV2/Api/BotItemScorer.h b/src/modules/PlayerbotV2/Api/BotItemScorer.h index 484135ca4d..39f068cdcd 100644 --- a/src/modules/PlayerbotV2/Api/BotItemScorer.h +++ b/src/modules/PlayerbotV2/Api/BotItemScorer.h @@ -98,6 +98,10 @@ char const* RaidRoleName(RaidRole role); // item spells' auras (+healing, +damage, +attack power, hit, crit, mp5...) that are not item stats. int32 ScoreItemRaid(ItemTemplate const* tpl, uint8 cls, uint16 spec, uint8 level, uint8 slot); +// The item's resistance points in `school` (SpellSchools: holy 1, fire 2, nature 3, frost 4, shadow 5, arcane 6) for a wearer at `level`: +// the school's own resistance stat plus resistance to all schools, as the wearer gets them. 0 when it carries none. +int32 ResistPoints(ItemTemplate const* tpl, uint8 school, uint8 level); + // True when the (class, spec) fights with weapons in both hands or a two-hander, so a shield or a held-in-off-hand caster item // (Royal Scepter of Vek'lor) in the off hand is dead weight: rogues, warriors that are not protection, hunters and enhancement // shamans. Its off hand is a weapon or empty (behind a two-hander). diff --git a/src/modules/PlayerbotV2/Api/BotTrade.h b/src/modules/PlayerbotV2/Api/BotTrade.h index 16e1770a97..4a69b0dfbf 100644 --- a/src/modules/PlayerbotV2/Api/BotTrade.h +++ b/src/modules/PlayerbotV2/Api/BotTrade.h @@ -89,6 +89,8 @@ struct View std::uint64_t order_price = 0; bool order_item_present = false; // the ordered item is still in the bot's bags (or already in the window) bool bot_has_room = true; // the bot can store everything the player put up + bool has_delivery = false; // a craft order made for this player is waiting in the bot's bags, to be handed over for free + bool delivery_present = false; // that item is still in the bags (or already in the window) }; enum class Act : unsigned char @@ -98,6 +100,7 @@ enum class Act : unsigned char Cancel, // close the window SetMoney, // put `money` in the bot's side (0 clears it) AddOrdered, // put the ordered item in the bot's side + AddDelivery, // put the finished craft order in the bot's side ClearMine // take the bot's items back }; @@ -147,6 +150,15 @@ inline Action Decide(View const& v) { bool const he_gives = !v.his.empty(); + // A finished craft order that could not go by mail: handed over for nothing when he opens a trade with nothing in it. + if (!he_gives && v.has_delivery && v.his_money == 0 && v.my_money == 0) + { + if (v.mine.empty()) + return v.delivery_present ? Action{ Act::AddDelivery } : Action{ Act::Cancel, 0, Say::OrderGone }; + if (v.his_accepted && !v.my_accepted) return { Act::Accept }; + return {}; + } + // Sell to the player: no items from him, an order on the bot's list. if (!he_gives && v.has_order) { diff --git a/src/modules/PlayerbotV2/Api/BotTradeShop.cpp b/src/modules/PlayerbotV2/Api/BotTradeShop.cpp index 50d0e368f8..8658aade22 100644 --- a/src/modules/PlayerbotV2/Api/BotTradeShop.cpp +++ b/src/modules/PlayerbotV2/Api/BotTradeShop.cpp @@ -34,7 +34,15 @@ struct Shelf Offer order; }; +struct Delivery +{ + ObjectGuid requester; + uint32 entry = 0; + uint32 stamp_ms = 0; +}; + std::mutex g_mtx; +std::unordered_map g_deliveries; // bot -> the craft order waiting to be handed over std::unordered_map g_shelves; // (bot << 32) | buyer std::unordered_map> g_last_say; // bot -> (what was said, when) @@ -191,6 +199,13 @@ bool PlaceOrder(Player const* bot, Player const* buyer, size_t index, Offer& out return true; } +void StoreDelivery(Player const* bot, ObjectGuid requester, uint32 entry) +{ + std::lock_guard lk(g_mtx); + if (g_deliveries.size() > 4096) g_deliveries.clear(); + g_deliveries[bot->GetGUID().GetCounter()] = Delivery{ requester, entry, GameTime::GetGameTimeMS() }; +} + std::vector Describe(std::vector const& list) { std::vector out; @@ -312,6 +327,29 @@ Result Step(Player* bot, TradeData* mine, TradeData* his, bool gift_ok) v.order_price = order.price; v.order_item_present = oi && oi->GetEntry() == order.entry && oi->GetCount() == order.count && IsTradeable(oi); } + // A craft order made for this player that could not go by mail: still in the bags, it is handed over in this window. + Item* delivery = nullptr; + { + std::lock_guard lk(g_mtx); + auto it = g_deliveries.find(bot->GetGUID().GetCounter()); + if (it != g_deliveries.end()) + { + if (GameTime::GetGameTimeMS() - it->second.stamp_ms > kShelfLifeMs) + g_deliveries.erase(it); + else if (it->second.requester == partner->GetGUID()) + { + std::vector held = bot->GetItemListByEntry(it->second.entry, false); + if (held.empty()) + g_deliveries.erase(it); + else + { + delivery = held.front(); + v.has_delivery = true; + v.delivery_present = true; + } + } + } + } // Only look at room when the bot is about to take something in: it is the costly check. if (!v.his.empty() && v.his_accepted && !v.my_accepted) v.bot_has_room = HasRoomFor(bot, his_items); @@ -361,6 +399,19 @@ Result Step(Player* bot, TradeData* mine, TradeData* his, bool gift_ok) } return Result::Locked; } + case BotTrade::Act::AddDelivery: + { + if (!delivery) return Result::Locked; + for (uint8 i = 0; i < TRADE_SLOT_TRADED_COUNT; ++i) + if (!mine->GetItem(TradeSlots(i))) + { + if (delivery->IsBindedNotWith(partner)) return Result::ServerRefused; + mine->UpdateClientStateIndex(); + mine->SetItem(TradeSlots(i), delivery); + break; + } + return Result::Locked; + } case BotTrade::Act::Accept: { WorldPacket data(CMSG_ACCEPT_TRADE); diff --git a/src/modules/PlayerbotV2/Api/BotTradeShop.h b/src/modules/PlayerbotV2/Api/BotTradeShop.h index bb99d44a86..96aba05d7b 100644 --- a/src/modules/PlayerbotV2/Api/BotTradeShop.h +++ b/src/modules/PlayerbotV2/Api/BotTradeShop.h @@ -46,6 +46,10 @@ void StoreList(Player const* bot, Player const* buyer, std::vector list); bool GetList(Player const* bot, Player const* buyer, std::vector& out); bool PlaceOrder(Player const* bot, Player const* buyer, size_t index, Offer& out); +// A finished craft order that cannot go by mail (a conjured item, or the mail failed): when `requester` opens a trade with the bot +// within ten minutes, the bot puts the item (`entry`, from its bags) in the window and accepts once he has. One per bot. +void StoreDelivery(Player const* bot, ObjectGuid requester, uint32 entry); + // "1) Linen Cloth x20 - 40s" lines packed into whisper-sized chunks. std::vector Describe(std::vector const& list); diff --git a/src/modules/PlayerbotV2/Api/ClassicSpec.cpp b/src/modules/PlayerbotV2/Api/ClassicSpec.cpp index 553859f651..0955637d56 100644 --- a/src/modules/PlayerbotV2/Api/ClassicSpec.cpp +++ b/src/modules/PlayerbotV2/Api/ClassicSpec.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -61,7 +62,7 @@ struct ClassRules }; constexpr std::array kRules = {{ - { CLASS_WARRIOR, 71, {{ + { CLASS_WARRIOR, 72, {{ { 23922, 73 }, // Shield Slam { 12809, 73 }, // Concussion Blow { 23881, 72 }, // Bloodthirst @@ -100,14 +101,14 @@ constexpr std::array kRules = {{ { 17364, 263 }, // Stormstrike { 16166, 262 }, // Elemental Mastery }}}, - { CLASS_MAGE, 64, {{ + { CLASS_MAGE, 63, {{ // fallback: fire, the highest-damage raid spec (parity 184: fire 743, frost 523 buffed) { 12042, 62 }, // Arcane Power { 11129, 63 }, // Combustion { 11426, 64 }, // Ice Barrier { 11366, 63 }, // Pyroblast { 12043, 62 }, // Presence of Mind }}}, - { CLASS_WARLOCK, 265, {{ + { CLASS_WARLOCK, 267, {{ { 18220, 265 }, // Dark Pact { 18265, 265 }, // Siphon Life { 19028, 266 }, // Soul Link @@ -115,7 +116,7 @@ constexpr std::array kRules = {{ { 17962, 267 }, // Conflagrate { 17877, 267 }, // Shadowburn }}}, - { CLASS_DRUID, 102, {{ + { CLASS_DRUID, 103, {{ { 24858, 102 }, // Moonkin Form { 18562, 105 }, // Swiftmend { 17116, 105 }, // Nature's Swiftness @@ -148,6 +149,22 @@ std::string TalentKey(std::string_view name) return key; } +// A build pick may name alternatives, "A|B": the node of the first one the client data has. The client builds differ in a few nodes +// (70450 has Call of Thunder and Improved Fire Nova where 70532 has Elemental Mastery and Trial by Fire), and one build serves both. +template +auto FirstTalentAlternative(std::string_view name, Fn&& lookup) -> decltype(lookup(std::string())) +{ + for (std::size_t from = 0;;) + { + std::size_t const bar = name.find('|', from); + if (auto found = lookup(TalentKey(name.substr(from, bar == std::string_view::npos ? std::string_view::npos : bar - from)))) + return found; + if (bar == std::string_view::npos) + return {}; + from = bar + 1; + } +} + std::mutex g_indexLock; std::unordered_map g_indexes; @@ -224,8 +241,9 @@ uint32 InferFromTalents(Player const* player) continue; int32 score = 0; for (TalentPick const& pick : build.picks) - if (auto itr = owned.find(TalentKey(pick.name)); itr != owned.end()) - score += std::min(itr->second, pick.ranks); + if (int32 const held = FirstTalentAlternative(pick.name, [&](std::string const& key) + { auto itr = owned.find(key); return itr != owned.end() ? itr->second : 0; })) + score += std::min(held, pick.ranks); if (score > bestScore) { bestScore = score; @@ -242,8 +260,24 @@ TalentNode const* FindTalent(Player const* player, std::string const& name) ClassTalentIndex const* index = player ? GetClassTalentIndex(player) : nullptr; if (!index) return nullptr; - auto itr = index->byName.find(TalentKey(name)); - return itr != index->byName.end() ? &itr->second : nullptr; + return FirstTalentAlternative(name, [&](std::string const& key) -> TalentNode const* + { + auto itr = index->byName.find(key); + return itr != index->byName.end() ? &itr->second : nullptr; + }); +} + +std::vector ListTalentNames(Player const* player) +{ + std::vector names; + ClassTalentIndex const* index = player ? GetClassTalentIndex(player) : nullptr; + if (!index) + return names; + names.reserve(index->byName.size()); + for (auto const& [name, node] : index->byName) + names.push_back(name); + std::ranges::sort(names); + return names; } bool IsRetailClassSpec(uint8 cls, uint32 spec) diff --git a/src/modules/PlayerbotV2/Api/ClassicSpec.h b/src/modules/PlayerbotV2/Api/ClassicSpec.h index 99720cd7b8..94ec048d6e 100644 --- a/src/modules/PlayerbotV2/Api/ClassicSpec.h +++ b/src/modules/PlayerbotV2/Api/ClassicSpec.h @@ -20,6 +20,7 @@ #include "Define.h" #include "ObjectGuid.h" #include +#include class Player; @@ -51,5 +52,8 @@ struct TalentNode int32 MaxRanks = 0; }; TC_GAME_API TalentNode const* FindTalent(Player const* player, std::string const& name); +// Every talent name (lower-cased key) the player's class trees answer to: for a build pick FindTalent does not find, this shows +// what the client data calls it. +TC_GAME_API std::vector ListTalentNames(Player const* player); } // namespace Playerbot::Classic diff --git a/src/modules/PlayerbotV2/Api/ClassicSupplies.cpp b/src/modules/PlayerbotV2/Api/ClassicSupplies.cpp index 8909027c22..fb6a89db6c 100644 --- a/src/modules/PlayerbotV2/Api/ClassicSupplies.cpp +++ b/src/modules/PlayerbotV2/Api/ClassicSupplies.cpp @@ -1,11 +1,14 @@ #include "ClassicSupplies.h" #include "DB2Stores.h" #include "ItemTemplate.h" +#include "Log.h" #include "ObjectMgr.h" +#include "Player.h" #include "SharedDefines.h" #include "SpellInfo.h" #include "SpellMgr.h" #include +#include #include namespace Playerbot::Classic { @@ -45,6 +48,11 @@ constexpr SupplyRank kRebirthReagent[] = { // ---- Warlock ---- constexpr SupplyRank kSoulShard[] = { { 6265, 10 } }; +constexpr SupplyRank kInfernalStone[] = { { 5565, 50 } }; // Inferno +constexpr SupplyRank kDemonicFigurine[] = { { 16583, 60 } }; // Ritual of Doom +constexpr SupplyRank kRuneTeleport[] = { { 17031, 20 } }; // Teleport spells +constexpr SupplyRank kRunePortals[] = { { 17032, 40 } }; // Portal spells +constexpr SupplyRank kBlindingPowder[] = { { 5530, 34 } }; // Blind // ---- Every class: vendor food and water, potions, bandages (1.12 ids) ---- // Rank = the item's required level (bandages: the bot's First Aid at that @@ -84,6 +92,11 @@ constexpr SupplyFamily kFamilies[] = { { "Gift Reagent", CLASS_DRUID, 20, kGiftReagent }, { "Rebirth Reagent", CLASS_DRUID, 5, kRebirthReagent }, { "Soul Shard", CLASS_WARLOCK, 5, kSoulShard }, + { "Infernal Stone", CLASS_WARLOCK, 5, kInfernalStone }, + { "Demonic Figurine", CLASS_WARLOCK, 5, kDemonicFigurine }, + { "Rune of Teleportation", CLASS_MAGE, 10, kRuneTeleport }, + { "Rune of Portals", CLASS_MAGE, 10, kRunePortals }, + { "Blinding Powder", CLASS_ROGUE, 10, kBlindingPowder }, // Open-world bots keep a small stock; raid-level (55+) bots carry what a // raid night needs (the owner: full potion stacks, 20 food, 40 drinks). { "Food", 0, 5, kFood, kConsumable, 20 }, @@ -98,26 +111,48 @@ constexpr SupplyFamily kFamilies[] = { // Flask of the Titans 13510, Flask of Supreme Power 13512, Flask of Distilled Wisdom 13511, Elixir of Fortitude 3825, // Elixir of Superior Defense 13445, Elixir of the Mongoose 13452, Elixir of the Giants 9206, Greater Arcane Elixir 13454, // Mageblood Potion 20007, Smoked Desert Dumplings 20452, Grilled Squid 13928, Runn Tum Tuber Surprise 18254, -// Nightfin Soup 13931, Tender Wolf Steak 18045. +// Nightfin Soup 13931, Tender Wolf Steak 18045, Greater Fire / Frost / Nature / Shadow Protection Potion 13457 / 13456 / 13458 / 13459. +// Stock: how many a bot is topped up to before every pull (flasks, elixirs and potions 5, food 20), so a raid night does not run them out. constexpr RaidConsumable kTankKit[] = { - { 13510, false, 2, true }, { 13445, false, 2 }, { 3825, false, 2 }, { 18045, true, 5 }, - { 13457, false, 2, false, true }, // Greater Fire Protection Potion: drunk in the fight where the boss data orders it (Ragnaros) + { 13510, false, 5, true }, { 13445, false, 5 }, { 3825, false, 5 }, { 18045, true, 20 }, + { 13457, false, 5, false, true }, // Greater Fire Protection Potion: drunk in the fight where the boss data orders it (Ragnaros, Geddon, Onyxia, Firemaw, Vaelastrasz) + { 13459, false, 5, false, true }, // Greater Shadow Protection Potion: BWL Shadow Flame (Ebonroc, Flamegor, Nefarian) + { 13458, false, 5, false, true }, // Greater Nature Protection Potion: AQ40 Huhuran's Poison Bolt Volley + { 13456, false, 5, false, true }, // Greater Frost Protection Potion: Naxxramas Sapphiron }; constexpr RaidConsumable kMeleeKit[] = { - { 13452, false, 2 }, { 9206, false, 2 }, { 20452, true, 5 }, - { 13457, false, 1, false, true }, // Greater Fire Protection Potion: drunk in the fight where the boss data orders it (Ragnaros' Might hits 20 y round a random mana user) + { 13452, false, 5 }, { 9206, false, 5 }, { 20452, true, 20 }, + { 13457, false, 5, false, true }, // Greater Fire Protection Potion: drunk in the fight where the boss data orders it (Ragnaros, Geddon, Onyxia, Firemaw, Vaelastrasz) + { 13459, false, 5, false, true }, // Greater Shadow Protection Potion: BWL Shadow Flame (Ebonroc, Flamegor, Nefarian) + { 13458, false, 5, false, true }, // Greater Nature Protection Potion: AQ40 Huhuran's Poison Bolt Volley + { 13456, false, 5, false, true }, // Greater Frost Protection Potion: Naxxramas Sapphiron }; constexpr RaidConsumable kCasterKit[] = { - { 13512, false, 2, true }, { 13454, false, 2 }, { 18254, true, 5 }, - { 13457, false, 1, false, true }, // Greater Fire Protection Potion: drunk in the fight where the boss data orders it (Ragnaros' Might hits 20 y round a random mana user) + { 13512, false, 5, true }, { 13454, false, 5 }, { 18254, true, 20 }, + // Stocked, never drunk by the pre-pull picker (combat flag): Brilliant Wizard Oil goes on the main hand by idle:classic_weapon, the Major Mana + // Potion and the Dark / Demonic Rune by the fight's mana item rule (PickCombatManaItem). + { 20749, false, 5, false, true }, // Brilliant Wizard Oil: +36 spell damage, +1% spell crit on the weapon + { 13444, false, 5, false, true }, // Major Mana Potion + { 12662, false, 5, false, true }, // Demonic Rune + { 20520, false, 5, false, true }, // Dark Rune + { 13457, false, 5, false, true }, // Greater Fire Protection Potion: drunk in the fight where the boss data orders it (Ragnaros, Geddon, Onyxia, Firemaw, Vaelastrasz) + { 13459, false, 5, false, true }, // Greater Shadow Protection Potion: BWL Shadow Flame (Ebonroc, Flamegor, Nefarian) + { 13458, false, 5, false, true }, // Greater Nature Protection Potion: AQ40 Huhuran's Poison Bolt Volley + { 13456, false, 5, false, true }, // Greater Frost Protection Potion: Naxxramas Sapphiron }; constexpr RaidConsumable kHealerKit[] = { - { 13511, false, 2, true }, { 20007, false, 2 }, { 13931, true, 5 }, - { 13457, false, 1, false, true }, // Greater Fire Protection Potion: drunk in the fight where the boss data orders it (Ragnaros' Might hits 20 y round a random mana user) + { 13511, false, 5, true }, { 20007, false, 5 }, { 13931, true, 20 }, + { 13457, false, 5, false, true }, // Greater Fire Protection Potion: drunk in the fight where the boss data orders it (Ragnaros, Geddon, Onyxia, Firemaw, Vaelastrasz) + { 13459, false, 5, false, true }, // Greater Shadow Protection Potion: BWL Shadow Flame (Ebonroc, Flamegor, Nefarian) + { 13458, false, 5, false, true }, // Greater Nature Protection Potion: AQ40 Huhuran's Poison Bolt Volley + { 13456, false, 5, false, true }, // Greater Frost Protection Potion: Naxxramas Sapphiron }; constexpr RaidConsumable kHunterKit[] = { - { 13452, false, 2 }, { 9206, false, 2 }, { 13928, true, 5 }, - { 13457, false, 1, false, true }, // Greater Fire Protection Potion: drunk in the fight where the boss data orders it (Ragnaros' Might hits 20 y round a random mana user) + { 13452, false, 5 }, { 9206, false, 5 }, { 13928, true, 20 }, + { 13457, false, 5, false, true }, // Greater Fire Protection Potion: drunk in the fight where the boss data orders it (Ragnaros, Geddon, Onyxia, Firemaw, Vaelastrasz) + { 13459, false, 5, false, true }, // Greater Shadow Protection Potion: BWL Shadow Flame (Ebonroc, Flamegor, Nefarian) + { 13458, false, 5, false, true }, // Greater Nature Protection Potion: AQ40 Huhuran's Poison Bolt Volley + { 13456, false, 5, false, true }, // Greater Frost Protection Potion: Naxxramas Sapphiron }; } // namespace @@ -236,6 +271,29 @@ uint32 BestSupplyRank(SupplyFamily const& family, uint8 level) return 0; } +uint32 VirtualRecoveryRank(bool water, uint8 cls, uint8 level) +{ + SupplyFamily const* f = FindSupplyFamily(water ? "Water" : "Food"); + return f && SupplyFamilyForClass(*f, cls) ? BestSupplyRank(*f, level) : 0; +} + +bool IsVirtualRecoveryItem(uint32 item, uint8 cls, uint8 level, bool& water) +{ + for (bool const w : { false, true }) + { + SupplyFamily const* f = FindSupplyFamily(w ? "Water" : "Food"); + if (!f || !SupplyFamilyForClass(*f, cls)) + continue; + for (SupplyRank const& r : f->ranks) + if (r.item == item && r.min_level <= level) + { + water = w; + return true; + } + } + return false; +} + uint32 BestAmmo(uint8 kind, uint8 level) { if (kind != 1 && kind != 2) @@ -252,6 +310,8 @@ uint32 BestAmmo(uint8 kind, uint8 level) { // First pass: Classic-era (expansion 0) vendor-grade ammo; second pass drops the era filter // in case the item data does not tag it. + // Ammo the client draws with a model first: the generic 1.60 ammo display is a white box (Player::HasDrawableAmmoDisplay). + for (int drawable = 1; drawable >= 0 && !t[k - 1][lvl]; --drawable) for (int strict = 1; strict >= 0 && !t[k - 1][lvl]; --strict) { float bestDmg = -1.0f; @@ -267,6 +327,8 @@ uint32 BestAmmo(uint8 kind, uint8 level) continue; if (strict && proto.GetRequiredExpansion() != 0) continue; + if (drawable && !Player::HasDrawableAmmoDisplay(&proto)) + continue; ItemDamageAmmoEntry const* dmgRow = sItemDamageAmmoStore.LookupEntry(proto.GetBaseItemLevel()); float const dmg = dmgRow ? dmgRow->Quality[proto.GetQuality()] : 0.0f; int32 const req = proto.GetBaseRequiredLevel(); @@ -283,6 +345,14 @@ uint32 BestAmmo(uint8 kind, uint8 level) } } } + for (uint8 k = 1; k <= 2; ++k) + for (uint8 lvl : { uint8(1), uint8(10), uint8(20), uint8(40), uint8(60) }) + if (uint32 const id = t[k - 1][lvl]) + { + ItemTemplate const* proto = sObjectMgr->GetItemTemplate(id); + TC_LOG_INFO("playerbot.v2", "[ammo_display] {} level {}: item {} display {} drawable {}", k == 2 ? "bullet" : "arrow", lvl, id, + Player::GetAmmoDisplayId(proto), int(Player::HasDrawableAmmoDisplay(proto))); + } return t; }(); return table[kind - 1][std::min(level, 60)]; diff --git a/src/modules/PlayerbotV2/Api/ClassicSupplies.h b/src/modules/PlayerbotV2/Api/ClassicSupplies.h index 0bfc5925b0..6c629adc32 100644 --- a/src/modules/PlayerbotV2/Api/ClassicSupplies.h +++ b/src/modules/PlayerbotV2/Api/ClassicSupplies.h @@ -67,6 +67,12 @@ TC_GAME_API SupplyFamily const* FindSupplyFamily(std::string_view name); // Highest rank of `family` usable at `level` that the server knows; 0 when none. TC_GAME_API uint32 BestSupplyRank(SupplyFamily const& family, uint8 level); +// Infinite food and water (Api/VirtualSupply.h): the Food (`water` false) / Water rank a bot of `cls` and `level` eats or drinks when +// none is in its bags; 0 when the family is not the class's (water for a class without mana). +TC_GAME_API uint32 VirtualRecoveryRank(bool water, uint8 cls, uint8 level); +// `item` is a rank of the Food / Water family a bot of `cls` and `level` may use without the item; its kind in `water`. +TC_GAME_API bool IsVirtualRecoveryItem(uint32 item, uint8 cls, uint8 level, bool& water); + // ---- Group buff spells ---- // The party versions of the class buffs (Prayer of Fortitude, Prayer of Shadow Protection, Arcane Brilliance, Gift of the Wild) and // their higher ranks: a vanilla player trains them at 48-60, but the Forever trainers do not list them (MC mc_garr 2026-10-12: "spell @@ -81,7 +87,7 @@ TC_GAME_API bool LearnableGroupBuff(uint32 spell, uint8 level); // The restock tops the bags up to AMMO_TARGET (several stacks) once the stock is under // AMMO_LOW_PERCENT of it. constexpr uint32 AMMO_TARGET = 1000; -constexpr uint32 AMMO_LOW_PERCENT = 30; +constexpr uint32 AMMO_LOW_PERCENT = 60; constexpr uint32 AmmoLowBelow() { return AMMO_TARGET * AMMO_LOW_PERCENT / 100; } // Best projectile of `kind` a bot of `level` can use (required level <= level, highest diff --git a/src/modules/PlayerbotV2/Api/ClassicTalentBuilds.cpp b/src/modules/PlayerbotV2/Api/ClassicTalentBuilds.cpp index 95d6a6dbfa..0ff07a74dc 100644 --- a/src/modules/PlayerbotV2/Api/ClassicTalentBuilds.cpp +++ b/src/modules/PlayerbotV2/Api/ClassicTalentBuilds.cpp @@ -12,79 +12,108 @@ namespace { // ---- Warrior ---- constexpr TalentPick kWarriorArms[] = { - { "Improved Heroic Strike", 3 }, { "Deflection", 2 }, { "Improved Charge", 2 }, { "Tactical Mastery", 3 }, + // A talent below another needs a parent node filled to its maximum, so the first rows are bought in full (Deflection 5, Improved + // Tactical Mastery 5, Improved Rend 3, Improved Thunder Clap 3): 143 stopped Deflection at 4 and Tactical Mastery at 3 and never + // got Deep Wounds, Anger Management or Impale. + { "Improved Heroic Strike", 3 }, { "Deflection", 5 }, { "Improved Rend", 3 }, { "Improved Charge", 2 }, { "Improved Tactical Mastery", 5 }, + { "Improved Thunder Clap", 3 }, { "Improved Overpower", 2 }, { "Anger Management", 1 }, { "Deep Wounds", 3 }, { "Two-Handed Weapon Specialization", 5 }, { "Impale", 2 }, { "Sweeping Strikes", 1 }, - { "Sword Specialization", 5 }, { "Improved Hamstring", 1 }, { "Mortal Strike", 1 }, - { "Cruelty", 5 }, { "Unbridled Wrath", 5 }, { "Improved Battle Shout", 5 }, { "Improved Execute", 2 }, - { "Enrage", 3 }, - // Fillers, bought only with points left over: Forever's trees have no talent called - // Tactical Mastery, Sword Specialization or Improved Battle Shout (PC run 2026-10-05). - { "Booming Voice", 5 }, { "Improved Rend", 3 }, { "Axe Specialization", 5 }, { "Improved Thunder Clap", 3 }, + { "Weaponmaster", 5 }, { "Improved Hamstring", 1 }, { "Mortal Strike", 1 }, + { "Cruelty", 5 }, { "Unbridled Wrath", 4 }, + // Fillers, bought only with points left over (Forever's trees have no Tactical Mastery, Sword Specialization or Improved Battle Shout, + // and the 70532 tree no Axe Specialization: "build talents not found" on every arms walk of 235). + { "Improved Execute", 2, true }, { "Enrage", 3, true }, { "Booming Voice", 5, true }, }; constexpr TalentPick kWarriorFury[] = { - { "Cruelty", 5 }, { "Unbridled Wrath", 5 }, { "Improved Battle Shout", 5 }, { "Dual Wield Specialization", 5 }, - { "Improved Execute", 2 }, { "Death Wish", 1 }, { "Enrage", 2 }, { "Flurry", 5 }, { "Bloodthirst", 1 }, - { "Improved Cleave", 3 }, - { "Improved Heroic Strike", 3 }, { "Deflection", 3 }, { "Tactical Mastery", 5 }, { "Anger Management", 1 }, - { "Deep Wounds", 3 }, { "Impale", 2 }, - { "Booming Voice", 5 }, { "Improved Demoralizing Shout", 5 }, { "Blood Craze", 3 }, // fillers, see Arms + // The vanilla raid fury build, 17 Arms / 34 Fury (51 points). The Arms core goes first: the last build spent 46 points in Fury before it + // reached them and Deep Wounds was refused (damage_parity 146). The 147 build (Deflection, Tactical Mastery, Charge first) left Deep Wounds refused with + // LearnResult 2, so the parents it was bought under in the 71 build go first (Rend, Thunder Clap, Overpower, Anger Management). Impale needs more + // Arms points than 17 allow. + // 156: Deep Wounds was bought, Anger Management refused with nothing held (Improved Tactical Mastery, its parent, was not in the list and the + // 17 points had no room for the parent fill). Rend and Thunder Clap are what Deep Wounds was bought under; Tactical Mastery opens Anger Management. + { "Improved Rend", 3 }, { "Improved Thunder Clap", 3 }, { "Improved Tactical Mastery", 5 }, { "Anger Management", 1 }, { "Deep Wounds", 3 }, + { "Improved Heroic Strike", 2 }, + // Bloodthirst needs 30 points in the Fury tab (Flurry's row needs 20 before it). + { "Cruelty", 5 }, { "Unbridled Wrath", 5 }, { "Dual Wield Specialization", 5 }, { "Enrage", 5 }, { "Improved Execute", 2 }, + { "Improved Berserker Rage", 2 }, { "Death Wish", 1 }, { "Flurry", 5 }, { "Bloodthirst", 1 }, + { "Booming Voice", 3 }, + { "Blood Craze", 3, true }, // filler, see Arms }; constexpr TalentPick kWarriorProtection[] = { - { "Shield Specialization", 5 }, { "Anticipation", 5 }, { "Toughness", 5 }, { "Last Stand", 1 }, - { "Improved Shield Block", 3 }, { "Defiance", 5 }, { "Improved Sunder Armor", 3 }, { "Improved Taunt", 2 }, - { "Concussion Blow", 1 }, { "One-Handed Weapon Specialization", 5 }, { "Shield Slam", 1 }, - { "Improved Revenge", 2 }, - { "Improved Heroic Strike", 3 }, { "Deflection", 2 }, { "Tactical Mastery", 3 }, + // Forever's Protection tree has no Toughness, Improved Shield Block, Improved Taunt or One-Handed Weapon Specialization (readiness audit + // group 4); it has Iron Will, Improved Shield Bash, Improved Shield Wall, Master of Defense, Vanguard and Bastion in their place. + // A rank above a node's maximum is clamped by the walk. + { "Shield Specialization", 5 }, { "Anticipation", 5 }, { "Iron Will", 5 }, { "Last Stand", 1 }, + { "Improved Shield Wall", 2 }, { "Defiance", 5 }, { "Improved Sunder Armor", 3 }, { "Improved Shield Bash", 2 }, + { "Concussion Blow", 1 }, { "Master of Defense", 5 }, { "Shield Slam", 1 }, + { "Improved Revenge", 2 }, { "Vanguard", 3 }, { "Bastion", 3 }, + { "Improved Heroic Strike", 3 }, { "Deflection", 2 }, { "Improved Tactical Mastery", 3 }, { "Cruelty", 5 }, - { "Improved Bloodrage", 2 }, { "Booming Voice", 5 }, // fillers, see Arms + { "Improved Bloodrage", 2, true }, { "Booming Voice", 5, true }, // fillers, see Arms }; // ---- Paladin ---- constexpr TalentPick kPaladinHoly[] = { - { "Divine Intellect", 5 }, { "Spiritual Focus", 5 }, { "Healing Light", 3 }, { "Consecration", 1 }, - { "Divine Strength", 1 }, { "Illumination", 5 }, { "Divine Favor", 1 }, { "Improved Blessing of Wisdom", 2 }, - { "Improved Lay on Hands", 2 }, { "Holy Power", 5 }, { "Holy Shock", 1 }, - { "Redoubt", 5 }, { "Guardian's Favor", 2 }, { "Toughness", 3 }, { "Blessing of Kings", 1 }, - { "Anticipation", 4 }, { "Improved Concentration Aura", 3 }, { "Improved Hammer of Justice", 2 }, + // Forever's Holy nodes (talent coverage dump): Consecration and Blessing of Kings are spells there, and there is no Improved Lay on Hands, + // Improved Blessing of Wisdom or Improved Concentration Aura node under those names. Sanctified Light and Divinity are spells, not nodes + // (the client's node list of class 2 has neither), and Illumination hangs under Reverence (node 110871, 3 ranks): without it Illumination + // was refused and the holy paladin of the support scorecard (230) healed with no Illumination at all. Light's Vigil (row y5730) needs 30 + // points in the Holy tab, and Holy Conduit (node 105704) is a Retribution node: bought before it, the tab held 29 and Light's Vigil was + // refused (233, LearnResult 2). Voice of Truth first makes the 30; Improved Hammer of Justice at 1 keeps the list at 51. + { "Divine Intellect", 5 }, { "Spiritual Focus", 2 }, { "Healing Light", 3 }, { "Reverence", 3 }, { "Divine Favor", 1 }, + { "Holy Power", 5 }, { "Holy Shock", 1 }, { "Illumination", 5 }, { "Purifying Power", 2 }, { "Infusion of Light", 2 }, + { "Voice of Truth", 1 }, { "Light's Vigil", 1 }, { "Holy Conduit", 2 }, + { "Redoubt", 5 }, { "Guardian's Favor", 2 }, { "Toughness", 5 }, { "Anticipation", 5 }, { "Improved Hammer of Justice", 1 }, }; constexpr TalentPick kPaladinProtection[] = { - { "Redoubt", 5 }, { "Precision", 3 }, { "Toughness", 2 }, { "Blessing of Kings", 1 }, - { "Improved Righteous Fury", 3 }, { "Shield Specialization", 1 }, { "Anticipation", 5 }, - { "Blessing of Sanctuary", 1 }, { "Improved Hammer of Justice", 3 }, { "Guardian's Favor", 1 }, - { "One-Handed Weapon Specialization", 5 }, { "Holy Shield", 1 }, - { "Divine Strength", 5 }, { "Divine Intellect", 5 }, { "Improved Seal of Righteousness", 5 }, - { "Consecration", 1 }, { "Unyielding Faith", 2 }, { "Improved Lay on Hands", 2 }, + // Forever's Protection tab (client node list of class 2, 168 log) has no Blessing of Sanctuary, Improved Seal of Righteousness or + // Improved Lay on Hands, and Precision, Shield Specialization and One-Handed Weapon Specialization stop at 3 ranks. Shield + // Specialization hangs under Redoubt, Holy Shield (row y5730) under Templar's Bulwark (y4530); tier order, parents first. + { "Redoubt", 5 }, { "Toughness", 5 }, { "Precision", 3 }, { "Guardian's Favor", 2 }, { "Anticipation", 5 }, + { "Improved Righteous Fury", 3 }, { "Shield Specialization", 3 }, { "Sacred Duty", 2 }, + { "Improved Hammer of Justice", 3 }, { "One-Handed Weapon Specialization", 3 }, + { "Templar's Bulwark", 1 }, { "Reckoning", 5 }, { "Holy Shield", 1 }, + { "Divine Strength", 5 }, { "Divine Intellect", 5 }, { "Unyielding Faith", 2 }, }; constexpr TalentPick kPaladinRetribution[] = { - { "Improved Blessing of Might", 5 }, { "Benediction", 5 }, { "Improved Judgement", 2 }, - { "Improved Seal of the Crusader", 3 }, { "Seal of Command", 1 }, { "Conviction", 5 }, - { "Two-Handed Weapon Specialization", 3 }, { "Sanctity Aura", 1 }, { "Vengeance", 5 }, { "Repentance", 1 }, - { "Divine Strength", 5 }, { "Divine Intellect", 5 }, { "Improved Seal of Righteousness", 5 }, - { "Consecration", 1 }, { "Healing Light", 3 }, { "Unyielding Faith", 1 }, + // Forever's Retribution tab (class tree dump, 168 log): no Crusade, Sanctity Aura, Improved Blessing of Might or Improved Seal of the + // Crusader. Vengeance (row y4530) hangs under Sanctified Judgement (node 105701, 3 ranks), which is why it was refused with the tab + // full of other points. Tier order, parents first; the leftover pass spends the rest down the Retribution tab. + { "Improved Judgement", 2 }, { "Conviction", 5 }, { "Benediction", 5 }, { "Deflection", 5 }, + { "Vindication", 3 }, { "Sanctified Judgement", 3 }, { "Seal of Command", 1 }, { "Pursuit of Justice", 2 }, + { "Eye for an Eye", 2 }, { "Sacred Arbiter", 1 }, { "Vengeance", 3 }, { "Two-Handed Weapon Specialization", 3 }, + { "Repentance", 1 }, { "Improved Seal of Fury", 1 }, { "Swift Judgement", 1 }, { "Instrument of Law", 2 }, { "Twist of Light", 1 }, }; // ---- Hunter ---- constexpr TalentPick kHunterBeastMastery[] = { - { "Improved Aspect of the Hawk", 5 }, { "Endurance Training", 5 }, { "Unleashed Fury", 5 }, { "Ferocity", 5 }, - { "Intimidation", 1 }, { "Spirit Bond", 2 }, { "Bestial Discipline", 2 }, { "Frenzy", 5 }, + // Forever names (talent coverage dump of the client data): Deadly Aspects is the Improved Aspect of the Hawk, Lethal Attacks the Lethal Shots; + // Aimed Shot is a trainer spell there, not a talent. + { "Deadly Aspects", 5 }, { "Endurance Training", 5 }, { "Unleashed Fury", 5 }, { "Ferocity", 5 }, + { "Intimidation", 1 }, { "Spirit Bond", 2 }, { "Bestial Discipline", 2 }, { "Frenzy", 2 }, { "Bestial Wrath", 1 }, - { "Efficiency", 5 }, { "Lethal Shots", 5 }, { "Aimed Shot", 1 }, { "Hawk Eye", 3 }, - { "Improved Arcane Shot", 1 }, { "Mortal Shots", 5 }, + // Mortal Shots (node 105002) hangs under Careful Aim (node 105008) in full: without it Mortal Shots was refused in every scorecard + // (236: "refused Mortal Shots has parents: node 105008 edge type 2 0/5"). Careful Aim's 5 points come off Hawk Eye and Efficiency. + { "Efficiency", 3 }, { "Lethal Attacks", 5 }, { "Careful Aim", 5 }, + { "Improved Arcane Shot", 5 }, { "Mortal Shots", 5 }, }; constexpr TalentPick kHunterMarksmanship[] = { - { "Efficiency", 5 }, { "Lethal Shots", 5 }, { "Aimed Shot", 1 }, { "Hawk Eye", 3 }, - { "Improved Arcane Shot", 1 }, { "Mortal Shots", 5 }, { "Barrage", 3 }, { "Scatter Shot", 1 }, - { "Improved Hunter's Mark", 1 }, { "Ranged Weapon Specialization", 5 }, { "Trueshot Aura", 1 }, - { "Monster Slaying", 3 }, { "Humanoid Slaying", 2 }, { "Entrapment", 3 }, { "Survivalist", 5 }, - { "Surefooted", 3 }, { "Trap Mastery", 2 }, + // Names from the talent dump of the client data (147/156 logs): Forever's Marksmanship has no Lethal Shots, Aimed Shot (a trainer + // spell there), Improved Hunter's Mark, Monster / Humanoid Slaying or Trap Mastery. Mortal Shots was refused with the tab full of + // other points, so the rows that open its tier are bought before it, then the leftover pass spends what remains in the tab. + { "Improved Concussive Shot", 5 }, { "Efficiency", 5 }, { "Improved Arcane Shot", 5 }, { "Hawk Eye", 3 }, + { "Improved Serpent Sting", 5 }, { "Improved Stings", 3 }, { "Rapid Killing", 2 }, { "Careful Aim", 5 }, + { "Barrage", 3 }, { "Scatter Shot", 1 }, { "Mortal Shots", 5 }, { "Ranged Weapon Specialization", 5 }, + { "Trueshot Aura", 1 }, }; constexpr TalentPick kHunterSurvival[] = { - { "Monster Slaying", 3 }, { "Humanoid Slaying", 3 }, { "Savage Strikes", 2 }, { "Entrapment", 2 }, - { "Survivalist", 5 }, { "Deterrence", 1 }, { "Surefooted", 3 }, { "Trap Mastery", 1 }, - { "Killer Instinct", 3 }, { "Improved Feign Death", 2 }, { "Lightning Reflexes", 5 }, { "Wyvern Sting", 1 }, - { "Efficiency", 5 }, { "Lethal Shots", 5 }, { "Aimed Shot", 1 }, { "Hawk Eye", 3 }, - { "Improved Arcane Shot", 1 }, { "Mortal Shots", 5 }, + // Forever's Survival nodes (talent coverage dump of the client data): no Monster / Humanoid Slaying, Trap Mastery, Killer Instinct, Improved + // Feign Death or Lightning Reflexes there, and Wyvern Sting is a spell. 31 points in the tab, the rest in the Marksmanship nodes the rotation uses. + { "Savage Strikes", 2 }, { "Entrapment", 5 }, { "Survivalist", 5 }, { "Deterrence", 1 }, { "Surefooted", 3 }, { "Clever Traps", 1 }, + { "Survival Tactics", 2 }, { "Counterattack", 1 }, { "Improved Wing Clip", 3 }, { "Predator's Edge", 5 }, + { "Efficiency", 3 }, { "Lethal Attacks", 5 }, { "Careful Aim", 5 }, // Mortal Shots needs Careful Aim in full, see Beast Mastery + { "Improved Arcane Shot", 5 }, { "Mortal Shots", 5 }, }; // ---- Rogue ---- @@ -93,147 +122,171 @@ constexpr TalentPick kRogueAssassination[] = { { "Relentless Strikes", 1 }, { "Lethality", 5 }, { "Vile Poisons", 1 }, { "Cold Blood", 1 }, { "Improved Poisons", 4 }, { "Seal Fate", 5 }, { "Vigor", 1 }, { "Improved Sinister Strike", 2 }, { "Lightning Reflexes", 3 }, { "Precision", 5 }, { "Endurance", 2 }, - { "Riposte", 1 }, { "Improved Backstab", 2 }, { "Dual Wield Specialization", 5 }, + { "Improved Eviscerate", 1 }, { "Puncturing Wounds", 3 }, { "Dual Wield Specialization", 5 }, }; constexpr TalentPick kRogueCombat[] = { - { "Improved Sinister Strike", 2 }, { "Lightning Reflexes", 3 }, { "Precision", 5 }, { "Riposte", 1 }, + { "Improved Sinister Strike", 2 }, { "Lightning Reflexes", 3 }, { "Precision", 5 }, { "Deflection", 5 }, { "Riposte", 1 }, { "Endurance", 2 }, { "Improved Sprint", 2 }, { "Dual Wield Specialization", 5 }, { "Blade Flurry", 1 }, - { "Sword Specialization", 5 }, { "Weapon Expertise", 2 }, { "Aggression", 2 }, { "Adrenaline Rush", 1 }, + { "Hack and Slash", 5 }, { "Weapon Expertise", 2 }, { "Aggression", 2 }, { "Adrenaline Rush", 1 }, { "Malice", 5 }, { "Murder", 2 }, { "Ruthlessness", 3 }, { "Improved Slice and Dice", 3 }, { "Relentless Strikes", 1 }, { "Lethality", 1 }, { "Opportunity", 5 }, }; constexpr TalentPick kRogueSubtlety[] = { - { "Opportunity", 5 }, { "Sleight of Hand", 2 }, { "Camouflage", 3 }, { "Initiative", 3 }, + { "Opportunity", 5 }, { "Master of Deception", 5 }, { "Camouflage", 3 }, { "Initiative", 3 }, { "Improved Ambush", 3 }, { "Ghostly Strike", 1 }, { "Serrated Blades", 3 }, { "Hemorrhage", 1 }, - { "Preparation", 1 }, { "Dirty Deeds", 2 }, { "Setup", 1 }, { "Deadliness", 5 }, { "Premeditation", 1 }, + { "Preparation", 1 }, { "Dirty Deeds", 2 }, { "Setup", 1 }, { "Heightened Senses", 2 }, { "Premeditation", 1 }, { "Improved Sinister Strike", 2 }, { "Lightning Reflexes", 3 }, { "Precision", 5 }, { "Endurance", 2 }, - { "Riposte", 1 }, { "Improved Backstab", 2 }, { "Dual Wield Specialization", 5 }, + { "Improved Eviscerate", 1 }, { "Puncturing Wounds", 3 }, { "Dual Wield Specialization", 5 }, }; // ---- Priest ---- constexpr TalentPick kPriestDiscipline[] = { - { "Unbreakable Will", 5 }, { "Improved Power Word: Fortitude", 2 }, { "Improved Power Word: Shield", 3 }, - { "Inner Focus", 1 }, { "Meditation", 3 }, { "Martyrdom", 1 }, { "Mental Agility", 5 }, - { "Divine Spirit", 1 }, { "Mental Strength", 4 }, { "Force of Will", 5 }, { "Power Infusion", 1 }, - { "Improved Renew", 3 }, { "Holy Specialization", 2 }, { "Divine Fury", 5 }, { "Inspiration", 3 }, - { "Holy Nova", 1 }, { "Healing Focus", 1 }, { "Improved Healing", 3 }, { "Holy Reach", 2 }, + // Forever's Discipline tab (client node list of class 5, support scorecard 230) has no Divine Spirit or Force of Will; it has Twin Disciplines, + // Soul Warding, Renewed Hope, Penance and Divine Aegis, the shield and crit-heal talents a discipline healer is built round. + { "Twin Disciplines", 5 }, { "Improved Power Word: Shield", 3 }, { "Silent Resolve", 3 }, { "Martyrdom", 1 }, + { "Inner Focus", 1 }, { "Meditation", 3 }, { "Mental Agility", 3 }, { "Soul Warding", 1 }, { "Mental Strength", 5 }, + { "Renewed Hope", 5 }, { "Penance", 1 }, { "Divine Aegis", 3 }, { "Power Infusion", 1 }, + // 51 points: with Martyrdom at 2 the list held 52 and Inspiration, last, stopped at 2 of 3 (support scorecard 233). + { "Improved Renew", 3 }, { "Holy Specialization", 5 }, { "Divine Fury", 5 }, { "Inspiration", 3 }, }; constexpr TalentPick kPriestHoly[] = { - { "Improved Renew", 3 }, { "Holy Specialization", 2 }, { "Divine Fury", 5 }, { "Inspiration", 3 }, - { "Holy Nova", 1 }, { "Healing Focus", 1 }, { "Improved Healing", 3 }, { "Holy Reach", 2 }, - { "Spirit of Redemption", 1 }, { "Spiritual Guidance", 4 }, { "Spiritual Healing", 5 }, - { "Unbreakable Will", 5 }, { "Improved Power Word: Fortitude", 2 }, { "Improved Power Word: Shield", 3 }, - { "Meditation", 3 }, { "Inner Focus", 1 }, { "Martyrdom", 1 }, { "Mental Agility", 5 }, { "Divine Spirit", 1 }, + { "Improved Renew", 3 }, { "Holy Specialization", 5 }, { "Divine Fury", 5 }, { "Inspiration", 3 }, + { "Holy Nova", 1 }, { "Litany of Light", 2 }, { "Improved Healing", 3 }, { "Holy Reach", 2 }, + { "Spirit of Redemption", 1 }, { "Spiritual Guidance", 5 }, { "Spiritual Healing", 5 }, + { "Silent Resolve", 3 }, { "Improved Power Word: Shield", 3 }, + { "Meditation", 3 }, { "Inner Focus", 1 }, { "Martyrdom", 2 }, { "Mental Agility", 3 }, // no Divine Spirit node in Forever }; constexpr TalentPick kPriestShadow[] = { { "Spirit Tap", 5 }, { "Improved Shadow Word: Pain", 2 }, { "Shadow Focus", 5 }, { "Mind Flay", 1 }, - { "Improved Mind Blast", 2 }, { "Shadow Weaving", 5 }, { "Vampiric Embrace", 1 }, { "Silence", 1 }, + { "Improved Mind Blast", 5 }, { "Shadow Weaving", 5 }, { "Vampiric Embrace", 1 }, { "Silence", 1 }, { "Shadow Reach", 3 }, { "Darkness", 5 }, { "Shadowform", 1 }, - { "Wand Specialization", 5 }, { "Improved Power Word: Fortitude", 2 }, { "Improved Power Word: Shield", 3 }, - { "Inner Focus", 1 }, { "Meditation", 3 }, { "Martyrdom", 1 }, { "Mental Agility", 5 }, + { "Wand Specialization", 5 }, { "Improved Power Word: Shield", 3 }, + { "Inner Focus", 1 }, { "Meditation", 3 }, { "Martyrdom", 2 }, { "Mental Agility", 5 }, }; // ---- Shaman ---- constexpr TalentPick kShamanElemental[] = { - { "Convection", 5 }, { "Concussion", 5 }, { "Elemental Focus", 1 }, { "Call of Thunder", 5 }, - { "Elemental Devastation", 3 }, { "Improved Fire Totems", 1 }, { "Elemental Fury", 1 }, { "Storm Reach", 2 }, - { "Call of Flame", 2 }, { "Lightning Mastery", 5 }, { "Elemental Mastery", 1 }, - { "Tidal Focus", 5 }, { "Totemic Focus", 5 }, { "Nature's Guidance", 3 }, { "Totemic Mastery", 1 }, - { "Healing Grace", 1 }, { "Tidal Mastery", 5 }, + // Forever's Elemental tab (193 log: Improved Fire Totems, Storm Reach, Lightning Mastery, Elemental Mastery, Nature's Guidance, Totemic Mastery and + // Healing Grace are not in the client data, so the bot had no cast-time or crit talents and Call of Thunder / Elemental Fury were refused for + // their parents). These are the client's names; a rank above a node's maximum is clamped. The 70532 client data has no Call of Thunder or + // Improved Fire Nova (236: "build talents not found: Improved Fire Nova", Call of Thunder not held, 6 points spent outside the tab); it has + // Elemental Mastery (row y5730, under Lava Burst) and Trial by Fire (node 104764: the Fire Nova talent, spell 16086) in their place. + { "Convection", 5 }, { "Concussion", 5 }, { "Call of Flame", 3 }, { "Elemental Devastation", 3 }, { "Reverberation", 5 }, + { "Elemental Warding", 3 }, { "Elemental Focus", 1 }, { "Elemental Alacrity", 3 }, { "Eye of the Storm", 3 }, + { "Elemental Reach", 2 }, { "Lightning Overload", 3 }, { "Elemental Fury", 5 }, { "Lava Burst", 1 }, + { "Call of Thunder|Elemental Mastery", 1 }, { "Improved Fire Nova|Trial by Fire", 2 }, + { "Earth's Grasp", 2 }, { "Earthbound", 1 }, }; constexpr TalentPick kShamanEnhancement[] = { - { "Ancestral Knowledge", 5 }, { "Thundering Strikes", 5 }, { "Two-Handed Axes and Maces", 1 }, - { "Anticipation", 4 }, { "Flurry", 5 }, { "Elemental Weapons", 3 }, { "Improved Weapon Totems", 2 }, - { "Weapon Mastery", 5 }, { "Stormstrike", 1 }, - { "Tidal Focus", 5 }, { "Totemic Focus", 5 }, { "Nature's Guidance", 3 }, { "Totemic Mastery", 1 }, - { "Healing Grace", 1 }, { "Restorative Totems", 5 }, + // 147 bought 19 Enhancement points: Forever's Enhancement tab has no Two-Handed Axes and Maces, Improved Weapon Totems or Weapon Mastery, + // and the Tidal Focus / Totemic Focus / Restorative Totems picks that followed took 15 points in Restoration, so Anticipation stopped at 3 + // and Flurry was refused. These are names from the client data; a rank above a node's maximum is clamped. + { "Ancestral Knowledge", 5 }, { "Thundering Strikes", 5 }, { "Anticipation", 5 }, { "Toughness", 5 }, { "Elemental Weapons", 3 }, + { "Flurry", 5 }, { "Spirit Weapons", 1 }, { "Shamanistic Focus", 1 }, { "Stormstrike", 1 }, { "Improved Stormstrike", 5 }, + { "Mental Dexterity", 5 }, { "Mental Quickness", 5 }, { "Guardian Totems", 2 }, { "Improved Lightning Shield", 3 }, { "Improved Ghost Wolf", 2 }, }; constexpr TalentPick kShamanRestoration[] = { - { "Improved Healing Wave", 5 }, { "Tidal Focus", 5 }, { "Nature's Guidance", 3 }, { "Totemic Mastery", 1 }, - { "Healing Focus", 1 }, { "Tidal Mastery", 5 }, { "Nature's Swiftness", 1 }, { "Healing Way", 3 }, - { "Restorative Totems", 1 }, { "Purification", 5 }, { "Mana Tide Totem", 1 }, - { "Restorative Totems", 5 }, { "Healing Grace", 3 }, { "Ancestral Healing", 3 }, { "Totemic Focus", 5 }, - { "Healing Focus", 5 }, { "Improved Reincarnation", 1 }, + // Forever's Restoration tab (client node list of class 7, support scorecard 230) has no Nature's Guidance, Totemic Mastery or Healing Grace. + // Natural Grace is its spell-threat talent (Healing Grace's job), and it has Water Shield and Riptide. + { "Improved Healing Wave", 5 }, { "Tidal Focus", 5 }, { "Natural Grace", 3 }, { "Water Shield", 1 }, + { "Healing Focus", 5 }, { "Tidal Mastery", 5 }, { "Nature's Swiftness", 1 }, { "Healing Way", 3 }, + { "Restorative Totems", 1 }, { "Purification", 5 }, { "Mana Tide Totem", 1 }, { "Riptide", 1 }, + { "Restorative Totems", 5 }, { "Ancestral Healing", 3 }, { "Totemic Focus", 5 }, + { "Healing Focus", 5 }, { "Improved Reincarnation", 2 }, }; // ---- Mage ---- constexpr TalentPick kMageArcane[] = { { "Arcane Subtlety", 2 }, { "Arcane Focus", 3 }, { "Arcane Concentration", 5 }, - { "Improved Arcane Explosion", 3 }, { "Arcane Resilience", 1 }, { "Magic Absorption", 1 }, - { "Arcane Meditation", 3 }, { "Improved Arcane Missiles", 2 }, { "Presence of Mind", 1 }, - { "Arcane Mind", 5 }, { "Arcane Instability", 3 }, { "Magic Attunement", 1 }, { "Arcane Power", 1 }, + { "Arcane Impact", 3 }, { "Arcane Resilience", 1 }, { "Magic Absorption", 1 }, + { "Arcane Meditation", 3 }, { "Improved Channeling", 2 }, { "Presence of Mind", 1 }, + { "Arcane Mind", 5 }, { "Arcane Instability", 3 }, { "Arcane Power", 1 }, { "Improved Frostbolt", 5 }, { "Ice Shards", 5 }, { "Piercing Ice", 3 }, { "Frostbite", 2 }, { "Frost Channeling", 3 }, { "Elemental Precision", 2 }, }; constexpr TalentPick kMageFire[] = { - { "Improved Fireball", 5 }, { "Ignite", 5 }, { "Pyroblast", 1 }, { "Improved Flamestrike", 3 }, - { "Burning Soul", 1 }, { "Improved Scorch", 3 }, { "Master of Elements", 2 }, { "Critical Mass", 3 }, - { "Blast Wave", 1 }, { "Impact", 1 }, { "Fire Power", 5 }, { "Combustion", 1 }, - { "Arcane Subtlety", 2 }, { "Arcane Focus", 3 }, { "Arcane Concentration", 5 }, - { "Improved Arcane Explosion", 3 }, { "Magic Absorption", 2 }, { "Arcane Meditation", 3 }, - { "Improved Arcane Missiles", 2 }, + // Every Fire talent of the client list at its full rank (parity 200: the fire mage fell from 743 to 575 when the leftover points that used to + // finish the Fire tab went to the Arcane tail), the damage ones first; the last 7 points are Arcane Subtlety and Arcane Concentration. + // The 70532 client data gives Critical Mass 5 ranks, and Combustion hangs under it in full (236: Combustion refused under node 105784 at 3/5); + // it has no Wake of Fire, and Improved Fire Blast (2 ranks) in its place. A rank above a node's maximum is clamped (Critical Mass 3 on 70450). + { "Improved Fireball", 5 }, { "Ignite", 5 }, { "Fire Power", 5 }, { "Critical Mass", 5 }, { "Improved Scorch", 3 }, + { "Master of Elements", 3 }, { "Incineration", 3 }, { "Pyroblast", 1 }, { "Combustion", 1 }, { "Impact", 3 }, + { "Improved Flamestrike", 3 }, { "Blast Wave", 1 }, { "Burning Soul", 3 }, { "Wake of Fire|Improved Fire Blast", 2 }, { "Heating Up", 1 }, + { "Flamethrowing", 2 }, + { "Arcane Subtlety", 2 }, { "Arcane Concentration", 5 }, }; constexpr TalentPick kMageFrost[] = { - { "Improved Frostbolt", 5 }, { "Ice Shards", 5 }, { "Piercing Ice", 3 }, { "Cold Snap", 1 }, + // Cold Snap sits a tier down that needs 20 points in the tree: bought third it was refused (LearnResult 1, 147), so the rows above it go first. + { "Improved Frostbolt", 5 }, { "Ice Shards", 5 }, { "Piercing Ice", 3 }, { "Improved Blizzard", 1 }, { "Frost Channeling", 3 }, { "Shatter", 2 }, { "Ice Block", 1 }, - { "Elemental Precision", 3 }, { "Frostbite", 1 }, { "Winter's Chill", 5 }, { "Ice Barrier", 1 }, + { "Elemental Precision", 3 }, { "Cold Snap", 1 }, { "Frostbite", 1 }, { "Winter's Chill", 5 }, { "Ice Barrier", 1 }, { "Arcane Subtlety", 2 }, { "Arcane Focus", 3 }, { "Arcane Concentration", 5 }, - { "Improved Arcane Explosion", 3 }, { "Magic Absorption", 2 }, { "Arcane Meditation", 3 }, - { "Improved Arcane Missiles", 2 }, + { "Arcane Impact", 3 }, { "Magic Absorption", 2 }, { "Arcane Meditation", 3 }, + { "Improved Channeling", 2 }, }; // ---- Warlock ---- +// Forever's warlock tree has no Fel Intellect, Fel Stamina, Improved Healthstone, Devastation, Improved Firebolt, Improved Drain Soul, Grim Reach, +// Improved Curse of Weakness, Improved Immolate or Emberstorm (147 log: "build talents not found"); its names are Improved Bane of Agony, Improved Drains, +// Improved Health Funnel, Improved Imp, Fel Vitality, Aftermath, Pyroclasm, Intensity and the others of the client list. Filler picks (third field) +// are bought only with points left over, so an unknown rank cap never starves the core. constexpr TalentPick kWarlockAffliction[] = { - { "Improved Corruption", 5 }, { "Improved Life Tap", 2 }, { "Improved Drain Soul", 2 }, - { "Improved Curse of Weakness", 1 }, { "Improved Curse of Agony", 3 }, { "Amplify Curse", 1 }, - { "Fel Concentration", 1 }, { "Nightfall", 2 }, { "Grim Reach", 2 }, { "Siphon Life", 1 }, - { "Suppression", 5 }, { "Shadow Mastery", 5 }, { "Dark Pact", 1 }, - { "Demonic Embrace", 5 }, { "Fel Intellect", 5 }, { "Fel Domination", 1 }, { "Fel Stamina", 4 }, - { "Master Summoner", 2 }, { "Unholy Power", 2 }, { "Improved Healthstone", 1 }, + // The 70532 client data has no Malediction (236: "build talents not found: Malediction"); its row holds Malevolence (node 110876, spell + // 1310949: critical chance of Shadow spells, 5 ranks), which takes the same 3 points there. + { "Improved Corruption", 5 }, { "Improved Life Tap", 2 }, { "Improved Drains", 1 }, + { "Improved Bane of Agony", 3 }, { "Amplify Curse", 1 }, + { "Fel Concentration", 3 }, { "Nightfall", 2 }, { "Suppression", 5 }, { "Siphon Life", 1 }, + { "Malediction|Malevolence", 3 }, { "Shadow Mastery", 5 }, { "Pandemic", 1 }, + { "Demonic Embrace", 5 }, { "Fel Domination", 1 }, { "Master Summoner", 2 }, { "Unholy Power", 2 }, + { "Improved Shadow Bolt", 5, true }, { "Bane", 5, true }, }; constexpr TalentPick kWarlockDemonology[] = { - { "Demonic Embrace", 5 }, { "Fel Intellect", 5 }, { "Fel Domination", 1 }, { "Fel Stamina", 4 }, - { "Unholy Power", 5 }, { "Demonic Sacrifice", 1 }, { "Master Summoner", 2 }, { "Improved Healthstone", 2 }, - { "Master Demonologist", 5 }, { "Soul Link", 1 }, - { "Improved Shadow Bolt", 5 }, { "Bane", 5 }, { "Devastation", 5 }, { "Destructive Reach", 2 }, - { "Improved Firebolt", 2 }, { "Cataclysm", 1 }, + // Destruction/Ruin with a sacrificed Imp: the Demonology points that reach Demonic Sacrifice, then Destruction down to Ruin. + { "Demonic Embrace", 5 }, { "Improved Imp", 3 }, { "Improved Health Funnel", 2 }, { "Fel Domination", 1 }, + { "Master Summoner", 2 }, { "Unholy Power", 5 }, { "Demonic Sacrifice", 1 }, + { "Improved Shadow Bolt", 5 }, { "Bane", 5 }, { "Destructive Reach", 2 }, { "Cataclysm", 1 }, { "Ruin", 1 }, + { "Aftermath", 5 }, { "Pyroclasm", 3 }, { "Intensity", 2 }, + { "Fel Vitality", 3, true }, { "Master Demonologist", 5, true }, }; constexpr TalentPick kWarlockDestruction[] = { - { "Improved Shadow Bolt", 5 }, { "Bane", 5 }, { "Devastation", 5 }, { "Destructive Reach", 2 }, - { "Improved Firebolt", 2 }, { "Cataclysm", 1 }, { "Ruin", 1 }, { "Improved Immolate", 4 }, - { "Emberstorm", 5 }, { "Conflagrate", 1 }, - { "Demonic Embrace", 5 }, { "Fel Intellect", 5 }, { "Fel Domination", 1 }, { "Fel Stamina", 4 }, - { "Master Summoner", 2 }, { "Unholy Power", 2 }, { "Improved Healthstone", 1 }, + { "Improved Shadow Bolt", 5 }, { "Bane", 5 }, { "Destructive Reach", 2 }, { "Cataclysm", 1 }, { "Intensity", 2 }, + { "Aftermath", 5 }, { "Ruin", 1 }, { "Pyroclasm", 3 }, { "Conflagrate", 1 }, { "Shadowburn", 1 }, { "Decimation", 3 }, + { "Demonic Embrace", 5 }, { "Fel Domination", 1 }, { "Master Summoner", 2 }, { "Unholy Power", 2 }, + { "Improved Imp", 3, true }, { "Improved Health Funnel", 2, true }, { "Fel Vitality", 3, true }, }; // ---- Druid ---- constexpr TalentPick kDruidBalance[] = { - { "Improved Wrath", 5 }, { "Improved Moonfire", 5 }, { "Omen of Clarity", 1 }, { "Nature's Reach", 2 }, - { "Natural Weapons", 2 }, { "Vengeance", 5 }, { "Nature's Grace", 1 }, { "Moonglow", 3 }, - { "Improved Starfire", 1 }, { "Moonfury", 5 }, { "Moonkin Form", 1 }, - { "Furor", 5 }, { "Nature's Focus", 5 }, { "Reflection", 3 }, { "Improved Mark of the Wild", 2 }, + // Forever's druid trees have no Omen of Clarity, Natural Weapons or Improved Mark of the Wild (damage_parity 147); Insect Swarm is a talent + // there and the rotation casts it. + { "Improved Wrath", 5 }, { "Improved Moonfire", 5 }, { "Nature's Reach", 2 }, { "Vengeance", 5 }, + { "Nature's Grace", 1 }, { "Moonglow", 3 }, { "Improved Starfire", 5 }, { "Moonfury", 5 }, + { "Moonkin Form", 1 }, { "Insect Swarm", 1 }, + { "Furor", 5 }, { "Nature's Focus", 5 }, { "Reflection", 3 }, { "Improved Rejuvenation", 3 }, { "Tranquil Spirit", 2 }, }; +// Forever's feral tree names (damage_parity 147 talent list): no Feral Aggression, Improved Shred, Faerie Fire (Feral), Primal Fury or Improved Enrage. constexpr TalentPick kDruidFeralCat[] = { - { "Ferocity", 5 }, { "Feral Aggression", 5 }, { "Sharpened Claws", 3 }, { "Feline Swiftness", 2 }, - { "Improved Shred", 2 }, { "Predatory Strikes", 3 }, { "Blood Frenzy", 2 }, { "Savage Fury", 2 }, - { "Faerie Fire (Feral)", 1 }, { "Heart of the Wild", 5 }, { "Leader of the Pack", 1 }, - { "Furor", 5 }, { "Improved Mark of the Wild", 5 }, { "Improved Enrage", 2 }, { "Nature's Focus", 3 }, - { "Reflection", 3 }, { "Subtlety", 2 }, + { "Ferocity", 5 }, { "Feral Swiftness", 2 }, { "Sharpened Claws", 3 }, { "Shredding Attacks", 2 }, + { "Predatory Strikes", 3 }, { "Blood Frenzy", 2 }, { "Savage Fury", 2 }, { "Heart of the Wild", 5 }, + { "Leader of the Pack", 1 }, { "Furor", 5 }, { "Rend and Tear", 5 }, { "Brutal Impact", 2 }, + { "Feral Instinct", 5 }, { "Natural Shapeshifter", 3 }, { "Berserk", 1 }, { "Subtlety", 2 }, { "Reflection", 3 }, }; constexpr TalentPick kDruidFeralBear[] = { { "Ferocity", 5 }, { "Thick Hide", 5 }, { "Feral Charge", 1 }, { "Sharpened Claws", 3 }, - { "Feline Swiftness", 1 }, { "Predatory Strikes", 3 }, { "Primal Fury", 2 }, { "Faerie Fire (Feral)", 1 }, - { "Savage Fury", 2 }, { "Blood Frenzy", 2 }, { "Heart of the Wild", 5 }, { "Leader of the Pack", 1 }, - { "Furor", 5 }, { "Improved Mark of the Wild", 5 }, { "Improved Enrage", 2 }, { "Nature's Focus", 3 }, - { "Reflection", 3 }, { "Subtlety", 2 }, + { "Feral Swiftness", 2 }, { "Predatory Strikes", 3 }, { "Savage Fury", 2 }, { "Blood Frenzy", 2 }, + { "Heart of the Wild", 5 }, { "Leader of the Pack", 1 }, { "Furor", 5 }, { "Brutal Impact", 2 }, + { "Feral Instinct", 5 }, { "Natural Shapeshifter", 3 }, { "Subtlety", 2 }, { "Reflection", 3 }, }; constexpr TalentPick kDruidRestoration[] = { - { "Furor", 5 }, { "Improved Healing Touch", 5 }, { "Reflection", 3 }, { "Improved Mark of the Wild", 2 }, - { "Tranquil Spirit", 5 }, { "Nature's Swiftness", 1 }, { "Improved Rejuvenation", 3 }, - { "Gift of Nature", 5 }, { "Improved Regrowth", 5 }, { "Swiftmend", 1 }, { "Subtlety", 5 }, - { "Improved Wrath", 5 }, { "Improved Moonfire", 4 }, { "Natural Weapons", 1 }, { "Omen of Clarity", 1 }, + // Nature's Swiftness (node 104921) hangs under Naturalist (node 104922, edge type 2: the parent full), so with Naturalist at 2 of 5 it was + // refused in every support scorecard (233: "refused: Nature's Swiftness=2", readiness "Nature's Swiftness 0/1"). Naturalist in full; the three + // points come off Improved Moonfire. + { "Furor", 5 }, { "Genesis", 5 }, { "Reflection", 3 }, { "Naturalist", 5 }, + { "Tranquil Spirit", 5 }, { "Improved Rejuvenation", 3 }, + { "Gift of Nature", 5 }, { "Improved Regrowth", 5 }, { "Nature's Swiftness", 1 }, { "Swiftmend", 1 }, { "Subtlety", 5 }, + { "Improved Wrath", 5 }, { "Improved Moonfire", 1 }, }; // Class default first: it wins ties when a bot's talents fit several builds. diff --git a/src/modules/PlayerbotV2/Api/ClassicTalentBuilds.h b/src/modules/PlayerbotV2/Api/ClassicTalentBuilds.h index 840df582c2..3561a1f2cd 100644 --- a/src/modules/PlayerbotV2/Api/ClassicTalentBuilds.h +++ b/src/modules/PlayerbotV2/Api/ClassicTalentBuilds.h @@ -20,6 +20,7 @@ struct TalentPick { char const* name; uint8 ranks; + bool filler = false; // bought only with points left after every other pick has been tried }; struct TalentBuild diff --git a/src/modules/PlayerbotV2/Api/ForeignClassSpell.h b/src/modules/PlayerbotV2/Api/ForeignClassSpell.h new file mode 100644 index 0000000000..ea5fdba689 --- /dev/null +++ b/src/modules/PlayerbotV2/Api/ForeignClassSpell.h @@ -0,0 +1,15 @@ +// ForeignClassSpell - whether a spell a bot knows belongs to another class (Api/PlayerbotAPI.cpp purge_foreign_class_spells). +#pragma once + +#include + +namespace Playerbot::Api { + +// taught_by: the union of the class masks (1 << (class - 1)) of the trainers that teach the spell, 0 when no class trainer teaches it. +// A spell no class trainer teaches says nothing about its owner and is kept; one that only other classes' trainers teach is foreign. +constexpr bool IsForeignClassSpell(uint32_t taught_by, uint32_t class_mask) +{ + return taught_by != 0 && (taught_by & class_mask) == 0; +} + +} // namespace Playerbot::Api diff --git a/src/modules/PlayerbotV2/Api/JunkDrop.h b/src/modules/PlayerbotV2/Api/JunkDrop.h index d4aef712f1..dc966275da 100644 --- a/src/modules/PlayerbotV2/Api/JunkDrop.h +++ b/src/modules/PlayerbotV2/Api/JunkDrop.h @@ -16,6 +16,8 @@ struct JunkCandidate std::uint64_t value = 0; // vendor value of the whole stack bool poor = false; // grey quality: the only kind that may be destroyed bool quest = false; // quest items are never destroyed + bool spare_supply = false; // a stack of a shared consumable the restock hands out and tops up again (potions, Demonic Runes, + // bandages): never food or drink, never a class tool or reagent, never the player's own items }; // Returns the index of the cheapest destroyable grey that is worth less than the incoming loot, or npos when none is. @@ -35,4 +37,22 @@ inline std::size_t PickJunkToDrop(std::vector const& bags, bool i return best; } +// Room for a bot's food or drink (ClassicSupplies "Food" / "Water"): bots have endless supplies, and a healer with full bags and no drink +// cannot rest between pulls (deadmines_full on 0.1.23: the priest's bags were full, no water, healer_no_rest then healer_oom). The cheapest +// grey goes first; with none, the cheapest stack of a spare supply (it is restocked later, after the food and drink). Never anything else: +// the bot's gear and what its player gave it stay. npos when nothing may go. +inline std::size_t PickRoomForSupply(std::vector const& bags) +{ + std::size_t best = kNoJunk; + for (std::size_t i = 0; i < bags.size(); ++i) + if (bags[i].poor && !bags[i].quest && (best == kNoJunk || bags[i].value < bags[best].value)) + best = i; + if (best != kNoJunk) + return best; + for (std::size_t i = 0; i < bags.size(); ++i) + if (bags[i].spare_supply && !bags[i].quest && (best == kNoJunk || bags[i].value < bags[best].value)) + best = i; + return best; +} + } // namespace Playerbot diff --git a/src/modules/PlayerbotV2/Api/PathLiquid.h b/src/modules/PlayerbotV2/Api/PathLiquid.h index f38784d529..d9be7e775e 100644 --- a/src/modules/PlayerbotV2/Api/PathLiquid.h +++ b/src/modules/PlayerbotV2/Api/PathLiquid.h @@ -53,6 +53,15 @@ bool PathTouchesLiquid(std::vector const& pts, WetFn wet, float step return false; } +// Magma, slime and deep water only hurt the living: Player::EnvironmentalDamage returns at once for a dead player +// (IsImmuneToEnvironmentalDamage = !isTargetableForAttack), and the breath timer is disabled for a ghost. A ghost running to +// its corpse therefore walks over liquid; refusing a corpse run because the corpse lies in lava left the ghost standing at the +// graveyard (live 132g, Burning Steppes: path_fail Magma for the same corpse every 8 s, [move_abandon] ghost=true). +constexpr bool LiquidMattersFor(bool alive) +{ + return alive; +} + enum class LiquidAction : unsigned char { Go, UseDryRoute, Refuse }; // path_wet: the first route touches liquid; dry_found: a route that avoids it exists. diff --git a/src/modules/PlayerbotV2/Api/PlayerbotAPI.cpp b/src/modules/PlayerbotV2/Api/PlayerbotAPI.cpp index 5fb0f7f1fa..564816c538 100644 --- a/src/modules/PlayerbotV2/Api/PlayerbotAPI.cpp +++ b/src/modules/PlayerbotV2/Api/PlayerbotAPI.cpp @@ -2,16 +2,25 @@ // First real-bodies pass: cast_spell / move_to / hearth wired to TrinityCore. // Remaining commands listed in v2/API.md fill in incrementally. +#include +#include #include +#include +#include #include +#include "Api/ForeignClassSpell.h" #include "PlayerbotAPI.h" +#include "Bot/QuestLoot.h" #include "ClassicBotSkills.h" #include "Travel/ReachMemory.h" #include "ClassicSpec.h" #include "ClassicTalentBuilds.h" #include "ClassicSupplies.h" #include "Bot/ClassicUpkeep.h" +#include "Bot/AlwaysBuffs.h" +#include "Bot/SpellFamily.h" #include "Bot/Raid/ShieldRules.h" +#include "Diagnostics/DamageParity.h" #include "BotItemScorer.h" #include "Player.h" #include "Corpse.h" @@ -46,12 +55,16 @@ #include "PlayerbotMovement.h" // unified bot-movement helpers #include "FollowDrop.h" // follow_drop: ledge plan toward an owner who dropped or jumped down #include "Fleet/CityLayer.h" // same-level moves across a drop, NoPath storm +#include "Fleet/BotPool.h" // Pool::IsScenarioBot: a test character trades with nobody #include "Bot/World/ZonePicker.h" // IsVanillaCapitalZone #include "Fleet/InstanceEntry.h" // PrepareInstanceEntry: a stale raid lock must not keep a companion out of its owner's instance #include "PartialRouteStall.h" #include "NoMotionGuard.h" #include "TradeFlow.h" #include "JunkDrop.h" +#include "VirtualSupply.h" +#include "Services.h" +#include "Util/ConfigReader.h" #include "BotTrade.h" #include "BotTradeShop.h" #include "SocialMgr.h" // SOCIAL_FLAG_FRIEND/IGNORED for friend ops @@ -68,6 +81,7 @@ #include "GameObject.h" #include "GameObjectAI.h" #include "MoveSpline.h" +#include "MoveSplineInit.h" #include "GossipDef.h" #include "QuestDef.h" #include "ObjectMgr.h" @@ -230,19 +244,26 @@ namespace PathBudget { static bool g_active = false; static uint32 g_deadline_ms = 0; - void BeginWorldTick(uint32 now_ms, uint32 budget_ms) { g_active = true; g_deadline_ms = now_ms + budget_ms; } + static bool g_refused = false; + void BeginWorldTick(uint32 now_ms, uint32 budget_ms) { g_active = true; g_refused = false; g_deadline_ms = now_ms + budget_ms; } void EndWorldTick() { g_active = false; } - bool HasBudget(uint32 now_ms) { return !g_active || now_ms < g_deadline_ms; } + bool HasBudget(uint32 now_ms) + { + bool const ok = !g_active || now_ms < g_deadline_ms; + if (!ok) g_refused = true; + return ok; + } + bool Refused() { return g_refused; } } // Per-bot path-failure LRU. Quantize destinations to 5y buckets so wander // angle jitter still re-attempts, but persistent dead-target spam doesn't // burn Detour CalculatePath every tick. Stamp on NoPath / // FarFromPolyEnd; early-return Result::Locked on the same bucket for -// `kPathFailTtlMs` after the stamp. Keyed (player guid low → ring of 4 +// `kPathFailTtlMs` after the stamp. Keyed (player guid low → ring of 4 // recent failures). Single-threaded access from the world tick so no lock. namespace { - constexpr size_t kPathFailCap = 16; // was 4 — a bot thrashing between + constexpr size_t kPathFailCap = 16; // was 4 — a bot thrashing between // several dead targets evicted a // persistent off-mesh dest before it // could be suppressed (Falin/Varothel @@ -254,7 +275,7 @@ namespace { // destination is off-mesh (above // terrain, inside a wall, a phantom // POI Z) and will NOT become reachable - // in 3s — re-trying every 3s forever + // in 3s — re-trying every 3s forever // is what made bots run back and forth. // Suppress long so goal-selection // commits to a reachable objective. @@ -304,13 +325,86 @@ namespace { ::Playerbot::V2::Travel::ReachMemory::Instance().NoteOk(p->GetMapId(), p->GetPositionX(), p->GetPositionY(), x, y); } + // A bot that sat down to eat or drink and is then sent to move keeps its sitting pose: it slides along with no walk or run + // animation, "like on a broomstick" (132, mage bots told to attack). A client stands its player up when it moves; the bot does it here. + void StandForMove(Player* p) + { + UnitStandStateType const st = p->GetStandState(); + if (st == UNIT_STAND_STATE_SIT || st == UNIT_STAND_STATE_KNEEL) + p->SetStandState(UNIT_STAND_STATE_STAND); + } + + // Drives a validated route as a waypoint walk. WaypointMovementGenerator does nothing for an owner that is not alive (DoUpdate and + // StartMove return at the first line), so a ghost on its corpse run was given a WAYPOINT generator that never produced a step: soak 127 + // had every ghost released at the Burning Steppes graveyards standing there for the whole 30 s guard window, six times over, until the + // spirit healer took them. A ghost gets the same points as one spline instead (the generator type stays WAYPOINT so the + // same-goal skip and the stall breaker in move_to treat it alike). + // + // `navmesh_points`: the nodes are the points of a navmesh path (PathGenerator), already lying on walkable polygons a few yards + // apart. WaypointMovementGenerator sent each one as its own spline, and a hop shorter than three seconds is only sent when the one + // before has ended, so a bot walking a city street stopped and started at every point (two bots on one route showed it in + // Ironforge, 132). Those routes go out as one spline through all points instead. + void MoveAlongRoute(Player* p, WaypointPath const& route, bool run, bool navmesh_points = false) + { + // The path generator's own cap is 74 points. A longer navmesh route is cut to its first 60 points and goes out as one spline all + // the same: the per-point walk stopped at every point, and in Ironforge, whose ring streets turn a 200 y errand into a 250-300 y + // route, nearly every town walk was over 60 points (bots ran, stopped and turned all the way, live 275). The rule re-sends the + // move when the bot reaches the cut, and the route is computed again from there. + constexpr size_t kMaxSplinePoints = 60; + if (p->IsAlive() && navmesh_points) + { + std::vector nodes; + nodes.reserve(route.Nodes.size()); + float px = p->GetPositionX(), py = p->GetPositionY(), pz = p->GetPositionZ(); + uint32 nid = 0; + for (WaypointNode const& n : route.Nodes) + { + // the first point is the bot's own place, and a spline refuses two points on top of each other + if ((n.X - px) * (n.X - px) + (n.Y - py) * (n.Y - py) + (n.Z - pz) * (n.Z - pz) < 0.2f * 0.2f) + continue; + nodes.emplace_back(nid++, n.X, n.Y, n.Z); + px = n.X; py = n.Y; pz = n.Z; + } + if (nodes.size() > kMaxSplinePoints) + nodes.erase(nodes.begin() + kMaxSplinePoints, nodes.end()); + if (!nodes.empty()) + { + WaypointPath exact(0, std::move(nodes), run ? WaypointMoveType::Run : WaypointMoveType::Walk); + exact.BuildSegments(); + p->GetMotionMaster()->MovePath(exact, /*repeatable*/ false, {}, {}, + run ? MovementWalkRunSpeedSelectionMode::ForceRun + : MovementWalkRunSpeedSelectionMode::ForceWalk, + {}, {}, {}, /*exactSplinePath*/ true, /*generatePath*/ false); + return; + } + } + if (p->IsAlive()) + { + p->GetMotionMaster()->MovePath(route, /*repeatable*/ false, {}, {}, + run ? MovementWalkRunSpeedSelectionMode::ForceRun + : MovementWalkRunSpeedSelectionMode::ForceWalk); + return; + } + std::vector pts; + pts.reserve(route.Nodes.size()); + for (WaypointNode const& n : route.Nodes) + pts.emplace_back(n.X, n.Y, n.Z); + if (pts.size() < 2) + return; + p->GetMotionMaster()->LaunchMoveSpline([pts = std::move(pts), run](Movement::MoveSplineInit& init) + { + init.MovebyPath(pts); + init.SetWalk(!run); + }, 0, MOTION_PRIORITY_NORMAL, WAYPOINT_MOTION_TYPE); + } + inline uint64 PathDestKey(uint32 map_id, float x, float y) { - // 5y buckets — angle jitter within ~5y still re-tries; persistent + // 5y buckets — angle jitter within ~5y still re-tries; persistent // same-spot pushes hit the same bucket. map_id mixed into the high // bits so cross-map (x,y) collisions (e.g. (0,0) on every map) // don't false-block. 16 bits each for qx/qy is plenty given world - // bounds (±17000y / 5 = ±3400, fits in i16). + // bounds (±17000y / 5 = ±3400, fits in i16). constexpr float kBucket = 5.0f; int32 qx = static_cast(std::floor(x / kBucket)); int32 qy = static_cast(std::floor(y / kBucket)); @@ -330,8 +424,8 @@ namespace { // Progress probe for the same-goal skip's STALL-BREAKER. The same-goal skip // (above) intentionally lets an active spline run without re-issuing, so a // winding/chunked route isn't restart-thrashed. But a spline can STALL with - // its generator still "live" — e.g. a WaypointMovementGenerator that can't - // navigate a long water segment or a water↔land shoreline seam (live: AV + // its generator still "live" — e.g. a WaypointMovementGenerator that can't + // navigate a long water segment or a water↔land shoreline seam (live: AV // pushers frozen in the river z~10 mid-valley; IoC Workshop attackers frozen // in the moat 151y short, both on COMPLETE mmap_probe paths). The plain skip // then freezes the bot forever AND keeps returning Ok, which resets the @@ -348,10 +442,10 @@ namespace { // spot (building interior, terrain pocket) can have its only route OUT wind // past the 74-poly/~292y path cap before the route turns toward a far goal, // so the reachable partial ends a touch FARTHER in straight-line - // (forward_progress<0) — yet walking it UNLOCKS an advancing path from the + // (forward_progress<0) — yet walking it UNLOCKS an advancing path from the // new pose (live: Durnan, indoors z505, partial nets 115y to (-4986,-954) - // [−47y to goal], but from THERE the next partial advances +372y). The - // non-advancing branch otherwise refuses → bot frozen forever (154 blocks). + // [−47y to goal], but from THERE the next partial advances +372y). The + // non-advancing branch otherwise refuses → bot frozen forever (154 blocks). // We FOLLOW such a partial to escape, bounded per (bot,goal) so a true tiny // pocket can't ping-pong forever: `crawls` counts consecutive non-advancing // escape steps; it resets when the goal changes OR the bot has genuinely @@ -370,29 +464,29 @@ namespace { // Per-bot equip-refusal backoff. EquipUpgradeFire (V2 MaintainRules) re-fires // equip_item every eligible tick while the candidate is still in the bag. - // When the server REFUSES the swap (CanEquipItem != OK — e.g. the loadout + // When the server REFUSES the swap (CanEquipItem != OK — e.g. the loadout // would break a 2H/dual-wield rule, item is level-gated, slot can't be // unequipped), the item stays in the bag and the rule retries forever, // burning a CanEquipItem probe every tick AND making /diag believe an equip - // is perpetually "pending". Record refused (item-entry → dest-slot) pairs + // is perpetually "pending". Record refused (item-entry → dest-slot) pairs // with a long TTL so the same hopeless swap is skipped until the situation // can plausibly change (level-up, gear swap, respec all far longer than the // backoff). Keyed by player-guid-low like the path-fail ring. - constexpr uint32 kEquipFailTtlMs = 60000; // 60s — far longer than a tick + constexpr uint32 kEquipFailTtlMs = 60000; // 60s — far longer than a tick // Per-bot map of refused (item-entry,dest-slot) key -> failure timestamp. // Was a fixed 6-slot FIFO ring (kEquipFailCap) whose eviction re-enabled the - // OLDEST hopeless swap once a bot carried >6 distinct un-equippable items — + // OLDEST hopeless swap once a bot carried >6 distinct un-equippable items — // the round-robin then out-paced the rule-side lockout, producing the // "EquipItem|ServerRefused every few seconds forever" livelock (freeze-dump // signature). An unbounded-per-key map keeps EVERY distinct refused key // suppressed the full TTL regardless of bag count; expired keys are GC'd // opportunistically on insert so the inner map stays bounded by "distinct // items refused in the last 60s" (small). World-thread only (equip executes - // via the intent drain on the world thread), exactly like the prior ring — + // via the intent drain on the world thread), exactly like the prior ring — // no lock needed. std::unordered_map> g_equip_fail{}; - // Key folds the source item-entry (24 low bits — entries fit) with the + // Key folds the source item-entry (24 low bits — entries fit) with the // destination equipment slot (8 high bits) so "this item into this slot" // is the unit of backoff. The same item refused into a different slot, or a // different item into the same slot, still gets a fresh attempt. @@ -560,7 +654,7 @@ static uint32 HighestKnownRank(Player const* p, uint32 spell_id) // // Spell::CheckRange (strict, i.e. at Spell::prepare) rejects a player's // SPELL_FACING_FLAG_INFRONT spell with SPELL_FAILED_UNIT_NOT_INFRONT unless -// HasInArc(M_PI, target) — and a player's orientation is normally the +// HasInArc(M_PI, target) — and a player's orientation is normally the // client's. SetFacingToObject is no use right before a cast: it queues a // MotionMaster facing spline whose orientation lands only on the NEXT unit // update, and the spline's launch sets MOVEMENTFLAG_FORWARD until then, so @@ -569,7 +663,7 @@ static uint32 HighestKnownRank(Player const* p, uint32 spell_id) // SPELL_FAILED_MOVING). Unit::SetFacingToPoint launches the facing spline // (clients see the turn) and advances it by its own duration at once, so the // orientation is server-side current and the spline already finished before -// CastSpell runs — the same thing the core does for its own facing points. +// CastSpell runs — the same thing the core does for its own facing points. // // Only a standing caster is turned: a moving one faces its movement direction // (its cast-time spells cannot start anyway, and turning it would overwrite @@ -590,6 +684,29 @@ static bool CastFacingEnabled() // Core 2026-10-08: casters 20-40 y from Gehennas logged ~100 "[facing] ... action=refaced" each with the angle never changing and // cast nothing (the snapshot reads such a bot as not moving after 2 s without displacement; the core call did not). Falling is // left alone: a bot in the air really is moving. Returns true when a flag was cleared. +// A bot that casts or shoots while its move spline runs is shown by the client in the cast pose sliding along the path (PC 20 Oct: mages and +// hunters "glide" when ordered to attack). One line per bot every 5 s says which generator moves it and how long the spline still has to go. +static void LogCastWhileMoving(Player* p, char const* what, uint32 spell) +{ + if (p->movespline->Finalized()) + return; + static std::mutex sMutex; + static std::unordered_map sLast; + uint32 const now = getMSTime(); + { + std::lock_guard lock(sMutex); + if (sLast.size() > 4096) + sLast.clear(); + uint32& last = sLast[p->GetGUID().GetCounter()]; + if (last && now - last < 5000u) + return; + last = now ? now : 1u; + } + TC_LOG_INFO("playerbot.v2", "[cast_while_moving] {} {} {}: generator {} spline_left {} ms flags 0x{:X} chase {} follow {} casting {}", p->GetName(), what, spell, + int(p->GetMotionMaster()->GetCurrentMovementGeneratorType()), p->movespline->timeRemaining(), uint32(p->GetUnitMovementFlags()), + int(p->HasUnitState(UNIT_STATE_CHASE_MOVE)), int(p->HasUnitState(UNIT_STATE_FOLLOW_MOVE)), int(p->HasUnitState(UNIT_STATE_CASTING))); +} + static bool ClearStaleMoveFlags(Player* p) { constexpr MovementFlags kWalkFlags = MovementFlags(MOVEMENTFLAG_FORWARD | MOVEMENTFLAG_BACKWARD | MOVEMENTFLAG_STRAFE_LEFT | MOVEMENTFLAG_STRAFE_RIGHT); @@ -674,6 +791,23 @@ Result API::cast_spell(uint32 spell_id, ObjectGuid target, bool exact_rank) last_cast_fail_ = CastRejectNotKnown; if (!spell_id) return Result::NotKnown; + // Reincarnation: 20608 is the passive that grants it and has nothing to cast. The resurrection is 21169, which the core offers a dead + // shaman through SelfResSpells when the passive is known and 21169 is off cooldown; a client casts it with CMSG_SELF_RES + // (WorldSession::HandleSelfResOpcode). The bot's cast of 20608 while dead takes the same path. + if (spell_id == 20608 && !p_->IsAlive()) + { + constexpr int32 reincarnation_res = 21169; + if (p_->m_activePlayerData->SelfResSpells.FindIndex(reincarnation_res) < 0) + return Result::NotReady; + if (p_->HasAuraType(SPELL_AURA_PREVENT_RESURRECTION)) + return Result::Locked; + SpellCastResult const res = p_->CastSpell(p_, uint32(reincarnation_res), false); + if (res != SPELL_CAST_OK) + return Result::ServerRefused; + p_->RemoveSelfResSpell(reincarnation_res); + return Result::Ok; + } + uint32 const requested_id = spell_id; if (!exact_rank || !p_->HasSpell(spell_id)) spell_id = HighestKnownRank(p_, spell_id); @@ -758,7 +892,7 @@ Result API::cast_spell(uint32 spell_id, ObjectGuid target, bool exact_rank) // target from the snapshot, which can be one cadence stale: the // member may have changed map, phased out, or just disconnected. // Casting at it then fails server-side with SPELL_FAILED_BAD_TARGETS - // (error 91) — the dominant cause of a 72%-cast-failure / 32K-reject + // (error 91) — the dominant cause of a 72%-cast-failure / 32K-reject // storm observed live (heals/totems firing at a no-longer-valid // unit). Reject here so we never emit the doomed cast. if (tu->GetMapId() != p_->GetMapId() || !p_->InSamePhase(tu)) @@ -777,7 +911,7 @@ Result API::cast_spell(uint32 spell_id, ObjectGuid target, bool exact_rank) // Reject offensive casts on a dead (or about-to-despawn) target. // Audit 2026-05-22: all 14 caster specs gate only on // HasLiveTarget() (target guid present), not on the target's HP - // — so when a mob dies mid-cast-emit, the rotation queues a fresh + // — so when a mob dies mid-cast-emit, the rotation queues a fresh // 2.5s Frostbolt that resolves with SPELL_FAILED_TARGETS_DEAD, // wasting the GCD and mana. Centralize the dead-target gate here // so every spec inherits it, except rez-style spells that @@ -793,11 +927,11 @@ Result API::cast_spell(uint32 spell_id, ObjectGuid target, bool exact_rank) } // Reject offensive casts on a target carrying a Spell Reflect - // aura. Audit 2026-05-22: no caster spec checks this — bots + // aura. Audit 2026-05-22: no caster spec checks this — bots // happily chain Frostbolts into a Warrior with Spell Reflection // up and absorb their own damage. Targeted spells (info->IsTargetingArea // == false) on a HOSTILE target with a reflect aura should be - // skipped — let the rotation pick a different spell (instant / + // skipped — let the rotation pick a different spell (instant / // melee) or the spec's normal "no target" fallback. // Spell-reflect aura ids to detect: // 23920 Spell Reflection (Warrior; 5s reflect-all-magic buff) @@ -838,7 +972,7 @@ Result API::cast_spell(uint32 spell_id, ObjectGuid target, bool exact_rank) // can_cast(), but APL predicates across all 39 specs don't // consistently gate. Centralize at the API level so a silenced // bot doesn't spam SPELL_FAILED_SILENCED. Exception: melee abilities - // and self-buff spells aren't silenced — only spells in a school + // and self-buff spells aren't silenced — only spells in a school // the silence covers. Use the same check TC's CheckCast performs: // `HasAuraType(SPELL_AURA_MOD_SILENCE)` blocks all schools, while // `HasAuraType(SPELL_AURA_MOD_PACIFY_SILENCE)` blocks both melee @@ -855,7 +989,7 @@ Result API::cast_spell(uint32 spell_id, ObjectGuid target, bool exact_rank) } // Defensive range gate. Belt-and-suspenders for any rule whose target - // picker selects a unit far out of range — observed: group-buff rules + // picker selects a unit far out of range — observed: group-buff rules // casting Fortitude/Intellect/Soulstone at members 200-4800y away on a // shared continent map_id (~287k rejected casts in a 300MB log window). // The core rejects these in Spell::CheckRange anyway, but only after @@ -879,7 +1013,7 @@ Result API::cast_spell(uint32 spell_id, ObjectGuid target, bool exact_rank) } // Face the target when the spell needs it in front (Spell::CheckRange: - // SPELL_FACING_FLAG_INFRONT, ±90°) — Frostbolt, Shadow Bolt, melee and + // SPELL_FACING_FLAG_INFRONT, ±90°) — Frostbolt, Shadow Bolt, melee and // cone abilities fail with SPELL_FAILED_UNIT_NOT_INFRONT otherwise, and a // bot has no client to turn it. Live MC 2026-10-06: mages and warlocks // stood with their backs to the boss after a raid move; the old @@ -920,7 +1054,7 @@ Result API::cast_spell(uint32 spell_id, ObjectGuid target, bool exact_rank) } // Movement spells (Charge/Leap/Jump) pathfind SYNCHRONOUSLY in core - // Spell::CheckCast / effect handlers — the 2026-06-17 87s world-thread hang + // Spell::CheckCast / effect handlers — the 2026-06-17 87s world-thread hang // was exactly a Warrior Charge's PathGenerator here, unguarded by the module. // Gate ONLY these on the per-tick pathfinding budget (normal rotation casts // never pathfind, so they are never throttled). Return Result::Locked @@ -937,6 +1071,11 @@ Result API::cast_spell(uint32 spell_id, ObjectGuid target, bool exact_rank) ClearStaleMoveFlags(p_); SpellCastResult sr = p_->CastSpell(tu, spell_id, false); last_cast_fail_ = sr == SPELL_CAST_OK ? 0u : uint32(sr); + if (sr == SPELL_CAST_OK) + { + LogCastWhileMoving(p_, "casts", spell_id); + Diagnostics::Parity::NoteCast(p_, spell_id); + } if (sr != SPELL_CAST_OK) { // Throttled diagnostic: log the first failure per (spell, reason) combo @@ -946,7 +1085,7 @@ Result API::cast_spell(uint32 spell_id, ObjectGuid target, bool exact_rank) // picked it, but Casting=0 because the world thread rejected it. // For BAD_TARGETS we additionally dump the relationship breakdown so // we can tell apart visibility failures, faction friendliness, At-War - // flag misses, and immune-to-PC flags — they all surface as the same + // flag misses, and immune-to-PC flags — they all surface as the same // SpellCastResult but have different fixes. const float dist = tu != p_ ? p_->GetDistance(tu) : 0.f; if (sr == SPELL_FAILED_BAD_TARGETS && tu != p_) @@ -954,14 +1093,14 @@ Result API::cast_spell(uint32 spell_id, ObjectGuid target, bool exact_rank) // Faction / friendliness / hostility / immunity locals were // historically captured here but the log line below only consumes // canSee + validAttack + visibility/phase/stealth diagnostics. - // The MSVC C4189 spam (8 unused locals × every TU compile) hid - // real diagnostics — keep only what the log uses. + // The MSVC C4189 spam (8 unused locals × every TU compile) hid + // real diagnostics — keep only what the log uses. bool canSee = p_->CanSeeOrDetect(tu); bool validAttack = p_->IsValidAttackTarget(tu, info); // Decompose CanSeeOrDetect: phase + map already verified equal in // the previous iteration. Now drill down into the remaining branches - // — never-visible, private-object ownership, ghost/GM bitmask checks, - // detect-stealth/invis — to identify which one rejects the worg. + // — never-visible, private-object ownership, ghost/GM bitmask checks, + // detect-stealth/invis — to identify which one rejects the worg. bool sameMap = p_->GetMap() == tu->GetMap(); bool samePhase = WorldObject::InSamePhase(p_, tu); bool tgtInWorld = tu->IsInWorld(); @@ -1008,14 +1147,14 @@ Result API::cast_spell(uint32 spell_id, ObjectGuid target, bool exact_rank) // prereq (typical bot cases: warlock Create Healthstone refused // because one already exists, Soulstone already up on a target, a // proc-gated spell with no proc active). These persist far longer - // than a GCD — minutes, or until the underlying state cycles. + // than a GCD — minutes, or until the underlying state cycles. // Treat as persistent so the 10s back-off in BotIntentExecutor // kicks in, instead of hammering the rule every 1.5s GCD tick. case SPELL_FAILED_CASTER_AURASTATE: return Result::ServerRefused; case SPELL_FAILED_MOVING: return Result::Locked; // Not facing the target (a moving caster, or one whose turn could // not be applied): the next tick's cast faces it first, so retry then - // rather than taking the 10s ServerRefused back-off — that back-off + // rather than taking the 10s ServerRefused back-off — that back-off // is what left casters standing idle facing away from the fight. case SPELL_FAILED_UNIT_NOT_INFRONT: return Result::Locked; case SPELL_FAILED_INTERRUPTED: return Result::Locked; @@ -1041,6 +1180,24 @@ Result API::cast_spell_on_item(uint32 spell_id, ObjectGuid item_guid) if (!item) return Result::InvalidTarget; SpellCastResult sr = p_->CastSpell(item, spell_id, false); + // A weapon imbue or poison rank has a level floor on the weapon (Spell::CheckCast: the item's required level against the spell's + // base level, SPELL_FAILED_LOWLEVEL). A bot in a low-level weapon was refused the highest rank for ever; fall back to the highest + // lower rank it knows that the weapon takes. + if (sr == SPELL_FAILED_LOWLEVEL) + { + std::vector const ranks = SpellFamily::Ranks(spell_id); + for (auto it = ranks.rbegin(); it != ranks.rend() && sr == SPELL_FAILED_LOWLEVEL; ++it) + { + SpellInfo const* ri = sSpellMgr->GetSpellInfo(*it, p_->GetMap()->GetDifficultyID()); + if (*it == spell_id || !ri || ri->BaseLevel >= info->BaseLevel || !p_->HasSpell(*it)) + continue; + sr = p_->CastSpell(item, *it, false); + if (sr == SPELL_CAST_OK) + TC_LOG_INFO("playerbot.v2", "[imbue_cast] {} spell {} refused (weapon level), cast lower rank {}", p_->GetName(), spell_id, *it); + } + } + if (sr != SPELL_CAST_OK) + TC_LOG_INFO("playerbot.v2", "[imbue_cast] {} spell {} on item {} refused: result {}", p_->GetName(), spell_id, item->GetEntry(), uint32(sr)); switch (sr) { case SPELL_CAST_OK: return Result::Ok; @@ -1067,7 +1224,7 @@ Result API::cast_spell_at_position(uint32 spell_id, float x, float y, float z) return Result::NotKnown; // Gate movement ground-casts (Heroic Leap etc.) on the per-tick pathfinding - // budget — they pathfind synchronously in core like targeted Charge (see + // budget — they pathfind synchronously in core like targeted Charge (see // cast_spell). AoE ground-casts have no movement effect and are never gated. if (!PathBudget::HasBudget(GameTime::GetGameTimeMS()) && (info->HasEffect(SPELL_EFFECT_CHARGE) || info->HasEffect(SPELL_EFFECT_CHARGE_DEST) || @@ -1092,7 +1249,7 @@ Result API::cast_spell_at_position(uint32 spell_id, float x, float y, float z) // prereq (typical bot cases: warlock Create Healthstone refused // because one already exists, Soulstone already up on a target, a // proc-gated spell with no proc active). These persist far longer - // than a GCD — minutes, or until the underlying state cycles. + // than a GCD — minutes, or until the underlying state cycles. // Treat as persistent so the 10s back-off in BotIntentExecutor // kicks in, instead of hammering the rule every 1.5s GCD tick. case SPELL_FAILED_CASTER_AURASTATE: return Result::ServerRefused; @@ -1128,11 +1285,13 @@ bool API::follow_drop_acted() const Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, bool follow_drop) { if (!p_) return Result::Other; + if (p_->IsAlive()) + StandForMove(p_); - // ── VEHICLE DRIVING ── + // ── VEHICLE DRIVING ── // When the bot CONTROLS a vehicle (IoC siege engine / demolisher / glaive // thrower; SoTA/WG engines), it is a SEATED passenger of the vehicle base. - // The player's own MotionMaster can't move it — and worse, a seated bot + // The player's own MotionMaster can't move it — and worse, a seated bot // trips UNIT_STATE_NOT_MOVE / IsMovementPreventedByCasting below and bails // Result::Locked, so the vehicle never drives (live: IoC demolishers mounted // but frozen at the Workshop pad, [move_blocked] idle:bg_vehicle_drive_to_gate, @@ -1192,10 +1351,29 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, } } + // A long ground walk on a mount (idle bots of level 40 and up that know a mount, riding off alone: a city's crowd, a hub walk, a travel leg). + // This is the one funnel every walk goes through, so no single rule needs its own mount step. Short walks stay on foot, a bot in a group + // follows its leader's mount (ingroup rules), and the cast is only tried every 20 s per bot when the server refuses it (indoors, a no-mount area). + if (p_->GetLevel() >= 40 && !p_->IsMounted() && !p_->GetGroup() && !p_->GetBattleground() && p_->IsAlive() && p_->GetMap() && + !p_->GetMap()->Instanceable() && !p_->IsInCombat() && !p_->IsMountRestrictedHere(true) && !p_->IsInWater() && !p_->IsFlying() && !p_->IsInFlight() && + !p_->HasUnitState(UNIT_STATE_NOT_MOVE) && !p_->IsNonMeleeSpellCast(false) && p_->GetSkillValue(SKILL_RIDING) > 0 && + std::hypot(x - p_->GetPositionX(), y - p_->GetPositionY()) > 150.0f) + { + thread_local std::unordered_map s_mountTryMs; + uint32 const nowMs = GameTime::GetGameTimeMS(); + uint32& last = s_mountTryMs[p_->GetGUID().GetCounter()]; + if (last == 0 || nowMs - last >= 20000u) + { + last = nowMs; + if (mount(0) == Result::Ok && !p_->IsMounted()) + return Result::Locked; // the mount cast is under way; the walk is asked for again once it lands + } + } + // Movement-prevented precheck. PointMovementGenerator::Initialize sets // MOVEMENTGENERATOR_FLAG_INTERRUPTED + StopMoving when the unit has // UNIT_STATE_NOT_MOVE (root|stunned|died|distracted) or is mid-cast on - // a non-movable spell — the spline never starts and Result::Ok would + // a non-movable spell — the spline never starts and Result::Ok would // mislead the rule into thinking the bot is walking. Refuse early so // the rule's per-target retry / fallback rules can take over. if (p_->HasUnitState(UNIT_STATE_NOT_MOVE) || @@ -1204,7 +1382,7 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, // Name the refusal. A repeating MoveTo|Locked is indistinguishable in // the intent ring from a pathfinding refusal, and the campaign burned // two Phase-2 candidates (Shadow Labyrinth, SFK) chasing "missing - // geometry" that headless probes then proved COMPLETE — the real + // geometry" that headless probes then proved COMPLETE — the real // cause is one of ~7 unnamed Locked branches. Throttled, one line. static uint32 s_lock_state_ms = 0; const uint32 lk_now = GameTime::GetGameTimeMS(); @@ -1221,7 +1399,7 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, } // Active FlightPath guard. Bot is on a taxi spline (FLIGHT_MOTION_TYPE) - // — issuing MovePoint while in flight queues under, not over, the + // — issuing MovePoint while in flight queues under, not over, the // flight generator and the bot looks "stuck" until landing. Refuse so // the bot logic re-evaluates next snapshot when the taxi arrives. if (p_->GetMotionMaster()->GetCurrentMovementGeneratorType() == @@ -1298,15 +1476,15 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, return Result::Ok; } - // ── DIRECT move: committed traversal-link crossing ("just move, don't - // think"). No pathfinding, no ground snap — the endpoints are human- + // ── DIRECT move: committed traversal-link crossing ("just move, don't + // think"). No pathfinding, no ground snap — the endpoints are human- // verified rows from {SharedDb()}.playerbot_nav_links, and pathfinding // toward the far side of a real navmesh split would NoPath and refuse. // MovePoint with generatePath=false launches a straight walk/jump spline // exactly like a player crossing the split. Distance-capped so a corrupt // row cannot yeet a bot across the map; the same-goal skip below is // intentionally bypassed (the caller-side emit dedup already holds the - // running spline — see BotIntentEmitter::move_to). + // running spline — see BotIntentEmitter::move_to). if (drop) { // A drop off a ledge (WSG graveyard ridge): the bot walked to the ledge point, now it leaves it. A jump move to the landing @@ -1360,7 +1538,7 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, } // Snap target Z to a real walkable surface. Callers (idle:wander, - // idle:travel_to_hub, idle:quest_path …) pass either the bot's + // idle:travel_to_hub, idle:quest_path …) pass either the bot's // current Z or a creature/object anchor Z, neither guaranteed to // sit on the navmesh. SnapToGround applies the same vmap/mmap // composite TC uses in Player::SetPosition, with a fall-through to @@ -1378,9 +1556,15 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, // joined only by steep faces). The ground probe would put the goal on the lower layer and the path would take the bot down the // face, where the town's hubs cannot be reached. The ask is // refused like a blocked path, so the rule picks another bearing. - if (!p_->GetGroup() && !p_->IsInFlight() && !p_->GetTransport() && p_->GetMap() && !p_->GetMap()->IsDungeon() - && !p_->GetMap()->IsBattlegroundOrArena() && ::Playerbot::V2::World::IsVanillaCapitalZone(p_->GetZoneId()) - && ::Playerbot::V2::Fleet::AcrossDrop(p_->GetPositionZ(), z_ask, z) + // Not for a bot in the water: its own z is the canal surface and the ground under its goal the canal floor (Stormwind 86 over 59.5), + // so every step it asked for read as a drop and was refused; idle:leave_water never moved it and the canals filled up (live 244). + // A pit of liquid under a same-level ask (Fleet::IntoLiquidPit: the Great Forge's lava) is refused or kept at the asked level the + // same way, for a grouped bot too: no group follows its leader into the lava. + bool const city_ground = !p_->IsInWater() && !p_->IsInFlight() && !p_->GetTransport() && p_->GetMap() && !p_->GetMap()->IsDungeon() + && !p_->GetMap()->IsBattlegroundOrArena() && ::Playerbot::V2::World::IsVanillaCapitalZone(p_->GetZoneId()); + bool const liquid_pit = city_ground && ::Playerbot::V2::Fleet::IntoLiquidPit(p_->GetPositionZ(), z_ask, z, + p_->GetMap()->GetLiquidStatus(p_->GetPhaseShift(), x, y, z + 0.05f, map_liquidHeaderTypeFlags::AllLiquids, nullptr) != LIQUID_MAP_NO_WATER); + if (city_ground && (liquid_pit || (!p_->GetGroup() && ::Playerbot::V2::Fleet::AcrossDrop(p_->GetPositionZ(), z_ask, z))) && !([&] { // The ground probe sees terrain and static models, the mover walks the navmesh. Where the mesh has a walkable surface at the @@ -1398,12 +1582,15 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, if (gat == 0 || gnow - gat >= 10000u) { gat = gnow ? gnow : 1u; - TC_LOG_INFO("playerbot.v2", "[level_guard] {} refused a same-level move across a drop: z={:.1f} dst=({:.1f},{:.1f}) ground={:.1f}", - p_->GetName(), z_ask, x, y, z); + TC_LOG_INFO("playerbot.v2", "[level_guard] {} refused a same-level move {}: z={:.1f} dst=({:.1f},{:.1f}) ground={:.1f}", + p_->GetName(), liquid_pit ? "into a liquid pit" : "across a drop", z_ask, x, y, z); } NotePathFail(p_, PathDestKey(p_->GetMapId(), x, y), GameTime::GetGameTimeMS()); return Result::Locked; } + // The swimmer's step at its own level stays on the surface, where the navmesh has its water polygons, not on the canal floor. + if (p_->IsInWater() && ::Playerbot::V2::Fleet::AcrossDrop(p_->GetPositionZ(), z_ask, z)) + z = z_ask; BotMovement::SnapToGround(p_, x, y, z); // Battleground start room (STATUS_WAIT_JOIN): the gates are shut and the bots only mill about their start area, so a @@ -1454,7 +1641,7 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, // isMoving() is FALSE even though the route is alive and about to move. The // emitter re-emits move_to every ~1.5s; if the skip required isMoving()==true // it fell through during the init delay, re-ran MovePath, and - // MotionMaster::DirectAdd REPLACED the generator (same ACTIVE/NORMAL slot) — + // MotionMaster::DirectAdd REPLACED the generator (same ACTIVE/NORMAL slot) — // restarting the 1000ms delay and _currentNode=0 every cycle. Net effect: a // bot with a complete far-goal path froze in place forever, each tick // returning Result::Ok (so note_move_succeeded reset the wedge detector and @@ -1462,18 +1649,18 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, // path mmap_probe proved COMPLETE (65 polys). Keying the skip off the live // generator type + goal-key (not the movement flag) lets the spline run to // completion. This also strictly improves the original winding-route fix - // (Grimfang Valley-exit oscillation) — same intent, without the isMoving hole. + // (Grimfang Valley-exit oscillation) — same intent, without the isMoving hole. uint64 const move_goal_key = PathDestKey(p_->GetMapId(), x, y); - // ── TEMP Gap-1 crossing diagnostic (Deadmines map 36 foundry bridge) ── + // ── TEMP Gap-1 crossing diagnostic (Deadmines map 36 foundry bridge) ── // Logs every branch move_to takes while a bot sits in the Gap-1 box, so the // off-mesh crossing is debuggable from the log alone. Remove after the fix. const bool dbg_gap1 = p_->GetMapId() == 36 && p_->GetPositionY() > -560.0f && p_->GetPositionY() < -480.0f && p_->GetPositionX() > -235.0f && p_->GetPositionX() < -200.0f; // Same-goal skip covers BOTH spline kinds: - // * WAYPOINT (long-haul MovePath, below) — original winding-route fix. + // * WAYPOINT (long-haul MovePath, below) — original winding-route fix. // * POINT (MovePoint(generatePath), incl. the BG short-approach + - // off-mesh-bridge case) — re-issuing MovePoint REPLACES the + // off-mesh-bridge case) — re-issuing MovePoint REPLACES the // PointMovementGenerator and RESTARTS its spline from the bot's current // pose every tick. For a path that crosses an OFF-MESH connection (AV // garrison bridge, cave/den bridges) the off-mesh "hop" is a few points @@ -1484,10 +1671,10 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, // POINT spline run to completion lets the off-mesh hop fire. The 5y // PathDestKey bucket means a captain wandering <5y holds the skip (no // restart) while a real >5y move / a rule redirect changes the key and - // re-issues immediately. Reverts to IDLE on arrival → re-evaluated next - // tick. (Keyed off generator type + goal, NOT isMoving — see the init-gap + // re-issues immediately. Reverts to IDLE on arrival → re-evaluated next + // tick. (Keyed off generator type + goal, NOT isMoving — see the init-gap // note below.) - // POINT dedup scoped to battlegrounds AND dungeon/raid instances — both are + // POINT dedup scoped to battlegrounds AND dungeon/raid instances — both are // verified off-mesh-approach cases (BG captain-garrison / cave-den bridges, and // the Deadmines foundry Gap-1 bridge). In a dungeon a per-tick re-emit was // restarting the in-flight off-mesh hop from the bot's mid-gap pose, dropping it @@ -1522,27 +1709,34 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, (uint32)(now_probe - pr.ms), (int)mtype); if (pr.key != move_goal_key) { - // New goal for the probe — start the progress clock here. + // New goal for the probe — start the progress clock here. pr = { move_goal_key, p_->GetPositionX(), p_->GetPositionY(), now_probe }; return Result::Ok; } if (pdx * pdx + pdy * pdy >= 4.0f * 4.0f) { - // Advanced >=4y since the mark — progressing, refresh + keep running. + // Advanced >=4y since the mark — progressing, refresh + keep running. pr.x = p_->GetPositionX(); pr.y = p_->GetPositionY(); pr.ms = now_probe; return Result::Ok; } if (now_probe - pr.ms < 3000u) - return Result::Ok; // within grace — let the spline keep trying + return Result::Ok; // within grace — let the spline keep trying // Stalled >3s within 4y: reset the clock and FALL THROUGH to re-issue. pr.x = p_->GetPositionX(); pr.y = p_->GetPositionY(); pr.ms = now_probe; } } // Record the goal we're (re)computing toward, so the next same-goal emit while // the resulting WAYPOINT spline is still running is skipped above. Harmless - // for MovePoint/Locked outcomes — the WAYPOINT-type check gates the skip. + // for MovePoint/Locked outcomes — the WAYPOINT-type check gates the skip. g_movePathGoal[p_->GetGUID().GetCounter()] = move_goal_key; + // A request the pathfinding budget defers is not a bot that will not move: the window of this world tick is spent and the request + // is made again next tick. Before this check it went on to the guard below, which counted the wait as time without moving and + // after 32 s dropped the goal as unreachable, for 60 s. The bots at the end of the registry order are the ones a spent window + // refuses (Coldridge: new bots at login asked for a hub 360 y away, stood for minutes, then dropped it). + if (!PathBudget::HasBudget(GameTime::GetGameTimeMS())) + return Result::Locked; + // A goal asked for over and over while the bot does not move is dropped (NoMotionGuard): the destination is suppressed like a // failed path, so the rules above pick another goal. World bots only (grouped bots, battlegrounds and instances have their own // hold-position logic), and only while the goal is still a good way off. @@ -1554,10 +1748,14 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, p_->GetPositionX(), p_->GetPositionY(), GameTime::GetGameTimeMS())) { TC_LOG_INFO("playerbot.v2", "[move_abandon] {} asked for ({:.0f},{:.0f},{:.0f}) for over 30 s without moving; goal dropped " - "(at {:.0f},{:.0f},{:.0f} motion={} casting={} sitting={} rooted={} stunned={} combat={} path_fail_recent={})", + "(at {:.0f},{:.0f},{:.0f} motion={} casting={} sitting={} rooted={} stunned={} combat={} path_fail_recent={} ghost={} teleporting={} " + "spline_set={} spline_done={} spline_t={}/{} ms flags=0x{:x} falling={})", p_->GetName(), x, y, z, p_->GetPositionX(), p_->GetPositionY(), p_->GetPositionZ(), int(p_->GetMotionMaster()->GetCurrentMovementGeneratorType()), p_->HasUnitState(UNIT_STATE_CASTING), p_->GetStandState() != UNIT_STAND_STATE_STAND, p_->HasUnitState(UNIT_STATE_ROOT), - p_->HasUnitState(UNIT_STATE_STUNNED), p_->IsInCombat(), PathFailedRecently(p_, PathDestKey(p_->GetMapId(), x, y), GameTime::GetGameTimeMS())); + p_->HasUnitState(UNIT_STATE_STUNNED), p_->IsInCombat(), PathFailedRecently(p_, PathDestKey(p_->GetMapId(), x, y), GameTime::GetGameTimeMS()), + p_->HasAuraType(SPELL_AURA_GHOST), p_->IsBeingTeleported(), + p_->movespline->Initialized(), p_->movespline->Finalized(), p_->movespline->timePassed(), p_->movespline->Duration(), + uint32(p_->GetUnitMovementFlags()), p_->IsFalling()); NotePathFail(p_, PathDestKey(p_->GetMapId(), x, y), GameTime::GetGameTimeMS(), kPathFailTtlLongMs); return Result::Locked; } @@ -1596,7 +1794,7 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, } // Per-world-tick pathfinding budget. Once this tick's bot-pathfinding window - // is spent (set by DrainIntents), DEFER this move — return Result::Locked so + // is spent (set by DrainIntents), DEFER this move — return Result::Locked so // the rule retries next tick. Bounds the aggregate Detour load per world tick // so a quest-funnel surge cannot flood the world thread and hang it // (2026-06-17). Placed after the cheap prechecks + per-dest backoff, before @@ -1606,19 +1804,19 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, // Path validation gate. TC's PointMovementGenerator silently falls back // to a straight-line spline when Detour returns PATHFIND_NOPATH / - // PATHFIND_FARFROMPOLY_START — that's the root cause of "bot walks + // PATHFIND_FARFROMPOLY_START — that's the root cause of "bot walks // into walls / stairs / off cliffs" reports. We build the same path // PointMovementGenerator would build and inspect the result before // committing to the move: - // * NOPATH → refuse; rule retries another target - // * FARFROMPOLY_START → NearTeleport onto nearest mesh poly + // * NOPATH → refuse; rule retries another target + // * FARFROMPOLY_START → NearTeleport onto nearest mesh poly // first, then proceed (the next emit // after the snap will succeed) - // * FARFROMPOLY_END → refuse; the destination is off-mesh + // * FARFROMPOLY_END → refuse; the destination is off-mesh // (cliff edge / inside geometry / etc) - // * SHORT / INCOMPLETE → walk the partial path; rule re-fires + // * SHORT / INCOMPLETE → walk the partial path; rule re-fires // next tick to extend - // * NORMAL / SHORTCUT → proceed (SHORTCUT is intentional for + // * NORMAL / SHORTCUT → proceed (SHORTCUT is intentional for // swimming / falling cases) PathGenerator path(p_); // Road-aware per-pathfind opt-out heuristic. Disable road bias for @@ -1630,7 +1828,7 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, // Threshold: 25y. Anything shorter is treated as tactical; longer // is treated as travel where road preference helps. // - // Also disable for bots already in combat — even long retreats / + // Also disable for bots already in combat — even long retreats / // kiting / reposition steps shouldn't detour for roads. { float dx = p_->GetPositionX() - x; @@ -1643,17 +1841,17 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, // Defensive SEH wrap around CalculatePath. Detour's dtNavMeshQuery // can ACCESS_VIOLATION when a navmesh tile gets unloaded mid-query // (e.g., grid stream-out during the path build). Crash 2026-05-13 - // 06:44 hit getPathToNode+80 with RAX=0 — null poly deref. We can't + // 06:44 hit getPathToNode+80 with RAX=0 — null poly deref. We can't // catch AV via try/catch under /EHsc; SEH is the only option. The // helper lives outside this scope so no objects with destructors // straddle the __try (PathGenerator's destructor lands after this). bool path_ok = SehSafeCalculatePath(path, x, y, z); PathType pt = path.GetPathType(); - // Outcome enum mirrors PerfCounters::PathOutcome — order: + // Outcome enum mirrors PerfCounters::PathOutcome — order: // 0=Ok, 1=NoPath, 2=FarFromPolyStart, 3=FarFromPolyEnd, 4=Incomplete, 5=Short. // Per-failure diagnostic. We already counter-aggregate via // OnPathOutcome, but the aggregate doesn't tell us WHERE the bot - // was when the path failed — needed to diagnose water/swim + // was when the path failed — needed to diagnose water/swim // pathing without manually positioning a bot. Logs bot name, // current position, target position, water flag at both ends, // and the outcome. Only fires on FAILURE outcomes so the success @@ -1663,7 +1861,7 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, Map* mm = p_->GetMap(); bool src_water = false; // Classify the destination through the shared water gate so the - // diagnostic shows WADE / SWIM / HAZARD, not just a water bool — + // diagnostic shows WADE / SWIM / HAZARD, not just a water bool — // this is what distinguishes "pier path failed over shallow water // (data/navmesh problem)" from "destination is genuinely in deep // water (correctly refused)". Same per-point + depth model the gate @@ -1685,7 +1883,7 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, } // Endpoint-resolution introspection: query the SAME navmesh the // server uses to see whether src/dst polys resolve and whether - // their tiles are loaded — distinguishes "tile not loaded" from + // their tiles are loaded — distinguishes "tile not loaded" from // "poly out of vertical extents" from "filter excluded". char ep_diag[128] = ""; if (Map* mdiag = p_->GetMap()) @@ -1701,11 +1899,11 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, float ext[3] = {3.0f, 5.0f, 3.0f}; // SEH-guarded probes (SehSafeNearestPolyProbe): the raw // findNearestPoly here crashed the world thread twice in - // minutes on 2026-06-12 (boot-time mass logins → max - // path-fail rate → probe hit a tile mid-load; full WER + // minutes on 2026-06-12 (boot-time mass logins → max + // path-fail rate → probe hit a tile mid-load; full WER // dumps show dtVlerp/closestPointOnDetailEdges reading // bad detail data). Same hazard CalculatePath learned on - // 2026-05-13 — the diag block shipped without the guard. + // 2026-05-13 — the diag block shipped without the guard. auto test = [&](float tx, float ty, float tz) -> int { float pt[3] = {ty, tz, tx}; // TC->Detour (y,z,x) @@ -1740,7 +1938,7 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, // Dest-Z mesh-snap RETRY. Stepped/projected waypoints carry the // BOT's z; when the true surface lies far below or above (a step // bearing crossing a river gorge under a bluff, an elevated - // anchor over ground), findNearestPoly's ±5y vertical extents + // anchor over ground), findNearestPoly's ±5y vertical extents // miss every poly and CalculatePath returns NOPATH even though // the mesh connects (proven with mmap_probe on Somi's Razor Hill // wedge: the exact failing pairs return PARTIAL once the dest z @@ -1751,8 +1949,20 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, // Orgrimmar street targets snapped to roof height). if (Map* mm0 = p_->GetMap()) { - const float gz = mm0->GetHeight(p_->GetPhaseShift(), x, y, - z + 50.0f, true, 120.0f); + // The surface nearest the asked z, not the first one under z + 50: a target on a balcony under a higher + // floor (SFK 2026-10-20: the tank at z 86.5, the floor above at 99.9) snapped to that upper floor, the + // retry built a 73-poly path toward the wrong floor and the healer below never got the genuine NOPATH + // its rules act on. Walk down through the stacked surfaces while they get closer to z. + float gz = mm0->GetHeight(p_->GetPhaseShift(), x, y, + z + 50.0f, true, 120.0f); + for (int layer = 0; layer < 4 && gz > INVALID_HEIGHT && gz > z + 8.0f; ++layer) + { + const float below = mm0->GetHeight(p_->GetPhaseShift(), x, y, gz - 0.5f, true, + (gz - 0.5f) - (z - 70.0f)); + if (below <= INVALID_HEIGHT || below >= gz - 0.5f || std::fabs(below - z) >= std::fabs(gz - z)) + break; + gz = below; + } if (gz > INVALID_HEIGHT && std::fabs(gz - z) > 8.0f) { // Re-run on the SAME PathGenerator (repeated CalculatePath @@ -1768,7 +1978,7 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, // Midpoint-bisection rescue. NOPATH|SHORTCUT with BOTH // endpoint polys resolvable (Somi's UC lobby walk: a clean // 71-poly corridor that the standalone probe routes, but the - // live BuildPointPath collapses on — core findStraightPath + // live BuildPointPath collapses on — core findStraightPath // edge case). Halving the request converges past whatever // segment poisons the long call; the rule re-fires next tick // from the midpoint and bisects again if needed. @@ -1793,8 +2003,8 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, // FARFROMPOLY_END even though the corridor built // perfectly (observed: 71-point path to z-42.5 // refused because the request said z2.5). Walk to - // the path's ACTUAL reachable end — that's the - // progress we wanted — and clear the far-end bit. + // the path's ACTUAL reachable end — that's the + // progress we wanted — and clear the far-end bit. G3D::Vector3 const& bend = path.GetActualEndPosition(); x = bend.x; y = bend.y; z = bend.z; pt = PathType(pt & ~PATHFIND_FARFROMPOLY_END); @@ -1809,21 +2019,21 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, // Water-stuck EXIT recovery. A bot that swam / fell into a canal, lake or // harbour can sit on a liquid poly cluster the navmesh won't route OUT of // toward a dry goal (Detour NoPath) even though a DESIGNED exit (bank - // steps / ramp) is only yards away — observed: Tindle wedged in the + // steps / ramp) is only yards away — observed: Tindle wedged in the // Stormwind canal for HOURS while a valid 11-leg travel route to its quest // existed, unreachable solely because it could not leave the water. // Crawling straight at the far goal is WRONG (it scales the canal WALL); // the canal HAS exits, so navigate to the nearest one. NearestNavPoint's // filter is GROUND|GROUND_STEEP|ROAD and EXCLUDES water, so it returns the - // nearest DRY footing — the real bank/stairs exit — within the search box. + // nearest DRY footing — the real bank/stairs exit — within the search box. // Swim STRAIGHT there (generatePath=false: the span to the nearest bank is // open water, no obstacle); once on dry mesh the next emit pathfinds to the // goal normally. Only fires while actually in water (a legitimate swim has // path_ok=true, not NoPath), and the 60y extent bounds it to a local exit, // never long-haul routing. // Liquid at the bot's CURRENT spot. Use Map::GetLiquidStatus (ANY liquid - // present, any depth) — the SAME check that sets the [path_fail] "WATER" - // flag — NOT p_->IsInWater() (false unless submerged) and NOT + // present, any depth) — the SAME check that sets the [path_fail] "WATER" + // flag — NOT p_->IsInWater() (false unless submerged) and NOT // ClassifyDestinationLiquid at the bot's feet (returns Dry when the bot // stands on the canal BOTTOM with no liquid above its own z). The bot is // plainly in the canal but those two report false, which is why the exit @@ -1843,7 +2053,7 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, const float exdz = navpt ? exit_pt.GetPositionZ() - p_->GetPositionZ() : 0.f; const float exd2 = exdx * exdx + exdy * exdy + exdz * exdz; // DIAG (throttled 5s/bot): the [water_exit] recovery never logged across - // builds — show which gate fails (liquid? navpoint? distance?). + // builds — show which gate fails (liquid? navpoint? distance?). { static std::unordered_map s_weAt; uint32& weat = s_weAt[p_->GetGUID().GetCounter()]; @@ -1881,7 +2091,7 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, return Result::Ok; } } - // Navmesh has no route — but the .map heightfield may still have + // Navmesh has no route — but the .map heightfield may still have // walkable ground here (a gen-time hole under tree canopy / on a // walkway). Try a guarded terrain-skim across a short, near-level gap // before giving up. Fixes e.g. the Teldrassil holes that trap Night @@ -1903,6 +2113,16 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, NoteReachFail(p_, x, y, GameTime::GetGameTimeMS()); return Result::Locked; } + // A wet route is refused here as well as at the liquid gate below: the partial and far-end branches in between drive the route they + // got without reaching that gate. + if (BotMovement::g_LiquidPathPolicy && path.IsWetRoute() + && BotMovement::DecideLiquid(BotMovement::g_LiquidPathPolicy(p_), /*path_wet*/ true, /*dry_found*/ false) == BotMovement::LiquidAction::Refuse) + { + Playerbot::V2::Module::instance().OnPathOutcome(3 /*FarFromPolyEnd*/); + log_path_fail("Liquid"); + NotePathFail(p_, PathDestKey(p_->GetMapId(), x, y), GameTime::GetGameTimeMS()); + return Result::Locked; + } // Retry at the polygon found, for a destination that lies just off the mesh. A chunk step is aimed at a point on the bot's own level a // stride ahead, so it often lands a few yards off a road, on a slope above or below it, or on another level of the same x,y. Detour then // builds the corridor to the nearest polygon and flags the end as far from its polygon (6298 of these in; 1271 @@ -1918,7 +2138,11 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, // In a capital the layers lie 20 to 40 y apart (Stormwind): a polygon that far from the asked height is another level, not a // slope (Hellice, on a roof at z 148.6, was snapped to a polygon 20 to 35 y below it). float const max_dz = ::Playerbot::V2::World::IsVanillaCapitalZone(p_->GetZoneId()) ? ::Playerbot::V2::Fleet::kCityDropYards : 60.0f; - if (off_end <= 12.0f && std::fabs(dz_end) < max_dz && !::Playerbot::V2::Fleet::PathHasCliff(path.GetPath())) + // A polygon in magma or slime is no place to walk to: the liquid gate below refuses it, and the refusal is only the short 3 s + // one, so the goal was picked again and again (Burning Steppes, Simer: 53 path_fail Magma for one quest goal in 3 minutes). + // Left unsnapped, the goal ends as FarFromPolyEnd, which suppresses it for long and lets goal selection move on. + bool const end_in_hazard = BotMovement::ClassifyDestinationLiquid(p_, ae.x, ae.y, ae.z) == BotMovement::LiquidVerdict::Hazard; + if (off_end <= 12.0f && std::fabs(dz_end) < max_dz && !end_in_hazard && !::Playerbot::V2::Fleet::PathHasCliff(path.GetPath())) { if (SehSafeCalculatePath(path, ae.x, ae.y, ae.z) && !(path.GetPathType() & (PATHFIND_NOPATH | PATHFIND_FARFROMPOLY_END))) { @@ -1951,7 +2175,7 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, log_path_fail("FarFromPolyEnd"); BotMovement::NoteNoPath(p_); // Off-mesh destination (above terrain / inside geometry / a phantom POI - // Z). Permanently unreachable until the data changes — suppress long so + // Z). Permanently unreachable until the data changes — suppress long so // the bot stops oscillating toward it and goal-selection moves on. NotePathFail(p_, PathDestKey(p_->GetMapId(), x, y), GameTime::GetGameTimeMS(), kPathFailTtlLongMs); @@ -1967,7 +2191,7 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, // Bot is off-mesh at the source (standing on an unmeshed WMO platform, // just teleported into geometry, fell off a ledge, login spawn into a // wall). Prefer WALKING off it: if there's continuous walkable VMAP - // ground toward the target, crawl that way (no start poly needed — the + // ground toward the target, crawl that way (no start poly needed — the // skim uses GetHeight, not Detour) and let a later emit re-pathfind once // back on mesh. Only when no walkable line exists do we resort to the // teleport-snap below. This honours no-teleport-rescue: move under the @@ -1976,13 +2200,13 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, return Result::Ok; // Snap to the nearest valid poly so the next move_to emit can pathfind // from a real mesh point. Use the path's actual end position as a heuristic - // for "where Detour wishes the source had been" — this is the + // for "where Detour wishes the source had been" — this is the // closest poly Detour found from the bot's current XY. G3D::Vector3 const& near_poly = path.GetActualEndPosition(); // XY bound on the snap: it exists to NUDGE the bot onto an adjacent // poly (unmeshed platform lip, login-into-wall), not to RELOCATE it. // When the whole local area is unmeshed, Detour's "closest poly" can - // be enormously far — observed 2026-06-12 Deephaul Ravine: bot + // be enormously far — observed 2026-06-12 Deephaul Ravine: bot // spawned in the (unmeshed) elevated start area got snapped 1.2K // yards outside the arena and wedged there for the whole match // (133 NoPath re-paths from one spot). Beyond the bound, refuse: @@ -2008,7 +2232,7 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, // 20y Z-delta canary (rejects cave-roof / stratum-skip teleports // that the raw Player::NearTeleportTo doesn't guard against). // If the snap-target Z is on a different stratum than the bot's - // current Z, SafeNearTeleport refuses — return Locked so the + // current Z, SafeNearTeleport refuses — return Locked so the // rule can try a different target, otherwise we'd loop forever // on the same off-mesh source with the same refused snap. const bool snap_ok = BotMovement::SafeNearTeleport( @@ -2016,7 +2240,7 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, Playerbot::V2::Module::instance().OnPathOutcome(2 /*FarFromPolyStart*/); if (!snap_ok) { - // Stamp the destination as failed too — the SOURCE is off-mesh + // Stamp the destination as failed too — the SOURCE is off-mesh // for THIS target's pathfind. Different XY destinations may // still resolve from the same source, so the LRU's per-bucket // expiry lets the rule explore other directions. @@ -2032,15 +2256,15 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, // Partial / truncated paths: Detour could not reach the requested // destination and returned the closest reachable endpoint instead. // Two very different situations share this flag: - // (a) ADVANCING partial — a legitimate long-haul / chunked route + // (a) ADVANCING partial — a legitimate long-haul / chunked route // whose reachable endpoint is meaningfully closer to the goal. // Walk it; the next emit picks up from the new pose and extends. - // (b) NON-ADVANCING partial — the reachable endpoint sits ~at the + // (b) NON-ADVANCING partial — the reachable endpoint sits ~at the // bot (target on a disconnected nav island, a kill mob just past // a closable gap, a poly the A* budget couldn't bridge). Issuing // the MovePoint and returning Ok makes BotIntentExecutor call - // note_move_succeeded() every tick → path_blocked_count_ resets - // → check_anchor_wedge and the wander angle-salt never engage, + // note_move_succeeded() every tick → path_blocked_count_ resets + // → check_anchor_wedge and the wander angle-salt never engage, // and the LRU never suppresses the doomed dst. The bot walks the // short stub, stops, re-emits the SAME dst, and oscillates // forever (project_movement_recovery / wedge reports). @@ -2058,12 +2282,12 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, // A bot stranded on an elevated, OVERHANGING battleground platform (EotS) // is navmesh-disconnected from the arena floor: Detour returns an // Incomplete partial (sometimes "advancing" 200y, sometimes non-advancing) - // but the bot can't actually leave the platform — the drop to the field + // but the bot can't actually leave the platform — the drop to the field // isn't walkable. Handle it FIRST, before the advancing/non-advancing // split, so neither the MovePath-the-partial path (which stalls on the // rim) nor the local-minimum escape starves it. Relocate the bot onto the // field navmesh just in front of its platform (toward the objective, at - // field height — the elevator-disembark pattern); normal routing then + // field height — the elevator-disembark pattern); normal routing then // resumes from solid ground. Tight gate (objective >=18y BELOW the bot) // so it fires ONLY for a genuine platform descent, never for normal // near-level field movement, and BG-only / downward-only so it can never @@ -2073,7 +2297,7 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, return Result::Ok; // Minimum meaningful gain. Below this the partial is effectively a - // no-op (endpoint at, or no closer to — possibly farther from — the + // no-op (endpoint at, or no closer to — possibly farther from — the // goal). 5y is one SnapToGround bucket of slop; a genuine long route // chunk advances far more than this per emit. constexpr float kMinForwardProgressYards = 5.0f; @@ -2105,12 +2329,12 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, { // FINAL-APPROACH exception (2026-06-18): when the REACHABLE endpoint // already lands within NPC interaction range of the requested dst, the - // dst is simply a few yards OFF the navmesh — a quest giver / object / + // dst is simply a few yards OFF the navmesh — a quest giver / object / // POI whose exact point doesn't snap to a walkable poly. Parking here // freezes the bot ~3-12y short of its goal FOREVER, which the live logs // show is the single biggest fleet wedge: Norenen frozen cur_to_dst=5.0 // with the endpoint 3.3y from dst; Lorashel 12.3/11.7; Bemardel - // 10.0/9.6 — all stuck just outside an interactable they could reach. + // 10.0/9.6 — all stuck just outside an interactable they could reach. // Take the short final hop to the endpoint: it puts the bot within // interaction range so the quest/vendor/loot/gossip logic completes, // then the bot stops re-pathing. Bounded to end_to_dst <= 6y (the @@ -2130,7 +2354,7 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, } // Water-stuck EXIT recovery (same as the NoPath branch). A bot in a // canal / harbour whose objective sits on a navmesh-DISCONNECTED dry - // island (a dock / pier a few yards UP — e.g. the Stormwind harbour + // island (a dock / pier a few yards UP — e.g. the Stormwind harbour // Hired Courier at z=6.2 over Tindle at the water surface z=0) reports // a non-advancing partial here (forward_progress~0, end_to_dst just // over the 6y final-approach cap), NOT NoPath, so the recovery above @@ -2155,7 +2379,7 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, const float nexdx = nexit.GetPositionX() - p_->GetPositionX(); const float nexdy = nexit.GetPositionY() - p_->GetPositionY(); const float nexdz = nexit.GetPositionZ() - p_->GetPositionZ(); - // 3D (incl. vertical) — the dock/pier exit can be almost + // 3D (incl. vertical) — the dock/pier exit can be almost // straight up (small XY, large Z); XY-only rejected it. if (nexdx * nexdx + nexdy * nexdy + nexdz * nexdz > 3.0f * 3.0f) { @@ -2174,13 +2398,13 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, } } // NOTE (2026-06-09): a crawl-on-Incomplete fallback was tried here but - // ROLLED BACK — combined with the ramp-climb gate it shoved bots up onto + // ROLLED BACK — combined with the ramp-climb gate it shoved bots up onto // elevator platforms they couldn't then step off (Pyrethel/Gorois stranded // riding Org lift 206610). The proper elevator traversal is being designed // separately (travel-graph-defined post-platform step). See // docs/ELEVATOR_TRAVEL_HANDOVER_20260609.md. // - // Non-advancing partial — treat exactly like NoPath: stamp the + // Non-advancing partial — treat exactly like NoPath: stamp the // LRU, do NOT issue the doomed MovePoint, and return Locked so // BotIntentExecutor increments path_blocked_count_, logs // [move_blocked], and does NOT call note_move_succeeded(). That lets @@ -2188,7 +2412,7 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, // // TTL is distance-aware. The 60s long TTL is right for a NEARBY // disconnected target (an island / unbridgeable poly the bot is - // standing next to — geometry-stable, don't re-probe). But for a FAR + // standing next to — geometry-stable, don't re-probe). But for a FAR // goal the bot is mid CHUNKED long-haul: it momentarily reads // non-advancing at THIS pose (budget truncation, a tile not yet // loaded, a poly seam) yet the route genuinely extends further (e.g. @@ -2199,24 +2423,24 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, // retries within a tick or two and continues; keep the long TTL only // for a genuinely local disconnected target. // LOCAL-MINIMUM ESCAPE (2026-06-20). Before refusing, try to FOLLOW - // the partial to crawl OUT of a confined/winding spot — the only fix + // the partial to crawl OUT of a confined/winding spot — the only fix // for a bot whose route to a far goal must wind away-then-back past // the 74-poly cap (live: Durnan frozen 154 blocks indoors; walking the - // −47y partial to (-4986,-954) unlocks a +372y advancing path from + // −47y partial to (-4986,-954) unlocks a +372y advancing path from // there). Strictly gated so it can NOT re-introduce the rolled-back // crawl's elevator/ramp stranding or thrash a true dead-end: - // * far goal mid-haul (cur_to_dst > 100y) — not a local disconnected + // * far goal mid-haul (cur_to_dst > 100y) — not a local disconnected // target (those keep the long-TTL refuse below); - // * a real escape leg (endpoint >= 15y away) — not sub-step jitter; - // * NOT climbing (endpoint z <= pose z + 8y) — a downward/level + // * a real escape leg (endpoint >= 15y away) — not sub-step jitter; + // * NOT climbing (endpoint z <= pose z + 8y) — a downward/level // escape can't strand the bot riding a lift UP (the documented // 2026-06-09 rollback failure mode); // * pts >= 2 so MovePath feeds real waypoints (no MotionMaster // re-pathfind that degenerates to a same-poly zero-move); // * anti-oscillation budget per (bot,goal): a true tiny pocket - // ping-pongs without ever closing in → after kMaxEscapeCrawls + // ping-pongs without ever closing in → after kMaxEscapeCrawls // it falls through to the refuse and the wedge machinery engages. - // No extra pathfind — MovePath drives the ALREADY-COMPUTED partial, + // No extra pathfind — MovePath drives the ALREADY-COMPUTED partial, // so this adds zero world-thread CalculatePath cost. { auto const& esc_pts = path.GetPath(); @@ -2242,9 +2466,7 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, escPath.BuildSegments(); if (p_->IsWalking() == run) p_->SetWalk(!run); - p_->GetMotionMaster()->MovePath(escPath, /*repeatable*/ false, {}, {}, - run ? MovementWalkRunSpeedSelectionMode::ForceRun - : MovementWalkRunSpeedSelectionMode::ForceWalk); + MoveAlongRoute(p_, escPath, run, /*navmesh_points*/ true); TC_LOG_INFO("playerbot.v2", "[path_escape] {} crawl {}/{} out of local minimum: leg={:.0f}y " "endpoint=({:.0f},{:.0f},{:.0f}) cur_to_dst={:.0f}", @@ -2252,14 +2474,14 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, path_end.x, path_end.y, path_end.z, cur_to_dst); return Result::Ok; } - // Budget exhausted — a genuine pocket / oscillation; fall through. + // Budget exhausted — a genuine pocket / oscillation; fall through. } } // BG boss-approach CRAWL (2026-06-23). A CLOSE goal (cur_to_dst < // 80y) reading non-advancing is typically an objective just OFF/below // the navmesh: the AV enemy captain (Galvangar/Balinda) and general // (Drek'Thar/Vanndar) stand inside a walled garrison/keep whose floor - // is not meshed — the nearest poly sits ~35y ABOVE the spawn, so the + // is not meshed — the nearest poly sits ~35y ABOVE the spawn, so the // navmesh path dead-ends ~47y out and the whole push squad freezes // there and never lands a hit (live: min_gd pinned at 47y for 10min, // 0 casts landed, captain untouched). Crawl the remaining gap across @@ -2279,7 +2501,7 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, NoteReachFail(p_, x, y, GameTime::GetGameTimeMS()); return Result::Locked; } - // Advancing partial — drive to the REACHABLE endpoint Detour found, NOT + // Advancing partial — drive to the REACHABLE endpoint Detour found, NOT // the far requested dst. Re-issuing MovePoint(far dst, generatePath) can // leave the bot FROZEN: when the dst's navmesh tile isn't loaded (e.g. a // 676y cross-zone quest goal), the MotionMaster's OWN path resolves the @@ -2287,24 +2509,24 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, // (live: Gorthak wedged 9min at the Valley of Trials exit on quest 25133 // "Report to Sen'jin Village", srcpoly==dstpoly, forward_progress=254y but // never a step taken). The API already computed the reachable endpoint; - // MovePoint to THAT — it sits on a loaded poly so the MotionMaster paths + // MovePoint to THAT — it sits on a loaded poly so the MotionMaster paths // cleanly and the bot actually moves. The next emit re-paths from the // advanced pose and extends toward the goal, pulling in the next navmesh - // tile as the bot crosses the boundary — proper chunked long-haul. This - // is the documented "advancing partial — walk it" behavior, made real. + // tile as the bot crosses the boundary — proper chunked long-haul. This + // is the documented "advancing partial — walk it" behavior, made real. { // Drive the API's ALREADY-COMPUTED path points via MovePath rather than // MovePoint(actual_end, generatePath=true). MovePoint makes the // MotionMaster RE-pathfind to the endpoint, and on a truncated long-haul // (pts hit the cap) that endpoint sits on a poly/tile seam where the MM's - // own pathfind degenerates to a same-poly route and emits ZERO movement — + // own pathfind degenerates to a same-poly route and emits ZERO movement — // the bot freezes mid-route despite a 230y advancing partial (live: // Gorthak/Grimfang frozen at the Valley of Trials exit on Q25133 // "Report to Sen'jin", Incomplete forward_progress=230y, never a step). // MovePath feeds the validated smooth points straight to the waypoint // generator (which still navmesh-paths the short hops BETWEEN adjacent // points), so the bot actually walks the chunk; the next emit re-paths - // from the advanced pose and extends — proper chunked long-haul. Same + // from the advanced pose and extends — proper chunked long-haul. Same // mechanism the road-centerline branch above already uses successfully. auto const& pts = path.GetPath(); if (!Playerbot::BotMovement::AllowPartialRoute(g_route_stall[p_->GetGUID().GetCounter()], @@ -2338,12 +2560,10 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, if (p_->IsWalking() == run) p_->SetWalk(!run); - p_->GetMotionMaster()->MovePath(advPath, /*repeatable*/ false, {}, {}, - run ? MovementWalkRunSpeedSelectionMode::ForceRun - : MovementWalkRunSpeedSelectionMode::ForceWalk); + MoveAlongRoute(p_, advPath, run, /*navmesh_points*/ true); return Result::Ok; } - // Degenerate path (single point) — fall back to the endpoint MovePoint. + // Degenerate path (single point) — fall back to the endpoint MovePoint. G3D::Vector3 const& adv_end = path.GetActualEndPosition(); if (p_->IsWalking() == run) p_->SetWalk(!run); @@ -2363,9 +2583,9 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, // re-path to the MIDPOINT (mirrors the NoPath bisection above) so the // shorter corridor fits the cap and yields a REAL navmesh route; we then // MovePath to that reachable end and re-path from the advanced pose next - // emit — proper chunked long-haul. Only for a far goal (a near SHORT span + // emit — proper chunked long-haul. Only for a far goal (a near SHORT span // is open ground and fine to cross straight). One extra CalculatePath, and - // only on SHORT (rare) — within the already-checked per-tick path budget. + // only on SHORT (rare) — within the already-checked per-tick path budget. if (Map* mmS = p_->GetMap()) { const float sdx = x - p_->GetPositionX(); @@ -2411,16 +2631,16 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, } // Liquid safety gate. Classifies the destination POINT (not the tile/chunk - // — a chunk is routinely half-water / half-dry) through the shared + // — a chunk is routinely half-water / half-dry) through the shared // BotMovement water gate, which probes Map::GetLiquidStatus at (x,y,z) with // the bot's REAL collision height (floored at DEFAULT_COLLISION_HEIGHT). // Two refuse cases, both conservative: - // * Hazard (magma / slime) — bot burns to death on contact. - // * Swim (fully submerged for THIS bot) — a non-aquatic bot drowns and + // * Hazard (magma / slime) — bot burns to death on contact. + // * Swim (fully submerged for THIS bot) — a non-aquatic bot drowns and // the navmesh ends at the surface, so no walkable path exists below. // // Wadeable depth is ALLOWED for all bots. Shoreline hubs (Ratchet, Booty - // Bay, Echo Isles' Den, etc.) sit half-in-water — a bot approaching along a + // Bay, Echo Isles' Den, etc.) sit half-in-water — a bot approaching along a // curved shore momentarily clips the surface; blocking that caused wander // to oscillate and starter-zone bots to make zero progress. The collision- // height floor guarantees this gate is never more restrictive than the @@ -2435,11 +2655,11 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, BotMovement::LiquidVerdict const lv = BotMovement::ClassifyDestinationLiquid(p_, x, y, z); - // Hazard (magma / slime) is always refused — the bot burns to death + // Hazard (magma / slime) is always refused — the bot burns to death // on contact regardless of distance or breath. if (lv == BotMovement::LiquidVerdict::Hazard) { - // Treat as unreachable — wander angle hash picks a different + // Treat as unreachable — wander angle hash picks a different // direction next emit. Stamp the LRU so a wander loop that hashes // the same 5y bucket doesn't re-pay the full Detour + liquid probe // every tick; hazard polygons are terrain-stable so the 3s TTL is @@ -2464,7 +2684,7 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, } // Swim (destination submerges this bot) used to be refused outright, - // which meant bots could never cross ANY water — a pond, a stream, a + // which meant bots could never cross ANY water — a pond, a stream, a // shallow lagoon between two quest hubs all read as Swim at the far // bank and the move was rejected. Real players swim short stretches; // they just don't path across oceans. So: PERMIT a short swim that @@ -2477,7 +2697,7 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, // bot can breathe underwater indefinitely (water-breathing aura, GM // breath-disable, or dead/ghost). We assume full breath here because // the bot is at the START of the crossing (move_to is the entry to a - // swim, not a mid-swim re-emit) — a conservative assumption that only + // swim, not a mid-swim re-emit) — a conservative assumption that only // becomes MORE permissive when the bot actually still has full air. // // Budget: require the estimated swim duration to stay under a fraction @@ -2493,7 +2713,7 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, constexpr float kBreathSafety = 0.5f; // Hard span cap independent of breath, so an indefinite-breather // (water-walking / aquatic mount) still can't be routed straight - // across an ocean by this gate — long-haul water travel belongs to + // across an ocean by this gate — long-haul water travel belongs to // the higher routing layer, not a single MovePoint emit. constexpr float kMaxSwimSpanYards = 60.0f; @@ -2505,7 +2725,7 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, // The breath timer (getMaxTimer) is a protected Player member we // can't read from here. We don't need it: the hard span cap is the // real guard. A <=60y crossing at normal swim speed takes only a - // few seconds — far inside the shortest breath bar (~1 min) — so + // few seconds — far inside the shortest breath bar (~1 min) — so // any crossing that passes the span cap is breath-safe by // construction. kBreathSafety is retained only as documentation of // the margin the cap implies. @@ -2514,7 +2734,7 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, if (!allow_swim) { - // Genuinely long / unbreathable deep-water span — refuse as + // Genuinely long / unbreathable deep-water span — refuse as // before. Stamp the LRU so wander doesn't re-probe every tick. Playerbot::V2::Module::instance().OnPathOutcome(3 /*FarFromPolyEnd*/); log_path_fail("Submerged"); @@ -2522,7 +2742,7 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, GameTime::GetGameTimeMS()); return Result::Locked; } - // Short crossing within breath budget — fall through and let the + // Short crossing within breath budget — fall through and let the // MovePoint below issue the swim spline. PathGenerator already // returned a NORMAL/SHORTCUT path (we're past the NOPATH gate), so // Detour found a route across; we are only relaxing the *policy* @@ -2535,14 +2755,14 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, // as a waypoint spline instead of beelining. WaypointMovementGenerator still // navmesh-paths BETWEEN nodes (generatePath defaults true), so the authored // nodes act as guide points that pull the route onto the road while Detour - // handles fine pathing — and those sub-paths keep the NAV_AREA_ROAD bias. + // handles fine pathing — and those sub-paths keep the NAV_AREA_ROAD bias. // Skipped in combat and while flying; the area-cost bias remains the fallback. if (!p_->IsInCombat() && !p_->IsFlying()) { std::vector roadWps; bool roadOk = sHandcraftedRoadGraph->ComputeRoute(p_->GetMap(), p_->GetPhaseShift(), p_->GetPosition(), Position(x, y, z, 0.0f), roadWps) && roadWps.size() >= 2; - // Reject a road route whose FIRST waypoint heads AWAY from the goal — the + // Reject a road route whose FIRST waypoint heads AWAY from the goal — the // nearest road entry node can sit BEHIND the bot (e.g. back inside the Orc // Valley of Trials), so MovePathing it makes the bot backtrack onto the // road and oscillate at the exit chokepoint instead of leaving (live: @@ -2557,7 +2777,7 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, float const w2g = std::sqrt( (x - roadWps[0].GetPositionX()) * (x - roadWps[0].GetPositionX()) + (y - roadWps[0].GetPositionY()) * (y - roadWps[0].GetPositionY())); - if (w2g > b2g + 15.0f) // first road node is a >15y backtrack — skip the road + if (w2g > b2g + 15.0f) // first road node is a >15y backtrack — skip the road roadOk = false; } if (roadOk) @@ -2575,9 +2795,7 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, if (p_->IsWalking() == run) p_->SetWalk(!run); - p_->GetMotionMaster()->MovePath(roadPath, /*repeatable*/ false, {}, {}, - run ? MovementWalkRunSpeedSelectionMode::ForceRun - : MovementWalkRunSpeedSelectionMode::ForceWalk); + MoveAlongRoute(p_, roadPath, run); return Result::Ok; } } @@ -2586,22 +2804,22 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, // state a previous immersive-RP toggle / /walk command left behind, // and a "run to quest hub" emit becomes a leisurely 2.5y/s stroll. // Mirrors the SetWalk pattern used by FollowMovementGenerator (target's - // IsWalking → bot follows with same speed mode). + // IsWalking → bot follows with same speed mode). if (p_->IsWalking() == run) p_->SetWalk(!run); // Complete path: out of combat, drive the API's computed points via MovePath - // for the SAME reason as the advancing-partial branch — MovePoint(x,y,z, + // for the SAME reason as the advancing-partial branch — MovePoint(x,y,z, // generatePath=true) lets the MotionMaster RE-pathfind the dst and can resolve // it to a degenerate same-poly route (zero movement) on certain seams, even // when the API found a full path (live: Grimfang frozen at the Valley exit - // pursuing a 160y COMPLETE-path goal, no path_fail, never a step — while + // pursuing a 160y COMPLETE-path goal, no path_fail, never a step — while // Gorthak on the Incomplete branch was already unstuck by the MovePath fix). // GATED to !combat && !flying (mirrors the road-centerline branch) so chase / // flight movement keeps the established MovePoint behavior; this only changes // out-of-combat travel, where the degenerate-freeze wedge actually happens. // - // EXCEPTION — short approach over an OFF-MESH bridge in an instance (in-BG + // EXCEPTION — short approach over an OFF-MESH bridge in an instance (in-BG // 2026-06-23; broadened to dungeon/raid 2026-06-25). On a complete path that // crosses an off-mesh connection (AV captain garrison / cave-den bridges, and // the Deadmines foundry Gap-1 bridge), MovePath re-pathfinds BETWEEN its @@ -2613,7 +2831,7 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, // connections natively (Movement/PathGenerator.cpp getOffMeshConnectionPoly- // EndPoints). Scoped to a SHORT (<80y) in-instance approach so it can't reach // the FAR cross-tile MovePoint degenerate-freeze (Grimfang, ~160y) the MovePath - // branch exists to dodge — at <80y inside a loaded instance the dst poly is + // branch exists to dodge — at <80y inside a loaded instance the dst poly is // local, so MovePoint resolves a real spline. const float bg_cdx = x - p_->GetPositionX(); const float bg_cdy = y - p_->GetPositionY(); @@ -2635,9 +2853,7 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop, run ? WaypointMoveType::Run : WaypointMoveType::Walk); cmpPath.BuildSegments(); - p_->GetMotionMaster()->MovePath(cmpPath, /*repeatable*/ false, {}, {}, - run ? MovementWalkRunSpeedSelectionMode::ForceRun - : MovementWalkRunSpeedSelectionMode::ForceWalk); + MoveAlongRoute(p_, cmpPath, run, /*navmesh_points*/ true); return Result::Ok; } } @@ -2672,21 +2888,21 @@ bool API::TryTerrainWalkFallback(float x, float y, float z, bool run) // Per-emit skim cap. This bridges navmesh HOLES (canopy/walkway occlusion // during gen, elevated WMO platforms Recast skipped, bridges) where VMAP // collision EXISTS but no navmesh poly does. We no longer REFUSE a target - // beyond this range — instead we crawl toward it one capped segment per + // beyond this range — instead we crawl toward it one capped segment per // emit and let the next tick (re-issued from the advanced pose) continue, // so the bot "walks forward bit by bit" across an arbitrarily large // continuous walkable surface (e.g. the 73y Orgrimmar zeppelin-tower // platform that has collision but no mesh). Each segment is still validated // step-by-step below, so the crawl STOPS the instant the line hits a wall, - // ledge, void, or hazard — it never walks the bot off an edge or through + // ledge, void, or hazard — it never walks the bot off an edge or through // geometry. Long-range ROUTING still belongs to the pathfinder/travel graph; // this only takes over once Detour has already returned NoPath/FarFromPoly. constexpr float kFallbackRange = 40.0f; // Max ground-height delta between consecutive samples. Above this we're at - // a cliff edge / wall face / steep ramp, NOT a flat hole — refuse so we + // a cliff edge / wall face / steep ramp, NOT a flat hole — refuse so we // never walk off a ledge, through a wall, or down a fall. // NOTE (2026-06-09): a 5y asymmetric (up) variant was tried to climb the Org - // lift RAMP but ROLLED BACK — it let bots climb onto elevator platforms they + // lift RAMP but ROLLED BACK — it let bots climb onto elevator platforms they // then couldn't step off. Elevator ramp/platform traversal is being designed // properly (travel-graph-defined). See docs/ELEVATOR_TRAVEL_HANDOVER_20260609.md. constexpr float kStepClimb = 3.0f; @@ -2702,7 +2918,7 @@ bool API::TryTerrainWalkFallback(float x, float y, float z, bool run) constexpr float kSampleStep = 4.0f; // Upper sanity bound on the TARGET distance. The crawl bridges LOCAL holes - // (platforms, bridges, mesh gaps) — it must never become long-haul routing + // (platforms, bridges, mesh gaps) — it must never become long-haul routing // across the open world toward a far target Detour wrongly NoPath'd over flat // terrain. Beyond this the travel graph / taxi own the trip; refuse so the // bot gives up (NotePathFail) and re-routes instead of wandering. 150y @@ -2710,15 +2926,15 @@ bool API::TryTerrainWalkFallback(float x, float y, float z, bool run) constexpr float kMaxCrawlTarget = 150.0f; // BG start-platform / graveyard DESCENT (2026-06-22, owner-directed). In a // battleground a bot only ever moves DOWN off an elevated start or respawn - // platform — never UP — so the elevator-stranding failure that retired the + // platform — never UP — so the elevator-stranding failure that retired the // general crawl-on-Incomplete (see the move_to non-advancing branch) cannot // occur here. Two BG-only relaxations let the crawl carry a bot down the // unmeshed descent ramp onto the arena floor (where navmesh routing resumes): - // * lift the local-hole TARGET cap — the descent's true goal is a far + // * lift the local-hole TARGET cap — the descent's true goal is a far // objective (an EotS tower ~250y across the arena). Terrain-walk only // engages where Detour already FAILED (the disconnected platform edge); // the field below is meshed, so a far target can't degenerate this into - // open-world long-haul — the crawl ends the instant the bot lands on a + // open-world long-haul — the crawl ends the instant the bot lands on a // navmesh poly and the next emit re-paths normally. // * allow a larger DOWNWARD step (applied at the per-sample gate below); // UP steps keep the tight 3y limit so nothing climbs onto geometry. @@ -2753,7 +2969,7 @@ bool API::TryTerrainWalkFallback(float x, float y, float z, bool run) } // Aim at the destination directly when it's within one segment, otherwise at - // an intermediate point kFallbackRange along the line — the next emit picks + // an intermediate point kFallbackRange along the line — the next emit picks // up the remainder. The per-step validation is identical either way. const float reach = std::min(dist, kFallbackRange); const float tgtX = sx + (dx / dist) * reach; @@ -2772,13 +2988,13 @@ bool API::TryTerrainWalkFallback(float x, float y, float z, bool run) float const g = mm->GetHeight(p_->GetPhaseShift(), px, py, prevZ + 5.0f, /*vmap*/ true); if (g <= INVALID_HEIGHT) { - tw_log("refuse:void", px, py, g); // genuine void — nothing to walk on + tw_log("refuse:void", px, py, g); // genuine void — nothing to walk on return false; } // Cliff/wall/drop guard. UP steps always use the tight kStepClimb (3y) // so nothing climbs onto a ledge/elevator. DOWN steps are relaxed in a // BG (bg_descent): a bot leaving its start/respawn platform may need to - // walk a steep ramp — or take a short controlled drop — onto the arena + // walk a steep ramp — or take a short controlled drop — onto the arena // floor, and it can only ever go DOWN there, so a steeper descent can't // strand it. The void + hazard checks below still apply, so it never // crawls into nothing or into magma/deep water. @@ -2794,12 +3010,20 @@ bool API::TryTerrainWalkFallback(float x, float y, float z, bool run) // shared helper. A skim sample that lands in magma/slime or in water // deep enough to submerge the bot is refused (hazard / drown); wading // depth is fine. - if (BotMovement::IsLiquidImpassableForWalk( - BotMovement::ClassifyDestinationLiquid(p_, px, py, g))) + BotMovement::LiquidVerdict const tw_lv = BotMovement::ClassifyDestinationLiquid(p_, px, py, g); + if (BotMovement::IsLiquidImpassableForWalk(tw_lv)) { tw_log("refuse:hazard", px, py, g); // hazard / drown return false; } + // A bot that keeps out of liquid (a capital's town bots, see g_LiquidPathPolicy) does not skim into wading water either: the + // skim ignores the navmesh, so it would walk them off a quay into a canal. + if (tw_lv != BotMovement::LiquidVerdict::Dry && BotMovement::g_LiquidPathPolicy + && BotMovement::g_LiquidPathPolicy(p_) != BotMovement::LiquidPolicy::None) + { + tw_log("refuse:water", px, py, g); + return false; + } prevZ = g; if (i == steps) endZ = g; // validated ground at the segment end } @@ -2817,12 +3041,12 @@ bool API::TryTerrainWalkFallback(float x, float y, float z, bool run) // BG start-platform / graveyard STEP-DOWN (2026-06-22, owner-directed). // The EotS start platforms OVERHANG the arena: the platform edge toward the // objective has only void below it (GetHeight returns nothing within range), and -// no continuous walkable ramp exists for a crawl to follow — players reach the +// no continuous walkable ramp exists for a crawl to follow — players reach the // field by dropping off a designed exit, not by walking. Trying to crawl the // descent is the wrong model. Instead, do exactly what the elevator-disembark // does: find the FIELD navmesh poly in front of the platform (toward the // objective, at the objective's field height) and relocate the bot onto it, then -// let normal navmesh routing take over. This is a SHORT, designed platform→field +// let normal navmesh routing take over. This is a SHORT, designed platform→field // step (the BG's intended start), not a long-distance stuck-rescue, and it only // ever moves the bot DOWN onto the arena floor it is trying to reach. bool API::TryBgDescentCrawl(float x, float y, float z, bool run) @@ -2892,7 +3116,7 @@ Result API::stop_movement(bool clear_generators) return Result::Ok; } // A taxi flight owns the FLIGHT generator and IS the bot's intended - // movement — never tear it down here (the caller wants stale movers gone, + // movement — never tear it down here (the caller wants stale movers gone, // not a legitimate flight cancelled mid-air). if (p_->IsInFlight()) return Result::Ok; @@ -2911,6 +3135,7 @@ Result API::start_attack(ObjectGuid target, uint8 avoid_school_mask) { if (!p_) return Result::Other; if (!p_->IsAlive()) return Result::Locked; + StandForMove(p_); if (target.IsEmpty()) return Result::InvalidTarget; Unit* tu = ObjectAccessor::GetUnit(*p_, target); @@ -2918,8 +3143,8 @@ Result API::start_attack(ObjectGuid target, uint8 avoid_school_mask) if (tu == p_) return Result::InvalidTarget; if (!tu->IsAlive()) return Result::InvalidTarget; - // Friendly-fire gate. Unit::Attack() itself never validates hostility — - // it happily arms the swing timer against a groupmate — and the spell + // Friendly-fire gate. Unit::Attack() itself never validates hostility — + // it happily arms the swing timer against a groupmate — and the spell // engine only rejects at cast time (BAD_TARGETS), so a friendly victim // WEDGES: the bot keeps swinging air, member.victim publishes the // friendly guid, and group assist copies it fleet-wide (2026-06-11 @@ -2937,22 +3162,35 @@ Result API::start_attack(ObjectGuid target, uint8 avoid_school_mask) return Result::InvalidTarget; } + // A target beyond sight is never attacked, as a player cannot click it. A fight carried over a teleport on the same continent + // left hunters chasing a Young Thistle Boar 16 km away for good, still in combat (bots-on test 2026-10-27). Drop it like the + // friendly target above. + if (!p_->IsWithinDistInMap(tu, p_->GetMap()->GetVisibilityRange())) + { + if (p_->GetVictim() == tu) + { + p_->AttackStop(); + p_->SetSelection(ObjectGuid::Empty); + } + return Result::InvalidTarget; + } + // A mounted player cannot attack (Unit::Attack returns false), so a bot riding past an enemy emitted start_attack every // tick and nothing happened: bots ran past each other mounted in WSG (playtest, 2026-10-08). Like a real player who clicks // an enemy, the bot gets off its mount first. - if (p_->IsMounted() && tu->IsHostileTo(p_)) - p_->Dismount(); + if ((p_->IsMounted() || p_->HasAuraType(SPELL_AURA_MOUNTED)) && tu->IsHostileTo(p_)) + p_->RemoveAurasByType(SPELL_AURA_MOUNTED); // Ranged white damage. A real hunter's client casts Auto Shot (75, an // auto-repeat ranged spell) the moment they engage; the server then // re-fires it from Unit::_UpdateAutoRepeatSpell entirely server-side. // Bots have no client, and Player::Attack(melee=true) only arms the - // MELEE swing timer — so until 2026-06-10 every hunter bot did ZERO + // MELEE swing timer — so until 2026-06-10 every hunter bot did ZERO // ranged auto-attack damage (verified live: Uraimus L13 BM, white // damage absent between Steady Shots). Start the auto-repeat here, // both on fresh engages and on the idempotent re-engage path (the // core cancels CURRENT_AUTOREPEAT_SPELL when a CheckCast fails, e.g. - // a brief LOS break — re-arming on the next engage tick restores it). + // a brief LOS break — re-arming on the next engage tick restores it). // Spell 75 is special-cased in _UpdateAutoRepeatSpell to coexist with // hard casts (Steady Shot) and movement, matching retail behavior. // Raid school rule (bot module PveOrder::SchoolHint): physical avoided on @@ -2975,35 +3213,124 @@ Result API::start_attack(ObjectGuid target, uint8 avoid_school_mask) p_->InterruptSpell(CURRENT_AUTOREPEAT_SPELL); }; + // Auto Shot's minimum and maximum against this mob, from the same function the core's range check uses (Spell::CalcMinMaxRange): the caster's + // and the mob's combat reach, the range entry and the ranged weapon's range modifier. Estimating them here left a hunter standing 9-11 y from a + // mob, shot refused OUT_OF_RANGE on every try, and not knowing it was inside the zone (PC 20 Oct, Halorio on Blackhand trash). + auto autoShotRange = [&](Unit const* target) -> std::optional + { + SpellInfo const* shot = sSpellMgr->GetSpellInfo(75, DIFFICULTY_NONE); + if (!shot || !shot->RangeEntry) + return std::nullopt; + return Spell::CalcMinMaxRange(p_, target, false, shot, true); + }; + auto ensureAutoShot = [&](Unit* victim) { constexpr uint32 AUTO_SHOT = 75; if (physical_avoided) return; if (p_->GetClass() != CLASS_HUNTER) return; - if (p_->GetCurrentSpell(CURRENT_AUTOREPEAT_SPELL)) return; + // The core never drops a running Auto Shot (Unit::_UpdateAutoRepeatSpell keeps spell 75 when its CheckCast fails), so "one is running" + // is not "it is firing": the repeat sits on the first target, or waits on a failed check, and the hunter stands in the aim pose. + if (Spell* running = p_->GetCurrentSpell(CURRENT_AUTOREPEAT_SPELL)) + { + if (running->m_targets.GetUnitTargetGUID() != victim->GetGUID()) + p_->InterruptSpell(CURRENT_AUTOREPEAT_SPELL, false); // aimed at the previous mob: take it up again on this one + else + { + // A walking flag left set after the spline ended keeps Unit::isMoving() true; the repeat then waits for the bot to stop + // moving, which it already has (PC 20 Oct, level 2 hunters shot Concussive Shot once and never fired Auto Shot). + ClearStaleMoveFlags(p_); + SpellCastResult const check = running->CheckCast(true); + // Inside Auto Shot's minimum range the hunter fights in melee (hunter_dead_zone below), and the repeat is held there by + // design: only a hold outside that range is worth a line. + bool in_min_range = false; + std::optional const shot_range = autoShotRange(victim); + if (check == SPELL_FAILED_OUT_OF_RANGE && shot_range) + in_min_range = p_->GetExactDist(victim) < shot_range->Min + 1.0f; + if (check != SPELL_CAST_OK && check != SPELL_FAILED_DONT_REPORT && !in_min_range) + { + static std::mutex sHeldLogMutex; + static std::unordered_map sHeldLog; + uint32 const now = getMSTime(); + bool log_now = false; + { + std::lock_guard lock(sHeldLogMutex); + if (sHeldLog.size() > 4096) + sHeldLog.clear(); + uint32& last = sHeldLog[p_->GetGUID().GetCounter()]; + if (!last || now - last > 5000u) + { + last = now; + log_now = true; + } + } + if (log_now) + TC_LOG_INFO("playerbot.v2", "[autoshot_held] {} on {}: check {} dist {:.1f} min {:.1f} max {:.1f} moving {} in_front {} los {} ammo {} count {}", p_->GetName(), victim->GetName(), + uint32(check), p_->GetExactDist(victim), shot_range ? shot_range->Min : -1.0f, shot_range ? shot_range->Max : -1.0f, int(p_->isMoving()), int(p_->HasInArc(static_cast(M_PI), victim)), + int(p_->IsWithinLOSInMap(victim)), p_->GetAmmoId(), p_->GetAmmoId() ? p_->GetItemCount(p_->GetAmmoId()) : 0u); + // Facing is the one cause the bot can mend here: it never turns between shots, a client's player does. + if (check == SPELL_FAILED_UNIT_NOT_INFRONT) + FaceUnitForCast(p_, victim); + } + return; + } + } if (!p_->HasSpell(AUTO_SHOT)) return; if (!p_->GetWeaponForAttack(RANGED_ATTACK, true)) return; - p_->CastSpell(victim, AUTO_SHOT, false); + // The ammo slot is only filled on a few events (equip, login): a bot that was handed bullets later, or whose set stack ran out, has + // them in the bags and nothing set, and Auto Shot is refused NO_AMMO on every try. + if (p_->NeedsAmmo() && (!p_->GetAmmoId() || !p_->HasItemCount(p_->GetAmmoId()))) + p_->AutoSelectAmmo(); + SpellCastResult const shot = p_->CastSpell(victim, AUTO_SHOT, false); + if (shot == SPELL_CAST_OK) + LogCastWhileMoving(p_, "shoots", AUTO_SHOT); + // A refused Auto Shot is otherwise silent: the hunter stands in the aim pose and never fires (PC 20 Oct, two level 2 hunters). + // DONT_REPORT is the core's "the ranged swing is not ready yet" (Spell::CheckCast); Spell::prepare has queued the repeat, which fires + // when the timer is up. Nothing is lost, so it is not a refusal. + if (shot != SPELL_CAST_OK && shot != SPELL_FAILED_DONT_REPORT) + { + static std::mutex sShotLogMutex; + static std::unordered_map sShotLog; + uint32 const now = getMSTime(); + bool log_now = false; + { + std::lock_guard lock(sShotLogMutex); + if (sShotLog.size() > 4096) + sShotLog.clear(); + uint32& last = sShotLog[p_->GetGUID().GetCounter()]; + if (!last || now - last > 5000u) + { + last = now; + log_now = true; + } + } + if (log_now) + { + std::optional const shot_range = autoShotRange(victim); + TC_LOG_INFO("playerbot.v2", "[autoshot_fail] {} on {}: result {} dist {:.1f} min {:.1f} max {:.1f} ammo {} count {}", p_->GetName(), victim->GetName(), uint32(shot), + p_->GetExactDist(victim), shot_range ? shot_range->Min : -1.0f, shot_range ? shot_range->Max : -1.0f, p_->GetAmmoId(), p_->GetAmmoId() ? p_->GetItemCount(p_->GetAmmoId()) : 0u); + } + } }; // Idempotency fast-path: if we are already attacking this exact target, // do not re-call Attack or re-init MoveChase. Both have visible side - // effects every tick — MoveChase resets the chase generator, clearing + // effects every tick — MoveChase resets the chase generator, clearing // the spline and forcing a path recalc. Calling it every tick (which // the bot logic does as long as the engage rule keeps firing on the same // victim) produces the visible "stutter": bot stops, plans, takes one // step, stops again. Detect the no-op case and return Ok. // Mirror what a player click does: keep the selection in sync with the // victim. NOTE: Player::SetTarget is an EMPTY override ("does not apply - // to players") — selection is normally client-driven via - // CMSG_SET_SELECTION → SetSelection. Headless bots never send that + // to players") — selection is normally client-driven via + // CMSG_SET_SELECTION → SetSelection. Headless bots never send that // packet, so until 2026-06-11 UNIT_FIELD_TARGET stayed permanently // empty on every bot: other players selecting a bot saw no // target-of-target frame, and anything else reading the field // (assist macros, UnitIsUnit comparisons client-side) misbehaved. // MUST run BEFORE the idempotency fast-path: a victim acquired through // any other route (Charge-style attack spells, core melee engage) - // means every subsequent engage tick takes the early return — with the + // means every subsequent engage tick takes the early return — with the // selection-set below it, UNIT_FIELD_TARGET never caught up (user // re-report 2026-06-11 Stockades). if (p_->GetTarget() != tu->GetGUID()) @@ -3011,23 +3338,82 @@ Result API::start_attack(ObjectGuid target, uint8 avoid_school_mask) // Idempotency fast-path: if we are already attacking this exact target, // do not re-call Attack or re-init MoveChase. Both have visible side - // effects every tick — MoveChase resets the chase generator, clearing + // effects every tick — MoveChase resets the chase generator, clearing // the spline and forcing a path recalc. Calling it every tick (which // the bot logic does as long as the engage rule keeps firing on the same // victim) produces the visible "stutter": bot stops, plans, takes one // step, stops again. Detect the no-op case and return Ok. // Ranged-spec hunters with a usable ranged weapon engage RANGED-only: // Attack(melee=true) arms the melee swing timer, and TC happily swings - // it whenever the victim stands in reach — so in tight corridors + // it whenever the victim stands in reach — so in tight corridors // (Stockades, user report 2026-06-11) the hunter PUNCHED mobs between // shots. Modern hunters have no minimum range and never melee outside // Survival; meleeAttack=false still sets the victim/combat state while // Auto Shot (ensureAutoShot below) carries the white damage. + // Auto Shot has a minimum range (the range entry's minimum plus the melee range, Spell::GetMinMaxRange): a mob inside it cannot be shot, and a + // hunter that neither shoots nor swings stands and lets it kill the group. Inside it the hunter fights in melee, like a player closing in. + bool hunter_dead_zone = false; + if (p_->GetClass() == CLASS_HUNTER) + if (std::optional const shot_range = autoShotRange(tu)) + hunter_dead_zone = p_->GetExactDist(tu) < shot_range->Min + 1.0f; const bool ranged_hunter_engage = p_->GetClass() == CLASS_HUNTER && - ::Playerbot::Classic::EffectiveSpecId(p_) != uint32(ChrSpecialization::HunterSurvival) && - p_->GetWeaponForAttack(RANGED_ATTACK, true) != nullptr; + !hunter_dead_zone && + // Vanilla Survival shoots like the other two specs; only the retail table makes it the melee one. + (::Playerbot::IsVanillaRealm() || ::Playerbot::Classic::EffectiveSpecId(p_) != uint32(ChrSpecialization::HunterSurvival)) && + p_->GetWeaponForAttack(RANGED_ATTACK, true) != nullptr && + // With nothing to shoot the hunter fights in melee, like a player without arrows: Auto Shot would be refused every time. + (!p_->NeedsAmmo() || (p_->AutoSelectAmmo(), p_->GetAmmoId() != 0 && p_->HasItemCount(p_->GetAmmoId()))); const bool melee_swing = !ranged_hunter_engage && !physical_avoided; + // Every chase a hunter is given, with the distance and the shooting state it was given at (159: hunters put back at 24 y were 3.5 y from the dummy + // by the next check, and nothing in the log said who sent them in). One line a bot per 2 s. + auto logHunterChase = [&](char const* site) + { + if (p_->GetClass() != CLASS_HUNTER) + return; + static std::mutex sChaseLogMutex; + static std::unordered_map sChaseLog; + uint32 const now = getMSTime(); + { + std::lock_guard lock(sChaseLogMutex); + if (sChaseLog.size() > 4096) + sChaseLog.clear(); + uint32& last = sChaseLog[p_->GetGUID().GetCounter()]; + if (last && now - last < 2000u) + return; + last = now; + } + TC_LOG_INFO("playerbot.v2", "[hunter_chase] {} on {}: {} dist {:.1f} dead_zone {} ranged_engage {} melee_swing {}", p_->GetName(), tu->GetName(), site, p_->GetExactDist(tu), int(hunter_dead_zone), int(ranged_hunter_engage), int(melee_swing)); + }; + if (p_->GetClass() == CLASS_HUNTER && !ranged_hunter_engage) + { + // Why a hunter engages in melee (157: Raptor Strike and white swings against the dummy while the harness had it 15 y away): every + // condition of the ranged engage, once per 5 s per hunter. + static std::mutex sMeleeLogMutex; + static std::unordered_map sMeleeLog; + uint32 const now = getMSTime(); + bool log_now = false; + { + std::lock_guard lock(sMeleeLogMutex); + if (sMeleeLog.size() > 4096) + sMeleeLog.clear(); + uint32& last = sMeleeLog[p_->GetGUID().GetCounter()]; + if (!last || now - last > 5000u) + { + last = now; + log_now = true; + } + } + if (log_now) + { + Item const* ranged = p_->GetWeaponForAttack(RANGED_ATTACK, true); + Item const* equipped = p_->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED); + TC_LOG_INFO("playerbot.v2", "[hunter_melee_engage] {} on {}: dist {:.1f} dead_zone {} spec {} usable_ranged_weapon {} equipped_ranged {} needs_ammo {} ammo_id {} ammo_count {} physical_avoided {} los {}", + p_->GetName(), tu->GetName(), p_->GetExactDist(tu), int(hunter_dead_zone), ::Playerbot::Classic::EffectiveSpecId(p_), ranged ? ranged->GetEntry() : 0u, + equipped ? equipped->GetEntry() : 0u, int(p_->NeedsAmmo()), p_->GetAmmoId(), p_->GetAmmoId() ? p_->GetItemCount(p_->GetAmmoId()) : 0u, + int(physical_avoided), int(p_->IsWithinLOSInMap(tu))); + } + } if (p_->GetVictim() == tu) { @@ -3043,11 +3429,23 @@ Result API::start_attack(ObjectGuid target, uint8 avoid_school_mask) p_->Attack(tu, /*meleeAttack*/ true); holdAvoidedAutoRepeat(tu); ensureAutoShot(tu); + // A hunter engaged from range stands at its shooting spot (chase to 28 y). When the mob then comes inside Auto Shot's dead zone the + // fight turns to melee, but this path never chased again: the hunter stood a few yards off, unable to shoot or swing (Isane, 2026-10-20). + // Close in once it stands still; a hunter already walking keeps its chase. + if (p_->GetClass() == CLASS_HUNTER && hunter_dead_zone && melee_swing && p_->movespline->Finalized() && !p_->IsWithinMeleeRange(tu)) + { p_->GetMotionMaster()->MoveChase(tu); logHunterChase("dead_zone_close_in"); } + // The opening engage chases once; another layer's move (formation slot, follow) replaces that chase and this path never issued it + // again, so a hunter ordered at a mob beyond its shooting range stood in the aim pose for good (PC 20 Oct, whelp ~30+ y away). + // Take the chase up again whenever the bot is not chasing and the mob is out of its 28 y shooting spot. + else if (p_->GetClass() == CLASS_HUNTER && ranged_hunter_engage && p_->GetExactDist(tu) > 28.0f && + !(tu->IsCreature() && !tu->IsInCombat() && !tu->GetVictim() && p_->GetGroup() && p_->GetMap()->Instanceable()) && // an idle mob in an instance: see below + p_->GetMotionMaster()->GetCurrentMovementGeneratorType() != CHASE_MOTION_TYPE) + { p_->GetMotionMaster()->MoveChase(tu, ChaseRange(0.0f, 28.0f)); logHunterChase("ranged_28"); } return Result::Ok; } // Face the target. WoW's spell engine rejects casts that aren't in - // the caster's front arc (HasInArc(M_PI, target) ~= ±90° cone). Without + // the caster's front arc (HasInArc(M_PI, target) ~= ±90° cone). Without // an explicit orientation update the bot may have last faced its // previous travel waypoint or last npc dialog, causing every cast // to fail with SpellCastResult=126 (NOT_INFRONT) until MotionMaster @@ -3076,13 +3474,13 @@ Result API::start_attack(ObjectGuid target, uint8 avoid_school_mask) // Real Players chase the target via client input; an bot logic-driven bot Player // has no client and Player::Attack alone doesn't move them. Without an // explicit MoveChase the bot just stands at whatever range the engage - // rule spotted them — typically 30–40y — which breaks both melee + // rule spotted them — typically 30–40y — which breaks both melee // (no swings, no combat ignites) and casters (cast fails OOR / LOS). // // Class-aware chase distance: melee classes close to weapon range; pure // ranged classes stop at ~25y so they have a clean window for hard-cast // openers (Frostbolt / Shadow Bolt / Steady Shot all 30y range). - // Hybrids (Druid/Shaman/Evoker) default to melee here — their caster + // Hybrids (Druid/Shaman/Evoker) default to melee here — their caster // specs will switch to a ranged stance via the APL once it picks up, // and melee specs stay engaged. bool is_pure_caster = false; @@ -3096,20 +3494,20 @@ Result API::start_attack(ObjectGuid target, uint8 avoid_school_mask) break; case CLASS_HUNTER: // BM / MM are ranged-only since the BfA artifact removal, but - // SURVIVAL has been a melee spec since Legion — parking an SV + // SURVIVAL has been a melee spec since Legion — parking an SV // bot at 28y makes every Raptor Strike / Mongoose Bite fail // OOR and leaves only Auto Shot-less wand-range idling. Spec // check instead of class check; pre-L10 (spec None) hunters // default to ranged, which matches their Steady Shot kit. is_pure_caster = - ::Playerbot::Classic::EffectiveSpecId(p_) != uint32(ChrSpecialization::HunterSurvival); + (::Playerbot::IsVanillaRealm() || ::Playerbot::Classic::EffectiveSpecId(p_) != uint32(ChrSpecialization::HunterSurvival)) && ranged_hunter_engage; // melee fallback: close in break; case CLASS_EVOKER: - // Evoker is pure-caster like Mage/Hunter (no melee spec — + // Evoker is pure-caster like Mage/Hunter (no melee spec — // Devastation/Augmentation/Preservation are all caster) BUT // baseline range is only 25y (Living Flame, Disintegrate, // Azure Strike). The 28y max used for the other casters - // would leave Evoker OUT of cast range. Separate flag → 23y + // would leave Evoker OUT of cast range. Separate flag → 23y // max keeps the bot inside Living Flame range with 2y safety. is_pure_caster = true; is_short_range_caster = true; @@ -3139,16 +3537,29 @@ Result API::start_attack(ObjectGuid target, uint8 avoid_school_mask) default: break; } + if (!is_pure_caster && tu->IsCreature() && !tu->IsInCombat() && !tu->GetVictim() && p_->GetGroup() && p_->GetMap()->Instanceable() && + !::Playerbot::IsTankSpec(p_->GetClass(), uint16(::Playerbot::Classic::EffectiveSpecId(p_)))) + { + // A melee bot does not run at an idle mob while a tank of its group is on the map: the pull is the tank's, and the bot takes the mob + // once someone has it (the chase below starts then). UBRS 132f 22:15:14-26: a rogue chased an idle Veteran 38 y up a ramp alone. + bool tank_present = false; + for (GroupReference const& itr : p_->GetGroup()->GetMembers()) + if (Player const* m = itr.GetSource(); m && m != p_ && m->IsAlive() && m->GetMapId() == p_->GetMapId() && + ::Playerbot::IsTankSpec(m->GetClass(), uint16(::Playerbot::Classic::EffectiveSpecId(m)))) + { tank_present = true; break; } + if (tank_present) + return Result::Ok; + } if (is_pure_caster && tu->IsCreature() && !tu->IsInCombat() && !tu->GetVictim() && p_->GetGroup() && p_->GetMap()->Instanceable()) { // An idle mob in an instance: the core chase only ends with a line of sight, so a caster ordered at a mob up a ramp walked to the - // top, into the pack beside it. The opener's range / sight step (OpenerFire, which refuses a point in an idle pack's reach) - // takes the caster nearer instead. + // top, into the pack beside it (UBRS 132f 22:15:16, two Dragonspawn pulled onto a rogue). The opener's range / sight step + // (OpenerFire, which refuses a point in an idle pack's reach) takes the caster nearer instead. return Result::Ok; } if (is_pure_caster) { - // MinRange=0 — never back-pedal. ChaseRange(min=5, max=28) had the + // MinRange=0 — never back-pedal. ChaseRange(min=5, max=28) had the // bot moving backwards whenever a melee mob walked inside 5y, which // kept is_moving=true and starved every hard cast (cast attempts // surfaced as SPELL_FAILED_MOVING in the log). Real Frost Mages @@ -3158,22 +3569,20 @@ Result API::start_attack(ObjectGuid target, uint8 avoid_school_mask) // MaxRange=28 still keeps the bot inside Frostbolt / Shadow Bolt / // Steady Shot's 30y range with a small safety margin; Evoker // (25y range baseline) gets a tighter 23y to stay in range. - const float max_chase = is_short_range_caster ? 23.0f : 28.0f; + // 28 stopped the 167 warlock at 29.2 y: the chase range is edge to edge (the combat reaches come on top), so the bot stood at the edge of + // the 30 y cast range, where a step of the dummy or a wobble put it out of range. 25 puts it at about 26-27 y. + // Mind Flay and Earth Shock reach 20 y, not 30: the shadow priest and the elemental shaman stood at 27.5 y (190: 25 plus the combat reaches), + // so their rotation's channel and shock were never in range (no Mind Flay in the t1 and buffed legs) and only the 30 y spells fired. + ChrSpecialization const caster_spec = ChrSpecialization(::Playerbot::Classic::EffectiveSpecId(p_)); + bool const twenty_yard_rotation = caster_spec == ChrSpecialization::PriestShadow || caster_spec == ChrSpecialization::ShamanElemental; + const float max_chase = is_short_range_caster ? 21.0f : twenty_yard_rotation ? (caster_spec == ChrSpecialization::ShamanElemental ? 13.0f : 16.0f) : 25.0f; // the elemental also keeps the victim inside Searing Totem's 18 y p_->GetMotionMaster()->MoveChase(tu, ChaseRange(0.0f, max_chase)); + logHunterChase("opening_ranged"); } else { - if (tu->IsCreature() && !tu->IsInCombat() && !tu->GetVictim() && p_->GetGroup() && p_->GetMap()->Instanceable() && - !::Playerbot::IsTankSpec(p_->GetClass(), uint16(::Playerbot::Classic::EffectiveSpecId(p_)))) - { - // A melee bot does not run at an idle mob while a tank of its group is on the map: the pull is the tank's, and the bot takes the mob - // once someone has it (the chase below starts then). Without this a rogue chased an idle Veteran 38 y up a ramp alone. - for (GroupReference const& itr : p_->GetGroup()->GetMembers()) - if (Player const* m = itr.GetSource(); m && m != p_ && m->IsAlive() && m->GetMapId() == p_->GetMapId() && - ::Playerbot::IsTankSpec(m->GetClass(), uint16(::Playerbot::Classic::EffectiveSpecId(m)))) - return Result::Ok; - } p_->GetMotionMaster()->MoveChase(tu); + logHunterChase("opening_melee"); } return Result::Ok; } @@ -3182,14 +3591,17 @@ Result API::stop_attack(bool clear_ghost_combat) { if (!p_) return Result::Other; p_->AttackStop(); + // Attack off ends Auto Shot as well (a player's attack toggle does); left running it keeps the hunter in the aim pose with no target. + if (p_->GetClass() == CLASS_HUNTER) + p_->InterruptSpell(CURRENT_AUTOREPEAT_SPELL, false); if (!p_->IsInCombat()) p_->SetSheath(SHEATH_STATE_UNARMED); - // Mirror a real client deselecting on disengage — keeps the published + // Mirror a real client deselecting on disengage — keeps the published // UNIT_FIELD_TARGET truthful for other players' target-of-target frames. p_->SetSelection(ObjectGuid::Empty); // Ghost-combat self-heal: a stuck combat flag (combat refs to an // unreachable/evaded mob) with NO attackers means nothing is actually - // fighting the bot — drop the PvE refs so in_combat consumers (the + // fighting the bot — drop the PvE refs so in_combat consumers (the // tank's member-in-combat advance gate, drink/food rules, vendor // gating) stop reading a fight that doesn't exist. Guarded on the // attacker list so a bot in a REAL fight can never combat-drop: with @@ -3203,11 +3615,11 @@ Result API::stop_attack(bool clear_ghost_combat) // Also drop the bot's PET/minion combat. CombatStop(owner) purges the // owner's PvE refs, but a controlled unit (hunter/warlock pet, guardian) // still fighting an EVADED / out-of-scan mob keeps re-flagging the OWNER - // InCombat every tick — so clearing only the owner never sticks (observed + // InCombat every tick — so clearing only the owner never sticks (observed // 2026-06-16: 105 bots cycling [ghost_combat] ~19x each, never escaping). // The ghost-combat gate above already excluded the case where a nearby // enemy is genuinely fighting the bot or its pet (group_engaged), so the - // pet here is fighting nothing reachable — stopping its combat is correct + // pet here is fighting nothing reachable — stopping its combat is correct // and lets the owner's clear hold. for (Unit* minion : p_->m_Controlled) if (minion && minion->IsInCombat() && minion->getAttackers().empty()) @@ -3227,6 +3639,7 @@ Result API::follow(ObjectGuid leader, float distance, float angle_radians) { if (!p_) return Result::Other; if (!p_->IsAlive()) return Result::Locked; + StandForMove(p_); if (leader.IsEmpty() || leader == p_->GetGUID()) return Result::InvalidTarget; Unit* target = ObjectAccessor::GetUnit(*p_, leader); @@ -3302,8 +3715,12 @@ char const* API::MountDisplayProblem(uint32 spell_id, uint32* display_out) Result API::dismount() { if (!p_) return Result::Other; - if (!p_->IsMounted()) return Result::Ok; - p_->Dismount(); + if (!p_->IsMounted() && !p_->HasAuraType(SPELL_AURA_MOUNTED)) return Result::Ok; + // Take the mount AURA off, as a player does (CMSG_CANCEL_MOUNT_AURA): its removal dismounts. Unit::Dismount alone clears the model and the flag + // but leaves an aura without the dismount interrupt flag (the swift mounts) on the bot, still running at mount speed. + p_->RemoveAurasByType(SPELL_AURA_MOUNTED); + if (p_->IsMounted()) + p_->Dismount(); return Result::Ok; } @@ -3313,6 +3730,9 @@ Result API::mount(uint32 mount_id) if (p_->IsInCombat()) return Result::Locked; if (p_->IsMounted()) return Result::Ok; if (p_->IsInWater() || p_->IsFlying()) return Result::Locked; + // The mount cast is refused while the bot moves (SPELL_FAILED_MOVING): a bot that walks or follows stands still for it. + if (p_->isMoving()) + p_->StopMoving(); // Mounting drops a battleground flag or orb the bot carries: never mount with one (WSG flag picked up and dropped five times). for (uint32 carry_aura : { 23333u, 23335u, 34976u, 121164u, 121175u, 121176u, 121177u }) if (p_->HasAura(carry_aura)) return Result::Locked; @@ -3341,17 +3761,36 @@ Result API::mount(uint32 mount_id) // scan the player's spell map looking for an effect that applies // the mount aura. Linear pass; runs only on explicit /mount intent // so the per-cast cost is irrelevant. + // The fastest ground mount the bot knows (the first one in the spell map is arbitrary: a slow or undrawable one). + int32 best_speed = -1; for (auto const& [sid, ps] : p_->GetSpellMap()) { if (!ps.active || ps.disabled) continue; SpellInfo const* si = sSpellMgr->GetSpellInfo(sid, p_->GetMap()->GetDifficultyID()); if (!si) continue; bool is_mount = false; + int32 speed = 0; for (SpellEffectInfo const& eff : si->GetEffects()) - if (eff.ApplyAuraName == SPELL_AURA_MOUNTED) { is_mount = true; break; } - if (is_mount) { mount_id = sid; break; } + { + if (eff.ApplyAuraName == SPELL_AURA_MOUNTED) is_mount = true; + else if (eff.ApplyAuraName == SPELL_AURA_MOD_INCREASE_MOUNTED_SPEED) speed = std::max(speed, int32(eff.BasePoints)); + } + if (!is_mount || MountDisplayProblem(sid, nullptr)) continue; + if (speed > best_speed || (speed == best_speed && sid < mount_id)) { best_speed = speed; mount_id = sid; } + } + if (mount_id == 0) + { + thread_local std::unordered_map s_noMountLogMs; + uint32 const nowMs = getMSTime(); + uint32& last = s_noMountLogMs[p_->GetGUID().GetCounter()]; + if (last == 0 || nowMs - last >= 60000u) + { + last = nowMs; + TC_LOG_INFO("playerbot.v2", "[mount] {} has no mount spell (level {}, riding skill {})", p_->GetName(), uint32(p_->GetLevel()), + uint32(p_->GetSkillValue(SKILL_RIDING))); + } + return Result::NotKnown; } - if (mount_id == 0) return Result::NotKnown; } return cast_spell(mount_id, p_->GetGUID()); } @@ -3413,9 +3852,9 @@ Result API::cast_vehicle_spell_at(uint32 spell_id, float x, float y, float z) SpellInfo const* si = sSpellMgr->GetSpellInfo(spell_id, base->GetMap()->GetDifficultyID()); if (!si) return Result::NotKnown; // IoC/SoTA siege weapons (demolisher Hurl Boulder 67440, siege-engine Ram / - // cannon, catapult) are CATAPULT/GROUND-targeted AoE — they land at a + // cannon, catapult) are CATAPULT/GROUND-targeted AoE — they land at a // destination and apply siege damage to buildings in the blast. So cast at - // the gate's POSITION (NOT a GO target — that fails for ground spells; the + // the gate's POSITION (NOT a GO target — that fails for ground spells; the // 600k-HP keep gates breach under sustained siege fire). SpellCastResult sr = base->CastSpell(Position{x, y, z}, spell_id, false); switch (sr) @@ -3450,7 +3889,7 @@ Result API::unstuck(float distance) if (!p_) return Result::Other; if (p_->IsInCombat()) return Result::ServerRefused; if (p_->IsNonMeleeSpellCast(false, true, true)) return Result::ServerRefused; - // SafeNearTeleport below runs a synchronous PathGenerator rescue — gate it on + // SafeNearTeleport below runs a synchronous PathGenerator rescue — gate it on // the per-tick pathfinding budget so unstuck storms can't pile onto the world // thread; already returns Locked on rescue failure so deferral is contract-safe. if (!PathBudget::HasBudget(GameTime::GetGameTimeMS())) return Result::Locked; @@ -3470,7 +3909,7 @@ Result API::near_teleport_to(float x, float y, float z, float o, bool navmesh_po if (!p_) return Result::Other; if (p_->IsInCombat()) return Result::ServerRefused; if (p_->IsNonMeleeSpellCast(false, true, true)) return Result::ServerRefused; - // SafeNearTeleport runs a synchronous PathGenerator FARFROMPOLY rescue — gate + // SafeNearTeleport runs a synchronous PathGenerator FARFROMPOLY rescue — gate // on the per-tick pathfinding budget (low-volume rescue, rarely trips). Already // returns Locked on failure so deferral is contract-safe. if (!PathBudget::HasBudget(GameTime::GetGameTimeMS())) return Result::Locked; @@ -3484,6 +3923,68 @@ Result API::near_teleport_to(float x, float y, float z, float o, bool navmesh_po return Result::Ok; } +Result API::always_buffs(uint8 set, uint8 mask) +{ + if (!p_ || set >= kBuffSetCount) return Result::Other; + std::string changed; + bool const horde = p_->GetTeam() == HORDE; + // One row: put on when its kind is on here, taken off when it is off here. + auto const row = [&](AlwaysAura const& a) + { + bool const on = (mask & (a.world ? kAlwaysMaskWorldBuffs : kAlwaysMaskConsumables)) != 0 && (!a.horde_only || horde); + for (uint32 id : AlwaysAuraEffects(a)) + { + if (a.kind == AlwaysKind::Stone) + { + // The temporary enchantment on the main hand (a stone lasts an hour; two here, so it is not renewed every tick). + Item* mh = p_->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND); + if (!mh) continue; + uint32 const now = mh->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT); + if (on ? now != 0 : now != id) continue; // already on / another oil or stone is on / ours is not there to take off + p_->ApplyEnchantment(mh, TEMP_ENCHANTMENT_SLOT, false); + mh->SetEnchantment(TEMP_ENCHANTMENT_SLOT, on ? id : 0, on ? 2u * 60u * 60u * 1000u : 0u, 0); + p_->ApplyEnchantment(mh, TEMP_ENCHANTMENT_SLOT, true); + changed += (on ? " +enchant " : " -enchant ") + std::to_string(id); + } + else if (on) + { + if (!p_->HasAura(id) && p_->AddAura(id, p_)) + changed += " +" + std::to_string(id); + } + else if (p_->HasAura(id)) + { + p_->RemoveAurasDueToSpell(id); + changed += " -" + std::to_string(id); + } + } + }; + for (AlwaysAura const& a : kWorldBuffs) row(a); + for (uint8 b = 0; b < kBuffSetCount; ++b) + if (b == set || !(mask & (kAlwaysMaskConsumables | kAlwaysMaskWorldBuffs))) // the other roles' rows only to strip them + for (AlwaysAura const& a : AlwaysBuffRoleRows(BuffSet(b))) row(a); + if (mask & kAlwaysMaskRepair) + { + // Gear never wears out and the bot is never broke: a full repair at no cost, and the gold back up to the floor. + for (uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot) + if (Item* it = p_->GetItemByPos(INVENTORY_SLOT_BAG_0, slot)) + if (*it->m_itemData->MaxDurability && *it->m_itemData->Durability < *it->m_itemData->MaxDurability) + { + p_->DurabilityRepairAll(/*takeCost*/ false, 0.0f, /*guildBank*/ false); + changed += " +repair"; + break; + } + uint64 const floor = uint64(kAlwaysGoldFloor) * 10000ull; // copper per gold + if (p_->GetMoney() < floor) + { + p_->SetMoney(floor); + changed += " +gold"; + } + } + if (!changed.empty()) + TC_LOG_INFO("playerbot.v2", "[always_buff] {} mask {}{}", p_->GetName(), uint32(mask), changed); + return changed.empty() ? Result::NotKnown : Result::Ok; +} + Result API::cancel_aura(uint32 spell_id) { if (!p_) return Result::Other; @@ -3522,7 +4023,7 @@ Result API::toggle_pvp() Result API::add_friend(std::string const& name, std::string const& note) { // Mirrors HandleAddFriendOpcode but synchronous (no async DB callback for - // GM-permission lookup — bots use the cached AccountId directly). + // GM-permission lookup — bots use the cached AccountId directly). if (!p_) return Result::Other; std::string normalized = name; if (!normalizePlayerName(normalized)) return Result::InvalidTarget; @@ -3541,7 +4042,7 @@ Result API::add_friend(std::string const& name, std::string const& note) Result API::remove_friend(ObjectGuid friend_guid) { - // Mirrors HandleDelFriendOpcode. RemoveFromSocialList is permissive — if + // Mirrors HandleDelFriendOpcode. RemoveFromSocialList is permissive — if // the guid isn't on the list it's a no-op. Returns Ok for both branches. if (!p_) return Result::Other; if (friend_guid.IsEmpty()) return Result::InvalidTarget; @@ -3578,7 +4079,7 @@ Result API::mail_send_money(std::string const& recipient_name, uint64 copper, { // Mirrors HandleSendMail's money-only path. Sender bears the 30c flat // postage fee; total = postage + copper. Bot must have enough money. - // Recipient is resolved via CharacterCache (cache miss → InvalidTarget). + // Recipient is resolved via CharacterCache (cache miss → InvalidTarget). if (!p_) return Result::Other; std::string normalized = recipient_name; if (!normalizePlayerName(normalized)) return Result::InvalidTarget; @@ -3670,7 +4171,7 @@ Result API::mail_send_item(std::string const& recipient_name, ObjectGuid item_gu if (!attachment) { CharacterDatabase.CommitTransaction(trans); // releases the empty txn - p_->ModifyMoney(static_cast(cost)); // refund — clone failed + p_->ModifyMoney(static_cast(cost)); // refund — clone failed return Result::Other; } item->SetCount(item->GetCount() - count); @@ -3748,11 +4249,61 @@ Result API::face_target(ObjectGuid target, bool combat) ClearStaleMoveFlags(p_); if (p_->isMoving() || !p_->movespline->Finalized() || p_->HasUnitState(UNIT_STATE_LOST_CONTROL | UNIT_STATE_STUNNED) || p_->GetCurrentSpell(CURRENT_CHANNELED_SPELL) || p_->HasUnitState(UNIT_STATE_CASTING)) + { + // The caller logs "refaced" for every request it sends, so a bot the core never turns (damage_parity 166: a priest 90 degrees + // off its dummy for 3 minutes, 84 "refaced" lines, 5 s of casting) is told apart from a turned one by this line. + static std::mutex sLockedLogMutex; + static std::unordered_map sLockedLog; + uint32 const now = getMSTime(); + bool log_now = false; + { + std::lock_guard lock(sLockedLogMutex); + if (sLockedLog.size() > 4096) + sLockedLog.clear(); + uint32& last = sLockedLog[p_->GetGUID().GetCounter()]; + if (!last || now - last > 5000u) + { + last = now; + log_now = true; + } + } + if (log_now) + TC_LOG_INFO("playerbot.v2", "[face_locked] {} cannot be turned to {}: moving {} flags 0x{:X} spline_finalized {} spline_left {} ms generator {} lost_control {} stunned {} channeling {} casting_state {}", + p_->GetName(), u->GetName(), int(p_->isMoving()), uint32(p_->GetUnitMovementFlags()), int(p_->movespline->Finalized()), p_->movespline->timeRemaining(), + int(p_->GetMotionMaster()->GetCurrentMovementGeneratorType()), int(p_->HasUnitState(UNIT_STATE_LOST_CONTROL)), int(p_->HasUnitState(UNIT_STATE_STUNNED)), + int(p_->GetCurrentSpell(CURRENT_CHANNELED_SPELL) != nullptr), int(p_->HasUnitState(UNIT_STATE_CASTING))); return Result::Locked; + } float const off = Position::NormalizeOrientation(p_->GetOrientation() - p_->GetAbsoluteAngle(u)); if (off < 0.1f || off > 2.0f * float(M_PI) - 0.1f) return Result::Ok; + float const before = p_->GetOrientation(); p_->SetFacingToPoint(u->GetPosition(), /*force*/ true); + // A turn the core accepted but did not apply (damage_parity 189: a priest 90 degrees off its dummy for a whole leg, no refusal logged) + // leaves this line behind: the orientation before and after, the bearing wanted and the states that stop a unit turning. + float const after_off = Position::NormalizeOrientation(p_->GetOrientation() - p_->GetAbsoluteAngle(u)); + if (after_off > 0.1f && after_off < 2.0f * float(M_PI) - 0.1f) + { + static std::mutex sTurnLogMutex; + static std::unordered_map sTurnLog; + uint32 const now = getMSTime(); + bool log_now = false; + { + std::lock_guard lock(sTurnLogMutex); + if (sTurnLog.size() > 4096) + sTurnLog.clear(); + uint32& last = sTurnLog[p_->GetGUID().GetCounter()]; + if (!last || now - last > 5000u) + { + last = now; + log_now = true; + } + } + if (log_now) + TC_LOG_INFO("playerbot.v2", "[face_not_applied] {} asked to face {}: orientation {:.2f} -> {:.2f}, wanted {:.2f}, spline_finalized {} cannot_turn {} root {} on_transport {}", + p_->GetName(), u->GetName(), before, p_->GetOrientation(), p_->GetAbsoluteAngle(u), int(p_->movespline->Finalized()), int(p_->HasUnitState(UNIT_STATE_CANNOT_TURN)), int(p_->HasUnitState(UNIT_STATE_ROOT)), + int(p_->GetTransport() != nullptr)); + } return Result::Ok; } // Already facing it (within ~0.1 rad) and standing still: nothing to do. @@ -3827,7 +4378,7 @@ Result API::raid_chat(std::string const& text) namespace { // SC-P3a: resolve the racial language for spoken SAY/YELL so bot chatter // renders in faction script (Common/Orcish, garbled cross-faction) exactly -// like a real player's — instead of LANG_UNIVERSAL, which every faction can +// like a real player's — instead of LANG_UNIVERSAL, which every faction can // read and which the client tags as GM/system speech. A team-based default // is used (every member of a faction knows that faction's base language and // passes the core HasSkill check): Alliance -> Common, Horde -> Orcish. @@ -3877,7 +4428,7 @@ Result API::release_corpse() if (!p_) return Result::Other; if (p_->IsAlive()) { - TC_LOG_DEBUG("playerbot.api", "[API::release_corpse] {} already alive — noop", + TC_LOG_DEBUG("playerbot.api", "[API::release_corpse] {} already alive — noop", p_->GetName()); return Result::Ok; } @@ -3930,12 +4481,12 @@ Result API::release_corpse() p_->GetMotionMaster()->MovePoint(0, nearest->GetPositionX(), nearest->GetPositionY(), nearest->GetPositionZ(), /*generatePath*/ true); } } - TC_LOG_DEBUG("playerbot.api", "[API::release_corpse] {} already released (ghost + corpse) — noop", + TC_LOG_DEBUG("playerbot.api", "[API::release_corpse] {} already released (ghost + corpse) — noop", p_->GetName()); return Result::Ok; } TC_LOG_INFO("playerbot.api", - "[API::release_corpse] {} dead with STALE corpse at ({:.1f},{:.1f},{:.1f}) map {} and no ghost state — " + "[API::release_corpse] {} dead with STALE corpse at ({:.1f},{:.1f},{:.1f}) map {} and no ghost state — " "retiring bones and repopping", p_->GetName(), p_->GetCorpseLocation().GetPositionX(), @@ -3944,11 +4495,11 @@ Result API::release_corpse() uint32(p_->GetCorpseLocation().GetMapId())); p_->SpawnCorpseBones(); } - TC_LOG_DEBUG("playerbot.api", "[API::release_corpse] {} releasing — BuildPlayerRepop + RepopAtGraveyard from ({:.1f},{:.1f},{:.1f})", + TC_LOG_DEBUG("playerbot.api", "[API::release_corpse] {} releasing — BuildPlayerRepop + RepopAtGraveyard from ({:.1f},{:.1f},{:.1f})", p_->GetName(), p_->GetPositionX(), p_->GetPositionY(), p_->GetPositionZ()); p_->BuildPlayerRepop(); p_->RepopAtGraveyard(); - TC_LOG_DEBUG("playerbot.api", "[API::release_corpse] {} after release — alive={} hasCorpse={} pos=({:.1f},{:.1f},{:.1f})", + TC_LOG_DEBUG("playerbot.api", "[API::release_corpse] {} after release — alive={} hasCorpse={} pos=({:.1f},{:.1f},{:.1f})", p_->GetName(), p_->IsAlive(), p_->HasCorpse(), p_->GetPositionX(), p_->GetPositionY(), p_->GetPositionZ()); return Result::Ok; @@ -3959,12 +4510,12 @@ Result API::revive_at_corpse() if (!p_) return Result::Other; if (p_->IsAlive()) { - TC_LOG_DEBUG("playerbot.api", "[API::revive_at_corpse] {} already alive — noop", p_->GetName()); + TC_LOG_DEBUG("playerbot.api", "[API::revive_at_corpse] {} already alive — noop", p_->GetName()); return Result::Ok; } if (!p_->HasCorpse()) { - TC_LOG_DEBUG("playerbot.api", "[API::revive_at_corpse] {} no corpse — Locked. pos=({:.1f},{:.1f},{:.1f})", + TC_LOG_DEBUG("playerbot.api", "[API::revive_at_corpse] {} no corpse — Locked. pos=({:.1f},{:.1f},{:.1f})", p_->GetName(), p_->GetPositionX(), p_->GetPositionY(), p_->GetPositionZ()); return Result::Locked; } @@ -3972,7 +4523,7 @@ Result API::revive_at_corpse() p_->GetName(), p_->GetPositionX(), p_->GetPositionY(), p_->GetPositionZ()); // Mirror WorldSession::HandleReclaimCorpse: 50% restore (retail corpse- // run penalty) and SpawnCorpseBones to retire the corpse object. The old - // code skipped SpawnCorpseBones, so the corpse SURVIVED the revival — and + // code skipped SpawnCorpseBones, so the corpse SURVIVED the revival — and // on the bot's NEXT death release_corpse saw HasCorpse() and no-op'd // forever (BuildPlayerRepop also refuses while a same-map corpse exists), // leaving the bot wedged in dead:waiting_release for hours (verified @@ -3985,27 +4536,27 @@ Result API::revive_at_corpse() // Mirrors WorldSession::HandleReclaimCorpse (MiscHandler.cpp:417). Called // from State_Dead's corpse-run path when the bot has walked back to its // corpse and is within reclaim radius. ResurrectPlayer is invoked with -// applySickness=false (the default) — the corpse-run is the canonical +// applySickness=false (the default) — the corpse-run is the canonical // no-sickness path. SpawnCorpseBones cleans up the corpse marker. Result API::reclaim_corpse() { if (!p_) return Result::Other; if (p_->IsAlive()) { - TC_LOG_DEBUG("playerbot.api", "[API::reclaim_corpse] {} already alive — noop", p_->GetName()); + TC_LOG_DEBUG("playerbot.api", "[API::reclaim_corpse] {} already alive — noop", p_->GetName()); return Result::Ok; } if (p_->InArena()) return Result::Locked; if (!p_->HasPlayerFlag(PLAYER_FLAGS_GHOST)) { - TC_LOG_DEBUG("playerbot.api", "[API::reclaim_corpse] {} not ghost (release_corpse first) — Locked", + TC_LOG_DEBUG("playerbot.api", "[API::reclaim_corpse] {} not ghost (release_corpse first) — Locked", p_->GetName()); return Result::Locked; } Corpse* corpse = p_->GetCorpse(); if (!corpse) { - TC_LOG_DEBUG("playerbot.api", "[API::reclaim_corpse] {} no corpse — Locked", p_->GetName()); + TC_LOG_DEBUG("playerbot.api", "[API::reclaim_corpse] {} no corpse — Locked", p_->GetName()); return Result::Locked; } const bool pvp = corpse->GetType() == CORPSE_RESURRECTABLE_PVP; @@ -4016,7 +4567,7 @@ Result API::reclaim_corpse() } // Distinguish cross-Map corpse from same-map-too-far. The previous // "0.0y > 39y" log line was the symptom of bot+corpse on the same - // map_id but different Map* (continent ↔ instance with same parent + // map_id but different Map* (continent ↔ instance with same parent // map_id, e.g., Stormwind sewers / Naxx / etc), which IsWithinDistInMap // rejects because Map* pointers differ. The State_Dead cross-map // gate only compares map_id so this case slips through. Returning @@ -4024,14 +4575,14 @@ Result API::reclaim_corpse() if (corpse->GetMap() != p_->GetMap()) { TC_LOG_DEBUG("playerbot.api", - "[API::reclaim_corpse] {} corpse on different Map* (mapId={}↔{}) — OutOfRange", + "[API::reclaim_corpse] {} corpse on different Map* (mapId={}↔{}) — OutOfRange", p_->GetName(), p_->GetMapId(), corpse->GetMapId()); return Result::OutOfRange; } if (!corpse->IsWithinDistInMap(p_, CORPSE_RECLAIM_RADIUS, true)) { const float d = p_->GetDistance2d(corpse); - TC_LOG_DEBUG("playerbot.api", "[API::reclaim_corpse] {} corpse too far ({:.1f}y > {}y) — OutOfRange", + TC_LOG_DEBUG("playerbot.api", "[API::reclaim_corpse] {} corpse too far ({:.1f}y > {}y) — OutOfRange", p_->GetName(), d, CORPSE_RECLAIM_RADIUS); return Result::OutOfRange; } @@ -4105,14 +4656,14 @@ Result API::enter_area_trigger(uint32 area_trigger_id) // real corpse-run impractical. applySickness=true applies the standard // resurrection sickness (level-scaled; none below 11), and DurabilityLossAll // matches the 25% gear hit a real spirit-healer rez incurs. We skip the -// SpiritHealerActivate NPC validation — State_Dead has already chosen this +// SpiritHealerActivate NPC validation — State_Dead has already chosen this // path; there's no NPC to interact with for a headless bot. Result API::spirit_resurrect() { if (!p_) return Result::Other; if (p_->IsAlive()) { - TC_LOG_DEBUG("playerbot.api", "[API::spirit_resurrect] {} already alive — noop", p_->GetName()); + TC_LOG_DEBUG("playerbot.api", "[API::spirit_resurrect] {} already alive — noop", p_->GetName()); return Result::Ok; } // Ensure the bot has released first; the spirit-healer flow assumes the @@ -4184,7 +4735,7 @@ Result API::accept_summon() // once per pending request. p_->SummonIfPossible(true); // Post-summon snap. SummonIfPossible teleports to the summoner's - // last-reported position — which may sit slightly off-mesh (summoner + // last-reported position — which may sit slightly off-mesh (summoner // moved between the summon cast and the bot accept) or inside an // instance portal that hasn't fully geometry-resolved. The probe is // cheap when the landing is fine. @@ -4309,7 +4860,8 @@ Result API::trade_with(ObjectGuid owner, bool gift_ok) } Player* trader = mine->GetTrader(); TradeData* his = trader ? trader->GetTradeData() : nullptr; - if (!trader || !his || trader->GetGUID() != owner) + // A scenario test character's test gear never changes hands (BotAI declines its trades; this is the last gate). + if (!trader || !his || trader->GetGUID() != owner || ::Playerbot::Pool::IsScenarioBot(me)) { s_trade_seen.erase(me); p_->TradeCancel(true); @@ -4376,10 +4928,10 @@ Result API::invite_to_group(ObjectGuid target_player) if (!invitee) return Result::InvalidTarget; // Faction gate matches HandlePartyInviteOpcode unless cross-faction // grouping is enabled server-wide. We're conservative and refuse the - // cross-faction case rather than relying on the world config — bot + // cross-faction case rather than relying on the world config — bot // packs that party with opposing faction would be a PvP-server bug. if (p_->GetTeam() != invitee->GetTeam()) return Result::InvalidTarget; - // Already-grouped target → server would reject; surface up-front. + // Already-grouped target → server would reject; surface up-front. if (invitee->GetGroup() || invitee->GetGroupInvite()) return Result::Locked; if (invitee->GetSocial() && @@ -4399,7 +4951,7 @@ Result API::invite_to_group(ObjectGuid target_player) } else { - // No group yet — create one with the bot as leader-invitee. Same + // No group yet — create one with the bot as leader-invitee. Same // shape as the player path: not committed to DB until the invitee // accepts. Memory leaked back to the heap if the invitee declines // is reclaimed via Group::RemoveAllInvites + delete in that path. @@ -4554,9 +5106,9 @@ Result API::accept_guild_invite() Result API::decline_guild_invite() { // Mirrors HandleGuildDeclineInvitation: clearing GuildIdInvited drops the - // pending invite. Idempotent — already-cleared state still returns Ok. + // pending invite. Idempotent — already-cleared state still returns Ok. if (!p_) return Result::Other; - if (p_->GetGuildId()) return Result::Ok; // Already in a guild — invite is moot. + if (p_->GetGuildId()) return Result::Ok; // Already in a guild — invite is moot. p_->SetGuildIdInvited(UI64LIT(0)); return Result::Ok; } @@ -4678,15 +5230,27 @@ Result API::pet_attack(ObjectGuid target) } Unit* victim = ObjectAccessor::GetUnit(*p_, target); if (!victim || !victim->IsAlive()) return Result::InvalidTarget; - // PET_ACTION_ATTACK semantics: enable attack mode + start attacking the - // selected target. Mirrors what the client emits for the pet bar attack - // button. - pet->SetReactState(REACT_AGGRESSIVE); - pet->GetCharmInfo()->SetIsCommandAttack(true); - pet->GetCharmInfo()->SetIsAtStay(false); - pet->GetCharmInfo()->SetIsFollowing(false); - pet->GetCharmInfo()->SetIsReturning(false); - pet->ToCreature()->AI()->AttackStart(victim); + // COMMAND_ATTACK semantics, as the pet bar Attack button (PetHandler): + // the react state is left alone, so a Passive pet attacks this target + // only and goes back to its owner when it dies instead of pulling + // whatever is near. A pet on another live target is stopped first, since + // PetAI::AttackStart will not switch off a live victim. + CharmInfo* ci = pet->GetCharmInfo(); + if (!ci) return Result::Other; + if (pet->GetVictim() != victim || !ci->IsCommandAttack()) + { + if (pet->GetVictim()) + pet->AttackStop(); + ci->SetIsCommandAttack(true); + ci->SetIsAtStay(false); + ci->SetIsFollowing(false); + ci->SetIsCommandFollow(false); + ci->SetIsReturning(false); + if (PetAI* petAI = dynamic_cast(pet->AI())) + petAI->_AttackStart(victim); + else + pet->AI()->AttackStart(victim); + } return Result::Ok; } @@ -4731,7 +5295,7 @@ Result API::pet_cast(uint32 spell_id, ObjectGuid target) } SpellInfo const* spell = sSpellMgr->GetSpellInfo(spell_id, DIFFICULTY_NONE); if (!spell) return Result::Other; - // Pet must actually know the spell — otherwise the cast just fails + // Pet must actually know the spell — otherwise the cast just fails // silently server-side. HasSpell on the pet checks both the inherited // creature template spells and any taught (Hunter/DK) abilities. if (!pet->HasSpell(spell_id)) return Result::Locked; @@ -4743,7 +5307,7 @@ Result API::pet_cast(uint32 spell_id, ObjectGuid target) victim = ObjectAccessor::GetUnit(*p_, target); if (!victim) return Result::InvalidTarget; } - // Cast as the pet's caster — interrupts (Spell Lock) require a target; + // Cast as the pet's caster — interrupts (Spell Lock) require a target; // self-buffs / pet abilities don't. SpellCastTargets targets; if (victim) targets.SetUnitTarget(victim); @@ -4774,11 +5338,11 @@ Result API::dismiss_pet() // ---- Hunter pet stable ------------------------------------------------- // // Background: in retail Cataclysm-onwards, the stable owns three flavors of -// pet — active (in slots 0..MAX_ACTIVE_PETS-1), stabled (slots +// pet — active (in slots 0..MAX_ACTIVE_PETS-1), stabled (slots // PET_SAVE_FIRST_STABLE_SLOT..PET_SAVE_LAST_STABLE_SLOT-1), and unslotted // (PET_SAVE_NOT_IN_SLOT, kept around for re-summon by spell). The gossip / // stablemaster flow validates an interact range with the stable NPC. The -// bot path here intentionally bypasses the NPC range check — when running +// bot path here intentionally bypasses the NPC range check — when running // autonomously we want the bot logic to swap pets based on encounter (e.g. swap // to a stabled tank pet for a tough pull) without first dragging the bot // to a stablemaster. All other invariants (HUNTER_PET-only, exotic-tame @@ -4811,7 +5375,7 @@ Result API::swap_pet_to_slot(uint32 pet_number, uint8 dst_slot) const bool dstStabled = IsStabledPetSlot(dstSlotMode); if (srcActive != IsActivePetSlot(dstSlotMode)) { - // Cross-region swap will despawn the active pet — must be alive. + // Cross-region swap will despawn the active pet — must be alive. if (Pet* live = p_->GetPet()) if (!live->IsAlive() && (srcActive || dstStabled)) return Result::ServerRefused; @@ -4842,7 +5406,7 @@ Result API::delete_stabled_pet(uint32 pet_number) PetStable* stable = p_->GetPetStable(); if (!stable) return Result::NotKnown; - // Refuse to delete the currently summoned pet — caller must dismiss + // Refuse to delete the currently summoned pet — caller must dismiss // first. Without this guard, DeletePetFromDB would yank the row from // under a live Pet*, leaving a dangling summon that crashes on the // next pet-tick (CharmInfo lookup against a deleted row). @@ -4852,7 +5416,7 @@ Result API::delete_stabled_pet(uint32 pet_number) return Result::Locked; // Also refuse if the pet is the current ActivePet entry (even if not - // physically summoned right now — e.g. unsummoned for flying mount). + // physically summoned right now — e.g. unsummoned for flying mount). // In that case the summon path would re-resurrect a deleted DB row. if (PetStable::PetInfo const* current = stable->GetCurrentPet()) if (current->PetNumber == pet_number) @@ -4876,10 +5440,10 @@ Result API::summon_pet_by_number(uint32 pet_number) if (p_->HasUnitState(UNIT_STATE_CASTING)) return Result::ServerRefused; PetStable* stable = p_->GetPetStable(); if (!stable) return Result::NotKnown; - // A pet is already up — caller must dismiss first. + // A pet is already up — caller must dismiss first. if (p_->GetPet()) return Result::Locked; - // Locate pet across active slots only — stabled pets must be moved + // Locate pet across active slots only — stabled pets must be moved // to an active slot first via swap_pet_to_slot. This matches the // CALL_PET_SPELL_ID semantics: it loads from active-slot bank. auto [srcPet, srcSlot] = Pet::GetLoadPetInfo(*stable, 0, pet_number, {}); @@ -4921,7 +5485,7 @@ Result API::feed_pet(uint32 food_item_entry) // Note: pet level vs food level happiness math lives in // SPELL_EFFECT_FEED_PET; we don't pre-gate it here. Casting Feed Pet // on too-low food still consumes the item but yields zero happiness, - // matching live behavior — caller is responsible for filtering food + // matching live behavior — caller is responsible for filtering food // by ItemTemplate::ItemLevel vs Pet::GetLevel before issuing. // Cast Feed Pet on the pet itself; the spell handler consumes the @@ -4942,7 +5506,7 @@ Result API::abandon_pet() if (pet->getPetType() != HUNTER_PET) return Result::InvalidTarget; if (p_->IsInCombat()) return Result::ServerRefused; - // PET_SAVE_AS_DELETED is the canonical untame path — RemovePet handles + // PET_SAVE_AS_DELETED is the canonical untame path — RemovePet handles // updatefield purge, character_pet row delete, and tame-skill bookkeeping. p_->RemovePet(pet, PET_SAVE_AS_DELETED); return Result::Ok; @@ -4956,7 +5520,7 @@ Result API::pet_set_react_state(uint8 state) if (state > REACT_ASSIST) return Result::InvalidTarget; // Pet inherits Creature::SetReactState (Unit-level state), and PetAI // re-reads it on the next tick. CharmInfo doesn't store react state in - // 12.0 — the master copy is on Unit (UnitAI::ReactState). + // 12.0 — the master copy is on Unit (UnitAI::ReactState). pet->SetReactState(static_cast(state)); return Result::Ok; } @@ -5049,7 +5613,7 @@ Result API::pet_set_command_state(uint8 command) // Use pet_attack(target) for the actual attack-with-target // semantics. Setting the command without a target is a no-op // mirror of the pet bar's attack button when nothing is - // selected — surface InvalidTarget so the caller routes + // selected — surface InvalidTarget so the caller routes // through pet_attack instead. return Result::InvalidTarget; default: @@ -5096,49 +5660,49 @@ static bool BotWantsTradeGoodsSubclass(Player const* p, uint32 subclass) auto has = [p](uint32 skill) { return p->HasSkill(uint16(skill)); }; switch (subclass) { - // PARTS / EXPLOSIVES / DEVICES / EXPLOSIVES_DEVICES — Engineering + // PARTS / EXPLOSIVES / DEVICES / EXPLOSIVES_DEVICES — Engineering case 1: case 2: case 3: case 17: return has(202); - // JEWELCRAFTING (gems) — Jewelcrafting + // JEWELCRAFTING (gems) — Jewelcrafting case 4: return has(755); - // CLOTH — Tailoring (First Aid was removed in BfA) + // CLOTH — Tailoring (First Aid was removed in BfA) case 5: return has(197); - // LEATHER — Leatherworking + // LEATHER — Leatherworking case 6: return has(165); - // METAL_AND_STONE — Mining/Blacksmithing/Engineering/Jewelcrafting + // METAL_AND_STONE — Mining/Blacksmithing/Engineering/Jewelcrafting case 7: return has(186) || has(164) || has(202) || has(755); - // MEAT — Cooking. Includes raw fish (TC classifies raw fish meat + // MEAT — Cooking. Includes raw fish (TC classifies raw fish meat // as TRADE_GOODS subclass 8; cooked fish meals are CONSUMABLE // class entirely and never reach this filter). Cooking is granted // to every bot at L10+ in DoLearnProfessions, so this branch // mostly returns true. case 8: return has(185); - // HERB — Herbalism/Alchemy/Inscription + // HERB — Herbalism/Alchemy/Inscription case 9: return has(182) || has(171) || has(773); - // ELEMENTAL — multiple crafting professions; conservative-keep when + // ELEMENTAL — multiple crafting professions; conservative-keep when // any is trained. case 10: return has(164) || has(165) || has(171) || has(197) || has(202) || has(333) || has(755) || has(773); - // ENCHANTING (dust / essence / shard) — Enchanting. Subclass 12 + // ENCHANTING (dust / essence / shard) — Enchanting. Subclass 12 // (ITEM_SUBCLASS_ENCHANTING). Subclass 15 is - // WEAPON_ENCHANTMENT (oils, sharpening stones) — those are + // WEAPON_ENCHANTMENT (oils, sharpening stones) — those are // enchanting outputs / general consumables, not enchanter mats, // so we don't auto-keep them on enchanter classes. case 12: return has(333); - // INSCRIPTION (pigment / ink) — Inscription + // INSCRIPTION (pigment / ink) — Inscription case 16: return has(773); // 0 GENERIC, 11 TRADE_GOODS_OTHER, 13 MATERIAL, 14 ENCHANTMENT, // 15 WEAPON_ENCHANTMENT, 17+ EXPLOSIVES_DEVICES / OPTIONAL_REAGENT - // — no specific profession ownership; default keep. + // — no specific profession ownership; default keep. default: return true; } @@ -5146,7 +5710,7 @@ static bool BotWantsTradeGoodsSubclass(Player const* p, uint32 subclass) // Count empty inventory slots across the backpack (INVENTORY_SLOT_ITEM_*) and // the equipped bags (INVENTORY_SLOT_BAG_*). Profession bags only count free -// slots that the candidate item could actually occupy is NOT modelled here — +// slots that the candidate item could actually occupy is NOT modelled here — // this is a coarse "how tight are bags" gauge used to gate the BoE-clearance // branch below, not a precise can-store test (SellItemToVendor / the rule do // that). A non-bag backpack slot that is empty counts; a bag's empty cells @@ -5165,12 +5729,12 @@ static uint32 CountFreeBagSlots(Player const* p) // True when a Bind-on-Equip uncommon armor/weapon in the bag is "clearly // vendor trash" for THIS bot and may be sold under bag pressure when no -// auctioneer is reachable. Conservative by construction — every protection +// auctioneer is reachable. Conservative by construction — every protection // the backlog calls out is enforced here: -// * quest items (class QUEST / BIND_QUEST / StartQuest) — kept -// * heirlooms / account-bound (any BIND_*ACCOUNT*, ITEM_QUALITY_HEIRLOOM) — kept -// * current upgrades (would beat or fill the bot's equipped slot) — kept -// * anything bound that's an upgrade — kept (the upgrade test runs regardless +// * quest items (class QUEST / BIND_QUEST / StartQuest) — kept +// * heirlooms / account-bound (any BIND_*ACCOUNT*, ITEM_QUALITY_HEIRLOOM) — kept +// * current upgrades (would beat or fill the bot's equipped slot) — kept +// * anything bound that's an upgrade — kept (the upgrade test runs regardless // of bind state; BoP-but-better never reaches this branch because it's an // upgrade, and we only consider BoE here anyway) // Only genuine low-ilvl greens the bot has clearly outgrown clear out. @@ -5178,7 +5742,7 @@ static bool BotShouldVendorBoeGreen(Player* p, Item* it, ItemTemplate const* tmp { if (!p || !it || !tmpl) return false; - // Only Uncommon (green) — Rare/Epic BoE are real AH/bank candidates, never + // Only Uncommon (green) — Rare/Epic BoE are real AH/bank candidates, never // auto-vendored by this branch. if (tmpl->GetQuality() != ITEM_QUALITY_UNCOMMON) return false; @@ -5203,7 +5767,7 @@ static bool BotShouldVendorBoeGreen(Player* p, Item* it, ItemTemplate const* tmp tmpl->GetStartQuest() != 0) return false; - // Heirloom / account-bound protection — mail to alts, never vendor. + // Heirloom / account-bound protection — mail to alts, never vendor. if (tmpl->GetQuality() == ITEM_QUALITY_HEIRLOOM || tmpl->GetBonding() == BIND_BNET_ACCOUNT || tmpl->GetBonding() == BIND_BNET_ACCOUNT_UNTIL_EQUIPPED || @@ -5223,7 +5787,7 @@ static bool BotShouldVendorBoeGreen(Player* p, Item* it, ItemTemplate const* tmp // // empty slots. int32 const new_ilvl = static_cast(tmpl->GetBaseItemLevel()); - // Upgrade protection — the decisive gate. Resolve which equip slot this + // Upgrade protection — the decisive gate. Resolve which equip slot this // item would land in for THIS bot; if the slot is empty (would be a strict // gain) or the candidate scores at least as well as / out-ilvls the current // item, it is NOT trash. Mirrors ScoreQuestReward's slot-resolution path. @@ -5237,7 +5801,7 @@ static bool BotShouldVendorBoeGreen(Player* p, Item* it, ItemTemplate const* tmp { Item const* cur = p->GetItemByPos(INVENTORY_SLOT_BAG_0, equip_slot); if (!cur) - return false; // empty usable slot — keep, it's a gain + return false; // empty usable slot — keep, it's a gain ItemTemplate const* cur_tmpl = cur->GetTemplate(); int32 const cur_ilvl = cur_tmpl ? static_cast(cur_tmpl->GetBaseItemLevel()) : 0; @@ -5246,13 +5810,13 @@ static bool BotShouldVendorBoeGreen(Player* p, Item* it, ItemTemplate const* tmp // marginal sidegrades safe. constexpr int32 kIlvlSlack = 10; if (new_ilvl >= cur_ilvl - kIlvlSlack) - return false; // potential upgrade / sidegrade — keep + return false; // potential upgrade / sidegrade — keep } - // equip_slot out of range — falls through to "vendor" (can't be worn). + // equip_slot out of range — falls through to "vendor" (can't be worn). } // CanEquipNewItem != OK: the bot physically can't wear it (wrong class / // armor type / level). A green it can never equip and can't AH (no - // auctioneer) is bag rot — clear it. + // auctioneer) is bag rot — clear it. return true; } @@ -5273,7 +5837,7 @@ static bool IsBagRot(Player* p, Item* it, ItemTemplate const* tmpl, bool bags_ti { return true; } - // Soulbound BoP weapons/armor the bot can't equip — bag rot. + // Soulbound BoP weapons/armor the bot can't equip — bag rot. // Quest rewards offer 2-3 slots, bot picks one, but loot rolls // on BoP items the bot is ineligible for still accumulate (per // ITEM_VENDOR_SYSTEM_PLAN.md). These can never be auctioned @@ -5287,7 +5851,7 @@ static bool IsBagRot(Player* p, Item* it, ItemTemplate const* tmpl, bool bags_ti // ITEM_QUALITY_HEIRLOOM, equivalent in modern client) are // account-bound and should be preserved for alts. If the bot // can't use it now, mailing it to alts via the JIT mail system - // is the right disposition — never vendor. Audit 2026-05-22: + // is the right disposition — never vendor. Audit 2026-05-22: // current code would happily vendor a class-wrong heirloom // because it passes the `IsSoulBound() && CanUseItem != OK` // check. @@ -5302,7 +5866,7 @@ static bool IsBagRot(Player* p, Item* it, ItemTemplate const* tmpl, bool bags_ti && tmpl->GetBonding() != BIND_WOW_ACCOUNT && tmpl->GetBonding() != BIND_QUEST) { - // Only sell ITEMS IN BAGS, never equipped slots — same gate + // Only sell ITEMS IN BAGS, never equipped slots — same gate // the inventory iterator already implies (Inventory location) // but explicit for clarity. return true; @@ -5324,13 +5888,13 @@ Result API::sell_trash(ObjectGuid npc) if (!vendor) return Result::InvalidTarget; // Iterate inventory and main bags. Sell: - // 1) Every Poor (grey) item — vendor trash baseline. + // 1) Every Poor (grey) item — vendor trash baseline. // 2) Trade-goods (item class 7) of any quality where the subclass // doesn't match a profession the bot trained. A Mining bot in // possession of Light Leather has no use for it; freeing that // bag slot for ore is the right call. Quality bound at COMMON // (white) so we don't accidentally vendor an Uncommon+ mat that - // a teammate might want — those go to the auction house path + // a teammate might want — those go to the auction house path // when that lands. // 4) Under BAG PRESSURE only: Bind-on-Equip Uncommon (green) gear the // bot has clearly outgrown and can't equip, when bags are tight and @@ -5340,11 +5904,11 @@ Result API::sell_trash(ObjectGuid npc) // Quest-flagged items are skipped (vendor refuses them anyway). // // Bag-pressure gate for branch (4). Greens are real AH money, so we only - // vendor them when the bot is genuinely cramped — otherwise it keeps them + // vendor them when the bot is genuinely cramped — otherwise it keeps them // for the auction-house disposition. Threshold: 3 or fewer free slots. // // // L-P2a: needs an "auctioneer reachable / AH-flagged" signal to fully - // // honour the "no auctioneer accessible" condition — that lives in the V2 + // // honour the "no auctioneer accessible" condition — that lives in the V2 // // rule layer (AuctionRules), not on the live Player. sell_trash only // // receives a vendor NPC, so we approximate with bag pressure: the rule // // layer only invokes the BoE-clearance path when it has already decided @@ -5422,12 +5986,12 @@ Result API::repair_all(ObjectGuid npc, bool from_guild_bank) { if (!p_) return Result::Other; // Self-repair (empty npc): no repair vendor required. Used by the dungeon - // gear-readiness rule — instances have NO repair NPC, yet a tank whose + // gear-readiness rule — instances have NO repair NPC, yet a tank whose // durability breaks mid-run (every death strips 10%) degrades into paper // (0% durability ~ halved armor/stats) and death-spirals (observed // 2026-06-28: Deadmines tank 38 deaths, durability 16264->12976 HP, never // reached the boss). Bots are bot logic and the player-money branch below already - // grants the shortfall as a stipend, so a self-repair is effectively free — + // grants the shortfall as a stipend, so a self-repair is effectively free — // exactly the intended "gold self-repair on dungeon staging/running". if (!npc.IsEmpty()) { @@ -5450,7 +6014,7 @@ Result API::repair_all(ObjectGuid npc, bool from_guild_bank) // item and, if the bot can't afford the whole bill, silently repairs NOTHING // (Player.cpp ~4827 `if (!HasEnoughMoney(totalCost)) return;`). A fresh, poor // low-level bot almost never affords a full repair, so that all-or-nothing - // gate stranded bots at 0% gear forever — a death spiral (broken gear -> can't + // gate stranded bots at 0% gear forever — a death spiral (broken gear -> can't // fight -> can't earn -> still can't afford the full repair). Observed: // Bramwell (L5, 224c) parked on top of Godric Rothgar, firing // idle:critical_repair every tick with durability never moving off 0%. @@ -5478,15 +6042,15 @@ Result API::repair_all(ObjectGuid npc, bool from_guild_bank) std::sort(repairables.begin(), repairables.end(), [](auto const& a, auto const& b) { return a.second < b.second; }); - // Repair-reserve top-up — SAME stipend pattern as the flight reserve at + // Repair-reserve top-up — SAME stipend pattern as the flight reserve at // fly_to_node (owner directive 2026-06-21). Bots are perpetually broke // (Morthan: 0% gear, ~20 silver); a poor low-level bot can't afford a full // repair, so the affordable-partial loop below leaves its costliest slots at - // 0% forever — the poverty death-spiral (broken gear -> can't fight -> can't + // 0% forever — the poverty death-spiral (broken gear -> can't fight -> can't // earn -> still can't repair). Grant the shortfall so a broke bot can always // fully repair (bots are bot logic; a free repair is fine and far cheaper than the // leveling time lost to a bot stranded at 0% gear). Solvent bots are - // unaffected — they already cover the bill, so no money is added. + // unaffected — they already cover the bill, so no money is added. { uint64 total_cost = 0; for (auto const& pr : repairables) total_cost += pr.second; @@ -5509,7 +6073,7 @@ Result API::repair_all(ObjectGuid npc, bool from_guild_bank) return any ? Result::Ok : Result::Locked; } -// Cast an item's ON_USE effect via Player::CastItemUseSpell — the same path +// Cast an item's ON_USE effect via Player::CastItemUseSpell — the same path // HandleUseItemOpcode uses. Going through cast_spell here would fail because // item-trigger spells (e.g. Food = 433 on Conjured Bread) aren't in the // player's spellbook, and cast_spell rejects them with NotKnown. The item @@ -5536,7 +6100,7 @@ static Result UseItemImpl(Player* p, Item* item, ObjectGuid target) if (Unit* tu = ObjectAccessor::GetUnit(*p, target)) { // Spellclick NPCs: when the quest target is a UNIT_NPC_FLAG_SPELLCLICK - // creature, "using the item on it" is, on a real client, a CMSG_SPELL_CLICK — + // creature, "using the item on it" is, on a real client, a CMSG_SPELL_CLICK — // Unit::HandleSpellClick both casts the click spell AND fires the creature's // OnSpellClick bot logic. That bot logic is what credits this whole class of quests // (e.g. Q26118: spellclick Ambassador Slaghammer 42146 -> SmartAI @@ -5579,11 +6143,42 @@ static Result UseItemImpl(Player* p, Item* item, ObjectGuid target) return Result::Ok; } +// Infinite food and water (Api/VirtualSupply.h): the bot has none of the Food / Water rank its recovery rules picked (bags full of +// gear and quest items), so it eats / drinks without the item: the item's on-use spell, cast like the item would, nothing consumed. +static Result UseVirtualSupply(Player* p, uint32 item_entry) +{ + bool water = false; + if (!Classic::UseVirtually(false, Services::Config().classic_class_supplies(), + Classic::IsVirtualRecoveryItem(item_entry, p->GetClass(), uint8(p->GetLevel()), water))) + return Result::InvalidTarget; + ItemTemplate const* proto = sObjectMgr->GetItemTemplate(item_entry); + if (!proto) + return Result::InvalidTarget; + uint32 spellId = 0; + for (ItemEffectEntry const* eff : proto->Effects) + if (eff->TriggerType == ITEM_SPELLTRIGGER_ON_USE && eff->SpellID > 0) + { + spellId = uint32(eff->SpellID); + break; + } + if (!spellId || !sSpellMgr->GetSpellInfo(spellId, DIFFICULTY_NONE)) + return Result::Other; + SpellCastResult const res = p->CastSpell(p, spellId, CastSpellExtraArgs(TRIGGERED_NONE)); + if (res != SPELL_CAST_OK) + return Result::Locked; + TC_LOG_INFO("playerbot.v2", "[supplies] {} {} without the item: {} ({}), none in the bags ({} free slots)", p->GetName(), + water ? "drinks" : "eats", item_entry, proto->GetName(sWorld->GetDefaultDbcLocale()), p->GetFreeInventorySlotCount()); + return Result::Ok; +} + Result API::use_item_by_entry(uint32 item_entry, ObjectGuid target) { if (!p_) return Result::Other; if (!p_->IsAlive()) return Result::Locked; - return UseItemImpl(p_, p_->GetItemByEntry(item_entry), target); + Item* item = p_->GetItemByEntry(item_entry); + if (!item && (target.IsEmpty() || target == p_->GetGUID())) + return UseVirtualSupply(p_, item_entry); + return UseItemImpl(p_, item, target); } Result API::use_item_by_slot(uint8 bag, uint8 slot, ObjectGuid target) @@ -5593,7 +6188,7 @@ Result API::use_item_by_slot(uint8 bag, uint8 slot, ObjectGuid target) return UseItemImpl(p_, p_->GetItemByPos(bag, slot), target); } -Result API::loot_corpse(ObjectGuid corpse) +Result API::loot_corpse(ObjectGuid corpse, bool quest_items_only) { if (!p_) return Result::Other; if (!p_->IsAlive()) return Result::Locked; @@ -5607,6 +6202,26 @@ Result API::loot_corpse(ObjectGuid corpse) if (loot->isLooted() && loot->items.empty() && loot->gold == 0) return Result::InvalidTarget; + // A bot a player leads: only its own quest drops, stored directly (party loot rules would only open and release the window). + if (quest_items_only) + { + ObjectGuid const owner = loot->GetOwnerGUID(); + uint32 taken = 0; + for (uint8 slot = 0; slot < loot->items.size(); ++slot) + { + if (!IsPendingQuestLoot(p_, loot, slot)) continue; + LootItem const& qi = loot->items[slot]; + ItemPosCountVec dest; + if (p_->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, qi.itemid, qi.count) != EQUIP_ERR_OK) continue; + p_->StoreLootItem(owner, slot, loot); + ++taken; + } + TC_LOG_INFO("playerbot.v2", "[loot_quest] {} corpse={} took {} quest item(s)", p_->GetName(), corpse.GetCounter(), taken); + if (WorldSession* sess = p_->GetSession()) + sess->DoLootRelease(loot); + return Result::Ok; + } + // Group with non-FFA loot rules: defer to SendLoot so the rolling / // master-loot pipeline owns the items. We don't auto-grab in that case. Group* group = p_->GetGroup(); @@ -5624,7 +6239,7 @@ Result API::loot_corpse(ObjectGuid corpse) return Result::Ok; } - // Solo / FFA — directly transfer items the bot is allowed to take. + // Solo / FFA — directly transfer items the bot is allowed to take. ObjectGuid lootOwnerGuid = loot->GetOwnerGUID(); uint32 dbg_items = uint32(loot->items.size()); uint32 dbg_stored = 0, dbg_blocked = 0, dbg_looted = 0, dbg_nofit = 0, dbg_nullitem = 0; @@ -5633,7 +6248,7 @@ Result API::loot_corpse(ObjectGuid corpse) // ROOT CAUSE of the loot/skin hot-loop (4-day forensics): free-for-all // (FFA) loot items track their looted state PER PLAYER in `ffaItem`, NOT // in the shared `it->is_looted` (Player::StoreLootItem only sets the - // shared flag for non-FFA items — `if (!item->freeforall)`). The old call + // shared flag for non-FFA items — `if (!item->freeforall)`). The old call // omitted the ffaItem out-param, so the bot never saw that it had already // taken its own FFA copy and re-looted the SAME FFA items every tick: the // shared is_looted never flipped, the corpse never fully cleared, never @@ -5699,7 +6314,7 @@ Result API::loot_corpse(ObjectGuid corpse) "[loot_drain] bot={} corpse={} items={} stored={} blocked={} prelooted={} nofit={} nullitem={} after_isLooted={}", p_->GetGUID().GetCounter(), corpse.GetCounter(), dbg_items, dbg_stored, dbg_blocked, dbg_looted, dbg_nofit, dbg_nullitem, loot->isLooted() ? 1 : 0); - // CRITICAL: SendLootRelease() only sends the client a packet — it does NOT + // CRITICAL: SendLootRelease() only sends the client a packet — it does NOT // run the server-side release. The real release (WorldSession::DoLootRelease) // is what clears UNIT_DYNFLAG_LOOTABLE (removes the corpse "glitter") and, // for a fully-looted creature corpse, calls AllLootRemovedFromCorpse() which @@ -5718,7 +6333,7 @@ Result API::hearth() { if (!p_) return Result::Other; if (p_->IsInCombat()) return Result::Locked; - // Hearthstone is an ITEM (entry 6948) — players obtain it from any + // Hearthstone is an ITEM (entry 6948) — players obtain it from any // innkeeper after binding their home location, then USE the item to // cast its hearth spell. Spell 8690 is the *triggered* spell inside the // item; calling cast_spell(8690) rejects with "not in spellbook" since @@ -5739,7 +6354,7 @@ Result API::interact_with_npc(ObjectGuid npc) if (p_->IsInCombat()) return Result::Locked; // Mirrors WorldSession::HandleGossipHelloOpcode (NPCHandler.cpp). Same // interact-range / NPC-flag check; same cancel-of-Interacting auras; - // same pause-on-talk; same OnGossipHello → PrepareGossipMenu → + // same pause-on-talk; same OnGossipHello → PrepareGossipMenu → // SendPreparedGossip pipeline. Only the packet read/write is omitted // because we're invoking from server side. Creature* unit = p_->GetNPCIfCanInteractWith(npc, UNIT_NPC_FLAG_GOSSIP, UNIT_NPC_FLAG_2_NONE); @@ -5823,20 +6438,20 @@ Result API::use_game_object(ObjectGuid go_guid) // the server then attaches it. A bot has NO client, so standing on the deck // does nothing (observed live: bots at dist 0.0 with on_transport=0 forever). // We attach/detach server-side instead. Treated as a toggle so we can reuse - // the existing UseObjectIntent (no new intent type — the IntentBody variant + // the existing UseObjectIntent (no new intent type — the IntentBody variant // is at its MSVC heap limit): not aboard + in range => board; already aboard // => disembark (drops the bot at its current world position, i.e. on the dock // deck at the destination). // // Resolve as a TransportBase, which covers BOTH transport flavours: - // * GAMEOBJECT_TYPE_MAP_OBJ_TRANSPORT (15) — cross-map ships/zeppelins, and - // * GAMEOBJECT_TYPE_TRANSPORT (11) — local animated lifts (the Orgrimmar + // * GAMEOBJECT_TYPE_MAP_OBJ_TRANSPORT (15) — cross-map ships/zeppelins, and + // * GAMEOBJECT_TYPE_TRANSPORT (11) — local animated lifts (the Orgrimmar // zeppelin-tower elevators, Undercity/city lifts, etc). // The previous code resolved via Map::GetTransport(), which returns ONLY // type-15 (guid.IsMOTransport()). Every type-11 elevator therefore fell // through the whole branch and AddPassenger NEVER fired for one (verified // live: ADDPASSENGER 0 fleet-wide while a bot looped boarding an elevator, - // dist growing 11→18y as the platform cycled away un-attached). Map:: + // dist growing 11→18y as the platform cycled away un-attached). Map:: // GetGameObject() finds both flavours and GameObject::ToTransportBase() // yields the passenger interface for each; the type-11 GO is relocated live // by its animation frames, so GetPosition() is the current platform height. @@ -5845,7 +6460,7 @@ Result API::use_game_object(ObjectGuid go_guid) GameObject* go = tmap->GetGameObject(go_guid); if (TransportBase* tr = go ? go->ToTransportBase() : nullptr) { - // DISEMBARK: already aboard → step off. The caller (idle ride-guard) + // DISEMBARK: already aboard → step off. The caller (idle ride-guard) // only emits this when the ship is STOPPED at the destination dock, // so RemovePassenger leaves the bot standing on the deck at the dock // and its normal rules walk it onto land next tick. @@ -5855,7 +6470,7 @@ Result API::use_game_object(ObjectGuid go_guid) p_->SetFallInformation(0, p_->GetPositionZ()); // ELEVATOR step-off (type-11). A ship (type-15) drops the bot on - // its stationary dock deck, which is real navmesh — nothing more to + // its stationary dock deck, which is real navmesh — nothing more to // do. A type-11 lift, however, leaves the bot standing on the // PLATFORM CENTRE at the arrival floor, which for an upper stop is // open air over the shaft (the moving platform is carved OUT of the @@ -5889,7 +6504,7 @@ Result API::use_game_object(ObjectGuid go_guid) ledge.GetPositionX(), ledge.GetPositionY(), ledge.GetPositionZ()); return Result::Ok; } - // No walkable ledge within reach — fall through to the plain + // No walkable ledge within reach — fall through to the plain // log. The bot detaches in place (pre-existing behaviour); the // WARN flags a lift whose disembark floor has no navmesh nearby // (data gap worth investigating). @@ -5905,8 +6520,8 @@ Result API::use_game_object(ObjectGuid go_guid) p_->GetName(), go->GetEntry(), p_->GetMapId()); return Result::Ok; } - // BOARD — V1-proven recipe. A bot has no client to send the board - // movement packet, so we attach server-side — but it WALKS onto the + // BOARD — V1-proven recipe. A bot has no client to send the board + // movement packet, so we attach server-side — but it WALKS onto the // deck like a player, we never snap/teleport it on. Two requirements // V1 honoured and the first V2 cut missed: // 1) Only board a transport that is STOPPED at its dock. Boarding a @@ -5921,7 +6536,7 @@ Result API::use_game_object(ObjectGuid go_guid) // ELEVATOR / already-on-deck fast path. If the bot is standing // essentially ON the transport (within ~7y 3D), attach IMMEDIATELY at // its current spot. This covers (a) a vertical elevator platform that - // has cycled down to the bot's floor — elevators move CONTINUOUSLY so + // has cycled down to the bot's floor — elevators move CONTINUOUSLY so // the stationary gate below never passes for them, but the bot is // physically on the platform so boarding now is correct; and (b) a ship // deck the bot already walked onto (the V1 path below leads here). The @@ -5973,7 +6588,7 @@ Result API::use_game_object(ObjectGuid go_guid) } if (now_ms - track.second < 2000) { - // Still sailing / just pulling in — wait at the dock, don't chase a + // Still sailing / just pulling in — wait at the dock, don't chase a // moving deck. Locked holds the bot; the idle wait_for_transport // rule keeps it on the pier until the ship settles, then this // re-fires and boards. @@ -5982,7 +6597,7 @@ Result API::use_game_object(ObjectGuid go_guid) // Docked and stationary. Walk onto the deck and attach once standing // on it (the bot visibly walks aboard, as V1 did). The deck height - // above the transport pivot varies per ship — most boats deck ~2y + // above the transport pivot varies per ship — most boats deck ~2y // above the waterline pivot, but some have a raised deck reached by // entrance stairs (e.g. Stormwind's Pride / Valiance-Keep icebreaker, // deck ~z9.4 over a z0 pivot). Use an operator-provided per-entry deck @@ -5992,9 +6607,9 @@ Result API::use_game_object(ObjectGuid go_guid) // TravelNode.cpp generateTransportNodes exit offsets): the zeppelin // pivot hangs ~17y above its gondola deck (= the tower deck it docks // at), and the Deeprun Tram car ("Subway") pivot sits 10y above the - // car floor. The rider cannot walk onto the pivot X/Y there — the + // car floor. The rider cannot walk onto the pivot X/Y there — the // gondola / car floor is not navmesh and hangs off the tower edge / - // over the track — so for these the bot walks as close as the mesh + // over the track — so for these the bot walks as close as the mesh // allows and steps aboard from within a few yards of the deck. bool deckBelowPivot = false; switch (go->GetEntry()) @@ -6035,7 +6650,7 @@ Result API::use_game_object(ObjectGuid go_guid) } } GameObject* obj = p_->GetGameObjectIfCanInteractWith(go_guid); - // [bg_use_diag] TEMP — verify BG flag/node use (pickup vs cap). + // [bg_use_diag] TEMP — verify BG flag/node use (pickup vs cap). if (Map* dmap2 = p_->GetMap()) if (GameObject* raw = dmap2->GetGameObject(go_guid)) { @@ -6069,6 +6684,11 @@ Result API::use_game_object(ObjectGuid go_guid) } return Result::InvalidTarget; } + // A chest a player could not click either: despawned, or a quest object (mushroom, flower, crate) for a quest the bot does not + // have. A bot opening one took nothing from it, but the object stayed opened with loot made for the bot, and the player who + // needed it found it empty (Discord 2026-10-27). + if (obj->GetGoType() == GAMEOBJECT_TYPE_CHEST && (!obj->isSpawned() || !obj->ActivateToQuest(p_))) + return Result::InvalidTarget; // Mounted-restriction check from HandleGameObjectUseOpcode: most GOs // refuse interaction while mounted unless flagged UsableMounted. if (p_->IsMounted() && !obj->GetGOInfo()->IsUsableMounted()) @@ -6076,7 +6696,10 @@ Result API::use_game_object(ObjectGuid go_guid) // A battleground flag or banner is not used in a shapeshift form (a bear-form druid stood at the Lumber Mill banner doing nothing, // the owner AB 2026-10-11): leave the form first, the next click (the rule re-emits) goes through as a caster. - if (p_->InBattleground() && p_->GetShapeshiftForm() != FORM_NONE && + // Only a real shapeshift (druid animal forms, Ghost Wolf) blocks the click; a warrior stance or Stealth does not (SpellInfo::CheckShapeshift). + // The log showed warriors (form 17, 18) and rogues (form 30) dropping their stance or stealth for every flag click. + SpellShapeshiftFormEntry const* const formInfo = p_->GetShapeshiftForm() != FORM_NONE ? sSpellShapeshiftFormStore.LookupEntry(p_->GetShapeshiftForm()) : nullptr; + if (p_->InBattleground() && formInfo && !formInfo->GetFlags().HasFlag(SpellShapeshiftFormFlags::Stance) && (obj->GetGoType() == GAMEOBJECT_TYPE_BUTTON || obj->GetGoType() == GAMEOBJECT_TYPE_GOOBER || obj->GetGoType() == GAMEOBJECT_TYPE_FLAGSTAND || obj->GetGoType() == GAMEOBJECT_TYPE_FLAGDROP || obj->GetGoType() == GAMEOBJECT_TYPE_NEW_FLAG || obj->GetGoType() == GAMEOBJECT_TYPE_NEW_FLAG_DROP || obj->GetGoType() == GAMEOBJECT_TYPE_CAPTURE_POINT)) @@ -6106,6 +6729,26 @@ Result API::use_game_object(ObjectGuid go_guid) return Result::Locked; // The same banner, or another banner standing at the same pole (a contested node keeps its neutral banner next to the faction // one): the capture in progress continues instead of restarting. + // An enemy player within 11 y breaks the capture and the bot fights first (the older bots do the same: a capture channel + // does not survive a hit anyway). Without this the bot stood at the banner for the whole 5 s and was cut down. + { + bool enemyNear = false; + if (Battleground* bgNear = p_->GetBattleground()) + for (auto const& entry : bgNear->GetPlayers()) + { + Player* other = ObjectAccessor::FindPlayer(entry.first); + if (other && other != p_ && other->IsAlive() && other->GetBGTeam() != p_->GetBGTeam() && p_->IsWithinDist(other, 11.0f)) + { enemyNear = true; break; } + } + if (enemyNear) + { + if (cap.startMs != 0) + TC_LOG_INFO("playerbot.v2", "[bg_capture] {} interrupt entry={} reason=enemy", p_->GetName(), obj->GetEntry()); + cap.startMs = 0; + cap.go = ObjectGuid::Empty; + return Result::Locked; + } + } bool const sameGo = cap.startMs != 0 && (cap.go == go_guid || cap.goPos.GetExactDist2d(obj) < 3.0f); bool const moved = sameGo && p_->GetExactDist2d(cap.pos) > 3.0f; bool const hurt = sameGo && p_->GetHealth() < cap.health; @@ -6136,7 +6779,7 @@ Result API::use_game_object(ObjectGuid go_guid) // Auto-loot for lootable GO types (CHEST, GOOBER with loot, etc.). // GameObject::Use opens the loot window server-side (m_loot is // populated, GO state transitions to ACTIVATED) but for headless - // bots — and for self-bot logic bots without auto-loot enabled — there's + // bots — and for self-bot logic bots without auto-loot enabled — there's // no client to send CMSG_LOOT_ITEM. The chest stays open with the // items inside untaken, the quest objective never progresses, and // the bot moves on or hearths after stuck-detection. @@ -6145,7 +6788,7 @@ Result API::use_game_object(ObjectGuid go_guid) // off it, got stuck on the objective. // // Mirrors API::loot_corpse: walk loot.items, store each. Skip the - // group / master-loot path (chests are FFA by default — TC's + // group / master-loot path (chests are FFA by default — TC's // ROLL_NEED_BEFORE_GREED and master-loot apply only to creature // corpses). if (Loot* loot = obj->GetLootForPlayer(p_)) @@ -6157,7 +6800,7 @@ Result API::use_game_object(ObjectGuid go_guid) { // Same FFA fix as API::loot_corpse: chests are FFA, so a looted // item's state lives in the per-player ffaItem, not the shared - // it->is_looted — without checking it the bot re-loots the chest + // it->is_looted — without checking it the bot re-loots the chest // every tick and the GO never reaches GO_JUST_DEACTIVATED. NotNormalLootItem* ffaItem = nullptr; LootItem* it = loot->LootItemInSlot(slot, p_, &ffaItem); @@ -6170,8 +6813,15 @@ Result API::use_game_object(ObjectGuid go_guid) p_->ModifyMoney(loot->gold); loot->gold = 0; } - p_->SendLootRelease(go_guid); } + // The real release, as API::loot_corpse does: SendLootRelease alone is only a packet, so a looted chest or quest object + // stayed opened (GO_ACTIVATED) and never despawned or respawned; every player who clicked it later got an empty window + // (Discord 2026-10-27). + WorldSession* sess = p_->GetSession(); + if (sess && p_->GetLootGUID() == go_guid) + sess->DoLootRelease(loot); + else + p_->SendLootRelease(go_guid); } return Result::Ok; } @@ -6213,8 +6863,8 @@ Result API::accept_quest(ObjectGuid quest_giver, uint32 quest_id) if (!p_->CanInteractWithQuestGiver(object)) { log_reject("out_of_range"); return Result::OutOfRange; } // Junk-quest accept-gate (R2, defense-in-depth). A quest with ZERO // objectives AND no creature/GO turn-in NPC is structurally unfinishable - // and unturnable — accepting it parks the bot forever (current_quest_id=0 - // → [picker_none]). The snapshot offer-scan already filters these, but a + // and unturnable — accepting it parks the bot forever (current_quest_id=0 + // → [picker_none]). The snapshot offer-scan already filters these, but a // shared-quest / gossip path could still reach here. (q55660 "Time Trials" // was held by 13,641 bots fleet-wide.) Mirrors IsBotJunkQuest in the V2 // module; checked inline to avoid a cross-library dependency. @@ -6259,9 +6909,9 @@ Result API::accept_quest(ObjectGuid quest_giver, uint32 quest_id) // Score a single choice-reward item from a completable quest. Higher score wins. // Decision tree (matches QUEST_SYSTEM_PLAN.md L1.A): -// 1. Item not usable by bot at all (CanUseItem != OK) → vendor value only. -// 2. Item is equippable for an empty equipment slot → ilvl * 100. -// 3. Item is equippable, slot already occupied → (delta_ilvl) * 100 + (delta_quality) * 10. +// 1. Item not usable by bot at all (CanUseItem != OK) → vendor value only. +// 2. Item is equippable for an empty equipment slot → ilvl * 100. +// 3. Item is equippable, slot already occupied → (delta_ilvl) * 100 + (delta_quality) * 10. // Negative deltas allowed; the comparison still produces a score we can rank. // 4. Tabards / shirts (cosmetic): cap at vendor value (no equip-bonus weight). // Vendor value is item->GetSellPrice() * count; clamped to int32 to keep score @@ -6278,7 +6928,7 @@ static int32 ScoreQuestReward(Player* bot, Quest const* quest, uint32 choice_ind ItemTemplate const* tmpl = sObjectMgr->GetItemTemplate(item_id); if (!tmpl) return 0; - // Vendor base — used as a tiebreaker plus the floor for un-equippable items. + // Vendor base — used as a tiebreaker plus the floor for un-equippable items. // SellPrice is in copper; cast to int32 first so a 0-stack is just 0 not UB. int32 const vendor_value = static_cast(tmpl->GetSellPrice()) * static_cast(count > 0 ? count : 1); @@ -6306,10 +6956,10 @@ static int32 ScoreQuestReward(Player* bot, Quest const* quest, uint32 choice_ind if (equip_slot >= EQUIPMENT_SLOT_END) return vendor_value; // Item level for ranking. Use the LEVEL-SCALED effective ilvl the bot will - // actually wear the item at — TC 12.0 scales many items via a curve, so the + // actually wear the item at — TC 12.0 scales many items via a curve, so the // static base ilvl can be wildly off (a base-120 reward collapsing to // effective ilvl 5 at L16). The old code used GetBaseItemLevel() despite the - // comment promising scaled — fixed 2026-06-17 (under-gearing campaign) so + // comment promising scaled — fixed 2026-06-17 (under-gearing campaign) so // quest-reward picks match what the bot wears. int32 const new_ilvl = ::Playerbot::Gear::EffectiveItemLevelForLevel(tmpl, bot->GetLevel()); int32 const new_qual = static_cast(tmpl->GetQuality()); @@ -6332,7 +6982,7 @@ static int32 ScoreQuestReward(Player* bot, Quest const* quest, uint32 choice_ind } ItemTemplate const* cur_tmpl = cur->GetTemplate(); - // Effective ilvl of the equipped item (live item → real scaled value). + // Effective ilvl of the equipped item (live item → real scaled value). int32 const cur_ilvl = static_cast(cur->GetItemLevel(bot)); int32 const cur_qual = cur_tmpl ? static_cast(cur_tmpl->GetQuality()) : 0; @@ -6408,7 +7058,7 @@ static int32 PickUpgradeQuestReward(Player* bot, Quest const* quest, float& rati return best_choice; } -Result API::complete_quest(ObjectGuid quest_giver, uint32 quest_id, uint32 reward_choice) +Result API::complete_quest(ObjectGuid quest_giver, uint32 quest_id, uint32 reward_choice, bool copy_leader) { if (!p_) return Result::Other; Quest const* quest = sObjectMgr->GetQuestTemplate(quest_id); @@ -6425,12 +7075,34 @@ Result API::complete_quest(ObjectGuid quest_giver, uint32 quest_id, uint32 rewar "[complete_quest] {} reject quest={} lvl={} reason={}", p_->GetName(), quest_id, uint32(p_->GetLevel()), why); }; - if (!p_->CanRewardQuest(quest, false)) { log_reject("cant_reward_pre"); return Result::Locked; } + // A companion copies its leader: when the leader has just handed this quest in, the bot's open copy is finished for it (the items a + // collect quest wants are put in its bags; a grouped bot never loots) and handed in at the same ender. + bool const copy = copy_leader && p_->GetQuestStatus(quest_id) == QUEST_STATUS_INCOMPLETE; + if (!copy && !p_->CanRewardQuest(quest, false)) { log_reject("cant_reward_pre"); return Result::Locked; } Object* object = ObjectAccessor::GetObjectByTypeMask(*p_, quest_giver, TYPEMASK_UNIT | TYPEMASK_GAMEOBJECT | TYPEMASK_ITEM); if (!object) { log_reject("turnin_giver_lost"); return Result::InvalidTarget; } if (!p_->CanInteractWithQuestGiver(object)) { log_reject("turnin_out_of_range"); return Result::OutOfRange; } + if (copy) + { + for (QuestObjective const& obj : quest->GetObjectives()) + { + if (obj.Type != QUEST_OBJECTIVE_ITEM || (obj.Flags2 & QUEST_OBJECTIVE_FLAG_2_QUEST_BOUND_ITEM)) + continue; + uint32 const have = p_->GetItemCount(obj.ObjectID); + if (have >= uint32(obj.Amount)) + continue; + uint32 const missing = uint32(obj.Amount) - have; + ItemPosCountVec dest; + if (p_->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, obj.ObjectID, missing) != EQUIP_ERR_OK) + { log_reject("copy_leader_no_room"); return Result::Locked; } + p_->StoreNewItem(dest, obj.ObjectID, true); + } + p_->CompleteQuest(quest_id); + if (!p_->CanRewardQuest(quest, false)) { log_reject("copy_leader_cant_reward"); return Result::Locked; } + TC_LOG_INFO("playerbot.v2", "[complete_quest] {} copies its leader on quest={}", p_->GetName(), quest_id); + } // Auto-reward selection: when caller passes the kRewardChoiceAuto sentinel, // walk every choice item and pick the highest-scoring one. Score combines @@ -6480,7 +7152,7 @@ Result API::complete_quest(ObjectGuid quest_giver, uint32 quest_id, uint32 rewar { choice_item = quest->RewardChoiceItemId[reward_choice]; } - // reward_choice >= num_choices (and not the sentinel) → choice_item + // reward_choice >= num_choices (and not the sentinel) → choice_item // stays 0; CanRewardQuest below will reject and return Locked. } @@ -6493,7 +7165,7 @@ Result API::complete_quest(ObjectGuid quest_giver, uint32 quest_id, uint32 rewar p_->RewardQuest(quest, LootItemType::Item, choice_item, object); // Verify the reward actually landed in bag. RewardQuest can fail to // place items silently when bag space is tight enough that AutoStore - // can't find a slot — those items go to mail. Log both presence in + // can't find a slot — those items go to mail. Log both presence in // bag and mail-deferred outcome so the operator can distinguish // "reward never arrived" (genuine bug) from "reward arrived but in // mail" (bag full, recoverable via mailbox visit). @@ -6533,10 +7205,10 @@ Result API::complete_quest(ObjectGuid quest_giver, uint32 quest_id, uint32 rewar fixed_summary); // Same-NPC follow-up auto-accept. Scripted escort NPCs (Tarindrella for - // quest chain 28725→28726→28727→28728 in Shadowthread Cave) often despawn + // quest chain 28725→28726→28727→28728 in Shadowthread Cave) often despawn // a few seconds after a turn-in via their SmartAI OOC timer. The // post-RewardQuest world tick gives the bot logic ~1 snapshot to re-probe - // CanTakeQuest and emit accept_quest before the giver vanishes — that + // CanTakeQuest and emit accept_quest before the giver vanishes — that // window can close before the bot's accept intent dispatches, producing // the "giver_not_found" / "giver_lost_relation" reject pair observed for // Uraimus 2026-05-21 (quest 28728 "Signs of Things to Come"). @@ -6602,11 +7274,11 @@ Result API::lfg_queue(uint32 dungeon_id, uint8 roles) lfg::LfgDungeonSet dungeons; dungeons.insert(dungeon_id); sLFGMgr->JoinLfg(p_, roles, dungeons); - // Verify JoinLfg actually queued us — if state didn't transition to + // Verify JoinLfg actually queued us — if state didn't transition to // QUEUED, an LFG-side gate fired silently (RBAC, deserter aura, gear // ilvl, level mismatch, freeze debuff, group membership, etc.). This // is the diagnostic that lets us answer "filler queued 4, only 2 in - // queue — why?" without grepping LFGMgr internals. + // queue — why?" without grepping LFGMgr internals. lfg::LfgState const post_state = sLFGMgr->GetState(p_->GetGUID()); if (post_state != lfg::LFG_STATE_QUEUED && post_state != lfg::LFG_STATE_ROLECHECK && @@ -6675,7 +7347,7 @@ Result API::equip_item(uint8 from_bag, uint8 from_slot, uint8 to_slot) // Server-refusal backoff. The caller (EquipUpgradeFire) re-issues this // every eligible tick while the item is still in the bag. If a prior // attempt was refused (and the item therefore never left the bag), skip - // the swap until the backoff expires — otherwise we re-run CanEquipItem + // the swap until the backoff expires — otherwise we re-run CanEquipItem // and emit a phantom "Ok" every tick, which makes /diag report an equip // that will never land. Keyed on (item-entry, dest-slot). uint32 const efail_now = GameTime::GetGameTimeMS(); @@ -6694,7 +7366,7 @@ Result API::equip_item(uint8 from_bag, uint8 from_slot, uint8 to_slot) return Result::ServerRefused; } - // ---- Bag destination (slots 30-33) — B-11b ---- + // ---- Bag destination (slots 30-33) — B-11b ---- // Containers don't go through CanEquipItem (that path refuses them); // Player::SwapItem natively supports "swap an EMPTY bag from inventory // with an equipped bag, transferring the equipped bag's contents into @@ -6708,11 +7380,11 @@ Result API::equip_item(uint8 from_bag, uint8 from_slot, uint8 to_slot) if (!src_bag) { NoteEquipFail(p_, efail_key, efail_now); - return Result::ServerRefused; // not a container — rule bug + return Result::ServerRefused; // not a container — rule bug } // SwapItem's content-exchange branch only runs when the INCOMING bag // is empty (a freshly looted / quest-rewarded bag always is). A bag - // the bot has stored items into is a transient state — skip, the + // the bot has stored items into is a transient state — skip, the // periodic re-check retries after the bag empties. if (!src_bag->IsEmpty()) return Result::Locked; @@ -6748,7 +7420,7 @@ Result API::equip_item(uint8 from_bag, uint8 from_slot, uint8 to_slot) // Pre-validate the equip the same way Player::SwapItem will internally, // so we can return a TRUTHFUL result instead of an unconditional Ok. // SwapItem returns void and only SendEquipError's the client on failure, - // leaving the item in the bag — invisible to the API caller. CanEquipItem + // leaving the item in the bag — invisible to the API caller. CanEquipItem // with swap=true mirrors the swap case (destination slot may be occupied; // the current item gets swapped back into the source slot). This is the // exact gate SwapItem applies, so a non-OK result here means SwapItem @@ -6823,7 +7495,7 @@ Result API::vendor_buy_by_category(ObjectGuid npc, uint8 item_class, uint8 item_ // can actually use. For most vendors there's a single food entry per // level bracket so this resolves cleanly; when multiple match (Algari // Travel Ration vs Loose-Leaf Tea) we'd happily buy whichever shows up - // highest — both restore the same well-fed buff. + // highest — both restore the same well-fed buff. uint32 best_slot = items->GetItemCount(); int32 best_required_level = -1; uint32 best_buy_count = 1; // fallback if BuyCount is 0 (older data) @@ -6865,7 +7537,7 @@ Result API::vendor_buy_by_category(ObjectGuid npc, uint8 item_class, uint8 item_ Result API::vendor_buy_by_entry(ObjectGuid npc, uint32 item_entry, uint32 count) { - // Convenience wrapper around vendor_buy_by_slot — walks the vendor's + // Convenience wrapper around vendor_buy_by_slot — walks the vendor's // inventory looking for the matching item entry, then issues the buy. // Useful when callers know the item ID (script integrations, recipe // reagent lookup) but not the slot index. @@ -6912,10 +7584,10 @@ Result API::jump(float forward) // facing nearly always launches INTO whatever wedged it (the bot was // walking toward its goal when it jammed, so it's still pointing at the // wall / ledge / closed door). TryUnstickJump tries the current facing, - // then ±90°, then 180° (reverse out of a dead-end pocket), and launches + // then ±90°, then 180° (reverse out of a dead-end pocket), and launches // the first bearing whose landing has real ground and a clear arc chord. // It faces the chosen bearing before MoveJump so the arc travels that - // way. Returns false only when every bearing is blocked / groundless — + // way. Returns false only when every bearing is blocked / groundless — // refuse rather than launch the bot into geometry / the void. if (!BotMovement::TryUnstickJump(p_, forward)) return Result::Locked; @@ -6946,7 +7618,7 @@ Result API::mail_take_money(ObjectGuid mailbox, uint64 mail_id) // ModifyMoney with the strict overflow guard. Returns false when the // bot is over the gold cap, in which case we surface NotEnoughResource - // rather than mutating mail state — mirrors EQUIP_ERR_TOO_MUCH_GOLD. + // rather than mutating mail state — mirrors EQUIP_ERR_TOO_MUCH_GOLD. if (!p_->ModifyMoney(m->money, false)) return Result::NotEnoughResource; @@ -6959,7 +7631,7 @@ Result API::mail_take_money(ObjectGuid mailbox, uint64 mail_id) // picked up by the next player save (Player::_SaveMail walks the mail // vector unconditionally when m_mailsUpdated is set). _SaveMail is // protected on Player and not friend-accessible from this module, so we - // can't co-commit it inside our own transaction — relying on the + // can't co-commit it inside our own transaction — relying on the // periodic save tick for mail durability is the same pattern Trinity // uses for the in-game UI mail-money take button. CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); @@ -7025,7 +7697,7 @@ Result API::mail_take_item(ObjectGuid mailbox, uint64 mail_id, uint64 item_guid_ p_->MoveItemToInventory(dest, item, true); p_->SaveInventoryAndGoldToDB(trans); // _SaveMail is protected; rely on m_mailsUpdated for the next periodic - // save (same rationale as mail_take_money — see comment there). + // save (same rationale as mail_take_money — see comment there). CharacterDatabase.CommitTransaction(trans); return Result::Ok; } @@ -7051,7 +7723,7 @@ Result API::bind_homebind(ObjectGuid innkeeper) if (p_->GetMap() && p_->GetMap()->Instanceable()) return Result::Locked; Creature* npc = p_->GetNPCIfCanInteractWith(innkeeper, UNIT_NPC_FLAG_INNKEEPER, UNIT_NPC_FLAG_2_NONE); if (!npc) return Result::InvalidTarget; - // Spell 3286 = Bind. Cast from the NPC at the bot — the spell handler + // Spell 3286 = Bind. Cast from the NPC at the bot — the spell handler // updates the homebind row. npc->CastSpell(p_, /*Bind*/ 3286, true); return Result::Ok; @@ -7064,7 +7736,7 @@ Result API::loot_roll(ObjectGuid loot_object, uint8 loot_list_id, uint8 vote_typ if (!roll) return Result::Locked; // RollVote enum values match the wire protocol: Pass=0, Need=1, // Greed=2, Disenchant=3. Anything outside that range is forced to - // Pass (safe default — never accidentally take loot). + // Pass (safe default — never accidentally take loot). RollVote vote = RollVote::Pass; switch (vote_type) { @@ -7118,7 +7790,7 @@ std::vector ParseCuratedBuild(std::string const& text) } // Look up a curated build row in playerbot_v2_talent_build, with fallback -// from (class, spec, context) → (class, spec, Default). Returns the +// from (class, spec, context) → (class, spec, Default). Returns the // `entries_json` text (despite the column name, we use a CSV format). // Empty string means no curated row found. std::string LookupCuratedBuildRow(uint32 classId, uint32 specId, uint8 context) @@ -7153,7 +7825,7 @@ std::string LookupCuratedBuildRow(uint32 classId, uint32 specId, uint8 context) return {}; } -// Leveling spec per class (the DPS spec the baseline APLs are tuned for — +// Leveling spec per class (the DPS spec the baseline APLs are tuned for — // mirrors ApRegistry::DefaultSpecForClass). Used to promote a bot off the // class's INITIAL placeholder specialization, which 92% of the L10+ fleet // was still on: the Initial spec has no Combat TraitConfig, so every talent @@ -7182,7 +7854,7 @@ uint32 LevelingSpecForClass(uint8 cls) // Promote the bot to a REAL specialization if it still sits on the class's // Initial placeholder. ActivateTalentGroup learns spec spells + mastery and -// creates/activates the matching Combat TraitConfig — the precondition for +// creates/activates the matching Combat TraitConfig — the precondition for // any talent application. Returns false when no spec could be resolved. bool EnsureRealSpec(Player* p) { @@ -7190,7 +7862,7 @@ bool EnsureRealSpec(Player* p) if (::Playerbot::Classic::IsSingleSpecClass(p->GetClass())) return true; if (p->GetLevel() < 10) - return false; // retail unlocks specialization at L10 — nothing to do yet + return false; // retail unlocks specialization at L10 — nothing to do yet ChrSpecializationEntry const* initial = sDB2Manager.GetDefaultChrSpecializationForClass(p->GetClass()); const uint32 cur = uint32(AsUnderlyingType(p->GetPrimarySpecialization())); @@ -7207,7 +7879,7 @@ bool EnsureRealSpec(Player* p) return true; } -// Count purchased ranks in the bot's ACTIVE trait config — the ground-truth +// Count purchased ranks in the bot's ACTIVE trait config — the ground-truth // "talents actually applied" signal (the legacy GetTalentMap is never // written by the 12.0 trait system). uint32 CountActiveTraitRanks(Player* p) @@ -7229,7 +7901,7 @@ Result API::apply_talent_build(uint8 context) if (::Playerbot::Classic::IsSingleSpecClass(p_->GetClass())) return apply_classic_talents(); - // Promote off the Initial placeholder spec first — without a real spec + // Promote off the Initial placeholder spec first — without a real spec // there is no Combat TraitConfig and this path silently no-op'd for 92% // of the L10+ fleet (audit B05/B06). if (!EnsureRealSpec(p_)) return Result::NotKnown; @@ -7242,7 +7914,7 @@ Result API::apply_talent_build(uint8 context) const uint32 specId = uint32(AsUnderlyingType(p_->GetPrimarySpecialization())); // Look up curated build. If none, fall back to TraitMgr's starter - // build — that's still a valid spec-aware spend (just not optimized + // build — that's still a valid spec-aware spend (just not optimized // for raid / M+ / PvP). std::string curatedCsv = LookupCuratedBuildRow(classId, specId, context); @@ -7269,7 +7941,7 @@ Result API::apply_talent_build(uint8 context) /*requireSpendingAllCurrencies=*/ false, /*removeInvalidEntries=*/ true); // A curated build is a MAX-LEVEL spend. removeInvalidEntries only - // strips STRUCTURALLY-invalid nodes — it does NOT trim for talent- + // strips STRUCTURALLY-invalid nodes — it does NOT trim for talent- // currency overflow, so an under-level bot's config still holds the // full endgame node set and ValidateConfig returns an error (e.g. // NotEnoughTalentsInPrimaryTree) WITHOUT pruning. The old code @@ -7281,7 +7953,7 @@ Result API::apply_talent_build(uint8 context) { // withCastTime=false: bots have no client to animate the 1.5s // "Applying Talents" commit cast for, and leveling bots move - // constantly — the interruptible cast was the reason commits + // constantly — the interruptible cast was the reason commits // never landed fleet-wide (audit B05). Verify the result. p_->UpdateTraitConfig(std::move(new_cfg), 0, /*withCastTime*/ false); const uint32 ranks = CountActiveTraitRanks(p_); @@ -7294,7 +7966,7 @@ Result API::apply_talent_build(uint8 context) } } - // No curated build → starter build. Same as apply_starter_talents. + // No curated build → starter build. Same as apply_starter_talents. TraitMgr::InitializeStarterBuildTraitConfig(new_cfg, p_); new_cfg.CombatConfigFlags |= TraitCombatConfigFlags::StarterBuild; p_->UpdateTraitConfig(std::move(new_cfg), 0, /*withCastTime*/ false); @@ -7316,7 +7988,7 @@ Result API::apply_starter_talents() // Promote off the Initial placeholder spec first (audit B06): without a // real spec there is no Combat TraitConfig and this path returned - // NotKnown silently for 92% of the L10+ fleet — 13K+ bots at 0 talents. + // NotKnown silently for 92% of the L10+ fleet — 13K+ bots at 0 talents. if (!EnsureRealSpec(p_)) return Result::NotKnown; int32 const active_id = p_->m_activePlayerData->ActiveCombatTraitConfigID; @@ -7325,7 +7997,7 @@ Result API::apply_starter_talents() // Build a writable copy of the active config, then ask TraitMgr to fill // it with the curated starter selections. This is the same code path - // the client triggers when the player toggles "Starter Build" — the + // the client triggers when the player toggles "Starter Build" — the // resulting config is a complete, valid trait spend for the spec. WorldPackets::Traits::TraitConfig new_cfg(*active); TraitMgr::InitializeStarterBuildTraitConfig(new_cfg, p_); @@ -7334,7 +8006,7 @@ Result API::apply_starter_talents() // withCastTime=false (audit B05): the 1.5s "Applying Talents" commit // cast exists for client presentation; leveling bots move constantly, // the cast was interrupted, the result was never checked, and the - // fire-once idle rule never retried — so commits never landed anywhere. + // fire-once idle rule never retried — so commits never landed anywhere. // Commit immediately and VERIFY by re-reading the active config. p_->UpdateTraitConfig(std::move(new_cfg), 0, /*withCastTime*/ false); const uint32 ranks = CountActiveTraitRanks(p_); @@ -7345,6 +8017,23 @@ Result API::apply_starter_talents() return ranks > 0 ? Result::Ok : Result::Locked; } +// The trait edges that end at a node, indexed once. sTraitEdgeStore is a sparse array of about 1.4 million slots, and the talent walk below asks for the +// parents of a node for every refused pick, again after every rank it places and in each recursion: a scan of the whole store each time held the +// world thread for 60 s when a group of bots logged in together (168 freeze, the hot loop was this scan). +static std::vector const& TraitEdgesInto(int32 nodeId) +{ + static std::unordered_map> byRight; + static std::once_flag once; + static std::vector const none; + std::call_once(once, [] + { + for (TraitEdgeEntry const* edge : sTraitEdgeStore) + byRight[edge->RightTraitNodeID].push_back(edge); + }); + auto itr = byRight.find(nodeId); + return itr != byRight.end() ? itr->second : none; +} + Result API::apply_classic_talents() { if (!p_) return Result::Other; @@ -7357,6 +8046,73 @@ Result API::apply_classic_talents() auto const build = ::Playerbot::Classic::GetTalentBuild(p_->GetClass(), spec); if (build.empty()) return Result::NotKnown; + // The walk below validates the whole trait config once per rank and per refused pick (TraitMgr::FillOwnedCurrenciesMap and + // MeetsTraitCondition each time), which is seconds of world thread for one bot. Companions ask for it on every upkeep and a group of + // them logs in together (169 freeze: 60 s), so a bot whose level, specialization and purchased ranks are what its last walk left + // is not walked again, and walks that are still needed are spaced by a duty cycle (the caller is told Locked and asks again later). + struct TalentWalkState { uint8 level; uint32 spec; uint32 ranks; }; + static std::mutex s_walkLock; + static std::unordered_map s_walked; + static std::atomic s_nextWalkMs{ 0 }; + uint64 const walkKey = p_->GetGUID().GetCounter(); + { + std::lock_guard lock(s_walkLock); + auto const walked = s_walked.find(walkKey); + if (walked != s_walked.end() && walked->second.level == uint8(p_->GetLevel()) && walked->second.spec == spec + && walked->second.ranks == CountActiveTraitRanks(p_)) + return Result::Ok; + } + // Playerbot.ClassicTalents.ApplyOnLogin = 0 (default): a bot that already holds all the points of its level on the build its talents + // say it has (171 froze with 17 walks in one second at login) is not walked again; one that changed spec or still has points to place is. + static bool const applyOnLogin = sConfigMgr->GetBoolDefault("Playerbot.ClassicTalents.ApplyOnLogin", false, true); + if (!applyOnLogin) + { + uint32 const held = CountActiveTraitRanks(p_); + int32 const points = std::max(0, int32(p_->GetLevel()) - 9); + // The bot must hold the build as it is defined now: every pick, in the build's order, up to the points of its level, at the ranks the + // build lists. A build definition that changed (talent names corrected to Forever's nodes) or a spec pinned by a scenario fails this + // and the bot is walked once; a pick the class trees have no node for cannot be held and does not count against the bot. + bool holdsBuild = held > 0 && int32(held) >= points; + if (holdsBuild) + { + UF::TraitConfig const* activeCfg = p_->GetTraitConfig(p_->m_activePlayerData->ActiveCombatTraitConfigID); + int32 placed = 0; + for (::Playerbot::Classic::TalentPick const& pick : build) + { + if (placed >= points) + break; + if (pick.filler) + continue; + placed += pick.ranks; + ::Playerbot::Classic::TalentNode const* node = ::Playerbot::Classic::FindTalent(p_, pick.name); + if (!node) + continue; + int32 rank = 0; + for (UF::TraitEntry const& e : activeCfg->Entries) + if (e.TraitNodeID == node->TraitNodeID && e.TraitNodeEntryID == node->TraitNodeEntryID) + rank = e.Rank + e.GrantedRanks; + if (rank < std::min(pick.ranks, node->MaxRanks)) + { + holdsBuild = false; + break; + } + } + } + if (holdsBuild) + { + std::lock_guard lock(s_walkLock); + s_walked[walkKey] = { uint8(p_->GetLevel()), spec, held }; + return Result::Ok; + } + } + // At most one walk per world update, whatever the duty cycle says. + static std::atomic s_lastWalkLoop{ 0 }; + uint32 const loopNow = World::m_worldLoopCounter.load(); + if (loopNow == s_lastWalkLoop.load() || int32(getMSTime() - s_nextWalkMs.load()) < 0) + return Result::Locked; + s_lastWalkLoop.store(loopNow); + uint32 const walkStartMs = getMSTime(); + // Start from the free (granted) ranks only and buy the build rank by // rank. ValidateConfig enforces tier gates and the points the bot's // level grants: the first rank it refuses ends that talent, and the @@ -7383,18 +8139,126 @@ Result API::apply_classic_talents() std::vector buildTrees; // the trees the build spends in, in the order it first names them std::string unresolved; // build talents the class trees have no node for, by name - for (::Playerbot::Classic::TalentPick const& pick : build) + std::map rankOf; // pick name -> ranks held when its last visit ended + std::map refusedBy; // pick name -> the last LearnResult that stopped its ranks (the reason a talent is missing) + + // ValidateConfig answers from the config and the player alone, and the player does not change during the walk, so a rank it refused stays refused + // until another rank is bought. `cfgVersion` counts the ranks bought; a node or pick refused at the current version is not validated again. + // Without it fillParents filled every ancestor once per path to it (a node under two parents that share a parent: that one twice, and so on + // five levels up), and every refused pick, with its parents, was validated again after each leftover rank. On the 70532 client data (234, + // 2026-10-23) the walk held the world thread past the 60 s freeze detector, inside ValidateConfig, when chris targeted or cast. + uint32 cfgVersion = 0; + std::map parentsTriedAt; // node id -> cfgVersion when its parents were last filled + std::map pickTriedAt; // pick name -> cfgVersion when its ranks were last refused + + // Whatever the data, one walk may not hold the world thread longer than this: a walk cut short keeps the ranks it validated, says so once per + // class and spec, and the bot is not walked again until its level, spec or ranks change. + static uint32 const walkBudgetMs = sConfigMgr->GetIntDefault("Playerbot.ClassicTalents.WalkBudgetMs", 250, true); + uint32 validations = 0; + bool cutShort = false; + auto const overBudget = [&] + { + if (!cutShort && getMSTimeDiff(walkStartMs, getMSTime()) > walkBudgetMs) + cutShort = true; + return cutShort; + }; + auto const validate = [&] + { + ++validations; + return TraitMgr::ValidateConfig(cfg, p_); + }; + + // A talent below another is refused until a parent node is filled to its maximum (ValidateConfig), and a build that takes a + // parent only partway (3 of 5) loses everything under it. Buys the parents of a node, and theirs, up to their maximum ranks as + // far as ValidateConfig allows; true when at least one rank was bought. + // The class trees have edges both ways between two nodes (70532: ten pairs, 104708 <-> 104709 among them). Following one + // back to a node still being filled (`path`) found that node's entry before it held a rank and erased it, under the + // indexes the callers hold: the walk then wrote ranks past the end of the vector and erased from beyond it, which corrupted + // the heap and spun the world thread in memmove until the freeze detector ended it (234, crashes 00:49 and 00:55). + std::vector path; + std::vector const configNodes = TraitMgr::GetNodeEntriesForConfig(cfg); + std::function fillParents = [&](int32 nodeId, int32 depth) -> bool + { + bool bought = false; + if (depth > 4 || overBudget() || std::ranges::find(path, nodeId) != path.end()) + return false; + // Filled already with the config as it stands: the same ranks would be refused again. + if (auto [tried, first] = parentsTriedAt.try_emplace(nodeId, cfgVersion); !first) + { + if (tried->second == cfgVersion) + return false; + tried->second = cfgVersion; + } + path.push_back(nodeId); + for (TraitEdgeEntry const* edge : TraitEdgesInto(nodeId)) + { + if (overBudget()) + break; + if (std::ranges::find(path, int32(edge->LeftTraitNodeID)) != path.end()) + continue; + auto info = std::ranges::find(configNodes, edge->LeftTraitNodeID, &TraitMgr::NodeEntryInfo::TraitNodeID); + if (info == configNodes.end()) + continue; + + auto itr = std::ranges::find_if(cfg.Entries, [&](WorldPackets::Traits::TraitEntry const& e) + { + return e.TraitNodeID == info->TraitNodeID && e.TraitNodeEntryID == info->TraitNodeEntryID; + }); + bool const added = itr == cfg.Entries.end(); + if (added) + { + WorldPackets::Traits::TraitEntry& entry = cfg.Entries.emplace_back(); + entry.TraitNodeID = info->TraitNodeID; + entry.TraitNodeEntryID = info->TraitNodeEntryID; + itr = std::prev(cfg.Entries.end()); + } + size_t const index = size_t(std::distance(cfg.Entries.begin(), itr)); + + // the parent's own parents first, or its ranks are refused as well + if (cfg.Entries[index].Rank + cfg.Entries[index].GrantedRanks < info->MaxRanks && fillParents(info->TraitNodeID, depth + 1)) + bought = true; + // that call can add entries, but only after this one + while (cfg.Entries[index].Rank + cfg.Entries[index].GrantedRanks < info->MaxRanks && !overBudget()) + { + ++cfg.Entries[index].Rank; + if (validate() != TraitMgr::LearnResult::Ok) + { + --cfg.Entries[index].Rank; + break; + } + ++cfgVersion; + bought = true; + } + // only the entry this call added: one that was there before belongs to a caller + if (added && !cfg.Entries[index].Rank && !cfg.Entries[index].GrantedRanks) + cfg.Entries.erase(cfg.Entries.begin() + index); + } + path.pop_back(); + return bought; + }; + + // Buys the pick's ranks as far as ValidateConfig allows; true when at least one rank was bought. `firstVisit` records + // the pick's name and tree once (the walk below passes over every pick more than once). + auto buyPick = [&](::Playerbot::Classic::TalentPick const& pick, bool firstVisit) -> bool { ::Playerbot::Classic::TalentNode const* node = ::Playerbot::Classic::FindTalent(p_, pick.name); if (!node) { - if (!unresolved.empty()) - unresolved += ", "; - unresolved += pick.name; - continue; + if (firstVisit) + { + if (!unresolved.empty()) + unresolved += ", "; + unresolved += pick.name; + } + return false; } - if (std::ranges::find(buildTrees, treeOf(node->TraitNodeID)) == buildTrees.end()) + if (firstVisit && std::ranges::find(buildTrees, treeOf(node->TraitNodeID)) == buildTrees.end()) buildTrees.push_back(treeOf(node->TraitNodeID)); + if (overBudget()) + return false; + // refused with the config as it stands (its parents tried as well): nothing has been bought since that would let a rank through + if (auto tried = pickTriedAt.find(pick.name); tried != pickTriedAt.end() && tried->second == cfgVersion) + return false; auto entryItr = std::ranges::find_if(cfg.Entries, [&](WorldPackets::Traits::TraitEntry const& e) { @@ -7409,18 +8273,48 @@ Result API::apply_classic_talents() } size_t const entryIndex = size_t(std::distance(cfg.Entries.begin(), entryItr)); + int32 const before = cfg.Entries[entryIndex].Rank; int32 const target = std::min(pick.ranks, node->MaxRanks - cfg.Entries[entryIndex].GrantedRanks); - while (cfg.Entries[entryIndex].Rank < target) + for (bool parentsTried = false; ; parentsTried = true) { - ++cfg.Entries[entryIndex].Rank; - if (TraitMgr::ValidateConfig(cfg, p_) != TraitMgr::LearnResult::Ok) + while (cfg.Entries[entryIndex].Rank < target && !overBudget()) { - --cfg.Entries[entryIndex].Rank; - break; + ++cfg.Entries[entryIndex].Rank; + if (TraitMgr::LearnResult const result = validate(); result != TraitMgr::LearnResult::Ok) + { + --cfg.Entries[entryIndex].Rank; + refusedBy[pick.name] = int32(AsUnderlyingType(result)); + break; + } + ++cfgVersion; + refusedBy.erase(pick.name); } + // refused: fill the parent nodes to their maximum once and try the remaining ranks again + if (parentsTried || cfg.Entries[entryIndex].Rank >= target || !fillParents(node->TraitNodeID, 0)) + break; } + bool const bought = cfg.Entries[entryIndex].Rank > before; + if (cfg.Entries[entryIndex].Rank < target) + pickTriedAt[pick.name] = cfgVersion; + rankOf[pick.name] = cfg.Entries[entryIndex].Rank; if (!cfg.Entries[entryIndex].Rank && !cfg.Entries[entryIndex].GrantedRanks) cfg.Entries.erase(cfg.Entries.begin() + entryIndex); + return bought; + }; + + // A talent in a deeper tier is refused until the tab holds enough points (ValidateConfig's tier gates), and the build lists + // talents in levelling order, so a single walk lost every talent whose tier the earlier picks had not opened yet (the arms + // bot ended with no Deep Wounds, Two-Handed Weapon Specialization, Impale or Sweeping Strikes: damage_parity 2026-10-21). + // Walk the build again until a pass buys nothing; the fillers come last, with the points left. + for (bool filler : { false, true }) + { + for (bool progress = true, firstVisit = true; progress; firstVisit = false) + { + progress = false; + for (::Playerbot::Classic::TalentPick const& pick : build) + if (pick.filler == filler && buyPick(pick, firstVisit)) + progress = true; + } } // Points the build couldn't place (a name Forever's trees spell differently, a prerequisite it doesn't list) were // left unspent: a level 60 paladin sat on 13 of 51 (Celestera, 2026-10-05). Spend the rest down the trees, the one @@ -7451,11 +8345,23 @@ Result API::apply_classic_talents() }); // One rank per talent per pass, repeated until a pass places nothing: the first tree takes every point it can // (its deeper tiers open as it fills) before a point goes to the next one. - for (bool placed = true; placed; ) + // A level L bot has L - 9 points to spend (51 at 60). Every point bought ends the walk below, and the pass that finds nothing + // left to place validates every talent of the class once more, so a bot whose points are all spent does not go through it. + int32 const pointsForLevel = std::max(0, int32(p_->GetLevel()) - 9); + auto const ranksBought = [&cfg] + { + int32 total = 0; + for (WorldPackets::Traits::TraitEntry const& e : cfg.Entries) + total += std::max(0, e.Rank); + return total; + }; + for (bool placed = true; placed && ranksBought() < pointsForLevel && !overBudget(); ) { placed = false; for (TraitMgr::NodeEntryInfo const& info : nodes) { + if (overBudget()) + break; auto entryItr = std::ranges::find_if(cfg.Entries, [&](WorldPackets::Traits::TraitEntry const& e) { return e.TraitNodeID == info.TraitNodeID && e.TraitNodeEntryID == info.TraitNodeEntryID; @@ -7471,9 +8377,19 @@ Result API::apply_classic_talents() if (entryItr->Rank + entryItr->GrantedRanks < info.MaxRanks) { ++entryItr->Rank; - if (TraitMgr::ValidateConfig(cfg, p_) == TraitMgr::LearnResult::Ok) + if (validate() == TraitMgr::LearnResult::Ok) { + ++cfgVersion; placed = true; + // A build talent refused for want of points in its tab (Vengeance, 147) is tried again as each rank lands: the + // leftover points would otherwise take all of what it needs by the time its tier opens. + std::vector retry; + for (auto const& [name, result] : refusedBy) + retry.push_back(name); + for (std::string const& name : retry) + for (::Playerbot::Classic::TalentPick const& pick : build) + if (name == pick.name) + buyPick(pick, false); break; // restart from the top: the preferred tree's next rank may have just opened } --entryItr->Rank; @@ -7498,8 +8414,7 @@ Result API::apply_classic_talents() for (UF::TraitEntry const& e : active->Entries) if (e.Rank > 0) current[{ e.TraitNodeID, e.TraitNodeEntryID }] = e.Rank; - if (ranksOf(cfg.Entries) == current) - return Result::Ok; // already on the build for this level + bool const already = ranksOf(cfg.Entries) == current; // already on the build for this level // Ranks per tree, the build's trees first: shows whether the tabs were told apart. std::map perTree; @@ -7513,9 +8428,119 @@ Result API::apply_classic_talents() if (std::ranges::find(buildTrees, tree) == buildTrees.end()) split += (split.empty() ? "" : "/") + std::to_string(ranks); - p_->UpdateTraitConfig(std::move(cfg), 0, /*withCastTime*/ false); - TC_LOG_INFO("playerbot.api", "[API::talents] {} classic build for spec {} committed: {} ranks, per tree {} (build talents not found: {})", - p_->GetName(), spec, CountActiveTraitRanks(p_), split, unresolved.empty() ? "none" : unresolved); + // Every talent the walk left ranks in, by name (read before UpdateTraitConfig moves the config): the build's picks and the points the leftover pass + // spent. Parity 200 (fire mage 575 against 743) had the same auras up as 184 and nothing to say which ranks differed. + std::string heldRanks; + if (!already && p_->GetLevel() >= 60) + for (std::string const& n : ::Playerbot::Classic::ListTalentNames(p_)) + if (::Playerbot::Classic::TalentNode const* node = ::Playerbot::Classic::FindTalent(p_, n)) + for (WorldPackets::Traits::TraitEntry const& e : cfg.Entries) + if (e.Rank > 0 && e.TraitNodeID == node->TraitNodeID && e.TraitNodeEntryID == node->TraitNodeEntryID) + heldRanks += fmt::format("{}{}={}/{}", heldRanks.empty() ? "" : ", ", n, e.Rank, node->MaxRanks); + + if (!already) + p_->UpdateTraitConfig(std::move(cfg), 0, /*withCastTime*/ false); + if (!unresolved.empty() && p_->GetLevel() >= 60) + { + // once per class and process: the names the client data gives this class's talents, to correct the build's + static std::mutex s_namesLock; + static std::set s_namesLogged; + std::lock_guard lock(s_namesLock); + if (s_namesLogged.insert(p_->GetClass()).second) + { + std::string all; + // with each node's row, the ranks this bot holds and the nodes it hangs under, so a build can be mapped onto the tab + for (std::string const& n : ::Playerbot::Classic::ListTalentNames(p_)) + { + std::string info; + if (::Playerbot::Classic::TalentNode const* node = ::Playerbot::Classic::FindTalent(p_, n)) + { + TraitNodeEntry const* tn = sTraitNodeStore.LookupEntry(node->TraitNodeID); + int32 held = 0; + for (WorldPackets::Traits::TraitEntry const& e : cfg.Entries) + if (e.TraitNodeID == node->TraitNodeID && e.TraitNodeEntryID == node->TraitNodeEntryID) + held = e.Rank; + std::string parents; + for (TraitEdgeEntry const* edge : TraitEdgesInto(node->TraitNodeID)) + parents += (parents.empty() ? "" : "+") + std::to_string(edge->LeftTraitNodeID) + "t" + std::to_string(edge->Type); + info = fmt::format("[{} y{} {}/{}{}{}]", node->TraitNodeID, tn ? tn->PosY : -1, held, node->MaxRanks, parents.empty() ? "" : " under ", parents); + } + all += (all.empty() ? "" : ", ") + n + info; + } + TC_LOG_INFO("playerbot.api", "[API::talents] class {} talent names in the client data: {}", uint32(p_->GetClass()), all); + } + } + std::string refused; // build talents left short of their ranks, with ValidateConfig's LearnResult + for (auto const& [name, result] : refusedBy) + refused += (refused.empty() ? "" : ", ") + name + "=" + std::to_string(result) + " (holds " + std::to_string(rankOf.contains(name) ? rankOf[name] : 0) + ")"; + // The detail walks the edge store per refused talent: once per class and spec, and only for a bot with every point (a levelling bot's + // refusals are its level; build 171 hung the world thread for 60 s with the lines written for every bot of the roster). + static std::mutex s_detailLock; + static std::set s_detailLogged; + bool logDetail = false; + if (!refusedBy.empty() && p_->GetLevel() >= 60) + { + std::lock_guard lock(s_detailLock); + logDetail = s_detailLogged.insert(uint32(p_->GetClass()) << 16 | spec).second; + } + if (logDetail) + { + // Where each build pick sits and what it holds, to see which tab's points the refused one is waiting for: node id, the currencies + // its tab spends (Forever's three tabs share one tree and differ by currency), the posY row, and the ranks held. + std::string detail; + for (::Playerbot::Classic::TalentPick const& pick : build) + if (::Playerbot::Classic::TalentNode const* node = ::Playerbot::Classic::FindTalent(p_, pick.name)) + { + std::string currencies; + for (int32 c : std::get<2>(treeOf(node->TraitNodeID))) + currencies += (currencies.empty() ? "" : "+") + std::to_string(c); + TraitNodeEntry const* tn = sTraitNodeStore.LookupEntry(node->TraitNodeID); + int32 held = 0; + for (WorldPackets::Traits::TraitEntry const& e : cfg.Entries) + if (e.TraitNodeID == node->TraitNodeID && e.TraitNodeEntryID == node->TraitNodeEntryID) + held = e.Rank; + detail += fmt::format("{}{}[node {} cur {} y {} {}/{}]", detail.empty() ? "" : ", ", pick.name, node->TraitNodeID, currencies, tn ? tn->PosY : -1, held, node->MaxRanks); + } + TC_LOG_INFO("playerbot.api", "[API::talents] refused detail: {}", detail); + // The nodes a refused pick hangs under: ValidateConfig refuses it (LearnResult 2) until a RequiredForAvailability parent is full. + for (auto const& [name, result] : refusedBy) + if (::Playerbot::Classic::TalentNode const* node = ::Playerbot::Classic::FindTalent(p_, name)) + { + std::string parents; + for (TraitEdgeEntry const* edge : TraitEdgesInto(node->TraitNodeID)) + { + auto info = std::ranges::find(configNodes, edge->LeftTraitNodeID, &TraitMgr::NodeEntryInfo::TraitNodeID); + int32 held = 0; + for (WorldPackets::Traits::TraitEntry const& e : cfg.Entries) + if (info != configNodes.end() && e.TraitNodeID == info->TraitNodeID && e.TraitNodeEntryID == info->TraitNodeEntryID) + held = e.Rank + e.GrantedRanks; + parents += fmt::format("{}node {} edge type {} {}/{}", parents.empty() ? "" : ", ", edge->LeftTraitNodeID, edge->Type, held, + info != configNodes.end() ? info->MaxRanks : -1); + } + TC_LOG_INFO("playerbot.api", "[API::talents] refused {} (node {}) has parents: {}", name, node->TraitNodeID, parents.empty() ? "none" : parents); + } + } + TC_LOG_INFO("playerbot.api", "[API::talents] {} classic build for spec {} {}: {} ranks, per tree {} (build talents not found: {}; refused: {})", + p_->GetName(), spec, already ? "already in place" : "committed", CountActiveTraitRanks(p_), split, unresolved.empty() ? "none" : unresolved, refused.empty() ? "none" : refused); + if (!heldRanks.empty()) + TC_LOG_INFO("playerbot.api", "[API::talents] {} spec {} holds: {}", p_->GetName(), spec, heldRanks); + { + static std::mutex s_cutLock; + static std::set s_cutLogged; + std::lock_guard lock(s_cutLock); + if (cutShort && s_cutLogged.insert(uint32(p_->GetClass()) << 16 | spec).second) + TC_LOG_ERROR("playerbot.api", "[API::talents] {} classic build for spec {} cut short after {} ms and {} validations ({} ranks placed, budget " + "Playerbot.ClassicTalents.WalkBudgetMs = {}): the class trees make the walk too long", p_->GetName(), spec, + getMSTimeDiff(walkStartMs, getMSTime()), validations, CountActiveTraitRanks(p_), walkBudgetMs); + } + { + uint32 const now = getMSTime(); + s_nextWalkMs.store(now + 3 * getMSTimeDiff(walkStartMs, now)); + std::lock_guard lock(s_walkLock); + if (s_walked.size() > 8192) + s_walked.clear(); + s_walked[walkKey] = { uint8(p_->GetLevel()), spec, CountActiveTraitRanks(p_) }; + } return CountActiveTraitRanks(p_) > 0 ? Result::Ok : Result::Locked; } @@ -7550,8 +8575,56 @@ Result API::restock_class_supplies() if (s_supplyReasonLogged.insert(key).second) TC_LOG_INFO("playerbot.v2", "[supplies] {} gets no {} (item {}): {} ({})", p_->GetName(), f.name, item, why, detail); }; - for (Classic::SupplyFamily const& f : Classic::GetSupplyFamilies()) + // Food and drink first, and room made for them (JunkDrop.h PickRoomForSupply): bots have endless supplies, and the families were + // stocked in table order, so reagents and potions took the last free slots and a healer with full bags got no water at all + // (deadmines_full on 0.1.23: "Scnpriest gets no Water: no room in the bags", then healer_no_rest and healer_oom). + auto const essential = [](Classic::SupplyFamily const& f) + { return std::string_view(f.name) == "Food" || std::string_view(f.name) == "Water"; }; + // Spare: the shared consumables (potions, Demonic Runes, bandages), never a class tool or reagent (totems, shards, poisons). + auto const spare_supply = [&](uint32 entry) { + for (Classic::SupplyFamily const& f : Classic::GetSupplyFamilies()) + if (!essential(f) && f.cls == 0) + for (Classic::SupplyRank const& r : f.ranks) + if (r.item == entry) + return true; + return false; + }; + // Destroys one grey, else one spare supply stack, to make room; false when nothing may go. + auto const make_room = [&](Classic::SupplyFamily const& f, uint32 entry) + { + std::vector cands; + std::vector cand_items; + p_->ForEachItem(ItemSearchLocation::Inventory, [&](Item* bi) + { + ItemTemplate const* bt = bi ? bi->GetTemplate() : nullptr; + if (bt && !bi->IsBag() && bi->GetEntry() != entry) + { + cands.push_back({ uint64(bt->GetSellPrice()) * bi->GetCount(), bt->GetQuality() == ITEM_QUALITY_POOR, + bt->GetClass() == ITEM_CLASS_QUEST, spare_supply(bi->GetEntry()) }); + cand_items.push_back(bi); + } + return ItemSearchCallbackResult::Continue; + }); + std::size_t const v = PickRoomForSupply(cands); + if (v == kNoJunk) + return false; + Item* victim = cand_items[v]; + TC_LOG_INFO("playerbot.v2", "[supplies] {} destroys item {} x{} ({}) to make room for {} (item {})", p_->GetName(), victim->GetEntry(), + victim->GetCount(), cands[v].poor ? "grey" : "spare supply", f.name, entry); + p_->DestroyItem(victim->GetBagSlot(), victim->GetSlot(), true); + return true; + }; + std::vector families; + for (Classic::SupplyFamily const& f : Classic::GetSupplyFamilies()) + if (essential(f)) + families.push_back(&f); + for (Classic::SupplyFamily const& f : Classic::GetSupplyFamilies()) + if (!essential(f)) + families.push_back(&f); + for (Classic::SupplyFamily const* fp : families) + { + Classic::SupplyFamily const& f = *fp; if (!Classic::SupplyFamilyForClass(f, p_->GetClass())) continue; if (Classic::MageConjuresFamily(p_->GetClass(), f.name, [this](uint32 id) { return p_->HasSpell(id); })) continue; uint32 const entry = Classic::BestSupplyRank(f, level); @@ -7595,19 +8668,35 @@ Result API::restock_class_supplies() uint32 const target = Classic::SupplyTarget(f, level); if (have >= target) continue; ItemPosCountVec dest; - if (InventoryResult const stored = p_->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, entry, target - have); stored != EQUIP_ERR_OK) + uint32 count = target - have; + uint32 no_space = 0; + InventoryResult stored = p_->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, entry, count, &no_space); + // Food and drink: make room (a few slots at most), then take what fits. + for (int freed = 0; stored != EQUIP_ERR_OK && essential(f) && freed < 4 && make_room(f, entry); ++freed) + { + dest.clear(); + no_space = 0; + stored = p_->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, entry, count, &no_space); + } + if (stored != EQUIP_ERR_OK && no_space > 0 && no_space < count) + { + count -= no_space; // part of the stack fits + dest.clear(); + stored = p_->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, entry, count); + } + if (stored != EQUIP_ERR_OK) { full = true; skipped(f, entry, "no room in the bags", uint32(stored)); continue; } if (p_->StoreNewItem(dest, entry, true)) - added += target - have; + added += count; else skipped(f, entry, "StoreNewItem refused", 0); } // Ammo for the equipped bow / crossbow / gun (thrown needs none): the best arrows or - // bullets the level allows, topped up in whole stacks to AMMO_TARGET once under 30%. + // bullets the level allows, topped up in whole stacks to AMMO_TARGET once under 60%. // Hunter pet food is the plain "Food" family above and is not touched here. if (p_->NeedsAmmo()) { @@ -7622,11 +8711,12 @@ Result API::restock_class_supplies() p_->ForEachItem(ItemSearchLocation::Inventory, [&](Item* item) { ItemTemplate const* t = item->GetTemplate(); - if (t->GetClass() == ITEM_CLASS_PROJECTILE && t->GetSubClass() == ammoProto->GetSubClass()) + // Only stacks the bot can use count: a stack too high for its level (a level 3 hunter holding level 10 bullets) is no supply. + if (t->GetClass() == ITEM_CLASS_PROJECTILE && t->GetSubClass() == ammoProto->GetSubClass() && p_->CanUseItem(t) == EQUIP_ERR_OK) have += item->GetCount(); return ItemSearchCallbackResult::Continue; }); - if (have < Classic::AmmoLowBelow()) + if (have < Classic::AMMO_TARGET) // whenever the restock runs: to the full stack { uint32 given = 0; uint32 const stack = std::max(1u, ammoProto->GetMaxStackSize()); @@ -7688,7 +8778,7 @@ Result API::bg_queue(ObjectGuid battlemaster, uint16 bg_type_id, uint8 arena_typ { if (!p_) return Result::Other; // Empty battlemaster GUID signals the UI-equivalent path (PVP browser / - // queue-from-anywhere) — no NPC interaction required. Bot-driven queues + // queue-from-anywhere) — no NPC interaction required. Bot-driven queues // (BotQueueFiller, /bg whisper, JIT spawn) use this path because the bot // isn't always standing at a battlemaster. Non-empty GUID still validates // NPC range as before for /bg via NPC click. @@ -7736,7 +8826,7 @@ Result API::bg_queue(ObjectGuid battlemaster, uint16 bg_type_id, uint8 arena_typ // category (BattlegroundQueueIdType::Arena) keyed by team size; the // BG category is HARDCODED-teamSize-0. `arena_type` (2/3/5) selects // the skirmish bracket; we also treat any arena-flagged template as - // an arena even if the caller passed 0 (defensive — a bot should + // an arena even if the caller passed 0 (defensive — a bot should // never end up BG-queued onto an arena map). rated=false: bots run // SKIRMISH arenas (no arena-team / MMR dependency), mirroring // HandleBattlemasterJoinArena with arena teams disabled. @@ -7824,7 +8914,7 @@ Result API::bg_queue(ObjectGuid battlemaster, uint16 bg_type_id, uint8 arena_typ "[bg_queue] {} queued GROUP of {} for bg_type_id={} (arena_type={} premade={})", p_->GetName(), grp->GetMembersCount(), bg_type_id, uint32(arena_type), isPremade ? 1 : 0); - // Fill the rest of the match (both factions — most importantly the + // Fill the rest of the match (both factions — most importantly the // OPPOSING team, which nothing else provides for a bot premade). // The module's hook handler lets bot GROUP LEADERS through for // exactly this purpose (audit B25). For arenas the opposing team is @@ -7834,7 +8924,7 @@ Result API::bg_queue(ObjectGuid battlemaster, uint16 bg_type_id, uint8 arena_typ Playerbot::V2::Module::instance().OnPlayerJoinedBgQueue(p_, bg_type_id, bracket->GetBracketId()); return Result::Ok; } - // SOLO path below. Arenas have no solo queue — they require a full + // SOLO path below. Arenas have no solo queue — they require a full // arena_type-sized group whose leader queues (the GROUP branch above). // A solo arena request can only come from a mis-emitted intent (the // group dissolved before the deferred queue fired); reject it cleanly @@ -7848,7 +8938,7 @@ Result API::bg_queue(ObjectGuid battlemaster, uint16 bg_type_id, uint8 arena_typ if (p_->IsDeserter()) { TC_LOG_INFO("playerbot.v2", "[bg_queue] {} reject: deserter", p_->GetName()); return Result::Locked; } if (p_->GetBattlegroundQueueIndex(qid) < PLAYER_MAX_BATTLEGROUND_QUEUES) - return Result::Ok; // already queued — idempotent + return Result::Ok; // already queued — idempotent if (!p_->HasFreeBattlegroundQueueId()) { TC_LOG_INFO("playerbot.v2", "[bg_queue] {} reject: no_free_queue_slot", p_->GetName()); return Result::Locked; } @@ -7887,7 +8977,7 @@ Result API::lfg_proposal_respond(uint32 proposal_id, bool accept) { if (!p_) return Result::Other; if (proposal_id == 0) return Result::Locked; - // sLFGMgr->UpdateProposal silently no-ops on missing proposal — re-check + // sLFGMgr->UpdateProposal silently no-ops on missing proposal — re-check // via the read-only accessor so we surface the state to the caller. if (sLFGMgr->GetActiveProposalIdForPlayer(p_->GetGUID()) != proposal_id) return Result::Locked; @@ -7904,7 +8994,7 @@ Result API::bg_port(uint16 bg_type_id, bool accept) // hooks can race a second intent through after a successful port; the // RemovePlayerAtLeave + SendToBattleground sequence below then re-enters // Map::RemovePlayerFromMap while the bot is mid-teleport, hitting the - // ASSERT at Map.cpp:935 ("remove" — player not in grid). + // ASSERT at Map.cpp:935 ("remove" — player not in grid). if (accept && p_->InBattleground()) { if (Battleground const* cur = p_->GetBattleground()) @@ -7918,7 +9008,7 @@ Result API::bg_port(uint16 bg_type_id, bool accept) } } } - // Also reject when the bot's not in a grid — mid-teleport or pending + // Also reject when the bot's not in a grid — mid-teleport or pending // logout. Map::RemovePlayerFromMap would fire the same ASSERT in this // window. The caller will retry on a later tick once the teleport // settles. @@ -7989,6 +9079,14 @@ Result API::bg_port(uint16 bg_type_id, bool accept) if (p_->GetLevel() > bg->GetMaxLevel()) return Result::Locked; if (p_->HasAura(/*Freeze*/ 9454)) return Result::Locked; if (!p_->IsInvitedForBattlegroundQueueType(qid)) return Result::Locked; + // TeleportTo refuses while another teleport is pending, and SendToBattleground does not say so: the bot kept the battleground + // id set below while it stayed in the world (WSG 2026-10-24: a fresh JIT bot whose setup teleport was still running ported, stayed + // in Redridge and held an Alliance place and an order slot all match). It stays invited, so the port is fired again later. + if (p_->IsBeingTeleported()) + { + TC_LOG_INFO("playerbot.v2", "[bg_port] {} teleport still pending; deferring", p_->GetName()); + return Result::NotReady; + } if (!p_->InBattleground()) p_->SetBattlegroundEntryPoint(); @@ -8004,10 +9102,20 @@ Result API::bg_port(uint16 bg_type_id, bool accept) p_->SetBattlegroundId(bg->GetInstanceID(), bg->GetTypeID(), qid); p_->SetBGTeam(ginfo.Team); BattlegroundMgr::SendToBattleground(p_, bg); + // A far teleport leaves the old map at once (or waits as a delayed world port); still in the world on another map with no teleport + // pending means it was refused. Undo the battleground id the way the world-port handler does on a non-battleground map. + if (p_->IsInWorld() && !p_->IsBeingTeleported() && p_->GetMapId() != bg->GetMapId()) + { + TC_LOG_INFO("playerbot.v2", "[bg_port] {} port to bg_inst={} refused (still on map {}); battleground id cleared", + p_->GetName(), bg->GetInstanceID(), p_->GetMapId()); + p_->SetBattlegroundId(0, BATTLEGROUND_TYPE_NONE, BATTLEGROUND_QUEUE_NONE); + p_->SetBGTeam(TEAM_OTHER); + return Result::ServerRefused; + } // Seething Shore (BG_SS = 894) post-port fix. SS uses a transport // (airship) for initial player placement. Bots porting via this - // API don't always attach to the transport correctly — they land + // API don't always attach to the transport correctly — they land // in mid-air at the airship's spawn coord, fall into water and // drown before the snapshot can react. Manually teleport them to // a known-safe inland coord on solid ground (Air Supply landing @@ -8015,8 +9123,8 @@ Result API::bg_port(uint16 bg_type_id, bool accept) if (bgTypeId == BATTLEGROUND_SS) { // Team-specific safe coords (mirror SeethingShoreScript home_base). - // Horde: Air Supply 3 area — (1226.99, 2825.09, 39.26) - // Alliance: Air Supply 1 area — (1398.72, 2728.05, 28.02) + // Horde: Air Supply 3 area — (1226.99, 2825.09, 39.26) + // Alliance: Air Supply 1 area — (1398.72, 2728.05, 28.02) WorldLocation safe(/*mapId*/ 1803, Position(1398.72f, 2728.05f, 28.02f, 0.f)); if (ginfo.Team == HORDE) @@ -8063,7 +9171,7 @@ Result API::bg_leave() } return Result::Ok; } - // Not in BG — drop from any active queues. Walk the per-player queue + // Not in BG — drop from any active queues. Walk the per-player queue // slot table and remove each registered queue. bool any = false; for (uint8 i = 0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i) @@ -8093,7 +9201,7 @@ Result API::auction_sell_item(ObjectGuid auctioneer, ObjectGuid item_guid, Creature* npc = p_->GetNPCIfCanInteractWith(auctioneer, UNIT_NPC_FLAG_AUCTIONEER, UNIT_NPC_FLAG_2_NONE); if (!npc) return Result::InvalidTarget; - // Mirror the live handler's price gating: silver-aligned, > 0, ≤ cap. + // Mirror the live handler's price gating: silver-aligned, > 0, ≤ cap. if (min_bid == 0 && buyout == 0) return Result::Locked; if (min_bid > MAX_MONEY_AMOUNT || buyout > MAX_MONEY_AMOUNT) return Result::Locked; if ((min_bid % SILVER) != 0 || (buyout % SILVER) != 0) return Result::Locked; @@ -8131,7 +9239,7 @@ Result API::auction_sell_item(ObjectGuid auctioneer, ObjectGuid item_guid, auction.Owner = p_->GetGUID(); // OwnerAccount: bots don't carry an account-guid value the same way // sessions do; the live handler reads GetAccountGUID() (the bnet acc - // guid). For bot-owned auctions we leave it Empty — outbid/sold mail + // guid). For bot-owned auctions we leave it Empty — outbid/sold mail // resolution falls back to Owner. auction.OwnerAccount = ObjectGuid::Empty; auction.MinBid = min_bid; @@ -8243,7 +9351,7 @@ Result API::auction_cancel(ObjectGuid auctioneer, uint32 auction_id) if (!auction->Bidder.IsEmpty()) { // Live handler debits 5% of the active bid as a cancel fee, refunds - // bid via mail. Reject up-front when we can't afford the fee — the + // bid via mail. Reject up-front when we can't afford the fee — the // auction stays alive untouched. uint64 cancel_cost = CalculatePct(auction->BidAmount, 5u); if (!p_->HasEnoughMoney(cancel_cost)) return Result::NotEnoughResource; @@ -8313,7 +9421,7 @@ Result API::auction_buyout(ObjectGuid auctioneer, uint32 auction_id, uint64 max_ if (auction->Owner == p_->GetGUID()) return Result::Locked; const uint64 buyout = auction->BuyoutOrUnitPrice; - if (buyout == 0) return Result::NotKnown; // bid-only listing — use auction_bid + if (buyout == 0) return Result::NotKnown; // bid-only listing — use auction_bid // Caller-supplied price guard: refuse if the LIVE buyout exceeds what the // economy rule agreed to (the snapshot-observed price). Protects against a @@ -8402,7 +9510,7 @@ Result API::auction_bid(ObjectGuid auctioneer, uint32 auction_id, uint64 bid) if (can_buyout && bid == auction->BuyoutOrUnitPrice) { - // Bid hit the buyout — complete the sale. + // Bid hit the buyout — complete the sale. std::map::node_type removed = auction_house->RemoveAuction(trans, auction); auction_house->SendAuctionSold(&removed.mapped(), nullptr, trans); auction_house->SendAuctionWon(&removed.mapped(), p_, trans); @@ -8444,7 +9552,7 @@ Result API::auction_buy_commodity(ObjectGuid auctioneer, uint32 item_entry, // we create a quote over the cheapest non-self listings, validate the // total against the caller's slippage guard + the bot's gold, then commit // BuyCommodity in one synchronous character-DB transaction (no client - // confirm round-trip — quote+buy are atomic for a server-driven bot). + // confirm round-trip — quote+buy are atomic for a server-driven bot). if (!p_) return Result::Other; if (quantity == 0) return Result::NotKnown; Creature* npc = p_->GetNPCIfCanInteractWith(auctioneer, UNIT_NPC_FLAG_AUCTIONEER, UNIT_NPC_FLAG_2_NONE); @@ -8464,7 +9572,7 @@ Result API::auction_buy_commodity(ObjectGuid auctioneer, uint32 item_entry, // listings, sums unit prices for `quantity` units, and stashes the quote // keyed by the bot's GUID (consumed by BuyCommodity::extract below). Null // means: no template, no bucket, not enough quantity listed, or the bot - // can't afford the total — collapse all to NotKnown (no buyable supply). + // can't afford the total — collapse all to NotKnown (no buyable supply). CommodityQuote const* quote = auction_house->CreateCommodityQuote(p_, item_entry, quantity); if (!quote) return Result::NotKnown; @@ -8490,7 +9598,7 @@ Result API::auction_buy_commodity(ObjectGuid auctioneer, uint32 item_entry, // Commit. BuyCommodity re-walks the bucket, re-validates total <= quoted // (allows a LOWER price if cheaper listings appeared), debits the bot, - // mails the items to the bot, and removes the consumed listings — all + // mails the items to the bot, and removes the consumed listings — all // appended onto `trans`. delayForNextAction is the throttle delay echoed // back in the result packet; immaterial for a bot, pass 0ms. CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); @@ -8580,14 +9688,14 @@ Result API::craft_fulfill_order(uint64 order_id, uint32 spell_id, uint32 item_en // Stage the product as a standalone item owned by the requester and mail // it. We create it directly (not into the crafter's bags) so the delivery - // doesn't depend on the crafter having free bag space — mirroring the + // doesn't depend on the crafter having free bag space — mirroring the // clone-and-save path in mail_send_item. Respect the item's max stack by // splitting into multiple attachments / mails as needed. const uint32 max_stack = std::max(1u, tmpl->GetMaxStackSize()); CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); uint32 remaining = qty; bool any_mailed = false; - // Bound the number of attachments per mail (MAX_MAIL_ITEMS) — start a new + // Bound the number of attachments per mail (MAX_MAIL_ITEMS) — start a new // mail when full. For typical small craft orders this is a single mail. while (remaining > 0) { @@ -8663,7 +9771,7 @@ uint64 API::gold_cost_estimate_reagent_buy(uint32 reagent_entry, uint32 desired_ const uint32 need = desired_total - have; // Vendor price is per BuyCount-sized stack; bots pay BuyPrice per stack, - // so per-unit = BuyPrice / BuyCount (round up to be conservative — the + // so per-unit = BuyPrice / BuyCount (round up to be conservative — the // affordability gate should never under-estimate). const uint32 buy_count = std::max(tmpl->GetBuyCount(), 1u); const uint64 stack_price = tmpl->GetBuyPrice(); @@ -8695,7 +9803,7 @@ Result API::discover_taxi_node(ObjectGuid flight_master) unit->GetPositionX(), unit->GetPositionY(), unit->GetPositionZ(), unit->GetMapId(), p_->GetTeam()); if (!node) return Result::NotKnown; - // SetTaximaskNode returns false when the node was already known — + // SetTaximaskNode returns false when the node was already known — // surface that as Ok (idempotent), false-from-an-unknown-node would // be Other but isn't reachable since the node was just resolved. p_->m_taxi.SetTaximaskNode(node); @@ -8750,7 +9858,7 @@ Result API::fly_to_node(ObjectGuid flight_master, uint32 to_node) return Result::Locked; } // Bots are perpetually broke (a fresh L3 has ~67 copper), and - // ActivateTaxiPathTo charges the taxi fare — so flights silently failed and + // ActivateTaxiPathTo charges the taxi fare — so flights silently failed and // the bot ran back and forth at the FM forever. Cover the fare: top the bot // up to a flight reserve so it can always afford the hop (bots are bot logic; a free // ride is fine, and this is far cheaper than the leveling time lost to a bot @@ -8770,7 +9878,7 @@ Result API::fly_to_node(ObjectGuid flight_master, uint32 to_node) // Mirrors WorldSession::CanUseBank without the session-only "command source" // path. Bots always interact via a real banker NPC; we just verify range -// + the BANKER flag (account bank also accepted — newer clients allow both). +// + the BANKER flag (account bank also accepted — newer clients allow both). static Creature* ResolveBanker(Player* p, ObjectGuid banker) { if (!p) return nullptr; @@ -8793,7 +9901,7 @@ Result API::bank_deposit_item(ObjectGuid banker, uint8 from_bag, uint8 from_slot InventoryResult msg = p_->CanBankItem(NULL_BAG, NULL_SLOT, dest, item, false); if (msg != EQUIP_ERR_OK) return Result::InventoryFull; // CanBankItem can resolve to "stays where it is" (dest == src). The - // live handler treats that as CANT_SWAP — surface Locked so the caller + // live handler treats that as CANT_SWAP — surface Locked so the caller // knows further attempts will fail too. if (dest.size() == 1 && dest[0].pos == item->GetPos()) return Result::Locked; @@ -8848,7 +9956,7 @@ Result API::guild_bank_deposit_money(ObjectGuid banker, uint64 amount) if (!guild) return Result::InvalidTarget; if (!p_->HasEnoughMoney(amount)) return Result::NotEnoughResource; - // HandleMemberDepositMoney is void — it logs and broadcasts but doesn't + // HandleMemberDepositMoney is void — it logs and broadcasts but doesn't // signal failure. Sample bot gold before/after to detect rank-permission // refusal (rank 0 always permitted; lower ranks may be blocked). The // Guild API will not deduct money on failure, so a no-change after the @@ -8887,10 +9995,10 @@ Result API::guild_bank_deposit_item(ObjectGuid banker, uint8 tab, uint8 bank_slo Item* item = p_->GetItemByPos(player_bag, player_slot); if (!item) return Result::NotKnown; - // SwapItemsWithInventory(toChar=false) deposits inventory→bank. The + // SwapItemsWithInventory(toChar=false) deposits inventory→bank. The // function logs internally and is silent on failure. Compare item- // presence at the source slot before/after to confirm the swap landed. - // For mergeable stacks the source might still hold a partial — accept + // For mergeable stacks the source might still hold a partial — accept // any change as success; only an unchanged source is failure. uint32 before_count = item->GetCount(); guild->SwapItemsWithInventory(p_, /*toChar=*/false, tab, bank_slot, player_bag, player_slot, count); @@ -8927,17 +10035,17 @@ Result API::share_quest_with_party(uint32 quest_id) { Player* receiver = itr.GetSource(); if (!receiver || receiver == p_) continue; - // Already mid-share or dead — skip silently. The live handler does + // Already mid-share or dead — skip silently. The live handler does // SendPushToPartyResponse for diagnostics but our caller doesn't // need that level of detail. if (!receiver->GetPlayerSharingQuest().IsEmpty()) continue; if (!receiver->IsAlive()) continue; - // Status gates — already on / done. + // Status gates — already on / done. QuestStatus status = receiver->GetQuestStatus(quest_id); if (status == QUEST_STATUS_REWARDED || status == QUEST_STATUS_INCOMPLETE || status == QUEST_STATUS_COMPLETE) continue; - // Eligibility gates — match HandlePushQuestToParty's Satisfy ladder. + // Eligibility gates — match HandlePushQuestToParty's Satisfy ladder. if (!receiver->SatisfyQuestLog(false)) continue; if (!receiver->SatisfyQuestDay(quest, false)) continue; if (!receiver->SatisfyQuestMinLevel(quest, false)) continue; @@ -8966,7 +10074,7 @@ Result API::guild_bank_withdraw_item(ObjectGuid banker, uint8 tab, uint8 bank_sl if (!Player::IsInventoryPos(player_bag, player_slot) && player_slot != NULL_SLOT) return Result::InvalidTarget; - // SwapItemsWithInventory(toChar=true) withdraws bank→inventory. Compare + // SwapItemsWithInventory(toChar=true) withdraws bank→inventory. Compare // the destination slot before/after; the destination should now hold an // item it didn't before (or a strictly-larger stack). Item* dst_before = (player_slot == NULL_SLOT) ? nullptr : p_->GetItemByPos(player_bag, player_slot); @@ -8997,7 +10105,7 @@ Result API::trainer_buy_all_available(ObjectGuid trainer_npc, Trainer::Trainer const* trainer = sObjectMgr->GetTrainer(trainer_id); if (!trainer) return Result::NotKnown; - // TeachSpell internally re-checks CanTeachSpell — we don't need to + // TeachSpell internally re-checks CanTeachSpell — we don't need to // pre-filter. Bots may carry insufficient gold partway through the // batch; that surfaces as a NotEnoughMoney teach-failure for that // spell only and the loop continues with the next. @@ -9019,12 +10127,95 @@ Result API::trainer_buy_all_available(ObjectGuid trainer_npc, else if (out_skipped) ++*out_skipped; } // "Nothing learned + nothing already known + nothing offered" is - // unusual — surface as Ok (trainer simply has no spells for the bot). + // unusual — surface as Ok (trainer simply has no spells for the bot). if (!any_learned && spells.empty()) return Result::Ok; if (!any_learned && out_already && *out_already == 0) return Result::ServerRefused; return Result::Ok; } +// The top vanilla ranks (Shadow Bolt 25307, Greater Heal 25314, ...) are Ahn'Qiraj book ranks: no trainer sells them, so the trainer pass never +// teaches them. A rank is another spell of the same name, class family, kind and first effect as one the bot knows (the match HighestKnownRank +// uses, because the spell data chains few class spells) with a spell level the bot has reached, listed under the class's skill lines. +// Vanilla-era ids only: the Forever spells above 100000 come with talents and runes, not as ranks. +static uint32 LearnHigherRanksOfKnownSpells(Player* p) +{ + ChrClassesEntry const* classEntry = sChrClassesStore.LookupEntry(p->GetClass()); + if (!classEntry) + return 0; + LocaleConstant const loc = sWorld->GetDefaultDbcLocale(); + auto const keyOf = [loc](SpellInfo const* si) -> std::string + { + char const* name = si->SpellName ? (*si->SpellName)[loc] : nullptr; + if (!name || !*name || si->GetEffects().empty()) + return {}; + return fmt::format("{}|{}|{}|{}", name, uint32(si->SpellFamilyName), uint32(si->GetEffect(EFFECT_0).Effect), si->IsPassive()); + }; + std::unordered_set knownNames; + std::unordered_map> known; // key -> (spell level, id) of the highest rank the bot has: the level, then the id, orders ranks + for (auto const& [id, ps] : p->GetSpellMap()) + { + if (ps.state == PLAYERSPELL_REMOVED || ps.disabled) + continue; + SpellInfo const* si = sSpellMgr->GetSpellInfo(id, DIFFICULTY_NONE); + if (!si || si->SpellFamilyName != classEntry->SpellClassSet) + continue; + if (std::string key = keyOf(si); !key.empty()) + { + auto const rank = std::make_pair(int32(si->SpellLevel), si->Id); + auto [it, inserted] = known.try_emplace(key, rank); + if (!inserted && rank > it->second) + it->second = rank; + knownNames.insert(key.substr(0, key.find('|'))); + } + } + std::vector toLearn; + std::unordered_set seen; + static std::atomic rejectLog{ 0 }; + for (SkillLineAbilityEntry const* entry : sSkillLineAbilityStore) + { + if (!entry || entry->Spell >= 100000 || !seen.insert(entry->Spell).second || p->HasSpell(entry->Spell)) + continue; + SpellInfo const* si = sSpellMgr->GetSpellInfo(entry->Spell, DIFFICULTY_NONE); + if (!si || si->IsPassive() || si->SpellLevel == 0 || si->SpellLevel > p->GetLevel() || si->SpellFamilyName != classEntry->SpellClassSet) + continue; + std::string const key = keyOf(si); + auto const itr = key.empty() ? known.end() : known.find(key); + if (itr == known.end()) + { + if (!key.empty() && knownNames.count(key.substr(0, key.find('|'))) && rejectLog.fetch_add(1) < 400) + TC_LOG_INFO("playerbot.v2", "[BookRanks] {} {}: candidate {} \"{}\" level {} skipped: a spell of that name is known, but family, first effect or kind differs", p->GetName(), + uint32(p->GetClass()), si->Id, key, si->SpellLevel); + continue; + } + // Vanilla ranks of one spell can share a spell level (the last two ranks of many spells are both level 60): the level, then the id, orders them. + auto const reject = [&](char const* why) + { + if (rejectLog.fetch_add(1) < 400) + TC_LOG_INFO("playerbot.v2", "[BookRanks] {} {}: candidate {} \"{}\" level {} rejected: {} (best known {} at level {})", p->GetName(), uint32(p->GetClass()), + si->Id, key, si->SpellLevel, why, itr->second.second, itr->second.first); + }; + if (std::make_pair(int32(si->SpellLevel), si->Id) <= itr->second) + { + reject("not above the best known rank"); + continue; + } + if (!p->IsSpellFitByClassAndRace(si->Id)) + { + reject("IsSpellFitByClassAndRace"); + continue; + } + if (!SpellMgr::IsSpellValid(si, p, false)) + { + reject("IsSpellValid"); + continue; + } + toLearn.push_back(si->Id); + } + for (uint32 id : toLearn) + p->LearnSpell(id, false); + return uint32(toLearn.size()); +} + uint32 API::learn_trainer_spells_free() { if (!p_) return 0; @@ -9047,6 +10238,10 @@ uint32 API::learn_trainer_spells_free() if (!learned) break; } + uint32 const higher_ranks = LearnHigherRanksOfKnownSpells(p_); + if (higher_ranks) + TC_LOG_INFO("playerbot.v2", "[BotSetupPipeline] {} learned {} higher ranks no trainer sells (book ranks)", p_->GetName(), higher_ranks); + total += higher_ranks; if (!total) { // Nothing learned: say which trainers were in reach, so a data problem shows in the log. @@ -9108,7 +10303,7 @@ uint32 API::purge_foreign_class_spells() for (auto const& [spellId, state] : p_->GetSpellMap()) { auto it = taughtBy.find(spellId); - if (it != taughtBy.end() && !(it->second & mine)) + if (it != taughtBy.end() && ::Playerbot::Api::IsForeignClassSpell(it->second, mine)) doomed.push_back(spellId); } for (uint32 spellId : doomed) @@ -9296,6 +10491,76 @@ uint32 API::learn_class_quest_spells_free() return learned; } +namespace +{ +// A granted pet is one the hunter has raised: a fresh tame is Rebellious (no training points, so no Bite or Claw), Unhappy (x0.75 damage, Pet::GetHappinessDamageMod) +// and loses loyalty until it runs away. The grant makes it a Best Friend, fed, and teaches the highest rank of each damage ability of its family that its level and +// training points allow (cost per chain from classic_pet_spell_training_points), with autocast on, as a player's pet is trained at 60. +void RaiseGrantedHunterPet(Pet* pet, Player const* owner) +{ + pet->InitLoyalty(Pet::BEST_FRIEND, Pet::GetLoyaltyStartPoints(Pet::BEST_FRIEND)); + pet->SetPower(POWER_HAPPINESS, Pet::HAPPINESS_MAX); + + CreatureTemplate const* tpl = pet->GetCreatureTemplate(); + CreatureFamilyEntry const* family = tpl && tpl->family ? sCreatureFamilyStore.LookupEntry(tpl->family) : nullptr; + if (!family) + return; + + uint32 budget = pet->GetTrainingPointsTotal(); + std::vector learned; + std::set chains; + for (uint8 line = 0; line < 2; ++line) + { + if (!family->SkillLine[line]) + continue; + std::vector const* abilities = sDB2Manager.GetSkillLineAbilitiesBySkill(family->SkillLine[line]); + if (!abilities) + continue; + for (SkillLineAbilityEntry const* ability : *abilities) + { + uint32 const first = sSpellMgr->GetFirstSpellInChain(ability->Spell); + if (!Pet::GetSpellTrainingPoints(ability->Spell) || !chains.insert(first).second) + continue; + // The highest rank of the chain the pet's level reaches and the points pay for. + uint32 best = 0; + for (uint32 id = first; id; id = sSpellMgr->GetNextSpellInChain(id)) + { + SpellInfo const* info = sSpellMgr->GetSpellInfo(id, DIFFICULTY_NONE); + if (!info || info->SpellLevel > pet->GetLevel() || Pet::GetSpellTrainingPoints(id) > budget) + break; + best = id; + } + SpellInfo const* info = best ? sSpellMgr->GetSpellInfo(best, DIFFICULTY_NONE) : nullptr; + if (!info || info->IsPositive() || !info->IsAutocastable()) + continue; + bool damaging = false; + for (SpellEffectInfo const& eff : info->GetEffects()) + damaging = damaging || eff.IsEffect(SPELL_EFFECT_SCHOOL_DAMAGE) || eff.IsEffect(SPELL_EFFECT_WEAPON_DAMAGE) + || eff.IsEffect(SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL) || eff.IsEffect(SPELL_EFFECT_NORMALIZED_WEAPON_DMG) + || eff.IsEffect(SPELL_EFFECT_WEAPON_PERCENT_DAMAGE); + if (!damaging) + continue; + budget -= Pet::GetSpellTrainingPoints(best); + learned.push_back(best); + } + } + + for (uint32 spellId : learned) + { + pet->learnSpell(spellId); + if (SpellInfo const* info = sSpellMgr->GetSpellInfo(spellId, DIFFICULTY_NONE)) + { + pet->ToggleAutocast(info, true); + if (CharmInfo* ci = pet->GetCharmInfo()) + ci->SetSpellAutocast(info, true); + } + } + pet->UpdateTrainingPoints(); + TC_LOG_INFO("playerbot.api", "[API::starter_pet] {} pet {} (family {}) raised: Best Friend, happy, {} damage abilities trained ({} of {} points left)", + owner->GetName(), pet->GetEntry(), tpl->family, learned.size(), budget, pet->GetTrainingPointsTotal()); +} +} + API::StarterPetResult API::grant_starter_hunter_pet(uint32 entry) { if (!p_ || p_->GetClass() != CLASS_HUNTER || p_->GetLevel() < 10) @@ -9333,6 +10598,7 @@ API::StarterPetResult API::grant_starter_hunter_pet(uint32 entry) } pet->GetMap()->AddToMap(pet->ToCreature()); p_->SetMinion(pet, true); + RaiseGrantedHunterPet(pet, p_); pet->SavePetToDB(PET_SAVE_AS_CURRENT); p_->PetSpellInitialize(); // characters.summonedPetNumber now, as BotSetupPipeline::DoAcquireMount does: a teleport before the next @@ -9434,7 +10700,7 @@ uint32 API::learn_riding_free() } uint16 const target = fix.skill; // A bot a retail trainer pass raised past its level's tier (Journeyman at 40) goes back to the vanilla tier, tier spells included. - if (p_->GetSkillValue(SKILL_RIDING) > target) + if (p_->GetSkillValue(SKILL_RIDING) > target && ::Playerbot::IsVanillaRealm()) { p_->SetSkill(SKILL_RIDING, target / 75, target, target); for (uint32 tier_spell : { 33391u, 34090u, 34091u, 90265u }) // Journeyman, Expert, Artisan, Master Riding @@ -9574,12 +10840,12 @@ Result API::trainer_buy_spell(ObjectGuid trainer_npc, uint32 spell_id) Creature* npc = p_->GetNPCIfCanInteractWith(trainer_npc, UNIT_NPC_FLAG_TRAINER, UNIT_NPC_FLAG_2_NONE); if (!npc) return Result::InvalidTarget; - // Idempotent — caller may re-issue across snapshot ticks if the + // Idempotent — caller may re-issue across snapshot ticks if the // first buy raced with a snapshot rebuild. Already-known is success. if (p_->HasSpell(spell_id)) return Result::Ok; // Resolve trainer template id from the creature entry. NPCs without - // a registered trainer (rare — usually means data isn't loaded) get + // a registered trainer (rare — usually means data isn't loaded) get // NotKnown so callers can fall back to another trainer. uint32 const trainer_id = sObjectMgr->GetCreatureDefaultTrainer(npc->GetEntry()); if (!trainer_id) return Result::NotKnown; diff --git a/src/modules/PlayerbotV2/Api/PlayerbotAPI.h b/src/modules/PlayerbotV2/Api/PlayerbotAPI.h index 39414e985d..525c27294c 100644 --- a/src/modules/PlayerbotV2/Api/PlayerbotAPI.h +++ b/src/modules/PlayerbotV2/Api/PlayerbotAPI.h @@ -90,6 +90,9 @@ namespace PathBudget void BeginWorldTick(uint32 now_ms, uint32 budget_ms); void EndWorldTick(); bool HasBudget(uint32 now_ms); + // Did a pathfind request find the window spent since BeginWorldTick? The drain pass then starts at another bot next time, so the + // bots at the tail of the registry are not the ones that wait every time. + bool Refused(); } // API: thin facade over Player and friends. Constructed transiently per call @@ -327,6 +330,9 @@ public: // when the server let it in nowhere. A dead bot is refused (Locked): the // ghost path is ghost_enter_area_trigger. Result enter_area_trigger(uint32 area_trigger_id); + // always_buffs: Playerbot.AlwaysBuffs. mask = kAlwaysMask* kinds on where the bot stands: add the aura rows of the BuffSet `set` (Bot/AlwaysBuffs.h) of an on kind the bot lacks, direct, no cast, and take off the rows of an off kind; + // mask 0 takes every always-on aura off. Logs [always_buff] for what it changes. + Result always_buffs(uint8 set, uint8 mask); // spirit_resurrect: spirit-healer instant rez. Mirrors // WorldSession::SendSpiritResurrect: ResurrectPlayer(0.5f, applySickness=true) // + DurabilityLossAll(0.25f) + SpawnCorpseBones, then teleport to the @@ -673,7 +679,8 @@ public: // Loot a creature corpse: pick up gold + auto-store all items the bot has // permission to take. Skips group-loot blocks (Need/Greed in flight). The // caller is responsible for moving the bot into loot range first. - Result loot_corpse(ObjectGuid corpse); + // quest_items_only: take only the quest drops this bot may loot (a bot a player leads leaves the rest to him). + Result loot_corpse(ObjectGuid corpse, bool quest_items_only = false); // Vendor / repair // sell_item_by_entry: sells one stack of the given item to the nearby @@ -754,7 +761,7 @@ public: // Returns Locked when the quest isn't complete or the choice is out // of range. static constexpr uint32 kRewardChoiceAuto = 0xFF; - Result complete_quest(ObjectGuid quest_giver, uint32 quest_id, uint32 reward_choice); + Result complete_quest(ObjectGuid quest_giver, uint32 quest_id, uint32 reward_choice, bool copy_leader = false); // Drop the quest from the bot's quest log. Used by stuck/obsolete // cleanup. Returns NotKnown when the quest isn't in the log. Result abandon_quest(uint32 quest_id); diff --git a/src/modules/PlayerbotV2/Api/PlayerbotMovement.cpp b/src/modules/PlayerbotV2/Api/PlayerbotMovement.cpp index bad7bd9a9e..fbb723696b 100644 --- a/src/modules/PlayerbotV2/Api/PlayerbotMovement.cpp +++ b/src/modules/PlayerbotV2/Api/PlayerbotMovement.cpp @@ -633,6 +633,10 @@ void PostTeleportSnap(Player* p) { if (!p || !p->IsInWorld()) return; + // A teleport is still pending (delayed or waiting for its ack): the position here is the one being left, so the probe would judge + // and snap the wrong place (WSG 2026-10-24: a bot's refused BG port logged an "off-mesh landing" on its Redridge spawn spot). + if (p->IsBeingTeleported()) + return; Map* m = p->GetMap(); if (!m) return; @@ -704,7 +708,7 @@ LiquidVerdict ClassifyDestinationLiquid(Player* p, float x, float y, float z, if (outData) *outData = liq; - if (zs == LIQUID_MAP_NO_WATER) + if (zs == LIQUID_MAP_NO_WATER || !LiquidMattersFor(p->IsAlive())) return LiquidVerdict::Dry; // Magma / slime is lethal on contact regardless of depth. diff --git a/src/modules/PlayerbotV2/Api/VirtualSupply.h b/src/modules/PlayerbotV2/Api/VirtualSupply.h new file mode 100644 index 0000000000..921db3e7e2 --- /dev/null +++ b/src/modules/PlayerbotV2/Api/VirtualSupply.h @@ -0,0 +1,30 @@ +// VirtualSupply - infinite food and water for bots (PlayerbotV2.Classic.ClassSupplies). +// The restock tops the bags up and makes room for food and drink (JunkDrop.h PickRoomForSupply), but bags full of gear and quest items +// can still leave a healer with nothing to drink. Bots have infinite supplies by design, so a bot that should eat or drink and has no +// item uses the food / water rank of its level without one: the item's on-use spell, cast with no item consumed. +// Pure decision logic, tested in tests/game/ClassicVirtualSupply.cpp. + +#pragma once + +#include + +namespace Playerbot::Classic +{ + +// The food / drink the recovery rules pick: the best one in the bags, else (infinite supplies on) the supply rank of the bot's level. +// 0 = nothing to eat or drink. +inline constexpr std::uint32_t RecoveryItemOrVirtual(std::uint32_t in_bags, bool infinite_supplies, std::uint32_t supply_rank) +{ + if (in_bags) + return in_bags; + return infinite_supplies ? supply_rank : 0; +} + +// At use time: the bot has no such item and the entry is a food / water supply rank its level allows, so it eats / drinks without it. +// A missing item of any other kind (a quest item, a potion) is never conjured from nothing. +inline constexpr bool UseVirtually(bool in_bags, bool infinite_supplies, bool food_or_water_rank) +{ + return !in_bags && infinite_supplies && food_or_water_rank; +} + +} // namespace Playerbot::Classic diff --git a/src/modules/PlayerbotV2/BOT_COMMANDS.md b/src/modules/PlayerbotV2/BOT_COMMANDS.md index dce715846c..3718d86593 100644 --- a/src/modules/PlayerbotV2/BOT_COMMANDS.md +++ b/src/modules/PlayerbotV2/BOT_COMMANDS.md @@ -58,12 +58,13 @@ The `.bot` commands for your own bots work for every account, no GM needed; each | Command | What it does | |---|---| | `.bot add [tank\|healer\|dps] [race] [male\|female]` | Creates a companion bound to you, levels it to you, teaches spells, sets role/talents/gear, brings it over and groups it. The role is kept across relog and `.bot call`. | +| `.bot lfg [tank\|healer\|dps]` | Fills the missing tank / healer / damage places of your group (1 tank, 1 healer, 3 damage) with level-matched companions, now. The word is your own role. The Group Finder does the same on its own: post a dungeon listing and, if nobody joins within `Playerbot.Lfg.BotFillSeconds` (default 180), the missing roles are filled. | | `.bot call ` | Brings back a companion (logs it in, joins your group). `all` = your saved roster plus every bot in your group. | | `.bot summon ` | Every player, own bots only: `.bot summon all` brings only the bots that are in your group right now (it never logs anyone in), `.bot summon saved` your saved roster plus the grouped bots (logging them in), `.bot summon ` one of your companions. Any other name: "You can only summon your own bots". The GM `.summon` (other players) is unchanged and stays GM-only. | | `.bot save ` | Puts a companion (or every bot with you) on your roster. | | `.bot unsave ` | Takes it off the roster; it stays yours and `.bot call ` still works. | | `.bot dismiss ` | Removes it from your group and logs it out. Gear is kept. | -| `.bot delete ` | Deletes the character for good (the addon asks first). | +| `.bot delete ` | Deletes the character for good (the addon asks first). Only bots made for you: one of your own characters summoned as a bot (`.playerbot summon`) is refused with a pointer to `.bot dismiss`. | | `.bot list` | Your companions, online or not (`saved` marks roster ones). | | `.bot regear ` | Re-rolls the equipment of online companions so they do not all wear the same pieces. Better pieces they wear stay; replaced ones go to the bags. | | `.bot world` | Status of the world-bot spawner (Playerbot.World.*), console too. | @@ -139,7 +140,8 @@ from the bot. | `pull back` / `pullback` / `pull and back` | yes | yes | The main tank (or the assigned/closest tank) opens from range, runs to the rally point and tanks it there. Others hold. Gives up after 30 s. | | `pull rti` | yes | yes | Opens on the mob carrying the bot's own rti symbol (Ike3Commands). | | `max dps` / `save mana` / `normal` | yes | no | Burn mode (cooldowns on every fight), healers keep to efficient heals, clear both. Ike3Commands. | -| `focus `, `target `, `mark `, `interrupt`, `cc`, `aoe [on\|off]` | yes | no | Finer combat control. | +| `focus `, `target `, `mark `, `interrupt`, `cc` | yes | no | Finer combat control. | +| `aoe on\|off` (bare `aoe` toggles), `aoe_all on\|off` | yes | no | Off: the bot casts no spell that hits more than one enemy (area and cone spells, damaging ground areas such as Blizzard or Consecration, chained spells such as Chain Lightning, Multi-Shot or Cleave, Magma and Fire Nova Totem) until on. `aoe_all` sets every bot of the group. Memory only; `clearprefs` turns it on again. | ### Questions and housekeeping (OwnerCommands) @@ -182,6 +184,30 @@ All of these are group-allowed (party/raid chat) and whisperable. flag. Raid groups only. With a main tank set, only that tank pulls. - **Marks need an order** (`MarksNeedOrder`, default on): putting an icon on a mob never starts a fight by itself. Bots engage after `attack`, `pull`, `pull back`, `pull rti` or `focus`. +- **Crowd control on and off, per class**: `@warlock no fear`, `@mages no sheep`, then `@warlock yes fear`, `@mage yes sheep` to + allow it again. Without a class the order is for every bot (`no fear`, `yes fear`). `off cc` / `on cc` (also `cc off` / `cc on`) + stops or allows all crowd control for every bot, and `@warlock off cc` for one class. Party / raid chat, a whisper to any of your + bots, or `;` lines; it is your setting, not the bot's, so it also covers bots of that class who join later, and you get one + answer (`Your warlocks will not use fear now (left out for them: fear).`). Kinds: `fear` (Fear, Howl of Terror, Death Coil, + Psychic Scream, Intimidating Shout, Scare Beast, Turn Undead), `sheep` / `poly`, `banish`, `shackle`, `sap`, `sleep` (Hibernate, + Wyvern Sting), `trap` (Freezing Trap), `charm` / `seduce` (Seduction, Enslave Demon, Mind Control), `cc` (all of them). Stuns, + roots, snares and interrupts are not crowd control here and stay in the rotations. A denied spell is skipped and the bot goes on + with its next spell; marked crowd control picks another spell or no bot for that mob. Memory only: a server restart allows + everything again. The panel's CC icon (`crowdcontrol on|off`) stays the switch for marked crowd control alone. +- **The bot's own picks (whisper)**: `prefer blessing might|wisdom|kings|salvation|light|sanctuary`, `prefer aura + devotion|retribution|concentration|shadow|frost|fire|sanctity`, `prefer earth stoneskin|strength|tremor|earthbind|stoneclaw`, + `prefer fire searing|nova|magma|flametongue|frost`, `prefer water mana|healing|poison|disease|fire`, `prefer air + windfury|grace|grounding|nature|windwall|tranquil`, `prefer aspect hawk|monkey|wild|cheetah|pack`, `prefer demon + imp|voidwalker|succubus|felhunter`; `prefer auto` returns that slot to the plan, `prefer clear` all of them, a bare + `prefer` lists them. The pick replaces the group plan for that choice only: a pinned paladin gives its blessing to everyone in + reach (a Greater Blessing per class with Symbol of Kings; Salvation never on a tank) and the other paladins leave it out of + their split; a pinned aura counts as taken for the party; a pinned totem stands in for its element (a damage fire totem only + near a living victim); Cheetah and Pack are held out of combat only (Hawk in a fight); a pinned demon is summoned and never + sacrificed. Refused for another class (`Prefer: I am no paladin, ...`) or a spell the bot does not know yet. `pet off` dismisses + a hunter's or warlock's pet and keeps it away until `pet on`; `stealth off` keeps a rogue from opening out of Stealth (and from + Sap) until `stealth on`. Memory only: a relog or restart clears them. +- **Warlock summon and soulstone**: `ritual ` casts Ritual of Summoning on that member of the group; two more members click + the portal (`use summoning` in party chat sends bots). `soulstone ` stones that member (bare `soulstone`: your target, else you). - **Pull back vs fall back**: `pull back` is one tank pulling a mob home to the rally point. `fall back` (also `fallback`, `back`) is the whole raid dropping its target and running to the rally point to re-form, see [Raid orders](#7-raid-orders). @@ -309,6 +335,9 @@ Defaults are those of `conf/playerbot.conf.dist`. Behaviour switches are read wh | `Playerbot.Behavior.DungeonFlow` / `DungeonAutopilot` / `DungeonLoot` | 1 / 1 / 1 | | `Playerbot.Behavior.PullRecover` / `WipeReleaseWait` / `ReadyCheckInfo` | 1 / 1 / 1 | | `Playerbot.TankThreatMultiplier` | 3.0 | +| `Playerbot.Raid.TankThreatMultiplier` | 5.0 | +| `Playerbot.Raid.SureTaunt` | 1 | +| `Playerbot.Scenario.OwnerThreat` | 1 | **Raid combat behaviour (all default 1)**: `RaidGear`, `AmmoSupply`, `TankRangedWeapon`, `HealClaims`, `CastFacing`, `GroundSnap`, `ReFace`, `AvoidCircles`, `PackStop`, `RaidSpacing`, `SpreadOut`, `LooseMobHold`, `RaidBuffHold`, @@ -409,4 +438,8 @@ In party or raid chat every addressed bot answers (`all:`, `tank:`, `:` pr Whisper a bot of your group `craft [x5]` (or `craft list`). The bot makes it with the recipes and reagents it carries (one craft at a time, up to 20 items) and mails the result to you; missing reagents are whispered back, trade them to the bot and ask again. +A name that fits no item is tried against the recipe names, so a mage answers `craft water x20` and `craft food x20` with its best +Conjure Water / Conjure Food rank. `water` / `drink` and `food` (also the Russian `вода`, `воду`, `напиток`, `еда`, `еду`, `пища`) find +those ranks by the spell data, so they work whatever language the server's item names are in. Of the items a name fits, the best one you are high enough to use is made. Conjured items cannot go +by mail: the bot asks you to open a trade with it and puts them in the window. A bare `craft ` is the older owner command and still casts that recipe once. Idea and parser from Trixx34/ForeverBots (GPL-2.0). diff --git a/src/modules/PlayerbotV2/Bot/AlwaysBuffs.h b/src/modules/PlayerbotV2/Bot/AlwaysBuffs.h new file mode 100644 index 0000000000..75b4a5d10e --- /dev/null +++ b/src/modules/PlayerbotV2/Bot/AlwaysBuffs.h @@ -0,0 +1,148 @@ +// Playerbot.AlwaysBuffs: every bot of the raiding levels carries its role's flask or elixirs, scrolls, food, weapon stone and +// world buffs all the time, put on straight (aura or temporary weapon enchant; no item used, no cast time, no GCD), and loses +// them on a battleground or arena map. One table: role -> rows. +// +// A row is a spell (the aura's own id, checked against the client spell data: the ids below were read from SpellName.db2) or an +// item (the buff is whatever the item's on-use spell leaves: its triggered spell for food, its own aura for a scroll, the +// temporary weapon enchant for a stone). `name` is a part of the spell's or item's own name, checked when the row is resolved; +// a row that does not match is logged "[always_buff] ... skipped" and left out, so a wrong id never gives the wrong buff. +// spell_group on this server (checked 2026-10-23): the flasks 17626/17627/17628 are in battle group 1 and guardian group 2 with +// Mongoose 17538 and Greater Firepower 26276 (exclusive), so those two are not used on a flask. Greater Arcane 16889, Elixir of +// Shadow Power 11476, Elixir of Frost Power 21923, Mageblood 24365 and Giants 16883 are in no group and stack with a flask. +#pragma once + +#include "Define.h" +#include + +namespace Playerbot { + +enum class BuffSet : uint8 { Tank, MeleeStrength, MeleeAgility, Caster, Healer, CasterShadow, CasterFrost }; +constexpr uint8 kBuffSetCount = 7; + +enum class AlwaysKind : uint8 { Spell, Item, Stone }; + +struct AlwaysAura +{ + AlwaysKind kind; + uint32 id; // spell id (Spell) or item id (Item, Stone) + char const* name; + bool horde_only = false; + bool world = false; // a world buff (switch WorldBuffs); every other row is a consumable (switch Consumables) +}; + +// The switches, Playerbot.AlwaysBuffs.. (playerbot.conf.dist). Place: Raid = raids and dungeons, World = everywhere +// else, Battleground = battlegrounds and arenas. +enum class AlwaysSwitch : uint8 { Supplies, Repair, WorldBuffs, Consumables }; +enum class AlwaysPlace : uint8 { Raid, World, Battleground }; +constexpr uint8 kAlwaysSwitchCount = 4; +constexpr uint8 kAlwaysPlaceCount = 3; + +// The mask an AlwaysBuffIntent carries: which kinds are on where the bot stands. +constexpr uint8 kAlwaysMaskConsumables = 1; +constexpr uint8 kAlwaysMaskWorldBuffs = 2; +constexpr uint8 kAlwaysMaskRepair = 4; + +constexpr uint8 kAlwaysBuffMinLevel = 58; + +// Also under Playerbot.AlwaysBuffs: gear is kept whole (durability back to full, no repair bill) and a bot never has less gold than this. +constexpr int32 kAlwaysGoldFloor = 200; // gold: enough for any trainer + +// World buffs every role gets. +constexpr AlwaysAura kWorldBuffs[] = { + { AlwaysKind::Spell, 22888, "Rallying Cry of the Dragonslayer", false, true }, + { AlwaysKind::Spell, 24425, "Spirit of Zandalar", false, true }, + { AlwaysKind::Spell, 15366, "Songflower Serenade", false, true }, + { AlwaysKind::Spell, 16609, "Warchief's Blessing", true, true }, +}; +constexpr AlwaysAura kTankBuffs[] = { + { AlwaysKind::Spell, 17626, "Flask of the Titans" }, // +1200 health + { AlwaysKind::Spell, 22818, "Mol'dar's Moxie", false, true }, + { AlwaysKind::Item, 10307, "Scroll of Stamina IV" }, + { AlwaysKind::Item, 10310, "Scroll of Strength IV" }, + { AlwaysKind::Item, 18045, "Tender Wolf Steak" }, + { AlwaysKind::Stone, 18262, "Elemental Sharpening Stone" }, +}; +constexpr AlwaysAura kMeleeStrengthBuffs[] = { + { AlwaysKind::Spell, 17538, "Elixir of the Mongoose" }, + { AlwaysKind::Spell, 16883, "Elixir of the Giants" }, + { AlwaysKind::Spell, 22817, "Fengus' Ferocity", false, true }, + { AlwaysKind::Item, 10310, "Scroll of Strength IV" }, + { AlwaysKind::Item, 20452, "Smoked Desert Dumplings" }, + { AlwaysKind::Stone, 18262, "Elemental Sharpening Stone" }, +}; +constexpr AlwaysAura kMeleeAgilityBuffs[] = { + { AlwaysKind::Spell, 17538, "Elixir of the Mongoose" }, + { AlwaysKind::Spell, 16883, "Elixir of the Giants" }, + { AlwaysKind::Spell, 22817, "Fengus' Ferocity", false, true }, + { AlwaysKind::Item, 10309, "Scroll of Agility IV" }, + { AlwaysKind::Item, 13928, "Grilled Squid" }, + { AlwaysKind::Stone, 18262, "Elemental Sharpening Stone" }, +}; +constexpr AlwaysAura kCasterBuffs[] = { + { AlwaysKind::Spell, 17628, "Supreme Power" }, // Flask of Supreme Power: +150 spell damage + { AlwaysKind::Spell, 16889, "Greater Arcane Elixir" }, + { AlwaysKind::Spell, 24365, "Mageblood Elixir" }, + { AlwaysKind::Spell, 22820, "Slip'kik's Savvy", false, true }, + { AlwaysKind::Item, 10308, "Scroll of Intellect IV" }, + { AlwaysKind::Item, 10306, "Scroll of Spirit IV" }, + { AlwaysKind::Item, 18254, "Runn Tum Tuber Surprise" }, +}; +// Warlock and shadow priest: the caster rows plus the Shadow Power elixir. +constexpr AlwaysAura kCasterShadowBuffs[] = { + { AlwaysKind::Spell, 17628, "Supreme Power" }, + { AlwaysKind::Spell, 16889, "Greater Arcane Elixir" }, + { AlwaysKind::Spell, 11476, "Elixir of Shadow Power" }, + { AlwaysKind::Spell, 24365, "Mageblood Elixir" }, + { AlwaysKind::Spell, 22820, "Slip'kik's Savvy", false, true }, + { AlwaysKind::Item, 10308, "Scroll of Intellect IV" }, + { AlwaysKind::Item, 10306, "Scroll of Spirit IV" }, + { AlwaysKind::Item, 18254, "Runn Tum Tuber Surprise" }, +}; +// Frost mage: the caster rows plus the Frost Power elixir. +constexpr AlwaysAura kCasterFrostBuffs[] = { + { AlwaysKind::Spell, 17628, "Supreme Power" }, + { AlwaysKind::Spell, 16889, "Greater Arcane Elixir" }, + { AlwaysKind::Spell, 21923, "Elixir of Frost Power" }, + { AlwaysKind::Spell, 24365, "Mageblood Elixir" }, + { AlwaysKind::Spell, 22820, "Slip'kik's Savvy", false, true }, + { AlwaysKind::Item, 10308, "Scroll of Intellect IV" }, + { AlwaysKind::Item, 10306, "Scroll of Spirit IV" }, + { AlwaysKind::Item, 18254, "Runn Tum Tuber Surprise" }, +}; +constexpr AlwaysAura kHealerBuffs[] = { + { AlwaysKind::Spell, 17627, "Distilled Wisdom" }, // Flask of Distilled Wisdom: +2000 mana + { AlwaysKind::Spell, 24365, "Mageblood Elixir" }, + { AlwaysKind::Spell, 22820, "Slip'kik's Savvy", false, true }, + { AlwaysKind::Item, 10308, "Scroll of Intellect IV" }, + { AlwaysKind::Item, 10306, "Scroll of Spirit IV" }, + { AlwaysKind::Item, 13931, "Nightfin Soup" }, +}; + +constexpr std::span AlwaysBuffRoleRows(BuffSet set) +{ + switch (set) + { + case BuffSet::Tank: return kTankBuffs; + case BuffSet::MeleeStrength: return kMeleeStrengthBuffs; + case BuffSet::MeleeAgility: return kMeleeAgilityBuffs; + case BuffSet::Caster: return kCasterBuffs; + case BuffSet::Healer: return kHealerBuffs; + case BuffSet::CasterShadow: return kCasterShadowBuffs; + case BuffSet::CasterFrost: return kCasterFrostBuffs; + } + return {}; +} + +// What a row leaves on the bot, resolved once from the client data: the aura spell ids for a Spell or Item row (empty when the +// name check failed), the temporary enchantment id for a Stone row (empty = none). Bot/ClassicUpkeep.cpp. +std::span AlwaysAuraEffects(AlwaysAura const& row); + +class BotSnapshotView; +class GroupSnapshotView; + +// The role's set and the kinds on where the bot stands, as idle:always_buff gives them to the AlwaysBuffIntent. +// Bot/States/Rules/OocConsumableRules.cpp. +BuffSet AlwaysBuffSetOf(BotSnapshotView const& s, GroupSnapshotView const& g); +uint8 AlwaysMask(BotSnapshotView const& s, GroupSnapshotView const& g); + +} // namespace Playerbot diff --git a/src/modules/PlayerbotV2/Bot/AoeDeny.h b/src/modules/PlayerbotV2/Bot/AoeDeny.h new file mode 100644 index 0000000000..81241e103e --- /dev/null +++ b/src/modules/PlayerbotV2/Bot/AoeDeny.h @@ -0,0 +1,30 @@ +// AoeDeny.h - the owner's "aoe off": the bot casts nothing that hits more than one enemy until "aoe on" (BotCommandParser "aoe", +// "aoe_all", the add-on's AoE switch and menu entry). Kept on BotAI (memory only), mirrored into BotSnapshot::aoe_denied; +// BotIntentEmitter drops such a cast, so a rotation falls through to its single-target rule. +// Pure: the emitter passes in what SpellInfo says of the spell (no SpellMgr here). +#pragma once + +#include + +namespace Playerbot::AoeDeny { + +// Totems that do their damage round themselves: the summon spell is not harmful, the totem's own pulse is (rank 1 ids). +inline bool AreaTotem(uint32_t first_rank) +{ + return first_rank == 8190 // Magma Totem + || first_rank == 1535; // Fire Nova Totem +} + +// Does "aoe off" leave out this spell? A harmful spell that picks its targets from an area or a cone, puts down a damaging +// area (Blizzard, Consecration, Rain of Fire), or chains to further enemies (Chain Lightning, Multi-Shot, Cleave), and the +// area totems. `chain_targets` is the largest ChainTargets of its effects. +inline bool IsAoe(bool positive, bool affecting_area, uint32_t chain_targets, uint32_t first_rank) +{ + if (AreaTotem(first_rank)) + return true; + if (positive) + return false; + return affecting_area || chain_targets > 1; +} + +} // namespace Playerbot::AoeDeny diff --git a/src/modules/PlayerbotV2/Bot/Battleground/BgAvPlan.h b/src/modules/PlayerbotV2/Bot/Battleground/BgAvPlan.h index 596fea91b0..72d69d8a92 100644 --- a/src/modules/PlayerbotV2/Bot/Battleground/BgAvPlan.h +++ b/src/modules/PlayerbotV2/Bot/Battleground/BgAvPlan.h @@ -13,10 +13,75 @@ namespace Playerbot::BgAvPlan // Time cap (playtest, AV 2026-10-11: a pile of bots waited at the Stonehearth staging spot for a quorum): after kCaptainGatherMaxMs of waiting the squad // goes with whoever is there (at least one), so bots arriving one at a time never park for good. constexpr uint32_t kCaptainGatherMaxMs = 75000; - constexpr bool CaptainGather(int at_stage, bool latched, uint32_t waited_ms = 0) + // `squad` = the bots the plan sends at the captain (0 = unknown: the plain five-bot rule). A big squad waits for two thirds of itself + // (bot-only AV 249: the squad went in whenever five stood at the waiting spot while the rest were still on the road, and died in + // turn); the time cap still lets a small or straggling squad go, but a known squad goes on the cap only with five at the spot (or all + // of a squad smaller than five): in AV 251 every assault went on the cap with 1 or 2 of a squad of 23 to 31, because the bots coming + // back from the graveyards need longer than the cap, and the "wipes" of those one-bot assaults gave the captain up in 6 minutes. + // `since_arrival_ms` = how long the count at the spot has not grown: the time cap goes only once the squad stopped arriving. AV 253: + // all six captain assaults went "5 at the waiting spot" of a squad of 23 to 31, never on the quorum, because the cap counts from the + // last wipe and had run out long before; the fifth bot to arrive set off the assault while the rest were still on the road. + constexpr uint32_t kGatherSettleMs = 20000; + constexpr bool CaptainGather(int at_stage, bool latched, uint32_t waited_ms = 0, int squad = 0, uint32_t since_arrival_ms = kGatherSettleMs) { - return latched || at_stage >= kCaptainGatherCount || (at_stage >= 1 && waited_ms >= kCaptainGatherMaxMs); + int const quorum = squad * 2 / 3 > kCaptainGatherCount ? squad * 2 / 3 : kCaptainGatherCount; + int const cap_min = squad <= 0 ? 1 : (squad < kCaptainGatherCount ? squad : kCaptainGatherCount); + return latched || at_stage >= quorum || + (at_stage >= cap_min && waited_ms >= kCaptainGatherMaxMs && since_arrival_ms >= kGatherSettleMs); } + // ike3 sends the non-supporters (60-80 %) at the captain, mod-playerbots 90 %. The supporters (garrisons, the valley brawl, Snowfall, + // mine bosses) may only take what is left over: in AV 249 they took them first and the captain squad was whoever remained, a handful + // of bots against the captain, two lieutenants and the garrison. + constexpr int CaptainReserve(int alive_free) { return (alive_free * 65 + 99) / 100; } + // A captain the team cannot kill must not hold the match: after kCaptainMaxAssaults wiped assaults the team leaves the captain and + // goes for the towers and the general (the general push needs the towers, not the captain). + constexpr int kCaptainMaxAssaults = 3; + constexpr bool CaptainGivenUp(int wiped_assaults) { return wiped_assaults >= kCaptainMaxAssaults; } + // The assault that went in is over once its squad is gone (bot-only AV soak 2026-10-25: the latch held until the captain died, so after + // the first wipe every bot back from the graveyard ran into Iceblood Garrison alone; ~350 deaths there with 30 of 37 alive, Galvangar + // never died and the towers, which come after him, were never attacked). Fewer than kCaptainSquadMin alive bots within + // kCaptainSquadRadius of the captain, kCaptainAssaultGraceMs after the go (the walk in from the waiting spot, 57 yd at Iceblood): the + // team gathers at the waiting spot again. + constexpr int kCaptainSquadMin = 2; + constexpr float kCaptainSquadRadius = 100.0f; + constexpr uint32_t kCaptainAssaultGraceMs = 30000; + constexpr bool CaptainAssaultBroken(int alive_near_captain, uint32_t since_go_ms, uint32_t grace_ms = kCaptainAssaultGraceMs) + { + return since_go_ms >= grace_ms && alive_near_captain < kCaptainSquadMin; + } + // A squad member still on its way in counts as the assault too: it has left the waiting spot toward the target (`to_target` yards + // from it, the spot `stage_to_target`) by more than kOnWayMargin. Bot-only AV 262: the general squad went from Snowfall at 02:11:03 + // and 02:18:09 and was "wiped" 6 min 15 s later both times, the grace of the 1,200 yd straight line, while it was still on the + // road; 51 s after the first "wipe" 17 stood at the waiting spot again (back from the road, not from the graveyard). + constexpr float kOnWayMargin = 30.0f; + constexpr bool OnTheWay(float to_target, float stage_to_target) { return to_target < stage_to_target - kOnWayMargin; } + // Waves. A bot that died after its assault went (`died_ms`, match time of the last plan that saw it dead; `died` = ever seen dead) is + // out of that wave: it goes back to the waiting spot instead of running in alone, and does not keep the wave from counting as wiped. + // Once kCaptainGatherCount of them stand at the spot and no more have come for kGatherSettleMs they go in as the next wave. + // Bot-only AV 268: after the graveyard steps the two general squads met between Snowfall and Stonehearth for 1 h 35 min; the + // Alliance assault went at 10:37 and never counted as wiped (its dead came back on the road from Stonehearth Graveyard and counted + // as on their way), the Horde's held from 11:16 to 12:14 the same way. The bots ran back in one by one (a death there had 0.7 + // teammates within 45 yd on average in the sampled role log), and none got within 50 yd of the graveyard it was sent to. + constexpr bool OutOfWave(bool died, uint32_t died_ms, uint32_t wave_ms) { return died && died_ms >= wave_ms; } + constexpr bool WaveReinforce(int at_stage, uint32_t since_arrival_ms) + { + return at_stage >= kCaptainGatherCount && since_arrival_ms >= kGatherSettleMs; + } + // The grace for a walk of `stage_to_target` yards from the waiting spot (the node rally: Iceblood GY is 240 yd from the Alliance + // waiting spot): 4 yd/s on foot plus 10 s, never less than kCaptainAssaultGraceMs. + constexpr uint32_t AssaultGraceMs(float stage_to_target) + { + uint32_t const walk = uint32_t(stage_to_target > 0.f ? stage_to_target : 0.f) * 250u + 10000u; + return walk > kCaptainAssaultGraceMs ? walk : kCaptainAssaultGraceMs; + } + // Node rally (bot-only AV 251: once the captain was left, the bots ran from Stonehearth GY to Iceblood one by one, about 650 yd past + // the Winterax trolls, Korrak and the garrison, and the Alliance took no Horde banner in 45 minutes): a bot this far beyond the + // waiting spot's own distance to the target goes to the waiting spot first; the rest go straight in. + constexpr float kRallyDetour = 50.0f; + // The node squad's waiting spot: this far (straight line) back from the first node along the recorded route in from the home base, + // clear of the tower's bowmen and commander (BgRoutes::ApproachPoint; Stonehearth Bunker's Randolph and his bowmen stand within 25 yd). + constexpr float kNodeRallyBack = 100.0f; + constexpr bool RallyFirst(float bot_to_target, float stage_to_target) { return bot_to_target > stage_to_target + kRallyDetour; } struct MineTarget { float x, y, z; uint32_t entry; char const* name; }; @@ -119,8 +184,8 @@ namespace Playerbot::BgAvPlan inline std::vector const& AttackList(uint8_t team) { static std::vector const horde = { - { 73.7f, -426.0f, "Stonehearth GY" }, { -154.0f, -446.0f, "Stonehearth Bunker" }, { 203.0f, -361.0f, "Icewing Bunker" }, - { 669.0f, -294.0f, "Stormpike GY" }, { 556.0f, -84.0f, "Dun Baldar South Bunker" }, { 678.0f, -139.0f, "Dun Baldar North Bunker" }, + { 77.8f, -404.7f, "Stonehearth GY" }, { -152.4f, -441.6f, "Stonehearth Bunker" }, { 203.0f, -361.0f, "Icewing Bunker" }, + { 669.0f, -294.0f, "Stormpike GY" }, { 553.8f, -78.7f, "Dun Baldar South Bunker" }, { 674.0f, -143.1f, "Dun Baldar North Bunker" }, { 638.5f, -31.5f, "Stormpike Aid Station" } }; // Alliance: Iceblood GY, Iceblood Tower, Tower Point, Frostwolf GY, East / West Frostwolf Tower, Frostwolf Relief Hut. static std::vector const alliance = { @@ -179,10 +244,67 @@ namespace Playerbot::BgAvPlan { return enemy_towers_up == 0 || (enemy_towers_razed >= 2 && (own_final_gy || friends_near_boss >= kBossFriendsNeeded)); } + // Classic AV ends only on a general kill, and in bot-only matches the towers do not fall: in the soaks of 2026-10-25 (247 to 259) the + // towers were taken 4 to 9 times a match and every one was won back by its garrison before it burned, so GeneralPushOk never held + // and every match ran into the time limit with both captains dead (257: 1314 / 1344 s, 259: Balinda 912 s). The towers get + // kGeneralAfterCaptainMs after the enemy captain died or was left; then the team goes for the general (his warmasters / marshals + // for the standing towers are part of that fight). + constexpr uint32_t kGeneralAfterCaptainMs = 10u * 60u * 1000u; + constexpr bool GeneralDue(uint32_t in_progress_ms, uint32_t captain_done_ms) + { + return in_progress_ms >= captain_done_ms && in_progress_ms - captain_done_ms >= kGeneralAfterCaptainMs; + } + // The general squad's waiting spot: our graveyard nearest the enemy general (held, not under attack), where the bots respawn anyway, + // so a wiped push regroups where its dead come back. Bot-only AV 261: a spot 200 yd short of the general (below Frostwolf Keep) was + // never reached: the push fired at 23:52, the Alliance walked to it one by one, and in an hour none got past Iceblood, where they + // died to the Horde bots (0 at the spot, no "general assault goes"). `gy` = graveyard nodes, -1 when we hold none (the caller then + // falls back to kGeneralStageBack along the route in). + struct GyView { float x, y; bool ours; bool contested; }; + inline int GeneralStageGraveyard(std::vector const& gy, float general_x, float general_y) + { + int best = -1; + float best_d = 0.f; + for (int i = 0; i < int(gy.size()); ++i) + { + if (!gy[i].ours || gy[i].contested) continue; + float const dx = gy[i].x - general_x, dy = gy[i].y - general_y, d = dx * dx + dy * dy; + if (best < 0 || d < best_d) { best = i; best_d = d; } + } + return best; + } + constexpr float kGeneralStageBack = 200.0f; // Our last graveyard (the one an AV team keeps until the end). struct AvPoint { float x, y, z; }; constexpr AvPoint FinalGraveyard(uint8_t team) { return team == 2 ? AvPoint{ -1402.0f, -307.0f, 89.0f } : AvPoint{ 638.5f, -31.5f, 46.0f }; } + // The graveyard the general push takes before it goes on: of the graveyards nearer the general than our waiting spot (`stage`, an + // index into `gy`, or -1 for the home base at home_x/home_y), the nearest to us that is not ours and settled; -1 when none is left + // and the squad goes for the general. The enemy's last graveyard (FinalGraveyard of `enemy_team`) stands next to the general and is + // not a step. A graveyard we are taking (ours, contested) stays the target until it is ours, so the squad holds it while it turns. + // Bot-only AV 265: both general pushes went (06:59 / 07:02) and met at Iceblood for 45 minutes, nobody wiped and nobody got + // through. Iceblood Graveyard stayed Horde the whole match: every Horde bot that died came back 100 yd from the fight, every + // Alliance bot 350-500 yd back at Snowfall or Stonehearth. The towers / captain plan never took it (the node assaults wiped at 5-8 + // bots), so the push now takes the enemy graveyards on its way, as AV is played (ike3's attack list starts with them too). + inline int GeneralRouteGraveyard(std::vector const& gy, int stage, float home_x, float home_y, float general_x, float general_y, + uint8_t enemy_team) + { + auto d2 = [&](float x, float y) { float const dx = x - general_x, dy = y - general_y; return dx * dx + dy * dy; }; + float const ref = stage >= 0 ? d2(gy[stage].x, gy[stage].y) : d2(home_x, home_y); + AvPoint const fin = FinalGraveyard(enemy_team); + int best = -1; + float best_d = 0.f; + for (int i = 0; i < int(gy.size()); ++i) + { + if (gy[i].ours && !gy[i].contested) continue; + float const fx = gy[i].x - fin.x, fy = gy[i].y - fin.y; + if (fx * fx + fy * fy < 30.0f * 30.0f) continue; + float const d = d2(gy[i].x, gy[i].y); + if (d >= ref) continue; + if (best < 0 || d > best_d) { best = i; best_d = d; } + } + return best; + } + // Nothing left to attack: wait next to the enemy general (mod-playerbots AV_BOSS_WAIT_H / AV_BOSS_WAIT_A). constexpr AvPoint BossWait(uint8_t team) { return team == 2 ? AvPoint{ 689.21f, -20.173f, 50.62f } : AvPoint{ -1361.773f, -248.977f, 99.369f }; } diff --git a/src/modules/PlayerbotV2/Bot/Battleground/BgTargetPick.h b/src/modules/PlayerbotV2/Bot/Battleground/BgTargetPick.h index 5338b7c9f4..ed92b0e547 100644 --- a/src/modules/PlayerbotV2/Bot/Battleground/BgTargetPick.h +++ b/src/modules/PlayerbotV2/Bot/Battleground/BgTargetPick.h @@ -78,4 +78,66 @@ namespace Playerbot::BgTargetPick return none; return best->guid; } + + // Whether the open-engage rule may start a fight with this creature: only one that already fights this bot, its pet or a teammate + // (`friends`: guids of the friendly units around the bot), or the creature the bot's order names (`order_entry`, 0 = none). + // Bot-only AV 253: bots on the march opened on every creature within the 40 yd AV aggro range (ike3's range is for enemy PLAYERS): + // 822 openings on creatures that were not in combat, 68 of them on Korrak the Bloodrager (113k HP, 1.8-2.3k a hit), who killed 79 + // bots one at a time, and the rams, wolves, harpies and garrison guards beside the roads split every squad on its way. + template + bool CreatureWorthOpening(Unit const& u, Guid const& me, Guid const& pet, Friends const& friends, uint32_t order_entry) + { + if (order_entry != 0 && u.entry == order_entry) + return true; + Guid const none{}; + if (u.victim == none) + return false; + if (u.victim == me || (!(pet == none) && u.victim == pet)) + return true; + for (auto const& f : friends) + if (f.guid == u.victim) + return true; + return false; + } + + // The creature that is hitting this bot in melee (an attacker whose victim is `me`, alive and fightable, within kBesetRange), nearest + // first; nullptr when none. Walking on does not shake it: the creature runs as fast as the bot and hits it in the back. + // Bot-only AV 255: 298 of the 884 deaths had the in-combat march to the ordered boss (combat:bg_push_endgame_advance) as their last + // rule, with the killer 2-5 yd away: 97 in Coldtooth Mine to the Whitewhisker kobolds (one bot died at the same spot 20 times on the + // way to the mine boss), 23 each to the Frostwolf Warriors and Mine Layers at Iceblood, 15 to Commander Randolph. + constexpr float kBesetRange = 10.0f; + template + Unit const* BesetBy(Guid const& me, float bx, float by, std::vector const& attackers) + { + Unit const* best = nullptr; + float best_d = kBesetRange * kBesetRange; + for (Unit const& u : attackers) + { + if (u.is_player || !(u.victim == me) || u.hp <= 0 || u.untargetable || u.is_pacified || u.cannot_reach) continue; + float const dx = u.x - bx, dy = u.y - by, d = dx * dx + dy * dy; + if (d <= best_d) { best_d = d; best = &u; } + } + return best; + } + + // The enemy player attacking this bot (an attacker that is a player, its victim `me`, alive and fightable, not held by a friendly + // CC, within kShotByRange), nearest first; nullptr when none. A pusher fights back before the march goes on, as BesetBy does for + // creatures. Bot-only AV 264: after both general pushes went, 152 of the 290 deaths to players had the march + // (combat:bg_push_endgame_advance) as their last rule: the two squads met on the river road under Iceblood Tower and walked past each + // other, shot from 0-40 yd (136 of the 152), and neither got past Iceblood in 28 minutes. + constexpr float kShotByRange = 40.0f; + template + Unit const* ShotBy(Guid const& me, float bx, float by, std::vector const& attackers) + { + Unit const* best = nullptr; + float best_d = kShotByRange * kShotByRange; + for (Unit const& u : attackers) + { + if (!u.is_player || !(u.victim == me) || u.hp <= 0 || u.untargetable || u.is_pacified || u.cannot_reach || u.is_cc_locked) + continue; + float const dx = u.x - bx, dy = u.y - by, d = dx * dx + dy * dy; + if (d <= best_d) { best_d = d; best = &u; } + } + return best; + } } diff --git a/src/modules/PlayerbotV2/Bot/Battleground/BgTeamCoordinator.cpp b/src/modules/PlayerbotV2/Bot/Battleground/BgTeamCoordinator.cpp index 5fcc7e397d..7b9be7968a 100644 --- a/src/modules/PlayerbotV2/Bot/Battleground/BgTeamCoordinator.cpp +++ b/src/modules/PlayerbotV2/Bot/Battleground/BgTeamCoordinator.cpp @@ -33,6 +33,7 @@ #include "Player.h" #include "BgAvPlan.h" +#include "BgWaypointRoutes.h" #include #include #include @@ -403,20 +404,40 @@ void BgTeamCoordinator::PlanCtf(TeamPlanContext& ctx) }; return key(a) < key(b); }); - int k = 0; - auto give = [&](Zone const& z, int count, uint8 squad) + auto assign_zone = [&](Member& m, Zone const& z, uint8 squad) { - for (int q = 0; q < count && k < n; ++q, ++k) - { - Member& m = ctx.members[free_idx[k]]; - float const ox = float(int((m.guid_low * 7u) % 15u) - 7), oy = float(int((m.guid_low * 11u) % 15u) - 7); - AssignOrder(m.guid_low, BgOrder::AttackNode, z.x + ox, z.y + oy, z.z, ObjectGuid::Empty, squad, /*target_entry=*/0); - m.assigned = true; - } + float const ox = float(int((m.guid_low * 7u) % 15u) - 7), oy = float(int((m.guid_low * 11u) % 15u) - 7); + AssignOrder(m.guid_low, BgOrder::AttackNode, z.x + ox, z.y + oy, z.z, ObjectGuid::Empty, squad, /*target_entry=*/0); + m.assigned = true; }; - give(kMid, n_mid, 3); - give(enemy_gy, n_camp, 4); - give(own_gy, n_own, 5); + Zone const zones[3] = { kMid, enemy_gy, own_gy }; + int quota[3] = { n_mid, n_camp, n_own }; + // A bot keeps the zone it already holds while that zone still has room. The free list shrinks and grows as bots become + // escorts or hunters, so the hash order alone moved a bot from the middle to the graveyard every few seconds. + // A new rotation epoch reshuffles everyone (that is the point of the rotation); within an epoch nobody moves. + uint64 const zone_key = (uint64(ctx.instance_id) << 2) | ctx.team; + auto ze = zone_epoch_.find(zone_key); + bool const same_epoch = ze != zone_epoch_.end() && ze->second == epoch; + zone_epoch_[zone_key] = epoch; + std::vector rest; + for (int idx : free_idx) + { + Member& m = ctx.members[idx]; + auto prev = orders_.find(m.guid_low); + int const zone = (same_epoch && prev != orders_.end() && prev->second.kind == BgOrder::AttackNode && + prev->second.squad >= 3 && prev->second.squad <= 5) ? int(prev->second.squad) - 3 : -1; + if (zone >= 0 && quota[zone] > 0) + { + --quota[zone]; + assign_zone(m, zones[zone], uint8(zone + 3)); + } + else + rest.push_back(idx); + } + size_t k = 0; + for (int zone = 0; zone < 3; ++zone) + for (; quota[zone] > 0 && k < rest.size(); --quota[zone], ++k) + assign_zone(ctx.members[rest[k]], zones[zone], uint8(zone + 3)); } // Remainder stays unordered on pure CTF: the legacy mid-pressure / // score-bias roles are already good there, and leaving them free keeps @@ -563,8 +584,38 @@ void BgTeamCoordinator::PlanNodeRace(TeamPlanContext& ctx) int alive_free = 0; for (auto const& m : ctx.members) if (m.alive && !m.assigned && !m.is_carrier) ++alive_free; + // AV captain first (ike3 / mod-playerbots, see below): the captain squad is reserved before the supporters are picked, so the garrisons, + // the brawl, Snowfall and the mine bosses only take what it leaves (BgAvPlan::CaptainReserve). + const uint64 commit_key = (uint64(ctx.instance_id) << 2) | uint64(ctx.team); + if (ctx.type_id == 1) + { + auto& died = died_ms_[commit_key]; + for (auto const& m : ctx.members) + if (!m.alive) died[m.guid_low] = ctx.in_progress_ms; + } + auto const wipes_it = captain_wipes_.find(commit_key); + bool const captain_given_up = wipes_it != captain_wipes_.end() && BgAvPlan::CaptainGivenUp(int(wipes_it->second)); + bool const captain_first = ctx.type_id == 1 && ctx.captain_alive && PosSet(ctx.captain_x, ctx.captain_y) && !captain_given_up; + // AV general push after the captain (BgAvPlan::GeneralDue): the match time the enemy captain was killed or left is kept per team; + // kGeneralAfterCaptainMs later the team goes for the general whatever the towers, with the same reserve and gather as the captain. + if (ctx.type_id == 1 && !ctx.nodes.empty() && (!ctx.captain_alive || captain_given_up)) + captain_done_ms_.emplace(commit_key, ctx.in_progress_ms); + bool general_due = false; + if (ctx.type_id == 1 && ctx.endgame_creature_entry != 0 && PosSet(ctx.endgame_x, ctx.endgame_y)) + if (auto const done = captain_done_ms_.find(commit_key); done != captain_done_ms_.end()) + general_due = BgAvPlan::GeneralDue(ctx.in_progress_ms, done->second); + int const captain_reserve = (captain_first || general_due) ? BgAvPlan::CaptainReserve(alive_free) : 0; + auto supporters_left = [&]() + { + int n = 0; + for (auto const& m : ctx.members) + if (!m.assigned && m.alive && !m.is_carrier) ++n; + return std::max(0, n - captain_reserve); + }; // The brawlers come out of the garrisons first: a bot fighting in the valley is not standing on a tower. - const int garrison_budget = std::max(1, int(float(alive_free) * 0.6f * (1.0f - 0.6f * mid_share))); + int garrison_budget = std::max(1, int(float(alive_free) * 0.6f * (1.0f - 0.6f * mid_share))); + if (captain_first || general_due) + garrison_budget = std::min(garrison_budget, std::max(0, alive_free - captain_reserve)); const int emergency_budget = std::max(1, (alive_free * 3) / 4); int spent = 0; // AV defender flip (mod-playerbots BGT 1919-1931): a bot already deep in the enemy half does not garrison; it keeps free for the attack. @@ -668,6 +719,24 @@ void BgTeamCoordinator::PlanNodeRace(TeamPlanContext& ctx) float tx = 0.f, ty = 0.f, tz = 0.f; uint8 order_kind = BgOrder::AttackNode; uint32 push_entry = 0; + // AV node rally (set in the AV attack branch below): a bot far behind the captain waiting spot meets the squad there first + // (BgAvPlan::RallyFirst), and while the squad gathers (node_go false) the bots at the spot wait. Gives where `m` goes for a node at (x,y,z). + bool node_rally = false, node_go = true; + float node_stage_x = 0.f, node_stage_y = 0.f, node_stage_z = 0.f; // the node squad's waiting spot (set with node_rally) + // AV assault waves (BgAvPlan::OutOfWave): while the captain / general assault is on, a squad bot that died after its wave went goes to + // the waiting spot (wave_x/y/z) instead, with target_entry wave_entry. + uint32 wave_ms = 0; + bool wave = false; + float wave_x = 0.f, wave_y = 0.f, wave_z = 0.f; + uint32 wave_entry = 0; + auto rally_dest = [&](Member const& m, float& x, float& y, float& z) + { + if (!node_rally) return; + float const stage_to = std::sqrt(Dist2(node_stage_x, node_stage_y, x, y)); + bool const at_stage = Dist2(m.x, m.y, node_stage_x, node_stage_y) < 60.f * 60.f; + if (BgAvPlan::RallyFirst(std::sqrt(Dist2(m.x, m.y, x, y)), stage_to) || (!node_go && at_stage)) + { x = node_stage_x; y = node_stage_y; z = node_stage_z; } + }; // Push the enemy boss when LOSING (all_in) OR when the script flags the // push unconditional (AV: enemy reinforcements are low — the boss kill // ends the match regardless of node count, so push even while winning). @@ -692,18 +761,24 @@ void BgTeamCoordinator::PlanNodeRace(TeamPlanContext& ctx) // genuinely crushed (score_delta < -150, i.e. about to lose — fall back to // defending). This is also how humans break the stall: the leading team // drives the captain->general kill instead of trading nodes forever. - const uint64 commit_key = (uint64(ctx.instance_id) << 2) | uint64(ctx.team); if (lead_push) endgame_commit_[commit_key] = ctx.in_progress_ms; const bool committed = endgame_commit_.find(commit_key) != endgame_commit_.end(); if (ctx.endgame_creature_entry == 0 || ctx.score_delta < -150) endgame_commit_.erase(commit_key); // endgame done / team collapsing if (!ctx.captain_alive) - { captain_go_.erase(commit_key); captain_wait_.erase(commit_key); } // captain dead: the next assault starts from the staging spot again + { + captain_gate_.Reset(commit_key); // captain dead: start over + captain_wipes_.erase(commit_key); + // Once per match (bot-only AV 255 had no line for it: the captain kills could only be read off the plan switching to the nodes). + if (ctx.type_id == 1 && !ctx.nodes.empty() && captain_down_.insert(commit_key).second) + TC_LOG_INFO("playerbot.v2", "[bgcoord] bg_type={} instance={} team={} enemy captain {} down at {} s", ctx.type_id, ctx.instance_id, + ctx.team, ctx.team == 1 ? 11947u : 11949u, ctx.in_progress_ms / 1000u); + } const bool sticky_push = committed && ctx.endgame_creature_entry != 0 && ctx.score_delta >= -150; const bool push_boss = all_in || ctx.endgame_unconditional || lead_push || - sticky_push; + sticky_push || general_due; // Enemy towers / bunkers still standing (AV): the general keeps their buffs, so the general push waits until they are down // (ike3's rule). A tower is a priority-2 script node held by the enemy that is not razed. @@ -727,20 +802,20 @@ void BgTeamCoordinator::PlanNodeRace(TeamPlanContext& ctx) if (PosSet(ctx.endgame_x, ctx.endgame_y)) for (auto const& m : ctx.members) if (m.alive && Dist2(m.x, m.y, ctx.endgame_x, ctx.endgame_y) < 200.f * 200.f) ++friends_near_boss; - bool const general_ok = BgAvPlan::GeneralPushOk(enemy_towers_up, enemy_towers_razed, own_final_gy, friends_near_boss); + bool const general_ok = general_due || BgAvPlan::GeneralPushOk(enemy_towers_up, enemy_towers_razed, own_final_gy, friends_near_boss); // -- AV open-field brawl (playtest 2026-10-08) ------------------------------- // Send the brawlers (share decided above) to the fight zone as ordinary AttackNode orders. The brawl ends once // the push for the enemy captain/general is on (a lead, a deficit, low enemy reinforcements), so matches end. // The brawl also goes on while the general push is held back by standing enemy towers and no captain is left to go for. - bool const push_held = ctx.endgame_needs_towers && !general_ok && !(ctx.captain_alive && PosSet(ctx.captain_x, ctx.captain_y)); + bool const push_held = ctx.endgame_needs_towers && !general_ok && !(ctx.captain_alive && PosSet(ctx.captain_x, ctx.captain_y) && !captain_given_up); if (mid_share > 0.f && (!push_boss || push_held)) { int free_n = 0; for (auto const& m : ctx.members) if (!m.assigned && m.alive && !m.is_carrier) ++free_n; // The squad keeps at least 30% of the free bots so towers still fall. - int const to_mid = std::min(int(mid_share * float(alive_total) + 0.5f), (free_n * 7) / 10); + int const to_mid = std::min({ int(mid_share * float(alive_total) + 0.5f), (free_n * 7) / 10, supporters_left() }); for (int q = 0; q < to_mid; ++q) { int const pick = PickNearest(ctx.members, BgOrder::AttackNode, ctx.fight_x, ctx.fight_y, /*healer_bias=*/0, @@ -766,7 +841,7 @@ void BgTeamCoordinator::PlanNodeRace(TeamPlanContext& ctx) int free_n = 0; for (auto const& m : ctx.members) if (!m.assigned && m.alive && !m.is_carrier) ++free_n; - int const k = BgAvPlan::SnowfallDetail(free_n, ctx.in_progress_ms); + int const k = std::min(BgAvPlan::SnowfallDetail(free_n, ctx.in_progress_ms), supporters_left()); for (int q = 0; q < k; ++q) { int const pick = PickNearest(ctx.members, BgOrder::AttackNode, n.x, n.y, /*healer_bias=*/+1, /*allow_carrier=*/false); @@ -780,7 +855,7 @@ void BgTeamCoordinator::PlanNodeRace(TeamPlanContext& ctx) // AV mine bosses (ike3 mine-boss objective): a few bots kill the boss of every mine the team does not own. Not during the push. if (!push_boss || push_held) for (auto const& kt : ctx.kill_targets) - for (int q = 0; q < 3; ++q) + for (int q = 0; q < 3 && supporters_left() > 0; ++q) { int const pick = PickNearest(ctx.members, BgOrder::PushEndgame, kt.x, kt.y, /*healer_bias=*/+1, /*allow_carrier=*/false); if (pick < 0) break; @@ -790,31 +865,35 @@ void BgTeamCoordinator::PlanNodeRace(TeamPlanContext& ctx) // ike3 / mod-playerbots: the captain comes first. Non-supporters (ike3 60-80 %) or 90 % of everyone (mod-playerbots) walk to the enemy // captain while it lives, gathering at the staging spot first; the towers follow once it is down. So the captain squad starts without - // the lead / deficit trigger the general push needs. - bool const captain_first = ctx.type_id == 1 && ctx.captain_alive && PosSet(ctx.captain_x, ctx.captain_y); - if ((push_boss || captain_first) && ctx.captain_alive && PosSet(ctx.captain_x, ctx.captain_y)) + // the lead / deficit trigger the general push needs (captain_first, decided with the supporter budget above). + if ((push_boss || captain_first) && ctx.captain_alive && PosSet(ctx.captain_x, ctx.captain_y) && !captain_given_up) { // Captain: the squad gathers at the staging spot and goes in together once five of the team stand there (ike3: engage once 5 // attackers are at the waiting spot). The decision latches until the captain is dead. bool go = true; if (PosSet(ctx.captain_stage_x, ctx.captain_stage_y)) { - if (captain_go_.find(commit_key) == captain_go_.end()) + bool wiped = false; + go = AvAssaultGo(ctx, captain_gate_, commit_key, ctx.captain_stage_x, ctx.captain_stage_y, { { ctx.captain_x, ctx.captain_y } }, + free_count, "captain", wiped); + if (wiped) { - int at_stage = 0; - for (auto const& m : ctx.members) - if (m.alive && Dist2(m.x, m.y, ctx.captain_stage_x, ctx.captain_stage_y) < 60.f * 60.f) ++at_stage; - uint32 const waited_since = captain_wait_.emplace(commit_key, ctx.in_progress_ms).first->second; - uint32 const waited = ctx.in_progress_ms >= waited_since ? ctx.in_progress_ms - waited_since : 0u; - if (BgAvPlan::CaptainGather(at_stage, false, waited)) captain_go_[commit_key] = ctx.in_progress_ms; + uint32 const wipes = ++captain_wipes_[commit_key]; + TC_LOG_INFO("playerbot.v2", "[bgcoord] bg_type={} instance={} team={} captain assault wiped ({} of {}){}", ctx.type_id, + ctx.instance_id, ctx.team, wipes, BgAvPlan::kCaptainMaxAssaults, + BgAvPlan::CaptainGivenUp(int(wipes)) ? ", captain left, towers next" : ", gathering again"); } - go = captain_go_.find(commit_key) != captain_go_.end(); } if (go) { tx = ctx.captain_x; ty = ctx.captain_y; tz = ctx.captain_z; order_kind = BgOrder::PushEndgame; push_entry = ctx.captain_creature_entry; + if (auto const went = captain_gate_.go.find(commit_key); went != captain_gate_.go.end()) + { + wave = true; wave_ms = went->second; + wave_x = ctx.captain_stage_x; wave_y = ctx.captain_stage_y; wave_z = ctx.captain_stage_z; + } } else { @@ -824,9 +903,80 @@ void BgTeamCoordinator::PlanNodeRace(TeamPlanContext& ctx) } else if (push_boss && general_ok && PosSet(ctx.endgame_x, ctx.endgame_y)) { - tx = ctx.endgame_x; ty = ctx.endgame_y; tz = ctx.endgame_z; - order_kind = BgOrder::PushEndgame; - push_entry = ctx.endgame_creature_entry; + // AV: the squad gathers at our graveyard nearest the general (BgAvPlan::GeneralStageGraveyard; without one, kGeneralStageBack + // yards short of him on the route in) and goes into his room together, the captain's gather / go / regroup cycle. Walking in as + // they came, the bots met the enemy team and the keep's guards one at a time. + bool go = true; + float sx = 0.f, sy = 0.f, sz = 0.f; + bool staged = false; + // The enemy graveyard the push takes on its way (BgAvPlan::GeneralRouteGraveyard), nullptr when the general is next. + BgNodeState const* step_gy = nullptr; + if (ctx.type_id == 1) + { + std::vector gy; + std::vector gy_nodes; + for (auto const& n : ctx.nodes) + if (!n.is_destroyed && NodePriorityFor(ctx, n) == 0) + { + gy.push_back({ n.x, n.y, n.owner_team == ctx.team, n.is_contested }); + gy_nodes.push_back(&n); + } + int const pick = BgAvPlan::GeneralStageGraveyard(gy, ctx.endgame_x, ctx.endgame_y); + if (pick >= 0) + { + sx = gy_nodes[pick]->x; sy = gy_nodes[pick]->y; sz = gy_nodes[pick]->z; + staged = true; + } + else + staged = BgRoutes::ApproachPoint(uint16(ctx.type_id), ctx.home_x, ctx.home_y, ctx.home_z, ctx.endgame_x, ctx.endgame_y, + ctx.endgame_z, BgAvPlan::kGeneralStageBack, sx, sy, sz); + int const step = BgAvPlan::GeneralRouteGraveyard(gy, pick, ctx.home_x, ctx.home_y, ctx.endgame_x, ctx.endgame_y, enemy_team); + if (step >= 0) + step_gy = gy_nodes[step]; + } + if (staged) + { + bool wiped = false; + std::pair const target = step_gy ? std::make_pair(step_gy->x, step_gy->y) : std::make_pair(ctx.endgame_x, ctx.endgame_y); + go = AvAssaultGo(ctx, general_gate_, commit_key, sx, sy, { target }, free_count, "general", wiped); + if (wiped) + TC_LOG_INFO("playerbot.v2", "[bgcoord] bg_type={} instance={} team={} general assault wiped, gathering again", ctx.type_id, + ctx.instance_id, ctx.team); + if (auto const went = general_gate_.go.find(commit_key); go && went != general_gate_.go.end()) + { + wave = true; wave_ms = went->second; + wave_x = sx; wave_y = sy; wave_z = sz; + wave_entry = ctx.endgame_creature_entry; // keeps the push's route round a living captain, as on the graveyard steps + } + } + if (go && step_gy) + { + // Take the graveyard: an ordinary node assault order, so the squad clicks the banner and holds it while it turns. It carries + // the general's entry (only PushEndgame reads it as a kill target) so the bots keep the general push's route round a living + // captain (State_Idle BgRouteMove): from Snowfall the plain route to Iceblood Graveyard passes 62 yd from Galvangar. + tx = step_gy->x; ty = step_gy->y; tz = step_gy->z; + order_kind = BgOrder::AttackNode; + push_entry = ctx.endgame_creature_entry; + uint64 const step_sig = uint64(uint32(int32(tx))) << 32 | uint32(int32(ty)); + uint64& last_step = general_step_[commit_key]; + if (last_step != step_sig) + { + last_step = step_sig; + TC_LOG_INFO("playerbot.v2", "[bgcoord] bg_type={} instance={} team={} general push takes the graveyard at ({:.0f},{:.0f}) first", + ctx.type_id, ctx.instance_id, ctx.team, tx, ty); + } + } + else if (go) + { + tx = ctx.endgame_x; ty = ctx.endgame_y; tz = ctx.endgame_z; + order_kind = BgOrder::PushEndgame; + push_entry = ctx.endgame_creature_entry; + } + else + { + tx = sx; ty = sy; tz = sz; + order_kind = BgOrder::AttackNode; + } } else { @@ -882,6 +1032,39 @@ void BgTeamCoordinator::PlanNodeRace(TeamPlanContext& ctx) if (rank == 0) { tx = n.x; ty = n.y; tz = n.z; best_cost = 0.f; } ++rank; } + // Node rally: the captain is dead or left (or the push waits for the towers), so the squads for these nodes go in together + // from the captain waiting spot, the same gather / go / regroup cycle as the captain assault (AvAssaultGo). The squad is the + // bots that would rally (far behind the spot, or standing at it); bots already nearer the nodes go straight in. + // The waiting spot is on the near side of the first node (BgAvPlan::kNodeRallyBack back along the recorded route from the + // home base), not the captain's: bot-only AV 257, after Balinda died the Horde gathered at her spot (28,-303), which lies + // beyond its target Stonehearth Bunker, so every bot walked alone past Commander Randolph and the bunker's bowmen + // (71 Horde deaths to them in 21 minutes) and the Horde sent 2 node assaults to the Alliance's 10. For the Alliance on + // Iceblood Tower the spot comes out where Galvangar's was, (-492,-187). + node_stage_x = ctx.captain_stage_x; node_stage_y = ctx.captain_stage_y; node_stage_z = ctx.captain_stage_z; + if (!split_cands.empty()) + BgRoutes::ApproachPoint(uint16(ctx.type_id), ctx.home_x, ctx.home_y, ctx.home_z, split_cands[0].x, split_cands[0].y, + split_cands[0].z, BgAvPlan::kNodeRallyBack, node_stage_x, node_stage_y, node_stage_z); + if (!split_cands.empty() && PosSet(node_stage_x, node_stage_y)) + { + node_rally = true; + std::vector> targets; + for (auto const& c : split_cands) targets.emplace_back(c.x, c.y); + int squad = 0; + for (auto const& m : ctx.members) + { + if (m.assigned || !m.alive || m.is_carrier) continue; + if (Dist2(m.x, m.y, node_stage_x, node_stage_y) < 60.f * 60.f) { ++squad; continue; } + for (auto const& c : split_cands) + if (BgAvPlan::RallyFirst(std::sqrt(Dist2(m.x, m.y, c.x, c.y)), + std::sqrt(Dist2(node_stage_x, node_stage_y, c.x, c.y)))) + { ++squad; break; } + } + bool wiped = false; + node_go = AvAssaultGo(ctx, node_gate_, commit_key, node_stage_x, node_stage_y, targets, squad, "node", wiped); + if (wiped) + TC_LOG_INFO("playerbot.v2", "[bgcoord] bg_type={} instance={} team={} node assault wiped, gathering again", ctx.type_id, + ctx.instance_id, ctx.team); + } } if (split_cands.size() >= 2 && ctx.nodes.size() >= 4) { @@ -918,7 +1101,9 @@ void BgTeamCoordinator::PlanNodeRace(TeamPlanContext& ctx) auto prev = orders_.find(m.guid_low); if (prev == orders_.end() || prev->second.kind != BgOrder::AttackNode || prev->second.squad != 1) continue; if (Dist2(prev->second.x, prev->second.y, c.x, c.y) >= kStickyRadius * kStickyRadius) continue; - AssignOrder(m.guid_low, BgOrder::AttackNode, c.x, c.y, c.z, ObjectGuid::Empty, /*squad=*/1, /*target_entry=*/0); + float dx = c.x, dy = c.y, dz = c.z; + rally_dest(m, dx, dy, dz); + AssignOrder(m.guid_low, BgOrder::AttackNode, dx, dy, dz, ObjectGuid::Empty, /*squad=*/1, /*target_entry=*/0); m.assigned = true; ++kept; } @@ -927,7 +1112,9 @@ void BgTeamCoordinator::PlanNodeRace(TeamPlanContext& ctx) int const pick = PickNearest(ctx.members, BgOrder::AttackNode, c.x, c.y, /*healer_bias=*/+1, /*allow_carrier=*/false); if (pick < 0) return; - AssignOrder(ctx.members[pick].guid_low, BgOrder::AttackNode, c.x, c.y, c.z, + float dx = c.x, dy = c.y, dz = c.z; + rally_dest(ctx.members[pick], dx, dy, dz); + AssignOrder(ctx.members[pick].guid_low, BgOrder::AttackNode, dx, dy, dz, ObjectGuid::Empty, /*squad=*/1, /*target_entry=*/0); ctx.members[pick].assigned = true; } @@ -967,7 +1154,9 @@ void BgTeamCoordinator::PlanNodeRace(TeamPlanContext& ctx) int const pick = PickNearest(ctx.members, BgOrder::AttackNode, c.x, c.y, /*healer_bias=*/+1, /*allow_carrier=*/false); if (pick < 0) break; - AssignOrder(ctx.members[pick].guid_low, BgOrder::AttackNode, c.x, c.y, c.z, + float dx = c.x, dy = c.y, dz = c.z; + rally_dest(ctx.members[pick], dx, dy, dz); + AssignOrder(ctx.members[pick].guid_low, BgOrder::AttackNode, dx, dy, dz, ObjectGuid::Empty, /*squad=*/1, /*target_entry=*/0); ctx.members[pick].assigned = true; } @@ -995,12 +1184,118 @@ void BgTeamCoordinator::PlanNodeRace(TeamPlanContext& ctx) for (auto& m : ctx.members) { if (m.assigned || !m.alive || m.is_carrier) continue; - AssignOrder(m.guid_low, order_kind, tx, ty, tz, ObjectGuid::Empty, + if (wave && OutOfWave(commit_key, m.guid_low, wave_ms)) + { + AssignOrder(m.guid_low, BgOrder::AttackNode, wave_x, wave_y, wave_z, ObjectGuid::Empty, /*squad=*/1, /*target_entry=*/wave_entry); + m.assigned = true; + continue; + } + float dx = tx, dy = ty, dz = tz; + rally_dest(m, dx, dy, dz); // only set for the AV node attack + AssignOrder(m.guid_low, order_kind, dx, dy, dz, ObjectGuid::Empty, /*squad=*/1, /*target_entry=*/push_entry); m.assigned = true; } } +bool BgTeamCoordinator::OutOfWave(uint64 key, uint64 guid, uint32 wave_ms) const +{ + auto const team = died_ms_.find(key); + if (team == died_ms_.end()) return false; + auto const it = team->second.find(guid); + return it != team->second.end() && BgAvPlan::OutOfWave(true, it->second, wave_ms); +} + +// AV assault gate, shared by the captain squad and the node rally (see the header). A wiped assault lets go of the latch: the bots coming +// back from the graveyard gather at the waiting spot again instead of running in one at a time, and the time cap starts over. +bool BgTeamCoordinator::AvAssaultGo(TeamPlanContext const& ctx, AvGate& gate, uint64 key, float stage_x, float stage_y, + std::vector> const& targets, int squad, char const* what, bool& wiped) +{ + wiped = false; + if (targets.empty()) return true; + float stage_to_target = 1e30f; + uint64 sig = 1469598103934665603ull; + for (auto const& t : targets) + { + stage_to_target = std::min(stage_to_target, std::sqrt(Dist2(stage_x, stage_y, t.first, t.second))); + sig = (sig ^ (uint64(uint32(int32(t.first))) << 32 | uint32(int32(t.second)))) * 1099511628211ull; + } + if (auto const went = gate.go.find(key); went != gate.go.end()) + { + // The latched squad moved on to a new target (a node taken): the walk there gets its grace again. + if (auto const ts = gate.targets.find(key); ts == gate.targets.end() || ts->second != sig) + { + went->second = ctx.in_progress_ms; + gate.targets[key] = sig; + } + float const r2 = BgAvPlan::kCaptainSquadRadius * BgAvPlan::kCaptainSquadRadius; + int near_target = 0; + for (auto const& m : ctx.members) + { + if (!m.alive || OutOfWave(key, m.guid_low, went->second)) continue; + for (auto const& t : targets) + { + float const d2 = Dist2(m.x, m.y, t.first, t.second); + // Near a target, or a squad bot (not a garrison or other supporter, those are assigned by now) still on its way in. + if (d2 < r2 || (!m.assigned && BgAvPlan::OnTheWay(std::sqrt(d2), stage_to_target))) { ++near_target; break; } + } + } + uint32 const since_go = ctx.in_progress_ms >= went->second ? ctx.in_progress_ms - went->second : 0u; + if (BgAvPlan::CaptainAssaultBroken(near_target, since_go, BgAvPlan::AssaultGraceMs(stage_to_target))) + { + gate.go.erase(went); + gate.targets.erase(key); + gate.count.erase(key); + gate.rise.erase(key); + gate.wait[key] = ctx.in_progress_ms; + wiped = true; + } + else + { + // The bots back from the graveyard gather at the waiting spot and go in as the next wave (BgAvPlan::WaveReinforce). + int back = 0; + for (auto const& m : ctx.members) + if (m.alive && OutOfWave(key, m.guid_low, went->second) && Dist2(m.x, m.y, stage_x, stage_y) < 60.f * 60.f) ++back; + uint32& last_back = gate.count.emplace(key, 0u).first->second; + uint32& rise_ms = gate.rise.emplace(key, ctx.in_progress_ms).first->second; + if (uint32(back) > last_back) rise_ms = ctx.in_progress_ms; + last_back = uint32(back); + if (BgAvPlan::WaveReinforce(back, ctx.in_progress_ms >= rise_ms ? ctx.in_progress_ms - rise_ms : 0u)) + { + went->second = ctx.in_progress_ms; + gate.count.erase(key); + gate.rise.erase(key); + TC_LOG_INFO("playerbot.v2", "[bgcoord] bg_type={} instance={} team={} {} assault: next wave of {} goes from the waiting spot", + ctx.type_id, ctx.instance_id, ctx.team, what, back); + } + } + } + if (gate.go.find(key) == gate.go.end()) + { + int at_stage = 0; + for (auto const& m : ctx.members) + if (m.alive && Dist2(m.x, m.y, stage_x, stage_y) < 60.f * 60.f) ++at_stage; + uint32 const waited_since = gate.wait.emplace(key, ctx.in_progress_ms).first->second; + uint32 const waited = ctx.in_progress_ms >= waited_since ? ctx.in_progress_ms - waited_since : 0u; + uint32& last_count = gate.count.emplace(key, 0u).first->second; + uint32& rise_ms = gate.rise.emplace(key, ctx.in_progress_ms).first->second; + if (uint32(at_stage) > last_count) rise_ms = ctx.in_progress_ms; + last_count = uint32(at_stage); + uint32 const since_arrival = ctx.in_progress_ms >= rise_ms ? ctx.in_progress_ms - rise_ms : 0u; + if (BgAvPlan::CaptainGather(at_stage, false, waited, squad, since_arrival)) + { + gate.go[key] = ctx.in_progress_ms; + gate.targets[key] = sig; + gate.wait.erase(key); + gate.count.erase(key); + gate.rise.erase(key); + TC_LOG_INFO("playerbot.v2", "[bgcoord] bg_type={} instance={} team={} {} assault goes: {} at the waiting spot, squad {}", + ctx.type_id, ctx.instance_id, ctx.team, what, at_stage, squad); + } + } + return gate.go.find(key) != gate.go.end(); +} + // Match a live node against the script's static node list to read its // priority weight (position match within 25y — banner GO vs advice coords // are a few yards apart on most maps). @@ -1120,6 +1415,9 @@ void BgTeamCoordinator::Update(uint32 now_ms) Battleground* bg = p->GetBattleground(); if (!bg || bg->isArena()) return; if (bg->GetStatus() != STATUS_IN_PROGRESS) return; + // The battleground id alone is not presence: a bot whose port failed kept it in the open world, took an order slot and died in + // Redridge all match (WSG 2026-10-24). Only bots on the battleground's map play its plan. + if (!bg->FindBgMap() || p->FindMap() != bg->FindBgMap()) return; const uint8 team_u8 = p->GetEffectiveTeam() == ALLIANCE ? 1 : 2; const uint64 key = (uint64(bg->GetInstanceID()) << 2) | team_u8; Bucket& b = buckets[key]; @@ -1179,8 +1477,7 @@ void BgTeamCoordinator::Update(uint32 now_ms) ctx.enemy_flag_z = adv.enemy_flag_z; ctx.own_flag_x = adv.own_flag_x; ctx.own_flag_y = adv.own_flag_y; ctx.own_flag_z = adv.own_flag_z; - ctx.home_x = adv.home_base_x; ctx.home_y = adv.home_base_y; - ctx.home_z = adv.home_base_z; + ctx.home_x = adv.home_base_x; ctx.home_y = adv.home_base_y; ctx.home_z = adv.home_base_z; ctx.endgame_x = adv.endgame_target_x; ctx.endgame_y = adv.endgame_target_y; ctx.endgame_z = adv.endgame_target_z; ctx.endgame_unconditional = adv.endgame_unconditional; @@ -1214,7 +1511,7 @@ void BgTeamCoordinator::Update(uint32 now_ms) // own zone), Stonehearth GY on the Alliance side of the valley, Iceblood GY on the Horde side. Coordinates are the AV // script's banner spawns. struct Spot { float x, y, z; }; - Spot const kSpots[] = { { ctx.fight_x, ctx.fight_y, ctx.fight_z }, { 73.7f, -426.0f, 61.0f }, { -612.5f, -397.0f, 61.0f } }; + Spot const kSpots[] = { { ctx.fight_x, ctx.fight_y, ctx.fight_z }, { 77.8f, -404.7f, 46.9f }, { -612.5f, -397.0f, 61.0f } }; uint32 const spot = (ref->bg.in_progress_ms / (5u * 60u * 1000u) + b.instance_id) % 3u; if (spot != 0u) { ctx.fight_x = kSpots[spot].x; ctx.fight_y = kSpots[spot].y; ctx.fight_z = kSpots[spot].z; } @@ -1344,6 +1641,23 @@ void BgTeamCoordinator::Update(uint32 now_ms) it = buckets.count(it->first) ? std::next(it) : endgame_commit_.erase(it); for (auto it = mid_state_.begin(); it != mid_state_.end();) it = buckets.count(it->first) ? std::next(it) : mid_state_.erase(it); + for (auto it = captain_wipes_.begin(); it != captain_wipes_.end();) + it = buckets.count(it->first) ? std::next(it) : captain_wipes_.erase(it); + for (auto it = captain_down_.begin(); it != captain_down_.end();) + it = buckets.count(*it) ? std::next(it) : captain_down_.erase(it); + for (auto it = captain_done_ms_.begin(); it != captain_done_ms_.end();) + it = buckets.count(it->first) ? std::next(it) : captain_done_ms_.erase(it); + for (auto it = general_step_.begin(); it != general_step_.end();) + it = buckets.count(it->first) ? std::next(it) : general_step_.erase(it); + for (auto it = died_ms_.begin(); it != died_ms_.end();) + it = buckets.count(it->first) ? std::next(it) : died_ms_.erase(it); + for (AvGate* gate : { &captain_gate_, &node_gate_, &general_gate_ }) + for (auto* m : { &gate->go, &gate->wait, &gate->count, &gate->rise }) + for (auto it = m->begin(); it != m->end();) + it = buckets.count(it->first) ? std::next(it) : m->erase(it); + for (AvGate* gate : { &captain_gate_, &node_gate_, &general_gate_ }) + for (auto it = gate->targets.begin(); it != gate->targets.end();) + it = buckets.count(it->first) ? std::next(it) : gate->targets.erase(it); last_dump_ = dump.str(); if (last_dump_.empty()) last_dump_ = "no active bot battleground teams"; diff --git a/src/modules/PlayerbotV2/Bot/Battleground/BgTeamCoordinator.h b/src/modules/PlayerbotV2/Bot/Battleground/BgTeamCoordinator.h index 1a3b629899..c2851cd59d 100644 --- a/src/modules/PlayerbotV2/Bot/Battleground/BgTeamCoordinator.h +++ b/src/modules/PlayerbotV2/Bot/Battleground/BgTeamCoordinator.h @@ -48,6 +48,7 @@ #include "../BotSnapshot.h" #include +#include #include #include @@ -151,9 +152,25 @@ private: std::vector dropped_flags; }; + // `targets` = a signature of what the latched squad attacks: a new target (a node taken, the window sliding on) starts the grace again. + // `count` / `rise` = the bots at the waiting spot last plan and when that count last grew (the time cap waits for arrivals to stop). + struct AvGate + { + std::unordered_map go, wait, count, rise; + std::unordered_map targets; + void Reset(uint64 key) { go.erase(key); wait.erase(key); count.erase(key); rise.erase(key); targets.erase(key); } + }; + void PlanTeam(TeamPlanContext& ctx, uint32 now_ms); void PlanCtf(TeamPlanContext& ctx); void PlanNodeRace(TeamPlanContext& ctx); + // AV: runs the gather-at-the-waiting-spot / go in together / regroup-after-a-wipe cycle of `gate` and returns whether the squad goes + // in. `targets` are what the squad attacks (the wipe check looks within BgAvPlan::kCaptainSquadRadius of them, after a grace for the + // walk from the waiting spot to the nearest one); `squad` = the bots the plan sends; `wiped` is set when this call ended an assault. + bool AvAssaultGo(TeamPlanContext const& ctx, AvGate& gate, uint64 key, float stage_x, float stage_y, + std::vector> const& targets, int squad, char const* what, bool& wiped); + // Whether `guid` died after the assault wave of `key` that went at `wave_ms` (BgAvPlan::OutOfWave). + bool OutOfWave(uint64 key, uint64 guid, uint32 wave_ms) const; void AssignOrder(uint64 guid, uint8 kind, float x, float y, float z, ObjectGuid focus = ObjectGuid::Empty, uint8 squad = 0, uint32 target_entry = 0); @@ -179,11 +196,23 @@ private: // pile into the captain's courtyard to kill him. Value = commit timestamp // (unused beyond presence); key packs (instance_id<<8 | team). std::unordered_map endgame_commit_; - // Per-(instance,team) AV captain assault latch: set once enough of the team stood at the staging spot, cleared when the captain - // dies. Without it the squad leaving the spot would drop the count below the threshold and send everyone back. - std::unordered_map captain_go_; - // Per-(instance,team) match time at which the captain squad started waiting at the staging spot (BgAvPlan::kCaptainGatherMaxMs time cap). - std::unordered_map captain_wait_; + // AvGate (above) per (instance,team): `go` is the latch, set once enough of the squad stood at the waiting spot and cleared when the + // target is gone or the squad that went in is wiped (BgAvPlan::CaptainAssaultBroken); without it the squad leaving the spot would + // drop the count below the threshold and send everyone back. `wait` = match time the squad started waiting (the time cap). + // The captain assault, and the assault on the enemy nodes (towers and graveyards) once the captain is dead or left. + AvGate captain_gate_; + AvGate node_gate_; + AvGate general_gate_; // the general push (BgAvPlan::GeneralDue or the tower rule), gathering short of his room + // Per-(instance,team) count of wiped captain assaults; at BgAvPlan::kCaptainMaxAssaults the team leaves the captain for the towers. + std::unordered_map captain_wipes_; + // Per-(instance,team): the enemy captain's death has been logged. + std::unordered_set captain_down_; + // Per-(instance,team): match time at which the enemy captain was first seen dead or was left (BgAvPlan::GeneralDue counts from it). + std::unordered_map captain_done_ms_; + // Per-(instance,team): bot guid -> match time of the last plan that saw it dead (AV assault waves, BgAvPlan::OutOfWave). + std::unordered_map> died_ms_; + // Per-(instance,team): the graveyard the general push last went for (BgAvPlan::GeneralRouteGraveyard), so each new one is logged once. + std::unordered_map general_step_; // Per-(instance,team) AV brawl state: the match's random base share, the follow mode in force // (0 = base, 1 = a human fights in the valley, 2 = a human pushes the enemy bases) and when a // different mode was first wanted (kMidModeHoldMs hysteresis so bots do not flip-flop). @@ -192,6 +221,8 @@ private: // Per-(instance,team,node) match time at which the enemy's assault on a node was first seen: the contest age the defender picker // uses (BgTactics::CanArriveBeforeFlip). Erased as soon as the node is no longer contested. std::unordered_map contest_since_; + // Per-(instance,team) WSG zone-rotation epoch last planned (PlanCtf): bots keep their zone within an epoch, and a new epoch reshuffles. + std::unordered_map zone_epoch_; uint32 last_plan_ms_ = 0; std::string last_dump_; }; diff --git a/src/modules/PlayerbotV2/Bot/Battleground/BgWaypointRoutes.h b/src/modules/PlayerbotV2/Bot/Battleground/BgWaypointRoutes.h index 21e6e97873..0c6dffbab7 100644 --- a/src/modules/PlayerbotV2/Bot/Battleground/BgWaypointRoutes.h +++ b/src/modules/PlayerbotV2/Bot/Battleground/BgWaypointRoutes.h @@ -52,10 +52,12 @@ inline bool IsOneWayPath(std::string_view nm) class Graph { public: + struct AvoidArea { float x, y, r; }; // see kAvoidSets below + // junction_xy: recordings of one place that lie within this many yards (and 4 y in height) are the same place. AV needs 3.5: the // Frostwolf graveyard flag was recorded twice 3.15 y apart ((-1081.3,-348.2) and (-1079.6,-345.5)), which cut the whole Horde half // of the map (129 nodes) off from the valley, so no Horde bot had a route to any Alliance objective (av-stuck-2, 2026-10-11). - Graph(RoutePath const* paths, size_t count, float junction_xy = 2.5f) + Graph(RoutePath const* paths, size_t count, float junction_xy = 2.5f, std::vector avoid = {}) : avoid_(std::move(avoid)) { for (size_t pi = 0; pi < count; ++pi) { @@ -114,14 +116,76 @@ public: return best; } + // The node a bot at (x,y,z) starts its route to `target` from: of the nodes within `slack` yards of as near as the nearest node + // (`nearest`, `nearest_dist` away), the one with the shortest walk to it plus route on to `target`; -1 when none reaches it. A node + // counts only when the recorded paths link it to `nearest` within a short way (either direction), or when it is within kCross yards of + // as near as `nearest`: the recordings are walked ground, a straight line to an unlinked node further off can cross a wall. + // Always starting at the nearest node turned bots round on the spot (bot-only AV 254 / 253 [bg_route] back-and-forths): + // * 2,739 for the Horde at (-418.6,-342.5,18.7) / (-398.0,-372.6,31.4) on the way to Stonehearth: ike3 recorded the second node + // 14 y above the ground the bots walk on (they stand at (-399,-371,17)), so from under it Nearest picked the first one again; + // * 417 on the Alliance cave slope near (488,-427): a bot a few yards past its nearest node was sent back to it by the lookahead; + // * 256 at the Frostwolf graveyard (-1055,-373): the nearest node lies on the one-way path into the graveyard, away from the goal. + // Picking any node within a radius instead (AV 255) sent Horde bots on the Iceblood graveyard path at (-567,-391) straight at the + // tower-crossroad path's first node (-536.6,-373.8) 35 y away, which no walk connects ([wedge] cat=Navmesh): 900 lines stuck. + // 25 y: the AV river road has two recordings 10-15 y apart, and at 15 y a bot between them could take neither and turned round + // (walk sim: stuck runs AV 145 -> 41); the Iceblood graveyard shortcut above is 35 y. + static constexpr float kCross = 25.0f; + int StartToward(float x, float y, float z, int nearest, float nearest_dist, float slack, int target, int variant = 0) const + { + if (nearest < 0) return -1; + float const reach = nearest_dist + slack; + // Recorded-path distance from `nearest` to every node near it, along the paths in either direction (bounded Dijkstra). + size_t const n = nodes_.size(); + float const limit = 2.0f * reach + 20.0f; + std::vector local(n, std::numeric_limits::max()); + using QE = std::pair; + std::priority_queue, std::greater> q; + local[size_t(nearest)] = 0.0f; + q.emplace(0.0f, nearest); + while (!q.empty()) + { + auto [d, u] = q.top(); + q.pop(); + if (d > local[size_t(u)]) continue; + for (auto const* edges : { &nodes_[size_t(u)].out, &nodes_[size_t(u)].in }) + for (auto const& [v, w] : *edges) + if (d + w <= limit && d + w < local[size_t(v)]) + { + local[size_t(v)] = d + w; + q.emplace(d + w, v); + } + } + int best = -1; + float best_cost = std::numeric_limits::max(); + for (size_t i = 0; i < n; ++i) + { + RoutePoint const& p = nodes_[i].p; + float const dx = p.x - x, dy = p.y - y, dz = (p.z - z) * 3.0f; + float const d = std::sqrt(dx * dx + dy * dy + dz * dz); + if (d > reach) continue; + // Linked to the nearest node by the recorded paths nearby, or about as near as it: the same stretch of ground. + if (local[i] == std::numeric_limits::max() && d > nearest_dist + kCross) continue; + float const route = DistanceTo(int(i), target, variant); + if (route == std::numeric_limits::max()) continue; + if (d + route < best_cost) { best_cost = d + route; best = int(i); } + } + return best; + } + // Next node to step to from `from` on the shortest path to `target`, or -1 when `target` is unreachable. // variant 0 = the plain shortest path; 1..kVariants-1 scale every recorded path's length by a per-variant factor (0.75 .. 1.6) so // different bots / different runs prefer different tunnels, graveyard jumps and roofs instead of all walking one lane. static constexpr int kVariants = 8; + // Avoid sets: a route `variant` of kVariants * k + v is variant v that keeps clear of avoid area k (1-based, the graph's `avoid` list, + // AV only): every recorded edge with an end inside the area costs kAvoidFactor times its length, so the route goes round when there + // is a way round and still goes through when there is none. + static constexpr int kAvoidSets = 3; + static constexpr float kAvoidFactor = 20.0f; + static constexpr int kRouteKeys = kVariants * kAvoidSets; int NextToward(int from, int target, int variant = 0) const { if (from == target) return -1; - Table const& t = HopsTo(target, variant % kVariants); + Table const& t = HopsTo(target, variant % kRouteKeys); return t.hop[size_t(from)]; } @@ -129,7 +193,7 @@ public: float DistanceTo(int from, int target, int variant = 0) const { if (from == target) return 0.0f; - return HopsTo(target, variant % kVariants).dist[size_t(from)]; + return HopsTo(target, variant % kRouteKeys).dist[size_t(from)]; } // The first / last node of the recorded path called `name`, or -1. @@ -166,7 +230,7 @@ private: Table const& HopsTo(int target, int variant) const { std::lock_guard lock(mutex_); - int const key = target * kVariants + variant; + int const key = target * kRouteKeys + variant; auto it = cache_.find(key); if (it != cache_.end()) return it->second; size_t const n = nodes_.size(); @@ -176,13 +240,22 @@ private: std::priority_queue, std::greater> pq; dist[size_t(target)] = 0.0f; pq.emplace(0.0f, target); + int const avoid = variant / kVariants; + AvoidArea const* area = avoid > 0 && size_t(avoid) <= avoid_.size() ? &avoid_[size_t(avoid - 1)] : nullptr; + auto inside = [&](int i) + { + if (!area) return false; + float const dx = nodes_[size_t(i)].p.x - area->x, dy = nodes_[size_t(i)].p.y - area->y; + return dx * dx + dy * dy <= area->r * area->r; + }; while (!pq.empty()) { auto [d, v] = pq.top(); pq.pop(); if (d > dist[size_t(v)]) continue; for (auto const& [u, w] : nodes_[size_t(v)].in) // u -> v exists - if (float const w2 = w * Factor(nodes_[size_t(u)].path, variant); d + w2 < dist[size_t(u)]) + if (float const w2 = w * Factor(nodes_[size_t(u)].path, variant % kVariants) * (inside(u) || inside(v) ? kAvoidFactor : 1.0f); + d + w2 < dist[size_t(u)]) { dist[size_t(u)] = d + w2; hop[size_t(u)] = v; @@ -204,13 +277,24 @@ private: mutable std::mutex mutex_; mutable std::unordered_map cache_; std::vector names_; + std::vector avoid_; }; +// AV route avoid sets (Graph::kAvoidSets) and the radius round the captain they keep clear of: his garrison (Galvangar's Frostwolf +// Warriors and lieutenants stand 10-40 yd from him) and the road through it (Iceblood Garrison (-492,-187) is 57 yd, (-532,-231) 67 yd). +constexpr int kAvoidGalvangar = 1; +constexpr int kAvoidBalinda = 2; +constexpr float kCaptainAvoidRadius = 70.0f; + inline Graph const* GraphFor(uint16_t bg_type) { static Graph const wsg(kPathsWsg, sizeof(kPathsWsg) / sizeof(kPathsWsg[0])); static Graph const ab(kPathsAb, sizeof(kPathsAb) / sizeof(kPathsAb[0])); - static Graph const av(kPathsAv, sizeof(kPathsAv) / sizeof(kPathsAv[0]), 3.5f); + // AV avoid areas (Graph::kAvoidSets): 1 = Iceblood Garrison around Galvangar, 2 = Stonehearth Outpost around Balinda. A team that + // left the enemy captain alive (BgAvPlan::CaptainGivenUp) walks its general push round his garrison: in bot-only AV 263 the + // Alliance push from Snowfall took the road through Iceblood Garrison past the living Galvangar and died there. + static Graph const av(kPathsAv, sizeof(kPathsAv) / sizeof(kPathsAv[0]), 3.5f, + { { -545.2f, -165.4f, kCaptainAvoidRadius }, { -57.8f, -286.6f, kCaptainAvoidRadius } }); switch (bg_type) { case 1: return &av; @@ -220,6 +304,37 @@ inline Graph const* GraphFor(uint16_t bg_type) } } +// A recorded node on the route from (hx,hy,hz) to (tx,ty,tz), the first one walking back from the target end that is at least `back` +// yards from the target (x/y): a spot on the near side of the target, on the way in. False when the graph has no such route; when the +// whole route is nearer than `back`, its first node. +inline bool ApproachPoint(uint16_t bg_type, float hx, float hy, float hz, float tx, float ty, float tz, float back, + float& rx, float& ry, float& rz) +{ + Graph const* g = GraphFor(bg_type); + if (!g || g->size() == 0) return false; + float dh = 0.f, dt = 0.f; + int const from = g->Nearest(hx, hy, hz, dh); + int const to = g->Nearest(tx, ty, tz, dt); + if (from < 0 || to < 0) return false; + std::vector path{ from }; + for (int cur = from; cur != to;) + { + cur = g->NextToward(cur, to); + if (cur < 0 || path.size() > g->size()) return false; + path.push_back(cur); + } + for (auto it = path.rbegin(); it != path.rend(); ++it) + { + RoutePoint const& p = g->Point(*it); + if ((p.x - tx) * (p.x - tx) + (p.y - ty) * (p.y - ty) >= back * back || std::next(it) == path.rend()) + { + rx = p.x; ry = p.y; rz = p.z; + return true; + } + } + return false; +} + // The waypoint to walk to next on the way from (bx,by,bz) to (tx,ty,tz): the first node on the recorded route that is at least // `lookahead` yards from the bot (or the route's last node). False = no usable route (not a classic BG, a leg shorter than 40 y, // the bot or the goal far from every recorded path, no connection): the caller then walks straight to the goal as before. @@ -247,7 +362,26 @@ inline bool NextWaypoint(uint16_t bg_type, float bx, float by, float bz, float t nx = f.x; ny = f.y; nz = f.z; return true; } - int cur = from; + int const cur_start = g->StartToward(bx, by, bz, from, db, std::max(lookahead, 20.0f), to, variant); + int cur = cur_start >= 0 ? cur_start : from; + // No recorded way from here to the goal: no waypoint (the bot moves on the navmesh). Returning the start node anyway sent a bot + // 20-28 yd from it back to it and the plain move away again, for good (AV, Snowfall to the node nearest a goal on a one-way path). + if (cur != to && g->NextToward(cur, to, variant) < 0) + return false; + // A start node the bot has already walked past (its next node on the route is nearer the bot than the start node is) is not walked + // back to (AV, the Horde's river road to its captain waiting spot: a bot at (-334,-284) started at (-360.3,-299.9) 31 yd behind it, + // past the lookahead, and turned round between that node and (-294.7,-283.6) for good). + for (int k = 0; k < 4 && cur != to; ++k) + { + int const next = g->NextToward(cur, to, variant); + if (next < 0) break; + RoutePoint const& a = g->Point(cur); + RoutePoint const& b = g->Point(next); + auto d2 = [](float x, float y, float z, RoutePoint const& q) + { float const dx = q.x - x, dy = q.y - y, dz = (q.z - z) * 3.0f; return dx * dx + dy * dy + dz * dz; }; + if (d2(bx, by, bz, b) >= d2(a.x, a.y, a.z, b)) break; + cur = next; + } int steps = 0; while (steps++ < 64) { diff --git a/src/modules/PlayerbotV2/Bot/Battleground/Scripts/AlteracValleyScript.cpp b/src/modules/PlayerbotV2/Bot/Battleground/Scripts/AlteracValleyScript.cpp index 7daad0b60d..896377a7d5 100644 --- a/src/modules/PlayerbotV2/Bot/Battleground/Scripts/AlteracValleyScript.cpp +++ b/src/modules/PlayerbotV2/Bot/Battleground/Scripts/AlteracValleyScript.cpp @@ -44,14 +44,15 @@ public: // AV banners are GO type 1 (BUTTON) / type 10 (GOOBER) — there are // NO type-42/24 GOs on map 30 (audit B26), so node interaction was // impossible. Enumerate the DB-verified banner entries instead - // (every per-state Alliance/Horde/Contested variant on map 30). + // (every per-state Alliance/Horde/Contested variant on map 30). The + // "[PH] ... Tower Banner BIG" / "Pre-Banner BIG" objects on the tower + // tops are decorations (no lock, no script): clicking one does nothing, + // and the AV 247 soak spent 103 captures on 178927, so they are not here. a.auto_use_go_entries = { - 178364, 178365, 178388, 178389, 178393, 178394, 178925, 178927, - 178929, 178932, 178935, 178936, 178940, 178943, 178944, 178945, - 178946, 178947, 178948, 178955, 178956, 178957, 178958, 179284, + 178364, 178365, 178388, 178389, 178393, 178394, 178925, 178929, + 178935, 178936, 178940, 178943, 178944, 178945, 178946, 179284, 179285, 179286, 179287, 179304, 179305, 179308, 179310, 179435, - 179436, 179439, 179440, 179441, 179442, 179443, 179444, 179445, - 179446, 179449, 179450, 179453, 179454, 179458, 179465, 179466, + 179439, 179441, 179443, 179445, 179449, 179453, 179465, 179466, 179467, 179468, 179470, 179471, 179472, 179473, 179481, 179482, 179483, 179484, 180418, 180419, 180420, }; @@ -67,8 +68,9 @@ public: // spawn clusters on map 30. if (s.is_horde()) { - // Horde spawn — Frostwolf Stadium (V1 HORDE_SPAWNS[0]). - a.home_base_x = -1437.00f; a.home_base_y = -610.00f; a.home_base_z = 51.16f; + // Horde start = world_safe_locs 610 (world SQL 2026_10_25_95): behind the Horde gate. The old (-1437,-610,51) was inside the hill + // in the 70532 map 30 (no geometry, no navmesh), so no Horde bot ever left it. + a.home_base_x = -890.00f; a.home_base_y = -575.00f; a.home_base_z = 70.24f; // Endgame: Vanndar Stormpike in Dun Baldar (NORTH end, +X). a.endgame_target_x = 722.4f; a.endgame_target_y = -11.0f; @@ -88,8 +90,12 @@ public: // Captain staging (ike3 BattleGroundTacticsAV.cpp, Karrz1/wow-1.12 raid10-revamp bcc8b9fe, named locations // AV_ICEBLOOD_GARRISON_WAITING_ALLIANCE / AV_STONEHEART_OUTPOST_WAITING_HORDE): the squad for the enemy captain gathers here and // goes in together (BgTeamCoordinator::PlanNodeRace), not one bot after another. The Alliance hunts Galvangar, the Horde Balinda. + // Horde: not ike3's (28.1,-302.6), which lies east of Balinda inside Stonehearth Outpost (an Alliance Sentinel 3 yd away, + // Lieutenant Stouthandle 11 yd): coming from the west every bot had to pass her and her guards to get there, and in bot-only + // AV 261 the Horde squad did not gather for 51 minutes (first assault 00:17, "5 at the waiting spot, squad 31"). This is the + // recorded river road node 115 yd west of her, on the way in from the Horde base, nearest creature 58 yd. if (s.is_horde()) - { a.captain_stage_x = 28.1264f; a.captain_stage_y = -302.593f; a.captain_stage_z = 15.076f; } + { a.captain_stage_x = -171.3f; a.captain_stage_y = -266.6f; a.captain_stage_z = 9.1f; } else { a.captain_stage_x = -492.17f; a.captain_stage_y = -187.077f; a.captain_stage_z = 57.1342f; } // ike3 only goes for the general once every enemy tower / bunker is down (they carry the general's buffs). @@ -122,7 +128,7 @@ public: // Graveyards — priority 0 (rez logistics only). { 669.0f, -294.0f, 30.0f, "Stormpike GY", 0 }, { 638.5f, -31.5f, 46.0f, "Stormpike Aid Station", 0 }, - { 73.7f, -426.0f, 61.0f, "Stonehearth GY", 0 }, + { 77.8f, -404.7f, 46.9f, "Stonehearth GY", 0 }, { -202.5f, -113.0f, 78.0f, "Snowfall GY (neutral)", 0 }, { -612.5f, -397.0f, 61.0f, "Iceblood GY", 0 }, { -1082.5f, -347.0f, 55.0f, "Frostwolf GY", 0 }, @@ -130,10 +136,10 @@ public: // Alliance bunkers — priority 2 (-75 reinf on destruction). // South is the lower-X bunker (the classic map script's node // table, VMaNGOS BG_AV_Nodes against its banner spawns). - { 556.0f, -84.0f, 52.0f, "Dun Baldar South Bunker", 2 }, - { 678.0f, -139.0f, 64.0f, "Dun Baldar North Bunker", 2 }, + { 553.8f, -78.7f, 51.9f, "Dun Baldar South Bunker", 2 }, + { 674.0f, -143.1f, 63.7f, "Dun Baldar North Bunker", 2 }, { 203.0f, -361.0f, 56.0f, "Icewing Bunker", 2 }, - { -154.0f, -446.0f, 45.0f, "Stonehearth Bunker", 2 }, + { -152.4f, -441.6f, 40.4f, "Stonehearth Bunker", 2 }, // Horde towers — priority 2. // Labels corrected (BG audit §2): the DB captain garrisons prove // the names were reversed — Commander Dardosh (13140) garrisons diff --git a/src/modules/PlayerbotV2/Bot/BotAI.cpp b/src/modules/PlayerbotV2/Bot/BotAI.cpp index faccf204bf..859f04f21c 100644 --- a/src/modules/PlayerbotV2/Bot/BotAI.cpp +++ b/src/modules/PlayerbotV2/Bot/BotAI.cpp @@ -1,5 +1,7 @@ #include "BotAI.h" #include "TownLife.h" +#include "Fleet/GateDuels.h" +#include "Fleet/BotPool.h" // Pool::IsScenarioBot - a test character trades with nobody #include "BotSnapshotView.h" #include "TradeRule.h" #include "BotTrade.h" @@ -288,18 +290,20 @@ void BotAI::tick(BotSnapshotView snapshot, // on false→true transition; clear on true→false. Ships pass // through this latch too — harmless since the exit rule gates // on metadata kind, not raw Z. - // Normalise newly-summoned pets to defensive. Aggressive mode (the + // Normalise newly-summoned pets to passive. Aggressive mode (the // server default for hunter pets) makes the pet pull every mob in // its 25y leash radius — breaking CC, dragging adds onto the group, - // chasing respawns out of LoS — all things that actively hinder - // bot progress. Detect any pet-guid transition (Empty→guid or - // guid→different-guid) and fire one PetSetReactStateIntent{1}. + // chasing respawns out of LoS — and defensive still lets it open on + // whatever touches it or its owner. A bot pet only fights what the + // bot orders it onto (State_InCombat's pet_attack on the bot's own + // victim). Detect any pet-guid transition (Empty→guid or + // guid→different-guid) and fire one PetSetReactStateIntent{0}. // The intent is GCD-free so it doesn't compete with combat casts. { const ObjectGuid cur_pet = snapshot.pet_guid(); if (!cur_pet.IsEmpty() && cur_pet != last_known_pet_guid_) { - emit.pet_set_react_state(1); // REACT_DEFENSIVE + emit.pet_set_react_state(0); // REACT_PASSIVE } last_known_pet_guid_ = cur_pet; } @@ -705,7 +709,9 @@ void BotAI::update_dungeon_autopilot_hold(BotSnapshotView s, GroupSnapshotView g human_lead_hold_ = lead_hold; TC_LOG_INFO("playerbot.v2", "[dungeon_flow] {} {} the dungeon autopilot on map {}: {}", s.name(), lead_hold ? "suspends" : "resumes", s.map_id(), - lead_hold ? "a human leads (follows him, advances/pulls on his orders)" : "order / fight window or no human near"); + lead_hold ? "a human leads (follows him, advances/pulls on his orders)" + : !s.is_in_dungeon() ? "left the dungeon (the autopilot runs only inside one)" + : "order / fight window or no human near"); } } @@ -784,9 +790,12 @@ void BotAI::dispatch_layers(BotSnapshotView s, GroupSnapshotView g, const int32 diff = int32(s.level()) - int32(s.duel_initiator_level()); const uint32 h = ((uint32(s.bot_id()) + 1u) * 2654435761u) ^ (uint32(s.duel_initiator().GetCounter()) * 2246822519u) ^ ((now_ms / 60000u) * 3266489917u); - const bool close = diff >= -5 && diff <= 5; + // Playerbot.World.GateDuels.Enable: a player who wants a duel gets one from any idle bot within 10 levels (the + // nostalgic duel outside the gate); otherwise about one time in three within 5. + const bool gate_duels = Services::Config().gate_duels_enable(); + const bool close = gate_duels ? V2::GateDuels::PlayerDuelOk(s.level(), s.duel_initiator_level()) : (diff >= -5 && diff <= 5); const bool fit = s.hp_pct() >= 70 && !s.in_combat() && s.is_alive() && !s.is_moving(); - if (close && fit && ((h >> 9) % 3u) == 0u) + if (close && fit && (gate_duels || ((h >> 9) % 3u) == 0u)) { em.duel_accept(); em.say_world("alright, you're on"); @@ -814,7 +823,12 @@ void BotAI::dispatch_layers(BotSnapshotView s, GroupSnapshotView g, // Trades opened on the bot are likewise declined automatically. Window // stays open server-side until either side cancels — without this the // bot would sit there with the dialog up indefinitely. - if (s.has_trade_request() && + if (s.has_trade_request() && ::Playerbot::Pool::IsScenarioBot(s.bot_id())) + { + // A scenario test character (the scorecard raids in Tier 3 test gear) never buys, sells or takes a gift: cancelled at once. + em.trade_decline(); + } + else if (s.has_trade_request() && AcceptsTradeFrom(Services::Config().behavior_accept_owner_trade(), s.trade_partner_is_real(), !s.raw().owner_guid.IsEmpty() && s.raw().social_events.trade_partner_guid == s.raw().owner_guid, s.raw().social_events.trade_partner_in_my_group)) diff --git a/src/modules/PlayerbotV2/Bot/BotAI.h b/src/modules/PlayerbotV2/Bot/BotAI.h index 88636e4429..e2cc02cf4a 100644 --- a/src/modules/PlayerbotV2/Bot/BotAI.h +++ b/src/modules/PlayerbotV2/Bot/BotAI.h @@ -8,6 +8,7 @@ #include "IdleWatch.h" #include "WalkOrder.h" +#include "TownErrand.h" #include "Travel/ReachMemory.h" #include "BotTypes.h" #include "Util/AtomicSharedPtr.h" @@ -465,6 +466,11 @@ public: uint32 pending_equip_upgrade_at_ms() const { return pending_equip_upgrade_at_ms_; } void set_pending_equip_upgrade_at_ms(uint32 v) { pending_equip_upgrade_at_ms_ = v; } + // The resistance school (SpellSchools value) of the raid gear this bot was last ordered to wear, 0 = its own gear. While set, the + // equip-upgrade rule leaves the worn pieces alone (it would put the better scoring own piece straight back). + uint8 resist_gear_school() const { return resist_gear_school_; } + void set_resist_gear_school(uint8 v) { resist_gear_school_ = v; } + // Mailbox-open hesitation slot. uint32 pending_mail_open_at_ms() const { return pending_mail_open_at_ms_; } void set_pending_mail_open_at_ms(uint32 v) { pending_mail_open_at_ms_ = v; } @@ -532,6 +538,14 @@ public: // Toggled via /aoe whisper. bool aoe_preference() const { return aoe_preference_; } void set_aoe_preference(bool b) { aoe_preference_ = b; } + // Owner "aoe off" (AoeDeny.h): no spell that hits more than one enemy until "aoe on". Mirrored into the snapshot. + bool aoe_denied() const { return aoe_denied_; } + void set_aoe_denied(bool b) { aoe_denied_ = b; } + + // The owner's spell picks for this bot ("prefer blessing might", "pet off", "stealth off"; OwnerPicks.h). Memory only: a relog + // clears them. Written by the whisper handler (world thread), mirrored into the snapshot and the group member summary. + OwnerPicks::Picks const& owner_picks() const { return owner_picks_; } + OwnerPicks::Picks& owner_picks() { return owner_picks_; } // Battle-rez dedup state. brez_target_ is the GUID of the dead member // we last fired Rebirth (Druid) / Raise Ally (DK) / Soulstone (Warlock) @@ -2229,6 +2243,8 @@ public: uint32 last_wander_diag_ms() const { return last_wander_diag_ms_; } ::Playerbot::V2::IdleWatch& idle_watch() { return idle_watch_; } ::Playerbot::V2::WalkOrder& walk_order() { return walk_order_; } // the spawner's arrive / leave request (WalkOrder.h) + ::Playerbot::V2::TownErrand::State& town_errand() { return town_errand_; } + ::Playerbot::V2::GoalProgress& goal_progress() { return goal_progress_; } // idle:pursue_quest_goal, closing in on the goal (IdleWatch.h) // idle:town_errand, a capital resident's next place (TownErrand.h) ::Playerbot::BgTactics::StallWatch& bg_stall() { return bg_stall_; } void set_last_wander_diag_ms(uint32 ms) { last_wander_diag_ms_ = ms; } @@ -2675,6 +2691,9 @@ public: // object's guid_low (bit 41 set). Companion quest help // (idle:companion_quest_*): 15s between attempts on the same quest / object. CompanionQuestShare = 56, // target = 0 (per bot). One auto-share pass per 90s. + BgFormHold = 57, // target = 0. A bot clicking a battleground flag / banner: no druid shapeshift cast + // for 6s (the click leaves the form; the rotation shifted straight back in). + AlwaysBuff = 58, // target = kAlwaysBuffLockKey. idle:always_buff (Playerbot.AlwaysBuffs): 10s between passes. }; static constexpr uint32 kActionRetryLockoutMs = 5u * 60u * 1000u; // Per-kind cooldown override — most actions use the 5 min default, but @@ -2803,6 +2822,14 @@ public: case ActionKind::DruidFormEntered: // A buff that can't land must not flip the form every tick. return 10u * 1000u; + case ActionKind::BgFormHold: + // Past the 3 s BgUseGo retry, so the second click lands out of form. + return 6u * 1000u; + case ActionKind::AlwaysBuff: + // The gate fires only when an aura is out of step with where the bot stands, so a short pace is enough. It shared the + // potion's 5 min lockout once: a bot that got its gold floor in the world and joined a raid group a few seconds later + // could not take its flask for 5 minutes (support scorecard on 230: no flask on any of ten bots for the whole run). + return 10u * 1000u; case ActionKind::CompanionQuest: // A refused accept / turn-in / click (bags full, out of range) retries at human pace. return 15u * 1000u; @@ -2899,6 +2926,7 @@ public: // without this the 6s / 10s leave / re-enter windows were no-ops. case ActionKind::DruidFormLeft: case ActionKind::DruidFormEntered: + case ActionKind::BgFormHold: case ActionKind::CompanionQuestShare: return true; default: @@ -3228,10 +3256,19 @@ public: { uint32 idle_since_ms = 0; uint32 logged_ms = 0; + // Idle watchdog ([idle_reposition]): where the bot stood when the streak began or the watchdog last fired, and when. A bot that has + // moved on from there is walking somewhere; one still within a few yards of it after 3 s is stuck and is sent to a spot. + float anchor_x = 0.f; + float anchor_y = 0.f; + uint32 anchor_ms = 0; }; CombatIdleState& combat_idle() { return combat_idle_; } + // Game time of the last damage this bot itself dealt (world thread writes from the damage hook, the bot worker reads); 0 = none yet. + void note_damage_done(uint32 now_ms) { last_damage_done_ms_.store(now_ms ? now_ms : 1u, std::memory_order_relaxed); } + uint32 last_damage_done_ms() const { return last_damage_done_ms_.load(std::memory_order_relaxed); } private: CombatIdleState combat_idle_; + std::atomic last_damage_done_ms_{0}; // [cast_fail] window (world thread only; see note_cast_outcome). struct CastFailWindow @@ -3394,6 +3431,7 @@ private: // Slot resets when the rule isn't gating (in combat / dungeon / // BG), so a fresh upgrade after exit gets a fresh window. uint32 pending_equip_upgrade_at_ms_ = 0; + uint8 resist_gear_school_ = 0; // Mailbox-open hesitation: real humans click the mailbox, see the // list, hover one row, click "Take All". 1.5–4s before the first // take packet lands. Reset when the bot walks out of mailbox range. @@ -3415,6 +3453,8 @@ private: ObjectGuid last_trained_trainer_; uint8 last_train_level_ = 0; bool aoe_preference_ = false; + bool aoe_denied_ = false; + OwnerPicks::Picks owner_picks_; // Owner-squad-control state (Phase C of OWNER_SQUAD_CONTROL_PLAN.md). // The owner's orders to this bot, all in one place. Written by the chat handlers (world thread), read by the bot worker. struct OwnerOrders @@ -3699,6 +3739,9 @@ public: void set_cached_spellmap_size(size_t v) { cached_spellmap_size_ = v; } std::vector const& cached_known_spells() const { return cached_known_spells_; } std::vector& mutable_cached_known_spells() { return cached_known_spells_; } + // The known spells' range modifiers (SpellbookState::range_bonus), rebuilt with the known-spell cache: talents change both. + std::vector> const& cached_range_bonus() const { return cached_range_bonus_; } + std::vector>& mutable_cached_range_bonus() { return cached_range_bonus_; } // Best-mount-spell cache (perf 0.2). The Builder used to walk the whole // SpellMap, fetch SpellInfo, and iterate every effect's ApplyAuraName to @@ -3785,6 +3828,7 @@ private: std::vector cached_recipes_; std::vector cached_self_teleports_; std::vector cached_known_spells_; + std::vector> cached_range_bonus_; uint32 last_reputation_scan_ms_ = 0; uint32 last_skills_scan_ms_ = 0; uint32 last_spellcache_scan_ms_ = 0; @@ -4122,6 +4166,8 @@ private: ::Playerbot::BgTactics::StallWatch bg_stall_; // battleground stand-still watchdog (State_Idle bg_stall) ::Playerbot::V2::WalkOrder walk_order_; ::Playerbot::V2::IdleWatch idle_watch_; // world-wide standing-still detector (DispatchIdle) + ::Playerbot::V2::TownErrand::State town_errand_; + ::Playerbot::V2::GoalProgress goal_progress_; // idle:town_errand (Bot/States/Rules/AmbientRules.cpp) // Cached corpse → graveyard distance. Recomputing every snapshot tick // walks `WorldSafeLocsEntry` against `sConditionMgr` for every nearby // graveyard, evaluating per-graveyard team / faction / level conditions. @@ -4362,6 +4408,14 @@ public: // yanking a ranged DPS that is merely between casts (briefly out of combat // but in range / actively repositioning); a genuinely stranded bot stays // out of combat for the whole window and trips it. + // Healer-sight clock (State_InCombat [tank_sight]): how long a 5-man tank's healer has been unable to see it from another + // floor, 0 while a healer sees it. + uint32 healer_sight_lost_ms(bool lost_now, uint32 now_ms) + { + if (!lost_now) { healer_sight_lost_since_ms_ = 0; return 0; } + if (healer_sight_lost_since_ms_ == 0) healer_sight_lost_since_ms_ = now_ms ? now_ms : 1u; + return now_ms - healer_sight_lost_since_ms_; + } uint32 combat_join_stuck_ms(bool stuck_now, uint32 now_ms) { // A gap of a second or two (the tank's victim blinking empty between swings, a cast starting, the bot flickering @@ -4579,7 +4633,12 @@ public: void set_travel_plan(std::vector legs, uint64 goal_key) { travel_plan_ = std::move(legs); travel_plan_leg_ = 0; travel_plan_goal_ = goal_key; } void advance_travel_leg() { if (travel_plan_leg_ < travel_plan_.size()) ++travel_plan_leg_; } - void clear_travel_plan() { travel_plan_.clear(); travel_plan_leg_ = 0; travel_plan_goal_ = 0; } + void clear_travel_plan() { travel_plan_.clear(); travel_plan_leg_ = 0; travel_plan_goal_ = 0; transport_wait_since_ms_ = 0; } + // When the bot began waiting on a dock for a same-map ride (0 = not waiting) and when it last logged it. + uint32 transport_wait_since_ms() const { return transport_wait_since_ms_; } + void set_transport_wait_since_ms(uint32 ms) { transport_wait_since_ms_ = ms; } + uint32 transport_wait_logged_ms() const { return transport_wait_logged_ms_; } + void set_transport_wait_logged_ms(uint32 ms) { transport_wait_logged_ms_ = ms; } // Leg-skip rate-limit (harbor fix): when anchor-wedged on an unreachable // WALK leg, the bot advances to the next leg instead of replanning the same // bad route. The anchor-wedge cooldown returns "wedged" every tick for 30s, @@ -4926,13 +4985,13 @@ public: { pet_summon_backoff_until_ms_ = 0; } // Last pet_guid we observed. Tick() compares against the live - // snapshot and emits a PetSetReactStateIntent{1} (defensive) on + // snapshot and emits a PetSetReactStateIntent{0} (passive) on // any empty→non-empty or guid-change transition — keeps every - // newly-summoned pet in defensive instead of the server default - // (aggressive for hunter pets, defensive for warlock pets, but - // we normalise to defensive across the board because aggressive - // mode actively hinders bot progress: pets pull mobs the group - // wasn't ready for, break CC, chase respawns out of LoS). + // newly-summoned pet passive instead of the server default + // (aggressive for hunter pets, defensive for warlock pets): a bot + // pet attacks only the target its bot orders it onto, so it never + // pulls mobs the group wasn't ready for, breaks CC, or chases + // respawns out of LoS). ObjectGuid last_known_pet_guid() const { return last_known_pet_guid_; } void set_last_known_pet_guid(ObjectGuid g) { last_known_pet_guid_ = g; } private: @@ -5158,6 +5217,8 @@ private: // L2/L3 cached travel plan (see PlanLeg + accessors above). std::vector travel_plan_{}; size_t travel_plan_leg_ = 0; + uint32 transport_wait_since_ms_ = 0; + uint32 transport_wait_logged_ms_ = 0; uint64 travel_plan_goal_ = 0; uint32 last_leg_skip_ms_ = 0; // leg-skip rate-limit (see accessor) // Oscillation leash backing (see note_position_leash). Goal-agnostic, so it @@ -5183,6 +5244,7 @@ private: // the time that best stopped improving. See regroup_stuck_ms above. uint32 regroup_stuck_since_ms_ = 0; float regroup_stuck_best_ = 0.f; + uint32 healer_sight_lost_since_ms_ = 0; // see healer_sight_lost_ms // Own-position frozen clock: the bot's last sampled pose + when it last // moved >3y from it. See frozen_ms above (rally-independent strand timer). uint32 frozen_since_ms_ = 0; @@ -5250,24 +5312,11 @@ private: uint8 strikes = 0; }; std::array bad_goals_{}; + uint32 hub_walk_id_ = 0, hub_walk_since_ms_ = 0, hub_walk_seen_ms_ = 0; + float hub_walk_x_ = 0.f, hub_walk_y_ = 0.f; uint32 anchor_seen_ms_ = 0, anchor_move_ms_ = 0; float anchor_x_ = 0.f, anchor_y_ = 0.f; public: - // Whether the follow anchor (leader or owner) has moved in the last second, seen from successive ticks. A follower that waits for the - // full recall slack (13-15 yd for a caster) before it starts runs 2-4 s behind a leader who sets off; while he moves it starts at the - // follow distance instead. - bool anchor_moving(float x, float y, uint32 now_ms) - { - if (anchor_seen_ms_ == 0 || now_ms - anchor_seen_ms_ > 3000u) - { - anchor_x_ = x; anchor_y_ = y; anchor_seen_ms_ = now_ms; anchor_move_ms_ = 0; - return false; - } - const float dx = x - anchor_x_, dy = y - anchor_y_; - if (dx * dx + dy * dy > 1.0f) { anchor_move_ms_ = now_ms; anchor_x_ = x; anchor_y_ = y; } - anchor_seen_ms_ = now_ms; - return anchor_move_ms_ != 0 && now_ms - anchor_move_ms_ < 1000u; - } void note_path_blocked(uint32 now_ms) { ++path_blocked_count_; @@ -5432,6 +5481,38 @@ public: slot->until_ms = now_ms + kBackoffMs[slot->strikes - 1]; if (slot->until_ms == 0) slot->until_ms = 1; } + // The hub walk (idle:travel_to_hub) that goes nowhere: the same hub asked for, the bot not 10 yd from where it started, for 40 s. + // The move is dropped inside the API (no motion, a failed path) and the rule kept choosing the same hub every tick, so the bot + // never reached its wander; the caller marks the hub tried and the goal bad when this says true. + bool hub_walk_stalled(uint32 hub_id, float bx, float by, uint32 now_ms) + { + constexpr uint32 kStallMs = 40000u, kGapMs = 5000u; + if (hub_walk_id_ != hub_id || hub_walk_seen_ms_ == 0 || now_ms - hub_walk_seen_ms_ > kGapMs) + { + hub_walk_id_ = hub_id; hub_walk_since_ms_ = now_ms; hub_walk_x_ = bx; hub_walk_y_ = by; + } + hub_walk_seen_ms_ = now_ms; + const float dx = bx - hub_walk_x_, dy = by - hub_walk_y_; + if (dx * dx + dy * dy >= 10.0f * 10.0f) { hub_walk_since_ms_ = now_ms; hub_walk_x_ = bx; hub_walk_y_ = by; return false; } + if (now_ms - hub_walk_since_ms_ < kStallMs) return false; + hub_walk_id_ = 0; hub_walk_seen_ms_ = 0; + return true; + } + // Whether the follow anchor (leader or owner) has moved in the last second, seen from successive ticks. A follower that waits for the + // full recall slack (13-15 yd for a caster) before it starts runs 2-4 s behind a leader who sets off; while he moves it starts at the + // follow distance instead. + bool anchor_moving(float x, float y, uint32 now_ms) + { + if (anchor_seen_ms_ == 0 || now_ms - anchor_seen_ms_ > 3000u) + { + anchor_x_ = x; anchor_y_ = y; anchor_seen_ms_ = now_ms; anchor_move_ms_ = 0; + return false; + } + const float dx = x - anchor_x_, dy = y - anchor_y_; + if (dx * dx + dy * dy > 1.0f) { anchor_move_ms_ = now_ms; anchor_x_ = x; anchor_y_ = y; } + anchor_seen_ms_ = now_ms; + return anchor_move_ms_ != 0 && now_ms - anchor_move_ms_ < 1000u; + } bool quest_recently_shared(uint32 q) const { for (uint32 e : shared_ring_) if (e == q) return true; diff --git a/src/modules/PlayerbotV2/Bot/BotChatModel.cpp b/src/modules/PlayerbotV2/Bot/BotChatModel.cpp new file mode 100644 index 0000000000..d844129e1f --- /dev/null +++ b/src/modules/PlayerbotV2/Bot/BotChatModel.cpp @@ -0,0 +1,553 @@ +// BotChatModel - see header. + +#include "BotChatModel.h" +#include "BotChatModelClient.h" +#include "BotConversation.h" +#include "BotIntent.h" +#include "../Services.h" +#include "../Threading/IntentQueue.h" +#include "../Util/ConfigReader.h" + +#include "Log.h" +#include "GameTime.h" +#include "Player.h" +#include "Util.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Playerbot { + +namespace { + +using Clock = std::chrono::steady_clock; + +struct Job +{ + BotId bot = 0; + std::string bot_name; + std::string sender_name; + BotChatModel::Channel channel = BotChatModel::Channel::Whisper; + uint64 history_key = 0; + std::string question; + ChatModel::Settings settings; + std::vector messages; + Clock::time_point asked; + uint32 max_wait_ms = 30000; + uint32 extra_delay_ms = 0; +}; + +struct Done +{ + BotId bot = 0; + std::string bot_name; + std::string sender_name; + BotChatModel::Channel channel = BotChatModel::Channel::Whisper; + uint64 history_key = 0; + std::string question; + std::string answer; + uint32 took_ms = 0; + uint32 extra_delay_ms = 0; +}; + +// Shared between the world thread and the worker, under g_mtx. +std::mutex g_mtx; +std::condition_variable g_cv; +std::deque g_jobs; +std::vector g_done; +bool g_stop = false; +ChatModel::Client* g_client = nullptr; // the worker's client while it runs (for Cancel) +std::thread g_worker; + +// After a failed request the model counts as down for a minute: Ask declines, so bots give their usual replies meanwhile +// instead of going quiet. Written by the worker, read by the world thread (steady_clock ticks). +std::atomic g_down_until{0}; +constexpr std::chrono::seconds kDownFor{60}; + +// World thread only. +struct History +{ + std::deque lines; // oldest first, always starting with the player's line + Clock::time_point last; // the last exchange +}; +std::unordered_map g_history; // (bot << 32 | sender) -> the conversation so far +std::unordered_map g_last_ask; +std::deque g_minute; // asks in the last 60 s +std::deque g_say_minute; // AskSay asks in the last 60 s (their own cap) +std::unordered_map>> g_said; // AskSay key -> lines said, not yet taken + +ChatModel::Settings SettingsFrom(ConfigReader::ChatModelConfig const& cfg) +{ + ChatModel::Settings s; + s.host = cfg.host; + s.port = uint16(cfg.port); + s.model = cfg.model; + s.timeout_ms = cfg.timeout_ms; + s.max_tokens = cfg.max_tokens; + s.temperature = cfg.temperature; + s.keep_alive = cfg.keep_alive; + s.context_length = cfg.context_length; + return s; +} + +// World thread only: the model (host:port/model) the last warm-up was sent for. +std::string g_warmed; + +bool IsDown() +{ + return Clock::now().time_since_epoch().count() < g_down_until.load(); +} + +uint32 MsSince(Clock::time_point t) +{ + return uint32(std::chrono::duration_cast(Clock::now() - t).count()); +} + +void WorkerLoop() +{ + ChatModel::Client client; + { + std::lock_guard lk(g_mtx); + g_client = &client; + } + Clock::time_point last_warn{}; + uint32 failures_since_warn = 0; + for (;;) + { + Job job; + { + std::unique_lock lk(g_mtx); + g_cv.wait(lk, [] { return g_stop || !g_jobs.empty(); }); + if (g_stop) + break; + job = std::move(g_jobs.front()); + g_jobs.pop_front(); + } + // Waited too long in the queue: the moment has passed. + if (MsSince(job.asked) > job.max_wait_ms) + continue; + + Clock::time_point const start = Clock::now(); + std::string raw, error; + bool const ok = client.Chat(job.settings, job.messages, raw, error); + { + std::lock_guard lk(g_mtx); + if (g_stop) + break; + } + if (job.bot == 0) // warm-up: only loads the model + { + if (ok) + TC_LOG_INFO("server.worldserver", "[PlayerbotV2] Chat model {} loaded and ready ({} ms).", job.settings.model, MsSince(start)); + } + if (!ok) + { + // Ollama not running or the model not pulled is the usual cause: say so, at most once a minute. + g_down_until = (Clock::now() + kDownFor).time_since_epoch().count(); + ++failures_since_warn; + if (last_warn == Clock::time_point{} || MsSince(last_warn) > 60000) + { + TC_LOG_WARN("server.worldserver", "[PlayerbotV2] Chat model request to {}:{} ({}) failed: {} ({} failure(s) since the last warning)." + " Is Ollama running, and has the model been pulled? Bots use their usual replies for a minute.", job.settings.host, job.settings.port, job.settings.model, error, + failures_since_warn); + last_warn = Clock::now(); + failures_since_warn = 0; + } + continue; + } + if (job.bot == 0) + continue; + std::string answer = ChatModel::CleanReply(raw, job.bot_name); + if (answer.empty()) + { + TC_LOG_INFO("playerbot.v2", "[conv] {} <- {}: chat model reply unusable: \"{}\"", job.bot_name, job.sender_name, raw); + continue; + } + Done d; + d.bot = job.bot; + d.bot_name = std::move(job.bot_name); + d.sender_name = std::move(job.sender_name); + d.channel = job.channel; + d.history_key = job.history_key; + d.question = std::move(job.question); + d.answer = std::move(answer); + d.took_ms = MsSince(start); + d.extra_delay_ms = job.extra_delay_ms; + std::lock_guard lk(g_mtx); + // Too late to answer (asked > MaxWaitMs ago): drop it rather than reply to a conversation that moved on. + if (MsSince(job.asked) > job.max_wait_ms) + continue; + g_done.push_back(std::move(d)); + } + std::lock_guard lk(g_mtx); + g_client = nullptr; +} + +char const* RaceName(uint8 race) +{ + static constexpr char const* kRace[] = { "", "human", "orc", "dwarf", "night elf", "undead", "tauren", "gnome", "troll", + "goblin", "blood elf", "draenei" }; + return race < sizeof(kRace) / sizeof(kRace[0]) && kRace[race][0] ? kRace[race] : ""; +} + +// True when most letters in `msg` are Cyrillic (UTF-8 lead bytes 0xD0 / 0xD1: U+0400-U+047F). +bool IsMostlyCyrillic(std::string const& msg) +{ + std::size_t cyrillic = 0, latin = 0; + for (std::size_t i = 0; i < msg.size(); ++i) + { + unsigned char const b = static_cast(msg[i]); + if ((b == 0xD0 || b == 0xD1) && i + 1 < msg.size()) + { + ++cyrillic; + ++i; + } + else if (std::isalpha(b)) + ++latin; + } + return cyrillic > 0 && cyrillic >= latin; +} + +// The language line. "auto": the player's language - named outright for Cyrillic (small models answer an English prompt in +// English unless told), otherwise "the same language". Any other setting ("Russian", "German", ...) is used as given. +std::string LanguageLine(std::string const& setting, std::string const& msg) +{ + if (setting.empty() || setting == "auto" || setting == "Auto") + return IsMostlyCyrillic(msg) ? " Reply in Russian." : " Reply in the same language the player wrote in."; + return " Always reply in " + setting + "."; +} + +std::string BuildSystemPrompt(Player* bot, V2::ConversationContext const& ctx, BotChatModel::Channel channel, + std::string const& language, std::string const& msg, std::string const& extra, bool date) +{ + std::string p = "You are " + ctx.self_name + ", a level " + std::to_string(ctx.level); + if (char const* race = RaceName(bot->GetRace()); *race) + p += std::string(" ") + race; + p += " " + (ctx.class_name.empty() ? std::string("adventurer") : ctx.class_name); + p += " playing World of Warcraft Classic (the original 2004 Azeroth, levels 1-60)."; + if (!ctx.zone.empty()) + p += " You are in " + ctx.zone + "."; + if (!ctx.activity.empty()) + p += " Right now you are " + ctx.activity + "."; + if (!ctx.quest_title.empty()) + p += " One quest in your log is \"" + ctx.quest_title + "\"."; + if (!ctx.guild_name.empty()) + p += " Your guild is <" + ctx.guild_name + ">."; + if (!ctx.professions.empty()) + { + p += " Your professions:"; + for (std::size_t i = 0; i < ctx.professions.size(); ++i) + p += (i ? ", " : " ") + ctx.professions[i]; + p += "."; + } + if (channel == BotChatModel::Channel::SayReply) + p += " " + ctx.sender_name + " is standing next to you and says something to you out loud."; + else if (channel == BotChatModel::Channel::Whisper) + p += " " + ctx.sender_name + (ctx.knows_sender ? ", who is in your group," : ", a player you don't know,") + " whispers you."; + else if (channel == BotChatModel::Channel::Raid) + p += " You are in a raid group and " + ctx.sender_name + " says something in raid chat."; + else + p += " You are in a party and " + ctx.sender_name + " says something in party chat."; + p += " Answer as a real player typing in game chat: one short line, under 20 words, casual, no emojis, no actions in" + " asterisks, no quotation marks, no name prefix. Never say you are a bot or a program. If you don't know" + " something, say so briefly rather than making it up. Don't invent quests, items or places."; + switch (ctx.tone) + { + case V2::ConvTone::Rude: p += " You are blunt and a bit grumpy."; break; + case V2::ConvTone::Polite: p += " You are friendly and polite."; break; + default: break; + } + if (ctx.length == V2::ConvLength::Terse) + p += " You type as little as possible."; + else if (ctx.length == V2::ConvLength::Chatty) + p += " You enjoy a chat."; + if (date) + { + // The server's real clock: a small model otherwise makes a date up. + tm const t = TimeBreakdown(GameTime::GetGameTime()); + char buf[96]; + if (std::strftime(buf, sizeof(buf), "%A %d %B %Y, %H:%M (%Z)", &t)) + p += std::string(" The real date and time now is ") + buf + "."; + } + p += LanguageLine(language, msg); + if (!extra.empty()) + p += " " + extra; + return p; +} + +} // namespace + +bool BotChatModel::WhispersOn() +{ + auto const& c = Services::Config().chat_model(); + return c.enable && c.whispers && !IsDown(); +} + +bool BotChatModel::PartyOn() +{ + auto const& c = Services::Config().chat_model(); + return c.enable && c.party && !IsDown(); +} + +bool BotChatModel::SayReplyOn() +{ + auto const& c = Services::Config().chat_model(); + return c.enable && c.say_reply && !IsDown(); +} + +bool BotChatModel::SayOn() +{ + return Services::Config().chat_model().enable && !IsDown(); +} + +bool BotChatModel::AskSay(Player* bot, std::string const& system, std::string const& chat, uint64 key, uint32 per_minute) +{ + auto const& cfg = Services::Config().chat_model(); + if (!cfg.enable || !bot || IsDown()) + return false; + BotId const id = bot->GetGUID().GetCounter(); + Clock::time_point const now = Clock::now(); + while (!g_say_minute.empty() && now - g_say_minute.front() >= std::chrono::seconds(60)) + g_say_minute.pop_front(); + if (g_say_minute.size() >= per_minute) + return false; + + Job job; + job.bot = id; + job.bot_name = bot->GetName(); + job.channel = Channel::Say; + job.history_key = key; + job.settings = SettingsFrom(cfg); + job.asked = now; + job.max_wait_ms = std::min(cfg.max_wait_ms, 20000u); // a late line in a talk that moved on reads wrong + job.messages.push_back({ "system", system }); + job.messages.push_back({ "user", chat.empty() ? std::string("Start the talk with one line.") + : "The talk so far:\n" + chat + "\nYour next line:" }); + { + std::lock_guard lk(g_mtx); + if (g_stop || g_jobs.size() * 2 >= cfg.max_queue) + return false; + if (!g_worker.joinable()) + { + TC_LOG_INFO("server.loading", "[PlayerbotV2] Chat model on: {} at {}:{}.", cfg.model, cfg.host, cfg.port); + g_worker = std::thread(WorkerLoop); + } + g_jobs.push_back(std::move(job)); + } + g_cv.notify_one(); + g_say_minute.push_back(now); + return true; +} + +std::vector> BotChatModel::TakeSaid(uint64 key) +{ + std::vector> out; + if (auto it = g_said.find(key); it != g_said.end()) + { + out.swap(it->second); + g_said.erase(it); + } + return out; +} + +bool BotChatModel::Ask(Player* bot, Player* sender, V2::ConversationContext const& ctx, Channel channel, std::string const& msg, + uint32 extra_delay_ms) +{ + auto const& cfg = Services::Config().chat_model(); + if (!cfg.enable || !bot || !sender || msg.empty()) + return false; + + BotId const id = bot->GetGUID().GetCounter(); + Clock::time_point const now = Clock::now(); + + if (IsDown()) + return false; + if (auto it = g_last_ask.find(id); it != g_last_ask.end() && now - it->second < std::chrono::milliseconds(cfg.bot_cooldown_ms)) + return false; + while (!g_minute.empty() && now - g_minute.front() >= std::chrono::seconds(60)) + g_minute.pop_front(); + if (g_minute.size() >= cfg.max_per_minute) + { + TC_LOG_INFO("playerbot.v2", "[conv] {} <- {}: chat model skipped (MaxPerMinute {} reached)", bot->GetName(), sender->GetName(), + cfg.max_per_minute); + return false; + } + + Job job; + job.bot = id; + job.bot_name = bot->GetName(); + job.sender_name = sender->GetName(); + job.channel = channel; + job.history_key = (uint64(id) << 32) | uint64(uint32(sender->GetGUID().GetCounter())); + job.question = msg; + job.settings = SettingsFrom(cfg); + job.asked = now; + job.max_wait_ms = cfg.max_wait_ms + extra_delay_ms; + job.extra_delay_ms = extra_delay_ms; + job.messages.push_back({ "system", BuildSystemPrompt(bot, ctx, channel, cfg.language, msg, cfg.extra_prompt, cfg.date_in_prompt) }); + // The conversation so far with this player, unless it went quiet for HistoryMinutes (a new talk starts fresh). + if (auto h = g_history.find(job.history_key); h != g_history.end()) + { + if (now - h->second.last > std::chrono::minutes(cfg.history_minutes)) + g_history.erase(h); + else + for (ChatModel::Message const& m : h->second.lines) + job.messages.push_back(m); + } + job.messages.push_back({ "user", msg }); + + { + std::lock_guard lk(g_mtx); + if (g_stop) + return false; + if (g_jobs.size() >= cfg.max_queue) + { + TC_LOG_INFO("playerbot.v2", "[conv] {} <- {}: chat model skipped (queue full, MaxQueue {})", job.bot_name, job.sender_name, + cfg.max_queue); + return false; + } + if (!g_worker.joinable()) + { + TC_LOG_INFO("server.loading", "[PlayerbotV2] Chat model on: {} at {}:{}.", cfg.model, cfg.host, cfg.port); + g_worker = std::thread(WorkerLoop); + } + g_jobs.push_back(std::move(job)); + } + g_cv.notify_one(); + + g_last_ask[id] = now; + g_minute.push_back(now); + if (g_last_ask.size() > 4096) + std::erase_if(g_last_ask, [&](auto const& kv) { return now - kv.second > std::chrono::minutes(10); }); + return true; +} + +void BotChatModel::WarmUp() +{ + auto const& cfg = Services::Config().chat_model(); + if (!cfg.enable) + return; + std::string const which = cfg.host + ":" + std::to_string(cfg.port) + "/" + cfg.model; + if (which == g_warmed) + return; + g_warmed = which; + + Job job; + job.settings = SettingsFrom(cfg); + // A cold load reads the whole model from disk; give it more than a normal reply. + job.settings.timeout_ms = std::max(cfg.timeout_ms, 120000u); + job.settings.max_tokens = 1; + job.asked = Clock::now(); + job.max_wait_ms = 300000u; + job.messages.push_back({ "user", "hi" }); + { + std::lock_guard lk(g_mtx); + if (g_stop) + return; + if (!g_worker.joinable()) + { + TC_LOG_INFO("server.loading", "[PlayerbotV2] Chat model on: {} at {}:{}; loading it now.", cfg.model, cfg.host, cfg.port); + g_worker = std::thread(WorkerLoop); + } + g_jobs.push_front(std::move(job)); + } + g_cv.notify_one(); +} + +void BotChatModel::DeliverReplies(uint32 now_ms) +{ + WarmUp(); + std::vector done; + { + std::lock_guard lk(g_mtx); + if (g_done.empty()) + return; + done.swap(g_done); + } + uint32 const history_lines = Services::Config().chat_model().history_lines; + for (Done& d : done) + { + if (!Services::HasIntents(d.bot)) // logged out meanwhile + continue; + if (d.channel == Channel::Say) + { + TC_LOG_INFO("playerbot.v2", "[gathering] {} says (chat model, {} ms): \"{}\"", d.bot_name, d.took_ms, d.answer); + if (g_said.size() > 256) + g_said.clear(); + g_said[d.history_key].emplace_back(d.bot_name, d.answer); + uint32 const typing_ms = std::min(uint32(d.answer.size()) * 30u, 2500u); + Intent it{}; + it.bot_id = d.bot; + it.body = ChatIntent{SayChatIntent{std::move(d.answer)}}; + it.defer_until_ms = now_ms + typing_ms; + Services::Intents(d.bot).push(std::move(it)); + continue; + } + std::string const target = d.channel == Channel::Whisper ? "whisper to " + d.sender_name + : d.channel == Channel::Party ? std::string("party chat") + : d.channel == Channel::Raid ? std::string("raid chat") + : std::string("/say"); + TC_LOG_INFO("playerbot.v2", "[conv] {} <- {} \"{}\": chat model ({} ms) -> {}: \"{}\"", d.bot_name, d.sender_name, d.question, + d.took_ms, target, d.answer); + + if (history_lines > 0) + { + if (g_history.size() > 2048 && !g_history.contains(d.history_key)) + g_history.clear(); + History& h = g_history[d.history_key]; + // A long player line is kept cut short: the history stays a few hundred tokens inside ContextLength. + h.lines.push_back({ "user", d.question.size() > 300 ? d.question.substr(0, 300) : d.question }); + h.lines.push_back({ "assistant", d.answer }); + h.last = Clock::now(); + while (h.lines.size() > history_lines || (!h.lines.empty() && h.lines.front().role != "user")) + h.lines.pop_front(); + } + + // The model already took its time; add a short "typing" pause so a long line doesn't appear instantly. + uint32 const typing_ms = std::min(uint32(d.answer.size()) * 30u, 2500u); + Intent it{}; + it.bot_id = d.bot; + if (d.channel == Channel::Whisper) + it.body = ChatIntent{WhisperIntent{std::move(d.sender_name), std::move(d.answer)}}; + else if (d.channel == Channel::Raid) + it.body = ChatIntent{RaidChatIntent{std::move(d.answer)}}; + else if (d.channel == Channel::Party) + it.body = ChatIntent{PartyChatIntent{std::move(d.answer)}}; + else + it.body = ChatIntent{SayChatIntent{std::move(d.answer)}}; + it.defer_until_ms = now_ms + typing_ms + d.extra_delay_ms; + Services::Intents(d.bot).push(std::move(it)); + } +} + +void BotChatModel::Shutdown() +{ + { + std::lock_guard lk(g_mtx); + g_stop = true; + if (g_client) + g_client->Cancel(); + g_jobs.clear(); + g_done.clear(); + } + g_cv.notify_all(); + if (g_worker.joinable()) + g_worker.join(); + g_history.clear(); + g_last_ask.clear(); + g_minute.clear(); + g_say_minute.clear(); + g_said.clear(); +} + +} // namespace Playerbot diff --git a/src/modules/PlayerbotV2/Bot/BotChatModel.h b/src/modules/PlayerbotV2/Bot/BotChatModel.h new file mode 100644 index 0000000000..5b84ae1f69 --- /dev/null +++ b/src/modules/PlayerbotV2/Bot/BotChatModel.h @@ -0,0 +1,65 @@ +// BotChatModel - optional chat-model replies for bots (Playerbot.ChatModel.*, off by default). +// +// With Playerbot.ChatModel.Enable = 1, a whisper to a bot and party chat with a bot are answered by a local Ollama server +// instead of the keyword pools. The world thread only builds the prompt and queues it (Ask); one worker thread sends the +// requests, one at a time, and parks finished replies; DeliverReplies (world thread, every update) hands them to the bots' +// intent queues as WhisperIntent / PartyChatIntent. Nothing here ever waits on the network from the world thread. +// +// Limits: a per-bot cooldown, a realm-wide cap per minute and a short queue (Ask returns false when any of them is hit, and +// the caller falls back to its usual reply). After a failed request (Ollama not running, model missing, timeout) Ask declines +// for a minute, so bots keep talking the usual way. A reply that arrives after Playerbot.ChatModel.MaxWaitMs is dropped. Each bot +// remembers the last few lines with each player (HistoryLines) so a conversation can follow on. + +#pragma once + +#include "BotTypes.h" + +#include +#include +#include + +class Player; + +namespace Playerbot { + +namespace V2 { struct ConversationContext; } + +class BotChatModel +{ +public: + // Say: a bot-to-bot gathering line (AskSay). SayReply: a bot answering a player's /say that addressed it. Each answer + // goes out on the channel it was asked on (whisper, party, raid, /say). + enum class Channel : uint8 { Whisper, Party, Say, SayReply, Raid }; + + // On in the config, and not resting after a failed request. + static bool WhispersOn(); + static bool PartyOn(); + static bool SayReplyOn(); + + // World thread. Queues `msg` from `sender` for `bot` to answer on `channel`; `ctx` describes the bot (BotChatReactor's + // MakeConvContext). False when the request was not queued (off, cooling down, over the cap, queue full). + // `extra_delay_ms` holds the answer back that much longer (a second bot chiming in after the first). + static bool Ask(Player* bot, Player* sender, V2::ConversationContext const& ctx, Channel channel, std::string const& msg, + uint32 extra_delay_ms = 0); + + // World thread. A /say line for a bot talking with other bots (the gate gatherings, Fleet/Gathering.h): `system` sets the scene, + // `chat` is the talk so far as "Name: line" rows (empty: the bot opens it). Under its own `per_minute` cap, and only while the + // queue is at most half full so a player's whisper always has room. The reply is said in /say and kept for TakeSaid(`key`). + static bool AskSay(Player* bot, std::string const& system, std::string const& chat, uint64 key, uint32 per_minute); + // World thread. The lines said for `key` since the last call (name, line), oldest first. + static std::vector> TakeSaid(uint64 key); + // On in the config and not resting after a failed request. + static bool SayOn(); + + // World thread (from DeliverReplies): once chat is on, and again when the model, host or port changes, sends a one-token + // request so Ollama loads the model before the first player line instead of during it. + static void WarmUp(); + + // World thread, from Module::OnWorldUpdate. + static void DeliverReplies(uint32 now_ms); + + // Stops the worker (cancels a request in flight). From Module::Shutdown. + static void Shutdown(); +}; + +} // namespace Playerbot diff --git a/src/modules/PlayerbotV2/Bot/BotChatModelClient.cpp b/src/modules/PlayerbotV2/Bot/BotChatModelClient.cpp new file mode 100644 index 0000000000..2331b3451d --- /dev/null +++ b/src/modules/PlayerbotV2/Bot/BotChatModelClient.cpp @@ -0,0 +1,305 @@ +// BotChatModelClient - see header. + +#include "BotChatModelClient.h" + +#include +#include +#include +#include +#include +#include + +#include "Errors.h" // rapidjson's RAPIDJSON_ASSERT is WPAssert in this tree + +#include +#include +#include + +#include +#include +#include +#include + +namespace Playerbot::ChatModel { + +namespace beast = boost::beast; +namespace http = boost::beast::http; +using tcp = boost::asio::ip::tcp; + +std::string BuildRequestBody(Settings const& s, std::vector const& messages) +{ + rapidjson::StringBuffer buf; + rapidjson::Writer w(buf); + w.StartObject(); + w.Key("model"); w.String(s.model.c_str(), rapidjson::SizeType(s.model.size())); + w.Key("stream"); w.Bool(false); + w.Key("keep_alive"); w.String(s.keep_alive.c_str(), rapidjson::SizeType(s.keep_alive.size())); + w.Key("messages"); + w.StartArray(); + for (Message const& m : messages) + { + w.StartObject(); + w.Key("role"); w.String(m.role.c_str(), rapidjson::SizeType(m.role.size())); + w.Key("content"); w.String(m.content.c_str(), rapidjson::SizeType(m.content.size())); + w.EndObject(); + } + w.EndArray(); + w.Key("options"); + w.StartObject(); + w.Key("num_predict"); w.Uint(s.max_tokens); + w.Key("num_ctx"); w.Uint(s.context_length); + w.Key("temperature"); w.Double(std::round(double(s.temperature) * 100.0) / 100.0); + w.EndObject(); + w.EndObject(); + return std::string(buf.GetString(), buf.GetSize()); +} + +bool ParseReply(std::string const& body, std::string& out, std::string& error) +{ + rapidjson::Document doc; + doc.Parse(body.c_str(), body.size()); + if (doc.HasParseError() || !doc.IsObject()) + { + error = "reply is not JSON"; + return false; + } + if (auto e = doc.FindMember("error"); e != doc.MemberEnd() && e->value.IsString()) + { + error = e->value.GetString(); + return false; + } + auto m = doc.FindMember("message"); + if (m == doc.MemberEnd() || !m->value.IsObject()) + { + error = "reply has no message"; + return false; + } + auto c = m->value.FindMember("content"); + if (c == m->value.MemberEnd() || !c->value.IsString()) + { + error = "reply has no content"; + return false; + } + out.assign(c->value.GetString(), c->value.GetStringLength()); + return true; +} + +namespace { + +std::string Trim(std::string s) +{ + auto const not_space = [](unsigned char ch) { return !std::isspace(ch); }; + s.erase(s.begin(), std::find_if(s.begin(), s.end(), not_space)); + s.erase(std::find_if(s.rbegin(), s.rend(), not_space).base(), s.end()); + return s; +} + +std::string Lower(std::string s) +{ + for (char& ch : s) + ch = char(std::tolower(static_cast(ch))); + return s; +} + +// Keeps what the game font can draw: ASCII (minus control characters and '|') and 2-byte UTF-8 (accented letters). Typographic +// quotes, dashes and the ellipsis become their ASCII forms; other symbols from U+2000 up and every 4-byte sequence (emoji) go. +std::string FilterChars(std::string const& in) +{ + std::string out; + out.reserve(in.size()); + std::size_t i = 0; + while (i < in.size()) + { + unsigned char const b = static_cast(in[i]); + if (b < 0x80) + { + if (b == '|') + ; + else if (b < 0x20 || b == 0x7F) + out += ' '; + else + out += char(b); + ++i; + continue; + } + std::size_t len = (b & 0xE0) == 0xC0 ? 2 : (b & 0xF0) == 0xE0 ? 3 : (b & 0xF8) == 0xF0 ? 4 : 1; + if (i + len > in.size()) + break; + bool valid = len > 1; + for (std::size_t k = 1; valid && k < len; ++k) + valid = (static_cast(in[i + k]) & 0xC0) == 0x80; + if (!valid) + { + ++i; + continue; + } + if (len == 2) + out.append(in, i, 2); + else if (len == 3) + { + std::uint32_t const cp = (std::uint32_t(b & 0x0F) << 12) | (std::uint32_t(in[i + 1] & 0x3F) << 6) | std::uint32_t(in[i + 2] & 0x3F); + if (cp == 0x2018 || cp == 0x2019) + out += '\''; + else if (cp == 0x201C || cp == 0x201D) + out += '"'; + else if (cp == 0x2013 || cp == 0x2014) + out += '-'; + else if (cp == 0x2026) + out += "..."; + else if (cp < 0x2000) + out.append(in, i, 3); + } + i += len; + } + return out; +} + +} // namespace + +std::string CleanReply(std::string const& raw, std::string const& bot_name, std::size_t max_bytes) +{ + std::string s = raw; + + // A reasoning model's block (an unclosed one drops everything after it). + for (std::size_t open; (open = s.find("")) != std::string::npos;) + { + std::size_t const close = s.find("", open); + s.erase(open, close == std::string::npos ? std::string::npos : close + 8 - open); + } + + // First non-empty line. + { + std::string line; + std::size_t start = 0; + while (start <= s.size()) + { + std::size_t const nl = s.find('\n', start); + line = Trim(s.substr(start, nl == std::string::npos ? std::string::npos : nl - start)); + if (!line.empty() || nl == std::string::npos) + break; + start = nl + 1; + } + s = line; + } + + s = Trim(FilterChars(s)); + + // "*waves*" style actions. + for (std::size_t open; (open = s.find('*')) != std::string::npos;) + { + std::size_t const close = s.find('*', open + 1); + s.erase(open, close == std::string::npos ? 1 : close + 1 - open); + } + s = Trim(s); + + // "Name: text", ": text", "[Name]: text" - the model speaking as the bot by name (the add-on also hides a whisper + // that starts ":" as an order confirmation). + if (std::size_t const colon = s.find(':'); colon != std::string::npos && colon <= 26) + { + std::string head = Lower(Trim(s.substr(0, colon))); + if (head.size() >= 2 && ((head.front() == '<' && head.back() == '>') || (head.front() == '[' && head.back() == ']'))) + head = Trim(head.substr(1, head.size() - 2)); + if (!bot_name.empty() && head == Lower(bot_name)) + s = Trim(s.substr(colon + 1)); + } + + // Wrapping quotes. + while (s.size() >= 2 && ((s.front() == '"' && s.back() == '"') || (s.front() == '\'' && s.back() == '\''))) + s = Trim(s.substr(1, s.size() - 2)); + + // Collapse runs of spaces left by the filters. + { + std::string collapsed; + collapsed.reserve(s.size()); + for (char ch : s) + if (ch != ' ' || collapsed.empty() || collapsed.back() != ' ') + collapsed += ch; + s = collapsed; + } + + if (s.size() > max_bytes) + { + std::size_t cut = max_bytes; + while (cut > 0 && (static_cast(s[cut]) & 0xC0) == 0x80) + --cut; + std::size_t const space = s.rfind(' ', cut); + if (space != std::string::npos && space > max_bytes / 2) + cut = space; + s = Trim(s.substr(0, cut)); + } + return s; +} + +bool Client::Chat(Settings const& s, std::vector const& messages, std::string& out, std::string& error) +{ + ioc_.restart(); + if (cancelled_) + { + error = "cancelled"; + return false; + } + + tcp::resolver resolver(ioc_); + beast::tcp_stream stream(ioc_); + beast::flat_buffer buffer; + http::response res; + + http::request req{http::verb::post, "/api/chat", 11}; + req.set(http::field::host, s.host + ":" + std::to_string(s.port)); + req.set(http::field::content_type, "application/json"); + req.body() = BuildRequestBody(s, messages); + req.prepare_payload(); + + beast::error_code result; + char const* stage = "resolve"; + // One deadline for the whole exchange: resolve, connect, send and the (slow) generation. + stream.expires_after(std::chrono::milliseconds(s.timeout_ms)); + resolver.async_resolve(s.host, std::to_string(s.port), + [&](beast::error_code ec, tcp::resolver::results_type results) + { + if (ec) { result = ec; return; } + stage = "connect"; + stream.async_connect(results, [&](beast::error_code ec2, tcp::endpoint const&) + { + if (ec2) { result = ec2; return; } + stage = "send"; + http::async_write(stream, req, [&](beast::error_code ec3, std::size_t) + { + if (ec3) { result = ec3; return; } + stage = "read"; + http::async_read(stream, buffer, res, [&](beast::error_code ec4, std::size_t) + { + result = ec4; + if (!ec4) + stage = "done"; + }); + }); + }); + }); + ioc_.run(); + + beast::error_code ignored; + stream.socket().shutdown(tcp::socket::shutdown_both, ignored); + + if (result || std::string_view(stage) != "done") + { + error = std::string(stage) + ": " + (result ? result.message() : std::string("cancelled")); + return false; + } + if (res.result() != http::status::ok) + { + std::string unused, detail; + ParseReply(res.body(), unused, detail); + error = "HTTP " + std::to_string(res.result_int()) + (detail.empty() ? std::string() : ": " + detail); + return false; + } + return ParseReply(res.body(), out, error); +} + +void Client::Cancel() +{ + cancelled_ = true; + ioc_.stop(); +} + +} // namespace Playerbot::ChatModel diff --git a/src/modules/PlayerbotV2/Bot/BotChatModelClient.h b/src/modules/PlayerbotV2/Bot/BotChatModelClient.h new file mode 100644 index 0000000000..8a7b55cbea --- /dev/null +++ b/src/modules/PlayerbotV2/Bot/BotChatModelClient.h @@ -0,0 +1,62 @@ +// BotChatModelClient - the HTTP side of the optional bot chat model (Playerbot.ChatModel.*). +// +// Talks to a local Ollama server (POST /api/chat, stream off). Holds no game state and includes no game headers, so it can +// be built and tested on its own. One Client per thread: Chat() blocks its caller (BotChatModel's worker thread, never the +// world thread) until the reply, an error or the timeout. Cancel() may be called from any thread and makes a running Chat() +// return at once. + +#pragma once + +#include + +#include +#include +#include +#include + +namespace Playerbot::ChatModel { + +struct Settings +{ + std::string host = "127.0.0.1"; + std::uint16_t port = 11434; + std::string model = "llama3.2:3b"; + std::uint32_t timeout_ms = 45000; + std::uint32_t max_tokens = 60; + float temperature = 0.8f; + std::string keep_alive = "30m"; // how long Ollama keeps the model loaded after a reply + std::uint32_t context_length = 2048; // options.num_ctx: Ollama's default context can be 32k, a multi-GB KV cache +}; + +struct Message +{ + std::string role; // "system", "user" or "assistant" + std::string content; +}; + +// The /api/chat request body. +std::string BuildRequestBody(Settings const& s, std::vector const& messages); + +// Reads message.content (or Ollama's "error") out of an /api/chat response body. +bool ParseReply(std::string const& body, std::string& out, std::string& error); + +// Turns a raw model reply into one chat line a bot can say: drops a block, keeps the first non-empty line, strips a +// leading "Name:" (also ":" / "[Name]:") and wrapping quotes or asterisks, removes '|' (the client's escape character) and characters the game +// font has no glyph for (emoji), and cuts it to `max_bytes` on a word boundary. Empty when nothing usable is left. +std::string CleanReply(std::string const& raw, std::string const& bot_name, std::size_t max_bytes = 250); + +class Client +{ +public: + // Sends one chat request. True with `out` set to the model's raw text (CleanReply makes it a chat line); false with `error` set. + bool Chat(Settings const& s, std::vector const& messages, std::string& out, std::string& error); + + // Ends a running Chat() and makes every later one fail at once (the client is done: used at shutdown). + void Cancel(); + +private: + boost::asio::io_context ioc_; + std::atomic cancelled_{false}; +}; + +} // namespace Playerbot::ChatModel diff --git a/src/modules/PlayerbotV2/Bot/BotChatReactor.cpp b/src/modules/PlayerbotV2/Bot/BotChatReactor.cpp index 46dad8e437..c074581ca1 100644 --- a/src/modules/PlayerbotV2/Bot/BotChatReactor.cpp +++ b/src/modules/PlayerbotV2/Bot/BotChatReactor.cpp @@ -3,7 +3,9 @@ // PartyChatIntent through the per-bot intent queue. #include "BotChatReactor.h" +#include "BotChatModel.h" #include "BotConversation.h" +#include "../LfgBotFill.h" #include "BotAI.h" #include "BotIntent.h" @@ -34,6 +36,7 @@ #include "QuestDef.h" #include "World.h" // sWorld locale + CONFIG_LISTEN_RANGE_* for say/yell #include "WorldSession.h" +#include "Containers.h" #include "GameTime.h" #include "ObjectAccessor.h" #include "ObjectGuid.h" @@ -41,6 +44,7 @@ #include #include #include +#include #include #include #include @@ -541,7 +545,18 @@ bool BuildSmallTalkReply(Player* bot, BotAI* ai, std::string const& msg, Player* { if (!Services::Config().chatter_conversation()) return false; - return V2::ConvReply(MakeConvContext(bot, ai, sender), V2::ConvNormalize(msg), msg, sel, addressed, out); + V2::ConversationContext ctx = MakeConvContext(bot, ai, sender); + std::string const norm = V2::ConvNormalize(msg); + // A member of a bot group listed in the Group Finder says yes to a player without a group who asks to join, and the player + // is in the group (and its leader) at once, the same as sending the invite from the list. + bool const joins = addressed && V2::ConvClassify(norm) == V2::ConvIntent::GroupInvite && V2::LfgBotGroupCanTake(bot, sender); + if (joins) + ctx.in_group = false; + if (!V2::ConvReply(ctx, norm, msg, sel, addressed, out)) + return false; + if (joins) + V2::LfgBotGroupJoinRequest(bot, sender); + return true; } // True when the message carries a pause cue ("wait"/"hold"/"stop"/"back"/ @@ -756,6 +771,10 @@ void BotChatReactor::React(Player* sender, Group* group, std::string const& msg) } } + // Playerbot.ChatModel: the model answers party chat instead (ReactPartyModel, from Module::OnPartyChat once the line is + // known not to be an order). + if (BotChatModel::PartyOn()) return; + if (candidates.empty()) return; // When ANY candidate is addressed (their name appeared), only addressed @@ -865,6 +884,98 @@ void BotChatReactor::React(Player* sender, Group* group, std::string const& msg) emit_reply(candidates[idx], 0u); } +// Playerbot.ChatModel: an unprompted line gets one answer from `pool`, tried in random order until a bot takes it (so one +// bot cooling down doesn't leave the line unanswered); then SecondReplyChance percent of the time a second bot chimes in a +// few seconds after the first. Returns how many bots were asked. +static uint32 AskOneOrTwo(std::vector> pool, Player* sender, BotChatModel::Channel channel, + std::string const& msg) +{ + auto const& cfg = Services::Config().chat_model(); + Trinity::Containers::RandomShuffle(pool.begin(), pool.end()); + uint32 asked = 0; + for (auto const& [bot, ai] : pool) + { + uint32 const delay = asked == 0 ? 0u : urand(2500, 6000); + if (!BotChatModel::Ask(bot, sender, MakeConvContext(bot, ai, sender), channel, msg, delay)) + continue; + if (++asked >= 2 || urand(0, 99) >= cfg.second_reply_chance) + break; + } + return asked; +} + +void BotChatReactor::ReactPartyModel(Player* sender, Group* group, std::string const& msg, bool raid_chat) +{ + if (!sender || !group || msg.empty() || !BotChatModel::PartyOn()) return; + if (sender->GetSession() && sender->GetSession()->IsBot()) return; + if (msg.front() == ';' || msg.front() == '.' || msg.front() == '/') return; + const std::string norm = Normalize(msg); + if (norm.size() < 2) return; + + // Party chat in a raid only reaches the speaker's subgroup, so only bots there heard it - and their party-chat answer + // reaches the speaker the same way. + bool const subgroup_only = !raid_chat && group->isRaidGroup(); + BotChatModel::Channel const channel = raid_chat ? BotChatModel::Channel::Raid : BotChatModel::Channel::Party; + struct Candidate { Player* bot; BotAI* ai; bool addressed; }; + std::vector candidates; + BotRegistry& reg = Services::Registry(); + for (GroupReference const& itr : group->GetMembers()) + { + Player* member = itr.GetSource(); + if (!member || member == sender) continue; + if (subgroup_only && !group->SameSubGroup(sender, member)) continue; + if (!member->GetSession() || !member->GetSession()->IsBot()) continue; + if (!member->IsAlive()) continue; + const BotId mid = member->GetGUID().GetCounter(); + if (!reg.has(mid)) continue; + BotAI* ai = reg.ai(mid); + if (!ai) continue; + const std::string first = FirstNameLower(member->GetName()); + const bool addr = first.size() >= 3 && ContainsWord(norm, first.c_str()); + // A bot named in the line answers whatever its verbosity; a quiet bot speaks up unprompted only QuietChance of the time. + if (!addr && ai->personality().verbosity <= Verbosity::Terse && + urand(0, 99) >= Services::Config().chat_model().quiet_chance) continue; + candidates.push_back({member, ai, addr}); + } + if (candidates.empty()) return; + + // A bot named in the line answers (the first one named). Otherwise one bot answers PartyChance of the lines (maybe with a + // second chiming in), and not again in this group for GroupCooldownMs. + Candidate const* chosen = nullptr; + for (auto const& c : candidates) + if (c.addressed) { chosen = &c; break; } + if (!chosen) + { + auto const& cfg = Services::Config().chat_model(); + if (urand(0, 99) >= cfg.party_chance) + { + TC_LOG_INFO("playerbot.v2", "[conv] party <- {} \"{}\": no bot named, skipped (PartyChance {}%)", sender->GetName(), msg, + cfg.party_chance); + return; + } + static std::unordered_map s_group_last; // world thread only + const uint32 now_ms = GameTime::GetGameTimeMS(); + const uint64 gkey = group->GetGUID().GetCounter(); + if (auto it = s_group_last.find(gkey); it != s_group_last.end() && now_ms - it->second < cfg.group_cooldown_ms) + { + TC_LOG_INFO("playerbot.v2", "[conv] party <- {} \"{}\": no bot named, skipped (GroupCooldownMs {})", sender->GetName(), msg, + cfg.group_cooldown_ms); + return; + } + if (s_group_last.size() > 1024) + s_group_last.clear(); + std::vector> pool; + for (auto const& c : candidates) + pool.emplace_back(c.bot, c.ai); + if (AskOneOrTwo(std::move(pool), sender, channel, msg)) + s_group_last[gkey] = now_ms ? now_ms : 1u; + else + TC_LOG_INFO("playerbot.v2", "[conv] party <- {} \"{}\": no bot took it (cooldown / per-minute cap / queue)", sender->GetName(), msg); + return; + } + BotChatModel::Ask(chosen->bot, sender, MakeConvContext(chosen->bot, chosen->ai, sender), channel, msg); +} + // Whisper social reactor. Real players reply when strangers whisper "hi" // or "ty". The reactor is reused here: classify the message against the // same keyword table and emit a whisper-back via the bot's intent queue. @@ -971,7 +1082,10 @@ void BotChatReactor::ReactWhisper(Player* sender, Player* bot, std::string const BotAI* ai = reg.ai(mid); if (!ai) return; const Verbosity v = ai->personality().verbosity; - if (v == Verbosity::Silent || !bot->IsAlive()) + // With Playerbot.ChatModel on, a whisper is a direct question and the model answers it whatever the bot's verbosity; + // verbosity only keeps quiet bots from unprompted chatter. + bool const chat_model = BotChatModel::WhispersOn(); + if ((v == Verbosity::Silent && !chat_model) || !bot->IsAlive()) { TC_LOG_INFO("playerbot.v2", "[conv] {} <- {} whisper \"{}\": silent ({})", bot->GetName(), sender->GetName(), msg, v == Verbosity::Silent ? "personality is Silent" : "bot is dead"); @@ -1015,12 +1129,13 @@ void BotChatReactor::ReactWhisper(Player* sender, Player* bot, std::string const // (and the command parser did not take) still gets an answer - ike3's ChatReplyAction fallback. if (kind == ReactKind::None) { - if (!BotTextMgr::instance().Enabled() && + if (!chat_model && !BotTextMgr::instance().Enabled() && !(Services::Config().chatter_conversation() && V2::ConvUnderstands(V2::ConvNormalize(msg)))) return; kind = ReactKind::DirectAddress; } - if (!VerbosityAllows(v, kind)) + bool const quiet = v == Verbosity::Silent || !VerbosityAllows(v, kind); + if (quiet && !chat_model) { TC_LOG_INFO("playerbot.v2", "[conv] {} <- {} whisper \"{}\": silent (personality verbosity {})", bot->GetName(), sender->GetName(), msg, int(v)); @@ -1062,6 +1177,17 @@ void BotChatReactor::ReactWhisper(Player* sender, Player* bot, std::string const g_last_react_ms[mid] = now_ms; } + // Playerbot.ChatModel: the model answers (later, through the bot's intent queue). When the request is not taken (cooldown, + // per-minute cap, full queue) the usual reply below goes out instead. + if (chat_model && BotChatModel::Ask(bot, sender, MakeConvContext(bot, ai, sender), BotChatModel::Channel::Whisper, msg)) + return; + if (quiet) + { + TC_LOG_INFO("playerbot.v2", "[conv] {} <- {} whisper \"{}\": silent (personality verbosity {}, chat model not taking requests)", + bot->GetName(), sender->GetName(), msg, int(v)); + return; + } + // Whisper-flavored ack — same pool selectors but DirectAddress // applies because every whisper is implicitly addressed to the bot. const uint32 sender_low = sender->GetGUID().GetCounter(); @@ -1253,6 +1379,75 @@ void BotChatReactor::ReactGuild(Player* sender, uint64 guild_id, std::string con namespace { +// Playerbot.ChatModel /say path: a bot within /say range that the line names, or that the speaker has targeted, is being +// spoken to, and the model answers it in /say whatever its verbosity. True when a request was queued; false leaves the line +// to the usual /say reactions below (nobody addressed, model off or not taking requests). +bool ReactSayModel(Player* sender, std::string const& msg, std::string const& norm) +{ + if (!BotChatModel::SayReplyOn()) return false; + float const range = sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_SAY); + BotRegistry& reg = Services::Registry(); + auto usable = [&](Player* p) -> BotAI* + { + if (!p || p == sender || !p->IsAlive() || !p->GetSession() || !p->GetSession()->IsBot()) return nullptr; + if (!p->IsInMap(sender) || !p->IsWithinDist(sender, range)) return nullptr; + BotId const id = p->GetGUID().GetCounter(); + return reg.has(id) ? reg.ai(id) : nullptr; + }; + + Player* chosen = nullptr; + BotAI* chosen_ai = nullptr; + std::list nearby; + Position const senderPos = sender->GetPosition(); + Trinity::AnyPlayerInPositionRangeCheck check(&senderPos, range, /*reqAlive=*/true); + Trinity::PlayerListSearcher searcher(sender, nearby, check); + Cell::VisitWorldObjects(sender, searcher, range); + for (Player* p : nearby) + { + BotAI* ai = usable(p); + if (!ai) continue; + std::string const first = FirstNameLower(p->GetName()); + if (first.size() >= 3 && ContainsWord(norm, first.c_str())) { chosen = p; chosen_ai = ai; break; } + } + if (!chosen) + { + ObjectGuid const target = sender->GetTarget(); + if (target.IsPlayer()) + if (Player* p = ObjectAccessor::GetPlayer(*sender, target)) + if (BotAI* ai = usable(p)) { chosen = p; chosen_ai = ai; } + } + if (chosen) + return BotChatModel::Ask(chosen, sender, MakeConvContext(chosen, chosen_ai, sender), BotChatModel::Channel::SayReply, msg); + + // Nobody addressed: SayChance of the time one bot in earshot answers - bots in the speaker's group first - under the + // realm-wide SayPerMinute cap. Busy bots (combat, battlegrounds, arenas) stay out of it. + auto const& cfg = Services::Config().chat_model(); + if (urand(0, 99) >= cfg.say_chance) return false; + static std::deque s_say_times; // world thread only + uint32 const now_ms = GameTime::GetGameTimeMS(); + while (!s_say_times.empty() && now_ms - s_say_times.front() >= 60000u) + s_say_times.pop_front(); + if (cfg.say_per_minute && s_say_times.size() >= cfg.say_per_minute) + { + TC_LOG_INFO("playerbot.v2", "[conv] say <- {} \"{}\": skipped (SayPerMinute {})", sender->GetName(), msg, cfg.say_per_minute); + return false; + } + std::vector> grouped, others; + Group const* group = sender->GetGroup(); + for (Player* p : nearby) + { + BotAI* ai = usable(p); + if (!ai || p->IsInCombat() || p->InBattleground() || p->InArena()) continue; + if (ai->personality().verbosity <= Verbosity::Terse && urand(0, 99) >= cfg.quiet_chance) continue; + (group && group->IsMember(p->GetGUID()) ? grouped : others).emplace_back(p, ai); + } + uint32 const asked = AskOneOrTwo(grouped.empty() ? std::move(others) : std::move(grouped), sender, + BotChatModel::Channel::SayReply, msg); + for (uint32 i = 0; i < asked; ++i) + s_say_times.push_back(now_ms); + return asked > 0; +} + // SC-P1a: shared /say + /yell reaction core. Anchored on the speaking // player's position, runs a grid-bounded PlayerListSearcher within `range` // (CONFIG_LISTEN_RANGE_SAY / _YELL — never a magic number), gathers nearby @@ -1279,6 +1474,9 @@ void ReactSpoken(Player* sender, std::string const& msg, bool is_yell, const std::string norm = Normalize(msg); if (norm.size() < 2) return; + if (!is_yell && ReactSayModel(sender, msg, norm)) + return; + // Range from server config — the same listen ranges the core uses to // decide who HEARS the say/yell, so a bot only answers what it could // actually have heard. @@ -1508,6 +1706,15 @@ void ReactSpoken(Player* sender, std::string const& msg, bool is_yell, } // namespace +bool BotChatReactor::SmallTalk(Player* bot, Player* sender, std::string const& msg, std::string& out) +{ + if (!bot || !sender) + return false; + BotAI* ai = Services::Registry().ai(BotId(bot->GetGUID().GetCounter())); + uint32 const sel = uint32(bot->GetGUID().GetCounter()) ^ uint32(sender->GetGUID().GetCounter()) ^ GameTime::GetGameTimeMS(); + return BuildSmallTalkReply(bot, ai, msg, sender, sel, /*addressed*/ false, out); +} + void BotChatReactor::ReactSay(Player* sender, std::string const& msg) { // Say is answered relatively often (1-in-2 ambient gate) since /say is diff --git a/src/modules/PlayerbotV2/Bot/BotChatReactor.h b/src/modules/PlayerbotV2/Bot/BotChatReactor.h index b3b7dfe25a..25a176a90b 100644 --- a/src/modules/PlayerbotV2/Bot/BotChatReactor.h +++ b/src/modules/PlayerbotV2/Bot/BotChatReactor.h @@ -37,6 +37,12 @@ public: // No-op when sender is null / a bot / message is empty. static void React(Player* sender, Group* group, std::string const& msg); + // Playerbot.ChatModel party/raid path. Called from PlayerbotV2::Module::OnPartyChat for a line that is not an order. A bot + // named in the line, or now and then one picked by hash, answers through BotChatModel on the channel it heard: raid chat + // for a raid-chat line (any bot in the raid), party chat for a party line (only bots in the speaker's own subgroup, the + // ones a party line reaches). No-op when the model's party replies are off. + static void ReactPartyModel(Player* sender, Group* group, std::string const& msg, bool raid_chat); + // Whisper variant. Called from OnWhisperReceived AFTER BotCommandParser // returned false (command not recognized) — treats the line as a // social cue and emits a whisper-back if the message matches a known @@ -66,6 +72,10 @@ public: // at scale. No-op when sender is a bot / message is a command prefix. static void ReactSay(Player* sender, std::string const& msg); + // A small-talk answer from `bot`'s own state (BotConversation) to a line `sender` wrote where everyone reads it (a channel): + // false when the rules have nothing to say. No cooldowns here; the caller keeps its own. + static bool SmallTalk(Player* bot, Player* sender, std::string const& msg, std::string& out); + // SC-P1a /yell reactor. Same machinery as ReactSay but anchored at // CONFIG_LISTEN_RANGE_YELL and gated to a LOWER fire chance — players // answer yells far less often than says. Shares the per-bot/per-area diff --git a/src/modules/PlayerbotV2/Bot/BotCommandParser.cpp b/src/modules/PlayerbotV2/Bot/BotCommandParser.cpp index c063e08a5a..cfaaa9419e 100644 --- a/src/modules/PlayerbotV2/Bot/BotCommandParser.cpp +++ b/src/modules/PlayerbotV2/Bot/BotCommandParser.cpp @@ -5,6 +5,7 @@ #include "BotRegistry.h" #include "ClassTables.h" #include "ClassicSpec.h" +#include "SpecWords.h" #include "RecipeDifficulty.h" #include "../Threading/IntentQueue.h" #include "../Threading/SnapshotPublisher.h" @@ -17,6 +18,8 @@ #include "PlayerbotMovement.h" // SehSafeCalculatePath (tile-race guard) #include "dtQueryFilterTC.h" // /roadstats reads RoadStats counters #include "../Fleet/OwnerRegistry.h" +#include "CcDeny.h" +#include "OwnerPicks.h" #include "../Fleet/PlayerCraftOrders.h" #include "BotAddressResolver.h" #include "../Diagnostics/BotInspector.h" @@ -1285,6 +1288,9 @@ std::string SpecLabel(uint32 spec) { if (spec == 0) return "no spec"; + // The 70532 client data has no spec names (the DB2 lookup answered "spec 72"): the Classic specs by their own names. + if (char const* const classic = ::Playerbot::V2::SpecWords::Label(spec)) + return classic; if (ChrSpecializationEntry const* e = sChrSpecializationStore.LookupEntry(spec)) { char const* n = e->Name[sWorld->GetDefaultDbcLocale()]; @@ -1659,6 +1665,18 @@ bool OwnerWordOrder(Player* sender, Player* bot, std::string const& n) return true; } // ---- invite (whispered: the bot invites its owner) -------------------------------------------------------------- + // "leave" / "leave group": the bot leaves whatever group it is in (a bots-only remainder after its owner left, for one). + if ((n == "leave" || n == "leave group" || n == "leavegroup") && t_direct_whisper) + { + if (!bot->GetGroup()) + { + say(me + ": I am not in a group"); + return true; + } + Push(bot, GroupLeaveIntent{}); + say(me + ": leaving the group"); + return true; + } if (n == "invite" && t_direct_whisper) { if (Group const* g = bot->GetGroup(); g && g->IsMember(sender->GetGUID())) @@ -1666,6 +1684,15 @@ bool OwnerWordOrder(Player* sender, Player* bot, std::string const& n) say(me + ": you are already in my group"); return true; } + // In a group of bots only (left behind when its owner left): leave it first, or the invite below could not be made. + if (Group const* g = bot->GetGroup()) + { + bool has_player = false; + for (auto const& slot : g->GetMemberSlots()) + if (slot.guid != bot->GetGUID() && !Services::Registry().has(slot.guid.GetCounter())) { has_player = true; break; } + if (!has_player) + Push(bot, GroupLeaveIntent{}); + } Push(bot, InviteToGroupIntent{sender->GetGUID()}); say(me + ": invite sent"); return true; @@ -1744,9 +1771,57 @@ static std::string FormatAddressKind(ResolvedAddress const& a) return "?"; } +bool BotCommandParser::ApplyCcOrder(Player* sender, std::string const& line, char const* via) +{ + auto const order = CcDeny::ParseOrder(line); + if (!order || !sender || !sender->GetSession()) + return false; + uint32 const account = sender->GetSession()->GetAccountId(); + if (account == 0) + return false; + OwnerRegistry& owners = Services::Owners(); + std::string const who = CcDeny::ClassPlural(order->cls); + std::string const what = CcDeny::Describe(order->kinds); + std::string answer; + if (order->cls == 0 && order->kinds == CcDeny::All) + { + // "off cc" / "on cc": every kind for every class, and the marked crowd control (the panel's icon) with it. + owners.SetCcEnabled(account, !order->deny); + if (order->deny) + owners.SetCcDeny(account, 0, CcDeny::All, true); + else + owners.ClearCcDeny(account); + answer = order->deny ? "Crowd control off for all your bots (say 'on cc' to turn it back on)." + : "Crowd control on for all your bots."; + } + else + { + owners.SetCcDeny(account, order->cls, order->kinds, order->deny); + // A "yes" after "off cc" brings the marked crowd control back for what is allowed again. + if (!order->deny) + owners.SetCcEnabled(account, true); + if (order->cls == 0) + answer = order->deny ? fmt::format("None of your bots will use {} now.", what) + : fmt::format("Your bots may use {} again.", what); + else + { + std::string const left_out = CcDeny::Describe(owners.CcDenied(account, order->cls)); + answer = order->deny ? fmt::format("Your {} will not use {} now (left out for them: {}).", who, what, left_out) + : fmt::format("Your {} may use {} again (left out for them: {}).", who, what, left_out); + } + } + TC_LOG_INFO("playerbot.v2", "[cc_order] {} ({}): {} {} for {}", sender->GetName(), via ? via : "?", order->deny ? "deny" : "allow", + what, who); + ChatHandler(sender->GetSession()).PSendSysMessage("%s", answer.c_str()); + return true; +} + bool BotCommandParser::Dispatch(Player* sender, Player* bot, std::string const& msg, char const* via) { if (!sender || !bot) return false; + // A crowd-control order ("@warlock no fear", "off cc") is the owner's, not each bot's: stored once, answered once. + if (ApplyCcOrder(sender, msg, via)) + return true; // Resolve squad-address prefix (all:/tank:/mage:/Areon:/...). // Single-recipient is the most common path — short-circuit so we // don't pay the snapshot lookups when the owner just `/w Areon come`. @@ -3369,7 +3444,7 @@ bool BotCommandParser::DispatchSingleImpl(Player* sender, Player* bot, std::stri Push(bot, WhisperIntent{sender->GetName(), "no snapshot."}); return true; } - constexpr uint8 TRINKET1 = 13, TRINKET2 = 14; + constexpr uint8 TRINKET1 = 12, TRINKET2 = 13; // EQUIPMENT_SLOT_TRINKET1 / TRINKET2 const BotSnapshotView v{*snap}; for (uint8 slot : {TRINKET1, TRINKET2}) { @@ -3508,32 +3583,64 @@ bool BotCommandParser::DispatchSingleImpl(Player* sender, Player* bot, std::stri } if (cmd == "setspec") { - // /setspec — applies ChrSpecialization.db2 id; rejected - // when bot is in combat. Same args[0] parser shape as other id - // commands. - if (args.size() < 1) + // setspec : "setspec holy", "setspec prot", "setspec tank" (the class's tank spec) or a + // ChrSpecialization id (Bot/SpecWords.h). Classic: pins the virtual spec, stores it with the role so a relog or a + // restart pins it again (ApplyCompanionRole at login), and re-buys the talents down that spec's build when out of + // combat, so one whisper respecs a bot or a summoned alt. + uint8 const cls = bot->GetClass(); + ::Playerbot::V2::SpecWords::Word const word = ::Playerbot::V2::SpecWords::Parse(cls, parsed.tail); + uint32 spec = 0; + using SK = ::Playerbot::V2::SpecWords::Kind; + switch (word.kind) { - Push(bot, WhisperIntent{sender->GetName(), "Setspec: "}); + case SK::Spec: spec = word.spec; break; + case SK::Tank: spec = TankSpecForClass(cls); break; + case SK::Healer: spec = HealerSpecForClass(cls); break; + case SK::Dps: + { + // The DPS spec it plays now, else the class's default one. + uint32 const now = ::Playerbot::Classic::EffectiveSpecId(bot); + spec = (now && !IsTankSpec(cls, uint16(now)) && !IsHealerSpec(cls, uint16(now))) ? now : DpsSpecForClass(cls); + break; + } + default: break; + } + if (word.kind == SK::None) + { + Push(bot, WhisperIntent{sender->GetName(), + "Setspec: a spec name of my class (holy, arms, prot, fire, frost...), tank, heal, dps or a spec id."}); + return true; + } + if (!spec) + { + Push(bot, WhisperIntent{sender->GetName(), fmt::format("Setspec: my class has no {} spec.", + word.kind == SK::Tank ? "tank" : "healing")}); return true; } // Classic 1.60: there is nothing to activate; pin the virtual spec. - if (::Playerbot::Classic::SetSpecOverride(bot, static_cast(args[0]))) + if (::Playerbot::Classic::SetSpecOverride(bot, spec)) { // The spec chosen is the role: a role pin from before (a healer pin on a now tank spec) would disagree with it. + BotId const id = bot->GetGUID().GetCounter(); + Role const r = IsTankSpec(cls, uint16(spec)) ? Role::Tank : IsHealerSpec(cls, uint16(spec)) ? Role::Healer : Role::Dps; + if (BotAI* ai = Services::Registry().ai(id)) + if (ai->role_override() != Role::Unknown) + ai->set_role_override(r); + PersistDeclaredRole(bot, r); + if (Services::Owners().GetOwner(id).account_id != 0) + Services::Owners().SetStoredSpec(id, spec); + std::string const name = SpecLabel(spec); + if (bot->IsInCombat()) { - uint8 const cls = bot->GetClass(); - uint16 const sid = uint16(args[0]); - Role const r = IsTankSpec(cls, sid) ? Role::Tank : IsHealerSpec(cls, sid) ? Role::Healer : Role::Dps; - if (BotAI* ai = Services::Registry().ai(bot->GetGUID().GetCounter())) - if (ai->role_override() != Role::Unknown) - ai->set_role_override(r); - PersistDeclaredRole(bot, r); + Push(bot, WhisperIntent{sender->GetName(), + fmt::format("Setspec: playing as {}. In combat: whisper \"talents apply\" after the fight for the talents.", name)}); + return true; } - Push(bot, WhisperIntent{sender->GetName(), - fmt::format("Setspec: playing as spec {} (Classic).", args[0])}); + Push(bot, ApplyStarterTalentsIntent{}); + Push(bot, WhisperIntent{sender->GetName(), fmt::format("Setspec: playing as {}, talents re-learned for it.", name)}); return true; } - Push(bot, ActivateSpecIntent{static_cast(args[0])}); + Push(bot, ActivateSpecIntent{spec}); // Auto-apply Blizzard's starter build for the new spec — without this, // the bot has no talent picks for the just-activated spec and the APL // thinks it doesn't know talented spells. Visitor processes in order: @@ -3541,7 +3648,7 @@ bool BotCommandParser::DispatchSingleImpl(Player* sender, Player* bot, std::stri // active config. Push(bot, ApplyStarterTalentsIntent{}); Push(bot, WhisperIntent{sender->GetName(), - fmt::format("Setspec: queued switch to spec {} + starter talents.", args[0])}); + fmt::format("Setspec: queued switch to spec {} + starter talents.", spec)}); return true; } if (cmd == "setspec_all" || cmd == "setspecall") @@ -4141,7 +4248,14 @@ bool BotCommandParser::DispatchSingleImpl(Player* sender, Player* bot, std::stri // A healer keeps healing on Attack and does not walk in to melee (playtest, Deadmines 2026-10-15): it takes no engage order. Its // own fight logic heals first and casts or wands at the group's target only while nobody needs healing. if (BotRole(bot) == Role::Healer) + { + // A Stay left by an earlier order (the altar's "then I stay there", 30 min) pinned both priests at the altar while + // Pyroguard Emberseer killed one in melee at 3 y (UBRS 20 Oct 21:02): the Attack ends it, the healer follows and heals again. + if (BotAI* heal_ai = Services::Registry().ai(bot->GetGUID().GetCounter())) + if (heal_ai->holding_position(GameTime::GetGameTimeMS())) + heal_ai->exit_manual(); return true; + } Push(bot, StartAttackIntent{target->GetGUID()}); if (BotAI* ai = Services::Registry().ai(bot->GetGUID().GetCounter())) { @@ -4376,6 +4490,7 @@ bool BotCommandParser::DispatchSingleImpl(Player* sender, Player* bot, std::stri ai->set_follow_distance(0.f); ai->set_verbose_logging(false); ai->set_aoe_preference(false); + ai->set_aoe_denied(false); Push(bot, WhisperIntent{sender->GetName(), "Clearprefs: focus, role, follow_distance, verbose, aoe reset."}); return true; @@ -4393,6 +4508,7 @@ bool BotCommandParser::DispatchSingleImpl(Player* sender, Player* bot, std::stri ai->set_follow_distance(0.f); ai->set_verbose_logging(false); ai->set_aoe_preference(false); + ai->set_aoe_denied(false); }); Push(bot, WhisperIntent{sender->GetName(), fmt::format("Clearprefs_all: reset on {} bot(s).", changed)}); @@ -4465,8 +4581,8 @@ bool BotCommandParser::DispatchSingleImpl(Player* sender, Player* bot, std::stri } if (cmd == "aoe") { - // /aoe on — bias rotation toward AoE - // /aoe off — back to single-target priority + // /aoe on — area spells allowed (and the retail rotations bias toward them) + // /aoe off — no spell that hits more than one enemy (AoeDeny.h; the emitter drops it) // /aoe — toggle (default) BotAI* ai = Services::Registry().ai(bot->GetGUID().GetCounter()); if (!ai) @@ -4477,10 +4593,11 @@ bool BotCommandParser::DispatchSingleImpl(Player* sender, Player* bot, std::stri bool desired; if (parsed.tail == "on" || parsed.tail == "1") desired = true; else if (parsed.tail == "off" || parsed.tail == "0") desired = false; - else desired = !ai->aoe_preference(); + else desired = ai->aoe_denied(); ai->set_aoe_preference(desired); + ai->set_aoe_denied(!desired); Push(bot, WhisperIntent{sender->GetName(), - desired ? "Aoe: ON (rotation biases AoE)" : "Aoe: OFF (single-target)"}); + desired ? "Aoe: ON (area spells allowed)" : "Aoe: OFF (no spells that hit more than one enemy)"}); return true; } if (cmd == "setrole") @@ -4531,8 +4648,9 @@ bool BotCommandParser::DispatchSingleImpl(Player* sender, Player* bot, std::stri { BotAI* ai = Services::Registry().ai(p->GetGUID().GetCounter()); if (!ai) return; - const bool desired = (mode == -1) ? !ai->aoe_preference() : (mode == 1); + const bool desired = (mode == -1) ? ai->aoe_denied() : (mode == 1); ai->set_aoe_preference(desired); + ai->set_aoe_denied(!desired); }); Push(bot, WhisperIntent{sender->GetName(), fmt::format("Aoe_all: applied to {} bot(s).", changed)}); @@ -7015,6 +7133,24 @@ done_dispel: Push(bot, WhisperIntent{sender->GetName(), "Teleport: queued."}); return true; } + if (cmd == "pet" && OwnerPicks::ParseSwitch(parsed.tail)) + { + // "pet off": the pet is dismissed and neither summoned nor revived until "pet on" (Bot/OwnerPicks.h). + bool const on = *OwnerPicks::ParseSwitch(parsed.tail); + BotAI* ai = Services::Registry().ai(bot->GetGUID().GetCounter()); + if (!ai) + return true; + if (bot->GetClass() != CLASS_HUNTER && bot->GetClass() != CLASS_WARLOCK) + { + Push(bot, WhisperIntent{sender->GetName(), "Pet: hunter and warlock only."}); + return true; + } + ai->owner_picks().pet_off = !on; + if (!on && bot->GetPet()) + Push(bot, DismissPetIntent{}); + Push(bot, WhisperIntent{sender->GetName(), on ? "Pet: on, I call it again when we rest." : "Pet: off, dismissed and kept away."}); + return true; + } if (cmd == "pet") { const uint64 id = bot->GetGUID().GetCounter(); @@ -8650,10 +8786,125 @@ done_dispel: Push(bot, CastSpellIntent{REBIRTH, target}); return true; } + if (cmd == "prefer") + { + // The owner's spell picks (Bot/OwnerPicks.h): "prefer blessing might", "prefer aura fire", "prefer earth stoneskin", + // "prefer aspect monkey", "prefer demon voidwalker", "prefer auto", "prefer clear"; a bare "prefer" reports them. + // Memory only on BotAI; the snapshot carries them to the Classic upkeep picks and rotations. + BotAI* ai = Services::Registry().ai(bot->GetGUID().GetCounter()); + if (!ai) + { + Push(bot, WhisperIntent{sender->GetName(), "Prefer: bot not registered."}); + return true; + } + OwnerPicks::Picks& picks = ai->owner_picks(); + if (parsed.tail.empty() || parsed.tail == "?") + { + std::string line; + for (uint8 i = 0; i < OwnerPicks::kSlotCount; ++i) + if (OwnerPicks::Choice const* c = OwnerPicks::FindChoice(picks.spell[i])) + line += (line.empty() ? "" : ", ") + std::string(c->label); + if (picks.pet_off) line += line.empty() ? "pet off" : ", pet off"; + if (picks.stealth_off) line += line.empty() ? "stealth off" : ", stealth off"; + Push(bot, WhisperIntent{sender->GetName(), line.empty() ? std::string("Prefer: nothing picked, I follow my own plan.") + : "Prefer: " + line + "."}); + return true; + } + std::optional const order = OwnerPicks::ParseOrder("prefer " + parsed.tail); + if (!order) + { + Push(bot, WhisperIntent{sender->GetName(), + "Prefer: blessing|aura|earth|fire|water|air|aspect|demon |auto, or prefer clear."}); + return true; + } + if (order->clear_all) + { + picks = {}; + Push(bot, WhisperIntent{sender->GetName(), "Prefer: cleared, back to my own plan (pet and stealth on)."}); + return true; + } + if (bot->GetClass() != OwnerPicks::SlotClass(order->slot)) + { + Push(bot, WhisperIntent{sender->GetName(), + fmt::format("Prefer: I am no {}, a {} is not mine to pick.", + order->slot == OwnerPicks::Aspect ? "hunter" : order->slot == OwnerPicks::Demon ? "warlock" + : (order->slot == OwnerPicks::Blessing || order->slot == OwnerPicks::Aura) ? "paladin" : "shaman", + OwnerPicks::SlotName(order->slot))}); + return true; + } + if (order->spell == 0) + { + picks.spell[order->slot] = 0; + Push(bot, WhisperIntent{sender->GetName(), fmt::format("Prefer: {} back to my own plan.", OwnerPicks::SlotName(order->slot))}); + return true; + } + OwnerPicks::Choice const* choice = OwnerPicks::FindChoice(order->spell); + auto const snap = Services::Snapshots().latest(bot->GetGUID().GetCounter()); + if (!snap || !BotSnapshotView{*snap}.knows_spell(order->spell)) + { + Push(bot, WhisperIntent{sender->GetName(), fmt::format("Prefer: I don't know {} yet.", choice ? choice->label : "that")}); + return true; + } + picks.spell[order->slot] = order->spell; + Push(bot, WhisperIntent{sender->GetName(), fmt::format("Prefer: {} from now on{}.", choice ? choice->label : "that", + OwnerPicks::TravelAspect(order->spell) ? " (Hawk in a fight, it dazes the group)" : "")}); + return true; + } + if (cmd == "stealth") + { + // "stealth off": the rogue opens without Stealth (and no Sap, MarkCc) until "stealth on"; Stealth up now is cancelled. + std::optional const on = OwnerPicks::ParseSwitch(parsed.tail); + BotAI* ai = Services::Registry().ai(bot->GetGUID().GetCounter()); + if (!on || !ai) + { + Push(bot, WhisperIntent{sender->GetName(), "Stealth: on|off."}); + return true; + } + if (bot->GetClass() != CLASS_ROGUE) + { + Push(bot, WhisperIntent{sender->GetName(), "Stealth: rogue only."}); + return true; + } + ai->owner_picks().stealth_off = !*on; + if (!*on) + for (uint32 const rank : { 1784u, 1785u, 1786u, 1787u }) + if (bot->HasAura(rank)) + Push(bot, CancelAuraIntent{rank}); + Push(bot, WhisperIntent{sender->GetName(), *on ? "Stealth: on, I open from Stealth again." : "Stealth: off, no Stealth openers."}); + return true; + } + if (cmd == "ritual") + { + // Warlock Ritual of Summoning (698) on a member of the bot's group: "ritual ". Two more members click the portal + // (or "use summoning" to bots in party chat, the "use" order). + if (bot->GetClass() != CLASS_WARLOCK) + { + Push(bot, WhisperIntent{sender->GetName(), "Ritual: warlock only."}); + return true; + } + constexpr uint32 RITUAL_OF_SUMMONING = 698; + if (!bot->HasSpell(RITUAL_OF_SUMMONING)) + { + Push(bot, WhisperIntent{sender->GetName(), "Ritual: I don't know Ritual of Summoning yet."}); + return true; + } + Player* who = parsed.tail.empty() ? nullptr : ObjectAccessor::FindPlayerByName(parsed.tail); + Group const* grp = bot->GetGroup(); + if (!who || !grp || !grp->IsMember(who->GetGUID()) || who == bot) + { + Push(bot, WhisperIntent{sender->GetName(), "Ritual: say 'ritual ' with the name of someone in our group."}); + return true; + } + Push(bot, CastSpellIntent{RITUAL_OF_SUMMONING, who->GetGUID()}); + Push(bot, WhisperIntent{sender->GetName(), + fmt::format("Ritual: summoning {}. Two more of us click the portal (say 'use summoning' in party chat).", who->GetName())}); + return true; + } if (cmd == "soulstone") { // Warlock pre-rez — Soulstone (20707). Casts on selection (or // sender) to apply the stone; target self-rezzes on death. + // "soulstone " puts it on that member of the bot's group. const BotId id = bot->GetGUID().GetCounter(); auto snap = Services::Snapshots().latest(id); if (!snap) return true; @@ -8668,6 +8919,15 @@ done_dispel: return true; } ObjectGuid target = sender->GetTarget(); if (target.IsEmpty()) target = sender->GetGUID(); + if (!parsed.tail.empty()) + { + Player* who = ObjectAccessor::FindPlayerByName(parsed.tail); + Group const* grp = bot->GetGroup(); + if (!who || !(who == bot || (grp && grp->IsMember(who->GetGUID())))) + { Push(bot, WhisperIntent{sender->GetName(), "Soulstone: say 'soulstone ' with the name of someone in our group."}); + return true; } + target = who->GetGUID(); + } Push(bot, CastSpellIntent{SOULSTONE, target}); return true; } @@ -8860,6 +9120,8 @@ done_dispel: "movement: follow, come/summon, stay/halt, mount, dismount, hearth, jump, dismiss"}); Push(bot, WhisperIntent{sender->GetName(), "combat: attack, stop/passive, cast , heal, dispel, buff, reset"}); + Push(bot, WhisperIntent{sender->GetName(), + "picks: prefer blessing|aura|earth|fire|water|air|aspect|demon |auto, prefer clear, pet on|off, stealth on|off, ritual , soulstone [name], portal "}); Push(bot, WhisperIntent{sender->GetName(), "loot/inv: sell [ []], repair, use, bank, buy [], buyfood, buypot, buybandage, buyall"}); Push(bot, WhisperIntent{sender->GetName(), diff --git a/src/modules/PlayerbotV2/Bot/BotCommandParser.h b/src/modules/PlayerbotV2/Bot/BotCommandParser.h index 42e60af989..2127cd2514 100644 --- a/src/modules/PlayerbotV2/Bot/BotCommandParser.h +++ b/src/modules/PlayerbotV2/Bot/BotCommandParser.h @@ -34,6 +34,11 @@ public: // command needs to run, and by tests that bypass the prefix layer. static bool DispatchSingle(Player* sender, Player* bot_player, std::string const& msg, char const* via = "whisper"); + // The owner's crowd-control orders ("no fear", "@warlock no fear", "@mages no sheep", "yes sheep", "off cc", "on cc"; CcDeny.h): + // when `line` is one, stores it for the sender's account (OwnerRegistry::SetCcDeny, the marked-CC switch for "off cc" / "on cc"), + // answers the sender once and returns true. The bots pick it up with their next snapshot. World thread. + static bool ApplyCcOrder(Player* sender, std::string const& line, char const* via); + // May `sender` give this bot a group order (the panel, a party / raid line)? Its owner, or for a bot with no owner a player // who is its controller in the group they share (GroupControl.h): the group leader when human, else the first human // member. An invited world bot obeys the leader exactly like a companion. diff --git a/src/modules/PlayerbotV2/Bot/BotIntent.h b/src/modules/PlayerbotV2/Bot/BotIntent.h index c349712b57..f3977fcc5a 100644 --- a/src/modules/PlayerbotV2/Bot/BotIntent.h +++ b/src/modules/PlayerbotV2/Bot/BotIntent.h @@ -112,7 +112,7 @@ struct FollowIntent { ObjectGuid leader; float distance; float angle_ra struct UseItemIntent { uint8 bag, slot; ObjectGuid target; }; struct UseItemByEntryIntent { uint32 item_entry; ObjectGuid target; }; struct EquipItemIntent { uint8 from_bag, from_slot; uint8 to_slot; }; -struct LootIntent { ObjectGuid corpse_or_object; }; +struct LootIntent { ObjectGuid corpse_or_object; bool quest_only = false; }; // quest_only: take only this bot's quest drops struct ReleaseCorpseIntent {}; struct ReviveAtCorpseIntent {}; // Corpse-run completion: bot is ghost and has walked back into reclaim @@ -148,7 +148,8 @@ struct QuestAcceptIntent { ObjectGuid npc; uint32 quest_id; }; // `reward_choice` selects from the quest's choice-item list (0 = first). // Pass 0xFF to let PlayerbotAPI auto-pick (ScoreQuestReward weighs equippable // upgrades > vendor value). Quests with only fixed rewards ignore the field. -struct QuestCompleteIntent { ObjectGuid npc; uint32 quest_id; uint8 reward_choice; }; +// copy_leader: the bot's copy is finished for it first (a grouped bot that does not loot) because its leader just handed the quest in. +struct QuestCompleteIntent { ObjectGuid npc; uint32 quest_id; uint8 reward_choice; bool copy_leader = false; }; struct QuestAbandonIntent { uint32 quest_id; }; // Accept a quest just shared by a group member. The receiver-side popup is // driven by `Player::SetQuestSharingInfo`; the API uses GetSharedQuestID for @@ -382,6 +383,8 @@ struct LfgRoleCheckIntent { uint8 roles; }; // reviving at the graveyard outside. Lives in QueueIntent with the other // instance-entry ops (BG port, LFG proposal). Calls API::enter_area_trigger. struct EnterAreaTriggerIntent { uint32 area_trigger_id; }; +// Playerbot.AlwaysBuffs: keep the bot in the always-on state of its place: `set` is a BuffSet, `mask` the kAlwaysMask* kinds that are on there (0 = take every always-on aura off). +struct AlwaysBuffIntent { uint8 set; uint8 mask; }; // ---- World interaction ---- struct UseObjectIntent { ObjectGuid object; }; @@ -528,6 +531,9 @@ namespace EconomyOp { // (PlayerbotAPI::stock_raid_consumable; the core refuses anything outside the kits and any // map but a raid). Gated by Playerbot.Raid.ProvideConsumables. struct StockRaidConsumable { uint32 item; }; + // Raid preparation: wear the vanilla resistance pieces of `school` (a SpellSchools value) in place of the bot's own, or put its own + // back (school 0). BotPopulationManager::SwapResistGear; gated by Playerbot.Raid.ResistGear. + struct ResistGear { uint8 school; }; } struct EconomyIntent @@ -542,7 +548,8 @@ struct EconomyIntent EconomyOp::CraftPost, EconomyOp::CraftClaim, EconomyOp::RestockClassSupplies, - EconomyOp::StockRaidConsumable + EconomyOp::StockRaidConsumable, + EconomyOp::ResistGear > op; }; @@ -609,7 +616,7 @@ struct QueueIntent std::variant< BgQueueIntent, BgLeaveIntent, BgPortIntent, LfgQueueIntent, LfgUnqueueIntent, LfgProposalRespondIntent, - LfgRoleCheckIntent, EnterAreaTriggerIntent + LfgRoleCheckIntent, EnterAreaTriggerIntent, AlwaysBuffIntent > op; }; // Housing (12.0+) — 4 sub-ops. Wrapped per feedback_intent_variant_capacity diff --git a/src/modules/PlayerbotV2/Bot/BotIntentEmitter.cpp b/src/modules/PlayerbotV2/Bot/BotIntentEmitter.cpp index 9820e68395..9669af0a01 100644 --- a/src/modules/PlayerbotV2/Bot/BotIntentEmitter.cpp +++ b/src/modules/PlayerbotV2/Bot/BotIntentEmitter.cpp @@ -2,6 +2,8 @@ #include #include #include "BotAI.h" +#include "CcDeny.h" +#include "AoeDeny.h" #include "BotSnapshot.h" #include "BotSnapshotView.h" #include "Log.h" @@ -158,7 +160,7 @@ bool BotIntentEmitter::pet_attack(ObjectGuid target) if (uint8 const mask = pet_hold_mask(target)) return hold_pet(target, mask); // already held there: nothing pushed const bool pushed = emit(PetAttackIntent{target}); - // PetAttack sets the pet aggressive and on `target`: any hold is over. + // PetAttack puts the pet on `target`: any hold is over. if (pushed && ai_) { ai_->raid_school().pet_hold_target = ObjectGuid::Empty; @@ -167,8 +169,59 @@ bool BotIntentEmitter::pet_attack(ObjectGuid target) return pushed; } +namespace { + +// The CcDeny kind of a spell: its rank in the table, else its first rank's, else (a harmful spell only) the crowd-control mechanic its +// effects carry, so a Forever spell id missing from the table still counts. +uint16 SpellCcKind(uint32 spell_id) +{ + if (uint16 const k = CcDeny::KindOfSpell(spell_id)) + return k; + if (uint32 const first = sSpellMgr->GetFirstSpellInChain(spell_id); first && first != spell_id) + if (uint16 const k = CcDeny::KindOfSpell(first)) + return k; + SpellInfo const* si = sSpellMgr->GetSpellInfo(spell_id, DIFFICULTY_NONE); + if (!si || si->IsPositive()) + return 0; + uint64 const m = si->GetAllEffectsMechanicMask(); + auto const has = [m](Mechanics mech) { return (m & (uint64(1) << mech)) != 0; }; + uint16 k = 0; + if (has(MECHANIC_FEAR) || has(MECHANIC_HORROR) || has(MECHANIC_TURN)) k |= CcDeny::Fear; + if (has(MECHANIC_POLYMORPH)) k |= CcDeny::Polymorph; + if (has(MECHANIC_BANISH)) k |= CcDeny::Banish; + if (has(MECHANIC_SHACKLE)) k |= CcDeny::Shackle; + if (has(MECHANIC_SAPPED)) k |= CcDeny::Sap; + if (has(MECHANIC_SLEEP)) k |= CcDeny::Sleep; + if (has(MECHANIC_CHARM)) k |= CcDeny::Charm; + return k; +} + +} // namespace + +bool BotIntentEmitter::cc_denied(uint32 spell_id) const +{ + return school_snap_ && school_snap_->cc_deny && spell_id && (SpellCcKind(spell_id) & school_snap_->cc_deny) != 0; +} + +bool BotIntentEmitter::aoe_denied(uint32 spell_id) const +{ + if (!school_snap_ || !school_snap_->aoe_denied || !spell_id) + return false; + SpellInfo const* si = sSpellMgr->GetSpellInfo(spell_id, DIFFICULTY_NONE); + if (!si) + return false; + uint32 chain = 0; + for (SpellEffectInfo const& eff : si->GetEffects()) + if (eff.IsEffect() && eff.ChainTargets > 0 && uint32(eff.ChainTargets) > chain) + chain = uint32(eff.ChainTargets); + uint32 const first = sSpellMgr->GetFirstSpellInChain(spell_id); + return AoeDeny::IsAoe(si->IsPositive(), si->IsAffectingArea(), chain, first ? first : spell_id); +} + bool BotIntentEmitter::pet_cast(uint32 spell_id, ObjectGuid target) { + if (owner_denied(spell_id)) + return false; if (school_snap_) { SpellInfo const* si = spell_id ? sSpellMgr->GetSpellInfo(spell_id, DIFFICULTY_NONE) : nullptr; @@ -203,13 +256,13 @@ bool BotIntentEmitter::sync_school_hold(ObjectGuid victim) { // The held target's hint cleared (or it died and left the // hints): send the pet back in on the victim, or, with no - // victim, back to the defensive stance a pet gets on summon. + // victim, back to the passive stance a pet gets on summon. ObjectGuid const back = rs.pet_hold_target; if (!victim.IsEmpty() && pet_hold_mask(victim) == 0) pushed_pet = pet_attack(victim); else { - pushed_pet = emit(HunterPetIntent{PetSetReactStateIntent{1 /*REACT_DEFENSIVE*/}}); + pushed_pet = emit(HunterPetIntent{PetSetReactStateIntent{0 /*REACT_PASSIVE*/}}); if (pushed_pet) { rs.pet_hold_target = ObjectGuid::Empty; @@ -437,6 +490,34 @@ static bool HasCastTime(uint32 spell_id) return si && si->CalcCastTime() > 0; } +namespace +{ +// Cat, Bear, Dire Bear, Moonkin, Travel and Aquatic Form. +bool IsDruidShapeshiftSpell(uint32 spell_id) +{ + switch (spell_id) + { + case 768: case 5487: case 9634: case 24858: case 783: case 1066: + return true; + default: + return false; + } +} +} + +bool BotIntentEmitter::cast_imbue(uint32 spell_id, ObjectGuid item_guid) +{ + if (!ai_) + return emit(CastSpellOnItemIntent{spell_id, item_guid}); + uint32 const now_ms = GameTime::GetGameTimeMS(); + if (ai_->action_recently_tried(BotAI::ActionKind::ClassUpkeep, spell_id, now_ms)) + return false; + bool const pushed = emit(CastSpellOnItemIntent{spell_id, item_guid}); + if (pushed) + ai_->note_action_retry(BotAI::ActionKind::ClassUpkeep, spell_id, now_ms); + return pushed; +} + bool BotIntentEmitter::cast(uint32 spell_id, ObjectGuid target) { if (ai_ && ai_->mana_break_active(GameTime::GetGameTimeMS()) && HasCastTime(spell_id)) @@ -459,11 +540,19 @@ bool BotIntentEmitter::cast(uint32 spell_id, ObjectGuid target) // Raid school rule: an avoided school at a hinted enemy is not sent. if (school_blocked(spell_id, target)) return false; + // The owner said no to this kind of crowd control ("@warlock no fear"), or to area spells ("aoe off"). + if (owner_denied(spell_id)) + return false; if (ai_) { const uint32 now_ms = GameTime::GetGameTimeMS(); if (ai_->cast_recently_emitted(spell_id, now_ms)) return false; + // A bot that has just clicked a battleground flag or banner left its druid form to do it (API::use_game_object); the + // rotation's form rule shifted it straight back in and the next click left it again (WSG 2026-10-21: a dire bear druid + // "leaves form 8" three times in 7 s at a dropped flag and never took it). + if (IsDruidShapeshiftSpell(spell_id) && ai_->action_recently_tried(BotAI::ActionKind::BgFormHold, 0, now_ms)) + return false; uint32 const gcd_ms = GcdLengthMs(spell_id); if (gcd_ms && ai_->gcd_recently_started(now_ms)) return false; @@ -483,14 +572,19 @@ bool BotIntentEmitter::cast_rank(uint32 spell_id, ObjectGuid target) { if (ai_ && ai_->mana_break_active(GameTime::GetGameTimeMS()) && HasCastTime(spell_id)) return false; - // Same raid school gate and per-spell emit dedup as cast(); ranks have their own ids. - if (school_blocked(spell_id, target)) + // Same raid school gate, crowd-control orders and per-spell emit dedup as cast(); ranks have their own ids. + if (school_blocked(spell_id, target) || owner_denied(spell_id)) return false; if (ai_) { const uint32 now_ms = GameTime::GetGameTimeMS(); if (ai_->cast_recently_emitted(spell_id, now_ms)) return false; + // A bot that has just clicked a battleground flag or banner left its druid form to do it (API::use_game_object); the + // rotation's form rule shifted it straight back in and the next click left it again (WSG 2026-10-21: a dire bear druid + // "leaves form 8" three times in 7 s at a dropped flag and never took it). + if (IsDruidShapeshiftSpell(spell_id) && ai_->action_recently_tried(BotAI::ActionKind::BgFormHold, 0, now_ms)) + return false; uint32 const gcd_ms = GcdLengthMs(spell_id); if (gcd_ms && ai_->gcd_recently_started(now_ms)) return false; diff --git a/src/modules/PlayerbotV2/Bot/BotIntentEmitter.h b/src/modules/PlayerbotV2/Bot/BotIntentEmitter.h index 35707d4921..684fcde56f 100644 --- a/src/modules/PlayerbotV2/Bot/BotIntentEmitter.h +++ b/src/modules/PlayerbotV2/Bot/BotIntentEmitter.h @@ -74,7 +74,7 @@ public: bool cast_rank(uint32 spell_id, ObjectGuid target); bool cast_at(uint32 spell_id, float x, float y, float z) - { return emit(GroundTargetSpellIntent{spell_id, x, y, z}); } + { return !owner_denied(spell_id) && emit(GroundTargetSpellIntent{spell_id, x, y, z}); } // start_attack() drops the emit silently if the same target was just // refused by Player::Attack within the last 30 s — see @@ -275,6 +275,10 @@ public: // Cast a spell on an Item (disenchant 13262 / prospect 31252 / mill 51005). bool cast_on_item(uint32 spell_id, ObjectGuid item_guid) { return emit(CastSpellOnItemIntent{spell_id, item_guid}); } + // Weapon imbue (Windfury / Flametongue / Rockbiter Weapon) on the bot's own weapon, under the same 30 s retry lockout as the + // out-of-combat idle:classic_weapon rule: an imbue the server refuses (or the snapshot does not show yet) is not re-sent every + // tick, and the rotation falls through to its other rules while the lockout runs. + bool cast_imbue(uint32 spell_id, ObjectGuid item_guid); // Vehicle controls. enter_vehicle takes a Unit GUID of the vehicle // (a Creature or other Unit with a VehicleKit) and an optional seat @@ -310,8 +314,8 @@ public: { return emit(VehicleGroundSpellIntent{spell_id, x, y, z}); } bool accept_quest(ObjectGuid giver, uint32 quest_id) { return emit(QuestAcceptIntent{giver, quest_id}); } - bool complete_quest(ObjectGuid giver, uint32 quest_id, uint8 reward_choice = 0) - { return emit(QuestCompleteIntent{giver, quest_id, reward_choice}); } + bool complete_quest(ObjectGuid giver, uint32 quest_id, uint8 reward_choice = 0, bool copy_leader = false) + { return emit(QuestCompleteIntent{giver, quest_id, reward_choice, copy_leader}); } bool abandon_quest(uint32 quest_id) { return emit(QuestAbandonIntent{quest_id}); } bool accept_shared_quest() { return emit(QuestSharedAcceptIntent{}); } bool resolve_junk_quests() { return emit(ResolveJunkQuestsIntent{}); } @@ -397,6 +401,9 @@ public: // Raid preparation: hand the bot one flask / elixir / food of its role kit (EconomyOp::StockRaidConsumable). bool stock_raid_consumable(uint32 item) { return emit(EconomyIntent{EconomyOp::StockRaidConsumable{item}}); } + // Raid preparation: resistance gear for `school` on, or the bot's own back on (0) (EconomyOp::ResistGear). + bool resist_gear(uint8 school) + { return emit(EconomyIntent{EconomyOp::ResistGear{school}}); } // Battleground / arena queue. `arena_type` 0 = battleground (solo or // group-leader), 2/3/5 = arena skirmish bracket (group-leader only). @@ -447,6 +454,12 @@ private: bool push(Intent i); // Raid school rule gate for cast()/cast_rank(); see set_school_source. bool school_blocked(uint32 spell_id, ObjectGuid target); + // The owner's crowd-control orders ("@warlock no fear", "off cc"; CcDeny.h): a spell of a kind the snapshot's cc_deny holds is + // not sent, by cast() / cast_rank() / cast_at() / pet_cast() alike, so the rotation falls through to its next rule. + bool cc_denied(uint32 spell_id) const; + // The owner's "aoe off" (AoeDeny.h, snapshot aoe_denied): a spell that hits more than one enemy is not sent either. + bool aoe_denied(uint32 spell_id) const; + bool owner_denied(uint32 spell_id) const { return cc_denied(spell_id) || aoe_denied(spell_id); } void note_school_cast(uint32 spell_id, ObjectGuid target); // Avoided part of the pet's damage schools on `target` (0 = no hold). uint8 pet_hold_mask(ObjectGuid target) const; diff --git a/src/modules/PlayerbotV2/Bot/BotIntentExecutor.cpp b/src/modules/PlayerbotV2/Bot/BotIntentExecutor.cpp index c1e60620ee..4dfbf12e5b 100644 --- a/src/modules/PlayerbotV2/Bot/BotIntentExecutor.cpp +++ b/src/modules/PlayerbotV2/Bot/BotIntentExecutor.cpp @@ -10,6 +10,7 @@ #include "../Util/ConfigReader.h" #include "../Fleet/BotGuildCharter.h" #include "../Fleet/BotGuildMgr.h" +#include "../Fleet/BotPopulationManager.h" // SwapResistGear #include "../Fleet/CraftOrderBoard.h" #include "../Fleet/JunkQuestResolver.h" #include "../Threading/IntentQueue.h" @@ -27,6 +28,7 @@ #include #include "Channel.h" #include "ChannelMgr.h" +#include "DB2Stores.h" #include "Creature.h" #include "Guild.h" #include "GuildMgr.h" @@ -34,6 +36,9 @@ #include "ObjectAccessor.h" #include "GameTime.h" #include "Log.h" +#include "Bot/DrainOrder.h" +#include "Bot/ReactionTiming.h" +#include "Combat/Apl/ApInterrupt.h" #include #include #include @@ -66,6 +71,21 @@ Result SayInZoneChannel(Player* bot, uint8 channel_id, std::string const& text) bot->UpdateLocalChannels(bot->GetZoneId()); ch = find(channel_id); } + // LookingForGroup is not an auto-join channel: the bot joins it the way a player types /join, on its first line there. + if (!ch) + if (ChatChannelsEntry const* entry = sChatChannelsStore.LookupEntry(channel_id)) + if (entry->GetFlags().HasFlag(ChatChannelFlags::LookingForGroup)) + if (ChannelMgr* mgr = ChannelMgr::ForTeam(bot->GetTeam())) + { + AreaTableEntry const* zone = sAreaTableStore.LookupEntry(bot->GetZoneId()); + Channel* lfg = entry->GetFlags().HasFlag(ChatChannelFlags::ZoneBased) ? (zone ? mgr->GetSystemChannel(channel_id, zone) : nullptr) + : mgr->GetSystemChannel(channel_id); + if (lfg) + { + lfg->JoinChannel(bot); + ch = find(channel_id); + } + } // Trade exists only in cities; ike3 posted the line to General instead. if (!ch && channel_id != 1) ch = find(1); @@ -131,6 +151,15 @@ struct IntentVisitor Combat::ClassicHeal::ReleaseHealClaim(bp->GetGUID().GetCounter(), i.target, GameTime::GetGameTimeMS()); if (r == Result::Ok && bot_ai) bot_ai->set_last_cast_spell_id(i.spell_id); + if (r == Result::Ok) + if (Player const* bp = api.player()) + { + namespace In = Combat::Interrupt; + bool const kick = i.spell_id == In::PUMMEL || i.spell_id == In::SHIELD_BASH || i.spell_id == In::KICK || i.spell_id == In::KIDNEY_SHOT || + i.spell_id == In::COUNTERSPELL || i.spell_id == In::EARTH_SHOCK || i.spell_id == In::SILENCE || i.spell_id == In::BASH; + if (kick) ReactionTiming::Instance().OnKick(bp->GetGUID().GetCounter(), GameTime::GetGameTimeMS()); + else ReactionTiming::Instance().OnCast(bp->GetGUID().GetCounter(), GameTime::GetGameTimeMS()); + } // [cast_fail] per-reason tally, logged every 10 s per bot with failures. if (bot_ai) if (Player const* bp = api.player()) @@ -223,6 +252,9 @@ struct IntentVisitor Result operator()(MoveToIntent const& i) { Result const r = api.move_to(i.x, i.y, i.z, i.run, i.direct, i.drop, i.follow_drop); + if (r == Result::Ok) + if (Player const* bp = api.player()) + ReactionTiming::Instance().OnMove(bp->GetGUID().GetCounter(), GameTime::GetGameTimeMS()); if (i.follow_drop && bot_ai && r != Result::Locked) { // A ledge walk or flight commits the follow; an ordinary pathed move means the walking route is fine (State_InGroup HonorFollowDrop). @@ -311,7 +343,7 @@ struct IntentVisitor Result operator()(TradeDeclineIntent const& i) { return i.accept ? api.trade_with(i.owner, i.gift) : api.decline_trade(); } Result operator()(UseItemByEntryIntent const& i) { return api.use_item_by_entry(i.item_entry, i.target); } Result operator()(UseItemIntent const& i) { return api.use_item_by_slot(i.bag, i.slot, i.target); } - Result operator()(LootIntent const& i) { return api.loot_corpse(i.corpse_or_object); } + Result operator()(LootIntent const& i) { return api.loot_corpse(i.corpse_or_object, i.quest_only); } Result operator()(InteractWithNpcIntent const& i) { return api.interact_with_npc(i.npc); } Result operator()(GossipSelectIntent const& i) { return api.gossip_select_by_index(i.npc, i.option); } Result operator()(UseObjectIntent const& i) { return api.use_game_object(i.object); } @@ -322,7 +354,7 @@ struct IntentVisitor Result operator()(VehicleSpellIntent const& i) { return api.cast_vehicle_spell(i.spell_id, i.target); } Result operator()(VehicleGroundSpellIntent const& i) { return api.cast_vehicle_spell_at(i.spell_id, i.x, i.y, i.z); } Result operator()(QuestAcceptIntent const& i) { return api.accept_quest(i.npc, i.quest_id); } - Result operator()(QuestCompleteIntent const& i) { return api.complete_quest(i.npc, i.quest_id, i.reward_choice); } + Result operator()(QuestCompleteIntent const& i) { return api.complete_quest(i.npc, i.quest_id, i.reward_choice, i.copy_leader); } Result operator()(QuestAbandonIntent const& i) { return api.abandon_quest(i.quest_id); } Result operator()(QuestSharedAcceptIntent const&) { return api.accept_shared_quest(); } Result operator()(ResolveJunkQuestsIntent const&) @@ -450,6 +482,7 @@ struct IntentVisitor else if constexpr (std::is_same_v) return api.lfg_proposal_respond(op.proposal_id, op.accept); else if constexpr (std::is_same_v) return api.lfg_role_check(op.roles); else if constexpr (std::is_same_v) return api.enter_area_trigger(op.area_trigger_id); + else if constexpr (std::is_same_v) return api.always_buffs(op.set, op.mask); else return Result::Other; }, qi.op); } @@ -517,9 +550,20 @@ struct IntentVisitor return claimed.id != 0 ? Result::Ok : Result::ServerRefused; } else if constexpr (std::is_same_v) + { + // The supplies rule reaches every bot now and then: a petless world hunter gets its beast here (BotPopulationManager::EnsureBotHunterPet). + V2::Fleet::BotPopulationManager::EnsureBotHunterPet(api.player()); return api.restock_class_supplies(); + } else if constexpr (std::is_same_v) return api.stock_raid_consumable(op.item); + else if constexpr (std::is_same_v) + { + Player* bot = api.player(); + if (!bot || !Services::Config().raid_resist_gear()) return Result::ServerRefused; + Services::Population().SwapResistGear(bot, op.school); + return Result::Ok; + } else return Result::Other; }, ei.op); } @@ -665,7 +709,7 @@ size_t V2::Module::DrainIntents() constexpr auto kDrainBudget = std::chrono::milliseconds(30); const auto drain_start = std::chrono::steady_clock::now(); bool over_budget = false; - reg.for_each([&](BotId id, BotRegistryEntry const& entry) + auto const drain_bot = [&](BotId id, BotRegistryEntry const& entry) { if (over_budget) return; if (!entry.intents) return; @@ -976,7 +1020,31 @@ size_t V2::Module::DrainIntents() perf_slowest_intent_kind_ = batch_slowest_kind; } } - }); + }; + // The pass starts at a different bot each time one was cut short (the 30 ms limit, or a pathfind request that found the window spent): + // with a fixed order the same bots at the tail waited every frame, and a bot told to wait for minutes looks like one that will not + // move. The bots before the start index go last in the same pass. + static size_t s_start = 0; + static uint32 s_stat_ms = 0, s_passes = 0, s_refused = 0, s_cut = 0; + size_t const n_bots = reg.size(); + size_t const start = n_bots ? s_start % n_bots : 0; + size_t idx = 0; + reg.for_each([&](BotId id, BotRegistryEntry const& entry) { if (idx++ >= start) drain_bot(id, entry); }); + if (start) + { + idx = 0; + reg.for_each([&](BotId id, BotRegistryEntry const& entry) { if (idx++ < start) drain_bot(id, entry); }); + } + bool const refused = Playerbot::PathBudget::Refused(); + ++s_passes; s_refused += refused ? 1u : 0u; s_cut += over_budget ? 1u : 0u; + s_start = NextDrainStart(start, n_bots, refused || over_budget); + if (uint32 const now_stat = GameTime::GetGameTimeMS(); !s_stat_ms || now_stat - s_stat_ms >= 60000u) + { + if (s_stat_ms && (s_refused || s_cut)) + TC_LOG_INFO("playerbot.v2", "[drain] last minute: {} passes, {} had a pathfind request refused (window spent), {} cut by the 30 ms limit, {} bots; next pass starts at bot {}", + s_passes, s_refused, s_cut, n_bots, s_start); + s_stat_ms = now_stat; s_passes = s_refused = s_cut = 0; + } // Close the pathfinding-budget window so it never throttles a pathfind issued // outside DrainIntents (HasBudget fails open when inactive). Playerbot::PathBudget::EndWorldTick(); diff --git a/src/modules/PlayerbotV2/Bot/BotSnapshot.h b/src/modules/PlayerbotV2/Bot/BotSnapshot.h index 02bd879717..a802075fc4 100644 --- a/src/modules/PlayerbotV2/Bot/BotSnapshot.h +++ b/src/modules/PlayerbotV2/Bot/BotSnapshot.h @@ -11,6 +11,7 @@ #include "BotTypes.h" #include "FlatIndex.h" #include "ObjectGuid.h" +#include "OwnerPicks.h" #include "Raid/RaidOrder.h" #include "Quest/CompanionQuest.h" // CompanionQuestState (companion_quest) #include @@ -77,6 +78,9 @@ struct EquippedItem // is_ready(on_use_spell_id) without dragging ItemTemplate into the // worker thread. Used by InCombat for trinket auto-fire on cooldown. uint32 on_use_spell_id = 0; + // Remaining cooldown of that spell in ms (the item's use cooldown). The trinket's spell is not in the spellbook, so the snapshot's + // spell cooldown rows never carry it. + uint32 on_use_cd_ms = 0; // Stat block for the equipped item. Lets the equip-upgrade rule // compute score(equipped[slot]) without re-resolving the live Item*. ItemStatBlock stats{}; @@ -307,11 +311,18 @@ struct NearbyUnit // nearby_enemies). Drives the tanks' Demo refresh over a pack // (TankThreat::DemoMissingAround). int32 ap_debuff_ms = 0; + // A root or a snare (movement slowed) is on the unit. Hostile units (attackers + nearby_enemies). + bool snared = false; // The unit is immune to a stun right now (template / aura mechanic // immunity, probed with Bash's stun effect - most raid bosses). Hostile // units (attackers + nearby_enemies). Keeps a bear's Bash out of the // interrupt rotation on such a mob (Combat/Apl/ApInterrupt.h). bool stun_immune = false; + // The unit is immune to the warrior's Rend right now (bleed mechanic + // immunity, probed with Rend rank 1). Filled for warrior bots only, on the + // same units as stun_immune. Keeps Rend from being recast every GCD on a + // mob that never takes it. + bool bleed_immune = false; Role role = Role::Unknown; ObjectGuid victim; // Who this unit is currently attacking (Empty if none). // For Creature units: lower 32 bits of UNIT_NPC_FLAG_* (vendor/repair/ @@ -1368,6 +1379,9 @@ struct CombatTargetsState // The group has more than 15 members (a 40-man raid): adds appear faster than // the tanks can build threat on them, so trash is never held for threat. bool big_raid = false; + // The bot's group is a raid group (wherever it stands). A raid in the open world (a world boss, the support scorecard) plays by the raid + // rules the instance maps get: threat discipline and the healers' mana-efficiency rules. + bool raid_group = false; // Hostile ground-effect zones around the bot (see GroundHazard). std::vector ground_hazards; // LoS to each live same-map group tank (see TankLos). @@ -1379,6 +1393,7 @@ struct CombatTargetsState tank_los.clear(); group_tank = ObjectGuid::Empty; big_raid = false; + raid_group = false; victim = ObjectGuid::Empty; current_target = ObjectGuid::Empty; current_target_hostile = false; @@ -2063,6 +2078,9 @@ struct SpellbookState // (Overpower before a dodge, Revenge before a block, Execute above 20%). // Sorted ascending; BotSnapshotView::is_ready treats them as not ready. std::vector aura_state_blocked; + // Known spells whose maximum range the bot's spell modifiers change (Flame Throwing, Arctic Reach, Grim Reach ...): the yards they add, + // sorted by spell id. Spell::CalcMinMaxRange applies SpellModOp::Range; a range read from the spell data alone missed it. + std::vector> range_bonus; bool is_starter_build = false; void reset() @@ -2072,6 +2090,7 @@ struct SpellbookState active_talents.clear(); active_glyphs.clear(); aura_state_blocked.clear(); + range_bonus.clear(); is_starter_build = false; } }; @@ -2685,6 +2704,15 @@ struct BotSnapshot // Owner "max dps" / "save mana" (BotAI::tactic_burn / tactic_save_mana), mirrored by the builder. bool tactic_burn = false; bool tactic_save_mana = false; + // The CcDeny kinds (CcDeny.h) this bot leaves out by its owner's order ("@warlock no fear", "off cc"), resolved by the builder + // from OwnerRegistry::CcDenied for the account that commands the bot. The emitter drops such a cast; MarkCc skips it. + uint16 cc_deny = 0; + // The owner's spell picks for this bot ("prefer blessing might", "pet off", "stealth off"; OwnerPicks.h), mirrored from + // BotAI::owner_picks by the builder. Read by the Classic upkeep picks and rotations. + OwnerPicks::Picks owner_picks; + // The owner's "aoe off" (BotAI::aoe_denied, AoeDeny.h), mirrored by the builder: the emitter drops a spell that hits more than + // one enemy. + bool aoe_denied = false; // (duel + quest-share + trade + summon migrated into social_events above) // LFG queue / role-check / proposal / vote-kick state — REFACTOR_2 // sub-struct rollout. See LfgState above for per-field semantics. @@ -2968,6 +2996,9 @@ struct BotSnapshot owner_dist = -1.0f; tactic_burn = false; tactic_save_mana = false; + cc_deny = 0; + owner_picks = {}; + aoe_denied = false; // Sub-structs (declaration order). identity.reset(); diff --git a/src/modules/PlayerbotV2/Bot/BotSnapshotBuilder.cpp b/src/modules/PlayerbotV2/Bot/BotSnapshotBuilder.cpp index d6e8c860e7..c78f703ae8 100644 --- a/src/modules/PlayerbotV2/Bot/BotSnapshotBuilder.cpp +++ b/src/modules/PlayerbotV2/Bot/BotSnapshotBuilder.cpp @@ -14,6 +14,7 @@ #include "StatPriority.h" #include "Gear/BotGearGenerator.h" // RaidGearActive / RaidEquipUpgrade (raid-gear upgrade test) #include "../Services.h" +#include "../Diagnostics/DamageParity.h" #include "../Util/ConfigReader.h" // ConfigReader full type — Services::Config() use below #include "../Fleet/BotGuildMgr.h" #include "../Fleet/CraftOrderBoard.h" @@ -2379,6 +2380,8 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b { snap->tactic_burn = bot_ai->tactic_burn(); snap->tactic_save_mana = bot_ai->tactic_save_mana(); + snap->owner_picks = bot_ai->owner_picks(); + snap->aoe_denied = bot_ai->aoe_denied(); } snap->social_events.has_duel_request = p->duel && p->duel->State == DUEL_STATE_CHALLENGED && p->duel->Initiator != p; @@ -3061,6 +3064,9 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b if (eff->TriggerType == ITEM_SPELLTRIGGER_ON_USE) { dst.on_use_spell_id = static_cast(eff->SpellID); + if (SpellInfo const* use_info = sSpellMgr->GetSpellInfo(eff->SpellID, DIFFICULTY_NONE)) + if (SpellHistory const* use_hist = p->GetSpellHistory(); use_hist && use_hist->HasCooldown(use_info, item->GetEntry())) + dst.on_use_cd_ms = static_cast(std::max(1, use_hist->GetRemainingCooldown(use_info).count())); break; } } @@ -3260,7 +3266,12 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b uint8 const want = gun ? ITEM_SUBCLASS_BULLET : ITEM_SUBCLASS_ARROW; for (auto const& it : snap->inventory.bag_items) if (it.item_class == ITEM_CLASS_PROJECTILE && it.item_subclass == want) - snap->consumables.ammo_count += it.count; + { + // A stack the bot cannot use yet (above its level) is no ammo: AutoSelectAmmo skips it as well. + ItemTemplate const* ammo_proto = sObjectMgr->GetItemTemplate(it.entry); + if (ammo_proto && p->CanUseItem(ammo_proto) == EQUIP_ERR_OK) + snap->consumables.ammo_count += it.count; + } } // Wand damage school, the same rule Spell::Spell applies to a wand user's @@ -3359,6 +3370,22 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b } } + // ---- Owner crowd-control orders ("@warlock no fear", "off cc"): those of the player who commands the bot, the owner, or the + // group's controller for a bot whose owner is not in the group (BotCommandParser::ApplyCcOrder). ---- + if (Services::Initialized()) + { + uint32 cc_account = 0; + if (snap->led_by_player && !snap->owner_in_group) + { + if (Player const* c = ObjectAccessor::FindConnectedPlayer(snap->controller_guid); c && c->GetSession()) + cc_account = c->GetSession()->GetAccountId(); + } + else + cc_account = Services::Owners().GetOwner(snap->bot_id).account_id; + if (cc_account) + snap->cc_deny = Services::Owners().CcDenied(cc_account, snap->identity.cls); + } + // ---- Spellbook (sorted, binary-searchable in BotSnapshotView::knows_spell) ---- // Filter (active && !disabled) + copy + sort of the whole SpellMap // (300+ entries) used to run every Build, though the result only @@ -3393,6 +3420,7 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b if (ks_throttled) { snap->spellbook.known_spells = ks_ai->cached_known_spells(); + snap->spellbook.range_bonus = ks_ai->cached_range_bonus(); } else { @@ -3403,8 +3431,17 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b snap->spellbook.known_spells.push_back(spell_id); } std::sort(snap->spellbook.known_spells.begin(), snap->spellbook.known_spells.end()); + // The range the cast is held to (Spell::CalcMinMaxRange) carries the caster's SpellModOp::Range modifiers: 241 support scorecard, the fire + // mage with Flame Throwing (+6 y) stood 24 y from the boss, inside Fire Blast's 26 y, and never cast it in 8 of 9 runs because the + // rotation read the spell's 20 y. + snap->spellbook.range_bonus.clear(); + for (uint32 sid : snap->spellbook.known_spells) + if (SpellInfo const* si = sSpellMgr->GetSpellInfo(sid, DIFFICULTY_NONE); si && si->RangeEntry) + if (float const bonus = si->GetMaxRange(false, p) - si->GetMaxRange(false); bonus != 0.0f) + snap->spellbook.range_bonus.emplace_back(sid, bonus); if (ks_ai) { + ks_ai->mutable_cached_range_bonus() = snap->spellbook.range_bonus; ks_ai->mutable_cached_known_spells() = snap->spellbook.known_spells; ks_ai->set_cached_spellmap_size(ks_active); ks_ai->set_last_known_spells_scan_ms(ks_now); @@ -3822,6 +3859,11 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b { if (Spell* casting = p->GetCurrentSpell(static_cast(slot))) { + // A cast whose cast time is over and whose projectile is still in flight (LAUNCHED) is no longer a cast in progress: the core + // accepts the next cast (Unit::IsNonMeleeSpellCast skips it) and the bot is free to act. Counting it held every caster idle for the + // flight time of its Fireball / Frostbolt / Shadow Bolt (0.4-0.9 s after each, ~15 s of every 120). + if (slot == CURRENT_GENERIC_SPELL && casting->getState() == SPELL_STATE_LAUNCHED) + continue; snap->cast.is_casting = true; snap->cast.current_cast_spell_id = casting->m_spellInfo->Id; const int32 rem = casting->GetRemainingCastTime(); @@ -3852,9 +3894,11 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b threat_tanks.clear(); snap->combat.group_tank = ObjectGuid::Empty; snap->combat.big_raid = false; + snap->combat.raid_group = false; if (Group const* tg = p->GetGroup()) { snap->combat.big_raid = tg->GetMembersCount() > 15; + snap->combat.raid_group = tg->isRaidGroup(); for (auto const& slot : tg->GetMemberSlots()) { Player* mp = slot.guid == p->GetGUID() ? p : ObjectAccessor::GetPlayer(*p, slot.guid); @@ -3904,6 +3948,13 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b } u.stun_immune = immune; } + // Bleed immunity (warrior Rend): the whole spell, so a mechanic + // immunity on the spell or on its periodic effect both count. + if (p->GetClass() == CLASS_WARRIOR) + { + static SpellInfo const* const rend = sSpellMgr->GetSpellInfo(772, DIFFICULTY_NONE); + u.bleed_immune = rend && t->IsImmunedToSpell(rend, MAX_EFFECT_MASK, p); + } if (u.has_threat_list) { ThreatManager const& tm = t->GetThreatManager(); @@ -4009,10 +4060,15 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b if (CreatureTemplate const* act = ac->GetCreatureTemplate()) { u.creature_type = uint8(act->type); - if (act->unit_flags & UNIT_FLAG_PACIFIED) - u.is_pacified = true; - if (act->unit_flags & UNIT_FLAG_UNINTERACTIBLE) - u.untargetable = true; + // The template flags mark static props. A unit that is hitting somebody is no prop: an event boss + // (Pyroguard Emberseer) is spawned with them and its script clears them on the live unit. + if (!ac->GetVictim()) + { + if (act->unit_flags & UNIT_FLAG_PACIFIED) + u.is_pacified = true; + if (act->unit_flags & UNIT_FLAG_UNINTERACTIBLE) + u.untargetable = true; + } } } // Attacker-side CC scan — same shape as nearby_enemies. Without @@ -4044,6 +4100,7 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b if (IsDemoApDebuff(asi->Id)) NoteApDebuff(u, abase); if (asi->Mechanic == MECHANIC_ROOT) u.root_caster = abase->GetCasterGUID(); // MarkCc: Entangling Roots up (not CC-locked) + if (asi->Mechanic == MECHANIC_ROOT || asi->Mechanic == MECHANIC_SNARE) u.snared = true; // Concussive Shot, Wing Clip, Frostbolt: a hunter can step back int pri = -1; switch (asi->Mechanic) { @@ -4607,7 +4664,8 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b if (CreatureTemplate const* ct = c->GetCreatureTemplate()) u.is_ranged_caster = ct->unit_class == CLASS_MAGE; // creatures only have warrior, paladin, rogue and mage u.is_boss_rank = c->isWorldBoss() - || c->GetCreatureClassification() == CreatureClassifications::Obsolete; // vanilla rank 3 "boss" + || c->GetCreatureClassification() == CreatureClassifications::Obsolete // vanilla rank 3 "boss" + || Diagnostics::Parity::IsSupportBoss(c->GetGUID()); // the support scorecard's boss dummy // Folds CREATURE_STATIC_FLAG_NO_XP + template flags_extra // NO_XP. Training dummies and other no-reward targets must // never be grind-engaged (they don't die, grant nothing, and @@ -4657,10 +4715,16 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b { // CreatureType is uint8 in TC; Beast=1, etc. u.creature_type = uint8(ct->type); - if (ct->unit_flags & UNIT_FLAG_PACIFIED) - u.is_pacified = true; - if (ct->unit_flags & UNIT_FLAG_UNINTERACTIBLE) - u.untargetable = true; + // Static props only: a unit that is hitting somebody is no prop. Pyroguard Emberseer is spawned with these flags + // and its script clears them on the live unit, so the template flags kept the attackable boss out of the + // raid tracker and the DPS stood idle (UBRS 20 Oct). + if (!c->GetVictim()) + { + if (ct->unit_flags & UNIT_FLAG_PACIFIED) + u.is_pacified = true; + if (ct->unit_flags & UNIT_FLAG_UNINTERACTIBLE) + u.untargetable = true; + } // Elite / RareElite / Rare = legit high-HP, slow kills; the // unkillable-target leash must never abandon them. u.is_elite_or_rare = @@ -4771,6 +4835,7 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b if (IsDemoApDebuff(asi->Id)) NoteApDebuff(u, abase); if (asi->Mechanic == MECHANIC_ROOT) u.root_caster = abase->GetCasterGUID(); // MarkCc: Entangling Roots up (not CC-locked) + if (asi->Mechanic == MECHANIC_ROOT || asi->Mechanic == MECHANIC_SNARE) u.snared = true; // Concussive Shot, Wing Clip, Frostbolt: a hunter can step back int pri = -1; switch (asi->Mechanic) { @@ -8225,6 +8290,49 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b } snap->world_objects.nearby_objects.push_back(n); } + + // Tram cars (type-11 GOs that run between two stations on one map, the Deeprun Tram): they sit in the grid, so the + // MO-transport set above never holds them, and the 30 y object scan only sees one standing right beside the bot. A + // bot waiting on the platform for a ride looked at "transports in sight 0" for 300 s, then gave the route up. The + // cars are few and known (PortalIndex), so look them up by spawn id within the same 200 y. + if (Services::Initialized() && Services::Portals().IsInitialized()) + { + auto const& car_ids = Services::Portals().ShuttleSpawnIds(p->GetMapId()); + if (!car_ids.empty()) + { + static std::atomic s_carLogAt{0}; + uint32 const cnow = GameTime::GetGameTimeMS(); + uint32 last = s_carLogAt.load(std::memory_order_relaxed); + if (cnow - last >= 120000u && s_carLogAt.compare_exchange_strong(last, cnow ? cnow : 1u)) + { + size_t in_world = 0; + for (uint64 const id : car_ids) + if (GameObject* c = tmap->GetGameObjectBySpawnId(id); c && c->IsInWorld()) ++in_world; + TC_LOG_INFO("playerbot.v2", "[xport_cars] map {}: {} tram cars known, {} in the world; {} sees {:.0f},{:.0f},{:.0f}", + p->GetMapId(), car_ids.size(), in_world, p->GetName(), p->GetPositionX(), p->GetPositionY(), p->GetPositionZ()); + } + } + for (uint64 const spawn_id : car_ids) + { + GameObject* car = tmap->GetGameObjectBySpawnId(spawn_id); + if (!car || !car->IsInWorld()) continue; + const float cdx = car->GetPositionX() - p->GetPositionX(); + const float cdy = car->GetPositionY() - p->GetPositionY(); + const float cdz = car->GetPositionZ() - p->GetPositionZ(); + if (cdx*cdx + cdy*cdy + cdz*cdz > kTransportScanSq) continue; + bool const have = std::any_of(snap->world_objects.nearby_objects.begin(), snap->world_objects.nearby_objects.end(), + [&](BotSnapshot::NearbyObject const& o) { return o.guid == car->GetGUID(); }); + if (have) continue; + BotSnapshot::NearbyObject n{}; + n.guid = car->GetGUID(); + n.entry = car->GetEntry(); + n.go_type = car->GetGoType(); + n.x = car->GetPositionX(); + n.y = car->GetPositionY(); + n.z = car->GetPositionZ(); + snap->world_objects.nearby_objects.push_back(n); + } + } } // ---- Extended gathering-node scan (200y) ---- @@ -9204,15 +9312,15 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b static constexpr AvWsNode AV_WS_NODES[] = { { 638.5f, -31.5f, 46.0f, 1325, 1326, 1327, 1328, 0, "Stormpike Aid Station" }, { 669.0f, -294.0f, 30.0f, 1333, 1335, 1334, 1336, 0, "Stormpike Graveyard" }, - { 73.7f, -426.0f, 61.0f, 1302, 1304, 1301, 1303, 0, "Stonehearth Graveyard" }, + { 77.8f, -404.7f, 46.9f, 1302, 1304, 1301, 1303, 0, "Stonehearth Graveyard" }, { -202.5f, -113.0f, 78.0f, 1341, 1343, 1342, 1344, 0, "Snowfall Graveyard" }, { -612.5f, -397.0f, 61.0f, 1346, 1348, 1347, 1349, 0, "Iceblood Graveyard" }, { -1082.5f, -347.0f, 55.0f, 1337, 1339, 1338, 1340, 0, "Frostwolf Graveyard" }, { -1402.0f, -307.0f, 89.0f, 1329, 1331, 1330, 1332, 0, "Frostwolf Relief Hut" }, - { 556.0f, -84.0f, 52.0f, 1361, 1375, 1370, 1378, 1, "Dun Baldar South Bunker" }, - { 678.0f, -139.0f, 64.0f, 1362, 1374, 1371, 1379, 1, "Dun Baldar North Bunker" }, + { 553.8f, -78.7f, 51.9f, 1361, 1375, 1370, 1378, 1, "Dun Baldar South Bunker" }, + { 674.0f, -143.1f, 63.7f, 1362, 1374, 1371, 1379, 1, "Dun Baldar North Bunker" }, { 203.0f, -361.0f, 56.0f, 1363, 1376, 1372, 1380, 1, "Icewing Bunker" }, - { -154.0f, -446.0f, 45.0f, 1364, 1377, 1373, 1381, 1, "Stonehearth Bunker" }, + { -152.4f, -441.6f, 40.4f, 1364, 1377, 1373, 1381, 1, "Stonehearth Bunker" }, { -572.0f, -263.0f, 75.0f, 1368, 1390, 1385, 1395, 2, "Iceblood Tower" }, { -768.0f, -363.0f, 91.0f, 1367, 1389, 1384, 1394, 2, "Tower Point" }, { -1303.0f, -317.0f, 114.0f, 1366, 1388, 1383, 1393, 2, "East Frostwolf Tower" }, @@ -10607,6 +10715,17 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b } } + // Playerbot.World.Questing = 0: a bot of the world (no owner, no group) sees no quests, so nothing sends it to a giver, a hub or a quest + // objective; it grinds and roams (idle:grind_roam). A companion keeps its quests (CompanionQuest). + if (!Services::Config().world_questing() && snap->owner_guid.IsEmpty() && snap->owner_name.empty() && snap->group.group_guid.IsEmpty() && !snap->led_by_player) + { + uint16 const completed = snap->quest_log.completed_quest_count; + snap->quest_log.reset(); + snap->quest_log.completed_quest_count = completed; + snap->quest_discovery.quest_offers.clear(); + snap->quest_discovery.quest_turnins.clear(); + } + return snap; } diff --git a/src/modules/PlayerbotV2/Bot/BotSnapshotView.cpp b/src/modules/PlayerbotV2/Bot/BotSnapshotView.cpp index d70dbb8335..b335f73f0a 100644 --- a/src/modules/PlayerbotV2/Bot/BotSnapshotView.cpp +++ b/src/modules/PlayerbotV2/Bot/BotSnapshotView.cpp @@ -1,4 +1,4 @@ -#include "BotSnapshotView.h" +#include "BotSnapshotView.h" #include "SpellMgr.h" #include "Log.h" #include "SpellInfo.h" @@ -426,9 +426,14 @@ bool BotSnapshotView::in_spell_range(uint32 spell_id, NearbyUnit const& t, float limit = std::max(kSelfReach + t.combat_reach + 4.0f / 3.0f, kNominalMelee); else { - float const base = si->GetMaxRange(false); + float base = si->GetMaxRange(false); if (base <= 0.f) return true; + // The bot's range modifiers on this spell (SpellbookState::range_bonus), as Spell::CalcMinMaxRange applies them. + auto const& rb = s_->spellbook.range_bonus; + if (auto it = std::lower_bound(rb.begin(), rb.end(), spell_id, [](std::pair const& e, uint32 id) { return e.first < id; }); + it != rb.end() && it->first == spell_id) + base += it->second; limit = base + kSelfReach + t.combat_reach; if (si->CalcCastTime() > 0) // Spell::CheckRange: hard casts get +10% (<= 3y) limit += std::min(3.0f, base * 0.1f); @@ -437,6 +442,18 @@ bool BotSnapshotView::in_spell_range(uint32 spell_id, NearbyUnit const& t, float return d2 <= limit * limit; } +float BotSnapshotView::spell_min_range(uint32 spell_id, NearbyUnit const& t) const +{ + if (uint32 known = resolve_rank(spell_id)) spell_id = known; + SpellInfo const* si = sSpellMgr->GetSpellInfo(spell_id, DIFFICULTY_NONE); + if (!si || !si->RangeEntry) + return 0.f; + float min = si->GetMinRange(false); + if (si->RangeEntry->Flags & SPELL_RANGE_RANGED) + min += std::max(1.5f + t.combat_reach + 4.0f / 3.0f, 5.0f); // DEFAULT_PLAYER_COMBAT_REACH + target reach + 4/3, at least NOMINAL_MELEE_RANGE + return min; +} + bool BotSnapshotView::victim_in_spell_range(uint32 spell_id, float slack) const { NearbyUnit const* v = victim_info(); @@ -982,7 +999,7 @@ static NearbyUnit const* UnclaimedLooseAttacker(BotSnapshot const& s, float rang // The victim's role from the bot's own friend sweep (the snapshot carries no group list; a victim outside the 12 closest friends // reads as no preference). Cloth casters would need a class on NearbyUnit; only healers are preferred here. A victim already // below kDyingVictimPct comes before everyone: with more loose mobs than tanks the mob on the member about to die is the one - // to take (two mobs on a rogue at 5% health while both tanks took mobs on members at full health). + // to take (UBRS 132f 22:15:30: two Dragonspawn on a rogue at 5% health, both tanks took mobs on members at full health). for (NearbyUnit const& f : s.combat.nearby_friends) if (f.guid == e.victim) { @@ -1005,7 +1022,11 @@ NearbyUnit const* BotSnapshotView::taunt_candidate(float range) const // Ours, and not on us yet: taunt it wherever it is, another tank // included. No ping-pong: the holder sees it as a mob on itself, // and its own fallback below skips mobs claimed by other tanks. - if (ThreatVictim(a->victim_kind) != ThreatVictim::Me) + // A raid boss another tank holds is left there: each swap turns it (Onyxia's Flame Breath and Tail Sweep, Broodlord's + // Cleave) and the taunt war never settles. The planned swaps (debuff stacks) are RaidBrain's taunt orders, not this. + bool const boss_on_tank = s_->instance_ctx.is_in_raid && ThreatVictim(a->victim_kind) == ThreatVictim::Tank && + (a->is_dungeon_boss || a->is_boss_rank); + if (ThreatVictim(a->victim_kind) != ThreatVictim::Me && !boss_on_tank) { const float dx = a->x - s_->position.x; const float dy = a->y - s_->position.y; diff --git a/src/modules/PlayerbotV2/Bot/BotSnapshotView.h b/src/modules/PlayerbotV2/Bot/BotSnapshotView.h index 8573863da4..9905e14b37 100644 --- a/src/modules/PlayerbotV2/Bot/BotSnapshotView.h +++ b/src/modules/PlayerbotV2/Bot/BotSnapshotView.h @@ -25,6 +25,10 @@ public: bool is_horde() const { return s_->identity.team == 2u; } uint8 cls() const { return s_->identity.cls; } uint32 spec() const { return s_->identity.spec; } + // The owner's pick for a slot ("prefer blessing might"; OwnerPicks.h): rank-1 spell id, 0 = the bot's own plan. + uint32 owner_pick(OwnerPicks::Slot slot) const { return s_->owner_picks[slot]; } + bool owner_pet_off() const { return s_->owner_picks.pet_off; } + bool owner_stealth_off() const { return s_->owner_picks.stealth_off; } uint8 gender() const { return s_->identity.gender; } uint32 faction() const { return s_->identity.faction; } ObjectGuid guid() const { return s_->guid; } @@ -93,6 +97,8 @@ public: bool is_companion_with_owner() const { return s_->owner_in_group; } // In a group with a player who commands it: a companion, or a world bot a player invited. Neither runs world errands. bool is_led_by_player() const { return s_->owner_in_group || s_->led_by_player; } + // A bot of the world: no owner, not in any group, not led by a player. + bool is_free_world_bot() const { return s_->owner_guid.IsEmpty() && s_->owner_name.empty() && s_->group.group_guid.IsEmpty() && !s_->led_by_player; } bool no_tag_stance() const { return s_->no_tag_stance; } bool holding_position() const { return s_->holding_position; } ObjectGuid controller_guid() const { return s_->owner_in_group ? s_->owner_guid : s_->controller_guid; } @@ -281,6 +287,9 @@ public: // in_spell_range against victim_info(); true when the victim is not in the // snapshot lists (no distance to judge) - the API's own gate still holds. bool victim_in_spell_range(uint32 spell_id, float slack = 1.0f) const; + // The core's minimum range for a hostile cast at `t` (Spell::GetMinMaxRange): the range entry's own minimum, plus the melee range (both + // combat reaches + 4/3, at least 5 y) for a spell with the ranged flag. 0 when the spell has no minimum. + float spell_min_range(uint32 spell_id, NearbyUnit const& t) const; NearbyUnit const* lowest_hp_friend() const; NearbyUnit const* highest_threat_attacker() const; // First attacker in the threat list that is currently casting an @@ -388,6 +397,7 @@ public: // ungrouped or no tank is on this map. ObjectGuid group_tank() const { return s_->combat.group_tank; } bool big_raid() const { return s_->combat.big_raid; } + bool in_raid_group() const { return s_->combat.raid_group; } // Damage-restraint verdict for a NON-TANK group member about to damage // `target` (MCRaidHoldDamage): TankOpening while the tank has not yet // built `opening_lead` threat (or nobody has engaged the mob yet); @@ -504,19 +514,19 @@ public: return seen ? lo : 100; } - // First trinket on-use spell that's actually ready to fire. Returns 0 - // when the bot has no equipped on-use trinket or both are on cooldown. - // Trinkets live in EQUIPMENT_SLOT_TRINKET1 (13) and TRINKET2 (14); the - // builder pre-resolved each slot's ON_USE spell so we just probe the - // ready bit. InCombat fires this on cooldown to extract trinket value - // without per-tick ItemTemplate lookups. - uint32 ready_on_use_trinket() const + // Item entry of the first equipped trinket whose on-use spell is off cooldown; 0 when there is none. A trinket's spell is not in the + // spellbook, so is_ready() (which refuses an unknown spell) never passed one: no trinket of any class fired until this check + // (215 scorecard: no trinket in any hunter's cast list). The builder pre-resolved each slot's ON_USE spell; the cooldown is the spell's, + // as the core keeps an item's use cooldown under its spell. The caller uses the item (UseItemByEntry), not a spell cast. + uint32 ready_on_use_trinket_item() const { - constexpr uint8 TRINKET1 = 13, TRINKET2 = 14; + constexpr uint8 TRINKET1 = 12, TRINKET2 = 13; // EQUIPMENT_SLOT_TRINKET1 / TRINKET2 + if (s_->vitals.is_stunned) return 0; for (uint8 slot : {TRINKET1, TRINKET2}) { - const uint32 sid = s_->inventory.equipped[slot].on_use_spell_id; - if (sid != 0 && is_ready(sid)) return sid; + auto const& eq = s_->inventory.equipped[slot]; + if (eq.entry != 0 && eq.on_use_spell_id != 0 && eq.on_use_cd_ms == 0) + return eq.entry; } return 0; } diff --git a/src/modules/PlayerbotV2/Bot/BotTextMgr.cpp b/src/modules/PlayerbotV2/Bot/BotTextMgr.cpp index 84fc83879b..8236b1696c 100644 --- a/src/modules/PlayerbotV2/Bot/BotTextMgr.cpp +++ b/src/modules/PlayerbotV2/Bot/BotTextMgr.cpp @@ -1,6 +1,7 @@ // BotTextMgr / BotChatter - see header. #include "BotTextMgr.h" +#include "ChannelTalk.h" #include "BotAI.h" #include "BotIntent.h" @@ -60,9 +61,10 @@ void BotTextMgr::Load() speech_.callouts_enabled = sConfigMgr->GetBoolDefault("Playerbot.Chatter.Callouts.Enabled", true, true); speech_.callout_key_cooldown_ms = ms("Playerbot.Chatter.Callouts.KeyCooldownMs", 60000); speech_.callout_group_cooldown_ms = ms("Playerbot.Chatter.Callouts.GroupCooldownMs", 8000); + speech_.callout_taunts = sConfigMgr->GetBoolDefault("Playerbot.Chatter.Callouts.Taunts", false, true); speech_.suggest_enabled = sConfigMgr->GetBoolDefault("Playerbot.Chatter.Suggest.Enabled", true, true); - speech_.suggest_bot_cooldown_ms = std::max(60000, ms("Playerbot.Chatter.Suggest.BotCooldownMs", 1800000)); - speech_.suggest_channel_cooldown_ms = ms("Playerbot.Chatter.Suggest.ChannelCooldownMs", 180000); + speech_.suggest_bot_cooldown_ms = std::max(60000, ms("Playerbot.Chatter.Suggest.BotCooldownMs", 900000)); + speech_.suggest_channel_cooldown_ms = ms("Playerbot.Chatter.Suggest.ChannelCooldownMs", 90000); speech_.suggest_global_cooldown_ms = ms("Playerbot.Chatter.Suggest.GlobalCooldownMs", 10000); speech_.global_max_per_minute = ms("Playerbot.Chatter.GlobalMaxPerMinute", 60); @@ -164,6 +166,9 @@ BotTextMgr::Line BotTextMgr::Pick(std::string_view key, TextPlaceholders const& out.text = row->text; out.yell = row->say_type == 1; Fill(out.text, ph); + // A placeholder the caller did not fill ("" from a line meant for another kind of speech) is never said. + if (V2::ChannelTalk::HasUnfilledPlaceholder(out.text)) + out.text.clear(); return out; } @@ -772,7 +777,7 @@ void Callouts(BotAI& ai, BotSnapshotView const& s, BotIntentEmitter& em, uint32 else if (hp_worse && hp_band == 1) { kind = CK_LowHealth; key = "low health"; } else if (mana_worse) { kind = CK_LowMana; key = "low mana"; } else if (ammo_worse && ammo_band == 1) { kind = CK_LowAmmo; key = "low ammo"; } - else if (taunt_target && !st.taunt_said) { kind = CK_Taunt; key = "taunt"; st.taunt_said = true; } + else if (taunt_target && !st.taunt_said && cfg.callout_taunts) { kind = CK_Taunt; key = "taunt"; st.taunt_said = true; } else if (big_pull && !st.aoe_said) { kind = CK_Aoe; key = "aoe"; st.aoe_said = true; } st.primed = true; diff --git a/src/modules/PlayerbotV2/Bot/BotTextMgr.h b/src/modules/PlayerbotV2/Bot/BotTextMgr.h index 7dc51078ca..6fb0e694d3 100644 --- a/src/modules/PlayerbotV2/Bot/BotTextMgr.h +++ b/src/modules/PlayerbotV2/Bot/BotTextMgr.h @@ -97,9 +97,10 @@ public: bool callouts_enabled = true; uint32 callout_key_cooldown_ms = 60000; uint32 callout_group_cooldown_ms = 8000; + bool callout_taunts = false; // a tank's taunt line at a loose mob (ike3 pool, many are villain quotes) bool suggest_enabled = true; - uint32 suggest_bot_cooldown_ms = 1800000; - uint32 suggest_channel_cooldown_ms = 180000; + uint32 suggest_bot_cooldown_ms = 900000; + uint32 suggest_channel_cooldown_ms = 90000; uint32 suggest_global_cooldown_ms = 10000; uint32 global_max_per_minute = 60; }; diff --git a/src/modules/PlayerbotV2/Bot/CcDeny.h b/src/modules/PlayerbotV2/Bot/CcDeny.h new file mode 100644 index 0000000000..09af0e9a49 --- /dev/null +++ b/src/modules/PlayerbotV2/Bot/CcDeny.h @@ -0,0 +1,195 @@ +// CcDeny.h - the owner's crowd-control orders: "no fear", "@warlock no fear", "@mages no sheep", "yes sheep", "off cc", "on cc". +// +// An order names a kind of crowd control (or all of it with "cc") and, optionally, a class. The owner's choice is kept per account +// and class (OwnerRegistry::CcDenied) and mirrored into each bot's snapshot (BotSnapshot::cc_deny); BotIntentEmitter drops a cast of +// a denied kind and MarkCc::PickOption skips it, so a rotation falls through to its next rule and no mob is held for a cast that +// never comes. Stuns, roots, snares and interrupts are not crowd control here: they stay part of the rotations. +// Pure text and spell ids: no Player, no SpellMgr (the emitter adds the mechanic fallback for spells missing from the table). +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace Playerbot::CcDeny { + +enum Kind : uint16_t +{ + Fear = 1u << 0, // Fear, Howl of Terror, Death Coil, Psychic Scream, Intimidating Shout, Scare Beast, Turn Undead + Polymorph = 1u << 1, + Banish = 1u << 2, + Shackle = 1u << 3, + Sap = 1u << 4, + Sleep = 1u << 5, // Hibernate, Wyvern Sting + Trap = 1u << 6, // Freezing Trap + Charm = 1u << 7, // Seduction, Enslave Demon, Mind Control + All = 0xFF, +}; + +// The kind a crowd-control spell belongs to (every rank listed: the 70532 data does not chain every one), 0 = not crowd control. +inline uint16_t KindOfSpell(uint32_t spell) +{ + switch (spell) + { + case 5782: case 6213: case 6215: // Fear + case 5484: case 17928: // Howl of Terror + case 6789: case 17925: case 17926: // Death Coil (the mob runs in horror) + case 8122: case 8124: case 10888: case 10890: // Psychic Scream + case 5246: // Intimidating Shout + case 1513: case 14326: case 14327: // Scare Beast + case 2878: case 5627: case 10326: // Turn Undead + return Fear; + case 118: case 12824: case 12825: case 12826: case 28271: case 28272: + return Polymorph; + case 710: case 18647: + return Banish; + case 9484: case 9485: case 10955: + return Shackle; + case 6770: case 2070: case 11297: + return Sap; + case 2637: case 18657: case 18658: // Hibernate + case 19386: case 24132: case 24133: // Wyvern Sting + return Sleep; + case 1499: case 14310: case 14311: + return Trap; + case 6358: // Seduction (Succubus) + case 1098: case 11725: case 11726: // Enslave Demon + case 605: case 10911: case 10912: // Mind Control + return Charm; + default: + return 0; + } +} + +// "fear", "sheep", "cc" (= every kind) ... -> the kind, 0 = not a crowd-control word. +inline uint16_t KindOfWord(std::string_view w) +{ + static constexpr std::pair kWords[] = { + { "fear", Fear }, { "fears", Fear }, { "howl", Fear }, { "scream", Fear }, { "horror", Fear }, { "scare", Fear }, + { "sheep", Polymorph }, { "sheeps", Polymorph }, { "poly", Polymorph }, { "polys", Polymorph }, { "polymorph", Polymorph }, + { "morph", Polymorph }, { "pig", Polymorph }, { "turtle", Polymorph }, + { "banish", Banish }, { "banishes", Banish }, + { "shackle", Shackle }, { "shackles", Shackle }, + { "sap", Sap }, { "saps", Sap }, + { "sleep", Sleep }, { "hibernate", Sleep }, { "wyvern", Sleep }, { "wyvern sting", Sleep }, + { "trap", Trap }, { "traps", Trap }, { "freezing trap", Trap }, + { "charm", Charm }, { "seduce", Charm }, { "seduction", Charm }, { "enslave", Charm }, { "mc", Charm }, { "mind control", Charm }, + { "cc", All }, + }; + for (auto const& [word, kind] : kWords) + if (w == word) + return kind; + return 0; +} + +// The kinds in `mask` as words ("fear, polymorph"), "all crowd control" for every kind, "nothing" for none. +inline std::string Describe(uint16_t mask) +{ + if ((mask & All) == All) + return "all crowd control"; + static constexpr std::pair kNames[] = { + { Fear, "fear" }, { Polymorph, "polymorph" }, { Banish, "banish" }, { Shackle, "shackle" }, + { Sap, "sap" }, { Sleep, "sleep" }, { Trap, "freezing trap" }, { Charm, "charm" }, + }; + std::string out; + for (auto const& [bit, name] : kNames) + if (mask & bit) + out += (out.empty() ? "" : ", ") + std::string(name); + return out.empty() ? "nothing" : out; +} + +// Class ids (ChrClasses: CLASS_WARRIOR 1 ... CLASS_EVOKER 13) by the name a player types, singular or plural, 0 = none. +inline uint8_t ClassOfWord(std::string_view w) +{ + static constexpr std::pair kClasses[] = { + { "warrior", 1 }, { "paladin", 2 }, { "pally", 2 }, { "pallies", 2 }, { "hunter", 3 }, { "rogue", 4 }, { "priest", 5 }, + { "deathknight", 6 }, { "dk", 6 }, { "shaman", 7 }, { "mage", 8 }, { "warlock", 9 }, { "lock", 9 }, { "monk", 10 }, + { "druid", 11 }, { "demonhunter", 12 }, { "dh", 12 }, { "evoker", 13 }, + }; + for (auto const& [name, cls] : kClasses) + if (w == name || (w.size() == name.size() + 1 && w.back() == 's' && w.substr(0, name.size()) == name)) + return cls; + return 0; +} + +// The plural a reply names a class by ("warlocks"); "every class" for 0. +inline std::string ClassPlural(uint8_t cls) +{ + static constexpr char const* kNames[] = { "every class", "warriors", "paladins", "hunters", "rogues", "priests", "death knights", + "shamans", "mages", "warlocks", "monks", "druids", "demon hunters", "evokers" }; + return cls < std::size(kNames) ? kNames[cls] : "that class"; +} + +// A parsed order: deny (true) or allow `kinds` for class `cls` (0 = every class). +struct Order +{ + uint8_t cls = 0; + bool deny = true; + uint16_t kinds = 0; + bool operator==(Order const&) const = default; +}; + +// Reads one chat line as a crowd-control order, else nullopt (any other order or chatter). Accepted, case-insensitive: +// [@ | : | ] (no | off | deny | dont | don't) e.g. "@warlock no fear", "mages no sheep", "off cc" +// [...] (yes | on | allow) e.g. "@mage yes sheep", "on cc" +// [...] (off | no | on | yes) e.g. "cc off", "fear on" +// is a word of KindOfWord ("freezing trap", "mind control" as two words). The panel's "crowdcontrol on|off" is not an order +// here: it is the marked crowd-control switch alone (OwnerRegistry::SetCcEnabled). +inline std::optional ParseOrder(std::string_view line) +{ + std::string text(line); + std::transform(text.begin(), text.end(), text.begin(), [](unsigned char c) { return char(std::tolower(c)); }); + std::vector words; + for (size_t i = 0; i < text.size();) + { + size_t const b = text.find_first_not_of(" \t,", i); + if (b == std::string::npos) break; + size_t const e = text.find_first_of(" \t,", b); + words.push_back(text.substr(b, e == std::string::npos ? std::string::npos : e - b)); + i = e == std::string::npos ? text.size() : e; + } + if (words.size() < 2) + return std::nullopt; + Order out; + // The class address: "@warlock", "warlock:", "warlocks". + { + std::string first = words.front(); + bool const at = first.front() == '@'; + if (at) first.erase(0, 1); + if (!first.empty() && first.back() == ':') first.pop_back(); + if (uint8_t const cls = ClassOfWord(first)) + { + out.cls = cls; + words.erase(words.begin()); + } + else if (at) + return std::nullopt; // "@skull no ..." and other selectors are not class orders + } + if (words.size() < 2 || words.size() > 3) + return std::nullopt; + auto const verb = [](std::string const& w) -> int // 1 deny, 2 allow, 0 neither + { + if (w == "no" || w == "off" || w == "deny" || w == "dont" || w == "don't") return 1; + if (w == "yes" || w == "on" || w == "allow") return 2; + return 0; + }; + std::string kind_text; + int v = verb(words.front()); + if (v) + kind_text = words.size() == 3 ? words[1] + " " + words[2] : words[1]; + else if ((v = verb(words.back()))) + kind_text = words.size() == 3 ? words[0] + " " + words[1] : words[0]; + else + return std::nullopt; + out.kinds = KindOfWord(kind_text); + if (!out.kinds) + return std::nullopt; + out.deny = v == 1; + return out; +} + +} // namespace Playerbot::CcDeny diff --git a/src/modules/PlayerbotV2/Bot/ChannelChat.cpp b/src/modules/PlayerbotV2/Bot/ChannelChat.cpp new file mode 100644 index 0000000000..856efb0f31 --- /dev/null +++ b/src/modules/PlayerbotV2/Bot/ChannelChat.cpp @@ -0,0 +1,365 @@ +#include "ChannelChat.h" + +#include "BotAI.h" +#include "BotChatReactor.h" +#include "BotIntent.h" +#include "BotPersonality.h" +#include "BotRegistry.h" +#include "BotTextMgr.h" +#include "BotTrade.h" +#include "BotTradeShop.h" +#include "ChannelTalk.h" +#include "ClassTables.h" +#include "../Api/ClassicSpec.h" +#include "../Fleet/BotPopulationManager.h" +#include "../LfgBotFill.h" +#include "../Services.h" +#include "../Threading/IntentQueue.h" +#include "../Util/ConfigReader.h" + +#include "Channel.h" +#include "DB2Stores.h" +#include "GameTime.h" +#include "Log.h" +#include "Map.h" +#include "ObjectAccessor.h" +#include "Player.h" +#include "Random.h" +#include "WorldSession.h" + +#include +#include +#include +#include +#include + +namespace Playerbot::V2::ChannelChat +{ + +namespace +{ + +namespace CT = ChannelTalk; + +constexpr uint32 kGeneral = 1; +constexpr uint32 kTrade = 2; +constexpr uint32 kSenderCooldownMs = 20000; // one answered line per player per 20 s +constexpr uint32 kChannelCooldownMs = 12000; // one rule answer (question / greeting) per channel and zone per 12 s +constexpr uint32 kLfgCallGapMs = 20000; // bots' own LFG calls: one per faction per 20 s + +std::mutex g_mtx; +std::unordered_map g_sender_ms; +std::unordered_map g_channel_ms; +std::array g_lfg_call_ms{}; +CT::RecentLines g_recent_calls; +AnswerHook g_hook = nullptr; + +bool Elapsed(uint32 now, uint32 then, uint32 gap) { return then == 0 || now - then >= gap; } + +template +void Prune(Map& m, uint32 now, uint32 keep) +{ + if (m.size() < 512) + return; + for (auto it = m.begin(); it != m.end();) + it = (now - it->second > keep) ? m.erase(it) : std::next(it); +} + +enum class Reach : uint8 { None, Zone, City, Faction }; + +Reach ReachOf(Channel const* ch, uint32 lfg_id) +{ + uint32 const id = ch->GetChannelId(); + if (!id) + return Reach::None; // a custom channel + if (id == kGeneral) + return Reach::Zone; + if (id == kTrade) + return Reach::City; + if (id == lfg_id || ch->IsLFG()) + return Reach::Faction; + return Reach::None; +} + +bool InCity(Player const* p) +{ + AreaTableEntry const* zone = sAreaTableStore.LookupEntry(p->GetZoneId()); + return zone && zone->GetFlags().HasFlag(AreaFlags::AllowTradeChannel); +} + +uint8 RoleBitOf(Player const* p) +{ + uint8 const cls = p->GetClass(); + uint16 const spec = uint16(::Playerbot::Classic::EffectiveSpecId(p)); + if (IsTankSpec(cls, spec)) return CT::kTank; + if (IsHealerSpec(cls, spec)) return CT::kHealer; + return CT::kDps; +} + +struct Cand +{ + Player* bot; + BotId id; + BotAI* ai; +}; + +// The world bots that read this channel line: same faction, free (no owner, no group), awake and not busy, in the channel's reach. +std::vector Readers(Player* sender, Reach reach) +{ + std::vector ids; + Services::Registry().for_each([&](BotId id, BotRegistryEntry const&) { ids.push_back(id); }); + std::vector out; + auto& pop = Services::Population(); + for (BotId id : ids) + { + Player* p = ObjectAccessor::FindConnectedPlayer(ObjectGuid::Create(uint64(id))); + if (!p || p == sender || !p->IsInWorld() || !p->IsAlive() || p->IsInCombat() || p->GetGroup() || p->InBattleground() + || p->InArena() || p->IsBeingTeleported() || !p->GetSocial()) + continue; + if (p->GetTeam() != sender->GetTeam()) + continue; + if (Map const* m = p->GetMap(); !m || m->Instanceable()) + continue; + if (!pop.IsAmbientBot(id, p)) + continue; + if (reach == Reach::Zone && p->GetZoneId() != sender->GetZoneId()) + continue; + if (reach == Reach::City && !InCity(p)) + continue; + BotAI* ai = Services::Registry().ai(id); + if (!ai || ai->personality().verbosity == Verbosity::Silent) + continue; + out.push_back({ p, id, ai }); + } + // A different order each time, so the same bot is not always the one who answers. + for (std::size_t i = out.size(); i > 1; --i) + std::swap(out[i - 1], out[urand(0, uint32(i - 1))]); + return out; +} + +void Whisper(BotId bot, std::string const& to, std::string text, uint32 when_ms) +{ + Intent it{}; + it.bot_id = bot; + it.body = ChatIntent{ WhisperIntent{ to, std::move(text) } }; + it.defer_until_ms = when_ms; + Services::Intents(bot).push(std::move(it)); +} + +bool LevelOk(Player const* bot, CT::Ask const& a, uint32 player_level) +{ + if (a.dungeon != CT::kNoDungeon) + return CT::LevelFits(a.dungeon, bot->GetLevel(), 1); + int const d = int(bot->GetLevel()) - int(player_level); + return d >= -3 && d <= 3; +} + +// LFM: one bot per wanted role (two at most) whispers to be invited. +void AnswerLfm(Player* sender, CT::Ask const& a, std::vector const& readers, uint32 now) +{ + uint32 offered = 0, delay = 3000u + urand(0, 6000); + for (uint8 bit : { uint8(CT::kTank), uint8(CT::kHealer), uint8(CT::kDps) }) + { + if (!(a.roles & bit) || offered >= 2) + continue; + for (Cand const& c : readers) + { + if (RoleBitOf(c.bot) != bit || !LevelOk(c.bot, a, sender->GetLevel())) + continue; + std::string line = CT::OfferLine(bit, a.dungeon, c.bot->GetLevel(), urand(0, 0xFFFF)); + TC_LOG_INFO("playerbot.v2", "[channel] lfm {} -> {}: {}", c.bot->GetName(), sender->GetName(), line); + Whisper(c.id, sender->GetName(), std::move(line), now + delay); + delay += 2000u + urand(0, 6000); + ++offered; + break; + } + } +} + +// LFG: a listed bot group with a place for him first; else a free bot of his level offers to come along. +void AnswerLfg(Player* sender, CT::Ask const& a, std::vector const& readers, uint32 now) +{ + uint32 const map = a.dungeon != CT::kNoDungeon ? CT::kDungeons[a.dungeon].map : 0u; + if (Player* member = LfgBotGroupMemberFor(sender, map)) + { + int dungeon = a.dungeon; + if (dungeon == CT::kNoDungeon) + for (std::size_t i = 0; i < CT::kDungeonCount; ++i) + if (CT::LevelFits(int(i), sender->GetLevel())) { dungeon = int(i); break; } + std::string line = CT::GroupSpotLine(dungeon, urand(0, 0xFFFF)); + TC_LOG_INFO("playerbot.v2", "[channel] lfg group {} -> {}: {}", member->GetName(), sender->GetName(), line); + Whisper(BotId(member->GetGUID().GetCounter()), sender->GetName(), std::move(line), now + 4000u + urand(0, 8000)); + return; + } + if (urand(0, 99) >= 60) + return; + for (Cand const& c : readers) + { + uint8 const bit = RoleBitOf(c.bot); + if ((a.roles & bit) || !LevelOk(c.bot, a, sender->GetLevel())) + continue; // a second player of his own role is no help to him + std::string line = CT::OfferLine(bit, a.dungeon, c.bot->GetLevel(), urand(0, 0xFFFF)); + TC_LOG_INFO("playerbot.v2", "[channel] lfg {} -> {}: {}", c.bot->GetName(), sender->GetName(), line); + Whisper(c.id, sender->GetName(), std::move(line), now + 5000u + urand(0, 10000)); + return; + } +} + +// WTB: the first bot within reach that sells it whispers the price; "buy 1" and a trade window then run the usual trade talk. +void AnswerWtb(Player* sender, CT::Ask const& a, std::vector const& readers, uint32 now) +{ + uint32 checked = 0; + for (Cand const& c : readers) + { + if (++checked > 24) + break; + for (TradeShop::Offer const& o : TradeShop::BuildOffers(c.bot, 30)) + { + bool const match = a.item_entry ? o.entry == a.item_entry + : CT::Lower(o.name).find(a.item_name) != std::string::npos; + if (!match) + continue; + TradeShop::StoreList(c.bot, sender, { o }); + std::string line = "i have " + o.name + (o.count > 1 ? " x" + std::to_string(o.count) : std::string()) + " for " + + BotTrade::FormatMoney(o.price) + ", whisper me \"buy 1\" and open a trade"; + TC_LOG_INFO("playerbot.v2", "[channel] wtb {} -> {}: {}", c.bot->GetName(), sender->GetName(), line); + Whisper(c.id, sender->GetName(), std::move(line), now + 6000u + urand(0, 12000)); + return; + } + } +} + +bool TakeChannelSlot(uint64 key, uint32 now) +{ + std::lock_guard lk(g_mtx); + auto it = g_channel_ms.find(key); + if (it != g_channel_ms.end() && !Elapsed(now, it->second, kChannelCooldownMs)) + return false; + Prune(g_channel_ms, now, kChannelCooldownMs * 4); + g_channel_ms[key] = now ? now : 1u; + return true; +} + +} // namespace + +void SetAnswerHook(AnswerHook hook) +{ + std::lock_guard lk(g_mtx); + g_hook = hook; +} + +void Post(BotId bot, uint32 channel_id, std::string text, uint32 when_ms) +{ + if (text.empty() || channel_id == 0 || channel_id > 255) + return; + Intent it{}; + it.bot_id = bot; + it.body = ChatIntent{ ChannelChatIntent{ uint8(channel_id), std::move(text) } }; + it.defer_until_ms = when_ms; + Services::Intents(bot).push(std::move(it)); +} + +uint32 LfgChannelId() +{ + static uint32 const id = [] + { + for (ChatChannelsEntry const* e : sChatChannelsStore) + if (e && e->GetFlags().HasFlag(ChatChannelFlags::LookingForGroup) && e->ID <= 255) + return uint32(e->ID); + return 0u; + }(); + return id; +} + +bool LfgCallSlot(bool alliance, std::string const& line, uint32 now_ms) +{ + std::lock_guard lk(g_mtx); + uint32& last = g_lfg_call_ms[alliance ? 0 : 1]; + if (!Elapsed(now_ms, last, kLfgCallGapMs) || g_recent_calls.Seen(line)) + return false; + last = now_ms ? now_ms : 1u; + g_recent_calls.Note(line); + return true; +} + +void OnPlayerLine(Player* sender, Channel* ch, std::string const& msg) +{ + if (!sender || !ch || msg.empty() || !Services::Initialized() || !Services::Config().chatter_channel_replies()) + return; + if (!sender->GetSession() || sender->GetSession()->IsBot()) + return; + if (msg.front() == '.' || msg.front() == ';' || msg.front() == '!') + return; + Reach const reach = ReachOf(ch, LfgChannelId()); + if (reach == Reach::None) + return; + CT::Ask const a = CT::Parse(msg); + if (a.kind == CT::Kind::None) + return; + + uint32 const now = GameTime::GetGameTimeMS(); + { + std::lock_guard lk(g_mtx); + uint64 const key = sender->GetGUID().GetCounter(); + auto it = g_sender_ms.find(key); + if (it != g_sender_ms.end() && !Elapsed(now, it->second, kSenderCooldownMs)) + return; + Prune(g_sender_ms, now, kSenderCooldownMs * 4); + g_sender_ms[key] = now ? now : 1u; + } + + std::vector const readers = Readers(sender, reach); + if (readers.empty()) + return; + + switch (a.kind) + { + case CT::Kind::LookingForMore: AnswerLfm(sender, a, readers, now); return; + case CT::Kind::LookingForGroup: AnswerLfg(sender, a, readers, now); return; + case CT::Kind::WantToBuy: AnswerWtb(sender, a, readers, now); return; + default: break; + } + + // A question or a greeting is answered in the channel, by one bot, now and then. + uint32 const pct = a.kind == CT::Kind::Question ? Services::Config().chatter_channel_question_pct() + : Services::Config().chatter_channel_greet_pct(); + if (urand(0, 99) >= pct) + return; + uint64 const slot = (uint64(sender->GetTeam()) << 48) | (uint64(ch->GetChannelId()) << 32) | (reach == Reach::Zone ? sender->GetZoneId() : 0u); + if (!TakeChannelSlot(slot, now)) + return; + Cand const* chosen = nullptr; + for (Cand const& c : readers) + if (c.ai->personality().verbosity >= Verbosity::Normal) { chosen = &c; break; } + if (!chosen) + return; + + std::string reply; + if (a.kind == CT::Kind::Greeting) + { + if (BotTextMgr::instance().Enabled()) + reply = BotTextMgr::instance().GetReply(ReplyType::Hello, sender->GetName()); + if (reply.empty()) + { + static constexpr char const* kHi[] = { "hey", "o/", "hi", "hello", "heya", "hey there", "yo" }; + reply = kHi[urand(0, uint32(std::size(kHi)) - 1)]; + } + } + else if (!BotChatReactor::SmallTalk(chosen->bot, sender, msg, reply)) + { + AnswerHook hook; + { + std::lock_guard lk(g_mtx); + hook = g_hook; + } + if (hook && hook(chosen->bot, sender, ch->GetChannelId(), msg)) + TC_LOG_INFO("playerbot.v2", "[channel] {} hands {}'s line to the answer hook", chosen->bot->GetName(), sender->GetName()); + return; + } + if (reply.empty() || CT::HasUnfilledPlaceholder(reply)) + return; + TC_LOG_INFO("playerbot.v2", "[channel] {} answers {} in channel {}: {}", chosen->bot->GetName(), sender->GetName(), ch->GetChannelId(), reply); + Post(chosen->id, ch->GetChannelId(), std::move(reply), now + 2500u + urand(0, 5000)); +} + +} // namespace Playerbot::V2::ChannelChat diff --git a/src/modules/PlayerbotV2/Bot/ChannelChat.h b/src/modules/PlayerbotV2/Bot/ChannelChat.h new file mode 100644 index 0000000000..ea78aadf52 --- /dev/null +++ b/src/modules/PlayerbotV2/Bot/ChannelChat.h @@ -0,0 +1,46 @@ +// ChannelChat - bots answer what real players write in General, Trade and LookingForGroup (Playerbot.Chatter.ChannelReplies.*). +// +// LFM ("LF healer DM") a free world bot of the wanted role and level whispers the player to invite it (one per role, two at most). +// LFG ("lfg sfk") a listed bot group with a place whispers him to join; else a free bot of his level offers to come. +// WTB ("wtb [Linen Cloth]") a bot in the channel's reach that has it whispers its price; "buy 1" and a trade then work as usual. +// a question now and then one bot answers in the channel from its own state (BotConversation); a line the rules +// do not understand goes to the answer hook, when one is set. +// a greeting now and then one bot says hi back. +// The channel's reach decides who may answer: General the bots in the player's zone, Trade the bots in a city of his faction, +// LookingForGroup any bot of his faction. Only world bots answer (no owner, not grouped). The line parsing is Bot/ChannelTalk.h. +// +// The bots' own LFG calls (idle:yell_lfg) go to the LookingForGroup channel and General through LfgCallSlot / Post. +// +// World thread only. +#pragma once + +#include "Define.h" +#include "Bot/BotTypes.h" + +#include + +class Channel; +class Player; + +namespace Playerbot::V2::ChannelChat +{ + +// A real player wrote `msg` in the system channel `ch` (from the chat hook, before the line is sent). +void OnPlayerLine(Player* sender, Channel* ch, std::string const& msg); + +// An answer source for channel lines the rules leave unanswered (a chat model, for one). Called on the world thread with the bot +// chosen to answer; return true when it takes the line (it then answers later through Post), false to let the line go. Must not +// block. nullptr clears it. +using AnswerHook = bool (*)(Player* bot, Player* sender, uint32 channel_id, std::string const& msg); +void SetAnswerHook(AnswerHook hook); + +// `bot` writes `text` in its channel `channel_id` (1 General, 2 Trade, LfgChannelId()) at `when_ms` (game time, 0 = now). +void Post(BotId bot, uint32 channel_id, std::string text, uint32 when_ms = 0); + +// The LookingForGroup channel of the client's ChatChannels table, 0 when it has none. +uint32 LfgChannelId(); + +// One LFG call per faction per 20 s realm-wide, and never a line that went out recently. True = `line` may be posted now (noted). +bool LfgCallSlot(bool alliance, std::string const& line, uint32 now_ms); + +} // namespace Playerbot::V2::ChannelChat diff --git a/src/modules/PlayerbotV2/Bot/ChannelTalk.h b/src/modules/PlayerbotV2/Bot/ChannelTalk.h new file mode 100644 index 0000000000..12611bf9e5 --- /dev/null +++ b/src/modules/PlayerbotV2/Bot/ChannelTalk.h @@ -0,0 +1,394 @@ +// ChannelTalk - reading what a real player writes in General, Trade or LookingForGroup, and the lines bots post there. Pure: no +// Player / BotAI access, tested offline (tests/game/ClassicChannelTalk.cpp). Bot/ChannelChat.cpp applies it to the live world. +// +// A line is one of: a player looking for members (LFM, "LF healer", "need tank"), a player looking for a group (LFG, "lfg dm"), a +// want-to-buy (WTB, with an item link or a name), a question, a greeting, or nothing a bot answers. +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Playerbot::V2::ChannelTalk +{ + +enum class Kind : std::uint8_t { None, LookingForMore, LookingForGroup, WantToBuy, Question, Greeting }; + +enum RoleBits : std::uint8_t { kTank = 1, kHealer = 2, kDps = 4 }; + +// The 1.12 dungeons by the words players use for them. `map` is the instance map, the level range is the usual party's. +struct Dungeon { char const* name; std::uint32_t map; std::uint8_t lo, hi; }; +inline constexpr Dungeon kDungeons[] = { + { "Ragefire Chasm", 389, 13, 18 }, { "Wailing Caverns", 43, 17, 24 }, { "the Deadmines", 36, 17, 26 }, + { "Shadowfang Keep", 33, 20, 30 }, { "Blackfathom Deeps", 48, 24, 32 }, { "the Stockade", 34, 24, 32 }, + { "Gnomeregan", 90, 29, 38 }, { "Razorfen Kraul", 47, 29, 38 }, { "the Scarlet Monastery", 189, 30, 45 }, + { "Razorfen Downs", 129, 37, 46 }, { "Uldaman", 70, 41, 51 }, { "Zul'Farrak", 209, 44, 54 }, + { "Maraudon", 349, 46, 55 }, { "the Sunken Temple", 109, 50, 60 }, { "Blackrock Depths", 230, 52, 60 }, + { "Lower Blackrock Spire", 229, 55, 60 }, { "Upper Blackrock Spire", 229, 58, 60 }, { "Dire Maul", 429, 56, 60 }, + { "Stratholme", 329, 58, 60 }, { "Scholomance", 289, 58, 60 }, +}; +constexpr std::size_t kDungeonCount = sizeof(kDungeons) / sizeof(kDungeons[0]); +constexpr int kNoDungeon = -1; + +struct Ask +{ + Kind kind = Kind::None; + std::uint8_t roles = 0; // LookingForMore: the places wanted; LookingForGroup: the role the player says he plays + int dungeon = kNoDungeon; // index into kDungeons + std::uint32_t item_entry = 0; // WantToBuy with an item link + std::string item_name; // WantToBuy: the link's name or the words after "wtb", lower-case +}; + +inline std::string Lower(std::string s) +{ + for (char& c : s) + c = char(std::tolower(static_cast(c))); + return s; +} + +// Replaces each item link (|cff..|Hitem:ENTRY:...|h[Name]|h|r) by its name; the first link's entry and name come out. +inline std::string StripLinks(std::string const& raw, std::uint32_t& first_entry, std::string& first_name) +{ + first_entry = 0; + first_name.clear(); + std::string out; + out.reserve(raw.size()); + std::size_t i = 0; + while (i < raw.size()) + { + if (raw[i] == '|' && i + 1 < raw.size()) + { + char const t = raw[i + 1]; + if (t == 'c' && i + 10 <= raw.size()) { i += 10; continue; } // |cAARRGGBB + if (t == 'r') { i += 2; continue; } + if (t == 'H') + { + std::size_t const end = raw.find("|h", i + 2); + if (end == std::string::npos) { i += 2; continue; } + std::string_view const link(raw.data() + i + 2, end - (i + 2)); + if (link.rfind("item:", 0) == 0 && !first_entry) + first_entry = std::uint32_t(std::strtoul(std::string(link.substr(5)).c_str(), nullptr, 10)); + i = end + 2; + std::size_t const close = raw.find("|h", i); + std::string name = raw.substr(i, close == std::string::npos ? std::string::npos : close - i); + if (name.size() >= 2 && name.front() == '[' && name.back() == ']') + name = name.substr(1, name.size() - 2); + if (first_name.empty() && first_entry) + first_name = Lower(name); + out += name; + i = close == std::string::npos ? raw.size() : close + 2; + continue; + } + } + out += raw[i++]; + } + return out; +} + +// Words of a lower-case line: letters, digits and apostrophes; everything else separates. +inline std::vector Words(std::string const& lower) +{ + std::vector w; + std::string cur; + for (char c : lower) + { + if (std::isalnum(static_cast(c)) || c == '\'') + cur += c; + else if (!cur.empty()) + { + w.push_back(cur); + cur.clear(); + } + } + if (!cur.empty()) + w.push_back(cur); + return w; +} + +inline bool HasWord(std::vector const& w, std::string_view x) +{ + return std::find(w.begin(), w.end(), x) != w.end(); +} + +inline bool HasPhrase(std::string const& lower, std::string_view x) +{ + return lower.find(x) != std::string::npos; +} + +// The dungeon the line names, kNoDungeon when none. +inline int FindDungeon(std::vector const& w, std::string const& lower) +{ + struct Alias { char const* word; int idx; }; + static constexpr Alias kWords[] = { + { "rfc", 0 }, { "ragefire", 0 }, { "wc", 1 }, { "wailing", 1 }, { "dm", 2 }, { "vc", 2 }, { "deadmines", 2 }, { "deadmine", 2 }, + { "sfk", 3 }, { "shadowfang", 3 }, { "bfd", 4 }, { "blackfathom", 4 }, { "stocks", 5 }, { "stockade", 5 }, { "stockades", 5 }, + { "gnomer", 6 }, { "gnomeregan", 6 }, { "rfk", 7 }, { "kraul", 7 }, { "sm", 8 }, { "scarlet", 8 }, { "cath", 8 }, { "armory", 8 }, + { "lib", 8 }, { "library", 8 }, { "gy", 8 }, { "rfd", 9 }, { "downs", 9 }, { "ulda", 10 }, { "uld", 10 }, { "uldaman", 10 }, + { "zf", 11 }, { "zul'farrak", 11 }, { "zulfarrak", 11 }, { "mara", 12 }, { "maraudon", 12 }, { "st", 13 }, { "sunken", 13 }, + { "brd", 14 }, { "lbrs", 15 }, { "ubrs", 16 }, { "dme", 17 }, { "dmw", 17 }, { "dmn", 17 }, { "strat", 18 }, + { "stratholme", 18 }, { "strath", 18 }, { "scholo", 19 }, { "scholomance", 19 }, { "scholo's", 19 }, + }; + if (HasPhrase(lower, "dire maul")) return 17; + if (HasPhrase(lower, "blackrock depths")) return 14; + if (HasPhrase(lower, "lower blackrock") || HasPhrase(lower, "lower spire")) return 15; + if (HasPhrase(lower, "upper blackrock") || HasPhrase(lower, "upper spire")) return 16; + if (HasPhrase(lower, "sunken temple") || HasPhrase(lower, "temple of atal")) return 13; + for (std::string const& x : w) + for (Alias const& a : kWords) + if (x == a.word) + return a.idx; + return kNoDungeon; +} + +inline std::uint8_t FindRoles(std::vector const& w) +{ + std::uint8_t r = 0; + for (std::string const& x : w) + { + if (x == "tank" || x == "tanks" || x == "mt" || x == "prot") r |= kTank; + else if (x == "heal" || x == "heals" || x == "healer" || x == "healers" || x == "heala" || x == "heale") r |= kHealer; + else if (x == "dps" || x == "dd" || x == "damage" || x == "melee" || x == "caster" || x == "rdps" || x == "mdps") r |= kDps; + } + return r; +} + +inline bool IsLfmWord(std::string const& x) +{ + if (x == "lfm" || x == "lf" || x == "need" || x == "needs" || x == "lfmore") return true; + // lf1m, lf2m, lf3m, lf4m + return x.size() == 4 && x[0] == 'l' && x[1] == 'f' && std::isdigit(static_cast(x[2])) && x[3] == 'm'; +} + +// Reads one channel line. +inline Ask Parse(std::string const& raw) +{ + Ask a; + std::uint32_t entry = 0; + std::string link_name; + std::string const lower = Lower(StripLinks(raw, entry, link_name)); + std::vector const w = Words(lower); + if (w.empty()) + return a; + + bool const wtb = HasWord(w, "wtb") || (w.front() == "buying") || HasPhrase(lower, "want to buy") || HasPhrase(lower, "looking to buy"); + if (wtb) + { + a.kind = Kind::WantToBuy; + a.item_entry = entry; + if (!link_name.empty()) + a.item_name = link_name; + else + { + // The words after the verb, up to a price or a "pst". + std::size_t start = 0; + for (std::size_t i = 0; i < w.size(); ++i) + if (w[i] == "wtb" || w[i] == "buying" || w[i] == "buy") { start = i + 1; break; } + std::string name; + for (std::size_t i = start; i < w.size(); ++i) + { + std::string const& x = w[i]; + if (x == "pst" || x == "pm" || x == "whisper" || x == "w" || x == "for" || x == "paying" || x == "msg" || x == "me") break; + bool const count = (x.size() >= 2 && x[0] == 'x' && std::isdigit(static_cast(x[1]))) + || std::all_of(x.begin(), x.end(), [](char c) { return std::isdigit(static_cast(c)); }); + if (count) continue; + if (!name.empty()) name += ' '; + name += x; + if (name.size() > 40) break; + } + a.item_name = name; + } + if (!a.item_entry && a.item_name.size() < 3) + a.kind = Kind::None; + return a; + } + + // "lfm" / "lf2m" always ask for members; "lf" / "need" only with a role or a dungeon ("lf gold farm" is not a group call). + bool strong_lfm = false, weak_lfm = false, lfg = false; + for (std::string const& x : w) + { + if (x == "lfg" || x == "lf2g") lfg = true; + else if (x == "lf" || x == "need" || x == "needs") weak_lfm = true; + else if (IsLfmWord(x)) strong_lfm = true; + } + if (HasPhrase(lower, "looking for group") || HasPhrase(lower, "looking for a group") || HasPhrase(lower, "lf group") + || HasPhrase(lower, "lf a group")) + lfg = true; + if (HasPhrase(lower, "looking for more") || HasPhrase(lower, "looking for a tank") || HasPhrase(lower, "looking for a heal") + || HasPhrase(lower, "looking for dps")) + strong_lfm = true; + std::uint8_t const roles = FindRoles(w); + int const dungeon = FindDungeon(w, lower); + bool const lfm = !lfg && (strong_lfm || (weak_lfm && (roles || dungeon != kNoDungeon))); + if (lfm) + { + a.kind = Kind::LookingForMore; + a.roles = roles ? roles : std::uint8_t(kDps); + a.dungeon = dungeon; + return a; + } + if (lfg) + { + a.kind = Kind::LookingForGroup; + a.roles = roles; + a.dungeon = dungeon; + return a; + } + + std::string const& f = w.front(); + bool const question = raw.find('?') != std::string::npos || f == "where" || f == "how" || f == "anyone" || f == "does" + || f == "what" || f == "who" || f == "is" || f == "can" || HasPhrase(lower, "anyone know"); + if (question && w.size() >= 2) + { + a.kind = Kind::Question; + return a; + } + if (w.size() <= 4 && (f == "hi" || f == "hello" || f == "hey" || f == "heya" || f == "hiya" || f == "yo" || f == "sup" || f == "greetings" + || f == "evening" || f == "morning" || f == "o")) + a.kind = Kind::Greeting; + return a; +} + +// Is `level` inside the dungeon's band (with `slack` levels either way)? +inline bool LevelFits(int dungeon, std::uint32_t level, std::uint32_t slack = 0) +{ + if (dungeon < 0 || std::size_t(dungeon) >= kDungeonCount) + return false; + Dungeon const& d = kDungeons[dungeon]; + return level + slack >= d.lo && level <= std::uint32_t(d.hi) + slack; +} + +// A text left with a placeholder nobody filled ("", "%zone_name"): never say it. +inline bool HasUnfilledPlaceholder(std::string const& text) +{ + for (std::size_t i = 0; i < text.size(); ++i) + { + if (text[i] == '<') + { + std::size_t j = i + 1; + while (j < text.size() && (std::islower(static_cast(text[j])) || text[j] == '_')) ++j; + if (j > i + 1 && j < text.size() && text[j] == '>') return true; + } + else if (text[i] == '%' && i + 2 < text.size() && std::isalpha(static_cast(text[i + 1])) + && (std::isalpha(static_cast(text[i + 2])) || text[i + 2] == '_')) + return true; + } + return false; +} + +// ---- what bots write ---- + +// The whisper a bot sends to a player whose LFM wants its role. +inline std::string ShortName(int dungeon) +{ + if (dungeon < 0 || std::size_t(dungeon) >= kDungeonCount) + return "it"; + std::string n = kDungeons[dungeon].name; + return n.rfind("the ", 0) == 0 ? n.substr(4) : n; +} + +inline std::string OfferLine(std::uint8_t role_bit, int dungeon, std::uint32_t level, std::uint32_t seed) +{ + static constexpr std::array kOpen = { + "inv, {r} here", "{r} lvl {l}, inv pls", "hey, can {r} {d} if you still need one", "inv me, {r}", "{r} here, still need one?", + "can come {r}", "i can {r} {d}, inv", "{r}, ready to go", + }; + std::string s = kOpen[seed % kOpen.size()]; + auto put = [&s](std::string_view key, std::string const& val) + { + for (std::size_t p; (p = s.find(key)) != std::string::npos;) + s.replace(p, key.size(), val); + }; + put("{r}", role_bit == kTank ? std::string("tank") : role_bit == kHealer ? std::string((seed & 8u) ? "heals" : "healer") : std::string("dps")); + put("{d}", ShortName(dungeon)); + put("{l}", std::to_string(level)); + return s; +} + +// The whisper a member of a listed bot group sends to a player looking for a group. +inline std::string GroupSpotLine(int dungeon, std::uint32_t seed) +{ + std::string const d = dungeon >= 0 ? std::string(kDungeons[dungeon].name) : std::string("a run"); + switch (seed % 5) + { + case 0: return "we've got a spot for " + d + ", invite me and you're in"; + case 1: return "need one more for " + d + ", want in? just invite me"; + case 2: return "our " + d + " group has room, inv me to join"; + case 3: return "hey, forming " + d + " now, inv me and i'll pull you in"; + default: return "still lf1m for " + d + ", send me an invite"; + } +} + +// The channel call of a bot that wants a group: role, the dungeon of its level (nullptr = any), its level. Many shapes, so a busy +// LookingForGroup channel does not repeat itself. +inline std::string LfgCallLine(std::uint8_t role_bit, char const* dungeon, std::uint32_t level, std::uint32_t seed) +{ + char const* role = role_bit == kTank ? "tank" : role_bit == kHealer ? "healer" : "dps"; + std::string const lvl = std::to_string(level); + std::string const d = dungeon ? std::string(dungeon) : std::string(); + std::string const dshort = d.rfind("the ", 0) == 0 ? d.substr(4) : d; + std::uint32_t const k = (seed >> 3) % 10; + if (!dungeon) + { + switch (k) + { + case 0: return std::string(role) + " LFG"; + case 1: return std::string("lvl ") + lvl + " " + role + " lfg, anything"; + case 2: return std::string("LFG any dungeon, ") + role; + case 3: return std::string(role) + " looking for a group, whisper me"; + case 4: return std::string("anyone need a ") + role + "?"; + case 5: return std::string(role) + " " + lvl + " lf group"; + case 6: return std::string("lfg, ") + role + ", can go now"; + case 7: return std::string("any groups need a ") + role + "? pst"; + case 8: return std::string(lvl) + " " + role + " LFG"; + default: return std::string("bored, ") + role + " lfg anything"; + } + } + switch (k) + { + case 0: return std::string(role) + " LFG " + dshort; + case 1: return std::string("LFG ") + dshort + ", " + role + " here, whisper me"; + case 2: return std::string("lvl ") + lvl + " " + role + " lfg " + dshort; + case 3: return std::string("anyone running ") + d + "? " + role + " looking"; + case 4: return std::string(role) + " lf " + dshort + " group"; + case 5: return std::string("LFG ") + dshort + " or anything, " + role; + case 6: return std::string("need a ") + role + " for " + dshort + "? pst"; + case 7: return std::string(dshort) + " anyone? " + role + " lvl " + lvl; + case 8: return std::string("lf group ") + dshort + ", " + role; + default: return std::string(role) + " " + lvl + " LFG " + dshort + ", can summon at the stone"; + } +} + +// The last few lines posted, realm-wide, so the same text does not come round again within the window. +class RecentLines +{ +public: + static constexpr std::size_t kKeep = 24; + bool Seen(std::string const& line) const + { + std::uint64_t const h = Hash(line); + return std::find(hashes_.begin(), hashes_.end(), h) != hashes_.end(); + } + void Note(std::string const& line) + { + hashes_[next_ % kKeep] = Hash(line); + ++next_; + } + +private: + static std::uint64_t Hash(std::string const& s) + { + std::uint64_t h = 1469598103934665603ull; + for (char c : Lower(s)) { h ^= std::uint8_t(c); h *= 1099511628211ull; } + return h ? h : 1; + } + std::array hashes_{}; + std::size_t next_ = 0; +}; + +} // namespace Playerbot::V2::ChannelTalk diff --git a/src/modules/PlayerbotV2/Bot/ClassTables.cpp b/src/modules/PlayerbotV2/Bot/ClassTables.cpp index 1e6e763f49..98b3173a47 100644 --- a/src/modules/PlayerbotV2/Bot/ClassTables.cpp +++ b/src/modules/PlayerbotV2/Bot/ClassTables.cpp @@ -241,21 +241,22 @@ bool IsHealerSpec(uint8 cls, uint16 spec) return false; } +// Highest-damage PvE spec per class (raid scorecard + chris's list): Fury, Ret, MM, Combat, Shadow, Enhancement, Fire, Destruction, Cat. uint32 DpsSpecForClass(uint8 cls) { switch (cls) { - case CLASS_WARRIOR: return 71; // Arms + case CLASS_WARRIOR: return 72; // Fury case CLASS_PALADIN: return 70; // Retribution case CLASS_HUNTER: return 254; // Marksmanship (ranged) case CLASS_ROGUE: return 260; // Outlaw/Combat case CLASS_PRIEST: return 258; // Shadow case CLASS_DEATH_KNIGHT: return 251; // Frost case CLASS_SHAMAN: return 263; // Enhancement - case CLASS_MAGE: return 64; // Frost - case CLASS_WARLOCK: return 265; // Affliction + case CLASS_MAGE: return 63; // Fire + case CLASS_WARLOCK: return 267; // Destruction case CLASS_MONK: return 269; // Windwalker - case CLASS_DRUID: return 102; // Balance + case CLASS_DRUID: return 103; // Feral (cat) case CLASS_DEMON_HUNTER: return 577; // Havoc case CLASS_EVOKER: return 1467; // Devastation default: return 0; diff --git a/src/modules/PlayerbotV2/Bot/ClassicUpkeep.cpp b/src/modules/PlayerbotV2/Bot/ClassicUpkeep.cpp index 874935a289..9d7064d7fe 100644 --- a/src/modules/PlayerbotV2/Bot/ClassicUpkeep.cpp +++ b/src/modules/PlayerbotV2/Bot/ClassicUpkeep.cpp @@ -4,6 +4,7 @@ #include "BotSnapshotView.h" #include "ClassTables.h" #include "ClassicSupplies.h" +#include "VirtualSupply.h" #include "Group/GroupSnapshot.h" #include "Raid/RaidEncounters.h" #include "SharedDefines.h" @@ -30,6 +31,8 @@ #include #include #include +#include "Bot/ResistGear.h" +#include "Bot/AlwaysBuffs.h" namespace Playerbot::Classic { @@ -167,6 +170,16 @@ int BlessingAt(BotSnapshotView const& s, size_t paladin_index, std::span= 1 ? pin : 0; + NearbyUnit const* v = s.victim_info(); + if (!v || v->hp_pct() < 25) + return 0; + float bx, by, bz; s.position(bx, by, bz); + return Dist2(v->x, v->y, v->z, bx, by, bz) <= 18.f * 18.f ? pin : 0; +} + uint32 DesiredTotem(BotSnapshotView const& s, GroupSnapshotView const& g, Element e) { + if (uint32 const pin = s.owner_pick(OwnerPicks::Slot(OwnerPicks::TotemEarth + e)); pin && s.knows_spell(pin)) + return OwnerTotem(s, e, pin); bool const self_melee = !ShamanIsCaster(s.spec()); auto const melee_mate = [](GroupMemberSummary const& m) { return m.role == Role::Tank || IsMeleeSpec(m.cls, m.spec); }; size_t const index = ShamanIndexInParty(s, g); @@ -500,14 +531,19 @@ CastPick PickBlessing(BotSnapshotView const& s, GroupSnapshotView const& g, bool if (s.cls() != CLASS_PALADIN || s.is_mounted()) return {}; int64 const min_ms = in_combat ? 0 : 60'000; + // The owner's blessing for this paladin, when it knows it: it gives that one to everyone and leaves the group split. + int pinned = PinnedBlessing(s.owner_pick(OwnerPicks::Blessing)); + if (pinned >= 0 && !s.knows_spell(kBlessings[pinned].normal)) + pinned = -1; auto const* members = g.members(); if (!members || members->empty()) { - // Solo: bless self by own role. + // Solo: bless self by own role (or the owner's blessing). bool const tank = IsTankSpec(CLASS_PALADIN, uint16(s.spec())); - int const b = BlessingAt(s, 0, tank ? std::span(kSoloTankOrder) - : MemberBlessingOrder(CLASS_PALADIN, s.spec(), false)); + int const b = pinned >= 0 ? pinned + : BlessingAt(s, 0, tank ? std::span(kSoloTankOrder) + : MemberBlessingOrder(CLASS_PALADIN, s.spec(), false)); if (b < 0 || !s.is_ready(kBlessings[b].normal)) return {}; AuraEntry const* mine = s.find_aura(kBlessings[b].normal); @@ -519,26 +555,71 @@ CastPick PickBlessing(BotSnapshotView const& s, GroupSnapshotView const& g, bool return { kBlessings[b].normal, s.guid(), key }; } + bool const raid = g.is_raid(); + bool const greater_ok = s.item_count(SYMBOL_OF_KINGS) > 0; + float bx, by, bz; s.position(bx, by, bz); + auto in_reach = [&](GroupMemberSummary const& m) + { + return m.online && m.is_alive && m.map_id == s.map_id() + && (m.guid == s.guid() || Dist2(m.x, m.y, m.z, bx, by, bz) <= kBlessRange * kBlessRange); + }; + + // The owner's blessing: every member in reach gets it, as a Greater Blessing per class once Symbol of Kings is in the bags. + // Salvation never goes on a tank (it cuts the tank's threat); that tank gets nothing from this paladin. + if (pinned >= 0) + { + Blessing const pb = Blessing(pinned); + bool const greater = greater_ok && s.knows_spell(kBlessings[pb].greater) && GreaterBlessingWorks(kBlessings[pb].greater); + for (GroupMemberSummary const& m : *members) + { + if (!m.cls || m.cls >= 16 || !in_reach(m) || HasBlessing(m.buffs, pb, min_ms)) continue; + bool const tank = IsTankMember(s, m); + if (tank && pb == SALVATION) continue; + bool class_has_tank = false; + for (GroupMemberSummary const& o : *members) + if (o.cls == m.cls && o.online && IsTankMember(s, o)) { class_has_tank = true; break; } + if (greater && !(class_has_tank && pb == SALVATION)) + { + uint64 const key = (1ull << 48) | (uint64(pb) << 8) | m.cls; + if (s.is_ready(kBlessings[pb].greater) && !skip(key)) + return { kBlessings[pb].greater, m.guid, key }; + continue; + } + uint64 const key = (2ull << 48) | (uint64(pb) << 40) | (m.guid.GetCounter() & 0xFFFFFFFFFFull); + if (s.is_ready(kBlessings[pb].normal) && !skip(key)) + return { kBlessings[pb].normal, m.guid, key }; + } + return {}; + } + + // Blessings the owners of the other bot paladins pinned ("prefer blessing might"): those paladins give them to everyone, so + // they are left out of the split, and the pinned paladins do not count in it. + auto const pinned_other = [&](GroupMemberSummary const& m) + { + return m.cls == CLASS_PALADIN && m.is_bot && m.online && m.is_alive && m.map_id == s.map_id() && m.guid != s.guid() + && PinnedBlessing(m.owner_blessing) >= 0; + }; + uint8 others_pinned = 0; // bit per Blessing + for (GroupMemberSummary const& m : *members) + if (pinned_other(m)) + others_pinned = uint8(others_pinned | (1u << PinnedBlessing(m.owner_blessing))); + // This paladin's index among the group's bot paladins on the map (by // guid, stable across ticks). A human paladin blesses by hand: its // blessings still count as present (HasBlessing reads any caster). size_t index = 0; for (GroupMemberSummary const& m : *members) if (m.cls == CLASS_PALADIN && m.is_bot && m.online && m.is_alive && m.map_id == s.map_id() - && m.guid != s.guid() && m.guid < s.guid()) + && m.guid != s.guid() && m.guid < s.guid() && !pinned_other(m)) ++index; - bool const raid = g.is_raid(); - bool const greater_ok = s.item_count(SYMBOL_OF_KINGS) > 0; - float bx, by, bz; s.position(bx, by, bz); - // Kings for the tanks (+10% stamina is the biggest blessing a tank gets): the lowest-guid Protection bot paladin // of the map owns Kings on every class that has a tank in it (Kings is a Protection talent), whatever the class // order says; the other paladins plan that class from the order without Kings, their index not counting it. ObjectGuid kings_guid; for (GroupMemberSummary const& m : *members) if (m.cls == CLASS_PALADIN && m.is_bot && m.online && m.is_alive && m.map_id == s.map_id() && m.spec == 66 - && (kings_guid.IsEmpty() || m.guid < kings_guid)) + && !pinned_other(m) && !(others_pinned & (1u << KINGS)) && (kings_guid.IsEmpty() || m.guid < kings_guid)) kings_guid = m.guid; size_t const index_without_kings = (!kings_guid.IsEmpty() && kings_guid != s.guid() && kings_guid < s.guid()) ? index - 1 : index; struct ClassPlan { std::array order{}; size_t n = 0; size_t index = 0; }; @@ -553,21 +634,17 @@ CastPick PickBlessing(BotSnapshotView const& s, GroupSnapshotView const& g, bool return p; } for (Blessing b : base) - if (b != KINGS) + if (b != KINGS && !(others_pinned & (1u << b))) p.order[p.n++] = b; p.index = index_without_kings; return p; } for (Blessing b : base) - p.order[p.n++] = b; + if (!(others_pinned & (1u << b))) + p.order[p.n++] = b; p.index = index; return p; }; - auto in_reach = [&](GroupMemberSummary const& m) - { - return m.online && m.is_alive && m.map_id == s.map_id() - && (m.guid == s.guid() || Dist2(m.x, m.y, m.z, bx, by, bz) <= kBlessRange * kBlessRange); - }; uint16 seen = 0; // bit per recipient class already planned (classes 1..11) for (GroupMemberSummary const& first : *members) { @@ -664,8 +741,30 @@ CastPick PickImbue(BotSnapshotView const& s, bool in_combat) return {}; } +// A damage caster's weapon oil: Brilliant Wizard Oil (+36 spell damage, +1% crit) on the main hand while it carries no temporary enchant, as +// every raiding caster ran it. Not the shaman (its Flametongue imbue holds the same slot) and not the healers (Brilliant Mana Oil is a separate pick). +constexpr uint32 BRILLIANT_WIZARD_OIL = 20749; +static bool IsDamageCaster(BotSnapshotView const& s) +{ + switch (s.cls()) + { + case CLASS_MAGE: + case CLASS_WARLOCK: return true; + case CLASS_PRIEST: return s.spec() == 258; // Shadow + case CLASS_DRUID: return s.spec() == 102; // Balance + default: return false; + } +} + ItemPick PickPoison(BotSnapshotView const& s) { + if (IsDamageCaster(s) && !s.is_mounted()) + { + WeaponUpkeep const& mh = s.classic_upkeep().main_hand; + if (!mh.guid.IsEmpty() && s.item_count(BRILLIANT_WIZARD_OIL) > 0 && (!mh.temp_enchant || mh.temp_remaining.count() < 60'000)) + return { BRILLIANT_WIZARD_OIL, mh.guid }; + return {}; + } if (s.cls() != CLASS_ROGUE || s.is_mounted()) return {}; auto best_in_bags = [&s](char const* family) -> uint32 @@ -711,7 +810,7 @@ uint32 PickTotem(BotSnapshotView const& s, GroupSnapshotView const& g) if (cur.spell == want && cur.totem) { // In place: keep it unless the fight moved away from it. - if (e == FIRE) + if (e == FIRE && want != FROST_RESISTANCE_TOTEM && want != FLAMETONGUE_TOTEM) { NearbyUnit const* v = s.victim_info(); if (!v || Dist2(v->x, v->y, v->z, cur.totem->x, cur.totem->y, cur.totem->z) <= 18.f * 18.f) @@ -772,9 +871,9 @@ uint32 HealRank(BotSnapshotView const& s, GroupSnapshotView const& g, uint32 spe void ShortClassSupplies(BotSnapshotView const& s, std::vector& out) { out.clear(); - // Ammo for the equipped bow / crossbow / gun: short under 30% of the target (the entry is the + // Ammo for the equipped bow / crossbow / gun: short under 60% of the target (the entry is the // ammo item the restock will hand out, so it doubles as the retry-lockout key). - if (Services::Config().behavior_ammo_supply() && s.ammo_kind() != 0 && s.ammo_count() < AmmoLowBelow()) + if (Services::Config().behavior_ammo_supply() && s.ammo_kind() != 0 && s.ammo_count() < (AlwaysOn(s, AlwaysSwitch::Supplies) ? AMMO_TARGET : AmmoLowBelow())) if (uint32 const ammo = BestAmmo(s.ammo_kind(), s.level())) out.push_back(ammo); if (!Services::Config().classic_class_supplies()) @@ -798,7 +897,9 @@ void ShortClassSupplies(BotSnapshotView const& s, std::vector& out) } else have = s.item_count(best); - if (have < std::max(1u, SupplyTarget(f, s.level()) / 2u)) + // Playerbot.AlwaysBuffs: topped up to the full stack as soon as one is used, not only under half of it. + uint32 const want = AlwaysOn(s, AlwaysSwitch::Supplies) ? SupplyTarget(f, s.level()) : std::max(1u, SupplyTarget(f, s.level()) / 2u); + if (have < want) out.push_back(best); } } @@ -972,6 +1073,13 @@ uint32 BestConsumable(BotSnapshotView const& s, ConsumableKind kind, bool conjur return best; } +uint32 RecoveryConsumable(BotSnapshotView const& s, ConsumableKind kind) +{ + bool const water = kind == ConsumableKind::Drink; + uint32 const rank = Services::Config().classic_class_supplies() ? VirtualRecoveryRank(water, s.cls(), uint8(s.level())) : 0; + return RecoveryItemOrVirtual(BestConsumable(s, kind), Services::Config().classic_class_supplies(), rank); +} + bool CombatConsumableUsedRecently(BotSnapshotView const& s, uint32 window_ms) { for (InventoryItem const& it : s.raw().inventory.bag_items) @@ -1004,9 +1112,11 @@ bool IsDrinking(BotSnapshotView const& s) { return HasRegenAura(s, true); } bool RecoverBeforeWalking(BotSnapshotView const& s) { - if (s.hp_pct() < 50) return true; if (IsEating(s) || IsDrinking(s)) return true; - return s.max_power(POWER_MANA) > 0 && s.power_pct(POWER_MANA) < 20 && BestConsumable(s, ConsumableKind::Drink) != 0; + // Hurt: stop only for a meal the bot can sit down to; with nothing to eat it keeps going instead of standing about (it never sits + // just to regenerate). + if (s.hp_pct() < 50 && RecoveryConsumable(s, ConsumableKind::Food) != 0) return true; + return s.max_power(POWER_MANA) > 0 && s.power_pct(POWER_MANA) < 20 && RecoveryConsumable(s, ConsumableKind::Drink) != 0; } bool SafeToRecover(BotSnapshotView const& s, GroupSnapshotView const* g) @@ -1132,6 +1242,8 @@ bool RaidConsumableBuffUp(BotSnapshotView const& s, RaidConsumable const& c) return false; } +} // namespace + // The raid role whose kit the bot uses. The group's role wins (a healer-flipped paladin takes the healer kit), then // the tank test the blessings use, then the spec. RaidConsumableRole RaidConsumableRoleOf(BotSnapshotView const& s, GroupSnapshotView const& g) @@ -1155,9 +1267,15 @@ RaidConsumableRole RaidConsumableRoleOf(BotSnapshotView const& s, GroupSnapshotV return role; } +namespace { + +constexpr uint8 kDungeonKitMinLevel = 58; // the flasks and elixirs of the kits need level 51-55; dungeon runs of the raiding bots are 58+ + bool RaidConsumablesApply(BotSnapshotView const& s) { - return IsVanillaRealm() && s.in_group() && s.is_in_raid() && s.is_alive() && !s.is_mounted() && ConsumablesAllowed(s); + // A raid, and, with Playerbot.Raid.ConsumablesInDungeons, any dungeon instance a bot of the raiding levels is in with a group. + bool const where = s.is_in_raid() || (s.is_in_instance() && s.level() >= kDungeonKitMinLevel && Services::Config().raid_consumables_in_dungeons()); + return IsVanillaRealm() && s.in_group() && where && s.is_alive() && !s.is_mounted() && ConsumablesAllowed(s); } } // namespace @@ -1169,6 +1287,18 @@ bool ConsumablesAllowed(BotSnapshotView const& s) return pvp ? Services::Config().consumables_pvp() : Services::Config().consumables_pve(); } +AlwaysPlace AlwaysPlaceOf(BotSnapshotView const& s, GroupSnapshotView const* g) +{ + if (s.in_battleground() || s.is_bg_orphan()) + return AlwaysPlace::Battleground; + return s.is_in_raid() || s.is_in_instance() || (g && g->is_raid()) ? AlwaysPlace::Raid : AlwaysPlace::World; +} + +bool AlwaysOn(BotSnapshotView const& s, AlwaysSwitch what, GroupSnapshotView const* g) +{ + return Services::Config().always_on(what, AlwaysPlaceOf(s, g)); +} + uint32 PickRaidConsumable(BotSnapshotView const& s, GroupSnapshotView const& g) { if (!RaidConsumablesApply(s)) @@ -1183,9 +1313,18 @@ uint32 PickRaidConsumableStock(BotSnapshotView const& s, GroupSnapshotView const { if (!RaidConsumablesApply(s)) return 0; + // A resistance potion is stocked only for a school this raid's bosses deal; one for another school counts as handled. + uint32 const map_id = s.map_id(); + auto const school_wanted = [map_id](RaidConsumable const& c) + { + for (Resist r : { Resist::Fire, Resist::Frost, Resist::Nature, Resist::Shadow }) + if (c.item == ResistPotionItem(r)) + return InstanceDealsSchool(map_id, r); + return true; + }; RaidConsumable const* next = NextRaidConsumableToStock(RaidConsumableRoleOf(s, g), [&](uint32 item) { return s.item_count(item); }, - [&](RaidConsumable const& c) { return RaidConsumableBuffUp(s, c); }); + [&](RaidConsumable const& c) { return RaidConsumableBuffUp(s, c) || (c.combat && !school_wanted(c)); }); return next ? next->item : 0; } @@ -1207,10 +1346,10 @@ RecoveryPick PickRecovery(BotSnapshotView const& s, int32 start_hp, int32 start_ bool const eating = IsEating(s); bool const drinking = IsDrinking(s); if (!eating && hp < start_hp) - if (uint32 const food = BestConsumable(s, ConsumableKind::Food)) + if (uint32 const food = RecoveryConsumable(s, ConsumableKind::Food)) return { food, false }; if (!drinking && mana_user && mana < start_mana) - if (uint32 const drink = BestConsumable(s, ConsumableKind::Drink)) + if (uint32 const drink = RecoveryConsumable(s, ConsumableKind::Drink)) return { drink, false, true }; // A grouped instance DPS (start_mana == kPullReadyDpsManaPct) sits only to 85%: the rest is minutes of waiting for the raid. int32 const top_mana = start_mana == kPullReadyDpsManaPct ? 85 : kTopOffPct; @@ -1302,7 +1441,9 @@ bool BossFight(BotSnapshotView const& s) return false; } NearbyUnit const* v = s.victim_info(); - return v && v->hp > 0 && (IsBossUnit(*v) || v->max_hp >= 100'000); + // Open world: a boss or a big pool as before, and now also an elite or a pack of three or more, so a bot grinding or questing + // kills them faster; the long cooldowns still come back for the bosses. + return v && v->hp > 0 && (IsBossUnit(*v) || v->max_hp >= 100'000 || v->is_elite_or_rare || s.attackers_count() >= 3); } namespace { @@ -1353,6 +1494,7 @@ void NoteManaItemRefused(BotSnapshotView const& s) if (s.max_power(POWER_MANA) <= 0 || !s.in_combat() || !s.is_in_instance() || s.power_pct(POWER_MANA) > 20 || !LogPaced(s, 0x6D616E61u)) return; uint32 potions = 0, runes = 0, gems = 0, other = 0, rune_items = 0; + std::string states; // each mana item in the bags: what UsableNow reads for it for (InventoryItem const& it : s.raw().inventory.bag_items) { if (it.entry == 12662) @@ -1360,6 +1502,9 @@ void NoteManaItemRefused(BotSnapshotView const& s) if (!IsConsumableClass(it.item_class, it.item_subclass)) continue; ConsumableInfo const& info = Classify(it.entry); + if (info.kinds & (KindBit(ConsumableKind::ManaPotion) | KindBit(ConsumableKind::ManaItem))) + states += fmt::format(" [{} req {} (bot {}), skill {}/{}, cooldown {} ms]", it.entry, info.req_level, uint32(s.level()), + info.req_skill ? s.skill_value(uint16(info.req_skill)) : 0u, info.req_skill_rank, s.cd_remaining(info.spell).count()); if (info.kinds & KindBit(ConsumableKind::ManaPotion)) potions += it.count; else if (info.kinds & KindBit(ConsumableKind::ManaItem)) @@ -1394,9 +1539,9 @@ void NoteManaItemRefused(BotSnapshotView const& s) } } TC_LOG_INFO("playerbot.v2", "[raid_consume] {} mana {}% and no mana item picked: casting {}, consumables allowed {}, a combat consumable used recently {}, " - "usable potion {}, in the bags: {} mana potions, {} runes ({} Demonic Runes by entry), {} gems, {} other combat consumables, hp {}%", + "usable potion {}, in the bags: {} mana potions, {} runes ({} Demonic Runes by entry), {} gems, {} other combat consumables, hp {}%, items:{}", s.name(), s.power_pct(POWER_MANA), s.is_casting() ? 1 : 0, ConsumablesAllowed(s) ? 1 : 0, CombatConsumableUsedRecently(s) ? 1 : 0, - BestConsumable(s, ConsumableKind::ManaPotion), potions, runes, rune_items, gems, other, s.hp_pct()); + BestConsumable(s, ConsumableKind::ManaPotion), potions, runes, rune_items, gems, other, s.hp_pct(), states); } // ======================= Raid support ======================= @@ -1859,8 +2004,11 @@ uint32 ResistPotionItem(Resist r) { switch (r) { - case Resist::Fire: return 13457; // Greater Fire Protection Potion - default: return 0; + case Resist::Fire: return 13457; // Greater Fire Protection Potion + case Resist::Frost: return 13456; // Greater Frost Protection Potion + case Resist::Nature: return 13458; // Greater Nature Protection Potion + case Resist::Shadow: return 13459; // Greater Shadow Protection Potion + default: return 0; } } @@ -1883,6 +2031,27 @@ uint32 PickResistPotion(BotSnapshotView const& s) return item; } +uint8 PickResistGearSchool(BotSnapshotView const& s) +{ + if (!IsVanillaRealm() || !s.in_group() || !s.is_in_raid() || !s.is_alive() || !ResistSwapMap(s.map_id()) || !ConsumablesAllowed(s)) + return 0; + Raid::RaidRules const* rules = Raid::RulesForMap(s.map_id()); + if (!rules || rules->resistPotion.empty()) + return 0; + for (NearbyUnit const& u : s.nearby_enemies()) // nearest first + { + if (u.hp <= 0 || u.is_player || !IsBossUnit(u)) + continue; + for (Raid::ResistPotion const& rp : rules->resistPotion) + if (rp.enemy == u.entry) + for (auto const& [school, spell_school] : { std::pair{ Resist::Fire, uint8(SPELL_SCHOOL_FIRE) }, std::pair{ Resist::Nature, uint8(SPELL_SCHOOL_NATURE) }, + std::pair{ Resist::Frost, uint8(SPELL_SCHOOL_FROST) }, std::pair{ Resist::Shadow, uint8(SPELL_SCHOOL_SHADOW) } }) + if (rp.item == ResistPotionItem(school)) + return spell_school; + } + return 0; +} + CastPick PickFearWard(BotSnapshotView const& s, GroupSnapshotView const& g) { constexpr uint32 FEAR_WARD = 6346; @@ -2079,6 +2248,17 @@ uint32 BestMageConjure(ConsumableKind kind, std::function const& k return best ? best->spell : 0; } +bool IsMageConjure(uint32 spell, ConsumableKind& kind) +{ + for (ConjureSpell const& c : MageConjureSpells()) + if (c.spell == spell) + { + kind = c.kind; + return true; + } + return false; +} + bool MageConjuresFamily(uint8 cls, std::string_view family, std::function const& knows) { if (cls != CLASS_MAGE) @@ -2107,6 +2287,10 @@ uint32 MageConjureSpell(BotSnapshotView const& s, ConsumableKind kind, uint32 wa if (it.item_class == ITEM_CLASS_CONSUMABLE && Classify(it.entry).conjured && (Classify(it.entry).kinds & KindBit(kind))) have += it.count; + // No conjured stack to top up and no free slot: the cast fails (DONT_REPORT) and the mage stood recasting it every half minute + // (live 244, Devonia in Stormwind with full bags). + if (have == 0 && s.bag_free_slots() == 0) + return 0; return have < want_below ? spell : 0; } @@ -2557,7 +2741,10 @@ uint32 PickPaladinAura(BotSnapshotView const& s, GroupSnapshotView const& g) auto const* members = g.members(); uint32 pick = 0; - if (!members || members->empty()) + // The owner's aura ("prefer aura fire"; OwnerPicks.h), when this paladin knows it: held whatever the party plan says. + if (uint32 const pin = s.owner_pick(OwnerPicks::Aura); pin && s.knows_spell(pin)) + pick = pin; + else if (!members || members->empty()) { Role const role = IsTankSpec(CLASS_PALADIN, uint16(s.spec())) ? Role::Tank : IsHealerSpec(CLASS_PALADIN, uint16(s.spec())) ? Role::Healer : Role::Dps; @@ -2587,6 +2774,12 @@ uint32 PickPaladinAura(BotSnapshotView const& s, GroupSnapshotView const& g) if (uint32 const h = HeldAura(m); h && nt < 8) taken[nt++] = h; continue; } + // Another bot paladin holding its owner's aura: taken, and that paladin is out of the plan. + if (m.guid != s.guid() && m.owner_aura) + { + if (nt < 8) taken[nt++] = m.owner_aura; + continue; + } pals.push_back(&m); } std::sort(pals.begin(), pals.end(), [](GroupMemberSummary const* a, GroupMemberSummary const* b) { return a->guid < b->guid; }); @@ -2873,3 +3066,106 @@ bool IsCurseDispelSpell(uint32 spell) } } // namespace Playerbot::Classic + +namespace Playerbot { + +namespace { + +std::string_view SpellEnglishName(SpellInfo const* si) +{ + return si && si->SpellName ? std::string_view((*si->SpellName)[LOCALE_enUS]) : std::string_view(); +} + +void ResolveAlwaysAura(AlwaysAura const& row, std::vector& out) +{ + if (row.kind == AlwaysKind::Spell) + { + SpellInfo const* si = sSpellMgr->GetSpellInfo(row.id, DIFFICULTY_NONE); + if (SpellEnglishName(si).find(row.name) != std::string_view::npos) + out.push_back(row.id); + else + TC_LOG_ERROR("playerbot.v2", "[always_buff] spell {} is not '{}', skipped", row.id, row.name); + return; + } + ItemTemplate const* tmpl = sObjectMgr->GetItemTemplate(row.id); + if (!tmpl || std::string_view(tmpl->GetName(LOCALE_enUS)).find(row.name) == std::string_view::npos) + { + TC_LOG_ERROR("playerbot.v2", "[always_buff] item {} is not '{}', skipped", row.id, row.name); + return; + } + for (ItemEffectEntry const* eff : tmpl->Effects) + { + if (!eff || eff->TriggerType != ITEM_SPELLTRIGGER_ON_USE || eff->SpellID <= 0) + continue; + SpellInfo const* si = sSpellMgr->GetSpellInfo(uint32(eff->SpellID), DIFFICULTY_NONE); + if (!si) + continue; + bool triggers = false; + for (SpellEffectInfo const& e : si->GetEffects()) + { + if (row.kind == AlwaysKind::Stone) + { + if (e.IsEffect(SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY)) + out.push_back(uint32(e.MiscValue)); + } + else if (e.TriggerSpell) + { + out.push_back(e.TriggerSpell); + triggers = true; + } + } + // A scroll or elixir leaves its own aura; food only eats and triggers the stat buff (Well Fed). The eating aura (Food 1129 / 1131, an on-use + // spell of its own beside the Well Fed one) ends when the bot stands, so it is never up on a bot that fights: as a row aura it read as + // missing on every check and idle:always_buff fired every 10 s for each bot through the whole support scorecard (233, "+1129"). + if (row.kind == AlwaysKind::Item && !triggers && !si->HasAuraInterruptFlag(SpellAuraInterruptFlags::Standing)) + out.push_back(uint32(eff->SpellID)); + } +} + +} // namespace + +std::span AlwaysAuraEffects(AlwaysAura const& row) +{ + static std::mutex mu; + static std::map, std::vector> cache; + std::lock_guard lk(mu); + auto const key = std::make_pair(uint8(row.kind), row.id); + auto it = cache.find(key); + if (it == cache.end()) + { + std::vector v; + ResolveAlwaysAura(row, v); + it = cache.emplace(key, std::move(v)).first; + } + return it->second; +} + +} // namespace Playerbot + +namespace Playerbot::Classic { + +uint32 PickStrangerBuff(BotSnapshotView const& s, uint8 held, bool target_has_mana, uint8& bit_out) +{ + bit_out = 0; + if (!IsVanillaRealm() || s.in_combat() || s.is_mounted() || SelfInDruidForm(s)) + return 0; + struct Def { uint8 cls; uint32 base; uint8 bit; bool mana_only; }; + static constexpr Def kDefs[] = { + { CLASS_PRIEST, 1243, 1, false }, // Power Word: Fortitude + { CLASS_MAGE, 1459, 2, true }, // Arcane Intellect + { CLASS_DRUID, 1126, 4, false }, // Mark of the Wild + }; + for (Def const& d : kDefs) + { + if (d.cls != s.cls() || (held & d.bit) || (d.mana_only && !target_has_mana) || !s.knows_spell(d.base)) + continue; + uint32 const spell = EffectiveBuffSpell(s, d.base); + if (!spell || !SpellAppliesAura(sSpellMgr->GetSpellInfo(spell, DIFFICULTY_NONE)) || !s.is_ready(spell)) + continue; + bit_out = d.bit; + return spell; + } + return 0; +} + +} // namespace Playerbot::Classic diff --git a/src/modules/PlayerbotV2/Bot/ClassicUpkeep.h b/src/modules/PlayerbotV2/Bot/ClassicUpkeep.h index 4c10e412f5..f640032461 100644 --- a/src/modules/PlayerbotV2/Bot/ClassicUpkeep.h +++ b/src/modules/PlayerbotV2/Bot/ClassicUpkeep.h @@ -16,6 +16,8 @@ #include #include #include "InstanceSchools.h" +#include "AlwaysBuffs.h" +#include "ClassicSupplies.h" // RaidConsumableRole #include "BotTypes.h" #include "ObjectGuid.h" #include @@ -90,8 +92,8 @@ bool InstanceDealsSchool(uint32 map_id, Resist school); // the fear prep ([raid_fear]). bool BossFears(uint32 map_id, uint32 creature_entry); -// The resistance potion for an instance's resistance (Fire: Greater Fire -// Protection Potion 13457), 0 when there is none. +// The Greater Protection Potion for a resistance school (Fire 13457, Frost +// 13456, Nature 13458, Shadow 13459), 0 when there is none. uint32 ResistPotionItem(Resist r); // In combat: the resistance potion the raid plan asks this bot to drink @@ -99,6 +101,11 @@ uint32 ResistPotionItem(Resist r); // in the bags, off cooldown and its protection is not already up. 0 = none. uint32 PickResistPotion(BotSnapshotView const& s); +// Raid resistance gear (Playerbot.Raid.ResistGear): the school (SpellSchools value) of the boss a grouped bot stands before: the nearest living +// boss within the bot's 40 yd scan whose RaidRules::resistPotion row names a Greater Protection Potion, on a map the swap runs on +// (Bot/ResistGear.h). 0 = none: the bot wears its own gear. +uint8 PickResistGearSchool(BotSnapshotView const& s); + // Dwarf priest: Fear Ward (6346) on the tank the raid plan gave it // (PveOrder::fear_ward_target) while that tank is in range. spell 0 = nothing. CastPick PickFearWard(BotSnapshotView const& s, GroupSnapshotView const& g); @@ -115,6 +122,10 @@ CastPick PickFearWard(BotSnapshotView const& s, GroupSnapshotView const& g); // change the plan. Out of combat only; nothing while this bot is in a form // (DruidFormToLeave takes it out first). CastPick PickClassBuff(BotSnapshotView const& s, GroupSnapshotView const& g, PickSkip skip = {}); +// A world bot's buff for a passing real player (Playerbot.World.Kindness): Fortitude (priest), Intellect (mage, a mana user only) +// or Mark of the Wild (druid), the spell the bot would cast on its own group. `held` = the Strangers::BuffBit the player has. +// `bit_out` = the buff picked. Nothing in combat, mounted or in a druid form. +uint32 PickStrangerBuff(BotSnapshotView const& s, uint8 held, bool target_has_mana, uint8& bit_out); // A cast PickClassBuff returned with a kind 6 key (caster-centred buff): tracks whether it reached anyone, and backs the buff off when not. void NoteAreaBuffCast(ObjectGuid caster, uint64 key, uint32 needy, uint32 now_ms); @@ -261,8 +272,15 @@ void ShortClassSupplies(BotSnapshotView const& s, std::vector& out); // PickRaidConsumableStock: the kit item the bags are short of whose buff is missing, to stock (0 = none). // Playerbot.Consumables.PvE / .PvP for the bot's current map (battlegrounds and arenas are PvP, everything else PvE). bool ConsumablesAllowed(BotSnapshotView const& s); +// Playerbot.AlwaysBuffs..: where the bot stands (a battleground or arena map, else a raid or dungeon instance, else the world) +// and whether a switch is on there. A bot in a raid-type group counts as in a raid wherever it stands (the dps scorecard fights in the +// open world with a 22-bot raid and its flasks and world buffs were stripped there). +AlwaysPlace AlwaysPlaceOf(BotSnapshotView const& s, GroupSnapshotView const* g = nullptr); +bool AlwaysOn(BotSnapshotView const& s, AlwaysSwitch what, GroupSnapshotView const* g = nullptr); uint32 PickRaidConsumable(BotSnapshotView const& s, GroupSnapshotView const& g); uint32 PickRaidConsumableStock(BotSnapshotView const& s, GroupSnapshotView const& g); +// The role whose kit (ClassicSupplies RaidConsumablesFor) the bot drinks: the group's role first, then the tank test, then the spec. +RaidConsumableRole RaidConsumableRoleOf(BotSnapshotView const& s, GroupSnapshotView const& g); // Physical melee damage dealer or tank by class and (virtual Classic) spec. bool IsMeleeSpec(uint8 cls, uint32 spec); @@ -287,12 +305,18 @@ enum class ConsumableKind : uint8 // first on a tie. With `conjured_only` only conjured items count. 0 = none. uint32 BestConsumable(BotSnapshotView const& s, ConsumableKind kind, bool conjured_only = false); +// Food / Drink to recover with: BestConsumable, else (PlayerbotV2.Classic.ClassSupplies: infinite supplies) the Food / Water rank of +// the bot's level, which the API eats / drinks without the item (Api/VirtualSupply.h). A healer is never left with nothing to drink. +uint32 RecoveryConsumable(BotSnapshotView const& s, ConsumableKind kind); + // Mage Conjure Water / Conjure Food: the best rank the mage knows (found in the spell data, like // the healthstones) when fewer than `want_below` conjured items of that kind (Drink / Food) are // in the bags, else 0. uint32 MageConjureSpell(BotSnapshotView const& s, ConsumableKind kind, uint32 want_below); // Best Conjure Water (Drink) / Conjure Food (Food) rank `knows` accepts, 0 = none. uint32 BestMageConjure(ConsumableKind kind, std::function const& knows); +// `spell` is a Conjure Water (Drink) / Conjure Food (Food) rank: its kind in `kind`. Found by the spell data, so any locale. +bool IsMageConjure(uint32 spell, ConsumableKind& kind); // A mage that can conjure the item of supply family `family` ("Water", "Food") makes its own: the restock skips it. bool MageConjuresFamily(uint8 cls, std::string_view family, std::function const& knows); @@ -400,8 +424,8 @@ uint32 PickCombatManaItem(BotSnapshotView const& s, GroupSnapshotView const* g = constexpr int32 kCombatHealthItemPct = 30; // Mana % at or below which a group healer in a boss fight uses a mana item. constexpr int32 kBossHealerManaItemPct = 35; -// ... and the mana % above which it does not even look. The items are on a 2-minute cooldown: spent at 71-81 % they were on cooldown -// when the bar ran dry 80 s later, so a healer uses one only when mana is low. +// ... and the mana % above which it does not even look. The items are on a 2-minute cooldown: spent at 71-81 % (UBRS 20 Oct, both priests) +// they were on cooldown when the bar ran dry 80 s later, so a healer uses one only when mana is low. constexpr int32 kHealerManaItemCeilingPct = 30; // ======================= Boss fights (major cooldowns) ======================= diff --git a/src/modules/PlayerbotV2/Bot/CompanionLeash.h b/src/modules/PlayerbotV2/Bot/CompanionLeash.h new file mode 100644 index 0000000000..0c8e7de799 --- /dev/null +++ b/src/modules/PlayerbotV2/Bot/CompanionLeash.h @@ -0,0 +1,37 @@ +// CompanionLeash - how far from the player it follows a led bot walks after its target (State_InCombat melee gap-close). +// +// Pure function on plain values, so the rule is unit-tested without a server. +// +// A bot the dungeon autopilot is suspended for (a human leads, Passive, a follow / stay order) fights where the player is. A mob +// standing 30 y or more from him is not walked after unless it is hitting the bot itself: it comes to the group, or the group goes +// to it on the player's order (UBRS 2026-10-26: the Urok challenge put its adds in combat with everyone on the map, and a passive +// companion warrior walked 180 y after one of them, pulling the Scarshield packs in between). The tank's own leash +// ([tank_chase], 30 y) is the same distance. +// The group's own fight is never leashed (the owner, 2026-10-27: "bots should always fight if you're fighting"): the player's own +// target, or a mob fighting a group member (within the leash of that member) who stands within the leash of the player, is walked +// after. The Urok adds, unreachable 180 y off with the tank beside the player on their threat lists, stay leashed. + +#pragma once + +namespace Playerbot::CompanionLeash { + +constexpr float kLeashYd = 30.0f; + +struct Inputs +{ + bool led = false; // the autopilot is suspended for this bot (a human leads, Passive, follow / stay order) + bool leader_known = false; // the player it follows is alive on this map + float victim_to_leader_d2 = 0.0f; + bool victim_on_me = false; // the mob is hitting this bot: it comes anyway + bool leader_target = false; // the player it follows has this mob as his target + bool on_member_near_leader = false; // the mob is on a group member (or a pet of one) within kLeashYd of the player, and + // within kLeashYd of that member +}; + +inline bool StopsChase(Inputs const& in) +{ + return in.led && in.leader_known && !in.victim_on_me && !in.leader_target && !in.on_member_near_leader && + in.victim_to_leader_d2 > kLeashYd * kLeashYd; +} + +} // namespace Playerbot::CompanionLeash diff --git a/src/modules/PlayerbotV2/Bot/DrainOrder.h b/src/modules/PlayerbotV2/Bot/DrainOrder.h new file mode 100644 index 0000000000..3c03c4e732 --- /dev/null +++ b/src/modules/PlayerbotV2/Bot/DrainOrder.h @@ -0,0 +1,21 @@ +// DrainOrder - where the intent drain pass starts. The bots are visited in registry order and a pass has two limits (the 30 ms wall +// budget, and the pathfinding window of Api PathBudget), so with a fixed start the bots at the tail wait every frame while the same +// head bots are served. A pass that hit a limit moves the start on by a sixth of the bots; the bots before the start go last in the +// same pass, so every bot is first in turn. Tested in tests/game/ClassicDrainOrder.cpp. +#pragma once + +#include +#include + +namespace Playerbot::V2 +{ + +// The start index for the next pass. `start` is the current one, `bots` the number registered, `cut` whether this pass hit a limit. +inline std::size_t NextDrainStart(std::size_t start, std::size_t bots, bool cut) +{ + if (!bots) return 0; + start %= bots; + return cut ? (start + std::max(1u, bots / 6u)) % bots : start; +} + +} // namespace Playerbot::V2 diff --git a/src/modules/PlayerbotV2/Bot/Dungeon/MarkCc.h b/src/modules/PlayerbotV2/Bot/Dungeon/MarkCc.h index e55faadfc0..483ca3aead 100644 --- a/src/modules/PlayerbotV2/Bot/Dungeon/MarkCc.h +++ b/src/modules/PlayerbotV2/Bot/Dungeon/MarkCc.h @@ -20,6 +20,7 @@ #include #include "../BotSnapshot.h" +#include "../CcDeny.h" namespace Playerbot::MarkCc { @@ -100,14 +101,16 @@ inline uint8 TypeOf(NearbyUnit const& u) return t ? uint8(t->type) : uint8(0); } -// The option this bot can hold `creature_type` with (known spell, type fits, Sap only out of combat), else nullptr. -// `ooc` = neither the bot nor the mob is in combat. +// The option this bot can hold `creature_type` with (known spell, type fits, Sap only out of combat, a kind its owner has not +// said no to: "@warlock no fear", CcDeny.h; no Sap while the owner keeps the rogue out of Stealth: "stealth off"), else nullptr. `ooc` = neither the bot nor the mob is in combat. template Option const* PickOption(View const& s, uint8 cls, uint8 creature_type, bool ooc) { if (creature_type == 0) return nullptr; // a player: never by symbol for (Option const& o : OptionsFor(cls)) - if ((o.type_mask & (1u << creature_type)) && (!o.ooc_only || ooc) && s.knows_spell(SpellFor(s, o)) && + if ((o.type_mask & (1u << creature_type)) && (!o.ooc_only || ooc) && (CcDeny::KindOfSpell(o.spell) & s.raw().cc_deny) == 0 && + (!o.needs_stealth || !s.raw().owner_picks.stealth_off) && + s.knows_spell(SpellFor(s, o)) && (!o.needs_no_pet || !s.has_pet()) && (!o.needs_reagent || s.has_reagents(SpellFor(s, o)))) return &o; return nullptr; @@ -182,7 +185,7 @@ bool TryCast(View const& s, Emit& emit, ObjectGuid target) float const dx = u->x - p.x, dy = u->y - p.y, dz = u->z - p.z; float const dist = std::sqrt(dx * dx + dy * dy + dz * dz); if (!o) - return LogRefusal(low, now, s.name().c_str(), "no spell of this class holds that creature type (or not known / no shard)", + return LogRefusal(low, now, s.name().c_str(), "no spell of this class holds that creature type (or not known / no shard / the owner said no to it)", u->entry, TypeOf(*u), dist), false; if (o->needs_stealth && !s.has_aura(kStealth)) { @@ -195,10 +198,31 @@ bool TryCast(View const& s, Emit& emit, ObjectGuid target) // Out of reach: walk into it instead of standing out of range (Garr 2026-10-09: the banishers kept their formation slot 38-57 yd // from the Firesworn, 103 refusals, and the adds ran loose later). The stop point is a few yards inside the range on the line // from the mob. + // A mob on this caster comes first: a hard cast on another mob while it is being hit is the death of a mage (brd_roccor 127: + // Scnmage re-sheeped the Anvilrage Guardsman with a Bloodhound on it and died in the cast). The hold on the very mob hitting + // it is the answer to that one, and a trap at the feet goes out regardless. + if (!o->self_cast && u->victim != s.guid()) + for (NearbyUnit const& a : s.raw().combat.attackers) + if (a.hp > 0 && a.guid != target && a.victim == s.guid()) + return LogRefusal(low, now, s.name().c_str(), "a mob is on this caster", u->entry, TypeOf(*u), dist), false; if (dist > o->range) { + // Never past the tank toward the mob: the walk-in stops no closer to it than the tank stands, less a couple of yards + // (brd_roccor 127: the mage walked from 50 y to 27 y of a pack the tank was still 37 y from, stood in front of the pull + // and the pack ate it). With the tank further off than the spell reaches, the caster waits for the tank's pull spot. + float stop = std::max(o->range - 5.0f, 5.0f); + float tank_d = -1.0f; + for (NearbyUnit const& f : s.raw().combat.nearby_friends) + { + if (f.role != Role::Tank || f.hp <= 0) continue; + float const tx = u->x - f.x, ty = u->y - f.y, tz = u->z - f.z; + float const td = std::sqrt(tx * tx + ty * ty + tz * tz); + if (tank_d < 0.0f || td < tank_d) tank_d = td; + } + if (tank_d >= 0.0f && stop < tank_d - 2.0f) stop = tank_d - 2.0f; + if (stop > o->range) + return LogRefusal(low, now, s.name().c_str(), "out of range, the tank stands further off: waiting behind it", u->entry, TypeOf(*u), dist), false; LogRefusal(low, now, s.name().c_str(), "out of range, moving in", u->entry, TypeOf(*u), dist); - float const stop = std::max(o->range - 5.0f, 5.0f); float const f = stop / dist; // fraction of the mob->bot line return emit.move_to(u->x + (p.x - u->x) * f, u->y + (p.y - u->y) * f, u->z + (p.z - u->z) * f, /*run=*/true); } diff --git a/src/modules/PlayerbotV2/Bot/Dungeon/PveGroupCoordinator.cpp b/src/modules/PlayerbotV2/Bot/Dungeon/PveGroupCoordinator.cpp index 9ba2b50937..82f154c4db 100644 --- a/src/modules/PlayerbotV2/Bot/Dungeon/PveGroupCoordinator.cpp +++ b/src/modules/PlayerbotV2/Bot/Dungeon/PveGroupCoordinator.cpp @@ -42,6 +42,7 @@ #include "WorldSession.h" #include +#include #include #include #include @@ -62,8 +63,44 @@ constexpr uint32 kOwnerAttackWindowMs = 10000; using V2::OwnerAttackRecent; +// Damage done to creatures per player (pets count for their owner), for the [raid_dps] line. Written from the map threads, read and +// reset on the world thread at the start and end of a pull. +std::mutex g_dmg_done_mtx; +std::unordered_map g_dmg_done; + +uint64 TakeDamageDone(uint64 guid_low, bool reset) +{ + std::lock_guard lk(g_dmg_done_mtx); + auto it = g_dmg_done.find(guid_low); + if (it == g_dmg_done.end()) return 0; + uint64 const v = it->second; + if (reset) g_dmg_done.erase(it); + return v; +} + +char const* ShortClass(uint8 cls) +{ + switch (cls) + { + case CLASS_WARRIOR: return "War"; case CLASS_PALADIN: return "Pal"; case CLASS_HUNTER: return "Hun"; + case CLASS_ROGUE: return "Rog"; case CLASS_PRIEST: return "Pri"; case CLASS_SHAMAN: return "Sha"; + case CLASS_MAGE: return "Mag"; case CLASS_WARLOCK: return "Wlk"; case CLASS_DRUID: return "Dru"; + default: return "?"; + } +} + } // namespace +void PveGroupCoordinator::NoteDamageDone(Unit* attacker, Unit* victim, int32 amount) +{ + if (!attacker || !victim || amount <= 0 || victim->IsPlayer()) return; + Player* owner = attacker->GetCharmerOrOwnerPlayerOrPlayerItself(); + if (!owner) return; + std::lock_guard lk(g_dmg_done_mtx); + if (g_dmg_done.size() > 4096) g_dmg_done.clear(); + g_dmg_done[owner->GetGUID().GetCounter()] += uint64(amount); +} + void PveGroupCoordinator::Update(uint32 now_ms) { if (now_ms - last_plan_ms_ < kPlanIntervalMs) @@ -1294,6 +1331,14 @@ void PveGroupCoordinator::PlanMarkOrders(uint64 group_low, uint32 map_id, bool i static std::mutex cc_stick_mx; static std::unordered_map cc_stick; uint32 const cc_now = GameTime::GetGameTimeMS(); + // A tank (or the owner) hitting the mob is the call to kill it, the last of its pack: the hold ends, as the automatic + // crowd control's does, instead of re-sheeping the tank's target at every break (wc_cobrahn 127). + auto const tank_hits = [&](ObjectGuid mob) + { + for (auto const& m : mem) + if ((!m.is_bot || m.tank) && m.src && m.src->victim == mob) return true; + return false; + }; bool kept = false; { std::lock_guard lk(cc_stick_mx); @@ -1305,7 +1350,7 @@ void PveGroupCoordinator::PlanMarkOrders(uint64 group_low, uint32 map_id, bool i NearbyUnit const* su = icon_on ? unit_any(st.mob) : nullptr; if (su) st.seen_ms = cc_now; - if (icon_on && (su || uint32(cc_now - st.seen_ms) <= 4000u) && + if (icon_on && !tank_hits(st.mob) && (su || uint32(cc_now - st.seen_ms) <= 4000u) && std::find(cc_taken.begin(), cc_taken.end(), st.mob) == cc_taken.end() && !(su && su->max_hp > 0 && su->hp * 2 < su->max_hp) && (!su || MarkCc::PickOption(view, e.cls, MarkCc::TypeOf(*su), !e.src->in_combat && !su->unit_in_combat))) @@ -1326,6 +1371,7 @@ void PveGroupCoordinator::PlanMarkOrders(uint64 group_low, uint32 map_id, bool i if (!u || Classic::IsBossUnit(*u) || never_controlled(u->entry)) continue; if (u->guid == icon[7] || u->guid == icon[6]) continue; // marked skull / cross: killed, never crowd-controlled if (u->max_hp > 0 && u->hp * 2 < u->max_hp) continue; // under half health: being killed, not held again + if (tank_hits(u->guid)) continue; // the tank is on it: killed, not held again if (std::find(cc_taken.begin(), cc_taken.end(), u->guid) != cc_taken.end()) continue; const bool ooc = !e.src->in_combat && !u->unit_in_combat; if (!MarkCc::PickOption(view, e.cls, MarkCc::TypeOf(*u), ooc)) @@ -1348,7 +1394,13 @@ void PveGroupCoordinator::PlanMarkOrders(uint64 group_low, uint32 map_id, bool i // (playtest 2026-10-15). In a raid, an entry the encounter rules already crowd-control (RaidBrain::ElectCrowdControl) is left to them. // Never the owner's skull / cross or the raid's kill focus, never a boss or an unpulled mob, never one already under half // health; at least three live mobs are on the group (with two, killing them is quicker than holding one). - if (po->second.cc_target.IsEmpty()) + // A healer holds nothing of its own once it is in a fight: its mana is the group's healing (rfd_tutenkash 127: the + // priest shackled a fresh ghoul every few seconds between Greater Heals, 94% to 15% mana in 27 s, out of mana three + // times, the tank died). Before the pull it still shackles; an icon the owner gave it is still its call. + // Not in a raid: ten or more players kill a pack quicker than two of the six damage dealers can hold one mob each, and + // the hold broke and re-formed every few seconds as the kill focus moved (UBRS 20 Oct: mark_cc assign / release 66 times + // in 5 minutes, two casters' GCDs gone). The raid's encounter rules and the owner's icons still hold mobs. + if (!is_raid && po->second.cc_target.IsEmpty() && !(e.healer && e.src->in_combat)) { static std::mutex auto_cc_mx; static std::unordered_map auto_cc; // caster -> the mob it holds @@ -2452,7 +2504,9 @@ void PveGroupCoordinator::PlanRaidTanks(uint64 bkey, uint64 group_low, uint32 ma // The previous focus is kept while it is still a fair pick: a boss is not once adds are engaged (n31 mc_majordomo: the focus // fell on Majordomo in the first second, before the adds were counted, and the stickiness kept it for two minutes while the // raid hit a boss that cannot die and the adds killed it). - if (Mob const* pm = find_mob(prev); pm && pick && pm != pick && !pick_is_mt && !(adds_alive && is_boss(*pm->u)) && !never_target(*pm->u)) + // The main tank's target is no reason to leave a mob that a tank holds too: the tank's pick moves with every stun and + // drop, and the focus followed it every 2 s (UBRS 20 Oct, 27 -> 30 -> 27), a fresh curse and a new target each time. + if (Mob const* pm = find_mob(prev); pm && pick && pm != pick && !(pick_is_mt && !tank_held(*pm)) && !(adds_alive && is_boss(*pm->u)) && !never_target(*pm->u)) { const bool plu = loose_unowned(*pm); if ((plu || tank_held(*pm)) && (plu || !pick_loose)) @@ -2543,6 +2597,12 @@ void PveGroupCoordinator::PlanRaidTanks(uint64 bkey, uint64 group_low, uint32 ma fl.mob_hp.clear(); fl.dmg_total = 0; fl.dmg_last_ms = 0; + fl.start_mana.clear(); + for (auto const& e : mem) + { + TakeDamageDone(e.guid_low, true); + if (e.src && e.src->max_mana > 0) fl.start_mana[e.guid_low] = Pct(e.src->mana, e.src->max_mana); + } uint32 alive = 0, tanks = 0, healers = 0; for (auto const& e : mem) { @@ -2659,7 +2719,8 @@ void PveGroupCoordinator::PlanRaidTanks(uint64 bkey, uint64 group_low, uint32 ma if (e.src->is_casting) ++dps_cast; else if (!e.src->victim.IsEmpty()) ++dps_hit; if (!fight_focus.IsEmpty() && e.src->victim == fight_focus) ++dps_focus; - else ++dps_none; + // Idle = no victim and not casting. A bot on another mob than the focus is fighting (it counts under hitting). + if (e.src->victim.IsEmpty() && !e.src->is_casting) ++dps_none; if (e.src->max_mana > 0) { dps_mana_sum += Pct(e.src->mana, e.src->max_mana); ++dps_mana_n; } } uint64 dmg_window = 0; @@ -2681,7 +2742,7 @@ void PveGroupCoordinator::PlanRaidTanks(uint64 bkey, uint64 group_low, uint32 ma TC_LOG_INFO("playerbot.v2", "[raid_fight] group={} map={} t={}s alive={}/{} deaths={} | tanks: {} | mobs {} (loose {}): {} | " - "healers {} mana avg {}% under20% {} casting {} | dps bots {} casting {} hitting {} no target {} (on the focus {}) mana avg {}% | " + "healers {} mana avg {}% under20% {} casting {} | dps bots {} casting {} hitting {} idle {} (on the focus {}) mana avg {}% | " "raid damage {}/s now, {}/s avg, {} per dps bot", group_low, map_id, (now_ms - fl.started_ms) / 1000, alive, uint32(mem.size()), fl.deaths, tanks.empty() ? std::string("none alive") : tanks, uint32(mobs.size()), loose, @@ -2700,6 +2761,25 @@ void PveGroupCoordinator::PlanRaidTanks(uint64 bkey, uint64 group_low, uint32 ma "[raid_fight] group={} map={} pull ended after {}s: alive={}/{} deaths={} | raid damage seen {} ({}/s)", group_low, map_id, (now_ms - fl.started_ms) / 1000, alive, uint32(mem.size()), fl.deaths, fl.dmg_total, fl.dmg_total / std::max((now_ms - fl.started_ms) / 1000, 1)); + // One line per pull: what each damage dealer did to the mobs (own hits, DoTs and pet), highest first, so per-class tuning has numbers. + std::vector> rows; + uint32 const dur = std::max((now_ms - fl.started_ms) / 1000, 1); + for (auto const& e : mem) + { + uint64 const d = TakeDamageDone(e.guid_low, true); + if (e.tank || e.healer || !e.is_bot || !d) continue; + std::string mana; + auto const sm = fl.start_mana.find(e.guid_low); + if (sm != fl.start_mana.end() && e.src->max_mana > 0) + mana = ", mana " + std::to_string(sm->second) + ">" + std::to_string(Pct(e.src->mana, e.src->max_mana)) + "%"; + rows.emplace_back(d, std::string(e.src->name) + "(" + ShortClass(e.cls) + ") " + std::to_string(d) + " (" + + std::to_string(d / dur) + "/s" + mana + ")"); + } + std::sort(rows.begin(), rows.end(), [](auto const& a, auto const& b) { return a.first > b.first; }); + std::string txt; + for (auto const& r : rows) { if (!txt.empty()) txt += ", "; txt += r.second; } + if (!txt.empty()) + TC_LOG_INFO("playerbot.v2", "[raid_dps] group={} map={} pull of {}s, damage per dps bot: {}", group_low, map_id, dur, txt); fl.in_fight = false; } } diff --git a/src/modules/PlayerbotV2/Bot/Dungeon/PveGroupCoordinator.h b/src/modules/PlayerbotV2/Bot/Dungeon/PveGroupCoordinator.h index 843a7fdec1..f8634e2f0b 100644 --- a/src/modules/PlayerbotV2/Bot/Dungeon/PveGroupCoordinator.h +++ b/src/modules/PlayerbotV2/Bot/Dungeon/PveGroupCoordinator.h @@ -47,6 +47,7 @@ #include class Player; +class Unit; namespace Playerbot { @@ -69,6 +70,10 @@ public: return it == orders_.end() ? nullptr : &it->second; } + // Damage a player (or its pet) did to a creature, tallied per player for the [raid_dps] line. From Module::OnDamageTaken on the + // map's thread; takes its own lock. + static void NoteDamageDone(Unit* attacker, Unit* victim, int32 amount); + // Human-readable plan dump for `.playerbot pvecoord`. std::string DebugDump() const; @@ -111,6 +116,8 @@ private: std::unordered_map mob_hp; uint64 dmg_total = 0; uint32 dmg_last_ms = 0; + // Mana % of each member when the pull started, for the [raid_dps] line. + std::unordered_map start_mana; }; // Raid tank -> mob assignment for one (group, map) bucket, the generic diff --git a/src/modules/PlayerbotV2/Bot/Dungeon/Tactics/DungeonTacticsData_rfd.cpp b/src/modules/PlayerbotV2/Bot/Dungeon/Tactics/DungeonTacticsData_rfd.cpp index 0bbd135ca3..baabffdcb7 100644 --- a/src/modules/PlayerbotV2/Bot/Dungeon/Tactics/DungeonTacticsData_rfd.cpp +++ b/src/modules/PlayerbotV2/Bot/Dungeon/Tactics/DungeonTacticsData_rfd.cpp @@ -93,10 +93,11 @@ constexpr SpellTactic kSpells_rfd_7357[] = { }; constexpr SpellTactic kSpells_rfd_7358[] = { // spell, name, school, cast_ms, tags, dispel, target, when, first_min, first_max, repeat_min, repeat_max, hp_max, hp_min, ally_hp_max, range_min, range_max, amount, tick, counters, severity, holds_schools, flags - { 12642, "", 0, kCastUnknown, Tag::None, Disp::None, Tgt::Self, When::Combat, 0, 0, 0, 0, 100, 0, 0, 0, 0, 0, 0, Ctr::None, 0, 0, SF::None }, + { 12642, "Summon Frost Spectres", 1, 0, Tag::Summon, Disp::None, Tgt::Self, When::Combat, 0, 0, 0, 0, 66, 33, 0, 0, 0, 0, 0, Ctr::None, 2, 0, SF::Scripted }, + { 12642, "Summon Frost Spectres", 1, 0, Tag::Summon, Disp::None, Tgt::Self, When::Combat, 0, 0, 0, 0, 33, 1, 0, 0, 0, 0, 0, Ctr::None, 2, 0, SF::Scripted }, { 15530, "Frostbolt", 16, kCastUnknown, Tag::Nuke | Tag::Dmg, Disp::None, Tgt::Victim, When::Combat, 0, 0, 2000, 2000, 100, 0, 0, 5, 40, 196, 0, Ctr::Interrupt, 2, 0, SF::Ranged }, { 15531, "Frost Nova", 16, kCastUnknown, Tag::Dmg, Disp::None, Tgt::Victim, When::Combat, 0, 0, 10000, 15000, 100, 0, 0, 0, 5, 120, 0, Ctr::None, 1, 0, SF::None }, - { 13009, "", 0, kCastUnknown, Tag::None, Disp::None, Tgt::Victim, When::Combat, 8000, 8000, 12000, 12000, 100, 0, 0, 0, 0, 0, 0, Ctr::None, 0, 0, SF::None }, + { 13009, "Amnennar's Wrath", 1, 0, Tag::Knock, Disp::None, Tgt::Victim, When::Combat, 8000, 8000, 12000, 12000, 100, 0, 0, 0, 0, 0, 0, Ctr::None, 0, 0, SF::None }, }; constexpr SpellTactic kSpells_rfd_8567[] = { // spell, name, school, cast_ms, tags, dispel, target, when, first_min, first_max, repeat_min, repeat_max, hp_max, hp_min, ally_hp_max, range_min, range_max, amount, tick, counters, severity, holds_schools, flags @@ -125,7 +126,7 @@ constexpr MobTactic kMobs_rfd[] = { { 7355, "Tuten'kash", 40, 40, 1, 6, 0, 0, Mob::Boss, 0, Cc::FreezeTrap | Cc::Shackle, 1, 0x800010u, 0x0u, nullptr, 0, nullptr, 0, "" }, { 7356, "Plaguemaw the Rotting", 40, 40, 1, 7, 0, 0, Mob::Boss, 0, Cc::Polymorph | Cc::Sap | Cc::FreezeTrap, 1, 0x800010u, 0x0u, nullptr, 0, nullptr, 0, "" }, { 7357, "Mordresh Fire Eye", 39, 39, 1, 6, 8, 1, Mob::Boss | Mob::Caster, 0, Cc::FreezeTrap | Cc::Shackle, 1, 0x800010u, 0x0u, kSpells_rfd_7357, 2, nullptr, 0, "" }, - { 7358, "Amnennar the Coldbringer", 41, 41, 1, 6, 2, 1, Mob::Boss | Mob::Caster, 0, Cc::FreezeTrap | Cc::Shackle, 1, 0x800010u, 0x0u, kSpells_rfd_7358, 4, nullptr, 0, "" }, + { 7358, "Amnennar the Coldbringer", 41, 41, 1, 6, 2, 1, Mob::Boss | Mob::Caster, 0, Cc::FreezeTrap | Cc::Shackle, 1, 0x800010u, 0x0u, kSpells_rfd_7358, 5, nullptr, 0, "" }, { 8567, "Glutton", 40, 40, 1, 6, 1, 1, Mob::Boss, 0, Cc::FreezeTrap | Cc::Shackle, 1, 0x800010u, 0x0u, kSpells_rfd_8567, 2, nullptr, 0, "" }, }; diff --git a/src/modules/PlayerbotV2/Bot/Dungeon/Tactics/DungeonTacticsData_sm.cpp b/src/modules/PlayerbotV2/Bot/Dungeon/Tactics/DungeonTacticsData_sm.cpp index 4b37384aa5..5962f75283 100644 --- a/src/modules/PlayerbotV2/Bot/Dungeon/Tactics/DungeonTacticsData_sm.cpp +++ b/src/modules/PlayerbotV2/Bot/Dungeon/Tactics/DungeonTacticsData_sm.cpp @@ -20,15 +20,15 @@ constexpr SpellTactic kSpells_sm_3975[] = { }; constexpr SpellTactic kSpells_sm_3976[] = { // spell, name, school, cast_ms, tags, dispel, target, when, first_min, first_max, repeat_min, repeat_max, hp_max, hp_min, ally_hp_max, range_min, range_max, amount, tick, counters, severity, holds_schools, flags - { 9257, "", 0, kCastUnknown, Tag::None, Disp::None, Tgt::Invoker, When::Combat, 0, 0, 0, 0, 100, 0, 0, 0, 0, 0, 0, Ctr::None, 0, 0, SF::Scripted }, + { 9257, "Lay on Hands", 2, 0, Tag::Heal, Disp::None, Tgt::Invoker, When::Combat, 0, 0, 0, 0, 100, 0, 0, 0, 0, 0, 0, Ctr::None, 0, 0, SF::Scripted }, { 1020, "Divine Shield", 2, 0, Tag::Buff | Tag::Immune, Disp::None, Tgt::Self, When::Combat, 0, 0, 0, 0, 50, 1, 0, 0, 0, 0, 0, Ctr::StopDamage, 2, 127, SF::None }, { 14518, "Crusader Strike", 2, kCastUnknown, Tag::Dmg, Disp::None, Tgt::Victim, When::Combat, 6000, 12000, 6000, 18000, 100, 0, 0, 0, 0, 50, 0, Ctr::None, 0, 0, SF::None }, { 5589, "Hammer of Justice", 16, kCastUnknown, Tag::Stun, Disp::None, Tgt::Victim, When::Combat, 7000, 16000, 60000, 80000, 100, 0, 0, 0, 0, 0, 0, Ctr::None, 2, 0, SF::Unverified }, }; constexpr SpellTactic kSpells_sm_3977[] = { // spell, name, school, cast_ms, tags, dispel, target, when, first_min, first_max, repeat_min, repeat_max, hp_max, hp_min, ally_hp_max, range_min, range_max, amount, tick, counters, severity, holds_schools, flags - { 9256, "", 0, kCastUnknown, Tag::None, Disp::None, Tgt::Self, When::Combat, 0, 0, 0, 0, 50, 0, 0, 0, 0, 0, 0, Ctr::None, 0, 0, SF::None }, - { 9232, "", 0, kCastUnknown, Tag::None, Disp::None, Tgt::Self, When::Combat, 0, 0, 0, 0, 100, 0, 0, 0, 0, 0, 0, Ctr::None, 0, 0, SF::None }, + { 9256, "Deep Sleep", 32, 0, Tag::Sleep, Disp::None, Tgt::Self, When::Combat, 0, 0, 0, 0, 50, 0, 0, 0, 0, 0, 0, Ctr::None, 2, 0, SF::None }, + { 9232, "Scarlet Resurrection", 1, 2000, Tag::Heal, Disp::None, Tgt::Friendly, When::Combat, 0, 0, 0, 0, 100, 0, 0, 0, 0, 0, 0, Ctr::Interrupt, 3, 0, SF::Unverified }, { 14515, "Dominate Mind", 32, kCastUnknown, Tag::Charm, Disp::None, Tgt::RandomNotTop, When::Combat, 15000, 30000, 60000, 60000, 100, 0, 0, 0, 0, 0, 0, Ctr::Interrupt, 3, 0, SF::Unverified }, { 12039, "Heal", 2, 2500, Tag::Heal, Disp::None, Tgt::Friendly, When::Combat, 0, 0, 30000, 60000, 100, 0, 60, 0, 0, 637, 0, Ctr::Interrupt, 3, 0, SF::None }, { 22187, "Power Word: Shield", 0, kCastUnknown, Tag::Shield, Disp::None, Tgt::Invoker, When::AllyUnbuffed, 0, 0, 10000, 30000, 100, 0, 0, 0, 0, 0, 0, Ctr::None, 2, 0, SF::None }, diff --git a/src/modules/PlayerbotV2/Bot/FalseCombatEscape.h b/src/modules/PlayerbotV2/Bot/FalseCombatEscape.h new file mode 100644 index 0000000000..f8f3357019 --- /dev/null +++ b/src/modules/PlayerbotV2/Bot/FalseCombatEscape.h @@ -0,0 +1,50 @@ +// FalseCombatEscape - where a dungeon bot walks when it is held in combat by attackers it can never hit +// (State_Idle DungeonCombatPositioning, [false_combat_esc]). +// +// Pure function on plain values, so the choice is unit-tested without a server. +// +// The escape was written for the dungeon autopilot: the tank walks on to the next boss it owes, the others walk to the tank. +// A bot the autopilot is suspended for (a human leads, Passive, a follow / stay / fallback order) has no pulls of its own, so it +// never walks to a boss: it walks to the player it follows, else it drops the fight in place (UBRS 2026-10-26: a passive +// companion tank summoned in with three Urok Enforcers on its threat list walked to the first boss's waypoint for minutes, +// pulling every pack on the way while the group defended it). + +#pragma once + +namespace Playerbot::FalseCombatEscape { + +enum class Goal { BossWaypoint, Tank, Leader, Disengage }; + +struct Inputs +{ + bool autopilot = true; // the dungeon autopilot leads this bot (not suspended) + bool is_tank = false; + bool tank_known = false; // a live group tank on this map, other than the bot + bool leader_known = false; // the player the bot follows, alive on this map and more than 8 y away + bool immune_lock = false; // only immune attackers hold it: walking re-aggros them + bool far_from_boss = false; // the boss it owes is 40 y or more away +}; + +inline Goal Pick(Inputs const& in) +{ + if (!in.autopilot) + return in.leader_known ? Goal::Leader : Goal::Disengage; + if (in.immune_lock || !in.far_from_boss) + return Goal::Disengage; + if (!in.is_tank) + return in.tank_known ? Goal::Tank : Goal::Disengage; + return Goal::BossWaypoint; +} + +inline char const* Tag(Goal g) +{ + switch (g) + { + case Goal::BossWaypoint: return "boss_wp"; + case Goal::Tank: return "TANK"; + case Goal::Leader: return "LEADER"; + default: return ""; + } +} + +} // namespace Playerbot::FalseCombatEscape diff --git a/src/modules/PlayerbotV2/Bot/Gear/ArmorSwapGate.h b/src/modules/PlayerbotV2/Bot/Gear/ArmorSwapGate.h new file mode 100644 index 0000000000..cbddcc9230 --- /dev/null +++ b/src/modules/PlayerbotV2/Bot/Gear/ArmorSwapGate.h @@ -0,0 +1,13 @@ +#pragma once +// Armor cannot be put on or taken off while a bot is fighting (EQUIP_ERR_NOT_IN_COMBAT, 61) or casting (EQUIP_ERR_CLIENT_LOCKED_OUT, 40). +// The gear step stores each generated piece before it equips it, so it must not start at all in that state: it would refuse every piece +// and still be marked done. Pure: tested in tests/game/ClassicArmorSwapGate.cpp. + +namespace Playerbot::Gear { + +constexpr bool CanSwapArmorNow(bool in_combat, bool casting) +{ + return !in_combat && !casting; +} + +} // namespace Playerbot::Gear diff --git a/src/modules/PlayerbotV2/Bot/Gear/BisPools.cpp b/src/modules/PlayerbotV2/Bot/Gear/BisPools.cpp new file mode 100644 index 0000000000..25ec8163ee --- /dev/null +++ b/src/modules/PlayerbotV2/Bot/Gear/BisPools.cpp @@ -0,0 +1,119 @@ +#include "BisPools.h" + +namespace Playerbot::Gear::Bis { + +namespace { + +// Melee: warrior, rogue, retribution paladin, enhancement shaman (their Phase 6 raid lists, merged). +constexpr PoolEntry kMelee[] = { + { Kind::Trinket, 1, "Diamond Flask" }, + { Kind::Trinket, 1, "Hand of Justice" }, + { Kind::Trinket, 1, "Earthstrike" }, + { Kind::Trinket, 2, "Drake Fang Talisman" }, + { Kind::Trinket, 3, "Slayer's Crest" }, + { Kind::Trinket, 3, "Kiss of the Spider" }, + { Kind::Trinket, 3, "Jom Gabbar" }, + { Kind::Neck, 2, "Prestor's Talisman of Connivery" }, + { Kind::Neck, 3, "Stormrage's Talisman of Seething" }, + { Kind::Back, 3, "Shroud of Dominion" }, + { Kind::Back, 3, "Cloak of the Fallen God" }, + { Kind::Ring, 1, "Don Julio's Band" }, + { Kind::Ring, 2, "Circle of Applied Force" }, + { Kind::Ring, 3, "Band of Unnatural Forces" }, + { Kind::Ring, 3, "Bonescythe Ring" }, + { Kind::Ring, 3, "Ring of the Qiraji Fury" }, +}; + +// Hunter. +constexpr PoolEntry kHunter[] = { + { Kind::Trinket, 1, "Blackhand's Breadth" }, + { Kind::Trinket, 1, "Earthstrike" }, + { Kind::Trinket, 3, "Slayer's Crest" }, + { Kind::Trinket, 3, "Kiss of the Spider" }, + { Kind::Neck, 2, "Prestor's Talisman of Connivery" }, + { Kind::Back, 3, "Cloak of the Fallen God" }, + { Kind::Ring, 3, "Ring of the Cryptstalker" }, + { Kind::Ring, 3, "Band of Reanimation" }, +}; + +// Casters: mage, warlock, shadow priest, balance druid. +constexpr PoolEntry kCaster[] = { + { Kind::Trinket, 2, "Mind Quickening Gem" }, + { Kind::Trinket, 2, "Neltharion's Tear" }, + { Kind::Trinket, 3, "The Restrained Essence of Sapphiron" }, + { Kind::Trinket, 3, "Mark of the Champion" }, + { Kind::Neck, 1, "Choker of the Fire Lord" }, + { Kind::Neck, 3, "Amulet of Vek'nilash" }, + { Kind::Neck, 3, "Gem of Trapped Innocents" }, + { Kind::Neck, 3, "Malice Stone Pendant" }, + { Kind::Back, 3, "Cloak of the Necropolis" }, + { Kind::Back, 3, "Cloak of the Devoured" }, + { Kind::Ring, 3, "Frostfire Ring" }, + { Kind::Ring, 3, "Ring of the Eternal Flame" }, + { Kind::Ring, 3, "Ring of the Fallen God" }, + { Kind::Ring, 3, "Band of the Inevitable" }, + // Off hand and wand, from the items this client has (itemsparse-decoded.tsv 2026-10-22): the vanilla caster weapons by name (Staff of the Shadow + // Flame, Hand of Edward the Odd, Sapphiron's Eyes, Wand of Qiraji Nobility) are not in its item table. Kris of Unspoken Names stays the main hand. + { Kind::Offhand, 1, "Therazane's Touch" }, + { Kind::Offhand, 2, "Master Dragonslayer's Orb" }, + { Kind::Offhand, 3, "Royal Scepter of Vek'lor" }, + { Kind::Ranged, 1, "Greater Eternal Wand" }, + { Kind::Ranged, 1, "Brilliant Wand" }, +}; + +// Healers: priest, druid, paladin, shaman. +constexpr PoolEntry kHealer[] = { + { Kind::Trinket, 1, "Zandalarian Hero Charm" }, + { Kind::Trinket, 1, "Shard of the Scale" }, + { Kind::Trinket, 2, "Rejuvenating Gem" }, + { Kind::Trinket, 3, "Warmth of Forgiveness" }, + { Kind::Trinket, 3, "Eye of the Dead" }, + { Kind::Trinket, 3, "Scarab Brooch" }, + { Kind::Neck, 3, "Amulet of the Fallen God" }, + { Kind::Neck, 3, "Necklace of Necropsy" }, + { Kind::Back, 3, "Cloak of Suturing" }, + { Kind::Back, 3, "Cloak of Clarity" }, + { Kind::Ring, 2, "Pure Elementium Band" }, + { Kind::Ring, 3, "Ring of Faith" }, + { Kind::Ring, 3, "Band of Unanswered Prayers" }, + { Kind::Ring, 3, "Ring of the Martyr" }, + { Kind::Ring, 3, "Ring of Redemption" }, + { Kind::Ring, 3, "Ring of the Earthshatterer" }, +}; + +// Tanks: protection warrior, feral druid (defensive and threat entries both; the role score decides). +constexpr PoolEntry kTank[] = { + { Kind::Trinket, 1, "Earthstrike" }, + { Kind::Trinket, 1, "Diamond Flask" }, + { Kind::Trinket, 1, "Nat Pagle's Broken Reel" }, + { Kind::Trinket, 2, "Drake Fang Talisman" }, + { Kind::Trinket, 2, "Lifegiving Gem" }, + { Kind::Trinket, 2, "Styleen's Impeding Scarab" }, + { Kind::Trinket, 3, "Kiss of the Spider" }, + { Kind::Neck, 3, "Mark of C'Thun" }, + { Kind::Neck, 3, "Sadist's Collar" }, + { Kind::Back, 3, "Cloak of the Fallen God" }, + { Kind::Back, 3, "Cryptfiend Silk Cloak" }, + { Kind::Ring, 2, "Circle of Applied Force" }, + { Kind::Ring, 3, "Ring of the Dreadnaught" }, + { Kind::Ring, 3, "Ring of Emperor Vek'lor" }, + { Kind::Ring, 3, "Ring of the Godslayer" }, + { Kind::Ring, 3, "Signet of the Fallen Defender" }, +}; + +} // namespace + +std::span PoolFor(Loadout::Role role) +{ + switch (role) + { + case Loadout::Role::Melee: return kMelee; + case Loadout::Role::Hunter: return kHunter; + case Loadout::Role::Caster: return kCaster; + case Loadout::Role::Healer: return kHealer; + case Loadout::Role::Tank: return kTank; + } + return {}; +} + +} // namespace Playerbot::Gear::Bis diff --git a/src/modules/PlayerbotV2/Bot/Gear/BisPools.h b/src/modules/PlayerbotV2/Bot/Gear/BisPools.h new file mode 100644 index 0000000000..95398da95f --- /dev/null +++ b/src/modules/PlayerbotV2/Bot/Gear/BisPools.h @@ -0,0 +1,30 @@ +#pragma once +// BisPools - best-in-slot candidates of a raid tier for the slots a class tier set does not cover (neck, back, rings, trinkets), by raid role. +// +// The names come from the Icy Veins Season of Mastery Phase 6 (Naxxramas) raid lists, fetched 2026-10-22: warrior dps and tank, rogue, hunter, +// mage, warlock, shadow priest, balance druid, retribution paladin, enhancement shaman, feral tank, and the priest, druid, paladin and shaman +// healer pages. The tier of an entry is where the item is first available. Each name is a +// CANDIDATE, never a command. The gear generator resolves a name to an item in the item data, drops a name the data +// lacks (logged once as "[bis] unresolved"), and takes a candidate for a slot only when the role-weighted raid score +// (Gear::ScoreItemRaid) beats what the generator picked there, under the tier's item level ceiling. A wrong or missing name therefore costs +// nothing. Pure data: tested in tests/game/ClassicBisPools.cpp. + +#include "RaidLoadout.h" + +namespace Playerbot::Gear::Bis { + +enum class Kind : std::uint8_t { Neck, Back, Ring, Trinket, Offhand, Ranged }; + +struct PoolEntry +{ + Kind kind; + std::uint8_t tier; // first tier (1 = Molten Core / Onyxia, 2 = Blackwing Lair, 3 = Ahn'Qiraj / Naxxramas) the item is available in + std::string_view name; // exact English item name +}; + +// All entries a role may use in `tier` (those with entry.tier <= tier), in the order of the table. +std::span PoolFor(Loadout::Role role); + +constexpr bool InTier(PoolEntry const& e, int tier) { return e.tier <= tier; } + +} // namespace Playerbot::Gear::Bis diff --git a/src/modules/PlayerbotV2/Bot/Gear/BotGearGenerator.cpp b/src/modules/PlayerbotV2/Bot/Gear/BotGearGenerator.cpp index 9b22dbf7b8..436059b648 100644 --- a/src/modules/PlayerbotV2/Bot/Gear/BotGearGenerator.cpp +++ b/src/modules/PlayerbotV2/Bot/Gear/BotGearGenerator.cpp @@ -1,6 +1,7 @@ #include "BotGearGenerator.h" #include "BotItemScorer.h" #include "OwnedGearPolicy.h" +#include "BisPools.h" #include "WorldGearStart.h" #include "Bot/ClassTables.h" // MaxPlayerLevel() #include "ObjectMgr.h" @@ -9,6 +10,7 @@ #include "Player.h" #include "PlayerbotAPI.h" // IsItemRenderableInSlot — the renderability gate #include "Log.h" +#include "World.h" #include "Config.h" #include "../BotSnapshot.h" // PlanEquipOrder #include "../../Services.h" // Services::Config(): Playerbot.Behavior.TankRangedWeapon @@ -22,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -126,6 +129,21 @@ constexpr std::array kSlots = { EQUIPMENT_SLOT_RANGED, // Classic 1.60: bows, guns, crossbows, thrown and wands have their own slot (Player::FindEquipSlot) }; +// The slots resistance gear goes in (GearGenerationContext::resist_school): armour and jewellery. Weapons, trinkets and the ranged slot +// keep their role picks, as a raider dressing for Huhuran kept its weapons. +constexpr bool ResistGearSlot(uint8 slot) +{ + switch (slot) + { + case EQUIPMENT_SLOT_HEAD: case EQUIPMENT_SLOT_NECK: case EQUIPMENT_SLOT_SHOULDERS: case EQUIPMENT_SLOT_CHEST: case EQUIPMENT_SLOT_WAIST: + case EQUIPMENT_SLOT_LEGS: case EQUIPMENT_SLOT_FEET: case EQUIPMENT_SLOT_WRISTS: case EQUIPMENT_SLOT_HANDS: case EQUIPMENT_SLOT_FINGER1: + case EQUIPMENT_SLOT_FINGER2: case EQUIPMENT_SLOT_BACK: + return true; + default: + return false; + } +} + // Preferred armor tier comes from BotItemScorer - ONE definition shared with // the scorer that ranks these pools. Keeping a second copy here is what let the // two drift apart. @@ -239,6 +257,38 @@ bool IsBotWearableItemId(uint32 entry) return !tpl || tpl->ExtendedData->RequiredPVPRank <= 0; } +// A whole word "Test" or "Deprecated" in the name, any case: developer items that ship in the item data. The same holds for the placeholders +// the client data carries for unfinished items: "[PH]" / "PH]" / "[DNT]" markers, "Nax PH ..." and the "90 Epic Warrior Cloak" stand-ins +// (item level 90, above every raid cap but not real gear; found decoding ItemSparse.db2, 224 names). +static bool IsTestItemName(std::string const& name) +{ + std::string lower; + lower.reserve(name.size()); + for (char c : name) lower.push_back(char(std::tolower(static_cast(c)))); + if (lower.find("ph]") != std::string::npos || lower.find("dnt]") != std::string::npos || lower.find(" ph ") != std::string::npos) + return true; + { + size_t digits = 0; + while (digits < lower.size() && std::isdigit(static_cast(lower[digits]))) ++digits; + if (digits > 0 && lower.compare(digits, 1, " ") == 0) + for (char const* tier : { "epic ", "green ", "rare ", "blue ", "purple " }) + if (lower.compare(digits + 1, std::strlen(tier), tier) == 0) + return true; + } + for (char const* word : { "test", "deprecated" }) + { + for (size_t pos = lower.find(word); pos != std::string::npos; pos = lower.find(word, pos + 1)) + { + size_t const end = pos + std::strlen(word); + bool const start_ok = pos == 0 || !std::isalpha(static_cast(lower[pos - 1])); + bool const end_ok = end >= lower.size() || !std::isalpha(static_cast(lower[end])); + if (start_ok && end_ok) + return true; + } + } + return false; +} + void Initialize() { if (g_initialized) return; @@ -278,6 +328,8 @@ void Initialize() // rejects them outright with EQUIP_ERR_CANT_EQUIP_EVER. if (tpl.HasFlag(ITEM_FLAG2_INTERNAL_ITEM)) continue; if (!IsBotWearableItemId(entry)) continue; + // A developer test item ("Fast Test Thrown", item 5559) is not gear: bots wore it as their thrown weapon (PC 20 Oct). + if (IsTestItemName(tpl.GetName(DEFAULT_LOCALE))) continue; // Skip items with too-high required level for our brackets if (tpl.GetBaseRequiredLevel() > MaxPlayerLevel()) continue; // Skip items with no required level set BUT high ilvl (raid drops typically) @@ -678,13 +730,21 @@ uint32 PickThrownWeapon(Player const* wearer) if (!g_initialized || !wearer || wearer->GetClass() >= MAX_CLASSES) return 0; uint8 const level = wearer->GetLevel(); ItemTemplate const* best = nullptr; - // A thrown weapon whose display is the generic 1.60 one is drawn by the client as a white box with blue dots: + // A thrown weapon whose display is the generic 1.60 one is drawn by the client as a white box with blue dots (UBRS, 20 Oct): // a weapon with its own display goes first, whatever its level. auto key = [&](ItemTemplate const* t) { return std::tuple(Player::HasDrawableAmmoDisplay(t), t->GetBaseRequiredLevel(), uint32(t->GetQuality()), ::Playerbot::Gear::EffectiveItemLevelForLevel(t, level), ~t->GetId()); }; + static std::once_flag thrown_log_once; + std::call_once(thrown_log_once, [&] + { + for (ItemTemplate const* tpl : g_pools[wearer->GetClass()].slots[EQUIPMENT_SLOT_RANGED]) + if (tpl->GetClass() == ITEM_CLASS_WEAPON && tpl->GetSubClass() == ITEM_SUBCLASS_WEAPON_THROWN) + TC_LOG_INFO("playerbot.v2", "[thrown_display] item {} required level {} display {} drawable {}", tpl->GetId(), tpl->GetBaseRequiredLevel(), + Player::GetAmmoDisplayId(tpl), int(Player::HasDrawableAmmoDisplay(tpl))); + }); for (ItemTemplate const* tpl : g_pools[wearer->GetClass()].slots[EQUIPMENT_SLOT_RANGED]) { if (tpl->GetClass() != ITEM_CLASS_WEAPON || tpl->GetSubClass() != ITEM_SUBCLASS_WEAPON_THROWN) continue; @@ -704,7 +764,7 @@ std::vector GenerateGearFor(GearGenerationContext const& ctx) std::vector out; if (!g_initialized || ctx.cls < 1 || ctx.cls >= MAX_CLASSES) return out; // A world bot below level 10 keeps its starting outfit (WorldGearStart.h). - if (!::Playerbot::Gear::GeneratesGear(ctx.world_bot(), ctx.level)) return out; + if (!::Playerbot::Gear::GeneratesGear(ctx.world_bot(), ctx.level, ctx.replace_unrenderable_starter)) return out; uint16 const target_ilvl = TargetIlvlForLevel(ctx.level); auto const& pool = g_pools[ctx.cls]; @@ -729,6 +789,11 @@ std::vector GenerateGearFor(GearGenerationContext const& ctx) // Tier modes (an owner's "gear t3"): the tier set below, and the other slots up to that tier's item level. bool const tier_mode = raid && !ctx.world_bot() && Owned::IsTierMode(ctx.gear_mode); bool const bis_mode = raid && !ctx.world_bot() && ctx.gear_mode == Owned::GearMode::Bis; + // Resistance gear for a fight (ctx.resist_school): a piece with the school's resistance outranks any stat fit in the armour and + // jewellery slots, more resistance first; the slots it fills are kept from the tier set below. + bool const resist_mode = raid && !ctx.world_bot() && ctx.resist_school != 0; + constexpr int32 kResistPick = 10000000; + std::array resist_held{}; int32 const raid_cap = ctx.world_bot() ? WorldIlvlCap() : tier_mode ? CapForTier(float(Owned::TierNumber(ctx.gear_mode))) : bis_mode ? CapForTier(3.0f) @@ -787,7 +852,10 @@ std::vector GenerateGearFor(GearGenerationContext const& ctx) // below the pre-raid rares, so a roster does not wear one set. bool const world_mix = raid && ctx.world_bot() && ctx.bot_id; bool const pvp_slot = world_mix && WorldPvpSetBot(ctx.bot_id) && PvpSetSlot(slot); - for (int pass = raid ? 0 : 1; pass < 2 && (!best || world_mix); ++pass) + bool const resist_slot = resist_mode && ResistGearSlot(slot); + // A resistance slot runs the plain pass too when the raid-prep pass found no piece with the school's resistance: a green of it + // beats a blue without, as the raiders of the day wore them. + for (int pass = raid ? 0 : 1; pass < 2 && (!best || world_mix || (resist_slot && best_score < kResistPick)); ++pass) for (auto const* tpl : candidates) { if (tpl->GetBaseRequiredLevel() > ctx.level) continue; @@ -855,6 +923,9 @@ std::vector GenerateGearFor(GearGenerationContext const& ctx) // nothing better can. bool const prep = tpl->GetQuality() >= ITEM_QUALITY_RARE && tpl->GetBaseRequiredLevel() >= int32(kRaidMinRequiredLevel); combined = fit + (prep ? 1000000 : 0) + (pvp_piece ? 100000 : 0); + if (resist_slot) + if (int32 const points = ::Playerbot::Gear::ResistPoints(tpl, ctx.resist_school, ctx.level); points > 0) + combined += kResistPick + points * 20000; // the stat fit only decides between pieces of equal resistance } else if (owned_lv) { @@ -878,6 +949,7 @@ std::vector GenerateGearFor(GearGenerationContext const& ctx) // Raid-ready variety: any of the best few (same tier, within a few percent of the best score) by the bot's guid and // the slot. Stable for a given bot, so regear never churns. + bool const resist_pick = resist_slot && best && best_score >= kResistPick; if (world_mix && best && scored.size() > 1) { uint64 h = ctx.bot_id * 0x9E3779B97F4A7C15ull ^ (uint64(slot) + 11) * 0xA24BAED4963EE407ull; @@ -907,6 +979,8 @@ std::vector GenerateGearFor(GearGenerationContext const& ctx) else if (options.size() == 1) best = options[0]; } + else if (resist_pick) + resist_held[slot] = true; // the most resistance, no variety roll among the pieces else if ((raid || owned_lv) && best && ctx.bot_id && !bis_mode) { bool const best_prep = best_score >= 500000; @@ -956,9 +1030,47 @@ std::vector GenerateGearFor(GearGenerationContext const& ctx) // empty slot, but only when the item may actually be worn twice - for a // unique-equipped piece the second equip would be refused and we would // have produced a pick that can never land. - if (!best && twin && !twin->HasFlag(ITEM_FLAG_UNIQUE_EQUIPPABLE)) + if (!best && twin && !twin->HasFlag(ITEM_FLAG_UNIQUE_EQUIPPABLE) && twin->GetMaxCount() != 1) best = twin; + // A tier leg whose main hand stays empty fights with fists (damage_parity 147 shaman, t1: no weapon, 107 dps): say which filter emptied the pool. + if (!best && tier_mode && slot == EQUIPMENT_SLOT_MAINHAND) + { + uint32 n_level = 0, n_skill = 0, n_wear = 0, n_ilvl = 0, n_fit = 0; + for (auto const* tpl : candidates) + { + if (tpl->GetBaseRequiredLevel() > ctx.level) { ++n_level; continue; } + if (ctx.wearer && ctx.wearer->CanUseItem(tpl) != EQUIP_ERR_OK) { ++n_wear; continue; } + if (ctx.wearer && tpl->GetSkill() && !ctx.wearer->GetSkillValue(tpl->GetSkill())) { ++n_skill; continue; } + if (::Playerbot::Gear::IsPvpItem(tpl) || ::Playerbot::Gear::EffectiveItemLevelForLevel(tpl, ctx.level) > raid_cap) { ++n_ilvl; continue; } + if (::Playerbot::Gear::ScoreItemRaid(tpl, ctx.cls, ctx.spec, ctx.level, slot) <= -100000) ++n_fit; + } + TC_LOG_INFO("playerbot.v2", "[gear_gen] class {} spec {} level {}: no main hand under item level {}: {} candidates, {} above the level, {} refused by CanUseItem, {} without the skill, {} over the cap or PvP, {} refused by the stat weights", + uint32(ctx.cls), uint32(ctx.spec), uint32(ctx.level), raid_cap, candidates.size(), n_level, n_wear, n_skill, n_ilvl, n_fit); + } + + // A tier leg's off hand that is not a raid-prep weapon (fury t1 wore Left-Handed Blades, item level 35, while one-handers of item level 76 exist): + // count the prep weapons of the pool by the filter that removed each, so the next run names the cause. + if (tier_mode && slot == EQUIPMENT_SLOT_OFFHAND && ctx.cls == CLASS_WARRIOR && (!best || best->GetQuality() < ITEM_QUALITY_RARE || + best->GetBaseRequiredLevel() < int32(kRaidMinRequiredLevel))) + { + uint32 n_prep = 0, n_level = 0, n_wear = 0, n_skill = 0, n_cap = 0, n_fit = 0, n_dual = 0, n_ok = 0; + for (auto const* tpl : candidates) + { + if (tpl->GetClass() != ITEM_CLASS_WEAPON || tpl->GetQuality() < ITEM_QUALITY_RARE || tpl->GetBaseRequiredLevel() < int32(kRaidMinRequiredLevel)) continue; + ++n_prep; + if (tpl->GetBaseRequiredLevel() > ctx.level) { ++n_level; continue; } + if (ctx.wearer && ctx.wearer->CanUseItem(tpl) != EQUIP_ERR_OK) { ++n_wear; continue; } + if (ctx.wearer && tpl->GetSkill() && !ctx.wearer->GetSkillValue(tpl->GetSkill())) { ++n_skill; continue; } + if (::Playerbot::Gear::IsPvpItem(tpl) || ::Playerbot::Gear::EffectiveItemLevelForLevel(tpl, ctx.level) > raid_cap) { ++n_cap; continue; } + if (!can_dual_wield) { ++n_dual; continue; } + if (::Playerbot::Gear::ScoreItemRaid(tpl, ctx.cls, ctx.spec, ctx.level, slot) <= -100000) { ++n_fit; continue; } + ++n_ok; + } + TC_LOG_INFO("playerbot.v2", "[gear_gen] class {} spec {} level {}: off hand pick {} is not a prep weapon; pool has {} prep weapons ({} above the level, {} refused by CanUseItem, {} without the skill, {} over the cap or PvP, {} with no dual wield, {} refused by the stat weights, {} usable)", + uint32(ctx.cls), uint32(ctx.spec), uint32(ctx.level), best ? best->GetId() : 0u, n_prep, n_level, n_wear, n_skill, n_cap, n_dual, n_fit, n_ok); + } + if (best) { out.push_back({slot, best->GetId()}); @@ -973,7 +1085,40 @@ std::vector GenerateGearFor(GearGenerationContext const& ctx) { // The class tier set goes on over the raid picks: the slots it covers are its own, the rest keep the picks made under the tier's // item level ceiling above. - for (uint32 const entry : TierSetPieces(ctx.cls, Owned::TierNumber(ctx.gear_mode))) + // A class and spec with a sourced list (warrior dps, Tier 3) wears that list, slot by slot, instead of the tier set. + auto const& sourced = SourcedTierGear(ctx.cls, ctx.spec, ctx.gear_mode); + uint32 sourced_slots = 0; + for (SourcedGearPick const& pick : sourced) + { + ItemTemplate const* tpl = sObjectMgr->GetItemTemplate(pick.entry); + if (!tpl || resist_held[pick.slot] || (ctx.wearer && ctx.wearer->CanUseItem(tpl) != EQUIP_ERR_OK)) + { + TC_LOG_INFO("playerbot.v2", "[gear] bot {} sourced pick {} for slot {} skipped: {}", ctx.bot_id, pick.entry, uint32(pick.slot), + !tpl ? "no such item in the item data" : resist_held[pick.slot] ? "slot held by resistance gear" + : fmt::format("CanUseItem error {}", uint32(ctx.wearer->CanUseItem(tpl)))); + continue; + } + if (ctx.race) + { + if (!tpl->GetAllowableRace().HasRace(ctx.race)) continue; + uint32 const team = ::Player::TeamForRace(ctx.race); + if (tpl->HasFlag(ITEM_FLAG2_FACTION_HORDE) && team != HORDE) continue; + if (tpl->HasFlag(ITEM_FLAG2_FACTION_ALLIANCE) && team != ALLIANCE) continue; + } + sourced_slots |= 1u << pick.slot; + auto it = std::ranges::find(out, pick.slot, &GearItem::slot); + if (it != out.end()) + it->item_entry = pick.entry; + else + out.push_back({ pick.slot, pick.entry }); + } + // A two-hander in the main hand leaves no off hand. + if (!sourced.empty()) + if (auto mh = std::ranges::find(out, uint8(EQUIPMENT_SLOT_MAINHAND), &GearItem::slot); mh != out.end()) + if (ItemTemplate const* mtpl = sObjectMgr->GetItemTemplate(mh->item_entry); mtpl && mtpl->GetInventoryType() == INVTYPE_2HWEAPON) + std::erase_if(out, [](GearItem const& g) { return g.slot == EQUIPMENT_SLOT_OFFHAND; }); + // The tier set fills the slots the sourced list did not set (a sourced entry the item data lacks leaves its slot to the set). + for (uint32 const entry : !TierSetIsHealerSet(ctx.cls, ctx.spec) ? TierSetPieces(ctx.cls, Owned::TierNumber(ctx.gear_mode)) : std::vector{}) { ItemTemplate const* tpl = sObjectMgr->GetItemTemplate(entry); if (!tpl) @@ -984,7 +1129,7 @@ std::vector GenerateGearFor(GearGenerationContext const& ctx) for (uint8 s : { uint8(EQUIPMENT_SLOT_HEAD), uint8(EQUIPMENT_SLOT_SHOULDERS), uint8(EQUIPMENT_SLOT_CHEST), uint8(EQUIPMENT_SLOT_WAIST), uint8(EQUIPMENT_SLOT_LEGS), uint8(EQUIPMENT_SLOT_FEET), uint8(EQUIPMENT_SLOT_WRISTS), uint8(EQUIPMENT_SLOT_HANDS) }) if (InventoryTypeFitsSlot(s, tpl->GetInventoryType())) { slot = s; break; } - if (slot == 255) + if (slot == 255 || resist_held[slot] || (sourced_slots & (1u << slot))) continue; if (ctx.wearer && ctx.wearer->CanUseItem(tpl) != EQUIP_ERR_OK) continue; @@ -1002,6 +1147,151 @@ std::vector GenerateGearFor(GearGenerationContext const& ctx) out.push_back({ slot, entry }); } } + // Best-in-slot candidates of the tier for the slots no tier set covers (BisPools.h): neck, back, rings, trinkets. A candidate goes on only when + // the role-weighted raid score beats what the pick above holds there, under the tier's item level ceiling; unknown names are skipped. + if (tier_mode) + { + int const tier = int(Owned::TierNumber(ctx.gear_mode)); + auto const role = ::Playerbot::Gear::Loadout::Role(uint8(::Playerbot::Gear::RaidRoleForBot(ctx.cls, ctx.spec))); + auto const resolve = [](std::string_view name) -> uint32 + { + static std::mutex lock; + static std::unordered_map cache; + std::lock_guard g(lock); + std::string const key(name); + if (auto it = cache.find(key); it != cache.end()) + return it->second; + uint32 found = 0; + LocaleConstant const loc = sWorld->GetDefaultDbcLocale(); + for (auto const& [id, tpl] : sObjectMgr->GetItemTemplateStore()) + { + char const* n = tpl.GetName(loc); + if (n && name == n && (!found || tpl.GetBaseItemLevel() > sObjectMgr->GetItemTemplate(found)->GetBaseItemLevel())) + found = id; + } + if (!found) + TC_LOG_INFO("playerbot.v2", "[bis] unresolved: no item named \"{}\" in the item data", name); + cache.emplace(key, found); + return found; + }; + auto const score_of = [&](uint8 slot) -> int32 + { + auto it = std::ranges::find(out, slot, &GearItem::slot); + ItemTemplate const* t = it != out.end() ? sObjectMgr->GetItemTemplate(it->item_entry) : nullptr; + return t ? ::Playerbot::Gear::ScoreItemRaid(t, ctx.cls, ctx.spec, ctx.level, slot) : 0; + }; + struct KindSlots { ::Playerbot::Gear::Bis::Kind kind; std::array slots; }; + for (KindSlots const& ks : { KindSlots{ ::Playerbot::Gear::Bis::Kind::Neck, { EQUIPMENT_SLOT_NECK, 255 } }, KindSlots{ ::Playerbot::Gear::Bis::Kind::Back, { EQUIPMENT_SLOT_BACK, 255 } }, + KindSlots{ ::Playerbot::Gear::Bis::Kind::Ring, { EQUIPMENT_SLOT_FINGER1, EQUIPMENT_SLOT_FINGER2 } }, + KindSlots{ ::Playerbot::Gear::Bis::Kind::Trinket, { EQUIPMENT_SLOT_TRINKET1, EQUIPMENT_SLOT_TRINKET2 } }, + KindSlots{ ::Playerbot::Gear::Bis::Kind::Offhand, { EQUIPMENT_SLOT_OFFHAND, 255 } }, + KindSlots{ ::Playerbot::Gear::Bis::Kind::Ranged, { EQUIPMENT_SLOT_RANGED, 255 } } }) + { + // No off hand next to a two-hand weapon. + if (ks.kind == ::Playerbot::Gear::Bis::Kind::Offhand) + { + auto mh = std::ranges::find(out, uint8(EQUIPMENT_SLOT_MAINHAND), &GearItem::slot); + ItemTemplate const* mt = mh != out.end() ? sObjectMgr->GetItemTemplate(mh->item_entry) : nullptr; + if (mt && mt->GetInventoryType() == INVTYPE_2HWEAPON) + continue; + } + std::vector taken; + for (uint8 const slot : ks.slots) + { + if (slot == 255 || resist_held[slot]) + continue; + ItemTemplate const* best = nullptr; + // A ring or trinket is unique: what the paired slot holds is not a candidate here (damage_parity 164: the same Band of Unnatural + // Forces and Slayer's Crest were picked for both slots, and the second copy was refused with error 17). + std::vector in_pair = taken; + for (uint8 const other : ks.slots) + if (other != 255 && other != slot) + if (auto held = std::ranges::find(out, other, &GearItem::slot); held != out.end()) + in_pair.push_back(held->item_entry); + auto cur_pick = std::ranges::find(out, slot, &GearItem::slot); + bool const cur_dup = cur_pick != out.end() && std::ranges::find(in_pair, cur_pick->item_entry) != in_pair.end(); + int32 best_score = cur_dup ? std::numeric_limits::min() : score_of(slot); + // The weapon slots log what the slot holds and why each pool candidate was refused or what it scored (174 kept item 4696 in the off + // hand with three pool pieces on offer, and nothing said why). + bool const log_slot = ks.kind == ::Playerbot::Gear::Bis::Kind::Offhand || ks.kind == ::Playerbot::Gear::Bis::Kind::Ranged; + int32 const held_score = best_score; + uint32 const held_item = cur_pick != out.end() ? cur_pick->item_entry : 0; + auto const note = [&](std::string_view name, uint32 entry, std::string const& what) + { + if (log_slot) + TC_LOG_INFO("playerbot.v2", "[bis] slot {} holds item {} (score {}): candidate \"{}\" ({}) {}", uint32(slot), held_item, held_score, name, entry, what); + }; + for (::Playerbot::Gear::Bis::PoolEntry const& e : ::Playerbot::Gear::Bis::PoolFor(role)) + { + if (e.kind != ks.kind || !::Playerbot::Gear::Bis::InTier(e, tier)) + continue; + uint32 const entry = resolve(e.name); + ItemTemplate const* tpl = entry ? sObjectMgr->GetItemTemplate(entry) : nullptr; + if (!tpl || std::ranges::find(in_pair, entry) != in_pair.end() || !InventoryTypeFitsSlot(slot, tpl->GetInventoryType())) + { + note(e.name, entry, !tpl ? "refused: no item template" : "refused: taken or does not fit the slot"); + continue; + } + if (::Playerbot::Gear::EffectiveItemLevelForLevel(tpl, ctx.level) > raid_cap || ::Playerbot::Gear::IsPvpItem(tpl)) + { + note(e.name, entry, "refused: over the item level cap or a PvP item"); + continue; + } + if (ctx.wearer && ctx.wearer->CanUseItem(tpl) != EQUIP_ERR_OK) + { + note(e.name, entry, "refused: the wearer cannot use it"); + continue; + } + if (ctx.race) + { + if (!tpl->GetAllowableRace().HasRace(ctx.race)) continue; + uint32 const team = ::Player::TeamForRace(ctx.race); + if (tpl->HasFlag(ITEM_FLAG2_FACTION_HORDE) && team != HORDE) continue; + if (tpl->HasFlag(ITEM_FLAG2_FACTION_ALLIANCE) && team != ALLIANCE) continue; + } + int32 const sc = ::Playerbot::Gear::ScoreItemRaid(tpl, ctx.cls, ctx.spec, ctx.level, slot); + note(e.name, entry, fmt::format("scores {}", sc)); + if (sc > best_score) + { + best = tpl; + best_score = sc; + } + } + if (!best) + { + if (cur_dup) + out.erase(cur_pick); // a second copy of a unique piece cannot be worn: the slot goes without a pick + continue; + } + taken.push_back(best->GetId()); + if (auto it = std::ranges::find(out, slot, &GearItem::slot); it != out.end()) + it->item_entry = best->GetId(); + else + out.push_back({ slot, best->GetId() }); + } + } + } + // A piece the raid wears for the fight whatever it scores (ctx.wear_entry: the Onyxia Scale Cloak against Shadow Flame): over the pick, + // the tier piece or the resistance piece in its slot. + if (raid && !ctx.world_bot() && ctx.wear_entry) + { + ItemTemplate const* tpl = sObjectMgr->GetItemTemplate(ctx.wear_entry); + uint8 slot = 255; + if (tpl) + for (uint8 s : kSlots) + if (InventoryTypeFitsSlot(s, tpl->GetInventoryType())) { slot = s; break; } + if (tpl && slot != 255 && (!ctx.wearer || ctx.wearer->CanUseItem(tpl) == EQUIP_ERR_OK)) + { + auto it = std::ranges::find(out, slot, &GearItem::slot); + if (it != out.end()) + it->item_entry = ctx.wear_entry; + else + out.push_back({ slot, ctx.wear_entry }); + } + else + TC_LOG_INFO("playerbot.v2", "[gear] bot {} cannot wear the fight's piece {}: {}", ctx.bot_id, ctx.wear_entry, + !tpl ? "no such item" : slot == 255 ? "no equipment slot takes it" : "CanUseItem refuses it"); + } return out; } @@ -1051,10 +1341,57 @@ std::vector const& TierSetPieces(uint8 cls, int32 tier) return cls >= 1 && cls < 12 && tier >= 1 && tier <= 3 ? cache[cls][tier] : empty; } -bool IsTierSetPick(uint8 cls, Owned::GearMode mode, uint32 entry) +// Phase 6 (Naxxramas) best in slot for a dps warrior, Icy Veins "Warrior DPS Season of Mastery Phase 6 Gear": +// https://www.icy-veins.com/wow-classic/warrior-dps-season-of-mastery-phase-6-gear (one list for fury and arms). The page names Lionheart Helm, +// Stormrage's Talisman of Seething, Conqueror's Spaulders, Shroud of Dominion, Plated Abomination Ribcage, Wristguards of Vengeance, +// Gauntlets of Annihilation, Girdle of the Mentor, Legplates of Carnage, Chromatic Boots, Band of Unnatural Forces, Don Julio's Band, +// Drake Fang Talisman, Slayer's Crest (Diamond Flask and Kiss of the Spider are the other trinkets it lists), Soulstring; weapons: The Hungering +// Cold and Gressil, Dawn of Ruin for dual wield (fury), Might of Menethil for two-hand (arms). +// The client item data (ItemSparse.db2, decoded) holds only the entries below. Plated Abomination Ribcage (23000), Wristguards of Vengeance +// (22936), Girdle of the Mentor (23219), Legplates of Carnage (23068), Chromatic Boots (19387), Shroud of Dominion (23045), Soulstring (22811), +// The Hungering Cold (23577), Gressil, Dawn of Ruin (23054) and Might of Menethil (22798) do not exist in it. Those slots are left out here: +// the Dreadnaught set (items 22416 to 22423, all present) fills chest, wrists, waist, legs and feet, and back, ranged and weapons keep +// the role-scored pick (BisPools, ScoreItemRaid) under the item level ceiling. +std::vector const& SourcedTierGear(uint8 cls, uint16 spec, Owned::GearMode mode) +{ + static std::vector const none; + static std::vector const common = { + { EQUIPMENT_SLOT_HEAD, 12640 }, { EQUIPMENT_SLOT_NECK, 23053 }, { EQUIPMENT_SLOT_SHOULDERS, 21330 }, { EQUIPMENT_SLOT_HANDS, 21581 }, + { EQUIPMENT_SLOT_FINGER1, 23038 }, { EQUIPMENT_SLOT_FINGER2, 19325 }, { EQUIPMENT_SLOT_TRINKET1, 19406 }, { EQUIPMENT_SLOT_TRINKET2, 23041 } }; + // Fury dual wields. The weapons of the list are not in the client data; the one-handers that are and carry the most attack power are Ancient + // Qiraji Ripper 21650 (sword, 2.8 s, 91 attack power, 64 crit rating) and Death's Sting 21126 (dagger, 1.8 s, 158 attack power). The off hand + // they replace was Left-Handed Blades 15909, item level 35 (itemsparse-decoded.tsv). + static std::vector const fury = [] { auto v = common; v.push_back({ EQUIPMENT_SLOT_MAINHAND, 21650 }); v.push_back({ EQUIPMENT_SLOT_OFFHAND, 21126 }); return v; }(); + if (cls != CLASS_WARRIOR || mode != Owned::GearMode::T3 || spec == 73) + return none; + return spec == 71 ? common : fury; +} + +// The hybrids' tier sets (Cenarion / Stormrage / Dreamwalker, Lawbringer / Judgement / Redemption, Prophecy / Transcendence / Faith, Earthfury / +// Ten Storms / Earthshatterer) are built for the healer. A damage spec of those classes (balance and cat druid, retribution paladin, shadow priest, +// elemental and enhancement shaman) wears the picks of its own role under the tier's item level ceiling instead: damage_parity 147 gave a balance +// druid 168 spell power at Tier 3 against 268 at Tier 1. +bool TierSetIsHealerSet(uint8 cls, uint16 spec) +{ + switch (cls) + { + case CLASS_DRUID: return spec == 102 || spec == 103; + case CLASS_PALADIN: return spec == 70; + case CLASS_PRIEST: return spec == 258; + case CLASS_SHAMAN: return spec == 262 || spec == 263; + default: return false; + } +} + +bool IsTierSetPick(uint8 cls, Owned::GearMode mode, uint32 entry, uint16 spec) { if (!Owned::IsTierMode(mode)) return false; + if (TierSetIsHealerSet(cls, spec)) + return false; + for (SourcedGearPick const& pick : SourcedTierGear(cls, spec, mode)) + if (pick.entry == entry) + return true; auto const& pieces = TierSetPieces(cls, Owned::TierNumber(mode)); return std::ranges::find(pieces, entry) != pieces.end(); } diff --git a/src/modules/PlayerbotV2/Bot/Gear/BotGearGenerator.h b/src/modules/PlayerbotV2/Bot/Gear/BotGearGenerator.h index 3bcf1e775f..d45be33019 100644 --- a/src/modules/PlayerbotV2/Bot/Gear/BotGearGenerator.h +++ b/src/modules/PlayerbotV2/Bot/Gear/BotGearGenerator.h @@ -60,6 +60,17 @@ struct GearGenerationContext // What the owner asked for (Owned::GearMode, already reduced by Owned::EffectiveMode): at the cap T1 / T2 / T3 put the class tier set on // and raise the ceiling to that tier for the other slots; Best ignores the owner's own gear level. Ignored for world bots. Owned::GearMode gear_mode = Owned::GearMode::Match; + // A fight the bot gears resistance for (a SpellSchools value; 0 = none): at the cap, in a tier or best-in-slot mode, every armour and + // jewellery slot takes the piece with the most resistance to that school under the mode's item level (Gear::ResistPoints), the tier + // set filling the rest, as a vanilla raid dressed for Princess Huhuran. Weapons, trinkets and the ranged slot keep their picks. + // Ignored for world bots. + uint8 resist_school = 0; + // A piece worn for the fight whatever it scores (an item entry; 0 = none): the Onyxia Scale Cloak, whose aura is what the drakes' Shadow + // Flame checks. It goes on over the pick, the tier piece or the resistance piece in its slot. Ignored for world bots. + uint32 wear_entry = 0; + // Generate even for a world bot under level 10 (WorldGearStart.h). Set only to replace a starter piece the client cannot draw, so + // the bot is not left bare; the caller then uses just the slots it needs. + bool replace_unrenderable_starter = false; bool world_bot() const { return ::Playerbot::Pool::UsesWorldGear(role); } }; @@ -79,7 +90,13 @@ int32 OwnedSlotScore(ItemTemplate const* tpl, uint8 cls, uint16 spec, uint8 leve // The item entries of a class's tier set (ItemSet.db2, found by name, see Owned::TierSetName), tier 1..3; empty when the data has none. std::vector const& TierSetPieces(uint8 cls, int32 tier); // Whether `entry` is a piece of the tier set the mode names for the class. -bool IsTierSetPick(uint8 cls, Owned::GearMode mode, uint32 entry); +bool TierSetIsHealerSet(uint8 cls, uint16 spec); +bool IsTierSetPick(uint8 cls, Owned::GearMode mode, uint32 entry, uint16 spec = 0); + +struct SourcedGearPick { uint8 slot; uint32 entry; }; +// The Naxxramas gear list of a class and spec when the tier mode wears a sourced best-in-slot list instead of the tier set (warrior dps in the +// Tier 3 mode); empty otherwise. +std::vector const& SourcedTierGear(uint8 cls, uint16 spec, Owned::GearMode mode); // Variety: a pick may be any candidate of the best's quality whose effective item level is within this many points of // the best's (and that scores about as well), chosen by bot_id and slot. Two items of one quality this close are diff --git a/src/modules/PlayerbotV2/Bot/Gear/OwnedGearPolicy.h b/src/modules/PlayerbotV2/Bot/Gear/OwnedGearPolicy.h index c8ff468121..bbf9cb65e2 100644 --- a/src/modules/PlayerbotV2/Bot/Gear/OwnedGearPolicy.h +++ b/src/modules/PlayerbotV2/Bot/Gear/OwnedGearPolicy.h @@ -168,7 +168,7 @@ inline std::string_view TierSetName(uint8_t cls, int32_t tier) { "Nightslayer Armor", "Bloodfang Armor", "Bonescythe Armor" }, // 4 rogue { "Vestments of Prophecy", "Vestments of Transcendence", "Vestments of Faith" }, // 5 priest { {}, {}, {} }, // 6 (death knight: none in Classic) - { "The Earthfury", "The Ten Storms", "The Earthshatter" }, // 7 shaman + { "The Earthfury", "The Ten Storms", "The Earthshatterer" }, // 7 shaman { "Arcanist Regalia", "Netherwind Regalia", "Frostfire Regalia" }, // 8 mage { "Felheart Raiment", "Nemesis Raiment", "Plagueheart Raiment" }, // 9 warlock { {}, {}, {} }, // 10 (monk: none in Classic) diff --git a/src/modules/PlayerbotV2/Bot/Gear/RaidEnchants.cpp b/src/modules/PlayerbotV2/Bot/Gear/RaidEnchants.cpp new file mode 100644 index 0000000000..bd11dd9dac --- /dev/null +++ b/src/modules/PlayerbotV2/Bot/Gear/RaidEnchants.cpp @@ -0,0 +1,231 @@ +#include "RaidEnchants.h" + +#include "BotItemScorer.h" +#include "Bot/ClassTables.h" // MaxPlayerLevel() +#include "DB2Stores.h" +#include "Item.h" +#include "ItemTemplate.h" +#include "Log.h" +#include "Player.h" +#include "RaidLoadout.h" +#include "SharedDefines.h" +#include "SpellInfo.h" +#include "SpellMgr.h" +#include "World.h" +#include +#include +#include +#include +#include + +namespace Playerbot::Gear { + +namespace { + +std::mutex s_lock; +// Enchanting spell name -> the spell's SpellItemEnchantment id (0 = the data has no such spell). Filled lazily, once per name. +std::unordered_map s_enchant_by_name; +std::set s_unresolved_logged; + +uint32 EnchantIdOfSpell(SpellInfo const* si) +{ + for (SpellEffectInfo const& e : si->GetEffects()) + if (e.Effect == SPELL_EFFECT_ENCHANT_ITEM && e.MiscValue > 0) + return uint32(e.MiscValue); + return 0; +} + +// Highest-id spell of that exact name with a permanent enchant effect. +uint32 ResolveEnchantId(std::string const& name) +{ + // "#24161": the enchanting spell by id, for the Zandalar enchants whose names the client data shares between spells (the wish lists the name after it). + if (!name.empty() && name[0] == '#') + { + SpellInfo const* si = sSpellMgr->GetSpellInfo(uint32(std::strtoul(name.c_str() + 1, nullptr, 10)), DIFFICULTY_NONE); + return si ? EnchantIdOfSpell(si) : 0; + } + { + std::lock_guard lock(s_lock); + if (auto it = s_enchant_by_name.find(name); it != s_enchant_by_name.end()) + return it->second; + } + uint32 found = 0, found_spell = 0; + LocaleConstant const loc = sWorld->GetDefaultDbcLocale(); + sSpellMgr->ForEachSpellInfo([&](SpellInfo const* si) + { + if (!si || si->Difficulty != DIFFICULTY_NONE || !si->SpellName || name != (*si->SpellName)[loc]) + return; + if (uint32 const id = EnchantIdOfSpell(si); id && si->Id > found_spell) + { + found = id; + found_spell = si->Id; + } + }); + std::lock_guard lock(s_lock); + s_enchant_by_name[name] = found; + return found; +} + +Loadout::Role RoleOf(uint8 cls, uint16 spec) +{ + switch (RaidRoleForBot(cls, spec)) + { + case RaidRole::Tank: return Loadout::Role::Tank; + case RaidRole::Healer: return Loadout::Role::Healer; + case RaidRole::Caster: return Loadout::Role::Caster; + case RaidRole::Melee: return Loadout::Role::Melee; + case RaidRole::Hunter: return Loadout::Role::Hunter; + } + return Loadout::Role::Melee; +} + +// The spell school a caster's gloves are for. +uint8 CasterSchool(uint8 cls, uint16 spec) +{ + switch (cls) + { + case CLASS_WARLOCK: return SPELL_SCHOOL_SHADOW; + case CLASS_PRIEST: return SPELL_SCHOOL_SHADOW; + case CLASS_MAGE: return spec == 64 ? SPELL_SCHOOL_FROST : SPELL_SCHOOL_FIRE; // 64 = frost; fire and arcane take fire power + case CLASS_DRUID: return SPELL_SCHOOL_NATURE; // balance (a feral or restoration druid is not a Caster role) + case CLASS_SHAMAN: return SPELL_SCHOOL_NATURE; // elemental + default: return 0; + } +} + +// Every enchantment id the loadouts can put on (all roles, glove variants and schools, every candidate name). Built once. +std::set const& LoadoutEnchantIds() +{ + static std::set const ids = [] + { + std::set out; + for (Loadout::Role role : { Loadout::Role::Tank, Loadout::Role::Healer, Loadout::Role::Caster, Loadout::Role::Melee, Loadout::Role::Hunter }) + for (bool agility : { false, true }) + for (uint8 school : { uint8(0), uint8(2), uint8(3), uint8(4), uint8(5) }) + for (Loadout::EnchantWish const& w : Loadout::WishesFor(role, agility, school)) + Loadout::FirstKnown(w.names, [&](std::string_view n) + { + if (uint32 const id = ResolveEnchantId(std::string(n))) + out.insert(id); + return false; // visit every candidate + }); + return out; + }(); + return ids; +} + +} // namespace + +uint32 StripRaidEnchants(Player* p) +{ + if (!p || !p->IsInWorld()) + return 0; + std::set const& ids = LoadoutEnchantIds(); + uint32 done = 0; + for (uint8 s = EQUIPMENT_SLOT_START; s < EQUIPMENT_SLOT_END; ++s) + { + Item* item = p->GetItemByPos(INVENTORY_SLOT_BAG_0, s); + if (!item) + continue; + uint32 const enchant = item->GetEnchantmentId(PERM_ENCHANTMENT_SLOT); + if (!enchant || !ids.count(enchant)) + continue; + p->ApplyEnchantment(item, PERM_ENCHANTMENT_SLOT, false); + item->ClearEnchantment(PERM_ENCHANTMENT_SLOT); + ++done; + TC_LOG_INFO("playerbot.v2", "[enchant] removed from {} (level {}) slot {} item {}: enchantment {}", p->GetName(), uint32(p->GetLevel()), + uint32(s), item->GetEntry(), enchant); + } + return done; +} + +uint32 ApplyRaidEnchants(Player* p, uint16 spec) +{ + if (!p || !p->IsInWorld()) + return 0; + // The regear's reroll and scrub passes run at any level: a levelling bot gets none of these. + if (p->GetLevel() < MaxPlayerLevel()) + { + StripRaidEnchants(p); + return 0; + } + // The bot's gear decides how good its enchants are (RaidLoadout.h EnchantTier): greens get the cheap ones, Naxxramas enchants + // only from tier 2.5 gear. + uint32 sum = 0, cnt = 0; + for (uint8 s = EQUIPMENT_SLOT_START; s < EQUIPMENT_SLOT_END; ++s) + if (s != EQUIPMENT_SLOT_BODY && s != EQUIPMENT_SLOT_TABARD) + if (Item const* eq = p->GetItemByPos(INVENTORY_SLOT_BAG_0, s)) + { + sum += eq->GetItemLevel(p); + ++cnt; + } + Loadout::EnchantTier const tier = Loadout::TierForAverageItemLevel(cnt ? sum / cnt : 0u); + std::set const& ours = LoadoutEnchantIds(); + uint8 const cls = p->GetClass(); + bool const agility_hands = cls == CLASS_ROGUE || cls == CLASS_HUNTER || (cls == CLASS_DRUID && spec != 102); + uint32 done = 0; + for (Loadout::EnchantWish const& w : Loadout::WishesFor(RoleOf(cls, spec), agility_hands, CasterSchool(cls, spec))) + { + Item* item = p->GetItemByPos(INVENTORY_SLOT_BAG_0, w.slot); + if (!item) + continue; + // An enchant the loadouts did not put on (a player's own) stays. + uint32 const current = item->GetEnchantmentId(PERM_ENCHANTMENT_SLOT); + if (current && !ours.count(current)) + continue; + ItemTemplate const* tpl = item->GetTemplate(); + if (!tpl) + continue; + // Weapon enchants go on weapons only (a shield or held-in-off-hand item takes none of them); shield enchants on shields only. + bool const weapon_slot = w.slot == Loadout::SLOT_MAINHAND || w.slot == Loadout::SLOT_OFFHAND; + bool const wants_shield = w.names.starts_with("Enchant Shield"); + if (weapon_slot && !wants_shield && tpl->GetClass() != ITEM_CLASS_WEAPON) + continue; + if (wants_shield && tpl->GetInventoryType() != INVTYPE_SHIELD) + continue; + // "Enchant 2H Weapon" enchants go on two-handers only. + bool const two_hand = tpl->GetInventoryType() == INVTYPE_2HWEAPON; + bool any_known = false; + std::string_view const name = Loadout::FirstKnown(w.names, [&](std::string_view n) + { + if ((!two_hand && n.starts_with("Enchant 2H")) || ResolveEnchantId(std::string(n)) == 0) + return false; + any_known = true; + return Loadout::EnchantAllowed(n, tier); + }); + if (name.empty()) + { + if (!any_known) + { + bool first = false; + { + std::lock_guard lock(s_lock); + first = s_unresolved_logged.insert(std::string(w.names)).second; + } + if (first) + TC_LOG_INFO("playerbot.v2", "[enchant] unresolved: none of \"{}\" is an enchanting spell in the spell data", w.names); + } + // Nothing for this gear level: an enchant of a better tier (gear the bot no longer wears, an older build) comes off. + if (current) + { + p->ApplyEnchantment(item, PERM_ENCHANTMENT_SLOT, false); + item->ClearEnchantment(PERM_ENCHANTMENT_SLOT); + TC_LOG_INFO("playerbot.v2", "[enchant] {} slot {} item {}: enchantment {} removed (tier {})", p->GetName(), uint32(w.slot), tpl->GetId(), + current, uint32(tier)); + } + continue; + } + uint32 const enchant = ResolveEnchantId(std::string(name)); + if (enchant == current) + continue; + p->ApplyEnchantment(item, PERM_ENCHANTMENT_SLOT, false); + item->SetEnchantment(PERM_ENCHANTMENT_SLOT, enchant, 0, 0); + p->ApplyEnchantment(item, PERM_ENCHANTMENT_SLOT, true); + ++done; + TC_LOG_INFO("playerbot.v2", "[enchant] {} slot {} item {}: \"{}\" (enchantment {}, tier {}, was {})", p->GetName(), uint32(w.slot), tpl->GetId(), name, + enchant, uint32(tier), current); + } + return done; +} + +} // namespace Playerbot::Gear diff --git a/src/modules/PlayerbotV2/Bot/Gear/RaidEnchants.h b/src/modules/PlayerbotV2/Bot/Gear/RaidEnchants.h new file mode 100644 index 0000000000..1956414654 --- /dev/null +++ b/src/modules/PlayerbotV2/Bot/Gear/RaidEnchants.h @@ -0,0 +1,23 @@ +#pragma once +// Permanent enchants for a raid-ready bot (Playerbot.Gear.RaidEnchants): every equipped piece the role's loadout (RaidLoadout.h) names gets +// its enchant, as a vanilla raider's did. World thread. + +#include "Define.h" + +class Player; + +namespace Playerbot::Gear { + +// Enchants the bot's worn items for its gear level (Loadout::EnchantTier by average equipped item level): an item with no permanent +// enchant gets the best one its tier allows, and one of the loadouts' own enchants of another tier is swapped (or taken off when the +// tier allows none in that slot). A permanent enchant the loadouts do not name is left alone. Returns how many it enchanted. Logs "[enchant]" lines: what went on, and +// the names the spell data did not know (once per name). +// Below the realm level cap it enchants nothing and takes the loadout's enchants off instead (StripRaidEnchants): they are level-60 raid +// enchants, not a levelling bot's. +uint32 ApplyRaidEnchants(Player* p, uint16 spec); + +// Takes every enchant the raid loadouts name (any role) off the worn items of a bot below the level cap. Other permanent enchants stay. +// Returns how many it removed. Logs "[enchant] removed" lines. +uint32 StripRaidEnchants(Player* p); + +} // namespace Playerbot::Gear diff --git a/src/modules/PlayerbotV2/Bot/Gear/RaidLoadout.cpp b/src/modules/PlayerbotV2/Bot/Gear/RaidLoadout.cpp new file mode 100644 index 0000000000..4de65c7859 --- /dev/null +++ b/src/modules/PlayerbotV2/Bot/Gear/RaidLoadout.cpp @@ -0,0 +1,173 @@ +#include "RaidLoadout.h" + +#include + +namespace Playerbot::Gear::Loadout { + +namespace { + +// Vanilla trade enchants of the Naxxramas era. Weapons: Crusader for the physical roles (the Crusader proc was the melee standard), Spell Power +// (Mighty Intellect before it is known) for casters. Casters also wear Arcanum of Focus on head and legs and a Zandalar Signet / Power of the +// Scourge on the shoulders (the 182 warlock wore only chest, bracer, glove, cloak and weapon enchants). Gloves and bracers follow the role's +// main stat; a tank takes stamina and threat. +constexpr EnchantWish kMelee[] = { + { SLOT_HEAD, "#24161|Arcanum of Rapidity" }, + { SLOT_LEGS, "#24161|Arcanum of Rapidity" }, + { SLOT_SHOULDERS, "Might of the Scourge|Zandalar Signet of Might" }, + { SLOT_CHEST, "Enchant Chest - Greater Stats|Enchant Chest - Major Stats|Enchant Chest - Stats" }, + { SLOT_WRISTS, "Enchant Bracer - Superior Strength|Enchant Bracer - Greater Strength|Enchant Bracer - Strength" }, + { SLOT_HANDS, "Enchant Gloves - Greater Strength|Enchant Gloves - Strength" }, + { SLOT_FEET, "Enchant Boots - Greater Agility|Enchant Boots - Agility" }, + { SLOT_BACK, "Enchant Cloak - Lesser Agility|Enchant Cloak - Agility" }, + { SLOT_MAINHAND, "Enchant Weapon - Crusader" }, + { SLOT_OFFHAND, "Enchant Weapon - Crusader" }, +}; +constexpr EnchantWish kMeleeAgility[] = { + { SLOT_HEAD, "#24161|Arcanum of Rapidity" }, + { SLOT_LEGS, "#24161|Arcanum of Rapidity" }, + { SLOT_SHOULDERS, "Might of the Scourge|Zandalar Signet of Might" }, + { SLOT_CHEST, "Enchant Chest - Greater Stats|Enchant Chest - Major Stats|Enchant Chest - Stats" }, + { SLOT_WRISTS, "Enchant Bracer - Superior Strength|Enchant Bracer - Greater Strength|Enchant Bracer - Strength" }, + { SLOT_HANDS, "Enchant Gloves - Greater Agility|Enchant Gloves - Agility" }, + { SLOT_FEET, "Enchant Boots - Greater Agility|Enchant Boots - Agility" }, + { SLOT_BACK, "Enchant Cloak - Lesser Agility|Enchant Cloak - Agility" }, + { SLOT_MAINHAND, "Enchant Weapon - Crusader" }, + { SLOT_OFFHAND, "Enchant Weapon - Crusader" }, +}; +constexpr EnchantWish kHunter[] = { + { SLOT_HEAD, "#24162|Falcon's Call|Arcanum of Rapidity" }, + { SLOT_LEGS, "#24162|Falcon's Call|Arcanum of Rapidity" }, + { SLOT_SHOULDERS, "Might of the Scourge|Zandalar Signet of Might" }, + { SLOT_CHEST, "Enchant Chest - Greater Stats|Enchant Chest - Major Stats|Enchant Chest - Stats" }, + { SLOT_WRISTS, "Enchant Bracer - Superior Agility|Enchant Bracer - Greater Agility|Enchant Bracer - Agility" }, + { SLOT_HANDS, "Enchant Gloves - Greater Agility|Enchant Gloves - Agility" }, + { SLOT_FEET, "Enchant Boots - Greater Agility|Enchant Boots - Agility" }, + { SLOT_BACK, "Enchant Cloak - Lesser Agility|Enchant Cloak - Agility" }, + { SLOT_MAINHAND, "Enchant 2H Weapon - Agility|Enchant Weapon - Agility|Enchant Weapon - Crusader" }, +}; +constexpr EnchantWish kTank[] = { + { SLOT_HEAD, "#24149|Presence of Might|Arcanum of Protection" }, + { SLOT_LEGS, "#24149|Presence of Might|Arcanum of Protection" }, + { SLOT_SHOULDERS, "Fortitude of the Scourge|Zandalar Signet of Might" }, + { SLOT_CHEST, "Enchant Chest - Greater Stats|Enchant Chest - Major Stats|Enchant Chest - Stats" }, + { SLOT_WRISTS, "Enchant Bracer - Superior Stamina|Enchant Bracer - Greater Stamina|Enchant Bracer - Stamina" }, + { SLOT_HANDS, "Enchant Gloves - Threat" }, + { SLOT_FEET, "Enchant Boots - Greater Stamina|Enchant Boots - Stamina" }, + { SLOT_BACK, "Enchant Cloak - Greater Defense|Enchant Cloak - Defense" }, + { SLOT_MAINHAND, "Enchant Weapon - Crusader" }, + { SLOT_OFFHAND, "Enchant Shield - Superior Stamina|Enchant Shield - Greater Stamina|Enchant Shield - Stamina" }, +}; +constexpr EnchantWish kHealer[] = { + { SLOT_HEAD, "#24168|#24167|Arcanum of Focus" }, + { SLOT_LEGS, "#24168|#24167|Arcanum of Focus" }, + { SLOT_SHOULDERS, "Zandalar Signet of Serenity|#24420" }, + { SLOT_FEET, "Enchant Boots - Spirit|Enchant Boots - Greater Stamina|Enchant Boots - Stamina" }, + { SLOT_CHEST, "Enchant Chest - Greater Stats|Enchant Chest - Major Stats|Enchant Chest - Stats" }, + { SLOT_WRISTS, "Enchant Bracer - Mana Regeneration|Enchant Bracer - Healing Power|Enchant Bracer - Superior Spirit" }, + { SLOT_HANDS, "Enchant Gloves - Healing Power" }, + { SLOT_BACK, "Enchant Cloak - Lesser Agility" }, + { SLOT_MAINHAND, "Enchant Weapon - Healing Power|Enchant Weapon - Mighty Intellect" }, +}; +constexpr EnchantWish kCasterFire[] = { + { SLOT_HEAD, "Arcanum of Focus" }, + { SLOT_LEGS, "Arcanum of Focus" }, + { SLOT_SHOULDERS, "Zandalar Signet of Mojo|Power of the Scourge" }, + { SLOT_CHEST, "Enchant Chest - Greater Stats|Enchant Chest - Major Stats|Enchant Chest - Stats" }, + { SLOT_WRISTS, "Enchant Bracer - Superior Intellect|Enchant Bracer - Greater Intellect|Enchant Bracer - Intellect" }, + { SLOT_HANDS, "Enchant Gloves - Fire Power" }, + { SLOT_FEET, "Enchant Boots - Greater Stamina|Enchant Boots - Stamina" }, + { SLOT_BACK, "Enchant Cloak - Lesser Agility" }, + { SLOT_MAINHAND, "Enchant Weapon - Spell Power|Enchant Weapon - Mighty Intellect" }, +}; +constexpr EnchantWish kCasterFrost[] = { + { SLOT_HEAD, "Arcanum of Focus" }, + { SLOT_LEGS, "Arcanum of Focus" }, + { SLOT_SHOULDERS, "Zandalar Signet of Mojo|Power of the Scourge" }, + { SLOT_CHEST, "Enchant Chest - Greater Stats|Enchant Chest - Major Stats|Enchant Chest - Stats" }, + { SLOT_WRISTS, "Enchant Bracer - Superior Intellect|Enchant Bracer - Greater Intellect|Enchant Bracer - Intellect" }, + { SLOT_HANDS, "Enchant Gloves - Frost Power" }, + { SLOT_FEET, "Enchant Boots - Greater Stamina|Enchant Boots - Stamina" }, + { SLOT_BACK, "Enchant Cloak - Lesser Agility" }, + { SLOT_MAINHAND, "Enchant Weapon - Spell Power|Enchant Weapon - Mighty Intellect" }, +}; +constexpr EnchantWish kCasterShadow[] = { + { SLOT_HEAD, "Arcanum of Focus" }, + { SLOT_LEGS, "Arcanum of Focus" }, + { SLOT_SHOULDERS, "Zandalar Signet of Mojo|Power of the Scourge" }, + { SLOT_CHEST, "Enchant Chest - Greater Stats|Enchant Chest - Major Stats|Enchant Chest - Stats" }, + { SLOT_WRISTS, "Enchant Bracer - Superior Intellect|Enchant Bracer - Greater Intellect|Enchant Bracer - Intellect" }, + { SLOT_HANDS, "Enchant Gloves - Shadow Power" }, + { SLOT_FEET, "Enchant Boots - Greater Stamina|Enchant Boots - Stamina" }, + { SLOT_BACK, "Enchant Cloak - Lesser Agility" }, + { SLOT_MAINHAND, "Enchant Weapon - Spell Power|Enchant Weapon - Mighty Intellect" }, +}; +constexpr EnchantWish kCasterNature[] = { + { SLOT_HEAD, "Arcanum of Focus" }, + { SLOT_LEGS, "Arcanum of Focus" }, + { SLOT_SHOULDERS, "Zandalar Signet of Mojo|Power of the Scourge" }, + { SLOT_CHEST, "Enchant Chest - Greater Stats|Enchant Chest - Major Stats|Enchant Chest - Stats" }, + { SLOT_WRISTS, "Enchant Bracer - Superior Intellect|Enchant Bracer - Greater Intellect|Enchant Bracer - Intellect" }, + { SLOT_HANDS, "Enchant Gloves - Natural Power|Enchant Gloves - Fire Power|Enchant Gloves - Healing Power" }, + { SLOT_FEET, "Enchant Boots - Greater Stamina|Enchant Boots - Stamina" }, + { SLOT_BACK, "Enchant Cloak - Lesser Agility" }, + { SLOT_MAINHAND, "Enchant Weapon - Spell Power|Enchant Weapon - Mighty Intellect" }, +}; +constexpr EnchantWish kCasterPlain[] = { + { SLOT_HEAD, "Arcanum of Focus" }, + { SLOT_LEGS, "Arcanum of Focus" }, + { SLOT_SHOULDERS, "Zandalar Signet of Mojo|Power of the Scourge" }, + { SLOT_CHEST, "Enchant Chest - Greater Stats|Enchant Chest - Major Stats|Enchant Chest - Stats" }, + { SLOT_WRISTS, "Enchant Bracer - Superior Intellect|Enchant Bracer - Greater Intellect|Enchant Bracer - Intellect" }, + { SLOT_FEET, "Enchant Boots - Greater Stamina|Enchant Boots - Stamina" }, + { SLOT_BACK, "Enchant Cloak - Lesser Agility" }, + { SLOT_MAINHAND, "Enchant Weapon - Spell Power|Enchant Weapon - Mighty Intellect" }, +}; + +// The cheap trade enchants a levelling or freshly 60 player could afford. +constexpr std::string_view kCheap[] = { + "Enchant Bracer - Strength", "Enchant Bracer - Agility", "Enchant Bracer - Stamina", "Enchant Bracer - Intellect", + "Enchant Gloves - Strength", "Enchant Gloves - Agility", "Enchant Boots - Agility", "Enchant Boots - Stamina", + "Enchant Cloak - Lesser Agility", "Enchant Cloak - Defense", "Enchant Shield - Stamina", "Enchant Chest - Stats", +}; + +} // namespace + +EnchantTier TierForAverageItemLevel(std::uint32_t avg_ilvl) +{ + if (avg_ilvl >= kNaxxEnchantIlvl) + return EnchantTier::Naxx; + return avg_ilvl >= kStandardEnchantIlvl ? EnchantTier::Standard : EnchantTier::Cheap; +} + +EnchantTier TierOfEnchant(std::string_view name) +{ + if (name.ends_with(" of the Scourge")) + return EnchantTier::Naxx; + for (std::string_view c : kCheap) + if (name == c) + return EnchantTier::Cheap; + return EnchantTier::Standard; +} + +std::span WishesFor(Role role, bool agility_hands, std::uint8_t school) +{ + switch (role) + { + case Role::Tank: return kTank; + case Role::Healer: return kHealer; + case Role::Hunter: return kHunter; + case Role::Melee: return agility_hands ? std::span(kMeleeAgility) : std::span(kMelee); + case Role::Caster: + switch (school) + { + case 2: return kCasterFire; + case 3: return kCasterNature; + case 4: return kCasterFrost; + case 5: return kCasterShadow; + default: return kCasterPlain; + } + } + return {}; +} + +} // namespace Playerbot::Gear::Loadout diff --git a/src/modules/PlayerbotV2/Bot/Gear/RaidLoadout.h b/src/modules/PlayerbotV2/Bot/Gear/RaidLoadout.h new file mode 100644 index 0000000000..15a0f1d821 --- /dev/null +++ b/src/modules/PlayerbotV2/Bot/Gear/RaidLoadout.h @@ -0,0 +1,62 @@ +#pragma once +// RaidLoadout - the permanent enchants a vanilla raider wore, by role, as names of the enchanting spells. +// +// Names, not ids: the Forever client data renumbers some vanilla spells, and an enchant that is not in the data is +// then skipped and logged ("[enchant] unresolved ...") instead of putting a wrong enchantment on an item. Each wish +// lists candidate names separated by '|'; the first one the spell data has is used. Pure, no game headers: tested in +// tests/game/ClassicRaidLoadout.cpp. + +#include +#include +#include + +namespace Playerbot::Gear::Loadout { + +// Mirrors Gear::RaidRole. +enum class Role : std::uint8_t { Tank, Healer, Caster, Melee, Hunter }; + +// Equipment slots (EquipmentSlots values). +constexpr std::uint8_t SLOT_HEAD = 0, SLOT_SHOULDERS = 2, SLOT_LEGS = 6, SLOT_CHEST = 4, SLOT_FEET = 7, SLOT_WRISTS = 8, SLOT_HANDS = 9, SLOT_BACK = 14, SLOT_MAINHAND = 15, SLOT_OFFHAND = 16; + +struct EnchantWish +{ + std::uint8_t slot; + std::string_view names; // candidates, '|' separated, in order of preference +}; + +// The wishes for a role. `agility_hands` picks the agility gloves (rogue, feral, hunter) over the strength ones, `school` the spell school +// of caster gloves (2 fire, 4 frost, 5 shadow; anything else = no school gloves). Healers take healing power. +std::span WishesFor(Role role, bool agility_hands, std::uint8_t school); + +// How far a bot's gear is, which decides the enchants it wears (a bot in greens does not walk around with Naxxramas enchants). +// Cheap average equipped item level below kStandardEnchantIlvl (greens, levelling blues): the cheap trade enchants only +// (bracer, gloves, boots, cloak, shield and chest stats); no weapon, head, leg or shoulder enchant. +// Standard pre-raid best in slot, Molten Core and Blackwing Lair gear: the vanilla raider's enchants (Crusader, the Zul'Gurub and +// Dire Maul head and leg enchants, Zandalar signets, the greater trade enchants). +// Naxx from kNaxxEnchantIlvl (Ahn'Qiraj / tier 2.5 gear and above): the Naxxramas shoulder enchants (... of the Scourge) too. +enum class EnchantTier : std::uint8_t { Cheap, Standard, Naxx }; +constexpr std::uint32_t kStandardEnchantIlvl = 60; // a level-60 bot mostly in dungeon blues / pre-raid pieces +constexpr std::uint32_t kNaxxEnchantIlvl = 86; // mostly Ahn'Qiraj 40 (88, tier 2.5) or better; Blackwing Lair is 83 +EnchantTier TierForAverageItemLevel(std::uint32_t avg_ilvl); +// The tier an enchant (a candidate name of a wish) belongs to, and whether a bot of `tier` may wear it. +EnchantTier TierOfEnchant(std::string_view name); +inline bool EnchantAllowed(std::string_view name, EnchantTier tier) { return TierOfEnchant(name) <= tier; } + +// The first candidate of `names` for which `has(name)` is true; empty when none. +template +std::string_view FirstKnown(std::string_view names, Has has) +{ + while (!names.empty()) + { + std::size_t const bar = names.find('|'); + std::string_view const one = names.substr(0, bar); + if (!one.empty() && has(one)) + return one; + if (bar == std::string_view::npos) + break; + names.remove_prefix(bar + 1); + } + return {}; +} + +} // namespace Playerbot::Gear::Loadout diff --git a/src/modules/PlayerbotV2/Bot/Gear/WorldGearStart.h b/src/modules/PlayerbotV2/Bot/Gear/WorldGearStart.h index 47fef8ab6c..261aa23f8d 100644 --- a/src/modules/PlayerbotV2/Bot/Gear/WorldGearStart.h +++ b/src/modules/PlayerbotV2/Bot/Gear/WorldGearStart.h @@ -1,6 +1,6 @@ #pragma once // A world bot below this level keeps the outfit its character was created with, as a vanilla level 1-9 does: no gear is generated for -// it (a level 1 wore rings, trinkets, neck and cloak). Companions of a player are not world bots and are not +// it (a level 1 wore rings, trinkets, neck and cloak, playtest 2026-10-18). Companions of a player are not world bots and are not // affected. Pure: tested in tests/game/ClassicWorldGearStart.cpp. #include @@ -9,9 +9,11 @@ namespace Playerbot::Gear { constexpr std::uint8_t kWorldGearMinLevel = 10; -constexpr bool GeneratesGear(bool world_bot, std::uint8_t level) +// replace_unrenderable_starter: the caller is swapping out a starter piece the client cannot draw, which is the one case where a +// level 1-9 world bot still gets a generated piece (otherwise it would be left bare). +constexpr bool GeneratesGear(bool world_bot, std::uint8_t level, bool replace_unrenderable_starter = false) { - return !world_bot || level >= kWorldGearMinLevel; + return replace_unrenderable_starter || !world_bot || level >= kWorldGearMinLevel; } } // namespace Playerbot::Gear diff --git a/src/modules/PlayerbotV2/Bot/GroupControl.h b/src/modules/PlayerbotV2/Bot/GroupControl.h index ce4a0d0aba..e9a284ecab 100644 --- a/src/modules/PlayerbotV2/Bot/GroupControl.h +++ b/src/modules/PlayerbotV2/Bot/GroupControl.h @@ -33,6 +33,38 @@ Guid ResolveController(Guid const& leader, std::vector> const& othe return Guid{}; } +// Passive holds only while the human leading the group is not fighting: Passive keeps a bot from STARTING a fight, and once the +// player is in combat his bots fight with him (the owner, 2026-10-27: "bots should always fight if you're fighting"). +inline bool PassiveHolds(bool passive_stance, bool leader_human, bool leader_alive, bool leader_in_combat) +{ + return passive_stance && !(leader_human && leader_alive && leader_in_combat); +} + +// Which mobs a Passive bot joins once the player fights (PassiveHolds false): his own target, a mob within kFightJoinYd of him, or a +// mob on a group member who stands within kFightJoinYd of him while the mob is within kFightJoinYd of that member (it is fighting +// him there). Never a fight elsewhere on the map: UBRS 2026-10-26, passive bots ran across the instance after a companion tank that +// was in combat with unreachable Urok adds far from the player. Distances are 2D yards; a negative distance means unknown. +constexpr float kFightJoinYd = 40.0f; +inline bool LeaderFightMayJoin(bool leader_target, float mob_to_leader, float member_to_leader, float mob_to_member) +{ + if (leader_target) + return true; + if (mob_to_leader >= 0.f && mob_to_leader <= kFightJoinYd) + return true; + return member_to_leader >= 0.f && member_to_leader <= kFightJoinYd && mob_to_member >= 0.f && mob_to_member <= kFightJoinYd; +} + +// A bot fighting its victim moves for the fight (its chase, the combat gap-close), not after its leader: the follow / formation of a +// grouped bot stands down while it has a living victim that is in the fight (the mob is in combat or has a victim, or the bot is in +// combat) or that the owner ordered it at, and the bot is within `kFightMoveLeashYd` of the leader. The follow re-issued every tick +// replaced the chase start_attack gave it, so a rogue next to a warlock owner casting from 30 y stood beside him and swung at nothing +// (UBRS 2026-10-27, Eman: "all he's doing is following me around when he should be fighting"). Beyond the leash the follow takes it back. +constexpr float kFightMoveLeashYd = 45.f; +inline bool FightOwnsMovement(bool live_victim, bool victim_in_fight, bool owner_ordered_attack, float bot_to_leader) +{ + return live_victim && (victim_in_fight || owner_ordered_attack) && bot_to_leader >= 0.f && bot_to_leader < kFightMoveLeashYd; +} + // Passive: a mob already on the bot is always fought (it cannot be ignored); a mob on someone else is taken only while it is // within `leash` yards of the controller, so a bot never leaves the group to chase one. leash <= 0 switches the leash off. inline bool PassiveMayDefend(bool mob_on_self, float mob_to_controller, float leash) diff --git a/src/modules/PlayerbotV2/Bot/GroupOrderText.cpp b/src/modules/PlayerbotV2/Bot/GroupOrderText.cpp index fe851676ea..a233adfe09 100644 --- a/src/modules/PlayerbotV2/Bot/GroupOrderText.cpp +++ b/src/modules/PlayerbotV2/Bot/GroupOrderText.cpp @@ -37,7 +37,10 @@ std::optional ClassifyGroupOrder(std::string_view msg, bool owner_w (std::find(kOwnerWords.begin(), kOwnerWords.end(), order) != kOwnerWords.end() || order.rfind("drop quest ", 0) == 0); // Formation / spacing / main tank orders carry an argument ("formation circle", "spacing tight", "set main tank X"). // Gear orders: "equip ", "use your best gear" (BotCommandParser OrderEquip). + // "use " (an altar, brazier, lever, orb; BotCommandParser "use") is unambiguous as a bare party line, so it needs no ";" + // (chris typed "use altar" / "use orb" in party chat and nothing answered, 2026-10-23). A bare "use" alone still says nothing. bool const arg_order = order.rfind("gear ", 0) == 0 || order == "equip" || order.rfind("equip ", 0) == 0 || order == "use your best gear" || + order.rfind("use ", 0) == 0 || order == "wear your best gear" || order.rfind("formation ", 0) == 0 || order.rfind("spacing ", 0) == 0 || order == "spread out" || order == "spaced out" || order == "tight" || order == "close" || order == "maintank" || order == "main tank" || order == "set main tank" || diff --git a/src/modules/PlayerbotV2/Bot/IdleRule.cpp b/src/modules/PlayerbotV2/Bot/IdleRule.cpp index b486f3f264..8133469e7c 100644 --- a/src/modules/PlayerbotV2/Bot/IdleRule.cpp +++ b/src/modules/PlayerbotV2/Bot/IdleRule.cpp @@ -9,6 +9,8 @@ #include #include #include "Log.h" // TC_LOG_ERROR +#include "Services.h" +#include "Util/ConfigReader.h" namespace Playerbot { @@ -46,7 +48,7 @@ bool IsWorldErrand(std::string_view name) "idle:pet_swap_from_stable", "idle:pursue_quest_", "idle:pvp_help_callout", "idle:assist_friend_pvp", "idle:quest_", "idle:react_to_passerby", "idle:resolve_junk_quests", "idle:swim_stuck_hearth", "idle:swim_stuck_walk_to_hub", "idle:tame_beast", "idle:taxi_discover", "idle:transport_ride", "idle:vendor_visit", - "idle:bag_hearth", "idle:fidget", "idle:inn_rest", "idle:mailbox", "idle:town_duel", "idle:wander", + "idle:bag_hearth", "idle:fidget", "idle:inn_rest", "idle:mailbox", "idle:town_duel", "idle:town_errand", "idle:town_linger", "idle:wander", "idle:walk_", "idle:wq_", "idle:yell_lfg", "idle:ambient_sit", "idle:rpg_", }; @@ -60,7 +62,11 @@ bool IsWorldErrand(std::string_view name) void IdleRuleRegistry::finalize() { for (IdleRule& rule : rules_) + { rule.world_errand = IsWorldErrand(rule.name); + rule.quest_seek = rule.name == "idle:walk_to_known_hub" || rule.name == "idle:wander_to_quest_hub"; + rule.fight_exempt = rule.name.starts_with("idle:autoact_dispatch"); + } std::stable_sort(rules_.begin(), rules_.end(), [](IdleRule const& a, IdleRule const& b) { return a.priority > b.priority; }); throttled_ = 0; @@ -100,6 +106,9 @@ std::string_view IdleRuleRegistry::tick(BotSnapshotView const& s, BotAI& ai, if (!r.gate) continue; // A bot in a group with a player (its owner, or the player who invited it) never runs world errands. if (r.world_errand && s.is_led_by_player()) continue; + // No errand (bag run, vendor, walk to a hub) while fighting or with a victim (auto-attack target): a full-bag bot used to walk off mid-fight. + if (r.world_errand && !r.fight_exempt && (s.in_combat() || !s.victim().IsEmpty())) continue; + if (r.quest_seek && !Services::Config().world_questing() && s.is_free_world_bot()) continue; // Per-rule gate-throttle, kept per bot: a rule with min_interval_ms > 0 is looked at by a given bot no more than once per interval // (low-urgency rules such as mail, calendar, auction and charter do not need every tick). The first look is spread over the // interval by a hash of bot and rule, so a fleet does not look in the same second. diff --git a/src/modules/PlayerbotV2/Bot/IdleRule.h b/src/modules/PlayerbotV2/Bot/IdleRule.h index 31c8ffba64..e9cf625a0e 100644 --- a/src/modules/PlayerbotV2/Bot/IdleRule.h +++ b/src/modules/PlayerbotV2/Bot/IdleRule.h @@ -74,6 +74,11 @@ struct IdleRule // is a companion in its owner's group, which would otherwise wander off on it whenever the owner stands still. // Set by finalize() from the rule name. bool world_errand = false; + + // Rule that sends a questless bot to a quest giver or hub. Skipped for a bot of the world while Playerbot.World.Questing is 0. + // Set by finalize() from the rule name. + bool quest_seek = false; + bool fight_exempt = false; // a world errand that may still run in combat or with a live target (the grind engage itself) }; class IdleRuleRegistry diff --git a/src/modules/PlayerbotV2/Bot/IdleWatch.h b/src/modules/PlayerbotV2/Bot/IdleWatch.h index 498b1dade9..727f6ddc82 100644 --- a/src/modules/PlayerbotV2/Bot/IdleWatch.h +++ b/src/modules/PlayerbotV2/Bot/IdleWatch.h @@ -46,8 +46,8 @@ constexpr float kIdleMaxHubYards = 2500.0f; constexpr std::size_t kIdleHubChoices = 6; // the nearest few; strikes and the bot id pick among them // Call every tick. `exempt` = a good reason to stand (fighting, casting, resting at low health, grouped, owned, in an instance, -// riding). Returns true once when the bot has stood still for kIdleStuckMs without a reason. -inline bool IdleStuck(IdleWatch& w, float x, float y, std::uint32_t now_ms, bool exempt) +// riding). Returns true once when the bot has stood still for `stuck_ms` (kIdleStuckMs; shorter in a capital) without a reason. +inline bool IdleStuck(IdleWatch& w, float x, float y, std::uint32_t now_ms, bool exempt, std::uint32_t stuck_ms = kIdleStuckMs) { float const dx = x - w.x, dy = y - w.y; float const moved2 = dx * dx + dy * dy; @@ -57,7 +57,7 @@ inline bool IdleStuck(IdleWatch& w, float x, float y, std::uint32_t now_ms, bool w.x = x; w.y = y; w.since_ms = now_ms ? now_ms : 1u; return false; } - if (now_ms - w.since_ms >= kIdleStuckMs) + if (now_ms - w.since_ms >= stuck_ms) { w.since_ms = now_ms; ++w.strikes; @@ -66,6 +66,40 @@ inline bool IdleStuck(IdleWatch& w, float x, float y, std::uint32_t now_ms, bool return false; } +// A walk toward a far goal that keeps moving but never gets closer: the bot runs back and forth (a party in Ironforge's Military Ward +// chunk-walked for half an hour toward a Searing Gorge objective that has no walking route out of the room, live 275). The idle watch +// does not see it, the bot is never still. `key` names the goal; the best distance resets whenever the goal changes. +struct GoalProgress +{ + std::uint64_t key = 0; + float best = 0.f; + std::uint32_t since_ms = 0; // when `best` last improved by kGoalProgressYards + std::uint32_t last_ms = 0; // the last call: a walk broken off (a fight, a meal, another rule) starts the clock again +}; + +constexpr float kGoalProgressYards = 30.0f; +constexpr std::uint32_t kGoalProgressMs = 180000u; // a walking bot covers 1200 y in that time: any real route gains 30 y +constexpr std::uint32_t kGoalProgressGapMs = 20000u; + +// Call each time the bot walks toward the goal. True once it has gone kGoalProgressMs without getting kGoalProgressYards closer. +inline bool GoalStalled(GoalProgress& g, std::uint64_t key, float dist, std::uint32_t now_ms) +{ + bool const broken_off = g.last_ms != 0 && now_ms - g.last_ms > kGoalProgressGapMs; + g.last_ms = now_ms ? now_ms : 1u; + if (g.key != key || g.since_ms == 0 || broken_off || dist <= g.best - kGoalProgressYards) + { + g.key = key; g.best = dist; g.since_ms = now_ms ? now_ms : 1u; + return false; + } + if (now_ms - g.since_ms >= kGoalProgressMs) + { + g.since_ms = now_ms ? now_ms : 1u; + g.best = dist; + return true; + } + return false; +} + // Which of the `count` candidate hubs (nearest first) a stuck bot is sent to: a different one at each strike, a different one per bot. inline std::size_t IdlePickHub(std::size_t count, std::uint32_t strikes, std::uint32_t bot_id) { diff --git a/src/modules/PlayerbotV2/Bot/InstanceSchools.h b/src/modules/PlayerbotV2/Bot/InstanceSchools.h index 728771021e..68b66f666c 100644 --- a/src/modules/PlayerbotV2/Bot/InstanceSchools.h +++ b/src/modules/PlayerbotV2/Bot/InstanceSchools.h @@ -19,7 +19,8 @@ struct InstanceSchool { std::uint32_t map; Resist school; }; inline constexpr InstanceSchool kInstanceSchools[] = { { 409, Resist::Fire }, // Molten Core - { 469, Resist::Fire }, // Blackwing Lair + { 469, Resist::Fire }, // Blackwing Lair (Firemaw, Vaelastrasz) + { 469, Resist::Shadow }, // Shadow Flame: Ebonroc, Flamegor, Nefarian { 249, Resist::Fire }, // Onyxia's Lair { 533, Resist::Frost }, // Naxxramas (Sapphiron, Kel'Thuzad) { 533, Resist::Shadow }, // Loatheb, the Four Horsemen diff --git a/src/modules/PlayerbotV2/Bot/MeleeReach.h b/src/modules/PlayerbotV2/Bot/MeleeReach.h new file mode 100644 index 0000000000..bee9a2dfb5 --- /dev/null +++ b/src/modules/PlayerbotV2/Bot/MeleeReach.h @@ -0,0 +1,33 @@ +// MeleeReach - how far from a victim's centre a melee bot already hits it (State_InCombat melee gap-close). +// +// Pure function on plain values, so the rule is unit-tested without a server. +// +// The server's own test (Unit::IsWithinMeleeRange / GetMeleeRange): 3D centre distance up to both combat reaches plus 4/3 y, never +// less than the nominal 5 y. The gap-close used a flat 5 y, so a bot swinging at a big creature from 6-8 y (a dragon, a giant, a +// golem) counted as "not in melee": it kept walking at the centre, ran into the stuck-chase cap and dropped its target, or stopped +// on the companion leash and stood (UBRS 2026-10-27, the first pull through the door: the rogue stood for the whole first +// Rage Talon dragon and joined on the second). + +#pragma once + +#include + +namespace Playerbot::MeleeReach { + +constexpr float kNominalYd = 5.0f; // NOMINAL_MELEE_RANGE +constexpr float kPlayerCombatReachYd = 1.5f; // DEFAULT_PLAYER_COMBAT_REACH, every bot is a player +constexpr float kMarginYd = 0.5f; // stay this much inside the server's limit: positions move between snapshots + +// Centre distance at which the bot is in melee of a victim with this combat reach. +inline float Of(float victim_combat_reach) +{ + return std::max(kNominalYd, kPlayerCombatReachYd + std::max(0.0f, victim_combat_reach) + 4.0f / 3.0f - kMarginYd); +} + +inline bool InReach(float dist2, float victim_combat_reach) +{ + float const r = Of(victim_combat_reach); + return dist2 <= r * r; +} + +} // namespace Playerbot::MeleeReach diff --git a/src/modules/PlayerbotV2/Bot/OwnerPicks.h b/src/modules/PlayerbotV2/Bot/OwnerPicks.h new file mode 100644 index 0000000000..88b82b48bc --- /dev/null +++ b/src/modules/PlayerbotV2/Bot/OwnerPicks.h @@ -0,0 +1,216 @@ +// OwnerPicks.h - the owner's spell picks for one bot: "prefer blessing might", "prefer aura fire", "prefer earth stoneskin", +// "prefer aspect monkey", "prefer demon voidwalker", "prefer auto", "prefer clear", plus "pet off|on" and "stealth off|on". +// +// A pick replaces the group plan for that one choice only: a paladin with "prefer blessing might" gives Might to everyone in reach +// and the other paladins leave Might out of their split (PickBlessing); a pinned aura is taken before the party's aura plan runs +// (PickPaladinAura); a pinned totem stands in for that element's plan (PickTotem); a hunter holds the pinned aspect (Cheetah and +// Pack only out of combat, Hawk in a fight); a warlock summons the pinned demon. "pet off" dismisses the pet and keeps it away, +// "stealth off" keeps a rogue from opening out of Stealth. The picks live on BotAI (memory only, like "aoe" and the crowd-control +// orders: a relog or server restart clears them) and are mirrored into the bot's snapshot and its group member summary. +// Pure text and spell ids: no Player, no SpellMgr. The spells are the rank-1 ids; the bot casts its highest known rank. +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace Playerbot::OwnerPicks { + +// The totem slots follow ClassicUpkeep's Element order (EARTH, FIRE, WATER, AIR): TotemEarth + element. +enum Slot : uint8_t { Blessing, Aura, TotemEarth, TotemFire, TotemWater, TotemAir, Aspect, Demon, kSlotCount }; + +struct Picks +{ + std::array spell{}; // rank-1 spell id per slot, 0 = the bot's own plan + bool pet_off = false; // "pet off": dismissed and not summoned again + bool stealth_off = false; // "stealth off": no Stealth opener + + uint32_t operator[](Slot s) const { return spell[s]; } + bool operator==(Picks const&) const = default; +}; + +struct Choice +{ + Slot slot; + uint32_t spell; + std::string_view label; // what the bot answers with + std::array words; // the words that name it after the slot word (first = the add-on's word) +}; + +inline constexpr Choice kChoices[] = { + { Blessing, 19740, "Blessing of Might", { "might" } }, + { Blessing, 19742, "Blessing of Wisdom", { "wisdom" } }, + { Blessing, 20217, "Blessing of Kings", { "kings" } }, + { Blessing, 1038, "Blessing of Salvation", { "salvation", "salv" } }, + { Blessing, 19977, "Blessing of Light", { "light" } }, + { Blessing, 20911, "Blessing of Sanctuary", { "sanctuary" } }, + + { Aura, 465, "Devotion Aura", { "devotion" } }, + { Aura, 7294, "Retribution Aura", { "retribution", "ret" } }, + { Aura, 19746, "Concentration Aura", { "concentration" } }, + { Aura, 19876, "Shadow Resistance Aura", { "shadow", "shadow resistance" } }, + { Aura, 19888, "Frost Resistance Aura", { "frost", "frost resistance" } }, + { Aura, 19891, "Fire Resistance Aura", { "fire", "fire resistance" } }, + { Aura, 20218, "Sanctity Aura", { "sanctity" } }, + + { TotemEarth, 8075, "Strength of Earth Totem", { "strength", "strength of earth" } }, + { TotemEarth, 8071, "Stoneskin Totem", { "stoneskin" } }, + { TotemEarth, 8143, "Tremor Totem", { "tremor" } }, + { TotemEarth, 2484, "Earthbind Totem", { "earthbind" } }, + { TotemEarth, 5730, "Stoneclaw Totem", { "stoneclaw" } }, + + { TotemFire, 3599, "Searing Totem", { "searing" } }, + { TotemFire, 1535, "Fire Nova Totem", { "nova", "fire nova" } }, + { TotemFire, 8190, "Magma Totem", { "magma" } }, + { TotemFire, 8227, "Flametongue Totem", { "flametongue" } }, + { TotemFire, 8181, "Frost Resistance Totem", { "frost", "frost resistance" } }, + + { TotemWater, 5675, "Mana Spring Totem", { "mana", "mana spring" } }, + { TotemWater, 5394, "Healing Stream Totem", { "healing", "healing stream" } }, + { TotemWater, 8166, "Poison Cleansing Totem", { "poison", "poison cleansing" } }, + { TotemWater, 8170, "Disease Cleansing Totem", { "disease", "disease cleansing" } }, + { TotemWater, 8184, "Fire Resistance Totem", { "fire", "fire resistance" } }, + + { TotemAir, 8512, "Windfury Totem", { "windfury" } }, + { TotemAir, 8835, "Grace of Air Totem", { "grace", "grace of air" } }, + { TotemAir, 8177, "Grounding Totem", { "grounding" } }, + { TotemAir, 10595, "Nature Resistance Totem", { "nature", "nature resistance" } }, + { TotemAir, 15107, "Windwall Totem", { "windwall" } }, + { TotemAir, 25908, "Tranquil Air Totem", { "tranquil", "tranquil air" } }, + + { Aspect, 13165, "Aspect of the Hawk", { "hawk" } }, + { Aspect, 13163, "Aspect of the Monkey", { "monkey" } }, + { Aspect, 20043, "Aspect of the Wild", { "wild" } }, + { Aspect, 5118, "Aspect of the Cheetah", { "cheetah" } }, + { Aspect, 13159, "Aspect of the Pack", { "pack" } }, + + { Demon, 688, "Imp", { "imp" } }, + { Demon, 697, "Voidwalker", { "voidwalker", "void" } }, + { Demon, 712, "Succubus", { "succubus", "succ" } }, + { Demon, 691, "Felhunter", { "felhunter", "fel" } }, +}; + +// The class a slot belongs to (TrinityCore Classes values): paladin 2, hunter 3, shaman 7, warlock 9. +inline uint8_t SlotClass(Slot s) +{ + switch (s) + { + case Blessing: case Aura: return 2; + case Aspect: return 3; + case Demon: return 9; + default: return 7; + } +} + +inline std::string_view SlotName(Slot s) +{ + switch (s) + { + case Blessing: return "blessing"; + case Aura: return "aura"; + case TotemEarth: return "earth totem"; + case TotemFire: return "fire totem"; + case TotemWater: return "water totem"; + case TotemAir: return "air totem"; + case Aspect: return "aspect"; + case Demon: return "demon"; + default: return "?"; + } +} + +inline Choice const* FindChoice(uint32_t spell) +{ + for (Choice const& c : kChoices) + if (c.spell == spell) + return &c; + return nullptr; +} + +// Do the cheetah / pack aspects daze the group when it is hit? Those are held out of combat only. +inline bool TravelAspect(uint32_t spell) { return spell == 5118 || spell == 13159; } + +// One "prefer ..." line: a slot and its spell (0 = back to the bot's own plan), or every slot cleared ("prefer clear"). +struct Order +{ + bool clear_all = false; + Slot slot = Blessing; + uint32_t spell = 0; + bool operator==(Order const&) const = default; +}; + +namespace Detail { +inline std::string Normalize(std::string_view in) +{ + std::string out; + bool space = false; + for (char c : in) + { + if (std::isspace(static_cast(c))) { space = !out.empty(); continue; } + if (space) { out.push_back(' '); space = false; } + out.push_back(static_cast(std::tolower(static_cast(c)))); + } + return out; +} +inline bool TakeWord(std::string_view& s, std::string_view word) +{ + if (s.substr(0, word.size()) != word) return false; + std::string_view const rest = s.substr(word.size()); + if (!rest.empty() && rest.front() != ' ') return false; + s = rest.empty() ? rest : rest.substr(1); + return true; +} +} + +// "prefer blessing might", "prefer earth stoneskin" (also "prefer totem earth stoneskin", "prefer earth totem stoneskin"), +// "prefer aura fire resistance", "prefer aspect auto", "prefer clear". Case and extra spaces do not matter. Anything else: nullopt. +inline std::optional ParseOrder(std::string_view line) +{ + std::string const norm = Detail::Normalize(line); + std::string_view s = norm; + if (!Detail::TakeWord(s, "prefer")) + return std::nullopt; + if (s == "clear" || s == "auto" || s == "reset") + return Order{ true, Blessing, 0 }; + + static constexpr std::pair kSlotWords[] = { + { "blessing", Blessing }, { "bless", Blessing }, { "aura", Aura }, + { "earth", TotemEarth }, { "fire", TotemFire }, { "water", TotemWater }, { "air", TotemAir }, + { "aspect", Aspect }, { "demon", Demon }, { "pet", Demon }, + }; + bool const totem_first = Detail::TakeWord(s, "totem"); + std::optional slot; + for (auto const& [word, sl] : kSlotWords) + if (Detail::TakeWord(s, word)) { slot = sl; break; } + if (!slot) + return std::nullopt; + bool const totem_slot = *slot >= TotemEarth && *slot <= TotemAir; + if (totem_first && !totem_slot) + return std::nullopt; + if (totem_slot && !totem_first) + Detail::TakeWord(s, "totem"); + if (s == "auto" || s == "clear" || s == "none" || s == "default") + return Order{ false, *slot, 0 }; + for (Choice const& c : kChoices) + { + if (c.slot != *slot) continue; + for (std::string_view w : c.words) + if (!w.empty() && (s == w || (totem_slot && s.size() == w.size() + 6 && s.substr(0, w.size()) == w && s.substr(w.size()) == " totem"))) + return Order{ false, *slot, c.spell }; + } + return std::nullopt; +} + +// "on" / "off" after "pet" or "stealth": true = on, false = off, nullopt = neither. +inline std::optional ParseSwitch(std::string_view tail) +{ + std::string const t = Detail::Normalize(tail); + if (t == "on" || t == "1" || t == "yes") return true; + if (t == "off" || t == "0" || t == "no") return false; + return std::nullopt; +} + +} // namespace Playerbot::OwnerPicks diff --git a/src/modules/PlayerbotV2/Bot/PartyLink.h b/src/modules/PlayerbotV2/Bot/PartyLink.h new file mode 100644 index 0000000000..b80914bf51 --- /dev/null +++ b/src/modules/PlayerbotV2/Bot/PartyLink.h @@ -0,0 +1,32 @@ +// PartyLink - the rule-side view of Fleet/BotParties.h: is this bot of the world in a small party of world bots, and who are its mates? +#pragma once + +#include "Bot/BotSnapshotView.h" +#include "Fleet/BotParties.h" +#include "Services.h" +#include "Util/ConfigReader.h" + +namespace Playerbot::V2::Parties +{ + +// The party link of this bot, or null. `keep` holds the published table alive while the link is read. +inline Link const* LinkOf(BotSnapshotView const& s, std::shared_ptr const>& keep) +{ + if (!Services::Config().parties_enable() || !s.is_free_world_bot()) + return nullptr; + keep = Board::Get().Current(); + if (!keep || keep->empty()) + return nullptr; + auto const it = keep->find(s.guid().GetCounter()); + return it != keep->end() && it->second.map == s.map_id() ? &it->second : nullptr; +} + +// A follower leaves the pulling and the choice of grind spot to its leader. +inline bool Following(BotSnapshotView const& s) +{ + std::shared_ptr const> keep; + Link const* l = LinkOf(s, keep); + return l && l->slot > 0; +} + +} // namespace Playerbot::V2::Parties diff --git a/src/modules/PlayerbotV2/Bot/PlayerCraftOrder.h b/src/modules/PlayerbotV2/Bot/PlayerCraftOrder.h index e2908218c1..a1f8d87a6e 100644 --- a/src/modules/PlayerbotV2/Bot/PlayerCraftOrder.h +++ b/src/modules/PlayerbotV2/Bot/PlayerCraftOrder.h @@ -139,18 +139,53 @@ inline Request ParseRequest(std::string_view text, std::uint32_t max_count) return r; } +enum class Conjured : std::uint8_t { None, Water, Food }; + struct Option { std::uint32_t spell = 0; std::uint32_t item = 0; std::uint32_t yield = 1; // items one cast makes std::string name; // lower case item name + std::uint32_t rank = 0; // how good the item is (required level, then item level): the better one wins a name that fits several ranks + std::string spell_name; // lower case recipe name ("conjure food"), tried only when no item name fits + Conjured conjured = Conjured::None; // a Conjure Water / Conjure Food rank, from the spell data (no names, so any locale) }; -// Index of the recipe that answers the request, -1 when none. A link matches by item entry; a name matches exactly, then as a prefix, -// then as a substring (ties: shorter name, then lower spell id). -inline int Match(Request const& request, std::span