mirror of
https://github.com/brues-code/ClassicAPI.git
synced 2026-11-12 04:47:37 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3009c6d8d2 | ||
|
|
b83bb5b52b | ||
|
|
f30efb29b1 | ||
|
|
19b6232e43 | ||
|
|
bbac6b9cac | ||
|
|
e48e4e2361 | ||
|
|
09cd9040f7 | ||
|
|
8f79084c57 | ||
|
|
597b16cb74 | ||
|
|
60ef54b4a6 | ||
|
|
0e8b002af9 | ||
|
|
8bc43b455c | ||
|
|
923cf943e3 | ||
|
|
3a06590add | ||
|
|
c1086189f7 | ||
|
|
e827e319be | ||
|
|
d3667797b5 | ||
|
|
e1ae53488b | ||
|
|
b1a58f0d08 | ||
|
|
a61ff06e9a | ||
|
|
3d2ac4d944 | ||
|
|
167815f27b | ||
|
|
80af00f0c7 | ||
|
|
15e1e21c8c | ||
|
|
8318daa74a | ||
|
|
fc4a983644 | ||
|
|
cd5d38d921 | ||
|
|
51b8a47d7a | ||
|
|
8801b8ce35 | ||
|
|
128186288a | ||
|
|
b46b0cd503 | ||
|
|
1e81acf277 | ||
|
|
a0ee633397 | ||
|
|
792cd4c62b | ||
|
|
bdd9e8faad | ||
|
|
b39e95bc66 | ||
|
|
e83307d4c5 | ||
|
|
628b1c347e | ||
|
|
ed8f0ba851 | ||
|
|
15a36827cd | ||
|
|
52e17d05c1 | ||
|
|
00bad65103 | ||
|
|
8e800502e1 | ||
|
|
da7be7a50a | ||
|
|
9ba66e147c | ||
|
|
7614a50aa4 | ||
|
|
53af083339 | ||
|
|
718e5a31fe | ||
|
|
4554c3a5f5 | ||
|
|
7240688008 | ||
|
|
f8e242639b | ||
|
|
81c4aedb06 | ||
|
|
f08e360f10 | ||
|
|
8d1402dc83 | ||
|
|
81eaf24748 | ||
|
|
bac67038ea | ||
|
|
c8880444f4 | ||
|
|
3e4db9279e | ||
|
|
62cabb2acb | ||
|
|
81e1396f81 | ||
|
|
cf5e9c8ee7 | ||
|
|
622478df04 | ||
|
|
362669b071 | ||
|
|
929b6f5c60 | ||
|
|
3751b31cda | ||
|
|
20c4312251 | ||
|
|
7e6bfd70ad | ||
|
|
c1ac5109e5 | ||
|
|
0b7076d330 | ||
|
|
1d3ca3db6e | ||
|
|
f112a13695 | ||
|
|
986f849b65 | ||
|
|
863cb61e8d | ||
|
|
28bc2b3ee2 | ||
|
|
f6ba0ff9a1 | ||
|
|
1e2a36d630 | ||
|
|
2cab0dcb12 | ||
|
|
a2e3eed0de | ||
|
|
9b01cca336 | ||
|
|
1384160fb0 | ||
|
|
116a3b352c | ||
|
|
56871fdebf | ||
|
|
f96e46113e | ||
|
|
0ee594b9e1 | ||
|
|
943597ca0d | ||
|
|
a446e4cf8c | ||
|
|
a53a08be95 | ||
|
|
0668c37156 | ||
|
|
a37b18bdfd | ||
|
|
3d41c8a702 | ||
|
|
5db35619ca | ||
|
|
6b95c03888 | ||
|
|
1a47cb3215 | ||
|
|
d243457ecf | ||
|
|
e84496d036 | ||
|
|
3ce2880c93 | ||
|
|
9f4e45551b | ||
|
|
09492782cc | ||
|
|
b3955f89df | ||
|
|
1645f6513a | ||
|
|
2d2a5b9442 | ||
|
|
9a2de093b9 | ||
|
|
ff57450b7c | ||
|
|
05b978df3c | ||
|
|
e2c789510a | ||
|
|
fd7843b8b3 | ||
|
|
e6f0a077e6 | ||
|
|
bbd78b437f | ||
|
|
d5c6530b80 | ||
|
|
a47f871adb | ||
|
|
b9071a37f9 | ||
|
|
9ab6627d90 | ||
|
|
799ab1d3ce | ||
|
|
77fb074191 | ||
|
|
5c5c21e2ec | ||
|
|
eccf5896cb | ||
|
|
fdae686cc9 | ||
|
|
e75e585551 | ||
|
|
4ea0223f34 | ||
|
|
6f55df19fa | ||
|
|
889a096963 | ||
|
|
90b4691130 | ||
|
|
99de63755b | ||
|
|
7cd891e86c | ||
|
|
6e50577565 | ||
|
|
024c6d2021 | ||
|
|
4b47059788 | ||
|
|
1aa5a07823 | ||
|
|
00f32e0e2f | ||
|
|
5537432662 | ||
|
|
5962ccc83d | ||
|
|
f5acea6060 | ||
|
|
a86f1219c3 | ||
|
|
338c6777d6 | ||
|
|
aeb3bdf07b | ||
|
|
1caf9fde18 | ||
|
|
d496ff2aa7 | ||
|
|
8b96fccfe9 | ||
|
|
9d3bdfb6ad | ||
|
|
42d037f080 | ||
|
|
af4a379311 | ||
|
|
2b9d0e7127 | ||
|
|
a68fb0a6be | ||
|
|
721f32ac77 | ||
|
|
fcdc24471c | ||
|
|
58f5b4f78e | ||
|
|
6be4aac9fb | ||
|
|
a6270469e1 | ||
|
|
a8f73623c4 | ||
|
|
47b258ad95 | ||
|
|
ac6bd552d5 | ||
|
|
2a05baee8d | ||
|
|
80ef0e2988 | ||
|
|
5df5ce00cf | ||
|
|
1297b9522a | ||
|
|
b3188ced2a | ||
|
|
f55893fdf4 | ||
|
|
e0b2e56070 | ||
|
|
20dc9fc962 | ||
|
|
51d226f67d | ||
|
|
eb3c32094c | ||
|
|
26ca1b4e84 | ||
|
|
7331922070 | ||
|
|
27d8f90f03 | ||
|
|
35ef1228eb | ||
|
|
76cc907bd0 | ||
|
|
e9e431e014 | ||
|
|
fbcc1c9ae1 | ||
|
|
142faafb13 | ||
|
|
c243489916 | ||
|
|
917b15640e | ||
|
|
7ccbbaaf68 | ||
|
|
71805db62f | ||
|
|
85619155f8 | ||
|
|
46dc198505 | ||
|
|
7707127d5f | ||
|
|
fa7d71435f | ||
|
|
3467513df9 | ||
|
|
6000df8009 | ||
|
|
fde3beca9d | ||
|
|
452f3c14fc | ||
|
|
6bb12c3c12 | ||
|
|
7a08199ba5 | ||
|
|
a5bb3823fb | ||
|
|
8c941c757d | ||
|
|
2fff9564b2 | ||
|
|
bbefdb847d | ||
|
|
56d2dbbc27 | ||
|
|
0296e0e5a4 | ||
|
|
6812771a89 | ||
|
|
4d835aa674 | ||
|
|
dfbba225d2 | ||
|
|
930b0c6492 | ||
|
|
428c3308c6 | ||
|
|
a33146241e | ||
|
|
c7af8d396e | ||
|
|
a2a2ccb804 | ||
|
|
7a4ab29cb0 | ||
|
|
ef8ea710d4 | ||
|
|
a2d7d4e9e6 | ||
|
|
449841b4eb | ||
|
|
89c705b922 | ||
|
|
bf79ee1d93 | ||
|
|
4f99a1ed95 | ||
|
|
298eff528c | ||
|
|
b8b9da2adb | ||
|
|
40abcabe9d | ||
|
|
108a91a843 | ||
|
|
b4e5f4f2bb | ||
|
|
390eec4749 | ||
|
|
f86893c8ef | ||
|
|
d4ac5dc210 | ||
|
|
b0585f5628 | ||
|
|
6013d8b937 | ||
|
|
27277b11aa | ||
|
|
ccfdb8309c | ||
|
|
be7a8a0dd7 | ||
|
|
f9167bac06 | ||
|
|
7d82ae8e92 | ||
|
|
ed7e7628c7 | ||
|
|
a562573559 | ||
|
|
5aa382bbb1 | ||
|
|
d98d3a9fd5 | ||
|
|
3d91ae0f91 | ||
|
|
fedccf5b95 | ||
|
|
0ba73b8457 | ||
|
|
d9565fbe1f | ||
|
|
61db68dd7f | ||
|
|
f895d38f76 | ||
|
|
804ed61c76 | ||
|
|
aacace1645 |
@@ -53,6 +53,9 @@ jobs:
|
||||
build:
|
||||
needs: pick-runner
|
||||
runs-on: ${{ needs.pick-runner.outputs.label }}
|
||||
outputs:
|
||||
tag: ${{ steps.ver.outputs.tag }}
|
||||
is_release: ${{ steps.ver.outputs.is_release }}
|
||||
# Windows PowerShell 5.1 is always present; the runner's default `pwsh`
|
||||
# (PowerShell Core) is not installed by default, and `shell: bash` on a
|
||||
# self-hosted box resolves to the WSL launcher in System32.
|
||||
@@ -68,7 +71,7 @@ jobs:
|
||||
# is_release=true when a vX.Y.Z tag is in play (pushed tag,
|
||||
# dispatched-from-tag, or a `tag` input); the embedded addon's
|
||||
# `## Version:` and the compiled CLASSIC_API_VERSION are both
|
||||
# stamped from it at embed/compile time (see cmake/embed_addon.cmake)
|
||||
# stamped from it at embed/compile time (see cmake/embed_resources.cmake)
|
||||
# — no source edit.
|
||||
- name: Resolve version
|
||||
id: ver
|
||||
|
||||
@@ -7,6 +7,9 @@
|
||||
|
||||
locales\locales.xml
|
||||
|
||||
FrameXML\InterfaceOptions.xml
|
||||
FrameXML\InterfaceOptions.lua
|
||||
|
||||
SecureTemplates.xml
|
||||
Compat.lua
|
||||
Util\Print.lua
|
||||
@@ -45,9 +48,24 @@ Util\Vector3D.lua
|
||||
Util\Vector4D.lua
|
||||
Util\UiMapPoint.lua
|
||||
Util\UIParent.lua
|
||||
Util\ActionButton.lua
|
||||
Util\Cooldown.lua
|
||||
Util\WorldMap.lua
|
||||
Util\AuraDurationModifiers.lua
|
||||
Util\AuraUtil.lua
|
||||
Util\SecureUnitMenu.lua
|
||||
Util\TextureUtil.lua
|
||||
Util\MacroOptions.lua
|
||||
Util\SecureStateDriver.lua
|
||||
Util\MacroIconSelection.lua
|
||||
|
||||
Options\Panel.lua
|
||||
|
||||
APIDocumentation\BaseAPIMixin.lua
|
||||
APIDocumentation\FieldsAPIMixin.lua
|
||||
APIDocumentation\FunctionsAPIMixin.lua
|
||||
APIDocumentation\SystemsAPIMixin.lua
|
||||
APIDocumentation\TablesAPIMixin.lua
|
||||
APIDocumentation\EventsAPIMixin.lua
|
||||
APIDocumentation\APIDocumentation.lua
|
||||
APIDocumentation\APIDocumentation_Bootstrap.lua
|
||||
|
||||
@@ -0,0 +1,421 @@
|
||||
-- Backport of Blizzard_APIDocumentation/Blizzard_APIDocumentation.lua to
|
||||
-- vanilla 1.12 / Lua 5.0.
|
||||
--
|
||||
-- Implementation differences from the retail source:
|
||||
-- - Lua 5.0 has no length operator (#); sequence length comes from
|
||||
-- table.getn(t), matching the rest of this addon.
|
||||
-- - Lua 5.0 has no `...` inside a function body; WriteLineF takes its
|
||||
-- extra values from the implicit `arg` table.
|
||||
-- - ChatFrameUtil does not exist. HandleOpenDump uses this client's
|
||||
-- ChatFrame_OpenChat, which applies the text from ChatEdit_OnUpdate
|
||||
-- rather than immediately -- so the cursor is placed one frame later,
|
||||
-- after that text has landed.
|
||||
|
||||
local tGetN = table.getn;
|
||||
|
||||
APIDocumentationMixin = {};
|
||||
|
||||
-- "public"
|
||||
function APIDocumentationMixin:OnLoad()
|
||||
self.tables = {};
|
||||
self.functions = {};
|
||||
self.systems = {};
|
||||
self.fields = {};
|
||||
self.events = {};
|
||||
self.callbacks = {};
|
||||
|
||||
self.Commands = {
|
||||
Default = 1,
|
||||
CopyAPI = 2,
|
||||
OpenDump = 3,
|
||||
};
|
||||
|
||||
if DEFAULT_CHAT_FRAME then
|
||||
DEFAULT_CHAT_FRAME:SetMaxLines(2000);
|
||||
end
|
||||
end
|
||||
|
||||
function APIDocumentationMixin:HandleSlashCommand(command)
|
||||
local commands = { (" "):split(command) };
|
||||
|
||||
if commands[1] == "?" or commands[1] == "help" or commands[1] == "" then
|
||||
self:OutputUsage();
|
||||
elseif commands[1] == "stats" then
|
||||
self:OutputStats();
|
||||
elseif commands[1] == "system" then
|
||||
if commands[2] == "list" then
|
||||
self:OutputAllSystems();
|
||||
else
|
||||
self:OutputUsage();
|
||||
end
|
||||
elseif commands[1] == "s" or commands[1] == "search" then
|
||||
self:OutputAllAPIMatches(unpack(commands, 2));
|
||||
elseif commands[1] then
|
||||
self:TryHandlingSystemSearchCommand(unpack(commands));
|
||||
else
|
||||
self:OutputUsage();
|
||||
end
|
||||
end
|
||||
|
||||
function APIDocumentationMixin:HandleAPILink(link, command)
|
||||
local _, type, name, parentName = (":"):split(link);
|
||||
local apiInfo = self:FindAPIByName(type, name, parentName);
|
||||
if apiInfo then
|
||||
if command == self.Commands.CopyAPI then
|
||||
self:HandleCopyAPI(apiInfo);
|
||||
elseif command == self.Commands.OpenDump then
|
||||
self:HandleOpenDump(apiInfo);
|
||||
else
|
||||
self:HandleDefaultCommand(apiInfo);
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function APIDocumentationMixin:HandleDefaultCommand(apiInfo)
|
||||
self:WriteLine(" ");
|
||||
self:WriteAllLines(apiInfo:GetDetailedOutputLines());
|
||||
end
|
||||
|
||||
function APIDocumentationMixin:HandleCopyAPI(apiInfo)
|
||||
local clipboardString = apiInfo:GetClipboardString();
|
||||
CopyToClipboard(clipboardString);
|
||||
self:WriteLineF("Copied to clipboard: %s", clipboardString);
|
||||
end
|
||||
|
||||
function APIDocumentationMixin:HandleOpenDump(apiInfo)
|
||||
if apiInfo.Type == "Function" then
|
||||
local dumpString;
|
||||
local systemNamespace = apiInfo.System and apiInfo.System:GetNamespaceName() or nil;
|
||||
if systemNamespace and systemNamespace ~= "" then
|
||||
dumpString = ("/dump %s.%s()"):format(systemNamespace, apiInfo.Name);
|
||||
else
|
||||
dumpString = ("/dump %s()"):format(apiInfo.Name);
|
||||
end
|
||||
|
||||
local desiredCursorPosition = string.len(dumpString) - 1;
|
||||
ChatFrame_OpenChat(dumpString);
|
||||
RunNextFrame(function()
|
||||
if ChatFrameEditBox and ChatFrameEditBox:IsVisible() then
|
||||
ChatFrameEditBox:SetCursorPosition(desiredCursorPosition);
|
||||
end
|
||||
end);
|
||||
else
|
||||
self:WriteLine("Can only /dump functions");
|
||||
end
|
||||
end
|
||||
|
||||
function APIDocumentationMixin:FindAPIByName(apiType, name, parentName)
|
||||
local apiTable = self:GetAPITableByTypeName(apiType);
|
||||
if apiTable then
|
||||
for i, apiInfo in ipairs(apiTable) do
|
||||
if apiInfo:MatchesName(name, parentName) then
|
||||
return apiInfo;
|
||||
end
|
||||
end
|
||||
end
|
||||
return nil;
|
||||
end
|
||||
|
||||
function APIDocumentationMixin:GetAPITableByTypeName(apiType)
|
||||
if apiType == "function" then
|
||||
return self.functions;
|
||||
elseif apiType == "table" then
|
||||
return self.tables;
|
||||
elseif apiType == "system" then
|
||||
return self.systems;
|
||||
elseif apiType == "field" then
|
||||
return self.fields;
|
||||
elseif apiType == "event" then
|
||||
return self.events;
|
||||
elseif apiType == "callback" then
|
||||
return self.callbacks;
|
||||
end
|
||||
return nil;
|
||||
end
|
||||
|
||||
function APIDocumentationMixin:OutputUsage()
|
||||
self:WriteLine("Usage:");
|
||||
|
||||
self:WriteLine("Search for API");
|
||||
self:WriteLine(self:GetIndentString() .. "/classicapi search <api name>");
|
||||
self:WriteLine(self:GetIndentString() .. "or");
|
||||
self:WriteLine(self:GetIndentString() .. "/classicapi s <api name>");
|
||||
self:WriteLine(self:GetIndentString() .. "Example: /classicapi search spell");
|
||||
self:WriteLine(" ");
|
||||
|
||||
self:WriteLine("List all systems");
|
||||
self:WriteLine(self:GetIndentString() .. "/classicapi system list");
|
||||
self:WriteLine(" ");
|
||||
|
||||
self:WriteLine("Search system for API");
|
||||
self:WriteLine(self:GetIndentString() .. "/classicapi <system name> search <api name>");
|
||||
self:WriteLine(self:GetIndentString() .. "or");
|
||||
self:WriteLine(self:GetIndentString() .. "/classicapi <system name> s <api name>");
|
||||
self:WriteLine(self:GetIndentString() .. "Example: /classicapi spell search cooldown");
|
||||
self:WriteLine(" ");
|
||||
|
||||
self:WriteLine("List all API in a system");
|
||||
self:WriteLine(self:GetIndentString() .. "/classicapi <system name> list");
|
||||
self:WriteLine(self:GetIndentString() .. "Example: /classicapi spell list");
|
||||
self:WriteLine(" ");
|
||||
self:WriteLine("All searches support Lua patterns.");
|
||||
end
|
||||
|
||||
function APIDocumentationMixin:OutputStats()
|
||||
self:WriteLine("Stats:");
|
||||
self:WriteLineF("Total systems: %d", tGetN(self.systems));
|
||||
local totalFunctions = 0;
|
||||
local totalEvents = 0;
|
||||
local totalTables = 0;
|
||||
|
||||
for i, systemInfo in ipairs(self.systems) do
|
||||
totalFunctions = totalFunctions + systemInfo:GetNumFunctions();
|
||||
totalEvents = totalEvents + systemInfo:GetNumEvents();
|
||||
totalTables = totalTables + systemInfo:GetNumTables();
|
||||
end
|
||||
|
||||
self:WriteLineF("Total functions: %d", totalFunctions);
|
||||
self:WriteLineF("Total events: %d", totalEvents);
|
||||
self:WriteLineF("Total tables: %d", totalTables);
|
||||
end
|
||||
|
||||
function APIDocumentationMixin:OutputAllSystems()
|
||||
self:WriteLineF("All systems (%d):", tGetN(self.systems));
|
||||
for i, systemInfo in ipairs(self.systems) do
|
||||
self:WriteLine(systemInfo:GetSingleOutputLine());
|
||||
end
|
||||
end
|
||||
|
||||
function APIDocumentationMixin:TryHandlingSystemSearchCommand(systemName, subCommand, apiToSearchFor)
|
||||
local system = self:FindSystemByName(systemName);
|
||||
if system then
|
||||
if subCommand == nil then
|
||||
self:WriteLine(system:GetSingleOutputLine());
|
||||
elseif subCommand == "s" or subCommand == "search" and apiToSearchFor then
|
||||
self:OutputAllSystemAPIMatches(system, apiToSearchFor);
|
||||
elseif subCommand == "list" then
|
||||
self:OutputAllSystemAPI(system);
|
||||
else
|
||||
self:OutputUsage();
|
||||
end
|
||||
else
|
||||
self:WriteLineF("No system found (%s)", tostring(systemName));
|
||||
end
|
||||
end
|
||||
|
||||
function APIDocumentationMixin:OutputAPIMatches(apiMatches, headerName)
|
||||
if apiMatches and tGetN(apiMatches) > 0 then
|
||||
self:WriteLineF("Found %d %s", tGetN(apiMatches), headerName);
|
||||
for i, api in ipairs(apiMatches) do
|
||||
self:WriteLine(self:GetIndentString() .. api:GetSingleOutputLine());
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function APIDocumentationMixin:OutputAllAPIMatches(apiToSearchFor)
|
||||
if not apiToSearchFor or apiToSearchFor == "" then
|
||||
self:OutputUsage();
|
||||
return;
|
||||
end
|
||||
self:WriteLine(" ");
|
||||
|
||||
local apiMatches = self:FindAllAPIMatches(apiToSearchFor);
|
||||
if apiMatches then
|
||||
local total = tGetN(apiMatches.tables) + tGetN(apiMatches.functions) + tGetN(apiMatches.events) + tGetN(apiMatches.systems) + tGetN(apiMatches.callbacks);
|
||||
assert(total > 0);
|
||||
self:WriteLineF("Found %d API that matches %q", total, apiToSearchFor);
|
||||
|
||||
self:OutputAPIMatches(apiMatches.systems, "system(s)");
|
||||
self:OutputAPIMatches(apiMatches.functions, "function(s)");
|
||||
self:OutputAPIMatches(apiMatches.events, "events(s)");
|
||||
self:OutputAPIMatches(apiMatches.tables, "table(s)");
|
||||
self:OutputAPIMatches(apiMatches.callbacks, "callback(s)");
|
||||
else
|
||||
self:WriteLineF("No API found that matches %q", apiToSearchFor);
|
||||
end
|
||||
end
|
||||
|
||||
function APIDocumentationMixin:OutputAllSystemAPIMatches(system, apiToSearchFor)
|
||||
local apiMatches = system:FindAllAPIMatches(apiToSearchFor);
|
||||
if apiMatches then
|
||||
local total = tGetN(apiMatches.tables) + tGetN(apiMatches.functions) + tGetN(apiMatches.events);
|
||||
assert(total > 0);
|
||||
self:WriteLineF("Found %d API that matches %q", total, apiToSearchFor);
|
||||
|
||||
self:OutputAPIMatches(apiMatches.functions, "function(s)");
|
||||
self:OutputAPIMatches(apiMatches.events, "events(s)");
|
||||
self:OutputAPIMatches(apiMatches.tables, "table(s)");
|
||||
else
|
||||
self:WriteLineF("No API found that matches %q in %s", apiToSearchFor, system:GenerateAPILink());
|
||||
end
|
||||
end
|
||||
|
||||
function APIDocumentationMixin:OutputAllSystemAPI(system)
|
||||
local apiMatches = system:ListAllAPI();
|
||||
if apiMatches then
|
||||
self:WriteLineF("All API in %s", system:GenerateAPILink());
|
||||
|
||||
self:OutputAPIMatches(apiMatches.functions, "function(s)");
|
||||
self:OutputAPIMatches(apiMatches.events, "events(s)");
|
||||
self:OutputAPIMatches(apiMatches.tables, "table(s)");
|
||||
else
|
||||
self:WriteLineF("No API found in %s", system:GenerateAPILink());
|
||||
end
|
||||
end
|
||||
|
||||
--[[static]] function APIDocumentationMixin:AddAllMatches(apiContainer, matchesContainer, apiToSearchFor)
|
||||
for i, apiInfo in ipairs(apiContainer) do
|
||||
if apiInfo:MatchesSearchString(apiToSearchFor) then
|
||||
table.insert(matchesContainer, apiInfo);
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function APIDocumentationMixin:FindAllAPIMatches(apiToSearchFor)
|
||||
apiToSearchFor = apiToSearchFor:lower();
|
||||
|
||||
local matches = {
|
||||
tables = {},
|
||||
functions = {},
|
||||
events = {},
|
||||
systems = {},
|
||||
callbacks = {},
|
||||
};
|
||||
|
||||
self:AddAllMatches(self.tables, matches.tables, apiToSearchFor);
|
||||
self:AddAllMatches(self.functions, matches.functions, apiToSearchFor);
|
||||
self:AddAllMatches(self.systems, matches.systems, apiToSearchFor);
|
||||
self:AddAllMatches(self.events, matches.events, apiToSearchFor);
|
||||
self:AddAllMatches(self.callbacks, matches.callbacks, apiToSearchFor);
|
||||
|
||||
-- Only return something if we matched anything
|
||||
for name, subTable in pairs(matches) do
|
||||
if tGetN(subTable) > 0 then
|
||||
return matches;
|
||||
end
|
||||
end
|
||||
|
||||
return nil;
|
||||
end
|
||||
|
||||
function APIDocumentationMixin:FindSystemByName(systemName)
|
||||
systemName = systemName:lower();
|
||||
for i, systemInfo in ipairs(self.systems) do
|
||||
if systemInfo:MatchesNameCaseInsenstive(systemName) then
|
||||
return systemInfo;
|
||||
end
|
||||
end
|
||||
return nil;
|
||||
end
|
||||
|
||||
function APIDocumentationMixin:AddDocumentationTable(documentationInfo)
|
||||
if documentationInfo.Name then
|
||||
self:AddSystem(documentationInfo);
|
||||
else
|
||||
for i, tableInfo in ipairs(documentationInfo.Tables) do
|
||||
self:AddTable(tableInfo);
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function APIDocumentationMixin:WriteLine(message)
|
||||
if DEFAULT_CHAT_FRAME then
|
||||
local info = ChatTypeInfo["SYSTEM"];
|
||||
DEFAULT_CHAT_FRAME:AddMessage(message, info.r, info.g, info.b, info.id);
|
||||
else
|
||||
print(message);
|
||||
end
|
||||
end
|
||||
|
||||
-- The `...` in the parameter list is what creates `arg`; a Lua 5.0 function
|
||||
-- declared without it has no `arg` at all.
|
||||
function APIDocumentationMixin:WriteLineF(format, ...)
|
||||
self:WriteLine(string.format(format, unpack(arg)));
|
||||
end
|
||||
|
||||
function APIDocumentationMixin:WriteAllLines(lines)
|
||||
for i, line in ipairs(lines) do
|
||||
self:WriteLine(line);
|
||||
end
|
||||
end
|
||||
|
||||
function APIDocumentationMixin:GetIndentString(numIndent)
|
||||
return (" "):rep(numIndent or 1);
|
||||
end
|
||||
|
||||
-- "private"
|
||||
function APIDocumentationMixin:AddTable(documentationInfo)
|
||||
Mixin(documentationInfo, TablesAPIMixin);
|
||||
|
||||
table.insert(self.tables, documentationInfo);
|
||||
|
||||
if documentationInfo.Fields then
|
||||
for i, field in ipairs(documentationInfo.Fields) do
|
||||
field.Table = documentationInfo;
|
||||
self:AddField(field);
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function APIDocumentationMixin:AddFunction(documentationInfo)
|
||||
Mixin(documentationInfo, FunctionsAPIMixin);
|
||||
|
||||
table.insert(self.functions, documentationInfo);
|
||||
|
||||
if documentationInfo.Arguments then
|
||||
for i, field in ipairs(documentationInfo.Arguments) do
|
||||
field.Function = documentationInfo;
|
||||
self:AddField(field);
|
||||
end
|
||||
end
|
||||
|
||||
if documentationInfo.Returns then
|
||||
for i, field in ipairs(documentationInfo.Returns) do
|
||||
field.Function = documentationInfo;
|
||||
self:AddField(field);
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function APIDocumentationMixin:AddEvent(documentationInfo)
|
||||
Mixin(documentationInfo, EventsAPIMixin);
|
||||
|
||||
table.insert(self.events, documentationInfo);
|
||||
|
||||
if documentationInfo.Payload then
|
||||
for i, field in ipairs(documentationInfo.Payload) do
|
||||
field.Event = documentationInfo;
|
||||
self:AddField(field);
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function APIDocumentationMixin:AddField(documentationInfo)
|
||||
Mixin(documentationInfo, FieldsAPIMixin);
|
||||
|
||||
table.insert(self.fields, documentationInfo);
|
||||
end
|
||||
|
||||
function APIDocumentationMixin:AddSystem(documentationInfo)
|
||||
Mixin(documentationInfo, SystemsAPIMixin);
|
||||
|
||||
table.insert(self.systems, documentationInfo);
|
||||
|
||||
for i, functionInfo in ipairs(documentationInfo.Functions) do
|
||||
functionInfo.System = documentationInfo;
|
||||
self:AddFunction(functionInfo);
|
||||
end
|
||||
|
||||
for i, eventInfo in ipairs(documentationInfo.Events) do
|
||||
eventInfo.System = documentationInfo;
|
||||
self:AddEvent(eventInfo);
|
||||
end
|
||||
|
||||
for i, tableInfo in ipairs(documentationInfo.Tables) do
|
||||
tableInfo.System = documentationInfo;
|
||||
self:AddTable(tableInfo);
|
||||
end
|
||||
end
|
||||
|
||||
APIDocumentation = CreateFromMixins(APIDocumentationMixin);
|
||||
APIDocumentation:OnLoad();
|
||||
@@ -0,0 +1,66 @@
|
||||
-- Backport of Blizzard_APIDocumentation/Blizzard_APIDocumentation_Bootstrap.lua
|
||||
-- to vanilla 1.12 / Lua 5.0, plus the `/api` command and `api` link handler
|
||||
-- that retail keeps in Blizzard_ChatFrameBase and Blizzard_UIPanels_Game.
|
||||
--
|
||||
-- Implementation differences from the retail source:
|
||||
-- - Retail loads a generated data addon on demand
|
||||
-- (LoadAddOnWithErrorHandling). ClassicAPI keeps the documentation in the
|
||||
-- DLL instead, so APIDocumentation_LoadUI reads it through
|
||||
-- C_APIDocumentation and feeds each system to AddDocumentationTable. The
|
||||
-- load still happens on first use, so a session that never types /api
|
||||
-- builds no tables at all.
|
||||
-- - IsModifiedClick does not exist on this client. CHATLINK is Shift by
|
||||
-- default, so a shift-click stands in for it.
|
||||
-- - Lua 5.0 has no length operator (#); table.getn(t) gives the count.
|
||||
|
||||
local loaded = false;
|
||||
|
||||
-- Fetches every documented system from the DLL. Returns true once the
|
||||
-- documentation is in place, false when the DLL is absent (the addon can be
|
||||
-- installed on its own).
|
||||
function APIDocumentation_LoadUI()
|
||||
if loaded then
|
||||
return true;
|
||||
end
|
||||
-- Latch BEFORE the fetch: a system table the browser chokes on must not
|
||||
-- raise the same error on every later /api.
|
||||
loaded = true;
|
||||
|
||||
if not C_APIDocumentation then
|
||||
APIDocumentation:WriteLine("API documentation is not available (C_APIDocumentation is missing).");
|
||||
return false;
|
||||
end
|
||||
|
||||
-- ipairs, not a length call: it walks 1..nil whatever the table's internal
|
||||
-- shape, which is how every other consumer reads an array the DLL built.
|
||||
for i, name in ipairs(C_APIDocumentation.GetSystems()) do
|
||||
local system = C_APIDocumentation.GetSystem(name);
|
||||
if system then
|
||||
APIDocumentation:AddDocumentationTable(system);
|
||||
end
|
||||
end
|
||||
return true;
|
||||
end
|
||||
|
||||
-- Retail calls this `/api`. Here the browser holds only what ClassicAPI adds,
|
||||
-- not the 1.12 API the client already ships, so it is named for what it
|
||||
-- documents. `/capi` is the short form.
|
||||
SLASH_CLASSICAPI1 = "/classicapi";
|
||||
SLASH_CLASSICAPI2 = "/capi";
|
||||
SlashCmdList["CLASSICAPI"] = function(msg)
|
||||
APIDocumentation_LoadUI();
|
||||
APIDocumentation:HandleSlashCommand(msg or "");
|
||||
end
|
||||
|
||||
LinkUtil.RegisterLinkHandler(LinkTypes.APIDocumentation, function(link, text, linkData, contextData)
|
||||
APIDocumentation_LoadUI();
|
||||
|
||||
local command = APIDocumentation.Commands.Default;
|
||||
if contextData and contextData.button == "RightButton" then
|
||||
command = APIDocumentation.Commands.CopyAPI;
|
||||
elseif IsShiftKeyDown() then
|
||||
command = APIDocumentation.Commands.OpenDump;
|
||||
end
|
||||
|
||||
APIDocumentation:HandleAPILink(link, command);
|
||||
end);
|
||||
@@ -0,0 +1,115 @@
|
||||
-- Backport of Blizzard_APIDocumentation/BaseAPIMixin.lua to vanilla 1.12 /
|
||||
-- Lua 5.0.
|
||||
--
|
||||
-- Implementation differences from the retail source: none. Every construct
|
||||
-- here (method calls on string literals, string.format's %s, table.insert,
|
||||
-- ipairs, CreateFromMixins) exists on this client.
|
||||
|
||||
BaseAPIMixin = {};
|
||||
|
||||
function BaseAPIMixin:GetType()
|
||||
return assert(false);
|
||||
end
|
||||
|
||||
function BaseAPIMixin:GetPrettyType()
|
||||
return self:GetType();
|
||||
end
|
||||
|
||||
function BaseAPIMixin:GetLinkHexColor()
|
||||
return "ffffff";
|
||||
end
|
||||
|
||||
function BaseAPIMixin:GetName()
|
||||
return self.Name;
|
||||
end
|
||||
|
||||
function BaseAPIMixin:GetFullName()
|
||||
return self:GetName();
|
||||
end
|
||||
|
||||
function BaseAPIMixin:GetParentName()
|
||||
return "";
|
||||
end
|
||||
|
||||
function BaseAPIMixin:GetLoweredParentName()
|
||||
if not self.loweredParentName then
|
||||
self.loweredParentName = self:GetParentName():lower();
|
||||
end
|
||||
return self.loweredParentName;
|
||||
end
|
||||
|
||||
function BaseAPIMixin:GetLoweredName()
|
||||
if not self.loweredName then
|
||||
self.loweredName = self:GetName():lower();
|
||||
end
|
||||
return self.loweredName;
|
||||
end
|
||||
|
||||
function BaseAPIMixin:GetClipboardString()
|
||||
return self:GetFullName();
|
||||
end
|
||||
|
||||
function BaseAPIMixin:GenerateAPILink()
|
||||
return ("|cff%s|Hapi:%s:%s:%s|h%s|h|r"):format(self:GetLinkHexColor(), self:GetType(), self:GetName(), self:GetParentName(), self:GetFullName());
|
||||
end
|
||||
|
||||
function BaseAPIMixin:GetSingleOutputLine()
|
||||
return ("%s %s"):format(self:GetPrettyType(), self:GenerateAPILink());
|
||||
end
|
||||
|
||||
function BaseAPIMixin:GetDetailedOutputLines()
|
||||
return { self:GetSingleOutputLine() };
|
||||
end
|
||||
|
||||
function BaseAPIMixin:MatchesSearchString(searchString)
|
||||
return false;
|
||||
end
|
||||
|
||||
function BaseAPIMixin:MatchesName(name, parentName)
|
||||
if name == self:GetName() then
|
||||
return not parentName or parentName == self:GetParentName();
|
||||
end
|
||||
return false;
|
||||
end
|
||||
|
||||
function BaseAPIMixin:MatchesNameCaseInsenstive(name, parentName)
|
||||
if name == self:GetLoweredName() then
|
||||
return not parentName or parentName == self:GetLoweredParentName();
|
||||
end
|
||||
return false;
|
||||
end
|
||||
|
||||
function BaseAPIMixin:MatchesAnyAPI(apiTable, searchString)
|
||||
if apiTable then
|
||||
for i, apiInfo in ipairs(apiTable) do
|
||||
if apiInfo:MatchesSearchString(searchString) then
|
||||
return true;
|
||||
end
|
||||
end
|
||||
end
|
||||
return false;
|
||||
end
|
||||
|
||||
function BaseAPIMixin:MatchesAnyDocumentation(searchString)
|
||||
if self.Documentation then
|
||||
for i, documentation in ipairs(self.Documentation) do
|
||||
if documentation:lower():match(searchString) then
|
||||
return true;
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function BaseAPIMixin:AddDocumentationTags(lines)
|
||||
if self.Documentation then
|
||||
for i, documentation in ipairs(self.Documentation) do
|
||||
table.insert(lines, APIDocumentation:GetIndentString() .. documentation);
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function BaseAPIMixin:AddSystemTag(lines)
|
||||
if self.System then
|
||||
table.insert(lines, APIDocumentation:GetIndentString() .. ("Part of the %s system"):format(self.System:GenerateAPILink()));
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,104 @@
|
||||
-- Backport of Blizzard_APIDocumentation/EventsAPIMixin.lua to vanilla 1.12 /
|
||||
-- Lua 5.0.
|
||||
--
|
||||
-- Implementation differences from the retail source:
|
||||
-- - The clipboard snippet uses this client's event convention. Handlers
|
||||
-- here read the `event` and `arg1`..`argN` globals rather than a vararg
|
||||
-- list, so the copied body declares those instead of `local a = ...`.
|
||||
|
||||
EventsAPIMixin = CreateFromMixins(BaseAPIMixin);
|
||||
|
||||
function EventsAPIMixin:GetParentName() -- override
|
||||
if self.System then
|
||||
return self.System:GetName();
|
||||
end
|
||||
|
||||
return "";
|
||||
end
|
||||
|
||||
function EventsAPIMixin:GetType() -- override
|
||||
return "event";
|
||||
end
|
||||
|
||||
function EventsAPIMixin:GetLinkHexColor()
|
||||
return "77ff22";
|
||||
end
|
||||
|
||||
function EventsAPIMixin:GetClipboardString()
|
||||
local lines = {};
|
||||
table.insert(lines, ([[if event == "%s" then]]):format(self.LiteralName));
|
||||
if self.Payload then
|
||||
local names = {};
|
||||
for i, payloadInfo in ipairs(self.Payload) do
|
||||
table.insert(names, ("local %s = arg%d;"):format(payloadInfo:GetName(), i));
|
||||
end
|
||||
table.insert(lines, "\t" .. table.concat(names, " "));
|
||||
end
|
||||
table.insert(lines, "end");
|
||||
return table.concat(lines, "\r\n");
|
||||
end
|
||||
|
||||
function EventsAPIMixin:GetFullName(decorateOptionals, includeColorCodes) -- override
|
||||
if self.System then
|
||||
return ("Event.%s.%s -> %s"):format(self.System:GetName(), self:GetName(), self:GetPayloadString(decorateOptionals, includeColorCodes));
|
||||
end
|
||||
return ("Event.%s -> %s"):format(self:GetName(), self:GetPayloadString(decorateOptionals, includeColorCodes));
|
||||
end
|
||||
|
||||
function EventsAPIMixin:MatchesSearchString(searchString) -- override
|
||||
if self:GetLoweredName():match(searchString) then
|
||||
return true;
|
||||
end
|
||||
|
||||
if self.System and self.System:GetLoweredName():match(searchString) then
|
||||
return true;
|
||||
end
|
||||
|
||||
if self.LiteralName:lower():match(searchString) then
|
||||
return true;
|
||||
end
|
||||
|
||||
if self:MatchesAnyDocumentation(searchString) then
|
||||
return true;
|
||||
end
|
||||
|
||||
if self:MatchesAnyAPI(self.Payload, searchString) then
|
||||
return true
|
||||
end
|
||||
|
||||
return false;
|
||||
end
|
||||
|
||||
function EventsAPIMixin:GetPayloadString(decorateOptionals, includeColorCodes) -- override
|
||||
if self.Payload then
|
||||
local values = {};
|
||||
for i, payloadInfo in ipairs(self.Payload) do
|
||||
if includeColorCodes ~= false then
|
||||
table.insert(values, ("%s|cff%s"):format(payloadInfo:GetPayloadString(decorateOptionals, includeColorCodes), self:GetLinkHexColor()));
|
||||
else
|
||||
table.insert(values, payloadInfo:GetPayloadString(decorateOptionals, includeColorCodes));
|
||||
end
|
||||
end
|
||||
return table.concat(values, ", ");
|
||||
end
|
||||
return "";
|
||||
end
|
||||
|
||||
function EventsAPIMixin:GetDetailedOutputLines() -- override
|
||||
local lines = {};
|
||||
table.insert(lines, self:GetSingleOutputLine());
|
||||
|
||||
self:AddSystemTag(lines);
|
||||
self:AddDocumentationTags(lines);
|
||||
|
||||
table.insert(lines, APIDocumentation:GetIndentString() .. "Literal Name: \"" .. self.LiteralName .. "\"");
|
||||
|
||||
if self.Payload then
|
||||
table.insert(lines, APIDocumentation:GetIndentString() .. "Payload");
|
||||
for i, payloadInfo in ipairs(self.Payload) do
|
||||
table.insert(lines, APIDocumentation:GetIndentString(2) .. ("%d. %s"):format(i, payloadInfo:GetSingleOutputLine()));
|
||||
end
|
||||
end
|
||||
|
||||
return lines;
|
||||
end
|
||||
@@ -0,0 +1,90 @@
|
||||
-- Backport of Blizzard_APIDocumentation/FieldsAPIMixin.lua to vanilla 1.12 /
|
||||
-- Lua 5.0.
|
||||
--
|
||||
-- Implementation differences from the retail source: none.
|
||||
|
||||
FieldsAPIMixin = CreateFromMixins(BaseAPIMixin);
|
||||
|
||||
function FieldsAPIMixin:GetParentName()
|
||||
if self.Function then
|
||||
return self.Function:GetName();
|
||||
end
|
||||
|
||||
if self.Table then
|
||||
return self.Table:GetName();
|
||||
end
|
||||
return "";
|
||||
end
|
||||
|
||||
function FieldsAPIMixin:GetType()
|
||||
return "field";
|
||||
end
|
||||
|
||||
function FieldsAPIMixin:GetLinkHexColor()
|
||||
return "ffdd55";
|
||||
end
|
||||
|
||||
function FieldsAPIMixin:MatchesSearchString(searchString)
|
||||
if self:GetLoweredName():match(searchString) then
|
||||
return true;
|
||||
end
|
||||
|
||||
if self:MatchesAnyDocumentation(searchString) then
|
||||
return true;
|
||||
end
|
||||
|
||||
return false;
|
||||
end
|
||||
|
||||
function FieldsAPIMixin:GetLuaType()
|
||||
if self.InnerType then
|
||||
local complexType = APIDocumentation:FindAPIByName("table", self.InnerType);
|
||||
return ("%s of %s"):format(self.Type, complexType and complexType:GenerateAPILink() or self.InnerType)
|
||||
end
|
||||
|
||||
if self.EnumValue then
|
||||
return self.EnumValue;
|
||||
end
|
||||
|
||||
local complexType = APIDocumentation:FindAPIByName("table", self.Type);
|
||||
return complexType and complexType:GenerateAPILink() or self.Type;
|
||||
end
|
||||
|
||||
function FieldsAPIMixin:GetStrideIndex()
|
||||
return self.StrideIndex;
|
||||
end
|
||||
|
||||
function FieldsAPIMixin:IsOptional()
|
||||
return self.Default ~= nil or self.Nilable;
|
||||
end
|
||||
|
||||
function FieldsAPIMixin:GetSingleOutputLine()
|
||||
local optionalString = "";
|
||||
if self:IsOptional() then
|
||||
if self.Default ~= nil then
|
||||
optionalString = ("(default:%s) "):format(tostring(self.Default));
|
||||
else
|
||||
optionalString = "(optional) ";
|
||||
end
|
||||
end
|
||||
if self.Documentation then
|
||||
return ("%s%s %s - %s"):format(optionalString, self:GetLuaType(), self:GenerateAPILink(), table.concat(self.Documentation, " "));
|
||||
end
|
||||
return ("%s%s %s"):format(optionalString, self:GetLuaType(), self:GenerateAPILink());
|
||||
end
|
||||
|
||||
function FieldsAPIMixin:GetArgumentString(decorateOptionals, includeColorCodes)
|
||||
local prefix = decorateOptionals ~= false and self:IsOptional() and "optional " or "";
|
||||
if includeColorCodes ~= false then
|
||||
return ("|cff%s%s%s|r"):format(self:GetLinkHexColor(), prefix, self:GetName());
|
||||
end
|
||||
return ("%s%s"):format(prefix, self:GetName());
|
||||
end
|
||||
|
||||
function FieldsAPIMixin:GetReturnString(decorateOptionals, includeColorCodes)
|
||||
return self:GetArgumentString(decorateOptionals, includeColorCodes); -- Nothing special currently
|
||||
end
|
||||
|
||||
function FieldsAPIMixin:GetPayloadString(decorateOptionals, includeColorCodes)
|
||||
return self:GetReturnString(decorateOptionals, includeColorCodes); -- Nothing special currently
|
||||
end
|
||||
@@ -0,0 +1,121 @@
|
||||
-- Backport of Blizzard_APIDocumentation/FunctionsAPIMixin.lua to vanilla 1.12
|
||||
-- / Lua 5.0.
|
||||
--
|
||||
-- Implementation differences from the retail source: none.
|
||||
--
|
||||
-- A widget-method system (Type "ScriptObject") carries no Namespace, so
|
||||
-- GetFullName prints its methods bare -- "SetSpellByID(spellID)" -- exactly as
|
||||
-- retail prints its own widget API.
|
||||
|
||||
FunctionsAPIMixin = CreateFromMixins(BaseAPIMixin);
|
||||
|
||||
function FunctionsAPIMixin:GetParentName()
|
||||
if self.System then
|
||||
return self.System:GetName();
|
||||
end
|
||||
|
||||
return "";
|
||||
end
|
||||
|
||||
function FunctionsAPIMixin:GetType()
|
||||
return "function";
|
||||
end
|
||||
|
||||
function FunctionsAPIMixin:GetLinkHexColor()
|
||||
return "55ddff";
|
||||
end
|
||||
|
||||
function FunctionsAPIMixin:GetFullName(decorateOptionals, includeColorCodes)
|
||||
if self.System and self.System:GetNamespaceName() ~= "" then
|
||||
return ("%s.%s(%s)"):format(self.System:GetNamespaceName(), self:GetName(), self:GetArgumentString(decorateOptionals, includeColorCodes));
|
||||
end
|
||||
return ("%s(%s)"):format(self:GetName(), self:GetArgumentString(decorateOptionals, includeColorCodes));
|
||||
end
|
||||
|
||||
function FunctionsAPIMixin:MatchesSearchString(searchString)
|
||||
if self:GetLoweredName():match(searchString) then
|
||||
return true;
|
||||
end
|
||||
|
||||
if self:MatchesAnyDocumentation(searchString) then
|
||||
return true;
|
||||
end
|
||||
|
||||
if self:MatchesAnyAPI(self.Arguments, searchString) then
|
||||
return true
|
||||
end
|
||||
|
||||
if self:MatchesAnyAPI(self.Returns, searchString) then
|
||||
return true
|
||||
end
|
||||
|
||||
return false;
|
||||
end
|
||||
|
||||
function FunctionsAPIMixin:GetArgumentString(decorateOptionals, includeColorCodes)
|
||||
if self.Arguments then
|
||||
local values = {};
|
||||
for i, argumentInfo in ipairs(self.Arguments) do
|
||||
if includeColorCodes ~= false then
|
||||
table.insert(values, ("%s|cff%s"):format(argumentInfo:GetArgumentString(decorateOptionals, includeColorCodes), self:GetLinkHexColor()));
|
||||
else
|
||||
table.insert(values, argumentInfo:GetArgumentString(decorateOptionals, includeColorCodes));
|
||||
end
|
||||
end
|
||||
return table.concat(values, ", ");
|
||||
end
|
||||
return "";
|
||||
end
|
||||
|
||||
function FunctionsAPIMixin:GetReturnString(decorateOptionals, includeColorCodes)
|
||||
if self.Returns then
|
||||
local values = {};
|
||||
for i, returnInfo in ipairs(self.Returns) do
|
||||
if includeColorCodes ~= false then
|
||||
table.insert(values, ("%s|cff%s"):format(returnInfo:GetReturnString(decorateOptionals, includeColorCodes), self:GetLinkHexColor()));
|
||||
else
|
||||
table.insert(values, returnInfo:GetReturnString(decorateOptionals, includeColorCodes));
|
||||
end
|
||||
end
|
||||
return table.concat(values, ", ");
|
||||
end
|
||||
return "";
|
||||
end
|
||||
|
||||
function FunctionsAPIMixin:GetClipboardString()
|
||||
if self.Returns then
|
||||
return ("local %s = %s"):format(self:GetReturnString(false, false), self:GetFullName(false, false));
|
||||
end
|
||||
return self:GetFullName(false, false);
|
||||
end
|
||||
|
||||
function FunctionsAPIMixin:GetDetailedOutputLines()
|
||||
local lines = {};
|
||||
table.insert(lines, self:GetSingleOutputLine());
|
||||
|
||||
self:AddSystemTag(lines);
|
||||
self:AddDocumentationTags(lines);
|
||||
|
||||
if self.Arguments then
|
||||
table.insert(lines, APIDocumentation:GetIndentString() .. "Arguments");
|
||||
for i, argumentInfo in ipairs(self.Arguments) do
|
||||
if argumentInfo:GetStrideIndex() == 1 then
|
||||
table.insert(lines, APIDocumentation:GetIndentString(2) .. "(Variable arguments)");
|
||||
end
|
||||
|
||||
table.insert(lines, APIDocumentation:GetIndentString(2) .. ("%d. %s"):format(i, argumentInfo:GetSingleOutputLine()));
|
||||
end
|
||||
end
|
||||
|
||||
if self.Returns then
|
||||
table.insert(lines, APIDocumentation:GetIndentString() .. "Returns");
|
||||
for i, returnInfo in ipairs(self.Returns) do
|
||||
if returnInfo:GetStrideIndex() == 1 then
|
||||
table.insert(lines, APIDocumentation:GetIndentString(2) .. "(Variable returns)");
|
||||
end
|
||||
table.insert(lines, APIDocumentation:GetIndentString(2) .. ("%d. %s"):format(i, returnInfo:GetSingleOutputLine()));
|
||||
end
|
||||
end
|
||||
|
||||
return lines;
|
||||
end
|
||||
@@ -0,0 +1,159 @@
|
||||
-- Backport of Blizzard_APIDocumentation/SystemsAPIMixin.lua to vanilla 1.12 /
|
||||
-- Lua 5.0.
|
||||
--
|
||||
-- Implementation differences from the retail source:
|
||||
-- - Lua 5.0 has no length operator (#); sequence length comes from
|
||||
-- table.getn(t), matching the rest of this addon.
|
||||
-- - A search also matches a system's namespace. The namespace is the name
|
||||
-- people type, and retail's version checks only the short name, so
|
||||
-- "search C_Spell" found nothing while "search spell" found the system.
|
||||
|
||||
local tGetN = table.getn;
|
||||
|
||||
SystemsAPIMixin = CreateFromMixins(BaseAPIMixin);
|
||||
|
||||
function SystemsAPIMixin:GetType()
|
||||
return "system";
|
||||
end
|
||||
|
||||
function SystemsAPIMixin:GetLinkHexColor()
|
||||
return "ff55dd";
|
||||
end
|
||||
|
||||
function SystemsAPIMixin:GetNamespaceName()
|
||||
return self.Namespace or "";
|
||||
end
|
||||
|
||||
function SystemsAPIMixin:GetLoweredNamespaceName()
|
||||
if not self.loweredNamespaceName then
|
||||
self.loweredNamespaceName = self:GetNamespaceName():lower();
|
||||
end
|
||||
return self.loweredNamespaceName;
|
||||
end
|
||||
|
||||
function SystemsAPIMixin:MatchesSearchString(searchString)
|
||||
if self:GetLoweredName():match(searchString) then
|
||||
return true;
|
||||
end
|
||||
|
||||
local namespace = self:GetLoweredNamespaceName();
|
||||
if namespace ~= "" and namespace:match(searchString) then
|
||||
return true;
|
||||
end
|
||||
|
||||
if self:MatchesAnyDocumentation(searchString) then
|
||||
return true;
|
||||
end
|
||||
|
||||
return false;
|
||||
end
|
||||
|
||||
function SystemsAPIMixin:GetSingleOutputLine()
|
||||
if self.Namespace then
|
||||
return ("%s %s (%s)"):format(self:GetPrettyType(), self:GenerateAPILink(), self.Namespace);
|
||||
end
|
||||
return BaseAPIMixin.GetSingleOutputLine(self);
|
||||
end
|
||||
|
||||
function SystemsAPIMixin:GetDetailedOutputLines()
|
||||
local lines = {};
|
||||
table.insert(lines, self:GetSingleOutputLine());
|
||||
|
||||
self:AddDocumentationTags(lines);
|
||||
|
||||
if self.Functions and tGetN(self.Functions) > 0 then
|
||||
table.insert(lines, APIDocumentation:GetIndentString() .. "Functions");
|
||||
for i, functionInfo in ipairs(self.Functions) do
|
||||
table.insert(lines, APIDocumentation:GetIndentString(2) .. functionInfo:GetSingleOutputLine());
|
||||
end
|
||||
end
|
||||
|
||||
if self.Events and tGetN(self.Events) > 0 then
|
||||
table.insert(lines, APIDocumentation:GetIndentString() .. "Events");
|
||||
for i, eventInfo in ipairs(self.Events) do
|
||||
table.insert(lines, APIDocumentation:GetIndentString(2) .. eventInfo:GetSingleOutputLine());
|
||||
end
|
||||
end
|
||||
|
||||
if self.Tables and tGetN(self.Tables) > 0 then
|
||||
table.insert(lines, APIDocumentation:GetIndentString() .. "Tables");
|
||||
for i, tableInfo in ipairs(self.Tables) do
|
||||
table.insert(lines, APIDocumentation:GetIndentString(2) .. tableInfo:GetSingleOutputLine());
|
||||
end
|
||||
end
|
||||
|
||||
return lines;
|
||||
end
|
||||
|
||||
function SystemsAPIMixin:MatchesName(name, parentName)
|
||||
if BaseAPIMixin.MatchesName(self, name, parentName) then
|
||||
return true;
|
||||
end
|
||||
|
||||
return name == self:GetNamespaceName();
|
||||
end
|
||||
|
||||
function SystemsAPIMixin:MatchesNameCaseInsenstive(name, parentName)
|
||||
if BaseAPIMixin.MatchesNameCaseInsenstive(self, name, parentName) then
|
||||
return true;
|
||||
end
|
||||
|
||||
return name == self:GetLoweredNamespaceName();
|
||||
end
|
||||
|
||||
function SystemsAPIMixin:FindAllAPIMatches(apiToSearchFor)
|
||||
apiToSearchFor = apiToSearchFor:lower();
|
||||
|
||||
local matches = {
|
||||
tables = {},
|
||||
functions = {},
|
||||
events = {},
|
||||
};
|
||||
|
||||
APIDocumentationMixin:AddAllMatches(self.Tables, matches.tables, apiToSearchFor);
|
||||
APIDocumentationMixin:AddAllMatches(self.Functions, matches.functions, apiToSearchFor);
|
||||
APIDocumentationMixin:AddAllMatches(self.Events, matches.events, apiToSearchFor);
|
||||
|
||||
-- Only return something if we matched anything
|
||||
for name, subTable in pairs(matches) do
|
||||
if tGetN(subTable) > 0 then
|
||||
return matches;
|
||||
end
|
||||
end
|
||||
|
||||
return nil;
|
||||
end
|
||||
|
||||
local function AddAll(apiContainer, matchesContainer)
|
||||
if apiContainer then
|
||||
for i, apiInfo in ipairs(apiContainer) do
|
||||
table.insert(matchesContainer, apiInfo);
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function SystemsAPIMixin:ListAllAPI()
|
||||
local allAPI = {
|
||||
tables = {},
|
||||
functions = {},
|
||||
events = {},
|
||||
};
|
||||
|
||||
AddAll(self.Tables, allAPI.tables);
|
||||
AddAll(self.Functions, allAPI.functions);
|
||||
AddAll(self.Events, allAPI.events);
|
||||
|
||||
return allAPI;
|
||||
end
|
||||
|
||||
function SystemsAPIMixin:GetNumTables()
|
||||
return self.Tables and tGetN(self.Tables) or 0;
|
||||
end
|
||||
|
||||
function SystemsAPIMixin:GetNumFunctions()
|
||||
return self.Functions and tGetN(self.Functions) or 0;
|
||||
end
|
||||
|
||||
function SystemsAPIMixin:GetNumEvents()
|
||||
return self.Events and tGetN(self.Events) or 0;
|
||||
end
|
||||
@@ -0,0 +1,74 @@
|
||||
-- Backport of Blizzard_APIDocumentation/TablesAPIMixin.lua to vanilla 1.12 /
|
||||
-- Lua 5.0.
|
||||
--
|
||||
-- Implementation differences from the retail source: none.
|
||||
|
||||
TablesAPIMixin = CreateFromMixins(BaseAPIMixin);
|
||||
|
||||
function TablesAPIMixin:GetParentName()
|
||||
if self.System then
|
||||
return self.System:GetName();
|
||||
end
|
||||
|
||||
return "";
|
||||
end
|
||||
|
||||
function TablesAPIMixin:GetType()
|
||||
return "table";
|
||||
end
|
||||
|
||||
function TablesAPIMixin:GetPrettyType()
|
||||
return self.Type:lower();
|
||||
end
|
||||
|
||||
function TablesAPIMixin:GetLinkHexColor()
|
||||
return "55ffdd";
|
||||
end
|
||||
|
||||
function TablesAPIMixin:GetFullName() -- override
|
||||
if self.Type == "Enumeration" then
|
||||
return ("Enum.%s"):format(self:GetName());
|
||||
end
|
||||
|
||||
return BaseAPIMixin.GetFullName(self);
|
||||
end
|
||||
|
||||
function TablesAPIMixin:MatchesSearchString(searchString)
|
||||
if self:GetLoweredName():match(searchString) then
|
||||
return true;
|
||||
end
|
||||
|
||||
if self:MatchesAnyDocumentation(searchString) then
|
||||
return true;
|
||||
end
|
||||
|
||||
if self:MatchesAnyAPI(self.Fields, searchString) then
|
||||
return true
|
||||
end
|
||||
return false;
|
||||
end
|
||||
|
||||
function TablesAPIMixin:GetDetailedOutputLines()
|
||||
local lines = {};
|
||||
table.insert(lines, self:GetSingleOutputLine());
|
||||
|
||||
self:AddSystemTag(lines);
|
||||
self:AddDocumentationTags(lines);
|
||||
|
||||
if self.Fields then
|
||||
if self.Type == "Enumeration" then
|
||||
table.insert(lines, APIDocumentation:GetIndentString() .. "Num Values: " .. self.NumValues);
|
||||
table.insert(lines, APIDocumentation:GetIndentString() .. "Min Value: " .. self.MinValue);
|
||||
table.insert(lines, APIDocumentation:GetIndentString() .. "Max Value: " .. self.MaxValue);
|
||||
table.insert(lines, APIDocumentation:GetIndentString() .. "Values");
|
||||
else
|
||||
table.insert(lines, APIDocumentation:GetIndentString() .. "Fields");
|
||||
end
|
||||
|
||||
for i, fieldInfo in ipairs(self.Fields) do
|
||||
table.insert(lines, APIDocumentation:GetIndentString(2) .. fieldInfo:GetSingleOutputLine());
|
||||
end
|
||||
end
|
||||
|
||||
return lines;
|
||||
end
|
||||
@@ -0,0 +1,373 @@
|
||||
-- Backport of the Interface Options panel's addon side (InterfaceOptionsFrame,
|
||||
-- InterfaceOptions_AddCategory, InterfaceOptionsFrame_OpenToCategory) to
|
||||
-- vanilla 1.12 / Lua 5.0.
|
||||
--
|
||||
-- Later clients list addon option panels in InterfaceOptionsFrame. Addons add
|
||||
-- theirs with InterfaceOptions_AddCategory(panel) - Ace3's
|
||||
-- AceConfigDialog:AddToBlizOptions does it for every Ace3 addon - and open them
|
||||
-- with InterfaceOptionsFrame_OpenToCategory. Frame and list names match later
|
||||
-- clients because addons reach for them directly (Zygor Guides Viewer 2.0
|
||||
-- re-tints the frame's first region; LibBetterBlizzOptions-1.0 resizes the
|
||||
-- lists through their `buttons` / `buttonHeight` / `update` fields).
|
||||
--
|
||||
-- Implementation differences from the modern source:
|
||||
-- - Addon panels only. Vanilla's own options stay in UIOptionsFrame and
|
||||
-- friends; the Categories list exists (empty, hidden) for code that
|
||||
-- expects it.
|
||||
-- - Panel protocol as on later clients: panel.name (required), panel.parent
|
||||
-- (name of the category to nest under), and optional okay / cancel /
|
||||
-- default / refresh, each called with the panel. Categories with children
|
||||
-- start collapsed. Okay and Cancel call okay / cancel on every panel;
|
||||
-- Defaults calls default on the one shown; Escape is Cancel.
|
||||
-- - The game-menu entry is an extra AddOn Options button: the client's own
|
||||
-- options keep their buttons, so the addon list gets one of its own.
|
||||
-- Not "AddOns" - on later clients that button opens the addon list.
|
||||
-- - Lua 5.0: no `...` expression or select().
|
||||
|
||||
if InterfaceOptionsFrame then return end -- a real implementation wins
|
||||
|
||||
INTERFACEOPTIONS_ADDONCATEGORIES = INTERFACEOPTIONS_ADDONCATEGORIES or {}
|
||||
local categories = INTERFACEOPTIONS_ADDONCATEGORIES
|
||||
|
||||
local BUTTON_HEIGHT = 18
|
||||
local NUM_BUTTONS = 24
|
||||
|
||||
local function report(err)
|
||||
local handler = geterrorhandler and geterrorhandler()
|
||||
if handler then handler(err) end
|
||||
end
|
||||
|
||||
local LIST_BACKDROP = {
|
||||
bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
|
||||
edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
|
||||
tile = true, tileSize = 16, edgeSize = 16,
|
||||
insets = { left = 5, right = 5, top = 5, bottom = 5 },
|
||||
}
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Frame
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
local frame = CreateFrame("Frame", "InterfaceOptionsFrame", UIParent)
|
||||
frame:Hide()
|
||||
frame:SetWidth(648)
|
||||
frame:SetHeight(568)
|
||||
frame:SetPoint("CENTER", UIParent, "CENTER", 0, 0)
|
||||
frame:SetFrameStrata("DIALOG")
|
||||
frame:SetToplevel(true)
|
||||
frame:EnableMouse(true)
|
||||
frame:SetMovable(true)
|
||||
frame:SetClampedToScreen(true)
|
||||
|
||||
-- The background is the frame's first region: addons re-tint it through
|
||||
-- InterfaceOptionsFrame:GetRegions().
|
||||
local background = frame:CreateTexture(nil, "BACKGROUND")
|
||||
background:SetTexture("Interface\\DialogFrame\\UI-DialogBox-Background")
|
||||
background:SetPoint("TOPLEFT", frame, "TOPLEFT", 11, -12)
|
||||
background:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -12, 11)
|
||||
frame:SetBackdrop({
|
||||
edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border",
|
||||
edgeSize = 32,
|
||||
insets = { left = 11, right = 12, top = 12, bottom = 11 },
|
||||
})
|
||||
|
||||
local header = frame:CreateTexture(nil, "ARTWORK")
|
||||
header:SetTexture("Interface\\DialogFrame\\UI-DialogBox-Header")
|
||||
header:SetWidth(360)
|
||||
header:SetHeight(64)
|
||||
header:SetPoint("TOP", frame, "TOP", 0, 12)
|
||||
local title = frame:CreateFontString(nil, "ARTWORK", "GameFontNormal")
|
||||
title:SetPoint("TOP", header, "TOP", 0, -14)
|
||||
title:SetText(ADDON_OPTIONS)
|
||||
|
||||
frame:SetScript("OnMouseDown", function()
|
||||
if arg1 == "LeftButton" then this:StartMoving() end
|
||||
end)
|
||||
frame:SetScript("OnMouseUp", function() this:StopMovingOrSizing() end)
|
||||
|
||||
-- A native center panel, as on later clients: ShowUIPanel swaps it with the
|
||||
-- game menu, CloseAllWindows closes it, and closing returns to lastFrame.
|
||||
UIPanelWindows["InterfaceOptionsFrame"] = { area = "center", pushable = 0, whileDead = 1 }
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Category lists and the panel container
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
local function CreateList(name)
|
||||
local list = CreateFrame("Frame", name, frame)
|
||||
list:SetWidth(185)
|
||||
list:SetPoint("TOPLEFT", frame, "TOPLEFT", 22, -40)
|
||||
list:SetPoint("BOTTOMLEFT", frame, "BOTTOMLEFT", 22, 50)
|
||||
list:SetBackdrop(LIST_BACKDROP)
|
||||
list:SetBackdropColor(0, 0, 0, 0.5)
|
||||
list:SetBackdropBorderColor(0.6, 0.6, 0.6)
|
||||
list.buttonHeight = BUTTON_HEIGHT
|
||||
list.buttons = {}
|
||||
for i = 1, NUM_BUTTONS do
|
||||
local button = CreateFrame("Button", name .. "Button" .. i, list, "InterfaceOptionsListButtonTemplate")
|
||||
if i == 1 then
|
||||
button:SetPoint("TOPLEFT", list, "TOPLEFT", 5, -8)
|
||||
else
|
||||
button:SetPoint("TOPLEFT", list.buttons[i - 1], "BOTTOMLEFT", 0, 0)
|
||||
end
|
||||
button:Hide()
|
||||
list.buttons[i] = button
|
||||
end
|
||||
return list
|
||||
end
|
||||
|
||||
-- Vanilla keeps its own options elsewhere; this list stays empty.
|
||||
local gameList = CreateList("InterfaceOptionsFrameCategories")
|
||||
gameList.update = function() end
|
||||
gameList:Hide()
|
||||
|
||||
local addOnList = CreateList("InterfaceOptionsFrameAddOns")
|
||||
|
||||
local scroll = CreateFrame("ScrollFrame", "InterfaceOptionsFrameAddOnsList", addOnList, "FauxScrollFrameTemplate")
|
||||
scroll:SetPoint("TOPLEFT", addOnList, "TOPLEFT", 0, -8)
|
||||
scroll:SetPoint("BOTTOMRIGHT", addOnList, "BOTTOMRIGHT", -30, 8)
|
||||
|
||||
local container = CreateFrame("Frame", "InterfaceOptionsFramePanelContainer", frame)
|
||||
container:SetPoint("TOPLEFT", addOnList, "TOPRIGHT", 16, 0)
|
||||
container:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -22, 50)
|
||||
container:SetBackdrop(LIST_BACKDROP)
|
||||
container:SetBackdropColor(0, 0, 0, 0.5)
|
||||
container:SetBackdropBorderColor(0.6, 0.6, 0.6)
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Categories
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
local function FindCategory(name)
|
||||
for _, panel in ipairs(categories) do
|
||||
if panel.name == name then return panel end
|
||||
end
|
||||
end
|
||||
|
||||
local function HasChildren(panel)
|
||||
for _, p in ipairs(categories) do
|
||||
if p.parent == panel.name then return true end
|
||||
end
|
||||
end
|
||||
|
||||
-- Top-level categories in order, each followed by its children when expanded.
|
||||
-- A child whose parent is not registered is listed at the top level.
|
||||
local function VisibleCategories()
|
||||
local out = {}
|
||||
for _, panel in ipairs(categories) do
|
||||
if not panel.parent or not FindCategory(panel.parent) then
|
||||
table.insert(out, panel)
|
||||
if not panel.collapsed then
|
||||
for _, child in ipairs(categories) do
|
||||
if child.parent == panel.name then table.insert(out, child) end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
function InterfaceAddOnsList_Update()
|
||||
local entries = VisibleCategories()
|
||||
local offset = FauxScrollFrame_GetOffset(scroll) or 0
|
||||
local numButtons = table.getn(addOnList.buttons)
|
||||
for i = 1, numButtons do
|
||||
local button = addOnList.buttons[i]
|
||||
local panel = entries[i + offset]
|
||||
local text = getglobal(button:GetName() .. "Text")
|
||||
local toggle = getglobal(button:GetName() .. "Toggle")
|
||||
if panel then
|
||||
button.element = panel
|
||||
text:SetText(panel.name)
|
||||
local isChild = panel.parent and FindCategory(panel.parent)
|
||||
text:SetFontObject(isChild and GameFontHighlightSmall or GameFontNormal)
|
||||
text:ClearAllPoints()
|
||||
text:SetPoint("LEFT", button, "LEFT", isChild and 20 or 8, 0)
|
||||
if toggle then
|
||||
if HasChildren(panel) then
|
||||
local tex = panel.collapsed and "Plus" or "Minus"
|
||||
toggle:SetNormalTexture("Interface\\Buttons\\UI-" .. tex .. "Button-UP")
|
||||
toggle:SetPushedTexture("Interface\\Buttons\\UI-" .. tex .. "Button-DOWN")
|
||||
toggle:Show()
|
||||
else
|
||||
toggle:Hide()
|
||||
end
|
||||
end
|
||||
if panel == container.displayedPanel then button:LockHighlight() else button:UnlockHighlight() end
|
||||
button:Show()
|
||||
else
|
||||
button.element = nil
|
||||
button:UnlockHighlight()
|
||||
button:Hide()
|
||||
end
|
||||
end
|
||||
FauxScrollFrame_Update(scroll, table.getn(entries), numButtons, BUTTON_HEIGHT)
|
||||
end
|
||||
addOnList.update = InterfaceAddOnsList_Update
|
||||
|
||||
scroll:SetScript("OnVerticalScroll", function()
|
||||
FauxScrollFrame_OnVerticalScroll(BUTTON_HEIGHT, InterfaceAddOnsList_Update)
|
||||
end)
|
||||
|
||||
-- The shown panel lives in container.displayedPanel, as on later clients:
|
||||
-- addons read it there.
|
||||
local function DisplayPanel(panel)
|
||||
local shown = container.displayedPanel
|
||||
if shown and shown ~= panel then shown:Hide() end
|
||||
container.displayedPanel = panel
|
||||
panel:SetParent(container)
|
||||
panel:ClearAllPoints()
|
||||
panel:SetPoint("TOPLEFT", container, "TOPLEFT", 4, -4)
|
||||
panel:SetPoint("BOTTOMRIGHT", container, "BOTTOMRIGHT", -4, 4)
|
||||
panel:Show()
|
||||
if type(panel.refresh) == "function" then
|
||||
local ok, err = pcall(panel.refresh, panel)
|
||||
if not ok then report(err) end
|
||||
end
|
||||
InterfaceAddOnsList_Update()
|
||||
end
|
||||
|
||||
function InterfaceOptionsListButton_OnClick(button)
|
||||
if button and button.element then DisplayPanel(button.element) end
|
||||
end
|
||||
|
||||
function InterfaceOptionsListButton_ToggleSubCategories(button)
|
||||
local panel = button and button.element
|
||||
if not panel then return end
|
||||
panel.collapsed = not panel.collapsed
|
||||
InterfaceAddOnsList_Update()
|
||||
end
|
||||
|
||||
function InterfaceOptions_AddCategory(panel, addOn, position)
|
||||
if type(panel) ~= "table" or type(panel.name) ~= "string" then
|
||||
error("Usage: InterfaceOptions_AddCategory(panel [, addOn, position])", 2)
|
||||
end
|
||||
panel:Hide()
|
||||
if panel.parent then
|
||||
local parent = FindCategory(panel.parent)
|
||||
if parent and parent.collapsed == nil then parent.collapsed = true end
|
||||
end
|
||||
if position and position >= 1 and position <= table.getn(categories) + 1 then
|
||||
table.insert(categories, position, panel)
|
||||
else
|
||||
table.insert(categories, panel)
|
||||
end
|
||||
if panel.collapsed == nil and HasChildren(panel) then panel.collapsed = true end
|
||||
if frame:IsShown() then InterfaceAddOnsList_Update() end
|
||||
end
|
||||
|
||||
function InterfaceOptionsFrame_OpenToCategory(panel)
|
||||
if type(panel) == "string" then panel = FindCategory(panel) end
|
||||
if type(panel) ~= "table" then return end
|
||||
local p = panel
|
||||
while p and p.parent do
|
||||
local parent = FindCategory(p.parent)
|
||||
if parent then parent.collapsed = false end
|
||||
p = parent
|
||||
end
|
||||
ShowUIPanel(frame)
|
||||
DisplayPanel(panel)
|
||||
end
|
||||
|
||||
function InterfaceOptionsFrame_Show()
|
||||
if frame:IsShown() then HideUIPanel(frame) else ShowUIPanel(frame) end
|
||||
end
|
||||
|
||||
frame:SetScript("OnShow", function()
|
||||
if not container.displayedPanel and categories[1] then
|
||||
DisplayPanel(categories[1])
|
||||
else
|
||||
InterfaceAddOnsList_Update()
|
||||
end
|
||||
end)
|
||||
|
||||
frame:SetScript("OnHide", function()
|
||||
if this.lastFrame then
|
||||
ShowUIPanel(this.lastFrame)
|
||||
this.lastFrame = nil
|
||||
end
|
||||
end)
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Okay / Cancel / Defaults
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
local function CallAll(method)
|
||||
for _, panel in ipairs(categories) do
|
||||
local fn = panel[method]
|
||||
if type(fn) == "function" then
|
||||
local ok, err = pcall(fn, panel)
|
||||
if not ok then report(err) end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function PanelButton(name, label, point, x)
|
||||
local b = CreateFrame("Button", name, frame, "UIPanelButtonTemplate")
|
||||
b:SetWidth(96)
|
||||
b:SetHeight(22)
|
||||
b:SetPoint(point, frame, point, x, 16)
|
||||
b:SetText(label)
|
||||
return b
|
||||
end
|
||||
|
||||
PanelButton("InterfaceOptionsFrameCancel", CANCEL, "BOTTOMRIGHT", -16):SetScript("OnClick", function()
|
||||
CallAll("cancel")
|
||||
HideUIPanel(frame)
|
||||
end)
|
||||
PanelButton("InterfaceOptionsFrameOkay", OKAY, "BOTTOMRIGHT", -114):SetScript("OnClick", function()
|
||||
CallAll("okay")
|
||||
HideUIPanel(frame)
|
||||
end)
|
||||
PanelButton("InterfaceOptionsFrameDefaults", DEFAULTS, "BOTTOMLEFT", 22):SetScript("OnClick", function()
|
||||
local panel = container.displayedPanel
|
||||
if panel and type(panel.default) == "function" then
|
||||
local ok, err = pcall(panel.default, panel)
|
||||
if not ok then report(err) end
|
||||
end
|
||||
end)
|
||||
|
||||
-- Escape is Cancel, as on later clients: their ToggleGameMenu clicks
|
||||
-- InterfaceOptionsFrameCancel right after dismissing a static popup.
|
||||
-- Without this, Escape reaches CloseAllWindows, which closes the window
|
||||
-- without calling any panel's cancel.
|
||||
local ToggleGameMenu_Orig = ToggleGameMenu
|
||||
function ToggleGameMenu(clicked)
|
||||
if not clicked and frame:IsVisible() then
|
||||
if not StaticPopup_EscapePressed() then InterfaceOptionsFrameCancel:Click() end
|
||||
return
|
||||
end
|
||||
ToggleGameMenu_Orig(clicked)
|
||||
end
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Game menu entry
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
-- Goes right above Key Bindings. Stock anchors Key Bindings under Interface
|
||||
-- Options and Turtle under its single Options button, so the new button takes
|
||||
-- over whatever anchor Key Bindings has and Key Bindings moves under it.
|
||||
--
|
||||
-- The splice waits for the menu's first show. Other addons insert their own
|
||||
-- buttons the same way -- ShaguTweaks anchors "Advanced Options" under
|
||||
-- Interface Options and moves Key Bindings under it -- and they load after
|
||||
-- us. Splicing at load time would claim the slot first, and the later addon
|
||||
-- would anchor its button on the same spot as ours. By the first show every
|
||||
-- addon has placed its buttons, so ours goes into the chain as it stands.
|
||||
local menuButton = CreateFrame("Button", "GameMenuButtonAddOnOptions", GameMenuFrame, "GameMenuButtonTemplate")
|
||||
menuButton:SetText(ADDON_OPTIONS)
|
||||
local spliced
|
||||
GameMenuFrame:HookScript("OnShow", function()
|
||||
if spliced then return end
|
||||
spliced = true
|
||||
local point, relativeTo, relativePoint, x, y = GameMenuButtonKeybindings:GetPoint()
|
||||
menuButton:SetPoint(point, relativeTo, relativePoint, x, y)
|
||||
GameMenuButtonKeybindings:ClearAllPoints()
|
||||
GameMenuButtonKeybindings:SetPoint(point, menuButton, relativePoint, x, y)
|
||||
GameMenuFrame:SetHeight(GameMenuFrame:GetHeight() + menuButton:GetHeight() - y)
|
||||
end)
|
||||
menuButton:SetScript("OnClick", function()
|
||||
PlaySound("igMainMenuOption")
|
||||
ShowUIPanel(frame)
|
||||
frame.lastFrame = GameMenuFrame
|
||||
end)
|
||||
@@ -0,0 +1,63 @@
|
||||
<Ui xmlns="http://www.blizzard.com/wow/ui/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.blizzard.com/wow/ui/ ..\FrameXML\UI.xsd">
|
||||
<!-- One row of the Interface Options category list (see InterfaceOptions.lua).
|
||||
Named as on later clients: addons and libraries create extra rows from it
|
||||
by name (LibBetterBlizzOptions-1.0). Handlers use vanilla's this/arg1. -->
|
||||
<Button name="InterfaceOptionsListButtonTemplate" virtual="true">
|
||||
<Size>
|
||||
<AbsDimension x="175" y="18"/>
|
||||
</Size>
|
||||
<Layers>
|
||||
<Layer level="OVERLAY">
|
||||
<FontString name="$parentText" inherits="GameFontNormal" justifyH="LEFT">
|
||||
<Size>
|
||||
<AbsDimension x="150" y="18"/>
|
||||
</Size>
|
||||
<Anchors>
|
||||
<Anchor point="LEFT">
|
||||
<Offset>
|
||||
<AbsDimension x="8" y="0"/>
|
||||
</Offset>
|
||||
</Anchor>
|
||||
</Anchors>
|
||||
</FontString>
|
||||
</Layer>
|
||||
</Layers>
|
||||
<Frames>
|
||||
<Button name="$parentToggle" hidden="true">
|
||||
<Size>
|
||||
<AbsDimension x="14" y="14"/>
|
||||
</Size>
|
||||
<Anchors>
|
||||
<Anchor point="RIGHT">
|
||||
<Offset>
|
||||
<AbsDimension x="-6" y="0"/>
|
||||
</Offset>
|
||||
</Anchor>
|
||||
</Anchors>
|
||||
<Scripts>
|
||||
<OnClick>InterfaceOptionsListButton_ToggleSubCategories(this:GetParent())</OnClick>
|
||||
</Scripts>
|
||||
<NormalTexture file="Interface\Buttons\UI-PlusButton-UP"/>
|
||||
<PushedTexture file="Interface\Buttons\UI-PlusButton-DOWN"/>
|
||||
<HighlightTexture file="Interface\Buttons\UI-PlusButton-Hilight" alphaMode="ADD"/>
|
||||
</Button>
|
||||
</Frames>
|
||||
<Scripts>
|
||||
<OnClick>InterfaceOptionsListButton_OnClick(this)</OnClick>
|
||||
</Scripts>
|
||||
<HighlightTexture file="Interface\QuestFrame\UI-QuestTitleHighlight" alphaMode="ADD">
|
||||
<Anchors>
|
||||
<Anchor point="TOPLEFT">
|
||||
<Offset>
|
||||
<AbsDimension x="0" y="1"/>
|
||||
</Offset>
|
||||
</Anchor>
|
||||
<Anchor point="BOTTOMRIGHT">
|
||||
<Offset>
|
||||
<AbsDimension x="0" y="1"/>
|
||||
</Offset>
|
||||
</Anchor>
|
||||
</Anchors>
|
||||
</HighlightTexture>
|
||||
</Button>
|
||||
</Ui>
|
||||
@@ -0,0 +1,337 @@
|
||||
-- ClassicAPI's own entry in the AddOn Options window
|
||||
-- (FrameXML\InterfaceOptions.lua): a ClassicAPI page with Controls, Combat
|
||||
-- and Text To Speech pages under it.
|
||||
--
|
||||
-- Where retail's Settings shows a setting, the option copies its label,
|
||||
-- tooltip and value mapping (Blizzard_SettingsDefinitions_Frame: Controls,
|
||||
-- Combat, Accessibility; the TTS options use the Text To Speech window's
|
||||
-- labels). Retail has no labels for the player cache, the cast settings or
|
||||
-- friendly soft targeting, so those strings are ClassicAPI's own.
|
||||
--
|
||||
-- Changes apply at once. Cancel (and Escape) restores what each page held
|
||||
-- when it was first shown since the last Okay or Cancel; Defaults restores
|
||||
-- the shown page's defaults.
|
||||
--
|
||||
-- Lua 5.0: no `...` expression or select().
|
||||
|
||||
local L = {
|
||||
ABOUT = "Settings for the features that ClassicAPI adds to the game.",
|
||||
PLAYER_CACHE = "Player Cache",
|
||||
REMEMBER_PLAYERS = "Remember players",
|
||||
REMEMBER_PLAYERS_TOOLTIP = "Saves the name, class, race and sex of the players you meet, so addons can show them in later sessions. All your characters on this realm share the data.",
|
||||
SCAN_PLAYERS = "Scan nearby players",
|
||||
SCAN_PLAYERS_TOOLTIP = "Every 10 seconds, adds all the players near you to the player cache. Needs Remember players.",
|
||||
FRIEND_TARGETING = "Enable Friendly Action Targeting",
|
||||
FRIEND_TARGETING_TOOLTIP = "Picks the nearest friendly unit where you are looking. When you have no target, your helpful spells go to it.",
|
||||
AUTO_STAND = "Auto Stand",
|
||||
AUTO_STAND_TOOLTIP = "Stand up when you cast a spell while you sit.",
|
||||
AUTO_DISMOUNT = "Auto Dismount",
|
||||
AUTO_DISMOUNT_TOOLTIP = "Dismount when you cast a spell while you are mounted.",
|
||||
AUTO_UNSHIFT = "Auto Cancel Form",
|
||||
AUTO_UNSHIFT_TOOLTIP = "Leave your form when you cast a spell that you cannot cast in it.",
|
||||
}
|
||||
|
||||
-- Enum.SoftTargetEnableFlags: retail's checkboxes switch between Any (on)
|
||||
-- and Gamepad (off).
|
||||
local SOFT_TARGET_GAMEPAD, SOFT_TARGET_ANY = 1, 3
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Settings: get / set / reset over cvars or the player cache
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
local function ResetCVars(cvars)
|
||||
for _, cvar in ipairs(cvars) do
|
||||
SetCVar(cvar, GetCVarDefault(cvar))
|
||||
end
|
||||
end
|
||||
|
||||
local function CVarSetting(cvar)
|
||||
return {
|
||||
get = function() return GetCVar(cvar) == "1" end,
|
||||
set = function(value) SetCVar(cvar, value and "1" or "0") end,
|
||||
reset = function() ResetCVars({ cvar }) end,
|
||||
}
|
||||
end
|
||||
|
||||
local function NumberCVarSetting(cvar)
|
||||
return {
|
||||
get = function() return tonumber(GetCVar(cvar)) end,
|
||||
set = function(value) SetCVar(cvar, tostring(value)) end,
|
||||
reset = function() ResetCVars({ cvar }) end,
|
||||
}
|
||||
end
|
||||
|
||||
-- Retail's "Enable Interact Key" / "Enable Action Targeting" proxies.
|
||||
local function SoftTargetSetting(cvar)
|
||||
return {
|
||||
get = function() return tonumber(GetCVar(cvar)) == SOFT_TARGET_ANY end,
|
||||
set = function(value) SetCVar(cvar, tostring(value and SOFT_TARGET_ANY or SOFT_TARGET_GAMEPAD)) end,
|
||||
reset = function() ResetCVars({ cvar }) end,
|
||||
}
|
||||
end
|
||||
|
||||
-- Retail's "Interact Key Icons" proxy: 1 = NPCs only, 2 = all, 3 = none.
|
||||
local ICON_CVARS = { "SoftTargetIconEnemy", "SoftTargetIconInteract", "SoftTargetIconGameObject", "SoftTargetLowPriorityIcons" }
|
||||
local ICON_PRESETS = {
|
||||
[1] = { "0", "1", "0", "0" },
|
||||
[2] = { "1", "1", "1", "1" },
|
||||
[3] = { "0", "0", "0", "0" },
|
||||
}
|
||||
local interactIconsSetting = {
|
||||
get = function()
|
||||
local on, off = true, true
|
||||
for _, cvar in ipairs(ICON_CVARS) do
|
||||
if GetCVar(cvar) == "1" then off = false else on = false end
|
||||
end
|
||||
if on then return 2 elseif off then return 3 else return 1 end
|
||||
end,
|
||||
set = function(value)
|
||||
for i, cvar in ipairs(ICON_CVARS) do
|
||||
SetCVar(cvar, ICON_PRESETS[value][i])
|
||||
end
|
||||
end,
|
||||
reset = function() ResetCVars(ICON_CVARS) end,
|
||||
}
|
||||
|
||||
local function PlayerCacheSetting(isEnabled, setEnabled)
|
||||
return {
|
||||
get = function() return isEnabled() and true or false end,
|
||||
set = function(value) setEnabled(value) end,
|
||||
reset = function() setEnabled(false) end,
|
||||
}
|
||||
end
|
||||
|
||||
local rememberSetting = PlayerCacheSetting(C_PlayerCache.IsEnabled, C_PlayerCache.SetEnabled)
|
||||
local scanSetting = PlayerCacheSetting(C_PlayerCache.IsScanEnabled, C_PlayerCache.SetScanEnabled)
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Pages
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
local numControls = 0
|
||||
local function NextName()
|
||||
numControls = numControls + 1
|
||||
return "ClassicAPIOptionsControl" .. numControls
|
||||
end
|
||||
|
||||
local function RefreshControls(page)
|
||||
page.updating = true
|
||||
for _, control in ipairs(page.controls) do
|
||||
control:Update()
|
||||
end
|
||||
page.updating = nil
|
||||
end
|
||||
|
||||
local function NewPage(name, parent, title, subtitle)
|
||||
local page = CreateFrame("Frame")
|
||||
page.name = name
|
||||
page.parent = parent
|
||||
page.controls = {}
|
||||
|
||||
local heading = page:CreateFontString(nil, "ARTWORK", "GameFontNormalLarge")
|
||||
heading:SetPoint("TOPLEFT", page, "TOPLEFT", 16, -16)
|
||||
heading:SetText(title)
|
||||
page.y = -40
|
||||
if subtitle then
|
||||
local text = page:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall")
|
||||
text:SetPoint("TOPLEFT", heading, "BOTTOMLEFT", 0, -8)
|
||||
text:SetPoint("RIGHT", page, "RIGHT", -32, 0)
|
||||
text:SetJustifyH("LEFT")
|
||||
text:SetText(subtitle)
|
||||
page.y = -64
|
||||
end
|
||||
|
||||
page.refresh = function()
|
||||
if not page.saved then
|
||||
page.saved = {}
|
||||
for i, control in ipairs(page.controls) do
|
||||
page.saved[i] = control.setting.get()
|
||||
end
|
||||
end
|
||||
RefreshControls(page)
|
||||
end
|
||||
page.okay = function()
|
||||
page.saved = nil
|
||||
end
|
||||
page.cancel = function()
|
||||
if not page.saved then return end
|
||||
for i, control in ipairs(page.controls) do
|
||||
if control.setting.get() ~= page.saved[i] then
|
||||
control.setting.set(page.saved[i])
|
||||
end
|
||||
end
|
||||
page.saved = nil
|
||||
end
|
||||
page.default = function()
|
||||
for _, control in ipairs(page.controls) do
|
||||
control.setting.reset()
|
||||
end
|
||||
RefreshControls(page)
|
||||
end
|
||||
|
||||
InterfaceOptions_AddCategory(page)
|
||||
return page
|
||||
end
|
||||
|
||||
local function AddControl(page, control, setting, height)
|
||||
control.setting = setting
|
||||
table.insert(page.controls, control)
|
||||
page.y = page.y - height
|
||||
end
|
||||
|
||||
local function AddHeader(page, text)
|
||||
local header = page:CreateFontString(nil, "ARTWORK", "GameFontNormal")
|
||||
header:SetPoint("TOPLEFT", page, "TOPLEFT", 16, page.y - 8)
|
||||
header:SetText(text)
|
||||
page.y = page.y - 28
|
||||
end
|
||||
|
||||
-- `enabledIf`, when given, greys the checkbox out while it returns false.
|
||||
local function AddCheckbox(page, label, tooltip, setting, enabledIf)
|
||||
local check = CreateFrame("CheckButton", NextName(), page, "OptionsCheckButtonTemplate")
|
||||
check:SetPoint("TOPLEFT", page, "TOPLEFT", 16, page.y)
|
||||
local text = getglobal(check:GetName() .. "Text")
|
||||
text:SetText(label)
|
||||
check.tooltipText = tooltip
|
||||
check:SetScript("OnClick", function()
|
||||
this.setting.set(this:GetChecked() and true or false)
|
||||
RefreshControls(page)
|
||||
end)
|
||||
check.Update = function(self)
|
||||
self:SetChecked(self.setting.get())
|
||||
if not enabledIf or enabledIf() then
|
||||
self:Enable()
|
||||
text:SetTextColor(NORMAL_FONT_COLOR.r, NORMAL_FONT_COLOR.g, NORMAL_FONT_COLOR.b)
|
||||
else
|
||||
self:Disable()
|
||||
text:SetTextColor(GRAY_FONT_COLOR.r, GRAY_FONT_COLOR.g, GRAY_FONT_COLOR.b)
|
||||
end
|
||||
end
|
||||
AddControl(page, check, setting, 30)
|
||||
return check
|
||||
end
|
||||
|
||||
-- `options()` returns the entries as { value = ..., text = ... }.
|
||||
local function AddDropDown(page, label, tooltip, setting, options)
|
||||
local title = page:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall")
|
||||
title:SetPoint("TOPLEFT", page, "TOPLEFT", 20, page.y - 6)
|
||||
title:SetText(label)
|
||||
|
||||
local dropdown = CreateFrame("Frame", NextName(), page, "UIDropDownMenuTemplate")
|
||||
dropdown:SetPoint("TOPLEFT", page, "TOPLEFT", 0, page.y - 20)
|
||||
UIDropDownMenu_SetWidth(180, dropdown)
|
||||
dropdown:EnableMouse(true)
|
||||
dropdown:SetScript("OnEnter", function()
|
||||
GameTooltip:SetOwner(this, "ANCHOR_RIGHT")
|
||||
GameTooltip:SetText(tooltip, nil, nil, nil, nil, 1)
|
||||
end)
|
||||
dropdown:SetScript("OnLeave", function() GameTooltip:Hide() end)
|
||||
|
||||
local function Initialize()
|
||||
local selected = setting.get()
|
||||
for _, option in ipairs(options()) do
|
||||
local info = {}
|
||||
info.text = option.text
|
||||
info.value = option.value
|
||||
info.checked = option.value == selected and 1 or nil
|
||||
info.func = function()
|
||||
UIDropDownMenu_SetSelectedValue(dropdown, this.value)
|
||||
setting.set(this.value)
|
||||
end
|
||||
UIDropDownMenu_AddButton(info)
|
||||
end
|
||||
end
|
||||
dropdown.Update = function(self)
|
||||
UIDropDownMenu_Initialize(self, Initialize)
|
||||
UIDropDownMenu_SetSelectedValue(self, setting.get())
|
||||
end
|
||||
AddControl(page, dropdown, setting, 56)
|
||||
return dropdown
|
||||
end
|
||||
|
||||
local function AddSlider(page, label, tooltip, setting, minValue, maxValue)
|
||||
local slider = CreateFrame("Slider", NextName(), page, "OptionsSliderTemplate")
|
||||
slider:SetPoint("TOPLEFT", page, "TOPLEFT", 24, page.y - 20)
|
||||
slider:SetWidth(200)
|
||||
slider:SetMinMaxValues(minValue, maxValue)
|
||||
slider:SetValueStep(1)
|
||||
slider.tooltipText = tooltip
|
||||
getglobal(slider:GetName() .. "Text"):SetText(label)
|
||||
getglobal(slider:GetName() .. "Low"):SetText(minValue)
|
||||
getglobal(slider:GetName() .. "High"):SetText(maxValue)
|
||||
|
||||
local value = slider:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall")
|
||||
value:SetPoint("LEFT", slider, "RIGHT", 8, 0)
|
||||
|
||||
slider:SetScript("OnValueChanged", function()
|
||||
local v = math.floor(this:GetValue() + 0.5)
|
||||
value:SetText(v)
|
||||
if not page.updating and v ~= setting.get() then
|
||||
setting.set(v)
|
||||
end
|
||||
end)
|
||||
slider.Update = function(self)
|
||||
local v = setting.get()
|
||||
self:SetValue(v)
|
||||
value:SetText(v)
|
||||
end
|
||||
AddControl(page, slider, setting, 56)
|
||||
return slider
|
||||
end
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- ClassicAPI
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
local version = GetAddOnMetadata("!!!ClassicAPI", "Version")
|
||||
local main = NewPage("ClassicAPI", nil, "ClassicAPI " .. version, L.ABOUT)
|
||||
|
||||
AddHeader(main, L.PLAYER_CACHE)
|
||||
AddCheckbox(main, L.REMEMBER_PLAYERS, L.REMEMBER_PLAYERS_TOOLTIP, rememberSetting)
|
||||
AddCheckbox(main, L.SCAN_PLAYERS, L.SCAN_PLAYERS_TOOLTIP, scanSetting, rememberSetting.get)
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Controls
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
local controls = NewPage(CONTROLS_LABEL, main.name, CONTROLS_LABEL)
|
||||
|
||||
AddCheckbox(controls, ENABLE_INTERACT_TEXT, OPTION_TOOLTIP_ENABLE_INTERACT, SoftTargetSetting("SoftTargetInteract"))
|
||||
AddDropDown(controls, INTERACT_ICONS_OPTION, OPTION_TOOLTIP_INTERACT_ICONS, interactIconsSetting, function()
|
||||
return {
|
||||
{ value = 1, text = INTERACT_ICONS_DEFAULT },
|
||||
{ value = 2, text = INTERACT_ICONS_SHOW_ALL },
|
||||
{ value = 3, text = INTERACT_ICONS_SHOW_NONE },
|
||||
}
|
||||
end)
|
||||
AddCheckbox(controls, L.AUTO_STAND, L.AUTO_STAND_TOOLTIP, CVarSetting("autoStand"))
|
||||
AddCheckbox(controls, L.AUTO_DISMOUNT, L.AUTO_DISMOUNT_TOOLTIP, CVarSetting("autoDismount"))
|
||||
AddCheckbox(controls, L.AUTO_UNSHIFT, L.AUTO_UNSHIFT_TOOLTIP, CVarSetting("autoUnshift"))
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Combat
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
local combat = NewPage(COMBAT_LABEL, main.name, COMBAT_LABEL)
|
||||
|
||||
AddCheckbox(combat, ACTION_TARGETING_OPTION, OPTION_TOOLTIP_ACTION_TARGETING, SoftTargetSetting("SoftTargetEnemy"))
|
||||
-- Retail has no friend checkbox; same mapping as its enemy one.
|
||||
AddCheckbox(combat, L.FRIEND_TARGETING, L.FRIEND_TARGETING_TOOLTIP, SoftTargetSetting("SoftTargetFriend"))
|
||||
AddCheckbox(combat, ACTION_BUTTON_USE_KEY_DOWN, OPTION_TOOLTIP_ACTION_BUTTON_USE_KEY_DOWN, CVarSetting("ActionButtonUseKeyDown"))
|
||||
AddCheckbox(combat, STOP_AUTO_ATTACK, OPTION_TOOLTIP_STOP_AUTO_ATTACK, CVarSetting("stopAutoAttackOnTargetChange"))
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Text To Speech
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
local tts = NewPage(TEXT_TO_SPEECH, main.name, TEXT_TO_SPEECH)
|
||||
|
||||
AddDropDown(tts, TEXT_TO_SPEECH_VOICE_OPTION, TEXT_TO_SPEECH_VOICE_OPTION, NumberCVarSetting("ttsVoice"), function()
|
||||
local options = {}
|
||||
for _, voice in ipairs(C_VoiceChat.GetTtsVoices()) do
|
||||
table.insert(options, { value = voice.voiceID, text = voice.name })
|
||||
end
|
||||
return options
|
||||
end)
|
||||
AddSlider(tts, TEXT_TO_SPEECH_ADJUST_RATE, TEXT_TO_SPEECH_ADJUST_RATE, NumberCVarSetting("ttsSpeed"), -10, 10)
|
||||
AddSlider(tts, TEXT_TO_SPEECH_ADJUST_VOLUME, TEXT_TO_SPEECH_ADJUST_VOLUME, NumberCVarSetting("ttsVolume"), 0, 100)
|
||||
@@ -0,0 +1,98 @@
|
||||
-- ActionButtonUseKeyDown: action-bar key bindings act on the key press when
|
||||
-- the cvar is set, on the release otherwise -- 4.3.4's FrameXML handlers
|
||||
-- (ActionButton.lua, MultiActionBars.lua, PetActionBarFrame.lua). Each keeps
|
||||
-- 1.12's own body; 4.3.4 adds only the cvar test: the press always shows the
|
||||
-- button pushed and acts when the cvar is set, the release shows it normal
|
||||
-- and acts when it is not. The engine registers the cvar (default 0, so the
|
||||
-- release stays the default).
|
||||
|
||||
local GetCVarBool = ClassicAPI.C_CVar.GetCVarBool;
|
||||
|
||||
local function UseKeyDown()
|
||||
return GetCVarBool("ActionButtonUseKeyDown");
|
||||
end
|
||||
|
||||
-- 1.12's ActionButtonUp / MultiActionButtonUp body.
|
||||
local function UseActionButton(button, onSelf)
|
||||
if ( MacroFrame_SaveMacro ) then
|
||||
MacroFrame_SaveMacro();
|
||||
end
|
||||
UseAction(ActionButton_GetPagedID(button), 0, onSelf);
|
||||
if ( IsCurrentAction(ActionButton_GetPagedID(button)) ) then
|
||||
button:SetChecked(1);
|
||||
else
|
||||
button:SetChecked(0);
|
||||
end
|
||||
end
|
||||
|
||||
local function MainBarButton(id)
|
||||
if ( BonusActionBarFrame:IsShown() ) then
|
||||
return getglobal("BonusActionButton"..id), true;
|
||||
end
|
||||
return getglobal("ActionButton"..id), false;
|
||||
end
|
||||
|
||||
function ActionButtonDown(id)
|
||||
local button = MainBarButton(id);
|
||||
if ( button:GetButtonState() == "NORMAL" ) then
|
||||
button:SetButtonState("PUSHED");
|
||||
end
|
||||
if ( UseKeyDown() ) then
|
||||
UseActionButton(button);
|
||||
end
|
||||
end
|
||||
|
||||
function ActionButtonUp(id, onSelf)
|
||||
local button, bonus = MainBarButton(id);
|
||||
if ( button:GetButtonState() == "PUSHED" ) then
|
||||
button:SetButtonState("NORMAL");
|
||||
if ( not UseKeyDown() ) then
|
||||
-- 1.12's bonus-bar branch uses the action without onSelf.
|
||||
if ( bonus ) then
|
||||
UseActionButton(button);
|
||||
else
|
||||
UseActionButton(button, onSelf);
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function MultiActionButtonDown(bar, id)
|
||||
local button = getglobal(bar.."Button"..id);
|
||||
if ( button:GetButtonState() == "NORMAL" ) then
|
||||
button:SetButtonState("PUSHED");
|
||||
end
|
||||
if ( UseKeyDown() ) then
|
||||
UseActionButton(button);
|
||||
end
|
||||
end
|
||||
|
||||
function MultiActionButtonUp(bar, id, onSelf)
|
||||
local button = getglobal(bar.."Button"..id);
|
||||
if ( button:GetButtonState() == "PUSHED" ) then
|
||||
button:SetButtonState("NORMAL");
|
||||
if ( not UseKeyDown() ) then
|
||||
UseActionButton(button, onSelf);
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function PetActionButtonDown(id)
|
||||
local button = getglobal("PetActionButton"..id);
|
||||
if ( button:GetButtonState() == "NORMAL" ) then
|
||||
button:SetButtonState("PUSHED");
|
||||
end
|
||||
if ( UseKeyDown() ) then
|
||||
CastPetAction(id);
|
||||
end
|
||||
end
|
||||
|
||||
function PetActionButtonUp(id)
|
||||
local button = getglobal("PetActionButton"..id);
|
||||
if ( button:GetButtonState() == "PUSHED" ) then
|
||||
button:SetButtonState("NORMAL");
|
||||
if ( not UseKeyDown() ) then
|
||||
CastPetAction(id);
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -127,6 +127,25 @@ if C_AddOns.DoesAddOnExist("LunaUnitFrames") then
|
||||
end)
|
||||
end
|
||||
|
||||
-- Turtle's Options frame sets `GroupFrame_ToggleMovement(state)` as the
|
||||
-- "Toggle Movement" button's OnClick (FrameXML\OptionsFrame.lua), while the
|
||||
-- group dropdown and the addon itself call it directly with 0 or 1. As a
|
||||
-- handler it expects `state` to be nil so it toggles from the current mouse
|
||||
-- state. Given `self` instead, it does `1 - state` on the button and errors
|
||||
-- (Turtle_GroupUI.lua:409). The button is reused and its script re-set on every
|
||||
-- redraw, so wrap the global it reads rather than the frame: only a number
|
||||
-- passes through.
|
||||
if C_AddOns.DoesAddOnExist("Turtle_GroupUI") then
|
||||
EventUtil.ContinueOnAddOnLoaded("Turtle_GroupUI", function()
|
||||
local original = GroupFrame_ToggleMovement
|
||||
if not original then return end
|
||||
GroupFrame_ToggleMovement = function(state)
|
||||
if type(state) ~= "number" then state = nil end
|
||||
return original(state)
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
if C_AddOns.DoesAddOnExist("Puppeteer") then
|
||||
EventUtil.ContinueOnAddOnLoaded("Puppeteer", function()
|
||||
CAPI_MouseoverClearedCompat(PTEnemyUpdater)
|
||||
|
||||
@@ -72,8 +72,9 @@ end
|
||||
-- Returns the AuraData table's fields in the classic `UnitAura` positional order,
|
||||
-- for code written against that shape. Retail appends `unpack(auraData.points)`;
|
||||
-- vanilla auras carry no points, so the tuple ends at timeMod (15 values). Field
|
||||
-- #13 is `isFromPlayerOrPlayerPet` (the table's field) -- note the positional
|
||||
-- C_UnitAuras.UnitAura reports the higher-fidelity `castByPlayer` at #13 instead.
|
||||
-- #13 is `isFromPlayerOrPlayerPet` (the table's field), as retail's UnpackAuraData
|
||||
-- does -- the positional C_UnitAuras.UnitAura reports `castByPlayer` there
|
||||
-- instead, which is false for a pet's aura.
|
||||
function AuraUtil.UnpackAuraData(auraData)
|
||||
if not auraData then
|
||||
return nil;
|
||||
|
||||
@@ -137,4 +137,119 @@ BASE_MOVEMENT_SPEED = 7;
|
||||
UPPER_LEFT_VERTEX = 1;
|
||||
LOWER_LEFT_VERTEX = 2;
|
||||
UPPER_RIGHT_VERTEX = 3;
|
||||
LOWER_RIGHT_VERTEX = 4;
|
||||
LOWER_RIGHT_VERTEX = 4;
|
||||
-- Combat log object flags: sourceFlags / destFlags of COMBAT_LOG_EVENT.
|
||||
COMBATLOG_OBJECT_AFFILIATION_MINE = tonumber("00000001", 16);
|
||||
COMBATLOG_OBJECT_AFFILIATION_PARTY = tonumber("00000002", 16);
|
||||
COMBATLOG_OBJECT_AFFILIATION_RAID = tonumber("00000004", 16);
|
||||
COMBATLOG_OBJECT_AFFILIATION_OUTSIDER = tonumber("00000008", 16);
|
||||
COMBATLOG_OBJECT_AFFILIATION_MASK = tonumber("0000000F", 16);
|
||||
COMBATLOG_OBJECT_REACTION_FRIENDLY = tonumber("00000010", 16);
|
||||
COMBATLOG_OBJECT_REACTION_NEUTRAL = tonumber("00000020", 16);
|
||||
COMBATLOG_OBJECT_REACTION_HOSTILE = tonumber("00000040", 16);
|
||||
COMBATLOG_OBJECT_REACTION_MASK = tonumber("000000F0", 16);
|
||||
COMBATLOG_OBJECT_CONTROL_PLAYER = tonumber("00000100", 16);
|
||||
COMBATLOG_OBJECT_CONTROL_NPC = tonumber("00000200", 16);
|
||||
COMBATLOG_OBJECT_CONTROL_MASK = tonumber("00000300", 16);
|
||||
COMBATLOG_OBJECT_TYPE_PLAYER = tonumber("00000400", 16);
|
||||
COMBATLOG_OBJECT_TYPE_NPC = tonumber("00000800", 16);
|
||||
COMBATLOG_OBJECT_TYPE_PET = tonumber("00001000", 16);
|
||||
COMBATLOG_OBJECT_TYPE_GUARDIAN = tonumber("00002000", 16);
|
||||
COMBATLOG_OBJECT_TYPE_OBJECT = tonumber("00004000", 16);
|
||||
COMBATLOG_OBJECT_TYPE_MASK = tonumber("0000FC00", 16);
|
||||
COMBATLOG_OBJECT_TARGET = tonumber("00010000", 16);
|
||||
COMBATLOG_OBJECT_FOCUS = tonumber("00020000", 16);
|
||||
COMBATLOG_OBJECT_MAINTANK = tonumber("00040000", 16);
|
||||
COMBATLOG_OBJECT_MAINASSIST = tonumber("00080000", 16);
|
||||
COMBATLOG_OBJECT_NONE = tonumber("80000000", 16);
|
||||
COMBATLOG_OBJECT_SPECIAL_MASK = tonumber("FFFF0000", 16);
|
||||
|
||||
-- Combat log raid flags: sourceRaidFlags / destRaidFlags of COMBAT_LOG_EVENT.
|
||||
COMBATLOG_OBJECT_RAIDTARGET1 = tonumber("00000001", 16);
|
||||
COMBATLOG_OBJECT_RAIDTARGET2 = tonumber("00000002", 16);
|
||||
COMBATLOG_OBJECT_RAIDTARGET3 = tonumber("00000004", 16);
|
||||
COMBATLOG_OBJECT_RAIDTARGET4 = tonumber("00000008", 16);
|
||||
COMBATLOG_OBJECT_RAIDTARGET5 = tonumber("00000010", 16);
|
||||
COMBATLOG_OBJECT_RAIDTARGET6 = tonumber("00000020", 16);
|
||||
COMBATLOG_OBJECT_RAIDTARGET7 = tonumber("00000040", 16);
|
||||
COMBATLOG_OBJECT_RAIDTARGET8 = tonumber("00000080", 16);
|
||||
COMBATLOG_OBJECT_RAIDTARGET_MASK = tonumber("000000FF", 16);
|
||||
|
||||
-- Combat log filter masks, for CombatLogAddFilter and CombatLog_Object_IsA.
|
||||
COMBATLOG_FILTER_ME = bit.bor(
|
||||
COMBATLOG_OBJECT_AFFILIATION_MINE,
|
||||
COMBATLOG_OBJECT_REACTION_FRIENDLY,
|
||||
COMBATLOG_OBJECT_CONTROL_PLAYER,
|
||||
COMBATLOG_OBJECT_TYPE_PLAYER
|
||||
);
|
||||
|
||||
COMBATLOG_FILTER_MINE = bit.bor(
|
||||
COMBATLOG_OBJECT_AFFILIATION_MINE,
|
||||
COMBATLOG_OBJECT_REACTION_FRIENDLY,
|
||||
COMBATLOG_OBJECT_CONTROL_PLAYER,
|
||||
COMBATLOG_OBJECT_TYPE_PLAYER,
|
||||
COMBATLOG_OBJECT_TYPE_OBJECT
|
||||
);
|
||||
|
||||
COMBATLOG_FILTER_MY_PET = bit.bor(
|
||||
COMBATLOG_OBJECT_AFFILIATION_MINE,
|
||||
COMBATLOG_OBJECT_REACTION_FRIENDLY,
|
||||
COMBATLOG_OBJECT_CONTROL_PLAYER,
|
||||
COMBATLOG_OBJECT_TYPE_GUARDIAN,
|
||||
COMBATLOG_OBJECT_TYPE_PET
|
||||
);
|
||||
COMBATLOG_FILTER_FRIENDLY_UNITS = bit.bor(
|
||||
COMBATLOG_OBJECT_AFFILIATION_PARTY,
|
||||
COMBATLOG_OBJECT_AFFILIATION_RAID,
|
||||
COMBATLOG_OBJECT_AFFILIATION_OUTSIDER,
|
||||
COMBATLOG_OBJECT_REACTION_FRIENDLY,
|
||||
COMBATLOG_OBJECT_CONTROL_PLAYER,
|
||||
COMBATLOG_OBJECT_CONTROL_NPC,
|
||||
COMBATLOG_OBJECT_TYPE_PLAYER,
|
||||
COMBATLOG_OBJECT_TYPE_NPC,
|
||||
COMBATLOG_OBJECT_TYPE_PET,
|
||||
COMBATLOG_OBJECT_TYPE_GUARDIAN,
|
||||
COMBATLOG_OBJECT_TYPE_OBJECT
|
||||
);
|
||||
|
||||
COMBATLOG_FILTER_HOSTILE_PLAYERS = bit.bor(
|
||||
COMBATLOG_OBJECT_AFFILIATION_PARTY,
|
||||
COMBATLOG_OBJECT_AFFILIATION_RAID,
|
||||
COMBATLOG_OBJECT_AFFILIATION_OUTSIDER,
|
||||
COMBATLOG_OBJECT_REACTION_HOSTILE,
|
||||
COMBATLOG_OBJECT_CONTROL_PLAYER,
|
||||
COMBATLOG_OBJECT_TYPE_PLAYER,
|
||||
COMBATLOG_OBJECT_TYPE_NPC,
|
||||
COMBATLOG_OBJECT_TYPE_PET,
|
||||
COMBATLOG_OBJECT_TYPE_GUARDIAN,
|
||||
COMBATLOG_OBJECT_TYPE_OBJECT
|
||||
);
|
||||
|
||||
COMBATLOG_FILTER_HOSTILE_UNITS = bit.bor(
|
||||
COMBATLOG_OBJECT_AFFILIATION_PARTY,
|
||||
COMBATLOG_OBJECT_AFFILIATION_RAID,
|
||||
COMBATLOG_OBJECT_AFFILIATION_OUTSIDER,
|
||||
COMBATLOG_OBJECT_REACTION_HOSTILE,
|
||||
COMBATLOG_OBJECT_CONTROL_NPC,
|
||||
COMBATLOG_OBJECT_TYPE_PLAYER,
|
||||
COMBATLOG_OBJECT_TYPE_NPC,
|
||||
COMBATLOG_OBJECT_TYPE_PET,
|
||||
COMBATLOG_OBJECT_TYPE_GUARDIAN,
|
||||
COMBATLOG_OBJECT_TYPE_OBJECT
|
||||
);
|
||||
|
||||
COMBATLOG_FILTER_NEUTRAL_UNITS = bit.bor(
|
||||
COMBATLOG_OBJECT_AFFILIATION_PARTY,
|
||||
COMBATLOG_OBJECT_AFFILIATION_RAID,
|
||||
COMBATLOG_OBJECT_AFFILIATION_OUTSIDER,
|
||||
COMBATLOG_OBJECT_REACTION_NEUTRAL,
|
||||
COMBATLOG_OBJECT_CONTROL_PLAYER,
|
||||
COMBATLOG_OBJECT_CONTROL_NPC,
|
||||
COMBATLOG_OBJECT_TYPE_PLAYER,
|
||||
COMBATLOG_OBJECT_TYPE_NPC,
|
||||
COMBATLOG_OBJECT_TYPE_PET,
|
||||
COMBATLOG_OBJECT_TYPE_GUARDIAN,
|
||||
COMBATLOG_OBJECT_TYPE_OBJECT
|
||||
);
|
||||
COMBATLOG_FILTER_UNKNOWN_UNITS = COMBATLOG_OBJECT_NONE;
|
||||
COMBATLOG_FILTER_EVERYTHING = tonumber("FFFFFFFF", 16);
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
-- CooldownFrame_SetTimer for both kinds of cooldown frame. A Cooldown frame
|
||||
-- (CreateFrame("Cooldown") or <Cooldown>) takes 4.3.4's body (Cooldown.lua),
|
||||
-- which hands the timer to the frame's own SetCooldown. Every other frame is
|
||||
-- one of 1.12's indicator Models (CooldownFrameTemplate, as the action, bag,
|
||||
-- spellbook and paper-doll buttons build theirs) and keeps 1.12's body, which
|
||||
-- drives the model's sweep from CooldownFrame_OnUpdateModel.
|
||||
|
||||
function CooldownFrame_SetTimer(this, start, duration, enable)
|
||||
if ( this:IsObjectType("Cooldown") ) then
|
||||
if ( start and start > 0 and duration > 0 and enable > 0 ) then
|
||||
this:SetCooldown(start, duration);
|
||||
this:Show();
|
||||
else
|
||||
this:Hide();
|
||||
end
|
||||
return;
|
||||
end
|
||||
if ( start > 0 and duration > 0 and enable > 0) then
|
||||
this.start = start;
|
||||
this.duration = duration;
|
||||
this.stopping = 0;
|
||||
this:SetSequence(0);
|
||||
this:Show();
|
||||
else
|
||||
this:Hide();
|
||||
end
|
||||
end
|
||||
@@ -27,3 +27,18 @@ function EquipmentManager_GetLocationData(location)
|
||||
|
||||
return locationData;
|
||||
end
|
||||
|
||||
function EquipmentManager_EquipSet(setID)
|
||||
if ( C_EquipmentSet.EquipmentSetContainsLockedItems(setID) or C_Spell.UnitCastingInfo("player") ) then
|
||||
UIErrorsFrame:AddMessage(ERR_CLIENT_LOCKED_OUT, 1.0, 0.1, 0.1, 1.0);
|
||||
return;
|
||||
end
|
||||
C_EquipmentSet.UseEquipmentSet(setID);
|
||||
end
|
||||
|
||||
-- An equipment-set action button fires WEAR_EQUIPMENT_SET; equipping is the UI's job.
|
||||
local EquipmentManagerFrame = CreateFrame("Frame");
|
||||
EquipmentManagerFrame:SetScript("OnEvent", function()
|
||||
EquipmentManager_EquipSet(arg1);
|
||||
end);
|
||||
EquipmentManagerFrame:RegisterEvent("WEAR_EQUIPMENT_SET");
|
||||
|
||||
@@ -61,6 +61,18 @@ LinkTypes = {
|
||||
|
||||
LinkUtil = {};
|
||||
|
||||
-- `assertsafe` isn't a global in stock 1.12; defined as a local fallback so
|
||||
-- this file stays self-contained, the same way FunctionUtil.lua and Pools.lua
|
||||
-- do. Only fires when `condition` is falsy, matching Blizzard's semantics.
|
||||
local function assertsafe(condition, msg)
|
||||
if not condition then
|
||||
local handler = geterrorhandler and geterrorhandler();
|
||||
if handler then
|
||||
handler(msg or "assertion failed!");
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function LinkUtil.FormatLink(linkType, linkDisplayText, ...)
|
||||
local linkFormatTable = { string.format("|H%s", linkType) };
|
||||
for i = 1, arg.n do
|
||||
@@ -185,3 +197,25 @@ do
|
||||
s_linkHandlerFunctions[linkType] = handlerFunction;
|
||||
end
|
||||
end
|
||||
|
||||
------------------------------------------------------------------------------
|
||||
-- Click dispatch. Retail's SetItemRef opens with exactly this: build the
|
||||
-- context, offer the link to the registered handlers, and stop if one took it.
|
||||
-- 1.12's SetItemRef knows only item and player links and would reject anything
|
||||
-- else, so the dispatch wraps it here instead of living in the engine.
|
||||
--
|
||||
-- The chat renderer itself accepts any |H<type>:...|h[text]|h and makes it
|
||||
-- clickable, so a handler is all a new link type needs.
|
||||
--
|
||||
-- Capture-and-replace, not hooksecurefunc: a post-hook cannot stop the engine
|
||||
-- from rejecting the link first. 1.12 passes (link, text, button); `link` is
|
||||
-- the payload without the |H and |h wrappers, `text` the whole decorated link.
|
||||
------------------------------------------------------------------------------
|
||||
local originalSetItemRef = SetItemRef;
|
||||
function SetItemRef(link, text, button, chatFrame)
|
||||
local contextData = { button = button, frame = chatFrame };
|
||||
if LinkUtil.ProcessLink(link, text, contextData) == LinkProcessorResponse.Handled then
|
||||
return;
|
||||
end
|
||||
return originalSetItemRef(link, text, button, chatFrame);
|
||||
end
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
-- MacroIconSelection.lua -- the Macro UI's macro list shows the icon a
|
||||
-- `#showtooltip` resolved to, the way the action button does.
|
||||
--
|
||||
-- `GetMacroInfo` reports the icon the macro STORES, and it has to keep
|
||||
-- reporting that one: `MacroFrame_Update` seeds the icon selector from that
|
||||
-- return, so answering with a resolved icon there would pre-select an icon the
|
||||
-- player never picked, in the one place that edits the stored icon.
|
||||
--
|
||||
-- That leaves the list buttons showing the question mark for a macro whose
|
||||
-- action button shows a spell. `C_Macro.GetMacroIcon` returns the icon a macro
|
||||
-- currently shows, so paint the buttons from it once the stock update has
|
||||
-- drawn them. An empty slot and a macro with a chosen icon both answer with
|
||||
-- what stock already drew, so those are left alone.
|
||||
|
||||
local function ApplyIcon(texture, macroSlot)
|
||||
if not texture then
|
||||
return
|
||||
end
|
||||
local shown = C_Macro.GetMacroIcon(macroSlot)
|
||||
if shown then
|
||||
texture:SetTexture(shown)
|
||||
end
|
||||
end
|
||||
|
||||
local function PaintMacroList()
|
||||
if not (MacroFrame and MacroFrame.macroBase) then
|
||||
return
|
||||
end
|
||||
for i = 1, MAX_MACROS do
|
||||
ApplyIcon(_G["MacroButton" .. i .. "Icon"], MacroFrame.macroBase + i)
|
||||
end
|
||||
if MacroFrame.selectedMacro then
|
||||
ApplyIcon(MacroFrameSelectedMacroButtonIcon, MacroFrame.selectedMacro)
|
||||
end
|
||||
end
|
||||
|
||||
local function WrapMacroFrameUpdate()
|
||||
if not MacroFrame_Update then
|
||||
return
|
||||
end
|
||||
|
||||
local original = MacroFrame_Update
|
||||
-- No `...`: `MacroFrame_Update` takes no arguments, and Lua 5.0 would
|
||||
-- build an `arg` table for every vararg call.
|
||||
MacroFrame_Update = function()
|
||||
original()
|
||||
PaintMacroList()
|
||||
end
|
||||
end
|
||||
|
||||
-- Blizzard_MacroUI loads on demand.
|
||||
EventUtil.ContinueOnAddOnLoaded("Blizzard_MacroUI", WrapMacroFrameUpdate)
|
||||
@@ -24,8 +24,9 @@
|
||||
-- one ClassicAPI extension: [known:spellID] / [known:name].
|
||||
-- Where a keyword's underlying state does not exist on 1.12 (flying, flyable,
|
||||
-- vehicleui, unithasvehicleui) the condition is a constant false; where 1.12
|
||||
-- only has a partial answer (spec is always primary, button/actionbar default
|
||||
-- to the resting state) the closest honest mapping is used. An UNKNOWN keyword
|
||||
-- only has a partial answer (spec is always primary; actionbar defaults to the
|
||||
-- resting state, as does button when no click is running) the closest honest
|
||||
-- mapping is used. An UNKNOWN keyword
|
||||
-- is a hard false with a one-time warning -- never a silent pass -- so a typo
|
||||
-- can't wrongly show a frame. See docs/API.md for the full contract.
|
||||
--
|
||||
@@ -217,29 +218,46 @@ CONDITIONS.spec = function(target, args)
|
||||
return true;
|
||||
end
|
||||
|
||||
-- [mod:X/Y] passes when any value is a held modified click: a modifier string
|
||||
-- ("shift", "lctrl", "alt-shift") or a modified-click action ("SELFCAST"), as
|
||||
-- 4.3.4's EvaluateModifier asks IsModifiedClick. Bare [mod] is any of them.
|
||||
local IsModifiedClick = ClassicAPI.IsModifiedClick;
|
||||
|
||||
CONDITIONS.modifier = function(target, args)
|
||||
if args then
|
||||
for i = 1, args.n do
|
||||
local a = strlower(args[i]);
|
||||
if a == "shift" then
|
||||
if IsShiftKeyDown() then return true; end
|
||||
elseif a == "ctrl" then
|
||||
if IsControlKeyDown() then return true; end
|
||||
elseif a == "alt" then
|
||||
if IsAltKeyDown() then return true; end
|
||||
end
|
||||
if IsModifiedClick(args[i]) then return true; end
|
||||
end
|
||||
return false;
|
||||
end
|
||||
return IsShiftKeyDown() or IsControlKeyDown() or IsAltKeyDown();
|
||||
return IsModifiedClick() ~= nil;
|
||||
end
|
||||
|
||||
-- Outside a click context the "current" button is the left button.
|
||||
-- [button:N] numbers the mouse buttons the way the rest of the modern API
|
||||
-- does -- 1 left, 2 RIGHT, 3 middle, 4, 5. That is deliberately not the order
|
||||
-- of the engine's internal click bitmask (where 2 is the middle button), which
|
||||
-- never reaches Lua. A name is matched as written, so a button clicked with an
|
||||
-- explicit name (`someButton:Click("LeftButton")`) answers [button:leftbutton]
|
||||
-- as well as [button:1].
|
||||
local BUTTON_NUMBER_NAMES = {
|
||||
["1"] = "leftbutton",
|
||||
["2"] = "rightbutton",
|
||||
["3"] = "middlebutton",
|
||||
["4"] = "button4",
|
||||
["5"] = "button5",
|
||||
};
|
||||
|
||||
CONDITIONS.button = function(target, args)
|
||||
if args then
|
||||
-- GetMouseButtonClicked() is the button of the click this macro is
|
||||
-- running inside. It reads nil when no click is running -- a state
|
||||
-- driver poll, or the re-evaluation behind a macro's #showtooltip
|
||||
-- display -- and the engine's own no-argument Button:Click() means the
|
||||
-- left button, so that is the resting answer.
|
||||
local current = strlower(GetMouseButtonClicked() or "LeftButton");
|
||||
for i = 1, args.n do
|
||||
local a = args[i];
|
||||
if a == "1" or strlower(a) == "leftbutton" then return true; end
|
||||
local a = strlower(args[i]);
|
||||
if (BUTTON_NUMBER_NAMES[a] or a) == current then return true; end
|
||||
end
|
||||
return false;
|
||||
end
|
||||
|
||||
@@ -1,222 +1,219 @@
|
||||
-- SecureStateDriver: automatic frame state / visibility from macro conditionals.
|
||||
--
|
||||
-- Backports FrameXML's SecureStateDriverManager. A registered driver re-runs
|
||||
-- SecureCmdOptionParse (Util/MacroOptions.lua) on a 0.2s poll (plus an instant
|
||||
-- rescan on the events below) and applies the result:
|
||||
-- * RegisterStateDriver(frame, "visibility", "[combat] hide; show") -> the
|
||||
-- value "show"/"hide" drives frame:Show()/Hide();
|
||||
-- * RegisterStateDriver / RegisterAttributeDriver for any other state ->
|
||||
-- frame:SetAttribute("state-"..state, value), so an OnAttributeChanged
|
||||
-- handler reacts to it;
|
||||
-- * RegisterUnitWatch(frame [, asState]) -> shows/hides (or sets
|
||||
-- "state-unitexists") as the frame's `unit` attribute comes and goes.
|
||||
-- SecureStateDriverManager
|
||||
-- Automatically sets states based on macro options for state driver frames
|
||||
-- Also handled showing/hiding frames based on unit existence (code originally by Tem)
|
||||
--
|
||||
-- Base: 3.3.5 FrameXML/SecureStateDriver.lua, with the anniversary refinements
|
||||
-- grafted in (the resolveDriver() consolidation, tonumber() coercion of driver
|
||||
-- values, the literal string 'nil' -> nil, and the "statehidden" attribute).
|
||||
-- 4.3.4 FrameXML/SecureStateDriver.lua, with three changes this client needs:
|
||||
-- * Each handler falls back to the vanilla globals (`this`, `arg1`, `arg2`)
|
||||
-- when called without arguments, so it keeps working while modern script
|
||||
-- arguments are switched off (SetModernScriptArgs(false)).
|
||||
-- * `string.match` instead of `strmatch`, which this client does not define.
|
||||
-- * Events this client does not define (UPDATE_STEALTH, ...) are skipped
|
||||
-- instead of registered, and UPDATE_SHAPESHIFT_FORMS (the 1.12 name) is
|
||||
-- registered alongside UPDATE_SHAPESHIFT_FORM.
|
||||
-- SecureCmdOptionParse is Util/MacroOptions.lua; SecureButton_GetUnit is
|
||||
-- SecureTemplates.lua (loaded earlier).
|
||||
|
||||
-- Register a frame attribute to be set automatically with changes in game state
|
||||
function RegisterAttributeDriver(frame, attribute, values)
|
||||
if ( attribute and values and attribute:sub(1, 1) ~= "_" ) then
|
||||
SecureStateDriverManager:SetAttribute("setframe", frame);
|
||||
SecureStateDriverManager:SetAttribute("setstate", attribute.." "..values);
|
||||
end
|
||||
end
|
||||
|
||||
-- Unregister a frame from the state driver manager.
|
||||
function UnregisterAttributeDriver(frame, attribute)
|
||||
if ( attribute ) then
|
||||
SecureStateDriverManager:SetAttribute("setframe", frame);
|
||||
SecureStateDriverManager:SetAttribute("setstate", attribute);
|
||||
else
|
||||
SecureStateDriverManager:SetAttribute("delframe", frame);
|
||||
end
|
||||
end
|
||||
|
||||
-- Bridge functions for compatibility
|
||||
function RegisterStateDriver(frame, state, values)
|
||||
return RegisterAttributeDriver(frame, "state-"..state, values);
|
||||
end
|
||||
|
||||
function UnregisterStateDriver(frame, state)
|
||||
return UnregisterAttributeDriver(frame, "state-"..state);
|
||||
end
|
||||
|
||||
-- Register a frame to be notified when a unit's existence changes, the
|
||||
-- unit is obtained from the frame's attributes. If asState is true then
|
||||
-- notification is via the 'state-unitexists' attribute with values
|
||||
-- true and false. Otherwise it's via :Show() and :Hide()
|
||||
function RegisterUnitWatch(frame, asState)
|
||||
if ( asState ) then
|
||||
SecureStateDriverManager:SetAttribute("addwatchstate", frame);
|
||||
else
|
||||
SecureStateDriverManager:SetAttribute("addwatch", frame);
|
||||
end
|
||||
end
|
||||
|
||||
-- Unregister a frame from the unit existence monitor.
|
||||
function UnregisterUnitWatch(frame)
|
||||
SecureStateDriverManager:SetAttribute("removewatch", frame);
|
||||
end
|
||||
|
||||
--
|
||||
-- Three deliberate deviations from upstream, all because 1.12 has no taint and
|
||||
-- our attribute system fires OnAttributeChanged SYNCHRONOUSLY:
|
||||
-- 1. No attribute-bootstrap manager. Upstream drives itself through
|
||||
-- SecureStateDriverManager:SetAttribute("setframe"/"setstate"/...) -- a
|
||||
-- taint-boundary trick. Our SetAttribute has a recursion guard (a nested
|
||||
-- SetAttribute stores the value but does NOT fire the handler, see
|
||||
-- src/frame/Attributes.cpp), so doing the registration-time resolve from
|
||||
-- inside that handler would silently swallow the target frame's own
|
||||
-- OnAttributeChanged. Instead the public Register* functions write plain
|
||||
-- local tables and resolve immediately at top level. Public signatures are
|
||||
-- unchanged from retail.
|
||||
-- 2. GetTime()-deadline throttle instead of the OnUpdate `elapsed` arg (1.12
|
||||
-- handlers take no parameters).
|
||||
-- 3. UpdateUnitWatch guards its "statehidden"/"state-unitexists" writes on a
|
||||
-- real change, so a watched frame's handler is not fired at 5 Hz.
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- SecureButton_* (minimal -- no taint, no modifier/button suffix machinery)
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
-- SecureButton_GetAttribute and SecureButton_GetUnit are defined in
|
||||
-- SecureTemplates.lua (loaded earlier via SecureTemplates.xml).
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Private state
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
local secureAttributeDrivers = {}; -- [frame][attribute] = optionsString
|
||||
local unitExistsWatchers = {}; -- [frame] = doState (boolean)
|
||||
local unitExistsCache = setmetatable({}, {
|
||||
__index = function(t, k)
|
||||
local v = (UnitExists(k) and true) or false;
|
||||
t[k] = v;
|
||||
return v;
|
||||
end,
|
||||
});
|
||||
|
||||
-- Private implementation
|
||||
--
|
||||
local secureAttributeDrivers = {};
|
||||
local unitExistsWatchers = {};
|
||||
local unitExistsCache = setmetatable({},
|
||||
{ __index = function(t,k)
|
||||
local v = UnitExists(k) or false;
|
||||
t[k] = v;
|
||||
return v;
|
||||
end
|
||||
});
|
||||
local STATE_DRIVER_UPDATE_THROTTLE = 0.2;
|
||||
local nextUpdate = 0;
|
||||
local timer = 0;
|
||||
|
||||
local wipe = table.wipe;
|
||||
|
||||
-- Check to see if a frame is registered
|
||||
function UnitWatchRegistered(frame)
|
||||
return not (unitExistsWatchers[frame] == nil);
|
||||
end
|
||||
|
||||
local function SecureStateDriverManager_UpdateUnitWatch(frame, doState)
|
||||
local unit = SecureButton_GetUnit(frame);
|
||||
local exists = (unit and unitExistsCache[unit]);
|
||||
if ( doState ) then
|
||||
local attr = exists or false;
|
||||
if ( frame:GetAttribute("state-unitexists") ~= attr ) then
|
||||
frame:SetAttribute("state-unitexists", attr);
|
||||
end
|
||||
else
|
||||
if ( exists ) then
|
||||
frame:Show();
|
||||
frame:SetAttribute("statehidden", nil);
|
||||
else
|
||||
frame:Hide();
|
||||
frame:SetAttribute("statehidden", true);
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local pairs = pairs;
|
||||
|
||||
function UnitWatchRegistered(frame)
|
||||
return unitExistsWatchers[frame] ~= nil;
|
||||
end
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Resolvers
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
local function UpdateUnitWatch(frame, doState)
|
||||
local unit = SecureButton_GetUnit(frame);
|
||||
local exists = (unit and unitExistsCache[unit]) or false;
|
||||
if doState then
|
||||
if frame:GetAttribute("state-unitexists") ~= exists then
|
||||
frame:SetAttribute("state-unitexists", exists);
|
||||
end
|
||||
else
|
||||
if exists then
|
||||
frame:Show();
|
||||
else
|
||||
frame:Hide();
|
||||
end
|
||||
local hidden = (not exists) or nil;
|
||||
if frame:GetAttribute("statehidden") ~= hidden then
|
||||
frame:SetAttribute("statehidden", hidden);
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- consolidate duplicated code for footprint and maintainability
|
||||
local function resolveDriver(frame, attribute, values)
|
||||
local newValue = SecureCmdOptionParse(values);
|
||||
local newValue = SecureCmdOptionParse(values);
|
||||
|
||||
if attribute == "state-visibility" then
|
||||
if newValue == "show" then
|
||||
frame:Show();
|
||||
if frame:GetAttribute("statehidden") ~= nil then
|
||||
frame:SetAttribute("statehidden", nil);
|
||||
end
|
||||
elseif newValue == "hide" then
|
||||
frame:Hide();
|
||||
if frame:GetAttribute("statehidden") ~= true then
|
||||
frame:SetAttribute("statehidden", true);
|
||||
if ( attribute == "state-visibility" ) then
|
||||
if ( newValue == "show" ) then
|
||||
frame:Show();
|
||||
frame:SetAttribute("statehidden", nil);
|
||||
elseif ( newValue == "hide" ) then
|
||||
frame:Hide();
|
||||
frame:SetAttribute("statehidden", true);
|
||||
end
|
||||
elseif ( newValue ) then
|
||||
if ( newValue == 'nil' ) then
|
||||
newValue = nil;
|
||||
else
|
||||
newValue = tonumber(newValue) or newValue;
|
||||
end
|
||||
local oldValue = frame:GetAttribute(attribute);
|
||||
if ( newValue ~= oldValue ) then
|
||||
frame:SetAttribute(attribute, newValue);
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function SecureStateDriverManager_OnUpdate(self,elapsed)
|
||||
elapsed = elapsed or arg1;
|
||||
timer = timer - elapsed;
|
||||
if ( timer <= 0 ) then
|
||||
timer = STATE_DRIVER_UPDATE_THROTTLE;
|
||||
|
||||
-- Handle state driver updates
|
||||
for frame,drivers in pairs(secureAttributeDrivers) do
|
||||
for attribute,values in pairs(drivers) do
|
||||
resolveDriver(frame, attribute, values);
|
||||
end
|
||||
end
|
||||
elseif newValue then
|
||||
if newValue == "nil" then
|
||||
newValue = nil;
|
||||
else
|
||||
newValue = tonumber(newValue) or newValue;
|
||||
|
||||
-- Handle unit existence changes
|
||||
wipe(unitExistsCache);
|
||||
for k in pairs(unitExistsCache) do
|
||||
unitExistsCache[k] = nil;
|
||||
end
|
||||
if frame:GetAttribute(attribute) ~= newValue then
|
||||
frame:SetAttribute(attribute, newValue);
|
||||
for frame,doState in pairs(unitExistsWatchers) do
|
||||
SecureStateDriverManager_UpdateUnitWatch(frame, doState);
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Manager frame
|
||||
-- ---------------------------------------------------------------------------
|
||||
local function SecureStateDriverManager_OnEvent(self, event)
|
||||
timer = 0;
|
||||
end
|
||||
|
||||
SecureStateDriverManager = CreateFrame("Frame", "SecureStateDriverManager");
|
||||
SecureStateDriverManager:Hide(); -- hidden -> no OnUpdate until a driver exists
|
||||
|
||||
SecureStateDriverManager:SetScript("OnUpdate", function()
|
||||
local now = GetTime();
|
||||
if now < nextUpdate then
|
||||
local function SecureStateDriverManager_OnAttributeChanged(self, name, value)
|
||||
if ( not self ) then
|
||||
self, name, value = this, arg1, arg2;
|
||||
end
|
||||
if ( not value ) then
|
||||
return;
|
||||
end
|
||||
nextUpdate = now + STATE_DRIVER_UPDATE_THROTTLE;
|
||||
|
||||
for frame, drivers in pairs(secureAttributeDrivers) do
|
||||
for attribute, values in pairs(drivers) do
|
||||
if ( name == "setframe" ) then
|
||||
if ( not secureAttributeDrivers[value] ) then
|
||||
secureAttributeDrivers[value] = {};
|
||||
end
|
||||
SecureStateDriverManager:Show();
|
||||
elseif ( name == "delframe" ) then
|
||||
secureAttributeDrivers[value] = nil;
|
||||
elseif ( name == "setstate" ) then
|
||||
local frame = self:GetAttribute("setframe");
|
||||
local attribute, values = string.match(value, "^(%S+)%s*(.*)$");
|
||||
if ( values == "" ) then
|
||||
secureAttributeDrivers[frame][attribute] = nil;
|
||||
else
|
||||
secureAttributeDrivers[frame][attribute] = values;
|
||||
resolveDriver(frame, attribute, values);
|
||||
end
|
||||
elseif ( name == "addwatch" or name == "addwatchstate" ) then
|
||||
local doState = (name == "addwatchstate");
|
||||
unitExistsWatchers[value] = doState;
|
||||
SecureStateDriverManager:Show();
|
||||
SecureStateDriverManager_UpdateUnitWatch(value, doState);
|
||||
elseif ( name == "removewatch" ) then
|
||||
unitExistsWatchers[value] = nil;
|
||||
elseif ( name == "updatetime" ) then
|
||||
STATE_DRIVER_UPDATE_THROTTLE = value;
|
||||
end
|
||||
end
|
||||
|
||||
for k in pairs(unitExistsCache) do
|
||||
unitExistsCache[k] = nil;
|
||||
end
|
||||
for frame, doState in pairs(unitExistsWatchers) do
|
||||
UpdateUnitWatch(frame, doState);
|
||||
end
|
||||
end);
|
||||
SecureStateDriverManager = CreateFrame("Frame", "SecureStateDriverManager", nil, "SecureFrameTemplate");
|
||||
SecureStateDriverManager:Hide();
|
||||
SecureStateDriverManager:SetScript("OnUpdate", SecureStateDriverManager_OnUpdate);
|
||||
SecureStateDriverManager:SetScript("OnEvent", SecureStateDriverManager_OnEvent);
|
||||
SecureStateDriverManager:SetScript("OnAttributeChanged", SecureStateDriverManager_OnAttributeChanged);
|
||||
|
||||
SecureStateDriverManager:SetScript("OnEvent", function()
|
||||
nextUpdate = 0; -- force a rescan on the next frame
|
||||
end);
|
||||
|
||||
SecureStateDriverManager:SetScript("OnAttributeChanged", function()
|
||||
if arg1 == "updatetime" and tonumber(arg2) then
|
||||
STATE_DRIVER_UPDATE_THROTTLE = tonumber(arg2);
|
||||
end
|
||||
end);
|
||||
|
||||
-- Events that warrant an early rescan. Each is guarded so a name this client
|
||||
-- doesn't define (e.g. UPDATE_STEALTH) is simply skipped.
|
||||
local rescanEvents = {
|
||||
"MODIFIER_STATE_CHANGED", -- ClassicAPI-fired
|
||||
"PLAYER_FOCUS_CHANGED", -- ClassicAPI-fired
|
||||
"UPDATE_SHAPESHIFT_FORM", -- ClassicAPI-fired (singular)
|
||||
"UPDATE_SHAPESHIFT_FORMS", -- native 1.12 (plural)
|
||||
-- Events that trigger early rescans
|
||||
for _, event in ipairs({
|
||||
"MODIFIER_STATE_CHANGED",
|
||||
"ACTIONBAR_PAGE_CHANGED",
|
||||
"UPDATE_BONUS_ACTIONBAR",
|
||||
"PLAYER_ENTERING_WORLD",
|
||||
"UPDATE_SHAPESHIFT_FORM",
|
||||
"UPDATE_SHAPESHIFT_FORMS",
|
||||
"UPDATE_STEALTH",
|
||||
"PLAYER_TARGET_CHANGED",
|
||||
"PLAYER_FOCUS_CHANGED",
|
||||
"PLAYER_REGEN_DISABLED",
|
||||
"PLAYER_REGEN_ENABLED",
|
||||
"UNIT_PET",
|
||||
"RAID_ROSTER_UPDATE",
|
||||
"PARTY_MEMBERS_CHANGED",
|
||||
};
|
||||
for _, event in ipairs(rescanEvents) do
|
||||
if C_EventUtils.IsEventValid(event) then
|
||||
}) do
|
||||
if ( C_EventUtils.IsEventValid(event) ) then
|
||||
SecureStateDriverManager:RegisterEvent(event);
|
||||
end
|
||||
end
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Public API
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
function RegisterAttributeDriver(frame, attribute, values)
|
||||
if attribute and values and string.sub(attribute, 1, 1) ~= "_" then
|
||||
local drivers = secureAttributeDrivers[frame];
|
||||
if not drivers then
|
||||
drivers = {};
|
||||
secureAttributeDrivers[frame] = drivers;
|
||||
end
|
||||
drivers[attribute] = values;
|
||||
SecureStateDriverManager:Show();
|
||||
resolveDriver(frame, attribute, values);
|
||||
end
|
||||
end
|
||||
|
||||
function UnregisterAttributeDriver(frame, attribute)
|
||||
if attribute then
|
||||
local drivers = secureAttributeDrivers[frame];
|
||||
if drivers then
|
||||
drivers[attribute] = nil;
|
||||
end
|
||||
else
|
||||
secureAttributeDrivers[frame] = nil;
|
||||
end
|
||||
end
|
||||
|
||||
function RegisterStateDriver(frame, state, values)
|
||||
RegisterAttributeDriver(frame, "state-" .. state, values);
|
||||
end
|
||||
|
||||
function UnregisterStateDriver(frame, state)
|
||||
UnregisterAttributeDriver(frame, state and ("state-" .. state));
|
||||
end
|
||||
|
||||
function RegisterUnitWatch(frame, asState)
|
||||
local doState = (asState and true) or false;
|
||||
unitExistsWatchers[frame] = doState;
|
||||
SecureStateDriverManager:Show();
|
||||
UpdateUnitWatch(frame, doState);
|
||||
end
|
||||
|
||||
function UnregisterUnitWatch(frame)
|
||||
unitExistsWatchers[frame] = nil;
|
||||
end
|
||||
-- Deliberately ignoring mouseover and others' target changes because they change so much
|
||||
|
||||
@@ -6,6 +6,13 @@ function RegisterNewSlashCommand(callback, command, commandAlias)
|
||||
SlashCmdList[name] = callback;
|
||||
end
|
||||
|
||||
-- Keys that exist before this file runs, so the block at the bottom can tell
|
||||
-- the commands we ADD from the ones we replace.
|
||||
local preexistingKeys = {};
|
||||
for key in pairs(SlashCmdList) do
|
||||
preexistingKeys[key] = true;
|
||||
end
|
||||
|
||||
-- `/cast` and `/use` (the FrameXML ChatFrame.lua shape): conditionals through
|
||||
-- SecureCmdOptionParse, items before spells, `[@unit]` cast targets.
|
||||
-- A bare number is an inventory slot only when it is one (1..19); any other
|
||||
@@ -120,32 +127,12 @@ function SecureCmdUseItem(name, bag, slot, target)
|
||||
end
|
||||
end
|
||||
|
||||
local function SecureCmdCast(msg)
|
||||
local action, target = SecureCmdOptionParse(msg);
|
||||
if ( not action or action == "" ) then
|
||||
return;
|
||||
end
|
||||
-- `!Name` asks for the spell to be started but never turned off, for the
|
||||
-- abilities that toggle: auto-repeat (Shoot, Auto Shot) and the self-auras
|
||||
-- (stances, aspects, seals, forms, tracking). Strip the prefix here and
|
||||
-- cast through `CastSpellNoToggle`, which asks the engine whether the
|
||||
-- ability is already up before it casts.
|
||||
local noToggle;
|
||||
if ( string.sub(action, 1, 1) == "!" ) then
|
||||
noToggle = true;
|
||||
action = string.sub(action, 2);
|
||||
if ( action == "" ) then
|
||||
return;
|
||||
end
|
||||
end
|
||||
target = SecureCmdNormalizeTarget(target);
|
||||
if ( target == false ) then
|
||||
return; -- a named unit with nobody around to match it
|
||||
end
|
||||
local name, bag, slot = SecureCmdItemParse(action);
|
||||
if ( slot or (name and not IsBareNumber(action) and C_Item.GetItemCount(name) > 0) ) then
|
||||
SecureCmdUseItem(name, bag, slot, target);
|
||||
elseif ( target == "cursor" ) then
|
||||
-- Cast one resolved spell at one normalized target. Split out of
|
||||
-- `SecureCmdCast` so `/castsequence` performs its step under exactly the same
|
||||
-- rules: 1.12's `CastSpellByName` takes no unit, so every targeted form has to
|
||||
-- go through `C_Spell.CastAtUnit`, and a sequence must not reinvent that.
|
||||
local function SecureCmdPerformSpell(action, noToggle, target)
|
||||
if ( target == "cursor" ) then
|
||||
C_Spell.CastAtCursor(action);
|
||||
elseif ( not target or target == "target" ) then
|
||||
if ( noToggle ) then
|
||||
@@ -169,6 +156,43 @@ local function SecureCmdCast(msg)
|
||||
end
|
||||
end
|
||||
|
||||
-- Perform one action at one normalized target: an item the line names, else a
|
||||
-- spell. `/cast`, `/use` and the random commands all land here, so the
|
||||
-- item-before-spell rule and the `!` prefix are decided in one place.
|
||||
local function SecureCmdPerformAction(action, target)
|
||||
-- `!Name` asks for the spell to be started but never turned off, for the
|
||||
-- abilities that toggle: auto-repeat (Shoot, Auto Shot) and the self-auras
|
||||
-- (stances, aspects, seals, forms, tracking). Strip the prefix here and
|
||||
-- cast through `CastSpellNoToggle`, which asks the engine whether the
|
||||
-- ability is already up before it casts.
|
||||
local noToggle;
|
||||
if ( string.sub(action, 1, 1) == "!" ) then
|
||||
noToggle = true;
|
||||
action = string.sub(action, 2);
|
||||
if ( action == "" ) then
|
||||
return;
|
||||
end
|
||||
end
|
||||
local name, bag, slot = SecureCmdItemParse(action);
|
||||
if ( slot or (name and not IsBareNumber(action) and C_Item.GetItemCount(name) > 0) ) then
|
||||
SecureCmdUseItem(name, bag, slot, target);
|
||||
else
|
||||
SecureCmdPerformSpell(action, noToggle, target);
|
||||
end
|
||||
end
|
||||
|
||||
local function SecureCmdCast(msg)
|
||||
local action, target = SecureCmdOptionParse(msg);
|
||||
if ( not action or action == "" ) then
|
||||
return;
|
||||
end
|
||||
target = SecureCmdNormalizeTarget(target);
|
||||
if ( target == false ) then
|
||||
return; -- a named unit with nobody around to match it
|
||||
end
|
||||
SecureCmdPerformAction(action, target);
|
||||
end
|
||||
|
||||
SlashCmdList["CAST"] = SecureCmdCast;
|
||||
SlashCmdList["USE"] = SecureCmdCast;
|
||||
|
||||
@@ -562,3 +586,515 @@ end
|
||||
SlashCmdList["PET_AUTOCASTTOGGLE"] = function(msg)
|
||||
SecureCmdPetAutocast(msg, nil);
|
||||
end
|
||||
|
||||
-- ---------------------------------------------------------------------
|
||||
-- /castsequence
|
||||
--
|
||||
-- One entry per sequence STRING (the text after the conditions), holding the
|
||||
-- step index and the parsed action list. The string is the key on purpose:
|
||||
-- the same sequence typed in two macros advances as one, which is how
|
||||
-- FrameXML behaves and what lets the macro icon ask about a sequence it has
|
||||
-- only the text of.
|
||||
--
|
||||
-- The icon side reads this through `QueryCastSequence`, which the macro
|
||||
-- display calls whenever it needs the current step. That is Blizzard's own
|
||||
-- split -- there the C macro code calls the same global by name -- so the
|
||||
-- index lives here and nowhere else, and execution and display can never
|
||||
-- disagree about which step is current.
|
||||
|
||||
local CastSequenceManager;
|
||||
local CastSequenceTable = {};
|
||||
local CastSequenceFreeList = {};
|
||||
|
||||
-- Cleared by the command-surrender pass at the bottom of this file if another
|
||||
-- addon owns `/castsequence`. Our table only advances while OUR handler runs,
|
||||
-- so once the command is theirs every index we hold is frozen at step one --
|
||||
-- and the macro icon asks us, not them. Answering then would paint a
|
||||
-- confidently wrong step on a sequence somebody else is advancing, so stop
|
||||
-- answering instead and let the icon fall back to unresolved.
|
||||
local castSequenceOwned = true;
|
||||
|
||||
local function Trim(text)
|
||||
return (string.gsub(text or "", "^%s*(.-)%s*$", "%1"));
|
||||
end
|
||||
|
||||
-- The comma-separated pieces of a sequence, empty pieces included: a step
|
||||
-- that resolves to nothing still occupies an index and is skipped at cast
|
||||
-- time, so dropping it here would renumber the sequence.
|
||||
local function SplitSequence(text)
|
||||
local pieces = {};
|
||||
for piece in string.gmatch(text..",", "([^,]*),") do
|
||||
table.insert(pieces, Trim(piece));
|
||||
end
|
||||
return pieces;
|
||||
end
|
||||
|
||||
-- An action is an item when it names a bag or inventory slot, or when the
|
||||
-- player is carrying one by that name. Same test `/cast` uses, and the same
|
||||
-- limit: 1.12 can only look an item up by name among the ones you hold.
|
||||
local function SequenceActionIsItem(action)
|
||||
local name, _, slot = SecureCmdItemParse(action);
|
||||
return slot ~= nil
|
||||
or (name ~= nil and not IsBareNumber(action) and C_Item.GetItemCount(name) > 0);
|
||||
end
|
||||
|
||||
local function CreateCanonicalActions(entry, actions)
|
||||
entry.spells = {};
|
||||
entry.spellNames = {};
|
||||
entry.items = {};
|
||||
for i = 1, table.getn(actions) do
|
||||
local action = strlower(actions[i]);
|
||||
if ( SequenceActionIsItem(action) ) then
|
||||
entry.items[i] = action;
|
||||
entry.spells[i] = strlower(C_Item.GetItemSpell(action) or "");
|
||||
entry.spellNames[i] = entry.spells[i];
|
||||
else
|
||||
entry.spells[i] = action;
|
||||
-- `!Name` is a cast rule, not part of the name the cast events
|
||||
-- report back, so the matcher compares against the bare name.
|
||||
entry.spellNames[i] = string.gsub(action, "^!*(.*)$", "%1");
|
||||
end
|
||||
end
|
||||
entry.count = table.getn(actions);
|
||||
end
|
||||
|
||||
local function SetCastSequenceIndex(entry, index)
|
||||
entry.index = index;
|
||||
entry.pending = nil;
|
||||
end
|
||||
|
||||
local function ResetCastSequence(sequence, entry)
|
||||
SetCastSequenceIndex(entry, 1);
|
||||
CastSequenceFreeList[sequence] = entry;
|
||||
CastSequenceTable[sequence] = nil;
|
||||
end
|
||||
|
||||
local function SetNextCastSequence(sequence, entry)
|
||||
if ( entry.index >= entry.count ) then
|
||||
ResetCastSequence(sequence, entry);
|
||||
else
|
||||
SetCastSequenceIndex(entry, entry.index + 1);
|
||||
end
|
||||
end
|
||||
|
||||
-- A sequence restarts when the player holds the modifier its `reset=` names.
|
||||
local function CastSequenceModifierReset(entry)
|
||||
return (IsShiftKeyDown() and string.find(entry.reset, "shift", 1, true))
|
||||
or (IsControlKeyDown() and string.find(entry.reset, "ctrl", 1, true))
|
||||
or (IsAltKeyDown() and string.find(entry.reset, "alt", 1, true));
|
||||
end
|
||||
|
||||
local function ParseCastSequence(sequence)
|
||||
local reset, spells = string.match(sequence, "^reset=([^%s]+)%s*(.*)$");
|
||||
if ( not reset ) then
|
||||
spells = sequence;
|
||||
end
|
||||
local entry = {};
|
||||
CreateCanonicalActions(entry, SplitSequence(spells));
|
||||
entry.reset = strlower(reset or "");
|
||||
return entry;
|
||||
end
|
||||
|
||||
-- The cast events carry the spell in different argument positions depending on
|
||||
-- the event, so read the name and rank per event rather than by one offset.
|
||||
local function CastEventSpell()
|
||||
if ( event == "UNIT_SPELLCAST_SENT" ) then
|
||||
return arg1, arg5, arg6; -- unit, target, castGUID, spellID, name, rank
|
||||
end
|
||||
return arg1, arg4, arg5; -- unit, castGUID, spellID, name, rank
|
||||
end
|
||||
|
||||
local function CastSequenceManager_OnEvent()
|
||||
-- Death restarts every sequence.
|
||||
if ( event == "PLAYER_DEAD" ) then
|
||||
for sequence, entry in pairs(CastSequenceTable) do
|
||||
ResetCastSequence(sequence, entry);
|
||||
end
|
||||
return;
|
||||
end
|
||||
|
||||
if ( event == "UNIT_SPELLCAST_SENT"
|
||||
or event == "UNIT_SPELLCAST_SUCCEEDED"
|
||||
or event == "UNIT_SPELLCAST_INTERRUPTED"
|
||||
or event == "UNIT_SPELLCAST_FAILED"
|
||||
or event == "UNIT_SPELLCAST_FAILED_QUIET" ) then
|
||||
local unit, name, rank = CastEventSpell();
|
||||
if ( not name ) then
|
||||
-- A server-side spell with no name of its own. Nothing in any
|
||||
-- sequence can match it, so leave every index alone.
|
||||
return;
|
||||
end
|
||||
if ( unit == "player" or unit == "pet" ) then
|
||||
name, rank = strlower(name), strlower(rank or "");
|
||||
local nameplus = name.."()";
|
||||
local fullname = name.."("..rank..")";
|
||||
for sequence, entry in pairs(CastSequenceTable) do
|
||||
local entryName = entry.spellNames[entry.index];
|
||||
if ( entryName == name or entryName == nameplus or entryName == fullname ) then
|
||||
if ( event == "UNIT_SPELLCAST_SENT" ) then
|
||||
-- In flight. Hold the index so a second press
|
||||
-- cannot skip a step the server has not answered.
|
||||
entry.pending = 1;
|
||||
else
|
||||
entry.pending = nil;
|
||||
if ( event == "UNIT_SPELLCAST_SUCCEEDED" ) then
|
||||
SetNextCastSequence(sequence, entry);
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return;
|
||||
end
|
||||
|
||||
local reset = "";
|
||||
if ( event == "PLAYER_TARGET_CHANGED" ) then
|
||||
reset = "target";
|
||||
elseif ( event == "PLAYER_REGEN_ENABLED" ) then
|
||||
reset = "combat";
|
||||
end
|
||||
for sequence, entry in pairs(CastSequenceTable) do
|
||||
if ( string.find(entry.reset, reset, 1, true) ) then
|
||||
ResetCastSequence(sequence, entry);
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function CastSequenceManager_OnUpdate()
|
||||
local elapsed = CastSequenceManager.elapsed + (arg1 or 0);
|
||||
if ( elapsed < 1 ) then
|
||||
CastSequenceManager.elapsed = elapsed;
|
||||
return;
|
||||
end
|
||||
for sequence, entry in pairs(CastSequenceTable) do
|
||||
if ( entry.timeout ) then
|
||||
if ( elapsed >= entry.timeout ) then
|
||||
ResetCastSequence(sequence, entry);
|
||||
else
|
||||
entry.timeout = entry.timeout - elapsed;
|
||||
end
|
||||
end
|
||||
end
|
||||
CastSequenceManager.elapsed = 0;
|
||||
end
|
||||
|
||||
local function CastSequenceEntry(sequence)
|
||||
local entry = CastSequenceTable[sequence];
|
||||
if ( entry ) then
|
||||
return entry;
|
||||
end
|
||||
entry = CastSequenceFreeList[sequence] or ParseCastSequence(sequence);
|
||||
CastSequenceTable[sequence] = entry;
|
||||
entry.index = entry.index or 1;
|
||||
return entry;
|
||||
end
|
||||
|
||||
local function ExecuteCastSequence(sequence, target)
|
||||
if ( not CastSequenceManager ) then
|
||||
CastSequenceManager = CreateFrame("Frame");
|
||||
CastSequenceManager.elapsed = 0;
|
||||
CastSequenceManager:RegisterEvent("PLAYER_DEAD");
|
||||
CastSequenceManager:RegisterEvent("UNIT_SPELLCAST_SENT");
|
||||
CastSequenceManager:RegisterEvent("UNIT_SPELLCAST_SUCCEEDED");
|
||||
CastSequenceManager:RegisterEvent("UNIT_SPELLCAST_INTERRUPTED");
|
||||
CastSequenceManager:RegisterEvent("UNIT_SPELLCAST_FAILED");
|
||||
CastSequenceManager:RegisterEvent("UNIT_SPELLCAST_FAILED_QUIET");
|
||||
CastSequenceManager:RegisterEvent("PLAYER_TARGET_CHANGED");
|
||||
CastSequenceManager:RegisterEvent("PLAYER_REGEN_ENABLED");
|
||||
CastSequenceManager:SetScript("OnEvent", CastSequenceManager_OnEvent);
|
||||
CastSequenceManager:SetScript("OnUpdate", CastSequenceManager_OnUpdate);
|
||||
end
|
||||
|
||||
local entry = CastSequenceEntry(sequence);
|
||||
|
||||
-- A step already sent and not yet answered keeps the sequence where it is.
|
||||
if ( entry.pending ) then
|
||||
return;
|
||||
end
|
||||
|
||||
if ( CastSequenceModifierReset(entry) ) then
|
||||
SetCastSequenceIndex(entry, 1);
|
||||
end
|
||||
|
||||
-- The timeout counts from the last use, so every press renews it.
|
||||
local timeout = string.match(entry.reset, "(%d+)");
|
||||
if ( timeout ) then
|
||||
entry.timeout = CastSequenceManager.elapsed + tonumber(timeout);
|
||||
end
|
||||
|
||||
local item, spell = entry.items[entry.index], entry.spells[entry.index];
|
||||
if ( item ) then
|
||||
local name, bag, slot = SecureCmdItemParse(item);
|
||||
if ( slot ) then
|
||||
-- A slot names whatever is in it right now, so the spell the
|
||||
-- matcher waits for is re-read on every use.
|
||||
spell = name and strlower(C_Item.GetItemSpell(name) or "") or "";
|
||||
entry.spellNames[entry.index] = spell;
|
||||
end
|
||||
if ( C_Item.IsEquippableItem(name) and not C_Item.IsEquippedItem(name) ) then
|
||||
C_Item.EquipItemByName(name);
|
||||
else
|
||||
SecureCmdUseItem(name, bag, slot, target);
|
||||
end
|
||||
else
|
||||
local noToggle;
|
||||
if ( string.sub(spell or "", 1, 1) == "!" ) then
|
||||
noToggle = true;
|
||||
spell = string.sub(spell, 2);
|
||||
end
|
||||
SecureCmdPerformSpell(spell, noToggle, target);
|
||||
end
|
||||
if ( spell == "" ) then
|
||||
-- Nothing castable at this step: step past it so the sequence cannot
|
||||
-- stall on an item the player no longer carries.
|
||||
SetNextCastSequence(sequence, entry);
|
||||
end
|
||||
end
|
||||
|
||||
-- The step a sequence is on, without advancing it. Returns the index, the
|
||||
-- item the step names (nil for a spell), and the spell name. The macro
|
||||
-- display calls this by name.
|
||||
function QueryCastSequence(sequence)
|
||||
if ( not castSequenceOwned ) then
|
||||
return;
|
||||
end
|
||||
local index = 1;
|
||||
local item, spell;
|
||||
local entry = CastSequenceTable[sequence];
|
||||
if ( entry ) then
|
||||
if ( not CastSequenceModifierReset(entry) ) then
|
||||
index = entry.index;
|
||||
end
|
||||
item, spell = entry.items[index], entry.spells[index];
|
||||
else
|
||||
entry = CastSequenceFreeList[sequence];
|
||||
if ( not entry ) then
|
||||
-- Never used yet: parse it so the icon shows step one instead of
|
||||
-- the question mark, but do not make it live.
|
||||
entry = ParseCastSequence(sequence);
|
||||
end
|
||||
item, spell = entry.items[index], entry.spells[index];
|
||||
end
|
||||
if ( item ) then
|
||||
local name, _, slot = SecureCmdItemParse(item);
|
||||
if ( slot ) then
|
||||
spell = name and strlower(C_Item.GetItemSpell(name) or "") or "";
|
||||
end
|
||||
end
|
||||
return index, item, spell;
|
||||
end
|
||||
|
||||
SlashCmdList["CASTSEQUENCE"] = function(msg)
|
||||
local sequence, target = SecureCmdOptionParse(msg);
|
||||
if ( not sequence or sequence == "" ) then
|
||||
return;
|
||||
end
|
||||
target = SecureCmdNormalizeTarget(target);
|
||||
if ( target == false ) then
|
||||
return; -- a named unit with nobody around to match it
|
||||
end
|
||||
ExecuteCastSequence(sequence, target);
|
||||
end
|
||||
SLASH_CASTSEQUENCE1 = "/castsequence";
|
||||
|
||||
-- ---------------------------------------------------------------------
|
||||
-- /castrandom and /userandom
|
||||
--
|
||||
-- One pick per action list, held until a cast SUCCEEDS. A failed or
|
||||
-- interrupted cast keeps the same pick, so a spell that was out of range or
|
||||
-- out of mana is retried rather than swapped for another one -- pressing the
|
||||
-- button again means "try that again", not "roll again". `/userandom` is the
|
||||
-- same command as `/castrandom`, the way `/use` is the same as `/cast`: both
|
||||
-- perform whatever the chosen action turns out to be.
|
||||
|
||||
local CastRandomManager;
|
||||
local CastRandomTable = {};
|
||||
|
||||
local function CastRandomManager_OnEvent()
|
||||
local unit, name, rank = CastEventSpell();
|
||||
if ( not name or unit ~= "player" ) then
|
||||
return;
|
||||
end
|
||||
name, rank = strlower(name), strlower(rank or "");
|
||||
local nameplus = name.."()";
|
||||
local fullname = name.."("..rank..")";
|
||||
for _, entry in pairs(CastRandomTable) do
|
||||
if ( entry.pending and entry.value ) then
|
||||
local entryName = strlower(entry.value);
|
||||
if ( entryName == name or entryName == nameplus or entryName == fullname ) then
|
||||
entry.pending = nil;
|
||||
if ( event == "UNIT_SPELLCAST_SUCCEEDED" ) then
|
||||
entry.value = nil; -- rolled again on the next press
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- The action this press uses. Nil when the list holds nothing to pick from.
|
||||
local function ExecuteCastRandom(actions)
|
||||
if ( not CastRandomManager ) then
|
||||
CastRandomManager = CreateFrame("Frame");
|
||||
CastRandomManager:RegisterEvent("UNIT_SPELLCAST_SUCCEEDED");
|
||||
CastRandomManager:RegisterEvent("UNIT_SPELLCAST_INTERRUPTED");
|
||||
CastRandomManager:RegisterEvent("UNIT_SPELLCAST_FAILED");
|
||||
CastRandomManager:RegisterEvent("UNIT_SPELLCAST_FAILED_QUIET");
|
||||
CastRandomManager:SetScript("OnEvent", CastRandomManager_OnEvent);
|
||||
end
|
||||
|
||||
local entry = CastRandomTable[actions];
|
||||
if ( not entry ) then
|
||||
-- Only the raw pieces are kept. The matcher compares the chosen text
|
||||
-- against the cast events, so the canonical item/spell split the
|
||||
-- sequences build has nothing to do here.
|
||||
entry = { list = SplitSequence(actions) };
|
||||
CastRandomTable[actions] = entry;
|
||||
end
|
||||
if ( not entry.value ) then
|
||||
local count = table.getn(entry.list);
|
||||
if ( count == 0 ) then
|
||||
return nil;
|
||||
end
|
||||
entry.value = entry.list[math.random(count)];
|
||||
end
|
||||
entry.pending = true;
|
||||
return entry.value;
|
||||
end
|
||||
|
||||
local function SecureCmdCastRandom(msg)
|
||||
local actions, target = SecureCmdOptionParse(msg);
|
||||
if ( not actions or actions == "" ) then
|
||||
return;
|
||||
end
|
||||
target = SecureCmdNormalizeTarget(target);
|
||||
if ( target == false ) then
|
||||
return; -- a named unit with nobody around to match it
|
||||
end
|
||||
local action = ExecuteCastRandom(actions);
|
||||
if ( action and action ~= "" ) then
|
||||
SecureCmdPerformAction(action, target);
|
||||
end
|
||||
end
|
||||
|
||||
SlashCmdList["CASTRANDOM"] = SecureCmdCastRandom;
|
||||
SLASH_CASTRANDOM1 = "/castrandom";
|
||||
SlashCmdList["USERANDOM"] = SecureCmdCastRandom;
|
||||
SLASH_USERANDOM1 = "/userandom";
|
||||
|
||||
-- `/stopmacro [conditions]` -- stop before the rest of the body runs. The flag
|
||||
-- belongs to the macro runner, which clears it for each body it starts, so a
|
||||
-- bare call outside a macro does nothing and cannot leave one armed.
|
||||
--
|
||||
-- Through the mirror, not the bare global. `StopMacro` is a plain name in a
|
||||
-- crowded space, and the global is only ours until an addon declares one of
|
||||
-- its own -- at which point this command would set THEIR flag, ours would
|
||||
-- stay clear, and the rest of the macro would keep running with nothing to
|
||||
-- show for it. The mirror captured our function at registration, before
|
||||
-- FrameXML and every addon.
|
||||
local StopMacroSelf = ClassicAPI.StopMacro;
|
||||
|
||||
SlashCmdList["STOPMACRO"] = function(msg)
|
||||
if ( SecureCmdOptionParse(msg) ) then
|
||||
StopMacroSelf();
|
||||
end
|
||||
end
|
||||
SLASH_STOPMACRO1 = "/stopmacro";
|
||||
|
||||
-- ---------------------------------------------------------------------
|
||||
-- Give a contested command back to whoever already owned it
|
||||
--
|
||||
-- Vanilla has no `/petattack`, so the entry above ADDS it. A macro addon can
|
||||
-- ship the same command under its own SlashCmdList key -- SuperCleveRoidMacros
|
||||
-- registers `PETATTACK` where we register `PET_ATTACK`, both with a
|
||||
-- `SLASH_*` string of "/petattack". `ChatEdit_ParseText` walks SlashCmdList
|
||||
-- with `pairs` and takes the first match, so two keys claiming one command
|
||||
-- make the winner hash order: a coin flip. When ours won, it fed
|
||||
-- `[hastarget,alive,harm]` to SecureCmdOptionParse, which does not know that
|
||||
-- addon's conditions, so the line matched nothing and the macro did nothing.
|
||||
--
|
||||
-- Rejecting a condition we cannot evaluate is right on its own -- retail does
|
||||
-- the same -- so the error is owning the command at all. Hand it back. One
|
||||
-- command split across two condition dialects would be worse than one owner,
|
||||
-- because the dialects disagree: our `[@unit]`-only group passes only while
|
||||
-- that unit exists, where 3.3.5's passes unconditionally.
|
||||
--
|
||||
-- Only commands we ADD are given up. A command we replace (`/cast`, `/target`)
|
||||
-- has no second entry to lose to, and an addon that wraps ours afterwards
|
||||
-- chains through us as it always did.
|
||||
--
|
||||
-- And only while the entry is still ours to give. Both halves of the decision
|
||||
-- are snapshotted below at file scope, while the table holds exactly what this
|
||||
-- file registered:
|
||||
--
|
||||
-- * The handler, so a key another addon has since taken OVER is left alone.
|
||||
-- SuperCleveRoidMacros writes its own conditional handler into our
|
||||
-- `SlashCmdList.CANCELAURA`, so clearing the key a frame later would delete
|
||||
-- that addon's command instead of handing ours back. Taking a key over is
|
||||
-- already how an addon wins a command; there is nothing left to resolve.
|
||||
-- * The command strings, because an addon that takes a key over also writes
|
||||
-- its own aliases into the same `SLASH_<key><i>` globals -- SCRM's
|
||||
-- `SLASH_CANCELAURA2 = "/unbuff"` replaces ours. Read a frame later, the
|
||||
-- test would run against a command we never registered, and a third addon
|
||||
-- owning that command would make us surrender an entry over a collision
|
||||
-- that is none of our business.
|
||||
--
|
||||
-- Resolved a frame later, not at file scope: this addon loads first by design,
|
||||
-- so while it runs the other addon has not registered yet and there is nothing
|
||||
-- to detect. It cannot wait on PLAYER_LOGIN either -- that has already fired
|
||||
-- on a `/reload`, so `ContinueOnPlayerLogin` would run the check immediately
|
||||
-- and see the same empty table. The addon load pass is synchronous, so the
|
||||
-- next frame is after every non-demand addon has registered, on a cold login
|
||||
-- and on a reload alike. An addon that loads on demand later keeps its own
|
||||
-- entry and the coin flip with it.
|
||||
|
||||
-- The command strings a SlashCmdList key answers to, upper-cased the way
|
||||
-- `ChatEdit_ParseText` compares them.
|
||||
local function CommandStrings(key)
|
||||
local commands = {};
|
||||
local i = 1;
|
||||
while ( _G["SLASH_"..key..i] ) do
|
||||
commands[strupper(_G["SLASH_"..key..i])] = true;
|
||||
i = i + 1;
|
||||
end
|
||||
return commands;
|
||||
end
|
||||
|
||||
local addedKeys = {};
|
||||
local addedHandlers = {};
|
||||
local addedCommands = {};
|
||||
for key, handler in pairs(SlashCmdList) do
|
||||
if ( not preexistingKeys[key] ) then
|
||||
addedKeys[key] = true;
|
||||
addedHandlers[key] = handler;
|
||||
addedCommands[key] = CommandStrings(key);
|
||||
end
|
||||
end
|
||||
|
||||
local function ClaimedElsewhere(key, commands)
|
||||
for otherKey in pairs(SlashCmdList) do
|
||||
if ( otherKey ~= key and not addedKeys[otherKey] ) then
|
||||
local i = 1;
|
||||
while ( _G["SLASH_"..otherKey..i] ) do
|
||||
if ( commands[strupper(_G["SLASH_"..otherKey..i])] ) then
|
||||
return true;
|
||||
end
|
||||
i = i + 1;
|
||||
end
|
||||
end
|
||||
end
|
||||
return false;
|
||||
end
|
||||
|
||||
RunNextFrame(function()
|
||||
for key in pairs(addedKeys) do
|
||||
if ( SlashCmdList[key] == addedHandlers[key]
|
||||
and ClaimedElsewhere(key, addedCommands[key]) ) then
|
||||
SlashCmdList[key] = nil;
|
||||
if ( key == "CASTSEQUENCE" ) then
|
||||
-- The sequence is theirs to advance now, so stop reporting a
|
||||
-- step to the macro icon that we no longer track.
|
||||
castSequenceOwned = false;
|
||||
end
|
||||
end
|
||||
end
|
||||
end)
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
-- The closed world map follows the player's zone, as the 3.x UI keeps it.
|
||||
--
|
||||
-- GetPlayerMapPosition("player") answers for whichever map the world map is
|
||||
-- set to, open or not, and returns 0,0 when the player isn't on that map.
|
||||
-- The 3.x FrameXML puts the map back on the player's zone whenever it is out
|
||||
-- of view: WorldMapFrame_OnHide ends with SetMapToCurrentZone(), and
|
||||
-- WatchFrame calls it on PLAYER_ENTERING_WORLD and, while the map is closed,
|
||||
-- on ZONE_CHANGED_NEW_AREA. Vanilla has no WatchFrame and doesn't reset the
|
||||
-- map when it closes, so after the player changes zones - or browses another
|
||||
-- zone and closes the map - the closed map stays on that other zone, and code
|
||||
-- written for 3.x that reads the player's position without setting the map
|
||||
-- first gets 0,0 (Zygor Guides Viewer's travel steps never complete).
|
||||
--
|
||||
-- WatchFrame skips the zone-change reset while "Show quest objectives on the
|
||||
-- map" is off; vanilla has no such option (the reset fed the tracker's POIs),
|
||||
-- so here it always runs.
|
||||
|
||||
local frame = CreateFrame("Frame")
|
||||
frame:RegisterEvent("PLAYER_ENTERING_WORLD")
|
||||
frame:RegisterEvent("ZONE_CHANGED_NEW_AREA")
|
||||
frame:SetScript("OnEvent", function(self, ev)
|
||||
ev = ev or event
|
||||
if ev == "ZONE_CHANGED_NEW_AREA" and WorldMapFrame:IsShown() then
|
||||
return
|
||||
end
|
||||
SetMapToCurrentZone()
|
||||
end)
|
||||
|
||||
WorldMapFrame:HookScript("OnHide", function()
|
||||
SetMapToCurrentZone()
|
||||
end)
|
||||
@@ -1,7 +1,12 @@
|
||||
if GetLocale() ~= "deDE" then return end
|
||||
|
||||
ACTION_BUTTON_USE_KEY_DOWN = "Aktionen werden beim Drücken von\nTasten ausgelöst";
|
||||
ACTION_TARGETING_OPTION = "Zielerfassung für Aktionen aktivieren";
|
||||
BINDING_NAME_FOCUSTARGET = "Fokus setzen";
|
||||
BINDING_NAME_INTERACTMOUSEOVER = "Mit Mouseover interagieren";
|
||||
BINDING_NAME_INTERACTTARGET = "Mit Ziel interagieren";
|
||||
BINDING_NAME_TARGETFOCUS = "Fokus anvisieren";
|
||||
COMBAT_LABEL = "Kampf";
|
||||
CONFIRM_DELETE_EQUIPMENT_SET = "Seid Ihr sicher, dass Ihr das Ausrüstungsset \"%s\" löschen wollt?";
|
||||
CONFIRM_SAVE_EQUIPMENT_SET = "Möchtet Ihr das Ausrüstungsset \"%s\" speichern?";
|
||||
DEBUFF_SYMBOL_CURSE = "Fl";
|
||||
@@ -9,6 +14,7 @@ DEBUFF_SYMBOL_DISEASE = "Kr";
|
||||
DEBUFF_SYMBOL_MAGIC = "Ma";
|
||||
DEBUFF_SYMBOL_POISON = "Gi";
|
||||
DEBUG_FRAMESTACK = "Frame Stack";
|
||||
ENABLE_INTERACT_TEXT = "Interaktionstaste aktivieren";
|
||||
EQUIPMENT_MANAGER = "Ausrüstungsmanager";
|
||||
EQUIPMENT_MANAGER_IGNORE_SLOT = "Diesen Platz ignorieren";
|
||||
EQUIPMENT_MANAGER_IS_DISABLED = "Der Ausrüstungsmanager ist abgeschaltet.";
|
||||
@@ -26,6 +32,15 @@ ERR_EQUIPMENT_MANAGER_BAGS_FULL = "Ausrüstungstausch fehlgeschlagen. Inventar i
|
||||
ERR_EQUIPMENT_MANAGER_COMBAT_SWAP_S = "Einige Gegenstände des Sets '%s' können nicht gewechselt werden, da Ihr Euch im Kampf befindet.";
|
||||
ERR_EQUIPMENT_MANAGER_MISSING_ITEM_S = "Mindestens ein Teil des Sets '%s' fehlt und kann nicht ausgerüstet werden.";
|
||||
CLEAR_FOCUS = "Fokus löschen";
|
||||
INTERACT_ICONS_DEFAULT = "Nur NSCs (Standard)";
|
||||
INTERACT_ICONS_OPTION = "Interaktionstastensymbole";
|
||||
INTERACT_ICONS_SHOW_ALL = "Alles anzeigen";
|
||||
INTERACT_ICONS_SHOW_NONE = "Nichts anzeigen";
|
||||
OPTION_TOOLTIP_ACTION_BUTTON_USE_KEY_DOWN = "Vordefinierte Tastaturbelegungen für Aktionen reagieren bei gedrückter statt bei losgelassener Taste.";
|
||||
OPTION_TOOLTIP_ACTION_TARGETING = "Ein Zielerfassungssystem, das Gegner auf Grundlage Eurer Blickrichtung dynamisch anvisiert. Funktioniert im Zusammenspiel mit dem Standardzielerfassungssystem.";
|
||||
OPTION_TOOLTIP_ENABLE_INTERACT = "Erlaubt Interaktion mit NSCs und Objekten per Tastendruck";
|
||||
OPTION_TOOLTIP_INTERACT_ICONS = "Legt fest, welche Symbole über NSCs und Gegenständen angezeigt werden, wenn die Interaktionstastenfunktion aktiviert ist.";
|
||||
OPTION_TOOLTIP_STOP_AUTO_ATTACK = "Automatischen Angriff stoppen, sobald das Ziel gewechselt wird.";
|
||||
SET_FOCUS = "Fokus setzen";
|
||||
FOCUSTARGET = "Ziel als Fokus festlegen";
|
||||
GEARSETS_POPUP_TEXT = "Setnamen eingeben (Max. 16 Zeichen):";
|
||||
@@ -35,6 +50,7 @@ ITEMS_IN_INVENTORY = "%d |4Gegenstand:Gegenstände; im Inventar";
|
||||
ITEM_SLOTS_IGNORED = "%d |4Platz:Plätze; ignoriert";
|
||||
ITEM_MISSING = "%s fehlt";
|
||||
ITEMS_NOT_IN_INVENTORY = "%d |4Gegenstand fehlt:Gegenstände fehlen;";
|
||||
STOP_AUTO_ATTACK = "Autom. Angriff stoppen";
|
||||
TARGETFOCUS = "Fokussierte Einheit anvisieren";
|
||||
-- BINDING_NAME_AOELOOT = "AoE Loot";
|
||||
COPPER_AMOUNT_SYMBOL = "K";
|
||||
@@ -69,6 +85,15 @@ ITEM_MOD_DODGE_RATING_SHORT = "Ausweichen";
|
||||
ITEM_MOD_PARRY_RATING_SHORT = "Parieren";
|
||||
ITEM_MOD_BLOCK_RATING_SHORT = "Blocken";
|
||||
ITEM_MOD_BLOCK_VALUE_SHORT = "Blocken";
|
||||
ITEM_MOD_HOLY_SPELL_DAMAGE_DONE_SHORT = "Heiligzauberschaden";
|
||||
ITEM_MOD_FIRE_SPELL_DAMAGE_DONE_SHORT = "Feuerzauberschaden";
|
||||
ITEM_MOD_NATURE_SPELL_DAMAGE_DONE_SHORT = "Naturzauberschaden";
|
||||
ITEM_MOD_FROST_SPELL_DAMAGE_DONE_SHORT = "Frostzauberschaden";
|
||||
ITEM_MOD_SHADOW_SPELL_DAMAGE_DONE_SHORT = "Schattenzauberschaden";
|
||||
ITEM_MOD_ARCANE_SPELL_DAMAGE_DONE_SHORT = "Arkanzauberschaden";
|
||||
ITEM_MOD_SPELL_PENETRATION_SHORT = "Zauberdurchschlagskraft";
|
||||
ITEM_MOD_ARMOR_PENETRATION_RATING_SHORT = "Rüstungsdurchschlag";
|
||||
ITEM_MOD_HEALTH_REGEN_SHORT = "Gesundheitsregeneration";
|
||||
ITEM_MOD_DAMAGE_PER_SECOND_SHORT = "Schaden pro Sekunde";
|
||||
LARGE_NUMBER_SEPERATOR = ".";
|
||||
MINUTES_SECONDS = "%.2d:%.2d";
|
||||
@@ -147,3 +172,7 @@ SLASH_TARGET_NEAREST_RAID2 = "/targetraid";
|
||||
SLASH_USE1 = "/benutzen";
|
||||
SLASH_USE2 = "/use";
|
||||
LINK_TRADESKILL_TOOLTIP = "Hier klicken, um einen Link zu Eurem Beruf zu erstellen.";
|
||||
TEXT_TO_SPEECH = "Text-to-Speech";
|
||||
TEXT_TO_SPEECH_ADJUST_RATE = "Sprechgeschwindigkeit anpassen";
|
||||
TEXT_TO_SPEECH_ADJUST_VOLUME = "Sprechlautstärke";
|
||||
TEXT_TO_SPEECH_VOICE_OPTION = "Stimmenauswahl";
|
||||
|
||||
@@ -1,15 +1,22 @@
|
||||
ACTION_BUTTON_USE_KEY_DOWN = "Cast action keybinds on key down";
|
||||
ACTION_TARGETING_OPTION = "Enable Action Targeting";
|
||||
ADDON_OPTIONS = "AddOn Options";
|
||||
BINDING_NAME_AOELOOT = "AoE Loot";
|
||||
BINDING_NAME_FOCUSTARGET = "Focus Target";
|
||||
BINDING_NAME_INTERACTMOUSEOVER = "Interact With Mouseover";
|
||||
BINDING_NAME_INTERACTTARGET = "Interact With Target";
|
||||
BINDING_NAME_TARGETFOCUS = "Target Focus";
|
||||
COMBAT_LABEL = "Combat";
|
||||
CONFIRM_DELETE_EQUIPMENT_SET = "Are you sure you want to delete the equipment set %s?";
|
||||
CONFIRM_SAVE_EQUIPMENT_SET = "Would you like to save the equipment set \"%s\"?";
|
||||
COPPER_AMOUNT_SYMBOL = "c";
|
||||
COPPER_AMOUNT_TEXTURE = "%d|TInterface\\MoneyFrame\\UI-MoneyIcons:%d:%d:0:0:4:1:2:3:0:1|t";
|
||||
COPPER_AMOUNT_TEXTURE = "%d|TInterface\\MoneyFrame\\UI-MoneyIcons:%d:%d:2:0:4:1:2:3:0:1|t";
|
||||
DEBUFF_SYMBOL_CURSE = "Cu";
|
||||
DEBUFF_SYMBOL_DISEASE = "Di";
|
||||
DEBUFF_SYMBOL_MAGIC = "Ma";
|
||||
DEBUFF_SYMBOL_POISON = "Po";
|
||||
DEBUG_FRAMESTACK = "Frame Stack";
|
||||
ENABLE_INTERACT_TEXT = "Enable Interact Key";
|
||||
EQUIPMENT_MANAGER = "Equipment Manager";
|
||||
EQUIPMENT_MANAGER_IGNORE_SLOT = "Ignore This Slot";
|
||||
EQUIPMENT_MANAGER_IS_DISABLED = "The Equipment Manager is disabled.";
|
||||
@@ -27,13 +34,23 @@ ERR_EQUIPMENT_MANAGER_BAGS_FULL = "Equipment swap failed. Inventory is full.";
|
||||
ERR_EQUIPMENT_MANAGER_COMBAT_SWAP_S = "Some items from set %s cannot be swapped because you are in combat.";
|
||||
ERR_EQUIPMENT_MANAGER_MISSING_ITEM_S = "One or more items from set %s were missing and could not be equipped.";
|
||||
CLEAR_FOCUS = "Clear Focus";
|
||||
INTERACT_ICONS_DEFAULT = "NPCs Only (Default)";
|
||||
INTERACT_ICONS_OPTION = "Interact Key Icons";
|
||||
INTERACT_ICONS_SHOW_ALL = "Show All";
|
||||
INTERACT_ICONS_SHOW_NONE = "Show None";
|
||||
OPTION_TOOLTIP_ACTION_BUTTON_USE_KEY_DOWN = "Action button keybinds will respond on key down, rather than on key up.";
|
||||
OPTION_TOOLTIP_ACTION_TARGETING = "A targeting system that dynamically targets enemies based on where you're looking. Works alongside the standard targeting system.";
|
||||
OPTION_TOOLTIP_ENABLE_INTERACT = "Allows you to interact with NPCs and objects using a keypress";
|
||||
OPTION_TOOLTIP_INTERACT_ICONS = "Controls which icons appear above NPCs and objects when the Interact Key feature is enabled";
|
||||
OPTION_TOOLTIP_STOP_AUTO_ATTACK = "Stop auto attacking when you switch targets.";
|
||||
SET_FOCUS = "Set Focus";
|
||||
FOCUS_TOKEN_NOT_FOUND = "<no focus>";
|
||||
FOCUSTARGET = "Focus Target";
|
||||
GEARSETS_POPUP_TEXT = "Enter Set Name (Max 16 Characters):";
|
||||
GENERIC_FRACTION_STRING = "%d/%d";
|
||||
GOLD_AMOUNT_SYMBOL = "g";
|
||||
GOLD_AMOUNT_TEXTURE = "%d|TInterface\\MoneyFrame\\UI-MoneyIcons:%d:%d:0:0:4:1:0:1:0:1|t";
|
||||
GOLD_AMOUNT_TEXTURE_STRING = "%s|TInterface\\MoneyFrame\\UI-MoneyIcons:%d:%d:0:0:4:1:0:1:0:1|t";
|
||||
GOLD_AMOUNT_TEXTURE = "%d|TInterface\\MoneyFrame\\UI-MoneyIcons:%d:%d:2:0:4:1:0:1:0:1|t";
|
||||
GOLD_AMOUNT_TEXTURE_STRING = "%s|TInterface\\MoneyFrame\\UI-MoneyIcons:%d:%d:2:0:4:1:0:1:0:1|t";
|
||||
HOURS_MINUTES_SECONDS = "%.2d:%.2d:%.2d";
|
||||
ICON_FILTER_ALL = "All Icons";
|
||||
ICON_FILTER_ITEM = "Items";
|
||||
@@ -63,6 +80,15 @@ ITEM_MOD_DODGE_RATING_SHORT = "Dodge";
|
||||
ITEM_MOD_PARRY_RATING_SHORT = "Parry";
|
||||
ITEM_MOD_BLOCK_RATING_SHORT = "Block";
|
||||
ITEM_MOD_BLOCK_VALUE_SHORT = "Block Value";
|
||||
ITEM_MOD_HOLY_SPELL_DAMAGE_DONE_SHORT = "Holy Spell Damage";
|
||||
ITEM_MOD_FIRE_SPELL_DAMAGE_DONE_SHORT = "Fire Spell Damage";
|
||||
ITEM_MOD_NATURE_SPELL_DAMAGE_DONE_SHORT = "Nature Spell Damage";
|
||||
ITEM_MOD_FROST_SPELL_DAMAGE_DONE_SHORT = "Frost Spell Damage";
|
||||
ITEM_MOD_SHADOW_SPELL_DAMAGE_DONE_SHORT = "Shadow Spell Damage";
|
||||
ITEM_MOD_ARCANE_SPELL_DAMAGE_DONE_SHORT = "Arcane Spell Damage";
|
||||
ITEM_MOD_SPELL_PENETRATION_SHORT = "Spell Penetration";
|
||||
ITEM_MOD_ARMOR_PENETRATION_RATING_SHORT = "Armor Penetration";
|
||||
ITEM_MOD_HEALTH_REGEN_SHORT = "Health Regeneration";
|
||||
ITEM_MOD_DAMAGE_PER_SECOND_SHORT = "Damage Per Second";
|
||||
ITEMS_EQUIPPED = "%d |4item:items; equipped";
|
||||
ITEMS_IN_INVENTORY = "%d |4item:items; in inventory";
|
||||
@@ -75,10 +101,11 @@ MINUTES_SECONDS = "%.2d:%.2d";
|
||||
PAPERDOLL_EQUIPMENTMANAGER = "Equipment Manager";
|
||||
PAPERDOLL_NEWEQUIPMENTSET = "New Set";
|
||||
PERCENTAGE_STRING = "%d%%";
|
||||
PLAYER_LIST_DELIMITER = ", ";
|
||||
SET_FRIENDNOTE_LABEL = "Set Notes for %s:";
|
||||
SET_NOTE = "Set Note";
|
||||
SILVER_AMOUNT_SYMBOL = "s";
|
||||
SILVER_AMOUNT_TEXTURE = "%d|TInterface\\MoneyFrame\\UI-MoneyIcons:%d:%d:0:0:4:1:1:2:0:1|t";
|
||||
SILVER_AMOUNT_TEXTURE = "%d|TInterface\\MoneyFrame\\UI-MoneyIcons:%d:%d:2:0:4:1:1:2:0:1|t";
|
||||
SLASH_CANCELAURA1 = "/cancelaura";
|
||||
SLASH_CANCELAURA2 = "/cancelaura";
|
||||
SLASH_CANCELFORM1 = "/cancelform";
|
||||
@@ -147,5 +174,10 @@ SLASH_TARGET_NEAREST_RAID1 = "/targetraid";
|
||||
SLASH_TARGET_NEAREST_RAID2 = "/targetraid";
|
||||
SLASH_USE1 = "/use";
|
||||
SLASH_USE2 = "/use";
|
||||
STOP_AUTO_ATTACK = "Stop Auto Attack";
|
||||
TARGETFOCUS = "Target Focus";
|
||||
LINK_TRADESKILL_TOOLTIP = "Click here to create a link to your profession.";
|
||||
LINK_TRADESKILL_TOOLTIP = "Click here to create a link to your profession.";
|
||||
TEXT_TO_SPEECH = "Text To Speech";
|
||||
TEXT_TO_SPEECH_ADJUST_RATE = "Adjust Rate of Speech";
|
||||
TEXT_TO_SPEECH_ADJUST_VOLUME = "Speech Volume";
|
||||
TEXT_TO_SPEECH_VOICE_OPTION = "Voice Option";
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
if GetLocale() ~= "esES" then return end
|
||||
|
||||
ACTION_BUTTON_USE_KEY_DOWN = "Ejecutar acción al pulsar tecla";
|
||||
ACTION_TARGETING_OPTION = "Habilitar selección de objetivo de acción";
|
||||
BINDING_NAME_FOCUSTARGET = "Establecer objetivo";
|
||||
BINDING_NAME_INTERACTMOUSEOVER = "Interactuar al pasar el ratón";
|
||||
BINDING_NAME_INTERACTTARGET = "Interactuar con objetivo";
|
||||
BINDING_NAME_TARGETFOCUS = "Seleccionar enfocado";
|
||||
COMBAT_LABEL = "Combate";
|
||||
CONFIRM_DELETE_EQUIPMENT_SET = "¿Seguro que quieres eliminar el equipamiento %s?";
|
||||
CONFIRM_SAVE_EQUIPMENT_SET = "¿Quieres guardar el conjunto de equipamiento \"%s\"?";
|
||||
DEBUFF_SYMBOL_CURSE = "Mal";
|
||||
@@ -9,6 +14,7 @@ DEBUFF_SYMBOL_DISEASE = "En";
|
||||
DEBUFF_SYMBOL_MAGIC = "Mag";
|
||||
DEBUFF_SYMBOL_POISON = "Ve";
|
||||
DEBUG_FRAMESTACK = "Trama de pila";
|
||||
ENABLE_INTERACT_TEXT = "Habilitar tecla Interactuar";
|
||||
EQUIPMENT_MANAGER = "Gestor de equipamiento";
|
||||
EQUIPMENT_MANAGER_IGNORE_SLOT = "Ignorar esta casilla";
|
||||
EQUIPMENT_MANAGER_IS_DISABLED = "El Gestor de equipamiento está desactivado.";
|
||||
@@ -26,6 +32,15 @@ ERR_EQUIPMENT_MANAGER_BAGS_FULL = "No se ha podido cambiar el equipamiento. Inve
|
||||
ERR_EQUIPMENT_MANAGER_COMBAT_SWAP_S = "Algunos objetos del equipo %s no se cambiarán porque estás en combate.";
|
||||
ERR_EQUIPMENT_MANAGER_MISSING_ITEM_S = "Falta uno o más objetos del equipo %s y no se ha podido equipar.";
|
||||
CLEAR_FOCUS = "Quitar foco";
|
||||
INTERACT_ICONS_DEFAULT = "Solo PNJ (por defecto)";
|
||||
INTERACT_ICONS_OPTION = "Iconos de tecla Interactuar";
|
||||
INTERACT_ICONS_SHOW_ALL = "Mostrar todos";
|
||||
INTERACT_ICONS_SHOW_NONE = "No mostrar ninguno";
|
||||
OPTION_TOOLTIP_ACTION_BUTTON_USE_KEY_DOWN = "Los atajos de los botones de acción responderán al pulsar una tecla y no al soltarla.";
|
||||
OPTION_TOOLTIP_ACTION_TARGETING = "Un sistema de selección de objetivo que selecciona de forma dinámica a los enemigos en función de la dirección en la que mires. Funciona junto al sistema de selección de objetivos estándar.";
|
||||
OPTION_TOOLTIP_ENABLE_INTERACT = "Te permite interactuar con PNJ y objetos pulsando una tecla.";
|
||||
OPTION_TOOLTIP_INTERACT_ICONS = "Controla los iconos que aparecen sobre los PNJ y objetos cuando se habilita la opción de tecla Interactuar";
|
||||
OPTION_TOOLTIP_STOP_AUTO_ATTACK = "Detiene el ataque automático al cambiar de objetivo.";
|
||||
SET_FOCUS = "Establecer foco";
|
||||
FOCUSTARGET = "Establecer objetivo";
|
||||
GEARSETS_POPUP_TEXT = "Nombra este equipamiento (Máx. 16 carac.):";
|
||||
@@ -35,6 +50,7 @@ ITEMS_IN_INVENTORY = "En inventario: %d |4objeto:objetos;";
|
||||
ITEM_SLOTS_IGNORED = "Ignorado: %d |4casilla:casillas;";
|
||||
ITEM_MISSING = "Falta: %s";
|
||||
ITEMS_NOT_IN_INVENTORY = "Faltan: %d |4objeto:objetos;";
|
||||
STOP_AUTO_ATTACK = "Detener ataque automático";
|
||||
TARGETFOCUS = "Fijar unidad objetivo";
|
||||
-- BINDING_NAME_AOELOOT = "AoE Loot";
|
||||
COPPER_AMOUNT_SYMBOL = "c";
|
||||
@@ -69,6 +85,15 @@ ITEM_MOD_DODGE_RATING_SHORT = "Esquiva";
|
||||
ITEM_MOD_PARRY_RATING_SHORT = "Parada";
|
||||
ITEM_MOD_BLOCK_RATING_SHORT = "Bloqueo";
|
||||
ITEM_MOD_BLOCK_VALUE_SHORT = "Valor de bloqueo";
|
||||
ITEM_MOD_HOLY_SPELL_DAMAGE_DONE_SHORT = "Daño de hechizos Sagrados";
|
||||
ITEM_MOD_FIRE_SPELL_DAMAGE_DONE_SHORT = "Daño de hechizos de Fuego";
|
||||
ITEM_MOD_NATURE_SPELL_DAMAGE_DONE_SHORT = "Daño de hechizos de Naturaleza";
|
||||
ITEM_MOD_FROST_SPELL_DAMAGE_DONE_SHORT = "Daño de hechizos de Escarcha";
|
||||
ITEM_MOD_SHADOW_SPELL_DAMAGE_DONE_SHORT = "Daño de hechizos de Sombras";
|
||||
ITEM_MOD_ARCANE_SPELL_DAMAGE_DONE_SHORT = "Daño de hechizos Arcanos";
|
||||
ITEM_MOD_SPELL_PENETRATION_SHORT = "Penetración de hechizos";
|
||||
ITEM_MOD_ARMOR_PENETRATION_RATING_SHORT = "Penetración de armadura";
|
||||
ITEM_MOD_HEALTH_REGEN_SHORT = "Regeneración de salud";
|
||||
ITEM_MOD_DAMAGE_PER_SECOND_SHORT = "daño por segundo";
|
||||
LARGE_NUMBER_SEPERATOR = "";
|
||||
MINUTES_SECONDS = "%.2d:%.2d";
|
||||
@@ -147,3 +172,7 @@ SLASH_TARGET_NEAREST_RAID2 = "/targetraid";
|
||||
SLASH_USE1 = "/use";
|
||||
SLASH_USE2 = "/usar";
|
||||
LINK_TRADESKILL_TOOLTIP = "Haz clic aquí para crear un vínculo a tu profesión.";
|
||||
TEXT_TO_SPEECH = "Texto a voz";
|
||||
TEXT_TO_SPEECH_ADJUST_RATE = "Ajustar velocidad de voz";
|
||||
TEXT_TO_SPEECH_ADJUST_VOLUME = "Volumen de voz";
|
||||
TEXT_TO_SPEECH_VOICE_OPTION = "Opción de voz";
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
if GetLocale() ~= "frFR" then return end
|
||||
|
||||
ACTION_BUTTON_USE_KEY_DOWN = "Enfoncer la touche déclenche l’action";
|
||||
ACTION_TARGETING_OPTION = "Activer le ciblage des actions";
|
||||
BINDING_NAME_FOCUSTARGET = "Définir cible";
|
||||
BINDING_NAME_INTERACTMOUSEOVER = "Interagir par survol de la souris";
|
||||
BINDING_NAME_INTERACTTARGET = "Interagir avec la cible";
|
||||
BINDING_NAME_TARGETFOCUS = "Reprendre cible";
|
||||
COMBAT_LABEL = "Combat";
|
||||
CONFIRM_DELETE_EQUIPMENT_SET = "Voulez-vous vraiment supprimer l'ensemble d'équipement %s ?";
|
||||
CONFIRM_SAVE_EQUIPMENT_SET = "Voulez-vous sauvegarder l'ensemble d'équipement %s ?";
|
||||
DEBUFF_SYMBOL_CURSE = "Mn";
|
||||
@@ -9,6 +14,7 @@ DEBUFF_SYMBOL_DISEASE = "Md";
|
||||
DEBUFF_SYMBOL_MAGIC = "Mg";
|
||||
DEBUFF_SYMBOL_POISON = "Po";
|
||||
DEBUG_FRAMESTACK = "Empilement des cadres";
|
||||
ENABLE_INTERACT_TEXT = "Activer la commande d’interaction";
|
||||
EQUIPMENT_MANAGER = "Gestionnaire d'équipement";
|
||||
EQUIPMENT_MANAGER_IGNORE_SLOT = "Ignorer cet emplacement";
|
||||
EQUIPMENT_MANAGER_IS_DISABLED = "Le Gestionnaire d'équipement est désactivé.";
|
||||
@@ -26,6 +32,15 @@ ERR_EQUIPMENT_MANAGER_BAGS_FULL = "Échec de l'échange d'équipement. L'inventa
|
||||
ERR_EQUIPMENT_MANAGER_COMBAT_SWAP_S = "Certains objets de l'ensemble %s ne peuvent pas être échangés car vous êtes en combat.";
|
||||
ERR_EQUIPMENT_MANAGER_MISSING_ITEM_S = "Une ou plusieurs pièces de l'ensemble %s manquaient et n'ont pu être équipées.";
|
||||
CLEAR_FOCUS = "Effacer la focalisation";
|
||||
INTERACT_ICONS_DEFAULT = "PNJ uniquement (Par défaut)";
|
||||
INTERACT_ICONS_OPTION = "Icônes de commande d’interaction";
|
||||
INTERACT_ICONS_SHOW_ALL = "Tout afficher";
|
||||
INTERACT_ICONS_SHOW_NONE = "Ne rien afficher";
|
||||
OPTION_TOOLTIP_ACTION_BUTTON_USE_KEY_DOWN = "Les boutons d’action associés à un raccourci clavier se déclencheront au moment où la touche est enfoncée, et non relâchée.";
|
||||
OPTION_TOOLTIP_ACTION_TARGETING = "Un système de ciblage qui vise en temps réel les adversaires en fonction de l’endroit où vous regardez. Fonctionne en parallèle du système de ciblage standard.";
|
||||
OPTION_TOOLTIP_ENABLE_INTERACT = "Vous permet d’interagir avec les PNJ et les objets en appuyant sur une touche";
|
||||
OPTION_TOOLTIP_INTERACT_ICONS = "Contrôle les icônes qui s’affichent au-dessus des PNJ et des objets quand la fonction Commande d’interaction est activée";
|
||||
OPTION_TOOLTIP_STOP_AUTO_ATTACK = "Interrompt l'attaque automatique lorsque vous changez de cible.";
|
||||
SET_FOCUS = "Définir la focalisation";
|
||||
FOCUSTARGET = "Définir la cible de focalisation";
|
||||
ITEMS_VARIABLE_QUANTITY = "%d |4objet:objets;";
|
||||
@@ -34,6 +49,7 @@ ITEMS_IN_INVENTORY = "%d |4objet:objets; dans l'inventaire";
|
||||
ITEM_SLOTS_IGNORED = "%d |4emplacement ignoré:emplacements ignorés;";
|
||||
ITEM_MISSING = "Objet manquant : %s";
|
||||
ITEMS_NOT_IN_INVENTORY = "%d |4objet:objets; manquants";
|
||||
STOP_AUTO_ATTACK = "Interrompre attaque auto.";
|
||||
TARGETFOCUS = "Cibler l'unité focalisée";
|
||||
-- BINDING_NAME_AOELOOT = "AoE Loot";
|
||||
COPPER_AMOUNT_SYMBOL = "c";
|
||||
@@ -69,6 +85,15 @@ ITEM_MOD_DODGE_RATING_SHORT = "Esquive";
|
||||
ITEM_MOD_PARRY_RATING_SHORT = "Parade";
|
||||
ITEM_MOD_BLOCK_RATING_SHORT = "Blocage";
|
||||
ITEM_MOD_BLOCK_VALUE_SHORT = "Valeur de blocage";
|
||||
ITEM_MOD_HOLY_SPELL_DAMAGE_DONE_SHORT = "Dégâts du Sacré";
|
||||
ITEM_MOD_FIRE_SPELL_DAMAGE_DONE_SHORT = "Dégâts de Feu";
|
||||
ITEM_MOD_NATURE_SPELL_DAMAGE_DONE_SHORT = "Dégâts de Nature";
|
||||
ITEM_MOD_FROST_SPELL_DAMAGE_DONE_SHORT = "Dégâts de Givre";
|
||||
ITEM_MOD_SHADOW_SPELL_DAMAGE_DONE_SHORT = "Dégâts d'Ombre";
|
||||
ITEM_MOD_ARCANE_SPELL_DAMAGE_DONE_SHORT = "Dégâts des Arcanes";
|
||||
ITEM_MOD_SPELL_PENETRATION_SHORT = "Pénétration des sorts";
|
||||
ITEM_MOD_ARMOR_PENETRATION_RATING_SHORT = "Pénétration d'armure";
|
||||
ITEM_MOD_HEALTH_REGEN_SHORT = "Régénération des points de vie";
|
||||
ITEM_MOD_DAMAGE_PER_SECOND_SHORT = "Dégâts par seconde";
|
||||
LARGE_NUMBER_SEPERATOR = "";
|
||||
MINUTES_SECONDS = "%.2d:%.2d";
|
||||
@@ -147,3 +172,7 @@ SLASH_TARGET_NEAREST_RAID2 = "/targetraid";
|
||||
SLASH_USE1 = "/use";
|
||||
SLASH_USE2 = "/utiliser";
|
||||
LINK_TRADESKILL_TOOLTIP = "Cliquez ici pour créer un lien vers votre profession.";
|
||||
TEXT_TO_SPEECH = "Narrateur";
|
||||
TEXT_TO_SPEECH_ADJUST_RATE = "Modifie la vitesse de la voix";
|
||||
TEXT_TO_SPEECH_ADJUST_VOLUME = "Volume de la voix";
|
||||
TEXT_TO_SPEECH_VOICE_OPTION = "Option vocale";
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
if GetLocale() ~= "ruRU" then return end
|
||||
|
||||
ACTION_BUTTON_USE_KEY_DOWN = "Способности при нажатии клавиш";
|
||||
ACTION_TARGETING_OPTION = "Разрешить динамическое выделение";
|
||||
BINDING_NAME_FOCUSTARGET = "Запомненная цель";
|
||||
BINDING_NAME_INTERACTMOUSEOVER = "Взаимодействовать указателем мыши";
|
||||
BINDING_NAME_INTERACTTARGET = "Взаимодействовать с целью";
|
||||
BINDING_NAME_TARGETFOCUS = "Восстановить цель";
|
||||
COMBAT_LABEL = "Бой";
|
||||
CONFIRM_DELETE_EQUIPMENT_SET = "Вы действительно хотите удалить комплект экипировки \"%s\"?";
|
||||
CONFIRM_SAVE_EQUIPMENT_SET = "Хотите сохранить комплект экипировки \"%s\"?";
|
||||
DEBUFF_SYMBOL_CURSE = "Пр";
|
||||
@@ -9,6 +14,7 @@ DEBUFF_SYMBOL_DISEASE = "Бз";
|
||||
DEBUFF_SYMBOL_MAGIC = "Мг";
|
||||
DEBUFF_SYMBOL_POISON = "Яд";
|
||||
DEBUG_FRAMESTACK = "Соединение рамок";
|
||||
ENABLE_INTERACT_TEXT = "Включить клавишу взаимодействия";
|
||||
EQUIPMENT_MANAGER = "Комплекты экипировки";
|
||||
EQUIPMENT_MANAGER_IGNORE_SLOT = "Пропустить ячейку";
|
||||
EQUIPMENT_MANAGER_IS_DISABLED = "Управление экипировкой отключено.";
|
||||
@@ -26,6 +32,15 @@ ERR_EQUIPMENT_MANAGER_BAGS_FULL = "Не удалось заменить комп
|
||||
ERR_EQUIPMENT_MANAGER_COMBAT_SWAP_S = "Некоторые предметы из набора \"%s\" не будут экипированы, поскольку вы участвуете в бою.";
|
||||
ERR_EQUIPMENT_MANAGER_MISSING_ITEM_S = "Недостает одного или более предметов из набора \"%s\".";
|
||||
CLEAR_FOCUS = "Отменить запоминание цели";
|
||||
INTERACT_ICONS_DEFAULT = "Только NPC (по умолчанию)";
|
||||
INTERACT_ICONS_OPTION = "Значки клавиш взаимодействия";
|
||||
INTERACT_ICONS_SHOW_ALL = "Показать все";
|
||||
INTERACT_ICONS_SHOW_NONE = "Не показывать";
|
||||
OPTION_TOOLTIP_ACTION_BUTTON_USE_KEY_DOWN = "Способности будут задействоваться, когда пользователь нажимает, а не отпускает клавишу.";
|
||||
OPTION_TOOLTIP_ACTION_TARGETING = "Система захвата целей, динамически выбирающая цели в поле зрения. Работает параллельно со стандартной системой наведения.";
|
||||
OPTION_TOOLTIP_ENABLE_INTERACT = "Позволяет взаимодействовать с NPC и объектами по нажатию клавиши.";
|
||||
OPTION_TOOLTIP_INTERACT_ICONS = "Определяет, какие значки появляются над NPC и объектами, если включен параметр клавиши взаимодействия.";
|
||||
OPTION_TOOLTIP_STOP_AUTO_ATTACK = "Прекращение автоматической атаки при смене цели.";
|
||||
SET_FOCUS = "Запомнить цель";
|
||||
FOCUSTARGET = "Запомнить цель";
|
||||
ITEMS_VARIABLE_QUANTITY = "%d |4предмет:предмета:предметов;";
|
||||
@@ -34,6 +49,7 @@ ITEMS_IN_INVENTORY = "%d |4предмет:предмета:предметов;
|
||||
ITEM_SLOTS_IGNORED = "%d |4ячейка пропущена:ячейки пропущены:ячейки пропущены;";
|
||||
ITEM_MISSING = "Предмет для ячейки %s отсутствует";
|
||||
ITEMS_NOT_IN_INVENTORY = "%d |4предмет отсутствует:предмета отсутствует:предметов отсутствуют;";
|
||||
STOP_AUTO_ATTACK = "Прекращение автоатаки";
|
||||
TARGETFOCUS = "Восстановить цель";
|
||||
-- BINDING_NAME_AOELOOT = "AoE Loot";
|
||||
COPPER_AMOUNT_SYMBOL = "м";
|
||||
@@ -69,6 +85,15 @@ ITEM_MOD_DODGE_RATING_SHORT = "Уклонение";
|
||||
ITEM_MOD_PARRY_RATING_SHORT = "Парирование";
|
||||
ITEM_MOD_BLOCK_RATING_SHORT = "Блок";
|
||||
ITEM_MOD_BLOCK_VALUE_SHORT = "к показателю блокирования";
|
||||
ITEM_MOD_HOLY_SPELL_DAMAGE_DONE_SHORT = "к урону от магии света";
|
||||
ITEM_MOD_FIRE_SPELL_DAMAGE_DONE_SHORT = "к урону от магии огня";
|
||||
ITEM_MOD_NATURE_SPELL_DAMAGE_DONE_SHORT = "к урону от сил природы";
|
||||
ITEM_MOD_FROST_SPELL_DAMAGE_DONE_SHORT = "к урону от магии льда";
|
||||
ITEM_MOD_SHADOW_SPELL_DAMAGE_DONE_SHORT = "к урону от темной магии";
|
||||
ITEM_MOD_ARCANE_SPELL_DAMAGE_DONE_SHORT = "к урону от тайной магии";
|
||||
ITEM_MOD_SPELL_PENETRATION_SHORT = "к проникающей способности заклинаний";
|
||||
ITEM_MOD_ARMOR_PENETRATION_RATING_SHORT = "к пробиванию брони";
|
||||
ITEM_MOD_HEALTH_REGEN_SHORT = "к восполнению здоровья";
|
||||
ITEM_MOD_DAMAGE_PER_SECOND_SHORT = "к урону в секунду";
|
||||
LARGE_NUMBER_SEPERATOR = "";
|
||||
MINUTES_SECONDS = "%.2d:%.2d";
|
||||
@@ -147,3 +172,7 @@ SLASH_TARGET_NEAREST_RAID2 = "/targetraid";
|
||||
SLASH_USE1 = "/use";
|
||||
SLASH_USE2 = "/использовать";
|
||||
LINK_TRADESKILL_TOOLTIP = "Щелкните здесь, чтобы создать ссылку на вашу профессию.";
|
||||
TEXT_TO_SPEECH = "Текст в речь";
|
||||
TEXT_TO_SPEECH_ADJUST_RATE = "Изменить скорость речи.";
|
||||
TEXT_TO_SPEECH_ADJUST_VOLUME = "Громкость речи";
|
||||
TEXT_TO_SPEECH_VOICE_OPTION = "Параметры голоса";
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
if GetLocale() ~= "zhCN" then return end
|
||||
|
||||
ACTION_BUTTON_USE_KEY_DOWN = "按下快捷键时施法";
|
||||
ACTION_TARGETING_OPTION = "开启动作瞄准";
|
||||
BINDING_NAME_FOCUSTARGET = "焦点目标";
|
||||
BINDING_NAME_INTERACTMOUSEOVER = "与鼠标悬停处互动";
|
||||
BINDING_NAME_INTERACTTARGET = "与目标互动";
|
||||
BINDING_NAME_TARGETFOCUS = "目标焦点";
|
||||
COMBAT_LABEL = "战斗";
|
||||
CONFIRM_DELETE_EQUIPMENT_SET = "你确认要删除装备方案%s吗?";
|
||||
CONFIRM_SAVE_EQUIPMENT_SET = "你想要保存装备方案\"%s\"吗?";
|
||||
DEBUFF_SYMBOL_CURSE = "诅";
|
||||
@@ -9,6 +14,7 @@ DEBUFF_SYMBOL_DISEASE = "疾";
|
||||
DEBUFF_SYMBOL_MAGIC = "魔";
|
||||
DEBUFF_SYMBOL_POISON = "毒";
|
||||
DEBUG_FRAMESTACK = "框架栈";
|
||||
ENABLE_INTERACT_TEXT = "开启交互按键";
|
||||
EQUIPMENT_MANAGER = "装备管理";
|
||||
EQUIPMENT_MANAGER_IGNORE_SLOT = "忽略此栏位";
|
||||
EQUIPMENT_MANAGER_IS_DISABLED = "装备管理已禁用。";
|
||||
@@ -26,6 +32,15 @@ ERR_EQUIPMENT_MANAGER_BAGS_FULL = "装备更换失败。背包已满。";
|
||||
ERR_EQUIPMENT_MANAGER_COMBAT_SWAP_S = "装备方案%s中的某些物品不能在战斗中切换。";
|
||||
ERR_EQUIPMENT_MANAGER_MISSING_ITEM_S = "未找到套装方案%s中的一件或多件物品,无法装备。";
|
||||
CLEAR_FOCUS = "清除焦点";
|
||||
INTERACT_ICONS_DEFAULT = "仅限NPC(默认)";
|
||||
INTERACT_ICONS_OPTION = "交互按键图标";
|
||||
INTERACT_ICONS_SHOW_ALL = "显示全部";
|
||||
INTERACT_ICONS_SHOW_NONE = "全不显示";
|
||||
OPTION_TOOLTIP_ACTION_BUTTON_USE_KEY_DOWN = "在按下快捷键时施法,而不是在松开快捷键时施法。";
|
||||
OPTION_TOOLTIP_ACTION_TARGETING = "此瞄准系统可以以你观看的方向动态地瞄准敌人。可以和标准的瞄准系统一起使用。";
|
||||
OPTION_TOOLTIP_ENABLE_INTERACT = "使你可以通过按键与NPC和物体进行交互";
|
||||
OPTION_TOOLTIP_INTERACT_ICONS = "控制交互按键启用后NPC和物体上方出现的图标";
|
||||
OPTION_TOOLTIP_STOP_AUTO_ATTACK = "当你切换目标时停止自动攻击。";
|
||||
SET_FOCUS = "设置焦点";
|
||||
FOCUSTARGET = "设定焦点目标";
|
||||
ITEMS_VARIABLE_QUANTITY = "%d件物品";
|
||||
@@ -34,6 +49,7 @@ ITEMS_IN_INVENTORY = "背包中有%d件物品";
|
||||
ITEM_SLOTS_IGNORED = "忽略%d个栏位";
|
||||
ITEM_MISSING = "%s缺失";
|
||||
ITEMS_NOT_IN_INVENTORY = "缺少%d件物品";
|
||||
STOP_AUTO_ATTACK = "停止自动攻击";
|
||||
TARGETFOCUS = "选中焦点目标";
|
||||
-- BINDING_NAME_AOELOOT = "AoE Loot";
|
||||
COPPER_AMOUNT_SYMBOL = "铜";
|
||||
@@ -69,6 +85,15 @@ ITEM_MOD_DODGE_RATING_SHORT = "躲闪";
|
||||
ITEM_MOD_PARRY_RATING_SHORT = "招架";
|
||||
ITEM_MOD_BLOCK_RATING_SHORT = "格挡";
|
||||
ITEM_MOD_BLOCK_VALUE_SHORT = "格挡值";
|
||||
ITEM_MOD_HOLY_SPELL_DAMAGE_DONE_SHORT = "神圣伤害加成";
|
||||
ITEM_MOD_FIRE_SPELL_DAMAGE_DONE_SHORT = "火焰伤害加成";
|
||||
ITEM_MOD_NATURE_SPELL_DAMAGE_DONE_SHORT = "自然伤害加成";
|
||||
ITEM_MOD_FROST_SPELL_DAMAGE_DONE_SHORT = "冰霜伤害加成";
|
||||
ITEM_MOD_SHADOW_SPELL_DAMAGE_DONE_SHORT = "暗影伤害加成";
|
||||
ITEM_MOD_ARCANE_SPELL_DAMAGE_DONE_SHORT = "奥术伤害加成";
|
||||
ITEM_MOD_SPELL_PENETRATION_SHORT = "法术穿透";
|
||||
ITEM_MOD_ARMOR_PENETRATION_RATING_SHORT = "护甲穿透";
|
||||
ITEM_MOD_HEALTH_REGEN_SHORT = "生命值恢复";
|
||||
ITEM_MOD_DAMAGE_PER_SECOND_SHORT = "每秒伤害";
|
||||
LARGE_NUMBER_SEPERATOR = ",";
|
||||
MINUTES_SECONDS = "%.2d:%.2d";
|
||||
@@ -147,3 +172,7 @@ SLASH_TARGET_NEAREST_RAID2 = "/targetraid";
|
||||
SLASH_USE1 = "/use";
|
||||
SLASH_USE2 = "/use";
|
||||
LINK_TRADESKILL_TOOLTIP = "点击这里以创建一个链接到你的专业的快捷方式。";
|
||||
TEXT_TO_SPEECH = "文本转语音";
|
||||
TEXT_TO_SPEECH_ADJUST_RATE = "调节讲话速度";
|
||||
TEXT_TO_SPEECH_ADJUST_VOLUME = "音量";
|
||||
TEXT_TO_SPEECH_VOICE_OPTION = "语音设置";
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
if GetLocale() ~= "zhTW" then return end
|
||||
|
||||
ACTION_BUTTON_USE_KEY_DOWN = "於按下按鍵時施放技能";
|
||||
ACTION_TARGETING_OPTION = "啟用行動鎖定";
|
||||
BINDING_NAME_FOCUSTARGET = "鎖定目標";
|
||||
BINDING_NAME_INTERACTMOUSEOVER = "與滑鼠指定的目標互動";
|
||||
BINDING_NAME_INTERACTTARGET = "與目標互動";
|
||||
BINDING_NAME_TARGETFOCUS = "選定鎖定目標";
|
||||
COMBAT_LABEL = "戰鬥";
|
||||
CONFIRM_DELETE_EQUIPMENT_SET = "你確定要刪除裝備設定:%s嗎?";
|
||||
CONFIRM_SAVE_EQUIPMENT_SET = "你想要儲存裝備設定「%s」嗎?";
|
||||
DEBUFF_SYMBOL_CURSE = "咒";
|
||||
@@ -9,6 +14,7 @@ DEBUFF_SYMBOL_DISEASE = "疾";
|
||||
DEBUFF_SYMBOL_MAGIC = "魔";
|
||||
DEBUFF_SYMBOL_POISON = "毒";
|
||||
DEBUG_FRAMESTACK = "框架堆疊";
|
||||
ENABLE_INTERACT_TEXT = "啟用互動鍵";
|
||||
EQUIPMENT_MANAGER = "裝備管理員";
|
||||
EQUIPMENT_MANAGER_IGNORE_SLOT = "忽略此欄位";
|
||||
EQUIPMENT_MANAGER_IS_DISABLED = "裝備管理員已關閉。";
|
||||
@@ -26,6 +32,15 @@ ERR_EQUIPMENT_MANAGER_BAGS_FULL = "裝備切換失敗。物品欄已滿。";
|
||||
ERR_EQUIPMENT_MANAGER_COMBAT_SWAP_S = "%s設定中的某些物品必須等到你脫離戰鬥後才能更換。";
|
||||
ERR_EQUIPMENT_MANAGER_MISSING_ITEM_S = "%s設定中的一個或多個物品未尋獲,因此無法裝備。";
|
||||
CLEAR_FOCUS = "清除專注目標";
|
||||
INTERACT_ICONS_DEFAULT = "僅限NPC(預設)";
|
||||
INTERACT_ICONS_OPTION = "互動鍵圖示";
|
||||
INTERACT_ICONS_SHOW_ALL = "顯示全部";
|
||||
INTERACT_ICONS_SHOW_NONE = "不顯示圖示";
|
||||
OPTION_TOOLTIP_ACTION_BUTTON_USE_KEY_DOWN = "快捷鍵按鍵設定會在按下按鍵時生效,而不是在鬆開按鍵的時候。";
|
||||
OPTION_TOOLTIP_ACTION_TARGETING = "根據你的視線方向,動態鎖定敵人的鎖定系統。與標準鎖定系統相輔相成。";
|
||||
OPTION_TOOLTIP_ENABLE_INTERACT = "可透過按鍵與NPC和物件互動";
|
||||
OPTION_TOOLTIP_INTERACT_ICONS = "在啟用互動鍵功能後,控制出現在NPC和物件上方的圖示";
|
||||
OPTION_TOOLTIP_STOP_AUTO_ATTACK = "當你切換目標時停止自動攻擊。";
|
||||
SET_FOCUS = "設定專注目標";
|
||||
FOCUSTARGET = "設定鎖定目標";
|
||||
ITEMS_VARIABLE_QUANTITY = "%d件物品";
|
||||
@@ -34,6 +49,7 @@ ITEMS_IN_INVENTORY = "%d件物品在物品欄中";
|
||||
ITEM_SLOTS_IGNORED = "忽略%d個欄位";
|
||||
ITEM_MISSING = "缺少%s物品";
|
||||
ITEMS_NOT_IN_INVENTORY = "缺少%d件物品";
|
||||
STOP_AUTO_ATTACK = "停止自動攻擊";
|
||||
TARGETFOCUS = "選定鎖定單位";
|
||||
-- BINDING_NAME_AOELOOT = "AoE Loot";
|
||||
COPPER_AMOUNT_SYMBOL = "銅";
|
||||
@@ -69,6 +85,15 @@ ITEM_MOD_DODGE_RATING_SHORT = "閃躲";
|
||||
ITEM_MOD_PARRY_RATING_SHORT = "招架";
|
||||
ITEM_MOD_BLOCK_RATING_SHORT = "格擋";
|
||||
ITEM_MOD_BLOCK_VALUE_SHORT = "格擋值";
|
||||
ITEM_MOD_HOLY_SPELL_DAMAGE_DONE_SHORT = "神聖傷害加成";
|
||||
ITEM_MOD_FIRE_SPELL_DAMAGE_DONE_SHORT = "火焰傷害加成";
|
||||
ITEM_MOD_NATURE_SPELL_DAMAGE_DONE_SHORT = "自然傷害加成";
|
||||
ITEM_MOD_FROST_SPELL_DAMAGE_DONE_SHORT = "冰霜傷害加成";
|
||||
ITEM_MOD_SHADOW_SPELL_DAMAGE_DONE_SHORT = "暗影傷害加成";
|
||||
ITEM_MOD_ARCANE_SPELL_DAMAGE_DONE_SHORT = "秘法傷害加成";
|
||||
ITEM_MOD_SPELL_PENETRATION_SHORT = "法術穿透";
|
||||
ITEM_MOD_ARMOR_PENETRATION_RATING_SHORT = "護甲穿透";
|
||||
ITEM_MOD_HEALTH_REGEN_SHORT = "生命力恢復";
|
||||
ITEM_MOD_DAMAGE_PER_SECOND_SHORT = "每秒傷害";
|
||||
LARGE_NUMBER_SEPERATOR = ",";
|
||||
MINUTES_SECONDS = "%.2d:%.2d";
|
||||
@@ -147,3 +172,7 @@ SLASH_TARGET_NEAREST_RAID2 = "/targetraid";
|
||||
SLASH_USE1 = "/使用";
|
||||
SLASH_USE2 = "/use";
|
||||
LINK_TRADESKILL_TOOLTIP = "點擊這裡以製造一個你專業技能的連結。";
|
||||
TEXT_TO_SPEECH = "文字轉語音";
|
||||
TEXT_TO_SPEECH_ADJUST_RATE = "調整語速";
|
||||
TEXT_TO_SPEECH_ADJUST_VOLUME = "語音音量";
|
||||
TEXT_TO_SPEECH_VOICE_OPTION = "聲音選項";
|
||||
|
||||
+109
-139
@@ -3,13 +3,11 @@
|
||||
--
|
||||
-- Major changes from the 3.3.5 source:
|
||||
-- * Lua 5.0 has no "..." varargs and no select(); script handlers take
|
||||
-- explicit (this, event, arg1..arg9) parameters from XML inline scripts.
|
||||
-- explicit (this, event, arg1..arg19) parameters from XML inline scripts.
|
||||
-- * RegisterAllEvents is used when available; the curated default list is
|
||||
-- a fallback if the client doesn't expose it.
|
||||
-- * No GameTooltip:SetFrameStack -- /framestack walks the engine's
|
||||
-- frame list via EnumerateFrames(prev) and renders into our own
|
||||
-- FrameStackTooltip instead. Catches anonymous frames the modern
|
||||
-- engine method shows but a _G walk would miss.
|
||||
-- * /fstack accepts "true" (as on 3.3.5) or "hidden" to list hidden
|
||||
-- frames too.
|
||||
-- * No UIPanelDialogTemplate, no parentKey, no clampedToScreen, no
|
||||
-- OnSizeChanged in vanilla -- frames have fixed dimensions.
|
||||
-- * No debuglocals
|
||||
@@ -157,8 +155,8 @@ end);
|
||||
|
||||
local _EventTraceFrame;
|
||||
|
||||
_framesSinceLast = 0;
|
||||
_timeSinceLast = 0;
|
||||
local _framesSinceLast = 0;
|
||||
local _timeSinceLast = 0;
|
||||
|
||||
local _timer = CreateFrame("Frame");
|
||||
_timer:SetScript("OnUpdate", function()
|
||||
@@ -170,12 +168,55 @@ end);
|
||||
-- EventTraceFrame
|
||||
------------------------------------------------------------------------------
|
||||
|
||||
-- The engine sets at most arg1..arg19 for an event, so the XML OnEvent passes
|
||||
-- all 19 globals and trailing nils mark the end.
|
||||
EVENT_TRACE_MAX_ARGS = 19;
|
||||
|
||||
-- Entries keep an ever-growing index (lastIndex, filteredIndices,
|
||||
-- button.index), but are stored in a ring of EVENT_TRACE_MAX_ENTRIES fixed
|
||||
-- slots. Keys that only grow would make every column table rehash, and
|
||||
-- reallocate, every few events.
|
||||
local function _Slot(index)
|
||||
local f = _EventTraceFrame;
|
||||
if (not index or index < 1 or index > f.lastIndex
|
||||
or index <= f.lastIndex - EVENT_TRACE_MAX_ENTRIES) then
|
||||
return nil;
|
||||
end
|
||||
return math.mod(index - 1, EVENT_TRACE_MAX_ENTRIES) + 1;
|
||||
end
|
||||
|
||||
-- An event row stores only its GetTime(); the text is built when the row
|
||||
-- is drawn, so a closed window builds no strings.
|
||||
local function _TimeText(slot)
|
||||
local f = _EventTraceFrame;
|
||||
local kind = f.times[slot];
|
||||
if (kind) then return kind; end
|
||||
local seconds = f.rawtimes[slot];
|
||||
local minutes = math.floor(math.floor(seconds) / 60);
|
||||
local hours = math.floor(minutes / 60);
|
||||
seconds = seconds - 60 * minutes;
|
||||
minutes = minutes - 60 * hours;
|
||||
hours = math.mod(hours, 1000);
|
||||
return string.format("%.2d:%.2d:%06.3f", hours, minutes, seconds);
|
||||
end
|
||||
|
||||
local function _EventText(slot)
|
||||
local f = _EventTraceFrame;
|
||||
if (f.times[slot] == "Elapsed") then
|
||||
return string.format("%.3f sec - %d frame(s)", f.elapsed[slot], f.frames[slot]);
|
||||
end
|
||||
return f.events[slot];
|
||||
end
|
||||
|
||||
function EventTraceFrame_OnLoad(self)
|
||||
self.buttons = {};
|
||||
self.events = {};
|
||||
self.times = {};
|
||||
self.rawtimes = {};
|
||||
self.args = { {}, {}, {}, {}, {}, {}, {}, {}, {} };
|
||||
self.elapsed = {};
|
||||
self.frames = {};
|
||||
self.args = {};
|
||||
for i = 1, EVENT_TRACE_MAX_ARGS do self.args[i] = {}; end
|
||||
self.ignoredEvents = {};
|
||||
self.lastIndex = 0;
|
||||
self.visibleButtons = EVENT_TRACE_NUM_BUTTONS;
|
||||
@@ -207,7 +248,8 @@ function EventTraceFrame_OnLoad(self)
|
||||
end
|
||||
end
|
||||
|
||||
function EventTraceFrame_OnEvent(self, event, a1, a2, a3, a4, a5, a6, a7, a8, a9)
|
||||
function EventTraceFrame_OnEvent(self, event, a1, a2, a3, a4, a5, a6, a7, a8, a9,
|
||||
a10, a11, a12, a13, a14, a15, a16, a17, a18, a19)
|
||||
if (self.ignoredEvents[event]) then return; end
|
||||
-- Pause swallows real engine events but lets the synthetic
|
||||
-- "Begin Capture"/"End Capture"/"On Update" markers through so the
|
||||
@@ -224,67 +266,54 @@ function EventTraceFrame_OnEvent(self, event, a1, a2, a3, a4, a5, a6, a7, a8, a9
|
||||
end
|
||||
|
||||
local nextIndex = self.lastIndex + 1;
|
||||
if (nextIndex > EVENT_TRACE_MAX_ENTRIES) then
|
||||
local staleIndex = nextIndex - EVENT_TRACE_MAX_ENTRIES;
|
||||
self.events[staleIndex] = nil;
|
||||
self.times[staleIndex] = nil;
|
||||
self.rawtimes[staleIndex] = nil;
|
||||
for k, v in pairs(self.args) do
|
||||
self.args[k][staleIndex] = nil;
|
||||
end
|
||||
end
|
||||
local slot = math.mod(nextIndex - 1, EVENT_TRACE_MAX_ENTRIES) + 1;
|
||||
|
||||
-- Every column of the slot is written, so nothing from the entry it
|
||||
-- replaces is left behind.
|
||||
self.times[slot] = nil;
|
||||
self.elapsed[slot] = nil;
|
||||
self.frames[slot] = nil;
|
||||
if (string.find(event, "Begin Capture", 1, true) or
|
||||
string.find(event, "End Capture", 1, true)) then
|
||||
self.times[nextIndex] = "System";
|
||||
self.times[slot] = "System";
|
||||
if (self.eventsToCapture) then
|
||||
self.events[nextIndex] = string.format("%s (%s events)", event,
|
||||
tostring(self.eventsToCapture));
|
||||
self.events[slot] = string.format("%s (%s events)", event,
|
||||
tostring(self.eventsToCapture));
|
||||
else
|
||||
self.events[nextIndex] = event;
|
||||
self.events[slot] = event;
|
||||
end
|
||||
elseif (event == "On Update") then
|
||||
self.times[nextIndex] = "Elapsed";
|
||||
self.events[nextIndex] = string.format(
|
||||
string.format("%.3f sec", _timeSinceLast) .. " - %d frame(s)",
|
||||
_framesSinceLast);
|
||||
self.times[slot] = "Elapsed";
|
||||
self.events[slot] = event;
|
||||
self.elapsed[slot] = _timeSinceLast;
|
||||
self.frames[slot] = _framesSinceLast;
|
||||
_timeSinceLast = 0;
|
||||
_framesSinceLast = 0;
|
||||
else
|
||||
self.events[nextIndex] = event;
|
||||
local seconds = GetTime();
|
||||
local minutes = math.floor(math.floor(seconds) / 60);
|
||||
local hours = math.floor(minutes / 60);
|
||||
seconds = seconds - 60 * minutes;
|
||||
minutes = minutes - 60 * hours;
|
||||
hours = math.mod(hours, 1000);
|
||||
self.times[nextIndex] = string.format("%.2d:%.2d:%06.3f", hours, minutes, seconds);
|
||||
|
||||
local packed = { a1, a2, a3, a4, a5, a6, a7, a8, a9 };
|
||||
local numArgs = 0;
|
||||
for i = 9, 1, -1 do
|
||||
if (packed[i] ~= nil) then
|
||||
numArgs = i;
|
||||
break;
|
||||
end
|
||||
end
|
||||
for i = 1, numArgs do
|
||||
if (not self.args[i]) then self.args[i] = {}; end
|
||||
self.args[i][nextIndex] = packed[i];
|
||||
end
|
||||
|
||||
self.events[slot] = event;
|
||||
if (self.eventsToCapture) then
|
||||
self.eventsToCapture = self.eventsToCapture - 1;
|
||||
end
|
||||
end
|
||||
|
||||
self.rawtimes[nextIndex] = GetTime();
|
||||
-- Stored straight into the per-argument columns: a table to pack them
|
||||
-- would be one more allocation per event. The markers pass none.
|
||||
local args = self.args;
|
||||
args[1][slot] = a1; args[2][slot] = a2; args[3][slot] = a3;
|
||||
args[4][slot] = a4; args[5][slot] = a5; args[6][slot] = a6;
|
||||
args[7][slot] = a7; args[8][slot] = a8; args[9][slot] = a9;
|
||||
args[10][slot] = a10; args[11][slot] = a11; args[12][slot] = a12;
|
||||
args[13][slot] = a13; args[14][slot] = a14; args[15][slot] = a15;
|
||||
args[16][slot] = a16; args[17][slot] = a17; args[18][slot] = a18;
|
||||
args[19][slot] = a19;
|
||||
|
||||
self.rawtimes[slot] = GetTime();
|
||||
self.lastIndex = nextIndex;
|
||||
-- Keep the filtered view in sync if a search is active. We append-
|
||||
-- on-match here rather than re-walking the whole event list each
|
||||
-- tick (would be O(n) per event for the most common case where
|
||||
-- the search matches none / many).
|
||||
if (self.filteredIndices and _EventTrace_MatchesSearch(self.events[nextIndex])) then
|
||||
if (self.filteredIndices and _EventTrace_MatchesSearch(self.events[slot])) then
|
||||
table.insert(self.filteredIndices, nextIndex);
|
||||
-- Bound the filtered list to the same MAX_ENTRIES window the
|
||||
-- raw store enforces. Drop the head when we overflow.
|
||||
@@ -293,7 +322,8 @@ function EventTraceFrame_OnEvent(self, event, a1, a2, a3, a4, a5, a6, a7, a8, a9
|
||||
table.remove(self.filteredIndices, 1);
|
||||
end
|
||||
end
|
||||
EventTraceFrame_Update();
|
||||
-- No redraw here: OnUpdate redraws once per frame while the window is
|
||||
-- shown, and a hidden window needs none.
|
||||
if (self.eventsToCapture and self.eventsToCapture <= 0) then
|
||||
self.eventsToCapture = nil;
|
||||
EventTraceFrame_StopEventCapture();
|
||||
@@ -333,7 +363,7 @@ function _EventTrace_RebuildFilter()
|
||||
local indices = {};
|
||||
local first = math.max(1, (_EventTraceFrame.lastIndex or 0) - EVENT_TRACE_MAX_ENTRIES + 1);
|
||||
for i = first, (_EventTraceFrame.lastIndex or 0) do
|
||||
local ev = _EventTraceFrame.events[i];
|
||||
local ev = _EventTraceFrame.events[_Slot(i)];
|
||||
if (ev and string.find(string.lower(ev), needle, 1, true)) then
|
||||
table.insert(indices, i);
|
||||
end
|
||||
@@ -370,16 +400,16 @@ end
|
||||
-- on, appends a comma-separated rendering of the captured args after
|
||||
-- the event name. System rows (Begin/End Capture, On Update markers)
|
||||
-- never get args.
|
||||
function _EventTrace_FormatRow(index)
|
||||
local ev = _EventTraceFrame.events[index];
|
||||
function _EventTrace_FormatRow(slot)
|
||||
local ev = _EventText(slot);
|
||||
if (not ev) then return nil; end
|
||||
if (not _EventTraceFrame.showArguments) then return ev; end
|
||||
if (EVENT_TRACE_SYSTEM_TIMES[_EventTraceFrame.times[index]]) then return ev; end
|
||||
if (EVENT_TRACE_SYSTEM_TIMES[_EventTraceFrame.times[slot]]) then return ev; end
|
||||
local parts = {};
|
||||
for i = 1, 9 do
|
||||
for i = 1, EVENT_TRACE_MAX_ARGS do
|
||||
local argList = _EventTraceFrame.args[i];
|
||||
if (argList and argList[index] ~= nil) then
|
||||
table.insert(parts, EventTrace_FormatArgValue(argList[index]));
|
||||
if (argList and argList[slot] ~= nil) then
|
||||
table.insert(parts, EventTrace_FormatArgValue(argList[slot]));
|
||||
end
|
||||
end
|
||||
if (table.getn(parts) == 0) then return ev; end
|
||||
@@ -504,9 +534,10 @@ function EventTraceFrame_Update()
|
||||
local button = _EventTraceFrame.buttons[i];
|
||||
if (button) then
|
||||
local index = _EventTrace_ResolveIndex(scrollBarValue, i - 1);
|
||||
local event = index and _EventTraceFrame.events[index];
|
||||
local slot = _Slot(index);
|
||||
local event = slot and _EventTraceFrame.events[slot];
|
||||
if (event) then
|
||||
local timeString = _EventTraceFrame.times[index];
|
||||
local timeString = _EventTraceFrame.times[slot];
|
||||
button.index = index;
|
||||
local timeFS = getglobal(button:GetName() .. "Time");
|
||||
local eventFS = getglobal(button:GetName() .. "Event");
|
||||
@@ -515,11 +546,11 @@ function EventTraceFrame_Update()
|
||||
-- left edge stable, which matters when toggling on/off
|
||||
-- mid-session.
|
||||
if (_EventTraceFrame.showTimestamp) then
|
||||
timeFS:SetText(timeString);
|
||||
timeFS:SetText(_TimeText(slot));
|
||||
else
|
||||
timeFS:SetText("");
|
||||
end
|
||||
eventFS:SetText(_EventTrace_FormatRow(index));
|
||||
eventFS:SetText(_EventTrace_FormatRow(slot));
|
||||
local color = EVENT_TRACE_EVENT_COLORS[event]
|
||||
or EVENT_TRACE_EVENT_COLORS[timeString];
|
||||
if (color) then
|
||||
@@ -651,7 +682,10 @@ function EventTraceFrame_HandleSlashCmd(msg)
|
||||
_EventTraceFrame.events = {};
|
||||
_EventTraceFrame.times = {};
|
||||
_EventTraceFrame.rawtimes = {};
|
||||
_EventTraceFrame.args = { {}, {}, {}, {}, {}, {}, {}, {}, {} };
|
||||
_EventTraceFrame.elapsed = {};
|
||||
_EventTraceFrame.frames = {};
|
||||
_EventTraceFrame.args = {};
|
||||
for i = 1, EVENT_TRACE_MAX_ARGS do _EventTraceFrame.args[i] = {}; end
|
||||
_EventTraceFrame.lastIndex = 0;
|
||||
_EventTraceFrame.filteredIndices = nil;
|
||||
EventTraceFrame_Update();
|
||||
@@ -732,30 +766,30 @@ function EventTrace_FormatArgValue(val)
|
||||
end
|
||||
|
||||
function EventTraceFrameEvent_DisplayTooltip(eventButton)
|
||||
local index = eventButton.index;
|
||||
if (not index) then return; end
|
||||
local slot = _Slot(eventButton.index);
|
||||
if (not slot) then return; end
|
||||
|
||||
local tooltip = EventTraceTooltip;
|
||||
tooltip:SetOwner(eventButton, "ANCHOR_NONE");
|
||||
tooltip:SetPoint("TOPLEFT", eventButton, "TOPRIGHT", 24, 2);
|
||||
local timeString = _EventTraceFrame.times[index];
|
||||
local timeString = _EventTraceFrame.times[slot];
|
||||
if (EVENT_TRACE_SYSTEM_TIMES[timeString]) then
|
||||
tooltip:AddLine(timeString, 1, 1, 1);
|
||||
tooltip:AddDoubleLine(TIME_ENTRY_FORMAT,
|
||||
tostring(_EventTraceFrame.rawtimes[index]),
|
||||
tostring(_EventTraceFrame.rawtimes[slot]),
|
||||
1, .82, 0, 1, 1, 1);
|
||||
tooltip:AddDoubleLine(DETAILS_ENTRY_FORMAT,
|
||||
_EventTraceFrame.events[index],
|
||||
_EventText(slot),
|
||||
1, .82, 0, 1, 1, 1);
|
||||
else
|
||||
tooltip:AddLine(_EventTraceFrame.events[index], 1, 1, 1);
|
||||
tooltip:AddLine(_EventTraceFrame.events[slot], 1, 1, 1);
|
||||
tooltip:AddDoubleLine(TIME_ENTRY_FORMAT,
|
||||
tostring(_EventTraceFrame.rawtimes[index]),
|
||||
tostring(_EventTraceFrame.rawtimes[slot]),
|
||||
1, .82, 0, 1, 1, 1);
|
||||
for k, v in ipairs(_EventTraceFrame.args) do
|
||||
if (v[index] ~= nil) then
|
||||
if (v[slot] ~= nil) then
|
||||
tooltip:AddDoubleLine(string.format(ARGUMENT_ENTRY_FORMAT, k),
|
||||
EventTrace_FormatArgValue(v[index]),
|
||||
EventTrace_FormatArgValue(v[slot]),
|
||||
1, .82, 0, 1, 1, 1);
|
||||
end
|
||||
end
|
||||
@@ -980,70 +1014,6 @@ function DebugTooltip_OnLoad(self)
|
||||
end
|
||||
end
|
||||
|
||||
local _STRATA_RANK = {
|
||||
BACKGROUND = 1, LOW = 2, MEDIUM = 3, HIGH = 4,
|
||||
DIALOG = 5, FULLSCREEN = 6, FULLSCREEN_DIALOG = 7, TOOLTIP = 8,
|
||||
};
|
||||
|
||||
-- Walks every frame the engine knows about via EnumerateFrames (the
|
||||
-- engine-internal frame iterator). Beats a getfenv(0) walk on two
|
||||
-- counts: faster (the engine list is much shorter than _G), and
|
||||
-- includes anonymous frames that never appear in globals (parented
|
||||
-- templates, runtime `CreateFrame` with no `name` arg, etc.). The
|
||||
-- iteration order itself is engine-implementation detail; we re-
|
||||
-- sort by strata + level below either way.
|
||||
local function _CollectFramesUnderMouse(showHidden)
|
||||
local matches = {};
|
||||
local frame = EnumerateFrames(nil);
|
||||
while (frame) do
|
||||
local visOK, visible = pcall(frame.IsVisible, frame);
|
||||
local overOK, mouseOver = pcall(frame.IsMouseOver, frame);
|
||||
if (overOK and mouseOver and (showHidden or (visOK and visible))) then
|
||||
local nameOK, name = pcall(frame.GetName, frame);
|
||||
if (not nameOK or not name) then name = "<anonymous>"; end
|
||||
table.insert(matches, { name = name, frame = frame });
|
||||
end
|
||||
frame = EnumerateFrames(frame);
|
||||
end
|
||||
table.sort(matches, function(a, b)
|
||||
local sa = _STRATA_RANK[a.frame:GetFrameStrata()] or 0;
|
||||
local sb = _STRATA_RANK[b.frame:GetFrameStrata()] or 0;
|
||||
if (sa ~= sb) then return sa > sb; end
|
||||
local la = a.frame:GetFrameLevel() or 0;
|
||||
local lb = b.frame:GetFrameLevel() or 0;
|
||||
return la > lb;
|
||||
end);
|
||||
return matches;
|
||||
end
|
||||
|
||||
local function _UpdateFrameStackTooltip(tooltip, showHidden)
|
||||
tooltip:ClearLines();
|
||||
tooltip:AddLine(DEBUG_FRAMESTACK or "Frame Stack", 1, 1, 1);
|
||||
local matches = _CollectFramesUnderMouse(showHidden);
|
||||
local count = table.getn(matches);
|
||||
if (count == 0) then
|
||||
tooltip:AddLine("(no frames under cursor)", .7, .7, .7);
|
||||
else
|
||||
local shown = 0;
|
||||
for i = 1, count do
|
||||
local m = matches[i];
|
||||
local strata = m.frame:GetFrameStrata() or "?";
|
||||
local level = m.frame:GetFrameLevel() or 0;
|
||||
local label = string.format("%s |cff888888[%s:%d]|r",
|
||||
m.name, strata, level);
|
||||
tooltip:AddLine(label, 1, .82, 0);
|
||||
shown = shown + 1;
|
||||
if (shown >= 30) then
|
||||
tooltip:AddLine(string.format("|cffff8888...%d more|r",
|
||||
count - shown),
|
||||
1, 1, 1);
|
||||
break;
|
||||
end
|
||||
end
|
||||
end
|
||||
tooltip:Show();
|
||||
end
|
||||
|
||||
function FrameStackTooltip_Toggle(showHidden)
|
||||
local tooltip = FrameStackTooltip;
|
||||
if (tooltip:IsVisible()) then
|
||||
@@ -1053,7 +1023,7 @@ function FrameStackTooltip_Toggle(showHidden)
|
||||
tooltip:SetPoint("BOTTOMRIGHT", UIParent, "BOTTOMRIGHT", -32, 96);
|
||||
tooltip.default = 1;
|
||||
tooltip.showHidden = showHidden;
|
||||
_UpdateFrameStackTooltip(tooltip, showHidden);
|
||||
tooltip:SetFrameStack(showHidden);
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1064,7 +1034,7 @@ function FrameStackTooltip_OnUpdate(self, elapsed)
|
||||
_frameStackAccum = _frameStackAccum + elapsed;
|
||||
if (_frameStackAccum >= FRAMESTACK_UPDATE_TIME) then
|
||||
_frameStackAccum = 0;
|
||||
_UpdateFrameStackTooltip(self, self.showHidden);
|
||||
self:SetFrameStack(self.showHidden);
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1095,7 +1065,7 @@ FrameStackTooltip_OnEnter = FrameStackTooltip_OnShow;
|
||||
|
||||
function FrameStackTooltip_HandleSlashCmd(msg)
|
||||
if (msg == nil) then msg = ""; end
|
||||
local showHidden = (string.find(msg, "hidden") ~= nil);
|
||||
local showHidden = (msg == "true" or string.find(msg, "hidden") ~= nil);
|
||||
FrameStackTooltip_Toggle(showHidden);
|
||||
end
|
||||
|
||||
|
||||
@@ -60,7 +60,11 @@
|
||||
</EdgeSize>
|
||||
</Backdrop>
|
||||
<Layers>
|
||||
<Layer level="BACKGROUND">
|
||||
<!-- ARTWORK, not BACKGROUND: the Backdrop draws its own
|
||||
background into BACKGROUND after the textures declared here,
|
||||
which would bury this bar. The title text is in OVERLAY, so
|
||||
it still reads over the top. -->
|
||||
<Layer level="ARTWORK">
|
||||
<Texture name="$parentTitleBG" file="Interface\QuestFrame\UI-QuestLogTitleHighlight">
|
||||
<Size x="280" y="20"/>
|
||||
<Anchors>
|
||||
@@ -252,7 +256,7 @@
|
||||
</Frames>
|
||||
<Scripts>
|
||||
<OnLoad>EventTraceFrame_OnLoad(this);</OnLoad>
|
||||
<OnEvent>EventTraceFrame_OnEvent(this, event, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9);</OnEvent>
|
||||
<OnEvent>EventTraceFrame_OnEvent(this, event, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19);</OnEvent>
|
||||
<OnUpdate>EventTraceFrame_OnUpdate(this, arg1);</OnUpdate>
|
||||
</Scripts>
|
||||
</Frame>
|
||||
@@ -278,7 +282,12 @@
|
||||
</EdgeSize>
|
||||
</Backdrop>
|
||||
<Layers>
|
||||
<Layer level="BACKGROUND">
|
||||
<!-- ARTWORK, not BACKGROUND: the Backdrop above draws its
|
||||
background and border into BACKGROUND, and it is applied
|
||||
after the textures declared here, so a header in that layer
|
||||
ends up behind the window border. Every Blizzard frame that
|
||||
uses UI-DialogBox-Header puts it in ARTWORK for this reason. -->
|
||||
<Layer level="ARTWORK">
|
||||
<Texture name="$parentTitleBG" file="Interface\DialogFrame\UI-DialogBox-Header">
|
||||
<Size x="256" y="64"/>
|
||||
<Anchors>
|
||||
@@ -322,8 +331,16 @@
|
||||
<OnDragStop>ScriptErrorsFrame_TitleButton_OnDragStop();</OnDragStop>
|
||||
</Scripts>
|
||||
</Frame>
|
||||
<!-- Width leaves room for the scroll bar inside the border.
|
||||
UIPanelScrollFrameTemplate hangs its bar off this frame's
|
||||
right edge (+6, 16 wide, button art a little wider), so the
|
||||
bar ends at about right + 23. The frame's interior margin is
|
||||
368, where the Close button ends, which puts the widest this
|
||||
can be at 328. Blizzard's own numbers do not carry over here:
|
||||
its ScriptErrorsFrame inherits UIPanelDialogTemplate, a thin
|
||||
GearManager border, not this 32px dialog backdrop. -->
|
||||
<ScrollFrame name="$parentScrollFrame" inherits="UIPanelScrollFrameTemplate">
|
||||
<Size x="343" y="170"/>
|
||||
<Size x="328" y="170"/>
|
||||
<Anchors>
|
||||
<Anchor point="TOPLEFT">
|
||||
<Offset x="16" y="-32"/>
|
||||
@@ -331,7 +348,7 @@
|
||||
</Anchors>
|
||||
<ScrollChild>
|
||||
<EditBox name="$parentText" multiLine="true" letters="4000" autoFocus="false">
|
||||
<Size x="343" y="170"/>
|
||||
<Size x="328" y="170"/>
|
||||
<Scripts>
|
||||
<OnEscapePressed>this:ClearFocus();</OnEscapePressed>
|
||||
<OnEditFocusGained>this:HighlightText(0);</OnEditFocusGained>
|
||||
@@ -437,7 +454,9 @@
|
||||
</EdgeSize>
|
||||
</Backdrop>
|
||||
<Layers>
|
||||
<Layer level="BACKGROUND">
|
||||
<!-- ARTWORK, not BACKGROUND: see the same note on
|
||||
EventTraceFrame above. -->
|
||||
<Layer level="ARTWORK">
|
||||
<Texture name="$parentTitleBG" file="Interface\QuestFrame\UI-QuestLogTitleHighlight">
|
||||
<Size x="454" y="20"/>
|
||||
<Anchors>
|
||||
|
||||
+31
-53
@@ -45,7 +45,7 @@ set(TINYCBOR_SOURCES
|
||||
# always pass locally. CI release builds pass `-DCLASSICAPI_TAG=vX.Y.Z`,
|
||||
# which drives BOTH the compiled `CLASSIC_API_VERSION` int AND the
|
||||
# embedded addon's `## Version:` toc line (substituted in
|
||||
# embed_addon.cmake). The on-disk source toc stays `## Version: DEV`;
|
||||
# embed_resources.cmake). The on-disk source toc stays `## Version: DEV`;
|
||||
# only the embedded copy is stamped, so a release build needs nothing
|
||||
# but the flag — no source edit.
|
||||
set(CLASSICAPI_VERSION_VALUE 99999999)
|
||||
@@ -73,55 +73,30 @@ elseif(CLASSICAPI_TAG)
|
||||
)
|
||||
endif()
|
||||
|
||||
# Bundle `AddOns/!!!ClassicAPI/` into a generated header so the DLL can
|
||||
# surface the addon to the engine even when the user doesn't have it
|
||||
# installed on disk. The file-read hook in `src/addons/Embedded.cpp`
|
||||
# returns these buffers when the engine asks for paths under
|
||||
# `Interface\AddOns\!!!ClassicAPI\`.
|
||||
set(EMBEDDED_CLASSICAPI_SRC "${CMAKE_CURRENT_SOURCE_DIR}/AddOns/!!!ClassicAPI")
|
||||
set(EMBEDDED_CLASSICAPI_HEADER "${CMAKE_BINARY_DIR}/generated/embedded_classicapi.h")
|
||||
file(GLOB_RECURSE EMBEDDED_CLASSICAPI_FILES CONFIGURE_DEPENDS
|
||||
"${EMBEDDED_CLASSICAPI_SRC}/*")
|
||||
# The `.classicapi-dev` marker is a disk-only developer signal — keep it
|
||||
# out of the embed inputs (embed_addon.cmake filters it too).
|
||||
list(FILTER EMBEDDED_CLASSICAPI_FILES EXCLUDE REGEX "/\\.classicapi-dev$")
|
||||
add_custom_command(
|
||||
OUTPUT "${EMBEDDED_CLASSICAPI_HEADER}"
|
||||
COMMAND ${CMAKE_COMMAND}
|
||||
-DSRC_DIR=${EMBEDDED_CLASSICAPI_SRC}
|
||||
-DOUT_HEADER=${EMBEDDED_CLASSICAPI_HEADER}
|
||||
-DADDON_NAME=ClassicAPI
|
||||
-DADDON_VERSION=${CLASSICAPI_TOC_VERSION}
|
||||
-P "${CMAKE_CURRENT_SOURCE_DIR}/cmake/embed_addon.cmake"
|
||||
DEPENDS
|
||||
${EMBEDDED_CLASSICAPI_FILES}
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/cmake/embed_addon.cmake"
|
||||
COMMENT "Embedding !!!ClassicAPI addon into ${EMBEDDED_CLASSICAPI_HEADER}"
|
||||
VERBATIM)
|
||||
|
||||
# Bundle `src/bindings/Bindings.xml` (our TARGETING-group additions)
|
||||
# into a generated header. `src/bindings/Inject.cpp` extracts the
|
||||
# inner `<Binding>` elements from the embedded buffer and splices them
|
||||
# into the engine's `Interface\FrameXML\Bindings.xml` at load time.
|
||||
set(EMBEDDED_BINDINGS_SRC "${CMAKE_CURRENT_SOURCE_DIR}/src/bindings/Bindings.xml")
|
||||
set(EMBEDDED_BINDINGS_HEADER "${CMAKE_BINARY_DIR}/generated/embedded_bindings.h")
|
||||
add_custom_command(
|
||||
OUTPUT "${EMBEDDED_BINDINGS_HEADER}"
|
||||
COMMAND ${CMAKE_COMMAND}
|
||||
-DINPUT_FILE=${EMBEDDED_BINDINGS_SRC}
|
||||
-DOUT_HEADER=${EMBEDDED_BINDINGS_HEADER}
|
||||
-DSYMBOL=kEmbeddedBindingsXml
|
||||
-P "${CMAKE_CURRENT_SOURCE_DIR}/cmake/embed_file.cmake"
|
||||
DEPENDS
|
||||
"${EMBEDDED_BINDINGS_SRC}"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/cmake/embed_file.cmake"
|
||||
COMMENT "Embedding bindings XML into ${EMBEDDED_BINDINGS_HEADER}"
|
||||
VERBATIM)
|
||||
|
||||
add_library(${PROJECT_NAME} SHARED
|
||||
${SOURCES} ${HEADERS} ${TINYCBOR_SOURCES}
|
||||
${EMBEDDED_CLASSICAPI_HEADER}
|
||||
${EMBEDDED_BINDINGS_HEADER})
|
||||
${SOURCES} ${HEADERS} ${TINYCBOR_SOURCES})
|
||||
|
||||
# Embed `AddOns/!!!ClassicAPI/` and `src/bindings/Bindings.xml` as RCDATA
|
||||
# resources. The file-read hook in `src/addons/Embedded.cpp` serves the
|
||||
# addon files when the engine asks for paths under
|
||||
# `Interface\AddOns\!!!ClassicAPI\`, so the addon loads even when the user
|
||||
# doesn't have it on disk. `src/bindings/Inject.cpp` splices the bindings
|
||||
# XML (our TARGETING-group additions) into the engine's
|
||||
# `Interface\FrameXML\Bindings.xml` at load time.
|
||||
include(cmake/embed_resources.cmake)
|
||||
set(EMBEDDED_CLASSICAPI_SRC "${CMAKE_CURRENT_SOURCE_DIR}/AddOns/!!!ClassicAPI")
|
||||
file(GLOB_RECURSE EMBEDDED_CLASSICAPI_FILES CONFIGURE_DEPENDS RELATIVE
|
||||
"${EMBEDDED_CLASSICAPI_SRC}" "${EMBEDDED_CLASSICAPI_SRC}/*")
|
||||
# Never embed the developer marker: it must reflect on-disk presence only
|
||||
# (see DiskHasDevMarker in src/addons/Embedded.cpp).
|
||||
list(FILTER EMBEDDED_CLASSICAPI_FILES EXCLUDE REGEX "(^|/)\\.classicapi-dev$")
|
||||
embed_resources(
|
||||
TARGET ${PROJECT_NAME}
|
||||
ADDON_DIR "${EMBEDDED_CLASSICAPI_SRC}"
|
||||
ADDON_FILES ${EMBEDDED_CLASSICAPI_FILES}
|
||||
ADDON_VERSION "${CLASSICAPI_TOC_VERSION}"
|
||||
BINDINGS_XML "${CMAKE_CURRENT_SOURCE_DIR}/src/bindings/Bindings.xml"
|
||||
OUT_DIR "${CMAKE_BINARY_DIR}/generated")
|
||||
|
||||
target_compile_definitions(
|
||||
${PROJECT_NAME}
|
||||
@@ -140,6 +115,12 @@ configure_file(
|
||||
@ONLY)
|
||||
target_sources(${PROJECT_NAME} PRIVATE "${CLASSICAPI_VERSION_RC}")
|
||||
|
||||
# The .def exports `Load` (VanillaFixes' post-injection entry point)
|
||||
# undecorated so its GetProcAddress(module, "Load") resolves. See the
|
||||
# loader-lock rationale in src/DllMain.cpp. Listed as a source so CMake emits
|
||||
# a quoted /DEF: on every generator and relinks when the file changes.
|
||||
target_sources(${PROJECT_NAME} PRIVATE src/ClassicAPI.def)
|
||||
|
||||
# ole32: COM (CoInitializeEx / CoCreateInstance / CoTaskMemFree) for the
|
||||
# SAPI text-to-speech backend in src/voicechat/Tts.cpp. The SAPI GUIDs are
|
||||
# instantiated in that TU via <initguid.h>, so no sapi.lib is needed.
|
||||
@@ -178,8 +159,5 @@ set(CMAKE_SHARED_LINKER_FLAGS
|
||||
# identical-COMDAT fold); they are listed explicitly below so they stay ON
|
||||
# and the shipped DLL does not grow. (/OPT:ICF folds identical functions, so
|
||||
# a few map symbols share an address — harmless.)
|
||||
# /DEF exports `Load` (VanillaFixes' post-injection entry point) undecorated
|
||||
# so its GetProcAddress(module, "Load") resolves. See src/ClassicAPI.def and
|
||||
# the loader-lock rationale in src/DllMain.cpp.
|
||||
"/OPT:REF /OPT:ICF /MERGE:.rdata=.text /MERGE:.pdata=.text /SECTION:.text,EWR /NODEFAULTLIB:MSVCRT /MAP /DEBUG /DEF:${CMAKE_CURRENT_SOURCE_DIR}/src/ClassicAPI.def"
|
||||
"/OPT:REF /OPT:ICF /MERGE:.rdata=.text /MERGE:.pdata=.text /SECTION:.text,EWR /NODEFAULTLIB:MSVCRT /MAP /DEBUG"
|
||||
)
|
||||
|
||||
@@ -23,15 +23,21 @@ The flagship feature: run modern Lua 5.1 addon code on 1.12's Lua 5.0 VM.
|
||||
|---------|--------|
|
||||
| [Syntax](docs/API.md#lua-51-syntax) | Compiles the Lua 5.1 length (`#`), modulo (`%`), `...`-expression, `0x` hex-literal, and leveled long bracket (`[=[ ]=]`) syntax that vanilla's Lua 5.0 rejects, by rewriting addon source before it compiles. Each addon file also receives its `(name, table)` through `...` (`local name, tbl = ...`). |
|
||||
| [Upvalue limit](docs/API.md#upvalue-limit) | A function can use up to 60 upvalues, the outer locals it refers to, matching Lua 5.1. Lua 5.0 stops at 32 and rejects the whole file, so a large handler that reads many file-level locals can be valid 5.1 and still fail to load here. Nothing changes for a function within 32. |
|
||||
| [`for` loop variables](docs/API.md#for-loop-variables-per-pass) | Each pass of a `for` loop has its own loop variables, as in Lua 5.1, so a function made in the loop keeps that pass's values. On Lua 5.0 every such function sees the loop's last value, which is `nil` for a `for ... in` loop. |
|
||||
| [String methods](docs/API.md#string-methods-supper-sformat) | Every string value accepts method calls — `("asd"):upper()`, `("%d gold"):format(n)`, `msg:match("^!(%w+)")` — resolving through the `string` table, the way Lua 5.1 works. Works on literals and variables, in-world and on the login screen, and inside coroutines. |
|
||||
| [Script-handler arguments](docs/API.md#setmodernscriptargsenable--getmodernscriptargs) | Frame-script handlers receive their values as positional arguments — `OnMouseWheel(self, delta)`, `OnClick(self, button)`, `OnEvent(self, event, ...)`, etc. — so modern addon ports work unmodified. The `this` / `arg1` globals stay set. A handler that declares no parameters is unaffected. A handler that declared a parameter and expected nil now receives its real value. On by default. `SetModernScriptArgs(false)` restores exact vanilla dispatch. |
|
||||
| [XML script bodies](docs/API.md#xml-script-bodies-see-self-and-their-arguments) | An XML script body written for later clients, such as `<OnLoad>self:Init()</OnLoad>`, sees `self` and its script's arguments by name (`elapsed`, `button`, ...). Bodies that read `this` / `arg1` compile as before. |
|
||||
|
||||
### Modern client behaviors
|
||||
|
||||
| Feature | Effect |
|
||||
|---------|--------|
|
||||
| Inline textures | Draws inline texture markup (`\|T…\|t`) and atlas markup (`\|A…\|a`) as icons in FontStrings, chat, and tooltips. This covers item and spell icons, raid-target markers, and the coin icons in money strings. `GetStringWidth` and `GetStringHeight` count the icons, so measured width and text wrapping stay correct. Done in pure C++ by hooking the engine's text pipeline — no addon. |
|
||||
| [Soft interact](docs/API.md#soft-interact-softinteract--anyinteract) | The Interact Key. After you bind **Interact With Target** to a key, the key interacts with the nearest object in front of you. This object can be an NPC with a service, a corpse that you can loot or skin, a mailbox, a chest, or an herb or mining node. The `softinteract` and `anyinteract` unit tokens point at the object, and `PLAYER_SOFT_INTERACT_CHANGED` fires when it changes. When `SoftTargetIconInteract` is `1`, an icon over the object shows the cursor that the mouse shows over it. |
|
||||
| [Soft enemy and soft friend](docs/API.md#soft-enemy-and-soft-friend-softenemy--softfriend--anyenemy--anyfriend) | The `softenemy` and `softfriend` unit tokens point at the nearest enemy and the nearest friendly unit, and your target does not change. When your target qualifies, they point at your target. `anyenemy` and `anyfriend` use your target first. `PLAYER_SOFT_ENEMY_CHANGED` and `PLAYER_SOFT_FRIEND_CHANGED` fire when the units change. With no target, an attack goes to `softenemy`, a harmful spell goes to `softenemy` and a helpful spell goes to `softfriend`. A harmful spell makes its unit a loose target, which follows the nearest soft enemy. A dimmer selection circle shows under each unit. `SoftTargetIconEnemy` and `SoftTargetIconFriend` show an icon over each unit. Turn them on with `SoftTargetEnemy` and `SoftTargetFriend`. |
|
||||
| [Animations](docs/API.md#animation) | Animation groups on frames, textures and font strings, made in Lua or XML: `CreateAnimationGroup`, looping, smoothing, scripts and templates, with `Alpha`, `Translation`, `Scale`, `Rotation` and `Path` applied. |
|
||||
| Tooltip line cap | Lifts `GameTooltip`'s hard 30-line limit to 60 for every `GameTooltipTemplate` frame (`GameTooltip`, `ShoppingTooltip1/2`, `ItemRefTooltip`, AtlasLoot, …). Stat-heavy tooltips and comparison blocks (e.g. pfUI's eqcompare) no longer have their extra lines silently dropped. Done in pure C++ by growing the engine's FontString pool at tooltip-creation time. |
|
||||
| [XML attributes](docs/API.md#parentkey-in-xml) | More XML attributes work: `parentKey="Name"` makes `parent.Name` point to a frame, texture or font string, `<OnLoad function="Name"/>` uses a global function as a script handler, `<OnLoad method="Name"/>` uses the frame's own function, `mixin="A, B"` copies mixins onto the object, `<KeyValues>` sets fields on the object, a button's `<NormalFont style="..."/>` sets its font, and `inherits="A, B"` applies more than one template. |
|
||||
| [Macro conditions](docs/API.md#more-commands-with-conditions) | `[conditions]` and `@unit` work on 38 slash commands, from `/cast` and `/use` to `/target`, `/follow`, `/cancelaura` and the `/pet` family. With `/cast [@mouseover,harm][] Fireball`, the spell goes to the mouseover unit. With no mouseover unit, it goes to your target. `@cursor` places a ground-target spell or item under the mouse and `@player` places it at your feet. A character name works where a unit token does (`[target=Feral]`). Addons read the same rules through `SecureCmdOptionParse`. |
|
||||
| [`#showtooltip`](docs/API.md#showtooltip-and-show) | A macro button shows what the macro does. The icon, tooltip, cooldown, range, usable state and auto-repeat glow all follow the spell or item that the directive resolves to, conditions included. They update as the conditions change. The result goes into the engine field that action-bar addons already read, so they need no code of their own. An addon with its own macro parser can publish its result through `C_Macro.SetMacroDisplay`. It then does not need to replace the action globals. |
|
||||
| [Event-driven nameplates](docs/API.md#nameplate) | The modern `C_NamePlate` API, driven by real events. `NAME_PLATE_UNIT_ADDED` / `NAME_PLATE_UNIT_REMOVED` fire as plates appear and vanish, `nameplate1`..`nameplateN` tokens resolve with every `UnitX` function (and fire `UNIT_HEALTH`, `UNIT_AURA`, … as `arg1 == "nameplateN"`), and `C_NamePlate.GetNamePlateForUnit` / `GetNamePlates` hand back the live frames. |
|
||||
@@ -41,6 +47,9 @@ The flagship feature: run modern Lua 5.1 addon code on 1.12's Lua 5.0 VM.
|
||||
| [Launch switches](docs/API.md#launch) | Options you add to the shortcut that starts the game. `-config <name>` reads and writes `WTF\<name>` in place of `WTF\Config.wtf`, so one install can hold several settings profiles. `-gluescript` and `-gluescriptFile` run Lua at the login and character-select screens, every time those screens appear. `-gamescript` and `-gamescriptFile` run it one time, after you enter the world. Each script runs after the interface has loaded, so it can call interface functions and use frames. |
|
||||
| [Any texture size](docs/API.md#texture-size-and-shape) | Textures load at any size and any shape. Width and height do not need to be powers of two, and there is no fixed upper limit. The only limit is the maximum texture size of your graphics card. This applies to every texture path: `SetTexture`, sprite sheets, inline textures, tooltips, and masks. The client allocates memory for a large texture only when an addon loads one, so small textures cost nothing extra. |
|
||||
|
||||
Smaller behavior fixes, such as frame alpha and `SetParent` frame levels, are
|
||||
in **[docs/API.md](docs/API.md)** with the API that they change.
|
||||
|
||||
## Full API reference
|
||||
|
||||
Everything ClassicAPI adds, in full. Each section is collapsed — click a
|
||||
@@ -50,67 +59,89 @@ reference in **[docs/API.md](docs/API.md)**.
|
||||
<details>
|
||||
<summary><b>In-game Lua calls</b> — 550+ functions across ~60 namespaces</summary>
|
||||
|
||||
In the Frame rows, a name that starts with `:` is a method of the widget that the row names, for example `:SetShown` is `frame:SetShown`.
|
||||
|
||||
| Namespace | Calls |
|
||||
|-----------|-------|
|
||||
| [Action](docs/API.md#action) | `GetActionInfo` |
|
||||
| [AddOns](docs/API.md#addons) | `C_AddOns.DoesAddOnExist`, `C_AddOns.GetAddOnLocalTable`, `C_AddOns.GetAddOnName`, `C_AddOns.GetAddOnNotes`, `C_AddOns.GetAddOnOptionalDependencies`, `C_AddOns.GetAddOnSecurity`, `C_AddOns.GetAddOnTitle`, `C_AddOns.IsAddOnLoadable`, `C_AddOns.IsAddOnLoaded`, `C_AddOns.LoadAddOn` |
|
||||
| [AddOns](docs/API.md#addons) | `C_AddOns.DoesAddOnExist`, `C_AddOns.GetAddOnInterfaceVersion`, `C_AddOns.GetAddOnLocalTable`, `C_AddOns.GetAddOnName`, `C_AddOns.GetAddOnNotes`, `C_AddOns.GetAddOnOptionalDependencies`, `C_AddOns.GetAddOnSecurity`, `C_AddOns.GetAddOnTitle`, `C_AddOns.IsAddOnLoadable`, `C_AddOns.IsAddOnLoaded`, `C_AddOns.LoadAddOn` |
|
||||
| [APIDocumentation](docs/API.md#apidocumentation) | `/classicapi` in-game browser, `C_APIDocumentation.GetSystem`, `C_APIDocumentation.GetSystems` |
|
||||
| [Animation](docs/API.md#animation) | `region:CreateAnimationGroup`, `region:GetAnimationGroups`, `region:StopAnimating`, `SetMaxAnimFramerate`, `GetMaxAnimFramerate`, `AnimationGroup` and `Animation` / `Alpha` / `Translation` / `Scale` / `Rotation` / `Path` / `ControlPoint` methods |
|
||||
| [AuctionHouse](docs/API.md#auctionhouse) | `C_AuctionHouse.PostItem` |
|
||||
| [Bindings](docs/API.md#bindings) | `SetBindingSpell`, `SetBindingItem`, `SetBindingMacro`, `SetBindingClick`, `SetOverrideBinding`, `SetOverrideBindingSpell`, `SetOverrideBindingItem`, `SetOverrideBindingMacro`, `SetOverrideBindingClick`, `ClearOverrideBindings` |
|
||||
| [Bindings](docs/API.md#bindings) | `SetBindingSpell`, `SetBindingItem`, `SetBindingMacro`, `SetBindingClick`, `SetOverrideBinding`, `SetOverrideBindingSpell`, `SetOverrideBindingItem`, `SetOverrideBindingMacro`, `SetOverrideBindingClick`, `ClearOverrideBindings`, `GetBindingAction` (`checkOverride`), `GetBindingByKey`, `IsModifiedClick`, `GetModifiedClick`, `SetModifiedClick`, `GetNumModifiedClickActions`, `GetModifiedClickAction` |
|
||||
| [Chat](docs/API.md#chat) | `GetCurrentChatGUID` |
|
||||
| [ChatBubbles](docs/API.md#chatbubbles) | `C_ChatBubbles.GetAllChatBubbles` |
|
||||
| [Class](docs/API.md#class) | `FillLocalizedClassList` |
|
||||
| [ClassColor](docs/API.md#classcolor) | `C_ClassColor.GetClassColor` |
|
||||
| [ColorUtil](docs/API.md#colorutil) | `C_ColorUtil.ConvertRGBToHSV`, `C_ColorUtil.ConvertHSVToRGB`, `C_ColorUtil.ConvertHSVToHSL`, `C_ColorUtil.ConvertHSLToHSV`, `C_ColorUtil.ConvertHSLToRGB`, `C_ColorUtil.GenerateTextColorCode`, `C_ColorUtil.WrapTextInColor`, `C_ColorUtil.WrapTextInColorCode` |
|
||||
| [Combat](docs/API.md#combat) | `InCombatLockdown`, `StartAttack`, `StopAttack` |
|
||||
| [CombatLog](docs/API.md#combatlog) | `CombatLogGetCurrentEventInfo`, `COMBATLOG_OBJECT_*` (constants) |
|
||||
| [Console](docs/API.md#console) | `CalculateStringEditDistance`, `ConsoleEcho`, `ConsoleExec`, `ConsoleGetAllCommands`, `ConsoleGetColorFromType`, `ConsoleGetFontHeight`, `ConsoleIsActive`, `ConsolePrintAllMatchingCommands`, `SetConsoleKey` |
|
||||
| [CVar](docs/API.md#cvar) | `C_CVar.AreCVarsLoaded`, `C_CVar.DoesCVarExist`, `C_CVar.GetCVarBitfield`, `C_CVar.GetCVarBool`, `C_CVar.GetCVarInfo`, `C_CVar.SetCVarBitfield` |
|
||||
| [CVar](docs/API.md#cvar) | `C_CVar.AreCVarsLoaded`, `C_CVar.DoesCVarExist`, `C_CVar.GetCVarBitfield`, `C_CVar.GetCVarBool`, `C_CVar.GetCVarInfo`, `C_CVar.RemoveTempCVar`, `C_CVar.SetCVar`, `C_CVar.SetCVarBitfield`, `C_CVar.SetTempCVar`, `GetCVar`, `GetCVarDefault` |
|
||||
| [Cursor](docs/API.md#cursor) | `GetCursorInfo` |
|
||||
| [Container](docs/API.md#container) | `C_Container.AutoStoreItem`, `C_Container.CalculateTotalNumberOfFreeBagSlots`, `C_Container.GetContainerItemCharges`, `C_Container.GetContainerItemDurability`, `C_Container.GetContainerItemID`, `C_Container.GetContainerItemInfo`, `C_Container.GetContainerItemEquipmentSetInfo`, `C_Container.GetContainerItemQuestInfo`, `C_Container.GetContainerItemRepairCost`, `C_Container.GetContainerFreeSlots`, `C_Container.GetContainerNumFreeSlots`, `C_Container.GetBackpackAutosortDisabled`, `C_Container.GetBankAutosortDisabled`, `C_Container.GetItemCooldown`, `C_Container.GetSortBagsRightToLeft`, `C_Container.HasContainerItem`, `C_Container.IsContainerItemOpenable`, `C_Container.MoveItem`, `C_Container.PlayerHasHearthstone`, `C_Container.SetBackpackAutosortDisabled`, `C_Container.SetBankAutosortDisabled`, `C_Container.SetSortBagsRightToLeft`, `C_Container.SortBags`, `C_Container.SortBankBags`, `C_Container.SwapItems`, `C_Container.UseHearthstone`, `GetItemCooldown` |
|
||||
| [Creature](docs/API.md#creature) | `C_CreatureInfo.GetCreatureID`, `C_CreatureInfo.GetCreatureInfoByID`, `C_CreatureInfo.RequestLoadCreatureByID`, `C_CreatureInfo.GetRaceInfo`, `C_CreatureInfo.GetClassInfo`, `C_CreatureInfo.GetCreatureFamilyInfo`, `C_CreatureInfo.GetCreatureFamilyIDs`, `C_CreatureInfo.GetFactionInfo`, `C_CreatureInfo.GetCreatureTypeInfo`, `C_CreatureInfo.GetCreatureTypeIDs` |
|
||||
| [Currency](docs/API.md#currency) | `GetCoinTextureString`, `C_CurrencyInfo.GetCoinTextureString` |
|
||||
| EncodingUtil | `C_EncodingUtil.CompressString`, `C_EncodingUtil.DecompressString`, `C_EncodingUtil.EncodeBase64`, `C_EncodingUtil.DecodeBase64`, `C_EncodingUtil.EncodeHex`, `C_EncodingUtil.DecodeHex`, `C_EncodingUtil.SerializeJSON`, `C_EncodingUtil.DeserializeJSON`, `C_EncodingUtil.SerializeCBOR`, `C_EncodingUtil.DeserializeCBOR` |
|
||||
| [EquipmentSet](docs/API.md#equipmentset) | `C_EquipmentSet.CanUseEquipmentSets`, `C_EquipmentSet.ClearIgnoredSlotsForSave`, `C_EquipmentSet.CreateEquipmentSet`, `C_EquipmentSet.DeleteEquipmentSet`, `C_EquipmentSet.EquipmentSetContainsLockedItems`, `C_EquipmentSet.GetEquipmentSetID`, `C_EquipmentSet.GetEquipmentSetIDs`, `C_EquipmentSet.GetEquipmentSetInfo`, `C_EquipmentSet.GetIgnoredSlots`, `C_EquipmentSet.GetItemIDs`, `C_EquipmentSet.GetItemLocations`, `C_EquipmentSet.GetNumEquipmentSets`, `C_EquipmentSet.IgnoreSlotForSave`, `C_EquipmentSet.IsSlotIgnoredForSave`, `C_EquipmentSet.ModifyEquipmentSet`, `C_EquipmentSet.SaveEquipmentSet`, `C_EquipmentSet.UnignoreSlotForSave`, `C_EquipmentSet.UseEquipmentSet` |
|
||||
| [EquipmentSet](docs/API.md#equipmentset) | `C_EquipmentSet.CanUseEquipmentSets`, `C_EquipmentSet.ClearIgnoredSlotsForSave`, `C_EquipmentSet.CreateEquipmentSet`, `C_EquipmentSet.DeleteEquipmentSet`, `C_EquipmentSet.EquipmentSetContainsLockedItems`, `C_EquipmentSet.GetEquipmentSetID`, `C_EquipmentSet.GetEquipmentSetIDs`, `C_EquipmentSet.GetEquipmentSetInfo`, `C_EquipmentSet.GetIgnoredSlots`, `C_EquipmentSet.GetItemIDs`, `C_EquipmentSet.GetItemLocations`, `C_EquipmentSet.GetNumEquipmentSets`, `C_EquipmentSet.IgnoreSlotForSave`, `C_EquipmentSet.IsSlotIgnoredForSave`, `C_EquipmentSet.ModifyEquipmentSet`, `C_EquipmentSet.PickupEquipmentSet`, `C_EquipmentSet.SaveEquipmentSet`, `C_EquipmentSet.UnignoreSlotForSave`, `C_EquipmentSet.UseEquipmentSet` |
|
||||
| [Events](docs/API.md#events) | `C_EventUtils.IsEventValid`, `GetFramesRegisteredForEvent` |
|
||||
| [Expansion](docs/API.md#expansion) | `ClassicExpansionAtLeast`, `ClassicExpansionAtMost`, `GetClassicExpansionLevel` |
|
||||
| [Faction](docs/API.md#faction) | `C_Reputation.GetFactionDataByID`, `C_Reputation.GetFactionDataByIndex`, `C_Reputation.GetFactionStandings`, `C_Reputation.GetLastStandingChange`, `C_Reputation.GetWatchedFactionData`, `C_Reputation.IsFactionActive`, `C_Reputation.IsFactionActiveByID`, `C_Reputation.IsFactionInactive`, `C_Reputation.SetFactionActive`, `C_Reputation.SetFactionActiveByID`, `C_Reputation.SetFactionInactive`, `C_Reputation.SetFactionInactiveByID`, `C_Reputation.SetSelectedFaction`, `C_Reputation.SetSelectedFactionByID`, `C_Reputation.SetWatchedFactionByID`, `C_Reputation.ToggleFactionAtWar`, `C_Reputation.ToggleFactionAtWarByID`, `GetFactionIDByIndex`, `GetFactionInfoByID`, `GetFactionParentID` |
|
||||
| [Focus](docs/API.md#focus) | `ClearFocus`, `FocusUnit` |
|
||||
| [Frame](docs/API.md#frame) | `region:SetPoint("point")` (one-arg form), `region:SetSize`, `region:GetSize`, `region:IsMouseOver`, `region:GetRect`, `region:IsDragging`, `GetMouseFoci`, `frame:SetShown`, `fontstring:GetStringHeight`, `fontstring:GetUnboundedStringWidth`, `fontstring:GetWrappedWidth`, `fontstring:GetNumLines`, `fontstring:GetLineHeight`, `fontstring:IsTruncated`, `fontstring:SetMaxLines`, `fontstring:GetMaxLines`, `fontstring:SetFormattedText`, `texture:SetRotation`, `texture:GetRotation`, `texture:SetVertexOffset`, `texture:GetVertexOffset`, `texture:SetColorTexture`, `texture:SetAtlas`, `texture:GetAtlas`, `texture:ResetTexCoord`, `texture:SetSpriteSheetCell`, `texture:SetDesaturation`, `texture:GetDesaturation`, `texture:SetMask`, `frame:CreateMaskTexture`, `texture:AddMaskTexture`, `texture:RemoveMaskTexture`, `texture:GetNumMaskTextures`, `texture:GetMaskTexture`, `fontstring:SetRotation`, `fontstring:GetRotation`, `editBox:SetCursorPosition`, `editBox:GetCursorPosition`, `editBox:GetUTF8CursorPosition`, `editBox:ClearHighlightText`, `editBox:HasFocus`, `editBox:HasText`, `editBox:SetHighlightColor`, `editBox:GetHighlightColor`, `editBox:ClearHistory`, `frame:SetResizeBounds`, `frame:HookScript`, `frame:IsEventRegistered`, `frame:RegisterUnitEvent`, `frame:GetEffectiveAlpha`, `frame:SetAttribute`, `frame:SetAttributeNoHandler`, `frame:ClearAttribute`, `frame:GetAttribute`, `OnAttributeChanged` (script), `SetModernScriptArgs`, `GetModernScriptArgs`, `PreClick` (script), `PostClick` (script), `GetClickFrame` |
|
||||
| [Frame: Region](docs/API.md#regionsetpointpoint-one-argument-form) | `:SetPoint("point")` (one-arg form), `:SetSize` / `:GetSize`, `:GetRect`, `:IsMouseOver`, `:IsDragging`, `:IsProtected` / `:CanChangeProtectedState` |
|
||||
| [Frame: Frame](docs/API.md#createframeframetype--name-parent-template-id) | `CreateFrame` template lists and `id`, `GetMouseFoci`, `:SetShown`, `:SetClampRectInsets` / `:GetClampRectInsets`, `:SetResizeBounds`, `:GetBoundsRect`, `:GetEffectiveAlpha`, `:HookScript`, `:IsEventRegistered`, `:RegisterUnitEvent`, `:SetPropagateKeyboardInput` / `:GetPropagateKeyboardInput`, `:SetDontSavePosition` / `:GetDontSavePosition`, `:SetAttribute`, `:SetAttributeNoHandler`, `:ClearAttribute`, `:GetAttribute`, `:CanChangeAttribute`, `:AllowAttributeChanges` |
|
||||
| [Frame: Button](docs/API.md#buttonsetnormalfontobjectfont--buttongetnormalfontobject) | `:SetEnabled`, `:SetFormattedText`, `:SetNormalFontObject` / `:GetNormalFontObject`, `:SetMotionScriptsWhileDisabled` / `:GetMotionScriptsWhileDisabled`, `:RegisterForClicks("AnyUp"/"AnyDown")`, `:RegisterForMouse`, `GetClickFrame` |
|
||||
| [Frame: FontString](docs/API.md#fontstringgetstringheight) | `:GetStringHeight`, `:GetUnboundedStringWidth`, `:GetWrappedWidth`, `:GetNumLines`, `:GetLineHeight`, `:GetFontHeight` / `:SetFontHeight` (also on fonts), `:GetFieldSize`, `:IsTruncated`, `:SetMaxLines` / `:GetMaxLines`, `:SetWordWrap` / `:CanWordWrap`, `:SetIndentedWordWrap` / `:GetIndentedWordWrap` (also on fonts, edit boxes, message frames, and SimpleHTML), `:SetFormattedText`, `:SetRotation` / `:GetRotation` |
|
||||
| [Frame: Texture](docs/API.md#texturesetrotationangle--cx-cy) | `:SetRotation` / `:GetRotation`, `:SetVertexOffset` / `:GetVertexOffset`, `:SetColorTexture`, `:SetAtlas` / `:GetAtlas`, `:ResetTexCoord`, `:SetSpriteSheetCell`, `:SetDesaturation` / `:GetDesaturation`, `IsDesaturateSupported`, `:SetMask`, `frame:CreateMaskTexture`, `:AddMaskTexture` / `:RemoveMaskTexture`, `:GetNumMaskTextures`, `:GetMaskTexture` |
|
||||
| [Frame: EditBox](docs/API.md#editboxsetcursorpositionposition) | `:SetCursorPosition` / `:GetCursorPosition`, `:GetUTF8CursorPosition`, `:ClearHighlightText`, `:SetHighlightColor` / `:GetHighlightColor`, `:HasFocus`, `GetCurrentKeyBoardFocus`, `:HasText`, `:ClearHistory`, `:Enable` / `:Disable` / `:IsEnabled`, `:SetCountInvisibleLetters` / `:IsCountInvisibleLetters`, `:IsInIMECompositionMode` |
|
||||
| [Frame: StatusBar](docs/API.md#statusbarsetreversefillisreversefill--statusbargetreversefill) | `:SetReverseFill` / `:GetReverseFill`, `:SetRotatesTexture` / `:GetRotatesTexture`, `:SetFillStyle` / `:GetFillStyle`, `:SetColorFill`, `:SetStatusBarDesaturated` / `:IsStatusBarDesaturated`, `:SetStatusBarDesaturation` / `:GetStatusBarDesaturation` |
|
||||
| [Frame: Slider](docs/API.md#sliderenable--sliderdisable--sliderisenabled) | `:Enable` / `:Disable` / `:IsEnabled` |
|
||||
| [Frame: Cooldown](docs/API.md#createframecooldown--name-parent-template) | `CreateFrame("Cooldown")`, `:SetCooldown`, `:SetReverse` / `:GetReverse`, `:SetDrawEdge` / `:GetDrawEdge` |
|
||||
| [Frame: ScrollingMessageFrame](docs/API.md#smfsethyperlinksenabledenabled--smfgethyperlinksenabled) | `:SetHyperlinksEnabled` / `:GetHyperlinksEnabled` |
|
||||
| [Frame: scripts](docs/API.md#onenable-and-ondisable-scripts) | `OnEnable`, `OnDisable`, `OnMinMaxChanged`, `OnAttributeChanged`, `OnCharComposition`, `OnTextChanged` (`userInput`), `PreClick`, `PostClick`, `SetModernScriptArgs` / `GetModernScriptArgs` |
|
||||
| [FriendList](docs/API.md#friendlist) | `C_FriendList.GetFriendInfo`, `C_FriendList.GetFriendInfoByIndex`, `C_FriendList.GetNumFriends`, `C_FriendList.GetNumOnlineFriends`, `C_FriendList.GetNumWhoResults`, `C_FriendList.GetWhoInfo`, `C_FriendList.IsFriend`, `C_FriendList.IsIgnored`, `C_FriendList.IsIgnoredByGuid`, `C_FriendList.IsWhoQueryPending`, `C_FriendList.SendWhoQueryByName`, `C_FriendList.SetFriendNotes`, `C_FriendList.SetFriendNotesByIndex` |
|
||||
| [GameObject](docs/API.md#gameobject) | `C_GameObjectInfo.GetGameObjectInfoByID`, `C_GameObjectInfo.RequestLoadGameObjectByID`, `ClosestGameObjectPosition` |
|
||||
| [Glue](docs/API.md#glue) | `C_Glue.IsOnGlueScreen` |
|
||||
| [Gossip](docs/API.md#gossip) | `C_GossipInfo.CloseGossip`, `C_GossipInfo.GetActiveQuests`, `C_GossipInfo.GetAvailableQuests`, `C_GossipInfo.GetNumActiveQuests`, `C_GossipInfo.GetNumAvailableQuests`, `C_GossipInfo.GetNumOptions`, `C_GossipInfo.GetOptions`, `C_GossipInfo.GetText`, `C_GossipInfo.SelectActiveQuest`, `C_GossipInfo.SelectAvailableQuest`, `C_GossipInfo.SelectOption`, `C_GossipInfo.SelectOptionByIndex` |
|
||||
| [GameTooltip](docs/API.md#gametooltip) | `GameTooltip:AddSpellByID`, `GameTooltip:GetGameObject`, `GameTooltip:GetItem`, `GameTooltip:GetOwner`, `GameTooltip:GetSpell`, `GameTooltip:GetUnitGUID`, `GameTooltip:HasGameObject`, `GameTooltip:HasItem`, `GameTooltip:HasSpell`, `GameTooltip:HasUnit`, `GameTooltip:IsEquippedItem`, `GameTooltip:SetEquipmentSet`, `GameTooltip:SetHyperlinkCompareItem`, `GameTooltip:SetInventoryItemByID`, `GameTooltip:SetItemByGUID`, `GameTooltip:SetItemByID`, `GameTooltip:SetSpellByID`, `GameTooltip:SetTalentByID`, `GameTooltip:SetTotem`, `GameTooltip:SetUnitAura`, `OnTooltipSetItem`, `OnTooltipSetSpell`, `OnTooltipSetUnit`, `OnTooltipSetGameObject` (scripts) |
|
||||
| [GameTooltip](docs/API.md#gametooltip) | `GameTooltip:AddSpellByID`, `GameTooltip:AddTexture`, `GameTooltip:GetGameObject`, `GameTooltip:GetItem`, `GameTooltip:GetMinimumWidth`, `GameTooltip:GetOwner`, `GameTooltip:GetPadding`, `GameTooltip:GetSpell`, `GameTooltip:GetUnit`, `GameTooltip:GetUnitGUID`, `GameTooltip:HasGameObject`, `GameTooltip:HasItem`, `GameTooltip:HasSpell`, `GameTooltip:HasUnit`, `GameTooltip:IsEquippedItem`, `GameTooltip:IsUnit`, `GameTooltip:SetAnchorType`, `GameTooltip:SetEquipmentSet`, `GameTooltip:SetFrameStack`, `GameTooltip:SetHyperlink` (full links, `spell:`, `quest:`), `GameTooltip:SetHyperlinkCompareItem`, `GameTooltip:SetInventoryItemByID`, `GameTooltip:SetItemByGUID`, `GameTooltip:SetItemByID`, `GameTooltip:SetSpellByID`, `GameTooltip:SetTalentByID`, `GameTooltip:SetTotem`, `GameTooltip:SetUnitAura`, `OnTooltipSetItem`, `OnTooltipSetSpell`, `OnTooltipSetUnit`, `OnTooltipSetGameObject`, `OnTooltipSetFrameStack` (scripts) |
|
||||
| [Gossip](docs/API.md#gossip) | `C_GossipInfo.CloseGossip`, `C_GossipInfo.GetActiveQuests`, `C_GossipInfo.GetAvailableQuests`, `C_GossipInfo.GetNumActiveQuests`, `C_GossipInfo.GetNumAvailableQuests`, `C_GossipInfo.GetNumOptions`, `C_GossipInfo.GetOptions`, `C_GossipInfo.GetText`, `C_GossipInfo.SelectActiveQuest`, `C_GossipInfo.SelectAvailableQuest`, `C_GossipInfo.SelectOption`, `C_GossipInfo.SelectOptionByIndex`, `GetNumGossipActiveQuests`, `GetNumGossipAvailableQuests` |
|
||||
| [Hooks](docs/API.md#hooks) | `hooksecurefunc` |
|
||||
| [Input](docs/API.md#input) | `GetMouseButtonClicked`, `IsLeftAltKeyDown`, `IsLeftControlKeyDown`, `IsLeftShiftKeyDown`, `IsModifierKeyDown`, `IsMouseButtonDown`, `IsRightAltKeyDown`, `IsRightControlKeyDown`, `IsRightShiftKeyDown` |
|
||||
| [Instance](docs/API.md#instance) | `GetInstanceInfo` |
|
||||
| [Item](docs/API.md#item) | `C_Item.DoesItemExist`, `C_Item.DoesItemExistByID`, `C_Item.EquipItemByName`, `C_Item.GetCurrentItemLevel`, `C_Item.GetDetailedItemLevelInfo`, `C_Item.GetEnchantInfo`, `C_Item.GetItemCount`, `C_Item.GetItemFamily`, `C_Item.GetItemGUID`, `C_Item.GetItemIcon`, `C_Item.GetItemIconByID`, `C_Item.GetItemID`, `C_Item.GetItemInfo`, `C_Item.GetItemInfoInstant`, `C_Item.GetItemInventorySlotInfo`, `C_Item.GetItemInventorySlotKey`, `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.GetItemSellPrice`, `C_Item.GetItemSellPriceByID`, `C_Item.GetItemSetID`, `C_Item.GetItemSetIDByID`, `C_Item.GetItemSetInfo`, `C_Item.GetItemSpell`, `C_Item.GetItemStatDelta`, `C_Item.GetItemStats`, `C_Item.GetItemClassInfo`, `C_Item.GetItemSubClassInfo`, `C_Item.GetItemTempEnchantInfo`, `C_Item.GetItemUniqueness`, `C_Item.GetItemUniquenessByID`, `C_Item.GetStackCount`, `C_Item.GetWeaponEnchantInfo`, `C_Item.IsBound`, `C_Item.IsConsumableItem`, `C_Item.IsEquippableItem`, `C_Item.IsEquippedItem`, `C_Item.IsItemDataCached`, `C_Item.IsItemDataCachedByID`, `C_Item.IsItemGUIDInInventory`, `C_Item.IsItemInRange`, `C_Item.IsItemOpenable`, `C_Item.IsLocked`, `C_Item.LockItem`, `C_Item.LockItemByGUID`, `C_Item.PickupItem`, `C_Item.UnlockAllItems`, `C_Item.UnlockItem`, `C_Item.RequestLoadItemData`, `C_Item.RequestLoadItemDataByID`, `C_Item.UseAtCursor`, `C_Item.UseAtUnit`, `C_Item.UseItemByName`, `GetAuctionItemID`, `GetAuctionSellItemID`, `GetAverageItemLevel`, `GetCraftReagentItemID`, `GetInboxItemID`, `GetInventoryItemDurability`, `GetInventoryItemID`, `GetInventoryItemsForSlot`, `GetInventoryItemRepairCost`, `GetItemClassInfo`, `GetItemIcon`, `GetItemSubClassInfo`, `GetLootRollItemID`, `GetLootSlotItemID`, `GetMerchantItemID`, `GetQuestItemID`, `GetQuestLogItemID`, `GetTradePlayerItemID`, `GetTradeSkillItemID`, `GetTradeSkillReagentItemID`, `GetTradeTargetItemID`, `OffhandHasWeapon` |
|
||||
| [Instance](docs/API.md#instance) | `GetInstanceInfo`, `IsActiveBattlefieldArena` |
|
||||
| [Item: C_Item](docs/API.md#item) | `C_Item.DoesItemExist` / `C_Item.DoesItemExistByID`, `C_Item.EquipItemByName`, `C_Item.GetCurrentItemLevel`, `C_Item.GetDetailedItemLevelInfo`, `C_Item.GetEnchantInfo`, `C_Item.GetItemClassInfo`, `C_Item.GetItemCount`, `C_Item.GetItemData` / `C_Item.GetItemDataByID`, `C_Item.GetItemFamily`, `C_Item.GetItemGUID`, `C_Item.GetItemIcon` / `C_Item.GetItemIconByID`, `C_Item.GetItemID`, `C_Item.GetItemInfo`, `C_Item.GetItemInfoInstant`, `C_Item.GetItemInventorySlotInfo`, `C_Item.GetItemInventorySlotKey`, `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.GetItemSellPrice` / `C_Item.GetItemSellPriceByID`, `C_Item.GetItemSetID` / `C_Item.GetItemSetIDByID`, `C_Item.GetItemSetInfo`, `C_Item.GetItemSpell`, `C_Item.GetItemStatDelta`, `C_Item.GetItemStats`, `C_Item.GetItemSubClassInfo`, `C_Item.GetItemTempEnchantInfo`, `C_Item.GetItemUniqueness` / `C_Item.GetItemUniquenessByID`, `C_Item.GetStackCount`, `C_Item.GetWeaponEnchantInfo`, `C_Item.IsBound`, `C_Item.IsConsumableItem`, `C_Item.IsEquippableItem`, `C_Item.IsEquippedItem`, `C_Item.IsItemDataCached` / `C_Item.IsItemDataCachedByID`, `C_Item.IsItemGUIDInInventory`, `C_Item.IsItemInRange`, `C_Item.IsItemOpenable`, `C_Item.IsLocked`, `C_Item.IsUsableItem`, `C_Item.LockItem`, `C_Item.LockItemByGUID`, `C_Item.UnlockItem`, `C_Item.UnlockAllItems`, `C_Item.PickupItem`, `C_Item.RequestLoadItemData` / `C_Item.RequestLoadItemDataByID`, `C_Item.UseAtCursor`, `C_Item.UseAtUnit`, `C_Item.UseItemByName` |
|
||||
| [Item: info](docs/API.md#getitemclassinfoclassid) | `GetItemClassInfo`, `GetItemSubClassInfo`, `GetItemIcon`, `IsConsumableItem`, `IsUsableItem` |
|
||||
| [Item: inventory](docs/API.md#getaverageitemlevel) | `GetAverageItemLevel`, `GetInventoryItemID`, `GetInventoryItemDurability`, `GetInventoryItemRepairCost`, `GetInventoryItemsForSlot`, `OffhandHasWeapon` |
|
||||
| [Item: item IDs](docs/API.md#getitemid--companions-to-the-engines-getitemlink-family) | `GetAuctionItemID`, `GetAuctionSellItemID`, `GetCraftReagentItemID`, `GetInboxItemID`, `GetLootRollItemID`, `GetLootSlotItemID`, `GetMerchantItemID`, `GetQuestItemID`, `GetQuestLogItemID`, `GetTradePlayerItemID`, `GetTradeTargetItemID`, `GetTradeSkillItemID`, `GetTradeSkillReagentItemID` |
|
||||
| [Loot](docs/API.md#loot) | `C_Loot.GetNearbyLootableUnits`, `C_Loot.GetLastScanResults`, `C_Loot.IsScanInProgress`, `C_Loot.LootAllCorpses`, `C_Loot.LootUnit`, `C_Loot.LootUnitItem`, `C_Loot.ScanNearbyLoot` |
|
||||
| [LootHistory](docs/API.md#loothistory) | `C_LootHistory.GetNumItems`, `C_LootHistory.GetItem`, `C_LootHistory.GetPlayerInfo`, `C_LootHistory.Clear` |
|
||||
| [LossOfControl](docs/API.md#lossofcontrol) | `C_LossOfControl.GetActiveLossOfControlData`, `C_LossOfControl.GetActiveLossOfControlDataCount` |
|
||||
| [Lua](docs/API.md#lua) | `collectgarbage` (5.1 options), `coroutine.create`, `coroutine.resume`, `coroutine.running`, `coroutine.status`, `coroutine.wrap`, `coroutine.yield`, `CreateFromMixins`, `math.fmod`, `math.huge`, `math.modf`, `Mixin`, `select`, `string.gmatch`, `string.gsub` (table replacement), `string.match`, `string.reverse`, `strjoin`, `strreplace`, `strrev`, `strsplit`, `strtrim`, `table.count`, `table.maxn`, `table.wipe`, `unpack` (range args), `xpcall` (argument forwarding) |
|
||||
| [Macros](docs/API.md#macros) | `C_Macro.CreateMacro`, `C_Macro.EditMacro`, `C_Macro.SetMacroDisplay`, `GetLooseMacroIcons`, `GetLooseMacroItemIcons`, `GetMacroIcons`, `GetMacroItem`, `GetMacroItemIcons`, `GetMacroSpell` |
|
||||
| [LossOfControl](docs/API.md#lossofcontrol) | `C_LossOfControl.GetActiveLossOfControlData`, `C_LossOfControl.GetActiveLossOfControlDataCount`, `C_LossOfControl.GetSchoolLockout` |
|
||||
| [Lua](docs/API.md#lua) | `collectgarbage` (5.1 options), `coroutine.create`, `coroutine.resume`, `coroutine.running`, `coroutine.status`, `coroutine.wrap`, `coroutine.yield`, `CreateFromMixins`, `math.fmod`, `math.huge`, `math.modf`, `Mixin`, `select`, `string.gmatch`, `string.gsub` (table replacement), `string.join`, `string.match`, `string.reverse`, `string.split`, `string.trim`, `strjoin`, `strmatch`, `strreplace`, `strrev`, `strsplit`, `strtrim`, `table.count`, `table.maxn`, `table.wipe`, `unpack` (range args), `xpcall` (argument forwarding) |
|
||||
| [Macros](docs/API.md#macros) | `C_Macro.CreateMacro`, `C_Macro.EditMacro`, `C_Macro.SetMacroDisplay`, `DeleteMacro` / `EditMacro` / `GetMacroInfo` / `PickupMacro` by name, `GetLooseMacroIcons`, `GetLooseMacroItemIcons`, `GetMacroIcons`, `GetMacroItem`, `GetMacroItemIcons`, `GetMacroSpell`, `StopMacro` |
|
||||
| [Mail](docs/API.md#mail) | `GetInboxItemLink`, `GetSendMailItemLink` |
|
||||
| [Map](docs/API.md#map) | `C_Map.CanSetUserWaypointOnMap`, `C_Map.ClearUserWaypoint`, `C_Map.GetAreaInfo`, `C_Map.GetAreas`, `C_Map.GetAreaTriggerInfo`, `C_Map.GetAreaTriggers`, `C_Map.GetBestMapForUnit`, `C_Map.GetFallbackWorldMapID`, `C_Map.GetMapAreaIDs`, `C_Map.GetMapArtLayers`, `C_Map.GetMapArtLayerTextures`, `C_Map.GetMapChildrenInfo`, `C_Map.GetMapInfo`, `C_Map.GetMapInfoAtPosition`, `C_Map.GetMapOverlays`, `C_Map.GetMapPosFromWorldPos`, `C_Map.GetMapRectOnMap`, `C_Map.GetMapWorldSize`, `C_Map.GetPlayerMapPosition`, `C_Map.GetUserWaypoint`, `C_Map.GetUserWaypointFromHyperlink`, `C_Map.GetUserWaypointHyperlink`, `C_Map.GetUserWaypointPositionForMap`, `C_Map.GetWorldPosFromMapPos`, `C_Map.HasUserWaypoint`, `C_Map.MapHasArt`, `C_Map.SetUserWaypoint` |
|
||||
| [MapExplorationInfo](docs/API.md#mapexplorationinfo) | `C_MapExplorationInfo.GetExploredMapTextures`, `C_MapExplorationInfo.GetUnexploredMapTextures` |
|
||||
| [MapExplorationInfo](docs/API.md#mapexplorationinfo) | `C_MapExplorationInfo.GetExploredAreaIDsAtPosition`, `C_MapExplorationInfo.GetExploredMapTextures`, `C_MapExplorationInfo.GetUnexploredMapTextures` |
|
||||
| [MerchantFrame](docs/API.md#merchantframe) | `C_MerchantFrame.GetBuybackItemID`, `C_MerchantFrame.GetItemInfo`, `C_MerchantFrame.GetNumJunkItems`, `C_MerchantFrame.IsMerchantItemRefundable`, `C_MerchantFrame.IsSellAllJunkEnabled`, `C_MerchantFrame.SellAllJunkItems` |
|
||||
| [Model](docs/API.md#model) | `DressUpModel:TryOn` (links, recipes, names), `DressUpModel:UndressSlot`, `Model:SetGlow`, `PlayerModel:RefreshCamera`, `PlayerModel:SetCamDistanceScale`, `PlayerModel:SetCreature`, `PlayerModel:SetDisplayInfo`, `PlayerModel:SetPortraitZoom`, `PlayerModel:SetRotation` (`animate`) |
|
||||
| [NamePlate](docs/API.md#nameplate) | `C_NamePlate.GetNamePlateForGUID`, `C_NamePlate.GetNamePlateForUnit`, `C_NamePlate.GetNamePlateGUIDs`, `C_NamePlate.GetNamePlates` |
|
||||
| [NameCache](docs/API.md#namecache) | `C_PlayerCache.GetPlayerInfoByName`, `C_PlayerCache.IsEnabled`, `C_PlayerCache.IsScanEnabled`, `C_PlayerCache.RememberPlayer`, `C_PlayerCache.SetEnabled`, `C_PlayerCache.SetScanEnabled`, `GetPlayerInfoByGUID`, `UnitNameFromGUID` |
|
||||
| [NewItems](docs/API.md#newitems) | `C_NewItems.ClearAll`, `C_NewItems.IsNewItem`, `C_NewItems.RemoveNewItem` |
|
||||
| [PlayerInfo](docs/API.md#playerinfo) | `C_PlayerInfo.CanUseItem`, `C_PlayerInfo.GetClass`, `C_PlayerInfo.GetName`, `C_PlayerInfo.GetRace`, `C_PlayerInfo.GetSex`, `C_PlayerInfo.GUIDIsCreature`, `C_PlayerInfo.GUIDIsGameObject`, `C_PlayerInfo.GUIDIsPet`, `C_PlayerInfo.GUIDIsPlayer`, `C_PlayerInfo.IsConnected` |
|
||||
| [Quest](docs/API.md#quest) | `C_QuestLog.GetNumQuestObjectives`, `C_QuestLog.GetQuestDetails`, `C_QuestLog.GetHeaderIndexForQuest`, `C_QuestLog.GetLogIndexForQuestID`, `C_QuestLog.GetQuestIDForLogIndex`, `C_QuestLog.GetTitleForQuestID`, `C_QuestLog.IsOnQuest`, `C_QuestLog.IsQuestDataCachedByID`, `C_QuestLog.IsUnitOnQuest`, `C_QuestLog.RequestLoadQuestByID`, `GetQuestLogLeaderBoardID` |
|
||||
| [Quest](docs/API.md#quest) | `C_QuestLog.GetInfo`, `C_QuestLog.GetNumQuestObjectives`, `C_QuestLog.GetQuestDetails`, `C_QuestLog.GetQuestLogTitle`, `C_QuestLog.GetHeaderIndexForQuest`, `C_QuestLog.GetLogIndexForQuestID`, `C_QuestLog.GetQuestIDForLogIndex`, `C_QuestLog.GetTitleForQuestID`, `C_QuestLog.IsOnQuest`, `C_QuestLog.IsQuestDataCachedByID`, `C_QuestLog.IsUnitOnQuest`, `C_QuestLog.RequestLoadQuestByID`, `GetQuestLogLeaderBoardID` |
|
||||
| [Sound](docs/API.md#sound) | `C_Sound.GetRecentSoundFiles`, `C_Sound.GetSoundScaledVolume`, `C_Sound.IsPlaying`, `C_Sound.PlayItemSound`, `C_Sound.PlaySound`, `C_Sound.PlaySoundWithOptions`, `C_Sound.PlayVocalErrorSound`, `MuteSoundFile`, `PlaySound`, `PlaySoundFile`, `StopSound`, `UnmuteSoundFile` |
|
||||
| [Spell](docs/API.md#spell) | `C_Spell.CancelSpellByID`, `C_Spell.CastAtCursor`, `C_Spell.CastAtUnit`, `C_Spell.CastingInfo`, `C_Spell.ChannelInfo`, `C_Spell.DoesSpellExist`, `C_Spell.GetSchoolString`, `C_Spell.GetSpellCastCount`, `C_Spell.GetSpellCooldown`, `C_Spell.GetSpellDescription`, `C_Spell.GetSpellDispelType`, `C_Spell.GetSpellEffectInfo`, `C_Spell.GetSpellEffectMechanics`, `C_Spell.GetSpellInfo`, `C_Spell.GetSpellLevelInfo`, `C_Spell.GetSpellLink`, `C_Spell.GetSpellLossOfControlCooldown`, `C_Spell.GetSpellMechanicByID`, `C_Spell.GetSpellName`, `C_Spell.GetSpellPowerCost`, `C_Spell.GetSpellRadius`, `C_Spell.GetSpellReagents`, `C_Spell.GetSpellRequiredTargetLevel`, `C_Spell.GetSpellSubtext`, `C_Spell.GetSpellTexture`, `C_Spell.IsAutoAttackSpell`, `C_Spell.IsCurrentSpell`, `C_Spell.IsNextMeleeSpell`, `C_Spell.IsRangedAutoAttackSpell`, `C_Spell.IsSelfBuff`, `C_Spell.IsSpellHarmful`, `C_Spell.IsSpellHelpful`, `C_Spell.IsSpellInRange`, `C_Spell.IsSpellPassive`, `C_Spell.IsSpellUsable`, `C_Spell.ResetsMeleeSwing`, `C_Spell.SpellHasRange`, `C_Spell.UnitCastingInfo`, `C_Spell.UnitChannelInfo`, `CanDualWield`, `CancelSpellByName`, `CastSpellNoToggle`, `GetCraftSpellID`, `GetSpellBonusDamage`, `GetSpellBonusHealing`, `GetSpellInfo`, `GetSpellLink`, `GetSpellRadius`, `GetSpellRequiredTargetLevel`, `GetSpellSchool`, `IsHarmfulSpell`, `IsHelpfulSpell`, `IsPassiveSpell`, `IsPlayerSpell`, `IsSpellKnown`, `IsUsableSpell`, `SpellHasRange` |
|
||||
| [SpellBook](docs/API.md#spellbook) | `C_SpellBook.ContainsAnyDisenchantSpell`, `C_SpellBook.GetCurrentLevelSpells`, `C_SpellBook.GetNumSpellBookSkillLines`, `C_SpellBook.GetPlayerSpellsByAura`, `C_SpellBook.GetSkillLineIndexByID`, `C_SpellBook.GetSkillLineName`, `C_SpellBook.GetSkillLineRank`, `C_SpellBook.GetSpellBookItemCastCount`, `C_SpellBook.GetSpellBookItemInfo`, `C_SpellBook.GetSpellBookItemLossOfControlCooldownDuration`, `C_SpellBook.GetSpellBookItemLossOfControlCooldownInfo`, `C_SpellBook.GetSpellBookItemSkillLineIndex`, `C_SpellBook.GetSpellBookSkillLineInfo`, `C_SpellBook.GetSpellLevelLearned`, `C_SpellBook.GetSpellSkillLine`, `C_SpellBook.IsAutoAttackSpellBookItem`, `C_SpellBook.IsClassTalentSpellBookItem`, `C_SpellBook.IsRangedAutoAttackSpellBookItem`, `FindSpellBookSlotByID` |
|
||||
| [State](docs/API.md#state) | `CancelShapeshiftForm`, `Dismount`, `GetMirrorTimerInfo`, `GetMirrorTimerProgress`, `GetShapeshiftFormID`, `GetSheathState`, `IsAssistingRitual`, `IsFalling`, `IsIndoors`, `IsInGroup`, `IsInRaid`, `IsLoggedIn`, `IsMounted`, `IsOutdoors`, `IsStealthed`, `IsSwimming` |
|
||||
| [SwingTimer](docs/API.md#swingtimer) | `C_SwingTimer.EnableRangeCheck`, `C_SwingTimer.IsTargetWithinSwingRange` |
|
||||
| [System](docs/API.md#system) | `CopyToClipboard`, `GetPhysicalScreenSize` |
|
||||
| [Talent](docs/API.md#talent) | `GetTalentIDByIndex`, `GetTalentSpellID` |
|
||||
| [Targeting](docs/API.md#targeting) | `GetPlayerFacing`, `TargetDirectionEnemy`, `TargetDirectionFriend`, `TargetNearest`, `TargetNearestEnemyPlayer`, `TargetNearestFriendPlayer` |
|
||||
| [Targeting](docs/API.md#targeting) | `GetPlayerFacing`, `TargetDirectionEnemy`, `TargetDirectionFriend`, `TargetDirectionFinished`, `TargetNearest`, `TargetNearestEnemyPlayer`, `TargetNearestFriendPlayer`, `InteractUnit`, `C_PlayerInteractionManager.InteractUnit`, `IsTargetLoose` |
|
||||
| [TaxiMap](docs/API.md#taximap) | `C_TaxiMap.GetTaxiNodesForMap`, `C_TaxiMap.GetAllTaxiNodes`, `C_TaxiMap.GetTaxiPaths`, `C_TaxiMap.GetTaxiPathWaypoints`, `C_TaxiMap.GetTaxiRoute` |
|
||||
| [Texture](docs/API.md#texture) | `C_Texture.GetAtlasElementID`, `C_Texture.GetAtlasElements`, `C_Texture.GetAtlasExists`, `C_Texture.GetAtlasID`, `C_Texture.GetAtlasInfo`, `C_Texture.RegisterAtlas` |
|
||||
| [Time](docs/API.md#time) | `C_DateAndTime.AdjustTimeByDays`, `C_DateAndTime.AdjustTimeByMinutes`, `C_DateAndTime.CompareCalendarTime`, `C_DateAndTime.GetCalendarTimeFromEpoch`, `C_DateAndTime.GetCurrentCalendarTime`, `C_DateAndTime.GetSecondsUntilDailyReset`, `C_DateAndTime.GetServerTimeLocal`, `C_Timer.After`, `C_Timer.NewTicker`, `C_Timer.NewTimer`, `GetServerTime`, `GetTimeCached` |
|
||||
| [Totem](docs/API.md#totem) | `GetTotemInfo`, `GetTotemTimeLeft`, `GetTotemDuration`, `TargetTotem` |
|
||||
| [Tracking](docs/API.md#tracking) | `GetNumTrackingTypes`, `GetTrackingInfo`, `SetTracking` |
|
||||
| [TradeSkillUI](docs/API.md#tradeskillui) | `C_TradeSkillUI.GetTradeSkillListLink`, `C_TradeSkillUI.GetCraftListLink`, `C_TradeSkillUI.GetTradeSkillListRecipes` |
|
||||
| [TradeSkillUI](docs/API.md#tradeskillui) | `C_TradeSkillUI.GetTradeSkillListLink`, `C_TradeSkillUI.GetCraftListLink`, `C_TradeSkillUI.GetTradeSkillListRecipes`, `GetTradeSkillRecipeLink`, `IsTradeSkillLinked` |
|
||||
| [UIColor](docs/API.md#uicolor) | `C_UIColor.GetColors` |
|
||||
| [Unit](docs/API.md#unit) | `ClosestUnitPosition`, `GetUnitSpeed`, `IsUnitToken`, `UnitClassBase`, `UnitCreatedBySpell`, `UnitCreatureFamilyID`, `UnitCreatureID`, `UnitCreatureTypeID`, `UnitDistanceSquared`, `UnitGUID`, `UnitHealthMissing`, `UnitInLineOfSight`, `UnitInRange`, `UnitIsAFK`, `UnitIsDND`, `UnitIsFeignDeath`, `UnitIsInMyGuild`, `UnitIsMinion`, `UnitIsOtherPlayersPet`, `UnitIsPet`, `UnitIsPossessed`, `UnitOwnerGUID`, `UnitPosition`, `UnitPower`, `UnitPowerMax`, `UnitPowerMissing`, `UnitPowerType`, `UnitRaceBase`, `UnitSpellHaste`, `UnitSpellTargetName`, `UnitStandState`, `UnitSubName`, `UnitTokenFromGUID`, `UnitTokenFromName` |
|
||||
| [Unit](docs/API.md#unit) | `ClosestUnitPosition`, `GetUnitSpeed`, `IsUnitToken`, `SetUnitCursorTexture`, `UnitClassBase`, `UnitCreatedBySpell`, `UnitCreatureFamilyID`, `UnitCreatureID`, `UnitCreatureTypeID`, `UnitDistanceSquared`, `UnitGUID`, `UnitHealthMissing`, `UnitInLineOfSight`, `UnitInRange`, `UnitIsAFK`, `UnitIsDND`, `UnitIsFeignDeath`, `UnitIsInMyGuild`, `UnitIsMinion`, `UnitIsOtherPlayersPet`, `UnitIsPet`, `UnitIsPossessed`, `UnitOwnerGUID`, `UnitPosition`, `UnitPower`, `UnitPowerMax`, `UnitPowerMissing`, `UnitPowerType`, `UnitRaceBase`, `UnitSelectionColor`, `UnitSelectionType`, `UnitSpellHaste`, `UnitSpellTargetName`, `UnitStandState`, `UnitSubName`, `UnitTokenFromGUID`, `UnitTokenFromName` |
|
||||
| [UnitAuras](docs/API.md#unitauras) | `C_UnitAuras.GetAuraDataByIndex`, `C_UnitAuras.GetAuraDataBySlot`, `C_UnitAuras.GetAuraDataBySpellName`, `C_UnitAuras.GetAuraDispelTypeColor`, `C_UnitAuras.GetAuraSlots`, `C_UnitAuras.GetBuffDataByIndex`, `C_UnitAuras.GetDebuffDataByIndex`, `C_UnitAuras.GetPlayerAuraBySpellID`, `C_UnitAuras.GetUnitAuraBySpellID`, `C_UnitAuras.GetUnitAuras`, `C_UnitAuras.RegisterAuraDurationModifierByTrigger`, `C_UnitAuras.RegisterComboDuration`, `C_UnitAuras.UnitAura`, `C_UnitAuras.UnitAuraBySlot`, `C_UnitAuras.UnitBuff`, `C_UnitAuras.UnitDebuff` |
|
||||
| [VoiceChat](docs/API.md#voicechat) | `C_VoiceChat.GetTtsVoices`, `C_VoiceChat.GetRemoteTtsVoices`, `C_VoiceChat.SpeakText`, `C_VoiceChat.StopSpeakingText`, `C_TTSSettings.GetSpeechRate`, `C_TTSSettings.GetSpeechVolume`, `C_TTSSettings.GetSpeechVoiceID`, `C_TTSSettings.GetVoiceOptionName`, `C_TTSSettings.SetSpeechRate`, `C_TTSSettings.SetSpeechVolume`, `C_TTSSettings.SetVoiceOption`, `C_TTSSettings.SetVoiceOptionByName`, `C_TTSSettings.SetDefaultSettings`, `C_TTSSettings.RefreshVoices` |
|
||||
| [XMLUtil](docs/API.md#xmlutil) | `C_XMLUtil.DoesTemplateExist`, `C_XMLUtil.GetTemplateInfo`, `C_XMLUtil.GetTemplates` |
|
||||
@@ -131,7 +162,7 @@ the glue state because GlueXML had no way to reach them otherwise.
|
||||
|-------|-------|
|
||||
| [Account](docs/API.md#account) | `SaveAccount`, `DeleteAccount`, `GetSavedAccounts`, `LoginWithSavedAccount` (passwords encrypted in Windows Credential Manager, scoped per realmlist; plaintext never returned to Lua) |
|
||||
| [CharacterList](docs/API.md#characterlist) | `GetSavedCharacterOrder`, `SetSavedCharacterOrder` (persist to `WTF\Account\...\ClassicAPI.txt`) |
|
||||
| CVar | `GetCVar`, `SetCVar`, `RegisterCVar`, `GetCVarDefault`, `C_CVar.GetCVarBool` (storage is process-global — writes from glue are visible in-world and vice versa) |
|
||||
| CVar | `GetCVar`, `SetCVar`, `RegisterCVar`, `GetCVarDefault`, `C_CVar.GetCVarBool`, `C_CVar.SetTempCVar`, `C_CVar.RemoveTempCVar` (storage is process-global — writes from glue are visible in-world and vice versa) |
|
||||
| [Glue](docs/API.md#glue) | `C_Glue.IsFirstLoadThisSession`, `C_Glue.IsOnGlueScreen` |
|
||||
| Script | `RunScript` (compile and run a Lua chunk in the glue state's globals — useful for slash-command-style helpers in GlueXML) |
|
||||
| State | `IsLoggedIn` |
|
||||
@@ -148,7 +179,7 @@ details.
|
||||
| Form | What it does |
|
||||
|------|--------------|
|
||||
| `#showtooltip [conditions] Value` | First line of a macro. Sets what the button shows. Bare `#showtooltip` follows the first `/cast` or `/use` line instead. `#show` is the same form. |
|
||||
| `[conditions]` and `@unit` | Accepted by 38 commands. The slash-command list below names them. |
|
||||
| `[conditions]` and `@unit` | Accepted by 42 commands. The slash-command list below names them. |
|
||||
| `!Name` | Starts an ability but never turns it off. Use it for auto-repeat shots and for the self-buffs (stance, aspect, seal, form, tracking). |
|
||||
| A line that starts with `#` | A comment. The line never reaches chat. |
|
||||
| `/cast <spellID>` | For a spell you know, `/cast 5019` casts it by ID. The macro slot also tags correctly for an action-bar addon. |
|
||||
@@ -158,17 +189,19 @@ details.
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Slash commands</b> — <code>[conditions]</code> on 38 commands</summary>
|
||||
<summary><b>Slash commands</b> — <code>[conditions]</code> on 42 commands</summary>
|
||||
|
||||
The bundled addon registers these commands. Each one takes the same
|
||||
`[conditions]` and `@unit` syntax as `/cast`. Each client language has its
|
||||
own command names next to the English ones. See
|
||||
[More commands with `[conditions]`](docs/API.md#more-commands-with-conditions)
|
||||
for what each command does.
|
||||
for what each command does, and
|
||||
[`/castsequence`](docs/API.md#castsequence) and
|
||||
[`/castrandom`](docs/API.md#castrandom-and-userandom) for the list forms.
|
||||
|
||||
| Group | Commands |
|
||||
|-------|----------|
|
||||
| Casting | `/cast`, `/use`, `/stopcasting`, `/cancelaura`, `/cancelform`, `/dismount` |
|
||||
| Casting | `/cast`, `/use`, `/castsequence`, `/castrandom`, `/userandom`, `/stopcasting`, `/stopmacro`, `/cancelaura`, `/cancelform`, `/dismount` |
|
||||
| Targeting | `/target`, `/targetexact`, `/cleartarget`, `/targetlasttarget`, `/targetlastenemy`, `/targetenemy`, `/targetfriend`, `/targetenemyplayer`, `/targetfriendplayer`, `/targetparty`, `/targetraid`, `/assist`, `/follow`, `/focus`, `/clearfocus`, `/startattack`, `/stopattack` |
|
||||
| Equipment | `/equip`, `/equipslot`, `/equipset` |
|
||||
| Action bars | `/changeactionbar`, `/swapactionbar`, `/click` |
|
||||
@@ -176,6 +209,42 @@ for what each command does.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>CVars</b> — new settings, set with <code>/console name value</code></summary>
|
||||
|
||||
Each setting is saved in `WTF\Config.wtf`. Read and write them with `GetCVar`
|
||||
/ `SetCVar` or `/console`. Click a group name for the full rules. To change
|
||||
the most common settings and the player cache in the game, open the game
|
||||
menu and click AddOn Options, then ClassicAPI.
|
||||
|
||||
| Group | CVar | Default | What it does |
|
||||
|-------|------|---------|--------------|
|
||||
| [Bindings](docs/API.md#actionbuttonusekeydown) | `ActionButtonUseKeyDown` | `0` | `1` uses an action-bar key binding when you press the key. `0` uses it when you release the key. |
|
||||
| [Combat](docs/API.md#stopautoattackontargetchange) | `stopAutoAttackOnTargetChange` | `0` | `1` stops melee auto-attack, Auto Shot and wand shots when you change target. |
|
||||
| [Cast settings](docs/API.md#cast-settings-autostand-autodismount-autounshift) | `autoStand` | `0` | `1` makes you stand up when you cast while you sit. |
|
||||
| | `autoDismount` | `0` | `1` makes you dismount when you cast while you are mounted. |
|
||||
| | `autoUnshift` | `0` | `1` makes you leave your form when a spell cannot be cast in it. |
|
||||
| [Soft interact](docs/API.md#soft-interact-softinteract--anyinteract) | `SoftTargetInteract` | `3` | Turns `softinteract` on: `2` keyboard and mouse, `3` always, `0` / `1` off. |
|
||||
| | `SoftTargetInteractArc` | `0` | Where the object can be: `0` straight ahead of the camera, `1` within 30° of it, `2` any direction. |
|
||||
| | `SoftTargetInteractRange` | `10` | Maximum distance in yards. |
|
||||
| | `SoftTargetInteractRangeIsHard` | `0` | `1` always applies the range. `0` also picks an object past it that you can use now. |
|
||||
| | `SoftTargetIconInteract` | `0` | `1` shows an icon over the soft-interact object. |
|
||||
| | `SoftTargetIconGameObject` | `0` | `1` also shows that icon over game objects. |
|
||||
| [Soft enemy / friend](docs/API.md#soft-enemy-and-soft-friend-softenemy--softfriend--anyenemy--anyfriend) | `SoftTargetEnemy` / `SoftTargetFriend` | `1` / `0` | Turns `softenemy` / `softfriend` on: `2` keyboard and mouse, `3` always, `0` / `1` off. |
|
||||
| | `SoftTargetEnemyArc` / `SoftTargetFriendArc` | `0` | The same values as `SoftTargetInteractArc`. |
|
||||
| | `SoftTargetEnemyRange` / `SoftTargetFriendRange` | `45` | Maximum distance in yards. |
|
||||
| | `SoftTargetMatchLocked` | `1` | `1` uses your target as the soft unit when it qualifies. `0` always uses the nearest unit. |
|
||||
| | `SoftTargetWithLocked` | `1` | `0` turns soft enemy and soft friend off while you have a locked target. |
|
||||
| | `SoftTargetForce` | `1` | A loose target follows `softenemy` (`1`) or `softfriend` (`2`). `0` keeps it. |
|
||||
| | `SoftTargetIconEnemy` / `SoftTargetIconFriend` | `0` | `1` shows an icon over `softenemy` / `softfriend`. |
|
||||
| | `SoftTargetLowPriorityIcons` | `0` | `1` also shows the normal pointer as an icon. |
|
||||
| | `SoftTargetNameplateSize` | `19` | Size of all soft-target icons. |
|
||||
| [Text to speech](docs/API.md#tts-cvars) | `ttsVoice` | `0` | The voice that `C_VoiceChat.SpeakText` uses. |
|
||||
| | `ttsSpeed` | `0` | Speech rate, `-10` to `10`. |
|
||||
| | `ttsVolume` | `100` | Speech volume, `0` to `100`. |
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Console commands</b> — developer console (<code>-console</code>)</summary>
|
||||
|
||||
@@ -188,6 +257,10 @@ when launching with `-console`), not as Lua functions. See the
|
||||
| `ExportInterfaceFiles code` | Extracts Blizzard's UI source (`.lua`/`.xml`/`.toc`/`.xsd`) from the MPQs to `BlizzardInterfaceCode\` |
|
||||
| `ExportInterfaceFiles art` | Extracts Blizzard's UI art (`.blp`/`.tga`) from the MPQs to `BlizzardInterfaceArt\` |
|
||||
| `ExportDBCFiles` | Extracts the client's `.dbc` tables from the MPQs to `DBFilesClient\` |
|
||||
| `ExportSoundFiles [subpath]` | Extracts the client's sound files from the MPQs to `BlizzardSound\`; the optional subpath narrows it (the full tree is ~1 GB) |
|
||||
| `pitchLimit degrees` | Sets how far the camera can tilt up and down (default 89) |
|
||||
| `AppendLogToFile [filename] [numLines]` | Writes the console output to a text file (default `ConsoleLogs\Log<Timestamp>.txt`) |
|
||||
| Tab / Ctrl+Tab | Tab completes CVar names after `set`, `cvar_reset` and `cvar_default`; Ctrl+Tab lists every command that contains the typed text |
|
||||
|
||||
</details>
|
||||
|
||||
@@ -198,6 +271,9 @@ when launching with `-console`), not as Lua functions. See the
|
||||
|-------|---------|
|
||||
| `BAG_NEW_ITEMS_UPDATED` | *(none)* |
|
||||
| `BAG_UPDATE_DELAYED` | *(none)* |
|
||||
| `CHAT_MSG_*` | adds `lineID, guid` as `arg11, arg12` after the existing ten ([details](docs/API.md#chat_msg_-arguments-lineid-arg11-and-guid-arg12)) |
|
||||
| `COMBAT_LOG_EVENT` | `timestamp, subevent, hideCaster, sourceGUID, sourceName, sourceFlags, sourceRaidFlags, destGUID, destName, destFlags, destRaidFlags, ...` ([details](docs/API.md#combat_log_event_unfiltered--combat_log_event-events)) |
|
||||
| `COMBAT_LOG_EVENT_UNFILTERED` | same as `COMBAT_LOG_EVENT` |
|
||||
| `CURSOR_CHANGED` | `isDefault, newCursorType, oldCursorType, oldCursorVirtualID` |
|
||||
| `EQUIPMENT_SETS_CHANGED` | *(none)* |
|
||||
| `EQUIPMENT_SWAP_PENDING` | `setID` |
|
||||
@@ -213,23 +289,31 @@ when launching with `-console`), not as Lua functions. See the
|
||||
| `LOOT_SCAN_COMPLETED` | *(none)* |
|
||||
| `LOSS_OF_CONTROL_ADDED` | `eventIndex` |
|
||||
| `LOSS_OF_CONTROL_UPDATE` | `unitToken` (always `"player"`) |
|
||||
| `MAP_EXPLORATION_UPDATED` | *(none)* |
|
||||
| `MODIFIER_STATE_CHANGED` | `keyName, down` |
|
||||
| `NAME_PLATE_CREATED` | `nameplateFrame` |
|
||||
| `NAME_PLATE_UNIT_ADDED` | `unitToken` ("nameplateN") |
|
||||
| `NAME_PLATE_UNIT_REMOVED` | `unitToken` ("nameplateN") |
|
||||
| `PLAYER_AVG_ITEM_LEVEL_READY` | *(none)* |
|
||||
| `PLAYER_EQUIPMENT_CHANGED` | `equipmentSlot, hasCurrent` |
|
||||
| `PLAYER_FOCUS_CHANGED` | *(none)* |
|
||||
| `PLAYER_SOFT_ENEMY_CHANGED` | *(none)* |
|
||||
| `PLAYER_SOFT_FRIEND_CHANGED` | *(none)* |
|
||||
| `PLAYER_SOFT_INTERACT_CHANGED` | `oldTarget, newTarget` |
|
||||
| `PLAYER_STARTED_LOOKING` | *(none)* |
|
||||
| `PLAYER_STOPPED_LOOKING` | *(none)* |
|
||||
| `PLAYER_STARTED_MOVING` | *(none)* |
|
||||
| `PLAYER_STOPPED_MOVING` | *(none)* |
|
||||
| `PLAYER_STARTED_TURNING` | *(none)* |
|
||||
| `PLAYER_STOPPED_TURNING` | *(none)* |
|
||||
| `PLAYER_SWING` | `swingDuration, swingType` |
|
||||
| `PLAYER_SWING_RANGE_UPDATE` | `swingType, isInRange, checksRange` |
|
||||
| `PLAYER_TOTEM_UPDATE` | `totemSlot` |
|
||||
| `QUEST_ACCEPTED` | `questLogIndex, questID` |
|
||||
| `QUEST_DATA_LOAD_RESULT` | `questID, success` |
|
||||
| `QUEST_REMOVED` | `questID` |
|
||||
| `QUEST_TURNED_IN` | `questID, xpReward, moneyReward` |
|
||||
| `SOUNDKIT_FINISHED` | `soundHandle` (only for sounds played with `runFinishCallback`) |
|
||||
| `UNIT_SPELLCAST_SENT` | `"player", target, castGUID, spellID, spellName, rank` |
|
||||
| `UNIT_SPELLCAST_START` | `unit, castGUID, spellID, spellName, rank` |
|
||||
| `UNIT_SPELLCAST_STOP` | `unit, castGUID, spellID, spellName, rank` |
|
||||
@@ -243,6 +327,8 @@ when launching with `-console`), not as Lua functions. See the
|
||||
| `UNIT_SPELLCAST_CHANNEL_STOP` | `unit, castGUID, spellID, spellName, rank` |
|
||||
| `UNIT_SPELLCAST_RETICLE_TARGET` | `"player", "", spellID, spellName, rank` |
|
||||
| `UNIT_SPELLCAST_RETICLE_CLEAR` | `"player", "", spellID, spellName, rank` |
|
||||
| `UNIT_SPELLCAST_INTERRUPTIBLE` | `unit` |
|
||||
| `UNIT_SPELLCAST_NOT_INTERRUPTIBLE` | `unit` |
|
||||
| `UPDATE_INVENTORY_DURABILITY` | *(none)* |
|
||||
| `UPDATE_SHAPESHIFT_FORM` | *(none)* |
|
||||
| `USER_WAYPOINT_UPDATED` | *(none)* |
|
||||
@@ -250,6 +336,8 @@ when launching with `-console`), not as Lua functions. See the
|
||||
| `VOICE_CHAT_TTS_PLAYBACK_FINISHED` | `numConsumers, utteranceID, destination` |
|
||||
| `VOICE_CHAT_TTS_PLAYBACK_FAILED` | `status, utteranceID, destination` |
|
||||
| `VOICE_CHAT_TTS_VOICES_UPDATE` | *(none)* |
|
||||
| `WEAPON_SLOT_CHANGED` | *(none)* |
|
||||
| `WEAR_EQUIPMENT_SET` | `setID` |
|
||||
|
||||
</details>
|
||||
|
||||
@@ -270,17 +358,20 @@ when launching with `-console`), not as Lua functions. See the
|
||||
| Cursor type | `Enum.UICursorType.{Default,Item,Money,Spell,PetAction,Merchant,Macro,Pet,…}` (0–20; this client yields 0–5, 7 and 9) |
|
||||
| Spellbook bank | `Enum.SpellBookSpellBank.{Player,Pet}` (0–1) |
|
||||
| Spellbook item type | `Enum.SpellBookItemType.{None,Spell,FutureSpell,PetAction,Flyout}` (0–4; 1.12 only yields `Spell`/`PetAction`) |
|
||||
| Player swing type | `Enum.PlayerSwingType.{MainHand,OffHand,Ranged}` (0–2) |
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Unit tokens</b> — <code>nameplateN</code>, <code>focus</code>, <code>markN</code></summary>
|
||||
<summary><b>Unit tokens</b> — <code>nameplateN</code>, <code>focus</code>, <code>markN</code>, <code>softinteract</code>, <code>softenemy</code>, <code>softfriend</code>, <code>anyinteract</code>, <code>anyenemy</code>, <code>anyfriend</code></summary>
|
||||
|
||||
| Token | Resolves to |
|
||||
|-------|-------------|
|
||||
| `nameplate1`..`nameplateN` | Unit behind the Nth visible nameplate, in creation-order. Works with every `UnitX` function — `UnitName`, `UnitGUID`, `UnitClass`, `UnitHealth`, etc. Suffix chains (`nameplate1target`, `nameplate1targettarget`) compose. See [NamePlate / Unit tokens](docs/API.md#unit-tokens-nameplaten). |
|
||||
| `focus` / `focustarget` | Sticky target set via [`FocusUnit`](docs/API.md#focusunitunit), cleared via [`ClearFocus`](docs/API.md#clearfocus). Same `UnitX` coverage as `nameplateN`. Fires [`PLAYER_FOCUS_CHANGED`](docs/API.md#player_focus_changed-event) on transition. See [Focus](docs/API.md#focus). |
|
||||
| `mark1`..`mark8` | Unit currently wearing the Nth raid-target marker (`mark1` = star … `mark8` = skull). Same `UnitX` coverage as `nameplateN`, and fires unit events (`UNIT_HEALTH`, `UNIT_AURA`, …) with `arg1 == "markN"`. `UnitExists("markN")` is `false` when the marker is unset, out of range, or on a non-unit. Suffix chains (`mark1target`) compose. See [Unit tokens (`markN`)](docs/API.md#unit-tokens-markn). |
|
||||
| `softinteract` / `anyinteract` / `anyleftinteract` | The object that the Interact Key uses. `softinteract` is the nearest object in front of you that you can interact with. `anyinteract` is your target when you can interact with it, else `softinteract`. Both can be a game object or a corpse, which only `UnitGUID` reads. See [Soft interact](docs/API.md#soft-interact-softinteract--anyinteract). |
|
||||
| `softenemy` / `softfriend` / `anyenemy` / `anyfriend` | The nearest enemy and the nearest friendly unit, or your target when it qualifies. `anyenemy` and `anyfriend` use your target first. See [Soft enemy and soft friend](docs/API.md#soft-enemy-and-soft-friend-softenemy--softfriend--anyenemy--anyfriend). |
|
||||
|
||||
</details>
|
||||
|
||||
|
||||
@@ -951,88 +951,15 @@ See [src/unit/Tooltip.cpp](src/unit/Tooltip.cpp) and the
|
||||
`FUN_SCRIPT_GAMETOOLTIP_SET_UNIT_*` block in
|
||||
[src/Offsets.h](src/Offsets.h).
|
||||
|
||||
## 46. `GameTooltip:SetFrameStack([showHidden])` — deferred (Lua-side fix in place)
|
||||
## ~~46. `GameTooltip:SetFrameStack([showHidden])`~~ — DONE
|
||||
|
||||
Renders a tooltip listing the chain of frames at the mouse cursor,
|
||||
sorted by strata + level. The 3.0+ debug-tooling primitive used by
|
||||
Blizzard's `Blizzard_DebugTools` and every layout-debugging addon.
|
||||
|
||||
### Current state in this project
|
||||
|
||||
Our bundled `DebugTools/` backport ships its own `FrameStackTooltip`
|
||||
in [DebugTools/DebugTools.lua](DebugTools/DebugTools.lua), driven
|
||||
by `_CollectFramesUnderMouse`. As of the EnumerateFrames switch,
|
||||
the iterator walks the engine's own frame list — fast (typically
|
||||
~hundreds of entries) and includes anonymous frames the engine
|
||||
sees but a `_G` walk would miss.
|
||||
|
||||
What's still missing relative to the real engine `SetFrameStack`:
|
||||
|
||||
- **Anonymous-frame display name.** We currently show
|
||||
`<anonymous>` for frames where `frame:GetName()` returns nil.
|
||||
The engine's method shows the frame's pointer + the Lua-side
|
||||
registry-table address. To get there we'd need a Lua-callable
|
||||
shim that exposes a numeric handle per frame (vftable + Lua-ref
|
||||
lookup), which is non-trivial.
|
||||
- **Single-tooltip semantics.** Modern addons can call
|
||||
`GameTooltip:SetFrameStack(...)` directly on any tooltip;
|
||||
ours requires the `FrameStackTooltip` we ship in `DebugTools/`.
|
||||
Most consumers (`Blizzard_DebugTools` ports, layout addons via
|
||||
`/framestack`) don't care, but a strict polyfill would.
|
||||
|
||||
### C++ port from 3.3.5 — kept as a research note
|
||||
|
||||
What `Script_GameTooltip_SetFrameStack`
|
||||
actually does in 3.3.5 (Frostmourne client, registration entry at
|
||||
VA 0x00AD2CF0 → function VA 0x00626560 → inner builder
|
||||
`FUN_006230d0`):
|
||||
|
||||
- Pulls cursor (in frame space) via `FUN_0047BFF0` from a render-
|
||||
state global at `[DAT_00B499A8 + 0x1224 / +0x1228]`.
|
||||
- Walks an intrusive linked list at `[DAT_00B499A8 + 0xCD4]`. Each
|
||||
frame node reads:
|
||||
- `[+0x00]` — vftable; `vftable[+0x10]` = "is the frame visible
|
||||
enough to hit-test" predicate.
|
||||
- `[+0x0E0]` (`node[0x38]`) = strata; gates `(strata != 0 ||
|
||||
showHidden)`.
|
||||
- `[+0x0D0]..[+0x0DC]` (`node[0x34..0x37]`) = frame rect for
|
||||
hit-test.
|
||||
- `[+0x0D8]` (`node[0x36]`) flags, bit 2 → visible.
|
||||
- `[+0x288]` (`node[0xA2]`) = next pointer.
|
||||
- Per-frame name via `vftable[+0x04]` (a `GetDebugName()`-style
|
||||
virtual). If the frame is Lua-side (`vftable[+0x10]` returns
|
||||
type code 5), an extra `lua_rawgeti(L, REGISTRY, frame->luaRef)`
|
||||
pulls the Lua-table reference for the `"%s: %p (%s)"` format;
|
||||
otherwise it's `"%s: %p"`.
|
||||
- Builds into a scratch sort array at `DAT_00C5D370` (entry stride
|
||||
`0x410`), `qsort` against comparator `FUN_0061A5B0`.
|
||||
- Header line via `FUN_00819D40("DEBUG_FRAMESTACK", ...)` (Lua
|
||||
`GetGlobalString`) then per-entry `FUN_0061FEC0` (tooltip
|
||||
`AddLine` equivalent, takes color codes from a 4-byte-stride
|
||||
table at `0xAD2DC0` / `0xAD2DB8` / `0xAD2DB0` for
|
||||
visible/hidden/special states).
|
||||
|
||||
For a 1.12 port we'd need to derive:
|
||||
|
||||
- The frame-manager global (3.3.5's `DAT_00B499A8` — different VA
|
||||
in 1.12, different field offsets likely).
|
||||
- Frame struct offsets for rect, strata, flags, next, name vftable
|
||||
slot — the layout shifted between 1.12 and 3.3.5 (same way unit
|
||||
field offsets did, per the `OFF_UNIT_FIELD_HEALTH` discovery in
|
||||
CLAUDE.md).
|
||||
- AddTooltipLine engine address (1.12 has it — every
|
||||
`GameTooltip:SetX` method calls it internally).
|
||||
- Lua-side reference lookup helper (whatever 1.12 uses to map
|
||||
frame → Lua table; the `FrameScript_GetObject` chain at
|
||||
`0x6F3740` is part of this).
|
||||
|
||||
### Recommendation
|
||||
|
||||
The Lua-side iterator switch is done. The C++ port stays deferred
|
||||
unless we need the engine frame list for something else
|
||||
(`GetMouseFocus` polyfill, anonymous-frame inspector with extra
|
||||
fields beyond what Lua exposes, single-tooltip strict polyfill,
|
||||
etc.) that would amortize the RE cost.
|
||||
A mirror of 4.3.4's CGTooltip::SetFrameStack in
|
||||
[src/tooltip/FrameStack.cpp](src/tooltip/FrameStack.cpp), plus the
|
||||
`OnTooltipSetFrameStack` script in Tooltip::SetEvents. Every input exists in
|
||||
1.12: the CSimpleTop frame list, the NDC cursor + NDCToDDC, CLayoutFrame
|
||||
GetRect, the frame's visible / enabled-input / strata / level fields,
|
||||
FrameStrataToString and the two default tooltip colors (all in Offsets.h).
|
||||
The `/fstack` UI itself is addon Lua and can now call the method.
|
||||
|
||||
## ~~47. `IsPlayerSpell(spellID)`~~ — DONE
|
||||
|
||||
@@ -1120,51 +1047,50 @@ spell-API functions use. Returns `(1, nil)` / `(nil, 1)` /
|
||||
`(nil, nil)` per legacy convention. `C_Spell.IsSpellUsable` is the
|
||||
modern shape — same logic, returns proper booleans.
|
||||
|
||||
**Two engine-cache approaches investigated and discarded:**
|
||||
**Reworked for issue #51 (2026-09-12) — it now IS the engine's
|
||||
verdict.** `IsUsableAction` reads the per-slot cache
|
||||
(`0x00BC6B60` usable / `0x00BC67A0` noMana, reader `FUN_004E5230`),
|
||||
which the recompute `FUN_004E5050` fills per slot. For a player spell
|
||||
slot that recompute is one call: `FUN_SPELL_IS_USABLE(record,
|
||||
&noMana)` (`0x006E3D60`). For a pet spell slot it is `FUN_PET_ACTIONS_
|
||||
USABLE()` then the pet's power vs `FUN_GET_SPELL_COST(spellID, 0)`.
|
||||
`Spell::Usable` now runs exactly those two paths live (plus a
|
||||
knowledge gate on `VAR_PLAYER_SPELL_BITMAP`, since the helper is also
|
||||
fed item on-use spells and never checks knowledge). Verified check
|
||||
list of the helper is on `FUN_SPELL_IS_USABLE` in `Offsets.h`.
|
||||
|
||||
**The first version hand-rolled five checks instead** (known, alive,
|
||||
off cooldown, power, reagents) and diverged from `IsUsableAction`
|
||||
exactly where the helper does more or less — the issue #51 repro
|
||||
(Warrior, Whirlwind):
|
||||
|
||||
| State | `IsUsableAction` | old `IsUsableSpell` |
|
||||
|---|---|---|
|
||||
| Berserker, 0 rage, on CD | `nil, 1` | `nil, nil` (we tested cooldown first — the engine never does) |
|
||||
| Battle Stance, 25 rage | `nil, nil` | `1, nil` (we never tested stance) |
|
||||
|
||||
Cooldown is deliberately NOT part of usability: FrameXML greys
|
||||
(`IsUsableAction`) and swipes (`GetActionCooldown`) as two separate
|
||||
states, and the engine helper has no cooldown branch. Rule #1 case:
|
||||
`Item::Usable` had been calling the helper all along.
|
||||
|
||||
**Two engine-cache approaches investigated and discarded before the
|
||||
first version** (still true, kept for the record):
|
||||
|
||||
1. **Per-spell cache at `0x004F0F40` returning fields at +0x564
|
||||
/ +0x568** — initially looked promising (the action-bar
|
||||
dispatcher at `0x004E5BA0` reads these), but the writers
|
||||
(`0x004EFF17` cluster) showed they're parsed config integers,
|
||||
not real-time usability bools. False trail.
|
||||
not real-time usability bools. False trail. (Later identified as
|
||||
the macro entry's cached primary spell — see the `#showtooltip`
|
||||
notes.)
|
||||
2. **Action-bar per-slot caches at `0x00BC67A0` (noMana) and
|
||||
`0x00BC6B60` (usable)** — these ARE real-time, but only updated
|
||||
for the 120 action-bar slots. Spells off the bar stay
|
||||
uninitialized. Action-bar-only is the wrong abstraction since
|
||||
modern `IsUsableSpell(spellID)` is action-bar-agnostic.
|
||||
|
||||
Settled on a **manual five-check approach**:
|
||||
1. Player knows the spell (`VAR_PLAYER_SPELL_BITMAP` lookup —
|
||||
covers profession recipes, talents, racials, etc.).
|
||||
2. Player is alive (`HEALTH > 0`).
|
||||
3. Spell is not on cooldown (`FUN_SPELL_QUERY_COOLDOWN` —
|
||||
the engine helper `Script_GetSpellCooldown` calls internally
|
||||
after slot resolution, queried with `bookType=0` for player).
|
||||
4. Player has ≥ `ManaCost` of the spell's `PowerType` —
|
||||
only this failure flips `noMana=true`.
|
||||
5. Player has all required reagents in bags
|
||||
(`Spell.dbc` Reagent[8] / ReagentCount[8] at `+0x110` /
|
||||
`+0x130`, walked via `Item::Location::ResolveBag`).
|
||||
|
||||
**Not checked** (deliberate, different concerns): silence, GCD,
|
||||
stance/form, range, target type, line-of-sight, casting state.
|
||||
|
||||
**Verified on Turtle WoW:**
|
||||
- Mana check: Renew rank 3 (cost 105) reports usable at 144 mana
|
||||
and unusable at 39 mana, transitioning exactly at the cost
|
||||
boundary.
|
||||
- Reagent check: SHIPPED BUT UNVERIFIED — the Reagent[8] /
|
||||
ReagentCount[8] offsets at `+0x110` / `+0x130` are the
|
||||
CMaNGOS-documented vanilla layout, and we know spell records
|
||||
match CMaNGOS docs (PowerType=+0x7C and ManaCost=+0x80 both
|
||||
match), so high confidence — but no in-game verification yet.
|
||||
Should test with a reagent spell (e.g., Mage Teleport spell 3565
|
||||
needs Rune of Teleportation 17031). Failure mode if offsets are
|
||||
wrong: reagent check becomes a no-op (always passes).
|
||||
- Cooldown check: SHIPPED BUT UNVERIFIED in this implementation —
|
||||
the helper signature was traced via `Script_GetSpellCooldown` at
|
||||
`0x004B40A0` but not exercised in-game. Should test with a
|
||||
cooldown'd spell.
|
||||
modern `IsUsableSpell(spellID)` is action-bar-agnostic. The fix
|
||||
above sidesteps this by calling what FILLS the cache, not the
|
||||
cache.
|
||||
|
||||
**Important offset correction along the way.** Initial implementation
|
||||
read POWER1 at descriptor `+0x5C` based on the CMaNGOS-documented
|
||||
@@ -1741,7 +1667,14 @@ is a thin wrapper. If they're inlined, we'd either need to skip
|
||||
the clear ourselves (call after some no-op state setup) or
|
||||
manually call the line-emission primitives.
|
||||
|
||||
## ~~61. `GameTooltip:GetItem()` / `GetSpell()` / `GetUnit()`~~ — `GetItem` + `GetSpell` DONE; `GetUnit` skipped
|
||||
## ~~61. `GameTooltip:GetItem()` / `GetSpell()` / `GetUnit()`~~ — DONE
|
||||
|
||||
`GetUnit` shipped later in [src/unit/Tooltip.cpp](src/unit/Tooltip.cpp):
|
||||
`SetUnit` is re-registered in front of the engine's (no MinHook) to
|
||||
stage the token, and the token binds in the unit-builder co-hook that
|
||||
`Tooltip::SetEvents` already owned. The builder has three callers:
|
||||
SetUnit, the world-mouseover setter (→ `"mouseover"`), and an in-place
|
||||
refresh (keeps the token). The notes below are the original skip.
|
||||
|
||||
Modern query methods that return what the tooltip is currently
|
||||
showing:
|
||||
@@ -1847,10 +1780,17 @@ are supported.
|
||||
|
||||
### Unhookable globals
|
||||
|
||||
Modern WoW rejects `hooksecurefunc("<core lua/secure fn>", ...)` outright
|
||||
to keep callers from clobbering language primitives or breaking taint
|
||||
propagation. We mirror that with a name blacklist in `Script_HookSecureFunc`
|
||||
that fires `lua_error` with `"hooksecurefunc: function is unhookable"`
|
||||
Patch 11.0.0 (The War Within, 2024-07-23) made `hooksecurefunc` refuse a
|
||||
fixed set of names with a "Cannot hook function" error, to keep callers
|
||||
from clobbering language primitives or breaking taint propagation. No
|
||||
earlier client has the restriction (3.3.5, 4.3.4 and 5.4.8 carry no such
|
||||
string), so 11.0's published list is the reference — and it is NOT the
|
||||
engine's base-library table (`0x00811E28`, 36 entries, catalogued in
|
||||
`BlizzardScriptAPI.md` §3): 11.0 leaves `tostring`/`error`/`loadstring`
|
||||
hookable and includes secure-family names that are not base functions. We
|
||||
mirror the 11.0 list verbatim with a name blacklist in
|
||||
`Script_HookSecureFunc` that fires `lua_error` with
|
||||
`"hooksecurefunc: function is unhookable"`
|
||||
when the two-arg form targets one of: `getfenv`, `getmetatable`,
|
||||
`hooksecurefunc`, `ipairs`, `issecurevalue`, `issecurevariable`, `next`,
|
||||
`pairs`, `pcall`, `pcallwithenv`, `rawget`, `rawset`, `scrub`,
|
||||
@@ -3827,9 +3767,10 @@ private namespace table **only** when BOTH hold, else `nil`:
|
||||
boolean flag; approach (a) from the notes below — no parser hook).
|
||||
|
||||
The two paths stay separate, as required:
|
||||
- **Internal** `__addonns` (the `local name, ns = ...` preamble) stays
|
||||
**ungated** — an addon always gets its own namespace. Still in
|
||||
`luasyntax/Transpile.cpp`.
|
||||
- **Internal**: each addon file is called with `(name, ns)` as real
|
||||
arguments, as 4.3.4 does (`Script_RunAddonFile` in
|
||||
`luasyntax/Transpile.cpp`) — **ungated**, an addon always gets its own
|
||||
namespace. (Replaced the `__addonns` global preamble.)
|
||||
- **Public** `C_AddOns.GetAddOnLocalTable` carries the gate, in
|
||||
`addons/LocalTable.cpp`.
|
||||
|
||||
@@ -3854,3 +3795,337 @@ Not shipped by default: no addon opts in yet. The embedded `!!!ClassicAPI`
|
||||
addon could add `## AllowAddOnTableAccess: 1` to its `.toc` to expose its own
|
||||
namespace as a worked example, but that's a product/security decision left to
|
||||
the maintainer.
|
||||
|
||||
## 100. Self-documenting API + `/classicapi` browser — SHIPPED (first slice)
|
||||
|
||||
`docs/API.md` is 18.7k lines and its anchors are signature slugs, so a
|
||||
signature edit breaks the 281 internal + 88 README links into it. Blizzard
|
||||
solved the same problem by shipping the API as DATA
|
||||
(`Blizzard_APIDocumentationGenerated`: one table per system with typed
|
||||
`Functions` / `Events` / `Tables`) plus a browser addon
|
||||
(`Blizzard_APIDocumentation`, the `/api` command). warcraft.wiki.gg's
|
||||
Arguments/Returns blocks are those same tables rendered by a bot — so one set
|
||||
of descriptors feeds the in-game browser, a page generator, and a drift check.
|
||||
|
||||
**Shipped in this round**
|
||||
|
||||
- `namespace Game::Doc` in [src/Game.h](src/Game.h) — `Field` +
|
||||
`Req`/`Opt`/`Vararg`, `FieldList`, `Function`, `Method`, `Structure`,
|
||||
`Event`. Constant-initialized `const` objects; no heap, no dynamic init.
|
||||
- A trailing descriptor argument on all six `Game::Lua::Register*`, and on
|
||||
`Event::Custom::AutoReserve`. Zero changes inside any `Script_*`.
|
||||
- [src/api/Documentation.cpp](src/api/Documentation.cpp) — records every
|
||||
registration on the first pass of each Lua state, derives systems, and
|
||||
exports `C_APIDocumentation.GetSystems()` / `GetSystem(name)` lazily in
|
||||
Blizzard's exact table shape, plus `_classicapi_UndocumentedAPI()`.
|
||||
- `AddOns/!!!ClassicAPI/APIDocumentation/` — the 8-file port of
|
||||
`Blizzard_APIDocumentation`, driven by `/classicapi` (short `/capi`).
|
||||
Named for what it documents: the browser holds only ClassicAPI's own
|
||||
surface, so `/api` would have over-promised.
|
||||
- `Util/LinkUtil.lua` — the `SetItemRef` → `LinkUtil.ProcessLink` dispatch,
|
||||
wiring up a `RegisterLinkHandler` registry that had been dead code. Any
|
||||
future link type now registers a handler instead of stacking another
|
||||
`SetItemRef` override. Also fixed `assertsafe` being undefined there.
|
||||
- Documented: the whole `C_Spell` / `C_SpellBook` surface, the spell globals
|
||||
(`SpellGlobals`), the two SpellBook enums, the 13 `UNIT_SPELLCAST_*`
|
||||
events, `GameTooltipAPI` (frame-method example), and `C_Glue` (glue and
|
||||
mixed-environment example).
|
||||
|
||||
**The remaining sweep.** `_classicapi_UndocumentedAPI()` is the worklist —
|
||||
~700 registrations across ~46 namespaces. Do it a namespace at a time; the
|
||||
descriptor goes beside the registration and must be written against the
|
||||
`Script_*` BODY, not against `docs/API.md` (which is already stale in
|
||||
places — `IsHarmfulSpell` / `IsHelpfulSpell` describe an `AttributesEx` bit
|
||||
read that the code does not do; it walks the effects' implicit targets).
|
||||
`tools/New-ApiDocSkeletons.ps1` emits paste-ready skeletons from the 207
|
||||
single-line `Usage:` strings + the API.md headings, with `// TODO` on every
|
||||
guess — a starting point to verify, never to paste blind.
|
||||
|
||||
When the sweep finishes, delete the `= nullptr` / `= 0` defaults from the six
|
||||
registrar parameters: a registration without a descriptor then fails to
|
||||
compile, which is the whole point of putting the descriptor at the call site.
|
||||
|
||||
**Then, not before:** an `ExportAPIDocumentation` console command (glue-
|
||||
registered like `ExportInterfaceFiles`, writing one Blizzard-format `.lua`
|
||||
per system plus `Undocumented.txt`), a CI diff of the committed copies to
|
||||
catch descriptor drift, and a Markdown/wiki generator to replace the
|
||||
hand-maintained `docs/API.md` — the reason the descriptors exist at all.
|
||||
|
||||
## 101. `Frame:SetOnUpdateMode(mode)` + `Enum.OnUpdateMode` — medium
|
||||
|
||||
```
|
||||
Frame:SetOnUpdateMode(onUpdateMode) -- Enum.OnUpdateMode
|
||||
0 Disabled no OnUpdate, visible or not
|
||||
1 RunWhenVisible the vanilla behaviour (default)
|
||||
2 RunWhenVisibleOnce run once while visible; resets to Disabled BEFORE running
|
||||
3 RunOnce run once regardless of visibility; resets to Disabled BEFORE running
|
||||
4 RunAlways run regardless of visibility
|
||||
```
|
||||
|
||||
"Resets before running" is load-bearing: the handler re-arms by calling
|
||||
`SetOnUpdateMode` again from inside itself.
|
||||
|
||||
**Engine (verified 2026-09-15).** The per-frame dispatcher is `FUN_0076B2C0`,
|
||||
`__thiscall(frame, float elapsed)` at vtable `+0x38`, present in every frame
|
||||
vtable with subclass overrides chaining into it (same shape as the click
|
||||
vmethod `FUN_00779540`):
|
||||
|
||||
```c
|
||||
if (frame[0x128] != 0) // the OnUpdate slot
|
||||
FUN_007026F0(frame, frame + 0x128, "%f", elapsed); // fmt @0x00835160
|
||||
```
|
||||
|
||||
The walk is `FUN_00765650`: nine strata buckets of an intrusive list
|
||||
(`frame+0x310` = next, saved into the bucket before each call so a handler may
|
||||
unlink itself), calling `vtable+0x38` per node — with **no visibility check in
|
||||
the loop and none in the dispatcher**. Visibility is therefore *list
|
||||
membership*, not a test, and that list is the per-strata render list, so a
|
||||
hidden frame is simply absent. Contention: a literal scan of every DLL in
|
||||
`dll\` + `dll_local\` finds no reference to `FUN_0076B2C0` or `FUN_00765650`.
|
||||
|
||||
**Design.** Modes 0/1/2 need only a co-hook on `FUN_0076B2C0` — mode 0 returns
|
||||
without calling the original, mode 2 sets Disabled then calls it, mode 1 is the
|
||||
engine unchanged. Guard the detour on an empty mode map so non-users pay a
|
||||
compare.
|
||||
|
||||
Modes 3/4 cannot come from that hook: the frame is not in the walk's list while
|
||||
hidden, and forcing membership would put it in the RENDER list (it would try to
|
||||
draw). Drive them from `Tick::WorldTick` instead — an already-owned hook, so no
|
||||
second MinHook — calling the engine's own `FUN_0076B2C0(frame, elapsed)` so the
|
||||
handler sees exactly the fire it normally would, with a per-tick mark set by the
|
||||
hook so a *visible* `RunAlways` frame is not dispatched twice.
|
||||
|
||||
**Open question before writing it:** the `elapsed` for the self-driven modes.
|
||||
The walk receives it from its caller; cleanest is to capture it in the hook (one
|
||||
value per pass, shared by every frame) and reuse it, falling back to a
|
||||
`Time::Clock` delta when nothing visible ran that frame. Needs checking whether
|
||||
`Tick::WorldTick` (`FUN_0066FD50`, the world subsystem) runs before or after the
|
||||
UI pass, which decides whether the captured value is this frame's or last
|
||||
frame's.
|
||||
|
||||
**Cost:** one new MinHook (uncontended, guarded to ~zero when unused), one
|
||||
WorldTick subscriber, a frame-keyed mode map, `Enum.OnUpdateMode`, and
|
||||
`SetOnUpdateMode` / `GetOnUpdateMode`.
|
||||
|
||||
**Value, honestly.** `RunAlways` is the only genuinely new capability — a hidden
|
||||
frame currently cannot run OnUpdate at all, which is why addons keep a
|
||||
permanently-shown dummy frame for their tickers. `Disabled` duplicates
|
||||
`SetScript("OnUpdate", nil)` and `RunOnce` overlaps `C_Timer.After(0, …)`, so
|
||||
the rest is API parity. Worth it for the one capability plus a clean enum, not
|
||||
as a performance feature.
|
||||
|
||||
## 102. Texture tiling: `SetHorizTile` / `SetVertTile` (+ `SetNonBlocking`) — medium
|
||||
|
||||
The only texture methods 4.3.4 has that 1.12 + ClassicAPI lack
|
||||
(`wowdecomp15595/Engine/Source/Frame/CSimpleTexture_Scripts.cpp`): six
|
||||
setter/getter pairs on `m_textureFlags`. Getters answer 1 or nil.
|
||||
|
||||
| Methods | 4.3.4 flag | Effect |
|
||||
|---|---|---|
|
||||
| `SetHorizTile` / `GetHorizTile` | `0x4` | repeat on U |
|
||||
| `SetVertTile` / `GetVertTile` | `0x8` | repeat on V |
|
||||
| `SetNonBlocking` / `GetNonBlocking` | `0x1` | skip drawing an unloaded image this frame instead of force-loading it |
|
||||
|
||||
**How 4.3.4 tiles.** `CRenderBatch::QueueTexture` (`CRenderBatch.cpp:164`):
|
||||
while the dirty flag `0x2` is set, every non-zero U texcoord becomes
|
||||
`rectWidthInPixels / gxTex->m_width` (V likewise with height), using
|
||||
`DDCToNDCWidth(aspect × 1024 × (right − left)) / m_layoutScale` from the drawn
|
||||
corners. A layout change (`CSimpleRender.cpp:2391`) sets `0x2` again when either
|
||||
tile flag is on. Repeat only shows if the image was loaded with wrap.
|
||||
|
||||
**Wrap on 1.12.** `CSimpleTexture::SetTexture` `0x770200` already takes
|
||||
`(name, wrap, filter, shader)` (benilla-re `ui/texture#settexture`); the Lua
|
||||
`SetTexture` always passes wrap 0. 4.3.4's Lua `SetTexture(file, tile)` reads
|
||||
arg 3 as wrap for both axes — add that. To verify: vanilla has one wrap flag,
|
||||
4.3.4 has `wrapU`/`wrapV`; check whether `CGxTexFlags` `0x58A980` can wrap one
|
||||
axis alone.
|
||||
|
||||
**Where to hook.** The rescale belongs where the drawn corners are built — the
|
||||
texture `OnFrameSizeChanged` co-hook `0x770670` the animation system already
|
||||
owns (`src/animation/Region.cpp`).
|
||||
|
||||
**XML.** `<Texture horizTile= vertTile= nonBlocking=>`; 4.3.4's loader also
|
||||
turns wrap on when `<TexCoords>` leave 0..1 and errors
|
||||
`Texture %s: Invalid TexCoords value (horizTile is on)` (`CSimpleRender.cpp:3024`).
|
||||
|
||||
**NonBlocking.** Only meaningful if 1.12 has a lazy texture-load path (4.3.4:
|
||||
`TextureForceLoadForDiskOnly` vs `NotifyDelayedLoad`). Not checked — if 1.12
|
||||
always loads synchronously it is a stored flag with no effect.
|
||||
|
||||
## ~~103. FontString `SetWordWrap` / `CanWordWrap` / `GetFieldSize`~~ — DONE
|
||||
|
||||
The only FontString methods 4.3.4 has that 1.12 + ClassicAPI lacked
|
||||
(`CSimpleFontString_Scripts.cpp`). Code: `src/fontstring/WordWrap.cpp`,
|
||||
`GetFieldSize` in `src/fontstring/Metrics.cpp`.
|
||||
|
||||
- **SetWordWrap / CanWordWrap.** 4.3.4 style bit `0x40` (set = no wrap). The
|
||||
setter is 1.12's own `SetNonSpaceWrap` (`0x79E9F0`, identical body on bit
|
||||
`0x1000`) with `0x40` inverted. `TextBlockCreate` `0x44D420` already maps
|
||||
`0x40` to text flag `0x2` exactly as 4.3.4's `ConvertStringFlags`, and 1.12's
|
||||
layout `0x5CDC20` / line count `0x5C2070` stop after one line on it.
|
||||
Verified in-game: one line, `...` at the width (the fit `0x771EC0`), lines
|
||||
after `\n` dropped, no width = the whole line. A change must lay the string
|
||||
out again (`FontString::Layout::Invalidate`, as `SetText`), not only rebuild
|
||||
it: a text-sized string kept its two-line height and the fit cut at a whole
|
||||
word with no `...`.
|
||||
- **GetFieldSize.** 4.3.4 returns a constant 8191. 1.12's truth: a string with a
|
||||
fixed text size `+0xE8` (XML `bytes="n"`) keeps `n − 1` bytes (`SetText`'s
|
||||
`SStrCopy(text, src, n)`, `0x771E0F`); without one the buffer grows to any
|
||||
length, so it returns infinity.
|
||||
|
||||
## ~~104. XML `<KeyValues>`~~ — DONE
|
||||
|
||||
Shipped in a2e3eed (`mixin=` and `method=` followed in 2cab0dc). Code:
|
||||
`src/xml/KeyValues.cpp`; the texture / font string hooks in
|
||||
`src/xml/ParentKey.cpp` call it directly (no `RegionLoad` fan-out), and
|
||||
`src/animation/Xml.cpp` reads it for groups and animations. Notes below
|
||||
are the original plan.
|
||||
|
||||
Not in 4.3.4 (no decomp); the contract comes from retail's `UI.xsd`
|
||||
(`_classic_era_/BlizzardInterfaceCode/.../Blizzard_SharedXML/UI.xsd`) and
|
||||
`XMLUtilDocumentation.lua`. Blizzard's classic-era UI uses it in 356 files.
|
||||
|
||||
- `<KeyValues><KeyValue key= value= type= keyType=/></KeyValues>`; `type` and
|
||||
`keyType` are `nil` / `boolean` / `number` / `string` (default) / `global`
|
||||
(`_G[value]`). Sets `object[key] = value` on the Lua wrapper.
|
||||
- A LayoutField: frames, textures, font strings. Also a child of
|
||||
`AnimationGroup` and `Animation`.
|
||||
- `C_XMLUtil.GetTemplateInfo(name).keyValues` is a list of
|
||||
`{key, keyType, type, value}` (all strings); ours always returns `{}`
|
||||
(`src/xml/Templates.cpp`).
|
||||
|
||||
**Ordering.** `NineSlicePanelMixin:OnLoad` reads `self:GetParent().layoutType`
|
||||
— a parent's KeyValue must be set before its child frames load. 1.12's frame
|
||||
load (benilla-re `ui/frames#loading-from-xml`): `0x769820` loads the inherited
|
||||
node first, then attributes, `Layers`, `Scripts`; `0x76A060` then loads the
|
||||
child `<Frames>` and the load ends (OnLoad). So the existing
|
||||
`Xml::FrameLoad::AutoSubscribe` (after `0x769820`, as `<Attributes>` uses) is
|
||||
the right point: template values first, the node's own win, before children
|
||||
and OnLoad.
|
||||
|
||||
**Plan.**
|
||||
1. Textures / font strings: `ParentKey.cpp` owns the `0x76FE20` / `0x770F40`
|
||||
loader hooks and calls `Animation::Xml::LoadAnimations` from them by hand.
|
||||
Turn them into a shared `Xml::RegionLoad::AutoSubscribe` fan-out (like
|
||||
`FrameLoad`) and subscribe ParentKey, Animations and KeyValues.
|
||||
2. `Xml::PushTypedValue(L, type, value)` shared with `<Attributes>`
|
||||
(`Frame::Attributes::LoadXmlAttributes`, engine `FUN_XML_ATTR_TO_BOOL` /
|
||||
`FUN_SSTR_TO_FLOAT`), plus `global`.
|
||||
3. `src/xml/KeyValues.cpp` for frames + regions; the animation loader
|
||||
(`src/animation/Xml.cpp`) reads it for groups and animations.
|
||||
4. Fill `GetTemplateInfo`'s `keyValues` from the template node.
|
||||
|
||||
**Unverifiable without a retail binary** — follow `<Attributes>` and say so in
|
||||
the code: a `boolean` value other than true/false, a `number` that fails to
|
||||
parse, and whether `GetTemplateInfo` includes inherited templates' entries
|
||||
(plan: the node's own only).
|
||||
|
||||
## 105. Button methods — small to medium
|
||||
|
||||
Button methods later clients have that 1.12 + ClassicAPI lack. 4.3.4 adds three
|
||||
over 1.12 (`CSimpleButton_Scripts.cpp`); retail's `SimpleButtonAPIDocumentation`
|
||||
(`_classic_era_` install) lists the rest. `Get/SetNormalFontObject` are done
|
||||
(`src/frame/Modern.cpp`).
|
||||
|
||||
**From 4.3.4 (decomp available).**
|
||||
- **DONE** (`src/frame/MotionScriptsWhileDisabled.cpp`, verified in-game
|
||||
2026-10-19). `SetMotionScriptsWhileDisabled(enabled)` / `GetMotionScriptsWhileDisabled()`
|
||||
— the one real new capability: tooltips on disabled buttons. 4.3.4
|
||||
`CSimpleButton::OnLayerCursorEnter/Exit` (`CSimpleButton.cpp:827/844`): an
|
||||
enabled button runs the frame's enter/leave and the label refresh; a disabled
|
||||
one does nothing unless the flag is set, then shows `m_hoverFrame` and runs
|
||||
ONLY the OnEnter/OnLeave script (no highlight, no label refresh). 1.12 is
|
||||
4.3.4 without the flag: `0x779490` (slot 19) / `0x7794E0` (slot 20) skip the
|
||||
frame's enter/leave (`0x76B6A0` / `0x76B6F0`, scripts + highlight) and the
|
||||
label refresh `0x779810` for state 0 (benilla-re `ui/button#entering-and-leaving`).
|
||||
Needs: a per-button flag (side map, reset on reload), co-hooks on the two
|
||||
slots, a way to run just the script (find the script runner inside
|
||||
`0x76B6A0`), what 1.12 has for `m_hoverFrame`, and the XML attribute
|
||||
`motionScriptsWhileDisabled` (4.3.4 `m_buttonFlags` bits 0x4 set / 0x8 value,
|
||||
`CSimpleButton.cpp:1058`). Default false.
|
||||
- **DONE** (`src/frame/FormattedText.cpp`, shared with the font string's;
|
||||
verified in-game 2026-10-19).
|
||||
`button:SetFormattedText(fmt, ...)` — 4.3.4 formats into a 4096-byte buffer
|
||||
and calls the button's `SetText`. We have it on font strings only
|
||||
(`src/fontstring/Metrics.cpp`, engine `str_format` under pcall); register the
|
||||
same on the Button registry with the button's own SetText.
|
||||
|
||||
**From later clients (contract from retail docs only — no decomp).**
|
||||
- **DONE** (`src/frame/SetEnabled.cpp`). `SetEnabled(enabled)` — `Enable()` /
|
||||
`Disable()` by a bool, through the button's Enable vmethod as they do.
|
||||
- `SetNormalAtlas` / `SetPushedAtlas` / `SetDisabledAtlas` /
|
||||
`SetHighlightAtlas(atlas[, blendMode])` — the state texture made or reused
|
||||
through `SetNormalTexture` etc., then `Texture::Atlas`'s `SetAtlas`.
|
||||
- `ClearNormalTexture` / `ClearPushedTexture` / `ClearDisabledTexture` /
|
||||
`ClearHighlightTexture` — remove the state texture. Check what 1.12's
|
||||
`SetNormalTexture(nil)` does first (`CSimpleButton::SetStateTexture`
|
||||
`0x778FD0` deletes the old one).
|
||||
- **DONE** (`src/frame/MouseRegistration.cpp`). `RegisterForMouse(buttons...)`
|
||||
— which mouse buttons fire OnMouseDown/Up. 1.12 filters nothing: the base
|
||||
frame pair 0x76BF70 / 0x76C040 fire both for any button through the runner,
|
||||
where `Frame::ClickEvents`' gate now refuses unregistered ones.
|
||||
|
||||
## 106. Script-object API sweep — remaining methods, globals and scripts
|
||||
|
||||
A name-level diff, 2026-10-19: every 4.3.4 method table
|
||||
(`wowdecomp15595/Engine/Source/Frame/*_Scripts.cpp`) and retail's
|
||||
`Blizzard_APIDocumentationGenerated/Simple*APIDocumentation.lua` (`_classic_era_`
|
||||
install) against 1.12 (`docs/BlizzardScriptAPI.md`) and what `src/` registers.
|
||||
Texture (#102), FontString (#103 done) and Button (#105) have their own items.
|
||||
Each entry still needs the usual check of how the engine does it before building.
|
||||
|
||||
### From 4.3.4 (decomp available)
|
||||
|
||||
- **DONE** (`src/slider/Enable.cpp`). **Slider** `Enable` / `Disable` / `IsEnabled`: frame flag `0x400`, read by the
|
||||
thumb-drag path (`CSimpleSlider.cpp:317`); `Disable` runs OnDisable unless
|
||||
loading (we have OnEnable/OnDisable in `src/frame/EnableScripts.cpp`).
|
||||
- **DONE** (`src/frame/MinMaxChanged.cpp`). **OnMinMaxChanged** (Slider, StatusBar): `SetMinMaxValues` runs it with
|
||||
`(min, max)` when the range changes (`CSimpleStatusBar.cpp:39/141`). 1.12 has
|
||||
no such script.
|
||||
- **DONE** (`src/statusbar/Fill.cpp`, `src/statusbar/BarTexture.cpp`; XML
|
||||
`reverseFill` / `rotatesTexture` / `fillStyle` attributes not backported).
|
||||
**StatusBar** `SetReverseFill` / `GetReverseFill`, `SetRotatesTexture` /
|
||||
`GetRotatesTexture` (`CSimpleStatusBar.cpp:135`, the vertical texcoord path
|
||||
at `:285`). Retail adds `SetFillStyle` (STANDARD / CENTER / REVERSE),
|
||||
`SetColorFill`, `SetStatusBarDesaturated` / `Desaturation`.
|
||||
- **ScrollingMessageFrame** `SetInsertMode` / `GetInsertMode`,
|
||||
`GetMessageInfo`, `RemoveMessagesByAccessID`, `RemoveMessagesByExtraData`,
|
||||
`SetScrollOffset` — in C in 4.3.4 (retail moved the type to Lua).
|
||||
- **DONE** (`src/editbox/Focus.cpp`, `src/animation/Framerate.cpp`).
|
||||
**Globals** (`SimpleFrameScript_Scripts.cpp`): `GetCurrentKeyBoardFocus()`
|
||||
(the focused edit box's wrapper, or nil); `SetMaxAnimFramerate(fps)` /
|
||||
`GetMaxAnimFramerate()` — 4.3.4's `CSimpleAnim::s_frameInterval`, the 1/30 s
|
||||
throttle our animation port already has.
|
||||
- Not worth it: Frame `EnableJoystick` / `IsJoystickEnabled`; the stereo-depth
|
||||
set `SetDepth` / `GetDepth` / `GetEffectiveDepth` / `IgnoreDepth` /
|
||||
`IsIgnoringDepth`; `GetText(token[, gender[, ordinal]])` — gendered
|
||||
global-string lookup, little use on 1.12.
|
||||
|
||||
### From later clients (retail docs only — contract, no decomp)
|
||||
|
||||
Likely worth it (small, ported code uses them):
|
||||
- Object: `GetParentKey` / `SetParentKey` / `ClearParentKey`, `GetDebugName`.
|
||||
- Region: `SetIgnoreParentAlpha` / `IsIgnoringParentAlpha` (4.3.4 has it
|
||||
internally: its texture XML load calls `SetIgnoreParentAlpha` from
|
||||
`m_regionFlags 0x10/0x20`, `CSimpleRender.cpp`),
|
||||
`SetIgnoreParentScale` / `IsIgnoringParentScale`.
|
||||
- ScriptRegion: `GetScaledRect`, `IsRectValid`, `Intersects`.
|
||||
- Frame: `GetResizeBounds` (we have `SetResizeBounds`), `SetFixedFrameStrata` /
|
||||
`SetFixedFrameLevel` / `HasFixed*`, `GetHighestFrameLevel` /
|
||||
`GetRaisedFrameLevel`, `SetUsingParentLevel`, `ClearAttributes`,
|
||||
`IsObjectLoaded`, `RotateTextures` (on `Texture::Transform`), `AbortDrag`.
|
||||
- Slider: `SetObeyStepOnDrag`, `SetStepsPerPage`, `IsDraggingThumb`,
|
||||
`SetEnabled` (also EditBox `SetEnabled`).
|
||||
- FontString / Font: `SetTextScale` /
|
||||
`GetTextScale`, `ClearText`, `SetTextToFit`,
|
||||
`GetUnboundedStringWidthForText`, `FindCharacterIndexAtCoordinate`.
|
||||
- Texture: `GetTextureFilePath`, `ClearVertexOffsets`.
|
||||
- SimpleHTML `GetContentHeight`; ColorSelect alpha (`SetColorAlpha` + its
|
||||
textures).
|
||||
|
||||
Larger, decide separately: mouse-motion / click split and propagation
|
||||
(`SetMouseMotionEnabled`, `SetMouseClickEnabled`, `SetPropagateMouseClicks`,
|
||||
`SetPassThroughButtons`); `SetClipsChildren` (scissoring); `CreateLine` (the
|
||||
Line region type); texture slicing (`SetTextureSliceMargins` / `Mode`); Model
|
||||
camera / transform / alpha (~40 methods); `RegisterEventCallback`; EditBox
|
||||
secure-text and byte-limit options; MessageFrame fade power and message IDs.
|
||||
|
||||
@@ -1,138 +0,0 @@
|
||||
# embed_addon.cmake — bundle an addon directory into a generated C++ header.
|
||||
#
|
||||
# Invoked from CMakeLists.txt via `cmake -P` as a custom command. Reads every
|
||||
# file under SRC_DIR recursively and emits OUT_HEADER containing:
|
||||
#
|
||||
# namespace Addons::Embedded {
|
||||
# struct File {
|
||||
# const char *path;
|
||||
# const unsigned char *data;
|
||||
# size_t size;
|
||||
# };
|
||||
# extern const File kFiles[];
|
||||
# extern const size_t kFileCount;
|
||||
# }
|
||||
#
|
||||
# Paths are normalized to lowercase backslash-form relative to
|
||||
# `Interface\AddOns\` so they match what the engine's TOC parser
|
||||
# constructs when it asks for the addon's files (see
|
||||
# `s_Interface_AddOns__s__s_toc_00853840` in the binary). The
|
||||
# manifest is hash-table-friendly for fast lookup but the lookup
|
||||
# walks the array linearly — fine for 25 files.
|
||||
#
|
||||
# Usage:
|
||||
# cmake -DSRC_DIR=... -DOUT_HEADER=... -DADDON_NAME=... -P embed_addon.cmake
|
||||
|
||||
if(NOT SRC_DIR)
|
||||
message(FATAL_ERROR "embed_addon.cmake: SRC_DIR required")
|
||||
endif()
|
||||
if(NOT OUT_HEADER)
|
||||
message(FATAL_ERROR "embed_addon.cmake: OUT_HEADER required")
|
||||
endif()
|
||||
if(NOT ADDON_NAME)
|
||||
message(FATAL_ERROR "embed_addon.cmake: ADDON_NAME required")
|
||||
endif()
|
||||
|
||||
file(GLOB_RECURSE INPUT_FILES RELATIVE "${SRC_DIR}" "${SRC_DIR}/*")
|
||||
# Never embed the developer marker — it must reflect on-disk presence
|
||||
# only (see src/addons/Embedded.cpp DiskHasDevMarker), and it is
|
||||
# gitignored so it only exists in a developer working tree anyway.
|
||||
list(FILTER INPUT_FILES EXCLUDE REGEX "(^|/)\\.classicapi-dev$")
|
||||
list(SORT INPUT_FILES) # deterministic codegen
|
||||
|
||||
set(BODY "")
|
||||
set(MANIFEST "")
|
||||
set(INDEX 0)
|
||||
foreach(REL_PATH ${INPUT_FILES})
|
||||
set(ABS_PATH "${SRC_DIR}/${REL_PATH}")
|
||||
|
||||
# Stamp the addon's `## Version:` line from the build flag rather
|
||||
# than the committed source (which stays `DEV`). This is what makes
|
||||
# a release build a pure function of `-DCLASSICAPI_TAG` — the source
|
||||
# toc is never edited. Only the `.toc` file is rewritten, in-memory,
|
||||
# before hex-encoding; every other file is embedded verbatim.
|
||||
if(ADDON_VERSION AND REL_PATH MATCHES "\\.toc$")
|
||||
file(READ "${ABS_PATH}" TOC_TEXT)
|
||||
string(REGEX REPLACE "## Version:[^\n\r]*"
|
||||
"## Version: ${ADDON_VERSION}" TOC_TEXT "${TOC_TEXT}")
|
||||
# Round-trip through a temp file to hex-encode the modified text
|
||||
# (portable to CMake 3.10; avoids requiring string(HEX), 3.18+).
|
||||
set(TOC_TMP "${OUT_HEADER}.toc.tmp")
|
||||
file(WRITE "${TOC_TMP}" "${TOC_TEXT}")
|
||||
file(READ "${TOC_TMP}" CONTENT_HEX HEX)
|
||||
file(REMOVE "${TOC_TMP}")
|
||||
else()
|
||||
file(READ "${ABS_PATH}" CONTENT_HEX HEX)
|
||||
endif()
|
||||
|
||||
string(LENGTH "${CONTENT_HEX}" HEX_LEN)
|
||||
math(EXPR FILE_SIZE "${HEX_LEN} / 2")
|
||||
|
||||
# Convert hex string to comma-separated byte literals. 16 bytes per line
|
||||
# keeps the generated header readable.
|
||||
set(BYTES "")
|
||||
set(COL 0)
|
||||
set(POS 0)
|
||||
while(POS LESS HEX_LEN)
|
||||
string(SUBSTRING "${CONTENT_HEX}" ${POS} 2 BYTE)
|
||||
if(COL EQUAL 0)
|
||||
string(APPEND BYTES " ")
|
||||
endif()
|
||||
string(APPEND BYTES "0x${BYTE},")
|
||||
math(EXPR POS "${POS} + 2")
|
||||
math(EXPR COL "${COL} + 1")
|
||||
if(COL EQUAL 16)
|
||||
string(APPEND BYTES "\n")
|
||||
set(COL 0)
|
||||
else()
|
||||
string(APPEND BYTES " ")
|
||||
endif()
|
||||
endwhile()
|
||||
if(NOT COL EQUAL 0)
|
||||
string(APPEND BYTES "\n")
|
||||
endif()
|
||||
|
||||
# Normalize path to engine-style: `<AddonName>\Sub\Path.lua` with
|
||||
# backslashes. Engine constructs full path as
|
||||
# `Interface\AddOns\<AddonName>\<file>` — we strip the
|
||||
# `Interface\AddOns\<AddonName>\` prefix at lookup time so storing
|
||||
# just the relative form keeps the manifest small.
|
||||
string(REPLACE "/" "\\\\" REL_PATH_BS "${REL_PATH}")
|
||||
|
||||
string(APPEND BODY "static const unsigned char kData_${INDEX}[] = {\n${BYTES}};\n\n")
|
||||
string(APPEND MANIFEST " { \"${REL_PATH_BS}\", kData_${INDEX}, ${FILE_SIZE} },\n")
|
||||
|
||||
math(EXPR INDEX "${INDEX} + 1")
|
||||
endforeach()
|
||||
|
||||
set(HEADER_CONTENT "// Auto-generated by embed_addon.cmake — do not edit.
|
||||
// Source: ${SRC_DIR}
|
||||
//
|
||||
// Addon \"${ADDON_NAME}\" embedded as a fallback for users who don't have
|
||||
// it installed on disk. See src/addons/Embedded.cpp for the file-read
|
||||
// hook that surfaces these buffers to the engine.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
|
||||
namespace Addons::Embedded {
|
||||
|
||||
namespace ${ADDON_NAME}Files {
|
||||
|
||||
${BODY}static const struct File {
|
||||
const char *path;
|
||||
const unsigned char *data;
|
||||
size_t size;
|
||||
} kFiles[] = {
|
||||
${MANIFEST}};
|
||||
|
||||
static constexpr size_t kFileCount = sizeof(kFiles) / sizeof(kFiles[0]);
|
||||
|
||||
} // namespace ${ADDON_NAME}Files
|
||||
|
||||
} // namespace Addons::Embedded
|
||||
")
|
||||
|
||||
file(WRITE "${OUT_HEADER}" "${HEADER_CONTENT}")
|
||||
message(STATUS "embed_addon: wrote ${OUT_HEADER} (${INDEX} files)")
|
||||
@@ -1,62 +0,0 @@
|
||||
# embed_file.cmake — bundle a single file into a generated C++ header.
|
||||
#
|
||||
# Invoked from CMakeLists.txt via `cmake -P` as a custom command. Reads
|
||||
# INPUT_FILE and emits OUT_HEADER containing a constexpr byte array
|
||||
# named SYMBOL plus a `SYMBOL ## Size` size constant. Both live at file
|
||||
# scope; the header is meant to be included exactly once.
|
||||
#
|
||||
# Usage:
|
||||
# cmake -DINPUT_FILE=... -DOUT_HEADER=... -DSYMBOL=... -P embed_file.cmake
|
||||
|
||||
if(NOT INPUT_FILE)
|
||||
message(FATAL_ERROR "embed_file.cmake: INPUT_FILE required")
|
||||
endif()
|
||||
if(NOT OUT_HEADER)
|
||||
message(FATAL_ERROR "embed_file.cmake: OUT_HEADER required")
|
||||
endif()
|
||||
if(NOT SYMBOL)
|
||||
message(FATAL_ERROR "embed_file.cmake: SYMBOL required")
|
||||
endif()
|
||||
|
||||
file(READ "${INPUT_FILE}" CONTENT_HEX HEX)
|
||||
string(LENGTH "${CONTENT_HEX}" HEX_LEN)
|
||||
math(EXPR FILE_SIZE "${HEX_LEN} / 2")
|
||||
|
||||
# Convert hex string to comma-separated byte literals. 16 bytes per
|
||||
# line keeps the generated header readable.
|
||||
set(BYTES "")
|
||||
set(COL 0)
|
||||
set(POS 0)
|
||||
while(POS LESS HEX_LEN)
|
||||
string(SUBSTRING "${CONTENT_HEX}" ${POS} 2 BYTE)
|
||||
if(COL EQUAL 0)
|
||||
string(APPEND BYTES " ")
|
||||
endif()
|
||||
string(APPEND BYTES "0x${BYTE},")
|
||||
math(EXPR POS "${POS} + 2")
|
||||
math(EXPR COL "${COL} + 1")
|
||||
if(COL EQUAL 16)
|
||||
string(APPEND BYTES "\n")
|
||||
set(COL 0)
|
||||
else()
|
||||
string(APPEND BYTES " ")
|
||||
endif()
|
||||
endwhile()
|
||||
if(NOT COL EQUAL 0)
|
||||
string(APPEND BYTES "\n")
|
||||
endif()
|
||||
|
||||
set(HEADER_CONTENT "// Auto-generated by embed_file.cmake — do not edit.
|
||||
// Source: ${INPUT_FILE}
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
|
||||
static constexpr unsigned char ${SYMBOL}[] = {
|
||||
${BYTES}};
|
||||
static constexpr size_t ${SYMBOL}Size = sizeof(${SYMBOL});
|
||||
")
|
||||
|
||||
file(WRITE "${OUT_HEADER}" "${HEADER_CONTENT}")
|
||||
message(STATUS "embed_file: wrote ${OUT_HEADER} (${FILE_SIZE} bytes)")
|
||||
@@ -0,0 +1,111 @@
|
||||
# embed_resources.cmake — embed the addon and the bindings XML as Win32
|
||||
# RCDATA resources.
|
||||
#
|
||||
# Runs at configure time. It writes two files into OUT_DIR:
|
||||
#
|
||||
# embedded.rc one `<id> RCDATA "<path>"` line per file; rc.exe
|
||||
# reads each file straight from disk.
|
||||
# embedded_resources.h the IDs the DLL looks up at runtime through
|
||||
# src/embed/Resource.h:
|
||||
#
|
||||
# namespace Embed::Ids { constexpr int kBindingsXml = ...; }
|
||||
# namespace Addons::Embedded::ClassicAPIFiles {
|
||||
# struct File { const char *path; int resourceId; };
|
||||
# constexpr File kFiles[] = { ... };
|
||||
# constexpr size_t kFileCount = ...;
|
||||
# }
|
||||
#
|
||||
# Addon paths are relative to the addon folder, in backslash form
|
||||
# (`Util\Print.lua`) — the suffix the engine builds after
|
||||
# `Interface\AddOns\!!!ClassicAPI\`. The DLL compares them ignoring case.
|
||||
#
|
||||
# The `.toc` is the one file that is not embedded verbatim: its
|
||||
# `## Version:` line is stamped with ADDON_VERSION into a copy under
|
||||
# OUT_DIR, so a release build is a pure function of `-DCLASSICAPI_TAG` and
|
||||
# the source toc stays `DEV`.
|
||||
#
|
||||
# Rebuild triggers: adding or removing a file reconfigures through the
|
||||
# caller's CONFIGURE_DEPENDS glob; editing the toc reconfigures through
|
||||
# CMAKE_CONFIGURE_DEPENDS; editing any other file recompiles the .rc
|
||||
# through its OBJECT_DEPENDS.
|
||||
#
|
||||
# Usage:
|
||||
# embed_resources(TARGET <t> ADDON_DIR <dir> ADDON_FILES <rel paths...>
|
||||
# ADDON_VERSION <v> BINDINGS_XML <file> OUT_DIR <dir>)
|
||||
|
||||
# Write `content` to `path` only when it differs, so an unchanged
|
||||
# reconfigure does not touch the file and trigger a rebuild.
|
||||
function(_embed_write_if_changed path content)
|
||||
set(tmp "${path}.tmp")
|
||||
file(WRITE "${tmp}" "${content}")
|
||||
configure_file("${tmp}" "${path}" COPYONLY)
|
||||
file(REMOVE "${tmp}")
|
||||
endfunction()
|
||||
|
||||
function(embed_resources)
|
||||
cmake_parse_arguments(E "" "TARGET;ADDON_DIR;ADDON_VERSION;BINDINGS_XML;OUT_DIR"
|
||||
"ADDON_FILES" ${ARGN})
|
||||
|
||||
set(rc "// Generated by cmake/embed_resources.cmake - do not edit.\n\n")
|
||||
set(manifest "")
|
||||
set(inputs "")
|
||||
set(id 1)
|
||||
|
||||
string(APPEND rc "${id} RCDATA \"${E_BINDINGS_XML}\"\n")
|
||||
list(APPEND inputs "${E_BINDINGS_XML}")
|
||||
set(bindings_id ${id})
|
||||
math(EXPR id "${id} + 1")
|
||||
|
||||
set(files ${E_ADDON_FILES})
|
||||
list(SORT files) # deterministic IDs
|
||||
foreach(rel ${files})
|
||||
set(abs "${E_ADDON_DIR}/${rel}")
|
||||
if(rel MATCHES "\\.toc$")
|
||||
file(READ "${abs}" toc)
|
||||
string(REGEX REPLACE "## Version:[^\n\r]*"
|
||||
"## Version: ${E_ADDON_VERSION}" toc "${toc}")
|
||||
set(stamped "${E_OUT_DIR}/embed/${rel}")
|
||||
_embed_write_if_changed("${stamped}" "${toc}")
|
||||
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${abs}")
|
||||
set(abs "${stamped}")
|
||||
endif()
|
||||
string(APPEND rc "${id} RCDATA \"${abs}\"\n")
|
||||
list(APPEND inputs "${abs}")
|
||||
string(REPLACE "/" "\\\\" rel_bs "${rel}")
|
||||
string(APPEND manifest " { \"${rel_bs}\", ${id} },\n")
|
||||
math(EXPR id "${id} + 1")
|
||||
endforeach()
|
||||
|
||||
_embed_write_if_changed("${E_OUT_DIR}/embedded.rc" "${rc}")
|
||||
_embed_write_if_changed("${E_OUT_DIR}/embedded_resources.h"
|
||||
"// Generated by cmake/embed_resources.cmake — do not edit.
|
||||
// Resource IDs for the RCDATA entries in embedded.rc. Load them through
|
||||
// src/embed/Resource.h.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
|
||||
namespace Embed::Ids {
|
||||
constexpr int kBindingsXml = ${bindings_id};
|
||||
} // namespace Embed::Ids
|
||||
|
||||
namespace Addons::Embedded::ClassicAPIFiles {
|
||||
|
||||
struct File {
|
||||
const char *path;
|
||||
int resourceId;
|
||||
};
|
||||
|
||||
constexpr File kFiles[] = {
|
||||
${manifest}};
|
||||
|
||||
constexpr size_t kFileCount = sizeof(kFiles) / sizeof(kFiles[0]);
|
||||
|
||||
} // namespace Addons::Embedded::ClassicAPIFiles
|
||||
")
|
||||
|
||||
target_sources(${E_TARGET} PRIVATE "${E_OUT_DIR}/embedded.rc")
|
||||
set_source_files_properties("${E_OUT_DIR}/embedded.rc" PROPERTIES
|
||||
OBJECT_DEPENDS "${inputs}")
|
||||
endfunction()
|
||||
+5056
-1395
File diff suppressed because it is too large
Load Diff
@@ -9,7 +9,8 @@ ImageBase `0x00400000`. All VAs in this doc use that base.
|
||||
|
||||
## How Blizzard wires Lua
|
||||
|
||||
There are two registries.
|
||||
There are two Blizzard registries, plus the Lua standard libraries, which are
|
||||
bound a third way (§3) and are NOT in the batch counts below.
|
||||
|
||||
### 1. Global functions — `FrameScript_RegisterFunction` at `0x00704120`
|
||||
|
||||
@@ -57,6 +58,62 @@ C3 ret
|
||||
23 tables found, **481 methods total**. The runtime dispatcher at `0x005368D0`
|
||||
resolves `frame:method(...)` by looking the name up in the matching context.
|
||||
|
||||
### 3. Lua standard libraries — `luaL_openlib` tables
|
||||
|
||||
The Lua 5.0 standard libraries, and Blizzard's replacements inside them, are
|
||||
bound by `luaL_openlib` walking one `luaL_reg { char *name; lua_CFunction
|
||||
func; }[]` table per library when the Lua state is created (`FUN_00703B80`,
|
||||
called immediately BEFORE `FUN_LOAD_SCRIPT_FUNCTIONS`). They never pass
|
||||
through `FrameScript_RegisterFunction`, so none of them appear in the 54
|
||||
batches above or in the loop scan behind `raw_globals.txt` — which is how
|
||||
`debugprofilestart` / `debugprofilestop` (stock since 1.7.0) went
|
||||
uncatalogued here until 2026-09. **Before declaring a global absent, check
|
||||
these tables or `/dump` the name in game.**
|
||||
|
||||
**Base library** — table `[0x00811E28]`, 36 entries, `.rdata`. Blizzard's
|
||||
own base library: the stock 5.0 set minus `dofile`/`loadfile`/`require`/
|
||||
`print` (`print` is a ClassicAPI backport), plus the `debug*` /
|
||||
`*errorhandler` / `date` / `time` additions.
|
||||
|
||||
```
|
||||
0x00702770 setglobal 0x00702DF0 type
|
||||
0x007027B0 getglobal 0x00702E30 tonumber
|
||||
0x007027E0 debugload 0x00702F40 tostring
|
||||
0x007027F0 debuginfo 0x007030A0 unpack
|
||||
0x00702800 debugprint 0x007030F0 rawequal
|
||||
0x00702810 debugdump 0x00703130 rawget
|
||||
0x00702820 debugbreak 0x00703160 rawset
|
||||
0x00702830 debugtimestamp 0x007031A0 assert
|
||||
0x00702840 debugprofilestart 0x00703200 gcinfo
|
||||
0x00702860 debugprofilestop 0x00703250 collectgarbage
|
||||
0x00702900 seterrorhandler 0x00703280 loadstring
|
||||
0x00702950 geterrorhandler 0x007032F0 pcall
|
||||
0x00702970 error 0x00703340 xpcall
|
||||
0x007029F0 getmetatable 0x007033A0 date
|
||||
0x00702A40 setmetatable 0x007035A0 time
|
||||
0x00702AC0 getfenv 0x00703760 debugstack
|
||||
0x00702BE0 setfenv
|
||||
0x00702C90 next
|
||||
0x00702CD0 ipairs
|
||||
0x00702DA0 pairs
|
||||
```
|
||||
|
||||
`debugprofilestart` stores `rdtsc` in `0x00CEEB58` (u64);
|
||||
`debugprofilestop` pushes `|rdtsc − start| / (ticksPerSecond / 1000)` as a
|
||||
double, where `ticksPerSecond` is `FUN_0042C020` = `(int64)(1000.0 /
|
||||
[0x008332C8])` — a TSC scale calibrated at boot (the image holds `1.0`). So:
|
||||
milliseconds with a sub-microsecond fraction, from the CPU counter, unrelated
|
||||
to the engine's millisecond tick and to `GetTime()`.
|
||||
|
||||
The `table`, `string` and `math` libraries have the same shape (the `table`
|
||||
library's `luaL_reg` is at `0x00822D70` — see `Offsets.h`
|
||||
`FUN_LUA_TABLE_INSERT`) and are not enumerated here. The short global
|
||||
aliases (`tinsert`, `getn`, `strlen`, `format`, `floor`, …) are not registered
|
||||
at all: an embedded Lua chunk at `.data 0x008722E8`, run by the same state
|
||||
init, assigns them from the library tables (`tinsert = tab.insert`). A module
|
||||
that registers over a library function must therefore re-bind its alias —
|
||||
`Game::Lua::RegisterGlobalAlias`.
|
||||
|
||||
## Scope
|
||||
|
||||
The 54 global-function batches split into two phases:
|
||||
|
||||
+161
-112
@@ -69,30 +69,35 @@ The DLL hooks the engine's own text pipeline — no companion addon:
|
||||
earlier `0xFF` alpha force at emit was a misdiagnosis of a bubble that built
|
||||
while faded out; it froze icon-line text fully opaque while everything
|
||||
around it faded.
|
||||
- **Outlined fonts** — outline ink extends past the glyph advances; the
|
||||
engine itself grows line height by exactly 4.0 / 2.0 pen px for thick / thin
|
||||
outline (`face+0x180` bits 3 / 0, `.rdata` constants). `OutlineInkPen` reads
|
||||
the same flags and constants, and half the ink leads each icon, half trails
|
||||
— threaded through the shared advance helper so the emitter advance, the
|
||||
justify pre-shift, and the wrap-stepper probes all agree. Without it, coins
|
||||
clipped into outlined digits the moment the exact K removed the old
|
||||
miscalibration's accidental slack (`968335d`).
|
||||
- **Size, spacing and alignment are 4.3.4's rules** (decompiled source in
|
||||
`C:\Git\wowdecomp15595`; 3.3.5 has the same). See "Icon geometry" below.
|
||||
Every hand-tuned constant this module once carried (a 0.18 × font lead/trail
|
||||
pad, a 0.6 × font vertical centre, a −1px region nudge, a size multiplier)
|
||||
is gone.
|
||||
- **Measure** — three cold FontString-level co-hooks make measure match the
|
||||
drawn result: width (`FUN_00772890`), height (`FUN_007729B0`), and wrap
|
||||
(`FUN_005C7260`). `GetStringWidth`, `fontstring:GetStringHeight`, wrap
|
||||
breaks, and line height all count the icon.
|
||||
- **Tall icons** — an icon taller than the font grows its line height, so it
|
||||
does not overlap its neighbors, and it centers in the grown line. A hyperlink
|
||||
- **Tall icons** — a line holding an icon taller than the font moves itself
|
||||
and the lines after it down by the overflow, as 4.3.4 does, so it does not
|
||||
overlap its neighbors; the icon aligns by the line's vertical justification
|
||||
(below). A hyperlink
|
||||
that contains a tall icon is hoverable across the whole icon
|
||||
(`49934b0`, `b9d0705`).
|
||||
- **Chat fade** — icons fade in lockstep with their chat line (`3ca3b7e`).
|
||||
- **Editboxes** — an editbox keeps the raw markup, so the caret stays aligned
|
||||
(two complementary signals, below).
|
||||
- **Edit boxes** — render the icons in their text, as 4.3.4 does; the caret,
|
||||
the mouse and the arrow keys treat an icon as one character, and Ctrl+C
|
||||
drops icons (4.3.4's 0x1500 strip mask). Typed markup stays literal by the
|
||||
engine's own input escape (below).
|
||||
- **Payload** — the full
|
||||
`|Tpath:height:width:offsetX:offsetY:texW:texH:left:right:top:bottom:r:g:b|t`:
|
||||
size, pen offset, sprite-sheet crop, and vertex tint. BLP and uncompressed
|
||||
TGA.
|
||||
- **Anti-spoof** — chat strips player-injected `|T` icons.
|
||||
- **Anti-spoof** — chat neutralizes a player-injected `|T` the way the edit
|
||||
box neutralizes a typed one (the `|` is doubled).
|
||||
- **Raid markers** — `{rt1}`/`{skull}`/… become icons in the CHAT_MSG text and,
|
||||
separately, in the speech bubble after its escape strip (4.3.4's
|
||||
`CGChatBubbleFrame::ParseRaidIcons`).
|
||||
|
||||
Every fs-level measure path now counts icons: width (`FUN_00772890`), height
|
||||
(`FUN_007729B0`), wrap (`FUN_005C7260`), and the substring measure
|
||||
@@ -171,7 +176,7 @@ SetTexture `+0x104`). Selector map (shared across GL/D3D backends): 7=blend,
|
||||
0x10=depthtest, 0x14=cullface, 0x17-0x1e=texture bind (8 units),
|
||||
0x1f-0x26=colorop/alphaop preset (unit 0-7).
|
||||
|
||||
## SOLVED — positioning, measure/wrap, editbox exclusion, texcoords
|
||||
## SOLVED — positioning, measure/wrap, edit boxes, texcoords
|
||||
|
||||
The primitive draws at arbitrary coords; the rest is knowing WHERE and WHEN.
|
||||
Everything is in [src/text/InlineTexture.cpp](../src/text/InlineTexture.cpp);
|
||||
@@ -196,8 +201,7 @@ frame → renderNode [frame+0x118] → group [renderNode+0x18]
|
||||
- The **emitter** `FUN_005ccbe0(line, text, len, colorState, penXYZ, pageMask,
|
||||
linkState)` builds one wrapped line's glyph quads. `this` (the "line"/node the
|
||||
icon list keys on) owns batches `[+0xa0+page*4]` and origin `[+0x70]`. **Note
|
||||
the render node the emitter sees has NO back-pointer up to the frame** — the
|
||||
editbox discriminator had to be found another way (see below).
|
||||
the render node the emitter sees has NO back-pointer up to the frame.**
|
||||
|
||||
### Positioning — segmented delegation (co-hook the emitter)
|
||||
|
||||
@@ -224,14 +228,27 @@ We do NOT reimplement the emitter's intricate glyph vertex math. Instead, in the
|
||||
does NOT reset it between left-justified lines, so leaving it mutated
|
||||
cascade-shifts every following line).
|
||||
|
||||
### FontString pipe-doubling — the escape arrives as `||T…||t`
|
||||
### The span rule — `|T…|t` only, `||` is always a literal pipe
|
||||
|
||||
The FontString text sanitizer **doubles any pipe that doesn't begin a recognized
|
||||
escape** so it renders as a literal `|`. 1.12 doesn't know `|T`, so a caller's
|
||||
`|Tpath:h|t` reaches the emitter as `||Tpath:h||t` (verified: emitter text length
|
||||
+2, pipes doubled). The detector therefore matches BOTH the doubled form (the
|
||||
real-world case) and a clean `|T` (should one ever arrive undoubled). Normal
|
||||
doubled pipes (`|| `) never match because the next char must be `T`.
|
||||
One scanner, `IconSpanAt`, decides what a span is, with 4.3.4's
|
||||
`GxuDetermineQuotedCode` CODE_TEXTURESTART rule: after `|T` (or `|A`), the
|
||||
FIRST `|` must be followed by `t` (`a`), and an empty `|T|t` is literal.
|
||||
Anything else is not a span and draws as text. Every walker steps over `||`
|
||||
as a pair, because `||` is the escaped pipe in both engines.
|
||||
|
||||
That is what keeps typed markup literal everywhere — chat display, edit
|
||||
boxes, macros: the edit box stores a typed `|` as `||` (`0x77c254`; Paste
|
||||
goes through the same `InsertChar`, as in 4.3.4), so a typed `|Tpath|t` is
|
||||
`||Tpath||t` in every buffer it reaches.
|
||||
|
||||
(An earlier version matched a "doubled" `||T…||t` form too, on the belief
|
||||
that the FontString sanitizer doubled unknown escapes. Stock 1.12 has no
|
||||
such sanitizer — not SetText `0x771d80`, its grammar pass `0x7716f0`,
|
||||
FitText `0x771ec0`, nor the edit box's RebuildLabel `0x77d4d0`. The `||T`
|
||||
seen in chat lines was typed text, and our own `{rt1}` expansion emitted it
|
||||
on purpose to survive the bubble's escape strip. Matching it turned every
|
||||
typed `|T` into an icon, which is why the edit box needed the suppression
|
||||
gates the span rule replaced.)
|
||||
|
||||
### bit-3 batch-clear mode
|
||||
|
||||
@@ -258,15 +275,76 @@ per build — on the first wrapped line, detected by `text == [node+0x48]` (the
|
||||
node's text start) — and icons ACCUMULATE across lines. Multiple icons per line
|
||||
fall out of the segmentation loop naturally.
|
||||
|
||||
### Vertical centring — font-relative
|
||||
### Icon geometry — 4.3.4's rules, ported
|
||||
|
||||
`penXYZ[1]` sits near the text TOP, so the icon centre = `penY + fontHeight *
|
||||
g_centerFrac` (0.6, calibrated in-game across chat + pfUI's bubble). Font height
|
||||
comes from the engine's own `FUN_005c6fa0(flag, [node+0x1c])` (the emitter's
|
||||
glyph-sizing call), so centring holds across font sizes without a fixed pixel
|
||||
nudge. A TALL icon (height > font) centres in its GROWN line (see the tall-icon
|
||||
sections in Current design) — the string-height co-hook adds the overflow, so
|
||||
the extra room sits half above and half below the text.
|
||||
**Size** (`ParseEmbeddedTexture`, 0x00617BA0 in 4.3.4). A WRITTEN size is not
|
||||
pixels: it multiplies by `fontPx / (14 × ddcWidthScale)`, the reduction of the
|
||||
engine's `windowPx / (aspectComp × 1024) × fontHeight / NDCToDDCWidth(14 /
|
||||
(aspectComp × 1024))` (the call list of the real apwow.exe function confirms
|
||||
`CoordinateGetAspectCompensation` + `NDCToDDCWidth`). So sizes are relative to
|
||||
a 14-unit font and follow the text's size, UI scale and resolution. 1.12 holds
|
||||
ddcWidthScale in the same Coordinate static (`VAR_COORD_DDC_WIDTH_SCALE`,
|
||||
0x00832A44 — the four statics sit at 0x00832A40 with 4.3.4's exact initial
|
||||
values). On top of that, every size multiplies by the fontstring's layout
|
||||
scale (`fs+0x7C`) — 3.3.5's `CGxString::m_scale`, applied again although the
|
||||
font height already includes it. 4.3.4 dropped this factor; 3.3.5's was kept
|
||||
after a side-by-side look in game. Every wrap gets the same scale, as 4.3.4
|
||||
passes `m_layoutScale` to every `CalcWrapPoint`: the draw builder through the
|
||||
node's owner, and the three fs-level callers (the height getter, the
|
||||
display-text truncation inside the rebuild, the break array) through a
|
||||
fontstring scope their co-hooks set (`WrapLayoutScale`). Size cases: height ≤ 0 → font height; width absent → the height;
|
||||
width > 0 → width × scale, or a RATIO of the height when the height came from
|
||||
the font (`:0:2` is twice as wide); width ≤ 0 → the font height. Offsets are
|
||||
screen pixels and move only the drawn texture (+x right, +y UP), never the
|
||||
layout. `ResolveIconSize` is the one implementation.
|
||||
|
||||
**Spacing** (`InitializeTextLine`, case CODE_TEXTURESTART). An icon starts at
|
||||
the previous glyph's INK edge — bearing + cell width, clamped to ≥ 0 and
|
||||
capped at the glyph's own advance (`FUN_TEXT_GLYPH_BASE_ADVANCE`) — plus
|
||||
the face's outline ink (4 × scale thick / 2 × scale thin, `face+0x180` bits 3 /
|
||||
0; the same constants the 1.12 emitter grows its line by); with no glyph
|
||||
since the line start or the last icon it starts at the pen, no gap. The next
|
||||
glyph starts at `floor(iconRight + 0.5)` with no kerning against the icon.
|
||||
1.12's emitter doesn't report its last glyph's position (its pen is lazy), so
|
||||
`drawRun` replays the run's placements with the emitter's own helpers — the
|
||||
pair advance, the snap rounding (`FADD 0.5; __ftol`), `FUN_TEXT_GLYPH_DESC`
|
||||
(`CGxFont::NewCodeDesc`) and `FUN_TEXT_GLYPH_BEARING` — and floors the cell
|
||||
width in snap mode exactly as the emitter draws the quad. Measures count an
|
||||
icon as its width plus the outline gap when a glyph precedes it
|
||||
(`SumIconAdvances`); the engine measures width alone, but counting the gap
|
||||
keeps measure and render in step for tooltips and right-justified text. The
|
||||
advance cap is ClassicAPI's: every measure counts the preceding glyph by its
|
||||
advance, so an ink edge past the advance (a glyph cell wider than its step —
|
||||
seen on "[" in chat) pushed each following icon and the rest of the line past
|
||||
the measured width, and wrapped chat lines overran the frame edge.
|
||||
|
||||
**Vertical** (same case + `CreateGeometry`). By the node's vertical justify
|
||||
(`OFF_TEXT_NODE_JUSTIFY_V`, node+0x50: 0 top / 1 middle / 2 bottom — the
|
||||
branch of the origin finalize `FUN_005cdf70`): top → the icon's top on the line
|
||||
top; bottom → its bottom on the baseline; middle → centred on the font height
|
||||
below the line top. The baseline is `penXYZ[1]` and the line top is the draw
|
||||
builder's `linkState[1]` (baseline + font height + spacing), 4.3.4's
|
||||
m_baseLineHeight / m_lineHeight.
|
||||
|
||||
**Tall lines** (`CGxString::InitializeText` + `InitializeViewTranslation` +
|
||||
`GxuFontGetWrappedTextHeight`), mirrored step for step:
|
||||
- A line whose tallest icon reaches past the font height moves down by that
|
||||
overflow, and every later line with it: all of it before the line for
|
||||
bottom justify, all after for top, `floor(overflow / 2)` before and after
|
||||
for middle. The emitter co-hook moves the builder's pen y and link band
|
||||
(`penXYZ[1]` = its `local_48`, `linkState[1]/[3]` = its `local_74[0]/[2]`),
|
||||
which the builder lowers per line, so the move carries forward.
|
||||
- The node's summed overflow (`m_extraLineHeight`) joins the text height the
|
||||
origin finalize justifies by: the `FUN_TEXT_NODE_FINALIZE_ORIGIN` co-hook
|
||||
raises the node position y (`+0x24`) by half / all of it for middle /
|
||||
bottom justify for the call, so the engine's own math and rounding produce
|
||||
4.3.4's origin. It also runs on every reposition (`FUN_005ccb10`).
|
||||
- `GetStringHeight` adds the same per-line overflows, summed. The wrap
|
||||
stepper reports each line's overflow during the engine's own height pass,
|
||||
so the lines are the engine's breaks; the sum is kept per fontstring while
|
||||
the engine serves its cached height.
|
||||
A link's hit band grows toward where its icon reaches (below for top, above
|
||||
for bottom, half each way for middle); 4.3.4 keeps the band at the text.
|
||||
|
||||
### Measure / wrap — co-hook the tokenizer
|
||||
|
||||
@@ -308,13 +386,9 @@ the measure core `FUN_0044D670`, then divides the pen-space result by
|
||||
`fs+0x7C`.
|
||||
|
||||
The co-hook lives in `src/text/InlineTexture.cpp`. It calls the original,
|
||||
then adds `SumIconAdvances(text) / K` when two gates pass:
|
||||
|
||||
- `InlineInterceptActive(text)` is true — the **same predicate** the tokenizer
|
||||
hook stands down on, factored into one function so measure and render can
|
||||
never disagree.
|
||||
- The fs is not an editbox: `fs+0x120 & 0x1000` is clear (the fs-level bit
|
||||
`FUN_0044D670` translates into the gxu editbox flag 0x40).
|
||||
then adds the icons' advances (`SumIconAdvances`) whenever the feature is
|
||||
on — the same condition the tokenizer hook intercepts on, so measure and
|
||||
render never disagree.
|
||||
|
||||
The icon sum is computed in TRUE PEN PX — the exact numbers the emitter
|
||||
reserves — and bridged into the getter's return space by the font height
|
||||
@@ -355,8 +429,7 @@ measure `FUN_005C2070`, the chars-that-fit counter `FUN_005C21C0` (ellipsis),
|
||||
and the break-array computer `FUN_005C2430` (behind `FUN_00772B60`).
|
||||
|
||||
The co-hook shrinks the `wrapWidth` argument by a **minimal feasible
|
||||
shrink**, gated on the same `InlineInterceptActive` predicate plus the flags
|
||||
editbox bit 0x40 the dispatcher already carries. The stepper reports each
|
||||
shrink** whenever the feature is on. The stepper reports each
|
||||
probe's measured (icons-at-zero) line width in `outWidth`, which gives a
|
||||
direct feasibility check: the line renders inside the frame iff its icons
|
||||
fit in the shrink plus the spare the break left (`iconSum ≤ s + (probeW −
|
||||
@@ -410,87 +483,65 @@ line through our co-hooked tokenizer (`FUN_005c2810`) and wrap-stepper
|
||||
(`FUN_005c7260`). So the recorded rect rides the same icon-aware position
|
||||
accounting the wrap fix installs; the icon lands inside the hover region for free,
|
||||
and hovering it fires the frame's `OnHyperlinkEnter`. This is a consequence of the
|
||||
wrap fix, not a separate feature. (Ghidra caveat: the decompile of the
|
||||
`FUN_005cd310` call args is mangled — a pointer-as-float + an uninitialized temp —
|
||||
so this is confirmed by the call path plus in-game test, not the byte-level
|
||||
formula.)
|
||||
wrap fix, not a separate feature. (`FUN_005cd310` itself, from benilla
|
||||
font/string "Hyperlink regions", difftested: it multiplies the rect's y fields
|
||||
`+0x08`/`+0x10` by 1/H and its x fields `+0x0c`/`+0x14` by 1/W and appends the
|
||||
32-byte record to the array at `+0x7c`. Ghidra's own decompile of the call
|
||||
args is mangled.)
|
||||
|
||||
**Still icon-blind (accepted residuals):**
|
||||
|
||||
- Sub-pixel only for a string-final icon: the width hooks report its INK edge
|
||||
(advance minus the trail half-pad/ink — `TrailingIconTrimPen`), matching the
|
||||
engine's own last-glyph convention (the gxu width loop ends on ink, not
|
||||
advance — the source of the old −0.8px measurement, whose previous-glyph
|
||||
advance treatment is semantically CORRECT once an icon renders after it).
|
||||
- Sub-pixel only for an icon after a glyph: layout starts it at that glyph's
|
||||
INK edge while measures count the glyph's advance, so the two differ by the
|
||||
glyph's right bearing — the same discrepancy 4.3.4 has between its own
|
||||
layout and measure loops. A string-final icon measures exactly (the gxu
|
||||
width loop ends on the last glyph's ink, which is where the icon starts).
|
||||
What remains is the icon region's ±0.5px placement rounding and the base
|
||||
loop's ~0 contribution for the payload-0 icon token.
|
||||
- An fs whose `fs+0xFC` cache was filled while the feature was toggled
|
||||
differently (`_classicapi_InlineTexEnable`) keeps its old base width until
|
||||
the next `SetText`/font change re-dirties it. Debug-toggle-only.
|
||||
|
||||
**Editbox measure stays raw (by design).** The caret/measure path reads the
|
||||
focused editbox's INPUT buffer in place, and the tokenizer stands down on it
|
||||
per-editbox (`TextInFocusedEditbox` pointer-range test — not a global focus
|
||||
check), so caret math measures the raw `|T…|t` literal the editbox renders.
|
||||
The width hook mirrors that with the `fs+0x120 & 0x1000` editable gate. One
|
||||
marginal wobble: the focused single-line chat editbox's display fontstring
|
||||
carries editable=0 (only multi-line editors set the bit), so the caret
|
||||
positioner's line-boundary branch (multi-line-only in practice) can see an
|
||||
icon-adjusted `FUN_00772890` on it. Closing that costs a per-token content
|
||||
compare, which is not worth it.
|
||||
### Edit boxes — 4.3.4's model, no special case
|
||||
|
||||
### Editbox exclusion — two COMPLEMENTARY signals (bit 6 + focus global)
|
||||
4.3.4's edit box renders `|T…|t` in its text: no frame code ever sets the
|
||||
FontString style bit 0x10000 that `ConvertStringFlags` maps to the gxu
|
||||
texture-off flag 0x1000. Its cursor treats the span as one markup token
|
||||
(`UpdateTextInfo` / `GetNumToLen`), and its `CopyToClipboard` strips with
|
||||
0x1500 — colours, links AND textures. Typed markup never renders because a
|
||||
typed `|` is stored as `||` (`CSimpleEditBox.cpp`, `ch == '|'`). 1.12 does
|
||||
the same input escape, so ClassicAPI's edit boxes need no special case:
|
||||
|
||||
Editable text must show raw, editable `|T…|t` markup, not rendered icons — you
|
||||
edit macros, tweak icon fields, copy/paste texture strings. **This is
|
||||
retail-correct, verified in-game on a modern client:** typing
|
||||
`|TInterface\Icons\INV_Misc_Coin_01:16|t` into the chat entry box OR a macro body
|
||||
shows it **raw** (no icon) — Blizzard neutralizes player-*typed* escape sequences
|
||||
as anti-abuse — while addon/system text (`AddMessage`, `GetCoinTextureString`)
|
||||
renders. Retail's discriminator is the text's SOURCE (trusted vs player-typed),
|
||||
not editbox-vs-display; a shift-clicked item link renders in the chat box because
|
||||
it's inserted through the trusted path, but a typed `|T`/`|c` does not. Our
|
||||
editbox-raw + display-renders split reproduces the same observable outcome. (One
|
||||
mechanism-level divergence we accept: our editbox-raw uses the GLOBAL focus signal
|
||||
below, so while an editbox is focused OTHER display text that rebuilds also
|
||||
briefly shows raw; retail suppresses per-source. Cosmetic, and a per-editbox fix
|
||||
would need hot-path text-buffer matching — not worth it.) 1.12's tokenizer,
|
||||
unlike 4.3.4's, has no per-render texture-disable bit (4.3.4 uses tokenizer flag
|
||||
**0x1000** to kill only `|T`, **0x800** to kill all escapes), and editbox text
|
||||
nodes are NOT distinguishable by class from the render node — the emitter can't
|
||||
reach the owning frame. It takes **two signals together**, not one (an earlier
|
||||
version of this note wrongly called the focus global a redundant "belt-and-
|
||||
suspenders fallback" — removing it renders the chat/copy boxes' `|T` as icons):
|
||||
- **Render** — the label FontString (`RebuildLabel` `0x77d4d0`,
|
||||
`SetText(buffer + scroll, 0)`, no pipe doubling) renders like any other,
|
||||
and its regions parent to the edit box, so a ScrollFrame clips them.
|
||||
- **Cursor** — the class array (`0x77ba90`) tokenizes through our tokenizer
|
||||
hook, so a span is one class-6 letter: Left/Right cross it in one step,
|
||||
Backspace deletes it whole, and an insert can never land inside it.
|
||||
Class 6 is also the safe class — a skip class (0/4) as the last token
|
||||
hangs the step loop (benilla ui/editboxmarkup "Faults"). 4.3.4 joins an
|
||||
icon with the following character into one step; ours is its own step.
|
||||
- **Caret x** — `FUN_0077DA80` measures the line through
|
||||
`FUN_00772AE0`, whose co-hook adds the icons.
|
||||
- **Click → cursor, single-line window** — `GetIndexAtPoint` (`0x77d0d0`),
|
||||
`RebuildLabel` and `MeasureWindow` count characters with
|
||||
`FUN_FONTSTRING_FIT_TEXT` (`0x772bc0` → `0x44d860` → `0x5c6c50`), whose
|
||||
kernel counts an icon as one character of no width. Its co-hook mirrors
|
||||
4.3.4's `GxuFontGetMaxCharsWithinWidth`: the run before each icon is fitted
|
||||
by the original with the budget the earlier icons left, and an icon fits
|
||||
when the icon-aware width through its end does.
|
||||
- **Ctrl+C** — `CopySelection` (`0x77e1d0`) pushes 0x500; patched to 4.3.4's
|
||||
0x1500, and the `GxuStripControlCodes` (`0x5c2590`) co-hook honours 0x1000
|
||||
by dropping spans and stray `|t`. Paste re-escapes every `|`
|
||||
(`InsertChar` per character), as in 4.3.4.
|
||||
|
||||
- **Node flag `[node+0x5c]` bit 6 (0x40) = EDITABLE** — catches the **macro
|
||||
editor** (`MacroFrameText`, flags `0x4D`), which builds its layout once,
|
||||
**un-focused**, so the focus global never sees it. But single-line inputs
|
||||
(chat entry box, `pfChatCopyBox`) have bit 6 **CLEAR** — their nodes are
|
||||
`0x0D`/`0x20D`, identical to display FontStrings — so bit 6 can't catch them.
|
||||
- **Focused-editbox global `DAT_00cf4dc8`** (`InputFocused()`; holds the editbox
|
||||
with keyboard focus, cleared by `ClearFocus` = `FUN_0077e410`) — catches those
|
||||
single-line inputs. It's GLOBAL (true UI-wide, not per-node), which is why,
|
||||
while an editbox is focused, other display text that *rebuilds* also briefly
|
||||
renders raw. That's an accepted tradeoff: there is no per-node signal for
|
||||
single-line inputs, and when you're in an editbox seeing raw markup is what you
|
||||
want anyway.
|
||||
|
||||
**Why the tokenizer's bit-6 gate is load-bearing for RENDER, not just measure:**
|
||||
when the emitter suppresses an editbox it delegates to the ORIGINAL emitter,
|
||||
which **re-enters the tokenizer** to lay out glyphs (`FUN_005ccbe0` →
|
||||
`FUN_005c2810`). On that render path `flags` is the node's own flags, so bit
|
||||
0x40 makes the tokenizer stand down and the `|T` draws as literal text. Drop the
|
||||
bit-6 gate and the (un-focused) macro editor draws **BLANK** — the tokenizer eats
|
||||
the span as a zero-width token and the original emitter renders nothing (verified
|
||||
in-game). Focused single-line inputs get the same "don't intercept" via
|
||||
`Suppressed()` → `InputFocused()`. So both the emitter and the tokenizer consult
|
||||
`Suppressed() || bit-6`; the two must agree or you get blank-vs-raw mismatches.
|
||||
|
||||
(Dead end: **monochrome render flag `DAT_00c2b9dc`** (`FUN_005c8b70` sets it per
|
||||
group) — un-set at MacroFrameText's build time and flickered as a flush gate.
|
||||
Dropped. The editbox class vtable is `0x0081c8c0`, its script-slot resolver
|
||||
`FUN_0077a310` with focus slots at `+0x438`/`+0x440` — useful if a frame-level
|
||||
hook is ever needed.)
|
||||
(History: before the span rule, every typed `|T` reached the emitter as a
|
||||
matching `||T`, so edit boxes were special-cased with three gates — node
|
||||
flag bit 6, a focused-buffer pointer test, and a content compare of the
|
||||
render line against the focused input — plus a re-entry bracket so the
|
||||
delegated raw layout did not draw blank. All removed. Node flag bit 6 is
|
||||
NON-SPACE-WRAP, not "editable"; the gate only worked because the macro
|
||||
editor sets it.)
|
||||
|
||||
### Descriptor fields + the vertical flip
|
||||
|
||||
@@ -544,9 +595,7 @@ backend note.)
|
||||
- **Still icon-blind** (accepted): the hyperlink hit-test past a tall icon
|
||||
OUTSIDE the link on the same line. The substring measure `FUN_00772AE0` was
|
||||
hooked once its real consumer surfaced (the tooltip auto-size measures
|
||||
wrapped SEGMENTS with it), and the trailing-icon width residual is trimmed
|
||||
to sub-pixel (`TrailingIconTrimPen` — a string-final icon reports its ink
|
||||
edge, not its advance, per the engine's own last-glyph convention).
|
||||
wrapped SEGMENTS with it).
|
||||
|
||||
## Goal & spec
|
||||
|
||||
|
||||
@@ -1259,4 +1259,42 @@
|
||||
2: 0x00706040 CreateFont
|
||||
3: 0x007060B0 CreateFrame
|
||||
|
||||
=== luaL_openlib base library Table 0x00811E28 Count=36 (not a FrameScript_RegisterFunction batch; see BlizzardScriptAPI.md §3) ===
|
||||
0: 0x00702770 setglobal
|
||||
1: 0x007027B0 getglobal
|
||||
2: 0x007027E0 debugload
|
||||
3: 0x007027F0 debuginfo
|
||||
4: 0x00702800 debugprint
|
||||
5: 0x00702810 debugdump
|
||||
6: 0x00702820 debugbreak
|
||||
7: 0x00702830 debugtimestamp
|
||||
8: 0x00702840 debugprofilestart
|
||||
9: 0x00702860 debugprofilestop
|
||||
10: 0x00702900 seterrorhandler
|
||||
11: 0x00702950 geterrorhandler
|
||||
12: 0x00702970 error
|
||||
13: 0x007029F0 getmetatable
|
||||
14: 0x00702A40 setmetatable
|
||||
15: 0x00702AC0 getfenv
|
||||
16: 0x00702BE0 setfenv
|
||||
17: 0x00702C90 next
|
||||
18: 0x00702CD0 ipairs
|
||||
19: 0x00702DA0 pairs
|
||||
20: 0x00702DF0 type
|
||||
21: 0x00702E30 tonumber
|
||||
22: 0x00702F40 tostring
|
||||
23: 0x007030A0 unpack
|
||||
24: 0x007030F0 rawequal
|
||||
25: 0x00703130 rawget
|
||||
26: 0x00703160 rawset
|
||||
27: 0x007031A0 assert
|
||||
28: 0x00703200 gcinfo
|
||||
29: 0x00703250 collectgarbage
|
||||
30: 0x00703280 loadstring
|
||||
31: 0x007032F0 pcall
|
||||
32: 0x00703340 xpcall
|
||||
33: 0x007033A0 date
|
||||
34: 0x007035A0 time
|
||||
35: 0x00703760 debugstack
|
||||
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
#include "Common.h"
|
||||
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <windows.h>
|
||||
|
||||
namespace Common {
|
||||
@@ -31,6 +32,38 @@ bool PatchBytes(void *dst, const void *src, size_t len) {
|
||||
return true;
|
||||
}
|
||||
|
||||
bool RedirectCall(uintptr_t site, uintptr_t expected, const void *target) {
|
||||
const auto *code = reinterpret_cast<const uint8_t *>(site);
|
||||
if (code[0] != 0xE8)
|
||||
return false;
|
||||
const auto callee = [site](int32_t rel) { return site + 5 + static_cast<uintptr_t>(rel); };
|
||||
int32_t rel = 0;
|
||||
std::memcpy(&rel, code + 1, sizeof rel);
|
||||
const uintptr_t to = reinterpret_cast<uintptr_t>(target);
|
||||
if (callee(rel) == to)
|
||||
return true;
|
||||
if (callee(rel) != expected)
|
||||
return false;
|
||||
rel = static_cast<int32_t>(to - (site + 5));
|
||||
return PatchBytes(reinterpret_cast<uint8_t *>(site) + 1, &rel, sizeof rel);
|
||||
}
|
||||
|
||||
bool ReplaceWithCall(uintptr_t site, const uint8_t *original, size_t len, const void *target) {
|
||||
uint8_t code[16];
|
||||
if (len < 5 || len > sizeof code)
|
||||
return false;
|
||||
code[0] = 0xE8;
|
||||
const int32_t rel = static_cast<int32_t>(reinterpret_cast<uintptr_t>(target) - (site + 5));
|
||||
std::memcpy(code + 1, &rel, sizeof rel);
|
||||
std::memset(code + 5, 0x90, len - 5);
|
||||
const void *at = reinterpret_cast<const void *>(site);
|
||||
if (std::memcmp(at, code, len) == 0)
|
||||
return true;
|
||||
if (std::memcmp(at, original, len) != 0)
|
||||
return false;
|
||||
return PatchBytes(reinterpret_cast<void *>(site), code, len);
|
||||
}
|
||||
|
||||
void BoundedCopy(char *dst, const char *src, size_t n) {
|
||||
if (dst == nullptr || n == 0)
|
||||
return;
|
||||
@@ -40,4 +73,17 @@ void BoundedCopy(char *dst, const char *src, size_t n) {
|
||||
dst[i] = '\0';
|
||||
}
|
||||
|
||||
void EnsureParentDirs(const char *relPath) {
|
||||
std::string accum;
|
||||
for (const char *p = relPath; *p != '\0'; ++p) {
|
||||
if (*p == '\\' || *p == '/') {
|
||||
if (!accum.empty())
|
||||
CreateDirectoryA(accum.c_str(), nullptr);
|
||||
accum.push_back('\\');
|
||||
} else {
|
||||
accum.push_back(*p);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace Common
|
||||
|
||||
@@ -12,15 +12,33 @@
|
||||
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
namespace Common {
|
||||
|
||||
bool PatchBytes(void *dst, const void *src, size_t len);
|
||||
|
||||
// Points the `E8 rel32` call at `site` to `target` when it still calls
|
||||
// `expected`; true when the call now reaches `target`. A call that reaches
|
||||
// anything else (another DLL's patch, a different build) is left alone.
|
||||
// Idempotent, so it can run on every registration pass.
|
||||
bool RedirectCall(uintptr_t site, uintptr_t expected, const void *target);
|
||||
|
||||
// Writes `call target` plus NOP padding over the `len`-byte (>= 5)
|
||||
// instruction at `site` when it still holds `original`; true when the site
|
||||
// now calls `target`. A site holding anything else (another DLL's patch, a
|
||||
// different build) is left alone. Idempotent, like RedirectCall.
|
||||
bool ReplaceWithCall(uintptr_t site, const uint8_t *original, size_t len, const void *target);
|
||||
|
||||
// Bounded, always-terminated string copy: writes at most `n - 1`
|
||||
// characters plus the terminator, and treats a null `src` as empty. `n`
|
||||
// is the size of `dst`. Stands in for `strncpy`, which MSVC deprecates
|
||||
// (C4996) and which does not terminate on truncation.
|
||||
void BoundedCopy(char *dst, const char *src, size_t n);
|
||||
|
||||
// Creates every parent directory of `relPath` (backslash- or slash-separated,
|
||||
// e.g. "BlizzardInterfaceCode\FrameXML\Foo.lua"), relative to the working
|
||||
// directory. Directories that already exist are a no-op.
|
||||
void EnsureParentDirs(const char *relPath);
|
||||
|
||||
} // namespace Common
|
||||
|
||||
+9
-7
@@ -15,6 +15,7 @@
|
||||
#include "Game.h"
|
||||
#include "MinHook.h"
|
||||
#include "Offsets.h"
|
||||
#include "config/CommandLine.h"
|
||||
#include "config/FileSwitch.h"
|
||||
#include "event/Custom.h"
|
||||
#include "player/NameCache.h"
|
||||
@@ -208,13 +209,14 @@ BOOL APIENTRY DllMain(HMODULE hModule, DWORD reason, LPVOID lpReserved) {
|
||||
if (reason == DLL_PROCESS_ATTACH) {
|
||||
DisableThreadLibraryCalls(hModule);
|
||||
|
||||
// The ONE thing that has to happen this early, and the only module this
|
||||
// file names directly. The engine reads its config file during boot,
|
||||
// several calls before VanillaFixes invokes `Load`, so a `-config`
|
||||
// switch cannot be applied from the normal install path — by then the
|
||||
// file has been read. This is a single 4-byte store, not a hook, so it
|
||||
// carries none of the loader-lock cost described above.
|
||||
Config::FileSwitch::Apply();
|
||||
// The ONE thing that has to happen this early, and the only modules this
|
||||
// file names directly. The engine parses its launch switches and reads
|
||||
// its config file during boot, several calls before VanillaFixes invokes
|
||||
// `Load`, so our switches cannot be wired from the normal install path.
|
||||
// Each is a single rel32 store, not a hook, so it carries none of the
|
||||
// loader-lock cost described above.
|
||||
Config::CommandLine::Install();
|
||||
Config::FileSwitch::Install();
|
||||
|
||||
// Install nothing here (loader lock — see the block comment above).
|
||||
//
|
||||
|
||||
+258
-53
@@ -14,6 +14,7 @@
|
||||
#include "Game.h"
|
||||
#include "MinHook.h"
|
||||
#include "Offsets.h"
|
||||
#include "api/Documentation.h"
|
||||
|
||||
namespace Game {
|
||||
|
||||
@@ -23,6 +24,22 @@ void *ResolveUnitToken(const char *token) {
|
||||
return fn(token);
|
||||
}
|
||||
|
||||
float PixelToInternal(float px) {
|
||||
const float mul = Read<float>(Offsets::VAR_COORD_DDC_WIDTH_SCALE);
|
||||
const float div = Read<float>(Offsets::VAR_COORD_ASPECT_COMPENSATION);
|
||||
if (div == 0.0f)
|
||||
return 0.0f;
|
||||
return px * mul / (div * static_cast<float>(Offsets::UI_COORD_SCALE_UNIT));
|
||||
}
|
||||
|
||||
double InternalToPixel(float internal) {
|
||||
const float mul = Read<float>(Offsets::VAR_COORD_DDC_WIDTH_SCALE);
|
||||
const float div = Read<float>(Offsets::VAR_COORD_ASPECT_COMPENSATION);
|
||||
if (mul == 0.0f)
|
||||
return 0.0;
|
||||
return static_cast<double>(internal) * div * Offsets::UI_COORD_SCALE_UNIT / mul;
|
||||
}
|
||||
|
||||
namespace Lua {
|
||||
// Each entry binds a typed function pointer in `Game::Lua::` to the
|
||||
// corresponding raw VA in `Offsets`. The X-macro keeps the column-aligned
|
||||
@@ -44,8 +61,10 @@ namespace Lua {
|
||||
F(NewTable, lua_newtable, LUA_NEW_TABLE) \
|
||||
F(GetTable, lua_gettable, LUA_GET_TABLE) \
|
||||
F(RawGet, lua_rawget, LUA_RAW_GET) \
|
||||
F(RawGetI, lua_rawgeti, LUA_RAWGETI) \
|
||||
F(SetTable, lua_settable, LUA_SET_TABLE) \
|
||||
F(RawSet, lua_rawset, LUA_RAW_SET) \
|
||||
F(GetMetatable,lua_getmetatable,LUA_GET_METATABLE)\
|
||||
F(SetMetatable,lua_setmetatable,LUA_SET_METATABLE)\
|
||||
F(Insert, lua_insert, LUA_INSERT) \
|
||||
F(Remove, lua_remove, LUA_REMOVE) \
|
||||
@@ -55,6 +74,7 @@ namespace Lua {
|
||||
F(PCall, lua_pcall, LUA_PCALL) \
|
||||
F(Next, lua_next, LUA_NEXT) \
|
||||
F(Type, lua_type, LUA_TYPE) \
|
||||
F(TypeName, lua_typename, LUA_TYPE_NAME) \
|
||||
F(Error, lua_error, LUA_ERROR) \
|
||||
F(ToPointer, lua_topointer, LUA_TO_POINTER) \
|
||||
F(ToThread, lua_tothread, LUA_TO_THREAD) \
|
||||
@@ -99,26 +119,104 @@ void *ResolveObject(void *L, int idx) {
|
||||
return result;
|
||||
}
|
||||
|
||||
void RegisterGlobalFunction(const char *name, CFunction func) {
|
||||
auto fn = reinterpret_cast<FrameScript_RegisterFunction_t>(
|
||||
Offsets::FUN_FRAMESCRIPT_REGISTER_FUNCTION);
|
||||
fn(name, func);
|
||||
int ObjectLuaRef(void *object) {
|
||||
using ScriptRegister_t = void(__thiscall *)(void *object, void *nameOrNull);
|
||||
if (Game::Read<int>(object, Offsets::OFF_COBJECT_LUA_REFCOUNT) == 0)
|
||||
reinterpret_cast<ScriptRegister_t>(
|
||||
Offsets::FUN_FRAMESCRIPT_OBJECT_SCRIPT_REGISTER)(object, nullptr);
|
||||
return Game::Read<int>(object, Offsets::OFF_COBJECT_LUA_REF);
|
||||
}
|
||||
|
||||
// Aliased to the same engine entry; the engine reads VAR_LUA_STATE
|
||||
// internally to decide which state to write to, and the glue hook
|
||||
// runs while that pointer is set to the glue state. Wrapped as a
|
||||
// named function (rather than `using RegisterGlueFunction = ...`) so
|
||||
// callers express intent at the call site.
|
||||
void RegisterGlueFunction(const char *name, CFunction func) {
|
||||
auto fn = reinterpret_cast<FrameScript_RegisterFunction_t>(
|
||||
Offsets::FUN_FRAMESCRIPT_REGISTER_FUNCTION);
|
||||
fn(name, func);
|
||||
void PushObject(void *L, void *object) {
|
||||
RawGetI(L, REGISTRY_INDEX, ObjectLuaRef(object));
|
||||
}
|
||||
|
||||
void RegisterFrameMethods(void *context, const FrameMethodEntry *table, int count) {
|
||||
auto fn = reinterpret_cast<RegisterFrameMethods_t>(Offsets::FUN_REGISTER_FRAME_METHODS);
|
||||
fn(table, count, context);
|
||||
const char *ObjectDisplayName(void *object) {
|
||||
using GetName_t = const char *(__thiscall *)(void *);
|
||||
const void *vtable = Game::Read<const void *>(object, 0);
|
||||
const char *name = Game::Read<GetName_t>(
|
||||
vtable, Offsets::VTBL_SCRIPTOBJECT_GET_NAME)(object);
|
||||
return name != nullptr ? name
|
||||
: reinterpret_cast<const char *>(Offsets::VAR_STR_UNNAMED);
|
||||
}
|
||||
|
||||
namespace {
|
||||
using FrameScriptIsA_t = char(__thiscall *)(void *self, int typeId);
|
||||
|
||||
const char *EngineString(uintptr_t address) {
|
||||
return reinterpret_cast<const char *>(address);
|
||||
}
|
||||
|
||||
// Shared body: the engine's prologue with N accepted type ids.
|
||||
void *ResolveChecked(void *L, int idx, const uintptr_t *typeIdVars, int count,
|
||||
bool raiseError) {
|
||||
if (Type(L, idx) != TYPE_TABLE) {
|
||||
if (raiseError)
|
||||
Error(L, EngineString(Offsets::STR_FS_THIS_NON_TABLE));
|
||||
return nullptr;
|
||||
}
|
||||
void *obj = ResolveObject(L, idx);
|
||||
if (obj == nullptr) {
|
||||
if (raiseError)
|
||||
Error(L, EngineString(Offsets::STR_FS_THIS_NON_OBJECT));
|
||||
return nullptr;
|
||||
}
|
||||
for (int i = 0; i < count; ++i) {
|
||||
if (IsA(obj, typeIdVars[i]))
|
||||
return obj;
|
||||
}
|
||||
if (raiseError)
|
||||
Error(L, EngineString(Offsets::STR_FS_WRONG_OBJECT_TYPE));
|
||||
return nullptr;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int FrameScriptTypeId(uintptr_t typeIdVar) {
|
||||
auto &typeId = Game::Ref<int>(typeIdVar);
|
||||
if (typeId == 0) {
|
||||
auto &counter = Game::Ref<int>(Offsets::VAR_FRAMESCRIPT_TYPE_ID_COUNTER);
|
||||
counter += 1;
|
||||
typeId = counter;
|
||||
}
|
||||
return typeId;
|
||||
}
|
||||
|
||||
bool IsA(void *object, uintptr_t typeIdVar) {
|
||||
auto **vtable = *reinterpret_cast<void ***>(object);
|
||||
auto isA = reinterpret_cast<FrameScriptIsA_t>(
|
||||
vtable[Offsets::OFF_VMT_FRAMESCRIPT_ISA / sizeof(void *)]);
|
||||
return isA(object, FrameScriptTypeId(typeIdVar)) != 0;
|
||||
}
|
||||
|
||||
void *ResolveTypedObject(void *L, int idx, uintptr_t typeIdVar, bool raiseError) {
|
||||
return ResolveChecked(L, idx, &typeIdVar, 1, raiseError);
|
||||
}
|
||||
|
||||
void *ResolveTypedObjectAny(void *L, int idx, const uintptr_t *typeIdVars,
|
||||
int count, bool raiseError) {
|
||||
return ResolveChecked(L, idx, typeIdVars, count, raiseError);
|
||||
}
|
||||
|
||||
void *ResolveTooltip(void *L, int idx, bool raiseError) {
|
||||
return ResolveTypedObject(L, idx, Offsets::VAR_GAMETOOLTIP_LUA_TYPE_ID, raiseError);
|
||||
}
|
||||
void *ResolveFrame(void *L, int idx, bool raiseError) {
|
||||
return ResolveTypedObject(L, idx, Offsets::VAR_FRAME_LUA_TYPE_ID, raiseError);
|
||||
}
|
||||
void *ResolveRegion(void *L, int idx, bool raiseError) {
|
||||
return ResolveTypedObject(L, idx, Offsets::VAR_REGION_LUA_TYPE_ID, raiseError);
|
||||
}
|
||||
void *ResolveTexture(void *L, int idx, bool raiseError) {
|
||||
return ResolveTypedObject(L, idx, Offsets::VAR_TEXTURE_LUA_TYPE_ID, raiseError);
|
||||
}
|
||||
void *ResolveFontString(void *L, int idx, bool raiseError) {
|
||||
return ResolveTypedObject(L, idx, Offsets::VAR_FONTSTRING_LUA_TYPE_ID, raiseError);
|
||||
}
|
||||
void *ResolveEditBox(void *L, int idx, bool raiseError) {
|
||||
return ResolveTypedObject(L, idx, Offsets::VAR_EDITBOX_LUA_TYPE_ID, raiseError);
|
||||
}
|
||||
void *ResolveModel(void *L, int idx, bool raiseError) {
|
||||
return ResolveTypedObject(L, idx, Offsets::VAR_MODEL_LUA_TYPE_ID, raiseError);
|
||||
}
|
||||
|
||||
// Looks up `_G[name]`. If absent, creates a fresh table and binds it.
|
||||
@@ -136,11 +234,110 @@ void EnsureGlobalTable(void *L, const char *name) {
|
||||
Insert(L, -2); // [tbl, name, tbl]
|
||||
SetTable(L, GLOBALS_INDEX); // _G[name] = tbl; pops k+v. [tbl]
|
||||
}
|
||||
|
||||
// Same, one level down: ensures `parent[name]` is a table, with `parent`
|
||||
// on top of the stack. Leaves `[parent, sub]`. Raw access, so a namespace
|
||||
// carrying a metatable can't divert the read or the write.
|
||||
void EnsureSubTable(void *L, const char *name) {
|
||||
PushString(L, name); // [parent, name]
|
||||
RawGet(L, -2); // [parent, parent[name]]
|
||||
if (Type(L, -1) == TYPE_TABLE)
|
||||
return;
|
||||
SetTop(L, -2); // pop the non-table. [parent]
|
||||
NewTable(L); // [parent, sub]
|
||||
PushString(L, name); // [parent, sub, name]
|
||||
PushValue(L, -2); // [parent, sub, name, sub]
|
||||
RawSet(L, -4); // parent[name] = sub. [parent, sub]
|
||||
}
|
||||
|
||||
// The escape-hatch namespace. Registering a name is not the same as owning
|
||||
// it: the engine's registrars write `_G`, FrameXML and every addon load
|
||||
// after that, and whoever writes last wins with no error and no way for the
|
||||
// loser to notice. `GetServerTime` is the case on record — a client whose
|
||||
// GameTime.lua declares its own replaced ours on every login.
|
||||
//
|
||||
// So every name the registrars below bind is also bound under
|
||||
// `_G.ClassicAPI`, which nothing else writes. Two properties earn their
|
||||
// keep, and both depend on doing this HERE rather than from Lua:
|
||||
//
|
||||
// - It runs at registration, so the mirror captures OUR function. A
|
||||
// Lua-side `ClassicAPI.X = X` in the embedded addon would run after
|
||||
// FrameXML and faithfully copy the clobbered version.
|
||||
// - It mirrors by VALUE, reading the name back instead of making a
|
||||
// second closure over the same C function. So `ClassicAPI.X == X`
|
||||
// holds until something replaces the global, and the pair doubles as
|
||||
// a clobber check for addons and for us.
|
||||
//
|
||||
// Not covered: frame methods (`obj:Method()` lives in the per-frame-type
|
||||
// registry, not `_G`) and `RegisterIntegerEnum` values (a mirrored number
|
||||
// is a copy, not a reference).
|
||||
constexpr const char *kMirrorTable = "ClassicAPI";
|
||||
|
||||
void MirrorRegistration(const char *tableName, const char *name) {
|
||||
void *L = State();
|
||||
if (L == nullptr)
|
||||
return;
|
||||
const int top = GetTop(L);
|
||||
|
||||
// Read back whatever the registration actually bound.
|
||||
if (tableName != nullptr) {
|
||||
EnsureGlobalTable(L, tableName); // [src]
|
||||
PushString(L, name); // [src, name]
|
||||
RawGet(L, -2); // [src, value]
|
||||
} else {
|
||||
PushString(L, name); // [name]
|
||||
GetTable(L, GLOBALS_INDEX); // [value]
|
||||
}
|
||||
if (Type(L, -1) != TYPE_FUNCTION) {
|
||||
SetTop(L, top); // registration didn't land; nothing to mirror
|
||||
return;
|
||||
}
|
||||
const int valueIdx = GetTop(L); // absolute, so the pushes below can't skew it
|
||||
|
||||
EnsureGlobalTable(L, kMirrorTable); // [..., mirror]
|
||||
if (tableName != nullptr)
|
||||
EnsureSubTable(L, tableName); // [..., mirror, sub]
|
||||
PushString(L, name);
|
||||
PushValue(L, valueIdx);
|
||||
RawSet(L, -3); // target[name] = value
|
||||
SetTop(L, top);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
void RegisterGlobalFunction(const char *name, CFunction func, const Doc::Function *doc) {
|
||||
auto fn = reinterpret_cast<FrameScript_RegisterFunction_t>(
|
||||
Offsets::FUN_FRAMESCRIPT_REGISTER_FUNCTION);
|
||||
fn(name, func);
|
||||
MirrorRegistration(nullptr, name);
|
||||
Api::Documentation::RecordGlobal(name, doc);
|
||||
}
|
||||
|
||||
// Aliased to the same engine entry; the engine reads VAR_LUA_STATE
|
||||
// internally to decide which state to write to, and the glue hook
|
||||
// runs while that pointer is set to the glue state. Wrapped as a
|
||||
// named function (rather than `using RegisterGlueFunction = ...`) so
|
||||
// callers express intent at the call site.
|
||||
void RegisterGlueFunction(const char *name, CFunction func, const Doc::Function *doc) {
|
||||
auto fn = reinterpret_cast<FrameScript_RegisterFunction_t>(
|
||||
Offsets::FUN_FRAMESCRIPT_REGISTER_FUNCTION);
|
||||
fn(name, func);
|
||||
// `State()` is the glue state here for the same reason the engine
|
||||
// registrar writes there, so the mirror lands on the glue `_G`.
|
||||
MirrorRegistration(nullptr, name);
|
||||
Api::Documentation::RecordGlobal(name, doc);
|
||||
}
|
||||
|
||||
void RegisterFrameMethods(void *context, const FrameMethodEntry *table, int count,
|
||||
const Doc::Method *docs, int docCount) {
|
||||
auto fn = reinterpret_cast<RegisterFrameMethods_t>(Offsets::FUN_REGISTER_FRAME_METHODS);
|
||||
fn(table, count, context);
|
||||
Api::Documentation::RecordFrameMethods(context, table, count, docs, docCount);
|
||||
}
|
||||
|
||||
// Registers `func` at `_G[tableName][methodName]`. If the namespace
|
||||
// doesn't already exist, creates an empty table for it.
|
||||
void RegisterTableFunction(const char *tableName, const char *methodName, CFunction func) {
|
||||
void RegisterTableFunction(const char *tableName, const char *methodName, CFunction func,
|
||||
const Doc::Function *doc) {
|
||||
void *L = State();
|
||||
if (L == nullptr)
|
||||
return;
|
||||
@@ -149,10 +346,41 @@ void RegisterTableFunction(const char *tableName, const char *methodName, CFunct
|
||||
PushCClosure(L, func, 0); // [tbl, methodName, closure]
|
||||
SetTable(L, -3); // tbl[m]=c; pops k+v. [tbl]
|
||||
SetTop(L, -2); // pop tbl. []
|
||||
MirrorRegistration(tableName, methodName);
|
||||
Api::Documentation::RecordTable(tableName, methodName, doc);
|
||||
}
|
||||
|
||||
// `_G[alias] = _G[tableName][methodName]`, by VALUE. The engine binds its
|
||||
// short aliases this way (`tinsert = tab.insert` in the compat snippet it
|
||||
// runs at Lua init), so a module that registers over a library function has
|
||||
// to re-bind the alias to the same closure — that keeps `tinsert ==
|
||||
// table.insert` true, as the engine left it, instead of minting a second
|
||||
// closure. A plain raw write, exactly what the snippet's assignment did. No-op
|
||||
// if the source is not a function (nothing was registered to alias).
|
||||
void RegisterGlobalAlias(const char *alias, const char *tableName, const char *methodName,
|
||||
const Doc::Function *doc) {
|
||||
void *L = State();
|
||||
if (L == nullptr)
|
||||
return;
|
||||
const int top = GetTop(L);
|
||||
EnsureGlobalTable(L, tableName); // [tbl]
|
||||
PushString(L, methodName); // [tbl, m]
|
||||
RawGet(L, -2); // [tbl, value]
|
||||
if (Type(L, -1) != TYPE_FUNCTION) {
|
||||
SetTop(L, top);
|
||||
return;
|
||||
}
|
||||
PushString(L, alias); // [tbl, value, alias]
|
||||
PushValue(L, -2); // [tbl, value, alias, value]
|
||||
RawSet(L, GLOBALS_INDEX); // _G[alias] = value. [tbl, value]
|
||||
SetTop(L, top);
|
||||
MirrorRegistration(nullptr, alias);
|
||||
Api::Documentation::RecordGlobal(alias, doc);
|
||||
}
|
||||
|
||||
void RegisterIntegerEnum(const char *parent, const char *sub,
|
||||
const EnumIntegerEntry *entries, int count) {
|
||||
const EnumIntegerEntry *entries, int count,
|
||||
const char *docSystem) {
|
||||
void *L = State();
|
||||
if (L == nullptr)
|
||||
return;
|
||||
@@ -166,6 +394,7 @@ void RegisterIntegerEnum(const char *parent, const char *sub,
|
||||
}
|
||||
SetTable(L, -3); // parentTbl[sub] = subTbl
|
||||
SetTop(L, -2); // pop parentTbl
|
||||
Api::Documentation::RecordEnum(parent, sub, entries, count, docSystem);
|
||||
}
|
||||
|
||||
void SetFieldNumber(void *L, const char *key, double value) {
|
||||
@@ -230,45 +459,14 @@ void PushLocalizedString(void *L, const char *globalName, const char *fallback)
|
||||
}
|
||||
}
|
||||
|
||||
// In-place `string.gsub(stack[-1], pattern, replacement)` — replaces
|
||||
// the string at the top of the stack with the substitution result.
|
||||
// Discards gsub's second return (the substitution count) by
|
||||
// requesting only one return from `Call`.
|
||||
static void GsubInPlace(void *L, const char *pattern, const char *replacement) {
|
||||
PushString(L, "string");
|
||||
GetTable(L, GLOBALS_INDEX);
|
||||
PushString(L, "gsub");
|
||||
GetTable(L, -2); // [..., str, string, gsub]
|
||||
Remove(L, -2); // [..., str, gsub]
|
||||
Insert(L, -2); // [..., gsub, str]
|
||||
PushString(L, pattern);
|
||||
PushString(L, replacement);
|
||||
Call(L, 3, 1); // [..., result]
|
||||
}
|
||||
|
||||
void PushLocalizedFormatInt(void *L, const char *globalName,
|
||||
const char *fallback, int n) {
|
||||
// Resolve `string.format` from _G.
|
||||
PushString(L, "format");
|
||||
GetTable(L, GLOBALS_INDEX);
|
||||
PushLocalizedString(L, globalName, fallback);
|
||||
|
||||
// Expand WoW's `|4singular:plural;` (and 3-form
|
||||
// `|4nom:gen_sing:plural;`) pluralization template by piggybacking
|
||||
// on Lua's `string.gsub`. The 2- vs 3-form distinction is locale
|
||||
// grammar (Slavic counting has a separate genitive-singular form
|
||||
// for 2..4); we collapse to nominative/plural since vanilla has
|
||||
// no proper locale-aware counting rules. 3-form pattern runs
|
||||
// first because it's more specific. Vanilla's `string.format`
|
||||
// doesn't process `|4` natively, so without this the template
|
||||
// would render literally.
|
||||
const char *picker3 = (n == 1) ? "%1" : "%3";
|
||||
const char *picker2 = (n == 1) ? "%1" : "%2";
|
||||
GsubInPlace(L, "|4([^:;]+):([^:;]+):([^;]+);", picker3);
|
||||
GsubInPlace(L, "|4([^:;]+):([^;]+);", picker2);
|
||||
|
||||
PushNumber(L, static_cast<double>(n));
|
||||
Call(L, 2, 1); // format(expandedFmt, n) → string
|
||||
Call(L, 2, 1); // format(fmt, n) → string
|
||||
}
|
||||
} // namespace Lua
|
||||
|
||||
@@ -276,7 +474,7 @@ namespace Console {
|
||||
namespace {
|
||||
using RegisterCommand_t = int(__fastcall *)(const char *name, void *handler,
|
||||
int category, const char *description);
|
||||
using Write_t = void(__fastcall *)(const char *line, int colorFlag);
|
||||
using Write_t = void(__fastcall *)(const char *line, int color);
|
||||
} // namespace
|
||||
|
||||
void RegisterCommand(const char *name, CommandHandler handler, int category,
|
||||
@@ -285,10 +483,13 @@ void RegisterCommand(const char *name, CommandHandler handler, int category,
|
||||
fn(name, reinterpret_cast<void *>(handler), category, description);
|
||||
}
|
||||
|
||||
void Write(const char *line) {
|
||||
void Write(const char *line, Color color) {
|
||||
auto fn = reinterpret_cast<Write_t>(Offsets::FUN_CONSOLE_WRITE);
|
||||
fn(line, 0);
|
||||
fn(line, color);
|
||||
}
|
||||
|
||||
void(__cdecl *const Printf)(const char *format, ...) =
|
||||
reinterpret_cast<void(__cdecl *)(const char *, ...)>(Offsets::FUN_CONSOLE_PRINTF);
|
||||
} // namespace Console
|
||||
|
||||
namespace {
|
||||
@@ -303,8 +504,10 @@ ModuleAutoRegister::ModuleAutoRegister(Fn f) : fn(f), next(g_moduleHead) {
|
||||
}
|
||||
|
||||
void RunModuleRegistrations() {
|
||||
Api::Documentation::BeginPass(Api::Documentation::ENV_GAME);
|
||||
for (auto *node = g_moduleHead; node != nullptr; node = node->next)
|
||||
node->fn();
|
||||
Api::Documentation::EndPass();
|
||||
}
|
||||
|
||||
GlueModuleAutoRegister::GlueModuleAutoRegister(Fn f)
|
||||
@@ -313,8 +516,10 @@ GlueModuleAutoRegister::GlueModuleAutoRegister(Fn f)
|
||||
}
|
||||
|
||||
void RunGlueModuleRegistrations() {
|
||||
Api::Documentation::BeginPass(Api::Documentation::ENV_GLUE);
|
||||
for (auto *node = g_glueModuleHead; node != nullptr; node = node->next)
|
||||
node->fn();
|
||||
Api::Documentation::EndPass();
|
||||
}
|
||||
|
||||
ReloadAutoRegister::ReloadAutoRegister(Fn f) : fn(f), next(g_reloadHead) {
|
||||
|
||||
+273
-16
@@ -13,6 +13,7 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
namespace Game {
|
||||
@@ -57,6 +58,22 @@ inline T &Ref(uintptr_t address) {
|
||||
return *reinterpret_cast<T *>(address);
|
||||
}
|
||||
|
||||
// Calls `fn(object)` for each object of one of a frame's intrusive lists,
|
||||
// OFF_FRAME_REGION_LIST or OFF_FRAME_CHILD_LIST: node+4 next, node+8 object,
|
||||
// a NULL or low-bit-1 link ends it - the walk the engine's own frame code
|
||||
// does (the alpha setter, the bounds walk 0x00786F80).
|
||||
template <typename Fn>
|
||||
void ForEachFrameListObject(void *frame, uintptr_t listOffset, Fn fn) {
|
||||
uintptr_t link = Read<uintptr_t>(frame, listOffset);
|
||||
while (link != 0 && (link & 1) == 0) {
|
||||
void *obj = *reinterpret_cast<void *const *>(link + 8);
|
||||
const uintptr_t next = *reinterpret_cast<const uintptr_t *>(link + 4);
|
||||
if (obj != nullptr)
|
||||
fn(obj);
|
||||
link = next;
|
||||
}
|
||||
}
|
||||
|
||||
// --- Engine primitives ------------------------------------------------------
|
||||
|
||||
// Resolve a unit token (`"player"`, `"target"`, `"party3"`, `"nameplate1"`,
|
||||
@@ -70,6 +87,15 @@ inline T &Ref(uintptr_t address) {
|
||||
// across a dozen modules.
|
||||
void *ResolveUnitToken(const char *token);
|
||||
|
||||
// UI pixels <-> internal layout (anchor) units. Script_SetPoint converts its
|
||||
// pixel offsets with `px * [VAR_COORD_DDC_WIDTH_SCALE] / ([VAR_COORD_ASPECT_COMPENSATION]
|
||||
// * UI_COORD_SCALE_UNIT)`; Script_GetLeft and Script_GetStringWidth push the
|
||||
// inverse. A region's LOCAL pixels must be multiplied by its effective scale
|
||||
// (OFF_REGION_EFFECTIVE_SCALE) first. Both return 0 while the scale globals
|
||||
// are unset, so an early caller gets a zero offset rather than a wild one.
|
||||
float PixelToInternal(float px);
|
||||
double InternalToPixel(float internal);
|
||||
|
||||
using FrameScript_Initialize_t = bool(__fastcall *)();
|
||||
using LoadScriptFunctions_t = void(__fastcall *)();
|
||||
|
||||
@@ -78,6 +104,113 @@ using LoadScriptFunctions_t = void(__fastcall *)();
|
||||
// registering its 109 glue functions. See FUN_LOAD_GLUE_SCRIPT_FUNCTIONS.
|
||||
using LoadGlueScriptFunctions_t = void(__stdcall *)();
|
||||
|
||||
// --- API documentation descriptors -----------------------------------------
|
||||
//
|
||||
// Every Lua registration (see the `Register*` functions in `Game::Lua`) can
|
||||
// carry a descriptor: the signature the function presents to Lua — typed
|
||||
// arguments and returns, nilability, defaults — plus a one-sentence summary.
|
||||
// The descriptors are the single source of truth for the API's SHAPE.
|
||||
// `src/api/Documentation.cpp` records each registration on the first pass of
|
||||
// each Lua state and exports the result on demand as Blizzard
|
||||
// `APIDocumentation` tables (`C_APIDocumentation.GetSystems` / `GetSystem`),
|
||||
// which the embedded addon's `/api` browser renders. Prose beyond one
|
||||
// sentence stays in the docs; a descriptor is shape, not manual.
|
||||
//
|
||||
// Rules:
|
||||
// - One descriptor per REGISTERED NAME, not per C function. The same
|
||||
// `Script_*` bound twice with different return conventions
|
||||
// (`IsUsableSpell` → 1/nil pairs, `C_Spell.IsSpellUsable` → booleans)
|
||||
// gets two descriptors; a pair with the same shape may share one.
|
||||
// - `type` uses Blizzard's spellings — "number", "string", "bool",
|
||||
// "table", "luaIndex", "UnitToken", "SpellIdentifier", … — or the Name
|
||||
// of a `Structure` / enumeration declared elsewhere, which the browser
|
||||
// renders as a link.
|
||||
// - `Function::system` names the System a GLOBAL belongs to; convention
|
||||
// `<Area>Globals` ("SpellGlobals", "ItemGlobals"). Table functions
|
||||
// derive theirs from the table ("C_Spell" → System "Spell", Namespace
|
||||
// "C_Spell"); frame methods from the registry. A global's system must
|
||||
// not reuse a namespaced System's Name — the browser would prefix it.
|
||||
// - Descriptors are `const` objects with constant initializers (string
|
||||
// literals + file-scope arrays): no heap, no dynamic init.
|
||||
// - Summaries are user-facing text: one sentence, plain words, present
|
||||
// tense, no patch versions.
|
||||
namespace Doc {
|
||||
|
||||
struct Field {
|
||||
const char *name;
|
||||
const char *type;
|
||||
bool nilable;
|
||||
const char *defaultValue; // Lua literal ("false", "0", "\"player\""), or nullptr
|
||||
const char *doc; // one sentence, or nullptr
|
||||
};
|
||||
|
||||
// Required argument / always-present return.
|
||||
constexpr Field Req(const char *name, const char *type, const char *doc = nullptr) {
|
||||
return {name, type, false, nullptr, doc};
|
||||
}
|
||||
// Optional: nilable when no default is given, otherwise non-nil with that
|
||||
// default (Blizzard marks defaulted arguments `Nilable = false` + `Default`).
|
||||
constexpr Field Opt(const char *name, const char *type, const char *dflt = nullptr,
|
||||
const char *doc = nullptr) {
|
||||
return {name, type, dflt == nullptr, dflt, doc};
|
||||
}
|
||||
// Variable arguments / returns.
|
||||
constexpr Field Vararg(const char *type, const char *doc = nullptr) {
|
||||
return {"...", type, true, nullptr, doc};
|
||||
}
|
||||
|
||||
// A view over a file-scope `const Field[]`; `{}` means none.
|
||||
struct FieldList {
|
||||
const Field *data = nullptr;
|
||||
int count = 0;
|
||||
constexpr FieldList() = default;
|
||||
template <size_t N>
|
||||
constexpr FieldList(const Field (&a)[N]) : data(a), count(static_cast<int>(N)) {}
|
||||
};
|
||||
|
||||
// A registered function. Positional init: `{summary, args, rets}` for a
|
||||
// table function, `{summary, args, rets, "XGlobals"}` for a global, and
|
||||
// `{summary, args, rets, nullptr, true}` for a namespaced ClassicAPI
|
||||
// extension.
|
||||
struct Function {
|
||||
const char *summary;
|
||||
FieldList args;
|
||||
FieldList rets;
|
||||
const char *system; // globals / glue / aliases only; see the rules above
|
||||
bool extension; // a ClassicAPI-original API, not a Blizzard one
|
||||
};
|
||||
|
||||
// Pairs a frame method with its descriptor BY NAME (the engine's method
|
||||
// tables are name-keyed; `SetShown` exists on four registries with four
|
||||
// function pointers). Order is free; unmatched names are reported.
|
||||
struct Method {
|
||||
const char *name;
|
||||
const Function *doc;
|
||||
};
|
||||
|
||||
// A table shape a function returns or accepts → `Tables{Type="Structure"}`
|
||||
// in `system`. Self-registering: nothing binds a structure to Lua, so it
|
||||
// chains onto a static list at construction. Declare it next to the
|
||||
// function that returns it.
|
||||
struct Structure {
|
||||
Structure(const char *name, const char *system, FieldList fields,
|
||||
const char *summary = nullptr);
|
||||
const char *name;
|
||||
const char *system;
|
||||
FieldList fields;
|
||||
const char *summary;
|
||||
const Structure *next;
|
||||
};
|
||||
|
||||
// A custom event's payload, attached to its `Event::Custom::AutoReserve`.
|
||||
struct Event {
|
||||
const char *system;
|
||||
const char *summary;
|
||||
FieldList payload;
|
||||
};
|
||||
|
||||
} // namespace Doc
|
||||
|
||||
namespace Lua {
|
||||
using CFunction = int(__fastcall *)(void *L);
|
||||
|
||||
@@ -121,8 +254,14 @@ using lua_pushcclosure_t = void(__fastcall *)(void *L, CFunction fn, int upvals)
|
||||
using lua_newtable_t = void(__fastcall *)(void *L);
|
||||
using lua_gettable_t = void(__fastcall *)(void *L, int idx);
|
||||
using lua_rawget_t = void(__fastcall *)(void *L, int idx);
|
||||
// Pushes t[n] for the table at idx, raw (no metamethods). With idx =
|
||||
// REGISTRY_INDEX it pushes a value stored under an integer ref.
|
||||
using lua_rawgeti_t = void(__fastcall *)(void *L, int idx, int n);
|
||||
using lua_settable_t = void(__fastcall *)(void *L, int idx);
|
||||
using lua_rawset_t = void(__fastcall *)(void *L, int idx);
|
||||
// Pushes the metatable of the value at idx and returns 1, or pushes
|
||||
// nothing and returns 0 when it has none.
|
||||
using lua_getmetatable_t = int(__fastcall *)(void *L, int idx);
|
||||
// Pops the table at the top and installs it as the metatable of the value
|
||||
// at idx; returns 1.
|
||||
using lua_setmetatable_t = int(__fastcall *)(void *L, int idx);
|
||||
@@ -134,6 +273,7 @@ using lua_call_t = void(__fastcall *)(void *L, int nargs, int nresults);
|
||||
using lua_pcall_t = int(__fastcall *)(void *L, int nargs, int nresults, int errfunc);
|
||||
using lua_next_t = int(__fastcall *)(void *L, int idx);
|
||||
using lua_type_t = int(__fastcall *)(void *L, int index);
|
||||
using lua_typename_t = const char *(__fastcall *)(void *L, int type);
|
||||
// The 1.12 `lua_error` wrapper at `0x6F4940` is actually variadic —
|
||||
// it does `lua_pushvfstring(L, fmt, args)` then prepends `luaL_where`
|
||||
// and throws. Existing callers pass a single literal (no `%`), which
|
||||
@@ -179,8 +319,10 @@ extern const lua_pushcclosure_t PushCClosure;
|
||||
extern const lua_newtable_t NewTable;
|
||||
extern const lua_gettable_t GetTable;
|
||||
extern const lua_rawget_t RawGet;
|
||||
extern const lua_rawgeti_t RawGetI;
|
||||
extern const lua_settable_t SetTable;
|
||||
extern const lua_rawset_t RawSet;
|
||||
extern const lua_getmetatable_t GetMetatable;
|
||||
extern const lua_setmetatable_t SetMetatable;
|
||||
extern const lua_insert_t Insert;
|
||||
extern const lua_remove_t Remove;
|
||||
@@ -190,6 +332,7 @@ extern const lua_call_t Call;
|
||||
extern const lua_pcall_t PCall;
|
||||
extern const lua_next_t Next;
|
||||
extern const lua_type_t Type;
|
||||
extern const lua_typename_t TypeName;
|
||||
extern const lua_error_t Error;
|
||||
extern const lua_topointer_t ToPointer;
|
||||
extern const lua_tothread_t ToThread;
|
||||
@@ -216,9 +359,84 @@ void *State();
|
||||
// the `self` slot of any `frame:method(...)` invocation.
|
||||
void *ResolveObject(void *L, int idx);
|
||||
|
||||
// The inverse: the object's Lua-registry ref, created on first use exactly as
|
||||
// the engine does it (GetMouseFocus and the script runners register an
|
||||
// object with FUN_FRAMESCRIPT_OBJECT_SCRIPT_REGISTER when its refcount is 0).
|
||||
int ObjectLuaRef(void *object);
|
||||
// Pushes the object's Lua table (registry[ObjectLuaRef(object)]).
|
||||
void PushObject(void *L, void *object);
|
||||
|
||||
// How the engine names an object in its frame-script usage errors:
|
||||
// `GetName() ?: "<unnamed>"` (VTBL_SCRIPTOBJECT_GET_NAME).
|
||||
const char *ObjectDisplayName(void *object);
|
||||
|
||||
// Same resolve, then the type gate every engine frame method applies to its
|
||||
// `self` before touching it: `lua_type == table`, resolve to the object, then
|
||||
// the `IsA(typeId)` vmethod at vtable+0x10. `ResolveObject` alone is not
|
||||
// enough for a method that casts the result — it hands back a
|
||||
// `CFrameScriptObject *` for ANY frame, so `GameTooltip.SetSpellByID(button)`
|
||||
// would reach the tooltip builder with a Button. Frame methods are ordinary
|
||||
// first-class Lua values (the per-type dispatcher is an `__index` handler
|
||||
// that returns the method closure), so that call is reachable from plain Lua
|
||||
// and the gate is not optional.
|
||||
//
|
||||
// `typeIdVar` is the class's `VAR_*_LUA_TYPE_ID`, which must match the
|
||||
// registry the method was registered on. The id is assigned lazily by
|
||||
// whichever method of the class runs first, so these mirror that assignment
|
||||
// and work even before any stock method of the type has been called.
|
||||
//
|
||||
// Raises the engine's own three errors and returns null. Pass
|
||||
// `raiseError = false` for an optional object ARGUMENT, where the caller
|
||||
// wants a silent null rather than a "this" error naming the wrong slot.
|
||||
// Returns null either way, so callers always check.
|
||||
void *ResolveTypedObject(void *L, int idx, uintptr_t typeIdVar,
|
||||
bool raiseError = true);
|
||||
|
||||
// For a method registered on SEVERAL registries, where any of those types is
|
||||
// a legitimate `self`. Accepts the object if `IsA` passes for any of the
|
||||
// listed ids — which is exactly what being in all of those registries means,
|
||||
// and avoids having to pin down the shared base class.
|
||||
void *ResolveTypedObjectAny(void *L, int idx, const uintptr_t *typeIdVars,
|
||||
int count, bool raiseError = true);
|
||||
|
||||
// The class's live type id, assigning it if the engine has not yet. Needed
|
||||
// directly only when calling a type-specific vtable slot.
|
||||
int FrameScriptTypeId(uintptr_t typeIdVar);
|
||||
|
||||
// The object's `IsA(typeId)` vmethod for a class's `VAR_*_LUA_TYPE_ID`.
|
||||
bool IsA(void *object, uintptr_t typeIdVar);
|
||||
|
||||
// Per-type sugar over `ResolveTypedObject`, so a call site cannot pair a
|
||||
// method with the wrong class's id. `idx` defaults to the `self` slot.
|
||||
void *ResolveTooltip(void *L, int idx = 1, bool raiseError = true);
|
||||
void *ResolveFrame(void *L, int idx = 1, bool raiseError = true);
|
||||
void *ResolveRegion(void *L, int idx = 1, bool raiseError = true);
|
||||
void *ResolveTexture(void *L, int idx = 1, bool raiseError = true);
|
||||
void *ResolveFontString(void *L, int idx = 1, bool raiseError = true);
|
||||
void *ResolveEditBox(void *L, int idx = 1, bool raiseError = true);
|
||||
void *ResolveModel(void *L, int idx = 1, bool raiseError = true);
|
||||
|
||||
// Every name these registrars bind is ALSO bound under `_G.ClassicAPI` —
|
||||
// `ClassicAPI.GetSpellInfo`, `ClassicAPI.C_Item.IsBound` — as an escape
|
||||
// hatch for names something else replaces later, and by value so
|
||||
// `ClassicAPI.X == X` until that happens. Automatic; a new module needs no
|
||||
// extra call. See `MirrorRegistration` in Game.cpp for why it lives here
|
||||
// and what it does not cover.
|
||||
//
|
||||
// Every registrar also RECORDS the registration for the API documentation
|
||||
// (`src/api/Documentation.cpp`): kind, table, name, registry, and which Lua
|
||||
// state's pass it ran in (in-game / glue / both). Only the FIRST pass of
|
||||
// each state records — later passes (every `/reload`) are no-ops — and a
|
||||
// registration made outside a `Run*Registrations` pass is not recorded at
|
||||
// all. The trailing `doc` argument is the descriptor (see `Game::Doc`
|
||||
// above); pass `nullptr` for a not-yet-documented registration and
|
||||
// `_classicapi_UndocumentedAPI()` lists it. The defaults exist only until
|
||||
// the sweep finishes; then they go and a missing descriptor stops compiling.
|
||||
|
||||
// Registers a single global Lua function (e.g. `GetSpellInfo`). The function
|
||||
// must use the WoW Lua C function ABI: `int __fastcall(void *L)`.
|
||||
void RegisterGlobalFunction(const char *name, CFunction func);
|
||||
void RegisterGlobalFunction(const char *name, CFunction func,
|
||||
const Doc::Function *doc = nullptr);
|
||||
|
||||
// Glue-state equivalent of `RegisterGlobalFunction`. Identical wire
|
||||
// (calls `FrameScript_RegisterFunction`); the engine routes the
|
||||
@@ -228,7 +446,8 @@ void RegisterGlobalFunction(const char *name, CFunction func);
|
||||
// its own 109 glue functions, and `VAR_LUA_STATE` still points at the
|
||||
// glue state. Calling outside that window would silently target the
|
||||
// wrong state.
|
||||
void RegisterGlueFunction(const char *name, CFunction func);
|
||||
void RegisterGlueFunction(const char *name, CFunction func,
|
||||
const Doc::Function *doc = nullptr);
|
||||
|
||||
// Frame-method registration entry: { name, func } pairs walked by the engine's
|
||||
// per-frame-type method-table iterator. Layout matches what the engine expects
|
||||
@@ -240,15 +459,26 @@ struct FrameMethodEntry {
|
||||
|
||||
// Registers a batch of methods on a per-frame-type registry (e.g.
|
||||
// GameTooltipMethodRegistry for `tooltip:Foo()` calls). `context` is the
|
||||
// registry address — see Offsets::VAR_*_METHOD_REGISTRY.
|
||||
void RegisterFrameMethods(void *context, const FrameMethodEntry *table, int count);
|
||||
// registry address — see Offsets::VAR_*_METHOD_REGISTRY. `docs` pairs
|
||||
// descriptors to the entries by NAME (any order, any subset).
|
||||
void RegisterFrameMethods(void *context, const FrameMethodEntry *table, int count,
|
||||
const Doc::Method *docs = nullptr, int docCount = 0);
|
||||
|
||||
// Registers `func` at `_G[tableName][methodName]`, creating the namespace
|
||||
// table if it doesn't already exist. This is how modern WoW C_*-style APIs
|
||||
// are bound — the engine has no built-in support for table-bound Lua
|
||||
// functions, so we manipulate the globals table directly via the Lua C API.
|
||||
void RegisterTableFunction(const char *tableName, const char *methodName,
|
||||
CFunction func);
|
||||
CFunction func, const Doc::Function *doc = nullptr);
|
||||
|
||||
// Binds `_G[alias]` to the SAME closure as `_G[tableName][methodName]`, by
|
||||
// value — the way the engine's own Lua-init snippet binds its short aliases
|
||||
// (`tinsert = table.insert`, `strlen = string.len`, …). Use it after
|
||||
// registering over a library function whose alias the snippet has already
|
||||
// captured, so the alias follows the replacement and `alias == table.method`
|
||||
// stays true. Mirrored under `_G.ClassicAPI` like every other registration.
|
||||
void RegisterGlobalAlias(const char *alias, const char *tableName, const char *methodName,
|
||||
const Doc::Function *doc = nullptr);
|
||||
|
||||
// Key/value pair for `RegisterIntegerEnum`. `key` becomes a field name
|
||||
// (PascalCase, matching Blizzard's `Enum.*` naming) and `value` is the
|
||||
@@ -261,8 +491,11 @@ struct EnumIntegerEntry {
|
||||
// Registers `_G[parent][sub] = { entries }` as an integer-valued enum
|
||||
// table, creating `_G[parent]` if needed. Used for Blizzard-style
|
||||
// `Enum.AddOnSecurityStatus = { Secure=0, Insecure=1, ... }` shapes.
|
||||
// `docSystem` is the documentation System the enumeration belongs to
|
||||
// ("SpellBook", "Item", …); the entries themselves are the documentation.
|
||||
void RegisterIntegerEnum(const char *parent, const char *sub,
|
||||
const EnumIntegerEntry *entries, int count);
|
||||
const EnumIntegerEntry *entries, int count,
|
||||
const char *docSystem = nullptr);
|
||||
|
||||
// Set `t[key] = value` on the table currently at stack[-1] (the most
|
||||
// common shape used when populating a struct-style table mid-build).
|
||||
@@ -299,6 +532,8 @@ void PushLocalizedString(void *L, const char *globalName, const char *fallback);
|
||||
// `ITEM_SLOTS_IGNORED = "%d slot(s) ignored"`, etc.). Callers that
|
||||
// need string or float args, or multiple args, can build their own
|
||||
// using `PushLocalizedString` + manual `string.format` invocation.
|
||||
// A `|4singular:plural;` in the string stays; the engine's grammar pass
|
||||
// (Text::Grammar) expands it when the text is set.
|
||||
void PushLocalizedFormatInt(void *L, const char *globalName,
|
||||
const char *fallback, int n);
|
||||
|
||||
@@ -326,16 +561,17 @@ bool CallGlobalString(void *L, const char *name, const char *arg);
|
||||
// section in CLAUDE.md for the underlying offsets and ABI.
|
||||
namespace Console {
|
||||
|
||||
// Console-command handler ABI: `args` is the command-line text after
|
||||
// the command name (empty string when invoked bare). The engine
|
||||
// ignores the return value; return 1 by convention.
|
||||
using CommandHandler = int(__fastcall *)(void *unused, const char *args);
|
||||
// Console-command handler ABI — 4.3.4's `COMMANDHANDLER(command,
|
||||
// arguments)`. `command` is the name the command was invoked by, which
|
||||
// is how one handler serves several names: every CVar is registered with
|
||||
// the shared FUN_CONSOLE_CVAR_COMMAND_HANDLER, which looks the CVar up by
|
||||
// `command`. `args` is the text after the name (empty string when
|
||||
// invoked bare). The engine ignores the return value; return 1.
|
||||
using CommandHandler = int(__fastcall *)(const char *command, const char *args);
|
||||
|
||||
// Help-grouping categories — the engine's `help` enumerates these nine
|
||||
// (in this order). Cosmetic: the value only affects which group `help`
|
||||
// lists the command under; the engine doesn't validate it. Values are
|
||||
// sequential table indices (graphics=1 confirmed via FUN_0066F6C0, the
|
||||
// rest follow the displayed order).
|
||||
// Help-grouping categories — 4.3.4's `CATEGORY` enum, which matches the
|
||||
// nine-entry table the 1.12 `help` command lists (VAR_CONSOLE_CATEGORY_TABLE).
|
||||
// Cosmetic: only `help` grouping reads it; the registrar doesn't validate it.
|
||||
enum Category {
|
||||
CATEGORY_DEBUG = 0,
|
||||
CATEGORY_GRAPHICS = 1,
|
||||
@@ -357,9 +593,30 @@ enum Category {
|
||||
void RegisterCommand(const char *name, CommandHandler handler, int category,
|
||||
const char *description);
|
||||
|
||||
// Line colour types — 4.3.4's `COLOR_T`, indexing the nine-entry
|
||||
// VAR_CONSOLE_COLORS table. The engine's `help` writes WARNING (yellow),
|
||||
// its failures ERROR (red), and its plain output DEFAULT.
|
||||
enum Color {
|
||||
COLOR_DEFAULT = 0,
|
||||
COLOR_INPUT = 1,
|
||||
COLOR_ECHO = 2,
|
||||
COLOR_ERROR = 3,
|
||||
COLOR_WARNING = 4,
|
||||
COLOR_GLOBAL = 5,
|
||||
COLOR_ADMIN = 6,
|
||||
COLOR_HIGHLIGHT = 7,
|
||||
COLOR_BACKGROUND = 8,
|
||||
};
|
||||
|
||||
// Writes a line to the console output buffer. No-ops cleanly when the
|
||||
// console isn't active, so it's always safe to call.
|
||||
void Write(const char *line);
|
||||
void Write(const char *line, Color color = COLOR_DEFAULT);
|
||||
|
||||
// The engine's own `ConsolePrintf` (FUN_CONSOLE_PRINTF): formats with
|
||||
// Storm's printf into a 1024-byte buffer, then writes it in
|
||||
// COLOR_DEFAULT. Exposed as the engine's entry itself rather than a
|
||||
// wrapper, because a cdecl varargs call cannot be forwarded.
|
||||
extern void(__cdecl *const Printf)(const char *format, ...);
|
||||
|
||||
} // namespace Console
|
||||
|
||||
|
||||
+99
-110
@@ -11,7 +11,10 @@
|
||||
// You should have received a copy of the GNU General Public License along with
|
||||
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#include "HookSecureFunc.h"
|
||||
|
||||
#include "Game.h"
|
||||
#include "Offsets.h"
|
||||
|
||||
#include <cstring>
|
||||
|
||||
@@ -19,14 +22,19 @@ namespace HookSecureFunc {
|
||||
|
||||
namespace {
|
||||
|
||||
// Names that must not be hooked when targeting `_G`. Hooking any of these
|
||||
// would either break taint propagation (the "secure" functions) or replace
|
||||
// core Lua language primitives whose behavior the engine depends on
|
||||
// internally — e.g. `pairs` is called from C in the iterator path; if Lua
|
||||
// `pairs` is replaced with a wrapper closure, the engine still gets the
|
||||
// original via its own table-method dispatch, but Lua-side iteration goes
|
||||
// through our wrapper, and the two diverging is a footgun. Modern WoW
|
||||
// rejects the hook outright; we mirror that. Sorted alphabetically.
|
||||
// Names that must not be hooked when targeting `_G`. This is the client's
|
||||
// own list, VERBATIM: patch 11.0.0 (The War Within, 2024-07-23) made
|
||||
// `hooksecurefunc` refuse exactly these 23 names with a "Cannot hook
|
||||
// function" error — the taint-relevant primitives (the "secure" family plus
|
||||
// the Lua primitives secure code paths run through). It is deliberately NOT
|
||||
// "every base-library function": 11.0 leaves `tostring`, `error`,
|
||||
// `loadstring`, `assert`, `collectgarbage`, … hookable, and includes names
|
||||
// that are not base-library functions at all. So do not derive this from
|
||||
// the engine's `luaopen_base` table (`0x00811E28`, 36 entries — see
|
||||
// BlizzardScriptAPI.md §3); that is a different set with a different
|
||||
// purpose. Names with no 1.12 counterpart (`wipe` is `table.wipe` here; the
|
||||
// secure family does not exist) stay for parity of the error an addon
|
||||
// sees. Sorted alphabetically.
|
||||
const char *const kUnhookableNames[] = {
|
||||
"getfenv", "getmetatable", "hooksecurefunc", "ipairs", "issecurevalue",
|
||||
"issecurevariable", "next", "pairs", "pcall", "pcallwithenv", "rawget",
|
||||
@@ -45,138 +53,113 @@ bool IsUnhookable(const char *name) {
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// Wrapper closure body — called when the hooked function is invoked.
|
||||
// Stack contains the wrapper's args (`[arg1..argN]`); the closure's
|
||||
// upvalues hold `(orig, callback)`.
|
||||
// upvalues hold `(orig, callback)`. 4.3.4's FrameScript_HookWrapper, less
|
||||
// its taint bookkeeping (1.12 has no taint):
|
||||
//
|
||||
// Modern `hooksecurefunc` semantics: original runs first, callback
|
||||
// runs after with the same args (returns ignored), original's
|
||||
// results propagate to the caller. No cap on return count. A buggy
|
||||
// callback must NOT prevent the original's results from reaching
|
||||
// the caller — that's why step (3) uses pcall.
|
||||
//
|
||||
// Stack-shuffling mirrors 3.3.5's `FUN_00817050` so the args sit at
|
||||
// the top for both calls without copying them twice; results sink
|
||||
// to the bottom and end up as the wrapper's natural return frame.
|
||||
int __fastcall HookWrapper(void *L) {
|
||||
// 1. orig(...) with lua_call — an error in the original propagates to
|
||||
// the caller, as it would unhooked.
|
||||
// 2. Results sink below the args, so they end up as the wrapper's
|
||||
// return frame without being copied again.
|
||||
// 3. callback(...) through lua_pcall with the engine's frame-script
|
||||
// message handler as errfunc: a broken hook is REPORTED the way any
|
||||
// script error is (the error frame / geterrorhandler), and the
|
||||
// original's results still reach the caller.
|
||||
int __fastcall Wrapper(void *L) {
|
||||
const int nargs = Game::Lua::GetTop(L);
|
||||
|
||||
// (1) orig(...) — pops orig + nargs args (copies), pushes results.
|
||||
// Stack after: `[arg1..argN, res1..resM]`.
|
||||
Game::Lua::PushValue(L, Game::Lua::UpvalueIndex(1));
|
||||
// (1) Stack after: `[arg1..argN, res1..resM]`.
|
||||
for (int i = 1; i <= nargs; ++i)
|
||||
Game::Lua::PushValue(L, i);
|
||||
Game::Lua::PushValue(L, Game::Lua::UpvalueIndex(1));
|
||||
Game::Lua::Insert(L, nargs + 1);
|
||||
Game::Lua::Call(L, nargs, Game::Lua::MULTRET);
|
||||
const int nresults = Game::Lua::GetTop(L) - nargs;
|
||||
|
||||
// (2) Shuffle results below the saved args. Each `Insert(L, 1)`
|
||||
// moves the current top down to position 1; running it
|
||||
// nresults times rotates the results block beneath the args.
|
||||
// (2) Each `Insert(L, 1)` moves the top value to the bottom; nresults
|
||||
// of them rotate the results block beneath the args.
|
||||
// Stack after: `[res1..resM, arg1..argN]`.
|
||||
for (int i = 0; i < nresults; ++i)
|
||||
Game::Lua::Insert(L, 1);
|
||||
|
||||
// (3) callback(...) via pcall — errors are caught and dropped so
|
||||
// the original's return values always reach the caller. This
|
||||
// is the load-bearing safety property of hooksecurefunc on
|
||||
// 3.x; on 1.12 it just means a buggy hook can't break the
|
||||
// hooked path. errfunc=0 → no traceback (3.3.5 uses
|
||||
// `registry["_TRACEBACK"]`, not a 1.12 convention; we'd be
|
||||
// discarding the formatted message anyway).
|
||||
// (3) Stack: `[res1..resM, errfunc, callback, arg1..argN]`. The
|
||||
// handler ref is the one every engine script pcall passes; 0 (not
|
||||
// yet set) falls back to no handler rather than a bad index.
|
||||
Game::Lua::PushValue(L, Game::Lua::UpvalueIndex(2));
|
||||
Game::Lua::Insert(L, nresults + 1);
|
||||
if (Game::Lua::PCall(L, nargs, 0, 0) != 0) {
|
||||
// pcall failure leaves the error message on top; drop it.
|
||||
Game::Lua::Remove(L, -1);
|
||||
int errIdx = 0;
|
||||
const int errRef = Game::Read<int>(
|
||||
static_cast<uintptr_t>(Offsets::VAR_FRAMESCRIPT_ERROR_HANDLER_REF));
|
||||
if (errRef > 0) {
|
||||
Game::Lua::RawGetI(L, Game::Lua::REGISTRY_INDEX, errRef);
|
||||
Game::Lua::Insert(L, nresults + 1);
|
||||
errIdx = nresults + 1;
|
||||
}
|
||||
Game::Lua::PCall(L, nargs, 0, errIdx);
|
||||
|
||||
// Stack: `[res1..resM]` — return the original's results verbatim.
|
||||
// Drop the handler and any error value — `[res1..resM]` remains.
|
||||
Game::Lua::SetTop(L, nresults);
|
||||
return nresults;
|
||||
}
|
||||
|
||||
// `hooksecurefunc(name, callback)` — hooks a global by name, target
|
||||
// table is `_G`.
|
||||
// `hooksecurefunc(table, name, callback)` — hooks `table[name]`.
|
||||
//
|
||||
// In both cases the original function runs first and its results
|
||||
// propagate; `callback` runs after with the same args (returns
|
||||
// discarded). The "secure" label refers to taint propagation in
|
||||
// 3.x+; on 1.12 it's just a post-hook with return preservation.
|
||||
void PushWrapper(void *L) {
|
||||
Game::Lua::PushCClosure(L, &Wrapper, 2);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
// `hooksecurefunc([table,] "function", hookfunc)` — replaces
|
||||
// `table[name]` (default `_G`) with a wrapper that runs the original, then
|
||||
// `hookfunc` with the same args, and returns the original's results.
|
||||
// 4.3.4's Script_hooksecurefunc, less taint:
|
||||
// * a non-table first argument means `_G` is inserted at index 1, so
|
||||
// both forms share one index layout;
|
||||
// * the name only has to pass lua_isstring, so a number works (and is
|
||||
// looked up as its string, the same as lua_tostring makes it);
|
||||
// * the original is read with lua_gettable (inherited methods resolve
|
||||
// through __index) but the wrapper is written with lua_rawset, so a
|
||||
// target's __newindex never runs;
|
||||
// * the error texts are 4.3.4's.
|
||||
// The one addition is the 11.0 unhookable-name check for the `_G` form.
|
||||
int __fastcall Script_HookSecureFunc(void *L) {
|
||||
int targetIdx, nameIdx, callbackIdx;
|
||||
const int t1 = Game::Lua::Type(L, 1);
|
||||
const bool implicitGlobals = Game::Lua::Type(L, 1) != Game::Lua::TYPE_TABLE;
|
||||
if (implicitGlobals) {
|
||||
Game::Lua::PushValue(L, Game::Lua::GLOBALS_INDEX);
|
||||
Game::Lua::Insert(L, 1);
|
||||
}
|
||||
|
||||
if (t1 == Game::Lua::TYPE_TABLE) {
|
||||
// Three-arg form: (table, name, callback)
|
||||
targetIdx = 1;
|
||||
nameIdx = 2;
|
||||
callbackIdx = 3;
|
||||
} else if (t1 == Game::Lua::TYPE_STRING) {
|
||||
// Two-arg form: (name, callback) — target = _G via pseudo-
|
||||
// index. Don't push _G with `lua_pushvalue(GLOBALS_INDEX)`:
|
||||
// it crashes (the pushvalue → setobj2s chain dereferences a
|
||||
// bad TValue pointer for that pseudo-index). `lua_gettable` /
|
||||
// `lua_settable` accept GLOBALS_INDEX as the table arg
|
||||
// directly, so we use it that way without pushing.
|
||||
targetIdx = Game::Lua::GLOBALS_INDEX;
|
||||
nameIdx = 1;
|
||||
callbackIdx = 2;
|
||||
} else {
|
||||
Game::Lua::Error(L,
|
||||
"hooksecurefunc(table, name, callback) or hooksecurefunc(name, callback)");
|
||||
if (!Game::Lua::IsString(L, 2) ||
|
||||
Game::Lua::Type(L, 3) != Game::Lua::TYPE_FUNCTION) {
|
||||
Game::Lua::Error(L, "Usage: hooksecurefunc([table,] \"function\", hookfunc)");
|
||||
return 0;
|
||||
}
|
||||
Game::Lua::SetTop(L, 3); // [t, name, hookfunc]
|
||||
// Converts a number name to its string in place; the string stays on
|
||||
// the stack, so the pointer outlives every use below.
|
||||
const char *name = Game::Lua::ToString(L, 2);
|
||||
|
||||
// Block the hook when targeting `_G` implicitly and the name is in the
|
||||
// unhookable set. Not applied to the three-arg form (table targets):
|
||||
// hooking `MyLib.pairs` is fine even if Lua's global `pairs` is not,
|
||||
// and a caller who passes `_G` explicitly is opting in deliberately.
|
||||
if (implicitGlobals && IsUnhookable(name)) {
|
||||
Game::Lua::Error(L, "hooksecurefunc: function is unhookable");
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (Game::Lua::Type(L, nameIdx) != Game::Lua::TYPE_STRING) {
|
||||
Game::Lua::Error(L, "hooksecurefunc: name must be a string");
|
||||
return 0;
|
||||
}
|
||||
if (Game::Lua::Type(L, callbackIdx) != Game::Lua::TYPE_FUNCTION) {
|
||||
Game::Lua::Error(L, "hooksecurefunc: callback must be a function");
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Block the hook when targeting `_G` and the name is in the unhookable
|
||||
// set. We don't apply this to the three-arg form (table targets):
|
||||
// hooking `MyLib.pairs` is fine even if Lua's global `pairs` is not —
|
||||
// the blacklist is specifically about `_G[name]`. A user who passes
|
||||
// `_G` explicitly as the table target is opting in deliberately and we
|
||||
// don't second-guess it.
|
||||
if (targetIdx == Game::Lua::GLOBALS_INDEX) {
|
||||
const char *name = Game::Lua::ToString(L, nameIdx);
|
||||
if (IsUnhookable(name)) {
|
||||
Game::Lua::Error(L,
|
||||
"hooksecurefunc: function is unhookable");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Fetch target[name] — the original function. `gettable` uses
|
||||
// metamethods, so frame methods (resolved via the frame
|
||||
// metatable's __index) come back as callable closures, exactly
|
||||
// what we want to wrap.
|
||||
Game::Lua::PushValue(L, nameIdx);
|
||||
Game::Lua::GetTable(L, targetIdx);
|
||||
Game::Lua::PushValue(L, 2);
|
||||
Game::Lua::GetTable(L, 1); // [t, name, hookfunc, orig]
|
||||
if (Game::Lua::Type(L, -1) != Game::Lua::TYPE_FUNCTION) {
|
||||
Game::Lua::Error(L, "hooksecurefunc: target field is not a function");
|
||||
Game::Lua::Error(L, "hooksecurefunc(): %s is not a function", name);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Push callback as the second upvalue; orig is already on top
|
||||
// from the GetTable above.
|
||||
Game::Lua::PushValue(L, callbackIdx);
|
||||
|
||||
// Build the wrapper as a C closure with (orig, callback) as the
|
||||
// two upvalues. PushCClosure pops the upvalues from the stack
|
||||
// and pushes the closure.
|
||||
Game::Lua::PushCClosure(L, &HookWrapper, 2);
|
||||
|
||||
// Install: target[name] = wrapper. SetTable expects the value
|
||||
// on top and the key just below; push them in that order.
|
||||
Game::Lua::PushValue(L, nameIdx);
|
||||
Game::Lua::PushValue(L, -2); // duplicate the closure
|
||||
Game::Lua::SetTable(L, targetIdx);
|
||||
|
||||
Game::Lua::Insert(L, 3); // [t, name, orig, hookfunc]
|
||||
PushWrapper(L); // [t, name, wrapper]
|
||||
Game::Lua::RawSet(L, 1); // t[name] = wrapper
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -185,7 +168,13 @@ int __fastcall Script_HookSecureFunc(void *L) {
|
||||
static void RegisterLuaFunctions() {
|
||||
Game::Lua::RegisterGlobalFunction("hooksecurefunc", &Script_HookSecureFunc);
|
||||
}
|
||||
// 4.3.4 registers it from FrameScript_Initialize, which runs for the glue
|
||||
// state (Client.cpp) as well as the world (GameUI.cpp).
|
||||
static void RegisterGlueFunctions() {
|
||||
Game::Lua::RegisterGlueFunction("hooksecurefunc", &Script_HookSecureFunc);
|
||||
}
|
||||
|
||||
static const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
|
||||
static const Game::GlueModuleAutoRegister _autoregGlue{&RegisterGlueFunctions};
|
||||
|
||||
} // namespace HookSecureFunc
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
// This file is part of ClassicAPI.
|
||||
//
|
||||
// ClassicAPI is free software: you can redistribute it and/or modify it under the terms
|
||||
// of the GNU 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 General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License along with
|
||||
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#pragma once
|
||||
|
||||
// The one hook wrapper `hooksecurefunc` and `Frame:HookScript` both install —
|
||||
// 4.3.4 uses its FrameScript_HookWrapper for both, so a hooked function and a
|
||||
// hooked script behave the same way.
|
||||
namespace HookSecureFunc {
|
||||
|
||||
// The wrapper closure body. Upvalue 1 = the original, upvalue 2 = the hook.
|
||||
// Runs the original with the wrapper's args (its errors propagate), then the
|
||||
// hook with the same args under the engine's script error handler, and
|
||||
// returns the original's results. Exposed so readers can recognize the
|
||||
// closure by its C function.
|
||||
int __fastcall Wrapper(void *L);
|
||||
|
||||
// Pops the hook (top) and the original (below it) and pushes the wrapper
|
||||
// closure over them.
|
||||
void PushWrapper(void *L);
|
||||
|
||||
} // namespace HookSecureFunc
|
||||
+3893
-669
File diff suppressed because it is too large
Load Diff
+36
-41
@@ -12,42 +12,37 @@
|
||||
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
// `GetActionInfo(slot)` — modern-WoW-style action descriptor lookup.
|
||||
// Returns `actionType, id, subType` for the slot, or nil if empty.
|
||||
// Returns `actionType, id, subType` for the slot, or nothing if the slot
|
||||
// holds nothing the descriptor can describe (4.3.4 returns nothing there
|
||||
// too, rather than a nil).
|
||||
//
|
||||
// The vanilla 1.12.1 engine stores action descriptors as packed
|
||||
// uint32s in `VAR_ACTION_TABLE` (`0x00BC6980`, 120 slots). Top 4 bits
|
||||
// are the type tag; the `0x40000000` tag is ambiguous between
|
||||
// macros and bag-items and is disambiguated by checking the per-
|
||||
// character macro-slot map at `VAR_MACRO_SLOT_MAP` (36 entries).
|
||||
// are the type tag — the server's ACTION_BUTTON_* values shifted into the
|
||||
// top byte: 0x00 spell, 0x40 macro, 0x80 item.
|
||||
//
|
||||
// empty slot: nil
|
||||
// spell action: "spell", spellID, "spell"
|
||||
// macro: "macro", macroIndex (1-based)
|
||||
// bag item: "item", nil (see note below)
|
||||
// item-by-id: "item", itemID
|
||||
// item: "item", itemID
|
||||
// equipment set: "equipmentset", setName
|
||||
//
|
||||
// The subType is always "spell" for spell-type entries — the engine
|
||||
// helper hardcodes pet=0 for entries on this table. Pet-bar actions
|
||||
// live in a separate table; that's `PetHasActionBar` + the pet-action
|
||||
// helpers, not this function.
|
||||
//
|
||||
// The macro discriminator is the same trick SuperWoWhook uses in its
|
||||
// modified `GetActionText`: walk the 36-entry macro-slot map and check
|
||||
// whether `entry & 0xBFFFFFFF` matches one of those macro IDs. If yes,
|
||||
// the slot holds a macro; if no, it's a bag-item.
|
||||
//
|
||||
// **Bag-item itemID note.** For real bag items (top-4 bits = `0x4`
|
||||
// and the payload isn't in the macro-slot map), the engine stores a
|
||||
// bag-instance key, not the itemID. Resolving to itemID requires
|
||||
// walking the per-character action-item hash table at `[0x00BDCC54]`
|
||||
// and reading a struct field whose offset we haven't fully derived
|
||||
// yet. For now we report the action *type* ("item") but return nil
|
||||
// for the id. Callers that need it can fall back to
|
||||
// `GetActionTexture` + Lua-side item lookups.
|
||||
// A 0x40 entry is a macro only while its macroID is in the macro-slot map
|
||||
// (`FUN_ACTION_IS_MACRO`, which every engine reader gates its macro branch
|
||||
// on). One that is not — a macro deleted out from under its button — is
|
||||
// nothing, as in 4.3.4: its IsItem and IsMacro are both false, so it falls
|
||||
// through to an empty return. There is no bag-item tag: items are always
|
||||
// by-itemID (0x80), and an earlier reading of the 0x40 "miss" as a bag item
|
||||
// was wrong.
|
||||
|
||||
#include "Game.h"
|
||||
#include "Offsets.h"
|
||||
#include "action/Slot.h"
|
||||
#include "equipmentset/Data.h"
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
@@ -70,16 +65,12 @@ int __fastcall Script_GetActionInfo(void *L) {
|
||||
}
|
||||
|
||||
const int slot0 = static_cast<int>(Game::Lua::ToNumber(L, 1)) - 1;
|
||||
if (slot0 < 0 || slot0 >= Offsets::ACTION_TABLE_MAX_SLOTS) {
|
||||
Game::Lua::PushNil(L);
|
||||
return 1;
|
||||
}
|
||||
if (slot0 < 0 || slot0 >= Offsets::ACTION_TABLE_MAX_SLOTS)
|
||||
return 0;
|
||||
|
||||
const uint32_t entry = ReadEntry(slot0);
|
||||
if (entry == 0) {
|
||||
Game::Lua::PushNil(L);
|
||||
return 1;
|
||||
}
|
||||
if (entry == 0)
|
||||
return 0;
|
||||
|
||||
const uint32_t type = entry & Offsets::ACTION_TYPE_MASK;
|
||||
|
||||
@@ -92,10 +83,8 @@ int __fastcall Script_GetActionInfo(void *L) {
|
||||
static_cast<uintptr_t>(Offsets::FUN_ACTION_SLOT_TO_SPELL));
|
||||
uint32_t petFlag = 0;
|
||||
const uint32_t spellID = fn(static_cast<uint32_t>(slot0), &petFlag);
|
||||
if (spellID == 0) {
|
||||
Game::Lua::PushNil(L);
|
||||
return 1;
|
||||
}
|
||||
if (spellID == 0)
|
||||
return 0;
|
||||
(void)petFlag; // hardcoded 0 in the engine helper for this table
|
||||
Game::Lua::PushString(L, "spell");
|
||||
Game::Lua::PushNumber(L, static_cast<double>(spellID));
|
||||
@@ -111,12 +100,7 @@ int __fastcall Script_GetActionInfo(void *L) {
|
||||
Game::Lua::PushNumber(L, static_cast<double>(macroSlot));
|
||||
return 2;
|
||||
}
|
||||
// Not a macro — it's a bag item. We know the type but extracting
|
||||
// the itemID from the bag-instance hash needs more reversing;
|
||||
// see the file-level comment.
|
||||
Game::Lua::PushString(L, "item");
|
||||
Game::Lua::PushNil(L);
|
||||
return 2;
|
||||
return 0; // a macro button whose macro is gone — see the file comment
|
||||
}
|
||||
|
||||
if (type == Offsets::ACTION_TYPE_ITEM_BY_ID) {
|
||||
@@ -126,9 +110,20 @@ int __fastcall Script_GetActionInfo(void *L) {
|
||||
return 2;
|
||||
}
|
||||
|
||||
// Unknown type tag — surface as nil so callers don't get garbage.
|
||||
Game::Lua::PushNil(L);
|
||||
return 1;
|
||||
if (type == Offsets::ACTION_TYPE_EQUIPMENT_SET) {
|
||||
// 3.3.5 `Script_GetActionInfo` (`FUN_005a8f10`): the type and the
|
||||
// set's name.
|
||||
const EquipmentSet::Set *set = EquipmentSet::Data::FindByID(
|
||||
entry & ~static_cast<uint32_t>(Offsets::ACTION_TYPE_EQUIPMENT_SET));
|
||||
if (set == nullptr)
|
||||
return 0;
|
||||
Game::Lua::PushString(L, "equipmentset");
|
||||
Game::Lua::PushString(L, set->name.c_str());
|
||||
return 2;
|
||||
}
|
||||
|
||||
// Unknown type tag — nothing, so callers don't get garbage.
|
||||
return 0;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
// This file is part of ClassicAPI.
|
||||
//
|
||||
// ClassicAPI is free software: you can redistribute it and/or modify it under the terms
|
||||
// of the GNU 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 General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License along with
|
||||
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
// Dropping a spell on a slot that already holds it — 4.3.4's
|
||||
// CGActionBar::PutActionInSlot:
|
||||
//
|
||||
// else if (CGActionBar::IsSpell(slot) && CGActionBar::GetSpell(slot, petSpell) == spellId)
|
||||
// CGGameUI::DropCursorSpell();
|
||||
//
|
||||
// 1.12's FUN_ACTION_PLACE runs the same compare without the IsSpell gate,
|
||||
// and FUN_ACTION_SLOT_TO_SPELL resolves a macro slot to the macro's spell.
|
||||
// So a spell dropped on a `/cast <that spell>` macro was taken for a
|
||||
// duplicate: the cursor cleared and the macro stayed. The gate is one call
|
||||
// redirect: a slot that is not a spell action has no spell to match.
|
||||
|
||||
#include "Common.h"
|
||||
#include "Game.h"
|
||||
#include "Offsets.h"
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace Action::Place {
|
||||
|
||||
namespace {
|
||||
|
||||
using SlotToSpell_t = uint32_t(__fastcall *)(uint32_t slot0, uint32_t *outPetFlag);
|
||||
|
||||
uint32_t __fastcall SpellSlotSpell(uint32_t slot0, uint32_t *outPetFlag) {
|
||||
const uint32_t action = reinterpret_cast<const uint32_t *>(Offsets::VAR_ACTION_TABLE)[slot0];
|
||||
if (action == 0 || (action & Offsets::ACTION_TYPE_MASK) != Offsets::ACTION_TYPE_SPELL)
|
||||
return 0;
|
||||
return reinterpret_cast<SlotToSpell_t>(Offsets::FUN_ACTION_SLOT_TO_SPELL)(slot0, outPetFlag);
|
||||
}
|
||||
|
||||
void Register() {
|
||||
Common::RedirectCall(Offsets::CALL_ACTION_PLACE_SAME_SPELL, Offsets::FUN_ACTION_SLOT_TO_SPELL,
|
||||
reinterpret_cast<const void *>(&SpellSlotSpell));
|
||||
}
|
||||
|
||||
const Game::ModuleAutoRegister _autoreg{&Register};
|
||||
|
||||
} // namespace
|
||||
|
||||
} // namespace Action::Place
|
||||
+5
-7
@@ -20,13 +20,11 @@ namespace Action::Slot {
|
||||
int MacroSlotForID(uint32_t macroID) {
|
||||
if (macroID == 0)
|
||||
return 0;
|
||||
auto *map = reinterpret_cast<const uint32_t *>(
|
||||
static_cast<uintptr_t>(Offsets::VAR_MACRO_SLOT_MAP));
|
||||
for (int i = 0; i < Offsets::MACRO_SLOT_MAP_COUNT; ++i) {
|
||||
if (map[i] == macroID)
|
||||
return i + 1;
|
||||
}
|
||||
return 0;
|
||||
// The engine's own scan: the 0-based slot, or 0xFFFFFFFF on a miss.
|
||||
using IdToSlot_t = uint32_t(__fastcall *)(int macroID);
|
||||
const uint32_t slot0 = reinterpret_cast<IdToSlot_t>(
|
||||
static_cast<uintptr_t>(Offsets::FUN_MACRO_ID_TO_SLOT))(static_cast<int>(macroID));
|
||||
return slot0 == 0xFFFFFFFFu ? 0 : static_cast<int>(slot0) + 1;
|
||||
}
|
||||
|
||||
uint32_t MacroIDForSlot(int slot0) {
|
||||
|
||||
+4
-4
@@ -18,8 +18,9 @@
|
||||
// Action-slot ↔ macro decoding shared by every module that has to answer
|
||||
// "which macro sits in this action slot" (`GetActionInfo`, the
|
||||
// `#showtooltip` display overrides). The action table stores macroIDs under
|
||||
// the ambiguous `0x40000000` tag; the macro-slot map says which of those ids
|
||||
// are macros (the rest are bag items). Pure C — no Lua stack.
|
||||
// the `0x40000000` tag; the macro-slot map says which of those ids still
|
||||
// name a macro (the rest are buttons whose macro is gone). Pure C — no Lua
|
||||
// stack.
|
||||
|
||||
namespace Action::Slot {
|
||||
|
||||
@@ -29,8 +30,7 @@ namespace Action::Slot {
|
||||
int MacroSlotForID(uint32_t macroID);
|
||||
|
||||
// The macroID in action slot `slot0` (0-based, `< ACTION_TABLE_MAX_SLOTS`),
|
||||
// or 0 when the slot is empty, isn't `0x40000000`-tagged, or holds a bag
|
||||
// item rather than a macro.
|
||||
// or 0 when the slot is empty, isn't `0x40000000`-tagged, or its macro is gone.
|
||||
uint32_t MacroIDForSlot(int slot0);
|
||||
|
||||
} // namespace Action::Slot
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
// This file is part of ClassicAPI.
|
||||
//
|
||||
// ClassicAPI is free software: you can redistribute it and/or modify it under the terms
|
||||
// of the GNU 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 General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License along with
|
||||
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
// The `ActionButtonUseKeyDown` cvar — registered by 4.3.4's engine
|
||||
// (GameUI_CVar.cpp, "Activate the action button on a keydown") and read only
|
||||
// by FrameXML's action-button key handlers, which this project's addon ports
|
||||
// (Util/ActionButton.lua). The engine half is the registration. The default
|
||||
// is 0, keeping 1.12's action buttons firing on key release; 4.3.4 shipped 1.
|
||||
|
||||
#include "Game.h"
|
||||
#include "Offsets.h"
|
||||
#include "cvar/Factory.h"
|
||||
|
||||
namespace Action::UseKeyDown {
|
||||
|
||||
namespace {
|
||||
|
||||
void Register() {
|
||||
CVar::Factory::Register("ActionButtonUseKeyDown", "Activate the action button on a keydown",
|
||||
Offsets::CVAR_CATEGORY_GAME, "0");
|
||||
}
|
||||
|
||||
const Game::ModuleAutoRegister _autoreg{&Register};
|
||||
|
||||
} // namespace
|
||||
|
||||
} // namespace Action::UseKeyDown
|
||||
+83
-96
@@ -18,8 +18,8 @@
|
||||
// How:
|
||||
//
|
||||
// 1. The CMake build embeds every file under `AddOns/!!!ClassicAPI/`
|
||||
// into a generated header (`embedded_classicapi.h`) as a byte
|
||||
// array per file plus a `{path, data, size}` manifest.
|
||||
// as an RCDATA resource, plus a generated `{path, resourceId}`
|
||||
// manifest (`embedded_resources.h`).
|
||||
//
|
||||
// 2. We hook the engine's file-read function at `FUN_FILE_READ`.
|
||||
// When the engine asks for a path under
|
||||
@@ -28,14 +28,20 @@
|
||||
// embedded content in, and hand it back. The caller's normal
|
||||
// `SMemFree` reclaims it on completion — no special lifetime.
|
||||
//
|
||||
// 3. We post-hook the engine's `FUN_ADDON_INIT`. After the engine's
|
||||
// own `Interface\AddOns\` scan finishes, we call the TOC parser
|
||||
// directly with `"!!!ClassicAPI"`. The parser opens its TOC via
|
||||
// our hooked read function and registers the addon as a normal
|
||||
// entry. The TOC parser is dedup-safe: if the user already has
|
||||
// the addon on disk, the engine's scan picked it up, the
|
||||
// hash-table lookup hits, and our call is a no-op. So the
|
||||
// conditional "only if not on disk" behavior is free.
|
||||
// 3. We hook the exists-check `FUN_FILE_EXISTS` so it answers the same
|
||||
// way for the same paths. Without it every embedded file reads fine
|
||||
// but reports as missing — the per-addon loader would skip an
|
||||
// embedded `Bindings.xml`, and `Xml::ScriptPath` would never find an
|
||||
// embedded `<Script file="sub\x.lua">`.
|
||||
//
|
||||
// 4. We pre-hook the engine's `FUN_ADDON_SCAN_FULL` and call the TOC
|
||||
// parser with `"!!!ClassicAPI"` before the scan runs. The registry
|
||||
// is empty there (the login init resets it just before), so our
|
||||
// entry is the first record and the load pass — which walks the
|
||||
// records in registration order — loads it first. The scan's own
|
||||
// `## LoadWith:` pass then sees it like any disk addon. The parser
|
||||
// is dedup-safe: when the user also has the addon on disk, the
|
||||
// scan's call for that folder hits the hash table and is a no-op.
|
||||
//
|
||||
// Same pattern WeirdUtils.dll uses (we reverse-engineered it from
|
||||
// `0x10015A74` while figuring this out). The addon load pass then
|
||||
@@ -43,7 +49,7 @@
|
||||
// `Compat.lua`, `Util\Print.lua`, etc. all surface from
|
||||
// embedded buffers.
|
||||
|
||||
#include "embedded_classicapi.h"
|
||||
#include "embedded_resources.h"
|
||||
|
||||
#include "Game.h"
|
||||
#include "Offsets.h"
|
||||
@@ -54,6 +60,7 @@
|
||||
#include "addons/Toc.h"
|
||||
#include "addons/TocRewrite.h"
|
||||
#include "bindings/Inject.h"
|
||||
#include "embed/Resource.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
@@ -109,23 +116,27 @@ const char *StripAddonPrefix(const char *path) {
|
||||
return p;
|
||||
}
|
||||
|
||||
const ClassicAPIFiles::File *LookupEmbedded(const char *suffix) {
|
||||
// The embedded bytes for `suffix`; `data` is NULL when it is not embedded.
|
||||
Embed::Bytes LookupEmbedded(const char *suffix) {
|
||||
for (size_t i = 0; i < ClassicAPIFiles::kFileCount; ++i) {
|
||||
if (PathEqualsCI(suffix, ClassicAPIFiles::kFiles[i].path))
|
||||
return &ClassicAPIFiles::kFiles[i];
|
||||
return Embed::Resource(ClassicAPIFiles::kFiles[i].resourceId);
|
||||
}
|
||||
return nullptr;
|
||||
return {nullptr, 0};
|
||||
}
|
||||
|
||||
// Engine file I/O + Storm allocator — see addons/EngineIO.h for the shapes and
|
||||
// the __stdcall / ESP-drift hazard. A buffer we SMemAlloc here is freed cleanly
|
||||
// by the caller's standard SMemFree in turn.
|
||||
using AddOns::EngineIO::FileExistsFn;
|
||||
using AddOns::EngineIO::FileReadFn;
|
||||
using AddOns::EngineIO::SMemAllocFn;
|
||||
using AddOns::EngineIO::SMemFreeFn;
|
||||
|
||||
// The trampoline to the original FUN_FILE_READ (installed by the co-hook below).
|
||||
// The trampolines to the original FUN_FILE_READ / FUN_FILE_EXISTS (installed
|
||||
// by the co-hooks below).
|
||||
FileReadFn FileRead_o = nullptr;
|
||||
FileExistsFn FileExists_o = nullptr;
|
||||
|
||||
// Extracts the value of the `## Version: X` line from a TOC byte
|
||||
// buffer. Writes into `out` (size `outSize`) and returns true on
|
||||
@@ -137,7 +148,7 @@ bool ExtractTocVersion(const char *content, size_t size,
|
||||
size_t n = 0;
|
||||
if (outSize == 0)
|
||||
return false;
|
||||
if (!AddOns::Toc::FindValue(content, size, "## Version:", &v, &n) || n == 0) {
|
||||
if (!AddOns::Toc::FindValue(content, size, "Version", &v, &n) || n == 0) {
|
||||
out[0] = '\0';
|
||||
return false;
|
||||
}
|
||||
@@ -187,19 +198,14 @@ Source g_source = Source::Undecided;
|
||||
|
||||
void EnsureEmbeddedVersionExtracted() {
|
||||
if (g_embeddedVersion[0] != '\0') return;
|
||||
for (size_t i = 0; i < ClassicAPIFiles::kFileCount; ++i) {
|
||||
if (PathEqualsCI(kAddonTocFile, ClassicAPIFiles::kFiles[i].path)) {
|
||||
ExtractTocVersion(
|
||||
reinterpret_cast<const char *>(ClassicAPIFiles::kFiles[i].data),
|
||||
ClassicAPIFiles::kFiles[i].size,
|
||||
g_embeddedVersion, sizeof(g_embeddedVersion));
|
||||
return;
|
||||
}
|
||||
}
|
||||
const Embed::Bytes toc = LookupEmbedded(kAddonTocFile);
|
||||
if (toc.data != nullptr)
|
||||
ExtractTocVersion(reinterpret_cast<const char *>(toc.data), toc.size,
|
||||
g_embeddedVersion, sizeof(g_embeddedVersion));
|
||||
}
|
||||
|
||||
// True iff the on-disk addon folder contains the `.classicapi-dev`
|
||||
// marker. Read via the ORIGINAL `FUN_FILE_READ` (bypassing our embed
|
||||
// marker. Asked of the ORIGINAL `FUN_FILE_EXISTS` (bypassing our embed
|
||||
// hook), so it reflects a real file on disk / in an MPQ — never an
|
||||
// embedded copy. That makes it a clean "is this a developer working
|
||||
// tree" signal: the marker is gitignored + excluded from the embed and
|
||||
@@ -209,14 +215,7 @@ bool DiskHasDevMarker() {
|
||||
char fullPath[256];
|
||||
std::snprintf(fullPath, sizeof(fullPath), "%s%s",
|
||||
kAddonPathPrefix, kDevMarkerFile);
|
||||
void *buf = nullptr;
|
||||
size_t size = 0;
|
||||
const int ok = FileRead_o(0, fullPath, &buf, &size, 1, 1, 0);
|
||||
if (ok == 0 || buf == nullptr)
|
||||
return false;
|
||||
auto SMemFree = reinterpret_cast<SMemFreeFn>(Offsets::FUN_STORM_SMEM_FREE);
|
||||
SMemFree(buf, __FILE__, __LINE__, 0);
|
||||
return true;
|
||||
return FileExists_o(fullPath, 1) != 0;
|
||||
}
|
||||
|
||||
// Decide whether disk or embedded should serve all reads for this
|
||||
@@ -329,8 +328,8 @@ int __stdcall FileRead_h(int unused, const char *path, void **outBuf,
|
||||
// Source::Embedded path, OR Source::Disk-but-file-missing fallback.
|
||||
// Look up the embedded version and synthesize a Storm buffer the
|
||||
// caller can free normally.
|
||||
const auto *entry = LookupEmbedded(suffix);
|
||||
if (entry == nullptr) {
|
||||
const Embed::Bytes entry = LookupEmbedded(suffix);
|
||||
if (entry.data == nullptr) {
|
||||
// Not in our embedded set either — let the engine try disk
|
||||
// one more time (returns 0 if that also fails). Covers
|
||||
// pathological cases like an empty disk install + embedded
|
||||
@@ -341,48 +340,46 @@ int __stdcall FileRead_h(int unused, const char *path, void **outBuf,
|
||||
|
||||
auto SMemAlloc = reinterpret_cast<SMemAllocFn>(
|
||||
Offsets::FUN_STORM_SMEM_ALLOC);
|
||||
const size_t totalSize = entry->size + extraBytes;
|
||||
const size_t totalSize = entry.size + extraBytes;
|
||||
void *buf = SMemAlloc(totalSize, __FILE__, __LINE__, 0);
|
||||
if (buf == nullptr) return 0;
|
||||
std::memcpy(buf, entry->data, entry->size);
|
||||
std::memcpy(buf, entry.data, entry.size);
|
||||
if (extraBytes > 0) {
|
||||
std::memset(static_cast<uint8_t *>(buf) + entry->size, 0, extraBytes);
|
||||
std::memset(static_cast<uint8_t *>(buf) + entry.size, 0, extraBytes);
|
||||
}
|
||||
if (outBuf != nullptr) *outBuf = buf;
|
||||
if (outSize != nullptr) *outSize = entry->size;
|
||||
if (outSize != nullptr) *outSize = entry.size;
|
||||
return 1;
|
||||
}
|
||||
|
||||
// `FUN_ADDON_INIT` — `__fastcall(accountName)`. We post-hook it: let
|
||||
// the engine's normal `Interface\AddOns\` scan run first, then call
|
||||
// the TOC parser with `"!!!ClassicAPI"`. Dedup-safe — see file header.
|
||||
using AddonInit_t = void(__fastcall *)(const char *accountName);
|
||||
AddonInit_t AddonInit_o = nullptr;
|
||||
// The exists-check counterpart of FileRead_h: the same source decision and
|
||||
// the same fallbacks, so a path reports as existing exactly when FileRead_h
|
||||
// would serve it. Other paths go to FlavorBindings (flavor-only addon
|
||||
// Bindings.xml), then to the original.
|
||||
int __stdcall FileExists_h(const char *path, int mode) {
|
||||
const char *suffix = StripAddonPrefix(path);
|
||||
if (suffix == nullptr) {
|
||||
if (FileExists_o(path, mode) != 0)
|
||||
return 1;
|
||||
return AddOns::FlavorBindings::TryExists(path, mode, FileExists_o) ? 1 : 0;
|
||||
}
|
||||
|
||||
DecideSource();
|
||||
if (g_source == Source::Disk && FileExists_o(path, mode) != 0)
|
||||
return 1;
|
||||
if (LookupEmbedded(suffix).data != nullptr)
|
||||
return 1;
|
||||
return FileExists_o(path, mode);
|
||||
}
|
||||
|
||||
// `FUN_ADDON_SCAN_FULL` — `void __cdecl()`. We pre-hook it: register
|
||||
// `"!!!ClassicAPI"` into the empty registry, then let the engine's scan
|
||||
// run. Dedup-safe — see file header.
|
||||
using AddonScan_t = void(__cdecl *)();
|
||||
AddonScan_t AddonScan_o = nullptr;
|
||||
|
||||
using TocParser_t = void(__fastcall *)(const char *name);
|
||||
using ListInsert_t = void(__thiscall *)(void *listCtrl, void *entry,
|
||||
int position, int anchor);
|
||||
|
||||
// `FUN_TOC_PARSER` appends new entries to the *tail* of the addon
|
||||
// registry's linked list, and the engine's addon-load pass at
|
||||
// `FUN_0051F600` walks that list in *insertion order* (NOT
|
||||
// alphabetical order — the alphabetical sort only applies to the
|
||||
// flat array `GetAddOnInfo(i)` reads from). So our post-hook
|
||||
// injection lands at the very end of the load order, after every
|
||||
// disk-scanned addon. Addons that consume our globals from their
|
||||
// main chunk (idTip's `FrameWatcher`, etc.) would see `nil` and
|
||||
// hard-error during their boot.
|
||||
//
|
||||
// Fix: walk the linked list, find our entry by name, and re-link
|
||||
// it to the head via `FUN_INTRUSIVE_LIST_INSERT(position=1)`. The
|
||||
// engine's own insert helper handles remove-then-insert atomically,
|
||||
// so it's safe to call on an entry that's already in the list.
|
||||
//
|
||||
// The list is walked via the shared `Addons::ForEachEntry`
|
||||
// (`addons/Registry.h`); the callback stops the walk once it finds and
|
||||
// re-links our entry, since the re-link invalidates the current
|
||||
// next-pointer.
|
||||
//
|
||||
// `entry + OFF_ADDON_ENTRY_FILTER_OUT` is the "filter-out" byte. The
|
||||
// flat display-array builder `FUN_0051da70` walks the linked list and
|
||||
// copies an entry into `GetNumAddOns`/`GetAddOnInfo`'s array ONLY when
|
||||
@@ -394,19 +391,14 @@ using ListInsert_t = void(__thiscall *)(void *listCtrl, void *entry,
|
||||
// loading (the load pass `FUN_0051f600` never reads `+0x29`) and does
|
||||
// NOT break dependency resolution or by-name queries (those use the
|
||||
// addon hash table, which keeps the entry regardless).
|
||||
//
|
||||
// DefaultState (`+0x2b`) needs no write: the entry constructor
|
||||
// `FUN_00520550` stores 1 there, our toc has no `## DefaultState:`, and
|
||||
// the resolver co-hook below forces enabled anyway.
|
||||
|
||||
// `entry+0x2b` — DefaultState (`## DefaultState: enabled/disabled`).
|
||||
// The enable resolver `FUN_ADDON_ENABLE_RESOLVE` falls back to this
|
||||
// when the player has no per-character override. Belt-and-suspenders
|
||||
// alongside the resolver co-hook below (which forces enabled anyway).
|
||||
constexpr int OFF_ADDON_ENTRY_DEFAULT_STATE = 0x2b;
|
||||
|
||||
// Post-registration finalize for the embedded entry: move it to the
|
||||
// head of the load-order list (so consumers that read our globals from
|
||||
// their main chunk see them — see the block comment above the offsets),
|
||||
// hide it from the addon list, and mark it default-enabled. Combined
|
||||
// with the `FUN_ADDON_ENABLE_RESOLVE` co-hook, `!!!ClassicAPI` always
|
||||
// loads and never appears as a toggleable entry.
|
||||
// Post-registration finalize for the embedded entry: hide it from the
|
||||
// addon list. Combined with the `FUN_ADDON_ENABLE_RESOLVE` co-hook,
|
||||
// `!!!ClassicAPI` always loads and never appears as a toggleable entry.
|
||||
void FinalizeEmbeddedEntry() {
|
||||
Addons::ForEachEntry([](uintptr_t entry) -> bool {
|
||||
const char *name = *reinterpret_cast<const char *const *>(
|
||||
@@ -414,27 +406,17 @@ void FinalizeEmbeddedEntry() {
|
||||
if (name == nullptr || std::strcmp(name, kAddonName) != 0)
|
||||
return true; // keep walking
|
||||
|
||||
// Hide from the character-select AddOns list and default it to
|
||||
// enabled, then move it to the head of the load order.
|
||||
*reinterpret_cast<uint8_t *>(
|
||||
entry + Offsets::OFF_ADDON_ENTRY_FILTER_OUT) = 1;
|
||||
*reinterpret_cast<uint8_t *>(entry + OFF_ADDON_ENTRY_DEFAULT_STATE) = 1;
|
||||
|
||||
auto fn = reinterpret_cast<ListInsert_t>(
|
||||
Offsets::FUN_INTRUSIVE_LIST_INSERT);
|
||||
fn(reinterpret_cast<void *>(
|
||||
static_cast<uintptr_t>(Offsets::VAR_ADDON_LIST_CTRL)),
|
||||
reinterpret_cast<void *>(entry),
|
||||
/*position=*/ 1, /*anchor=*/ 0);
|
||||
return false; // stop — the re-link invalidated our next-pointer
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
void __fastcall AddonInit_h(const char *accountName) {
|
||||
AddonInit_o(accountName);
|
||||
void __cdecl AddonScan_h() {
|
||||
auto TocParser = reinterpret_cast<TocParser_t>(Offsets::FUN_TOC_PARSER);
|
||||
TocParser(kAddonName);
|
||||
FinalizeEmbeddedEntry();
|
||||
AddonScan_o();
|
||||
}
|
||||
|
||||
// `FUN_ADDON_ENABLE_RESOLVE` — per-character enable resolver. We
|
||||
@@ -459,10 +441,15 @@ const Game::HookAutoRegister _hookFileRead{
|
||||
reinterpret_cast<void *>(&FileRead_h),
|
||||
reinterpret_cast<void **>(&FileRead_o)};
|
||||
|
||||
const Game::HookAutoRegister _hookAddonInit{
|
||||
Offsets::FUN_ADDON_INIT,
|
||||
reinterpret_cast<void *>(&AddonInit_h),
|
||||
reinterpret_cast<void **>(&AddonInit_o)};
|
||||
const Game::HookAutoRegister _hookFileExists{
|
||||
Offsets::FUN_FILE_EXISTS,
|
||||
reinterpret_cast<void *>(&FileExists_h),
|
||||
reinterpret_cast<void **>(&FileExists_o)};
|
||||
|
||||
const Game::HookAutoRegister _hookAddonScan{
|
||||
Offsets::FUN_ADDON_SCAN_FULL,
|
||||
reinterpret_cast<void *>(&AddonScan_h),
|
||||
reinterpret_cast<void **>(&AddonScan_o)};
|
||||
|
||||
const Game::HookAutoRegister _hookEnableResolve{
|
||||
Offsets::FUN_ADDON_ENABLE_RESOLVE,
|
||||
|
||||
@@ -15,8 +15,6 @@
|
||||
#include "addons/FlavorBindings.h"
|
||||
#include "addons/Toc.h"
|
||||
|
||||
#include "Game.h"
|
||||
#include "Offsets.h"
|
||||
#include "turtle/Detect.h"
|
||||
|
||||
#include <cstddef>
|
||||
@@ -72,40 +70,24 @@ int FlavorOrder(const char *(&order)[2]) {
|
||||
return count;
|
||||
}
|
||||
|
||||
// Engine file-exists probe FUN_00648a30 — __stdcall(path, mode) (RET 8).
|
||||
using EngineIO::FileExistsFn;
|
||||
FileExistsFn g_origExists = nullptr;
|
||||
} // namespace
|
||||
|
||||
// Co-hook the exists-check so `Interface\AddOns\<Name>\Bindings.xml` reports as
|
||||
// existing when the base file is absent but a flavor variant is present — so
|
||||
// the loader (`FUN_004b6f70`, then our TryHandle redirect) runs for a
|
||||
// flavor-only addon. Every non-Bindings path passes straight through.
|
||||
int __stdcall FileExists_h(const char *path, int mode) {
|
||||
bool TryExists(const char *path, int mode, FileExistsFn orig) {
|
||||
const size_t prefixLen = AddonBindingsPrefix(path);
|
||||
if (prefixLen == NPOS)
|
||||
return g_origExists(path, mode);
|
||||
|
||||
if (g_origExists(path, mode) != 0)
|
||||
return 1; // the plain Bindings.xml exists
|
||||
return false;
|
||||
|
||||
const char *order[2];
|
||||
const int count = FlavorOrder(order);
|
||||
char cand[512];
|
||||
for (int i = 0; i < count; ++i) {
|
||||
if (BuildFlavorPath(path, prefixLen, order[i], cand, sizeof cand) &&
|
||||
g_origExists(cand, mode) != 0)
|
||||
return 1;
|
||||
orig(cand, mode) != 0)
|
||||
return true;
|
||||
}
|
||||
return 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
const Game::HookAutoRegister _hookExists{
|
||||
Offsets::FUN_FILE_EXISTS,
|
||||
reinterpret_cast<void *>(&FileExists_h),
|
||||
reinterpret_cast<void **>(&g_origExists)};
|
||||
|
||||
} // namespace
|
||||
|
||||
bool TryHandle(int unused, const char *path, void **outBuf, size_t *outSize,
|
||||
size_t extraBytes, int flag1, int flag2, FileReadFn orig) {
|
||||
const size_t prefixLen = AddonBindingsPrefix(path);
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
|
||||
namespace AddOns::FlavorBindings {
|
||||
|
||||
using EngineIO::FileExistsFn;
|
||||
using EngineIO::FileReadFn;
|
||||
|
||||
// Flavor-specific addon Bindings selection — the Bindings.xml analog of
|
||||
@@ -36,10 +37,10 @@ using EngineIO::FileReadFn;
|
||||
// place if one exists (a selected flavor wins over a plain `Bindings.xml`,
|
||||
// matching FlavorToc). Probe order `Bindings_Turtle.xml` (only when
|
||||
// Turtle::Detected) then `Bindings_ClassicAPI.xml`.
|
||||
// 2. A co-hook on the exists-check `FUN_00648a30` (inside FlavorBindings.cpp):
|
||||
// report `Bindings.xml` as existing when the base is absent but a flavor
|
||||
// variant is present — otherwise the loader is never called for a
|
||||
// flavor-only addon.
|
||||
// 2. TryExists, called from the exists-check `FUN_FILE_EXISTS` hook: report
|
||||
// `Bindings.xml` as existing when the base is absent but a flavor variant
|
||||
// is present — otherwise the loader is never called for a flavor-only
|
||||
// addon.
|
||||
//
|
||||
// Only `_Turtle` / `_ClassicAPI` are selected — never `_Vanilla` / `_Classic`
|
||||
// (which target the 1.15 Classic Era build; its bindings reference handlers
|
||||
@@ -52,4 +53,9 @@ using EngineIO::FileReadFn;
|
||||
bool TryHandle(int unused, const char *path, void **outBuf, size_t *outSize,
|
||||
size_t extraBytes, int flag1, int flag2, FileReadFn orig);
|
||||
|
||||
// True when `path` is an addon `…\AddOns\<Name>\Bindings.xml` and a flavor
|
||||
// variant exists through `orig` (the original exists-check). The caller asks
|
||||
// `orig` about the base path itself; this answers only the flavor case.
|
||||
bool TryExists(const char *path, int mode, FileExistsFn orig);
|
||||
|
||||
} // namespace AddOns::FlavorBindings
|
||||
|
||||
+86
-34
@@ -35,6 +35,7 @@ namespace AddOns::Info {
|
||||
namespace {
|
||||
|
||||
using GetByIndex_t = void *(__fastcall *)(int idx0Based);
|
||||
using GetAddOnCount_t = int(__fastcall *)();
|
||||
using FieldByName_t = const char *(__fastcall *)(const char *name);
|
||||
using EntryByteFn_t = uint8_t(__fastcall *)(const uint8_t *entry);
|
||||
using GetSecurityIndex_t = uint32_t(__fastcall *)(const uint8_t *entry);
|
||||
@@ -45,7 +46,7 @@ using GetAccountName_t = const char *(*)();
|
||||
// Hash-lookup by name → the matched record's RequiredDeps descriptor
|
||||
// (`record + 0x48`), NULL on miss. Accepts an entry pointer too (its
|
||||
// first bytes are the inline name). We use it only to recover the
|
||||
// record base for string input; see `Script_GetAddOnOptionalDependencies`.
|
||||
// record base; see `Script_GetAddOnOptionalDependencies`.
|
||||
using ResolveReqDeps_t = uint8_t *(__fastcall *)(const char *nameOrEntry);
|
||||
|
||||
// Resolves the user's arg to a `const uint8_t *` that the engine's
|
||||
@@ -308,49 +309,66 @@ int __fastcall Script_DoesAddOnExist(void *L) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Resolves arg 1 to the addon's registry record, with the arg handling
|
||||
// of stock `Script_GetAddOnDependencies` (`0x0048E5E0`, identical to
|
||||
// 4.3.4's `Script_GetAddOnOptionalDependencies`), not `ResolveAddOnName`:
|
||||
// `lua_isnumber` first (so a numeric string like `"3"` is an index), an
|
||||
// out-of-range index raises the engine's own range error with the addon
|
||||
// count, anything else non-string raises `usage`, and an unknown *name*
|
||||
// returns nullptr with no error.
|
||||
//
|
||||
// Either input is then routed through the by-name hash lookup
|
||||
// `FUN_ADDON_RESOLVE_REQ_DEPS` to reach the record.
|
||||
// `FUN_ADDON_GET_BY_INDEX` returns a *name pointer*, NOT the record —
|
||||
// reading record offsets off it lands in string memory and crashes (a
|
||||
// numeric-path caller like pfUI's addon list hit exactly that). The
|
||||
// resolver returns the RequiredDeps descriptor at `record+0x48`;
|
||||
// subtract to recover the base.
|
||||
const uint8_t *ResolveRecord(void *L, const char *usage) {
|
||||
const char *name;
|
||||
if (Game::Lua::IsNumber(L, 1)) {
|
||||
const int idx = static_cast<int>(Game::Lua::ToNumber(L, 1)) - 1;
|
||||
auto byIndex = reinterpret_cast<GetByIndex_t>(Offsets::FUN_ADDON_GET_BY_INDEX);
|
||||
name = static_cast<const char *>(byIndex(idx));
|
||||
if (name == nullptr) {
|
||||
auto count = reinterpret_cast<GetAddOnCount_t>(Offsets::FUN_ADDON_GET_COUNT);
|
||||
Game::Lua::Error(L, reinterpret_cast<const char *>(static_cast<uintptr_t>(
|
||||
Offsets::VAR_ADDON_INDEX_RANGE_ERROR_FMT)),
|
||||
count());
|
||||
return nullptr;
|
||||
}
|
||||
} else if (Game::Lua::IsString(L, 1)) {
|
||||
name = Game::Lua::ToString(L, 1);
|
||||
} else {
|
||||
Game::Lua::Error(L, usage);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
auto resolve = reinterpret_cast<ResolveReqDeps_t>(
|
||||
Offsets::FUN_ADDON_RESOLVE_REQ_DEPS);
|
||||
uint8_t *reqDesc = resolve(name);
|
||||
if (reqDesc == nullptr)
|
||||
return nullptr;
|
||||
return reqDesc - Offsets::OFF_ADDON_REQDEPS_DESC;
|
||||
}
|
||||
|
||||
// `C_AddOns.GetAddOnOptionalDependencies(indexOrName)` — the addon's
|
||||
// `## OptionalDeps:` names as multiple return values, in declared order.
|
||||
// The exact shape of the stock `GetAddOnDependencies`, but reading the
|
||||
// *optional* dep array instead of the required one. No optional deps →
|
||||
// returns nothing.
|
||||
// *optional* dep array instead of the required one. No optional deps or
|
||||
// an unknown name → returns nothing.
|
||||
//
|
||||
// Vanilla parses `## OptionalDeps:` in the TOC parser `FUN_0051c9b0`
|
||||
// into a `{cap, count, data, quantum}` name-array descriptor at
|
||||
// `record+0x38` (count@+0x3C, data@+0x40), but ships no getter for it.
|
||||
//
|
||||
// Arg/error handling mirrors stock `Script_GetAddOnDependencies`
|
||||
// (`0x0048E5E0`): numeric out-of-range or a non-string/non-number arg
|
||||
// raises the usage error; an unknown *name* string returns nothing
|
||||
// (no error), matching the engine's own not-found path.
|
||||
//
|
||||
// Resolution mirrors stock `Script_GetAddOnDependencies` exactly: the
|
||||
// arg is first turned into a name-usable pointer (`ResolveAddOnName` —
|
||||
// numeric via `FUN_ADDON_GET_BY_INDEX`, string is the raw string), then
|
||||
// routed through the by-name hash lookup `FUN_ADDON_RESOLVE_REQ_DEPS`
|
||||
// to reach the deps-bearing record. `FUN_ADDON_GET_BY_INDEX` returns a
|
||||
// *name pointer*, NOT the record — reading dep offsets off it lands in
|
||||
// string memory and crashes (a numeric-path caller like pfUI's addon
|
||||
// list hit exactly that). The resolver returns the RequiredDeps
|
||||
// descriptor at `record+0x48`; subtract to recover the base. An unknown
|
||||
// name yields NULL → return nothing (no error), like stock.
|
||||
// Like stock, `lua_checkstack(count)` before the pushes — a C function
|
||||
// is only guaranteed LUA_MINSTACK (20) free slots.
|
||||
int __fastcall Script_GetAddOnOptionalDependencies(void *L) {
|
||||
static constexpr const char *kUsage =
|
||||
"Usage: C_AddOns.GetAddOnOptionalDependencies(index or \"name\")";
|
||||
|
||||
// NULL ⇒ out-of-range numeric index or a non-string/non-number arg;
|
||||
// stock raises the usage error in both cases.
|
||||
const uint8_t *nameOrEntry = ResolveAddOnName(L);
|
||||
if (nameOrEntry == nullptr) {
|
||||
Game::Lua::Error(L, "%s", kUsage);
|
||||
const uint8_t *record = ResolveRecord(
|
||||
L, "Usage: C_AddOns.GetAddOnOptionalDependencies(index or \"name\")");
|
||||
if (record == nullptr)
|
||||
return 0;
|
||||
}
|
||||
|
||||
auto resolve = reinterpret_cast<ResolveReqDeps_t>(
|
||||
Offsets::FUN_ADDON_RESOLVE_REQ_DEPS);
|
||||
uint8_t *reqDesc = resolve(reinterpret_cast<const char *>(nameOrEntry));
|
||||
if (reqDesc == nullptr)
|
||||
return 0; // unknown addon name — no error, push nothing
|
||||
const uint8_t *record = reqDesc - Offsets::OFF_ADDON_REQDEPS_DESC;
|
||||
|
||||
const uint32_t count = *reinterpret_cast<const uint32_t *>(
|
||||
record + Offsets::OFF_ADDON_OPTIONALDEPS_COUNT);
|
||||
@@ -360,11 +378,30 @@ int __fastcall Script_GetAddOnOptionalDependencies(void *L) {
|
||||
record + Offsets::OFF_ADDON_OPTIONALDEPS_ARRAY);
|
||||
if (names == nullptr)
|
||||
return 0;
|
||||
Game::Lua::CheckStack(L, static_cast<int>(count));
|
||||
for (uint32_t i = 0; i < count; ++i)
|
||||
Game::Lua::PushString(L, names[i]); // NULL → pushnil, per engine
|
||||
return static_cast<int>(count);
|
||||
}
|
||||
|
||||
// `C_AddOns.GetAddOnInterfaceVersion(indexOrName)` — the `## Interface:`
|
||||
// number the engine parsed into `record+0x1C`, the same value its
|
||||
// loadability check compares against the client version. A comma-list
|
||||
// is already reduced to retail's pick (closest value at or below the
|
||||
// client version) by `AddOns::TocRewrite` before the parser sees it.
|
||||
// nil for an unknown name.
|
||||
int __fastcall Script_GetAddOnInterfaceVersion(void *L) {
|
||||
const uint8_t *record = ResolveRecord(
|
||||
L, "Usage: C_AddOns.GetAddOnInterfaceVersion(index or \"name\")");
|
||||
if (record == nullptr) {
|
||||
Game::Lua::PushNil(L);
|
||||
return 1;
|
||||
}
|
||||
Game::Lua::PushNumber(L, static_cast<double>(*reinterpret_cast<const uint32_t *>(
|
||||
record + Offsets::OFF_ADDON_INTERFACE_VERSION)));
|
||||
return 1;
|
||||
}
|
||||
|
||||
// `Enum.AddOnSecurityStatus` — what `C_AddOns.GetAddOnSecurity`
|
||||
// returns. Slots 0..2 match the engine's own ordering at
|
||||
// `VAR_ADDON_SECURITY_TABLE`; slot 3 is our addition for
|
||||
@@ -376,6 +413,18 @@ constexpr Game::Lua::EnumIntegerEntry kAddOnSecurityStatusEntries[] = {
|
||||
{"NotAvailable", 3},
|
||||
};
|
||||
|
||||
const Game::Doc::Field kInterfaceVersionArgs[] = {
|
||||
Game::Doc::Req("name", "uiAddon", "An addon index or folder name."),
|
||||
};
|
||||
const Game::Doc::Field kInterfaceVersionRets[] = {
|
||||
Game::Doc::Opt("interfaceVersion", "number", nullptr,
|
||||
"The ## Interface: value from the TOC, or nil for an unknown name."),
|
||||
};
|
||||
const Game::Doc::Function kGetAddOnInterfaceVersion{
|
||||
"Returns the Interface directive of an addon TOC. For a comma-separated list, "
|
||||
"returns the closest value at or below the client interface version.",
|
||||
kInterfaceVersionArgs, kInterfaceVersionRets};
|
||||
|
||||
} // namespace
|
||||
|
||||
static void RegisterLuaFunctions() {
|
||||
@@ -401,6 +450,9 @@ static void RegisterLuaFunctions() {
|
||||
static_cast<uintptr_t>(Offsets::FUN_SCRIPT_LOAD_ADDON)));
|
||||
Game::Lua::RegisterTableFunction("C_AddOns", "GetAddOnOptionalDependencies",
|
||||
&Script_GetAddOnOptionalDependencies);
|
||||
Game::Lua::RegisterTableFunction("C_AddOns", "GetAddOnInterfaceVersion",
|
||||
&Script_GetAddOnInterfaceVersion,
|
||||
&kGetAddOnInterfaceVersion);
|
||||
Game::Lua::RegisterIntegerEnum(
|
||||
"Enum", "AddOnSecurityStatus",
|
||||
kAddOnSecurityStatusEntries,
|
||||
|
||||
@@ -12,17 +12,17 @@
|
||||
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
// `C_AddOns.GetAddOnLocalTable(name)` — the public, gated view of an addon's
|
||||
// private namespace table (the `local _, addonTable = ...` second vararg the
|
||||
// transpiler injects; see luasyntax/AddonNamespace.h).
|
||||
// private namespace table (the `local _, addonTable = ...` second vararg each
|
||||
// addon file is called with; see luasyntax/AddonNamespace.h).
|
||||
//
|
||||
// Retail added this in 11.0 alongside the `## AllowAddOnTableAccess` TOC
|
||||
// directive: one addon can read another's local table ONLY when the target
|
||||
// opts in. We mirror that gate:
|
||||
// 1. the named addon is currently LOADED, and
|
||||
// 2. its `.toc` declares `## AllowAddOnTableAccess: 1`.
|
||||
// Either check failing returns nil. The internal preamble path (an addon
|
||||
// receiving its OWN table) is a different, ungated function (`__addonns`) —
|
||||
// an addon never needs permission for its own namespace.
|
||||
// Either check failing returns nil. An addon receiving its OWN table is a
|
||||
// different, ungated path (its files are called with it at load) — an addon
|
||||
// never needs permission for its own namespace.
|
||||
//
|
||||
// Directive spelling verified against the 1.15.8 Classic Era binary (both the
|
||||
// `AllowAddOnTableAccess:` TOC key and the `GetAddOnLocalTable` name are
|
||||
@@ -77,7 +77,7 @@ bool TocAllowsTableAccess(const char *name) {
|
||||
size_t n = 0;
|
||||
bool allowed = false;
|
||||
if (AddOns::Toc::FindValue(static_cast<const char *>(buf), size,
|
||||
"## AllowAddOnTableAccess:", &v, &n)) {
|
||||
"AllowAddOnTableAccess", &v, &n)) {
|
||||
int value = 0;
|
||||
bool anyDigit = false;
|
||||
for (size_t k = 0; k < n && v[k] >= '0' && v[k] <= '9'; ++k) {
|
||||
|
||||
@@ -27,10 +27,10 @@ namespace Addons {
|
||||
// engine's own load pass (`FUN_0051F600`) and scan tail loop use.
|
||||
//
|
||||
// `fn` may return `void` (always continue) or `bool` (return `false` to STOP
|
||||
// early). Early stop is load-bearing for a visitor that mutates the list —
|
||||
// e.g. re-linking an entry to the head invalidates the current next-pointer,
|
||||
// so the walk must not follow it. Shared by `Addons::Embedded` (find + re-link
|
||||
// the embedded entry) and `Addons::Rescan` (snapshot / diff / fix-up passes).
|
||||
// early, e.g. once a by-name search finds its entry). A visitor must not
|
||||
// unlink the entry it is given and then continue: the walk reads that
|
||||
// entry's next-pointer after the call. Shared by `Addons::Embedded` (find the
|
||||
// embedded entry) and `Addons::Rescan` (snapshot / diff / fix-up passes).
|
||||
template <typename Fn> void ForEachEntry(Fn fn) {
|
||||
const int linkOffset = *reinterpret_cast<const int *>(
|
||||
static_cast<uintptr_t>(Offsets::VAR_ADDON_LIST_CTRL));
|
||||
|
||||
+25
-67
@@ -16,16 +16,15 @@
|
||||
// a stock 1.12 client, each fixed here with the engine's own machinery:
|
||||
//
|
||||
// 1. FILE VISIBILITY. Every relative-path read resolves through a
|
||||
// loose-file hash index built ONCE at boot (see Offsets.h,
|
||||
// `FUN_VFS_INDEX_SUBTREE`); files created after boot — a new
|
||||
// addon's TOC, a new .lua in an existing addon, a freshly written
|
||||
// SavedVariables file — are invisible until restart. The boot
|
||||
// indexer is dedup-safe and works on subtrees, so we re-run it per
|
||||
// /reload on the only two subtrees whose contents can change what
|
||||
// a /reload loads: `Interface\AddOns` and `WTF\Account`. New files
|
||||
// in EXISTING addons need nothing more — the per-addon loader
|
||||
// `FUN_0051F240` re-reads the TOC from disk on every load pass, so
|
||||
// once the files are visible they load.
|
||||
// loose-file hash index (see Offsets.h, `FUN_VFS_INDEX_CLEAR`);
|
||||
// a file created after the index was built — a new addon's TOC, a
|
||||
// new .lua in an existing addon — is invisible until it is rebuilt.
|
||||
// We call the engine's own clear, the same one the engine calls
|
||||
// after writing a new SavedVariables file: the next lookup rebuilds
|
||||
// the index from disk as boot does, so new files appear and deleted
|
||||
// ones drop out. New files in EXISTING addons need nothing more —
|
||||
// the per-addon loader `FUN_0051F240` re-reads the TOC from disk on
|
||||
// every load pass, so once the files are visible they load.
|
||||
//
|
||||
// 2. REGISTRY MEMBERSHIP. The addon registry is built once at login;
|
||||
// new folders are never walked. We replay the login scan's disk
|
||||
@@ -63,13 +62,13 @@
|
||||
//
|
||||
// Excluded from the evict path (everything else is fair game):
|
||||
// - `!!!ClassicAPI` — embedded; `Addons::Embedded` owns its entry
|
||||
// (head re-link + filter byte);
|
||||
// (registered first + filter byte);
|
||||
// - `## Secure:` / SMSG-managed entries — the parser cannot restore
|
||||
// packet-delivered state (see OFF_ADDON_ENTRY_SECURE).
|
||||
//
|
||||
// NOTE the surgical discipline. A previous attempt re-invoked the
|
||||
// login-only teardown+rescan (`FUN_ADDON_INIT`) mid-/reload and
|
||||
// corrupted the registry (duplicate loads + Lua memory explosion on the
|
||||
// login-only teardown+rescan (`LoadAddOnsForAccount`, `0x0051C740`)
|
||||
// mid-/reload and corrupted the registry (duplicate loads + Lua memory explosion on the
|
||||
// NEXT login). This module never runs bulk teardown; the only entry
|
||||
// mutation beyond what a login scan produces is the per-entry evict
|
||||
// above, which is (a) the engine's own complete destructor, (b) always
|
||||
@@ -78,10 +77,9 @@
|
||||
// registration gets. New entries come from the same parser call
|
||||
// `Addons::Embedded` has exercised every login.
|
||||
//
|
||||
// Thread note: the loose-file index has no lock, but the engine itself
|
||||
// builds it lazily on first access and we mutate it only during the
|
||||
// reload loading screen on the main thread — the same context in which
|
||||
// the engine does all its own file work.
|
||||
// Thread note: the loose-file index has no lock in 1.12. We clear it on
|
||||
// the main thread during the reload loading screen — the same context
|
||||
// in which the engine's own unload pass clears it.
|
||||
|
||||
#include "Game.h"
|
||||
#include "Offsets.h"
|
||||
@@ -102,11 +100,7 @@ namespace {
|
||||
|
||||
// ── Engine entry points (all verified by disassembly; see Offsets.h) ──
|
||||
|
||||
using FindOpen_t = void *(__stdcall *)(const char *dirPath);
|
||||
using FindClose_t = void(__stdcall *)(void *findBlock);
|
||||
using IndexSubtree_t = void(__fastcall *)(const char *basePath,
|
||||
const char *relSubdir,
|
||||
void *findHandle);
|
||||
using IndexClear_t = void(__cdecl *)();
|
||||
using ScanDiskDirs_t = int(__fastcall *)(const char *basePath,
|
||||
const char *pattern, void *callback,
|
||||
void *userParam, int includeHidden);
|
||||
@@ -163,51 +157,15 @@ uintptr_t ResolveEntryByName(const char *name) {
|
||||
|
||||
// ── Step 1: loose-file index refresh ──────────────────────────────────
|
||||
|
||||
// Register new on-disk files under `relSubdir` with the frozen index,
|
||||
// exactly as the boot walk would have (the indexer skips every file
|
||||
// already present). No-op when the directory doesn't exist —
|
||||
// `FUN_VFS_FIND_OPEN` requires an existing directory and returns NULL.
|
||||
void ReindexSubtree(const char *base, const char *relSubdir) {
|
||||
char dir[260];
|
||||
std::snprintf(dir, sizeof(dir), "%s\\%s", base, relSubdir);
|
||||
auto findOpen = reinterpret_cast<FindOpen_t>(Offsets::FUN_VFS_FIND_OPEN);
|
||||
auto findClose = reinterpret_cast<FindClose_t>(Offsets::FUN_VFS_FIND_CLOSE);
|
||||
void *handle = findOpen(dir);
|
||||
if (handle == nullptr)
|
||||
return;
|
||||
auto index =
|
||||
reinterpret_cast<IndexSubtree_t>(Offsets::FUN_VFS_INDEX_SUBTREE);
|
||||
index(base, relSubdir, handle);
|
||||
findClose(handle);
|
||||
}
|
||||
|
||||
// Drop the loose-file index; the next file lookup rebuilds it from disk.
|
||||
void RefreshLooseFileIndex() {
|
||||
// The boot walk's base choice (`FUN_00646EA0`): the recorded game
|
||||
// dir if it opens as a directory, else ".". Index keys are relative
|
||||
// to this, so it must match or the new keys would never be hit.
|
||||
auto findOpen = reinterpret_cast<FindOpen_t>(Offsets::FUN_VFS_FIND_OPEN);
|
||||
auto findClose = reinterpret_cast<FindClose_t>(Offsets::FUN_VFS_FIND_CLOSE);
|
||||
const char *base =
|
||||
reinterpret_cast<const char *>(Offsets::VAR_VFS_BASE_PATH);
|
||||
void *probe = findOpen(base);
|
||||
if (probe != nullptr)
|
||||
findClose(probe);
|
||||
else
|
||||
base = ".";
|
||||
|
||||
// The only subtrees whose post-boot changes affect what a /reload
|
||||
// loads: addon content, and the SavedVariables the unload pass
|
||||
// wrote moments ago (a first-ever SV file is otherwise invisible —
|
||||
// the stock client loses a freshly installed addon's settings on
|
||||
// /reload for exactly this reason).
|
||||
ReindexSubtree(base, "Interface\\AddOns");
|
||||
ReindexSubtree(base, "WTF\\Account");
|
||||
reinterpret_cast<IndexClear_t>(Offsets::FUN_VFS_INDEX_CLEAR)();
|
||||
}
|
||||
|
||||
// ── Step 1.5: `##` metadata refresh (evict + re-register on change) ──
|
||||
|
||||
// The embedded addon's name — its entry is owned by `Addons::Embedded`
|
||||
// (head re-link + filter byte) and never refreshed here.
|
||||
// (registered first + filter byte) and never refreshed here.
|
||||
constexpr const char *kEmbeddedAddon = "!!!ClassicAPI";
|
||||
|
||||
// name → FNV-1a hash of the addon's `##` lines, as last parsed.
|
||||
@@ -437,13 +395,13 @@ void RebuildDisplayArray() {
|
||||
}
|
||||
|
||||
void Run() {
|
||||
// Registry populated (login scan ran) and loose index built — both
|
||||
// always true by the first in-world LoadScriptFunctions, but these
|
||||
// are the states the steps below mutate, so gate explicitly.
|
||||
// Registry populated (login scan ran) — always true by the first
|
||||
// in-world LoadScriptFunctions, but it is the state the steps below
|
||||
// mutate, so gate explicitly. No gate on the index being built: the
|
||||
// unload pass clears it whenever it wrote a new SV file, and the
|
||||
// clear below is safe either way.
|
||||
if (*reinterpret_cast<const uint8_t *>(
|
||||
static_cast<uintptr_t>(Offsets::VAR_ADDON_INITIALIZED)) == 0 ||
|
||||
*reinterpret_cast<const uint8_t *>(
|
||||
static_cast<uintptr_t>(Offsets::VAR_VFS_INDEX_READY)) == 0)
|
||||
static_cast<uintptr_t>(Offsets::VAR_ADDON_INITIALIZED)) == 0)
|
||||
return;
|
||||
|
||||
RefreshLooseFileIndex();
|
||||
|
||||
@@ -35,18 +35,19 @@
|
||||
// The engine STILL runs its own SavedVariables load at the normal step, right
|
||||
// after the files. Left alone, that re-load would overwrite any value the
|
||||
// addon wrote to its SavedVariable at file scope before ADDON_LOADED. So we
|
||||
// also co-hook FUN_LUA_LOAD_FILE and suppress that one redundant re-load: each
|
||||
// path we pre-load is remembered, and the engine's imminent load of that exact
|
||||
// path is skipped once. This makes the behavior match true
|
||||
// LoadSavedVariablesFirst — file-scope reads AND writes both survive. Our own
|
||||
// early load calls the trampoline directly, so it is never self-suppressed.
|
||||
// FUN_LUA_LOAD_FILE loads FILES only (not RunScript string execution), so the
|
||||
// extra hook is a cold, addon-load-time path.
|
||||
// also suppress that one redundant re-load, through Script::LoadFile's shared
|
||||
// FUN_LUA_LOAD_FILE hook: each path we pre-load is remembered, and the
|
||||
// engine's imminent load of that exact path is skipped once. This makes the
|
||||
// behavior match true LoadSavedVariablesFirst — file-scope reads AND writes
|
||||
// both survive. Our own early load calls Script::LoadFile::Original, so it is
|
||||
// never self-suppressed. FUN_LUA_LOAD_FILE loads FILES only (not RunScript
|
||||
// string execution), so this is a cold, addon-load-time path.
|
||||
|
||||
#include "Game.h"
|
||||
#include "Offsets.h"
|
||||
#include "addons/EngineIO.h"
|
||||
#include "addons/Toc.h"
|
||||
#include "script/LoadFile.h"
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
@@ -67,14 +68,12 @@ using AddOns::EngineIO::FileExistsFn;
|
||||
using AddOns::EngineIO::FileReadFn;
|
||||
using AddOns::EngineIO::SMemFreeFn;
|
||||
using LoadTocFilesFn = uint32_t(__fastcall *)(char *tocPath, int *a2, int *a3);
|
||||
using LuaLoadFileFn = uint32_t(__fastcall *)(const char *path, void *a2, void *a3);
|
||||
using NameFn = const char *(*)(); // no-arg readers (return in EAX)
|
||||
|
||||
LoadTocFilesFn g_orig = nullptr;
|
||||
LuaLoadFileFn g_origLuaLoad = nullptr;
|
||||
|
||||
// Full SV paths we pre-loaded whose imminent engine re-load must be skipped
|
||||
// once. Populated in LoadSavedVarsEarly, drained by LuaLoad_h. Only ever holds
|
||||
// once. Populated in LoadSavedVarsEarly, drained by SuppressReload. Only ever holds
|
||||
// a handful of entries (one addon's SV files, briefly). Main-thread only.
|
||||
std::vector<std::string> g_pendingSuppress;
|
||||
|
||||
@@ -148,18 +147,18 @@ SvFlags ReadSvFlags(const char *tocPath) {
|
||||
|
||||
const char *v = nullptr;
|
||||
size_t n = 0;
|
||||
if (AddOns::Toc::FindValue(b, size, "## LoadSavedVariablesFirst:", &v, &n))
|
||||
if (AddOns::Toc::FindValue(b, size, "LoadSavedVariablesFirst", &v, &n))
|
||||
f.first = NonzeroFlag(v, n);
|
||||
// Gate each SV file on the DECLARATION, not mere file existence — mirroring
|
||||
// the engine, which loads the account file iff `## SavedVariables` is
|
||||
// declared and the per-char file iff `## SavedVariablesPerCharacter` is.
|
||||
// (The trailing `:` keeps "## SavedVariables:" from matching the
|
||||
// "## SavedVariablesPerCharacter:" line.) Otherwise a stale SV file from a
|
||||
// (FindValue requires `:` right after the key, so "SavedVariables" never
|
||||
// matches the "## SavedVariablesPerCharacter:" line.) Otherwise a stale SV file from a
|
||||
// scope the addon no longer declares would be executed early — Lua the
|
||||
// engine never runs — and queued for a suppression the engine never drains.
|
||||
f.account = AddOns::Toc::FindValue(b, size, "## SavedVariables:", &v, &n) && n > 0;
|
||||
f.account = AddOns::Toc::FindValue(b, size, "SavedVariables", &v, &n) && n > 0;
|
||||
f.perChar =
|
||||
AddOns::Toc::FindValue(b, size, "## SavedVariablesPerCharacter:", &v, &n) && n > 0;
|
||||
AddOns::Toc::FindValue(b, size, "SavedVariablesPerCharacter", &v, &n) && n > 0;
|
||||
|
||||
reinterpret_cast<SMemFreeFn>(static_cast<uintptr_t>(Offsets::FUN_STORM_SMEM_FREE))(
|
||||
buf, __FILE__, __LINE__, 0);
|
||||
@@ -173,12 +172,10 @@ bool FileExists(const char *path) {
|
||||
|
||||
// Load a SavedVariables file we found, then mark its path so the engine's own
|
||||
// re-load of it (right after the addon's files) is suppressed — preserving any
|
||||
// file-scope write. Calls the trampoline directly so this load is never itself
|
||||
// suppressed by our LuaLoad_h hook.
|
||||
// file-scope write. Calls the engine loader directly so this load is never
|
||||
// itself suppressed by SuppressReload.
|
||||
void RunLuaFile(const char *path) {
|
||||
if (g_origLuaLoad == nullptr)
|
||||
return;
|
||||
g_origLuaLoad(path, nullptr, nullptr);
|
||||
Script::LoadFile::Original(path, nullptr, nullptr);
|
||||
g_pendingSuppress.emplace_back(path);
|
||||
}
|
||||
|
||||
@@ -241,18 +238,16 @@ uint32_t __fastcall LoadTocFiles_h(char *tocPath, int *a2, int *a3) {
|
||||
// Skip the engine's one redundant SavedVariables re-load per pre-loaded path.
|
||||
// Every other file load passes straight through. Match is by full path
|
||||
// (case-insensitive); a path is suppressed exactly once, so nothing else is
|
||||
// affected. Our own early load bypasses this via the trampoline.
|
||||
uint32_t __fastcall LuaLoad_h(const char *path, void *a2, void *a3) {
|
||||
if (path != nullptr) {
|
||||
for (size_t i = 0; i < g_pendingSuppress.size(); ++i) {
|
||||
if (SamePathCI(g_pendingSuppress[i].c_str(), path)) {
|
||||
g_pendingSuppress.erase(g_pendingSuppress.begin() +
|
||||
static_cast<std::ptrdiff_t>(i));
|
||||
return 0; // suppress — the addon's file-scope SV writes survive
|
||||
}
|
||||
// affected. Our own early load bypasses this through Original.
|
||||
bool SuppressReload(const char *path) {
|
||||
for (size_t i = 0; i < g_pendingSuppress.size(); ++i) {
|
||||
if (SamePathCI(g_pendingSuppress[i].c_str(), path)) {
|
||||
g_pendingSuppress.erase(g_pendingSuppress.begin() +
|
||||
static_cast<std::ptrdiff_t>(i));
|
||||
return true; // suppress — the addon's file-scope SV writes survive
|
||||
}
|
||||
}
|
||||
return g_origLuaLoad(path, a2, a3);
|
||||
return false;
|
||||
}
|
||||
|
||||
const Game::HookAutoRegister _hook{
|
||||
@@ -260,10 +255,7 @@ const Game::HookAutoRegister _hook{
|
||||
reinterpret_cast<void *>(&LoadTocFiles_h),
|
||||
reinterpret_cast<void **>(&g_orig)};
|
||||
|
||||
const Game::HookAutoRegister _hookLua{
|
||||
Offsets::FUN_LUA_LOAD_FILE,
|
||||
reinterpret_cast<void *>(&LuaLoad_h),
|
||||
reinterpret_cast<void **>(&g_origLuaLoad)};
|
||||
const Script::LoadFile::AutoSuppress _suppress{&SuppressReload};
|
||||
|
||||
} // namespace
|
||||
|
||||
|
||||
+50
-27
@@ -33,35 +33,58 @@ inline bool EqCI(const char *s, size_t n, const char *lit) {
|
||||
return lit[n] == '\0';
|
||||
}
|
||||
|
||||
// Scans an in-memory TOC buffer for `directive` (the full line prefix, e.g.
|
||||
// "## Version:") at a line start, case-insensitively, and returns the value
|
||||
// that follows via out-params: [*valStart, *valStart + *valLen), trimmed of
|
||||
// leading and trailing spaces/tabs and excluding the CR/LF/EOF terminator.
|
||||
// Returns false (out-params untouched) when the directive is absent. Pure —
|
||||
// reads no files; the caller owns the buffer (via FUN_FILE_READ, or an embedded
|
||||
// copy). Shared by addons/LocalTable.cpp (AllowAddOnTableAccess) and
|
||||
// addons/Embedded.cpp (Version) so the line-scan lives in one place.
|
||||
inline bool FindValue(const char *buf, size_t size, const char *directive,
|
||||
// Scans an in-memory TOC buffer for the `## <key>:` directive and returns the
|
||||
// first one's value via out-params: [*valStart, *valStart + *valLen), trimmed
|
||||
// of leading and trailing spaces/tabs and excluding the CR/LF/EOF terminator.
|
||||
// `key` is the bare name ("Version", "SavedVariables"). Returns false
|
||||
// (out-params untouched) when the directive is absent.
|
||||
//
|
||||
// Matches lines the way the engine's TOC parser `FUN_TOC_PARSER` (0x0051C9B0)
|
||||
// does, so a directive the engine reads is never one we miss: a UTF-8 BOM at
|
||||
// the start of the file is skipped; lines break at CR or LF; a line counts
|
||||
// when it starts with "##", then any number of spaces, then `key`
|
||||
// case-insensitively, IMMEDIATELY followed by ':' (the engine compares
|
||||
// against literals like "SavedVariables:", which is also why
|
||||
// "SavedVariables" never matches a "SavedVariablesPerCharacter:" line).
|
||||
//
|
||||
// Pure — reads no files; the caller owns the buffer (via FUN_FILE_READ, or an
|
||||
// embedded copy). Shared by every addon module that reads a TOC directive so
|
||||
// the line-scan lives in one place.
|
||||
inline bool FindValue(const char *buf, size_t size, const char *key,
|
||||
const char **valStart, size_t *valLen) {
|
||||
const size_t dlen = std::strlen(directive);
|
||||
if (dlen == 0)
|
||||
const size_t klen = std::strlen(key);
|
||||
if (klen == 0)
|
||||
return false;
|
||||
for (size_t i = 0; i + dlen <= size; ++i) {
|
||||
const bool atLineStart = (i == 0) || buf[i - 1] == '\n';
|
||||
if (!atLineStart || _strnicmp(buf + i, directive, dlen) != 0)
|
||||
continue;
|
||||
const char *p = buf + i + dlen;
|
||||
const char *end = buf + size;
|
||||
while (p < end && (*p == ' ' || *p == '\t'))
|
||||
++p;
|
||||
const char *v = p;
|
||||
while (p < end && *p != '\r' && *p != '\n')
|
||||
++p;
|
||||
while (p > v && (p[-1] == ' ' || p[-1] == '\t'))
|
||||
--p;
|
||||
*valStart = v;
|
||||
*valLen = static_cast<size_t>(p - v);
|
||||
return true;
|
||||
const char *end = buf + size;
|
||||
const char *line = buf;
|
||||
if (size >= 3 && static_cast<unsigned char>(buf[0]) == 0xEF &&
|
||||
static_cast<unsigned char>(buf[1]) == 0xBB &&
|
||||
static_cast<unsigned char>(buf[2]) == 0xBF)
|
||||
line += 3;
|
||||
while (line < end) {
|
||||
const char *eol = line;
|
||||
while (eol < end && *eol != '\r' && *eol != '\n')
|
||||
++eol;
|
||||
const char *p = line;
|
||||
if (eol - p >= 2 && p[0] == '#' && p[1] == '#') {
|
||||
p += 2;
|
||||
while (p < eol && *p == ' ')
|
||||
++p;
|
||||
if (static_cast<size_t>(eol - p) > klen && EqCI(p, klen, key) &&
|
||||
p[klen] == ':') {
|
||||
p += klen + 1;
|
||||
while (p < eol && (*p == ' ' || *p == '\t'))
|
||||
++p;
|
||||
const char *v = p;
|
||||
p = eol;
|
||||
while (p > v && (p[-1] == ' ' || p[-1] == '\t'))
|
||||
--p;
|
||||
*valStart = v;
|
||||
*valLen = static_cast<size_t>(p - v);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
line = eol + 1;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
+18
-13
@@ -78,13 +78,18 @@ uint32_t ClientInterfaceVersion() {
|
||||
static_cast<uintptr_t>(Offsets::FUN_ADDON_CLIENT_INTERFACE_VERSION))();
|
||||
}
|
||||
|
||||
// If `line` is a `## Interface:` directive whose value is a comma-list that
|
||||
// contains the client version but does NOT lead with it, append a normalized
|
||||
// `<prefix>: <clientVersion>` line to `out` and return true. Vanilla's parser
|
||||
// reads only the first number, so without this a later 11200 is never seen and
|
||||
// the addon is marked out of date. Returns false for any other line, and for
|
||||
// an interface line that needs no change (single value, no client version, or
|
||||
// client version already first) — the caller then copies the line verbatim.
|
||||
// If `line` is a `## Interface:` directive whose value is a comma-list, pick
|
||||
// the retail value — the closest entry at or below the client version — and,
|
||||
// when that is not already the first entry, append a normalized
|
||||
// `<prefix>: <value>` line to `out` and return true. Vanilla's parser reads
|
||||
// only the first number, so without this a later 11200 is never seen and the
|
||||
// addon is marked out of date. Loadability stays an exact match on the client
|
||||
// version, and the pick equals it iff it is in the list, so this only changes
|
||||
// the stored value (what GetAddOnInterfaceVersion reads) for lists that were
|
||||
// out of date anyway. Returns false for any other line, and for an interface
|
||||
// line that needs no change (single value, nothing at or below the client
|
||||
// version, or the pick already first) — the caller then copies the line
|
||||
// verbatim.
|
||||
bool TryRewriteInterfaceLine(const char *line, size_t len, std::string &out) {
|
||||
size_t s = 0;
|
||||
while (s < len && IsSpace(line[s])) ++s;
|
||||
@@ -103,8 +108,8 @@ bool TryRewriteInterfaceLine(const char *line, size_t len, std::string &out) {
|
||||
const size_t prefixEnd = p; // "## Interface:" (author spacing preserved)
|
||||
|
||||
const uint32_t client = ClientInterfaceVersion();
|
||||
long first = -1;
|
||||
bool hasComma = false, hasClient = false;
|
||||
long first = -1, best = -1;
|
||||
bool hasComma = false;
|
||||
size_t q = p;
|
||||
while (q < len) {
|
||||
while (q < len && (IsSpace(line[q]) || line[q] == ',')) {
|
||||
@@ -120,17 +125,17 @@ bool TryRewriteInterfaceLine(const char *line, size_t len, std::string &out) {
|
||||
}
|
||||
if (digit) {
|
||||
if (first < 0) first = v;
|
||||
if (static_cast<uint32_t>(v) == client) hasClient = true;
|
||||
if (static_cast<uint32_t>(v) <= client && v > best) best = v;
|
||||
} else if (q < len) {
|
||||
++q; // skip a stray non-digit so the scan always advances
|
||||
}
|
||||
}
|
||||
if (!hasComma || !hasClient || first == static_cast<long>(client))
|
||||
return false; // single value / no client version / already first
|
||||
if (!hasComma || best < 0 || first == best)
|
||||
return false; // single value / nothing at or below client / already first
|
||||
|
||||
out.append(line, prefixEnd);
|
||||
out.push_back(' ');
|
||||
out += std::to_string(client);
|
||||
out += std::to_string(best);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -59,12 +59,13 @@ namespace AddOns::TocRewrite {
|
||||
// Multi-flavor `## Interface:` list. Retail lets a TOC list several
|
||||
// interface versions (`## Interface: 120100, 50504, 11200`). Vanilla's
|
||||
// parser is a plain atoi that reads only the FIRST number, so it never
|
||||
// sees a later 11200 and marks the addon out of date. When the client
|
||||
// version (FUN_ADDON_CLIENT_INTERFACE_VERSION, 11200) appears anywhere in
|
||||
// the list but is not first, the `## Interface:` line is rewritten to that
|
||||
// single value so the engine marks the addon compatible. A list WITHOUT
|
||||
// the client version is left unchanged — it still parses to its first
|
||||
// value and stays out of date, exactly as before.
|
||||
// sees a later 11200 and marks the addon out of date. The line is rewritten
|
||||
// to retail's pick — the closest value at or below the client version
|
||||
// (FUN_ADDON_CLIENT_INTERFACE_VERSION, 11200) — when that is not already
|
||||
// first. If 11200 is listed the pick is 11200 and the addon loads; if not,
|
||||
// the addon stays out of date exactly as before, but the stored value
|
||||
// (`GetAddOnInterfaceVersion`) matches retail. A list with nothing at or
|
||||
// below the client version is left unchanged.
|
||||
//
|
||||
// Called from the FUN_FILE_READ hook after the read succeeds. Does
|
||||
// nothing unless `path` is an addon `.toc` read AND its content contains a
|
||||
|
||||
@@ -0,0 +1,715 @@
|
||||
// This file is part of ClassicAPI.
|
||||
//
|
||||
// ClassicAPI is free software: you can redistribute it and/or modify it under the terms
|
||||
// of the GNU 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 General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License along with
|
||||
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
// 4.3.4's CSimpleAnim and its Alpha, Translation, Scale and Rotation
|
||||
// subclasses (wowdecomp15595 CSimpleAnim.cpp, CSimple*Anim.cpp and their
|
||||
// _Scripts.cpp), on Animation::Object, and the group's CreateAnimation.
|
||||
// Path and its control points are in Path.cpp.
|
||||
|
||||
#include "animation/Classes.h"
|
||||
#include "animation/Region.h"
|
||||
#include "animation/Xml.h"
|
||||
|
||||
#include "Game.h"
|
||||
#include "Offsets.h"
|
||||
#include "baselib/Ascii.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
|
||||
namespace Animation {
|
||||
|
||||
namespace {
|
||||
|
||||
const char *const kAnimScripts[] = {"onload", "onplay", "onpause", "onstop", "onfinished", "onupdate"};
|
||||
|
||||
Class &ClassOf(AnimKind kind) {
|
||||
switch (kind) {
|
||||
case KIND_ALPHA: return Anim::s_alphaClass;
|
||||
case KIND_TRANSLATION: return Anim::s_translationClass;
|
||||
case KIND_SCALE: return Anim::s_scaleClass;
|
||||
case KIND_ROTATION: return Anim::s_rotationClass;
|
||||
case KIND_PATH: return Anim::s_pathClass;
|
||||
default: return Anim::s_class;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
AnimKind Anim::KindOf(const char *typeName) {
|
||||
if (typeName == nullptr || *typeName == '\0')
|
||||
return KIND_ANIMATION;
|
||||
if (Ascii::EqualCI(typeName, "Alpha"))
|
||||
return KIND_ALPHA;
|
||||
if (Ascii::EqualCI(typeName, "Translation"))
|
||||
return KIND_TRANSLATION;
|
||||
if (Ascii::EqualCI(typeName, "Scale"))
|
||||
return KIND_SCALE;
|
||||
if (Ascii::EqualCI(typeName, "Rotation"))
|
||||
return KIND_ROTATION;
|
||||
if (Ascii::EqualCI(typeName, "Path"))
|
||||
return KIND_PATH;
|
||||
return KIND_ANIMATION;
|
||||
}
|
||||
|
||||
// ---- Construction ---------------------------------------------------------------
|
||||
|
||||
// 4.3.4's constructor links the animation into the group's list; it joins an
|
||||
// order list only once it has an order (NotifyAnimAdded, SortAnimations).
|
||||
Anim::Anim(Group *group, AnimKind kind, const char *name) : Object(ClassOf(kind), group, name), kind(kind) {
|
||||
if (group != nullptr)
|
||||
group->animations.push_back(this);
|
||||
}
|
||||
|
||||
// ~CSimplePathAnim: a path's control points go with it.
|
||||
Anim::~Anim() {
|
||||
for (ControlPoint *point : controlPoints)
|
||||
delete point;
|
||||
}
|
||||
|
||||
// ---- Playback --------------------------------------------------------------------
|
||||
|
||||
bool Anim::Play() {
|
||||
if (targetName[0] != '\0')
|
||||
target = Region::FindRegionByName(targetName);
|
||||
if (playState != 1) {
|
||||
playState = 1;
|
||||
RunScript(A_ONPLAY, 0);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void Anim::Pause() {
|
||||
GetGroup()->Pause();
|
||||
if (playState == 1) {
|
||||
playState = 2;
|
||||
RunScript(A_ONPAUSE, 0);
|
||||
}
|
||||
}
|
||||
|
||||
void Anim::Stop(bool requested) {
|
||||
if (playState == 0)
|
||||
return;
|
||||
loopState = STATE_NONE;
|
||||
playState = 0;
|
||||
elapsed = 0.0f;
|
||||
progressWithDelay = 0.0f;
|
||||
progress = 0.0f;
|
||||
if (HasScript(A_ONSTOP)) {
|
||||
Game::Lua::PushBool(Game::Lua::State(), requested);
|
||||
RunScript(A_ONSTOP, 1);
|
||||
}
|
||||
}
|
||||
|
||||
bool Anim::IsDelaying() const {
|
||||
if (progressWithDelay <= 0.0f || progressWithDelay >= 1.0f)
|
||||
return false;
|
||||
const float total = endDelay + duration + startDelay;
|
||||
if (std::fabs(total) < 0.00000023841858f)
|
||||
return false;
|
||||
if (loopState == STATE_REVERSE) {
|
||||
if (endDelay > elapsed)
|
||||
return true;
|
||||
if (endDelay + duration > elapsed)
|
||||
return false;
|
||||
} else {
|
||||
if (startDelay > elapsed)
|
||||
return true;
|
||||
if (duration + startDelay > elapsed)
|
||||
return false;
|
||||
}
|
||||
return total > elapsed;
|
||||
}
|
||||
|
||||
float Anim::UpdateProgress(float elapsedSec) {
|
||||
const float prevElapsed = elapsed;
|
||||
elapsed += elapsedSec;
|
||||
const float total = orderPadding + startDelay + endDelay + duration;
|
||||
float now;
|
||||
if (total > elapsed) {
|
||||
now = elapsed;
|
||||
progressWithDelay = now / total;
|
||||
if (progressWithDelay > 1.0f)
|
||||
progressWithDelay = 1.0f;
|
||||
if (std::fabs(duration) < 0.00000023841858f) {
|
||||
progress = 1.0f;
|
||||
} else {
|
||||
frameElapsed += elapsedSec;
|
||||
if ((GetGroup()->flags & GROUP_IGNORE_THROTTLE) || frameElapsed >= g_frameInterval) {
|
||||
const float delay = loopState == STATE_REVERSE ? orderPadding + endDelay : startDelay;
|
||||
progress = (now - delay) / duration;
|
||||
if (progress < 0.0f)
|
||||
progress = 0.0f;
|
||||
else if (progress >= 1.0f)
|
||||
progress = 1.0f;
|
||||
frameElapsed = 0.0f;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
now = total;
|
||||
progressWithDelay = 1.0f;
|
||||
progress = 1.0f;
|
||||
}
|
||||
float p = loopState == STATE_REVERSE ? 1.0f - progress : progress;
|
||||
if (hasSmoother) {
|
||||
// CSimpleAnimSCurveSmoother::GetSmoothProgress.
|
||||
if (std::fabs(smoothIn) >= 0.001f && std::fabs(smoothOut) >= 0.001f)
|
||||
p = 0.5f - std::cos(p * 3.1415927f) * 0.5f;
|
||||
else if (std::fabs(smoothIn) >= 0.001f)
|
||||
p = 1.0f - std::cos(p * 1.5707964f);
|
||||
else if (std::fabs(smoothOut) >= 0.001f)
|
||||
p = std::cos((p + 1.0f) * 1.5707964f) * -1.0f;
|
||||
}
|
||||
smoothProgress = p;
|
||||
return now - prevElapsed;
|
||||
}
|
||||
|
||||
bool Anim::OnUpdate(float elapsedSec, float &consumed) {
|
||||
consumed = 0.0f;
|
||||
if (progressWithDelay >= 1.0f) {
|
||||
Apply(smoothProgress);
|
||||
return true;
|
||||
}
|
||||
if (playState == 0)
|
||||
return true;
|
||||
if (playState == 2) {
|
||||
Apply(smoothProgress);
|
||||
return false;
|
||||
}
|
||||
consumed = UpdateProgress(elapsedSec);
|
||||
if (HasScript(A_ONUPDATE)) {
|
||||
Game::Lua::PushNumber(Game::Lua::State(), elapsedSec);
|
||||
RunScript(A_ONUPDATE, 1);
|
||||
}
|
||||
Apply(smoothProgress);
|
||||
if (progressWithDelay < 1.0f)
|
||||
return false;
|
||||
RunScript(A_ONFINISHED, 0);
|
||||
return true;
|
||||
}
|
||||
|
||||
void Anim::Apply(float p) {
|
||||
void *region = GetRegionParent();
|
||||
if (region == nullptr)
|
||||
return;
|
||||
switch (kind) {
|
||||
case KIND_ALPHA:
|
||||
Region::AddAnimAlpha(region, target, static_cast<int16_t>(change * p));
|
||||
break;
|
||||
case KIND_TRANSLATION:
|
||||
Region::AddAnimTranslation(region, target, offsetX * p, offsetY * p);
|
||||
break;
|
||||
case KIND_SCALE:
|
||||
Region::AddAnimScale(region, target, originPoint, originX, originY, scaleChangeX * p, scaleChangeY * p);
|
||||
break;
|
||||
case KIND_ROTATION:
|
||||
Region::AddAnimRotation(region, target, originPoint, originX, originY, radians * p);
|
||||
break;
|
||||
case KIND_PATH:
|
||||
ApplyPath(p);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Settings ----------------------------------------------------------------------
|
||||
|
||||
void Anim::SetStartDelay(float delay, bool notify) {
|
||||
startDelay = delay < 0.0f ? 0.0f : delay;
|
||||
if (notify && parent != nullptr)
|
||||
GetGroup()->ComputeDuration();
|
||||
}
|
||||
|
||||
void Anim::SetEndDelay(float delay, bool notify) {
|
||||
endDelay = delay < 0.0f ? 0.0f : delay;
|
||||
if (notify && parent != nullptr)
|
||||
GetGroup()->ComputeDuration();
|
||||
}
|
||||
|
||||
void Anim::SetDuration(float value, bool notify) {
|
||||
duration = value;
|
||||
if (notify && parent != nullptr)
|
||||
GetGroup()->ComputeDuration();
|
||||
}
|
||||
|
||||
void Anim::SetOrder(int value, bool notify, bool wrap) {
|
||||
const int oldOrder = order;
|
||||
if (wrap)
|
||||
order = value < 0 || value > 99 ? 0 : value;
|
||||
else
|
||||
order = value < 0 ? 0 : (value > 99 ? 99 : value);
|
||||
// 4.3.4 compares the old order with the argument, not the clamped value.
|
||||
if (notify && parent != nullptr && oldOrder != value)
|
||||
GetGroup()->NotifyOrderChanged(this, oldOrder);
|
||||
}
|
||||
|
||||
void Anim::SetSmoothing(float in, float out) {
|
||||
if ((in > 0.0f && in <= 1.0f) || (out > 0.0f && out <= 1.0f)) {
|
||||
hasSmoother = true;
|
||||
smoothIn = in < 0.0f ? 0.0f : (in < 1.0f ? in : 1.0f);
|
||||
smoothOut = out < 0.0f ? 0.0f : (out < 1.0f ? out : 1.0f);
|
||||
}
|
||||
}
|
||||
|
||||
bool Anim::GetSmoothing(float &in, float &out) const {
|
||||
in = hasSmoother ? smoothIn : 0.0f;
|
||||
out = hasSmoother ? smoothOut : 0.0f;
|
||||
return hasSmoother;
|
||||
}
|
||||
|
||||
bool Anim::ChangeParent(Group *group) {
|
||||
if (group == nullptr || parent == group)
|
||||
return false;
|
||||
GetGroup()->NotifyAnimRemoved(this);
|
||||
parent = group;
|
||||
group->NotifyAnimAdded(this);
|
||||
return true;
|
||||
}
|
||||
|
||||
void Anim::PostLoadXML() {
|
||||
flags &= ~1;
|
||||
if (kind == KIND_PATH) {
|
||||
// CSimplePathAnim::PostLoadXML: the points' orders and positions.
|
||||
BuildSpline();
|
||||
UpdateControlPointPositions();
|
||||
}
|
||||
RunScript(A_ONLOAD, 0);
|
||||
}
|
||||
|
||||
// ---- Lua methods ----------------------------------------------------------------------
|
||||
|
||||
namespace {
|
||||
|
||||
using StringToPoint_t = int(__fastcall *)(const char *name, int *point);
|
||||
using PointToString_t = const char *(__fastcall *)(int point);
|
||||
|
||||
Anim *Self(void *L) { return static_cast<Anim *>(Resolve(L, 1, Anim::s_class)); }
|
||||
Anim *SelfOf(void *L, Class &cls) { return static_cast<Anim *>(Resolve(L, 1, cls)); }
|
||||
|
||||
// Usage error when argument `idx` isn't a number; the number otherwise.
|
||||
bool NumberArg(void *L, int idx, Anim *anim, const char *usage) {
|
||||
if (Game::Lua::IsNumber(L, idx))
|
||||
return true;
|
||||
Game::Lua::Error(L, usage, anim->DisplayName());
|
||||
return false;
|
||||
}
|
||||
|
||||
int __fastcall Script_Play(void *L) {
|
||||
if (Anim *a = Self(L))
|
||||
a->Play();
|
||||
return 0;
|
||||
}
|
||||
int __fastcall Script_Pause(void *L) {
|
||||
if (Anim *a = Self(L))
|
||||
a->Pause();
|
||||
return 0;
|
||||
}
|
||||
int __fastcall Script_Stop(void *L) {
|
||||
if (Anim *a = Self(L))
|
||||
a->Stop(true);
|
||||
return 0;
|
||||
}
|
||||
|
||||
template <typename Fn> int PushBoolOf(void *L, Fn fn) {
|
||||
Anim *a = Self(L);
|
||||
if (a == nullptr)
|
||||
return 0;
|
||||
Game::Lua::PushBool(L, fn(a));
|
||||
return 1;
|
||||
}
|
||||
template <typename Fn> int PushNumberOf(void *L, Fn fn) {
|
||||
Anim *a = Self(L);
|
||||
if (a == nullptr)
|
||||
return 0;
|
||||
Game::Lua::PushNumber(L, fn(a));
|
||||
return 1;
|
||||
}
|
||||
|
||||
int __fastcall Script_IsDone(void *L) { return PushBoolOf(L, [](Anim *a) { return a->progressWithDelay >= 1.0f; }); }
|
||||
int __fastcall Script_IsPlaying(void *L) { return PushBoolOf(L, [](Anim *a) { return a->playState == 1; }); }
|
||||
int __fastcall Script_IsPaused(void *L) { return PushBoolOf(L, [](Anim *a) { return a->playState == 2; }); }
|
||||
int __fastcall Script_IsStopped(void *L) { return PushBoolOf(L, [](Anim *a) { return a->playState == 0; }); }
|
||||
int __fastcall Script_IsDelaying(void *L) { return PushBoolOf(L, [](Anim *a) { return a->IsDelaying(); }); }
|
||||
int __fastcall Script_GetElapsed(void *L) { return PushNumberOf(L, [](Anim *a) { return a->elapsed; }); }
|
||||
int __fastcall Script_GetStartDelay(void *L) { return PushNumberOf(L, [](Anim *a) { return a->startDelay; }); }
|
||||
int __fastcall Script_GetEndDelay(void *L) { return PushNumberOf(L, [](Anim *a) { return a->endDelay; }); }
|
||||
int __fastcall Script_GetDuration(void *L) { return PushNumberOf(L, [](Anim *a) { return a->duration; }); }
|
||||
int __fastcall Script_GetSmoothProgress(void *L) {
|
||||
return PushNumberOf(L, [](Anim *a) { return a->smoothProgress; });
|
||||
}
|
||||
int __fastcall Script_GetProgress(void *L) { return PushNumberOf(L, [](Anim *a) { return a->progress; }); }
|
||||
int __fastcall Script_GetProgressWithDelay(void *L) {
|
||||
return PushNumberOf(L, [](Anim *a) { return a->progressWithDelay; });
|
||||
}
|
||||
int __fastcall Script_GetOrder(void *L) {
|
||||
return PushNumberOf(L, [](Anim *a) { return static_cast<double>(a->order + 1); });
|
||||
}
|
||||
|
||||
int __fastcall Script_SetStartDelay(void *L) {
|
||||
Anim *a = Self(L);
|
||||
if (a != nullptr && NumberArg(L, 2, a, "Usage: %s:SetStartDelay(delaySec)"))
|
||||
a->SetStartDelay(static_cast<float>(Game::Lua::ToNumber(L, 2)), true);
|
||||
return 0;
|
||||
}
|
||||
int __fastcall Script_SetEndDelay(void *L) {
|
||||
Anim *a = Self(L);
|
||||
if (a != nullptr && NumberArg(L, 2, a, "Usage: %s:SetEndDelay(delaySec)"))
|
||||
a->SetEndDelay(static_cast<float>(Game::Lua::ToNumber(L, 2)), true);
|
||||
return 0;
|
||||
}
|
||||
int __fastcall Script_SetDuration(void *L) {
|
||||
Anim *a = Self(L);
|
||||
if (a != nullptr && NumberArg(L, 2, a, "Usage: %s:SetDuration(durationSec)"))
|
||||
a->SetDuration(static_cast<float>(Game::Lua::ToNumber(L, 2)), true);
|
||||
return 0;
|
||||
}
|
||||
int __fastcall Script_SetSmoothProgress(void *L) {
|
||||
Anim *a = Self(L);
|
||||
if (a != nullptr && NumberArg(L, 2, a, "Usage: %s:SetSmoothProgress(smoothProgress)"))
|
||||
a->smoothProgress = static_cast<float>(Game::Lua::ToNumber(L, 2));
|
||||
return 0;
|
||||
}
|
||||
int __fastcall Script_SetOrder(void *L) {
|
||||
Anim *a = Self(L);
|
||||
if (a != nullptr && NumberArg(L, 2, a, "Usage: %s:SetOrder(order)"))
|
||||
a->SetOrder(static_cast<int>(Game::Lua::ToNumber(L, 2)) - 1, true, false);
|
||||
return 0;
|
||||
}
|
||||
int __fastcall Script_SetSmoothing(void *L) {
|
||||
Anim *a = Self(L);
|
||||
if (a == nullptr)
|
||||
return 0;
|
||||
if (!Game::Lua::IsString(L, 2)) {
|
||||
Game::Lua::Error(L, "Usage: %s:SetSmoothing(\"smoothingType\")", a->DisplayName());
|
||||
return 0;
|
||||
}
|
||||
float in, out;
|
||||
if (StringToSmoothWeights(Game::Lua::ToString(L, 2), in, out)) {
|
||||
a->SetSmoothing(in, out);
|
||||
return 0;
|
||||
}
|
||||
Game::Lua::Error(L, "%s:SetSmoothing(): Unknown smoothing type specified", a->DisplayName());
|
||||
return 0;
|
||||
}
|
||||
int __fastcall Script_GetSmoothing(void *L) {
|
||||
Anim *a = Self(L);
|
||||
if (a == nullptr)
|
||||
return 0;
|
||||
float in, out;
|
||||
a->GetSmoothing(in, out);
|
||||
Game::Lua::PushString(L, SmoothWeightsToString(in, out));
|
||||
return 1;
|
||||
}
|
||||
|
||||
int __fastcall Script_SetParent(void *L) {
|
||||
Anim *a = Self(L);
|
||||
if (a == nullptr)
|
||||
return 0;
|
||||
if (Game::Lua::Type(L, 2) == Game::Lua::TYPE_NIL) {
|
||||
Game::Lua::Error(L, "%s:SetParent(): Cannot set a 'nil' parent for animations", a->DisplayName());
|
||||
return 0;
|
||||
}
|
||||
Group *group = nullptr;
|
||||
if (Game::Lua::IsString(L, 2)) {
|
||||
// CScriptObject::GetScriptObjectByName(name, AnimationGroup).
|
||||
Game::Lua::PushString(L, Game::Lua::ToString(L, 2));
|
||||
Game::Lua::RawGet(L, Game::Lua::GLOBALS_INDEX);
|
||||
void *object = Game::Lua::Type(L, -1) == Game::Lua::TYPE_TABLE ? Game::Lua::ResolveObject(L, -1) : nullptr;
|
||||
Game::Lua::SetTop(L, -2);
|
||||
if (object != nullptr && IsOurs(object) &&
|
||||
Game::Lua::IsA(object, reinterpret_cast<uintptr_t>(&Group::s_class.typeId)))
|
||||
group = static_cast<Group *>(object);
|
||||
} else if (Game::Lua::Type(L, 2) == Game::Lua::TYPE_TABLE) {
|
||||
void *object = Game::Lua::ResolveObject(L, 2);
|
||||
if (object == nullptr) {
|
||||
Game::Lua::Error(L, "%s:SetParent(): Couldn't find 'this' in parent object", a->DisplayName());
|
||||
return 0;
|
||||
}
|
||||
if (!IsOurs(object) || !Game::Lua::IsA(object, reinterpret_cast<uintptr_t>(&Group::s_class.typeId))) {
|
||||
Game::Lua::Error(L, "%s:SetParent(): Wrong parent object type, expected AnimationGroup", a->DisplayName());
|
||||
return 0;
|
||||
}
|
||||
group = static_cast<Group *>(object);
|
||||
}
|
||||
if (group == nullptr) {
|
||||
Game::Lua::Error(L, "%s:SetParent(): Couldn't find animation group named '%s'", a->DisplayName(),
|
||||
Game::Lua::IsString(L, 2) ? Game::Lua::ToString(L, 2) : "");
|
||||
return 0;
|
||||
}
|
||||
const int oldOrder = a->order;
|
||||
if (Game::Lua::IsNumber(L, 3)) {
|
||||
a->SetOrder(static_cast<int>(Game::Lua::ToNumber(L, 3)) - 1, false, false);
|
||||
} else {
|
||||
int value = a->order;
|
||||
if (value == -1)
|
||||
value = group->GetMaxAnimOrder() + 1;
|
||||
a->SetOrder(value, false, true);
|
||||
}
|
||||
if (!a->ChangeParent(group) && oldOrder != a->order)
|
||||
group->NotifyOrderChanged(a, oldOrder);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int __fastcall Script_GetRegionParent(void *L) {
|
||||
Anim *a = Self(L);
|
||||
if (a == nullptr)
|
||||
return 0;
|
||||
void *region = a->GetRegionParent();
|
||||
if (region != nullptr)
|
||||
Game::Lua::PushObject(L, region);
|
||||
else
|
||||
Game::Lua::PushNil(L);
|
||||
return 1;
|
||||
}
|
||||
|
||||
// ---- Alpha ----
|
||||
|
||||
int __fastcall Script_SetChange(void *L) {
|
||||
Anim *a = SelfOf(L, Anim::s_alphaClass);
|
||||
if (a == nullptr || !NumberArg(L, 2, a, "Usage: %s:SetChange(change)"))
|
||||
return 0;
|
||||
// CSimpleAlphaAnim::SetChange.
|
||||
const float change = static_cast<float>(Game::Lua::ToNumber(L, 2));
|
||||
const float value = change < -1.0f ? -1.0f : (change >= 1.0f ? 1.0f : change);
|
||||
a->change = static_cast<int16_t>(value * 255.0f);
|
||||
return 0;
|
||||
}
|
||||
int __fastcall Script_GetChange(void *L) {
|
||||
Anim *a = SelfOf(L, Anim::s_alphaClass);
|
||||
if (a == nullptr)
|
||||
return 0;
|
||||
Game::Lua::PushNumber(L, a->change * (1.0f / 255.0f));
|
||||
return 1;
|
||||
}
|
||||
|
||||
// ---- Translation ----
|
||||
|
||||
int __fastcall Script_SetOffset(void *L) {
|
||||
Anim *a = SelfOf(L, Anim::s_translationClass);
|
||||
if (a == nullptr)
|
||||
return 0;
|
||||
if (!Game::Lua::IsNumber(L, 2) || !Game::Lua::IsNumber(L, 3)) {
|
||||
Game::Lua::Error(L, "Usage: %s:SetOffset(x, y)", a->DisplayName());
|
||||
return 0;
|
||||
}
|
||||
const float x = Game::PixelToInternal(static_cast<float>(Game::Lua::ToNumber(L, 2)));
|
||||
const float y = Game::PixelToInternal(static_cast<float>(Game::Lua::ToNumber(L, 3)));
|
||||
// CSimpleTranslationAnim::SetOffset: a near-zero offset is zero.
|
||||
if (x * x + y * y <= 0.00000023841858f) {
|
||||
a->offsetX = 0.0f;
|
||||
a->offsetY = 0.0f;
|
||||
} else {
|
||||
a->offsetX = x;
|
||||
a->offsetY = y;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
int __fastcall Script_GetOffset(void *L) {
|
||||
Anim *a = SelfOf(L, Anim::s_translationClass);
|
||||
if (a == nullptr)
|
||||
return 0;
|
||||
Game::Lua::PushNumber(L, Game::InternalToPixel(a->offsetX));
|
||||
Game::Lua::PushNumber(L, Game::InternalToPixel(a->offsetY));
|
||||
return 2;
|
||||
}
|
||||
|
||||
// ---- Scale and Rotation origin (ReadOrigin) ----
|
||||
|
||||
Anim *OriginSelf(void *L) {
|
||||
Anim *a = static_cast<Anim *>(Resolve(L, 1, Anim::s_class));
|
||||
if (a != nullptr && a->kind != KIND_SCALE && a->kind != KIND_ROTATION) {
|
||||
// The type test of 4.3.4's Scale / Rotation SetOrigin.
|
||||
Game::Lua::Error(L, "Wrong object type for member function");
|
||||
return nullptr;
|
||||
}
|
||||
return a;
|
||||
}
|
||||
int __fastcall Script_SetOrigin(void *L) {
|
||||
Anim *a = OriginSelf(L);
|
||||
if (a == nullptr)
|
||||
return 0;
|
||||
if (!Game::Lua::IsString(L, 2) || !Game::Lua::IsNumber(L, 3) || !Game::Lua::IsNumber(L, 4)) {
|
||||
Game::Lua::Error(L, "Usage: %s:SetOrigin(point, offsetX, offsetY)", a->DisplayName());
|
||||
return 0;
|
||||
}
|
||||
int point = Offsets::FRAMEPOINT_CENTER;
|
||||
if (!reinterpret_cast<StringToPoint_t>(Offsets::FUN_STRING_TO_FRAME_POINT)(Game::Lua::ToString(L, 2), &point))
|
||||
point = Offsets::FRAMEPOINT_CENTER;
|
||||
a->originPoint = point;
|
||||
a->originX = Game::PixelToInternal(static_cast<float>(Game::Lua::ToNumber(L, 3)));
|
||||
a->originY = Game::PixelToInternal(static_cast<float>(Game::Lua::ToNumber(L, 4)));
|
||||
return 0;
|
||||
}
|
||||
// 4.3.4 pushes the stored offsets as they are, in layout units.
|
||||
int __fastcall Script_GetOrigin(void *L) {
|
||||
Anim *a = OriginSelf(L);
|
||||
if (a == nullptr)
|
||||
return 0;
|
||||
Game::Lua::PushString(L, reinterpret_cast<PointToString_t>(Offsets::FUN_FRAME_POINT_TO_STRING)(a->originPoint));
|
||||
Game::Lua::PushNumber(L, a->originX);
|
||||
Game::Lua::PushNumber(L, a->originY);
|
||||
return 3;
|
||||
}
|
||||
|
||||
// ---- Scale ----
|
||||
|
||||
int __fastcall Script_SetScale(void *L) {
|
||||
Anim *a = SelfOf(L, Anim::s_scaleClass);
|
||||
if (a == nullptr)
|
||||
return 0;
|
||||
if (!Game::Lua::IsNumber(L, 2) || !Game::Lua::IsNumber(L, 3)) {
|
||||
Game::Lua::Error(L, "Usage: %s:SetScale(x, y)", a->DisplayName());
|
||||
return 0;
|
||||
}
|
||||
// CSimpleScaleAnim::SetScale.
|
||||
const float x = static_cast<float>(Game::Lua::ToNumber(L, 2));
|
||||
const float y = static_cast<float>(Game::Lua::ToNumber(L, 3));
|
||||
a->scaleChangeX = 1.0f - (x >= 0.001f ? x : 0.001f);
|
||||
a->scaleChangeY = 1.0f - (y >= 0.001f ? y : 0.001f);
|
||||
return 0;
|
||||
}
|
||||
int __fastcall Script_GetScale(void *L) {
|
||||
Anim *a = SelfOf(L, Anim::s_scaleClass);
|
||||
if (a == nullptr)
|
||||
return 0;
|
||||
Game::Lua::PushNumber(L, 1.0f - a->scaleChangeX);
|
||||
Game::Lua::PushNumber(L, 1.0f - a->scaleChangeY);
|
||||
return 2;
|
||||
}
|
||||
|
||||
// ---- Rotation ----
|
||||
|
||||
int __fastcall Script_SetDegrees(void *L) {
|
||||
Anim *a = SelfOf(L, Anim::s_rotationClass);
|
||||
if (a != nullptr && NumberArg(L, 2, a, "Usage: %s:SetDegrees(degrees)"))
|
||||
a->radians = static_cast<float>(Game::Lua::ToNumber(L, 2) * 0.017453292f);
|
||||
return 0;
|
||||
}
|
||||
int __fastcall Script_GetDegrees(void *L) {
|
||||
Anim *a = SelfOf(L, Anim::s_rotationClass);
|
||||
if (a == nullptr)
|
||||
return 0;
|
||||
Game::Lua::PushNumber(L, a->radians * 57.29578f);
|
||||
return 1;
|
||||
}
|
||||
int __fastcall Script_SetRadians(void *L) {
|
||||
Anim *a = SelfOf(L, Anim::s_rotationClass);
|
||||
if (a != nullptr && NumberArg(L, 2, a, "Usage: %s:SetRadians(radians)"))
|
||||
a->radians = static_cast<float>(Game::Lua::ToNumber(L, 2));
|
||||
return 0;
|
||||
}
|
||||
int __fastcall Script_GetRadians(void *L) {
|
||||
Anim *a = SelfOf(L, Anim::s_rotationClass);
|
||||
if (a == nullptr)
|
||||
return 0;
|
||||
Game::Lua::PushNumber(L, a->radians);
|
||||
return 1;
|
||||
}
|
||||
|
||||
const Game::Lua::FrameMethodEntry kAnimMethods[] = {
|
||||
{"GetObjectType", &Script_GetObjectType},
|
||||
{"IsObjectType", &Script_IsObjectType},
|
||||
{"GetName", &Script_GetName},
|
||||
{"GetParent", &Script_GetParent},
|
||||
{"Play", &Script_Play},
|
||||
{"Pause", &Script_Pause},
|
||||
{"Stop", &Script_Stop},
|
||||
{"IsDone", &Script_IsDone},
|
||||
{"IsPlaying", &Script_IsPlaying},
|
||||
{"IsPaused", &Script_IsPaused},
|
||||
{"IsStopped", &Script_IsStopped},
|
||||
{"IsDelaying", &Script_IsDelaying},
|
||||
{"GetElapsed", &Script_GetElapsed},
|
||||
{"SetStartDelay", &Script_SetStartDelay},
|
||||
{"GetStartDelay", &Script_GetStartDelay},
|
||||
{"SetEndDelay", &Script_SetEndDelay},
|
||||
{"GetEndDelay", &Script_GetEndDelay},
|
||||
{"SetDuration", &Script_SetDuration},
|
||||
{"GetDuration", &Script_GetDuration},
|
||||
{"GetSmoothProgress", &Script_GetSmoothProgress},
|
||||
{"SetSmoothProgress", &Script_SetSmoothProgress},
|
||||
{"GetProgress", &Script_GetProgress},
|
||||
{"GetProgressWithDelay", &Script_GetProgressWithDelay},
|
||||
{"SetOrder", &Script_SetOrder},
|
||||
{"GetOrder", &Script_GetOrder},
|
||||
{"SetSmoothing", &Script_SetSmoothing},
|
||||
{"GetSmoothing", &Script_GetSmoothing},
|
||||
{"SetParent", &Script_SetParent},
|
||||
{"GetRegionParent", &Script_GetRegionParent},
|
||||
{"HasScript", &Script_HasScript},
|
||||
{"GetScript", &Script_GetScript},
|
||||
{"SetScript", &Script_SetScript},
|
||||
{"HookScript", &Script_HookScript},
|
||||
};
|
||||
const Game::Lua::FrameMethodEntry kAlphaMethods[] = {
|
||||
{"SetChange", &Script_SetChange},
|
||||
{"GetChange", &Script_GetChange},
|
||||
};
|
||||
const Game::Lua::FrameMethodEntry kTranslationMethods[] = {
|
||||
{"SetOffset", &Script_SetOffset},
|
||||
{"GetOffset", &Script_GetOffset},
|
||||
};
|
||||
const Game::Lua::FrameMethodEntry kScaleMethods[] = {
|
||||
{"SetOrigin", &Script_SetOrigin},
|
||||
{"GetOrigin", &Script_GetOrigin},
|
||||
{"SetScale", &Script_SetScale},
|
||||
{"GetScale", &Script_GetScale},
|
||||
};
|
||||
const Game::Lua::FrameMethodEntry kRotationMethods[] = {
|
||||
{"SetOrigin", &Script_SetOrigin}, {"GetOrigin", &Script_GetOrigin}, {"SetDegrees", &Script_SetDegrees},
|
||||
{"GetDegrees", &Script_GetDegrees}, {"SetRadians", &Script_SetRadians}, {"GetRadians", &Script_GetRadians},
|
||||
};
|
||||
|
||||
template <size_t N> constexpr int Count(const Game::Lua::FrameMethodEntry (&)[N]) { return static_cast<int>(N); }
|
||||
|
||||
} // namespace
|
||||
|
||||
Class Anim::s_class{"Animation", nullptr, kAnimScripts, 6, kAnimMethods, Count(kAnimMethods), 0, 0};
|
||||
Class Anim::s_alphaClass{"Alpha", &Anim::s_class, nullptr, 0, kAlphaMethods, Count(kAlphaMethods), 0, 0};
|
||||
Class Anim::s_translationClass{"Translation", &Anim::s_class, nullptr, 0, kTranslationMethods,
|
||||
Count(kTranslationMethods), 0, 0};
|
||||
Class Anim::s_scaleClass{"Scale", &Anim::s_class, nullptr, 0, kScaleMethods, Count(kScaleMethods), 0, 0};
|
||||
Class Anim::s_rotationClass{"Rotation", &Anim::s_class, nullptr, 0, kRotationMethods, Count(kRotationMethods), 0, 0};
|
||||
|
||||
// ---- AnimationGroup:CreateAnimation ------------------------------------------------------
|
||||
|
||||
int __fastcall Script_CreateAnimation(void *L) {
|
||||
Group *group = static_cast<Group *>(Resolve(L, 1, Group::s_class));
|
||||
if (group == nullptr)
|
||||
return 0;
|
||||
const char *type = Game::Lua::IsString(L, 2) ? Game::Lua::ToString(L, 2) : "Animation";
|
||||
const char *name = Game::Lua::IsString(L, 3) ? Game::Lua::ToString(L, 3) : nullptr;
|
||||
const void *templateNode = nullptr;
|
||||
if (Game::Lua::Type(L, 4) == Game::Lua::TYPE_STRING) {
|
||||
const char *inherits = Game::Lua::ToString(L, 4);
|
||||
templateNode = Xml::Template(inherits);
|
||||
if (templateNode == nullptr) {
|
||||
Game::Lua::Error(L, "%s:CreateAnimation(): Couldn't find inherited node \"%s\"", group->DisplayName(),
|
||||
inherits);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
Anim *anim = new Anim(group, Anim::KindOf(type), name);
|
||||
if (templateNode != nullptr) {
|
||||
Xml::LoadAnim(anim, templateNode, nullptr);
|
||||
anim->PostLoadXML();
|
||||
}
|
||||
if (anim->order == -1)
|
||||
anim->SetOrder(group->GetMaxAnimOrder(), false, true);
|
||||
group->NotifyAnimAdded(anim);
|
||||
Push(L, anim);
|
||||
return 1;
|
||||
}
|
||||
|
||||
} // namespace Animation
|
||||
@@ -0,0 +1,213 @@
|
||||
// This file is part of ClassicAPI.
|
||||
//
|
||||
// ClassicAPI is free software: you can redistribute it and/or modify it under the terms
|
||||
// of the GNU 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 General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License along with
|
||||
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "animation/Object.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
// 4.3.4's CSimpleAnimGroup and CSimpleAnim (and its Alpha, Translation,
|
||||
// Scale, Rotation and Path subclasses, and Path's CSimpleControlPoint), ported from the decompiled client
|
||||
// (wowdecomp15595 Engine/Source/Frame/CSimpleAnimGroup.cpp, CSimpleAnim.cpp).
|
||||
// Field and function names follow it; the comments say where 1.12 differs.
|
||||
namespace Animation {
|
||||
|
||||
class Anim;
|
||||
class ControlPoint;
|
||||
|
||||
enum LoopType { LOOP_NONE = 0, LOOP_REPEAT = 1, LOOP_BOUNCE = 2 };
|
||||
enum LoopState { STATE_NONE = 0, STATE_FORWARD = 1, STATE_REVERSE = 2 };
|
||||
|
||||
// m_flags.
|
||||
constexpr uint8_t GROUP_LOADING = 0x01;
|
||||
constexpr uint8_t GROUP_PENDING_FINISH = 0x02;
|
||||
constexpr uint8_t GROUP_PAUSED = 0x04;
|
||||
constexpr uint8_t GROUP_STOPPING = 0x08;
|
||||
constexpr uint8_t GROUP_IGNORE_THROTTLE = 0x10;
|
||||
|
||||
// Script indexes (Class::scriptNames order).
|
||||
enum GroupScript { G_ONLOAD, G_ONPLAY, G_ONPAUSE, G_ONSTOP, G_ONFINISHED, G_ONUPDATE, G_ONLOOP };
|
||||
enum AnimScript { A_ONLOAD, A_ONPLAY, A_ONPAUSE, A_ONSTOP, A_ONFINISHED, A_ONUPDATE };
|
||||
|
||||
class Group : public Object {
|
||||
public:
|
||||
static Class s_class;
|
||||
|
||||
// `region`: the 1.12 region (frame, texture or font string) it animates.
|
||||
Group(void *region, const char *name);
|
||||
~Group();
|
||||
|
||||
void *RegionObject() const { return parent; }
|
||||
|
||||
bool IsDone() const;
|
||||
bool IsPlaying() const { return loopState != STATE_NONE && !(flags & GROUP_PAUSED); }
|
||||
bool Play(bool reverse);
|
||||
void Pause();
|
||||
void Stop(bool requested);
|
||||
void Finish();
|
||||
bool OnUpdate(float elapsedSec);
|
||||
int GetMaxAnimOrder() const;
|
||||
bool HasAlphaAnim() const;
|
||||
bool HasPositionAnim() const;
|
||||
|
||||
void NotifyAnimAdded(Anim *anim);
|
||||
void NotifyOrderChanged(Anim *anim, int oldOrder);
|
||||
void NotifyAnimRemoved(Anim *anim);
|
||||
void SortAnimations();
|
||||
void ComputeDuration();
|
||||
// XML: 4.3.4's PostLoadXML - every animation's, then sort, then OnLoad.
|
||||
void PostLoadXML();
|
||||
|
||||
LoopType loopType = LOOP_NONE;
|
||||
float duration = 0.0f;
|
||||
float initialOffsetX = 0.0f, initialOffsetY = 0.0f; // layout units
|
||||
LoopState loopState = STATE_NONE;
|
||||
uint8_t flags = 0;
|
||||
int currentOrder = -1;
|
||||
float elapsed = 0.0f;
|
||||
float progress = 0.0f;
|
||||
std::vector<Anim *> animations; // m_animations, creation order
|
||||
std::vector<std::vector<Anim *>> animLists; // m_animLists, by order
|
||||
|
||||
private:
|
||||
std::vector<Anim *> *FindAnimList(int order);
|
||||
std::vector<Anim *> *RegisterAnimList(int order);
|
||||
bool AddAnimListNode(std::vector<Anim *> *list, Anim *anim);
|
||||
bool RemoveAnimListNode(std::vector<Anim *> *list, Anim *anim);
|
||||
bool AdvanceLoopState(float elapsedSec, float remaining);
|
||||
bool DoGroupUpdateWork(float elapsedSec);
|
||||
void ResetAnims();
|
||||
};
|
||||
|
||||
enum AnimKind { KIND_ANIMATION, KIND_ALPHA, KIND_TRANSLATION, KIND_SCALE, KIND_ROTATION, KIND_PATH };
|
||||
|
||||
class Anim : public Object {
|
||||
public:
|
||||
static Class s_class; // "Animation"
|
||||
static Class s_alphaClass; // "Alpha"
|
||||
static Class s_translationClass; // "Translation"
|
||||
static Class s_scaleClass; // "Scale"
|
||||
static Class s_rotationClass; // "Rotation"
|
||||
static Class s_pathClass; // "Path"
|
||||
// The class of a CreateAnimation / XML type name; Animation for any
|
||||
// other (4.3.4's CreateAnimation falls back to it).
|
||||
static AnimKind KindOf(const char *typeName);
|
||||
|
||||
Anim(Group *group, AnimKind kind, const char *name);
|
||||
~Anim();
|
||||
|
||||
Group *GetGroup() const { return static_cast<Group *>(parent); }
|
||||
void *GetRegionParent() const { return parent != nullptr ? GetGroup()->RegionObject() : nullptr; }
|
||||
|
||||
bool Play();
|
||||
void Pause();
|
||||
void Stop(bool requested);
|
||||
bool IsDelaying() const;
|
||||
bool OnUpdate(float elapsedSec, float &consumed);
|
||||
void Apply(float progress);
|
||||
void SetStartDelay(float delay, bool notify);
|
||||
void SetEndDelay(float delay, bool notify);
|
||||
void SetDuration(float value, bool notify);
|
||||
void SetOrder(int value, bool notify, bool wrap);
|
||||
void SetSmoothing(float in, float out);
|
||||
bool GetSmoothing(float &in, float &out) const;
|
||||
bool ChangeParent(Group *group);
|
||||
// XML: 4.3.4's PostLoadXML - OnLoad.
|
||||
void PostLoadXML();
|
||||
|
||||
AnimKind kind;
|
||||
float startDelay = 0.0f;
|
||||
float endDelay = 0.0f;
|
||||
float duration = 0.0f;
|
||||
float frameElapsed = 0.0f;
|
||||
float elapsed = 0.0f;
|
||||
float progressWithDelay = 0.0f;
|
||||
float progress = 0.0f;
|
||||
float smoothProgress = 0.0f;
|
||||
float orderPadding = 0.0f;
|
||||
int order = -1;
|
||||
uint8_t flags = 0;
|
||||
int playState = 0; // 0 stopped, 1 playing, 2 paused
|
||||
int loopState = STATE_NONE;
|
||||
void *target = nullptr; // m_target, resolved from targetName on Play
|
||||
char targetName[128] = {}; // m_targetName
|
||||
bool hasSmoother = false;
|
||||
float smoothIn = 0.0f, smoothOut = 0.0f;
|
||||
|
||||
// Alpha: m_change, -255..255.
|
||||
int16_t change = 0;
|
||||
// Translation: the offset; Scale: the scale and origin; Rotation: the
|
||||
// angle and origin. Offsets in layout units, as 4.3.4 keeps them.
|
||||
float offsetX = 0.0f, offsetY = 0.0f;
|
||||
float scaleChangeX = 0.0f, scaleChangeY = 0.0f; // m_scaleChange: 1 - scale
|
||||
float radians = 0.0f;
|
||||
int originPoint = 4; // FRAMEPOINT_CENTER
|
||||
float originX = 0.0f, originY = 0.0f;
|
||||
|
||||
// Path (CSimplePathAnim, Path.cpp): the control points it owns in link
|
||||
// order (m_controlPoints), the same sorted by order (m_sortedPoints),
|
||||
// and m_curve (false NONE, true SMOOTH).
|
||||
std::vector<ControlPoint *> controlPoints;
|
||||
std::vector<ControlPoint *> sortedPoints;
|
||||
bool curve = false;
|
||||
void BuildSpline();
|
||||
void UpdateControlPointPositions();
|
||||
int FindControlPoint(int order) const;
|
||||
int GetMaxControlPointOrder() const;
|
||||
int RegisterSplineControlPoint(ControlPoint *point);
|
||||
void NotifyControlPointAdded(ControlPoint *point);
|
||||
void NotifyControlPointRemoved(ControlPoint *point);
|
||||
void NotifyControlPointOrderChanged(ControlPoint *point);
|
||||
void ApplyPath(float progress);
|
||||
|
||||
private:
|
||||
float UpdateProgress(float elapsedSec);
|
||||
};
|
||||
|
||||
// CSimpleControlPoint: a point of a Path, an offset from where the region
|
||||
// is, in layout units.
|
||||
class ControlPoint : public Object {
|
||||
public:
|
||||
static Class s_class; // "ControlPoint"
|
||||
|
||||
// Links the point at the end of the path's points.
|
||||
ControlPoint(Anim *path, const char *name);
|
||||
~ControlPoint();
|
||||
|
||||
Anim *GetPath() const { return static_cast<Anim *>(parent); }
|
||||
bool ChangeParent(Anim *path);
|
||||
void SetOffset(float x, float y);
|
||||
void SetOrder(int value, bool notify, bool wrap);
|
||||
|
||||
float offsetX = 0.0f, offsetY = 0.0f;
|
||||
float position = 0.0f; // m_position: the path progress the point is at
|
||||
int order = -1;
|
||||
};
|
||||
|
||||
// 4.3.4's s_frameInterval: progress steps at most this often unless the
|
||||
// group ignores the framerate throttle. 1/30 s until SetMaxAnimFramerate
|
||||
// (Framerate.cpp) changes it.
|
||||
extern float g_frameInterval;
|
||||
|
||||
// AnimationGroup:CreateAnimation (Anim.cpp, where the animation classes are).
|
||||
int __fastcall Script_CreateAnimation(void *L);
|
||||
|
||||
const char *LoopTypeToString(LoopType type);
|
||||
bool StringToLoopType(const char *text, LoopType &type);
|
||||
const char *LoopStateToString(int state);
|
||||
bool StringToSmoothWeights(const char *text, float &in, float &out);
|
||||
const char *SmoothWeightsToString(float in, float out);
|
||||
|
||||
} // namespace Animation
|
||||
@@ -0,0 +1,61 @@
|
||||
// This file is part of ClassicAPI.
|
||||
//
|
||||
// ClassicAPI is free software: you can redistribute it and/or modify it under the terms
|
||||
// of the GNU 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 General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License along with
|
||||
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
|
||||
// `SetMaxAnimFramerate(framesPerSec)` / `GetMaxAnimFramerate()` - 4.3.4's
|
||||
// globals over CSimpleAnim::s_frameInterval (SimpleFrameScript_Scripts.cpp),
|
||||
// the throttle that Anim::UpdateProgress steps progress by. The setter stores
|
||||
// 1 / fps unchecked, as 4.3.4 does: 0 stores infinity, so progress stops
|
||||
// stepping until the animation ends.
|
||||
|
||||
#include "Classes.h"
|
||||
#include "Game.h"
|
||||
|
||||
namespace Animation {
|
||||
|
||||
float g_frameInterval = 1.0f / 30.0f;
|
||||
|
||||
namespace {
|
||||
|
||||
int __fastcall Script_SetMaxAnimFramerate(void *L) {
|
||||
if (!Game::Lua::IsNumber(L, 1)) {
|
||||
Game::Lua::Error(L, "Usage: SetMaxFramerate(framesPerSec)");
|
||||
return 0;
|
||||
}
|
||||
g_frameInterval = 1.0f / static_cast<float>(Game::Lua::ToNumber(L, 1));
|
||||
return 0;
|
||||
}
|
||||
|
||||
int __fastcall Script_GetMaxAnimFramerate(void *L) {
|
||||
Game::Lua::PushNumber(L, 1.0f / g_frameInterval);
|
||||
return 1;
|
||||
}
|
||||
|
||||
const Game::Doc::Field kSetArgs[] = {Game::Doc::Req("framesPerSec", "number")};
|
||||
const Game::Doc::Field kGetRets[] = {Game::Doc::Req("framesPerSec", "number")};
|
||||
|
||||
const Game::Doc::Function kSet{"Sets how many times per second animations step their progress.", kSetArgs, {},
|
||||
"AnimationGlobals"};
|
||||
const Game::Doc::Function kGet{"Returns how many times per second animations step their progress.", {}, kGetRets,
|
||||
"AnimationGlobals"};
|
||||
|
||||
void RegisterLuaFunctions() {
|
||||
Game::Lua::RegisterGlobalFunction("SetMaxAnimFramerate", &Script_SetMaxAnimFramerate, &kSet);
|
||||
Game::Lua::RegisterGlobalFunction("GetMaxAnimFramerate", &Script_GetMaxAnimFramerate, &kGet);
|
||||
}
|
||||
|
||||
const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
|
||||
|
||||
} // namespace
|
||||
|
||||
} // namespace Animation
|
||||
@@ -0,0 +1,676 @@
|
||||
// This file is part of ClassicAPI.
|
||||
//
|
||||
// ClassicAPI is free software: you can redistribute it and/or modify it under the terms
|
||||
// of the GNU 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 General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License along with
|
||||
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
// 4.3.4's CSimpleAnimGroup (wowdecomp15595 CSimpleAnimGroup.cpp and
|
||||
// CSimpleAnimGroup_Scripts.cpp), on Animation::Object.
|
||||
|
||||
#include "animation/Classes.h"
|
||||
#include "animation/Region.h"
|
||||
|
||||
#include "Game.h"
|
||||
#include "Offsets.h"
|
||||
#include "baselib/Ascii.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
namespace Animation {
|
||||
|
||||
namespace {
|
||||
|
||||
const char *const kGroupScripts[] = {"onload", "onplay", "onpause", "onstop", "onfinished", "onupdate", "onloop"};
|
||||
|
||||
} // namespace
|
||||
|
||||
// ---- Construction ---------------------------------------------------------------
|
||||
|
||||
Group::Group(void *region, const char *name) : Object(s_class, region, name) {
|
||||
if (region != nullptr)
|
||||
Region::RegisterGroup(region, this);
|
||||
}
|
||||
|
||||
Group::~Group() {
|
||||
for (Anim *anim : animations)
|
||||
delete anim;
|
||||
}
|
||||
|
||||
// ---- State --------------------------------------------------------------------
|
||||
|
||||
bool Group::IsDone() const {
|
||||
if (duration <= 0.0001f)
|
||||
return true;
|
||||
if (loopType == LOOP_REPEAT || loopType == LOOP_BOUNCE)
|
||||
return false;
|
||||
if (loopState == STATE_FORWARD || loopState == STATE_REVERSE)
|
||||
return false;
|
||||
return progress >= 1.0f;
|
||||
}
|
||||
|
||||
void Group::Finish() {
|
||||
if (!IsDone() && loopState != STATE_NONE)
|
||||
flags |= GROUP_PENDING_FINISH;
|
||||
}
|
||||
|
||||
int Group::GetMaxAnimOrder() const {
|
||||
if (animLists.empty())
|
||||
return -1;
|
||||
return animLists.back().front()->order;
|
||||
}
|
||||
|
||||
bool Group::HasAlphaAnim() const {
|
||||
for (const Anim *anim : animations)
|
||||
if (anim->kind == KIND_ALPHA)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
bool Group::HasPositionAnim() const {
|
||||
for (const Anim *anim : animations)
|
||||
if (anim->kind != KIND_ALPHA)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
// ---- Order lists ----------------------------------------------------------------
|
||||
|
||||
std::vector<Anim *> *Group::FindAnimList(int order) {
|
||||
if (order == -1)
|
||||
return nullptr;
|
||||
int low = 0;
|
||||
int high = static_cast<int>(animLists.size()) - 1;
|
||||
while (low <= high) {
|
||||
const int middle = static_cast<int>(static_cast<unsigned>(high + low) >> 1);
|
||||
std::vector<Anim *> &list = animLists[middle];
|
||||
if (!list.empty()) {
|
||||
const int listOrder = list.front()->order;
|
||||
if (listOrder < order)
|
||||
low = middle + 1;
|
||||
else if (listOrder > order)
|
||||
high = middle - 1;
|
||||
else
|
||||
return &list;
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
std::vector<Anim *> *Group::RegisterAnimList(int order) {
|
||||
if (order == -1)
|
||||
return nullptr;
|
||||
const size_t count = animLists.size();
|
||||
if (count == 0) {
|
||||
animLists.emplace_back();
|
||||
return &animLists.back();
|
||||
}
|
||||
size_t index = count;
|
||||
for (size_t i = 0; i < count; ++i) {
|
||||
std::vector<Anim *> &list = animLists[i];
|
||||
if (list.empty())
|
||||
return &list;
|
||||
const int listOrder = list.front()->order;
|
||||
if (order == listOrder)
|
||||
return &list;
|
||||
if (order < listOrder) {
|
||||
index = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
animLists.insert(animLists.begin() + static_cast<ptrdiff_t>(index), std::vector<Anim *>());
|
||||
return &animLists[index];
|
||||
}
|
||||
|
||||
bool Group::AddAnimListNode(std::vector<Anim *> *list, Anim *anim) {
|
||||
if (list == nullptr)
|
||||
return false;
|
||||
list->push_back(anim);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Group::RemoveAnimListNode(std::vector<Anim *> *list, Anim *anim) {
|
||||
if (list == nullptr)
|
||||
return false;
|
||||
const auto it = std::find(list->begin(), list->end(), anim);
|
||||
if (it == list->end())
|
||||
return false;
|
||||
list->erase(it);
|
||||
if (list->empty())
|
||||
SortAnimations();
|
||||
return true;
|
||||
}
|
||||
|
||||
void Group::ComputeDuration() {
|
||||
duration = 0.0f;
|
||||
for (std::vector<Anim *> &list : animLists) {
|
||||
float span = 0.0f;
|
||||
for (const Anim *anim : list) {
|
||||
const float total = anim->duration + anim->endDelay + anim->startDelay;
|
||||
if (total > span)
|
||||
span = total;
|
||||
}
|
||||
for (Anim *anim : list)
|
||||
anim->orderPadding = span - (anim->duration + anim->endDelay + anim->startDelay);
|
||||
duration += span;
|
||||
}
|
||||
}
|
||||
|
||||
void Group::NotifyAnimAdded(Anim *anim) {
|
||||
if (anim == nullptr)
|
||||
return;
|
||||
// m_animations.LinkToTail: an animation already in the list moves to its tail.
|
||||
animations.erase(std::remove(animations.begin(), animations.end(), anim), animations.end());
|
||||
animations.push_back(anim);
|
||||
if (AddAnimListNode(RegisterAnimList(anim->order), anim))
|
||||
ComputeDuration();
|
||||
}
|
||||
|
||||
void Group::NotifyOrderChanged(Anim *anim, int oldOrder) {
|
||||
if (anim == nullptr)
|
||||
return;
|
||||
if (RemoveAnimListNode(FindAnimList(oldOrder), anim))
|
||||
if (AddAnimListNode(RegisterAnimList(anim->order), anim))
|
||||
ComputeDuration();
|
||||
}
|
||||
|
||||
void Group::NotifyAnimRemoved(Anim *anim) {
|
||||
if (anim == nullptr)
|
||||
return;
|
||||
animations.erase(std::remove(animations.begin(), animations.end(), anim), animations.end());
|
||||
std::vector<Anim *> *list = FindAnimList(anim->order);
|
||||
if (RemoveAnimListNode(list, anim)) {
|
||||
// RemoveAnimListNode sorts when the list emptied; the list may be gone.
|
||||
ComputeDuration();
|
||||
}
|
||||
}
|
||||
|
||||
void Group::SortAnimations() {
|
||||
if (loopState == STATE_NONE || (flags & GROUP_PAUSED)) {
|
||||
loopState = STATE_NONE;
|
||||
flags &= 0xF0;
|
||||
currentOrder = -1;
|
||||
elapsed = 0.0f;
|
||||
progress = 0.0f;
|
||||
} else {
|
||||
Stop(false);
|
||||
}
|
||||
if (animations.empty()) {
|
||||
animLists.clear();
|
||||
return;
|
||||
}
|
||||
for (std::vector<Anim *> &list : animLists)
|
||||
list.clear();
|
||||
int nextOrder = 0;
|
||||
for (Anim *anim : animations) {
|
||||
int order = anim->order;
|
||||
if (order == -1) {
|
||||
order = nextOrder++;
|
||||
anim->order = order < 0 ? 0 : order;
|
||||
} else {
|
||||
nextOrder = order + 1;
|
||||
}
|
||||
if (nextOrder > 99)
|
||||
nextOrder = 0;
|
||||
AddAnimListNode(RegisterAnimList(order), anim);
|
||||
}
|
||||
while (!animLists.empty() && animLists.back().empty())
|
||||
animLists.pop_back();
|
||||
}
|
||||
|
||||
void Group::ResetAnims() {
|
||||
for (Anim *anim : animations) {
|
||||
anim->loopState = loopState > 0 && loopState <= 2 ? loopState : 0;
|
||||
anim->playState = 0;
|
||||
anim->elapsed = 0.0f;
|
||||
anim->progressWithDelay = 0.0f;
|
||||
anim->progress = 0.0f;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Playback --------------------------------------------------------------------
|
||||
|
||||
void Group::Pause() {
|
||||
if (loopState == STATE_NONE || (flags & GROUP_PAUSED))
|
||||
return;
|
||||
flags |= GROUP_PAUSED;
|
||||
const std::vector<Anim *> list = animLists[currentOrder];
|
||||
for (Anim *anim : list)
|
||||
anim->Pause();
|
||||
RunScript(G_ONPAUSE, 0);
|
||||
}
|
||||
|
||||
void Group::Stop(bool requested) {
|
||||
if (loopState == STATE_NONE || (flags & GROUP_STOPPING))
|
||||
return;
|
||||
flags |= GROUP_STOPPING;
|
||||
const std::vector<Anim *> list = animLists[currentOrder];
|
||||
for (Anim *anim : list)
|
||||
anim->Stop(requested);
|
||||
Region::NotifyEnd(RegionObject(), this);
|
||||
flags &= 0xF0;
|
||||
loopState = STATE_NONE;
|
||||
currentOrder = -1;
|
||||
elapsed = 0.0f;
|
||||
progress = 0.0f;
|
||||
if (HasScript(G_ONSTOP)) {
|
||||
Game::Lua::PushBool(Game::Lua::State(), requested);
|
||||
RunScript(G_ONSTOP, 1);
|
||||
}
|
||||
}
|
||||
|
||||
bool Group::AdvanceLoopState(float /*elapsedSec*/, float /*remaining*/) {
|
||||
const int count = static_cast<int>(animLists.size());
|
||||
const bool reverse = loopState == STATE_REVERSE;
|
||||
const int step = reverse ? -1 : 1;
|
||||
const int first = reverse ? count - 1 : 0;
|
||||
const int end = reverse ? -1 : count;
|
||||
|
||||
currentOrder += step;
|
||||
if (currentOrder == end) {
|
||||
if (loopType == LOOP_NONE || (flags & GROUP_PENDING_FINISH))
|
||||
return true;
|
||||
if (loopType == LOOP_BOUNCE) {
|
||||
loopState = static_cast<LoopState>(!reverse + 1);
|
||||
currentOrder -= step;
|
||||
} else {
|
||||
currentOrder = first;
|
||||
}
|
||||
elapsed = 0.0f;
|
||||
progress = 0.0f;
|
||||
ResetAnims();
|
||||
if (HasScript(G_ONLOOP)) {
|
||||
Game::Lua::PushString(Game::Lua::State(), LoopStateToString(loopState));
|
||||
RunScript(G_ONLOOP, 1);
|
||||
}
|
||||
if (loopState == STATE_NONE || (flags & GROUP_PAUSED))
|
||||
return true;
|
||||
}
|
||||
const std::vector<Anim *> list = animLists[currentOrder];
|
||||
for (Anim *anim : list)
|
||||
anim->Play();
|
||||
return false;
|
||||
}
|
||||
|
||||
bool Group::DoGroupUpdateWork(float elapsedSec) {
|
||||
float remaining = elapsedSec < 0.0f ? 0.0f : (elapsedSec >= 60.0f ? 60.0f : elapsedSec);
|
||||
while (true) {
|
||||
for (Anim *anim : animLists[currentOrder]) {
|
||||
void *region = anim->GetRegionParent();
|
||||
if (region != nullptr)
|
||||
Region::PreOnAnimUpdate(region);
|
||||
}
|
||||
for (int i = 0; i < currentOrder; ++i)
|
||||
for (Anim *anim : animLists[i])
|
||||
anim->Apply(1.0f);
|
||||
|
||||
float maxConsumed = 0.0f;
|
||||
bool finished = true;
|
||||
const std::vector<Anim *> list = animLists[currentOrder];
|
||||
for (Anim *anim : list) {
|
||||
float consumed;
|
||||
finished = anim->OnUpdate(remaining, consumed) && finished;
|
||||
if (consumed > maxConsumed)
|
||||
maxConsumed = consumed;
|
||||
}
|
||||
|
||||
if (!(flags & GROUP_PAUSED) && loopState != STATE_NONE) {
|
||||
remaining -= maxConsumed;
|
||||
elapsed += maxConsumed;
|
||||
progress = elapsed < duration ? elapsed / duration : 1.0f;
|
||||
if (finished && AdvanceLoopState(elapsedSec, remaining))
|
||||
return true;
|
||||
}
|
||||
|
||||
if (remaining <= 0.0001f || IsDone() || loopState == STATE_NONE || (flags & GROUP_PAUSED))
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool Group::OnUpdate(float elapsedSec) {
|
||||
if (IsDone() || loopState == STATE_NONE)
|
||||
return true;
|
||||
const bool done = DoGroupUpdateWork(elapsedSec);
|
||||
if (HasScript(G_ONUPDATE)) {
|
||||
Game::Lua::PushNumber(Game::Lua::State(), elapsedSec);
|
||||
RunScript(G_ONUPDATE, 1);
|
||||
}
|
||||
if (done) {
|
||||
Region::NotifyEnd(RegionObject(), this);
|
||||
const bool requested = (flags & GROUP_PENDING_FINISH) != 0;
|
||||
loopState = STATE_NONE;
|
||||
flags &= 0xF0;
|
||||
currentOrder = -1;
|
||||
elapsed = 0.0f;
|
||||
progress = 0.0f;
|
||||
if (HasScript(G_ONFINISHED)) {
|
||||
Game::Lua::PushBool(Game::Lua::State(), requested);
|
||||
RunScript(G_ONFINISHED, 1);
|
||||
}
|
||||
}
|
||||
return IsDone();
|
||||
}
|
||||
|
||||
bool Group::Play(bool reverse) {
|
||||
if (animations.empty())
|
||||
return false;
|
||||
if (loopState != STATE_NONE && !(flags & GROUP_PAUSED))
|
||||
return true;
|
||||
if (flags & GROUP_PAUSED) {
|
||||
flags &= ~GROUP_PAUSED;
|
||||
} else {
|
||||
flags &= 0xF0;
|
||||
loopState = STATE_NONE;
|
||||
currentOrder = reverse ? 0x7FFF : -1;
|
||||
elapsed = 0.0f;
|
||||
progress = 0.0f;
|
||||
}
|
||||
RunScript(G_ONPLAY, 0);
|
||||
const int count = static_cast<int>(animLists.size());
|
||||
if (count > 0) {
|
||||
if (currentOrder < 0 || currentOrder >= count) {
|
||||
if (currentOrder < 0) {
|
||||
loopState = STATE_FORWARD;
|
||||
currentOrder = 0;
|
||||
} else {
|
||||
loopState = STATE_REVERSE;
|
||||
currentOrder = count - 1;
|
||||
}
|
||||
ResetAnims();
|
||||
}
|
||||
const std::vector<Anim *> list = animLists[currentOrder];
|
||||
for (Anim *anim : list)
|
||||
anim->Play();
|
||||
Region::NotifyBegin(RegionObject(), this);
|
||||
}
|
||||
OnUpdate(0.0f);
|
||||
return true;
|
||||
}
|
||||
|
||||
void Group::PostLoadXML() {
|
||||
flags &= ~GROUP_LOADING;
|
||||
const std::vector<Anim *> list = animations;
|
||||
for (Anim *anim : list)
|
||||
anim->PostLoadXML();
|
||||
SortAnimations();
|
||||
ComputeDuration();
|
||||
RunScript(G_ONLOAD, 0);
|
||||
}
|
||||
|
||||
// ---- Strings ----------------------------------------------------------------------
|
||||
|
||||
namespace {
|
||||
|
||||
struct Named {
|
||||
int value;
|
||||
const char *name;
|
||||
};
|
||||
const Named kLoopTypes[] = {{LOOP_NONE, "NONE"}, {LOOP_REPEAT, "REPEAT"}, {LOOP_BOUNCE, "BOUNCE"}};
|
||||
const Named kLoopStates[] = {{STATE_NONE, "NONE"}, {STATE_FORWARD, "FORWARD"}, {STATE_REVERSE, "REVERSE"}};
|
||||
|
||||
struct Weights {
|
||||
float in, out;
|
||||
const char *name;
|
||||
};
|
||||
const Weights kSmoothWeights[] = {
|
||||
{0.0f, 0.0f, "NONE"}, {1.0f, 0.0f, "IN"}, {0.0f, 1.0f, "OUT"}, {1.0f, 1.0f, "IN_OUT"}, {1.0f, 1.0f, "OUT_IN"},
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
const char *LoopTypeToString(LoopType type) {
|
||||
for (const Named &n : kLoopTypes)
|
||||
if (n.value == type)
|
||||
return n.name;
|
||||
return "UNKNOWN";
|
||||
}
|
||||
|
||||
bool StringToLoopType(const char *text, LoopType &type) {
|
||||
for (const Named &n : kLoopTypes)
|
||||
if (text != nullptr && Ascii::EqualCI(n.name, text)) {
|
||||
type = static_cast<LoopType>(n.value);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const char *LoopStateToString(int state) {
|
||||
for (const Named &n : kLoopStates)
|
||||
if (n.value == state)
|
||||
return n.name;
|
||||
return "UNKNOWN";
|
||||
}
|
||||
|
||||
bool StringToSmoothWeights(const char *text, float &in, float &out) {
|
||||
for (const Weights &w : kSmoothWeights)
|
||||
if (text != nullptr && Ascii::EqualCI(w.name, text)) {
|
||||
in = w.in;
|
||||
out = w.out;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const char *SmoothWeightsToString(float in, float out) {
|
||||
for (const Weights &w : kSmoothWeights)
|
||||
if (std::fabs(in - w.in) < 0.001f && std::fabs(out - w.out) < 0.001f)
|
||||
return w.name;
|
||||
return "UNKNOWN";
|
||||
}
|
||||
|
||||
// ---- Lua methods (CSimpleAnimGroup_Scripts.cpp) -------------------------------
|
||||
|
||||
namespace {
|
||||
|
||||
Group *Self(void *L) { return static_cast<Group *>(Resolve(L, 1, Group::s_class)); }
|
||||
|
||||
using LooseBool_t = int(__fastcall *)(void *L, int idx, int defaultValue);
|
||||
bool LooseBool(void *L, int idx, int dflt) {
|
||||
return reinterpret_cast<LooseBool_t>(Offsets::FUN_LUA_TO_BOOLEAN_LOOSE)(L, idx, dflt) != 0;
|
||||
}
|
||||
|
||||
int __fastcall Script_Play(void *L) {
|
||||
if (Group *g = Self(L))
|
||||
g->Play(LooseBool(L, 2, 0));
|
||||
return 0;
|
||||
}
|
||||
int __fastcall Script_Pause(void *L) {
|
||||
if (Group *g = Self(L))
|
||||
g->Pause();
|
||||
return 0;
|
||||
}
|
||||
int __fastcall Script_Stop(void *L) {
|
||||
if (Group *g = Self(L))
|
||||
g->Stop(true);
|
||||
return 0;
|
||||
}
|
||||
int __fastcall Script_Finish(void *L) {
|
||||
if (Group *g = Self(L))
|
||||
g->Finish();
|
||||
return 0;
|
||||
}
|
||||
int __fastcall Script_GetProgress(void *L) {
|
||||
Group *g = Self(L);
|
||||
if (g == nullptr)
|
||||
return 0;
|
||||
Game::Lua::PushNumber(L, g->elapsed / g->duration);
|
||||
return 1;
|
||||
}
|
||||
int __fastcall Script_IsDone(void *L) {
|
||||
Group *g = Self(L);
|
||||
if (g == nullptr)
|
||||
return 0;
|
||||
Game::Lua::PushBool(L, g->IsDone());
|
||||
return 1;
|
||||
}
|
||||
int __fastcall Script_IsPlaying(void *L) {
|
||||
Group *g = Self(L);
|
||||
if (g == nullptr)
|
||||
return 0;
|
||||
Game::Lua::PushBool(L, g->IsPlaying());
|
||||
return 1;
|
||||
}
|
||||
int __fastcall Script_IsPaused(void *L) {
|
||||
Group *g = Self(L);
|
||||
if (g == nullptr)
|
||||
return 0;
|
||||
Game::Lua::PushBool(L, (g->flags & GROUP_PAUSED) != 0);
|
||||
return 1;
|
||||
}
|
||||
int __fastcall Script_IsPendingFinish(void *L) {
|
||||
Group *g = Self(L);
|
||||
if (g == nullptr)
|
||||
return 0;
|
||||
Game::Lua::PushBool(L, (g->flags & GROUP_PENDING_FINISH) != 0);
|
||||
return 1;
|
||||
}
|
||||
int __fastcall Script_GetDuration(void *L) {
|
||||
Group *g = Self(L);
|
||||
if (g == nullptr)
|
||||
return 0;
|
||||
Game::Lua::PushNumber(L, g->duration);
|
||||
return 1;
|
||||
}
|
||||
int __fastcall Script_SetLooping(void *L) {
|
||||
Group *g = Self(L);
|
||||
if (g == nullptr)
|
||||
return 0;
|
||||
if (!Game::Lua::IsString(L, 2)) {
|
||||
Game::Lua::Error(L, "Usage: %s:SetLooping(\"loopType\")", g->DisplayName());
|
||||
return 0;
|
||||
}
|
||||
LoopType type;
|
||||
if (StringToLoopType(Game::Lua::ToString(L, 2), type)) {
|
||||
g->loopType = type;
|
||||
return 0;
|
||||
}
|
||||
Game::Lua::Error(L, "%s:SetLooping(): Unknown loop type specified", g->DisplayName());
|
||||
return 0;
|
||||
}
|
||||
int __fastcall Script_GetLooping(void *L) {
|
||||
Group *g = Self(L);
|
||||
if (g == nullptr)
|
||||
return 0;
|
||||
Game::Lua::PushString(L, LoopTypeToString(g->loopType));
|
||||
return 1;
|
||||
}
|
||||
int __fastcall Script_GetLoopState(void *L) {
|
||||
Group *g = Self(L);
|
||||
if (g == nullptr)
|
||||
return 0;
|
||||
Game::Lua::PushString(L, LoopStateToString(g->loopState));
|
||||
return 1;
|
||||
}
|
||||
int __fastcall Script_GetMaxOrder(void *L) {
|
||||
Group *g = Self(L);
|
||||
if (g == nullptr)
|
||||
return 0;
|
||||
Game::Lua::PushNumber(L, g->GetMaxAnimOrder() + 1);
|
||||
return 1;
|
||||
}
|
||||
int __fastcall Script_SetInitialOffset(void *L) {
|
||||
Group *g = Self(L);
|
||||
if (g == nullptr)
|
||||
return 0;
|
||||
if (!Game::Lua::IsNumber(L, 2) || !Game::Lua::IsNumber(L, 3)) {
|
||||
Game::Lua::Error(L, "Usage: %s:SetInitialOffset(x, y)", g->DisplayName());
|
||||
return 0;
|
||||
}
|
||||
const float x = Game::PixelToInternal(static_cast<float>(Game::Lua::ToNumber(L, 2)));
|
||||
const float y = Game::PixelToInternal(static_cast<float>(Game::Lua::ToNumber(L, 3)));
|
||||
// 4.3.4's SetInitialOffset: a near-zero offset is zero.
|
||||
if (x * x + y * y <= 0.00000023841858f) {
|
||||
g->initialOffsetX = 0.0f;
|
||||
g->initialOffsetY = 0.0f;
|
||||
} else {
|
||||
g->initialOffsetX = x;
|
||||
g->initialOffsetY = y;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
int __fastcall Script_GetInitialOffset(void *L) {
|
||||
Group *g = Self(L);
|
||||
if (g == nullptr)
|
||||
return 0;
|
||||
Game::Lua::PushNumber(L, Game::InternalToPixel(g->initialOffsetX));
|
||||
Game::Lua::PushNumber(L, Game::InternalToPixel(g->initialOffsetY));
|
||||
return 2;
|
||||
}
|
||||
int __fastcall Script_GetAnimations(void *L) {
|
||||
Group *g = Self(L);
|
||||
if (g == nullptr)
|
||||
return 0;
|
||||
const int count = static_cast<int>(g->animations.size());
|
||||
if (!Game::Lua::CheckStack(L, count)) {
|
||||
Game::Lua::Error(L, "%s:GetAnimations(): Stack overflow", g->DisplayName());
|
||||
return 0;
|
||||
}
|
||||
for (Anim *anim : g->animations)
|
||||
Push(L, anim);
|
||||
return count;
|
||||
}
|
||||
int __fastcall Script_SetIgnoreFramerateThrottle(void *L) {
|
||||
Group *g = Self(L);
|
||||
if (g == nullptr)
|
||||
return 0;
|
||||
if (LooseBool(L, 2, 0))
|
||||
g->flags |= GROUP_IGNORE_THROTTLE;
|
||||
else
|
||||
g->flags &= ~GROUP_IGNORE_THROTTLE;
|
||||
return 0;
|
||||
}
|
||||
int __fastcall Script_GetIgnoreFramerateThrottle(void *L) {
|
||||
Group *g = Self(L);
|
||||
if (g == nullptr)
|
||||
return 0;
|
||||
if (g->flags & GROUP_IGNORE_THROTTLE)
|
||||
Game::Lua::PushNumber(L, 1.0);
|
||||
else
|
||||
Game::Lua::PushNil(L);
|
||||
return 1;
|
||||
}
|
||||
|
||||
const Game::Lua::FrameMethodEntry kMethods[] = {
|
||||
{"GetObjectType", &Script_GetObjectType},
|
||||
{"IsObjectType", &Script_IsObjectType},
|
||||
{"GetName", &Script_GetName},
|
||||
{"GetParent", &Script_GetParent},
|
||||
{"Play", &Script_Play},
|
||||
{"Pause", &Script_Pause},
|
||||
{"Stop", &Script_Stop},
|
||||
{"Finish", &Script_Finish},
|
||||
{"GetProgress", &Script_GetProgress},
|
||||
{"IsDone", &Script_IsDone},
|
||||
{"IsPlaying", &Script_IsPlaying},
|
||||
{"IsPaused", &Script_IsPaused},
|
||||
{"IsPendingFinish", &Script_IsPendingFinish},
|
||||
{"GetDuration", &Script_GetDuration},
|
||||
{"SetLooping", &Script_SetLooping},
|
||||
{"GetLooping", &Script_GetLooping},
|
||||
{"GetLoopState", &Script_GetLoopState},
|
||||
{"GetMaxOrder", &Script_GetMaxOrder},
|
||||
{"SetInitialOffset", &Script_SetInitialOffset},
|
||||
{"GetInitialOffset", &Script_GetInitialOffset},
|
||||
{"GetAnimations", &Script_GetAnimations},
|
||||
{"CreateAnimation", &Script_CreateAnimation},
|
||||
{"HasScript", &Script_HasScript},
|
||||
{"GetScript", &Script_GetScript},
|
||||
{"SetScript", &Script_SetScript},
|
||||
{"HookScript", &Script_HookScript},
|
||||
{"SetIgnoreFramerateThrottle", &Script_SetIgnoreFramerateThrottle},
|
||||
{"GetIgnoreFramerateThrottle", &Script_GetIgnoreFramerateThrottle},
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
Class Group::s_class{"AnimationGroup", nullptr, kGroupScripts, 7, kMethods,
|
||||
static_cast<int>(sizeof(kMethods) / sizeof(kMethods[0])), 0, 0};
|
||||
|
||||
} // namespace Animation
|
||||
@@ -0,0 +1,340 @@
|
||||
// This file is part of ClassicAPI.
|
||||
//
|
||||
// ClassicAPI is free software: you can redistribute it and/or modify it under the terms
|
||||
// of the GNU 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 General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License along with
|
||||
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#include "animation/Object.h"
|
||||
|
||||
#include "HookSecureFunc.h"
|
||||
#include "Offsets.h"
|
||||
#include "baselib/Ascii.h"
|
||||
#include "frame/ScriptArgs.h"
|
||||
|
||||
#include <cstring>
|
||||
|
||||
namespace Animation {
|
||||
|
||||
namespace {
|
||||
|
||||
using Construct_t = void(__fastcall *)(void *object);
|
||||
using Destruct_t = void(__fastcall *)(void *object);
|
||||
using Lock_t = void(__fastcall *)(void *object, void *edx, const char *name);
|
||||
using Unlock_t = void(__fastcall *)(void *object, void *edx, const char *name);
|
||||
using BaseResolve_t = uint32_t *(__fastcall *)(void *object, void *edx, const char *name);
|
||||
using Release_t = void(__stdcall *)(uint32_t *slot);
|
||||
using LuaRef_t = int(__fastcall *)(void *L, int t);
|
||||
using LuaUnref_t = void(__fastcall *)(void *L, int t, int ref);
|
||||
using GetName_t = const char *(__fastcall *)(const void *object);
|
||||
|
||||
// 4.3.4's CScriptObject type name, which every class's IsA(name) accepts.
|
||||
constexpr const char *kObjectTypeName = "Object";
|
||||
|
||||
Object *Self(void *object) { return static_cast<Object *>(object); }
|
||||
|
||||
// ---- The vtable (the engine calls these on our objects) --------------------
|
||||
|
||||
void *__fastcall V_Delete(Object *object, void * /*edx*/, unsigned flags);
|
||||
|
||||
const char *__fastcall V_GetName(Object *object) { return object->Name(); }
|
||||
|
||||
// vtable+0x08: push the method `name` of the object's class or a base.
|
||||
int __fastcall V_FindMethod(Object *object, void * /*edx*/, void *L, const char *name) {
|
||||
for (const Class *c = object->cls; c != nullptr; c = c->base) {
|
||||
if (c->methodsRef <= 0)
|
||||
continue;
|
||||
Game::Lua::RawGetI(L, Game::Lua::REGISTRY_INDEX, c->methodsRef);
|
||||
Game::Lua::PushString(L, name);
|
||||
Game::Lua::RawGet(L, -2);
|
||||
if (Game::Lua::Type(L, -1) != Game::Lua::TYPE_NIL) {
|
||||
Game::Lua::Remove(L, -2);
|
||||
return 1;
|
||||
}
|
||||
Game::Lua::SetTop(L, -3);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
// vtable+0x0C: 4.3.4's GetScriptByName - the base OnEvent first.
|
||||
uint32_t *__fastcall V_ResolveScript(Object *object, void * /*edx*/, const char *name) {
|
||||
uint32_t *slot =
|
||||
reinterpret_cast<BaseResolve_t>(Offsets::FUN_SCRIPT_OBJECT_BASE_RESOLVE_SCRIPT)(object, nullptr, name);
|
||||
return slot != nullptr ? slot : object->ScriptSlot(name);
|
||||
}
|
||||
|
||||
int __fastcall V_IsA(Object *object, void * /*edx*/, int typeId) {
|
||||
for (const Class *c = object->cls; c != nullptr; c = c->base)
|
||||
if (c->typeId != 0 && c->typeId == typeId)
|
||||
return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
// vtable+0x14 differs per engine class; nothing calls it on ours.
|
||||
int __fastcall V_Unused(Object * /*object*/) { return 0; }
|
||||
|
||||
int __fastcall V_IsAName(Object *object, void * /*edx*/, const char *typeName) {
|
||||
if (typeName == nullptr)
|
||||
return 0;
|
||||
for (const Class *c = object->cls; c != nullptr; c = c->base)
|
||||
if (Ascii::EqualCI(typeName, c->typeName))
|
||||
return 1;
|
||||
return Ascii::EqualCI(typeName, kObjectTypeName) ? 1 : 0;
|
||||
}
|
||||
|
||||
const char *__fastcall V_GetObjectTypeName(Object *object) { return object->cls->typeName; }
|
||||
|
||||
void *g_vtable[] = {
|
||||
reinterpret_cast<void *>(&V_Delete), reinterpret_cast<void *>(&V_GetName),
|
||||
reinterpret_cast<void *>(&V_FindMethod), reinterpret_cast<void *>(&V_ResolveScript),
|
||||
reinterpret_cast<void *>(&V_IsA), reinterpret_cast<void *>(&V_Unused),
|
||||
reinterpret_cast<void *>(&V_IsAName), reinterpret_cast<void *>(&V_GetObjectTypeName),
|
||||
};
|
||||
|
||||
// Slot 0, the engine's deleting destructor. The engine never deletes our
|
||||
// objects - their owners (a region, a group) do, by their concrete type.
|
||||
void *__fastcall V_Delete(Object *object, void * /*edx*/, unsigned /*flags*/) { return object; }
|
||||
|
||||
} // namespace
|
||||
|
||||
// ---- Object -------------------------------------------------------------------
|
||||
|
||||
Object::Object(const Class &cls, void *parent, const char *name) : cls(&cls), parent(parent) {
|
||||
reinterpret_cast<Construct_t>(Offsets::FUN_SCRIPT_OBJECT_CONSTRUCT)(this);
|
||||
vtable = g_vtable;
|
||||
if (name != nullptr && *name != '\0')
|
||||
this->name = CreateName(name, parent);
|
||||
reinterpret_cast<Lock_t>(Offsets::FUN_FRAMESCRIPT_OBJECT_SCRIPT_REGISTER)(this, nullptr, Name());
|
||||
}
|
||||
|
||||
bool Object::s_detached = false;
|
||||
|
||||
Object::~Object() {
|
||||
if (s_detached)
|
||||
return;
|
||||
for (auto &slot : scripts)
|
||||
reinterpret_cast<Release_t>(Offsets::FUN_SCRIPT_RELEASE)(slot);
|
||||
while (holders > 1)
|
||||
reinterpret_cast<Unlock_t>(Offsets::FUN_SCRIPT_OBJECT_UNLOCK)(this, nullptr, nullptr);
|
||||
if (holders > 0)
|
||||
reinterpret_cast<Unlock_t>(Offsets::FUN_SCRIPT_OBJECT_UNLOCK)(this, nullptr, Name());
|
||||
reinterpret_cast<Destruct_t>(Offsets::FUN_SCRIPT_OBJECT_DESTRUCT)(this);
|
||||
}
|
||||
|
||||
uint32_t *Object::ScriptSlot(const char *scriptName) {
|
||||
if (scriptName == nullptr)
|
||||
return nullptr;
|
||||
for (const Class *c = cls; c != nullptr; c = c->base) {
|
||||
for (int i = 0; i < c->scriptCount; ++i)
|
||||
if (Ascii::EqualCI(scriptName, c->scriptNames[i]))
|
||||
return scripts[i];
|
||||
if (c->scriptCount > 0)
|
||||
break; // only one class in a chain declares the scripts
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void Object::RunScript(int index, int nargs) {
|
||||
void *L = Game::Lua::State();
|
||||
if (L == nullptr)
|
||||
return;
|
||||
const int first = Game::Lua::GetTop(L) - nargs + 1;
|
||||
if (HasScript(index))
|
||||
Frame::ScriptArgs::RunSlotWithValues(L, scripts[index], this, first, nargs);
|
||||
Game::Lua::SetTop(L, first - 1);
|
||||
}
|
||||
|
||||
// ---- Helpers --------------------------------------------------------------------
|
||||
|
||||
int TypeId(Class &cls) { return Game::Lua::FrameScriptTypeId(reinterpret_cast<uintptr_t>(&cls.typeId)); }
|
||||
|
||||
Object *Resolve(void *L, int idx, Class &cls) {
|
||||
return static_cast<Object *>(Game::Lua::ResolveTypedObject(L, idx, reinterpret_cast<uintptr_t>(&cls.typeId)));
|
||||
}
|
||||
|
||||
void Push(void *L, Object *object) { Game::Lua::PushObject(L, object); }
|
||||
|
||||
bool IsOurs(const void *object) { return object != nullptr && Game::Read<void **>(object, 0) == g_vtable; }
|
||||
|
||||
std::string CreateName(const char *source, const void *parent) {
|
||||
constexpr const char kParent[] = "$parent";
|
||||
constexpr size_t kParentLen = sizeof(kParent) - 1;
|
||||
if (std::strlen(source) < kParentLen || !Ascii::EqualCI(std::string(source, kParentLen).c_str(), kParent))
|
||||
return source;
|
||||
std::string name = "Top";
|
||||
for (const void *p = parent; p != nullptr;) {
|
||||
const char *pname = IsOurs(p) ? static_cast<const Object *>(p)->Name()
|
||||
: Game::Read<GetName_t>(Game::Read<void *>(p, 0),
|
||||
Offsets::VTBL_SCRIPTOBJECT_GET_NAME)(p);
|
||||
if (pname != nullptr && *pname != '\0') {
|
||||
name = pname;
|
||||
break;
|
||||
}
|
||||
p = IsOurs(p) ? static_cast<const Object *>(p)->parent : Game::Read<void *>(p, Offsets::OFF_REGION_PARENT);
|
||||
}
|
||||
return name + (source + kParentLen);
|
||||
}
|
||||
|
||||
void RegisterClass(Class &cls) {
|
||||
void *L = Game::Lua::State();
|
||||
TypeId(cls);
|
||||
Game::Lua::NewTable(L);
|
||||
for (int i = 0; i < cls.methodCount; ++i) {
|
||||
Game::Lua::PushString(L, cls.methods[i].name);
|
||||
Game::Lua::PushCClosure(L, cls.methods[i].func, 0);
|
||||
Game::Lua::RawSet(L, -3);
|
||||
}
|
||||
cls.methodsRef = reinterpret_cast<LuaRef_t>(Offsets::LUA_REF_REF)(L, Game::Lua::REGISTRY_INDEX);
|
||||
}
|
||||
|
||||
// ---- The base methods -----------------------------------------------------------
|
||||
|
||||
namespace {
|
||||
|
||||
// The object at self, of any of our classes.
|
||||
Object *AnySelf(void *L) {
|
||||
if (Game::Lua::Type(L, 1) != Game::Lua::TYPE_TABLE)
|
||||
return nullptr;
|
||||
void *object = Game::Lua::ResolveObject(L, 1);
|
||||
return IsOurs(object) ? Self(object) : nullptr;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int __fastcall Script_GetObjectType(void *L) {
|
||||
Object *object = AnySelf(L);
|
||||
if (object == nullptr)
|
||||
return 0;
|
||||
Game::Lua::PushString(L, object->cls->typeName);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int __fastcall Script_IsObjectType(void *L) {
|
||||
Object *object = AnySelf(L);
|
||||
if (object == nullptr)
|
||||
return 0;
|
||||
if (!Game::Lua::IsString(L, 2)) {
|
||||
Game::Lua::Error(L, "Usage: %s:IsObjectType(\"TYPE\")", object->DisplayName());
|
||||
return 0;
|
||||
}
|
||||
if (V_IsAName(object, nullptr, Game::Lua::ToString(L, 2)))
|
||||
Game::Lua::PushNumber(L, 1.0);
|
||||
else
|
||||
Game::Lua::PushNil(L);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int __fastcall Script_GetName(void *L) {
|
||||
Object *object = AnySelf(L);
|
||||
if (object == nullptr)
|
||||
return 0;
|
||||
Game::Lua::PushString(L, object->Name());
|
||||
return 1;
|
||||
}
|
||||
|
||||
int __fastcall Script_GetParent(void *L) {
|
||||
Object *object = AnySelf(L);
|
||||
if (object == nullptr)
|
||||
return 0;
|
||||
if (object->parent != nullptr)
|
||||
Game::Lua::PushObject(L, object->parent);
|
||||
else
|
||||
Game::Lua::PushNil(L);
|
||||
return 1;
|
||||
}
|
||||
|
||||
// 4.3.4's HasScript: 1 when the class has the script, else nil.
|
||||
int __fastcall Script_HasScript(void *L) {
|
||||
Object *object = AnySelf(L);
|
||||
if (object == nullptr)
|
||||
return 0;
|
||||
if (!Game::Lua::IsString(L, 2)) {
|
||||
Game::Lua::Error(L, "Usage: %s:HasScript(\"type\")", object->DisplayName());
|
||||
return 0;
|
||||
}
|
||||
if (V_ResolveScript(object, nullptr, Game::Lua::ToString(L, 2)) != nullptr)
|
||||
Game::Lua::PushNumber(L, 1.0);
|
||||
else
|
||||
Game::Lua::PushNil(L);
|
||||
return 1;
|
||||
}
|
||||
|
||||
// The engine's Script GetScript (0x00774780) on our object: the slot's
|
||||
// context becomes current, then the handler (nil for none) is pushed.
|
||||
int __fastcall Script_GetScript(void *L) {
|
||||
Object *object = AnySelf(L);
|
||||
if (object == nullptr)
|
||||
return 0;
|
||||
if (!Game::Lua::IsString(L, 2)) {
|
||||
Game::Lua::Error(L, "Usage: %s:GetScript(\"type\")", object->DisplayName());
|
||||
return 0;
|
||||
}
|
||||
const uint32_t *slot = V_ResolveScript(object, nullptr, Game::Lua::ToString(L, 2));
|
||||
if (slot == nullptr) {
|
||||
Game::Lua::Error(L, "%s doesn't have a \"%s\" script", object->DisplayName(), Game::Lua::ToString(L, 2));
|
||||
return 0;
|
||||
}
|
||||
if (slot[1] != 0 && Game::Read<int>(Offsets::VAR_FRAMESCRIPT_EXEC_CONTEXT_DEPTH) != 0)
|
||||
Game::Ref<uint32_t>(Offsets::VAR_FRAMESCRIPT_EXEC_CONTEXT) = slot[1];
|
||||
Game::Lua::RawGetI(L, Game::Lua::REGISTRY_INDEX, static_cast<int>(slot[0]));
|
||||
return 1;
|
||||
}
|
||||
|
||||
// The engine's Script SetScript (0x007748D0) on our object: release the old
|
||||
// handler, store a ref of the new one (0 for nil) with the current context.
|
||||
int __fastcall Script_SetScript(void *L) {
|
||||
Object *object = AnySelf(L);
|
||||
if (object == nullptr)
|
||||
return 0;
|
||||
const int handlerType = Game::Lua::Type(L, 3);
|
||||
if (!Game::Lua::IsString(L, 2) ||
|
||||
(handlerType != Game::Lua::TYPE_FUNCTION && handlerType != Game::Lua::TYPE_NIL &&
|
||||
handlerType != -1 /* none */)) {
|
||||
Game::Lua::Error(L, "Usage: %s:SetScript(\"type\", function)", object->DisplayName());
|
||||
return 0;
|
||||
}
|
||||
uint32_t *slot = V_ResolveScript(object, nullptr, Game::Lua::ToString(L, 2));
|
||||
if (slot == nullptr) {
|
||||
Game::Lua::Error(L, "%s doesn't have a \"%s\" script", object->DisplayName(), Game::Lua::ToString(L, 2));
|
||||
return 0;
|
||||
}
|
||||
reinterpret_cast<Release_t>(Offsets::FUN_SCRIPT_RELEASE)(slot);
|
||||
Game::Lua::SetTop(L, 3);
|
||||
const int ref = reinterpret_cast<LuaRef_t>(Offsets::LUA_REF_REF)(L, Game::Lua::REGISTRY_INDEX);
|
||||
slot[0] = ref > 0 ? static_cast<uint32_t>(ref) : 0;
|
||||
slot[1] = Game::Read<uint32_t>(Offsets::VAR_FRAMESCRIPT_EXEC_CONTEXT);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Frame HookScript's (frame/Modern.cpp) on our object: no handler yet -> the
|
||||
// hook is the handler; else the hooksecurefunc wrapper over (old, hook).
|
||||
int __fastcall Script_HookScript(void *L) {
|
||||
Object *object = AnySelf(L);
|
||||
if (object == nullptr)
|
||||
return 0;
|
||||
if (!Game::Lua::IsString(L, 2) || Game::Lua::Type(L, 3) != Game::Lua::TYPE_FUNCTION) {
|
||||
Game::Lua::Error(L, "Usage: %s:HookScript(\"type\", function)", object->DisplayName());
|
||||
return 0;
|
||||
}
|
||||
Game::Lua::SetTop(L, 3); // (self, type, hook)
|
||||
Game::Lua::PushValue(L, 1);
|
||||
Game::Lua::PushValue(L, 2);
|
||||
Game::Lua::PushCClosure(L, &Script_GetScript, 0);
|
||||
Game::Lua::Insert(L, -3);
|
||||
Game::Lua::Call(L, 2, 1); // (self, type, hook, old)
|
||||
if (Game::Lua::Type(L, 4) == Game::Lua::TYPE_FUNCTION) {
|
||||
Game::Lua::Insert(L, 3); // (self, type, old, hook)
|
||||
HookSecureFunc::PushWrapper(L); // (self, type, wrapper)
|
||||
} else {
|
||||
Game::Lua::SetTop(L, 3);
|
||||
}
|
||||
return Script_SetScript(L);
|
||||
}
|
||||
|
||||
} // namespace Animation
|
||||
@@ -0,0 +1,123 @@
|
||||
// This file is part of ClassicAPI.
|
||||
//
|
||||
// ClassicAPI is free software: you can redistribute it and/or modify it under the terms
|
||||
// of the GNU 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 General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License along with
|
||||
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "Game.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
|
||||
// Animation groups and animations as real 1.12 script objects.
|
||||
//
|
||||
// 4.3.4's CSimpleAnimGroup and CSimpleAnim are CScriptObjects: the engine
|
||||
// hands them to Lua as the same kind of table as a frame (`t[0]` = the
|
||||
// object, metatable `__framescript_meta`), finds their methods through the
|
||||
// object's vtable, resolves `self` with the object's IsA, and stores their
|
||||
// scripts in {handler, context} slots it finds through the object's script
|
||||
// resolver. 1.12 has the same machinery (benilla-re ui/methods, ui/script):
|
||||
// - ConstructScriptObject (0x00701AE0) builds the 0x24-byte header below;
|
||||
// DestructScriptObject (0x00701B40) releases it;
|
||||
// - LockScriptObject / UnlockScriptObject (0x00701BD0 / 0x00701CD0) make and
|
||||
// free the object's table and its name global;
|
||||
// - `__framescript_meta.__index` (0x007020B0) calls vtable+0x08 (L, name)
|
||||
// to push a method; ResolveTypedObject's type test calls vtable+0x10;
|
||||
// - SetScriptObjectScript (0x007025C0) compiles an XML script body into
|
||||
// the slot vtable+0x0C returns, and FrameScriptReleaseScript (0x00702670)
|
||||
// frees a slot.
|
||||
// So an animation object is an engine script object whose vtable is ours.
|
||||
// It has no C++ virtual functions - its first bytes are the engine header -
|
||||
// and its class (Class) carries what differs per type.
|
||||
namespace Animation {
|
||||
|
||||
// The 1.12 script-object header, as ConstructScriptObject fills it.
|
||||
struct ScriptObjectHeader {
|
||||
void **vtable;
|
||||
int32_t holders; // +0x04, LockScriptObject's count
|
||||
int32_t luaRef; // +0x08, the table's registry ref (-2 when none)
|
||||
uint32_t onEvent[2]; // +0x0C, the base OnEvent slot
|
||||
uint32_t events[4]; // +0x14, the event index array
|
||||
};
|
||||
static_assert(sizeof(ScriptObjectHeader) == 0x24, "the engine's script-object header");
|
||||
|
||||
struct Class {
|
||||
const char *typeName; // GetObjectType, IsObjectType
|
||||
const Class *base;
|
||||
// The class's own script names, lower case; a slot per name.
|
||||
const char *const *scriptNames;
|
||||
int scriptCount;
|
||||
const Game::Lua::FrameMethodEntry *methods;
|
||||
int methodCount;
|
||||
int typeId; // from the engine's type counter, on first use
|
||||
int methodsRef; // registry ref of the method table, per Lua state
|
||||
};
|
||||
|
||||
constexpr int kMaxScripts = 8;
|
||||
|
||||
class Object : public ScriptObjectHeader {
|
||||
public:
|
||||
const Class *cls;
|
||||
// The script object this one hangs from: a group's region, an
|
||||
// animation's group (GetParent, "$parent").
|
||||
void *parent;
|
||||
std::string name;
|
||||
uint32_t scripts[kMaxScripts][2] = {}; // {handler ref, context}
|
||||
|
||||
// The object's script slot for `name` (any case), or nullptr.
|
||||
uint32_t *ScriptSlot(const char *name);
|
||||
bool HasScript(int index) const { return scripts[index][0] != 0; }
|
||||
// Runs script `index` with `nargs` values pushed on top of the stack,
|
||||
// and pops them.
|
||||
void RunScript(int index, int nargs);
|
||||
|
||||
const char *Name() const { return name.empty() ? nullptr : name.c_str(); }
|
||||
// While set, a destroyed object leaves the engine alone: its table and
|
||||
// handlers belonged to a Lua state that is gone (/reload leftovers).
|
||||
static bool s_detached;
|
||||
const char *DisplayName() const { return name.empty() ? "<unnamed>" : name.c_str(); }
|
||||
|
||||
protected:
|
||||
// Registers the object's table, under its name when it has one ("$parent"
|
||||
// resolved from `parent`).
|
||||
Object(const Class &cls, void *parent, const char *name);
|
||||
~Object();
|
||||
};
|
||||
|
||||
// The class's type id (the engine's counter, assigned on first use).
|
||||
int TypeId(Class &cls);
|
||||
// The object at `idx` when it is of `cls` or a class derived from it, else
|
||||
// raises the engine's errors (as every method does) and returns nullptr.
|
||||
Object *Resolve(void *L, int idx, Class &cls);
|
||||
// Pushes the object's table.
|
||||
void Push(void *L, Object *object);
|
||||
// Whether a script object is one of ours.
|
||||
bool IsOurs(const void *object);
|
||||
// 4.3.4's CScriptObject::CreateName: "$parent" at the start of `source`
|
||||
// becomes the nearest named ancestor's name, "Top" when none.
|
||||
std::string CreateName(const char *source, const void *parent);
|
||||
|
||||
// Builds every class's method table in the current Lua state.
|
||||
void RegisterClass(Class &cls);
|
||||
|
||||
// The base methods every class has (4.3.4's CScriptObject methods), and the
|
||||
// script methods groups and animations share.
|
||||
int __fastcall Script_GetObjectType(void *L);
|
||||
int __fastcall Script_IsObjectType(void *L);
|
||||
int __fastcall Script_GetName(void *L);
|
||||
int __fastcall Script_GetParent(void *L);
|
||||
int __fastcall Script_HasScript(void *L);
|
||||
int __fastcall Script_GetScript(void *L);
|
||||
int __fastcall Script_SetScript(void *L);
|
||||
int __fastcall Script_HookScript(void *L);
|
||||
|
||||
} // namespace Animation
|
||||
@@ -0,0 +1,501 @@
|
||||
// This file is part of ClassicAPI.
|
||||
//
|
||||
// ClassicAPI is free software: you can redistribute it and/or modify it under the terms
|
||||
// of the GNU 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 General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License along with
|
||||
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
// 4.3.4's CSimplePathAnim and CSimpleControlPoint (wowdecomp15595
|
||||
// CSimplePathAnim.cpp, CSimpleControlPoint.cpp and their _Scripts.cpp).
|
||||
//
|
||||
// A Path moves the region through its control points: each point is an
|
||||
// offset from where the region is, the points are spread evenly over the
|
||||
// animation's progress (point i of n at (i + 1) / n), and the path starts
|
||||
// at offset 0. Between points the offset is a straight line, or with the
|
||||
// SMOOTH curve a Catmull-Rom spline. The offset goes through the same
|
||||
// AddAnimTranslation as a Translation.
|
||||
|
||||
#include "animation/Classes.h"
|
||||
#include "animation/Region.h"
|
||||
#include "animation/Xml.h"
|
||||
|
||||
#include "Game.h"
|
||||
#include "baselib/Ascii.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
|
||||
namespace Animation {
|
||||
|
||||
// ---- CSimpleControlPoint ------------------------------------------------------------
|
||||
|
||||
ControlPoint::ControlPoint(Anim *path, const char *name) : Object(s_class, path, name) {
|
||||
if (path != nullptr)
|
||||
path->controlPoints.push_back(this);
|
||||
}
|
||||
|
||||
ControlPoint::~ControlPoint() = default;
|
||||
|
||||
void ControlPoint::SetOffset(float x, float y) {
|
||||
if (x * x + y * y <= 0.00000023841858f) {
|
||||
offsetX = 0.0f;
|
||||
offsetY = 0.0f;
|
||||
} else {
|
||||
offsetX = x;
|
||||
offsetY = y;
|
||||
}
|
||||
}
|
||||
|
||||
void ControlPoint::SetOrder(int value, bool notify, bool wrap) {
|
||||
const int oldOrder = order;
|
||||
if (wrap)
|
||||
order = value < 0 || value > 99 ? 0 : value;
|
||||
else
|
||||
order = value < 0 ? 0 : (value > 99 ? 99 : value);
|
||||
if (parent != nullptr && notify && oldOrder != order)
|
||||
GetPath()->NotifyControlPointOrderChanged(this);
|
||||
}
|
||||
|
||||
bool ControlPoint::ChangeParent(Anim *path) {
|
||||
if (path == nullptr || GetPath() == path)
|
||||
return false;
|
||||
// LinkToTail unlinks the point from the old path's list first.
|
||||
Anim *old = GetPath();
|
||||
if (old != nullptr)
|
||||
old->controlPoints.erase(std::remove(old->controlPoints.begin(), old->controlPoints.end(), this),
|
||||
old->controlPoints.end());
|
||||
path->controlPoints.push_back(this);
|
||||
if (old != nullptr)
|
||||
old->NotifyControlPointRemoved(this);
|
||||
parent = path;
|
||||
path->NotifyControlPointAdded(this);
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---- CSimplePathAnim -------------------------------------------------------------------
|
||||
|
||||
int Anim::GetMaxControlPointOrder() const { return sortedPoints.empty() ? -1 : sortedPoints.back()->order; }
|
||||
|
||||
int Anim::FindControlPoint(int value) const {
|
||||
if (value == -1)
|
||||
return -1;
|
||||
int low = 0;
|
||||
int high = static_cast<int>(sortedPoints.size()) - 1;
|
||||
while (low <= high) {
|
||||
const int middle = static_cast<int>(static_cast<unsigned>(high + low) >> 1);
|
||||
const ControlPoint *point = sortedPoints[middle];
|
||||
if (point == nullptr)
|
||||
break; // 4.3.4 spins here; the array has no holes after BuildSpline
|
||||
if (point->order < value)
|
||||
low = middle + 1;
|
||||
else if (point->order > value)
|
||||
high = middle - 1;
|
||||
else
|
||||
return middle;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
void Anim::UpdateControlPointPositions() {
|
||||
const size_t count = sortedPoints.size();
|
||||
if (count == 0)
|
||||
return;
|
||||
const float step = 1.0f / static_cast<float>(count);
|
||||
for (size_t i = 0; i < count; ++i) {
|
||||
float position = static_cast<float>(i + 1) * step;
|
||||
position = position < 0.0f ? 0.0f : (position >= 1.0f ? 1.0f : position);
|
||||
sortedPoints[i]->position = position;
|
||||
}
|
||||
}
|
||||
|
||||
int Anim::RegisterSplineControlPoint(ControlPoint *point) {
|
||||
const int count = static_cast<int>(sortedPoints.size());
|
||||
if (count == 0) {
|
||||
sortedPoints.push_back(point);
|
||||
return 0;
|
||||
}
|
||||
int index = count;
|
||||
for (int i = 0; i < count; ++i) {
|
||||
ControlPoint *existing = sortedPoints[i];
|
||||
if (existing == nullptr) {
|
||||
sortedPoints[i] = point;
|
||||
return i;
|
||||
}
|
||||
if (point->order == existing->order)
|
||||
return i;
|
||||
if (point->order < existing->order) {
|
||||
index = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
sortedPoints.insert(sortedPoints.begin() + index, point);
|
||||
return index;
|
||||
}
|
||||
|
||||
void Anim::BuildSpline() {
|
||||
Stop(false);
|
||||
if (controlPoints.empty()) {
|
||||
sortedPoints.clear();
|
||||
return;
|
||||
}
|
||||
std::fill(sortedPoints.begin(), sortedPoints.end(), nullptr);
|
||||
// Points take their order in link order; a point without one, or with
|
||||
// one below the next free order, takes the next free order.
|
||||
int nextOrder = 0;
|
||||
for (ControlPoint *point : controlPoints) {
|
||||
int value = point->order;
|
||||
if (value == -1 || value < nextOrder) {
|
||||
value = nextOrder++;
|
||||
point->order = value < 0 ? 0 : value;
|
||||
} else {
|
||||
nextOrder = value + 1;
|
||||
}
|
||||
if (nextOrder > 99)
|
||||
nextOrder = 0;
|
||||
RegisterSplineControlPoint(point);
|
||||
}
|
||||
while (!sortedPoints.empty() && sortedPoints.back() == nullptr)
|
||||
sortedPoints.pop_back();
|
||||
}
|
||||
|
||||
void Anim::NotifyControlPointAdded(ControlPoint *point) {
|
||||
if (point == nullptr)
|
||||
return;
|
||||
const int index = FindControlPoint(point->order);
|
||||
if (index < 0) {
|
||||
if (RegisterSplineControlPoint(point) >= 0)
|
||||
UpdateControlPointPositions();
|
||||
return;
|
||||
}
|
||||
// The order is taken: the point goes before the one that has it and
|
||||
// takes the order; BuildSpline moves the rest up.
|
||||
ControlPoint *existing = sortedPoints[index];
|
||||
controlPoints.erase(std::remove(controlPoints.begin(), controlPoints.end(), point), controlPoints.end());
|
||||
controlPoints.insert(std::find(controlPoints.begin(), controlPoints.end(), existing), point);
|
||||
BuildSpline();
|
||||
UpdateControlPointPositions();
|
||||
}
|
||||
|
||||
void Anim::NotifyControlPointRemoved(ControlPoint *point) {
|
||||
if (point != nullptr && FindControlPoint(point->order) >= 0) {
|
||||
BuildSpline();
|
||||
UpdateControlPointPositions();
|
||||
}
|
||||
}
|
||||
|
||||
void Anim::NotifyControlPointOrderChanged(ControlPoint *point) {
|
||||
if (point == nullptr)
|
||||
return;
|
||||
const int index = FindControlPoint(point->order);
|
||||
if (index >= 0 && sortedPoints[index] != point) {
|
||||
ControlPoint *existing = sortedPoints[index];
|
||||
controlPoints.erase(std::remove(controlPoints.begin(), controlPoints.end(), point), controlPoints.end());
|
||||
controlPoints.insert(std::find(controlPoints.begin(), controlPoints.end(), existing), point);
|
||||
}
|
||||
BuildSpline();
|
||||
UpdateControlPointPositions();
|
||||
}
|
||||
|
||||
void Anim::ApplyPath(float progress) {
|
||||
const int count = static_cast<int>(sortedPoints.size());
|
||||
if (count == 0)
|
||||
return;
|
||||
void *region = GetRegionParent();
|
||||
if (region == nullptr)
|
||||
return;
|
||||
|
||||
const float t = std::fabs(progress);
|
||||
// The segment: 4.3.4 converts count * t with the 2^16 + x float trick,
|
||||
// which rounds to 1/128 before it truncates. Kept, so a progress just
|
||||
// under a point's lands on the same segment.
|
||||
const float scaled = static_cast<float>(count) * t;
|
||||
const float biased = std::fabs(scaled) + 65536.0f;
|
||||
int32_t bits;
|
||||
std::memcpy(&bits, &biased, sizeof(bits));
|
||||
uint32_t scaledBits;
|
||||
std::memcpy(&scaledBits, &scaled, sizeof(scaledBits));
|
||||
const int32_t sign = static_cast<int32_t>(scaledBits >> 31);
|
||||
const int index = static_cast<int16_t>((((bits >> 7) & 0x7FFF) ^ sign) - sign);
|
||||
|
||||
float x = 0.0f, y = 0.0f;
|
||||
const auto offsetOf = [this](int i, float &ox, float &oy) {
|
||||
ox = sortedPoints[i]->offsetX;
|
||||
oy = sortedPoints[i]->offsetY;
|
||||
};
|
||||
if (static_cast<unsigned>(index) >= static_cast<unsigned>(count)) {
|
||||
offsetOf(count - 1, x, y);
|
||||
} else if (curve && count > 1) {
|
||||
// Catmull-Rom through p1 -> p2; the start is offset 0.
|
||||
float p0x = 0.0f, p0y = 0.0f, p1x = 0.0f, p1y = 0.0f, p2x, p2y, p3x, p3y, t0, t1;
|
||||
if (index != 0) {
|
||||
offsetOf(index - 1, p1x, p1y);
|
||||
t0 = sortedPoints[index - 1]->position;
|
||||
offsetOf(index, p2x, p2y);
|
||||
t1 = sortedPoints[index]->position;
|
||||
if (index != 1)
|
||||
offsetOf(index - 2, p0x, p0y);
|
||||
if (index == count - 1) {
|
||||
p3x = p2x * 2.0f - p1x;
|
||||
p3y = p2y * 2.0f - p1y;
|
||||
} else {
|
||||
offsetOf(index + 1, p3x, p3y);
|
||||
}
|
||||
} else {
|
||||
t0 = 0.0f;
|
||||
offsetOf(0, p2x, p2y);
|
||||
t1 = sortedPoints[0]->position;
|
||||
p0x = -p2x;
|
||||
p0y = -p2y;
|
||||
offsetOf(1, p3x, p3y);
|
||||
}
|
||||
const float f = (t - t0) / (t1 - t0);
|
||||
const float f2 = f * f;
|
||||
const float f3 = f2 * f;
|
||||
const float ax = -p0x + p1x * 3.0f - p2x * 3.0f + p3x;
|
||||
const float ay = -p0y + p1y * 3.0f - p2y * 3.0f + p3y;
|
||||
const float bx = p0x * 2.0f - p1x * 5.0f + p2x * 4.0f - p3x;
|
||||
const float by = p0y * 2.0f - p1y * 5.0f + p2y * 4.0f - p3y;
|
||||
const float cx = -p0x + p2x;
|
||||
const float cy = -p0y + p2y;
|
||||
x = (cx * f + p1x * 2.0f + bx * f2 + ax * f3) * 0.5f;
|
||||
y = (cy * f + p1y * 2.0f + by * f2 + ay * f3) * 0.5f;
|
||||
} else {
|
||||
float ax = 0.0f, ay = 0.0f, bx, by, t0;
|
||||
if (index != 0) {
|
||||
offsetOf(index - 1, ax, ay);
|
||||
t0 = sortedPoints[index - 1]->position;
|
||||
} else {
|
||||
t0 = 0.0f;
|
||||
}
|
||||
offsetOf(index, bx, by);
|
||||
const float t1 = sortedPoints[index]->position;
|
||||
const float f = (t - t0) / (t1 - t0);
|
||||
x = ax + (bx - ax) * f;
|
||||
y = f * (by - ay) + ay;
|
||||
}
|
||||
|
||||
if (progress >= 0.0f)
|
||||
Region::AddAnimTranslation(region, target, x, y);
|
||||
else
|
||||
Region::AddAnimTranslation(region, target, -x, -y);
|
||||
}
|
||||
|
||||
// ---- Lua methods ---------------------------------------------------------------------
|
||||
|
||||
namespace {
|
||||
|
||||
Anim *PathSelf(void *L) { return static_cast<Anim *>(Resolve(L, 1, Anim::s_pathClass)); }
|
||||
ControlPoint *PointSelf(void *L) { return static_cast<ControlPoint *>(Resolve(L, 1, ControlPoint::s_class)); }
|
||||
|
||||
// LoadXML.cpp's s_curveTypes.
|
||||
bool StringToCurve(const char *text, bool &curve) {
|
||||
if (Ascii::EqualCI(text, "NONE")) {
|
||||
curve = false;
|
||||
return true;
|
||||
}
|
||||
if (Ascii::EqualCI(text, "SMOOTH")) {
|
||||
curve = true;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
int __fastcall Script_SetCurve(void *L) {
|
||||
Anim *path = PathSelf(L);
|
||||
if (path == nullptr)
|
||||
return 0;
|
||||
if (!Game::Lua::IsString(L, 2)) {
|
||||
Game::Lua::Error(L, "Usage: %s:SetCurve(\"curveType\")", path->DisplayName());
|
||||
return 0;
|
||||
}
|
||||
if (!StringToCurve(Game::Lua::ToString(L, 2), path->curve))
|
||||
Game::Lua::Error(L, "%s:SetCurve(): Unknown curve type specified", path->DisplayName());
|
||||
return 0;
|
||||
}
|
||||
|
||||
int __fastcall Script_GetCurve(void *L) {
|
||||
Anim *path = PathSelf(L);
|
||||
if (path == nullptr)
|
||||
return 0;
|
||||
Game::Lua::PushString(L, path->curve ? "SMOOTH" : "NONE");
|
||||
return 1;
|
||||
}
|
||||
|
||||
int __fastcall Script_GetMaxOrder(void *L) {
|
||||
Anim *path = PathSelf(L);
|
||||
if (path == nullptr)
|
||||
return 0;
|
||||
Game::Lua::PushNumber(L, path->GetMaxControlPointOrder() + 1);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int __fastcall Script_GetControlPoints(void *L) {
|
||||
Anim *path = PathSelf(L);
|
||||
if (path == nullptr)
|
||||
return 0;
|
||||
const int count = static_cast<int>(path->sortedPoints.size());
|
||||
if (count == 0)
|
||||
return 0;
|
||||
if (!Game::Lua::CheckStack(L, count)) {
|
||||
Game::Lua::Error(L, "%s:GetControlPoints(): Stack overflow", path->DisplayName());
|
||||
return 0;
|
||||
}
|
||||
for (ControlPoint *point : path->sortedPoints)
|
||||
Push(L, point);
|
||||
return count;
|
||||
}
|
||||
|
||||
int __fastcall Script_CreateControlPoint(void *L) {
|
||||
Anim *path = PathSelf(L);
|
||||
if (path == nullptr)
|
||||
return 0;
|
||||
const char *name = Game::Lua::IsString(L, 2) ? Game::Lua::ToString(L, 2) : nullptr;
|
||||
const void *templateNode = nullptr;
|
||||
if (Game::Lua::Type(L, 3) == Game::Lua::TYPE_STRING) {
|
||||
const char *inherits = Game::Lua::ToString(L, 3);
|
||||
templateNode = Xml::Template(inherits);
|
||||
if (templateNode == nullptr) {
|
||||
Game::Lua::Error(L, "%s:CreateControlPoint(): Couldn't find inherited node \"%s\"", path->DisplayName(),
|
||||
inherits);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
ControlPoint *point = new ControlPoint(path, name);
|
||||
if (templateNode != nullptr)
|
||||
Xml::LoadControlPoint(point, templateNode, nullptr);
|
||||
if (Game::Lua::IsNumber(L, 4))
|
||||
point->SetOrder(static_cast<int>(Game::Lua::ToNumber(L, 4)) - 1, false, false);
|
||||
// The decompiled CreateControlPoint passes the highest order itself,
|
||||
// which takes the last point's place and reverses points made one after
|
||||
// another; one past it, as SetParent does, puts the point last.
|
||||
if (point->order == -1)
|
||||
point->SetOrder(path->GetMaxControlPointOrder() + 1, false, true);
|
||||
path->NotifyControlPointAdded(point);
|
||||
Push(L, point);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int __fastcall Script_PointSetParent(void *L) {
|
||||
ControlPoint *point = PointSelf(L);
|
||||
if (point == nullptr)
|
||||
return 0;
|
||||
if (Game::Lua::Type(L, 2) == Game::Lua::TYPE_NIL) {
|
||||
Game::Lua::Error(L, "%s:SetParent(): Cannot set a 'nil' parent for control points", point->DisplayName());
|
||||
return 0;
|
||||
}
|
||||
const uintptr_t pathType = reinterpret_cast<uintptr_t>(&Anim::s_pathClass.typeId);
|
||||
Anim *path = nullptr;
|
||||
if (Game::Lua::IsString(L, 2)) {
|
||||
// CScriptObject::GetScriptObjectByName(name, Path).
|
||||
Game::Lua::PushString(L, Game::Lua::ToString(L, 2));
|
||||
Game::Lua::RawGet(L, Game::Lua::GLOBALS_INDEX);
|
||||
void *object = Game::Lua::Type(L, -1) == Game::Lua::TYPE_TABLE ? Game::Lua::ResolveObject(L, -1) : nullptr;
|
||||
Game::Lua::SetTop(L, -2);
|
||||
if (object != nullptr && IsOurs(object) && Game::Lua::IsA(object, pathType))
|
||||
path = static_cast<Anim *>(object);
|
||||
} else if (Game::Lua::Type(L, 2) == Game::Lua::TYPE_TABLE) {
|
||||
void *object = Game::Lua::ResolveObject(L, 2);
|
||||
if (object == nullptr) {
|
||||
Game::Lua::Error(L, "%s:SetParent(): Couldn't find 'this' in parent object", point->DisplayName());
|
||||
return 0;
|
||||
}
|
||||
if (!IsOurs(object) || !Game::Lua::IsA(object, pathType)) {
|
||||
Game::Lua::Error(L, "%s:SetParent(): Wrong parent object type, expected Path", point->DisplayName());
|
||||
return 0;
|
||||
}
|
||||
path = static_cast<Anim *>(object);
|
||||
}
|
||||
if (path == nullptr) {
|
||||
Game::Lua::Error(L, "%s:SetParent(): Couldn't find Path named '%s'", point->DisplayName(),
|
||||
Game::Lua::IsString(L, 2) ? Game::Lua::ToString(L, 2) : "");
|
||||
return 0;
|
||||
}
|
||||
const int oldOrder = point->order;
|
||||
if (Game::Lua::IsNumber(L, 3)) {
|
||||
point->SetOrder(static_cast<int>(Game::Lua::ToNumber(L, 3)) - 1, false, false);
|
||||
} else {
|
||||
int value = point->order;
|
||||
if (value == -1)
|
||||
value = path->GetMaxControlPointOrder() + 1;
|
||||
point->SetOrder(value, false, true);
|
||||
}
|
||||
if (!point->ChangeParent(path) && oldOrder != point->order)
|
||||
path->NotifyControlPointOrderChanged(point);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int __fastcall Script_PointSetOffset(void *L) {
|
||||
ControlPoint *point = PointSelf(L);
|
||||
if (point == nullptr)
|
||||
return 0;
|
||||
if (!Game::Lua::IsNumber(L, 2) || !Game::Lua::IsNumber(L, 3)) {
|
||||
Game::Lua::Error(L, "Usage: %s:SetOffset(x, y)", point->DisplayName());
|
||||
return 0;
|
||||
}
|
||||
point->SetOffset(Game::PixelToInternal(static_cast<float>(Game::Lua::ToNumber(L, 2))),
|
||||
Game::PixelToInternal(static_cast<float>(Game::Lua::ToNumber(L, 3))));
|
||||
return 0;
|
||||
}
|
||||
|
||||
int __fastcall Script_PointGetOffset(void *L) {
|
||||
ControlPoint *point = PointSelf(L);
|
||||
if (point == nullptr)
|
||||
return 0;
|
||||
Game::Lua::PushNumber(L, Game::InternalToPixel(point->offsetX));
|
||||
Game::Lua::PushNumber(L, Game::InternalToPixel(point->offsetY));
|
||||
return 2;
|
||||
}
|
||||
|
||||
int __fastcall Script_PointSetOrder(void *L) {
|
||||
ControlPoint *point = PointSelf(L);
|
||||
if (point == nullptr)
|
||||
return 0;
|
||||
if (!Game::Lua::IsNumber(L, 2)) {
|
||||
Game::Lua::Error(L, "Usage: %s:SetOrder(order)", point->DisplayName());
|
||||
return 0;
|
||||
}
|
||||
point->SetOrder(static_cast<int>(Game::Lua::ToNumber(L, 2)) - 1, true, false);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int __fastcall Script_PointGetOrder(void *L) {
|
||||
ControlPoint *point = PointSelf(L);
|
||||
if (point == nullptr)
|
||||
return 0;
|
||||
Game::Lua::PushNumber(L, point->order + 1);
|
||||
return 1;
|
||||
}
|
||||
|
||||
const Game::Lua::FrameMethodEntry kPathMethods[] = {
|
||||
{"SetCurve", &Script_SetCurve},
|
||||
{"GetCurve", &Script_GetCurve},
|
||||
{"GetControlPoints", &Script_GetControlPoints},
|
||||
{"CreateControlPoint", &Script_CreateControlPoint},
|
||||
{"GetMaxOrder", &Script_GetMaxOrder},
|
||||
};
|
||||
|
||||
// CScriptObject's methods, then CSimpleControlPoint's.
|
||||
const Game::Lua::FrameMethodEntry kPointMethods[] = {
|
||||
{"GetObjectType", &Script_GetObjectType}, {"IsObjectType", &Script_IsObjectType},
|
||||
{"GetName", &Script_GetName}, {"GetParent", &Script_GetParent},
|
||||
{"SetParent", &Script_PointSetParent}, {"SetOffset", &Script_PointSetOffset},
|
||||
{"GetOffset", &Script_PointGetOffset}, {"SetOrder", &Script_PointSetOrder},
|
||||
{"GetOrder", &Script_PointGetOrder},
|
||||
};
|
||||
|
||||
template <size_t N> constexpr int Count(const Game::Lua::FrameMethodEntry (&)[N]) { return static_cast<int>(N); }
|
||||
|
||||
} // namespace
|
||||
|
||||
Class Anim::s_pathClass{"Path", &Anim::s_class, nullptr, 0, kPathMethods, Count(kPathMethods), 0, 0};
|
||||
Class ControlPoint::s_class{"ControlPoint", nullptr, nullptr, 0, kPointMethods, Count(kPointMethods), 0, 0};
|
||||
|
||||
} // namespace Animation
|
||||
@@ -0,0 +1,833 @@
|
||||
// This file is part of ClassicAPI.
|
||||
//
|
||||
// ClassicAPI is free software: you can redistribute it and/or modify it under the terms
|
||||
// of the GNU 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 General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License along with
|
||||
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
// The region side of the animation system, and the region methods
|
||||
// CreateAnimationGroup / GetAnimationGroups / StopAnimating.
|
||||
//
|
||||
// 4.3.4 (wowdecomp15595 CScriptRegion.cpp, CSimpleFrame.cpp, CSimpleRegion.cpp,
|
||||
// CSimpleRender.cpp, CLayoutFrame.cpp):
|
||||
// - a region owns its groups (m_animGroups) and lists the playing ones
|
||||
// (m_playingAnimGroups);
|
||||
// - CSimpleFrame::OnLayerUpdate runs OnUpdate, then every group of the
|
||||
// frame, then every group of each of its regions;
|
||||
// - when a group starts, the region stores the state its animations change
|
||||
// (AnimActivated: a frame its own alpha, a texture or font string its
|
||||
// vertex alpha), unless an earlier group already did; a frame does this
|
||||
// for every frame and region below it too;
|
||||
// - every update first puts that state back (PreOnAnimUpdate), then the
|
||||
// animations add to it (AddAnimAlpha: a frame's own alpha becomes
|
||||
// change + its drawn alpha; a region's vertex alpha change + its own);
|
||||
// - when the last group with that kind of animation on the region or any
|
||||
// ancestor ends, the stored state goes back (AnimDeactivated).
|
||||
// So, as in 4.3.4, GetAlpha returns the animated alpha while it plays.
|
||||
//
|
||||
// Position animations (Translation, Scale, Rotation) move only what
|
||||
// is DRAWN, never a frame's rect: a frame hands them to every texture and font
|
||||
// string below it. A texture moves the four corners its draw record points at
|
||||
// (+0xD4, TL BL TR BR, the order of 4.3.4's m_positions); a font string moves
|
||||
// its text block's string position, and is turned and scaled about its origin
|
||||
// when its glyphs are baked (4.3.4 bakes them again whenever the string's
|
||||
// rotation or scale changes; so does this, through the engine's node
|
||||
// invalidate). The glyphs are scaled, not drawn at a larger font size: one
|
||||
// size per update would fill the glyph cache. Their stored base is what the engine
|
||||
// itself lays out (4.3.4's StoreAnimPosition): a texture's corners from its
|
||||
// rect through the engine's corner store, a font string's inset x layout
|
||||
// scale + its rect's min corner. When the layout moves a region mid-animation,
|
||||
// the co-hooks on the two OnFrameSizeChanged callbacks move the base and keep
|
||||
// the animation's offset, as 4.3.4's own OnFrameSizeChanged legs do.
|
||||
//
|
||||
// 1.12's regions have no room for these, so they are kept here, keyed by the
|
||||
// region. A frame's own alpha is Frame::Alpha's (3.x's m_alpha), set through
|
||||
// the frame's vtable setter as SetAlpha sets it; a region's vertex alpha is the
|
||||
// engine's region color (FUN_REGION_GET_COLOR / FUN_FONTSTRING_SET_COLOR).
|
||||
// The groups update from a co-hook of CSimpleFrame::OnFrameUpdate, which the
|
||||
// engine calls for every shown frame after OnUpdate, so a hidden frame's
|
||||
// groups wait, as in 4.3.4. Groups die with their frame (Frame::Destruction).
|
||||
|
||||
#include "animation/Region.h"
|
||||
|
||||
#include "animation/Classes.h"
|
||||
#include "animation/Xml.h"
|
||||
|
||||
#include "Game.h"
|
||||
#include "Offsets.h"
|
||||
#include "frame/Alpha.h"
|
||||
#include "frame/Destruction.h"
|
||||
#include "texture/Transform.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace Animation::Region {
|
||||
|
||||
namespace {
|
||||
|
||||
struct State {
|
||||
std::vector<Group *> groups; // m_animGroups (owned)
|
||||
std::vector<Group *> playing; // m_playingAnimGroups
|
||||
};
|
||||
|
||||
// CAnimationData.
|
||||
struct AnimData {
|
||||
bool hasAlpha = false;
|
||||
uint8_t alpha = 0xFF;
|
||||
bool hasPosition = false;
|
||||
// m_position[4]: a texture's four corners {x, y, z}; a font string uses
|
||||
// the first as its string position.
|
||||
float position[12] = {};
|
||||
// A font string's animated rotation and scale (4.3.4's m_rotation /
|
||||
// m_scale over the animation base), and what its glyphs were last baked
|
||||
// with.
|
||||
float rotation = 0.0f;
|
||||
float scale = 1.0f;
|
||||
float bakedRotation = 0.0f;
|
||||
float bakedScale = 1.0f;
|
||||
};
|
||||
|
||||
std::unordered_map<void *, State> g_states;
|
||||
std::unordered_map<void *, AnimData> g_data;
|
||||
// Font strings whose rotation or scale an update reset: checked against what
|
||||
// they were baked with once the update has run.
|
||||
std::vector<void *> g_touchedStrings;
|
||||
// Regions (not frames) with groups: their frame's update has to look at its
|
||||
// regions.
|
||||
int g_regionsWithGroups = 0;
|
||||
|
||||
using FrameUpdate_t = void(__fastcall *)(void *frame, void *edx, float elapsed);
|
||||
using SetFrameAlpha_t = void(__fastcall *)(void *frame, void *edx, uint32_t alpha);
|
||||
using GetColor_t = void(__fastcall *)(void *region, void *edx, uint32_t *bgra);
|
||||
using SetColor_t = void(__fastcall *)(void *region, void *edx, const uint32_t *bgra);
|
||||
using StoreCorners_t = void(__fastcall *)(void *region, void *edx, float *rect);
|
||||
using Crop_t = void(__fastcall *)(void *region, void *edx, float *rect);
|
||||
using SetStringPos_t = void(__fastcall *)(void *block, const float *position);
|
||||
using NdcToDdc_t = void(__fastcall *)(float *outX, float *outY, float x, float y);
|
||||
using SizeChanged_t = void(__fastcall *)(void *layout, void *edx, const float *oldRect);
|
||||
using InvalidateNode_t = void(__fastcall *)(void *node);
|
||||
|
||||
FrameUpdate_t g_origFrameUpdate = nullptr;
|
||||
SizeChanged_t g_origTextureSizeChanged = nullptr;
|
||||
SizeChanged_t g_origFontStringSizeChanged = nullptr;
|
||||
|
||||
bool IsFrame(void *region) { return Game::Lua::IsA(region, Offsets::VAR_FRAME_LUA_TYPE_ID); }
|
||||
bool IsTexture(void *region) { return Game::Lua::IsA(region, Offsets::VAR_TEXTURE_LUA_TYPE_ID); }
|
||||
bool IsFontString(void *region) { return Game::Lua::IsA(region, Offsets::VAR_FONTSTRING_LUA_TYPE_ID); }
|
||||
void *ParentOf(void *region) { return Game::Read<void *>(region, Offsets::OFF_REGION_PARENT); }
|
||||
|
||||
State *Find(void *region) {
|
||||
const auto it = g_states.find(region);
|
||||
return it != g_states.end() ? &it->second : nullptr;
|
||||
}
|
||||
|
||||
AnimData *DataOf(void *region) {
|
||||
const auto it = g_data.find(region);
|
||||
return it != g_data.end() ? &it->second : nullptr;
|
||||
}
|
||||
|
||||
template <typename Fn> void ForEachChild(void *frame, Fn fn) {
|
||||
Game::ForEachFrameListObject(frame, Offsets::OFF_FRAME_CHILD_LIST, fn);
|
||||
Game::ForEachFrameListObject(frame, Offsets::OFF_FRAME_REGION_LIST, fn);
|
||||
}
|
||||
|
||||
// ---- The state alpha animations change -----------------------------------------
|
||||
|
||||
uint8_t OwnAlpha(void *frame) { return Frame::Alpha::OwnAlpha(frame); }
|
||||
|
||||
void SetOwnAlpha(void *frame, uint8_t alpha) {
|
||||
void **vtable = *static_cast<void ***>(frame);
|
||||
reinterpret_cast<SetFrameAlpha_t>(vtable[Offsets::VTBL_FRAME_SET_FRAME_ALPHA / sizeof(void *)])(frame, nullptr,
|
||||
alpha);
|
||||
}
|
||||
|
||||
uint8_t DrawnParentAlpha(void *frame) {
|
||||
void *parent = ParentOf(frame);
|
||||
return parent != nullptr ? Game::Read<uint8_t>(parent, Offsets::OFF_FRAME_ALPHA) : 0xFF;
|
||||
}
|
||||
|
||||
uint32_t VertexColor(void *region) {
|
||||
uint32_t bgra = 0xFFFFFFFF;
|
||||
reinterpret_cast<GetColor_t>(Offsets::FUN_REGION_GET_COLOR)(region, nullptr, &bgra);
|
||||
return bgra;
|
||||
}
|
||||
|
||||
void SetVertexAlpha(void *region, uint8_t alpha) {
|
||||
const uint32_t bgra = (VertexColor(region) & 0x00FFFFFF) | (static_cast<uint32_t>(alpha) << 24);
|
||||
reinterpret_cast<SetColor_t>(Offsets::FUN_FONTSTRING_SET_COLOR)(region, nullptr, &bgra);
|
||||
}
|
||||
|
||||
// ---- The state position animations change --------------------------------------
|
||||
|
||||
float *Corners(void *texture) { return Game::Ptr<float>(texture, Offsets::OFF_SIMPLETEXTURE_CORNERS); }
|
||||
|
||||
// CSimpleTexture::SetPosition(m_rect, m_positions): the corners from the rect,
|
||||
// written the way the texture's layout callback (FUN_TEXTURE_ON_FRAME_SIZE_CHANGED)
|
||||
// writes them - cropped when SetTexCoordModifiesRect is on - so the corner
|
||||
// store's co-hooks (Texture::Transform) shape them as they do on a layout.
|
||||
void StoreTextureCorners(void *texture) {
|
||||
float rect[4];
|
||||
std::memcpy(rect, Game::Ptr<float>(texture, Offsets::OFF_REGION_RECT), sizeof(rect));
|
||||
if (Game::Read<int>(texture, Offsets::OFF_REGION_TEXCOORD_MODIFIES_RECT) != 0)
|
||||
reinterpret_cast<Crop_t>(Offsets::FUN_REGION_TEXCOORD_CROP)(texture, nullptr, rect);
|
||||
reinterpret_cast<StoreCorners_t>(Offsets::FUN_REGION_STORE_CORNERS)(texture, nullptr, rect);
|
||||
}
|
||||
|
||||
void *StringBlock(void *fontString) { return Game::Read<void *>(fontString, Offsets::OFF_FONTSTRING_TEXT_BLOCK); }
|
||||
|
||||
// Where the engine lays the string out: inset x layout scale + the rect's min
|
||||
// corner (the position FUN_FONTSTRING_ON_FRAME_SIZE_CHANGED and SetTextOffset
|
||||
// pass), as 4.3.4's StoreAnimPosition computes it.
|
||||
void StringBase(void *fontString, float out[3]) {
|
||||
const float *rect = Game::Ptr<const float>(fontString, Offsets::OFF_REGION_RECT);
|
||||
const float scale = Game::Read<float>(fontString, Offsets::OFF_LAYOUT_SCALE);
|
||||
out[0] = Game::Read<float>(fontString, Offsets::OFF_FONTSTRING_INSET_X) * scale + rect[1];
|
||||
out[1] = Game::Read<float>(fontString, Offsets::OFF_FONTSTRING_INSET_Y) * scale + rect[0];
|
||||
out[2] = 0.0f;
|
||||
}
|
||||
|
||||
// TextBlockGetStringPos: the string node's position, back in DDC.
|
||||
bool GetStringPos(void *block, float out[3]) {
|
||||
const void *node = Game::Read<void *>(block, Offsets::OFF_TEXTBLOCK_NODE);
|
||||
if (node == nullptr)
|
||||
return false;
|
||||
const float *position = Game::Ptr<const float>(node, Offsets::OFF_TEXT_NODE_POSITION);
|
||||
reinterpret_cast<NdcToDdc_t>(Offsets::FUN_COORD_NDC_TO_DDC)(&out[0], &out[1], position[0], position[1]);
|
||||
out[2] = position[2];
|
||||
return true;
|
||||
}
|
||||
|
||||
void SetStringPos(void *block, const float position[3]) {
|
||||
reinterpret_cast<SetStringPos_t>(Offsets::FUN_TEXTBLOCK_SET_STRING_POS)(block, position);
|
||||
}
|
||||
|
||||
// CSimpleTexture / CSimpleFontString::StoreAnimPosition.
|
||||
void StoreAnimPosition(void *region, AnimData &data) {
|
||||
if (IsTexture(region)) {
|
||||
StoreTextureCorners(region);
|
||||
std::memcpy(data.position, Corners(region), sizeof(data.position));
|
||||
data.hasPosition = true;
|
||||
} else if (IsFontString(region)) {
|
||||
StringBase(region, data.position);
|
||||
data.hasPosition = true;
|
||||
}
|
||||
}
|
||||
|
||||
void *StringNode(void *fontString) {
|
||||
void *block = StringBlock(fontString);
|
||||
return block != nullptr ? Game::Read<void *>(block, Offsets::OFF_TEXTBLOCK_NODE) : nullptr;
|
||||
}
|
||||
|
||||
// GxuFontStringInvalidate after GxuFontSetRotation / GxuFontSetScale: the
|
||||
// glyphs are baked again on the next paint, where FontStringBaked turns and
|
||||
// scales them. Only when the values differ from the baked ones.
|
||||
void RebakeIfChanged(void *fontString, const AnimData &data) {
|
||||
if (data.rotation == data.bakedRotation && data.scale == data.bakedScale)
|
||||
return;
|
||||
if (void *node = StringNode(fontString))
|
||||
reinterpret_cast<InvalidateNode_t>(Offsets::FUN_TEXT_NODE_INVALIDATE)(node);
|
||||
}
|
||||
|
||||
// AnimData_ResetPositionData: the region goes back to where the layout puts it.
|
||||
void ResetPosition(void *region, AnimData &data) {
|
||||
data.hasPosition = false;
|
||||
if (IsTexture(region)) {
|
||||
StoreTextureCorners(region);
|
||||
} else if (IsFontString(region)) {
|
||||
// 4.3.4 leaves the string where the last update put it until the next
|
||||
// layout; it goes back now, as the corners of a texture do.
|
||||
if (void *block = StringBlock(region)) {
|
||||
float base[3];
|
||||
StringBase(region, base);
|
||||
SetStringPos(block, base);
|
||||
}
|
||||
data.rotation = 0.0f;
|
||||
data.scale = 1.0f;
|
||||
RebakeIfChanged(region, data);
|
||||
}
|
||||
}
|
||||
|
||||
// CSimpleFrame / CSimpleRegion::AnimActivated.
|
||||
void AnimActivated(void *region, bool alpha, bool position) {
|
||||
const bool frame = IsFrame(region);
|
||||
AnimData &data = g_data[region]; // AnimData_Init
|
||||
if (alpha) {
|
||||
data.hasAlpha = true;
|
||||
data.alpha = frame ? OwnAlpha(region) : static_cast<uint8_t>(VertexColor(region) >> 24);
|
||||
}
|
||||
// A frame stores no position of its own, but it is marked, so the end of
|
||||
// its last position group resets everything below it (NotifyEnd reads
|
||||
// the mark), as the end of an alpha group does.
|
||||
if (position) {
|
||||
if (frame)
|
||||
data.hasPosition = true;
|
||||
else
|
||||
StoreAnimPosition(region, data);
|
||||
}
|
||||
if (frame)
|
||||
ForEachChild(region, [alpha, position](void *child) { AnimActivated(child, alpha, position); });
|
||||
}
|
||||
|
||||
// CSimpleFrame / CSimpleRegion::AnimDeactivated.
|
||||
void AnimDeactivated(void *region, bool alpha, bool position) {
|
||||
const bool frame = IsFrame(region);
|
||||
AnimData *data = DataOf(region);
|
||||
if (alpha) {
|
||||
const uint8_t stored = data != nullptr ? data->alpha : 0xFF; // AnimData_GetAlpha
|
||||
if (frame) {
|
||||
if (stored != OwnAlpha(region))
|
||||
SetOwnAlpha(region, stored);
|
||||
} else {
|
||||
SetVertexAlpha(region, stored);
|
||||
}
|
||||
if (data != nullptr) {
|
||||
data->hasAlpha = false;
|
||||
data->alpha = 0xFF;
|
||||
}
|
||||
}
|
||||
if (position && data != nullptr) {
|
||||
if (frame)
|
||||
data->hasPosition = false;
|
||||
else
|
||||
ResetPosition(region, *data);
|
||||
}
|
||||
if (frame)
|
||||
ForEachChild(region, [alpha, position](void *child) { AnimDeactivated(child, alpha, position); });
|
||||
}
|
||||
|
||||
// CScriptRegion::HasActiveAlphaAnim / HasActivePositionAnim: a playing group
|
||||
// with that kind of animation on the region or an ancestor.
|
||||
template <typename Has> bool HasActiveAnim(void *region, Has has) {
|
||||
for (void *r = region; r != nullptr; r = ParentOf(r)) {
|
||||
const State *state = Find(r);
|
||||
if (state == nullptr)
|
||||
continue;
|
||||
for (const Group *group : state->playing)
|
||||
if (has(group))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// ---- The update ----------------------------------------------------------------------
|
||||
|
||||
void UpdateGroups(void *region, float elapsed) {
|
||||
State *state = Find(region);
|
||||
if (state == nullptr)
|
||||
return;
|
||||
const std::vector<Group *> groups = state->groups;
|
||||
for (Group *group : groups)
|
||||
group->OnUpdate(elapsed);
|
||||
}
|
||||
|
||||
void __fastcall FrameUpdate_h(void *frame, void *edx, float elapsed) {
|
||||
g_origFrameUpdate(frame, edx, elapsed);
|
||||
if (g_states.empty())
|
||||
return;
|
||||
UpdateGroups(frame, elapsed);
|
||||
if (g_regionsWithGroups > 0)
|
||||
Game::ForEachFrameListObject(frame, Offsets::OFF_FRAME_REGION_LIST,
|
||||
[elapsed](void *region) { UpdateGroups(region, elapsed); });
|
||||
// The font strings this update turned or scaled, or put back.
|
||||
for (void *fontString : g_touchedStrings)
|
||||
if (const AnimData *data = DataOf(fontString))
|
||||
RebakeIfChanged(fontString, *data);
|
||||
g_touchedStrings.clear();
|
||||
}
|
||||
|
||||
const Game::HookAutoRegister _frameUpdateHook{Offsets::FUN_FRAME_ON_UPDATE, reinterpret_cast<void *>(&FrameUpdate_h),
|
||||
reinterpret_cast<void **>(&g_origFrameUpdate)};
|
||||
|
||||
// ---- A layout during a position animation -----------------------------------------
|
||||
//
|
||||
// The layout writes the region's unanimated position. As in 4.3.4's
|
||||
// OnFrameSizeChanged legs, the stored base becomes that new position and the
|
||||
// drawn position keeps the animation's offset from it.
|
||||
|
||||
AnimData *PositionData(void *region) {
|
||||
if (g_data.empty())
|
||||
return nullptr;
|
||||
AnimData *data = DataOf(region);
|
||||
return data != nullptr && data->hasPosition ? data : nullptr;
|
||||
}
|
||||
|
||||
void __fastcall TextureSizeChanged_h(void *layout, void *edx, const float *oldRect) {
|
||||
void *texture = static_cast<char *>(layout) - Offsets::OFF_REGION_ANCHOR;
|
||||
AnimData *data = PositionData(texture);
|
||||
if (data == nullptr) {
|
||||
g_origTextureSizeChanged(layout, edx, oldRect);
|
||||
return;
|
||||
}
|
||||
float animated[12];
|
||||
std::memcpy(animated, Corners(texture), sizeof(animated));
|
||||
g_origTextureSizeChanged(layout, edx, oldRect);
|
||||
float *corners = Corners(texture);
|
||||
for (int i = 0; i < 12; ++i) {
|
||||
const float base = corners[i];
|
||||
corners[i] = animated[i] + (base - data->position[i]);
|
||||
data->position[i] = base;
|
||||
}
|
||||
}
|
||||
|
||||
void __fastcall FontStringSizeChanged_h(void *layout, void *edx, const float *oldRect) {
|
||||
void *fontString = static_cast<char *>(layout) - Offsets::OFF_REGION_ANCHOR;
|
||||
AnimData *data = PositionData(fontString);
|
||||
if (data == nullptr) {
|
||||
g_origFontStringSizeChanged(layout, edx, oldRect);
|
||||
return;
|
||||
}
|
||||
float animated[3];
|
||||
void *before = StringBlock(fontString);
|
||||
const bool hadString = before != nullptr && GetStringPos(before, animated);
|
||||
g_origFontStringSizeChanged(layout, edx, oldRect);
|
||||
float base[3];
|
||||
StringBase(fontString, base);
|
||||
void *block = StringBlock(fontString);
|
||||
if (hadString && block != nullptr) {
|
||||
float position[3];
|
||||
for (int i = 0; i < 3; ++i)
|
||||
position[i] = animated[i] + (base[i] - data->position[i]);
|
||||
SetStringPos(block, position);
|
||||
}
|
||||
std::memcpy(data->position, base, sizeof(base));
|
||||
}
|
||||
|
||||
const Game::HookAutoRegister _textureSizeHook{Offsets::FUN_TEXTURE_ON_FRAME_SIZE_CHANGED,
|
||||
reinterpret_cast<void *>(&TextureSizeChanged_h),
|
||||
reinterpret_cast<void **>(&g_origTextureSizeChanged)};
|
||||
const Game::HookAutoRegister _fontStringSizeHook{Offsets::FUN_FONTSTRING_ON_FRAME_SIZE_CHANGED,
|
||||
reinterpret_cast<void *>(&FontStringSizeChanged_h),
|
||||
reinterpret_cast<void **>(&g_origFontStringSizeChanged)};
|
||||
|
||||
// ---- Lifetime ------------------------------------------------------------------------
|
||||
|
||||
void DestroyGroupsOf(void *region) {
|
||||
const auto it = g_states.find(region);
|
||||
if (it != g_states.end()) {
|
||||
if (!it->second.groups.empty() && !IsFrame(region))
|
||||
--g_regionsWithGroups;
|
||||
const std::vector<Group *> groups = std::move(it->second.groups);
|
||||
g_states.erase(it);
|
||||
for (Group *group : groups)
|
||||
delete group;
|
||||
}
|
||||
g_data.erase(region);
|
||||
}
|
||||
|
||||
// The frame and its regions die here; its child frames run their own
|
||||
// destructors.
|
||||
void OnFrameDestroyed(void *frame) {
|
||||
if (g_states.empty() && g_data.empty())
|
||||
return;
|
||||
Game::ForEachFrameListObject(frame, Offsets::OFF_FRAME_REGION_LIST, [](void *region) { DestroyGroupsOf(region); });
|
||||
DestroyGroupsOf(frame);
|
||||
}
|
||||
|
||||
const Frame::Destruction::AutoSubscribe _destructionSub{&OnFrameDestroyed};
|
||||
|
||||
// Groups on frames that outlived a /reload: their tables and handlers were
|
||||
// in the old Lua state, so they are dropped without touching it.
|
||||
void DropLeftovers() {
|
||||
Object::s_detached = true;
|
||||
for (auto &entry : g_states)
|
||||
for (Group *group : entry.second.groups)
|
||||
delete group;
|
||||
Object::s_detached = false;
|
||||
g_states.clear();
|
||||
g_data.clear();
|
||||
g_regionsWithGroups = 0;
|
||||
}
|
||||
|
||||
// ---- Region methods (CScriptRegion_Scripts.cpp) -------------------------------------------
|
||||
|
||||
void StopAnimating(void *region) {
|
||||
if (State *state = Find(region)) {
|
||||
const std::vector<Group *> playing = state->playing;
|
||||
for (Group *group : playing)
|
||||
group->Stop(true);
|
||||
}
|
||||
// CSimpleFrame::StopAnimating: and everything below it.
|
||||
if (IsFrame(region))
|
||||
ForEachChild(region, [](void *child) { StopAnimating(child); });
|
||||
}
|
||||
|
||||
int __fastcall Script_CreateAnimationGroup(void *L) {
|
||||
void *region = Game::Lua::ResolveRegion(L);
|
||||
if (region == nullptr)
|
||||
return 0;
|
||||
const char *name = Game::Lua::IsString(L, 2) ? Game::Lua::ToString(L, 2) : nullptr;
|
||||
const void *templateNode = nullptr;
|
||||
if (Game::Lua::Type(L, 3) == Game::Lua::TYPE_STRING) {
|
||||
const char *inherits = Game::Lua::ToString(L, 3);
|
||||
templateNode = Xml::Template(inherits);
|
||||
if (templateNode == nullptr) {
|
||||
Game::Lua::Error(L, "%s:CreateAnimationGroup(): Couldn't find inherited node \"%s\"",
|
||||
Game::Lua::ObjectDisplayName(region), inherits);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
Group *group = new Group(region, name);
|
||||
if (templateNode != nullptr) {
|
||||
Xml::LoadGroup(group, templateNode, nullptr);
|
||||
group->PostLoadXML();
|
||||
}
|
||||
Push(L, group);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int __fastcall Script_GetAnimationGroups(void *L) {
|
||||
void *region = Game::Lua::ResolveRegion(L);
|
||||
if (region == nullptr)
|
||||
return 0;
|
||||
const State *state = Find(region);
|
||||
if (state == nullptr)
|
||||
return 0;
|
||||
const int count = static_cast<int>(state->groups.size());
|
||||
if (!Game::Lua::CheckStack(L, count)) {
|
||||
Game::Lua::Error(L, "%s:GetAnimationGroups(): Stack overflow", Game::Lua::ObjectDisplayName(region));
|
||||
return 0;
|
||||
}
|
||||
for (Group *group : state->groups)
|
||||
Push(L, group);
|
||||
return count;
|
||||
}
|
||||
|
||||
int __fastcall Script_StopAnimating(void *L) {
|
||||
void *region = Game::Lua::ResolveRegion(L);
|
||||
if (region != nullptr)
|
||||
StopAnimating(region);
|
||||
return 0;
|
||||
}
|
||||
|
||||
const Game::Lua::FrameMethodEntry kRegionMethods[] = {
|
||||
{"CreateAnimationGroup", &Script_CreateAnimationGroup},
|
||||
{"GetAnimationGroups", &Script_GetAnimationGroups},
|
||||
{"StopAnimating", &Script_StopAnimating},
|
||||
};
|
||||
|
||||
const Game::Doc::Field kCreateArgs[] = {
|
||||
Game::Doc::Opt("name", "string", nullptr, "The group's name; \"$parent\" is the region's."),
|
||||
Game::Doc::Opt("templateName", "string", nullptr, "A virtual <AnimationGroup> to inherit."),
|
||||
};
|
||||
const Game::Doc::Field kCreateRets[] = {
|
||||
Game::Doc::Req("animationGroup", "AnimationGroup"),
|
||||
};
|
||||
const Game::Doc::Field kGroupsRets[] = {
|
||||
Game::Doc::Vararg("AnimationGroup", "Every animation group of the region, in creation order."),
|
||||
};
|
||||
const Game::Doc::Function kCreateAnimationGroup{"Creates an animation group on the region.", kCreateArgs,
|
||||
kCreateRets};
|
||||
const Game::Doc::Function kGetAnimationGroups{"Returns the region's animation groups.", {}, kGroupsRets};
|
||||
const Game::Doc::Function kStopAnimating{
|
||||
"Stops every playing animation group of the region and, for a frame, of everything inside it.", {}, {}};
|
||||
const Game::Doc::Method kRegionDocs[] = {
|
||||
{"CreateAnimationGroup", &kCreateAnimationGroup},
|
||||
{"GetAnimationGroups", &kGetAnimationGroups},
|
||||
{"StopAnimating", &kStopAnimating},
|
||||
};
|
||||
|
||||
void RegisterLuaFunctions() {
|
||||
DropLeftovers();
|
||||
RegisterClass(Group::s_class);
|
||||
RegisterClass(Anim::s_class);
|
||||
RegisterClass(Anim::s_alphaClass);
|
||||
RegisterClass(Anim::s_translationClass);
|
||||
RegisterClass(Anim::s_scaleClass);
|
||||
RegisterClass(Anim::s_rotationClass);
|
||||
RegisterClass(Anim::s_pathClass);
|
||||
RegisterClass(ControlPoint::s_class);
|
||||
Game::Lua::RegisterFrameMethods(reinterpret_cast<void *>(Offsets::VAR_REGION_METHOD_REGISTRY), kRegionMethods,
|
||||
static_cast<int>(sizeof(kRegionMethods) / sizeof(kRegionMethods[0])),
|
||||
kRegionDocs, static_cast<int>(sizeof(kRegionDocs) / sizeof(kRegionDocs[0])));
|
||||
}
|
||||
|
||||
const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
|
||||
|
||||
} // namespace
|
||||
|
||||
// ---- The CScriptRegion animation members ---------------------------------------------
|
||||
|
||||
void RegisterGroup(void *region, Group *group) {
|
||||
State &state = g_states[region];
|
||||
if (state.groups.empty() && !IsFrame(region))
|
||||
++g_regionsWithGroups;
|
||||
state.groups.push_back(group);
|
||||
}
|
||||
|
||||
void NotifyBegin(void *region, Group *group) {
|
||||
if (group == nullptr)
|
||||
return;
|
||||
State &state = g_states[region];
|
||||
const AnimData *data = DataOf(region);
|
||||
const bool alpha = !(data != nullptr && data->hasAlpha) && group->HasAlphaAnim();
|
||||
const bool position = !(data != nullptr && data->hasPosition) && group->HasPositionAnim();
|
||||
AnimActivated(region, alpha, position);
|
||||
state.playing.push_back(group);
|
||||
}
|
||||
|
||||
void NotifyEnd(void *region, Group *group) {
|
||||
State *state = Find(region);
|
||||
if (group == nullptr || state == nullptr)
|
||||
return;
|
||||
state->playing.erase(std::remove(state->playing.begin(), state->playing.end(), group), state->playing.end());
|
||||
const AnimData *data = DataOf(region);
|
||||
const bool alpha = data != nullptr && data->hasAlpha &&
|
||||
!HasActiveAnim(region, [](const Group *g) { return g->HasAlphaAnim(); });
|
||||
const bool position = data != nullptr && data->hasPosition &&
|
||||
!HasActiveAnim(region, [](const Group *g) { return g->HasPositionAnim(); });
|
||||
AnimDeactivated(region, alpha, position);
|
||||
}
|
||||
|
||||
void PreOnAnimUpdate(void *region) {
|
||||
const bool frame = IsFrame(region);
|
||||
const AnimData *data = DataOf(region);
|
||||
if (data != nullptr && data->hasAlpha) {
|
||||
if (frame) {
|
||||
if (data->alpha != OwnAlpha(region))
|
||||
SetOwnAlpha(region, data->alpha);
|
||||
} else {
|
||||
SetVertexAlpha(region, data->alpha);
|
||||
}
|
||||
}
|
||||
if (data != nullptr && data->hasPosition) {
|
||||
if (IsTexture(region)) {
|
||||
std::memcpy(Corners(region), data->position, sizeof(data->position));
|
||||
} else if (IsFontString(region)) {
|
||||
if (void *block = StringBlock(region))
|
||||
SetStringPos(block, data->position);
|
||||
// CSimpleFontString::PreOnAnimUpdate: back to the base rotation
|
||||
// and scale.
|
||||
AnimData *own = DataOf(region);
|
||||
own->rotation = 0.0f;
|
||||
own->scale = 1.0f;
|
||||
g_touchedStrings.push_back(region);
|
||||
}
|
||||
}
|
||||
if (frame)
|
||||
ForEachChild(region, [](void *child) { PreOnAnimUpdate(child); });
|
||||
}
|
||||
|
||||
void AddAnimTranslation(void *region, void *target, float x, float y) {
|
||||
if (IsFrame(region)) {
|
||||
// CSimpleFrame::AddAnimTranslation: the frame itself does not move;
|
||||
// everything below it does, or only the target below it.
|
||||
if (target == region)
|
||||
target = nullptr;
|
||||
ForEachChild(region, [target, x, y](void *child) { AddAnimTranslation(child, target, x, y); });
|
||||
return;
|
||||
}
|
||||
if (target != nullptr && target != region)
|
||||
return;
|
||||
// Only a region whose base is stored: PreOnAnimUpdate puts it back before
|
||||
// the next add, so nothing builds up.
|
||||
const AnimData *data = DataOf(region);
|
||||
if (data == nullptr || !data->hasPosition)
|
||||
return;
|
||||
if (IsTexture(region)) {
|
||||
// ApplyTranslationAnim(m_positions, translation).
|
||||
float *corners = Corners(region);
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
corners[i * 3 + 0] += x;
|
||||
corners[i * 3 + 1] += y;
|
||||
}
|
||||
} else if (void *block = StringBlock(region)) {
|
||||
float position[3];
|
||||
if (!GetStringPos(block, position))
|
||||
return;
|
||||
position[0] += x;
|
||||
position[1] += y;
|
||||
SetStringPos(block, position);
|
||||
}
|
||||
}
|
||||
|
||||
void AddAnimAlpha(void *region, void *target, int16_t alpha) {
|
||||
if (IsFrame(region)) {
|
||||
// CSimpleFrame::AddAnimAlpha: a target below the frame takes it.
|
||||
if (target != nullptr && target != region) {
|
||||
ForEachChild(region, [target, alpha](void *child) { AddAnimAlpha(child, target, alpha); });
|
||||
return;
|
||||
}
|
||||
const uint8_t own = OwnAlpha(region);
|
||||
const int value = alpha + static_cast<uint8_t>(own * DrawnParentAlpha(region) / 255);
|
||||
const uint8_t newAlpha = static_cast<uint8_t>(value > 255 ? 255 : (value < 0 ? 0 : value));
|
||||
if (newAlpha != own)
|
||||
SetOwnAlpha(region, newAlpha);
|
||||
return;
|
||||
}
|
||||
// CSimpleRegion::AddAnimAlpha.
|
||||
if (target != nullptr && target != region)
|
||||
return;
|
||||
const int value = alpha + static_cast<int>(VertexColor(region) >> 24);
|
||||
SetVertexAlpha(region, static_cast<uint8_t>(value > 255 ? 255 : (value < 0 ? 0 : value)));
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
// The corners (TL, BL, TR, BR) as 2D points.
|
||||
float CornerX(const float *corners, int i) { return corners[i * 3 + 0]; }
|
||||
float CornerY(const float *corners, int i) { return corners[i * 3 + 1]; }
|
||||
|
||||
// GetOriginOffset (4.3.4 CSimpleRegion.cpp): the origin point on the drawn
|
||||
// quad, then the offset along the quad's bottom edge direction, so the
|
||||
// offset turns with a quad that is already turned.
|
||||
void GetOriginOffset(int origin, const float *c, float offsetX, float offsetY, float &x, float &y) {
|
||||
const auto mid = [c](int a, int b, float &mx, float &my) {
|
||||
mx = (CornerX(c, b) - CornerX(c, a)) * 0.5f + CornerX(c, a);
|
||||
my = (CornerY(c, b) - CornerY(c, a)) * 0.5f + CornerY(c, a);
|
||||
};
|
||||
switch (origin) {
|
||||
case Offsets::FRAMEPOINT_TOPLEFT: x = CornerX(c, 0); y = CornerY(c, 0); break;
|
||||
case Offsets::FRAMEPOINT_TOP: mid(0, 2, x, y); break;
|
||||
case Offsets::FRAMEPOINT_TOPRIGHT: x = CornerX(c, 2); y = CornerY(c, 2); break;
|
||||
case Offsets::FRAMEPOINT_LEFT: mid(0, 1, x, y); break;
|
||||
case Offsets::FRAMEPOINT_CENTER: mid(0, 3, x, y); break;
|
||||
case Offsets::FRAMEPOINT_RIGHT: mid(2, 3, x, y); break;
|
||||
case Offsets::FRAMEPOINT_BOTTOMLEFT: x = CornerX(c, 1); y = CornerY(c, 1); break;
|
||||
case Offsets::FRAMEPOINT_BOTTOM: mid(1, 3, x, y); break;
|
||||
case Offsets::FRAMEPOINT_BOTTOMRIGHT: x = CornerX(c, 3); y = CornerY(c, 3); break;
|
||||
default: x = 0.0f; y = 0.0f; break;
|
||||
}
|
||||
if (offsetX * offsetX + offsetY * offsetY > 0.00000011920929f) {
|
||||
float dx = CornerX(c, 3) - CornerX(c, 1);
|
||||
float dy = CornerY(c, 3) - CornerY(c, 1);
|
||||
const float length = dy * dy + dx * dx;
|
||||
if (length > 0.00000023841858f) {
|
||||
const float scale = 1.0f / std::sqrt(length);
|
||||
dx *= scale;
|
||||
dy *= scale;
|
||||
}
|
||||
x = offsetX * dx - offsetY * dy + x;
|
||||
y = offsetY * dx + offsetX * dy + y;
|
||||
}
|
||||
}
|
||||
|
||||
// The font string that takes a position animation, or nullptr.
|
||||
AnimData *AnimatedString(void *region, void *target) {
|
||||
if (target != nullptr && target != region)
|
||||
return nullptr;
|
||||
AnimData *data = DataOf(region);
|
||||
if (data == nullptr || !data->hasPosition || !IsFontString(region))
|
||||
return nullptr;
|
||||
return data;
|
||||
}
|
||||
|
||||
// The texture that takes a position animation (the target filter of the
|
||||
// region overrides), or nullptr.
|
||||
float *AnimatedCorners(void *region, void *target) {
|
||||
if (target != nullptr && target != region)
|
||||
return nullptr;
|
||||
const AnimData *data = DataOf(region);
|
||||
if (data == nullptr || !data->hasPosition || !IsTexture(region))
|
||||
return nullptr;
|
||||
return Corners(region);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void AddAnimScale(void *region, void *target, int origin, float offsetX, float offsetY, float x, float y) {
|
||||
if (IsFrame(region)) {
|
||||
// CSimpleFrame::AddAnimScale.
|
||||
if (target == region)
|
||||
target = nullptr;
|
||||
ForEachChild(region, [=](void *child) { AddAnimScale(child, target, origin, offsetX, offsetY, x, y); });
|
||||
return;
|
||||
}
|
||||
// CSimpleFontString::AddAnimScale: the text grows from its origin by the
|
||||
// x scale; the last scale animation of the update wins.
|
||||
if (AnimData *data = AnimatedString(region, target)) {
|
||||
data->scale = 1.0f - x;
|
||||
return;
|
||||
}
|
||||
// CSimpleTexture::AddAnimScale -> ApplyScaleAnim.
|
||||
float *c = AnimatedCorners(region, target);
|
||||
if (c == nullptr)
|
||||
return;
|
||||
float cx, cy;
|
||||
GetOriginOffset(origin, c, offsetX, offsetY, cx, cy);
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
c[i * 3 + 0] = (cx - c[i * 3 + 0]) * x + c[i * 3 + 0];
|
||||
c[i * 3 + 1] = (cy - c[i * 3 + 1]) * y + c[i * 3 + 1];
|
||||
}
|
||||
}
|
||||
|
||||
void AddAnimRotation(void *region, void *target, int origin, float offsetX, float offsetY, float radians) {
|
||||
if (IsFrame(region)) {
|
||||
// CSimpleFrame::AddAnimRotation.
|
||||
if (target == region)
|
||||
target = nullptr;
|
||||
ForEachChild(region, [=](void *child) { AddAnimRotation(child, target, origin, offsetX, offsetY, radians); });
|
||||
return;
|
||||
}
|
||||
// CSimpleFontString::AddAnimRotation: the text turns about its origin;
|
||||
// the last rotation animation of the update wins.
|
||||
if (AnimData *data = AnimatedString(region, target)) {
|
||||
data->rotation = radians;
|
||||
return;
|
||||
}
|
||||
// CSimpleTexture::AddAnimRotation -> ApplyRotationAnim.
|
||||
float *c = AnimatedCorners(region, target);
|
||||
if (c == nullptr)
|
||||
return;
|
||||
float cx, cy;
|
||||
GetOriginOffset(origin, c, offsetX, offsetY, cx, cy);
|
||||
const float cs = std::cos(radians);
|
||||
const float sn = std::sin(radians);
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
const float x = c[i * 3 + 0] - cx;
|
||||
const float y = c[i * 3 + 1] - cy;
|
||||
c[i * 3 + 0] = x * cs - y * sn + cx;
|
||||
c[i * 3 + 1] = x * sn + y * cs + cy;
|
||||
}
|
||||
}
|
||||
|
||||
void FontStringBaked(void *node, void *fontString) {
|
||||
if (g_data.empty())
|
||||
return;
|
||||
AnimData *data = DataOf(fontString);
|
||||
if (data == nullptr)
|
||||
return;
|
||||
if (data->rotation != 0.0f || data->scale != 1.0f)
|
||||
Texture::Transform::ScaleRotateFontStringNode(node, data->scale, data->rotation);
|
||||
data->bakedRotation = data->rotation;
|
||||
data->bakedScale = data->scale;
|
||||
}
|
||||
|
||||
float *TextureBaseCorners(void *texture) {
|
||||
if (g_data.empty())
|
||||
return nullptr;
|
||||
AnimData *data = DataOf(texture);
|
||||
return data != nullptr && data->hasPosition && IsTexture(texture) ? data->position : nullptr;
|
||||
}
|
||||
|
||||
bool StringAnimated(void *fontString) {
|
||||
if (g_data.empty())
|
||||
return false;
|
||||
const AnimData *data = DataOf(fontString);
|
||||
return data != nullptr && (data->rotation != 0.0f || data->scale != 1.0f || data->bakedRotation != 0.0f ||
|
||||
data->bakedScale != 1.0f);
|
||||
}
|
||||
|
||||
void *FindRegionByName(const char *name) {
|
||||
void *L = Game::Lua::State();
|
||||
if (L == nullptr || name == nullptr)
|
||||
return nullptr;
|
||||
Game::Lua::PushString(L, name);
|
||||
Game::Lua::RawGet(L, Game::Lua::GLOBALS_INDEX);
|
||||
void *object = Game::Lua::Type(L, -1) == Game::Lua::TYPE_TABLE ? Game::Lua::ResolveObject(L, -1) : nullptr;
|
||||
Game::Lua::SetTop(L, -2);
|
||||
if (object == nullptr || IsOurs(object) || !Game::Lua::IsA(object, Offsets::VAR_REGION_LUA_TYPE_ID))
|
||||
return nullptr;
|
||||
return object;
|
||||
}
|
||||
|
||||
} // namespace Animation::Region
|
||||
@@ -0,0 +1,62 @@
|
||||
// This file is part of ClassicAPI.
|
||||
//
|
||||
// ClassicAPI is free software: you can redistribute it and/or modify it under the terms
|
||||
// of the GNU 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 General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License along with
|
||||
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
// The region side of the animation system: 4.3.4's CScriptRegion animation
|
||||
// members (m_animGroups, m_playingAnimGroups, the CLayoutFrame animation
|
||||
// data) and their virtuals on CSimpleFrame and CSimpleRegion, for 1.12's
|
||||
// frames, textures and font strings, which have no room for them.
|
||||
namespace Animation {
|
||||
class Group;
|
||||
}
|
||||
|
||||
namespace Animation::Region {
|
||||
|
||||
// CScriptRegion::RegisterAnimGroup - the region owns the group from now on.
|
||||
void RegisterGroup(void *region, Group *group);
|
||||
// CScriptRegion::NotifyAnimBegin / NotifyAnimEnd.
|
||||
void NotifyBegin(void *region, Group *group);
|
||||
void NotifyEnd(void *region, Group *group);
|
||||
// CScriptRegion::PreOnAnimUpdate: put the animated state back to its base
|
||||
// before the animations apply themselves for this update.
|
||||
void PreOnAnimUpdate(void *region);
|
||||
// CScriptRegion::AddAnimAlpha(target, alpha) on the group's region.
|
||||
void AddAnimAlpha(void *region, void *target, int16_t alpha);
|
||||
// CScriptRegion::AddAnimTranslation(target, translation), in layout units:
|
||||
// moves the drawn textures and font strings, never a rect.
|
||||
void AddAnimTranslation(void *region, void *target, float x, float y);
|
||||
// CScriptRegion::AddAnimScale(target, origin, offset, scale): `x`/`y` are the
|
||||
// share of the way to the origin (1 - scale at full progress).
|
||||
void AddAnimScale(void *region, void *target, int origin, float offsetX, float offsetY, float x, float y);
|
||||
// CScriptRegion::AddAnimRotation(target, origin, offset, radians),
|
||||
// counter-clockwise.
|
||||
void AddAnimRotation(void *region, void *target, int origin, float offsetX, float offsetY, float radians);
|
||||
// A font string's glyphs were just baked (the draw builder): turn and scale
|
||||
// them by its animation, and remember what they were baked with.
|
||||
void FontStringBaked(void *node, void *fontString);
|
||||
// The stored corners (TL BL TR BR {x, y, z}) of a texture a position group
|
||||
// is playing on, or nullptr. Each update draws the animation on top of them,
|
||||
// so a change to the texture's own shape (Texture::Transform) goes here, not
|
||||
// to the drawn corners.
|
||||
float *TextureBaseCorners(void *texture);
|
||||
// Whether the font string's glyphs carry an animation's rotation or scale:
|
||||
// then a change to its own rotation has to bake them again.
|
||||
bool StringAnimated(void *fontString);
|
||||
// CScriptObject::GetScriptObjectByName for a region (Animation:Play's
|
||||
// target lookup): the region named `name`, or nullptr.
|
||||
void *FindRegionByName(const char *name);
|
||||
|
||||
} // namespace Animation::Region
|
||||
@@ -0,0 +1,378 @@
|
||||
// This file is part of ClassicAPI.
|
||||
//
|
||||
// ClassicAPI is free software: you can redistribute it and/or modify it under the terms
|
||||
// of the GNU 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 General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License along with
|
||||
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
// 4.3.4's animation XML (CScriptRegion::LoadXML_Animations,
|
||||
// CSimpleAnimGroup::LoadXML, CSimpleAnim::LoadXML and the subclasses',
|
||||
// LoadXML_AnimOrigin; the attributes BinaryXML.cpp parses), on 1.12 nodes.
|
||||
// A script body compiles through the engine's own SetScriptObjectScript, so
|
||||
// it is named "<object>:<script>" and handled like a frame's.
|
||||
|
||||
#include "animation/Xml.h"
|
||||
|
||||
#include "animation/Classes.h"
|
||||
|
||||
#include "Game.h"
|
||||
#include "Offsets.h"
|
||||
#include "baselib/Ascii.h"
|
||||
#include "xml/FrameLoad.h"
|
||||
#include "xml/KeyValues.h"
|
||||
#include "xml/Mixin.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <string>
|
||||
|
||||
namespace Animation::Xml {
|
||||
|
||||
namespace {
|
||||
|
||||
using SetScriptText_t = bool(__fastcall *)(void *object, void *edx, const char *name, const char *text);
|
||||
using StringToPoint_t = int(__fastcall *)(const char *name, int *point);
|
||||
using LuaRef_t = int(__fastcall *)(void *L, int t);
|
||||
|
||||
const void *FindChild(const void *node, const char *tag) {
|
||||
for (const void *c = ::Xml::FirstChild(node); c != nullptr; c = ::Xml::NextSibling(c))
|
||||
if (::Xml::TagIs(c, tag))
|
||||
return c;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
bool FloatAttr(const void *node, const char *name, float &out) {
|
||||
const char *v = ::Xml::Attr(node, name);
|
||||
if (v == nullptr || *v == '\0')
|
||||
return false;
|
||||
out = static_cast<float>(std::atof(v));
|
||||
return true;
|
||||
}
|
||||
|
||||
// object[parentKey] = child, as 4.3.4's LoadXML does for both.
|
||||
void BindParentKey(void *object, Object *child, const char *key) {
|
||||
if (key == nullptr || *key == '\0')
|
||||
return;
|
||||
void *L = Game::Lua::State();
|
||||
if (L == nullptr)
|
||||
return;
|
||||
const int top = Game::Lua::GetTop(L);
|
||||
if (::Xml::PushWrapper(L, object)) {
|
||||
Game::Lua::PushString(L, key);
|
||||
Push(L, child);
|
||||
Game::Lua::SetTable(L, -3);
|
||||
}
|
||||
Game::Lua::SetTop(L, top);
|
||||
}
|
||||
|
||||
// <Scripts>: each element's body, its `function` global, or its `method`
|
||||
// field on the object.
|
||||
void LoadScripts(Object *object, const void *node) {
|
||||
const void *scripts = FindChild(node, "Scripts");
|
||||
if (scripts == nullptr)
|
||||
return;
|
||||
for (const void *s = ::Xml::FirstChild(scripts); s != nullptr; s = ::Xml::NextSibling(s)) {
|
||||
const char *script = ::Xml::Tag(s);
|
||||
if (script == nullptr)
|
||||
continue;
|
||||
const char *function = ::Xml::Attr(s, "function");
|
||||
const char *method = ::Xml::Attr(s, "method");
|
||||
const bool byFunction = function != nullptr && *function != '\0';
|
||||
if (byFunction || (method != nullptr && *method != '\0')) {
|
||||
uint32_t *slot = object->ScriptSlot(script);
|
||||
void *L = Game::Lua::State();
|
||||
if (slot == nullptr || L == nullptr)
|
||||
continue;
|
||||
if (byFunction) {
|
||||
Game::Lua::PushString(L, function);
|
||||
Game::Lua::GetTable(L, Game::Lua::GLOBALS_INDEX);
|
||||
} else {
|
||||
Push(L, object);
|
||||
Game::Lua::PushString(L, method);
|
||||
Game::Lua::GetTable(L, -2);
|
||||
Game::Lua::Remove(L, -2);
|
||||
}
|
||||
if (Game::Lua::Type(L, -1) != Game::Lua::TYPE_FUNCTION) {
|
||||
Game::Lua::SetTop(L, -2);
|
||||
continue;
|
||||
}
|
||||
reinterpret_cast<void(__stdcall *)(uint32_t *)>(Offsets::FUN_SCRIPT_RELEASE)(slot);
|
||||
slot[0] = static_cast<uint32_t>(reinterpret_cast<LuaRef_t>(Offsets::LUA_REF_REF)(L, Game::Lua::REGISTRY_INDEX));
|
||||
slot[1] = 0;
|
||||
continue;
|
||||
}
|
||||
const char *body = Game::Read<const char *>(s, Offsets::OFF_XML_NODE_TEXT);
|
||||
if (body != nullptr && *body != '\0')
|
||||
reinterpret_cast<SetScriptText_t>(Offsets::FUN_SCRIPT_OBJECT_SET_SCRIPT_TEXT)(object, nullptr, script,
|
||||
body);
|
||||
}
|
||||
}
|
||||
|
||||
// <KeyValues> on a group or an animation, as on later clients' schema.
|
||||
void LoadKeyValues(Object *object, const void *node, void *status) {
|
||||
void *L = Game::Lua::State();
|
||||
if (L == nullptr)
|
||||
return;
|
||||
const int top = Game::Lua::GetTop(L);
|
||||
Push(L, object);
|
||||
::Xml::KeyValues::Apply(L, top + 1, node, status, object->DisplayName());
|
||||
Game::Lua::SetTop(L, top);
|
||||
}
|
||||
|
||||
// LoadXML_AnimOrigin: <Origin point="..."><Offset x= y=/></Origin>.
|
||||
void LoadOrigin(Anim *anim, const void *node) {
|
||||
const void *origin = FindChild(node, "Origin");
|
||||
if (origin == nullptr)
|
||||
return;
|
||||
int point = Offsets::FRAMEPOINT_CENTER;
|
||||
float x = 0.0f, y = 0.0f;
|
||||
const char *pointName = ::Xml::Attr(origin, "point");
|
||||
if (pointName != nullptr &&
|
||||
reinterpret_cast<StringToPoint_t>(Offsets::FUN_STRING_TO_FRAME_POINT)(pointName, &point)) {
|
||||
if (const void *offset = FindChild(origin, "Offset")) {
|
||||
const void *abs = FindChild(offset, "AbsDimension");
|
||||
const void *dim = abs != nullptr ? abs : offset;
|
||||
FloatAttr(dim, "x", x);
|
||||
FloatAttr(dim, "y", y);
|
||||
}
|
||||
} else {
|
||||
point = Offsets::FRAMEPOINT_CENTER;
|
||||
}
|
||||
anim->originPoint = point;
|
||||
anim->originX = Game::PixelToInternal(x);
|
||||
anim->originY = Game::PixelToInternal(y);
|
||||
}
|
||||
|
||||
void LoadAnimChildren(Group *group, const void *node, void *status) {
|
||||
for (const void *child = ::Xml::FirstChild(node); child != nullptr; child = ::Xml::NextSibling(child)) {
|
||||
const char *tag = ::Xml::Tag(child);
|
||||
if (tag == nullptr || ::Xml::TagIs(child, "Scripts"))
|
||||
continue;
|
||||
// 4.3.4 knows Animation, Translation, Rotation, Scale, Path and Alpha.
|
||||
if (!::Xml::TagIs(child, "Animation") && !::Xml::TagIs(child, "Translation") &&
|
||||
!::Xml::TagIs(child, "Rotation") && !::Xml::TagIs(child, "Scale") && !::Xml::TagIs(child, "Alpha") &&
|
||||
!::Xml::TagIs(child, "Path"))
|
||||
continue;
|
||||
Anim *anim = new Anim(group, Anim::KindOf(tag), ::Xml::Attr(child, "name"));
|
||||
anim->flags |= 1;
|
||||
LoadAnim(anim, child, status);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
const void *Template(const char *name) { return ::Xml::Template(name); }
|
||||
|
||||
namespace {
|
||||
|
||||
// LoadGroup re-enters itself for each inherited template; the mixins of the
|
||||
// whole chain go in once, from the outermost call, before any node's
|
||||
// KeyValues or scripts (see Xml::Mixin).
|
||||
int g_groupDepth = 0;
|
||||
|
||||
void LoadGroupNode(Group *group, const void *node, void *status);
|
||||
|
||||
} // namespace
|
||||
|
||||
void LoadGroup(Group *group, const void *node, void *status) {
|
||||
if (g_groupDepth == 0) {
|
||||
if (void *L = Game::Lua::State()) {
|
||||
const int top = Game::Lua::GetTop(L);
|
||||
Push(L, group);
|
||||
::Xml::Mixin::ApplyChain(L, top + 1, node, status, group->DisplayName(), false);
|
||||
Game::Lua::SetTop(L, top);
|
||||
}
|
||||
}
|
||||
++g_groupDepth;
|
||||
LoadGroupNode(group, node, status);
|
||||
--g_groupDepth;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
void LoadGroupNode(Group *group, const void *node, void *status) {
|
||||
group->flags |= GROUP_LOADING;
|
||||
if (const char *inherits = ::Xml::Attr(node, "inherits"); inherits != nullptr && *inherits != '\0') {
|
||||
const void *base = ::Xml::Template(inherits);
|
||||
if (base == nullptr)
|
||||
::Xml::Warn(status, "Couldn't find inherited node: %s", inherits);
|
||||
else
|
||||
LoadGroupNode(group, base, status);
|
||||
}
|
||||
BindParentKey(group->RegionObject(), group, ::Xml::Attr(node, "parentKey"));
|
||||
if (const char *looping = ::Xml::Attr(node, "looping"); looping != nullptr && *looping != '\0') {
|
||||
LoopType type;
|
||||
if (StringToLoopType(looping, type))
|
||||
group->loopType = type;
|
||||
else
|
||||
::Xml::Warn(status, "AnimationGroup %s: Invalid looping value: %s", group->DisplayName(), looping);
|
||||
}
|
||||
float x = 0.0f, y = 0.0f;
|
||||
FloatAttr(node, "initialOffsetX", x);
|
||||
FloatAttr(node, "initialOffsetY", y);
|
||||
x = Game::PixelToInternal(x);
|
||||
y = Game::PixelToInternal(y);
|
||||
if (x * x + y * y <= 0.00000023841858f) {
|
||||
group->initialOffsetX = 0.0f;
|
||||
group->initialOffsetY = 0.0f;
|
||||
} else {
|
||||
group->initialOffsetX = x;
|
||||
group->initialOffsetY = y;
|
||||
}
|
||||
LoadScripts(group, node);
|
||||
LoadKeyValues(group, node, status);
|
||||
LoadAnimChildren(group, node, status);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void LoadAnim(Anim *anim, const void *node, void *status) {
|
||||
// The subclass reads its values, then CSimpleAnim::LoadXML (inherits
|
||||
// first, then the shared attributes) - the order 4.3.4's overrides use.
|
||||
float x = 0.0f, y = 0.0f;
|
||||
switch (anim->kind) {
|
||||
case KIND_ALPHA:
|
||||
break; // CSimpleAlphaAnim::LoadXML reads `change` after the base.
|
||||
case KIND_TRANSLATION: {
|
||||
// CSimpleTranslationAnim::LoadXML sets the offset, 0 for a missing axis.
|
||||
FloatAttr(node, "offsetX", x);
|
||||
FloatAttr(node, "offsetY", y);
|
||||
const float ox = Game::PixelToInternal(x), oy = Game::PixelToInternal(y);
|
||||
const bool zero = ox * ox + oy * oy <= 0.00000023841858f;
|
||||
anim->offsetX = zero ? 0.0f : ox;
|
||||
anim->offsetY = zero ? 0.0f : oy;
|
||||
break;
|
||||
}
|
||||
case KIND_ROTATION:
|
||||
if (FloatAttr(node, "degrees", x))
|
||||
anim->radians = x * 0.017453292f;
|
||||
if (FloatAttr(node, "radians", y))
|
||||
anim->radians = y;
|
||||
break;
|
||||
case KIND_SCALE: {
|
||||
float sx = 1.0f, sy = 1.0f;
|
||||
if (FloatAttr(node, "scaleX", sx) && sx < 0.001f)
|
||||
::Xml::Warn(status, "%s: Invalid scaleX value: %s. Value must be at least 0.001.", anim->DisplayName(),
|
||||
::Xml::Attr(node, "scaleX"));
|
||||
if (FloatAttr(node, "scaleY", sy) && sy < 0.001f)
|
||||
::Xml::Warn(status, "%s: Invalid scaleY value: %s. Value must be at least 0.001.", anim->DisplayName(),
|
||||
::Xml::Attr(node, "scaleY"));
|
||||
anim->scaleChangeX = 1.0f - (sx >= 0.001f ? sx : 0.001f);
|
||||
anim->scaleChangeY = 1.0f - (sy >= 0.001f ? sy : 0.001f);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
// CSimpleAnim::LoadXML.
|
||||
anim->flags |= 1;
|
||||
if (const char *inherits = ::Xml::Attr(node, "inherits"); inherits != nullptr && *inherits != '\0') {
|
||||
const void *base = ::Xml::Template(inherits);
|
||||
if (base == nullptr)
|
||||
::Xml::Warn(status, "Couldn't find inherited node: %s", inherits);
|
||||
else
|
||||
LoadAnim(anim, base, status);
|
||||
}
|
||||
BindParentKey(anim->GetGroup(), anim, ::Xml::Attr(node, "parentKey"));
|
||||
if (const char *target = ::Xml::Attr(node, "target"); target != nullptr && *target != '\0') {
|
||||
const std::string name = CreateName(target, anim);
|
||||
if (name.size() + 1 > sizeof(anim->targetName))
|
||||
::Xml::Warn(status, "target key too long: %s", name.c_str());
|
||||
std::snprintf(anim->targetName, sizeof(anim->targetName), "%s", name.c_str());
|
||||
}
|
||||
if (FloatAttr(node, "startDelay", x))
|
||||
anim->startDelay = x < 0.0f ? 0.0f : x;
|
||||
if (FloatAttr(node, "endDelay", x))
|
||||
anim->endDelay = x < 0.0f ? 0.0f : x;
|
||||
if (FloatAttr(node, "duration", x))
|
||||
anim->duration = x;
|
||||
if (const char *smoothing = ::Xml::Attr(node, "smoothing"); smoothing != nullptr && *smoothing != '\0') {
|
||||
float in, out;
|
||||
if (StringToSmoothWeights(smoothing, in, out))
|
||||
anim->SetSmoothing(in, out);
|
||||
else
|
||||
::Xml::Warn(status, "%s: Invalid smoothing value: %s", anim->DisplayName(), smoothing);
|
||||
}
|
||||
if (const char *order = ::Xml::Attr(node, "order"); order != nullptr && *order != '\0') {
|
||||
const int value = std::atoi(order) - 1;
|
||||
if (value < 0 || value > 99)
|
||||
::Xml::Warn(status, "%s: Invalid order value: %s. Order must be between 1 and 100.", anim->DisplayName(),
|
||||
order);
|
||||
anim->order = value < 0 ? 0 : (value > 99 ? 99 : value);
|
||||
}
|
||||
LoadScripts(anim, node);
|
||||
LoadKeyValues(anim, node, status);
|
||||
|
||||
// The subclasses' reads after the base.
|
||||
// CSimpleAlphaAnim::LoadXML sets the change, 0 when it is missing.
|
||||
if (anim->kind == KIND_ALPHA) {
|
||||
x = 0.0f;
|
||||
if (FloatAttr(node, "change", x) && (x < -1.0f || x > 1.0f)) {
|
||||
::Xml::Warn(status, "%s: Invalid change value: %s. Value must be between -1 and 1, inclusive.",
|
||||
anim->DisplayName(), ::Xml::Attr(node, "change"));
|
||||
x = 0.0f;
|
||||
}
|
||||
anim->change = static_cast<int16_t>((x < -1.0f ? -1.0f : (x >= 1.0f ? 1.0f : x)) * 255.0f);
|
||||
}
|
||||
if (anim->kind == KIND_SCALE || anim->kind == KIND_ROTATION)
|
||||
LoadOrigin(anim, node);
|
||||
// CSimplePathAnim::LoadXML: the curve, then <ControlPoints>.
|
||||
if (anim->kind == KIND_PATH) {
|
||||
if (const char *curve = ::Xml::Attr(node, "curve"); curve != nullptr && *curve != '\0') {
|
||||
if (Ascii::EqualCI(curve, "NONE"))
|
||||
anim->curve = false;
|
||||
else if (Ascii::EqualCI(curve, "SMOOTH"))
|
||||
anim->curve = true;
|
||||
else
|
||||
::Xml::Warn(status, "Path %s: Invalid curve value: %s", anim->DisplayName(), curve);
|
||||
}
|
||||
if (const void *points = FindChild(node, "ControlPoints")) {
|
||||
for (const void *child = ::Xml::FirstChild(points); child != nullptr; child = ::Xml::NextSibling(child)) {
|
||||
if (!::Xml::TagIs(child, "ControlPoint")) {
|
||||
::Xml::Warn(status, "Path %s: Error loading Origin element", anim->DisplayName());
|
||||
continue;
|
||||
}
|
||||
LoadControlPoint(new ControlPoint(anim, ::Xml::Attr(child, "name")), child, status);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void LoadControlPoint(ControlPoint *point, const void *node, void *status) {
|
||||
// CSimpleControlPoint::LoadXML: inherits first, then parentKey (on the
|
||||
// path), then the offset - 0 on an axis the node does not give.
|
||||
if (const char *inherits = ::Xml::Attr(node, "inherits"); inherits != nullptr && *inherits != '\0') {
|
||||
const void *base = ::Xml::Template(inherits);
|
||||
if (base == nullptr)
|
||||
::Xml::Warn(status, "Couldn't find inherited node: %s", inherits);
|
||||
else
|
||||
LoadControlPoint(point, base, status);
|
||||
}
|
||||
BindParentKey(point->GetPath(), point, ::Xml::Attr(node, "parentKey"));
|
||||
float x = 0.0f, y = 0.0f;
|
||||
FloatAttr(node, "offsetX", x);
|
||||
FloatAttr(node, "offsetY", y);
|
||||
point->SetOffset(Game::PixelToInternal(x), Game::PixelToInternal(y));
|
||||
}
|
||||
|
||||
void LoadAnimations(void *region, const void *node, void *status) {
|
||||
const void *animations = FindChild(node, "Animations");
|
||||
if (animations == nullptr)
|
||||
return;
|
||||
for (const void *g = ::Xml::FirstChild(animations); g != nullptr; g = ::Xml::NextSibling(g)) {
|
||||
if (!::Xml::TagIs(g, "AnimationGroup"))
|
||||
continue;
|
||||
Group *group = new Group(region, ::Xml::Attr(g, "name"));
|
||||
LoadGroup(group, g, status);
|
||||
group->PostLoadXML();
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace Animation::Xml
|
||||
@@ -0,0 +1,42 @@
|
||||
// This file is part of ClassicAPI.
|
||||
//
|
||||
// ClassicAPI is free software: you can redistribute it and/or modify it under the terms
|
||||
// of the GNU 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 General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License along with
|
||||
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#pragma once
|
||||
|
||||
// <Animations>, <AnimationGroup> and the animation elements: 4.3.4's
|
||||
// CScriptRegion::LoadXML_AnimGroup, CSimpleAnimGroup::LoadXML and
|
||||
// CSimpleAnim::LoadXML (and the subclasses'), on 1.12's XML nodes. A
|
||||
// virtual top-level <AnimationGroup> or animation element is a template:
|
||||
// 1.12's file loader registers every virtual named top-level node
|
||||
// (RegisterXMLTemplate), whatever its tag, so `inherits` resolves through
|
||||
// Xml::Template as 4.3.4's XMLHashNodeRef does.
|
||||
namespace Animation {
|
||||
class Group;
|
||||
class Anim;
|
||||
class ControlPoint;
|
||||
} // namespace Animation
|
||||
|
||||
namespace Animation::Xml {
|
||||
|
||||
// The <Animations> child of a region's node, if any: each <AnimationGroup>
|
||||
// becomes a group of `region`, loaded and post-loaded (OnLoad runs).
|
||||
void LoadAnimations(void *region, const void *node, void *status);
|
||||
// CSimpleAnimGroup::LoadXML / CSimpleAnim::LoadXML of one node, its
|
||||
// `inherits` first.
|
||||
void LoadGroup(Group *group, const void *node, void *status);
|
||||
void LoadAnim(Anim *anim, const void *node, void *status);
|
||||
void LoadControlPoint(ControlPoint *point, const void *node, void *status);
|
||||
// The template node `name` resolves to, or nullptr.
|
||||
const void *Template(const char *name);
|
||||
|
||||
} // namespace Animation::Xml
|
||||
@@ -0,0 +1,703 @@
|
||||
// This file is part of ClassicAPI.
|
||||
//
|
||||
// ClassicAPI is free software: you can redistribute it and/or modify it under the terms
|
||||
// of the GNU 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 General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License along with
|
||||
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
// API documentation: the record of every Lua registration plus its
|
||||
// descriptor, exported on demand as Blizzard `APIDocumentation` tables.
|
||||
//
|
||||
// C_APIDocumentation.GetSystems() -> sorted array of system Names
|
||||
// C_APIDocumentation.GetSystem(name) -> one System table (Blizzard shape), or nil
|
||||
// _classicapi_UndocumentedAPI() -> array of registrations lacking a
|
||||
// descriptor, and its count
|
||||
//
|
||||
// The registrars in Game.cpp call `Record*` (see Documentation.h). Recording
|
||||
// runs once per Lua state — the first in-game pass and the first glue pass —
|
||||
// because the set of registrations is static: every module registers the
|
||||
// same names on every `/reload`. The recorded list is never materialized
|
||||
// into Lua wholesale; `GetSystem` builds ONE system's table per call, which
|
||||
// is how Blizzard's browser loads too (its generated data addon is
|
||||
// LoadOnDemand). Eager export would create thousands of tables on every
|
||||
// `/reload` for a feature used from a slash command.
|
||||
//
|
||||
// System grouping is derived, never authored, except for two strings:
|
||||
// - `C_Spell.X` -> System "Spell", Namespace "C_Spell" (strip `C_`)
|
||||
// - `table.insert` -> System "table", Namespace "table"
|
||||
// - a global -> `doc->system` ("SpellGlobals"); a global whose
|
||||
// descriptor names no system has no home and is
|
||||
// listed by the coverage function
|
||||
// - a frame method -> Blizzard's widget system for its registry
|
||||
// ("SimpleTextureAPI", Type "ScriptObject")
|
||||
// - an enum / structure /
|
||||
// event -> the System named in its declaration
|
||||
// A system's `Environment` is "All" when its functions were recorded in both
|
||||
// Lua states, else "Game" or "Glue"; a function whose own environment is
|
||||
// narrower than its system's gets a Documentation line saying so.
|
||||
|
||||
#include "api/Documentation.h"
|
||||
|
||||
#include "Game.h"
|
||||
#include "Offsets.h"
|
||||
#include "debug/Log.h"
|
||||
#include "event/Custom.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Api::Documentation {
|
||||
|
||||
using Game::Doc::Field;
|
||||
using Game::Doc::FieldList;
|
||||
using Game::Doc::Function;
|
||||
using Game::Doc::Method;
|
||||
using Game::Doc::Structure;
|
||||
// NOT `using Game::Doc::Event` — that name would shadow the global `Event`
|
||||
// namespace for the whole file, so `Event::Custom::…` would resolve to the
|
||||
// type. Same trap as `Time::Tick` vs the `Tick` namespace (see CLAUDE.md).
|
||||
using EventDoc = Game::Doc::Event;
|
||||
|
||||
// Head of the self-registering `Structure` list. Constant-initialized, so it
|
||||
// is valid before any `Structure` constructor runs, whatever the cross-TU
|
||||
// static-init order.
|
||||
const Structure *g_structureHead = nullptr;
|
||||
|
||||
namespace {
|
||||
|
||||
enum Kind : uint8_t {
|
||||
KIND_GLOBAL, // RegisterGlobalFunction / RegisterGlueFunction / RegisterGlobalAlias
|
||||
KIND_TABLE, // RegisterTableFunction
|
||||
KIND_FRAME_METHOD, // RegisterFrameMethods, one per entry
|
||||
KIND_ENUM, // RegisterIntegerEnum
|
||||
KIND_ORPHAN_METHOD_DOC // a Doc::Method naming no entry in its table
|
||||
};
|
||||
|
||||
struct Entry {
|
||||
Kind kind;
|
||||
unsigned env; // Env bits the registration was recorded in
|
||||
const char *table; // KIND_TABLE: the namespace; KIND_ENUM: the parent ("Enum")
|
||||
const char *name; // registered name / method name / enum sub-name
|
||||
const void *registry; // frame methods only
|
||||
const Function *doc; // nullptr = undocumented
|
||||
const char *enumSystem;
|
||||
const Game::Lua::EnumIntegerEntry *enumEntries;
|
||||
int enumCount;
|
||||
};
|
||||
|
||||
std::vector<Entry> g_entries;
|
||||
Env g_pass = ENV_NONE;
|
||||
unsigned g_sealed = 0;
|
||||
int g_recordedThisPass = 0;
|
||||
|
||||
constexpr const char *kDebugPrefix = "_classicapi_";
|
||||
|
||||
bool IsDebugName(const char *name) {
|
||||
return std::strncmp(name, kDebugPrefix, std::strlen(kDebugPrefix)) == 0;
|
||||
}
|
||||
|
||||
bool SameText(const char *a, const char *b) {
|
||||
if (a == nullptr || b == nullptr)
|
||||
return a == b;
|
||||
return std::strcmp(a, b) == 0;
|
||||
}
|
||||
|
||||
bool SameTextNoCase(const char *a, const char *b) {
|
||||
if (a == nullptr || b == nullptr)
|
||||
return a == b;
|
||||
return _stricmp(a, b) == 0;
|
||||
}
|
||||
|
||||
Entry *Find(Kind kind, const char *table, const char *name, const void *registry) {
|
||||
for (Entry &e : g_entries) {
|
||||
if (e.kind == kind && e.registry == registry && SameText(e.table, table) &&
|
||||
SameText(e.name, name))
|
||||
return &e;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void Record(Kind kind, const char *table, const char *name, const void *registry,
|
||||
const Function *doc) {
|
||||
if (g_pass == ENV_NONE || name == nullptr)
|
||||
return;
|
||||
++g_recordedThisPass;
|
||||
if (Entry *e = Find(kind, table, name, registry)) {
|
||||
e->env |= g_pass;
|
||||
if (e->doc == nullptr)
|
||||
e->doc = doc;
|
||||
return;
|
||||
}
|
||||
Entry e{};
|
||||
e.kind = kind;
|
||||
e.env = g_pass;
|
||||
e.table = table;
|
||||
e.name = name;
|
||||
e.registry = registry;
|
||||
e.doc = doc;
|
||||
g_entries.push_back(e);
|
||||
}
|
||||
|
||||
// ---- System resolution ------------------------------------------------------
|
||||
|
||||
// Blizzard's names for the widget-method systems, keyed by the engine
|
||||
// registry each `FrameMethodEntry[]` is bound to.
|
||||
struct WidgetSystem {
|
||||
uintptr_t registry;
|
||||
const char *system;
|
||||
};
|
||||
const WidgetSystem kWidgetSystems[] = {
|
||||
{Offsets::VAR_GAMETOOLTIP_METHOD_REGISTRY, "GameTooltipAPI"},
|
||||
{Offsets::VAR_REGION_METHOD_REGISTRY, "ScriptRegionAPI"},
|
||||
{Offsets::VAR_FRAME_METHOD_REGISTRY, "SimpleFrameAPI"},
|
||||
{Offsets::VAR_TEXTURE_METHOD_REGISTRY, "SimpleTextureAPI"},
|
||||
{Offsets::VAR_FONTSTRING_METHOD_REGISTRY, "SimpleFontStringAPI"},
|
||||
{Offsets::VAR_FONT_METHOD_REGISTRY, "SimpleFontAPI"},
|
||||
{Offsets::VAR_EDITBOX_METHOD_REGISTRY, "SimpleEditBoxAPI"},
|
||||
{Offsets::VAR_MODEL_METHOD_REGISTRY, "SimpleModelAPI"},
|
||||
};
|
||||
|
||||
// Hashes of the frame classes this DLL adds (NameWidgetSystem).
|
||||
std::vector<WidgetSystem> g_ownWidgetSystems;
|
||||
|
||||
const char *WidgetSystemFor(const void *registry) {
|
||||
for (const WidgetSystem &w : kWidgetSystems)
|
||||
if (reinterpret_cast<const void *>(w.registry) == registry)
|
||||
return w.system;
|
||||
for (const WidgetSystem &w : g_ownWidgetSystems)
|
||||
if (reinterpret_cast<const void *>(w.registry) == registry)
|
||||
return w.system;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// "C_Spell" -> "Spell"; anything else is its own system name.
|
||||
const char *SystemNameForTable(const char *table) {
|
||||
if (table[0] == 'C' && table[1] == '_' && table[2] != '\0')
|
||||
return table + 2;
|
||||
return table;
|
||||
}
|
||||
|
||||
// The System an entry contributes a function to, or nullptr when it has
|
||||
// none (an undocumented global, a frame method on an unmapped registry).
|
||||
const char *SystemOf(const Entry &e) {
|
||||
switch (e.kind) {
|
||||
case KIND_TABLE:
|
||||
return SystemNameForTable(e.table);
|
||||
case KIND_GLOBAL:
|
||||
return e.doc != nullptr ? e.doc->system : nullptr;
|
||||
case KIND_FRAME_METHOD:
|
||||
return WidgetSystemFor(e.registry);
|
||||
case KIND_ENUM:
|
||||
return e.enumSystem;
|
||||
default:
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
struct SystemInfo {
|
||||
const char *name;
|
||||
const char *ns; // nullptr for global and widget systems
|
||||
const char *type; // "System" or "ScriptObject"
|
||||
unsigned env; // Env bits; 0 when nothing recorded (structures only)
|
||||
};
|
||||
|
||||
// Merge one entry's contribution into the system list.
|
||||
void AddSystem(std::vector<SystemInfo> &systems, const char *name, const char *ns,
|
||||
const char *type, unsigned env) {
|
||||
if (name == nullptr)
|
||||
return;
|
||||
for (SystemInfo &s : systems) {
|
||||
if (SameTextNoCase(s.name, name)) {
|
||||
if (s.ns == nullptr)
|
||||
s.ns = ns;
|
||||
if (type != nullptr)
|
||||
s.type = type;
|
||||
s.env |= env;
|
||||
return;
|
||||
}
|
||||
}
|
||||
systems.push_back(SystemInfo{name, ns, type != nullptr ? type : "System", env});
|
||||
}
|
||||
|
||||
std::vector<SystemInfo> CollectSystems() {
|
||||
std::vector<SystemInfo> systems;
|
||||
for (const Entry &e : g_entries) {
|
||||
switch (e.kind) {
|
||||
case KIND_TABLE:
|
||||
AddSystem(systems, SystemNameForTable(e.table), e.table, "System", e.env);
|
||||
break;
|
||||
case KIND_GLOBAL:
|
||||
AddSystem(systems, SystemOf(e), nullptr, "System", e.env);
|
||||
break;
|
||||
case KIND_FRAME_METHOD:
|
||||
AddSystem(systems, SystemOf(e), nullptr, "ScriptObject", e.env);
|
||||
break;
|
||||
case KIND_ENUM:
|
||||
AddSystem(systems, e.enumSystem, nullptr, nullptr, 0);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (const Structure *s = g_structureHead; s != nullptr; s = s->next)
|
||||
AddSystem(systems, s->system, nullptr, nullptr, 0);
|
||||
const int events = Event::Custom::ReservedCount();
|
||||
for (int i = 0; i < events; ++i) {
|
||||
const EventDoc *doc = Event::Custom::ReservedDoc(i);
|
||||
if (doc != nullptr)
|
||||
AddSystem(systems, doc->system, nullptr, nullptr, 0);
|
||||
}
|
||||
return systems;
|
||||
}
|
||||
|
||||
const SystemInfo *FindSystem(const std::vector<SystemInfo> &systems, const char *query) {
|
||||
for (const SystemInfo &s : systems)
|
||||
if (SameTextNoCase(s.name, query) || SameTextNoCase(s.ns, query))
|
||||
return &s;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
const char *EnvironmentName(unsigned env) {
|
||||
if (env == (ENV_GAME | ENV_GLUE) || env == 0)
|
||||
return "All";
|
||||
return env == ENV_GLUE ? "Glue" : "Game";
|
||||
}
|
||||
|
||||
// ---- Export builders (each leaves exactly what its comment says) -------------
|
||||
|
||||
namespace Lua = Game::Lua;
|
||||
|
||||
// Sets `Documentation = { line1 [, line2 [, line3]] }` on the table at
|
||||
// stack[-1]; no-op when every line is null.
|
||||
void SetDocumentation(void *L, const char *l1, const char *l2 = nullptr,
|
||||
const char *l3 = nullptr) {
|
||||
if (l1 == nullptr && l2 == nullptr && l3 == nullptr)
|
||||
return;
|
||||
Lua::PushString(L, "Documentation");
|
||||
Lua::NewTable(L);
|
||||
int n = 0;
|
||||
for (const char *line : {l1, l2, l3}) {
|
||||
if (line == nullptr)
|
||||
continue;
|
||||
Lua::PushNumber(L, static_cast<double>(++n));
|
||||
Lua::PushString(L, line);
|
||||
Lua::SetTable(L, -3);
|
||||
}
|
||||
Lua::SetTable(L, -3);
|
||||
}
|
||||
|
||||
// A Lua literal from a descriptor's `defaultValue`, pushed as the value it
|
||||
// denotes: `true`/`false` -> boolean, a quoted string -> string, else number.
|
||||
void PushDefault(void *L, const char *literal) {
|
||||
if (std::strcmp(literal, "true") == 0) {
|
||||
Lua::PushBool(L, true);
|
||||
} else if (std::strcmp(literal, "false") == 0) {
|
||||
Lua::PushBool(L, false);
|
||||
} else if (literal[0] == '"') {
|
||||
const size_t len = std::strlen(literal);
|
||||
Lua::PushLString(L, literal + 1, static_cast<unsigned>(len >= 2 ? len - 2 : 0));
|
||||
} else {
|
||||
Lua::PushNumber(L, std::strtod(literal, nullptr));
|
||||
}
|
||||
}
|
||||
|
||||
// Pushes one field record: { Name, Type, Nilable [, Default] [, Documentation] }.
|
||||
void PushField(void *L, const Field &f) {
|
||||
Lua::NewTable(L);
|
||||
Lua::SetFieldString(L, "Name", f.name);
|
||||
Lua::SetFieldString(L, "Type", f.type);
|
||||
Lua::SetFieldBool(L, "Nilable", f.nilable);
|
||||
if (f.defaultValue != nullptr) {
|
||||
Lua::PushString(L, "Default");
|
||||
PushDefault(L, f.defaultValue);
|
||||
Lua::SetTable(L, -3);
|
||||
}
|
||||
SetDocumentation(L, f.doc);
|
||||
}
|
||||
|
||||
// Sets `stack[-1][key] = { field records }`; no-op for an empty list.
|
||||
void SetFieldArray(void *L, const char *key, FieldList list) {
|
||||
if (list.count <= 0)
|
||||
return;
|
||||
Lua::PushString(L, key);
|
||||
Lua::NewTable(L);
|
||||
for (int i = 0; i < list.count; ++i) {
|
||||
Lua::PushNumber(L, static_cast<double>(i + 1));
|
||||
PushField(L, list.data[i]);
|
||||
Lua::SetTable(L, -3);
|
||||
}
|
||||
Lua::SetTable(L, -3);
|
||||
}
|
||||
|
||||
constexpr const char *kExtensionNote = "ClassicAPI extension - not part of the Blizzard API.";
|
||||
constexpr const char *kGlueOnlyNote = "Available only on the glue screen.";
|
||||
constexpr const char *kGameOnlyNote = "Available only in-game.";
|
||||
// An undocumented function lists with no arguments, which is indistinguishable
|
||||
// from a function that genuinely takes none. Say which it is, so an empty
|
||||
// signature is never read as a real one.
|
||||
constexpr const char *kUndocumentedNote =
|
||||
"Not documented yet. Its arguments and return values are not listed here.";
|
||||
|
||||
// Pushes one function record. An undocumented entry still lists by name so
|
||||
// `/classicapi <System> list` shows the whole surface; its shape arrives with
|
||||
// the descriptor.
|
||||
void PushFunction(void *L, const Entry &e, unsigned systemEnv) {
|
||||
Lua::NewTable(L);
|
||||
Lua::SetFieldString(L, "Name", e.name);
|
||||
Lua::SetFieldString(L, "Type", "Function");
|
||||
const char *envNote = nullptr;
|
||||
if (e.env != systemEnv && e.env != 0)
|
||||
envNote = (e.env == ENV_GLUE) ? kGlueOnlyNote : kGameOnlyNote;
|
||||
if (e.doc == nullptr) {
|
||||
SetDocumentation(L, kUndocumentedNote, envNote);
|
||||
return;
|
||||
}
|
||||
SetDocumentation(L, e.doc->summary, e.doc->extension ? kExtensionNote : nullptr, envNote);
|
||||
SetFieldArray(L, "Arguments", e.doc->args);
|
||||
SetFieldArray(L, "Returns", e.doc->rets);
|
||||
}
|
||||
|
||||
// Pushes { Name, Type = "Enumeration", NumValues, MinValue, MaxValue,
|
||||
// Fields = { { Name, Type = <enum>, EnumValue } } }.
|
||||
void PushEnumeration(void *L, const Entry &e) {
|
||||
int minValue = 0, maxValue = 0;
|
||||
for (int i = 0; i < e.enumCount; ++i) {
|
||||
const int v = e.enumEntries[i].value;
|
||||
if (i == 0 || v < minValue)
|
||||
minValue = v;
|
||||
if (i == 0 || v > maxValue)
|
||||
maxValue = v;
|
||||
}
|
||||
Lua::NewTable(L);
|
||||
Lua::SetFieldString(L, "Name", e.name);
|
||||
Lua::SetFieldString(L, "Type", "Enumeration");
|
||||
Lua::SetFieldNumber(L, "NumValues", e.enumCount);
|
||||
Lua::SetFieldNumber(L, "MinValue", minValue);
|
||||
Lua::SetFieldNumber(L, "MaxValue", maxValue);
|
||||
Lua::PushString(L, "Fields");
|
||||
Lua::NewTable(L);
|
||||
for (int i = 0; i < e.enumCount; ++i) {
|
||||
Lua::PushNumber(L, static_cast<double>(i + 1));
|
||||
Lua::NewTable(L);
|
||||
Lua::SetFieldString(L, "Name", e.enumEntries[i].key);
|
||||
Lua::SetFieldString(L, "Type", e.name);
|
||||
Lua::SetFieldNumber(L, "EnumValue", e.enumEntries[i].value);
|
||||
Lua::SetTable(L, -3);
|
||||
}
|
||||
Lua::SetTable(L, -3);
|
||||
}
|
||||
|
||||
// Pushes { Name, Type = "Structure" [, Documentation], Fields = { … } }.
|
||||
void PushStructure(void *L, const Structure &s) {
|
||||
Lua::NewTable(L);
|
||||
Lua::SetFieldString(L, "Name", s.name);
|
||||
Lua::SetFieldString(L, "Type", "Structure");
|
||||
SetDocumentation(L, s.summary);
|
||||
SetFieldArray(L, "Fields", s.fields);
|
||||
}
|
||||
|
||||
// "LOSS_OF_CONTROL_ADDED" -> "LossOfControlAdded" (Blizzard's event Name).
|
||||
void PascalCase(const char *literal, char *out, size_t cap) {
|
||||
size_t o = 0;
|
||||
bool upper = true;
|
||||
for (const char *p = literal; *p != '\0' && o + 1 < cap; ++p) {
|
||||
if (*p == '_') {
|
||||
upper = true;
|
||||
continue;
|
||||
}
|
||||
const unsigned char c = static_cast<unsigned char>(*p);
|
||||
out[o++] = static_cast<char>(upper ? std::toupper(c) : std::tolower(c));
|
||||
upper = false;
|
||||
}
|
||||
out[o] = '\0';
|
||||
}
|
||||
|
||||
// Pushes { Name, Type = "Event", LiteralName [, Documentation] [, Payload] }.
|
||||
void PushEvent(void *L, const char *literal, const EventDoc &doc) {
|
||||
char name[128];
|
||||
PascalCase(literal, name, sizeof name);
|
||||
Lua::NewTable(L);
|
||||
Lua::SetFieldString(L, "Name", name);
|
||||
Lua::SetFieldString(L, "Type", "Event");
|
||||
Lua::SetFieldString(L, "LiteralName", literal);
|
||||
SetDocumentation(L, doc.summary);
|
||||
SetFieldArray(L, "Payload", doc.payload);
|
||||
}
|
||||
|
||||
// Pushes the whole System table for `sys`.
|
||||
void PushSystem(void *L, const SystemInfo &sys) {
|
||||
Lua::NewTable(L);
|
||||
Lua::SetFieldString(L, "Name", sys.name);
|
||||
Lua::SetFieldString(L, "Type", sys.type);
|
||||
if (sys.ns != nullptr)
|
||||
Lua::SetFieldString(L, "Namespace", sys.ns);
|
||||
Lua::SetFieldString(L, "Environment", EnvironmentName(sys.env));
|
||||
|
||||
Lua::PushString(L, "Functions");
|
||||
Lua::NewTable(L);
|
||||
int n = 0;
|
||||
for (const Entry &e : g_entries) {
|
||||
if (e.kind != KIND_GLOBAL && e.kind != KIND_TABLE && e.kind != KIND_FRAME_METHOD)
|
||||
continue;
|
||||
if (!SameTextNoCase(SystemOf(e), sys.name) || IsDebugName(e.name))
|
||||
continue;
|
||||
Lua::PushNumber(L, static_cast<double>(++n));
|
||||
PushFunction(L, e, sys.env);
|
||||
Lua::SetTable(L, -3);
|
||||
}
|
||||
Lua::SetTable(L, -3);
|
||||
|
||||
Lua::PushString(L, "Events");
|
||||
Lua::NewTable(L);
|
||||
n = 0;
|
||||
const int events = Event::Custom::ReservedCount();
|
||||
for (int i = 0; i < events; ++i) {
|
||||
const EventDoc *doc = Event::Custom::ReservedDoc(i);
|
||||
if (doc == nullptr || !SameTextNoCase(doc->system, sys.name))
|
||||
continue;
|
||||
Lua::PushNumber(L, static_cast<double>(++n));
|
||||
PushEvent(L, Event::Custom::ReservedName(i), *doc);
|
||||
Lua::SetTable(L, -3);
|
||||
}
|
||||
Lua::SetTable(L, -3);
|
||||
|
||||
Lua::PushString(L, "Tables");
|
||||
Lua::NewTable(L);
|
||||
n = 0;
|
||||
for (const Structure *s = g_structureHead; s != nullptr; s = s->next) {
|
||||
if (!SameTextNoCase(s->system, sys.name))
|
||||
continue;
|
||||
Lua::PushNumber(L, static_cast<double>(++n));
|
||||
PushStructure(L, *s);
|
||||
Lua::SetTable(L, -3);
|
||||
}
|
||||
for (const Entry &e : g_entries) {
|
||||
if (e.kind != KIND_ENUM || !SameTextNoCase(e.enumSystem, sys.name))
|
||||
continue;
|
||||
Lua::PushNumber(L, static_cast<double>(++n));
|
||||
PushEnumeration(L, e);
|
||||
Lua::SetTable(L, -3);
|
||||
}
|
||||
Lua::SetTable(L, -3);
|
||||
}
|
||||
|
||||
// ---- Coverage ---------------------------------------------------------------
|
||||
|
||||
std::vector<std::string> Undocumented() {
|
||||
std::vector<std::string> out;
|
||||
const std::vector<SystemInfo> systems = CollectSystems();
|
||||
for (const Entry &e : g_entries) {
|
||||
if (IsDebugName(e.name))
|
||||
continue;
|
||||
switch (e.kind) {
|
||||
case KIND_GLOBAL:
|
||||
if (e.doc == nullptr) {
|
||||
out.push_back(e.name);
|
||||
} else if (e.doc->system == nullptr) {
|
||||
out.push_back(std::string(e.name) + " (doc has no system)");
|
||||
} else if (const SystemInfo *s = FindSystem(systems, e.doc->system);
|
||||
s != nullptr && s->ns != nullptr) {
|
||||
out.push_back(std::string(e.name) + " (system '" + e.doc->system +
|
||||
"' is namespaced)");
|
||||
}
|
||||
break;
|
||||
case KIND_TABLE:
|
||||
if (e.doc == nullptr)
|
||||
out.push_back(std::string(e.table) + "." + e.name);
|
||||
break;
|
||||
case KIND_FRAME_METHOD: {
|
||||
const char *sys = WidgetSystemFor(e.registry);
|
||||
if (sys == nullptr)
|
||||
out.push_back(std::string(e.name) + " (method registry not mapped)");
|
||||
else if (e.doc == nullptr)
|
||||
out.push_back(std::string(sys) + ":" + e.name);
|
||||
break;
|
||||
}
|
||||
case KIND_ORPHAN_METHOD_DOC: {
|
||||
const char *sys = WidgetSystemFor(e.registry);
|
||||
out.push_back(std::string(sys != nullptr ? sys : "?") + ":" + e.name +
|
||||
" (doc for unregistered method)");
|
||||
break;
|
||||
}
|
||||
case KIND_ENUM:
|
||||
if (e.enumSystem == nullptr)
|
||||
out.push_back(std::string(e.table) + "." + e.name);
|
||||
break;
|
||||
}
|
||||
}
|
||||
const int events = Event::Custom::ReservedCount();
|
||||
for (int i = 0; i < events; ++i)
|
||||
if (Event::Custom::ReservedDoc(i) == nullptr)
|
||||
out.push_back(std::string("event ") + Event::Custom::ReservedName(i));
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---- Lua surface ------------------------------------------------------------
|
||||
|
||||
int __fastcall Script_GetSystems(void *L) {
|
||||
std::vector<SystemInfo> systems = CollectSystems();
|
||||
std::sort(systems.begin(), systems.end(), [](const SystemInfo &a, const SystemInfo &b) {
|
||||
return _stricmp(a.name, b.name) < 0;
|
||||
});
|
||||
Lua::NewTable(L);
|
||||
for (size_t i = 0; i < systems.size(); ++i) {
|
||||
Lua::PushNumber(L, static_cast<double>(i + 1));
|
||||
Lua::PushString(L, systems[i].name);
|
||||
Lua::SetTable(L, -3);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
int __fastcall Script_GetSystem(void *L) {
|
||||
if (!Lua::IsString(L, 1)) {
|
||||
Lua::Error(L, "Usage: C_APIDocumentation.GetSystem(name)");
|
||||
return 0;
|
||||
}
|
||||
const char *query = Lua::ToString(L, 1);
|
||||
const std::vector<SystemInfo> systems = CollectSystems();
|
||||
const SystemInfo *sys = FindSystem(systems, query);
|
||||
if (sys == nullptr)
|
||||
return 0; // nil
|
||||
Lua::CheckStack(L, 32);
|
||||
PushSystem(L, *sys);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int __fastcall Script_UndocumentedAPI(void *L) {
|
||||
const std::vector<std::string> names = Undocumented();
|
||||
Lua::NewTable(L);
|
||||
for (size_t i = 0; i < names.size(); ++i) {
|
||||
Lua::PushNumber(L, static_cast<double>(i + 1));
|
||||
Lua::PushString(L, names[i].c_str());
|
||||
Lua::SetTable(L, -3);
|
||||
}
|
||||
Lua::PushNumber(L, static_cast<double>(names.size()));
|
||||
return 2;
|
||||
}
|
||||
|
||||
const Field kGetSystemsRets[] = {
|
||||
Game::Doc::Req("systems", "table", "Array of system Names, sorted without regard to case."),
|
||||
};
|
||||
const Function kGetSystems{
|
||||
"Returns the name of every documented system.",
|
||||
{}, kGetSystemsRets, nullptr, true};
|
||||
|
||||
const Field kGetSystemArgs[] = {
|
||||
Game::Doc::Req("system", "string", "A system Name or Namespace; case does not matter."),
|
||||
};
|
||||
const Field kGetSystemRets[] = {
|
||||
Game::Doc::Opt("system", "table", nullptr,
|
||||
"The system in Blizzard's APIDocumentation table shape, or nil when unknown."),
|
||||
};
|
||||
const Function kGetSystem{
|
||||
"Returns one system's documentation table.",
|
||||
kGetSystemArgs, kGetSystemRets, nullptr, true};
|
||||
|
||||
void RegisterLuaFunctions() {
|
||||
Game::Lua::RegisterTableFunction("C_APIDocumentation", "GetSystems", &Script_GetSystems,
|
||||
&kGetSystems);
|
||||
Game::Lua::RegisterTableFunction("C_APIDocumentation", "GetSystem", &Script_GetSystem,
|
||||
&kGetSystem);
|
||||
Game::Lua::RegisterGlobalFunction("_classicapi_UndocumentedAPI", &Script_UndocumentedAPI);
|
||||
}
|
||||
|
||||
const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
|
||||
|
||||
} // namespace
|
||||
|
||||
// ---- Recording (called from Game.cpp) ----------------------------------------
|
||||
|
||||
void BeginPass(Env env) {
|
||||
g_pass = (g_sealed & env) != 0 ? ENV_NONE : env;
|
||||
g_recordedThisPass = 0;
|
||||
}
|
||||
|
||||
void EndPass() {
|
||||
if (g_pass == ENV_NONE)
|
||||
return;
|
||||
g_sealed |= g_pass;
|
||||
const Env done = g_pass;
|
||||
g_pass = ENV_NONE;
|
||||
const std::vector<std::string> missing = Undocumented();
|
||||
Debug::Log::Printf("[doc] %s pass: %d registrations recorded, %d undocumented",
|
||||
done == ENV_GLUE ? "glue" : "game", g_recordedThisPass,
|
||||
static_cast<int>(missing.size()));
|
||||
}
|
||||
|
||||
void RecordGlobal(const char *name, const Function *doc) {
|
||||
Record(KIND_GLOBAL, nullptr, name, nullptr, doc);
|
||||
}
|
||||
|
||||
void RecordTable(const char *table, const char *name, const Function *doc) {
|
||||
Record(KIND_TABLE, table, name, nullptr, doc);
|
||||
}
|
||||
|
||||
void RecordFrameMethods(const void *registry, const Game::Lua::FrameMethodEntry *table,
|
||||
int count, const Method *docs, int docCount) {
|
||||
if (g_pass == ENV_NONE)
|
||||
return;
|
||||
for (int i = 0; i < count; ++i) {
|
||||
const Function *doc = nullptr;
|
||||
for (int d = 0; d < docCount; ++d) {
|
||||
if (std::strcmp(docs[d].name, table[i].name) == 0) {
|
||||
doc = docs[d].doc;
|
||||
break;
|
||||
}
|
||||
}
|
||||
Record(KIND_FRAME_METHOD, nullptr, table[i].name, registry, doc);
|
||||
}
|
||||
for (int d = 0; d < docCount; ++d) {
|
||||
bool matched = false;
|
||||
for (int i = 0; i < count && !matched; ++i)
|
||||
matched = std::strcmp(docs[d].name, table[i].name) == 0;
|
||||
if (!matched)
|
||||
Record(KIND_ORPHAN_METHOD_DOC, nullptr, docs[d].name, registry, docs[d].doc);
|
||||
}
|
||||
}
|
||||
|
||||
void NameWidgetSystem(const void *registry, const char *system) {
|
||||
if (WidgetSystemFor(registry) != nullptr)
|
||||
return;
|
||||
g_ownWidgetSystems.push_back({reinterpret_cast<uintptr_t>(registry), system});
|
||||
}
|
||||
|
||||
void RecordEnum(const char *parent, const char *sub, const Game::Lua::EnumIntegerEntry *entries,
|
||||
int count, const char *system) {
|
||||
if (g_pass == ENV_NONE || sub == nullptr)
|
||||
return;
|
||||
++g_recordedThisPass;
|
||||
if (Entry *e = Find(KIND_ENUM, parent, sub, nullptr)) {
|
||||
e->env |= g_pass;
|
||||
if (e->enumSystem == nullptr)
|
||||
e->enumSystem = system;
|
||||
return;
|
||||
}
|
||||
Entry e{};
|
||||
e.kind = KIND_ENUM;
|
||||
e.env = g_pass;
|
||||
e.table = parent;
|
||||
e.name = sub;
|
||||
e.enumSystem = system;
|
||||
e.enumEntries = entries;
|
||||
e.enumCount = count;
|
||||
g_entries.push_back(e);
|
||||
}
|
||||
|
||||
} // namespace Api::Documentation
|
||||
|
||||
// The Structure constructor lives here so the list head is private to this
|
||||
// TU; declared in Game.h beside the other descriptor types.
|
||||
Game::Doc::Structure::Structure(const char *n, const char *s, FieldList f, const char *sum)
|
||||
: name(n), system(s), fields(f), summary(sum), next(Api::Documentation::g_structureHead) {
|
||||
Api::Documentation::g_structureHead = this;
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// This file is part of ClassicAPI.
|
||||
//
|
||||
// ClassicAPI is free software: you can redistribute it and/or modify it under the terms
|
||||
// of the GNU 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 General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License along with
|
||||
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "Game.h"
|
||||
|
||||
// Recording side of the API documentation. The registrars in Game.cpp call
|
||||
// these; `Documentation.cpp` keeps the list, resolves systems, and exports
|
||||
// Blizzard-shaped `APIDocumentation` tables through `C_APIDocumentation`.
|
||||
// The descriptor model is the `Game::Doc` block in Game.h.
|
||||
namespace Api::Documentation {
|
||||
|
||||
enum Env : unsigned { ENV_NONE = 0, ENV_GAME = 1, ENV_GLUE = 2 };
|
||||
|
||||
// Bracket one `Run*Registrations()` pass. Recording happens only inside a
|
||||
// pass, and only the FIRST pass per environment records — every later pass
|
||||
// (each `/reload`, each logout→login) is a no-op. `EndPass` seals the
|
||||
// environment and logs one summary line to the debug log.
|
||||
void BeginPass(Env env);
|
||||
void EndPass();
|
||||
|
||||
void RecordGlobal(const char *name, const Game::Doc::Function *doc);
|
||||
void RecordTable(const char *table, const char *name, const Game::Doc::Function *doc);
|
||||
void RecordFrameMethods(const void *registry, const Game::Lua::FrameMethodEntry *table,
|
||||
int count, const Game::Doc::Method *docs, int docCount);
|
||||
// Names the widget system of a method hash this DLL owns (a frame class it
|
||||
// adds), alongside the engine registries the exporter already knows.
|
||||
void NameWidgetSystem(const void *registry, const char *system);
|
||||
void RecordEnum(const char *parent, const char *sub, const Game::Lua::EnumIntegerEntry *entries,
|
||||
int count, const char *system);
|
||||
|
||||
} // namespace Api::Documentation
|
||||
+32
-17
@@ -19,19 +19,22 @@
|
||||
//
|
||||
// Filter parsing (`ParseFilters`) tokenizes the modern AuraFilters string:
|
||||
// tokens separated by `|` and/or whitespace, each optionally negated with a
|
||||
// leading `!`. Whole-token matching, so `RAID_PLAYER_DISPELLABLE` is not
|
||||
// mistaken for `PLAYER` and `!PLAYER` is a negation rather than a match.
|
||||
// leading `!`, compared ignoring case as 4.3.4's parser does. Whole-token
|
||||
// matching, so `RAID_PLAYER_DISPELLABLE` is not mistaken for `PLAYER` and
|
||||
// `!PLAYER` is a negation rather than a match.
|
||||
// Honored: `HELPFUL` / `HARMFUL` (the aura's real polarity, read however this
|
||||
// server encodes it — see `Aura::Data::IsSlotHarmful`), `PLAYER` /
|
||||
// `!PLAYER` (caster == / != the local player, from the Aura::Source cache),
|
||||
// `!PLAYER` (caster is / isn't the local player or a unit they own, from the
|
||||
// Aura::Source cache), `RAID` (the engine's raid filter — see
|
||||
// `Aura::Data::IsRaidAura`), `CANCELABLE` / `NOT_CANCELABLE` (the descriptor's
|
||||
// cancelable bit),
|
||||
// `DISPELLABLE` / `!DISPELLABLE` (dispel type is / isn't one a
|
||||
// dispel/purge/steal can remove — Spell.dbc Dispel ∈ Magic/Curse/Disease/
|
||||
// Poison, matching the server's DISPEL_ALL_MASK), and `CROWD_CONTROL` /
|
||||
// `!CROWD_CONTROL` (is / isn't a hard control effect, via the shared
|
||||
// `Spell::CrowdControl` classifier that also backs C_LossOfControl). Every
|
||||
// other modern token (`RAID`, `CANCELABLE`, `INCLUDE_NAME_PLATE_ONLY`, `MAW`,
|
||||
// …) is accepted and ignored — they need a class-dispel matrix or systems
|
||||
// vanilla has no data for.
|
||||
// other modern token (`INCLUDE_NAME_PLATE_ONLY`, `MAW`, …) is accepted and
|
||||
// ignored — vanilla has no data for them.
|
||||
|
||||
#include "Data.h"
|
||||
|
||||
@@ -74,8 +77,10 @@ struct ParsedFilter {
|
||||
Data::CasterMode caster = Data::CasterMode::Any;
|
||||
Data::DispelMode dispel = Data::DispelMode::Any;
|
||||
Data::CcMode cc = Data::CcMode::Any;
|
||||
Data::CancelMode cancel = Data::CancelMode::Any;
|
||||
bool raid = false;
|
||||
|
||||
Data::Match ToMatch() const { return Data::Match{caster, dispel, cc}; }
|
||||
Data::Match ToMatch() const { return Data::Match{caster, dispel, cc, cancel, raid}; }
|
||||
};
|
||||
|
||||
// Reduces the parsed range tokens to the single `Data::Filter` the indexed /
|
||||
@@ -87,8 +92,8 @@ Data::Filter RangeFilter(const ParsedFilter &pf) {
|
||||
: Data::Filter::Helpful;
|
||||
}
|
||||
|
||||
// Tokenizes the filter string. Case-sensitive (modern documents the tokens as
|
||||
// upper-case constants). `HELPFUL`/`HARMFUL` are positive range selectors;
|
||||
// Tokenizes the filter string, ignoring case (4.3.4's Script_GetAuraInfo
|
||||
// compares tokens with SStrCmpI). `HELPFUL`/`HARMFUL` are positive range selectors;
|
||||
// negating them is meaningless for our slot-based ranges, so a leading `!` is
|
||||
// ignored on those. `PLAYER` honors negation (`!PLAYER` → NotPlayer). Any
|
||||
// unrecognized token is accepted and skipped.
|
||||
@@ -115,17 +120,25 @@ ParsedFilter ParseFilters(const char *filter) {
|
||||
}
|
||||
tok[n] = '\0';
|
||||
|
||||
if (strcmp(tok, "HELPFUL") == 0)
|
||||
if (_stricmp(tok, "HELPFUL") == 0)
|
||||
out.helpful = true;
|
||||
else if (strcmp(tok, "HARMFUL") == 0)
|
||||
else if (_stricmp(tok, "HARMFUL") == 0)
|
||||
out.harmful = true;
|
||||
else if (strcmp(tok, "PLAYER") == 0)
|
||||
else if (_stricmp(tok, "PLAYER") == 0)
|
||||
out.caster = negate ? Data::CasterMode::NotPlayer
|
||||
: Data::CasterMode::PlayerOnly;
|
||||
else if (strcmp(tok, "DISPELLABLE") == 0)
|
||||
else if (_stricmp(tok, "RAID") == 0)
|
||||
out.raid = !negate;
|
||||
else if (_stricmp(tok, "CANCELABLE") == 0)
|
||||
out.cancel = negate ? Data::CancelMode::NotCancelable
|
||||
: Data::CancelMode::CancelableOnly;
|
||||
else if (_stricmp(tok, "NOT_CANCELABLE") == 0)
|
||||
out.cancel = negate ? Data::CancelMode::CancelableOnly
|
||||
: Data::CancelMode::NotCancelable;
|
||||
else if (_stricmp(tok, "DISPELLABLE") == 0)
|
||||
out.dispel = negate ? Data::DispelMode::NotDispellable
|
||||
: Data::DispelMode::DispellableOnly;
|
||||
else if (strcmp(tok, "CROWD_CONTROL") == 0)
|
||||
else if (_stricmp(tok, "CROWD_CONTROL") == 0)
|
||||
out.cc = negate ? Data::CcMode::NotCrowdControl
|
||||
: Data::CcMode::CrowdControlOnly;
|
||||
// else: accepted and ignored (retail-only / unimplemented token).
|
||||
@@ -473,14 +486,16 @@ int __fastcall Script_UnitAuraBySlot(void *L) {
|
||||
return PushAuraBySlot(L, Data::Emit::Positional);
|
||||
}
|
||||
|
||||
// Iterates the auras of one polarity (in `SlotInFilterOrder`, the same order
|
||||
// the by-index getters use) and pushes AuraData tables into `outer` at
|
||||
// Iterates the auras of one polarity (in `WalkOrder`, the same order the
|
||||
// by-index getters use) and pushes AuraData tables into `outer` at
|
||||
// sequential keys starting from `nextKey`. Updates `nextKey` so a follow-up
|
||||
// call can append to the same outer table.
|
||||
void AppendRangeToArray(void *L, const uint8_t *unit, int outerIdx,
|
||||
Data::Filter filter, int &nextKey, Data::Match match) {
|
||||
int order[Offsets::UNIT_AURA_TOTAL];
|
||||
Data::WalkOrder(unit, filter, order);
|
||||
for (int i = 0; i < Offsets::UNIT_AURA_TOTAL; ++i) {
|
||||
const int slot = Data::SlotInFilterOrder(filter, i);
|
||||
const int slot = order[i];
|
||||
if (!Data::SlotMatchesFilter(unit, slot, filter, match))
|
||||
continue;
|
||||
Game::Lua::PushNumber(L, static_cast<double>(nextKey++));
|
||||
|
||||
@@ -227,8 +227,10 @@ uint32_t TryComboScaledMs(const uint8_t *spellRecord, uint32_t spellId) {
|
||||
Offsets::VAR_SPELL_DURATION_COUNT,
|
||||
static_cast<uint32_t>(idx));
|
||||
if (row != nullptr) {
|
||||
baseMs = *reinterpret_cast<const int32_t *>(row + 0x4);
|
||||
maxMs = *reinterpret_cast<const int32_t *>(row + 0xC);
|
||||
baseMs = *reinterpret_cast<const int32_t *>(
|
||||
row + Offsets::OFF_SPELLDURATION_BASE_MS);
|
||||
maxMs = *reinterpret_cast<const int32_t *>(
|
||||
row + Offsets::OFF_SPELLDURATION_MAX_MS);
|
||||
} else if (idx != 0) {
|
||||
// Dangling duration index — the client data is broken for this
|
||||
// spell. Defer to a registered resolver (the known values are
|
||||
|
||||
+472
-170
@@ -19,8 +19,10 @@
|
||||
#include "dbc/Lookup.h"
|
||||
#include "group/MemberStats.h"
|
||||
#include "guid/Guid.h"
|
||||
#include "object/Resolve.h"
|
||||
#include "spell/CrowdControl.h"
|
||||
#include "spell/IsSelfBuff.h"
|
||||
#include "tick/WorldTick.h"
|
||||
#include "time/Clock.h"
|
||||
#include "turtle/Detect.h"
|
||||
#include "unit/Identity.h"
|
||||
@@ -65,6 +67,18 @@ const char *LocalizedSpellName(const uint8_t *spellRecord) {
|
||||
return (s == nullptr || *s == '\0') ? nullptr : s;
|
||||
}
|
||||
|
||||
// True when the spell's locale-resolved name equals `query`, ignoring case:
|
||||
// Storm's SStrCmpI, the compare 4.3.4's GetSortedAuraSlot makes for UnitAura's
|
||||
// name form. `int __stdcall(a, b, n)` — see `FUN_SSTR_CMP_I`.
|
||||
bool SpellNameMatches(const uint8_t *spellRecord, const char *query) {
|
||||
const char *name = LocalizedSpellName(spellRecord);
|
||||
if (name == nullptr || query == nullptr)
|
||||
return false;
|
||||
using SStrCmpI_t = int(__stdcall *)(const char *, const char *, int);
|
||||
auto cmp = reinterpret_cast<SStrCmpI_t>(static_cast<uintptr_t>(Offsets::FUN_SSTR_CMP_I));
|
||||
return cmp(name, query, 0x7FFFFFFF) == 0;
|
||||
}
|
||||
|
||||
const char *SpellIconPath(const uint8_t *spellRecord) {
|
||||
if (spellRecord == nullptr)
|
||||
return nullptr;
|
||||
@@ -83,35 +97,35 @@ const uint8_t *LocalPlayer() {
|
||||
return static_cast<const uint8_t *>(Game::ResolveUnitToken("player"));
|
||||
}
|
||||
|
||||
// Looks up the player-buff-table entry for a given spellID. The table
|
||||
// at `VAR_PLAYER_BUFF_TABLE` mirrors the local player's auras with
|
||||
// timing data (which UNIT_FIELD_AURA lacks for all units). Returns
|
||||
// nullptr when the spell isn't in any populated entry.
|
||||
//
|
||||
// Only meaningful when the caller is building data for the local
|
||||
// player — every entry here belongs to "player". Caller is expected
|
||||
// to gate on that.
|
||||
const uint8_t *FindPlayerBuffEntry(uint32_t spellID) {
|
||||
// The player-buff-table record the engine built for absolute aura `slot`,
|
||||
// or nullptr. The table at `VAR_PLAYER_BUFF_TABLE` mirrors the local
|
||||
// player's auras (packed in insertion order, each record naming its slot);
|
||||
// looking up by slot rather than spell ID keeps two copies of one spell
|
||||
// apart. Only meaningful for the local player — caller gates on that.
|
||||
const uint8_t *FindPlayerBuffRecord(int slot) {
|
||||
auto *base = reinterpret_cast<const uint8_t *>(
|
||||
static_cast<uintptr_t>(Offsets::VAR_PLAYER_BUFF_TABLE));
|
||||
for (int i = 0; i < Offsets::PLAYER_BUFF_TABLE_COUNT; ++i) {
|
||||
const uint8_t *entry = base + i * Offsets::PLAYER_BUFF_ENTRY_STRIDE;
|
||||
const int slotCode = *reinterpret_cast<const int *>(
|
||||
entry + Offsets::OFF_PLAYER_BUFF_SLOT_CODE);
|
||||
if (slotCode < 0)
|
||||
continue;
|
||||
const uint32_t entrySpell = *reinterpret_cast<const uint32_t *>(
|
||||
entry + Offsets::OFF_PLAYER_BUFF_SPELL_ID);
|
||||
if (entrySpell == spellID)
|
||||
return entry;
|
||||
const uint8_t *record = base + i * Offsets::PLAYER_BUFF_ENTRY_STRIDE;
|
||||
if (Game::Read<int>(record, Offsets::OFF_PLAYER_BUFF_SLOT_CODE) == slot)
|
||||
return record;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// True when the engine marked the record's aura as lasting until cancelled
|
||||
// (`FUN_004E44B0`'s flag at +0x0C). `GameTooltip:SetPlayerBuff` shows no
|
||||
// time left for such an aura, and neither do we: the expiration table keeps
|
||||
// a slot's previous expiry after its aura ends, so a permanent aura that
|
||||
// takes over the slot would otherwise read the old aura's time.
|
||||
bool PlayerBuffUntilCancelled(const uint8_t *record) {
|
||||
return Game::Read<int>(record, Offsets::OFF_PLAYER_BUFF_UNTIL_CANCELLED) != 0;
|
||||
}
|
||||
|
||||
// Reads the absolute expiration timestamp (in seconds, GetTime-epoch)
|
||||
// for a player-buff entry, or 0 if the entry has expired / has no
|
||||
// timing. The engine stores ms-since-tickcount-epoch which matches
|
||||
// what Lua's `GetTime()` returns (engineMs * 0.001), so converting
|
||||
// for a player-buff record, or 0 if it has expired / has no timing. The
|
||||
// engine stores ms-since-tickcount-epoch which matches what Lua's
|
||||
// `GetTime()` returns (engineMs * 0.001), so converting
|
||||
// `expirationMs * 0.001` lands directly on the same timeline addons
|
||||
// compare against on the Lua side. No epoch reconciliation needed.
|
||||
//
|
||||
@@ -121,85 +135,59 @@ const uint8_t *FindPlayerBuffEntry(uint32_t spellID) {
|
||||
// only the "no timing" (0) sentinel. The engine's own arithmetic
|
||||
// works on the unsigned tick because both sides of `expiration -
|
||||
// currentMs` wrap together.
|
||||
double PlayerBuffExpirationSeconds(const uint8_t *entry) {
|
||||
if (entry == nullptr)
|
||||
double PlayerBuffExpirationSeconds(const uint8_t *record) {
|
||||
if (record == nullptr || PlayerBuffUntilCancelled(record))
|
||||
return 0.0;
|
||||
const int slotCode = *reinterpret_cast<const int *>(
|
||||
entry + Offsets::OFF_PLAYER_BUFF_SLOT_CODE);
|
||||
if (slotCode < 0)
|
||||
const int slotCode = Game::Read<int>(record, Offsets::OFF_PLAYER_BUFF_SLOT_CODE);
|
||||
if (slotCode < 0 || slotCode >= Offsets::UNIT_AURA_TOTAL)
|
||||
return 0.0;
|
||||
auto *expirationTable = reinterpret_cast<const uint32_t *>(
|
||||
static_cast<uintptr_t>(Offsets::VAR_PLAYER_BUFF_EXPIRATION_TABLE));
|
||||
const uint32_t expirationMs = expirationTable[slotCode];
|
||||
if (expirationMs == 0)
|
||||
return 0.0;
|
||||
// Report "no timer" once the stored expiration has elapsed — this is not a
|
||||
// heuristic, it's exactly what the engine's own GetPlayerBuffTimeLeft does.
|
||||
// Script_GetPlayerBuffTimeLeft (0x004e4930) → FUN_004e4450 reads this same
|
||||
// expiration table and returns:
|
||||
// if ((int)(now - expiration[slot]) >= 0) return 0; // elapsed -> 0
|
||||
// return expiration[slot] - now; // else remaining
|
||||
// Permanent auras (paladin auras, passives, racials) carry an infinite
|
||||
// Spell.dbc duration (SpellDuration base -1); the server stores the fixed
|
||||
// cast-time in this slot for them, so it's always "already elapsed" and the
|
||||
// engine shows no countdown. `Time::Clock::Reached` takes the signed diff, so
|
||||
// it also absorbs the ~24.86-day GetTickCount wrap (both operands wrap
|
||||
// together).
|
||||
// An elapsed expiry reads as "no timer", as the engine's own
|
||||
// GetPlayerBuffTimeLeft (0x004e4930 → FUN_004e4450) returns 0 once
|
||||
// `(int)(now - expiration[slot]) >= 0`. `Time::Clock::Reached` takes the
|
||||
// same signed diff, so it also absorbs the ~24.86-day GetTickCount wrap.
|
||||
if (Time::Clock::Reached(expirationMs))
|
||||
return 0.0; // expiration reached/passed → permanent or no timer
|
||||
return 0.0;
|
||||
return static_cast<double>(expirationMs) * 0.001;
|
||||
}
|
||||
|
||||
// Computes the spell's base duration in seconds via Spell.dbc →
|
||||
// SpellDuration.dbc lookup with level scaling. Returns 0 for spells
|
||||
// without a real duration (the sentinel `base < 0 && perLevel == 0`
|
||||
// path the engine uses for infinite auras like passives, paladin
|
||||
// auras, racials).
|
||||
// The spell's base duration in seconds, as the server computes it before
|
||||
// combo points and caster modifiers: the SpellDuration row's base, with
|
||||
// −1 meaning infinite (returned as 0) and any other negative taken as its
|
||||
// absolute value. Both vmangos and tortoise-wow (`SpellEntry::GetDuration`)
|
||||
// ignore the row's per-level term, so this does too — the client's own
|
||||
// helper (`FUN_GET_SPELL_DURATION`) scales by the PLAYER's level and would
|
||||
// disagree with the expiration the server actually applies. Mirrors the
|
||||
// engine's lookup bounds (`0x006EA000`): an index outside the store or an
|
||||
// empty row gives 0.
|
||||
//
|
||||
// Doesn't include talent / glyph / aura-extension modifiers — those
|
||||
// are caster-side and the engine applies them when computing the
|
||||
// expiration timestamp. So `expirationTime - GetTime()` reflects the
|
||||
// *true* remaining time; this `duration` is the base value modern
|
||||
// addons use for "X / Y" timer rendering.
|
||||
double SpellBaseDurationSeconds(uint32_t spellID, int unitLevel) {
|
||||
// Caster-side modifiers are baked into the expiration, so
|
||||
// `expirationTime - GetTime()` stays the true remaining time even where
|
||||
// this base omits them.
|
||||
double SpellBaseDurationSeconds(uint32_t spellID) {
|
||||
const uint8_t *spell = SpellRecord(spellID);
|
||||
if (spell == nullptr)
|
||||
return 0.0;
|
||||
const int durIdx = *reinterpret_cast<const int *>(
|
||||
spell + Offsets::OFF_SPELL_DURATION_INDEX);
|
||||
if (durIdx <= 0)
|
||||
spell + Offsets::OFF_SPELL_RECORD_DURATION_INDEX);
|
||||
if (durIdx < 0)
|
||||
return 0.0;
|
||||
const uint8_t *durRec = DBC::Record(Offsets::VAR_SPELLDURATION_RECORDS,
|
||||
Offsets::VAR_SPELLDURATION_COUNT,
|
||||
const uint8_t *durRec = DBC::Record(Offsets::VAR_SPELL_DURATION_RECORDS,
|
||||
Offsets::VAR_SPELL_DURATION_COUNT,
|
||||
static_cast<uint32_t>(durIdx));
|
||||
if (durRec == nullptr)
|
||||
return 0.0;
|
||||
const int base = *reinterpret_cast<const int *>(
|
||||
durRec + Offsets::OFF_SPELLDURATION_BASE_MS);
|
||||
const int perLevel = *reinterpret_cast<const int *>(
|
||||
durRec + Offsets::OFF_SPELLDURATION_PER_LEVEL_MS);
|
||||
const int maxMs = *reinterpret_cast<const int *>(
|
||||
durRec + Offsets::OFF_SPELLDURATION_MAX_MS);
|
||||
// Engine's "infinite duration" sentinel — matches the check in
|
||||
// `FUN_004E44B0`'s "no real duration" branch at `0x004e455c`.
|
||||
if (base < 0 && perLevel < 1)
|
||||
if (base == -1)
|
||||
return 0.0;
|
||||
const int spellBaseLevel = *reinterpret_cast<const int *>(
|
||||
spell + Offsets::OFF_SPELL_BASE_LEVEL);
|
||||
int effLevel = unitLevel;
|
||||
if (effLevel < spellBaseLevel)
|
||||
effLevel = spellBaseLevel;
|
||||
int durationMs = (effLevel - spellBaseLevel) * perLevel + base;
|
||||
if (maxMs > 0 && durationMs > maxMs)
|
||||
durationMs = maxMs;
|
||||
if (durationMs <= 0)
|
||||
return 0.0;
|
||||
return static_cast<double>(durationMs) * 0.001;
|
||||
return static_cast<double>(base < 0 ? -base : base) * 0.001;
|
||||
}
|
||||
|
||||
// Reads the player's level from UNIT_FIELD_LEVEL. Returns 0 when
|
||||
// unresolved (pre-login, no descriptor) — caller should treat that
|
||||
// as "skip level scaling".
|
||||
// True if the engine-tick expiration `expMs` has already reached/passed now.
|
||||
// Same signed-wrap-safe compare `PlayerBuffExpirationSeconds` uses (absorbs
|
||||
// the ~24.86-day GetTickCount wrap). An already-elapsed cached expiration is
|
||||
@@ -207,14 +195,6 @@ double SpellBaseDurationSeconds(uint32_t spellID, int unitLevel) {
|
||||
// unknown rather than as a negative remaining.
|
||||
bool ExpirationElapsed(uint32_t expMs) { return Time::Clock::Reached(expMs); }
|
||||
|
||||
int PlayerLevel(const uint8_t *player) {
|
||||
auto *desc = Descriptor(player);
|
||||
if (desc == nullptr)
|
||||
return 0;
|
||||
return *reinterpret_cast<const int *>(
|
||||
desc + Offsets::OFF_UNIT_FIELD_LEVEL);
|
||||
}
|
||||
|
||||
// Caster + timing attributed to ONE aura instance — the aura `spellID` sitting
|
||||
// in absolute descriptor `slot` on `guid` (`Aura::Source::SLOT_UNBOUND` when
|
||||
// the caller has no slot: the out-of-range group array, the cache fallback).
|
||||
@@ -361,16 +341,66 @@ int SlotInFilterOrder(Filter filter, int i) {
|
||||
return i;
|
||||
}
|
||||
|
||||
// The caster set the `PLAYER` filter selects, 4.3.4's
|
||||
// `CGSpellBook::IsAuraCaster`: the player, or a unit whose charmer-or-creator
|
||||
// is the player — the pet, a guardian, a totem, a charmed creature. A minion's
|
||||
// cast carries the MINION's guid in the Aura::Source cache (that is who
|
||||
// SMSG_SPELL_GO names), so a plain player compare drops e.g. a Hunter's own
|
||||
// Serpent Sting or a Shaman's totem buff off a `PLAYER` query. The pet guid is
|
||||
// a live engine global and answers the common case without resolving an
|
||||
// object; any other caster is resolved and its owner read, as 4.3.4 does — an
|
||||
// owner unit out of sight reads as not the player. A caster of 0 is a cache
|
||||
// miss, never a match (see CasterMode).
|
||||
bool IsPlayerOwnedCaster(uint64_t casterGuid) {
|
||||
if (casterGuid == 0)
|
||||
return false;
|
||||
const uint64_t player = Unit::Identity::PlayerGuid();
|
||||
if (casterGuid == player)
|
||||
return true;
|
||||
const uint64_t pet =
|
||||
Game::Read<uint64_t>(static_cast<uintptr_t>(Offsets::VAR_PET_GUID));
|
||||
if (pet != 0 && casterGuid == pet)
|
||||
return true;
|
||||
if (Guid::IsPlayer(casterGuid))
|
||||
return false; // another player is never the local player's minion
|
||||
const void *caster = Object::ByGuid(Offsets::TYPEMASK_UNIT, casterGuid);
|
||||
return player != 0 && Unit::Identity::OwnerGuid(caster) == player;
|
||||
}
|
||||
|
||||
bool IsPlayerCast(const uint8_t *unit, int slot) {
|
||||
const uint32_t spellID = ReadSpellID(unit, slot);
|
||||
if (spellID == 0)
|
||||
return false;
|
||||
const uint64_t player = Unit::Identity::PlayerGuid();
|
||||
return player != 0 && Attribute(UnitGuid(unit), spellID, slot).caster == player;
|
||||
return IsPlayerOwnedCaster(
|
||||
Attribute(UnitGuid(unit), spellID, slot).caster);
|
||||
}
|
||||
|
||||
// The slot's descriptor flag nibble. Bit 0x01 is the cancelable bit on every
|
||||
// server (the other bits differ — see `IsSlotHarmful`).
|
||||
uint8_t SlotNibble(const uint8_t *unit, int slot) {
|
||||
auto *desc = Descriptor(unit);
|
||||
if (desc == nullptr || slot < 0 || slot >= Offsets::UNIT_AURA_TOTAL)
|
||||
return 0;
|
||||
const uint8_t byte = *(desc + Offsets::OFF_UNIT_FIELD_AURAFLAGS + slot / 2);
|
||||
return (byte >> ((slot & 1) * 4)) & 0xF;
|
||||
}
|
||||
|
||||
// Cancelable for an aura with no descriptor nibble to read (the cache
|
||||
// fallback, the out-of-range group array): the rule both servers'
|
||||
// SetAuraFlag write into that bit — a helpful aura without
|
||||
// SPELL_ATTR_CANT_CANCEL.
|
||||
bool SpellCancelable(uint32_t spellID, bool harmful) {
|
||||
if (harmful)
|
||||
return false;
|
||||
const uint8_t *rec = SpellRecord(spellID);
|
||||
return rec != nullptr &&
|
||||
(Game::Read<uint32_t>(rec, Offsets::OFF_SPELL_RECORD_ATTRIBUTES) &
|
||||
Offsets::SPELL_ATTR_CANT_CANCEL) == 0;
|
||||
}
|
||||
|
||||
// Applies the PLAYER / !PLAYER caster restriction. `isPlayerCast` is the
|
||||
// per-aura "was this cast by the local player" answer (false on a cache miss).
|
||||
// per-aura "was this cast by the player or a unit they own" answer (false on
|
||||
// a cache miss).
|
||||
bool CasterMatches(CasterMode caster, bool isPlayerCast) {
|
||||
switch (caster) {
|
||||
case CasterMode::PlayerOnly: return isPlayerCast;
|
||||
@@ -410,10 +440,35 @@ bool CcMatches(CcMode cc, uint32_t spellID) {
|
||||
}
|
||||
}
|
||||
|
||||
bool MatchesAura(const Match &match, bool isPlayerCast, uint32_t spellID) {
|
||||
bool IsRaidAura(uint32_t spellID, bool harmful) {
|
||||
if (harmful) {
|
||||
const uint8_t *rec = SpellRecord(spellID);
|
||||
if (rec == nullptr)
|
||||
return false;
|
||||
using Fn = uint32_t(__fastcall *)(uint32_t dispelType);
|
||||
return reinterpret_cast<Fn>(static_cast<uintptr_t>(Offsets::FUN_DISPEL_TYPE_KNOWN))(
|
||||
Game::Read<uint32_t>(rec, Offsets::OFF_SPELL_DISPEL_TYPE)) != 0;
|
||||
}
|
||||
using Fn = uint32_t(__fastcall *)(uint32_t spellID);
|
||||
return reinterpret_cast<Fn>(static_cast<uintptr_t>(Offsets::FUN_SPELL_IS_CASTABLE_AURA))(
|
||||
spellID) != 0;
|
||||
}
|
||||
|
||||
bool CancelMatches(CancelMode cancel, bool cancelable) {
|
||||
switch (cancel) {
|
||||
case CancelMode::CancelableOnly: return cancelable;
|
||||
case CancelMode::NotCancelable: return !cancelable;
|
||||
default: return true; // Any
|
||||
}
|
||||
}
|
||||
|
||||
bool MatchesAura(const Match &match, bool isPlayerCast, uint32_t spellID,
|
||||
bool harmful, bool cancelable) {
|
||||
return CasterMatches(match.caster, isPlayerCast) &&
|
||||
DispelMatches(match.dispel, spellID) &&
|
||||
CcMatches(match.cc, spellID);
|
||||
CcMatches(match.cc, spellID) &&
|
||||
CancelMatches(match.cancel, cancelable) &&
|
||||
(!match.raid || IsRaidAura(spellID, harmful));
|
||||
}
|
||||
|
||||
// `MatchesAura` for a descriptor slot the caller has ALREADY established is
|
||||
@@ -424,7 +479,10 @@ static bool PopulatedSlotMatches(const uint8_t *unit, int slot,
|
||||
const Match &match) {
|
||||
const bool castByPlayer =
|
||||
match.caster != CasterMode::Any && IsPlayerCast(unit, slot);
|
||||
return MatchesAura(match, castByPlayer, ReadSpellID(unit, slot));
|
||||
const bool cancelable =
|
||||
(SlotNibble(unit, slot) & Offsets::UNIT_AURA_FLAG_CANCELABLE) != 0;
|
||||
return MatchesAura(match, castByPlayer, ReadSpellID(unit, slot),
|
||||
IsSlotHarmful(unit, slot), cancelable);
|
||||
}
|
||||
|
||||
bool SlotMatches(const uint8_t *unit, int slot, const Match &match) {
|
||||
@@ -444,18 +502,112 @@ bool SlotMatchesFilter(const uint8_t *unit, int slot, Filter filter,
|
||||
// no slot to attribute by and the cache is consulted by (guid, spellID) alone.
|
||||
// A miss counts as "not the player" (same as IsPlayerCast).
|
||||
bool GroupIsPlayerCast(uint64_t guid, uint32_t spellID) {
|
||||
const uint64_t player = Unit::Identity::PlayerGuid();
|
||||
return player != 0 &&
|
||||
Attribute(guid, spellID, Aura::Source::SLOT_UNBOUND).caster == player;
|
||||
return IsPlayerOwnedCaster(
|
||||
Attribute(guid, spellID, Aura::Source::SLOT_UNBOUND).caster);
|
||||
}
|
||||
|
||||
// ── Own-auras-first order ──────────────────────────────────────────────────
|
||||
|
||||
static bool CanApplyAura(const uint8_t *spellRecord, uint32_t spellID);
|
||||
|
||||
namespace {
|
||||
|
||||
// A slot's group in the walk order (see `WalkOrder`).
|
||||
enum Rank : uint8_t { RANK_OWN = 0, RANK_CAN_APPLY = 1, RANK_OTHER = 2 };
|
||||
constexpr int kRanks = 3;
|
||||
|
||||
// One unit's cached groups. `spell` is the aura array the groups were built
|
||||
// from; `canApply` keeps each slot's `CanApplyAura` answer, which depends only
|
||||
// on the spell and on what the player and pet know (`knowledge`), so a rebuild
|
||||
// reuses it for every slot whose spell did not change. Caster groups are
|
||||
// rebuilt every time: the cache can learn a caster after the aura appears.
|
||||
struct SortedUnit {
|
||||
uint64_t guid;
|
||||
uint32_t frame;
|
||||
uint64_t knowledge;
|
||||
uint32_t spell[Offsets::UNIT_AURA_TOTAL];
|
||||
bool canApply[Offsets::UNIT_AURA_TOTAL];
|
||||
uint8_t rank[Offsets::UNIT_AURA_TOTAL];
|
||||
};
|
||||
|
||||
// Direct-mapped by GUID: a raid's 40 members plus target, focus and nameplates
|
||||
// mostly land in their own entries, and a collision only costs a rebuild.
|
||||
constexpr int kSortedUnits = 64;
|
||||
SortedUnit g_sorted[kSortedUnits];
|
||||
|
||||
// Bumped once per world frame, so groups built in one frame are reused by every
|
||||
// walk in that frame (a by-index loop) and rebuilt in the next.
|
||||
uint32_t g_frame = 1;
|
||||
void OnWorldTick() { ++g_frame; }
|
||||
const Tick::WorldTick::AutoSubscribe _tick{&OnWorldTick};
|
||||
|
||||
// What the player and pet know, as far as `CanApplyAura` reads it: the
|
||||
// spellbook count changes on learn and unlearn, the pet GUID on a new pet.
|
||||
uint64_t KnowledgeKey() {
|
||||
const uint64_t pet =
|
||||
Game::Read<uint64_t>(static_cast<uintptr_t>(Offsets::VAR_PET_GUID));
|
||||
const uint32_t book =
|
||||
Game::Read<uint32_t>(static_cast<uintptr_t>(Offsets::VAR_PLAYER_SPELLBOOK_COUNT));
|
||||
return pet ^ (static_cast<uint64_t>(book) << 32);
|
||||
}
|
||||
|
||||
const uint8_t *SlotRanks(const uint8_t *unit) {
|
||||
const uint64_t guid = UnitGuid(unit);
|
||||
SortedUnit &su = g_sorted[(guid ^ (guid >> 32)) % kSortedUnits];
|
||||
uint32_t spell[Offsets::UNIT_AURA_TOTAL];
|
||||
for (int s = 0; s < Offsets::UNIT_AURA_TOTAL; ++s)
|
||||
spell[s] = ReadSpellID(unit, s);
|
||||
const bool sameUnit = su.guid == guid;
|
||||
if (sameUnit && su.frame == g_frame &&
|
||||
std::memcmp(su.spell, spell, sizeof spell) == 0)
|
||||
return su.rank;
|
||||
|
||||
const uint64_t knowledge = KnowledgeKey();
|
||||
const bool reuseCanApply = sameUnit && su.knowledge == knowledge;
|
||||
uint64_t caster[Offsets::UNIT_AURA_TOTAL];
|
||||
Aura::Source::CastersForSlots(guid, spell, caster);
|
||||
for (int s = 0; s < Offsets::UNIT_AURA_TOTAL; ++s) {
|
||||
if (!reuseCanApply || su.spell[s] != spell[s])
|
||||
su.canApply[s] = spell[s] != 0 && CanApplyAura(SpellRecord(spell[s]), spell[s]);
|
||||
// The self-buff inference `Attribute` makes, so the order agrees with
|
||||
// the PLAYER filter.
|
||||
uint64_t c = caster[s];
|
||||
if (c == 0 && spell[s] != 0 && Spell::IsSelfBuff::IsSelfBuff(spell[s]))
|
||||
c = guid;
|
||||
su.rank[s] = IsPlayerOwnedCaster(c) ? RANK_OWN
|
||||
: su.canApply[s] ? RANK_CAN_APPLY
|
||||
: RANK_OTHER;
|
||||
}
|
||||
su.guid = guid;
|
||||
su.frame = g_frame;
|
||||
su.knowledge = knowledge;
|
||||
std::memcpy(su.spell, spell, sizeof spell);
|
||||
return su.rank;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void WalkOrder(const uint8_t *unit, Filter filter, int *out) {
|
||||
const uint8_t *rank = SlotRanks(unit);
|
||||
int n = 0;
|
||||
for (int r = 0; r < kRanks; ++r) {
|
||||
for (int i = 0; i < Offsets::UNIT_AURA_TOTAL; ++i) {
|
||||
const int slot = SlotInFilterOrder(filter, i);
|
||||
if (rank[slot] == r)
|
||||
out[n++] = slot;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int FindNthSlot(const uint8_t *unit, int oneBasedIndex, Filter filter,
|
||||
Match match) {
|
||||
if (unit == nullptr || oneBasedIndex < 1)
|
||||
return -1;
|
||||
int order[Offsets::UNIT_AURA_TOTAL];
|
||||
WalkOrder(unit, filter, order);
|
||||
int matches = 0;
|
||||
for (int i = 0; i < Offsets::UNIT_AURA_TOTAL; ++i) {
|
||||
const int slot = SlotInFilterOrder(filter, i);
|
||||
const int slot = order[i];
|
||||
if (!SlotMatchesFilter(unit, slot, filter, match))
|
||||
continue;
|
||||
if (++matches == oneBasedIndex)
|
||||
@@ -468,8 +620,12 @@ int FindSlotBySpellID(const uint8_t *unit, uint32_t spellID,
|
||||
const Filter *filter, Match match) {
|
||||
if (unit == nullptr || spellID == 0)
|
||||
return -1;
|
||||
// Own auras first, as 4.3.4's name lookup walks its sorted list; with no
|
||||
// filter, the helpful walk, which visits every slot.
|
||||
int order[Offsets::UNIT_AURA_TOTAL];
|
||||
WalkOrder(unit, filter != nullptr ? *filter : Filter::Helpful, order);
|
||||
for (int i = 0; i < Offsets::UNIT_AURA_TOTAL; ++i) {
|
||||
const int slot = (filter != nullptr) ? SlotInFilterOrder(*filter, i) : i;
|
||||
const int slot = order[i];
|
||||
if (!IsSlotPopulated(unit, slot))
|
||||
continue;
|
||||
if (ReadSpellID(unit, slot) != spellID)
|
||||
@@ -488,12 +644,15 @@ int FindSlotBySpellName(const uint8_t *unit, const char *spellName,
|
||||
const Filter *filter, Match match) {
|
||||
if (unit == nullptr || spellName == nullptr || *spellName == '\0')
|
||||
return -1;
|
||||
// Own auras first, as 4.3.4's name lookup walks its sorted list; with no
|
||||
// filter, the helpful walk, which visits every slot.
|
||||
int order[Offsets::UNIT_AURA_TOTAL];
|
||||
WalkOrder(unit, filter != nullptr ? *filter : Filter::Helpful, order);
|
||||
for (int i = 0; i < Offsets::UNIT_AURA_TOTAL; ++i) {
|
||||
const int slot = (filter != nullptr) ? SlotInFilterOrder(*filter, i) : i;
|
||||
const int slot = order[i];
|
||||
if (!IsSlotPopulated(unit, slot))
|
||||
continue;
|
||||
const char *name = LocalizedSpellName(SpellRecord(ReadSpellID(unit, slot)));
|
||||
if (name == nullptr || std::strcmp(name, spellName) != 0)
|
||||
if (!SpellNameMatches(SpellRecord(ReadSpellID(unit, slot)), spellName))
|
||||
continue;
|
||||
if (filter != nullptr &&
|
||||
IsSlotHarmful(unit, slot) != (*filter == Filter::Harmful))
|
||||
@@ -547,25 +706,161 @@ const char *DispelName(uint32_t dispelTypeID) {
|
||||
return (name == nullptr || *name == '\0') ? nullptr : name;
|
||||
}
|
||||
|
||||
// True when the player or their pet knows `spellID`: the known-spell bitmap,
|
||||
// else the pet spellbook — the same two sources the engine's raid-buff test
|
||||
// (`FUN_SPELL_IS_CASTABLE_AURA`) reads.
|
||||
static bool PlayerOrPetKnowsSpell(uint32_t spellID) {
|
||||
const int spellCount = Game::Read<int>(
|
||||
static_cast<uintptr_t>(Offsets::VAR_SPELL_RECORD_COUNT));
|
||||
if (spellID == 0 || static_cast<int>(spellID) > spellCount)
|
||||
return false;
|
||||
auto *bitmap = Game::Read<const uint32_t *>(
|
||||
static_cast<uintptr_t>(Offsets::VAR_PLAYER_SPELL_BITMAP));
|
||||
if (bitmap != nullptr && (bitmap[spellID >> 5] & (1u << (spellID & 31))) != 0)
|
||||
return true;
|
||||
auto *petBook = reinterpret_cast<const uint32_t *>(
|
||||
static_cast<uintptr_t>(Offsets::VAR_PET_SPELLBOOK));
|
||||
for (int i = 0; i < Offsets::SPELLBOOK_MAX_SLOTS; ++i) {
|
||||
if (petBook[i] == spellID)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// 4.3.4's `CGSpellBook::CanApplyAura`: the player or their pet knows the
|
||||
// spell and one of its effects applies an aura. (4.3.4 also consults the
|
||||
// CastableRaidBuffs table and its summon list, neither of which exists here.)
|
||||
static bool CanApplyAura(const uint8_t *spellRecord, uint32_t spellID) {
|
||||
if (spellRecord == nullptr || !PlayerOrPetKnowsSpell(spellID))
|
||||
return false;
|
||||
for (int i = 0; i < 3; ++i) {
|
||||
const int effect = Game::Read<int>(spellRecord, Offsets::OFF_SPELL_RECORD_EFFECT + i * 4);
|
||||
if (effect == Offsets::SPELL_EFFECT_APPLY_AURA ||
|
||||
effect == Offsets::SPELL_EFFECT_PERSISTENT_AREA_AURA ||
|
||||
effect == Offsets::SPELL_EFFECT_APPLY_AREA_AURA_PARTY)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// The dispel types the player can remove from an enemy, as a `1 << type` mask.
|
||||
// 4.3.4 builds this in `CGSpellBook` when a spell is learned: every Dispel
|
||||
// effect (38) aimed at an enemy adds its type (SpellDispelType's mask column,
|
||||
// else `1 << type`; vanilla's table has no mask column). 1.12 builds only the
|
||||
// friendly half (`AddSpellToBook` -> the list `FUN_DISPEL_TYPE_KNOWN` reads), so
|
||||
// this applies 4.3.4's rule to the spells the player and pet know. The targets
|
||||
// are TARGET_UNIT_ENEMY (Purge, Shield Slam, Tranquilizing Shot) and
|
||||
// TARGET_UNIT, which reaches enemies too (Dispel Magic, Devour Magic) -- the
|
||||
// case 4.3.4 special-cases for Dispel Magic. Rebuilt when `KnowledgeKey`
|
||||
// changes.
|
||||
static uint32_t SpellOffensiveDispels(const uint8_t *rec) {
|
||||
uint32_t mask = 0;
|
||||
for (int i = 0; i < 3; ++i) {
|
||||
if (Game::Read<int>(rec, Offsets::OFF_SPELL_RECORD_EFFECT + i * 4) !=
|
||||
Offsets::SPELL_EFFECT_DISPEL)
|
||||
continue;
|
||||
const int target =
|
||||
Game::Read<int>(rec, Offsets::OFF_SPELL_RECORD_EFFECT_IMPLICIT_TARGET_A + i * 4);
|
||||
const int type =
|
||||
Game::Read<int>(rec, Offsets::OFF_SPELL_RECORD_EFFECT_MISC_VALUE + i * 4);
|
||||
if ((target == Offsets::TARGET_UNIT_ENEMY || target == Offsets::TARGET_UNIT) &&
|
||||
type > 0 && type < 32)
|
||||
mask |= 1u << type;
|
||||
}
|
||||
return mask;
|
||||
}
|
||||
|
||||
static uint32_t OffensiveDispelMask() {
|
||||
static uint64_t s_key = ~0ull;
|
||||
static uint32_t s_mask = 0;
|
||||
const uint64_t key = KnowledgeKey();
|
||||
if (key == s_key)
|
||||
return s_mask;
|
||||
uint32_t mask = 0;
|
||||
const int spellCount = Game::Read<int>(
|
||||
static_cast<uintptr_t>(Offsets::VAR_SPELL_RECORD_COUNT));
|
||||
auto *bitmap = Game::Read<const uint32_t *>(
|
||||
static_cast<uintptr_t>(Offsets::VAR_PLAYER_SPELL_BITMAP));
|
||||
if (bitmap != nullptr) {
|
||||
for (int word = 0; word <= (spellCount >> 5); ++word) {
|
||||
for (uint32_t bits = bitmap[word]; bits != 0; bits &= bits - 1) {
|
||||
int bit = 0;
|
||||
while (((bits >> bit) & 1u) == 0)
|
||||
++bit;
|
||||
const uint8_t *rec = SpellRecord(static_cast<uint32_t>(word * 32 + bit));
|
||||
if (rec != nullptr)
|
||||
mask |= SpellOffensiveDispels(rec);
|
||||
}
|
||||
}
|
||||
}
|
||||
auto *petBook = reinterpret_cast<const uint32_t *>(
|
||||
static_cast<uintptr_t>(Offsets::VAR_PET_SPELLBOOK));
|
||||
for (int i = 0; i < Offsets::SPELLBOOK_MAX_SLOTS; ++i) {
|
||||
const uint8_t *rec = petBook[i] != 0 ? SpellRecord(petBook[i]) : nullptr;
|
||||
if (rec != nullptr)
|
||||
mask |= SpellOffensiveDispels(rec);
|
||||
}
|
||||
s_key = key;
|
||||
s_mask = mask;
|
||||
return mask;
|
||||
}
|
||||
|
||||
// 4.3.4's `CGSpellBook::CanStealAura` without its Spellsteal half (vanilla has
|
||||
// none): the player can attack the unit, the aura is helpful, its spell is not
|
||||
// passive, not an area aura and not channeled (AttributesEx 0x44), and its
|
||||
// dispel type is one the player can remove from an enemy.
|
||||
static bool IsStealable(uint64_t unitGuid, const uint8_t *spellRecord, bool isHelpful) {
|
||||
if (!isHelpful || spellRecord == nullptr || unitGuid == 0)
|
||||
return false;
|
||||
const uint32_t mask = OffensiveDispelMask();
|
||||
const uint32_t type = Game::Read<uint32_t>(spellRecord, Offsets::OFF_SPELL_DISPEL_TYPE);
|
||||
if (type >= 32 || (mask & (1u << type)) == 0)
|
||||
return false;
|
||||
if ((Game::Read<uint32_t>(spellRecord, Offsets::OFF_SPELL_RECORD_ATTRIBUTES) &
|
||||
Offsets::SPELL_ATTR_PASSIVE) != 0 ||
|
||||
(Game::Read<uint32_t>(spellRecord, Offsets::OFF_SPELL_RECORD_ATTRIBUTES_EX) &
|
||||
Offsets::SPELL_ATTR_EX_CHANNELED) != 0)
|
||||
return false;
|
||||
for (int i = 0; i < 3; ++i) {
|
||||
const int effect = Game::Read<int>(spellRecord, Offsets::OFF_SPELL_RECORD_EFFECT + i * 4);
|
||||
if (effect == Offsets::SPELL_EFFECT_PERSISTENT_AREA_AURA ||
|
||||
effect == Offsets::SPELL_EFFECT_APPLY_AREA_AURA_PARTY)
|
||||
return false;
|
||||
}
|
||||
void *player = const_cast<uint8_t *>(Unit::Identity::PlayerObject());
|
||||
void *unit = Object::ByGuid(Offsets::TYPEMASK_UNIT, unitGuid);
|
||||
if (player == nullptr || unit == nullptr)
|
||||
return false;
|
||||
using CanAttack_t = bool(__thiscall *)(void *attacker, void *target);
|
||||
return reinterpret_cast<CanAttack_t>(static_cast<uintptr_t>(Offsets::FUN_UNIT_CAN_ATTACK))(
|
||||
player, unit);
|
||||
}
|
||||
|
||||
// The display fields resolved from a spell record + caster, shared by the table
|
||||
// emitter (`BuildTable`) and the positional emitter (`PushPositional`) so the
|
||||
// name / icon / dispel-name lookups live in exactly one place. `castByPlayer`
|
||||
// is the positional tuple's field #13 and the table's
|
||||
// `isFromPlayerOrPlayerPet` — same value, retail's two names for the two aura
|
||||
// shapes. Both mean "applied by ANY player or a player's pet" (Era
|
||||
// semantics), not the local player — that's the `PLAYER` filter's job. The
|
||||
// answer is the caster GUID's HIGHGUID prefix: player 0x0000 / pet 0xF140
|
||||
// (server-confirmed in tortoise-wow ObjectGuid.h). Vanilla totems carry the
|
||||
// creature prefix, so totem buffs read false. False on a cache miss (cast not
|
||||
// observed), since a GUID of 0 classifies as neither.
|
||||
// name / icon / dispel-name lookups live in exactly one place.
|
||||
//
|
||||
// The two "who cast it" answers are about ANY player, not the local player —
|
||||
// that is the `PLAYER` filter's job — and read the caster GUID's HIGHGUID
|
||||
// prefix (player 0x0000 / pet 0xF140, tortoise-wow ObjectGuid.h). Both are
|
||||
// false on a cache miss, since a GUID of 0 classifies as neither:
|
||||
// castByPlayer — the positional tuple's field #13: a player cast it, as
|
||||
// 4.3.4's UnitAura computes it (a pet's GUID reads false).
|
||||
// fromPlayerOrPet — the table's `isFromPlayerOrPlayerPet`: a player or a
|
||||
// pet cast it. Totems carry the creature prefix, so they read false.
|
||||
struct Display {
|
||||
const char *name;
|
||||
const char *icon;
|
||||
const char *dispelName;
|
||||
bool castByPlayer;
|
||||
bool fromPlayerOrPet;
|
||||
bool canApplyAura;
|
||||
bool isRaid;
|
||||
bool isStealable;
|
||||
};
|
||||
|
||||
static Display ResolveDisplay(uint32_t spellID, uint64_t casterGuid) {
|
||||
static Display ResolveDisplay(uint32_t spellID, uint64_t casterGuid, bool isHelpful,
|
||||
uint64_t unitGuid) {
|
||||
const uint8_t *spellRecord = SpellRecord(spellID);
|
||||
uint32_t dispelTypeID = 0;
|
||||
if (spellRecord != nullptr) {
|
||||
@@ -576,17 +871,21 @@ static Display ResolveDisplay(uint32_t spellID, uint64_t casterGuid) {
|
||||
d.name = LocalizedSpellName(spellRecord);
|
||||
d.icon = SpellIconPath(spellRecord);
|
||||
d.dispelName = DispelName(dispelTypeID);
|
||||
d.castByPlayer = Guid::IsPlayer(casterGuid) || Guid::IsPet(casterGuid);
|
||||
d.castByPlayer = Guid::IsPlayer(casterGuid);
|
||||
d.fromPlayerOrPet = d.castByPlayer || Guid::IsPet(casterGuid);
|
||||
d.canApplyAura = CanApplyAura(spellRecord, spellID);
|
||||
d.isRaid = IsRaidAura(spellID, !isHelpful);
|
||||
d.isStealable = IsStealable(unitGuid, spellRecord, isHelpful);
|
||||
return d;
|
||||
}
|
||||
|
||||
// Writes the full modern AuraData table on top of the Lua stack from
|
||||
// already-resolved values. Shared by the descriptor path (`Push`) and the
|
||||
// cache-fallback path (`PushFromCache`). Net stack effect: +1 (the table).
|
||||
static void BuildTable(void *L, uint32_t spellID, int applications,
|
||||
static void BuildTable(void *L, uint64_t unitGuid, uint32_t spellID, int applications,
|
||||
bool isHelpful, double duration, double expirationTime,
|
||||
uint64_t casterGuid) {
|
||||
const Display disp = ResolveDisplay(spellID, casterGuid);
|
||||
const Display disp = ResolveDisplay(spellID, casterGuid, isHelpful, unitGuid);
|
||||
const char *name = disp.name;
|
||||
const char *icon = disp.icon;
|
||||
const char *dispel = disp.dispelName;
|
||||
@@ -626,17 +925,17 @@ static void BuildTable(void *L, uint32_t spellID, int applications,
|
||||
Game::Lua::SetFieldNumber(L, "maxCharges", 0);
|
||||
Game::Lua::SetFieldNumber(L, "timeMod", 1);
|
||||
|
||||
Game::Lua::SetFieldBool(L, "isFromPlayerOrPlayerPet", disp.castByPlayer);
|
||||
Game::Lua::SetFieldBool(L, "isFromPlayerOrPlayerPet", disp.fromPlayerOrPet);
|
||||
Game::Lua::SetFieldBool(L, "canApplyAura", disp.canApplyAura);
|
||||
Game::Lua::SetFieldBool(L, "isRaid", disp.isRaid);
|
||||
Game::Lua::SetFieldBool(L, "isStealable", disp.isStealable);
|
||||
|
||||
// Boolean fields whose modern semantics don't apply in vanilla.
|
||||
Game::Lua::SetFieldBool(L, "isStealable", false);
|
||||
Game::Lua::SetFieldBool(L, "isBossAura", false);
|
||||
Game::Lua::SetFieldBool(L, "isNameplateOnly", false);
|
||||
Game::Lua::SetFieldBool(L, "nameplateShowAll", false);
|
||||
Game::Lua::SetFieldBool(L, "nameplateShowPersonal", false);
|
||||
Game::Lua::SetFieldBool(L, "canApplyAura", false);
|
||||
Game::Lua::SetFieldBool(L, "shouldConsolidate", false);
|
||||
Game::Lua::SetFieldBool(L, "isRaid", false);
|
||||
|
||||
// `auraInstanceID` and `points` are deliberately omitted — modern returns
|
||||
// nil for those when they don't apply, and Lua reading a missing key
|
||||
@@ -652,12 +951,10 @@ static void BuildTable(void *L, uint32_t spellID, int applications,
|
||||
// mirror the AuraData table exactly so packed / non-packed callers agree: name /
|
||||
// icon / dispelType push `""` when absent (as `SetFieldString` does), while
|
||||
// `source` pushes nil when there's no caster (as the table omits `sourceUnit`).
|
||||
// `isHelpful` is unused (the tuple has no isHelpful/isHarmful) — kept so the leaf
|
||||
// dispatch calls either emitter with a uniform arg list.
|
||||
static void PushPositional(void *L, uint32_t spellID, int applications,
|
||||
bool /*isHelpful*/, double duration,
|
||||
static void PushPositional(void *L, uint64_t unitGuid, uint32_t spellID, int applications,
|
||||
bool isHelpful, double duration,
|
||||
double expirationTime, uint64_t casterGuid) {
|
||||
const Display disp = ResolveDisplay(spellID, casterGuid);
|
||||
const Display disp = ResolveDisplay(spellID, casterGuid, isHelpful, unitGuid);
|
||||
|
||||
const char *source = nullptr;
|
||||
char tokenBuf[32];
|
||||
@@ -672,10 +969,10 @@ static void PushPositional(void *L, uint32_t spellID, int applications,
|
||||
Game::Lua::PushNumber(L, duration); // 5 duration
|
||||
Game::Lua::PushNumber(L, expirationTime); // 6 expirationTime
|
||||
Game::Lua::PushString(L, source); // 7 source (nil if none)
|
||||
Game::Lua::PushBool(L, false); // 8 isStealable
|
||||
Game::Lua::PushBool(L, disp.isStealable); // 8 isStealable
|
||||
Game::Lua::PushBool(L, false); // 9 nameplateShowPersonal
|
||||
Game::Lua::PushNumber(L, static_cast<double>(spellID)); // 10 spellId
|
||||
Game::Lua::PushBool(L, false); // 11 canApplyAura
|
||||
Game::Lua::PushBool(L, disp.canApplyAura); // 11 canApplyAura
|
||||
Game::Lua::PushBool(L, false); // 12 isBossDebuff
|
||||
Game::Lua::PushBool(L, disp.castByPlayer); // 13 castByPlayer
|
||||
Game::Lua::PushBool(L, false); // 14 nameplateShowAll
|
||||
@@ -685,11 +982,11 @@ static void PushPositional(void *L, uint32_t spellID, int applications,
|
||||
// Enriches a bare `(guid, spellID)` into a full AuraData table — the shared
|
||||
// core behind every push path (descriptor, cache fallback, group-array). No
|
||||
// dependence on a live descriptor: the descriptor path passes what it read
|
||||
// (stacks, level, is-this-the-player), the others pass their known-or-default
|
||||
// (stacks, is-this-the-player), the others pass their known-or-default
|
||||
// values.
|
||||
//
|
||||
// Timing rules (identical across paths): `duration` is the Spell.dbc →
|
||||
// SpellDuration.dbc base scaled by `unitLevel` (0 skips scaling); talent/glyph
|
||||
// Timing rules (identical across paths): `duration` is the server's base
|
||||
// (`SpellBaseDurationSeconds`); talent/glyph
|
||||
// duration modifiers are baked into the caster-side expiration, so
|
||||
// `expirationTime - GetTime()` is the true remaining time even when `duration`
|
||||
// omits the boost. `expirationTime` for the local player comes from the engine
|
||||
@@ -699,7 +996,10 @@ static void PushPositional(void *L, uint32_t spellID, int applications,
|
||||
// (expiration 0, no sourceUnit/GUID). `slot` is the absolute descriptor slot
|
||||
// the aura occupies, which is what attributes it to the right caster when two
|
||||
// of them hold the same spell on the unit; `Aura::Source::SLOT_UNBOUND` for the
|
||||
// paths with no descriptor to read one from.
|
||||
// paths with no descriptor to read one from. `duration` and `expirationTime`
|
||||
// are reported together or not at all — 4.3.4's `PushUnitAura` pushes
|
||||
// `m_duration·0.001, m_endTime·0.001` or `0, 0`, so a known base with no
|
||||
// expiration to pair it with reads as 0, 0.
|
||||
//
|
||||
// `known` short-circuits the by-(guid,spell,slot) resolve: the cache-fallback
|
||||
// paths already hold the exact entry's attribution (Enumerate copied it out),
|
||||
@@ -708,19 +1008,22 @@ static void PushPositional(void *L, uint32_t spellID, int applications,
|
||||
// return a miss — dropping a caster Enumerate already knew. Null for the
|
||||
// descriptor / group-array paths, which have no per-entry attribution in hand.
|
||||
static void PushEnriched(void *L, uint64_t guid, uint32_t spellID,
|
||||
bool isHelpful, int applications, int unitLevel,
|
||||
bool isHelpful, int applications,
|
||||
bool isPlayer, int slot,
|
||||
const Attribution *known = nullptr,
|
||||
Emit emit = Emit::Table) {
|
||||
double duration = 0.0;
|
||||
double expirationTime = 0.0;
|
||||
uint64_t casterGuid = 0;
|
||||
bool untilCancelled = false;
|
||||
if (spellID != 0)
|
||||
duration = SpellBaseDurationSeconds(spellID, unitLevel);
|
||||
duration = SpellBaseDurationSeconds(spellID);
|
||||
if (isPlayer && spellID != 0) {
|
||||
const uint8_t *entry = FindPlayerBuffEntry(spellID);
|
||||
if (entry != nullptr)
|
||||
expirationTime = PlayerBuffExpirationSeconds(entry);
|
||||
const uint8_t *record = FindPlayerBuffRecord(slot);
|
||||
if (record != nullptr) {
|
||||
untilCancelled = PlayerBuffUntilCancelled(record);
|
||||
expirationTime = PlayerBuffExpirationSeconds(record);
|
||||
}
|
||||
}
|
||||
if (spellID != 0 && guid != 0) {
|
||||
// Caster (sourceGUID/sourceUnit) and timing resolved together, so a
|
||||
@@ -743,11 +1046,17 @@ static void PushEnriched(void *L, uint64_t guid, uint32_t spellID,
|
||||
duration = static_cast<double>(a.durationMs) * 0.001;
|
||||
casterGuid = a.caster;
|
||||
}
|
||||
// The engine's own word that the player's aura has no end wins over
|
||||
// every other source of timing.
|
||||
if (untilCancelled || expirationTime == 0.0) {
|
||||
duration = 0.0;
|
||||
expirationTime = 0.0;
|
||||
}
|
||||
if (emit == Emit::Positional)
|
||||
PushPositional(L, spellID, applications, isHelpful, duration,
|
||||
PushPositional(L, guid, spellID, applications, isHelpful, duration,
|
||||
expirationTime, casterGuid);
|
||||
else
|
||||
BuildTable(L, spellID, applications, isHelpful, duration, expirationTime,
|
||||
BuildTable(L, guid, spellID, applications, isHelpful, duration, expirationTime,
|
||||
casterGuid);
|
||||
}
|
||||
|
||||
@@ -760,9 +1069,8 @@ static Attribution CachedAttribution(const Aura::Source::CachedAura &c) {
|
||||
void Push(void *L, const uint8_t *unit, int slot, Emit emit) {
|
||||
const uint32_t spellID = ReadSpellID(unit, slot);
|
||||
const bool isHelpful = !IsSlotHarmful(unit, slot); // nibble, not slot range
|
||||
const int unitLevel = (unit != nullptr) ? PlayerLevel(unit) : 0;
|
||||
PushEnriched(L, UnitGuid(unit), spellID, isHelpful, ReadStacks(unit, slot),
|
||||
unitLevel, unit != nullptr && unit == LocalPlayer(), slot,
|
||||
unit != nullptr && unit == LocalPlayer(), slot,
|
||||
/*known*/ nullptr, emit);
|
||||
}
|
||||
|
||||
@@ -780,9 +1088,8 @@ void PushFromCache(void *L, const uint8_t *unit,
|
||||
// re-resolving by (guid, spell, slot) — an unbound entry sharing its spell
|
||||
// with another caster's would otherwise resolve to a miss and drop the
|
||||
// caster. Stacks aren't in SMSG_SPELL_GO, so `applications` is 1.
|
||||
const int unitLevel = (unit != nullptr) ? PlayerLevel(unit) : 0;
|
||||
const Attribution a = CachedAttribution(c);
|
||||
PushEnriched(L, UnitGuid(unit), c.spellId, isHelpful, 1, unitLevel, false,
|
||||
PushEnriched(L, UnitGuid(unit), c.spellId, isHelpful, 1, false,
|
||||
c.slot, &a, emit);
|
||||
}
|
||||
|
||||
@@ -846,9 +1153,10 @@ bool FallbackEligible(const uint8_t *unit, const Aura::Source::CachedAura &c,
|
||||
|
||||
// Applies `match` to a cache entry. The entry carries its caster, so the caster
|
||||
// test is a plain GUID compare — no scan, nothing to defer.
|
||||
bool CachedMatches(const Aura::Source::CachedAura &c, const Match &match) {
|
||||
return MatchesAura(match, c.casterGuid == Unit::Identity::PlayerGuid(),
|
||||
c.spellId);
|
||||
bool CachedMatches(const Aura::Source::CachedAura &c, const Match &match,
|
||||
bool harmful) {
|
||||
return MatchesAura(match, IsPlayerOwnedCaster(c.casterGuid), c.spellId,
|
||||
harmful, SpellCancelable(c.spellId, harmful));
|
||||
}
|
||||
|
||||
// The eligible cache-fallback entries for `unit` under `filter`, in `Enumerate`
|
||||
@@ -890,7 +1198,7 @@ bool PushNthCacheFallback(void *L, const uint8_t *unit, int oneBasedIndex,
|
||||
const int n = EligibleFallbacks(unit, filter, buf);
|
||||
int seen = 0;
|
||||
for (int i = 0; i < n; ++i) {
|
||||
if (!CachedMatches(buf[i], match))
|
||||
if (!CachedMatches(buf[i], match, filter == Filter::Harmful))
|
||||
continue;
|
||||
if (++seen == oneBasedIndex) {
|
||||
PushFromCache(L, unit, buf[i], filter == Filter::Helpful, emit);
|
||||
@@ -905,7 +1213,7 @@ void AppendCacheFallbacks(void *L, const uint8_t *unit, Filter filter,
|
||||
Aura::Source::CachedAura buf[kFallbackMax];
|
||||
const int n = EligibleFallbacks(unit, filter, buf);
|
||||
for (int i = 0; i < n; ++i) {
|
||||
if (!CachedMatches(buf[i], match))
|
||||
if (!CachedMatches(buf[i], match, filter == Filter::Harmful))
|
||||
continue;
|
||||
Game::Lua::PushNumber(L, static_cast<double>(nextKey++));
|
||||
PushFromCache(L, unit, buf[i], filter == Filter::Helpful);
|
||||
@@ -920,7 +1228,7 @@ namespace {
|
||||
// Absolute slot range [start, end) for a filter in the GROUP ARRAY (helpful
|
||||
// 0..31, harmful 32..47). The array carries spell IDs only — no flag nibble —
|
||||
// so the seating range is the only polarity the out-of-range path has. (The
|
||||
// descriptor path reads the nibble instead; see SlotInFilterOrder.)
|
||||
// descriptor path reads the nibble instead; see WalkOrder.)
|
||||
void GroupRange(Filter filter, int &start, int &end) {
|
||||
start = (filter == Filter::Harmful) ? Offsets::UNIT_AURA_BUFF_COUNT : 0;
|
||||
end = (filter == Filter::Harmful) ? Offsets::UNIT_AURA_TOTAL
|
||||
@@ -954,13 +1262,9 @@ bool GroupSlotMatches(uint64_t guid, const uint16_t *arr, int slot,
|
||||
const uint32_t id = GroupSpellID(arr, slot);
|
||||
const bool castByPlayer =
|
||||
match.caster != CasterMode::Any && GroupIsPlayerCast(guid, id);
|
||||
return MatchesAura(match, castByPlayer, id);
|
||||
}
|
||||
|
||||
// The groupmate's level, for Spell.dbc duration scaling (0 = skip). Cheap
|
||||
// roster lookup; only hit on the out-of-range path.
|
||||
int GroupMemberLevel(uint64_t guid) {
|
||||
return Group::MemberStats::Lookup(guid).level;
|
||||
const bool harmful = slot >= Offsets::UNIT_AURA_BUFF_COUNT;
|
||||
return MatchesAura(match, castByPlayer, id, harmful,
|
||||
SpellCancelable(id, harmful));
|
||||
}
|
||||
|
||||
// True if the group array exposes ANY visible aura (either kind). When it
|
||||
@@ -1030,12 +1334,12 @@ bool PushNthGroupCacheFallback(void *L, uint64_t guid, const uint16_t *arr,
|
||||
EligibleGroupFallbacks(arr, guid, filter == Filter::Harmful, buf);
|
||||
int seen = 0;
|
||||
for (int i = 0; i < n; ++i) {
|
||||
if (!CachedMatches(buf[i], match))
|
||||
if (!CachedMatches(buf[i], match, filter == Filter::Harmful))
|
||||
continue;
|
||||
if (++seen == oneBasedIndex) {
|
||||
const Attribution a = CachedAttribution(buf[i]);
|
||||
PushEnriched(L, guid, buf[i].spellId, filter == Filter::Helpful, 1,
|
||||
GroupMemberLevel(guid), false, buf[i].slot, &a, emit);
|
||||
false, buf[i].slot, &a, emit);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -1049,13 +1353,12 @@ void AppendGroupCacheFallbacks(void *L, uint64_t guid, const uint16_t *arr,
|
||||
Aura::Source::CachedAura buf[kFallbackMax];
|
||||
const int n =
|
||||
EligibleGroupFallbacks(arr, guid, filter == Filter::Harmful, buf);
|
||||
const int level = GroupMemberLevel(guid);
|
||||
for (int i = 0; i < n; ++i) {
|
||||
if (!CachedMatches(buf[i], match))
|
||||
if (!CachedMatches(buf[i], match, filter == Filter::Harmful))
|
||||
continue;
|
||||
Game::Lua::PushNumber(L, static_cast<double>(nextKey++));
|
||||
const Attribution a = CachedAttribution(buf[i]);
|
||||
PushEnriched(L, guid, buf[i].spellId, filter == Filter::Helpful, 1, level,
|
||||
PushEnriched(L, guid, buf[i].spellId, filter == Filter::Helpful, 1,
|
||||
false, buf[i].slot, &a);
|
||||
Game::Lua::SetTable(L, outerIdx);
|
||||
}
|
||||
@@ -1072,14 +1375,13 @@ bool PushGroupCacheFallbackMatch(void *L, uint64_t guid, const uint16_t *arr,
|
||||
if (spellID != 0 && buf[i].spellId != spellID)
|
||||
continue;
|
||||
if (spellName != nullptr) {
|
||||
const char *nm = LocalizedSpellName(SpellRecord(buf[i].spellId));
|
||||
if (nm == nullptr || std::strcmp(nm, spellName) != 0)
|
||||
if (!SpellNameMatches(SpellRecord(buf[i].spellId), spellName))
|
||||
continue;
|
||||
}
|
||||
if (!CachedMatches(buf[i], match))
|
||||
if (!CachedMatches(buf[i], match, harmful))
|
||||
continue;
|
||||
const Attribution a = CachedAttribution(buf[i]);
|
||||
PushEnriched(L, guid, buf[i].spellId, !harmful, 1, GroupMemberLevel(guid),
|
||||
PushEnriched(L, guid, buf[i].spellId, !harmful, 1,
|
||||
false, buf[i].slot, &a);
|
||||
return true;
|
||||
}
|
||||
@@ -1104,7 +1406,7 @@ bool PushNthGroupAura(void *L, uint64_t guid, int oneBasedIndex, Filter filter,
|
||||
continue;
|
||||
if (++matches == oneBasedIndex) {
|
||||
PushEnriched(L, guid, GroupSpellID(arr, slot),
|
||||
filter == Filter::Helpful, 1, GroupMemberLevel(guid),
|
||||
filter == Filter::Helpful, 1,
|
||||
false, Aura::Source::SLOT_UNBOUND, /*known*/ nullptr,
|
||||
emit);
|
||||
return true;
|
||||
@@ -1135,7 +1437,7 @@ bool PushGroupAuraBySpellID(void *L, uint64_t guid, uint32_t spellID,
|
||||
if (!GroupSlotMatches(guid, arr, slot, match))
|
||||
continue;
|
||||
PushEnriched(L, guid, spellID, slot < Offsets::UNIT_AURA_BUFF_COUNT, 1,
|
||||
GroupMemberLevel(guid), false, Aura::Source::SLOT_UNBOUND);
|
||||
false, Aura::Source::SLOT_UNBOUND);
|
||||
return true;
|
||||
}
|
||||
// Empty array (server delta-resend gap): supplement from the cache.
|
||||
@@ -1167,13 +1469,12 @@ bool PushGroupAuraBySpellName(void *L, uint64_t guid, const char *spellName,
|
||||
const uint32_t id = GroupSpellID(arr, slot);
|
||||
if (id == 0)
|
||||
continue;
|
||||
const char *name = LocalizedSpellName(SpellRecord(id));
|
||||
if (name == nullptr || std::strcmp(name, spellName) != 0)
|
||||
if (!SpellNameMatches(SpellRecord(id), spellName))
|
||||
continue;
|
||||
if (!GroupSlotMatches(guid, arr, slot, match))
|
||||
continue;
|
||||
PushEnriched(L, guid, id, slot < Offsets::UNIT_AURA_BUFF_COUNT, 1,
|
||||
GroupMemberLevel(guid), false, Aura::Source::SLOT_UNBOUND);
|
||||
false, Aura::Source::SLOT_UNBOUND);
|
||||
return true;
|
||||
}
|
||||
// Empty array (server delta-resend gap): supplement from the cache.
|
||||
@@ -1197,13 +1498,12 @@ void AppendGroupAuras(void *L, uint64_t guid, Filter filter, Match match,
|
||||
Aura::Source::ObserveGroupAuras(guid, arr);
|
||||
int start, end;
|
||||
GroupRange(filter, start, end);
|
||||
const int level = GroupMemberLevel(guid);
|
||||
for (int slot = start; slot < end; ++slot) {
|
||||
if (!GroupSlotMatches(guid, arr, slot, match))
|
||||
continue;
|
||||
Game::Lua::PushNumber(L, static_cast<double>(nextKey++));
|
||||
PushEnriched(L, guid, GroupSpellID(arr, slot),
|
||||
filter == Filter::Helpful, 1, level, false,
|
||||
filter == Filter::Helpful, 1, false,
|
||||
Aura::Source::SLOT_UNBOUND);
|
||||
Game::Lua::SetTable(L, outerIdx);
|
||||
}
|
||||
@@ -1217,8 +1517,10 @@ int CollectSlots(const uint8_t *unit, uint64_t guid, Filter filter, Match match,
|
||||
int *out, int cap) {
|
||||
int n = 0;
|
||||
if (unit != nullptr) {
|
||||
int order[Offsets::UNIT_AURA_TOTAL];
|
||||
WalkOrder(unit, filter, order);
|
||||
for (int i = 0; i < Offsets::UNIT_AURA_TOTAL && n < cap; ++i) {
|
||||
const int slot = SlotInFilterOrder(filter, i);
|
||||
const int slot = order[i];
|
||||
if (SlotMatchesFilter(unit, slot, filter, match))
|
||||
out[n++] = slot;
|
||||
}
|
||||
@@ -1230,7 +1532,7 @@ int CollectSlots(const uint8_t *unit, uint64_t guid, Filter filter, Match match,
|
||||
const int base = (filter == Filter::Harmful) ? OPAQUE_CACHE_HARMFUL
|
||||
: OPAQUE_CACHE_HELPFUL;
|
||||
for (int k = 0; k < m && n < cap; ++k) {
|
||||
if (CachedMatches(buf[k], match))
|
||||
if (CachedMatches(buf[k], match, filter == Filter::Harmful))
|
||||
out[n++] = base + k;
|
||||
}
|
||||
return n;
|
||||
@@ -1253,7 +1555,7 @@ int CollectSlots(const uint8_t *unit, uint64_t guid, Filter filter, Match match,
|
||||
const int base = (filter == Filter::Harmful) ? OPAQUE_GROUP_CACHE_HARMFUL
|
||||
: OPAQUE_GROUP_CACHE_HELPFUL;
|
||||
for (int k = 0; k < m && n < cap; ++k) {
|
||||
if (CachedMatches(buf[k], match))
|
||||
if (CachedMatches(buf[k], match, filter == Filter::Harmful))
|
||||
out[n++] = base + k;
|
||||
}
|
||||
return n;
|
||||
@@ -1291,7 +1593,7 @@ bool PushBySlot(void *L, const uint8_t *unit, uint64_t guid, int slot, Emit emit
|
||||
if (!GroupSlotVisible(arr, k))
|
||||
return false;
|
||||
PushEnriched(L, guid, GroupSpellID(arr, k),
|
||||
k < Offsets::UNIT_AURA_BUFF_COUNT, 1, GroupMemberLevel(guid),
|
||||
k < Offsets::UNIT_AURA_BUFF_COUNT, 1,
|
||||
false, Aura::Source::SLOT_UNBOUND, /*known*/ nullptr, emit);
|
||||
return true;
|
||||
}
|
||||
@@ -1307,7 +1609,7 @@ bool PushBySlot(void *L, const uint8_t *unit, uint64_t guid, int slot, Emit emit
|
||||
if (k >= EligibleGroupFallbacks(arr, guid, harmful, buf))
|
||||
return false;
|
||||
const Attribution a = CachedAttribution(buf[k]);
|
||||
PushEnriched(L, guid, buf[k].spellId, !harmful, 1, GroupMemberLevel(guid),
|
||||
PushEnriched(L, guid, buf[k].spellId, !harmful, 1,
|
||||
false, buf[k].slot, &a, emit);
|
||||
return true;
|
||||
}
|
||||
|
||||
+60
-25
@@ -63,13 +63,20 @@ enum class Filter { Helpful, Harmful };
|
||||
enum class Emit { Table, Positional };
|
||||
|
||||
// Caster restriction from the `PLAYER` / `!PLAYER` aura filter tokens.
|
||||
// `Any` = no restriction; `PlayerOnly` = only auras the local player cast
|
||||
// (`PLAYER`); `NotPlayer` = only auras NOT cast by the local player
|
||||
// (`!PLAYER`). Caster attribution comes from the `Aura::Source` cache; a
|
||||
// cache miss counts as "not the player" (so `PlayerOnly` excludes it and
|
||||
// `NotPlayer` includes it — matching `IsPlayerCast`'s miss semantics).
|
||||
// `Any` = no restriction; `PlayerOnly` = only auras the local player cast,
|
||||
// or a unit the player owns cast — pet, guardian, totem, charmed unit
|
||||
// (`PLAYER`); `NotPlayer` = the complement (`!PLAYER`). This is 4.3.4's
|
||||
// `CGSpellBook::IsAuraCaster`. Caster attribution comes from the
|
||||
// `Aura::Source` cache; a cache miss counts as "not the player" (so
|
||||
// `PlayerOnly` excludes it and `NotPlayer` includes it — matching
|
||||
// `IsPlayerCast`'s miss semantics).
|
||||
enum class CasterMode { Any, PlayerOnly, NotPlayer };
|
||||
|
||||
// Restriction from the `CANCELABLE` / `NOT_CANCELABLE` aura filter tokens:
|
||||
// the descriptor nibble's cancelable bit, the test `GetPlayerBuff`'s own
|
||||
// filter makes (and 4.3.4's GetSortedAuraSlot).
|
||||
enum class CancelMode { Any, CancelableOnly, NotCancelable };
|
||||
|
||||
// Restriction from the `DISPELLABLE` / `!DISPELLABLE` aura filter tokens.
|
||||
// `Any` = no restriction; `DispellableOnly` = only auras that can be
|
||||
// dispelled / purged / stolen by SOME mechanism (dispel type Magic, Curse,
|
||||
@@ -91,6 +98,10 @@ struct Match {
|
||||
CasterMode caster = CasterMode::Any;
|
||||
DispelMode dispel = DispelMode::Any;
|
||||
CcMode cc = CcMode::Any;
|
||||
CancelMode cancel = CancelMode::Any;
|
||||
// `RAID`: a helpful aura the player can cast on others, a harmful one the
|
||||
// player can dispel — the engine's raid filter (see `IsRaidAura`).
|
||||
bool raid = false;
|
||||
};
|
||||
|
||||
// Reads the spell ID at the given absolute slot (0..47). Returns 0
|
||||
@@ -117,11 +128,18 @@ bool IsSlotHarmful(const uint8_t *unit, int slot);
|
||||
// the index the engine's tooltip methods expect for a given slot.
|
||||
bool IsSlotTooltipVisible(const uint8_t *unit, int slot);
|
||||
|
||||
// The i-th slot (0..UNIT_AURA_TOTAL-1) in the order a `filter` walk visits the
|
||||
// descriptor: the polarity's home range first (helpful 0..31, harmful 32..47),
|
||||
// then the other range, where spilled debuffs live. Every enumeration that
|
||||
// hands out indices or slot lists uses this so they agree on order.
|
||||
int SlotInFilterOrder(Filter filter, int i);
|
||||
// Fills `out` with all UNIT_AURA_TOTAL absolute slots of `unit` in the order a
|
||||
// `filter` walk visits them, the order 4.3.4's sorted aura list gives
|
||||
// (`CGUnit_C::InsertSortedAura`):
|
||||
// 1. auras the player, or a unit the player owns, cast (`IsPlayerCast`);
|
||||
// 2. auras the player could apply (`canApplyAura`);
|
||||
// 3. the rest.
|
||||
// Within each group, the polarity's home range comes first (helpful 0..31,
|
||||
// harmful 32..47), then the other range, where spilled debuffs live. Every
|
||||
// enumeration that hands out indices or slot lists uses this so they agree on
|
||||
// order. The groups are cached per unit and rebuilt when its aura array changes
|
||||
// or a new frame starts, so a by-index loop pays for them once.
|
||||
void WalkOrder(const uint8_t *unit, Filter filter, int *out);
|
||||
|
||||
// `SlotMatches` plus the polarity test: populated, of `filter`'s polarity, and
|
||||
// passing `match`.
|
||||
@@ -130,7 +148,7 @@ bool SlotMatchesFilter(const uint8_t *unit, int slot, Filter filter,
|
||||
|
||||
// Finds the absolute slot of the `oneBasedIndex`-th populated aura of
|
||||
// `filter`'s polarity that passes `match`. Returns -1 if no such aura. Walks
|
||||
// all 48 slots in `SlotInFilterOrder`.
|
||||
// all 48 slots in `WalkOrder`.
|
||||
int FindNthSlot(const uint8_t *unit, int oneBasedIndex, Filter filter,
|
||||
Match match = {});
|
||||
|
||||
@@ -142,30 +160,41 @@ int FindSlotBySpellID(const uint8_t *unit, uint32_t spellID,
|
||||
const Filter *filter, Match match = {});
|
||||
|
||||
// Finds the absolute slot of a populated aura whose locale-resolved
|
||||
// spell name exactly matches `spellName`. Case-sensitive. Otherwise
|
||||
// spell name matches `spellName`, ignoring case (Storm's SStrCmpI, as
|
||||
// 4.3.4's GetSortedAuraSlot compares names). Otherwise
|
||||
// same semantics as `FindSlotBySpellID`. Returns -1 if not found
|
||||
// or if `spellName` is null/empty.
|
||||
int FindSlotBySpellName(const uint8_t *unit, const char *spellName,
|
||||
const Filter *filter, Match match = {});
|
||||
|
||||
// True iff the aura at `slot` was cast by the local player, per the
|
||||
// `Aura::Source` cache. False on a cache miss (caster unknown) — so a
|
||||
// PLAYER-filtered query excludes auras whose cast we didn't observe.
|
||||
// True iff the aura at `slot` was cast by the local player or by a unit the
|
||||
// player owns (see `CasterMode`), per the `Aura::Source` cache. False on a
|
||||
// cache miss (caster unknown) — so a PLAYER-filtered query excludes auras
|
||||
// whose cast we didn't observe.
|
||||
bool IsPlayerCast(const uint8_t *unit, int slot);
|
||||
|
||||
// Applies a `CasterMode` to a per-aura "was cast by the local player" answer.
|
||||
// `Any` → always true; `PlayerOnly` → the answer; `NotPlayer` → its negation.
|
||||
// Applies a `CasterMode` to a per-aura "was cast by the player or a unit
|
||||
// they own" answer. `Any` → always true; `PlayerOnly` → the answer;
|
||||
// `NotPlayer` → its negation.
|
||||
bool CasterMatches(CasterMode caster, bool isPlayerCast);
|
||||
|
||||
// The engine's raid filter — UnitBuff/UnitDebuff's third argument, and
|
||||
// 4.3.4's `RAID` token: a helpful aura passes when the player can cast its
|
||||
// spell on others (`FUN_SPELL_IS_CASTABLE_AURA`), a harmful one when its
|
||||
// dispel type is in the player's dispel list (`FUN_DISPEL_TYPE_KNOWN`).
|
||||
bool IsRaidAura(uint32_t spellID, bool harmful);
|
||||
|
||||
// True iff the spell's dispel type is one a dispel/purge/steal can remove —
|
||||
// Magic, Curse, Disease, or Poison (`Spell.dbc` Dispel ∈ 1..4). None,
|
||||
// Stealth, Invisibility, Enrage, etc. are not dispellable. Verified against
|
||||
// the server's DISPEL_ALL_MASK.
|
||||
bool IsDispellable(uint32_t spellID);
|
||||
|
||||
// Applies a full `Match` (caster + dispel predicates) to one aura, given the
|
||||
// per-aura "was cast by the local player" answer and its spell ID.
|
||||
bool MatchesAura(const Match &match, bool isPlayerCast, uint32_t spellID);
|
||||
// Applies a full `Match` to one aura, given the per-aura "was cast by the
|
||||
// local player" answer, its spell ID, its polarity, and whether it is
|
||||
// cancelable.
|
||||
bool MatchesAura(const Match &match, bool isPlayerCast, uint32_t spellID,
|
||||
bool harmful, bool cancelable);
|
||||
|
||||
// True iff descriptor `slot` on `unit` is populated (per `IsSlotPopulated`) AND
|
||||
// passes `match`. The caster answer (`IsPlayerCast` — a scan of the
|
||||
@@ -203,13 +232,19 @@ const char *DispelName(uint32_t dispelTypeID);
|
||||
// sourceGUID (caster "0x..." GUID string; nil on miss — a ClassicAPI
|
||||
// extension, not in retail AuraData)
|
||||
//
|
||||
// And these from the spell and the player's spells:
|
||||
// isFromPlayerOrPlayerPet (caster GUID is a player or a pet),
|
||||
// canApplyAura (the player or pet knows the spell and it applies an aura),
|
||||
// isRaid (the aura passes the RAID filter, `IsRaidAura`),
|
||||
// isStealable (4.3.4's CanStealAura: a buff on an attackable unit whose
|
||||
// dispel type a spell the player or pet knows removes from
|
||||
// an enemy)
|
||||
//
|
||||
// And these with vanilla-truthful defaults (matches modern's
|
||||
// "field present but inapplicable" semantics):
|
||||
// charges=0, maxCharges=0, auraInstanceID=nil, points=nil,
|
||||
// isStealable=false, isBossAura=false, isFromPlayerOrPlayerPet=false,
|
||||
// isNameplateOnly=false, nameplateShowAll=false,
|
||||
// nameplateShowPersonal=false, canApplyAura=false,
|
||||
// shouldConsolidate=false, isRaid=false
|
||||
// isBossAura=false, isNameplateOnly=false, nameplateShowAll=false,
|
||||
// nameplateShowPersonal=false, shouldConsolidate=false
|
||||
//
|
||||
// Net stack effect: +1 for `Emit::Table` (the table), +15 for `Emit::Positional`
|
||||
// (the Classic-Era `UnitAura` tuple — see `Emit`).
|
||||
@@ -269,7 +304,7 @@ bool PushGroupAuraBySpellID(void *L, uint64_t guid, uint32_t spellID,
|
||||
const Filter *filter, Match match = {});
|
||||
|
||||
// As `PushGroupAuraBySpellID` but matched by locale-resolved spell name
|
||||
// (case-sensitive exact match), mirroring `FindSlotBySpellName`.
|
||||
// (ignoring case), mirroring `FindSlotBySpellName`.
|
||||
bool PushGroupAuraBySpellName(void *L, uint64_t guid, const char *spellName,
|
||||
const Filter *filter, Match match = {});
|
||||
|
||||
|
||||
+224
-50
@@ -24,10 +24,12 @@
|
||||
#include "object/Resolve.h"
|
||||
#include "player/StatSignal.h"
|
||||
#include "spell/CastEvents.h"
|
||||
#include "spell/Known.h"
|
||||
#include "spell/Lookup.h"
|
||||
#include "tick/WorldTick.h"
|
||||
#include "time/Clock.h"
|
||||
#include "totem/Tracker.h"
|
||||
#include "unit/TokenEvents.h"
|
||||
#include "unit/Identity.h"
|
||||
|
||||
#include <cstdint>
|
||||
@@ -60,11 +62,11 @@ using Time::Clock::NowMs;
|
||||
// Server-authoritative duration (ms). When the local player is the caster
|
||||
// we let the engine fold in the player's duration modifiers (skipMod = 0);
|
||||
// for any other caster we take the unmodified base (skipMod = 1) since we
|
||||
// only have the local player's mod tables. `unit = 0` selects the player
|
||||
// mod context per FUN_GET_SPELL_DURATION's signature.
|
||||
// only have the local player's mod tables. `pet = 0` selects the player
|
||||
// as the caster per FUN_GET_SPELL_DURATION's signature.
|
||||
uint32_t SpellDurationMs(const uint8_t *spellRecord, bool casterIsPlayer) {
|
||||
using GetDuration_t = int(__fastcall *)(const uint8_t *spellRecord,
|
||||
int unit, char skipMod);
|
||||
int pet, char skipMod);
|
||||
const int ms = reinterpret_cast<GetDuration_t>(
|
||||
static_cast<uintptr_t>(Offsets::FUN_GET_SPELL_DURATION))(
|
||||
spellRecord, 0, casterIsPlayer ? 0 : 1);
|
||||
@@ -324,7 +326,7 @@ Entry *Register(Entry *e) {
|
||||
Entry *Claim(uint32_t now) {
|
||||
for (auto &e : g_cache) {
|
||||
if (!e.used ||
|
||||
(e.expirationMs != 0 && now >= e.expirationMs &&
|
||||
(e.expirationMs != 0 && Time::Clock::Reached(now, e.expirationMs) &&
|
||||
!DescriptorListsAura(e.targetGuid, e.spellId)))
|
||||
return Register(&e);
|
||||
}
|
||||
@@ -638,11 +640,9 @@ void SignalAuraChanged(uint64_t guid) {
|
||||
}
|
||||
|
||||
void FlushAuraSignals() {
|
||||
using Broadcast_t = void(__fastcall *)(uint64_t *guid, uint32_t eventCode);
|
||||
auto broadcast = reinterpret_cast<Broadcast_t>(
|
||||
static_cast<uintptr_t>(Offsets::FUN_UNIT_EVENT_BROADCAST));
|
||||
// The engine broadcast plus ClassicAPI's tokens (see Unit::TokenEvents).
|
||||
for (int i = 0; i < g_pendingSignalCount; ++i)
|
||||
broadcast(&g_pendingSignals[i], Offsets::UNIT_EVENT_UNIT_AURA);
|
||||
Unit::TokenEvents::Broadcast(&g_pendingSignals[i], Offsets::UNIT_EVENT_UNIT_AURA);
|
||||
g_pendingSignalCount = 0;
|
||||
}
|
||||
|
||||
@@ -661,7 +661,8 @@ void ApplyModOp(Entry &e, int32_t op, int32_t valueMs, uint32_t now) {
|
||||
break;
|
||||
case MOD_REDUCE:
|
||||
if (e.expirationMs != 0) {
|
||||
if (e.expirationMs > now + static_cast<uint32_t>(valueMs)) {
|
||||
if (Time::Clock::Remaining(now, e.expirationMs) >
|
||||
static_cast<uint32_t>(valueMs)) {
|
||||
e.expirationMs -= static_cast<uint32_t>(valueMs);
|
||||
SignalAuraChanged(e.targetGuid);
|
||||
} else {
|
||||
@@ -1263,23 +1264,6 @@ constexpr int kTrigAppMax = 32;
|
||||
TriggeredApplication g_trigApps[kTrigAppMax];
|
||||
int g_trigAppCount = 0;
|
||||
|
||||
// Talent gate: does the player currently know `spellID`? The engine's
|
||||
// spell-knowledge bitmap (same store IsPlayerSpell reads — covers talent
|
||||
// passives), checked live at trigger time so respecs are honored.
|
||||
bool PlayerKnowsSpell(uint32_t spellID) {
|
||||
if (spellID == 0)
|
||||
return false;
|
||||
auto *bitmap = Game::Read<const uint32_t *>(
|
||||
static_cast<uintptr_t>(Offsets::VAR_PLAYER_SPELL_BITMAP));
|
||||
if (bitmap == nullptr)
|
||||
return false;
|
||||
const uint32_t spellCount = Game::Read<uint32_t>(
|
||||
static_cast<uintptr_t>(Offsets::VAR_SPELL_RECORD_COUNT));
|
||||
if (spellID > spellCount)
|
||||
return false;
|
||||
return (bitmap[spellID >> 5] & (1u << (spellID & 31))) != 0;
|
||||
}
|
||||
|
||||
// Armed rule instance awaiting its application on `victim`. Caster is
|
||||
// implicitly the local player (only player triggers arm).
|
||||
struct TrigAppArm {
|
||||
@@ -1355,7 +1339,7 @@ void ArmTriggeredApplications(uint64_t victim, uint32_t triggerSpellId,
|
||||
: !Spell::Lookup::IsFitToFamily(triggerRec, r.triggerFamily,
|
||||
r.triggerMask))
|
||||
continue;
|
||||
if (r.gateSpellId != 0 && !PlayerKnowsSpell(r.gateSpellId))
|
||||
if (r.gateSpellId != 0 && !Spell::Known::IsKnown(r.gateSpellId))
|
||||
continue;
|
||||
const uint32_t now = NowMs();
|
||||
RefreshTriggeredExisting(victim, r, now);
|
||||
@@ -1406,6 +1390,114 @@ int32_t ConsumeTriggeredApplication(uint64_t victim, const uint8_t *rec,
|
||||
// keeps the parse short and robust.
|
||||
constexpr int kMaxTargets = 16;
|
||||
|
||||
// ---- Triggered auras (SPELL_EFFECT_TRIGGER_SPELL) -------------------------
|
||||
//
|
||||
// An effect of type TRIGGER_SPELL makes the server cast EffectTriggerSpell[i]
|
||||
// as a side effect of the cast — Pounce 9005 → Pounce Bleed 9007 (Spell.dbc:
|
||||
// Effect = {6, 64, 80}, EffectTriggerSpell = {0, 9007, 0}). When the
|
||||
// triggered spell's own SMSG_SPELL_GO never reaches the client, its aura is
|
||||
// seated caster-less by OnAuraAdded. The trigger's SPELL_GO names the caster,
|
||||
// so attribution goes through it, read off the DBC link rather than a table.
|
||||
//
|
||||
// A hit by the TRIGGER doesn't prove the triggered aura landed: a target
|
||||
// immune to bleed takes Pounce's stun but not its bleed. So a fresh
|
||||
// application is ARMED, and only the application hook — the descriptor proof
|
||||
// that it landed — consumes the arm (same shape as the judgement arm above).
|
||||
// An instance this caster already holds on the target is refreshed in place
|
||||
// as well: the server's re-apply reuses the descriptor slot, so no
|
||||
// OnAuraAdded fires (the remove+add RefreshTriggeredExisting mirrors).
|
||||
//
|
||||
// Any caster: nothing here needs the caster's talents, and a remote caster
|
||||
// gets the base duration exactly as their directly cast auras do.
|
||||
|
||||
struct TrigAuraArm {
|
||||
uint64_t victim; // 0 = empty
|
||||
uint64_t caster;
|
||||
uint32_t spellId; // the triggered aura
|
||||
uint32_t untilMs;
|
||||
};
|
||||
constexpr int kTrigAuraArmMax = 8;
|
||||
constexpr uint32_t kTrigAuraArmTtlMs = 2000;
|
||||
TrigAuraArm g_trigAuraArms[kTrigAuraArmMax];
|
||||
|
||||
void ArmTriggeredAura(uint64_t victim, uint32_t spellId, uint64_t caster,
|
||||
uint32_t now) {
|
||||
TrigAuraArm *slot = nullptr;
|
||||
for (auto &a : g_trigAuraArms) {
|
||||
if (a.victim == victim && a.spellId == spellId && a.caster == caster) {
|
||||
slot = &a; // re-trigger inside the TTL — refresh in place
|
||||
break;
|
||||
}
|
||||
if (slot == nullptr &&
|
||||
(a.victim == 0 || Time::Clock::Reached(now, a.untilMs)))
|
||||
slot = &a;
|
||||
}
|
||||
if (slot == nullptr)
|
||||
slot = &g_trigAuraArms[0]; // all live — steal the first
|
||||
*slot = {victim, caster, spellId, now + kTrigAuraArmTtlMs};
|
||||
}
|
||||
|
||||
// The caster armed for `spellId` landing on `victim`, or 0. One-shot.
|
||||
uint64_t ConsumeTriggeredAura(uint64_t victim, uint32_t spellId, uint32_t now) {
|
||||
if (victim == 0)
|
||||
return 0;
|
||||
for (auto &a : g_trigAuraArms) {
|
||||
if (a.victim != victim || a.spellId != spellId ||
|
||||
Time::Clock::Reached(now, a.untilMs))
|
||||
continue;
|
||||
const uint64_t caster = a.caster;
|
||||
a = {};
|
||||
return caster;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Duration of an aura cast by `caster`. Combo-point finishers (Rupture,
|
||||
// Kidney Shot, …) have their real duration computed at cast time from the
|
||||
// combo points spent — the base-duration helper can't know it.
|
||||
// ComboDuration mirrors the server's computation from the CP snapshot its
|
||||
// send hook captured; 0 means "not combo-scaled", fall through to the base
|
||||
// path. 0 overall = unknown.
|
||||
uint32_t CastDurationMs(const uint8_t *rec, uint32_t spellId,
|
||||
bool casterIsPlayer) {
|
||||
const uint32_t comboMs =
|
||||
casterIsPlayer ? ComboDuration::TryComboScaledMs(rec, spellId) : 0;
|
||||
return comboMs != 0 ? comboMs : SpellDurationMs(rec, casterIsPlayer);
|
||||
}
|
||||
|
||||
void ApplyTriggeredAuras(uint64_t caster, uint32_t spellId, const uint8_t *rec,
|
||||
const uint64_t *targets, int numTargets) {
|
||||
if (rec == nullptr)
|
||||
return;
|
||||
const auto *effects = reinterpret_cast<const int32_t *>(
|
||||
rec + Offsets::OFF_SPELL_RECORD_EFFECT);
|
||||
const auto *triggered = reinterpret_cast<const int32_t *>(
|
||||
rec + Offsets::OFF_SPELL_RECORD_EFFECT_TRIGGER_SPELL);
|
||||
const bool casterIsPlayer = (caster == Unit::Identity::PlayerGuid());
|
||||
const uint32_t now = NowMs();
|
||||
for (int i = 0; i < Offsets::SPELL_RECORD_EFFECT_COUNT; ++i) {
|
||||
if (effects[i] != Offsets::SPELL_EFFECT_TRIGGER_SPELL ||
|
||||
triggered[i] <= 0)
|
||||
continue;
|
||||
const auto auraId = static_cast<uint32_t>(triggered[i]);
|
||||
if (auraId == spellId)
|
||||
continue;
|
||||
const uint8_t *auraRec = Spell::Lookup::RecordForID(triggered[i]);
|
||||
if (!SpellAppliesAura(auraRec))
|
||||
continue;
|
||||
const uint32_t durationMs =
|
||||
CastDurationMs(auraRec, auraId, casterIsPlayer);
|
||||
const uint32_t expirationMs = durationMs > 0 ? now + durationMs : 0;
|
||||
for (int t = 0; t < numTargets; ++t) {
|
||||
ArmTriggeredAura(targets[t], auraId, caster, now);
|
||||
if (FindByCaster(targets[t], auraId, caster) != nullptr &&
|
||||
DescriptorListsAura(targets[t], auraId))
|
||||
StoreFromCast(targets[t], auraId, caster, expirationMs,
|
||||
durationMs);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The self-contained SPELL_GO processing (succeeded events, server-side
|
||||
// duration edits, aura-source caching). None of it reads engine descriptor
|
||||
// state, so it's order-independent of the engine's own SPELL_GO handler —
|
||||
@@ -1455,19 +1547,23 @@ void HandleSpellGo(uint64_t caster, uint32_t spellId, const uint64_t *targets,
|
||||
for (int i = 0; i < numTargets; ++i)
|
||||
ArmTriggeredApplications(targets[i], spellId, rec);
|
||||
|
||||
// The units this cast's auras land on: the hit list, or the caster itself
|
||||
// when the packet carries none (self-cast with a caster-implicit target).
|
||||
// Shared by the triggered auras and the cast's own aura below.
|
||||
const uint64_t *auraTargets = targets;
|
||||
int numAuraTargets = numTargets;
|
||||
if (numTargets == 0) {
|
||||
auraTargets = &caster;
|
||||
numAuraTargets = 1;
|
||||
}
|
||||
|
||||
ApplyTriggeredAuras(caster, spellId, rec, auraTargets, numAuraTargets);
|
||||
|
||||
if (!SpellAppliesAura(rec))
|
||||
return;
|
||||
|
||||
const bool casterIsPlayer = (caster == Unit::Identity::PlayerGuid());
|
||||
// Combo-point finishers (Rupture, Kidney Shot, …) have their real
|
||||
// duration computed at cast time from the combo points spent — the
|
||||
// base-duration helper can't know it. ComboDuration mirrors the
|
||||
// server's computation from the CP snapshot its send hook captured;
|
||||
// 0 means "not combo-scaled", fall through to the base path.
|
||||
uint32_t durationMs =
|
||||
casterIsPlayer ? ComboDuration::TryComboScaledMs(rec, spellId) : 0;
|
||||
if (durationMs == 0)
|
||||
durationMs = SpellDurationMs(rec, casterIsPlayer);
|
||||
const uint32_t durationMs = CastDurationMs(rec, spellId, casterIsPlayer);
|
||||
const uint32_t expirationMs = durationMs > 0 ? NowMs() + durationMs : 0;
|
||||
|
||||
// Let the application hooks recover the player-talented duration for this
|
||||
@@ -1476,13 +1572,8 @@ void HandleSpellGo(uint64_t caster, uint32_t spellId, const uint64_t *targets,
|
||||
if (casterIsPlayer)
|
||||
RememberPlayerCast(spellId);
|
||||
|
||||
if (numTargets == 0) {
|
||||
// No explicit hit list (self-cast with caster-implicit target).
|
||||
StoreFromCast(caster, spellId, caster, expirationMs, durationMs);
|
||||
return;
|
||||
}
|
||||
for (int i = 0; i < numTargets; ++i)
|
||||
StoreFromCast(targets[i], spellId, caster, expirationMs, durationMs);
|
||||
for (int i = 0; i < numAuraTargets; ++i)
|
||||
StoreFromCast(auraTargets[i], spellId, caster, expirationMs, durationMs);
|
||||
}
|
||||
|
||||
// SMSG_SPELL_GO parse (funnel subscriber). At the leaf handler the engine has
|
||||
@@ -1565,6 +1656,16 @@ void StampApplication(void *unit, uint32_t spellId, int slot) {
|
||||
durationMs = 1;
|
||||
}
|
||||
}
|
||||
// A triggered-aura arm (Pounce → Pounce Bleed): the server cast this aura
|
||||
// off a trigger whose SPELL_GO named the caster, and this application is
|
||||
// the proof it landed. Target-scoped, so it goes before the spell-scoped
|
||||
// recent-cast window below, for the same reason as the nettle arm.
|
||||
if (caster == 0) {
|
||||
caster = ConsumeTriggeredAura(unitGuid, spellId, NowMs());
|
||||
if (caster != 0)
|
||||
durationMs =
|
||||
SpellDurationMs(rec, caster == Unit::Identity::PlayerGuid());
|
||||
}
|
||||
if (caster == 0) {
|
||||
const bool byPlayer = WasRecentPlayerCast(spellId);
|
||||
durationMs = SpellDurationMs(rec, byPlayer);
|
||||
@@ -1590,6 +1691,30 @@ void NotifyIfPlayer(void *unit) {
|
||||
Player::StatSignal::Notify();
|
||||
}
|
||||
|
||||
const AutoObserve *g_observers = nullptr;
|
||||
|
||||
void NotifyObservers(const Change &change) {
|
||||
for (const AutoObserve *o = g_observers; o != nullptr; o = o->next)
|
||||
o->callback(change);
|
||||
}
|
||||
|
||||
// The change for the aura in `slot`, with the caster and polarity of the
|
||||
// instance this cache binds to it. A removed aura's slot already holds the
|
||||
// next aura's flags, so its polarity is the one recorded when it landed.
|
||||
Change MakeChange(ChangeType type, void *unit, int slot, uint32_t spellId) {
|
||||
Change c{type, unit, slot, spellId, 0, false, 0, 0};
|
||||
const Entry *e = FindInstance(Unit::Identity::GuidForObject(unit), spellId, slot);
|
||||
if (e != nullptr)
|
||||
c.caster = e->casterGuid;
|
||||
if (type != ChangeType::Removed)
|
||||
c.harmful = KindForSlot(unit, slot) == KIND_HARMFUL;
|
||||
else if (e != nullptr && e->kind != KIND_UNKNOWN)
|
||||
c.harmful = e->kind == KIND_HARMFUL;
|
||||
else
|
||||
c.harmful = slot >= Offsets::UNIT_AURA_BUFF_COUNT;
|
||||
return c;
|
||||
}
|
||||
|
||||
// OnAuraAdded — a new aura occupies a slot (gives the spellId directly).
|
||||
using OnAuraAdded_t = void(__fastcall *)(void *unit, void *edx, uint32_t slot,
|
||||
uint32_t spellId);
|
||||
@@ -1600,6 +1725,7 @@ void __fastcall OnAuraAdded_h(void *unit, void *edx, uint32_t slot,
|
||||
g_origOnAuraAdded(unit, edx, slot, spellId);
|
||||
StampApplication(unit, spellId, static_cast<int>(slot));
|
||||
NotifyIfPlayer(unit);
|
||||
NotifyObservers(MakeChange(ChangeType::Added, unit, static_cast<int>(slot), spellId));
|
||||
}
|
||||
|
||||
const Game::HookAutoRegister _hookAuraAdded{
|
||||
@@ -1609,17 +1735,24 @@ const Game::HookAutoRegister _hookAuraAdded{
|
||||
// OnAuraStacksChanged — an existing aura's stack count changed (e.g. Shadow
|
||||
// Weaving climbing). Only the slot is given, so read the spellID back from
|
||||
// the unit's aura array. Re-stamps expiration so stacking refreshes count.
|
||||
// The byte argument is the slot's OLD applications byte: the engine compares
|
||||
// it with the descriptor's new one and logs a stack line when the new is
|
||||
// higher (0x00612450).
|
||||
using OnAuraStacksChanged_t = void(__fastcall *)(void *unit, void *edx,
|
||||
int slot, uint8_t stackCount);
|
||||
int slot, uint8_t oldApplications);
|
||||
OnAuraStacksChanged_t g_origOnAuraStacksChanged = nullptr;
|
||||
|
||||
void __fastcall OnAuraStacksChanged_h(void *unit, void *edx, int slot,
|
||||
uint8_t stackCount) {
|
||||
g_origOnAuraStacksChanged(unit, edx, slot, stackCount);
|
||||
StampApplication(
|
||||
unit,
|
||||
Aura::Data::ReadSpellID(static_cast<const uint8_t *>(unit), slot), slot);
|
||||
uint8_t oldApplications) {
|
||||
g_origOnAuraStacksChanged(unit, edx, slot, oldApplications);
|
||||
const auto *u = static_cast<const uint8_t *>(unit);
|
||||
const uint32_t spellId = Aura::Data::ReadSpellID(u, slot);
|
||||
StampApplication(unit, spellId, slot);
|
||||
NotifyIfPlayer(unit);
|
||||
Change c = MakeChange(ChangeType::Stacks, unit, slot, spellId);
|
||||
c.oldStacks = static_cast<int>(oldApplications) + 1;
|
||||
c.newStacks = Aura::Data::ReadStacks(u, slot);
|
||||
NotifyObservers(c);
|
||||
}
|
||||
|
||||
const Game::HookAutoRegister _hookAuraStacks{
|
||||
@@ -1647,6 +1780,7 @@ OnAuraRemoved_t g_origOnAuraRemoved = nullptr;
|
||||
void __fastcall OnAuraRemoved_h(void *unit, void *edx, uint32_t slot,
|
||||
uint32_t spellId) {
|
||||
g_origOnAuraRemoved(unit, edx, slot, spellId);
|
||||
NotifyObservers(MakeChange(ChangeType::Removed, unit, static_cast<int>(slot), spellId));
|
||||
Evict(Unit::Identity::GuidForObject(unit), spellId, static_cast<int>(slot));
|
||||
NotifyIfPlayer(unit);
|
||||
}
|
||||
@@ -1674,6 +1808,42 @@ bool Get(uint64_t unitGuid, uint32_t spellId, int slot, uint64_t *outCaster,
|
||||
return true;
|
||||
}
|
||||
|
||||
void CastersForSlots(uint64_t unitGuid, const uint32_t *slotSpellIds,
|
||||
uint64_t *outCaster) {
|
||||
constexpr int kSlots = Offsets::UNIT_AURA_TOTAL;
|
||||
const Entry *seated[kSlots] = {};
|
||||
const Entry *sole[kSlots] = {};
|
||||
int soleCount[kSlots] = {};
|
||||
for (int i = 0; i < kSlots; ++i)
|
||||
outCaster[i] = 0;
|
||||
if (unitGuid == 0)
|
||||
return;
|
||||
// `FindInstance` for all slots in one pass: the entry seated in the slot
|
||||
// (FindBySlot), else the unit's only entry for the slot's spell (FindSole).
|
||||
for (int i = 0; i < g_usedHigh; ++i) {
|
||||
const Entry &e = g_cache[i];
|
||||
if (!e.used || e.targetGuid != unitGuid)
|
||||
continue;
|
||||
if (e.slot >= 0 && e.slot < kSlots && slotSpellIds[e.slot] == e.spellId &&
|
||||
seated[e.slot] == nullptr)
|
||||
seated[e.slot] = &e;
|
||||
for (int s = 0; s < kSlots; ++s) {
|
||||
if (slotSpellIds[s] == e.spellId) {
|
||||
sole[s] = &e;
|
||||
++soleCount[s];
|
||||
}
|
||||
}
|
||||
}
|
||||
for (int s = 0; s < kSlots; ++s) {
|
||||
if (slotSpellIds[s] == 0)
|
||||
continue;
|
||||
if (seated[s] != nullptr)
|
||||
outCaster[s] = seated[s]->casterGuid;
|
||||
else if (soleCount[s] == 1)
|
||||
outCaster[s] = sole[s]->casterGuid;
|
||||
}
|
||||
}
|
||||
|
||||
bool AddDurationMod(uint32_t triggerSpellId, uint32_t affectedFamily,
|
||||
uint64_t affectedMask, uint32_t affectedIcon, int op,
|
||||
int32_t valueMs) {
|
||||
@@ -1865,7 +2035,7 @@ int Enumerate(uint64_t unitGuid, bool harmful, CachedAura *out, int maxOut) {
|
||||
const Entry &e = g_cache[i];
|
||||
if (!e.used || e.targetGuid != unitGuid || e.kind != want)
|
||||
continue;
|
||||
if (e.expirationMs != 0 && now >= e.expirationMs)
|
||||
if (e.expirationMs != 0 && Time::Clock::Reached(now, e.expirationMs))
|
||||
continue; // expired (infinite-duration entries pass)
|
||||
out[n++] = {e.spellId, e.casterGuid, e.expirationMs, e.durationMs,
|
||||
e.slot};
|
||||
@@ -1924,4 +2094,8 @@ void ObserveGroupAuras(uint64_t guid, const uint16_t *auraArray) {
|
||||
snap->touchMs = now;
|
||||
}
|
||||
|
||||
AutoObserve::AutoObserve(ChangeCallback cb) : callback(cb), next(g_observers) {
|
||||
g_observers = this;
|
||||
}
|
||||
|
||||
} // namespace Aura::Source
|
||||
|
||||
@@ -60,6 +60,15 @@ constexpr int SLOT_UNBOUND = -1;
|
||||
bool Get(uint64_t unitGuid, uint32_t spellId, int slot, uint64_t *outCaster,
|
||||
uint32_t *outExpirationMs, uint32_t *outDurationMs);
|
||||
|
||||
// `Get`'s caster for every descriptor slot at once, in one pass over the
|
||||
// cache: `outCaster[slot]` is the caster `Get(unitGuid, slotSpellIds[slot],
|
||||
// slot, ...)` would report, or 0. `slotSpellIds` and `outCaster` hold
|
||||
// `Offsets::UNIT_AURA_TOTAL` entries. For walks that need every slot's caster
|
||||
// (the own-auras-first sort), where 48 separate `Get` scans would cost 48
|
||||
// passes.
|
||||
void CastersForSlots(uint64_t unitGuid, const uint32_t *slotSpellIds,
|
||||
uint64_t *outCaster);
|
||||
|
||||
// Refreshes `casterGuid`'s aura on `unitGuid` matching the same selector the
|
||||
// duration rules use — SpellFamilyName plus a family-flag overlap and/or a
|
||||
// SpellIconID, at least one of the two — to a full duration from now. Returns
|
||||
@@ -228,4 +237,31 @@ int Enumerate(uint64_t unitGuid, bool harmful, CachedAura *out, int maxOut);
|
||||
// any real SpellGo timing we already hold, so this never downgrades better data.
|
||||
void ObserveGroupAuras(uint64_t guid, const uint16_t *auraArray);
|
||||
|
||||
// An aura arriving on a unit, leaving it, or changing its stack count, as the
|
||||
// engine's own handlers see it (`OnAuraAdded`, `OnAuraRemoved`,
|
||||
// `OnAuraStacksChanged`), with the caster this cache binds to it.
|
||||
enum class ChangeType { Added, Removed, Stacks };
|
||||
|
||||
struct Change {
|
||||
ChangeType type;
|
||||
void *unit;
|
||||
int slot;
|
||||
uint32_t spellId;
|
||||
uint64_t caster; // 0 when unknown
|
||||
bool harmful;
|
||||
int oldStacks; // Stacks only: the count before the change
|
||||
int newStacks; // Stacks only: the count now
|
||||
};
|
||||
|
||||
using ChangeCallback = void (*)(const Change &change);
|
||||
|
||||
// Declare a file-scope `static const Aura::Source::AutoObserve _obs{&fn};`.
|
||||
// Added and Stacks reach the callback after the cache has stamped the aura,
|
||||
// Removed before the cache evicts it, so `caster` is the cache's in all three.
|
||||
struct AutoObserve {
|
||||
explicit AutoObserve(ChangeCallback cb);
|
||||
ChangeCallback callback;
|
||||
const AutoObserve *next;
|
||||
};
|
||||
|
||||
} // namespace Aura::Source
|
||||
|
||||
+63
-51
@@ -16,22 +16,38 @@
|
||||
// (added 5.4.x) with exact same-semantic coalescing: addons listen
|
||||
// to DELAYED instead of BAG_UPDATE and rescan once per frame.
|
||||
//
|
||||
// See TODO #67 for the full investigation history.
|
||||
// Architecture: three MinHooks on the engine's three BAG_UPDATE
|
||||
// emitters, plus one tick subscription. Names are benilla-re's.
|
||||
//
|
||||
// Architecture: three MinHooks plus one tick subscription.
|
||||
//
|
||||
// 1. `FUN_004F91A0` — bag-slot diff loop. Hook just sets the
|
||||
// `g_pending` flag.
|
||||
// 2. `FUN_004F9370` — item→bag resolver (most common path). Hook
|
||||
// just sets the `g_pending` flag.
|
||||
// 3. `FUN_004F8DB0` — bag-descriptor change callback. Covers the
|
||||
// keyring `BAG_UPDATE(slot)` direct-fire branch that doesn't
|
||||
// route through `FUN_004F9370`.
|
||||
// 1. `RaiseBagEvents` (`0x004F91A0`) — compares the ten bag slots
|
||||
// (4 bags, 6 bank bags) with the cached container GUIDs and
|
||||
// fires BAG_CLOSED / BAG_UPDATE per changed slot. Called by the
|
||||
// bag-slot field watcher and once at login.
|
||||
// 2. `RaiseBagUpdate` (`0x004F9370`) — fires BAG_UPDATE for the
|
||||
// player or one of the ten cached containers; the most common
|
||||
// path. Its callers are the backpack and container slot
|
||||
// watchers, and the item-field watcher `0x004F9480`, which
|
||||
// passes an item's container — the PLAYER for equipped gear, so
|
||||
// a durability change on worn gear fires BAG_UPDATE(0) and
|
||||
// therefore DELAYED. That is the engine's behaviour, kept.
|
||||
// 3. `OnBackpackSlotChanged` (`0x004F8DB0`) — the field watcher on
|
||||
// backpack slots 23..38 and keyring slots 81..112. Keyring
|
||||
// changes fire BAG_UPDATE directly here; backpack changes go
|
||||
// through `RaiseBagUpdate`. Standard watcher ABI
|
||||
// `__fastcall(offset, unused, guidLo, guidHi, previous*, user)`,
|
||||
// ret 0x10 — the same shape as `OnContainerSlotChanged`.
|
||||
// 4. `Tick::WorldTick::AutoSubscribe` — shared per-frame
|
||||
// subscription (the engine's world-subsystem update at
|
||||
// `FUN_0066FD50`, single-hooked in `src/tick/WorldTick.cpp`).
|
||||
// Our callback drains `g_pending` and fires DELAYED if set.
|
||||
//
|
||||
// The hooks set `g_pending` after every call rather than only when
|
||||
// an event fired. The one call that fires nothing is
|
||||
// `RaiseBagUpdate` for a container outside the cache, which does not
|
||||
// occur in practice; mirroring that check here would be a parallel
|
||||
// copy of the engine's test. The bank's main slots 39..62 have no
|
||||
// engine watcher, so they never fire BAG_UPDATE or DELAYED.
|
||||
//
|
||||
// All hook targets are quiet (≤3 callers each, in code regions
|
||||
// other DLLs don't touch). The previous attempt at this feature
|
||||
// hooked `FUN_FIRE_EVENT` (100+ callers, in the chat path) and a
|
||||
@@ -68,7 +84,12 @@ namespace {
|
||||
|
||||
constexpr const char *kEventName = "BAG_UPDATE_DELAYED";
|
||||
|
||||
const Event::Custom::AutoReserve _reserve{kEventName};
|
||||
const Game::Doc::Event kUpdateDelayedDoc{
|
||||
"Container",
|
||||
"Fires once in each frame in which one or more BAG_UPDATE events fired, "
|
||||
"after all of them.",
|
||||
{}};
|
||||
const Event::Custom::AutoReserve _reserve{kEventName, &kUpdateDelayedDoc};
|
||||
|
||||
// Set by the bag-update hooks, drained by the world-tick hook.
|
||||
// Single bool, no atomics needed — the engine is single-threaded.
|
||||
@@ -83,40 +104,31 @@ AutoSubscribe::AutoSubscribe(Callback cb) : cb(cb), next(g_subs) {
|
||||
g_subs = this;
|
||||
}
|
||||
|
||||
// `FUN_004F91A0` — `__cdecl void()`. Bag-slot diff loop. Walks the
|
||||
// 10 bag slots, fires BAG_UPDATE for each that changed.
|
||||
using BagSlotDiff_t = void(__cdecl *)();
|
||||
BagSlotDiff_t BagSlotDiff_o = nullptr;
|
||||
void __cdecl BagSlotDiff_h() {
|
||||
BagSlotDiff_o();
|
||||
// `RaiseBagEvents` — `__cdecl void()`.
|
||||
using RaiseBagEvents_t = void(__cdecl *)();
|
||||
RaiseBagEvents_t RaiseBagEvents_o = nullptr;
|
||||
void __cdecl RaiseBagEvents_h() {
|
||||
RaiseBagEvents_o();
|
||||
g_pending = true;
|
||||
}
|
||||
|
||||
// `FUN_004F9370` — `__stdcall void(int guidLo, int guidHi)`. Most
|
||||
// common BAG_UPDATE path — fires from every per-item descriptor
|
||||
// field change.
|
||||
using BagItemToBag_t = void(__stdcall *)(int guidLo, int guidHi);
|
||||
BagItemToBag_t BagItemToBag_o = nullptr;
|
||||
void __stdcall BagItemToBag_h(int guidLo, int guidHi) {
|
||||
BagItemToBag_o(guidLo, guidHi);
|
||||
// `RaiseBagUpdate` — `__stdcall void(containerGuidLo, containerGuidHi)`.
|
||||
using RaiseBagUpdate_t = void(__stdcall *)(int guidLo, int guidHi);
|
||||
RaiseBagUpdate_t RaiseBagUpdate_o = nullptr;
|
||||
void __stdcall RaiseBagUpdate_h(int guidLo, int guidHi) {
|
||||
RaiseBagUpdate_o(guidLo, guidHi);
|
||||
g_pending = true;
|
||||
}
|
||||
|
||||
// `FUN_004F8DB0` — `__thiscall unsigned(this, a1, a2, a3, a4)` in the
|
||||
// Octo build. Wired with `__fastcall` + dummy EDX to match the
|
||||
// thiscall ABI: ECX takes `this`, EDX unused, stack takes the four
|
||||
// dword args, callee cleans 16 bytes (`RET 0x10`). Same trick
|
||||
// `Frame::RegisterEvent` uses in DllMain, just with four stack args
|
||||
// instead of one — the Octo function is wider than the vanilla
|
||||
// signature Ghidra showed when this hook was first written.
|
||||
using KeyringDescChange_t = unsigned(__fastcall *)(void *bagDesc, void *edx_unused,
|
||||
unsigned a1, unsigned a2,
|
||||
unsigned a3, unsigned a4);
|
||||
KeyringDescChange_t KeyringDescChange_o = nullptr;
|
||||
unsigned __fastcall KeyringDescChange_h(void *bagDesc, void *edx,
|
||||
unsigned a1, unsigned a2,
|
||||
unsigned a3, unsigned a4) {
|
||||
const unsigned result = KeyringDescChange_o(bagDesc, edx, a1, a2, a3, a4);
|
||||
// `OnBackpackSlotChanged` — field-watcher ABI, `__fastcall(offset,
|
||||
// unused, guidLo, guidHi, previous*, user)`, callee cleans 0x10.
|
||||
using BackpackSlotChanged_t = unsigned(__fastcall *)(unsigned offset, unsigned unused,
|
||||
unsigned guidLo, unsigned guidHi,
|
||||
const void *previous, void *user);
|
||||
BackpackSlotChanged_t BackpackSlotChanged_o = nullptr;
|
||||
unsigned __fastcall BackpackSlotChanged_h(unsigned offset, unsigned unused, unsigned guidLo,
|
||||
unsigned guidHi, const void *previous, void *user) {
|
||||
const unsigned result = BackpackSlotChanged_o(offset, unused, guidLo, guidHi, previous, user);
|
||||
g_pending = true;
|
||||
return result;
|
||||
}
|
||||
@@ -151,20 +163,20 @@ void OnWorldTick() {
|
||||
node->cb();
|
||||
}
|
||||
|
||||
static const Game::HookAutoRegister _hookSlotDiff{
|
||||
Offsets::FUN_BAG_SLOT_DIFF,
|
||||
reinterpret_cast<void *>(&BagSlotDiff_h),
|
||||
reinterpret_cast<void **>(&BagSlotDiff_o)};
|
||||
static const Game::HookAutoRegister _hookRaiseBagEvents{
|
||||
Offsets::FUN_RAISE_BAG_EVENTS,
|
||||
reinterpret_cast<void *>(&RaiseBagEvents_h),
|
||||
reinterpret_cast<void **>(&RaiseBagEvents_o)};
|
||||
|
||||
static const Game::HookAutoRegister _hookItemToBag{
|
||||
Offsets::FUN_BAG_ITEM_TO_BAG,
|
||||
reinterpret_cast<void *>(&BagItemToBag_h),
|
||||
reinterpret_cast<void **>(&BagItemToBag_o)};
|
||||
static const Game::HookAutoRegister _hookRaiseBagUpdate{
|
||||
Offsets::FUN_RAISE_BAG_UPDATE,
|
||||
reinterpret_cast<void *>(&RaiseBagUpdate_h),
|
||||
reinterpret_cast<void **>(&RaiseBagUpdate_o)};
|
||||
|
||||
static const Game::HookAutoRegister _hookKeyringDesc{
|
||||
Offsets::FUN_BAG_KEYRING_DESC_CHANGE,
|
||||
reinterpret_cast<void *>(&KeyringDescChange_h),
|
||||
reinterpret_cast<void **>(&KeyringDescChange_o)};
|
||||
static const Game::HookAutoRegister _hookBackpackSlot{
|
||||
Offsets::FUN_ON_BACKPACK_SLOT_CHANGED,
|
||||
reinterpret_cast<void *>(&BackpackSlotChanged_h),
|
||||
reinterpret_cast<void **>(&BackpackSlotChanged_o)};
|
||||
|
||||
static const Tick::WorldTick::AutoSubscribe _tickSub{&OnWorldTick};
|
||||
|
||||
|
||||
@@ -24,15 +24,15 @@
|
||||
// CreateFromMixins(...) -- Mixin({}, ...); returns the new table.
|
||||
// Non-table extra arguments are skipped (the Lua form guards nil the same way).
|
||||
|
||||
#include "baselib/Mixin.h"
|
||||
|
||||
#include "Game.h"
|
||||
|
||||
namespace BaseLib::Mixin {
|
||||
|
||||
namespace {
|
||||
|
||||
// Shallow-copy every pair from the table at `srcIdx` onto the table at
|
||||
// `dstIdx` (both absolute, positive stack indices). Stack-balanced.
|
||||
void MixinInto(void *L, int dstIdx, int srcIdx) {
|
||||
void Into(void *L, int dstIdx, int srcIdx) {
|
||||
Game::Lua::PushNil(L);
|
||||
while (Game::Lua::Next(L, srcIdx) != 0) {
|
||||
// stack top: ..., key (-2), value (-1). Copy both so the originals
|
||||
@@ -44,6 +44,8 @@ void MixinInto(void *L, int dstIdx, int srcIdx) {
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
int __fastcall Script_Mixin(void *L) {
|
||||
const int top = Game::Lua::GetTop(L);
|
||||
if (top < 1 || Game::Lua::Type(L, 1) != Game::Lua::TYPE_TABLE) {
|
||||
@@ -52,7 +54,7 @@ int __fastcall Script_Mixin(void *L) {
|
||||
}
|
||||
for (int i = 2; i <= top; ++i)
|
||||
if (Game::Lua::Type(L, i) == Game::Lua::TYPE_TABLE)
|
||||
MixinInto(L, 1, i);
|
||||
Into(L, 1, i);
|
||||
Game::Lua::PushValue(L, 1); // return object
|
||||
return 1;
|
||||
}
|
||||
@@ -63,7 +65,7 @@ int __fastcall Script_CreateFromMixins(void *L) {
|
||||
const int objIdx = top + 1;
|
||||
for (int i = 1; i <= top; ++i)
|
||||
if (Game::Lua::Type(L, i) == Game::Lua::TYPE_TABLE)
|
||||
MixinInto(L, objIdx, i);
|
||||
Into(L, objIdx, i);
|
||||
Game::Lua::SetTop(L, objIdx); // the new table is the sole result
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
// This file is part of ClassicAPI.
|
||||
//
|
||||
// ClassicAPI is free software: you can redistribute it and/or modify it under the terms
|
||||
// of the GNU 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 General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License along with
|
||||
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#pragma once
|
||||
|
||||
namespace BaseLib::Mixin {
|
||||
|
||||
// dst[k] = v for every field of the table at `srcIdx` — Mixin()'s copy.
|
||||
// Both indices must be absolute.
|
||||
void Into(void *L, int dstIdx, int srcIdx);
|
||||
|
||||
} // namespace BaseLib::Mixin
|
||||
@@ -13,7 +13,8 @@
|
||||
|
||||
// String helpers that 1.12's Lua 5.0 is missing:
|
||||
//
|
||||
// - `string.match(s, pattern [, init])` — first-match extraction (5.1).
|
||||
// - `string.match(s, pattern [, init])` — first-match extraction (5.1),
|
||||
// also the global `strmatch`, as `string.find` is `strfind`.
|
||||
// - `string.gmatch(s, pattern)` — match iterator (5.1).
|
||||
// - `string.gsub` TABLE replacement — 5.1 form (see the shim below).
|
||||
// - `strsplit(sep, str [, pieces])` — WoW global; split on any char.
|
||||
@@ -389,15 +390,24 @@ void RegisterFns() {
|
||||
Game::Lua::RegisterTableFunction("string", "gsub", &Script_string_gsub);
|
||||
Game::Lua::RegisterTableFunction("string", "reverse", &Script_string_reverse);
|
||||
Game::Lua::RegisterTableFunction("string", "split", &Script_strsplit);
|
||||
// The bare `gsub` global (1.12 exposes the string functions as globals
|
||||
// too) must match `string.gsub`, so addons calling either form get the
|
||||
// table-replacement upgrade.
|
||||
Game::Lua::RegisterGlobalFunction("gsub", &Script_string_gsub);
|
||||
Game::Lua::RegisterGlobalFunction("strsplit", &Script_strsplit);
|
||||
Game::Lua::RegisterGlobalFunction("strjoin", &Script_strjoin);
|
||||
Game::Lua::RegisterGlobalFunction("strtrim", &Script_strtrim);
|
||||
Game::Lua::RegisterTableFunction("string", "trim", &Script_strtrim);
|
||||
Game::Lua::RegisterTableFunction("string", "join", &Script_strjoin);
|
||||
// 4.3.4's compat.lua binds each short global and its string-table twin
|
||||
// to ONE function by assignment (`gsub = str.gsub`, `strmatch =
|
||||
// str.match`, `strrev = str.reverse`, `str.trim = strtrim`, `str.split =
|
||||
// strsplit`, `str.join = strjoin`), so `strtrim == string.trim`. A second
|
||||
// Register* call would mint a second closure over the same C function, so
|
||||
// the globals alias the table entries by value instead. The string-table
|
||||
// half is what lets `(" x "):trim()` work and libraries capture it at
|
||||
// file scope (AceConfigCmd-3.0: `strtrim = string.trim`); the bare `gsub`
|
||||
// gets the table-replacement upgrade by being the same function.
|
||||
Game::Lua::RegisterGlobalAlias("gsub", "string", "gsub");
|
||||
Game::Lua::RegisterGlobalAlias("strmatch", "string", "match");
|
||||
Game::Lua::RegisterGlobalAlias("strsplit", "string", "split");
|
||||
Game::Lua::RegisterGlobalAlias("strjoin", "string", "join");
|
||||
Game::Lua::RegisterGlobalAlias("strtrim", "string", "trim");
|
||||
Game::Lua::RegisterGlobalAlias("strrev", "string", "reverse");
|
||||
Game::Lua::RegisterGlobalFunction("strreplace", &Script_strreplace);
|
||||
Game::Lua::RegisterGlobalFunction("strrev", &Script_string_reverse);
|
||||
}
|
||||
|
||||
// Both states are Lua 5.0 and equally missing these; RegisterTableFunction
|
||||
|
||||
+318
-491
@@ -12,391 +12,269 @@
|
||||
// You should have received a copy of the GNU General Public License along with
|
||||
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
// Backports the direct-action and override binding APIs introduced in 2.0.
|
||||
// Normal bindings are stored by vanilla's SetBinding implementation using the
|
||||
// later-client SPELL/ITEM/MACRO/CLICK command strings. The resolved-command
|
||||
// hook executes those four command families; every native binding command is
|
||||
// passed through unchanged.
|
||||
// The binding API 4.3.4 has and 1.12 lacks (decomp Ui/UIBindings.cpp,
|
||||
// UIBindings_Scripts.cpp):
|
||||
//
|
||||
// Override bindings live in a separate owner-scoped layer in front of the
|
||||
// native key lookup. They are deliberately never written to the saved binding
|
||||
// table, so clearing an owner immediately reveals the next override or the
|
||||
// unchanged native binding underneath it.
|
||||
// SetBindingSpell / Item / Macro / Click — "SPELL x" etc. into the
|
||||
// current set through the engine's own SetBinding.
|
||||
// SetOverrideBinding[Spell / Item / Macro / Click], ClearOverrideBindings
|
||||
// — owner-scoped bindings in front of the saved ones, never saved.
|
||||
// GetBindingAction(key [, checkOverride]) — sees overrides when asked.
|
||||
// GetBindingByKey(key) — what a press of the key runs.
|
||||
//
|
||||
// Overrides — 4.3.4's OVERRIDEKEYBINDING: per key (case-insensitive), two
|
||||
// lists (normal, priority) of {owner, command}; setting an owner's binding
|
||||
// unlinks its old one from both and links the new one at the head of its
|
||||
// priority's list, so the newest priority binding wins, then the newest
|
||||
// normal one. 4.3.4 consults them inside its key lookup, before the saved
|
||||
// binding, for every key it tries.
|
||||
//
|
||||
// Reduced keys — 4.3.4's GetReducedKeyBinding. 1.12's key dispatch
|
||||
// (FUN_BINDING_KEY_DISPATCH) tries only two keys: the pressed one, then the
|
||||
// pressed one minus its first modifier. 4.3.4 tries every subset of the
|
||||
// modifiers (ALT-SHIFT-Q: ALT-SHIFT-Q, SHIFT-Q, ALT-Q, Q). The co-hook walks
|
||||
// 4.3.4's list, tries an override, then the saved binding
|
||||
// (FUN_BINDINGS_GET_COMMAND_ACTION), for each key in turn — skipping one whose
|
||||
// command is unknown, as 4.3.4 does — and lets the engine run a saved binding
|
||||
// it finds.
|
||||
//
|
||||
// Around whatever runs, the key-state override (Input::Modifier) hides the
|
||||
// matched key's own modifiers, as 4.3.4's ExecKey does. Direct actions
|
||||
// (Bindings::Command) run only for a key: the command co-hook acts while the
|
||||
// manager's executing flag — set by the key dispatch, not by RunBinding — is
|
||||
// up, which is 4.3.4's ExecKey / ExecCommand split.
|
||||
|
||||
#include "Game.h"
|
||||
#include "Offsets.h"
|
||||
#include "macro/Execute.h"
|
||||
#include "bindings/Command.h"
|
||||
#include "input/Modifier.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <list>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace Bindings::Api {
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr const char kSpellPrefix[] = "SPELL ";
|
||||
constexpr const char kItemPrefix[] = "ITEM ";
|
||||
constexpr const char kMacroPrefix[] = "MACRO ";
|
||||
constexpr const char kClickPrefix[] = "CLICK ";
|
||||
constexpr const char kDefaultMouseButton[] = "LeftButton";
|
||||
using KeyDispatch_t = int(__fastcall *)(void *mgr, void *edx, const char *key, int isDown);
|
||||
using CommandExecute_t = int(__fastcall *)(void *mgr, void *edx, const char *cmd, int isDown);
|
||||
using GetCommandAction_t = const char *(__thiscall *)(void *mgr, const char *key);
|
||||
using ScriptFn_t = int(__fastcall *)(void *L);
|
||||
using ToBool_t = int(__fastcall *)(void *L, int idx, int dflt);
|
||||
|
||||
using ScriptSetBinding_t = int(__fastcall *)(void *L);
|
||||
using KeyDispatch_t = int(__thiscall *)(void *mgr, const char *key, int isDown);
|
||||
using CommandExecute_t = int(__thiscall *)(void *mgr, const char *cmd, int isDown);
|
||||
KeyDispatch_t g_keyDispatchOriginal = nullptr;
|
||||
CommandExecute_t g_commandExecuteOriginal = nullptr;
|
||||
|
||||
KeyDispatch_t KeyDispatch_o = nullptr;
|
||||
CommandExecute_t CommandExecute_o = nullptr;
|
||||
// --- override table (OVERRIDEKEYBINDING) ------------------------------------
|
||||
|
||||
enum class CommandType {
|
||||
None,
|
||||
Spell,
|
||||
Item,
|
||||
Macro,
|
||||
Click,
|
||||
};
|
||||
|
||||
struct ParsedCommand {
|
||||
CommandType type = CommandType::None;
|
||||
const char *argument = nullptr;
|
||||
};
|
||||
|
||||
struct OverrideEntry {
|
||||
const void *owner = nullptr;
|
||||
std::string key;
|
||||
struct Entry {
|
||||
const void *owner;
|
||||
std::string command;
|
||||
bool priority = false;
|
||||
uint64_t sequence = 0;
|
||||
};
|
||||
|
||||
std::vector<OverrideEntry> g_overrides;
|
||||
std::unordered_map<std::string, std::string> g_activeOverrides;
|
||||
uint64_t g_nextSequence = 0;
|
||||
struct OverrideKey {
|
||||
std::string key;
|
||||
std::list<Entry> lists[2]; // [0] normal, [1] priority; head = newest
|
||||
};
|
||||
|
||||
// Normalizes a binding key to the engine's own canonical form so a stored
|
||||
// override matches the string FUN_BINDING_KEY_DISPATCH builds at keypress. The
|
||||
// engine's key-string builder (FUN_004b6630) always emits modifiers in the
|
||||
// fixed order ALT-CTRL-SHIFT- ahead of the base key, regardless of the order
|
||||
// the caller passed them; vanilla SetBinding never reorders, so the override
|
||||
// layer does it here. Both the store and the lookup run through this, so they
|
||||
// stay consistent while also matching the engine's keypress form.
|
||||
std::string CanonicalKey(const char *key) {
|
||||
std::string result = key ? key : "";
|
||||
for (char &character : result) {
|
||||
if (character >= 'a' && character <= 'z')
|
||||
character = static_cast<char>(character - 'a' + 'A');
|
||||
}
|
||||
std::vector<OverrideKey> g_overrides;
|
||||
|
||||
// Strip the three modifier prefixes in whatever order/repetition they
|
||||
// appear, then re-emit them in the engine's fixed order. Prefix-stripping
|
||||
// (rather than splitting on '-') keeps the minus base key correct, e.g.
|
||||
// "SHIFT--" -> modifier SHIFT + base "-".
|
||||
bool alt = false, ctrl = false, shift = false;
|
||||
size_t base = 0;
|
||||
for (bool matched = true; matched;) {
|
||||
matched = false;
|
||||
if (result.compare(base, 4, "ALT-") == 0) {
|
||||
alt = true;
|
||||
base += 4;
|
||||
matched = true;
|
||||
} else if (result.compare(base, 5, "CTRL-") == 0) {
|
||||
ctrl = true;
|
||||
base += 5;
|
||||
matched = true;
|
||||
} else if (result.compare(base, 6, "SHIFT-") == 0) {
|
||||
shift = true;
|
||||
base += 6;
|
||||
matched = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!alt && !ctrl && !shift)
|
||||
return result;
|
||||
|
||||
std::string canonical;
|
||||
if (alt)
|
||||
canonical += "ALT-";
|
||||
if (ctrl)
|
||||
canonical += "CTRL-";
|
||||
if (shift)
|
||||
canonical += "SHIFT-";
|
||||
canonical += result.substr(base);
|
||||
|
||||
return canonical;
|
||||
OverrideKey *FindKey(const char *key) {
|
||||
for (OverrideKey &entry : g_overrides)
|
||||
if (_stricmp(entry.key.c_str(), key) == 0)
|
||||
return &entry;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
std::string MakeCommand(const char *prefix, const char *arg) {
|
||||
std::string cmd = prefix;
|
||||
cmd += arg;
|
||||
return cmd;
|
||||
// OVERRIDEKEYBINDING::SetOverrideBinding.
|
||||
void SetOverride(OverrideKey &binding, const void *owner, bool priority, const char *command) {
|
||||
for (auto &list : binding.lists)
|
||||
list.remove_if([owner](const Entry &entry) { return entry.owner == owner; });
|
||||
if (command != nullptr && *command != '\0')
|
||||
binding.lists[priority ? 1 : 0].push_front(Entry{owner, command});
|
||||
}
|
||||
|
||||
std::string MakeClickCommand(const char *btnName, const char *mouseBtn) {
|
||||
std::string cmd = MakeCommand(kClickPrefix, btnName);
|
||||
if (mouseBtn != nullptr) {
|
||||
cmd += ':';
|
||||
cmd += mouseBtn;
|
||||
// OVERRIDEKEYBINDING::GetActiveBinding.
|
||||
const char *ActiveOverride(const char *key) {
|
||||
const OverrideKey *binding = FindKey(key);
|
||||
if (binding == nullptr)
|
||||
return nullptr;
|
||||
for (int i = 1; i >= 0; --i)
|
||||
if (!binding->lists[i].empty())
|
||||
return binding->lists[i].front().command.c_str();
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// CGUIBindings::SetOverrideBinding.
|
||||
void SetOverrideBinding(const void *owner, bool priority, const char *key, const char *command) {
|
||||
OverrideKey *binding = FindKey(key);
|
||||
if (binding == nullptr) {
|
||||
g_overrides.push_back(OverrideKey{key, {}});
|
||||
binding = &g_overrides.back();
|
||||
}
|
||||
|
||||
return cmd;
|
||||
SetOverride(*binding, owner, priority, command);
|
||||
}
|
||||
|
||||
ParsedCommand ParseCommand(const char *cmd) {
|
||||
if (cmd == nullptr)
|
||||
// --- key dispatch -------------------------------------------------------------
|
||||
|
||||
void *Manager() { return Game::Read<void *>(Offsets::VAR_BINDINGS_MANAGER); }
|
||||
|
||||
const char *SavedCommand(void *mgr, const char *key) {
|
||||
return reinterpret_cast<GetCommandAction_t>(Offsets::FUN_BINDINGS_GET_COMMAND_ACTION)(mgr,
|
||||
key);
|
||||
}
|
||||
|
||||
// Whether the command table has `command` — the walk the engine inlines in
|
||||
// FUN_BINDING_COMMAND_EXECUTE (see OFF_BINDINGS_COMMAND_TABLE).
|
||||
bool IsKnownCommand(void *mgr, const char *command) {
|
||||
using HashHT_t = uint32_t(__stdcall *)(const char *);
|
||||
using CmpI_t = int(__stdcall *)(const char *, const char *, int);
|
||||
const uintptr_t table = reinterpret_cast<uintptr_t>(mgr) + Offsets::OFF_BINDINGS_COMMAND_TABLE;
|
||||
const uint32_t mask = Game::Read<uint32_t>(table + Offsets::OFF_HASHTABLE_MASK);
|
||||
if (*command == '\0' || mask == 0xFFFFFFFF)
|
||||
return false;
|
||||
const uint32_t hash = reinterpret_cast<HashHT_t>(Offsets::FUN_SSTR_HASH_HT)(command);
|
||||
const uintptr_t bucket =
|
||||
Game::Read<uintptr_t>(table + Offsets::OFF_HASHTABLE_SLOTS) + (hash & mask) * 12;
|
||||
const uint32_t link = Game::Read<uint32_t>(bucket);
|
||||
for (uintptr_t node = Game::Read<uintptr_t>(bucket + 8); node != 0 && (node & 1) == 0;
|
||||
node = Game::Read<uintptr_t>(node + link + 4)) {
|
||||
if (Game::Read<uint32_t>(node) == hash &&
|
||||
reinterpret_cast<CmpI_t>(Offsets::FUN_SSTR_CMP_I)(
|
||||
Game::Read<const char *>(node + Offsets::OFF_HASHTABLE_NODE_NAME), command,
|
||||
0x7FFFFFFF) == 0)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// CGUIBindings::GetKeyBinding: the key's active override, else its saved
|
||||
// binding — and none when that command is neither a direct action nor a known
|
||||
// command (a saved one is never checked when set). 4.3.4's retry under the
|
||||
// generic modifier names (LSHIFT- → SHIFT-) is left out: 1.12 builds chords
|
||||
// from ALT-, CTRL- and SHIFT- only, so a pressed key is already generic.
|
||||
struct KeyBinding {
|
||||
const char *command = nullptr;
|
||||
bool isOverride = false;
|
||||
};
|
||||
|
||||
KeyBinding FindKeyBinding(void *mgr, const char *key) {
|
||||
KeyBinding binding{ActiveOverride(key), true};
|
||||
if (binding.command == nullptr)
|
||||
binding = {SavedCommand(mgr, key), false};
|
||||
if (binding.command == nullptr ||
|
||||
!(Command::IsDirectAction(binding.command) || IsKnownCommand(mgr, binding.command)))
|
||||
return {};
|
||||
return binding;
|
||||
}
|
||||
|
||||
struct PrefixEntry {
|
||||
const char *prefix;
|
||||
size_t length;
|
||||
CommandType type;
|
||||
};
|
||||
|
||||
static constexpr PrefixEntry prefixes[] = {
|
||||
{kSpellPrefix, sizeof(kSpellPrefix) - 1, CommandType::Spell},
|
||||
{kItemPrefix, sizeof(kItemPrefix) - 1, CommandType::Item},
|
||||
{kMacroPrefix, sizeof(kMacroPrefix) - 1, CommandType::Macro},
|
||||
{kClickPrefix, sizeof(kClickPrefix) - 1, CommandType::Click},
|
||||
};
|
||||
|
||||
for (const PrefixEntry &entry : prefixes) {
|
||||
if (std::strncmp(cmd, entry.prefix, entry.length) == 0)
|
||||
return {entry.type, cmd + entry.length};
|
||||
// CGUIBindings::GetReducedKeyBinding: up to three leading modifiers split off
|
||||
// at '-', then the key with each subset of them in 4.3.4's fixed order (bit j
|
||||
// keeps modifier j) — ALT-SHIFT-Q tries ALT-SHIFT-Q, SHIFT-Q, ALT-Q, Q. The
|
||||
// first reduced key with a binding wins and is left in `reduced`.
|
||||
KeyBinding FindReducedKeyBinding(void *mgr, const char *key, std::string &reduced) {
|
||||
std::string modifiers[3];
|
||||
size_t count = 0;
|
||||
const char *rest = key;
|
||||
while (count < 3) {
|
||||
const char *separator = std::strchr(rest, '-');
|
||||
if (separator == nullptr || separator == rest)
|
||||
break;
|
||||
modifiers[count++].assign(rest, separator - rest + 1);
|
||||
rest = separator + 1;
|
||||
}
|
||||
|
||||
static constexpr uint8_t kCombinations[4][9] = {
|
||||
{1, 0},
|
||||
{2, 1, 0},
|
||||
{4, 3, 2, 1, 0},
|
||||
{8, 7, 6, 5, 3, 4, 2, 1, 0},
|
||||
};
|
||||
for (uint8_t i = 0; i < kCombinations[count][0]; ++i) {
|
||||
reduced.clear();
|
||||
for (size_t j = 0; j < count; ++j)
|
||||
if ((1u << j) & kCombinations[count][i + 1])
|
||||
reduced += modifiers[j];
|
||||
reduced += rest;
|
||||
const KeyBinding binding = FindKeyBinding(mgr, reduced.c_str());
|
||||
if (binding.command != nullptr)
|
||||
return binding;
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
bool CallGlobalString(void *L, const char *func, const char *arg) {
|
||||
const int top = Game::Lua::GetTop(L);
|
||||
if (!Game::Lua::PushGlobalFunction(L, func)) {
|
||||
Game::Lua::SetTop(L, top);
|
||||
return false;
|
||||
}
|
||||
|
||||
Game::Lua::PushString(L, arg);
|
||||
const bool ok = Game::Lua::PCall(L, 1, 0, 0) == 0;
|
||||
Game::Lua::SetTop(L, top);
|
||||
|
||||
return ok;
|
||||
int ExecuteCommand(void *mgr, const char *command, int isDown) {
|
||||
if (Command::IsDirectAction(command))
|
||||
return Command::RunKey(command, isDown);
|
||||
return g_commandExecuteOriginal(mgr, nullptr, command, isDown);
|
||||
}
|
||||
|
||||
bool CallTableString(void *L, const char *table, const char *func, const char *arg) {
|
||||
const int top = Game::Lua::GetTop(L);
|
||||
|
||||
Game::Lua::PushString(L, table);
|
||||
Game::Lua::GetTable(L, Game::Lua::GLOBALS_INDEX);
|
||||
if (Game::Lua::Type(L, -1) != Game::Lua::TYPE_TABLE) {
|
||||
Game::Lua::SetTop(L, top);
|
||||
return false;
|
||||
}
|
||||
|
||||
const int tableIndex = Game::Lua::GetTop(L);
|
||||
|
||||
Game::Lua::PushString(L, func);
|
||||
Game::Lua::GetTable(L, tableIndex);
|
||||
if (Game::Lua::Type(L, -1) != Game::Lua::TYPE_FUNCTION) {
|
||||
Game::Lua::SetTop(L, top);
|
||||
return false;
|
||||
}
|
||||
|
||||
Game::Lua::PushString(L, arg);
|
||||
const bool ok = Game::Lua::PCall(L, 1, 0, 0) == 0;
|
||||
Game::Lua::SetTop(L, top);
|
||||
|
||||
return ok;
|
||||
}
|
||||
|
||||
void InvokeButtonClick(void *L, const char *btnName, size_t btnNameLength, const char *mouseBtn) {
|
||||
const int top = Game::Lua::GetTop(L);
|
||||
|
||||
Game::Lua::PushLString(L, btnName, static_cast<unsigned int>(btnNameLength));
|
||||
Game::Lua::GetTable(L, Game::Lua::GLOBALS_INDEX);
|
||||
if (Game::Lua::Type(L, -1) != Game::Lua::TYPE_TABLE) {
|
||||
Game::Lua::SetTop(L, top);
|
||||
return;
|
||||
}
|
||||
|
||||
const int frameIndex = Game::Lua::GetTop(L);
|
||||
Game::Lua::PushString(L, "Click");
|
||||
Game::Lua::GetTable(L, frameIndex);
|
||||
if (Game::Lua::Type(L, -1) == Game::Lua::TYPE_FUNCTION) {
|
||||
Game::Lua::PushValue(L, frameIndex);
|
||||
Game::Lua::PushString(L, mouseBtn);
|
||||
Game::Lua::PCall(L, 2, 0, 0);
|
||||
}
|
||||
|
||||
Game::Lua::SetTop(L, top);
|
||||
}
|
||||
|
||||
void ExecuteClick(void *L, const char *arg) {
|
||||
const char *separator = std::strrchr(arg, ':');
|
||||
if (separator == arg || (separator != nullptr && separator[1] == '\0'))
|
||||
return;
|
||||
|
||||
const char *mouseBtn = kDefaultMouseButton;
|
||||
size_t btnNameLength = std::strlen(arg);
|
||||
if (separator != nullptr) {
|
||||
btnNameLength = static_cast<size_t>(separator - arg);
|
||||
mouseBtn = separator + 1;
|
||||
}
|
||||
|
||||
if (btnNameLength == 0)
|
||||
return;
|
||||
|
||||
InvokeButtonClick(L, arg, btnNameLength, mouseBtn);
|
||||
}
|
||||
|
||||
// Returns true for every recognized direct-action command, including malformed
|
||||
// or stale commands. Vanilla cannot execute these namespaces, so a bad command
|
||||
// is consumed as a no-op instead of falling through to an unrelated handler.
|
||||
bool ExecuteSpecialCommand(const char *cmd, int isDown) {
|
||||
const ParsedCommand parsed = ParseCommand(cmd);
|
||||
if (parsed.type == CommandType::None)
|
||||
return false;
|
||||
|
||||
if (!isDown || parsed.argument == nullptr || *parsed.argument == '\0')
|
||||
return true;
|
||||
|
||||
void *L = Game::Lua::State();
|
||||
if (L == nullptr)
|
||||
return true;
|
||||
|
||||
switch (parsed.type) {
|
||||
case CommandType::Spell:
|
||||
CallGlobalString(L, "CastSpellByName", parsed.argument);
|
||||
break;
|
||||
case CommandType::Item:
|
||||
CallTableString(L, "C_Item", "UseItemByName", parsed.argument);
|
||||
break;
|
||||
case CommandType::Macro:
|
||||
Macro::Execute::Saved(L, parsed.argument);
|
||||
break;
|
||||
case CommandType::Click:
|
||||
ExecuteClick(L, parsed.argument);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
const OverrideEntry *FindEffectiveOverride(const std::string &key) {
|
||||
const OverrideEntry *best = nullptr;
|
||||
for (const OverrideEntry &entry : g_overrides) {
|
||||
if (entry.key != key)
|
||||
continue;
|
||||
|
||||
if (best == nullptr || entry.priority > best->priority ||
|
||||
(entry.priority == best->priority && entry.sequence > best->sequence))
|
||||
best = &entry;
|
||||
}
|
||||
|
||||
return best;
|
||||
}
|
||||
|
||||
void SetOverride(const void *owner, bool priority, const std::string &key, const std::string &cmd) {
|
||||
auto existing =
|
||||
std::find_if(g_overrides.begin(), g_overrides.end(),
|
||||
[&](const OverrideEntry &entry) {
|
||||
return entry.owner == owner && entry.key == key;
|
||||
});
|
||||
|
||||
if (existing == g_overrides.end()) {
|
||||
g_overrides.push_back(
|
||||
{owner, key, cmd, priority, ++g_nextSequence});
|
||||
return;
|
||||
}
|
||||
|
||||
existing->command = cmd;
|
||||
existing->priority = priority;
|
||||
existing->sequence = ++g_nextSequence;
|
||||
}
|
||||
|
||||
void RemoveOverride(const void *owner, const std::string &key) {
|
||||
g_overrides.erase(std::remove_if(g_overrides.begin(), g_overrides.end(),
|
||||
[&](const OverrideEntry &entry) {
|
||||
return entry.owner == owner &&
|
||||
entry.key == key;
|
||||
}),
|
||||
g_overrides.end());
|
||||
}
|
||||
|
||||
int ExecuteCommand(void *mgr, const char *cmd, int isDown) {
|
||||
if (ExecuteSpecialCommand(cmd, isDown))
|
||||
return 1;
|
||||
|
||||
return CommandExecute_o(mgr, cmd, isDown);
|
||||
}
|
||||
|
||||
int __fastcall CommandExecute_h(void *mgr, void *, const char *cmd, int isDown) {
|
||||
return ExecuteCommand(mgr, cmd, isDown);
|
||||
}
|
||||
|
||||
// Runs an override-resolved command with the same execution context the engine
|
||||
// wraps around a native keypress. FUN_BINDING_KEY_DISPATCH saves the frame-
|
||||
// script exec-context, zeroes it for the nested command, marks the manager as
|
||||
// mid-command (`+0xD8`), then restores the context and floors the nesting
|
||||
// depth. Native-table bindings already run inside this (the engine sets it up
|
||||
// before calling FUN_BINDING_COMMAND_EXECUTE, which we co-hook); overrides
|
||||
// bypass that path, so we mirror it here. Without it, a native Bindings.xml
|
||||
// command dispatched through an override would run without the context its
|
||||
// handler expects. Special SPELL/ITEM/MACRO/CLICK commands run harmlessly
|
||||
// inside the same wrapper.
|
||||
int DispatchOverrideCommand(void *mgr, const char *cmd, int isDown) {
|
||||
volatile uint32_t *context =
|
||||
reinterpret_cast<volatile uint32_t *>(Offsets::VAR_FRAMESCRIPT_EXEC_CONTEXT);
|
||||
volatile uint32_t *depth = reinterpret_cast<volatile uint32_t *>(
|
||||
Offsets::VAR_FRAMESCRIPT_EXEC_CONTEXT_DEPTH);
|
||||
volatile uint32_t *executing =
|
||||
Game::Ptr<volatile uint32_t>(mgr, Offsets::OFF_BINDING_MANAGER_EXECUTING);
|
||||
|
||||
const uint32_t savedContext = *context;
|
||||
*depth = *depth + 1;
|
||||
if (*depth != 0)
|
||||
*context = 0;
|
||||
|
||||
*executing = 1;
|
||||
const int result = ExecuteCommand(mgr, cmd, isDown);
|
||||
*executing = 0;
|
||||
|
||||
if (*depth != 0)
|
||||
*context = savedContext;
|
||||
if (static_cast<int32_t>(*depth) - 1 > 0)
|
||||
*depth = *depth - 1;
|
||||
else
|
||||
*depth = 0;
|
||||
|
||||
// An override's command, run in the frame the engine dispatch gives a saved
|
||||
// one: exec context saved and cleared, depth bumped, the manager's executing
|
||||
// flag up (FUN_BINDING_KEY_DISPATCH, see Offsets.h).
|
||||
int RunOverride(void *mgr, const char *command, int isDown) {
|
||||
const std::string copy = command; // the command may clear its own override
|
||||
auto &context = Game::Ref<uint32_t>(Offsets::VAR_FRAMESCRIPT_EXEC_CONTEXT);
|
||||
auto &depth = Game::Ref<int32_t>(Offsets::VAR_FRAMESCRIPT_EXEC_CONTEXT_DEPTH);
|
||||
auto &executing = Game::Ref<uint32_t>(mgr, Offsets::OFF_BINDING_MANAGER_EXECUTING);
|
||||
const uint32_t saved = context;
|
||||
if (++depth != 0)
|
||||
context = 0;
|
||||
executing = 1;
|
||||
const int result = ExecuteCommand(mgr, copy.c_str(), isDown);
|
||||
executing = 0;
|
||||
if (depth != 0)
|
||||
context = saved;
|
||||
depth = depth - 1 > 0 ? depth - 1 : 0;
|
||||
return result;
|
||||
}
|
||||
|
||||
int __fastcall KeyDispatch_h(void *mgr, void *, const char *key, int isDown) {
|
||||
const std::string canonicalKey = CanonicalKey(key);
|
||||
// CGUIBindings::ExecKey. A saved binding is run by the engine, handed the
|
||||
// reduced key: it uses the key only for its table lookup, and finds it as the
|
||||
// first of its own two. No binding runs nothing, as in 4.3.4.
|
||||
int __fastcall KeyDispatch_h(void *mgr, void *edx, const char *key, int isDown) {
|
||||
if (key == nullptr || *key == '\0')
|
||||
return g_keyDispatchOriginal(mgr, edx, key, isDown);
|
||||
|
||||
// Keep a key-down paired with its override command even if that override is
|
||||
// cleared while the command executes. The newly revealed native binding
|
||||
// must not receive only the key-up half of the same physical press.
|
||||
if (!isDown) {
|
||||
auto active = g_activeOverrides.find(canonicalKey);
|
||||
if (active != g_activeOverrides.end()) {
|
||||
DispatchOverrideCommand(mgr, active->second.c_str(), 0);
|
||||
g_activeOverrides.erase(active);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
std::string reduced;
|
||||
const KeyBinding binding = FindReducedKeyBinding(mgr, key, reduced);
|
||||
if (binding.command == nullptr)
|
||||
return 0;
|
||||
const Input::Modifier::KeyStateOverride keyState(reduced.c_str());
|
||||
if (binding.isOverride)
|
||||
return RunOverride(mgr, binding.command, isDown);
|
||||
return g_keyDispatchOriginal(mgr, edx, reduced.c_str(), isDown);
|
||||
}
|
||||
|
||||
const OverrideEntry *entry = FindEffectiveOverride(canonicalKey);
|
||||
if (entry == nullptr)
|
||||
return KeyDispatch_o(mgr, key, isDown);
|
||||
// Direct actions only for a key (executing flag up); RunBinding reaches the
|
||||
// engine's command table, which has none of them — as in 4.3.4.
|
||||
int __fastcall CommandExecute_h(void *mgr, void *edx, const char *command, int isDown) {
|
||||
if (Game::Read<uint32_t>(mgr, Offsets::OFF_BINDING_MANAGER_EXECUTING) != 0 &&
|
||||
Command::IsDirectAction(command))
|
||||
return Command::RunKey(command, isDown);
|
||||
return g_commandExecuteOriginal(mgr, edx, command, isDown);
|
||||
}
|
||||
|
||||
if (isDown)
|
||||
g_activeOverrides[canonicalKey] = entry->command;
|
||||
// --- Lua ----------------------------------------------------------------------
|
||||
|
||||
return DispatchOverrideCommand(mgr, entry->command.c_str(), isDown);
|
||||
bool LooseBool(void *L, int idx) {
|
||||
return reinterpret_cast<ToBool_t>(Offsets::FUN_LUA_TO_BOOLEAN_LOOSE)(L, idx, 0) != 0;
|
||||
}
|
||||
|
||||
const char *OptString(void *L, int idx) {
|
||||
return Game::Lua::IsString(L, idx) ? Game::Lua::ToString(L, idx) : nullptr;
|
||||
}
|
||||
|
||||
// SetBinding(key, command) through the engine's own Script_SetBinding: its
|
||||
// key normalization, current-set write, UPDATE_BINDINGS and 1/nil result.
|
||||
int SetBinding(void *L, const std::string &key, const std::string &command) {
|
||||
Game::Lua::SetTop(L, 0);
|
||||
Game::Lua::PushString(L, key.c_str());
|
||||
Game::Lua::PushString(L, command.c_str());
|
||||
return reinterpret_cast<ScriptFn_t>(Offsets::FUN_SCRIPT_SET_BINDING)(L);
|
||||
}
|
||||
|
||||
int SetBindingCommand(void *L, const char *prefix, const char *usage) {
|
||||
@@ -404,216 +282,165 @@ int SetBindingCommand(void *L, const char *prefix, const char *usage) {
|
||||
Game::Lua::Error(L, usage);
|
||||
return 0;
|
||||
}
|
||||
|
||||
const std::string key = Game::Lua::ToString(L, 1);
|
||||
const std::string command = MakeCommand(prefix, Game::Lua::ToString(L, 2));
|
||||
|
||||
// Preserve the stock SetBinding return value, binding-set selection,
|
||||
// key normalization, UPDATE_BINDINGS event, and SaveBindings behavior.
|
||||
Game::Lua::SetTop(L, 0);
|
||||
Game::Lua::PushString(L, key.c_str());
|
||||
Game::Lua::PushString(L, command.c_str());
|
||||
auto setBinding =
|
||||
reinterpret_cast<ScriptSetBinding_t>(Offsets::FUN_SCRIPT_SET_BINDING);
|
||||
|
||||
return setBinding(L);
|
||||
}
|
||||
|
||||
const char *OptionalMouseButton(void *L, int index, const char *usage) {
|
||||
if (Game::Lua::GetTop(L) < index || Game::Lua::Type(L, index) == Game::Lua::TYPE_NIL)
|
||||
return nullptr;
|
||||
|
||||
if (!Game::Lua::IsString(L, index)) {
|
||||
Game::Lua::Error(L, usage);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
return Game::Lua::ToString(L, index);
|
||||
return SetBinding(L, Game::Lua::ToString(L, 1),
|
||||
std::string(prefix) + Game::Lua::ToString(L, 2));
|
||||
}
|
||||
|
||||
int __fastcall Script_SetBindingSpell(void *L) {
|
||||
return SetBindingCommand(L, kSpellPrefix, "Usage: SetBindingSpell(key, spell)");
|
||||
return SetBindingCommand(L, "SPELL ", "Usage: SetBindingSpell(\"KEY\", \"spellname\")");
|
||||
}
|
||||
|
||||
int __fastcall Script_SetBindingItem(void *L) {
|
||||
return SetBindingCommand(L, kItemPrefix, "Usage: SetBindingItem(key, item)");
|
||||
return SetBindingCommand(L, "ITEM ", "Usage: SetBindingItem(\"KEY\", \"itemname\")");
|
||||
}
|
||||
int __fastcall Script_SetBindingMacro(void *L) {
|
||||
return SetBindingCommand(L, "MACRO ",
|
||||
"Usage: SetBindingMacro(\"KEY\", \"macroname\"|macroid)");
|
||||
}
|
||||
|
||||
int __fastcall Script_SetBindingMacro(void *L) {
|
||||
return SetBindingCommand(L, kMacroPrefix, "Usage: SetBindingMacro(key, macro)");
|
||||
std::string ClickCommand(const char *button, const char *mouseButton) {
|
||||
return std::string("CLICK ") + button + ":" +
|
||||
(mouseButton != nullptr ? mouseButton : "LeftButton");
|
||||
}
|
||||
|
||||
int __fastcall Script_SetBindingClick(void *L) {
|
||||
constexpr const char *usage = "Usage: SetBindingClick(key, buttonName [, mouseButton])";
|
||||
if (!Game::Lua::IsString(L, 1) || !Game::Lua::IsString(L, 2)) {
|
||||
Game::Lua::Error(L, usage);
|
||||
Game::Lua::Error(
|
||||
L, "Usage: SetBindingClick(\"KEY\", \"buttonName\"[, \"mouseButton\"])");
|
||||
return 0;
|
||||
}
|
||||
|
||||
const std::string key = Game::Lua::ToString(L, 1);
|
||||
const char *buttonName = Game::Lua::ToString(L, 2);
|
||||
const char *mouseButton = OptionalMouseButton(L, 3, usage);
|
||||
const std::string command = MakeClickCommand(buttonName, mouseButton);
|
||||
|
||||
Game::Lua::SetTop(L, 0);
|
||||
Game::Lua::PushString(L, key.c_str());
|
||||
Game::Lua::PushString(L, command.c_str());
|
||||
auto setBinding =
|
||||
reinterpret_cast<ScriptSetBinding_t>(Offsets::FUN_SCRIPT_SET_BINDING);
|
||||
|
||||
return setBinding(L);
|
||||
return SetBinding(L, Game::Lua::ToString(L, 1),
|
||||
ClickCommand(Game::Lua::ToString(L, 2), OptString(L, 3)));
|
||||
}
|
||||
|
||||
bool ReadOverrideHeader(void *L, const char *usage, const void **owner,
|
||||
bool *priority, std::string *key) {
|
||||
*owner = Game::Lua::ResolveObject(L, 1);
|
||||
if (*owner == nullptr || Game::Lua::Type(L, 2) != Game::Lua::TYPE_BOOLEAN ||
|
||||
!Game::Lua::IsString(L, 3)) {
|
||||
Game::Lua::Error(L, usage);
|
||||
return false;
|
||||
}
|
||||
// The owner argument: a frame, as 4.3.4 requires.
|
||||
const void *Owner(void *L) { return Game::Lua::ResolveFrame(L, 1, /*raiseError*/ false); }
|
||||
|
||||
*priority = Game::Lua::ToBoolean(L, 2) != 0;
|
||||
*key = CanonicalKey(Game::Lua::ToString(L, 3));
|
||||
return true;
|
||||
}
|
||||
|
||||
int SetOverrideBindingCommand(void *L, const char *prefix, const char *usage) {
|
||||
const void *owner = nullptr;
|
||||
bool priority = false;
|
||||
|
||||
std::string key;
|
||||
if (!ReadOverrideHeader(L, usage, &owner, &priority, &key))
|
||||
return 0;
|
||||
|
||||
if (!Game::Lua::IsString(L, 4)) {
|
||||
Game::Lua::Error(L, usage);
|
||||
int __fastcall Script_SetOverrideBinding(void *L) {
|
||||
const void *owner = Owner(L);
|
||||
if (owner == nullptr || !Game::Lua::IsString(L, 3)) {
|
||||
Game::Lua::Error(L, "Usage: SetOverrideBinding(owner, isPriority, \"KEY\"[, \"COMMAND\"])");
|
||||
return 0;
|
||||
}
|
||||
|
||||
SetOverride(owner, priority, key,
|
||||
MakeCommand(prefix, Game::Lua::ToString(L, 4)));
|
||||
|
||||
SetOverrideBinding(owner, LooseBool(L, 2), Game::Lua::ToString(L, 3), OptString(L, 4));
|
||||
return 0;
|
||||
}
|
||||
|
||||
int __fastcall Script_SetOverrideBinding(void *L) {
|
||||
constexpr const char *usage = "Usage: SetOverrideBinding(owner, isPriority, key [, command])";
|
||||
const void *owner = nullptr;
|
||||
bool priority = false;
|
||||
|
||||
std::string key;
|
||||
if (!ReadOverrideHeader(L, usage, &owner, &priority, &key))
|
||||
return 0;
|
||||
|
||||
if (Game::Lua::GetTop(L) < 4 ||
|
||||
Game::Lua::Type(L, 4) == Game::Lua::TYPE_NIL) {
|
||||
RemoveOverride(owner, key);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (!Game::Lua::IsString(L, 4)) {
|
||||
int SetOverrideCommand(void *L, const char *prefix, const char *usage) {
|
||||
const void *owner = Owner(L);
|
||||
if (owner == nullptr || !Game::Lua::IsString(L, 3) || !Game::Lua::IsString(L, 4)) {
|
||||
Game::Lua::Error(L, usage);
|
||||
return 0;
|
||||
}
|
||||
|
||||
SetOverride(owner, priority, key, Game::Lua::ToString(L, 4));
|
||||
const std::string command = std::string(prefix) + Game::Lua::ToString(L, 4);
|
||||
SetOverrideBinding(owner, LooseBool(L, 2), Game::Lua::ToString(L, 3), command.c_str());
|
||||
return 0;
|
||||
}
|
||||
|
||||
int __fastcall Script_SetOverrideBindingSpell(void *L) {
|
||||
return SetOverrideBindingCommand(
|
||||
L, kSpellPrefix,
|
||||
"Usage: SetOverrideBindingSpell(owner, isPriority, key, spell)");
|
||||
return SetOverrideCommand(
|
||||
L, "SPELL ", "Usage: SetOverrideBindingSpell(owner, isPriority, \"KEY\", \"spellname\")");
|
||||
}
|
||||
|
||||
int __fastcall Script_SetOverrideBindingItem(void *L) {
|
||||
return SetOverrideBindingCommand(
|
||||
L, kItemPrefix,
|
||||
"Usage: SetOverrideBindingItem(owner, isPriority, key, item)");
|
||||
return SetOverrideCommand(
|
||||
L, "ITEM ", "Usage: SetOverrideBindingItem(owner, isPriority, \"KEY\", \"itemname\")");
|
||||
}
|
||||
|
||||
int __fastcall Script_SetOverrideBindingMacro(void *L) {
|
||||
return SetOverrideBindingCommand(
|
||||
L, kMacroPrefix,
|
||||
"Usage: SetOverrideBindingMacro(owner, isPriority, key, macro)");
|
||||
return SetOverrideCommand(
|
||||
L, "MACRO ",
|
||||
"Usage: SetOverrideBindingMacro(owner, isPriority, \"KEY\", \"macroname\"|macroid)");
|
||||
}
|
||||
|
||||
int __fastcall Script_SetOverrideBindingClick(void *L) {
|
||||
constexpr const char *usage =
|
||||
"Usage: SetOverrideBindingClick(owner, "
|
||||
"isPriority, key, buttonName [, mouseButton])";
|
||||
|
||||
const void *owner = nullptr;
|
||||
bool priority = false;
|
||||
|
||||
std::string key;
|
||||
if (!ReadOverrideHeader(L, usage, &owner, &priority, &key))
|
||||
return 0;
|
||||
|
||||
if (!Game::Lua::IsString(L, 4)) {
|
||||
Game::Lua::Error(L, usage);
|
||||
const void *owner = Owner(L);
|
||||
if (owner == nullptr || !Game::Lua::IsString(L, 3) || !Game::Lua::IsString(L, 4)) {
|
||||
Game::Lua::Error(L, "Usage: SetOverrideBindingClick(owner, isPriority, \"KEY\", "
|
||||
"\"buttonName\"[, \"mouseButton\"])");
|
||||
return 0;
|
||||
}
|
||||
|
||||
const char *buttonName = Game::Lua::ToString(L, 4);
|
||||
const char *mouseButton = OptionalMouseButton(L, 5, usage);
|
||||
SetOverride(owner, priority, key,
|
||||
MakeClickCommand(buttonName, mouseButton));
|
||||
|
||||
const std::string command = ClickCommand(Game::Lua::ToString(L, 4), OptString(L, 5));
|
||||
SetOverrideBinding(owner, LooseBool(L, 2), Game::Lua::ToString(L, 3), command.c_str());
|
||||
return 0;
|
||||
}
|
||||
|
||||
int __fastcall Script_ClearOverrideBindings(void *L) {
|
||||
const void *owner = Game::Lua::ResolveObject(L, 1);
|
||||
const void *owner = Owner(L);
|
||||
if (owner == nullptr) {
|
||||
Game::Lua::Error(L, "Usage: ClearOverrideBindings(owner)");
|
||||
return 0;
|
||||
}
|
||||
|
||||
g_overrides.erase(std::remove_if(g_overrides.begin(), g_overrides.end(),
|
||||
[&](const OverrideEntry &entry) {
|
||||
return entry.owner == owner;
|
||||
}),
|
||||
g_overrides.end());
|
||||
for (OverrideKey &binding : g_overrides)
|
||||
SetOverride(binding, owner, false, nullptr);
|
||||
return 0;
|
||||
}
|
||||
|
||||
void RegisterLuaFunctions() {
|
||||
// A fresh FrameScript state makes every owner pointer from the previous
|
||||
// state stale. Permanent bindings remain in vanilla's binding table.
|
||||
g_overrides.clear();
|
||||
g_activeOverrides.clear();
|
||||
g_nextSequence = 0;
|
||||
// GetBindingAction(key [, checkOverride]): 4.3.4's GetCommandAction checks the
|
||||
// override first when asked; the saved binding is the engine's own answer.
|
||||
int __fastcall Script_GetBindingAction(void *L) {
|
||||
if (Game::Lua::IsString(L, 1) && LooseBool(L, 2)) {
|
||||
if (const char *command = ActiveOverride(Game::Lua::ToString(L, 1))) {
|
||||
Game::Lua::PushString(L, command);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
return reinterpret_cast<ScriptFn_t>(Offsets::FUN_SCRIPT_GET_BINDING_ACTION)(L);
|
||||
}
|
||||
|
||||
// GetBindingByKey(key): the command a press of `key` runs — the reduced-key
|
||||
// lookup ExecKey makes, overrides included.
|
||||
int __fastcall Script_GetBindingByKey(void *L) {
|
||||
if (!Game::Lua::IsString(L, 1)) {
|
||||
Game::Lua::Error(L, "Usage: GetBindingByKey(\"action\"[, mode])");
|
||||
return 0;
|
||||
}
|
||||
std::string reduced;
|
||||
const KeyBinding binding = FindReducedKeyBinding(Manager(), Game::Lua::ToString(L, 1), reduced);
|
||||
if (binding.command == nullptr)
|
||||
return 0;
|
||||
Game::Lua::PushString(L, binding.command);
|
||||
return 1;
|
||||
}
|
||||
|
||||
const Game::Doc::Field kGetBindingByKeyArgs[] = {
|
||||
Game::Doc::Req("key", "string", "A key with its modifiers, such as \"ALT-SHIFT-Q\"."),
|
||||
};
|
||||
const Game::Doc::Field kGetBindingByKeyRets[] = {
|
||||
Game::Doc::Opt("command", "string", nullptr,
|
||||
"The command a press of the key runs, else nil. When the key itself has no "
|
||||
"binding, the key with fewer modifiers is tried."),
|
||||
};
|
||||
const Game::Doc::Function kGetBindingByKey{"Returns the command that a key press runs.",
|
||||
kGetBindingByKeyArgs, kGetBindingByKeyRets,
|
||||
"BindingsGlobals"};
|
||||
|
||||
void RegisterLuaFunctions() {
|
||||
Game::Lua::RegisterGlobalFunction("GetBindingByKey", &Script_GetBindingByKey,
|
||||
&kGetBindingByKey);
|
||||
Game::Lua::RegisterGlobalFunction("SetBindingSpell", &Script_SetBindingSpell);
|
||||
Game::Lua::RegisterGlobalFunction("SetBindingItem", &Script_SetBindingItem);
|
||||
Game::Lua::RegisterGlobalFunction("SetBindingMacro", &Script_SetBindingMacro);
|
||||
Game::Lua::RegisterGlobalFunction("SetBindingClick", &Script_SetBindingClick);
|
||||
Game::Lua::RegisterGlobalFunction("SetOverrideBinding",
|
||||
&Script_SetOverrideBinding);
|
||||
Game::Lua::RegisterGlobalFunction("SetOverrideBindingSpell",
|
||||
&Script_SetOverrideBindingSpell);
|
||||
Game::Lua::RegisterGlobalFunction("SetOverrideBindingItem",
|
||||
&Script_SetOverrideBindingItem);
|
||||
Game::Lua::RegisterGlobalFunction("SetOverrideBindingMacro",
|
||||
&Script_SetOverrideBindingMacro);
|
||||
Game::Lua::RegisterGlobalFunction("SetOverrideBindingClick",
|
||||
&Script_SetOverrideBindingClick);
|
||||
Game::Lua::RegisterGlobalFunction("ClearOverrideBindings",
|
||||
&Script_ClearOverrideBindings);
|
||||
Game::Lua::RegisterGlobalFunction("SetOverrideBinding", &Script_SetOverrideBinding);
|
||||
Game::Lua::RegisterGlobalFunction("SetOverrideBindingSpell", &Script_SetOverrideBindingSpell);
|
||||
Game::Lua::RegisterGlobalFunction("SetOverrideBindingItem", &Script_SetOverrideBindingItem);
|
||||
Game::Lua::RegisterGlobalFunction("SetOverrideBindingMacro", &Script_SetOverrideBindingMacro);
|
||||
Game::Lua::RegisterGlobalFunction("SetOverrideBindingClick", &Script_SetOverrideBindingClick);
|
||||
Game::Lua::RegisterGlobalFunction("ClearOverrideBindings", &Script_ClearOverrideBindings);
|
||||
Game::Lua::RegisterGlobalFunction("GetBindingAction", &Script_GetBindingAction);
|
||||
}
|
||||
|
||||
const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
|
||||
|
||||
const Game::HookAutoRegister _hookKeyDispatch{
|
||||
Offsets::FUN_BINDING_KEY_DISPATCH, reinterpret_cast<void *>(&KeyDispatch_h),
|
||||
reinterpret_cast<void **>(&KeyDispatch_o)};
|
||||
// Owners are frames of the Lua state being torn down; their overrides go with it.
|
||||
void PrepareForReload() { g_overrides.clear(); }
|
||||
const Game::ReloadAutoRegister _reload{&PrepareForReload};
|
||||
|
||||
const Game::HookAutoRegister _hookKeyDispatch{Offsets::FUN_BINDING_KEY_DISPATCH,
|
||||
reinterpret_cast<void *>(&KeyDispatch_h),
|
||||
reinterpret_cast<void **>(&g_keyDispatchOriginal)};
|
||||
|
||||
const Game::HookAutoRegister _hookCommandExecute{
|
||||
Offsets::FUN_BINDING_COMMAND_EXECUTE,
|
||||
reinterpret_cast<void *>(&CommandExecute_h),
|
||||
reinterpret_cast<void **>(&CommandExecute_o)};
|
||||
Offsets::FUN_BINDING_COMMAND_EXECUTE, reinterpret_cast<void *>(&CommandExecute_h),
|
||||
reinterpret_cast<void **>(&g_commandExecuteOriginal)};
|
||||
|
||||
} // namespace
|
||||
|
||||
|
||||
@@ -12,7 +12,35 @@
|
||||
<Binding name="TARGETFOCUS">
|
||||
TargetUnit("focus");
|
||||
</Binding>
|
||||
<Binding name="INTERACTMOUSEOVER">
|
||||
if ( not C_PlayerInteractionManager.InteractUnit("mouseover", false, false) ) then
|
||||
C_PlayerInteractionManager.InteractUnit("anyinteract");
|
||||
end
|
||||
</Binding>
|
||||
<Binding name="INTERACTTARGET">
|
||||
C_PlayerInteractionManager.InteractUnit("anyinteract");
|
||||
</Binding>
|
||||
<Binding name="AOELOOT">
|
||||
C_Loot.LootAllCorpses()
|
||||
</Binding>
|
||||
<!-- 4.3.4's modified-click actions and defaults (FrameXML\Bindings.xml).
|
||||
Read by src/bindings/ModifiedClick.cpp. -->
|
||||
<ModifiedClick action="SELFCAST" default="ALT"/>
|
||||
<ModifiedClick action="FOCUSCAST" default="NONE"/>
|
||||
<ModifiedClick action="AUTOLOOTTOGGLE" default="SHIFT"/>
|
||||
<ModifiedClick action="MAILAUTOLOOTTOGGLE" default="SHIFT"/>
|
||||
<ModifiedClick action="STICKYCAMERA" default="CTRL"/>
|
||||
<ModifiedClick action="CHATLINK" default="SHIFT-BUTTON1"/>
|
||||
<ModifiedClick action="DRESSUP" default="CTRL-BUTTON1"/>
|
||||
<ModifiedClick action="SOCKETITEM" default="SHIFT-BUTTON2"/>
|
||||
<ModifiedClick action="SPLITSTACK" default="SHIFT"/>
|
||||
<ModifiedClick action="PICKUPACTION" default="SHIFT"/>
|
||||
<ModifiedClick action="PICKUPITEM" default="SHIFT"/>
|
||||
<ModifiedClick action="COMPAREITEMS" default="SHIFT"/>
|
||||
<ModifiedClick action="OPENALLBAGS" default="SHIFT"/>
|
||||
<ModifiedClick action="QUESTWATCHTOGGLE" default="SHIFT"/>
|
||||
<ModifiedClick action="TOKENWATCHTOGGLE" default="SHIFT"/>
|
||||
<ModifiedClick action="SHOWITEMFLYOUT" default="ALT"/>
|
||||
<ModifiedClick action="SHOWMULTICASTFLYOUT" default="ALT"/>
|
||||
<ModifiedClick action="TRADESEARCHADD" default="SHIFT"/>
|
||||
</Bindings>
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
// This file is part of ClassicAPI.
|
||||
//
|
||||
// ClassicAPI is free software: you can redistribute it and/or modify it under the terms
|
||||
// of the GNU 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 General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License along with
|
||||
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
// The SPELL / ITEM / MACRO / CLICK binding commands — 4.3.4's
|
||||
// CGUIBindings::ExecKey branches (decomp UIBindings.cpp), on 1.12's own
|
||||
// primitives:
|
||||
//
|
||||
// SPELL x on release: the spellbook slot named x (FUN_RESOLVE_SPELL_NAME_TO_SLOT)
|
||||
// cast through FUN_SPELL_CAST_DISPATCH at you when SELFCAST is held,
|
||||
// at your focus when FOCUSCAST is, else with no explicit target.
|
||||
// ITEM x on release: the item named x you carry (equipment, then bags)
|
||||
// used through FUN_ITEM_USE with the same target.
|
||||
// MACRO x on release: macro index x when x is all digits, else the macro
|
||||
// named x, run through FUN_MACRO_RUN_BODY.
|
||||
// CLICK f:b press and release: the frame named f gets a mouse down and a
|
||||
// mouse up for button b.
|
||||
//
|
||||
// The release timing is 4.3.4's (and vanilla action buttons'): the command
|
||||
// runs when the key comes back up.
|
||||
//
|
||||
// CLICK: 4.3.4's frames take a `btn` argument on OnLayerMouseDown / Up that
|
||||
// marks a virtual click — no hit test, and a button clicks for ANY press
|
||||
// (down) or release (up) bit it is registered for. 1.12's take only the mouse
|
||||
// event and hit-test it, so the virtual branch is built from the button's own
|
||||
// pieces, in 4.3.4's order: the frame's OnMouseDown / OnMouseUp script with
|
||||
// the button name, then the Button state machine (click / double-click
|
||||
// vmethods, SetButtonState). Only frames that are Buttons get the second part,
|
||||
// as only CSimpleButton overrides the handlers 4.3.4 runs.
|
||||
|
||||
#include "bindings/Command.h"
|
||||
|
||||
#include "Game.h"
|
||||
#include "Offsets.h"
|
||||
#include "bindings/ModifiedClick.h"
|
||||
#include "frame/ClickFrame.h"
|
||||
#include "item/Arg.h"
|
||||
#include "item/Location.h"
|
||||
#include "item/Use.h"
|
||||
#include "spell/Placement.h"
|
||||
#include "time/Clock.h"
|
||||
#include "unit/Focus.h"
|
||||
#include "unit/Identity.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
namespace Bindings::Command {
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr const char kSpell[] = "SPELL ";
|
||||
constexpr const char kItem[] = "ITEM ";
|
||||
constexpr const char kMacro[] = "MACRO ";
|
||||
constexpr const char kClick[] = "CLICK ";
|
||||
|
||||
bool HasPrefix(const char *command, const char *prefix) {
|
||||
return _strnicmp(command, prefix, std::strlen(prefix)) == 0;
|
||||
}
|
||||
|
||||
// The target 4.3.4 picks for SPELL / ITEM: you for SELFCAST, your focus for
|
||||
// FOCUSCAST, else none (the engine then uses your target).
|
||||
uint64_t ModifiedTarget() {
|
||||
if (ModifiedClick::IsModifiedClick("SELFCAST"))
|
||||
return Unit::Identity::PlayerGuid();
|
||||
if (ModifiedClick::IsModifiedClick("FOCUSCAST"))
|
||||
return Unit::Focus::Get();
|
||||
return 0;
|
||||
}
|
||||
|
||||
void CastSpell(const char *name) {
|
||||
Spell::Placement::DispatchSpellCastByName(name, ModifiedTarget());
|
||||
}
|
||||
|
||||
void UseItem(const char *name) {
|
||||
const Item::Arg::Resolved byName{0, 0, name};
|
||||
Item::Location::ByGUIDResult found{};
|
||||
if (!Item::Location::FindByArgNoLua(byName, &found) || found.item == nullptr)
|
||||
return;
|
||||
Item::Use::UseItem(found.item, ModifiedTarget());
|
||||
}
|
||||
|
||||
void RunMacro(const char *name) {
|
||||
using SlotToEntry_t = const uint8_t *(__fastcall *)(unsigned slot);
|
||||
using NameToSlot_t = uint32_t(__fastcall *)(const char *name);
|
||||
using RunBody_t = void(__fastcall *)(const uint8_t *entry);
|
||||
const char *digit = name;
|
||||
while (*digit >= '0' && *digit <= '9')
|
||||
++digit;
|
||||
const uint32_t slot =
|
||||
(*name != '\0' && *digit == '\0')
|
||||
? static_cast<uint32_t>(std::atoi(name) - 1)
|
||||
: reinterpret_cast<NameToSlot_t>(Offsets::FUN_MACRO_NAME_TO_SLOT)(name);
|
||||
const uint8_t *entry =
|
||||
reinterpret_cast<SlotToEntry_t>(Offsets::FUN_MACRO_SLOT_TO_ENTRY)(slot);
|
||||
if (entry != nullptr)
|
||||
reinterpret_cast<RunBody_t>(Offsets::FUN_MACRO_RUN_BODY)(entry);
|
||||
}
|
||||
|
||||
// StringToMouseButton: the click mask for a button name, 0 for any other
|
||||
// (the click vmethod then names it "UNKNOWN").
|
||||
uint32_t MaskForButton(const char *button) {
|
||||
static const struct {
|
||||
uintptr_t name;
|
||||
uint32_t mask;
|
||||
} kButtons[] = {
|
||||
{Offsets::VAR_BUTTON_NAME_LEFT, 0x01}, {Offsets::VAR_BUTTON_NAME_RIGHT, 0x04},
|
||||
{Offsets::VAR_BUTTON_NAME_MIDDLE, 0x02}, {Offsets::VAR_BUTTON_NAME_4, 0x08},
|
||||
{Offsets::VAR_BUTTON_NAME_5, 0x10},
|
||||
};
|
||||
for (const auto &entry : kButtons)
|
||||
if (_stricmp(reinterpret_cast<const char *>(entry.name), button) == 0)
|
||||
return entry.mask;
|
||||
return 0;
|
||||
}
|
||||
|
||||
// The frame's OnMouseDown / OnMouseUp, fired as the engine fires them.
|
||||
void FireMouseScript(void *frame, uintptr_t slotOffset, const char *button) {
|
||||
using FireVariadic_t = void(__cdecl *)(void *frame, uint32_t *slotPtr, const char *fmt, ...);
|
||||
uint32_t *slot = Game::Ptr<uint32_t>(frame, slotOffset);
|
||||
if (slot[0] == 0)
|
||||
return;
|
||||
void *L = Game::Lua::State();
|
||||
const int top = L != nullptr ? Game::Lua::GetTop(L) : 0;
|
||||
reinterpret_cast<FireVariadic_t>(Offsets::FUN_FRAME_RUN_SCRIPT_VARIADIC)(
|
||||
frame, slot, reinterpret_cast<const char *>(Offsets::VAR_SCRIPT_FMT_S), button);
|
||||
if (L != nullptr)
|
||||
Game::Lua::SetTop(L, top);
|
||||
}
|
||||
|
||||
using ButtonMethod_t = void(__thiscall *)(void *button, uint32_t arg, int flag);
|
||||
|
||||
void CallButton(void *button, uintptr_t slot, uint32_t arg) {
|
||||
auto *vtable = Game::Read<uintptr_t *>(button, 0);
|
||||
reinterpret_cast<ButtonMethod_t>(vtable[slot / sizeof(uintptr_t)])(button, arg, 0);
|
||||
}
|
||||
|
||||
int &ButtonState(void *button) { return Game::Ref<int>(button, Offsets::OFF_BUTTON_STATE); }
|
||||
bool StateLocked(void *button) {
|
||||
return Game::Read<int>(button, Offsets::OFF_BUTTON_STATE_LOCKED) != 0;
|
||||
}
|
||||
|
||||
// The button's click under the engine's "in click" flag.
|
||||
template <typename Fn> void InClick(Fn fn) {
|
||||
auto &flag = Game::Ref<int>(Offsets::VAR_BUTTON_IN_CLICK);
|
||||
flag = 1;
|
||||
fn();
|
||||
flag = 0;
|
||||
}
|
||||
|
||||
// CSimpleButton::OnLayerMouseDown with a `btn`.
|
||||
void VirtualMouseDown(void *frame, const char *button) {
|
||||
FireMouseScript(frame, Offsets::OFF_FRAME_ONMOUSEDOWN_SLOT, button);
|
||||
if (!Game::Lua::IsA(frame, Offsets::VAR_BUTTON_LUA_TYPE_ID) ||
|
||||
ButtonState(frame) == Offsets::BUTTON_STATE_DISABLED)
|
||||
return;
|
||||
if (Game::Read<uint32_t>(frame, Offsets::OFF_BUTTON_CLICK_MASK) & 0xFF)
|
||||
InClick([&] { CallButton(frame, Offsets::VTBL_BUTTON_CLICK, MaskForButton(button)); });
|
||||
if (!StateLocked(frame) && ButtonState(frame) != Offsets::BUTTON_STATE_DISABLED)
|
||||
CallButton(frame, Offsets::VTBL_BUTTON_SET_STATE, Offsets::BUTTON_STATE_PUSHED);
|
||||
}
|
||||
|
||||
// CSimpleButton::OnLayerMouseUp with a `btn`.
|
||||
void VirtualMouseUp(void *frame, const char *button) {
|
||||
FireMouseScript(frame, Offsets::OFF_FRAME_ONMOUSEUP_SLOT, button);
|
||||
if (!Game::Lua::IsA(frame, Offsets::VAR_BUTTON_LUA_TYPE_ID) ||
|
||||
ButtonState(frame) != Offsets::BUTTON_STATE_PUSHED)
|
||||
return;
|
||||
if (Game::Read<uint32_t>(frame, Offsets::OFF_BUTTON_CLICK_MASK) & 0xFF00) {
|
||||
InClick([&] {
|
||||
const uint32_t now = Time::Clock::NowMs();
|
||||
auto &last = Game::Ref<uint32_t>(frame, Offsets::OFF_BUTTON_LAST_CLICK_MS);
|
||||
const uint32_t mask = MaskForButton(button);
|
||||
if (Game::Read<uint32_t>(frame, Offsets::OFF_BUTTON_ONDOUBLECLICK_HANDLER) != 0 &&
|
||||
last != 0 && Time::Clock::Elapsed(last, now) <= Offsets::BUTTON_DOUBLE_CLICK_MS) {
|
||||
CallButton(frame, Offsets::VTBL_BUTTON_DOUBLE_CLICK, mask);
|
||||
last = 0;
|
||||
} else {
|
||||
CallButton(frame, Offsets::VTBL_BUTTON_CLICK, mask);
|
||||
last = now;
|
||||
}
|
||||
});
|
||||
}
|
||||
if (!StateLocked(frame) && ButtonState(frame) != Offsets::BUTTON_STATE_DISABLED)
|
||||
CallButton(frame, Offsets::VTBL_BUTTON_SET_STATE, Offsets::BUTTON_STATE_NORMAL);
|
||||
}
|
||||
|
||||
int Click(const char *target, int isDown) {
|
||||
const char *separator = std::strchr(target, ':');
|
||||
if (separator == nullptr)
|
||||
return 0;
|
||||
void *frame = Frame::ClickFrame::Find(Game::Lua::State(), target,
|
||||
static_cast<size_t>(separator - target));
|
||||
if (frame == nullptr || frame == Game::Read<void *>(Offsets::VAR_GAME_STATE_PTR))
|
||||
return 0; // no such frame, or the world frame
|
||||
const char *button = separator + 1;
|
||||
if (isDown)
|
||||
VirtualMouseDown(frame, button);
|
||||
else
|
||||
VirtualMouseUp(frame, button);
|
||||
return 1;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool IsDirectAction(const char *command) {
|
||||
return command != nullptr && (HasPrefix(command, kSpell) || HasPrefix(command, kItem) ||
|
||||
HasPrefix(command, kMacro) || HasPrefix(command, kClick));
|
||||
}
|
||||
|
||||
int RunKey(const char *command, int isDown) {
|
||||
if (HasPrefix(command, kSpell)) {
|
||||
if (!isDown)
|
||||
CastSpell(command + sizeof kSpell - 1);
|
||||
return 1;
|
||||
}
|
||||
if (HasPrefix(command, kItem)) {
|
||||
if (!isDown)
|
||||
UseItem(command + sizeof kItem - 1);
|
||||
return 1;
|
||||
}
|
||||
if (HasPrefix(command, kMacro)) {
|
||||
if (!isDown)
|
||||
RunMacro(command + sizeof kMacro - 1);
|
||||
return 1;
|
||||
}
|
||||
return Click(command + sizeof kClick - 1, isDown);
|
||||
}
|
||||
|
||||
} // namespace Bindings::Command
|
||||
@@ -0,0 +1,29 @@
|
||||
// This file is part of ClassicAPI.
|
||||
//
|
||||
// ClassicAPI is free software: you can redistribute it and/or modify it under the terms
|
||||
// of the GNU 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 General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License along with
|
||||
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#pragma once
|
||||
|
||||
namespace Bindings::Command {
|
||||
|
||||
// True for the direct-action command families a key binding can hold:
|
||||
// "SPELL x", "ITEM x", "MACRO x", "CLICK frame:button" (case-insensitive
|
||||
// prefix, as 4.3.4 tests them).
|
||||
bool IsDirectAction(const char *command);
|
||||
|
||||
// Runs a direct-action command for a key press or release, as 4.3.4's
|
||||
// CGUIBindings::ExecKey does. Returns the engine's handled flag: 1 for SPELL,
|
||||
// ITEM and MACRO, 1 for CLICK when the frame exists, else 0. Only call it for
|
||||
// IsDirectAction commands.
|
||||
int RunKey(const char *command, int isDown);
|
||||
|
||||
} // namespace Bindings::Command
|
||||
@@ -49,7 +49,8 @@
|
||||
#include "Inject.h"
|
||||
#include "Offsets.h"
|
||||
|
||||
#include "embedded_bindings.h"
|
||||
#include "embed/Resource.h"
|
||||
#include "embedded_resources.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
@@ -132,8 +133,10 @@ bool ExtractHeaderAttr(const char *tagStart, const char *tagEnd,
|
||||
|
||||
EmbeddedConfig ResolveEmbeddedConfig() {
|
||||
EmbeddedConfig out = {};
|
||||
const char *content = reinterpret_cast<const char *>(kEmbeddedBindingsXml);
|
||||
const char *end = content + kEmbeddedBindingsXmlSize;
|
||||
const Embed::Bytes xml = Embed::Resource(Embed::Ids::kBindingsXml);
|
||||
if (xml.data == nullptr) return out;
|
||||
const char *content = reinterpret_cast<const char *>(xml.data);
|
||||
const char *end = content + xml.size;
|
||||
|
||||
// Locate `<Bindings` opening tag (skipping any comment blocks
|
||||
// that mention the tag literally for documentation purposes).
|
||||
|
||||
@@ -0,0 +1,484 @@
|
||||
// This file is part of ClassicAPI.
|
||||
//
|
||||
// ClassicAPI is free software: you can redistribute it and/or modify it under the terms
|
||||
// of the GNU 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 General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License along with
|
||||
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
// Modified clicks — 4.3.4's MODIFIEDCLICK system (decomp Ui/MODIFIEDCLICK.cpp,
|
||||
// UIBindings.cpp, UIBindings_Scripts.cpp), which 1.12's binding manager lacks.
|
||||
//
|
||||
// An action ("SELFCAST", "CHATLINK", …) is bound to a modifier set and/or a
|
||||
// mouse button ("ALT", "SHIFT-BUTTON1", "NONE"), once per binding set (0
|
||||
// default, 1 account, 2 character, 3 current), exactly like key bindings. 1.12
|
||||
// has 4.3.4's binding sets, file format and load / save / copy steps, so each
|
||||
// gains the modified-click half 4.3.4 has, through a co-hook on the step:
|
||||
//
|
||||
// - Load (Bindings.xml): `<ModifiedClick action="X" default="Y"/>` defines
|
||||
// an action and its default. We register the actions from the same file
|
||||
// first. The engine's loop tests each root tag inline and logs "Unknown
|
||||
// node type" for anything but <Binding>; 4.3.4's loop has a ModifiedClick
|
||||
// branch there, so the loader runs with a status that drops exactly that
|
||||
// warning for a ModifiedClick node and forwards everything else.
|
||||
// - LoadBindings (a binding file into a set): the set starts from the
|
||||
// defaults, then `modifiedclick BINDING ACTION` lines apply.
|
||||
// - SaveBindings: `modifiedclick` lines for every action not left at its
|
||||
// default.
|
||||
// - CopyBindings: the set's bindings are copied with the key bindings.
|
||||
//
|
||||
// The actions live as long as the binding manager: the engine builds it on
|
||||
// every world load and /reload, so the table is cleared with the Lua state.
|
||||
// Key state comes from Input::Modifier (the left/right bits 4.3.4's
|
||||
// CGGameUI::IsKeyDown reads) and the clicked button from Frame::ClickEvents
|
||||
// (4.3.4's CSimpleTop::m_mouseButtonName).
|
||||
|
||||
#include "bindings/ModifiedClick.h"
|
||||
|
||||
#include "Game.h"
|
||||
#include "Offsets.h"
|
||||
#include "addons/EngineIO.h"
|
||||
#include "baselib/Ascii.h"
|
||||
#include "frame/ClickEvents.h"
|
||||
#include "input/Modifier.h"
|
||||
#include "xml/FrameLoad.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Bindings::ModifiedClick {
|
||||
|
||||
namespace {
|
||||
|
||||
// 4.3.4's modifier bits, = Input::Modifier's left/right key bits (and what
|
||||
// Input::Modifier::ParseModifiers returns).
|
||||
constexpr uint32_t kLShift = 0x01, kRShift = 0x02, kLCtrl = 0x04, kRCtrl = 0x08,
|
||||
kLAlt = 0x10, kRAlt = 0x20;
|
||||
constexpr int kKeyCount = 6;
|
||||
|
||||
// MODIFIEDCLICK_DATA. Flag 1 = the set holds the default (never saved).
|
||||
constexpr uint32_t kFlagDefault = 0x1;
|
||||
struct Data {
|
||||
uint32_t flags = 0;
|
||||
uint32_t modifiers = 0;
|
||||
const char *button = nullptr;
|
||||
};
|
||||
|
||||
struct Click {
|
||||
std::string action;
|
||||
Data data[Offsets::BINDING_SET_COUNT];
|
||||
};
|
||||
|
||||
std::vector<Click> g_clicks;
|
||||
|
||||
Click *Find(const char *action) {
|
||||
if (action == nullptr)
|
||||
return nullptr;
|
||||
for (Click &click : g_clicks)
|
||||
if (_stricmp(click.action.c_str(), action) == 0)
|
||||
return &click;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
bool KeyDown(int key) { return (Input::Modifier::CurrentMask() & (1u << key)) != 0; }
|
||||
|
||||
bool PrefixIs(const char *s, const char *prefix) {
|
||||
return _strnicmp(s, prefix, std::strlen(prefix)) == 0;
|
||||
}
|
||||
|
||||
// CGUIBindings::AddMetaPrefix, appended to `out`.
|
||||
void AddMetaPrefix(uint32_t modifiers, std::string &out) {
|
||||
const auto side = [&](uint32_t left, uint32_t right, const char *both, const char *l,
|
||||
const char *r) {
|
||||
if ((modifiers & (left | right)) == (left | right))
|
||||
out += both;
|
||||
else if (modifiers & left)
|
||||
out += l;
|
||||
else if (modifiers & right)
|
||||
out += r;
|
||||
};
|
||||
side(kLAlt, kRAlt, "ALT-", "LALT-", "RALT-");
|
||||
side(kLCtrl, kRCtrl, "CTRL-", "LCTRL-", "RCTRL-");
|
||||
side(kLShift, kRShift, "SHIFT-", "LSHIFT-", "RSHIFT-");
|
||||
}
|
||||
|
||||
// BUTTONn <-> mouse-button name (IndexToMouseButton / MouseButtonToIndex).
|
||||
// 1..5 are the engine's own name literals, the strings GetMouseButtonClicked
|
||||
// and the click scope hold.
|
||||
const char *const kExtraButtons[] = {"Button6", "Button7", "Button8", "Button9"};
|
||||
|
||||
const char *ButtonForIndex(int index) {
|
||||
switch (index) {
|
||||
case 1: return reinterpret_cast<const char *>(Offsets::VAR_BUTTON_NAME_LEFT);
|
||||
case 2: return reinterpret_cast<const char *>(Offsets::VAR_BUTTON_NAME_RIGHT);
|
||||
case 3: return reinterpret_cast<const char *>(Offsets::VAR_BUTTON_NAME_MIDDLE);
|
||||
case 4: return reinterpret_cast<const char *>(Offsets::VAR_BUTTON_NAME_4);
|
||||
case 5: return reinterpret_cast<const char *>(Offsets::VAR_BUTTON_NAME_5);
|
||||
case 6: case 7: case 8: case 9: return kExtraButtons[index - 6];
|
||||
default: return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
int IndexForButton(const char *button) {
|
||||
for (int index = 1; index <= 9; ++index)
|
||||
if (_stricmp(ButtonForIndex(index), button) == 0)
|
||||
return index;
|
||||
return 0;
|
||||
}
|
||||
|
||||
// MODIFIEDCLICK::SetBinding.
|
||||
bool SetBinding(Click &click, int set, const char *binding) {
|
||||
const char *button = nullptr;
|
||||
uint32_t modifiers = 0;
|
||||
if (binding != nullptr && *binding != '\0' && _stricmp(binding, "NONE") != 0) {
|
||||
modifiers = Input::Modifier::ParseModifiers(binding);
|
||||
if (PrefixIs(binding, "BUTTON")) {
|
||||
binding += 6;
|
||||
button = ButtonForIndex(std::atoi(binding));
|
||||
++binding;
|
||||
}
|
||||
if (*binding != '\0')
|
||||
return false;
|
||||
}
|
||||
Data &data = click.data[set];
|
||||
if (set != Offsets::BINDING_SET_DEFAULT)
|
||||
data.flags &= ~kFlagDefault;
|
||||
else
|
||||
data.flags |= kFlagDefault;
|
||||
data.button = button;
|
||||
data.modifiers = modifiers;
|
||||
return true;
|
||||
}
|
||||
|
||||
// MODIFIEDCLICK::GetBinding.
|
||||
std::string GetBinding(const Click &click, int set) {
|
||||
const Data &data = click.data[set];
|
||||
if (data.modifiers == 0 && data.button == nullptr)
|
||||
return "NONE";
|
||||
std::string out;
|
||||
AddMetaPrefix(data.modifiers, out);
|
||||
if (data.button != nullptr)
|
||||
out += "BUTTON" + std::to_string(IndexForButton(data.button));
|
||||
else
|
||||
out.pop_back(); // the prefix's trailing '-'
|
||||
return out;
|
||||
}
|
||||
|
||||
// MODIFIEDCLICK::IsActive.
|
||||
bool IsActive(const Click &click, int set) {
|
||||
const Data &data = click.data[set];
|
||||
if (data.modifiers != 0) {
|
||||
int key = 0;
|
||||
while (!((1u << key) & data.modifiers) || !KeyDown(key)) {
|
||||
if (++key >= kKeyCount)
|
||||
return false;
|
||||
}
|
||||
if (data.button == nullptr)
|
||||
return true;
|
||||
} else if (data.button == nullptr) {
|
||||
return false;
|
||||
}
|
||||
const char *current = Frame::ClickEvents::CurrentButton();
|
||||
return current == nullptr || std::strcmp(current, data.button) == 0;
|
||||
}
|
||||
|
||||
// One side of a modifier test: left only, right only, or either.
|
||||
bool SideHeld(uint32_t modifiers, uint32_t left, uint32_t right, int leftKey, int rightKey) {
|
||||
const uint32_t bits = modifiers & (left | right);
|
||||
if (bits == left)
|
||||
return KeyDown(leftKey);
|
||||
if (bits == right || (bits == (left | right) && !KeyDown(leftKey)))
|
||||
return KeyDown(rightKey);
|
||||
return true;
|
||||
}
|
||||
|
||||
// --- Bindings.xml: <ModifiedClick action default> ---------------------------
|
||||
|
||||
using LoadFile_t = int(__fastcall *)(void *mgr, void *edx, const char *path, void *md5,
|
||||
void *status);
|
||||
LoadFile_t g_loadFileOriginal = nullptr;
|
||||
|
||||
using TreeLoad_t = void *(__fastcall *)(const char *data, uint32_t size);
|
||||
using TreeFree_t = void(__fastcall *)(void *tree);
|
||||
|
||||
// CGUIBindings::LoadModifiedClick for every root node of the file.
|
||||
void LoadModifiedClicks(const char *path, void *status) {
|
||||
void *data = nullptr;
|
||||
size_t size = 0;
|
||||
if (!reinterpret_cast<AddOns::EngineIO::FileReadFn>(Offsets::FUN_FILE_READ)(0, path, &data,
|
||||
&size, 0, 1, 0))
|
||||
return;
|
||||
void *tree = reinterpret_cast<TreeLoad_t>(Offsets::FUN_XML_TREE_LOAD)(
|
||||
static_cast<const char *>(data), static_cast<uint32_t>(size));
|
||||
reinterpret_cast<AddOns::EngineIO::SMemFreeFn>(Offsets::FUN_STORM_SMEM_FREE)(data, __FILE__,
|
||||
__LINE__, 0);
|
||||
if (tree == nullptr)
|
||||
return; // the engine loader reports the parse error
|
||||
const void *root = Game::Read<const void *>(tree, 0);
|
||||
for (const void *node = root ? Xml::FirstChild(root) : nullptr; node != nullptr;
|
||||
node = Xml::NextSibling(node)) {
|
||||
if (!Xml::TagIs(node, "ModifiedClick"))
|
||||
continue;
|
||||
const char *action = Xml::Attr(node, "action");
|
||||
if (action == nullptr || *action == '\0') {
|
||||
Xml::Warn(status, "Found modified click with no action in %s", path);
|
||||
continue;
|
||||
}
|
||||
if (Find(action) != nullptr) {
|
||||
Xml::Warn(status, "Modified click %s is defined more than once in %s", action, path);
|
||||
continue;
|
||||
}
|
||||
g_clicks.push_back(Click{action, {}});
|
||||
const char *binding = Xml::Attr(node, "default");
|
||||
if (binding != nullptr && *binding != '\0')
|
||||
SetBinding(g_clicks.back(), Offsets::BINDING_SET_DEFAULT, binding);
|
||||
}
|
||||
reinterpret_cast<TreeFree_t>(Offsets::FUN_XML_TREE_FREE)(tree);
|
||||
}
|
||||
|
||||
// The status the engine loader is given: a CStatus whose only used slot,
|
||||
// Add (vtable +0xC), forwards to the real status. Load passes at most two
|
||||
// string arguments after the format, and Add is __cdecl, so taking exactly
|
||||
// two is safe whatever the format consumes.
|
||||
struct LoadStatus {
|
||||
const void *const *vtable;
|
||||
void *real;
|
||||
};
|
||||
|
||||
void __cdecl LoadStatusAdd(LoadStatus *self, int level, const char *fmt, const char *a,
|
||||
const char *b) {
|
||||
if (fmt == reinterpret_cast<const char *>(Offsets::STR_BINDINGS_UNKNOWN_NODE) &&
|
||||
a != nullptr && Ascii::EqualCI(a, "ModifiedClick"))
|
||||
return; // a node this loader now knows (LoadModifiedClicks)
|
||||
using Add_t = void(__cdecl *)(void *status, int level, const char *fmt, ...);
|
||||
const void *vtable = Game::Read<const void *>(self->real, 0);
|
||||
Game::Read<Add_t>(vtable, Offsets::VTBL_XML_STATUS_ADD)(self->real, level, fmt, a, b);
|
||||
}
|
||||
|
||||
static_assert(Offsets::VTBL_XML_STATUS_ADD == 3 * sizeof(void *));
|
||||
const void *const kLoadStatusVtable[4] = {nullptr, nullptr, nullptr,
|
||||
reinterpret_cast<const void *>(&LoadStatusAdd)};
|
||||
|
||||
int __fastcall LoadFile_h(void *mgr, void *edx, const char *path, void *md5, void *status) {
|
||||
if (status == nullptr)
|
||||
status = reinterpret_cast<void *>(Offsets::VAR_BINDINGS_LOAD_STATUS);
|
||||
if (path != nullptr)
|
||||
LoadModifiedClicks(path, status);
|
||||
LoadStatus filtered{kLoadStatusVtable, status};
|
||||
return g_loadFileOriginal(mgr, edx, path, md5, &filtered);
|
||||
}
|
||||
|
||||
// --- binding files: modifiedclick lines -----------------------------------
|
||||
|
||||
using LoadSet_t = void(__fastcall *)(int set, const char *text);
|
||||
LoadSet_t g_loadSetOriginal = nullptr;
|
||||
|
||||
using Tokenize_t = void(__stdcall *)(const char **cursor, char *out, unsigned outSize,
|
||||
const char *delims, int *outQuoted);
|
||||
|
||||
// The modified-click half of 4.3.4's LoadBindings: start from the defaults,
|
||||
// then apply `modifiedclick BINDING ACTION` lines.
|
||||
void __fastcall LoadSet_h(int set, const char *text) {
|
||||
g_loadSetOriginal(set, text);
|
||||
if (set < 0 || set >= Offsets::BINDING_SET_COUNT)
|
||||
return;
|
||||
if (set != Offsets::BINDING_SET_DEFAULT)
|
||||
for (Click &click : g_clicks)
|
||||
click.data[set] = click.data[Offsets::BINDING_SET_DEFAULT];
|
||||
|
||||
auto tokenize = reinterpret_cast<Tokenize_t>(Offsets::FUN_STORM_STR_TOKENIZE);
|
||||
const char *lineDelims = reinterpret_cast<const char *>(Offsets::VAR_MACRO_LINE_DELIMS);
|
||||
const char *spaceDelims = reinterpret_cast<const char *>(Offsets::VAR_STR_SPACE_DELIM);
|
||||
char line[1024];
|
||||
char key[32];
|
||||
const char *cursor = text;
|
||||
while (cursor != nullptr && *cursor != '\0') {
|
||||
tokenize(&cursor, line, sizeof line, lineDelims, nullptr);
|
||||
const char *p = line;
|
||||
while (*p == ' ' || *p == '\t')
|
||||
++p;
|
||||
if (!PrefixIs(p, "modifiedclick "))
|
||||
continue;
|
||||
const char *action = p + 14;
|
||||
tokenize(&action, key, sizeof key, spaceDelims, nullptr);
|
||||
if (action != nullptr)
|
||||
if (Click *click = Find(action))
|
||||
SetBinding(*click, set, key);
|
||||
}
|
||||
}
|
||||
|
||||
using SaveSet_t = void(__fastcall *)(void *mgr, void *edx, int set, void *file);
|
||||
SaveSet_t g_saveSetOriginal = nullptr;
|
||||
|
||||
using WriteFile_t = int(__fastcall *)(void *file, const void *buffer, uint32_t size,
|
||||
uint32_t *written);
|
||||
|
||||
void __fastcall SaveSet_h(void *mgr, void *edx, int set, void *file) {
|
||||
g_saveSetOriginal(mgr, edx, set, file);
|
||||
if (set < 0 || set >= Offsets::BINDING_SET_COUNT)
|
||||
return;
|
||||
auto write = reinterpret_cast<WriteFile_t>(Offsets::FUN_OS_WRITE_FILE);
|
||||
for (const Click &click : g_clicks) {
|
||||
if (click.data[set].flags & kFlagDefault)
|
||||
continue;
|
||||
const std::string line =
|
||||
"modifiedclick " + GetBinding(click, set) + " " + click.action + "\r\n";
|
||||
uint32_t written = 0;
|
||||
write(file, line.data(), static_cast<uint32_t>(line.size()), &written);
|
||||
}
|
||||
}
|
||||
|
||||
using CopySet_t = void(__fastcall *)(void *mgr, void *edx, int source, int dest);
|
||||
CopySet_t g_copySetOriginal = nullptr;
|
||||
|
||||
void __fastcall CopySet_h(void *mgr, void *edx, int source, int dest) {
|
||||
g_copySetOriginal(mgr, edx, source, dest);
|
||||
if (source < 0 || source >= Offsets::BINDING_SET_COUNT || dest < 0 ||
|
||||
dest >= Offsets::BINDING_SET_COUNT)
|
||||
return;
|
||||
for (Click &click : g_clicks)
|
||||
click.data[dest] = click.data[source];
|
||||
}
|
||||
|
||||
const Game::HookAutoRegister _loadFileHook{Offsets::FUN_BINDINGS_LOAD_FILE,
|
||||
reinterpret_cast<void *>(&LoadFile_h),
|
||||
reinterpret_cast<void **>(&g_loadFileOriginal)};
|
||||
const Game::HookAutoRegister _loadSetHook{Offsets::FUN_BINDINGS_LOAD_SET,
|
||||
reinterpret_cast<void *>(&LoadSet_h),
|
||||
reinterpret_cast<void **>(&g_loadSetOriginal)};
|
||||
const Game::HookAutoRegister _saveSetHook{Offsets::FUN_BINDINGS_SAVE_SET,
|
||||
reinterpret_cast<void *>(&SaveSet_h),
|
||||
reinterpret_cast<void **>(&g_saveSetOriginal)};
|
||||
const Game::HookAutoRegister _copySetHook{Offsets::FUN_BINDINGS_COPY_SET,
|
||||
reinterpret_cast<void *>(&CopySet_h),
|
||||
reinterpret_cast<void **>(&g_copySetOriginal)};
|
||||
|
||||
// The binding manager is rebuilt with every Lua state; so are its actions.
|
||||
void PrepareForReload() { g_clicks.clear(); }
|
||||
const Game::ReloadAutoRegister _reload{&PrepareForReload};
|
||||
|
||||
// --- Lua --------------------------------------------------------------------
|
||||
|
||||
int __fastcall Script_GetNumModifiedClickActions(void *L) {
|
||||
Game::Lua::PushNumber(L, static_cast<double>(g_clicks.size()));
|
||||
return 1;
|
||||
}
|
||||
|
||||
int __fastcall Script_GetModifiedClickAction(void *L) {
|
||||
if (!Game::Lua::IsNumber(L, 1)) {
|
||||
Game::Lua::Error(L, "Usage: GetModifiedClickAction(index)");
|
||||
return 0;
|
||||
}
|
||||
const int index = static_cast<int>(Game::Lua::ToNumber(L, 1)) - 1;
|
||||
Game::Lua::PushString(L, index >= 0 && index < static_cast<int>(g_clicks.size())
|
||||
? g_clicks[index].action.c_str()
|
||||
: nullptr);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int __fastcall Script_SetModifiedClick(void *L) {
|
||||
if (!Game::Lua::IsString(L, 1)) {
|
||||
Game::Lua::Error(L, "Usage: SetModifiedClick(\"action\", \"binding\")");
|
||||
return 0;
|
||||
}
|
||||
const char *action = Game::Lua::ToString(L, 1);
|
||||
const char *binding = Game::Lua::IsString(L, 2) ? Game::Lua::ToString(L, 2) : nullptr;
|
||||
Click *click = Find(action);
|
||||
if (click == nullptr || !SetBinding(*click, Offsets::BINDING_SET_CURRENT, binding)) {
|
||||
char message[256];
|
||||
std::snprintf(message, sizeof message,
|
||||
"SetModifiedClick(): Unknown action (%s) or binding (%s)", action,
|
||||
binding != nullptr ? binding : "(null)");
|
||||
Game::Lua::Error(L, "%s", message);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int __fastcall Script_GetModifiedClick(void *L) {
|
||||
if (!Game::Lua::IsString(L, 1)) {
|
||||
Game::Lua::Error(L, "Usage: GetModifiedClick(\"action\")");
|
||||
return 0;
|
||||
}
|
||||
const Click *click = Find(Game::Lua::ToString(L, 1));
|
||||
if (click == nullptr) {
|
||||
Game::Lua::PushNil(L);
|
||||
return 1;
|
||||
}
|
||||
Game::Lua::PushString(L, GetBinding(*click, Offsets::BINDING_SET_CURRENT).c_str());
|
||||
return 1;
|
||||
}
|
||||
|
||||
int __fastcall Script_IsModifiedClick(void *L) {
|
||||
const char *action = Game::Lua::IsString(L, 1) ? Game::Lua::ToString(L, 1) : nullptr;
|
||||
if (IsModifiedClick(action))
|
||||
Game::Lua::PushNumber(L, 1.0);
|
||||
else
|
||||
Game::Lua::PushNil(L);
|
||||
return 1;
|
||||
}
|
||||
|
||||
const Game::Doc::Field kIndexArgs[] = {Game::Doc::Req("index", "luaIndex")};
|
||||
const Game::Doc::Field kActionArgs[] = {Game::Doc::Req("action", "string")};
|
||||
const Game::Doc::Field kSetArgs[] = {Game::Doc::Req("action", "string"),
|
||||
Game::Doc::Opt("binding", "string")};
|
||||
const Game::Doc::Field kIsArgs[] = {Game::Doc::Opt("action", "string")};
|
||||
const Game::Doc::Field kCountRets[] = {Game::Doc::Req("count", "number")};
|
||||
const Game::Doc::Field kActionRets[] = {Game::Doc::Opt("action", "string")};
|
||||
const Game::Doc::Field kBindingRets[] = {Game::Doc::Opt("binding", "string")};
|
||||
const Game::Doc::Field kIsRets[] = {Game::Doc::Opt("isModified", "number")};
|
||||
|
||||
const Game::Doc::Function kGetNum{"Returns the number of modified-click actions.", {},
|
||||
kCountRets, "BindingsGlobals"};
|
||||
const Game::Doc::Function kGetAction{"Returns the name of the modified-click action at an index.",
|
||||
kIndexArgs, kActionRets, "BindingsGlobals"};
|
||||
const Game::Doc::Function kSet{"Sets the modifier keys and mouse button for an action.",
|
||||
kSetArgs, {}, "BindingsGlobals"};
|
||||
const Game::Doc::Function kGet{"Returns the modifier keys and mouse button set for an action.",
|
||||
kActionArgs, kBindingRets, "BindingsGlobals"};
|
||||
const Game::Doc::Function kIs{"Returns 1 when the keys and mouse button for an action are held.",
|
||||
kIsArgs, kIsRets, "BindingsGlobals"};
|
||||
|
||||
void RegisterLuaFunctions() {
|
||||
Game::Lua::RegisterGlobalFunction("GetNumModifiedClickActions",
|
||||
&Script_GetNumModifiedClickActions, &kGetNum);
|
||||
Game::Lua::RegisterGlobalFunction("GetModifiedClickAction", &Script_GetModifiedClickAction,
|
||||
&kGetAction);
|
||||
Game::Lua::RegisterGlobalFunction("SetModifiedClick", &Script_SetModifiedClick, &kSet);
|
||||
Game::Lua::RegisterGlobalFunction("GetModifiedClick", &Script_GetModifiedClick, &kGet);
|
||||
Game::Lua::RegisterGlobalFunction("IsModifiedClick", &Script_IsModifiedClick, &kIs);
|
||||
}
|
||||
|
||||
const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
|
||||
|
||||
} // namespace
|
||||
|
||||
bool IsModifiedClick(const char *action) {
|
||||
if (action != nullptr) {
|
||||
const char *rest = action;
|
||||
const uint32_t modifiers = Input::Modifier::ParseModifiers(rest);
|
||||
if (modifiers == 0) {
|
||||
const Click *click = Find(action);
|
||||
return click != nullptr && IsActive(*click, Offsets::BINDING_SET_CURRENT);
|
||||
}
|
||||
return SideHeld(modifiers, kLShift, kRShift, 0, 1) &&
|
||||
SideHeld(modifiers, kLCtrl, kRCtrl, 2, 3) &&
|
||||
SideHeld(modifiers, kLAlt, kRAlt, 4, 5);
|
||||
}
|
||||
if ((Input::Modifier::CurrentMask() & 0x3F) != 0)
|
||||
return true;
|
||||
for (const Click &click : g_clicks)
|
||||
if (IsActive(click, Offsets::BINDING_SET_CURRENT))
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace Bindings::ModifiedClick
|
||||
@@ -0,0 +1,24 @@
|
||||
// This file is part of ClassicAPI.
|
||||
//
|
||||
// ClassicAPI is free software: you can redistribute it and/or modify it under the terms
|
||||
// of the GNU 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 General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License along with
|
||||
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#pragma once
|
||||
|
||||
namespace Bindings::ModifiedClick {
|
||||
|
||||
// 4.3.4's CGUIBindings::IsModifiedClick. `action` null: any modifier key is
|
||||
// held or any modified-click action is active. A modifier string ("SHIFT",
|
||||
// "LCTRL-ALT"): those keys are held. Otherwise: the named action's binding in
|
||||
// the current set is active.
|
||||
bool IsModifiedClick(const char *action);
|
||||
|
||||
} // namespace Bindings::ModifiedClick
|
||||
Vendored
+59
@@ -0,0 +1,59 @@
|
||||
// This file is part of ClassicAPI.
|
||||
//
|
||||
// ClassicAPI is free software: you can redistribute it and/or modify it under the terms
|
||||
// of the GNU 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 General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License along with
|
||||
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#include "cache/Query.h"
|
||||
|
||||
#include "Game.h"
|
||||
#include "Offsets.h"
|
||||
|
||||
namespace Cache::Query {
|
||||
|
||||
namespace {
|
||||
|
||||
// The engine's stack CDataStore (see Offsets::VTABLE_CDATASTORE).
|
||||
struct DataStore {
|
||||
uintptr_t vtable;
|
||||
void *buffer;
|
||||
uint32_t base;
|
||||
uint32_t alloc;
|
||||
uint32_t size;
|
||||
uint32_t read;
|
||||
};
|
||||
static_assert(sizeof(DataStore) == 0x18, "CDataStore layout");
|
||||
|
||||
using PutU32_t = void(__thiscall *)(DataStore *self, uint32_t value);
|
||||
using PutGuid_t = void(__thiscall *)(DataStore *self, uint32_t lo, uint32_t hi);
|
||||
using Send_t = void(__thiscall *)(DataStore *self);
|
||||
using Free_t = void(__thiscall *)(DataStore *self, void **buffer, uint32_t *base, uint32_t *alloc);
|
||||
|
||||
} // namespace
|
||||
|
||||
// The send of FUN_DBCACHE_ITEMSTATS_GET_RECORD (0x0055BB18..0x0055BB89),
|
||||
// step for step. Every DBCache<T> clone builds the same packet.
|
||||
void Send(void *cache, uint32_t key) {
|
||||
DataStore packet{Offsets::VTABLE_CDATASTORE, nullptr, 0, 0, 0, 0xFFFFFFFF};
|
||||
const auto putU32 = reinterpret_cast<PutU32_t>(Offsets::FUN_DATASTORE_PUT_U32);
|
||||
putU32(&packet, Game::Read<uint32_t>(cache, Offsets::OFF_DBCACHE_QUERY_OPCODE));
|
||||
putU32(&packet, key);
|
||||
if (Game::Read<uint8_t>(cache, Offsets::OFF_DBCACHE_OWNER_FLAG) != 0)
|
||||
reinterpret_cast<PutGuid_t>(Offsets::FUN_DATASTORE_PUT_GUID)(&packet, 0, 0);
|
||||
packet.read = 0;
|
||||
reinterpret_cast<Send_t>(Offsets::FUN_CLIENT_SERVICES_SEND)(&packet);
|
||||
if (packet.alloc != 0xFFFFFFFF) {
|
||||
const auto release =
|
||||
*reinterpret_cast<const Free_t *>(Offsets::VTABLE_CDATASTORE + sizeof(uintptr_t));
|
||||
release(&packet, &packet.buffer, &packet.base, &packet.alloc);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace Cache::Query
|
||||
Vendored
+36
@@ -0,0 +1,36 @@
|
||||
// This file is part of ClassicAPI.
|
||||
//
|
||||
// ClassicAPI is free software: you can redistribute it and/or modify it under the terms
|
||||
// of the GNU 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 General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License along with
|
||||
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
// Re-sending a DBCache query.
|
||||
//
|
||||
// A DBCache `_GetRecord` sends its query only when it creates the pending
|
||||
// node; a lookup that finds the node pending just adds its callback. The
|
||||
// server drops a STATUS_LOGGEDIN query (every *_QUERY opcode) while the
|
||||
// player is not in the world - before login completes and behind every
|
||||
// loading screen - so a query sent then is never answered, and the node
|
||||
// stays pending for the rest of the session. Sending the query again is the
|
||||
// only way out; the answer then fills the node and runs every callback on it
|
||||
// through the engine's own receive.
|
||||
|
||||
namespace Cache::Query {
|
||||
|
||||
// Sends `cache`'s query for `key` exactly as its `_GetRecord` does for a new
|
||||
// node: the cache's opcode, the key, and a zero GUID when the cache's owner
|
||||
// flag is set.
|
||||
void Send(void *cache, uint32_t key);
|
||||
|
||||
} // namespace Cache::Query
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user