diff --git a/src/modules/PlayerbotV2/Addon/ForeverBots/Bindings.xml b/src/modules/PlayerbotV2/Addon/ForeverBots/Bindings.xml new file mode 100644 index 0000000000..4dccfd7c59 --- /dev/null +++ b/src/modules/PlayerbotV2/Addon/ForeverBots/Bindings.xml @@ -0,0 +1,19 @@ + + + ForeverBots_ToggleWindow() + + + ForeverBots_ToggleStance() + + + + + + + + + + + + + diff --git a/src/modules/PlayerbotV2/Addon/ForeverBots/ForeverBots.lua b/src/modules/PlayerbotV2/Addon/ForeverBots/ForeverBots.lua index a9136618b1..a5225d80ec 100644 --- a/src/modules/PlayerbotV2/Addon/ForeverBots/ForeverBots.lua +++ b/src/modules/PlayerbotV2/Addon/ForeverBots/ForeverBots.lua @@ -29,7 +29,7 @@ end local CLASSES = { { key = "warrior", label = "Warrior", token = "WARRIOR", roles = { "tank", "dps" } }, - { key = "paladin", label = "Paladin", token = "PALADIN", roles = { "tank", "healer", "dps" }, faction = "Alliance" }, + { key = "paladin", label = "Paladin", token = "PALADIN", roles = { "tank", "healer", "dps" } }, { key = "shaman", label = "Shaman", token = "SHAMAN", roles = { "healer", "dps" }, faction = "Horde" }, { key = "hunter", label = "Hunter", token = "HUNTER", roles = { "dps" } }, { key = "rogue", label = "Rogue", token = "ROGUE", roles = { "dps" } }, @@ -57,8 +57,25 @@ local function ServerCommand(text) SendChatMessage(text, "SAY") end --- Stance toggle of the panel: false = the last order sent was passive (the default while you lead a dungeon group). -local stanceAggressive = false +-- Stance toggle of the panel: ForeverBotsDB.stance is "passive" or "aggressive" (nil = never picked: passive, the default while +-- you lead a dungeon group). The pick is kept between sessions and re-sent to the group whenever it changes (new bots). +local function StanceIsAggressive() + return ForeverBotsDB ~= nil and ForeverBotsDB.stance == "aggressive" +end +-- What the button shows: the pick; before one, "Passive" inside an instance (that is what is sent to the group there, see the group +-- change timer below) and "Auto" elsewhere (nothing sent, the bots use their own default). +local function StanceLabel() + local stance = ForeverBotsDB and ForeverBotsDB.stance + if stance == "aggressive" then return "Aggressive" end + if stance == "passive" then return "Passive" end + local okI, inInstance = pcall(IsInInstance) + if okI and inInstance then return "Passive" end + return "Auto" +end +local stanceBtn +local function RefreshStance() + if stanceBtn then stanceBtn:SetText(StanceLabel()) end +end -- Bot orders go to the group as addon messages under a fixed prefix; the server reads them like party chat. SendChatMessage -- from addon code is blocked by this client in combat and in battlegrounds (taint), addon messages are not. Out of combat a @@ -73,7 +90,14 @@ do end end -local function GroupOrder(text) +-- Result codes of SendAddonMessage that mean "try again in a moment" (AddonMessageThrottle 3, ChannelThrottle 8): a burst of +-- clicks in a 40-man raid, or the other raid addons' traffic in a fight, fills the client's addon message budget, and an order +-- lost to it is no refusal of combat. The order is retried for up to five seconds before it is given up. +local THROTTLED = { [3] = true, [8] = true } +local ORDER_RETRIES = 6 + +local function GroupOrder(text, attempt) + attempt = attempt or 0 local channel if IsInRaid and IsInRaid() then channel = "RAID" elseif (IsInGroup and IsInGroup()) or (GetNumPartyMembers and GetNumPartyMembers() > 0) then channel = "PARTY" @@ -81,15 +105,31 @@ local function GroupOrder(text) Print("you have no group yet: add a bot first.") return end + local code, errText if prefixOk then local send = C_ChatInfo and C_ChatInfo.SendAddonMessage or SendAddonMessage local ok, res = pcall(send, ORDER_PREFIX, text, channel) -- Enum.SendAddonMessageResult.Success is 0; older clients return nothing, which counts as sent. local sent = ok and (res == nil or res == true or res == 0 or (Enum and Enum.SendAddonMessageResult and res == Enum.SendAddonMessageResult.Success)) if sent then return end + if ok then code = tonumber(res) or (res == false and -1 or nil) else errText = tostring(res) end + if code and THROTTLED[code] and attempt < ORDER_RETRIES and C_Timer and C_Timer.After then + C_Timer.After(0.8, function() GroupOrder(text, attempt + 1) end) + return + end end if InCombatLockdown and InCombatLockdown() then - Print("the order could not be sent in combat.") + -- The client lets the player's own Enter send chat in combat (typing "pull back" in raid chat works while the button does + -- not), so the line is put in the chat box ready to send: an order is never lost. + local why = code and (" (addon message result " .. code .. ")") or errText and (" (" .. errText .. ")") or (prefixOk and "" or " (addon prefix not registered)") + -- Only straight from the click (attempt 0): from the C_Timer retry the client blocks chat-box access as "an action only + -- available to the Blizzard UI", so a retry prints the hint instead. + if attempt == 0 and ChatFrame_OpenChat then + ChatFrame_OpenChat((channel == "RAID" and "/raid " or "/party ") .. text) + Print("the order could not be sent in combat" .. why .. ": press Enter to send it.") + else + Print("the order could not be sent in combat" .. why .. ": type it in " .. strlower(channel) .. " chat.") + end return end SendChatMessage(text, channel) @@ -365,6 +405,79 @@ local function MakeButton(parent, text, width, onClick, height) return b end +-- Fixed group orders (Follow, Pull back, Fall back, ...) are secure macro buttons that run "/raid " or "/party ": +-- the client keeps addon code from sending anything itself during a boss fight (SendAddonMessage is refused and the chat call +-- raises "Interface action failed because of an AddOn", live MC Baron Geddon 2026-10-12), but a click on a secure button runs +-- the player's own chat command, in combat too. The server reads that line like typed chat. The macro text names the channel and +-- is set out of combat (a secure attribute cannot change in a fight): on every group change and when combat ends. +local secureOrders = {} +local secureDirty = false + +local function OrderChannelWord() + return (IsInRaid and IsInRaid()) and "/raid " or "/party " +end + +local function RefreshOrderMacros() + if InCombatLockdown and InCombatLockdown() then + secureDirty = true + return + end + secureDirty = false + local word = OrderChannelWord() + for _, b in ipairs(secureOrders) do + b:SetAttribute("type", "macro") + b:SetAttribute("macrotext", (b.macroPre or "") .. word .. b.orderText) + end +end + +local function MakeSecureOrderButton(parent, text, width, order, height) + local b = CreateFrame("Button", nil, parent, "UIPanelButtonTemplate,SecureActionButtonTemplate") + b:SetSize(width, height or 22) + b:SetText(text) + b:RegisterForClicks("AnyUp", "AnyDown") + b.orderText = order + secureOrders[#secureOrders + 1] = b + RefreshOrderMacros() + return b +end + +local orderMacroFrame = CreateFrame("Frame") +for _, ev in ipairs({ "GROUP_ROSTER_UPDATE", "PARTY_MEMBERS_CHANGED", "RAID_ROSTER_UPDATE", "PLAYER_REGEN_ENABLED", "PLAYER_ENTERING_WORLD" }) do + pcall(orderMacroFrame.RegisterEvent, orderMacroFrame, ev) +end +orderMacroFrame:SetScript("OnEvent", function() RefreshOrderMacros() end) + +------------------------------------------------------------------------------------------------------------- key bindings +-- Esc > Options > Key Bindings > AddOns > "WoW Forever Bots" (Bindings.xml; unbound until the player picks keys). Order keys +-- click hidden secure buttons that run the same "/party " or "/raid " line as the window buttons, so they work in +-- combat. Nothing here touches the chat edit box or runs from a timer. +local KEY_ORDERS = { + { "Attack", "attack", "Attack (your target)" }, + { "Pull", "pull", "Pull" }, + { "PullBack", "pull back", "Pull back" }, + { "Follow", "follow", "Follow" }, + { "Stay", "stay", "Stay" }, + { "Resume", "resume", "Resume" }, + { "Stop", "disengage", "Stop attacking" }, + { "Flee", "flee", "Flee" }, + { "Come", "come", "Come" }, + { "FallBack", "fallback", "Fall back" }, + { "AttackMouseover", "attack", "Attack (mouseover)", "/target [@mouseover,harm,nodead]\n" }, +} +BINDING_HEADER_FOREVERBOTS = "WoW Forever Bots" +BINDING_NAME_FOREVERBOTS_TOGGLE_WINDOW = "Show / hide the bot window" +BINDING_NAME_FOREVERBOTS_TOGGLE_STANCE = "Toggle stance (Passive / Aggressive)" +for _, k in ipairs(KEY_ORDERS) do + local name = "ForeverBotsKey" .. k[1] + local b = CreateFrame("Button", name, UIParent, "SecureActionButtonTemplate") + b:RegisterForClicks("AnyUp", "AnyDown") + b.orderText = k[2] + b.macroPre = k[4] -- optional macro lines before the order (Attack mouseover targets the unit under the cursor first) + secureOrders[#secureOrders + 1] = b + _G["BINDING_NAME_CLICK " .. name .. ":LeftButton"] = k[3] +end +RefreshOrderMacros() + local function ClassColor(token) local c = RAID_CLASS_COLORS and RAID_CLASS_COLORS[token] if c then @@ -447,6 +560,79 @@ local function Tip(b, title, body) b:SetScript("OnLeave", function() GameTooltip:Hide() end) end +-- Raid ready: one click for the usual start of a raid night. It calls your saved bots (".bot summon saved", the call every player may use), waits until the group +-- stops growing, makes it a raid when it holds more than five, sets the formation and spacing, hands the fight back +-- ("resume"), sets the Main Tank flag when you target a group member, and starts a ready check once the bots have buffed +-- themselves. A new click or combat cancels a run in progress. +local raidReadyRun = 0 +local function MemberCount() + if GetNumGroupMembers then return GetNumGroupMembers() end + if GetNumRaidMembers and GetNumRaidMembers() > 0 then return GetNumRaidMembers() end + return (GetNumPartyMembers and GetNumPartyMembers() or 0) + 1 +end + +local function RaidReady() + if InCombatLockdown and InCombatLockdown() then + Print("raid ready: not in combat.") + return + end + if not (C_Timer and C_Timer.After) then + Print("raid ready: this client has no timers; use /fb call all.") + return + end + raidReadyRun = raidReadyRun + 1 + local run = raidReadyRun + local function After(sec, fn) + C_Timer.After(sec, function() + if run == raidReadyRun and not (InCombatLockdown and InCombatLockdown()) then fn() end + end) + end + local function IsRaidNow() return IsInRaid and IsInRaid() end + + local function ReadyCheck() + local ok = pcall(function() DoReadyCheck() end) + Print(ok and "raid ready: ready check sent." or "raid ready: done (only the leader can start a ready check).") + end + local function Orders(n) + GroupOrder("resume") + After(0.4, function() GroupOrder("formation circle") end) + After(0.8, function() GroupOrder("spacing close") end) + After(1.2, function() + GroupOrder(ForeverBotsDB.cc == false and "crowdcontrol off" or "crowdcontrol on") + local tgt = UnitExists and UnitExists("target") and not IsSecret(UnitName("target")) + if tgt and (UnitInRaid and UnitInRaid("target") or UnitInParty and UnitInParty("target")) then + GroupOrder("set main tank") + end + end) + Print("raid ready: " .. n .. " in the group, formation set. Ready check in 20 seconds.") + After(20, ReadyCheck) + end + local function Finish(n) + if n <= 1 then + Print("raid ready: no bots joined. Save a group with /fb save all first.") + return + end + if n > 5 and not IsRaidNow() then + local conv = (C_PartyInfo and C_PartyInfo.ConvertToRaid) or ConvertToRaid + if conv then pcall(conv) end + After(1.5, function() Orders(MemberCount()) end) + else + Orders(n) + end + end + + Print("raid ready: calling your saved bots...") + ServerCommand(".bot summon saved") + local lastN, stable, waited = -1, 0, 0 + local function Poll() + local n = MemberCount() + if n == lastN then stable = stable + 1 else stable = 0; lastN = n end + waited = waited + 1 + if (n > 1 and stable >= 3) or waited >= 30 then Finish(n) else After(1, Poll) end + end + After(2, Poll) +end + local function BuildFrame() frame = CreateFrame("Frame", "ForeverBotsFrame", UIParent, BackdropTemplateMixin and "BackdropTemplate" or nil) frame:SetSize(330, 10) @@ -552,6 +738,10 @@ local function BuildFrame() "The bots leave marked mobs alone: no crowd control.", function(on) GroupOrder(on and "crowdcontrol on" or "crowdcontrol off") end) y = y - 34 + local raidReadyBtn = MakeButton(frame, "Raid ready", 298, RaidReady, 24) + raidReadyBtn:SetPoint("TOPLEFT", 16, y) + Tip(raidReadyBtn, "Raid ready", "Calls your saved bots, makes the group a raid if it needs one, sets the formation and spacing, and starts a ready check once the bots have buffed. Target your main tank first to set the Main Tank flag too. Not in combat.") + y = y - 32 ---------------------------------------------------------------------------------------------- order rows local function Header(text, hint) @@ -573,7 +763,11 @@ local function BuildFrame() local made = {} for _, d in ipairs(defs) do local b - b = MakeButton(frame, d[1], d[2], function() d[5](b) end) + if d[6] then + b = MakeSecureOrderButton(frame, d[1], d[2], d[6]) + else + b = MakeButton(frame, d[1], d[2], function() d[5](b) end) + end b:SetPoint("TOPLEFT", x, y) if d[3] then Tip(b, d[3], d[4]) end made[#made + 1] = b @@ -586,55 +780,56 @@ local function BuildFrame() Header("Orders to the group", "Everything below goes to all your bots.") -- Move and fight. Row({ - { "Follow", 72, "Follow", "Bots follow you and only defend. They do not advance or pull until you say Attack, Pull or Resume.", function() GroupOrder("follow") end }, - { "Stay", 72, "Stay", "Bots hold where they stand.", function() GroupOrder("stay") end }, - { "Attack", 72, "Attack", "Bots attack your target.", function() GroupOrder("attack") end }, - { "Resume", 72, "Resume", "Hand the fight back: bots go on with their normal play.", function() GroupOrder("resume") end }, + { "Follow", 72, "Follow", "Bots follow you and only defend. They do not advance or pull until you say Attack, Pull or Resume.", function() GroupOrder("follow") end, "follow" }, + { "Stay", 72, "Stay", "Bots hold where they stand.", function() GroupOrder("stay") end, "stay" }, + { "Attack", 72, "Attack", "Bots attack your target.", function() GroupOrder("attack") end, "attack" }, + { "Resume", 72, "Resume", "Hand the fight back: bots go on with their normal play.", function() GroupOrder("resume") end, "resume" }, }) Row({ - { "Pull", 72, "Pull", "Your tank bots open on your target; the rest join once it is engaged.", function() GroupOrder("pull") end }, - { "Pull back", 72, "Pull back", "The main tank bot opens on your target from range, runs back to the rally point (or where it stood) and tanks it there, so nothing else aggros.", function() GroupOrder("pull back") end }, - { "Stop", 72, "Stop", "Bots stop attacking and go back to normal.", function() GroupOrder("disengage") end }, - { "Flee", 72, "Flee", "Bots break off and run to you.", function() GroupOrder("flee") end }, + { "Pull", 72, "Pull", "Your tank bots open on your target; the rest join once it is engaged.", function() GroupOrder("pull") end, "pull" }, + { "Pull back", 72, "Pull back", "The main tank bot opens on your target from range, runs back to the rally point (or where it stood) and tanks it there, so nothing else aggros.", function() GroupOrder("pull back") end, "pull back" }, + { "Stop", 72, "Stop", "Bots stop attacking and go back to normal.", function() GroupOrder("disengage") end, "disengage" }, + { "Flee", 72, "Flee", "Bots break off and run to you.", function() GroupOrder("flee") end, "flee" }, }) -- Stance toggle. Passive: the bots start nothing on their own and only defend themselves and the group until you say -- Attack or Pull. Aggressive: they attack anything hostile within about 10 yards of you. The button shows the stance -- it last sent (the bots start passive while you lead a dungeon group). - Row({ - { "Come", 72, "Come", "Bots teleport to you.", function() GroupOrder("come") end }, - { stanceAggressive and "Aggressive" or "Passive", 98, "Stance", - "Passive: bots start nothing and only defend. Aggressive: they attack anything hostile within about 10 yards of you. Shows what you last sent.", + local stanceRow = Row({ + { "Come", 72, "Come", "Bots teleport to you.", function() GroupOrder("come") end, "come" }, + { StanceLabel(), 98, "Stance", + "Auto: nothing sent yet outside an instance, the bots use their own default. Inside an instance the panel sends Passive until you pick. Passive: bots start nothing and only defend. Aggressive: they attack anything hostile within about 10 yards of you. Shows what you last sent; it is sent again to every bot that joins.", function(self) - stanceAggressive = not stanceAggressive - GroupOrder(stanceAggressive and "aggressive" or "passive") - self:SetText(stanceAggressive and "Aggressive" or "Passive") + ForeverBotsDB.stance = StanceIsAggressive() and "passive" or "aggressive" + GroupOrder(ForeverBotsDB.stance) + self:SetText(StanceLabel()) end }, }) + stanceBtn = stanceRow[2] y = y - 8 Header("After a wipe or to regroup") Row({ -- Dead bots release their spirit and run back to their corpses; living ones ignore it. - { "Release", 96, "Release", "After a wipe: every dead bot releases, runs back to its corpse and rejoins you. Living bots ignore it.", function() GroupOrder("release") end }, + { "Release", 96, "Release", "After a wipe: every dead bot releases, runs back to its corpse and rejoins you. Living bots ignore it.", function() GroupOrder("release") end, "release" }, -- Fall back: every bot drops the fight, runs to the rally point (set with Set rally, else where you stand) and -- re-forms there; it fights only what follows until Attack, Pull or Resume. - { "Fall back", 96, "Fall back", "Every bot drops the fight and runs to the rally point, then re-forms there. It fights only what follows until you say Attack, Pull or Resume.", function() GroupOrder("fallback") end }, - { "Set rally", 96, "Set rally", "Sets the rally point to where you stand (used by Fall back and Pull back).", function() GroupOrder("rally here") end }, + { "Fall back", 96, "Fall back", "Every bot drops the fight and runs to the rally point, then re-forms there. It fights only what follows until you say Attack, Pull or Resume.", function() GroupOrder("fallback") end, "fallback" }, + { "Set rally", 96, "Set rally", "Sets the rally point to where you stand (used by Fall back and Pull back).", function() GroupOrder("rally here") end, "rally here" }, }) y = y - 8 Header("Formation and spacing") Row({ -- Formation round you out of combat (None = the plain follow behind you) and the spacing between bots. - { "Circle", 72, "Circle", "Out of combat the bots stand in a ring round you.", function() GroupOrder("formation circle") end }, - { "Arrow", 72, "Arrow", "Out of combat the bots form an arrow pointing the way you face.", function() GroupOrder("formation arrow") end }, - { "Line", 72, "Line", "Out of combat the bots line up abreast behind you.", function() GroupOrder("formation line") end }, - { "No form.", 72, "No formation", "The plain follow behind you.", function() GroupOrder("formation none") end }, + { "Circle", 72, "Circle", "Out of combat the bots stand in a ring round you.", function() GroupOrder("formation circle") end, "formation circle" }, + { "Arrow", 72, "Arrow", "Out of combat the bots form an arrow pointing the way you face.", function() GroupOrder("formation arrow") end, "formation arrow" }, + { "Line", 72, "Line", "Out of combat the bots line up abreast behind you.", function() GroupOrder("formation line") end, "formation line" }, + { "No form.", 72, "No formation", "The plain follow behind you.", function() GroupOrder("formation none") end, "formation none" }, }) Row({ - { "Tight", 72, "Tight spacing", "About 2.5 yards between bots.", function() GroupOrder("spacing tight") end }, - { "Close", 72, "Close spacing", "About 4 yards between bots (the default).", function() GroupOrder("spacing close") end }, - { "Spread", 72, "Spread spacing", "About 8 yards between bots.", function() GroupOrder("spacing spread") end }, + { "Tight", 72, "Tight spacing", "About 2.5 yards between bots.", function() GroupOrder("spacing tight") end, "spacing tight" }, + { "Close", 72, "Close spacing", "About 4 yards between bots (the default).", function() GroupOrder("spacing close") end, "spacing close" }, + { "Spread", 72, "Spread spacing", "About 8 yards between bots.", function() GroupOrder("spacing spread") end, "spacing spread" }, }) -- Distance row: how far the bots follow you (and the formation spacing), stepped 1 yard per click. local distLabel = frame:CreateFontString(nil, "OVERLAY", "GameFontNormal") @@ -810,6 +1005,11 @@ end -- Sends the coalesced distance order and re-sends it silently when the group grows or shrinks (new bots need it). +local function GroupSize() + if GetNumGroupMembers then return GetNumGroupMembers() end + if GetNumRaidMembers and GetNumRaidMembers() > 0 then return GetNumRaidMembers() end + return (GetNumPartyMembers and GetNumPartyMembers() or 0) +end local distFrame = CreateFrame("Frame") distFrame.acc = 0 distFrame:SetScript("OnUpdate", function(self, elapsed) @@ -824,18 +1024,25 @@ distFrame:SetScript("OnUpdate", function(self, elapsed) self.groupAt = nil SendDistance(true) end + if self.stanceAt and now >= self.stanceAt then + self.stanceAt = nil + -- The bots of a group start on the server's default stance, so the stance the panel shows is sent to every one of them + -- (new and re-created bots included); a never-picked stance is sent only inside an instance, where Passive is the default. + local okI, inInstance = pcall(IsInInstance) + if GroupSize() > 0 and (ForeverBotsDB.stance or (okI and inInstance)) then + GroupOrder(StanceIsAggressive() and "aggressive" or "passive") + end + RefreshStance() + end end) -local function GroupSize() - if GetNumGroupMembers then return GetNumGroupMembers() end - if GetNumRaidMembers and GetNumRaidMembers() > 0 then return GetNumRaidMembers() end - return (GetNumPartyMembers and GetNumPartyMembers() or 0) -end local function OnGroupChanged() local n = GroupSize() if n ~= lastGroupSize then lastGroupSize = n if n == 0 then gearSent = "match" end if n > 0 and ForeverBotsDB.distance then distFrame.groupAt = Now() + 2 end + if n > 0 then distFrame.stanceAt = Now() + 2.5 end + RefreshStance() end end for _, ev in ipairs({ "GROUP_ROSTER_UPDATE", "PARTY_MEMBERS_CHANGED", "RAID_ROSTER_UPDATE" }) do @@ -848,6 +1055,16 @@ local function Toggle() if frame:IsShown() then frame:Hide() else frame:Show() end end +function ForeverBots_ToggleWindow() Toggle() end + +function ForeverBots_ToggleStance() + if not ForeverBotsDB then return end + ForeverBotsDB.stance = StanceIsAggressive() and "passive" or "aggressive" + GroupOrder(ForeverBotsDB.stance) + RefreshStance() + Print("stance: " .. StanceLabel()) +end + ------------------------------------------------------------------------------------------------------------- bot panel -- A small floating panel for ONE bot: it follows your target whenever that is a friendly player in your group (a bot), -- and every button is a whisper to that bot ("/w follow"), so the order acts on that bot only and the bot @@ -878,12 +1095,28 @@ end -- The player's own invite: the call typed /invite makes (the client's portrait "Invite" sends nothing for a bot on 70338). local function InviteByName(name) + -- Always says what it did, so a click that sends nothing is visible in the chat frame (portrait Invite, 2026-10-12: no + -- packet reached the server and nothing was shown). + local can + if C_PartyInfo and C_PartyInfo.CanInvite then + local okC, res = pcall(C_PartyInfo.CanInvite) + if okC then can = res end + end + if can == false then Print("cannot invite " .. name .. " (the game says you may not invite right now)") end + local sent, how = false, nil if C_PartyInfo and C_PartyInfo.InviteUnit then local ok, err = pcall(C_PartyInfo.InviteUnit, name) - if ok then return end - Debug("invite: C_PartyInfo.InviteUnit failed: " .. tostring(err)) + if ok then sent, how = true, "C_PartyInfo.InviteUnit" else Debug("invite: C_PartyInfo.InviteUnit failed: " .. tostring(err)) end end - if SlashCmdList and SlashCmdList.INVITE then SlashCmdList.INVITE(name) else Print("type /invite " .. name) end + if not sent and InviteUnit then + local ok, err = pcall(InviteUnit, name) + if ok then sent, how = true, "InviteUnit" else Debug("invite: InviteUnit failed: " .. tostring(err)) end + end + if not sent and SlashCmdList and SlashCmdList.INVITE then + local ok, err = pcall(SlashCmdList.INVITE, name) + if ok then sent, how = true, "/invite" else Debug("invite: /invite failed: " .. tostring(err)) end + end + if sent then Print("invite sent to " .. name .. " (" .. how .. ")") else Print("could not send the invite; type /invite " .. name) end end local function BotWhisper(text) @@ -1076,88 +1309,35 @@ end) -- and the floating panel (target-driven) is the way in. -- Opens the client's chat box already in whisper mode for (no slash text, so the client's slash parser is not involved: -- on client 70291 in a battleground every slash line errors inside Blizzard's HandleChatType, "table cannot be indexed with --- secret keys", Karrz 2026-10-09). Enter then sends an ordinary whisper packet. Opened a frame later because a typed "/w" runs --- from the chat box, which the client closes after the handler returns. -function OpenWhisperBox(name, text, now) - local function Open() - if ForeverBotsDB.bgWhisper == "dot" or not (ChatEdit_ChooseBoxForSend and ChatEdit_ActivateChat and ChatEdit_UpdateHeader) then - if ChatFrame_OpenChat then ChatFrame_OpenChat(".w " .. name .. " " .. (text or "")) end - return - end - local eb = ChatEdit_ChooseBoxForSend() - eb:SetAttribute("chatType", "WHISPER") - eb:SetAttribute("tellTarget", name) - ChatEdit_UpdateHeader(eb) - ChatEdit_ActivateChat(eb) - eb:SetText(text or "") +-- secret keys", playtest 2026-10-09). Enter then sends an ordinary whisper packet. It touches the chat box, so it is called ONLY +-- straight from a click handler (the portrait menu's "Whisper (Forever Bots)"): never from a timer, an event or a hook on the +-- client's own functions, where the client blocks it ("ForeverBots has been blocked from an action only available to the +-- Blizzard UI", reported 2026-10-15). Anything that is not a click whispers with SendChatMessage / an addon whisper instead. +function OpenWhisperBox(name, text) + if not (ChatEdit_ChooseBoxForSend and ChatEdit_ActivateChat and ChatEdit_UpdateHeader) then + Print("type /w " .. name .. " to whisper") + return end - -- now: called from a button click (the player's own action, so the box may be touched at once, also in a battleground) - if not now and C_Timer and C_Timer.After then C_Timer.After(0.05, Open) else Open() end + local eb = ChatEdit_ChooseBoxForSend() + eb:SetAttribute("chatType", "WHISPER") + eb:SetAttribute("tellTarget", name) + ChatEdit_UpdateHeader(eb) + ChatEdit_ActivateChat(eb) + eb:SetText(text or "") end --- Clicking a name in chat, a name's right-click Whisper, the friends / who / LFG lists all end in ChatFrameUtil.SendTellWithMessage, --- which puts " Name " in the chat box and asks the box to parse it. On 70291 SLASH_WHISPER1 is "/cw", which the --- client does not turn into a whisper (Karrz 2026-10-09: clicking a name shows "Say: /cw Berolt"), so the box stays in Say mode with --- the slash text in it. A post-hook (hooksecurefunc: the client's function is not replaced) then puts the box in whisper mode for --- that name and clears the slash text. It runs synchronously, inside the click that started it: an addon may only touch the chat box --- from a player action in a battleground (a timer callback there failed with "Interface action failed because of an AddOn" and left --- "/cw Name" in the box, Karrz 2026-10-09). The client's own /w /whisper /t /tell are untouched. -local function HookSendTell() - if not hooksecurefunc then return end - local function ToWhisper(eb, name, text) - local who = strtrim((strsplit("-", name)) or "") -- "Name-Realm" -> "Name": a single realm - if who == "" then return end - Debug("whisper box: switching to whisper mode for " .. who) - eb:SetAttribute("chatType", "WHISPER") - eb:SetAttribute("tellTarget", who) - if ChatEdit_UpdateHeader then ChatEdit_UpdateHeader(eb) end - eb:SetText(SafeStr(text) or "") - end - -- The client's own Whisper (portrait menu Interact, friends list, ...) can open the box with the dead "/cw Name" text - -- instead (SLASH_WHISPER1 is "/cw" on this client). Writing that global from here would taint every reader of it, so the - -- box is looked at after it opens instead: a box showing "/cw Name [text]" is turned into whisper mode for Name, like the - -- SendTellWithMessage hook above. Synchronous, inside the click that opened it (an addon may only touch the box from a player - -- action in a battleground). - local function FixCwBox() - pcall(function() - local eb = ChatEdit_GetActiveWindow and ChatEdit_GetActiveWindow() - if not eb then return end - local text = SafeStr(eb:GetText()) - if not text then return end - local name, rest = strmatch(text, "^/[cC][wW]%s+(%S+)%s*(.-)$") - if name then ToWhisper(eb, name, rest) end - end) - end - if ChatFrameUtil and ChatFrameUtil.SendTellWithMessage then - hooksecurefunc(ChatFrameUtil, "SendTellWithMessage", function(name, text) - name = SafeStr(name) - if not name then return end - local eb = ChatEdit_GetActiveWindow and ChatEdit_GetActiveWindow() - if not eb then return end - local ok, chatType = pcall(function() return eb:GetAttribute("chatType") end) - if ok and (chatType == "WHISPER" or chatType == "BN_WHISPER") then - -- the client already switched to whisper mode but typed "/cw Name" into the box as well (Karrz 2026-10-11, - -- "Tell Name:" with "/cw Name" after it): keep the mode, clear that text - FixCwBox() - return - end - ToWhisper(eb, name, text) - end) - end - if ChatFrameUtil and ChatFrameUtil.OpenChat then pcall(hooksecurefunc, ChatFrameUtil, "OpenChat", FixCwBox) end - if ChatFrame_OpenChat then pcall(hooksecurefunc, "ChatFrame_OpenChat", FixCwBox) end - if ChatEdit_ActivateChat then pcall(hooksecurefunc, "ChatEdit_ActivateChat", FixCwBox) end - -- and the text itself: the client sets "/cw Name" with SetText after the box is open - for i = 1, (NUM_CHAT_WINDOWS or 10) do - local box = _G["ChatFrame" .. i .. "EditBox"] - if box and box.SetText then pcall(hooksecurefunc, box, "SetText", FixCwBox) end - end -end +-- The client's own Whisper (name click, friends list, portrait Interact menu) opens the box with "/cw Name"; fixing that used +-- to hook ChatFrameUtil.SendTellWithMessage, ChatFrame_OpenChat, ChatEdit_ActivateChat and the edit boxes' SetText and rewrite +-- 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. local function AddPopupEntry() 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 -- 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 (Karrz 2026-10-11: no CMSG_PARTY_INVITE from the menu, typed /invite works), so + -- 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 -- bot-panel entry for a group member (world, party, raid and battleground menus alike). -- Right-clicking the target frame crashed the client once with entries of ours in MENU_UNIT_PLAYER (Menu.lua:1103, @@ -1175,7 +1355,7 @@ local function AddPopupEntry() if who == "" then return end local grouped = (UnitInParty and UnitInParty(unit)) or (UnitInRaid and UnitInRaid(unit)) root:CreateDivider() - root:CreateButton("Whisper (Forever Bots)", function() OpenWhisperBox(who, nil, true) end) + root:CreateButton("Whisper (Forever Bots)", function() OpenWhisperBox(who) end) if grouped then root:CreateButton("WoW Forever Bots", function() local token = select(2, UnitClass(unit)) @@ -1184,7 +1364,24 @@ local function AddPopupEntry() UpdateBotPanel() end) else - root:CreateButton("Invite (Forever Bots)", function() InviteByName(who) end) + -- 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. + local replaced = false + if root.EnumerateElementDescriptions then + for _, desc in root:EnumerateElementDescriptions() do + pcall(function() + local text = desc.GetText and desc:GetText() + if type(text) == "string" and not IsSecret(text) and (text == PARTY_INVITE or text == INVITE or text == "Invite") + and desc.SetResponder then + desc:SetResponder(function() InviteByName(who) end) + replaced = true + end + end) + end + end + if not replaced then + root:CreateButton("Invite (Forever Bots)", function() InviteByName(who) end) + end end end) if not ok then Debug("unit menu entry skipped") end @@ -1196,7 +1393,7 @@ end ------------------------------------------------------------------------------------------------------------- slash --- Typed whispers: on this client "/w Name text" and the unit menu's "/cw Name text" do nothing (Karrz 2026-10-08: no packet +-- Typed whispers: on this client "/w Name text" and the unit menu's "/cw Name text" do nothing (playtest 2026-10-08: no packet -- reaches the server, no Lua error, also with every addon off), while SendChatMessage(text, "WHISPER", nil, name) works. -- So /w /t /tell /cw are defined here as a plain SendChatMessage whisper (the client's own /whisper and /r stay native: they work). -- Restored 2026-10-11: in a raid (Molten Core) typed "/w Cal hi" did nothing while "/whisper Cal hi" worked, and the box filled by @@ -1210,6 +1407,21 @@ do return ok and inInstance and (kind == "pvp" or kind == "arena") end + -- Inside a BG the whisper goes out as an addon whisper (FBOTS) that the server hands to the bot. Remembers the last one so + -- the Enter-key path below never sends the same line twice. + local lastBg = { at = 0 } + local function BgWhisper(name, text) + if ForeverBotsDB.bgWhisper == "dot" or not prefixOk then return false end + local send = C_ChatInfo and C_ChatInfo.SendAddonMessage or SendAddonMessage + local ok, res = pcall(send, ORDER_PREFIX, text, "WHISPER", name) + if not (ok and (res == nil or res == true or res == 0 or (Enum and Enum.SendAddonMessageResult and res == Enum.SendAddonMessageResult.Success))) then + return false + end + lastBg.name, lastBg.text, lastBg.at = name, text, GetTime() + DEFAULT_CHAT_FRAME:AddMessage("|cffff80ffTo " .. name .. ": " .. text .. "|r") + return true + end + local function Whisper(msg) msg = SafeStr(msg) or "" -- the unit menu can leave non-breaking / zero-width blanks after the name (the plain-space trim does not see them) @@ -1222,29 +1434,18 @@ do end name = strtrim((strsplit("-", name))) -- "Name-Realm" -> "Name": a single realm if name == "" then return end - -- Inside a battleground or arena the client blocks anything an addon sends itself (Karrz 2026-10-08, WSG: "Interface - -- action failed because of an AddOn", no packet). There the whisper is put in the chat box as the server command - -- ".w " and sent by the player's own Enter, which the client lets through. if InPvP() then -- The client's own /w and /whisper do nothing in a battleground (70338: the box stays in Say mode). The typed line is -- sent as an addon whisper under the FBOTS prefix, which the server hands to the bot like a whisper (the bot answers - -- as usual); it needs no second step. If the client refuses it, the box opens in whisper mode with the text in it - -- and Enter sends it ("/fb bgw dot" falls back to the ".w " command). - if text and ForeverBotsDB.bgWhisper ~= "dot" and prefixOk then - local send = C_ChatInfo and C_ChatInfo.SendAddonMessage or SendAddonMessage - local ok, res = pcall(send, ORDER_PREFIX, text, "WHISPER", name) - if ok and (res == nil or res == true or res == 0 or (Enum and Enum.SendAddonMessageResult and res == Enum.SendAddonMessageResult.Success)) then - DEFAULT_CHAT_FRAME:AddMessage("|cffff80ffTo " .. name .. ": " .. text .. "|r") - if ChatEdit_SetLastToldTarget then pcall(ChatEdit_SetLastToldTarget, name, "WHISPER") end - return - end - end - OpenWhisperBox(name, text) - Print("battleground: press Enter to whisper " .. name .. "; if the client blocks it, /fb bgw dot") + -- as usual); it needs no second step. + if text and BgWhisper(name, text) then return end + -- no chat box from a slash handler: the portrait menu's "Whisper (Forever Bots)" opens it from a click + Print("battleground: the whisper to " .. name .. " could not be sent" .. (text and "" or " (type /w " .. name .. " )") + .. "; right-click " .. name .. " and choose Whisper (Forever Bots)") return end if not text then - if ChatFrame_OpenChat then ChatFrame_OpenChat("/w " .. name .. " ") else Print("/w whispers a player") end + Print("type /w " .. name .. " to whisper") return end -- Sent straight from the slash handler (no timer, no hook on SendChatMessage): the client's own /w never works in 70205. @@ -1253,9 +1454,37 @@ do Print("whisper to " .. name .. " failed: " .. tostring(err)) return end - if ChatEdit_SetLastToldTarget then pcall(ChatEdit_SetLastToldTarget, name, "WHISPER") end end + -- The client's own Whisper (name click, friends list, portrait Interact > Whisper) leaves "/cw Name " in the chat box. Outside a + -- battleground pressing Enter on it reaches the /cw handler above. In a battleground the client's slash parser fails on such a + -- line before any handler runs, so the whisper is lost. For that case the edit boxes' OnEnterPressed gets a post-hook that + -- only READS the text (kept from OnTextChanged, since the client clears the box when it sends) and, for "/cw Name message" + -- typed in a BG, sends the addon whisper during that same key press (a player action). Nothing writes to the box, no ChatEdit_ + -- function is called, no client function is replaced. + local seen = {} -- [editbox] = { text = last non-empty text, at = time } + local function HookBox(box) + if not (box and box.HookScript) then return end + pcall(box.HookScript, box, "OnTextChanged", function(self) + local ok, text = pcall(self.GetText, self) + text = ok and SafeStr(text) or nil + if text and text ~= "" then seen[self] = { text = text, at = GetTime() } end + end) + pcall(box.HookScript, box, "OnEscapePressed", function(self) seen[self] = nil end) + pcall(box.HookScript, box, "OnEnterPressed", function(self) + local rec = seen[self] + seen[self] = nil + if not rec or GetTime() - rec.at > 30 or not InPvP() then return end + local name, text = strmatch(rec.text, "^/[cC][wW]%s+(%S+)%s+(.-)%s*$") + if not name or text == "" then return end + name = strtrim((strsplit("-", name))) + if name == "" then return end + if lastBg.name == name and lastBg.text == text and GetTime() - lastBg.at < 2 then return end -- the handler already sent it + BgWhisper(name, text) + end) + end + for i = 1, (NUM_CHAT_WINDOWS or 10) do HookBox(_G["ChatFrame" .. i .. "EditBox"]) end + for i, word in ipairs({ "/w", "/t", "/tell", "/cw", "/whisper" }) do _G["SLASH_FOREVERBOTSW" .. i .. "1"] = word SlashCmdList["FOREVERBOTSW" .. i] = Whisper @@ -1333,6 +1562,49 @@ SlashCmdList.FOREVERBOTS = function(msg) show("C_ChatInfo.SendChatMessage", function() return type(C_ChatInfo and C_ChatInfo.SendChatMessage) end) return 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")) + return + end + if verb == "chattest" then + -- Run this in a fight (type it, or bind it to a macro): says what the client does with a group order sent as an addon message + -- and as a plain chat line, so the order buttons can use whichever works in combat. The text "fbtest" is no bot order. + local channel = (IsInRaid and IsInRaid()) and "RAID" or "PARTY" + local function show(label, fn, ...) + local ok, v = pcall(fn, ...) + if not ok then v = "error: " .. tostring(v) elseif IsSecret(v) then v = "" end + Print("chattest " .. label .. " = " .. tostring(v)) + end + Print("chattest: in combat " .. tostring(InCombatLockdown and InCombatLockdown()) .. ", channel " .. channel .. ", prefix registered " .. tostring(prefixOk)) + if C_ChatInfo then + for _, fn in ipairs({ "InChatMessagingLockdown", "IsAddonChatRestricted" }) do + if C_ChatInfo[fn] then show("C_ChatInfo." .. fn, C_ChatInfo[fn]) end + end + end + show("SendAddonMessage result", C_ChatInfo and C_ChatInfo.SendAddonMessage or SendAddonMessage, ORDER_PREFIX, "fbtest", channel) + local seen = false + local ev = CreateFrame("Frame") + ev:RegisterEvent(channel == "RAID" and "CHAT_MSG_RAID" or "CHAT_MSG_PARTY") + ev:RegisterEvent(channel == "RAID" and "CHAT_MSG_RAID_LEADER" or "CHAT_MSG_PARTY_LEADER") + ev:SetScript("OnEvent", function(_, _, text) if text == "fbtest" then seen = true end end) + show("SendChatMessage call", SendChatMessage, "fbtest", channel) + if C_Timer and C_Timer.After then + C_Timer.After(2, function() + ev:UnregisterAllEvents() + Print("chattest: the chat line " .. (seen and "WAS" or "was NOT") .. " delivered to " .. channel .. " chat (a blocked call shows no error, only a missing line)") + end) + end + return + end + if verb == "menu" then + if class == "on" then ForeverBotsDB.menuEntries = true + elseif class == "off" then ForeverBotsDB.menuEntries = false + else ForeverBotsDB.menuEntries = (ForeverBotsDB.menuEntries == false) end + Print("Whisper/Invite entries in the portrait right-click menu: " .. (ForeverBotsDB.menuEntries == false and "off" or "on") + .. " (takes effect after /reload) (/fb menu on|off)") + return + end if verb == "bgw" then ForeverBotsDB.bgWhisper = (class == "dot") and "dot" or "native" Print("battleground whisper mode: " .. ForeverBotsDB.bgWhisper .. " (/fb bgw native|dot)") @@ -1379,6 +1651,8 @@ SlashCmdList.FOREVERBOTS = function(msg) ServerCommand(".bot delete " .. class) elseif verb == "list" then ServerCommand(".bot list") + elseif verb == "raidready" or verb == "ready" then + RaidReady() elseif verb == "fallback" then GroupOrder("fallback") elseif verb == "rally" then @@ -1398,7 +1672,26 @@ SlashCmdList.FOREVERBOTS = function(msg) elseif verb == "" or verb == nil then Toggle() else - Print("/fb opens the window; /fb add [tank|healer|dps]; /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 debug on|off") + 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 debug on|off") + end +end + +-- 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. +local function SayHello(attempt) + attempt = attempt or 1 + local send = C_ChatInfo and C_ChatInfo.SendAddonMessage or SendAddonMessage + local me = UnitName and UnitName("player") + local sent = false + if prefixOk and send and me then + local ok, res = pcall(send, ORDER_PREFIX, "hello", "WHISPER", me) + sent = ok and (res == nil or res == true or res == 0 or (Enum and Enum.SendAddonMessageResult and res == Enum.SendAddonMessageResult.Success)) + end + -- The self-whisper alone did not reach the server in a live test (the download hint came to players who have the add-on), so + -- the same greeting also goes as a silent server command, once. It says nothing back. + if attempt == 1 then pcall(ServerCommand, ".bot addon") end + if not sent and attempt < 4 and C_Timer and C_Timer.After then + C_Timer.After(4, function() SayHello(attempt + 1) end) end end @@ -1406,8 +1699,8 @@ local loader = CreateFrame("Frame") loader:RegisterEvent("PLAYER_LOGIN") loader:SetScript("OnEvent", function() Print("type /fb for the bot window.") + if C_Timer and C_Timer.After then C_Timer.After(2, SayHello) else SayHello() end AddPopupEntry() - HookSendTell() lastGroupSize = GroupSize() ShowDistance() if ForeverBotsDB.distance and lastGroupSize > 0 then distFrame.groupAt = Now() + 3 end @@ -1418,7 +1711,7 @@ loader:SetScript("OnEvent", function() end) -- On client 70291 a battleground leaves the chat box broken: every typed slash line (also /fb, /w) then throws --- ChatFrameEditBox.lua:206 "table cannot be indexed with secret keys" until /reload (Karrz 2026-10-09). Say so on leaving one. +-- ChatFrameEditBox.lua:206 "table cannot be indexed with secret keys" until /reload (playtest 2026-10-09). Say so on leaving one. do local pvpWas = false local pvpWatch = CreateFrame("Frame") @@ -1453,3 +1746,60 @@ do pcall(groupWatch.RegisterEvent, groupWatch, "GROUP_ROSTER_UPDATE") groupWatch:SetScript("OnEvent", function(_, ev) Report(ev == "PLAYER_ENTERING_WORLD" and "entering world" or "roster update") end) end + +------------------------------------------------------------------------------------------------------ issue reporter +-- 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. +do + local hooked, found = {}, {} + local function HideFrame(name, f) + if hooked[f] then return end + hooked[f] = true + found[#found + 1] = name + pcall(f.Hide, f) + pcall(hooksecurefunc, f, "Show", function(self) pcall(self.Hide, self) end) + end + local function Scan() + for _, name in ipairs({ "IssueReporterButton", "IssueReporterFrame", "IssueReporter", "BetaIssueReporter", "BugReportButton", "BugReportFrame" }) 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 + end + end + local watch = CreateFrame("Frame") + watch:RegisterEvent("PLAYER_ENTERING_WORLD") + watch:RegisterEvent("ADDON_LOADED") + watch:SetScript("OnEvent", function() pcall(Scan) end) + pcall(Scan) + ForeverBotsListIssueFrames = function() pcall(Scan); return found end +end + +------------------------------------------------------------------------------------------------------ forbidden-action guard +-- "ForeverBots has been blocked from an action only available to the Blizzard UI" (ADDON_ACTION_FORBIDDEN) names the protected +-- function but only in the popup. This records that name (ForeverBotsDB.lastForbidden, and one chat line, so a player can report +-- it) and, when it is not one of our own chat sends, switches the portrait-menu entries off for the next load: the entries are the +-- 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 + local guard = CreateFrame("Frame") + guard:RegisterEvent("ADDON_ACTION_FORBIDDEN") + guard:SetScript("OnEvent", function(_, _, addon, func) + if addon ~= ADDON then return end + func = type(func) == "string" and func or "?" + ForeverBotsDB.lastForbidden = { func = func, at = date and date("%Y-%m-%d %H:%M:%S") or "" } + if func:find("SendChatMessage", 1, true) or func:find("SendAddonMessage", 1, true) then + Print("the client blocked " .. func .. "() (not allowed in this situation)") + return + end + Print("the client blocked " .. func .. "() because of ForeverBots; the portrait menu entries are switched off after /reload (/fb menu on to bring them back). Please report this line.") + ForeverBotsDB.menuEntries = false + end) +end + diff --git a/src/modules/PlayerbotV2/Addon/ForeverBots/ForeverBots.toc b/src/modules/PlayerbotV2/Addon/ForeverBots/ForeverBots.toc index 449e0e8f7c..8d03b6664f 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.2.0 +## Version: 0.2.3 ## SavedVariables: ForeverBotsDB ForeverBots.lua diff --git a/src/modules/PlayerbotV2/Addon/ForeverBots/README.md b/src/modules/PlayerbotV2/Addon/ForeverBots/README.md index b4e42cc6cc..8ec961aae2 100644 --- a/src/modules/PlayerbotV2/Addon/ForeverBots/README.md +++ b/src/modules/PlayerbotV2/Addon/ForeverBots/README.md @@ -6,6 +6,10 @@ does not depend on the addon-message protocol PlayerbotControl uses. Install: copy this folder to `\_classic_beta_\Interface\AddOns\ForeverBots` (the folder name must stay `ForeverBots`). If the character screen's AddOns list marks it out of date, tick "Load out of date AddOns". +In game: `/fb` opens the window. The Raid ready button (or `/fb raidready`) calls your saved bots (`.bot summon saved`), makes the group a raid if needed, sets formation and spacing, and starts a ready check once the bots have buffed. + +On login the add-on greets the server once (a self-whisper under the `FBOTS` prefix). A player whose client does not greet within 30 seconds gets one chat line with the download link (`Playerbot.AddonHint.*` in the module config). + In game: `/fb` opens the window. The window is grouped under headings: Orders to the group (move and fight, wipe and regroup, formation and spacing, tanks and markers), Assign a bot to an icon, Your bots. Hover any button for what it does. - "Add bots >" at the top opens a separate drop-down beside the window: "Select gear" (Match my gear, Best for their level, @@ -94,3 +98,6 @@ The window stays where you put it and stays open (it is not closed by Escape, cl `/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 need a GM account (gm level 3 on the realm). + +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. +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. diff --git a/src/modules/PlayerbotV2/Api/ClassicSupplies.cpp b/src/modules/PlayerbotV2/Api/ClassicSupplies.cpp index 1c3392f94f..8909027c22 100644 --- a/src/modules/PlayerbotV2/Api/ClassicSupplies.cpp +++ b/src/modules/PlayerbotV2/Api/ClassicSupplies.cpp @@ -3,6 +3,8 @@ #include "ItemTemplate.h" #include "ObjectMgr.h" #include "SharedDefines.h" +#include "SpellInfo.h" +#include "SpellMgr.h" #include #include @@ -83,7 +85,7 @@ constexpr SupplyFamily kFamilies[] = { { "Rebirth Reagent", CLASS_DRUID, 5, kRebirthReagent }, { "Soul Shard", CLASS_WARLOCK, 5, kSoulShard }, // Open-world bots keep a small stock; raid-level (55+) bots carry what a - // raid night needs (Karrz: full potion stacks, 20 food, 40 drinks). + // raid night needs (the owner: full potion stacks, 20 food, 40 drinks). { "Food", 0, 5, kFood, kConsumable, 20 }, { "Water", 0, 10, kWater, kConsumable | SUPPLY_MANA_USERS, 40 }, { "Healing Potion", 0, 2, kHealingPotion, kConsumable, 5 }, @@ -99,18 +101,23 @@ constexpr SupplyFamily kFamilies[] = { // Nightfin Soup 13931, Tender Wolf Steak 18045. 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) }; 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) }; 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) }; 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) }; 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) }; } // namespace @@ -144,6 +151,32 @@ bool IsRaidConsumable(uint32 item) return RaidConsumableStock(item) != 0; } +std::span GroupBuffSpells(uint8 cls) +{ + // 21562 / 21564 Prayer of Fortitude r1 / r2, 27683 Prayer of Shadow Protection, 23028 Arcane Brilliance, 21849 / 21850 Gift of the Wild r1 / r2. + static constexpr uint32 kPriest[] = { 21562, 21564, 27683 }; + static constexpr uint32 kMage[] = { 23028 }; + static constexpr uint32 kDruid[] = { 21849, 21850 }; + switch (cls) + { + case CLASS_PRIEST: return kPriest; + case CLASS_MAGE: return kMage; + case CLASS_DRUID: return kDruid; + default: return {}; + } +} + +bool LearnableGroupBuff(uint32 spell, uint8 level) +{ + SpellInfo const* si = sSpellMgr->GetSpellInfo(spell, DIFFICULTY_NONE); + if (!si || si->SpellLevel > level) + return false; + for (SpellEffectInfo const& e : si->GetEffects()) + if (e.IsEffect() && e.IsAura()) + return true; + return false; +} + std::span GetSupplyFamilies() { return kFamilies; diff --git a/src/modules/PlayerbotV2/Api/ClassicSupplies.h b/src/modules/PlayerbotV2/Api/ClassicSupplies.h index 024af3f882..0bfc5925b0 100644 --- a/src/modules/PlayerbotV2/Api/ClassicSupplies.h +++ b/src/modules/PlayerbotV2/Api/ClassicSupplies.h @@ -67,6 +67,15 @@ 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); +// ---- 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 +// not known" for every one of them on level 60 bots), so the supplies restock teaches the ones the bot's level allows. +TC_GAME_API std::span GroupBuffSpells(uint8 cls); +// Whether `spell` exists in the spell data, is within a bot of `level`, and has an aura effect (Gift of the Wild has none in Forever's data: +// learning it would give a bot a buff that buffs nobody). +TC_GAME_API bool LearnableGroupBuff(uint32 spell, uint8 level); + // ---- Ammo for the equipped bow / crossbow / gun (Playerbot.Behavior.AmmoSupply) ---- // Kinds match the snapshot's ammo_kind: 1 = arrows (bow, crossbow), 2 = bullets (gun). // The restock tops the bags up to AMMO_TARGET (several stacks) once the stock is under @@ -90,6 +99,7 @@ struct RaidConsumable bool food; // buff is "Well Fed" (the eating spell triggers it) rather than the item's own spell uint8 stock; // how many a bot is kept stocked with bool flask = false; // a flask: it fills both elixir slots, so an elixir used on top of it removes it (MC Garr 2026-10-11: Mageblood took the +2000 mana of a Flask of Distilled Wisdom off five healers) + bool combat = false; // drunk in the fight when the encounter data orders it (RaidRules::resistPotion), never in the pre-pull; only stocked }; TC_GAME_API std::span RaidConsumablesFor(RaidConsumableRole role); @@ -104,7 +114,7 @@ TC_GAME_API uint8 RaidConsumableStock(uint32 item); template bool ElixirOverFlask(RaidConsumableRole role, RaidConsumable const& c, Buffed buffed) { - if (c.food || c.flask) + if (c.food || c.flask || c.combat) return false; for (RaidConsumable const& k : RaidConsumablesFor(role)) if (k.flask && buffed(k)) @@ -119,7 +129,7 @@ template RaidConsumable const* NextRaidConsumable(RaidConsumableRole role, InBags in_bags, Buffed buffed) { for (RaidConsumable const& c : RaidConsumablesFor(role)) - if (!buffed(c) && in_bags(c.item) && !ElixirOverFlask(role, c, buffed)) + if (!c.combat && !buffed(c) && in_bags(c.item) && !ElixirOverFlask(role, c, buffed)) return &c; return nullptr; } diff --git a/src/modules/PlayerbotV2/Api/DiagProbes.h b/src/modules/PlayerbotV2/Api/DiagProbes.h index 7b712fb6f3..5ae1a6d7e2 100644 --- a/src/modules/PlayerbotV2/Api/DiagProbes.h +++ b/src/modules/PlayerbotV2/Api/DiagProbes.h @@ -38,7 +38,7 @@ namespace Playerbot::Probes if (now >= nextRead.load(std::memory_order_relaxed)) { nextRead.store(now + 5, std::memory_order_relaxed); - enabled.store(sConfigMgr->GetBoolDefault("Playerbot.Diag.Probes", false), std::memory_order_relaxed); + enabled.store(sConfigMgr->GetBoolDefault("Playerbot.Diag.Probes", false, true), std::memory_order_relaxed); } return enabled.load(std::memory_order_relaxed); } diff --git a/src/modules/PlayerbotV2/Api/PlayerbotAPI.cpp b/src/modules/PlayerbotV2/Api/PlayerbotAPI.cpp index 757f659800..0cdf6c6f0c 100644 --- a/src/modules/PlayerbotV2/Api/PlayerbotAPI.cpp +++ b/src/modules/PlayerbotV2/Api/PlayerbotAPI.cpp @@ -2,12 +2,14 @@ // 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 "PlayerbotAPI.h" #include "ClassicBotSkills.h" #include "ClassicSpec.h" #include "ClassicTalentBuilds.h" #include "ClassicSupplies.h" +#include "Bot/ClassicUpkeep.h" #include "BotItemScorer.h" #include "Player.h" #include "Corpse.h" @@ -40,6 +42,7 @@ #include "DetourNavMeshQuery.h" #include "PlayerbotV2.h" // path-outcome telemetry, bot-leader battleground queue #include "PlayerbotMovement.h" // unified bot-movement helpers +#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" @@ -452,7 +455,7 @@ static uint32 HighestKnownRank(Player const* p, uint32 spell_id) // Off = the previous path: SetFacingToObject whenever the target is not in front. static bool CastFacingEnabled() { - static bool const enabled = sConfigMgr->GetBoolDefault("Playerbot.Behavior.CastFacing", true); + static bool const enabled = sConfigMgr->GetBoolDefault("Playerbot.Behavior.CastFacing", true, true); return enabled; } @@ -545,7 +548,7 @@ Result API::cast_spell(uint32 spell_id, ObjectGuid target, bool exact_rank) uint32 const requested_id = spell_id; if (!exact_rank || !p_->HasSpell(spell_id)) spell_id = HighestKnownRank(p_, spell_id); - // [cast_rank] (Karrz, 2026-10-08: confirm every damage spell goes out at the top known rank): per bot and requested spell, at most one + // [cast_rank] (playtest, 2026-10-08: confirm every damage spell goes out at the top known rank): per bot and requested spell, at most one // line a minute, "requested -> cast". { static std::unordered_map s_rank_log; @@ -759,13 +762,13 @@ Result API::cast_spell(uint32 spell_id, ObjectGuid target, bool exact_rank) if (!FaceUnitForCast(p_, tu) && CastFacingEnabled()) return last_cast_fail_ = 0, Result::Locked; // Spells that do not need the target in front (heals, buffs) still turn the caster to a target that is behind it when it - // can (Karrz, Deadmines 2026-10-10: the priest healed with her back to the target). Best effort: a caster that is moving + // can (playtest, Deadmines 2026-10-10: the priest healed with her back to the target). Best effort: a caster that is moving // keeps its heading and the cast goes out anyway. if (tu != p_ && CastFacingEnabled() && !(info->FacingCasterFlags & SPELL_FACING_FLAG_INFRONT)) FaceUnitForCast(p_, tu); // A bot that drank or sat and now casts stands up first, as a client does when its player casts (the drink aura ends on the - // cast, the sitting pose did not: Karrz saw the priest heal kneeling). Food / drink spells themselves sit the bot, so they are + // cast, the sitting pose did not: the owner saw the priest heal kneeling). Food / drink spells themselves sit the bot, so they are // left alone. [stand_state] logs each change, at most one line per bot per 5 s. if (p_->GetStandState() == UNIT_STAND_STATE_SIT || p_->GetStandState() == UNIT_STAND_STATE_KNEEL) if (!info->HasAura(SPELL_AURA_MOD_POWER_REGEN) && !info->HasAura(SPELL_AURA_MOD_REGEN)) @@ -805,7 +808,7 @@ Result API::cast_spell(uint32 spell_id, ObjectGuid target, bool exact_rank) // Throttled diagnostic: log the first failure per (spell, reason) combo // so the operator can see WHY a rule is firing but the cast never lands // (out of range, LOS, moving, etc). Without this the bot looks "stuck" - // in inspect: LastRule says e.g. "Frostbolt (filler)" because the AI + // in inspect: LastRule says e.g. "Frostbolt (filler)" because the bot logic // 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 @@ -1070,7 +1073,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 // flight generator and the bot looks "stuck" until landing. Refuse so - // the AI re-evaluates next snapshot when the taxi arrives. + // the bot logic re-evaluates next snapshot when the taxi arrives. if (p_->GetMotionMaster()->GetCurrentMovementGeneratorType() == FLIGHT_MOTION_TYPE) return Result::Locked; @@ -1117,7 +1120,7 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop) return Result::Locked; // A free fall: the jump spline's parabola (height = g*T^2/8, MotionMaster::MoveJump) is exactly gravity over the drop // when T = sqrt(2*fall/g), so the leap takes that long. A fixed 8 y/s along the whole path took 3 s for a 15 y drop and - // looked like a slow fall (Karrz, WSG 2026-10-09). The walk off the edge is allowed 16 y/s at most. + // looked like a slow fall (playtest, WSG 2026-10-09). The walk off the edge is allowed 16 y/s at most. float const dist3 = std::sqrt(dxy * dxy + fall * fall); float const fall_s = std::max(std::sqrt(2.0f * fall / float(Movement::gravity)), dxy / 16.0f); float const speed = dist3 / fall_s; @@ -1170,7 +1173,7 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop) // Battleground start room (STATUS_WAIT_JOIN): the gates are shut and the bots only mill about their start area, so a // destination whose ground is far above or below the bot is off the platform (a gate-wait spot spread over the edge of // the plateau, a slope under a cliff). Routing there ends in a straight-line spline over empty air or in the platform - // step-down relocation below, which is how bots ended up hanging in the air above the AB valley (Karrz, 2026-10-08). + // step-down relocation below, which is how bots ended up hanging in the air above the AB valley (playtest, 2026-10-08). // Refuse it; the idle rule picks another spot. if (Battleground const* prep_bg = p_->GetBattleground(); prep_bg && prep_bg->GetStatus() == STATUS_WAIT_JOIN && @@ -1615,7 +1618,10 @@ Result API::move_to(float x, float y, float z, bool run, bool direct, bool drop) } // 3D distance, NOT horizontal-only: a harbour dock / pier exit can sit // almost directly ABOVE the bot (small XY, large Z). - if (navpt && exd2 > 3.0f * 3.0f) + // One yard, not three: a bot in lava two or three yards off the bank is exactly the one that must step out. Ragnaros 2026-10-13 + // 650994ea: a healer stood 85 s in the magma at the platform's edge, 2.8 y from the dry point its raid order named, hurt every + // second and healed back by the others, and did not move once. + if (navpt && exd2 > 1.0f * 1.0f) { p_->GetMotionMaster()->MovePoint( 0, exit_pt.GetPositionX(), exit_pt.GetPositionY(), @@ -2634,7 +2640,7 @@ Result API::start_attack(ObjectGuid target, uint8 avoid_school_mask) } // 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 (Karrz, 2026-10-08). Like a real player who clicks + // 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(); @@ -2686,7 +2692,7 @@ Result API::start_attack(ObjectGuid target, uint8 avoid_school_mask) // do not re-call Attack or re-init MoveChase. Both have visible side // effects every tick — MoveChase resets the chase generator, clearing // the spline and forcing a path recalc. Calling it every tick (which - // the AI does as long as the engage rule keeps firing on the same + // 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 @@ -2709,7 +2715,7 @@ Result API::start_attack(ObjectGuid target, uint8 avoid_school_mask) // do not re-call Attack or re-init MoveChase. Both have visible side // effects every tick — MoveChase resets the chase generator, clearing // the spline and forcing a path recalc. Calling it every tick (which - // the AI does as long as the engage rule keeps firing on the same + // 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: @@ -2769,7 +2775,7 @@ Result API::start_attack(ObjectGuid target, uint8 avoid_school_mask) holdAvoidedAutoRepeat(tu); ensureAutoShot(tu); - // Real Players chase the target via client input; an AI-driven bot Player + // 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 @@ -2994,7 +3000,7 @@ Result API::mount(uint32 mount_id) for (uint32 carry_aura : { 23333u, 23335u, 34976u, 121164u, 121175u, 121176u, 121177u }) if (p_->HasAura(carry_aura)) return Result::Locked; // One rule for battlegrounds (Battleground::GetMountRefusal): closed start doors or an indoor area, no distance radius. Players - // are held to the same rule in Spell.cpp. One line per bot every 20 s says why a mount is refused (Karrz, WSG 70291). + // are held to the same rule in Spell.cpp. One line per bot every 20 s says why a mount is refused (playtest, WSG 70291). if (Battleground const* bg = p_->GetBattleground()) if (char const* why = bg->GetMountRefusal(p_)) { @@ -3753,6 +3759,8 @@ Result API::enter_area_trigger(uint32 area_trigger_id) WorldSession* sess = p_->GetSession(); if (!sess) return Result::Other; AreaTriggerTeleport const* dest = sObjectMgr->GetAreaTrigger(area_trigger_id); + if (dest && dest->Loc.GetMapId() != p_->GetMapId()) + V2::Fleet::PrepareInstanceEntry(p_, dest->Loc.GetMapId()); WorldPackets::AreaTrigger::AreaTrigger packet{ WorldPacket(CMSG_AREA_TRIGGER) }; packet.AreaTriggerID = int32(area_trigger_id); packet.Entered = true; @@ -3823,6 +3831,10 @@ Result API::teleport_to(uint32 map_id, float x, float y, float z, float orientat if (!p_->IsAlive()) return Result::Locked; if (p_->IsInCombat()) return Result::Locked; if (p_->IsNonMeleeSpellCast(false, false, true)) return Result::Locked; + // Into an instance (the owner's raid): the door checks run first so a refusal is logged with its reason, and a lock on + // another instance is dropped for a companion that follows its owner in. + if (map_id != p_->GetMapId() && V2::Fleet::PrepareInstanceEntry(p_, map_id) != TRANSFER_ABORT_NONE) + return Result::ServerRefused; // SafeTeleport probes the destination map (if loaded) for ground // height and snaps to ground+2 when the requested Z is >50y above // the queried floor (typical "stale POI / hand-curated coord" bug @@ -3947,7 +3959,7 @@ Result API::decline_trade() return Result::Ok; } -// `owner` is the trade partner the AI decided to trade with. gift_ok: the bot's owner or a real player in its own group or raid (Bot/TradeRule.h), who may +// `owner` is the trade partner the bot logic decided to trade with. gift_ok: the bot's owner or a real player in its own group or raid (Bot/TradeRule.h), who may // hand over gear and gold as a gift; anyone else gets the fair-price bargain (BotTrade.h). Result API::accept_owner_trade(ObjectGuid owner) { @@ -4308,7 +4320,7 @@ Result API::set_raid_difficulty(uint32 difficulty_id, bool legacy) return Result::Ok; } -// A creature the bot mind-controls (priest Mind Control: Razuvious' understudies). It has no pet bar AI and is not +// A creature the bot mind-controls (priest Mind Control: Razuvious' understudies). It has no pet bar bot logic and is not // moved by a client, so attack and chase are driven from here. nullptr when the bot controls nothing. static Creature* PossessedCreature(Player* p) { @@ -4438,7 +4450,7 @@ Result API::dismiss_pet() // (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 -// autonomously we want the AI to swap pets based on encounter (e.g. swap +// 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 // gating, dead-active refusal, current-pet-not-deletable) match Player:: @@ -5085,7 +5097,7 @@ Result API::repair_all(ObjectGuid npc, bool from_guild_bank) // 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 AI and the player-money branch below already + // 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 — // exactly the intended "gold self-repair on dungeon staging/running". if (!npc.IsEmpty()) @@ -5143,7 +5155,7 @@ Result API::repair_all(ObjectGuid npc, bool from_guild_bank) // 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 // earn -> still can't repair). Grant the shortfall so a broke bot can always - // fully repair (bots are AI; a free repair is fine and far cheaper than the + // 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. { @@ -5197,10 +5209,10 @@ static Result UseItemImpl(Player* p, Item* item, ObjectGuid 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 — // Unit::HandleSpellClick both casts the click spell AND fires the creature's - // OnSpellClick AI. That AI is what credits this whole class of quests + // OnSpellClick bot logic. That bot logic is what credits this whole class of quests // (e.g. Q26118: spellclick Ambassador Slaghammer 42146 -> SmartAI // SMART_EVENT_ON_SPELLCLICK -> SMART_ACTION_COMPLETE_QUEST). A raw - // CastItemUseSpell never triggers the AI, so the quest never completes. + // CastItemUseSpell never triggers the bot logic, so the quest never completes. if (tu->HasNpcFlag(UNIT_NPC_FLAG_SPELLCLICK)) { p->SetTarget(tu->GetGUID()); @@ -5273,7 +5285,7 @@ Result API::loot_corpse(ObjectGuid corpse) { p_->SendLoot(*loot, false); // SendLoot opens the loot window (LootGUID, UNIT_FLAG_LOOTING = the kneeling loot pose) and a bot has no client to close - // it: every bot in a group with party loot rules stayed in the loot pose through every fight and cast (Karrz, Deadmines + // it: every bot in a group with party loot rules stayed in the loot pose through every fight and cast (playtest, Deadmines // 2026-10-10: "they're always looting"). Close it as a player closing the window does - the rolls the open started stay. if (WorldSession* sess = p_->GetSession()) sess->DoLootRelease(loot); @@ -5711,7 +5723,7 @@ Result API::use_game_object(ObjectGuid go_guid) if (!obj) { // Not silent for the classic AB banners (entries 180058-180091): a bot standing at a pole that cannot click it was the - // "bots stand at the Stables, nothing is captured" report (Karrz, AB test 2026-10-08). + // "bots stand at the Stables, nothing is captured" report (playtest, AB test 2026-10-08). if (p_->InBattleground()) if (Map* bmap = p_->GetMap()) if (GameObject* raw = bmap->GetGameObject(go_guid)) @@ -5734,7 +5746,7 @@ Result API::use_game_object(ObjectGuid go_guid) return Result::Locked; // A battleground flag or banner is not used in a shapeshift form (a bear-form druid stood at the Lumber Mill banner doing nothing, - // Karrz AB 2026-10-11): leave the form first, the next click (the rule re-emits) goes through as a caster. + // 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 && (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 || @@ -5747,7 +5759,7 @@ Result API::use_game_object(ObjectGuid go_guid) // Battleground node banners (AB / AV / Gilneas style BUTTON and GOOBER objects) are not instant for a player: the capture is // a channel of several seconds that movement or damage breaks. Calling Use() straight away let a whole squad flip the - // Blacksmith and Lumber Mill Alliance/Horde/Alliance/Horde every second (Karrz, AB test 2026-10-08). The bot now "channels" + // Blacksmith and Lumber Mill Alliance/Horde/Alliance/Horde every second (playtest, AB test 2026-10-08). The bot now "channels" // too: the first call starts the capture, a later call (the rule re-emits every ~3 s) completes it once 5 s have passed and // the bot has neither moved more than 3 y nor lost health; after a completed capture it must wait 15 s before the next one. if (p_->InBattleground() && @@ -5758,7 +5770,7 @@ Result API::use_game_object(ObjectGuid go_guid) BannerCapture& cap = s_bannerCapture[p_->GetGUID()]; uint32 const nowMs = GameTime::GetGameTimeMS(); // A cast already running (the capture spell the object's Use() starts) must never be restarted by a second click: a - // new Use() while the bar is filling cancels it (Karrz, AB test: "she keeps casting and it stops"). + // new Use() while the bar is filling cancels it (playtest, AB test: "she keeps casting and it stops"). if (p_->IsNonMeleeSpellCast(false)) return Result::Locked; if (cap.lastDoneMs && nowMs - cap.lastDoneMs < 15000u) @@ -5795,7 +5807,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-AI 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. @@ -6194,7 +6206,7 @@ Result API::complete_quest(ObjectGuid quest_giver, uint32 quest_id, uint32 rewar // Same-NPC follow-up auto-accept. Scripted escort NPCs (Tarindrella for // 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 AI ~1 snapshot to re-probe + // post-RewardQuest world tick gives the bot logic ~1 snapshot to re-probe // 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 @@ -6782,14 +6794,29 @@ std::vector ParseCuratedBuild(std::string const& text) // Empty string means no curated row found. std::string LookupCuratedBuildRow(uint32 classId, uint32 specId, uint8 context) { + // The curated table only changes by hand and a build is looked up for every + // bot setup and respec, so each (class, spec, context) is read from the DB + // once per process (misses cached too) instead of once per bot. + static std::mutex cacheMutex; + static std::unordered_map cache; auto try_row = [&](uint8 ctx) -> std::string { + uint32 const key = (classId << 16) | ((specId & 0xFFu) << 8) | ctx; + { + std::lock_guard lock(cacheMutex); + if (auto it = cache.find(key); it != cache.end()) + return it->second; + } + std::string row; auto r = CharacterDatabase.PQuery( "SELECT entries_json FROM playerbot_v2_talent_build " "WHERE class_id={} AND spec_id={} AND context={}", classId, specId, ctx); - if (!r) return {}; - return r->Fetch()[0].GetString(); + if (r) + row = r->Fetch()[0].GetString(); + std::lock_guard lock(cacheMutex); + cache.emplace(key, row); + return row; }; if (auto s = try_row(context); !s.empty()) return s; if (context != 0) @@ -7171,11 +7198,39 @@ Result API::restock_class_supplies() uint32 added = 0; bool full = false; uint8 const level = uint8(p_->GetLevel()); + // The party versions of the class buffs, which no Forever trainer sells. + for (uint32 const spell : Classic::GroupBuffSpells(p_->GetClass())) + { + if (p_->HasSpell(spell)) + continue; + if (!Classic::LearnableGroupBuff(spell, level)) + continue; + SpellInfo const* si = sSpellMgr->GetSpellInfo(spell, DIFFICULTY_NONE); + p_->LearnSpell(spell, false); + ++added; + TC_LOG_INFO("playerbot.v2", "[supplies] {} learns {} ({})", p_->GetName(), spell, si->SpellName ? (*si->SpellName)[sWorld->GetDefaultDbcLocale()] : ""); + } + // Why a family left nothing in the bags, once per bot and reason ([supplies]; the Demonic Rune never reached the bags of the + // Ragnaros squad and nothing said why). World thread only, like the rest of this function. + static std::unordered_set s_supplyReasonLogged; + auto const skipped = [&](Classic::SupplyFamily const& f, uint32 item, char const* why, uint32 detail) + { + uint64 const key = std::hash{}(f.name) ^ (uint64(p_->GetGUID().GetCounter()) * 0x9E3779B97F4A7C15ull) ^ (uint64(detail) * 0xC2B2AE3D27D4EB4Full); + if (s_supplyReasonLogged.size() > 8192) + s_supplyReasonLogged.clear(); + 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()) { 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); - if (!entry) continue; + if (!entry) + { + skipped(f, 0, "no rank for the level has an item template", level); + continue; + } // Bandages need First Aid: every bot knows it at the rank of its // level (ike3's factory gives bots the skill the same way). if (f.flags & Classic::SUPPLY_FIRST_AID) @@ -7195,7 +7250,11 @@ Result API::restock_class_supplies() ItemTemplate const* proto = sObjectMgr->GetItemTemplate(entry); // Poisons need the Poisons skill (a level 20 rogue quest); hand out // only what the bot can actually use. - if (!proto || p_->CanUseItem(proto) != EQUIP_ERR_OK) continue; + if (!proto || p_->CanUseItem(proto) != EQUIP_ERR_OK) + { + skipped(f, entry, "the bot cannot use the item", proto ? uint32(p_->CanUseItem(proto)) : 0u); + continue; + } uint32 have = 0; if (f.flags & Classic::SUPPLY_ALL_RANKS) { @@ -7207,13 +7266,16 @@ Result API::restock_class_supplies() uint32 const target = Classic::SupplyTarget(f, level); if (have >= target) continue; ItemPosCountVec dest; - if (p_->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, entry, target - have) != EQUIP_ERR_OK) + if (InventoryResult const stored = p_->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, entry, target - have); 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; + 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%. @@ -8361,7 +8423,7 @@ Result API::fly_to_node(ObjectGuid flight_master, uint32 to_node) // Bots are perpetually broke (a fresh L3 has ~67 copper), 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 AI; a free + // 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 // stranded on the wrong continent). 5g covers any single multi-hop route. constexpr uint64 kFlightReserve = 50000; // 5 gold in copper diff --git a/src/modules/PlayerbotV2/Api/PlayerbotAPI.h b/src/modules/PlayerbotV2/Api/PlayerbotAPI.h index ddfd93260c..478d324732 100644 --- a/src/modules/PlayerbotV2/Api/PlayerbotAPI.h +++ b/src/modules/PlayerbotV2/Api/PlayerbotAPI.h @@ -161,7 +161,7 @@ public: // Why a mount spell would draw nothing on the client, nullptr when its model resolves: the display the aura picks (Mount // DB2 displays, else the creature in the aura's misc value) has no CreatureDisplayInfo or no model data / file. A bot on - // such a mount runs at mount speed and looks on foot (Karrz, WSG 2026-10-09: Arimer, Fareed). `display_out` receives the + // such a mount runs at mount speed and looks on foot (playtest, WSG 2026-10-09: Arimer, Fareed). `display_out` receives the // first display id checked. static char const* MountDisplayProblem(uint32 spell_id, uint32* display_out = nullptr); @@ -652,7 +652,7 @@ public: // whetstone applied to a weapon). Result use_item_by_entry(uint32 item_entry, ObjectGuid target = ObjectGuid::Empty); // use_item_by_slot: same effect resolution as by-entry but addresses the - // item by bag/slot. Used when AI rules pre-pick a specific stack (e.g. + // item by bag/slot. Used when bot logic rules pre-pick a specific stack (e.g. // a particular potion variant when several share an entry id is rare, // but bag/slot avoids ambiguity). Result use_item_by_slot(uint8 bag, uint8 slot, ObjectGuid target = ObjectGuid::Empty); diff --git a/src/modules/PlayerbotV2/Api/PlayerbotMovement.cpp b/src/modules/PlayerbotV2/Api/PlayerbotMovement.cpp index 7cd09f57e9..5083e08f85 100644 --- a/src/modules/PlayerbotV2/Api/PlayerbotMovement.cpp +++ b/src/modules/PlayerbotV2/Api/PlayerbotMovement.cpp @@ -227,7 +227,7 @@ float GroundZ(Player* p, float x, float y, float zHint, char const* where, bool* { if (ok) *ok = false; - static bool const enabled = sConfigMgr->GetBoolDefault("Playerbot.Behavior.GroundSnap", true); + static bool const enabled = sConfigMgr->GetBoolDefault("Playerbot.Behavior.GroundSnap", true, true); if (!enabled || !p) return zHint; Map* m = p->GetMap(); diff --git a/src/modules/PlayerbotV2/Api/PlayerbotMovement.h b/src/modules/PlayerbotV2/Api/PlayerbotMovement.h index aa01423ade..4efcf4ba60 100644 --- a/src/modules/PlayerbotV2/Api/PlayerbotMovement.h +++ b/src/modules/PlayerbotV2/Api/PlayerbotMovement.h @@ -12,7 +12,7 @@ // * Jumps and other ballistic moves refuse to launch into walls / closed // doors / cliff faces. // * Off-mesh recovery (FARFROMPOLY_START) re-snaps the bot to the nearest -// valid navmesh poly before the AI re-emits movement. +// valid navmesh poly before the bot logic re-emits movement. // // Inspiration: mod-playerbots' SearchForBestPath / CheckCollisionAndGetValidCoords // (AzerothCore module), mapped onto TrinityCore's PathGenerator + vmap/mmap @@ -97,7 +97,7 @@ float GroundZ(Player* p, float x, float y, float zHint, char const* where, bool* // surrounding floor: ~14-16y for city lifts. Detour caps a findNearestPoly // box at ~128 overlapped polys, so keep `hz` modest (≤8y) to avoid grabbing a // poly from a different elevator floor. Runs on the world thread (queries the -// live navmesh); never call from an AI worker. +// live navmesh); never call from an bot worker. bool NearestNavPoint(Player* p, float tx, float ty, float tz, float hxy, float hz, Position& out); diff --git a/src/modules/PlayerbotV2/BOT_COMMANDS.md b/src/modules/PlayerbotV2/BOT_COMMANDS.md index 65203fc201..1816fcbd59 100644 --- a/src/modules/PlayerbotV2/BOT_COMMANDS.md +++ b/src/modules/PlayerbotV2/BOT_COMMANDS.md @@ -74,6 +74,10 @@ Install the `ForeverBots` folder into `Interface\AddOns` (the folder name must s out of date AddOns"). The addon only sends ordinary chat, so it needs nothing else on the client. - `/fb` opens or closes the window (it stays open across relog). The window has: + - **Raid ready** (also `/fb raidready`): calls your saved bots (`.bot summon saved`), waits until the group stops growing, + makes it a raid when it holds more than five, sets formation circle and spacing close, sends `resume` and the + crowd-control switch, sets the Main Tank flag when you target a group member, and starts a ready check about twenty + seconds later while the bots buff themselves. Not in combat; a new click or combat cancels it. - **Add buttons**: one per class and role (`.bot add `). - **Orders**: Follow, Stay, Attack (your target), Resume, Pull, Flee, Come, Stop, Release, Pull back, Fall back, Set rally. They go out in party/raid chat, so typing the word is identical. @@ -87,7 +91,7 @@ out of date AddOns"). The addon only sends ordinary chat, so it needs nothing el frame (drag it, position is saved): the eight icons (click assigns, right-click clears), Follow, Stay, Attack, Pull back, Dist -/+, Dismiss and a status line with the bot's last confirmation. `/fb bot on|off` toggles it. The client cannot tell a bot from a human, so do not use the panel on real players. -- Slash commands that work without the window: `/fb add [role]`, `/fb call|dismiss|save|unsave|regear +- Slash commands that work without the window: `/fb add [role]`, `/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 tank |clear`, `/fb assign [role]`, `/fb assign list`. @@ -147,10 +151,11 @@ from the bot. | `repair` | yes | yes | Same pattern with a repair vendor: `Raveni: repairing at ...`. | | `loot` | yes | yes | Need before greed with the usual etiquette (human gets first claim). `Raveni: need before greed, the usual rules`. | | `loot all` | yes | yes | The bot rolls for itself on every drop and takes every corpse item, greys included. `Raveni: looting everything, greys included, and rolling for myself`. Memory only (resets on relog). | +| `use ` | yes | yes | Uses a dungeon object near the bot: an altar, brazier, lever or orb (`use altar`, `use brazier`). The bot walks to the nearest match within 30 yards, uses it once and then stays there until you say `follow`. For an object that needs several people, such as the Blackrock Altar in Upper Blackrock Spire (three), click it yourself and send it to two bots by name: `;Raveni:use altar`, `;Doran:use altar`. Nothing matching: `no 'altar' within 30 yards of me`. | ### Gear and economy by whisper (selected NPC needed) -`buy [n]`, `buyfood`, `buypot`, `buybandage`, `buyall`, `use `, `equip `, `bank`, `auction`, +`buy [n]`, `buyfood`, `buypot`, `buybandage`, `buyall`, `equip `, `bank`, `auction`, `mail`, `train`, `talents [apply]`, `upgrades [apply]`, `fly ` and the `*_all` broadcasts such as `repair_all`, `sell_all`, `buyfood_all`. They need a selected vendor/auctioneer/flight master where the bot has to interact. The full index is the `commands` whisper. @@ -265,8 +270,8 @@ World bots are ambient characters with no owner (`Playerbot.World.Enable = 1` sp Invites: `Playerbot.Interact.AutoAcceptInvites` (`none`, `friends_or_higher`, `guild_or_higher`, `anyone`). - Companion banter (`PartyBanter`): a short lowercase line now and then on ready check, wipe, rez, death, boss kill; never in a group over 15 or with `Playerbot.Chatter.Enabled = 0`. -- Hostile-faction world bots can be placed near you (`Playerbot.World.FriendlyPct`, default 80); set it to 100 to - avoid fights on a PvP realm. +- Hostile-faction world bots can be placed near you (`Playerbot.World.FriendlyPct` and the per-zone `*FriendlyPct` keys, all 100 = none by default); lower them to + get them (they fight on a PvP realm). ## 12. Config keys @@ -310,7 +315,7 @@ Defaults are those of `conf/playerbot.conf.dist`. Behaviour switches are read wh **Social and world (default)**: `BotWhisperable` 1, `WorldBotSayReply` 1, `PoliteWorldBots` 1, `PartyBanter` 1, `SocialEmotes` 1, `Fidget` 1, `Playerbot.Chatter.Enabled` 1, `Playerbot.Interact.AutoAcceptInvites` friends_or_higher, `Playerbot.Interact.AutoLeaderHandover` 1, `Playerbot.World.Enable` 0 (`MaxBots` 100, `BotsPerPlayer` 25, -`ActivityRadius` 300, `FriendlyPct` 80), `Playerbot.Population.TotalTarget` 0. +`ActivityRadius` 300, `FriendlyPct` 100), `Playerbot.Population.TotalTarget` 0. **Battlegrounds**: `Playerbot.Bg.AutoSeed.Matches` 0, `Playerbot.Bg.AutoJoin` 0, `Playerbot.Bg.MakeRoomForPlayers` 1, `Playerbot.Bg.Coordinator.Enable` 1. diff --git a/src/modules/PlayerbotV2/Bot/AddonHint.h b/src/modules/PlayerbotV2/Bot/AddonHint.h new file mode 100644 index 0000000000..441c303027 --- /dev/null +++ b/src/modules/PlayerbotV2/Bot/AddonHint.h @@ -0,0 +1,48 @@ +// Who still has to be told where to get the ForeverBots add-on: a player is noted at login and dropped as soon as the add-on +// says hello (a self-whisper under the order prefix) or the player leaves. Whoever is still noted after the grace period is due +// once, then forgotten, so each login produces at most one hint. Pure bookkeeping: no Player, no clock, no config. +#pragma once + +#include +#include +#include +#include +#include + +namespace Playerbot::V2 { + +// Text of the add-on's greeting to the server. +inline constexpr std::string_view kAddonHelloText = "hello"; + +class AddonHintTracker +{ +public: + void Login(uint64_t player, uint32_t now_ms, uint32_t delay_ms) { due_[player] = now_ms + delay_ms; } + void Hello(uint64_t player) { due_.erase(player); } + void Logout(uint64_t player) { due_.erase(player); } + bool Pending(uint64_t player) const { return due_.count(player) != 0; } + size_t Size() const { return due_.size(); } + + // Players whose grace period has run out; they are removed (one hint per login). Wrap-safe for the 32-bit millisecond clock. + std::vector TakeDue(uint32_t now_ms) + { + std::vector out; + for (auto it = due_.begin(); it != due_.end();) + { + if (int32_t(now_ms - it->second) >= 0) + { + out.push_back(it->first); + it = due_.erase(it); + } + else + ++it; + } + std::sort(out.begin(), out.end()); + return out; + } + +private: + std::unordered_map due_; +}; + +} // namespace Playerbot::V2 diff --git a/src/modules/PlayerbotV2/Bot/Battleground/BattlegroundScript.h b/src/modules/PlayerbotV2/Bot/Battleground/BattlegroundScript.h index 17b9417dfc..4414a44995 100644 --- a/src/modules/PlayerbotV2/Bot/Battleground/BattlegroundScript.h +++ b/src/modules/PlayerbotV2/Bot/Battleground/BattlegroundScript.h @@ -303,7 +303,7 @@ private: // nodes can each have an active callout but the same node can't be // re-shouted by 40 bots. // -// Threading: callout claims happen on the AI worker thread (one bot +// Threading: callout claims happen on the bot worker thread (one bot // per worker per tick); the registry uses a shared_mutex for read- // dominant lookups + an upgrade write when claiming/expiring entries. // diff --git a/src/modules/PlayerbotV2/Bot/Battleground/BgAvPlan.h b/src/modules/PlayerbotV2/Bot/Battleground/BgAvPlan.h index f2c6499051..596fea91b0 100644 --- a/src/modules/PlayerbotV2/Bot/Battleground/BgAvPlan.h +++ b/src/modules/PlayerbotV2/Bot/Battleground/BgAvPlan.h @@ -1,4 +1,4 @@ -// Alterac Valley objective rules imported from ike3's bots (the ike3-based playerbot code, +// Alterac Valley objective rules imported from ike3's bots (Karrz1/wow-1.12 raid10-revamp bcc8b9fe70c42a8fa5d50fa83a472da9e9d19546, // BattleGroundTacticsAV.cpp): the mine-boss objective and the captain gathering threshold. Pure functions, no game state, so they can be // tested offline (tests/game/BgAvPlan.cpp). The mid-field fighting tactics are ours and do not live here. #pragma once @@ -10,7 +10,7 @@ namespace Playerbot::BgAvPlan { // The captain squad goes in once this many of the team stand at the waiting spot (ike3: attackers near the waiting spot >= 5). constexpr int kCaptainGatherCount = 5; - // Time cap (Karrz, AV 2026-10-11: a pile of bots waited at the Stonehearth staging spot for a quorum): after kCaptainGatherMaxMs of waiting the squad + // 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) @@ -164,7 +164,7 @@ namespace Playerbot::BgAvPlan return n < 1 ? 1 : n; } - // ---- Rules from ike3 / mod-playerbots AV that the planner uses (the ike3-based playerbot code raid10-revamp BattleGroundTacticsAV.cpp, mod-playerbots + // ---- Rules from ike3 / mod-playerbots AV that the planner uses (Karrz1/wow-1.12 raid10-revamp BattleGroundTacticsAV.cpp, mod-playerbots // BattleGroundTactics.cpp selectObjective) ---- // A defender already deep in the enemy half becomes an attacker: x >= -62 for the Horde, x <= -462 for the Alliance (AV runs from the // Frostwolf end at x -1400 to Dun Baldar at x +700); with chance 20 + 15 per own node razed (mod-playerbots BGT 1919-1931). diff --git a/src/modules/PlayerbotV2/Bot/Battleground/BgTactics.h b/src/modules/PlayerbotV2/Bot/Battleground/BgTactics.h index 44ef1a10dd..f7894ad3fc 100644 --- a/src/modules/PlayerbotV2/Bot/Battleground/BgTactics.h +++ b/src/modules/PlayerbotV2/Bot/Battleground/BgTactics.h @@ -3,7 +3,7 @@ // Ideas ported from the two reference bot families, rewritten for our team planner (credit: ike3 playerbots for the // capture-skip / role split ideas, liyunfan1223/mod-playerbots BattleGroundTactics.cpp for the capture abort, the 60 s // objective reset and the camp-the-enemy-graveyard rule). Values are vanilla 1.12 behaviour (AB capture 60 s, AV tower 5 min). -// Written for Karrz (Karrz). +// Written for Karrz. #pragma once #include diff --git a/src/modules/PlayerbotV2/Bot/Battleground/BgTargetPick.h b/src/modules/PlayerbotV2/Bot/Battleground/BgTargetPick.h index ec1f31de3f..5338b7c9f4 100644 --- a/src/modules/PlayerbotV2/Bot/Battleground/BgTargetPick.h +++ b/src/modules/PlayerbotV2/Bot/Battleground/BgTargetPick.h @@ -1,6 +1,6 @@ // BG victim validity: a battleground bot never keeps a target it cannot hurt, and re-picks when an enemy player is close. // -// Karrz, WSG 2026-10-09: a Horde priest stood next to him swinging at nothing and ignored him. The idle engage rule only ran with an empty +// the owner, WSG 2026-10-09: a Horde priest stood next to him swinging at nothing and ignored him. The idle engage rule only ran with an empty // victim, and the in-combat BG switches only react to a carrier, a peel or a healer, so a victim that was gone, dead, untargetable or // not fighting back held the bot for good. Pure function over the snapshot's unit lists (templated, so tests/game/BgTargetPick.cpp can // run it on plain structs). Used by State_Idle and State_InCombat; both log the result as [bg_target]. @@ -30,7 +30,7 @@ namespace Playerbot::BgTargetPick } } - // How far a battleground bot looks for an enemy to fight (Karrz, WSG 2026-10-09: "make the radius where they attack people bigger"). + // How far a battleground bot looks for an enemy to fight (playtest, WSG 2026-10-09: "make the radius where they attack people bigger"). // The snapshot scans this far in a battleground (BotSnapshotBuilder), the engage and re-pick rules read it. constexpr float kBgEngageRange = 55.0f; constexpr float kIdleMobPlayerRange = 15.0f; // an enemy player this close beats a creature that is not attacking us diff --git a/src/modules/PlayerbotV2/Bot/Battleground/BgTeamCoordinator.cpp b/src/modules/PlayerbotV2/Bot/Battleground/BgTeamCoordinator.cpp index 8669dc7c15..5fcc7e397d 100644 --- a/src/modules/PlayerbotV2/Bot/Battleground/BgTeamCoordinator.cpp +++ b/src/modules/PlayerbotV2/Bot/Battleground/BgTeamCoordinator.cpp @@ -364,7 +364,7 @@ void BgTeamCoordinator::PlanCtf(TeamPlanContext& ctx) ctx.members[pick].assigned = true; } } - // -- WSG zone roles (Karrz 2026-10-08: not just a straight lane between the bases) --------------------------------------------- + // -- WSG zone roles (playtest 2026-10-08: not just a straight lane between the bases) --------------------------------------------- // Free fighters (after carrier, runner, escorts, hunters) are split over the map: mid skirmishers at the tunnel junction, a // camp at the ENEMY graveyard (they take the fight to the respawn point and make the return trip hard), and a guard at our OWN // graveyard. The slot a bot gets rotates every few minutes of match time, so the same bot does not hold one spot all game and no @@ -494,7 +494,7 @@ void BgTeamCoordinator::PlanNodeRace(TeamPlanContext& ctx) [](Demand const& a, Demand const& b) { return a.emergency > b.emergency; }); - // AV open-field brawl share (Karrz 2026-10-08), decided here so it can shrink the garrison budget and + // AV open-field brawl share (playtest 2026-10-08), decided here so it can shrink the garrison budget and // used further down to send the bots (see "AV open-field brawl"). Old Classic AV: a big part of each side // farmed kills in the valley while the rest took towers, so games lasted. The share is a random 25-55% // per match and team (hash of instance + team: stable for the whole match, no RNG state) and follows the @@ -506,7 +506,7 @@ void BgTeamCoordinator::PlanNodeRace(TeamPlanContext& ctx) for (auto const& m : ctx.members) if (m.alive && !m.is_carrier) ++alive_total; uint64 const mid_key = (uint64(ctx.instance_id) << 2) | uint64(ctx.team); - // Karrz 2026-10-11: the valley brawl is OFF. Bots piled up idle in AV, and he asked to drop the fight in the middle in case it was the + // playtest 2026-10-11: the valley brawl is OFF. Bots piled up idle in AV, and he asked to drop the fight in the middle in case it was the // cause; AV bots now play the way ike3 / mod-playerbots do (towers, graveyards, captain, general, mines). Flip to true to bring it back. constexpr bool kAvValleyBrawl = false; if (kAvValleyBrawl && ctx.type_id == 1 && PosSet(ctx.fight_x, ctx.fight_y) && !all_in && !ctx.endgame_unconditional && @@ -729,7 +729,7 @@ void BgTeamCoordinator::PlanNodeRace(TeamPlanContext& ctx) 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); - // -- AV open-field brawl (Karrz 2026-10-08) ------------------------------- + // -- 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. @@ -856,7 +856,7 @@ void BgTeamCoordinator::PlanNodeRace(TeamPlanContext& ctx) { best_cost = cost; tx = n.x; ty = n.y; tz = n.z; } } // Node-race split (WSG-free maps with 4+ nodes, i.e. AB/Gilneas style): the old single concentrated squad sent the whole - // team Stables -> Blacksmith across the river and nobody took the Lumber Mill, Farm or Mine (Karrz, AB test 2026-10-08). + // team Stables -> Blacksmith across the river and nobody took the Lumber Mill, Farm or Mine (playtest, AB test 2026-10-08). // Spread the free attackers over up to four takeable nodes in proportion to the node weight (script priority + 2, so the // Blacksmith pivot gets the biggest group), keep about one in eight unordered as roamers. Held nodes keep their garrison // from the defense pass above; a node that is lost or attacked turns up in the next plan and is re-assigned (the sticky @@ -885,7 +885,7 @@ void BgTeamCoordinator::PlanNodeRace(TeamPlanContext& ctx) } if (split_cands.size() >= 2 && ctx.nodes.size() >= 4) { - // Variety (Karrz: no two matches alike): the focus rotates. Every 4 minutes of match time, per match, each candidate's + // Variety (the owner: no two matches alike): the focus rotates. Every 4 minutes of match time, per match, each candidate's // cost and weight are nudged by a hash of its position, so the main squad is not always on the same pivot node and a // second node regularly gets a real group. uint32 const var_epoch = ctx.in_progress_ms / (4u * 60u * 1000u) + ctx.instance_id * 7u; @@ -932,10 +932,10 @@ void BgTeamCoordinator::PlanNodeRace(TeamPlanContext& ctx) ctx.members[pick].assigned = true; } } - // Road skirmishers (Karrz: fights on the roads between the nodes, not only at the banners). About a fifth of the bots still + // Road skirmishers (the owner: fights on the roads between the nodes, not only at the banners). About a fifth of the bots still // free go to a point midway between two of the contested nodes, picked by a hash that rotates every 3 minutes, and fight // whatever they meet on the way and there. Their orders are AttackNode at the road point; the 40 y engage does the rest. - if (split_cands.size() >= 2 && !av) // AV: no road skirmishers (ike3 / mod-playerbots have none; Karrz 2026-10-11) + if (split_cands.size() >= 2 && !av) // AV: no road skirmishers (ike3 / mod-playerbots have none; playtest 2026-10-11) { int left = 0; for (auto const& m : ctx.members) @@ -1092,7 +1092,7 @@ void BgTeamCoordinator::Update(uint32 now_ms) return; last_plan_ms_ = now_ms; - if (!sConfigMgr->GetBoolDefault("Playerbot.Bg.Coordinator.Enable", true)) + if (!sConfigMgr->GetBoolDefault("Playerbot.Bg.Coordinator.Enable", true, true)) { if (!orders_.empty()) orders_.clear(); last_dump_ = "coordinator disabled (Playerbot.Bg.Coordinator.Enable=0)"; @@ -1112,6 +1112,8 @@ void BgTeamCoordinator::Update(uint32 now_ms) Services::Registry().for_each([&](BotId id, BotRegistryEntry const& e) { if (!e.ai) return; + // A bot stopped with "bgrun stop" (or not armed) never runs an order (BgDispatch returns at once), so it gets no quota slot. + if (!e.ai->bg_active()) return; Player* p = ObjectAccessor::FindConnectedPlayer( ObjectGuid::Create(id)); if (!p) return; @@ -1152,13 +1154,13 @@ void BgTeamCoordinator::Update(uint32 now_ms) const uint16 resolved_type_id = ref->bg.current_type_id; // Advice is computed HERE, on the world thread, from the immutable // reference snapshot. Do NOT borrow a member BotAI's BgAdviceCache: - // that cache is OWNED BY THE AI WORKER THREAD — BgDispatch + // that cache is OWNED BY THE bot logic WORKER THREAD — BgDispatch // reassigns its heap vectors every ≤2s, so reading it here could // iterate freed buffers (use-after-free; adversarial review // 2026-06-10). Scripts are stateless and registered once at boot; // GetAdvice on a snapshot view is thread-safe and costs one call // per (instance, team) per 750ms plan — negligible next to the - // per-bot per-tick churn the AI-side cache exists to avoid. + // per-bot per-tick churn the bot logic-side cache exists to avoid. BattlegroundAdvice const adv = Services::Battlegrounds().GetAdvice(BotSnapshotView(*ref)); diff --git a/src/modules/PlayerbotV2/Bot/Battleground/BgTeamCoordinator.h b/src/modules/PlayerbotV2/Bot/Battleground/BgTeamCoordinator.h index d1ef0a9f99..1a3b629899 100644 --- a/src/modules/PlayerbotV2/Bot/Battleground/BgTeamCoordinator.h +++ b/src/modules/PlayerbotV2/Bot/Battleground/BgTeamCoordinator.h @@ -7,7 +7,7 @@ // rebalancing. This service computes ONE plan per (battleground instance, // team) on the WORLD THREAD and publishes per-bot orders; the snapshot // builder copies each bot's order into its snapshot (BotSnapshot::BgState:: -// BgOrder) and the AI executes it, falling back to the legacy per-bot role +// BgOrder) and the bot logic executes it, falling back to the legacy per-bot role // logic whenever no order is present — graceful degradation by design. // // Threading: Update() is the only WRITER of orders_ and runs on the WORLD @@ -17,7 +17,7 @@ // writer and the readers are temporally disjoint — orders_ is never mutated // during the build phase, and concurrent reads of a non-mutating unordered_map // are well-defined. Move Update() into the parallel phase and this needs a -// shared_mutex. The AI workers only ever see orders through their snapshots. +// shared_mutex. The bot workers only ever see orders through their snapshots. // // Inputs (all already maintained elsewhere — this class adds no harvest): // * Roster: live Player objects of V2 bots in the BG (registry walk). @@ -26,7 +26,7 @@ // snapshot build, including the per-node player-pressure counts). // * Static script data: BattlegroundScriptMgr::GetAdvice computed HERE // on the world thread from that same immutable snapshot. Never read a -// BotAI's BgAdviceCache from this class — it is owned by the AI worker +// BotAI's BgAdviceCache from this class — it is owned by the bot worker // thread, which reassigns its heap vectors every ≤2s (use-after-free; // adversarial review 2026-06-10). // diff --git a/src/modules/PlayerbotV2/Bot/Battleground/BgWaypointData.inc b/src/modules/PlayerbotV2/Bot/Battleground/BgWaypointData.inc index 98f2241ebd..4014b7cfe6 100644 --- a/src/modules/PlayerbotV2/Bot/Battleground/BgWaypointData.inc +++ b/src/modules/PlayerbotV2/Bot/Battleground/BgWaypointData.inc @@ -1,4 +1,4 @@ -// Generated from ike3 BattleGroundTactics (the ike3-based playerbot code raid10-revamp, vmangos hand-recorded paths). Do not edit by hand. +// Generated from ike3 BattleGroundTactics (Karrz1/wow-1.12 raid10-revamp, vmangos hand-recorded paths). Do not edit by hand. // Each path: name, first/last = junctions; points are x,y,z on the classic maps (AV 30, WSG 489, AB 529). inline const RoutePath kPathsWsg[] = { { "HordeFlagRoom_to_HordeGraveyard", {{933.331f,1433.72f,345.536f}, {944.859f,1423.05f,345.437f}, {966.691f,1422.53f,345.223f}, {979.588f,1422.84f,345.46f}, {997.806f,1422.52f,344.623f}, {1008.53f,1417.02f,343.206f}, {1016.42f,1402.33f,341.352f}, {1029.14f,1387.49f,340.836f}} }, @@ -87,7 +87,7 @@ inline const RoutePath kPathsAv[] = { { "Alliance_Base_Bunker_Third_Crossroad_to_Alliance_Base_Flag", {{648.593f,-33.8686f,47.1592f}, {640.404f,-32.0183f,46.2328f}} }, { "Alliance_Base_Bunker_Third_Crossroad_to_Alliance_Base_Vanndar_Stormpike", {{648.593f,-33.8686f,47.1592f}, {664.325f,-28.0147f,50.6198f}, {690.605f,-20.6846f,50.6198f}, {696.331f,-27.5629f,50.6198f}, {699.006f,-31.7397f,50.6198f}, {704.958f,-34.5659f,50.6198f}, {717.709f,-16.6861f,50.1354f}} }, { "Stormpike_Crossroad_to_Stormpike_Flag", {{638.087f,-287.84f,30.1471f}, {667.173f,-295.225f,30.29f}} }, - // Added 2026-10-09 from the ike3-based playerbot code BattleBotWaypoints.cpp (it was missing from the first import) + // Added 2026-10-09 from Karrz1/wow-1.12 raid10-revamp bcc8b9f BattleBotWaypoints.cpp (it was missing from the first import) { "Stormpike_Graveyard_to_Stormpike_Flag", {{676.0f,-374.0f,29.782f}, {665.922f,-347.777f,29.493f}, {667.173f,-295.225f,30.29f}} }, { "Stormpike_Crossroad_to_Irontooth_Mine_Entrance", {{638.087f,-287.84f,30.1471f}, {665.708f,-283.570f,29.187f}, {685.958f,-274.358f,23.618f}, {701.911f,-271.504f,28.409f}, {715.155f,-276.190f,36.108f}, {727.653f,-288.440f,43.433f}, {742.260f,-305.039f,51.649f}, {753.219f,-314.030f,56.008f}} }, { "Irontooth_Mine_Entrance_to_Irontooth_Mine_Boss", {{753.219f,-314.030f,56.008f}, {772.425f,-310.607f,54.891f}, {789.429f,-308.122f,54.883f}, {803.955f,-324.896f,52.259f}, {820.946f,-341.782f,49.227f}, {831.603f,-351.672f,47.041f}, {836.755f,-369.026f,48.233f}, {827.558f,-386.418f,47.731f}, {827.334f,-407.188f,48.293f}, {842.166f,-413.971f,47.832f}, {861.532f,-422.612f,51.013f}, {870.832f,-436.016f,51.130f}, {881.273f,-442.002f,54.664f}} }, diff --git a/src/modules/PlayerbotV2/Bot/Battleground/BgWaypointRoutes.h b/src/modules/PlayerbotV2/Bot/Battleground/BgWaypointRoutes.h index c061886983..21e6e97873 100644 --- a/src/modules/PlayerbotV2/Bot/Battleground/BgWaypointRoutes.h +++ b/src/modules/PlayerbotV2/Bot/Battleground/BgWaypointRoutes.h @@ -29,7 +29,7 @@ struct RoutePath { char const* name; std::vector pts; }; #include "BgWaypointData.inc" // A path that may only be walked first point to last: a jump / roof drop, and the start-room, cave and graveyard exits that the -// original bots never walk backwards (vPaths_NoReverseAllowed, the ike3-based playerbot code BattleBotWaypoints.cpp). +// original bots never walk backwards (vPaths_NoReverseAllowed, Karrz1/wow-1.12 raid10-revamp bcc8b9f BattleBotWaypoints.cpp). // Horde_Cave_to_Tower_Point_Crossroad is in their list but is NOT one-way here: our router also uses it backwards, it is the only // link by which a bot from the Alliance half reaches the Horde base (the test below fails when it is made one-way). inline bool IsOneWayPath(std::string_view nm) @@ -275,7 +275,7 @@ inline bool NextWaypoint(uint16_t bg_type, float bx, float by, float bz, float t // A lane is one of the ways across the field a bot may take: either one of the recorded graph paths above (a graveyard-ridge jump // into the enemy flag room, the second recording of the mid line), or a chain of hand-recorded waypoints (BgWsgLanes.inc: the // tunnel, the graveyard ridge and the north ramp out of the own base, the mid field, then the enemy tunnel or ramp). The route to a -// goal is forced through the lane, so a team spreads over the whole map instead of every bot walking the one shortest line (Karrz, +// goal is forced through the lane, so a team spreads over the whole map instead of every bot walking the one shortest line (the owner, // WSG 2026-10-09: "just straight out the tunnel and straight back up the tunnel"). Nothing here is invented: every coordinate comes // from recorded data. // drop: the leg from the previous point to this one is a drop off a ledge (the previous point is the ledge, this one the landing). @@ -307,7 +307,7 @@ inline std::vector const& LanesFor(uint16_t bg_type, bool east, bool flank // A fight below the graveyard ridge: the ridge lane whose drop the bot stands above, when the bot is on the ridge within `reach` y of the ledge // and has not dropped yet (it stands more than 8 y above the landing). Out: the ridge lane (of the two, `selector` picks) and the landing. -// The caller sends the bot over the ledge, instead of the random lane, when enemies are at the landing (Karrz, WSG 2026-10-09: the whole +// The caller sends the bot over the ledge, instead of the random lane, when enemies are at the landing (playtest, WSG 2026-10-09: the whole // rez wave ran the long way round the back while the enemy was fighting below the cliff). inline Lane const* RidgeDropAbove(std::vector const& lanes, uint32_t selector, float bx, float by, float bz, float reach, LanePoint* landing = nullptr) { diff --git a/src/modules/PlayerbotV2/Bot/Battleground/BgWsgLanes.inc b/src/modules/PlayerbotV2/Bot/Battleground/BgWsgLanes.inc index 2bba20826f..2c3d0f5ea9 100644 --- a/src/modules/PlayerbotV2/Bot/Battleground/BgWsgLanes.inc +++ b/src/modules/PlayerbotV2/Bot/Battleground/BgWsgLanes.inc @@ -1,6 +1,6 @@ // Warsong Gulch lanes, hand-recorded waypoint chains. // -// Source: the ike3-based playerbot code branch raid10-revamp, commit bcc8b9fe70c42a8fa5d50fa83a472da9e9d19546, src/game/PlayerBots/playerbot/ +// Source: Karrz1/wow-1.12 branch raid10-revamp, commit bcc8b9fe70c42a8fa5d50fa83a472da9e9d19546, src/game/PlayerBots/playerbot/ // strategy/actions/BattleGroundTactics.cpp, BGTactics::wsgPaths() ("old wsg waypoints", the ike3 / cmangos playerbots lineage, GPL). // Map 489 coordinates, the same map as BgWaypointData.inc. Only the points are taken; the choice among them is ours (per-bot lanes). // Checked offline against the recorded graph (BgWaypointData.inc): all but the two south mid-field points lie within ~20 y of a @@ -62,8 +62,8 @@ inline std::vector BuildWsgLanes(bool east, bool flank_only) // (their own code marks that lane "BUGGED"; ours does not path it, so the NOPATH that made it unusable cannot occur). char const* const names[6] = { "tunnel>tunnel", "tunnel>ramp", "ridge>tunnel", "ridge>ramp", "ramp>tunnel", "ramp>ramp" }; bool const flank[6] = { false, false, true, true, true, true }; // a base tunnel is not a flank - // Weights (Karrz, WSG 2026-10-09 playtest: bots ran the long way round the ramp where players drop off the ridge): the ridge - // lanes carry the drop and are the players' shortcut, so they weigh most. Karrz, same playtest: "still running up and down the middle": + // Weights (playtest, WSG 2026-10-09 playtest: bots ran the long way round the ramp where players drop off the ridge): the ridge + // lanes carry the drop and are the players' shortcut, so they weigh most. The owner, same playtest: "still running up and down the middle": // the tunnel lanes and the two plain middle lines are the middle, about a quarter of the picks now; the ramp-out lanes end on the side of // the field their ramp leads to and no longer cut back through the middle (eastbound they used to go on to the middle point). int const weight[6] = { 6, 6, 34, 34, 10, 10 }; diff --git a/src/modules/PlayerbotV2/Bot/Battleground/Scripts/AlteracValleyScript.cpp b/src/modules/PlayerbotV2/Bot/Battleground/Scripts/AlteracValleyScript.cpp index 696cac2d7b..7daad0b60d 100644 --- a/src/modules/PlayerbotV2/Bot/Battleground/Scripts/AlteracValleyScript.cpp +++ b/src/modules/PlayerbotV2/Bot/Battleground/Scripts/AlteracValleyScript.cpp @@ -5,7 +5,7 @@ // Vandar Stormpike ends the BG. // // Authoritative data from V1 (production-tested): -// src/modules/Playerbot/AI/Coordination/Battleground/Scripts/Siege/ +// src/modules/Playerbot/bot logic/Coordination/Battleground/Scripts/Siege/ // AlteracValleyData.h:35 (REINF_GAIN_PER_CAPTAIN), :128-130 (Vandar), // :134-136 (Drek'Thar), :149-164 (Captains), :191+ (towers), // :451-457 (spawns). @@ -85,7 +85,7 @@ public: a.endgame_target_z = 98.5f; a.endgame_creature_entry = 11946; // DREKTHAR_ENTRY } - // Captain staging (ike3 BattleGroundTacticsAV.cpp, the ike3-based playerbot code, named locations + // 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. if (s.is_horde()) diff --git a/src/modules/PlayerbotV2/Bot/Battleground/Scripts/ArathiBasinScript.cpp b/src/modules/PlayerbotV2/Bot/Battleground/Scripts/ArathiBasinScript.cpp index 40839acd44..a864b7ea18 100644 --- a/src/modules/PlayerbotV2/Bot/Battleground/Scripts/ArathiBasinScript.cpp +++ b/src/modules/PlayerbotV2/Bot/Battleground/Scripts/ArathiBasinScript.cpp @@ -4,7 +4,7 @@ // 4-cap: defend 4, soft-attack the 5th (typically the contested mid). // // Authoritative coords + strategic weights from V1 -// src/modules/Playerbot/AI/Coordination/Battleground/Scripts/Domination/ +// src/modules/Playerbot/bot logic/Coordination/Battleground/Scripts/Domination/ // ArathiBasinData.h:54-81 (positions), :110-121 (GetNodeStrategicValue), // :159, :168 (faction spawns). diff --git a/src/modules/PlayerbotV2/Bot/Battleground/Scripts/AshranScript.cpp b/src/modules/PlayerbotV2/Bot/Battleground/Scripts/AshranScript.cpp index 710acfc461..c69cd6ba8f 100644 --- a/src/modules/PlayerbotV2/Bot/Battleground/Scripts/AshranScript.cpp +++ b/src/modules/PlayerbotV2/Bot/Battleground/Scripts/AshranScript.cpp @@ -3,7 +3,7 @@ // Glory control points + 8 side events + faction commanders. // // Authoritative coords from V1 -// src/modules/Playerbot/AI/Coordination/Battleground/Scripts/Epic/ +// src/modules/Playerbot/bot logic/Coordination/Battleground/Scripts/Epic/ // AshranData.h:118 (event interval), :138-149 (Volrath/Tremblade), // :156-160 (control points), :171-173 (faction spawns). // diff --git a/src/modules/PlayerbotV2/Bot/Battleground/Scripts/BattleForGilneasScript.cpp b/src/modules/PlayerbotV2/Bot/Battleground/Scripts/BattleForGilneasScript.cpp index 92cf049c18..8c1e20a3da 100644 --- a/src/modules/PlayerbotV2/Bot/Battleground/Scripts/BattleForGilneasScript.cpp +++ b/src/modules/PlayerbotV2/Bot/Battleground/Scripts/BattleForGilneasScript.cpp @@ -3,7 +3,7 @@ // Capture 2+ of 3 (Lighthouse / Waterworks / Mines) to score. // // Authoritative coords + weights from V1 -// src/modules/Playerbot/AI/Coordination/Battleground/Scripts/Domination/ +// src/modules/Playerbot/bot logic/Coordination/Battleground/Scripts/Domination/ // BattleForGilneasData.h:52-67 (positions), :92-101 (GetNodeStrategicValue), // :137, :146 (faction spawns). diff --git a/src/modules/PlayerbotV2/Bot/Battleground/Scripts/DeepwindGorgeScript.cpp b/src/modules/PlayerbotV2/Bot/Battleground/Scripts/DeepwindGorgeScript.cpp index 20a185cd17..a77ac66f17 100644 --- a/src/modules/PlayerbotV2/Bot/Battleground/Scripts/DeepwindGorgeScript.cpp +++ b/src/modules/PlayerbotV2/Bot/Battleground/Scripts/DeepwindGorgeScript.cpp @@ -8,7 +8,7 @@ // DeepwindGorgeData.h:159-374). // // Map id: 1105 (NOT 998 — 998 is Temple of Kotmogu, common confusion). -// V1 coords: src/modules/Playerbot/AI/Coordination/Battleground/Scripts/ +// V1 coords: src/modules/Playerbot/bot logic/Coordination/Battleground/Scripts/ // Domination/DeepwindGorgeData.h:50-63 (nodes), :475-483 (faction spawns). #include "../BattlegroundScript.h" diff --git a/src/modules/PlayerbotV2/Bot/Battleground/Scripts/EyeOfTheStormScript.cpp b/src/modules/PlayerbotV2/Bot/Battleground/Scripts/EyeOfTheStormScript.cpp index 86ccafa261..f304df41b9 100644 --- a/src/modules/PlayerbotV2/Bot/Battleground/Scripts/EyeOfTheStormScript.cpp +++ b/src/modules/PlayerbotV2/Bot/Battleground/Scripts/EyeOfTheStormScript.cpp @@ -11,7 +11,7 @@ // :92 — BG_OBJECT_FLAG2_EY_ENTRY = 208977 (NEW_FLAG type, ie 36) // :101 — AREATRIGGER_CAPTURE_FLAG = 33 (capture mechanic) // V1 coords for towers + center flag: -// src/modules/Playerbot/AI/Coordination/Battleground/Scripts/Domination/ +// src/modules/Playerbot/bot logic/Coordination/Battleground/Scripts/Domination/ // EyeOfTheStormData.h:64-91 #include "../BattlegroundScript.h" diff --git a/src/modules/PlayerbotV2/Bot/Battleground/Scripts/IsleOfConquestScript.cpp b/src/modules/PlayerbotV2/Bot/Battleground/Scripts/IsleOfConquestScript.cpp index 8f8b0ddf7e..2b3bfd01fe 100644 --- a/src/modules/PlayerbotV2/Bot/Battleground/Scripts/IsleOfConquestScript.cpp +++ b/src/modules/PlayerbotV2/Bot/Battleground/Scripts/IsleOfConquestScript.cpp @@ -14,7 +14,7 @@ // :182-191, :221-227 — node banners + keep gate entries // :386-395 — OnUnitKilled (win-condition) // V1 author-attested coords (NOT TC-validated; DB-driven on TC): -// src/modules/Playerbot/AI/Coordination/Battleground/Scripts/Siege/ +// src/modules/Playerbot/bot logic/Coordination/Battleground/Scripts/Siege/ // IsleOfConquestData.h:128-134 (nodes), :354-364 (Generals). #include "../BattlegroundScript.h" diff --git a/src/modules/PlayerbotV2/Bot/Battleground/Scripts/StrandOfAncientsScript.cpp b/src/modules/PlayerbotV2/Bot/Battleground/Scripts/StrandOfAncientsScript.cpp index 0cd6d33a36..33b44ce047 100644 --- a/src/modules/PlayerbotV2/Bot/Battleground/Scripts/StrandOfAncientsScript.cpp +++ b/src/modules/PlayerbotV2/Bot/Battleground/Scripts/StrandOfAncientsScript.cpp @@ -16,7 +16,7 @@ // :166 — BG_SA_ATTACKER_TEAM worldstate // :250-251 — Demolisher + Antipersonnel Turret entries // V1 author-attested coords (not TC-validated; DB-driven): -// src/modules/Playerbot/AI/Coordination/Battleground/Scripts/Siege/ +// src/modules/Playerbot/bot logic/Coordination/Battleground/Scripts/Siege/ // StrandOfTheAncientsData.h:186-188 (relic), :238-245 (gates), // :251-257 (graveyards), :263-268 (demolisher mount points). diff --git a/src/modules/PlayerbotV2/Bot/Battleground/Scripts/TwinPeaksScript.cpp b/src/modules/PlayerbotV2/Bot/Battleground/Scripts/TwinPeaksScript.cpp index d5caac3e2a..0e3170ae08 100644 --- a/src/modules/PlayerbotV2/Bot/Battleground/Scripts/TwinPeaksScript.cpp +++ b/src/modules/PlayerbotV2/Bot/Battleground/Scripts/TwinPeaksScript.cpp @@ -7,7 +7,7 @@ // src/server/game/Miscellaneous/SharedDefines.h:3195-3196 // NEW_FLAG=36, NEW_FLAG_DROP=37 // V1 coords: -// src/modules/Playerbot/AI/Coordination/Battleground/Scripts/CTF/ +// src/modules/Playerbot/bot logic/Coordination/Battleground/Scripts/CTF/ // TwinPeaksData.h:80-89 (flag spawns), :165, :187 (defender posts) #include "../BattlegroundScript.h" diff --git a/src/modules/PlayerbotV2/Bot/Battleground/Scripts/WarsongGulchScript.cpp b/src/modules/PlayerbotV2/Bot/Battleground/Scripts/WarsongGulchScript.cpp index 5cc11a34ff..5fa7248f11 100644 --- a/src/modules/PlayerbotV2/Bot/Battleground/Scripts/WarsongGulchScript.cpp +++ b/src/modules/PlayerbotV2/Bot/Battleground/Scripts/WarsongGulchScript.cpp @@ -10,7 +10,7 @@ // :3195 — GAMEOBJECT_TYPE_NEW_FLAG = 36 // :3196 — GAMEOBJECT_TYPE_NEW_FLAG_DROP = 37 // V1 coords: -// src/modules/Playerbot/AI/Coordination/Battleground/Scripts/CTF/ +// src/modules/Playerbot/bot logic/Coordination/Battleground/Scripts/CTF/ // WarsongGulchData.h:38-47 (flag spawns), :123-149 (defender posts) #include "../BattlegroundScript.h" @@ -40,8 +40,8 @@ public: a.role_by_slot = { BgRole::FlagCarrier, BgRole::FCEscort, - BgRole::Defender, // flag room guards: two, each at its own post beside the stand (not on it: Karrz, two bots camped on - BgRole::Defender, // the stand). Ported from the ike3 bots' two defender posts (the ike3-based playerbot code) + BgRole::Defender, // flag room guards: two, each at its own post beside the stand (not on it: the owner, two bots camped on + BgRole::Defender, // the stand). Ported from the ike3 bots' two defender posts (Karrz1/wow-1.12 raid10-revamp bcc8b9f) BgRole::Roamer, BgRole::Roamer, BgRole::Attacker, diff --git a/src/modules/PlayerbotV2/Bot/BotAI.cpp b/src/modules/PlayerbotV2/Bot/BotAI.cpp index 98d0b7999c..47e36497c6 100644 --- a/src/modules/PlayerbotV2/Bot/BotAI.cpp +++ b/src/modules/PlayerbotV2/Bot/BotAI.cpp @@ -1,4 +1,5 @@ #include "BotAI.h" +#include "TownLife.h" #include "BotSnapshotView.h" #include "TradeRule.h" #include "BotTrade.h" @@ -34,7 +35,9 @@ void BotAI::set_rally_point(uint32 map, float x, float y, float z) void BotAI::note_cast_outcome(uint32 code, uint32 spell_id, uint32 now_ms, std::string const& bot_name) { - if (code == uint32(SPELL_FAILED_NO_AMMO)) + // A warrior with no thrown weapon equipped fails Throw with EQUIPPED_ITEM, not NO_AMMO: the same "no ranged opener". + if (code == uint32(SPELL_FAILED_NO_AMMO) || + (code == uint32(SPELL_FAILED_EQUIPPED_ITEM) && (spell_id == 2764 || spell_id == 2480 || spell_id == 7918 || spell_id == 7919))) last_no_ammo_ms_.store(now_ms ? now_ms : 1u, std::memory_order_relaxed); // A refused cast started no global cooldown: release the emitter's GCD hold (note_gcd_started). // NOT_READY keeps it: the GCD (or a cooldown) the stale snapshot missed is what refused it. @@ -301,7 +304,7 @@ void BotAI::tick(BotSnapshotView snapshot, } // Pet taunt autocast. Growl / Torment / Suffering on autocast rip mobs - // off the group's tank (Karrz's raid change: pet Growl off in groups). + // off the group's tank (the owner's raid change: pet Growl off in groups). // Off while the bot is grouped with another member who tanks (role Tank, // or the coordinator's main tank) and the bot is not a tank itself; the // single-target taunts back on when solo or when the bot tanks (an area @@ -406,7 +409,7 @@ void BotAI::tick(BotSnapshotView snapshot, // to detect zones the bot has "settled into" (cumulative >30min) and // rebind hearth there. Skip while in BG/dungeon (those are transient // and shouldn't accumulate hearth-relevant time). Delta is bounded - // by the AI tick interval (typically 200-1000ms). + // by the bot tick interval (typically 200-1000ms). if (snapshot.is_alive() && !snapshot.in_battleground() && !snapshot.is_in_dungeon()) { const uint32 now_ms = snapshot.published_at_ms(); @@ -497,7 +500,7 @@ void BotAI::tick(BotSnapshotView snapshot, // The owner's release order is kept: one that reached the bot between // its real death and this edge (a snapshot or more later) must still // release it. Only an order from before this death is dropped: it was - // left by a revival this AI never observed. The death instant is + // left by a revival this bot logic never observed. The death instant is // Module::OnDeath's stamp; if that is missing or plainly from an // older death, fall back to this edge minus a small slack. if (const uint32 order = release_order_ms()) @@ -635,9 +638,11 @@ void BotAI::tick(BotSnapshotView snapshot, void BotAI::update_dungeon_autopilot_hold(BotSnapshotView s, GroupSnapshotView g) { - // A companion's party that is not a raid group, inside a raid map (MC 2026-10-06: Karrz's + // An owner Stay / Hold: the dungeon autopilot (converge, rejoin, advance, pull) walks nobody who was told to stay. + owner_hold_ = holding_position(s.published_at_ms()); + // A companion's party that is not a raid group, inside a raid map (MC 2026-10-06: the owner's // 6-man party), never runs the raid autopilot: the tank advanced and pulled Molten Giants - // the party could not survive while Karrz was still forming the raid. It follows its owner + // the party could not survive while the owner was still forming the raid. It follows its owner // (State_InGroup) and defends (InCombat); converting to a raid group re-arms the run. // Playerbot.Behavior.OwnerFollowHold off: no hold, and a follow order left over from before // the switch was turned off is released. @@ -657,7 +662,7 @@ void BotAI::update_dungeon_autopilot_hold(BotSnapshotView s, GroupSnapshotView g : (g.exists() && g.is_raid() ? "the group is a raid group" : "left the raid map / owner's group")); } - // The owner engaging a mob himself no longer releases his follow order or opens an autopilot window (Karrz, Deadmines + // The owner engaging a mob himself no longer releases his follow order or opens an autopilot window (playtest, Deadmines // 2026-10-10: the tank ran off and pulled everything in the first room once he attacked anything). A suspended bot helps on // the owner's target and defends the group (State_InGroup assist chain, the tank included); only an order (attack / pull / // resume / aggressive, release_owner_lead) hands the pulls back to the autopilot. @@ -737,7 +742,7 @@ void BotAI::dispatch_layers(BotSnapshotView s, GroupSnapshotView g, // get auto-accepted so owner sparring works without a manual whisper; // strangers get auto-declined to avoid being trolled into PvP. The // friend flag is resolved on the world thread by the snapshot builder - // (Player::GetSocial::HasFriend + group/guild membership), so the AI + // (Player::GetSocial::HasFriend + group/guild membership), so the bot logic // worker just inspects a single bool here. if (s.has_duel_request()) { @@ -761,6 +766,9 @@ void BotAI::dispatch_layers(BotSnapshotView s, GroupSnapshotView g, } else if (s.duel_initiator_is_friend()) em.duel_accept(); + else if (!s.duel_initiator_is_real() && !s.has_owner_character() && !s.in_group() + && V2::TownLife::PactHolds(s.bot_id(), s.duel_initiator().GetCounter(), s.published_at_ms())) + em.duel_accept(); // another world bot asked for this duel (idle:town_duel) else if (polite) { // Answer a moment after the request (0-2 s, per bot), once; the verdict is stable for a minute so a diff --git a/src/modules/PlayerbotV2/Bot/BotAI.h b/src/modules/PlayerbotV2/Bot/BotAI.h index 423b6b2d79..05258745b5 100644 --- a/src/modules/PlayerbotV2/Bot/BotAI.h +++ b/src/modules/PlayerbotV2/Bot/BotAI.h @@ -1,12 +1,13 @@ // BotAI - The top-level state machine. CONTRACTS.md §2.6. // -// Constructed once per bot. Lives on the AI worker thread that runs the bot. +// Constructed once per bot. Lives on the bot worker thread that runs the bot. // Pure: tick(snapshot, group, events, emit) — no global mutation, no I/O. #pragma once #include "ClassicBuffLedger.h" #include "IdleWatch.h" +#include "WalkOrder.h" #include "BotTypes.h" #include "BotSnapshot.h" // CurrencyEntry — cached_currencies_ member needs full type #include "Battleground/BgTactics.h" // BgTactics::StallWatch (bg_stall_ member) @@ -40,7 +41,7 @@ class BotAI public: BotAI(BotId id, BotPersonality personality, BotRng rng); - // Called by AI worker. Pure: snapshot in → intents out. + // Called by bot worker. Pure: snapshot in → intents out. // BotEventInbox parameter was removed 2026-05-21 — see PlayerbotV2.cpp // OnDamageTaken comment for rationale. void tick(BotSnapshotView snapshot, @@ -204,7 +205,7 @@ public: // Owner's "release" order (BotCommandParser::OrderRelease, world thread): // GameTime ms it reached this dead bot, 0 = none. State_Dead releases at - // once and runs back. NOT cleared on the AI's death edge (an order can + // once and runs back. NOT cleared on the bot logic's death edge (an order can // arrive between the real death and the snapshot showing it); cleared on // revival (clear_release_order_before) and dropped as stale on the death // edge when it predates this death (died_at_ms). @@ -265,6 +266,10 @@ public: // Last summon to the entrance (companion of an owner inside; see // idle:rejoin_group_instance), paced so a refused port is not spammed. uint32 summon_ms = 0; + // Direct ports into the owner's instance tried since the rejoin began; after kDirectTries refusals the bot goes by the + // entrance trigger again. + uint32 direct_tries = 0; + static constexpr uint32 kDirectTries = 3; }; RejoinRun& rejoin_run() { return rejoin_run_; } RejoinRun const& rejoin_run() const { return rejoin_run_; } @@ -628,6 +633,10 @@ public: // marks and DPS wait for it. A Pull never sets it. 0 = never. void note_owner_attack(uint32 now_ms) { owner_attack_ms_ = now_ms ? now_ms : 1u; } uint32 owner_attack_ms() const { return owner_attack_ms_; } + // The owner's Pull / Pull back reached this (non-pulling) bot: in a party the DPS then wait for his Attack, at most 6 s from the + // tank's first hit (EvaluateThreatHold). 0 = never. + void note_owner_pull(uint32 now_ms) { owner_pull_ms_ = now_ms ? now_ms : 1u; } + uint32 owner_pull_ms() const { return owner_pull_ms_; } void set_last_owner_name(std::string name) { last_owner_name_ = std::move(name); } std::string const& last_owner_name() const { return last_owner_name_; } @@ -640,7 +649,7 @@ public: // Owner spacing preset (BotCommandParser "spacing tight|close|spread", "tight", "close", "spread out"): // yards between neighbours in the follow formation (State_InGroup) and, as formation_spacing_scale() // (yards / 4, Close = 1), the raid ranged / pre-pull arc spacing in State_Idle. Written by the chat - // handlers (world thread), read by the AI worker. + // handlers (world thread), read by the bot worker. FormationSpacing formation_spacing() const { return FormationSpacing(formation_spacing_.load(std::memory_order_relaxed)); } // Choosing a preset drops any numeric spacing; a "distance " order sets exact yards (memory only, like the @@ -735,7 +744,7 @@ public: // Owner "follow" order: the owner leads, so the bot follows its owner and defends, and the // dungeon autopilot stands down until the owner says attack / assist / tank / pull / resume / // run (or follow stop), or engages a mob himself. Unlike the 30s manual-mode window it lasts - // until released. Written by the chat handlers (world thread), read and released by the AI + // until released. Written by the chat handlers (world thread), read and released by the bot logic // worker. Returns true when the value changed (callers log [owner_order] on change). bool owner_follow_order() const { return owner_follow_order_.load(std::memory_order_relaxed); } bool set_owner_follow_order(bool on) @@ -744,7 +753,7 @@ public: // follow the owner and defend. Recomputed each tick (update_dungeon_autopilot_hold). bool raid_map_party_hold() const { return raid_map_party_hold_; } bool dungeon_autopilot_suspended() const - { return owner_follow_order() || owner_passive() || fallback_active() || pull_back_active() || raid_map_party_hold_ || human_lead_hold_; } + { return owner_follow_order() || owner_passive() || fallback_active() || pull_back_active() || raid_map_party_hold_ || human_lead_hold_ || owner_hold_; } // Owner stance (panel Aggressive / Passive toggle, whisper and group words "passive" / "aggressive"), kept per bot until // changed (the group order reaches every bot of the group): // Auto - passive when a human leads the group inside an instance, otherwise the bot's own autonomy; @@ -752,7 +761,7 @@ public: // target); it defends itself and the group (a mob already on a member) and fights on the owner's // attack / pull order (release_owner_lead opens a window); // Aggressive - besides the group's own fights it attacks any hostile within kAggressiveRadiusYd of the owner. - // Written by the chat handlers (world thread), read by the AI worker. + // Written by the chat handlers (world thread), read by the bot worker. enum class OwnerStance : uint8_t { Auto = 0, Passive = 1, Aggressive = 2 }; static constexpr float kAggressiveRadiusYd = 10.0f; // Aggressive: hostiles this close to the owner are attacked OwnerStance owner_stance() const { return OwnerStance(owner_stance_.load(std::memory_order_relaxed)); } @@ -764,6 +773,8 @@ public: return std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()).count() < owner_order_until_.load(std::memory_order_relaxed); } + // "passive" ends the window an Attack / Pull opened, so the stance holds at once and not after 15 s. + void close_owner_order_window() { owner_order_until_.store(0, std::memory_order_relaxed); } // Starts no fight on its own right now (stance Passive, or Auto in an instance led by a human), outside an order window. bool passive_now(bool human_led_instance) const { @@ -781,7 +792,7 @@ public: // (tanks in front, ranged and healers on an arc behind) and fight only what follows. Suspends // the autopilot like the follow order, anchored at the rally instead of the owner; released // by the same orders. The plan is written by the chat handler (world thread) and read by the - // AI worker (States::FallbackTick), hence the mutex. + // bot worker (States::FallbackTick), hence the mutex. struct FallbackPlan { bool active = false; @@ -818,12 +829,13 @@ public: // Every order opens the 15 s order window (owner_order_window_open: a passive bot assists the owner's / the group's targets). // autopilot_window = true (resume / run / "go") also opens the human-lead release window, so the dungeon autopilot runs on its // own for 15 s (BotAI::update_dungeon_autopilot_hold). Attack / pull / aggressive pass false: they fight what the owner points - // at and never pull the next pack (Karrz, Deadmines 2026-10-10: Aggressive resumed the autopilot, the tank ran about). + // at and never pull the next pack (playtest, Deadmines 2026-10-10: Aggressive resumed the autopilot, the tank ran about). bool release_owner_lead(bool autopilot_window = true) { const bool a = set_owner_follow_order(false); const bool b = end_fallback(); const bool c = end_pull_back(); + end_owner_use(); int64_t const now_ms = std::chrono::duration_cast( std::chrono::steady_clock::now().time_since_epoch()).count(); owner_order_until_.store(now_ms + 15000, std::memory_order_relaxed); @@ -835,7 +847,7 @@ public: // Owner "pull back" order (BotCommandParser OrderPullBack, main tank only): open on the target // from range, run back to the return point (the rally point, else where the tank stood) with // the mob following, and tank it there (States::PullBackTick). Suspends the autopilot like a - // fallback. Written by the chat handler (world thread), advanced by the AI worker; same mutex. + // fallback. Written by the chat handler (world thread), advanced by the bot worker; same mutex. enum class PullBackPhase : uint8 { Pull = 0, Retreat = 1, Hold = 2 }; struct PullBackPlan { @@ -902,9 +914,35 @@ public: RallyPoint rally_point() const { std::lock_guard lk(fallback_mtx_); return rally_point_; } void set_rally_point(uint32 map, float x, float y, float z); // BotAI.cpp (stamps GameTime) + // Owner "use " (BotCommandParser): walk to this game object and use it once (an altar, brazier, lever, orb); the + // bot then stays put, so a ritual's channel is not broken by a follow. Written by the chat handler (world thread), run by + // the bot worker (idle:owner_use); same mutex as the fallback. Ends on use, death, map change or after 30 s. + struct OwnerUseOrder { bool set = false; uint32 map = 0; ObjectGuid go; float x = 0.f, y = 0.f, z = 0.f; uint32 set_ms = 0; }; + bool owner_use_active() const { return owner_use_active_.load(std::memory_order_relaxed); } + OwnerUseOrder owner_use_order() const + { std::lock_guard lk(fallback_mtx_); return owner_use_; } + void start_owner_use(OwnerUseOrder o) + { + std::lock_guard lk(fallback_mtx_); + o.set = true; + owner_use_ = o; + owner_use_active_.store(true, std::memory_order_relaxed); + } + bool end_owner_use() + { + std::lock_guard lk(fallback_mtx_); + owner_use_ = {}; + return owner_use_active_.exchange(false, std::memory_order_relaxed); + } // The ranged opener (Throw / Shoot) failed NO_AMMO: remembered so a pull back does not pick it again (world thread - // writes via note_cast_outcome, AI worker reads). + // writes via note_cast_outcome, bot worker reads). uint32 last_no_ammo_ms() const { return last_no_ammo_ms_.load(std::memory_order_relaxed); } + // The [move_to_refused] diagnostics are limited to one a `gap_ms` per bot. + bool dedup_log_due(uint32 now_ms, uint32 gap_ms) + { + uint32 last = move_refused_log_ms_.load(std::memory_order_relaxed); + return now_ms - last > gap_ms && move_refused_log_ms_.compare_exchange_strong(last, now_ms); + } // Battleground-run mode (mirrors DungeonRunMode for BG context). // Active when bot is in a battleground; drives objective-aware @@ -1144,11 +1182,19 @@ public: // Last server-time (ms) the bot idle-rotated to "look at" a nearby NPC // (idle:look_at_npc). Drives a jittered 30-60s cadence so bots aren't // eerily still in a hub. 0 = primed (fire on first eligible tick). + // Next time (module ms; 0 = not seeded yet) the rule in throttle slot `slot` may be looked at for this bot. IdleRuleRegistry::tick. + uint32& gate_next_ms(size_t slot, size_t total) + { + if (gate_next_ms_.size() < total) gate_next_ms_.resize(total, 0u); + return gate_next_ms_[slot]; + } uint32 last_look_around_ms() const { return last_look_around_ms_; } void set_last_look_around_ms(uint32 v) { last_look_around_ms_ = v; } // Last server-time (ms) the bot struck a sustained "state" emote // (idle:ambient_state_emote — dance/sit/sleep while idle in a hub). // Low-frequency; 0 = primed. + uint32 last_town_show_ms() const { return last_town_show_ms_; } // last duel / campfire (Bot/TownLife.h) + void set_last_town_show_ms(uint32 v) { last_town_show_ms_ = v; } uint32 last_ambient_state_emote_ms() const { return last_ambient_state_emote_ms_; } void set_last_ambient_state_emote_ms(uint32 v) { last_ambient_state_emote_ms_ = v; } uint32 last_guild_babble_ms() const { return last_guild_babble_ms_; } @@ -1515,7 +1561,7 @@ public: // and the backoff is continuously re-armed => a PERMANENT FREEZE over a // perfectly valid navmesh (live: bot 164465, dst=(1848.1,1530.5,123.4), // "[move_lock] reason=path_fail_backoff" repeating forever, headless - // probes proved the mesh itself was fine). This ring lets the AI side + // probes proved the mesh itself was fine). This ring lets the bot logic side // remember "that spot was just refused by the API" so the NEXT tick's // candidate selection (dungeon step-emit sites, route-follower crumb // scan) can skip it and try a DIFFERENT candidate instead of @@ -2114,11 +2160,17 @@ public: uint32 last_quest_diag_ms() const { return last_quest_diag_ms_; } void set_last_quest_diag_ms(uint32 ms) { last_quest_diag_ms_ = ms; } + // Throttle stamp for the `[quest_accept_stall]` diagnostic in QuestRules: an offer in sight that idle:quest_accept + // did not act on. One line per bot per 30s. + uint32 last_accept_stall_diag_ms() const { return last_accept_stall_diag_ms_; } + void set_last_accept_stall_diag_ms(uint32 ms) { last_accept_stall_diag_ms_ = ms; } + // Throttle stamp for the `[wander_reason]` diagnostic in // State_Idle. One log line per bot per 60s — wander fires 1000+/min // fleet-wide so anything tighter would drown the log. 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::BgTactics::StallWatch& bg_stall() { return bg_stall_; } void set_last_wander_diag_ms(uint32 ms) { last_wander_diag_ms_ = ms; } @@ -2665,7 +2717,7 @@ public: // Coordinator-order movement: re-assert the move every 3s // while marching on the ordered target (combat knockbacks, // CC and local melee shuffles interrupt the path), without - // spamming a move_to every AI tick. + // spamming a move_to every bot tick. return 3u * 1000u; case ActionKind::RaidIcon: // One icon-set attempt per target per 10s — a refused set @@ -2869,7 +2921,7 @@ public: // --- RPG / idle life (Bot/States/Rules/RpgRules.cpp, port of ike3 "rpg") --- // A world bot in a town strolls from NPC to NPC (visit = approach, then // linger), and now and then travels to a city or auction house (trip). - // Owned and read only by the rpg rules on this bot's AI tick. + // Owned and read only by the rpg rules on this bot's bot tick. struct RpgState { // Current NPC visit. The target is a TownNpcIndex spawn; its live guid @@ -3107,7 +3159,7 @@ private: public: uint32 rule_fire_seq() const { return rule_fire_seq_; } - // [dps_idle] tracker (AI worker; State_InCombat's end-of-tick probe). + // [dps_idle] tracker (bot worker; State_InCombat's end-of-tick probe). // idle_since = first tick of the current no-action streak (0 = acting), // logged = when the streak was last reported (throttle, 10 s per bot). struct CombatIdleState @@ -3182,9 +3234,12 @@ private: FallbackPlan fallback_plan_; RallyPoint rally_point_; std::atomic last_no_ammo_ms_{0}; + std::atomic move_refused_log_ms_{0}; std::atomic fallback_active_{false}; PullBackPlan pull_back_plan_; std::atomic pull_back_active_{false}; + OwnerUseOrder owner_use_; + std::atomic owner_use_active_{false}; mutable std::mutex manual_travel_mtx_; // guards manual_travel_ (parser writes / builder reads+clears, cross-thread) bool travel_force_graph_ = false; uint64 poi_prog_key_ = 0; @@ -3303,6 +3358,7 @@ private: uint32 manual_mode_until_ms_ = 0; uint32 last_owner_command_ms_ = 0; uint32 owner_attack_ms_ = 0; + uint32 owner_pull_ms_ = 0; std::string last_owner_name_; uint8 formation_slot_ = 0; FormationType formation_type_ = FormationType::Free; @@ -3316,6 +3372,7 @@ private: std::atomic owner_follow_order_{false}; std::atomic owner_stance_{0}; // OwnerStance bool raid_map_party_hold_ = false; + bool owner_hold_ = false; // an owner Stay / Hold is on: the autopilot walks nobody (update_dungeon_autopilot_hold) bool human_lead_hold_ = false; // see human_lead_hold() uint32 human_seen_ms_ = 0; // last tick a leading human was in range (0 = never) std::atomic human_release_until_{0}; // steady-clock ms: autopilot allowed until then @@ -3359,14 +3416,14 @@ private: uint32_t last_built_ms = 0u; BattlegroundAdvice cached; }; - // OWNED BY THE AI WORKER THREAD. BgDispatch reassigns `cached`'s heap + // OWNED BY THE bot logic WORKER THREAD. BgDispatch reassigns `cached`'s heap // vectors on every cache miss (≤2s apart), so no other thread may read // this struct — world-thread consumers use published_bg_advice_ below. BgAdviceCache bg_advice_cache_; public: // World-thread-readable advice mirror (adversarial review 2026-06-10: // the snapshot builder's bg_role block read bg_advice_cache_.cached - // directly from the world thread while the AI worker reassigned its + // directly from the world thread while the bot worker reassigned its // vectors — use-after-free window every cache rebuild). On each // rebuild the worker publishes an IMMUTABLE copy through a C++20 // atomic (same pattern as SnapshotPublisher slots); @@ -3468,7 +3525,9 @@ private: bool verbose_logging_ = false; uint32 last_ambient_emote_ms_ = 0; uint32 last_look_around_ms_ = 0; + std::vector gate_next_ms_; // per-bot throttle table of the idle rules uint32 last_ambient_state_emote_ms_ = 0; + uint32 last_town_show_ms_ = 0; uint32 last_guild_babble_ms_ = 0; uint32 last_yell_lfg_ms_ = 0; // Per-bot throttle on the snapshot builder's 500y hub-radius scan. @@ -3477,7 +3536,7 @@ private: // Cell::VisitAllObjects every world frame (50Hz) — 10-25K wide-scans/sec. // 1s cadence is plenty: hub quest-givers don't move, and the smaller // 40y scan still captures the immediate neighborhood every tick. - // Builder reads/writes; AI worker doesn't touch this field. + // Builder reads/writes; bot worker doesn't touch this field. uint32 last_hub_scan_ms_ = 0; // Same throttle pattern for the 200y extended gather-node scan // (perf audit #3 — capital-clustered gatherers also fire this @@ -3982,11 +4041,13 @@ private: // BotSnapshotBuilder. Single uint32 since the diagnostic logs once // per bot per 5s regardless of quest_id. uint32 last_quest_diag_ms_ = 0; + uint32 last_accept_stall_diag_ms_ = 0; uint32 last_moving_ms_ = 0; // for idle:ambient_sit sustained-idle gate // Throttle for the `[wander_reason]` diagnostic — 1 line per bot // per 60s. Wander fires ~1000+/min fleet-wide. uint32 last_wander_diag_ms_ = 0; ::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) // Cached corpse → graveyard distance. Recomputing every snapshot tick // walks `WorldSafeLocsEntry` against `sConditionMgr` for every nearby @@ -4018,15 +4079,15 @@ public: // Optimistic per-spell emit cooldown. Modern WoW puts most abilities on // a server-side cooldown the moment they cast — but the snapshot that // reflects that cooldown is published on the next world tick (~200 ms - // later). Between emit and snapshot reflection, the AI worker may tick + // later). Between emit and snapshot reflection, the bot worker may tick // again on the SAME stale snapshot and re-emit the same cast intent; // the API rejects with SPELL_FAILED_NOT_READY (91) and the rule fires // again next tick. Result: 4-5 redundant emits per real cooldown cycle, // each producing a Server.log rejection line. // - // Lock the spell out on the AI side for ~1.5 s after emit (covers the + // Lock the spell out on the bot logic side for ~1.5 s after emit (covers the // GCD plus snapshot publish lag). The next snapshot's real cooldown - // table catches up before the lockout expires, so the AI never sees + // table catches up before the lockout expires, so the bot logic never sees // a "ready" window the server disagrees with. static constexpr uint32 kCastEmitLockoutMs = 1500u; // Longer back-off used when the API REJECTED a cast (vs the short @@ -4061,6 +4122,21 @@ public: gcd_emit_until_ms_.store(now_ms + len, std::memory_order_relaxed); } void clear_gcd_started() { gcd_emit_until_ms_.store(0, std::memory_order_relaxed); } + // A caster at its mana-item threshold whose potion is held back by the cast in flight: no new hard cast starts until the item + // is used or the window ends (a healer chaining Greater Heals never has an idle tick, so it never drank). + // A break that ended without an item going out is not started again for 12 s, so an item the core keeps refusing cannot starve the + // caster of casts. + void note_mana_break(uint32 now_ms) + { + uint32 const until = mana_break_until_ms_.load(std::memory_order_relaxed); + if (now_ms < until) + return; // already running; the window is not extended + if (until && now_ms - until < 12000u) + return; + mana_break_until_ms_.store(now_ms + 4000u, std::memory_order_relaxed); + } + void clear_mana_break() { mana_break_until_ms_.store(0, std::memory_order_relaxed); } + bool mana_break_active(uint32 now_ms) const { return now_ms < mana_break_until_ms_.load(std::memory_order_relaxed); } bool gcd_recently_started(uint32 now_ms) const { return now_ms < gcd_emit_until_ms_.load(std::memory_order_relaxed); } // The core said NOT_READY: lock the spell out for what its cooldown / the GCD still has // to run (min 250 ms), instead of re-emitting it every tick against a stale snapshot. @@ -4256,7 +4332,7 @@ public: // Tier 4 (> 60 s): hearth home (or release-corpse fallback) // Reset whenever distance drops by >= 5 y (real progress) or the goal // changes (different target). Stays within BotAI for thread-safety: - // builder reads/writes from the world thread; AI worker reads to drive + // builder reads/writes from the world thread; bot worker reads to drive // the rule. Eventually-consistent — a stale read just delays escalation // by one tick. struct StuckTracker @@ -4375,8 +4451,8 @@ public: // non-walk bridge (areatrigger teleport / ship / portal)?" decision, keyed // by the hub goal so the builder runs the FindRoute probe only once per goal // change (not per tick). POD (uint64+bool) written + read ONLY on the world - // thread (the snapshot builder) — never touched by the AI worker, so unlike - // the travel_plan_ vector it needs no cross-thread synchronization. The AI + // thread (the snapshot builder) — never touched by the bot worker, so unlike + // the travel_plan_ vector it needs no cross-thread synchronization. The bot logic // worker sees the result purely through the snapshot's objective_is_relocation // flag the builder sets from it. uint64 reloc_bridge_goal_key() const { return reloc_bridge_goal_; } @@ -4436,7 +4512,7 @@ public: // bad route. The anchor-wedge cooldown returns "wedged" every tick for 30s, // so this timestamp gates the skip to once per few seconds — letting the bot // start moving toward the skipped-to leg before another skip is considered. - // AI-worker-only (like travel_plan_): no cross-thread synchronization. + // bot-worker-only (like travel_plan_): no cross-thread synchronization. uint32 last_leg_skip_ms() const { return last_leg_skip_ms_; } void set_last_leg_skip_ms(uint32 ms) { last_leg_skip_ms_ = ms; } // One-shot escalation: the next driveTravelPlanTo for ANY goal routes @@ -4448,7 +4524,7 @@ public: // The reloc-bridge probe's VALIDATED route legs (source attaches checked // against the live navmesh). World-thread only, like the reloc_bridge // decision POD: written by the probe, read by the builder when copying - // into the snapshot's bridge_route. The AI worker consumes them via the + // into the snapshot's bridge_route. The bot worker consumes them via the // snapshot — it must NOT recompute the route itself (its FindRoute can't // validate attaches off the world thread, so it would get the // unexecutable euclidean route a wedged bot can't follow). @@ -4561,7 +4637,7 @@ public: // The adjustment is a percentage applied ABOVE the hard quality floor in // AuctionRules, so the floor still clamps the discount — the loop can never // dump an item below its band floor regardless of how many times it - // expires. Single-writer (AI worker thread), same model as the other + // expires. Single-writer (bot worker thread), same model as the other // per-bot retry caches below. struct SellPriceMemo { @@ -4621,7 +4697,7 @@ public: // detects "distance to the leader isn't dropping" so the rule can fall // back from follow to an explicit, navmesh-validated move_to toward the // leader (which then engages the walk-first unstick ladder). No teleport. - // Single-writer (AI worker) — same threading model as the wedge maps. + // Single-writer (bot worker) — same threading model as the wedge maps. struct FollowProgress { uint64 anchor = 0; float last_dist = 0.f; uint32 stale_ticks = 0; uint32 last_repath_ms = 0; }; // Throttle for the validated follow-repath move_to. The follow rule fires // every tick; without this a follower whose leader is unreachable would @@ -4711,6 +4787,8 @@ private: std::unordered_map cast_emit_until_ms_; // End of the global cooldown the last emitted GCD-bound cast starts (note_gcd_started). std::atomic gcd_emit_until_ms_{0}; + // End of the mana break (note_mana_break). + std::atomic mana_break_until_ms_{0}; // Per-item-entry equip retry cooldown — see kEquipTryLockoutMs above. std::unordered_map equip_try_until_ms_; // Per-hub blacklist for unproductive arrivals — see kHubTriedLockoutMs. @@ -5177,7 +5255,7 @@ public: // anchor blacklisting in the snapshot requires the Builder to know // which anchor failed, but path_blocked_count() is global per-bot // (path failures from any rule increment it). By tracking baselines - // per rule name on the AI side, each rule independently sees "from + // per rule name on the bot logic side, each rule independently sees "from // the moment I started firing, has the global block count grown by // K?" — a clean wedge detector that doesn't need anchor identity. // diff --git a/src/modules/PlayerbotV2/Bot/BotActivityTier.h b/src/modules/PlayerbotV2/Bot/BotActivityTier.h index 3b9c45b728..7866cf874d 100644 --- a/src/modules/PlayerbotV2/Bot/BotActivityTier.h +++ b/src/modules/PlayerbotV2/Bot/BotActivityTier.h @@ -10,7 +10,7 @@ struct BotSnapshot; // forward — full type in BotSnapshot.h // Tick frequency table — lower = more reactive, more CPU. On a 5950X // with 33% baseline CPU and ~1100 of 1237 bots sitting in Idle tier, -// halving Idle roughly doubles aggregate AI work and lifts quality +// halving Idle roughly doubles aggregate bot logic work and lifts quality // across the fleet (faster BG pivots, smoother movement, snappier // social timing). Active also bumped a notch since travelling/questing // bots want quick re-evaluation. Combat unchanged — already at 10 Hz @@ -20,7 +20,7 @@ struct BotSnapshot; // forward — full type in BotSnapshot.h // population: a solo, open-world bot that is merely travelling or // questing (moving OR has an objective) but is NOT human-facing // (unowned, ungrouped-with-real, no real player nearby), NOT path-blocked, -// and NOT casting. Such a bot's movement spline is server-side; the AI +// and NOT casting. Such a bot's movement spline is server-side; the bot logic // only needs to issue the next waypoint a touch less often, so it // tolerates 300 ms. This roughly halves snapshot-build cost for the // questing fleet that previously pinned every moving/objective bot to @@ -37,7 +37,7 @@ struct BotSnapshot; // forward — full type in BotSnapshot.h // tail of idle city/inn bots). 2000 ms is deliberately capped at the // AiWorkerPool staleness guard's 1000 ms ceiling × 2 — a parked bot's // snapshot can be up to one Parked period old, which only ever causes -// the worker to *skip* that AI tick (stale_skip), never to act on bad +// the worker to *skip* that bot tick (stale_skip), never to act on bad // data or repath; the next scheduler pass re-builds fresh. See // AiWorkerPool.cpp staleness guard. Any wake event (combat / owner // control / movement / a real player arriving) demotes the bot back to diff --git a/src/modules/PlayerbotV2/Bot/BotChatReactor.cpp b/src/modules/PlayerbotV2/Bot/BotChatReactor.cpp index a9630f41cd..46dad8e437 100644 --- a/src/modules/PlayerbotV2/Bot/BotChatReactor.cpp +++ b/src/modules/PlayerbotV2/Bot/BotChatReactor.cpp @@ -745,7 +745,11 @@ void BotChatReactor::React(Player* sender, Group* group, std::string const& msg) else /* go */ { mai->set_chat_pause_until_ms(0); - mai->release_owner_lead(); // DungeonFlow: "go" opens the human-lead release window + // DungeonFlow: only "go" opens the human-lead release window. "pull" / "pulling" / "engage" are the owner's own + // orders (their handlers decide what the autopilot may do); opening the window for every bot on them let the + // tank autopilot pull on and run back and the casters wander (Deadmines 2026-10-14). + if (ContainsWord(norm, "go")) + mai->release_owner_lead(); } } } diff --git a/src/modules/PlayerbotV2/Bot/BotCommandParser.cpp b/src/modules/PlayerbotV2/Bot/BotCommandParser.cpp index 45b1b225bb..cdd54ae0d3 100644 --- a/src/modules/PlayerbotV2/Bot/BotCommandParser.cpp +++ b/src/modules/PlayerbotV2/Bot/BotCommandParser.cpp @@ -275,6 +275,7 @@ void SetOwnerFollowOrder(Player const* bot, bool on, bool autopilot_window = tru { ai->end_fallback(); ai->end_pull_back(); + ai->end_owner_use(); ai->set_owner_follow_order(true); } else @@ -447,6 +448,7 @@ void OrderFallback(Player* sender, Player* bot) ai->exit_manual(); ai->set_owner_follow_order(false); ai->end_pull_back(); + ai->end_owner_use(); ai->start_fallback(plan); ai->set_last_owner_name(sender->GetName()); TC_LOG_INFO("playerbot.v2", @@ -477,7 +479,7 @@ bool RaidPullGateAllows(Player const* bot_c, Unit const* target) return vp && BotCommandParser::BotRole(const_cast(vp)) == Role::Tank; } Group const* grp = bot->GetGroup(); - // A tank with an owner icon assignment pulls its own mob whatever the main-tank flag says (Karrz, MC Garr 2026-10-08: with a + // A tank with an owner icon assignment pulls its own mob whatever the main-tank flag says (playtest, MC Garr 2026-10-08: with a // flagged main tank only that tank went, and the adds killed it). if (grp && BotCommandParser::BotRole(bot) == Role::Tank) for (auto const& [tank_low, marker] : Services::Owners().TankMarks(grp->GetGUID().GetCounter())) @@ -503,11 +505,13 @@ bool RaidPullGateAllows(Player const* bot_c, Unit const* target) if (tank_low == bot->GetGUID().GetCounter()) return true; return false; } + // Only a LIVE lower-guid tank holds the pull: the group coordinator picks the first live tank, so a dead one must not + // leave the raid without a puller after a wipe. for (Group::MemberSlot const& slot : grp->GetMemberSlots()) { if (slot.guid == bot->GetGUID() || slot.guid.GetCounter() >= bot->GetGUID().GetCounter()) continue; Player* other = ObjectAccessor::FindConnectedPlayer(slot.guid); - if (other && Services::Registry().has(BotId(slot.guid.GetCounter())) && + if (other && other->IsAlive() && Services::Registry().has(BotId(slot.guid.GetCounter())) && BotCommandParser::BotRole(other) == Role::Tank) return false; } @@ -542,6 +546,47 @@ Unit* RtiPullTarget(Player* bot) return nullptr; } +// "attack" with nothing selected: the mob the group is already fighting. The owner's own victim first, then a group member's victim +// (the tank's before the others'), then the hostile nearest the owner that is attacking any group member. nullptr when the group fights nothing. +Unit* AttackFallbackTarget(Player* sender, Player* bot) +{ + auto usable = [&](Unit* u) -> Unit* + { + return u && !u->IsPlayer() && u->IsAlive() && bot->IsValidAttackTarget(u) ? u : nullptr; + }; + if (Unit* u = usable(sender->GetVictim())) + return u; + Group* grp = bot->GetGroup(); + if (!grp) + return nullptr; + Unit* tank_victim = nullptr; + Unit* other_victim = nullptr; + Unit* nearest = nullptr; + float nearest_d = 0.f; + for (GroupReference const& itr : grp->GetMembers()) + { + Player* m = itr.GetSource(); + if (!m || !m->IsAlive() || m->GetMapId() != bot->GetMapId()) + continue; + if (Unit* v = usable(m->GetVictim())) + { + if (!tank_victim && m != sender && Services::Registry().has(m->GetGUID().GetCounter()) && BotCommandParser::BotRole(m) == Role::Tank) + tank_victim = v; + else if (!other_victim) + other_victim = v; + } + for (Unit* at : m->getAttackers()) + if (Unit* u = usable(at)) + { + float const d = sender->GetDistance(u); + if (!nearest || d < nearest_d) { nearest = u; nearest_d = d; } + } + } + if (tank_victim) return tank_victim; + if (other_victim) return other_victim; + return nearest; +} + // Owner "pull back" (also "pullback", "pull and back"): the main tank opens on the owner's selected mob (else the // skull / own rti mark) from range, runs back to the rally point (set with "rally here") or, with none, to where it // stood, and tanks the mob there (BotAI::PullBackPlan, States::PullBackTick). Tank role only; in a raid map the @@ -554,7 +599,7 @@ bool OrderPullBack(Player* sender, Player* bot) BotAI* ai = Services::Registry().ai(bot->GetGUID().GetCounter()); if (!ai || !bot->IsAlive() || bot->GetMapId() != sender->GetMapId()) return true; - // Owner-assigned tank icons (assign , Karrz 2026-10-08): with any in the group only those tanks pull, each + // Owner-assigned tank icons (assign , playtest 2026-10-08): with any in the group only those tanks pull, each // on its own icon's mob; the other tanks, and everyone else, stand by until a mob is brought back. bool assigned_pull = false; Unit* target = nullptr; @@ -1574,7 +1619,8 @@ bool OwnerWordOrder(Player* sender, Player* bot, std::string const& n) return refuse("you are in a battleground"); if (bm && bm->Instanceable() && bot->GetMapId() != sender->GetMapId()) return refuse("I am inside an instance - walk out first"); - if (sm && sm->Instanceable() && bot->GetMapId() != sender->GetMapId()) + // Into the owner's instance only as a member of the owner's group (the door checks and their log are API::teleport_to's). + if (sm && sm->Instanceable() && bot->GetMapId() != sender->GetMapId() && !(bot->GetGroup() && bot->GetGroup() == sender->GetGroup())) return refuse("you are inside an instance - invite me and walk in with the group"); Push(bot, TeleportToIntent{sender->GetMapId(), sender->GetPositionX(), sender->GetPositionY(), sender->GetPositionZ(), sender->GetOrientation()}); @@ -1596,6 +1642,10 @@ bool OwnerWordOrder(Player* sender, Player* bot, std::string const& n) { if (ai->set_owner_stance(BotAI::OwnerStance::Passive)) TC_LOG_INFO("playerbot.v2", "[owner_order] {} <- {}: passive (starts no fights until attack / pull)", me, sender->GetName()); + // Passive after an Attack / Pull ends that order's 15 s window and its Engage at once; a Stay / Hold is kept. + ai->close_owner_order_window(); + if (ai->owner_command() == BotAI::OwnerCommand::Engage) + ai->exit_manual(); ai->set_last_owner_name(sender->GetName()); } say(me + ": passive, defending only until you say attack or pull"); @@ -1608,8 +1658,12 @@ bool OwnerWordOrder(Player* sender, Player* bot, std::string const& n) if (ai->set_owner_stance(BotAI::OwnerStance::Aggressive)) TC_LOG_INFO("playerbot.v2", "[owner_order] {} <- {}: aggressive (attacks hostiles within {:.0f} yd of the owner)", me, sender->GetName(), BotAI::kAggressiveRadiusYd); - ai->exit_manual(); - ai->release_owner_lead(false); + // A Stay / Hold stays: aggressive changes the stance only (it used to cancel the Stay silently). + if (!ai->holding_position(GameTime::GetGameTimeMS())) + { + ai->exit_manual(); + ai->release_owner_lead(false); + } } say(fmt::format("{}: aggressive, attacking anything hostile within {:.0f} yards of you", me, BotAI::kAggressiveRadiusYd)); return true; @@ -1620,6 +1674,9 @@ bool OwnerWordOrder(Player* sender, Player* bot, std::string const& n) if (BotAI* ai = Services::Registry().ai(bid)) { ai->enter_manual(BotAI::OwnerCommand::Hold, ObjectGuid::Empty, GameTime::GetGameTimeMS(), BotAI::kHoldPositionTtlMs); + // Defensive replaces an Aggressive stance (a Passive one already fights only what attacks); the Hold does the rest. + if (ai->owner_stance() == BotAI::OwnerStance::Aggressive) + ai->set_owner_stance(BotAI::OwnerStance::Auto); ai->set_last_owner_name(sender->GetName()); } say(me + ": defensive, holding here and fighting only what attacks"); @@ -1643,7 +1700,7 @@ bool OwnerWordOrder(Player* sender, Player* bot, std::string const& n) } // anonymous -// Owner's "release" order (ike3's ReleaseSpiritAction / Karrz's "release"), +// Owner's "release" order (ike3's ReleaseSpiritAction / the owner's "release"), // also taken when the owner releases their own spirit (Module:: // OnSpiritReleased): a dead bot releases its spirit now and runs back to its // corpse as a ghost, or, dying inside a dungeon / raid, revives at the @@ -1660,7 +1717,7 @@ bool BotCommandParser::OrderRelease(Player const* sender, Player const* bot, cha BotAI* ai = Services::Registry().ai(bot->GetGUID().GetCounter()); if (!ai) return false; - // An order latched before this death (a revival the AI never saw cleared + // An order latched before this death (a revival the bot logic never saw cleared // nothing) is stale: replace it rather than keep it. uint32 const held = ai->release_order_ms(); if (held == 0 || (ai->died_at_ms() != 0 && held < ai->died_at_ms())) @@ -1679,6 +1736,9 @@ void BotCommandParser::ReleaseOwnerFollowOrder(Player const* sender, Player cons { if (!bot) return; BotAI* ai = Services::Registry().ai(bot->GetGUID().GetCounter()); + // A Pull / Pull back the bot does not carry out itself: it waits for the owner's Attack (party, EvaluateThreatHold). + if (ai && why && std::string_view(why).find("pull") != std::string_view::npos) + ai->note_owner_pull(GameTime::GetGameTimeMS()); if (ai && ai->release_owner_lead(false)) TC_LOG_INFO("playerbot.v2", "[owner_order] {} from {}: follow / fallback order released ({})", bot->GetName(), sender ? sender->GetName() : std::string("?"), why ? why : "?"); @@ -2587,6 +2647,8 @@ bool BotCommandParser::DispatchSingleImpl(Player* sender, Player* bot, std::stri if (Services::Config().behavior_owner_follow_hold()) { ai->end_fallback(); + ai->end_pull_back(); + ai->end_owner_use(); ai->set_owner_follow_order(true); } } @@ -2601,7 +2663,7 @@ bool BotCommandParser::DispatchSingleImpl(Player* sender, Player* bot, std::stri // relocation objective; the full travel // pipeline (walk/taxi/portal/ship/areatrigger) // drives the bot there organically — never a - // teleport. The bot resumes normal AI on + // teleport. The bot resumes normal bot logic on // arrival (it's a journey, not a parking). float a1 = 0.f, a2 = 0.f, a3 = 0.f; const int n_args = std::sscanf(parsed.tail.c_str(), "%f %f %f", &a1, &a2, &a3); @@ -2997,6 +3059,11 @@ bool BotCommandParser::DispatchSingleImpl(Player* sender, Player* bot, std::stri { ai->enter_manual(BotAI::OwnerCommand::Stay, ObjectGuid::Empty, GameTime::GetGameTimeMS(), BotAI::kHoldPositionTtlMs); + // Stay and Follow replace each other, and Stay ends a pull back / fallback that would walk the bot away. + ai->set_owner_follow_order(false); + ai->end_fallback(); + ai->end_pull_back(); + ai->end_owner_use(); ai->set_last_owner_name(sender->GetName()); } return true; @@ -3011,6 +3078,10 @@ bool BotCommandParser::DispatchSingleImpl(Player* sender, Player* bot, std::stri { ai->enter_manual(BotAI::OwnerCommand::Hold, ObjectGuid::Empty, GameTime::GetGameTimeMS(), BotAI::kHoldPositionTtlMs); + ai->set_owner_follow_order(false); + ai->end_fallback(); + ai->end_pull_back(); + ai->end_owner_use(); ai->set_last_owner_name(sender->GetName()); } Push(bot, WhisperIntent{sender->GetName(), "Hold: holding position."}); @@ -3023,7 +3094,9 @@ bool BotCommandParser::DispatchSingleImpl(Player* sender, Player* bot, std::stri if (BotAI* ai = Services::Registry().ai(bot->GetGUID().GetCounter())) { ai->exit_manual(); - ai->release_owner_lead(); + // Resume ends the Stay / Follow / fallback / pull back; it does not start the dungeon autopilot (that is "go" or + // "run": the 15 s autopilot window made a resumed tank walk off to the next pack on its own). + ai->release_owner_lead(false); Push(bot, WhisperIntent{sender->GetName(), "Resume: autonomous."}); } return true; @@ -3095,7 +3168,7 @@ bool BotCommandParser::DispatchSingleImpl(Player* sender, Player* bot, std::stri BotAI* ai = Services::Registry().ai(bot->GetGUID().GetCounter()); if (!ai) { - Push(bot, WhisperIntent{sender->GetName(), "Bgrun: no AI."}); + Push(bot, WhisperIntent{sender->GetName(), "Bgrun: no bot logic."}); return true; } if (parsed.tail == "pause") @@ -3177,7 +3250,7 @@ bool BotCommandParser::DispatchSingleImpl(Player* sender, Player* bot, std::stri { // Diagnostic: walk all group bots and report their intent-queue depth. // Useful for spotting stalled bots — if the queue keeps growing, the - // AI worker can't keep up with the executor or vice versa. + // bot worker can't keep up with the executor or vice versa. const uint32 reported = ForEachGroupBot(bot, [&](Player const* p) { IntentQueue* q = Services::Registry().intents(p->GetGUID().GetCounter()); @@ -3281,76 +3354,12 @@ bool BotCommandParser::DispatchSingleImpl(Player* sender, Player* bot, std::stri } if (cmd == "pull") { - // Coordinated raid pull. Owner says "pull" with the next pull's - // target selected. Bot pauses N seconds (default 3) before engaging, - // matching the WoW pull-timer macro convention. Owners can call /pull - // 5 for a longer countdown when the puller needs to walk to position. - // When the bot is a raid leader/assistant, also broadcasts a raid - // warning ("Pulling in Ns!") so the rest of the raid sees the - // standard pull-timer cue. - // "pull rti" (Playerbot.Behavior.Ike3Commands): the mob carrying the bot's own rti symbol, not the selection. - bool const by_rti = parsed.tail.rfind("rti", 0) == 0 && Services::Config().behavior_ike3_commands(); - Unit const* target = by_rti ? RtiPullTarget(bot) : sender->GetSelectedUnit(); - if (!target || target->GetGUID() == bot->GetGUID()) - { - Push(bot, WhisperIntent{sender->GetName(), - by_rti ? "Pull: no marked mob for my rti symbol." : "Pull: select an enemy first."}); - return true; - } - uint32 ms = args.size() >= 1 ? static_cast(args[0] * 1000ULL) : 3000u; - if (ms > 60'000) ms = 60'000; - // Raid map: the pull goes to the main tank only; every other bot ignores it (it follows / assists). - if (!RaidPullGateAllows(bot, target)) - return true; - const uint64 id = bot->GetGUID().GetCounter(); - Services::Registry().for_each([&](BotId bid, BotRegistryEntry const& e) - { - if (bid != id) return; - const uint32_t until = GameTime::GetGameTimeMS() + ms; - const_cast(e).paused_until_ms.store(until, std::memory_order_relaxed); - }); - // Broadcast a raid warning if the bot can. raid_warning() bails Locked - // when not allowed, which is fine — solo bots and non-officers just - // skip the broadcast and still fire the pull on their end. - Push(bot, RaidWarningIntent{ - fmt::format("Pulling {} in {}s!", target->GetName(), ms / 1000)}); - Push(bot, StartAttackIntent{target->GetGUID()}); - SetOwnerFollowOrder(bot, false, false); - - // Broadcast to all OTHER registered bots in the same group: pause - // them for the same window then engage the same target. Caller bots - // already had their pause set above. Healers/casters benefit from - // the synchronized pull window so they can pre-position; melee bots - // sync their burst CDs. - if (Group const* grp = bot->GetGroup()) - { - const ObjectGuid target_guid = target->GetGUID(); - const uint32_t until = GameTime::GetGameTimeMS() + ms; - uint32 broadcast_count = 0; - for (GroupReference const& itr : grp->GetMembers()) - { - Player* member = itr.GetSource(); - if (!member || member == bot) continue; - const BotId mid = member->GetGUID().GetCounter(); - if (!Services::Registry().has(mid)) continue; - if (!RaidPullGateAllows(member, target)) continue; - Services::Registry().for_each([&](BotId bid, BotRegistryEntry const& e) - { - if (bid != mid) return; - const_cast(e).paused_until_ms - .store(until, std::memory_order_relaxed); - }); - Push(member, StartAttackIntent{target_guid}); - SetOwnerFollowOrder(member, false, false); - ++broadcast_count; - } - if (broadcast_count > 0) - Push(bot, WhisperIntent{sender->GetName(), - fmt::format("Pull: synced to {} group bot(s).", broadcast_count)}); - } - - Push(bot, WhisperIntent{sender->GetName(), - fmt::format("Pull: engaging {} in {}ms.", target->GetName(), ms)}); + // One Pull, the same as the word in party chat and on the panel (Module::RouteGroupOrder): the tank takes the owner's + // selection, everyone else is handed the fight back and waits for the owner's Attack. The old countdown-and-everyone-attacks + // path (pause 3 s, StartAttack on the whole group) was a second Pull. + if (BotRole(bot) == Role::Tank) + return DispatchSingleImpl(sender, bot, "tank"); + ReleaseOwnerFollowOrder(sender, bot, "pull"); return true; } if (cmd == "trinkets") @@ -3660,7 +3669,7 @@ bool BotCommandParser::DispatchSingleImpl(Player* sender, Player* bot, std::stri if (cmd == "queue") { // Per-bot intent-queue diagnostic. Reports queue size + capacity - // so the owner can see whether the AI worker is stalled (queue + // so the owner can see whether the bot worker is stalled (queue // grows) or healthy (queue empties between ticks). const uint64 id = bot->GetGUID().GetCounter(); IntentQueue* q = Services::Registry().intents(id); @@ -4061,6 +4070,10 @@ bool BotCommandParser::DispatchSingleImpl(Player* sender, Player* bot, std::stri "Assist: anchor has no target."}); return true; } + // The same raid pull gate as attack and assist_all: in a raid the main tank opens, so a whispered assist and the + // party-chat word (which is rewritten to attack) answer alike. + if (!RaidPullGateAllows(bot, ObjectAccessor::GetUnit(*sender, tgt))) + return true; Push(bot, StartAttackIntent{tgt}); SetOwnerFollowOrder(bot, false, false); return true; @@ -4107,6 +4120,8 @@ bool BotCommandParser::DispatchSingleImpl(Player* sender, Player* bot, std::stri // automatically when the target dies (in_combat→Idle transition // detects empty victim and resets owner_command). Unit const* target = sender->GetSelectedUnit(); + if (!target) + target = AttackFallbackTarget(sender, bot); // nothing selected: the mob the group is already fighting if (!target) { Push(bot, WhisperIntent{sender->GetName(), @@ -4127,6 +4142,12 @@ bool BotCommandParser::DispatchSingleImpl(Player* sender, Player* bot, std::stri cur->owner_command() == BotAI::OwnerCommand::Engage && cur->owner_target() == target->GetGUID() && bot->GetVictim() == target) return true; + // Attack is instant for the whole group (playtest, Deadmines 2026-10-15): every bot opens on the owner's target at once, tank + // or not. Only Pull and Pull back keep the tank first. + // 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) + return true; Push(bot, StartAttackIntent{target->GetGUID()}); if (BotAI* ai = Services::Registry().ai(bot->GetGUID().GetCounter())) { @@ -4259,6 +4280,9 @@ bool BotCommandParser::DispatchSingleImpl(Player* sender, Player* bot, std::stri bool const by_icon = target != nullptr; if (!target) target = sender->GetSelectedUnit(); + // Nothing selected: the owner's skull, else cross (the same pick as "pull back" and "pull rti"). + if (!target) + target = RtiPullTarget(bot); if (!target) { Push(bot, WhisperIntent{sender->GetName(), "Tank: select a pull target first."}); @@ -4495,7 +4519,7 @@ bool BotCommandParser::DispatchSingleImpl(Player* sender, Player* bot, std::stri // Broadcast AoE-preference toggle across all group bots. /aoe_all on / // off / (no arg → toggle each individually). Mutates BotAI state // directly via Services::Registry().ai(id), since AoE preference is a - // per-bot AI flag rather than an emitted intent. + // per-bot bot logic flag rather than an emitted intent. const std::string& want = parsed.tail; const int mode = (want == "on" || want == "1") ? 1 : (want == "off" || want == "0") ? 0 @@ -4628,7 +4652,7 @@ bool BotCommandParser::DispatchSingleImpl(Player* sender, Player* bot, std::stri // Owner emergency unstuck. Clears in-flight movement, attack, and // pending cast. Does NOT touch the snapshot or intent queue (the // worker drains the queue as a normal-turn result of the next - // tick), so the bot picks up fresh AI decisions on the next loop. + // tick), so the bot picks up fresh bot logic decisions on the next loop. // Useful when the bot is wedged on a target it can't reach or // mid-rotation on a target the owner wants to disengage from. Push(bot, StopMovementIntent{/*clear_generators*/ true}); @@ -5802,7 +5826,7 @@ bool BotCommandParser::DispatchSingleImpl(Player* sender, Player* bot, std::stri if (cmd == "distance" || cmd == "dist") { // Report distance from bot to sender's selection (default sender). - // Whisper-only diagnostic; no AI side effect. + // Whisper-only diagnostic; no bot logic side effect. Unit const* tgt = sender->GetSelectedUnit(); if (!tgt) tgt = sender; const float dist = bot->GetDistance(tgt); @@ -5875,18 +5899,67 @@ bool BotCommandParser::DispatchSingleImpl(Player* sender, Player* bot, std::stri } if (cmd == "use") { - // Use the sender's selected target as a game object (chest, herb, - // ore, quest object). For NPC interaction use the "talk" command - // instead. The intent is rejected by the API if the selection is - // not a GameObject. + // "use ": the nearest matching game object within 30 y of the bot (an altar, brazier, lever, orb). + // The bot walks over, uses it once and stays there (idle:owner_use); "follow" releases it. A ritual such as the UBRS + // Blackrock Altar (3 users) completes once enough different players have used it: the owner plus ";Name:use altar" to two bots. + // A selected game object still works for clients that can select one. ObjectGuid selection = sender->GetTarget(); - if (selection.IsEmpty() || !selection.IsGameObject()) + std::string want = parsed.tail; // lower case (Normalize) + size_t const b = want.find_first_not_of(' '); + want = b == std::string::npos ? std::string() : want.substr(b); + if (want.empty() && !selection.IsEmpty() && selection.IsGameObject()) { - Push(bot, WhisperIntent{sender->GetName(), - "Use: select a game object first."}); + Push(bot, UseObjectIntent{selection}); return true; } - Push(bot, UseObjectIntent{selection}); + if (want.empty()) + { + Push(bot, WhisperIntent{sender->GetName(), "Use: say 'use ' near the object (for example 'use altar')."}); + return true; + } + uint32 const want_entry = args.empty() ? 0u : uint32(args.front()); + std::list nearby; + Trinity::GameObjectInRangeCheck check(bot->GetPositionX(), bot->GetPositionY(), bot->GetPositionZ(), 30.0f); + Trinity::GameObjectListSearcher searcher(bot, nearby, check); + Cell::VisitGridObjects(bot, searcher, 30.0f); + GameObject* best = nullptr; + float best_d = 1.0e9f; + for (GameObject* go : nearby) + { + if (!go || !go->isSpawned() || go->HasFlag(GO_FLAG_NOT_SELECTABLE)) + continue; + bool const match = want_entry != 0 ? go->GetEntry() == want_entry + : Normalize(go->GetGOInfo()->name).find(want) != std::string::npos; + if (!match) + continue; + float const d = bot->GetDistance(go); + if (d < best_d) { best_d = d; best = go; } + } + if (!best) + { + Push(bot, WhisperIntent{sender->GetName(), fmt::format("Use: no '{}' within 30 yards of me.", want)}); + return true; + } + BotAI* ai = Services::Registry().ai(bot->GetGUID().GetCounter()); + if (!ai) + return true; + uint32 const now = GameTime::GetGameTimeMS(); + // Stay, so the follow does not walk the bot off the object (a ritual's channel breaks when the user moves). + ai->enter_manual(BotAI::OwnerCommand::Stay, ObjectGuid::Empty, now, BotAI::kHoldPositionTtlMs); + ai->set_owner_follow_order(false); + ai->end_fallback(); + ai->end_pull_back(); + ai->end_owner_use(); + ai->set_last_owner_name(sender->GetName()); + BotAI::OwnerUseOrder o; + o.map = bot->GetMapId(); + o.go = best->GetGUID(); + o.x = best->GetPositionX(); o.y = best->GetPositionY(); o.z = best->GetPositionZ(); + o.set_ms = now ? now : 1u; + ai->start_owner_use(o); + Push(bot, WhisperIntent{sender->GetName(), fmt::format("Use: {} ({:.0f} yards), then I stay there.", best->GetGOInfo()->name, best_d)}); + TC_LOG_INFO("playerbot.v2", "[owner_use] {} ordered to use {} (entry {}) at {:.0f}y", bot->GetName(), + best->GetGOInfo()->name, best->GetEntry(), best_d); return true; } if (cmd == "talents_all" || cmd == "talentsall") @@ -6123,7 +6196,7 @@ bool BotCommandParser::DispatchSingleImpl(Player* sender, Player* bot, std::stri BotAI* ai = Services::Registry().ai(id); if (!ai) { - Push(bot, WhisperIntent{sender->GetName(), "WhyIdle: no AI handle."}); + Push(bot, WhisperIntent{sender->GetName(), "WhyIdle: no bot logic handle."}); return true; } const uint32 now_ms = GameTime::GetGameTimeMS(); @@ -6175,7 +6248,7 @@ bool BotCommandParser::DispatchSingleImpl(Player* sender, Player* bot, std::stri if (cmd == "stats" || cmd == "status") { // Whisper a one-line status report back to the requester. The data - // comes from the latest published snapshot — same fact base the AI + // comes from the latest published snapshot — same fact base the bot logic // workers see, so this is naturally consistent. const BotId id = bot->GetGUID().GetCounter(); auto snap = Services::Snapshots().latest(id); @@ -7254,7 +7327,7 @@ done_dispel: } if (cmd == "age") { - // Snapshot freshness — diagnostic for AI staleness investigation. + // Snapshot freshness — diagnostic for bot logic staleness investigation. const uint64 id = bot->GetGUID().GetCounter(); auto snap = Services::Snapshots().latest(id); if (!snap) diff --git a/src/modules/PlayerbotV2/Bot/BotIntent.h b/src/modules/PlayerbotV2/Bot/BotIntent.h index dff59aed7a..0b7a12bce5 100644 --- a/src/modules/PlayerbotV2/Bot/BotIntent.h +++ b/src/modules/PlayerbotV2/Bot/BotIntent.h @@ -1,4 +1,4 @@ -// BotIntent - Typed messages from AI workers to world thread. +// BotIntent - Typed messages from bot workers to world thread. // First iteration carries the load-bearing intent variants; the full set per // CONTRACTS.md §2.3 lands as subsystems implement the corresponding paths. @@ -135,7 +135,7 @@ struct VendorSellTrashIntent { ObjectGuid npc; }; struct MakeBagRoomIntent { uint8 min_free = 4; }; struct RepairAllIntent { ObjectGuid npc; bool from_guild_bank; }; // Buy first vendor item matching item_class/item_subclass that the bot meets -// the level requirement for. Used by auto-restock rules where the AI doesn't +// the level requirement for. Used by auto-restock rules where the bot logic doesn't // know the vendor's exact slot layout. `total_count` is the desired quantity; // the API stops once that many units have been purchased (multiple buy_slot // calls if the vendor sells the item in stacks +#include #include "BotAI.h" #include "BotSnapshot.h" #include "BotSnapshotView.h" @@ -55,7 +57,7 @@ char const* SchoolSpellName(SpellInfo const* si) uint8 BotIntentEmitter::SpellSchoolMaskOf(uint32 spell_id, uint8 wand_school_mask) { // sSpellMgr is a read-only store after load; the Classic APL helpers read - // it from the AI workers the same way (ApClassicHeal.h). + // it from the bot workers the same way (ApClassicHeal.h). SpellInfo const* si = spell_id ? sSpellMgr->GetSpellInfo(spell_id, DIFFICULTY_NONE) : nullptr; if (!si) return 0; // Spell::Spell: a wand user's ranged-attack spell deals the wand's school. @@ -262,9 +264,31 @@ bool BotIntentEmitter::start_attack(ObjectGuid target) if (ai_ && school_snap_) { BotAI::RaidSchoolState& rs = ai_->raid_school(); + // Once a minute per bot and mob: the bot flips between the immune mob and its fallback target every tick (Rag's submerge, + // MC 2026-10-12: 3807 lines in one fight), and the first line already says why (the [raid_school_why] line names the aura). + // start_attack runs on the bot workers, so the pacing map is locked and bounded. + static std::mutex sLoggedMutex; + static std::unordered_map sLogged; + uint64_t const lkey = (school_snap_->guid.GetCounter() << 24) ^ target.GetCounter(); + uint32_t const lnow = school_snap_->published_at_ms; + bool log_now = false; if (rs.hold_target != target) + { + std::lock_guard lock(sLoggedMutex); + if (sLogged.size() > 4096) + sLogged.clear(); + uint32_t& lat = sLogged[lkey]; + if (!lat || lnow - lat > 60000) + { + lat = lnow; + log_now = true; + } + } + if (log_now) + { TC_LOG_INFO("playerbot.v2", "[raid_school] {} on {}: immune to every school -> not attacking it", school_snap_->identity.name, target.ToString()); + } rs.hold_target = target; rs.hold_mask = 0; } @@ -272,6 +296,33 @@ bool BotIntentEmitter::start_attack(ObjectGuid target) } const bool pushed = emit(StartAttackIntent{target, avoid}); if (pushed && ai_ && school_snap_) + { + static std::mutex sOpenLogMutex; + static std::unordered_map sOpenLog; + uint32_t const onow = school_snap_->published_at_ms; + uint64_t const okey = (school_snap_->guid.GetCounter() << 24) ^ target.GetCounter(); + bool open_log = false; + { + std::lock_guard lock(sOpenLogMutex); + if (sOpenLog.size() > 4096) + sOpenLog.clear(); + uint32_t& last = sOpenLog[okey]; + if (!last || onow - last > 10000u) + { + last = onow; + open_log = true; + } + } + if (open_log) + { + int in_combat = -1, victim_kind = -1; + for (NearbyUnit const& u : school_snap_->combat.nearby_enemies) + if (u.guid == target) { in_combat = u.unit_in_combat ? 1 : 0; victim_kind = int(u.victim_kind); break; } + TC_LOG_INFO("playerbot.v2", "[attack_start] {} attacks {} stance {} last_rule {} mob in_combat {} victim_kind {}", + school_snap_->identity.name, target.ToString(), int(ai_->owner_stance()), ai_->last_rule_fired() ? ai_->last_rule_fired() : "none", in_combat, victim_kind); + } + } + if (pushed && ai_ && school_snap_) { BotAI::RaidSchoolState& rs = ai_->raid_school(); uint8 const white = uint8(SPELL_SCHOOL_MASK_NORMAL | school_snap_->consumables.wand_school_mask); @@ -285,6 +336,11 @@ bool BotIntentEmitter::start_attack(ObjectGuid target) return pushed; } +bool BotIntentEmitter::move_already_emitted(float x, float y, float z) const +{ + return ai_ && ai_->move_to_recently_emitted(x, y, z, GameTime::GetGameTimeMS()); +} + bool BotIntentEmitter::move_to(float x, float y, float z, bool run, bool direct, bool drop) { // Per-bot dedup: skip if the previous move_to went to ~the same XYZ @@ -297,7 +353,15 @@ bool BotIntentEmitter::move_to(float x, float y, float z, bool run, bool direct, { const uint32 now_ms = GameTime::GetGameTimeMS(); if (ai_->move_to_recently_emitted(x, y, z, now_ms)) + { + // Why a move_to returned false (pull back "refused" on flat ground, Deadmines 2026-10-15): the dedup, not the navmesh. + // Per bot: one global throttle was used up by the 300+ dedups of background bots, and the squad's lines never showed. + if (ai_->dedup_log_due(now_ms, 1000u)) + TC_LOG_INFO("playerbot.v2", + "[move_to_refused] bot={} dst=({:.1f},{:.1f},{:.1f}) direct={} reason=dedup: a move to within 3 y was emitted in the last 1.5 s", + ai_->bot_id(), x, y, z, direct ? 1 : 0); return false; + } // REFUSAL GUARD (emitter-level on purpose). PlayerbotAPI::move_to // keeps a per-destination path-fail backoff: one failed pathfind // poisons that dst, every later move_to to ~it returns Locked @@ -332,6 +396,13 @@ bool BotIntentEmitter::move_to(float x, float y, float z, bool run, bool direct, const bool pushed = emit(MoveToIntent{x, y, z, run, direct, drop}); if (pushed) ai_->note_move_to_emitted(x, y, z, now_ms); + else + { + if (ai_->dedup_log_due(now_ms, 1000u)) + TC_LOG_INFO("playerbot.v2", + "[move_to_refused] bot={} dst=({:.1f},{:.1f},{:.1f}) direct={} reason=intent queue refused the push", + ai_->bot_id(), x, y, z, direct ? 1 : 0); + } return pushed; } return emit(MoveToIntent{x, y, z, run, direct, drop}); @@ -347,11 +418,32 @@ static uint32 GcdLengthMs(uint32 spell_id) return uint32(si->StartRecoveryTime); } +void BotIntentEmitter::hold_casts_for_mana_item() +{ + if (ai_) + ai_->note_mana_break(GameTime::GetGameTimeMS()); +} + +void BotIntentEmitter::end_mana_break() +{ + if (ai_) + ai_->clear_mana_break(); +} + +// A spell with a cast time: the kind a running cast of the same bot would have to finish first. +static bool HasCastTime(uint32 spell_id) +{ + SpellInfo const* si = sSpellMgr->GetSpellInfo(spell_id, DIFFICULTY_NONE); + return si && si->CalcCastTime() > 0; +} + bool BotIntentEmitter::cast(uint32 spell_id, ObjectGuid target) { + if (ai_ && ai_->mana_break_active(GameTime::GetGameTimeMS()) && HasCastTime(spell_id)) + return false; // Optimistic per-spell emit dedup. The snapshot's spell_cooldowns // table reflects server-side cooldowns one world-tick after the cast - // lands; in the ~200-1000ms gap, the AI worker may re-tick on the + // lands; in the ~200-1000ms gap, the bot worker may re-tick on the // same stale snapshot, see "is_ready=true" for a spell whose cast // just landed, and re-emit. Server rejects with SPELL_FAILED_NOT_READY // (91) — every rejection logs to Server.log and burns one intent slot. @@ -359,7 +451,7 @@ bool BotIntentEmitter::cast(uint32 spell_id, ObjectGuid target) // Solution: track per-spell emit timestamps in BotAI; drop duplicate // emits within kCastEmitLockoutMs (~1.5s, > snapshot cadence). The // next snapshot's real cooldown table picks up before the lockout - // expires, so the AI never sees a "ready" window the server disagrees + // expires, so the bot logic never sees a "ready" window the server disagrees // with. // // Skipped when ai_ is null (test harness etc.) — the dedup is @@ -389,6 +481,8 @@ bool BotIntentEmitter::cast(uint32 spell_id, ObjectGuid target) 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)) return false; diff --git a/src/modules/PlayerbotV2/Bot/BotIntentEmitter.h b/src/modules/PlayerbotV2/Bot/BotIntentEmitter.h index 9606252608..d0402e5305 100644 --- a/src/modules/PlayerbotV2/Bot/BotIntentEmitter.h +++ b/src/modules/PlayerbotV2/Bot/BotIntentEmitter.h @@ -1,4 +1,4 @@ -// BotIntentEmitter - Push-only handle to a bot's intent queue. Held by AI +// BotIntentEmitter - Push-only handle to a bot's intent queue. Held by bot logic // workers during tick. CONTRACTS.md §2.4. #pragma once @@ -103,6 +103,9 @@ public: // direct=true = straight MovePoint spline, no pathfinding (committed // traversal-link crossings only — see MoveToIntent). bool move_to(float x, float y, float z, bool run = true, bool direct = false, bool drop = false); + // A move_to to ~(x,y,z) was already emitted in the last 1.5 s (the one move_to dedups, returning false). That is a move under way, + // not a refusal: callers that count false results as path refusals ask this first. + bool move_already_emitted(float x, float y, float z) const; // ---- Raid damage-school rule (PveOrder::SchoolHint) ---- // The worker pool hands the emitter the snapshot the bot's tick runs on. @@ -434,6 +437,11 @@ public: bool equip_item(uint8 from_bag, uint8 from_slot, uint8 to_slot) { return emit(EquipItemIntent{from_bag, from_slot, to_slot}); } + // Mana break: a mana item is due but a cast is running. Until the item goes out (or 4 s pass) cast()/cast_rank() refuse any + // spell with a cast time, so the running cast is the last one and the next tick can use the item. + void hold_casts_for_mana_item(); + void end_mana_break(); + private: bool push(Intent i); // Raid school rule gate for cast()/cast_rank(); see set_school_source. diff --git a/src/modules/PlayerbotV2/Bot/BotIntentExecutor.cpp b/src/modules/PlayerbotV2/Bot/BotIntentExecutor.cpp index ae347c8037..181f2da697 100644 --- a/src/modules/PlayerbotV2/Bot/BotIntentExecutor.cpp +++ b/src/modules/PlayerbotV2/Bot/BotIntentExecutor.cpp @@ -716,7 +716,7 @@ size_t V2::Module::DrainIntents() // Per-target StartAttack lockout. Player::Attack returns // false (→ Result::ServerRefused) when the target is // immune / phased / faction-locked / vehicle-locked / - // already attacking with same melee mode etc. The AI rule + // already attacking with same melee mode etc. The bot logic rule // re-emits next snapshot if we don't gate it; without this // mark, ~5 emits/sec from a single wedged bot saturate // the executor and stall the world thread (observed 60 s @@ -906,7 +906,7 @@ size_t V2::Module::DrainIntents() } // Per-bot diagnostic ring. Recorded AFTER the API call so the // captured Result reflects what actually happened, not what - // the AI worker hoped would happen. Used by /diag . + // the bot worker hoped would happen. Used by /diag . // MoveTo destinations are captured so alternating-target // loops show verbatim in /diag — an Ok-per-tick stream is // ambiguous without them (the API's goal-key dedup also diff --git a/src/modules/PlayerbotV2/Bot/BotRegistry.h b/src/modules/PlayerbotV2/Bot/BotRegistry.h index 40064b1902..3b2c9e1596 100644 --- a/src/modules/PlayerbotV2/Bot/BotRegistry.h +++ b/src/modules/PlayerbotV2/Bot/BotRegistry.h @@ -48,7 +48,7 @@ struct BotRegistryEntry size_t intent_history_head = 0; // next write slot size_t intent_history_size = 0; // [0, kIntentHistoryCap] mutable std::mutex intent_history_mtx; - // Corpses queued for looting (FIFO). Drained by State_Idle on the AI + // Corpses queued for looting (FIFO). Drained by State_Idle on the bot logic // worker thread; written by V2::Module::OnDeath on the world thread. // The mutex bridges those threads — without it the deque races (both // sides do push_back/pop_front). Bounded by kPendingLootMax so a diff --git a/src/modules/PlayerbotV2/Bot/BotSnapshot.h b/src/modules/PlayerbotV2/Bot/BotSnapshot.h index 26abfe9fa3..49507b936b 100644 --- a/src/modules/PlayerbotV2/Bot/BotSnapshot.h +++ b/src/modules/PlayerbotV2/Bot/BotSnapshot.h @@ -1,5 +1,5 @@ // BotSnapshot - Per-bot immutable snapshot. Built on world thread, consumed -// read-only by AI workers. See CONTRACTS.md §2.1. +// read-only by bot workers. See CONTRACTS.md §2.1. // // First-iteration shape: includes the load-bearing fields needed by the initial // state machine (Idle, LoggingIn, Travelling) and APL evaluator. Additional @@ -73,7 +73,7 @@ struct EquippedItem uint8 durability_pct; // First ON_USE spell from ItemTemplate.Effects, or 0 when the item has // no on-use effect (most weapons/armor; trinkets / engineering tinkers - // typically carry one). Resolved in the builder so AI can call + // typically carry one). Resolved in the builder so bot logic can call // 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; @@ -94,7 +94,7 @@ struct InventoryItem bool is_quest_item; // Item level (0 for non-equippable / non-leveled). Lets the auto-equip // rule compare upgrades against the currently-equipped item without - // re-resolving the live Item* on the AI worker thread. + // re-resolving the live Item* on the bot worker thread. uint16 item_level; // Target equipment slot (EQUIPMENT_SLOT_HEAD .. RANGED) the bot would // wear this item in. Resolved by Player::FindEquipSlot in the builder @@ -126,7 +126,7 @@ struct InventoryItem ItemStatBlock stats{}; }; -// One enumerable objective from `Quest::Objectives`. Captured per-tick so AI +// One enumerable objective from `Quest::Objectives`. Captured per-tick so bot logic // can decide which one to chase next without round-tripping the world thread // for every (quest, obj) pair. `type` matches QuestObjectiveType (KILL=0 / // ITEM=1 / GAMEOBJECT=2 / TALKTO=3 / AREATRIGGER=10 etc); `object_id` is the @@ -316,7 +316,7 @@ struct NearbyUnit ObjectGuid victim; // Who this unit is currently attacking (Empty if none). // For Creature units: lower 32 bits of UNIT_NPC_FLAG_* (vendor/repair/ // banker/trainer/flightmaster/innkeeper/etc). Zero for player units. - // Lets AI rules find capability-bearing NPCs without round-tripping + // Lets bot logic rules find capability-bearing NPCs without round-tripping // through a per-creature ObjectAccessor lookup. uint32 npc_flags = 0; // Dungeon-boss flag (creature_template.flags_extra & 0x10000000). @@ -350,6 +350,9 @@ struct NearbyUnit // and wedge InCombat forever firing at a target that never dies (observed // live: Grimfang frozen 2.5min shooting Valley-of-Trials Training Dummy). bool is_pacified = false; + // The creature is running away (a low-health mob fleeing for help, or feared): its motion is Fleeing, Timed fleeing or + // Assistance. Melee do not chase it out of the group. + bool is_fleeing = false; // UNIT_FLAG_UNINTERACTIBLE (0x02000000, the old NOT_SELECTABLE): players // cannot select/target the unit, and Unit::IsValidAttackTarget rejects it — // so a bot can NEVER acquire it as a victim. Invisible "stalker" / trigger @@ -448,12 +451,12 @@ struct NearbyUnit // sizing (Combat/Apl/ApClassicHeal.h). 0 for friends. float melee_swing = 0.f; - // ---- Threat discipline (port of Karrz's GroupPveRestraint / - // MCRaidHoldDamage / LooseAttackers, ike3-based bots ike3 playerbot). Read by the + // ---- Threat discipline (port of the owner's GroupPveRestraint / + // MCRaidHoldDamage / LooseAttackers, wow-1.12 ike3 playerbot). Read by the // builder from the unit's ThreatManager on the build thread; consumed by // BotSnapshotView::threat_hold() and loose_attacker(). Zero / false on // units without a threat list (players, threatless creatures). - // The bot's threat on this unit: max(bot, bot's pet), as Karrz counts it. + // The bot's threat on this unit: max(bot, bot's pet), as the owner counts it. float my_threat = 0.f; // Highest threat any group TANK (see CombatTargetsState::group_tank) // within 50y of the unit holds on it. 0 when the group has no tank. @@ -1074,7 +1077,7 @@ struct WorldQuestEntry }; // Quest discovery rollup. Lists of nearby questgivers (offers + turn-ins), // bag items that start a quest, and world-quest givers within range. All -// resolved by the snapshot builder so AI workers don't round-trip +// resolved by the snapshot builder so bot workers don't round-trip // ObjectMgr / Creature::hasInvolvedQuest from the worker thread. struct QuestDiscoveryState { @@ -1203,7 +1206,7 @@ struct QuestLogState // The VALIDATED bridge route to the objective, computed by the builder's // world-thread probe with navmesh-checked source attaches (see // RouteRequest::validate_source_walk). Mirrors BotAI::PlanLeg field-for- - // field. The AI worker MUST execute these legs instead of recomputing + // field. The bot worker MUST execute these legs instead of recomputing // the route: its own FindRoute can't validate attaches off the world // thread, so it would produce the euclidean walk-only route the wedged // bot provably can't follow (the exact failure this exists to fix — @@ -1387,7 +1390,7 @@ struct CombatTargetsState // Per-bot navigation telemetry surfaced to rules so they can short-circuit // when the bot's been wedged. BotAI tracks path failures via // `note_path_blocked`; the snapshot Builder copies the count + last-time -// here so AI worker rules can read without dereferencing BotAI directly. +// here so bot worker rules can read without dereferencing BotAI directly. // // `count` is the CONSECUTIVE (current-wedge) count of API::move_to results // that returned Result::Locked (NoPath / FarFromPolyEnd / Incomplete / Short). @@ -1470,7 +1473,7 @@ struct BankState }; // Active group/master loot rolls awaiting the bot's vote. See -// LootRollEntry for per-row semantics; AI emits LootRollIntent. +// LootRollEntry for per-row semantics; bot logic emits LootRollIntent. struct LootRollEntry { ObjectGuid loot_object; @@ -1479,7 +1482,7 @@ struct LootRollEntry uint8 vote_mask; bool is_upgrade; bool is_quest_item; - // Loot etiquette with a human in the group (Karrz's LootRollAction): + // Loot etiquette with a human in the group (the owner's LootRollAction): // a human group member on the bot's map, and whether one of them could // use the item and would want it (HumanWouldWantItem). bool human_in_group = false; @@ -1494,7 +1497,7 @@ struct LootRollsState void reset() { loot_rolls.clear(); } }; -// Nearby GameObjects within ~30yd that the AI cares about (mailbox, +// Nearby GameObjects within ~30yd that the bot logic cares about (mailbox, // chests, herbs/ore, fishing holes, questgivers, binders, hazards, // portals). go_type mirrors GAMEOBJECT_TYPE_*. Sorted by distance so // the closest survive the bounded cap. @@ -1551,7 +1554,7 @@ struct MovementState bool is_mounted = false; bool is_moving = false; // True while the CORE is flying the bot on a taxi path (UNIT_STATE_IN_ - // FLIGHT). The AI must do NOTHING during a taxi flight — the + // FLIGHT). The bot logic must do NOTHING during a taxi flight — the // FlightPathMovementGenerator owns movement; any idle rule that emits a // move_to / teleport (watchdog_escape, unstick, hearth rescue) would // corrupt the flight. DispatchIdle and GlobalStuckRescue bail on this. @@ -1597,7 +1600,7 @@ struct EnvironmentState // Dungeon execution context (Phase A of GROUP_DUNGEON_PLAN.md). Populated // when bot is inside an instance map so the dungeon-run rules can drive // tank pulls, interrupt rotation, wipe recovery, and run-completion -// without round-tripping the InstanceScript from the AI worker. Also holds +// without round-tripping the InstanceScript from the bot worker. Also holds // the cheaper "encounter context" pair (npc_id + phase) used by per-script // hooks. See per-field comments on the legacy flat fields (now consumed) // for full semantics. @@ -1670,6 +1673,8 @@ struct PetState // the assist-pet rule: bot picks up the pet's target so a hunter // standing idle while his cat melees a mob actually opens up too. ObjectGuid pet_victim; + // The pet's react state (REACT_PASSIVE 0 / DEFENSIVE 1 / AGGRESSIVE 2 / ASSIST 3). + uint8 pet_react = 1; // Mob guids actively engaging the pet (anyone with the pet in // m_attackers). Capped at 4 to keep the snapshot lean. Drives the // peel half of assist_pet: when pet melees mob A but mob B is @@ -1710,6 +1715,7 @@ struct PetState pet_auras.clear(); stable_pets.clear(); pet_victim = ObjectGuid::Empty; + pet_react = 1; pet_attackers.clear(); pet_taunt_spells.fill(0); pet_taunt_count = 0; @@ -2087,7 +2093,7 @@ struct ReputationEntry { uint32 faction_id; int32 standing; uint8 rank; }; // Bot progression rollup. Trained skills, currency wallet, faction // reputations. Builder writes; rules read via view accessors. Separated // out so the snapshot publisher can re-use the cached vector across -// ticks for AI threads where the underlying player object hasn't +// ticks for bot logic threads where the underlying player object hasn't // gained new entries (BotSetupPipeline holds the long-term cache; // snapshot replays into the vector when invalidated). struct ProgressionState @@ -2136,7 +2142,7 @@ inline float EquipFitScore(ItemStatBlock const& blk, uint16 item_level, return v; } -// Bag / equipment summary. Cached aggregates the AI consults to gate +// Bag / equipment summary. Cached aggregates the bot logic consults to gate // vendor-visit and equip-upgrade decisions without re-walking equipped[] / // bag_items every tick. bag_free_slots is the count of empty inventory // slots across all bags (cached because GetFreeInventorySlotCount walks @@ -2216,7 +2222,7 @@ struct VendorVisitState void reset() { *this = VendorVisitState{}; } }; -// Consumables — stack-quantity counts the AI checks for OOC restock and the +// Consumables — stack-quantity counts the bot logic checks for OOC restock and the // vendor-visit FSM gate. Built by the snapshot builder by walking bag_items // and sniffing item class / subclass. Health vs mana potion split is filled // only when the potion's primary spell effect is heal vs restore (so healers @@ -2232,6 +2238,9 @@ struct ConsumablesState // ammo, 1 = arrows, 2 = bullets. ammo_count is every usable projectile in the bags. uint8 ammo_kind = 0; uint32 ammo_count = 0; + // Item subclass of the weapon in the ranged slot (ITEM_SUBCLASS_WEAPON_*), 0xFF = slot empty. The pull-back opener + // picks the shot that weapon fires (Throw / Shoot Bow / Gun / Crossbow), never one the core refuses EQUIPPED_ITEM. + uint8 ranged_subclass = 0xFF; // Wand users (mage / priest / warlock) with a ranged weapon equipped: the // school mask of its damage (1 << ItemTemplate::GetDamageType(), as // Spell::Spell sets for a ranged-attack spell such as Shoot). 0 = none. @@ -2268,7 +2277,7 @@ struct ClassicUpkeepState struct BgState { // Up to PLAYER_MAX_BATTLEGROUND_QUEUES (3 in 12.0) active queues per - // bot. AI uses count > 0 to gate against re-queuing the same BG. + // bot. bot logic uses count > 0 to gate against re-queuing the same BG. std::vector queues; // True when the bot is inside a battleground instance (vs queued for / @@ -2521,7 +2530,7 @@ struct ArchetypeState // Craft-order board projection (#4B-2(a)). Read-only slice of // Fleet::CraftOrderBoard surfaced into each bot's snapshot so economy idle // rules can decide WITHOUT locking the board (the world thread populates this -// from the board during Build; rules read it on the AI worker thread). All +// from the board during Build; rules read it on the bot worker thread). All // fields default to "no order" so an un-populated snapshot is fail-closed. // // my_open_order_count : how many Open orders this bot has POSTED as requester @@ -2596,7 +2605,7 @@ struct BotSnapshot SnapshotVer version = 0; BotId bot_id = 0; TickId world_tick = 0; - // GameTimeMS at publication. Lets the AI worker compute snapshot age + // GameTimeMS at publication. Lets the bot worker compute snapshot age // ("how stale is this fact base?") and the /age whisper report it. // Mirrors GameTime::GetGameTimeMS at builder-exit; uint32 so it // matches the underlying TC clock. @@ -2646,7 +2655,7 @@ struct BotSnapshot GuildState guild{}; // Bot's owner character name resolved at snapshot time (empty when // unowned or the cache lookup fails). Used by mat-share-to-owner mail - // rule so the AI worker can address mail without round-tripping the + // rule so the bot worker can address mail without round-tripping the // owner registry + character cache from the worker thread. std::string owner_name; // Owner character guid (Empty when unowned or account-only ownership). @@ -2655,6 +2664,9 @@ struct BotSnapshot // The owner is in the bot's group: the bot is a companion and does what its owner's party does, not world-bot // errands (questing, vendors, gathering, travel). See IdleRuleRegistry::tick. bool owner_in_group = false; + // Flat distance to the owner when it is on the bot's map, else -1. nearby_friends keeps only the 12 nearest friends, so in a raid + // the owner is rarely in it (companion_may_sit). + float owner_dist = -1.0f; // Owner "max dps" / "save mana" (BotAI::tactic_burn / tactic_save_mana), mirrored by the builder. bool tactic_burn = false; bool tactic_save_mana = false; @@ -2706,10 +2718,10 @@ struct BotSnapshot // semantics. SecondaryStatsState secondary_stats{}; // (upgrades_pending migrated into bags.upgrades_pending above) - // Aggregate stack-quantity counts of consumable categories the AI cares + // Aggregate stack-quantity counts of consumable categories the bot logic cares // about for OOC restock decisions. Filled by the builder by walking // bag_items and sniffing item template GetClass/GetSubClass — saves the - // AI worker thread from looking up ItemTemplates for every bag item just + // bot worker thread from looking up ItemTemplates for every bag item just // to know "do I have enough food?". Populated for the categories the // auto-restock rules actually consult; add more as new rules need them. // (smallest_bag_capacity / has_empty_bag_slot migrated into bags above) @@ -2777,17 +2789,17 @@ struct BotSnapshot // questgivers (creature OR game object) that can accept a complete // quest from the bot's log. Built by walking nearby_friends + // nearby_objects in the snapshot builder against the bot's complete - // quests via Creature/GameObject::hasInvolvedQuest. AI iterates and + // quests via Creature/GameObject::hasInvolvedQuest. bot logic iterates and // emits QuestCompleteIntent for the first matching entry — no need // to round-trip the live world from the worker thread. using QuestTurnIn = Playerbot::QuestTurnIn; // Resolved quest offers: pairs of {giver_guid, quest_id} for nearby // questgivers that have a quest the bot doesn't yet hold and is - // eligible for. Same shape as quest_turnins. AI emits QuestAcceptIntent. + // eligible for. Same shape as quest_turnins. bot logic emits QuestAcceptIntent. // (quest_turnins / quest_offers migrated into quest_discovery below) // Bag items that start a quest the bot hasn't picked up yet (modern WoW // "letter from X" / "mysterious package" pickups). Each entry is the - // item entry + quest id; AI fires UseItemByEntryIntent to trigger the + // item entry + quest id; bot logic fires UseItemByEntryIntent to trigger the // pickup dialog and the snapshot's normal quest_offers accept path // takes it from there. Filtered by CanTakeQuest in the builder so we // don't surface items the bot can't actually start. @@ -2837,12 +2849,12 @@ struct BotSnapshot // scenario hasn't started a step yet. // * current_step_progress : count of completed criteria so far. using ScenarioStepInfo = Playerbot::ScenarioStepInfo; - // scenario_step lives inside quest_log. Keep the alias for AI callers + // scenario_step lives inside quest_log. Keep the alias for bot logic callers // that build a ScenarioStepInfo locally (e.g. /dungeon callouts). // Active group/master loot rolls awaiting the bot's vote — REFACTOR_2 // sub-struct. See LootRollsState / LootRollEntry above for per-row - // semantics. AI emits LootRollIntent. + // semantics. bot logic emits LootRollIntent. using LootRollEntry = Playerbot::LootRollEntry; LootRollsState loot{}; @@ -2912,7 +2924,7 @@ struct BotSnapshot // Returns this object to the exact state of a freshly default-constructed // BotSnapshot, but RETAINS the heap capacity of every inner container so // a subsequent Build() can refill without reallocating. The world thread - // calls this on the prior snapshot ONLY when use_count()==1 (no AI worker + // calls this on the prior snapshot ONLY when use_count()==1 (no bot worker // can still be reading it) — see BotSnapshotBuilder::Build. // // COMPLETENESS IS LOAD-BEARING: a member missed here leaks last tick's @@ -2934,6 +2946,7 @@ struct BotSnapshot owner_name.clear(); owner_guid = ObjectGuid::Empty; owner_in_group = false; + owner_dist = -1.0f; tactic_burn = false; tactic_save_mana = false; diff --git a/src/modules/PlayerbotV2/Bot/BotSnapshotBuilder.cpp b/src/modules/PlayerbotV2/Bot/BotSnapshotBuilder.cpp index 01e941da4f..4b0091a71f 100644 --- a/src/modules/PlayerbotV2/Bot/BotSnapshotBuilder.cpp +++ b/src/modules/PlayerbotV2/Bot/BotSnapshotBuilder.cpp @@ -1309,7 +1309,7 @@ bool InvTypeMatchesSlot(uint32 inv_type, uint8 slot) // idle:travel_to_hub). We probe the UnifiedTravelGraph with a throwaway // FindRoute and cache only the boolean verdict in BotAI keyed by the hub goal — // a POD the world thread owns exclusively, so (unlike the travel_plan_ vector, -// which the AI worker owns) there is no cross-thread race. The AI worker's +// which the bot worker owns) there is no cross-thread race. The bot worker's // travel-plan executor rebuilds the actual leg list itself when it runs. The // probe runs once per goal change, never per tick. // Does the travel graph reach (toMap,tx,ty,tz) from the bot's CURRENT position @@ -1560,7 +1560,7 @@ float TriggerCreatureZone(Creature const* c, uint32& out_spell) // snapshot buffer (reset_for_reuse() clears contents but KEEPS heap capacity), // so a recycled build does near-zero container allocations. // -// SAFETY GATE — the AI worker holds a shared_ptr copy of the published +// SAFETY GATE — the bot worker holds a shared_ptr copy of the published // snapshot for the duration of its tick (SnapshotPublisher stores it in an // atomic; latest() hands out a counted copy). A buffer is only // safe to overwrite when NO ONE else references it. We detect that with @@ -1598,6 +1598,7 @@ struct SnapRecyclePool { // Two retained buffers per bot. std::unordered_map, 2>> slots; + uint32 acquires_since_sweep = 0; // Returns a cleared, capacity-retaining buffer to build into. Prefers a // free (use_count==1) retained slot; otherwise allocates fresh. @@ -1606,8 +1607,12 @@ struct SnapRecyclePool // Opportunistic bound: if the map has grown large (bot churn / // never-pruned despawns), drop entries whose BOTH slots are free so // it can't grow without limit. Cheap amortised sweep, world thread. - if (slots.size() > 4096) + // Also every 2048 acquires: idle workers steal any map's batch, so each thread's pool came to hold buffers for most bots, and a + // logged-out world bot's stayed until the map passed 4096 entries, which a 3000-bot pool never reaches. A bot whose latest + // snapshot is still published keeps its entry (that slot is shared). + if (++acquires_since_sweep >= 2048 || slots.size() > 4096) { + acquires_since_sweep = 0; for (auto it = slots.begin(); it != slots.end(); ) { if ((!it->second[0] || it->second[0].use_count() == 1) && @@ -1779,7 +1784,7 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b // same self-cleaning behavior (clear on stop, re-anchor on move). bool moving = p->isMoving(); BotAI* mc_ai = bot_ai; - // Fall back to a local anchor when the AI can't be resolved; without + // Fall back to a local anchor when the bot logic can't be resolved; without // persistent state the wedge-corroboration simply trusts the flag, // which is the safe default (matches a fresh map entry). BotAI::MoveCorroborate local_anchor{}; @@ -1811,7 +1816,7 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b mc_ai->clear_move_corroborate(); snap->movement.is_moving = moving; } - // UNIT_STATE_IN_FLIGHT — the core is flying the bot on a taxi path. The AI + // UNIT_STATE_IN_FLIGHT — the core is flying the bot on a taxi path. The bot logic // must stand down entirely (DispatchIdle bails) so no idle/unstick/watchdog // rule fires a move_to or teleport that would corrupt the flight spline. snap->movement.is_in_taxi = p->IsInFlight(); @@ -2034,7 +2039,7 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b } } snap->travel.best_mount_spell = best_sid; - // [mount_pick] (Karrz, AV 2026-10-11: are the 60s on the 100% mount?). One line when the pick changes: the mount, the riding + // [mount_pick] (playtest, AV 2026-10-11: are the 60s on the 100% mount?). One line when the pick changes: the mount, the riding // skill, and whether the bot holds the two mount-speed passives (86457 = 60%, 86458 = 100%) and its race's epic mount. if (mt_ai && best_sid != mt_ai->cached_best_mount_spell() && p->GetLevel() >= 40) { @@ -2072,7 +2077,7 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b // removes a shared-map data-race surface with zero behavior change. // combat_*_ms()==0 means "not timing" / "never left", exactly as a // missing map entry did. Fall back to local scalars if the registry - // can't resolve the AI (mirrors every other ai() use-site here). + // can't resolve the bot logic (mirrors every other ai() use-site here). BotAI* ct_ai = bot_ai; int64_t local_start = 0, local_exit = 0; if (snap->vitals.in_combat) @@ -2136,7 +2141,7 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b // Death recovery: ghost flag, corpse position, reclaim window, and the // corpse-to-graveyard distance State_Dead reads to choose between // corpse-run (no sickness, slow) and spirit-healer (sickness, instant). - // Computed inline because the snapshot is a value type — the AI worker + // Computed inline because the snapshot is a value type — the bot worker // can't safely walk Map / ObjectMgr lookups on its thread. snap->death.is_ghost = p->HasPlayerFlag(PLAYER_FLAGS_GHOST); snap->death.has_corpse = p->HasCorpse(); @@ -2349,7 +2354,7 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b } } // Owner character name for mat-share mail. Resolved once per snapshot - // via OwnerRegistry → CharacterCache so the AI worker doesn't need to + // via OwnerRegistry → CharacterCache so the bot worker doesn't need to // round-trip those services. Empty string when bot is unowned, or when // it is bound to a whole account (`.playerbot adopt`) and nobody on that // account is online. Without the account case an adopted bot had no @@ -2472,7 +2477,7 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b // Goblin=7). Bots typically only post in their faction's house but might // have legacy postings elsewhere from cross-faction visits, so we walk // them all. Per-bot cap matches the live cap of a few hundred — we don't - // truncate, and the AI has constant-time access via the snapshot copy. + // truncate, and the bot logic has constant-time access via the snapshot copy. { const ObjectGuid me = p->GetGUID(); const time_t now = GameTime::GetGameTime(); @@ -2890,7 +2895,7 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b // multiple slots, so accumulate (FlatCountMap::add defers the sum to // finalize()). Tier 3.3: was unordered_map[entry] += count. snap->inventory.bag_count_by_entry.add(ii.entry, ii.count); - // Aggregate consumable-class counts so AI can decide "do I have enough + // Aggregate consumable-class counts so bot logic can decide "do I have enough // food?" without re-resolving ItemTemplate on the worker thread. // Stack count per item — a single 5-stack of food bumps food_drink_count // by 5, matching how MaintainOocFood uses one charge per use. @@ -3241,6 +3246,8 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b // Classic 1.60 ammo (the hunter's "no ammo" / "low ammo" lines). Every arrow or bullet stack // the equipped weapon can shoot counts: Player::AutoSelectAmmo moves on to the next stack. + if (Item const* worn_ranged = p->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED)) + snap->consumables.ranged_subclass = uint8(worn_ranged->GetTemplate()->GetSubClass()); if (p->NeedsAmmo()) { Item const* ranged = p->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED); @@ -3316,6 +3323,9 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b { snap->group.group_guid = g->GetGUID(); snap->owner_in_group = !snap->owner_guid.IsEmpty() && g->IsMember(snap->owner_guid); + if (snap->owner_in_group) + if (Player const* owner = ObjectAccessor::FindConnectedPlayer(snap->owner_guid); owner && owner->GetMapId() == p->GetMapId()) + snap->owner_dist = p->GetExactDist2d(owner); } // ---- Spellbook (sorted, binary-searchable in BotSnapshotView::knows_spell) ---- @@ -3741,7 +3751,8 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b auto& cds = snap->cooldowns.spell_cooldowns; for (auto const& bi : snap->inventory.bag_items) { - if (bi.item_class != ITEM_CLASS_CONSUMABLE) continue; + // The Demonic Rune is filed under Trade Goods / Other (class 7, subclass 11), and its cooldown is published like a potion's. + if (bi.item_class != ITEM_CLASS_CONSUMABLE && !(bi.item_class == ITEM_CLASS_TRADE_GOODS && bi.item_subclass == ITEM_SUBCLASS_TRADE_GOODS_OTHER)) continue; ItemTemplate const* tmpl = sObjectMgr->GetItemTemplate(bi.entry); if (!tmpl) continue; for (ItemEffectEntry const* eff : tmpl->Effects) @@ -3796,7 +3807,7 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b snap->cast.last_cast_spell_id = lc_ai->last_cast_spell_id(); // ---- Threat discipline context ---- - // Port of Karrz's group threat rules (ike3-based bots MCRaidHoldDamage / + // Port of the owner's group threat rules (wow-1.12 MCRaidHoldDamage / // LooseAttackersTrigger). Resolve the group's live same-map members and // tanks once, then stamp every attacker / nearby enemy below with the // bot's threat, the best tank threat and who the mob is hitting, read @@ -4598,6 +4609,10 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b // HasUnitFlag check read false and the bot still engaged it. The // template flag is the reliable signal for these static props. u.is_pacified = c->HasUnitFlag(UNIT_FLAG_PACIFIED); + { + MovementGeneratorType const mt = c->GetMotionMaster()->GetCurrentMovementGeneratorType(); + u.is_fleeing = mt == FLEEING_MOTION_TYPE || mt == TIMED_FLEEING_MOTION_TYPE || mt == ASSISTANCE_MOTION_TYPE; + } // Uninteractible (NOT_SELECTABLE): unkillable, unacquirable hazard // stalkers. Engage/pull rules skip these; the in-combat advance // walks the tank through them. See NearbyUnit + the harbor note. @@ -4657,7 +4672,7 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b int best_cc_pri = -1; // Affix-buff whitelist — small static list of POSITIVE buff // aura ids we surface on NearbyUnit.affix_buffs so the - // dungeon AI can react to M+ Bolstering and similar mob- + // dungeon bot logic can react to M+ Bolstering and similar mob- // empowering affixes without a generic per-unit auras dump. // Extend as more "mob carries this buff → adjust pull rule" // mechanics get wired. @@ -4697,7 +4712,12 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b const int32 age = (abase->IsPermanent() || maxd <= 0) ? std::numeric_limits::max() : std::max(0, maxd - abase->GetDuration()); - if (u.magic_buff_age_ms < 0 || age < u.magic_buff_age_ms) + // Majordomo's Magic Reflection / Damage Shield stop the whole raid from hitting an add until they are stripped: + // they come first, whatever younger buff the add carries (n32 mc_majordomo: the purgers took 12579 / 17794 off the + // Healers seven times and never the shield). + bool const shield = asi->Id == 20619 || asi->Id == 21075; + bool const shield_held = u.magic_buff_spell == 20619 || u.magic_buff_spell == 21075; + if (shield || (!shield_held && (u.magic_buff_age_ms < 0 || age < u.magic_buff_age_ms))) { u.magic_buff_age_ms = age; u.magic_buff_spell = asi->Id; @@ -4852,7 +4872,7 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b u.combat_reach = t->GetCombatReach(); if (Unit const* v = t->GetVictim()) u.victim = v->GetGUID(); - // Capture npc_flags for friendly Creatures so AI can find + // Capture npc_flags for friendly Creatures so bot logic can find // vendors/repairers/bankers/trainers/flightmasters/innkeepers // by capability (vs by entry id). Players keep npc_flags=0. if (Creature const* c = t->ToCreature()) @@ -5291,7 +5311,7 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b // are turn-in-ready or only contain implicit objectives (LEARNSPELL, // MIN_REPUTATION, AREATRIGGER without coords, etc). { - // bot_ai is the build-target's pre-resolved AI (function parameter). + // bot_ai is the build-target's pre-resolved bot logic (function parameter). const uint32 now_ms = GameTime::GetGameTimeMS(); const uint32 bot_map = p->GetMapId(); // Track best-eligible "any" + best-eligible "same-map" candidates. @@ -5845,7 +5865,7 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b uint64(best_breadcrumb_sm_set ? best_breadcrumb_sm_quest : 0u); // Per-bot log-dedup signature lives on the bot's own BotAI // (Phase 4 parallel-by-Map*): formerly a process-wide BotId-keyed - // static map, now single-writer per worker. When the AI can't be + // static map, now single-writer per worker. When the bot logic can't be // resolved we emit unconditionally (correct, just not deduped). BotAI* pc_ai = bot_ai; const uint64 last_sig = pc_ai ? pc_ai->picker_choice_log_sig() : (pc_sig ^ 1ull); @@ -5900,6 +5920,18 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b bool has_complete = false; for (auto const& dq : snap->quest_log.quests) if (dq.state == 1) { has_complete = true; break; } + // At most one dump per bot per minute (per build thread): a bot parked on a complete quest wrote it on every build, which + // made [picker_none] 79% of the log at 85-150 bots and pushed every other diagnostic out of the rotation. + if (has_complete) + { + thread_local std::unordered_map s_picker_none_ms; + uint32 const pn_now = snap->published_at_ms ? snap->published_at_ms : 1u; + uint32& pn_last = s_picker_none_ms[snap->guid.GetCounter()]; + if (pn_last && pn_now - pn_last < 60000u) + has_complete = false; + else + pn_last = pn_now; + } if (has_complete) { TC_LOG_INFO("playerbot.v2", @@ -6658,7 +6690,7 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b // ---- Stuck-by-terrain tracker update ---- // Detects bots wedged on geometry pursuing an unreachable target. Per-bot - // state lives on BotAI (so the AI worker reads/writes; world thread here + // state lives on BotAI (so the bot worker reads/writes; world thread here // only updates with the latest movement goal + distance). // // Goal selection priority: current_objective_poi > nearest quest_turnin @@ -7137,7 +7169,7 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b // Walks nearby_friends + nearby_objects on the world thread (where // we have safe access to the live Creature / GameObject ptrs) and // tags each (giver, quest_id) pair where the giver accepts the quest's - // turn-in. Lets AI in worker threads emit complete_quest with the + // turn-in. Lets bot logic in worker threads emit complete_quest with the // pre-resolved guid rather than guessing per-NPC. { std::vector complete_q; @@ -7181,7 +7213,7 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b // Quest offers: walk nearby creatures + GOs and surface any quest // they offer that the bot doesn't have. CanTakeQuest filters by // level / class / race / faction / prereq + quest log capacity. - // We cap surfaced offers per snapshot (the AI only acts on the + // We cap surfaced offers per snapshot (the bot logic only acts on the // first per tick; surfacing more is a small DB read but no // executor cost). constexpr size_t MAX_OFFERS = 16; @@ -7472,7 +7504,7 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b if (u.npc_flags & kQuestGiverFlagMask) ++giver_npc_count; for (auto const& o : snap->world_objects.nearby_objects) if (o.go_type == GAMEOBJECT_TYPE_QUESTGIVER) ++giver_go_count; - // Throttle to once per 5s per bot via the AI's last-scan + // Throttle to once per 5s per bot via the bot logic's last-scan // timestamp so we don't spam every snapshot publish. if (offer_bot_ai) { @@ -7594,13 +7626,13 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b } // ---- Active loot rolls ---- - // Surface in-flight group/master rolls so AI can vote without being + // Surface in-flight group/master rolls so bot logic can vote without being // event-driven. LootRoll exposes loot_obj + list_id + vote mask via // the Playerbot accessors we added on the core side. is_upgrade // pre-computes whether the roll item is a strict ilvl upgrade for any // equipped slot of matching inventory type (or fills an empty slot). { - // Loot etiquette (Karrz's LootRollAction IsInstanceGroupWithHuman / + // Loot etiquette (the owner's LootRollAction IsInstanceGroupWithHuman / // HumanWouldWantItem): the humans of the bot's group on its map get // first claim. Only gathered when a roll is waiting. std::vector humans; @@ -7755,7 +7787,7 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b if (eq.entry == 0) { // Empty matching-invtype slot: an upgrade - // (Karrz: need for an empty slot), but never a + // (the owner: need for an empty slot), but never a // cosmetic shirt or tabard. // An empty off hand is no reason to need a // one-hander the bot can't wield there (no dual @@ -7779,7 +7811,7 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b if (!eq_tmpl) continue; const float eq_score = score_block(eq.stats, eq.item_level); // A real upgrade beats the worn item by at least - // 5% (Karrz); side-grades are greed. + // 5% (the owner); side-grades are greed. const float margin = std::max(1.f, eq_score * 0.05f); if (roll_score >= eq_score + margin) { @@ -7796,7 +7828,7 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b // ---- Mail ---- // Snapshot the bot's mail vector. Player::GetMails() includes both - // delivered and pending-deliver mails; we publish all and let the AI + // delivered and pending-deliver mails; we publish all and let the bot logic // gate on `deliver_in_sec <= 0`. Skipping deleted entries because the // server flushes them on _SaveMail; surfacing them would cause // mail_delete intents to retry against rows that are already gone. @@ -7850,7 +7882,7 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b for (GameObject* go : scratch_gos) { if (!go) continue; - // Filter to types AI actually drives. Skip everything else to + // Filter to types bot logic actually drives. Skip everything else to // keep the vector bounded — chairs, transports, etc would // dominate the cap in major cities. GATHERING_NODE (50) is the // modern herbalism/mining node type — without it in the @@ -7880,7 +7912,7 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b // the static portal GO; TRANSPORT (11) is mooring rooms / // elevators / etc; MO_TRANSPORT (15) is the seafaring // ships and zeppelins that move between continents. The - // builder pre-resolves their destinations so the AI can + // builder pre-resolves their destinations so the bot logic can // walk to them and use/board. t == GAMEOBJECT_TYPE_SPELLCASTER || t == GAMEOBJECT_TYPE_TRANSPORT || @@ -8032,7 +8064,7 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b } } // Continental transport (ship / zeppelin). Same teleport_dest - // semantics: AI walks to the transport, server auto-attaches + // semantics: bot logic walks to the transport, server auto-attaches // the bot as a passenger when the bounding box overlaps, the // transport carries them across maps, and the bot's same-map // rules pick up at the destination dock. We populate the @@ -8062,7 +8094,7 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b n.teleport_dest_map = map_id; // No exact dest coords — the transport drops // the passenger at its dock spawn, which the - // AI doesn't strictly need to plan; we just + // Bot logic doesn't strictly need to plan; we just // need to know "this transport reaches the // goal map". break; @@ -8077,7 +8109,7 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b // walkable board/disembark LEDGES (nearest navmesh poly beside each // platform-centre). Cheap after the first encounter — every stop's // result is cached in ElevatorIndex. The elevator rules then read the - // ledge via ElevatorIndex::LedgeFor on the AI worker. + // ledge via ElevatorIndex::LedgeFor on the bot worker. else if (n.go_type == GAMEOBJECT_TYPE_TRANSPORT) { // Derive ledges for the WHOLE nearby lift cluster (not just this @@ -9326,7 +9358,7 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b // ---- bg_role: per-slot role from the active BattlegroundScript ---- // Mirrors the slot→role resolution in State_Idle.cpp BgDispatch so // the snapshot field agrees with the role the bot will actually - // execute this tick. Reads the IMMUTABLE advice copy the AI worker + // execute this tick. Reads the IMMUTABLE advice copy the bot worker // publishes after each cache rebuild (BotAI::published_bg_advice — // adversarial review 2026-06-10: reading the worker-owned // BgAdviceCache directly from this world-thread code raced its @@ -9410,7 +9442,7 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b // the build WORKER threads. The OrderFor read is race-free because it is // temporally disjoint from the write — orders_ is immutable for the whole // build phase (see BgTeamCoordinator.h threading contract). No plan entry - // leaves order.kind == None and the AI falls back to per-bot role logic. + // leaves order.kind == None and the bot logic falls back to per-bot role logic. if (Services::Initialized()) if (auto const* ord = Services::BgCoordinator().OrderFor( p->GetGUID().GetCounter())) @@ -9880,7 +9912,7 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b } } - // Publish the probe's VALIDATED route legs to the snapshot so the AI + // Publish the probe's VALIDATED route legs to the snapshot so the bot logic // worker executes THIS route instead of recomputing one. The worker's own // FindRoute runs with validate_source_walk=false (the default — the costly // live-navmesh probe is reserved for known-wedged bots here), so for a bot @@ -10099,7 +10131,7 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b // ---- Nearest cross-map portal/transport anchor ---- // When the bot has a current quest goal on a different map, ask the // global PortalIndex for the closest static portal or ship-dock on - // the bot's current map that reaches the goal map. The AI rule + // the bot's current map that reaches the goal map. The bot logic rule // (idle:walk_to_known_portal) walks the bot toward this anchor; once // within 30 y the SPELLCASTER/TRANSPORT GO becomes visible in // nearby_objects and the in-range rules (use_portal / @@ -10223,7 +10255,7 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b } // ---- Homebind ---- - // Snapshot the bot's bind point so the AI can decide cross-continent + // Snapshot the bot's bind point so the bot logic can decide cross-continent // hearth (when goal is on a different map but homebind is on the goal's // map, hearth saves a flight + walk). Player::m_homebind.GetMapId() is // 0 on a freshly-created character before login, but that's gated by @@ -10347,6 +10379,7 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b // this the bot has no way to know who its pet is fighting. if (Unit const* pv = pet->GetVictim()) snap->pet.pet_victim = pv->GetGUID(); + snap->pet.pet_react = uint8(pet->GetReactState()); // Pet attackers — feeds the peel branch of assist_pet. When the // pet's victim is mob A but mob B (a caster) is hammering the // pet from range, the rule prefers B so the bot peels instead @@ -10415,7 +10448,7 @@ std::shared_ptr BotSnapshotBuilder::Build(Player* p, BotAI* b // their consumers land. Threat list / attackers come with PerceptionBuilder.) // Path-block telemetry — surface BotAI's monotonic path-blocked count - // + last-block timestamp so AI worker rules can detect anchor wedge + // + last-block timestamp so bot worker rules can detect anchor wedge // and fall through without dereferencing BotAI directly. Captured at // build-end so any path failures during the build window are // included. diff --git a/src/modules/PlayerbotV2/Bot/BotSnapshotBuilder.h b/src/modules/PlayerbotV2/Bot/BotSnapshotBuilder.h index d871088113..9049c2d41f 100644 --- a/src/modules/PlayerbotV2/Bot/BotSnapshotBuilder.h +++ b/src/modules/PlayerbotV2/Bot/BotSnapshotBuilder.h @@ -29,7 +29,7 @@ public: // pointer. Resolving once on the world thread (where the registry is // quiescent w.r.t. this tick) eliminates that race while keeping behavior // byte-identical (same pointer, resolved once instead of ~32 times). May be - // null if the bot has no registered AI (Build tolerates a null bot_ai + // null if the bot has no registered bot logic (Build tolerates a null bot_ai // everywhere it is used). static std::shared_ptr Build(Player* p, BotAI* bot_ai, SnapshotVer next_version, TickId tick); }; diff --git a/src/modules/PlayerbotV2/Bot/BotSnapshotView.cpp b/src/modules/PlayerbotV2/Bot/BotSnapshotView.cpp index 49556b0b7c..13302977f3 100644 --- a/src/modules/PlayerbotV2/Bot/BotSnapshotView.cpp +++ b/src/modules/PlayerbotV2/Bot/BotSnapshotView.cpp @@ -11,6 +11,8 @@ #include #include #include +#include +#include #include #include #include @@ -172,6 +174,18 @@ bool BotSnapshotView::is_ready(uint32 spell_id) const if (power(uint8(pw->PowerType)) < cost) return false; } + // Mana: not ready when even the cheapest rank the bot knows costs more than it has (live Deadmines 2026-10-14: a level 14 shaman + // sent Lightning Shield and Healing Wave 14 times in 10 s, NO_POWER every time). The cheapest rank, not the one requested, so + // a healer that downranks to save mana still gets its cast; the DB2 cost is the untalented one, so a discounted cast waits a few + // points longer than the core would need - never fires early. + if (int32 cheapest = mana_cost(spell_id); cheapest > 0) + { + for (uint32 const r : known_ranks(spell_id)) + if (int32 const c = mana_cost(r); c > 0 && c < cheapest) + cheapest = c; + if (power(POWER_MANA) < cheapest) + return false; + } auto cd = FindCooldownIndexed(s_->cooldowns, spell_id); if (!cd) return true; if (cd->charges > 0) return true; @@ -765,7 +779,7 @@ BotSnapshotView::ThreatHold BotSnapshotView::threat_hold(ObjectGuid target, floa switch (ThreatVictim(u->victim_kind)) { // Self-defence: the mob is already hitting this bot or another - // non-tank member - everyone fights (Karrz: "nobody holds back"). + // non-tank member - everyone fights (the owner: "nobody holds back"). case ThreatVictim::Me: case ThreatVictim::Member: // Someone outside the group: not our tank's fight. @@ -835,14 +849,39 @@ NearbyUnit const* BotSnapshotView::assigned_tank_mob() const // target_reach: `range` is a spell's range, measured to the target's combat reach (Spell::GetMinMaxRange), so a big mob counts as in reach // from further off (MC Garr 2026-10-10: Firesworn 5-6 y from a tank, Taunt reach 4 y centre to centre, never taunted). // leash: the mob is walked to (a pickup chases it), so with a human owner in the group inside an instance it must stand within -// kPickupLeashYd of the owner; a tank that chased every mob on every member dragged the fight away from him (Karrz, Deadmines +// kPickupLeashYd of the owner; a tank that chased every mob on every member dragged the fight away from him (playtest, Deadmines // 2026-10-10: pickups 25-30 y out moved the melee spot 50 y from the group in four pulls). A taunt does not move the tank and is // not leashed. The owner is read from the friend sweep; out of it (or no owner) there is no leash. static constexpr float kPickupLeashYd = 25.0f; +// A 5-man tank keeps the fight where its healer can see it: the point (x, y) is further than kHealerLeashYd from every healer in the +// friend sweep (a heal reaches 40 y; the rest is the margin for the line of sight and a step). No healer in the sweep, no leash. +// Deadmines 2026-10-15 n43 run 6: the tank followed a held Goblin Engineer 20 y out of the room, the healers had no sight line at +// 29-42 y, and the tank died there with the priest unable to cast. +static constexpr float kHealerLeashYd = 30.0f; +static bool BeyondHealerLeash(BotSnapshot const& s, float x, float y) +{ + if (!s.instance_ctx.is_in_dungeon || s.instance_ctx.is_in_raid) + return false; + bool any_healer = false; + for (auto const& f : s.combat.nearby_friends) + { + if (f.role != Role::Healer || f.hp <= 0 || f.guid == s.guid) continue; + any_healer = true; + const float hx = x - f.x, hy = y - f.y; + if (hx * hx + hy * hy <= kHealerLeashYd * kHealerLeashYd) + return false; + } + return any_healer; +} + // A loose mob nobody was assigned goes to ONE tank: the nearest idle one that this bot's friend sweep shows (a tank busy with a // mob of its own is no contender; ties go to the lower guid). Without it every tank without an assignment ran at the same mob and // they taunted it back and forth (MC 2026-10-11: [tank_loose] from several tanks on one Firewalker, "claimed by another tank 0"). +// The nearer tank counts only while it can take the mob: within the pickup reach (n24 mc_garr: an idle tank 40 y off was the "nearest", every +// other idle tank deferred to it and a Firesworn stood 7 y from Mctankwb on a healer for a minute). +static constexpr float kOtherTankReachYd = 30.0f; + static bool OtherTankTakesLoose(BotSnapshot const& s, NearbyUnit const& mob) { const float mdx = mob.x - s.position.x, mdy = mob.y - s.position.y; @@ -856,12 +895,38 @@ static bool OtherTankTakesLoose(BotSnapshot const& s, NearbyUnit const& mob) if (busy) continue; const float dx = mob.x - f.x, dy = mob.y - f.y; const float theirs = dx * dx + dy * dy; + if (theirs > kOtherTankReachYd * kOtherTankReachYd) continue; if (theirs < mine || (theirs == mine && f.guid < s.guid)) return true; } return false; } +// How long a mob has stood on a group member without a tank on it (ms). The plan's claim on a mob (PveOrder::claimed_by_other_tanks) is +// "its owner is on the way"; once the mob has been on a member for kClaimStaleMs the owner is not (n24 mc_garr: Firesworn killed seven +// mages and healers while their claimed tanks held another mob), and any tank may take it. Mob-level state shared by all bots, written +// only while the mob is seen loose; a gap of kLooseGapMs starts it again. +static constexpr uint32 kClaimStaleMs = 3000; +static constexpr uint32 kLooseGapMs = 1500; +static uint32 LooseOnMemberMs(ObjectGuid mob, uint32 now) +{ + struct Seen { uint32 since; uint32 last; }; + static std::mutex mtx; + static std::unordered_map seen; + std::lock_guard lock(mtx); + if (seen.size() > 512) + for (auto it = seen.begin(); it != seen.end();) + it = now - it->second.last > 10'000u ? seen.erase(it) : std::next(it); + auto [it, fresh] = seen.try_emplace(mob.GetCounter(), Seen{ now, now }); + if (!fresh) + { + if (now - it->second.last > kLooseGapMs) + it->second.since = now; + it->second.last = now; + } + return now - it->second.since; +} + static NearbyUnit const* UnclaimedLooseAttacker(BotSnapshot const& s, float range, bool target_reach = false, bool leash = false) { NearbyUnit const* best = nullptr; @@ -875,8 +940,17 @@ static NearbyUnit const* UnclaimedLooseAttacker(BotSnapshot const& s, float rang { if (e.hp <= 0 || e.is_player || e.untargetable || e.is_pacified) continue; if (ThreatVictim(e.victim_kind) != ThreatVictim::Member) continue; - if (s.pve_order.active && s.pve_order.claimed_by_other_tank(e.guid)) continue; + if (s.pve_order.active && s.pve_order.claimed_by_other_tank(e.guid) && LooseOnMemberMs(e.guid, s.published_at_ms) < kClaimStaleMs) continue; if (OtherTankTakesLoose(s, e)) continue; + if (leash && BeyondHealerLeash(s, e.x, e.y)) + { + static std::atomic s_hleash_log{ 0 }; + uint32 last = s_hleash_log.load(std::memory_order_relaxed); + if (s.published_at_ms - last >= 5000u && s_hleash_log.compare_exchange_strong(last, s.published_at_ms)) + TC_LOG_INFO("playerbot.v2", "[tank_leash] {} leaves entry {} alone: further than {:.0f} y from every healer; no pickup chase", + s.identity.name, e.entry, kHealerLeashYd); + continue; + } if (owner_unit) { const float ox = e.x - owner_unit->x, oy = e.y - owner_unit->y; @@ -936,6 +1010,20 @@ NearbyUnit const* BotSnapshotView::taunt_candidate(float range) const return UnclaimedLooseAttacker(*s_, range, /*target_reach=*/true); } +bool BotSnapshotView::claim_blocks(NearbyUnit const& u) const +{ + if (!s_->pve_order.active || !s_->pve_order.claimed_by_other_tank(u.guid)) + return false; + if (ThreatVictim(u.victim_kind) != ThreatVictim::Member) + return true; + return LooseOnMemberMs(u.guid, s_->published_at_ms) < kClaimStaleMs; +} + +bool BotSnapshotView::beyond_healer_leash(float x, float y) const +{ + return BeyondHealerLeash(*s_, x, y); +} + NearbyUnit const* BotSnapshotView::pickup_candidate() const { if (NearbyUnit const* a = assigned_tank_mob()) @@ -1026,7 +1114,7 @@ MailEntry const* BotSnapshotView::next_drainable_mail() const // owner to handle manually. if (m.cod > 0) continue; // Returned mails sit in the bot's box but can't be re-returned; - // include them — the AI may still want to delete or take items + // include them — the bot logic may still want to delete or take items // (returns from auctions land here too). if (m.money > 0 || m.item_count > 0) return &m; } diff --git a/src/modules/PlayerbotV2/Bot/BotSnapshotView.h b/src/modules/PlayerbotV2/Bot/BotSnapshotView.h index 2a8cb84373..ee972809ba 100644 --- a/src/modules/PlayerbotV2/Bot/BotSnapshotView.h +++ b/src/modules/PlayerbotV2/Bot/BotSnapshotView.h @@ -95,13 +95,19 @@ public: bool tactic_save_mana() const { return s_->tactic_save_mana; } // owner "save mana" // A companion may sit down to eat or drink only when its owner has stopped next to it: otherwise the group follow // stands it up again at the next step and the next stop costs another item. + // In a raid the group stands spread over 30-40 y round the owner (formation, spacing), so "next to it" is the raid's own reach + // (playtest, live MC 2026-10-12: raid bots stood waiting on mana regen and never sat; a 10 y mark kept every bot past the first + // rank from ever drinking). bool companion_may_sit() const { if (!s_->owner_in_group) return true; float x, y, z; position(x, y, z); + float const reach = is_in_raid() ? 45.0f : 10.0f; + if (s_->owner_dist >= 0.0f) + return s_->owner_dist <= reach; for (auto const& u : s_->combat.nearby_friends) if (u.guid == s_->owner_guid) - return (u.x - x) * (u.x - x) + (u.y - y) * (u.y - y) <= 10.0f * 10.0f; + return (u.x - x) * (u.x - x) + (u.y - y) * (u.y - y) <= reach * reach; return false; } bool has_duel_request() const { return s_->social_events.has_duel_request; } @@ -143,6 +149,7 @@ public: // Classic ammo: 0 = nothing to shoot ammo with, 1 = arrows, 2 = bullets; count of usable ones in bags. uint8 ammo_kind() const { return s_->consumables.ammo_kind; } uint32 ammo_count() const { return s_->consumables.ammo_count; } + uint8 ranged_subclass() const { return s_->consumables.ranged_subclass; } int32 hp() const { return s_->vitals.hp; } int32 max_hp() const { return s_->vitals.max_hp; } // int64 intermediate prevents overflow at high HP pools — modern raid @@ -203,7 +210,7 @@ public: // True if `spell_id` can be cast while moving (instant cast OR no // Movement interrupt flag). Looked up from SpellInfo via the global // SpellMgr — that data is read-only after init, so the call is safe - // from AI worker threads. APL rules pair this with `is_moving()` to + // from bot worker threads. APL rules pair this with `is_moving()` to // gate hard-cast spells: `if (s.is_moving() && !s.can_cast_while_moving(SP)) return false;`. // Returns true when the spell is unknown (no filtering — let the cast // attempt and its server-side gates decide). @@ -369,7 +376,7 @@ public: // threat-grab behavior. Returns nullptr if every nearby enemy is on us. NearbyUnit const* untaunted_enemy(float range = 30.f) const; - // ---- Threat discipline (port of Karrz's ike3-based bots group threat rules) ---- + // ---- Threat discipline (port of Karrz's wow-1.12 group threat rules) ---- // The attacker / nearby-enemy record for `guid` (attackers first), or null. NearbyUnit const* hostile_unit(ObjectGuid guid) const; // Group's tank as resolved by the builder (may be this bot). Empty when @@ -385,11 +392,11 @@ public: // this bot or another non-tank member (self-defence) or someone outside // the group. Role, map-type and config gating are the CALLER's job, as // is the opening-wait timeout. - enum class ThreatHold : uint8 { None, TankOpening, OverThreat }; + enum class ThreatHold : uint8 { None, TankOpening, OverThreat, ShieldUp }; ThreatHold threat_hold(ObjectGuid target, float opening_lead, float max_ratio) const; // Tank helper (LooseAttackersTrigger): nearest live enemy within `range` // whose victim is a NON-TANK group member - the mobs a tank must taunt - // or pick up. loose_attackers_within counts them (Karrz: Challenging + // or pick up. loose_attackers_within counts them (the owner: Challenging // Shout / Roar at 3+ within 10y). NearbyUnit const* loose_attacker(float range = 30.f) const; size_t loose_attackers_within(float range) const; @@ -403,6 +410,12 @@ public: NearbyUnit const* assigned_tank_mob() const; NearbyUnit const* taunt_candidate(float range) const; NearbyUnit const* pickup_candidate() const; + // 5-man only: (x, y) lies further than 30 y from every healer in the friend sweep (false with no healer in it). A tank does not + // walk after a mob there. + bool beyond_healer_leash(float x, float y) const; + // The raid plan gave this mob to another tank AND that claim still holds: a claimed mob that has stood on a group member for a few + // seconds is not being picked up by its owner, so any tank may take it. + bool claim_blocks(NearbyUnit const& u) const; // Directional look-ahead. Returns the closest threatening hostile // creature inside a `half_width`-yard corridor from the bot's @@ -693,7 +706,7 @@ public: bool has_drainable_mail() const; MailEntry const* next_drainable_mail() const; - // Taxi — has the bot visited / been granted node `node_id`? Lets AI + // Taxi — has the bot visited / been granted node `node_id`? Lets bot logic // gate fly_to_node intents on pre-known endpoints rather than // catching the Result::Locked rebound. node_id is a TaxiNodes.dbc id. bool is_taxi_node_known(uint32 node_id) const @@ -706,7 +719,7 @@ public: // Recommended taxi route accessors — populated by the snapshot builder // when the bot has a long-distance same-map goal and a viable known-FM // → known-FM route exists. has_recommended_taxi_route() reflects "≥2 - // hops, both endpoints known"; the AI rule walks to the start FM and + // hops, both endpoints known"; the bot logic rule walks to the start FM and // emits fly_to_node(start_fm, dest_node) on arrival. ObjectGuid recommended_taxi_start_fm() const { return s_->travel.recommended_taxi_start_fm; } uint32 recommended_taxi_dest_node() const { return s_->travel.recommended_taxi_dest_node; } @@ -729,7 +742,7 @@ public: // Nearest known cross-map travel anchor. Builder fills from the // global PortalIndex when the bot has a cross-map goal; empty - // otherwise. AI uses these to walk toward the portal/dock from + // otherwise. bot logic uses these to walk toward the portal/dock from // anywhere on the source map (the GO itself is invisible past 30 y // so we can't rely on nearby_objects for the long-distance leg). bool has_nearest_portal_anchor() const @@ -802,7 +815,7 @@ public: // destination map (Mage Teleport: City, DK Death Gate, Druid // Teleport: Moonglade, etc). Builder pre-resolves each spell's // dest map via spell_target_position so this is a cheap snapshot - // scan with no DB lookups on the AI worker. + // scan with no DB lookups on the bot worker. std::vector const& self_teleport_spells() const { return s_->travel.self_teleport_spells; } @@ -886,7 +899,7 @@ public: std::vector const& bg_all_enemy_carriers() const { return s_->bg.all_enemy_carriers; } - // Bank capacity. AI uses bank_free_slots() == 0 to skip deposit attempts; + // Bank capacity. bot logic uses bank_free_slots() == 0 to skip deposit attempts; // bank_tab_count() lets the "buy a bank tab" rule fire when the bot // has gold and < 4 tabs. uint8 bank_tab_count() const { return s_->bank.bank_tab_count; } @@ -998,6 +1011,7 @@ public: std::string const& pet_name() const { return s_->pet.pet_name; } bool pet_can_bloodlust() const { return s_->pet.pet_can_bloodlust; } ObjectGuid pet_victim() const { return s_->pet.pet_victim; } + uint8 pet_react() const { return s_->pet.pet_react; } std::vector const& pet_attackers() const { return s_->pet.pet_attackers; } AuraEntry const* find_pet_aura(uint32 spell_id) const; std::vector const& stable_pets() const { return s_->pet.stable_pets; } @@ -1096,7 +1110,7 @@ private: // builder stores outbound auras as compact OutboundAura rows, but // find_aura must return an AuraEntry const*. Materialising the matched // row here — instead of a reused thread_local — keeps every returned - // pointer valid for the whole lifetime of this view (one AI tick), so a + // pointer valid for the whole lifetime of this view (one bot tick), so a // caller holding two find_aura results (or calling again before using // the first) never sees aliased/overwritten data. std::deque is chosen // because it never invalidates existing element pointers on push_back, diff --git a/src/modules/PlayerbotV2/Bot/BotTextMgr.cpp b/src/modules/PlayerbotV2/Bot/BotTextMgr.cpp index c718c5e68b..84fc83879b 100644 --- a/src/modules/PlayerbotV2/Bot/BotTextMgr.cpp +++ b/src/modules/PlayerbotV2/Bot/BotTextMgr.cpp @@ -51,16 +51,16 @@ BotTextMgr& BotTextMgr::instance() void BotTextMgr::Load() { - enabled_ = sConfigMgr->GetBoolDefault("Playerbot.Chatter.Enabled", true); - chance_scale_ = std::max(0.0f, sConfigMgr->GetFloatDefault("Playerbot.Chatter.ChanceScale", 1.0f)); - group_cooldown_ms_ = uint32(std::max(0, sConfigMgr->GetIntDefault("Playerbot.Chatter.GroupCooldownMs", 20000))); - bot_cooldown_ms_ = uint32(std::max(0, sConfigMgr->GetIntDefault("Playerbot.Chatter.BotCooldownMs", 60000))); + enabled_ = sConfigMgr->GetBoolDefault("Playerbot.Chatter.Enabled", true, true); + chance_scale_ = std::max(0.0f, sConfigMgr->GetFloatDefault("Playerbot.Chatter.ChanceScale", 1.0f, true)); + group_cooldown_ms_ = uint32(std::max(0, sConfigMgr->GetIntDefault("Playerbot.Chatter.GroupCooldownMs", 20000, true))); + bot_cooldown_ms_ = uint32(std::max(0, sConfigMgr->GetIntDefault("Playerbot.Chatter.BotCooldownMs", 60000, true))); - auto ms = [](char const* key, int32 def) { return uint32(std::max(0, sConfigMgr->GetIntDefault(key, def))); }; - speech_.callouts_enabled = sConfigMgr->GetBoolDefault("Playerbot.Chatter.Callouts.Enabled", true); + auto ms = [](char const* key, int32 def) { return uint32(std::max(0, sConfigMgr->GetIntDefault(key, def, true))); }; + 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_.suggest_enabled = sConfigMgr->GetBoolDefault("Playerbot.Chatter.Suggest.Enabled", 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_global_cooldown_ms = ms("Playerbot.Chatter.Suggest.GlobalCooldownMs", 10000); @@ -72,7 +72,7 @@ void BotTextMgr::Load() // Realm-independent content: lives in the shared playerbot schema (migration 0019), reached over // the character connection by qualifying with the configured schema name, as BotNamePool does. - std::string const shared = sConfigMgr->GetStringDefault("Playerbot.SharedDatabase", "playerbot"); + std::string const shared = sConfigMgr->GetStringDefault("Playerbot.SharedDatabase", "playerbot", true); if (QueryResult res = CharacterDatabase.Query(Trinity::StringFormat( "SELECT name, text, say_type, reply_type, weight FROM `{}`.playerbot_v2_bot_text ORDER BY id", shared).c_str())) @@ -576,7 +576,7 @@ void SayGoodbye(Player* bot, Player* owner) namespace { -// ---- limiter state (AI workers tick bots concurrently: everything below is behind a lock) ---- +// ---- limiter state (bot workers tick bots concurrently: everything below is behind a lock) ---- // One companion's callout memory: the band each watched value was last seen in (so a line is said // when the value CROSSES into a worse band, not on every tick it stays there), whether the fight's diff --git a/src/modules/PlayerbotV2/Bot/BotTextMgr.h b/src/modules/PlayerbotV2/Bot/BotTextMgr.h index 4aa1811061..7dc51078ca 100644 --- a/src/modules/PlayerbotV2/Bot/BotTextMgr.h +++ b/src/modules/PlayerbotV2/Bot/BotTextMgr.h @@ -1,7 +1,7 @@ // BotTextMgr - the bots' speech lines, carried over from Karrz's ike3 playerbot build. // // Data: {Playerbot.SharedDatabase}.playerbot_v2_bot_text / _bot_text_chance (migration 0019). Loaded -// once by Module::Init before any bot logs in; read-only afterwards, so the AI workers and the world +// once by Module::Init before any bot logs in; read-only afterwards, so the bot workers and the world // thread may read it concurrently without a lock. // // A line is picked at random among the rows of one key ('hello', 'goodbye', 'reply', @@ -21,7 +21,7 @@ // Playerbot.Chatter.GroupCooldownMs 20000 minimum gap between two unsolicited lines in one group // Playerbot.Chatter.BotCooldownMs 60000 minimum gap between two unsolicited lines from one bot // -// SpeechTick (below) is the per-tick side, run by the AI worker from the snapshot: ike3's SayStrategy +// SpeechTick (below) is the per-tick side, run by the bot worker from the snapshot: ike3's SayStrategy // combat callouts for companions (critical / low health, low mana, out of ammo, the tank's taunt // lines, the "so many mobs" line on a big pull) and SuggestWhatToDoAction's lines from world bots in // their zone's General / Trade channel. It emits ChatIntents like any other rule. @@ -158,7 +158,7 @@ void AddSelfPlaceholders(TextPlaceholders& ph, uint8 cls, uint8 race, uint8 leve enum class Slot : uint8 { Greet, LevelUp, Broadcast }; bool TakeSlot(Slot slot, uint64 group_low, BotId bot, uint32 now_ms); -// ---- lines for the AI worker (snapshot data only; the caller emits them as party chat) ---- +// ---- lines for the bot worker (snapshot data only; the caller emits them as party chat) ---- // ike3 'hello' (or 'hello_follow' for a companion joining its owner). Empty when chatter is off or // another bot of the group greeted moments ago. @@ -190,14 +190,14 @@ void SayGoodbye(Player* bot, Player* owner); // a 90 s gap per bot. The text is a small built-in pool varied by class, role and personality. enum class Banter : uint8 { Ready, Wipe, Thanks, Ouch, BossKill }; -// AI worker: the line to say now for `kind`, or empty (gates / roll / cooldown said no). The caller emits it. +// bot worker: the line to say now for `kind`, or empty (gates / roll / cooldown said no). The caller emits it. std::string BanterLine(Banter kind, BotAI& ai, BotSnapshotView const& s); // A boss (dungeon boss or world boss) died to `killer` or a group member. Called by the kill listener for any // killer. One nearby companion of the killer's group may say "gg" and one may bow (the killer is a real player, // "the owner finished the boss") or cheer. void OnBossKilled(Player* killer, Creature* boss); -// ---- per-tick speech (AI worker; snapshot data only; emits at most one ChatIntent per tick) ---- +// ---- per-tick speech (bot worker; snapshot data only; emits at most one ChatIntent per tick) ---- // ike3 SayStrategy + SuggestWhatToDoAction, see the header comment. Called from // BotAI::dispatch_layers every tick, whatever the bot's state. diff --git a/src/modules/PlayerbotV2/Bot/CastPacing.h b/src/modules/PlayerbotV2/Bot/CastPacing.h index fef2aec530..ae8397b563 100644 --- a/src/modules/PlayerbotV2/Bot/CastPacing.h +++ b/src/modules/PlayerbotV2/Bot/CastPacing.h @@ -1,6 +1,6 @@ // CastPacing.h - per-bot cast-speed context and multiplier (Playerbot.Cast.*). // -// Pure functions over a snapshot view and the config: no Player access, safe on the AI +// Pure functions over a snapshot view and the config: no Player access, safe on the bot logic // threads. PlayerbotV2.cpp publishes the result core-side (API::set_cast_speed_multiplier) // and BotSnapshotView scales its in-flight cast caps by the same number. #pragma once diff --git a/src/modules/PlayerbotV2/Bot/CasterStepOut.h b/src/modules/PlayerbotV2/Bot/CasterStepOut.h deleted file mode 100644 index 83c008e5a2..0000000000 --- a/src/modules/PlayerbotV2/Bot/CasterStepOut.h +++ /dev/null @@ -1,31 +0,0 @@ -// CasterStepOut - which engaged mob a ranged / healer bot of a 5-man instance party keeps its distance from: the pure rule behind the -// dungeon use of State_Idle's ranged spacing (5b), which in raid maps steps back from engaged elites. -// -// In a dungeon party the casters follow the tank closely, and a bot that stands inside the pack (Deadmines 2026-10-09: the mage 1.5 y -// from the Defias Evoker) is in the splash of every melee mob and of the caster's own ground effects. A mob counts when it is alive, -// targetable, in combat, held by a tank or hitting another member (a mob on the bot itself is left to the tank: running only drags it -// along) and is a caster: it is casting now, or the dungeon script lists it as a high-priority kill (the script's casters). The step -// goes to the ranged stand-off (22 y) of the group of such mobs, never into a hazard and never while the bot is casting. -// Pure: no game types, tested in tests/game/ClassicCasterStepOut.cpp. - -#pragma once - -namespace Playerbot { - -struct StepOutMob -{ - bool alive = false; - bool is_player = false; - bool targetable = false; - bool in_combat = false; - bool held_by_tank_or_member = false; // its victim is a tank, a member or a member's pet - not the bot itself - bool casting_now = false; - bool listed_caster = false; // the script's high_priority_kill_entries -}; - -inline bool StepOutFromMob(StepOutMob const& m) -{ - return m.alive && !m.is_player && m.targetable && m.in_combat && m.held_by_tank_or_member && (m.casting_now || m.listed_caster); -} - -} // namespace Playerbot diff --git a/src/modules/PlayerbotV2/Bot/ClassicBuffLedger.h b/src/modules/PlayerbotV2/Bot/ClassicBuffLedger.h index 81ca20d02c..09d157d23d 100644 --- a/src/modules/PlayerbotV2/Bot/ClassicBuffLedger.h +++ b/src/modules/PlayerbotV2/Bot/ClassicBuffLedger.h @@ -17,6 +17,7 @@ namespace Playerbot::Classic { constexpr uint32_t kGreaterBlessingTrustMs = 6u * 60u * 1000u; // lasts 15 min constexpr uint32_t kSingleBlessingTrustMs = 3u * 60u * 1000u; // lasts 5 min constexpr uint32_t kClassBuffTrustMs = 6u * 60u * 1000u; // 30 min and up +constexpr uint32_t kAreaBuffTrustMs = 15u * 1000u; // a caster-centred party / raid cast: only the snapshot's lag is covered, the aura list decides after inline uint32_t BuffTrustMs(uint64_t key) { @@ -27,6 +28,7 @@ inline uint32_t BuffTrustMs(uint64_t key) case 3: case 4: return kClassBuffTrustMs; case 5: return kSingleBlessingTrustMs; + case 6: return kAreaBuffTrustMs; default: return 0; } } diff --git a/src/modules/PlayerbotV2/Bot/ClassicHealScope.h b/src/modules/PlayerbotV2/Bot/ClassicHealScope.h index 335f4da69c..266e40ddd8 100644 --- a/src/modules/PlayerbotV2/Bot/ClassicHealScope.h +++ b/src/modules/PlayerbotV2/Bot/ClassicHealScope.h @@ -1,6 +1,6 @@ // ClassicHealScope - where the Classic healers' mana-efficiency rules apply (Combat/Apl/ApClassicHeal.h RaidHealing). // -// They used to run in raid maps only. A level 21 party in Deadmines (Karrz, 2026-10-09) runs out of mana for the same reasons a +// They used to run in raid maps only. A level 21 party in Deadmines (playtest, 2026-10-09) runs out of mana for the same reasons a // raid does - heals sized to the deficit, the efficient spell for everyone but an emergency or a tank under half health, heals // already on their way counted, topping up held back at low mana, the tank pre-healed - so every group inside an instance map // (5-man dungeon or raid) gets them. Open-world parties, solo play and battlegrounds keep the plain rules. diff --git a/src/modules/PlayerbotV2/Bot/ClassicUpkeep.cpp b/src/modules/PlayerbotV2/Bot/ClassicUpkeep.cpp index 0fa3781b89..82a4307fb5 100644 --- a/src/modules/PlayerbotV2/Bot/ClassicUpkeep.cpp +++ b/src/modules/PlayerbotV2/Bot/ClassicUpkeep.cpp @@ -15,7 +15,10 @@ #include "Services.h" #include "Util/ConfigReader.h" #include "Log.h" +#include "World.h" +#include "fmt/format.h" #include +#include #include #include #include @@ -26,6 +29,7 @@ #include #include #include +#include namespace Playerbot::Classic { @@ -110,6 +114,37 @@ std::span MemberBlessingOrder(uint8 cls, uint32 spec, bool raid) return raid ? std::span(kCasterRaidOrder) : std::span(kCasterOrder); } +// A Greater Blessing that does something on this server. The Greater Blessing spells of this data carry no effect at all (the spell +// audit lists effect 0 on 25782, 25890, 25894, 25898, 25899, 25916): the cast spends a Symbol of Kings, applies nothing, and the paladin +// that sees no aura on the class casts it again on the next tick (MC Magmadar 2026-10-10 and the 14-17 Greater casts per paladin in 14 +// minutes of the 2026-10-12 raid). Such a spell is not used; the paladin blesses the members one by one with the normal blessings, which +// the same data does apply. Answered once per spell id. +bool GreaterBlessingWorks(uint32 spell_id) +{ + static std::mutex mu; + static std::unordered_map memo; + { + std::lock_guard lk(mu); + if (auto it = memo.find(spell_id); it != memo.end()) + return it->second; + } + bool works = false; + if (SpellInfo const* si = sSpellMgr->GetSpellInfo(spell_id, DIFFICULTY_NONE)) + for (SpellEffectInfo const& eff : si->GetEffects()) + if (eff.Effect != SPELL_EFFECT_NONE) + { + works = true; + break; + } + { + std::lock_guard lk(mu); + memo.emplace(spell_id, works); + } + if (!works) + TC_LOG_INFO("playerbot.v2", "[bless] Greater Blessing spell {} has no effect in this data: paladins bless member by member instead", spell_id); + return works; +} + // Blessing `b` on a buff list, with more than `min_ms` left, normal or // Greater. `caster` set: only that paladin's; `not_caster` set: anyone else's. bool HasBlessing(std::vector const& buffs, Blessing b, int64 min_ms, @@ -348,6 +383,25 @@ bool FearBossEngaged(BotSnapshotView const& s) return false; } +// Molten Core: one of the bosses whose fire needs resistance (Magmadar, Baron Geddon, Ragnaros) is in combat with the group. +bool FireResistBossEngaged(BotSnapshotView const& s) +{ + for (NearbyUnit const& u : s.raw().combat.nearby_enemies) + if (FightingTheGroup(u) && (u.entry == 11982 || u.entry == 12056 || u.entry == 11502)) + return true; + return false; +} + +// The resistance school the fire resistance aura / totem is held for. In Molten Core they are held only against the three fire +// bosses: the aura puts a gold haze round every player in range (playtest 2026-10-13), so elsewhere the normal aura and totem stand. +Resist AuraResistance(BotSnapshotView const& s) +{ + Resist const r = InstanceResistance(s.map_id()); + if (r == Resist::Fire && s.map_id() == 409 && !FireResistBossEngaged(s)) + return Resist::None; + return r; +} + // Raid: the shaman's subgroup (itself included) has a tank in it, as the // coordinator counts tanks (role / tank spec / plan main tank). bool SubgroupHasTank(BotSnapshotView const& s, GroupSnapshotView const& g) @@ -366,7 +420,7 @@ uint32 DesiredTotem(BotSnapshotView const& s, GroupSnapshotView const& g, Elemen 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); - Resist const resist = InstanceResistance(s.map_id()); + Resist const resist = AuraResistance(s); switch (e) { case EARTH: @@ -530,7 +584,7 @@ CastPick PickBlessing(BotSnapshotView const& s, GroupSnapshotView const& g, bool // a tank in it - that one is blessed member by member below. ClassPlan const class_plan = plan_for(ClassBlessingOrder(cls, raid), class_has_tank); int const bc = BlessingAt(s, class_plan.index, std::span(class_plan.order.data(), class_plan.n)); - if (bc >= 0 && greater_ok && s.knows_spell(kBlessings[bc].greater) && !(class_has_tank && bc == SALVATION)) + if (bc >= 0 && greater_ok && s.knows_spell(kBlessings[bc].greater) && GreaterBlessingWorks(kBlessings[bc].greater) && !(class_has_tank && bc == SALVATION)) { uint64 const key = (1ull << 48) | (uint64(bc) << 8) | cls; for (GroupMemberSummary const& m : *members) @@ -725,9 +779,15 @@ void ShortClassSupplies(BotSnapshotView const& s, std::vector& out) out.push_back(ammo); if (!Services::Config().classic_class_supplies()) return; + // A party buff spell the bot's level allows and it has not learned: the restock teaches it. + for (uint32 spell : GroupBuffSpells(s.cls())) + if (!s.knows_spell(spell)) + if (LearnableGroupBuff(spell, uint8(s.level()))) + out.push_back(spell); for (SupplyFamily const& f : GetSupplyFamilies()) { if (!SupplyFamilyForClass(f, s.cls())) continue; + if (MageConjuresFamily(s.cls(), f.name, [&](uint32 id) { return s.knows_spell(id); })) continue; uint32 const best = BestSupplyRank(f, s.level()); if (!best) continue; uint32 have = 0; @@ -748,6 +808,13 @@ void ShortClassSupplies(BotSnapshotView const& s, std::vector& out) namespace { constexpr uint8 KindBit(ConsumableKind k) { return uint8(1u << uint8(k)); } + +// The item data files the Demonic Rune under Trade Goods / Other (class 7, subclass 11), not Consumable (MC Geddon on next-6: "class 7 subclass 11, +// 1 item effects [trigger 0 spell 16666 effect 30 ...]"): every bag scan and the classification take both classes, and the effects decide the kind. +constexpr bool IsConsumableClass(uint32 item_class, uint32 item_subclass) +{ + return item_class == ITEM_CLASS_CONSUMABLE || (item_class == ITEM_CLASS_TRADE_GOODS && item_subclass == ITEM_SUBCLASS_TRADE_GOODS_OTHER); +} constexpr uint8 kCombatKinds = KindBit(ConsumableKind::Healthstone) | KindBit(ConsumableKind::HealingPotion) | KindBit(ConsumableKind::ManaPotion) | KindBit(ConsumableKind::ManaItem); @@ -756,6 +823,7 @@ struct ConsumableInfo uint8 kinds = 0; // KindBit mask, 0 = not a consumable we use bool conjured = false; uint32 spell = 0; // on-use spell (its cooldown is published under this id) + uint32 restore_mana = 0; // mana the on-use spell gives (its energize effects at their base roll) uint32 cooldown_ms = 0; // full cooldown of that spell int32 req_level = 0; uint32 item_level = 0; @@ -767,7 +835,7 @@ ConsumableInfo ClassifyItem(uint32 entry) { ConsumableInfo info; ItemTemplate const* tmpl = sObjectMgr->GetItemTemplate(entry); - if (!tmpl || tmpl->GetClass() != ITEM_CLASS_CONSUMABLE) + if (!tmpl || !IsConsumableClass(tmpl->GetClass(), tmpl->GetSubClass())) return info; for (ItemEffectEntry const* eff : tmpl->Effects) { @@ -777,6 +845,9 @@ ConsumableInfo ClassifyItem(uint32 entry) if (!si) continue; info.spell = si->Id; + for (SpellEffectInfo const& e : si->GetEffects()) + if (e.IsEffect(SPELL_EFFECT_ENERGIZE) && e.MiscValue == POWER_MANA) + info.restore_mana += uint32(std::max(e.CalcValueAsInt(), 0)); info.cooldown_ms = uint32(std::max({ eff->CoolDownMSec, eff->CategoryCoolDownMSec, 0 })); if (!info.cooldown_ms) info.cooldown_ms = std::max(si->RecoveryTime, si->CategoryRecoveryTime); @@ -795,7 +866,16 @@ ConsumableInfo ClassifyItem(uint32 entry) } // Instant restores: generic consumables (healthstones, runes, // mana gems) and potions; elixirs, flasks and scrolls are buffs. - if (!info.kinds && (sub == ITEM_SUBCLASS_CONSUMABLE || sub == ITEM_SUBCLASS_POTION)) + // The 12.1 item data files Demonic Runes and the like under "Other" (subclass 8), not "Consumable" (0): the Ragnaros squad + // carried runes the bots never counted or used (0 runes in 76 bag censuses). + if (!info.kinds && tmpl->GetClass() == ITEM_CLASS_TRADE_GOODS) + { + // Only a mana restore: a trade good with a healing on-use is not a healthstone. + for (SpellEffectInfo const& e : si->GetEffects()) + if (e.IsEffect(SPELL_EFFECT_ENERGIZE) && e.MiscValue == POWER_MANA) + info.kinds |= KindBit(ConsumableKind::ManaItem); + } + else if (!info.kinds && (sub == ITEM_SUBCLASS_CONSUMABLE || sub == ITEM_SUBCLASS_POTION || sub == ITEM_SUBCLASS_CONSUMABLE_OTHER)) { for (SpellEffectInfo const& e : si->GetEffects()) { @@ -875,7 +955,7 @@ uint32 BestConsumable(BotSnapshotView const& s, ConsumableKind kind, bool conjur ConsumableInfo const* bestInfo = nullptr; for (InventoryItem const& it : s.raw().inventory.bag_items) { - if (it.item_class != ITEM_CLASS_CONSUMABLE || it.entry == best) + if (!IsConsumableClass(it.item_class, it.item_subclass) || it.entry == best) continue; ConsumableInfo const& info = Classify(it.entry); if (!(info.kinds & bit) || (conjured_only && !info.conjured) || !UsableNow(s, info)) @@ -896,7 +976,7 @@ bool CombatConsumableUsedRecently(BotSnapshotView const& s, uint32 window_ms) { for (InventoryItem const& it : s.raw().inventory.bag_items) { - if (it.item_class != ITEM_CLASS_CONSUMABLE) + if (!IsConsumableClass(it.item_class, it.item_subclass)) continue; ConsumableInfo const& info = Classify(it.entry); if (!(info.kinds & kCombatKinds) || !info.cooldown_ms) @@ -922,6 +1002,13 @@ bool HealIncoming(BotSnapshotView const& s, GroupSnapshotView const& g) bool IsEating(BotSnapshotView const& s) { return HasRegenAura(s, false); } 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; +} + bool SafeToRecover(BotSnapshotView const& s, GroupSnapshotView const* g) { if (!s.is_alive() || s.in_combat() || s.attackers_count() > 0) @@ -1147,27 +1234,41 @@ uint32 PickCombatHealthItem(BotSnapshotView const& s, GroupSnapshotView const& g return BestConsumable(s, ConsumableKind::HealingPotion); } -uint32 PickCombatManaItem(BotSnapshotView const& s, GroupSnapshotView const* g) +uint32 PickCombatManaItem(BotSnapshotView const& s, GroupSnapshotView const* g, bool while_casting) { - if (s.max_power(POWER_MANA) <= 0 || s.is_casting() || !ConsumablesAllowed(s)) + if (s.max_power(POWER_MANA) <= 0 || (s.is_casting() && !while_casting) || !ConsumablesAllowed(s)) return 0; int32 const mana = s.power_pct(POWER_MANA); - if (mana > kBossHealerManaItemPct) - return 0; // A healer in a boss fight, or in any fight of a raid (the trash packs // run for minutes), drinks early (its mana is the raid's health); // everyone else at 20%. - if (mana > 20 && !(g && IsGroupHealer(s, g) && (BossFight(s) || s.is_in_raid()))) + bool const raid_healer = g && IsGroupHealer(s, g) && (BossFight(s) || s.is_in_raid()); + // A raid healer uses an item whenever it is ready and the restore fits in what the pool is missing: the items are limited by their + // 2-minute cooldown, not by stock, and a bot that waits for 35% fires them late (MC Geddon n8 run 3: potion and rune both at 33% about + // 60 s in, the next ones ready at 180 s, the kill at 159 s, four healers dry for the last 30 s). + int32 const ceiling = raid_healer ? kHealerManaItemCeilingPct : 20; + if (mana > ceiling) return 0; if (CombatConsumableUsedRecently(s)) return 0; - if (uint32 const gem = BestConsumable(s, ConsumableKind::ManaItem, /*conjured_only*/ true)) + int32 const max_mana = s.max_power(POWER_MANA); + auto const fits = [&](uint32 item) + { + if (!item) + return false; + if (!raid_healer) + return true; + int64 const room = int64(max_mana) * (100 - mana) / 100; // mana the pool is missing + return mana <= kBossHealerManaItemPct || int64(Classify(item).restore_mana) <= room; + }; + if (uint32 const gem = BestConsumable(s, ConsumableKind::ManaItem, /*conjured_only*/ true); fits(gem)) return gem; - if (uint32 const potion = BestConsumable(s, ConsumableKind::ManaPotion)) + if (uint32 const potion = BestConsumable(s, ConsumableKind::ManaPotion); fits(potion)) return potion; // Dark / Demonic Rune: 600-1000 damage to the user. if (s.hp_pct() > 50) - return BestConsumable(s, ConsumableKind::ManaItem); + if (uint32 const rune = BestConsumable(s, ConsumableKind::ManaItem); fits(rune)) + return rune; return 0; } @@ -1207,7 +1308,7 @@ bool BossFight(BotSnapshotView const& s) namespace { // One [raid_cd] / [raid_consume] line per (bot, spell or item) per 10 s: the -// rules run on the AI workers, so the pacing map is locked. +// rules run on the bot workers, so the pacing map is locked. bool LogPaced(BotSnapshotView const& s, uint32 id) { static std::mutex mtx; @@ -1245,6 +1346,59 @@ void NoteConsumableUse(BotSnapshotView const& s, uint32 item, char const* what) BossFight(s) ? 1 : 0); } +// A mana user at 20% or less in an instance fight with nothing picked: why, once per 10 s. (MC Ragnaros 2026-10-13 650994ea: 8 mana items in +// a 4-minute fight for 12 healers, the five holy priests never drank and six healers sat under 10% from 210 s.) +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; + for (InventoryItem const& it : s.raw().inventory.bag_items) + { + if (it.entry == 12662) + rune_items += it.count; // Demonic Rune by entry, whatever the classification below says + if (!IsConsumableClass(it.item_class, it.item_subclass)) + continue; + ConsumableInfo const& info = Classify(it.entry); + if (info.kinds & KindBit(ConsumableKind::ManaPotion)) + potions += it.count; + else if (info.kinds & KindBit(ConsumableKind::ManaItem)) + (info.conjured ? gems : runes) += it.count; + else if (info.kinds & kCombatKinds) + other += it.count; + } + // Runes in the bag that the classification above does not count: what the item data says about them, once per entry and process. The item's + // class and subclass, then each effect with its trigger and the spell's effect types (MC scenarios on af2c045a: 5 Demonic Runes by entry in + // every healer bag, 0 classified, 218 refusals). + if (rune_items > runes) + { + static std::atomic s_runeLogged{ false }; + if (!s_runeLogged.exchange(true)) + { + ItemTemplate const* tmpl = sObjectMgr->GetItemTemplate(12662); + std::string effects; + if (tmpl) + for (ItemEffectEntry const* eff : tmpl->Effects) + { + if (!eff) + continue; + SpellInfo const* si = eff->SpellID > 0 ? sSpellMgr->GetSpellInfo(uint32(eff->SpellID), DIFFICULTY_NONE) : nullptr; + effects += fmt::format(" [trigger {} spell {} known {}", int(eff->TriggerType), eff->SpellID, si ? 1 : 0); + if (si) + for (SpellEffectInfo const& e : si->GetEffects()) + effects += fmt::format(" effect {} misc {}", int(e.Effect), e.MiscValue); + effects += "]"; + } + TC_LOG_INFO("playerbot.v2", "[raid_consume] Demonic Rune 12662 is not classified as a mana item: template {}, class {} subclass {}, {} item effects{}", + tmpl ? 1 : 0, tmpl ? int(tmpl->GetClass()) : -1, tmpl ? int(tmpl->GetSubClass()) : -1, tmpl ? tmpl->Effects.size() : 0u, effects); + } + } + 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 {}%", + 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()); +} + // ======================= Raid support ======================= // Port of Karrz's ike3 generic raid behaviour (playerbot/strategy: priest / // mage / druid buff strategies with BUFF_PARTY / GREATER_BUFF_PARTY actions, @@ -1399,6 +1553,70 @@ void BuffCasters(BotSnapshotView const& s, std::vector const std::sort(out.begin(), out.end(), [](GroupMemberSummary const* a, GroupMemberSummary const* b) { return a->guid < b->guid; }); } +// Forever's client data leaves some vanilla buff spells without any effect (Mark of the Wild 1126 and its ranks, Gift of the Wild: the +// [buff_plan] line shows "effect targets" empty and the research diff lists them 0/0), so a cast does nothing and the buff stays missing. +// The working version is another spell of the same name (Mark of the Wild 364163, level 50). A buff is cast with the spell that applies an +// aura: the rank 1 id itself, else the highest same-name spell of the class the bot knows and its level allows. +bool SpellAppliesAura(SpellInfo const* si) +{ + if (!si) + return false; + for (SpellEffectInfo const& e : si->GetEffects()) + if (e.IsEffect() && e.IsAura()) + return true; + return false; +} + +uint32 EffectiveBuffSpell(BotSnapshotView const& s, uint32 base) +{ + static std::mutex mu; + static std::unordered_map>> cache; // base -> (spell level, id), ascending + std::vector> cands; + { + std::lock_guard lk(mu); + auto it = cache.find(base); + if (it == cache.end()) + { + std::vector> built; + if (SpellInfo const* bi = sSpellMgr->GetSpellInfo(base, DIFFICULTY_NONE)) + { + if (SpellAppliesAura(bi)) + built.emplace_back(bi->SpellLevel, base); + else if (bi->SpellName) + { + LocaleConstant const loc = sWorld->GetDefaultDbcLocale(); + char const* name = (*bi->SpellName)[loc]; + sSpellMgr->ForEachSpellInfo([&](SpellInfo const* si) + { + if (!si || si->Id == base || si->SpellFamilyName != bi->SpellFamilyName || !SpellAppliesAura(si)) + return; + if (!si->SpellLevel || si->SpellLevel > 60 || si->HasAttribute(SPELL_ATTR0_PASSIVE) || !si->SpellName) + return; + char const* n = (*si->SpellName)[loc]; + if (name && n && std::string_view(name) == std::string_view(n)) + built.emplace_back(si->SpellLevel, si->Id); + }); + // Ascending level; at one level the LOWEST id comes last, so the walk from the back takes the vanilla rank (Mark of the + // Wild: 9885, level 60) before the same-name spells added later (24752 a 30 minute variant, 1291335 and 1310503 retail + // versions). MC 2026-10-13 4839bcf3: the druids cast 1310503 and not one of 40 raiders showed the buff. + std::sort(built.begin(), built.end(), [](auto const& a, auto const& b) { return a.first != b.first ? a.first < b.first : a.second > b.second; }); + std::string ids; + for (auto const& [lvl, id] : built) + ids += fmt::format(" {}(L{})", id, lvl); + TC_LOG_INFO("playerbot.v2", "[buff_plan] spell {} \"{}\" has no aura effect; same-name spells that do:{}", base, name ? name : "", + ids.empty() ? " none" : ids); + } + } + it = cache.emplace(base, std::move(built)).first; + } + cands = it->second; + } + for (auto it = cands.rbegin(); it != cands.rend(); ++it) + if (it->first <= s.level() && s.knows_spell(it->second)) + return it->second; + return base; +} + // The rank of the party version this bot casts: the highest rank it knows // whose reagents (spell data of that rank) are in the bags, walking down the // chain so a bot with only the lower rank's reagent (Holy Candle, Wild @@ -1411,8 +1629,8 @@ uint32 GroupBuffRank(BotSnapshotView const& s, ClassBuffDef const& d) for (int guard = 0; rank && guard < 32; ++guard, rank = sSpellMgr->GetPrevSpellInChain(rank)) { SpellInfo const* si = sSpellMgr->GetSpellInfo(rank, DIFFICULTY_NONE); - if (!si) - continue; + if (!si || !SpellAppliesAura(si)) + continue; // a rank with no effect (Gift of the Wild in Forever's data) buffs nobody bool have = true; for (size_t i = 0; i < si->Reagent.size() && have; ++i) if (si->Reagent[i] > 0 && si->ReagentCount[i] > 0 @@ -1584,7 +1802,7 @@ struct OwnedDispel // registers its auras (RegisterEncounterOwnedDispel): without it the generic // plan must remove everything, Molten Core's curses included. // -// Readers are the AI worker threads, at any time. Each registration builds a +// Readers are the bot worker threads, at any time. Each registration builds a // new immutable list under g_ownedDispelsWrite and publishes it with one // release store; readers take one acquire load and walk a list that never // changes. Superseded lists are kept alive (registration happens a handful @@ -1648,7 +1866,12 @@ uint32 ResistPotionItem(Resist r) uint32 PickResistPotion(BotSnapshotView const& s) { - uint32 const item = s.raw().pve_order.active ? s.raw().pve_order.resist_potion : 0; + uint32 item = s.raw().pve_order.active ? s.raw().pve_order.resist_potion : 0; + // A carrier aura on the bot itself (Living Bomb) asks for its potion whatever the boss order says. + if (!item) + if (Raid::RaidRules const* rules = Raid::RulesForMap(s.map_id())) + for (Raid::CarrierPotion const& cp : rules->carrierPotion) + if (s.has_aura(cp.aura)) { item = cp.item; break; } if (!item || !s.in_combat() || s.is_casting() || s.item_count(item) == 0 || !ConsumablesAllowed(s)) return 0; ConsumableInfo const& info = Classify(item); @@ -1756,6 +1979,137 @@ uint32 CreateHealthstoneSpell(BotSnapshotView const& s) return s.knows_spell(CREATE_HEALTHSTONE) ? CREATE_HEALTHSTONE : 0; } +namespace { + +// The item a Conjure Mana Gem spell creates (its Create Item effect), 0 when the spell data has none. +uint32 ManaGemItemOf(uint32 spell) +{ + SpellInfo const* si = sSpellMgr->GetSpellInfo(spell, DIFFICULTY_NONE); + if (!si) + return 0; + for (SpellEffectInfo const& e : si->GetEffects()) + if (e.IsEffect(SPELL_EFFECT_CREATE_ITEM) && e.ItemType) + return e.ItemType; + return 0; +} + +} // namespace + +bool HasManaGem(BotSnapshotView const& s) +{ + for (InventoryItem const& it : s.raw().inventory.bag_items) + { + // The item the conjure spells create, by entry: whatever the item data's class, subclass or conjured flag say. + for (uint32 const spell : { 10054u, 10053u, 3552u, 759u }) + if (it.entry == ManaGemItemOf(spell)) + return true; + if (it.item_class == ITEM_CLASS_CONSUMABLE) + { + ConsumableInfo const& info = Classify(it.entry); + if (info.conjured && (info.kinds & KindBit(ConsumableKind::ManaItem))) + return true; + } + } + return false; +} + +uint32 CreateManaGemSpell(BotSnapshotView const& s) +{ + if (s.cls() != CLASS_MAGE) + return 0; + // Conjure Mana Ruby 10054 (58), Jade 10053 (48), Citrine 3552 (38), Agate 759 (28) + for (uint32 const spell : { 10054u, 10053u, 3552u, 759u }) + if (s.knows_spell(spell)) + return spell; + return 0; +} + +namespace { + +// Conjure Water / Conjure Food spells, found like the healthstones: mage-family spells with a +// Create Item effect whose item is a drink or food (Classify). Scanned once on first use. +struct ConjureSpell +{ + uint32 spell = 0; + uint32 item = 0; + uint32 level = 0; + ConsumableKind kind = ConsumableKind::Food; +}; + +std::vector const& MageConjureSpells() +{ + static std::vector const spells = [] + { + std::vector out; + sSpellMgr->ForEachSpellInfo([&out](SpellInfo const* si) + { + if (!si || si->SpellFamilyName != SPELLFAMILY_MAGE) + return; + for (SpellEffectInfo const& e : si->GetEffects()) + { + if (!e.IsEffect(SPELL_EFFECT_CREATE_ITEM) || !e.ItemType) + continue; + ConsumableInfo const& info = Classify(e.ItemType); + if (!info.conjured) + continue; + ConsumableKind kind; + if (info.kinds & KindBit(ConsumableKind::Drink)) + kind = ConsumableKind::Drink; + else if (info.kinds & KindBit(ConsumableKind::Food)) + kind = ConsumableKind::Food; + else + continue; + if (std::none_of(out.begin(), out.end(), [&](ConjureSpell const& c) { return c.spell == si->Id; })) + out.push_back({ si->Id, e.ItemType, si->SpellLevel, kind }); + } + }); + return out; + }(); + return spells; +} + +} // namespace + +uint32 BestMageConjure(ConsumableKind kind, std::function const& knows) +{ + ConjureSpell const* best = nullptr; + for (ConjureSpell const& c : MageConjureSpells()) + if (c.kind == kind && knows(c.spell) && (!best || c.level > best->level)) + best = &c; + return best ? best->spell : 0; +} + +bool MageConjuresFamily(uint8 cls, std::string_view family, std::function const& knows) +{ + if (cls != CLASS_MAGE) + return false; + if (family == "Water") + return BestMageConjure(ConsumableKind::Drink, knows) != 0; + if (family == "Food") + return BestMageConjure(ConsumableKind::Food, knows) != 0; + return false; +} + +uint32 MageConjureSpell(BotSnapshotView const& s, ConsumableKind kind, uint32 want_below) +{ + if (s.cls() != CLASS_MAGE || (kind != ConsumableKind::Drink && kind != ConsumableKind::Food)) + return 0; + uint32 const family_top = BestMageConjure(kind, [&](uint32 id) { return s.knows_spell(id); }); + if (!family_top) + return 0; + // knows_spell answers for the whole rank family, so family_top is the highest rank of the data, not of the spellbook (a level 20 + // mage asked for rank 7 Conjure Food and got API_NOT_KNOWN on every try, 2026-10-14 Deadmines): cast the rank it has learned. + uint32 const spell = s.resolve_rank(family_top); + if (!spell) + return 0; + uint32 have = 0; + for (InventoryItem const& it : s.raw().inventory.bag_items) + if (it.item_class == ITEM_CLASS_CONSUMABLE && Classify(it.entry).conjured + && (Classify(it.entry).kinds & KindBit(kind))) + have += it.count; + return have < want_below ? spell : 0; +} + bool MemberHasBuff(GroupSnapshotView const& g, ObjectGuid guid, uint32 tracked_id) { if (auto const* members = g.members()) @@ -1873,6 +2227,66 @@ MissingBuff MissingGroupBuff(BotSnapshotView const& s, GroupSnapshotView const& namespace { +// A class buff whose single spell has no explicit unit target (Mark of the Wild in the Forever data: the cast log shows an empty +// target, whoever the bot aimed at) is cast around the caster: it reaches the caster's party, or its raid, in range, not a chosen +// member. Picking a target per member for it casts the same spell once per member (MC 2026-10-12: 42 + 40 casts of a 20 mana spell in a +// 40-man raid, none of the picked targets showing the buff afterwards). +struct AreaBuff +{ + bool area = false; + bool party_only = true; // reaches only the caster's subgroup +}; + +AreaBuff AreaBuffOf(uint32 spell) +{ + AreaBuff out; + SpellInfo const* si = spell ? sSpellMgr->GetSpellInfo(spell, DIFFICULTY_NONE) : nullptr; + if (!si) + return out; + { + // Once per spell: how the data targets it (the cast log's target column is empty for such a spell). + static std::mutex seen_mu; + static std::unordered_set seen; + bool first; + { + std::lock_guard lk(seen_mu); + first = seen.insert(spell).second; + } + if (first) + { + std::string targets; + for (SpellEffectInfo const& e : si->GetEffects()) + targets += fmt::format(" [{}/{}]", uint32(e.TargetA.GetTarget()), uint32(e.TargetB.GetTarget())); + char const* n = si->SpellName ? (*si->SpellName)[sWorld->GetDefaultDbcLocale()] : ""; + TC_LOG_INFO("playerbot.v2", "[buff_plan] spell {} \"{}\": explicit unit target {}, targets area {}, effect targets A/B{}", spell, n ? n : "", + si->NeedsExplicitUnitTarget() ? "yes" : "no", si->IsTargetingArea() ? "yes" : "no", targets); + } + } + if (si->NeedsExplicitUnitTarget() || !si->IsTargetingArea()) + return out; + out.area = true; + for (SpellEffectInfo const& e : si->GetEffects()) + for (Targets const t : { e.TargetA.GetTarget(), e.TargetB.GetTarget() }) + if (t == TARGET_UNIT_CASTER_AREA_RAID || t == TARGET_UNIT_TARGET_ALLY_OR_RAID) + out.party_only = false; + return out; +} + +// Back-off of such a cast that reached nobody: the needy count after a cast was no lower than before it, twice running (the spell +// does not reach those members: another subgroup, out of its radius, or caster only). The buff then waits kAreaBuffBackoffMs. +constexpr uint32 kAreaBuffBackoffMs = 5u * 60u * 1000u; +struct AreaBuffState { uint32 last_needy = 0; uint32 stalls = 0; uint32 backoff_until_ms = 0; }; +std::mutex g_area_buff_mu; +std::unordered_map g_area_buff; // (caster counter << 8) ^ buff index + +bool AreaBuffBackedOff(ObjectGuid caster, size_t di) +{ + uint32 const now = GameTime::GetGameTimeMS(); + std::lock_guard lk(g_area_buff_mu); + auto const it = g_area_buff.find((caster.GetCounter() << 8) ^ di); + return it != g_area_buff.end() && it->second.backoff_until_ms && int32(it->second.backoff_until_ms - now) > 0; +} + // The class buff this bot owes, whether or not it is shapeshifted right now // (the plan does not depend on the form: see BuffCasters). CastPick ClassBuffPick(BotSnapshotView const& s, GroupSnapshotView const& g, PickSkip skip) @@ -1889,6 +2303,10 @@ CastPick ClassBuffPick(BotSnapshotView const& s, GroupSnapshotView const& g, Pic ClassBuffDef const& d = kClassBuffs[di]; if (d.cls != s.cls() || !s.knows_spell(d.single)) continue; + // The spell this buff is cast with (see EffectiveBuffSpell); a buff with no spell that applies an aura is not cast at all. + uint32 const single = EffectiveBuffSpell(s, d.single); + if (!SpellAppliesAura(sSpellMgr->GetSpellInfo(single, DIFFICULTY_NONE))) + continue; if (d.raid_only && !g.is_raid()) continue; if (!InstanceDealsSchool(s.map_id(), d.school)) @@ -1903,8 +2321,8 @@ CastPick ClassBuffPick(BotSnapshotView const& s, GroupSnapshotView const& g, Pic continue; // Paced like the group picks: a cast whose aura the snapshot does not show must not repeat every tick. uint64 const key = (5ull << 48) | uint64(di); - if (!SelfHasBuff(s, d) && s.is_ready(d.single) && !skip(key)) - return { d.single, s.guid(), key }; + if (!SelfHasBuff(s, d) && s.is_ready(single) && !skip(key)) + return { single, s.guid(), key }; continue; } @@ -1914,6 +2332,36 @@ CastPick ClassBuffPick(BotSnapshotView const& s, GroupSnapshotView const& g, Pic if (me == casters.end()) continue; + if (AreaBuff const area = AreaBuffOf(single); area.area) + { + // One cast from this caster reaches its party (or raid) in range: owed when a member it reaches lacks the buff. + GroupMemberSummary const* const mine = *me; + if (AreaBuffBackedOff(s.guid(), di)) + continue; + uint32 needy = 0; + for (GroupMemberSummary const& m : *members) + { + if (!NeedsBuff(s, d, m)) continue; + if (area.party_only && m.subgroup != mine->subgroup) continue; + if (m.guid != s.guid() && MemberDist2(m, bx, by, bz) > kBuffCastRange * kBuffCastRange) continue; + ++needy; + } + if (!needy) + continue; + // Casters of the same subgroup share the work: the lowest guid casts (a raid-wide spell: every caster that reaches someone). + if (area.party_only) + if (GroupMemberSummary const* lead = *std::find_if(casters.begin(), casters.end(), + [&](GroupMemberSummary const* c) { return c->subgroup == mine->subgroup; }); + lead && lead->guid != s.guid()) + continue; + uint64 const key = (6ull << 48) | uint64(di); + if (!s.is_ready(single) || skip(key)) + continue; + CastPick pick{ single, s.guid(), key }; + pick.area_needy = needy; + return pick; + } + uint32 const group_rank = GroupBuffRank(s, d); for (uint8 sg = 0; sg < 8; ++sg) { @@ -1955,6 +2403,31 @@ CastPick ClassBuffPick(BotSnapshotView const& s, GroupSnapshotView const& g, Pic } if (!first) continue; + // MC 2026-10-12: 82 single Mark of the Wild and 44 single Power Word: Fortitude casts across two 40-man runs, no Gift of the + // Wild or Prayer of Fortitude at all. Name why the party version is not used, once a minute per caster and buff. + if (d.group && needy >= 2 && !group_rank) + { + static std::mutex why_mu; + static std::unordered_map why_last; + uint32 const now = GameTime::GetGameTimeMS(); + bool due = false; + { + std::lock_guard lk(why_mu); + uint32& l = why_last[(s.guid().GetCounter() << 20) ^ d.single]; + if (!l || now - l >= 60000u) { l = now ? now : 1u; due = true; } + } + if (due) + { + uint32 const known = s.resolve_rank(d.group); + std::string reagents; + if (SpellInfo const* si = known ? sSpellMgr->GetSpellInfo(known, DIFFICULTY_NONE) : nullptr) + for (size_t i = 0; i < si->Reagent.size(); ++i) + if (si->Reagent[i] > 0 && si->ReagentCount[i] > 0) + reagents += fmt::format(" {}x{}(has {})", si->ReagentCount[i], si->Reagent[i], s.item_count(uint32(si->Reagent[i]))); + TC_LOG_INFO("playerbot.v2", "[buff_plan] {} casts single {} on {} needy of subgroup {}: no party version ({}; known rank {}, reagents{})", + s.name(), d.single, needy, uint32(sg), known ? "reagents short" : "spell not known", known, reagents.empty() ? " none" : reagents); + } + } if (group_rank && needy >= 2) { // The party version covers the subgroup: while it is paced @@ -1972,8 +2445,8 @@ CastPick ClassBuffPick(BotSnapshotView const& s, GroupSnapshotView const& g, Pic if (m.subgroup != sg || !NeedsBuff(s, d, m)) continue; if (m.guid != s.guid() && MemberDist2(m, bx, by, bz) > kBuffCastRange * kBuffCastRange) continue; uint64 const key = (4ull << 48) | (uint64(di) << 40) | (m.guid.GetCounter() & 0xFFFFFFFFFFull); - if (s.is_ready(d.single) && !skip(key)) - return { d.single, m.guid, key }; + if (s.is_ready(single) && !skip(key)) + return { single, m.guid, key }; } } } @@ -1992,6 +2465,29 @@ constexpr int32 kFormDrinkBelowManaPct = 70; } // namespace +void NoteAreaBuffCast(ObjectGuid caster, uint64 key, uint32 needy, uint32 now_ms) +{ + if ((key >> 48) != 6) + return; + size_t const di = size_t(key & 0xFFFFu); + std::lock_guard lk(g_area_buff_mu); + AreaBuffState& st = g_area_buff[(caster.GetCounter() << 8) ^ di]; + // This cast comes after the last one's trust window: were that many members, or more, still needy, it reached nobody new. + if (st.last_needy && needy >= st.last_needy) + ++st.stalls; + else + st.stalls = 0; + st.last_needy = needy; + if (st.stalls >= 2) + { + st.backoff_until_ms = now_ms + kAreaBuffBackoffMs; + st.stalls = 0; + st.last_needy = 0; + TC_LOG_INFO("playerbot.v2", "[buff_plan] caster {} buff index {}: {} members still needy after two caster-centred casts, backing off {} s", caster.GetCounter(), di, + needy, kAreaBuffBackoffMs / 1000u); + } +} + CastPick PickClassBuff(BotSnapshotView const& s, GroupSnapshotView const& g, PickSkip skip) { // A druid in a form can't cast Mark of the Wild / Thorns: it leaves the @@ -2045,7 +2541,7 @@ uint32 PickPaladinAura(BotSnapshotView const& s, GroupSnapshotView const& g) { if (!IsVanillaRealm() || s.cls() != CLASS_PALADIN || s.is_mounted()) return 0; - Resist const resist = InstanceResistance(s.map_id()); + Resist const resist = AuraResistance(s); uint32 wishes[8]; size_t n = 0; @@ -2138,7 +2634,7 @@ bool IsEncounterOwnedDispel(uint32 map_id, uint32 aura_id) if (o.map_id == map_id && o.aura == aura_id) return true; // The raid layer's own rules for every raid map (Bot/Raid/RaidEncounterData_*.cpp): its dispel jobs, mind-controlled - // members and do-not-dispel auras. Read-only after the registry's one-time init, so safe from the AI workers; this is + // members and do-not-dispel auras. Read-only after the registry's one-time init, so safe from the bot workers; this is // why the raid layer never calls RegisterEncounterOwnedDispel. return Raid::OwnsAura(map_id, aura_id); } diff --git a/src/modules/PlayerbotV2/Bot/ClassicUpkeep.h b/src/modules/PlayerbotV2/Bot/ClassicUpkeep.h index d0ee7fe3ec..9f3a23d2e0 100644 --- a/src/modules/PlayerbotV2/Bot/ClassicUpkeep.h +++ b/src/modules/PlayerbotV2/Bot/ClassicUpkeep.h @@ -9,10 +9,12 @@ // - shaman weapon imbues and totems (one per element, by spec and group); // - rogue poisons (Instant on the main hand, Deadly on the off hand); // - whether the bot is short of a class tool or reagent (ClassicSupplies). -// Pure functions of the snapshot: safe on the AI worker threads. +// Pure functions of the snapshot: safe on the bot worker threads. #pragma once +#include +#include #include "InstanceSchools.h" #include "BotTypes.h" #include "ObjectGuid.h" @@ -38,6 +40,8 @@ struct CastPick // rank 1 id cast at the highest known rank (cast): a party buff whose top // rank's reagent is missing but the lower rank's is in the bags. bool exact_rank = false; + // A caster-centred buff (key kind 6): how many members it was needy of when picked, so the rule can tell a cast that reached nobody. + uint32 area_needy = 0; }; // Raid support picks skip work the caller is still pacing: `skip(ctx, key)` @@ -111,6 +115,8 @@ 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 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); // Druid, out of combat: the form aura (Cat, Bear, Dire Bear, Travel, Moonkin; // never Aquatic) to cancel because PickClassBuff has a buff for this druid once @@ -162,7 +168,7 @@ constexpr int32 kDispelMinManaPct = 15; // Shadow Word: Pain / Immolate, 409/19408 Magmadar's Panic; // - register only auras the layer really removes, or nobody will; // - registration is idempotent and thread-safe at any time (an immutable -// list is republished atomically; AI workers read it lock-free), but +// list is republished atomically; bot workers read it lock-free), but // registering at startup avoids a window in which both the layer and // the generic plan dispel the same debuff. There is no unregister. bool IsEncounterOwnedDispel(uint32 map_id, uint32 aura_id); @@ -192,6 +198,11 @@ bool IsHealthstoneItem(uint32 item_entry); bool HasHealthstone(BotSnapshotView const& s); uint32 CreateHealthstoneSpell(BotSnapshotView const& s); +// Mage mana gems: HasManaGem is a conjured mana-restoring item in the bags; CreateManaGemSpell the best Conjure Mana Agate / Citrine / +// Jade / Ruby the mage knows (0 = none, or not a mage). The gem is the first mana item PickCombatManaItem takes. +bool HasManaGem(BotSnapshotView const& s); +uint32 CreateManaGemSpell(BotSnapshotView const& s); + // A group member carries the tracked buff `tracked_id` (any caster). bool MemberHasBuff(GroupSnapshotView const& g, ObjectGuid guid, uint32 tracked_id); @@ -276,8 +287,17 @@ 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); +// 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); +// 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); + // The bot used a combat consumable (potion, healthstone, rune, mana gem) in -// the last `window_ms` (Karrz: at most one per 2.5 s, so a healthstone and a +// the last `window_ms` (the owner: at most one per 2.5 s, so a healthstone and a // potion never go in the same instant). bool CombatConsumableUsedRecently(BotSnapshotView const& s, uint32 window_ms = 2500); @@ -288,7 +308,11 @@ bool HealIncoming(BotSnapshotView const& s, GroupSnapshotView const& g); bool IsEating(BotSnapshotView const& s); bool IsDrinking(BotSnapshotView const& s); -// Karrz's SafeToRecover / UseFoodStrategy: free to sit down - nothing attacks +// The quest / travel walkers (idle priority 697-700) stand down while the bot should recover first: under half health, a +// food / drink aura is up (standing up mid-meal wastes the item), or a caster with water in the bags is under a fifth mana. +bool RecoverBeforeWalking(BotSnapshotView const& s); + +// the owner's SafeToRecover / UseFoodStrategy: free to sit down - nothing attacks // the bot and no group member fights within 45 yards and no enemy engaged with the bot or its group stands within 30 yards (Bot/RecoverRules.h). // Without a group view only the enemies are checked (a fight next to the bot // still shows as an enemy with a victim). @@ -308,9 +332,9 @@ RecoveryPick PickRecovery(BotSnapshotView const& s, int32 start_hp, int32 start_ // Healer mana a grouped instance tank waits for before it pulls (State_Idle // dungeon group-ready gate). The drink rules start a grouped healer's drink // below this same value, so a healer that holds the pull always drinks. -// 85 was Karrz's ike3 "raid prepull recover" target; 75 since 2026-10-07 (Karrz: MC trash takes too long). +// 85 was Karrz's ike3 "raid prepull recover" target; 75 since 2026-10-07 (the owner: MC trash takes too long). constexpr int32 kPullReadyHealerManaPct = 75; -// A five-man healer has no trash-pace cost to weigh (Karrz's 2026-10-07 call was about MC): a drink that starts only below 75 % +// A five-man healer has no trash-pace cost to weigh (the owner's 2026-10-07 call was about MC): a drink that starts only below 75 % // never starts for a priest at 75-94 %, so she pulled into every pack three-quarters full and was dry by the boss // (deadmines_full@sneed). Dungeon healers start the drink, and the tank's pull gate waits, below this. constexpr int32 kPullReadyDungeonHealerManaPct = 90; @@ -341,6 +365,9 @@ constexpr int32 kHeldRaidHealerManaPct = 95; // Same value: the tank's gate waits for such a member for at most // kPullReadyDpsHoldCapMs per hold (a bot with no drink must not freeze the raid). constexpr uint32 kPullReadyDpsHoldCapMs = 20000; +// A member under the pull-ready health mark (70 %) holds the tank's pull for at most this long per hold: the healers top a hurt member off +// in seconds, so a longer wait means they cannot (out of reach, a tick that keeps hurting it) and the raid goes on. +constexpr uint32 kPullReadyHpHoldCapMs = 30000; // This bot drinks for the next pull of its grouped instance: a healer, or // (PullRecover on) any other mana user. @@ -355,7 +382,7 @@ bool IsGroupHealer(BotSnapshotView const& s, GroupSnapshotView const* g); int32 OocDrinkStartManaPct(BotSnapshotView const& s, GroupSnapshotView const* g, int32 open_world_pct); -// In-combat emergency heal item (Karrz's UsePotionsStrategy): at 30% health +// In-combat emergency heal item (the owner's UsePotionsStrategy): at 30% health // or below, healthstone first, then a healing potion; kept while a heal is // about to land unless the bot is at 20% or below. 0 = nothing to use. uint32 PickCombatHealthItem(BotSnapshotView const& s, GroupSnapshotView const& g); @@ -365,12 +392,15 @@ uint32 PickCombatHealthItem(BotSnapshotView const& s, GroupSnapshotView const& g // Demonic Rune (which costs health: only above 50%). The potions' shared // cooldown and the runes' own cooldown are read separately per item (an item // on cooldown is skipped), so a healer drinks a potion and later a rune. -uint32 PickCombatManaItem(BotSnapshotView const& s, GroupSnapshotView const* g = nullptr); +// asks whether an item would be due if no cast were running (the mana break: the caster stops starting casts). +uint32 PickCombatManaItem(BotSnapshotView const& s, GroupSnapshotView const* g = nullptr, bool while_casting = false); // Health % at or below which PickCombatHealthItem uses an item. 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: from here down an item is used as soon as its restore fits in the missing mana. +constexpr int32 kHealerManaItemCeilingPct = 85; // ======================= Boss fights (major cooldowns) ======================= // A boss by its creature data: the dungeon-boss flag or the world-boss rank @@ -393,5 +423,9 @@ void NoteCooldownUse(BotSnapshotView const& s, uint32 spell, char const* what); // instance (same pacing as NoteCooldownUse). void NoteConsumableUse(BotSnapshotView const& s, uint32 item, char const* what); +// [raid_consume] line for a mana user at 20% or less in an instance fight with no mana item picked: the reason (casting, a recent +// consumable, none in the bags), once per bot per 10 s. +void NoteManaItemRefused(BotSnapshotView const& s); + } // namespace Classic } // namespace Playerbot diff --git a/src/modules/PlayerbotV2/Bot/DeathHotspots.h b/src/modules/PlayerbotV2/Bot/DeathHotspots.h index 2efcdae673..85119e26f9 100644 --- a/src/modules/PlayerbotV2/Bot/DeathHotspots.h +++ b/src/modules/PlayerbotV2/Bot/DeathHotspots.h @@ -2,7 +2,7 @@ // that saw DeathsNeeded deaths within WindowSec is a hotspot, and it is dangerous for a bot that is more than // LevelMargin levels below the strongest killer seen there. Quest pursuit uses it to give up objectives inside a // hotspot, so a bot stops walking into the camp that has just killed a dozen of its peers (Booty Bay Bloodsail camp, -// 2026-10-07: 20 Fireball deaths). Written on the world thread (Module::OnDeath), read from the AI workers. +// 2026-10-07: 20 Fireball deaths). Written on the world thread (Module::OnDeath), read from the bot workers. #pragma once diff --git a/src/modules/PlayerbotV2/Bot/Dungeon/DungeonScript.cpp b/src/modules/PlayerbotV2/Bot/Dungeon/DungeonScript.cpp index 072d970bef..b3e1359a5c 100644 --- a/src/modules/PlayerbotV2/Bot/Dungeon/DungeonScript.cpp +++ b/src/modules/PlayerbotV2/Bot/Dungeon/DungeonScript.cpp @@ -26,14 +26,14 @@ inline uint64_t MakeKey(uint32_t map_id, uint32_t difficulty) // Playerbot.Behavior.DungeonTactics (default on): the generated mob tactics (Tactics/DungeonTactics.h) feed the advice on a Classic realm. bool DungeonTacticsEnabled() { - static bool const on = IsVanillaRealm() && sConfigMgr->GetBoolDefault("Playerbot.Behavior.DungeonTactics", true); + static bool const on = IsVanillaRealm() && sConfigMgr->GetBoolDefault("Playerbot.Behavior.DungeonTactics", true, true); return on; } std::string const& SharedDb() { static std::string const db = - sConfigMgr->GetStringDefault("Playerbot.SharedDatabase", "playerbot"); + sConfigMgr->GetStringDefault("Playerbot.SharedDatabase", "playerbot", true); return db; } } diff --git a/src/modules/PlayerbotV2/Bot/Dungeon/DungeonScript.h b/src/modules/PlayerbotV2/Bot/Dungeon/DungeonScript.h index a67ab39bbc..21d8d4a1cb 100644 --- a/src/modules/PlayerbotV2/Bot/Dungeon/DungeonScript.h +++ b/src/modules/PlayerbotV2/Bot/Dungeon/DungeonScript.h @@ -24,9 +24,9 @@ namespace Playerbot { class BotSnapshotView; // Advice bundle returned by a DungeonScript per tick. Empty fields -// mean "no opinion" — the AI uses generic logic. The advice struct +// mean "no opinion" — the bot logic uses generic logic. The advice struct // is intentionally small and value-typed so the registry can hand -// it out by-value to the AI worker without locking. +// it out by-value to the bot worker without locking. struct DungeonAdvice { // Creature_template entries the bot should pull first / focus @@ -96,7 +96,7 @@ struct DungeonAdvice std::vector soak_spells; // Boss creature entries in encounter order. Order is encounter- - // progression so the dungeon AI can tell whether the run is complete + // progression so the dungeon bot logic can tell whether the run is complete // (all bosses dead) and which boss is "next". Used by tank-advance // and by diag commands. Live boss creature positions are read from // the map; if no waypoints are provided, advancement falls back to a @@ -157,7 +157,7 @@ struct DungeonAdvice // platform, or descent reached after the main clear — where the group must // stay TIGHT and FOCUS-KILL casters instead of CCing/spreading, and the // tank must not out-range its healer. When the tank descends BELOW this - // world-Z the dungeon AI switches into "tight engagement" mode: + // world-Z the dungeon bot logic switches into "tight engagement" mode: // * tighter advance-cohesion gate (healer ≤18y, every member ≤25y, ≥85% HP) // * tighter follower regroup radius (14y vs the default 22y) so the group // balls up INSIDE the advance gate — eliminates the 18-22y cohesion @@ -245,7 +245,7 @@ public: DungeonScriptMgr() = default; // Takes ownership; called once per script at module init. The - // registry must be assembled before any AI ticks consult it. + // registry must be assembled before any bot ticks consult it. void Register(std::unique_ptr script); // Register an "always-on" script whose advice is merged with the @@ -275,7 +275,7 @@ public: // again from `.playerbot reloadroutes` (SOAP) whenever the editor commits // route changes — builds the new table off to the side and atomically swaps // the shared_ptr under routes_mutex_, so concurrent GetAdvice readers on the - // AI worker threads keep a consistent (old or new) snapshot and no restart + // bot worker threads keep a consistent (old or new) snapshot and no restart // is needed. Returns the number of waypoints loaded. size_t LoadGeneratedRoutes(); @@ -322,7 +322,7 @@ private: // DB-sourced route waypoints keyed by (map_id<<8)|difficulty. The map is // IMMUTABLE once published; LoadGeneratedRoutes builds a fresh instance and // swaps the shared_ptr under routes_mutex_ (hot-reload). GetAdvice readers - // (AI worker threads, every tick) take a brief shared_lock only to copy the + // (bot worker threads, every tick) take a brief shared_lock only to copy the // shared_ptr, then read the immutable map lock-free — an in-flight reader // keeps the old table alive via its shared_ptr during a swap. using RouteTable = diff --git a/src/modules/PlayerbotV2/Bot/Dungeon/GroupWedgeWatchdog.cpp b/src/modules/PlayerbotV2/Bot/Dungeon/GroupWedgeWatchdog.cpp index 4c111f021b..0e862e3d46 100644 --- a/src/modules/PlayerbotV2/Bot/Dungeon/GroupWedgeWatchdog.cpp +++ b/src/modules/PlayerbotV2/Bot/Dungeon/GroupWedgeWatchdog.cpp @@ -45,7 +45,7 @@ void GroupWedgeWatchdog::Update(uint32 now_ms) return; last_tick_ms_ = now_ms; - if (!sConfigMgr->GetBoolDefault("PlayerbotV2.GroupWedge.Enabled", true)) + if (!sConfigMgr->GetBoolDefault("PlayerbotV2.GroupWedge.Enabled", true, true)) { if (!groups_.empty()) groups_.clear(); return; @@ -54,11 +54,11 @@ void GroupWedgeWatchdog::Update(uint32 now_ms) // Tunables (read live so they are hot-reloadable; quiet defaults so the keys // are optional). A wedge is "no forward progress (group centroid moved // < MoveYards) AND not in real combat for WindowMs". - const uint32 windowMs = uint32(sConfigMgr->GetIntDefault("PlayerbotV2.GroupWedge.WindowMs", 20000)); - const float cohereY = float(sConfigMgr->GetFloatDefault("PlayerbotV2.GroupWedge.CohereYards", 30.0)); - const float splitY = float(sConfigMgr->GetFloatDefault("PlayerbotV2.GroupWedge.SplitYards", 45.0)); - const float farY = float(sConfigMgr->GetFloatDefault("PlayerbotV2.GroupWedge.FarYards", 45.0)); - const float moveY = float(sConfigMgr->GetFloatDefault("PlayerbotV2.GroupWedge.MoveYards", 12.0)); + const uint32 windowMs = uint32(sConfigMgr->GetIntDefault("PlayerbotV2.GroupWedge.WindowMs", 20000, true)); + const float cohereY = float(sConfigMgr->GetFloatDefault("PlayerbotV2.GroupWedge.CohereYards", 30.0, true)); + const float splitY = float(sConfigMgr->GetFloatDefault("PlayerbotV2.GroupWedge.SplitYards", 45.0, true)); + const float farY = float(sConfigMgr->GetFloatDefault("PlayerbotV2.GroupWedge.FarYards", 45.0, true)); + const float moveY = float(sConfigMgr->GetFloatDefault("PlayerbotV2.GroupWedge.MoveYards", 12.0, true)); // -- Bucket grouped, instanced bots by (group, map) (mirror PveGroupCoordinator) -- struct Bucket @@ -66,6 +66,7 @@ void GroupWedgeWatchdog::Update(uint32 now_ms) uint64 group_low = 0; uint32 map_id = 0; std::vector> bots; + bool owner_ordered = false; // a bot is under the owner's Stay / Hold / Follow order: standing still is the order, not a wedge }; std::unordered_map buckets; Services::Registry().for_each([&](BotId id, BotRegistryEntry const& e) @@ -84,6 +85,8 @@ void GroupWedgeWatchdog::Update(uint32 now_ms) b.group_low = glow; b.map_id = m->GetId(); b.bots.emplace_back(uint64(id), p); + if (e.ai->holding_position(now_ms) || e.ai->owner_follow_order()) + b.owner_ordered = true; }); // Forget groups that are no longer bucketed (left instance / disbanded). @@ -96,6 +99,13 @@ void GroupWedgeWatchdog::Update(uint32 now_ms) Services::Snapshots().latest_group(b.bots.front().first); if (!gs || gs->members.empty()) continue; + // A human-led party is the owner's to move (he can be AFK, or wait for his Attack), and an ordered Stay / Hold / Follow is + // standing still on purpose: neither is a wedge. + if (b.owner_ordered || !GroupSnapshotView(*gs).leader_is_bot()) + { + groups_.erase(key); + continue; + } // Alive, same-map member geometry. (Corpse-runners / cross-map laggards // excluded — a wedge is about the live body's progress.) diff --git a/src/modules/PlayerbotV2/Bot/Dungeon/MarkCc.h b/src/modules/PlayerbotV2/Bot/Dungeon/MarkCc.h index 7c0614e671..ac502e8e14 100644 --- a/src/modules/PlayerbotV2/Bot/Dungeon/MarkCc.h +++ b/src/modules/PlayerbotV2/Bot/Dungeon/MarkCc.h @@ -127,6 +127,19 @@ inline void LogRefusal(uint64 bot_low, uint32 now_ms, char const* name, char con TC_LOG_INFO("playerbot.v2", "[mark_cc] {} does not cast: {} (entry {} type {} dist {:.0f})", name, why, entry, ctype, dist); } +// The bot's own crowd control still holds a mob other than `except`. Vanilla Polymorph / Shackle / Banish / Hibernate hold one target per +// caster, so a second cast breaks the first: every crowd-control decider (the group CC pick and the marked CC) asks this one check. +template +bool CasterHoldsAnother(View const& s, ObjectGuid except) +{ + if (s.cls() == CLASS_ROGUE) + return false; // a rogue's Sap holds any number of mobs + for (NearbyUnit const& n : s.raw().combat.nearby_enemies) + if (n.is_cc_locked && n.cc_caster == s.guid() && n.guid != except) + return true; + return false; +} + // Cast the bot's crowd control on `target` (the PveOrder::cc_target mob) when it is not held yet. True when it emitted. template bool TryCast(View const& s, Emit& emit, ObjectGuid target) @@ -146,6 +159,8 @@ bool TryCast(View const& s, Emit& emit, ObjectGuid target) return false; if (u->is_cc_locked) return false; // held (by us or another): the goal + if (CasterHoldsAnother(s, target)) + return LogRefusal(low, now, s.name().c_str(), "this caster's crowd control already holds another mob", u->entry, TypeOf(*u), 0.f), false; // The raid's current kill target, or a mob already under half health, is being killed: a broken hold is not re-applied // (Garr 2026-10-08: the warlocks re-banished the add the raid was finishing and Garr enraged). if (s.raw().pve_order.kill_focus == target) @@ -168,8 +183,8 @@ bool TryCast(View const& s, Emit& emit, ObjectGuid target) return false; } uint32 const spell = SpellFor(s, *o); - if (!s.is_ready(spell)) - return LogRefusal(low, now, s.name().c_str(), "spell not ready", u->entry, TypeOf(*u), dist), false; + // Range and standing still come before the ready check, which refuses a hard cast while the bot walks: a caster held in its + // raid formation slot 26-35 y from the mob was "not ready" for 26 s and never walked in (Majordomo n78: Gorham and Elladu). // 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. @@ -181,11 +196,13 @@ bool TryCast(View const& s, Emit& emit, ObjectGuid target) 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); } // In range but walking (a formation step): stop, the cast goes out next tick (a hard cast is refused while moving). - if (s.is_moving()) + if (s.is_moving() && s.knows_spell(spell)) { emit.stop_movement(); return true; } + if (!s.is_ready(spell)) + return LogRefusal(low, now, s.name().c_str(), "spell not ready", u->entry, TypeOf(*u), dist), false; bool const ok = o->self_cast ? emit.cast(spell) : emit.cast(spell, target); if (ok) TC_LOG_INFO("playerbot.v2", "[mark_cc] cast {} spell={} on entry={} ({}) type={} dist={:.0f}", diff --git a/src/modules/PlayerbotV2/Bot/Dungeon/PveGroupCoordinator.cpp b/src/modules/PlayerbotV2/Bot/Dungeon/PveGroupCoordinator.cpp index 0ad66be543..6edb08c78e 100644 --- a/src/modules/PlayerbotV2/Bot/Dungeon/PveGroupCoordinator.cpp +++ b/src/modules/PlayerbotV2/Bot/Dungeon/PveGroupCoordinator.cpp @@ -40,6 +40,7 @@ #include "WorldSession.h" #include +#include #include #include #include @@ -67,7 +68,7 @@ void PveGroupCoordinator::Update(uint32 now_ms) return; last_plan_ms_ = now_ms; - if (!sConfigMgr->GetBoolDefault("Playerbot.Pve.Coordinator.Enable", true)) + if (!sConfigMgr->GetBoolDefault("Playerbot.Pve.Coordinator.Enable", true, true)) { if (!orders_.empty()) orders_.clear(); last_dump_ = "coordinator disabled (Playerbot.Pve.Coordinator.Enable=0)"; @@ -112,15 +113,15 @@ void PveGroupCoordinator::Update(uint32 now_ms) if (p->IsAlive() && p->IsInCombat()) b.in_combat = true; // The owner's go (MarksNeedOrder): an attack / engage order, a /focus pin or a pull back running on a member bot. - // A pull back is NOT the group's go (Karrz, MC Molten Giants 2026-10-08: four marked tanks pulled back and the whole raid + // A pull back is NOT the group's go (playtest, MC Molten Giants 2026-10-08: four marked tanks pulled back and the whole raid // ran in): only the pulling tank is released; the others wait until the mob is on a tank. if (e.ai->pull_back_active()) b.pullers.push_back(uint64(id)); else if ((!e.ai->focus_target().IsEmpty() || (e.ai->is_manual_mode(now_ms) && e.ai->owner_command() == BotAI::OwnerCommand::Engage)) && - // A Pull is the tanks' own engage: it must not release the rest of the raid (Karrz, MC Gehennas - // 2026-10-08: "pull, then I say attack"). Only a non-tank bot carrying the order is the owner's Attack. - (!m->IsRaid() || BotCommandParser::BotRole(p) != Role::Tank)) + // A Pull is the tanks' own engage: it must not release the rest of the raid (playtest, MC Gehennas + // 2026-10-08: "pull, then I say attack"; a party's Pull waits for the owner's Attack too). Only a non-tank bot carrying the order is the owner's Attack. + BotCommandParser::BotRole(p) != Role::Tank) // raid and 5-man alike: Pull never releases the others b.owner_order = true; // The spoken Attack, however the pull gate treated this bot (only the main tank carries Engage while the mob is idle). if (OwnerAttackRecent(now_ms, e.ai->owner_attack_ms(), kOwnerAttackWindowMs)) @@ -134,10 +135,27 @@ void PveGroupCoordinator::Update(uint32 now_ms) { // Shared group snapshot: one per group per tick, covers EVERY // member including humans (roles, positions, vitals). - std::shared_ptr gs = - Services::Snapshots().latest_group(b.bots.front().first); + // The first bot that has one: a bucket's first bot can be a corpse or a ghost whose group snapshot is gone, and the + // whole raid plan (tanks, curses, [raid_fight]) went silent for the rest of the fight (Ragnaros 2026-10-13: the fight + // lines stopped at 103 s of 249 s, after the first deaths). + std::shared_ptr gs; + for (auto const& [blow, p] : b.bots) + { + gs = Services::Snapshots().latest_group(blow); + if (gs && !gs->members.empty()) + break; + } if (!gs || gs->members.empty()) + { + static uint32 s_cold_log_ms = 0; + if (b.in_combat && now_ms - s_cold_log_ms >= 5000u) + { + s_cold_log_ms = now_ms; + TC_LOG_INFO("playerbot.v2", "[pve_plan] group={} map={} skipped: none of its {} bots has a group snapshot, the raid plan does not run", + b.group_low, b.map_id, uint32(b.bots.size())); + } continue; // group data cold — legacy runs + } // Reference bot snapshot: freshest member view; provides // nearby_enemies for the synchronized kill target and the view @@ -212,7 +230,7 @@ void PveGroupCoordinator::Update(uint32 now_ms) if (b.owner_order) mark_release_until_[bkey] = now_ms + 10000u; // The Attack stands for the whole fight: while the group is in combat a live release is carried on, so it neither - // lapses when the owner dies or his order expires, nor re-holds the DPS mid-fight (Karrz, MC Gehennas 2026-10-08: + // lapses when the owner dies or his order expires, nor re-holds the DPS mid-fight (playtest, MC Gehennas 2026-10-08: // rogues idle after the owner fell). It ends 10 s after the fight. else if (b.in_combat && mark_release_until_.count(bkey) && now_ms < mark_release_until_[bkey]) mark_release_until_[bkey] = now_ms + 10000u; @@ -372,6 +390,12 @@ void PveGroupCoordinator::Update(uint32 now_ms) uint64 main_tank = 0, off_tank = 0; for (auto const& e : mem) if (e.tank && e.alive && e.src->is_main_tank) { main_tank = e.guid_low; break; } + // Without the flag the main tank stays whoever it was while that tank lives: a death and a rez no longer hand the role back to the + // lowest guid (tank_duty and the heal quotas flipped twice per death). + if (!main_tank) + if (auto kept = last_main_tank_.find(bkey); kept != last_main_tank_.end()) + for (auto const& e : mem) + if (e.guid_low == kept->second && e.tank && e.alive) { main_tank = e.guid_low; break; } for (auto const& e : mem) { if (!e.tank || !e.alive) continue; @@ -380,6 +404,8 @@ void PveGroupCoordinator::Update(uint32 now_ms) if (!off_tank && wants_off_tank) { off_tank = e.guid_low; continue; } } + if (main_tank) + last_main_tank_[bkey] = main_tank; for (auto const& e : mem) { if (!e.tank) continue; @@ -599,6 +625,26 @@ void PveGroupCoordinator::Update(uint32 now_ms) // The brain plans after this coordinator, so this is its previous plan (one raid cadence old). if (ObjectGuid const rule_focus = Raid::GetBrain().FocusFor(b.group_low, b.map_id); !rule_focus.IsEmpty()) kill_focus = rule_focus; + // The owner's skull, else cross, on a mob somebody fights is the kill target, above the script's priority list and the encounter + // rule: "skull then cross" is the one order the raid always follows (MC Majordomo 2026-10-15: the owner skulled a Flamewaker Healer, + // the priority list picked another one and the raid burned that, while the polymorphers sheeped the skull). + if (!GroupSnapshotView(*gs).leader_is_bot() && b.bots.front().second) + if (Group* kg = b.bots.front().second->GetGroup()) + for (uint8 icon : { uint8(7), uint8(6) }) // skull, cross + { + ObjectGuid const mark = kg->GetTargetIcon(icon); + if (mark.IsEmpty()) + continue; + bool fought = false; + for (auto const& u : ref->combat.nearby_enemies) + if (u.guid == mark && u.hp > 0 && !u.victim.IsEmpty()) + fought = true; + if (fought) + { + kill_focus = mark; + break; + } + } if (kill_focus.IsEmpty()) last_kill_focus_.erase(bkey); else @@ -612,63 +658,6 @@ void PveGroupCoordinator::Update(uint32 now_ms) } } - // -- Auto skull: after the owner's Attack, the skull follows the fight -------------------------------------------- - // When the skull mob dies the skull moves to the next ENGAGED mob (kill focus first, else the most hurt), and the - // cross to the one after if the cross is free, so the owner sees what is next and no DPS waits for a new mark - // (Karrz, MC Gehennas 2026-10-08). Only with a human leader, only once the owner released the marks, only on - // mobs somebody already fights; an unpulled mob is never marked. Nothing happens until the owner has put a skull. - if (marks_released && b.in_combat && !GroupSnapshotView(*gs).leader_is_bot() && b.bots.front().second) - if (Group* grp = b.bots.front().second->GetGroup()) - { - constexpr uint8 kSkull = 7, kCross = 6; - Map* gm = b.bots.front().second->GetMap(); - auto mob_of = [&](ObjectGuid g) -> Creature* { return (gm && !g.IsEmpty()) ? gm->GetCreature(g) : nullptr; }; - auto live = [&](Creature* c) { return c && c->IsAlive(); }; - ObjectGuid const skull = grp->GetTargetIcon(kSkull); - ObjectGuid& seen = last_skull_[bkey]; - if (live(mob_of(skull))) - seen = skull; // the owner's (or a bot's) live skull: this is the one to follow - else if (!seen.IsEmpty()) - { - std::vector engaged; - for (auto const& u : ref->combat.nearby_enemies) - { - if (u.hp <= 0 || u.victim.IsEmpty() || u.guid == seen || u.is_player || u.is_cc_locked) continue; - if (!live(mob_of(u.guid))) continue; - ObjectGuid const cross = grp->GetTargetIcon(kCross); - if (u.guid == cross) continue; - // A mob carrying any other raid icon is a tank's to hold (moon, square, ... = a tank assignment, Karrz, MC Garr - // 2026-10-08: the skull jumped to Garr, marked moon for his own tank, the moment the first add died): the - // skull never moves onto it. - bool tank_marked = false; - for (uint8 icon = 0; icon < 6; ++icon) - if (grp->GetTargetIcon(icon) == u.guid) { tank_marked = true; break; } - if (tank_marked) continue; - engaged.push_back(&u); - } - std::sort(engaged.begin(), engaged.end(), [&](NearbyUnit const* a, NearbyUnit const* c) - { - // Adds before bosses: the boss is the last kill. - bool const ba = a->is_dungeon_boss || a->is_boss_rank, bc = c->is_dungeon_boss || c->is_boss_rank; - if (ba != bc) return !ba; - if ((a->guid == kill_focus) != (c->guid == kill_focus)) return a->guid == kill_focus; - return a->max_hp > 0 && c->max_hp > 0 ? double(a->hp) / a->max_hp < double(c->hp) / c->max_hp : a->hp < c->hp; - }); - ObjectGuid const changer = grp->GetLeaderGUID(); - if (!engaged.empty()) - { - grp->SetTargetIcon(kSkull, engaged[0]->guid, changer); - seen = engaged[0]->guid; - if (!live(mob_of(grp->GetTargetIcon(kCross))) && engaged.size() > 1) - grp->SetTargetIcon(kCross, engaged[1]->guid, changer); - TC_LOG_INFO("playerbot.v2", "[auto_skull] group={} map={} skull -> entry {} ({}), {} engaged", - b.group_low, b.map_id, engaged[0]->entry, engaged[0]->guid.GetCounter(), engaged.size()); - } - else - seen = ObjectGuid::Empty; // nothing engaged left: the next pull starts from the owner's mark - } - } - // -- Raid tank -> mob assignment + fight diagnostics ------------------ PlanRaidTanks(bkey, b.group_low, b.map_id, wants_off_tank, now_ms, main_tank, off_tank, kill_focus, @@ -801,6 +790,8 @@ void PveGroupCoordinator::Update(uint32 now_ms) it = buckets.count(it->first) ? std::next(it) : fight_log_.erase(it); for (auto it = last_tank_target_.begin(); it != last_tank_target_.end();) it = buckets.count(it->first) ? std::next(it) : last_tank_target_.erase(it); + for (auto it = cc_held_.begin(); it != cc_held_.end();) + it = buckets.count(it->first) ? std::next(it) : cc_held_.erase(it); for (auto it = mark_release_until_.begin(); it != mark_release_until_.end();) it = buckets.count(it->first) ? std::next(it) : mark_release_until_.erase(it); for (auto it = fight_start_.begin(); it != fight_start_.end();) @@ -837,8 +828,6 @@ void PveGroupCoordinator::Update(uint32 now_ms) for (auto it = last_kill_focus_.begin(); it != last_kill_focus_.end();) it = buckets.count(it->first) ? std::next(it) : last_kill_focus_.erase(it); - for (auto it = last_skull_.begin(); it != last_skull_.end();) - it = buckets.count(it->first) ? std::next(it) : last_skull_.erase(it); last_dump_ = dump.str(); if (last_dump_.empty()) last_dump_ = "no coordinated dungeon/raid groups"; @@ -1131,6 +1120,7 @@ constexpr uint32 kFightSummaryMs = 3000; // A spare tank never runs further than this for a mob; beyond it the mob // belongs to whoever is closer (or the loose-attacker pick-up). constexpr float kTankAssignRange = 60.0f; +constexpr uint32 kCcHoldMs = 45000; // how long a tank is remembered as the holder of a mob under a group member's crowd control // An unpulled mob this close to an engaged one belongs to the pack (the link-pull reach). constexpr float kPackReach = 25.0f; @@ -1242,6 +1232,11 @@ void PveGroupCoordinator::PlanMarkOrders(uint64 group_low, uint32 map_id, bool i if (e.alive && e.src->max_hp > 0 && Pct(e.src->hp, e.src->max_hp) < 40) { emergency = true; break; } std::vector cc_taken; + bool moon_is_tank_mark = false; + for (auto const& [tank_low, marker] : Services::Owners().TankMarks(group_low)) + if (marker == 4) moon_is_tank_mark = true; + if (auto h = by_low.find(held_by[4]); held_by[4] && h != by_low.end() && h->second->tank) + moon_is_tank_mark = true; // the moon on a tank bot itself // Pass 1: crowd control. Bots in member order, one bot per mob, never the skull, never a boss. if (cc_on) for (auto const& e : mem) @@ -1255,6 +1250,11 @@ void PveGroupCoordinator::PlanMarkOrders(uint64 group_low, uint32 map_id, bool i if (uint8 const h = held_symbol(e.guid_low); h != 0xFF && h != 7) order.push_back(h); for (uint8 c : Services::Owners().RtiOrderOf(e.guid_low).cc) if (c < 7 && std::find(order.begin(), order.end(), c) == order.end()) order.push_back(c); + // No icon or rti cc of its own: the caster holds the owner's moon (ike3's default rti cc). Marked mobs left the auto crowd + // control, so without this a moon nobody was assigned to stayed free. + // Not when the owner gave the moon to a tank ("assign moon" on a tank bot): that tank holds the mob, and a sheep on + // it breaks on the tank's first hit (n71 Majordomo: Deleria sheeped the Healer Yuna was tanking). + if (order.empty() && !moon_is_tank_mark) order.push_back(4); BotSnapshotView const view(*sn->second); // Sticky: a bot keeps its mob while the icon stays on it and the mob lives; a view that loses the mob for a few // seconds (a banished mob drops out of a lock's list) is no release (Garr 2026-10-08: Gustinor was assigned and @@ -1313,6 +1313,96 @@ void PveGroupCoordinator::PlanMarkOrders(uint64 group_low, uint32 map_id, bool i } break; } + // No icon call for this caster: it picks a mob of its own to hold, so the owner never has to assign crowd control + // (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()) + { + static std::mutex auto_cc_mx; + static std::unordered_map auto_cc; // caster -> the mob it holds + auto const& kill_focus_of = [&](ObjectGuid g) + { + for (auto const& [low, o] : plan) + if (o.kill_focus == g) return true; + return false; + }; + std::vector pack; + { + std::unordered_set seen; + for (auto const& sn : snaps) + { + if (sn->position.map_id != map_id) continue; + for (auto const& u : sn->combat.nearby_enemies) + if (u.hp > 0 && !u.is_player && !u.untargetable && u.unit_in_combat && !u.victim.IsEmpty() && + !Classic::IsBossUnit(u) && seen.insert(u.guid.GetCounter()).second) + if (NearbyUnit const* full = unit_any(u.guid)) + pack.push_back(full); + } + } + auto holdable = [&](NearbyUnit const& u) -> bool + { + // A mob carrying any raid icon is the owner's call (or a tank's assignment): no automatic hold on it. Only an icon + // the owner put on a caster sends that caster to hold it (the loop above). + for (ObjectGuid const& marked : icon) + if (u.guid == marked) return false; + if (kill_focus_of(u.guid)) return false; + // Nor the mob the owner (any human) or a tank is hitting: a sheep on it breaks at once and is recast, over and over. + for (auto const& m : mem) + if ((!m.is_bot || m.tank) && m.src && m.src->victim == u.guid) return false; + if (is_raid) + if (Raid::RaidRules const* rr = Raid::RulesForMap(map_id)) + for (Raid::CrowdControl const& rule : rr->crowdControl) + if (rule.enemy == u.entry) return false; + if (u.max_hp > 0 && u.hp * 2 < u.max_hp) return false; + if (std::find(cc_taken.begin(), cc_taken.end(), u.guid) != cc_taken.end()) return false; + MarkCc::Option const* opt = MarkCc::PickOption(view, e.cls, MarkCc::TypeOf(u), !e.src->in_combat && !u.unit_in_combat); + // A root is not a hold on a caster: a rooted Flamewaker Elite stands and fireballs the healers (n71 Majordomo: four + // raid members died to Fireball). Only the owner's own mark roots one. + return opt && !(opt->root && u.is_ranged_caster); + }; + ObjectGuid pick; + { + std::lock_guard lk(auto_cc_mx); + if (auto it = auto_cc.find(e.guid_low); it != auto_cc.end()) + { + NearbyUnit const* kept_u = unit_any(it->second); + if (kept_u && holdable(*kept_u)) + pick = it->second; + else + auto_cc.erase(it); + } + } + if (pick.IsEmpty() && pack.size() >= 3) + { + // Mobs nobody tanks first (they are on a member), then the lowest guid so every plan chooses the same one. + NearbyUnit const* best = nullptr; + bool best_loose = false; + for (NearbyUnit const* u : pack) + { + if (!holdable(*u)) continue; + auto tv = by_low.find(u->victim.GetCounter()); + bool const loose = tv == by_low.end() || !tv->second->tank; + if (!best || (loose && !best_loose) || (loose == best_loose && u->guid.GetCounter() < best->guid.GetCounter())) + { + best = u; + best_loose = loose; + } + } + if (best) + { + pick = best->guid; + std::lock_guard lk(auto_cc_mx); + auto_cc[e.guid_low] = pick; + } + } + if (!pick.IsEmpty()) + { + po->second.cc_target = pick; + po->second.cc_symbol = 0xFF; + cc_taken.push_back(pick); + } + } } // [mark_cc] assign / break / release, change-detected per bot (the plan runs every tick). @@ -1395,7 +1485,9 @@ void PveGroupCoordinator::PlanMarkOrders(uint64 group_low, uint32 map_id, bool i if (!u || o.cc_reserved_mob(u->guid)) continue; if (u->is_cc_locked && sym != 7) continue; // a held mob is left alone unless it is the skull o.mark_target = u->guid; - if (u->unit_in_combat) o.kill_focus = u->guid; // engaged mobs only: an unpulled mob stays the tank's call + // Engaged mobs only: an unpulled mob stays the tank's call. A bot's own kill symbol never replaces the group's kill focus + // (the owner's skull / cross); only an icon the owner put on that bot does. + if (u->unit_in_combat && (o.kill_focus.IsEmpty() || held != 0xFF)) o.kill_focus = u->guid; break; } } @@ -1568,12 +1660,14 @@ void PveGroupCoordinator::PlanRaidTanks(uint64 bkey, uint64 group_low, uint32 ma for (auto it = sticky.begin(); it != sticky.end();) { auto t = by_low.find(it->first); - const bool keep = t != by_low.end() && t->second->tank && t->second->alive && - find_mob(it->second) != nullptr; + bool keep = t != by_low.end() && t->second->tank && t->second->alive && + find_mob(it->second) != nullptr; if (!keep && t != by_low.end() && t->second->tank && t->second->alive) { // [raid_tank] why a tank lost its mob (Garr 2026-10-08: one tank hopped between Firesworn ~15 times). NearbyUnit const* gone = unit_any_early(it->second); + if (gone && gone->is_cc_locked && member_of(gone->cc_caster)) + cc_held_[bkey][it->second.GetCounter()] = { t->first, now_ms + kCcHoldMs }; TC_LOG_INFO("playerbot.v2", "[raid_tank] group={} map={} {} drops {} ({}): {}", group_low, map_id, t->second->src->name, it->second.GetEntry(), it->second.GetCounter(), !gone ? "out of every view or dead" : (gone->is_cc_locked ? "crowd-controlled" : (!gone->unit_in_combat ? "out of combat" : "no longer hitting the group"))); @@ -1700,6 +1794,7 @@ void PveGroupCoordinator::PlanRaidTanks(uint64 bkey, uint64 group_low, uint32 ma auto assign = [&](Member const* t, Mob const& m, char const* why) { sticky[t->guid_low] = m.u->guid; + cc_held_[bkey].erase(m.u->guid.GetCounter()); taken.push_back(m.u->guid); const float dx = m.u->x - t->src->x, dy = m.u->y - t->src->y; Member const* v = member_of(m.u->victim); @@ -1721,31 +1816,70 @@ void PveGroupCoordinator::PlanRaidTanks(uint64 bkey, uint64 group_low, uint32 ma Mob const* held = find_mob(sit->second); return held && held->u->guid != m.u->guid && (held->u->is_dungeon_boss || held->u->is_boss_rank); }; + // Holds of this bucket still in force: one that ran out is dropped (a CC'd mob is not in `mobs`, so only time ends it). + auto& cc_held = cc_held_[bkey]; + for (auto it = cc_held.begin(); it != cc_held.end();) + it = now_ms >= it->second.until_ms ? cc_held.erase(it) : std::next(it); + // A mob carrying an icon the owner gave a crowd-control caster is that caster's (Majordomo n78: the circle on an Elite was + // Scott's, and Hannorto took the same Elite as "nearest", so his hits broke the sheep over and over). Tanks leave it alone + // until it is loose on a member. + auto cc_owned = [&](Mob const& m) -> bool + { + if (!mk_grp || m.loose) return false; + for (uint8 sym = 0; sym < 7; ++sym) + { + if (mk_grp->GetTargetIcon(sym) != m.u->guid) continue; + for (Member const& e : mem) + { + if (!e.is_bot || e.tank || !MarkCc::IsMarkCcClass(e.cls)) continue; + if (held_by[sym] == e.guid_low) return true; + for (uint8 c : Services::Owners().RtiOrderOf(e.guid_low).cc) + if (c == sym) return true; + } + } + return false; + }; auto nearest_free = [&](Member const* t) -> Mob const* { auto rank = [&](Mob const& m) -> int { if (Raid::NoTank(map_id, m.u->entry)) return 3; + if (Raid::TankLast(map_id, m.u->entry)) return 4; // Majordomo: the tank left over takes him + if (auto const hold = cc_held.find(m.u->guid.GetCounter()); hold != cc_held.end() && hold->second.tank_low == t->guid_low) + return -1; // the tank that held it before the crowd control ended takes it back first if (m.loose) return 0; return on_boss_tank(m) ? 1 : 2; }; Mob const* best = nullptr; int best_rank = 99; + uint32 best_order = UINT32_MAX; float best_d2 = kTankAssignRange * kTankAssignRange; for (auto const& m : mobs) { - if (is_taken(m.u->guid)) continue; + if (is_taken(m.u->guid) || cc_owned(m)) continue; const float dx = m.u->x - t->src->x, dy = m.u->y - t->src->y; const float d2 = dx * dx + dy * dy; if (d2 > kTankAssignRange * kTankAssignRange) continue; const int r = rank(m); - if (best && (r > best_rank || (r == best_rank && d2 >= best_d2))) continue; + // Within a class the encounter's tank order comes before distance (Majordomo: Healers, then Elites). + const uint32 order = Raid::TankOrder(map_id, m.u->entry); + if (best && (r > best_rank || (r == best_rank && (order > best_order || (order == best_order && d2 >= best_d2))))) continue; best = &m; best_rank = r; + best_order = order; best_d2 = d2; } return best; }; + // A free engaged mob other than that is neither a summoned add nor one the rules leave to the tank left over: while one + // exists, a tankLast mob (Majordomo) is nobody's to hold. + auto other_free_mob = [&](ObjectGuid except) -> bool + { + for (auto const& m : mobs) + if (m.u->guid != except && !is_taken(m.u->guid) && !Raid::NoTank(map_id, m.u->entry) && !Raid::TankLast(map_id, m.u->entry)) + return true; + return false; + }; // The main tank chooses first: the mob it already hits (its pull), else the mob engaged with it, else the // nearest. Without this a spare tank that ran at the pull target before the main tank had a victim of its own // would be handed the main tank's mob, and the main tank the next one. @@ -1757,19 +1891,35 @@ void PveGroupCoordinator::PlanRaidTanks(uint64 bkey, uint64 group_low, uint32 ma Mob const* pick = find_mob(t->src->victim); char const* why = "already_on_it"; if (pick && Raid::NoTank(map_id, pick->u->entry)) pick = nullptr; // a Spawn is no mob to hold + if (pick && Raid::TankLast(map_id, pick->u->entry) && other_free_mob(pick->u->guid)) pick = nullptr; // the adds first if (!pick || is_taken(pick->u->guid)) { pick = nullptr; for (auto const& m : mobs) - if (m.u->victim == t->src->guid && !is_taken(m.u->guid)) { pick = &m; why = "on_main_tank"; break; } + if (m.u->victim == t->src->guid && !is_taken(m.u->guid) && + !(Raid::TankLast(map_id, m.u->entry) && other_free_mob(m.u->guid))) { pick = &m; why = "on_main_tank"; break; } } if (!pick) { pick = nearest_free(t); why = "nearest"; } if (pick) assign(t, *pick, why); } + // A mob that has just come off a group member's crowd control goes back to the tank that held it, before any other tank + // is offered it as a loose mob. for (Member const* t : tanks) { if (!t->is_bot || sticky.count(t->guid_low)) continue; - if (Mob const* cur = find_mob(t->src->victim); cur && !is_taken(cur->u->guid) && !Raid::NoTank(map_id, cur->u->entry)) + for (auto const& m : mobs) + if (auto const hold = cc_held.find(m.u->guid.GetCounter()); + hold != cc_held.end() && hold->second.tank_low == t->guid_low && !is_taken(m.u->guid) && !Raid::NoTank(map_id, m.u->entry)) + { + assign(t, m, "cc_released"); + break; + } + } + for (Member const* t : tanks) + { + if (!t->is_bot || sticky.count(t->guid_low)) continue; + if (Mob const* cur = find_mob(t->src->victim); cur && !is_taken(cur->u->guid) && !Raid::NoTank(map_id, cur->u->entry) && + !(Raid::TankLast(map_id, cur->u->entry) && other_free_mob(cur->u->guid))) assign(t, *cur, "already_on_it"); } for (Member const* t : tanks) @@ -1782,6 +1932,46 @@ void PveGroupCoordinator::PlanRaidTanks(uint64 bkey, uint64 group_low, uint32 ma assign(t, *best, best->loose ? "loose_nearest" : "nearest"); } } + // -- The owner's skull and cross are held by a tank ----------------------- + // They are the owner's kill calls, and a mob nobody tanks is on a healer or a mage while the raid burns it (n78 Majordomo: the + // skull moved onto a sheeped Healer, the sheep broke, and no tank took it; then the cross Healer ran loose for 20 s and killed + // the owner, while every tank sat on its own Elite or dropped target). A tank with no symbol of the owner's drops its mob for + // it: the main tank first, else the one with the fewest mobs on it. Skull first, then cross, each on a different tank. + if (mk_grp) + for (uint8 const kill_icon : { uint8(7), uint8(6) }) + { + ObjectGuid const sk = mk_grp->GetTargetIcon(kill_icon); + if (sk.IsEmpty()) continue; + Mob const* sm = find_mob(sk); + if (!sm || is_taken(sk) || Raid::NoTank(map_id, sm->u->entry) || sm->u->is_dungeon_boss || sm->u->is_boss_rank) + continue; + Member const* best = nullptr; + size_t best_load = SIZE_MAX; + for (Member const* t : tanks) + { + if (!t->is_bot || !t->alive || user_sym.count(t->guid_low)) continue; + // A tank already on the other kill mark keeps it. + if (auto sit = sticky.find(t->guid_low); sit != sticky.end() && + (sit->second == mk_grp->GetTargetIcon(7) || sit->second == mk_grp->GetTargetIcon(6))) + continue; + size_t load = 0; + for (Mob const& o : mobs) + if (o.u->victim == t->src->guid) ++load; + if (!best || (t->guid_low == main_tank && best->guid_low != main_tank) || + (best->guid_low != main_tank && load < best_load)) + { + best = t; + best_load = load; + } + } + if (!best) continue; + if (auto sit = sticky.find(best->guid_low); sit != sticky.end()) + { + taken.erase(std::remove(taken.begin(), taken.end(), sit->second), taken.end()); + sticky.erase(sit); + } + assign(best, *sm, kill_icon == 7 ? "owner_skull" : "owner_cross"); + } // -- The boss is never left without a tank ---------------------------- // An engaged boss nobody holds (its tank died, or every tank is busy with adds) is the threat that wipes the raid; // the strongest bot tank drops its add for it, the add becoming a free mob for the next pass (Garr 2026-10-08: the @@ -1791,15 +1981,32 @@ void PveGroupCoordinator::PlanRaidTanks(uint64 bkey, uint64 group_low, uint32 ma { if (!(m.u->is_dungeon_boss || m.u->is_boss_rank) || Raid::NoTank(map_id, m.u->entry) || is_taken(m.u->guid)) continue; + bool const tank_last = Raid::TankLast(map_id, m.u->entry); + bool const adds_up = tank_last && + std::any_of(mobs.begin(), mobs.end(), [&](Mob const& o) { return o.u->guid != m.u->guid && !Raid::NoTank(map_id, o.u->entry) && !Raid::TankLast(map_id, o.u->entry); }); + // No tank leaves an add for him while an add is loose: the adds are the threat. Once every add is held he goes to the tank with + // the fewest mobs on it, not to whichever tank is left (n44 mc_majordomo: nobody held him, he stood on a healer all fight and + // killed two by melee). + if (adds_up && std::any_of(mobs.begin(), mobs.end(), [&](Mob const& o) { return o.loose && !Raid::NoTank(map_id, o.u->entry) && !Raid::TankLast(map_id, o.u->entry); })) + continue; Member const* best = nullptr; + size_t best_load = SIZE_MAX; for (Member const* t : tanks) { if (!t->is_bot || user_sym.count(t->guid_low)) continue; - // The main tank first, else the healthiest. - bool const better = !best || (t->guid_low == main_tank && best->guid_low != main_tank) || - (best->guid_low != main_tank && Pct(t->src->hp, t->src->max_hp) > Pct(best->src->hp, best->src->max_hp)); + size_t load = 0; + if (adds_up) + for (Mob const& o : mobs) + if (o.u->victim == t->src->guid && o.u->guid != m.u->guid) ++load; + // The main tank first, else the healthiest (else, with adds up, the lightest load first). + bool const better = !best || (adds_up ? (load < best_load || (load == best_load && Pct(t->src->hp, t->src->max_hp) > Pct(best->src->hp, best->src->max_hp))) + : ((t->guid_low == main_tank && best->guid_low != main_tank) || + (best->guid_low != main_tank && Pct(t->src->hp, t->src->max_hp) > Pct(best->src->hp, best->src->max_hp)))); if (better) + { best = t; + best_load = load; + } } if (!best) break; if (auto sit = sticky.find(best->guid_low); sit != sticky.end()) @@ -1957,7 +2164,8 @@ void PveGroupCoordinator::PlanRaidTanks(uint64 bkey, uint64 group_low, uint32 ma } // Never skull or cross: those are the owner's kill call (explicit_kill_mark), not a tank's assignment (Garr 2026-10-08: the // main tank marked the boss with skull and the raid left the adds). - static constexpr uint8 kOrder[] = { 0, 1, 2, 3, 4, 5 }; + // Nor moon: it is the owner's crowd-control call, and a caster holds whatever carries it. + static constexpr uint8 kOrder[] = { 0, 1, 2, 3, 5 }; // An icon is never used automatically while a member holds it (the owner's symbol on a bot). auto marker_used = [&](uint8 m) { @@ -2002,7 +2210,7 @@ void PveGroupCoordinator::PlanRaidTanks(uint64 bkey, uint64 group_low, uint32 ma } // -- Generic raid kill focus ---------------------------------------- - // Karrz's raid DPS target (DpsTargetValue McFocusTarget): every DPS + // the owner's raid DPS target (DpsTargetValue McFocusTarget): every DPS // on ONE engaged, non-CC'd mob, lowest health first, instead of each // bot opening on whatever is nearest - 30 DPS spread over a pack // out-threat every tank at once. A dungeon script's priority add @@ -2050,7 +2258,7 @@ void PveGroupCoordinator::PlanRaidTanks(uint64 bkey, uint64 group_low, uint32 ma if (mk_grp) for (uint8 m : { uint8(7), uint8(6), uint8(0), uint8(1), uint8(2), uint8(3), uint8(4), uint8(5) }) { - // Only skull and cross are kill orders; the other icons are tank / crowd-control markers (Karrz, MC Garr + // Only skull and cross are kill orders; the other icons are tank / crowd-control markers (playtest, MC Garr // 2026-10-08: circle marked on Garr and every DPS attacked it). An icon some bot has as its own kill symbol // (assign kill) stays a kill order for the group. bool kill_icon = m >= 6; @@ -2093,8 +2301,10 @@ void PveGroupCoordinator::PlanRaidTanks(uint64 bkey, uint64 group_low, uint32 ma // (Garr 2026-10-09: the skull Firesworn read all-school immune and 3 DPS held for minutes). The next mark or the // generic pick takes over; the skull returns to it once the immunity ends. !Raid::GetBrain().AllSchoolsAvoided(group_low, map_id, u.guid) && - // A skull the owner puts on a crowd-controlled mob is the call to kill it: the CC is released. - !(u.is_cc_locked && member_of(u.cc_caster) && !(explicit_call && idle_call)) && + // A skull the owner puts on a crowd-controlled mob is the call to kill it, in a fight too: the caster stops + // holding it (TryCast refuses the kill target) and the raid switches (n71 Majordomo: the owner rotates the + // skull onto each sheeped Healer in turn). Any other mark on a held mob is no kill call. + !(u.is_cc_locked && member_of(u.cc_caster) && !explicit_call) && (u.unit_in_combat || (explicit_call && idle_call))) marked = &u; break; @@ -2134,8 +2344,13 @@ void PveGroupCoordinator::PlanRaidTanks(uint64 bkey, uint64 group_low, uint32 ma auto loose_unowned = [&](Mob const& m) { return m.loose && !is_taken(m.u->guid); }; Mob const* pick = nullptr; bool pick_loose = false; + // A mob the encounter's rules mark "never a DPS target" (Majordomo: he surrenders when the adds die) is no focus, with or + // without adds engaged this tick. + Raid::RaidRules const* const focus_rules = Raid::RulesForMap(map_id); + auto never_target = [&](NearbyUnit const& u) { return focus_rules && Raid::PriorityFor(*focus_rules, u.entry) < 0; }; for (auto const& m : mobs) { + if (never_target(*m.u)) continue; if (adds_alive && is_boss(*m.u)) continue; // adds first, the boss last const bool lu = loose_unowned(m); if (!lu && !tank_held(m)) continue; @@ -2158,7 +2373,7 @@ void PveGroupCoordinator::PlanRaidTanks(uint64 bkey, uint64 group_low, uint32 ma if (auto mt = by_low.find(main_tank); mt != by_low.end() && mt->second->alive) mtm = mt->second; if (!mtm && !tanks.empty()) mtm = tanks.front(); if (mtm) - if (Mob const* mm = find_mob(mtm->src->victim); mm && !(adds_alive && is_boss(*mm->u))) + if (Mob const* mm = find_mob(mtm->src->victim); mm && !(adds_alive && is_boss(*mm->u)) && !never_target(*mm->u)) { pick = mm; pick_is_mt = true; @@ -2169,7 +2384,10 @@ void PveGroupCoordinator::PlanRaidTanks(uint64 bkey, uint64 group_low, uint32 ma auto it = last_raid_focus_.find(bkey); return it != last_raid_focus_.end() ? it->second : ObjectGuid::Empty; }(); - if (Mob const* pm = find_mob(prev); pm && pick && pm != pick && !pick_is_mt) + // 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)) { const bool plu = loose_unowned(*pm); if ((plu || tank_held(*pm)) && (plu || !pick_loose)) @@ -2219,6 +2437,7 @@ void PveGroupCoordinator::PlanRaidTanks(uint64 bkey, uint64 group_low, uint32 ma else { last_tank_target_.erase(bkey); + cc_held_.erase(bkey); last_raid_focus_.erase(bkey); tank_mark_auto_.erase(bkey); marks_set_.erase(bkey); @@ -2465,6 +2684,67 @@ NearbyUnit const* EngagedBoss(uint32 map_id, std::vectorGetAppliedAuras()) + if (!app->IsPositive()) + ++n; + return n; +} + +char const* ClassTag(uint8 cls) +{ + switch (cls) + { + case CLASS_WARRIOR: return "warrior"; + case CLASS_PALADIN: return "paladin"; + case CLASS_HUNTER: return "hunter"; + case CLASS_ROGUE: return "rogue"; + case CLASS_PRIEST: return "priest"; + case CLASS_SHAMAN: return "shaman"; + case CLASS_MAGE: return "mage"; + case CLASS_WARLOCK: return "warlock"; + case CLASS_DRUID: return "druid"; + default: return "other"; + } +} + +// What the raid has put on its boss: every harmful aura a player cast, with stacks, time left and the caster's class, and how many of +// the boss's debuff slots are taken. One line per 10 s while the boss is engaged. +void LogBossDebuffs(uint64 group_low, uint32 map_id, Creature* boss, uint32 now_ms) +{ + static std::unordered_map s_last; + uint32& last = s_last[group_low]; + if (last && now_ms - last < 10'000u) + return; + last = now_ms ? now_ms : 1u; + std::string list; + for (auto const& [id, app] : boss->GetAppliedAuras()) + { + if (app->IsPositive()) + continue; + Aura const* a = app->GetBase(); + Unit* caster = a->GetCaster(); + if (!caster || !caster->IsPlayer()) + continue; + SpellInfo const* si = a->GetSpellInfo(); + if (!list.empty()) list += ", "; + list += std::string(si && si->SpellName && (*si->SpellName)[LOCALE_enUS] ? (*si->SpellName)[LOCALE_enUS] : "?") + " " + std::to_string(a->GetId()); + if (a->GetStackAmount() > 1) + list += " x" + std::to_string(a->GetStackAmount()); + list += std::string(" (") + ClassTag(caster->GetClass()) + (a->IsPermanent() ? "" : ", " + std::to_string(a->GetDuration() / 1000) + " s") + ")"; + } + uint32 const slots = HarmfulAuraCount(boss); + TC_LOG_INFO("playerbot.v2", "[raid_debuffs] group={} map={} {} {}% carries {}/{} debuff slots: {}{}", + group_low, map_id, boss->GetName(), uint32(boss->GetHealthPct()), slots, kBossDebuffSlots, + list.empty() ? std::string("none from the raid") : list, slots >= kBossDebuffSlots ? " (full)" : ""); +} + } // namespace void PveGroupCoordinator::PlanCurses(uint64 bkey, uint64 group_low, uint32 map_id, bool is_raid, @@ -2482,6 +2762,15 @@ void PveGroupCoordinator::PlanCurses(uint64 bkey, uint64 group_low, uint32 map_i std::unordered_map snap_of; for (auto const& sp : snaps) snap_of[sp->guid.GetCounter()] = sp.get(); + // What the raid has put on the boss it fights, whether or not a warlock is in it. + if (NearbyUnit const* fb = EngagedBoss(map_id, snaps, false)) + for (auto const& [low, p] : bots) + if (p && p->IsInWorld() && p->GetMapId() == map_id) + { + if (Creature* bc = ObjectAccessor::GetCreature(*p, fb->guid); bc && bc->IsAlive()) + LogBossDebuffs(group_low, map_id, bc, GameTime::GetGameTimeMS()); + break; + } // The raid's bot warlocks by guid (census order puts bots by guid). std::vector locks; std::vector lock_guids; @@ -2568,8 +2857,9 @@ void PveGroupCoordinator::PlanCurses(uint64 bkey, uint64 group_low, uint32 map_i } } // Agony stacks across casters; two of them are plenty and leave the boss's debuff slots to Sunder / Faerie Fire / Expose. + // Only while the boss has slots to spare: a full list loses a Sunder stack or a Faerie Fire to the next debuff cast. uint32 agony = 0; - if (!immune(CURSE_OF_AGONY)) + if (!immune(CURSE_OF_AGONY) && HarmfulAuraCount(mob) + 2 < kBossDebuffSlots) for (Member const* l : locks) if (agony < 2 && !assign.count(l->guid_low) && knows(l, CURSE_OF_AGONY)) { @@ -2702,7 +2992,7 @@ void PveGroupCoordinator::PlanFearAndResist(uint64 bkey, uint64 group_low, uint3 // -- Resistance potions (opt-in): a boss of a resistance instance engaged. uint32 potion = 0; NearbyUnit const* boss = nullptr; - if (sConfigMgr->GetBoolDefault("Playerbot.Raid.ResistPotions", false)) + if (sConfigMgr->GetBoolDefault("Playerbot.Raid.ResistPotions", false, true)) if (uint32 const item = Classic::ResistPotionItem(Classic::InstanceResistance(map_id))) if ((boss = EngagedBoss(map_id, snaps, false)) != nullptr) potion = item; @@ -2717,6 +3007,21 @@ void PveGroupCoordinator::PlanFearAndResist(uint64 bkey, uint64 group_low, uint3 if (potion) for (auto& [low, o] : plan) o.resist_potion = potion; + // Boss data (RaidRules::resistPotion): the potion a role drinks when this boss is engaged, whatever the global switch says. Ragnaros' + // Elemental Fire killed five tanks in three minutes (MC 2026-10-12). The global order, when on, wins for the bots it covers. + if (Raid::RaidRules const* rules = Raid::RulesForMap(map_id)) + if (!rules->resistPotion.empty()) + if (NearbyUnit const* eng = EngagedBoss(map_id, snaps, false)) + for (Raid::ResistPotion const& rp : rules->resistPotion) + if (rp.enemy == eng->entry) + for (auto& [low, o] : plan) + { + auto const mit = by_low.find(low); + if (o.resist_potion || mit == by_low.end()) + continue; + if (rp.who == Raid::Who::Anyone || (rp.who == Raid::Who::Tank && mit->second->tank)) + o.resist_potion = rp.item; + } } std::string PveGroupCoordinator::DebugDump() const diff --git a/src/modules/PlayerbotV2/Bot/Dungeon/PveGroupCoordinator.h b/src/modules/PlayerbotV2/Bot/Dungeon/PveGroupCoordinator.h index ef2ef9b93a..f641e065db 100644 --- a/src/modules/PlayerbotV2/Bot/Dungeon/PveGroupCoordinator.h +++ b/src/modules/PlayerbotV2/Bot/Dungeon/PveGroupCoordinator.h @@ -29,7 +29,7 @@ // is ever moved to run concurrently with the build, orders_ needs a shared_mutex. // Inputs are the published immutable GroupSnapshot / BotSnapshot shared_ptrs and // DungeonScriptMgr::GetAdvice computed HERE from a member snapshot — never a -// BotAI-owned cache (those are AI-worker property; reading them cross-thread is a +// BotAI-owned cache (those are bot-worker property; reading them cross-thread is a // use-after-free, see the 2026-06-10 BG coordinator review). // // Human members are never ordered, but they OCCUPY duties: a human tank @@ -62,7 +62,7 @@ public: // Order lookup for the snapshot builder. Returns nullptr when no // current plan covers the bot (consumer publishes a default-inactive - // order and the AI runs legacy logic). + // order and the bot logic runs legacy logic). PveOrder const* OrderFor(uint64 bot_guid_low) const { auto it = orders_.find(bot_guid_low); @@ -157,10 +157,15 @@ private: // than a read-back from member orders, which broke when the sampled // member left the group or the data ticked cold. std::unordered_map last_kill_focus_; - std::unordered_map last_skull_; // the skull mob the auto-skull follows (per group bucket) // Per-(group, map) raid tank -> mob assignment, sticky while the mob // lives so tanks don't trade mobs (and threat) every plan. std::unordered_map> last_tank_target_; + std::unordered_map last_main_tank_; // bucket -> guid low of the main tank, kept while that tank lives + // Per-(group, map): the tank that held a mob when a group member's crowd control (Banish, Polymorph, Shackle) took it out of the + // assignment -> that tank, until when. When the CC ends the same tank takes the mob back first (MC Garr 2026-10-12: banished + // Firesworn came off and hit mages while the nearest tank was 27-57 y away). + struct CcHold { uint64 tank_low = 0; uint32 until_ms = 0; }; + std::unordered_map> cc_held_; // bucket -> mob guid counter -> hold // Per-(group, map) raid tank roster (guid lows, duty order): the tank-spec // members that act as tanks. Grows while the raid fights, shrinks back // out of combat; the other tank-spec bots play DPS (raid_dps_tank). diff --git a/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/BlackwingDescentScript.cpp b/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/BlackwingDescentScript.cpp index 3845290131..4f177fc6d6 100644 --- a/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/BlackwingDescentScript.cpp +++ b/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/BlackwingDescentScript.cpp @@ -22,7 +22,7 @@ public: DungeonAdvice a; // TC has no boss scripts for BWD; generic combat applies. // Boss progression — NPC entries from TC's blackwing_descent.h - // (the instance script defines them even though boss AI doesn't). + // (the instance script defines them even though boss bot logic doesn't). // Omnotron Defense System isn't in the TC header — standard // entries 42180-42183 (Arcanotron/Electron/Magmatron/Toxitron); // listing the lead controller entry only. diff --git a/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/DeadminesScript.cpp b/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/DeadminesScript.cpp index db008b288d..2a28f94778 100644 --- a/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/DeadminesScript.cpp +++ b/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/DeadminesScript.cpp @@ -98,7 +98,7 @@ public: // 734/48418 = foundry-gauntlet adds/Envoker. The trailing five are the // HARBOR-FLOOR Defias casters (FoeReaper->Ripsnarl): once the DPS // assist-engage there (harbor_focus_kill suppresses pre-emptive CC, see - // State_Idle), the combat AI focus-fires these ranged sources FIRST so + // State_Idle), the combat bot logic focus-fires these ranged sources FIRST so // the burst that kills the tank is removed fastest — the tank can no // longer be left to solo them (live 2026-06-28: tank death-ground while // the DPS only sheeped these). 48417 Blood Wizard (bolt + pack-heal) and diff --git a/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/DragonSoulScript.cpp b/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/DragonSoulScript.cpp index c9af5ae0f1..bab4b824cf 100644 --- a/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/DragonSoulScript.cpp +++ b/src/modules/PlayerbotV2/Bot/Dungeon/Scripts/DragonSoulScript.cpp @@ -21,7 +21,7 @@ public: { DungeonAdvice a; // Boss progression — Dragon Soul has 8 encounters. - // TC has no boss AI; entries from WoWHead community data. + // TC has no boss bot logic; entries from WoWHead community data. a.bosses = { 55265, // Morchok 55308, // Warlord Zon'ozz diff --git a/src/modules/PlayerbotV2/Bot/Dungeon/Tactics/DungeonTactics.h b/src/modules/PlayerbotV2/Bot/Dungeon/Tactics/DungeonTactics.h index 7f72009d35..671439eabb 100644 --- a/src/modules/PlayerbotV2/Bot/Dungeon/Tactics/DungeonTactics.h +++ b/src/modules/PlayerbotV2/Bot/Dungeon/Tactics/DungeonTactics.h @@ -63,7 +63,7 @@ constexpr uint8_t StopDamage = 16; // the mob is immune for a while: hold the d namespace Disp { enum : uint8_t { None, Magic, Curse, Poison, Disease }; } namespace Tgt { enum : uint8_t { Self, Victim, Random, RandomNotTop, Invoker, Friendly, Position, Other }; } -// When the AI casts it: in the fight on a timer, out of combat, when the fight starts, when it spawns, when it dies, when it evades, +// When the bot logic casts it: in the fight on a timer, out of combat, when the fight starts, when it spawns, when it dies, when it evades, // or on an ally that lacks the buff. namespace When { enum : uint8_t { Combat, Ooc, Aggro, Spawn, Death, Evade, AllyUnbuffed }; } @@ -160,7 +160,7 @@ MapTactics const* TacticsForMap(uint32_t map); // One creature of a map, nullptr when the table does not list it. MobTactic const* FindMob(uint32_t map, uint32_t entry); -// The tactics as the lists the dungeon AI already reads (kill order, mandatory interrupts, crowd control targets, dispel priorities). +// The tactics as the lists the dungeon bot logic already reads (kill order, mandatory interrupts, crowd control targets, dispel priorities). // Appends to `advice`; DungeonScriptMgr::GetAdvice removes the duplicates afterwards. void AppendAdvice(uint32_t map, DungeonAdvice& advice); diff --git a/src/modules/PlayerbotV2/Bot/FlatIndex.h b/src/modules/PlayerbotV2/Bot/FlatIndex.h index 7615aeeb4b..2fd86deffe 100644 --- a/src/modules/PlayerbotV2/Bot/FlatIndex.h +++ b/src/modules/PlayerbotV2/Bot/FlatIndex.h @@ -24,7 +24,7 @@ // finalize(). finalize() stably sorts by key and (for the additive variant) // merges duplicate keys, so lookups are valid only after finalize(). // -// World-thread-only writes (the builder); read-only on AI workers after the +// World-thread-only writes (the builder); read-only on bot workers after the // snapshot is published — the same access discipline the unordered_maps had. #pragma once diff --git a/src/modules/PlayerbotV2/Bot/Gear/BotGearGenerator.cpp b/src/modules/PlayerbotV2/Bot/Gear/BotGearGenerator.cpp index c041b6b2d8..f189eaec68 100644 --- a/src/modules/PlayerbotV2/Bot/Gear/BotGearGenerator.cpp +++ b/src/modules/PlayerbotV2/Bot/Gear/BotGearGenerator.cpp @@ -30,7 +30,7 @@ namespace { // The highest effective item level raid gear may reach: Playerbot.Gear.RaidIlvlCap when set (> 0), else the cap of -// Playerbot.Gear.MaxTier (default 1 = Molten Core / Onyxia). Approximate Classic item level ceilings per raid tier +// Playerbot.Gear.MaxTier (default 2 = Blackwing Lair). Approximate Classic item level ceilings per raid tier // (not derived from the item store, which was not reachable): pre-raid dungeon gear ~58-63, MC / Onyxia up to ~76, // Blackwing Lair non-set drops up to ~83, AQ40 81-88, Naxxramas 86-92. Monotone in the tier. Generation and // RaidEquipUpgrade both compare it with EffectiveItemLevelForLevel(item, wearer level). @@ -50,7 +50,7 @@ int32 RaidIlvlCap() int32 const explicit_cap = sConfigMgr->GetIntDefault("Playerbot.Gear.RaidIlvlCap", 0, true); if (explicit_cap > 0) return explicit_cap; - return CapForTier(sConfigMgr->GetFloatDefault("Playerbot.Gear.MaxTier", 1.0f, true)); + return CapForTier(sConfigMgr->GetFloatDefault("Playerbot.Gear.MaxTier", 2.0f, true)); }(); return cap; } diff --git a/src/modules/PlayerbotV2/Bot/Gear/BotGearGenerator.h b/src/modules/PlayerbotV2/Bot/Gear/BotGearGenerator.h index 94691c34a2..3bcf1e775f 100644 --- a/src/modules/PlayerbotV2/Bot/Gear/BotGearGenerator.h +++ b/src/modules/PlayerbotV2/Bot/Gear/BotGearGenerator.h @@ -122,7 +122,7 @@ std::string PlanEquipOrder(::Playerbot::BotSnapshot const& snap, std::string con // RaidRegearPass makes: the bagged item must be wearable PvE gear (no PvP item, effective item level <= kRaidIlvlCap) and // score kRaidUpgradeRatio above the worn piece in `slot` (ScoreItemRaid), a two-hander against main hand + off hand // together, and an off hand never next to a worn two-hander. cur_* are the worn entries (0 = empty). Touches no Player: -// item templates and DB2 only, so it can run on the snapshot build / AI worker threads. +// item templates and DB2 only, so it can run on the snapshot build / bot worker threads. bool RaidEquipUpgrade(uint8 cls, uint16 spec, uint8 level, uint8 slot, uint32 bag_entry, uint32 cur_entry, uint32 cur_mainhand_entry, uint32 cur_offhand_entry, bool world_bot = false, uint64 bot_id = 0); diff --git a/src/modules/PlayerbotV2/Bot/GroupOrderText.cpp b/src/modules/PlayerbotV2/Bot/GroupOrderText.cpp index 9cc103bf5c..38bae8322a 100644 --- a/src/modules/PlayerbotV2/Bot/GroupOrderText.cpp +++ b/src/modules/PlayerbotV2/Bot/GroupOrderText.cpp @@ -53,6 +53,10 @@ std::optional ClassifyGroupOrder(std::string_view msg, bool owner_w return std::nullopt; if (order == "assist") order = "attack"; + // "pull rti" is a Pull on the marked mob: one tank pulls the skull (else cross) when nothing is selected. Read as its own words it + // reached every bot, and every tank-role bot pulled the owner's selection. + if (order.rfind("pull rti", 0) == 0) + order = "pull"; if (order == "pullback" || order == "pull and back") order = "pull back"; return order; diff --git a/src/modules/PlayerbotV2/Bot/IdleRule.cpp b/src/modules/PlayerbotV2/Bot/IdleRule.cpp index 7cb912bcbb..b6691cb378 100644 --- a/src/modules/PlayerbotV2/Bot/IdleRule.cpp +++ b/src/modules/PlayerbotV2/Bot/IdleRule.cpp @@ -16,12 +16,12 @@ void IdleRuleRegistry::register_rule(IdleRule r) { // finalize() runs after every register_rule from RegisterAllIdleRules. // Hitting this branch means someone is registering a rule AFTER init, - // which would race with AI workers calling tick(). Refuse instead. + // which would race with bot workers calling tick(). Refuse instead. if (finalized_) { TC_LOG_ERROR("playerbot.v2", "[IdleRuleRegistry] register_rule('{}', prio={}) called after " - "finalize() — refusing to mutate vector while AI workers tick. " + "finalize() — refusing to mutate vector while bot workers tick. " "All rule registration must complete in RegisterAllIdleRules.", r.name, r.priority); return; @@ -62,6 +62,12 @@ void IdleRuleRegistry::finalize() rule.world_errand = IsWorldErrand(rule.name); std::stable_sort(rules_.begin(), rules_.end(), [](IdleRule const& a, IdleRule const& b) { return a.priority > b.priority; }); + throttled_ = 0; + for (IdleRule& rule : rules_) + rule.throttle_slot = rule.min_interval_ms != 0 ? int(throttled_++) : -1; + fired_ = std::make_unique[]>(rules_.size()); + for (size_t i = 0; i < rules_.size(); ++i) + fired_[i].store(0, std::memory_order_relaxed); finalized_ = true; } @@ -85,33 +91,61 @@ std::string_view IdleRuleRegistry::tick(BotSnapshotView const& s, BotAI& ai, }); finalize(); } - for (auto const& r : rules_) + for (size_t ri = 0; ri < rules_.size(); ++ri) { + auto const& r = rules_[ri]; if (r.priority < min_priority) break; // rules_ sorted desc — bail early if (!r.enabled) continue; if (!r.gate) continue; if (r.world_errand && s.is_companion_with_owner()) continue; - // Per-rule gate-throttle. Rules with min_interval_ms > 0 skip - // the gate entirely until the throttle window elapses. Saves - // the gate-call cost for low-urgency rules (mail, calendar, - // auction, charter) that don't need 5Hz responsiveness. - if (r.min_interval_ms != 0) + // 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. + if (r.throttle_slot >= 0) { - if (r.last_gate_attempt_ms != 0 - && (now_ms - r.last_gate_attempt_ms) < r.min_interval_ms) + uint32& next = ai.gate_next_ms(size_t(r.throttle_slot), throttled_); + if (next == 0) + { + uint32 const h = (uint32(s.bot_id()) + 1u) * 2654435761u ^ (uint32(r.throttle_slot) + 1u) * 2246822519u; + next = (now_ms + (h >> 7) % r.min_interval_ms) | 1u; + } + if (int32(now_ms - next) < 0) continue; - r.last_gate_attempt_ms = now_ms; + next = (now_ms + r.min_interval_ms) | 1u; } if (!r.gate(s, ai, g, now_ms)) continue; if (r.fire && r.fire(s, ai, g, emit, now_ms)) { r.last_fired_ms = now_ms; + if (fired_) fired_[ri].fetch_add(1, std::memory_order_relaxed); return r.name; } } return {}; } +std::vector> IdleRuleRegistry::FireCensus(size_t top, std::vector const& always) const +{ + std::vector> all; + if (!fired_) return all; + for (size_t i = 0; i < rules_.size(); ++i) + all.emplace_back(std::string_view(rules_[i].name), fired_[i].load(std::memory_order_relaxed)); + std::stable_sort(all.begin(), all.end(), [](auto const& a, auto const& b) { return a.second > b.second; }); + std::vector> out; + for (auto const& row : all) + if (out.size() < top && row.second > 0) out.push_back(row); + // Every throttled rule too: the ones the old fleet-wide clock starved are the ones to watch. + for (size_t i = 0; i < rules_.size(); ++i) + if (rules_[i].min_interval_ms != 0 + && std::none_of(out.begin(), out.end(), [&](auto const& o) { return o.first == rules_[i].name; })) + out.push_back({ std::string_view(rules_[i].name), fired_[i].load(std::memory_order_relaxed) }); + for (std::string_view want : always) + for (auto const& row : all) + if (row.first == want && std::none_of(out.begin(), out.end(), [&](auto const& o) { return o.first == want; })) + out.push_back(row); + return out; +} + std::vector IdleRuleRegistry::diagnose(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const& g, uint32 now_ms) const @@ -171,8 +205,8 @@ void RegisterAllIdleRules(IdleRuleRegistry& r) // RegisterBgRules(r); ... // CRITICAL: finalize sorts rules_ + locks against further register_rule. - // Must run BEFORE any AI worker calls tick(). Services::Init calls - // RegisterAllIdleRules immediately before starting the AI worker pool + // Must run BEFORE any bot worker calls tick(). Services::Init calls + // RegisterAllIdleRules immediately before starting the bot worker pool // (see Services.cpp), so finalize() runs single-threaded here. r.finalize(); } diff --git a/src/modules/PlayerbotV2/Bot/IdleRule.h b/src/modules/PlayerbotV2/Bot/IdleRule.h index 8b9c629e46..31c8ffba64 100644 --- a/src/modules/PlayerbotV2/Bot/IdleRule.h +++ b/src/modules/PlayerbotV2/Bot/IdleRule.h @@ -8,9 +8,12 @@ #pragma once #include "BotTypes.h" +#include #include +#include #include #include +#include #include namespace Playerbot { @@ -63,11 +66,9 @@ struct IdleRule // low-urgency rules opt in; everything else keeps its responsiveness. uint32 min_interval_ms = 0; - // Throttle bookkeeping (used iff min_interval_ms != 0). Updated by - // tick() when we decide to evaluate; read on subsequent ticks to - // compute "has the throttle window elapsed?". Mutable because tick() - // takes the rule by const-ref via the rules_ vector. - mutable uint32 last_gate_attempt_ms = 0; + // Which entry of the bot's own throttle table this rule uses (-1 = no throttle). Set by finalize(). The clock is per bot: BotAI keeps + // the next time each throttled rule may be looked at for that bot. + int throttle_slot = -1; // World-bot errand (questing, vendors, mail, auction, gathering, guild, travel, queueing): skipped while the bot // is a companion in its owner's group, which would otherwise wander off on it whenever the owner stands still. @@ -112,10 +113,16 @@ public: uint32 now_ms) const; size_t size() const { return rules_.size(); } + // How many rules carry a throttle: the size of each bot's throttle table. + size_t throttled_count() const { return throttled_; } + + // How often each rule has fired since the server started, busiest first (at most `top` rows), plus every rule named in `always` even + // when it has never fired. Read by the world spawner for its [rules] log line. + std::vector> FireCensus(size_t top, std::vector const& always) const; // Sort rules by priority desc + mark the registry immutable. MUST be // called from RegisterAllIdleRules at module init, AFTER every - // register_rule call, BEFORE any AI worker starts ticking. Once + // register_rule call, BEFORE any bot worker starts ticking. Once // finalized, tick() runs lock-free across all worker threads. // // Why this is needed: a previous lazy-sort design did @@ -129,10 +136,13 @@ public: private: std::vector rules_; + // One relaxed counter per rule (same order as rules_), allocated by finalize(); a fire is rare next to a gate check, so counting it is cheap. + std::unique_ptr[]> fired_; // True once finalize() has run. tick() asserts this in debug builds; // in release we log a warning once and call finalize() defensively // (still a hazard, but better than heap corruption). bool finalized_ = false; + size_t throttled_ = 0; }; // Per-subsystem registrars. Each lives in Bot/States/Rules/Rules.cpp diff --git a/src/modules/PlayerbotV2/Bot/InstanceSchools.h b/src/modules/PlayerbotV2/Bot/InstanceSchools.h index 6e12705bd6..728771021e 100644 --- a/src/modules/PlayerbotV2/Bot/InstanceSchools.h +++ b/src/modules/PlayerbotV2/Bot/InstanceSchools.h @@ -1,7 +1,7 @@ // InstanceSchools - which schools of spell damage a raid instance's bosses deal. // // Resistance buffs (Shadow Protection, the paladin resistance auras, the shaman totems) are kept up only for a school the instance -// deals. MC 2026-10-11 (Karrz: priests standing with hands glowing): five priests spent a refresh round of 40 Shadow Protection casts +// deals. MC 2026-10-11 (the owner: priests standing with hands glowing): five priests spent a refresh round of 40 Shadow Protection casts // in Molten Core, where the raid takes fire. Data, not per-spell rules: a new instance or school is one row. Pure: tested in // tests/game/ClassicInstanceSchools.cpp. diff --git a/src/modules/PlayerbotV2/Bot/MarkGate.h b/src/modules/PlayerbotV2/Bot/MarkGate.h index 12bdfef0e1..b5d2687d99 100644 --- a/src/modules/PlayerbotV2/Bot/MarkGate.h +++ b/src/modules/PlayerbotV2/Bot/MarkGate.h @@ -58,7 +58,17 @@ inline bool MayEngage(BotSnapshotView const& s, BotAI const& ai, GroupSnapshotVi if (u.guid == mob) { unit = &u; break; } } if (unit && (unit->unit_in_combat || !unit->victim.IsEmpty())) return true; - if (Released(s, ai, mob)) return true; + // A bot already fighting opens an idle marked mob (the next pack's skull or moon the owner marks mid-fight) only on its own order + // for that mob, never on the group latch: the latch (any Attack, a mob on a non-tank, the DPS wait timeout) runs for the whole fight, + // so a mark put on the next pack pulled it into this one. + if (s.in_combat()) + { + if (!mob.IsEmpty() && (ai.focus_target() == mob || + (ai.is_manual_mode(s.published_at_ms()) && ai.owner_command() == BotAI::OwnerCommand::Engage && ai.owner_target() == mob))) + return true; + } + else if (Released(s, ai, mob)) + return true; static std::mutex mx; static std::unordered_map last_ms; diff --git a/src/modules/PlayerbotV2/Bot/PositioningGates.h b/src/modules/PlayerbotV2/Bot/PositioningGates.h index 8eb82d3c72..5f72840c42 100644 --- a/src/modules/PlayerbotV2/Bot/PositioningGates.h +++ b/src/modules/PlayerbotV2/Bot/PositioningGates.h @@ -1,12 +1,10 @@ #pragma once -// Pure positioning decisions for melee-behind stepping, flee-angle memory and dungeon disperse / kite steps. +// Pure positioning decision for the melee-behind step. // -// Ideas from the generic layers of two other bot projects, rewritten against our snapshot (no code copied): -// * Karrz's VMaNGOS bots (the ike3-based playerbot code, playerbot/values/StanceReposition.cpp, Stances.cpp): the melee "behind" step -// fires only for a mob a tank holds, inside a 135 degree front arc, never on the mob's own victim, never on Onyxia. -// * AzerothCore mod-playerbots (MovementActions.cpp CheckLastFlee / CombatFormationMoveAction): a flee step that reverses a -// recent flee is rejected, and ranged / melee keep 5 / 2 yards from the nearest member. -// State_Idle.cpp calls these; keeping them here keeps that file's diff small. +// Idea from Karrz's VMaNGOS bots (Karrz1/wow-1.12, playerbot/values/StanceReposition.cpp, Stances.cpp), rewritten against our +// snapshot (no code copied): the melee "behind" step fires only for a mob a tank holds, inside a 135 degree front arc, never on +// the mob's own victim, never on Onyxia. +// State_Idle.cpp calls it; keeping it here keeps that file's diff small. #include "Bot/BotSnapshot.h" #include @@ -34,47 +32,4 @@ inline bool MeleeBehindWanted(NearbyUnit const& mob, ObjectGuid me, float bot_x, return dot > std::cos(kBehindFrontHalfAngle); } -// Recent flee bearings per bot, newest last. A step whose bearing reverses a recent one (within 45 degrees of the opposite) -// is the oscillation between two overlapping step-out rules. -class FleeMemory -{ -public: - static constexpr uint32 kWindowMs = 5000; - static constexpr size_t kMax = 10; - - static void Note(uint64 bot, float angle, uint32 now_ms) - { - std::lock_guard lk(Mu()); - auto& q = Map()[bot]; - q.push_back({ angle, now_ms }); - while (q.size() > kMax) q.pop_front(); - } - - static bool Reverses(uint64 bot, float angle, uint32 now_ms) - { - std::lock_guard lk(Mu()); - auto it = Map().find(bot); - if (it == Map().end()) return false; - for (auto const& e : it->second) - { - if (now_ms - e.second > kWindowMs) continue; - float d = std::fabs(std::remainder(angle - (e.first + 3.14159265f), 6.28318531f)); - if (d < 0.785398f) return true; - } - return false; - } - -private: - using Q = std::deque>; - static std::mutex& Mu() { static std::mutex m; return m; } - static std::unordered_map& Map() { static std::unordered_map m; return m; } -}; - -// Distance to keep from the nearest group member in a dungeon fight (AzerothCore disperse: ranged 5, melee 2), scaled by the -// owner's formation spacing. -constexpr float kRangedDisperse = 5.0f; -constexpr float kMeleeDisperse = 2.0f; -// A mob already fighting the group closer than this to a ranged bot or healer (AzerothCore "enemy too close"). -constexpr float kRangedTooCloseToMob = 5.0f; - } // namespace Playerbot::Positioning diff --git a/src/modules/PlayerbotV2/Bot/QuestDoable.h b/src/modules/PlayerbotV2/Bot/QuestDoable.h index 8294fb7811..9b805c7137 100644 --- a/src/modules/PlayerbotV2/Bot/QuestDoable.h +++ b/src/modules/PlayerbotV2/Bot/QuestDoable.h @@ -11,7 +11,7 @@ // THREADING: both helpers call LIVE Player APIs (CanTakeQuest, GetSkillValue, // GetQuestRewardStatus). They MUST only be invoked where the live Player is // owned by the calling thread — i.e. the snapshot BUILD path (world thread) and -// the idle dispatch (world thread). They MUST NOT be called from the AI worker +// the idle dispatch (world thread). They MUST NOT be called from the bot worker // hot path, and in particular MUST NOT run while QuestHubDatabase's _mutex is // held (SelectLevelingHub takes this predicate as a callback and runs it only // after dropping the lock — see QuestHubDatabase::SelectLevelingHub). diff --git a/src/modules/PlayerbotV2/Bot/Raid/BossWarningData_MC.h b/src/modules/PlayerbotV2/Bot/Raid/BossWarningData_MC.h index d52a91f443..8797cc1ee0 100644 --- a/src/modules/PlayerbotV2/Bot/Raid/BossWarningData_MC.h +++ b/src/modules/PlayerbotV2/Bot/Raid/BossWarningData_MC.h @@ -25,7 +25,7 @@ inline std::vector const& MoltenCoreBossWarnings() { 12264, 19712, "Arcane Explosion - casters move out!", true, 0, 0, 0, 0 }, // Shazzrah { 12264, 23138, "Gate of Shazzrah - he blinks into the raid", false, 25000, 25000, 4000, 0 }, { 12056, 19695, "Inferno - run out of range!", false, 18000, 18000, 4000, 0 }, // Baron Geddon - { 12056, 20475, "Living Bomb - spread out", false, 15000, 12000, 3000, 20475 }, + { 12056, 20475, "Living Bomb - spread out", false, 15000, 12000, 3000, 20475, "has the Living Bomb - move away from the raid!" }, { 12056, 19659, "Ignite Mana - dump your mana", false, 10000, 20000, 3000, 19659 }, { 11988, 20228, "Pyroblast - interrupt or heal through", true, 0, 0, 0, 0 }, // Golemagg { 11988, 19798, "Earthquake - get out of the melee", true, 0, 0, 0, 0 }, diff --git a/src/modules/PlayerbotV2/Bot/Raid/BossWarnings.cpp b/src/modules/PlayerbotV2/Bot/Raid/BossWarnings.cpp index 097c2371c0..ae9fd60a79 100644 --- a/src/modules/PlayerbotV2/Bot/Raid/BossWarnings.cpp +++ b/src/modules/PlayerbotV2/Bot/Raid/BossWarnings.cpp @@ -17,6 +17,7 @@ #include #include +#include #include #include @@ -47,6 +48,7 @@ struct Fight explicit Fight(uint32_t entry) : tracker(&BossWarningsFor(entry)) {} BossWarnTracker tracker; uint32_t lastSeen = 0; + std::set> carriers; // (rule, member) already named while the aura is on them }; std::unordered_map g_fights; @@ -145,9 +147,8 @@ void UpdateBossWarnings(uint32_t nowMs) } } - for (BossWarnEvent const& e : f.tracker.Tick(nowMs, castingSpell, castLeft, auraPresent)) + auto announce = [&](std::string const& text) { - std::string const text = FormatBossWarning(boss->GetName(), rules[e.rule], e); for (GroupReference const& ref : group->GetMembers()) { Player* m = ref.GetSource(); @@ -157,7 +158,30 @@ void UpdateBossWarnings(uint32_t nowMs) packet.Initialize(CHAT_MSG_RAID_BOSS_EMOTE, LANG_UNIVERSAL, boss, m, text); m->SendDirectMessage(packet.Write()); } + }; + + // A member who has just gained a carrier aura (Living Bomb) is named to the humans the moment it lands, so they know who to + // keep away from; the timed warning above only says one is coming. + std::set> carrying; + for (size_t i = 0; i < rules.size(); ++i) + { + if (!rules[i].carrierLabel || !rules[i].resyncAura) + continue; + for (GroupReference const& ref : group->GetMembers()) + { + Player* m = ref.GetSource(); + if (!m || !m->IsInWorld() || !m->IsAlive() || m->GetMap() != boss->GetMap() || !m->HasAura(rules[i].resyncAura)) + continue; + auto const key = std::make_pair(i, m->GetGUID()); + carrying.insert(key); + if (!f.carriers.count(key)) + announce(m->GetName() + " " + rules[i].carrierLabel); + } } + f.carriers = std::move(carrying); + + for (BossWarnEvent const& e : f.tracker.Tick(nowMs, castingSpell, castLeft, auraPresent)) + announce(FormatBossWarning(boss->GetName(), rules[e.rule], e)); } } diff --git a/src/modules/PlayerbotV2/Bot/Raid/BossWarnings.h b/src/modules/PlayerbotV2/Bot/Raid/BossWarnings.h index f7257a7529..749616cd19 100644 --- a/src/modules/PlayerbotV2/Bot/Raid/BossWarnings.h +++ b/src/modules/PlayerbotV2/Bot/Raid/BossWarnings.h @@ -34,6 +34,7 @@ struct BossWarning uint32_t repeatMs; // earliest re-use after the previous one (0 = does not repeat / not predictable) uint32_t leadMs; // warn this long before the earliest time uint32_t resyncAura; // aura that appears when the spell has just landed (0 = none) + char const* carrierLabel = nullptr; // when set, a raid member gaining resyncAura is named at once: " " }; struct BossWarnEvent diff --git a/src/modules/PlayerbotV2/Bot/Raid/README.md b/src/modules/PlayerbotV2/Bot/Raid/README.md index 298e876b90..fd896a9677 100644 --- a/src/modules/PlayerbotV2/Bot/Raid/README.md +++ b/src/modules/PlayerbotV2/Bot/Raid/README.md @@ -1,6 +1,6 @@ # Raid layer (branch playerbot-v2-raid) -Port of Karrz's raid10-revamp ike3 raid logic (the ike3-based playerbot code, src/game/PlayerBots) onto PlayerbotV2. +Port of Karrz's raid10-revamp ike3 raid logic (Karrz1/wow-1.12, src/game/PlayerBots) onto PlayerbotV2. - `RaidEncounters.h/.cpp`: rule vocabulary and per-map registry (409 MC, 469 BWL, 249 Onyxia, 531 AQ40, 533 Naxx). - `RaidEncounterData_*.cpp`: data only. MC/BWL/Onyxia ported as-is (ids match Forever's Classic VMaNGOS ports); @@ -56,7 +56,7 @@ Known BWL gaps: Chromaggus' Bronze affliction needs Hourglass Sand; the other cl form, hunter bow, rogue paralyze) have no counter a bot could play. Untested: whether Forever's spell data lets a possessed Razorgore cast Destroy Egg on an egg, and the Blessing of Protection ids the paladin call uses. -Not done: 10-player scaling (Karrz chose 40 only). Untested in game: the Naxx scripted mechanics, in particular +Not done: 10-player scaling (the owner chose 40 only). Untested in game: the Naxx scripted mechanics, in particular whether a possessed creature follows MoveChase for a bot controller and whether the understudy template spells (Taunt 29060, Shield Wall 29061) are castable from Forever's data. @@ -64,7 +64,7 @@ whether a possessed creature follows MoveChase for a bot controller and whether - Branch head f93ecd4f, pushed, builds clean on Linux (-DBUILD_PLAYERBOT_V2=1). It includes trial 513e126b. - Batch 1 (MC/BWL/Onyxia port, threat hold) and batch 2 (Garr no-AoE, Heigan, Sapphiron, Razuvious, Four Horsemen, - Patchwerk) are untested in game. Karrz's first MC trash pull ran on df756243 and wiped: one Molten Giant had no tank, + Patchwerk) are untested in game. the owner's first MC trash pull ran on df756243 and wiped: one Molten Giant had no tank, which the trial thread is fixing in pvecoord (one mob per tank in raids). - The raid layer logs a "[raid] group N: ... main tank " header when it plans a fight, plus one line per changed bot decision. diff --git a/src/modules/PlayerbotV2/Bot/Raid/RaidBrain.cpp b/src/modules/PlayerbotV2/Bot/Raid/RaidBrain.cpp index 6f7ef2435c..33221f8c35 100644 --- a/src/modules/PlayerbotV2/Bot/Raid/RaidBrain.cpp +++ b/src/modules/PlayerbotV2/Bot/Raid/RaidBrain.cpp @@ -13,11 +13,14 @@ #include "RaidGeometry.h" #include "RaidReadiness.h" #include "RaidHealStats.h" +#include "RaidIncoming.h" +#include "RaidManaLedger.h" #include "RaidRoster.h" #include "../../Fleet/BotPopulationManager.h" #include "../../Fleet/OwnerRegistry.h" #include "../BotRegistry.h" #include "../ClassTables.h" +#include "../ThreatLimits.h" #include "../Dungeon/PveGroupCoordinator.h" #include "../../Group/GroupSnapshot.h" #include "../../Fleet/BotIdentityRegistry.h" @@ -38,6 +41,7 @@ #include "Log.h" #include "Map.h" #include "MapManager.h" +#include "MotionMaster.h" #include "ObjectAccessor.h" #include "ObjectMgr.h" #include "PathGenerator.h" @@ -201,6 +205,7 @@ bool Matches(Who who, Member const& m, Player* mainTank) case Who::ManaUser: return m.mana; case Who::Caster: return !m.tank && !m.healer && m.ranged && m.p->GetClass() != CLASS_HUNTER; case Who::Physical: return !m.tank && !m.healer && (!m.ranged || m.p->GetClass() == CLASS_HUNTER); + case Who::AoeShare: return !m.tank && !m.healer && m.ranged && m.p->GetClass() != CLASS_HUNTER && (m.p->GetGUID().GetCounter() & 1) == 0; } return false; } @@ -238,14 +243,18 @@ bool Controlled(Unit* u) // --------------------------------------------------------------------------- // Path queries in one plan pass, all bots together. A full 40-man pass with every bot spreading used to run ~1000 of them -// on the world thread; urgent probes (leaving a hazard, a carrier run, scripted mechanics, a cone) may use the whole cap, -// routine ones (spread, role spots, stay near) stop at kPathProbeRoutine so an escape later in the pass still finds room. -// The budget only bounds the cost: a bot whose probe was refused keeps its sticky point or retries next pass (300 ms). -constexpr int kPathProbeCap = 160; +// on the world thread. Routine probes (spread, role spots, stay near) stop at kPathProbeRoutine; urgent ones (leaving a hazard, a carrier +// run, scripted mechanics, a cone) have a budget of their own. They used to share one cap of 160 with the routine ones: the bots early in +// the pass spent 100 on spreading and left 60 for the escapes, about three probes for each of the 18 raiders inside Geddon's Inferno +// circle, so the ones late in the pass found no way out and stood in it (MC Geddon 2026-10-13 d202b196: six melee dead at 16-20 y, and +// the ranged starting out 0.6 s apart one pass at a time). The budget only bounds the cost: a bot whose probe was refused keeps its sticky +// point or retries next pass (300 ms). +constexpr int kUrgentProbeCap = 420; constexpr int kPathProbeRoutine = 100; int g_pathProbes = 0; +int g_urgentProbes = 0; -void ResetPathProbes() { g_pathProbes = 0; } +void ResetPathProbes() { g_pathProbes = 0; g_urgentProbes = 0; } // Hostile creatures near the plan's raid that are not fighting yet, with their aggro reach against the raid (refreshed per // plan, see SetIdleHostiles). A raid move never ends inside that reach: a bot leaving Smash or spreading used to run into @@ -271,6 +280,61 @@ void SetIdleHostiles(Plan const& plan, Player* ref) } } +// RaidRules::keepOut circles of the bosses in the fight (refreshed per plan): no raid move ends inside one. The candidate searches skip them +// (Escape, Clearest, Usable), so a bot leaving a breath corridor takes the next way out instead of the nearest one, which for Onyxia's +// north-south breath is the cave mouth and its whelps; ApplyKeepOut is the clamp for the moves that name a point (role spots, flanks). +std::vector g_keepOut; + +void SetKeepOut(Plan const& plan) +{ + g_keepOut.clear(); + for (KeepOut const& zone : plan.rules->keepOut) + for (Unit* enemy : plan.enemies) + if (enemy->GetEntry() == zone.enemy && enemy->IsAlive() && enemy->IsInCombat() && g_keepOut.size() < 16) + { + g_keepOut.push_back({ zone.x, zone.y, zone.radius }); + break; + } +} + +// Enemies already in the fight, with the reach of their melee. A ranged bot's free raid move (leave hazard, spread, stay near) +// never ends inside it and never runs through it: leaving Garr's Massive Eruption circle sent a mage across the Firesworn pack +// to the far side of the ring (mc_garr 2026-10-12: five casters and priests dead to Firesworn melee, last rule raid:move). +// A mob the bot already stands inside is skipped; nothing can be done about that one from here. +std::vector g_engagedReach; +constexpr float kEngagedMeleeMargin = 6.0f; // melee range 5 + a step + +void SetEngagedReach(Plan const& plan) +{ + g_engagedReach.clear(); + for (Unit* enemy : plan.enemies) + if (enemy && enemy->IsAlive() && !enemy->IsPlayer() && g_engagedReach.size() < 64) + g_engagedReach.push_back({ enemy->GetPositionX(), enemy->GetPositionY(), enemy->GetCombatReach() + kEngagedMeleeMargin }); +} + +float SegmentDist2D(float ax, float ay, float bx, float by, float px, float py) +{ + float const dx = bx - ax, dy = by - ay; + float const len2 = dx * dx + dy * dy; + float const t = len2 > 0.0f ? std::clamp(((px - ax) * dx + (py - ay) * dy) / len2, 0.0f, 1.0f) : 0.0f; + return Dist2D(px, py, ax + t * dx, ay + t * dy); +} + +// True when the walk from the bot to (x, y) ends in or passes through the melee reach of an engaged enemy the bot is not +// already inside. +bool CrossesEngagedReach(Player* bot, float x, float y) +{ + float const bx = bot->GetPositionX(), by = bot->GetPositionY(); + for (Circle const& c : g_engagedReach) + { + if (Dist2D(bx, by, c.x, c.y) < c.r) + continue; + if (SegmentDist2D(bx, by, x, y, c.x, c.y) < c.r) + return true; + } + return false; +} + // The fight a bot's free raid moves (leave hazard, cone, spread, stay near) must stay part of, set by DecideMove after the // scripted mechanics had their turn (Heigan's dance, the stomach and Gothik's sides pick their own far points). Without it a // bot leaving Smash or spreading took any walkable point: ledges and rocks off the side of the fight, with no sight of its @@ -283,6 +347,7 @@ struct FightArea float targetRange = 0.0f; // ranged: stay within cast range of `target`; 0 for melee }; FightArea g_fight; +bool g_carrierRun = false; // set while a bomb carrier's escape point is searched (RaidBrain DecideMove) constexpr float kFightRadius = 35.0f; // from the main tank constexpr float kRangedReach = 30.0f; // casting / shooting range @@ -321,11 +386,16 @@ bool InFightArea(Player* bot, float x, float y, float z, bool urgent) { if (!g_fight.active) return true; - if (g_fight.anchor && !WithinOrCloser(bot, g_fight.anchor, x, y, kFightRadius)) + // A carrier leaving the raid may go past the usual fight radius and out of casting range of its target: any way out comes first + // (Living Bomb, MC 2026-10-12: "fight area" refused 12 of the probed points; a carrier on the far end of the 50 y ranged arc was 47 y + // from the tank: b0a1c616, 9 more). The bomb lasts 8 s, so what a carrier can run is within 60 y of where it stands. + if (g_fight.anchor && !WithinOrCloser(bot, g_fight.anchor, x, y, g_carrierRun ? kFightRadius + 60.0f : kFightRadius)) return false; Unit* target = g_fight.target; if (!target || target == bot) return true; + if (g_carrierRun) + return true; if (g_fight.targetRange > 0.0f && !WithinOrCloser(bot, target, x, y, g_fight.targetRange + target->GetCombatReach())) return false; // A spot with no sight of the target is a spot the bot cannot fight from. Leaving a hazard goes first: any way out of it. @@ -338,38 +408,111 @@ bool InFightArea(Player* bot, float x, float y, float z, bool urgent) // A point the bot can actually stand on and walk to, outside every idle pack's aggro reach, and (inside DecideMove) part of // the fight: near the main tank, in reach and sight of the bot's target, reached by a path without a detour. -bool Usable(Player* bot, float x, float y, float zHint, float& outZ, bool urgent) +// Why the last Usable() refused a point (Clearest tallies them for its "no reachable clear spot" log). +int g_usableWhy = 0; +constexpr char const* kUsableWhyName[] = { "ok", "idle pack", "engaged reach", "path probe cap", "no ground", "no LoS", "fight area", "no path", "detour" }; + +bool MagmaAt(Map* map, PhaseShift const& phase, float x, float y, float z, float& surfaceZ); + +// `hazard`: the point is a way out of something that is killing the bot (Inferno's circle, a cone). It keeps the fight where it is only +// as far as the ground allows: a point in lava, with no ground, with no sight of the bot or no path is refused, and the fight-area and +// engaged-reach limits are not applied (MC Geddon 2026-10-13 650994ea: seven raiders inside Inferno's circle "found no way out" with the +// fight area and the engaged reach refusing 7-14 of their probes, and then stood in it). +bool Usable(Player* bot, float x, float y, float zHint, float& outZ, bool urgent, bool hazard) { + g_usableWhy = 0; + if (!hazard && InsideAny(g_keepOut, x, y, 0.0f)) // a way out of a hazard may use the cave rim: a whelp pack can be survived, a breath cannot + return g_usableWhy = 1, false; + // Nor walk across one on the way (a flank re-post from one side of a cave mouth to the other). Open floor: the straight line stands + // in for the path. A bot already inside is leaving and may cross its own circle. + if (!hazard) + for (Circle const& k : g_keepOut) + if (Dist2D(bot->GetPositionX(), bot->GetPositionY(), k.x, k.y) >= k.r && + SegmentDist2D(bot->GetPositionX(), bot->GetPositionY(), x, y, k.x, k.y) < k.r) + return g_usableWhy = 1, false; if (InsideAny(g_idleHostiles, x, y, 0.0f) && !InsideAny(g_idleHostiles, bot->GetPositionX(), bot->GetPositionY(), 0.0f)) - return false; - if (g_pathProbes >= (urgent ? kPathProbeCap : kPathProbeRoutine)) - return false; + return g_usableWhy = 1, false; + if (!hazard && g_fight.active && g_fight.targetRange > 0.0f && CrossesEngagedReach(bot, x, y)) // a ranged, non-tank bot + return g_usableWhy = 2, false; + if (urgent ? g_urgentProbes >= kUrgentProbeCap : g_pathProbes >= kPathProbeRoutine) + return g_usableWhy = 3, false; Map* map = bot->GetMap(); float const height = map->GetHeight(bot->GetPhaseShift(), x, y, zHint + 2.0f, true, 12.0f); if (height <= INVALID_HEIGHT + 1.0f || std::fabs(height - zHint) > 12.0f) - return false; + return g_usableWhy = 4, false; + // Lava is refused for every point, not only for ways out: the role spots, spread, taunt walk and cleaner reach used to be + // able to pick one, and LeaveMagma then walked the bot out on the next plan, where the routine pick sent it back in. + { + float surface = 0.0f; + if (MagmaAt(map, bot->GetPhaseShift(), x, y, height + 0.05f, surface)) + return g_usableWhy = 4, false; + } if (!bot->IsWithinLOS(x, y, height + bot->GetCollisionHeight())) - return false; - if (!InFightArea(bot, x, y, height, urgent)) - return false; - ++g_pathProbes; + return g_usableWhy = 5, false; + if (!hazard && !InFightArea(bot, x, y, height, urgent)) + return g_usableWhy = 6, false; + ++(urgent ? g_urgentProbes : g_pathProbes); PathGenerator path(bot); if (!BotMovement::SehSafeCalculatePath(path, x, y, height)) - return false; + return g_usableWhy = 7, false; if (path.GetPathType() & (PATHFIND_NOPATH | PATHFIND_INCOMPLETE)) - return false; + return g_usableWhy = 7, false; if (g_fight.active && path.GetPath().size() >= 2) { // A walkable point reached by climbing round a rock is up on the rock: the path must be close to the straight line. float const dx = x - bot->GetPositionX(), dy = y - bot->GetPositionY(), dz = height - bot->GetPositionZ(); float const straight = std::sqrt(dx * dx + dy * dy + dz * dz); if (path.GetPathLength() > straight * kDetourFactor + kDetourSlack) - return false; + return g_usableWhy = 8, false; } outZ = height; return true; } +// The one clamp on every raid move (RaidRules::keepOut): a finished target inside a keep-out circle of a boss that is in the fight moves to the +// circle's rim, along the line from its centre. The ground there is looked up again; with none the move is dropped, never kept. +void ApplyKeepOut(Plan const& plan, Member const& self, std::vector const& circles, RaidOrder& out) +{ + if (!out.move || plan.rules->keepOut.empty()) + return; + // A way out of a hazard is not clamped: the cave rim is survivable, the breath is not. + if (out.move_reason && (std::strcmp(out.move_reason, "leave hazard") == 0 || std::strcmp(out.move_reason, "leave cone") == 0)) + return; + for (KeepOut const& zone : plan.rules->keepOut) + { + bool fighting = false; + for (Unit* enemy : plan.enemies) + if (enemy->GetEntry() == zone.enemy && enemy->IsAlive() && enemy->IsInCombat()) { fighting = true; break; } + if (!fighting) + continue; + float const d = Dist2D(out.move_x, out.move_y, zone.x, zone.y); + if (d >= zone.radius) + continue; + float ux = out.move_x - zone.x, uy = out.move_y - zone.y; + if (d < 0.5f) + { + ux = self.p->GetPositionX() - zone.x; uy = self.p->GetPositionY() - zone.y; + float const l = std::sqrt(ux * ux + uy * uy); + ux = l > 0.5f ? ux / l : 1.0f; uy = l > 0.5f ? uy / l : 0.0f; + } + else { ux /= d; uy /= d; } + float const nx = zone.x + ux * (zone.radius + 1.0f), ny = zone.y + uy * (zone.radius + 1.0f); + float const nz = self.p->GetMap()->GetHeight(self.p->GetPhaseShift(), nx, ny, out.move_z + 2.0f, true, 12.0f); + if (nz <= INVALID_HEIGHT + 1.0f || std::fabs(nz - out.move_z) > 12.0f) + { + out.move = false; + return; + } + // The rim of a keep-out circle may lie inside a hazard the bot is leaving: no move then, not a walk back into it. + if (InsideAny(circles, nx, ny, 1.0f)) + { + out.move = false; + return; + } + out.move_x = nx; out.move_y = ny; out.move_z = nz; + } +} + bool SetMove(RaidOrder& out, float x, float y, float z, char const* reason) { out.move = true; @@ -378,7 +521,21 @@ bool SetMove(RaidOrder& out, float x, float y, float z, char const* reason) return true; } -bool Escape(Player* bot, std::vector const& circles, RaidOrder& out) +// `tankOf` (the raid, for a tank): a tank leaving a boss's circle goes out sideways to the raid, not straight back through it. The boss +// follows its tank when the circle ends, and the tank's way out is where the boss ends up: straight back put Geddon 19 y closer to the +// ranged block between two Infernos (MC Geddon 2026-10-12 b0a1c616: 14 bots in range of the second one). +std::string g_escapeWhy; // why the last Escape found no way out, for the "[raid_circle] ... no way out" log + +// Where the boss of the latest aura circle started the fight (its home point), and when that circle opened. A tank leaving the circle +// takes the boss with it, so it leaves toward this point once the boss has been pulled off it: left to the sideways exit alone the boss +// walked ~20 y toward the room's edge every Inferno (MC Geddon 2026-10-13 mc-n5: x 655 -> 565 over one run, then six raiders "found no +// way out" against the lava edges). +struct BossHome { float x = 0.0f, y = 0.0f; uint32_t at = 0; }; +BossHome g_bossHome; +constexpr uint32_t kBossHomeMaxAgeMs = 25000; // the circle, its tail and the walk back +constexpr float kBossHomeSlack = 6.0f; // a boss within this of its home point is left where it is + +bool Escape(Player* bot, std::vector const& circles, RaidOrder& out, std::vector const* tankOf = nullptr) { int deepest = -1; float depth = -1.0f; @@ -391,59 +548,208 @@ bool Escape(Player* bot, std::vector const& circles, RaidOrder& out) return false; Circle const& c = circles[deepest]; - float const base = std::atan2(bot->GetPositionY() - c.y, bot->GetPositionX() - c.x); // straight away from the centre first - int pathChecks = 0; - for (float extra : { 2.0f, 5.0f, 9.0f }) - for (int k = 0; k < 12; ++k) + float base = std::atan2(bot->GetPositionY() - c.y, bot->GetPositionX() - c.x); // straight away from the centre first + if (tankOf && !tankOf->empty()) + { + float rx = 0.0f, ry = 0.0f; + for (Player* p : *tankOf) { - float const offset = k == 0 ? 0.0f : float((k + 1) / 2) * (float(M_PI) / 6.0f) * ((k % 2) ? 1.0f : -1.0f); + rx += p->GetPositionX(); + ry += p->GetPositionY(); + } + float const toRaid = std::atan2(ry / float(tankOf->size()) - c.y, rx / float(tankOf->size()) - c.x); + // Perpendicular to the centre-to-raid line, on the side the tank already stands on. + float const side = std::sin(base - toRaid) >= 0.0f ? 1.0f : -1.0f; + float const away = std::cos(base - toRaid); // 1 = the tank stands between the boss and the raid + if (away > 0.3f) + { + // Sideways, but no more than 35 degrees off the tank's own way out: the exit point is picked on the ring round the boss, and a point 90 + // degrees round it from where the tank stands is a walk through the circle, past the boss (MC Geddon 2026-10-13 mc_geddon run 2: the + // main tank started 19 y from Geddon, was sent to a point 36 y away on the far side, and died at tick four 3.3 y from him; the next + // tank died 21 y out on the same kind of walk). + constexpr float kMaxSideSwing = 0.61f; // 35 degrees + float const sideways = toRaid + side * float(M_PI) * 0.5f; + float delta = sideways - base; + while (delta > float(M_PI)) delta -= 2.0f * float(M_PI); + while (delta < -float(M_PI)) delta += 2.0f * float(M_PI); + base += std::clamp(delta, -kMaxSideSwing, kMaxSideSwing); + } + // Boss pulled off its home point: leave toward it, so the boss follows its tank back instead of further out. Only when that + // walk does not cut through the boss: the straight line from the tank to the ring point on the home bearing must pass the centre + // no closer than 70 % of the tank's own distance to it (the refusal rule of the n5 exit fix); otherwise the clamped base stands. + if (g_bossHome.at && GameTime::GetGameTimeMS() - g_bossHome.at < kBossHomeMaxAgeMs) + { + float const homeDist = Dist2D(c.x, c.y, g_bossHome.x, g_bossHome.y); + if (homeDist > kBossHomeSlack && homeDist < 80.0f) + { + float const homeAngle = std::atan2(g_bossHome.y - c.y, g_bossHome.x - c.x); + float const tx = c.x + (c.r + 2.0f) * std::cos(homeAngle), ty = c.y + (c.r + 2.0f) * std::sin(homeAngle); + float const bx = bot->GetPositionX(), by = bot->GetPositionY(); + float const sx = tx - bx, sy = ty - by; + float const len2 = sx * sx + sy * sy; + float const u = len2 > 0.01f ? std::clamp(((c.x - bx) * sx + (c.y - by) * sy) / len2, 0.0f, 1.0f) : 0.0f; + float const closest = Dist2D(c.x, c.y, bx + sx * u, by + sy * u); + if (closest >= 0.7f * Dist2D(c.x, c.y, bx, by)) + base = homeAngle; + } + } + } + int pathChecks = 0, inOther = 0, why[9] = {}; + auto const tally = [&]() + { + std::ostringstream w; + w << "in another circle " << inOther; + for (int i = 1; i < 9; ++i) + if (why[i]) + w << ", " << kUsableWhyName[i] << " " << why[i]; + g_escapeWhy = w.str(); + }; + // Rings out to 20 y past the deepest circle and every 15 degrees: with the live circle, the origin circle and the predicted one open + // together (Geddon walking), the first rings are mostly inside another circle (6 of 7 probes in MC Geddon 650994ea). + // First without the keep-out circles, then with them allowed: leaving a breath outranks staying out of the caves. + for (int pass = 0; pass < 2; ++pass) + { + pathChecks = 0; + for (float extra : { 2.0f, 5.0f, 9.0f, 14.0f, 20.0f }) + for (int k = 0; k < 24; ++k) + { + float const offset = k == 0 ? 0.0f : float((k + 1) / 2) * (float(M_PI) / 12.0f) * ((k % 2) ? 1.0f : -1.0f); float const px = c.x + (c.r + extra) * std::cos(base + offset); float const py = c.y + (c.r + extra) * std::sin(base + offset); if (InsideAny(circles, px, py, 1.0f)) + { + ++inOther; continue; - if (++pathChecks > 14) - return false; + } + if (pass == 0 && InsideAny(g_keepOut, px, py, 0.0f)) + continue; // out of bounds (RaidRules::keepOut): the next way out, before a path probe is spent + // A way out that runs through the middle of the circle is no way out: the walk passes the boss at under 70 percent of the bot's + // own distance (a point on the far side of the ring is a walk across it, at the heaviest ticks). + { + float const sx = px - bot->GetPositionX(), sy = py - bot->GetPositionY(); + float const len2 = sx * sx + sy * sy; + float const cx = c.x - bot->GetPositionX(), cy = c.y - bot->GetPositionY(); + float const t = len2 > 0.01f ? std::clamp((cx * sx + cy * sy) / len2, 0.0f, 1.0f) : 0.0f; + float const nearest = std::sqrt((cx - t * sx) * (cx - t * sx) + (cy - t * sy) * (cy - t * sy)); + if (nearest < 0.7f * std::sqrt(cx * cx + cy * cy)) + continue; + } + if (++pathChecks > 20) + break; // this pass's probe budget is spent float pz = 0.0f; - if (!Usable(bot, px, py, bot->GetPositionZ(), pz, /*urgent*/ true)) + if (!Usable(bot, px, py, bot->GetPositionZ(), pz, /*urgent*/ true, /*hazard*/ true)) + { + ++why[g_usableWhy]; continue; + } return SetMove(out, px, py, pz, "leave hazard"); } + } + tally(); return false; } // Best nearby point that increases the distance to every raid member in `others`. +std::string g_clearestWhy; + bool Clearest(Player* bot, std::vector const& others, float wanted, RaidOrder& out, char const* reason, std::vector const& avoid, bool urgent) { float nearest = 9999.0f; for (Player* p : others) nearest = std::min(nearest, Dist2D(bot->GetPositionX(), bot->GetPositionY(), p->GetPositionX(), p->GetPositionY())); - float bestScore = -9999.0f; - float bx = 0.0f, by = 0.0f, bz = 0.0f; - int pathChecks = 0; - for (float distance : { wanted, wanted * 1.4f }) - for (int i = 0; i < 16 && pathChecks < 12; ++i) + + // Candidate points on rings round the bot, scored first (cheap) and probed best first (a path query each). A carrier standing inside + // the raid (Living Bomb, MC 2026-10-12: nearest raider 11-14 yd, 25-30 of the ring points "not better") needs the rings that reach past + // the raid's edge, and probing in ring order spent the whole probe budget on the nearest, worst points. + struct Candidate { float x, y, score; }; + std::vector candidates; + float const improvement = urgent ? 2.0f : 4.0f; + std::vector rings = urgent ? std::vector{ wanted * 0.7f, wanted, wanted * 1.4f, wanted * 1.9f } + : std::vector{ wanted, wanted * 1.4f }; + int const steps = urgent ? 24 : 16; + int skippedNear = 0, skippedAvoid = 0, why[9] = {}; + for (float distance : rings) + for (int i = 0; i < steps; ++i) { - float const angle = float(i) * (2.0f * float(M_PI) / 16.0f); + float const angle = float(i) * (2.0f * float(M_PI) / float(steps)); float const px = bot->GetPositionX() + distance * std::cos(angle); float const py = bot->GetPositionY() + distance * std::sin(angle); float clear = 9999.0f; for (Player* p : others) clear = std::min(clear, Dist2D(px, py, p->GetPositionX(), p->GetPositionY())); - if (clear < nearest + 4.0f) + if (clear < nearest + improvement) + { + ++skippedNear; continue; // must be a real improvement - if (!avoid.empty() && InsideAny(avoid, px, py, 1.0f)) + } + if ((!avoid.empty() && InsideAny(avoid, px, py, 1.0f)) || InsideAny(g_keepOut, px, py, 0.0f)) + { + ++skippedAvoid; continue; - ++pathChecks; - float pz = 0.0f; - if (!Usable(bot, px, py, bot->GetPositionZ(), pz, urgent)) + } + // The cheap fight-area test first: a path probe is the scarce thing, and the best-scored points of a carrier run are the farthest + // ones, which the fight area can refuse (MC Geddon 2026-10-13 09a8ff07: "fight area 14" - all 14 probes spent on refused points). + if (g_carrierRun && !InFightArea(bot, px, py, bot->GetPositionZ(), urgent)) + { + ++why[6]; continue; - float const score = std::min(clear, 28.0f) - 0.2f * distance; - if (score > bestScore) { bestScore = score; bx = px; by = py; bz = pz; } + } + candidates.push_back({ px, py, std::min(clear, wanted + 12.0f) - 0.2f * distance }); } - if (bestScore <= -9999.0f) - return false; - return SetMove(out, bx, by, bz, reason); + std::stable_sort(candidates.begin(), candidates.end(), [](Candidate const& a, Candidate const& b) { return a.score > b.score; }); + + int pathChecks = 0, snapChecks = 0, offMesh = 0; + for (Candidate const& c : candidates) + { + if (pathChecks >= (urgent ? 14 : 12)) + break; + float cx = c.x, cy = c.y; + // A carrier's run spot is picked from the walkable navmesh first: ring points over a ledge, a pit or a wall had no ground and spent the + // probe budget (Living Bomb, MC Geddon 2026-10-14 n38: "no reachable clear spot ... no ground 13-14" with raiders 1-19 y away). Each + // point is moved to the nearest walkable poly within 3 y; no poly there, no probe. A moved point must still beat standing here. + if (g_carrierRun) + { + if (++snapChecks > 60) + break; + Position snapped; + if (!BotMovement::NearestNavPoint(bot, c.x, c.y, bot->GetPositionZ(), 3.0f, 6.0f, snapped)) + { + ++offMesh; + continue; + } + cx = snapped.GetPositionX(); + cy = snapped.GetPositionY(); + float clear = 9999.0f; + for (Player* p : others) + clear = std::min(clear, Dist2D(cx, cy, p->GetPositionX(), p->GetPositionY())); + if (clear < nearest + improvement || (!avoid.empty() && InsideAny(avoid, cx, cy, 1.0f))) + { + ++offMesh; + continue; + } + } + ++pathChecks; + float pz = 0.0f; + if (!Usable(bot, cx, cy, bot->GetPositionZ(), pz, urgent)) + { + ++why[g_usableWhy]; + continue; + } + return SetMove(out, cx, cy, pz, reason); + } + + // Why nothing was found, for the carrier-run log: candidates no better than standing here, candidates inside a hazard circle, and + // what refused each point that was probed. + std::ostringstream w; + w << "not better " << skippedNear << ", in hazard " << skippedAvoid; + if (offMesh) + w << ", off navmesh " << offMesh; + for (int i = 1; i < 9; ++i) + if (why[i]) + w << ", " << kUsableWhyName[i] << " " << why[i]; + g_clearestWhy = w.str(); + return false; } // Keeps a decision for a couple of seconds so bots do not jitter between equally good points. @@ -455,6 +761,8 @@ std::unordered_map g_lastTankFace; std::unordered_map g_lastFaceAway; std::unordered_map g_lastRearStep; std::unordered_map g_lastCarrierLog; +std::unordered_map g_lastBombLog; +std::unordered_map g_lastStuckLog; bool UseSticky(Player* bot, std::vector const& circles, uint32_t now, RaidOrder& out) { @@ -473,8 +781,11 @@ void Remember(Player* bot, RaidOrder const& d, uint32_t now) } // Line hazard (AvoidBreath): the corridor is latched when the breath starts so it stays put while the enemy flies along it. -struct BreathLatch { float x = 0, y = 0, o = 0; uint32_t until = 0, lockout = 0; }; +struct BreathLatch { float x = 0, y = 0, o = 0; uint32_t until = 0, lockout = 0, stateLogged = 0; }; std::unordered_map g_breath; +// The breath spell a fixed-path rule saw cast (AvoidBreath::fixedPath) and until when its corridor stays open. +struct BreathSpellLatch { uint32_t spell = 0, until = 0; }; +std::unordered_map g_breathSpell; bool IsCasting(Unit* enemy, uint32_t spell) { @@ -487,29 +798,59 @@ bool IsCasting(Unit* enemy, uint32_t spell) return false; } -bool BreathActive(Unit* enemy, uint32_t spell) +// The breath spell the enemy is casting or carries right now, 0 for none (for the log line). +uint32_t CastingBreath(Unit* enemy, std::vector const& spells) { - if (spell && enemy->HasAura(spell)) - return true; + for (uint32_t spell : spells) + if (spell && enemy->HasAura(spell)) + return spell; + for (CurrentSpellTypes type : { CURRENT_GENERIC_SPELL, CURRENT_CHANNELED_SPELL }) + if (Spell* cast = enemy->GetCurrentSpell(type)) + if (cast->GetSpellInfo() && std::find(spells.begin(), spells.end(), cast->GetSpellInfo()->Id) != spells.end()) + return cast->GetSpellInfo()->Id; + return 0; +} + +bool BreathActive(Unit* enemy, std::vector const& spells, bool windup) +{ + // Any of the enemy's breath spells: it casts the one of the waypoint it stands at, so checking only the first listed one saw one breath in eight. + for (uint32_t spell : spells) + if (spell && enemy->HasAura(spell)) + return true; for (CurrentSpellTypes type : { CURRENT_GENERIC_SPELL, CURRENT_CHANNELED_SPELL }) { Spell* cast = enemy->GetCurrentSpell(type); - if (cast && cast->GetSpellInfo() && cast->GetSpellInfo()->Id == spell) + if (cast && cast->GetSpellInfo() && std::find(spells.begin(), spells.end(), cast->GetSpellInfo()->Id) != spells.end()) return true; } + // The wind-up: airborne, standing still, no target (her script clears the target for the 5 s wait, then restores it on arrival). + if (windup && enemy->IsFlying() && !enemy->isMoving() && enemy->GetTarget().IsEmpty()) + return true; // The breath pass itself: Onyxia flies it at run speed rate 3.0 (classic_boss_onyxia.cpp ONYXIA_BREATH_SPEED). return enemy->isMoving() && enemy->GetSpeedRate(MOVE_RUN) >= 2.5f; } -bool BreathLine(Unit* enemy, uint32_t spell, uint32_t now, float& x, float& y, float& o) +bool BreathLine(Unit* enemy, std::vector const& spells, bool windup, uint32_t now, float& x, float& y, float& o) { - bool const active = BreathActive(enemy, spell); + bool const active = BreathActive(enemy, spells, windup); BreathLatch& latch = g_breath[enemy->GetGUID().GetCounter()]; + // While the breather is airborne, once a second: what the detection sees. A breath that killed the raid unlatched (onyxia_full n14, 36 deaths at + // 195 s, one latch in the run) needs this to say which condition failed. + if (enemy->IsFlying() && now - latch.stateLogged >= 1000) + { + latch.stateLogged = now; + TC_LOG_INFO("playerbot.v2.raid", "[raid_breath_state] {} at {:.1f},{:.1f} facing {:.0f} flying {} moving {} target {} speed {:.1f} casting {} active {} lockout in {} ms latched for {} ms", + enemy->GetName(), enemy->GetPositionX(), enemy->GetPositionY(), enemy->GetOrientation() * 180.0f / float(M_PI), enemy->IsFlying(), enemy->isMoving(), + enemy->GetTarget().IsEmpty() ? "none" : "set", enemy->GetSpeedRate(MOVE_RUN), IsCasting(enemy, spells.empty() ? 0u : spells.front()), active, + latch.lockout > now ? latch.lockout - now : 0u, latch.until > now ? latch.until - now : 0u); + } if (active && now > latch.lockout) { latch.x = enemy->GetPositionX(); latch.y = enemy->GetPositionY(); latch.o = enemy->GetOrientation(); latch.until = now + 10000; // the wait (5 s) plus the flight - latch.lockout = now + 14000; // no re-latch at the end of the same pass + TC_LOG_INFO("playerbot.v2.raid", "[raid_breath] {} breath corridor latched at {:.1f},{:.1f} facing {:.0f} deg (cast {} windup {} moving {} speed {:.1f})", + enemy->GetName(), latch.x, latch.y, latch.o * 180.0f / float(M_PI), CastingBreath(enemy, spells), windup, enemy->isMoving(), enemy->GetSpeedRate(MOVE_RUN)); + latch.lockout = now + 9000; // no re-latch at the end of the same pass (5 s wait + about 4 s flight; onyxia_full n8: a second breath 13 s after the first got no corridor under the old 14 s) } else if (active && now <= latch.until && Dist2D(enemy->GetPositionX(), enemy->GetPositionY(), latch.x, latch.y) < 3.0f) latch.o = enemy->GetOrientation(); // she turns to face the far waypoint just after the cast @@ -519,19 +860,109 @@ bool BreathLine(Unit* enemy, uint32_t spell, uint32_t now, float& x, float& y, f return true; } +// When an AvoidEnemyAura rule's aura or cast was last seen on an enemy, by (enemy guid << 32) ^ aura. World thread only. +std::unordered_map g_auraCircleSeen; +constexpr uint32_t kAuraCircleTailMs = 2500; +// Where the enemy stood when the circle opened, and whether the drift past it has been logged. A boss that walks during the spell (MC Geddon +// 2026-10-13 d5753b04: the Inferno circle opened at 653.8,-821.7 and the damage came from 645.1,-809.9, 13.7 y away, on bots that had just +// reached the edge of the first circle) keeps both circles open: the bots leave the place it was and the place it is. +struct AuraCircleOrigin { float x, y; bool drift; uint32_t openedMs; }; +uint32_t g_auraCircleOpenedMs = 0; // when the latest aura circle opened (diagnostic: how fast the bots start leaving) +std::unordered_map g_auraCircleLeaveLogged; // bot -> g_auraCircleOpenedMs it was logged for +std::unordered_map g_auraCircleOrigin; + +uint32_t g_breathEnemy = 0, g_breathCast = 0; // the fixed-path breath whose corridor HazardsFor just opened for this member (0 for none) + // Every avoid-circle that applies to this member right now. std::vector HazardsFor(Plan const& plan, Member const& self, uint32_t now) { RaidRules const& rules = *plan.rules; Player* bot = self.p; std::vector circles; + g_breathCast = 0; for (AvoidEnemyAura const& rule : rules.avoidEnemyAura) if (Matches(rule.who, self, plan.mainTank)) for (Unit* enemy : plan.enemies) + { + if (enemy->GetEntry() != rule.enemy) + continue; // The aura, or the cast that applies it: the circle opens when the boss starts the spell, not a plan // interval after it landed (MC Geddon 2026-10-11: 35 of 36 deaths in one Inferno, bots still inside). - if (enemy->GetEntry() == rule.enemy && (enemy->HasAura(rule.aura) || IsCasting(enemy, rule.aura))) + // It stays open kAuraCircleTailMs after both end: the last, heaviest tick of a periodic spell (Inferno: 5000) lands after the + // boss's aura is gone, and a bot walking back at the aura's end took it (MC Geddon 2026-10-12). + uint64_t const key = (enemy->GetGUID().GetCounter() << 32) ^ rule.aura; + if (enemy->HasAura(rule.aura) || IsCasting(enemy, rule.aura)) + { + // The circle opens: who stands inside it right now, for the next wipe's analysis (MC Geddon 2026-10-13: only the death + // distances were known, not where the raid stood when the cast began). One line per cast. + auto const prev = g_auraCircleSeen.find(key); + if (prev == g_auraCircleSeen.end() || now - prev->second > kAuraCircleTailMs) + { + uint32_t inside = 0, ranged = 0, tanks = 0; + float nearest = 9999.0f; + for (Member const& m : plan.members) + { + float const d = Dist2D(m.p->GetPositionX(), m.p->GetPositionY(), enemy->GetPositionX(), enemy->GetPositionY()); + nearest = std::min(nearest, d); + if (d <= rule.radius) + { + ++inside; + ranged += (m.ranged || m.healer) ? 1u : 0u; + tanks += m.tank ? 1u : 0u; + } + } + TC_LOG_INFO("playerbot.v2.raid", "[raid_circle] {} ({}) starts aura {}: circle {:.0f} y at {:.1f},{:.1f}; {} of {} members inside ({} ranged/healers, {} tanks), nearest {:.1f} y", + enemy->GetName(), enemy->GetEntry(), rule.aura, rule.radius, enemy->GetPositionX(), enemy->GetPositionY(), inside, + plan.members.size(), ranged, tanks, nearest); + if (Creature const* boss = enemy->ToCreature()) + { + Position const& home = boss->GetHomePosition(); + g_bossHome = { home.GetPositionX(), home.GetPositionY(), GameTime::GetGameTimeMS() }; + } + g_auraCircleOrigin[key] = { enemy->GetPositionX(), enemy->GetPositionY(), false, now ? now : 1u }; + g_auraCircleOpenedMs = now ? now : 1u; + } + g_auraCircleSeen[key] = now; + } + auto const seen = g_auraCircleSeen.find(key); + if (seen != g_auraCircleSeen.end() && now - seen->second <= kAuraCircleTailMs) + { circles.push_back({ enemy->GetPositionX(), enemy->GetPositionY(), rule.radius }); + auto origin = g_auraCircleOrigin.find(key); + if (origin != g_auraCircleOrigin.end()) + { + float const drift = Dist2D(origin->second.x, origin->second.y, enemy->GetPositionX(), enemy->GetPositionY()); + if (drift > 2.0f && circles.size() < 64) + circles.push_back({ origin->second.x, origin->second.y, rule.radius }); + // Where the walk ends: the drift so far, carried on to the end of the aura. Geddon walked ~15 y in one Inferno (MC + // 2026-10-13 2318f9d0): the ranged block stood outside the circle where he began, was run over at the seventh second and + // started out 0.3 s before the last tick. Capped, so one stray step does not throw a circle across the room. + if (drift > 2.0f && now > origin->second.openedMs + 500u && circles.size() < 64) + if (Aura const* aura = enemy->GetAura(rule.aura); aura && aura->GetDuration() > 0) + { + float const elapsed = float(now - origin->second.openedMs); + float const ahead = std::min(25.0f, drift / elapsed * float(std::min(aura->GetDuration(), 10000))); + float const dx = enemy->GetPositionX() - origin->second.x, dy = enemy->GetPositionY() - origin->second.y; + circles.push_back({ enemy->GetPositionX() + dx / drift * ahead, enemy->GetPositionY() + dy / drift * ahead, rule.radius }); + } + if (drift > 3.0f && !origin->second.drift) + { + origin->second.drift = true; + // What moves it: moving now, the root state, a root aura on it, and the generator on top (1 idle, 4 chase, 5 follow...). + // When it moved: ms since the circle opened and what is left of the aura (-1: the aura is gone and this is the + // tail). Geddon's script roots him for the eight ticks and lets go at the last one while the 10 s aura still has + // time on it, so a walk 7 s in with the root state clear is the chase starting again, not a root that failed. + Aura const* const live = enemy->GetAura(rule.aura); + TC_LOG_INFO("playerbot.v2.raid", "[raid_circle] {} ({}) moved {:.1f} y after aura {} opened (now {:.1f},{:.1f}), {} ms in, aura left {} ms; both circles stay open; moving {}, root state {}, root aura {}, generator {}, script {}", + enemy->GetName(), enemy->GetEntry(), drift, rule.aura, enemy->GetPositionX(), enemy->GetPositionY(), + now - origin->second.openedMs, live ? live->GetDuration() : -1, + enemy->isMoving() ? 1 : 0, enemy->HasUnitState(UNIT_STATE_ROOT) ? 1 : 0, enemy->HasAuraType(SPELL_AURA_MOD_ROOT) ? 1 : 0, + int(enemy->GetMotionMaster()->GetCurrentMovementGeneratorType()), + enemy->ToCreature() ? enemy->ToCreature()->GetScriptName() : std::string()); + } + } + } + } for (AvoidCarrier const& rule : rules.avoidCarrier) if (Matches(rule.who, self, plan.mainTank) && !bot->HasAura(rule.aura)) for (Member const& m : plan.members) @@ -588,7 +1019,45 @@ std::vector HazardsFor(Plan const& plan, Member const& self, uint32_t no if (creature->IsInCombat()) boss = creature; float lx, ly, lo; - if (!boss || !BreathLine(boss, rule.castSpell, now, lx, ly, lo)) + std::vector spells; + for (AvoidBreath const& other : rules.avoidBreath) + if (other.enemy == rule.enemy) + spells.push_back(other.castSpell); + if (rule.fixedPath) + { + // The corridor of the breath spell the enemy is casting, from the spell's own end points. Latched by spell id for the cast + // plus the chained triggers (5 s cast, then 250 ms per step), so it holds while she flies on. + if (!boss) + continue; + BreathSpellLatch& latch = g_breathSpell[boss->GetGUID().GetCounter()]; + if (uint32_t const cast = CastingBreath(boss, spells)) + { + if (latch.spell != cast || now > latch.until) + TC_LOG_INFO("playerbot.v2.raid", "[raid_breath] {} breath spell {} corridor opened", boss->GetName(), cast); + latch.spell = cast; + latch.until = now + 11000; + } + if (!latch.spell || now > latch.until) + continue; + for (AvoidBreath const& path : rules.avoidBreath) + if (path.enemy == rule.enemy && path.fixedPath && path.castSpell == latch.spell && Matches(path.who, self, plan.mainTank)) + { + breathAdded.push_back(rule.enemy); + g_breathEnemy = rule.enemy; + g_breathCast = path.castSpell; + float const dx = path.bx - path.ax, dy = path.by - path.ay; + float const len = std::sqrt(dx * dx + dy * dy); + float const step = std::max(path.halfWidth * 0.8f, 2.0f); + if (len < 1.0f) + break; + // from 10 yards before the first point to 10 past the last one + for (float d = -10.0f; d <= len + 10.0f + step && circles.size() < 64; d += step) + circles.push_back({ path.ax + dx / len * d, path.ay + dy / len * d, path.halfWidth }); + break; + } + continue; + } + if (!boss || !BreathLine(boss, spells, rule.windup, now, lx, ly, lo)) continue; breathAdded.push_back(rule.enemy); // Rectangle -> chain of circles of radius halfWidth, spaced 0.8 * halfWidth along the centre line, starting 10 yards behind. @@ -676,6 +1145,33 @@ Brain::MoveContext BuildMoveContext(Plan const& plan, Member const& self, std::v } } + // Flank stands (Onyxia): a melee bot's own approach to the boss (backstab behind the target, the nearest contact point, 1 y behind her) is + // what walked it into the tail sweep cone again and again (onyxia_full n8: 26-33 "leave cone" steps per melee bot, 128 flank steps). The + // cone circles above keep 4 y clear of the boss, so the apex behind her was unguarded. Keep-out circles over the rear half and the front + // arc leave only the flank wedge open to the generic approach. + for (StandFlank const& rule : plan.rules->standFlank) + { + if (!Matches(rule.who, self, plan.mainTank) || self.tank) + continue; + for (Unit* enemy : plan.enemies) + { + if (enemy->GetEntry() != rule.enemy || !enemy->IsAlive() || enemy->IsFlying() || !InPhase(enemy, rule.hpMax, rule.hpMin)) + continue; + float const eo = enemy->GetOrientation(), ex = enemy->GetPositionX(), ey = enemy->GetPositionY(); + // Rear: three circles across the back half; front: one in line with her facing. Radius 5 at 6.5 y. + for (float offDeg : { 180.0f, 140.0f, -140.0f }) + { + float const a = eo + offDeg * (float(M_PI) / 180.0f); + ctx.circles.push_back({ ex + 6.5f * std::cos(a), ey + 6.5f * std::sin(a), 5.0f }); + } + ctx.circles.push_back({ ex + 6.5f * std::cos(eo), ey + 6.5f * std::sin(eo), 4.5f }); + } + } + + // The keep-out zones (Onyxia's cave mouths) too: the bot's own move pickers (melee and healer gap-close, the LoS and cone steps, + // spacing, the formation slot) read only these circles, so without them a melee bot chasing a fresh whelp walked into the cave. + for (Circle const& k : g_keepOut) + ctx.circles.push_back({ k.x, k.y, k.r }); std::sort(ctx.circles.begin(), ctx.circles.end(), [&](Brain::MoveContext::Circle const& a, Brain::MoveContext::Circle const& c) { return Dist2D(bx, by, a.x, a.y) - a.r < Dist2D(bx, by, c.x, c.y) - c.r; }); float radius = 0.0f; @@ -698,8 +1194,13 @@ std::unordered_map g_faceAxis; constexpr float kAxisDrift = 8.0f; constexpr uint32_t kAxisStaleMs = 30000; -bool FaceAxisFor(Plan const& plan, Unit* enemy, uint32_t now, float& axis) +bool FaceAxisFor(Plan const& plan, Unit* enemy, uint32_t now, float& axis, float fixedBearingDeg = kNoBearing) { + if (fixedBearingDeg != kNoBearing) + { + axis = fixedBearingDeg * (float(M_PI) / 180.0f); + return true; + } uint64_t const key = (plan.groupLow << 32) ^ enemy->GetEntry(); float const ex = enemy->GetPositionX(), ey = enemy->GetPositionY(); FaceAxisLock& lock = g_faceAxis[key]; @@ -727,6 +1228,116 @@ bool FaceAxisFor(Plan const& plan, Unit* enemy, uint32_t now, float& axis) return true; } +// A bot standing in lava or slime leaves it for the nearest dry navmesh point. The Ragnaros fight (live 2026-10-12) had bots standing in +// the lava round the platform and not moving out; the log line says whether the core even applies the liquid to them (z against the +// surface), the move takes them out. "In" is the core's own contact test (MAP_LIQUID_STATUS_IN_CONTACT: in, under, or on the surface within +// a tenth of a yard), the one that starts the lava damage. A floor a few tenths above the surface is not lava: the Ragnaros platform is a +// model floor lying just over a magma sheet (2026-10-13: 169 "stands in magma" lines for bots at z -228.6 on a surface of -229.0, none of +// them hurt, each sent to another point of the same floor), and treating it as lava kept the whole raid walking. +std::unordered_map g_lastLavaLog; + +bool MagmaAt(Map* map, PhaseShift const& phase, float x, float y, float z, float& surfaceZ) +{ + LiquidData ld; + ZLiquidStatus const st = map->GetLiquidStatus(phase, x, y, z, map_liquidHeaderTypeFlags::Magma | map_liquidHeaderTypeFlags::Slime, &ld); + if (!(st & MAP_LIQUID_STATUS_IN_CONTACT)) + return false; + surfaceZ = ld.level; + return true; +} + +bool InMagma(Player* bot, float& surfaceZ) +{ + return MagmaAt(bot->GetMap(), bot->GetPhaseShift(), bot->GetPositionX(), bot->GetPositionY(), bot->GetPositionZ(), surfaceZ); +} + +// The nearest navmesh footing that is not itself in magma: rings of candidates round the bot, each snapped to the mesh and tested with the +// same contact check as the bot's own spot, so a leave-lava move never aims at another lava point. +bool ProbeDryFooting(Player* bot, Position& dry) +{ + constexpr int kBearings = 16; + constexpr float kRings[] = { 2.0f, 4.0f, 7.0f, 10.0f, 14.0f, 19.0f, 25.0f }; + float const bx = bot->GetPositionX(), by = bot->GetPositionY(), bz = bot->GetPositionZ(); + for (float ring : kRings) + { + float bestD = 1e9f; + bool found = false; + for (int k = 0; k < kBearings; ++k) + { + float const a = (2.0f * float(M_PI) * float(k)) / float(kBearings); + Position p; + if (!BotMovement::NearestNavPoint(bot, bx + std::cos(a) * ring, by + std::sin(a) * ring, bz, 2.0f, 6.0f, p)) + continue; + float surface = 0.0f; + if (MagmaAt(bot->GetMap(), bot->GetPhaseShift(), p.GetPositionX(), p.GetPositionY(), p.GetPositionZ() + 0.05f, surface)) + continue; + float const d = Dist2D(bx, by, p.GetPositionX(), p.GetPositionY()); + if (d < bestD) + { + bestD = d; + dry = p; + found = true; + } + } + if (found) + return true; + } + return false; +} + +// The probe is up to 112 navmesh queries, and LeaveMagma runs it for every bot in lava on every 300 ms plan. A bot that has not moved +// more than 3 y keeps the answer for 1.5 s. +bool NearestDryFooting(Player* bot, Position& dry) +{ + struct Cached { uint32_t at = 0; float x = 0.0f, y = 0.0f; Position dry; bool ok = false; }; + static std::unordered_map cache; + uint32_t const now = GameTime::GetGameTimeMS(); + Cached& c = cache[bot->GetGUID().GetCounter()]; + if (c.at && now - c.at < 1500 && Dist2D(c.x, c.y, bot->GetPositionX(), bot->GetPositionY()) < 3.0f) + { + if (c.ok) + dry = c.dry; + return c.ok; + } + c.at = now; + c.x = bot->GetPositionX(); + c.y = bot->GetPositionY(); + c.ok = ProbeDryFooting(bot, c.dry); + if (c.ok) + dry = c.dry; + if (cache.size() > 512) + for (auto it = cache.begin(); it != cache.end();) + it = (now - it->second.at > 10000) ? cache.erase(it) : std::next(it); + return c.ok; +} + +bool LeaveMagma(Player* bot, uint32_t now, RaidOrder& out) +{ + float surface = 0.0f; + if (!InMagma(bot, surface)) + return false; + uint32_t& at = g_lastLavaLog[bot->GetGUID().GetCounter()]; + bool const log = now - at >= 5000; + if (log) + at = now; + Position dry; + if (!NearestDryFooting(bot, dry)) + { + if (log) + TC_LOG_INFO("playerbot.v2.raid", "[raid_lava] {} stands in magma at ({:.1f},{:.1f},{:.1f}), surface z {:.1f}, hp {}%: no navmesh point within 25 y", + bot->GetName(), bot->GetPositionX(), bot->GetPositionY(), bot->GetPositionZ(), surface, uint32(bot->GetHealthPct())); + return false; + } + if (log) + TC_LOG_INFO("playerbot.v2.raid", "[raid_lava] {} stands in magma at ({:.1f},{:.1f},{:.1f}), surface z {:.1f}, hp {}%: leaves for ({:.1f},{:.1f},{:.1f}); " + "moving {}, casting {}, cast keeps it standing {}, cannot move (root/stun) {}, generator {}", + bot->GetName(), bot->GetPositionX(), bot->GetPositionY(), bot->GetPositionZ(), surface, uint32(bot->GetHealthPct()), + dry.GetPositionX(), dry.GetPositionY(), dry.GetPositionZ(), + bot->isMoving(), bot->IsNonMeleeSpellCast(false), bot->IsMovementPreventedByCasting(), + bot->HasUnitState(UNIT_STATE_NOT_MOVE), uint32(bot->GetMotionMaster()->GetCurrentMovementGeneratorType())); + return SetMove(out, dry.GetPositionX(), dry.GetPositionY(), dry.GetPositionZ(), "leave lava"); +} + void DecideMove(Plan const& plan, Member const& self, uint32_t now, std::vector const& circles, RaidOrder& out) { // 0. Scripted mechanics (Heigan's dance, Sapphiron's ice blocks) own the bot's movement while they run. @@ -743,31 +1354,119 @@ void DecideMove(Plan const& plan, Member const& self, uint32_t now, std::vector< if (others.empty()) return; + // Standing in lava or slime comes before every other move. + if (LeaveMagma(bot, now, out)) + return; + // 1. Carrier run (Living Bomb style): leave the group until clear of everyone. for (CarrierRun const& rule : rules.carrierRun) if (bot->HasAura(rule.aura) && Matches(rule.who, self, plan.mainTank)) { float nearest = 9999.0f; + int within = 0; for (Player* p : others) - nearest = std::min(nearest, Dist2D(bot->GetPositionX(), bot->GetPositionY(), p->GetPositionX(), p->GetPositionY())); + { + float const d = Dist2D(bot->GetPositionX(), bot->GetPositionY(), p->GetPositionX(), p->GetPositionY()); + nearest = std::min(nearest, d); + if (d <= 18.0f) + ++within; + } + // Who carries it, with how much health and how many raiders the blast reaches, once per bomb (Geddon 2026-10-13 5b31e3df: a caster + // died to the Explosion 29 y from Geddon and no line said whose bomb it was). + if (Aura const* bomb = bot->GetAura(rule.aura)) + if (uint32_t& seen = g_lastBombLog[bot->GetGUID().GetCounter()]; now - seen >= 12000u) + { + seen = now; + TC_LOG_INFO("playerbot.v2.raid", "[raid_bomb] {} carries aura {} (class {}, {} health, {} ms left): nearest raider {:.1f} y, {} within 18 y", + bot->GetName(), rule.aura, uint32(bot->GetClass()), bot->GetHealth(), bomb->GetDuration(), nearest, within); + } + // Already clear: stand still, do not run into other hazards. The stand is an order, not the absence of one: without it the + // formation and cast-reach rules walked the carrier back toward the raid, it was clear again a second later and ran out again, and + // the bomb went off 36-41 y from Geddon in the middle of the casters (n14 mc_geddon: Mclockb alternated carrier run, formation + // and "steps in" for 8 s; a healer died to the 3200 Explosion). + // A carrier standing in a hazard circle (Inferno) still leaves it: the bomb is 3200 on top of ticks up to 5000, and standing in the + // circle for the whole bomb timer killed Mctankda at 12 y from Geddon (n17 mc_geddon run 3). The hazard escape below picks the way + // out; the carrier circles of other bombs are already in `circles`. + bool const inHazard = !circles.empty() && InsideAny(circles, bot->GetPositionX(), bot->GetPositionY(), 0.0f); if (nearest >= rule.clearDistance - 1.0f) - return; // already clear: stand still, do not run into other hazards - if (Clearest(bot, others, rule.clearDistance, out, "carrier run", circles, /*urgent*/ true)) { Remember(bot, out, now); return; } + { + if (inHazard) + break; + SetMove(out, bot->GetPositionX(), bot->GetPositionY(), bot->GetPositionZ(), "carrier hold"); + return; + } + g_carrierRun = true; + bool const found = Clearest(bot, others, rule.clearDistance, out, "carrier run", circles, /*urgent*/ true); + g_carrierRun = false; + if (found) { Remember(bot, out, now); return; } uint32_t& at = g_lastCarrierLog[bot->GetGUID().GetCounter()]; if (now - at >= 3000) { at = now; - TC_LOG_INFO("playerbot.v2.raid", "[raid] {} carries aura {} but found no reachable clear spot (nearest raider {:.0f} yd)", - bot->GetName(), rule.aura, nearest); + TC_LOG_INFO("playerbot.v2.raid", "[raid] {} carries aura {} but found no reachable clear spot (nearest raider {:.0f} yd; {})", + bot->GetName(), rule.aura, nearest, g_clearestWhy); } + if (inHazard) + break; return; } // 2. Hazards (circles computed by the caller, which also publishes them in the order). if (!circles.empty() && InsideAny(circles, bot->GetPositionX(), bot->GetPositionY(), 0.0f)) { + // A breath with listed safe points: walk to the nearest usable one (it may lie inside the corridor's padding, so it is not tested + // against the circles), and stay on it while the corridor is open. + if (g_breathCast) + { + std::vector spots; + for (BreathSafe const& s : rules.breathSafe) + if (s.enemy == g_breathEnemy && s.castSpell == g_breathCast) + spots.push_back(&s); + std::sort(spots.begin(), spots.end(), [&](BreathSafe const* a, BreathSafe const* b) + { + return Dist2D(bot->GetPositionX(), bot->GetPositionY(), a->x, a->y) < Dist2D(bot->GetPositionX(), bot->GetPositionY(), b->x, b->y); + }); + for (BreathSafe const* s : spots) + { + float pz = 0.0f; + if (!Usable(bot, s->x, s->y, bot->GetPositionZ(), pz, /*urgent*/ true, /*hazard*/ true)) + continue; + SetMove(out, s->x, s->y, pz, "leave hazard"); + Remember(bot, out, now); + return; + } + } if (UseSticky(bot, circles, now, out)) return; - if (Escape(bot, circles, out)) { Remember(bot, out, now); return; } + if (Escape(bot, circles, out, self.tank ? &others : nullptr)) + { + // How long after the circle opened this member started out, and how far it has to go (MC Geddon 2026-10-13 4839bcf3: six melee died + // 17.8-21.2 y from the boss, still running). + if (g_auraCircleOpenedMs && now - g_auraCircleOpenedMs < 8000u && g_auraCircleLeaveLogged[bot->GetGUID().GetCounter()] != g_auraCircleOpenedMs) + { + g_auraCircleLeaveLogged[bot->GetGUID().GetCounter()] = g_auraCircleOpenedMs; + TC_LOG_INFO("playerbot.v2.raid", "[raid_circle] {} starts leaving {} ms after the circle opened, {} circles, going to {:.1f},{:.1f} ({:.1f} y)", + bot->GetName(), now - g_auraCircleOpenedMs, circles.size(), out.move_x, out.move_y, + Dist2D(bot->GetPositionX(), bot->GetPositionY(), out.move_x, out.move_y)); + } + Remember(bot, out, now); + return; + } + // Inside a circle with no way out found: the bot stands in it until the next pass. Said once a second per bot, with what refused the + // probed points (Geddon 2026-10-13 d202b196: six melee died in the Inferno circle and no line said they were stuck). + uint32_t& stuckAt = g_lastStuckLog[bot->GetGUID().GetCounter()]; + if (now - stuckAt >= 1000u) + { + stuckAt = now; + TC_LOG_INFO("playerbot.v2.raid", "[raid_circle] {} is inside a hazard circle at {:.1f},{:.1f} and found no way out: {} ({} circles, {} urgent probes this pass)", + bot->GetName(), bot->GetPositionX(), bot->GetPositionY(), g_escapeWhy, circles.size(), g_urgentProbes); + } + return; + } + // 2a. Inside a keep-out zone (feared, knocked or chased into Onyxia's cave mouth): walk out. Only the end points of planned moves were + // kept out of it, so a bot that got in some other way stayed there, next to the idle whelps. + if (!g_keepOut.empty() && InsideAny(g_keepOut, bot->GetPositionX(), bot->GetPositionY(), 0.0f) && Escape(bot, g_keepOut, out, nullptr)) + { + Remember(bot, out, now); return; } // Melee whose target stands inside a hazard for them: hold instead of chasing back in. @@ -810,7 +1509,7 @@ void DecideMove(Plan const& plan, Member const& self, uint32_t now, std::vector< if (++pathChecks > 6) break; float pz = 0.0f; - if (!Usable(bot, px, py, bot->GetPositionZ(), pz, /*urgent*/ true)) + if (!Usable(bot, px, py, bot->GetPositionZ(), pz, /*urgent*/ true, /*hazard*/ true)) continue; SetMove(out, px, py, pz, "leave cone"); return; @@ -825,7 +1524,7 @@ void DecideMove(Plan const& plan, Member const& self, uint32_t now, std::vector< if (self.tank && !self.healer) for (AvoidFrontal const& rule : rules.avoidFrontal) { - if (rule.who != Who::NonTank || rule.facingOffsetDeg != 0.0f) + if (rule.who != Who::NonTank || !rule.tankTurns || rule.facingOffsetDeg != 0.0f) continue; for (Unit* enemy : plan.enemies) { @@ -901,7 +1600,7 @@ void DecideMove(Plan const& plan, Member const& self, uint32_t now, std::vector< continue; float const ex = enemy->GetPositionX(), ey = enemy->GetPositionY(); float axis; - if (!FaceAxisFor(plan, enemy, now, axis)) + if (!FaceAxisFor(plan, enemy, now, axis, rule.bearingDeg)) continue; if (geo::TankOnAxis(ex, ey, bot->GetPositionX(), bot->GetPositionY(), axis, 30.0f * (float(M_PI) / 180.0f))) continue; @@ -960,7 +1659,7 @@ void DecideMove(Plan const& plan, Member const& self, uint32_t now, std::vector< if (fa.enemy == rule.enemy) { float axis; - if (FaceAxisFor(plan, enemy, now, axis)) + if (FaceAxisFor(plan, enemy, now, axis, fa.bearingDeg)) eo = axis; break; } @@ -983,6 +1682,60 @@ void DecideMove(Plan const& plan, Member const& self, uint32_t now, std::vector< } } + // 3d. Stand on the flank (Onyxia): matching bots stand in the wedge beside the enemy, between its front cones and its tail sweep, on the + // side they are on. A bot already in the wedge stays; at most one step per bot every 4 s. + for (StandFlank const& rule : rules.standFlank) + { + if (!Matches(rule.who, self, plan.mainTank) || self.tank) + continue; + for (Unit* enemy : plan.enemies) + { + if (enemy->GetEntry() != rule.enemy || !enemy->IsAlive() || enemy->IsFlying() || !InPhase(enemy, rule.hpMax, rule.hpMin)) + continue; + float const ex = enemy->GetPositionX(), ey = enemy->GetPositionY(); + float const eo = enemy->GetOrientation(); + float const half = rule.halfAngleDeg * (float(M_PI) / 180.0f), centre = rule.centerDeg * (float(M_PI) / 180.0f); + // Which flank: the side of its facing the bot is on. The rear-sector helpers measure from the line straight behind a facing, so the + // flank is handed to them as the "rear" of a facing turned a quarter round the other way. + float const side = geo::NormalizeAngle(geo::Bearing(ex, ey, bot->GetPositionX(), bot->GetPositionY()) - eo) >= 0.0f ? 1.0f : -1.0f; + // One slot per bot: the matching members on the same side, in guid order (plan.members is sorted), share the wedge as a grid + // of rows (distance) and columns (angle). A bot only walks to its own slot, so nothing else moves it and nobody lands on the + // same edge point (phase 3 live 2026-10-15: the raid in one clump beside her). + uint32_t index = 0, count = 0; + for (Member const& other : plan.members) + { + if (!Matches(rule.who, other, plan.mainTank) || other.tank) + continue; + float const otherSide = geo::NormalizeAngle(geo::Bearing(ex, ey, other.p->GetPositionX(), other.p->GetPositionY()) - eo) >= 0.0f ? 1.0f : -1.0f; + if (otherSide != side) + continue; + if (other.p == self.p) + index = count; + ++count; + } + float const depth = std::max(rule.maxDist - rule.minDist, 1.0f); + uint32_t const rows = std::clamp(uint32_t(std::ceil(depth / 5.0f)), 1u, 4u); + uint32_t const cols = std::max(1u, (count + rows - 1) / rows); + uint32_t const row = index % rows, col = index / rows; + float const angle = centre - half + (float(col) + 0.5f) / float(cols) * 2.0f * half; + float const dist = rule.minDist + (float(row) + 0.5f) / float(rows) * depth; + float const px = ex + dist * std::cos(eo + side * angle), py = ey + dist * std::sin(eo + side * angle); + if (Dist2D(bot->GetPositionX(), bot->GetPositionY(), px, py) <= 3.0f) + break; + uint32_t& at = g_lastRearStep[bot->GetGUID().GetCounter()]; + if (now - at < 4000) + break; + if (!circles.empty() && InsideAny(circles, px, py, 1.0f)) + break; + float pz = 0.0f; + if (!Usable(bot, px, py, enemy->GetPositionZ(), pz)) + break; + at = now; + SetMove(out, px, py, pz, "flank boss"); + return; + } + } + // 4. Role positions. for (StandByAura const& rule : rules.standByAura) { @@ -1009,6 +1762,20 @@ void DecideMove(Plan const& plan, Member const& self, uint32_t now, std::vector< { if (!Matches(rule.who, self, plan.mainTank)) continue; + if (rule.share) + { + // Position among the matching members (plan.members is sorted by guid): odd and even ones go to different posts. + uint32_t index = 0; + for (Member const& other : plan.members) + { + if (other.p == self.p) + break; + if (Matches(rule.who, other, plan.mainTank)) + ++index; + } + if ((index & 1u) != (rule.share == 2 ? 1u : 0u)) + continue; + } if (rule.who == Who::Healer) { // Healer camp positions only make sense when there are two tanks to be healed at two camps. @@ -1151,8 +1918,15 @@ void ElectTankSwaps(Election& e) if (!hm || !hm->tank || Stacks(holder, rule.debuffAura) < need) continue; bool swapped = false; + // The clean tank nearest to the enemy takes it: one that stands in melee reach keeps the boss in front of the raid, one that + // was knocked back would leave him with nobody to hit (Ragnaros 2026-10-15: no tank within 20 y of him for seconds after Wrath). + std::vector clean; for (Member& m : plan.members) + clean.push_back(&m); + std::stable_sort(clean.begin(), clean.end(), [&](Member* a, Member* b) { return a->p->GetDistance(enemy) < b->p->GetDistance(enemy); }); + for (Member* mp : clean) { + Member& m = *mp; if (m.p == holder || !m.tank || !m.bot || Stacks(m.p, rule.debuffAura) > 0 || e.busy.count(m.p->GetGUID().GetCounter())) continue; bool taken = false; @@ -1170,6 +1944,8 @@ void ElectTankSwaps(Election& e) // Hand the enemy over in the tank assignment now, so the new tank stays on it after the taunt. Services::PveCoordinator().ReassignTankTarget(plan.groupLow, plan.mapId, m.p->GetGUID().GetCounter(), enemy->GetGUID()); e.dump << " " << m.p->GetName() << ": taunt swap " << enemy->GetName() << " off " << holder->GetName() << "\n"; + TC_LOG_INFO("playerbot.v2", "[raid_swap] {} taunts {} off {} ({} stacks of {}), {:.0f}y from it", m.p->GetName(), enemy->GetName(), + holder->GetName(), Stacks(holder, rule.debuffAura), rule.debuffAura, m.p->GetDistance(enemy)); taken = true; } break; @@ -1213,15 +1989,14 @@ void ElectTankSwaps(Election& e) } // A boss that a Blink, a fear or a death left on a non-tank (Shazzrah's Gate of Shazzrah resets his threat and teleports him to a -// random player; Magmadar's Panic scatters the tanks): a tank taunts it back at once, the main tank first, and takes the tank -// assignment with it. Lucifron, Magmadar, Gehennas, Shazzrah. Logged as [raid_retaunt]. +// random player; Magmadar's Panic scatters the tanks; Ragnaros' Wrath resets it): a tank taunts it back at once, the main tank first, and +// takes the tank assignment with it. The bosses are RaidRules::retaunt. Logged as [raid_retaunt]. void ElectRetaunt(Election& e) { - static constexpr uint32_t kBosses[] = { 12118, 11982, 12259, 12264 }; Plan& plan = e.plan; for (Unit* enemy : plan.enemies) { - if (std::find(std::begin(kBosses), std::end(kBosses), enemy->GetEntry()) == std::end(kBosses) || Controlled(enemy)) + if (std::find(plan.rules->retaunt.begin(), plan.rules->retaunt.end(), enemy->GetEntry()) == plan.rules->retaunt.end() || Controlled(enemy)) continue; Unit* held = enemy->GetVictim(); Player* holder = held ? held->ToPlayer() : nullptr; @@ -1436,6 +2211,11 @@ void ElectDispels(Election& e) Plan& plan = e.plan; for (Dispel const& rule : plan.rules->dispel) { + // The data says nobody can dispel it (a fear with no dispel type): no order, or the dispellers spend their globals on casts the + // core refuses. + if (SpellInfo const* info = sSpellMgr->GetSpellInfo(rule.aura, DIFFICULTY_NONE)) + if (info->Dispel == DISPEL_NONE) + continue; auto const families = DispelSpellsFor(KindOf(rule)); // Healers and tanks first for an urgent debuff: Soul Burn silences, and a silenced healer is a dead tank. std::vector carriers; @@ -1609,7 +2389,7 @@ void ElectControlledMembers(Election& e) } // Forbidden targets and the fallback a DPS bot attacks instead. -void PublishTargets(Plan& plan, std::unordered_map& orders) +void PublishTargets(Plan& plan, std::unordered_map& orders, ObjectGuid coordFocus) { RaidRules const& rules = *plan.rules; std::vector forbiddenAll; // nobody attacks these @@ -1652,9 +2432,8 @@ void PublishTargets(Plan& plan, std::unordered_map& orders) return false; }; - Unit* best = nullptr; - int bestPriority = 0; Unit* tankTarget = plan.mainTank ? plan.mainTank->GetVictim() : nullptr; + std::vector candidates; // enemies a member may be told to kill; the rank is per member (Priority::who / gate) for (Unit* enemy : plan.enemies) { if (std::find(forbiddenAll.begin(), forbiddenAll.end(), enemy->GetGUID()) != forbiddenAll.end() || @@ -1663,25 +2442,59 @@ void PublishTargets(Plan& plan, std::unordered_map& orders) if (trailsHolder(enemy)) continue; // within the spread but not the healthiest: no focus on it bool const reflecting = enemy->HasAura(kMagicReflection) || enemy->HasAura(kDamageShield); - if (Controlled(enemy) || reflecting) + // The owner's skull on a sheeped mob is the call to kill it (Majordomo: he rotates the skull onto each sheeped Healer). + bool const skulled_hold = Controlled(enemy) && !coordFocus.IsEmpty() && enemy->GetGUID() == coordFocus; + if ((Controlled(enemy) && !skulled_hold) || reflecting) { forbiddenAll.push_back(enemy->GetGUID()); continue; } - int const priority = PriorityFor(rules, enemy->GetEntry()); - if (priority < 0) + if (PriorityFor(rules, enemy->GetEntry()) < 0) { forbiddenDps.push_back(enemy->GetGUID()); continue; } if (!enemy->GetVictim()) continue; // unpulled: the tank owns first contact - if (!best || priority > bestPriority || (priority == bestPriority && enemy == tankTarget)) - { - best = enemy; - bestPriority = priority; - } + candidates.push_back(enemy); } + // First matching entry per enemy wins; a gated entry needs a living gate enemy inside its health window. + auto const priorityFor = [&](Member const& m, Unit* enemy) + { + for (Priority const& rule : rules.priority) + { + if (rule.enemy != enemy->GetEntry() || !Matches(rule.who, m, plan.mainTank)) + continue; + if (rule.gateEnemy) + { + bool gated = false; + for (Unit* gate : plan.enemies) + if (gate->GetEntry() == rule.gateEnemy && InPhase(gate, rule.hpMax, rule.hpMin)) + gated = true; + if (!gated) + continue; + } + return rule.value; + } + return 1; + }; + auto const bestFor = [&](Member const& m) -> Unit* + { + Unit* best = nullptr; + int bestPriority = 0; + for (Unit* enemy : candidates) + { + int const priority = priorityFor(m, enemy); + if (priority < 0) + continue; + if (!best || priority > bestPriority || (priority == bestPriority && enemy == tankTarget)) + { + best = enemy; + bestPriority = priority; + } + } + return best; + }; for (Member const& m : plan.members) { if (!m.bot) @@ -1699,10 +2512,34 @@ void PublishTargets(Plan& plan, std::unordered_map& orders) for (Unit* enemy : plan.enemies) if (enemy->GetEntry() == rule.enemy) o.forbidden_targets.push_back(enemy->GetGUID()); - if (!m.tank && !m.healer && best) - o.fallback_target = best->GetGUID(); - if (m.tank && m.p != plan.mainTank && best) - o.tank_fallback_target = best->GetGUID(); + if (!m.tank && !m.healer) + { + // A DPS with no target goes to the raid's kill focus (the owner's skull / cross) before any rule's pick: nothing here + // competes with what the owner marked. + ObjectGuid const focus = coordFocus; + Unit* pick = nullptr; + if (!focus.IsEmpty()) + for (Unit* enemy : candidates) + if (enemy->GetGUID() == focus) + pick = enemy; + if (!pick) + pick = bestFor(m); + if (pick) + o.fallback_target = pick->GetGUID(); + } + else if (m.tank) + { + // A tank whose enemy is airborne (Onyxia in phase 2) cannot hold it: the enemy is forbidden for it and it takes the best ground + // target (the whelps, Priority) so they do not reach the healers. The main tank keeps its enemy while it is on the ground. + Unit* victim = m.p->GetVictim(); + bool const airborne = victim && victim->IsFlying(); + if (m.p != plan.mainTank || airborne || !victim) + if (Unit* best = bestFor(m)) + if (!best->IsFlying()) + o.tank_fallback_target = best->GetGUID(); + if (airborne) + o.forbidden_targets.push_back(victim->GetGUID()); + } } } @@ -1780,16 +2617,31 @@ void PublishThreatHolds(Plan& plan, std::unordered_map& ord if (!fight.first || now - fight.last > kFightGapMs) fight.first = now; fight.last = now; - uint32_t const capMs = boss ? (tankThreat <= 0.0f ? 3000u : 6000u) : (tankThreat <= 0.0f ? 1000u : 2000u); + // A boss gets the tank's time to arrive and build its lead: mc_geddon 09a8ff07 had Geddon on a mage 6 s in (the tank, 40 y off at the + // pull, still short of the 900 lead when the 6 s opening wait ran out), loose in the middle of the raid when Inferno came. + // Never longer than six seconds from the tank's first hit (playtest 2026-10-15), the same cap as the combat state's wait. + uint32_t const capMs = boss ? 6000u : (tankThreat <= 0.0f ? 1000u : 2000u); hold = now - std::min(since, fight.first) < capMs; } else { // At the tank's threat, not under 90 % of it (24 DPS capped at about the tank's rate less a tenth: MC Garr 2026-10-10). - hold = myThreat >= tankThreat * 1.0f; + // A boss that cuts its tank's threat on a schedule is held at what stays after a cut (RaidRules::threatDrop), like the generic hold. + float const share = (boss && creature && plan.rules) ? ThreatShareAfterDrop(*plan.rules, creature->GetEntry()) : 1.0f; + // Early in the pull the hold starts a typical hit short of the tank's threat and is not released until the tank has built up + // (ThreatEarlyHoldRatio), the same as the generic hold. + // A boss with a scheduled cut: ThreatEarlyHoldRatio already measures one more typical hit against the tank as it will be after the cut + // (kPullSafe* x share), so the base is the normal 1.0, not the share too (n38 onyxia_full: the base and the release limit were both + // exactly the share, so the timed release below could never apply, and DPS stood at 75-82 % of the tank for 13 s and more). + bool const cut = share < 1.0f; + float const holdRatio = ThreatEarlyHoldRatio(cut ? 1.0f : share, !m.ranged, tankThreat, share); + hold = myThreat >= tankThreat * holdRatio; if (hold) { - float const hard = m.ranged ? 1.20f : 1.05f; + // The timed release reaches the ratio at which the bot is still at the safe pull ratio of the tank after the cut. + float const hard = cut ? (m.ranged ? kPullSafeRanged : kPullSafeMelee) * share + : std::min({ ThreatHardRatio(!m.ranged, /*raid=*/true, tankThreat), share, + holdRatio < share ? holdRatio : 1.0e9f }); // the same limits as the generic hold (Bot/ThreatLimits.h) OverHold& oh = g_overHold[key]; if (!oh.first || now - oh.last > kOverHoldGapMs) oh.first = now; @@ -1899,7 +2751,10 @@ struct PullLog uint64_t groupLow = 0; uint32_t startMs = 0, lastSeenMs = 0; uint32_t startAlive = 0, groupSize = 0; - struct Mob { uint32_t entry; std::string name; bool boss; }; + uint32_t aliveLast = 0; // raiders alive at the last plan pass of the pull (the end line is written 4 s later, often after the squad left the map) + // seenDead: its corpse was seen. A mob that merely left the map (evade and despawn after a wipe) is not a kill (n32 mc_majordomo: the + // eight adds despawned at 89-99 % health and the line read "killed=8/9"). + struct Mob { uint32_t entry; std::string name; bool boss; bool seenDead = false; int32_t lastPct = 100; }; std::map engaged; bool readyLogged = false; // Deaths in this pull, for the wipe report: who fell first and what was hitting them. @@ -2078,7 +2933,7 @@ BossReadiness EvaluateBoss(uint32_t bossEntry, detail::Plan const& plan) return r; } -// The gaps to the humans of the group (Karrz, MC Magmadar 2026-10-10: no hunter in the raid, nobody could remove Frenzy and only +// The gaps to the humans of the group (playtest, MC Magmadar 2026-10-10: no hunter in the raid, nobody could remove Frenzy and only // the log said so). Once per boss per minute, whether it is sent before the pull or at the engage. std::unordered_map g_readyWarned; // (group << 32 | boss entry) -> ms of the last warning @@ -2112,7 +2967,7 @@ void WarnBeforePull(detail::Plan const& plan, Map* map, uint32_t now_ms) BossReadiness const r = EvaluateBoss(t->GetEntry(), plan); if (!r.any) continue; - // A human pull skips the bots' mana gate (Karrz pulled Magmadar with the healers at 58%), so the mana is checked here too. + // A human pull skips the bots' mana gate (the owner pulled Magmadar with the healers at 58%), so the mana is checked here too. WarnOwners(map, plan.groupLow, t->GetEntry(), t->GetName(), r.missing, now_ms, r.healerManaPct); return; } @@ -2151,8 +3006,13 @@ void TrackPull(uint64_t key, Group* group, detail::Plan const& plan, Map* map, u pl.startAlive = uint32_t(plan.members.size()); pl.groupSize = group->GetMembersCount(); ResetHealStats(); + ManaLedgerReset(); + IncomingReset(); } pl.lastSeenMs = now_ms; + pl.aliveLast = uint32_t(plan.members.size()); + for (Member const& m : plan.members) + IncomingWatch(m.p->GetGUID().GetCounter(), m.tank); for (GroupReference const& gref : group->GetMembers()) { Player* gp = gref.GetSource(); @@ -2160,6 +3020,10 @@ void TrackPull(uint64_t key, Group* group, detail::Plan const& plan, Map* map, u continue; uint64_t const gl = gp->GetGUID().GetCounter(); bool const alive = gp->IsAlive(); + // The mana ledger watches every class that can heal; it prints only those that sent a heal. + if (alive) + if (uint8_t const gc = gp->GetClass(); gc == CLASS_PRIEST || gc == CLASS_PALADIN || gc == CLASS_DRUID || gc == CLASS_SHAMAN) + ManaLedgerSample(gl, gp->GetName(), uint32(gp->GetPower(POWER_MANA)), uint32(gp->GetMaxPower(POWER_MANA)), GameTime::GetGameTimeMS()); if (auto w = pl.wasAlive.find(gl); w != pl.wasAlive.end() && w->second && !alive) { ++pl.deaths; @@ -2187,6 +3051,14 @@ void TrackPull(uint64_t key, Group* group, detail::Plan const& plan, Map* map, u pl.engaged.emplace(c->GetGUID(), PullLog::Mob{ c->GetEntry(), c->GetName(), boss }); added = true; } + for (auto& [eg, em] : pl.engaged) + if (Creature* ec = map->GetCreature(eg)) + { + if (!ec->IsAlive()) + em.seenDead = true; + else + em.lastPct = int32_t(ec->GetHealthPct()); + } if (added && now_ms == pl.startMs) TC_LOG_INFO("playerbot.v2.raid", "[raid_encounter] ts={} map={} group={} pull start: {} | alive={}/{}", uint64_t(GameTime::GetGameTime()), pl.mapId, pl.groupLow, PullLabel(pl), pl.startAlive, pl.groupSize); @@ -2214,31 +3086,76 @@ void EndQuietPulls(uint32_t now_ms) continue; } Map* map = sMapMgr->FindMap(pl.mapId, pl.instanceId); - uint32_t killed = 0; + uint32_t killed = 0, bosses = 0, bossesDead = 0; std::string left; for (auto const& [guid, mob] : pl.engaged) { Creature* c = map ? map->GetCreature(guid) : nullptr; - if (!c || !c->IsAlive()) + // Gone from the map is a despawn, not a kill, unless its corpse was seen or it was last seen at the edge of death: a boss or an + // add that vanished at 90 % was reset. + bool const dead = mob.seenDead || (c && !c->IsAlive()) || (!c && mob.lastPct <= 3); + if (mob.boss) + { + ++bosses; + bossesDead += dead; + } + if (dead) ++killed; else if (left.size() < 120) - left += (left.empty() ? "" : ", ") + mob.name + " " + std::to_string(int32(c->GetHealthPct())) + "%"; + left += (left.empty() ? "" : ", ") + mob.name + " " + std::to_string(c ? int32(c->GetHealthPct()) : mob.lastPct) + "%"; } - uint32_t alive = 0; + // The raiders alive at the last plan pass of the pull: by the time this line is written the squad may be out of the map (a scenario + // that ends takes it out), which read as alive=0/40 on every clean kill (n24 2026-10-14). + uint32_t alive = pl.aliveLast; + // A human of the group lying dead on the map with no living raider left on it is a wipe, however many bots stood at the last plan + // pass or died before the squad was counted out (n58 live 2026-10-15: 29 deaths of 40, 13 "alive" from the last pass, result "reset": + // the encounter end below never ran and Release Spirit stayed greyed out, "a member of your group is in combat"). + bool humanDeadNoneAlive = false; if (map) + { + uint32_t onMap = 0; + bool humanDead = false; for (MapReference const& ref : map->GetPlayers()) - if (Player* p = ref.GetSource(); p && p->IsAlive() && p->GetGroup() && - p->GetGroup()->GetGUID().GetCounter() == pl.groupLow) - ++alive; - char const* result = killed == pl.engaged.size() ? "kill" : (alive * 4 <= pl.startAlive ? "wipe" : "reset"); - TC_LOG_INFO("playerbot.v2.raid", "[raid_encounter] ts={} map={} group={} pull end: result={} dur={}s killed={}/{} alive={}/{} | {}{}{}", + if (Player* p = ref.GetSource(); p && p->GetGroup() && p->GetGroup()->GetGUID().GetCounter() == pl.groupLow) + { + if (p->IsAlive()) + ++onMap; + else if (!Services::Lifecycle().is_bot(p->GetGUID().GetCounter())) + humanDead = true; + } + if (onMap) + alive = onMap; + else if (humanDead) + { + humanDeadNoneAlive = true; + alive = 0; + } + } + // A wipe is raiders dead, not raiders gone: a scenario that ends at its death limit takes the squad out of the map, and a raid that + // left the instance is no wipe either (onyxia_full / mc_geddon n7 2026-10-14: six deaths, run over, "alive=0/40 wipe"). + bool const mostDead = pl.deaths * 4 >= pl.startAlive * 3; + // The boss dead is a kill even with its adds still standing (Garr's Firesworn, Ragnaros' Sons of Flame): the left list names them. + bool const bossKilled = bosses > 0 && bossesDead == bosses; + char const* result = killed == pl.engaged.size() || bossKilled ? "kill" : ((alive * 4 <= pl.startAlive && mostDead) || humanDeadNoneAlive ? "wipe" : "reset"); + TC_LOG_INFO("playerbot.v2.raid", "[raid_encounter] ts={} map={} group={} pull end: result={} dur={}s killed={}/{} alive={}/{} deaths={} | {}{}{}", uint64_t(GameTime::GetGameTime()), pl.mapId, pl.groupLow, result, (pl.lastSeenMs - pl.startMs) / 1000, killed, - uint32_t(pl.engaged.size()), alive, pl.startAlive, PullLabel(pl), left.empty() ? "" : " | left: ", left); + uint32_t(pl.engaged.size()), alive, pl.startAlive, pl.deaths, PullLabel(pl), left.empty() ? "" : " | left: ", left); // Healer throughput of the pull: heal casts per minute per healer (a healer missing from the list cast nothing). uint32_t healersCast = 0; std::string const healStats = TakeHealStats(uint32_t((pl.lastSeenMs - pl.startMs) / 1000), healersCast); TC_LOG_INFO("playerbot.v2.raid", "[raid_fight] map={} group={} healers that cast: {} | {}", pl.mapId, pl.groupLow, healersCast, healStats.empty() ? "none" : healStats); + for (std::string const& line : ManaLedgerTake(uint32_t((pl.lastSeenMs - pl.startMs) / 1000), [](uint32 id) + { + SpellInfo const* si = sSpellMgr->GetSpellInfo(id, DIFFICULTY_NONE); + char const* const name = si && si->SpellName ? (*si->SpellName)[sWorld->GetDefaultDbcLocale()] : nullptr; + return std::string(name && *name ? name : "spell") + "#" + std::to_string(id); + })) + TC_LOG_INFO("playerbot.v2.raid", "[mana_ledger] map={} group={} {}", pl.mapId, pl.groupLow, line); + for (std::string const& line : DealtTake(uint32_t((pl.lastSeenMs - pl.startMs) / 1000))) + TC_LOG_INFO("playerbot.v2.raid", "[raid_dealt] map={} group={} {}", pl.mapId, pl.groupLow, line); + for (std::string const& line : IncomingTake(uint32_t((pl.lastSeenMs - pl.startMs) / 1000))) + TC_LOG_INFO("playerbot.v2.raid", "[raid_incoming] map={} group={} {}", pl.mapId, pl.groupLow, line); // Wipe report to the humans of the group (a system line in their chat window). if (std::strcmp(result, "wipe") == 0) if (map) @@ -2248,7 +3165,7 @@ void EndQuietPulls(uint32_t now_ms) ChatHandler(hp->GetSession()).SendSysMessage(fmt::format("Wipe: {} lasted {} s, {} died, first down {}.", PullLabel(pl), (pl.lastSeenMs - pl.startMs) / 1000, pl.deaths, pl.firstDead.empty() ? std::string("nobody seen") : pl.firstDead)); - // [raid_wipe] encounter end (Karrz, MC Garr 2026-10-08: the whole raid dead and released, "A member of your group is in combat" + // [raid_wipe] encounter end (playtest, MC Garr 2026-10-08: the whole raid dead and released, "A member of your group is in combat" // still blocked his release; the client's own encounter state stayed on). With nobody of the group alive on the map: end the // encounter for every group member, wherever they are (SendToPlayers reaches only the map), fail any boss still IN_PROGRESS // and make the mobs of the pull evade and reset. @@ -2283,7 +3200,7 @@ void EndQuietPulls(uint32_t now_ms) } // namespace -// [release] (Karrz, MC 2026-10-08: "A member of your group is in combat" blocks Release Spirit, which worked in the morning): while a human of +// [release] (playtest, MC 2026-10-08: "A member of your group is in combat" blocks Release Spirit, which worked in the morning): while a human of // the group is dead, every 5 s which members the client can see in combat, whether an offer is pending on him and whether the map's // encounter is on. The server's repop handler has no combat check; this shows what the client is reacting to. static void LogReleaseState(Group const* group, Map const* map, uint32_t now_ms) @@ -2317,6 +3234,128 @@ static void LogReleaseState(Group const* group, Map const* map, uint32_t now_ms) } } +// An encounter nobody is alive to fight is over (Onyxia 2026-10-15: the pull was judged at the instant one bot still lived, the wipe end +// above never ran, and the boss stayed IN_PROGRESS with the whole raid dead). With a human of a dungeon group dead and no living player +// left on his instance for 3 s: fail the bosses still IN_PROGRESS (that sends the encounter end to the client) and send the mobs in +// combat to evade. +static void EndAbandonedEncounters(uint32_t now_ms) +{ + static std::unordered_map since; + std::unordered_set seen; + for (auto const& [guid, h] : ObjectAccessor::GetPlayers()) + { + if (!h || !h->IsInWorld() || h->IsAlive() || Services::Lifecycle().is_bot(h->GetGUID().GetCounter())) + continue; + Map* map = h->GetMap(); + InstanceMap* im = map ? map->ToInstanceMap() : nullptr; + InstanceScript* script = im ? im->GetInstanceScript() : nullptr; + if (!script || !script->IsEncounterInProgress() || !seen.insert(im->GetInstanceId()).second) + continue; + bool anyAlive = false; + for (MapReference const& ref : im->GetPlayers()) + if (Player* p = ref.GetSource(); p && p->IsAlive() && !p->IsGameMaster()) + { + anyAlive = true; + break; + } + uint32_t& s = since[im->GetInstanceId()]; + if (anyAlive) + { + s = 0; + continue; + } + if (!s) + { + s = now_ms ? now_ms : 1u; + continue; + } + if (now_ms - s < 3000u) + continue; + s = 0; + uint32_t failed = 0, evaded = 0; + for (uint32 id = 0; id < script->GetEncounterCount(); ++id) + if (script->GetBossState(id) == IN_PROGRESS && script->SetBossState(id, FAIL)) + ++failed; + for (auto const& [spawnId, c] : im->GetCreatureBySpawnIdStore()) + if (c && c->IsInWorld() && c->IsAlive() && c->IsInCombat() && !c->IsControlledByPlayer() && c->AI()) + { + c->AI()->EnterEvadeMode(EvadeReason::NoHostiles); + ++evaded; + } + TC_LOG_INFO("playerbot.v2.raid", "[raid_wipe] encounter abandoned: map={} instance={} nobody alive on it: {} boss state(s) failed, {} mob(s) sent to evade", + im->GetId(), im->GetInstanceId(), failed, evaded); + } +} + +// [release_state] (playtest 2026-10-15, MC Majordomo wipe: Release Spirit stayed greyed out, "a member of your group is in combat", for +// about two minutes after every bot had left the instance and the bosses had reset; [release] above stops once the raid is off the map). +// While a human of a dungeon group lies dead, every 5 s and wherever the raid is: his own combat flags, every group member's combat and +// pet-combat flags on any map, the creatures of his map still in combat, and the map's boss states. The first line names what is left. +static void LogDeadHumanReleaseState(uint32_t now_ms) +{ + static std::unordered_map last; + for (auto const& [guid, h] : ObjectAccessor::GetPlayers()) + { + if (!h || !h->IsInWorld() || h->IsAlive() || Services::Lifecycle().is_bot(h->GetGUID().GetCounter())) + continue; + Group const* group = h->GetGroup(); + Map const* map = h->GetMap(); + if (!group || !map || !map->IsDungeon()) + continue; + uint32_t& l = last[h->GetGUID().GetCounter()]; + if (l && now_ms - l < 5000u) + continue; + l = now_ms ? now_ms : 1u; + + uint32_t members = 0, onMap = 0, dead = 0, combat = 0, petCombat = 0, otherMap = 0; + std::string names; + for (GroupReference const& ref : group->GetMembers()) + { + Player const* m = ref.GetSource(); + if (!m || m == h) + continue; + ++members; + if (m->IsInWorld() && m->GetMap() == map) + ++onMap; + else + ++otherMap; + if (!m->IsAlive()) + ++dead; + bool const c = m->IsInCombat(), pc = m->HasUnitFlag(UNIT_FLAG_PET_IN_COMBAT); + if (c) + ++combat; + if (pc) + ++petCombat; + if ((c || pc) && names.size() < 160) + names += (names.empty() ? "" : ", ") + m->GetName() + "[map " + std::to_string(m->GetMapId()) + (m->IsAlive() ? "" : " dead") + + (c ? " combat" : "") + (pc ? " pet" : "") + "]"; + } + + uint32_t mobsCombat = 0; + std::string mobNames; + for (auto const& [spawnId, c] : map->GetCreatureBySpawnIdStore()) + if (c && c->IsInWorld() && c->IsAlive() && c->IsInCombat() && !c->IsControlledByPlayer()) + { + ++mobsCombat; + if (mobNames.size() < 160) + mobNames += (mobNames.empty() ? "" : ", ") + c->GetName() + (c->HasUnitState(UNIT_STATE_EVADE) ? "[evade]" : ""); + } + + InstanceScript const* script = map->ToInstanceMap() ? map->ToInstanceMap()->GetInstanceScript() : nullptr; + std::string bosses; + if (script) + for (uint32 id = 0; id < script->GetEncounterCount(); ++id) + if (script->GetBossState(id) != NOT_STARTED) + bosses += (bosses.empty() ? "" : ", ") + std::to_string(id) + ":" + std::to_string(int(script->GetBossState(id))); + + TC_LOG_INFO("playerbot.v2.raid", + "[release_state] {} dead map={} ghost={} self_combat={} self_pet_combat={} offer_pending={} | group {} others: {} on map, {} elsewhere, {} dead, {} in combat, {} pet in combat: {} | creatures in combat on map: {}: {} | encounter in progress: {} boss states (id:state, not NOT_STARTED): {}", + h->GetName(), h->GetMapId(), int(h->HasPlayerFlag(PLAYER_FLAGS_GHOST)), int(h->IsInCombat()), int(h->HasUnitFlag(UNIT_FLAG_PET_IN_COMBAT)), + int(h->IsResurrectRequested()), members, onMap, otherMap, dead, combat, petCombat, names.empty() ? "-" : names, mobsCombat, + mobNames.empty() ? "-" : mobNames, script ? int(script->IsEncounterInProgress()) : -1, bosses.empty() ? "-" : bosses); + } +} + // A resurrection a group bot cast on a human member sits as a pending offer until the client answers. The 70205 client has shown // no "X wants to resurrect you" popup (MC 2026-10-08: the first healer's Resurrection landed, the offer stayed pending, every // other rezzer saw the corpse as being raised and the owner stayed dead). A pending offer from a bot of the group is accepted @@ -2421,6 +3460,9 @@ void Brain::Update(uint32_t now_ms) return; } + LogDeadHumanReleaseState(now_ms); + EndAbandonedEncounters(now_ms); + // Bucket bots on raid maps that have rules by (group, map). struct Bucket { Group* group = nullptr; uint32_t mapId = 0; uint64_t refBot = 0; Player* ref = nullptr; }; std::map buckets; @@ -2519,6 +3561,8 @@ void Brain::Update(uint32_t now_ms) std::sort(plan.enemies.begin(), plan.enemies.end(), [](Unit* a, Unit* c) { return a->GetGUID() < c->GetGUID(); }); TrackPull(key, b.group, plan, b.ref->GetMap(), now_ms); SetIdleHostiles(plan, b.ref); + SetKeepOut(plan); + SetEngagedReach(plan); AcceptBotRezOffers(b.group, b.ref->GetMap(), now_ms); LogReleaseState(b.group, b.ref->GetMap(), now_ms); @@ -2612,6 +3656,7 @@ void Brain::Update(uint32_t now_ms) nextMoveCtx[m.p->GetGUID().GetCounter()] = BuildMoveContext(plan, m, circles); if (!m.p->HasUnitState(UNIT_STATE_ROOT | UNIT_STATE_STUNNED | UNIT_STATE_CONFUSED | UNIT_STATE_FLEEING)) DecideMove(plan, m, now_ms, circles, o); + ApplyKeepOut(plan, m, circles, o); if (o.move) dump << " " << m.p->GetName() << ": move (" << o.move_reason << ")\n"; for (NoAoe const& rule : plan.rules->noAoe) @@ -2630,6 +3675,29 @@ void Brain::Update(uint32_t now_ms) if (m.tank) if (Unit* v = m.p->GetVictim()) tankTargets.push_back(v); + // A mob a tank is assigned, or that carries a tank marker (star..square), is the tank's, not the mages': the assignment runs a + // moment ahead of the tank's victim (n32 mc_majordomo: a Healer marked for a tank was sheeped a second later and the tank dropped it). + { + Group const* grp = nullptr; + for (Member const& m : plan.members) + { + if (!grp && m.p) + grp = m.p->GetGroup(); + if (m.tank && m.bot) + if (PveOrder const* po = Services::PveCoordinator().OrderFor(m.p->GetGUID().GetCounter()); po && po->active && !po->tank_target.IsEmpty()) + for (Unit* enemy : plan.enemies) + if (enemy->GetGUID() == po->tank_target) + tankTargets.push_back(enemy); + } + if (grp) + // Every marked mob is the owner's call (playtest 2026-10-15): the encounter rules never crowd-control it. The moon + // is held by the mark orders (PveGroupCoordinator::PlanMarkOrders), not elected a second time here. + for (uint8 icon = 0; icon < 8; ++icon) + if (ObjectGuid const g = grp->GetTargetIcon(icon); !g.IsEmpty()) + for (Unit* enemy : plan.enemies) + if (enemy->GetGUID() == g) + tankTargets.push_back(enemy); + } ElectControlledMembers(e); MechanicsElect(e, now_ms); // scripted jobs first (Razuvious' mind control): they must not lose their priest to a dispel ElectTankSwaps(e); @@ -2638,7 +3706,7 @@ void Brain::Update(uint32_t now_ms) ElectDispels(e); ElectPurges(e); ElectCrowdControl(e, tankTargets, CoordinatorFocus(plan.groupLow, plan.mapId)); - PublishTargets(plan, next); + PublishTargets(plan, next, CoordinatorFocus(plan.groupLow, plan.mapId)); if (std::vector hints = SchoolHints(plan, dump); !hints.empty()) nextSchools[FocusKey(plan.groupLow, plan.mapId)] = std::move(hints); if (!plan.ruleFocus.IsEmpty()) diff --git a/src/modules/PlayerbotV2/Bot/Raid/RaidBrainInternal.h b/src/modules/PlayerbotV2/Bot/Raid/RaidBrainInternal.h index 20f83cee8d..83a5fe7c58 100644 --- a/src/modules/PlayerbotV2/Bot/Raid/RaidBrainInternal.h +++ b/src/modules/PlayerbotV2/Bot/Raid/RaidBrainInternal.h @@ -55,7 +55,7 @@ bool Controlled(Unit* u); // Path queries are capped per plan pass (all bots together, see ResetPathProbes): urgent probes (leaving a hazard, // a carrier run, scripted mechanics, a breath / cone) may use the whole cap, the rest (spread, role spots, stay near) // stop early so an escape never finds the pass's budget spent. -bool Usable(Player* bot, float x, float y, float zHint, float& outZ, bool urgent = false); +bool Usable(Player* bot, float x, float y, float zHint, float& outZ, bool urgent = false, bool hazard = false); void ResetPathProbes(); bool SetMove(RaidOrder& out, float x, float y, float z, char const* reason); // Best nearby point that increases the distance to every raid member in `others`. diff --git a/src/modules/PlayerbotV2/Bot/Raid/RaidCombat.cpp b/src/modules/PlayerbotV2/Bot/Raid/RaidCombat.cpp index 2463dcb172..2e844fc3f5 100644 --- a/src/modules/PlayerbotV2/Bot/Raid/RaidCombat.cpp +++ b/src/modules/PlayerbotV2/Bot/Raid/RaidCombat.cpp @@ -67,12 +67,15 @@ bool DispatchRaidOrder(BotAI& ai, BotSnapshotView const& s, BotIntentEmitter& em } // 1. Hazards first: leaving Inferno / Living Bomb range / a breath corridor beats everything else. - // A deduped re-emit (same point, still walking) still owns the tick so the rotation does not chase back in. + // A deduped re-emit (same point, still walking) still owns the tick so the rotation does not chase back in. A move that was + // refused (the path ring, the API's no-path answer) owns nothing: the bot stood on the spot casting and attacking nothing. if (o.move) { - emit.move_to(o.move_x, o.move_y, o.move_z, /*run=*/true); - ai.set_last_rule_fired("raid:move"); - return true; + if (emit.move_to(o.move_x, o.move_y, o.move_z, /*run=*/true) || emit.move_already_emitted(o.move_x, o.move_y, o.move_z)) + { + ai.set_last_rule_fired("raid:move"); + return true; + } } // A debuff that turns the bot's rotation against the raid (Nefarian's priest call): no rotation until it fades, a heal @@ -85,6 +88,18 @@ bool DispatchRaidOrder(BotAI& ai, BotSnapshotView const& s, BotIntentEmitter& em return true; } + // A melee bot whose target stands in a hazard it has just left (Inferno, a cloud): no rotation, the rotation's approach would walk it + // straight back in. The brain sets the flag every plan while the hazard is up; it clears when the circle closes. (MC Geddon n8 run 4: six + // melee left the Inferno circle, the rotation sent them back at second six, and the last tick killed all six at 17-20 y; the flag had + // been set for every plan and nothing read it.) An elected job (a dispel) still runs. + if (o.hold_melee && o.cast_kind == RaidOrder::CastKind::None) + { + // The victim stays selected: the brain raises the flag only while the victim stands in the hazard, so dropping it would clear the flag + // and the rotation would walk back in on the next plan. + ai.set_last_rule_fired("raid:melee_hold"); + return true; + } + // 2. The elected job (taunt swap, dispel, purge, crowd control). Let a running cast finish, then cast. if (o.cast_kind != RaidOrder::CastKind::None && o.cast_spell) { @@ -126,6 +141,13 @@ bool DispatchRaidOrder(BotAI& ai, BotSnapshotView const& s, BotIntentEmitter& em std::find(o.forbidden_targets.begin(), o.forbidden_targets.end(), victim) != o.forbidden_targets.end(); // An idle DPS bot picks up the fallback too, unless its owner told it to stay. bool const idleDps = victim.IsEmpty() && !o.fallback_target.IsEmpty() && !ai.holding_position(s.published_at_ms()); + // An idle tank (its enemy is airborne or dead) takes the brain's ground target. + bool const idleTank = victim.IsEmpty() && o.fallback_target.IsEmpty() && !o.tank_fallback_target.IsEmpty() && !ai.holding_position(s.published_at_ms()); + if (idleTank && emit.start_attack(o.tank_fallback_target)) + { + ai.set_last_rule_fired("raid:switch_target"); + return true; + } if (forbidden || idleDps) { if (!o.fallback_target.IsEmpty() && o.fallback_target != victim) @@ -217,7 +239,9 @@ void RegisterRaidIdleRules(IdleRuleRegistry& r) move.fire = [](BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const&, BotIntentEmitter& emit, uint32) { RaidOrder const& o = s.raw().raid_order; - emit.move_to(o.move_x, o.move_y, o.move_z, /*run=*/true); + // A refused move does not claim the tick (see raid:move in DispatchRaidOrder): the idle rules below get the bot. + if (!emit.move_to(o.move_x, o.move_y, o.move_z, /*run=*/true) && !emit.move_already_emitted(o.move_x, o.move_y, o.move_z)) + return false; ai.set_last_rule_fired("idle:raid_move"); return true; }; diff --git a/src/modules/PlayerbotV2/Bot/Raid/RaidEncounterData_BWL.cpp b/src/modules/PlayerbotV2/Bot/Raid/RaidEncounterData_BWL.cpp index ac70ed87e3..9362f386f6 100644 --- a/src/modules/PlayerbotV2/Bot/Raid/RaidEncounterData_BWL.cpp +++ b/src/modules/PlayerbotV2/Bot/Raid/RaidEncounterData_BWL.cpp @@ -1,6 +1,6 @@ #include "RaidEncounters.h" -// Ported from Karrz's raid10-revamp ike3 bots (the ike3-based playerbot code). Script references (mc/..., bwl/..., ony/...) point at the +// Ported from Karrz's raid10-revamp ike3 bots (Karrz1/wow-1.12). Script references (mc/..., bwl/..., ony/...) point at the // VMaNGOS scripts that Forever's scripts/Custom/Classic instances were ported from; the ids are the same. namespace Playerbot::Raid { diff --git a/src/modules/PlayerbotV2/Bot/Raid/RaidEncounterData_BWL_Movement.cpp b/src/modules/PlayerbotV2/Bot/Raid/RaidEncounterData_BWL_Movement.cpp index fc1b23fceb..6a1628af91 100644 --- a/src/modules/PlayerbotV2/Bot/Raid/RaidEncounterData_BWL_Movement.cpp +++ b/src/modules/PlayerbotV2/Bot/Raid/RaidEncounterData_BWL_Movement.cpp @@ -1,6 +1,6 @@ #include "RaidEncounters.h" -// Ported from Karrz's raid10-revamp ike3 bots (the ike3-based playerbot code). Script references (mc/..., bwl/..., ony/...) point at the +// Ported from Karrz's raid10-revamp ike3 bots (Karrz1/wow-1.12). Script references (mc/..., bwl/..., ony/...) point at the // VMaNGOS scripts that Forever's scripts/Custom/Classic instances were ported from; the ids are the same. namespace Playerbot::Raid { diff --git a/src/modules/PlayerbotV2/Bot/Raid/RaidEncounterData_MC.cpp b/src/modules/PlayerbotV2/Bot/Raid/RaidEncounterData_MC.cpp index 5d6bbbc0bd..faf6c00ec9 100644 --- a/src/modules/PlayerbotV2/Bot/Raid/RaidEncounterData_MC.cpp +++ b/src/modules/PlayerbotV2/Bot/Raid/RaidEncounterData_MC.cpp @@ -1,6 +1,6 @@ #include "RaidEncounters.h" -// Ported from Karrz's raid10-revamp ike3 bots (the ike3-based playerbot code). Script references (mc/..., bwl/..., ony/...) point at the +// Ported from Karrz's raid10-revamp ike3 bots (Karrz1/wow-1.12). Script references (mc/..., bwl/..., ony/...) point at the // VMaNGOS scripts that Forever's scripts/Custom/Classic instances were ported from; the ids are the same. namespace Playerbot::Raid { @@ -13,7 +13,10 @@ namespace Playerbot::Raid { r.bosses = { 12118, 11982, 12259, 12057, 12264, 12056, 12098, 11988, 12018, 11502 }; // LUCIFRON - boss 12118 - r.dispel.push_back({ 19703, DispelKind::Curse }); // Lucifron's Curse (mc/boss_lucifron.cpp:19) + // Lucifron's Curse doubles the mana cost of every spell and ability of everyone within 40 yards for 5 min (classic_boss_lucifron.cpp:31): + // on the healers it is the difference between a sustained kill and an out-of-mana wipe, so it is urgent (healers and tanks first, + // even while the raid is in an emergency), like Gehennas' Curse. + r.dispel.push_back({ 19703, DispelKind::Curse, true }); // Lucifron's Curse (mc/boss_lucifron.cpp:19) r.dispel.push_back({ 19702, DispelKind::Magic, true }); // Impending Doom, 2000 shadow after 10s within 40 yd (mc/boss_lucifron.cpp:18); kind UNVERIFIED r.priority.push_back({ 12119, 4 }); // Flamewaker Protector (MCRaidPolicy.h:100) r.controlledMember.push_back({ 20604 }); // Protector's Dominate Mind (vanilla_smartai, VMaNGOS spell list 121190) @@ -69,13 +72,26 @@ namespace Playerbot::Raid { // He surrenders when the adds are dead and cannot be killed (mc/boss_majordomo_executus.cpp:335,379): never a target. // Every 30s one of Magic Reflection / Damage Shield is cast on ALL living adds (:485-501): dispel them off before attacking. r.priority.push_back({ 12018, -1 }); // Majordomo Executus (mc/boss_majordomo_executus.cpp:335) + // One plan (n71 wipe): one tank holds Majordomo, away from the raid, and the other tanks take the four Elites. Mages sheep up to + // three Healers; the raid kills Healers first, then Elites (the owner's marks first). Casters stop on Magic Reflection, melee on + // Damage Shield. He surrenders when all eight adds are dead. + // The adds' casts go first for the kickers: Shadow Bolt (Healer) and Fireball (Elite) were interrupted four times in 95 s (n38). + r.interruptFirst.push_back(21077); + r.interruptFirst.push_back(20420); + // Flamewaker Elite: Blast Wave 20229 hits everyone within about 10 yards for 1100-1300 (n38: seven raiders dead in 3 s, hunters, + // rogues, a healer and a warrior beside the tanks holding the Elites). Casters, hunters and healers keep 13 yards from them. + r.avoidEnemy.push_back({ 11664, 13.0f, Who::Ranged }); + r.avoidEnemy.push_back({ 11664, 13.0f, Who::Healer }); + r.tankOrder.push_back(12018); + r.tankOrder.push_back(11664); + r.tankOrder.push_back(11663); // The brain already refuses to hit an add under either shield (Raid::kMagicReflection / kDamageShield) but nothing took // them off, so the raid stood idle for up to 30 s per cast. Priests and shamans purge them (Election::Assign purge). r.purge.push_back({ 20619 }); // Magic Reflection (classic_boss_majordomo_executus.cpp:50) r.purge.push_back({ 21075 }); // Damage Shield (classic_boss_majordomo_executus.cpp:51) r.priority.push_back({ 11664, 4 }); // Flamewaker Elite (MCRaidPolicy.h:100) r.priority.push_back({ 11663, 5 }); // Flamewaker Healer (MCRaidPolicy.h:99) - r.crowdControl.push_back({ 11663, CcKind::Polymorph, 21087 }); // humanoid; skip once Immunity 21087 is on it (mc/boss_majordomo_executus.cpp:47,179) + // No raid-chosen sheep here: the owner marks the Healers and gives each to a mage; skull moves onto them in turn (n71). // RAGNAROS - boss 11502 // Submerged phase: it ends early when every Son of Flame is banished (mc/boss_ragnaros.cpp:347-363). diff --git a/src/modules/PlayerbotV2/Bot/Raid/RaidEncounterData_MC_Movement.cpp b/src/modules/PlayerbotV2/Bot/Raid/RaidEncounterData_MC_Movement.cpp index 1f2b28cf49..a917fb9e0f 100644 --- a/src/modules/PlayerbotV2/Bot/Raid/RaidEncounterData_MC_Movement.cpp +++ b/src/modules/PlayerbotV2/Bot/Raid/RaidEncounterData_MC_Movement.cpp @@ -1,6 +1,6 @@ #include "RaidEncounters.h" -// Ported from Karrz's raid10-revamp ike3 bots (the ike3-based playerbot code). Script references (mc/..., bwl/..., ony/...) point at the +// Ported from Karrz's raid10-revamp ike3 bots (Karrz1/wow-1.12). Script references (mc/..., bwl/..., ony/...) point at the // VMaNGOS scripts that Forever's scripts/Custom/Classic instances were ported from; the ids are the same. namespace Playerbot::Raid { @@ -9,12 +9,47 @@ namespace Playerbot::Raid { void RegisterMoltenCoreMovement(RaidRules& r) { // Living Bomb (Baron Geddon): the carrier runs from the group, everybody else keeps clear of the carrier. - r.carrierRun.push_back({ 20475, 16.0f, Who::Anyone }); - r.avoidCarrier.push_back({ 20475, 14.0f, Who::Anyone }); + // Living Bomb: the Explosion (20476, 3200 fire) reaches radius index 19 = 18 yards from the carrier plus the victim's combat reach (~19.5), + // not the 10 the old values assumed: three casters 26-28 y from Geddon died to one in mc_geddon on 09a8ff07 because the carrier + // could only get 13-15 y from the nearest raider. The carrier runs until 20 y clear; the raid keeps 20 y from a carrier. + r.carrierRun.push_back({ 20475, 20.0f, Who::Anyone }); + r.avoidCarrier.push_back({ 20475, 20.0f, Who::Anyone }); + // The Explosion hits its carrier too, for the full 3200: a caster under 3200 health dies of its own bomb however far it runs (MC Geddon + // 2026-10-13 5b31e3df: Mcmagec, 29 y from Geddon and clear of the raid, killed by 3200 with 50 over). Vanilla raids drank Greater Fire + // Protection for Geddon; the 1350 absorb is what carries a 3100-health caster through it. + r.resistPotion.push_back({ 12056, 13457, Who::Anyone }); + // The boss-wide order above is eaten by the first Inferno before the next bomb lands, so a carrier drinks its own the moment the + // bomb is on it. + r.carrierPotion.push_back({ 20475, 13457 }); // Inferno (Baron Geddon, rooted for 8 seconds): everybody leaves his range from the cast start until the aura ends. // The damage spell 19698 reaches 20 yards (spell data); 26 gives a bot a still-moving margin, since the first ticks are // light (500) and the last (5000) kill (MC Geddon 2026-10-11: the 22 y circle left bots at 16-21 y to the end). - r.avoidEnemyAura.push_back({ 12056, 19695, 26.0f, Who::Anyone }); + r.avoidEnemyAura.push_back({ 12056, 19695, 24.0f, Who::Anyone }); + // The spell reaches 20 yards from his centre plus the victim's combat reach (WorldObject::IsInRange2d: ~21.5), and the circle above opens + // only when the cast starts, with the heaviest ticks (4000-5000) five seconds in: casters and healers stand outside it all fight, as + // vanilla raids do, so only the melee run out. MC Geddon 2026-10-12 b0a1c616: 27 Inferno deaths at 12-21 y, 14 of them in one tick, all + // "raid:move" - the ranged block stood 22 y behind the tank, which is 13-20 y from Geddon, and was still running when the ticks landed. + // The ranged / healer slot rows are measured from the circle's centre (the boss), not from the tank, and start outside radius + hazard + // margin (RaidRangedApproachTank), so the circle and the stand slots are the same number. Heal range to the tank is 40 y. + r.avoidEnemy.push_back({ 12056, 24.0f, Who::Ranged }); + r.avoidEnemy.push_back({ 12056, 24.0f, Who::Healer }); + // Threat resets and teleports that leave the boss on a non-tank: Lucifron, Magmadar (Panic), Gehennas, Shazzrah (Gate), Ragnaros (Wrath + // 20566 runs ResetThreatList, boss_ragnaros.cpp:198). A tank taunts the boss back at once; with no one in melee reach he casts Magma Blast + // (6000 fire, range unlimited) on whoever holds threat: three casters died to it in the last fight. Geddon, Garr, Golemagg and Sulfuron are + // on the list too: a boss that walks onto a mage takes the whole raid with it (mc_geddon 09a8ff07: Geddon on a mage 6 s in, loose in the + // casters' block when Inferno came, 8 dead). + for (uint32_t boss : { 12118u, 11982u, 12259u, 12264u, 11502u, 12056u, 12057u, 11988u, 12098u }) + r.retaunt.push_back(boss); + // Ragnaros: Elemental Fire (20564, 2400 fire a tick for 8 s) is reapplied by every swing on the current victim. The tank who carries it + // hands over to a clean one (taunt 10 s), so each tank takes one application per turn; the holder with it stops attacking while a clean + // tank exists. Everyone drinks Greater Fire Protection when he is engaged: Might of Ragnaros (21154, a random mana user) puts a Flame + // of Ragnaros under its target whose Intense Heat (21155) deals 2000 fire to everyone within 20 y, which killed nine healers and casters in + // one hit (MC Ragnaros 2026-10-13 d5753b04) - the raid cannot stand 20 y apart from a random caster, the absorb is the answer. + r.tankSwap.push_back({ 11502, 20564, 1 }); + r.resistPotion.push_back({ 11502, 13457, Who::Anyone }); + // Ragnaros' Lava Burst (21908) puts a trap (game object 178088, spell 21158: 1000 fire to the one who triggers it, radius 3.5) under the + // raid for 3 s. Everybody but the tanks (who must stay in his melee reach) steps off it. + r.avoidGameObject.push_back({ 178088, 5.0f, Who::NonTank }); // Gehennas: Rain of Fire ground effects. r.avoidGroundEffect.push_back({ 12259, 19717, 3.0f, Who::Anyone }); // Magmadar: Lava Bomb 19411 / 20474 makes the target summon a fire patch (Summon Lava Bomb 20494 / 20495, 30 / 60 s). @@ -22,10 +57,11 @@ namespace Playerbot::Raid { // 181742 is the later "small" patch, kept in case the 1.14 client data summons it. r.avoidGameObject.push_back({ 177704, 7.0f, Who::Anyone }); r.avoidGameObject.push_back({ 181742, 5.0f, Who::Anyone }); - // Magmadar's tactic (Karrz 2026-10-10): the main tank takes him to the far side from the raid, so he turns his back on + // Magmadar's tactic (playtest 2026-10-10): the main tank takes him to the far side from the raid, so he turns his back on // everybody else (his frontal attacks, Lava Bomb victims and Panic runners then do not start at the raid), and the raid // stands in the 140-degree sector behind him. Melee at his heels, casters and healers further back but well inside heal range. r.faceAway.push_back({ 11982 }); + r.faceAway.push_back({ 12018 }); // Majordomo: his tank stands on the far side from the raid, away from the adds r.standBehind.push_back({ 11982, Who::Melee, 3.0f, 7.0f, 80.0f }); r.standBehind.push_back({ 11982, Who::Ranged, 18.0f, 26.0f, 70.0f }); r.standBehind.push_back({ 11982, Who::Healer, 18.0f, 26.0f, 70.0f }); @@ -46,6 +82,9 @@ namespace Playerbot::Raid { // Garr: the Firesworn carry Separation Anxiety (23487, mc/boss_garr.cpp:105): an add that strays from Garr is punished. // The tanks holding them keep within 30 yards of Garr (a tank further out walks back toward him). r.stayNear.push_back({ 12057, 30.0f, Who::Tank }); + // Ragnaros: both tanks stand in his melee reach, so the one that takes him over after Wrath (a knockback and a threat reset) is already + // there and the one thrown back walks straight in again. n32 mc_ragnaros: tanks stood about 22 y out in Elemental Fire for seconds. + r.stayNear.push_back({ 11502, 8.0f, Who::Tank }); // Golemagg: main tank holds him at the tank camp, the off tank drags the Core Ragers to the far camp, healers stand between. r.stand.push_back({ 11988, Who::MainTank, 795.73f, -994.88f, -207.19f, 6.0f, true, 0 }); r.stand.push_back({ 11988, Who::OffTank, 846.65f, -1019.06f, -198.98f, 6.0f, true, 11672 }); diff --git a/src/modules/PlayerbotV2/Bot/Raid/RaidEncounterData_NAXX.cpp b/src/modules/PlayerbotV2/Bot/Raid/RaidEncounterData_NAXX.cpp index 067fb80a8e..da8198d874 100644 --- a/src/modules/PlayerbotV2/Bot/Raid/RaidEncounterData_NAXX.cpp +++ b/src/modules/PlayerbotV2/Bot/Raid/RaidEncounterData_NAXX.cpp @@ -38,7 +38,7 @@ namespace Playerbot::Raid { r.avoidGroundEffect.push_back({ 15953, 28794, 3.0f, Who::Anyone }); r.priority.push_back({ 16505, 3 }); // Naxxramas Follower (classic_boss_faerlina.cpp:53): silence, charge // Worshippers are the enrage counter: after each Enrage 28798 a priest mind-controls one and sacrifices it with Widow's - // Embrace 28732 on her (RaidMechanics_Naxx.cpp). They have no AI; never a DPS target. + // Embrace 28732 on her (RaidMechanics_Naxx.cpp). They have no bot logic; never a DPS target. r.priority.push_back({ 16506, -1 }); // --------------------------------------------------------------------------------------------------------------- diff --git a/src/modules/PlayerbotV2/Bot/Raid/RaidEncounterData_ONY.cpp b/src/modules/PlayerbotV2/Bot/Raid/RaidEncounterData_ONY.cpp index 02866a69b9..477e44bf02 100644 --- a/src/modules/PlayerbotV2/Bot/Raid/RaidEncounterData_ONY.cpp +++ b/src/modules/PlayerbotV2/Bot/Raid/RaidEncounterData_ONY.cpp @@ -1,6 +1,6 @@ #include "RaidEncounters.h" -// Ported from Karrz's raid10-revamp ike3 bots (the ike3-based playerbot code). Script references (mc/..., bwl/..., ony/...) point at the +// Ported from Karrz's raid10-revamp ike3 bots (Karrz1/wow-1.12). Script references (mc/..., bwl/..., ony/...) point at the // VMaNGOS scripts that Forever's scripts/Custom/Classic instances were ported from; the ids are the same. namespace Playerbot::Raid { @@ -19,9 +19,22 @@ namespace Playerbot::Raid { r.name = "Onyxia's Lair"; r.bosses = { 10184 }; + // Knock Away (19633) every 15-30 s takes 25 percent of her victim's threat (classic_boss_onyxia.cpp ModifyThreatByPercent -25). The + // raid held at 100 percent of the tank's, so every cut put the mages at 133 percent and she turned on one (n8 run 1: a Taunt every + // 9-12 s, her facing swinging the melee cones with it). + r.threatDrop.push_back({ 10184, 25.0f }); + // Whelps die to a single AoE tick but several at once overwhelm healers; the Warders sit in the egg pit and are respawned // when Onyxia aggroes (ony/boss_onyxia.cpp:298-302) - they are not part of the kill. - r.priority.push_back({ 11262, 2 }); // Onyxian Whelp: above Onyxia (default 1) because she cannot be reached in phase 2 (ony/boss_onyxia.cpp:70,479) + // Phase 2 (65..40 percent) she flies and only ranged can reach her; in n24 run 2 every DPS (casters and hunters included) went + // to the whelps and she sat at 57-61 percent from 121 s to 333 s while the waves stacked. Ranged DPS stay on her; the melee and an + // AoE share of the casters (every second one by guid) take the whelps. Tanks and everyone outside phase 2 rank the whelps above + // her (a landed Onyxia in phase 1 and 3 is the tank's, the whelps are the adds). First matching entry wins. + r.priority.push_back({ 11262, 2, Who::Tank, 10184, 65.0f, 40.0f }); // tanks pick up the whelps while she flies + r.priority.push_back({ 11262, 2, Who::Melee, 10184, 65.0f, 40.0f }); + r.priority.push_back({ 11262, 0, Who::NonTank, 10184, 65.0f, 40.0f }); // below Onyxia (1): the rest stay on her + r.priority.push_back({ 11262, 2, Who::Anyone, 10184, 100.0f, 65.0f }); + r.priority.push_back({ 11262, 2, Who::Anyone, 10184, 40.0f, 0.0f }); r.priority.push_back({ 12129, 0 }); // Onyxian Warder: below Onyxia, never chased (ony/boss_onyxia.cpp:71,298-302) // Phase 2 Fireball (18392) is cast at her current victim and the victim changes every cast (ony/boss_onyxia.cpp:461-466); @@ -31,20 +44,99 @@ namespace Playerbot::Raid { r.spread.push_back({ 10184, 8.0f, Who::Ranged, 65.0f, 40.0f }); // UNVERIFIED radius (spell 18392 area not in the scripts) r.spread.push_back({ 10184, 8.0f, Who::Healer, 65.0f, 40.0f }); // UNVERIFIED radius - // Deep Breath (phase 2, boss_onyxia.cpp:512-538): she casts the path spell of her CURRENT waypoint on herself, turns to face the - // opposite waypoint (m_uiMovePoint + 4), waits 5s, then flies there at speed rate 3.0 (:448-462). The path spells' target positions - // (comment block at the end of the file) run along that straight line, 89-90 yards between the waypoints (:106-116) and out to - // the cave wall. Corridor = 10 yd behind her position, 95 yd ahead along her facing. Half width 14 is UNVERIFIED (the trigger - // spells' radius is not in the scripts); the points along the paths are 7-12 yd apart. - for (uint32_t spell : { 17086u, 18351u, 18576u, 18609u, 18564u, 18584u, 18596u, 18617u }) - r.avoidBreath.push_back({ 10184, spell, 14.0f, 95.0f, Who::Anyone }); + // Deep Breath (phase 2, boss_onyxia.cpp:512-538): she casts the path spell of her CURRENT waypoint on herself (5 s cast), then flies + // to the opposite waypoint at speed rate 3.0. The spell's chained triggers (250 ms apart, 20 steps) land on fixed points along the + // line between the two waypoints, whatever her position and facing: the script starts the breath where its timer runs out, often + // mid-flight. onyxia_full n31 runs 5 and 6: she stood at -8.7,-216.5 facing east, the old corridor (taken from her position and + // facing) ran east, the breath ran west along the north-south line and killed 16 of 40 both times; every death sat within 31 y of + // that line. So the corridor is the segment between the two waypoints of the cast spell (ClassicOnyxMoveData in + // classic_boss_onyxia.cpp), half width 34. The hall is about 70 y across, the safe ground is the two cave mouths at its sides. + struct BreathPath { uint32_t spell; float ax, ay, bx, by; }; + static constexpr BreathPath kPaths[] = + { + { 17086u, 22.8763f, -217.152f, -65.8444f, -213.809f }, // north to south + { 18351u, -65.8444f, -213.809f, 22.8763f, -217.152f }, // south to north + { 18576u, -31.4963f, -250.123f, -33.5561f, -182.682f }, // east to west + { 18609u, -33.5561f, -182.682f, -31.4963f, -250.123f }, // west to east + { 18564u, -63.5156f, -240.096f, 6.8951f, -180.246f }, // south-east to north-west + { 18584u, 6.8951f, -180.246f, -63.5156f, -240.096f }, // north-west to south-east + { 18596u, -58.2509f, -189.020f, 10.2191f, -247.912f }, // south-west to north-east + { 18617u, 10.2191f, -247.912f, -58.2509f, -189.020f }, // north-east to south-west + }; + for (BreathPath const& path : kPaths) + r.avoidBreath.push_back({ 10184, path.spell, 34.0f, 0.0f, Who::Anyone, false, true, path.ax, path.ay, path.bx, path.by }); // Phase 1 on the ground: Flame Breath 18435, Wing Buffet 18500 and Cleave 19983 hit the front, Tail Sweep 15847 the back // (classic_boss_onyxia.cpp:20-25). Only the tank stands in front, nobody stands behind her; melee and casters take the - // flanks. The cones skip her while she flies (phase 2), where her facing changes at every waypoint. Cone angles and - // lengths are from the classic tooltips, UNVERIFIED (the spell radii are client data, not in the scripts). - r.avoidFrontal.push_back({ 10184, 25.0f, 45.0f, Who::NonTank }); - r.avoidFrontal.push_back({ 10184, 15.0f, 80.0f, Who::NonTank, 180.0f }); + // flanks. The cones skip her while she flies (phase 2), where her facing changes at every waypoint. Lengths are the spells' radii + // from the spell audit (research/pc-2026-10-11/SpellAudit.tsv): Flame Breath 45 y (3500 fire, 2 s cast), Tail Sweep 30 y (800), + // Wing Buffet 20 y. The cone angle (45 degrees either side) is still the engine's default for a front cone, UNVERIFIED. + // onyxia_full n17 2026-10-14: casters died to hits of 2000-3900 from 19-38 y away, outside the 25 y this rule had. + r.avoidFrontal.push_back({ 10184, 45.0f, 45.0f, Who::NonTank, 0.0f, 100.0f, 0.0f, false }); + r.avoidFrontal.push_back({ 10184, 30.0f, 80.0f, Who::NonTank, 180.0f, 100.0f, 0.0f, false }); + + // Where to stand for each breath, the AzerothCore bots' safe zones (mod-playerbots Ai/Raid/Ony/OnyActions.h): two points per breath, + // 32-53 y off its line, at the hall's ends. A member inside a corridor walks to the nearer one. + struct SafeSpot { uint32_t spell; float x1, y1, x2, y2; }; + static constexpr SafeSpot kSafe[] = + { + { 17086u, -10.0f, -180.0f, -20.0f, -250.0f }, { 18351u, -10.0f, -180.0f, -20.0f, -250.0f }, + { 18576u, 20.0f, -210.0f, -75.0f, -210.0f }, { 18609u, 20.0f, -210.0f, -75.0f, -210.0f }, + { 18564u, -60.0f, -195.0f, 10.0f, -240.0f }, { 18584u, -60.0f, -195.0f, 10.0f, -240.0f }, + { 18596u, 7.0f, -185.0f, -60.0f, -240.0f }, { 18617u, 7.0f, -185.0f, -60.0f, -240.0f }, + }; + for (SafeSpot const& s : kSafe) + { + r.breathSafe.push_back({ 10184, s.spell, s.x1, s.y1 }); + r.breathSafe.push_back({ 10184, s.spell, s.x2, s.y2 }); + } + + // Greater Fire Protection Potion for everyone: Deep Breath (1500 fire a tick) cannot be left on its north-south and south-north lines, where the + // corridor covers the width of the hall (n71 live 2026-10-15: two such breaths killed 35 of 40, the raid found no way out in the west half). + r.resistPotion.push_back({ 10184, 13457, Who::Anyone }); + + // The tank holds her on the far side from the raid, so her front (Flame Breath, Wing Buffet, Cleave) points at the wall and not at the + // raiders. One step to the far side, then it stays: the tank's spot lies due east of her (bearing 0, the back of the lair; the raid enters from the west), so + // there is no repeated turning. The cone-triggered turn of AvoidFrontal is off for her (tankTurns false: n57 run 1, the tank turned her + // every 9 s and the ranged re-positioned each time). Phases 1 and 3; in phase 2 she flies. + r.faceAway.push_back({ 10184, 100.0f, 65.0f, 0.0f }); + r.faceAway.push_back({ 10184, 40.0f, 0.0f, 0.0f }); + + // Melee DPS stand on her flank, in the wedge between the front cones (45 degrees) and the tail sweep (everything behind, from 90): + // 55..85 degrees off her facing, 3-8 yards out. Phases 1 and 3 only; she flies in phase 2 (the rule skips a flying enemy too). + // Onyxia n7 2026-10-14: six melee DPS died to one tail sweep at 19 s while alternating "leave cone" and attack. + r.standFlank.push_back({ 10184, Who::Melee, 2.0f, 9.0f, 70.0f, 20.0f, 100.0f, 65.0f }); + r.standFlank.push_back({ 10184, Who::Melee, 2.0f, 9.0f, 70.0f, 20.0f, 40.0f, 0.0f }); + + // Each bot has its own slot in the wedge (RaidBrain 3d: the matching members on its side share a grid of rows and columns) and that is + // the only position rule for it in phases 1 and 3; healers take the inner band (20-26 y), ranged the outer one (26-34 y), melee 2-9 y. + // Ranged DPS and healers take the same side wedges, out of Wing Buffet (20 y) and the tail sweep, 22-30 y from her. Her facing follows + // whoever she is hitting; with the ranged massed on one bearing a single Flame Breath (45 y) took ten of them at once, in the first + // minute of n38 run 5 (all ten stood 48-68 degrees off her facing, 8-30 y out) and in a dozen breaths of run 6's phase 3, where the + // whole raid stood round her. In the wedges only the side she turns to is exposed, and the other side is clear. Phases 1 and 3. + r.standFlank.push_back({ 10184, Who::Ranged, 26.0f, 34.0f, 70.0f, 20.0f, 100.0f, 65.0f }); + r.standFlank.push_back({ 10184, Who::Ranged, 26.0f, 34.0f, 70.0f, 20.0f, 40.0f, 0.0f }); + r.standFlank.push_back({ 10184, Who::Healer, 20.0f, 26.0f, 70.0f, 20.0f, 100.0f, 65.0f }); + r.standFlank.push_back({ 10184, Who::Healer, 20.0f, 26.0f, 70.0f, 20.0f, 40.0f, 0.0f }); + + // The two cave alcoves (-30.1,-254.5 and -30.8,-177.1, ony/boss_onyxia.cpp whelp spawn points) are out of bounds: static whelps lie in + // them, and raiders sent there (the off-tanks stood 6 y inside each mouth, the casters' AoE share behind them) and raiders pushed there by + // a flank, spacing or dodge move pulled out dozens of whelps, 38 loose at 3 min (n58 live 2026-10-15). No move target may end within + // 22 y of either centre; the whelps the script sends out come to the raid, which fights them where it stands. + r.keepOut.push_back({ 10184, -30.1f, -254.5f, 22.0f }); + r.keepOut.push_back({ 10184, -30.8f, -177.1f, 22.0f }); + + // Phase 2 range. In n50 run 1 she went 56% -> 54% in 36 s with 20 DPS "hitting": the ranged stood 54-78 y from her (dps_idle_reason + // "target out of range" with the flying Onyxia, moving=1 for whole minutes) and the casters on the whelp share ran 36-71 y after + // whelps at the far cave. She flies a ring and moves every 15-25 s, so the ranged that work on her follow her to within 20 y on the + // ground (about 30 y with her 20 y altitude, the casters' range). + r.stayNear.push_back({ 10184, 20.0f, Who::Ranged, 65.0f, 40.0f }); + + // The floor cracks of phase 3: the lair's two lava trap game objects, 177984 (16.8,-225.1) and 177985 (-28.1,-190.7), both spawned in + // our world data on map 249 and declared (GO_LAVATRAP_1/2) in the VMaNGOS boss_onyxia.cpp; nobody stands within 8 y of one. The radius is + // UNVERIFIED (the template's trap radius was not in the data we could read). + r.avoidGameObject.push_back({ 177984, 8.0f, Who::Anyone }); + r.avoidGameObject.push_back({ 177985, 8.0f, Who::Anyone }); // Left out on purpose (needs engine support or coordinates the scripts do not give): // - Bellowing Roar fear (18431): no dispel (fear), tremor totem / fear ward is a buff decision. diff --git a/src/modules/PlayerbotV2/Bot/Raid/RaidEncounters.cpp b/src/modules/PlayerbotV2/Bot/Raid/RaidEncounters.cpp index 439c7ab33f..24e1e421d0 100644 --- a/src/modules/PlayerbotV2/Bot/Raid/RaidEncounters.cpp +++ b/src/modules/PlayerbotV2/Bot/Raid/RaidEncounters.cpp @@ -30,12 +30,10 @@ std::map>& Registry() auto onyxia = std::make_unique(); onyxia->name = "Onyxia's Lair"; RegisterOnyxia(*onyxia); - // Onyxia's breath comes out of the front on the ground phases. - onyxia->avoidFrontal.push_back({ 10184, 40.0f, 45.0f, Who::NonTank }); - // Tail Sweep 15847 behind her (classic_boss_onyxia.cpp): melee stand at her sides. - onyxia->avoidFrontal.push_back({ 10184, 20.0f, 45.0f, Who::NonTank, 180.0f }); - // Phase 3 Bellowing Roar 18431: AoE fear, dispelled off whoever a dispeller can reach. - onyxia->dispel.push_back({ 18431, DispelKind::Magic }); + // Her frontal cones (Flame Breath, Tail Sweep) are in RegisterOnyxia; a second copy here made the tank turn her again. + // Phase 3 Bellowing Roar: AoE fear, dispelled off whoever a dispeller can reach. This core casts 22686 (classic_boss_onyxia.cpp:53; + // vanilla 18431 is not in the 1.60 client), so the old 18431 rule never matched. No order when the data gives it no dispel type. + onyxia->dispel.push_back({ 22686, DispelKind::Magic }); rules[249] = std::move(onyxia); auto aq40 = std::make_unique(); @@ -86,10 +84,45 @@ bool NoTank(uint32_t mapId, uint32_t entry) return rules && std::find(rules->noTank.begin(), rules->noTank.end(), entry) != rules->noTank.end(); } +uint32_t TankOrder(uint32_t mapId, uint32_t entry) +{ + RaidRules const* rules = RulesForMap(mapId); + if (!rules) + return UINT32_MAX; + auto const it = std::find(rules->tankOrder.begin(), rules->tankOrder.end(), entry); + return it == rules->tankOrder.end() ? UINT32_MAX : uint32_t(it - rules->tankOrder.begin()); +} + +bool TankLast(uint32_t mapId, uint32_t entry) +{ + RaidRules const* rules = RulesForMap(mapId); + return rules && std::find(rules->tankLast.begin(), rules->tankLast.end(), entry) != rules->tankLast.end(); +} + +bool Retaunts(uint32_t mapId, uint32_t entry) +{ + RaidRules const* rules = RulesForMap(mapId); + return rules && std::find(rules->retaunt.begin(), rules->retaunt.end(), entry) != rules->retaunt.end(); +} + +float ThreatShareAfterDrop(RaidRules const& rules, uint32_t entry) +{ + for (ThreatDrop const& rule : rules.threatDrop) + if (rule.enemy == entry) + return std::clamp(1.0f - rule.percent / 100.0f, 0.1f, 1.0f); + return 1.0f; +} + +float ThreatShareAfterDrop(uint32_t mapId, uint32_t entry) +{ + RaidRules const* rules = RulesForMap(mapId); + return rules ? ThreatShareAfterDrop(*rules, entry) : 1.0f; +} + int PriorityFor(RaidRules const& rules, uint32_t entry) { for (Priority const& rule : rules.priority) - if (rule.enemy == entry) + if (rule.enemy == entry && rule.who == Who::Anyone && !rule.gateEnemy) return rule.value; return 1; } @@ -102,7 +135,7 @@ std::vector KillOrder(uint32_t mapId) return order; std::vector ranked; for (Priority const& rule : rules->priority) - if (rule.value >= 2) + if (rule.value >= 2 && rule.who == Who::Anyone && !rule.gateEnemy) ranked.push_back(rule); std::stable_sort(ranked.begin(), ranked.end(), [](Priority const& a, Priority const& b) { return a.value > b.value; }); for (Priority const& rule : ranked) diff --git a/src/modules/PlayerbotV2/Bot/Raid/RaidEncounters.h b/src/modules/PlayerbotV2/Bot/Raid/RaidEncounters.h index 230dff77c7..b3320d5e7a 100644 --- a/src/modules/PlayerbotV2/Bot/Raid/RaidEncounters.h +++ b/src/modules/PlayerbotV2/Bot/Raid/RaidEncounters.h @@ -1,6 +1,6 @@ // RaidEncounters — data-driven raid encounter rules for the bots. // -// Ported from Karrz's raid10-revamp ike3 playerbots (the ike3-based playerbot code, +// Ported from Karrz's raid10-revamp ike3 playerbots (Karrz1/wow-1.12, // src/game/PlayerBots/playerbot/strategy/generic/RaidEncounters.h). Forever's // raids run the Classic ports of the VMaNGOS scripts (scripts/Custom/Classic), // so the creature entries and spell ids carry over unchanged. @@ -37,7 +37,8 @@ enum class Who : uint8_t Healer, ManaUser, // anybody with a mana bar (Kel'Thuzad's Detonate Mana) Caster, // ranged DPS that deal spell damage (not hunters) - Physical // DPS that deal physical damage: melee and hunters + Physical, // DPS that deal physical damage: melee and hunters + AoeShare // every second caster (by guid): the share of the ranged DPS that a rule hands to an area-damage job }; enum class DispelKind : uint8_t { Magic, Curse, Poison, Disease }; @@ -57,7 +58,10 @@ struct CarrierRun { uint32_t aura; float clearDistance; Who who = Who::NonTank; // Frontal cone (breath, Wing Buffet, Shadow Flame, cleaves): matching bots stay out of the sector in front of that is // yards deep and degrees either side of where it faces. Use Who::NonTank so the tank keeps the boss. // facingOffsetDeg turns the cone: 180 is a tail sweep behind the enemy. -struct AvoidFrontal { uint32_t enemy; float radius; float halfAngleDeg; Who who; float facingOffsetDeg = 0.0f; float hpMax = 100.0f; float hpMin = 0.0f; }; +// tankTurns: when three or more non-tanks stand in the cone, the tank holding the enemy steps to the far side of it to turn it away from the raid +// (Magmadar). Off for a boss whose raid stands on fixed flank wedges (Onyxia): there the turn sends her breath across the wedges, the whole +// ranged group has to re-position each time, and onyxia_full n57 run 1 saw the main tank do it every 9 s for four minutes (1880 "leave cone" steps). +struct AvoidFrontal { uint32_t enemy; float radius; float halfAngleDeg; Who who; float facingOffsetDeg = 0.0f; float hpMax = 100.0f; float hpMin = 0.0f; bool tankTurns = true; }; // Ground effects created by through (dynamic objects such as Rain of Fire): stay out of them, plus . struct AvoidGroundEffect { uint32_t enemy; uint32_t spell; float margin; Who who; }; @@ -71,12 +75,17 @@ struct AvoidGameObject { uint32_t entry; float radius; Who who; }; struct AvoidCreature { uint32_t entry; float radius; Who who; bool corpse = false; }; // While is alive and fighting, matching bots keep at least from the nearest other raid member. +// No raid move ends inside this circle while is alive and fighting (one clamp for every rule, applied to the finished move target in +// RaidBrain). Onyxia's two cave alcoves: the static whelps lie there, and a bot that walks up to them pulls the lot. +struct KeepOut { uint32_t enemy; float x, y, radius; }; + struct Spread { uint32_t enemy; float radius; Who who; float hpMax = 100.0f; float hpMin = 0.0f; }; // Matching bots go to (x,y,z) and hold within while is alive and fighting. // needOtherEnemy: when not 0, this other entry must also be alive and fighting (e.g. Golemagg's Core Ragers). // needVictimIsMe: only when the enemy is attacking this bot - the creature when one is given, else . -struct Stand { uint32_t enemy; Who who; float x, y, z; float tolerance; bool needVictimIsMe; uint32_t needOtherEnemy; float hpMax = 100.0f; float hpMin = 0.0f; }; +struct Stand { uint32_t enemy; Who who; float x, y, z; float tolerance; bool needVictimIsMe; uint32_t needOtherEnemy; float hpMax = 100.0f; float hpMin = 0.0f; + uint8_t share = 0; }; // share 1 / 2: only the even / odd numbered of the members this rule matches (by guid order), so one rule list can split e.g. the off-tanks between two posts // While is alive and fighting, a member carrying stands yards from the enemy's live position // along the fixed world bearing (radians) and holds within (Thaddius' Positive / Negative Charge @@ -103,7 +112,15 @@ struct CrowdControl { uint32_t enemy; CcKind kind; uint32_t skipIfAura; uint32_t // Kill order: higher value first. Entries not listed use the default priority 1. Negative = never a DPS target // (tanks may still hold it, e.g. Golemagg's Core Ragers). Priority >= 2 feeds the group's synchronized kill focus. -struct Priority { uint32_t enemy; int value; }; +// who / gateEnemy / hpMax / hpMin make an entry conditional: it applies only to matching bots, and, when gateEnemy is not 0, only while a +// living enemy of that entry is inside the health window (Onyxia's whelps outrank her for the melee in phase 2, not for the casters). +// The first matching entry per enemy wins, so list the specific ones first. Only unconditional entries feed the synchronized kill focus. +struct Priority { uint32_t enemy; int value; Who who = Who::Anyone; uint32_t gateEnemy = 0; float hpMax = 100.0f; float hpMin = 0.0f; }; + +// A boss that cuts its tank's threat on a schedule (Onyxia's Knock Away: -25 percent on its victim). Non-tank damage holds at the +// remaining share of the tank's threat, so the cut leaves the tank level with the raid and never under it: a ranged bot only needs +// 130 percent of the holder's threat to take the boss, melee 110. +struct ThreatDrop { uint32_t enemy; float percent; }; // Do not use area damage while this enemy is alive within 40 yards (adds that explode or must not be pulled). struct NoAoe { uint32_t enemy; }; @@ -122,7 +139,20 @@ struct AvoidEnemy { uint32_t enemy; float radius; Who who; float hpMax = 100.0f; // it as an aura), or is flying at >= 2.5x run speed (the breath pass itself), the corridor is latched for about 10 seconds: it // starts 10 yards behind the enemy's position and facing at that moment, runs yards straight ahead and is // yards either side of the centre line. Matching bots leave it. -struct AvoidBreath { uint32_t enemy; uint32_t castSpell; float halfWidth; float length; Who who; }; +// : the enemy also counts as breathing while it hovers in the air, standing still with no target. Onyxia's script clears +// her target and waits 5 s facing the far waypoint before the pass (classic_boss_onyxia.cpp DoMovement); the path spell is cast +// triggered on herself at that moment and is neither an aura nor a current spell by the time a bot ticks (Onyxia wipe 2026-10-13: +// 33 of 40 stood in the corridor, no bot moved), so the wind-up is the only warning before the speed-3 pass. +// fixedPath: the corridor is the segment (ax,ay)-(bx,by) in world coordinates, unused, and it opens only while casts +// (or carries it): the spell's chained triggers land on fixed points, whatever the caster's position and facing. Onyxia's script starts +// the breath wherever her movement timer runs out, mid-flight, so a corridor taken from her position and facing pointed the wrong way +// (onyxia_full n31 runs 5 and 6: she stood at -8.7,-216.5 facing east, the breath ran west, 16 raiders died in each). +// Fixed standing points out of one breath spell's corridor (the AzerothCore bots' per-breath safe zones): a member inside the +// corridor of walks to the nearest of these instead of searching for a way out. +struct BreathSafe { uint32_t enemy; uint32_t castSpell; float x, y; }; + +struct AvoidBreath { uint32_t enemy; uint32_t castSpell; float halfWidth; float length; Who who; bool windup = false; + bool fixedPath = false; float ax = 0.0f, ay = 0.0f, bx = 0.0f, by = 0.0f; }; // Melee soak (Patchwerk's Hateful Strike hits the highest-health player in melee among his top four on threat): up to // matching bots (never the main tank) keep attacking in melee so the strike lands on them instead of a DPS. @@ -158,13 +188,34 @@ struct StayNear { uint32_t enemy; float radius; Who who; float hpMax = 100.0f; f // While is alive and a tank holds it, that tank stands on the far side of the enemy from the raid (the line from the // raid's centre through the enemy, at melee range), so the enemy turns its back on everybody else (Magmadar). The raid's centre // is the mean position of the non-tank members within 60 yards. A tank that already opposes the raid within 30 degrees stays. -struct FaceAway { uint32_t enemy; float hpMax = 100.0f; float hpMin = 0.0f; }; +// bearingDeg (when not kNoBearing): the world bearing from the enemy to the tank's spot, instead of the line from the raid's centre. Onyxia: east, +// the back of the lair, wherever the raid stands (the raid enters from the west and spreads; a bearing taken from where it stood at the pull +// put the tank on the wrong side once the raid moved). +constexpr float kNoBearing = 1000.0f; +struct FaceAway { uint32_t enemy; float hpMax = 100.0f; float hpMin = 0.0f; float bearingDeg = kNoBearing; }; // While is alive and fighting, matching bots stand in the sector behind it: either side of the line // straight behind where it faces, between and yards. A bot outside walks to the nearest such spot on its // own side. Pair with FaceAway so the tank decides which way "behind" is. struct StandBehind { uint32_t enemy; Who who; float minDist; float maxDist; float halfAngleDeg; float hpMax = 100.0f; float hpMin = 0.0f; }; +// While is alive and fighting (in the hp window), matching bots stand on its flank: either side of the line +// off where it faces, on the side they are already on, between and yards. For a boss that hits the +// front (breath, Wing Buffet, Cleave) and the whole back half (Tail Sweep): melee reach it from the flank wedge between the two cones +// (Onyxia: centre 70, half 15, so 55..85 degrees off her facing; the tail sweep starts at 90). Uses her live facing, so the tank keeps +// her still; a bot already inside the wedge does not move, so there is no leave / come back cycle. +struct StandFlank { uint32_t enemy; Who who; float minDist; float maxDist; float centerDeg; float halfAngleDeg; float hpMax = 100.0f; float hpMin = 0.0f; }; + +// A resistance potion a matching bot drinks when is engaged, without the global Playerbot.Raid.ResistPotions switch (Ragnaros' +// Elemental Fire: 2400 a tick on the tank, five tank deaths in three minutes, MC 2026-10-12). The kit stocks it (Classic::RaidConsumable::combat). +// Only Who::Tank and Who::Anyone are read. +struct ResistPotion { uint32_t enemy; uint32_t item; Who who; }; + +// A member that gains in this raid drinks at once, whoever it is and whatever the boss order says: the aura is a hit that +// kills the carrier or the carrier's neighbours and the absorb is what carries it (Living Bomb: 3200 fire to the carrier, a caster under +// 3200 health dies of its own bomb). The boss-wide ResistPotion order is spent by the first Inferno before the next bomb lands. +struct CarrierPotion { uint32_t aura; uint32_t item; }; + // Phase windows (hpMax / hpMin on AvoidFrontal, Spread, Stand, AvoidEnemy, StayNear): the rule only applies while the enemy's // health percent is within [hpMin, hpMax] (Onyxia's Fireball spread is phase 2: 65..40). Defaults 100 / 0 = always. @@ -181,6 +232,7 @@ struct RaidRules std::vector avoidCreature; std::vector avoidFrontal; std::vector spread; + std::vector keepOut; std::vector stand; std::vector standByAura; std::vector dispel; @@ -191,6 +243,7 @@ struct RaidRules std::vector tankSwap; std::vector avoidEnemy; std::vector avoidBreath; + std::vector breathSafe; std::vector meleeSoak; std::vector controlledMember; std::vector onlyAttackers; @@ -200,8 +253,15 @@ struct RaidRules std::vector stayNear; std::vector faceAway; std::vector standBehind; + std::vector standFlank; + std::vector resistPotion; + std::vector carrierPotion; + std::vector retaunt; // bosses whose threat a Blink, a fear or a threat reset (Ragnaros' Wrath) can leave on a non-tank: a tank taunts them back at once (ElectRetaunt) + std::vector threatDrop; // bosses that cut their tank's threat on a schedule (ThreatDropFraction) std::vector noDispel; // auras nobody removes (removing them hurts: Wyvern Sting, Mutating Injection) std::vector noTank; // summoned adds the DPS burns down: tanks hold every other mob first and never count them as a roster need + std::vector tankOrder; // mobs the tanks take in this order, first listed first (Majordomo: Healers, then Elites); unlisted mobs come after + std::vector tankLast; // a mob the tanks take only when no other free mob is left (Majordomo: he does little damage and cannot die) std::vector interruptFirst; // casts the PvE coordinator's kick election takes before any other (heals, sheep) }; @@ -220,6 +280,21 @@ bool InterruptFirst(uint32_t mapId, uint32_t spell); // tank such a mob only when no other engaged mob is free, and the tank roster does not grow for it. bool NoTank(uint32_t mapId, uint32_t entry); +// RaidRules::tankOrder: the position of in the map's tank order (0 = first), or UINT32_MAX when it is not listed. +uint32_t TankOrder(uint32_t mapId, uint32_t entry); + +// True when the map's rules list in RaidRules::tankLast. +bool TankLast(uint32_t mapId, uint32_t entry); + +// True when the map's rules list as a boss whose threat a scripted reset or a Blink can leave on a non-tank (RaidRules::retaunt): a +// tank taunts it back at once, so the raid's wait for that tank is short. +bool Retaunts(uint32_t mapId, uint32_t entry); + +// The share of its tank's threat that stays after 's scheduled threat cut (ThreatDrop), 1.0 when the map's rules list none. Non-tank +// damage holds at this share of the tank's threat on that boss (EvaluateThreatHold). +float ThreatShareAfterDrop(uint32_t mapId, uint32_t entry); +float ThreatShareAfterDrop(RaidRules const& rules, uint32_t entry); + // Rule-based kill priority for an enemy entry (default 1 when no rule exists). int PriorityFor(RaidRules const& rules, uint32_t entry); diff --git a/src/modules/PlayerbotV2/Bot/Raid/RaidHealGroups.h b/src/modules/PlayerbotV2/Bot/Raid/RaidHealGroups.h index 06c09c6913..87c3603e96 100644 --- a/src/modules/PlayerbotV2/Bot/Raid/RaidHealGroups.h +++ b/src/modules/PlayerbotV2/Bot/Raid/RaidHealGroups.h @@ -1,6 +1,6 @@ // RaidHealGroups - which raid subgroup each triage healer looks after first. Pure; tested in tests/game/ClassicRaidHealGroups.cpp. // -// Karrz, live MC 2026-10-10: when a warlock Life Taps, druids, priests and paladins all put HoTs and heals on him. Every triage healer +// the owner, live MC 2026-10-10: when a warlock Life Taps, druids, priests and paladins all put HoTs and heals on him. Every triage healer // picked the lowest member of the whole raid, so the whole raid's healers piled onto the same few members. Now each raid subgroup has // one healer who heals it first (RaidHealGroups.h -> PveOrder::heal_groups -> ClassicHeal::PickPatient); the tank healers keep their // tanks (RaidHealSlots.h) and are not in this plan. @@ -20,6 +20,7 @@ namespace Playerbot::Raid { // Under this mana a healer is out of the plan (its groups are covered by the others) until it recovers. constexpr int kHealGroupOutManaPct = 10; +constexpr int kHealGroupBackManaPct = 20; // a healer that dropped out returns above this struct GroupHealer { @@ -39,9 +40,15 @@ inline std::map AssignHealGroups(std::vector co { std::map result; std::vector avail; + // A healer already in the plan stays in down to kHealGroupOutManaPct; one that left needs kHealGroupBackManaPct to return, so a healer + // whose mana hovers at the mark does not drop out and rejoin on every plan (groups moving between healers each time). for (GroupHealer const& h : healers) - if (h.mana_pct >= kHealGroupOutManaPct) + { + auto const had = previous.find(h.id); + bool const in_plan = had != previous.end() && had->second != 0; + if (h.mana_pct >= (in_plan ? kHealGroupOutManaPct : kHealGroupBackManaPct)) avail.push_back(h.id); + } if (avail.empty() || groups.empty()) return result; std::sort(avail.begin(), avail.end()); diff --git a/src/modules/PlayerbotV2/Bot/Raid/RaidHealStats.h b/src/modules/PlayerbotV2/Bot/Raid/RaidHealStats.h index 3bc2c66cab..dd236ae829 100644 --- a/src/modules/PlayerbotV2/Bot/Raid/RaidHealStats.h +++ b/src/modules/PlayerbotV2/Bot/Raid/RaidHealStats.h @@ -1,5 +1,5 @@ // Per-healer heal casts of the current raid pull, for the [raid_encounter] pull end line ("healer throughput"). -// Written by the heal emitter (AI worker threads), read and reset by the raid brain. +// Written by the heal emitter (bot worker threads), read and reset by the raid brain. #pragma once #include "Define.h" diff --git a/src/modules/PlayerbotV2/Bot/Raid/RaidIncoming.h b/src/modules/PlayerbotV2/Bot/Raid/RaidIncoming.h new file mode 100644 index 0000000000..a469a86b2f --- /dev/null +++ b/src/modules/PlayerbotV2/Bot/Raid/RaidIncoming.h @@ -0,0 +1,106 @@ +// Damage the raid took in the current pull, by the creature that dealt it and by whether the victim was a tank, printed as [raid_incoming] +// lines at the pull end. The healers' mana is the raid's incoming damage: this says where it came from, so that what a tank or a rule could +// have kept away from the cloth members is visible (n24 mc_garr: 7 deaths, all to Firesworn melee on mages and healers, but no log said how +// much of the healing went there). +// Written from the world thread by the damage hook; the raid brain registers the roles and reads it. +#pragma once + +#include "Define.h" +#include +#include +#include +#include +#include + +namespace Playerbot::Raid { + +namespace detail { +struct IncomingRow { std::string name; uint64 tank = 0; uint64 other = 0; uint32 hits_tank = 0; uint32 hits_other = 0; }; +inline std::mutex g_incMu; +inline std::unordered_map g_incRole; // watched victim -> is a tank +inline std::unordered_map g_incRows; // attacker creature entry +struct DealtRow { std::string name; uint64 damage = 0; uint32 hits = 0; }; +inline std::unordered_map g_dealtRows; // enemy creature entry the raid hit +} // namespace detail + +inline void IncomingReset() +{ + std::lock_guard lk(detail::g_incMu); + detail::g_incRole.clear(); + detail::g_incRows.clear(); + detail::g_dealtRows.clear(); +} + +inline void IncomingWatch(uint64 victim_low, bool tank) +{ + std::lock_guard lk(detail::g_incMu); + detail::g_incRole[victim_low] = tank; +} + +// A creature hit a player for . +inline void IncomingHit(uint32 entry, char const* name, uint64 victim_low, uint32 damage) +{ + std::lock_guard lk(detail::g_incMu); + auto const role = detail::g_incRole.find(victim_low); + if (role == detail::g_incRole.end()) + return; + auto& row = detail::g_incRows[entry]; + if (row.name.empty() && name) + row.name = name; + if (role->second) { row.tank += damage; ++row.hits_tank; } + else { row.other += damage; ++row.hits_other; } +} + +// A watched raider dealt to the creature . +inline void DealtHit(uint32 entry, char const* name, uint64 attacker_low, uint32 damage) +{ + std::lock_guard lk(detail::g_incMu); + if (!detail::g_incRole.count(attacker_low)) + return; + auto& row = detail::g_dealtRows[entry]; + if (row.name.empty() && name) + row.name = name; + row.damage += damage; + ++row.hits; +} + +// What the raid hit, biggest first: the answer to "where did the damage go" (n32 mc_majordomo: 221k dealt, the adds at 89-99 %). +inline std::vector DealtTake(uint32 duration_s, size_t max_rows = 10) +{ + std::lock_guard lk(detail::g_incMu); + std::vector> rows(detail::g_dealtRows.begin(), detail::g_dealtRows.end()); + std::sort(rows.begin(), rows.end(), [](auto const& a, auto const& b) { return a.second.damage > b.second.damage; }); + uint32 const secs = std::max(duration_s, 1u); + std::vector out; + for (auto const& [entry, r] : rows) + { + if (out.size() >= max_rows) + break; + out.push_back(r.name + " (" + std::to_string(entry) + ") took " + std::to_string(r.damage) + " in " + std::to_string(r.hits) + " hits (" + + std::to_string(r.damage / secs) + "/s)"); + } + detail::g_dealtRows.clear(); + return out; +} + +// The biggest sources first (by total), at most ; clears the table. +inline std::vector IncomingTake(uint32 duration_s, size_t max_rows = 8) +{ + std::lock_guard lk(detail::g_incMu); + std::vector> rows(detail::g_incRows.begin(), detail::g_incRows.end()); + std::sort(rows.begin(), rows.end(), [](auto const& a, auto const& b) { return a.second.tank + a.second.other > b.second.tank + b.second.other; }); + uint32 const secs = std::max(duration_s, 1u); + std::vector out; + for (auto const& [entry, r] : rows) + { + if (out.size() >= max_rows) + break; + out.push_back(r.name + " (" + std::to_string(entry) + ") on non-tanks " + std::to_string(r.other) + " in " + std::to_string(r.hits_other) + + " hits (" + std::to_string(r.other / secs) + "/s), on tanks " + std::to_string(r.tank) + " in " + std::to_string(r.hits_tank) + " hits"); + } + detail::g_incRole.clear(); + detail::g_incRows.clear(); + return out; +} + +} // namespace Playerbot::Raid diff --git a/src/modules/PlayerbotV2/Bot/Raid/RaidManaLedger.h b/src/modules/PlayerbotV2/Bot/Raid/RaidManaLedger.h new file mode 100644 index 0000000000..9c4ee98819 --- /dev/null +++ b/src/modules/PlayerbotV2/Bot/Raid/RaidManaLedger.h @@ -0,0 +1,193 @@ +// Per-healer mana ledger of the current raid pull, printed as [mana_ledger] lines at the pull end next to the "healers that cast" line. +// What each healer paid per spell (the core's own cost, taken when the cast completes), what the heals it sent were estimated at against +// what landed (overheal), the mana that came back in and out of the five second rule (Classic 1.60: spirit regeneration stops for 5 s +// after mana is paid, ClassicManaRegen.h) and the potions, runes and Innervate used. +// +// Written from the world thread by the core hooks (OnSpellCast, OnHeal) and the raid brain's sampler; the heal emitter adds its estimate +// from the bot workers, so the table is locked. +#pragma once + +#include "Define.h" +#include +#include +#include +#include +#include +#include + +namespace Playerbot::Raid { + +namespace detail { + +struct ManaSpellRow { uint32 casts = 0; int64 mana = 0; }; +struct ManaRestoreRow { uint32 uses = 0; int64 nominal = 0; }; + +struct ManaEntry +{ + std::string name; + uint32 max_mana = 0; + uint32 first_mana = 0; + uint32 min_mana = 0; + uint32 last_mana = 0; + uint32 last_sample_ms = 0; + uint32 last_spend_ms = 0; // game ms of the last paid cast + bool sampled = false; + int64 pending_spent = 0; // paid since the last sample + int64 pending_restore = 0; // nominal item / spell restores since the last sample + int64 regen_in = 0; // mana gained while the five second rule ran + int64 regen_out = 0; // mana gained outside it + uint32 ms_in = 0; + uint32 ms_out = 0; + int64 heal_est = 0; // sum of the estimates of the heals sent + uint32 heals_sent = 0; + int64 heal_effective = 0; // healing that landed (OnHeal, effective gain only) + std::map spells; + std::map restores; +}; + +inline std::mutex g_manaMu; +inline std::unordered_map g_mana; +inline std::unordered_map g_manaFreeSeen; // healers whose free cast was already explained in this pull + +} // namespace detail + +// A group member that can heal is watched from now on (the raid brain calls this every tick of a pull). +// / are its mana, the game time in ms. +inline void ManaLedgerSample(uint64 guid_low, std::string const& name, uint32 cur, uint32 max, uint32 now_ms) +{ + if (max == 0) + return; + std::lock_guard lk(detail::g_manaMu); + auto& e = detail::g_mana[guid_low]; + if (!e.sampled) + { + e.name = name; + e.max_mana = max; + e.first_mana = e.min_mana = e.last_mana = cur; + e.last_sample_ms = now_ms; + e.sampled = true; + e.pending_spent = e.pending_restore = 0; + return; + } + uint32 const dt = now_ms - e.last_sample_ms; + int64 const gained = std::max(0, int64(cur) - int64(e.last_mana) + e.pending_spent - e.pending_restore); + bool const inside = now_ms - e.last_spend_ms < 5000u; + if (inside) { e.regen_in += gained; e.ms_in += dt; } + else { e.regen_out += gained; e.ms_out += dt; } + e.min_mana = std::min(e.min_mana, cur); + e.last_mana = cur; + e.last_sample_ms = now_ms; + e.pending_spent = e.pending_restore = 0; +} + +// One spell of a watched healer completed and cost mana (0 for a free spell). +inline void ManaLedgerCast(uint64 guid_low, uint32 spell, int32 cost, uint32 now_ms) +{ + std::lock_guard lk(detail::g_manaMu); + auto it = detail::g_mana.find(guid_low); + if (it == detail::g_mana.end() || !it->second.sampled) + return; + auto& row = it->second.spells[spell]; + ++row.casts; + if (cost > 0) + { + row.mana += cost; + it->second.pending_spent += cost; + it->second.last_spend_ms = now_ms; + } +} + +// A potion, rune or Innervate () restored about mana to a watched healer. +inline void ManaLedgerRestore(uint64 guid_low, uint32 spell, int32 nominal) +{ + std::lock_guard lk(detail::g_manaMu); + auto it = detail::g_mana.find(guid_low); + if (it == detail::g_mana.end() || !it->second.sampled) + return; + auto& row = it->second.restores[spell]; + ++row.uses; + row.nominal += nominal; + it->second.pending_restore += nominal; +} + +// The heal emitter sent a heal it estimated at . +inline void ManaLedgerHealSent(uint64 guid_low, float est) +{ + std::lock_guard lk(detail::g_manaMu); + auto it = detail::g_mana.find(guid_low); + if (it == detail::g_mana.end() || !it->second.sampled) + return; + ++it->second.heals_sent; + it->second.heal_est += int64(est); +} + +// A heal of a watched healer landed for (effective, overheal already removed by the core). +inline void ManaLedgerHealLanded(uint64 guid_low, uint32 gain) +{ + std::lock_guard lk(detail::g_manaMu); + auto it = detail::g_mana.find(guid_low); + if (it == detail::g_mana.end() || !it->second.sampled) + return; + it->second.heal_effective += gain; +} + +inline bool ManaLedgerWatching(uint64 guid_low) +{ + std::lock_guard lk(detail::g_manaMu); + auto it = detail::g_mana.find(guid_low); + return it != detail::g_mana.end() && it->second.sampled; +} + +inline void ManaLedgerReset() +{ + std::lock_guard lk(detail::g_manaMu); + detail::g_mana.clear(); + detail::g_manaFreeSeen.clear(); +} + +// True the first time per pull for a healer: the caller then logs why a spell that has a mana cost was charged nothing. +inline bool ManaLedgerFirstFree(uint64 guid_low) +{ + std::lock_guard lk(detail::g_manaMu); + return detail::g_manaFreeSeen.try_emplace(guid_low, true).second; +} + +// One line per healer that sent a heal, cleared on return. turns a spell id into text. +template +inline std::vector ManaLedgerTake(uint32 duration_s, NameFn&& spell_name) +{ + std::lock_guard lk(detail::g_manaMu); + std::vector rows; + for (auto const& [g, e] : detail::g_mana) + if (e.heals_sent > 0 || !e.spells.empty()) + rows.push_back(&e); + std::sort(rows.begin(), rows.end(), [](detail::ManaEntry const* a, detail::ManaEntry const* b) { return a->name < b->name; }); + std::vector out; + uint32 const secs = std::max(duration_s, 1u); + for (detail::ManaEntry const* e : rows) + { + int64 spent = 0; + for (auto const& [id, r] : e->spells) + spent += r.mana; + int64 restored = 0; + for (auto const& [id, r] : e->restores) + restored += r.nominal; + int const over = e->heal_est > 0 ? int(100 - std::min(100, e->heal_effective * 100 / e->heal_est)) : 0; + std::string line = e->name + " mana " + std::to_string(e->first_mana * 100u / e->max_mana) + "%->" + + std::to_string(e->last_mana * 100u / e->max_mana) + "% (low " + std::to_string(e->min_mana * 100u / e->max_mana) + + "%) spent " + std::to_string(spent) + " (" + std::to_string(spent / secs) + "/s) heals " + std::to_string(e->heals_sent) + + " est " + std::to_string(e->heal_est) + " landed " + std::to_string(e->heal_effective) + " overheal~" + std::to_string(over) + + "% | regen in 5sr " + std::to_string(e->regen_in) + " over " + std::to_string(e->ms_in / 1000u) + "s, out " + + std::to_string(e->regen_out) + " over " + std::to_string(e->ms_out / 1000u) + "s | items+innervate " + + std::to_string(restored) + " |"; + for (auto const& [id, r] : e->spells) + line += " " + spell_name(id) + " x" + std::to_string(r.casts) + "=" + std::to_string(r.mana); + for (auto const& [id, r] : e->restores) + line += " +" + spell_name(id) + " x" + std::to_string(r.uses) + "=" + std::to_string(r.nominal); + out.push_back(std::move(line)); + } + detail::g_mana.clear(); + return out; +} + +} // namespace Playerbot::Raid diff --git a/src/modules/PlayerbotV2/Bot/Raid/RaidMechanics_BWL.cpp b/src/modules/PlayerbotV2/Bot/Raid/RaidMechanics_BWL.cpp index 00e30009f8..f382214a75 100644 --- a/src/modules/PlayerbotV2/Bot/Raid/RaidMechanics_BWL.cpp +++ b/src/modules/PlayerbotV2/Bot/Raid/RaidMechanics_BWL.cpp @@ -61,8 +61,20 @@ void ElectRazorgoreOrb(Election& e, uint32_t now) for (Unit* enemy : plan.enemies) if (enemy->GetEntry() == kRazorgore) raz = enemy->ToCreature(); - if (!raz || !raz->IsInCombat()) + if (!raz) return; + // The orb works from the start of the encounter: once the raid is fighting (the guards, or Razorgore himself), a click on the orb + // makes Razorgore engage the controller (go_orbe_domination). Until then nobody touches him, so waiting for him to be in combat + // would let a raid that pulls the guards first attack him with the eggs still standing. + if (!raz->IsInCombat()) + { + bool fighting = false; + for (Member const& m : plan.members) + if (m.p->IsInCombat() && m.p->GetExactDist2d(raz) < 120.f) + fighting = true; + if (!fighting) + return; + } std::list eggs; raz->GetGameObjectListWithEntryInGrid(eggs, kBlackDragonEgg, 250.0f); diff --git a/src/modules/PlayerbotV2/Bot/Raid/RaidMechanics_Naxx.cpp b/src/modules/PlayerbotV2/Bot/Raid/RaidMechanics_Naxx.cpp index 6e0cd0420f..344a87e16d 100644 --- a/src/modules/PlayerbotV2/Bot/Raid/RaidMechanics_Naxx.cpp +++ b/src/modules/PlayerbotV2/Bot/Raid/RaidMechanics_Naxx.cpp @@ -380,8 +380,8 @@ uint32_t CastingMindControl(Player* p, ObjectGuid& target) if (Spell* cast = p->GetCurrentSpell(CURRENT_GENERIC_SPELL)) if (cast->GetSpellInfo() && std::find(kMindControl.begin(), kMindControl.end(), cast->GetSpellInfo()->Id) != kMindControl.end()) { - if (Unit* t = cast->m_targets.GetUnitTarget()) - target = t->GetGUID(); + if (ObjectGuid const guid = cast->m_targets.GetUnitTargetGUID(); !guid.IsEmpty()) + target = guid; // by GUID: the spell's object pointer can dangle between map updates return cast->GetSpellInfo()->Id; } return 0; @@ -492,7 +492,7 @@ constexpr uint32_t kFaerlinaRage = 28798; // Enrage, every 60 s constexpr uint32_t kWidowsEmbrace = 28732; // removes the enrage and blocks the next one and her volley for 30 s // Faerlina: once she enrages, a priest mind-controls a Naxxramas Worshipper and makes it cast Widow's Embrace on her -// (naxx/classic_boss_faerlina.cpp SpellHit; the worshipper has no AI of its own, the spell is its template spell). +// (naxx/classic_boss_faerlina.cpp SpellHit; the worshipper has no bot logic of its own, the spell is its template spell). // Sacrificing after the enrage, not before, buys the full minute. void ElectFaerlina(Election& e) { diff --git a/src/modules/PlayerbotV2/Bot/Raid/RaidRoster.h b/src/modules/PlayerbotV2/Bot/Raid/RaidRoster.h index f534882162..f626019b14 100644 --- a/src/modules/PlayerbotV2/Bot/Raid/RaidRoster.h +++ b/src/modules/PlayerbotV2/Bot/Raid/RaidRoster.h @@ -1,6 +1,6 @@ // RaidRoster - the raid's tank and healer quota, filled from companions that have no role yet. // -// A 40-player raid needs about one healer in three and four tanks, and Karrz's companions are mostly paladins and druids +// A 40-player raid needs about one healer in three and four tanks, and the owner's companions are mostly paladins and druids // whose role was never set (OwnerRegistry::DeclaredRole == Unknown). PlanRaidRoles picks which of those take a healer or // tank role so the raid has its quota; a role anyone gave (the owner's /setrole, a stored inference) is never changed. // Pure: no game types, tested in tests/game/ClassicRaidRoster.cpp. diff --git a/src/modules/PlayerbotV2/Bot/RaidFight.h b/src/modules/PlayerbotV2/Bot/RaidFight.h index f2a2eaf66f..4ca5e92777 100644 --- a/src/modules/PlayerbotV2/Bot/RaidFight.h +++ b/src/modules/PlayerbotV2/Bot/RaidFight.h @@ -1,5 +1,5 @@ // RaidFight - the small decisions that decide whether a raid bot fights or walks, as plain functions so they are tested without a world -// (tests/game/ClassicRaidFight.cpp). Live MC 2026-10-11 (Karrz: "half of the bots aren't fighting", about 15 casters and hunters at full mana +// (tests/game/ClassicRaidFight.cpp). Live MC 2026-10-11 (the owner: "half of the bots aren't fighting", about 15 casters and hunters at full mana // doing nothing): the owner's Attack never released the DPS when the marked mob was still idle, and ranged DPS kept walking to their // formation slot with the target 5-15 y away in line of sight. diff --git a/src/modules/PlayerbotV2/Bot/RecipeDifficulty.h b/src/modules/PlayerbotV2/Bot/RecipeDifficulty.h index db480c6d58..3a7928d02e 100644 --- a/src/modules/PlayerbotV2/Bot/RecipeDifficulty.h +++ b/src/modules/PlayerbotV2/Bot/RecipeDifficulty.h @@ -1,5 +1,5 @@ // RecipeDifficulty - Per-recipe skill-color resolver. One-time index built at -// module init from sSkillLineAbilityStore so AI rules can ask "is this recipe +// module init from sSkillLineAbilityStore so bot logic rules can ask "is this recipe // orange/yellow/green/gray for my current skill?" in O(1) without re-scanning // the dbc on every tick. diff --git a/src/modules/PlayerbotV2/Bot/RezClaims.h b/src/modules/PlayerbotV2/Bot/RezClaims.h index e10801870c..266b90e247 100644 --- a/src/modules/PlayerbotV2/Bot/RezClaims.h +++ b/src/modules/PlayerbotV2/Bot/RezClaims.h @@ -30,7 +30,7 @@ inline bool IsRezSpell(uint32 spell) return false; } -// [raid_rez] effects (Karrz, MC 2026-10-10: the rez casts spend their mana and never offer anything, and neither the SPELL_EFFECT_RESURRECT / +// [raid_rez] effects (playtest, MC 2026-10-10: the rez casts spend their mana and never offer anything, and neither the SPELL_EFFECT_RESURRECT / // RESURRECT_WITH_AURA cast-state log nor the core's rez logs ever printed, so the Classic rez spells carry another effect): once per // process, the effect ids and targets of every vanilla rez rank as the core loaded them. Called by the first rez cast and by the first raid // rez evaluation, so a scenario shows it without a death. diff --git a/src/modules/PlayerbotV2/Bot/RezRule.h b/src/modules/PlayerbotV2/Bot/RezRule.h index dc28fa436e..e9f04aed57 100644 --- a/src/modules/PlayerbotV2/Bot/RezRule.h +++ b/src/modules/PlayerbotV2/Bot/RezRule.h @@ -1,5 +1,5 @@ // RezRule - who may resurrect, and when, in a group fight. Plain functions so they are tested without a world -// (tests/game/ClassicRezRule.cpp). Raid rules (Karrz, MC 2026-10-10): only a druid (Rebirth) may raise someone while the fight is on; +// (tests/game/ClassicRezRule.cpp). Raid rules (playtest, MC 2026-10-10): only a druid (Rebirth) may raise someone while the fight is on; // a priest, paladin or shaman waits until it is over, and one rezzer takes each corpse. #pragma once diff --git a/src/modules/PlayerbotV2/Bot/States/Rules/AmbientRules.cpp b/src/modules/PlayerbotV2/Bot/States/Rules/AmbientRules.cpp index 9cedf63750..baaf3e6a70 100644 --- a/src/modules/PlayerbotV2/Bot/States/Rules/AmbientRules.cpp +++ b/src/modules/PlayerbotV2/Bot/States/Rules/AmbientRules.cpp @@ -25,6 +25,12 @@ #include "Bot/DeathHotspots.h" #include "Bot/States/MaintainHelpers.h" // States::ChunkedWalkToward #include "Travel/QuestHubDatabase.h" +#include "Travel/TownNpcIndex.h" +#include "Bot/TownLife.h" +#include "Bot/BotRegistry.h" +#include "Fleet/OwnerRegistry.h" +#include "Util.h" +#include "Config.h" #include "Bot/World/ZonePicker.h" #include "GameTime.h" #include "UnitDefines.h" // UNIT_NPC_FLAG_FLIGHTMASTER / _QUESTGIVER @@ -176,18 +182,32 @@ bool PvpHelpCalloutFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView c return true; } +// Playerbot.World.TownLife (default 1): the shows below and the level-gated LFG yells. Read once at start. +bool TownLifeEnabled() +{ + static bool const on = sConfigMgr->GetBoolDefault("Playerbot.World.TownLife", true); + return on; +} + // ---------- idle:yell_lfg ---------- +// A solo bot in a rested area (town / inn) now and then calls for a group. The level-60 bots call for any group; a bot of a dungeon's +// level names that dungeon, but only a few take part at a time. Nothing here forms a group: a bot joins one only when a real player +// invites it (the invite rules), so a dungeon is never run by bots alone and costs no RAM until a player asks for it. bool YellLfgGate(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const&,uint32) { if (s.in_group()) return false; - if (s.level() < 60) return false; - if (s.raw().identity.rest_bonus_xp <= 0) return false; + if (s.level() < 13) return false; + if (s.has_owner_character()) return false; + // A rested place: the rested pool fills in inns and cities, but a level-60 bot has none, so a capital counts as well. + if (s.raw().identity.rest_bonus_xp <= 0 && !::Playerbot::V2::World::IsVanillaCapitalZone(s.zone_id())) return false; if (ai.personality().verbosity == Verbosity::Silent) return false; if (s.is_moving() || s.in_combat() || s.is_casting()) return false; if (s.raw().movement.is_mounted) return false; - constexpr uint32 kYellThrottleMs = 45u * 60u * 1000u; const uint32 yell_now_ms = s.published_at_ms(); + // Below level 60 only a share of the bots call at a time (a different set every 45 minutes). + if (s.level() < 60 && (!TownLifeEnabled() || !V2::TownLife::TakesPart(s.bot_id(), 3u, yell_now_ms, 15u, kYellThrottleMs))) return false; + if (ai.last_yell_lfg_ms() == 0) { const uint32 stagger = (s.bot_id() * 9173u) % kYellThrottleMs; @@ -206,18 +226,18 @@ bool YellLfgFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const&,B const uint32 yell_now_ms = s.published_at_ms(); constexpr char const* kTankYells[] = { "Tank LFG, msg me!", - "Looking for heroic group, can tank.", - "Tank for hire, dungeons or M+.", + "Looking for a group, can tank.", + "Tank here, any dungeon, whisper me.", }; constexpr char const* kHealerYells[] = { "Healer LFG.", - "Looking for group to heal, dungeon or raid.", + "Looking for a group to heal, whisper me.", "Healer available, msg me for runs.", }; constexpr char const* kDpsYells[] = { "DPS LFG.", "Looking for any group.", - "Hi! Anyone running content tonight?", + "Hi! Anyone running a dungeon tonight?", "lfg, can do most stuff.", }; constexpr uint32 kTankSize = sizeof(kTankYells) / sizeof(kTankYells[0]); @@ -232,7 +252,16 @@ bool YellLfgFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const&,B phrase = kHealerYells[sel_seed % kHealerSize]; else phrase = kDpsYells[sel_seed % kDpsSize]; - emit.yell_world(phrase); + // A bot of a dungeon's level names the dungeon. + std::string line = phrase; + if (s.level() < 60) + if (char const* dungeon = V2::TownLife::LfgDungeonFor(s.level(), sel_seed)) + { + char const* rolename = role == Role::Tank ? "tank" : role == Role::Healer ? "healer" : "dps"; + line = std::string("LFG ") + dungeon + ", " + rolename + " here. Whisper me!"; + } + V2::TownLife::Counters().lfg_calls.fetch_add(1, std::memory_order_relaxed); + emit.yell_world(line); ai.set_last_yell_lfg_ms(yell_now_ms); ai.set_last_rule_fired("idle:yell_lfg"); return true; @@ -704,6 +733,150 @@ bool LeaveWaterFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const hub->location.GetPositionZ(), "idle:leave_water", now_ms); } +// ---------- idle:inn_rest ---------- +// In a capital a share of the bots (most at night) walk to the nearest inn and sit there for a while. One check of the town NPC index +// per tick, only for the bots whose turn it is. +constexpr float kInnSearchYards = 150.0f; +constexpr float kInnStandYards = 5.0f; + +bool InnRestGate(BotSnapshotView const& s, BotAI&, GroupSnapshotView const&, uint32) +{ + if (!TownLifeEnabled()) return false; + if (!::Playerbot::V2::World::IsVanillaCapitalZone(s.zone_id())) return false; + int const hour = TimeBreakdown(GameTime::GetGameTime()).tm_hour; + if (!V2::TownLife::TakesPart(s.bot_id(), 1u, s.published_at_ms(), V2::TownLife::InnPercent(hour), 15u * 60u * 1000u)) return false; + if (!s.is_alive() || s.in_combat() || s.is_casting() || s.has_owner_character() || s.in_group()) return false; + if (s.is_in_instance() || s.is_in_dungeon() || s.in_battleground() || s.raw().movement.is_mounted) return false; + return s.enemies_within(40.0f) == 0 && !s.has_actionable_quest(); +} + +bool InnRestFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const&, BotIntentEmitter& emit, uint32 now_ms) +{ + float bx, by, bz; + s.position(bx, by, bz); + auto const* inn = ::Playerbot::V2::Travel::TownNpcIndex::Instance().Nearest( + s.map_id(), bx, by, bz, UNIT_NPC_FLAG_INNKEEPER, s.is_alliance(), kInnSearchYards); + if (!inn) return false; + // Stand a few yards from the innkeeper, on the side the bot comes from, so a crowd does not stack on one point. + float const dx = bx - inn->x, dy = by - inn->y, len = std::hypot(dx, dy); + float const ux = len > 0.5f ? dx / len : 1.0f, uy = len > 0.5f ? dy / len : 0.0f; + float const stand = kInnStandYards + float(s.bot_id() % 5u); + float const tx = inn->x + ux * stand, ty = inn->y + uy * stand; + if (std::hypot(bx - tx, by - ty) > 4.0f) + return States::ChunkedWalkToward(s, ai, emit, tx, ty, inn->z, "idle:inn_rest", now_ms); + V2::TownLife::Counters().inn_ticks.fetch_add(1, std::memory_order_relaxed); + if (s.is_moving()) return false; + emit.sit(); + ai.set_last_rule_fired("idle:inn_rest"); + return true; +} + +// ---------- idle:mailbox ---------- +// A few bots in a town walk to the nearest mailbox and stand there a while, then the window turns over and they go back to their errands. +// The share is picked per time window by hash, so nothing is stored per bot. +constexpr float kMailboxSearchYards = 120.0f; +constexpr float kMailboxStandYards = 2.5f; +constexpr uint32 kMailboxWindowMs = 90u * 1000u; + +bool MailboxGate(BotSnapshotView const& s, BotAI&, GroupSnapshotView const&, uint32) +{ + if (!TownLifeEnabled()) return false; + if (!::Playerbot::V2::World::IsVanillaCapitalZone(s.zone_id())) return false; + if (!V2::TownLife::TakesPart(s.bot_id(), 5u, s.published_at_ms(), 4u, kMailboxWindowMs)) return false; + if (!s.is_alive() || s.in_combat() || s.is_casting() || s.has_owner_character() || s.in_group()) return false; + if (s.is_in_instance() || s.is_in_dungeon() || s.in_battleground() || s.raw().movement.is_mounted) return false; + return s.enemies_within(40.0f) == 0 && !s.has_actionable_quest(); +} + +bool MailboxFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const&, BotIntentEmitter& emit, uint32 now_ms) +{ + float bx, by, bz; + s.position(bx, by, bz); + auto const* box = ::Playerbot::V2::Travel::TownNpcIndex::Instance().NearestMailbox(s.map_id(), bx, by, bz, kMailboxSearchYards); + if (!box) return false; + V2::TownLife::Counters().mailbox_ticks.fetch_add(1, std::memory_order_relaxed); + float const dx = bx - box->x, dy = by - box->y, len = std::hypot(dx, dy); + if (len > kMailboxStandYards + 1.5f) + { + float const ux = dx / len, uy = dy / len; + return States::ChunkedWalkToward(s, ai, emit, box->x + ux * kMailboxStandYards, box->y + uy * kMailboxStandYards, box->z, "idle:mailbox", now_ms); + } + if (s.is_moving()) return false; + ai.set_last_rule_fired("idle:mailbox"); + return true; +} + +// ---------- idle:town_duel ---------- +// A bot in a town challenges a nearby world bot of about its level (spell 7266, Duel); the other accepts (BotAI duel pact), the duel runs +// the usual way. A share of the bots take part, a pair at a time, at most once every 15 minutes per bot. +bool TownDuelGate(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const&, uint32) +{ + if (!TownLifeEnabled()) return false; + if (!V2::TownLife::TakesPart(s.bot_id(), 2u, s.published_at_ms(), 6u, 20u * 60u * 1000u)) return false; + if (!s.is_alive() || s.in_combat() || s.is_casting() || s.has_owner_character() || s.in_group()) return false; + if (s.is_in_instance() || s.is_in_dungeon() || s.in_battleground() || s.raw().movement.is_mounted || s.is_moving()) return false; + if (s.hp_pct() < 90 || s.level() < 6 || s.enemies_within(40.0f) > 0 || s.has_actionable_quest()) return false; + if (s.raw().social_events.has_duel_request || s.duel_in_progress()) return false; + uint32 const now = s.published_at_ms(); + if (ai.last_town_show_ms() && now - ai.last_town_show_ms() < 15u * 60u * 1000u) return false; + if (!V2::TownLife::TakesPart(s.bot_id(), 2u, now, 6u, 20u * 60u * 1000u)) return false; + float bx, by, bz; + s.position(bx, by, bz); + return ::Playerbot::V2::World::IsVanillaCapitalZone(s.zone_id()) + || ::Playerbot::V2::Travel::TownNpcIndex::Instance().CountNear(s.map_id(), bx, by, 60.0f, s.is_alliance(), 0xFFFFFFFFu) >= 3; +} + +bool TownDuelFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const&, BotIntentEmitter& emit, uint32) +{ + float bx, by, bz; + s.position(bx, by, bz); + for (auto const& u : s.nearby_friends()) + { + if (!u.is_player || u.is_in_group || u.hp <= 0 || u.max_hp <= 0) continue; + float const d = std::hypot(u.x - bx, u.y - by); + if (d < 6.0f || d > 25.0f) continue; + uint64 const other = u.guid.GetCounter(); + if (!Services::Registry().has(BotId(other)) || Services::Owners().GetOwner(BotId(other)).account_id != 0) continue; // a world bot only + int const other_hp = int((int64(u.hp) * 100) / u.max_hp); + if (!V2::TownLife::DuelPartners(s.level(), s.hp_pct(), u.level, other_hp, s.bot_id(), other)) continue; + uint32 const now = s.published_at_ms(); + V2::TownLife::PactSet(other, s.bot_id(), now); + emit.cast(7266u, u.guid); // Duel + V2::TownLife::Counters().duels.fetch_add(1, std::memory_order_relaxed); + ai.set_last_town_show_ms(now); + ai.set_last_rule_fired("idle:town_duel"); + return true; + } + return false; +} + +// ---------- idle:campfire ---------- +// Outdoors at night, a few bots that stand still light a campfire (Basic Campfire, 818); the usual ambient sit does the rest. +bool CampfireGate(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const&, uint32) +{ + if (!TownLifeEnabled()) return false; + if (!s.is_alive() || s.in_combat() || s.is_casting() || s.has_owner_character() || s.in_group() || s.is_moving()) return false; + if (s.is_in_instance() || s.is_in_dungeon() || s.in_battleground() || s.raw().movement.is_mounted || s.is_swimming()) return false; + if (s.enemies_within(40.0f) > 0 || !s.knows_spell(818u)) return false; + int const hour = TimeBreakdown(GameTime::GetGameTime()).tm_hour; + if (hour >= 6 && hour < 18) return false; + uint32 const now = s.published_at_ms(); + uint8 lo = 0, hi = 0; + if (!::Playerbot::V2::World::VanillaZoneLevelRange(s.zone_id(), lo, hi)) return false; // outdoors, not in a capital + if (ai.last_moving_ms() == 0 || now - ai.last_moving_ms() < 30u * 1000u) return false; // has stood still a while + if (ai.last_town_show_ms() && now - ai.last_town_show_ms() < 20u * 60u * 1000u) return false; + return V2::TownLife::TakesPart(s.bot_id(), 4u, now, 4u, 30u * 60u * 1000u); +} + +bool CampfireFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const&, BotIntentEmitter& emit, uint32) +{ + ai.set_last_town_show_ms(s.published_at_ms()); + emit.cast(818u); + V2::TownLife::Counters().campfires.fetch_add(1, std::memory_order_relaxed); + ai.set_last_rule_fired("idle:campfire"); + return true; +} + } // anonymous namespace void RegisterAmbientRules(IdleRuleRegistry& r) @@ -844,6 +1017,40 @@ void RegisterAmbientRules(IdleRuleRegistry& r) rule.min_interval_ms = 60000; r.register_rule(std::move(rule)); } + { + // Town life (Bot/TownLife.h): just above the rpg errands (110-135), so a bot whose turn it is does the show instead of strolling, and + // below upkeep, quests and travel. Each takes part only for a share of the bots. + IdleRule rule; + rule.name = "idle:inn_rest"; + rule.priority = 139; + rule.gate = &InnRestGate; + rule.fire = &InnRestFire; + r.register_rule(std::move(rule)); + } + { + IdleRule rule; + rule.name = "idle:mailbox"; + rule.priority = 138; + rule.gate = &MailboxGate; + rule.fire = &MailboxFire; + r.register_rule(std::move(rule)); + } + { + IdleRule rule; + rule.name = "idle:town_duel"; + rule.priority = 137; + rule.gate = &TownDuelGate; + rule.fire = &TownDuelFire; + r.register_rule(std::move(rule)); + } + { + IdleRule rule; + rule.name = "idle:campfire"; + rule.priority = 136; + rule.gate = &CampfireGate; + rule.fire = &CampfireFire; + r.register_rule(std::move(rule)); + } } } // namespace Playerbot diff --git a/src/modules/PlayerbotV2/Bot/States/Rules/ClassicUpkeepRules.cpp b/src/modules/PlayerbotV2/Bot/States/Rules/ClassicUpkeepRules.cpp index 3e1f4aedc2..3b0ad1c34a 100644 --- a/src/modules/PlayerbotV2/Bot/States/Rules/ClassicUpkeepRules.cpp +++ b/src/modules/PlayerbotV2/Bot/States/Rules/ClassicUpkeepRules.cpp @@ -17,6 +17,8 @@ // idle:classic_healthstone warlocks keep a healthstone in the bags inside // dungeons / raids (the dungeon hold swallows the // world idle:conjured_item there) +// idle:classic_mana_gem mages keep a conjured mana gem in the bags inside +// dungeons / raids // idle:classic_fear_ward dwarf priests keep Fear Ward on their raid tank // // The decisions live in Bot/ClassicUpkeep.cpp, shared with the vanilla @@ -52,6 +54,9 @@ bool UpkeepWindow(BotSnapshotView const& s, GroupSnapshotView const& g) if (!s.is_alive() || s.in_combat() || s.is_casting() || s.is_mounted() || s.on_transport() || s.raw().vehicle.on_vehicle || !s.victim().IsEmpty() || s.attackers_count() > 0) return false; + // The 992 band sits above the lava / drowning rules (900-865): get out of the hazard before any buff. + if (s.is_in_damaging_liquid() || s.is_swimming()) + return false; if (auto const* members = g.members()) for (GroupMemberSummary const& m : *members) if (m.in_combat && m.map_id == s.map_id()) @@ -218,6 +223,7 @@ bool RaidBuffsFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const& { ai.note_action_retry(BotAI::ActionKind::ClassUpkeep, b.key, now_ms); ai.note_buff_cast(b.key, now_ms); + Classic::NoteAreaBuffCast(s.guid(), b.key, b.area_needy, now_ms); } // [raid_support] why this class buff goes out (MC Garr 2026-10-10: the druids cast Mark of the Wild over and over): the target's // tracked buffs as the group snapshot sees them, once per caster and key per minute. @@ -412,6 +418,115 @@ bool HealthstoneFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView cons return true; } +// ---------- idle:classic_mana_gem ---------- +// A mage keeps a conjured mana gem in the bags inside dungeons / raids (the gem is the first mana item of the fight, and nothing +// conjured one: the mage branch of idle:conjured_item makes retail Refreshment). + +// A conjure that leaves no gem the bag scan recognises must not repeat for ever: after kGemAttemptCap casts without a gem the +// bot pauses kGemPauseMs, then gets a fresh set of attempts. +constexpr uint32 kGemAttemptCap = 3; +constexpr uint32 kGemPauseMs = 10 * 60 * 1000; + +struct GemTries { uint32 count = 0; uint32 pause_until = 0; }; + +std::mutex& GemTriesMutex() { static std::mutex m; return m; } +std::unordered_map& GemTriesTable() { static std::unordered_map t; return t; } + +bool GemMayTry(uint64 bot, uint32 now_ms) +{ + std::lock_guard lk(GemTriesMutex()); + auto it = GemTriesTable().find(bot); + if (it == GemTriesTable().end() || !it->second.pause_until) + return true; + if (static_cast(now_ms - it->second.pause_until) < 0) + return false; + GemTriesTable().erase(it); // pause over: fresh attempts + return true; +} + +void GemForget(uint64 bot) +{ + std::lock_guard lk(GemTriesMutex()); + GemTriesTable().erase(bot); +} + +// Counts a cast; returns true when it was the last attempt before the pause. +bool GemNoteCast(uint64 bot, uint32 now_ms) +{ + std::lock_guard lk(GemTriesMutex()); + GemTries& t = GemTriesTable()[bot]; + if (++t.count < kGemAttemptCap) + return false; + t.pause_until = now_ms + kGemPauseMs; + return true; +} + +bool ManaGemGate(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const& g, uint32 now_ms) +{ + if (!s.is_in_instance() || !UpkeepWindow(s, g) || s.is_moving() || s.is_casting() || s.recently_in_combat(5000)) + return false; + uint32 const create = Classic::CreateManaGemSpell(s); + if (!create) + return false; + if (Classic::HasManaGem(s)) + { + GemForget(s.guid().GetCounter()); // the conjure worked: forget earlier misses + return false; + } + return s.is_ready(create) + && V2::MayConjure(s.in_combat(), s.recently_in_combat(5000), s.power(POWER_MANA), s.mana_cost(create)) + && !ai.action_recently_tried(BotAI::ActionKind::ClassUpkeep, create, now_ms) + && GemMayTry(s.guid().GetCounter(), now_ms); +} +bool ManaGemFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const&, BotIntentEmitter& emit, uint32 now_ms) +{ + uint32 const create = Classic::CreateManaGemSpell(s); + if (!create || !emit.cast(create)) + return false; + ai.note_action_retry(BotAI::ActionKind::ClassUpkeep, create, now_ms); + if (GemNoteCast(s.guid().GetCounter(), now_ms)) + TC_LOG_INFO("playerbot.v2", "[supplies] {} cast mana gem spell {} {} times without a gem reaching the bags; pausing {} min", + s.name(), create, kGemAttemptCap, kGemPauseMs / 60000); + ai.set_last_rule_fired("idle:classic_mana_gem"); + return true; +} + +// ---------- idle:classic_conjure ---------- +// Mages: Conjure Water and Conjure Food when the conjured stock runs low, in instances (out in the world +// idle:conjured_item does it). The conjured items are drunk / eaten like any other (consumables are +// classified by their on-use spell). + +constexpr uint32 kConjureWaterBelow = 20; +constexpr uint32 kConjureFoodBelow = 10; + +uint32 PickConjure(BotSnapshotView const& s, BotAI& ai, uint32 now_ms) +{ + for (auto kind : { Classic::ConsumableKind::Drink, Classic::ConsumableKind::Food }) + { + uint32 const create = Classic::MageConjureSpell(s, kind, kind == Classic::ConsumableKind::Drink ? kConjureWaterBelow : kConjureFoodBelow); + if (create && s.is_ready(create) + && V2::MayConjure(s.in_combat(), s.recently_in_combat(5000), s.power(POWER_MANA), s.mana_cost(create)) + && !ai.action_recently_tried(BotAI::ActionKind::ClassUpkeep, create, now_ms)) + return create; + } + return 0; +} +bool ConjureGate(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const& g, uint32 now_ms) +{ + if (s.cls() != CLASS_MAGE || !s.is_in_instance() || !UpkeepWindow(s, g) || s.is_moving() || s.recently_in_combat(5000)) + return false; + return PickConjure(s, ai, now_ms) != 0; +} +bool ConjureFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const&, BotIntentEmitter& emit, uint32 now_ms) +{ + uint32 const create = PickConjure(s, ai, now_ms); + if (!create || !emit.cast(create)) + return false; + ai.note_action_retry(BotAI::ActionKind::ClassUpkeep, create, now_ms); + ai.set_last_rule_fired("idle:classic_conjure"); + return true; +} + // ---------- idle:classic_fear_ward ---------- // The raid plan (PveGroupCoordinator) gives each dwarf priest one tank that // lacks Fear Ward; between pulls the priest puts it back up (in combat the @@ -494,6 +609,8 @@ void RegisterClassicUpkeepRules(IdleRuleRegistry& r) add("idle:classic_dispel", 992, &DispelGate, &DispelFire); add("idle:classic_soulstone", 992, &SoulstoneGate, &SoulstoneFire); add("idle:classic_healthstone", 992, &HealthstoneGate, &HealthstoneFire); + add("idle:classic_mana_gem", 992, &ManaGemGate, &ManaGemFire); + add("idle:classic_conjure", 992, &ConjureGate, &ConjureFire); add("idle:classic_fear_ward", 992, &FearWardGate, &FearWardFire); add("idle:classic_raid_consumables", 991, &RaidConsumablesGate, &RaidConsumablesFire); } diff --git a/src/modules/PlayerbotV2/Bot/States/Rules/CoreFlowRules.cpp b/src/modules/PlayerbotV2/Bot/States/Rules/CoreFlowRules.cpp index f7e6508ce9..2052719d30 100644 --- a/src/modules/PlayerbotV2/Bot/States/Rules/CoreFlowRules.cpp +++ b/src/modules/PlayerbotV2/Bot/States/Rules/CoreFlowRules.cpp @@ -374,7 +374,7 @@ bool RejoinInstanceGate(BotSnapshotView const& s, BotAI&, // Instance-entrance area triggers: areatrigger_teleport rows whose trigger // volume lies on one map and whose destination is an instanceable map. Built // once from load-time stores (AreaTrigger.db2, ObjectMgr's trigger map), both -// read-only after load, so the AI thread may read them. The same set the +// read-only after load, so the bot logic thread may read them. The same set the // snapshot builder resolves for a ghost's portal run. struct InstanceEntranceTrigger { uint32 at_id; uint32 src_map; uint32 dst_map; float x, y, z; }; std::vector const& InstanceEntranceTriggers() @@ -817,6 +817,26 @@ bool RejoinInstanceFire(BotSnapshotView const& s, BotAI& ai, constexpr float kWalkRange = 500.0f; constexpr float kWalkRangeEnter = 400.0f; constexpr float kWalkRangeLeave = 600.0f; + // The owner is inside and this is the owner's own companion: it goes in to the owner's spot at once. The door checks (a refusal + // is logged with its reason, a stale lock on another instance is dropped) are API::teleport_to's. After a few refusals the + // entrance trigger below takes over again (walk in, or be summoned to the entrance). + if (owner == anchor && rr.direct_tries < BotAI::RejoinRun::kDirectTries && (rr.summon_ms == 0 || now_ms - rr.summon_ms >= 3000u)) + { + rr.summon_ms = now_ms ? now_ms : 1u; + ++rr.direct_tries; + TC_LOG_INFO("playerbot.v2", "[rejoin] {} is ported into map {} to {} at ({:.0f},{:.0f},{:.0f}) (try {}/{})", s.name(), + anchor->map_id, anchor->name, anchor->x, anchor->y, anchor->z, rr.direct_tries, BotAI::RejoinRun::kDirectTries); + if (s.is_mounted()) + emit.dismount(); + emit.teleport_to(anchor->map_id, anchor->x, anchor->y, anchor->z, anchor->o); + ai.set_last_rule_fired("idle:rejoin_enter_owner"); + return true; + } + if (owner == anchor && rr.direct_tries < BotAI::RejoinRun::kDirectTries) + { + ai.set_last_rule_fired("idle:rejoin_enter_owner"); + return true; + } InstanceEntranceTrigger const* t = ResolveEntranceTrigger(s.map_id(), bx, by, anchor->map_id); if (!t) { diff --git a/src/modules/PlayerbotV2/Bot/States/Rules/CraftOrderRules.cpp b/src/modules/PlayerbotV2/Bot/States/Rules/CraftOrderRules.cpp index e3724aace4..bad05f8dde 100644 --- a/src/modules/PlayerbotV2/Bot/States/Rules/CraftOrderRules.cpp +++ b/src/modules/PlayerbotV2/Bot/States/Rules/CraftOrderRules.cpp @@ -19,7 +19,7 @@ // ticks to top the crafter up; if mats never arrive the board times the // claim out and refunds the requester. // -// THREADING: these rules run on the AI WORKER thread and only EMIT intents. The +// THREADING: these rules run on the bot logic WORKER thread and only EMIT intents. The // actual board mutations (PostOrder / ClaimOpenOrder / MarkDelivered) and the // craft+mail all run on the WORLD thread inside the intent executor, where the // escrow debit, the live spellbook check, and the fleet-bot human-firewall live. diff --git a/src/modules/PlayerbotV2/Bot/States/Rules/FarTravelRules.cpp b/src/modules/PlayerbotV2/Bot/States/Rules/FarTravelRules.cpp index 8bc4b685e0..3000e413c7 100644 --- a/src/modules/PlayerbotV2/Bot/States/Rules/FarTravelRules.cpp +++ b/src/modules/PlayerbotV2/Bot/States/Rules/FarTravelRules.cpp @@ -31,6 +31,7 @@ #include "Bot/BotAI.h" #include "Bot/BotSnapshotView.h" #include "Bot/BotIntentEmitter.h" +#include "Bot/ClassicUpkeep.h" #include "Bot/States/MaintainHelpers.h" #include "Services.h" #include "Travel/PortalIndex.h" @@ -87,11 +88,8 @@ bool FarSameMapTravelGate(BotSnapshotView const& s, BotAI& ai, if (ai.in_profession_mode(s.published_at_ms())) return false; // HP<50%: heal first (same gate as pursue_quest_goal — a hurt bot should not // set off across open terrain to a far goal unhealed). - { - auto const& v = s.raw().vitals; - if (v.max_hp > 0 && uint64(v.hp) * 100u < uint64(v.max_hp) * 50u) - return false; - } + if (Classic::RecoverBeforeWalking(s)) + return false; // Yield to a nearby acceptable offer (giver in scan) or any pending turn-in — // accept/turn-in own those; trekking to a far goal must not preempt a quest // hand-in the bot could complete right here (mirrors pursue_quest_goal). diff --git a/src/modules/PlayerbotV2/Bot/States/Rules/GuildRules.cpp b/src/modules/PlayerbotV2/Bot/States/Rules/GuildRules.cpp index ef037628a2..e182739710 100644 --- a/src/modules/PlayerbotV2/Bot/States/Rules/GuildRules.cpp +++ b/src/modules/PlayerbotV2/Bot/States/Rules/GuildRules.cpp @@ -248,7 +248,7 @@ bool CharterDriveFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView con const uint32 sigs = Services::Guilds() .ActiveFounderSignatureCount(kFaction); const uint32 required = sConfigMgr->GetIntDefault( - "MinPetitionSigns", 4); + "MinPetitionSigns", 4, true); if (sigs >= required) { ai.advance_guild_charter_phase(4); diff --git a/src/modules/PlayerbotV2/Bot/States/Rules/HearthRules.cpp b/src/modules/PlayerbotV2/Bot/States/Rules/HearthRules.cpp index 1ec777c2e4..f9a916fa97 100644 --- a/src/modules/PlayerbotV2/Bot/States/Rules/HearthRules.cpp +++ b/src/modules/PlayerbotV2/Bot/States/Rules/HearthRules.cpp @@ -28,6 +28,7 @@ bool WalkInnkeeperGate(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView co const uint32 zid = s.zone_id(); if (zid == 0) return false; if (ai.hearth_zone() == zid) return false; + if (s.has_actionable_quest()) return false; // quest work in reach wins; the quest walkers would pull the bot back over the 80 y line return ai.ms_in_zone(zid) >= ::Playerbot::BotAI::kHearthRebindThresholdMs; } diff --git a/src/modules/PlayerbotV2/Bot/States/Rules/LootDrainRules.cpp b/src/modules/PlayerbotV2/Bot/States/Rules/LootDrainRules.cpp index e8c213b9e5..453548fa21 100644 --- a/src/modules/PlayerbotV2/Bot/States/Rules/LootDrainRules.cpp +++ b/src/modules/PlayerbotV2/Bot/States/Rules/LootDrainRules.cpp @@ -37,6 +37,10 @@ namespace { constexpr float kLootRange = 11.0f; // A human leads an instance group: bots walk only to corpses this close to him (the rest wait in the queue). constexpr float kHumanLootLeashYd = 20.0f; +// A bot tank leads: bots walk only to corpses this close to the anchor tank (rejoin_tank pulls a follower back at 40 y). +constexpr float kTankLootLeashYd = 28.0f; +// A corpse with an idle hostile mob this close is not walked to (the walk would pull it). +constexpr float kLootIdleMobClearYd = 16.0f; constexpr uint16 SKILL_SKINNING_LOCAL = 393; // PROF-P2b: resolve the rank-appropriate skinning cast spell from the bot's @@ -67,7 +71,15 @@ bool LootDrainGate(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const& // Told to stay: the corpse can wait until it is released. if (ai.is_manual_mode(s.published_at_ms()) && ai.owner_command() == BotAI::OwnerCommand::Stay) return false; - // Loot etiquette with a human in the group (Karrz's AddLootAction): no + // A dungeon mana user under the pull-ready mana drinks instead of walking to corpses (the tank's pull waits for that mana, and a + // walking caster never sits): the healer mark for a healer, the DPS mark for the rest, as the tank's gate reads them. This one check + // serves the registered rule and DungeonLootDrain. deadmines_full c82a7e21, Scnpriest under 10% mana at t=383-404 s walked to + // corpses and back to the tank without drinking. + if (s.is_in_instance() && s.max_power(POWER_MANA) > 0 && Classic::DrinksForPull(s, &g) + && s.power_pct(POWER_MANA) < Classic::OocDrinkStartManaPct(s, &g, 0) + && Classic::BestConsumable(s, Classic::ConsumableKind::Drink)) // no drink in the bags: it loots rather than waits for nothing + return false; + // Loot etiquette with a human in the group (the owner's AddLootAction): no // looting while the bot or a human of the group on its map is still // fighting. The queue keeps the corpses for after the fight. if (auto const* members = g.members()) @@ -355,7 +367,7 @@ bool LootDrainFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const& continue; } // A human leads the instance group: the bots follow him (Follow / Stay obeyed), so a corpse far from him waits - // in the queue until he walks near it. Karrz, Deadmines 2026-10-10: he hit Follow and two bots stayed down + // in the queue until he walks near it. The owner, Deadmines 2026-10-10: he hit Follow and two bots stayed down // the tunnel - the loot walk leased the follow-recall away (grant_detour below). if (s.is_in_instance() && !g.leader_is_bot()) if (auto const* mems = g.members()) @@ -367,6 +379,35 @@ bool LootDrainFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const& return; break; } + // A bot-led dungeon group: a corpse further from the anchor tank than kTankLootLeashYd waits (the queue rotates to + // the next corpse). ingroup:dungeon_rejoin_tank walks a follower back once it is 40 y from the tank, so a loot + // walk to a corpse near that line ping-ponged with it and the follower stood still for 45 s (deadmines_full + // c82a7e21: Scnpriest alternated idle:move_to_corpse / ingroup:dungeon_rejoin_tank from t=947 s to t=1020 s). + if (s.is_in_instance() && g.leader_is_bot()) + if (GroupMemberSummary const* tk = States::GroupAnchorTank(s, ai, g); + tk && tk->online && tk->is_alive && tk->guid != s.guid() && tk->map_id == s.map_id()) + { + const float tx = c->GetPositionX() - tk->x, ty = c->GetPositionY() - tk->y; + if (tx * tx + ty * ty > kTankLootLeashYd * kTankLootLeashYd) + { + if (rotate_sentinel == c->GetGUID()) + return; // came full circle this tick: every queued corpse is too far + if (rotate_sentinel.IsEmpty()) + rotate_sentinel = c->GetGUID(); + q.push_back(q.front()); + q.pop_front(); + continue; + } + } + // An idle hostile mob beside the corpse (the rest of the pack, a patrol standing by it) is aggroed by the walk: the + // corpse waits in the queue until the mob is dealt with (playtest, Deadmines 2026-10-15: bots ran to loot and pulled more). + for (NearbyUnit const& u : s.raw().combat.nearby_enemies) + { + if (u.hp <= 0 || u.unit_in_combat || !u.victim.IsEmpty() || u.is_pacified || u.untargetable || u.no_xp_kill) continue; + const float ux = u.x - c->GetPositionX(), uy = u.y - c->GetPositionY(); + if (ux * ux + uy * uy <= kLootIdleMobClearYd * kLootIdleMobClearYd) + return; + } emit.move_to(c->GetPositionX(), c->GetPositionY(), c->GetPositionZ(), /*run*/ true); // Lease a few seconds of follow-recall slack so a grouped @@ -410,10 +451,7 @@ bool DungeonLootDrain(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView con for (GroupMemberSummary const& m : *members) if (m.guid != s.guid() && m.online && m.is_alive && m.in_combat && m.map_id == s.map_id()) return false; - // A healer under the pull-ready mana drinks instead of walking to corpses: the tank's pull waits for that mana, and a - // looting healer is always "moving" (idle:dungeon_healer_drink needs her still; deadmines_rhahkzor run 7: 15-64% mana, never sat). - if (Classic::IsGroupHealer(s, &g) && s.max_power(POWER_MANA) > 0 && s.power_pct(POWER_MANA) < Classic::PullReadyHealerManaPct(s)) - return false; + // The drink-before-loot check (deadmines_rhahkzor run 7: a looting healer is always "moving" and never sat) lives in LootDrainGate. const uint32 now_ms = s.published_at_ms(); if (!LootDrainGate(s, ai, g, now_ms)) return false; diff --git a/src/modules/PlayerbotV2/Bot/States/Rules/MaintainRules.cpp b/src/modules/PlayerbotV2/Bot/States/Rules/MaintainRules.cpp index 8d6c55ba64..212b813f58 100644 --- a/src/modules/PlayerbotV2/Bot/States/Rules/MaintainRules.cpp +++ b/src/modules/PlayerbotV2/Bot/States/Rules/MaintainRules.cpp @@ -122,6 +122,8 @@ bool OocRezFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const& g, BotIntentEmitter& emit, uint32) { + // Registered above the classic upkeep (992), so keep out of the hazards that sit below it. + if (s.is_in_damaging_liquid() || s.is_swimming()) return false; if (!MaintainOocRez(s, g, emit)) return false; ai.set_last_rule_fired("idle:ooc_rez"); return true; @@ -132,6 +134,7 @@ bool OocHealFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const& g, BotIntentEmitter& emit, uint32) { + if (s.is_in_damaging_liquid() || s.is_swimming()) return false; if (!MaintainOocHeal(s, g, emit, ai.effective_role(s))) return false; ai.set_last_rule_fired("idle:ooc_heal"); return true; @@ -348,16 +351,6 @@ bool ConjuredItemFire(BotSnapshotView const& s, BotAI& ai, return true; } -// ---------- idle:ooc_food ---------- -bool OocFoodFire(BotSnapshotView const& s, BotAI& ai, - GroupSnapshotView const&, - BotIntentEmitter& emit, uint32) -{ - if (!MaintainOocFood(s, ai, emit)) return false; - ai.set_last_rule_fired("idle:ooc_food"); - return true; -} - } // anonymous namespace void RegisterMaintainRules(IdleRuleRegistry& r) @@ -381,8 +374,10 @@ void RegisterMaintainRules(IdleRuleRegistry& r) add("idle:apply_context_talents", 692, &ContextTalentsFire); add("idle:auto_equip", 690, &AutoEquipFire); add("idle:equip_bag_upgrade", 689, &BagUpgradeFire); - add("idle:ooc_rez", 688, &OocRezFire); - add("idle:ooc_heal", 686, &OocHealFire); + // 993 / 993 (were 688 / 686): above the classic upkeep (992) and the quest funnel, so the dead are raised and the hurt healed + // before buffs go out or a quest walk starts. Rez first: registration order breaks the tie. + add("idle:ooc_rez", 993, &OocRezFire); + add("idle:ooc_heal", 993, &OocHealFire); add("idle:ooc_dispel", 684, &OocDispelFire); add("idle:self_buff", 682, &SelfBuffFire); add("idle:soulstone", 680, &SoulstoneFire); @@ -439,7 +434,8 @@ void RegisterMaintainRules(IdleRuleRegistry& r) } add("idle:group_utility", 674, &GroupUtilityFire); add("idle:conjured_item", 672, &ConjuredItemFire); - add("idle:ooc_food", 671, &OocFoodFire); + // Eating and drinking: idle:ooc_eat_food (OocConsumableRules). It always ran right after the old ooc_food rule declined, so it + // set the real thresholds; MaintainOocFood remains only for the battleground prep cascade. } } // namespace Playerbot diff --git a/src/modules/PlayerbotV2/Bot/States/Rules/OocConsumableRules.cpp b/src/modules/PlayerbotV2/Bot/States/Rules/OocConsumableRules.cpp index 4d6ec9a493..db52ec322a 100644 --- a/src/modules/PlayerbotV2/Bot/States/Rules/OocConsumableRules.cpp +++ b/src/modules/PlayerbotV2/Bot/States/Rules/OocConsumableRules.cpp @@ -5,7 +5,7 @@ // - idle:ic_potion (combat healthstone / potion, as State_InCombat) // - idle:ooc_eat_food (sit-eat-drink between pulls) // - idle:ooc_bandage (self-bandage when low HP and no food works) -// - idle:loot_roll (auto-vote on group loot rolls with Karrz's +// - idle:loot_roll (auto-vote on group loot rolls with the owner's // human-first etiquette; reports loot_roll / // loot_roll_quest / loot_roll_de / *_human) // - idle:equip_upgrade (stat-priority + ilvl scored equip swap) @@ -121,7 +121,7 @@ bool OocPotionGate(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const& const auto thr = GetIdleConsumeThresholds(ai); if (s.hp_pct() >= thr.potion_below) return false; if (Classic::SafeToRecover(s, &g) && Classic::BestConsumable(s, Classic::ConsumableKind::Food)) - return false; // eat instead (idle:ooc_eat_food / idle:ooc_food) + return false; // eat instead (idle:ooc_eat_food) return Classic::BestConsumable(s, Classic::ConsumableKind::HealingPotion) != 0; } @@ -146,7 +146,7 @@ bool OocPotionFire(BotSnapshotView const& s, BotAI& ai, // The in-combat dispatcher (State_InCombat MaybeUseSurvivalItem) covers a // bot in its combat state; this catches the ticks where the bot is already // in combat but still dispatched as idle. Same decision for both -// (Classic::PickCombatHealthItem, Karrz's UsePotionsStrategy): at 30% health +// (Classic::PickCombatHealthItem, the owner's UsePotionsStrategy): at 30% health // or below a healthstone, then the best healing potion for the level, kept // while a group heal is about to land (unless at 20% or below), one combat // consumable per 2.5 s and only items off cooldown. @@ -168,7 +168,7 @@ bool IcPotionFire(BotSnapshotView const& s, BotAI& ai, } // ---------- idle:ooc_eat_food ---------- -// Sit-eat-drink between pulls (Karrz's UseFoodStrategy): eat below 90% +// Sit-eat-drink between pulls (the owner's UseFoodStrategy): eat below 90% // health, drink below 70% mana, only when SafeToRecover - nothing attacks the // bot and nobody (group member or enemy) is fighting within 45 yards - so a // companion eats at its owner's side and stands up for the next pull. While @@ -189,7 +189,7 @@ bool OwnerNotLeading(BotSnapshotView const& s, GroupSnapshotView const& g) return false; } -// Open-world drink threshold (Karrz's UseFoodStrategy). A healer grouped in +// Open-world drink threshold (the owner's UseFoodStrategy). A healer grouped in // an instance drinks below Classic::kPullReadyHealerManaPct instead - the mana // its tank waits for before the next pull - so it never holds a pull it is not // drinking for (Classic::OocDrinkStartManaPct). @@ -200,6 +200,10 @@ int32 OocDrinkStart(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const { if (s.is_in_raid() && ai.holding_position(now_ms) && Classic::IsGroupHealer(s, &g)) return Classic::kHeldRaidHealerManaPct; + // The owner's hold in a raid is the wait for a boss pull for the casters and hunters too: they drink to the same mark (playtest, live MC + // 2026-10-12: "full mana for fights"). + if (s.is_in_raid() && ai.holding_position(now_ms) && s.max_power(POWER_MANA) > 0) + return Classic::kHeldRaidHealerManaPct; return Classic::OocDrinkStartManaPct(s, &g, kOocDrinkBelowManaPct); } @@ -215,7 +219,19 @@ bool OocEatFoodGate(BotSnapshotView const& s, BotAI& ai, if (s.raw().movement.is_mounted) return false; if (s.is_encounter_in_progress()) return false; if (!Classic::SafeToRecover(s, &g)) return false; - Classic::RecoveryPick const pick = Classic::PickRecovery(s, 90, OocDrinkStart(s, ai, g, now_ms)); + // A solo quester does not sit down with its quest kill targets ready to engage in scan range; a grouped bot goes at the + // group's pace, so this never applies to it. + if (!s.in_group()) + { + for (auto const& ao : s.actionable_objectives()) + { + if (ao.type == /*MONSTER*/ 0 || + ao.type == /*KILL_WITH_LABEL*/ 21 || + (ao.type == /*ITEM*/ 1 && ao.source_guid.IsCreature())) + return false; + } + } + Classic::RecoveryPick const pick = Classic::PickRecovery(s, GetIdleConsumeThresholds(ai).food_floor, OocDrinkStart(s, ai, g, now_ms)); if (pick.item) return !s.raw().movement.is_moving; return pick.hold; @@ -225,7 +241,7 @@ bool OocEatFoodFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const& g, BotIntentEmitter& emit, uint32 now_ms) { - Classic::RecoveryPick const pick = Classic::PickRecovery(s, 90, OocDrinkStart(s, ai, g, now_ms)); + Classic::RecoveryPick const pick = Classic::PickRecovery(s, GetIdleConsumeThresholds(ai).food_floor, OocDrinkStart(s, ai, g, now_ms)); if (pick.item) { emit.emit(UseItemByEntryIntent{pick.item, s.raw().guid}); @@ -238,7 +254,7 @@ bool OocEatFoodFire(BotSnapshotView const& s, BotAI& ai, } // ---------- idle:ooc_bandage ---------- -// Self-bandage below 50% health (Karrz: out-of-combat bandages when no +// Self-bandage below 50% health (the owner: out-of-combat bandages when no // healer is near). Bandages need First Aid at the item's rank (the supplies // restock teaches it); Recently Bandaged blocks another for a minute. constexpr uint32 kRecentlyBandaged = 11196; @@ -319,7 +335,7 @@ bool LootRollFire(BotSnapshotView const& s, BotAI& ai, { uint8 vote = 0; char const* rule_name = "idle:loot_roll"; - // Loot etiquette with a human in the group (Karrz's LootRollAction): + // Loot etiquette with a human in the group (the owner's LootRollAction): // the human gets first claim. Bind on pickup, or not equipment // (tokens, quest items) the human could use: pass. Bind on equip the // human could use: greed at most. diff --git a/src/modules/PlayerbotV2/Bot/States/Rules/PrologueRules.cpp b/src/modules/PlayerbotV2/Bot/States/Rules/PrologueRules.cpp index b93cf2d957..e59bdccf55 100644 --- a/src/modules/PlayerbotV2/Bot/States/Rules/PrologueRules.cpp +++ b/src/modules/PlayerbotV2/Bot/States/Rules/PrologueRules.cpp @@ -14,12 +14,14 @@ // hazards. Holding mode is the exception — it preserves the legacy // "fall through" semantic via fire-returns-false. +#include #include "Bot/IdleRule.h" #include "Group/GroupSnapshot.h" #include "Bot/BotAI.h" #include "Bot/BotSnapshotView.h" #include "Bot/BotIntentEmitter.h" #include "Bot/ThreatDiscipline.h" // RaidLogDue (opener pull discipline) +#include "Bot/States/StateBase.h" // ThreatHoldActive #include "Bot/MarkGate.h" // Playerbot.Behavior.MarksNeedOrder #include "Bot/ClassicUpkeep.h" // Classic::IsBossUnit #include "Bot/States/MaintainHelpers.h" // States::GroupAnchorTank @@ -87,7 +89,7 @@ bool WatchdogFire(BotSnapshotView const& s, BotAI& ai, { const uint32 wdog_now_ms = s.published_at_ms(); float bx, by, bz; s.position(bx, by, bz); - const uint32 epoch = wdog_now_ms / 2000u; + const uint32 epoch = wdog_now_ms / 8000u; // one heading per 8 s window, so the escape runs straight instead of re-aiming every 2 s const uint64 mixed = (uint64(s.bot_id()) * 0x9E3779B97F4A7C15ULL) ^ (uint64(epoch) * 0xBF58476D1CE4E5B9ULL); const float angle = (float(mixed & 0xFFFFu) / 65536.0f) * 6.2831853f; @@ -147,6 +149,21 @@ bool OpenerGate(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const& g, ai.reset_opener_own_since(); return false; } + // A tank on the owner's Attack / Pull order, the mob not yet reached: idle:owner_engaging walks it in (own pathing, straight + // line when the navmesh has none). The opener (993) held the tick with a cast the mob was out of range for, and the tank stood + // still for seconds before the pull (Deadmines 2026-10-15, 7 s from the order to the first step). + if (s.is_in_dungeon() && ai.effective_role(s) == Role::Tank && ai.is_manual_mode(s.published_at_ms()) && + ai.owner_command() == BotAI::OwnerCommand::Engage && ai.owner_target() == s.victim()) + for (NearbyUnit const& u : s.nearby_enemies()) + if (u.guid == s.victim()) + { + float px, py, pz; + s.position(px, py, pz); + float const dx = u.x - px, dy = u.y - py; + if (dx * dx + dy * dy > (std::max(u.combat_reach, 4.0f) + 3.5f) * (std::max(u.combat_reach, 4.0f) + 3.5f)) + return false; + break; + } // ABSOLUTE opener ceiling inside a dungeon (2026-07-21). The per-victim // give-up (opener_victim_since_ms, 25s) is DEFEATED when the server-side // victim selection flips between GUIDs every tick: set_opener_victim @@ -257,7 +274,7 @@ bool OpenerFire(BotSnapshotView const& s, BotAI& ai, // leaves the snapshot). Most scripted dungeon bosses (incl. Admiral Ripsnarl) // are not flagged as bosses by the core, so fall back to the per-dungeon // advice.bosses entry list. Computed once per fresh victim (the advice copy is - // non-trivial) and cached on the AI. + // non-trivial) and cached on the bot logic. if (vu && fresh_open) { bool is_boss = Classic::IsBossUnit(*vu); // either boss flag (is_dungeon_boss is never set on this core) @@ -419,6 +436,8 @@ bool FollowPullThreatGate(BotSnapshotView const& s, BotAI& ai, if (s.in_combat() || s.is_casting() || !s.is_alive()) return false; if (s.raw().movement.is_mounted) return false; if (s.in_battleground() || s.is_in_dungeon()) return false; + // Passive = defend only; Stay / Hold = keep the spot: neither starts a fight with a mob in the corridor. + if (ai.passive_now(false) || ai.holding_position(s.published_at_ms())) return false; if (!g.exists()) return false; ObjectGuid const leader_guid = g.leader(); if (leader_guid.IsEmpty() || leader_guid == s.guid()) return false; @@ -521,11 +540,89 @@ bool OwnerEngageGate(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView cons { return ManualModeActive(s, ai) && ai.owner_command() == BotAI::OwnerCommand::Engage; } -bool OwnerEngageFire(BotSnapshotView const&, BotAI& ai, - GroupSnapshotView const&, BotIntentEmitter&, uint32) +bool OwnerEngageFire(BotSnapshotView const& s, BotAI& ai, + GroupSnapshotView const& g, BotIntentEmitter& emit, uint32) { + // A tank ordered onto a mob (raid boss or dungeon pull) walks up to it and attacks. The rule used to do nothing but hold the tick, which suits a bot that is + // already in the fight; a tank ordered onto a stationary boss (Ragnaros has no combat movement) from 37 y away stood there for the + // whole Engage window while the boss killed the casters with Magma Blast (MC Ragnaros 2026-10-13 eb79ff8d). + ObjectGuid const owner_target = ai.owner_target(); + bool target_in_sight = false; + for (NearbyUnit const& u : s.nearby_enemies()) + if (u.guid == owner_target && u.hp > 0) + { + target_in_sight = true; + break; + } + if (s.is_in_dungeon() && s.is_alive() && !s.in_combat() && !s.is_casting() && ai.effective_role(s) == Role::Tank) + { + ObjectGuid const target = owner_target; + for (NearbyUnit const& u : s.nearby_enemies()) + { + if (u.guid != target || u.hp <= 0) + continue; + float px, py, pz; + s.position(px, py, pz); + float const dx = u.x - px, dy = u.y - py; + float const dist = std::sqrt(dx * dx + dy * dy); + float const stand = std::max(u.combat_reach, 4.0f) + 2.0f; // inside melee reach of a big boss, not inside the boss + if (dist > stand + 1.5f && dist > 0.1f) + { + float const gx = u.x - dx / dist * stand, gy = u.y - dy / dist * stand; + { + // Every 2 s (one line at a time across bots): where the tank is and what its walk to the ordered mob looks like. + static std::atomic s_walk_log_ms{0}; + uint32 const now_log = s.published_at_ms(); + uint32 last_log = s_walk_log_ms.load(std::memory_order_relaxed); + if (now_log - last_log >= 2000u && s_walk_log_ms.compare_exchange_strong(last_log, now_log)) + TC_LOG_INFO("playerbot.v2", "[engage_walk] {} at ({:.1f},{:.1f},{:.1f}) to mob {} at ({:.1f},{:.1f},{:.1f}) dist={:.1f} stand={:.1f} dst=({:.1f},{:.1f}) moving={} path_dest={} los={}", + s.name(), px, py, pz, u.entry, u.x, u.y, u.z, dist, stand, gx, gy, s.is_moving() ? 1 : 0, + s.has_path_destination() ? 1 : 0, u.in_los ? 1 : 0); + } + // The same walk emitted a moment ago is under way (the dedup answers false for it): not a refusal, so no direct + // straight-line walk replaces the pathed one. + if (emit.move_already_emitted(gx, gy, u.z) || emit.move_to(gx, gy, u.z, /*run*/ true)) + { + ai.set_last_rule_fired("idle:owner_engage_close"); + return true; + } + // The navmesh gave no route (mine carts and props between the tank and the pull, Deadmines 2026-10-14: the tank said + // "pulling" and stood still): a mob in sight and close is walked to in a straight line, bounded to 25 y. + if (u.in_los && dist <= 25.0f && + emit.move_to(u.x - dx / dist * stand, u.y - dy / dist * stand, u.z, /*run*/ true, /*direct*/ true)) + { + ai.set_last_rule_fired("idle:owner_engage_close_direct"); + return true; + } + } + else if (emit.start_attack(target)) + { + ai.set_last_rule_fired("idle:owner_engaging"); + return true; + } + break; + } + } + // A non-tank that did not open on the Attack order (a party's casters wait for the tank, BotCommandParser "attack") opens once + // the threat hold lets go: the tank has its lead, or the bounded wait is over. + if (target_in_sight && s.is_alive() && !s.in_combat() && !s.is_casting() && s.victim().IsEmpty() && + ai.effective_role(s) != Role::Tank && !States::ThreatHoldActive(ai, s, owner_target, &g) && + emit.start_attack(owner_target)) + { + ai.set_last_rule_fired("idle:owner_engaging"); + return true; + } + // The ordered mob is dead or gone and the bot is out of the fight: the Attack / Pull order is done. It ends here instead of + // holding the tick for the rest of its 30 s window (looting, drinking and buffing below priority 975 were starved). + if (!target_in_sight && !s.in_combat()) + { + ai.exit_manual(); + return false; + } ai.set_last_rule_fired("idle:owner_engaging"); - return true; + // A companion whose ordered mob is not near keeps its upkeep going (rez, heal, buffs, drink), as under follow and stay; + // with the mob in sight the rule still holds the tick. + return !s.is_companion_with_owner() || target_in_sight; } // idle:owner_disengage @@ -631,14 +728,27 @@ bool FallbackTick(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const& const bool healer = ai.effective_role(s) == Role::Healer; auto tag = [&](char const* idle_tag, char const* combat_tag) { ai.set_last_rule_fired(in_combat_state ? combat_tag : idle_tag); }; + // A raid avoid circle (Baron Geddon's Inferno, a Living Bomb carrier) outranks the order's walk. The bot standing in one is left to + // the raid brain's step-out; a rally point or slot inside one is not walked into, the bot waits where it is (MC Geddon 2026-10-12: + // Fall back sent bots back to a rally point inside Inferno, 14 of the deaths read combat:fallback_hold / fallback_return). + PveOrder const& hazard_order = s.raw().pve_order; + bool const hazards = Services::Config().behavior_avoid_circles() && hazard_order.active && hazard_order.avoid_circle_count > 0; + if (hazards && hazard_order.in_avoid_circle(bx, by, 0.0f)) + return false; // Head for (x,y,z) unless a live path already ends there (re-issuing restarts the spline). auto head_to = [&](float x, float y, float z, bool run) { + if (hazards && hazard_order.in_avoid_circle(x, y, 2.0f)) + { + if (s.is_moving()) emit.stop_movement(); + return false; + } if (s.is_moving() && s.has_path_destination()) { float qx, qy, qz; s.path_destination(qx, qy, qz); if (d2xy(qx, qy, x, y) < 2.0f * 2.0f) return true; } + if (emit.move_already_emitted(x, y, z)) return true; // under way, not refused return emit.move_to(x, y, z, run); }; @@ -807,14 +917,17 @@ bool PullBackTick(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const&, float bx, by, bz; s.position(bx, by, bz); auto d2xy = [](float ax, float ay, float cx, float cy) { return (ax - cx) * (ax - cx) + (ay - cy) * (ay - cy); }; // head_to is true when the move was queued; false = refused (counted by hopeless()). - auto head_to = [&](float x, float y, float z, bool run) + auto head_to = [&](float x, float y, float z, bool run, bool direct = false) { if (s.is_moving() && s.has_path_destination()) { float qx, qy, qz; s.path_destination(qx, qy, qz); if (d2xy(qx, qy, x, y) < 2.0f * 2.0f) return true; } - return emit.move_to(x, y, z, run); + // The same walk was emitted a moment ago: it is under way, not refused (Deadmines 2026-10-15 n43: the retake's approach + // re-asked for its spot each tick, the dedup answered false, and two of those ended the order as "path refused 2x"). + if (emit.move_already_emitted(x, y, z)) return true; + return emit.move_to(x, y, z, run, direct); }; // The movement toward a goal is hopeless: a path refusal (move refused, or the path-block counter grew) on 2 // ticks, or no closer to the goal for 4 s. `why` says which. @@ -881,7 +994,7 @@ bool PullBackTick(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const&, { opener_unavail = true; ai.edit_pull_back([](BotAI::PullBackPlan& q) { q.opener_unavail = true; }); - TC_LOG_INFO("playerbot.v2", "[pull_back] {} ranged opener unavailable (NO_AMMO): taunt / plain engage instead", s.name()); + TC_LOG_INFO("playerbot.v2", "[pull_back] {} ranged opener refused (no ammo or no usable ranged weapon): taunt / plain engage instead", s.name()); } // Opener: first ready ranged spell of the class whose window holds d; none (or it did not take) = plain engage. struct Opener { uint32 spell; float min_d, max_d; }; @@ -905,12 +1018,32 @@ bool PullBackTick(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const&, TC_LOG_INFO("playerbot.v2", "[pull_back] {} the opener did not engage {} within 3 s: target {:.0f}y, in sight {}, hp {}", s.name(), p.target.GetCounter(), d, tu ? (tu->in_los ? "yes" : "NO") : "?", tu ? tu->hp : -1); } + // A warrior's shot is the one his ranged slot fires: Throw needs a thrown weapon, Shoot Bow / Gun / Crossbow the matching + // weapon and ammo. Picking by "known" alone sent Throw from a gun-wearing tank; the core refused it EQUIPPED_ITEM, the order + // dropped the opener and the tank walked into the pack and body-pulled it (playtest 2026-10-15). + auto weapon_fires = [&](uint32 spell) -> bool + { + if (s.cls() != 1) return true; // CLASS_WARRIOR only + uint8 const sub = s.ranged_subclass(); + switch (spell) + { + case 2764: return sub == 16; // Throw: ITEM_SUBCLASS_WEAPON_THROWN + case 2480: return sub == 2 && s.ammo_count() > 0; // Shoot Bow: ITEM_SUBCLASS_WEAPON_BOW + case 7918: return sub == 3 && s.ammo_count() > 0; // Shoot Gun: ITEM_SUBCLASS_WEAPON_GUN + case 7919: return sub == 18 && s.ammo_count() > 0; // Shoot Crossbow: ITEM_SUBCLASS_WEAPON_CROSSBOW + default: return true; + } + }; Opener const* pick = nullptr; // A retake (the mob is on somebody else): a ranged hit does not take it, only a taunt / melee swing does. if (!opener_failed && !opener_unavail && p.retakes == 0) for (size_t i = 0; i < n; ++i) - if (s.knows_spell(list[i].spell) && s.cd_remaining(list[i].spell).count() == 0) + if (s.knows_spell(list[i].spell) && s.cd_remaining(list[i].spell).count() == 0 && weapon_fires(list[i].spell)) { pick = &list[i]; break; } + if (!pick && !p.opened_ms && p.retakes == 0 && !p.opener_failed_logged && + RaidLogDue(RaidLogKey(s, RaidLogKind::PullBackOpener), now_ms, 10000u)) + TC_LOG_INFO("playerbot.v2", "[pull_back] {} no ranged opener (ranged slot subclass {}, ammo {}): walking in to pull by hand", + s.name(), s.ranged_subclass() == 0xFF ? -1 : int(s.ranged_subclass()), s.ammo_count()); // No ranged opener: the plain engage starts from 15y (a retake: from taunt range). const float reach = pick ? pick->max_d : (p.retakes ? 5.0f : 15.0f); const float near_min = pick ? pick->min_d : 0.0f; @@ -957,6 +1090,13 @@ bool PullBackTick(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const&, queued = head_to(ax, ay, az, true); TC_LOG_INFO("playerbot.v2", "[pull_back] {} straight-line spot ({:.1f},{:.1f},{:.1f}) {}", s.name(), ax, ay, az, queued ? "queued" : "refused too"); + // Mob in sight and close, no route from the navmesh (a lip in the floor, Deadmines 2026-10-15): walk the line itself. + if (!queued && tu && tu->in_los && d <= 25.0f) + { + queued = head_to(ax, ay, az, true, /*direct*/ true); + TC_LOG_INFO("playerbot.v2", "[pull_back] {} direct walk to ({:.1f},{:.1f},{:.1f}) {}", s.name(), ax, ay, az, + queued ? "queued" : "refused"); + } } } } @@ -1062,6 +1202,11 @@ bool PullBackTick(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const&, bool others = false; // something besides the pull target is on us for (auto const& u : s.raw().combat.attackers) if (u.guid != p.target && u.hp > 0) { others = true; break; } + // The mob is on the tank and the tank is fighting: the pull is over and the tank rules own the fight. The leash below only walks a + // tank the mob has not taken yet; applied to an engaged boss it dragged the main tank off Baron Geddon toward the return point, inside + // his Inferno circle (MC 2026-10-13: Devane died 20 y out, rule combat:pull_back_leash, no target for 12 s before). + if (tu->victim == s.guid() && s.in_combat() && now_ms - p.phase_ms > 3000u) + return false; if (d2xy(bx, by, p.rx, p.ry) > 12.0f * 12.0f) { if (!s.victim().IsEmpty()) emit.stop_attack(); @@ -1078,6 +1223,45 @@ bool PullBackTick(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const&, } // namespace States +// idle:owner_use - the owner's "use ": walk to within reach of the object, use it once, then stay (the command set Stay). +bool OwnerUseGate(BotSnapshotView const&, BotAI& ai, GroupSnapshotView const&, uint32) +{ + return ai.owner_use_active(); +} +bool OwnerUseFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const&, BotIntentEmitter& emit, uint32) +{ + BotAI::OwnerUseOrder const o = ai.owner_use_order(); + uint32 const now_ms = s.published_at_ms(); + auto finish = [&](char const* why) + { + ai.end_owner_use(); + TC_LOG_INFO("playerbot.v2", "[owner_use] {} order ends: {}", s.name(), why); + return false; + }; + if (!o.set) return finish("cleared"); + if (!s.is_alive()) return finish("dead"); + if (o.map != s.map_id()) return finish("left the map"); + if (now_ms - o.set_ms > 30000u) return finish("not in reach after 30 s"); + float bx, by, bz; s.position(bx, by, bz); + float const dx = o.x - bx, dy = o.y - by; + float const d = std::sqrt(dx * dx + dy * dy); + if (d > 4.5f || std::fabs(o.z - bz) > 5.0f) + { + // Stop 2.5 y short on the line from the bot: the object itself (an altar, a brazier) is often solid. + float const k = d > 2.5f ? (d - 2.5f) / d : 0.0f; + float const mx = bx + dx * k, my = by + dy * k; + if (!emit.move_already_emitted(mx, my, o.z) && !emit.move_to(mx, my, o.z, /*run*/ true)) + return finish("no path to the object"); + ai.set_last_rule_fired("idle:owner_use_walk"); + return true; + } + emit.use_game_object(o.go); + ai.end_owner_use(); + TC_LOG_INFO("playerbot.v2", "[owner_use] {} uses object {} at {:.1f}y", s.name(), o.go.GetCounter(), d); + ai.set_last_rule_fired("idle:owner_use"); + return true; +} + void RegisterPrologueRules(IdleRuleRegistry& r) { auto add = [&r](char const* name, int prio, @@ -1102,6 +1286,7 @@ void RegisterPrologueRules(IdleRuleRegistry& r) // 994: the owner's fallback order owns the tick above the opener (States::FallbackTick). add("idle:fallback", 994, &FallbackGate, &FallbackFire); add("idle:pull_back", 994, &PullBackGate, &PullBackFire); + add("idle:owner_use", 994, &OwnerUseGate, &OwnerUseFire); add("combat:opener", 993, &OpenerGate, &OpenerFire); // 991: fires BEFORE owner_following (990) so a corridor threat // preempts the no-op follow tag and start_attack interrupts the diff --git a/src/modules/PlayerbotV2/Bot/States/Rules/QuestRules.cpp b/src/modules/PlayerbotV2/Bot/States/Rules/QuestRules.cpp index e14cf70445..554e788f3a 100644 --- a/src/modules/PlayerbotV2/Bot/States/Rules/QuestRules.cpp +++ b/src/modules/PlayerbotV2/Bot/States/Rules/QuestRules.cpp @@ -9,10 +9,15 @@ #include "GameTime.h" #include "Bot/BotSnapshotView.h" #include "Bot/BotIntentEmitter.h" +#include "Bot/ClassicUpkeep.h" #include "Bot/States/MaintainHelpers.h" // States::ChunkedWalkToward (far-goal chunked walk) #include "Bot/QuestDoable.h" #include "Fleet/JunkQuestResolver.h" #include "Fleet/WorldLeash.h" +#include "Fleet/QuestSiteShare.h" +#include "Fleet/OwnerRegistry.h" +#include "Bot/BotRegistry.h" +#include "Config.h" #include "World/WorldMetadata.h" #include "Services.h" #include "Travel/QuestHubDatabase.h" @@ -188,6 +193,23 @@ bool WqTurninFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const&, return false; } +// One line per bot per 30s when an offer is in sight and idle:quest_accept did not act on it (Zephras Isle 2026-10-12: ~90 bots +// stood beside Allee Farheart for minutes, offers=1, not one [accept_quest] line in the whole run). +void LogAcceptStall(BotSnapshotView const& s, BotAI& ai, char const* why, float nearest_giver_dist) +{ + const uint32 now_ms = s.published_at_ms(); + const uint32 last = ai.last_accept_stall_diag_ms(); + if (last != 0 && now_ms - last < 30000u) return; + ai.set_last_accept_stall_diag_ms(now_ms); + uint32 first_quest = 0; + if (!s.raw().quest_discovery.quest_offers.empty()) + first_quest = s.raw().quest_discovery.quest_offers.front().quest_id; + TC_LOG_INFO("playerbot.v2", + "[quest_accept_stall] bot={} lvl={} why={} offers={} first_quest={} bag_free={} nearest_giver_dist={:.1f} in_combat={} moving={}", + s.name(), uint32(s.level()), why, uint32(s.raw().quest_discovery.quest_offers.size()), first_quest, + uint32(s.bag_free_slots()), nearest_giver_dist, s.in_combat() ? 1 : 0, s.is_moving() ? 1 : 0); +} + // ---------- idle:quest_accept ---------- bool QuestAcceptGate(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const&,uint32) { @@ -199,7 +221,11 @@ bool QuestAcceptGate(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView cons // so the bot frees space the player way first; accept resumes once a slot // opens. bag_free_slots()==0 is the clean gate (deferring a no-item quest a // few ticks until space frees is harmless). - if (s.bag_free_slots() == 0) return false; + if (s.bag_free_slots() == 0) + { + if (!s.raw().quest_discovery.quest_offers.empty()) LogAcceptStall(s, ai, "bags_full", -1.f); + return false; + } if (s.raw().quest_discovery.quest_offers.empty()) { if (ai.pending_quest_accept_at_ms() != 0) ai.set_pending_quest_accept_at_ms(0); @@ -300,6 +326,9 @@ bool QuestAcceptFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView cons : "idle:quest_accept_approach"); return true; } + LogAcceptStall(s, ai, near_dsq == std::numeric_limits::max() ? "giver_not_in_scan" + : s.in_combat() ? "in_combat" : "giver_too_far", + near_dsq == std::numeric_limits::max() ? -1.f : std::sqrt(near_dsq)); return false; } @@ -491,11 +520,9 @@ bool WalkToKnownHubGate(BotSnapshotView const& s, BotAI& ai, // benign to defer for a healthy-ish bot, but a <50% bot should not walk // across open terrain unhealed. (Accept/turn-in are instant so they need no // such deferral.) 2026-06-17. - { - auto const& v = s.raw().vitals; - if (v.max_hp > 0 && uint64(v.hp) * 100u < uint64(v.max_hp) * 50u) - return false; - } + // Also yields while eating / drinking or a caster is dry (Classic::RecoverBeforeWalking). + if (Classic::RecoverBeforeWalking(s)) + return false; // In-scan acceptable offer giver? quest_offers are builder-filtered to // genuinely takeable offers (CanTakeQuest + SatisfyQuestLog). The close- // approach in Fire below walks the bot to the giver so quest_accept (one @@ -794,11 +821,9 @@ bool QuestPursueGoalGate(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView // SHOULD keep questing here to gain combat XP from kills, so no bag gate.) // Now at 698 (above the OOC maintenance band) — yield to a genuinely hurt // bot so it heals before trekking to a far goal. 2026-06-17. - { - auto const& v = s.raw().vitals; - if (v.max_hp > 0 && uint64(v.hp) * 100u < uint64(v.max_hp) * 50u) - return false; - } + // Also yields while eating / drinking or a caster is dry (Classic::RecoverBeforeWalking). + if (Classic::RecoverBeforeWalking(s)) + return false; // Yield to a nearby offer ONLY when its giver is actually in scan — i.e. the // close-approach (walk_to_known_hub) + quest_accept can walk to it and grab it, // after which this resumes. An offer whose giver is NOT in scan can't be @@ -929,10 +954,57 @@ bool QuestPursueGoalFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView return true; } +// ---------- idle:quest_site_share ---------- +// A world bot working a quest spot with more than the cap of other players already there (the nearest ones by id, real players first) +// gives that objective up for 15 minutes and the quest picker takes another one. Keeps a popular mob camp from drawing a dozen bots. +// Side effect only: the rule never claims the tick. Playerbot.World.QuestSiteCap (default 5, 0 = off). +bool QuestSiteShareGate(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const&, uint32) +{ + static uint32 const cap = uint32(std::max(0, sConfigMgr->GetIntDefault("Playerbot.World.QuestSiteCap", int32(V2::Fleet::kQuestSiteCapDefault)))); + if (cap == 0) return false; + if (s.has_owner_character() || s.in_group() || s.is_in_instance() || s.is_in_dungeon() || s.in_battleground()) return false; + auto const& poi = s.current_objective_poi(); + if (!poi.valid || poi.map_id != s.map_id() || ai.current_objective_blacklisted(s.published_at_ms())) return false; + float bx, by, bz; s.position(bx, by, bz); + return std::hypot(poi.x - bx, poi.y - by) <= 60.0f; +} + +bool QuestSiteShareFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const&, BotIntentEmitter&, uint32 now_ms) +{ + uint32 const cap = uint32(std::max(0, sConfigMgr->GetIntDefault("Playerbot.World.QuestSiteCap", int32(V2::Fleet::kQuestSiteCapDefault)))); + float bx, by, bz; s.position(bx, by, bz); + std::vector near; + for (auto const& u : s.raw().combat.nearby_friends) + { + if (!u.is_player || u.hp <= 0) continue; + uint64 const id = u.guid.GetCounter(); + if (id == s.bot_id() || std::hypot(u.x - bx, u.y - by) > V2::Fleet::kQuestSiteRadius) continue; + bool const is_bot = Services::Registry().has(BotId(id)); + bool const owned = is_bot && Services::Owners().GetOwner(BotId(id)).account_id != 0; + near.push_back({ id, !is_bot || owned }); + } + if (!V2::Fleet::YieldQuestSite(s.bot_id(), near, cap)) return false; + ai.blacklist_current_objective(now_ms + V2::Fleet::kQuestSiteGiveUpMs); + ai.set_last_rule_fired("idle:quest_site_share"); + TC_LOG_INFO("playerbot.v2", "[quest_site] {} lvl={} zone={} gave up the objective at ({:.0f},{:.0f}): {} others within {:.0f} y, cap {}", + s.name(), uint32(s.level()), s.zone_id(), s.current_objective_poi().x, s.current_objective_poi().y, near.size(), + V2::Fleet::kQuestSiteRadius, cap); + return false; // side effect only +} + } // anonymous namespace void RegisterQuestRules(IdleRuleRegistry& r) { + { + IdleRule rule; + rule.name = "idle:quest_site_share"; + rule.priority = 696; + rule.gate = &QuestSiteShareGate; + rule.fire = &QuestSiteShareFire; + rule.min_interval_ms = 10000; // per bot + r.register_rule(std::move(rule)); + } { IdleRule rule; rule.name = "idle:walk_to_known_hub"; diff --git a/src/modules/PlayerbotV2/Bot/States/Rules/RpgRules.cpp b/src/modules/PlayerbotV2/Bot/States/Rules/RpgRules.cpp index 90441112d4..0c5f1c51cc 100644 --- a/src/modules/PlayerbotV2/Bot/States/Rules/RpgRules.cpp +++ b/src/modules/PlayerbotV2/Bot/States/Rules/RpgRules.cpp @@ -41,6 +41,7 @@ #include "Bot/BotSnapshotView.h" #include "Bot/BotIntentEmitter.h" #include "Bot/BotIntent.h" +#include "Bot/ClassicUpkeep.h" #include "Services.h" #include "Util/ConfigReader.h" #include "Bot/States/MaintainHelpers.h" // ChunkedWalkToward, DriveTravelPlanTo @@ -120,8 +121,7 @@ bool WorldBotFree(BotSnapshotView const& s, BotAI& ai, uint32 now_ms) if (s.on_transport()) return false; if (ai.in_profession_mode(now_ms)) return false; if (s.has_actionable_quest()) return false; // quest work in reach always wins - auto const& v = s.raw().vitals; - if (v.max_hp > 0 && uint64(v.hp) * 100u < uint64(v.max_hp) * 50u) return false; + if (Classic::RecoverBeforeWalking(s)) return false; // hurt, mid-meal or dry: recover first return true; } @@ -593,7 +593,7 @@ bool AhTripFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const&, B void RegisterRpgRules(IdleRuleRegistry& r) { - // Built here, on the world thread at module init, before any AI worker ticks. + // Built here, on the world thread at module init, before any bot worker ticks. TownNpcIndex::Instance().Initialize(); // All three sit below every need-driven rule (vendor 500, mail 470-480, diff --git a/src/modules/PlayerbotV2/Bot/States/Rules/SurvivalRules.cpp b/src/modules/PlayerbotV2/Bot/States/Rules/SurvivalRules.cpp index 4b7305dfc9..052f1470e8 100644 --- a/src/modules/PlayerbotV2/Bot/States/Rules/SurvivalRules.cpp +++ b/src/modules/PlayerbotV2/Bot/States/Rules/SurvivalRules.cpp @@ -66,7 +66,8 @@ bool FleeDamagingLiquidGate(BotSnapshotView const& s, BotAI&, GroupSnapshotView bool FleeDamagingLiquidFire(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const&,BotIntentEmitter& emit, uint32) { float bx, by, bz; s.position(bx, by, bz); - const uint32 epoch = s.published_at_ms() / 1000u; + // One heading per 8 s window: a new random heading every second zig-zagged the bot inside the liquid. + const uint32 epoch = s.published_at_ms() / 8000u; const uint64 mixed = (uint64(s.bot_id()) * 0x9E3779B97F4A7C15ULL) ^ (uint64(epoch) * 0xBF58476D1CE4E5B9ULL); const float angle = (float(mixed & 0xFFFFu) / 65536.0f) * 6.2831853f; diff --git a/src/modules/PlayerbotV2/Bot/States/Rules/VendorRules.cpp b/src/modules/PlayerbotV2/Bot/States/Rules/VendorRules.cpp index 080d673918..796c45a14b 100644 --- a/src/modules/PlayerbotV2/Bot/States/Rules/VendorRules.cpp +++ b/src/modules/PlayerbotV2/Bot/States/Rules/VendorRules.cpp @@ -535,6 +535,8 @@ bool CriticalRepairGate(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView c ai.crit_repair_reset_episode(); // gear healthy again — fresh episode next time return false; } + // A battleground match owns the bot (BgDispatch, priority 718): a repair walk would pull it off the march every tick. + if (s.in_battleground()) return false; // Futility backoff: the bot was at a vendor making no durability progress // (too poor to repair the rest even after selling trash) and yielded so the // quest funnel could run and earn money. Stay suppressed until the cooldown diff --git a/src/modules/PlayerbotV2/Bot/States/StateBase.h b/src/modules/PlayerbotV2/Bot/States/StateBase.h index ef8c1afb01..2e21f5402f 100644 --- a/src/modules/PlayerbotV2/Bot/States/StateBase.h +++ b/src/modules/PlayerbotV2/Bot/States/StateBase.h @@ -40,7 +40,7 @@ void DispatchAtMailbox (BotAI&, BotSnapshotView, GroupSnapshotView, BotIntentEm void DispatchAtAh (BotAI&, BotSnapshotView, GroupSnapshotView, BotIntentEmitter&); void DispatchDecorating (BotAI&, BotSnapshotView, GroupSnapshotView, BotIntentEmitter&); -// Group threat discipline (State_InCombat.cpp; port of Karrz's ike3-based bots +// Group threat discipline (State_InCombat.cpp; port of Karrz's wow-1.12 // MCRaidHoldDamage). True while this NON-TANK grouped bot must not damage // `target`: the tank has not built its opening lead yet (bounded wait) or // the bot is at/over PlayerbotV2.Threat.MaxRatio of the tank's threat. @@ -50,5 +50,9 @@ void DispatchDecorating (BotAI&, BotSnapshotView, GroupSnapshotView, BotIntentEm bool ThreatHoldActive(BotAI& ai, BotSnapshotView const& s, ObjectGuid target, GroupSnapshotView const* g = nullptr); +// The owner said Stay / Hold and no mob is on this bot: it keeps its spot. Every mover and target picker that would walk the bot +// (melee chase, skull pick, stack / melee-behind positioning) asks this first; a mob that attacks the bot lifts it. +bool HeldByOwner(BotAI const& ai, BotSnapshotView const& s); + } // namespace States } // namespace Playerbot diff --git a/src/modules/PlayerbotV2/Bot/States/State_Dead.cpp b/src/modules/PlayerbotV2/Bot/States/State_Dead.cpp index 61b3e52f77..70737797b2 100644 --- a/src/modules/PlayerbotV2/Bot/States/State_Dead.cpp +++ b/src/modules/PlayerbotV2/Bot/States/State_Dead.cpp @@ -159,7 +159,7 @@ void DispatchDead(BotAI& ai, { group_can_rez = true; break; } } } - // --- Owner orders and wipes (ike3 ReleaseSpiritAction, Karrz's raid rules) --- + // --- Owner orders and wipes (ike3 ReleaseSpiritAction, the owner's raid rules) --- // release_ordered: the owner said "release" (BotCommandParser::OrderRelease). // owner_released: the companion's owner (a group member on our map) is a // ghost on a corpse run; we release and run back with them instead of @@ -208,7 +208,7 @@ void DispatchDead(BotAI& ai, // promptly. The watchdog and the rez-accept wait both key off this cap. constexpr uint32 kGroupRezWaitMs = 90000u; // A raid does not wait the full 90 s: its bots hold the death screen a - // per-bot random 10-40 s for a living healer's resurrect (Karrz's + // per-bot random 10-40 s for a living healer's resurrect (the owner's // ReleaseSpiritAction), then release (Playerbot.Behavior.WipeReleaseWait). const bool raid_wait = group_can_rez && snapshot.is_in_raid() && Services::Config().behavior_wipe_release_wait(); const uint32 raid_wait_ms = 10000u + (uint32(snapshot.bot_id()) * 2246822519u) % 30001u; @@ -221,7 +221,7 @@ void DispatchDead(BotAI& ai, const uint32 release_cap = encounter_wait ? kEncounterWaitMs : raid_wait ? raid_wait_ms : (group_can_rez ? kGroupRezWaitMs : kPreReleaseStallMs); // Wipe chatter: once 80% of the raid on this map is dead, one corpse in - // four says so, at most once per 600 s across the fleet (Karrz: 1 in 4, + // four says so, at most once per 600 s across the fleet (the owner: 1 in 4, // 600 s). Party chat, the same helper as the rez thanks above. if (dead_clock_active && snapshot.is_in_raid() && group.exists() && group.members() && Services::Config().behavior_wipe_release_wait() && !snapshot.is_ghost()) diff --git a/src/modules/PlayerbotV2/Bot/States/State_Idle.cpp b/src/modules/PlayerbotV2/Bot/States/State_Idle.cpp index 00bb3c5396..c68b01afcd 100644 --- a/src/modules/PlayerbotV2/Bot/States/State_Idle.cpp +++ b/src/modules/PlayerbotV2/Bot/States/State_Idle.cpp @@ -1,6 +1,7 @@ #include "../WanderRule.h" #include "StateBase.h" #include "Bot/BotAI.h" +#include "Bot/TownLife.h" #include "Bot/SpellFamily.h" #include "Bot/TankHazardHold.h" #include "Bot/BotSnapshotView.h" @@ -21,7 +22,6 @@ #include "Bot/ConjureGate.h" #include "Bot/RaidFight.h" // CastsInsteadOfSlotWalk: a ranged DPS in reach of its target casts, it does not walk to its slot #include "Bot/CcPick.h" // PickCcTarget - idle:dungeon_auto_cc_script -#include "Bot/CasterStepOut.h" // StepOutFromMob - the dungeon use of ranged spacing (5b) #include "Bot/Battleground/BattlegroundScript.h" #include "Bot/Battleground/BgWaypointRoutes.h" #include "Bot/Battleground/BgAvPlan.h" @@ -31,6 +31,8 @@ #include "../Services.h" #include "Util/ConfigReader.h" // full type for Services::Config() (detour pull-gate knobs) #include "Travel/QuestHubDatabase.h" +#include "Fleet/TownGatherSource.h" +#include "Bot/World/ZonePicker.h" #include "MaintainHelpers.h" // ChunkedWalkToward (idle watch) #include "Travel/RepairVendorIndex.h" #include "Travel/UnifiedTravelGraph.h" @@ -70,6 +72,7 @@ #include "PlayerbotMovement.h" // BotMovement::SehSafeCalculatePath (tile-race guard) #include "PlayerbotAPI.h" // PathBudget::HasBudget (dungeon scan gating) #include +#include #include #include #include @@ -87,6 +90,19 @@ namespace Playerbot::States { // GetIdleConsumeThresholds, ClassOocRez) get `static` for internal // linkage instead of an anonymous namespace. +// The mana wait before a pull. A party with a player in it has none (playtest 2026-10-15: the player watches the mana); a raid keeps it, +// and so does a group of bots alone, where nobody else would hold the pull for the healer's drink (deadmines_full n57: the priest +// went into every fight at 1-5 % mana). +static bool PullManaGate(BotSnapshotView const& s, GroupSnapshotView const& g) +{ + if (s.is_in_raid()) return true; + auto const* members = g.members(); + if (!members) return false; + for (auto const& m : *members) + if (m.online && !m.is_bot) return false; + return true; +} + // Score an item against the bot's spec stat weights. Used by the // equip-upgrade rule (Phase 1 of ITEM_VENDOR_SYSTEM_PLAN.md). Decision // flow: @@ -182,6 +198,8 @@ bool MaintainSoulstone(BotSnapshotView const& s, GroupSnapshotView const& g, { if (InTransitNoMaintenance(s)) return false; if (s.cls() != CLASS_WARLOCK) return false; + // Classic 1.60: idle:classic_soulstone (ClassicUpkeepRules, prio 992) owns the stone; two rules cast it twice. + if (IsVanillaRealm()) return false; constexpr uint32 SOULSTONE = 20707; if (!s.knows_spell(SOULSTONE)) return false; if (!s.is_ready(SOULSTONE)) return false; @@ -473,6 +491,20 @@ bool MaintainConjuredItem(BotSnapshotView const& s, BotAI& ai, BotIntentEmitter& } if (s.cls() == CLASS_MAGE) { + // Vanilla Conjure Water / Conjure Food (found in the spell data). In dungeons / raids + // idle:classic_conjure (ClassicUpkeepRules) covers them, the dungeon hold swallows this rule. + for (auto kind : { Classic::ConsumableKind::Drink, Classic::ConsumableKind::Food }) + { + uint32 const create = Classic::MageConjureSpell(s, kind, kind == Classic::ConsumableKind::Drink ? 20u : 10u); + if (create && s.is_ready(create) + && V2::MayConjure(s.in_combat(), s.recently_in_combat(5000), s.power(POWER_MANA), s.mana_cost(create)) + && !ai.action_recently_tried(BotAI::ActionKind::ClassUpkeep, create, now_ms)) + { + emit.cast(create); + ai.note_action_retry(BotAI::ActionKind::ClassUpkeep, create, now_ms); + return true; + } + } constexpr uint32 CONJURE_REFRESHMENT = 190336; // Conjure Refreshment creates one of several conjured-food entries // depending on client/server version: Pandaria's Conjured Mana Cake @@ -492,9 +524,11 @@ bool MaintainConjuredItem(BotSnapshotView const& s, BotAI& ai, BotIntentEmitter& for (uint32 e : CONJURED_MANA_CAKES) if (s.has_item(e)) { already_have = true; break; } if (!already_have && - s.knows_spell(CONJURE_REFRESHMENT) && s.is_ready(CONJURE_REFRESHMENT)) + s.knows_spell(CONJURE_REFRESHMENT) && s.is_ready(CONJURE_REFRESHMENT) + && !ai.action_recently_tried(BotAI::ActionKind::ClassUpkeep, CONJURE_REFRESHMENT, now_ms)) { emit.cast(CONJURE_REFRESHMENT); + ai.note_action_retry(BotAI::ActionKind::ClassUpkeep, CONJURE_REFRESHMENT, now_ms); return true; } } @@ -526,7 +560,7 @@ static IdleConsumeThresholds GetIdleConsumeThresholds(BotAI const& ai) return {60, 50, 30}; } -// OOC eat / drink to top off HP / mana between pulls (Karrz's +// OOC eat / drink to top off HP / mana between pulls (the owner's // UseFoodStrategy): only when it is safe to sit - nothing attacks the bot and // nobody is fighting within 45 yards - and never while moving or mounted. // Food (health) and drink (mana) are told apart by their spell, so a warrior @@ -985,7 +1019,7 @@ bool MaintainOocHeal(BotSnapshotView const& s, GroupSnapshotView const& g, if (effective_role != Role::Healer) return false; if (!g.exists()) return false; // Classic 1.60 (single-spec class data): the vanilla efficient heal, - // Karrz's heal-target scoring (range, LOS, tank first) and downranking + // the owner's heal-target scoring (range, LOS, tank first) and downranking // to the deficit (Combat/Apl/ApClassicHeal.h). The retail ClassOocHeal // ids (77472 Healing Wave, ...) do not exist for these bots. if (Classic::IsSingleSpecClass(s.cls())) @@ -1079,7 +1113,7 @@ bool MaintainOocRez(BotSnapshotView const& s, GroupSnapshotView const& g, // starting the same 10 s cast (Combat::ClassicHeal::RezTarget). // (Mass Resurrection above is self-cast AoE - left ungated.) constexpr float kRezCastRange = 28.0f; - if (Combat::ClassicHeal::RaidFightLive(g, s.map_id())) return false; // only a druid raises in a live fight + if (Combat::ClassicHeal::RezFightOn(s, g)) return false; // only a druid raises in a live fight const ObjectGuid target = Combat::ClassicHeal::RezTarget(s, g, kRezCastRange, [](GroupMemberSummary const& m) { return ClassOocRez(m.cls) != 0 && m.level >= 10; }); if (target.IsEmpty()) return false; @@ -1090,14 +1124,14 @@ bool MaintainOocRez(BotSnapshotView const& s, GroupSnapshotView const& g, // Raid out-of-combat rez ([raid_rez]). Raid bots out of combat run State_InGroup, not the idle cascade, so idle:ooc_rez (prio 688) // never ran for them: live MC 2026-10-08 the owner died to lava with the raid out of combat, a dozen healers stood 1 y round // the corpse in formation hold and nobody raised him. A rez-capable bot (priest / shaman / paladin) that is alive, out of real -// combat and not casting raises the dead member the group ranks first (the owner, then healers, tanks, the rest). In cast range +// combat and not casting raises the dead member the group ranks first (playtest, then healers, tanks, the rest). In cast range // (28 y, LoS) it casts; otherwise the two rezzers nearest to a corpse within 80 y walk up to it, so one cast is not dogpiled. State_InGroup // calls it before anything else; true = tick consumed. bool RaidOocRez(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const& g, BotIntentEmitter& emit) { if (!s.is_in_raid() || s.in_battleground() || !g.exists() || !g.members()) return false; const uint32 rez = ClassOocRez(s.cls()); - // [raid_rez] skip: a rezzer class with a dead member on its map says why it does not rez (Karrz, MC 2026-10-08: the raid stood + // [raid_rez] skip: a rezzer class with a dead member on its map says why it does not rez (playtest, MC 2026-10-08: the raid stood // around his corpse), at most once per 5 s per bot. auto skip = [&](char const* why) -> bool { @@ -1121,9 +1155,9 @@ bool RaidOocRez(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const& g, if (s.is_casting()) return skip("busy casting"); // The core refuses a rez cast from a bot that is in combat at all (AFFECTING_COMBAT; MC Garr 2026-10-10: healers in combat with the adds // spent the fight on raid:ooc_rez and were refused each time), so the test is the core's own: any combat, stalker-only included. And a - // rez waits for the fight to end while a tank of the group is still in it: the healers heal first (Karrz: rez after the encounter). + // rez waits for the fight to end while a tank of the group is still in it: the healers heal first (the owner: rez after the encounter). if (s.in_combat()) return skip("in combat"); - if (Combat::ClassicHeal::RaidFightLive(g, s.map_id())) return skip("the fight is still on"); + if (Combat::ClassicHeal::RezFightOn(s, g)) return skip("the fight is still on"); if (!rez || s.cls() == CLASS_DRUID) return false; if (!s.knows_spell(rez)) return skip("spell not known"); if (!g.dead_member(s.map_id())) return false; @@ -1180,7 +1214,7 @@ bool RaidOocRez(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const& g, // A corpse in cast range and sight that the shared pick gave to another rezzer: this bot waits where it stands (one rezzer per corpse). if (best_d2 <= 28.0f * 28.0f && Combat::ClassicHeal::InLos(s, target->guid)) return skip("another rezzer takes the corpse in range"); - // Only the two rezzers nearest to that corpse walk. + // Only the rezzer nearest to that corpse walks (one rezzer per corpse; two walked before and only one of them cast). int nearer = 0; for (auto const& m : *g.members()) { @@ -1190,13 +1224,17 @@ bool RaidOocRez(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const& g, const float dx = target->x - m.x, dy = target->y - m.y; if (dx * dx + dy * dy < best_d2) ++nearer; } - if (nearer >= 2) return skip("two other rezzers are nearer the corpse"); + if (nearer >= 1) return skip("another rezzer is nearer the corpse"); const float dist = std::sqrt(best_d2); constexpr float kStandOff = 20.0f; // inside the 28 y cast range with room for the LoS wobble const float k = std::max(0.0f, (dist - kStandOff) / std::max(dist, 1.0f)); + const float wx = bx + (target->x - bx) * k, wy = by + (target->y - by) * k; + // A corpse beside an idle pack (Onyxia's cave whelps after a wipe at the mouth): the walk would pull it. + if (RaidPointInUnpulledReach(s, wx, wy, target->z)) + return skip("the rez spot lies in an unpulled pack's reach"); if (RaidLogDue(RaidLogKey(s, RaidLogKind::ThreatHold), s.published_at_ms(), 5000u)) TC_LOG_INFO("playerbot.v2", "[raid_rez] {} walks {:.0f} y to raise {} ({})", s.name(), dist, target->name, target->is_bot ? "bot" : "player"); - emit.move_to(bx + (target->x - bx) * k, by + (target->y - by) * k, target->z, /*run*/ true); + emit.move_to(wx, wy, target->z, /*run*/ true); ai.set_last_rule_fired("raid:ooc_rez_walk"); return true; } @@ -2135,7 +2173,7 @@ static bool RaidSpacingElite(NearbyUnit const& u) // max level, clamped 5..45, times Rate.Creature.Aggro), tested through // IsWithinDistInMap, which adds both combat reaches - the creature's own // reach cancels the "15 - reach" base, the player's 1.5y stays. Computed from -// the snapshot (the creature's level as this bot sees it) so the AI worker +// the snapshot (the creature's level as this bot sees it) so the bot worker // never reads a creature's aura table; detect-range auras are covered by // kPackAggroMargin. constexpr int kAggroExpansionMaxLevel = 60; // Classic 1.60 @@ -2186,6 +2224,9 @@ static bool UnpulledPackMob(BotSnapshotView const& s, NearbyUnit const& u, Dunge return true; } +// Mobs this close to the one a bot is engaging are its pack: they come with it. +static constexpr float kEngagedPackRadius = 10.0f; + // The unpulled mob (UnpulledPackMob) whose aggro reach + kPackAggroMargin + // extra contains (x, y, z) - 3D, as the core tests it - the one the point is // deepest into. out_d: the point's distance to it; out_reach: its aggro @@ -2193,7 +2234,8 @@ static bool UnpulledPackMob(BotSnapshotView const& s, NearbyUnit const& u, Dunge static NearbyUnit const* UnpulledPackReaching(BotSnapshotView const& s, DungeonAdvice const* advice, float x, float y, float z, float extra, bool need_los, BotAI const* ai, uint32 now_ms, - float* out_d = nullptr, float* out_reach = nullptr) + float* out_d = nullptr, float* out_reach = nullptr, + NearbyUnit const* engaged = nullptr) { // Playerbot.Behavior.PackStop off: no unpulled-reach checks anywhere (the pack stop, pull spot and // pull-from-range rules, and every "never step into an idle pack's reach" filter see no pack). @@ -2203,6 +2245,13 @@ static NearbyUnit const* UnpulledPackReaching(BotSnapshotView const& s, DungeonA for (auto const& u : s.raw().combat.nearby_enemies) { if (!UnpulledPackMob(s, u, advice, need_los, ai, now_ms)) continue; + // The pack the bot is itself engaging (an owner Attack / Pull order picked it): going for it pulls it anyway, so its reach + // is no reason to hold on the ledge. Only the other packs are kept out of. + if (engaged) + { + const float ex = u.x - engaged->x, ey = u.y - engaged->y; + if (u.guid == engaged->guid || ex * ex + ey * ey <= kEngagedPackRadius * kEngagedPackRadius) continue; + } const float reach = PackAggroReach(s, u); const float dx = u.x - x, dy = u.y - y, dz = u.z - z; const float d = std::sqrt(dx * dx + dy * dy + dz * dz); @@ -2222,17 +2271,21 @@ static NearbyUnit const* UnpulledPackReaching(BotSnapshotView const& s, DungeonA // pack's edge may still step along or away from it; it never steps further in. bool RaidPointInUnpulledReach(BotSnapshotView const& s, float x, float y, float z) { - // Raid and 5-man alike (Karrz, Deadmines 2026-10-10: a mage / warlock that was hit ran, and the run took it into the next + // Raid and 5-man alike (playtest, Deadmines 2026-10-10: a mage / warlock that was hit ran, and the run took it into the next // pack, which pulled too). if (!s.is_in_instance() || s.in_battleground()) return false; const uint32 now_ms = s.published_at_ms(); float pd = 0.f, pr = 0.f; - NearbyUnit const* pack = UnpulledPackReaching(s, nullptr, x, y, z, 0.0f, /*need_los=*/false, nullptr, now_ms, &pd, &pr); + NearbyUnit const* engaged = nullptr; + if (!s.victim().IsEmpty()) + for (auto const& e : s.raw().combat.nearby_enemies) + if (e.guid == s.victim() && e.hp > 0) { engaged = &e; break; } + NearbyUnit const* pack = UnpulledPackReaching(s, nullptr, x, y, z, 0.0f, /*need_los=*/false, nullptr, now_ms, &pd, &pr, engaged); if (!pack) return false; float bx, by, bz; s.position(bx, by, bz); float sd = 0.f, sr = 0.f; - const bool refused = !UnpulledPackReaching(s, nullptr, bx, by, bz, 0.0f, /*need_los=*/false, nullptr, now_ms, &sd, &sr) || + const bool refused = !UnpulledPackReaching(s, nullptr, bx, by, bz, 0.0f, /*need_los=*/false, nullptr, now_ms, &sd, &sr, engaged) || (pr - pd) > (sr - sd) + 0.5f; if (refused && RaidLogDue(RaidLogKey(s, RaidLogKind::Los) ^ 0x70616b72u, now_ms, 4000u)) TC_LOG_INFO("playerbot.v2", "[move_refused] {} will not step to ({:.0f},{:.0f}): {:.0f} y from idle entry {} (aggro reach {:.0f} y + margin)", @@ -2392,7 +2445,7 @@ static std::string HazardSpellName(uint32 spell_id) return std::string{ (*si->SpellName)[sWorld->GetDefaultDbcLocale()] }; } -// Stand-point validation. These rules run on the AI worker from the snapshot +// Stand-point validation. These rules run on the bot worker from the snapshot // and the snapshot carries no navmesh query, so this uses the idiom the // dungeon steppers in this file already use from the worker // (DungeonTargetReachableAndStep, the rejoin / converge / regroup steps): a @@ -2578,9 +2631,12 @@ static char const* RaidRangedSlotInvalid(Player* self, GroupMemberSummary const& // mob), and the pre-pull spots kPrePullMinSpacing (6 y) on three (22 / 28 / // 34 y behind the anchor, +-90 deg). // Defaults at the "close" preset (4 y); the owner's spacing preset (BotAI::formation_spacing_scale: tight .625, -// close 1, spread 2) scales it. Karrz 2026-10-06: the 5-6 y arcs left the raid far too spread out. -constexpr float kRaidRangedMinSpacing = 3.5f; -constexpr float kRaidRangedArcMax = 2.0944f; // +-120 deg +// close 1, spread 2) scales it. The owner 2026-10-06: the 5-6 y arcs left the raid far too spread out. +constexpr float kRaidRangedMinSpacing = 3.0f; +// The owner 2026-10-12: the raid spread over a large area in boss fights and pulled extra packs. Three tight rows (22 y, one spacing in, one +// spacing out) over +-50 deg hold about 33 ranged / healers in a block roughly 30 y wide and 7 deep; the old two rows over +-120 deg +// put the same raid on a 90 y arc. +constexpr float kRaidRangedArcMax = 0.8727f; // +-50 deg static bool GroupRangedOrHealer(GroupMemberSummary const& m) { if (m.role == Role::Tank) return false; @@ -2752,8 +2808,43 @@ static bool RaidRangedApproachTank(BotSnapshotView const& s, BotAI& ai, // Own slot: 22 y arc first, then the 17 y one (both within 30 y of the // tank's mob), neighbours kRaidRangedMinSpacing apart (RaidRangedArcSlot). const float ranged_spacing = std::max(2.0f, kRaidRangedMinSpacing * ai.formation_spacing_scale()); - RaidArcSlot const as = RaidRangedArcSlot(s, g, { kRaidRangedStandOff, kRaidRangedStandOff - ranged_spacing }, - ranged_spacing, kRaidRangedArcMax); + // An avoid circle round the fight's enemy (Geddon's 24 y ranged / healer circle, the Inferno in progress) blocks every stand point + // inside its radius plus the hazard margin, and the tank stands up to 15 y in front of the enemy, so rows measured from the tank landed + // 13-20 y from it (MC Geddon 2026-10-12, 27 Inferno deaths) or inside the circle and were all refused. With such a circle near the tank the + // rows are measured from its centre instead and start outside it (boss distance = row radius on the whole arc), as far as the 30 y spells + // reach (kRaidSlotSpellReach), on a wider arc (+-70 deg) so two rows still hold the raid. + float cx = tk.x, cy = tk.y; + float row0 = kRaidRangedStandOff; + float arc_max = kRaidRangedArcMax; + bool boss_rows = false; + if (Services::Config().behavior_avoid_circles()) + { + PveOrder const& po = s.raw().pve_order; + if (po.active) + for (size_t i = 0; i < std::min(po.avoid_circle_count, po.avoid_circles.size()); ++i) + { + PveOrder::AvoidCircle const& c = po.avoid_circles[i]; + const float need = c.r + kHazardMargin + 1.0f; + if (need <= row0 || need > kRaidSlotSpellReach - 5.0f) continue; + const float ctx = c.x - tk.x, cty = c.y - tk.y; + if (ctx * ctx + cty * cty > 15.0f * 15.0f) continue; + if (fight) + { + const float cfx = c.x - fight->x, cfy = c.y - fight->y; + if (cfx * cfx + cfy * cfy > 4.0f * 4.0f) continue; + } + row0 = need; cx = c.x; cy = c.y; boss_rows = true; + } + } + RaidArcSlot as; + if (boss_rows) + { + arc_max = 1.2217f; + as = RaidRangedArcSlot(s, g, { row0, row0 + ranged_spacing }, ranged_spacing, arc_max); + } + else + as = RaidRangedArcSlot(s, g, { kRaidRangedStandOff, kRaidRangedStandOff - ranged_spacing, kRaidRangedStandOff + ranged_spacing }, + ranged_spacing, arc_max); const float slot = as.angle, step = as.step, ar = as.radius; struct Cand { float a, r; bool own; }; Cand cands[5 + std::size(kRaidStandBearings)]; @@ -2771,8 +2862,8 @@ static bool RaidRangedApproachTank(BotSnapshotView const& s, BotAI& ai, auto point = [&](Cand const& c, float& px, float& py) { const float co = std::cos(c.a), sn = std::sin(c.a); - px = tk.x + (dx * co - dy * sn) * c.r; - py = tk.y + (dx * sn + dy * co) * c.r; + px = cx + (dx * co - dy * sn) * c.r; + py = cy + (dx * sn + dy * co) * c.r; }; if (slot_tolerance > 0.0f) { @@ -2873,7 +2964,7 @@ static bool RaidRangedApproachTank(BotSnapshotView const& s, BotAI& ai, return false; } -// In-fight formation (Karrz, MC Gehennas 2026-10-08: "some way of keeping a formation so we can pull them back and forward"): +// In-fight formation (playtest, MC Gehennas 2026-10-08: "some way of keeping a formation so we can pull them back and forward"): // while the anchor tank fights, a raid ranged DPS / healer keeps its own arc slot (RaidRangedArcSlot, kRaidRangedStandOff behind the // tank, away from its mob) and re-takes it once the tank (the boss pulled back, kited or repositioned) has moved it more than // kFormationSlack away. Slots are spaced like the converge arcs and honour the owner's spacing preset. Returns true when it emitted @@ -2971,9 +3062,9 @@ bool RaidFormationHold(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView co constexpr float kPrePullPackRange = 40.0f; // a pack this near the tank is the next pull constexpr float kPrePullPackClear = 30.0f; // spot stays this far from the pack (aggro / pull range) constexpr float kPrePullInPlace = 5.0f; // within this of a spot = in place -constexpr float kPrePullMinSpacing = 4.0f; // raid ranged pre-pull slots: neighbours this far apart -constexpr float kPrePullArcRowGap = 6.0f; // ... and the arcs (rows) this far apart radially -constexpr float kPrePullArcMax = 1.5708f; // +-90 deg off straight back (the arcs never wrap toward the pack) +constexpr float kPrePullMinSpacing = 3.0f; // raid ranged pre-pull slots: neighbours this far apart +constexpr float kPrePullArcRowGap = 4.0f; // ... and the arcs (rows) this far apart radially +constexpr float kPrePullArcMax = 1.0472f; // +-60 deg off straight back (the arcs never wrap toward the pack) constexpr float kPrePullRaidInPlace = 3.5f; // raid ranged: in place within this of its own spot (the walkable // probe ends within 3 y of it) - tighter than kPrePullInPlace so // two neighbours "in place" stay apart @@ -3027,6 +3118,7 @@ static PrePullSpacing RaidPrePullSpacing(BotSnapshotView const& s, BotAI& ai, Gr { // Playerbot.Behavior.RaidSpacing off: no pre-pull fan-out (ranged / healers regroup as before). if (!Services::Config().behavior_raid_spacing()) return PrePullSpacing::Inactive; + if (!s.is_in_raid()) return PrePullSpacing::Inactive; // a 5-man party does not fan out before a pull if (role == PrePullRole::None) return PrePullSpacing::Inactive; if (tk.in_combat || s.in_combat() || s.is_casting()) return PrePullSpacing::Inactive; // A healer under the pull-ready mana stands and drinks (idle:dungeon_healer_drink needs it still): the tank's pull is @@ -3275,18 +3367,36 @@ static TankHazardStep RaidTankHazardStepOut(BotSnapshotView const& s, BotAI& ai, return TankHazardStep::Stay; }; + // Every stay below is bounded: a tank that has held its spot kStayCapMs in a row (a gap of kStayGapMs resets the clock) steps out + // even though a mob is still casting (a pack caster bolting the tank kept it in the fire for the whole fight). + constexpr uint32 kStayCapMs = 4000u, kStayGapMs = 2500u; + static std::mutex s_stay_mu; + static std::unordered_map> s_stay_clock; // tank guid -> first stay, last stay + auto stay_cap_open = [&]() -> bool + { + std::lock_guard lk(s_stay_mu); + auto [it, inserted] = s_stay_clock.try_emplace(me.GetCounter(), std::pair{ now_ms, now_ms }); + if (!inserted) + { + if (now_ms - it->second.second > kStayGapMs) it->second.first = now_ms; + if (now_ms - it->second.first < kStayCapMs) it->second.second = now_ms; + } + return now_ms - it->second.first < kStayCapMs; + }; + PveOrder const& po = s.raw().pve_order; for (size_t i = 0; i < nh; ++i) { // Held for a cast that depends on the mob's facing, never for one that lands on the tank's own spot (TankHazardHold.h). if (held[i]->is_casting && - TankHoldsWhileMobCasts(SpellFamily::Same(held[i]->casting_spell_id, in.spell_id), CastIsGroundAreaOnTarget(held[i]->casting_spell_id))) + TankHoldsWhileMobCasts(SpellFamily::Same(held[i]->casting_spell_id, in.spell_id), CastIsGroundAreaOnTarget(held[i]->casting_spell_id)) && + stay_cap_open()) return stay("mob_casting", held[i]); - if (po.active && po.claimed_by_other_tank(held[i]->guid)) return stay("claimed_by_other_tank", held[i]); + if (po.active && po.claimed_by_other_tank(held[i]->guid) && stay_cap_open()) return stay("claimed_by_other_tank", held[i]); } if (NearbyUnit const* v = s.victim_info(); v && v->victim == me) for (AuraEntry const& a : s.raw().auras.victim_auras) - if (!a.caster.IsEmpty() && a.caster != me && IsTauntSpell(a.spell_id)) + if (!a.caster.IsEmpty() && a.caster != me && IsTauntSpell(a.spell_id) && stay_cap_open()) return stay("other_tank_taunt", v); // Raid members (non-tanks) the mobs must not face; another tank casting @@ -3302,7 +3412,7 @@ static TankHazardStep RaidTankHazardStepOut(BotSnapshotView const& s, BotAI& ai, const bool m_tank = m.role == Role::Tank || IsTankSpec(m.cls, uint16(m.spec)); if (m_tank) { - if (m.is_casting && is_held(m.casting_target)) + if (m.is_casting && is_held(m.casting_target) && stay_cap_open()) return stay("other_tank_casting_on_mob", nullptr); continue; } @@ -3664,7 +3774,7 @@ bool RaidCastLosStep(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView cons dx /= dist; dy /= dist; const uint32 now_ms = s.published_at_ms(); // Ranged DPS and healers hold their spot while the target is in sight; a sight line lost for under kLosGraceMs is a mob - // moving past a corner, not a reason to walk (Karrz, Deadmines 2026-10-10: Ulfrico chased the mobs all over the room, 16 y + // moving past a corner, not a reason to walk (playtest, Deadmines 2026-10-10: Ulfrico chased the mobs all over the room, 16 y // steps toward the tank every time the line flickered). Only a sustained loss steps. constexpr uint32 kLosGraceMs = 2500u; if (uint32 const lost_for = human ? LosLostFor(s.guid(), now_ms) : kLosGraceMs; lost_for < kLosGraceMs) @@ -3685,6 +3795,9 @@ bool RaidCastLosStep(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView cons static constexpr float kLosBearings[] = { 0.0f, 0.5236f, -0.5236f, 1.0472f, -1.0472f, 1.5708f, -1.5708f }; constexpr float kClearOfElite = kRaidRangedTooClose + 2.0f; Player* self = ObjectAccessor::FindConnectedPlayer(s.raw().guid); + // Which filter threw out each bearing, for the "no walkable step" line (Deadmines 2026-10-15 n43: the priest stood 80 s + // without a sight line to the tank and the log could not say what held it). + uint32 rej_elite = 0, rej_hazard = 0, rej_arc = 0, rej_dungeon = 0, rej_walk = 0, rej_refused_move = 0; for (float a : kLosBearings) { const float c = std::cos(a), sn = std::sin(a); @@ -3698,29 +3811,32 @@ bool RaidCastLosStep(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView cons const float ux = px - u.x, uy = py - u.y; if (ux * ux + uy * uy < kClearOfElite * kClearOfElite) { clear = false; break; } } - if (!clear) continue; + if (!clear) { ++rej_elite; continue; } if (RaidPointBlocked(s, px, py, pz, kHazardMargin) || - RaidPointInUnpulledReach(s, px, py, pz)) continue; // nor into an idle pack's reach + RaidPointInUnpulledReach(s, px, py, pz)) { ++rej_hazard; continue; } // nor into an idle pack's reach // Never into a tanked boss's front arc: the cone sidestep would take // it straight back out of LoS (a two-rule ping-pong). { float ad2, afx, afy; - if (FrontArcBossAt(s, g, px, py, ad2, afx, afy)) continue; + if (FrontArcBossAt(s, g, px, py, ad2, afx, afy)) { ++rej_arc; continue; } } - if (DungeonStepRefused(s, ai, px, py, pz, now_ms)) continue; + if (DungeonStepRefused(s, ai, px, py, pz, now_ms)) { ++rej_dungeon; continue; } G3D::Vector3 end; float len = 0.0f; if (!RaidStandPointWalkable(self, px, py, pz, /*check_detour*/ true, end, len)) + { + ++rej_walk; continue; + } if (RaidPointBlocked(s, end.x, end.y, end.z, kHazardMargin) || - RaidPointInUnpulledReach(s, end.x, end.y, end.z)) continue; // nor into an idle pack's reach - if (DungeonStepRefused(s, ai, end.x, end.y, end.z, now_ms)) continue; + RaidPointInUnpulledReach(s, end.x, end.y, end.z)) { ++rej_hazard; continue; } // nor into an idle pack's reach + if (DungeonStepRefused(s, ai, end.x, end.y, end.z, now_ms)) { ++rej_dungeon; continue; } if (DungeonMoveOwnedElsewhere(s, ai, end.x, end.y, end.z, now_ms, "raid:los_step")) { ai.set_last_rule_fired("raid:los_step_hold"); return true; } - if (!emit.move_to(end.x, end.y, end.z, /*run*/ true)) continue; + if (!emit.move_to(end.x, end.y, end.z, /*run*/ true)) { ++rej_refused_move; continue; } ai.note_move_commit(s.map_id(), end.x, end.y, end.z, now_ms); ai.set_last_rule_fired("raid:los_step"); if (RaidLogDue(RaidLogKey(s, RaidLogKind::Los), now_ms, 3000u)) @@ -3771,8 +3887,10 @@ bool RaidCastLosStep(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView cons } if (RaidLogDue(RaidLogKey(s, RaidLogKind::Los), now_ms, 3000u)) TC_LOG_INFO("playerbot.v2", - "[raid_los] {} has no line of sight to its {} but no walkable step clear of the splash / hazards", - s.name(), what); + "[raid_los] {} has no line of sight to its {} but no walkable step clear of the splash / hazards " + "(bearings thrown out: near an engaged elite {}, hazard / idle pack {}, boss front arc {}, dungeon step {}, not walkable {}, move refused {}; " + "{:.0f}y from the anchor, anchor at ({:.1f},{:.1f},{:.1f}))", + s.name(), what, rej_elite, rej_hazard, rej_arc, rej_dungeon, rej_walk, rej_refused_move, dist, ax, ay, az); return false; } @@ -3790,7 +3908,8 @@ bool RaidCastLosStep(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView cons static bool RaidFrontalConeStep(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const& g, BotIntentEmitter& emit, uint32 now_ms) { - if (!InstanceRangedOrHealer(s, ai) || s.is_casting() || s.is_rooted()) return false; + // Raid only: a 5-man party does not sidestep cones. + if (!s.is_in_raid() || !InstanceRangedOrHealer(s, ai) || s.is_casting() || s.is_rooted()) return false; // A map with raid rules lists the cones its encounters really have (Raid::RulesForMap -> avoidFrontal) and the raid brain // steps bots out of them. This generic step treats every tanked elite as a cone mob: on a Molten Giant (Smash is a // point-blank blast, Knock Away hits the tank) casters inside 16 y found no flank outside the Giant's avoid ring and @@ -3853,75 +3972,6 @@ static bool RaidFrontalConeStep(BotSnapshotView const& s, BotAI& ai, GroupSnapsh return false; } -// Dungeon disperse / kite step (AzerothCore disperse + "enemy too close" ideas, see Bot/PositioningGates.h). Ranged DPS and healers -// of a 5-man step off a mob fighting the group that stands within Positioning::kRangedTooCloseToMob of them, and every ranged non-tank -// keeps Positioning::kRangedDisperse x formation spacing from the nearest member. Raid maps -// (rules, ranged arc, spread rules) are left to the raid layer. -static bool DungeonDisperseStep(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const& g, - BotIntentEmitter& emit, uint32 now_ms) -{ - constexpr uint64 kDisperseKey = 5; - if (s.is_in_raid() || !s.is_in_dungeon() || !s.in_combat() || s.is_casting() || s.is_rooted() || s.raw().movement.is_moving) - return false; - Role const role = ai.effective_role(s); - if (role == Role::Tank) return false; - bool const ranged = InstanceRangedOrHealer(s, ai); - // A melee bot stepping 4 y off its target would leave melee range and walk back: only ranged DPS and healers disperse here. - if (!ranged) return false; - float bx, by, bz; s.position(bx, by, bz); - // Points to get away from: a mob fighting the group within 5 y (ranged / healers only; not the mob this bot melees or tanks) - // and the nearest member within the disperse distance. - std::vector> away; - if (ranged) - for (auto const& u : s.raw().combat.nearby_enemies) - { - if (u.hp <= 0 || u.untargetable || u.is_pacified || u.victim.IsEmpty() || u.victim == s.guid()) continue; - const float dx = u.x - bx, dy = u.y - by; - if (dx * dx + dy * dy < Positioning::kRangedTooCloseToMob * Positioning::kRangedTooCloseToMob) - away.emplace_back(u.x, u.y); - } - const float want = (ranged ? Positioning::kRangedDisperse : Positioning::kMeleeDisperse) * ai.formation_spacing_scale(); - if (auto const* mems = g.members()) - for (GroupMemberSummary const& m : *mems) - { - if (!m.online || !m.is_alive || m.guid == s.guid() || m.map_id != s.map_id()) continue; - const float dx = m.x - bx, dy = m.y - by; - if (dx * dx + dy * dy < want * want) away.emplace_back(m.x, m.y); - } - if (away.empty()) return false; - if (ai.action_recently_tried(BotAI::ActionKind::RaidSpacing, kDisperseKey, now_ms)) return false; - ai.note_action_retry(BotAI::ActionKind::RaidSpacing, kDisperseKey, now_ms); - - Player* self = ObjectAccessor::FindConnectedPlayer(s.raw().guid); - constexpr float kStep = 4.0f; - float best_score = -1.0f, best_angle = 0.0f; - G3D::Vector3 best_end; - for (int i = 0; i < 12; ++i) - { - const float a = float(i) * 0.5235988f; // 30 deg bearings - if (Positioning::FleeMemory::Reverses(s.guid().GetCounter(), a, now_ms)) continue; - const float px = bx + std::cos(a) * kStep, py = by + std::sin(a) * kStep; - float score = 1e9f; // distance to the nearest thing to get away from, after the step - for (auto const& w : away) - score = std::min(score, std::hypot(px - w.first, py - w.second)); - if (score <= best_score) continue; - if (RaidPointBlocked(s, px, py, bz, kHazardMargin) || RaidPointInUnpulledReach(s, px, py, bz)) continue; - if (DungeonStepRefused(s, ai, px, py, bz, now_ms)) continue; - G3D::Vector3 end; float len = 0.0f; - if (!RaidStandPointWalkable(self, px, py, bz, /*check_detour*/ true, end, len)) continue; - best_score = score; best_angle = a; best_end = end; - } - // Only a step that actually gains distance (the starting nearest distance is min over `away` from here). - float now_nearest = 1e9f; - for (auto const& w : away) now_nearest = std::min(now_nearest, std::hypot(bx - w.first, by - w.second)); - if (best_score < 0.0f || best_score <= now_nearest + 0.5f) return false; - if (!emit.move_to(best_end.x, best_end.y, best_end.z, /*run*/ false)) return false; - Positioning::FleeMemory::Note(s.guid().GetCounter(), best_angle, now_ms); - ai.note_move_commit(s.map_id(), best_end.x, best_end.y, best_end.z, now_ms); - ai.set_last_rule_fired("idle:dungeon_disperse"); - return true; -} - bool DungeonCombatPositioning(BotSnapshotView const& s, BotAI& ai, GroupSnapshotView const& g, BotIntentEmitter& emit, @@ -3970,7 +4020,7 @@ bool DungeonCombatPositioning(BotSnapshotView const& s, BotAI& ai, // repair to a high-priority preempt: OOC with any equipped piece under 60% // durability, self-repair BEFORE doing anything else. emit.repair_all(Empty) // routes to API's self-repair branch (no vendor; stipend top-up makes it free - // for AI bots). The retry throttle makes it one tick of repair then the bot + // for bot logic bots). The retry throttle makes it one tick of repair then the bot // proceeds, so it never blocks progression. OOC-gated so it never interrupts a // fight. General (all roles/dungeons) — a 0%-durability DPS is dead weight too. if (s.is_alive() && !s.in_combat() && @@ -4437,7 +4487,7 @@ bool DungeonCombatPositioning(BotSnapshotView const& s, BotAI& ai, // The boss is a long fight: the mana users drink to the pull-ready mark before it too, not only the healer // (deadmines_full@sneed: mage 2%, hunter 11% when the tank died). Bounded below so a bot that cannot drink // never freezes the pull. - if (m.max_mana > 0 && Services::Config().behavior_pull_recover() && + if (PullManaGate(s, g) && m.max_mana > 0 && Services::Config().behavior_pull_recover() && int64(m.mana) * 100 < int64(m.max_mana) * Classic::kPullReadyDpsManaPct) { ++boss_dps_dry; @@ -4450,7 +4500,7 @@ bool DungeonCombatPositioning(BotSnapshotView const& s, BotAI& ai, const float mdx = m.x - sx0, mdy = m.y - sy0; const float d2 = mdx * mdx + mdy * mdy; if (d2 < healer_d2) healer_d2 = d2; - if (m.max_mana > 0 && int64(m.mana) * 100 < int64(m.max_mana) * Classic::PullReadyHealerManaPct(s)) + if (PullManaGate(s, g) && m.max_mana > 0 && int64(m.mana) * 100 < int64(m.max_mana) * Classic::PullReadyHealerManaPct(s)) { healer_dry = true; healer_dry_name = m.name; @@ -5606,7 +5656,7 @@ bool DungeonCombatPositioning(BotSnapshotView const& s, BotAI& ai, // spell listed in advice.stack_on_cast_spells, non-tanks move to stack on // the closest tank ally. Only fires while the cast is in flight. if (!advice.stack_on_cast_spells.empty() && - ai.effective_role(s) != Role::Tank) + ai.effective_role(s) != Role::Tank && !HeldByOwner(ai, s)) { bool cast_in_flight = false; for (auto const& u : s.raw().combat.nearby_enemies) @@ -5649,10 +5699,6 @@ bool DungeonCombatPositioning(BotSnapshotView const& s, BotAI& ai, if (s.is_alive() && RaidFrontalConeStep(s, ai, g, emit, now_ms)) return true; - // (5a') Dungeon disperse / kite (Positioning): off a mob fighting the group, and a few yards from the nearest member. - if (s.is_alive() && DungeonDisperseStep(s, ai, g, emit, now_ms)) - return true; - // (5b) Raid ranged spacing. Ranged DPS and healers have no business in // a raid mob's melee AoE (the Molten Giant's Stomp wiped the PC's first // MC pull with casters stacked on the tank). When engaged elites that are @@ -5668,28 +5714,9 @@ bool DungeonCombatPositioning(BotSnapshotView const& s, BotAI& ai, // +-60 deg) must stay clear of every engaged elite and pass the navmesh // probe (RaidStandPointWalkable) - the old blind step along the mob->bot // line at the bot's own Z could land in MC lava or a wall. - // A 5-man instance party's ranged / healers keep the same distance from the engaged CASTERS (Bot/CasterStepOut.h; Deadmines - // 2026-10-09: the mage stood 1.5 y from the Defias Evoker): same stand-off, hazard and walkability checks, same - // Playerbot.Behavior.RaidSpacing switch. - bool const dungeon_casters = !s.is_in_raid() && s.is_in_dungeon() && !s.in_battleground() && - Services::Config().behavior_raid_spacing() && InstanceRangedOrHealer(s, ai); - auto const spacing_mob = [&](NearbyUnit const& u) -> bool - { - if (!dungeon_casters) - return RaidSpacingElite(u); - StepOutMob m; - m.alive = u.hp > 0; - m.is_player = u.is_player; - m.targetable = !u.untargetable; - m.in_combat = u.unit_in_combat; - ThreatVictim const k = ThreatVictim(u.victim_kind); - m.held_by_tank_or_member = k == ThreatVictim::Tank || k == ThreatVictim::Member || k == ThreatVictim::MemberPet; - m.casting_now = u.is_casting; - for (uint32_t e : advice.high_priority_kill_entries) - if (e == u.entry) { m.listed_caster = true; break; } - return StepOutFromMob(m); - }; - if ((RaidRangedOrHealer(s, ai) || dungeon_casters) && !s.is_casting()) + // Raid only: a 5-man party's casters stand where they cast (no step-out from mobs, no disperse), the party keeps to four orders. + auto const spacing_mob = [&](NearbyUnit const& u) -> bool { return RaidSpacingElite(u); }; + if (RaidRangedOrHealer(s, ai) && !s.is_casting()) { float bx_rs, by_rs, bz_rs; s.position(bx_rs, by_rs, bz_rs); float cx_rs = 0.f, cy_rs = 0.f, near_d2 = kRaidRangedTooClose * kRaidRangedTooClose; @@ -5757,6 +5784,12 @@ bool DungeonCombatPositioning(BotSnapshotView const& s, BotAI& ai, RaidPointInUnpulledReach(s, end.x, end.y, end.z)) continue; // nor into an idle pack's reach if (RaidBeyondStayNear(s, end.x, end.y)) continue; if (DungeonStepRefused(s, ai, end.x, end.y, end.z, now_ms)) continue; + // The step back keeps sight of the fight (the elites' centre): a caster or healer stepped out of line of sight, and the + // LoS step then walked it back in (Deadmines 2026-10-15). + if (self_rs && !self_rs->GetMap()->isInLineOfSight(self_rs->GetPhaseShift(), end.x, end.y, end.z + 2.0f, + cx_rs, cy_rs, bz_rs + 2.0f, + LINEOFSIGHT_ALL_CHECKS, VMAP::ModelIgnoreFlags::M2)) + continue; if (!emit.move_to(end.x, end.y, end.z, /*run*/ true)) continue; ai.set_last_rule_fired("raid:ranged_spacing"); if (ai.raid_pos_diag_due(now_ms)) @@ -5775,7 +5808,7 @@ bool DungeonCombatPositioning(BotSnapshotView const& s, BotAI& ai, } } - // (5b2) Raid ranged / healer clump separation (Karrz, MC Molten Giants 2026-10-08: ranged and healers stacked in one + // (5b2) Raid ranged / healer clump separation (playtest, MC Molten Giants 2026-10-08: ranged and healers stacked in one // clump regardless of the follow distance). In a fight, a ranged / healer bot with another group member inside // kRaidClumpApart steps ~kRaidClumpStep away from the neighbours' centroid (the pack's spells and the 40y heals still // reach). Skipped when the raid brain has a move for this bot (an encounter that stacks or spreads on purpose), mid-cast, @@ -5888,7 +5921,7 @@ bool DungeonCombatPositioning(BotSnapshotView const& s, BotAI& ai, // IsMeleeClass) — only confirmed melee specs reposition. if (!s.is_casting() && !s.victim().IsEmpty() && - ai.effective_role(s) != Role::Tank) + ai.effective_role(s) != Role::Tank && !HeldByOwner(ai, s)) { const uint8 cls_bp = s.raw().identity.cls; const uint32 spec_bp = s.spec(); @@ -5951,7 +5984,6 @@ bool DungeonCombatPositioning(BotSnapshotView const& s, BotAI& ai, { ai.note_action_retry(BotAI::ActionKind::WanderToNode, reposition_key, now_ms); - Positioning::FleeMemory::Note(s.guid().GetCounter(), std::atan2(aim_y - by_bp, aim_x - bx_bp), now_ms); ai.set_last_rule_fired("idle:melee_behind"); return true; } @@ -5976,13 +6008,13 @@ static void BgRouteMove(BotSnapshotView const& s, BotAI const& ai, BotIntentEmit float bx = 0.f, by = 0.f, bz = 0.f; s.position(bx, by, bz); float nx = 0.f, ny = 0.f, nz = 0.f; - // Route variety (Karrz: bots ran one straight lane): each bot weighs the recorded paths differently, and the choice shifts with + // Route variety (the owner: bots ran one straight lane): each bot weighs the recorded paths differently, and the choice shifts with // every cap (score total), so flag runs take different tunnels / graveyard jumps / roofs from run to run and bot to bot. int const route_variant = int(((uint32(s.guid().GetCounter()) * 2654435761u >> 11) + (s.raw().bg.score_alliance + s.raw().bg.score_horde) * 3u) % uint32(BgRoutes::Graph::kVariants)); // A flag carrier always flanks: variant 0 is the plain shortest lane its chasers expect. int const carrier_variant = s.bg_friendly_flag_carrier() == s.guid() ? 1 + route_variant % (BgRoutes::Graph::kVariants - 1) : route_variant; - // Lane (Karrz, WSG 2026-10-09: "straight out the tunnel and straight back"): every bot takes one of the recorded ways across the + // Lane (playtest, WSG 2026-10-09: "straight out the tunnel and straight back"): every bot takes one of the recorded ways across the // field, picked by a per-bot hash that shifts with each cap. Flag carriers only take the flanking lanes (a defended flag room is // not entered through the mid line). The lane is forced through its recorded path by BgRoutes::NextWaypointLane. bool const is_carrier = s.bg_friendly_flag_carrier() == s.guid(); @@ -5990,7 +6022,7 @@ static void BgRouteMove(BotSnapshotView const& s, BotAI const& ai, BotIntentEmit auto const& lanes_here = BgRoutes::LanesFor(s.raw().bg.current_type_id, x > bx, is_carrier); BgRoutes::Lane const* lane = BgRoutes::PickLane(lanes_here, lane_selector); // Lane variety is for open travel. A bot on the graveyard ridge with enemy players at the foot of the drop goes over the ledge to - // them (Karrz, WSG 2026-10-09: the whole rez wave took the long way round while the fight was below). Carriers keep their flank pick. + // them (playtest, WSG 2026-10-09: the whole rez wave took the long way round while the fight was below). Carriers keep their flank pick. if (!is_carrier && s.in_battleground() && !s.bg_in_prep()) { BgRoutes::LanePoint landing{}; @@ -6755,7 +6787,7 @@ static DungeonDetourVerdict DungeonTankDetour(Player* tank, // fix, 2026-07-03): PathBudget's window is opened/closed only around // DrainIntents on the WORLD thread (BotIntentExecutor.cpp); HasBudget // FAILS OPEN (always true, no bound) when that window is not active — - // which is the case for the AI worker threads these dungeon rules + // which is the case for the bot worker threads these dungeon rules // actually run on. So this only bounds aggregate probe cost within a // DrainIntents world-thread tick; it does NOT cap probe frequency on a // worker tick, and callers here still need their own cadence/prefilter. @@ -7776,22 +7808,24 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, // In range. Cross-caster dedup so multiple rezzers don't // all start an 8-10s OOC rez on the same corpse (only the // first lands). Mirrors MaintainOocRez's known-rez check. - bool another = false; - if (auto const* mems = g.members()) - for (auto const& m : *mems) - { - if (m.guid == s.guid()) continue; - if (!m.is_casting) continue; - if (m.casting_target != dead->guid) continue; - switch (m.casting_spell) + // The same claim rules as Combat::ClassicHeal::RezTarget: an offer already pending claims the corpse, and + // a rez in flight does too unless it recently failed or its cast is stuck (IsRezSpell covers Rebirth). + bool another = dead->rez_pending; + if (!another) + if (auto const* mems = g.members()) + for (auto const& m : *mems) { - case 2006: case 50769: case 2008: - case 7328: case 115178: case 361227: - another = true; break; - default: break; + if (m.guid == s.guid()) continue; + if (!m.is_casting) continue; + if (m.casting_target != dead->guid) continue; + if (Combat::ClassicHeal::IsRezSpell(m.casting_spell) && + !Combat::ClassicHeal::RezClaims::RecentlyFailed(m.guid, dead->guid, s.published_at_ms()) && + !Combat::ClassicHeal::RezCastStuck(m, dead->guid, s.published_at_ms())) + { + another = true; + break; + } } - if (another) break; - } // The core refused the last rez on this corpse (Deadmines 2026-10-10: LINE_OF_SIGHT, the priest stood // 20 y off behind a wall and re-cast): the snapshot has no sight line to a corpse, so the refusal is // the signal - walk up to the body, then cast again once the refusal window (6 s) has passed. @@ -8379,6 +8413,8 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, constexpr float kStrandedY = 60.0f; uint32 others = 0, others_near = 0, others_stranded = 0, dps_low_mana = 0; bool healer_low_mana = false; + bool healer_far = false; // held below, for at most kPullPositionHoldCapMs + decltype(mems->data()) hp_low_member = nullptr; // the first member under the HP mark for (auto const& m : *mems) { if (!m.online) continue; @@ -8391,7 +8427,12 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, if (m.map_id != s.map_id()) continue; if (m.max_hp > 0 && (int64(m.hp) * 100) < (int64(m.max_hp) * ready_hp_pct)) - return false; + { + // Held below, for at most the cap: a member the healers cannot or will not top off (out of their reach, or hurt by + // something that keeps ticking) must not freeze the raid for good (MC Ragnaros 2026-10-13 4839bcf3: the whole raid on + // "waiting_for=member_hp" for 90 s with nobody fighting). + if (!hp_low_member) hp_low_member = &m; + } const float dxg = m.x - bx_ga; const float dyg = m.y - by_ga; const float d2g = dxg*dxg + dyg*dyg; @@ -8414,10 +8455,12 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, } if (m.role == Role::Healer) { - if (d2g > ready_heal_y * ready_heal_y) return false; - // Healers drink to ~full before the next pull (Karrz's ready + if (d2g > ready_heal_y * ready_heal_y) healer_far = true; + // Healers drink to ~full before the next pull (the owner's ready // check): a healer under 80% mana holds the pull. - if (m.max_mana > 0 && + // A party with a player in it has no mana gate before a pull (playtest 2026-10-15): the owner watches the mana; raids + // and groups of bots alone keep it. + if (PullManaGate(s, g) && m.max_mana > 0 && (int64(m.mana) * 100) < (int64(m.max_mana) * kReadyHealerManaPct)) healer_low_mana = true; // held below, for at most the cap: a healer with no drink must not freeze the run } @@ -8426,7 +8469,7 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, // Other mana users drink to the same mark between pulls // (Playerbot.Behavior.PullRecover); the hold is capped // below so a bot with no drink never freezes the raid. - if (m.max_mana > 0 && Services::Config().behavior_pull_recover() && + if (PullManaGate(s, g) && m.max_mana > 0 && Services::Config().behavior_pull_recover() && (int64(m.mana) * 100) < (int64(m.max_mana) * Classic::kPullReadyDpsManaPct)) ++dps_low_mana; ++others; @@ -8469,6 +8512,27 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, s.name(), int(kReadyHealerManaPct), cap / 1000); } } + // A member under the HP mark holds the pull for at most the same cap (same clock idiom as the healer hold above). + { + static std::mutex hp_hold_mu; + static std::unordered_map> hp_hold; // tank -> {since, last asked} + std::lock_guard hold_lock(hp_hold_mu); + auto& clk = hp_hold[uint64(s.raw().guid.GetCounter())]; + if (!hp_low_member) + clk = {0u, 0u}; + else + { + if (clk.first == 0u || now_ms - clk.second > 5000u) + clk.first = now_ms ? now_ms : 1u; + clk.second = now_ms; + uint32 const cap = Classic::kPullReadyHpHoldCapMs; + if (now_ms - clk.first < cap) + return false; + if (now_ms - clk.first < cap + 1000u) + TC_LOG_INFO("playerbot.v2", "[hp_hold] {} pulls with {} at {}% health: held {}s, the healers did not top the member off", + s.name(), hp_low_member->name, hp_low_member->max_hp > 0 ? int(int64(hp_low_member->hp) * 100 / int64(hp_low_member->max_hp)) : 0, cap / 1000); + } + } // Mana users under the pull-ready mark (drinking: DrinksForPull) hold // the pull for at most kPullReadyDpsHoldCapMs per hold. The clock is // per tank and restarts after the tank has not asked for 5 s (next @@ -8490,15 +8554,47 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, return false; } } + // The two position holds (a healer out of range, too few of the group near the tank) wait for the group to walk up, for at + // most kPullPositionHoldCapMs per hold, so a straggler that cannot get there never freezes the run (same clock idiom as above). + // A dead member still holds without a cap: the dead are rezzed, not left behind. + constexpr uint32 kPullPositionHoldCapMs = 30000; + static std::mutex position_hold_mu; + static std::unordered_map> far_holds, cohesion_holds; // tank -> {since, last asked} + auto still_held = [&](std::unordered_map>& holds, bool cond, char const* why) -> bool + { + std::lock_guard hold_lock(position_hold_mu); + auto& clk = holds[uint64(s.raw().guid.GetCounter())]; + if (!cond) + { + clk = {0u, 0u}; + return false; + } + if (clk.first == 0u || now_ms - clk.second > 5000u) + clk.first = now_ms ? now_ms : 1u; + clk.second = now_ms; + if (now_ms - clk.first < kPullPositionHoldCapMs) + return true; + if (now_ms - clk.first < kPullPositionHoldCapMs + 1000u) + TC_LOG_INFO("playerbot.v2", "[pull_hold] {} pulls with the group not up ({}): held {}s", s.name(), why, kPullPositionHoldCapMs / 1000); + return false; + }; + // The harbor's burst pull (tight_engage) never goes without the healer on top of the tank: that hold stays uncapped. + if (healer_far && tight_engage) + return false; + if (still_held(far_holds, healer_far, "a healer out of range")) + return false; if (others == 0) return true; + bool cohesive; if (tight_engage) { const uint32 catching = others - others_near - others_stranded; - return catching == 0 && others_near > 0; + cohesive = catching == 0 && others_near > 0; } - return others_near * 2 >= others; + else + cohesive = others_near * 2 >= others; + return !still_held(cohesion_holds, !cohesive, "too few near the tank"); }; - // Buffs (Karrz's ready check): once the group is otherwise ready, the + // Buffs (the owner's ready check): once the group is otherwise ready, the // pull also waits while 3+ living members within 40y lack a raid buff // a present bot caster can give (Classic::MissingGroupBuff: Fortitude, // Mark of the Wild, Arcane Intellect, Spirit / Shadow Protection, @@ -11118,8 +11214,9 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, float bestSq = std::numeric_limits::max(); bool best_is_priority = false; int best_tier = 0; - const bool dungeon_flow_pull = s.is_in_dungeon() && !s.is_in_raid() && - Services::Config().behavior_dungeon_flow(); + // Raids included: the owner's icons (other tanks' mobs, crowd-control marks) are as binding on a raid pull as on a + // dungeon pull. The bots never set marks themselves, so every icon on a mob is the owner's call. + const bool dungeon_flow_pull = s.is_in_dungeon() && Services::Config().behavior_dungeon_flow(); float bx, by, bz; s.position(bx, by, bz); for (auto const& u : s.raw().combat.nearby_enemies) { @@ -11186,7 +11283,9 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, int tier = 1; if (dungeon_flow_pull && g.exists()) { - if (u.guid == g.explicit_kill_mark() || + // A kill mark on an idle mob is the owner's call only with a human leader and when the mark gate allows + // an engage; a bot leader's skull is a leftover from the last fight (icons outlive a wipe). + if ((u.guid == g.explicit_kill_mark() && !g.leader_is_bot() && MarkGate::MayEngage(s, ai, &g, u.guid)) || (ai.owner_command() == BotAI::OwnerCommand::Engage && ai.owner_target() == u.guid)) tier = 3; else if (!s.raw().pve_order.mark_target.IsEmpty() && u.guid == s.raw().pve_order.mark_target) @@ -11888,13 +11987,13 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, // threshold once it is safe to sit (no attacker, nobody fighting // within 45y, 5s after combat); PickRecovery keeps the bot seated // to 95%. Cohesion moves above run first, so it never sits while - // the group walks off. Non-healers keep their open-world habits. + // the group walks off. Everyone also eats below the 70% pull-ready health mark here (the swallowed ooc_eat_food was the + // only eater, so a warrior or rogue in a party never ate and the tank's HP hold ran to its cap). if (!s.in_combat() && !s.is_casting() && !s.recently_in_combat(5000) && - !s.raw().movement.is_mounted && Classic::DrinksForPull(s, &g) && - Classic::SafeToRecover(s, &g)) + !s.raw().movement.is_mounted && Classic::SafeToRecover(s, &g)) { Classic::RecoveryPick const dpick = Classic::PickRecovery( - s, /*start_hp*/ 0, Classic::PullReadyHealerManaPct(s)); + s, /*start_hp*/ 70, Classic::OocDrinkStartManaPct(s, &g, 0)); // the healer mark for a healer, the DPS mark (60) for the rest, as the tank's pull gate waits if (dpick.item && !s.is_moving()) { emit.emit(UseItemByEntryIntent{dpick.item, ObjectGuid::Empty}); @@ -11912,7 +12011,7 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, // Why a healer under the pull-ready mana is not drinking (Deadmines run 5: no drink line from the priest at all). // Throttled to the tank-diagnostic cadence; one line names the failing condition. if (!s.in_combat() && Classic::DrinksForPull(s, &g) && s.max_power(POWER_MANA) > 0 && - s.power_pct(POWER_MANA) < Classic::PullReadyHealerManaPct(s) && !Classic::IsDrinking(s) && ai.tank_diag_due(now_ms)) + s.power_pct(POWER_MANA) < Classic::OocDrinkStartManaPct(s, &g, 0) && !Classic::IsDrinking(s) && ai.tank_diag_due(now_ms)) { char const* why = s.is_casting() ? "casting" : s.recently_in_combat(5000) ? "combat_within_5s" : s.raw().movement.is_mounted ? "mounted" : !Classic::SafeToRecover(s, &g) ? "not_safe_to_sit(group member fighting within 45y or enemy engaged with the group within 30y)" @@ -11930,7 +12029,7 @@ bool DungeonDispatch(BotSnapshotView const& s, BotAI& ai, // Out of combat (this idle tail) with gear meaningfully worn (<60%), // self-repair. emit.repair_all(Empty) routes to API::repair_all's // self-repair branch (no NPC needed) whose stipend top-up makes it - // effectively free for AI bots — the "gold self-repair on dungeon + // effectively free for bot logic bots — the "gold self-repair on dungeon // staging/running" the owner asked for. After it repairs to full the // <60% gate self-clears; the 5s Repair lockout only stops the // snapshot-lag double-fire. Fires each OOC window (incl. just after a @@ -12390,10 +12489,10 @@ bool BgDispatch(BotSnapshotView const& s, BotAI& ai, // Players do not sit mounted in the start room for the whole countdown (and a mount is a 3 s cast): bots stay on foot while // they mill about and start the cast only in the last 4..9 s before the gates open (per-bot offset, so the room does not // mount in one go). The cast is the normal interruptible one (API::mount -> cast_spell), not an instant aura. - // Karrz, WSG test: bots stand around on foot until the last seconds. Once the buff / maintenance rules above have nothing + // The owner, WSG test: bots stand around on foot until the last seconds. Once the buff / maintenance rules above have nothing // left to do (this code is only reached then) and the bot stands at its gate spot, it mounts and waits mounted; the // moment is spread 20..80 s before the gates open so the room does not mount in one go. - // 2026-10-08 (Karrz, WSG: "the bots are still mounted in here"): no mounts in the start room at all. A bot that arrived + // 2026-10-08 (playtest, WSG: "the bots are still mounted in here"): no mounts in the start room at all. A bot that arrived // mounted gets off, and none mounts until the gates open (API::mount also refuses during STATUS_WAIT_JOIN). if (s.raw().movement.is_mounted && !s.on_vehicle()) { @@ -12405,7 +12504,7 @@ bool BgDispatch(BotSnapshotView const& s, BotAI& ai, bool const mount_due = false; uint32 const now_ms = GameTime::GetGameTimeMS(); uint32 const bot_salt = uint32(s.guid().GetCounter()) * 2654435761u; - // Karrz, AB test: during the two-minute countdown the team waits at its start gate, loosely spread like players, instead + // The owner, AB test: during the two-minute countdown the team waits at its start gate, loosely spread like players, instead // of wandering the start area. WSG / AB / AV have gate anchors; each bot gets its own spot 3..10 y inside the gate and // up to 7 y to either side, walks there once and stays (buff / mount rules above still run). bool gate_anchored = false; @@ -12413,7 +12512,7 @@ bool BgDispatch(BotSnapshotView const& s, BotAI& ai, float face_base = 0.0f; // heading from the bot's spot toward the gate bool at_spot = true; // no gate anchor for this BG: the bot mounts wherever it stands // Inside the gate line: the anchored bots' steps (spot, face, fidget) must stay on the room side. The doors only block - // by collision, a step that crosses the line walks the bot through the closed gate (Karrz, 2026-10-08, WSG). + // by collision, a step that crosses the line walks the bot through the closed gate (playtest, 2026-10-08, WSG). float gate_gx = 0.f, gate_gy = 0.f, gate_ix = 0.f, gate_iy = 0.f; auto inside_gate = [&](float x, float y, float margin) { return (x - gate_gx) * gate_ix + (y - gate_gy) * gate_iy >= margin; @@ -12426,7 +12525,7 @@ bool BgDispatch(BotSnapshotView const& s, BotAI& ai, float const gx = s.bg_gate_x(), gy = s.bg_gate_y(); float const ix = s.bg_gate_in_x(), iy = s.bg_gate_in_y(); { - // Karrz: "like soldiers in a line". A fan, not an arc: depth 2..17 y with most bots near the gate and a + // The owner: "like soldiers in a line". A fan, not an arc: depth 2..17 y with most bots near the gate and a // tail further back, the sideways spread widening with the depth, and a little extra scatter per bot. float const h1 = float((bot_salt >> 8) % 1000u) / 1000.0f; float const h2 = float((bot_salt >> 18) % 1000u) / 1000.0f; @@ -12475,7 +12574,7 @@ bool BgDispatch(BotSnapshotView const& s, BotAI& ai, return true; } } - // Karrz: bots at the gate "all face the same way like a parade". At its spot a bot turns, in about one 20 s slot of four, to + // The owner: bots at the gate "all face the same way like a parade". At its spot a bot turns, in about one 20 s slot of four, to // a heading within +-60 degrees of the gate direction (one bot in six looks anywhere around). The turn is a 1.2 y walk step // in that direction (there is no facing-by-angle intent), fired once per slot by the 3 s BgOrderMove lockout on a per-slot key. if (gate_anchored && have_face_base && at_spot && !s.is_moving()) @@ -12700,7 +12799,7 @@ bool BgDispatch(BotSnapshotView const& s, BotAI& ai, my_role = BgRole::Attacker; // every roamer pushes } - // Arathi Basin: how many bots defend follows the node count, not the role table (ike3 bots, the ike3-based playerbot code raid10-revamp + // Arathi Basin: how many bots defend follows the node count, not the role table (ike3 bots, Karrz1/wow-1.12 raid10-revamp // bcc8b9f, BattleGroundTactics.cpp, BATTLEGROUND_AB): the further behind on held bases, the more everybody attacks. Of every // ten bots (team rank mod 10) 1 defend when losing, 2 when level or ahead, 3 when two or more bases ahead; the rest attack. // Roamers and healers keep their jobs. A held base counts only when it is not being contested. @@ -12798,7 +12897,7 @@ bool BgDispatch(BotSnapshotView const& s, BotAI& ai, if (match) { near_objective_go = true; break; } } } - // A bot never stands still to mount with a live enemy near (Karrz, WSG 2026-10-09: bots ran past him, mounting beside him): the + // A bot never stands still to mount with a live enemy near (playtest, WSG 2026-10-09: bots ran past him, mounting beside him): the // fight rules below get the tick instead, and the bot mounts once nothing hostile is inside its engage range. bool enemy_near_for_mount = false; { @@ -12858,7 +12957,7 @@ bool BgDispatch(BotSnapshotView const& s, BotAI& ai, return true; } // Standing AT the ordered post for a minute with nothing to fight: the plan keeps a bot where there is nothing left to do - // (AV 2026-10-11, Karrz: a pile of bots idle at Stonehearth). Log the order and the rule so the soak shows which orders + // (AV 2026-10-11, the owner: a pile of bots idle at Stonehearth). Log the order and the rule so the soak shows which orders // park bots; no movement here, the planner owns where a bot goes next. TC_LOG_INFO("playerbot.v2", "[bg_stall] at_post bot={} order={} squad={} entry={} last_rule={} type={}", s.bot_id(), uint32(ord.kind), uint32(ord.squad), ord.target_entry, @@ -12880,7 +12979,7 @@ bool BgDispatch(BotSnapshotView const& s, BotAI& ai, ai.set_last_rule_fired("idle:bg_mount_cast"); return true; } - // Mounting drops the flag: the Alliance flag was picked up and dropped by one Horde bot five times running (Karrz, WSG + // Mounting drops the flag: the Alliance flag was picked up and dropped by one Horde bot five times running (playtest, WSG // 2026-10-09), each pickup followed by the 5 s mount retry. A carrier rides on foot. bool const carries_objective = s.bg_friendly_flag_carrier() == s.guid(); if (s.is_alive() && !s.raw().movement.is_mounted && !s.on_vehicle() && !carries_objective && @@ -13207,7 +13306,7 @@ bool BgDispatch(BotSnapshotView const& s, BotAI& ai, } } - // Flag callouts (FC up/down, EFC, carrying) belong to flag maps only. Karrz, AB 2026-10-11: a bot called "FC down" in Arathi + // Flag callouts (FC up/down, EFC, carrying) belong to flag maps only. the owner, AB 2026-10-11: a bot called "FC down" in Arathi // Basin, which has no flags. A flag map is one whose script names a flag spot; node maps (AB, AV) never do. const bool ctf_map = bg_advice.enemy_flag_x != 0.f || bg_advice.enemy_flag_y != 0.f || bg_advice.own_flag_x != 0.f || bg_advice.own_flag_y != 0.f; @@ -14138,7 +14237,7 @@ bool BgDispatch(BotSnapshotView const& s, BotAI& ai, // gate above meant bots marching to a node, escorting or picking up a flag walked straight past enemy players. A bot on a // march / pickup / escort / regroup order now also fights an enemy that is close (12 y); HuntEFC and CarryHome orders keep // their own handling. A bot carrying the flag never fights (the role table does not follow a pickup, so check the carrier). - // Victim validity (Karrz, WSG 2026-10-09: a priest stood beside him swinging at nothing and ignored him). The engage rule below needs an + // Victim validity (playtest, WSG 2026-10-09: a priest stood beside him swinging at nothing and ignored him). The engage rule below needs an // empty victim, so a victim that is gone, dead, untargetable, unreachable, or a creature that does not fight back while an enemy // player is close held the bot for good. Drop it for the nearest enemy player, or release it; same decision as combat:bg_victim_invalid. if (s.is_alive() && !s.is_casting() && !s.victim().IsEmpty() && s.bg_friendly_flag_carrier() != s.guid()) @@ -14177,12 +14276,12 @@ bool BgDispatch(BotSnapshotView const& s, BotAI& ai, my_role != BgRole::FlagCarrier && my_role != BgRole::OrbCarrier) { - // Karrz, WSG test: bots ran past enemies to the flag. Ordered bots now fight within 25 y as well; only the bot sent to + // The owner, WSG test: bots ran past enemies to the flag. Ordered bots now fight within 25 y as well; only the bot sent to // pick up a flag stays at 12 y (one runner stays focused, the escorts and everyone else peel off). float const eng_range = (eng_has_order && s.raw().bg.order.kind == BgState::BgOrder::PickupFlag) ? 24.0f : (s.raw().bg.current_type_id == 1 && s.raw().bg.status == 3) ? BgAvPlan::AggroRange(s.raw().bg.in_progress_ms) // ike3 AV aggro 40 -> 10 yd - : (my_role == BgRole::Healer ? 36.0f : BgTargetPick::kBgEngageRange); // Karrz 2026-10-09: bigger radius. The snapshot scans this far in a BG; healers close a bit less + : (my_role == BgRole::Healer ? 36.0f : BgTargetPick::kBgEngageRange); // playtest 2026-10-09: bigger radius. The snapshot scans this far in a BG; healers close a bit less float self_x = 0.f, self_y = 0.f, self_z = 0.f; s.position(self_x, self_y, self_z); const bool eng_ranged = IsRangedSpec(s.cls(), uint16(s.spec())); @@ -14197,13 +14296,13 @@ bool BgDispatch(BotSnapshotView const& s, BotAI& ai, float dy = e.y - self_y; float dsq = dx * dx + dy * dy; if (dsq > eng_range * eng_range) continue; // PvP engage range - // Players over mobs (AV/IoC creatures): the fight Karrz wants is player vs player. A mob only counts as 'closer' + // Players over mobs (AV/IoC creatures): the fight the owner wants is player vs player. A mob only counts as 'closer' // by 20 y so a guard next to the bot does not hide a player behind it. float const eng_score = dsq + (e.guid.IsPlayer() ? 0.f : 400.f); if (eng_score < best_dsq) { best_dsq = eng_score; closest = &e; } } // An enemy below the graveyard ridge: a chase would path the long way round the back (there is no navmesh link down the - // ledge). Go over the ledge to the fight by the ridge lane's drop (Karrz, WSG 2026-10-09), then the chase is level. + // ledge). Go over the ledge to the fight by the ridge lane's drop (playtest, WSG 2026-10-09), then the chase is level. if (closest && closest->guid.IsPlayer() && closest->z < self_z - 8.0f && !s.bg_in_prep() && s.bg_friendly_flag_carrier() != s.guid()) { @@ -14417,7 +14516,7 @@ bool BgDispatch(BotSnapshotView const& s, BotAI& ai, // real shot, so engaging the instant LoS exists at combat // range (<=40y, max cast range) lets every bot with a clear // angle damage him — casters from range, melee closing — and - // the class AI handles positioning. The old <=6y gate forced + // the class bot logic handles positioning. The old <=6y gate forced // bots to chase the moving captain to point-blank before // attacking, so only a couple ever landed damage. if (boss->in_los && boss_dsq <= 40.0f * 40.0f && @@ -14540,7 +14639,7 @@ bool BgDispatch(BotSnapshotView const& s, BotAI& ai, return true; } } - // Individuality (Karrz, AB test: everybody stands at the flag one bot is capping). About a third of the bots on an + // Individuality (playtest, AB test: everybody stands at the flag one bot is capping). About a third of the bots on an // attack order are scouts: they arrive within 24 y instead of 8 y and, standing on station with nobody to fight, // pace to a spot a few yards from the post every ~7 s, so the group spreads over the node instead of queueing. if (ord.kind == BgOrd::AttackNode && s.is_alive() && !s.is_casting() && !s.in_combat() && @@ -15113,7 +15212,7 @@ bool BgDispatch(BotSnapshotView const& s, BotAI& ai, ai.set_last_rule_fired("idle:bg_defender_hold_home"); return true; } - // Karrz 2026-10-08 (WSG): two Alliance bots camped ON the flag stand. A defender spawned inside the hold radius never + // playtest 2026-10-08 (WSG): two Alliance bots camped ON the flag stand. A defender spawned inside the hold radius never // moved at all. Stand off the anchor at a guard spot 9-14 y away (a guid-hashed bearing), and pace to it once. if (!at_defend_post && dx * dx + dy * dy < 8.0f * 8.0f) { @@ -18195,7 +18294,7 @@ bool AutoactDispatch(BotSnapshotView const& s, BotAI& ai, // pre-resolved teleport destination matches the goal's map. The // builder pre-resolves portal destinations (spell -> // spell_target_position) so this rule is a cheap snapshot scan - // with no DB lookups on the AI worker. Two sub-rules: + // with no DB lookups on the bot worker. Two sub-rules: // * idle:walk_to_portal : portal > 5y → walk to it // * idle:use_portal : portal ≤ 5y → emit use_game_object // The portal GO is invisible to other-faction players (it's a @@ -19863,14 +19962,20 @@ bool AutoactDispatch(BotSnapshotView const& s, BotAI& ai, // is NO known-good node within range — a genuinely isolated // off-mesh bot that would otherwise saturate the path system // forever. - auto const* node = Services::TravelGraph().FindNearestNodeOnMap( - s.map_id(), s.raw().position.x, s.raw().position.y, 800.f); + // Nearest in 3D, and never one already tried: in a city with floors on top of each other (Ironforge) the node + // nearest by x/y is often on another floor, unreachable from here, and asking for it again and again kept + // 130 bots wedged. Each node tried is put on the bot's goal blacklist, so the next wedge picks the next one. + uint32 const wedge_now = s.published_at_ms(); + auto const* node = Services::TravelGraph().FindNearestNodeOnMap3D( + s.map_id(), s.raw().position.x, s.raw().position.y, s.raw().position.z, 800.f, + [&](auto const& n) { return ai.goal_blacklisted(n.x, n.y, wedge_now); }); if (node) { const float ndx = node->x - s.raw().position.x; const float ndy = node->y - s.raw().position.y; if (ndx * ndx + ndy * ndy > 25.f) { + ai.blacklist_goal(node->x, node->y, wedge_now); emit.move_to(node->x, node->y, node->z, /*run*/ true); ai.set_last_rule_fired("idle:wander_wedge_escape"); return true; @@ -20109,7 +20214,7 @@ bool LegacyVendorDispatch(BotSnapshotView const& s, BotAI& ai, // threshold and a vendor is in interact range. Buy a 20-stack bracket so // the bot has plenty before next departure. Gated on having gold to spend // (food costs are trivial but the rule shouldn't bankrupt a fresh bot). - // Vendor category filter resolves the right item server-side; AI doesn't + // Vendor category filter resolves the right item server-side; bot logic doesn't // need to know vendor inventory layout. constexpr uint16 kFoodComfortMin = 5; constexpr int32 kFoodMinGold = 5000; // 50 silver @@ -20333,6 +20438,28 @@ void DispatchIdle(BotAI& ai, return; } + // Stamp every tick the bot is moving, not only when ambient_sit's gate happens to run: a rule-driven walk (quest, vendor, travel) + // outranks it, and the stale stamp sat the bot down the moment it arrived. + if (s.is_moving()) + ai.set_last_moving_ms(s.published_at_ms()); + + // ---- Spawner walk order: a world bot arrives on foot from the edge of town, or leaves toward an inn before it logs out ---- + { + auto& wo = ai.walk_order(); + if (wo.active.load(std::memory_order_acquire)) + { + if (!s.is_alive() || s.in_combat() || s.in_group() || s.is_in_instance() || s.in_battleground() || s.on_transport()) + wo.Clear(); + else if (States::ChunkedWalkToward(s, ai, emit, wo.x.load(), wo.y.load(), wo.z.load(), "walk_order", s.published_at_ms())) + { + ai.set_last_rule_fired(wo.kind.load() == ::Playerbot::V2::WalkOrder::Arrive ? "idle:arrive_walk" : "idle:leave_walk"); + return; + } + else if (wo.kind.load() == ::Playerbot::V2::WalkOrder::Arrive) + wo.Clear(); // arrived (or gave up): carry on as a resident. A leaving bot waits where it is for the spawner to log it out + } + } + // ---- World-wide idle watch ---- // A world bot that has not moved for a long time with no reason to stand is given a new activity, whichever rule is holding it // (see IdleWatch.h). First strike: a short wander step. Later strikes: walk to a level- and faction-appropriate quest hub on this @@ -20343,7 +20470,11 @@ void DispatchIdle(BotAI& ai, float px, py, pz; s.position(px, py, pz); bool const exempt = s.has_owner_character() || s.in_group() || s.in_battleground() || s.is_in_instance() || s.on_transport() - || s.is_mounted() || s.is_swimming() || s.in_combat() || s.is_casting() || s.hp_pct() < 70; + || s.is_mounted() || s.is_swimming() || s.in_combat() || s.is_casting() || s.hp_pct() < 70 + || Classic::IsEating(s) || Classic::IsDrinking(s) // a meal or a mana drink is a reason to stand + || (ai.last_rule_fired() && (std::strcmp(ai.last_rule_fired(), "idle:inn_rest") == 0 // resting at the inn is a reason to stand + || std::strcmp(ai.last_rule_fired(), "idle:mailbox") == 0 // and standing at a mailbox + || std::strcmp(ai.last_rule_fired(), "idle:res_sick_wait") == 0)); // so is waiting out Resurrection Sickness if (V2::IdleStuck(w, px, py, now, exempt)) { float tx = 0.f, ty = 0.f, tz = pz; @@ -20358,7 +20489,28 @@ void DispatchIdle(BotAI& ai, } std::sort(near.begin(), near.end(), [&](::Playerbot::V2::Travel::QuestHub const* a, ::Playerbot::V2::Travel::QuestHub const* b) { return a->GetDistanceFrom(s.raw()) < b->GetDistanceFrom(s.raw()); }); - if (!near.empty()) + // In a capital the places to stand are the bank, the auction house, the inn (Fleet/TownGather.h); the quest hubs there are + // the ward entrance rooms. A different spot at each strike and for each bot, weighted by what gathers there. + bool const in_capital = ::Playerbot::V2::World::IsVanillaCapitalZone(s.zone_id()); + std::vector<::Playerbot::V2::Fleet::GatherSpot> gather; + if (in_capital) + gather = ::Playerbot::V2::Fleet::TownGatherSpots(s.map_id(), px, py, 150.0f, s.is_alliance()); + std::vector<::Playerbot::V2::Fleet::GatherSpot> reach; + for (auto const& g : gather) + { + float const d = std::hypot(g.x - px, g.y - py); + if (d >= V2::kIdleMinHubYards && d <= V2::kIdleMaxHubYards) reach.push_back(g); + } + if (!reach.empty()) + { + uint32 const h32 = uint32(s.guid().GetCounter()) * 2654435761u + w.strikes * 40503u; + int const k = ::Playerbot::V2::Fleet::PickGatherSpot(reach, float(h32 % 10000u) / 10000.0f); + float const a = float(h32 % 628u) / 100.0f; + float const rr = float((h32 >> 8) % 100u) / 100.0f * ::Playerbot::V2::Fleet::kGatherRadius; + tx = reach[k].x + std::cos(a) * rr; ty = reach[k].y + std::sin(a) * rr; tz = reach[k].z; + what = "hub"; + } + else if (!near.empty()) { ::Playerbot::V2::Travel::QuestHub const* h = near[V2::IdlePickHub(near.size(), w.strikes, s.guid().GetCounter())]; tx = h->location.GetPositionX(); ty = h->location.GetPositionY(); tz = h->location.GetPositionZ(); @@ -20373,6 +20525,8 @@ void DispatchIdle(BotAI& ai, } w.tx = tx; w.ty = ty; w.tz = tz; w.has_target = true; w.forced_until_ms = now + V2::kIdleForcedMs; + (::Playerbot::V2::World::IsVanillaCapitalZone(s.zone_id()) ? ::Playerbot::V2::TownLife::Counters().idle_town : ::Playerbot::V2::TownLife::Counters().idle_field) + .fetch_add(1, std::memory_order_relaxed); TC_LOG_INFO("playerbot.v2", "[idle] bot={} lvl={} map={} zone={} stationary {}s last_rule={} strikes={} -> {} ({:.0f},{:.0f})", s.name(), uint32(s.level()), s.map_id(), s.zone_id(), V2::kIdleStuckMs / 1000u, ai.last_rule_fired() ? ai.last_rule_fired() : "-", w.strikes, what, tx, ty); diff --git a/src/modules/PlayerbotV2/Bot/States/State_InCombat.cpp b/src/modules/PlayerbotV2/Bot/States/State_InCombat.cpp index 3c0692773c..d52df5ff47 100644 --- a/src/modules/PlayerbotV2/Bot/States/State_InCombat.cpp +++ b/src/modules/PlayerbotV2/Bot/States/State_InCombat.cpp @@ -8,12 +8,14 @@ #include "Bot/BotSnapshotView.h" #include "Bot/BotIntentEmitter.h" #include "Bot/Raid/RaidCombat.h" // raid encounter orders (MC/BWL/Onyxia/Naxx) +#include "Bot/Raid/RaidEncounters.h" // Raid::Retaunts #include "Bot/RunToTankRules.h" // EnemyBlocksRunToTank #include "Bot/ClassicUpkeep.h" // Classic::PickCombatHealthItem / PickCombatManaItem #include "Bot/ClassTables.h" // ClassOocHeal — combat:pve_heal_focus #include "Bot/MarkGate.h" // Playerbot.Behavior.MarksNeedOrder #include "Bot/RacialRules.h" // EscapeArtistWanted #include "Bot/ThreatDiscipline.h" // opening lead + [raid_threat] / [raid_pull] log pacing +#include "Bot/ThreatLimits.h" // hard threat ratios shared with the raid brain #include "ClassicSpec.h" // Classic::IsSingleSpecClass — combat:pve_heal_focus #include "Bot/Dungeon/MarkCc.h" // MarkCc::TryCast - combat:marked_cc #include "Bot/Dungeon/DungeonScript.h" // DungeonAdvice — DungeonCombatPositioning (BUG G-P0a) @@ -128,7 +130,7 @@ void DiagSkipUnfightable(BotSnapshotView const& s, ObjectGuid victim, } } -// Emergency-survival item (Karrz's UsePotionsStrategy): at 30% health or +// Emergency-survival item (the owner's UsePotionsStrategy): at 30% health or // below use a healthstone, else the best healing potion in the bags for the // bot's level, unless a group heal is about to land (kept down to 20%). Not // mid-cast (a healer finishes its heal first), at most one combat consumable @@ -490,7 +492,7 @@ bool MaybeUseOffensiveRacial(BotSnapshotView const& s, Role role, BotIntentEmitt return false; } -// Mana refill (Karrz's UsePotionsStrategy): at 20% mana or below (a healer in +// Mana refill (the owner's UsePotionsStrategy): at 20% mana or below (a healer in // a boss fight: 35%) a conjured mana gem, then the best mana potion for the // level, then a Dark / Demonic Rune. Same cast / spacing / cooldown gates as // the healing item above. @@ -498,7 +500,16 @@ bool MaybeUseManaPotion(BotSnapshotView const& s, GroupSnapshotView const& g, Bo { uint32 const item = Classic::PickCombatManaItem(s, &g); if (!item) + { + // Due but a cast is running: a healer chaining heals has no idle tick, so stop it starting the next cast. The item goes out + // on the tick after this cast ends. + if (s.is_casting() && Classic::PickCombatManaItem(s, &g, /*while_casting=*/true)) + emit.hold_casts_for_mana_item(); + else + Classic::NoteManaItemRefused(s); return false; + } + emit.end_mana_break(); emit.emit(UseItemByEntryIntent{item, ObjectGuid::Empty}); Classic::NoteConsumableUse(s, item, "mana item"); return true; @@ -507,7 +518,7 @@ bool MaybeUseManaPotion(BotSnapshotView const& s, GroupSnapshotView const& g, Bo } // anonymous // ---- Group threat discipline ---- -// Port of Karrz's ike3-based bots group threat rules (MoltenCoreDungeonActions.cpp +// Port of Karrz's wow-1.12 group threat rules (MoltenCoreDungeonActions.cpp // MCRaidHoldDamage / MCRaidWaitForTank, MoltenCoreDungeonStrategies.cpp // GroupPveRestraint), generalised from Molten Core to any group with a tank. // The pure verdict lives in BotSnapshotView::threat_hold(); this layer adds @@ -517,7 +528,7 @@ namespace { using ThreatHold = BotSnapshotView::ThreatHold; // First tick a (bot, target) pair entered the opening hold. Rules run on the -// AI worker pool, so the map is shared and locked (Karrz's firstHeld map). +// bot worker pool, so the map is shared and locked (the owner's firstHeld map). std::mutex g_threat_hold_mu; std::unordered_map g_threat_hold_since; struct FightWaitClock { uint32 first_ms; uint32 last_ms; }; @@ -529,9 +540,11 @@ std::unordered_map g_threat_fight_clock; // per bot: w // so its loose-attacker pick-up / taunt takes it). Non-victim DPS then hold // damage as if over threat until a tank has it back - every hit they land // now is threat the tank must out-taunt. Raids only: 5-man and non-elite -// trash keep Karrz's "everyone fights a mob on a member" rule. The group +// trash keep the owner's "everyone fights a mob on a member" rule. The group // snapshot carries no cooldowns, so a tank's taunt readiness is approximated // by "on this mob or free". +constexpr float kLooseBossTankReach = 90.0f; // how far a tank may be from a boss on a member and still be coming for it + bool LooseRaidEliteOnMember(BotSnapshotView const& s, NearbyUnit const& u, GroupSnapshotView const* g) { if (!Services::Config().behavior_loose_mob_hold()) return false; // Playerbot.Behavior.LooseMobHold @@ -555,7 +568,10 @@ bool LooseRaidEliteOnMember(BotSnapshotView const& s, NearbyUnit const& u, Group if (m.role != Role::Tank || !m.online || !m.is_alive || m.map_id != s.map_id()) continue; if (m.guid == u.victim) continue; const float dx = m.x - u.x, dy = m.y - u.y, dz = m.z - u.z; - if (dx * dx + dy * dy + dz * dz > 30.0f * 30.0f) continue; + // A boss pulled onto a member far from its tank (Onyxia on a warlock, the tank 68 y off, n10 run 1): the tank is coming, and the + // casters that opened at once at 66 y out-threatened it 2900 to 1332 and she turned on a mage. The hold is bounded below. + float const reach = (u.is_dungeon_boss || u.is_boss_rank) ? kLooseBossTankReach : 30.0f; + if (dx * dx + dy * dy + dz * dz > reach * reach) continue; if (m.victim == u.guid || m.victim.IsEmpty()) return true; } return false; @@ -594,9 +610,14 @@ bool HoldClockExpired(std::mutex& mu, std::unordered_map return now - it->second.first_ms >= max_ms; } -bool LooseHoldExpired(BotSnapshotView const& s, ObjectGuid target) +// A boss the encounter data says loses its threat on a schedule (Ragnaros' Wrath) is on a member for the seconds a tank needs to +// taunt it back, not for a tank that cannot reach it: the raid waits for that taunt, not for the full bound (mc_ragnaros: every +// Wrath cost 3 to 6 s of 24 DPS bots, about a tenth of the fight's damage). +constexpr uint32 kLooseHoldRetauntMaxMs = 2500; + +bool LooseHoldExpired(BotSnapshotView const& s, ObjectGuid target, bool retaunting) { - return HoldClockExpired(g_loose_hold_mu, g_loose_hold, s, target, kLooseHoldMaxMs, kLooseHoldGapMs); + return HoldClockExpired(g_loose_hold_mu, g_loose_hold, s, target, retaunting ? kLooseHoldRetauntMaxMs : kLooseHoldMaxMs, kLooseHoldGapMs); } // A 5-man party's over-threat hold is bounded the same way (Deadmines 2026-10-09 run 3: the hunter and the rogue sat @@ -614,6 +635,9 @@ bool PartyOverThreatExpired(BotSnapshotView const& s, ObjectGuid target) return HoldClockExpired(g_party_hold_mu, g_party_hold, s, target, kPartyOverThreatMaxMs, kPartyOverThreatGapMs); } +// Majordomo Executus' Damage Shield, on himself and his Flamewakers (the Magic Reflection twin, 20619, is refused by the cast API). +constexpr uint32 kDamageShieldAura = 21075; + ThreatHold EvaluateThreatHold(BotAI& ai, BotSnapshotView const& s, ObjectGuid target, GroupSnapshotView const* g = nullptr) { @@ -625,7 +649,18 @@ ThreatHold EvaluateThreatHold(BotAI& ai, BotSnapshotView const& s, ObjectGuid ta NearbyUnit const* u = s.hostile_unit(target); if (!u) return ThreatHold::None; - if (LooseRaidEliteOnMember(s, *u, g) && !LooseHoldExpired(s, target)) + // Majordomo's Damage Shield (21075) sends every melee swing back at the swinger (n71 Majordomo wipe: two melee DPS at 35-39 % died + // to their own hits, and the melee kept swinging at the shielded adds for the whole fight). Melee wait the 10 s out, or until a + // purge strips it; casters are not hit by it. Not a tank: its swings are the threat, and it has a healer. + if (s.is_in_raid() && u->magic_buff_spell == kDamageShieldAura && IsMeleeSpec(s.cls(), s.spec())) + { + if (RaidLogDue(RaidLogKey(s, RaidLogKind::ThreatHold), s.published_at_ms(), 5000u)) + TC_LOG_INFO("playerbot.v2", "[raid_threat] {} holds melee on entry {} ({}): Damage Shield up", + s.name(), u->entry, target.GetCounter()); + return ThreatHold::ShieldUp; + } + + if (s.is_in_raid() && LooseRaidEliteOnMember(s, *u, g) && !LooseHoldExpired(s, target, Raid::Retaunts(s.map_id(), u->entry))) { if (RaidLogDue(RaidLogKey(s, RaidLogKind::ThreatHold), s.published_at_ms(), 5000u)) TC_LOG_INFO("playerbot.v2", @@ -641,14 +676,39 @@ ThreatHold EvaluateThreatHold(BotAI& ai, BotSnapshotView const& s, ObjectGuid ta // hard limits below keep a margin of 5 / 10 points under that. 90 % for 24 DPS capped the whole raid at about the tank's // threat per second less a tenth (MC Garr 2026-10-10: about 70 damage per second per DPS bot, mages held at 93 %). constexpr float kRaidThreatMaxRatio = 1.0f; - ThreatHold h = s.threat_hold(target, lead, s.is_in_raid() ? std::max(cfg.threat_max_ratio(), kRaidThreatMaxRatio) : cfg.threat_max_ratio()); + // A boss that cuts its tank's threat on a schedule (Onyxia's Knock Away, -25 %) is held at what stays of the tank's threat after a cut. + float const threat_share = (boss && s.is_in_raid()) ? Raid::ThreatShareAfterDrop(s.map_id(), u->entry) : 1.0f; + bool const melee_spec = IsMeleeSpec(s.cls(), s.spec()); + float const base_ratio = std::min(s.is_in_raid() ? std::max(cfg.threat_max_ratio(), kRaidThreatMaxRatio) : cfg.threat_max_ratio(), threat_share); + // Early in a raid pull the hold starts a typical hit short of the tank's threat (ThreatEarlyHoldRatio). + float const max_ratio = s.is_in_raid() ? ThreatEarlyHoldRatio(base_ratio, melee_spec, u->tank_threat, threat_share) : base_ratio; + ThreatHold h = s.threat_hold(target, lead, max_ratio); + // A 5-man party has one threat rule: the DPS wait for the owner's Attack, at most kPartyOpenWaitMs (6 s) from the tank's first hit (bounded below). The over-threat + // hold and its release limits are raid discipline; in a party the tank holds with its own threat and the healer heals. + if (!s.is_in_raid() && h == ThreatHold::OverThreat) + h = ThreatHold::None; + // After the owner's Pull / Pull back the party's DPS wait for his Attack even once the tank has its lead. There is one timer: + // kPartyOpenWaitMs below (6 s from the tank's first hit) lets them open by themselves. The Pull counts for the fight that + // follows it, until an Attack or the end of that fight. Not a mob that hits this bot (self-defence), not a healer. + if (!s.is_in_raid() && s.is_in_dungeon() && h == ThreatHold::None && u->victim != s.guid() && + ai.effective_role(s) != Role::Healer) + { + uint32 const pull_ms = ai.owner_pull_ms(), t = s.published_at_ms(); + uint32 const last_exit_ms = uint32(ai.combat_exit_ms()); // end of the bot's previous fight (0: none yet) + if (pull_ms && ai.owner_attack_ms() < pull_ms && last_exit_ms < pull_ms && + !(ai.is_manual_mode(t) && ai.owner_command() == BotAI::OwnerCommand::Engage && ai.owner_target() == target)) + h = ThreatHold::TankOpening; + } // The release is bounded: a mob switches to a non-tank at 110% of the tank's threat in melee reach, 130% at range. Past 100% (melee) // / 110% (caster) the hold stays however long it has lasted - after the 3 s release a caster kept nuking over the tank for the // whole fight and pulled the Defias Miner that killed the mage (deadmines_full run 9). Below those the release stands. // Deadmines 2026-10-10: with the tank stunned (its threat standing still) the 3 s release let the rogue climb to 1725 against // the tank's 1663, past the tank with no hold left; a melee DPS therefore never releases above the tank's own threat, a caster // keeps a tenth of margin under the 130 % a ranged attacker needs to take the mob. - const float hard_ratio = IsMeleeSpec(s.cls(), s.spec()) ? 1.0f : 1.10f; + // The scheduled cut lowers both limits: a hold released at 100 % of a tank about to lose a quarter of it pulls the boss. + // While one more hit would take the bot past the pull-safe ratio, the early ratio is also the release limit: the hold stays until the tank has built up. + const float hard_ratio = std::min({ ThreatHardRatio(melee_spec, s.is_in_raid(), u->tank_threat), threat_share, + max_ratio < base_ratio ? max_ratio : 1.0e9f }); const bool past_hard_limit = u->tank_threat > 0.0f && u->my_threat >= u->tank_threat * hard_ratio; if (h == ThreatHold::OverThreat && !past_hard_limit && PartyOverThreatExpired(s, target)) { @@ -664,7 +724,7 @@ ThreatHold EvaluateThreatHold(BotAI& ai, BotSnapshotView const& s, ObjectGuid ta "[raid_threat] {} holds damage on entry {} ({}): over threat mine={:.0f} tank={:.0f}", s.name(), u->entry, target.GetCounter(), u->my_threat, u->tank_threat); // Raid DPS wait for the owner's Attack: the tanks pull, everyone else holds until the owner presses Attack - // (/focus, an Engage order, or the group's mark release) - Karrz, MC Gehennas 2026-10-08. A mob that hits this + // (/focus, an Engage order, or the group's mark release) - the owner, MC Gehennas 2026-10-08. A mob that hits this // bot or its pet is still answered (self-defence), and no mob held by a bot-led group is touched. if (h == ThreatHold::None && cfg.raid_dps_wait_attack() && s.is_in_raid() && g && !g->leader_is_bot() && u->victim != s.guid() && ai.effective_role(s) != Role::Healer) @@ -684,6 +744,11 @@ ThreatHold EvaluateThreatHold(BotAI& ai, BotSnapshotView const& s, ObjectGuid ta const uint32 now = s.published_at_ms(); + // The owner's Attack on this target is instant in a party: no wait for the tank's lead (the over-threat limits above still hold). + // Pull and Pull back put only the tank into Engage, so they keep the tank first. + if (!s.is_in_raid() && ai.is_manual_mode(now) && ai.owner_command() == BotAI::OwnerCommand::Engage && ai.owner_target() == target) + return ThreatHold::None; + // Unpulled mob (nobody in the group has engaged it): opening on it IS a // pull, and pulls are the main tank's. No timeout - except for the // owner's explicit target (/focus, an Engage command, or the group's @@ -693,7 +758,7 @@ ThreatHold EvaluateThreatHold(BotAI& ai, BotSnapshotView const& s, ObjectGuid ta // human leader: a bot leader's marks are its in-combat auto-skull, and // one left on an idle mob is a leftover of the last fight (MC // 2026-10-06, GroupSnapshotView::leader_is_bot). - constexpr uint32 kMaxUnpulledOwnerWaitMs = 4000; + constexpr uint32 kMaxUnpulledOwnerWaitMs = 8000; // a tank walking in from 25 y needs more than 4 s (Deadmines 2026-10-15: the mage opened first) const bool owner_pick = ai.focus_target() == target || (ai.is_manual_mode(now) && ai.owner_command() == BotAI::OwnerCommand::Engage && ai.owner_target() == target) || @@ -713,17 +778,20 @@ ThreatHold EvaluateThreatHold(BotAI& ai, BotSnapshotView const& s, ObjectGuid ta // TankOpening), or after a bounded wait so a tank that cannot build // threat (out of reach, stunned, dead) never freezes the raid. The // config waits are honoured when longer. - constexpr uint32 kMaxOpenWaitTrashMs = 4000; - constexpr uint32 kMaxOpenWaitBossMs = 10000; + constexpr uint32 kMaxOpenWaitTrashMs = 3500; // from the tank's first damage on the mob (playtest 2026-10-15) + constexpr uint32 kMaxOpenWaitBossMs = 6000; // playtest 2026-10-15: never longer than six seconds, boss or not + // A party's DPS wait for the owner's Attack after a Pull / Pull back and open by themselves this long after the tank's first hit + // (playtest 2026-10-15: six seconds, in case the owner forgets). + constexpr uint32 kPartyOpenWaitMs = 6000; uint32 wait_ms = !u->unit_in_combat ? kMaxUnpulledOwnerWaitMs - : boss ? std::max(kMaxOpenWaitBossMs, cfg.threat_opening_wait_boss_ms()) - : std::max(kMaxOpenWaitTrashMs, cfg.threat_opening_wait_trash_ms()); + : boss ? std::min(kMaxOpenWaitBossMs, cfg.threat_opening_wait_boss_ms()) + : (s.is_in_raid() ? std::max(kMaxOpenWaitTrashMs, cfg.threat_opening_wait_trash_ms()) : kPartyOpenWaitMs); // A raid trash mob a tank already holds (it is the mob's victim) needs no long lead wait: its // threat only has to start building, so DPS opens ~2 s after the tank has it (MC 2026-10-06: // 26 bots sat the full 4 s on a Giant the tank was already hitting). // A party's trash the tank already holds gets the same short wait: every new target of a multi-mob pull restarts the // clock, and 4 s a target left the DPS idle through most of an 8-mob fight (Deadmines 2026-10-09 run 3). - if (u->unit_in_combat && !boss && ThreatVictim(u->victim_kind) == ThreatVictim::Tank) + if (s.is_in_raid() && u->unit_in_combat && !boss && ThreatVictim(u->victim_kind) == ThreatVictim::Tank) wait_ms = std::min(wait_ms, 2000u); // Separate clocks for the unpulled and the engaged phase of a target, so // time spent waiting for the pull does not eat the tank's opening wait. @@ -739,6 +807,9 @@ ThreatHold EvaluateThreatHold(BotAI& ai, BotSnapshotView const& s, ObjectGuid ta // One opening wait per fight, not per mob: a bot that has already waited for the tank in this fight (held within the last 8 s) // does not wait again for each next mob of the pull (Deadmines 2026-10-09: the clock restarted on every target). uint32 since = it->second; + // Counted from the tank's first damage: only the engaged phase feeds the fight clock, so the time spent waiting for the pull + // (up to kMaxUnpulledOwnerWaitMs) is not taken off the opening wait, and a mob in combat gets the DPS 3.5 s after the first hit. + if (u->unit_in_combat) { auto [fit, finserted] = g_threat_fight_clock.try_emplace(s.raw().guid.GetCounter(), FightWaitClock{ now, now }); if (!finserted) @@ -768,7 +839,7 @@ ThreatHold EvaluateThreatHold(BotAI& ai, BotSnapshotView const& s, ObjectGuid ta } // Over the tank's threat: shed it with the class's vanilla threat drop when -// one is ready (Karrz's bots used the same set). Returns true on an emit. +// one is ready (the owner's bots used the same set). Returns true on an emit. bool TryThreatDrop(BotSnapshotView const& s, ObjectGuid target, BotIntentEmitter& emit) { struct Drop { uint8 cls; uint32 spell; uint32 needs_aura; bool on_target; }; @@ -788,7 +859,7 @@ bool TryThreatDrop(BotSnapshotView const& s, ObjectGuid target, BotIntentEmitter } // Loose elite / boss on this non-tank bot in a tanked dungeon or raid group -// (Karrz's bots: the victim gets out of the way so the tank can pick the mob +// (the owner's bots: the victim gets out of the way so the tank can pick the mob // up). Hunter Feign Death, rogue Vanish (else Feint), priest Fade at once; // a mage Frost Novas a mob in melee reach first; then everyone steps toward // its anchor tank - a Classic healer casting its instant heals / HoTs / @@ -955,7 +1026,7 @@ bool RangedMeleedDefense(BotAI& ai, BotSnapshotView const& s, GroupSnapshotView { const float step = std::min(10.0f, dist - 5.0f); const float sx = bx + dx / dist * step, sy = by + dy / dist * step, sz = bz + dz / dist * step; - // Never into an idle pack's aggro reach: the run to the tank pulled the next pack (Karrz, Deadmines 2026-10-10). + // Never into an idle pack's aggro reach: the run to the tank pulled the next pack (playtest, Deadmines 2026-10-10). if (!RaidStandPointBlocked(s, sx, sy, sz) && !RaidPointInUnpulledReach(s, sx, sy, sz)) { if (emit.move_to(sx, sy, sz, /*run*/ true) || s.has_path_destination()) @@ -1118,7 +1189,7 @@ bool PreemptiveTankHeal(BotAI& ai, BotSnapshotView const& s, GroupSnapshotView c } // Hold on a target the bot is NOT attacking (the re-acquire paths): a melee -// bot still walks up to the mob - Karrz's "reach melee" was never vetoed - +// bot still walks up to the mob - the owner's "reach melee" was never vetoed - // so it is in place the moment the hold lifts. Returns true when it claimed // the tick. bool ThreatHoldWait(BotAI& ai, BotSnapshotView const& s, BotIntentEmitter& emit, @@ -1142,6 +1213,7 @@ bool ThreatHoldWait(BotAI& ai, BotSnapshotView const& s, BotIntentEmitter& emit, } } ai.set_last_rule_fired(h == ThreatHold::OverThreat ? "combat:threat_hold" + : h == ThreatHold::ShieldUp ? "combat:shield_hold" : "combat:threat_wait_tank"); return true; } @@ -1529,6 +1601,14 @@ bool SoloFleeTick(BotAI& ai, BotSnapshotView const& s, GroupSnapshotView const& } // anonymous +bool HeldByOwner(BotAI const& ai, BotSnapshotView const& s) +{ + if (!ai.holding_position(s.published_at_ms())) return false; + for (NearbyUnit const& at : s.raw().combat.attackers) + if (at.hp > 0 && at.victim == s.guid()) return false; + return true; +} + bool ThreatHoldActive(BotAI& ai, BotSnapshotView const& s, ObjectGuid target, GroupSnapshotView const* g) { @@ -1555,7 +1635,12 @@ bool MeleeSpreadSpot(BotSnapshotView const& s, GroupSnapshotView const& g, Nearb { const uint32 rank = (k + i * 3) % n; // a blocked slot tries the one three along float x, y; - MeleeArcSpot(s.guid().GetCounter(), rank, n, v.x, v.y, v.o, 1.0f, outer, x, y); + // Raid (playtest 2026-10-12): melee stack on the boss's back, nearly on top of each other, unless a boss rule spreads them. A 70 degree + // arc instead of the 160 degree one of a dungeon pack. + if (s.is_in_raid()) + MeleeArcSpot(s.guid().GetCounter(), rank, n, v.x, v.y, v.o, 1.0f, outer, x, y, 1.2217f); + else + MeleeArcSpot(s.guid().GetCounter(), rank, n, v.x, v.y, v.o, 1.0f, outer, x, y); if (RaidStandPointBlocked(s, x, y, v.z)) continue; ox = x; oy = y; static std::atomic s_last_log{ 0 }; @@ -1655,6 +1740,11 @@ void DispatchInCombat(BotAI& ai, // move it still consumes the tick at its old place below. const bool survival_item_used = MaybeUseSurvivalItem(snapshot, group, emit); + // The raid's resistance potion goes out the same way: alongside any raid move, not after it. It sat below the raid dispatch, which + // returns on every tick a bot has a move, a wait or a job, so only the bots the raid left idle ever drank it (Geddon, MC 2026-10-13: + // 9 of 40 bots drank, no mage did; a mage Living Bomb carrier took the full 3200 and died). + const bool resist_potion_used = !survival_item_used && MaybeUseResistPotion(snapshot, emit); + // Raid encounter orders (Bot/Raid): hazard moves, taunt swaps, dispels, // purges, crowd control and forbidden targets come before everything else. if (Raid::DispatchRaidOrder(ai, snapshot, emit)) @@ -2200,7 +2290,7 @@ void DispatchInCombat(BotAI& ai, // the anchor tank or around the pillar, staying out of the melee splash // and ground hazards - before the healer follow / gap-close below, which // only react to range. - // Under an owner Stay / Hold the bot keeps its spot unless a mob is on it (Karrz, Deadmines 2026-10-10: Edrin and Graziella + // Under an owner Stay / Hold the bot keeps its spot unless a mob is on it (playtest, Deadmines 2026-10-10: Edrin and Graziella // kept stepping 10-16 y for LoS under Stay). bool held_in_place = false; if (ai.holding_position(snapshot.published_at_ms())) @@ -2336,7 +2426,8 @@ void DispatchInCombat(BotAI& ai, // IGNORED instead. A human healer runs toward the hurt teammate. // When a group member is genuinely hurt (<65%) on this map and beyond // the heal gate, step toward them. Mirrors the melee gap-close. - if (snapshot.raw().group.my_role == Role::Healer && !snapshot.is_casting() && group.exists()) + // Same self-HP guard as the follow above: a healer under 40% with a mob on it heals itself instead of jogging to a hurt friend. + if (snapshot.raw().group.my_role == Role::Healer && !snapshot.is_casting() && snapshot.hp_pct() > 40 && group.exists()) { // Not mid-cast (see the follow above). Raid healer: never chase the // raid-wide lowest across the room. Close only on its heal_focus @@ -2440,7 +2531,10 @@ void DispatchInCombat(BotAI& ai, { auto const& th_po = snapshot.raw().pve_order; if (th_po.active && th_po.tank_hold && th_po.tank_target.IsEmpty() && snapshot.is_alive() && - !snapshot.is_casting() && snapshot.attackers_count() == 0) + !snapshot.is_casting() && snapshot.attackers_count() == 0 && + // ... unless a mob nobody was given stands on a group member: that one is this tank's to pick up or taunt, whatever the plan + // holds it for (n24 mc_garr: Mctankwb sat in tank_hold 7 y from a Firesworn on a healer, taunt ready, for a minute). + !snapshot.pickup_candidate()) { if (!snapshot.victim().IsEmpty()) emit.stop_attack(); @@ -2499,18 +2593,30 @@ void DispatchInCombat(BotAI& ai, // ---- The owner's skull (else cross) is the DPS target in every group ---- // The raid kill focus carries it in raids; 5-man and open-world groups have no coordinator focus, so a DPS bot that - // already fights something would stay on it (Karrz 2026-10-08: "DPS should follow the skull all the time"). Tanks hold + // already fights something would stay on it (playtest 2026-10-08: "DPS should follow the skull all the time"). Tanks hold // aggro and healers heal; an idle mark still needs the owner's order (MarkGate) and the tank's opening lead (threat hold). - if (!snapshot.in_battleground() && group.exists() && snapshot.is_alive() && !snapshot.is_casting()) + // The owner's latest Attack wins over a standing mark until its mob dies: a bot on the mob he just ordered stays on it. + const bool on_owner_attack = ai.is_manual_mode(snapshot.published_at_ms()) && + ai.owner_command() == BotAI::OwnerCommand::Engage && !ai.owner_target().IsEmpty() && snapshot.victim() == ai.owner_target(); + if (!snapshot.in_battleground() && group.exists() && snapshot.is_alive() && !snapshot.is_casting() && !on_owner_attack) { - ObjectGuid const skull = group.explicit_kill_mark(); + // Skull, else cross: a dead skull's icon can stay on the corpse (nothing clears it), which hid the cross. + ObjectGuid skull; + for (ObjectGuid const mark : { group.raid_mark(7), group.raid_mark(6) }) + { + if (mark.IsEmpty()) continue; + bool alive = false; + for (auto const& u : snapshot.nearby_enemies()) + if (u.guid == mark) { alive = u.hp > 0; break; } + if (alive) { skull = mark; break; } + } Role const sk_role = ai.effective_role(snapshot); - if (!skull.IsEmpty() && snapshot.victim() != skull && sk_role != Role::Tank && sk_role != Role::Healer) + if (!skull.IsEmpty() && snapshot.victim() != skull && sk_role != Role::Tank && sk_role != Role::Healer && + !HeldByOwner(ai, snapshot)) for (auto const& u : snapshot.nearby_enemies()) { if (u.guid != skull) continue; if (u.hp <= 0) break; - if (u.is_cc_locked && !u.cc_caster.IsEmpty()) break; // a mob the group controls is no kill call const uint32 sk_now = snapshot.published_at_ms(); const uint64 sk_key = skull.GetCounter(); if (!ai.action_recently_tried(BotAI::ActionKind::PveTargetSwitch, sk_key, sk_now) && @@ -2537,7 +2643,7 @@ void DispatchInCombat(BotAI& ai, { auto const& kf_po = snapshot.raw().pve_order; if (kf_po.active && !kf_po.kill_focus.IsEmpty() && - snapshot.is_alive() && !snapshot.is_casting() && + snapshot.is_alive() && !snapshot.is_casting() && !on_owner_attack && snapshot.victim() != kf_po.kill_focus) { for (auto const& u : snapshot.nearby_enemies()) @@ -2683,7 +2789,7 @@ void DispatchInCombat(BotAI& ai, if (fcx != 0.f || fcy != 0.f) { const float dx = fcx - bx, dy = fcy - by; - // An enemy within 30 y wins over the return (Karrz, WSG 2026-10-09: a druid on this rule stood in the tunnel for 40 s + // An enemy within 30 y wins over the return (playtest, WSG 2026-10-09: a druid on this rule stood in the tunnel for 40 s // with "no target" while enemy players ran past): the escort fights what is in front of it, and returns when none is close. bool escort_enemy_close = false; for (auto const& e : snapshot.nearby_enemies()) @@ -2777,7 +2883,7 @@ void DispatchInCombat(BotAI& ai, // runner's job IS to run the flag, not trade blows mid-field; // it pushes through, fighting only incidentally. Other roles // (Attacker/Defender/Healer) hold the line. - // 2026-10-08 (WSG test, Karrz: "running past each other without fighting"; [dps_idle] "85 s idle: + // 2026-10-08 (WSG test, the owner: "running past each other without fighting"; [dps_idle] "85 s idle: // combat:bg_fc_advance_flag, enemy at 3.8 y"): this rule returned before the rotation every tick, so every // Roamer / carrier-seeker ran through the enemy team without casting or swinging. An enemy within 22 y now wins: // the bot fights it (the rotation below closes and chases), and runs for the flag only when nothing hostile is @@ -2865,7 +2971,7 @@ void DispatchInCombat(BotAI& ai, // The `in_los` gate alone fixes that: a real raycast is clear // ONLY from a position with an actual shot. So engage the // instant the bot has LoS at normal combat range (<=40y, max - // cast range) and let the class AI position — casters fire from + // cast range) and let the class bot logic position — casters fire from // range, melee close to 5y. The old <=6y point-blank gate was a // workaround for the missing LoS check; with `in_los` it just // FORCED bots to chase the (moving) captain to within 6y before @@ -2976,7 +3082,7 @@ void DispatchInCombat(BotAI& ai, switch_rule = "combat:bg_focus_enemy_healer"; } } } - // Victim validity (Karrz, WSG 2026-10-09: a priest stood beside him swinging at nothing): a victim that is gone, dead, + // Victim validity (playtest, WSG 2026-10-09: a priest stood beside him swinging at nothing): a victim that is gone, dead, // untargetable, unreachable, or a creature that does not fight us while an enemy player is close is dropped for the // nearest enemy player, or released when there is none (the attacker seeding below picks the next one). if (switch_to.IsEmpty() && !snapshot.victim().IsEmpty()) @@ -3051,8 +3157,8 @@ void DispatchInCombat(BotAI& ai, // (Emitted above, ahead of the movement rules.) if (survival_item_used) return; - // Raid resistance potion (boss engaged, opt-in) - after the survival item. - if (MaybeUseResistPotion(snapshot, emit)) return; + // Raid resistance potion (boss engaged): emitted above, ahead of the raid orders. + if (resist_potion_used) return; // Mana refill for low-mana casters. Shares the potion CD with the // healing potion above; one will block the other in the API layer. @@ -3283,7 +3389,7 @@ void DispatchInCombat(BotAI& ai, // is_alive guard, not hp > 0: a released ghost main tank has hp == 1 // and would otherwise soak front-loaded heals all corpse run. // Classic 1.60 healers skip this pin: their APL heal picker - // (Combat/Apl/ApClassicHeal.h, Karrz's HealScore) already weighs the + // (Combat/Apl/ApClassicHeal.h, the owner's HealScore) already weighs the // heal_focus (+20) against emergencies elsewhere and downranks the cast, // and the retail ClassOocHeal ids are not the vanilla heals. { @@ -3351,6 +3457,7 @@ void DispatchInCombat(BotAI& ai, !raid_healer && IsMeleeSpec(snapshot.cls(), snapshot.spec())) { constexpr float kMeleeRange = 5.0f; + constexpr float kFleeLeashYd = 8.0f; // a fleeing mob this far from the bot is let go constexpr uint16 kStuckChaseTicksMax = 50; // ~5s @ 10Hz combat tier NearbyUnit const* vu = snapshot.victim_info(); if (vu) @@ -3367,15 +3474,30 @@ void DispatchInCombat(BotAI& ai, // waits at the edge, rotation running, until the tank's hazard // step-out (or the raid layer) moves the mob; the wait is not a // stuck chase. + // An owner Stay / Hold keeps the bot at its spot too: a mob out of reach is not chased (a mob on the bot lifts the hold). const bool chase_blocked = d2 > kMeleeRange * kMeleeRange && - snapshot.is_in_instance() && !snapshot.in_battleground() && - RaidStandPointBlocked(snapshot, vu->x, vu->y, vu->z); + ((snapshot.is_in_instance() && !snapshot.in_battleground() && + RaidStandPointBlocked(snapshot, vu->x, vu->y, vu->z)) || + HeldByOwner(ai, snapshot)); // Stuck-chase tracking: count ticks where we're out of melee // range with the same victim. Reset on different victim or once // we close distance. Past the cap → drop the chase to free the // bot from terrain-induced infinite gap-close loops. if (chase_blocked) ai.set_last_rule_fired("combat:melee_hold_hazard"); + else if (d2 > kMeleeRange * kMeleeRange && vu->is_fleeing && snapshot.is_in_dungeon() && d2 > kFleeLeashYd * kFleeLeashYd) + { + // A mob running for help is not chased (Deadmines 2026-10-13: the tank followed a fleeing Miner into the next + // packs). Melee stop and leave it to the ranged bots or its return; the engage shield keeps the target pick + // from taking it straight back. + if (RaidLogDue(RaidLogKey(snapshot, RaidLogKind::ThreatHold) ^ 0x666c6565u, snapshot.published_at_ms(), 5000u)) + TC_LOG_INFO("playerbot.v2", "[flee_chase] {} does not chase fleeing entry {} ({:.0f} y away)", snapshot.name(), vu->entry, std::sqrt(d2)); + emit.stop_attack(); + ai.note_engage(snapshot.victim(), snapshot.published_at_ms()); + ai.set_stuck_chase(ObjectGuid::Empty, 0); + ai.set_last_rule_fired("combat:flee_no_chase"); + return; + } else if (d2 > kMeleeRange * kMeleeRange) { if (ai.stuck_chase_victim() == snapshot.victim()) @@ -3386,8 +3508,43 @@ void DispatchInCombat(BotAI& ai, // (deadmines_full run 8: Rhahk'Zor on the priest for 57 s, the warrior silent after its 5 s chase cap). Its // chase ends when the mob is in reach (Taunt / melee) or dies; a victim it truly cannot path to is handled // above (unfightable skip) and by the mob's own leash. - bool const tank_keeps_chase = ai.effective_role(snapshot) == Role::Tank && vu->victim != snapshot.guid() && - ThreatVictim(vu->victim_kind) == ThreatVictim::Member; + bool tank_keeps_chase = ai.effective_role(snapshot) == Role::Tank && vu->victim != snapshot.guid() && + ThreatVictim(vu->victim_kind) == ThreatVictim::Member; + // ...but not far from the player it follows: in a dungeon a human leads, a mob that has run 30 y or more from him + // is not walked after (Deadmines 2026-10-13: the tank ended 44 y from the group chasing a Miner). The tank stops + // here, the group's own fight (and the mob's return) goes on. + // A fleeing mob (a low-health one running for help) is never walked after by a dungeon tank: it brings the next + // pack back with it, and the group's ranged finish it or it returns (playtest, Deadmines 2026-10-13). + if (tank_keeps_chase && vu->is_fleeing && snapshot.is_in_dungeon()) + tank_keeps_chase = false; + if (tank_keeps_chase && snapshot.raw().owner_in_group && snapshot.is_in_instance() && !snapshot.raw().owner_guid.IsEmpty()) + for (NearbyUnit const& f : snapshot.raw().combat.nearby_friends) + if (f.guid == snapshot.raw().owner_guid) + { + const float ox = vu->x - f.x, oy = vu->y - f.y; + constexpr float kTankChaseLeashYd = 30.0f; + if (ox * ox + oy * oy > kTankChaseLeashYd * kTankChaseLeashYd) + { + tank_keeps_chase = false; + if (RaidLogDue(RaidLogKey(snapshot, RaidLogKind::ThreatHold) ^ 0x6c656173u, snapshot.published_at_ms(), 5000u)) + TC_LOG_INFO("playerbot.v2", "[tank_chase] {} stops chasing entry {}: {:.0f} y from its owner (leash {:.0f} y)", + snapshot.name(), vu->entry, std::sqrt(ox * ox + oy * oy), kTankChaseLeashYd); + } + break; + } + // ...nor out of its healers' reach: in a 5-man the tank stays where the healer sees it and lets the mob come (the DPS + // finish it). Ends the chase at once, not after the stuck-chase window. + if (ai.effective_role(snapshot) == Role::Tank && vu->victim != snapshot.guid() && snapshot.beyond_healer_leash(vu->x, vu->y)) + { + if (RaidLogDue(RaidLogKey(snapshot, RaidLogKind::ThreatHold) ^ 0x68656c70u, snapshot.published_at_ms(), 5000u)) + TC_LOG_INFO("playerbot.v2", "[tank_chase] {} stops chasing entry {} ({:.0f}y away): further than the healer's reach", + snapshot.name(), vu->entry, std::sqrt(d2)); + emit.stop_attack(); + ai.note_engage(snapshot.victim(), snapshot.published_at_ms()); + ai.set_stuck_chase(ObjectGuid::Empty, 0); + ai.set_last_rule_fired("combat:tank_healer_leash"); + return; + } if (tank_keeps_chase && ai.stuck_chase_ticks() == kStuckChaseTicksMax && RaidLogDue(RaidLogKey(snapshot, RaidLogKind::ThreatHold) ^ 0x63687365u, snapshot.published_at_ms(), 5000u)) TC_LOG_INFO("playerbot.v2", "[tank_chase] {} keeps chasing entry {} ({:.0f}y away) held by a group member", @@ -3415,7 +3572,7 @@ void DispatchInCombat(BotAI& ai, // busy on someone else - slide to this bot's own spot, only when > 2 y from it, at most // every 3 s, never while casting, rooted or already walking. if (Services::Config().behavior_spread_out() && - (snapshot.is_in_raid() || vu->is_elite_or_rare) && + snapshot.is_in_raid() && vu->victim != snapshot.guid() && ai.effective_role(snapshot) != Role::Tank && !snapshot.is_rooted() && !snapshot.is_casting() && !snapshot.has_path_destination() && !ai.action_recently_tried(BotAI::ActionKind::RaidSpacing, 0, snapshot.published_at_ms())) @@ -3547,19 +3704,20 @@ void DispatchInCombat(BotAI& ai, // Only fires when not mid-cast (don't interrupt our own DPS cast for the // brez) and only when the dead target is on the same map. Server tracks // the per-encounter battle-rez budget; out-of-charges surfaces as - // ServerRefused and the AI moves on. brez_acked dedups against re-emits + // ServerRefused and the bot logic moves on. brez_acked dedups against re-emits // until the target rezzes (drops from dead_member) or leaves the group. if (group.exists() && !snapshot.is_casting()) { uint32 brez_spell = 0; switch (snapshot.cls()) { - case CLASS_DRUID: brez_spell = 20484; break; + case CLASS_DRUID: brez_spell = snapshot.spec() == 105 ? 0 : 20484; break; // Restoration: Rebirth sits in its APL after the heals (classic_resto:rebirth), one decider case CLASS_DEATH_KNIGHT: brez_spell = 61999; break; default: break; } // A tank holds the boss and never rezzes in the fight (MC Garr 2026-10-10: the bear tank cast Rebirth mid-fight, twice refused). - if (brez_spell != 0 && ai.effective_role(snapshot) != Role::Tank && snapshot.knows_spell(brez_spell) && snapshot.is_ready(brez_spell)) + if (brez_spell != 0 && ai.effective_role(snapshot) != Role::Tank && snapshot.knows_spell(brez_spell) && snapshot.is_ready(brez_spell) + && (snapshot.cls() != CLASS_DRUID || snapshot.power(0) >= snapshot.mana_cost(snapshot.resolve_rank(brez_spell) ? snapshot.resolve_rank(brez_spell) : brez_spell))) // mana: the core refuses an unaffordable Rebirth NO_POWER { // Target: a corpse in range and line of sight, healers then tanks // first. A corpse another member is already battle-rezzing (any @@ -3572,7 +3730,8 @@ void DispatchInCombat(BotAI& ai, [brez_cls](GroupMemberSummary const& m) { return m.cls == brez_cls && m.role != Role::Tank; }, /*in_combat_ok*/ true); // a combat rez: the rezzers are in the fight if (!dead.IsEmpty()) { - if (!ai.brez_acked() || ai.brez_target() != dead) + // A druid's Rebirth is retried each tick it is not casting (an interrupted or out-of-sight cast must not latch); RezTarget skips a corpse another druid is casting on. + if (snapshot.cls() == CLASS_DRUID || !ai.brez_acked() || ai.brez_target() != dead) { emit.cast(brez_spell, dead); ai.set_brez(dead, true); @@ -3598,7 +3757,7 @@ void DispatchInCombat(BotAI& ai, if (snapshot.is_casting()) return; // ---- Group threat discipline: DPS / healer restraint ---- - // Karrz's MCRaidHoldDamage: a non-tank bot must not out-threat the tank. + // the owner's MCRaidHoldDamage: a non-tank bot must not out-threat the tank. // While held on its victim it stops swinging / shooting / wanding // (cancel_cast here only ends the auto-repeat slot - a real cast already // returned above), calls its pet off that mob, and over the ratio sheds @@ -3624,6 +3783,7 @@ void DispatchInCombat(BotAI& ai, if (snapshot.has_pet() && snapshot.pet_victim() == hv) emit.pet_set_command_state(1 /*COMMAND_FOLLOW*/); ai.set_last_rule_fired(hold == ThreatHold::OverThreat ? "combat:threat_hold" + : hold == ThreatHold::ShieldUp ? "combat:shield_hold" : "combat:threat_wait_tank"); return; } @@ -3722,7 +3882,8 @@ void DispatchInCombat(BotAI& ai, } // Mobs on a healer that has nothing to cast: it walks to its tank (the mobs follow, and the tank's pick-up / Taunt // and AoE reach them) instead of standing and being killed. - if (snapshot.hp_pct() <= 60 && snapshot.attackers_count() >= 1 && !snapshot.is_rooted() && group.exists()) + if (snapshot.hp_pct() <= 60 && snapshot.attackers_count() >= 1 && !snapshot.is_rooted() && group.exists() && + !HeldByOwner(ai, snapshot)) // a healer told to stay / hold keeps its spot unless a mob is on it (then it walks) if (GroupMemberSummary const* tk = group.tank(); tk && tk->online && tk->is_alive && tk->map_id == snapshot.map_id()) { float hx, hy, hz; diff --git a/src/modules/PlayerbotV2/Bot/States/State_InGroup.cpp b/src/modules/PlayerbotV2/Bot/States/State_InGroup.cpp index f116b3182e..1b1a15c49f 100644 --- a/src/modules/PlayerbotV2/Bot/States/State_InGroup.cpp +++ b/src/modules/PlayerbotV2/Bot/States/State_InGroup.cpp @@ -19,6 +19,8 @@ #include #include "Travel/UnifiedTravelGraph.h" #include "SharedDefines.h" +#include "Bot/ThreatDiscipline.h" // ThreatOpeningLead (passive, tank first) +#include "Bot/ClassicUpkeep.h" // IsEating / IsDrinking (stand to defend) #include "Log.h" #include #include @@ -314,17 +316,19 @@ void DispatchInGroup(BotAI& ai, { if (!ai.ready_check_acked()) { - // Real information (Karrz's ReadyCheckAction): low health, a mana - // user low on mana or broken gear answers not ready and says why + // Real information (the owner's ReadyCheckAction): badly low health, a mana + // user badly low on mana or broken gear answers not ready and says why // in party chat; the out-of-combat recovery rules then drink / eat // / repair. The check is advisory, nothing else waits on the answer. + // A bot a little under (just arrived, a buff cast) is ready: the whole raid answering + // "not ready" after a call-up read as broken (playtest 2026-10-13). bool ready = true; char const* why = nullptr; if (Services::Config().behavior_ready_check_info()) { - if (snapshot.hp_pct() < 60) + if (snapshot.hp_pct() < 35) { ready = false; why = "low hp, eating first"; } - else if (snapshot.max_power(POWER_MANA) > 0 && snapshot.power_pct(POWER_MANA) < 60) + else if (snapshot.max_power(POWER_MANA) > 0 && snapshot.power_pct(POWER_MANA) < 35) { ready = false; why = "low on mana, drinking first"; } else if (snapshot.lowest_equipped_durability_pct() < 15) { ready = false; why = "my gear is broken, need a repair"; } @@ -362,10 +366,17 @@ void DispatchInGroup(BotAI& ai, // re-marking mid-fight thrashes assist targets. Trigger only on the // leader's tick; the published skull propagates to all bot members // through the next group snapshot. - // In a raid with Playerbot.Behavior.TankMarkers on, the raid coordinator marks the tanks' mobs (the main - // tank's mob is the skull, PveGroupCoordinator::PlanRaidTanks): no second auto-skull from the leader. + // In a raid with Playerbot.Behavior.TankMarkers on, the raid coordinator marks the tanks' mobs with the symbols + // 0-5 (PveGroupCoordinator::PlanRaidTanks never uses skull or cross, those stay the owner's kill call): no second + // auto-skull from the leader. + // A human in the group owns the marks (playtest 2026-10-15): the leader bot never calls a skull over his, so only an + // all-bot group gets the auto-skull. + bool group_has_human = false; + if (auto const* mems = group.members()) + for (auto const& m : *mems) + if (m.online && !m.is_bot) { group_has_human = true; break; } if (snapshot.in_combat() && !group.leader().IsEmpty() && - group.leader() == snapshot.raw().guid && + group.leader() == snapshot.raw().guid && !group_has_human && !(group.is_raid() && Services::Config().behavior_tank_markers())) { const ObjectGuid current_skull = group.skull_target(); @@ -458,11 +469,7 @@ void DispatchInGroup(BotAI& ai, group.leader() == snapshot.raw().guid) { const ObjectGuid current_skull = group.skull_target(); - bool human = false; - if (auto const* mems = group.members()) - for (auto const& m : *mems) - if (m.online && !m.is_bot) { human = true; break; } - if (!current_skull.IsEmpty() && !human) + if (!current_skull.IsEmpty() && !group_has_human) for (auto const& u : snapshot.raw().combat.nearby_enemies) { if (u.guid != current_skull) continue; @@ -487,7 +494,7 @@ void DispatchInGroup(BotAI& ai, // already running the APL. if (ai.state() == BotState::InCombat) return; - // A companion follows its owner, the human it came with, even when a bot holds the lead (Karrz's GetGroupMaster). + // A companion follows its owner, the human it came with, even when a bot holds the lead (the owner's GetGroupMaster). // While the owner is offline or on another map (a taxi, a zone-in) it falls back to the group's leader. ObjectGuid leader = group.leader(); auto const* members = group.members(); @@ -670,48 +677,36 @@ void DispatchInGroup(BotAI& ai, // Tanks pick their own targets via threat; they ignore assist but DO // honor skull (so they can pull/taunt the focus mob). // - // Aggression personality gates whether the bot proactively engages: - // - Passive: never assist on its own. Owner-pinned focus_target still - // wins (focus is an explicit owner directive, not assist), and the - // bot still defends itself via the InCombat dispatch when attacked. - // Useful for "follow but don't fight" RP / escort scenarios. - // - Defensive: assist only when the group is taking attrition damage - // (any same-map member <50% HP). Skips skull-mark assist and the - // leader-victim pile-on when the group looks healthy — Defensive - // bots conserve resources and let the tank manage trash. Owner - // focus + dropping below the wound threshold still engages. - // - Normal / Aggressive: full assist chain (focus → skull → leader - // victim → any in-combat member's victim). Identical for now; - // Aggressive is reserved for future opportunistic-pulling rules. + // Full assist chain: focus, skull, leader victim, any in-combat member's victim. The owner's stance and orders gate it, not + // the bot's personality. // Told to stay: keep the spot rather than run to the group's target, as a Passive bot would (it still fights back // when attacked). - const bool staying = ai.is_manual_mode(snapshot.published_at_ms()) && ai.owner_command() == BotAI::OwnerCommand::Stay; - const Aggression agg = staying ? Aggression::Passive : ai.personality().aggression; + const bool staying = ai.holding_position(snapshot.published_at_ms()); // Stay or Hold ("defensive": fights only what attacks) + // The bot's random personality does not decide who joins a fight: the owner's stance and orders are the only input here. // Owner "passive": no assist on the owner's, the skull's or a member's target; only a mob already on a group member is engaged // (the defend-member step below). Stance Passive, or Auto in an instance a human leads (BotAI::passive_now); an attack / pull // order opens a 15 s window in which it fights. const bool owner_passive = ai.passive_now(snapshot.is_in_instance() && !group.leader_is_bot()); - const bool has_focus_pin = !staying && !owner_passive && !ai.focus_target().IsEmpty(); - bool group_is_wounded = false; - if (agg == Aggression::Defensive) + // A Passive bot inside an order window (every Attack / Pull / assist order opens 15 s of it) joins the owner's own target and + // nothing wider: no skull, no kill focus, no other member's victim, no creature outside its scan or far from the owner (the owner, + // Deadmines 2026-10-15: "the bots were attacking willy-nilly, hitting things that weren't close to me"; with Attack pressed every few + // seconds the window never closed and the whole assist chain ran, the tank opening on mobs 32-43 y away). + const bool window_limited = !owner_passive && + (ai.owner_stance() == BotAI::OwnerStance::Passive || + (ai.owner_stance() == BotAI::OwnerStance::Auto && snapshot.is_in_instance() && !group.leader_is_bot())); + // A pet never starts a pull. PetAttack (the bot's own assist) leaves the pet Aggressive for good, and an aggressive pet + // pulls every mob around it while the group stands still (Deadmines, 2026-10-13). Between fights the pet goes back to + // Defensive (it fights what attacks its owner or itself), and to Passive when the group is told to stay or is passive. + // In a fight the bot's own attack orders move it again. + if (!snapshot.in_combat() && !snapshot.recently_in_combat(3000) && snapshot.has_pet()) { - for (auto const& m : *members) - { - if (!m.online || m.map_id != snapshot.map_id() || m.hp <= 0) continue; - if (m.max_hp > 0 && (int64(m.hp) * 100) < (int64(m.max_hp) * 50)) - { group_is_wounded = true; break; } - } + uint8 const want = (staying || owner_passive) ? 0 : 1; + uint8 const have = snapshot.pet_react(); + if (have != want && (want == 0 || have == 2)) + emit.pet_set_react_state(want); } - // Combat-in-progress override: if ANY same-map group member is - // currently in combat, every non-Passive bot assists. This is a - // symptom-driven signal — we *see* combat happening — and is more - // reliable than the dungeon-active flag (which can be inconsistent - // across the squad when `;all run` doesn't land on every bot, or - // when the squad is fighting world-content without the dungeon - // mode set). Real-player intent: "the group is fighting, I help." - // Defensive personality stops being "wait for HP to drop below 50%" - // and becomes "join the fight already in progress." Passive stays - // opted out (owner explicitly told it to never assist). + // Combat-in-progress signal: ANY same-map group member currently in combat. Symptom-driven and more reliable than the + // dungeon-active flag (which can be inconsistent across the squad when `;all run` doesn't land on every bot). bool any_member_in_combat = false; for (auto const& m : *members) { @@ -720,12 +715,10 @@ void DispatchInGroup(BotAI& ai, if (m.in_combat) { any_member_in_combat = true; break; } } const bool engage_allowed = - owner_passive || ai.owner_stance() == BotAI::OwnerStance::Aggressive || - (agg != Aggression::Passive) - ? (agg != Aggression::Defensive || group_is_wounded || - has_focus_pin || any_member_in_combat) - : has_focus_pin; - if (engage_allowed) + owner_passive || ai.owner_stance() == BotAI::OwnerStance::Aggressive || !staying; + // Not in a battleground: BgDispatch (State_Idle) and the in-combat BG layer own movement and targets there. This chain trusts + // creature victims at any range, so a teammate's fight with a mob pulled a bot off its ordered march (AV tower runs). + if (engage_allowed && !snapshot.in_battleground()) { if (snapshot.victim().IsEmpty()) { @@ -743,9 +736,7 @@ void DispatchInGroup(BotAI& ai, if (u.guid == focus && u.hp > 0) { assist_target = focus; break; } } // Skull mark wins for everyone (after focus). Only use it if it's - // actually nearby — out-of-vision skulls are stale. Defensive bots - // skip skull pile-ons (the tank can manage their own kill order) - // unless the group is already wounded enough to need extra DPS. + // actually nearby — out-of-vision skulls are stale. // // CRITICAL: non-tanks must wait for the tank (or another group // member) to be engaged with the skull before opening on it. @@ -755,8 +746,7 @@ void DispatchInGroup(BotAI& ai, // should be pulling it). Observed 2026-05-15: Defensive // warlock attacked skull immediately on mark, before tank // had any threat. Causes loss-of-aggro wipes. - if (assist_target.IsEmpty() && !owner_passive && - (agg != Aggression::Defensive || group_is_wounded)) + if (assist_target.IsEmpty() && !owner_passive && !window_limited) { if (ObjectGuid skull = group.skull_target(); !skull.IsEmpty()) { @@ -800,7 +790,7 @@ void DispatchInGroup(BotAI& ai, // It names only mobs already fighting the group, so it outranks the // leader's victim: a raid DPS joins the coordinated target instead // of whatever the (often human, non-tank) leader is hitting. - if (assist_target.IsEmpty() && !owner_passive && ai.effective_role(snapshot) != Role::Tank) + if (assist_target.IsEmpty() && !owner_passive && !window_limited && ai.effective_role(snapshot) != Role::Tank) { auto const& kf = snapshot.raw().pve_order; if (kf.active && !kf.kill_focus.IsEmpty()) @@ -835,13 +825,30 @@ void DispatchInGroup(BotAI& ai, // wedge class this guard exists for involved Player/Pet // guids only, and start_attack's IsValidAttackTarget gate // refuses anything that slips through at engage time. - return v.IsCreature(); + // In a raid only what the scan holds: a victim outside the scan has no threat figures (ThreatHold reads none and lets it through), so a + // raid DPS 87 y out at the lair's cliff edge opened on Onyxia the moment the tank was ordered, before any hold applied + // (onyxia_full n57 run 1: Mcshadb first, the lair whelps joined the pull at 12 s). It opens once the mob is in its scan. + return v.IsCreature() && !snapshot.is_in_raid(); }; - if (resolves_hostile(leader_member->victim)) + if (window_limited) + { + // The owner's own target only, in the bot's scan and within 25 y of the owner. + for (auto const& u : snapshot.raw().combat.nearby_enemies) + { + if (u.guid != leader_member->victim || u.hp <= 0) continue; + float const lx = u.x - leader_member->x, ly = u.y - leader_member->y; + if (lx * lx + ly * ly <= 25.f * 25.f) assist_target = u.guid; + break; + } + } + // Only members on this bot's own map: a raider out of the instance (a corpse run, a graveyard) fights what it meets there, and + // copying it set the stray bots fighting each other's mobs in Eastvale while the raid lay dead in Onyxia's Lair, so a member of + // the group stayed in combat and the owner could not release (n58 live 2026-10-15 11:28, Amastorion). + else if (leader_member->map_id == snapshot.map_id() && resolves_hostile(leader_member->victim)) assist_target = leader_member->victim; - if (assist_target.IsEmpty()) + if (assist_target.IsEmpty() && !window_limited) for (auto const& m : *members) - if (m.online && m.in_combat && resolves_hostile(m.victim)) + if (m.online && m.map_id == snapshot.map_id() && m.in_combat && resolves_hostile(m.victim)) { assist_target = m.victim; break; } } // Defend-member engage (ALL roles, tanks very much included): a mob @@ -864,10 +871,22 @@ void DispatchInGroup(BotAI& ai, { if (u.hp <= 0 || u.victim.IsEmpty() || !u.in_los) continue; bool attacks_member = (u.victim == snapshot.raw().guid); + GroupMemberSummary const* victim_member = nullptr; if (!attacks_member) for (auto const& m : *members) - if (m.guid == u.victim) { attacks_member = true; break; } + if (m.guid == u.victim) { attacks_member = true; victim_member = &m; break; } if (!attacks_member) continue; + // Passive, tank first (playtest 2026-10-14): a mob on another member is the tank's to pick up; a damage bot joins once the + // tank has its opening lead, or at once when the member it is on is under 70 % (a healer waits for nothing here: it heals). + if (owner_passive && victim_member && ai.effective_role(snapshot) == Role::Dps && !u.is_player) + if (GroupMemberSummary const* gt = group.tank(); + gt && gt->is_alive && gt->online && gt->map_id == snapshot.map_id() && gt->guid != snapshot.raw().guid && + victim_member->hp_pct() >= 70 && + // Bounded: the threat hold releases on the tank's lead or after its opening wait (a party's 6 s from the tank's first + // damage), so a tank that never reaches the lead (Deadmines 2026-10-15: Disc on the Overseer, the damage bots + // stood for the whole fight) does not hold the group out for good. + ThreatHoldActive(ai, snapshot, u.guid, &group)) + continue; // A spare duty tank (the plan gave it tank duty but the main tank holds the pull) stays near the // pack until a mob hits it itself or the plan assigns it one; it does not run at every mob that // hits a member before the fight has started. @@ -877,7 +896,30 @@ void DispatchInGroup(BotAI& ai, if (dsq < best_dsq) { best_dsq = dsq; assist_target = u.guid; } } } + // Defending stands a bot up (playtest, Deadmines 2026-10-15: "the mage is getting attacked and the other three guys are just + // sitting drinking"). A meal or drink is only broken by the bot's own damage or by standing, so a seated bot whose group + // member has a mob on it gets to its feet at once, ahead of the tank-first wait and whether or not it has the mob in sight. + if ((Classic::IsEating(snapshot) || Classic::IsDrinking(snapshot)) && snapshot.is_alive()) + { + float ex, ey, ez; snapshot.position(ex, ey, ez); + for (auto const& u : snapshot.raw().combat.nearby_enemies) + { + if (u.hp <= 0 || u.victim.IsEmpty()) continue; + bool on_member = (u.victim == snapshot.raw().guid); + if (!on_member) + for (auto const& m : *members) + if (m.guid == u.victim && m.online && m.is_alive) { on_member = true; break; } + if (!on_member) continue; + float const edx = u.x - ex, edy = u.y - ey; + if (edx * edx + edy * edy > 40.f * 40.f) continue; + emit.stand(); + ai.set_last_rule_fired("ingroup:stand_to_defend"); + return; + } + } // Aggressive stance: any hostile close to the owner is attacked, whether or not anyone is fighting yet. + // In a party the owner told it to go: the tank-first hold below does not cap this pick (a raid keeps it). + bool aggressive_pick = false; if (assist_target.IsEmpty() && ai.owner_stance() == BotAI::OwnerStance::Aggressive && !group.leader_is_bot()) { float best_dsq = std::numeric_limits::max(); @@ -889,24 +931,40 @@ void DispatchInGroup(BotAI& ai, const float d2 = ox * ox + oy * oy; if (d2 <= kR2 && d2 < best_dsq) { best_dsq = d2; assist_target = u.guid; } } + aggressive_pick = !assist_target.IsEmpty() && !snapshot.is_in_raid(); } // Threat discipline (State_InCombat.cpp ThreatHoldActive): a non-tank // does not open on the tank's mob until the tank has its opening lead. if (!assist_target.IsEmpty() && assist_target != snapshot.victim() && - !ThreatHoldActive(ai, snapshot, assist_target, &group)) + (aggressive_pick || !ThreatHoldActive(ai, snapshot, assist_target, &group))) { emit.start_attack(assist_target); ai.set_last_rule_fired("ingroup:assist"); + // Why a bot opened on its own (playtest, Deadmines 2026-10-15: "they run in as if not passive"): the stance, the order window + // and the mob's state at the moment of the opener, once a second per bot at most. + static std::atomic s_assist_why_ms{ 0 }; + uint32 const now_aw = snapshot.published_at_ms(); + uint32 last_aw = s_assist_why_ms.load(std::memory_order_relaxed); + if (now_aw - last_aw >= 500u && s_assist_why_ms.compare_exchange_strong(last_aw, now_aw)) + { + NearbyUnit const* au = nullptr; + for (auto const& u : snapshot.raw().combat.nearby_enemies) + if (u.guid == assist_target) { au = &u; break; } + float ax = 0.f, ay = 0.f, az = 0.f; snapshot.position(ax, ay, az); + float const ad = au ? std::sqrt((au->x - ax) * (au->x - ax) + (au->y - ay) * (au->y - ay)) : -1.f; + TC_LOG_INFO("playerbot.v2", + "[assist_why] {} opens on entry {} ({:.0f}y): stance {} passive_now {} order_window {} follow_order {} mob in_combat {} mob_victim_kind {} tank_threat {}", + snapshot.name(), au ? au->entry : 0u, ad, int(ai.owner_stance()), owner_passive ? 1 : 0, + ai.owner_order_window_open() ? 1 : 0, ai.owner_follow_order() ? 1 : 0, au && au->unit_in_combat ? 1 : 0, + au ? int(au->victim_kind) : -1, au ? au->tank_threat : -1); + } } } else { // Bot already has a victim. Honor focus pivots first, then skull // pivots. Focus is owner-pinned and outranks the raid leader's - // skull mark; both override the bot's pre-engaged target. Defensive - // bots still pivot off focus (owner directive) but skip skull - // pivots when the group is healthy — same conserve-resource logic - // as the open-engage path. + // skull mark; both override the bot's pre-engaged target. if (ObjectGuid focus = ai.focus_target(); !focus.IsEmpty() && focus != snapshot.victim()) { @@ -918,7 +976,6 @@ void DispatchInGroup(BotAI& ai, return; } } - if (agg != Aggression::Defensive || group_is_wounded) { if (ObjectGuid skull = group.skull_target(); !skull.IsEmpty() && skull != snapshot.victim()) @@ -993,8 +1050,11 @@ void DispatchInGroup(BotAI& ai, // bot tell). ComputeFormationOffset yields the per-slot // distance+angle for the owner-configured formation; Free/slot-0 // collapses to a plain follow so unconfigured squads are unchanged. + // One formation system at a time: with the owner formation on (Playerbot.Behavior.Formation) the slot ring below is the + // formation, and the plain follow is the rest; the legacy fixed 12 y circle / 8 y spread would otherwise take over the moment + // any member fights and send the group out of the owner's heal / buff range. FormationOffset formation_offset = ComputeFormationOffset( - ai.effective_formation_type(snapshot.in_combat()), + Services::Config().behavior_formation() ? FormationType::Free : ai.effective_formation_type(snapshot.in_combat()), ai.formation_slot(), kFollowDistance); // Owner formation (circle / arrow / line / column + spacing preset, Playerbot.Behavior.Formation): a stable @@ -1103,6 +1163,13 @@ void DispatchInGroup(BotAI& ai, dist < kDetourMaxRange; // Owner said stay/hold: keep the spot until follow/resume. const bool holding_position = ai.holding_position(snapshot.published_at_ms()); + // An Attack / Pull walk to the ordered mob, or a pull back's approach and retreat, is the idle rules' movement (this layer runs + // after them): a follow or slot move here would walk the tank back to the owner mid-pull. Bounded to 45 y so a bot that is + // far from the owner still rejoins. + const bool order_owns_movement = + (ai.pull_back_active() || + (ai.is_manual_mode(snapshot.published_at_ms()) && ai.owner_command() == BotAI::OwnerCommand::Engage)) && + dist < kDetourMaxRange; bool const refollow = ai.take_formation_refollow(); // Owner formation: the bot's goal is its SLOT, recomputed every tick from the owner's live position and facing, // not "within the recall slack of the owner" (a slot ring wider than the slack, or any spot inside the ring, @@ -1115,7 +1182,7 @@ void DispatchInGroup(BotAI& ai, auto& ft = ai.formation_track(); constexpr float kArriveYd = 1.5f, kStartYd = 2.5f, kRetargetYd = 2.0f; constexpr uint32 kMinReissueMs = 500, kStuckMs = 3000, kFallbackMs = 8000; - bool const gated = in_active_bg || dungeon_run_owns_movement || detour_leased || holding_position || snapshot.is_rooted(); + bool const gated = in_active_bg || dungeon_run_owns_movement || detour_leased || holding_position || order_owns_movement || snapshot.is_rooted(); float const slot_dist = DistanceXY(bx, by, slot_x, slot_y); bool const moving = snapshot.raw().movement.is_moving; // 0 = none, 1 = move, 2 = hold, 3 = fallback @@ -1172,7 +1239,7 @@ void DispatchInGroup(BotAI& ai, ai.formation_track().dest_valid = false; if (!formation_slot_active && - !in_active_bg && !dungeon_run_owns_movement && !detour_leased && !holding_position && + !in_active_bg && !dungeon_run_owns_movement && !detour_leased && !holding_position && !order_owns_movement && (dist > kRecallSlack || (refollow && dist > 1.5f)) && !snapshot.is_rooted()) { // Follow uses MotionMaster MoveFollow, which silently re-emits forever diff --git a/src/modules/PlayerbotV2/Bot/States/State_Stubs.cpp b/src/modules/PlayerbotV2/Bot/States/State_Stubs.cpp index 5e64b3b709..eef1147513 100644 --- a/src/modules/PlayerbotV2/Bot/States/State_Stubs.cpp +++ b/src/modules/PlayerbotV2/Bot/States/State_Stubs.cpp @@ -14,7 +14,9 @@ namespace Playerbot::States { -void DispatchLoggingIn (BotAI&, BotSnapshotView, GroupSnapshotView, BotIntentEmitter&) {} +// Reserved, not live: BotAI::transition_to is only ever called with Idle, InCombat and Dead, and the layer dispatchers below are +// never called (BotAI::tick has no detection for them yet). The Idle rules and the idle:* walkers do this work today. +void DispatchLoggingIn (BotAI&, BotSnapshotView, GroupSnapshotView, BotIntentEmitter&) {} void DispatchLoggingOut (BotAI&, BotSnapshotView, GroupSnapshotView, BotIntentEmitter&) {} void DispatchTravelling (BotAI&, BotSnapshotView, GroupSnapshotView, BotIntentEmitter&) {} void DispatchQuesting (BotAI&, BotSnapshotView, GroupSnapshotView, BotIntentEmitter&) {} diff --git a/src/modules/PlayerbotV2/Bot/ThreatDiscipline.h b/src/modules/PlayerbotV2/Bot/ThreatDiscipline.h index fa4d5fd960..48b6279491 100644 --- a/src/modules/PlayerbotV2/Bot/ThreatDiscipline.h +++ b/src/modules/PlayerbotV2/Bot/ThreatDiscipline.h @@ -1,10 +1,10 @@ // ThreatDiscipline.h - shared group threat rules for non-tank damage, AoE and -// healing (port of Karrz's ike3-based bots GroupPveRestraint / MCRaidHoldDamage, +// healing (port of Karrz's wow-1.12 GroupPveRestraint / MCRaidHoldDamage, // generalised to any group with a tank). // // Pure functions of the bot's snapshot (NearbyUnit my_threat / tank_threat / // victim_kind / is_cc_locked / unit_in_combat, stamped by BotSnapshotBuilder -// from each mob's ThreatManager), so they are safe on the AI worker threads +// from each mob's ThreatManager), so they are safe on the bot worker threads // and usable from the class rotations (Combat/Apl) as well as the states. // // * ThreatOpeningLead: the threat a tank must hold on a mob before the rest @@ -35,7 +35,7 @@ namespace Playerbot { -// True once per `interval_ms` for `key`. Shared across the AI worker threads. +// True once per `interval_ms` for `key`. Shared across the bot worker threads. inline bool RaidLogDue(uint64 key, uint32 now_ms, uint32 interval_ms) { static std::mutex mu; @@ -57,6 +57,7 @@ enum class RaidLogKind : uint8 { ThreatHold = 1, AoeHold = 2, PullHeld = 4, PullSkip = 5, OpenerHold = 6, // [raid_pull] non-tank opener on an unpulled mob (PrologueRules) + PullBackOpener = 7, // [pull_back] no ranged opener for this tank (PrologueRules) Escape = 16, CancelHeal = 17, Rez = 18, // [raid_escape], overheal cancel, rez spread Interrupt = 32, Tranq = 33, FearHold = 34, // [raid_interrupt], [raid_tranq], [raid_threat] fear hold Hazard = 48, Los = 49, Cone = 50, // [raid_hazard], [raid_los], [raid_cone] (State_Idle) @@ -81,7 +82,7 @@ inline bool ThreatDisciplineApplies(BotSnapshotView const& s) return !s.group_tank().IsEmpty(); } -// Karrz: bosses need ~900 threat (three tank GCDs at 60) before anyone opens, +// the owner: bosses need ~900 threat (three tank GCDs at 60) before anyone opens, // trash ~250 so the group rolls from one pack member to the next. Threat // scales with damage, i.e. with level - scaled down for levelling dungeons // (floor 15% so a level-15 tank still gets a lead). @@ -166,7 +167,8 @@ inline AoeHazard FindAoeHazard(BotSnapshotView const& s, float cx, float cy, flo if (hit.unit || !tanked || !u.has_threat_list) return false; // keep the first soft hazard if (!u.unit_in_combat) { hit = { &u, AoeHazardKind::Unpulled }; return false; } - if (!me_tank && ThreatVictim(u.victim_kind) == ThreatVictim::Tank && TankNotSecured(s, u)) + // Raid only: a party's AoE is not held for the tank's lead (the Unpulled and CC guards above still apply). + if (s.is_in_raid() && !me_tank && ThreatVictim(u.victim_kind) == ThreatVictim::Tank && TankNotSecured(s, u)) { hit = { &u, AoeHazardKind::NotTanked }; return false; } return false; }; @@ -271,13 +273,13 @@ inline NearbyUnit const* NearestUnpulled(BotSnapshotView const& s, float radius, // Raid gate for the emergency AoE fears (Psychic Scream, Howl of Terror). A // feared mob runs up to ~40y in a random direction and drags any pack it runs -// into, so in a raid group the fear holds while an unpulled mob is within 40y -// of the caster, and it is only for a bot an elite (or boss) is actually -// hitting - not for a bot standing next to mobs the tanks hold. Outside raid -// groups the callers' own conditions apply unchanged. +// into, so in a raid group or an instance the fear holds while an unpulled mob +// is within 40y of the caster. In a raid it is also only for a bot an elite (or +// boss) is actually hitting - not for a bot standing next to mobs the tanks +// hold. Elsewhere the callers' own conditions apply unchanged. inline bool RaidFearAllowed(BotSnapshotView const& s, bool raid_group, char const* what) { - if (!raid_group || s.in_battleground()) return true; + if ((!raid_group && !s.is_in_instance()) || s.in_battleground()) return true; constexpr float kFearPullRange = 40.0f; float d = 0.f; if (NearbyUnit const* u = NearestUnpulled(s, kFearPullRange, &d)) @@ -288,6 +290,8 @@ inline bool RaidFearAllowed(BotSnapshotView const& s, bool raid_group, char cons s.name(), what, d, u->entry, u->guid.GetCounter()); return false; } + if (!raid_group) + return true; for (NearbyUnit const& u : s.nearby_enemies()) if (u.hp > 0 && !u.is_player && u.victim == s.guid() && (u.is_elite_or_rare || (u.is_dungeon_boss || u.is_boss_rank))) return true; diff --git a/src/modules/PlayerbotV2/Bot/ThreatLimits.h b/src/modules/PlayerbotV2/Bot/ThreatLimits.h new file mode 100644 index 0000000000..3d54562b55 --- /dev/null +++ b/src/modules/PlayerbotV2/Bot/ThreatLimits.h @@ -0,0 +1,50 @@ +// ThreatLimits - the one place the hard threat limits live, shared by the generic damage hold (States::EvaluateThreatHold) and the raid +// brain's hold orders (Raid::PublishThreatHolds). A mob switches to a non-tank at 110 % of the tank's threat in melee reach and 130 % at +// range; the hold never releases at or past these ratios, however long it has lasted (the release after a few seconds only applies below +// them). With separate copies, a caster at 1.15 x the tank was released by the brain and held for good by the generic gate. + +#pragma once + +namespace Playerbot { + +constexpr float kThreatHardRatioMelee = 1.0f; // a melee DPS never releases above the tank's own threat +constexpr float kThreatHardRatioCaster = 1.10f; // a caster keeps a tenth of margin under the 130 % a ranged attacker needs + +// A raid tank with tens of thousands of threat takes one cast as a few percent, so a caster keeps ten points under the 130 % there (n10 +// mc_geddon: a mage held at 109 % of the tank for 20 s while the tank, out of melee in the Inferno, gained nothing). Early in a pull the +// tank holds a few thousand and one Frostbolt is a fifth of it: below kRaidTankThreatFloor the 110 % limit stays. +constexpr float kThreatHardRatioCasterRaid = 1.20f; +constexpr float kRaidTankThreatFloor = 8000.0f; + +constexpr float ThreatHardRatio(bool melee, bool raid = false, float tank_threat = 0.0f) +{ + return melee ? kThreatHardRatioMelee + : (raid && tank_threat >= kRaidTankThreatFloor ? kThreatHardRatioCasterRaid : kThreatHardRatioCaster); +} + +// A hold that starts at the tank's own threat is too late while the tank holds only a few thousand: the next cast is already in flight and +// is a large share of it (n14 Onyxia: tank 1586, a Frostbolt about 700, three casts took a mage to 132 % before the first poll could hold it). +// The hold therefore starts, and is not released, at the ratio from which one more typical hit still leaves the bot under the ratio that +// takes the boss (130 % ranged, 110 % melee, less a margin). That ratio reaches the normal limits once the tank holds a few thousand: a +// bound by tank threat alone froze casters for 20 s on Geddon, whose tank stands at 6-7k for half a minute (n17 mc_geddon). +constexpr float kNextHitThreatRanged = 1000.0f; // a crit Frostbolt or Fireball +constexpr float kNextHitThreatMelee = 350.0f; +constexpr float kPullSafeRanged = 1.25f; +constexpr float kPullSafeMelee = 1.05f; +constexpr float kMinEarlyHoldRatio = 0.4f; + +// The ratio of the tank's threat a non-tank holds at: , or lower while one typical hit would take the bot past kPullSafe* (never +// under kMinEarlyHoldRatio). Unknown tank threat leaves . +// is what stays of the tank's threat after the boss's scheduled cut (1 when it has none): the pull-safe ratio is measured against the +// tank as it will be after the cut (n17 Onyxia: a crit took a mage held at 75 % of the tank to 105 % of it, 140 % of the tank after the cut). +constexpr float ThreatEarlyHoldRatio(float base, bool melee, float tank_threat, float share = 1.0f) +{ + if (tank_threat <= 0.0f) + return base; + float const r = (melee ? kPullSafeMelee : kPullSafeRanged) * share - (melee ? kNextHitThreatMelee : kNextHitThreatRanged) / tank_threat; + float const floor = kMinEarlyHoldRatio < base ? kMinEarlyHoldRatio : base; + float const lowered = r < base ? r : base; + return lowered > floor ? lowered : floor; +} + +} // namespace Playerbot diff --git a/src/modules/PlayerbotV2/Bot/TownLife.h b/src/modules/PlayerbotV2/Bot/TownLife.h new file mode 100644 index 0000000000..4ef31d0167 --- /dev/null +++ b/src/modules/PlayerbotV2/Bot/TownLife.h @@ -0,0 +1,107 @@ +// TownLife - the small shows of a living town: bots resting at the inn at night, pairs duelling, a campfire, an LFG call for a +// dungeon of their level. Pure rules and one small shared table; the rules that use them are in Bot/States/Rules/AmbientRules.cpp. +// +// The cost is kept low by taking part, not by counting: a bot takes part in a show only when a hash of (bot, show, time window) falls +// under the show's share, so only a few percent of the world bots are ever on show at once, with no global counter. Tested in +// tests/game/ClassicTownLife.cpp. + +#pragma once + +#include +#include +#include +#include +#include + +namespace Playerbot::V2::TownLife +{ + +// What the shows did since the server started, for the [world] report line. Counted when a rule fires, so inn_ticks and mailbox_ticks +// are bot-ticks on the show (walking or standing), duels and campfires are single events. idle_town and idle_field count idle-watch +// strikes (a bot stood still too long), split by capital and elsewhere, which is how a frozen bot shows up in the log. +struct Stats +{ + std::atomic inn_ticks{0}, mailbox_ticks{0}, duels{0}, campfires{0}, lfg_calls{0}, idle_town{0}, idle_field{0}; +}; +inline Stats& Counters() +{ + static Stats stats; + return stats; +} + +// Does this bot take part in `show` during the window of `window_ms` that `now_ms` falls in? `pct` of the bots do, a different set +// each window. +inline bool TakesPart(std::uint32_t bot_id, std::uint32_t show, std::uint32_t now_ms, std::uint32_t pct, std::uint32_t window_ms) +{ + if (!pct || !window_ms) return false; + std::uint32_t const w = now_ms / window_ms; + std::uint32_t h = (bot_id + 1u) * 2654435761u; + h ^= (w + 1u) * 2246822519u; + h ^= (show + 1u) * 3266489917u; + h ^= h >> 15; + h *= 2246822519u; + h ^= h >> 13; + return (h % 100u) < pct; +} + +// Share of the bots resting at the inn for the local hour: most at night, some in the evening, few by day. +inline std::uint32_t InnPercent(int hour) +{ + if (hour < 0 || hour > 23) return 8; + if (hour < 6 || hour >= 23) return 35; + if (hour >= 18) return 20; + return 8; +} + +// Duel partners: close in level, both healthy. The lower id challenges so a pair does not challenge each other at once. +inline bool DuelPartners(std::uint32_t level_a, int hp_pct_a, std::uint32_t level_b, int hp_pct_b, std::uint64_t id_a, std::uint64_t id_b) +{ + int const d = int(level_a) - int(level_b); + return d >= -3 && d <= 3 && hp_pct_a >= 90 && hp_pct_b >= 90 && id_a < id_b; +} + +// Dungeons of the 1.12 game by the level of the party that runs them, for an LFG call. nullptr below the first. +struct LfgBand { std::uint32_t lo, hi; char const* name; }; +inline constexpr LfgBand kLfgBands[] = { + { 13, 17, "Ragefire Chasm" }, { 15, 20, "Wailing Caverns" }, { 18, 23, "the Deadmines" }, { 22, 27, "Shadowfang Keep" }, + { 24, 29, "Blackfathom Deeps" }, { 26, 31, "the Stockade" }, { 29, 34, "Gnomeregan" }, { 30, 36, "Razorfen Kraul" }, + { 34, 41, "the Scarlet Monastery" }, { 37, 45, "Razorfen Downs" }, { 40, 47, "Uldaman" }, { 44, 51, "Zul'Farrak" }, + { 46, 54, "Maraudon" }, { 50, 57, "the Sunken Temple" }, { 52, 60, "Blackrock Depths" }, { 58, 60, "Stratholme" }, +}; + +// The dungeon a bot of `level` calls for, one of the bands it fits, chosen by `pick`. nullptr when none fits. +inline char const* LfgDungeonFor(std::uint32_t level, std::uint32_t pick) +{ + std::uint32_t fit[16]; + std::size_t n = 0; + for (LfgBand const& b : kLfgBands) + if (level >= b.lo && level <= b.hi && n < 16) fit[n++] = std::uint32_t(&b - kLfgBands); + return n ? kLfgBands[fit[pick % n]].name : nullptr; +} + +// A duel one bot asked another for: the one asked accepts it. Entries expire; the table is tiny (a few pairs at a time). +inline std::mutex& PactMutex() { static std::mutex m; return m; } +inline std::unordered_map>& Pacts() +{ + static std::unordered_map> t; + return t; +} + +inline void PactSet(std::uint64_t target, std::uint64_t initiator, std::uint32_t now_ms) +{ + std::lock_guard g(PactMutex()); + auto& t = Pacts(); + if (t.size() > 256) + for (auto it = t.begin(); it != t.end();) + it = (now_ms - it->second.second > 60000u) ? t.erase(it) : std::next(it); + t[target] = { initiator, now_ms }; +} + +inline bool PactHolds(std::uint64_t target, std::uint64_t initiator, std::uint32_t now_ms) +{ + std::lock_guard g(PactMutex()); + auto const it = Pacts().find(target); + return it != Pacts().end() && it->second.first == initiator && now_ms - it->second.second <= 30000u; +} + +} // namespace Playerbot::V2::TownLife diff --git a/src/modules/PlayerbotV2/Bot/WalkOrder.h b/src/modules/PlayerbotV2/Bot/WalkOrder.h new file mode 100644 index 0000000000..ad1d000386 --- /dev/null +++ b/src/modules/PlayerbotV2/Bot/WalkOrder.h @@ -0,0 +1,27 @@ +// WalkOrder - the world spawner's request that a bot walk somewhere on its own legs: arrive from the edge of town to its spot, or leave +// toward an inn / out of sight before it logs out. Written by the spawner on the world thread, read by the bot's idle dispatch; plain +// atomics, no locks. The rule obeys while `active` and the spawner clears it (arrival clears itself). +#pragma once + +#include +#include + +namespace Playerbot::V2 +{ + +struct WalkOrder +{ + enum Kind : std::uint8_t { None = 0, Arrive = 1, Leave = 2 }; + std::atomic active{false}; + std::atomic kind{None}; + std::atomic x{0.0f}, y{0.0f}, z{0.0f}; + + void Set(Kind k, float tx, float ty, float tz) + { + x.store(tx); y.store(ty); z.store(tz); kind.store(k); + active.store(true, std::memory_order_release); + } + void Clear() { active.store(false, std::memory_order_release); kind.store(None); } +}; + +} // namespace Playerbot::V2 diff --git a/src/modules/PlayerbotV2/Bot/World/HunterPetsByRace.h b/src/modules/PlayerbotV2/Bot/World/HunterPetsByRace.h index 6684fad851..c1c1061b1d 100644 --- a/src/modules/PlayerbotV2/Bot/World/HunterPetsByRace.h +++ b/src/modules/PlayerbotV2/Bot/World/HunterPetsByRace.h @@ -32,6 +32,24 @@ uint32 HunterPetEntryForRace(uint32 race); constexpr uint32 GenericAllianceHunterPet = 299; // Stormpike Wolf (Dun Morogh wolf, lvl 1-2) constexpr uint32 GenericHordeHunterPet = 5826; // Mottled Boar (Valley of Trials, lvl 1-2) +// A world (ambient) hunter's own first pet, stable per bot: one of the faction's classic starter beasts picked by guid, so a street of +// hunters is not all one race's beast. Creature entries of HunterPetEntryForRace's classic races; the caller's tameable check still +// decides whether the pick exists as a beast in this data. `fallback` (the race's pet) is returned for an owned bot (guid 0). +inline uint32 VariedHunterPetEntry(bool alliance, uint64 guid, uint32 fallback) +{ + static constexpr uint32 kAlliance[] = { 299, 1132, 2031, 299, 1132 }; // wolf, boar, spider + static constexpr uint32 kHorde[] = { 5826, 1908, 2956, 2952, 5826, 1908 }; // boar, wolf, plainstrider, raptor + if (!guid) + return fallback; + uint64 h = guid * 0x9E3779B97F4A7C15ull; + h ^= h >> 29; + h *= 0xBF58476D1CE4E5B9ull; + h ^= h >> 32; + if (alliance) + return kAlliance[h % (sizeof(kAlliance) / sizeof(kAlliance[0]))]; + return kHorde[h % (sizeof(kHorde) / sizeof(kHorde[0]))]; +} + // The race's starter pet, else the faction-generic one. inline uint32 StarterHunterPetEntry(uint32 race, bool alliance) { diff --git a/src/modules/PlayerbotV2/Bot/World/ZonePicker.cpp b/src/modules/PlayerbotV2/Bot/World/ZonePicker.cpp index 9d47fd07cd..fea0b2e571 100644 --- a/src/modules/PlayerbotV2/Bot/World/ZonePicker.cpp +++ b/src/modules/PlayerbotV2/Bot/World/ZonePicker.cpp @@ -364,6 +364,8 @@ constexpr uint16 kVanillaCapitals[] = { 1519, 1537, 1657, 1637, 1638, 1497 }; bool VanillaZoneLevelRange(uint32 zone_id, uint8& lo, uint8& hi) { + // The ground outside Onyxia's Lair is an area of its own (2159): it is the Dustwallow Marsh entrance, not a town without levels. + if (zone_id == 2159) zone_id = 15; for (VanillaZone const& z : kVanillaZones) { if (z.zone != zone_id) continue; diff --git a/src/modules/PlayerbotV2/CMakeLists.txt b/src/modules/PlayerbotV2/CMakeLists.txt index 9d864dd5ae..6dae1ad5b5 100644 --- a/src/modules/PlayerbotV2/CMakeLists.txt +++ b/src/modules/PlayerbotV2/CMakeLists.txt @@ -64,10 +64,10 @@ function(playerbot_v2_configure_sublib target_name) endfunction() # --------------------------------------------------------------------------- -# Sub-library: Bot — top-level AI (state machine, snapshot/builder/view, +# Sub-library: Bot — top-level bot logic (state machine, snapshot/builder/view, # personality, RNG, command parser, intent emitter/executor, registries, # class tables, recipe difficulty), plus the State_* files under Bot/States/. -# This is the AI core; it's referenced by Combat / Group / Session. +# This is the bot logic core; it's referenced by Combat / Group / Session. # --------------------------------------------------------------------------- add_library(playerbot-v2-bot STATIC) CollectAndAddSourceFiles(playerbot-v2-bot ${CMAKE_CURRENT_SOURCE_DIR}/Bot) @@ -106,7 +106,7 @@ CollectAndAddSourceFiles(playerbot-v2-session ${CMAKE_CURRENT_SOURCE_DIR}/Sessio playerbot_v2_configure_sublib(playerbot-v2-session) # --------------------------------------------------------------------------- -# Sub-library: Threading — AI worker pool, snapshot publisher, tick scheduler, +# Sub-library: Threading — bot worker pool, snapshot publisher, tick scheduler, # lock hierarchy. The hot path; small but heavily used. # --------------------------------------------------------------------------- add_library(playerbot-v2-threading STATIC) diff --git a/src/modules/PlayerbotV2/Combat/ApRegistry.h b/src/modules/PlayerbotV2/Combat/ApRegistry.h index ffa74b26c2..9921e8d683 100644 --- a/src/modules/PlayerbotV2/Combat/ApRegistry.h +++ b/src/modules/PlayerbotV2/Combat/ApRegistry.h @@ -17,7 +17,7 @@ ApRotation const* GetRotation(uint8 cls, uint32 spec); void RegisterAllRotations(); // Called by individual Apl_*.cpp files at registration. Single-threaded; runs -// during init before AI workers start. +// during init before bot workers start. void RegisterRotation(uint8 cls, uint32 spec, ApRotation rotation); // Replaces any rotation already registered for (cls, spec). Used by the // Classic 1.60 vanilla rotations, which register after the retail ones. diff --git a/src/modules/PlayerbotV2/Combat/Apl/ApClassicHeal.h b/src/modules/PlayerbotV2/Combat/Apl/ApClassicHeal.h index 081e80fec0..3c5b0adb17 100644 --- a/src/modules/PlayerbotV2/Combat/Apl/ApClassicHeal.h +++ b/src/modules/PlayerbotV2/Combat/Apl/ApClassicHeal.h @@ -2,7 +2,7 @@ // rotations (Apl_Classic_Priest / Druid / Paladin / Shaman) and the // out-of-combat top-up (State_Idle MaintainOocHeal). // -// Port of Karrz's ike3 vanilla healer (ike3-based bots PlayerBots): +// Port of Karrz's ike3 vanilla healer (wow-1.12 PlayerBots): // - PickPatient: values/PartyMemberToHeal.cpp Calculate + MCRaidPolicy // HealScore. Candidates within heal range on the bot's map; members out // of line of sight are skipped unless they are a tank or below 35% (the @@ -29,7 +29,7 @@ // the debuffed members; the bot itself last. // Rank chains come from SpellMgr (vanilla rank 1 ids resolve through // BotSnapshotView::resolve_rank). Pure functions of the snapshots: safe on -// the AI worker threads. +// the bot worker threads. // // Mana efficiency (RaidHealing: vanilla realm, inside a raid or 5-man instance map, not a // battleground; open-world parties and solo play keep the rules above): @@ -63,7 +63,9 @@ #include "Bot/RezClaims.h" // IsRezSpell, rez cast refusals #include "Bot/RezRule.h" // RezRank, RezFightLive #include "Bot/ThreatDiscipline.h" +#include "Bot/Raid/RaidEncounters.h" // Raid::ThreatShareAfterDrop #include "Bot/Raid/RaidHealStats.h" +#include "Bot/Raid/RaidManaLedger.h" #include "Bot/ClassicHealScope.h" #include "Bot/ClassicHealCover.h" #include "HealClaimStore.h" @@ -86,7 +88,7 @@ namespace Playerbot::Combat { namespace ClassicHeal { -constexpr float kHealRange = 40.0f; // Karrz: HealDistance 38 + slack for the snapshot cadence +constexpr float kHealRange = 40.0f; // the owner: HealDistance 38 + slack for the snapshot cadence constexpr float kDispelRange = 30.0f; constexpr float kMeleeReach = 8.0f; // enemy-to-member distance that counts as "swinging at" constexpr int32 kEmergencyPct = 35; // HEAL_DOWNRANK_MIN_PCT / LOS exemption @@ -163,6 +165,8 @@ struct HealTiming uint32 need_ms = 0; // raid healer: last time its assignment needed healing (RaidHealerMayDamage) uint32 need_eval_ms = 0; // ... and the last time that was checked uint32 pick_logged_ms = 0; // last NoteRaidPick line + uint64 dispel_key = 0; // last assigned dispel cast (member + debuff type) ... + uint32 dispel_ms = 0; // ... and when (published_at_ms clock) }; template @@ -487,6 +491,84 @@ inline void NoteRaidPick(BotSnapshotView const& s, GroupSnapshotView const& g, P focus.IsEmpty() ? ", triage healer" : (focus == p.guid ? ", own tank" : ", tank healer on the raid"), tanks, raid_members); } +// A boss the tank is holding but has not out-threatened yet (the opening lead, as the damage dealers wait for it): a heal on a member +// puts threat on everything that member is fighting, so a raid healer leaves members above kHealOpeningHoldPct alone until the tank has +// its lead (Onyxia n6: Flash Heal on a raid member at tank_threat=0 took Onyxia off the tank). Bounded at 12 s of the healer's own +// combat: a tank that never builds the lead must not starve the raid. A tank is never held off. +constexpr int32 kHealOpeningHoldPct = 50; +constexpr int64 kHealOpeningHoldMs = 12000; +inline bool TankOpeningOnBoss(BotSnapshotView const& s) +{ + if (!ThreatDisciplineApplies(s) || s.combat_duration_ms() >= kHealOpeningHoldMs) + return false; + for (NearbyUnit const& u : s.raw().combat.nearby_enemies) + if ((u.is_dungeon_boss || u.is_boss_rank) && !u.is_player && u.hp > 0 && u.has_threat_list && u.unit_in_combat && + ThreatVictim(u.victim_kind) == ThreatVictim::Tank && u.tank_threat < ThreatOpeningLead(s, u)) + return true; + return false; +} + +// A healer whose heals have put it near the tank's threat on a boss the tank holds (n14 Onyxia at 180 s: a healer at 96 % of the tank, then a Knock +// Away cut the tank by a quarter and she turned on it). Healing threat is the effective health done, so the healer leaves members above +// kHealOpeningHoldPct alone until the tank is clear of it again. Emergencies are never held, and a tank is never held off. +constexpr float kHealerThreatHoldRatio = 0.85f; +inline bool HealerNearTankThreat(BotSnapshotView const& s) +{ + if (!ThreatDisciplineApplies(s)) + return false; + for (NearbyUnit const& u : s.raw().combat.nearby_enemies) + if ((u.is_dungeon_boss || u.is_boss_rank) && !u.is_player && u.hp > 0 && u.has_threat_list && u.unit_in_combat && + ThreatVictim(u.victim_kind) == ThreatVictim::Tank && u.tank_threat > 0.0f && + u.my_threat >= u.tank_threat * kHealerThreatHoldRatio * Raid::ThreatShareAfterDrop(s.map_id(), u.entry)) + return true; + return false; +} + +// Fair share of the raid's healing by mana. Whoever's rules run first claims a patient, so the fast, cheap-to-start heals (Flash of Light, +// Healing Touch) took nearly all of them and drained to 5-13 % mana while the priests, whose Greater Heal casts long, kept 92-100 % and +// cast a third as often (n24 mc_geddon, five priests 10-37 casts against 44-75 per paladin). A healer well under the other healers' mana +// leaves the patients who are not in trouble to them, which both lets it regenerate (the five second rule only runs while it is not +// casting) and gives the unspent mana something to do. Emergencies are never left. +constexpr int32 kHealerManaGapPct = 20; // under the other healers' average by this much +constexpr int32 kHealerManaStandDownPct = 65; // and under this much itself +constexpr int32 kHealerStandDownPatientPct = 60; // patients at or above this are left to the others +constexpr size_t kHealerManaPeersMin = 3; +// The further a healer is below the others, the more it leaves: a healer under kHealerManaLowPct while the others average kHealerPeersFullPct +// or more heals only emergencies, one under kHealerManaThinPct leaves everyone at kHealerThinPatientPct or more (n32 mc_ragnaros: the druids +// ended at 5 % mana and the paladins at 22-45 % with 80-105 heals each, the four priests at 100 % with 15-36). +constexpr int32 kHealerManaLowPct = 30; +constexpr int32 kHealerManaThinPct = 45; +constexpr int32 kHealerPeersFullPct = 60; +constexpr int32 kHealerThinPatientPct = 45; +constexpr int32 kHealerNoStandDown = 101; // PatientPct above any health: nothing is left +// The health at or above which this healer leaves a patient to the others (kHealerNoStandDown = it leaves none). +inline int32 HealerStandDownPatientPct(BotSnapshotView const& s, GroupSnapshotView const& g) +{ + if (s.max_power(0) <= 0 || ManaPct(s) >= kHealerManaStandDownPct) + return kHealerNoStandDown; + int64 sum = 0; + size_t peers = 0; + if (auto const* members = g.members()) + for (GroupMemberSummary const& m : *members) + { + if (m.guid == s.guid() || m.role != Role::Healer || !m.online || !m.is_alive || m.max_mana <= 0 || m.map_id != s.map_id()) + continue; + sum += int64(m.mana) * 100 / m.max_mana; + ++peers; + } + if (peers < kHealerManaPeersMin) + return kHealerNoStandDown; + int32 const avg = int32(sum / int64(peers)); + if (ManaPct(s) + kHealerManaGapPct >= avg) + return kHealerNoStandDown; + if (avg >= kHealerPeersFullPct) + { + if (ManaPct(s) < kHealerManaLowPct) return kEmergencyPct; + if (ManaPct(s) < kHealerManaThinPct) return kHealerThinPatientPct; + } + return kHealerStandDownPatientPct; +} + // Best heal target for this healer (PartyMemberToHeal::Calculate). Returns // the bot itself with valid == false and hp_pct 100 when nobody needs a heal. inline Patient PickPatient(BotSnapshotView const& s, GroupSnapshotView const& g, float range = kHealRange) @@ -503,10 +585,14 @@ inline Patient PickPatient(BotSnapshotView const& s, GroupSnapshotView const& g, // (`assigned`) is left as it was - the tank healer's duty. bool const raid = RaidHealing(s) && HealClaimsOn(); HealClaims const claims = raid ? CopyHealClaims(s.published_at_ms()) : HealClaims{}; + bool const opening_hold = raid && (TankOpeningOnBoss(s) || HealerNearTankThreat(s)); + int32 const stand_down_pct = raid ? HealerStandDownPatientPct(s, g) : kHealerNoStandDown; auto consider = [&](Patient const& raw, bool assigned, bool own = false) { if (!raw.valid || raw.max_hp <= 0) return; Patient p = raw; + if (opening_hold && !raw.tank && raw.actual_pct >= kHealOpeningHoldPct) return; + if (raw.actual_pct >= stand_down_pct) return; // A member at 95%+ is healed on projected damage only by the healers assigned to that tank (Garr 2026-10-08: 19 picks at // 100% "projected 65%", 185 cancels, ~39.8k mana wasted). if (raid && raw.actual_pct >= 95 && !(assigned && raw.tank)) return; @@ -570,7 +656,7 @@ inline Patient PickPatient(BotSnapshotView const& s, GroupSnapshotView const& g, int32 const pct = m.hp_pct(); if (!tank && pct >= kEmergencyPct && !InLos(s, m.guid)) continue; Patient const mp = MakePatient(s, m.guid, m.hp, m.max_hp, m.x, m.y, m.z, tank); - // A warlock's own Life Tap is intentional damage: not a reason for a heal until he is low (Karrz, live MC 2026-10-10). + // A warlock's own Life Tap is intentional damage: not a reason for a heal until he is low (playtest, live MC 2026-10-10). if (raid && LifeTapSkip(m.cls == CLASS_WARLOCK, tank, mp.actual_pct, mp.incoming)) continue; consider(mp, focus == m.guid, HealGroupHas(own_groups, m.subgroup)); @@ -765,7 +851,7 @@ inline uint64 HotAnyClaimKey(ObjectGuid target) } // Another healer's HoT of `spell`'s chain is already on (or on its way to) `target`; for a member that is not a tank, a HoT of any -// other kind counts too (Karrz, live MC 2026-10-10: a Life Tapping warlock carried a Renew, a Rejuvenation and a Regrowth at once, +// other kind counts too (playtest, live MC 2026-10-10: a Life Tapping warlock carried a Renew, a Rejuvenation and a Regrowth at once, // three healers' mana for one member). The tanks keep one HoT of each kind: their healers stack them on purpose. inline bool HotClaimedByOther(BotSnapshotView const& s, GroupSnapshotView const& g, ObjectGuid target, uint32 spell) { @@ -1065,7 +1151,7 @@ ObjectGuid RezTarget(BotSnapshotView const& s, GroupSnapshotView const& g, float auto const* members = g.members(); if (!members) return ObjectGuid::Empty; float bx, by, bz; s.position(bx, by, bz); - // The owner (a human member) is raised first (Karrz, MC Gehennas 2026-10-08: dead, nobody rezzed him), then healers, tanks, the rest. + // The owner (a human member) is raised first (playtest, MC Gehennas 2026-10-08: dead, nobody rezzed him), then healers, tanks, the rest. auto band = [](GroupMemberSummary const& m) { return !m.is_bot ? -1 : m.role == Role::Healer ? 0 : m.role == Role::Tank ? 1 : 2; }; GroupMemberSummary const* cand[40]; int n = 0, dead = 0, far_away = 0, no_los = 0, taken_n = 0; @@ -1099,7 +1185,7 @@ ObjectGuid RezTarget(BotSnapshotView const& s, GroupSnapshotView const& g, float } if (taken) ++taken_n; else cand[n++] = &m; } - // [raid_rez] (Karrz, MC Gehennas 2026-10-08: dead, nobody rezzed him; the log said nothing): why a dead member is, or is not, + // [raid_rez] (playtest, MC Gehennas 2026-10-08: dead, nobody rezzed him; the log said nothing): why a dead member is, or is not, // picked up by this bot, at most once per 5 s per bot and only in a raid. if (dead > 0 && s.is_in_raid()) { @@ -1122,7 +1208,7 @@ ObjectGuid RezTarget(BotSnapshotView const& s, GroupSnapshotView const& g, float int const ba = band(*a), bb = band(*b); return ba != bb ? ba < bb : a->guid < b->guid; }); - // One rezzer per corpse (Karrz, MC 2026-10-10: a dozen healers cast on him at once): every rezzer reads the same snapshot, so a "taken + // One rezzer per corpse (playtest, MC 2026-10-10: a dozen healers cast on him at once): every rezzer reads the same snapshot, so a "taken // by whoever is already casting" check alone lets all of them start in the same tick. The rezzers within 40 yd that can cast now // (alive, out of combat, not already on a rez) are ranked by guid; the first n of them take the n corpses, the rest wait. The // ranking turns every 3 s, so a front rezzer that cannot cast (no mana, on a cooldown, held by another order) does not stall the @@ -1178,9 +1264,16 @@ inline bool RaidFightLive(GroupSnapshotView const& g, uint32 map_id) return V2::RezFightLive(tanks, fighting); } +// The fight is on while a boss encounter is in progress too: a submerged Ragnaros leaves the raid with no tank and few members in combat, and the +// priests, paladins and shamans raised the dead in the middle of the encounter (playtest, MC Rag 2026-10-12). Only a druid raises in a live fight. +inline bool RezFightOn(BotSnapshotView const& s, GroupSnapshotView const& g) +{ + return s.is_encounter_in_progress() || RaidFightLive(g, s.map_id()); +} + inline ObjectGuid OocRezTarget(BotSnapshotView const& s, GroupSnapshotView const& g) { - if (!RezManaOk(s) || RaidFightLive(g, s.map_id())) + if (!RezManaOk(s) || RezFightOn(s, g)) return ObjectGuid::Empty; return RezTarget(s, g, 28.0f, [](GroupMemberSummary const& m) { @@ -1191,7 +1284,7 @@ inline ObjectGuid OocRezTarget(BotSnapshotView const& s, GroupSnapshotView const inline ObjectGuid RebirthTarget(BotSnapshotView const& s, GroupSnapshotView const& g) { // Rebirth is a combat rez: the druids in the fight are the rezzers it is ranked among. - return RezTarget(s, g, 28.0f, [](GroupMemberSummary const& m) { return m.cls == CLASS_DRUID && m.level >= 20; }, /*in_combat_ok*/ true); + return RezTarget(s, g, 28.0f, [](GroupMemberSummary const& m) { return m.cls == CLASS_DRUID && m.level >= 20 && m.role != Role::Tank; }, /*in_combat_ok*/ true); // a tank druid never rezzes in the fight } inline bool MemberHasDebuff(GroupSnapshotView const& g, ObjectGuid guid, uint32 spell) @@ -1259,17 +1352,30 @@ inline ObjectGuid DispelTarget(ApPredicateContext const& ctx, std::initializer_l // runs it; the target-picker above stays for callers outside the plan. The // mana floor (Classic::kDispelMinManaPct) is PickDispel's own, so the plan // never hands a job to a bot this gate would turn away. +// A dispel of the same debuff type on the same member is not repeated inside this window: a cure that worked takes the debuff off +// at once, so a second cast means it did not take (not dispellable, out of line of sight, or the debuff comes straight back). +// deadmines_full c82a7e21: a level 21 priest cast Dispel Magic ten times on one member, 830 of its 2345 mana. +constexpr uint32 kDispelRepeatMs = 8000; + +inline bool DispelRecently(void const* ctx, uint64 key) +{ + BotSnapshotView const& s = *static_cast(ctx); + uint32 const now = s.published_at_ms(); + return WithHealTiming(s, [&](HealTiming& t) { return t.dispel_key == key && t.dispel_ms && now - t.dispel_ms < kDispelRepeatMs; }); +} + inline bool ShouldAssignedDispel(ApPredicateContext const& ctx) { if (ctx.bot.is_casting()) return false; - return Classic::PickDispel(ctx.bot, ctx.group).spell != 0; + return Classic::PickDispel(ctx.bot, ctx.group, { &DispelRecently, &ctx.bot }).spell != 0; } inline void DoAssignedDispel(ApPredicateContext const& ctx, BotIntentEmitter& e) { - Classic::CastPick const d = Classic::PickDispel(ctx.bot, ctx.group); + Classic::CastPick const d = Classic::PickDispel(ctx.bot, ctx.group, { &DispelRecently, &ctx.bot }); if (d.spell && e.cast(d.spell, d.target)) { + WithHealTiming(ctx.bot, [&](HealTiming& t) { t.dispel_key = d.key; t.dispel_ms = ctx.bot.published_at_ms(); return 0; }); Classic::NoteRaidSupport(Classic::RaidSupportKind::Dispel, ctx.bot.map_id()); if (Classic::IsCurseDispelSpell(d.spell)) Classic::NoteRaidSupport(Classic::RaidSupportKind::Decurse, ctx.bot.map_id()); @@ -1361,6 +1467,7 @@ inline bool EmitHeal(BotSnapshotView const& s, GroupSnapshotView const& g, BotIn if (sent && RaidHealing(s)) { Playerbot::Raid::NoteHealCastSent(s.guid().GetCounter(), s.name(), s.published_at_ms()); + Playerbot::Raid::ManaLedgerHealSent(s.guid().GetCounter(), plan.est); // The same audit line as the claimed path below (deadmines_full: a 5-man priest wrote [raid_heal] choices but no [heal_cast]). TC_LOG_INFO("playerbot.v2", "[heal_cast] t={} {} spell {} -> {}{} at {}%: deficit {} (missing {} incoming {}) est {:.0f}, mana {}% (no heal claims)", s.published_at_ms(), s.name(), plan.rank ? plan.rank : spell, target.GetCounter(), p.tank ? " (tank)" : "", @@ -1401,6 +1508,7 @@ inline bool EmitHeal(BotSnapshotView const& s, GroupSnapshotView const& g, BotIn c.amount = plan.est > 0.0f ? plan.est : ExpectedHeal(si, s); c.start_ms = now; c.land_ms = now + uint32(cast_ms); + Playerbot::Raid::ManaLedgerHealSent(s.guid().GetCounter(), c.amount); // One line per raid heal sent, for the mana audit (MC Garr 2026-10-10: the choice lines log only a change, so same-second // stacking and the size of each cast could not be counted). est / deficit above 1 is an overheal risk. // The spell data chains few Classic ranks (GetSpellRank reads 0 for them), so the rank shows as the spell's base level. The diff --git a/src/modules/PlayerbotV2/Combat/Apl/ApCrowdControl.h b/src/modules/PlayerbotV2/Combat/Apl/ApCrowdControl.h index fe42fee06d..8fb6575230 100644 --- a/src/modules/PlayerbotV2/Combat/Apl/ApCrowdControl.h +++ b/src/modules/PlayerbotV2/Combat/Apl/ApCrowdControl.h @@ -6,7 +6,7 @@ // spell's TargetCreatureType mask with SPELL_FAILED_BAD_TARGETS — Polymorph // (118) alone burned 495,677 BAD_TARGETS in the 4-day run (~95% of all cast // rejections), the same creature re-attempted ~181x because the reject happens -// before the cooldown is consumed. We can't read SpellInfo on the AI worker, so +// before the cooldown is consumed. We can't read SpellInfo on the bot worker, so // this encodes the canonical creature-type masks for the CC spells the rotations // actually use. Header-only so the per-spec TUs pay no link cost. @@ -19,6 +19,7 @@ #include "Bot/BotSnapshotView.h" // BotSnapshotView, NearbyUnit, Role #include "Group/GroupSnapshot.h" // GroupSnapshotView (group CC) #include "SpellMgr.h" +#include "Bot/Dungeon/MarkCc.h" // MarkCc::CasterHoldsAnother namespace Playerbot::Combat { @@ -154,6 +155,10 @@ namespace Playerbot::Combat { auto const* members = ctx.group.members(); if (!members || members->size() < 2 || ApInPvp(ctx)) return PickOffTargetCC(ctx, spellId, ApInPvp(ctx)); + // In an instance the group plan (PveGroupCoordinator::PlanMarkOrders: the owner's icons, then auto crowd control) is the one CC + // decider; a second pick here sheeped the owner's cross and left the planned mob unheld. + if (bot.raw().pve_order.active) + return ObjectGuid::Empty; ObjectGuid const v = bot.victim(); if (v.IsEmpty()) return ObjectGuid::Empty; @@ -166,12 +171,10 @@ namespace Playerbot::Combat { }; auto const& enemies = bot.raw().combat.nearby_enemies; size_t engaged = 0; + if (MarkCc::CasterHoldsAnother(bot, ObjectGuid::Empty)) + return ObjectGuid::Empty; // our CC is still holding one (the same check the marked CC makes) for (auto const& u : enemies) - { - if (u.is_cc_locked && u.cc_caster == bot.guid()) - return ObjectGuid::Empty; // our CC is still holding one if (engaged_with_group(u)) ++engaged; - } if (engaged < 3) return ObjectGuid::Empty; @@ -195,6 +198,10 @@ namespace Playerbot::Combat { { if (!engaged_with_group(u) || u.is_cc_locked || (u.is_dungeon_boss || u.is_boss_rank) || !u.in_los) continue; if (u.guid == v || u.guid == skull || u.guid == tank_target) continue; + bool marked = false; // any raid icon is the owner's call (cross = kill next, moon = his CC) + for (uint8 i = 0; i < 8 && !marked; ++i) + marked = ctx.group.raid_mark(i) == u.guid; + if (marked) continue; if (!CanBeCCd(spellId, u.creature_type)) continue; // A mob under 40% health dies faster than the CC is worth (VMaNGOS CcTargetValue: skip below medium health). if (u.max_hp > 0 && u.hp * 100 < int64_t(u.max_hp) * 40) continue; diff --git a/src/modules/PlayerbotV2/Combat/Apl/ApInterrupt.h b/src/modules/PlayerbotV2/Combat/Apl/ApInterrupt.h index 95dbd7f625..03f1f547da 100644 --- a/src/modules/PlayerbotV2/Combat/Apl/ApInterrupt.h +++ b/src/modules/PlayerbotV2/Combat/Apl/ApInterrupt.h @@ -258,7 +258,7 @@ inline void Cast(ApPredicateContext const& ctx, BotIntentEmitter& e, uint32 spel a.spell, a.pet ? " (pet)" : "", uint32(c.rank), int64(c.unit->cast_remaining.count())); } -// ---- Purge duty (Karrz: ike3 DecideRaidCast purge election) ---- +// ---- Purge duty (the owner: ike3 DecideRaidCast purge election) ---- // Strips Magic buffs from an elite / boss engaged with a dungeon / raid // group. One bot at a time: every bot computes the same election from the // group snapshot - bot shamans with Purge first, then bot priests with @@ -399,6 +399,7 @@ inline void Cast(ApPredicateContext const& ctx, BotIntentEmitter& e) constexpr uint32 SUMMON_IMP = 688; constexpr uint32 SUMMON_VOIDWALKER = 697; constexpr uint32 SUMMON_FELHUNTER = 691; +constexpr uint32 SUMMON_SUCCUBUS = 712; constexpr uint8 kMaxRaidFelhunters = 2; // What this warlock's snapshot says about fielding a Spell Lock Felhunter @@ -454,6 +455,28 @@ inline uint32 ClassicWarlockPet(BotSnapshotView const& s, GroupSnapshotView cons if (!s.is_in_raid() && s.knows_spell(SUMMON_FELHUNTER) && FelhunterDuty(s, *g)) return SUMMON_FELHUNTER; if (s.knows_spell(SUMMON_IMP)) return SUMMON_IMP; } + // An ambient (world / pool) warlock has its own demon out, stable per bot: a street full of voidwalkers looked uniform (the owner, + // Ironforge 2026-10-12). One of the demons it has learned, picked by its guid (Imp L1, Voidwalker L10, Succubus L20, Felhunter L30). + // Without the soul shard the Succubus / Felhunter / Voidwalker cost, and with no demon out, the Imp comes out instead; a demon already + // out is kept. Owned companions keep the rule above and below. + if (!s.has_owner_character()) + { + uint32 known[4]; + uint32 n = 0; + for (uint32 sp : { SUMMON_IMP, SUMMON_VOIDWALKER, SUMMON_SUCCUBUS, SUMMON_FELHUNTER }) + if (s.knows_spell(sp)) + known[n++] = sp; + if (n) + { + uint64 const guid = s.guid().GetCounter(); + uint32 const h = uint32((guid * 0x9E3779B97F4A7C15ull) >> 40); + uint32 const pick = known[h % n]; + if (pick == SUMMON_IMP || s.has_pet() || s.has_reagents(pick)) + return pick; + return SUMMON_IMP; + } + return 0; + } if (s.knows_spell(SUMMON_VOIDWALKER)) return SUMMON_VOIDWALKER; if (s.knows_spell(SUMMON_IMP)) return SUMMON_IMP; return 0; @@ -467,6 +490,7 @@ inline uint32 SummonPetFamily(uint32 summon) case SUMMON_IMP: return CREATURE_FAMILY_IMP; case SUMMON_VOIDWALKER: return CREATURE_FAMILY_VOIDWALKER; case SUMMON_FELHUNTER: return CREATURE_FAMILY_FELHUNTER; + case SUMMON_SUCCUBUS: return CREATURE_FAMILY_SUCCUBUS; default: return 0; } } diff --git a/src/modules/PlayerbotV2/Combat/Apl/ApTankThreat.h b/src/modules/PlayerbotV2/Combat/Apl/ApTankThreat.h index 210406961d..1f6d9e99cb 100644 --- a/src/modules/PlayerbotV2/Combat/Apl/ApTankThreat.h +++ b/src/modules/PlayerbotV2/Combat/Apl/ApTankThreat.h @@ -71,8 +71,7 @@ inline bool InFront(BotSnapshotView const& s, NearbyUnit const& u) inline bool OtherTanksMob(BotSnapshotView const& s, NearbyUnit const& u) { if (ThreatVictim(u.victim_kind) == ThreatVictim::Tank) return true; - PveOrder const& po = s.raw().pve_order; - return po.active && po.claimed_by_other_tank(u.guid); + return s.claim_blocks(u); } // The tank's own victim is safe to leave for a GCD: dead / none, held by @@ -167,13 +166,12 @@ inline bool AoeRipsOtherTank(BotSnapshotView const& s, float radius, char const* inline size_t UnclaimedLooseWithin(BotSnapshotView const& s, float range) { const float r2 = range * range; - PveOrder const& po = s.raw().pve_order; size_t n = 0; for (NearbyUnit const& u : s.nearby_enemies()) { if (u.hp <= 0 || u.is_player || u.untargetable || u.is_pacified) continue; if (ThreatVictim(u.victim_kind) != ThreatVictim::Member) continue; - if (po.active && po.claimed_by_other_tank(u.guid)) continue; + if (s.claim_blocks(u)) continue; if (Dist2(s, u) <= r2) ++n; } return n; @@ -190,7 +188,7 @@ inline NearbyUnit const* CcLockedWithin(BotSnapshotView const& s, float range) return nullptr; } -// Area taunt gate (Challenging Shout / Roar, Karrz: 3+ loose within 10 yd): +// Area taunt gate (Challenging Shout / Roar, the owner: 3+ loose within 10 yd): // the loose mobs nobody else was given, and no crowd-controlled mob in reach. inline bool AreaTauntWorth(BotSnapshotView const& s, float range, char const* what) { diff --git a/src/modules/PlayerbotV2/Combat/Apl/ApThreatDump.h b/src/modules/PlayerbotV2/Combat/Apl/ApThreatDump.h index 7d3765920d..5f22a2150c 100644 --- a/src/modules/PlayerbotV2/Combat/Apl/ApThreatDump.h +++ b/src/modules/PlayerbotV2/Combat/Apl/ApThreatDump.h @@ -1,7 +1,7 @@ #pragma once // Threat-dump trigger for DPS and healers: how close the bot is to pulling aggro off the tank. // -// Idea from Karrz's VMaNGOS raid layer (the ike3-based playerbot code, playerbot/strategy/values/ThreatValues.cpp relative threat %, +// Idea from Karrz's VMaNGOS raid layer (Karrz1/wow-1.12, playerbot/strategy/values/ThreatValues.cpp relative threat %, // GenericTriggers.cpp HighThreat / MediumThreat at 80% / 60%); rewritten against our snapshot (NearbyUnit::my_threat and // tank_threat, filled by the snapshot builder). Used to time Fade and Feint. diff --git a/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Druid.cpp b/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Druid.cpp index 333079acf4..5c6328b37b 100644 --- a/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Druid.cpp +++ b/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Druid.cpp @@ -21,7 +21,7 @@ // are handled by the idle-state buff maintenance), Omen of Clarity, Cat // bail-out to heal. // -// Priorities follow Karrz's ike3 vanilla strategies (the ike3-based playerbot code +// Priorities follow Karrz's ike3 vanilla strategies (Karrz1/wow-1.12 // raid10-revamp, playerbot/strategy/druid/*Strategy.cpp, MANGOSBOT_ZERO). #include "../ApRegistry.h" @@ -87,7 +87,6 @@ constexpr uint32 SWIFTMEND = 18562; // Restoration talent constexpr uint32 NATURES_SWIFTNESS = 17116; // Restoration talent constexpr uint32 REBIRTH = 20484; constexpr uint32 TRANQUILITY = 740; -constexpr uint32 REVIVE = 50769; constexpr uint8 POWER_MANA = 0; constexpr uint8 POWER_RAGE = 1; @@ -181,7 +180,7 @@ struct HealTarget int32 hp_pct = 100; }; -// Heal target picked by Karrz's scoring (ClassicHeal::PickPatient: tank +// Heal target picked by the owner's scoring (ClassicHeal::PickPatient: tank // first, LOS, incoming-damage projection, healers spread); hp_pct is the // projected health. The bot itself at 100% when nobody needs a heal. HealTarget LowestFriendOrSelf(ApPredicateContext const& ctx) @@ -452,7 +451,7 @@ bool ShouldFrenziedRegen(ApPredicateContext const& ctx) } void DoFrenziedRegen(ApPredicateContext const&, BotIntentEmitter& e) { e.cast(FRENZIED_REGEN); } -// ---- Threat: loose attackers (Karrz's LooseAttackersTrigger) ---- +// ---- Threat: loose attackers (the owner's LooseAttackersTrigger) ---- // A "loose attacker" is a mob hitting a NON-TANK group member (snapshot // victim_kind == Member). Growl's reach is read from the spell data // (TankThreat::TauntReach, 10 yd when the data has none); the pick-up rule @@ -473,7 +472,7 @@ bool BearVictimSecured(ApPredicateContext const& ctx) return v->hp <= 0 || k == ThreatVictim::Me || k == ThreatVictim::Tank; } -// Challenging Roar when 3+ loose attackers are within 10 yd (Karrz) - only +// Challenging Roar when 3+ loose attackers are within 10 yd (the owner) - only // those no other tank was given, and never with a crowd-controlled mob in // reach (TankThreat::AreaTauntWorth). bool ShouldChallengingRoar(ApPredicateContext const& ctx) @@ -662,7 +661,11 @@ void DoSwiftmend(ApPredicateContext const& ctx, BotIntentEmitter& e) bool ShouldRebirth(ApPredicateContext const& ctx) { - return ctx.bot.in_combat() && CasterReady(ctx, REBIRTH) && !ClassicHeal::RebirthTarget(ctx.bot, ctx.group).IsEmpty(); + // The core refuses a cast the bar cannot pay with NO_POWER (MC Rag 2026-10-12: Rebirth refused NO_POWER on every attempt, the druid + // at 1.4-1.8k of 8.6k mana against a 1057 rank-2 cost): wait for the mana instead of burning the claim and the cooldown tick. + uint32 const known = ctx.bot.resolve_rank(REBIRTH); + return ctx.bot.in_combat() && CasterReady(ctx, REBIRTH) && ctx.bot.power(0) >= ctx.bot.mana_cost(known ? known : REBIRTH) + && !ClassicHeal::RebirthTarget(ctx.bot, ctx.group).IsEmpty(); } void DoRebirth(ApPredicateContext const& ctx, BotIntentEmitter& e) { @@ -673,16 +676,6 @@ void DoRebirth(ApPredicateContext const& ctx, BotIntentEmitter& e) e.cast(REBIRTH, t); } -bool ShouldRevive(ApPredicateContext const& ctx) -{ - return !ctx.bot.in_combat() && CasterReady(ctx, REVIVE) && ctx.group.dead_member(ctx.bot.map_id()) != nullptr; -} -void DoRevive(ApPredicateContext const& ctx, BotIntentEmitter& e) -{ - if (auto const* m = ctx.group.dead_member(ctx.bot.map_id())) - e.cast(REVIVE, m->guid); -} - bool ShouldFastHeal(ApPredicateContext const& ctx) { return CasterReady(ctx, FastHeal(ctx)) && LowestFriendOrSelf(ctx).hp_pct <= 45; @@ -693,7 +686,12 @@ bool ShouldFastHeal(ApPredicateContext const& ctx) void DoFastHeal(ApPredicateContext const& ctx, BotIntentEmitter& e) { ClassicHeal::Patient const p = ClassicHeal::PickPatient(ctx); - ClassicHeal::EmitHeal(ctx.bot, ctx.group, e, ClassicHeal::RaidChoose(ctx.bot, p, FastHeal(ctx), HEALING_TOUCH), p); + // Raid: Regrowth (880 mana for ~1.2k and a HoT, 31 % of a druid's mana in n31 mc_geddon) only for someone about to die; a tank under + // half health gets Healing Touch, which is twice as efficient per mana and lands within the same window with a downranked cast. + uint32 fast = FastHeal(ctx); + if (ClassicHeal::RaidHealing(ctx.bot) && p.actual_pct >= ClassicHeal::kEmergencyPct && p.hp_pct >= ClassicHeal::kEmergencyPct) + fast = HEALING_TOUCH; + ClassicHeal::EmitHeal(ctx.bot, ctx.group, e, ClassicHeal::RaidChoose(ctx.bot, p, fast, HEALING_TOUCH), p); } bool ShouldHealingTouch(ApPredicateContext const& ctx) @@ -716,7 +714,7 @@ void DoRejuvenation(ApPredicateContext const& ctx, BotIntentEmitter& e) ClassicHeal::NoteHotCast(ctx.bot, t, REJUVENATION); } -// Innervate (Karrz's fixed trigger: mana below AiPlayerbot.LowMana): the +// Innervate (the owner's fixed trigger: mana below AiPlayerbot.LowMana): the // druid itself first, otherwise another healer within 30 yd who is // running dry and isn't under any druid's Innervate yet (tracked buff), so // the raid's druids don't spend two Innervates on one priest. @@ -758,7 +756,7 @@ void DoHealerInnervate(ApPredicateContext const& ctx, BotIntentEmitter& e) Classic::NoteCooldownUse(ctx.bot, INNERVATE, "Innervate"); } -// Tranquility: 3 injured party members around the druid (Karrz's "medium +// Tranquility: 3 injured party members around the druid (the owner's "medium // aoe heal"); a 10 s channel on a 5 min cooldown, so only with the mana for it. bool ShouldTranquility(ApPredicateContext const& ctx) { @@ -820,7 +818,6 @@ ApRule const kHealerRules[] = { { ShouldHealingTouch, DoHealingTouch, "classic_resto:healing_touch" }, { ShouldDispel, DoDispel, "classic_resto:dispel" }, { ShouldRejuvenation, DoRejuvenation, "classic_resto:rejuvenation" }, - { ShouldRevive, DoRevive, "classic_resto:revive" }, { ShouldHealerSchoolNuke, DoHealerSchoolNuke, "classic_resto:school_nuke" }, { ShouldHealerMoonfire, DoMoonfire, "classic_resto:moonfire" }, { ShouldHealerWrath, DoWrath, "classic_resto:wrath" }, diff --git a/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Hunter.cpp b/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Hunter.cpp index 39e7d4e7ce..94107345af 100644 --- a/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Hunter.cpp +++ b/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Hunter.cpp @@ -15,7 +15,7 @@ // Skipped: Feign Death, Scatter Shot, Viper Sting, aspect swapping // (Monkey / Cheetah / Viper) - Hawk is the only aspect maintained. // -// Priorities follow Karrz's ike3 vanilla strategies (the ike3-based playerbot code +// Priorities follow Karrz's ike3 vanilla strategies (Karrz1/wow-1.12 // raid10-revamp, playerbot/strategy/hunter/*Strategy.cpp, MANGOSBOT_ZERO). #include "Bot/SpellFamily.h" @@ -79,8 +79,11 @@ int32 Mana(ApPredicateContext const& ctx) { return ctx.bot.power(POWER_MANA); } bool VictimInMelee(ApPredicateContext const& ctx) { return DistToVictim(ctx) <= 5.5f; } // Vanilla shots have an 8 yard minimum range. +// A shot needs a ranged weapon with ammo in the bags: without it the core refuses every one with NO_AMMO (Deadmines 2026-10-14). bool VictimInShotRange(ApPredicateContext const& ctx) { + if (ctx.bot.ammo_kind() == 0 || ctx.bot.ammo_count() == 0) + return false; float const d = DistToVictim(ctx); return d >= 8.f && d <= 35.f; } diff --git a/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Mage.cpp b/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Mage.cpp index 2072aac723..6c92e9f986 100644 --- a/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Mage.cpp +++ b/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Mage.cpp @@ -7,7 +7,7 @@ // as the last resort). Spell ids are vanilla rank 1 and resolve to the // highest known rank. // -// Priorities follow Karrz's ike3 vanilla strategies (the ike3-based playerbot code +// Priorities follow Karrz's ike3 vanilla strategies (Karrz1/wow-1.12 // raid10-revamp, playerbot/strategy/mage/*Strategy.cpp, MANGOSBOT_ZERO): // armor + Arcane Intellect upkeep, Counterspell on casters, Ice Block / // Frost Nova to survive, Evocation at low mana, boss cooldowns, Arcane @@ -80,6 +80,13 @@ bool VictimIsBossLike(ApPredicateContext const& ctx) return v && (Classic::IsBossUnit(*v) || v->max_hp >= 100'000); } +// The mana the nukes stop at: a mage with a wand shoots below 35% on ordinary fights (a short rest before the next pull instead of a +// drink to 60%), and casts down to 8% against a boss or when it holds no wand. +int32 NukeManaFloor(ApPredicateContext const& ctx) +{ + return ctx.bot.raw().consumables.wand_school_mask != 0 && !VictimIsBossLike(ctx) ? 35 : 8; +} + uint32 IceBlockSpell(ApPredicateContext const&) { return ICE_BLOCK; @@ -243,7 +250,7 @@ void DoFireBlast(ApPredicateContext const& ctx, BotIntentEmitter& e) { e.cast(FI bool ShouldNuke(ApPredicateContext const& ctx) { - return HasLiveTarget(ctx) && ManaPct(ctx) >= 8 && Ready(ctx, NukeSpell(ctx)); + return HasLiveTarget(ctx) && ManaPct(ctx) >= NukeManaFloor(ctx) && Ready(ctx, NukeSpell(ctx)); } void DoNuke(ApPredicateContext const& ctx, BotIntentEmitter& e) { e.cast(NukeSpell(ctx), ctx.bot.victim()); } @@ -252,7 +259,7 @@ void DoNuke(ApPredicateContext const& ctx, BotIntentEmitter& e) { e.cast(NukeSpe // Fireball on fire, Arcane Missiles on arcane), same mana gates as the nuke. bool NukeUsable(ApPredicateContext const& ctx, uint32 spell) { - return HasLiveTarget(ctx) && ManaPct(ctx) >= 8 && Ready(ctx, spell); + return HasLiveTarget(ctx) && ManaPct(ctx) >= NukeManaFloor(ctx) && Ready(ctx, spell); } bool ShouldFrostboltNuke(ApPredicateContext const& ctx) { return NukeUsable(ctx, FROSTBOLT); } bool ShouldFireballNuke(ApPredicateContext const& ctx) { return NukeUsable(ctx, FIREBALL); } @@ -282,7 +289,7 @@ void DoSchoolNuke(ApPredicateContext const& ctx, BotIntentEmitter& e) { SchoolHi bool ShouldWand(ApPredicateContext const& ctx) { return HasLiveTarget(ctx) && (Ready(ctx, SHOOT_WAND) && ctx.bot.victim_in_spell_range(SHOOT_WAND)) && ctx.bot.current_cast_spell_id() == 0 - && ManaPct(ctx) < 8; + && ManaPct(ctx) < NukeManaFloor(ctx); } void DoWand(ApPredicateContext const& ctx, BotIntentEmitter& e) { e.cast(SHOOT_WAND, ctx.bot.victim()); } diff --git a/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Paladin.cpp b/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Paladin.cpp index eca799bfe4..ebd3c7b686 100644 --- a/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Paladin.cpp +++ b/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Paladin.cpp @@ -5,7 +5,7 @@ // 70 and 0 = Retribution melee DPS. Spell ids are vanilla rank 1 and resolve // to the highest known rank in the snapshot view and API::cast_spell. // -// Priorities follow Karrz's ike3 vanilla strategies (the ike3-based playerbot code +// Priorities follow Karrz's ike3 vanilla strategies (Karrz1/wow-1.12 // raid10-revamp, playerbot/strategy/paladin/*Strategy.cpp, MANGOSBOT_ZERO). // Blessings follow the group assignment in Bot/ClassicUpkeep.cpp (each // paladin covers one blessing per class, Greater Blessings with Symbol of @@ -97,7 +97,7 @@ struct HealTarget int32 hp_pct = 100; }; -// Heal target picked by Karrz's scoring (ClassicHeal::PickPatient: tank +// Heal target picked by the owner's scoring (ClassicHeal::PickPatient: tank // first, LOS, incoming-damage projection, healers spread); hp_pct is the // projected health. The bot itself at 100% when nobody needs a heal. HealTarget LowestFriendOrSelf(ApPredicateContext const& ctx) @@ -258,7 +258,7 @@ void DoHammerOfJustice(ApPredicateContext const& ctx, BotIntentEmitter& e) { e.c // ======================= Healer ======================= // Lay on Hands (1 h cooldown, drains all mana) is reserved for a tank at -// critical health (Karrz's "party member critical tank health", 20%) and +// critical health (the owner's "party member critical tank health", 20%) and // for the paladin itself; anyone else gets Flash of Light. Forbearance from // any paladin (member debuff list) blocks it. ObjectGuid LayOnHandsTarget(ApPredicateContext const& ctx) diff --git a/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Priest.cpp b/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Priest.cpp index e723374ff0..243f623f71 100644 --- a/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Priest.cpp +++ b/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Priest.cpp @@ -6,7 +6,7 @@ // DPS list. Spell ids are vanilla rank 1 and resolve to the highest known // rank in the snapshot view and API::cast_spell. // -// Priorities follow Karrz's ike3 vanilla strategies (the ike3-based playerbot code +// Priorities follow Karrz's ike3 vanilla strategies (Karrz1/wow-1.12 // raid10-revamp, playerbot/strategy/priest/*Strategy.cpp, MANGOSBOT_ZERO): // shield + Flash Heal on critical, Greater Heal on low, Renew on topping, // Prayer of Healing on group damage, dispels (the raid dispel plan), Power @@ -79,7 +79,7 @@ struct HealTarget int32 hp_pct = 100; }; -// Heal target picked by Karrz's scoring (ClassicHeal::PickPatient: tank +// Heal target picked by the owner's scoring (ClassicHeal::PickPatient: tank // first, LOS, incoming-damage projection, healers spread); hp_pct is the // projected health. The bot itself at 100% when nobody needs a heal. HealTarget LowestFriendOrSelf(ApPredicateContext const& ctx) @@ -132,6 +132,9 @@ bool ShouldFade(ApPredicateContext const& ctx) || ThreatDump::ThreatPct(ctx.bot) >= ThreatDump::kMediumThreatPct); } void DoFade(ApPredicateContext const&, BotIntentEmitter& e) { e.cast(FADE); } +// A healer does not spend the GCD on Fade while someone is in the emergency band (the critical heals come first in the table, this keeps the +// threat triggers from stealing the tick when the heal is not castable yet). +bool ShouldFadeHealer(ApPredicateContext const& ctx) { return LowestFriendOrSelf(ctx).hp_pct > 40 && ShouldFade(ctx); } bool ShouldPsychicScream(ApPredicateContext const& ctx) { @@ -141,11 +144,12 @@ bool ShouldPsychicScream(ApPredicateContext const& ctx) // Raid school rule: not into a mob that avoids shadow (only that veto - // this is the emergency fear, the threat-discipline gates do not apply). float x, y, z; ctx.bot.position(x, y, z); - if (FindAoeHazard(ctx.bot, x, y, z, 8.0f, /*damaging*/ false, /*tank*/ false, PSYCHIC_SCREAM).kind - == AoeHazardKind::SchoolAvoided) + // A crowd-controlled mob in the ring vetoes it too (as Frost Nova's does). + AoeHazardKind const k = FindAoeHazard(ctx.bot, x, y, z, 8.0f, /*damaging*/ true, /*tank*/ false, PSYCHIC_SCREAM).kind; + if (k == AoeHazardKind::SchoolAvoided || k == AoeHazardKind::CrowdControlled) return false; - // Raid groups: no fear with an unpulled pack within 40y, and only for a - // priest an elite is hitting (ThreatDiscipline.h RaidFearAllowed). + // Raid groups and instances: no fear with an unpulled pack within 40y; raids + // also only for a priest an elite is hitting (ThreatDiscipline.h RaidFearAllowed). return RaidFearAllowed(ctx.bot, ctx.group.is_raid() || ctx.bot.is_in_raid(), "Psychic Scream"); } void DoPsychicScream(ApPredicateContext const&, BotIntentEmitter& e) { e.cast(PSYCHIC_SCREAM); } @@ -337,7 +341,7 @@ bool ShouldEmergencyBigHeal(ApPredicateContext const& ctx) } // Prayer of Healing heals the party within 30 yd of the priest: 3 injured -// members there (Karrz's "medium aoe heal"). +// members there (the owner's "medium aoe heal"). bool ShouldPrayerOfHealing(ApPredicateContext const& ctx) { return ManaPct(ctx) >= 20 && Ready(ctx, PRAYER_OF_HEALING) @@ -461,7 +465,7 @@ ApRule const kHealerRules[] = { { ShouldInnerFocus, DoInnerFocus, "classic_heal:inner_focus" }, { ShouldFlashHealCritical, DoFlashHeal, "classic_heal:flash_heal" }, { ShouldEmergencyBigHeal, DoBigHeal, "classic_heal:emergency_heal" }, - { ShouldFade, DoFade, "classic_heal:fade" }, + { ShouldFadeHealer, DoFade, "classic_heal:fade" }, { ShouldPsychicScream, DoPsychicScream, "classic_heal:psychic_scream" }, { ShouldPrayerOfHealing, DoPrayerOfHealing, "classic_heal:prayer_of_healing" }, { ShouldBigHeal, DoBigHeal, "classic_heal:big_heal" }, diff --git a/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Rogue.cpp b/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Rogue.cpp index 4c36323c92..eaffaf9eb9 100644 --- a/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Rogue.cpp +++ b/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Rogue.cpp @@ -15,7 +15,7 @@ // of combat by idle:classic_weapon (Bot/ClassicUpkeep.cpp). // Skipped: Kidney Shot, Vanish, Gouge. Feint: threat dump at 60% of the tank's threat (idea from Karrz's VMaNGOS bots). // -// Priorities follow Karrz's ike3 vanilla strategies (the ike3-based playerbot code +// Priorities follow Karrz's ike3 vanilla strategies (Karrz1/wow-1.12 // raid10-revamp, playerbot/strategy/rogue/*Strategy.cpp, MANGOSBOT_ZERO). #include "../ApRegistry.h" @@ -252,7 +252,7 @@ bool ShouldSliceAndDice(ApPredicateContext const& ctx) if (VictimHpPct(ctx) < 25 && !VictimIsBossLike(ctx)) return false; return (Ready(ctx, SLICE_AND_DICE) && ctx.bot.victim_in_spell_range(SLICE_AND_DICE)) && !SliceAndDiceUp(ctx); } -// Cast at the victim like a finishing move (Karrz's PartyBotAI does the same): in the +// Cast at the victim like a finishing move (the owner's PartyBotAI does the same): in the // Classic data a finishing move is bound to the combo target, and the self cast // (empty target) failed SPELL_FAILED_BAD_TARGETS on every attempt (MC wipe 2026-10-06). void DoSliceAndDice(ApPredicateContext const& ctx, BotIntentEmitter& e) { e.cast(SLICE_AND_DICE, ctx.bot.victim()); } diff --git a/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Shaman.cpp b/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Shaman.cpp index 4a281ad9a5..a2fa60b77e 100644 --- a/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Shaman.cpp +++ b/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Shaman.cpp @@ -6,7 +6,7 @@ // 1 and resolve to the highest known rank in the snapshot view and // API::cast_spell. // -// Priorities follow Karrz's ike3 vanilla strategies (the ike3-based playerbot code +// Priorities follow Karrz's ike3 vanilla strategies (Karrz1/wow-1.12 // raid10-revamp, playerbot/strategy/shaman/*Strategy.cpp, MANGOSBOT_ZERO). // Totems and weapon imbues come from Bot/ClassicUpkeep.cpp (one totem per // element by spec and party, Tremor / cleansing totems when the party needs @@ -80,7 +80,7 @@ struct HealTarget int32 hp_pct = 100; }; -// Heal target picked by Karrz's scoring (ClassicHeal::PickPatient: tank +// Heal target picked by the owner's scoring (ClassicHeal::PickPatient: tank // first, LOS, incoming-damage projection, healers spread); hp_pct is the // projected health. The bot itself at 100% when nobody needs a heal. HealTarget LowestFriendOrSelf(ApPredicateContext const& ctx) @@ -207,7 +207,7 @@ bool ShouldEmergencyHealingWave(ApPredicateContext const& ctx) return !ctx.bot.knows_spell(LESSER_HEALING_WAVE) && Ready(ctx, HEALING_WAVE) && LowestFriendOrSelf(ctx).hp_pct <= 40; } -// Chain Heal: 3 injured members (Karrz's "medium aoe heal"), cast on the +// Chain Heal: 3 injured members (the owner's "medium aoe heal"), cast on the // injured member with the most injured within a 12.5 yd jump of it. ObjectGuid ChainHealTarget(ApPredicateContext const& ctx) { diff --git a/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Warlock.cpp b/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Warlock.cpp index e1d866affc..ee1bb71a16 100644 --- a/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Warlock.cpp +++ b/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Warlock.cpp @@ -11,7 +11,7 @@ // else Imp; dungeon / raid group: Felhunter for the designated Spell Lock // warlocks, Imp for the rest) and points it at the victim in combat. // -// Priorities follow Karrz's ike3 vanilla strategies (the ike3-based playerbot code +// Priorities follow Karrz's ike3 vanilla strategies (Karrz1/wow-1.12 // raid10-revamp, playerbot/strategy/warlock/*Strategy.cpp, MANGOSBOT_ZERO): // armor + pet upkeep, emergency Death Coil / Howl of Terror / Drain Life, // Life Tap at low mana, dots (Corruption, Curse of Agony, Immolate, Siphon @@ -84,6 +84,13 @@ bool VictimIsBossLike(ApPredicateContext const& ctx) return v && ((v->is_dungeon_boss || v->is_boss_rank) || v->max_hp >= 100'000); } +// The mana the filler nukes stop at: a warlock with a wand shoots below 35% on ordinary fights, and casts down to 8% against a boss or +// when it holds no wand. +int32 NukeManaFloor(ApPredicateContext const& ctx) +{ + return ctx.bot.raw().consumables.wand_school_mask != 0 && !VictimIsBossLike(ctx) ? 35 : 8; +} + int32 VictimHpPct(ApPredicateContext const& ctx) { NearbyUnit const* v = ctx.bot.victim_info(); @@ -129,11 +136,12 @@ bool ShouldHowlOfTerror(ApPredicateContext const& ctx) // Raid school rule: not into a mob that avoids shadow (only that veto - // this is the emergency fear, the threat-discipline gates do not apply). float x, y, z; ctx.bot.position(x, y, z); - if (FindAoeHazard(ctx.bot, x, y, z, 10.0f, /*damaging*/ false, /*tank*/ false, HOWL_OF_TERROR).kind - == AoeHazardKind::SchoolAvoided) + // A crowd-controlled mob in the ring vetoes it too (as Frost Nova's does). + AoeHazardKind const k = FindAoeHazard(ctx.bot, x, y, z, 10.0f, /*damaging*/ true, /*tank*/ false, HOWL_OF_TERROR).kind; + if (k == AoeHazardKind::SchoolAvoided || k == AoeHazardKind::CrowdControlled) return false; - // Raid groups: no fear with an unpulled pack within 40y, and only for a - // warlock an elite is hitting (ThreatDiscipline.h RaidFearAllowed). + // Raid groups and instances: no fear with an unpulled pack within 40y; raids + // also only for a warlock an elite is hitting (ThreatDiscipline.h RaidFearAllowed). return RaidFearAllowed(ctx.bot, ctx.group.is_raid() || ctx.bot.is_in_raid(), "Howl of Terror"); } void DoHowlOfTerror(ApPredicateContext const&, BotIntentEmitter& e) { e.cast(HOWL_OF_TERROR); } @@ -311,7 +319,7 @@ void DoDrainSoul(ApPredicateContext const& ctx, BotIntentEmitter& e) { e.cast(DR bool ShouldShadowBolt(ApPredicateContext const& ctx) { - return HasLiveTarget(ctx) && ManaPct(ctx) >= 8 && (Ready(ctx, SHADOW_BOLT) && ctx.bot.victim_in_spell_range(SHADOW_BOLT)); + return HasLiveTarget(ctx) && ManaPct(ctx) >= NukeManaFloor(ctx) && (Ready(ctx, SHADOW_BOLT) && ctx.bot.victim_in_spell_range(SHADOW_BOLT)); } void DoShadowBolt(ApPredicateContext const& ctx, BotIntentEmitter& e) { e.cast(SHADOW_BOLT, ctx.bot.victim()); } @@ -321,7 +329,7 @@ void DoShadowBolt(ApPredicateContext const& ctx, BotIntentEmitter& e) { e.cast(S // / Searing Pain (the fire filler, Shadow Bolt's mana gate). bool ShouldSearingPain(ApPredicateContext const& ctx) { - return HasLiveTarget(ctx) && ManaPct(ctx) >= 8 && Ready(ctx, SEARING_PAIN); + return HasLiveTarget(ctx) && ManaPct(ctx) >= NukeManaFloor(ctx) && Ready(ctx, SEARING_PAIN); } SchoolHint::SchoolChoice const kSchoolChoices[] = { diff --git a/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Warrior.cpp b/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Warrior.cpp index 2ba062da33..8de6685fc9 100644 --- a/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Warrior.cpp +++ b/src/modules/PlayerbotV2/Combat/Apl/Apl_Classic_Warrior.cpp @@ -10,7 +10,7 @@ // (Overpower, Revenge, Execute) are gated by the snapshot's aura-state // check, so their predicates only test rage and stance. // -// Priorities follow Karrz's ike3 vanilla strategies (the ike3-based playerbot code +// Priorities follow Karrz's ike3 vanilla strategies (Karrz1/wow-1.12 // raid10-revamp, playerbot/strategy/warrior/*Strategy.cpp, MANGOSBOT_ZERO). #include "../ApRegistry.h" @@ -655,7 +655,7 @@ void DoShieldWall(ApPredicateContext const& ctx, BotIntentEmitter& e) Classic::NoteCooldownUse(ctx.bot, SHIELD_WALL, "Shield Wall"); } -// ---- Threat: loose attackers (Karrz's LooseAttackersTrigger) ---- +// ---- Threat: loose attackers (the owner's LooseAttackersTrigger) ---- // A "loose attacker" is a mob hitting a NON-TANK group member (snapshot // victim_kind == Member). Taunt's reach is read from the spell data // (TankThreat::TauntReach, 10 yd when the data has none); the pick-up rule @@ -676,7 +676,7 @@ bool VictimSecured(ApPredicateContext const& ctx) return v->hp <= 0 || k == ThreatVictim::Me || k == ThreatVictim::Tank; } -// Challenging Shout when 3+ loose attackers are within 10 yd (Karrz) - only +// Challenging Shout when 3+ loose attackers are within 10 yd (the owner) - only // those no other tank was given (its owner is coming; two tanks would burn // both shouts on one pack), and never with a crowd-controlled mob in reach. bool ShouldChallengingShout(ApPredicateContext const& ctx) @@ -838,7 +838,10 @@ bool ShouldTankCleave(ApPredicateContext const& ctx) bool ShouldShieldSlam(ApPredicateContext const& ctx) { - return HasLiveTarget(ctx) && Rage(ctx) >= 20 && (Ready(ctx, SHIELD_SLAM) && ctx.bot.victim_in_spell_range(SHIELD_SLAM)); + // Needs a shield: without one the core refuses every cast (EQUIPPED_ITEM_CLASS) and this rule, ahead of Sunder, ate the tank's rage + // all fight (n43 onyxia_full: 69 refusals, two of three warrior tanks without a shield, rage idle at 25+ for 40 % of the fight). + return HasLiveTarget(ctx) && Rage(ctx) >= 20 && Interrupt::HasShield(ctx.bot) + && (Ready(ctx, SHIELD_SLAM) && ctx.bot.victim_in_spell_range(SHIELD_SLAM)); } void DoShieldSlam(ApPredicateContext const& ctx, BotIntentEmitter& e) { e.cast(SHIELD_SLAM, ctx.bot.victim()); } diff --git a/src/modules/PlayerbotV2/Combat/Apl/Apl_Hunter_BeastMastery.cpp b/src/modules/PlayerbotV2/Combat/Apl/Apl_Hunter_BeastMastery.cpp index 1e0266e7ed..9616078af5 100644 --- a/src/modules/PlayerbotV2/Combat/Apl/Apl_Hunter_BeastMastery.cpp +++ b/src/modules/PlayerbotV2/Combat/Apl/Apl_Hunter_BeastMastery.cpp @@ -52,7 +52,7 @@ // * Tranquilizing Shot (19801) - [M]-only class talent, dispel logic // lives outside the DPS ladder. // * Track Pets / Exotic Beasts / Eyes of the Beast - minimap utility, -// passive, pet-vision toy (breaks bot AI control). +// passive, pet-vision toy (breaks bot bot logic control). #include "../ApRegistry.h" #include "../ApRotation.h" diff --git a/src/modules/PlayerbotV2/Combat/Apl/Apl_Hunter_Survival.cpp b/src/modules/PlayerbotV2/Combat/Apl/Apl_Hunter_Survival.cpp index 8a07ad4c84..b6e774762c 100644 --- a/src/modules/PlayerbotV2/Combat/Apl/Apl_Hunter_Survival.cpp +++ b/src/modules/PlayerbotV2/Combat/Apl/Apl_Hunter_Survival.cpp @@ -42,7 +42,7 @@ // Clip (195645) - out-of-combat or positional utility. // * Tranquilizing Shot (19801) / Camouflage (199483) - [M]-only class // talents, dispel / stealth logic lives outside the DPS ladder. -// * Eyes of the Beast ( 321297) - pet-vision toy, breaks bot AI control. +// * Eyes of the Beast ( 321297) - pet-vision toy, breaks bot bot logic control. #include "../ApRegistry.h" #include "../ApRotation.h" diff --git a/src/modules/PlayerbotV2/Combat/Apl/Apl_Warlock_Demonology.cpp b/src/modules/PlayerbotV2/Combat/Apl/Apl_Warlock_Demonology.cpp index deaeafaccd..a5456932c0 100644 --- a/src/modules/PlayerbotV2/Combat/Apl/Apl_Warlock_Demonology.cpp +++ b/src/modules/PlayerbotV2/Combat/Apl/Apl_Warlock_Demonology.cpp @@ -38,7 +38,7 @@ // makes Call Dreadstalkers summon the Vilefiend - nothing to cast. // - Doom (603): 12.1 Doom 460551 is a passive applied by Demonbolt. // - Fel Firebolt / Felstorm (89751): Wild Imp / Felguard PET abilities, -// handled by the pet AI server-side, never cast by the warlock. +// handled by the pet bot logic server-side, never cast by the warlock. // - Summon Felguard (30146) / Imp (688): pet maintenance lives in // State_Idle (ooc pet-summon rule), not in the combat APL. // - Banish (710), Fear (5782), Curse of Tongues (1714 [R]) / Exhaustion diff --git a/src/modules/PlayerbotV2/Combat/Apl/HealClaimStore.h b/src/modules/PlayerbotV2/Combat/Apl/HealClaimStore.h index d724daedd0..31034cb0f8 100644 --- a/src/modules/PlayerbotV2/Combat/Apl/HealClaimStore.h +++ b/src/modules/PlayerbotV2/Combat/Apl/HealClaimStore.h @@ -34,12 +34,27 @@ struct HealClaim }; using HealClaims = std::vector>; // healer guid counter -> claim +// One book for the whole process. The map and its mutex must not be function-local statics of a template: every lambda type is a +// separate instantiation, and each would get a private map, so a claim written by EmitHeal would be invisible to PickPatient, +// CopyHealClaims and ReleaseHealClaim. +struct HealClaimBook +{ + std::mutex mu; + std::unordered_map claims; +}; + +inline HealClaimBook& HealClaimBookInstance() +{ + static HealClaimBook book; + return book; +} + template auto WithHealClaims(uint32 now, F&& f) { - static std::mutex mu; - static std::unordered_map claims; - std::lock_guard lock(mu); + HealClaimBook& book = HealClaimBookInstance(); + std::lock_guard lock(book.mu); + auto& claims = book.claims; if (claims.size() > 64) for (auto it = claims.begin(); it != claims.end();) it = int32(now - it->second.start_ms) > int32(kHealClaimMaxAgeMs) ? claims.erase(it) : std::next(it); diff --git a/src/modules/PlayerbotV2/Commands/cs_playerbot_v2.cpp b/src/modules/PlayerbotV2/Commands/cs_playerbot_v2.cpp index 0cceef8abc..5d84321901 100644 --- a/src/modules/PlayerbotV2/Commands/cs_playerbot_v2.cpp +++ b/src/modules/PlayerbotV2/Commands/cs_playerbot_v2.cpp @@ -30,6 +30,7 @@ #include "WorldSession.h" #include "TypeContainerVisitor.h" #include "PlayerbotAPI.h" +#include "PlayerbotV2.h" #include "PlayerbotMovement.h" // BotMovement::SafeTeleport for GM summonall #include "RBAC.h" #include "SpellHistory.h" @@ -608,6 +609,7 @@ public: static ChatCommandTable botTable = { { "about", HandleBotAbout, rbac::RBAC_PERM_COMMAND_GM, Console::Yes }, + { "addon", HandleBotAddonHello, rbac::RBAC_PERM_JOIN_NORMAL_BG, Console::No }, { "add", HandleBotAdd, rbac::RBAC_PERM_COMMAND_GM, Console::No }, { "call", HandleBotCall, rbac::RBAC_PERM_COMMAND_GM, Console::No }, // Every player: brings the caller's own bots only (`.bot summon all|saved|`). @@ -707,6 +709,16 @@ public: return false; } + // .bot addon: sent silently by the ForeverBots add-on a few seconds after login, so the server knows this client has it and + // does not send the download hint (Playerbot.AddonHint.*). Says nothing. + static bool HandleBotAddonHello(ChatHandler* handler) + { + WorldSession* sess = handler ? handler->GetSession() : nullptr; + if (sess && sess->GetPlayer()) + Playerbot::V2::Module::instance().NoteAddonHello(sess->GetPlayer()); + return true; + } + // .bot about: the name of the bots, so it shows in the command list and `.bot` help static bool HandleBotAbout(ChatHandler* handler) { @@ -1126,7 +1138,7 @@ public: bool const with_me = ToLowerAscii(who) == "all"; std::string names; uint32 saved = 0; - // Save group REPLACES the saved roster (chris, 2026-10-11: after a second save the call said 78 saved where the first said 39: the + // Save group REPLACES the saved roster (playtest, 2026-10-11: after a second save the call said 78 saved where the first said 39: the // bots of the earlier save stayed saved next to the new ones). A companion saved earlier that is not in the group now is unsaved. if (with_me) { @@ -1511,10 +1523,10 @@ public: (void)gm; } // Already-online characters get the registry entry without a re-login, - // so the AI ticks can start at the next world update. Offline characters + // so the bot ticks can start at the next world update. Offline characters // get the marker only — the next time someone logs them in (manually or // via .playerbot login), OnPlayerLogin will see is_bot()==true and - // attach the AI. + // attach the bot logic. if (Player const* p = ObjectAccessor::FindConnectedPlayerByName(target_name)) { if (!Playerbot::Services::Registry().has(id)) @@ -1529,12 +1541,12 @@ public: Playerbot::Services::Scheduler().register_bot( id, Playerbot::ActivityTier::Idle); } - handler->PSendSysMessage("Marked %s (online) as a V2 bot — AI active.", + handler->PSendSysMessage("Marked %s (online) as a V2 bot — bot logic active.", p->GetName().c_str()); } else { - handler->PSendSysMessage("Marked '%s' as a V2 bot. AI activates on next login.", + handler->PSendSysMessage("Marked '%s' as a V2 bot. Bot logic activates on next login.", target_name.c_str()); } return true; @@ -1555,14 +1567,14 @@ public: } Playerbot::Services::Lifecycle().unmark_as_bot(id); // If the character is online and currently registered, drop the - // registry entry too so the AI stops driving them this session. + // registry entry too so the bot logic stops driving them this session. if (Playerbot::Services::Registry().has(id)) { Playerbot::Services::Scheduler().unregister_bot(id); Playerbot::Services::Snapshots().remove(id); Playerbot::Services::Registry().unregister_bot(id); } - handler->PSendSysMessage("Unmarked '%s'. AI detached.", target_name.c_str()); + handler->PSendSysMessage("Unmarked '%s'. Bot logic detached.", target_name.c_str()); // Owner binding becomes meaningless without the bot — clear it so // a future re-mark of the same character starts clean. Playerbot::Services::Owners().ClearOwner(id); @@ -1760,7 +1772,7 @@ public: const size_t registered = Playerbot::Services::Registry().size(); // Walk marked ids and count how many resolve to a connected Player — // gives the actual "in-world right now" number, distinct from - // registered (registered counts every bot whose AI exists, including + // registered (registered counts every bot whose bot logic exists, including // ones whose Player* may have despawned mid-tick). const auto ids = Playerbot::Services::Lifecycle().snapshot_ids(); size_t online = 0; @@ -1822,7 +1834,7 @@ public: CharacterCacheEntry const* ce = sCharacterCache->GetCharacterCacheByGuid(g); const bool online = ObjectAccessor::FindConnectedPlayer(g) != nullptr; const bool registered = Playerbot::Services::Registry().has(id); - char const* state = online ? (registered ? "ON+AI" : "ON ") + char const* state = online ? (registered ? "ON+OK" : "ON ") : (registered ? "REG " : "off "); if (ce) { @@ -2336,7 +2348,7 @@ public: return false; } - // Unregister AI + unmark before deleting the character row so the + // Unregister bot logic + unmark before deleting the character row so the // registry has no dangling reference if delete fails midway. if (Playerbot::Services::Registry().has(id)) { @@ -2699,7 +2711,7 @@ public: return true; } // Pure-bot groups never block formation: the BotGroupBuilder / - // social-invite AI constantly re-groups idle bots, so any test + // social-invite bot logic constantly re-groups idle bots, so any test // group has to be able to YANK its members out of those. Groups // containing a human are left untouched (skip with a message). auto detach_if_bot_group = [&](Player* p) -> bool @@ -2834,7 +2846,7 @@ public: // harnesses) can activate committed route/road changes instantly: // * dungeon route waypoints ({SharedDb}.playerbot_dungeon_routes) — // DungeonScriptMgr::LoadGeneratedRoutes builds a fresh table and - // atomically swaps it under the routes mutex (AI-worker readers keep a + // atomically swaps it under the routes mutex (bot-worker readers keep a // coherent snapshot); the next GetAdvice tick serves the new routes. // * handcrafted roads ({SharedDb}.handcrafted_road) — storage reload bumps // the generation counter and the road GRAPH cache is invalidated, so the @@ -3018,7 +3030,7 @@ public: } // Detach a bot from any pure-bot group so it can solo-queue LFG (the - // social-invite AI constantly re-groups idle bots). Humans untouched. + // social-invite bot logic constantly re-groups idle bots). Humans untouched. auto detach_if_bot_group = [&](Player* p) { Group* g = p->GetGroup(); @@ -4104,7 +4116,7 @@ public: // same account as the issuing player. Without this gate any GM // could conscript anyone's character on the realm. // 3) Auto-marks + auto-adopts on success: a single command end-to-end - // from "I want to play with my alt" to "AI-controlled bot is + // from "I want to play with my alt" to "bot-controlled bot is // following me." No separate mark/adopt/login dance. // // Account-wide-progress is the design intent: a player levels their @@ -4145,12 +4157,12 @@ public: } if (id == me->GetGUID().GetCounter()) { - // Summoning yourself collapses into the Wave-F bot-AI-on-self + // Summoning yourself collapses into the Wave-F bot-bot logic-on-self // toggle, which is a different command. Refuse explicitly so - // the user doesn't accidentally hand their main to the AI. + // the user doesn't accidentally hand their main to the bot logic. handler->SendSysMessage( "That's your current character. Use `.playerbot self on` " - "to drive your own character with the AI instead."); + "to drive your own character with the bot logic instead."); return false; } @@ -4233,7 +4245,7 @@ public: } handler->PSendSysMessage( - "Summoning your alt '%s' — AI-controlled bot enters world on " + "Summoning your alt '%s' — bot-controlled bot enters world on " "the next DB callback. You (and any other char on your account) " "can whisper `follow`, `stop`, `engage`, `squad`, `role` to it.", target_name.c_str()); @@ -4242,8 +4254,8 @@ public: // .playerbot self on | off | status // - // First-person testing toggle: attach (or detach) the V2 AI to the - // issuing player's OWN character. Lets the player observe AI decisions + // First-person testing toggle: attach (or detach) the V2 bot logic to the + // issuing player's OWN character. Lets the player observe bot logic decisions // from inside the bot — vastly deeper insight than reading logs after // the fact ("why did it stop?", "why didn't it kick?", "where was the // pull heuristic going to send me?"). @@ -4252,11 +4264,11 @@ public: // scoped to "myself" so the user doesn't have to type their own name. // The player's client input still flows through the network normally // — IntentExecutor and the client compete on movement and ability use, - // and the player wins when they actively press a key (the AI's movement + // and the player wins when they actively press a key (the bot logic's movement // intents will arrive late and overwrite, but only when the client is // idle). For pure observation, the player can simply not move and watch. // - // Status sub-form prints whether AI is currently attached to self + // Status sub-form prints whether bot logic is currently attached to self // without changing anything, useful for verifying the toggle. static bool HandleSelf(ChatHandler* handler, std::string const& arg) { @@ -4279,7 +4291,7 @@ public: if (mode.empty() || mode == "status") { handler->PSendSysMessage( - "Self-AI: marked=%s attached=%s (use `on`/`off` to toggle).", + "Self-bot: marked=%s attached=%s (use `on`/`off` to toggle).", is_bot ? "yes" : "no", is_attached ? "yes" : "no"); return true; @@ -4288,11 +4300,11 @@ public: { if (is_attached) { - handler->SendSysMessage("Self-AI is already attached."); + handler->SendSysMessage("Self-bot is already attached."); return true; } // Mark + adopt to self (account-bound). On-mark code path - // already registers + schedules the AI for the online player, + // already registers + schedules the bot logic for the online player, // so a single call wires everything. if (!is_bot) Playerbot::Services::Lifecycle().mark_as_bot(id); @@ -4311,16 +4323,16 @@ public: id, Playerbot::ActivityTier::Idle); } handler->SendSysMessage( - "Self-AI: ON. AI now drives your character. Your client " + "Self-bot: ON. Bot logic now drives your character. Your client " "input still works — pressing movement keys interrupts the " - "AI's move intents. Use `.playerbot self off` to detach."); + "Bot logic's move intents. Use `.playerbot self off` to detach."); return true; } if (mode == "off") { if (!is_bot && !is_attached) { - handler->SendSysMessage("Self-AI is not attached."); + handler->SendSysMessage("Self-bot is not attached."); return true; } if (Playerbot::Services::Registry().has(id)) @@ -4333,7 +4345,7 @@ public: Playerbot::Services::Lifecycle().unmark_as_bot(id); Playerbot::Services::Owners().ClearOwner(id); handler->SendSysMessage( - "Self-AI: OFF. AI detached. You are back to manual control."); + "Self-bot: OFF. Bot logic detached. You are back to manual control."); return true; } handler->PSendSysMessage("Usage: .playerbot self on | off | status"); diff --git a/src/modules/PlayerbotV2/Diagnostics/BotInspector.cpp b/src/modules/PlayerbotV2/Diagnostics/BotInspector.cpp index e4db7b49ea..8d3a4a0bab 100644 --- a/src/modules/PlayerbotV2/Diagnostics/BotInspector.cpp +++ b/src/modules/PlayerbotV2/Diagnostics/BotInspector.cpp @@ -579,7 +579,7 @@ std::string SystemStatus() "Tick lat (p99) : {} ms\n" "World lat (p50) : {} ms\n" "World lat (p99) : {} ms\n" - "AI workers : {} (queue high-watermark: {})\n", + "bot workers : {} (queue high-watermark: {})\n", // ==== Fleet args ==== fleet_in_world, fleet_alive, @@ -672,7 +672,7 @@ char const* ActivityBucket(char const* last_rule) if (starts_with("idle:bank")) return "Banking"; if (starts_with("idle:taxi") || starts_with("idle:homebind")) return "Traveling"; if (starts_with("idle:mail")) return "Mail"; - if (starts_with("idle:ooc_food") || starts_with("idle:ooc_potion") || + if (starts_with("idle:ooc_eat_food") || starts_with("idle:ooc_potion") || starts_with("idle:ooc_bandage") || starts_with("idle:cannibalize") || starts_with("idle:ooc_heal") || starts_with("idle:ooc_dispel") || starts_with("idle:ooc_rez") || starts_with("idle:self_buff") || @@ -713,7 +713,7 @@ std::string FleetActivity() if (!Services::Initialized()) return "PlayerbotV2 not initialized."; // Walk the registry once, bucket each bot's last_rule_fired. Bots whose - // AI has never ticked yet (last_rule_fired == nullptr) bucket as + // Bot logic has never ticked yet (last_rule_fired == nullptr) bucket as // "Idle/none" — usually means just-spawned or just-respawned bots that // haven't had a snapshot yet. std::map counts; diff --git a/src/modules/PlayerbotV2/Diagnostics/BotSmokeTest.cpp b/src/modules/PlayerbotV2/Diagnostics/BotSmokeTest.cpp index 4142303557..7a4f266069 100644 --- a/src/modules/PlayerbotV2/Diagnostics/BotSmokeTest.cpp +++ b/src/modules/PlayerbotV2/Diagnostics/BotSmokeTest.cpp @@ -261,7 +261,7 @@ void RunWorker(std::vector bot_ids, LaunchOptions opts, } // 3c) Each bot's intent history must have at least min_intents entries. - // A zero ring means the AI never fired a single intent in 60s — that's + // A zero ring means the bot logic never fired a single intent in 60s — that's // a regression in BotAI, the snapshot publisher, or the intent // executor. Distinct from "bots that haven't spawned yet" because we // already gated on AllDone above. @@ -291,9 +291,9 @@ void RunWorker(std::vector bot_ids, LaunchOptions opts, } // 3d) PerfCounters intents_dropped_total must not have grown. A drop - // is "AI worker produced an intent but per-bot IntentQueue was full" + // is "bot worker produced an intent but per-bot IntentQueue was full" // — sustained drops mean the world-thread executor is starving and - // the bot is effectively desynced from its own AI. + // the bot is effectively desynced from its own bot logic. { SmokeTestAssertion as; as.name = "no_dropped_intents"; diff --git a/src/modules/PlayerbotV2/Diagnostics/BotSmokeTest.h b/src/modules/PlayerbotV2/Diagnostics/BotSmokeTest.h index c2a301b551..5af0b06ffb 100644 --- a/src/modules/PlayerbotV2/Diagnostics/BotSmokeTest.h +++ b/src/modules/PlayerbotV2/Diagnostics/BotSmokeTest.h @@ -1,5 +1,5 @@ // BotSmokeTest - End-to-end regression harness driving the PlayerbotV2 -// spawn → setup-pipeline → AI-tick path. Used by `.playerbot smoketest +// spawn → setup-pipeline → bot logic-tick path. Used by `.playerbot smoketest // [count]` to catch regressions in fleet bring-up against a clean realm. // // Design constraints (see /diag and HealthReport documentation): diff --git a/src/modules/PlayerbotV2/Diagnostics/DamageParity.cpp b/src/modules/PlayerbotV2/Diagnostics/DamageParity.cpp index 085ffefafc..ce37fe86e4 100644 --- a/src/modules/PlayerbotV2/Diagnostics/DamageParity.cpp +++ b/src/modules/PlayerbotV2/Diagnostics/DamageParity.cpp @@ -390,7 +390,7 @@ std::uint32_t FindDummyEntry() // The operator's choice first, then known test dummies: 1000 Unkillable Test Dummy, 2673 Target Dummy, 1921 (the old training dummy). // Each is taken only if the server can actually put it in the world. std::vector candidates; - if (int const cfg = sConfigMgr->GetIntDefault("Playerbot.Scenario.DummyEntry", 0); cfg > 0) + if (int const cfg = sConfigMgr->GetIntDefault("Playerbot.Scenario.DummyEntry", 0, true); cfg > 0) candidates.push_back(std::uint32_t(cfg)); for (std::uint32_t const e : { 1000u, 2673u, 1921u }) candidates.push_back(e); @@ -539,7 +539,7 @@ void Engage(Player* p, Creature* d) } } -// The bot's own AI stops (a sweep casts by hand): the same three calls the scenario stand-in uses. +// The bot's own bot logic stops (a sweep casts by hand): the same three calls the scenario stand-in uses. void DetachAi(Player* p) { ::Playerbot::BotId const id = p->GetGUID().GetCounter(); @@ -1373,7 +1373,7 @@ bool EconStep(Player* p, Creature* d, std::string& failure) TC_LOG_INFO("playerbot.v2", "[econ] regen class={} state=casting spell=\"{}\" casts={} cost_each={:.0f} window_s={:.0f} mana_gained_window={:.0f} (net change {:.0f} plus the {:.0f} spent) mana_gained_10s={:.0f} ate_or_drank_in_window: {}", g.cls_name, MainSpellFor(g.cls), e.casts, e.cost, window_s, gained_window, cur - e.m0, e.spent, e.r_cast, RecoveryText(e.recov, e.sat)); g_energy_on = false; - // What else put mana in or fired in the window. The AI is detached, so anything listed here is a finding. + // What else put mana in or fired in the window. The bot logic is detached, so anything listed here is a finding. std::string energy; double energy_total = 0.0; { diff --git a/src/modules/PlayerbotV2/Diagnostics/DamageParity.h b/src/modules/PlayerbotV2/Diagnostics/DamageParity.h index 0649089f40..eb7ee25905 100644 --- a/src/modules/PlayerbotV2/Diagnostics/DamageParity.h +++ b/src/modules/PlayerbotV2/Diagnostics/DamageParity.h @@ -17,7 +17,7 @@ class Unit; namespace Playerbot::Diagnostics::Parity { -// Economy: mana pool, regen in and out of combat and while casting, spell costs, heal sizes (a caster or healer, AI detached). +// Economy: mana pool, regen in and out of combat and while casting, spell costs, heal sizes (a caster or healer, bot logic detached). // Incoming: a tank is hit by a level 63 dummy at bare / tier 1 / tier 3 armor, then by Firesworn, Magmadar and a Deadmines mob. // Trap: a hunter sets Explosive, Immolation, Frost and Freezing Trap out of combat, a target dummy is moved onto each, and the trap must fire // (the [trap_cast] line carries the cast result and the spell's effect targets) and do its job to the dummy. diff --git a/src/modules/PlayerbotV2/Diagnostics/PerfCounters.h b/src/modules/PlayerbotV2/Diagnostics/PerfCounters.h index 4f0225ff7b..22aeb04f82 100644 --- a/src/modules/PlayerbotV2/Diagnostics/PerfCounters.h +++ b/src/modules/PlayerbotV2/Diagnostics/PerfCounters.h @@ -21,7 +21,7 @@ public: void record_event_pushed(); void record_event_dropped(); // ring overflow // Intent producer couldn't push because the per-bot IntentQueue is full. - // Sustained increments mean an AI worker is producing faster than the + // Sustained increments mean an bot worker is producing faster than the // world thread drains, or the per-tick budget is too tight. void record_intent_dropped(); // Bucketed by Result enum value (cast to size_t at the call site to avoid @@ -225,7 +225,7 @@ private: // Per-(class, spec, bracket) BG outcome bucket store. Key encoding: // (cls << 24) | (spec << 8) | bracket_lo10. shared_mutex bridges - // multiple AI threads firing record_bg_outcome at near-simultaneous + // multiple bot logic threads firing record_bg_outcome at near-simultaneous // BG-end ticks; reads are infrequent (only on diag command). public: struct BgBucket { uint32_t wins = 0; uint32_t losses = 0; }; diff --git a/src/modules/PlayerbotV2/Diagnostics/ScenarioDefs.h b/src/modules/PlayerbotV2/Diagnostics/ScenarioDefs.h index 64f1cc7eef..3c0ddddcea 100644 --- a/src/modules/PlayerbotV2/Diagnostics/ScenarioDefs.h +++ b/src/modules/PlayerbotV2/Diagnostics/ScenarioDefs.h @@ -59,8 +59,14 @@ struct ScenarioDef // arrive_near_entry (the boss's room; the encounter is pre-spawned). order_attack: `order_delay_ms` into the run the main tank is // ordered onto goal_entry, which is what the owner's Attack does in a raid with a human leader. 0 / false = a dungeon scenario. std::uint32_t arrive_near_entry = 0; + // The raid lands at least this far from that creature (0 = the default 40 y). A boss that aggroes on sight (Onyxia: 58 y) is not held, so a + // landing inside its reach starts the fight on whoever stands nearest instead of on the tank walking in (onyxia_full n6, 2026-10-14). + float arrive_min_yards = 0.f; // Staging kills every hostile on the map but the goal boss, its formation and this entry (the boss's own adds); 0 = none. std::uint32_t keep_entry = 0; + // A fight with no boss death to wait for (Majordomo Executus yields when his eight adds are dead): the goal is reached when this many + // creatures of these two entries have died on the map. 0 = the goal boss's death. + std::uint32_t goal_adds_a = 0, goal_adds_b = 0, goal_adds_needed = 0; bool order_attack = false; std::uint32_t order_delay_ms = 0; // A whole-dungeon clear to the last boss: long, so `runall` with no filter leaves it out (`runall full` or `run ` starts it). @@ -69,17 +75,20 @@ struct ScenarioDef // damage leg measures. 0 = not a parity scenario. std::uint8_t parity = 0; std::uint32_t parity_leg_s = 180; - // The name of a member played like Karrz's own character: from the start of the run its AI is detached and the runner drives it, + // The name of a member played like the owner's own character: from the start of the run its bot logic is detached and the runner drives it, // following the main tank and attacking what the tank attacks (a player who only presses "assist"). The group logic still sees a - // bot-led group. nullptr = every member runs its own AI. + // bot-led group. nullptr = every member runs its own bot logic. char const* stand_in = nullptr; // Checkpoint starts (`scenario run @`): the squad enters at the entrance as usual, then is moved to a spot in sight of the first // spawn of the checkpoint's creature (a boss or a pack's mob) and plays on from there, bot-led and with no Hold, so a run does not replay // the part that is already solved. The goal and the first-death rule stay. Earlier bosses stay alive in the instance. std::vector checkpoints; + // A goal boss with no spawn row in the creature table (a script summons it: Ragnaros, by Majordomo): the lair it is summoned at + // (lair_z != 0). The runner finds the room from it and summons the boss itself, as the instance script does. No DB change. + float lair_x = 0.f, lair_y = 0.f, lair_z = 0.f, lair_o = 0.f; }; -// The party every dungeon scenario uses: the shape of Karrz's own (tank, healer, mage, rogue) plus a hunter for the fifth. The same +// The party every dungeon scenario uses: the shape of the owner's own (tank, healer, mage, rogue) plus a hunter for the fifth. The same // five characters are re-levelled and re-geared for each dungeon, so a full run of the set makes five characters, not sixty. inline std::vector StandardParty() { @@ -192,6 +201,9 @@ struct RaidBossRow std::uint32_t keep_entry = 0; // the boss's own adds (staging leaves them alive); 0 = none std::uint32_t min_tranq_shots = 0; // a kill must have seen at least this many Tranquilizing Shots (Magmadar's Frenzy); 0 = not checked std::uint32_t min_decurses = 0; // ... and this many curses removed (Lucifron's, Gehennas'); 0 = not checked + float lair_x = 0.f, lair_y = 0.f, lair_z = 0.f, lair_o = 0.f; // a boss a script summons (no creature row): where; see ScenarioDef::lair_x + float arrive_min_yards = 0.f; // see ScenarioDef::arrive_min_yards + std::uint32_t goal_adds_a = 0, goal_adds_b = 0, goal_adds_needed = 0; // see ScenarioDef::goal_adds_needed }; // In the order of the raid. Each starts at the boss's room with the encounter pre-spawned (the earlier bosses alive too). @@ -200,40 +212,107 @@ inline constexpr RaidBossRow kMcBosses[] = { { "mc_lucifron", "Molten Core: 40 level 60 raiders to Lucifron", 12118, "Lucifron", 15, 12119, 0, 1 }, // Flamewaker Protector; Lucifron's Curse must be removed { "mc_magmadar", "Molten Core: 40 level 60 raiders to Magmadar", 11982, "Magmadar", 15, 0, 1 }, // Frenzy must be tranquilized { "mc_gehennas", "Molten Core: 40 level 60 raiders to Gehennas", 12259, "Gehennas", 15, 11661, 0, 1 }, // Flamewaker; Gehennas' Curse must be removed - { "mc_geddon", "Molten Core: 40 level 60 raiders to Baron Geddon", 12056, "Baron Geddon", 15 }, // Inferno (19698, 20 y): the raid must leave his range; more than 6 deaths fails it + { "mc_sulfuron", "Molten Core: 40 level 60 raiders to Sulfuron Harbinger", 12098, "Sulfuron Harbinger", 15, 11662 }, // Flamewaker Priests: Dark Mending is interrupted, Inspire purged, Shadow Word: Pain kept off + { "mc_golemagg", "Molten Core: 40 level 60 raiders to Golemagg the Incinerator", 11988, "Golemagg the Incinerator", 15, 11672 }, // Core Ragers: the off tank holds them away from Golemagg; Magma Splash stacks on the main tank + // Majordomo does not die: the fight ends when his eight Flamewakers (11664 elite, 11663 healer) are dead and he yields. Magic Reflection and Damage + // Shield on the adds, Aegis of Ragnaros on him. + { "mc_majordomo", "Molten Core: 40 level 60 raiders to Majordomo Executus", 12018, "Majordomo Executus", 15, 0, 0, 0, 758.089f, -1176.71f, -118.640f, 3.12414f, 0.f, 11664, 11663, 8 }, // no creature row: the instance script summons him in his hall (classic_instance_molten_core.cpp, SummonCreature 758.089,-1176.71,-118.640); the runner summons him there + { "mc_geddon", "Molten Core: 40 level 60 raiders to Baron Geddon", 12056, "Baron Geddon", 15 }, // Inferno (19698, 20 y): the raid must leave his range + { "mc_ragnaros", "Molten Core: 40 level 60 raiders to Ragnaros", 11502, "Ragnaros", 20, 0, 0, 0, + 838.308f, -831.466f, -232.185f, 2.19911f }, // no creature row: summoned at his lair (classic_boss_majordomo_executus.cpp:342). Elemental Fire on the tank, Wrath threat reset and knockback, Magma Blast out of melee reach, submerge at 3 min (Sons of Flame) }; -inline ScenarioDef MakeMcScenario(RaidBossRow const& r) +// Where a 40-man raid scenario arrives: the instance and its entrance areatrigger target. +struct RaidEntrance { std::uint32_t map; float x, y, z, o_deg; }; + +inline constexpr RaidEntrance kMcEntrance = { 409, 1091.89f, -466.985f, -105.084f, 180.f }; // areatrigger_teleport 1102886 +inline constexpr RaidEntrance kBwlEntrance = { 469, -7673.2f, -1106.2f, 396.65f, 200.f }; // areatrigger_teleport 1103726 (vanilla entrance target) +inline constexpr RaidEntrance kOnyEntrance = { 249, 30.8916f, -54.079f, -5.02784f, 270.f }; // areatrigger_teleport 1102848 + +inline ScenarioDef MakeRaidScenario(RaidBossRow const& r, RaidEntrance const& e, std::vector squad) { ScenarioDef d{}; d.name = r.name; d.summary = r.summary; d.level = 60; - d.squad = RaidSquad(kMcRaid, sizeof(kMcRaid) / sizeof(kMcRaid[0])); - d.map = 409; - d.x = 1091.89f; d.y = -466.985f; d.z = -105.084f; // the Molten Core entrance (areatrigger_teleport 1102886) - d.o = 180.f * 3.14159265f / 180.f; + d.squad = std::move(squad); + d.map = e.map; + d.x = e.x; d.y = e.y; d.z = e.z; + d.o = e.o_deg * 3.14159265f / 180.f; d.goal = ScenarioGoalKind::KillCreature; d.goal_entry = r.boss_entry; d.goal_name = r.boss_name; d.timeout_ms = r.timeout_min * 60u * 1000u; - d.limits.expected_map = 409; + d.limits.expected_map = e.map; d.limits.bounds = { true, d.x - 800.f, d.x + 800.f, d.y - 800.f, d.y + 800.f, d.z - 250.f, d.z + 250.f }; d.limits.expected_group = std::uint32_t(d.squad.size()); - d.limits.tolerated_deaths = 5; // more than five dead raiders fails the run - d.limits.max_deaths = 6; + d.limits.kill_is_pass = true; // playtest 2026-10-14: a boss kill passes, however many die + d.limits.tolerated_deaths = 0; // every death is a warning in the result + d.limits.max_deaths = 0; // and none ends the run: only a full wipe, a reset, a stall or the timeout does d.limits.dps_hold_ms = 20000; - d.limits.tanks_dead_is_wipe = true; + d.limits.tanks_dead_is_wipe = false; d.limits.min_tranq_shots = r.min_tranq_shots; d.limits.min_decurses = r.min_decurses; d.limits.stray_yards = 120.f; // a raid spreads over a room d.arrive_near_entry = r.boss_entry; d.keep_entry = r.keep_entry; + d.goal_adds_a = r.goal_adds_a; d.goal_adds_b = r.goal_adds_b; d.goal_adds_needed = r.goal_adds_needed; + d.lair_x = r.lair_x; d.lair_y = r.lair_y; d.lair_z = r.lair_z; d.lair_o = r.lair_o; + d.arrive_min_yards = r.arrive_min_yards; d.order_attack = true; d.order_delay_ms = 20000; return d; } +inline ScenarioDef MakeMcScenario(RaidBossRow const& r) +{ + return MakeRaidScenario(r, kMcEntrance, RaidSquad(kMcRaid, sizeof(kMcRaid) / sizeof(kMcRaid[0]))); +} + +// ---- Onyxia's Lair: the whole fight, 40 level 60 raiders ---- +// Phase 1 (100-65 %): tank her with her back to the raid, melee behind and on the flanks, Wing Buffet / Knock Away on the tank, Flame Breath +// and Tail Sweep cones left empty. Phase 2 (65-40 %): she flies, Fireball spreads the ranged, 5-7 whelps per wave to the tanks and AoE, and a +// Deep Breath along one of eight lines (the 5 s wind-up is the only warning: the whole raid must leave the corridor). Phase 3 (< 40 %): she +// lands, Bellowing Roar fear every 15-30 s (a Dwarf priest's Fear Ward on the main tank), a whelp every 1-10 s, melee again from behind. +// The squad is the MC raid with one Dwarf priest healer for Fear Ward. A boss kill passes the run however many die; a Deep Breath that finds the +// raid standing on the line (the 2026-10-13 wipe: 33 dead in one second) is a wipe and fails it. Read the run's [raid_breath] lines (corridor latched +// at the wind-up), [raid_death] and the phase hp in [raid_fight]. +inline constexpr RaidRow kOnyRaid[] = { + { "Mctankw", ScnRace::Human, ScnClass::Warrior, ScenarioRoleKind::Tank, 3 }, + { "Mctankd", ScnRace::NightElf, ScnClass::Druid, ScenarioRoleKind::Tank, 1 }, + { "Mcheals", ScnRace::Human, ScnClass::Priest, ScenarioRoleKind::Healer, 4 }, + { "Mchealsd", ScnRace::Dwarf, ScnClass::Priest, ScenarioRoleKind::Healer, 1 }, // Fear Ward (Dwarf racial) + { "Mchealp", ScnRace::Human, ScnClass::Paladin, ScenarioRoleKind::Healer, 4 }, + { "Mchealdr", ScnRace::NightElf, ScnClass::Druid, ScenarioRoleKind::Healer, 3 }, + { "Mcmage", ScnRace::Human, ScnClass::Mage, ScenarioRoleKind::Dps, 5 }, + { "Mclock", ScnRace::Human, ScnClass::Warlock, ScenarioRoleKind::Dps, 5 }, + { "Mcrogue", ScnRace::Human, ScnClass::Rogue, ScenarioRoleKind::Dps, 4 }, + { "Mchunt", ScnRace::Dwarf, ScnClass::Hunter, ScenarioRoleKind::Dps, 4 }, + { "Mcwarr", ScnRace::Dwarf, ScnClass::Warrior, ScenarioRoleKind::Dps, 3 }, + { "Mcret", ScnRace::Human, ScnClass::Paladin, ScenarioRoleKind::Dps, 1 }, + { "Mcshad", ScnRace::Human, ScnClass::Priest, ScenarioRoleKind::Dps, 2 }, +}; + +inline ScenarioDef MakeOnyScenario() +{ + static constexpr RaidBossRow kOny = { "onyxia_full", "Onyxia's Lair: 40 level 60 raiders, the whole fight (phase 1 tanking, phase 2 Deep Breath and whelps, phase 3 fear)", + 10184, "Onyxia", 20, 0, 0, 0, 0.f, 0.f, 0.f, 0.f, 68.f }; // Onyxia aggroes at 58 y: land outside it, the tanks pull + return MakeRaidScenario(kOny, kOnyEntrance, RaidSquad(kOnyRaid, sizeof(kOnyRaid) / sizeof(kOnyRaid[0]))); +} + +// ---- Blackwing Lair, Razorgore the Untamed: the orb fight, 40 level 60 raiders ---- +// Phase 1: nobody attacks Razorgore while a Black Dragon Egg stands (he dying early kills the raid). A DPS bot walks to the Orb of Domination +// (GO 177808) and uses it, which engages and possesses Razorgore; the controller sends him egg to egg (Destroy Egg), Mind Exhaustion hands the +// orb to the next bot. Phase 2: the eggs gone, the tanks hold him and the raid kills him. Pass = Razorgore killed. Read the run's [raid_fight] +// lines and the server's classic.bwl.orb lines (who clicked, the Possess cast result, any refusal and why). Grethok stays alive (his guards +// are the pull). +inline ScenarioDef MakeBwlRazorgoreScenario() +{ + static constexpr RaidBossRow kRaz = { "bwl_razorgore", "Blackwing Lair: 40 level 60 raiders to Razorgore the Untamed (a bot takes the Orb of Domination, the eggs, then the kill)", + 12435, "Razorgore the Untamed", 20, 12557 }; // 12557 Grethok the Controller + return MakeRaidScenario(kRaz, kBwlEntrance, RaidSquad(kMcRaid, sizeof(kMcRaid) / sizeof(kMcRaid[0]))); +} + // ---- damage_parity: one level 60 bot per class against a level 63 target dummy ---- // damage_parity_ seven legs of `leg_s` seconds (no gear / tier 1 / tier 3 / +spell power / +attack power / 0 armor / five Sunders) // finisher_sweep_ rogue, druid, warrior: every combo point or rage scaled spell at 1-5 points / rising rage, the damage must grow @@ -309,7 +388,7 @@ inline std::vector const& ScenarioCatalogue() { "smite", 646, -2.585f, -766.284f, 6.172f }, // [41] the ramp up to the ship { "greenskin", 647, -89.643f, -781.119f, 29.200f }, // [47] the gangway { "vancleef", 639, -49.167f, -795.944f, 38.956f } }; // [50] the deck - // The same clear with the rogue played like Karrz's own: it follows the tank and hits the tank's target, nothing else. + // The same clear with the rogue played like the owner's own: it follows the tank and hits the tank's target, nothing else. ScenarioDef p = d; p.name = "deadmines_player"; p.summary = "Deadmines: level 21 party with a rogue played like a player, entrance to Edwin VanCleef"; @@ -319,6 +398,8 @@ inline std::vector const& ScenarioCatalogue() } for (RaidBossRow const& r : kMcBosses) v.push_back(MakeMcScenario(r)); + v.push_back(MakeOnyScenario()); + v.push_back(MakeBwlRazorgoreScenario()); // The names are built once and kept: ScenarioDef carries char const*. static std::deque s_parity_names; for (ParityRow const& r : kParityClasses) diff --git a/src/modules/PlayerbotV2/Diagnostics/ScenarioMonitor.h b/src/modules/PlayerbotV2/Diagnostics/ScenarioMonitor.h index 0df73ba9d9..686223c5c5 100644 --- a/src/modules/PlayerbotV2/Diagnostics/ScenarioMonitor.h +++ b/src/modules/PlayerbotV2/Diagnostics/ScenarioMonitor.h @@ -47,7 +47,7 @@ struct ScenarioSample float hp_pct = 100.f; float mana_pct = -1.f; // -1 = no mana bar (warrior, rogue) std::uint32_t group_size = 0; // members of the group this bot is in; 0 = in none - std::string rule; // the rule the bot's AI fired last (BotAI::last_rule_fired); empty = none + std::string rule; // the rule the bot logic fired last (BotAI::last_rule_fired); empty = none }; enum class ScenarioFailKind : std::uint8_t { Idle, Stray, OutOfBounds, WrongMap, HealerOom, Death, GroupStalled, Wipe, Timeout, SetupFailed, GroupBroken, BossReset, DpsHold, HealerNoRest, SupportMissing }; @@ -138,6 +138,9 @@ struct ScenarioLimits std::uint32_t dps_hold_ms = 0; // Raid: every tank dead is a wipe, whoever else lives. bool tanks_dead_is_wipe = false; + // A boss kill passes the run however many die. The run then stops only on a full wipe, a boss reset, a stall, a timeout or a setup failure; + // every other finding (deaths, mana, holds, strays) is logged as a warning and no longer fails it. + bool kill_is_pass = false; // Support the encounter calls for, as the least number of casts a run that killed the boss must have seen (0 = not checked): hunters' // Tranquilizing Shots on an enrage, curse removals by mages / druids. std::uint32_t min_tranq_shots = 0; @@ -191,6 +194,42 @@ public: return true; } + // A raid whose pass bar is the kill ends on an effective wipe too, not only on the last bot dying: onyxia_full n24 sat to the 1200 s timeout with + // one raider alive after the pull had wiped. Two cases: nobody alive is in combat any more (the rest ran off or hide), and a tenth or less of + // the squad is left for 30 s. + if (limits_.kill_is_pass && entered && !samples.empty()) + { + if (any_combat) + { + fight_seen_ = true; + no_combat_since_ = 0; + no_combat_active_ = false; + } + else if (fight_seen_) + { + if (!no_combat_active_) { no_combat_active_ = true; no_combat_since_ = now_ms; } + if (now_ms - no_combat_since_ >= kEffectiveWipeMs) + { + Fail(ScenarioFailKind::Wipe, "", "the fight is over for the squad: no living member has been in combat for " + std::to_string(kEffectiveWipeMs / 1000u) + " s", now_ms, wipe_reported_); + return true; + } + } + std::size_t alive = 0; + for (ScenarioSample const& s : samples) + if (s.alive) ++alive; + if (fight_seen_ && alive * 10 <= samples.size()) + { + if (!few_alive_active_) { few_alive_active_ = true; few_alive_since_ = now_ms; } + if (now_ms - few_alive_since_ >= kFewAliveMs) + { + Fail(ScenarioFailKind::Wipe, "", std::to_string(alive) + " of " + std::to_string(samples.size()) + " members alive for " + std::to_string(kFewAliveMs / 1000u) + " s", now_ms, wipe_reported_); + return true; + } + } + else + few_alive_active_ = false; + } + ScenarioSample const* tank = nullptr; std::size_t tanks_total = 0; for (ScenarioSample const& s : samples) @@ -367,7 +406,7 @@ public: } else if (!stall_reported_ && now_ms - stall_since_ms_ >= limits_.stall_ms) { - // Where everybody stands and what each AI last decided: the one line that says why a whole group waits. + // Where everybody stands and what each bot logic last decided: the one line that says why a whole group waits. std::string who; for (ScenarioSample const& s : samples) who += (who.empty() ? "" : "; ") + s.name + (s.alive ? "" : " (dead)") + " at " + Trim(s.x) + "," + Trim(s.y) + "," + Trim(s.z) + " hp " + Trim(s.hp_pct) + "%" + @@ -431,9 +470,15 @@ public: // A line for the result that is not a failure (counts the run measured). void NoteInfo(std::string const& line) { tolerated_.push_back(line); } - std::vector const& failures() const { return failures_; } + // The runner is holding the Attack on purpose (the healers' mana wait, itself bounded): the squad standing still is the plan, not a stall. + // MC Ragnaros 2026-10-13 4839bcf3: group_stalled at 121 s, inside the 120 s wait that ends at 140 s. + void NoteDeliberateWait(std::uint32_t now_ms) { stall_since_ms_ = now_ms; } - // What each bot's AI was doing: one line per rule change, the last `per_bot` of each bot, oldest first. A failure that says + std::vector const& failures() const { return failures_; } + // Findings that do not fail a run whose kill is the pass bar (ScenarioLimits::kill_is_pass). + std::vector const& warnings() const { return warnings_; } + + // What each bot's bot logic was doing: one line per rule change, the last `per_bot` of each bot, oldest first. A failure that says // "the healer never healed" is answered by reading this (a movement rule that won every tick, a hold, the heal rules). std::vector Trace(std::size_t per_bot = 25) const { @@ -452,7 +497,8 @@ public: } bool passed(bool goal_reached) const { return goal_reached && failures_.empty(); } // The run cannot usefully go on: enough members have died. - bool terminal() const { return boss_reset_ || (limits_.max_deaths != 0 && deaths_ >= limits_.max_deaths); } + // A run whose pass bar is the kill is never ended by a death count, whatever max_deaths says. + bool terminal() const { return boss_reset_ || (!limits_.kill_is_pass && limits_.max_deaths != 0 && deaths_ >= limits_.max_deaths); } std::uint32_t deaths() const { return deaths_; } // Deaths inside the tolerance, as text lines (they are not failures). std::vector const& tolerated() const { return tolerated_; } @@ -528,10 +574,13 @@ private: }; static constexpr std::uint32_t kBossResetMs = 5000; + static constexpr std::uint32_t kEffectiveWipeMs = 15000; + static constexpr std::uint32_t kFewAliveMs = 30000; static bool IsThreatHold(std::string const& rule) { - return rule == "combat:threat_hold" || rule == "combat:threat_wait_tank" || rule == "raid:threat_hold"; + return rule == "combat:threat_hold" || rule == "combat:threat_wait_tank" || rule == "raid:threat_hold" || + rule == "combat:shield_hold"; } static float Dist2d(float ax, float ay, float bx, float by) { return std::hypot(ax - bx, ay - by); } @@ -563,7 +612,7 @@ private: void Fail(ScenarioFailKind kind, std::string bot, std::string detail, std::uint32_t now_ms) { - // What the bot's AI did in the 90 s before it: the last-25 trace of a long run no longer reaches back to an early failure. + // What the bot's bot logic did in the 90 s before it: the last-25 trace of a long run no longer reaches back to an early failure. if (!bot.empty()) for (auto const& kv : state_) if (kv.second.name == bot) @@ -584,7 +633,13 @@ private: if (e.first + kContextWindowMs >= now_ms && e.first <= now_ms && n++ < kContextLines) line(e); } - failures_.push_back({ kind, std::move(bot), std::move(detail), now_ms }); + // The ends of a run stay failures; the rest are what the bots did wrong on the way to a kill. + bool const ends_run = kind == ScenarioFailKind::Wipe || kind == ScenarioFailKind::Timeout || kind == ScenarioFailKind::SetupFailed || + kind == ScenarioFailKind::GroupBroken || kind == ScenarioFailKind::BossReset || kind == ScenarioFailKind::GroupStalled; + if (limits_.kill_is_pass && !ends_run) + warnings_.push_back({ kind, std::move(bot), std::move(detail), now_ms }); + else + failures_.push_back({ kind, std::move(bot), std::move(detail), now_ms }); } void Fail(ScenarioFailKind kind, std::string bot, std::string detail, std::uint32_t now_ms, bool& once) { @@ -596,10 +651,14 @@ private: ScenarioLimits limits_; std::unordered_map state_; std::vector failures_; + std::vector warnings_; std::unordered_map> stall_anchor_; std::uint32_t stall_since_ms_ = 0; bool stall_reported_ = false; bool wipe_reported_ = false; + bool fight_seen_ = false; + bool no_combat_active_ = false, few_alive_active_ = false; + std::uint32_t no_combat_since_ = 0, few_alive_since_ = 0; std::uint32_t deaths_ = 0; std::vector tolerated_; std::vector contexts_; diff --git a/src/modules/PlayerbotV2/Diagnostics/ScenarioRunner.cpp b/src/modules/PlayerbotV2/Diagnostics/ScenarioRunner.cpp index eab70447ea..bb7d681010 100644 --- a/src/modules/PlayerbotV2/Diagnostics/ScenarioRunner.cpp +++ b/src/modules/PlayerbotV2/Diagnostics/ScenarioRunner.cpp @@ -25,7 +25,9 @@ #include "InstanceLockMgr.h" #include "Item.h" #include "ItemTemplate.h" +#include "DB2Stores.h" #include "Map.h" +#include "MapManager.h" #include "MotionMaster.h" #include "ObjectMgr.h" #include "ObjectAccessor.h" @@ -38,6 +40,7 @@ #include "SpellHistory.h" #include "SpellInfo.h" +#include "TemporarySummon.h" #include "SpellMgr.h" #include @@ -46,6 +49,7 @@ #include #include #include +#include #include #include #include @@ -78,6 +82,7 @@ struct Member std::uint64_t id = 0; bool role_pinned = false; bool kit_learned = false; // the class trainer spells of the squad level are taught (LearnLevelKit) + bool tier_geared = false; // the Molten Core scenarios' Tier 1 gear is on (see the staging step) bool ready = false; }; @@ -89,6 +94,7 @@ struct PullStat std::atomic boss_damage{0}; std::atomic hits{0}; std::uint32_t seconds = 0, casting = 0, moving = 0, held = 0, dead = 0; + std::uint32_t rage_sum = 0, rage_max = 0, rage_ge25 = 0; // a rage user's rage in display units, sampled once a second std::map rules; // last bot rule fired, one count per second }; @@ -102,6 +108,7 @@ struct Run std::uint32_t phase_ms = 0; // time in the current phase std::uint32_t run_ms = 0; // time since the run began (what the failure timestamps count) bool goal_reached = false; + std::uint32_t adds_killed = 0; // ScenarioDef::goal_adds_needed std::string stage_status; // Raids: the goal boss's first spawn, the spot the squad is moved to, and whether the main tank has been ordered on it. bool boss_spawn_known = false; @@ -120,9 +127,13 @@ struct Run std::set engaged_logged; // hostile creatures whose first engagement was logged ([scenario] engaged), capped per run float arrive_x = 0.f, arrive_y = 0.f, arrive_z = 0.f, arrive_o = 0.f; bool order_sent = false; - bool stand_in_detached = false; // the stand-in's AI is off and the runner plays it + std::uint32_t attack_run_ms = 0; // run_ms of the Attack order + bool tank_probe_done = false; // the tanks' state a few seconds into the fight was logged + bool stand_in_detached = false; // the stand-in logic is off and the runner plays it ObjectGuid group_guid; // the squad's group: a member found in another one is put back before the run starts bool group_logged = false; + bool refusal_logged = false; // the map's refusal of the squad's entry is logged once per run + std::string refusal; // its reason, for the failure line std::string arrive_blocker; // why no landing spot was found (the hostile that blocked the nearest candidate) std::uint32_t stage_timeout_ms = kStageTimeoutMs; // Classic::RaidSupportTotal readings (tranq shots, curses removed, formation slot give-ups) when the run began. @@ -331,11 +342,31 @@ bool StageMember(Run& run, Member& m) return false; } + // Molten Core scenarios field the gear the owner's raid wears: the Tier 1 set plus raid pieces up to that tier's item level. The setup + // pipeline's generated gear is a level-60 green/blue kit, so a boss fight on it runs ~4x too long (mc_garr: healers out of mana in a + // fight a T1 squad finishes). The mode override stays for the run (the upkeep regears with it) and is dropped in Finish. + if (!m.tier_geared && def.level >= 60 && std::string_view(def.name).rfind("mc_", 0) == 0) + { + ::Playerbot::V2::Fleet::BotPopulationManager::SetGearModeOverride(id, 2); // Gear::Owned::GearMode::T1 + bool const changed = ::Playerbot::Services::Population().RegearNow(p); + m.tier_geared = true; + TC_LOG_INFO("playerbot.v2", "[scenario] {} {} Tier 1 gear (regear changed items: {})", def.name, m.def.name, changed ? "yes" : "no"); + run.stage_status += fmt::format("{}=t1gear ", m.def.name); + return false; + } + // Food and drink in the bags, as the vendor visit of a bot that had walked here would have left them: the upkeep rules // eat and drink between pulls only from what they carry (Deadmines run 3: no drink line from the priest at all, while // the tank's healer-mana gate held the pull). StockRations(run, p); + // The class supplies a bot's own upkeep tops up (reagents, mana and healing potions, Demonic Runes) and the party buff spells it learns + // from them, so a raid squad starts as the owner's bots do instead of waiting on the idle rule. + { + ::Playerbot::API api(p); + api.restock_class_supplies(); + } + // Full health and mana: a run starts from a rested squad, not from whatever the last one left. p->SetFullHealth(); if (p->GetPowerType() == POWER_MANA) @@ -423,6 +454,56 @@ void ResetLocks(Run& run) run.def->name, in_use); } +// The entry must open a new instance, never the last run's. A run that ends on a failure leaves its boss in combat inside a map that stays +// loaded, and an instance refuses entry while its encounter is in progress (transfer abort 6, "zone in combat": onyxia_full and mc_geddon, n14 +// run 2 and run 4). The squad's group goes back to the instance of its recent owner's lock - temporary locks included, which the lock reset +// above does not touch and cannot drop while a map holds them. So the group's recent instance owner is moved to a member who has no lock +// on the map, or one whose locked instance is no longer loaded, and the recent instance ids are cleared: the entry creates a fresh instance. +void ForgetRecentInstance(Run& run) +{ + std::uint32_t forgotten = 0; + for (Member const& m : run.members) + if (Player* p = Find(m.id)) + { + if (p->GetRecentInstanceId(run.def->map)) + ++forgotten; + p->SetRecentInstance(run.def->map, 0); + } + + MapEntry const* mapEntry = sMapStore.LookupEntry(run.def->map); + Player* leader = run.members.empty() ? nullptr : Find(run.members.front().id); + Group* group = leader ? leader->GetGroup() : nullptr; + if (!mapEntry || !group) + { + TC_LOG_WARN("playerbot.v2", "[scenario] {} no squad group to clear the recent instance of map {} for", run.def->name, run.def->map); + return; + } + + MapDifficultyEntry const* difficulty = sDB2Manager.GetDownscaledMapDifficultyData(run.def->map, group->GetDifficultyID(mapEntry)); + ObjectGuid owner; + std::uint32_t busy = 0; + if (difficulty) + { + MapDb2Entries const entries{ mapEntry, difficulty }; + for (Member const& m : run.members) + { + ObjectGuid const guid = ObjectGuid::Create(m.id); + InstanceLock const* lock = sInstanceLockMgr.FindActiveInstanceLock(guid, entries); + if (!lock || !sMapMgr->FindMap(run.def->map, lock->GetInstanceId())) + { + owner = guid; + break; + } + ++busy; + } + } + if (!owner) + owner = group->GetLeaderGUID(); + group->SetRecentInstance(run.def->map, owner, 0); + TC_LOG_INFO("playerbot.v2", "[scenario] {} recent instance of map {} cleared for the squad ({} of {} members had one), owner {} ({} members skipped: their locked instance is still loaded)", + run.def->name, run.def->map, forgotten, run.members.size(), owner.ToString(), busy); +} + // The goal boss's first spawn in the creature table: the boss room the raid is moved to is found from it. bool FindBossSpawn(Run& run) { @@ -439,6 +520,16 @@ bool FindBossSpawn(Run& run) return true; } } + // No spawn row: a boss a script summons (Ragnaros) is placed from the scenario's lair. + if (run.def->lair_z != 0.f) + { + run.boss_x = run.def->lair_x; + run.boss_y = run.def->lair_y; + run.boss_z = run.def->lair_z; + run.boss_o = run.def->lair_o; + run.boss_spawn_known = true; + return true; + } return false; } @@ -494,7 +585,9 @@ std::size_t ClearRaidTrash(Run& run, Player* viewer) { Creature* c = kv.second; if (!c || !c->IsAlive() || !c->IsHostileTo(viewer) || c->GetEntry() == run.def->arrive_near_entry || c->GetEntry() == run.def->goal_entry || - (run.def->keep_entry && c->GetEntry() == run.def->keep_entry)) + (run.def->keep_entry && c->GetEntry() == run.def->keep_entry) || + // The creatures whose deaths are the goal (Majordomo's Flamewakers) stand for the fight. + (run.def->goal_adds_needed && (c->GetEntry() == run.def->goal_adds_a || c->GetEntry() == run.def->goal_adds_b))) continue; if (boss_formation && c->GetFormation() == boss_formation) continue; @@ -504,9 +597,110 @@ std::size_t ClearRaidTrash(Run& run, Player* viewer) c->KillSelf(false); TC_LOG_INFO("playerbot.v2", "[scenario] {} cleared the trash before placing the raid: {} hostile creatures killed (boss entry {} and its formation left alone)", run.def->name, doomed.size(), run.def->arrive_near_entry); + // What still lives, by entry: n57 onyxia_full run 1 had 18 Onyxian Whelps on the tanks 3 s into the fight that this clearing never listed. + // Count, hostility to the viewer, whether it stands in the boss's formation, and the first one's place. + { + struct Left { std::size_t n = 0; std::size_t hostile = 0; std::size_t inFormation = 0; float x = 0, y = 0, z = 0; }; + std::map left; + for (auto const& kv : map->GetCreatureBySpawnIdStore()) + { + Creature* c = kv.second; + if (!c || !c->IsAlive() || c->GetEntry() == run.def->arrive_near_entry) + continue; + Left& l = left[c->GetEntry()]; + if (!l.n) { l.x = c->GetPositionX(); l.y = c->GetPositionY(); l.z = c->GetPositionZ(); } + ++l.n; + l.hostile += c->IsHostileTo(viewer) ? 1u : 0u; + l.inFormation += (boss_formation && c->GetFormation() == boss_formation) ? 1u : 0u; + } + std::string text; + for (auto const& [entry, l] : left) + text += fmt::format(" [entry {} x{} hostile {} in boss formation {} first at {:.1f},{:.1f},{:.1f}]", entry, l.n, l.hostile, l.inFormation, l.x, l.y, l.z); + TC_LOG_INFO("playerbot.v2", "[scenario] {} living creatures left after the clearing:{}", run.def->name, text.empty() ? std::string(" none") : text); + } return doomed.size(); } +// The goal boss stands alive in its room before the raid is placed. A boss that is dead or waiting out a respawn timer (a lock or a +// persisted raid state from an earlier run, a map that outlived the lock reset) is respawned, and what was found is logged either way: a +// boss scenario measures the fight, so a boss missing at the order is a setup fault to repair here, not a result (mc_geddon on 317cbf20 +// failed setup twice with "not alive within 400 y"). Returns whether a living boss is in the map now (a respawn from a timer happens on +// the map's next update, so the caller re-checks at the order). +bool EnsureBossAlive(Run& run, Player* viewer) +{ + Map* map = viewer->GetMap(); + if (!map || !run.arrive_entry) + return false; + std::uint32_t objects = 0; + Creature* corpse = nullptr; + for (auto const& kv : map->GetCreatureBySpawnIdStore()) + { + Creature* c = kv.second; + if (!c || c->GetEntry() != run.arrive_entry) + continue; + ++objects; + if (c->IsAlive()) + { + TC_LOG_INFO("playerbot.v2", "[scenario] {} boss {} spawn {} is alive at {:.1f},{:.1f},{:.1f}", run.def->name, run.arrive_entry, kv.first, + c->GetPositionX(), c->GetPositionY(), c->GetPositionZ()); + return true; + } + corpse = c; + } + ObjectGuid::LowType spawn_id = 0; + for (auto const& kv : sObjectMgr->GetAllCreatureData()) + if (kv.second.id == run.arrive_entry && kv.second.mapId == run.def->map) + { + spawn_id = kv.first; + break; + } + // A boss the instance script spawns itself (Ragnaros: spawn group 338, manual, spawned when Majordomo is done) has no creature in a fresh + // map: spawn its group, as the script would. + if (!objects && spawn_id) + if (SpawnGroupTemplateData const* group = sObjectMgr->GetSpawnGroupData(SPAWN_TYPE_CREATURE, spawn_id)) + if (group->groupId && (group->flags & SPAWNGROUP_FLAG_MANUAL_SPAWN) && !(group->flags & SPAWNGROUP_FLAG_SYSTEM)) + { + bool const spawned = map->SpawnGroupSpawn(group->groupId, /*ignoreRespawn*/ true, /*force*/ true); + TC_LOG_INFO("playerbot.v2", "[scenario] {} boss {} is in manual spawn group {} ({}): spawned the group: {}", run.def->name, run.arrive_entry, + group->groupId, group->name, spawned); + return false; + } + // A boss with no spawn row (Ragnaros: Majordomo's script summons him at his lair): summon it as the script does, for two hours. + if (!objects && !spawn_id && run.def->lair_z != 0.f) + { + // One the instance script has already summoned (Instance.MoltenCoreSkipRunes raises Ragnaros as soon as a player is inside) is not in the + // spawn store but is alive in the map: use it. A second one on the same spot took the tanks' Attack order (start_attack: InvalidTarget on the + // summon that still carried the script's immune and uninteractible flags) and left the fight unstarted (MC Ragnaros 2026-10-13 d202b196). + for (auto const& [guid, c] : map->GetObjectsStore().Data.FindContainer()) + if (c && c->GetEntry() == run.arrive_entry && c->IsAlive()) + { + TC_LOG_INFO("playerbot.v2", "[scenario] {} boss {} already stands in the map (guid {}) at {:.1f},{:.1f},{:.1f}: not summoning another", run.def->name, + run.arrive_entry, c->GetGUID().GetCounter(), c->GetPositionX(), c->GetPositionY(), c->GetPositionZ()); + return true; + } + Position const lair(run.def->lair_x, run.def->lair_y, run.def->lair_z, run.def->lair_o); + if (Creature* boss = map->SummonCreature(run.arrive_entry, lair, nullptr, std::chrono::hours(2))) + { + // The summoning event normally lifts these; a scenario has no event. + boss->SetImmuneToPC(false); + boss->SetUninteractible(false); + TC_LOG_INFO("playerbot.v2", "[scenario] {} boss {} has no spawn row: summoned at its lair {:.1f},{:.1f},{:.1f}", run.def->name, run.arrive_entry, + boss->GetPositionX(), boss->GetPositionY(), boss->GetPositionZ()); + return true; + } + TC_LOG_WARN("playerbot.v2", "[scenario] {} boss {} has no spawn row and the summon at its lair failed", run.def->name, run.arrive_entry); + return false; + } + time_t const due = spawn_id ? map->GetCreatureRespawnTime(spawn_id) : 0; + TC_LOG_WARN("playerbot.v2", "[scenario] {} boss {} is not alive: {} object(s) in the map, spawn row {}, respawn due in {} s; respawning it", run.def->name, + run.arrive_entry, objects, spawn_id ? std::to_string(spawn_id) : "none", due > GameTime::GetGameTime() ? int64(due - GameTime::GetGameTime()) : 0); + if (corpse) + corpse->Respawn(true); + else if (spawn_id) + map->Respawn(SPAWN_TYPE_CREATURE, spawn_id); + return false; +} + // Where the healers are in the first seconds after the landing and what each is doing (MC Garr 2026-10-10: healers 30 y out from the // landing by t=4 under a Hold, rule unknown): one line per healer per second, 14 rounds: its distance from the landing spot, whether it // moves, whether the Hold is on, and its last bot rule. @@ -586,6 +780,14 @@ void LogEngagements(Run& run, Player* viewer) // A spot 32-56 y from the boss's spawn, on the floor of the same room, in sight of him and kArriveClearance from every hostile creature, // preferring the way he faces (the way in). +// Lava or slime in contact with a body at (x, y, z): the core's own test (in, under, or within a tenth of a yard of the surface). +bool InMagmaContact(Map* map, PhaseShift const& ps, float x, float y, float z) +{ + LiquidData ld; + ZLiquidStatus const st = map->GetLiquidStatus(ps, x, y, z, map_liquidHeaderTypeFlags::Magma | map_liquidHeaderTypeFlags::Slime, &ld); + return (st & MAP_LIQUID_STATUS_IN_CONTACT) != 0; +} + bool PickArrival(Run& run, Player* leader) { Map* map = leader->GetMap(); @@ -620,16 +822,32 @@ bool PickArrival(Run& run, Player* leader) float nearest_blocker_d = 0.f; float const clearance = run.checkpoint ? kCheckpointClearance : kArriveClearance; std::uint32_t path_rejected = 0; - for (float dist : { 40.f, 44.f, 48.f, 52.f, 56.f, 60.f, 64.f, 36.f, 32.f }) + // A boss that aggroes on sight (arrive_min_yards) is approached from outside its reach; the ring widens from there, the default one + // (40 y) keeps its old order. + std::vector rings = { 40.f, 44.f, 48.f, 52.f, 56.f, 60.f, 64.f, 36.f, 32.f }; + if (run.def && run.def->arrive_min_yards > 40.f) + rings = { run.def->arrive_min_yards, run.def->arrive_min_yards + 4.f, run.def->arrive_min_yards + 8.f, run.def->arrive_min_yards + 12.f, + run.def->arrive_min_yards - 4.f }; + for (float dist : rings) for (int k = 0; k < 16; ++k) { int const n = (k + 1) / 2 * (k % 2 ? 1 : -1); // 0, 1, -1, 2, -2, ... float const a = run.boss_o + float(n) * step; float const cx = run.boss_x + std::cos(a) * dist; float const cy = run.boss_y + std::sin(a) * dist; - float const h = map->GetHeight(ps, cx, cy, run.boss_z + 3.0f, true, 12.0f); + float h = map->GetHeight(ps, cx, cy, run.boss_z + 3.0f, true, 12.0f); if (h <= INVALID_HEIGHT || std::fabs(h - run.boss_z) > 6.0f) continue; + // A floor under a lava or slime sheet is not a landing: the raid would burn from the first second (Ragnaros: the search starts 3 y + // over the boss, whose feet are in the lava core, and finds the bed 1.4 y under the surface; six raiders died of it, MC 2026-10-13 + // d202b196). The model floor lying over the sheet is the place to stand; with none, or one that is wet too, the candidate goes. + if (InMagmaContact(map, ps, cx, cy, h + 0.5f)) + { + float const over = map->GetHeight(ps, cx, cy, h + 4.0f, true, 6.0f); + if (over <= INVALID_HEIGHT || over <= h + 0.1f || InMagmaContact(map, ps, cx, cy, over + 0.5f)) + continue; + h = over; + } float hd = 0.f; if (Creature const* c = NearestHostile(map, leader, run.arrive_entry, cx, cy, h, hd); c && hd < clearance) { @@ -716,7 +934,7 @@ void LogGear(Run const& run) } } -// The stand-in stops being a bot: the AI that would route, pull and manage threat is taken off it (what `.playerbot self off` does), +// The stand-in stops being a bot: the bot logic that would route, pull and manage threat is taken off it (what `.playerbot self off` does), // and PlayStandIn drives it. Its identity mark stays, so the group logic still sees a bot-led group and the tank's autopilot runs. void DetachStandIn(Run& run) { @@ -731,7 +949,7 @@ void DetachStandIn(Run& run) ::Playerbot::Services::Registry().unregister_bot(id); } run.stand_in_detached = true; - TC_LOG_INFO("playerbot.v2", "[scenario] {} plays {} like a player: its AI is detached, it follows the tank and attacks the tank's target", run.def->name, p->GetName()); + TC_LOG_INFO("playerbot.v2", "[scenario] {} plays {} like a player: its logic is detached, it follows the tank and attacks the tank's target", run.def->name, p->GetName()); } // One second of a player who only follows the main tank and attacks what the tank attacks (or what is attacking him). @@ -820,14 +1038,16 @@ void ReportPull(Run& run, char const* when) if (it == run.pull.end()) continue; PullStat const& st = it->second; - // The three rules that took the most seconds. + // The eight rules that took the most seconds (a rule counts for the second only when it was the last to fire). std::vector> top; for (auto const& [rule, n] : st.rules) top.emplace_back(n, rule); std::sort(top.begin(), top.end(), [](auto const& a, auto const& b) { return a.first > b.first; }); std::string rules; - for (std::size_t i = 0; i < top.size() && i < 3; ++i) + for (std::size_t i = 0; i < top.size() && i < 8; ++i) rules += fmt::format(" {}={}", top[i].second, top[i].first); + if (st.rage_max) + rules += fmt::format(" | rage avg {} max {} seconds at 25+ {}", st.seconds ? st.rage_sum / st.seconds : 0u, st.rage_max, st.rage_ge25); TC_LOG_INFO("playerbot.v2", "[pull_stats] {} {} {} {} damage={} boss={} hits={} seconds={} casting={} moving={} held={} dead={} rules{}", run.def->name, m.def.name, ClassName(m.def.cls), RoleName(m.def.role), st.damage.load(), st.boss_damage.load(), st.hits.load(), st.seconds, st.casting, st.moving, st.held, st.dead, rules.empty() ? " -" : rules); @@ -868,6 +1088,13 @@ void SamplePull(Run& run) ++st.casting; if (p->isMoving()) ++st.moving; + if (p->GetPowerType() == POWER_RAGE) + { + std::uint32_t const rage = std::uint32_t(p->GetPower(POWER_RAGE) / 10); + st.rage_sum += rage; + st.rage_max = std::max(st.rage_max, rage); + st.rage_ge25 += rage >= 25 ? 1u : 0u; + } if (BotAI* ai = ::Playerbot::Services::Registry().ai(m.id)) { if (ai->holding_position(now)) @@ -883,6 +1110,58 @@ void SamplePull(Run& run) } } +// What the squad stands in at the pull: health and buffs per role, so a scenario that fails can be told from a raid that is under-prepared +// (MC Ragnaros 2026-10-13: healers died to 2000 damage with ~2000 health at the hit). One line per role. +void LogPullState(Run const& run) +{ + // Power Word: Fortitude / Prayer of Fortitude, Mark of the Wild / Gift of the Wild, Arcane Intellect / Brilliance, Blessings and Greater Blessings. + static constexpr uint32 kFortitude[] = { 1243, 1244, 1245, 2791, 10937, 10938, 21562, 21564 }; + static constexpr uint32 kWild[] = { 1126, 5232, 6756, 5234, 8907, 9884, 9885, 21849, 21850 }; + auto has_any = [](Player const* p, auto const& ids) { for (uint32 id : ids) if (p->HasAura(id)) return true; return false; }; + struct Tally { uint32 n = 0, hp = 0, hp_min = ~0u, fort = 0, wild = 0, auras = 0; }; + std::map by_role; + for (Member const& m : run.members) + { + Player* p = Find(m.id); + if (!p || !p->IsAlive()) + continue; + Tally& t = by_role[std::to_string(uint32(m.def.role))]; + ++t.n; + uint32 const hp = uint32(p->GetMaxHealth()); + t.hp += hp; + t.hp_min = std::min(t.hp_min, hp); + t.fort += has_any(p, kFortitude) ? 1u : 0u; + t.wild += has_any(p, kWild) ? 1u : 0u; + t.auras += uint32(p->GetAppliedAuras().size()); + } + for (auto const& [role, t] : by_role) + TC_LOG_INFO("playerbot.v2", "[scenario] {} pull state role {}: {} raiders, max health avg {} (lowest {}), Fortitude {}, Mark of the Wild {}, {} auras each on average", + run.def->name, role, t.n, t.n ? t.hp / t.n : 0u, t.hp_min == ~0u ? 0u : t.hp_min, t.fort, t.wild, t.n ? t.auras / t.n : 0u); +} + +// Where the tanks stand and what they are doing: at the order and a few seconds into the fight (MC Ragnaros 2026-10-13 2318f9d0: the three +// assigned tanks stayed at 80 % with no target for 12 s while a fourth, off-duty druid held the boss). +void LogTankProbe(Run& run, char const* when) +{ + Creature* boss = FindBoss(run); + for (Member const& m : run.members) + { + if (m.def.role != ScenarioRoleKind::Tank) + continue; + Player* p = Find(m.id); + if (!p) + continue; + BotAI* ai = ::Playerbot::Services::Registry().ai(m.id); + char const* rule = ai && ai->last_rule_fired() ? ai->last_rule_fired() : "-"; + Unit* victim = p->GetVictim(); + TC_LOG_INFO("playerbot.v2", "[scenario] {} tank {} {}: {} at {:.1f},{:.1f},{:.1f}, {:.1f} y from the boss, hp {}%, in combat {}, moving {}, rooted {}, victim {}, rule={}", + run.def->name, m.def.name, when, p->IsAlive() ? "alive" : "dead", p->GetPositionX(), p->GetPositionY(), p->GetPositionZ(), + boss ? p->GetDistance(boss) : -1.0f, p->GetMaxHealth() ? int(100 * uint64(p->GetHealth()) / p->GetMaxHealth()) : 0, + p->IsInCombat() ? 1 : 0, p->isMoving() ? 1 : 0, p->HasUnitState(UNIT_STATE_ROOT | UNIT_STATE_STUNNED) ? 1 : 0, + victim ? victim->GetName() : std::string("-"), rule); + } +} + bool IssueAttack(Run& run) { Player* tank = MainTank(run); @@ -895,7 +1174,29 @@ bool IssueAttack(Run& run) : "no living tank to order the attack"); return false; } + LogPullState(run); + // How many of the boss's entry stand within 400 y, and where: a leftover from an earlier run (Ragnaros summoned twice, a lair summon that + // was never cleared) would explain tanks that read 16-20 y from "the boss" at the order and a fight that starts on the wrong one. + { + std::list same; + tank->GetCreatureListWithEntryInGrid(same, run.def->goal_entry, 400.0f); + std::string where; + for (Creature* c : same) + where += fmt::format(" [{} guid {} {} at {:.1f},{:.1f},{:.1f}{}]", c->GetName(), c->GetGUID().GetCounter(), c->IsAlive() ? "alive" : "dead", + c->GetPositionX(), c->GetPositionY(), c->GetPositionZ(), c == boss ? ", the target" : ""); + TC_LOG_INFO("playerbot.v2", "[scenario] {} creature {} ({}) count within 400 y at the order: {}{}", run.def->name, run.def->goal_name, + run.def->goal_entry, same.size(), where); + } run.order_sent = true; + run.attack_run_ms = run.run_ms ? run.run_ms : 1u; + LogTankProbe(run, "at the order"); + // The Hold ends with the order, for everyone: the mana wait renews it every tick for 30 s at a time, so after a long wait the whole squad + // would stand in it for up to half a minute into the fight (MC Ragnaros 2026-10-13 2318f9d0: three assigned tanks with no target and 7 of 24 + // DPS hitting for the first 12 s, the boss on an off-duty druid). The main tank gets the Engage below. + for (Member const& m : run.members) + if (BotAI* ai = ::Playerbot::Services::Registry().ai(m.id)) + if (ai->holding_position(GameTime::GetGameTimeMS())) + ai->exit_manual(); ::Playerbot::API api(tank); ::Playerbot::Result const res = api.start_attack(boss->GetGUID()); if (BotAI* ai = ::Playerbot::Services::Registry().ai(tank->GetGUID().GetCounter())) @@ -905,6 +1206,10 @@ bool IssueAttack(Run& run) } TC_LOG_INFO("playerbot.v2", "[scenario] {} ordered {} onto {} ({}) at {} s, {:.0f} y away (start_attack result {})", run.def->name, tank->GetName(), boss->GetName(), run.def->goal_entry, run.run_ms / 1000u, tank->GetDistance(boss), int(res)); + // A target the server refuses (immune to players, not interactible) is a fault in the setup, not a fight that happens to be quiet. + if (res == ::Playerbot::Result::InvalidTarget) + run.monitor->NoteSetupFailure(run.run_ms, "", fmt::format("{} refused the attack order on {} ({}): the boss is not attackable (immune to players or not interactible)", + tank->GetName(), boss->GetName(), run.def->goal_entry)); return true; } @@ -997,7 +1302,7 @@ void AppendCooldowns(std::string& out, Player* p, KeySpell const (&table)[N]) } } -// One line a member: class, hp, mana / rage / energy, position, the rule its AI fired last, and its key cooldowns. +// One line a member: class, hp, mana / rage / energy, position, the rule its bot logic fired last, and its key cooldowns. std::string MemberState(Member const& m) { Player* p = Find(m.id); @@ -1070,7 +1375,7 @@ void Finish(Run& run, bool timed_out, std::string const& note = {}) ReportPull(run, "final"); if (def.parity) { - // The damage_parity family: the dummy, the stat bonuses and the gear override go; a bot whose AI was taken off for a sweep is logged out + // The damage_parity family: the dummy, the stat bonuses and the gear override go; a bot whose bot logic was taken off for a sweep is logged out // (the next staging logs it in with a fresh one). Parity::End(); if (def.parity != 1 && !run.members.empty()) @@ -1099,13 +1404,16 @@ void Finish(Run& run, bool timed_out, std::string const& note = {}) } bool const pass = run.monitor->passed(run.goal_reached); - std::string text = fmt::format("[scenario] result={} name={} level={} squad={} run_s={} goal={} failures={}", + std::string text = fmt::format("[scenario] result={} name={} level={} squad={} run_s={} goal={} failures={} warnings={}", pass ? "PASS" : "FAIL", def.name, uint32(def.level), run.members.size(), run.run_ms / 1000u, - run.goal_reached ? "reached" : "not_reached", run.monitor->failures().size()); + run.goal_reached ? "reached" : "not_reached", run.monitor->failures().size(), run.monitor->warnings().size()); if (!run.from_key.empty()) text += " from=" + run.from_key; for (ScenarioFailure const& f : run.monitor->failures()) text += fmt::format("\n[scenario] fail kind={} bot={} at_s={} {}", ToString(f.kind), f.bot.empty() ? "-" : f.bot, f.at_ms / 1000u, f.detail); + // What the bots did wrong on the way, in a run whose pass bar is the kill: deaths, mana, holds, strays. + for (ScenarioFailure const& f : run.monitor->warnings()) + text += fmt::format("\n[scenario] warn kind={} bot={} at_s={} {}", ToString(f.kind), f.bot.empty() ? "-" : f.bot, f.at_ms / 1000u, f.detail); for (std::string const& d : run.monitor->tolerated()) text += "\n[scenario] note " + d; // Each failing bot's rule changes in the 90 s before its failure, also on a run that goes on to fail for another reason. @@ -1148,13 +1456,14 @@ void Finish(Run& run, bool timed_out, std::string const& note = {}) g_wave_failed = true; } - // A detached stand-in has no AI to come back: it is logged out, and the next staging logs it in with a fresh one. + // A detached stand-in has no bot logic to come back: it is logged out, and the next staging logs it in with a fresh one. if (run.stand_in_detached) if (Player* si = StandIn(run)) ::Playerbot::Services::SessionMgr().LogoutBot(si->GetGUID()); for (Member const& m : run.members) if (Player* p = Find(m.id)) { + ::Playerbot::V2::Fleet::BotPopulationManager::SetGearModeOverride(m.id, -1); LeaveGroup(p); p->CombatStop(true); if (!p->IsAlive()) @@ -1489,6 +1798,7 @@ static void TickRun(Run& run, std::uint32_t diff_ms) { ResetLocks(run); FormGroup(run); + ForgetRecentInstance(run); for (Member const& m : run.members) if (Player* p = Find(m.id)) ::Playerbot::BotMovement::SafeTeleport(p, run.def->map, run.def->x, run.def->y, run.def->z, run.def->o, 0); @@ -1525,9 +1835,20 @@ static void TickRun(Run& run, std::uint32_t diff_ms) else if (p->IsInCombat()) why = "in combat"; else { - why = "teleport refused"; - if (::Playerbot::BotMovement::SafeTeleport(p, run.def->map, run.def->x, run.def->y, run.def->z, run.def->o, 0)) - why = "teleport resent"; + why = "teleport resent"; + if (!::Playerbot::BotMovement::SafeTeleport(p, run.def->map, run.def->x, run.def->y, run.def->z, run.def->o, 0)) + { + // The map's own entry check names the refusal (instance full, encounter in progress, another group's instance, + // the hourly instance limit, access requirements): the bare "refused" hid it for three runs. + TransferAbortParams const denied = Map::PlayerCannotEnter(run.def->map, p); + run.refusal = fmt::format("transfer abort reason {} (arg {})", uint32(denied.Reason), uint32(denied.Arg)); + why = denied ? run.refusal.c_str() : "teleport refused, the entry check passed"; + if (!run.refusal_logged) + { + run.refusal_logged = true; + TC_LOG_WARN("playerbot.v2", "[scenario] {} {} cannot enter map {}: {}", run.def->name, m.def.name, run.def->map, run.refusal); + } + } } } missing += fmt::format("{}{}(level {}, {}, map {})", missing.empty() ? "" : ", ", m.def.name, p ? uint32(p->GetLevel()) : 0u, why, @@ -1572,6 +1893,7 @@ static void TickRun(Run& run, std::uint32_t diff_ms) { run.trash_cleared = true; ClearRaidTrash(run, leader); + EnsureBossAlive(run, leader); } if (!leader || !PickArrival(run, leader)) { @@ -1619,6 +1941,10 @@ static void TickRun(Run& run, std::uint32_t diff_ms) p->SetFullHealth(); if (p->GetPowerType() == POWER_MANA) p->SetPower(POWER_MANA, p->GetMaxPower(POWER_MANA)); + // A rested squad also has its long cooldowns back: a raid waits them out between pulls, and a run started minutes + // after the last one inherited its Innervates (6 min) and mana potions (n10 run 4: both druids dry at 125 s with + // the Innervate still down from run 3). + p->GetSpellHistory()->ResetAllCooldowns(); } // A raid's squad holds its place until the Attack, as bots do for a human owner who has not given it yet. A dungeon // checkpoint is bot-led from the first second: no Hold, no ordered attack. @@ -1671,11 +1997,39 @@ static void TickRun(Run& run, std::uint32_t diff_ms) for (Member const& m : run.members) if (BotAI* ai = ::Playerbot::Services::Registry().ai(m.id)) ai->enter_manual(BotAI::OwnerCommand::Hold, ObjectGuid::Empty, GameTime::GetGameTimeMS(), 30000u); + run.monitor->NoteDeliberateWait(run.run_ms); if (run.run_ms - run.mana_wait_log_ms >= 10000u || !run.mana_wait_log_ms) { run.mana_wait_log_ms = run.run_ms ? run.run_ms : 1u; TC_LOG_INFO("playerbot.v2", "[scenario] {} the attack waits for the healers' mana: lowest {}% (needs {}%), {} s past the order time", run.def->name, lowest, kPullManaPct, (run.run_ms - run.def->order_delay_ms) / 1000u); + // Who the wait is on besides the healers: the least healthy member and the three emptiest mana pools, with what each bot logic last + // decided (MC Ragnaros 2026-10-13 4839bcf3: hunters, mages and warlocks at 4-16 % mana before any fight). + std::string hurt, dry; + int hurt_pct = 101; + std::vector> pools; + for (Member const& m : run.members) + { + Player* p = Find(m.id); + if (!p || !p->IsAlive()) + continue; + BotAI* ai = ::Playerbot::Services::Registry().ai(m.id); + char const* rule = ai && ai->last_rule_fired() ? ai->last_rule_fired() : "-"; + int const hp = p->GetMaxHealth() ? int(100 * uint64(p->GetHealth()) / p->GetMaxHealth()) : 100; + if (hp < hurt_pct) + { + hurt_pct = hp; + hurt = fmt::format("{} {}% rule={}", m.def.name, hp, rule); + } + if (p->GetPowerType() == POWER_MANA && p->GetMaxPower(POWER_MANA)) + pools.emplace_back(int(100 * uint64(p->GetPower(POWER_MANA)) / p->GetMaxPower(POWER_MANA)), + fmt::format("{} {}% rule={}", m.def.name, int(100 * uint64(p->GetPower(POWER_MANA)) / p->GetMaxPower(POWER_MANA)), rule)); + } + std::sort(pools.begin(), pools.end()); + for (size_t i = 0; i < pools.size() && i < 3; ++i) + dry += (dry.empty() ? "" : "; ") + pools[i].second; + TC_LOG_INFO("playerbot.v2", "[scenario] {} wait detail: least healthy {}; emptiest mana {}", run.def->name, hurt.empty() ? "-" : hurt, + dry.empty() ? "-" : dry); } attack_due = false; } @@ -1685,6 +2039,11 @@ static void TickRun(Run& run, std::uint32_t diff_ms) Finish(run, false); return; } + if (run.order_sent && !run.tank_probe_done && run.run_ms >= run.attack_run_ms + 6000u) + { + run.tank_probe_done = true; + LogTankProbe(run, "6 s into the fight"); + } PlayStandIn(run); LogLanding(run); SamplePull(run); @@ -1695,7 +2054,8 @@ static void TickRun(Run& run, std::uint32_t diff_ms) std::vector samples; Sample(run, samples); bool terminal = run.monitor->Feed(run.run_ms, samples, /*entered*/ true); - if (run.def->arrive_near_entry) + // A boss that yields when the goal is met (Majordomo evades with his adds dead) is not a reset. + if (run.def->arrive_near_entry && !run.goal_reached) { ScenarioBossSample bs; if (Creature* boss = FindBoss(run)) @@ -1779,12 +2139,31 @@ void NoteDamage(Unit* attacker, Unit* victim, std::int32_t amount) } } -void NoteCreatureKilled(std::uint32_t map, std::uint32_t entry) +void NoteCreatureKilled(std::uint32_t map, std::uint32_t entry, bool tapped) { // Squads on the same map do not exist side by side (a wave holds distinct dungeons), so the map and the entry name the run. for (auto const& r : g_runs) - if (r->phase == Phase::Run && r->def && r->def->goal == ScenarioGoalKind::KillCreature && map == r->def->map && entry == r->def->goal_entry) + { + if (r->phase != Phase::Run || !r->def || r->def->goal != ScenarioGoalKind::KillCreature || map != r->def->map) + continue; + // A death the raiders had no part in is no kill (bwl_razorgore n24 2026-10-14 passed with Razorgore at 94% and the raid wiped), and + // neither is one after the whole squad is dead. + if (!tapped) + continue; + bool any_alive = false; + for (Member const& m : r->members) + if (Player* p = Find(m.id); p && p->IsInWorld() && p->IsAlive()) + { + any_alive = true; + break; + } + if (!any_alive) + continue; + if (entry == r->def->goal_entry) r->goal_reached = true; + else if (r->def->goal_adds_needed && (entry == r->def->goal_adds_a || entry == r->def->goal_adds_b) && ++r->adds_killed >= r->def->goal_adds_needed) + r->goal_reached = true; + } } std::string Status() diff --git a/src/modules/PlayerbotV2/Diagnostics/ScenarioRunner.h b/src/modules/PlayerbotV2/Diagnostics/ScenarioRunner.h index 433b25679d..623401ac08 100644 --- a/src/modules/PlayerbotV2/Diagnostics/ScenarioRunner.h +++ b/src/modules/PlayerbotV2/Diagnostics/ScenarioRunner.h @@ -41,7 +41,7 @@ void Tick(std::uint32_t diff_ms); // From Module::OnDeath: a player died / a creature died. void NoteBotDeath(std::uint64_t guid_low, ScenarioDeath death); -void NoteCreatureKilled(std::uint32_t map, std::uint32_t entry); +void NoteCreatureKilled(std::uint32_t map, std::uint32_t entry, bool tapped); // tapped: the raiders had a share in the kill (a script's KillSelf or a despawn is no kill) // From Module::OnDamageTaken: every hit dealt; counted for the squad's raiders (and their pets) from the boss's first combat. void NoteDamage(Unit* attacker, Unit* victim, std::int32_t amount); diff --git a/src/modules/PlayerbotV2/Diagnostics/WedgeWatchdog.cpp b/src/modules/PlayerbotV2/Diagnostics/WedgeWatchdog.cpp index 1efec1d9b7..acbb707668 100644 --- a/src/modules/PlayerbotV2/Diagnostics/WedgeWatchdog.cpp +++ b/src/modules/PlayerbotV2/Diagnostics/WedgeWatchdog.cpp @@ -171,7 +171,7 @@ WedgeInfo ClassifyWedge(BotAI& ai, BotId id, uint32 stationary_for_ms, } } // path_blocked_count() is the authoritative live counter; fall back to the - // snapshot copy if the AI hasn't been re-read this tick. + // snapshot copy if the bot logic hasn't been re-read this tick. const uint32 path_blocks = ai.path_blocked_count() > 0 ? ai.path_blocked_count() : snap_path_blocks; diff --git a/src/modules/PlayerbotV2/Fleet/AreaCap.h b/src/modules/PlayerbotV2/Fleet/AreaCap.h new file mode 100644 index 0000000000..f67a72ccca --- /dev/null +++ b/src/modules/PlayerbotV2/Fleet/AreaCap.h @@ -0,0 +1,61 @@ +// A cap on how many world bots may stand in one area. Placement refuses a spot that is already full, and a periodic pass moves the +// bots beyond the cap out of a crowd that formed anyway (many bots after the same quest mob, a sleeping roster saved in one camp). +// Pure rules, tested in tests/game/ClassicAreaCap.cpp. +#pragma once + +#include +#include +#include +#include + +namespace Playerbot::V2::Fleet +{ + +struct CrowdPoint +{ + std::uint64_t id = 0; + float x = 0.0f, y = 0.0f; + std::uint32_t cap = 0; // how many may stand within the radius of this one (outdoors fewer than in a capital) +}; + +inline std::uint32_t CountWithin(std::vector const& pts, float x, float y, float radius) +{ + std::uint32_t n = 0; + float const r2 = radius * radius; + for (CrowdPoint const& p : pts) + { + float const dx = p.x - x, dy = p.y - y; + if (dx * dx + dy * dy <= r2) ++n; + } + return n; +} + +// The bots to move out, at most `max_out`: walking the bots in id order, one stays while fewer than its cap are already kept within +// the radius of it; the rest are extras. Deterministic, so the same crowd names the same extras on each pass until they have moved. +inline std::vector ExcessBots(std::vector const& pts, float radius, std::size_t max_out) +{ + std::vector order = pts; + for (std::size_t i = 1; i < order.size(); ++i) // insertion sort by id: the lists are a few hundred + for (std::size_t j = i; j > 0 && order[j].id < order[j - 1].id; --j) + std::swap(order[j], order[j - 1]); + std::vector kept; + std::vector out; + for (CrowdPoint const& p : order) + { + if (p.cap == 0 || CountWithin(kept, p.x, p.y, radius) < p.cap) + kept.push_back(p); + else if (out.size() < max_out) + out.push_back(p.id); + else + kept.push_back(p); // not moved this pass: it still stands there + } + return out; +} + +// May one more bot be put at (x, y)? The crowd already within the radius must be below the cap. +inline bool RoomFor(std::vector const& pts, float x, float y, float radius, std::uint32_t cap) +{ + return cap == 0 || CountWithin(pts, x, y, radius) < cap; +} + +} // namespace Playerbot::V2::Fleet diff --git a/src/modules/PlayerbotV2/Fleet/BotComposition.cpp b/src/modules/PlayerbotV2/Fleet/BotComposition.cpp index 7b17008fe5..7895b54428 100644 --- a/src/modules/PlayerbotV2/Fleet/BotComposition.cpp +++ b/src/modules/PlayerbotV2/Fleet/BotComposition.cpp @@ -120,7 +120,8 @@ bool IsVanillaCombo(uint8 race, uint8 cls) case RACE_NIGHTELF: mask = bit(CLASS_WARRIOR) | bit(CLASS_HUNTER) | bit(CLASS_ROGUE) | bit(CLASS_PRIEST) | bit(CLASS_DRUID); break; case RACE_GNOME: mask = bit(CLASS_WARRIOR) | bit(CLASS_ROGUE) | bit(CLASS_MAGE) | bit(CLASS_WARLOCK); break; case RACE_ORC: mask = bit(CLASS_WARRIOR) | bit(CLASS_HUNTER) | bit(CLASS_ROGUE) | bit(CLASS_SHAMAN) | bit(CLASS_WARLOCK); break; - case RACE_UNDEAD_PLAYER: mask = bit(CLASS_WARRIOR) | bit(CLASS_ROGUE) | bit(CLASS_PRIEST) | bit(CLASS_MAGE) | bit(CLASS_WARLOCK); break; + // Undead Paladin is a Classic 1.60 combination (CharBaseInfo; sql/custom/world/2026_09_30_00_world_classic_undead_paladin.sql). + case RACE_UNDEAD_PLAYER: mask = bit(CLASS_WARRIOR) | bit(CLASS_PALADIN) | bit(CLASS_ROGUE) | bit(CLASS_PRIEST) | bit(CLASS_MAGE) | bit(CLASS_WARLOCK); break; case RACE_TAUREN: mask = bit(CLASS_WARRIOR) | bit(CLASS_HUNTER) | bit(CLASS_SHAMAN) | bit(CLASS_DRUID); break; case RACE_TROLL: mask = bit(CLASS_WARRIOR) | bit(CLASS_HUNTER) | bit(CLASS_ROGUE) | bit(CLASS_PRIEST) | bit(CLASS_SHAMAN) | bit(CLASS_MAGE); break; // Classic 1.60 Skyborne: the combinations of CharBaseInfo.db2, from Fleet/SkyborneIsle.h diff --git a/src/modules/PlayerbotV2/Fleet/BotGroupBuilder.cpp b/src/modules/PlayerbotV2/Fleet/BotGroupBuilder.cpp index 11829bc1e9..e8fdfea0c5 100644 --- a/src/modules/PlayerbotV2/Fleet/BotGroupBuilder.cpp +++ b/src/modules/PlayerbotV2/Fleet/BotGroupBuilder.cpp @@ -50,7 +50,7 @@ enum RoleSlot : uint8 { kRoleTank = 0, kRoleHealer = 1, kRoleDps = 2 }; // Pull a bot's role affinity from its BotAI archetype (world-thread read of // the authoritative BotArchetype — PickCandidates runs on the world thread // via the bus DrainAsync). Returns {0,0,1} (pure DPS) when the bot has no -// registered AI, so an unmanaged candidate counts as DPS-only and never +// registered bot logic, so an unmanaged candidate counts as DPS-only and never // pre-empts a tank/healer slot. std::array RoleAffinityOf(uint64 bot_low) { diff --git a/src/modules/PlayerbotV2/Fleet/BotIdentityRegistry.h b/src/modules/PlayerbotV2/Fleet/BotIdentityRegistry.h index 154710931b..26a2f05317 100644 --- a/src/modules/PlayerbotV2/Fleet/BotIdentityRegistry.h +++ b/src/modules/PlayerbotV2/Fleet/BotIdentityRegistry.h @@ -29,7 +29,7 @@ public: // Transient mark: adds to the in-memory set only, NO DB write. // Used by .playerbot self on so a real human character is treated as - // an AI bot for the duration of the session, but NOT persisted across + // an bot logic bot for the duration of the session, but NOT persisted across // restart — otherwise BotPopulationManager::LoginExisting would grab // the character on next boot and the human couldn't log in. // The corresponding unmark just removes from memory; if the same id diff --git a/src/modules/PlayerbotV2/Fleet/BotNamePool.cpp b/src/modules/PlayerbotV2/Fleet/BotNamePool.cpp index 8a315ccd8d..9782177dbb 100644 --- a/src/modules/PlayerbotV2/Fleet/BotNamePool.cpp +++ b/src/modules/PlayerbotV2/Fleet/BotNamePool.cpp @@ -68,7 +68,7 @@ NameEntry PopRandom_locked(std::vector& v) std::string const& SharedDb() { static std::string const db = - sConfigMgr->GetStringDefault("Playerbot.SharedDatabase", "playerbot"); + sConfigMgr->GetStringDefault("Playerbot.SharedDatabase", "playerbot", true); return db; } diff --git a/src/modules/PlayerbotV2/Fleet/BotPopulationManager.cpp b/src/modules/PlayerbotV2/Fleet/BotPopulationManager.cpp index adacd4b5da..98340f1473 100644 --- a/src/modules/PlayerbotV2/Fleet/BotPopulationManager.cpp +++ b/src/modules/PlayerbotV2/Fleet/BotPopulationManager.cpp @@ -2,9 +2,11 @@ #include "../Util/SlowCall.h" #include "BotPopulationManager.h" #include "ClassicSpec.h" +#include "SoakAnchors.h" #include "CompanionRole.h" #include "BotQueueFiller.h" #include "InstanceGroupCap.h" +#include "InstanceEntry.h" #include "RaidSubgroupPlan.h" #include "BotSetupPipeline.h" #include "WorldBotSpawner.h" @@ -101,7 +103,7 @@ void WarnOversizedInstanceGroups(uint32 now_ms) if (open_world) { // Open world: any owner whose companions out exceed the cap, grouped with them or not (a player who logged in - // with 9 companions still online from before the cap, Karrz 2026-10-08). + // with 9 companions still online from before the cap, playtest 2026-10-08). // Companions above the open-world cap (called in an instance, or relogged with a big group) are dismissed once // the owner has stood outside for kTrimGraceMs. Invited world bots are not owned, so they are never trimmed. uint32 const open_cap = InstanceGroupCapFor(p, nullptr); @@ -377,7 +379,7 @@ bool IsAlliedRace(uint32 race) // Bots that must run the starter-only rescue (complete the starter quest chain // + relocate to capital, kept at start level) even with no distribution bucket, // because they're created in ISOLATED / phased starter zones whose scripted -// intro grants essential class/racial abilities the bot AI can't earn by normal +// intro grants essential class/racial abilities the bot bot logic can't earn by normal // questing: // - Death Knight → Acherus (map 609) // - Demon Hunter → Mardum (map 1481) @@ -1134,6 +1136,12 @@ void BotPopulationManager::CompanionUpkeep(BotId id, Player* p) GrantCompanionStarterPet(id, p); // A companion geared before per-bot gear variety wears the same top pick per slot as every other bot of its class // and level; it gets its one re-roll here (or in FinishCompanionSetup when it is called), whichever comes first. + // A level-cap companion that has had the first re-roll but not the raid-gear variety pass gets it here (RerollCompanionGear). + if (Services::Owners().GearVaried(id) && !Services::Owners().GearVariedRaid(id) && Gear::RaidGearActive(p->GetLevel())) + { + uint32 changed = 0; + RerollCompanionGear(p, changed); + } if (!Services::Owners().GearVaried(id)) { uint32 changed = 0; @@ -1186,7 +1194,7 @@ void BotPopulationManager::DrainCompanionDeletes() ++it; continue; } - // Same sequence as `.playerbot delete`: forget the AI and the bot mark before the character row goes. + // Same sequence as `.playerbot delete`: forget the bot logic and the bot mark before the character row goes. if (Services::Registry().has(id)) { Services::Scheduler().unregister_bot(id); @@ -1227,7 +1235,7 @@ Role BotPopulationManager::ApplyCompanionRole(Player* bot, Role requested, char : choice.source == Fleet::CompanionRoleSource::SpecHybrid ? "spec_hybrid" : "spec"; if (!choice.pin) { - // Not chosen by anybody: the AI keeps reading the live talents, the quota fill still sees it as unset, nothing is stored. + // Not chosen by anybody: the bot logic keeps reading the live talents, the quota fill still sees it as unset, nothing is stored. BotAI* ai = Services::Registry().ai(id); if (ai && ai->role_override() != Role::Unknown) ai->set_role_override(Role::Unknown); @@ -1323,7 +1331,7 @@ void BotPopulationManager::DrainCompanionSetups() BotId const id = it->first; PendingCompanion const pending = it->second; Player* bot = ObjectAccessor::FindConnectedPlayer(ObjectGuid::Create(id)); - // Wait until the bot is in the world with its AI registered (Module::OnPlayerLogin). + // Wait until the bot is in the world with its bot logic registered (Module::OnPlayerLogin). if (!bot || !bot->IsInWorld() || !Services::Registry().has(id)) { // queued_ms is getMSTime(); OnWorldTick's now_ms counts from the module's first tick, so compare on one clock. @@ -1523,7 +1531,7 @@ void BotPopulationManager::FinishCompanionSetup(Player* bot, Player* owner, uint uint32 const riding = api.learn_riding_free(); // The role the owner asked for (`.bot add healer`), else the one stored with the companion (`.bot call`, a - // relog), else what its talents say; pinned as the AI role and the virtual spec, and stored. Before the talent step, + // relog), else what its talents say; pinned as the bot logic role and the virtual spec, and stored. Before the talent step, // which spends the points down the pinned spec's build. ApplyCompanionRole(bot, Role(role_value), "setup"); ::Playerbot::Result const talents = bot->GetLevel() >= 10 ? api.apply_starter_talents() : ::Playerbot::Result::Ok; @@ -1595,14 +1603,24 @@ void BotPopulationManager::FinishCompanionSetup(Player* bot, Player* owner, uint { // Bring it to the owner (same map: a near teleport; otherwise a map change), straight into its place. // Same angle convention as the follow it gets next (MoveFollow: relative to the owner's facing). - float x, y, z; - owner->GetNearPoint(bot, x, y, z, slot_offset.distance, owner->GetOrientation() + slot_offset.angle_radians); - ::Playerbot::BotMovement::SafeTeleport(bot, owner->GetMapId(), x, y, z, owner->GetOrientation(), 0); - // A level 10+ hunter's pet, once ever. Mid map change it is not in the world yet: CompanionUpkeep grants it then. - GrantCompanionStarterPet(id, bot); + // Into the owner's instance the companion joins the group first: the door checks look at the group's instance, and a + // stale lock on another instance is dropped before the port (Fleet/InstanceEntry.h). + bool const joinFirst = owner->GetMap() && owner->GetMap()->IsDungeon() && !alreadyGrouped; + if (joinFirst) + joinFailure = JoinOwnerGroup(owner, bot); + if (joinFailure.empty()) + { + float x, y, z; + owner->GetNearPoint(bot, x, y, z, slot_offset.distance, owner->GetOrientation() + slot_offset.angle_radians); + Fleet::PrepareInstanceEntry(bot, owner->GetMapId()); + ::Playerbot::BotMovement::SafeTeleport(bot, owner->GetMapId(), x, y, z, owner->GetOrientation(), 0); + // A level 10+ hunter's pet, once ever. Mid map change it is not in the world yet: CompanionUpkeep grants it then. + GrantCompanionStarterPet(id, bot); - // Group with the owner (see JoinOwnerGroup). - joinFailure = JoinOwnerGroup(owner, bot); + // Group with the owner (see JoinOwnerGroup). + if (!joinFirst) + joinFailure = JoinOwnerGroup(owner, bot); + } } bool const grouped = joinFailure.empty(); @@ -1682,7 +1700,7 @@ static int32 OwnerGearCap(Player const* bot) // where the slot is empty or the pick scores at least kRaidUpgradeRatio above the worn piece (Gear::ScoreItemRaid, the // same score the generator ranks by), so existing gear is only ever upgraded. A two-hander replaces a mainhand + offhand // pair only when it beats their combined score. Logs one "[gear]" line. Returns the number of slots changed. World thread. -static uint32 RaidRegearPass(Player* p, bool& refused_any, bool only_over_cap = false, bool reroll_all = false) +static uint32 RaidRegearPass(Player* p, bool& refused_any, bool only_over_cap = false, bool reroll_all = false, bool vary = false) { refused_any = false; uint8 const lvl = p->GetLevel(); @@ -1703,6 +1721,11 @@ static uint32 RaidRegearPass(Player* p, bool& refused_any, bool only_over_cap = ctx.ilvl_cap = OwnerGearCap(p); } std::vector const picks = Gear::GenerateGearFor(ctx); + // Variety (an owned level-cap companion, once): the generator picks among the best few pieces by the bot's guid, but the regear only + // ever upgraded, so companions geared before variety all still wear the same top piece per slot. A worn piece goes for the bot's own + // pick when the pick is the same quality or better and scores within 5% of it; a tier-set or best-in-slot choice is the owner's. + bool const vary_ok = vary && !ctx.world_bot() && !Gear::Owned::IsCapMode(ctx.gear_mode); + constexpr float kVaryFloor = 0.95f; auto slot_score = [&](Item const* it, uint8 slot) -> int32 { @@ -1743,7 +1766,10 @@ static uint32 RaidRegearPass(Player* p, bool& refused_any, bool only_over_cap = { Item const* mh = p->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND); if (mh && mh->GetTemplate() && mh->GetTemplate()->GetInventoryType() == INVTYPE_2HWEAPON) + { + refused_any = refused_any || gtpl->GetInventoryType() == INVTYPE_SHIELD; // the second pass, once the one-hander is on continue; + } } int32 const pick_score = ::Playerbot::Gear::ScoreItemRaid(gtpl, cls, ctx.spec, lvl, g.slot); Item* off_for_2h = nullptr; @@ -1768,7 +1794,16 @@ static uint32 RaidRegearPass(Player* p, bool& refused_any, bool only_over_cap = // An off hand that is not a weapon on a class that must have one (rogue, non-protection warrior, hunter, enhancement shaman) goes for any weapon pick. bool const dead_offhand = ::Playerbot::Gear::OffhandMustBeWeapon(cls, ctx.spec) && g.slot == EQUIPMENT_SLOT_OFFHAND && cur->GetTemplate() && cur->GetTemplate()->GetClass() != ITEM_CLASS_WEAPON && gtpl->GetClass() == ITEM_CLASS_WEAPON; - bool const better = tier_pick || worn_pvp || dead_offhand || worn_over || (reroll_all && ctx.world_bot()) || (cur_score <= 0 ? pick_score > cur_score + // A protection tank's hands: a two-hander in the main hand goes for the one-hander pick, and an off hand that is not a shield + // goes for the shield pick, whatever they score (n43 onyxia_full: two of three protection warriors in the Tier 1 gear had no + // shield, no Shield Slam and a third of the armor; the 10 % upgrade rule kept the two-hander). + bool const shield_tank = ctx.spec == 73 || ctx.spec == 66; + bool const shield_fix = shield_tank && cur->GetTemplate() && + ((g.slot == EQUIPMENT_SLOT_MAINHAND && cur->GetTemplate()->GetInventoryType() == INVTYPE_2HWEAPON && gtpl->GetInventoryType() != INVTYPE_2HWEAPON) || + (g.slot == EQUIPMENT_SLOT_OFFHAND && gtpl->GetInventoryType() == INVTYPE_SHIELD && cur->GetTemplate()->GetInventoryType() != INVTYPE_SHIELD)); + bool const vary_swap = vary_ok && cur_score > 0 && !off_for_2h && cur->GetTemplate() && + gtpl->GetQuality() >= cur->GetTemplate()->GetQuality() && float(pick_score) >= float(cur_score) * kVaryFloor; + bool const better = shield_fix || vary_swap || tier_pick || worn_pvp || dead_offhand || worn_over || (reroll_all && ctx.world_bot()) || (cur_score <= 0 ? pick_score > cur_score : float(pick_score) >= float(cur_score) * Gear::kRaidUpgradeRatio); if (!better) continue; @@ -1852,6 +1887,19 @@ BotPopulationManager::RerollResult BotPopulationManager::RerollCompanionGear(Pla { bool refused = false; changed_slots = RaidRegearPass(p, refused); + // Once per companion: swap the clone-top pieces for the bot's own near-equal picks. + bool const first_vary = !Services::Owners().GearVariedRaid(id); + if (first_vary) + { + bool refused_v = false; + uint32 const varied = RaidRegearPass(p, refused_v, /*only_over_cap=*/false, /*reroll_all=*/false, /*vary=*/true); + changed_slots += varied; + if (!refused_v) + { + Services::Owners().MarkGearVariedRaid(id); + TC_LOG_INFO("playerbot.v2", "[gear_vary] {}: {} piece(s) swapped for its own picks", p->GetName(), varied); + } + } if (EnsureShieldTankWeapon(p)) ++changed_slots; return RerollResult::Done; @@ -1967,7 +2015,7 @@ BotPopulationManager::RerollResult BotPopulationManager::RerollCompanionGear(Pla return RerollResult::Done; } -// Karrz 2026-10-08 (MC raid): WSG bots (Dascard, Nadoc, Brahad) sat in his raid group while he was dead in Molten Core, and their combat in +// playtest 2026-10-08 (MC raid): WSG bots (Dascard, Nadoc, Brahad) sat in his raid group while he was dead in Molten Core, and their combat in // the battleground greyed out his Release Spirit ("a member of your group is in combat"). A pool / JIT bot has no business in a human's // regular group while it is in a battleground: its battleground group is the BG group, and an earlier group (the "original group" a // battleground restores on leaving, or one it never left) is dropped here. Owned companions keep their owner's group. Every 10 s. @@ -2003,7 +2051,7 @@ void BotPopulationManager::BgGroupHygiene(uint32 now_ms) }); } -// Karrz 2026-10-08: world, pool and BG bots are T1 at most and mostly blue; bots made before that cap (or logged in with a worn T3 piece) +// playtest 2026-10-08: world, pool and BG bots are T1 at most and mostly blue; bots made before that cap (or logged in with a worn T3 piece) // kept their gear until the 5 minute sweep, and then only 25 per sweep. Every 15 s this walks the online bots, and any bot without an owner // that wears a piece above the world cap (or an epic beyond its share) is regeared right away under the world rules, up to 8 bots a pass. // Covers login (the next pass) and BG entry (the bot is online and in the world by then). Logs one [gear] scrub line per bot. @@ -3266,12 +3314,12 @@ bool BotPopulationManager::IsAmbientBot(BotId id, Player const* p) const auto it = pipeline_row_cache_.find(uint64(id)); // A battleground JIT bot (jit tag still set) belongs to the queue filler, not to the world spawner. return it != pipeline_row_cache_.end() && it->second.dist_level > 0 && it->second.jit_tag.empty() - && !IsPlayerOwnedAlt(id, p); + && !IsPlayerOwnedAlt(id, p) && !(p && IsSoakAnchor(p->GetName())); // a soak anchor stands in for a player, it is not a resident } bool BotPopulationManager::AmbientFleetEnabled() { - return Services::Config().population_total_target() > 0 || sConfigMgr->GetBoolDefault("Playerbot.World.Enable", false); + return Services::Config().population_total_target() > 0 || sConfigMgr->GetBoolDefault("Playerbot.World.Enable", false, true); } std::string BotPopulationManager::WorldReport() const { return world_spawner_->Report(); } @@ -4210,7 +4258,7 @@ void BotPopulationManager::SeedBgMatches(uint32 now_ms) // Population 0 means owner bots only: no ambient fleet, so no ambient // matches either (each seed JIT-creates and logs in a full BG roster). if (!AmbientFleetEnabled()) return; - const int32 matches_cap = sConfigMgr->GetIntDefault("Playerbot.Bg.AutoSeed.Matches", 0); + const int32 matches_cap = sConfigMgr->GetIntDefault("Playerbot.Bg.AutoSeed.Matches", 0, true); if (matches_cap <= 0) return; constexpr uint32 kSeedIntervalMs = 3u * 60u * 1000u; if (last_bg_seed_ms_ && (now_ms - last_bg_seed_ms_) < kSeedIntervalMs) return; @@ -4287,7 +4335,7 @@ void BotPopulationManager::SeedBgMatches(uint32 now_ms) static std::vector seed_types; { std::vector wanted; - std::string const list = sConfigMgr->GetStringDefault("Playerbot.Bg.AutoSeed.Types", ""); + std::string const list = sConfigMgr->GetStringDefault("Playerbot.Bg.AutoSeed.Types", "", true); if (list.empty()) wanted = { 2, 3, 1 }; else @@ -4324,7 +4372,7 @@ void BotPopulationManager::SeedBgMatches(uint32 now_ms) // can be changed via `.reload config` without a restart. Useful BMLs: // WSG 1014, AB 1018, EotS 7, Twin Peaks 108, BfG 120, Kotmogu 699. const int32 forced_bg_type = - sConfigMgr->GetIntDefault("Playerbot.Bg.AutoSeed.ForceType", 0); + sConfigMgr->GetIntDefault("Playerbot.Bg.AutoSeed.ForceType", 0, true); const uint16 bg_type = forced_bg_type > 0 ? uint16(forced_bg_type) : seed_types[bg_seed_rotation_ % seed_types.size()]; @@ -4352,7 +4400,7 @@ void BotPopulationManager::SeedArenaMatches(uint32 now_ms) // `Playerbot.Bg.AutoSeed.Arena` = desired number of concurrent seeded // skirmishes (0 = disabled). One skirmish needs both factions' groups. if (!AmbientFleetEnabled()) return; // owner bots only, see SeedBgMatches - const int32 arena_cap = sConfigMgr->GetIntDefault("Playerbot.Bg.AutoSeed.Arena", 0); + const int32 arena_cap = sConfigMgr->GetIntDefault("Playerbot.Bg.AutoSeed.Arena", 0, true); if (arena_cap <= 0) return; constexpr uint32 kArenaSeedIntervalMs = 3u * 60u * 1000u; @@ -4373,7 +4421,7 @@ void BotPopulationManager::SeedArenaMatches(uint32 now_ms) // the same override that pins BG seeds can pin a specific arena // (4=Nagrand, 5=Blade's Edge, 6=AllArenas, 8=Ruins, 10=Sewers, 11=RoV). uint16 arena_bml = 6; // BATTLEGROUND_AA - const int32 forced = sConfigMgr->GetIntDefault("Playerbot.Bg.AutoSeed.ForceType", 0); + const int32 forced = sConfigMgr->GetIntDefault("Playerbot.Bg.AutoSeed.ForceType", 0, true); if (forced > 0) { if (BattlegroundTemplate const* ftmpl = @@ -4556,7 +4604,7 @@ void BotPopulationManager::TopUpActiveBGs(uint32 now_ms) if (!is_prep && !is_running) continue; // Only SUSTAIN a RUNNING battleground that has a human in it. A bot-only running match is not refilled: it runs down and ends // on its own, so few instances stay alive and real players are put into the ones that are (owner directive 2026-06-17, confirmed - // by Karrz 2026-10-11: as few instances as possible, as many real players in each). PREP BGs are left ungated so a forming + // by playtest 2026-10-11: as few instances as possible, as many real players in each). PREP BGs are left ungated so a forming // human match still fills before its gates open (the human is invited but may not have entered m_Players yet). bool const has_human = BgHasHumanPlayer(bg); if (is_running && !has_human) continue; diff --git a/src/modules/PlayerbotV2/Fleet/BotPopulationManager.h b/src/modules/PlayerbotV2/Fleet/BotPopulationManager.h index d951951a76..958eeb5465 100644 --- a/src/modules/PlayerbotV2/Fleet/BotPopulationManager.h +++ b/src/modules/PlayerbotV2/Fleet/BotPopulationManager.h @@ -159,7 +159,7 @@ public: // Returns the role pinned. World thread only. static Role ApplyCompanionRole(Player* bot, Role requested, char const* where); - // `.bot save`: stores the role the companion plays right now (its AI role, else what its talents say) when none is stored yet, so a + // `.bot save`: stores the role the companion plays right now (its bot logic role, else what its talents say) when none is stored yet, so a // call or relog brings it back as it was saved instead of re-reading talents that may have changed or not been bought. A role // already stored (declared) is left as it is. Returns the role stored. World thread only. static Role StoreCurrentRole(Player* bot); diff --git a/src/modules/PlayerbotV2/Fleet/BotQueueFiller.cpp b/src/modules/PlayerbotV2/Fleet/BotQueueFiller.cpp index 83f1c10150..275de553ed 100644 --- a/src/modules/PlayerbotV2/Fleet/BotQueueFiller.cpp +++ b/src/modules/PlayerbotV2/Fleet/BotQueueFiller.cpp @@ -1252,7 +1252,7 @@ bool BotQueueFiller::ClaimRunningBgForHuman(Player* human, uint32 bg_type_id, ui for (auto& w : g_human_waits) if (w.guid == human->GetGUID() && w.bg_type == bg_type_id) w.hold_until_ms = getMSTime() + 60u * 1000u; - // Places left in that instance once the human's party is in, both teams: a side that is mostly empty (Karrz, WSG + // Places left in that instance once the human's party is in, both teams: a side that is mostly empty (playtest, WSG // 2026-10-09: three Horde in the instance he was sent to) still needs the bot fill; the caller queues it capped to this. if (open_slots) { diff --git a/src/modules/PlayerbotV2/Fleet/BotQueueFiller.h b/src/modules/PlayerbotV2/Fleet/BotQueueFiller.h index 0b0de3b61e..8b618f2a5c 100644 --- a/src/modules/PlayerbotV2/Fleet/BotQueueFiller.h +++ b/src/modules/PlayerbotV2/Fleet/BotQueueFiller.h @@ -86,7 +86,7 @@ public: // OnBgMatchEnd / OnLfgGroupComplete (when those land). void OnMatchEnd(Player* bot); - // ---- Ambient BG participation (Playerbot.Bg.AutoJoin*, Karrz's RandomBotAutoJoinBG) ---- + // ---- Ambient BG participation (Playerbot.Bg.AutoJoin*, the owner's RandomBotAutoJoinBG) ---- // // Both are world-thread passes driven from BotPopulationManager::OnWorldTick; each keeps // its own cadence and does nothing while disabled or with no bots online. diff --git a/src/modules/PlayerbotV2/Fleet/BotSetupPipeline.cpp b/src/modules/PlayerbotV2/Fleet/BotSetupPipeline.cpp index eb72a65103..9ea16c63a0 100644 --- a/src/modules/PlayerbotV2/Fleet/BotSetupPipeline.cpp +++ b/src/modules/PlayerbotV2/Fleet/BotSetupPipeline.cpp @@ -484,7 +484,7 @@ bool BotSetupPipeline::DoApplyTalents(Player* bot) { // Retail: no-op at the pipeline layer. The existing // `idle:apply_context_talents` State_Idle rule applies the right talent - // context (Raid / Leveling) automatically on the bot's first AI tick. + // context (Raid / Leveling) automatically on the bot's first bot tick. if (!bot || !::Playerbot::IsVanillaRealm()) return true; @@ -751,6 +751,9 @@ bool BotSetupPipeline::DoAcquireMount(Player* bot) if (bot->GetClass() == CLASS_HUNTER && bot->GetPetGUID().IsEmpty()) { uint32 pet_entry = World::HunterPetEntryForRace(bot->GetRace()); + // A hunter nobody owns (world / pool bot) gets its own beast, stable per bot, instead of its race's one. + if (::Playerbot::Services::Owners().GetOwner(bot->GetGUID().GetCounter()).account_id == 0) + pet_entry = World::VariedHunterPetEntry(bot->GetTeam() == ALLIANCE, bot->GetGUID().GetCounter(), pet_entry); if (!pet_entry) { // Unmapped race (allied) — fall back to faction-generic. diff --git a/src/modules/PlayerbotV2/Fleet/CompanionRole.h b/src/modules/PlayerbotV2/Fleet/CompanionRole.h index 0c77291996..e0305be6f9 100644 --- a/src/modules/PlayerbotV2/Fleet/CompanionRole.h +++ b/src/modules/PlayerbotV2/Fleet/CompanionRole.h @@ -1,11 +1,11 @@ // CompanionRole - which role a companion plays, and whether that choice is remembered: the pure rule behind // BotPopulationManager::ApplyCompanionRole. // -// Only a role somebody CHOSE is stored with the companion (and pinned on the AI and the virtual spec): the one the owner +// Only a role somebody CHOSE is stored with the companion (and pinned on the bot logic and the virtual spec): the one the owner // asked for (`.bot add healer`, /setrole, the raid quota fill) or the one already stored. A role INFERRED from the // talents is a guess about a build that may not exist yet, so it is used for now and never stored: the login and the 5-minute // upkeep read the spec before the setup step has spent the talent points, so the guess was "dps" for a healer, was stored for -// good, and the talent walk then followed the stored role (Karrz, Stormwind 2026-10-09: 285 stored rows, healer priests as dps, +// good, and the talent walk then followed the stored role (playtest, Stormwind 2026-10-09: 285 stored rows, healer priests as dps, // paladins and druids split over tank and dps). Left unset, a companion is still free for the raid quota fill, which is what // RaidBrain's role_set test relies on. // Pure: no game types, tested in tests/game/ClassicCompanionRole.cpp. @@ -27,7 +27,7 @@ struct CompanionRoleChoice { ::Playerbot::Role role = ::Playerbot::Role::Dps; CompanionRoleSource source = CompanionRoleSource::Spec; - bool pin = false; // set the AI role override and the virtual spec + bool pin = false; // set the bot role override and the virtual spec bool store = false; // keep the role with the companion (only a chosen role) }; diff --git a/src/modules/PlayerbotV2/Fleet/DayRhythm.h b/src/modules/PlayerbotV2/Fleet/DayRhythm.h new file mode 100644 index 0000000000..bb3a4b05b9 --- /dev/null +++ b/src/modules/PlayerbotV2/Fleet/DayRhythm.h @@ -0,0 +1,31 @@ +// DayRhythm - how busy the world is at this hour of the server machine's day. The bubble target (ZoneBots / CityBots) is scaled by +// it, so the night is quieter (and costs less RAM and CPU) and the evening is busier, the way a real server is. Pure: tested in +// tests/game/ClassicDayRhythm.cpp. +#pragma once + +#include + +namespace Playerbot::V2::Fleet +{ + +// Percent of the day target for the local hour 0..23. +inline std::uint32_t RhythmPercent(int hour) +{ + if (hour < 0 || hour > 23) return 100; + if (hour < 6) return 60; // night + if (hour < 9) return 80; // early morning + if (hour < 18) return 100; // day + if (hour < 22) return 125; // evening, the busiest + return 80; // late evening +} + +// `target` scaled by the rhythm, never above `ceiling` (the world cap), and never below 1 for a nonzero target. +inline std::uint32_t RhythmTarget(std::uint32_t target, int hour, std::uint32_t ceiling) +{ + if (!target) return 0; + std::uint64_t const v = std::uint64_t(target) * RhythmPercent(hour) / 100u; + std::uint32_t const out = v > ceiling ? ceiling : std::uint32_t(v); + return out ? out : 1u; +} + +} // namespace Playerbot::V2::Fleet diff --git a/src/modules/PlayerbotV2/Fleet/InstanceEntry.h b/src/modules/PlayerbotV2/Fleet/InstanceEntry.h new file mode 100644 index 0000000000..648d81bb85 --- /dev/null +++ b/src/modules/PlayerbotV2/Fleet/InstanceEntry.h @@ -0,0 +1,72 @@ +// InstanceEntry.h: taking an owner's companion into the instance the owner stands in. +// +// A companion is refused at the door (Map::PlayerCannotEnter) when its own raid lock names a different instance than +// the one the group uses: the saved bots of last night's Molten Core kill hold a lock on that instance, and a fresh +// instance made for an owner without a lock is "locked to a different instance" for every one of them. The owner's +// own bots follow the owner, so such a stale lock on the map is dropped. Bots never collect raid saves any more (the core +// skips them when binding), so this only clears saves written before that. Every refusal is logged with its reason, the +// entrance walk stays the fallback. +#pragma once + +#include "DB2Stores.h" +#include "Group.h" +#include "InstanceLockMgr.h" +#include "Log.h" +#include "Map.h" +#include "Player.h" +#include "WorldSession.h" + +namespace Playerbot::V2::Fleet +{ + +inline char const* TransferAbortName(TransferAbortReason reason) +{ + switch (reason) + { + case TRANSFER_ABORT_NONE: return "none"; + case TRANSFER_ABORT_MAP_NOT_ALLOWED: return "map not allowed"; + case TRANSFER_ABORT_DIFFICULTY: return "difficulty not available"; + case TRANSFER_ABORT_NEED_GROUP: return "raid group needed"; + case TRANSFER_ABORT_LOCKED_TO_DIFFERENT_INSTANCE: return "locked to a different instance"; + case TRANSFER_ABORT_ALREADY_COMPLETED_ENCOUNTER: return "already completed an encounter"; + case TRANSFER_ABORT_TOO_MANY_INSTANCES: return "too many instances per hour"; + case TRANSFER_ABORT_MAX_PLAYERS: return "instance full"; + case TRANSFER_ABORT_ZONE_IN_COMBAT: return "encounter in progress"; + case TRANSFER_ABORT_NOT_FOUND: return "instance not found"; + default: return "other"; + } +} + +// Readies `bot` to enter instance map `map_id` and returns why it still cannot (TRANSFER_ABORT_NONE: it can). A bot holds no +// raid save of its own, so a lock that names another instance is dropped. Not an instance map, or the bot is already +// there: nothing to do. +inline TransferAbortReason PrepareInstanceEntry(Player* bot, uint32 map_id) +{ + MapEntry const* entry = sMapStore.LookupEntry(map_id); + if (!bot || !entry || !entry->IsDungeon() || bot->GetMapId() == map_id) + return TRANSFER_ABORT_NONE; + + TransferAbortParams denied = Map::PlayerCannotEnter(map_id, bot); + if (!denied) + return TRANSFER_ABORT_NONE; + + bool const staleLock = denied.Reason == TRANSFER_ABORT_LOCKED_TO_DIFFERENT_INSTANCE || + denied.Reason == TRANSFER_ABORT_ALREADY_COMPLETED_ENCOUNTER; + if (staleLock) + { + Group const* group = bot->GetGroup(); + Difficulty difficulty = group ? group->GetDifficultyID(entry) : bot->GetDifficultyID(entry); + if (MapDifficultyEntry const* mapDiff = sDB2Manager.GetDownscaledMapDifficultyData(map_id, difficulty)) + difficulty = Difficulty(mapDiff->DifficultyID); + std::vector reset, failed; + sInstanceLockMgr.ResetInstanceLocksForPlayer(bot->GetGUID(), map_id, difficulty, &reset, &failed); + TC_LOG_INFO("playerbot.v2", "[instance_enter] {} was refused for map {} ({}): its old save dropped, bots follow the group " + "(reset {}, still in use {})", bot->GetName(), map_id, TransferAbortName(denied.Reason), reset.size(), failed.size()); + denied = Map::PlayerCannotEnter(map_id, bot); + } + if (denied) + TC_LOG_INFO("playerbot.v2", "[instance_enter] {} cannot enter map {}: {}", bot->GetName(), map_id, TransferAbortName(denied.Reason)); + return denied.Reason; +} + +} // namespace Playerbot::V2::Fleet diff --git a/src/modules/PlayerbotV2/Fleet/InstanceGroupCap.h b/src/modules/PlayerbotV2/Fleet/InstanceGroupCap.h index bc84e52dbb..919a802585 100644 --- a/src/modules/PlayerbotV2/Fleet/InstanceGroupCap.h +++ b/src/modules/PlayerbotV2/Fleet/InstanceGroupCap.h @@ -41,7 +41,7 @@ inline uint32 InstanceGroupCapFor(Player const* owner, std::string* map_name = n InstanceMap const* im = map->ToInstanceMap(); uint32 cap = im ? im->GetMaxPlayers() : 0; // A raid is as big as the map says: the difficulty row can name a smaller flex size than the 40-player classic raid - // the map is (Molten Core refused a 10-bot add, Karrz 2026-10-08), so the larger of the two counts. + // the map is (Molten Core refused a 10-bot add, playtest 2026-10-08), so the larger of the two counts. if (map->IsRaid() && map->GetEntry() && map->GetEntry()->MaxPlayers > 0) cap = std::max(cap, uint32(map->GetEntry()->MaxPlayers)); if (!cap) diff --git a/src/modules/PlayerbotV2/Fleet/OwnerRegistry.cpp b/src/modules/PlayerbotV2/Fleet/OwnerRegistry.cpp index 8d147456b2..38d4a84ced 100644 --- a/src/modules/PlayerbotV2/Fleet/OwnerRegistry.cpp +++ b/src/modules/PlayerbotV2/Fleet/OwnerRegistry.cpp @@ -25,6 +25,7 @@ size_t OwnerRegistry::LoadFromDb() owners_.clear(); starter_pet_granted_.clear(); gear_varied_.clear(); + gear_varied_raid_.clear(); declared_role_.clear(); subgroup_.clear(); spec_.clear(); @@ -47,6 +48,8 @@ size_t OwnerRegistry::LoadFromDb() starter_pet_granted_.insert(bot); if (f[5].GetUInt8() != 0) gear_varied_.insert(bot); + if (f[5].GetUInt8() >= 2) + gear_varied_raid_.insert(bot); if (uint8 const r = f[6].GetUInt8(); r >= 1 && r <= 3) declared_role_[bot] = Role(r - 1); if (uint8 const sg = f[7].GetUInt8(); sg >= 1 && sg <= 8) @@ -162,7 +165,7 @@ void OwnerRegistry::SetOwner(BotId bot, uint32 account_id, uint64 player_guid) if (account_id == 0 && player_guid == 0) { owners_.erase(bot); - // The declared role stays with the character through a dismissal: re-added, it plays what it played (Karrz + // The declared role stays with the character through a dismissal: re-added, it plays what it played (the owner // 2026-10-08: dismissed paladins and druids came back as tanks from a talent inference). } else @@ -213,6 +216,23 @@ void OwnerRegistry::MarkStarterPetGranted(BotId bot) Db().DirectPExecute("UPDATE playerbot_v2_character SET starter_pet_granted = 1 WHERE character_guid_low = {}", bot); } +bool OwnerRegistry::GearVariedRaid(BotId bot) const +{ + std::shared_lock lk(mtx_); + return gear_varied_raid_.contains(bot); +} + +void OwnerRegistry::MarkGearVariedRaid(BotId bot) +{ + { + std::unique_lock lk(mtx_); + gear_varied_.insert(bot); + if (!gear_varied_raid_.insert(bot).second) + return; + } + Db().DirectPExecute("UPDATE playerbot_v2_character SET gear_varied = 2 WHERE character_guid_low = {}", bot); +} + bool OwnerRegistry::GearVaried(BotId bot) const { std::shared_lock lk(mtx_); diff --git a/src/modules/PlayerbotV2/Fleet/OwnerRegistry.h b/src/modules/PlayerbotV2/Fleet/OwnerRegistry.h index 3474a26f99..418fa6a150 100644 --- a/src/modules/PlayerbotV2/Fleet/OwnerRegistry.h +++ b/src/modules/PlayerbotV2/Fleet/OwnerRegistry.h @@ -10,7 +10,7 @@ // changes are infrequent and command authority depends on durability. // // World-thread mutations (mark / adopt / disown). Reads from any thread -// (whisper handler, AI workers, snapshot builder). +// (whisper handler, bot workers, snapshot builder). #pragma once @@ -74,6 +74,10 @@ public: // The companion's equipment has had its one full re-roll with the per-bot varied generator. Companions geared // before gear variety existed all wear the same top pick per slot; they are re-rolled once (in or out of combat // permitting) and then marked. Migration 0023. + // 2 in the same column: a level-cap companion has also had the raid-gear variety pass (RaidRegearPass `vary`), which swaps worn + // pieces for the bot's own near-equal pick. The 1 of the first re-roll leaves it at 1, so bots varied before are found again. + bool GearVariedRaid(BotId bot) const; + void MarkGearVariedRaid(BotId bot); bool GearVaried(BotId bot) const; void MarkGearVaried(BotId bot); @@ -206,6 +210,7 @@ private: std::unordered_map online_owner_character_; std::unordered_set starter_pet_granted_; std::unordered_set gear_varied_; + std::unordered_set gear_varied_raid_; std::unordered_map declared_role_; std::unordered_map spec_; std::unordered_map order_; diff --git a/src/modules/PlayerbotV2/Fleet/PetSnap.h b/src/modules/PlayerbotV2/Fleet/PetSnap.h new file mode 100644 index 0000000000..d5a0d9ace5 --- /dev/null +++ b/src/modules/PlayerbotV2/Fleet/PetSnap.h @@ -0,0 +1,51 @@ +// A pet of a playerbot that cannot walk to its owner (the owner stands on another level of a city, over a ledge the pet cannot take, +// or the path stops short): left to the follow generator it cheat-follows with a straight shortcut through the wall and shakes in +// place against it for as long as the owner stays there (Ironforge: a voidwalker on the Military Ward bridge, its warlock on a lower +// level). The way a player's pet ends up beside its owner when it falls behind is a snap to the owner's side, so: after a few +// looks in a row that find no way, and at most every kPetSnapCooldownMs, the pet is set down next to the owner. +// Pure decision logic for the module's world tick; the probe (the path) is made by the caller. +#pragma once + +#include + +namespace Playerbot::V2::Fleet +{ + +struct PetSnapState +{ + uint32_t next_check_ms = 0; // module ms before which the pet is not looked at again + uint32_t last_snap_ms = 0; + bool snapped_once = false; + uint8_t strikes = 0; // consecutive looks that found the pet with no way to its owner +}; + +constexpr uint32_t kPetSnapCheckMs = 1000u; // a pet is looked at this often +constexpr uint8_t kPetSnapStrikes = 3u; // no way to the owner three looks running (about three seconds) before it is snapped +constexpr uint32_t kPetSnapCooldownMs = 4000u; // at most one snap per pet in this time +constexpr float kPetSnapMinGap = 6.0f; // a pet this close to its owner is left alone + +inline bool PetSnapDue(PetSnapState const& st, uint32_t now_ms) +{ + return int32_t(now_ms - st.next_check_ms) >= 0; +} + +// Feeds one look. unreachable: the pet has no usable path to its owner. Returns true when the pet is to be snapped now. +inline bool PetSnapUpdate(PetSnapState& st, bool unreachable, uint32_t now_ms) +{ + st.next_check_ms = now_ms + kPetSnapCheckMs; + if (!unreachable) + { + st.strikes = 0; + return false; + } + if (st.strikes < 255) ++st.strikes; + if (st.strikes < kPetSnapStrikes) + return false; + if (st.snapped_once && int32_t(now_ms - st.last_snap_ms) < int32_t(kPetSnapCooldownMs)) + return false; + st.snapped_once = true; + st.last_snap_ms = now_ms; + return true; +} + +} // namespace Playerbot::V2::Fleet diff --git a/src/modules/PlayerbotV2/Fleet/PoolBalance.h b/src/modules/PlayerbotV2/Fleet/PoolBalance.h index ebf5b7bf7a..8109591969 100644 --- a/src/modules/PlayerbotV2/Fleet/PoolBalance.h +++ b/src/modules/PlayerbotV2/Fleet/PoolBalance.h @@ -1,5 +1,5 @@ // PoolBalance - which character the roster seeder creates next so the pool of sleeping residents is balanced between the factions -// in every level bracket (Karrz, 2026-10-11: the pool was ~94% Alliance, so no Horde was around when he quested and the Horde +// in every level bracket (playtest, 2026-10-11: the pool was ~94% Alliance, so no Horde was around when he quested and the Horde // battleground queues starved). The seeder used to flip a coin per bot; now it creates whichever (faction, bracket) is furthest // below the target ratio. Pure: no game types, tested in tests/game/ClassicPoolBalance.cpp. diff --git a/src/modules/PlayerbotV2/Fleet/QuestSiteShare.h b/src/modules/PlayerbotV2/Fleet/QuestSiteShare.h new file mode 100644 index 0000000000..7272bcba96 --- /dev/null +++ b/src/modules/PlayerbotV2/Fleet/QuestSiteShare.h @@ -0,0 +1,38 @@ +// QuestSiteShare - how many world bots may work the same quest spot. Bots pick their quest objectives one by one, so a popular mob +// camp can draw a dozen of them to the same few mobs; the mobs are gone as fast as they spawn and the crowd looks wrong. The bots at +// a spot take slots in a fixed order (real players, then companions of players, then world bots by id); a world bot whose place is past +// the cap gives that objective up for a while and the quest picker takes another. Deterministic, so every bot reaches the same answer +// about who stays, with no shared counter. Tested in tests/game/ClassicQuestSiteShare.cpp. +#pragma once + +#include +#include +#include + +namespace Playerbot::V2::Fleet +{ + +struct SiteWorker +{ + std::uint64_t id = 0; + bool ahead_of_bots = false; // a real player, or the companion of one: always has its slot +}; + +// Must the world bot `my_id` give the spot up? `near` are the other workers within reach of it. Its place is one past everyone ahead +// of it, so it yields when that place exceeds `cap`. cap 0 = never. +inline bool YieldQuestSite(std::uint64_t my_id, std::vector const& near, std::uint32_t cap) +{ + if (cap == 0) + return false; + std::uint32_t ahead = 0; + for (SiteWorker const& w : near) + if (w.ahead_of_bots || w.id < my_id) + ++ahead; + return ahead >= cap; +} + +constexpr std::uint32_t kQuestSiteCapDefault = 5u; // workers within kQuestSiteRadius of a bot +constexpr float kQuestSiteRadius = 40.0f; // the snapshot's friend scan +constexpr std::uint32_t kQuestSiteGiveUpMs = 15u * 60u * 1000u; + +} // namespace Playerbot::V2::Fleet diff --git a/src/modules/PlayerbotV2/Fleet/SoakAnchors.h b/src/modules/PlayerbotV2/Fleet/SoakAnchors.h new file mode 100644 index 0000000000..09d6bead44 --- /dev/null +++ b/src/modules/PlayerbotV2/Fleet/SoakAnchors.h @@ -0,0 +1,45 @@ +// SoakAnchors - characters that count as anchors for the world spawner although a bot plays them, so the world can be populated and +// watched with nobody logged in (overnight soaks). Playerbot.World.SoakAnchors = a comma-separated list of character names; empty +// (the default, and the release default) means none. An anchor is logged in and moved with the usual GM commands (`.playerbot login +// `, `.tele name `); the spawner then fills the world around it like around a player, and never treats it as +// one of its own residents. Name parsing is pure and tested in tests/game/ClassicSoakAnchors.cpp. +#pragma once + +#include +#include +#include +#include + +namespace Playerbot::V2::Fleet +{ + +inline std::unordered_set ParseSoakAnchors(std::string const& list) +{ + std::unordered_set out; + std::string cur; + auto flush = [&]() + { + std::size_t b = 0, e = cur.size(); + while (b < e && std::isspace(static_cast(cur[b]))) ++b; + while (e > b && std::isspace(static_cast(cur[e - 1]))) --e; + if (e > b) + { + std::string name = cur.substr(b, e - b); + std::transform(name.begin(), name.end(), name.begin(), [](unsigned char c) { return char(std::tolower(c)); }); + out.insert(std::move(name)); + } + cur.clear(); + }; + for (char c : list) + { + if (c == ',' || c == ';') flush(); + else cur.push_back(c); + } + flush(); + return out; +} + +// True when `name` is on the configured list. The list is re-read at most every 15 s. +bool IsSoakAnchor(std::string const& name); + +} // namespace Playerbot::V2::Fleet diff --git a/src/modules/PlayerbotV2/Fleet/StrandedWatch.h b/src/modules/PlayerbotV2/Fleet/StrandedWatch.h new file mode 100644 index 0000000000..94dcef69af --- /dev/null +++ b/src/modules/PlayerbotV2/Fleet/StrandedWatch.h @@ -0,0 +1,53 @@ +// A resident bot that stands where it cannot live: in a lava pit, or on a piece of ground with no way out of it (the Great Forge +// of Ironforge: the pit floor is a walkable surface the ground probe finds, but nothing on the navmesh joins it to the city). +// Pure decision logic for the world spawner's watch; the probes (liquid type, path) are made by the caller. +#pragma once + +#include +#include + +namespace Playerbot::V2::Fleet +{ + +struct StrandedState +{ + uint32_t next_check_ms = 0; // module ms before which the bot is not looked at again + float x = 0.0f, y = 0.0f, z = 0.0f; + uint8_t strikes = 0; // consecutive checks that found it with no path out, on the same spot +}; + +constexpr uint32_t kStrandedCheckMs = 20000u; // a bot is looked at this often +constexpr uint8_t kStrandedStrikes = 3u; // no path to the player three checks running (a minute) before it is moved + +inline bool StrandedDue(StrandedState const& st, uint32_t now_ms) +{ + return int32_t(now_ms - st.next_check_ms) >= 0; +} + +// Feeds one check. in_magma: lava (or slime) under its feet; path_out: a complete navmesh path to the town's player exists +// (or the bot has no reference to test against: pass true). Returns true when the bot is to be moved out now. Where the bot +// stands does not matter: a bot pacing a ledge over the forge is as cut off as one standing still on the pit floor. +inline bool StrandedUpdate(StrandedState& st, bool in_magma, bool path_out, float x, float y, float z, uint32_t now_ms) +{ + st.next_check_ms = now_ms + kStrandedCheckMs; + st.x = x; st.y = y; st.z = z; + if (in_magma) + { + st.strikes = 0; + return true; // lava is never somewhere to stand: no second look + } + if (path_out) + { + st.strikes = 0; + return false; + } + if (st.strikes < 255) ++st.strikes; + if (st.strikes >= kStrandedStrikes) + { + st.strikes = 0; + return true; + } + return false; +} + +} // namespace Playerbot::V2::Fleet diff --git a/src/modules/PlayerbotV2/Fleet/TownGather.h b/src/modules/PlayerbotV2/Fleet/TownGather.h new file mode 100644 index 0000000000..731558a3ed --- /dev/null +++ b/src/modules/PlayerbotV2/Fleet/TownGather.h @@ -0,0 +1,66 @@ +// Where people gather in a capital: the bank, the auction house, the inn, the flight master, the battlemaster. Quest-giver hubs are +// the wrong picture of a capital (the quest givers of Ironforge sit in the ward entrance rooms, the crowd stands in the Commons), +// so a town's residents are placed and sent to the service clusters instead. Pure part: clustering and the weighted pick. +#pragma once + +#include +#include +#include +#include + +namespace Playerbot::V2::Fleet +{ + +struct GatherNpc +{ + float x = 0.0f, y = 0.0f, z = 0.0f; + float weight = 0.0f; // how much a crowd forms around this NPC: bank / auctioneer / inn high, a lone trainer or vendor low +}; + +struct GatherSpot +{ + float x = 0.0f, y = 0.0f, z = 0.0f; + float weight = 0.0f; +}; + +constexpr float kGatherCell = 36.0f; // NPCs this close share a spot +constexpr float kGatherMinWeight = 4.0f; // a spot needs a bank's worth: a room of trainers is not a place to stand around +constexpr float kGatherRadius = 16.0f; // residents spread this far around a spot + +// Clusters the NPCs into grid cells; each cell with enough weight is one spot, at the weighted centre, heaviest first. +inline std::vector BuildGatherSpots(std::vector const& npcs) +{ + struct Acc { int cx, cy; float w = 0, sx = 0, sy = 0, sz = 0; }; + std::vector cells; + for (GatherNpc const& n : npcs) + { + if (n.weight <= 0.0f) continue; + int const cx = int(std::floor(n.x / kGatherCell)), cy = int(std::floor(n.y / kGatherCell)); + auto it = std::find_if(cells.begin(), cells.end(), [&](Acc const& a) { return a.cx == cx && a.cy == cy; }); + if (it == cells.end()) { cells.push_back(Acc{ cx, cy }); it = cells.end() - 1; } + it->w += n.weight; it->sx += n.x * n.weight; it->sy += n.y * n.weight; it->sz += n.z * n.weight; + } + std::vector out; + for (Acc const& a : cells) + if (a.w >= kGatherMinWeight) + out.push_back({ a.sx / a.w, a.sy / a.w, a.sz / a.w, a.w }); + std::sort(out.begin(), out.end(), [](GatherSpot const& l, GatherSpot const& r) { return l.weight > r.weight; }); + return out; +} + +// Index of a spot drawn in proportion to its weight; roll in [0, 1). -1 when there are none. +inline int PickGatherSpot(std::vector const& spots, float roll) +{ + float total = 0.0f; + for (GatherSpot const& s : spots) total += s.weight; + if (spots.empty() || total <= 0.0f) return -1; + float t = roll * total; + for (size_t i = 0; i < spots.size(); ++i) + { + t -= spots[i].weight; + if (t < 0.0f) return int(i); + } + return int(spots.size()) - 1; +} + +} // namespace Playerbot::V2::Fleet diff --git a/src/modules/PlayerbotV2/Fleet/TownGatherSource.h b/src/modules/PlayerbotV2/Fleet/TownGatherSource.h new file mode 100644 index 0000000000..366a5b182f --- /dev/null +++ b/src/modules/PlayerbotV2/Fleet/TownGatherSource.h @@ -0,0 +1,28 @@ +// The town's service NPCs (Travel/TownNpcIndex) turned into gathering spots (TownGather.h). +#pragma once + +#include "TownGather.h" +#include "Travel/TownNpcIndex.h" +#include "UnitDefines.h" + +namespace Playerbot::V2::Fleet +{ + +// Spots within `radius` of (x, y) on `map` that a player of the side can use, heaviest first. +inline std::vector TownGatherSpots(uint32 map, float x, float y, float radius, bool alliance) +{ + std::vector npcs; + ::Playerbot::V2::Travel::TownNpcIndex::Instance().ForEachNear(map, x, y, radius, [&](::Playerbot::V2::Travel::TownNpc const& n) + { + if (!n.usable_by(alliance)) return; + float w = 0.25f; // trainer, vendor, repair, petitioner... + if (n.npc_flags & (UNIT_NPC_FLAG_BANKER | UNIT_NPC_FLAG_AUCTIONEER)) w = 4.0f; + else if (n.npc_flags & UNIT_NPC_FLAG_INNKEEPER) w = 3.0f; + else if (n.npc_flags & (UNIT_NPC_FLAG_FLIGHTMASTER | UNIT_NPC_FLAG_BATTLEMASTER)) w = 2.0f; + else if (n.npc_flags & UNIT_NPC_FLAG_STABLEMASTER) w = 1.0f; + npcs.push_back({ n.x, n.y, n.z, w }); + }); + return BuildGatherSpots(npcs); +} + +} // namespace Playerbot::V2::Fleet diff --git a/src/modules/PlayerbotV2/Fleet/WakeSelect.h b/src/modules/PlayerbotV2/Fleet/WakeSelect.h index 6f2f8b19c3..ee88e87447 100644 --- a/src/modules/PlayerbotV2/Fleet/WakeSelect.h +++ b/src/modules/PlayerbotV2/Fleet/WakeSelect.h @@ -3,7 +3,7 @@ // A sleeper wakes only when it is standing between MinDist and MaxDist of the player (not beside him: it would pop into view), // is of the wanted faction, and - when the player is in a capital - stands in the capital's own zone, because the target of a // capital counts only bots of that zone (WorldBotSpawner::CountAmbientNear). Without the zone rule the countryside around a -// city woke up as well, did not count toward the city's target, and the spawner kept waking until nothing was left (Karrz, +// city woke up as well, did not count toward the city's target, and the spawner kept waking until nothing was left (the owner, // Stormwind, 2026-10-09: 280 awake for CityBots 250). At most `want` wake. // Pure: no game types, tested in tests/game/ClassicWakeSelect.cpp. @@ -11,6 +11,7 @@ #include #include +#include #include namespace Playerbot::V2::Fleet { @@ -52,4 +53,44 @@ inline std::vector SelectWake(std::vector const& in, Wa return out; } +// Fair share across the zones around the player. `awake_by_zone` is how many ambient bots already stand awake in each zone within +// the activity radius. Outdoors the player's own zone (rule.anchor_zone) is to hold about home_share of all the awake bots around +// him and the neighbouring zones the rest; each pick takes a sleeper of the group that is below its share, from the zone with the +// fewest awake bots in that group. A capital keeps its own zone only (WakeEligible). Candidates arrive in random order, so ties +// resolve at random. Stops at `want`. +inline std::vector SelectWakeShared(std::vector const& in, WakeRule const& r, uint32_t want, + std::unordered_map awake_by_zone, float home_share = 0.6f) +{ + std::vector out; + std::vector pool; + for (WakeCandidate const& c : in) + if (WakeEligible(c, r)) pool.push_back(&c); + while (out.size() < want && !pool.empty()) + { + uint64_t total = 0; + for (auto const& kv : awake_by_zone) total += kv.second; + uint32_t const home_awake = awake_by_zone.contains(r.anchor_zone) ? awake_by_zone[r.anchor_zone] : 0u; + bool const want_home = r.capital || total == 0 || float(home_awake) < home_share * float(total); + auto best = pool.end(); + uint32_t best_n = 0; + for (auto it = pool.begin(); it != pool.end(); ++it) + { + bool const is_home = (*it)->zone == r.anchor_zone; + if (is_home != want_home) continue; + uint32_t const n = awake_by_zone.contains((*it)->zone) ? awake_by_zone[(*it)->zone] : 0u; + if (best == pool.end() || n < best_n) { best = it; best_n = n; } + } + if (best == pool.end()) // nobody of the wanted group sleeps nearby: the other group + for (auto it = pool.begin(); it != pool.end(); ++it) + { + uint32_t const n = awake_by_zone.contains((*it)->zone) ? awake_by_zone[(*it)->zone] : 0u; + if (best == pool.end() || n < best_n) { best = it; best_n = n; } + } + out.push_back((*best)->guid); + ++awake_by_zone[(*best)->zone]; + pool.erase(best); + } + return out; +} + } // namespace Playerbot::V2::Fleet diff --git a/src/modules/PlayerbotV2/Fleet/WorldBotSpawner.cpp b/src/modules/PlayerbotV2/Fleet/WorldBotSpawner.cpp index f3c66ad1d3..6b20baf207 100644 --- a/src/modules/PlayerbotV2/Fleet/WorldBotSpawner.cpp +++ b/src/modules/PlayerbotV2/Fleet/WorldBotSpawner.cpp @@ -2,7 +2,14 @@ #include "Fleet/WorldLeash.h" #include "WorldBotSpawner.h" +#include "Bot/TownLife.h" #include "WakeSelect.h" +#include "StrandedWatch.h" +#include "DayRhythm.h" +#include "SoakAnchors.h" +#include "../Travel/TownNpcIndex.h" +#include "UnitDefines.h" +#include "TownGatherSource.h" #include "WorldFactionMix.h" #include "SkyborneIsle.h" #include "BotPopulationManager.h" @@ -14,6 +21,10 @@ #include "../Session/BotSessionMgr.h" #include "../Threading/SnapshotPublisher.h" #include "../Bot/BotRegistry.h" +#include "../Bot/IdleRule.h" +#include "../Bot/IdleWatch.h" +#include +#include "MotionMaster.h" #include "../Bot/World/ZonePicker.h" #include "../Bot/World/SpreadSpot.h" #include "Config.h" @@ -27,6 +38,7 @@ #include "GameObject.h" #include "ObjectAccessor.h" #include "Player.h" +#include "PathGenerator.h" #include "PlayerbotMovement.h" #include "Random.h" #include "StringFormat.h" @@ -34,6 +46,8 @@ #include "World.h" #include "WorldSession.h" #include +#include +#include #include #include #ifdef _WIN32 @@ -42,15 +56,38 @@ # endif # include # include +#else +# include #endif namespace Playerbot::V2::Fleet { +bool IsSoakAnchor(std::string const& name) +{ + static std::mutex mtx; + static std::unordered_set names; + static uint32 read_ms = 0; + std::lock_guard lock(mtx); + uint32 const now = getMSTime(); + if (!read_ms || getMSTimeDiff(read_ms, now) >= 15000u) + { + read_ms = now; + names = ParseSoakAnchors(sConfigMgr->GetStringDefault("Playerbot.World.SoakAnchors", "", true)); + } + if (names.empty()) + return false; + std::string lower = name; + std::transform(lower.begin(), lower.end(), lower.begin(), [](unsigned char c) { return char(std::tolower(c)); }); + return names.contains(lower); +} + namespace { constexpr uint32 kConfigReloadMs = 15000u; constexpr uint32 kReportMs = 60000u; constexpr uint32 kMemReportMs = 60000u; // [mem] line +constexpr uint32 kSwapBurstMs = 60000u; // after a jump the swap runs faster for this long +constexpr uint32 kSwapBurstFactor = 3u; // x spawn and despawn rate during it constexpr uint32 kPendingTimeoutMs = 120000u; // login + setup pipeline + placement constexpr uint32 kQueryTimeoutMs = 20000u; @@ -120,6 +157,24 @@ static uint64 ProcessRssKb() #endif } +// Physical memory of the machine in MB; 0 when the system will not say. +static uint64 PhysicalRamMb() +{ +#ifdef _WIN32 + MEMORYSTATUSEX ms{}; + ms.dwLength = sizeof(ms); + if (GlobalMemoryStatusEx(&ms)) + return uint64(ms.ullTotalPhys / (1024ull * 1024ull)); + return 0; +#else + long const pages = sysconf(_SC_PHYS_PAGES); + long const page = sysconf(_SC_PAGESIZE); + if (pages > 0 && page > 0) + return uint64(pages) * uint64(page) / (1024ull * 1024ull); + return 0; +#endif +} + // Private (committed, non-shared) bytes in KB; Windows only, 0 elsewhere. The working set can hide memory the OS has paged out. static uint64 ProcessPrivateKb() { @@ -163,44 +218,52 @@ WorldBotSpawner::WorldBotSpawner(BotPopulationManager& owner) : owner_(owner) {} void WorldBotSpawner::LoadConfig() { Config c; - c.enable = sConfigMgr->GetBoolDefault ("Playerbot.World.Enable", false); - c.max_bots = uint32(sConfigMgr->GetIntDefault("Playerbot.World.MaxBots", 100)); - c.bots_per_player = uint32(sConfigMgr->GetIntDefault("Playerbot.World.BotsPerPlayer", 25)); - c.city_bots = uint32(sConfigMgr->GetIntDefault("Playerbot.World.CityBots", 0)); - c.zone_bots = uint32(sConfigMgr->GetIntDefault("Playerbot.World.ZoneBots", 0)); - c.activity_radius = std::max(50.0f, sConfigMgr->GetFloatDefault("Playerbot.World.ActivityRadius", 300.0f)); + c.enable = sConfigMgr->GetBoolDefault ("Playerbot.World.Enable", false, true); + c.max_bots = uint32(sConfigMgr->GetIntDefault("Playerbot.World.MaxBots", 100, true)); + c.bots_per_player = uint32(sConfigMgr->GetIntDefault("Playerbot.World.BotsPerPlayer", 25, true)); + c.city_bots = uint32(sConfigMgr->GetIntDefault("Playerbot.World.CityBots", 0, true)); + c.zone_bots = uint32(sConfigMgr->GetIntDefault("Playerbot.World.ZoneBots", 0, true)); + c.activity_radius = std::max(50.0f, sConfigMgr->GetFloatDefault("Playerbot.World.ActivityRadius", 300.0f, true)); c.despawn_radius = std::max(c.activity_radius * 1.1f, - sConfigMgr->GetFloatDefault("Playerbot.World.DespawnRadius", c.activity_radius * 1.5f)); - c.ring_min = std::max(20.0f, sConfigMgr->GetFloatDefault("Playerbot.World.SpawnRingMin", 110.0f)); - c.ring_max = std::max(c.ring_min + 20.0f, sConfigMgr->GetFloatDefault("Playerbot.World.SpawnRingMax", 200.0f)); + sConfigMgr->GetFloatDefault("Playerbot.World.DespawnRadius", c.activity_radius * 1.5f, true)); + c.ring_min = std::max(20.0f, sConfigMgr->GetFloatDefault("Playerbot.World.SpawnRingMin", 110.0f, true)); + c.ring_max = std::max(c.ring_min + 20.0f, sConfigMgr->GetFloatDefault("Playerbot.World.SpawnRingMax", 200.0f, true)); c.ring_max = std::min(c.ring_max, c.activity_radius * 0.9f); c.ring_min = std::min(c.ring_min, c.ring_max - 10.0f); - c.tick_ms = std::max(500, uint32(sConfigMgr->GetIntDefault("Playerbot.World.TickMs", 1000))); - c.spawn_per_tick = std::max(1, uint32(sConfigMgr->GetIntDefault("Playerbot.World.SpawnPerTick", 2))); - c.global_fill = sConfigMgr->GetBoolDefault("Playerbot.World.GlobalFill", false); - c.global_per_tick = std::max(1, uint32(sConfigMgr->GetIntDefault("Playerbot.World.GlobalPerTick", 3))); - c.filler_hub_only = sConfigMgr->GetBoolDefault("Playerbot.World.FillerHubOnly", true); - c.rss_budget_mb = uint32(sConfigMgr->GetIntDefault("Playerbot.World.RssBudgetMb", 0)); - c.town_pct = std::min(100, uint32(sConfigMgr->GetIntDefault("Playerbot.World.TownPct", 70))); - c.city_spawn_per_tick = uint32(sConfigMgr->GetIntDefault("Playerbot.World.CitySpawnPerTick", 0)); - c.seed_roster = sConfigMgr->GetBoolDefault("Playerbot.World.SeedRoster", false); - c.seed_in_flight = std::max(1, uint32(sConfigMgr->GetIntDefault("Playerbot.World.SeedInFlight", 8))); - c.wake_radius = std::max(0.0f, sConfigMgr->GetFloatDefault("Playerbot.World.WakeRadius", 0.0f)); - c.zone_grace_ms = uint32(sConfigMgr->GetIntDefault("Playerbot.World.ZoneGraceSec", 300)) * 1000u; - c.despawn_per_tick = std::max(1, uint32(sConfigMgr->GetIntDefault("Playerbot.World.DespawnPerTick", 5))); - c.placed_grace_ms = uint32(sConfigMgr->GetIntDefault("Playerbot.World.PlacedGraceSec", 30)) * 1000u; - c.min_level = std::clamp(uint32(sConfigMgr->GetIntDefault("Playerbot.World.MinLevel", 10)), 1, 60); - c.max_level = std::clamp(uint32(sConfigMgr->GetIntDefault("Playerbot.World.MaxLevel", 60)), c.min_level, 60); - c.friendly_pct = std::min(100, uint32(sConfigMgr->GetIntDefault("Playerbot.World.FriendlyPct", 80))); + c.tick_ms = std::max(500, uint32(sConfigMgr->GetIntDefault("Playerbot.World.TickMs", 1000, true))); + c.spawn_per_tick = std::max(1, uint32(sConfigMgr->GetIntDefault("Playerbot.World.SpawnPerTick", 2, true))); + c.global_fill = sConfigMgr->GetBoolDefault("Playerbot.World.GlobalFill", false, true); + c.global_per_tick = std::max(1, uint32(sConfigMgr->GetIntDefault("Playerbot.World.GlobalPerTick", 3, true))); + c.filler_hub_only = sConfigMgr->GetBoolDefault("Playerbot.World.FillerHubOnly", true, true); + // Default (-1) is 45% of the machine's RAM, so a small PC stops adding filler bots before it swaps; 0 = no limit. + int32 const rss_cfg = sConfigMgr->GetIntDefault("Playerbot.World.RssBudgetMb", -1, true); + c.rss_budget_mb = rss_cfg >= 0 ? uint32(rss_cfg) : uint32(PhysicalRamMb() * 45u / 100u); + c.town_pct = std::min(100, uint32(sConfigMgr->GetIntDefault("Playerbot.World.TownPct", 100, true))); + c.city_spawn_per_tick = uint32(sConfigMgr->GetIntDefault("Playerbot.World.CitySpawnPerTick", 0, true)); + c.seed_roster = sConfigMgr->GetBoolDefault("Playerbot.World.SeedRoster", false, true); + c.seed_in_flight = std::max(1, uint32(sConfigMgr->GetIntDefault("Playerbot.World.SeedInFlight", 8, true))); + c.wake_radius = std::max(0.0f, sConfigMgr->GetFloatDefault("Playerbot.World.WakeRadius", 0.0f, true)); + c.natural_moves = sConfigMgr->GetBoolDefault("Playerbot.World.NaturalMoves", true); + c.day_rhythm = sConfigMgr->GetBoolDefault("Playerbot.World.DayRhythm", true); + c.jump_grace_ms = uint32(sConfigMgr->GetIntDefault("Playerbot.World.JumpGraceSec", 20, true)) * 1000u; + c.zone_grace_ms = uint32(sConfigMgr->GetIntDefault("Playerbot.World.ZoneGraceSec", 300, true)) * 1000u; + c.despawn_per_tick = std::max(1, uint32(sConfigMgr->GetIntDefault("Playerbot.World.DespawnPerTick", 5, true))); + c.placed_grace_ms = uint32(sConfigMgr->GetIntDefault("Playerbot.World.PlacedGraceSec", 30, true)) * 1000u; + c.min_level = std::clamp(uint32(sConfigMgr->GetIntDefault("Playerbot.World.MinLevel", 10, true)), 1, 60); + c.max_level = std::clamp(uint32(sConfigMgr->GetIntDefault("Playerbot.World.MaxLevel", 60, true)), c.min_level, 60); + c.friendly_pct = std::min(100, uint32(sConfigMgr->GetIntDefault("Playerbot.World.FriendlyPct", 100, true))); c.mix.default_pct = c.friendly_pct; - c.mix.by_zone = sConfigMgr->GetBoolDefault("Playerbot.World.ZoneMix", true); - c.mix.capital_pct = std::min(100, uint32(sConfigMgr->GetIntDefault("Playerbot.World.CapitalFriendlyPct", 90))); - c.mix.home_pct = std::min(100, uint32(sConfigMgr->GetIntDefault("Playerbot.World.HomeFriendlyPct", 90))); - c.mix.border_pct = std::min(100, uint32(sConfigMgr->GetIntDefault("Playerbot.World.BorderFriendlyPct", 75))); - c.mix.contested_pct = std::min(100, uint32(sConfigMgr->GetIntDefault("Playerbot.World.ContestedFriendlyPct", 60))); - c.pool_max = uint32(sConfigMgr->GetIntDefault("Playerbot.World.PoolMax", std::max(c.max_bots * 4, 200))); - c.pool_horde_pct = std::clamp(uint32(sConfigMgr->GetIntDefault("Playerbot.World.PoolHordePct", 50)), 5, 95); - c.skyborne_seed_pct = std::min(100, uint32(sConfigMgr->GetIntDefault("Playerbot.World.SkyborneSeedPct", 5))); + c.mix.by_zone = sConfigMgr->GetBoolDefault("Playerbot.World.ZoneMix", true, true); + c.mix.capital_pct = std::min(100, uint32(sConfigMgr->GetIntDefault("Playerbot.World.CapitalFriendlyPct", 100, true))); + c.mix.home_pct = std::min(100, uint32(sConfigMgr->GetIntDefault("Playerbot.World.HomeFriendlyPct", 100, true))); + c.mix.border_pct = std::min(100, uint32(sConfigMgr->GetIntDefault("Playerbot.World.BorderFriendlyPct", 100, true))); + c.mix.contested_pct = std::min(100, uint32(sConfigMgr->GetIntDefault("Playerbot.World.ContestedFriendlyPct", 100, true))); + c.pool_max = uint32(sConfigMgr->GetIntDefault("Playerbot.World.PoolMax", std::max(c.max_bots * 4, 200), true)); + c.area_cap_outdoors = uint32(std::clamp(sConfigMgr->GetIntDefault("Playerbot.World.AreaCapOutdoors", 14, true), 0, 500)); + c.area_cap_town = uint32(std::clamp(sConfigMgr->GetIntDefault("Playerbot.World.AreaCapTown", 40, true), 0, 500)); + c.area_radius = std::clamp(sConfigMgr->GetFloatDefault("Playerbot.World.AreaRadius", 45.0f, true), 15.0f, 200.0f); + c.pool_horde_pct = std::clamp(uint32(sConfigMgr->GetIntDefault("Playerbot.World.PoolHordePct", 50, true)), 5, 95); + c.skyborne_seed_pct = std::min(100, uint32(sConfigMgr->GetIntDefault("Playerbot.World.SkyborneSeedPct", 5, true))); cfg_ = c; } @@ -232,6 +295,14 @@ std::string WorldBotSpawner::Report() const n_no_match_, n_pool_full_, n_spawn_failed_, n_login_failed_, n_logged_in_, n_created_, n_placed_, n_despawned_, n_abandoned_, last_tick_cost_ms_, avg, max_tick_cost_ms_, rss / 1024, baseline_rss_kb_ / 1024, per_bot_mb); + line += Trinity::StringFormat(" | split world={} (cap {}) tied_up={} (group/BG/instance) owned={} (companions) soak_anchors={} evicted_for_room={} | walked_in={} walked_out={} leaving={}", + ambient_online_, cfg_.max_bots, tied_online_, owned_online_, soak_anchors_, n_evicted_, n_arrived_walking_, n_left_walking_, leaving_.size()); + { + auto& tl = ::Playerbot::V2::TownLife::Counters(); + line += Trinity::StringFormat(" | town_life inn_ticks={} mailbox_ticks={} duels={} campfires={} lfg_calls={} idle_strikes town={} field={}", + tl.inn_ticks.load(std::memory_order_relaxed), tl.mailbox_ticks.load(std::memory_order_relaxed), tl.duels.load(std::memory_order_relaxed), + tl.campfires.load(std::memory_order_relaxed), tl.lfg_calls.load(std::memory_order_relaxed), tl.idle_town.load(std::memory_order_relaxed), tl.idle_field.load(std::memory_order_relaxed)); + } auto const tiers = Services::Scheduler().tier_counts(); // Persistent residents: the pool is the roster, a bot logged out stays where it stood. sleeping = pool bots offline. int64 const pool = pool_count_ < 0 ? 0 : pool_count_; @@ -246,20 +317,16 @@ std::string WorldBotSpawner::Report() const void WorldBotSpawner::CollectAnchors(std::vector& out) { anchors_in_instance_ = 0; + soak_anchors_ = 0; auto& lifecycle = Services::Lifecycle(); - for (auto const& kv : ::World::instance()->GetAllSessions()) + auto add = [&](Player* p) { - WorldSession* session = kv.second; - if (!session) continue; - Player* p = session->GetPlayer(); - if (!p || !p->IsInWorld() || p->IsBeingTeleported()) continue; - if (lifecycle.is_bot(p->GetGUID().GetCounter())) continue; // a bot, not a real person Map* m = p->GetMap(); - if (!m) continue; + if (!m) return; if (m->IsDungeon() || m->IsBattlegroundOrArena()) { ++anchors_in_instance_; // world bots stay in the open world: nothing to spawn around a player inside - continue; + return; } Anchor a; a.guid = p->GetGUID(); @@ -271,23 +338,43 @@ void WorldBotSpawner::CollectAnchors(std::vector& out) a.level = uint8(p->GetLevel()); a.alliance = p->GetTeam() == ALLIANCE; out.push_back(a); + }; + for (auto const& kv : ::World::instance()->GetAllSessions()) + { + WorldSession* session = kv.second; + if (!session) continue; + Player* p = session->GetPlayer(); + if (!p || !p->IsInWorld() || p->IsBeingTeleported()) continue; + if (lifecycle.is_bot(p->GetGUID().GetCounter())) continue; // a bot, not a real person + add(p); } + // Bots play in headless sessions that the list above does not hold. A configured soak anchor (Fleet/SoakAnchors.h) stands in for a + // player; no other bot is ever an anchor. + Services::Registry().for_each([&](BotId id, BotRegistryEntry const&) + { + Player* p = ObjectAccessor::FindConnectedPlayer(ObjectGuid::Create(id)); + if (!p || !p->IsInWorld() || p->IsBeingTeleported() || !IsSoakAnchor(p->GetName())) return; + ++soak_anchors_; + add(p); + }); } uint32 WorldBotSpawner::SpawnRateFor(Anchor const& a) const { - uint8 lo = 0, hi = 0; - bool const town = !::Playerbot::V2::World::VanillaZoneLevelRange(a.zone, lo, hi); + bool const town = ::Playerbot::V2::World::IsVanillaCapitalZone(a.zone); return town && cfg_.city_spawn_per_tick ? cfg_.city_spawn_per_tick : cfg_.spawn_per_tick; } uint32 WorldBotSpawner::TargetFor(Anchor const& a) const { // A capital is packed (CityBots), a leveling zone gets an ordinary density spread over ActivityRadius (ZoneBots). - uint8 lo = 0, hi = 0; - bool const town = !::Playerbot::V2::World::VanillaZoneLevelRange(a.zone, lo, hi); + bool const town = ::Playerbot::V2::World::IsVanillaCapitalZone(a.zone); uint32 const t = town ? cfg_.city_bots : cfg_.zone_bots; - return t ? t : cfg_.bots_per_player; + uint32 const base = t ? t : cfg_.bots_per_player; + if (!cfg_.day_rhythm) + return base; + // The server machine's hour of the day: quieter at night (less RAM and CPU), busier in the evening (Fleet/DayRhythm.h). + return ::Playerbot::V2::Fleet::RhythmTarget(base, TimeBreakdown(GameTime::GetGameTime()).tm_hour, cfg_.max_bots); } uint32 WorldBotSpawner::CountAmbientNear(Anchor const& a) const @@ -295,8 +382,7 @@ uint32 WorldBotSpawner::CountAmbientNear(Anchor const& a) const uint32 n = 0; // In a capital only bots that stand in the capital count: the 600 y radius also reaches the countryside around // it (Elwynn for Stormwind), and bots out there must not fill the city's target. - uint8 tlo = 0, thi = 0; - bool const town = !::Playerbot::V2::World::VanillaZoneLevelRange(a.zone, tlo, thi); + bool const town = ::Playerbot::V2::World::IsVanillaCapitalZone(a.zone); Services::Registry().for_each([&](BotId id, BotRegistryEntry const&) { ObjectGuid const g = ObjectGuid::Create(id); @@ -309,6 +395,71 @@ uint32 WorldBotSpawner::CountAmbientNear(Anchor const& a) const return n; } +// Awake ambient bots around the anchor by zone: the shares the wake pass tops up (Fleet/WakeSelect.h SelectWakeShared). +std::unordered_map WorldBotSpawner::AwakeByZone(Anchor const& a) const +{ + std::unordered_map out; + Services::Registry().for_each([&](BotId id, BotRegistryEntry const&) + { + Player* p = ObjectAccessor::FindConnectedPlayer(ObjectGuid::Create(id)); + if (!p || !p->IsInWorld() || p->GetMapId() != a.map || !owner_.IsAmbientBot(id, p)) return; + if (Dist2D(p->GetPositionX(), p->GetPositionY(), a.x, a.y) <= cfg_.activity_radius) ++out[p->GetZoneId()]; + }); + return out; +} + +// Lava or slime under (x, y, z): ground a resident must never stand on, whatever the navmesh says about the surface below it. +static bool InMagma(Map* map, PhaseShift const& phase, float x, float y, float z) +{ + LiquidData ld; + ZLiquidStatus const st = map->GetLiquidStatus(phase, x, y, z, {}, &ld); + if (!(st & (LIQUID_MAP_IN_WATER | LIQUID_MAP_UNDER_WATER | LIQUID_MAP_WATER_WALK))) + return false; + return ld.type_flags.HasFlag(map_liquidHeaderTypeFlags::Magma) || ld.type_flags.HasFlag(map_liquidHeaderTypeFlags::Slime); +} + +// A complete navmesh path from `from` (standing where it is) to (x, y, z). A map without a mesh gives no verdict: reachable. +static bool CompletePathTo(Player* from, float x, float y, float z) +{ + PathGenerator pg(from); + ::Playerbot::BotMovement::SehSafeCalculatePath(pg, x, y, z); + PathType const t = pg.GetPathType(); + if (t & (PATHFIND_NOT_USING_PATH | PATHFIND_SHORTCUT)) + return true; + return (t & PATHFIND_NORMAL) && !(t & (PATHFIND_NOPATH | PATHFIND_INCOMPLETE | PATHFIND_FARFROMPOLY)); +} + +// Is there a way from where `from` stands to (x, y, z)? One path call gives up after 74 polygons and calls the rest INCOMPLETE, which in a +// winding city (Stormwind's canals and stairs, Orgrimmar's ramps) is no more than "far": 231 healthy bots an hour were rescued as +// stranded on that alone. So an incomplete path is followed: the next call starts where the last one ended, and the goal is reached when +// some call completes. A real pocket (the Great Forge pit) ends at the same point every time, so the chain stops advancing and it is +// refused. At most `hops` calls; `used` gets the number made (the caller's probe budget). +static bool ReachableChain(Player* from, float x, float y, float z, uint32 hops, uint32& used) +{ + float sx = from->GetPositionX(), sy = from->GetPositionY(), sz = from->GetPositionZ(); + for (uint32 h = 0; h < hops; ++h) + { + ++used; + PathGenerator pg(from); + ::Playerbot::BotMovement::SehSafeCalculatePathFrom(pg, sx, sy, sz, x, y, z); + PathType const t = pg.GetPathType(); + if (t & (PATHFIND_NOT_USING_PATH | PATHFIND_SHORTCUT)) + return true; + if ((t & PATHFIND_NORMAL) && !(t & (PATHFIND_NOPATH | PATHFIND_INCOMPLETE | PATHFIND_FARFROMPOLY))) + return true; + if (!(t & PATHFIND_INCOMPLETE) || (t & PATHFIND_NOPATH)) + return false; + Movement::PointsArray const& pts = pg.GetPath(); + if (pts.size() < 2) + return false; + G3D::Vector3 const& end = pts.back(); + if (std::hypot(end.x - sx, end.y - sy) < 3.0f) + return false; // no progress: the path ends where it began + sx = end.x; sy = end.y; sz = end.z; + } + return false; +} + // A sleeper saved in a crowd (the roster was once placed on one flight master point per town) must not wake into it. It wakes at a // quest hub of the same zone that suits its level, chosen anew each time, or failing that a few yards off the spot, on the // ground. A bot with nobody around it stays exactly where it slept. @@ -326,6 +477,27 @@ void WorldBotSpawner::StepOffStack(Player* bot) TC_LOG_INFO("playerbot.v2", "[world] {} woke {:.1f} y under the ground, lifted onto it", bot->GetName(), gz - bot->GetPositionZ()); } } + // A sleeper saved off the navmesh (over a lava pit, inside a wall, on a roof: a spot an older build placed it on) cannot path + // anywhere and stands there for good. Move it to the nearest walkable ground, if there is any close by. + if (bot->GetMap() && !bot->IsInCombat() && bot->IsAlive()) + { + Position onmesh; + float const px = bot->GetPositionX(), py = bot->GetPositionY(), pz = bot->GetPositionZ(); + if (!::Playerbot::BotMovement::NearestNavPoint(bot, px, py, pz, 3.0f, 4.0f, onmesh)) + { + Position wide; + if (::Playerbot::BotMovement::NearestNavPoint(bot, px, py, pz, 40.0f, 12.0f, wide)) + { + Playerbot::BotMovement::SafeNearTeleport(bot, wide.GetPositionX(), wide.GetPositionY(), wide.GetPositionZ() + 0.3f, + bot->GetOrientation(), /*navmesh_point*/ true); + TC_LOG_INFO("playerbot.v2", "[world] {} woke off the navmesh at ({:.0f},{:.0f},{:.0f}), moved {:.0f} y onto walkable ground", + bot->GetName(), px, py, pz, std::hypot(wide.GetPositionX() - px, wide.GetPositionY() - py)); + } + else + TC_LOG_INFO("playerbot.v2", "[world] {} woke off the navmesh at ({:.0f},{:.0f},{:.0f}), no walkable ground within 40 y", + bot->GetName(), px, py, pz); + } + } constexpr float kCrowdYards = 8.0f; uint32 near_bots = 0; Services::Registry().for_each([&](BotId id, BotRegistryEntry const&) @@ -363,15 +535,14 @@ bool WorldBotSpawner::PlaceNear(Player* bot, Player* anchor) // In a capital the districts are small and the player sees a few streets, not 110 y of open ground: use a tighter ring // so the crowd stays in the district the player stands in (the LOS preference below still hides the spawn itself). - uint8 tlo = 0, thi = 0; - bool const in_town = !::Playerbot::V2::World::VanillaZoneLevelRange(anchor->GetZoneId(), tlo, thi); + bool const in_town = ::Playerbot::V2::World::IsVanillaCapitalZone(anchor->GetZoneId()); float const ring_min = in_town ? std::min(cfg_.ring_min, 45.0f) : cfg_.ring_min; float const ring_max = in_town ? std::min(cfg_.ring_max, 110.0f) : cfg_.ring_max; // Spawn spots: quest hubs (and, in a capital, the hubs of the town) around the anchor, so the crowd stands where // bots actually live and then goes about its own business there. A ring spot around the player is only the // fallback; a crowd that is always rebuilt on a ring reads as bots following the player. - struct Spot { float x, y, z, r, d; }; + struct Spot { float x, y, z, r, d; float w = 1.0f; }; Anchor self; // the anchor as a plain record, to count the bots already around him self.guid = anchor->GetGUID(); self.map = anchor->GetMapId(); self.x = anchor->GetPositionX(); self.y = anchor->GetPositionY(); self.zone = anchor->GetZoneId(); @@ -380,6 +551,19 @@ bool WorldBotSpawner::PlaceNear(Player* bot, Player* anchor) { float const ax = anchor->GetPositionX(), ay = anchor->GetPositionY(); float const min_d = in_town ? 35.0f : 60.0f; + // A capital: where people gather (bank, auction house, inn, flight master, battlemaster), not the quest-giver hubs, which in + // Ironforge are the ward entrance rooms. + if (in_town) + for (::Playerbot::V2::Fleet::GatherSpot const& g : ::Playerbot::V2::Fleet::TownGatherSpots( + anchor->GetMapId(), ax, ay, std::min(cfg_.activity_radius * 0.9f, 150.0f), anchor->GetTeam() == ALLIANCE)) + { + float const d = Dist2D(g.x, g.y, ax, ay); + if (d < min_d * 0.5f) continue; + Spot const sp{ g.x, g.y, g.z, ::Playerbot::V2::Fleet::kGatherRadius, d, g.weight }; + hubs.push_back(sp); + if (d <= 150.0f) near_hubs.push_back(sp); + } + if (!(in_town && !hubs.empty())) Services::Hubs().ForEach([&](::Playerbot::V2::Travel::QuestHub const& h) { if (h.mapId != anchor->GetMapId()) return; @@ -394,6 +578,22 @@ bool WorldBotSpawner::PlaceNear(Player* bot, Player* anchor) }); } + // Where the residents of this map already stand: a hub pick prefers the less crowded of a few, and a spot already at the area cap + // is refused (Fleet/AreaCap.h). A town's hubs near the player are few, and "the closest ones first" put the whole crowd in one doorway. + uint32 const area_cap = in_town ? cfg_.area_cap_town : cfg_.area_cap_outdoors; + std::vector<::Playerbot::V2::Fleet::CrowdPoint> crowd; + Services::Registry().for_each([&](BotId id, BotRegistryEntry const&) + { + if (uint64(id) == bot->GetGUID().GetCounter()) return; + Player* o = ObjectAccessor::FindConnectedPlayer(ObjectGuid::Create(id)); + if (o && o->IsInWorld() && o->GetMapId() == anchor->GetMapId() && owner_.IsAmbientBot(id, o)) + crowd.push_back({ uint64(id), o->GetPositionX(), o->GetPositionY(), area_cap }); + }); + auto crowd_at = [&](Spot const& h) + { + return ::Playerbot::V2::Fleet::CountWithin(crowd, h.x, h.y, h.r + 15.0f); + }; + float bx = 0, by = 0, bz = 0; bool have = false, hidden = false; for (int attempt = 0; attempt < 12 && !hidden; ++attempt) @@ -409,12 +609,34 @@ bool WorldBotSpawner::PlaceNear(Player* bot, Player* anchor) // Arrival: while fewer than 20 bots stand around the player, the first ones go to the hubs closest to him, so // the nearest ones appear first; the rest spread as usual. std::vector pool = base; - if (arriving && pool.size() > 4) + if (arriving && pool.size() > 8) { - std::partial_sort(pool.begin(), pool.begin() + 4, pool.end(), [](Spot const& l, Spot const& r) { return l.d < r.d; }); - pool.resize(4); + std::partial_sort(pool.begin(), pool.begin() + 8, pool.end(), [](Spot const& l, Spot const& r) { return l.d < r.d; }); + pool.resize(8); } - Spot const& h = pool[urand(0u, uint32(pool.size() - 1))]; + // In a town: of three hubs drawn at random, the one with the fewest residents already around it. + // Weighted by what gathers there (bank and auction house over a lone vendor), then the least crowded for its weight. + auto draw = [&]() -> Spot const* + { + float total = 0.0f; + for (Spot const& sp : pool) total += sp.w; + float t = frand(0.0f, total); + for (Spot const& sp : pool) + { + t -= sp.w; + if (t < 0.0f) return &sp; + } + return &pool.back(); + }; + Spot const* pick = draw(); + if (in_town) + for (int k = 0; k < 2; ++k) + { + Spot const* alt = draw(); + if (float(crowd_at(*alt)) / alt->w < float(crowd_at(*pick)) / pick->w) + pick = alt; + } + Spot const& h = *pick; float const a = frand(0.0f, 2.0f * float(M_PI)); float const rr = frand(0.0f, h.r); x = h.x + std::cos(a) * rr; @@ -434,19 +656,64 @@ bool WorldBotSpawner::PlaceNear(Player* bot, Player* anchor) // The ground height of a canal or pond is its floor: never put a bot on a spot that has water over it (even ankle-deep: the check is at the floor, not at head height). if (map->GetLiquidStatus(anchor->GetPhaseShift(), x, y, z + 0.05f, {}) & (LIQUID_MAP_IN_WATER | LIQUID_MAP_UNDER_WATER)) continue; - bx = x; by = y; bz = z; + // The height probe finds ANY surface within 60 y below the player: the floor of a lava pit (Ironforge's Great Forge), a roof, + // a lower level. Stand only where a walkable navmesh polygon is, so the bot can path from its spot to anywhere. + Position nav; + if (!::Playerbot::BotMovement::NearestNavPoint(anchor, x, y, z, 4.0f, 5.0f, nav)) + continue; + // Walkable is not yet "a place to live": never lava or slime, and in a town a spot the player can walk to. The Great Forge's + // pit floor is ground to the probe and to the mesh but joins nothing; a bot put there stands in it for good. + if (InMagma(map, anchor->GetPhaseShift(), nav.GetPositionX(), nav.GetPositionY(), nav.GetPositionZ() + 0.05f)) + continue; + if (in_town && !CompletePathTo(anchor, nav.GetPositionX(), nav.GetPositionY(), nav.GetPositionZ())) + continue; + if (!::Playerbot::V2::Fleet::RoomFor(crowd, nav.GetPositionX(), nav.GetPositionY(), cfg_.area_radius, area_cap)) + continue; // the area is full: another spot + bx = nav.GetPositionX(); by = nav.GetPositionY(); bz = nav.GetPositionZ(); last_place_dist_ = dist; have = true; // Prefer a spot the anchor cannot see, so bots do not pop into view; keep the last candidate otherwise. - hidden = !anchor->IsWithinLOS(x, y, z + 1.5f); + hidden = !anchor->IsWithinLOS(bx, by, bz + 1.5f); } if (!have) return false; float const o = frand(0.0f, 2.0f * float(M_PI)); - if (bot->GetMapId() == anchor->GetMapId()) - return ::Playerbot::BotMovement::SafeNearTeleport(bot, bx, by, bz, o); - return ::Playerbot::BotMovement::SafeTeleport(bot, anchor->GetMapId(), bx, by, bz, o, /*options*/ 0); + // A spot the player can see: the bot does not pop into view there. It appears out of his sight, 110-160 y away, and walks in. + float ex = 0.0f, ey = 0.0f, ez = 0.0f; + bool arrive_on_foot = false; + if (cfg_.natural_moves && !hidden) + { + for (int k = 0; k < 10 && !arrive_on_foot; ++k) + { + float const ang = frand(0.0f, 2.0f * float(M_PI)); + float const d = frand(110.0f, 160.0f); + float const x = anchor->GetPositionX() + std::cos(ang) * d, y = anchor->GetPositionY() + std::sin(ang) * d; + if (Dist2D(x, y, bx, by) > 220.0f) continue; + float const z = map->GetHeight(anchor->GetPhaseShift(), x, y, anchor->GetPositionZ() + 20.0f, true, 60.0f); + if (z <= INVALID_HEIGHT) continue; + Position nav; + if (!::Playerbot::BotMovement::NearestNavPoint(anchor, x, y, z, 4.0f, 5.0f, nav)) continue; + if (InMagma(map, anchor->GetPhaseShift(), nav.GetPositionX(), nav.GetPositionY(), nav.GetPositionZ() + 0.05f)) continue; + if (map->GetLiquidStatus(anchor->GetPhaseShift(), nav.GetPositionX(), nav.GetPositionY(), nav.GetPositionZ() + 0.05f, {}) + & (LIQUID_MAP_IN_WATER | LIQUID_MAP_UNDER_WATER)) continue; + if (anchor->IsWithinLOS(nav.GetPositionX(), nav.GetPositionY(), nav.GetPositionZ() + 1.5f)) continue; + if (in_town && !CompletePathTo(anchor, nav.GetPositionX(), nav.GetPositionY(), nav.GetPositionZ())) continue; + ex = nav.GetPositionX(); ey = nav.GetPositionY(); ez = nav.GetPositionZ(); + arrive_on_foot = true; + } + } + float const sx = arrive_on_foot ? ex : bx, sy = arrive_on_foot ? ey : by, sz = arrive_on_foot ? ez : bz; + bool const moved = bot->GetMapId() == anchor->GetMapId() + ? ::Playerbot::BotMovement::SafeNearTeleport(bot, sx, sy, sz, o) + : ::Playerbot::BotMovement::SafeTeleport(bot, anchor->GetMapId(), sx, sy, sz, o, /*options*/ 0); + if (moved && arrive_on_foot) + if (BotAI* ai = Services::Registry().ai(bot->GetGUID().GetCounter())) + { + ai->walk_order().Set(::Playerbot::V2::WalkOrder::Arrive, bx, by, bz); + ++n_arrived_walking_; + } + return moved; } void WorldBotSpawner::DrivePending(uint32 now_ms, std::vector const&) @@ -509,8 +776,7 @@ void WorldBotSpawner::DrivePending(uint32 now_ms, std::vector const&) placed_[guid_low] = Placed{ now_ms }; ++n_placed_; // A town (capital: no zone level range): most bots stay there and do town things, so it looks busy. - uint8 tlo = 0, thi = 0; - if (!::Playerbot::V2::World::VanillaZoneLevelRange(anchor->GetZoneId(), tlo, thi) && urand(0, 99) < cfg_.town_pct) + if (::Playerbot::V2::World::IsVanillaCapitalZone(anchor->GetZoneId()) && urand(0, 99) < cfg_.town_pct) if (BotAI* ai = Services::Registry().ai(guid_low)) ai->force_activity_mode(BotAI::ActivityMode::Professioning, GameTime::GetGameTimeMS() + urand(45u, 90u) * 60u * 1000u); it = pending_.erase(it); @@ -542,24 +808,29 @@ void WorldBotSpawner::DriveDespawn(uint32 now_ms, std::vector const& anc ++it; } - struct Victim { ObjectGuid guid; float score; }; // score: larger = kicked first + struct Victim { ObjectGuid guid; float score; bool orphan; }; // score: larger = kicked first; orphan: beyond DespawnRadius std::vector victims; uint32 ambient = 0; uint32 far_bots = 0; uint32 all_bots = 0; + uint32 owned_bots = 0; // companions and a player's own bots: never part of the world cap + uint32 tied_bots = 0; // ambient bots in a group, instance or battleground: not part of the world cap either Services::Registry().for_each([&](BotId id, BotRegistryEntry const&) { ObjectGuid const g = ObjectGuid::Create(id); Player* p = ObjectAccessor::FindConnectedPlayer(g); if (!p || !p->IsInWorld()) return; ++all_bots; - if (!owner_.IsAmbientBot(id, p)) return; + if (!owner_.IsAmbientBot(id, p)) { ++owned_bots; return; } // Bots queued for / inside a battleground, in a group or in an instance are not part of the open-world population. if (p->InBattleground() || p->InBattlegroundQueue() || p->GetGroup() || (p->GetMap() && (p->GetMap()->IsDungeon() || p->GetMap()->IsBattlegroundOrArena()))) + { + ++tied_bots; return; + } ++ambient; - if (pending_.contains(uint64(id)) || seeding_.contains(uint64(id))) return; + if (pending_.contains(uint64(id)) || seeding_.contains(uint64(id)) || leaving_.contains(uint64(id))) return; // Distance to the nearest anchor on the bot's own map. float nearest = 1e9f; @@ -568,7 +839,9 @@ void WorldBotSpawner::DriveDespawn(uint32 now_ms, std::vector const& anc nearest = std::min(nearest, Dist2D(p->GetPositionX(), p->GetPositionY(), a.x, a.y)); if (nearest > cfg_.activity_radius) ++far_bots; bool const orphan = nearest > cfg_.despawn_radius; - if (!orphan) + // A bot behind the player (past ActivityRadius, inside DespawnRadius) can be recycled early when the world cap is full and a + // player's bubble still lacks bots; otherwise only orphans go. + if (!orphan && nearest <= cfg_.activity_radius) return; // Not while it is doing something that logging out would break. @@ -581,31 +854,37 @@ void WorldBotSpawner::DriveDespawn(uint32 now_ms, std::vector const& anc return; // Bots of the world-wide filler are only recycled once their setup is done (not mid-pipeline). if (cfg_.global_fill && !owner_.SetupDone(uint64(id))) return; - victims.push_back({ g, nearest }); + victims.push_back({ g, nearest, orphan }); }); ambient_online_ = ambient; global_online_ = far_bots; all_online_ = all_bots; + owned_online_ = owned_bots; + tied_online_ = tied_bots; + // The bubbles' shortfall: how many bots the players' targets still lack. + uint32 deficit = 0; + for (Anchor const& a : anchors) + { + uint32 pend = 0; + for (auto const& [gl, pd] : pending_) + if (pd.anchor == a.guid) ++pend; + uint32 const have = CountAmbientNear(a) + pend; + uint32 const tgt = TargetFor(a); + if (have < tgt) deficit += tgt - have; + } + uint32 const used = ambient + uint32(pending_.size()); + uint32 const free_budget = cfg_.max_bots > used ? cfg_.max_bots - used : 0; // With the world-wide filler a far bot is kept while there is budget; it is only recycled (farthest first) to // make room for the bubble around a real player that still has a deficit. - uint32 limit = cfg_.despawn_per_tick; + uint32 limit = cfg_.despawn_per_tick * (int32(swap_burst_until_ms_ - now_ms) > 0 ? kSwapBurstFactor : 1u); if (cfg_.global_fill && !anchors.empty()) - { - uint32 deficit = 0; - for (Anchor const& a : anchors) - { - uint32 pend = 0; - for (auto const& [gl, pd] : pending_) - if (pd.anchor == a.guid) ++pend; - uint32 const have = CountAmbientNear(a) + pend; - uint32 const tgt = TargetFor(a); - if (have < tgt) deficit += tgt - have; - } - uint32 const used = ambient + uint32(pending_.size()); - uint32 const free_budget = cfg_.max_bots > used ? cfg_.max_bots - used : 0; limit = deficit > free_budget ? std::min(limit, deficit - free_budget) : 0; - } + // At the world cap with a bubble still short: the bots farthest behind the player are recycled even inside DespawnRadius, so the + // zone he walks into fills at once instead of waiting for the ones behind him to age out. + bool const at_cap = used >= cfg_.max_bots && deficit > 0; + if (at_cap) + limit = std::min(std::max(limit, 1u), deficit); // Over the global cap with every bot still near someone: nothing to do here, DriveSpawn simply stops adding. std::sort(victims.begin(), victims.end(), [](Victim const& a, Victim const& b) { return a.score > b.score; }); @@ -613,15 +892,133 @@ void WorldBotSpawner::DriveDespawn(uint32 now_ms, std::vector const& anc for (Victim const& v : victims) { if (n >= limit) break; - if (Services::SessionMgr().LogoutBot(v.guid)) + if (!v.orphan && !at_cap) continue; + Player* vp = ObjectAccessor::FindConnectedPlayer(v.guid); + if (!vp) continue; + bool const was_awake = vp->IsInWorld(); + if (RetireBot(vp, now_ms, anchors)) { ++n; - ++n_despawned_; - placed_.erase(v.guid.GetCounter()); + if (!was_awake || !leaving_.contains(v.guid.GetCounter())) + { + ++n_despawned_; + placed_.erase(v.guid.GetCounter()); + } + if (!v.orphan) ++n_evicted_; } } } +bool WorldBotSpawner::RetireBot(Player* bot, uint32 now_ms, std::vector const& anchors) +{ + constexpr float kSeenYards = 100.0f; // a player this near, with a line of sight, sees the bot + constexpr float kAwayYards = 120.0f; // where a bot with no inn nearby walks to + constexpr float kInnYards = 250.0f; + ObjectGuid const g = bot->GetGUID(); + if (leaving_.contains(g.GetCounter())) + return false; // already on its way out + auto seen_by = [&](Anchor const*& nearest_out) + { + bool seen = false; + float best = 1e9f; + for (Anchor const& a : anchors) + { + if (a.map != bot->GetMapId()) continue; + float const d = Dist2D(bot->GetPositionX(), bot->GetPositionY(), a.x, a.y); + if (d < best) { best = d; nearest_out = &a; } + if (d > kSeenYards || seen) continue; + Player* ap = ObjectAccessor::FindConnectedPlayer(a.guid); + if (ap && ap->IsInWorld() && ap->IsWithinLOS(bot->GetPositionX(), bot->GetPositionY(), bot->GetPositionZ() + 1.5f)) + seen = true; + } + return seen; + }; + Anchor const* near_a = nullptr; + if (!cfg_.natural_moves || !seen_by(near_a) || !near_a) + return Services::SessionMgr().LogoutBot(g); + + // In sight: walk to the nearest inn the bot's side may use, else directly away from the player, then log out once unseen. + float tx = 0.0f, ty = 0.0f, tz = 0.0f; + bool have = false; + if (auto const* inn = ::Playerbot::V2::Travel::TownNpcIndex::Instance().Nearest( + bot->GetMapId(), bot->GetPositionX(), bot->GetPositionY(), bot->GetPositionZ(), UNIT_NPC_FLAG_INNKEEPER, + bot->GetTeam() == ALLIANCE, kInnYards)) + { + tx = inn->x; ty = inn->y; tz = inn->z; + have = true; + } + if (!have) + { + float dx = bot->GetPositionX() - near_a->x, dy = bot->GetPositionY() - near_a->y; + float const len = std::hypot(dx, dy); + if (len < 1.0f) { dx = 1.0f; dy = 0.0f; } else { dx /= len; dy /= len; } + Position nav; + float const wx = bot->GetPositionX() + dx * kAwayYards, wy = bot->GetPositionY() + dy * kAwayYards; + float const wz = bot->GetMap()->GetHeight(bot->GetPhaseShift(), wx, wy, bot->GetPositionZ() + 20.0f, true, 60.0f); + if (wz > INVALID_HEIGHT && ::Playerbot::BotMovement::NearestNavPoint(bot, wx, wy, wz, 15.0f, 8.0f, nav) + && !InMagma(bot->GetMap(), bot->GetPhaseShift(), nav.GetPositionX(), nav.GetPositionY(), nav.GetPositionZ() + 0.05f)) + { + tx = nav.GetPositionX(); ty = nav.GetPositionY(); tz = nav.GetPositionZ(); + have = true; + } + } + BotAI* ai = Services::Registry().ai(g.GetCounter()); + if (!have || !ai) + return Services::SessionMgr().LogoutBot(g); + ai->walk_order().Set(::Playerbot::V2::WalkOrder::Leave, tx, ty, tz); + leaving_[g.GetCounter()] = now_ms; + ++n_left_walking_; + return true; +} + +// Bots that were sent walking away log out once no player can see them, or after a minute (a bot that cannot get out of sight must +// not stay awake for good). +void WorldBotSpawner::DriveLeaving(uint32 now_ms, std::vector const& anchors) +{ + constexpr uint32 kLeaveTimeoutMs = 60000u; + constexpr float kSeenYards = 100.0f; + for (auto it = leaving_.begin(); it != leaving_.end();) + { + ObjectGuid const g = ObjectGuid::Create(it->first); + Player* bot = ObjectAccessor::FindConnectedPlayer(g); + if (!bot || !bot->IsInWorld()) + { + it = leaving_.erase(it); + continue; + } + bool seen = false; + for (Anchor const& a : anchors) + { + if (a.map != bot->GetMapId() || Dist2D(bot->GetPositionX(), bot->GetPositionY(), a.x, a.y) > kSeenYards) continue; + Player* ap = ObjectAccessor::FindConnectedPlayer(a.guid); + if (ap && ap->IsInWorld() && ap->IsWithinLOS(bot->GetPositionX(), bot->GetPositionY(), bot->GetPositionZ() + 1.5f)) + { + seen = true; + break; + } + } + bool const in_trouble = bot->IsInCombat() || bot->GetGroup() || bot->InBattleground() || bot->InBattlegroundQueue(); + if (in_trouble) + { + if (BotAI* ai = Services::Registry().ai(it->first)) ai->walk_order().Clear(); + it = leaving_.erase(it); // not leaving after all: the next despawn pass decides again + continue; + } + if (!seen || getMSTimeDiff(it->second, now_ms) >= kLeaveTimeoutMs) + { + if (BotAI* ai = Services::Registry().ai(it->first)) ai->walk_order().Clear(); + if (Services::SessionMgr().LogoutBot(g)) + { + ++n_despawned_; + placed_.erase(it->first); + } + it = leaving_.erase(it); + continue; + } + ++it; + } +} + void WorldBotSpawner::WindowFor(Anchor const& a, uint8& lo, uint8& hi) const { // Zephras Isle: its own levels, below MinLevel. The island's bots are Skyborne questers; they are not lifted to 10, which @@ -673,7 +1070,8 @@ void WorldBotSpawner::DriveSpawn(uint32 now_ms, std::vector const& ancho next_anchor_ = (next_anchor_ + k + 1) % anchors.size(); - uint32 want = std::min({ target - have, SpawnRateFor(a), + uint32 const burst = int32(swap_burst_until_ms_ - now_ms) > 0 ? kSwapBurstFactor : 1u; + uint32 want = std::min({ target - have, SpawnRateFor(a) * burst, cfg_.max_bots - uint32(ambient_online_ + pending_.size()) }); if (!want) return; @@ -698,7 +1096,7 @@ void WorldBotSpawner::DriveSpawn(uint32 now_ms, std::vector const& ancho std::vector slot_levels; for (uint32 i = 0; i < want; ++i) { - slots.push_back(BotIsAlliance(a.alliance, urand(0, 99), FriendlyPctFor(cfg_.mix, a.zone))); + slots.push_back(BotIsAllianceInZone(a.zone, a.alliance, urand(0, 99), FriendlyPctFor(cfg_.mix, a.zone))); slot_levels.push_back(uint8(urand(lo, hi))); } @@ -721,6 +1119,207 @@ void WorldBotSpawner::DriveSpawn(uint32 now_ms, std::vector const& ancho DriveGlobalSpawn(now_ms, anchors); } +// Where more world bots stand within AreaRadius of one another than the area cap allows (outdoors fewer than in a capital), the +// extras are placed again next to the nearest player, which refuses spots that are full. A few per pass, never a bot in combat, in a +// group, an instance or a battleground, or still being set up. Logged once per move. +void WorldBotSpawner::DriveCrowd(uint32 now_ms, std::vector const& anchors) +{ + constexpr uint32 kPassMs = 10000u; + constexpr size_t kMovesPerPass = 3u; + if ((!cfg_.area_cap_outdoors && !cfg_.area_cap_town) || anchors.empty()) + return; + if (last_crowd_ms_ && getMSTimeDiff(last_crowd_ms_, now_ms) < kPassMs) + return; + last_crowd_ms_ = now_ms; + + std::unordered_map> by_map; + std::unordered_map movable; + Services::Registry().for_each([&](BotId id, BotRegistryEntry const&) + { + Player* p = ObjectAccessor::FindConnectedPlayer(ObjectGuid::Create(id)); + if (!p || !p->IsInWorld() || !p->GetMap() || !owner_.IsAmbientBot(id, p)) return; + if (p->InBattleground() || p->InBattlegroundQueue() || p->GetGroup() || p->GetMap()->IsDungeon() || p->GetMap()->IsBattlegroundOrArena()) + return; + bool const town = ::Playerbot::V2::World::IsVanillaCapitalZone(p->GetZoneId()); + by_map[p->GetMapId()].push_back({ uint64(id), p->GetPositionX(), p->GetPositionY(), town ? cfg_.area_cap_town : cfg_.area_cap_outdoors }); + if (p->IsAlive() && !p->IsInCombat() && !p->IsBeingTeleported() && !p->IsInFlight() && !p->GetTransport() + && owner_.SetupDone(uint64(id)) && !pending_.contains(uint64(id)) && !seeding_.contains(uint64(id))) + movable[uint64(id)] = p; + }); + size_t moved = 0; + for (auto const& [map_id, pts] : by_map) + { + for (uint64 const id : ::Playerbot::V2::Fleet::ExcessBots(pts, cfg_.area_radius, 64u)) + { + if (moved >= kMovesPerPass) return; + auto mv = movable.find(id); + if (mv == movable.end()) continue; + Player* p = mv->second; + Anchor const* near_a = nullptr; + float near_d = 1e9f; + for (Anchor const& a : anchors) + { + if (a.map != map_id) continue; + float const d = Dist2D(p->GetPositionX(), p->GetPositionY(), a.x, a.y); + if (d < near_d) { near_d = d; near_a = &a; } + } + if (!near_a || near_d > cfg_.despawn_radius) continue; // nobody near: the despawn pass logs it out + Player* ap = ObjectAccessor::FindConnectedPlayer(near_a->guid); + if (!ap || !ap->IsInWorld()) continue; + float const fx = p->GetPositionX(), fy = p->GetPositionY(); + if (!PlaceNear(p, ap)) continue; + placed_[id] = Placed{ now_ms }; + ++moved; + ++n_crowd_moved_; + TC_LOG_INFO("playerbot.v2", "[world] crowd: {} ({}) was one of more than the cap within {:.0f} y at ({:.0f},{:.0f}) zone {}, placed again next to {}", + p->GetName(), id, cfg_.area_radius, fx, fy, p->GetZoneId(), ap->GetName()); + } + } +} + +// Residents that stand where they cannot live: in lava (at once), or in a town on ground with no way out of it +// (no complete path to the nearest player three checks running). They are placed again the way a new resident is, next to the nearest player, which now refuses such +// spots. This clears what older builds left in the Great Forge pit (and what sleeps there and wakes); the placement checks stop +// new ones. A few bots per pass, each bot looked at every kStrandedCheckMs. +void WorldBotSpawner::DriveStranded(uint32 now_ms, std::vector const& anchors) +{ + constexpr uint32 kPassMs = 2000u; + constexpr uint32 kProbesPerPass = 3u; // path probes (the costly ones) per pass; lava checks are cheap + constexpr float kTownPathRange = 200.0f; // a town's player this close gives the reference for "a way out" + if (last_stranded_ms_ && getMSTimeDiff(last_stranded_ms_, now_ms) < kPassMs) + return; + last_stranded_ms_ = now_ms; + if (anchors.empty()) + return; + + uint32 probes = 0; + std::vector seen; + Services::Registry().for_each([&](BotId id, BotRegistryEntry const& entry) + { + Player* p = ObjectAccessor::FindConnectedPlayer(ObjectGuid::Create(id)); + if (!p || !p->IsInWorld() || !p->IsAlive() || !p->GetMap() || p->IsBeingTeleported() || p->IsInFlight() || p->GetTransport()) + return; + if (!owner_.IsAmbientBot(id, p) || p->GetGroup() || p->IsInCombat() || p->InBattleground() || p->InBattlegroundQueue() + || p->GetMap()->IsDungeon() || p->GetMap()->IsBattlegroundOrArena()) + return; + if (!owner_.SetupDone(uint64(id)) || pending_.contains(uint64(id)) || seeding_.contains(uint64(id))) + return; + StrandedState& st = stranded_[uint64(id)]; + float const prev_x = st.x, prev_y = st.y, prev_z = st.z; // where the last check found it (zero before the first) + if (!StrandedDue(st, now_ms)) + return; + + // The nearest player on the bot's map: the reference for a way out, and where a stranded bot is put again. + Anchor const* near_a = nullptr; + float near_d = 1e9f; + for (Anchor const& a : anchors) + { + if (a.map != p->GetMapId()) continue; + float const d = Dist2D(p->GetPositionX(), p->GetPositionY(), a.x, a.y); + if (d < near_d) { near_d = d; near_a = &a; } + } + if (!near_a) + return; // nobody on this map: the despawn pass logs it out + + float const px = p->GetPositionX(), py = p->GetPositionY(), pz = p->GetPositionZ(); + bool const magma = InMagma(p->GetMap(), p->GetPhaseShift(), px, py, pz + 0.05f); + bool path_out = true; + bool const in_town = ::Playerbot::V2::World::IsVanillaCapitalZone(p->GetZoneId()); + if (!magma && in_town && near_a->zone == p->GetZoneId() && near_d <= kTownPathRange) + { + if (probes >= kProbesPerPass) + return; // next pass: st stays due + uint32 used = 0; + path_out = ReachableChain(p, near_a->x, near_a->y, near_a->z, 4u, used); + probes += std::max(1u, used); + } + if (!StrandedUpdate(st, magma, path_out, px, py, pz, now_ms)) + return; + + Player* ap = ObjectAccessor::FindConnectedPlayer(near_a->guid); + if (!ap || !ap->IsInWorld() || !PlaceNear(p, ap)) + return; + placed_[uint64(id)] = Placed{ now_ms }; + ++n_stranded_moved_; + // How it got there, so the cause can be read from the log: the rule that last moved it, and the spot the previous check found it + // on (a bot that walked in shows a previous spot nearby; one that was put there or woke there shows none or a far one). + char const* last_rule = entry.ai && entry.ai->last_rule_fired() ? entry.ai->last_rule_fired() : "-"; + TC_LOG_INFO("playerbot.v2", "[world] {} ({}) was {} at ({:.0f},{:.0f},{:.0f}) in zone {}, placed again next to {} | last_rule={} previous_check=({:.0f},{:.0f},{:.0f})", + p->GetName(), uint64(id), magma ? "standing in lava" : "on ground with no way out", px, py, pz, p->GetZoneId(), ap->GetName(), + last_rule, prev_x, prev_y, prev_z); + }); + // Forget bots that are gone. + if (stranded_.size() > 2048u) + for (auto it = stranded_.begin(); it != stranded_.end();) + it = ObjectAccessor::FindConnectedPlayer(ObjectGuid::Create(it->first)) ? std::next(it) : stranded_.erase(it); +} + +// The stuck ledger. The idle watch (Bot/IdleWatch.h) finds a bot standing for 45 s again and again and sends it to a new place each +// time; a bot that still never moves (Dexie: 44 strikes) cannot be helped by a new place. Here, on the world thread, the facts the bot +// worker cannot see are written down once a minute per bot: where it stands against the navmesh, what holds it (root, stun, a +// movement generator), and whether the place it was sent to can be reached from where it stands. A bot standing off the navmesh is +// put onto the nearest walkable ground (the same fix a sleeper gets at wake): every path from a spot with no polygon fails in place. +void WorldBotSpawner::DriveStuckLedger(uint32 now_ms) +{ + constexpr uint32 kPassMs = 5000u, kPerBotMs = 60000u, kMinStrikes = 3u, kBotsPerPass = 3u; + if (last_ledger_ms_ && getMSTimeDiff(last_ledger_ms_, now_ms) < kPassMs) + return; + last_ledger_ms_ = now_ms; + uint32 done = 0; + Services::Registry().for_each([&](BotId id, BotRegistryEntry const& entry) + { + if (done >= kBotsPerPass || !entry.ai) + return; + ::Playerbot::V2::IdleWatch const w = entry.ai->idle_watch(); // a copy: the bot worker writes it + if (w.strikes < kMinStrikes) + return; + Player* p = ObjectAccessor::FindConnectedPlayer(ObjectGuid::Create(id)); + if (!p || !p->IsInWorld() || !p->IsAlive() || !p->GetMap() || p->IsBeingTeleported() || p->IsInFlight() || p->GetTransport()) + return; + if (!owner_.IsAmbientBot(id, p) || p->GetGroup() || p->IsInCombat() || p->InBattleground() || p->InBattlegroundQueue() + || p->GetMap()->IsDungeon() || p->GetMap()->IsBattlegroundOrArena()) + return; + auto it = ledger_ms_.find(uint64(id)); + if (it != ledger_ms_.end() && getMSTimeDiff(it->second, now_ms) < kPerBotMs) + return; + ledger_ms_[uint64(id)] = now_ms; + ++done; + + float const px = p->GetPositionX(), py = p->GetPositionY(), pz = p->GetPositionZ(); + Position near_mesh, wide_mesh; + bool const on_mesh = ::Playerbot::BotMovement::NearestNavPoint(p, px, py, pz, 3.0f, 4.0f, near_mesh); + bool wide = false; + if (!on_mesh) + wide = ::Playerbot::BotMovement::NearestNavPoint(p, px, py, pz, 40.0f, 12.0f, wide_mesh); + char const* reach = "no_target"; + if (w.has_target) + { + uint32 used = 0; + reach = ReachableChain(p, w.tx, w.ty, w.tz, 4u, used) ? "reachable" : "unreachable"; + } + float const ground = p->GetMap()->GetHeight(p->GetPhaseShift(), px, py, pz + 3.0f, true, 20.0f); + TC_LOG_INFO("playerbot.v2", + "[stuck_ledger] {} ({}) zone {} at ({:.1f},{:.1f},{:.1f}) strikes={} on_mesh={} {} ground_z={:.1f} rooted={} stunned={} held_state={} " + "falling={} swimming={} move_gen={} run_speed={:.1f} target=({:.0f},{:.0f},{:.0f}) {} last_rule={}", + p->GetName(), uint64(id), p->GetZoneId(), px, py, pz, w.strikes, on_mesh ? "yes" : "NO", + on_mesh ? "" : (wide ? std::format("(walkable ground {:.0f} y away)", std::hypot(wide_mesh.GetPositionX() - px, wide_mesh.GetPositionY() - py)) : std::string("(none within 40 y)")), + ground > INVALID_HEIGHT ? ground : -999.f, p->HasUnitMovementFlag(MOVEMENTFLAG_ROOT) ? 1 : 0, p->HasUnitState(UNIT_STATE_STUNNED) ? 1 : 0, + p->HasUnitState(UNIT_STATE_ROOT | UNIT_STATE_CONFUSED | UNIT_STATE_FLEEING | UNIT_STATE_CONTROLLED) ? 1 : 0, + p->IsFalling() ? 1 : 0, p->IsInWater() ? 1 : 0, uint32(p->GetMotionMaster()->GetCurrentMovementGeneratorType()), + p->GetSpeed(MOVE_RUN), w.tx, w.ty, w.tz, reach, + entry.ai->last_rule_fired() ? entry.ai->last_rule_fired() : "-"); + if (!on_mesh && wide) + { + Playerbot::BotMovement::SafeNearTeleport(p, wide_mesh.GetPositionX(), wide_mesh.GetPositionY(), wide_mesh.GetPositionZ() + 0.3f, + p->GetOrientation(), /*navmesh_point*/ true); + TC_LOG_INFO("playerbot.v2", "[stuck_ledger] {} was off the navmesh, moved onto walkable ground", p->GetName()); + } + }); + if (ledger_ms_.size() > 2048u) + for (auto it = ledger_ms_.begin(); it != ledger_ms_.end();) + it = ObjectAccessor::FindConnectedPlayer(ObjectGuid::Create(it->first)) ? std::next(it) : ledger_ms_.erase(it); +} + void WorldBotSpawner::DriveGraduation(uint32 now_ms) { // Every few seconds, at most two bots per pass: a bot reaching level 10 on the isle is moved the way a new level-10 bot is @@ -820,8 +1419,7 @@ void WorldBotSpawner::DriveWake(uint32 now_ms, Anchor const& a, uint32 want) uint8 lo = 0, hi = 0; WindowFor(a, lo, hi); float const r = cfg_.wake_radius; - uint8 tlo = 0, thi = 0; - bool const town = !::Playerbot::V2::World::VanillaZoneLevelRange(a.zone, tlo, thi); + bool const town = ::Playerbot::V2::World::IsVanillaCapitalZone(a.zone); query_inflight_ = true; query_started_ms_ = now_ms; queries_.AddCallback(CharacterDatabase.AsyncQuery(Trinity::StringFormat( @@ -833,7 +1431,7 @@ void WorldBotSpawner::DriveWake(uint32 now_ms, Anchor const& a, uint32 want) a.map, uint32(lo), uint32(hi), a.x - r, a.x + r, a.y - r, a.y + r, SkyborneRaceClause(Skyborne::IsOnIsle(a.map)), town ? Trinity::StringFormat("AND c.zone = {} ", a.zone) : std::string(), // a capital wakes its own zone only (WakeSelect.h) - std::max(want * 6u, 30u)).c_str()) + std::max(want * 10u, 60u)).c_str()) .WithCallback([this, a, want, town](QueryResult res) { query_inflight_ = false; @@ -862,13 +1460,13 @@ void WorldBotSpawner::DriveWake(uint32 now_ms, Anchor const& a, uint32 want) if (Player* ap = ObjectAccessor::FindConnectedPlayer(a.guid); ap && ap->GetMap()) c.wet = (ap->GetMap()->GetLiquidStatus(ap->GetPhaseShift(), f[4].GetFloat(), f[5].GetFloat(), f[7].GetFloat() + 0.05f, {}) & (LIQUID_MAP_IN_WATER | LIQUID_MAP_UNDER_WATER)) != 0; - c.faction_ok = IsAllianceRace(f[2].GetUInt8()) == BotIsAlliance(a.alliance, urand(0, 99), FriendlyPctFor(cfg_.mix, a.zone)); + c.faction_ok = IsAllianceRace(f[2].GetUInt8()) == BotIsAllianceInZone(a.zone, a.alliance, urand(0, 99), FriendlyPctFor(cfg_.mix, a.zone)); cands.push_back(c); } while (res->NextRow()); // Never more than the target still lacks, and never past the global cap. uint32 const room = cfg_.max_bots > uint32(ambient_online_ + pending_.size()) ? cfg_.max_bots - uint32(ambient_online_ + pending_.size()) : 0u; - for (uint64 const guid : SelectWake(cands, rule, std::min(want, room))) + for (uint64 const guid : SelectWakeShared(cands, rule, std::min(want, room), AwakeByZone(a))) { auto lr = Services::SessionMgr().LoginBot(ObjectGuid::Create(guid)); if (!lr.ok) { ++n_login_failed_; continue; } @@ -1029,7 +1627,7 @@ void WorldBotSpawner::OnWorldTick(uint32 now_ms) WorldLeash::Clear(); return; } - if (uint32(sConfigMgr->GetIntDefault("Playerbot.Population.TotalTarget", 0)) > 0) + if (uint32(sConfigMgr->GetIntDefault("Playerbot.Population.TotalTarget", 0, true)) > 0) { if (!warned_exclusive_) { @@ -1122,9 +1720,19 @@ void WorldBotSpawner::OnWorldTick(uint32 now_ms) uint64 const k = a.guid.GetCounter(); seen.insert(k); auto it = prev_anchor_.find(k); - if (it != prev_anchor_.end() && cfg_.zone_grace_ms - && (it->second.map != a.map || Dist2D(it->second.x, it->second.y, a.x, a.y) > cfg_.despawn_radius)) - ghosts_.push_back({ it->second, now_ms + cfg_.zone_grace_ms }); + if (it != prev_anchor_.end() && (it->second.map != a.map || Dist2D(it->second.x, it->second.y, a.x, a.y) > cfg_.despawn_radius)) + { + // He jumped (teleport, hearth, flight end) and is still in the open world: the bots around the place he left are + // not kept for the long grace, which blocked the new place from filling (the cap was full of them); a short one + // covers a hop back, and the swap runs at a higher rate for a minute (SwapBurstMs). + if (cfg_.jump_grace_ms) + ghosts_.push_back({ it->second, now_ms + cfg_.jump_grace_ms }); + swap_burst_until_ms_ = now_ms + kSwapBurstMs; + wake_dry_until_.clear(); // a dry wake pass at the old place says nothing about the new one + TC_LOG_INFO("playerbot.v2", "[world] jump: player moved {:.0f} y (map {} -> {}): old bots kept {} s, swap burst for {} s", + it->second.map != a.map ? -1.0f : Dist2D(it->second.x, it->second.y, a.x, a.y), it->second.map, a.map, + cfg_.jump_grace_ms / 1000u, kSwapBurstMs / 1000u); + } prev_anchor_[k] = a; } for (auto it = prev_anchor_.begin(); it != prev_anchor_.end();) @@ -1157,6 +1765,10 @@ void WorldBotSpawner::OnWorldTick(uint32 now_ms) DriveSpawn(now_ms, anchors); DriveSeed(now_ms); DriveGraduation(now_ms); + DriveStranded(now_ms, anchors); + DriveStuckLedger(now_ms); + DriveLeaving(now_ms, anchors); + DriveCrowd(now_ms, anchors); last_tick_cost_ms_ = getMSTimeDiff(t0, getMSTime()); max_tick_cost_ms_ = std::max(max_tick_cost_ms_, last_tick_cost_ms_); @@ -1166,6 +1778,19 @@ void WorldBotSpawner::OnWorldTick(uint32 now_ms) if (ambient_online_ == 0 && !baseline_rss_kb_) baseline_rss_kb_ = ProcessRssKb(); // first reading only: later ones include memory the process keeps after logouts + // Every five minutes: which idle rules have won the bots' ticks so far (busiest 25), and the town-life and quest-spot rules by name + // even at zero. A show that never starts is then visible as a rule that never fires, not a mystery. + if (Services::Initialized() && (!last_rules_ms_ || getMSTimeDiff(last_rules_ms_, now_ms) >= 300000u)) + { + last_rules_ms_ = now_ms; + std::string row; + for (auto const& [name, n] : Services::IdleRules().FireCensus(25, { "idle:inn_rest", "idle:mailbox", "idle:town_duel", "idle:campfire", + "idle:quest_site_share", "idle:yell_lfg", "idle:rpg_visit", + "idle:rpg_city_trip", "idle:rpg_ah_trip" })) + row += Trinity::StringFormat(" {}={}", name, n); + TC_LOG_INFO("playerbot.v2", "[rules] fired since start:{}", row); + } + if (!last_report_ms_ || getMSTimeDiff(last_report_ms_, now_ms) >= kReportMs) { last_report_ms_ = now_ms; diff --git a/src/modules/PlayerbotV2/Fleet/WorldBotSpawner.h b/src/modules/PlayerbotV2/Fleet/WorldBotSpawner.h index ff34432903..80d082ebbc 100644 --- a/src/modules/PlayerbotV2/Fleet/WorldBotSpawner.h +++ b/src/modules/PlayerbotV2/Fleet/WorldBotSpawner.h @@ -26,6 +26,8 @@ #include #include +#include "AreaCap.h" +#include "StrandedWatch.h" #include "WorldLoadFacts.h" #include "WorldFactionMix.h" #include "PoolBalance.h" @@ -85,6 +87,12 @@ private: bool seed_roster = false; // build the sleeping roster up to PoolMax without waiting for a player to arrive uint32 seed_in_flight = 8; // seeded bots set up at the same time uint32 pool_max = 400; // ambient characters allowed to exist (online or not) + bool natural_moves = true; // bots arrive on foot from out of sight and leave toward an inn before they log out + bool day_rhythm = true; // scale the bubble target by the hour of the day (Fleet/DayRhythm.h) + uint32 jump_grace_ms = 20000; // bots around the place a player jumped away from are kept this long (an instance trip: ZoneGraceSec) + uint32 area_cap_outdoors = 14; // most world bots within area_radius of one another outdoors (0 = no cap; Fleet/AreaCap.h) + uint32 area_cap_town = 40; // the same in a capital + float area_radius = 45.0f; uint32 pool_horde_pct = 50; // share of the roster that should be Horde, in every level bracket (PoolBalance.h) uint32 skyborne_seed_pct = 5; // share of the roster seeds that are level 1-9 Skyborne residents of Zephras Isle (Classic 1.60) }; @@ -129,11 +137,22 @@ private: void DriveGlobalSpawn(uint32 now_ms, std::vector const& anchors); // Classic 1.60: a Skyborne bot that reached level 10 on Zephras Isle is carried once to a leveling town (the isle has no exit). void DriveGraduation(uint32 now_ms); + // Residents standing in lava or on ground with no way out are placed again (Fleet/StrandedWatch.h). + void DriveStranded(uint32 now_ms, std::vector const& anchors); + void DriveStuckLedger(uint32 now_ms); // bots the idle watch keeps finding standing: why they cannot move, and back onto the mesh if off it + // A bot the spawner no longer wants: out of every player's sight it logs out at once; in sight it first walks to the nearest inn + // (or away from the player) and logs out once it is out of view or after a minute. True when the bot was dealt with (logged out + // or sent walking). + bool RetireBot(Player* bot, uint32 now_ms, std::vector const& anchors); + void DriveLeaving(uint32 now_ms, std::vector const& anchors); + // A crowd over the area cap sends its extras to other spots next to the nearest player (Fleet/AreaCap.h). + void DriveCrowd(uint32 now_ms, std::vector const& anchors); // Level range of the bots around this anchor: its zone's, lifted to MinLevel, except on Zephras Isle (Fleet/SkyborneIsle.h). void WindowFor(Anchor const& a, uint8& lo, uint8& hi) const; bool PlaceNear(Player* bot, Player* anchor); void StepOffStack(Player* bot); uint32 CountAmbientNear(Anchor const& a) const; + std::unordered_map AwakeByZone(Anchor const& a) const; uint32 SpawnRateFor(Anchor const& a) const; uint32 TargetFor(Anchor const& a) const; // bubble size for this anchor: city_bots / zone_bots / bots_per_player @@ -177,6 +196,20 @@ private: struct Seeding { uint32 started_ms = 0; uint32 setup_done_ms = 0; }; std::unordered_map seeding_; uint32 last_grad_ms_ = 0; + uint32 last_stranded_ms_ = 0; + uint32 last_ledger_ms_ = 0; + std::unordered_map ledger_ms_; // per bot: when its last ledger line was written + uint32 last_crowd_ms_ = 0; + std::unordered_map leaving_; // bot guid low -> module ms when it was sent walking away + uint64 n_arrived_walking_ = 0; + uint64 n_left_walking_ = 0; + uint32 swap_burst_until_ms_ = 0; // module ms until which a jump (teleport / hearth) swaps the bubble at a higher rate + uint32 owned_online_ = 0; // companions and a player's own bots in the world (outside the world cap) + uint32 tied_online_ = 0; // ambient bots in a group, instance or battleground (outside the world cap) + uint64 n_evicted_ = 0; // bots recycled early, inside DespawnRadius, to make room at the world cap + uint64 n_crowd_moved_ = 0; + uint64 n_stranded_moved_ = 0; // residents found in lava or with no way out and placed again + std::unordered_map stranded_; uint64 n_graduated_ = 0; // Skyborne bots moved off Zephras Isle at level 10 uint64 n_seeded_ = 0; // residents created by the seeding pass and put to sleep uint64 n_woken_ = 0; // sleeping residents logged in at their saved position @@ -189,6 +222,8 @@ private: uint32 all_online_ = 0; // every bot in the world this tick (ambient, raid, BG, companions) uint32 global_online_ = 0; // ambient bots farther than ActivityRadius from every player (this tick) // Why nothing was spawned, since start (also in the [world] line). + uint32 last_rules_ms_ = 0; + uint32 soak_anchors_ = 0; // configured soak anchors (bots standing in for a player) found this tick uint32 anchors_in_instance_ = 0; // real players skipped this tick: in an instance, raid, battleground or arena uint64 n_no_match_ = 0; // slots with no offline pool bot of the wanted faction and level range uint64 n_pool_full_ = 0; // slots that could not create a character: PoolMax reached diff --git a/src/modules/PlayerbotV2/Fleet/WorldFactionMix.h b/src/modules/PlayerbotV2/Fleet/WorldFactionMix.h index e84e65585f..bf410edf52 100644 --- a/src/modules/PlayerbotV2/Fleet/WorldFactionMix.h +++ b/src/modules/PlayerbotV2/Fleet/WorldFactionMix.h @@ -1,7 +1,7 @@ // WorldFactionMix - share of an anchor's own faction among the world bots around it, by zone: the pure rule behind // WorldBotSpawner (new spawns and wakes). // -// Karrz, 2026-10-11: in the contested zones (Plaguelands around Light's Hope Chapel, Stranglethorn, Hillsbrad, Arathi...) there must +// the owner, 2026-10-11: in the contested zones (Plaguelands around Light's Hope Chapel, Stranglethorn, Hillsbrad, Arathi...) there must // be a real enemy presence at the player's level for world PvP, while capitals and home zones stay mostly the player's own faction. // Zones are data (kZoneTiers); a zone not listed keeps the plain FriendlyPct. The level window is not touched here: enemy bots // are drawn from the same level range as friendly ones. @@ -55,7 +55,7 @@ inline ZoneTier TierOfZone(uint32_t zone) struct FactionMix { - uint32_t default_pct = 80; // Playerbot.World.FriendlyPct: zones not listed + uint32_t default_pct = 80; // Playerbot.World.FriendlyPct: zones not listed (these struct values are test data; the spawner and conf ship 100) uint32_t capital_pct = 90; // Playerbot.World.CapitalFriendlyPct uint32_t home_pct = 90; // Playerbot.World.HomeFriendlyPct uint32_t border_pct = 75; // Playerbot.World.BorderFriendlyPct @@ -86,4 +86,25 @@ inline bool BotIsAlliance(bool anchor_alliance, uint32_t roll, uint32_t pct) return roll < pct ? anchor_alliance : !anchor_alliance; } +// The faction a capital city belongs to (playtest, 2026-10-12: a level 60 Horde troll walked around Ironforge among level 21s; a real +// Horde player does not stroll through an Alliance capital). 1 = Alliance, 2 = Horde, 0 = not a capital. +inline int CapitalFactionOfZone(uint32_t zone) +{ + switch (zone) + { + case 1519: case 1537: case 1657: return 1; // Stormwind, Ironforge, Darnassus + case 1637: case 1497: case 1638: return 2; // Orgrimmar, Undercity, Thunder Bluff + default: return 0; + } +} + +// Faction of one bot around an anchor standing in `zone`: in a capital it is always the capital's own faction, whoever the anchor is +// (a Horde player visiting Ironforge meets Alliance bots); elsewhere the zone share relative to the anchor. +inline bool BotIsAllianceInZone(uint32_t zone, bool anchor_alliance, uint32_t roll, uint32_t pct) +{ + if (int const capital = CapitalFactionOfZone(zone)) + return capital == 1; + return BotIsAlliance(anchor_alliance, roll, pct); +} + } // namespace Playerbot::V2::Fleet diff --git a/src/modules/PlayerbotV2/Fleet/WorldLeash.h b/src/modules/PlayerbotV2/Fleet/WorldLeash.h index d765c887cf..273e7e2fdf 100644 --- a/src/modules/PlayerbotV2/Fleet/WorldLeash.h +++ b/src/modules/PlayerbotV2/Fleet/WorldLeash.h @@ -1,5 +1,5 @@ // WorldLeash - the open-world anchors (real players and recently left spots) as the world bot spawner sees them, -// published for the bot AI worker threads. An ambient bot that picks a quest objective far from every anchor on its map +// published for the bot bot worker threads. An ambient bot that picks a quest objective far from every anchor on its map // would walk out of the population bubble and be logged out as an orphan (levelling lost, a new bot spawned instead); // idle:pursue_quest_goal asks LeashBlocks() and takes another objective. #pragma once diff --git a/src/modules/PlayerbotV2/Group/GroupSnapshot.cpp b/src/modules/PlayerbotV2/Group/GroupSnapshot.cpp index b3781c2267..4baf74db4a 100644 --- a/src/modules/PlayerbotV2/Group/GroupSnapshot.cpp +++ b/src/modules/PlayerbotV2/Group/GroupSnapshot.cpp @@ -70,6 +70,10 @@ GroupMemberSummary const* GroupSnapshotView::tank() const // Skip dead tanks — every caller (heal, beacon, lifebloom, augment buff, // pet send, threat dump) needs a living target. Battle-rez logic uses // dead_member() instead. + // The same answer as the PvE coordinator's main tank (PveGroupCoordinator): the raid-frame Main Tank flag first, else the first + // live tank, so the threat hold, the healers and the pull gates agree on who the tank is. + for (auto const& m : g_->members) + if (m.is_main_tank && m.online && m.hp > 0) return &m; for (auto const& m : g_->members) if (m.role == Role::Tank && m.online && m.hp > 0) return &m; return nullptr; diff --git a/src/modules/PlayerbotV2/Group/GroupSnapshot.h b/src/modules/PlayerbotV2/Group/GroupSnapshot.h index 28ab3fac79..e1ccfa302e 100644 --- a/src/modules/PlayerbotV2/Group/GroupSnapshot.h +++ b/src/modules/PlayerbotV2/Group/GroupSnapshot.h @@ -159,7 +159,7 @@ public: // Only the leader / raid assistants can set icons, and bots set them only // on an owner's command or as the leader's in-combat auto-skull // (State_InGroup), so a mark is the leader's / owner's call. Read by the - // DPS threat hold (opens on a marked unpulled mob after 4s) and the raid + // DPS threat hold (opens on a marked unpulled mob after 8 s, kMaxUnpulledOwnerWaitMs; a party's DPS open 6 s after the tank's first hit) and the raid // kill focus (PveGroupCoordinator). ObjectGuid explicit_kill_mark() const { diff --git a/src/modules/PlayerbotV2/Group/GroupSnapshotBuilder.cpp b/src/modules/PlayerbotV2/Group/GroupSnapshotBuilder.cpp index 3d5673684f..d010f775bf 100644 --- a/src/modules/PlayerbotV2/Group/GroupSnapshotBuilder.cpp +++ b/src/modules/PlayerbotV2/Group/GroupSnapshotBuilder.cpp @@ -337,8 +337,9 @@ std::shared_ptr GroupSnapshotBuilder::Build(Player* p, Snap { m.is_casting = true; m.casting_spell = casting->m_spellInfo->Id; - if (Unit* tgt = casting->m_targets.GetUnitTarget()) - m.casting_target = tgt->GetGUID(); + // By GUID: the Spell's raw object pointer is only refreshed on the spell's own update, so a target that despawned or died in the + // last map update (a whelp, n33 onyxia_full crash 02:38) is a dangling pointer here. + m.casting_target = casting->m_targets.GetUnitTargetGUID(); m.casting_end_ms = GameTime::GetGameTimeMS() + static_cast(std::max(casting->GetRemainingCastTime(), 0)); // [raid_rez] cast state: a resurrection in flight (MC 2026-10-08: every healer waited on a rez cast that never @@ -356,7 +357,7 @@ std::shared_ptr GroupSnapshotBuilder::Build(Player* p, Snap } if (due) { - Unit* rt = casting->m_targets.GetUnitTarget(); + Unit* rt = ObjectAccessor::GetUnit(*mp, casting->m_targets.GetUnitTargetGUID()); TC_LOG_INFO("playerbot.v2", "[raid_rez] cast state: {} spell {} state={} time_left={} ms target={} alive={} ghost={} resurrect_requested={}", mp->GetName(), casting->m_spellInfo->Id, uint32(casting->getState()), casting->GetRemainingCastTime(), diff --git a/src/modules/PlayerbotV2/Group/GroupSnapshotBuilder.h b/src/modules/PlayerbotV2/Group/GroupSnapshotBuilder.h index e15ab47443..00043a26c8 100644 --- a/src/modules/PlayerbotV2/Group/GroupSnapshotBuilder.h +++ b/src/modules/PlayerbotV2/Group/GroupSnapshotBuilder.h @@ -1,6 +1,6 @@ // GroupSnapshotBuilder - Constructs a GroupSnapshot for a member's bot. Runs // on the world thread once per snapshot publish; the resulting object is -// immutable and safe for AI worker consumption. +// immutable and safe for bot worker consumption. #pragma once diff --git a/src/modules/PlayerbotV2/NOTICE.md b/src/modules/PlayerbotV2/NOTICE.md index 1561f764d7..7e72bc21ef 100644 --- a/src/modules/PlayerbotV2/NOTICE.md +++ b/src/modules/PlayerbotV2/NOTICE.md @@ -10,7 +10,7 @@ Public License version 2 (`COPYING` at the repository root), the same terms as T module layout and most of the bot brain, travel and fleet code come from there. - **Classic (1.12) adaptation, raid, battleground, world-population and auction house work** was added for WoW Forever by Karrz (Karrz1). -- **ike3 / cmangos playerbots** (Ike's mangosbot for cMaNGOS; GPL-2.0): several behaviours +- **ike3 / cmangos playerbots** (ike3's mangosbot, https://github.com/ike3/mangosbot-bots, for cMaNGOS; GPL-2.0): several behaviours (raid brain, speech lines, rpg, battleground paths and objectives, travel) were ported from a VMaNGOS-based bot tree that derives from ike3 bots, VMaNGOS and cMaNGOS (all GPL-2.0). Source comments name the routines they follow. diff --git a/src/modules/PlayerbotV2/Persistence/PlayerbotMigrationMgr.cpp b/src/modules/PlayerbotV2/Persistence/PlayerbotMigrationMgr.cpp index 36625c2f49..01e6269d3c 100644 --- a/src/modules/PlayerbotV2/Persistence/PlayerbotMigrationMgr.cpp +++ b/src/modules/PlayerbotV2/Persistence/PlayerbotMigrationMgr.cpp @@ -37,7 +37,7 @@ auto& Db() { return CharacterDatabase; } std::string const& SharedDb() { static std::string const db = - sConfigMgr->GetStringDefault("Playerbot.SharedDatabase", "playerbot"); + sConfigMgr->GetStringDefault("Playerbot.SharedDatabase", "playerbot", true); return db; } diff --git a/src/modules/PlayerbotV2/PlayerbotV2.cpp b/src/modules/PlayerbotV2/PlayerbotV2.cpp index e00b3f932b..d31e56d66c 100644 --- a/src/modules/PlayerbotV2/PlayerbotV2.cpp +++ b/src/modules/PlayerbotV2/PlayerbotV2.cpp @@ -48,6 +48,7 @@ #include "Bot/BotCommandParser.h" #include "Bot/BotChatReactor.h" #include "Bot/GroupOrderText.h" +#include "Bot/AddonHint.h" #include "Bot/BotTextMgr.h" #include "Chat.h" #include "Bot/BotIntent.h" @@ -64,6 +65,9 @@ #include "GroupReference.h" #include "GroupMgr.h" #include "ObjectAccessor.h" +#include "PathGenerator.h" +#include "Pet.h" +#include "Fleet/PetSnap.h" #include "WorldSession.h" #include "Bot/BotCommandParser.h" #include "Threading/SnapshotPublisher.h" @@ -129,6 +133,9 @@ bool VerifyResetClearsAll(); namespace Playerbot::V2 { +// Players still to be told about the add-on (world thread only: the login hook, the add-on's hello and the world update all run there). +static AddonHintTracker g_addon_hints; + namespace { // Coarse spatial bucket key for the per-tick real-player proximity set. @@ -212,7 +219,7 @@ void DriveTeleportAck(Player* p) // 1-2y drift. Snapping aggressively (small threshold, both // directions) caused visible twitching: a moving bot finishes its // spline → Idle generator → we pull Z down a fraction → next tick -// the AI emits move_to and the spline starts again, repeat. Real +// the bot logic emits move_to and the spline starts again, repeat. Real // players get small Z corrections via client-side ground snap and // MSG_MOVE_HEARTBEAT updates; we approximate the catastrophic case // only. @@ -646,7 +653,7 @@ void GlobalStuckRescue(Player* p, BotAI* ai) g_global_stuck[key] = st; } -// Companion tank threat (Karrz's AiPlayerbot.TankThreatMultiplier on his +// Companion tank threat (the owner's AiPlayerbot.TankThreatMultiplier on his // VMaNGOS bots): a grouped bot owned by a human whose current duty is tank // generates Playerbot.TankThreatMultiplier x threat, so the owner and the DPS // bots rarely pull aggro off it. Duty = the PvE coordinator's order when one @@ -717,9 +724,9 @@ void UpdateCastSpeed(Player* p, BotSnapshot const& snap, ConfigReader::CastPacin cfg.enabled ? CastSkillOffsetPct(snap.guid, cfg.variance_pct) : 0); } -// PvP reaction floor (Playerbot.Pacing.PvpReactionDelayMs, Karrz's AiPlayerbot.PvpReactionDelay): +// PvP reaction floor (Playerbot.Pacing.PvpReactionDelayMs, the owner's AiPlayerbot.PvpReactionDelay): // while the bot is in PvP - a battleground/arena, an active duel, or in combat with players -// (ClassifyCastContext BG/WorldPvp) - its AI tick and snapshot period is at least the floor, +// (ClassifyCastContext BG/WorldPvp) - its bot tick and snapshot period is at least the floor, // so a fleet does not out-react real players. PvE (raid/dungeon/world) never gets it. Survival // bypass: a dead/ghost bot (release, resurrection) or one below 35% HP is ticked at its normal // tier period, so healing, defensives and ress are not starved. World thread (publish pass). @@ -766,7 +773,7 @@ void Module::Init() } // The bots' speech lines (shared DB, migration 0019). Loaded before any bot can tick; read-only - // afterwards, so AI workers and the world thread read it without a lock. + // afterwards, so bot workers and the world thread read it without a lock. BotTextMgr::instance().Load(); // Bring up Services (SnapshotPublisher, IntentQueue, AiWorkerPool, @@ -790,7 +797,7 @@ void Module::Init() Services::Owners().GetOwner(p->GetGUID().GetCounter()).account_id != 0); }; - // Register class/spec rotations (single-threaded; runs before AI workers + // Register class/spec rotations (single-threaded; runs before bot workers // dispatch ticks). Read-only afterwards; safe for concurrent lookup. Combat::RegisterAllRotations(); @@ -1030,28 +1037,77 @@ void Module::Shutdown() initialized_ = false; } +// Pets of playerbots that cannot walk to their owner are set down next to them (Fleet/PetSnap.h), the way a player's pet ends up beside +// its owner when it falls behind. Each pet is looked at every kPetSnapCheckMs; runs on the world thread, before the maps update. +static void DrivePetSnap(uint32 now_ms) +{ + static std::unordered_map state; + Services::Registry().for_each([&](BotId id, BotRegistryEntry const&) + { + Player* owner = ObjectAccessor::FindConnectedPlayer(ObjectGuid::Create(id)); + if (!owner || !owner->IsInWorld() || !owner->IsAlive() || !owner->GetMap() || owner->IsBeingTeleported() || owner->IsInFlight()) + return; + Pet* pet = owner->GetPet(); + if (!pet || !pet->IsInWorld() || !pet->IsAlive() || pet->GetMap() != owner->GetMap() || pet->IsInCombat()) + return; + Fleet::PetSnapState& st = state[uint64(id)]; + if (!Fleet::PetSnapDue(st, now_ms)) + return; + if (pet->GetExactDist(owner) <= Fleet::kPetSnapMinGap) + { + Fleet::PetSnapUpdate(st, false, now_ms); + return; + } + PathGenerator pg(pet); + ::Playerbot::BotMovement::SehSafeCalculatePath(pg, owner->GetPositionX(), owner->GetPositionY(), owner->GetPositionZ()); + PathType const type = pg.GetPathType(); + G3D::Vector3 const& end = pg.GetActualEndPosition(); + float const dx = end.x - owner->GetPositionX(), dy = end.y - owner->GetPositionY(), dz = end.z - owner->GetPositionZ(); + float const end_gap = std::sqrt(dx * dx + dy * dy + dz * dz); + bool const unreachable = (type & (PATHFIND_NOPATH | PATHFIND_SHORTCUT)) || ((type & PATHFIND_INCOMPLETE) && end_gap > 4.0f); + if (!Fleet::PetSnapUpdate(st, unreachable, now_ms)) + return; + pet->StopMoving(); + pet->NearTeleportTo(Position(owner->GetPositionX(), owner->GetPositionY(), owner->GetPositionZ(), owner->GetOrientation())); + TC_LOG_INFO("playerbot.v2", "[pet_snap] {}'s pet {} had no way to its owner at ({:.0f},{:.0f},{:.0f}), set down next to {}", + owner->GetName(), pet->GetName(), owner->GetPositionX(), owner->GetPositionY(), owner->GetPositionZ(), owner->GetName()); + }); + if (state.size() > 2048u) + for (auto it = state.begin(); it != state.end();) + it = ObjectAccessor::FindConnectedPlayer(ObjectGuid::Create(it->first)) ? std::next(it) : state.erase(it); +} + void Module::OnWorldUpdate(std::chrono::milliseconds diff) { if (!initialized_) return; static std::chrono::milliseconds total{0}; // #5 Phase 4: next_version is read-modify-write per built snapshot. Under // parallel-by-Map* Build a plain ++ is a torn counter (duplicate/garbage - // versions break the AI worker's staleness/version checks). Versions need + // versions break the bot worker's staleness/version checks). Versions need // only be UNIQUE + monotonic, not contiguous, so an atomic fetch_add is // the race-free fix. Pre-assigned per bot before the parallel region, so // the parallel tasks never touch this counter themselves. static std::atomic next_version{1}; static TickId next_tick = 1; total += diff; + { + static std::chrono::milliseconds last_hint_check{0}; + if (total - last_hint_check >= std::chrono::milliseconds(2000)) + { + last_hint_check = total; + SendDueAddonHints(); + } + } ::Playerbot::Diagnostics::Scenario::Tick(std::uint32_t(diff.count())); // bot scenario tests (.playerbot scenario) - // [cast_state] (Karrz, WSG start room 2026-10-11: a healer stood with the casting animation on while casting nothing). Twice a + // [cast_state] (playtest, WSG start room 2026-10-11: a healer stood with the casting animation on while casting nothing). Twice a // second, every bot in a battleground: a line when the spell it is casting changes (spell id, generic or channel, 0 = none), and a // [cast_stale] line when the server holds no cast at all but the unit data still names a channel spell: what a client draws as a // cast that never ends. The log answers which of the two it was; nothing is cleared here. { static std::chrono::milliseconds last_cast_check{0}; static std::unordered_map cast_seen; + static std::unordered_map cast_since; static std::unordered_map stale_logged_ms; static uint32 cast_lines = 0; if (total - last_cast_check >= std::chrono::milliseconds(500)) @@ -1062,18 +1118,32 @@ void Module::OnWorldUpdate(std::chrono::milliseconds diff) { if (!e.ai) return; Player* p = ObjectAccessor::FindConnectedPlayer(ObjectGuid::Create(id)); - if (!p || !p->IsInWorld() || !p->GetMap() || !p->GetMap()->IsBattleground()) { cast_seen.erase(id); return; } + if (!p || !p->IsInWorld() || !p->GetMap() || !(p->GetMap()->IsBattleground() || p->GetMap()->IsRaid())) { cast_seen.erase(id); cast_since.erase(id); return; } Spell const* gen = p->GetCurrentSpell(CURRENT_GENERIC_SPELL); Spell const* chan = p->GetCurrentSpell(CURRENT_CHANNELED_SPELL); uint32 const now_spell = chan ? chan->GetSpellInfo()->Id : gen ? gen->GetSpellInfo()->Id : 0u; uint32& seen = cast_seen[id]; - if (seen != now_spell && cast_lines < 1500) + if (seen != now_spell) { - ++cast_lines; - TC_LOG_INFO("playerbot.v2", "[cast_state] {} spell {} -> {} ({}) casting_state={} mounted={}", p->GetName(), seen, now_spell, - chan ? "channel" : gen ? "generic" : "none", p->HasUnitState(UNIT_STATE_CASTING), p->IsMounted()); + cast_since[id] = now_ms; + if (cast_lines < 1500) + { + ++cast_lines; + TC_LOG_INFO("playerbot.v2", "[cast_state] {} spell {} -> {} ({}) casting_state={} mounted={} combat={}", p->GetName(), seen, now_spell, + chan ? "channel" : gen ? "generic" : "none", p->HasUnitState(UNIT_STATE_CASTING), p->IsMounted(), p->IsInCombat()); + } seen = now_spell; } + else if (now_spell && cast_since[id] && now_ms - cast_since[id] >= 8000u && cast_lines < 1500) + { + // One cast that has been the current spell for 8 s or more: a cast bar that is not filling. + ++cast_lines; + cast_since[id] = now_ms; + Spell const* cur = chan ? chan : gen; + TC_LOG_INFO("playerbot.v2", "[cast_long] {} still on spell {} ({}) state={} timer={} ms target={} casting_state={} combat={}", p->GetName(), now_spell, + chan ? "channel" : "generic", uint32(cur->getState()), cur->GetTimer(), cur->m_targets.GetUnitTargetGUID().GetCounter(), + p->HasUnitState(UNIT_STATE_CASTING), p->IsInCombat()); + } if (!gen && !chan && !p->HasUnitState(UNIT_STATE_CASTING) && p->GetChannelSpellId() != 0) { uint32& last = stale_logged_ms[id]; @@ -1091,7 +1161,7 @@ void Module::OnWorldUpdate(std::chrono::milliseconds diff) // Bots hovering over the floor in a battleground: the start points (AB Trollbane Hall z=-9.0 over a courtyard at -15) sit a few // yards above the ground. A player falls client-side; a bot never does, so it stood in the air until it walked. Once a second, // a quarter of the bots (by id) that stand still in a battleground and are 2..30 y above the floor drop to it with a falling - // spline (Karrz, AB test 2026-10-08, "bots flying in the air"). + // spline (playtest, AB test 2026-10-08, "bots flying in the air"). { static std::chrono::milliseconds last_settle{0}; static uint32 settle_phase = 0; @@ -1497,7 +1567,7 @@ void Module::OnWorldUpdate(std::chrono::milliseconds diff) // a no-op for bots not in an orphaned BG map. RescueOrphanedBgBot(p); SnapToGroundIfDrifted(p); - // Resolve the bot's AI ONCE here on the world thread (registry + // Resolve the bot's bot logic ONCE here on the world thread (registry // quiescent under for_each's shared_lock) and thread it through // the BuiltSlot. Build workers MUST NOT call Registry().ai() // (unlocked map lookup races a concurrent rehash → garbage @@ -1653,9 +1723,9 @@ void Module::OnWorldUpdate(std::chrono::milliseconds diff) const uint32 group_ms_before = t_group_build_ms; // Companion tank threat multiplier (UpdateTankThreatMultiplier); 1.0 disables. const float tank_threat_mult = std::clamp( - float(sConfigMgr->GetFloatDefault("Playerbot.TankThreatMultiplier", 3.0f)), 1.0f, 10.0f); + float(sConfigMgr->GetFloatDefault("Playerbot.TankThreatMultiplier", 3.0f, true)), 1.0f, 10.0f); const float dps_threat_mult = std::clamp( - float(sConfigMgr->GetFloatDefault("Playerbot.DpsThreatMultiplier", 1.0f)), 0.3f, 1.5f); + float(sConfigMgr->GetFloatDefault("Playerbot.DpsThreatMultiplier", 1.0f, true)), 0.3f, 1.5f); ConfigReader::CastPacing const cast_pacing_cfg = Services::Config().cast_pacing(); uint32 const pvp_floor_ms = Services::Config().pacing().pvp_reaction_delay_ms; for (BuiltSlot& bs : build_order) @@ -1797,7 +1867,7 @@ void Module::OnWorldUpdate(std::chrono::milliseconds diff) // CRUISE (300 ms) — the dominant long-haul population: a // solo, non-human-facing bot that is merely travelling or // questing in the open world. Its movement spline runs - // server-side; the AI only needs to issue the next waypoint + // server-side; the bot logic only needs to issue the next waypoint // a touch less often, so half-rate snapshot builds are // tolerable. NOT path_blocked and NOT casting (those are // Active above), so no unstick/cast starvation. Cruise never @@ -1913,6 +1983,9 @@ void Module::OnWorldUpdate(std::chrono::milliseconds diff) t_population_ms = getMSTimeDiff(t0, getMSTime()); } + // 2.7. Pets that cannot walk to their bot owner are set down next to it. + DrivePetSnap(getMSTime()); + // 2b. Bot guild manager tick (GUILD_PLAN.md Phase A.2). Internally // 60s rate-limited; cheap to call every frame. Elects founders // when guild slots are open + sweeps stale name reservations @@ -2029,7 +2102,7 @@ void Module::OnWorldUpdate(std::chrono::milliseconds diff) : 0u; SampleFleetVitals(total, now_ms, in_world, alive, in_combat, avg_level_x100); - if (sConfigMgr->GetBoolDefault("Playerbot.LoadTest.Enable", false)) + if (sConfigMgr->GetBoolDefault("Playerbot.LoadTest.Enable", false, true)) { uint32 raid = 0, bg = 0; Services::Registry().for_each([&](BotId id, BotRegistryEntry const& e) @@ -2230,7 +2303,7 @@ void V2::Module::EmitLoadTestRow(uint32 in_world, uint32 raid, uint32 bg) Diagnostics::LoadRow row; row.unix_time = uint64(GameTime::GetGameTime()); row.build = GitRevision::GetHash(); - row.label = sConfigMgr->GetStringDefault("Playerbot.LoadTest.Label", ""); + row.label = sConfigMgr->GetStringDefault("Playerbot.LoadTest.Label", "", true); row.bots_awake = in_world; row.bots_raid = raid; row.bots_bg = bg; @@ -2249,12 +2322,12 @@ void V2::Module::EmitLoadTestRow(uint32 in_world, uint32 raid, uint32 bg) row.cpu_pct = wf.cpu_pct; Diagnostics::LoadLimits limits; - limits.max_p99_ms = uint32(sConfigMgr->GetIntDefault("Playerbot.LoadTest.MaxP99Ms", int(limits.max_p99_ms))); - limits.max_avg_ms = double(sConfigMgr->GetIntDefault("Playerbot.LoadTest.MaxAvgMs", int(limits.max_avg_ms))); - limits.max_rss_mb = uint32(sConfigMgr->GetIntDefault("Playerbot.LoadTest.MaxRssMb", int(limits.max_rss_mb))); - limits.max_slow_call_ms = uint32(sConfigMgr->GetIntDefault("Playerbot.LoadTest.MaxSlowCallMs", int(limits.max_slow_call_ms))); + limits.max_p99_ms = uint32(sConfigMgr->GetIntDefault("Playerbot.LoadTest.MaxP99Ms", int(limits.max_p99_ms), true)); + limits.max_avg_ms = double(sConfigMgr->GetIntDefault("Playerbot.LoadTest.MaxAvgMs", int(limits.max_avg_ms), true)); + limits.max_rss_mb = uint32(sConfigMgr->GetIntDefault("Playerbot.LoadTest.MaxRssMb", int(limits.max_rss_mb), true)); + limits.max_slow_call_ms = uint32(sConfigMgr->GetIntDefault("Playerbot.LoadTest.MaxSlowCallMs", int(limits.max_slow_call_ms), true)); - std::string const path = sConfigMgr->GetStringDefault("Playerbot.LoadTest.CsvPath", "playerbot_loadtest.csv"); + std::string const path = sConfigMgr->GetStringDefault("Playerbot.LoadTest.CsvPath", "playerbot_loadtest.csv", true); bool const fresh = !std::filesystem::exists(path); std::ofstream out(path, std::ios::app); if (!out) @@ -2451,6 +2524,8 @@ void Module::OnPlayerLogin(Player* p) const uint32 owner_account = sess->GetAccountId(); // Bots bound to the whole account treat this character as their owner while it is online. Services::Owners().NoteOwnerCharacterOnline(owner_account, id); + if (Services::Config().addon_hint_enabled()) + g_addon_hints.Login(id, GameTime::GetGameTimeMS(), Services::Config().addon_hint_delay_sec() * 1000); auto owned = Services::Owners().BotsOwnedBy(owner_account); std::string const& owner_name = p->GetName(); for (BotId bot_id : owned) @@ -2627,7 +2702,7 @@ void Module::OnPlayerLogin(Player* p) ai->set_follow_distance(s.follow_distance); ai->set_verbose_logging(s.owner_verbose); - // The role the owner gave a companion lives in the AI and the Classic virtual spec, both memory only: pin it + // The role the owner gave a companion lives in the bot logic and the Classic virtual spec, both memory only: pin it // again so a relog (or a restart) does not hand the bot's role back to a talent inference. // A companion with no stored role (added before roles were stored, or never asked) is pinned to the role it // plays now and stored: left unset, the raid quota fill treated it as free and moved paladins and druids from @@ -2684,10 +2759,10 @@ void Module::OnPlayerLogin(Player* p) // Bots taught by an earlier build can carry other classes' trainer spells (a rogue with Judgement): drop them at login. if (uint32 const removed = ::Playerbot::API(p).purge_foreign_class_spells()) TC_LOG_INFO("playerbot.v2", "[levelup] {} lost {} spells of other classes at login", p->GetName(), removed); - // INFO-level so the operator can see which bots actually attached AI + // INFO-level so the operator can see which bots actually attached bot logic // when bringing up a fresh worldserver / spawning via .playerbot login. // The DEBUG history can be inspected via /history or /inspect later. - TC_LOG_INFO("playerbot.v2", "[PlayerbotV2] Bot AI attached: {} (id {}, class {} race {} level {})", + TC_LOG_INFO("playerbot.v2", "[PlayerbotV2] Bot logic attached: {} (id {}, class {} race {} level {})", p->GetName(), id, uint32(p->GetClass()), uint32(p->GetRace()), uint32(p->GetLevel())); } @@ -2696,7 +2771,10 @@ void Module::OnPlayerLogout(Player* p) if (!initialized_ || !p) return; const BotId id = p->GetGUID().GetCounter(); if (WorldSession const* sess = p->GetSession(); sess && !sess->IsBot()) + { Services::Owners().NoteOwnerCharacterOffline(sess->GetAccountId(), id); + g_addon_hints.Logout(id); + } if (!Services::Registry().has(id)) return; // not one of ours // Speak queued chat (the `.bot dismiss` goodbye) while the bot is still in the world. BotChatter::FlushPendingChat(p); @@ -2711,7 +2789,7 @@ void Module::OnPlayerLogout(Player* p) // entries are dead data (guid_low is unique per character). g_last_snap_z_ms.erase(id); g_global_stuck.erase(id); - TC_LOG_INFO("playerbot.v2", "[PlayerbotV2] Bot AI detached: {} (id {})", p->GetName(), id); + TC_LOG_INFO("playerbot.v2", "[PlayerbotV2] Bot logic detached: {} (id {})", p->GetName(), id); } void Module::OnLevelUp(Player* p, uint8 new_level) @@ -2864,7 +2942,7 @@ void Module::OnDeath(Unit* victim, Unit* killer) // their rotation. The queue persists until State_Idle drains it. Creature* c = victim->ToCreature(); if (c) - Diagnostics::Scenario::NoteCreatureKilled(c->GetMapId(), c->GetEntry()); + Diagnostics::Scenario::NoteCreatureKilled(c->GetMapId(), c->GetEntry(), c->hasLootRecipient()); // Boss kill line for tools/Fight-Report.ps1: dungeon and raid bosses, with how many of the tapping group survived. if (c && c->GetMap() && c->GetMap()->IsDungeon() && (c->IsDungeonBoss() || c->isWorldBoss())) { @@ -2895,7 +2973,7 @@ void Module::OnDeath(Unit* victim, Unit* killer) // Queue the corpse onto the bot's pending-loot list. State_Idle // walks the bot to the closest entry and emits a LootIntent each // tick; the entry is popped on success. The push helper is mutex- - // protected since the AI worker drains concurrently. + // protected since the bot worker drains concurrently. reg.push_loot(id, corpse_guid); } } @@ -2926,8 +3004,18 @@ void Module::OnDamageDealt(Unit* /*attacker*/, Unit* /*victim*/, int32 /*amount* // freshly built snapshot's `in_combat` flag. } +namespace { thread_local uint32 tl_damage_spell = 0; } + +void Module::NoteDamageSpell(uint32 spell_id) +{ + tl_damage_spell = spell_id; +} + void Module::OnDamageTaken(Unit* attacker, Unit* victim, int32 amount, uint32 spell_id) { + // The hook that precedes OnDamage names the spell; consumed here so a later melee swing is not labelled with it. + uint32 const lethal_spell = spell_id ? spell_id : tl_damage_spell; + tl_damage_spell = 0; if (!initialized_) return; Diagnostics::Scenario::NoteDamage(attacker, victim, amount); // a scenario's boss-pull statistics; one atomic load when none runs Diagnostics::Parity::NoteDamage(attacker, victim, amount, spell_id); // the damage_parity tally; one atomic load when none runs @@ -2936,13 +3024,13 @@ void Module::OnDamageTaken(Unit* attacker, Unit* victim, int32 amount, uint32 sp { std::lock_guard lk(g_lethal_hits_mtx); g_lethal_hits[victim->GetGUID().GetCounter()] = - LethalHit{ spell_id, amount, int32(uint64(amount) - victim->GetHealth()) }; + LethalHit{ lethal_spell, amount, int32(uint64(amount) - victim->GetHealth()) }; } // Intentionally a no-op. The BotEventInbox was retired 2026-05-21 // after audit found zero consumers + the snapshot's in_combat / // hp / attackers vector already covers every actual rule need. // V1 had an event bus with real subscribers (174 publishers, 210 - // subscribers across 7 domains); V2's snapshot-then-AI-worker + // subscribers across 7 domains); V2's snapshot-then-bot-worker // distribution model fills that role differently. If event-driven // dispatch becomes needed for a specific feature (e.g. kick-then- // pause), introduce a focused per-event hook then. @@ -3072,7 +3160,7 @@ void Module::OnRaidSubgroupChanged(Group* group, ObjectGuid member, uint8 subgro void Module::OnSpiritReleased(Player* p) { - // The owner pressed Release Spirit (ike3 / Karrz: companions release with + // The owner pressed Release Spirit (ike3 / the owner: companions release with // their master). Inside a dungeon or raid RepopAtGraveyard revives the // owner at the graveyard, so the owner is never a ghost there and // State_Dead's owner-released check (owner->is_ghost) cannot fire; this @@ -3134,10 +3222,32 @@ void Module::RouteGroupOrder(Player* sender, Group* group, std::string order) // Raid pull: the main tank (raid-frame flag) pulls alone; with none set, every tank as before. ObjectGuid pull_main_tank; char const* pull_why = "every tank (no main tank set)"; + // A tank that can pull: one of the sender's own bots, alive, in the tank role. + auto const usable_tank = [&](Player* m) + { + if (!m || m == sender || !m->IsAlive()) + return false; + BotId const mid = m->GetGUID().GetCounter(); + return Services::Registry().has(mid) && Services::Owners().IsOwner(mid, account, sender->GetGUID().GetCounter()) && + BotCommandParser::BotRole(m) == Role::Tank; + }; + std::string main_tank_skipped; if ((order == "pull" || order == "pull back") && group->isRaidGroup()) for (Group::MemberSlot const& slot : group->GetMemberSlots()) - if (slot.flags & MEMBER_FLAG_MAINTANK) { pull_main_tank = slot.guid; pull_why = "the main tank"; break; } - if (order == "pull back") + { + if (!(slot.flags & MEMBER_FLAG_MAINTANK)) + continue; + // The flagged main tank pulls only if it can: a dead one, a player, someone else's bot or a bot that is not + // a tank would leave nobody pulling, so the next flagged one or the closest tank takes over. + Player* flagged = ObjectAccessor::FindConnectedPlayer(slot.guid); + if (usable_tank(flagged)) { pull_main_tank = slot.guid; pull_why = "the main tank"; break; } + main_tank_skipped += (main_tank_skipped.empty() ? "" : ", ") + slot.name; + } + if (!main_tank_skipped.empty() && pull_main_tank.IsEmpty()) + TC_LOG_INFO("playerbot.v2", "[pull_back] flagged main tank {} cannot pull (dead, not your bot or not a tank): next best tank pulls", + main_tank_skipped); + // A 5-man's Pull sends one tank like Pull back does (two tank-role bots would both run at the pack); a raid's Pull keeps every tank. + if (order == "pull back" || (order == "pull" && !group->isRaidGroup())) { // Exactly ONE bot pulls: the tank assigned to the selected mob's raid icon, else the main tank, else the // owned tank closest to the mob. Every other bot (other tanks included) holds where it stands. @@ -3191,7 +3301,7 @@ void Module::RouteGroupOrder(Player* sender, Group* group, std::string order) if (BotCommandParser::BotRole(member) != Role::Tank || (!pull_main_tank.IsEmpty() && member->GetGUID() != pull_main_tank)) { - // The other tanks come and stand beside the owner, where the mob is brought to (Karrz 2026-10-08: "all the + // The other tanks come and stand beside the owner, where the mob is brought to (playtest 2026-10-08: "all the // warriors should be standing beside me when I say pull back"); everyone else holds where they stand // (like "pull"); "fall back" is the whole-raid version. if (BotCommandParser::BotRole(member) == Role::Tank && member->IsAlive()) @@ -3229,7 +3339,26 @@ void Module::RouteGroupOrder(Player* sender, Group* group, std::string order) BotCommandParser::DispatchSingle(sender, member, order, "party"); } if ((order == "pull" || order == "pull back") && !tanks) - ChatHandler(sender->GetSession()).SendSysMessage("No tank among your bots to pull; use attack instead."); + { + // Say why: the flagged main tank could not pull, or none of the sender's bots in this group is a living tank. + uint32 owned_tanks = 0, dead_tanks = 0; + for (GroupReference const& itr : group->GetMembers()) + { + Player* m = itr.GetSource(); + if (!m || m == sender) continue; + BotId const mid = m->GetGUID().GetCounter(); + if (!Services::Registry().has(mid) || !Services::Owners().IsOwner(mid, account, sender->GetGUID().GetCounter()) || + BotCommandParser::BotRole(m) != Role::Tank) + continue; + ++owned_tanks; + if (!m->IsAlive()) ++dead_tanks; + } + ChatHandler(sender->GetSession()).PSendSysMessage(owned_tanks && dead_tanks == owned_tanks ? + "Your tank bots are all dead; use attack instead." : + "No tank among your bots to pull; use attack instead."); + TC_LOG_INFO("playerbot.v2", "[pull_back] {} '{}': no tank pulled (your tank bots in the group: {}, dead {}; flagged main tank skipped: {})", + sender->GetName(), order, owned_tanks, dead_tanks, main_tank_skipped.empty() ? "none" : main_tank_skipped); + } return; } @@ -3242,8 +3371,71 @@ void Module::OnAddonOrder(Player* sender, Group* group, std::string const& prefi RouteGroupOrder(sender, group, *order); } +void Module::OnGroupPingUnit(Player* sender, Group* group, Unit* target, uint8 type) +{ + if (!initialized_ || !sender || !group || !target || type != 0) return; // 0 = PingSubjectType::Attack + if (target->IsPlayer() || !target->IsAlive() || !sender->IsValidAttackTarget(target)) return; + TC_LOG_INFO("playerbot.v2", "[ping] {} pings attack on {}", sender->GetName(), target->GetName()); + // "attack" acts on the sender's selection: the ping picks the mob. + sender->SetSelection(target->GetGUID()); + RouteGroupOrder(sender, group, "attack"); +} + +void Module::OnGroupPingPoint(Player* sender, Group* group, Position const& point, uint8 type) +{ + if (!initialized_ || !sender || !group || type != 3) return; // 3 = PingSubjectType::OnMyWay + uint32 const account = sender->GetSession() ? sender->GetSession()->GetAccountId() : 0; + if (account == 0) return; + uint32 set = 0; + for (GroupReference const& itr : group->GetMembers()) + { + Player* m = itr.GetSource(); + if (!m || m == sender || !m->IsAlive() || m->GetMapId() != sender->GetMapId()) continue; + BotId const mid = m->GetGUID().GetCounter(); + if (!Services::Registry().has(mid) || !Services::Owners().IsOwner(mid, account, sender->GetGUID().GetCounter())) continue; + if (BotAI* ai = Services::Registry().ai(mid)) + { + ai->set_rally_point(sender->GetMapId(), point.GetPositionX(), point.GetPositionY(), point.GetPositionZ()); + ++set; + } + } + if (!set) return; + TC_LOG_INFO("playerbot.v2", "[ping] {} pings on my way to ({:.1f},{:.1f}): {} bots fall back there", sender->GetName(), + point.GetPositionX(), point.GetPositionY(), set); + RouteGroupOrder(sender, group, "fallback"); +} + +void Module::NoteAddonHello(Player* p) +{ + if (!initialized_ || !p) return; + if (g_addon_hints.Pending(p->GetGUID().GetCounter())) + TC_LOG_INFO("playerbot.v2", "[addon_hello] {} has the ForeverBots add-on", p->GetName()); + g_addon_hints.Hello(p->GetGUID().GetCounter()); +} + +void Module::SendDueAddonHints() +{ + if (!Services::Config().addon_hint_enabled()) + return; + for (uint64 guid : g_addon_hints.TakeDue(GameTime::GetGameTimeMS())) + { + Player* p = ObjectAccessor::FindConnectedPlayer(ObjectGuid::Create(guid)); + if (!p || !p->IsInWorld() || !p->GetSession() || p->GetSession()->IsBot()) + continue; + ChatHandler(p->GetSession()).PSendSysMessage("WoW Forever Bots add-on (buttons for your bots, Raid ready): %s - unzip it into Interface\\AddOns and type /reload.", + Services::Config().addon_hint_url().c_str()); + TC_LOG_INFO("playerbot.v2", "[addon_hint] {} has no ForeverBots add-on: link sent", p->GetName()); + } +} + void Module::OnAddonWhisper(Player* sender, Player* receiver, std::string const& prefix, std::string const& text) { + // The add-on's greeting to itself on login: this client has it, so no hint. + if (initialized_ && sender && sender == receiver && prefix == kAddonOrderPrefix && text == kAddonHelloText) + { + NoteAddonHello(sender); + return; + } if (!initialized_ || !sender || !receiver || text.empty() || prefix != kAddonOrderPrefix) return; TC_LOG_INFO("playerbot.v2", "[addon_whisper] {} -> {}", sender->GetName(), receiver->GetName()); OnWhisperReceived(sender, receiver, text); @@ -3319,7 +3511,21 @@ void Module::OnPartyChat(Player* sender, Group* group, std::string const& msg) if (!primary) primary = any_group_bot; if (!primary) return; - BotCommandParser::Dispatch(sender, primary, body, "party;"); + if (!BotCommandParser::Dispatch(sender, primary, body, "party;")) + { + // A ";" line is meant as an order: an unknown or refused one answers instead of vanishing. (A plain whisper falls + // through to the social reactor and a bare party word is chatter, so only this explicit route replies.) + BotId const pid = primary->GetGUID().GetCounter(); + if (Services::HasIntents(pid)) + { + Intent it{}; + it.bot_id = pid; + it.body = ChatIntent{WhisperIntent{ + sender->GetName(), + fmt::format("{}: no order '{}' (unknown, or not yours to give)", primary->GetName(), body.substr(0, 40))}}; + Services::Intents(pid).push(std::move(it)); + } + } } void Module::OnPlayerJoinedBgQueue(Player* player, uint32 bg_type_id, uint8 bracket) diff --git a/src/modules/PlayerbotV2/PlayerbotV2.h b/src/modules/PlayerbotV2/PlayerbotV2.h index 37ae6b9eda..bbb8f78c5f 100644 --- a/src/modules/PlayerbotV2/PlayerbotV2.h +++ b/src/modules/PlayerbotV2/PlayerbotV2.h @@ -20,6 +20,7 @@ class Player; class Unit; class Aura; class Group; +struct Position; namespace Playerbot { class SnapshotBuildPool; struct GroupSnapshot; } @@ -49,6 +50,8 @@ public: void OnSpecChanged(Player* p, uint8 new_spec); void OnDamageDealt(Unit* attacker, Unit* victim, int32 amount, uint32 spell_id); void OnDamageTaken(Unit* attacker, Unit* victim, int32 amount, uint32 spell_id); + // The spell behind the damage event OnDamageTaken is about to receive (UnitScript::OnDamageSpell runs just before OnDamage; 0 = melee). + void NoteDamageSpell(uint32 spell_id); void OnHitOutcome(Unit* attacker, Unit* victim, uint32 spell_id, uint8 outcome, uint32 damage); void OnEnergize(Unit* target, uint32 spell_id, int32 gained, uint8 power); void OnHealReceived(Unit* healer, Unit* target, int32 amount, uint32 spell_id); @@ -61,6 +64,14 @@ public: // A bot order sent by the ForeverBots panel as an addon message (fixed prefix, party/raid): same parser as party chat. void OnAddonOrder(Player* sender, Group* group, std::string const& prefix, std::string const& text); void OnAddonWhisper(Player* sender, Player* receiver, std::string const& prefix, std::string const& text); + // A group ping (PingSubjectType: 0 Attack, 3 OnMyWay): Attack on a hostile unit is the "attack" order on it, On my way on the + // ground is a fall back to that point. + void OnGroupPingUnit(Player* sender, Group* group, Unit* target, uint8 type); + void OnGroupPingPoint(Player* sender, Group* group, Position const& point, uint8 type); + // One line with the add-on's download link for a player whose client has not said hello (Playerbot.AddonHint.*). + void SendDueAddonHints(); + // The ForeverBots add-on greeted the server (self-whisper or the silent `.bot addon` command): no download hint for this player. + void NoteAddonHello(Player* p); void RouteGroupOrder(Player* sender, Group* group, std::string order); // Phase C.3: route guild chat messages to BotChatReactor::ReactGuild. void OnGuildChat(Player* sender, uint64 guild_id, std::string const& msg); diff --git a/src/modules/PlayerbotV2/PlayerbotV2Scripts.cpp b/src/modules/PlayerbotV2/PlayerbotV2Scripts.cpp index 708c38b929..af429b662d 100644 --- a/src/modules/PlayerbotV2/PlayerbotV2Scripts.cpp +++ b/src/modules/PlayerbotV2/PlayerbotV2Scripts.cpp @@ -12,12 +12,18 @@ #include "Group.h" #include "Guild.h" #include "Item.h" +#include "GameTime.h" #include "Log.h" #include "PathGenerator.h" #include "Player.h" #include "PlayerbotMovement.h" #include "ScriptMgr.h" #include "SharedDefines.h" +#include "Spell.h" +#include "SpellAuras.h" +#include "SpellInfo.h" +#include "Bot/Raid/RaidIncoming.h" +#include "Bot/Raid/RaidManaLedger.h" #include "WorldSession.h" void AddSC_playerbot_v2_commandscript(); @@ -61,7 +67,7 @@ public: void OnWorldInitialized() override { - auto value = [](char const* key) { return sConfigMgr->GetStringDefault(key, "(default)"); }; + auto value = [](char const* key) { return sConfigMgr->GetStringDefault(key, "(default)", true); }; TC_LOG_INFO("server.worldserver", "[startup] bots: Population.TotalTarget={} Gear.MaxTier={} World.Enable={} Raid.Enable={}", value("Playerbot.Population.TotalTarget"), value("Playerbot.Gear.MaxTier"), value("Playerbot.World.Enable"), value("Playerbot.Raid.Enable")); @@ -101,6 +107,50 @@ public: Module::instance().OnPlayerLogout(player); } + // Raid mana ledger: what a cast cost (the core's own figure, taken when the cast completes) and what a mana potion, rune or + // Innervate restored. Only a healer the raid brain watches in a pull is recorded. + void OnSpellCast(Player* player, Spell* spell, bool /*skipCheck*/) override + { + using namespace Playerbot::Raid; + if (!player || !spell || !ManaLedgerWatching(player->GetGUID().GetCounter())) + return; + SpellInfo const* si = spell->GetSpellInfo(); + if (!si) + return; + uint64 const g = player->GetGUID().GetCounter(); + int32 cost = 0; + for (SpellPowerCost const& c : spell->GetPowerCost()) + if (c.Power == POWER_MANA) + cost += c.Amount; + ManaLedgerCast(g, si->Id, cost, GameTime::GetGameTimeMS()); + // A spell with a mana cost in its data that was charged nothing: say why once per healer and pull (n31 mc_ragnaros: five priests cast + // 100+ heals at 100% mana). The caster's cheat flag and every aura on it are the candidates. + if (cost == 0 && !spell->IsTriggered() && ManaLedgerFirstFree(g)) + for (SpellPowerEntry const* pe : si->PowerCosts) + if (pe && pe->PowerType == POWER_MANA && (pe->ManaCost > 0 || pe->PowerCostPct > 0.0f)) + { + std::string auras; + // Each aura as id(charges, remaining ms or P for permanent, passive flag): an Inner Focus whose charge is never dropped + // (n38 mc_ragnaros: 43 Renews at no cost) shows as 14751 with its charges and duration. + for (auto const& [id, app] : player->GetAppliedAuras()) + if (app && app->GetBase()) + { + Aura const* ab = app->GetBase(); + auras += (auras.empty() ? "" : ",") + std::to_string(id) + "(c" + std::to_string(ab->GetCharges()) + "," + + (ab->IsPermanent() ? std::string("P") : std::to_string(ab->GetDuration())) + (ab->IsPassive() ? ",pass" : "") + ")"; + } + TC_LOG_INFO("playerbot.v2.raid", "[mana_free] {} cast {} (base cost {} / {}%) and paid nothing: cheat power {}, auras {}", + player->GetName(), si->Id, pe->ManaCost, pe->PowerCostPct, player->GetCommandStatus(CHEAT_POWER) ? 1 : 0, auras); + break; + } + constexpr uint32 kInnervate = 29166; + for (SpellEffectInfo const& eff : si->GetEffects()) + if (eff.Effect == SPELL_EFFECT_ENERGIZE && eff.MiscValue == POWER_MANA) + ManaLedgerRestore(g, si->Id, int32(eff.BasePoints)); + if (si->Id == kInnervate) + ManaLedgerRestore(g, si->Id, 0); + } + void OnLevelChanged(Player* player, uint8 oldLevel) override { if (player->GetLevel() > oldLevel) @@ -170,6 +220,19 @@ public: Module::instance().OnAddonOrder(player, group, prefix, text); } + // Group pings (the retail ping wheel): an Attack ping on an enemy sends the bots in, an On my way ping on the ground moves them. + void OnPingUnit(Player* player, Group* group, Unit* target, uint8 type) override + { + if (IsHuman(player)) + Module::instance().OnGroupPingUnit(player, group, target, type); + } + + void OnPingWorldPoint(Player* player, Group* group, Position const& point, uint8 type) override + { + if (IsHuman(player)) + Module::instance().OnGroupPingPoint(player, group, point, type); + } + void OnLootItem(Player* player, Item* item) override { Module::instance().OnItemLooted(player, item->GetEntry()); @@ -212,9 +275,28 @@ class playerbot_v2_unit : public UnitScript public: playerbot_v2_unit() : UnitScript("playerbot_v2_unit") { } + void OnDamageSpell(Unit* /*attacker*/, Unit* /*victim*/, uint32 /*damage*/, SpellInfo const* spellInfo) override + { + Module::instance().NoteDamageSpell(spellInfo ? spellInfo->Id : 0); + } + void OnDamage(Unit* attacker, Unit* victim, uint32& damage) override { Module::instance().OnDamageTaken(attacker, victim, int32(damage), 0); + // Raid incoming-damage table: a creature hit a player the raid brain watches in a pull. + if (attacker && victim && victim->GetTypeId() == TYPEID_PLAYER && attacker->GetTypeId() == TYPEID_UNIT) + Playerbot::Raid::IncomingHit(attacker->GetEntry(), attacker->GetName().c_str(), victim->GetGUID().GetCounter(), damage); + // ... and what the raid hit: a raider (or its pet) dealt damage to a creature. + if (attacker && victim && victim->GetTypeId() == TYPEID_UNIT) + if (Player* dealer = attacker->GetCharmerOrOwnerPlayerOrPlayerItself()) + Playerbot::Raid::DealtHit(victim->GetEntry(), victim->GetName().c_str(), dealer->GetGUID().GetCounter(), damage); + } + + // Raid mana ledger: healing that landed (the core passes the effective gain, overheal already removed). + void OnHeal(Unit* healer, Unit* /*receiver*/, uint32& gain) override + { + if (healer && healer->GetTypeId() == TYPEID_PLAYER) + Playerbot::Raid::ManaLedgerHealLanded(healer->GetGUID().GetCounter(), gain); } // Auto-loot for bots on the tap list, and a bot's own death. diff --git a/src/modules/PlayerbotV2/Services.cpp b/src/modules/PlayerbotV2/Services.cpp index f37f1bc75b..e1a382e347 100644 --- a/src/modules/PlayerbotV2/Services.cpp +++ b/src/modules/PlayerbotV2/Services.cpp @@ -567,7 +567,7 @@ void Init() h->accounts->LoadFromDb(); // Build the quest-hub spatial map. Synchronous DB-bound work — runs on // the world thread once at boot (~200ms on retail data per V1 numbers), - // afterwards reads are lock-free-ish via shared_mutex on the AI workers. + // afterwards reads are lock-free-ish via shared_mutex on the bot workers. h->hubs = std::make_unique(); h->hubs->Initialize(); // Build the repair-vendor spawn index — same lifecycle as Hubs: one diff --git a/src/modules/PlayerbotV2/Services.h b/src/modules/PlayerbotV2/Services.h index e4766dad98..10eb08cc77 100644 --- a/src/modules/PlayerbotV2/Services.h +++ b/src/modules/PlayerbotV2/Services.h @@ -55,7 +55,7 @@ V2::BotAccountMgr& Accounts(); V2::Travel::QuestHubDatabase& Hubs(); // Nearest faction-appropriate repair-vendor spawn index. Built once at boot // right after Hubs(); lock-free reads after. Used by the broken-gear repair / -// death-spiral-escape routing. World-thread init, AI-worker read. +// death-spiral-escape routing. World-thread init, bot-worker read. V2::Travel::RepairVendorIndex& RepairVendors(); V2::Travel::PortalIndex& Portals(); V2::Travel::UnifiedTravelGraph& TravelGraph(); diff --git a/src/modules/PlayerbotV2/Session/AddonControl.cpp b/src/modules/PlayerbotV2/Session/AddonControl.cpp index b04d95d7b3..09a12118e0 100644 --- a/src/modules/PlayerbotV2/Session/AddonControl.cpp +++ b/src/modules/PlayerbotV2/Session/AddonControl.cpp @@ -437,7 +437,7 @@ void HandleRosterReq(uint32 client_seq, WorldSession* sess, uint32 flags) if (!online && !include_offline) continue; // Headless = driven by one of OUR BotSessions. False for the - // owner's own self-AI character (real client session) — the + // owner's own self-bot logic character (real client session) — the // addon must NOT offer "Logout" for those rows. const bool headless = Services::SessionMgr().IsHeadless(guid); @@ -480,7 +480,7 @@ void HandleRosterReq(uint32 client_seq, WorldSession* sess, uint32 flags) } } - // Look up the current intent + last rule directly from the AI. + // Look up the current intent + last rule directly from the bot logic. // BotAI's last_rule_fired() is char const* to a string literal — // safe to read from any thread for diagnostics. BotAI* ai = Services::Registry().ai(id); @@ -610,7 +610,7 @@ void HandleBotDetailReq(uint32 client_seq, WorldSession* sess, uint32 guidLow) if (ai->last_rule_fired()) kv("last_rule", ai->last_rule_fired()); } - // Per-bot intent queue depth (proxy for "how busy is the AI"). The + // Per-bot intent queue depth (proxy for "how busy is the bot logic"). The // queue is lock-free MPMC; approximate_size is a relaxed-load read // that may drift by one but is the right call here — exact size // would require briefly stalling producers, which isn't worth it @@ -817,7 +817,7 @@ void HandleAltsReq(uint32 client_seq, WorldSession* sess) // ---------------------------------------------------------------------------- // SELF — addon counterpart to `.playerbot self on|off|status`. Attaches -// or detaches the V2 AI to the issuing player's OWN character. Mirrors +// or detaches the V2 bot logic to the issuing player's OWN character. Mirrors // HandleSelf in cs_playerbot_v2.cpp 1:1; keep these two paths in lock-step // so a future RBAC tightening (or perf cap on self-attach) lands in both. // @@ -853,7 +853,7 @@ void HandleSelfToggle(uint32 client_seq, WorldSession* sess, if (!was_attached) { // CRITICAL: use TRANSIENT mark. .playerbot self toggles a - // real human character into AI mode for the duration of + // real human character into bot logic mode for the duration of // their session — it must NEVER persist to // playerbot_v2_character, otherwise BotPopulationManager // ::LoginExisting will grab the character on the next @@ -873,7 +873,7 @@ void HandleSelfToggle(uint32 client_seq, WorldSession* sess, Services::Registry().register_bot( id, personality, BotRng{SeedForBot(id)}); Services::Scheduler().register_bot(id, ActivityTier::Idle); - // Give the transient self-AI bot a coherent archetype too + // Give the transient self-bot logic bot a coherent archetype too // (deterministic roll, NO DB write — this is a human's own // character marked transient; it must never touch // playerbot_v2_character per the comment above). @@ -884,9 +884,9 @@ void HandleSelfToggle(uint32 client_seq, WorldSession* sess, // Hand server-side movement control off the WoW client. Without // this the client keeps sending CMSG_MOVE_* every frame, which // overwrites every server-driven MotionMaster command, so the - // AI's MoveChase / MovePoint visibly fight client input and + // Bot logic's MoveChase / MovePoint visibly fight client input and // the character barely moves. Full-takeover mode: WASD is - // locked while self-AI is on; re-enabled below on "off". + // locked while self-bot logic is on; re-enabled below on "off". // SAFE post-transient-mark fix: ControlUpdate is purely // runtime/network state, no DB persistence, so a crash mid // session can't lock the character — the next login defaults diff --git a/src/modules/PlayerbotV2/Session/BotSession.cpp b/src/modules/PlayerbotV2/Session/BotSession.cpp index ec6034cd43..0afdf9c3b5 100644 --- a/src/modules/PlayerbotV2/Session/BotSession.cpp +++ b/src/modules/PlayerbotV2/Session/BotSession.cpp @@ -138,7 +138,7 @@ bool BotSession::Update(uint32 /*diff*/, PacketFilter& /*updater*/) { if (_player && !m_playerLogout) { - // A bot that leaves the world must not stay on a battleground group's member list as an "Offline" ghost (Karrz, + // A bot that leaves the world must not stay on a battleground group's member list as an "Offline" ghost (the owner, // 2026-10-08: five logged-out BG bots shown Offline in his frames). Leave the BG group first. if (Group* group = _player->GetGroup(); group && group->isBGGroup()) { diff --git a/src/modules/PlayerbotV2/Session/BotSessionMgr.cpp b/src/modules/PlayerbotV2/Session/BotSessionMgr.cpp index 8af9f56515..4c38e1c732 100644 --- a/src/modules/PlayerbotV2/Session/BotSessionMgr.cpp +++ b/src/modules/PlayerbotV2/Session/BotSessionMgr.cpp @@ -19,7 +19,7 @@ BotSessionMgr::~BotSessionMgr() { // Sessions are owned by shared_ptr; clearing the map runs each session's // destructor which logs out + saves the player. Ordering note: this runs - // at module Shutdown, after the AI worker pool has stopped, so no AI + // at module Shutdown, after the bot worker pool has stopped, so no bot logic // worker is still pushing intents into a session being torn down. std::lock_guard lk(mtx_); sessions_.clear(); diff --git a/src/modules/PlayerbotV2/Session/BotSessionMgr.h b/src/modules/PlayerbotV2/Session/BotSessionMgr.h index f4782878ae..0a67d8c28b 100644 --- a/src/modules/PlayerbotV2/Session/BotSessionMgr.h +++ b/src/modules/PlayerbotV2/Session/BotSessionMgr.h @@ -59,7 +59,7 @@ public: size_t active_count() const; // True when this character is driven by one of OUR headless BotSessions. - // False for a real-client character running self-AI (`.playerbot self`): + // False for a real-client character running self-bot logic (`.playerbot self`): // those must NEVER receive manufactured client packets (teleport acks // etc.) — the real client performs the genuine handshake, and forging it // desyncs the client (stuck loading screen on LFG teleport, live diff --git a/src/modules/PlayerbotV2/Threading/AiWorkerPool.cpp b/src/modules/PlayerbotV2/Threading/AiWorkerPool.cpp index d3f4ffe423..4a7b7447e3 100644 --- a/src/modules/PlayerbotV2/Threading/AiWorkerPool.cpp +++ b/src/modules/PlayerbotV2/Threading/AiWorkerPool.cpp @@ -161,11 +161,11 @@ void AiWorkerPool::run_one(BotId bot) if (!snap) return; // No snapshot published yet — bot hasn't fully spawned. // Staleness guard. Under load the snapshot-build pipeline can fall behind - // the AI worker pool, leaving the most-recently-published snapshot + // the bot worker pool, leaving the most-recently-published snapshot // arbitrarily old. Acting on it makes the bot decide against a world // state that no longer exists (moved enemies, dead targets, changed HP). // Skip the tick when the snapshot's age exceeds a tier-aware threshold — - // ~3× the bot's AI period so a single dropped/late build is tolerated, + // ~3× the bot's bot logic period so a single dropped/late build is tolerated, // but capped at 1s so even Idle/Hibernate bots never run on grossly stale // data. published_at_ms is stamped from GameTime::GetGameTimeMS() in the // builder, so we compare against the same time base here. The bot simply @@ -221,7 +221,7 @@ void AiWorkerPool::run_one(BotId bot) // Record per-bot tick latency. Bucketed histogram in PerfCounters // surfaces tick_p50 / tick_p99 via /perf — without this the field // stays at zero. Worker pool is the natural recording site since - // it knows when a single bot's AI tick begins/ends. + // it knows when a single bot's bot tick begins/ends. const uint32 tick_end = getMSTime(); Services::Perf().record_tick_latency( std::chrono::milliseconds{int32(tick_end - tick_start)}); diff --git a/src/modules/PlayerbotV2/Threading/AiWorkerPool.h b/src/modules/PlayerbotV2/Threading/AiWorkerPool.h index 4cbedefd01..0307192245 100644 --- a/src/modules/PlayerbotV2/Threading/AiWorkerPool.h +++ b/src/modules/PlayerbotV2/Threading/AiWorkerPool.h @@ -1,5 +1,5 @@ // AiWorkerPool - N worker threads consuming a tick-task queue. Each task is -// "run AI tick for bot X using snapshot Y, push intents to queue Z." The pool +// "run bot tick for bot X using snapshot Y, push intents to queue Z." The pool // is otherwise dumb — TickScheduler decides who runs and when. // // CONTRACTS.md §5.3. @@ -23,8 +23,8 @@ struct PerfStats uint64_t ticks_total = 0; uint64_t exceptions_total = 0; uint64_t queue_high_watermark = 0; - // AI ticks skipped because the published snapshot was grossly stale - // (age > ~3× the bot's tier AI period, capped at 1s). Acting on an + // bot ticks skipped because the published snapshot was grossly stale + // (age > ~3× the bot's tier bot logic period, capped at 1s). Acting on an // arbitrarily-old snapshot under load produces decisions against a // world state that no longer exists; skipping lets the bot re-tick // against a fresh snapshot on the next pass. diff --git a/src/modules/PlayerbotV2/Threading/IntentQueue.h b/src/modules/PlayerbotV2/Threading/IntentQueue.h index 3d090880ac..4b025cdb0a 100644 --- a/src/modules/PlayerbotV2/Threading/IntentQueue.h +++ b/src/modules/PlayerbotV2/Threading/IntentQueue.h @@ -1,5 +1,5 @@ // IntentQueue - Lock-free MPSC ring buffer. -// Many AI workers + fleet thread produce; world thread consumes. +// Many bot workers + fleet thread produce; world thread consumes. // CONTRACTS.md §5.1. #pragma once @@ -14,12 +14,14 @@ namespace Playerbot { // Default ring depth. One of these exists per REGISTERED bot, and the slot // array is sized capacity * sizeof(Slot) where Slot is an atomic // alongside a whole Intent - so this number is the single biggest per-bot -// allocation in the module. It is deliberately left at the historical value: -// push() drops the intent and bumps intents_dropped_total when the ring is -// full, so shrinking it trades memory for lost bot actions under burst. Size it -// from the measured peak (".playerbot inspect" reports "Dropped total") rather -// than from the typical depth, which is under five. -inline constexpr size_t kDefaultIntentQueueCapacity = 4096; +// allocation in the module. push() drops the intent and bumps +// intents_dropped_total when the ring is full, so shrinking it trades memory +// for lost bot actions under burst. 4096 slots were 768 KiB resident per bot +// (165 MB at 220 bots) for a queue the world thread drains (64 per bot per +// tick) faster than a bot fills it; 1024 keeps a wide margin over any burst +// at a quarter of the memory. Check ".playerbot inspect" "Dropped total" +// after a long session before going lower. +inline constexpr size_t kDefaultIntentQueueCapacity = 1024; class IntentQueue { diff --git a/src/modules/PlayerbotV2/Threading/SnapshotBuildPool.h b/src/modules/PlayerbotV2/Threading/SnapshotBuildPool.h index 324b38013b..f667d657c6 100644 --- a/src/modules/PlayerbotV2/Threading/SnapshotBuildPool.h +++ b/src/modules/PlayerbotV2/Threading/SnapshotBuildPool.h @@ -1,7 +1,7 @@ // SnapshotBuildPool - A fixed, persistent worker pool used to parallelize the // per-tick snapshot Build phase by Map* (PlayerbotV2 #5 Phase 4). // -// Unlike AiWorkerPool (a long-lived producer/consumer queue that runs the AI +// Unlike AiWorkerPool (a long-lived producer/consumer queue that runs the bot logic // tick), this pool is a *fork-join barrier* primitive: the world thread submits // a batch of independent tasks (one per Map* partition) via run_and_wait(), // the persistent workers drain them in parallel, and run_and_wait() returns diff --git a/src/modules/PlayerbotV2/Threading/SnapshotPublisher.h b/src/modules/PlayerbotV2/Threading/SnapshotPublisher.h index b7c110ad69..7d4ca5ba30 100644 --- a/src/modules/PlayerbotV2/Threading/SnapshotPublisher.h +++ b/src/modules/PlayerbotV2/Threading/SnapshotPublisher.h @@ -1,5 +1,5 @@ // SnapshotPublisher - Atomic per-bot snapshot slot. World thread publishes; -// AI workers read latest. CONTRACTS.md §5.2. +// bot workers read latest. CONTRACTS.md §5.2. #pragma once @@ -22,7 +22,7 @@ public: void publish(BotId id, std::shared_ptr snap); void publish_group(BotId id, std::shared_ptr snap); - // Called by AI workers (or fleet thread). Returns latest, or null if + // Called by bot workers (or fleet thread). Returns latest, or null if // no snapshot has been published for this bot yet. std::shared_ptr latest(BotId id) const; std::shared_ptr latest_group(BotId id) const; diff --git a/src/modules/PlayerbotV2/Threading/TickScheduler.cpp b/src/modules/PlayerbotV2/Threading/TickScheduler.cpp index 3a3d5fa9ec..6fe7049e89 100644 --- a/src/modules/PlayerbotV2/Threading/TickScheduler.cpp +++ b/src/modules/PlayerbotV2/Threading/TickScheduler.cpp @@ -18,7 +18,7 @@ namespace { // bot's first build after register — got identical deadlines and stayed phase- // locked forever, because they all re-armed from the same `now` with the same // period. The world thread then paid ALL of their snapshot builds (+ LoS -// raycasts, 30s spellbook rescans, AI ticks and the following intent drain) in +// raycasts, 30s spellbook rescans, bot ticks and the following intent drain) in // ONE tick per period and nothing in the ticks between: a 40-bot raid on one // map (serial build path — a single Map* never fans out) turned a ~3 ms average // snapshot phase into a ~30-150 ms spike every 100-150 ms. @@ -50,8 +50,8 @@ Ms EffectivePeriod(ActivityTier tier, Ms pvp_floor) TickScheduler::TickScheduler(AiWorkerPool& pool) : pool_(pool) { - lazy_ms_budget_ = sConfigMgr->GetIntDefault("Playerbot.Perf.TickBudgetMs", 0) > 0 - ? uint32(sConfigMgr->GetIntDefault("Playerbot.Perf.TickBudgetMs", 0)) : 0u; + lazy_ms_budget_ = sConfigMgr->GetIntDefault("Playerbot.Perf.TickBudgetMs", 0, true) > 0 + ? uint32(sConfigMgr->GetIntDefault("Playerbot.Perf.TickBudgetMs", 0, true)) : 0u; } void TickScheduler::on_world_tick(Ms now) @@ -69,7 +69,7 @@ void TickScheduler::on_world_tick(Ms now) { due_buf.push_back(id); // Phase-aligned (see NextPhaseDeadline) with the SAME phase as the - // snapshot deadline below, so a bot's AI tick still lands on the + // snapshot deadline below, so a bot's bot tick still lands on the // world tick that just rebuilt its snapshot. sched.next_tick = NextPhaseDeadline(id, now, EffectivePeriod(sched.tier, sched.pvp_floor)); } @@ -126,7 +126,7 @@ void TickScheduler::set_tier(BotId id, ActivityTier classified, Ms now) // Tier change. set_tier is only called from the post-build publish pass, // i.e. right after THIS bot's snapshot was rebuilt in this world tick, so // the snapshot the new tier was classified from is already fresh: - // * AI tick -> now: the bot acts on that fresh snapshot this very world + // * bot tick -> now: the bot acts on that fresh snapshot this very world // tick (TickScheduler::on_world_tick runs after the publish pass). This // is the reactivity guarantee: a bot entering combat / being owner- // controlled / starting to move reacts on this frame, never on the @@ -172,8 +172,8 @@ bool TickScheduler::should_build_snapshot(BotId id, Ms now) } --lazy_budget_; } - // Advance using the tier's AI-tick period — snapshot cadence - // matches AI tick cadence so an AI worker always sees fresh data + // Advance using the tier's bot logic-tick period — snapshot cadence + // matches bot tick cadence so an bot worker always sees fresh data // when its tick fires. Phase-aligned per bot (see NextPhaseDeadline) so // bots reset in the same tick do not stay phase-locked. it->second.next_snapshot = NextPhaseDeadline(id, now, EffectivePeriod(it->second.tier, it->second.pvp_floor)); diff --git a/src/modules/PlayerbotV2/Threading/TickScheduler.h b/src/modules/PlayerbotV2/Threading/TickScheduler.h index 456307963d..f2130d4d4b 100644 --- a/src/modules/PlayerbotV2/Threading/TickScheduler.h +++ b/src/modules/PlayerbotV2/Threading/TickScheduler.h @@ -1,5 +1,5 @@ // TickScheduler - Decides which bots tick this world frame and routes them to -// the AI worker pool. Driven by per-bot ActivityTier and the world tick budget. +// the bot worker pool. Driven by per-bot ActivityTier and the world tick budget. #pragma once @@ -19,14 +19,14 @@ public: explicit TickScheduler(AiWorkerPool& pool); // Called on world thread once per world tick. Selects bots whose next-tick - // deadline has passed and submits them to the AI worker pool. + // deadline has passed and submits them to the bot worker pool. void on_world_tick(Ms now); // Bot lifecycle void register_bot(BotId id, ActivityTier initial = ActivityTier::Idle); void unregister_bot(BotId id); - // Tier transition (called by AI tick logic via the snapshot publish path). + // Tier transition (called by bot tick logic via the snapshot publish path). // // `classified` is the tier the per-tick classifier decided the bot // SHOULD be in this frame (see PlayerbotV2.cpp). The scheduler applies @@ -36,7 +36,7 @@ public: // long tail of AFK city/inn bots. Any non-Idle classification (combat / // active / dead) resets the streak immediately, so a parked bot snaps // back to its fast cadence the moment it wakes. On any actual tier - // change the AI tick resets to `now` (the bot acts this frame on the + // change the bot tick resets to `now` (the bot acts this frame on the // snapshot that was just built and classified) and the snapshot deadline // re-arms to the bot's next phase point at the new tier's period, so // there is no reactivity regression. All deadlines are phase-aligned per @@ -45,7 +45,7 @@ public: void set_tier(BotId id, ActivityTier classified, Ms now); // Snapshot-build cadence gate. Per-bot tier-driven throttle on - // `BotSnapshotBuilder::Build` so Build is paid at the AI tick rate + // `BotSnapshotBuilder::Build` so Build is paid at the bot tick rate // (Combat 10Hz / Active 5Hz / Idle 1Hz) instead of every world frame // (50Hz). Returns true if it's time to rebuild for `id`; false if // the throttle is still holding. On true, advances the per-bot @@ -53,7 +53,7 @@ public: bool should_build_snapshot(BotId id, Ms now); // PvP reaction floor (Playerbot.Pacing.PvpReactionDelayMs): a per-bot minimum - // for the AI-tick and snapshot-build period, whatever the tier. 0 clears it. + // for the bot logic-tick and snapshot-build period, whatever the tier. 0 clears it. // Set by the publish pass each time the bot's snapshot is rebuilt: the caller // passes 0 for PvE and for survival (low HP, dead/ghost) so those never wait. // Clearing pulls the next deadlines back inside one tier period. diff --git a/src/modules/PlayerbotV2/Travel/ElevatorIndex.cpp b/src/modules/PlayerbotV2/Travel/ElevatorIndex.cpp index 010b21aca1..8b2d8a35d1 100644 --- a/src/modules/PlayerbotV2/Travel/ElevatorIndex.cpp +++ b/src/modules/PlayerbotV2/Travel/ElevatorIndex.cpp @@ -317,7 +317,7 @@ void ElevatorIndex::EnsureLedges(uint64_t spawn_id, Player* p) } // Derive OUTSIDE the lock — the navmesh query (NearestNavPoint) can - // LoadGrid + findNearestPoly, and we must not stall an AI worker's + // LoadGrid + findNearestPoly, and we must not stall an bot worker's // LedgeFor read for that duration. LedgeRec rec; Position out; diff --git a/src/modules/PlayerbotV2/Travel/ElevatorIndex.h b/src/modules/PlayerbotV2/Travel/ElevatorIndex.h index 71b2c54b92..2a8df117c8 100644 --- a/src/modules/PlayerbotV2/Travel/ElevatorIndex.h +++ b/src/modules/PlayerbotV2/Travel/ElevatorIndex.h @@ -121,7 +121,7 @@ public: // Read the cached ledge for a stop. Returns true and fills (lx,ly,lz) with // the walkable ledge when one was derived; false when no ledge has been // derived yet OR the derivation found none (caller should fall back to the - // platform centre). Thread-safe (taken under the index mutex), so the AI + // platform centre). Thread-safe (taken under the index mutex), so the bot logic // worker may call it while reading a published snapshot's stop. bool LedgeFor(uint64_t spawn_id, uint8_t stop_idx, float& lx, float& ly, float& lz) const; diff --git a/src/modules/PlayerbotV2/Travel/NearestNode3D.h b/src/modules/PlayerbotV2/Travel/NearestNode3D.h new file mode 100644 index 0000000000..4fb262e386 --- /dev/null +++ b/src/modules/PlayerbotV2/Travel/NearestNode3D.h @@ -0,0 +1,36 @@ +// NearestNode3D - the nearest travel-graph node to a bot, measured in 3D and skipping nodes it already failed to reach. A city has +// floors on top of each other (Ironforge: the Great Forge at z~400, the wards at z~500): the nearest node by x/y alone is often on +// another floor, unreachable from where the bot stands, so a wedged bot asked for that node again and again and never got out. +// Pure rules, tested in tests/game/ClassicNearestNode3D.cpp. + +#pragma once + +#include +#include + +namespace Playerbot::V2::Travel { + +constexpr float kNearestNodeVerticalWeight = 3.0f; // a yard of height counts like this many yards of distance + +// Index of the nearest accepted candidate within max_range, -1 when none. `at(i, x, y, z)` fills candidate i; accept(i) filters. +template +inline int PickNearestNode3D(std::size_t count, At const& at, Accept const& accept, float bx, float by, float bz, float max_range) +{ + int best = -1; + float best_d2 = max_range * max_range; + for (std::size_t i = 0; i < count; ++i) + { + float x, y, z; + at(i, x, y, z); + float const dx = x - bx, dy = y - by, dz = (z - bz) * kNearestNodeVerticalWeight; + float const d2 = dx * dx + dy * dy + dz * dz; + if (d2 < best_d2 && accept(i)) + { + best_d2 = d2; + best = int(i); + } + } + return best; +} + +} // namespace Playerbot::V2::Travel diff --git a/src/modules/PlayerbotV2/Travel/PortalPocketIndex.h b/src/modules/PlayerbotV2/Travel/PortalPocketIndex.h index 90d068c87e..cb6472183b 100644 --- a/src/modules/PlayerbotV2/Travel/PortalPocketIndex.h +++ b/src/modules/PlayerbotV2/Travel/PortalPocketIndex.h @@ -66,7 +66,7 @@ public: size_t Count() const { return _pockets.size(); } // Pocket whose bbox contains (x,y,z) on `map`, or nullptr. O(pockets) — a - // handful of entries — safe to call per-tick from the AI workers. + // handful of entries — safe to call per-tick from the bot workers. PortalPocket const* PocketContaining(uint32 map, float x, float y, float z) const; std::vector const& Pockets() const { return _pockets; } diff --git a/src/modules/PlayerbotV2/Travel/QuestHubDatabase.cpp b/src/modules/PlayerbotV2/Travel/QuestHubDatabase.cpp index 713f991c9d..79f7ebf3da 100644 --- a/src/modules/PlayerbotV2/Travel/QuestHubDatabase.cpp +++ b/src/modules/PlayerbotV2/Travel/QuestHubDatabase.cpp @@ -25,7 +25,7 @@ namespace Playerbot::V2::Travel { namespace { // Race-id -> team bit. Mirrors TC's Player::TeamForRace without pulling in -// Player.h (the per-tick lookup runs on AI worker threads which intentionally +// Player.h (the per-tick lookup runs on bot worker threads which intentionally // don't touch Player). Pandaren-neutral (24) treated as Neutral until they // pick a faction; bots are spawned with race 25/26 so that case is rare. // Bit0 Alliance, Bit1 Horde, Bit2 Neutral. @@ -411,7 +411,7 @@ LevelingHubChoice QuestHubDatabase::SelectLevelingHub( // needs only the snapshot — no Player), tag band membership, and stash the // (pointer, score, on_band) triples into a local vector. We do NOT call // is_doable here: it touches the live Player and MUST NOT run while _mutex is - // held (the database is otherwise Player-free for AI-worker safety). QuestHub + // held (the database is otherwise Player-free for bot-worker safety). QuestHub // pointers remain valid after the lock drops — _questHubs is immutable // post-init (same lock-free guarantee GetQuestHubAtPosition documents). struct Cand { QuestHub const* hub; float score; bool on_band; }; diff --git a/src/modules/PlayerbotV2/Travel/QuestHubDatabase.h b/src/modules/PlayerbotV2/Travel/QuestHubDatabase.h index f4999d1c25..0af0a10ab2 100644 --- a/src/modules/PlayerbotV2/Travel/QuestHubDatabase.h +++ b/src/modules/PlayerbotV2/Travel/QuestHubDatabase.h @@ -9,7 +9,7 @@ // // Adapted from src/modules/Playerbot/Quest/QuestHubDatabase.{h,cpp} for V2: // - Namespace Playerbot::V2::Travel. -// - Snapshot-based runtime API (no Player* on the AI worker hot path). +// - Snapshot-based runtime API (no Player* on the bot worker hot path). // - Lifecycle owned by Services::Hubs() rather than a Meyer's singleton. #pragma once diff --git a/src/modules/PlayerbotV2/Travel/RepairVendorIndex.h b/src/modules/PlayerbotV2/Travel/RepairVendorIndex.h index 90f50c17af..ecb9d6b7d8 100644 --- a/src/modules/PlayerbotV2/Travel/RepairVendorIndex.h +++ b/src/modules/PlayerbotV2/Travel/RepairVendorIndex.h @@ -12,7 +12,7 @@ // * Initialize() runs on the world thread at boot, takes the write lock, // fills the immutable vectors, then publishes them with a release store on // `_initialized`. -// * GetNearestRepairVendor() is a STRICT PURE READER on the AI worker hot +// * GetNearestRepairVendor() is a STRICT PURE READER on the bot worker hot // path: acquire-load the `_initialized` fence, take a shared_lock, scan the // bot's same-map immutable vector, return a copy. NO mutable / lazy / memo // state, NO navmesh, NO DB. It is NEVER called from the snapshot Build path diff --git a/src/modules/PlayerbotV2/Travel/TownNpcIndex.cpp b/src/modules/PlayerbotV2/Travel/TownNpcIndex.cpp index ae8731401f..a6034571dd 100644 --- a/src/modules/PlayerbotV2/Travel/TownNpcIndex.cpp +++ b/src/modules/PlayerbotV2/Travel/TownNpcIndex.cpp @@ -1,6 +1,7 @@ #include "TownNpcIndex.h" #include "CreatureData.h" +#include "GameObjectData.h" #include "DB2Stores.h" #include "DB2Structure.h" #include "Log.h" @@ -98,7 +99,31 @@ void TownNpcIndex::Initialize() ++_count; } + size_t mailboxes = 0; + for (auto const& [spawnId, data] : sObjectMgr->GetAllGameObjectData()) + { + MapEntry const* map = sMapStore.LookupEntry(data.mapId); + if (!map || !map->IsWorldMap() || data.phaseId != 0 || data.phaseGroup != 0) + continue; + if (data.spawnGroupData && (data.spawnGroupData->flags & SPAWNGROUP_FLAG_MANUAL_SPAWN)) + continue; + GameObjectTemplate const* tmpl = sObjectMgr->GetGameObjectTemplate(data.id); + if (!tmpl || tmpl->type != GAMEOBJECT_TYPE_MAILBOX) + continue; + TownNpc n; + n.spawn_id = spawnId; + n.entry = data.id; + n.map_id = data.mapId; + n.x = data.spawnPoint.GetPositionX(); + n.y = data.spawnPoint.GetPositionY(); + n.z = data.spawnPoint.GetPositionZ(); + n.alliance_ok = n.horde_ok = true; + _mail[n.map_id].push_back(n); + ++mailboxes; + } + _initialized.store(true, std::memory_order_release); + TC_LOG_INFO("playerbot.v2", "[TownNpcIndex] {} mailbox objects.", mailboxes); TC_LOG_INFO("playerbot.v2", "[TownNpcIndex] {} service NPC spawns on {} open-world maps in {} ms.", _count, _maps.size(), std::chrono::duration_cast(std::chrono::steady_clock::now() - t0).count()); @@ -174,6 +199,27 @@ TownNpc const* TownNpcIndex::Nearest(uint32 map, float x, float y, float z, uint return best; } +TownNpc const* TownNpcIndex::NearestMailbox(uint32 map, float x, float y, float z, float max_dist) const +{ + if (!_initialized.load(std::memory_order_acquire)) + return nullptr; + auto it = _mail.find(map); + if (it == _mail.end()) + return nullptr; + TownNpc const* best = nullptr; + float best_d2 = max_dist * max_dist; + for (TownNpc const& n : it->second) + { + const float dx = n.x - x, dy = n.y - y; + const float d2 = dx * dx + dy * dy; + if (d2 >= best_d2 || std::fabs(n.z - z) > 12.0f) + continue; + best = &n; + best_d2 = d2; + } + return best; +} + bool TownNpcIndex::AuctioneerNear(uint32 map, float x, float y, float radius) const { bool found = false; diff --git a/src/modules/PlayerbotV2/Travel/TownNpcIndex.h b/src/modules/PlayerbotV2/Travel/TownNpcIndex.h index 6433e79b1b..ab47be30b9 100644 --- a/src/modules/PlayerbotV2/Travel/TownNpcIndex.h +++ b/src/modules/PlayerbotV2/Travel/TownNpcIndex.h @@ -16,7 +16,7 @@ // Everlook, Ratchet) is open to both, a faction capital to its own side only. // // THREADING: Initialize() runs once on the world thread at module init, before -// any AI worker ticks, and publishes the immutable per-map grids with a release +// any bot worker ticks, and publishes the immutable per-map grids with a release // store. Every query is a pure reader (acquire fence, no locks, no state). #pragma once @@ -68,6 +68,10 @@ public: TownNpc const* Nearest(uint32 map, float x, float y, float z, uint32 flags, bool alliance, float max_dist) const; + // Nearest mailbox object on `map` within `max_dist` (2D, same floor). Mailboxes are kept apart from the service NPCs so they never + // count as a town's NPCs. + TownNpc const* NearestMailbox(uint32 map, float x, float y, float z, float max_dist) const; + // True when any auctioneer spawn (either side) stands within `radius`. // Cheap gate for the snapshot builder's auction-house scan. bool AuctioneerNear(uint32 map, float x, float y, float radius) const; @@ -83,6 +87,7 @@ private: }; std::unordered_map _maps; + std::unordered_map> _mail; // map -> mailbox object spawns size_t _count = 0; std::atomic _initialized{false}; }; diff --git a/src/modules/PlayerbotV2/Travel/UnifiedTravelGraph.cpp b/src/modules/PlayerbotV2/Travel/UnifiedTravelGraph.cpp index 35f2cfd4ae..3387b6c530 100644 --- a/src/modules/PlayerbotV2/Travel/UnifiedTravelGraph.cpp +++ b/src/modules/PlayerbotV2/Travel/UnifiedTravelGraph.cpp @@ -1,3 +1,4 @@ +#include "NearestNode3D.h" #include "UnifiedTravelGraph.h" #include "PlayerbotMovement.h" // SehSafeCalculatePath (tile-race guard) @@ -1053,6 +1054,23 @@ GraphNode const* UnifiedTravelGraph::FindNearestNodeOnMap( return best; } +GraphNode const* UnifiedTravelGraph::FindNearestNodeOnMap3D( + uint32 map_id, float x, float y, float z, float max_range, std::function const& skip) const +{ + std::shared_lock lk(_mtx); + auto it = _nodes_by_map.find(map_id); + if (it == _nodes_by_map.end()) return nullptr; + std::vector const& ids = it->second; + int const idx = PickNearestNode3D(ids.size(), + [&](std::size_t i, float& nx, float& ny, float& nz) + { + if (ids[i] >= _nodes.size()) { nx = ny = nz = 1e9f; return; } + nx = _nodes[ids[i]].x; ny = _nodes[ids[i]].y; nz = _nodes[ids[i]].z; + }, + [&](std::size_t i) { return ids[i] < _nodes.size() && !(skip && skip(_nodes[ids[i]])); }, x, y, z, max_range); + return idx < 0 ? nullptr : &_nodes[ids[std::size_t(idx)]]; +} + // ---------------------------------------------------------------- A* router namespace { @@ -1236,7 +1254,7 @@ Route UnifiedTravelGraph::FindRoute(RouteRequest const& req) const // walk, so weight it heavily; the elevator-stop nodes on the bot's // own level then win the attach and the lift edge enters the route. // (validate_source_walk does this properly with live navmesh checks - // but is world-thread-only; this heuristic covers AI-thread callers.) + // but is world-thread-only; this heuristic covers bot logic-thread callers.) auto attach_cost = [](float d2, float dz) -> float { return (d2 + 4.0f * std::fabs(dz)) / kWalkSpeedYds; }; if (auto it = _nodes_by_map.find(req.from_map); it != _nodes_by_map.end()) diff --git a/src/modules/PlayerbotV2/Travel/UnifiedTravelGraph.h b/src/modules/PlayerbotV2/Travel/UnifiedTravelGraph.h index dc667c0719..d594763a47 100644 --- a/src/modules/PlayerbotV2/Travel/UnifiedTravelGraph.h +++ b/src/modules/PlayerbotV2/Travel/UnifiedTravelGraph.h @@ -196,12 +196,12 @@ struct RouteRequest // only route that can never be executed and masking the real bridge // route (elevator / teleport) out of the pocket. Used by the snapshot // builder's wedged-objective probe. WORLD THREAD ONLY (PathGenerator - // queries the live navmesh); requires `bot`. Default off: AI-worker + // queries the live navmesh); requires `bot`. Default off: bot-worker // callers must not set this. bool validate_source_walk = false; // Skip the trivial same-map direct-walk branch and force graph A*. // Set by callers whose previously-planted direct walk WEDGED (the - // AI thread can't navmesh-validate, and geometry alone can't tell a + // Bot logic thread can't navmesh-validate, and geometry alone can't tell a // 540y/95z ramp from an elevator-only interior — Somi's UC→Brill // "trivial" walk was mesh-impossible). bool skip_trivial = false; @@ -250,6 +250,9 @@ public: // Thread-safe (shared lock). GraphNode const* FindNearestNodeOnMap(uint32 map_id, float x, float y, float max_range = 400.f) const; + // Same, measured in 3D (a floor above or below counts, see NearestNode3D.h) and skipping the nodes `skip` rejects. + GraphNode const* FindNearestNodeOnMap3D(uint32 map_id, float x, float y, float z, float max_range, + std::function const& skip) const; // Vanilla realm (IsVanillaRealm): true when a flight master creature is // spawned at this TaxiNodes entry in the world DB, i.e. a bot that walks diff --git a/src/modules/PlayerbotV2/Util/ConfigReader.cpp b/src/modules/PlayerbotV2/Util/ConfigReader.cpp index cdf58020c2..76a17d876a 100644 --- a/src/modules/PlayerbotV2/Util/ConfigReader.cpp +++ b/src/modules/PlayerbotV2/Util/ConfigReader.cpp @@ -44,9 +44,9 @@ void ConfigReader::apply_from_loaded_config() { auto& c = *sConfigMgr; - ai_worker_threads_ = c.GetIntDefault ("Playerbot.AiWorkerThreads", 0); - fleet_thread_enabled_ = c.GetBoolDefault("Playerbot.FleetThreadEnabled", true); - tick_budget_ms_ = c.GetIntDefault ("Playerbot.TickBudgetMs", 10); + ai_worker_threads_ = c.GetIntDefault ("Playerbot.AiWorkerThreads", 0, true); + fleet_thread_enabled_ = c.GetBoolDefault("Playerbot.FleetThreadEnabled", true, true); + tick_budget_ms_ = c.GetIntDefault ("Playerbot.TickBudgetMs", 10, true); // #5 Phase 4 parallel snapshot Build. DEFAULT ON. The 2026-06-15 crash // (ACCESS_VIOLATION in Build->objective_blacklisted, serial AND parallel) was // ultimately ABI SKEW: another session's uncommitted BotAI.h change (added @@ -56,170 +56,173 @@ void ConfigReader::apply_from_loaded_config() // read. Fixed by a clean recompile of all playerbot TUs. The genuine parallel // concern (concurrent Registry().ai() rehash) was separately fixed by // pre-resolving the BotAI* on the world thread. Kill-switch: set =0 to serial. - parallel_snapshot_build_ = c.GetBoolDefault("PlayerbotV2.ParallelSnapshotBuild", true); - snapshot_build_threads_ = c.GetIntDefault ("PlayerbotV2.SnapshotBuildThreads", 0); + parallel_snapshot_build_ = c.GetBoolDefault("PlayerbotV2.ParallelSnapshotBuild", true, true); + snapshot_build_threads_ = c.GetIntDefault ("PlayerbotV2.SnapshotBuildThreads", 0, true); // Classic 1.60 (Forever) default: 0 = no ambient world bots, owner bots only. - pop_target_ = c.GetIntDefault ("Playerbot.Population.TotalTarget", 0); - pop_horde_pct_ = static_cast(c.GetIntDefault("Playerbot.Population.HordePct", 50)); - pop_shape_ = c.GetStringDefault("Playerbot.Population.Shape", "MaxHeavy"); - pop_max_heavy_factor_ = float(c.GetFloatDefault("Playerbot.Population.MaxHeavyFactor", 0.40f)); + pop_target_ = c.GetIntDefault ("Playerbot.Population.TotalTarget", 0, true); + pop_horde_pct_ = static_cast(c.GetIntDefault("Playerbot.Population.HordePct", 50, true)); + pop_shape_ = c.GetStringDefault("Playerbot.Population.Shape", "MaxHeavy", true); + pop_max_heavy_factor_ = float(c.GetFloatDefault("Playerbot.Population.MaxHeavyFactor", 0.40f, true)); - accept_invites_ = c.GetStringDefault("Playerbot.Interact.AutoAcceptInvites", "friends_or_higher"); - auto_leader_handover_ = c.GetBoolDefault ("Playerbot.Interact.AutoLeaderHandover", true); + accept_invites_ = c.GetStringDefault("Playerbot.Interact.AutoAcceptInvites", "friends_or_higher", true); + auto_leader_handover_ = c.GetBoolDefault ("Playerbot.Interact.AutoLeaderHandover", true, true); { - std::string prefix = c.GetStringDefault("Playerbot.Interact.CommandPrefix", "!"); + std::string prefix = c.GetStringDefault("Playerbot.Interact.CommandPrefix", "!", true); command_prefix_ = prefix.empty() ? '!' : prefix[0]; } - raid_enabled_ = c.GetBoolDefault("Playerbot.Raid.Enable", true); - boss_warnings_enabled_ = c.GetBoolDefault("Playerbot.Raid.BossWarnings", true); - raid_auto_accept_rez_ = c.GetBoolDefault("Playerbot.Raid.AutoAcceptOwnerRez", true); + raid_enabled_ = c.GetBoolDefault("Playerbot.Raid.Enable", true, true); + boss_warnings_enabled_ = c.GetBoolDefault("Playerbot.Raid.BossWarnings", true, true); + raid_auto_accept_rez_ = c.GetBoolDefault("Playerbot.Raid.AutoAcceptOwnerRez", true, true); - housing_enabled_ = c.GetBoolDefault("Playerbot.Housing.Enabled", true); - nbhd_target_pct_ = static_cast(c.GetIntDefault("Playerbot.Housing.NeighborhoodTargetOccupancy", 60)); + housing_enabled_ = c.GetBoolDefault("Playerbot.Housing.Enabled", false, true); + nbhd_target_pct_ = static_cast(c.GetIntDefault("Playerbot.Housing.NeighborhoodTargetOccupancy", 60, true)); { - std::string strict = c.GetStringDefault("Playerbot.Housing.PlotPurchaseEligibilityCheck", "strict"); + std::string strict = c.GetStringDefault("Playerbot.Housing.PlotPurchaseEligibilityCheck", "strict", true); housing_strict_ = (strict != "lenient"); } - health_port_ = static_cast(c.GetIntDefault("Playerbot.Diag.HealthEndpointPort", 0)); - log_level_ = c.GetStringDefault("Playerbot.Log.Level", "info"); + health_port_ = static_cast(c.GetIntDefault("Playerbot.Diag.HealthEndpointPort", 0, true)); + log_level_ = c.GetStringDefault("Playerbot.Log.Level", "info", true); - auto_resume_on_boot_ = c.GetBoolDefault("Playerbot.V2.AutoResumeOnBoot", false); - auto_resume_cap_ = c.GetIntDefault ("Playerbot.V2.AutoResumeCap", 100); - auto_spawn_on_boot_ = c.GetIntDefault ("Playerbot.V2.AutoSpawnOnBoot", 0); - random_personality_ = c.GetBoolDefault("Playerbot.V2.RandomPersonality", true); - archetype_enabled_ = c.GetBoolDefault("PlayerbotV2.Archetype.Enabled", true); - economy_buy_enabled_ = c.GetBoolDefault("PlayerbotV2.Economy.BuyEnabled", true); - economy_bot_auctions_enabled_ = c.GetBoolDefault("PlayerbotV2.Economy.BotAuctions", false); - classic_class_supplies_ = c.GetBoolDefault("PlayerbotV2.Classic.ClassSupplies", true); + auto_resume_on_boot_ = c.GetBoolDefault("Playerbot.V2.AutoResumeOnBoot", false, true); + auto_resume_cap_ = c.GetIntDefault ("Playerbot.V2.AutoResumeCap", 100, true); + auto_spawn_on_boot_ = c.GetIntDefault ("Playerbot.V2.AutoSpawnOnBoot", 0, true); + random_personality_ = c.GetBoolDefault("Playerbot.V2.RandomPersonality", true, true); + archetype_enabled_ = c.GetBoolDefault("PlayerbotV2.Archetype.Enabled", true, true); + economy_buy_enabled_ = c.GetBoolDefault("PlayerbotV2.Economy.BuyEnabled", true, true); + economy_bot_auctions_enabled_ = c.GetBoolDefault("PlayerbotV2.Economy.BotAuctions", false, true); + classic_class_supplies_ = c.GetBoolDefault("PlayerbotV2.Classic.ClassSupplies", true, true); economy_max_reagent_vendor_multiple_ = static_cast( - c.GetIntDefault("PlayerbotV2.Economy.MaxReagentVendorMultiple", 15)); - session_rhythm_enabled_ = c.GetBoolDefault("PlayerbotV2.SessionRhythm.Enabled", true); - session_rhythm_multiplier_ = float(c.GetFloatDefault("PlayerbotV2.SessionRhythm.Multiplier", 1.0f)); + c.GetIntDefault("PlayerbotV2.Economy.MaxReagentVendorMultiple", 15, true)); + session_rhythm_enabled_ = c.GetBoolDefault("PlayerbotV2.SessionRhythm.Enabled", false, true); + session_rhythm_multiplier_ = float(c.GetFloatDefault("PlayerbotV2.SessionRhythm.Multiplier", 1.0f, true)); session_rhythm_max_logouts_per_cycle_ = static_cast( - c.GetIntDefault("PlayerbotV2.SessionRhythm.MaxLogoutsPerCycle", 25)); + c.GetIntDefault("PlayerbotV2.SessionRhythm.MaxLogoutsPerCycle", 25, true)); - guilds_enabled_ = c.GetBoolDefault("PlayerbotV2.Guilds.Enabled", true); - guilds_target_count_per_faction_ = static_cast(c.GetIntDefault("PlayerbotV2.Guilds.TargetCountPerFaction", 6)); - guilds_max_members_per_guild_ = static_cast(c.GetIntDefault("PlayerbotV2.Guilds.MaxMembersPerGuild", 75)); - guilds_events_enabled_ = c.GetBoolDefault("PlayerbotV2.Guilds.EventsEnabled", true); - guilds_recruitment_channel_enabled_ = c.GetBoolDefault("PlayerbotV2.Guilds.RecruitmentChannelEnabled", true); + guilds_enabled_ = c.GetBoolDefault("PlayerbotV2.Guilds.Enabled", false, true); + guilds_target_count_per_faction_ = static_cast(c.GetIntDefault("PlayerbotV2.Guilds.TargetCountPerFaction", 6, true)); + guilds_max_members_per_guild_ = static_cast(c.GetIntDefault("PlayerbotV2.Guilds.MaxMembersPerGuild", 75, true)); + guilds_events_enabled_ = c.GetBoolDefault("PlayerbotV2.Guilds.EventsEnabled", true, true); + guilds_recruitment_channel_enabled_ = c.GetBoolDefault("PlayerbotV2.Guilds.RecruitmentChannelEnabled", true, true); max_alts_as_bots_ = static_cast( - c.GetIntDefault("PlayerbotV2.MaxAltsAsBots", 5)); + c.GetIntDefault("PlayerbotV2.MaxAltsAsBots", 5, true)); wedge_watchdog_threshold_ms_ = static_cast( - c.GetIntDefault("PlayerbotV2.WedgeWatchdog.ThresholdMs", 90000)); + c.GetIntDefault("PlayerbotV2.WedgeWatchdog.ThresholdMs", 90000, true)); wedge_watchdog_combat_threshold_ms_ = static_cast( - c.GetIntDefault("PlayerbotV2.WedgeWatchdog.CombatThresholdMs", 180000)); + c.GetIntDefault("PlayerbotV2.WedgeWatchdog.CombatThresholdMs", 180000, true)); wedge_watchdog_min_displacement_ = static_cast( - c.GetFloatDefault("PlayerbotV2.WedgeWatchdog.MinDisplacementYards", 20.0f)); - wedge_remediation_enabled_ = c.GetBoolDefault("PlayerbotV2.WedgeWatchdog.RemediationEnabled", true); + c.GetFloatDefault("PlayerbotV2.WedgeWatchdog.MinDisplacementYards", 20.0f, true)); + wedge_remediation_enabled_ = c.GetBoolDefault("PlayerbotV2.WedgeWatchdog.RemediationEnabled", true, true); wedge_remediation_ms_ = static_cast( - c.GetIntDefault("PlayerbotV2.WedgeWatchdog.RemediationMs", 180000)); - wedge_noprogress_enabled_ = c.GetBoolDefault("PlayerbotV2.WedgeWatchdog.NoProgressEnabled", true); + c.GetIntDefault("PlayerbotV2.WedgeWatchdog.RemediationMs", 180000, true)); + wedge_noprogress_enabled_ = c.GetBoolDefault("PlayerbotV2.WedgeWatchdog.NoProgressEnabled", true, true); wedge_noprogress_ms_ = static_cast( - c.GetIntDefault("PlayerbotV2.WedgeWatchdog.NoProgressMs", 900000)); + c.GetIntDefault("PlayerbotV2.WedgeWatchdog.NoProgressMs", 900000, true)); wedge_noprogress_radius_ = static_cast( - c.GetFloatDefault("PlayerbotV2.WedgeWatchdog.NoProgressRadiusYards", 150.0f)); + c.GetFloatDefault("PlayerbotV2.WedgeWatchdog.NoProgressRadiusYards", 150.0f, true)); - alert_wedged_bots_ = static_cast(c.GetIntDefault("PlayerbotV2.Alert.WedgedBots", 5)); - alert_tick_p99_us_ = static_cast(c.GetIntDefault("PlayerbotV2.Alert.TickP99Us", 200000)); - alert_intent_drop_per_min_ = static_cast(c.GetIntDefault("PlayerbotV2.Alert.IntentDropPerMin", 600)); - alert_path_fail_per_min_ = static_cast(c.GetIntDefault("PlayerbotV2.Alert.PathFailPerMin", 300)); - alert_throttle_ms_ = static_cast(c.GetIntDefault("PlayerbotV2.Alert.ThrottleMs", 300000)); + alert_wedged_bots_ = static_cast(c.GetIntDefault("PlayerbotV2.Alert.WedgedBots", 5, true)); + alert_tick_p99_us_ = static_cast(c.GetIntDefault("PlayerbotV2.Alert.TickP99Us", 200000, true)); + alert_intent_drop_per_min_ = static_cast(c.GetIntDefault("PlayerbotV2.Alert.IntentDropPerMin", 600, true)); + alert_path_fail_per_min_ = static_cast(c.GetIntDefault("PlayerbotV2.Alert.PathFailPerMin", 300, true)); + alert_throttle_ms_ = static_cast(c.GetIntDefault("PlayerbotV2.Alert.ThrottleMs", 300000, true)); - pull_gate_enabled_ = c.GetBoolDefault("PlayerbotV2.PullGate.Enabled", true); - pull_gate_max_ratio_ = float(c.GetFloatDefault("PlayerbotV2.PullGate.MaxDetourRatio", 3.0f)); - pull_gate_min_extra_yards_ = float(c.GetFloatDefault("PlayerbotV2.PullGate.MinExtraYards", 40.0f)); - pull_gate_disengage_enabled_ = c.GetBoolDefault("PlayerbotV2.PullGate.DisengageEnabled", true); - tank_commit_enabled_ = c.GetBoolDefault("PlayerbotV2.PullGate.TankCommitEnabled", true); + pull_gate_enabled_ = c.GetBoolDefault("PlayerbotV2.PullGate.Enabled", true, true); + pull_gate_max_ratio_ = float(c.GetFloatDefault("PlayerbotV2.PullGate.MaxDetourRatio", 3.0f, true)); + pull_gate_min_extra_yards_ = float(c.GetFloatDefault("PlayerbotV2.PullGate.MinExtraYards", 40.0f, true)); + pull_gate_disengage_enabled_ = c.GetBoolDefault("PlayerbotV2.PullGate.DisengageEnabled", true, true); + tank_commit_enabled_ = c.GetBoolDefault("PlayerbotV2.PullGate.TankCommitEnabled", true, true); tank_commit_max_ms_ = static_cast( - c.GetIntDefault("PlayerbotV2.PullGate.TankCommitMaxMs", 45000)); + c.GetIntDefault("PlayerbotV2.PullGate.TankCommitMaxMs", 45000, true)); - move_step_hold_enabled_ = c.GetBoolDefault("PlayerbotV2.Move.StepHoldEnabled", true); + move_step_hold_enabled_ = c.GetBoolDefault("PlayerbotV2.Move.StepHoldEnabled", true, true); route_aware_combat_advance_ = c.GetBoolDefault( - "PlayerbotV2.Move.RouteAwareCombatAdvance", true); + "PlayerbotV2.Move.RouteAwareCombatAdvance", true, true); combat_skip_unfightable_ = c.GetBoolDefault( - "PlayerbotV2.Combat.SkipUnfightable", true); + "PlayerbotV2.Combat.SkipUnfightable", true, true); - threat_hold_enabled_ = c.GetBoolDefault("PlayerbotV2.Threat.HoldEnabled", true); - raid_dps_wait_attack_ = c.GetBoolDefault("Playerbot.Raid.DpsWaitForAttack", true); - raid_provide_consumables_ = c.GetBoolDefault("Playerbot.Raid.ProvideConsumables", false); - consumables_pve_ = c.GetBoolDefault("Playerbot.Consumables.PvE", true); - consumables_pvp_ = c.GetBoolDefault("Playerbot.Consumables.PvP", false); - raid_dps_wait_timeout_ms_ = uint32(std::clamp(int64(c.GetIntDefault("Playerbot.Raid.DpsWaitTimeoutMs", 10000)), 0, 600000)); - threat_hold_open_world_ = c.GetBoolDefault("PlayerbotV2.Threat.HoldInOpenWorld", false); - threat_max_ratio_ = std::clamp(float(c.GetFloatDefault("PlayerbotV2.Threat.MaxRatio", 0.9f)), 0.3f, 1.2f); - threat_opening_lead_boss_ = std::max(0.0f, float(c.GetFloatDefault("PlayerbotV2.Threat.OpeningLeadBoss", 900.0f))); - threat_opening_lead_trash_ = std::max(0.0f, float(c.GetFloatDefault("PlayerbotV2.Threat.OpeningLeadTrash", 250.0f))); + threat_hold_enabled_ = c.GetBoolDefault("PlayerbotV2.Threat.HoldEnabled", true, true); + raid_dps_wait_attack_ = c.GetBoolDefault("Playerbot.Raid.DpsWaitForAttack", true, true); + raid_provide_consumables_ = c.GetBoolDefault("Playerbot.Raid.ProvideConsumables", true, true); + consumables_pve_ = c.GetBoolDefault("Playerbot.Consumables.PvE", true, true); + consumables_pvp_ = c.GetBoolDefault("Playerbot.Consumables.PvP", false, true); + raid_dps_wait_timeout_ms_ = uint32(std::clamp(int64(c.GetIntDefault("Playerbot.Raid.DpsWaitTimeoutMs", 6000, true)), 1000, 6000)); + threat_hold_open_world_ = c.GetBoolDefault("PlayerbotV2.Threat.HoldInOpenWorld", false, true); + threat_max_ratio_ = std::clamp(float(c.GetFloatDefault("PlayerbotV2.Threat.MaxRatio", 0.9f, true)), 0.3f, 1.2f); + threat_opening_lead_boss_ = std::max(0.0f, float(c.GetFloatDefault("PlayerbotV2.Threat.OpeningLeadBoss", 900.0f, true))); + threat_opening_lead_trash_ = std::max(0.0f, float(c.GetFloatDefault("PlayerbotV2.Threat.OpeningLeadTrash", 250.0f, true))); threat_opening_wait_boss_ms_ = static_cast( - c.GetIntDefault("PlayerbotV2.Threat.OpeningWaitBossMs", 6000)); + c.GetIntDefault("PlayerbotV2.Threat.OpeningWaitBossMs", 6000, true)); threat_opening_wait_trash_ms_ = static_cast( - c.GetIntDefault("PlayerbotV2.Threat.OpeningWaitTrashMs", 2000)); + c.GetIntDefault("PlayerbotV2.Threat.OpeningWaitTrashMs", 2000, true)); - bhv_owner_follow_hold_ = c.GetBoolDefault("Playerbot.Behavior.OwnerFollowHold", true); - bhv_fallback_ = c.GetBoolDefault("Playerbot.Behavior.Fallback", true); - bhv_pull_back_ = c.GetBoolDefault("Playerbot.Behavior.PullBack", true); - bhv_tank_ranged_weapon_ = c.GetBoolDefault("Playerbot.Behavior.TankRangedWeapon", true); - bhv_ammo_supply_ = c.GetBoolDefault("Playerbot.Behavior.AmmoSupply", true); - bhv_raid_gear_ = c.GetBoolDefault("Playerbot.Behavior.RaidGear", true); - bhv_accept_owner_trade_ = c.GetBoolDefault("Playerbot.Behavior.AcceptOwnerTrade", true); - bhv_formation_ = c.GetBoolDefault("Playerbot.Behavior.Formation", true); - bhv_distance_order_ = c.GetBoolDefault("Playerbot.Behavior.DistanceOrder", true); - bhv_owner_main_tank_ = c.GetBoolDefault("Playerbot.Behavior.OwnerMainTank", true); - bhv_heal_claims_ = c.GetBoolDefault("Playerbot.Behavior.HealClaims", true); - bhv_cast_facing_ = c.GetBoolDefault("Playerbot.Behavior.CastFacing", true); - bhv_ground_snap_ = c.GetBoolDefault("Playerbot.Behavior.GroundSnap", true); - bhv_re_face_ = c.GetBoolDefault("Playerbot.Behavior.ReFace", true); - bhv_avoid_circles_ = c.GetBoolDefault("Playerbot.Behavior.AvoidCircles", true); - bhv_pack_stop_ = c.GetBoolDefault("Playerbot.Behavior.PackStop", true); - bhv_raid_spacing_ = c.GetBoolDefault("Playerbot.Behavior.RaidSpacing", true); - bhv_spread_out_ = c.GetBoolDefault("Playerbot.Behavior.SpreadOut", true); - bhv_loose_mob_hold_ = c.GetBoolDefault("Playerbot.Behavior.LooseMobHold", true); - bhv_raid_buff_hold_ = c.GetBoolDefault("Playerbot.Behavior.RaidBuffHold", true); - bhv_dungeon_loot_ = c.GetBoolDefault("Playerbot.Behavior.DungeonLoot", true); - bhv_warrior_stance_dance_ = c.GetBoolDefault("Playerbot.Behavior.WarriorStanceDance", true); - bhv_bot_whisperable_ = c.GetBoolDefault("Playerbot.Behavior.BotWhisperable", true); - chatter_conversation_ = c.GetBoolDefault("Playerbot.Chatter.Conversation", true); - bhv_world_bot_say_reply_ = c.GetBoolDefault("Playerbot.Behavior.WorldBotSayReply", true); - bhv_instance_group_cap_ = c.GetBoolDefault("Playerbot.Behavior.InstanceGroupCap", false); - bhv_open_world_group_cap_ = std::clamp(c.GetIntDefault("Playerbot.Behavior.OpenWorldGroupCap", 5), 1, 40); - bhv_bg_human_priority_ = c.GetBoolDefault("Playerbot.Behavior.BgHumanPriority", true); - bhv_tank_markers_ = c.GetBoolDefault("Playerbot.Behavior.TankMarkers", true); - bhv_mark_cc_ = c.GetBoolDefault("Playerbot.Behavior.MarkCc", true); - bhv_dungeon_flow_ = c.GetBoolDefault("Playerbot.Behavior.DungeonFlow", true); - bhv_dungeon_autopilot_ = c.GetBoolDefault("Playerbot.Behavior.DungeonAutopilot", true); - bhv_marks_need_order_ = c.GetBoolDefault("Playerbot.Behavior.MarksNeedOrder", true); - bhv_pull_recover_ = c.GetBoolDefault("Playerbot.Behavior.PullRecover", true); - bhv_loot_policy_ = c.GetBoolDefault("Playerbot.Behavior.LootPolicy", true); - bhv_wipe_release_wait_ = c.GetBoolDefault("Playerbot.Behavior.WipeReleaseWait", true); - bhv_ready_check_info_ = c.GetBoolDefault("Playerbot.Behavior.ReadyCheckInfo", true); - bhv_purge_duty_ = c.GetBoolDefault("Playerbot.Behavior.PurgeDuty", true); - bhv_ranged_slow_ = c.GetBoolDefault("Playerbot.Behavior.RangedSlow", true); - bhv_ike3_commands_ = c.GetBoolDefault("Playerbot.Behavior.Ike3Commands", true); - bhv_owner_commands_ = c.GetBoolDefault("Playerbot.Behavior.OwnerCommands", true); - bhv_fidget_ = c.GetBoolDefault("Playerbot.Behavior.Fidget", true); - bhv_pull_discipline_ = c.GetBoolDefault("Playerbot.Behavior.PullDiscipline", true); - bhv_solo_flee_ = c.GetBoolDefault("Playerbot.Behavior.SoloFlee", true); - bhv_druid_heal_form_ = c.GetBoolDefault("Playerbot.Behavior.DruidHealForm", true); - bhv_party_banter_ = c.GetBoolDefault("Playerbot.Behavior.PartyBanter", true); - bhv_social_emotes_ = c.GetBoolDefault("Playerbot.Behavior.SocialEmotes", true); - bhv_polite_world_bots_ = c.GetBoolDefault("Playerbot.Behavior.PoliteWorldBots", true); - bhv_quest_accept_ = c.GetBoolDefault("Playerbot.Behavior.QuestAccept", true); - bhv_quest_share_ = c.GetBoolDefault("Playerbot.Behavior.QuestShare", true); - bhv_quest_turn_in_ = c.GetBoolDefault("Playerbot.Behavior.QuestTurnIn", true); - bhv_quest_loot_ = c.GetBoolDefault("Playerbot.Behavior.QuestLoot", true); + bhv_owner_follow_hold_ = c.GetBoolDefault("Playerbot.Behavior.OwnerFollowHold", true, true); + bhv_fallback_ = c.GetBoolDefault("Playerbot.Behavior.Fallback", true, true); + bhv_pull_back_ = c.GetBoolDefault("Playerbot.Behavior.PullBack", true, true); + bhv_tank_ranged_weapon_ = c.GetBoolDefault("Playerbot.Behavior.TankRangedWeapon", true, true); + bhv_ammo_supply_ = c.GetBoolDefault("Playerbot.Behavior.AmmoSupply", true, true); + bhv_raid_gear_ = c.GetBoolDefault("Playerbot.Behavior.RaidGear", true, true); + bhv_accept_owner_trade_ = c.GetBoolDefault("Playerbot.Behavior.AcceptOwnerTrade", true, true); + bhv_formation_ = c.GetBoolDefault("Playerbot.Behavior.Formation", true, true); + bhv_distance_order_ = c.GetBoolDefault("Playerbot.Behavior.DistanceOrder", true, true); + bhv_owner_main_tank_ = c.GetBoolDefault("Playerbot.Behavior.OwnerMainTank", true, true); + bhv_heal_claims_ = c.GetBoolDefault("Playerbot.Behavior.HealClaims", true, true); + bhv_cast_facing_ = c.GetBoolDefault("Playerbot.Behavior.CastFacing", true, true); + bhv_ground_snap_ = c.GetBoolDefault("Playerbot.Behavior.GroundSnap", true, true); + bhv_re_face_ = c.GetBoolDefault("Playerbot.Behavior.ReFace", true, true); + bhv_avoid_circles_ = c.GetBoolDefault("Playerbot.Behavior.AvoidCircles", true, true); + bhv_pack_stop_ = c.GetBoolDefault("Playerbot.Behavior.PackStop", true, true); + bhv_raid_spacing_ = c.GetBoolDefault("Playerbot.Behavior.RaidSpacing", true, true); + bhv_spread_out_ = c.GetBoolDefault("Playerbot.Behavior.SpreadOut", true, true); + bhv_loose_mob_hold_ = c.GetBoolDefault("Playerbot.Behavior.LooseMobHold", true, true); + bhv_raid_buff_hold_ = c.GetBoolDefault("Playerbot.Behavior.RaidBuffHold", true, true); + bhv_dungeon_loot_ = c.GetBoolDefault("Playerbot.Behavior.DungeonLoot", true, true); + bhv_warrior_stance_dance_ = c.GetBoolDefault("Playerbot.Behavior.WarriorStanceDance", true, true); + bhv_bot_whisperable_ = c.GetBoolDefault("Playerbot.Behavior.BotWhisperable", true, true); + chatter_conversation_ = c.GetBoolDefault("Playerbot.Chatter.Conversation", true, true); + bhv_world_bot_say_reply_ = c.GetBoolDefault("Playerbot.Behavior.WorldBotSayReply", true, true); + bhv_instance_group_cap_ = c.GetBoolDefault("Playerbot.Behavior.InstanceGroupCap", false, true); + bhv_open_world_group_cap_ = std::clamp(c.GetIntDefault("Playerbot.Behavior.OpenWorldGroupCap", 5, true), 1, 40); + bhv_bg_human_priority_ = c.GetBoolDefault("Playerbot.Behavior.BgHumanPriority", true, true); + bhv_tank_markers_ = c.GetBoolDefault("Playerbot.Behavior.TankMarkers", true, true); + bhv_mark_cc_ = c.GetBoolDefault("Playerbot.Behavior.MarkCc", true, true); + bhv_dungeon_flow_ = c.GetBoolDefault("Playerbot.Behavior.DungeonFlow", true, true); + bhv_dungeon_autopilot_ = c.GetBoolDefault("Playerbot.Behavior.DungeonAutopilot", true, true); + bhv_marks_need_order_ = c.GetBoolDefault("Playerbot.Behavior.MarksNeedOrder", true, true); + bhv_pull_recover_ = c.GetBoolDefault("Playerbot.Behavior.PullRecover", true, true); + bhv_loot_policy_ = c.GetBoolDefault("Playerbot.Behavior.LootPolicy", true, true); + bhv_wipe_release_wait_ = c.GetBoolDefault("Playerbot.Behavior.WipeReleaseWait", true, true); + bhv_ready_check_info_ = c.GetBoolDefault("Playerbot.Behavior.ReadyCheckInfo", true, true); + bhv_purge_duty_ = c.GetBoolDefault("Playerbot.Behavior.PurgeDuty", true, true); + bhv_ranged_slow_ = c.GetBoolDefault("Playerbot.Behavior.RangedSlow", true, true); + bhv_ike3_commands_ = c.GetBoolDefault("Playerbot.Behavior.Ike3Commands", true, true); + bhv_owner_commands_ = c.GetBoolDefault("Playerbot.Behavior.OwnerCommands", true, true); + bhv_fidget_ = c.GetBoolDefault("Playerbot.Behavior.Fidget", true, true); + addon_hint_enabled_ = c.GetBoolDefault("Playerbot.AddonHint.Enable", false, true); + addon_hint_delay_sec_ = uint32(std::clamp(c.GetIntDefault("Playerbot.AddonHint.DelaySec", 30, true), 5, 600)); + addon_hint_url_ = c.GetStringDefault("Playerbot.AddonHint.Url", addon_hint_url_, true); + bhv_pull_discipline_ = c.GetBoolDefault("Playerbot.Behavior.PullDiscipline", true, true); + bhv_solo_flee_ = c.GetBoolDefault("Playerbot.Behavior.SoloFlee", true, true); + bhv_druid_heal_form_ = c.GetBoolDefault("Playerbot.Behavior.DruidHealForm", true, true); + bhv_party_banter_ = c.GetBoolDefault("Playerbot.Behavior.PartyBanter", true, true); + bhv_social_emotes_ = c.GetBoolDefault("Playerbot.Behavior.SocialEmotes", true, true); + bhv_polite_world_bots_ = c.GetBoolDefault("Playerbot.Behavior.PoliteWorldBots", true, true); + bhv_quest_accept_ = c.GetBoolDefault("Playerbot.Behavior.QuestAccept", true, true); + bhv_quest_share_ = c.GetBoolDefault("Playerbot.Behavior.QuestShare", true, true); + bhv_quest_turn_in_ = c.GetBoolDefault("Playerbot.Behavior.QuestTurnIn", true, true); + bhv_quest_loot_ = c.GetBoolDefault("Playerbot.Behavior.QuestLoot", true, true); { auto pct = [&](char const* key, int32 def, int32 lo, int32 hi) { - return uint32(std::clamp(c.GetIntDefault(key, def), lo, hi)); + return uint32(std::clamp(c.GetIntDefault(key, def, true), lo, hi)); }; CastPacing p; - p.enabled = c.GetBoolDefault("Playerbot.Cast.Enable", false); - p.raid_pct = pct("Playerbot.Cast.RaidSpeedPct", 80, 10, 300); + p.enabled = c.GetBoolDefault("Playerbot.Cast.Enable", false, true); + p.raid_pct = pct("Playerbot.Cast.RaidSpeedPct", 75, 10, 300); p.dungeon_pct = pct("Playerbot.Cast.DungeonSpeedPct", 90, 10, 300); p.world_pct = pct("Playerbot.Cast.WorldSpeedPct", 100, 10, 300); p.bg_pct = pct("Playerbot.Cast.BgSpeedPct", 115, 10, 300); @@ -233,15 +236,15 @@ void ConfigReader::apply_from_loaded_config() q.pvp_reaction_delay_ms = pct("Playerbot.Pacing.PvpReactionDelayMs", 700, 0, 3000); pacing_ = q; BgAutoJoin j; - j.enabled = c.GetBoolDefault("Playerbot.Bg.AutoJoin", false); + j.enabled = c.GetBoolDefault("Playerbot.Bg.AutoJoin", false, true); j.chance_pct = pct("Playerbot.Bg.AutoJoin.Chance", 3, 0, 100); j.max_queued = pct("Playerbot.Bg.AutoJoin.MaxQueued", 24, 0, 500); j.max_per_tick = pct("Playerbot.Bg.AutoJoin.MaxPerTick", 2, 1, 50); j.cooldown_min = pct("Playerbot.Bg.AutoJoin.CooldownMin", 20, 0, 600); j.queue_timeout_min = pct("Playerbot.Bg.AutoJoin.QueueTimeoutMin", 25, 1, 240); j.min_level = pct("Playerbot.Bg.AutoJoin.MinLevel", 10, 1, 255); - j.make_room = c.GetBoolDefault("Playerbot.Bg.MakeRoomForPlayers", true); - j.types = c.GetStringDefault("Playerbot.Bg.AutoJoin.Types", ""); + j.make_room = c.GetBoolDefault("Playerbot.Bg.MakeRoomForPlayers", true, true); + j.types = c.GetStringDefault("Playerbot.Bg.AutoJoin.Types", "", true); bg_auto_join_ = std::move(j); } } diff --git a/src/modules/PlayerbotV2/Util/ConfigReader.h b/src/modules/PlayerbotV2/Util/ConfigReader.h index ff2ad4c22c..ec5c1724d9 100644 --- a/src/modules/PlayerbotV2/Util/ConfigReader.h +++ b/src/modules/PlayerbotV2/Util/ConfigReader.h @@ -227,7 +227,7 @@ public: // - alert_wedged_bots: max acceptable concurrently-wedged bot count. // - alert_tick_p99_us: max acceptable tick p99 latency in microseconds. // - alert_intent_drop_per_min: max acceptable IntentQueue drops/min - // (sustained drops = an AI worker outrunning the world-thread drain). + // (sustained drops = an bot worker outrunning the world-thread drain). // - alert_path_fail_per_min: max acceptable path-validation failures/min. // - alert_throttle_ms: per-metric re-emit suppression window (default 5m) // so a sustained breach logs once per window, not once per sample. @@ -288,7 +288,7 @@ public: // (PlayerbotV2.Combat.SkipUnfightable) bool combat_skip_unfightable() const { return combat_skip_unfightable_; } - // Group threat discipline (port of Karrz's ike3-based bots GroupPveRestraint / + // Group threat discipline (port of Karrz's wow-1.12 GroupPveRestraint / // MCRaidHoldDamage). Non-tank bots in a group with a tank hold damage // until the tank has an opening threat lead and stay under max_ratio of // the tank's threat. Leads are level-60 values, scaled by bot level. @@ -310,7 +310,7 @@ public: // Behaviour switches (Playerbot.Behavior., default on = current behaviour). Each gate // makes its behaviour fall back to the previous simple path. Cached at load, so they are - // readable from the AI worker threads as well as the world thread. + // readable from the bot worker threads as well as the world thread. bool behavior_owner_follow_hold() const { return bhv_owner_follow_hold_; } bool behavior_fallback() const { return bhv_fallback_; } bool behavior_pull_back() const { return bhv_pull_back_; } @@ -353,6 +353,10 @@ public: bool behavior_ike3_commands() const { return bhv_ike3_commands_; } bool behavior_owner_commands() const { return bhv_owner_commands_; } bool behavior_fidget() const { return bhv_fidget_; } + // Players who log in without the ForeverBots add-on get one line with its download link. + bool addon_hint_enabled() const { return addon_hint_enabled_; } + uint32 addon_hint_delay_sec() const { return addon_hint_delay_sec_; } + std::string const& addon_hint_url() const { return addon_hint_url_; } bool behavior_pull_discipline() const { return bhv_pull_discipline_; } bool behavior_solo_flee() const { return bhv_solo_flee_; } bool behavior_druid_heal_form() const { return bhv_druid_heal_form_; } @@ -385,7 +389,7 @@ public: // Playerbot.Pacing.*, Karrz's VMaNGOS model. decision_delay_ms is a CEILING on how long a // bot waits to decide again after a cast (no tier is allowed a longer period; the shipped // tiers are already faster, so it never slows a bot). pvp_reaction_delay_ms is a FLOOR on - // the per-bot AI-tick / snapshot period while the bot is in PvP (battleground, active duel, + // the per-bot bot logic-tick / snapshot period while the bot is in PvP (battleground, active duel, // or in combat with players); never in PvE. 0 = off, 0..3000. struct Pacing { @@ -543,6 +547,9 @@ private: bool bhv_ike3_commands_ = true; bool bhv_owner_commands_ = true; bool bhv_fidget_ = true; + bool addon_hint_enabled_ = false; + uint32 addon_hint_delay_sec_ = 30; + std::string addon_hint_url_ = "https://github.com/Karrz1/Karrz-playerbots-wow-forever/raw/main/addon/ForeverBots-addon.zip"; bool bhv_pull_discipline_ = true; bool bhv_solo_flee_ = true; bool bhv_druid_heal_form_ = true; diff --git a/src/modules/PlayerbotV2/WORLD_BOTS.md b/src/modules/PlayerbotV2/WORLD_BOTS.md index 2ef77d289c..1c9e62c60f 100644 --- a/src/modules/PlayerbotV2/WORLD_BOTS.md +++ b/src/modules/PlayerbotV2/WORLD_BOTS.md @@ -12,7 +12,7 @@ Branch `playerbot-v2-world`, cut from `playerbot-v2-raid` 91236c23. Owner: the " | Despawn | session rhythm, LRU overflow | no real player within `DespawnRadius` | | Use it for | "1000 bots live in the world" load test | "bots are around me wherever I go" | -Both reuse the same pool characters, `BotCharacterFactory`, `BotSetupPipeline` (level, trainer spells, weapon skills, talents, gear, riding, then a first teleport to a leveling town), and the same bot AI (questing, travel, grinding, death and release rules). +Both reuse the same pool characters, `BotCharacterFactory`, `BotSetupPipeline` (level, trainer spells, weapon skills, talents, gear, riding, then a first teleport to a leveling town), and the same bot bot logic (questing, travel, grinding, death and release rules). ## What the world spawner does @@ -47,16 +47,16 @@ Raise `SpawnPerTick` for a faster ramp; the setup pipeline drains at most 10 bot ## Cost estimate (NOT measured: from code comments and structure only) -- Per bot the world pays: a `Player` plus its headless `WorldSession`, `BotAI` state, one snapshot and one intent queue, and its share of Map update (visibility, AI, movement). RAM is probably a few MB per bot (guess: 2-4 MB), so 1000 bots roughly 2-4 GB on top of the server (31 GB machine). Loaded map and mmap tiles add to that and grow with how widely the bots spread, not with the bot count. -- CPU: bot AI runs on a worker pool with activity tiers (Combat 100 ms, Active 150 ms, Cruise 300 ms, Idle 500 ms, Hibernate 2 s). A solo questing bot is Cruise. The Map update for the bots stays on the world thread(s), which is the likely limit, together with the SMSG traffic when bots are near the player. -- A previous retail deployment of this module ran 2000 bots on a 16-core desktop CPU (a 5950X; Karrz's PC has 16 threads, an RTX 5090 is irrelevant here), with a baseline of about a third of the CPU. Classic maps are lighter than retail, but the Forever core, the Classic rotations and the raid brain add cost of their own, so treat 200 and 500 as probable, 1000 as the stretch target, and let stage 5 settle it. +- Per bot the world pays: a `Player` plus its headless `WorldSession`, `BotAI` state, one snapshot and one intent queue, and its share of Map update (visibility, bot logic, movement). RAM is probably a few MB per bot (guess: 2-4 MB), so 1000 bots roughly 2-4 GB on top of the server (31 GB machine). Loaded map and mmap tiles add to that and grow with how widely the bots spread, not with the bot count. +- CPU: bot bot logic runs on a worker pool with activity tiers (Combat 100 ms, Active 150 ms, Cruise 300 ms, Idle 500 ms, Hibernate 2 s). A solo questing bot is Cruise. The Map update for the bots stays on the world thread(s), which is the likely limit, together with the SMSG traffic when bots are near the player. +- A previous retail deployment of this module ran 2000 bots on a 16-core desktop CPU (a 5950X; the owner's PC has 16 threads, an RTX 5090 is irrelevant here), with a baseline of about a third of the CPU. Classic maps are lighter than retail, but the Forever core, the Classic rotations and the raid brain add cost of their own, so treat 200 and 500 as probable, 1000 as the stretch target, and let stage 5 settle it. - Known multiplier: bots near the player cost network traffic (see the SMSG_PARTY_UPDATE flood earlier today). Only grouped bots send party updates, so ambient bots should not, but nearby ambient bots produce visibility/update packets for the client: watch FPS in stage 3 and 4. ## Known gaps and risks - Quest and travel on the vanilla quest data are unverified (the conf says so): bots may stand around or walk far away, and then get logged out as orphans while the player stays put. If bots leave the radius too quickly, raise `ActivityRadius`/`DespawnRadius`, or add a leash rule. - A new bot is first teleported to a leveling town by the setup pipeline, then to the ring: two teleports on a first spawn (cheap for pool bots). -- World PvP mix: the faction share is per zone (`Fleet/WorldFactionMix.h`, keys `ZoneMix`, `CapitalFriendlyPct` 90, `HomeFriendlyPct` 90, `BorderFriendlyPct` 75, `ContestedFriendlyPct` 60; unlisted zones use `FriendlyPct`). Contested zones (Plaguelands, Stranglethorn, Hillsbrad, Arathi, ...) hold ~40% opposing faction drawn from the same level window as friendly bots. +- World PvP mix: the faction share is per zone (`Fleet/WorldFactionMix.h`, keys `ZoneMix`, `CapitalFriendlyPct`, `HomeFriendlyPct`, `BorderFriendlyPct`, `ContestedFriendlyPct`, all 100 by default (no enemy-faction bots); unlisted zones use `FriendlyPct`). Contested zones (Plaguelands, Stranglethorn, Hillsbrad, Arathi, ...) hold ~40% opposing faction drawn from the same level window as friendly bots. - Roster balance: with `SeedRoster = 1` the seeder creates whichever (faction, level bracket 10s/50-60) is furthest below `PoolHordePct` (default 50) Horde (`Fleet/PoolBalance.h`); the census is logged as `[world] roster census` every two minutes. `PoolMax` must leave room for the characters a lopsided pool lacks. - Hostile-faction bots (`FriendlyPct` < 100) are placed near the player; on a PvP realm they will fight. Set `FriendlyPct = 100` to avoid that. - Bots below level 10 are not spawned (no navmesh in the starter zones), so a player in a starter zone sees none. @@ -97,3 +97,7 @@ Not run on the PC yet. Rules in `Fleet/SkyborneIsle.h` (tested: `ctest -L skybor - Zephras Isle is an island with no exit in the server data (its portals lead to Valanaar and Rohashi Spires on the same map; the Skyborne portals of Stormwind and Dalaran connect those two cities). So the isle is handled apart: around a real player on the isle the spawner keeps Skyborne bots of level 1-9 (MinLevel does not apply there), the pipeline leaves a level 1-9 Skyborne at its start, they quest with the same-map starter logic of low-level bots, and `WorldBotSpawner::DriveGraduation` moves a bot that reaches level 10 on the isle to a leveling town with `BotSetupPipeline::Graduate` (the placement a new level-10 bot gets). The graduation is the only carried move; it is logged as `[world] skyborne graduate`. - Seeding (`SeedRoster = 1`) makes `SkyborneSeedPct` (5) of the residents sleeping Skyborne level 1-9 at the isle start, so they wake when a player comes near. - Unverified: whether the quest givers of the isle deal with both Skyborne races in `giver_team_mask`, whether map 2991 is a normal open-world map for the anchor test (not an instance map), mmap coverage of the whole isle (33 mmtiles for 72 map tiles), and customization options for races 95/96 in `BotCharacterFactory`. + +- Area cap: no more than `AreaCapOutdoors` (14) world bots within `AreaRadius` (45 y) of one another outdoors, `AreaCapTown` (40) in a capital. Placement refuses a full spot, and every 10 s a pass moves up to three extras of an over-full crowd next to the nearest player (`[world] crowd:` line). `Fleet/AreaCap.h`. + +- World life: `DayRhythm` scales the targets by the server's hour (60% at night, 125% in the evening, never over MaxBots); `NaturalMoves` makes bots arrive on foot out of sight and leave toward an inn before logging out; `TownLife` adds the inn rest, duels, campfires and dungeon LFG calls (`Bot/TownLife.h`, rules in `Bot/States/Rules/AmbientRules.cpp`). Each show takes only a few percent of the bots at a time, so none adds RAM; nothing here forms a bot-only dungeon group. diff --git a/src/modules/PlayerbotV2/World/WorldMetadata.cpp b/src/modules/PlayerbotV2/World/WorldMetadata.cpp index db81d28045..ff7623f86f 100644 --- a/src/modules/PlayerbotV2/World/WorldMetadata.cpp +++ b/src/modules/PlayerbotV2/World/WorldMetadata.cpp @@ -19,7 +19,7 @@ namespace std::string const& SharedDb() { static std::string const db = - sConfigMgr->GetStringDefault("Playerbot.SharedDatabase", "playerbot"); + sConfigMgr->GetStringDefault("Playerbot.SharedDatabase", "playerbot", true); return db; } } // anonymous diff --git a/src/modules/PlayerbotV2/conf/playerbot.conf.dist b/src/modules/PlayerbotV2/conf/playerbot.conf.dist index 729c3c78fd..f6044bbfae 100644 --- a/src/modules/PlayerbotV2/conf/playerbot.conf.dist +++ b/src/modules/PlayerbotV2/conf/playerbot.conf.dist @@ -31,7 +31,7 @@ Playerbot.SharedDatabase = "playerbot" # Bot diagnostics ([wedge], [move_lock], [path_fail] ...) go to Playerbot.log; add Console to watch them live. # CrashRing is the worldserver.conf appender that keeps the last lines for the crash report. -Appender.Playerbot=2,3,0,Playerbot.log,w,67108864,5 +Appender.Playerbot=2,3,1,Playerbot.log,w,67108864,5 Logger.playerbot.v2=3,Playerbot CrashRing Logger.playerbot.api=3,Playerbot CrashRing @@ -53,7 +53,7 @@ RoadGraph.Enable = 1 # Core / threading #----------------------------------------------------------------------------- -# Number of AI worker threads. 0 = auto (min(8, hardware_concurrency)). +# Number of bot worker threads. 0 = auto (min(8, hardware_concurrency)). # HR-no Playerbot.AiWorkerThreads = 0 @@ -133,6 +133,10 @@ Playerbot.Population.MaxHeavyFactor = 0.40 # 0 = off. Playerbot.World.Enable = 0 # Ambient bots online at once, over all players. +# Starting points by machine until the measured numbers replace them (read ram_mb_per_awake_bot_incl_base and cpu_pct_per_awake_bot on the +# [world] log line with 50, 150 and 300 bots): 8 GB: MaxBots 60. 16 GB: MaxBots 100 (this default). RssBudgetMb below stops the bubble +# whatever MaxBots says. Sleeping residents (PoolMax) cost a database row, not memory. NaturalMoves, TownLife and DayRhythm each have an +# off key. Playerbot.World.MaxBots = 100 # Target number of bots within ActivityRadius of each real player. Playerbot.World.BotsPerPlayer = 25 @@ -150,7 +154,7 @@ Playerbot.World.CitySpawnPerTick = 0 # trip does not log out and rebuild the whole crowd. 0 = off. Playerbot.World.ZoneGraceSec = 300 # Persistent residents. 0 = off (a bot is created and placed when a player arrives). > 0: the pool is a fixed roster; a bot -# that no player is near is logged out and sleeps at its saved spot (offline, no memory, no AI). When a player comes +# that no player is near is logged out and sleeps at its saved spot (offline, no memory, no bot logic). When a player comes # within this many yards, sleeping bots standing there (60 y or farther from him) log in where they are. Where nobody # sleeps yet, new residents are placed as before and stay when logged out. Keep it near or below DespawnRadius. # The [world] log line reports roster/sleeping/awake, process CPU and RAM per awake bot. @@ -170,7 +174,7 @@ Playerbot.World.DespawnPerTick = 5 # A freshly placed bot is not logged out for this long (s). Playerbot.World.PlacedGraceSec = 30 # Share (%) of bots placed in a town (capital) that stay there for 20-40 min, using trainers, AH, bank and vendors. -Playerbot.World.TownPct = 70 +Playerbot.World.TownPct = 100 # World-wide filler: 1 = the MaxBots budget not needed for the bubble around players is filled with bots all over # the world (pool bots log in where they last were; new ones are set up and sent to a leveling town of their # level). Far bots run on the cheap activity tiers. They are only logged out (farthest first) to make room for the @@ -182,21 +186,22 @@ Playerbot.World.GlobalPerTick = 3 # instead of loading a corner of the world each. New filler bots are sent to leveling towns by the setup pipeline anyway. Playerbot.World.FillerHubOnly = 1 # Process memory budget (MB). Over it the world-wide filler stops adding bots (logged once); 15% over it the bubble -# around players waits too. Bots already online stay. 0 = no limit. Stage B/C: 12000 on a 31 GB PC that also runs a client. -Playerbot.World.RssBudgetMb = 0 +# around players waits too. Bots already online stay. -1 = 45% of the machine's RAM (the default), 0 = no limit. +# Stage B/C: 12000 on a 31 GB PC that also runs a client. +Playerbot.World.RssBudgetMb = -1 # Bot level limits. Playerbot.World.MinLevel = 10 Playerbot.World.MaxLevel = 60 # Percentage of bots of the player's own faction (the rest is the opposing faction). -Playerbot.World.FriendlyPct = 80 +Playerbot.World.FriendlyPct = 100 # World PvP mix by zone (Fleet/WorldFactionMix.h): contested zones (Plaguelands, Stranglethorn, Hillsbrad, Arathi, ...) hold a real share # of the opposing faction at the player's level; capitals and home zones stay mostly the player's own. Unlisted zones use FriendlyPct. # ZoneMix = 0 gives FriendlyPct everywhere. Playerbot.World.ZoneMix = 1 -Playerbot.World.CapitalFriendlyPct = 90 -Playerbot.World.HomeFriendlyPct = 90 -Playerbot.World.BorderFriendlyPct = 75 -Playerbot.World.ContestedFriendlyPct = 60 +Playerbot.World.CapitalFriendlyPct = 100 +Playerbot.World.HomeFriendlyPct = 100 +Playerbot.World.BorderFriendlyPct = 100 +Playerbot.World.ContestedFriendlyPct = 100 # Ambient characters allowed to exist (online or offline). Offline ones are reused before new ones are created. # Default: the larger of 4 x MaxBots and 200. # Playerbot.World.PoolMax = 200 @@ -212,6 +217,38 @@ Playerbot.World.SeedInFlight = 8 # the opposing faction for world PvP and battleground queues. 5..95. PoolMax must leave room for the Horde characters a lopsided # pool still lacks. Playerbot.World.PoolHordePct = 50 + +# Bots arrive on foot from out of the player's sight instead of appearing in view, and a bot the spawner retires in view walks to the +# nearest inn (or away) and logs out once unseen (at most a minute). 0 = appear and vanish where they stand. +Playerbot.World.NaturalMoves = 1 + +# Town life: a share of the bots rest at the inn (most at night), pairs duel in towns, a few light a campfire outdoors at night, and some +# call LFG for a dungeon of their level. No bot is created for it and a bot joins a dungeon only when a real player invites it. 0 = off. +Playerbot.World.TownLife = 1 + +# How many other players may stand within 40 yards of a world bot working a quest objective before it gives that objective up for 15 +# minutes and takes another quest (real players and their companions keep their place first, then world bots by id). Keeps a popular mob +# camp from drawing a dozen bots. 0 = off. +Playerbot.World.QuestSiteCap = 5 + +# For unattended test runs only, leave unset in a release: characters, comma-separated, that count as anchors although a bot plays them, +# so the world fills up around them with nobody logged in. Log one in with `.playerbot login ` and move it with `.tele name +# `. Use a saved companion bot (not a pool resident), which the spawner never moves or logs out. +# Playerbot.World.SoakAnchors = "" + +# Scale ZoneBots / CityBots / BotsPerPlayer by the server machine's hour: about 60% at night (0-6), 100% by day, 125% in the evening +# (18-22), never above MaxBots. 0 = a constant target. Quieter nights cost less RAM and CPU. +Playerbot.World.DayRhythm = 1 + +# Seconds the bots around the place a player jumped away from (teleport, hearthstone, flight end, still in the open world) are kept. An +# instance trip keeps them ZoneGraceSec. After a jump the swap runs at triple rate for a minute. +Playerbot.World.JumpGraceSec = 20 + +# Most world bots within AreaRadius yards of one another: placement refuses a spot that is full and a pass moves the extras of a crowd +# next to the nearest player (0 = no cap). Outdoors and in a capital. +Playerbot.World.AreaCapOutdoors = 14 +Playerbot.World.AreaCapTown = 40 +Playerbot.World.AreaRadius = 45 # Classic 1.60 (Skyborne): share of the seeded residents (SeedRoster = 1) that are level 1-9 Skyborne who sleep on Zephras Isle, the # Skyborne start, so a player who arrives there finds quests being done. Around a player on Zephras the spawner always keeps # Skyborne bots of level 1-9 (MinLevel does not apply there); a Skyborne bot that reaches level 10 on the island is moved to a @@ -238,7 +275,7 @@ Playerbot.Interact.CommandPrefix = ! # BG / Arena auto-seed and coordination #----------------------------------------------------------------------------- -# Battleground policy (Karrz, 2026-10-07): bots never queue or fight bot-vs-bot on their own. Bots join a +# Battleground policy (playtest, 2026-10-07): bots never queue or fight bot-vs-bot on their own. Bots join a # battleground only when a real player queues for it: the queue fill supplies both sides so the match starts, # tops it up while the player is in it, and the bots go back to the pool when it ends. The two switches below # (AutoSeed.Matches, AutoJoin) are therefore off; they remain for bot-only test matches. @@ -266,9 +303,10 @@ Playerbot.Bg.AutoSeed.ForceType = 0 # Playerbot.Bg.Av.MinPlayersPerTeam # Alterac Valley starts once this many players per side are queued (the client table's minimum is higher and the # queue never popped); bots keep topping the match up to 40 a side while it runs. 0 = the table's value. -# Default: 20 +# This also applies to real players, so set it only on a server where bots fill the match. +# Default: 0 # -Playerbot.Bg.Av.MinPlayersPerTeam = 20 +# Playerbot.Bg.Av.MinPlayersPerTeam = 20 Playerbot.Bg.AutoJoin = 0 Playerbot.Bg.AutoJoin.Chance = 3 @@ -331,7 +369,7 @@ Playerbot.TankThreatMultiplier = 3.0 # value is clamped to [MinPct, MaxPct]. Changes are logged as [cast_speed]. # Enable 0 (default) = all bots cast at normal speed (any multiplier already set is reset to 1.0) Playerbot.Cast.Enable = 0 -Playerbot.Cast.RaidSpeedPct = 80 +Playerbot.Cast.RaidSpeedPct = 75 Playerbot.Cast.DungeonSpeedPct = 90 Playerbot.Cast.WorldSpeedPct = 100 Playerbot.Cast.BgSpeedPct = 115 @@ -344,10 +382,10 @@ Playerbot.Cast.MaxPct = 140 # Decision pacing (Karrz's VMaNGOS model: GlobalCooldown 600 + PvpReactionDelay 1500, no # cast-time or haste change). # DecisionDelayMs Ceiling on how long a bot waits to decide again after a cast -# (100..5000). The shipped AI tick periods are already faster +# (100..5000). The shipped bot tick periods are already faster # (Combat 100 ms, casting bots Active 150 ms; the server GCD is the # real limiter), so nothing is slowed and this key has no effect today. -# PvpReactionDelayMs Floor on a bot's AI tick / snapshot period while it is in PvP: a +# PvpReactionDelayMs Floor on a bot's bot tick / snapshot period while it is in PvP: a # battleground or arena, an active duel, or in combat with players. # 0..3000, 0 = off. Never applied to raid/dungeon/world PvE. Dead or # ghost bots and bots under 35% HP bypass it (healing, defensives, ress). @@ -435,10 +473,10 @@ Playerbot.Behavior.AcceptOwnerTrade = 1 # Playerbot.Gear.MaxTier the best raid tier RaidGear may pick, as an effective item level ceiling (approximate # Classic boundaries): 0 = pre-raid / dungeon gear only (item level 63: Dire Maul, BRS, # Scholomance, Stratholme, UBRS), 1 = Molten Core / Onyxia (76), 2 = Blackwing Lair (83), -# 2.5 = Ahn'Qiraj 40 (88), 3 = Naxxramas (92). Default 1. Approximate, not read from item data. +# 2.5 = Ahn'Qiraj 40 (88), 3 = Naxxramas (92). Default 2. Approximate, not read from item data. # Required level 50+ and rare / epic quality still apply; never PvP items. # Playerbot.Gear.RaidIlvlCap explicit item level ceiling; when set above 0 it overrides MaxTier. Default 0 (use MaxTier). -Playerbot.Gear.MaxTier = 1 +Playerbot.Gear.MaxTier = 2 Playerbot.Gear.RaidIlvlCap = 0 # Playerbot.World.Gear.MaxTier world / ambient / BG-fill bots (the ones nobody owns): the same tier scale as Gear.MaxTier, # default 1 (item level 76). Owned and raid bots keep Playerbot.Gear.MaxTier. A world bot wearing @@ -505,7 +543,7 @@ Playerbot.Behavior.DungeonTactics = 1 Playerbot.Behavior.BotWhisperable = 1 Playerbot.Behavior.WorldBotSayReply = 1 # InstanceGroupCap OFF by default (an owner may have as many companions out as they like, up to the 40-man raid -# group limit; Karrz 2026-10-08). Set 1 to cap: inside an instance `.bot add`, `.bot call` and the addon buttons stop once the owner has +# group limit; playtest 2026-10-08). Set 1 to cap: inside an instance `.bot add`, `.bot call` and the addon buttons stop once the owner has # as many companions out as the map holds, or the group (human included) is full (5 dungeon, # 10/20/40 raid, from the map data; fallback 5 / 40). The owner is warned once when a larger # group enters a smaller instance. Outside an instance the OpenWorldGroupCap below applies. @@ -566,7 +604,7 @@ Playerbot.Behavior.ReadyCheckInfo = 1 # Snap resets a spent Ice Block when low. Off: neither. Playerbot.Behavior.PurgeDuty = 1 Playerbot.Behavior.RangedSlow = 1 -# Ike3Commands the owner's ike3-style chat commands: "@skull|@star|... " (only the bots holding that icon or +# Ike3Commands Karrz's ike3-style chat commands: "@skull|@star|... " (only the bots holding that icon or # targeting the marked mob), "@tank|@healer|@dps|@ranged|@melee|@ ", "pull rti", # "max dps" (cooldowns on every fight, no mana saving), "save mana" (healers keep to efficient heals), # "normal" (clears both), "rti raid" (roster / mark report). Off: none of these are parsed. @@ -580,6 +618,16 @@ Playerbot.Behavior.OwnerCommands = 1 # fidgets like a person: a jump, a short emote, a dance or a sit, every 20-90 s (random per bot). # Off: bots stand perfectly still. Playerbot.Behavior.Fidget = 1 + +# +# Playerbot.AddonHint.Enable (default 0, off) A player who logs in and whose client does not say hello (the ForeverBots add-on sends one +# a few seconds after login) gets one chat line with the add-on's download link. Once per login, never to bots. +# Playerbot.AddonHint.DelaySec seconds to wait for the hello before the line is sent (5-600, default 30). +# Playerbot.AddonHint.Url the link in that line. +# +Playerbot.AddonHint.Enable = 0 +Playerbot.AddonHint.DelaySec = 30 +Playerbot.AddonHint.Url = "https://github.com/Karrz1/Karrz-playerbots-wow-forever/raw/main/addon/ForeverBots-addon.zip" # SoloFlee a solo open-world bot (no group, not in an instance or battleground) losing a fight (HP under 30%, # 35% for casters / hunters / rogues, 25% for melee; the mob not nearly dead) uses its escape tools # (Disengage, Frost Nova + Blink, Fade / Psychic Scream, Death Coil, Vanish / Sprint, Intimidating @@ -628,7 +676,7 @@ Playerbot.Behavior.QuestLoot = 1 # Master switch for bot housing participation. # HR-yes -Playerbot.Housing.Enabled = 1 +Playerbot.Housing.Enabled = 0 # Per-neighborhood bot residency target percent of capacity. # HR-yes @@ -788,7 +836,7 @@ PlayerbotV2.Economy.MaxReagentVendorMultiple = 15 # # PlayerbotV2.SessionRhythm.Enabled # Master switch. 1 = on (default), 0 = bots never auto-logout on session length. -PlayerbotV2.SessionRhythm.Enabled = 1 +PlayerbotV2.SessionRhythm.Enabled = 0 # PlayerbotV2.SessionRhythm.Multiplier # Global scale on every archetype's target_session_minutes. 1.0 = use the @@ -827,7 +875,7 @@ PlayerbotV2.SessionRhythm.MaxLogoutsPerCycle = 25 #----------------------------------------------------------------------------- # `.playerbot summon ` lets a normal player turn one of their OWN -# characters (same account) into an AI-controlled bot that follows / fights +# characters (same account) into an bot-controlled bot that follows / fights # / quests alongside their main. Account-wide synergy: alts gain XP from # group-completed content while the player drives their main. # @@ -910,7 +958,7 @@ PlayerbotV2.GroupWedge.FarYards = 45.0 # WedgedBots max acceptable concurrently-wedged bot count. # TickP99Us max acceptable world-tick p99 latency (microseconds). # IntentDropPerMin max acceptable IntentQueue drops per 60s window -# (sustained drops = an AI worker outrunning the drain). +# (sustained drops = an bot worker outrunning the drain). # PathFailPerMin max acceptable path-validation failures per minute. # ThrottleMs per-metric re-emit suppression window (a sustained # breach logs once per window, not once per 60s sample). @@ -927,7 +975,7 @@ PlayerbotV2.Alert.ThrottleMs = 300000 #----------------------------------------------------------------------------- # Master switch for the bot guild system (founding, recruiting, membership). -PlayerbotV2.Guilds.Enabled = 1 +PlayerbotV2.Guilds.Enabled = 0 # Enable scheduled bot guild events (group activities, social cadence). PlayerbotV2.Guilds.EventsEnabled = 1 @@ -987,13 +1035,13 @@ PlayerbotV2.Move.RouteAwareCombatAdvance = 1 # combat frame; WC corridor freeze 2026-07-03 (z-disconnected ledge pack). PlayerbotV2.Combat.SkipUnfightable = 1 -# Group threat discipline (port of Karrz's ike3-based bots GroupPveRestraint / +# Group threat discipline (port of Karrz's wow-1.12 GroupPveRestraint / # MCRaidHoldDamage). Applies only to non-tank bots in a group that has a tank # (main-tank flag, LFG tank role or tank spec) - never to solo bots, BGs or # a mob already hitting a non-tank member (self-defence). Holding = the bot # stops attacking that mob (pet called back) but keeps healing / buffing. # HoldEnabled master switch -# HoldInOpenWorld 0 = dungeons/raids only (Karrz: open-world groups just +# HoldInOpenWorld 0 = dungeons/raids only (the owner: open-world groups just # fight); 1 = also hold in the open world # MaxRatio stay below this fraction of the tank's threat on the # target; over it, damage stops (and Fade / Feign Death / @@ -1013,7 +1061,7 @@ Playerbot.Raid.DpsWaitForAttack = 1 # hunters: Mongoose, Giants and a food; casters: Supreme Power, Greater Arcane; healers: Distilled Wisdom, Mageblood, # Nightfin Soup). Bots always use ones they carry; with this on, the bags are stocked for them first (free, like # the potion and reagent stock). Default 0; the server's make-configs set 1. -Playerbot.Raid.ProvideConsumables = 0 +Playerbot.Raid.ProvideConsumables = 1 # Playerbot.Consumables.PvE / Playerbot.Consumables.PvP server choice, separately for PvE (open world, dungeons, # raids) and PvP (battlegrounds and arenas): whether bots use flasks, elixirs, buff food, combat healing and mana # potions, healthstones and resistance potions on that kind of map. Off also stops ProvideConsumables stocking. @@ -1022,9 +1070,9 @@ Playerbot.Raid.ProvideConsumables = 0 Playerbot.Consumables.PvE = 1 Playerbot.Consumables.PvP = 0 # Playerbot.Raid.DpsWaitTimeoutMs with DpsWaitForAttack: after the tanks have fought this long without the owner's -# Attack, the DPS go anyway (a forgotten Attack no longer wipes the raid). 0 = never (the owner's Attack is always -# needed). Default 10000 (Karrz chose a 10 s fallback, 2026-10-08). -Playerbot.Raid.DpsWaitTimeoutMs = 10000 +# Attack, the DPS go anyway (a forgotten Attack no longer wipes the raid). Same six seconds as a party's Pull; the +# value is limited to 1000-6000 (there is no "never"). Default 6000. +Playerbot.Raid.DpsWaitTimeoutMs = 6000 PlayerbotV2.Threat.HoldInOpenWorld = 0 PlayerbotV2.Threat.MaxRatio = 0.9 PlayerbotV2.Threat.OpeningLeadBoss = 900