diff --git a/README.md b/README.md index 67335aef..d5430e47 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,7 @@ Full per-function reference: **[docs/API.md](docs/API.md)**. | Item | `C_Item.DoesItemExist`, `C_Item.DoesItemExistByID`, `C_Item.EquipItemByName`, `C_Item.GetCurrentItemLevel`, `C_Item.GetDetailedItemLevelInfo`, `C_Item.GetItemCount`, `C_Item.GetItemFamily`, `C_Item.GetItemGUID`, `C_Item.GetItemIcon`, `C_Item.GetItemIconByID`, `C_Item.GetItemID`, `C_Item.GetItemInfoInstant`, `C_Item.GetItemInventoryType`, `C_Item.GetItemInventoryTypeByID`, `C_Item.GetItemLink`, `C_Item.GetItemLocation`, `C_Item.GetItemMaxStackSize`, `C_Item.GetItemMaxStackSizeByID`, `C_Item.GetItemName`, `C_Item.GetItemNameByID`, `C_Item.GetItemQuality`, `C_Item.GetItemQualityByID`, `C_Item.GetItemSpell`, `C_Item.GetWeaponEnchantInfo`, `C_Item.IsBound`, `C_Item.IsEquippableItem`, `C_Item.IsEquippedItem`, `C_Item.IsItemDataCached`, `C_Item.IsItemDataCachedByID`, `C_Item.IsLocked`, `C_Item.RequestLoadItemData`, `C_Item.RequestLoadItemDataByID`, `GetAuctionItemID`, `GetAuctionSellItemID`, `GetCraftReagentItemID`, `GetInboxItemID`, `GetInventoryItemDurability`, `GetInventoryItemID`, `GetInventoryItemRepairCost`, `GetItemIcon`, `GetLootRollItemID`, `GetLootSlotItemID`, `GetMerchantItemID`, `GetQuestItemID`, `GetQuestLogItemID`, `GetTradePlayerItemID`, `GetTradeSkillItemID`, `GetTradeSkillReagentItemID`, `GetTradeTargetItemID`, `OffhandHasWeapon` | | NameCache | `C_PlayerCache.IsEnabled`, `C_PlayerCache.IsScanEnabled`, `C_PlayerCache.RememberPlayer`, `C_PlayerCache.SetEnabled`, `C_PlayerCache.SetScanEnabled`, `C_PlayerInfo.GUIDIsCreature`, `C_PlayerInfo.GUIDIsGameObject`, `C_PlayerInfo.GUIDIsPet`, `C_PlayerInfo.GUIDIsPlayer`, `GetPlayerInfoByGUID` | | Quest | `C_QuestLog.GetTitleForQuestID`, `C_QuestLog.RequestLoadQuestByID`, `GetQuestIDFromLogIndex` | -| Spell | `C_Spell.GetSpellDescription`, `C_Spell.GetSpellInfo`, `C_Spell.GetSpellLink`, `C_Spell.GetSpellName`, `C_Spell.GetSpellTexture`, `C_Spell.IsSpellHarmful`, `C_Spell.IsSpellHelpful`, `C_Spell.IsSpellPassive`, `C_Spell.IsSpellUsable`, `CastAutoRepeatSpell`, `FindSpellBookSlotByID`, `GetCraftSpellID`, `GetSpellInfo`, `GetSpellLink`, `GetSpellSchool`, `IsHarmfulSpell`, `IsHelpfulSpell`, `IsPassiveSpell`, `IsPlayerSpell`, `IsSpellKnown`, `IsUsableSpell` | +| Spell | `C_Spell.GetSpellDescription`, `C_Spell.GetSpellInfo`, `C_Spell.GetSpellLink`, `C_Spell.GetSpellName`, `C_Spell.GetSpellTexture`, `C_Spell.IsSpellHarmful`, `C_Spell.IsSpellHelpful`, `C_Spell.IsSpellPassive`, `C_Spell.IsSpellUsable`, `C_SpellBook.GetCurrentLevelSpells`, `C_SpellBook.GetSpellLevelLearned`, `CastAutoRepeatSpell`, `FindSpellBookSlotByID`, `GetCraftSpellID`, `GetSpellInfo`, `GetSpellLink`, `GetSpellSchool`, `IsHarmfulSpell`, `IsHelpfulSpell`, `IsPassiveSpell`, `IsPlayerSpell`, `IsSpellKnown`, `IsUsableSpell` | | State | `IsAssistingRitual`, `IsFalling`, `IsMounted`, `IsStealthed`, `IsSwimming` | | Table | `table.wipe` | | Talent | `GetTalentIDByIndex`, `GetTalentSpellID` | diff --git a/docs/API.md b/docs/API.md index aa5fcd14..2be76976 100644 --- a/docs/API.md +++ b/docs/API.md @@ -23,6 +23,8 @@ build instructions. - [`C_Spell.IsSpellUsable(spellID)`](#c_spellisspellusablespellid) - [`IsHarmfulSpell(spell)` / `IsHelpfulSpell(spell)`](#isharmfulspellspell--ishelpfulspellspell) - [`C_Spell.IsSpellHarmful(spellID)` / `C_Spell.IsSpellHelpful(spellID)`](#c_spellisspellharmfulspellid--c_spellisspellhelpfulspellid) + - [`C_SpellBook.GetSpellLevelLearned(spellID)`](#c_spellbookgetspelllevellearnedspellid) + - [`C_SpellBook.GetCurrentLevelSpells([level])`](#c_spellbookgetcurrentlevelspellslevel) - [`GetSpellSchool(spellID)`](#getspellschoolspellid) - [`CastAutoRepeatSpell(name | spellID)`](#castautorepeatspellname--spellid) - [Macros](#macros) @@ -693,6 +695,55 @@ C_Spell.IsSpellHelpful(2061) -- true (Flash Heal) Equivalent to `C_Spell.IsSpellHarmful` / `C_Spell.IsSpellHelpful` introduced in 11.x. +### `C_SpellBook.GetSpellLevelLearned(spellID)` + +Returns the level at which a spell becomes available — the +`BaseLevel` field in `Spell.dbc` (record `+0x70`). Direct read off +the cached record; no class/race filtering. + +```lua +C_SpellBook.GetSpellLevelLearned(133) -- Fireball rank 1 → 4 +C_SpellBook.GetSpellLevelLearned(25306) -- Fireball rank 12 → 60 +C_SpellBook.GetSpellLevelLearned(2061) -- Flash Heal rank 1 → 20 +``` + +Returns `0` for invalid spellIDs, spells with no level requirement +(most non-class utility spells), or records the engine hasn't +cached. Matches modern semantics — unknown / utility spells +return 0 rather than nil. + +### `C_SpellBook.GetCurrentLevelSpells([level])` + +Returns a 1-based table of spellIDs the player's class/race can +learn at the given level. Without arguments, defaults to the +player's current level. + +```lua +C_SpellBook.GetCurrentLevelSpells() -- spells trainable at your level +C_SpellBook.GetCurrentLevelSpells(20) -- preview what's available at 20 +C_SpellBook.GetCurrentLevelSpells(60) -- preview at 60 +``` + +Walks `SkillLineAbility.dbc` filtering by the player's class bit +(`1 << (classID - 1)`) and race bit, respecting both the include +masks (entries with mask = 0 are "all classes"/"all races", which +also pass) and the exclude masks. For each surviving entry, looks +up the spell's `BaseLevel` and includes it if it matches the +queried level. + +> **Vanilla is trainer-driven.** Modern `GetCurrentLevelSpells` +> (added in 5.x when trainers were removed) returns *auto-learned* +> spells. Vanilla 1.12 requires visiting a trainer to actually +> learn most class spells. We return the closest available analog: +> **what's *trainable* at this level**. Useful for "what's new +> this level" UI panels and level-preview tooling ported from MoP+. + +Class/race come from the local player — there's no +`(class, race, level)` form because vanilla doesn't expose a +clean class-string→classID lookup. Returns an empty table at +character select / pre-login (no CGPlayer yet) and for levels +where no class/race spells match. + ### `GetSpellSchool(spellID)` Returns `(schoolID, schoolName)` for any spell — known to the player diff --git a/src/Offsets.h b/src/Offsets.h index 512e2fae..5e3ccef7 100644 --- a/src/Offsets.h +++ b/src/Offsets.h @@ -991,6 +991,42 @@ enum Offsets { OFF_UNIT_DESCRIPTOR_CLASS_BYTE = 0x79, OFF_UNIT_DESCRIPTOR_SEX_BYTE = 0x7A, + // SkillLineAbility.dbc — maps each (class, race) pair to its + // learnable spell list with skill-rank gating. Indexed by record + // ID; reads via the standard `records[id]` pattern. Used by + // `GetCurrentLevelSpells` to filter the global spell set down to + // entries our class/race can learn. + // + // Class instance VA `0x00C0D94C` per docs/DBCs.md. Standard 5-DWORD + // class shape so the records-array pointer slot sits at +0x08 and + // the count slot at +0x0C. + VAR_SKILL_LINE_ABILITY_RECORDS = 0x00C0D954, + VAR_SKILL_LINE_ABILITY_COUNT = 0x00C0D958, + + // Record-internal offsets, vanilla 1.12 layout (CMaNGOS-canonical): + // +0x00 id + // +0x04 skillId (→ SkillLine.dbc; e.g. 44 = "Swords") + // +0x08 spellId (→ Spell.dbc — the spell taught by this entry) + // +0x0C raceMask (bit `1 << (race - 1)`; 0 = all races) + // +0x10 classMask (bit `1 << (class - 1)`; 0 = all classes) + // +0x14 excludeRace (bitmask of races this entry does NOT apply to) + // +0x18 excludeClass (bitmask of classes this entry does NOT apply to) + // +0x1C minSkillRank + // ... (more fields) + OFF_SLA_SPELL_ID = 0x08, + OFF_SLA_RACE_MASK = 0x0C, + OFF_SLA_CLASS_MASK = 0x10, + OFF_SLA_EXCLUDE_RACE = 0x14, + OFF_SLA_EXCLUDE_CLASS = 0x18, + + // Spell.dbc `BaseLevel` — the level a spell becomes available + // (trainer offers it, quest reward grants it, etc.). Distinct + // from `SpellLevel` at +0x74 which is the effective level used + // for damage scaling and resistance math. Per CMaNGOS-canonical + // 1.12 Spell.dbc layout; cross-checked against known fields at + // ±a few offsets (PowerType at +0x7C is verified). + OFF_SPELL_RECORD_BASE_LEVEL = 0x70, + // `UNIT_BYTES_1` (CMaNGOS field 132 in the 1.12.1 layout). 32-bit // composite field; the low byte is the standstate (standing / // sitting / sleeping / kneeling / etc.), the upper bytes hold diff --git a/src/debug/Probe.cpp b/src/debug/Probe.cpp index c8d99197..4633fda0 100644 --- a/src/debug/Probe.cpp +++ b/src/debug/Probe.cpp @@ -325,6 +325,70 @@ int __fastcall Script_DiffAllLog(void *L) { return 0; } +// Walks SkillLineAbility.dbc and returns a string with every row +// matching `spellID`, formatted as +// `row=N id=I skill=S race=0xR class=0xC excR=0xR excC=0xC minRank=M sup=S acq=A` +// Multiple rows are joined with newlines. Returns "(none)" if no +// match. Use to diagnose why a spell appears (or doesn't) in +// GetCurrentLevelSpells — Turtle WoW custom spells with weird +// classMask values surface here clearly. +int __fastcall Script_SLADumpForSpell(void *L) { + if (!Game::Lua::IsNumber(L, 1)) { + Game::Lua::Error(L, "Usage: _classicapi_SLADumpForSpell(spellID)"); + return 0; + } + const int wantSpellID = static_cast(Game::Lua::ToNumber(L, 1)); + + const uint8_t *const *records = *reinterpret_cast( + static_cast(Offsets::VAR_SKILL_LINE_ABILITY_RECORDS)); + const int count = *reinterpret_cast( + static_cast(Offsets::VAR_SKILL_LINE_ABILITY_COUNT)); + + static char buf[4096]; + int pos = 0; + buf[0] = '\0'; + + if (records == nullptr || count <= 0) { + Game::Lua::PushString(L, "(no SLA records)"); + return 1; + } + + for (int i = 1; i <= count && pos < static_cast(sizeof(buf)) - 256; ++i) { + const uint8_t *rec = records[i]; + if (rec == nullptr) + continue; + const int spellID = *reinterpret_cast( + rec + Offsets::OFF_SLA_SPELL_ID); + if (spellID != wantSpellID) + continue; + const int id = *reinterpret_cast(rec + 0x00); + const int skill = *reinterpret_cast(rec + 0x04); + const uint32_t race = *reinterpret_cast( + rec + Offsets::OFF_SLA_RACE_MASK); + const uint32_t cls = *reinterpret_cast( + rec + Offsets::OFF_SLA_CLASS_MASK); + const uint32_t excR = *reinterpret_cast( + rec + Offsets::OFF_SLA_EXCLUDE_RACE); + const uint32_t excC = *reinterpret_cast( + rec + Offsets::OFF_SLA_EXCLUDE_CLASS); + const int minRank = *reinterpret_cast(rec + 0x1C); + const int sup = *reinterpret_cast(rec + 0x20); + const int acq = *reinterpret_cast(rec + 0x24); + const int n = std::snprintf(buf + pos, sizeof(buf) - pos, + "row=%d id=%d skill=%d race=0x%X class=0x%X excR=0x%X excC=0x%X minRank=%d sup=%d acq=%d\n", + i, id, skill, race, cls, excR, excC, minRank, sup, acq); + if (n < 0) + break; + pos += n; + } + + if (pos == 0) + Game::Lua::PushString(L, "(none)"); + else + Game::Lua::PushString(L, buf); + return 1; +} + void RegisterLuaFunctions() { Game::Lua::RegisterGlobalFunction("_classicapi_DescDump", &Script_DescDump); Game::Lua::RegisterGlobalFunction("_classicapi_PlayerDump", &Script_PlayerDump); @@ -333,6 +397,8 @@ void RegisterLuaFunctions() { Game::Lua::RegisterGlobalFunction("_classicapi_SnapAll", &Script_SnapAll); Game::Lua::RegisterGlobalFunction("_classicapi_DiffAll", &Script_DiffAll); Game::Lua::RegisterGlobalFunction("_classicapi_DiffAllLog", &Script_DiffAllLog); + Game::Lua::RegisterGlobalFunction("_classicapi_SLADumpForSpell", + &Script_SLADumpForSpell); } const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions}; diff --git a/src/spell/Level.cpp b/src/spell/Level.cpp new file mode 100644 index 00000000..f1ae9fe5 --- /dev/null +++ b/src/spell/Level.cpp @@ -0,0 +1,324 @@ +// This file is part of ClassicAPI. +// +// ClassicAPI is free software: you can redistribute it and/or modify it under the terms +// of the GNU Lesser General Public License as published by the Free Software Foundation, either +// version 3 of the License, or (at your option) any later version. +// +// ClassicAPI is distributed in the hope that it will be useful, but WITHOUT ANY +// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License along with +// ClassicAPI. If not, see . + +#include "Game.h" +#include "Offsets.h" +#include "spell/Lookup.h" + +#include +#include + +namespace Spell::Level { + +namespace { + +using ResolveUnitToken_t = void *(__fastcall *)(const char *token); + +// Reads the local player's descriptor — same pattern as +// Unit::Combat::Script_InCombatLockdown. Returns nullptr at login +// screen / character select / loading transition where the +// CGPlayer doesn't exist yet. +const uint8_t *PlayerDescriptor() { + auto fn = reinterpret_cast(Offsets::FUN_RESOLVE_UNIT_TOKEN); + auto *player = static_cast(fn("player")); + if (player == nullptr) + return nullptr; + return *reinterpret_cast( + player + Offsets::OFF_UNIT_DESCRIPTOR); +} + +// Builds (or returns the cached) set of every spellID that appears +// in `Talent.dbc` — across all 9 rank slots of every talent record. +// Used to skip talent-tree spells in `GetCurrentLevelSpells`; modern +// `GetCurrentLevelSpells` only reports auto-learned / trainable +// class spells, never talents (which are point-purchased separately). +// +// Cache survives across calls in a session (Talent.dbc is a static +// DBC). First call before the engine has loaded the DBC (e.g., +// pre-login) leaves the set empty; subsequent calls retry until +// non-empty. +std::unordered_set &TalentSpellSet() { + static std::unordered_set set; + if (!set.empty()) + return set; + const uint8_t *const *records = *reinterpret_cast( + static_cast(Offsets::VAR_TALENT_DBC_RECORDS)); + const int count = *reinterpret_cast( + static_cast(Offsets::VAR_TALENT_DBC_COUNT)); + if (records == nullptr || count <= 0) + return set; + // Each Talent.dbc record stores rank-N spellIDs at +0x10 + N*4 + // for N = 0..8 (9 ranks). Many slots are 0 for unused ranks. + for (int i = 1; i <= count; ++i) { + const uint8_t *rec = records[i]; + if (rec == nullptr) + continue; + auto *ranks = reinterpret_cast( + rec + Offsets::OFF_TALENT_SPELL_RANK); + for (int j = 0; j < 9; ++j) { + const uint32_t spellID = ranks[j]; + if (spellID != 0) + set.insert(static_cast(spellID)); + } + } + return set; +} + +// Looks up the `BaseLevel` field of a Spell.dbc record. Returns 0 +// for invalid spellIDs or records the engine doesn't have cached. +int SpellBaseLevel(int spellID) { + const uint8_t *record = Spell::Lookup::RecordForID(spellID); + if (record == nullptr) + return 0; + return *reinterpret_cast( + record + Offsets::OFF_SPELL_RECORD_BASE_LEVEL); +} + +// Spell.dbc attribute fields/bits used to filter learnable-spell +// results down to what's actually user-facing. +// +// Attributes (+0x18) +// bit 0x80 = HIDDEN_CLIENTSIDE — engine-internal helpers like +// "Defensive Stance Passive" (7376) that pair with +// a user-visible spell (Defensive Stance, 71) and +// never appear in the spellbook. Skip these. +// +// AttributesEx2 (+0x24) +// bit 0x02000000 = HIDE_FROM_AUTOLEARN — the same gate Cata's +// GetCurrentLevelSpells checks +// (FUN_00911c60's `(spellData[+0x24] & +// 0x02000000) == 0`). Catches proc-only and +// engine-internal spells with a BaseLevel. +constexpr int OFF_SPELL_RECORD_ATTRIBUTES = 0x18; +constexpr int OFF_SPELL_RECORD_ATTRIBUTES_EX2 = 0x24; +constexpr uint32_t SPELL_ATTR_HIDDEN_CLIENTSIDE = 0x80; +constexpr uint32_t SPELL_ATTR_EX2_HIDE_FROM_AUTOLEARN = 0x02000000; + +bool SpellHiddenFromAutoLearn(int spellID) { + const uint8_t *record = Spell::Lookup::RecordForID(spellID); + if (record == nullptr) + return false; + const uint32_t attributes = *reinterpret_cast( + record + OFF_SPELL_RECORD_ATTRIBUTES); + if ((attributes & SPELL_ATTR_HIDDEN_CLIENTSIDE) != 0) + return true; + const uint32_t attrEx2 = *reinterpret_cast( + record + OFF_SPELL_RECORD_ATTRIBUTES_EX2); + return (attrEx2 & SPELL_ATTR_EX2_HIDE_FROM_AUTOLEARN) != 0; +} + +// `C_SpellBook.GetSpellLevelLearned(spellID)` — returns the level +// at which a spell becomes available (the `BaseLevel` field in +// Spell.dbc). Direct read off the record — no class/race filtering, +// the level is the spell's own intrinsic requirement. +// +// Returns 0 for: invalid spellIDs, spells with no level requirement +// (most non-class utility spells), or records the engine doesn't +// have. Matches modern semantics where unknown/utility spells +// return 0. +int __fastcall Script_GetSpellLevelLearned(void *L) { + if (!Game::Lua::IsNumber(L, 1)) { + Game::Lua::Error(L, "Usage: C_SpellBook.GetSpellLevelLearned(spellID)"); + return 0; + } + const int spellID = static_cast(Game::Lua::ToNumber(L, 1)); + if (spellID <= 0) { + Game::Lua::PushNumber(L, 0); + return 1; + } + Game::Lua::PushNumber(L, static_cast(SpellBaseLevel(spellID))); + return 1; +} + +// `C_SpellBook.GetCurrentLevelSpells([level])` — returns a 1-based +// table of spellIDs the player's class/race can learn at `level`. +// If `level` is omitted or non-numeric, defaults to the player's +// current level. +// +// Algorithm: walk SkillLineAbility.dbc; for each entry with the +// player's class/race mask bits matching (and not in the exclude +// masks), look up the spell's BaseLevel. If it equals the queried +// level, the entry contributes to the result. +// +// Vanilla 1.12's class progression is trainer-driven — most class +// spells require visiting a trainer to actually learn them, even +// though SkillLineAbility says "this is a Mage spell available at +// level 12". Modern `GetCurrentLevelSpells` (added in 5.x when +// trainers were removed) reports auto-learned spells; we report +// the closest available analog — *what's trainable* at this level. +// Addon code that ported from MoP+ for "what's new this level" UI +// will find this useful. +// +// The optional `level` argument lets addons preview "what would I +// get at level N" (e.g. a talent planner showing future spells). +// Class/race still comes from the local player — there's no +// `(class, race, level)` form because vanilla doesn't expose a +// class-string→classID lookup we can rely on cleanly. +// +// Empty inputs (no player, no descriptor, missing DBC) return an +// empty table — never errors, never returns nil. Matches modern. +int __fastcall Script_GetCurrentLevelSpells(void *L) { + // Optional level arg (stack[1]) — read BEFORE blowing the stack. + const bool hasLevelArg = Game::Lua::IsNumber(L, 1); + const int argLevel = hasLevelArg + ? static_cast(Game::Lua::ToNumber(L, 1)) + : 0; + + Game::Lua::SetTop(L, 0); + Game::Lua::NewTable(L); + + auto *desc = PlayerDescriptor(); + if (desc == nullptr) + return 1; + + const uint8_t classByte = *(desc + Offsets::OFF_UNIT_DESCRIPTOR_CLASS_BYTE); + const uint8_t raceByte = *(desc + Offsets::OFF_UNIT_DESCRIPTOR_RACE_BYTE); + const int32_t playerLevel = *reinterpret_cast( + desc + Offsets::OFF_UNIT_FIELD_LEVEL); + if (classByte == 0 || raceByte == 0 || playerLevel <= 0) + return 1; + + // Resolve the queried level — caller-provided when valid (>0), + // else fall back to the player's current level. Out-of-range + // values (negative, 0) are treated as "use mine" since there's + // no useful answer for them anyway. + const int queryLevel = (hasLevelArg && argLevel > 0) ? argLevel : playerLevel; + + const uint32_t playerClassBit = 1u << (classByte - 1); + const uint32_t playerRaceBit = 1u << (raceByte - 1); + + // Bitmask of all valid 1.12 vanilla class bits combined: + // 1=Warrior, 2=Paladin, 3=Hunter, 4=Rogue, 5=Priest, + // 7=Shaman, 8=Mage, 9=Warlock, 11=Druid + // (Class 6 = Death Knight, 10 = Monk; both post-vanilla.) + // + // Used as a sanity gate: a class mask with bits OUTSIDE this + // range is junk data — typically Turtle WoW custom spells with + // a buggy classMask = 0xFFFFFFFF or sentinel values. Honoring + // those would surface unrelated-class spells (e.g. Hunter's + // Searing Shot showing up for a Priest at level 32 because + // 0xFFFFFFFF AND Priest-bit != 0). Drop them. + constexpr uint32_t VALID_VANILLA_CLASS_MASK = + (1u << 0) | (1u << 1) | (1u << 2) | (1u << 3) | (1u << 4) | + (1u << 6) | (1u << 7) | (1u << 8) | (1u << 10); + + const uint8_t *const *records = *reinterpret_cast( + static_cast(Offsets::VAR_SKILL_LINE_ABILITY_RECORDS)); + const int count = *reinterpret_cast( + static_cast(Offsets::VAR_SKILL_LINE_ABILITY_COUNT)); + if (records == nullptr || count <= 0) + return 1; + + // Dedup: pet abilities (Bite, Claw, Growl) have one SLA entry per + // creature family, all pointing at the same spellID. Without + // dedup the list double-counts. Even if the class filter below + // catches them, profession recipes also have multi-row entries + // (per skill line tier) so we keep the set. + std::unordered_set seen; + + int outIdx = 1; + for (int i = 1; i <= count; ++i) { + const uint8_t *rec = records[i]; + if (rec == nullptr) + continue; + + const uint32_t recClassMask = *reinterpret_cast( + rec + Offsets::OFF_SLA_CLASS_MASK); + const uint32_t recRaceMask = *reinterpret_cast( + rec + Offsets::OFF_SLA_RACE_MASK); + const uint32_t recExcludeClass = *reinterpret_cast( + rec + Offsets::OFF_SLA_EXCLUDE_CLASS); + const uint32_t recExcludeRace = *reinterpret_cast( + rec + Offsets::OFF_SLA_EXCLUDE_RACE); + + // Skip if explicitly excluded. + if ((recExcludeClass & playerClassBit) != 0) + continue; + if ((recExcludeRace & playerRaceBit) != 0) + continue; + + // Race filter — race-locked spells need our race bit set in + // raceMask. Applied to both class spells and racials. Without + // this, Turtle WoW's race-locked class spells (e.g. Searing + // Shot tagged as Night Elf Priest at skill 613) leak into + // other races' results. + const bool raceOk = (recRaceMask == 0) || + ((recRaceMask & playerRaceBit) != 0); + if (!raceOk) + continue; + + // Match rules: + // - classMask has our class bit AND classMask has no + // bits outside vanilla's valid-class set → class spell + // (Smite, Fireball, etc.). The PRIMARY case. The + // valid-bits check rejects Turtle's buggy classMask = + // 0xFFFFFFFF entries that would otherwise leak Hunter + // spells into a Priest's list, etc. + // - classMask = 0 AND raceMask has our race bit → racial + // ability (Stoneform, Berserking, etc.) — class-agnostic + // but race-locked. (Race bit already verified above.) + // + // We deliberately DO NOT pass `classMask = 0 AND raceMask = 0` + // (universal entries) because that bucket is dominated by pet + // abilities, profession recipes, and generic utility — none of + // which modern's `GetCurrentLevelSpells` reports. Modern + // returns class-specific learnable spells only; we match that. + const bool maskWithinValid = + (recClassMask & ~VALID_VANILLA_CLASS_MASK) == 0; + const bool isClassSpell = maskWithinValid && + (recClassMask & playerClassBit) != 0; + const bool isRacial = (recClassMask == 0) && (recRaceMask != 0); + if (!isClassSpell && !isRacial) + continue; + + const int spellID = *reinterpret_cast( + rec + Offsets::OFF_SLA_SPELL_ID); + if (spellID <= 0) + continue; + if (SpellBaseLevel(spellID) != queryLevel) + continue; + // Skip talents — they're class spells in SLA but learned via + // talent points, not auto-granted at level. Modern's + // GetCurrentLevelSpells excludes them too. + if (TalentSpellSet().count(spellID) != 0) + continue; + // Skip spells flagged "hide from auto-learn list" — the + // same AttributesEx2 bit Cata's GetCurrentLevelSpells + // checks (FUN_00911c60). Catches engine-internal or proc- + // only spells that have a BaseLevel but aren't meant to + // surface as learnable. + if (SpellHiddenFromAutoLearn(spellID)) + continue; + if (!seen.insert(spellID).second) + continue; + + Game::Lua::PushNumber(L, static_cast(outIdx)); + Game::Lua::PushNumber(L, static_cast(spellID)); + Game::Lua::SetTable(L, -3); + ++outIdx; + } + return 1; +} + +void RegisterLuaFunctions() { + Game::Lua::RegisterTableFunction("C_SpellBook", "GetSpellLevelLearned", + &Script_GetSpellLevelLearned); + Game::Lua::RegisterTableFunction("C_SpellBook", "GetCurrentLevelSpells", + &Script_GetCurrentLevelSpells); +} + +const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions}; + +} // namespace + +} // namespace Spell::Level