mirror of
https://github.com/brues-code/ClassicAPI.git
synced 2026-11-11 12:27:35 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d7103de564 | ||
|
|
c00eb24a8d | ||
|
|
b65c9e0319 | ||
|
|
de033896b1 | ||
|
|
dc8d4caf12 | ||
|
|
20069f3815 | ||
|
|
f2fa112f0a | ||
|
|
fca967c827 | ||
|
|
24404b5a23 | ||
|
|
a106d86969 | ||
|
|
fac3be3a0b | ||
|
|
b49c107778 | ||
|
|
53b7f79440 | ||
|
|
7b21453469 | ||
|
|
ebfd9d034d | ||
|
|
d825bcbdda | ||
|
|
6b36bb10e6 | ||
|
|
6628dcca19 | ||
|
|
55d94c80d6 | ||
|
|
c0b403ba05 | ||
|
|
f6b98bc3ec | ||
|
|
8f4f574174 | ||
|
|
43a989dd56 | ||
|
|
0caddb8fe6 | ||
|
|
8e603a7a0b | ||
|
|
4726fd7c85 | ||
|
|
3e0c40184b | ||
|
|
b3e8d92b03 | ||
|
|
0a3f8324ea | ||
|
|
6f3a8ffc1d | ||
|
|
3862408e1a | ||
|
|
12a81f7f89 | ||
|
|
05fa5845b7 | ||
|
|
6ed0edc947 | ||
|
|
1645e6b43c | ||
|
|
efcdc54a50 | ||
|
|
6a24271cd1 | ||
|
|
a7ce7555f0 | ||
|
|
04790cb6c1 | ||
|
|
e7ecae56da | ||
|
|
65c6b0b271 | ||
|
|
5f94fb98bd | ||
|
|
426f6b6ec9 | ||
|
|
3a4d291748 | ||
|
|
1cdd46958f | ||
|
|
72f0e5d98f | ||
|
|
ceb6aaf46b | ||
|
|
84c936faa4 | ||
|
|
957d66af49 | ||
|
|
3849b7513b | ||
|
|
1cdd443e53 | ||
|
|
ada33825ad | ||
|
|
dd584703a2 | ||
|
|
5911298acd | ||
|
|
a6fa06faa0 | ||
|
|
045ab77508 | ||
|
|
ac5df0fab8 | ||
|
|
48822978c6 | ||
|
|
f061179646 | ||
|
|
f8a796ae04 | ||
|
|
aff52e0ef6 | ||
|
|
aef68d5ea4 | ||
|
|
cc1e70a641 | ||
|
|
f1843afc0f | ||
|
|
f8304c06f7 | ||
|
|
2396d44f10 | ||
|
|
1ee80b74e9 | ||
|
|
932e6ed82f | ||
|
|
b032dc09ac | ||
|
|
eb0b70bc5e | ||
|
|
238e35ae53 | ||
|
|
5b7fe94d4d | ||
|
|
43594398f0 | ||
|
|
2eef939b5a | ||
|
|
36f3661b98 | ||
|
|
4f3ee595e7 | ||
|
|
99f72aa631 | ||
|
|
9e5c0c558a | ||
|
|
b3b950f2d8 | ||
|
|
5dcf10a9fd | ||
|
|
3ef6c4ffed | ||
|
|
1ef8c5597a | ||
|
|
9b0aa46ff0 | ||
|
|
84171bef2d | ||
|
|
f19f13d44c | ||
|
|
4509da0966 | ||
|
|
38d5c6c7b6 | ||
|
|
be5ebd4017 | ||
|
|
44f9bcd9af | ||
|
|
f9ec92014c | ||
|
|
264af04ee3 | ||
|
|
2063507fb4 | ||
|
|
090cfc3bfd | ||
|
|
d1cdb47c3e | ||
|
|
237e5a7500 | ||
|
|
d339f4486d | ||
|
|
92025896b5 | ||
|
|
4eb214f7f1 | ||
|
|
706fb1c540 | ||
|
|
e37052c67d | ||
|
|
f8f6dc28b8 | ||
|
|
4472c81137 | ||
|
|
1e1463cf9a | ||
|
|
c21e44e086 | ||
|
|
e76616de83 | ||
|
|
92794a1822 | ||
|
|
ab0991f054 | ||
|
|
26c201b95b | ||
|
|
09693af5b9 | ||
|
|
f24b7e594b | ||
|
|
35c8ba5688 | ||
|
|
e2a34bd18a | ||
|
|
2f787889f7 | ||
|
|
9967cc0839 | ||
|
|
e47e881ae1 | ||
|
|
d9da100110 | ||
|
|
00cfe0c45b | ||
|
|
d92464b86c | ||
|
|
fec127c1af | ||
|
|
37ee71c663 | ||
|
|
6259e22480 | ||
|
|
474da1a5b5 | ||
|
|
6cee968a8a | ||
|
|
635c74d518 | ||
|
|
260d40f49b | ||
|
|
8f6ff33a39 | ||
|
|
5082f3c829 | ||
|
|
5d0568f759 | ||
|
|
9a78e159e7 | ||
|
|
503368623f | ||
|
|
735d304a20 | ||
|
|
29ddd78a80 | ||
|
|
b6c21216e3 | ||
|
|
6cc9d0db90 | ||
|
|
c6c201e575 | ||
|
|
77b304ae68 | ||
|
|
c965e49117 | ||
|
|
ead52e79ce | ||
|
|
7cb6cda101 | ||
|
|
5ab497f2c7 | ||
|
|
205d1fd43b | ||
|
|
950c9deb76 | ||
|
|
e7ccc11309 | ||
|
|
bab31b5f7b | ||
|
|
e0e24bab34 | ||
|
|
a46d823b01 | ||
|
|
38337c841d | ||
|
|
5a0b4f2e31 | ||
|
|
7d9dafbfcf | ||
|
|
79d4b7f44d | ||
|
|
9b07ad15df | ||
|
|
36d55ab305 | ||
|
|
ebe9b9b6de | ||
|
|
4df29722d2 | ||
|
|
086b9f9fbb | ||
|
|
bc2481395d | ||
|
|
daded912c2 | ||
|
|
a0c5c8a30c | ||
|
|
e26f8fb49e | ||
|
|
da9e9b6f55 | ||
|
|
a5e8a6f5b6 | ||
|
|
f191c53c2a | ||
|
|
797fea90ed | ||
|
|
026fe20a89 | ||
|
|
529bacd0cb | ||
|
|
c16c3a90dc | ||
|
|
ab829e98c0 | ||
|
|
602840419b | ||
|
|
40cd25315d | ||
|
|
984dc236ab | ||
|
|
cdc3506cdd | ||
|
|
6347bdd6c5 | ||
|
|
ff4a9ffd5a | ||
|
|
9541dc2949 | ||
|
|
1340cc75c7 | ||
|
|
9c50a90d34 | ||
|
|
1942383494 | ||
|
|
0f37ddc48d | ||
|
|
ac118d5305 | ||
|
|
cf645a30af | ||
|
|
fcd7e52be0 | ||
|
|
886a4cb140 | ||
|
|
e30da939ec | ||
|
|
6e4efb39f7 | ||
|
|
8c21ab4b04 | ||
|
|
7ec3829eb5 | ||
|
|
86bfd881a9 | ||
|
|
cd55ce9139 | ||
|
|
1f8042088c | ||
|
|
a86d5ec48f | ||
|
|
70dadf0449 | ||
|
|
5363434439 | ||
|
|
9bac760195 | ||
|
|
bd02983a08 | ||
|
|
852cf44b7d | ||
|
|
e59f9de5a8 | ||
|
|
59164e3575 | ||
|
|
711c810b72 | ||
|
|
dceec8b74c | ||
|
|
9edce4a9f9 | ||
|
|
4e3a18cdd1 | ||
|
|
fc8fba65cc | ||
|
|
f01a059cc0 | ||
|
|
8d22876c01 | ||
|
|
39a14054fe | ||
|
|
7e1edce462 | ||
|
|
e7b6c39ace | ||
|
|
9027e22e4f | ||
|
|
7add0fc88f | ||
|
|
04ce033907 | ||
|
|
1f3ce9229d | ||
|
|
091d2204a6 | ||
|
|
d93861d746 | ||
|
|
d9827852c7 | ||
|
|
2e75812339 | ||
|
|
1454dbe00c | ||
|
|
259071b647 | ||
|
|
2d887df71c | ||
|
|
317539dbd8 | ||
|
|
10d71371dd | ||
|
|
4959c2c38c | ||
|
|
cece5a4214 | ||
|
|
9daf3960c4 | ||
|
|
39ab9eb1ee | ||
|
|
e8bd35d8e4 | ||
|
|
f4d8f56c59 | ||
|
|
3f33320724 | ||
|
|
492085ac0c | ||
|
|
7b3b61de15 | ||
|
|
77efe8d796 | ||
|
|
8378f3c350 | ||
|
|
1a2f806f16 | ||
|
|
90be617700 | ||
|
|
45b54e89ba | ||
|
|
35b8eaa376 | ||
|
|
f5082cedee | ||
|
|
cca8ff3c55 | ||
|
|
b4256406f5 | ||
|
|
2adabbbd70 | ||
|
|
42ed0d27c7 | ||
|
|
0d19deaee0 | ||
|
|
abd5367533 | ||
|
|
3e83827ae9 | ||
|
|
443c78c453 | ||
|
|
a97909e36c | ||
|
|
89f8932b35 | ||
|
|
829b1cfed3 | ||
|
|
33804bb66d | ||
|
|
80d3e5d8d7 | ||
|
|
bfcd95504e | ||
|
|
bea82687a4 | ||
|
|
63078578b4 | ||
|
|
c7bb90895f | ||
|
|
cd7f830697 | ||
|
|
557dc2f454 | ||
|
|
6c5269e3e6 | ||
|
|
b5aed30a5d | ||
|
|
9755cd3e09 | ||
|
|
604d87b9fc | ||
|
|
6b0a74ec4b | ||
|
|
165ccf3e9c | ||
|
|
ce4f80518f | ||
|
|
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 |
@@ -10,3 +10,4 @@
|
||||
*.png binary
|
||||
*.jpg binary
|
||||
*.ico binary
|
||||
*.blp binary
|
||||
|
||||
@@ -53,7 +53,6 @@ jobs:
|
||||
build:
|
||||
needs: pick-runner
|
||||
runs-on: ${{ needs.pick-runner.outputs.label }}
|
||||
# Handed to the `mirror` job below, which cannot see this job's steps.
|
||||
outputs:
|
||||
tag: ${{ steps.ver.outputs.tag }}
|
||||
is_release: ${{ steps.ver.outputs.is_release }}
|
||||
@@ -72,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
|
||||
@@ -151,17 +150,3 @@ jobs:
|
||||
build/Release/ClassicAPI.dll
|
||||
build/Release/Crash-Symbols-Use-For-Debugging-${{ steps.ver.outputs.tag }}.zip
|
||||
generate_release_notes: true
|
||||
|
||||
# The Gitea mirror pulls commits and tags but never releases, so hand the
|
||||
# finished release across to it. A separate job on purpose: the DLL is
|
||||
# already published on GitHub by this point, so a mirror problem shows up on
|
||||
# its own instead of failing the release build. A `release: published` event
|
||||
# would not work here — releases made with the default GITHUB_TOKEN do not
|
||||
# start another workflow.
|
||||
mirror:
|
||||
needs: build
|
||||
if: needs.build.outputs.is_release == 'true'
|
||||
uses: ./.github/workflows/mirror-release.yml
|
||||
with:
|
||||
tag: ${{ needs.build.outputs.tag }}
|
||||
secrets: inherit
|
||||
|
||||
@@ -1,186 +0,0 @@
|
||||
name: Mirror release
|
||||
|
||||
# Copy a GitHub release — its notes and the files attached to it — across to
|
||||
# the Gitea mirror at https://octowow.st/git/brues/ClassicAPI.
|
||||
#
|
||||
# A Gitea pull mirror replicates commits and tags only. Releases are database
|
||||
# records with their own attachments, so they never cross: the mirror's
|
||||
# Releases page shows bare tags with nothing to download. This workflow pushes
|
||||
# them over through Gitea's API.
|
||||
#
|
||||
# ONE-TIME SETUP: on the mirror, go to Settings -> Applications -> Generate New
|
||||
# Token, tick `repository` write, and copy the token. On GitHub, add it under
|
||||
# Settings -> Secrets and variables -> Actions as `MIRROR_TOKEN`. The token
|
||||
# needs push rights on brues/ClassicAPI.
|
||||
#
|
||||
# Two ways in:
|
||||
# - `Build` calls it after every release build (see the `mirror` job there).
|
||||
# - Run it from the Actions UI with a `tag` to redo one release, or with
|
||||
# `tag` left blank to backfill every release that exists on GitHub.
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
tag:
|
||||
required: true
|
||||
type: string
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: 'Release tag to mirror (e.g. v2.0.0). Blank = every release.'
|
||||
required: false
|
||||
default: ''
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
mirror:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
# No checkout: the release files come from the GitHub release itself, so
|
||||
# this reads the same bytes a user downloads rather than a rebuild.
|
||||
- name: Push release to the mirror
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
MIRROR_TOKEN: ${{ secrets.MIRROR_TOKEN }}
|
||||
TAG: ${{ inputs.tag }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
if [ -z "${MIRROR_TOKEN:-}" ]; then
|
||||
echo "::error::MIRROR_TOKEN is not set - see the setup note at the top of .github/workflows/mirror-release.yml"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
API=https://octowow.st/git/api/v1
|
||||
MIRROR=brues/ClassicAPI
|
||||
RESP=$(mktemp)
|
||||
|
||||
# Sends one API call. Prints the HTTP status; leaves the body in $RESP.
|
||||
req() {
|
||||
local method=$1 path=$2
|
||||
shift 2
|
||||
curl -sS -m 600 -o "$RESP" -w '%{http_code}' -X "$method" \
|
||||
-H "Authorization: token $MIRROR_TOKEN" \
|
||||
-H 'Accept: application/json' \
|
||||
"$API/$path" "$@"
|
||||
}
|
||||
|
||||
fail() {
|
||||
echo "::error::$1"
|
||||
echo "the mirror replied: $(head -c 2000 "$RESP")"
|
||||
exit 1
|
||||
}
|
||||
|
||||
# A release must hang off a tag that is already on the mirror. If the
|
||||
# tag is missing the mirror has not pulled yet, so ask it to and wait.
|
||||
# Attaching to a tag the mirror does not have would let its next sync
|
||||
# turn our release back into a draft.
|
||||
ensure_tag() {
|
||||
local tag=$1 i
|
||||
if [ "$(req GET "repos/$MIRROR/tags/$tag")" = 200 ]; then
|
||||
return 0
|
||||
fi
|
||||
echo " tag $tag is not on the mirror yet - asking it to sync"
|
||||
req POST "repos/$MIRROR/mirror-sync" > /dev/null || true
|
||||
for i in $(seq 1 30); do
|
||||
sleep 10
|
||||
if [ "$(req GET "repos/$MIRROR/tags/$tag")" = 200 ]; then
|
||||
echo " tag $tag arrived after $(( i * 10 ))s"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
fail "tag $tag never reached the mirror. Sync it, then run this workflow again."
|
||||
}
|
||||
|
||||
mirror_one() {
|
||||
local tag=$1 work code id f name size have_id have_size enc
|
||||
work=$(mktemp -d)
|
||||
echo "=== $tag ==="
|
||||
|
||||
gh release view "$tag" --json tagName,name,body,isDraft,isPrerelease > "$work/gh.json"
|
||||
if [ "$(jq -r .isDraft "$work/gh.json")" = true ]; then
|
||||
echo " still a draft on GitHub - skipped"
|
||||
return 0
|
||||
fi
|
||||
|
||||
ensure_tag "$tag"
|
||||
|
||||
jq '{tag_name: .tagName,
|
||||
name: (.name // .tagName),
|
||||
body: (.body // ""),
|
||||
draft: false,
|
||||
prerelease: .isPrerelease}' "$work/gh.json" > "$work/release.json"
|
||||
|
||||
# Gitea's tag sync leaves a bare tag record behind. Patching it
|
||||
# promotes that record to a real release instead of colliding.
|
||||
code=$(req GET "repos/$MIRROR/releases/tags/$tag")
|
||||
if [ "$code" = 200 ]; then
|
||||
id=$(jq -r .id "$RESP")
|
||||
code=$(req PATCH "repos/$MIRROR/releases/$id" \
|
||||
-H 'Content-Type: application/json' --data-binary @"$work/release.json")
|
||||
if [ "$code" != 200 ]; then
|
||||
fail "could not update release $tag on the mirror (HTTP $code)"
|
||||
fi
|
||||
echo " updated release #$id"
|
||||
else
|
||||
code=$(req POST "repos/$MIRROR/releases" \
|
||||
-H 'Content-Type: application/json' --data-binary @"$work/release.json")
|
||||
if [ "$code" != 201 ]; then
|
||||
fail "could not create release $tag on the mirror (HTTP $code)"
|
||||
fi
|
||||
id=$(jq -r .id "$RESP")
|
||||
echo " created release #$id"
|
||||
fi
|
||||
|
||||
mkdir -p "$work/assets"
|
||||
# Exits non-zero when the release carries no files, which is fine.
|
||||
gh release download "$tag" --dir "$work/assets" --clobber || true
|
||||
|
||||
code=$(req GET "repos/$MIRROR/releases/$id/assets")
|
||||
if [ "$code" != 200 ]; then
|
||||
fail "could not list the mirror's attachments for $tag (HTTP $code)"
|
||||
fi
|
||||
cp "$RESP" "$work/have.json"
|
||||
|
||||
for f in "$work"/assets/*; do
|
||||
[ -f "$f" ] || continue
|
||||
name=$(basename "$f")
|
||||
size=$(stat -c %s "$f")
|
||||
have_id=$(jq -r --arg n "$name" 'map(select(.name == $n)) | .[0].id // ""' "$work/have.json")
|
||||
have_size=$(jq -r --arg n "$name" 'map(select(.name == $n)) | .[0].size // ""' "$work/have.json")
|
||||
|
||||
# Same name and same size: already mirrored. A size mismatch means
|
||||
# a re-cut release, so replace it - Gitea would otherwise keep both
|
||||
# and serve the stale one from the older link.
|
||||
if [ -n "$have_id" ] && [ "$have_size" = "$size" ]; then
|
||||
echo " $name is already there"
|
||||
continue
|
||||
fi
|
||||
if [ -n "$have_id" ]; then
|
||||
req DELETE "repos/$MIRROR/releases/$id/assets/$have_id" > /dev/null
|
||||
fi
|
||||
|
||||
enc=$(jq -rn --arg n "$name" '$n | @uri')
|
||||
code=$(req POST "repos/$MIRROR/releases/$id/assets?name=$enc" -F "attachment=@$f")
|
||||
if [ "$code" != 201 ]; then
|
||||
fail "could not upload $name (HTTP $code)"
|
||||
fi
|
||||
echo " uploaded $name ($size bytes)"
|
||||
done
|
||||
}
|
||||
|
||||
if [ -n "${TAG:-}" ]; then
|
||||
mirror_one "$TAG"
|
||||
else
|
||||
echo "no tag given - backfilling every release on GitHub"
|
||||
gh release list --limit 200 --json tagName --jq '.[].tagName' > /tmp/tags.txt
|
||||
# fd 3 keeps gh and curl from eating the tag list off stdin.
|
||||
while read -r t <&3; do
|
||||
if [ -n "$t" ]; then
|
||||
mirror_one "$t"
|
||||
fi
|
||||
done 3< /tmp/tags.txt
|
||||
fi
|
||||
+1
-1
@@ -47,4 +47,4 @@
|
||||
|
||||
CLAUDE.md
|
||||
|
||||
/AddOns/!!!ClassicAPI/.classicapi-dev
|
||||
/src/embed/AddOns/*/.classicapi-dev
|
||||
|
||||
@@ -7,3 +7,6 @@
|
||||
[submodule "external/tinycbor"]
|
||||
path = external/tinycbor
|
||||
url = https://github.com/intel/tinycbor.git
|
||||
[submodule "external/unordered_dense"]
|
||||
path = external/unordered_dense
|
||||
url = https://github.com/martinus/unordered_dense.git
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
## Interface: 11200
|
||||
## Title: !!!ClassicAPI
|
||||
## Notes: Library to emulate aspects of the modern WoW API on 1.12.1 / Lua 5.0.
|
||||
## Version: DEV
|
||||
## Author: Brues
|
||||
## X-Website: https://github.com/brues-code/ClassicAPI
|
||||
|
||||
locales\locales.xml
|
||||
|
||||
SecureTemplates.xml
|
||||
Compat.lua
|
||||
Util\Print.lua
|
||||
Util\Mixin.lua
|
||||
Util\Color.lua
|
||||
Util\Constants.lua
|
||||
Util\TableUtil.lua
|
||||
Util\MathUtil.lua
|
||||
Util\PixelUtil.lua
|
||||
Util\FrameUtil.lua
|
||||
Util\FormattingUtil.lua
|
||||
Util\TimeUtil.lua
|
||||
Util\CallbackRegistry.lua
|
||||
Util\GlobalCallbackRegistry.lua
|
||||
Util\ColorUtil.lua
|
||||
Util\ItemLocation.lua
|
||||
Util\PlayerLocation.lua
|
||||
Util\EventUtil.lua
|
||||
Util\ItemUtil.lua
|
||||
Util\AddOnCompat.lua
|
||||
Util\FunctionUtil.lua
|
||||
Util\CacheUtil.lua
|
||||
Util\Pools.lua
|
||||
Util\FrameWatcher.lua
|
||||
Util\TimedCallback.lua
|
||||
Util\EquipmentManager.lua
|
||||
Util\PlayerUtil.lua
|
||||
Util\SlashCommandsRegistry.lua
|
||||
Util\LinkUtil.lua
|
||||
Util\TradeSkillLink.lua
|
||||
Util\IconDataProvider.lua
|
||||
Util\GameTooltip.lua
|
||||
Util\Rectangle.lua
|
||||
Util\Vector2D.lua
|
||||
Util\Vector3D.lua
|
||||
Util\Vector4D.lua
|
||||
Util\UiMapPoint.lua
|
||||
Util\UIParent.lua
|
||||
Util\AuraDurationModifiers.lua
|
||||
Util\AuraUtil.lua
|
||||
Util\SecureUnitMenu.lua
|
||||
Util\TextureUtil.lua
|
||||
Util\MacroOptions.lua
|
||||
Util\SecureStateDriver.lua
|
||||
Util\MacroIconSelection.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
|
||||
@@ -1,3 +0,0 @@
|
||||
if not _G then
|
||||
_G = getfenv(0)
|
||||
end
|
||||
@@ -1,215 +0,0 @@
|
||||
-- Backport of 3.3.5 FrameXML/CallbackRegistryMixin.lua to vanilla 1.12 / Lua 5.0.
|
||||
--
|
||||
-- Implementation differences from the 3.3.5 source:
|
||||
-- - 1.12 has no taint or Secure-Templates system, so the entire
|
||||
-- AttributeDelegate/SetForbidden machinery for inserting event keys
|
||||
-- into the callback tables is unnecessary. Sub-tables are allocated
|
||||
-- lazily inside RegisterCallback instead.
|
||||
-- - securecallfunction/secureexecuterange don't exist; they reduce to
|
||||
-- direct calls / explicit for-loops here.
|
||||
-- - EnumUtil.MakeEnum is inlined as a plain string table.
|
||||
-- - GenerateClosure doesn't exist in 1.12; provide a local one that
|
||||
-- captures registration-time varargs via SafePack-style storage.
|
||||
-- - Lua 5.0 has no select() or `wipe()`; we use the implicit `arg`
|
||||
-- table and assign-nil to clear tables.
|
||||
|
||||
local generateOwnerID = CreateCounter()
|
||||
|
||||
local CallbackType = { Closure = "Closure", Function = "Function" }
|
||||
|
||||
-- Local GenerateClosure: binds `func` plus all of `...` so a later call
|
||||
-- invokes func(boundArgs..., callArgs...). Mirrors 3.3.5's helper of the
|
||||
-- same name. SafePack/SafeUnpack semantics so embedded nils survive.
|
||||
local function GenerateClosure(func, ...)
|
||||
local boundN = arg.n
|
||||
local bound = {}
|
||||
for i = 1, boundN do bound[i] = arg[i] end
|
||||
return function(...)
|
||||
local callN = arg.n
|
||||
-- Forward bound + call args faithfully, embedded/leading nils and all.
|
||||
-- The ONLY thing that makes unpack span holes on this Lua 5.0 build is
|
||||
-- a `.n` field: unpack takes its count from getn (which returns t.n)
|
||||
-- and ignores any explicit i/j, so a `.n`-less table stops dead at the
|
||||
-- first hole (verified: unpack({1, 1, nil, 1}, 1, 4) yields just 1, 1).
|
||||
local all = {}
|
||||
local n = 0
|
||||
for i = 1, boundN do n = n + 1; all[n] = bound[i] end
|
||||
for i = 1, callN do n = n + 1; all[n] = arg[i] end
|
||||
all.n = n
|
||||
return func(unpack(all))
|
||||
end
|
||||
end
|
||||
|
||||
CallbackRegistryMixin = CallbackRegistryMixin or {}
|
||||
|
||||
function CallbackRegistryMixin:OnLoad()
|
||||
local callbackTables = {}
|
||||
for _, value in pairs(CallbackType) do
|
||||
callbackTables[value] = {}
|
||||
end
|
||||
self.callbackTables = callbackTables
|
||||
end
|
||||
|
||||
function CallbackRegistryMixin:SetUndefinedEventsAllowed(allowed)
|
||||
self.isUndefinedEventAllowed = allowed
|
||||
end
|
||||
|
||||
function CallbackRegistryMixin:GetCallbackTables()
|
||||
return self.callbackTables
|
||||
end
|
||||
|
||||
function CallbackRegistryMixin:GetCallbackTable(callbackType)
|
||||
return self.callbackTables[callbackType]
|
||||
end
|
||||
|
||||
function CallbackRegistryMixin:GetCallbacksByEvent(callbackType, event)
|
||||
local callbackTable = self:GetCallbackTable(callbackType)
|
||||
return callbackTable[event]
|
||||
end
|
||||
|
||||
function CallbackRegistryMixin:HasRegistrantsForEvent(event)
|
||||
for _, callbackTable in pairs(self:GetCallbackTables()) do
|
||||
local callbacks = callbackTable[event]
|
||||
if callbacks and next(callbacks) then
|
||||
return true
|
||||
end
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
-- Lazy allocation of per-event sub-tables. In 3.3.5 this went through a
|
||||
-- forbidden attribute frame for taint-isolation reasons; that's a no-op
|
||||
-- consideration on 1.12, so we just assign here.
|
||||
function CallbackRegistryMixin:SecureInsertEvent(event)
|
||||
for _, callbackTable in pairs(self:GetCallbackTables()) do
|
||||
if not callbackTable[event] then
|
||||
callbackTable[event] = {}
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function CallbackRegistryMixin:RegisterCallback(event, func, owner, ...)
|
||||
if type(event) ~= "string" then
|
||||
error("CallbackRegistryMixin::RegisterCallback 'event' requires string type.")
|
||||
elseif type(func) ~= "function" then
|
||||
error("CallbackRegistryMixin::RegisterCallback 'func' requires function type.")
|
||||
else
|
||||
if owner == nil then
|
||||
owner = generateOwnerID()
|
||||
elseif type(owner) == "number" then
|
||||
error("CallbackRegistryMixin:RegisterCallback 'owner' as number is reserved internally.")
|
||||
end
|
||||
end
|
||||
|
||||
self:SecureInsertEvent(event)
|
||||
|
||||
for _, callbackTable in pairs(self:GetCallbackTables()) do
|
||||
local callbacks = callbackTable[event]
|
||||
callbacks[owner] = nil
|
||||
end
|
||||
|
||||
if arg.n > 0 then
|
||||
local callbacks = self:GetCallbacksByEvent(CallbackType.Closure, event)
|
||||
callbacks[owner] = GenerateClosure(func, owner, unpack(arg))
|
||||
else
|
||||
local callbacks = self:GetCallbacksByEvent(CallbackType.Function, event)
|
||||
callbacks[owner] = func
|
||||
end
|
||||
|
||||
return owner
|
||||
end
|
||||
|
||||
local function CreateCallbackHandle(cbr, event, owner)
|
||||
local handle =
|
||||
{
|
||||
Unregister = function()
|
||||
cbr:UnregisterCallback(event, owner)
|
||||
end,
|
||||
}
|
||||
return handle
|
||||
end
|
||||
|
||||
function CallbackRegistryMixin:RegisterCallbackWithHandle(event, func, owner, ...)
|
||||
owner = self:RegisterCallback(event, func, owner, unpack(arg))
|
||||
return CreateCallbackHandle(self, event, owner)
|
||||
end
|
||||
|
||||
function CallbackRegistryMixin:TriggerEvent(event, ...)
|
||||
if type(event) ~= "string" then
|
||||
error("CallbackRegistryMixin:TriggerEvent 'event' requires string type.")
|
||||
elseif not self.isUndefinedEventAllowed and not (self.Event and self.Event[event]) then
|
||||
error(string.format("CallbackRegistryMixin:TriggerEvent event '%s' doesn't exist.", event))
|
||||
end
|
||||
|
||||
local closures = self:GetCallbacksByEvent(CallbackType.Closure, event)
|
||||
if closures then
|
||||
for _, closure in pairs(closures) do
|
||||
closure(unpack(arg))
|
||||
end
|
||||
end
|
||||
|
||||
local funcs = self:GetCallbacksByEvent(CallbackType.Function, event)
|
||||
if funcs then
|
||||
for owner, func in pairs(funcs) do
|
||||
-- Stock 3.3.5 passes the owner as the first arg so callers can
|
||||
-- distinguish multiple registrations of the same function. `arg`
|
||||
-- carries its own `.n`, so unpack(arg) forwards the payload with
|
||||
-- leading/embedded nils intact. Do NOT instead merge into a
|
||||
-- `{ owner, ... }` table and unpack that WITHOUT setting `.n`: this
|
||||
-- build's unpack counts via getn, so a `.n`-less table collapses at
|
||||
-- the first hole (verified in-game: reload's PLAYER_ENTERING_WORLD,
|
||||
-- arg1=nil arg2=1, dropped the payload).
|
||||
func(owner, unpack(arg))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function CallbackRegistryMixin:UnregisterCallback(event, owner)
|
||||
if type(event) ~= "string" then
|
||||
error("CallbackRegistryMixin:UnregisterCallback 'event' requires string type.")
|
||||
elseif owner == nil then
|
||||
error("CallbackRegistryMixin:UnregisterCallback 'owner' is required.")
|
||||
end
|
||||
|
||||
for _, callbackTable in pairs(self:GetCallbackTables()) do
|
||||
local callbacks = callbackTable[event]
|
||||
if callbacks then
|
||||
callbacks[owner] = nil
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function CallbackRegistryMixin:UnregisterEvents(eventTable)
|
||||
if eventTable then
|
||||
for _, callbackTable in pairs(self:GetCallbackTables()) do
|
||||
for event in pairs(eventTable) do
|
||||
if callbackTable[event] then
|
||||
callbackTable[event] = nil
|
||||
end
|
||||
end
|
||||
end
|
||||
else
|
||||
for _, callbackTable in pairs(self:GetCallbackTables()) do
|
||||
for k in pairs(callbackTable) do
|
||||
callbackTable[k] = nil
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function CallbackRegistryMixin:GenerateCallbackEvents(events)
|
||||
if not self.Event then
|
||||
self.Event = {}
|
||||
end
|
||||
|
||||
for eventIndex, eventName in ipairs(events) do
|
||||
if self.Event[eventName] then
|
||||
error(string.format("CallbackRegistryMixin:GenerateCallbackEvents: event '%s' already exists.", eventName))
|
||||
end
|
||||
self.Event[eventName] = eventName
|
||||
end
|
||||
end
|
||||
|
||||
function CallbackRegistryMixin.DoesFrameHaveEvent(frame, event)
|
||||
return frame.Event and frame.Event[event]
|
||||
end
|
||||
@@ -1,140 +0,0 @@
|
||||
|
||||
|
||||
-- Item location bitflags (Using tonumber because lua 5.0 doesn't support hexadecimal literals. 0x)
|
||||
ITEM_INVENTORY_LOCATION_PLAYER = tonumber("0x00100000", 16);
|
||||
ITEM_INVENTORY_LOCATION_BAGS = tonumber("0x00200000", 16);
|
||||
ITEM_INVENTORY_LOCATION_BANK = tonumber("0x00400000", 16);
|
||||
ITEM_INVENTORY_BAG_BIT_OFFSET = 8; -- Number of bits that the bag index in GetInventoryItemsForSlot gets shifted to the left.
|
||||
ITEM_INVENTORY_BANK_BAG_OFFSET = 4;
|
||||
|
||||
-- Inventory slots
|
||||
INVSLOT_AMMO = 0;
|
||||
INVSLOT_HEAD = 1; INVSLOT_FIRST_EQUIPPED = INVSLOT_HEAD;
|
||||
INVSLOT_NECK = 2;
|
||||
INVSLOT_SHOULDER = 3;
|
||||
INVSLOT_BODY = 4;
|
||||
INVSLOT_CHEST = 5;
|
||||
INVSLOT_WAIST = 6;
|
||||
INVSLOT_LEGS = 7;
|
||||
INVSLOT_FEET = 8;
|
||||
INVSLOT_WRIST = 9;
|
||||
INVSLOT_HAND = 10;
|
||||
INVSLOT_FINGER1 = 11;
|
||||
INVSLOT_FINGER2 = 12;
|
||||
INVSLOT_TRINKET1 = 13;
|
||||
INVSLOT_TRINKET2 = 14;
|
||||
INVSLOT_BACK = 15;
|
||||
INVSLOT_MAINHAND = 16;
|
||||
INVSLOT_OFFHAND = 17;
|
||||
INVSLOT_RANGED = 18;
|
||||
INVSLOT_TABARD = 19; INVSLOT_LAST_EQUIPPED = INVSLOT_TABARD;
|
||||
|
||||
INVSLOTS_EQUIPABLE_IN_COMBAT = {
|
||||
[INVSLOT_MAINHAND] = true,
|
||||
[INVSLOT_OFFHAND] = true,
|
||||
[INVSLOT_RANGED] = true,
|
||||
}
|
||||
|
||||
-- Item IDs
|
||||
HEARTHSTONE_ITEM_ID = 6948;
|
||||
|
||||
--
|
||||
-- Equipment Set
|
||||
--
|
||||
MAX_EQUIPMENT_SETS_PER_PLAYER = 10;
|
||||
EQUIPMENT_SET_EMPTY_SLOT = 0;
|
||||
EQUIPMENT_SET_IGNORED_SLOT = 1;
|
||||
EQUIPMENT_SET_ITEM_MISSING = -1;
|
||||
|
||||
--
|
||||
-- Totems
|
||||
--
|
||||
|
||||
MAX_TOTEMS = 4;
|
||||
|
||||
FIRE_TOTEM_SLOT = 1;
|
||||
EARTH_TOTEM_SLOT = 2;
|
||||
WATER_TOTEM_SLOT = 3;
|
||||
AIR_TOTEM_SLOT = 4;
|
||||
|
||||
STANDARD_TOTEM_PRIORITIES = {1, 2, 3, 4};
|
||||
|
||||
SHAMAN_TOTEM_PRIORITIES = {
|
||||
EARTH_TOTEM_SLOT,
|
||||
FIRE_TOTEM_SLOT,
|
||||
WATER_TOTEM_SLOT,
|
||||
AIR_TOTEM_SLOT,
|
||||
};
|
||||
|
||||
-- Druid Forms.
|
||||
CAT_FORM = 1;
|
||||
BEAR_FORM = 5;
|
||||
|
||||
--
|
||||
-- Class
|
||||
--
|
||||
CLASS_SORT_ORDER = {
|
||||
"WARRIOR",
|
||||
"PALADIN",
|
||||
"PRIEST",
|
||||
"SHAMAN",
|
||||
"DRUID",
|
||||
"ROGUE",
|
||||
"MAGE",
|
||||
"WARLOCK",
|
||||
"HUNTER",
|
||||
};
|
||||
MAX_CLASSES = table.getn(CLASS_SORT_ORDER);
|
||||
|
||||
LOCALIZED_CLASS_NAMES_MALE = {};
|
||||
LOCALIZED_CLASS_NAMES_FEMALE = {};
|
||||
FillLocalizedClassList(LOCALIZED_CLASS_NAMES_MALE, false);
|
||||
FillLocalizedClassList(LOCALIZED_CLASS_NAMES_FEMALE, true);
|
||||
|
||||
--
|
||||
-- Inventory
|
||||
--
|
||||
BAG_ITEM_QUALITY_COLORS =
|
||||
{
|
||||
[LE_ITEM_QUALITY_COMMON] = COMMON_GRAY_COLOR,
|
||||
[LE_ITEM_QUALITY_UNCOMMON] = UNCOMMON_GREEN_COLOR,
|
||||
[LE_ITEM_QUALITY_RARE] = RARE_BLUE_COLOR,
|
||||
[LE_ITEM_QUALITY_EPIC] = EPIC_PURPLE_COLOR,
|
||||
[LE_ITEM_QUALITY_LEGENDARY] = LEGENDARY_ORANGE_COLOR,
|
||||
[LE_ITEM_QUALITY_ARTIFACT] = ARTIFACT_GOLD_COLOR,
|
||||
};
|
||||
|
||||
-- faction
|
||||
PLAYER_FACTION_GROUP = { [0] = "Horde", [1] = "Alliance", Horde = 0, Alliance = 1 };
|
||||
|
||||
FACTION_LABELS = {
|
||||
[0] = FACTION_HORDE,
|
||||
[1] = FACTION_ALLIANCE,
|
||||
};
|
||||
|
||||
FACTION_LABELS_FROM_STRING = {
|
||||
["Horde"] = FACTION_HORDE,
|
||||
["Alliance"] = FACTION_ALLIANCE,
|
||||
}
|
||||
|
||||
PLAYER_FACTION_COLORS =
|
||||
{
|
||||
[0] = PLAYER_FACTION_COLOR_HORDE,
|
||||
[1] = PLAYER_FACTION_COLOR_ALLIANCE,
|
||||
};
|
||||
|
||||
--
|
||||
-- Glyph
|
||||
--
|
||||
INSCRIPTION_AVAILABLE = false;
|
||||
|
||||
-- PaperDollFrame.lua
|
||||
EQUIPPED_FIRST = 1;
|
||||
EQUIPPED_LAST = 19;
|
||||
|
||||
BASE_MOVEMENT_SPEED = 7;
|
||||
|
||||
UPPER_LEFT_VERTEX = 1;
|
||||
LOWER_LEFT_VERTEX = 2;
|
||||
UPPER_RIGHT_VERTEX = 3;
|
||||
LOWER_RIGHT_VERTEX = 4;
|
||||
@@ -1,110 +0,0 @@
|
||||
-- Backport of FrameXML/FormattingUtil.lua (feasible subset) to vanilla
|
||||
-- 1.12 / Lua 5.0.
|
||||
--
|
||||
-- 5.0 notes: no `#`/`%`/string-method syntax — uses string.*, math.mod.
|
||||
-- GetMoneyString gives the text-symbol form ("12g 34s 56c"). The coin-icon form
|
||||
-- (GetCoinTextureString / C_CurrencyInfo.GetCoinTextureString) is provided by the
|
||||
-- ClassicAPI DLL in C++ (src/currency/CoinText.cpp) — like retail, where it's a
|
||||
-- C function — now that the inline-texture backport renders |T markup in 1.12.
|
||||
--
|
||||
-- The FrameXML format-string globals these functions consume
|
||||
-- (LARGE_NUMBER_SEPERATOR, PERCENTAGE_STRING, GOLD_AMOUNT_SYMBOL,
|
||||
-- GOLD_AMOUNT_TEXTURE, …) are defined in the locale layer (locales/enUS.lua),
|
||||
-- which loads first.
|
||||
|
||||
COPPER_PER_SILVER = 100;
|
||||
SILVER_PER_GOLD = 100;
|
||||
COPPER_PER_GOLD = COPPER_PER_SILVER * SILVER_PER_GOLD;
|
||||
|
||||
function FormatLargeNumber(amount)
|
||||
amount = tostring(amount);
|
||||
local newDisplay = "";
|
||||
local strlen = string.len(amount);
|
||||
-- Insert a separator before each group of three trailing digits.
|
||||
for i = 4, strlen, 3 do
|
||||
newDisplay = LARGE_NUMBER_SEPERATOR ..
|
||||
string.sub(amount, -(i - 1), -(i - 3)) .. newDisplay;
|
||||
end
|
||||
-- Prepend everything before the first separator.
|
||||
local lead = (math.mod(strlen, 3) == 0) and 3 or math.mod(strlen, 3);
|
||||
newDisplay = string.sub(amount, 1, lead) .. newDisplay;
|
||||
return newDisplay;
|
||||
end
|
||||
|
||||
function FormatPercentage(percentage, roundToNearestInteger)
|
||||
if roundToNearestInteger then
|
||||
percentage = Round(percentage * 100);
|
||||
else
|
||||
percentage = percentage * 100;
|
||||
end
|
||||
return string.format(PERCENTAGE_STRING, percentage);
|
||||
end
|
||||
|
||||
function FormatFraction(numerator, denominator)
|
||||
return string.format(GENERIC_FRACTION_STRING, numerator, denominator);
|
||||
end
|
||||
|
||||
function SplitTextIntoLines(text, delimiter)
|
||||
local lines = {};
|
||||
local startIndex = 1;
|
||||
local foundIndex = string.find(text, delimiter);
|
||||
while foundIndex do
|
||||
table.insert(lines, string.sub(text, startIndex, foundIndex - 1));
|
||||
startIndex = foundIndex + 2;
|
||||
foundIndex = string.find(text, delimiter, startIndex);
|
||||
end
|
||||
if startIndex <= string.len(text) then
|
||||
table.insert(lines, string.sub(text, startIndex));
|
||||
end
|
||||
return lines;
|
||||
end
|
||||
|
||||
function SplitTextIntoHeaderAndNonHeader(text)
|
||||
local foundIndex = string.find(text, "|n");
|
||||
local len = string.len(text);
|
||||
if not foundIndex then
|
||||
return text; -- no newline: whole thing is a header
|
||||
elseif len == 2 then
|
||||
return nil; -- the string was just a newline
|
||||
elseif foundIndex == 1 then
|
||||
return string.sub(text, 3); -- leading newline: rest is a header
|
||||
elseif foundIndex == len - 1 then
|
||||
return string.sub(text, 1, foundIndex - 1); -- trailing newline
|
||||
else
|
||||
return string.sub(text, 1, foundIndex - 1), string.sub(text, foundIndex + 2);
|
||||
end
|
||||
end
|
||||
|
||||
-- (money, separateThousands [, checkGoldThreshold, showZeroAsGold])
|
||||
-- Text-symbol form ("12g 34s 56c"); for the coin-icon form use
|
||||
-- GetCoinTextureString below. The checkGoldThreshold arg is accepted for
|
||||
-- signature compatibility but not applied (it relied on modern Constants tables).
|
||||
function GetMoneyString(money, separateThousands, checkGoldThreshold, showZeroAsGold)
|
||||
local gold = math.floor(money / COPPER_PER_GOLD);
|
||||
local silver = math.floor(math.mod(money, COPPER_PER_GOLD) / COPPER_PER_SILVER);
|
||||
local copper = math.mod(money, COPPER_PER_SILVER);
|
||||
|
||||
local goldString = (separateThousands and FormatLargeNumber(gold) or tostring(gold)) ..
|
||||
GOLD_AMOUNT_SYMBOL;
|
||||
local silverString = silver .. SILVER_AMOUNT_SYMBOL;
|
||||
local copperString = copper .. COPPER_AMOUNT_SYMBOL;
|
||||
|
||||
if showZeroAsGold and money == 0 then
|
||||
return goldString;
|
||||
end
|
||||
|
||||
local moneyString = "";
|
||||
local separator = "";
|
||||
if gold > 0 then
|
||||
moneyString = goldString;
|
||||
separator = " ";
|
||||
end
|
||||
if silver > 0 then
|
||||
moneyString = moneyString .. separator .. silverString;
|
||||
separator = " ";
|
||||
end
|
||||
if copper > 0 or moneyString == "" then
|
||||
moneyString = moneyString .. separator .. copperString;
|
||||
end
|
||||
return moneyString;
|
||||
end
|
||||
@@ -1,70 +0,0 @@
|
||||
-- Backport of FrameXML/FrameUtil.lua (core subset) to vanilla 1.12.
|
||||
--
|
||||
-- Only the dependency-light, commonly-called helpers are ported. Omitted:
|
||||
-- - the fade/flash functions (UIFrameFade*/UIFrameFlash*) are already
|
||||
-- native in 1.12.
|
||||
-- - the scale/layout/secure/EventRegistry helpers (rely on APIs absent
|
||||
-- here).
|
||||
|
||||
FrameUtil = FrameUtil or {};
|
||||
|
||||
function FrameUtil.RegisterFrameForEvents(frame, events)
|
||||
for i, event in ipairs(events) do
|
||||
frame:RegisterEvent(event);
|
||||
end
|
||||
end
|
||||
|
||||
function FrameUtil.RegisterFrameForUnitEvents(frame, events, ...)
|
||||
for i, event in ipairs(events) do
|
||||
frame:RegisterUnitEvent(event, unpack(arg));
|
||||
end
|
||||
end
|
||||
|
||||
function FrameUtil.UnregisterFrameForEvents(frame, events)
|
||||
for i, event in ipairs(events) do
|
||||
frame:UnregisterEvent(event);
|
||||
end
|
||||
end
|
||||
|
||||
function FrameUtil.GetRootParent(frame)
|
||||
local parent = frame:GetParent();
|
||||
while parent do
|
||||
local nextParent = parent:GetParent();
|
||||
if not nextParent then
|
||||
break;
|
||||
end
|
||||
parent = nextParent;
|
||||
end
|
||||
return parent;
|
||||
end
|
||||
|
||||
-- Reparents while preserving the frame's render layering.
|
||||
function FrameUtil.SetParentMaintainRenderLayering(frame, parent)
|
||||
local origStrata = frame:GetFrameStrata();
|
||||
local origFrameLevel = frame:GetFrameLevel();
|
||||
frame:SetParent(parent);
|
||||
frame:SetFrameStrata(origStrata);
|
||||
frame:SetFrameLevel(origFrameLevel);
|
||||
end
|
||||
|
||||
function DoesAncestryInclude(ancestry, frame)
|
||||
if ancestry then
|
||||
local currentFrame = frame;
|
||||
while currentFrame do
|
||||
if currentFrame == ancestry then
|
||||
return true;
|
||||
end
|
||||
currentFrame = currentFrame:GetParent();
|
||||
end
|
||||
end
|
||||
return false;
|
||||
end
|
||||
|
||||
function DoesAncestryIncludeAny(ancestry, frames)
|
||||
for _, frame in ipairs(frames) do
|
||||
if DoesAncestryInclude(ancestry, frame) then
|
||||
return true;
|
||||
end
|
||||
end
|
||||
return false;
|
||||
end
|
||||
@@ -1,415 +0,0 @@
|
||||
-- Backport of 3.3.5 FrameXML/ItemUtil.lua to vanilla 1.12 / Lua 5.0.
|
||||
--
|
||||
-- Implementation differences from the 3.3.5 source:
|
||||
-- - Many C_Item.* calls the modern code expects are not exposed by
|
||||
-- ClassicAPI.dll. We shim the missing ones at the top using the
|
||||
-- stock 1.12 globals (GetItemInfo, GetInventoryItemLink,
|
||||
-- GetContainerItemLink/Info). DLL-provided functions are left alone
|
||||
-- via `or` guards so we never clobber a real implementation.
|
||||
-- - Lua 5.0 has no select(); calls that previously did
|
||||
-- `select(N, GetItemInfo(...))` use named locals to peel off the
|
||||
-- return values instead.
|
||||
-- - CallErrorHandler isn't in 1.12; we route through geterrorhandler().
|
||||
-- - In 1.12 OnEvent scripts, event name + payload are exposed via the
|
||||
-- `event`, `arg1`, `arg2`... globals rather than as function args.
|
||||
-- - 1.12 has no concept of an item GUID and no public item-lock API,
|
||||
-- so those return nil / no-op.
|
||||
|
||||
----------------------------------------------------------------------
|
||||
|
||||
Item = {}
|
||||
ItemMixin = {}
|
||||
|
||||
local ItemEventListener
|
||||
|
||||
--[[static]] function Item:CreateFromItemLocation(itemLocation)
|
||||
if type(itemLocation) ~= "table" or type(itemLocation.HasAnyLocation) ~= "function" or not itemLocation:HasAnyLocation() then
|
||||
error("Usage: Item:CreateFromItemLocation(notEmptyItemLocation)", 2)
|
||||
end
|
||||
local item = CreateFromMixins(ItemMixin)
|
||||
item:SetItemLocation(itemLocation)
|
||||
return item
|
||||
end
|
||||
|
||||
--[[static]] function Item:CreateFromBagAndSlot(bagID, slotIndex)
|
||||
if type(bagID) ~= "number" or type(slotIndex) ~= "number" then
|
||||
error("Usage: Item:CreateFromBagAndSlot(bagID, slotIndex)", 2)
|
||||
end
|
||||
local item = CreateFromMixins(ItemMixin)
|
||||
item:SetItemLocation(ItemLocation:CreateFromBagAndSlot(bagID, slotIndex))
|
||||
return item
|
||||
end
|
||||
|
||||
--[[static]] function Item:CreateFromEquipmentSlot(equipmentSlotIndex)
|
||||
if type(equipmentSlotIndex) ~= "number" then
|
||||
error("Usage: Item:CreateFromEquipmentSlot(equipmentSlotIndex)", 2)
|
||||
end
|
||||
local item = CreateFromMixins(ItemMixin)
|
||||
item:SetItemLocation(ItemLocation:CreateFromEquipmentSlot(equipmentSlotIndex))
|
||||
return item
|
||||
end
|
||||
|
||||
--[[static]] function Item:CreateFromItemLink(itemLink)
|
||||
if type(itemLink) ~= "string" then
|
||||
error("Usage: Item:CreateFromItemLink(itemLinkString)", 2)
|
||||
end
|
||||
local item = CreateFromMixins(ItemMixin)
|
||||
item:SetItemLink(itemLink)
|
||||
return item
|
||||
end
|
||||
|
||||
--[[static]] function Item:CreateFromItemID(itemID)
|
||||
if type(itemID) ~= "number" then
|
||||
error("Usage: Item:CreateFromItemID(itemID)", 2)
|
||||
end
|
||||
local item = CreateFromMixins(ItemMixin)
|
||||
item:SetItemID(itemID)
|
||||
return item
|
||||
end
|
||||
|
||||
--[[static]] function Item:CreateFromItemGUID(itemGUID)
|
||||
if type(itemGUID) ~= "string" then
|
||||
error("Usage: Item:CreateFromItemGUID(itemGUIDString)", 2);
|
||||
end
|
||||
local item = CreateFromMixins(ItemMixin);
|
||||
item:SetItemGUID(itemGUID);
|
||||
return item;
|
||||
end
|
||||
|
||||
--[[static]] function Item:DoItemsMatch(item1, item2)
|
||||
if not item1 or not item2 then
|
||||
return false;
|
||||
end
|
||||
|
||||
return item1:Matches(item2);
|
||||
end
|
||||
|
||||
function ItemMixin:Matches(item)
|
||||
if not item then
|
||||
return false;
|
||||
end
|
||||
|
||||
local itemID = item:GetItemID();
|
||||
if (itemID ~= nil) and (self:GetItemID() == itemID) then
|
||||
return true;
|
||||
end
|
||||
|
||||
local itemLocation = item:GetItemLocation();
|
||||
if (itemLocation ~= nil) and itemLocation:IsEqualTo(self:GetItemLocation()) then
|
||||
return true;
|
||||
end
|
||||
|
||||
return false;
|
||||
end
|
||||
|
||||
function ItemMixin:SetItemLocation(itemLocation)
|
||||
self:Clear()
|
||||
self.itemLocation = itemLocation
|
||||
end
|
||||
|
||||
function ItemMixin:SetItemLink(itemLink)
|
||||
self:Clear()
|
||||
self.itemLink = itemLink
|
||||
end
|
||||
|
||||
function ItemMixin:SetItemID(itemID)
|
||||
self:Clear()
|
||||
self.itemID = itemID
|
||||
end
|
||||
|
||||
function ItemMixin:SetItemGUID(itemGUID)
|
||||
self:Clear();
|
||||
self.itemGUID = itemGUID;
|
||||
end
|
||||
|
||||
function ItemMixin:GetItemLocation()
|
||||
if self.itemLocation then
|
||||
return self.itemLocation;
|
||||
end
|
||||
|
||||
if self.itemGUID then
|
||||
return C_Item.GetItemLocation(self.itemGUID);
|
||||
end
|
||||
return nil;
|
||||
end
|
||||
|
||||
function ItemMixin:HasItemLocation()
|
||||
return self.itemLocation ~= nil
|
||||
end
|
||||
|
||||
function ItemMixin:Clear()
|
||||
self.itemLocation = nil
|
||||
self.itemLink = nil
|
||||
self.itemID = nil
|
||||
self.itemGUID = nil
|
||||
end
|
||||
|
||||
function ItemMixin:IsItemEmpty()
|
||||
if self:GetStaticBackingItem() then
|
||||
return not C_Item.DoesItemExistByID(self:GetStaticBackingItem())
|
||||
end
|
||||
|
||||
return not self:IsItemInPlayersControl()
|
||||
end
|
||||
|
||||
function ItemMixin:GetStaticBackingItem()
|
||||
return self.itemLink or self.itemID
|
||||
end
|
||||
|
||||
function ItemMixin:IsItemInPlayersControl()
|
||||
local itemLocation = self:GetItemLocation()
|
||||
return itemLocation and C_Item.DoesItemExist(itemLocation)
|
||||
end
|
||||
|
||||
-- Item API
|
||||
function ItemMixin:GetItemID()
|
||||
if self:GetStaticBackingItem() then
|
||||
return (C_Item.GetItemInfoInstant(self:GetStaticBackingItem()))
|
||||
end
|
||||
|
||||
if not self:IsItemEmpty() then
|
||||
return C_Item.GetItemID(self:GetItemLocation())
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
function ItemMixin:IsItemLocked()
|
||||
return self:IsItemInPlayersControl() and C_Item.IsLocked(self:GetItemLocation())
|
||||
end
|
||||
|
||||
function ItemMixin:LockItem()
|
||||
if self:IsItemInPlayersControl() then
|
||||
C_Item.LockItem(self:GetItemLocation())
|
||||
end
|
||||
end
|
||||
|
||||
function ItemMixin:UnlockItem()
|
||||
if self:IsItemInPlayersControl() then
|
||||
C_Item.UnlockItem(self:GetItemLocation())
|
||||
end
|
||||
end
|
||||
|
||||
function ItemMixin:GetItemIcon() -- requires item data to be loaded
|
||||
if self:GetStaticBackingItem() then
|
||||
return C_Item.GetItemIconByID(self:GetStaticBackingItem())
|
||||
end
|
||||
|
||||
if not self:IsItemEmpty() then
|
||||
return C_Item.GetItemIcon(self:GetItemLocation())
|
||||
end
|
||||
end
|
||||
|
||||
function ItemMixin:GetItemName() -- requires item data to be loaded
|
||||
if self:GetStaticBackingItem() then
|
||||
return C_Item.GetItemNameByID(self:GetStaticBackingItem())
|
||||
end
|
||||
|
||||
if not self:IsItemEmpty() then
|
||||
return C_Item.GetItemName(self:GetItemLocation())
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
function ItemMixin:GetItemLink() -- requires item data to be loaded
|
||||
if self.itemLink then
|
||||
return self.itemLink
|
||||
end
|
||||
|
||||
if self.itemID then
|
||||
return (select(2, C_Item.GetItemInfo(self.itemID)));
|
||||
end
|
||||
|
||||
if not self:IsItemEmpty() then
|
||||
return C_Item.GetItemLink(self:GetItemLocation())
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
function ItemMixin:GetItemQuality() -- requires item data to be loaded
|
||||
if self:GetStaticBackingItem() then
|
||||
return C_Item.GetItemQualityByID(self:GetStaticBackingItem())
|
||||
end
|
||||
|
||||
if not self:IsItemEmpty() then
|
||||
return C_Item.GetItemQuality(self:GetItemLocation())
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
function ItemMixin:GetCurrentItemLevel() -- requires item data to be loaded
|
||||
if self:GetStaticBackingItem() then
|
||||
return (C_Item.GetDetailedItemLevelInfo(self:GetStaticBackingItem()))
|
||||
end
|
||||
|
||||
if not self:IsItemEmpty() then
|
||||
return C_Item.GetCurrentItemLevel(self:GetItemLocation())
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
function ItemMixin:GetItemQualityColor() -- requires item data to be loaded
|
||||
local itemQuality = self:GetItemQuality()
|
||||
return ITEM_QUALITY_COLORS[itemQuality] -- may be nil if item data isn't loaded
|
||||
end
|
||||
|
||||
|
||||
function ItemMixin:GetItemQualityColorRGB() -- requires item data to be loaded
|
||||
local colorTbl = self:GetItemQualityColor()
|
||||
return colorTbl.color:GetRGB()
|
||||
end
|
||||
|
||||
function ItemMixin:GetItemMaxStackSize() -- requires item data to be loaded
|
||||
if self:GetStaticBackingItem() then
|
||||
return C_Item.GetItemMaxStackSizeByID(self:GetStaticBackingItem());
|
||||
end
|
||||
|
||||
if not self:IsItemEmpty() then
|
||||
return C_Item.GetItemMaxStackSize(self:GetItemLocation());
|
||||
end
|
||||
return nil;
|
||||
end
|
||||
|
||||
function ItemMixin:IsStackable() -- requires item data to be loaded
|
||||
local maxStackSize = self:GetItemMaxStackSize();
|
||||
return maxStackSize and maxStackSize > 1;
|
||||
end
|
||||
|
||||
function ItemMixin:GetInventoryType()
|
||||
if self:GetStaticBackingItem() then
|
||||
return C_Item.GetItemInventoryTypeByID(self:GetStaticBackingItem())
|
||||
end
|
||||
|
||||
if not self:IsItemEmpty() then
|
||||
return C_Item.GetItemInventoryType(self:GetItemLocation())
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
function ItemMixin:GetItemGUID()
|
||||
if self:GetStaticBackingItem() then
|
||||
return nil
|
||||
end
|
||||
|
||||
if not self:IsItemEmpty() then
|
||||
return C_Item.GetItemGUID(self:GetItemLocation())
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
function ItemMixin:GetInventoryTypeName()
|
||||
if not self:IsItemEmpty() then
|
||||
return select(4, C_Item.GetItemInfoInstant(self:GetItemID()));
|
||||
end
|
||||
end
|
||||
|
||||
function ItemMixin:IsItemDataCached()
|
||||
if self:GetStaticBackingItem() then
|
||||
return C_Item.IsItemDataCachedByID(self:GetStaticBackingItem())
|
||||
end
|
||||
|
||||
if not self:IsItemEmpty() then
|
||||
return C_Item.IsItemDataCached(self:GetItemLocation())
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
function ItemMixin:IsDataEvictable()
|
||||
return true
|
||||
end
|
||||
|
||||
-- Default error handler routing: stock 1.12 has no CallErrorHandler.
|
||||
local function ItemUtilErrorHandler(err)
|
||||
local h = geterrorhandler and geterrorhandler()
|
||||
if h then return h(err) end
|
||||
end
|
||||
|
||||
function ItemMixin:ContinueOnItemLoad(callbackFunction)
|
||||
if type(callbackFunction) ~= "function" or self:IsItemEmpty() then
|
||||
error("Usage: NonEmptyItem:ContinueOnLoad(callbackFunction)", 2)
|
||||
end
|
||||
|
||||
ItemEventListener:AddCallback(self:GetItemID(), callbackFunction)
|
||||
end
|
||||
|
||||
function ItemMixin:ContinueWithCancelOnItemLoad(callbackFunction)
|
||||
if type(callbackFunction) ~= "function" or self:IsItemEmpty() then
|
||||
error("Usage: NonEmptyItem:ContinueWithCancelOnItemLoad(callbackFunction)", 2)
|
||||
end
|
||||
|
||||
return ItemEventListener:AddCancelableCallback(self:GetItemID(), callbackFunction)
|
||||
end
|
||||
|
||||
--[ Item Event Listener ]
|
||||
|
||||
ItemEventListener = CreateFrame("Frame")
|
||||
ItemEventListener.callbacks = {}
|
||||
|
||||
-- 1.12 OnEvent receives no function args; event name and payload live in
|
||||
-- the `event`, `arg1`, ... globals.
|
||||
ItemEventListener:SetScript("OnEvent", function()
|
||||
if event == "ITEM_DATA_LOAD_RESULT" then
|
||||
local itemID, success = arg1, arg2
|
||||
if success then
|
||||
ItemEventListener:FireCallbacks(itemID)
|
||||
else
|
||||
ItemEventListener:ClearCallbacks(itemID)
|
||||
end
|
||||
end
|
||||
end)
|
||||
ItemEventListener:RegisterEvent("ITEM_DATA_LOAD_RESULT")
|
||||
|
||||
local CANCELED_SENTINEL = -1
|
||||
|
||||
function ItemEventListener:AddCallback(itemID, callbackFunction)
|
||||
local callbacks = self:GetOrCreateCallbacks(itemID)
|
||||
table.insert(callbacks, callbackFunction)
|
||||
C_Item.RequestLoadItemDataByID(itemID)
|
||||
end
|
||||
|
||||
function ItemEventListener:AddCancelableCallback(itemID, callbackFunction)
|
||||
local callbacks = self:GetOrCreateCallbacks(itemID)
|
||||
table.insert(callbacks, callbackFunction)
|
||||
C_Item.RequestLoadItemDataByID(itemID)
|
||||
|
||||
local index = table.getn(callbacks)
|
||||
return function()
|
||||
if table.getn(callbacks) > 0 and callbacks[index] ~= CANCELED_SENTINEL then
|
||||
callbacks[index] = CANCELED_SENTINEL
|
||||
return true
|
||||
end
|
||||
return false
|
||||
end
|
||||
end
|
||||
|
||||
function ItemEventListener:FireCallbacks(itemID)
|
||||
local callbacks = self:GetCallbacks(itemID)
|
||||
if callbacks then
|
||||
self:ClearCallbacks(itemID)
|
||||
for i, callback in ipairs(callbacks) do
|
||||
if callback ~= CANCELED_SENTINEL then
|
||||
xpcall(callback, ItemUtilErrorHandler)
|
||||
end
|
||||
end
|
||||
|
||||
for i = table.getn(callbacks), 1, -1 do
|
||||
callbacks[i] = nil
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function ItemEventListener:ClearCallbacks(itemID)
|
||||
self.callbacks[itemID] = nil
|
||||
end
|
||||
|
||||
function ItemEventListener:GetCallbacks(itemID)
|
||||
return self.callbacks[itemID]
|
||||
end
|
||||
|
||||
function ItemEventListener:GetOrCreateCallbacks(itemID)
|
||||
local callbacks = self.callbacks[itemID]
|
||||
if not callbacks then
|
||||
callbacks = {}
|
||||
self.callbacks[itemID] = callbacks
|
||||
end
|
||||
return callbacks
|
||||
end
|
||||
@@ -1,522 +0,0 @@
|
||||
-- Backport of FrameXML/Pools.lua to vanilla 1.12 / Lua 5.0.
|
||||
--
|
||||
-- Implementation differences from the modern source:
|
||||
-- - 1.12 has no taint/secure system, so the entire Secure*/Proxy
|
||||
-- machinery (SecureTypes, ProxyUtil, securecallfunction,
|
||||
-- CreateForbiddenFrame) is dropped. Only the Unsecured pools and
|
||||
-- pool collections exist; the canonical `CreateObjectPool` /
|
||||
-- `CreateFramePool` / etc. globals are aliased to them at the
|
||||
-- bottom of the file.
|
||||
-- - FrameUtil.SpecializeFrameWithMixins isn't a thing in 1.12; the
|
||||
-- "table specialization" branch is inlined as a plain Mixin().
|
||||
-- - CreateMaskTexture and CreateActor aren't in 1.12 — the
|
||||
-- corresponding pool creators are kept as stubs so chunk-load of
|
||||
-- consumer addons doesn't fail; they'll error at Acquire() time
|
||||
-- if anything actually invokes them.
|
||||
-- - Lua 5.0 has no `...` as expression; the converter mixins use
|
||||
-- `unpack(arg)` to forward varargs (spans arg[1..arg.n] via getn;
|
||||
-- this build's unpack ignores explicit i/j — the count lives in `.n`).
|
||||
-- - assertsafe / nop aren't globals in stock 1.12; defined as local
|
||||
-- fallbacks (same pattern as FunctionUtil.lua).
|
||||
|
||||
local function nop() end
|
||||
|
||||
local function assertsafe(condition, msg)
|
||||
if not condition then
|
||||
local h = geterrorhandler and geterrorhandler()
|
||||
if h then h(msg or "assertion failed!") end
|
||||
end
|
||||
end
|
||||
|
||||
local ObjectPoolBaseMixin = {};
|
||||
|
||||
--[[
|
||||
Reserve() is not exposed on the pool to prevent the attack vector of addons having control
|
||||
over the quantity of objects available to a preexisting pool.
|
||||
]]--
|
||||
local function Reserve(pool, capacity)
|
||||
pool.capacity = capacity or math.huge;
|
||||
|
||||
if pool.capacity ~= math.huge then
|
||||
for index = 1, pool.capacity do
|
||||
pool:Acquire();
|
||||
end
|
||||
pool:ReleaseAll();
|
||||
end
|
||||
end
|
||||
|
||||
local function GetObjectIsInvalidMsg(object, poolOrCollection)
|
||||
if poolOrCollection:DoesObjectBelongToPool(object) then
|
||||
return string.format("Attempted to release inactive object '%s'", tostring(object));
|
||||
else
|
||||
return string.format("Attempted to release object '%s' that doesn't belong to this pool", tostring(object));
|
||||
end
|
||||
end
|
||||
|
||||
function ObjectPoolBaseMixin:Acquire()
|
||||
if self:GetNumActive() == self.capacity then
|
||||
return nil, false;
|
||||
end
|
||||
|
||||
local object = self:PopInactiveObject();
|
||||
local new = object == nil;
|
||||
if new then
|
||||
object = self:CallCreate();
|
||||
|
||||
--[[
|
||||
While pools don't necessarily need to only contain tables, support for other types
|
||||
has not been tested, and therefore isn't allowed until we can justify a use for them.
|
||||
]]--
|
||||
assert(type(object) == "table");
|
||||
|
||||
self:CallReset(object, new);
|
||||
end
|
||||
|
||||
self:AddObject(object);
|
||||
return object, new;
|
||||
end
|
||||
|
||||
function ObjectPoolBaseMixin:Release(object, canFailToFindObject)
|
||||
local active = self:IsActive(object);
|
||||
|
||||
--[[
|
||||
If Release() is called on a pool directly from external code, then we expect
|
||||
an assert if the object is not found. However, if it was called from a pool
|
||||
collection, the object not being active is expected as the pool collection iterates
|
||||
all the pools until it is found. A separate assert in pool collections accounts for
|
||||
the case where the object was not found in any pool.
|
||||
]]--
|
||||
if not canFailToFindObject then
|
||||
assertsafe(active, GetObjectIsInvalidMsg(object, self));
|
||||
end
|
||||
|
||||
if active then
|
||||
self:CallReset(object);
|
||||
self:ReclaimObject(object);
|
||||
end
|
||||
|
||||
return active;
|
||||
end
|
||||
|
||||
function ObjectPoolBaseMixin:Dump()
|
||||
for index, object in self:EnumerateActive() do
|
||||
print(tostring(object));
|
||||
end
|
||||
end
|
||||
|
||||
local ObjectPoolMixin = CreateFromMixins(ObjectPoolBaseMixin);
|
||||
|
||||
function ObjectPoolMixin:Init(createFunc, resetFunc, capacity)
|
||||
self.createFunc = createFunc;
|
||||
self.resetFunc = resetFunc;
|
||||
self.activeObjects = {};
|
||||
self.inactiveObjects = {};
|
||||
self.activeObjectCount = 0;
|
||||
|
||||
Reserve(self, capacity);
|
||||
end
|
||||
|
||||
function ObjectPoolMixin:CallReset(object, new)
|
||||
self.resetFunc(self, object, new);
|
||||
end
|
||||
|
||||
function ObjectPoolMixin:CallCreate()
|
||||
-- The pool argument 'self' is passed only for addons already reliant on it.
|
||||
return self.createFunc(self);
|
||||
end
|
||||
|
||||
function ObjectPoolMixin:PopInactiveObject()
|
||||
return tremove(self.inactiveObjects);
|
||||
end
|
||||
|
||||
function ObjectPoolMixin:AddObject(object)
|
||||
local dummy = true;
|
||||
self.activeObjects[object] = dummy;
|
||||
self.activeObjectCount = self.activeObjectCount + 1;
|
||||
end
|
||||
|
||||
function ObjectPoolMixin:ReclaimObject(object)
|
||||
tinsert(self.inactiveObjects, object);
|
||||
self.activeObjects[object] = nil;
|
||||
self.activeObjectCount = self.activeObjectCount - 1;
|
||||
end
|
||||
|
||||
function ObjectPoolMixin:ReleaseAll()
|
||||
for object in pairs(self.activeObjects) do
|
||||
self:Release(object);
|
||||
end
|
||||
end
|
||||
|
||||
function ObjectPoolMixin:EnumerateActive()
|
||||
return pairs(self.activeObjects);
|
||||
end
|
||||
|
||||
function ObjectPoolMixin:GetNextActive(current)
|
||||
return next(self.activeObjects, current);
|
||||
end
|
||||
|
||||
function ObjectPoolMixin:IsActive(object)
|
||||
return self.activeObjects[object] ~= nil;
|
||||
end
|
||||
|
||||
function ObjectPoolMixin:DoesObjectBelongToPool(object)
|
||||
if self:IsActive(object) then
|
||||
return true;
|
||||
end
|
||||
|
||||
for index, candidate in pairs(self.inactiveObjects) do
|
||||
if candidate == object then
|
||||
return true;
|
||||
end
|
||||
end
|
||||
|
||||
return false;
|
||||
end
|
||||
|
||||
function ObjectPoolMixin:GetNumActive()
|
||||
return self.activeObjectCount;
|
||||
end
|
||||
|
||||
local function GetPoolKey(template, specialization)
|
||||
if specialization == nil then
|
||||
return template.."nil";
|
||||
end
|
||||
return template..tostring(specialization);
|
||||
end
|
||||
|
||||
local PoolCollectionBaseMixin = {};
|
||||
|
||||
function PoolCollectionBaseMixin:GetPool(template, specialization)
|
||||
local poolKey = GetPoolKey(template, specialization);
|
||||
return self:GetPoolByKey(poolKey);
|
||||
end
|
||||
|
||||
function PoolCollectionBaseMixin:HasPool(poolKey)
|
||||
return self:GetPoolByKey(poolKey) ~= nil;
|
||||
end
|
||||
|
||||
function PoolCollectionBaseMixin:Acquire(template, specialization)
|
||||
local pool = self:GetPool(template, specialization);
|
||||
return pool:Acquire();
|
||||
end
|
||||
|
||||
function PoolCollectionBaseMixin:ReleaseAllByTemplate(template, specialization)
|
||||
local pool = self:GetPool(template, specialization);
|
||||
if pool then
|
||||
pool:ReleaseAll();
|
||||
end
|
||||
end
|
||||
|
||||
function PoolCollectionBaseMixin:EnumerateActiveByTemplate(template, specialization)
|
||||
local pool = self:GetPool(template, specialization);
|
||||
if pool then
|
||||
return pool:EnumerateActive();
|
||||
end
|
||||
|
||||
return nop;
|
||||
end
|
||||
|
||||
function PoolCollectionBaseMixin:GetOrCreatePool(...)
|
||||
assert(false);
|
||||
end
|
||||
|
||||
function PoolCollectionBaseMixin:CreatePool(...)
|
||||
assert(false);
|
||||
end
|
||||
|
||||
function PoolCollectionBaseMixin:CreatePoolWithArgs(args)
|
||||
local poolKey = self:CreatePoolKeyFromPoolArgs(args);
|
||||
assert(not self:HasPool(poolKey));
|
||||
|
||||
local pool = self:CreatePoolInternal(args);
|
||||
self:SetPool(poolKey, pool);
|
||||
return pool;
|
||||
end
|
||||
|
||||
function PoolCollectionBaseMixin:GetOrCreatePoolWithArgs(args)
|
||||
local poolKey = self:CreatePoolKeyFromPoolArgs(args);
|
||||
local pool = self:GetPoolByKey(poolKey);
|
||||
local new = pool == nil;
|
||||
if new then
|
||||
pool = self:CreatePoolWithArgs(args);
|
||||
end
|
||||
return pool, new;
|
||||
end
|
||||
|
||||
function PoolCollectionBaseMixin:Dump()
|
||||
for object in self:EnumerateActive() do
|
||||
print(tostring(object));
|
||||
end
|
||||
end
|
||||
|
||||
local PoolCollectionMixin = CreateFromMixins(PoolCollectionBaseMixin);
|
||||
|
||||
function PoolCollectionMixin:Init()
|
||||
self.pools = {};
|
||||
end
|
||||
|
||||
function PoolCollectionMixin:GetNumActive()
|
||||
local total = 0;
|
||||
for poolKey, pool in pairs(self.pools) do
|
||||
total = total + pool:GetNumActive();
|
||||
end
|
||||
return total;
|
||||
end
|
||||
|
||||
function PoolCollectionMixin:SetPool(poolKey, pool)
|
||||
self.pools[poolKey] = pool;
|
||||
end
|
||||
|
||||
function PoolCollectionMixin:GetPoolByKey(poolKey)
|
||||
return self.pools[poolKey];
|
||||
end
|
||||
|
||||
function PoolCollectionMixin:Release(object)
|
||||
local canFailToFindObject = true;
|
||||
for poolKey, pool in pairs(self.pools) do
|
||||
if pool:Release(object, canFailToFindObject) then
|
||||
return;
|
||||
end
|
||||
end
|
||||
assertsafe(false, GetObjectIsInvalidMsg(object, self));
|
||||
end
|
||||
|
||||
function PoolCollectionMixin:DoesObjectBelongToPool(object)
|
||||
for poolKey, pool in pairs(self.pools) do
|
||||
if pool:DoesObjectBelongToPool(object) then
|
||||
return true;
|
||||
end
|
||||
end
|
||||
|
||||
return false;
|
||||
end
|
||||
|
||||
function PoolCollectionMixin:ReleaseAll()
|
||||
for poolKey, pool in pairs(self.pools) do
|
||||
pool:ReleaseAll();
|
||||
end
|
||||
end
|
||||
|
||||
-- Warning: this function only returns the object, unlike a pool that also returns the key.
|
||||
function PoolCollectionMixin:EnumerateActive()
|
||||
local currentObject = nil;
|
||||
local currentPoolKey, currentPool = next(self.pools, currentObject);
|
||||
return function()
|
||||
if currentPool then
|
||||
currentObject = currentPool:GetNextActive(currentObject);
|
||||
while not currentObject do
|
||||
currentPoolKey, currentPool = next(self.pools, currentPoolKey)
|
||||
if currentPool then
|
||||
currentObject = currentPool:GetNextActive(nil);
|
||||
else
|
||||
break;
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return currentObject;
|
||||
end, nil;
|
||||
end
|
||||
|
||||
function Pool_HideAndClearAnchors(pool, region)
|
||||
region:Hide();
|
||||
region:ClearAllPoints();
|
||||
end
|
||||
|
||||
function ActorPool_HideAndClearModel(actorPool, actor)
|
||||
actor:ClearModel();
|
||||
actor:Hide();
|
||||
end
|
||||
|
||||
--[[
|
||||
In addition to a specialization being used to create separate pools for the same template, it can
|
||||
be used to modify a frame after being created. On modern WoW this delegates to
|
||||
FrameUtil.SpecializeFrameWithMixins (which also wires up conventional script handlers); on 1.12
|
||||
we just Mixin() the table into the frame and let the consumer call SetScript() if needed.
|
||||
]]--
|
||||
local function ConvertSpecializationToPostCreate(specialization)
|
||||
local specializationType = type(specialization);
|
||||
if specializationType == "function" then
|
||||
return specialization;
|
||||
elseif specializationType == "table" then
|
||||
local function Initializer(frame)
|
||||
Mixin(frame, specialization);
|
||||
end
|
||||
return Initializer;
|
||||
end
|
||||
|
||||
return nil;
|
||||
end
|
||||
|
||||
function CreateUnsecuredRegionPoolInstance(template, createFunc, resetFunc, capacity)
|
||||
local pool = CreateFromMixins(ObjectPoolMixin);
|
||||
pool:Init(createFunc, resetFunc or Pool_HideAndClearAnchors, capacity);
|
||||
pool.GetTemplate = function(self)
|
||||
return template;
|
||||
end
|
||||
|
||||
return pool;
|
||||
end
|
||||
|
||||
--[[
|
||||
Args are packed into a table for ease of implementation in PoolCollectionBaseMixin, which is
|
||||
derived with different argument signatures. This also makes it easy to access named fields
|
||||
like `parent` off the table without dealing with argument position.
|
||||
]]--
|
||||
local function FramePoolCollection_ArgsToTable(frameType, parent, template, resetFunc, forbidden, specialization, capacity)
|
||||
return {
|
||||
frameType = frameType,
|
||||
parent = parent,
|
||||
template = template,
|
||||
resetFunc = resetFunc,
|
||||
forbidden = forbidden, -- ignored on 1.12 (no CreateForbiddenFrame)
|
||||
specialization = specialization,
|
||||
capacity = capacity,
|
||||
};
|
||||
end
|
||||
|
||||
local FramePoolCollectionConverterMixin = {};
|
||||
|
||||
function FramePoolCollectionConverterMixin:CreatePoolKeyFromPoolArgs(args)
|
||||
return GetPoolKey(args.template, args.specialization);
|
||||
end
|
||||
|
||||
function FramePoolCollectionConverterMixin:GetOrCreatePool(...)
|
||||
local args = FramePoolCollection_ArgsToTable(unpack(arg));
|
||||
return self:GetOrCreatePoolWithArgs(args);
|
||||
end
|
||||
|
||||
function FramePoolCollectionConverterMixin:CreatePool(...)
|
||||
local args = FramePoolCollection_ArgsToTable(unpack(arg));
|
||||
return self:CreatePoolWithArgs(args);
|
||||
end
|
||||
|
||||
local FramePoolCollectionMixin = CreateFromMixins(PoolCollectionMixin, FramePoolCollectionConverterMixin);
|
||||
|
||||
do
|
||||
local function CreateFramePoolInstance(frameType, parent, template, resetFunc, postCreate, capacity)
|
||||
local function Create()
|
||||
local name = nil;
|
||||
local frame = CreateFrame(frameType, name, parent, template);
|
||||
|
||||
if postCreate then
|
||||
postCreate(frame);
|
||||
end
|
||||
|
||||
return frame;
|
||||
end
|
||||
|
||||
return CreateUnsecuredRegionPoolInstance(template, Create, resetFunc, capacity);
|
||||
end
|
||||
|
||||
function FramePoolCollectionMixin:CreatePoolInternal(args)
|
||||
local postCreate = ConvertSpecializationToPostCreate(args.specialization);
|
||||
return CreateFramePoolInstance(args.frameType, args.parent, args.template, args.resetFunc, postCreate, args.capacity);
|
||||
end
|
||||
end
|
||||
|
||||
local FontStringPoolCollectionMixin = CreateFromMixins(PoolCollectionMixin);
|
||||
|
||||
function FontStringPoolCollectionMixin:CreatePoolKeyFromPoolArgs(args)
|
||||
return args.template;
|
||||
end
|
||||
|
||||
local function FontStringPoolCollection_ArgsToTable(parent, layer, subLayer, template, resetFunc, capacity)
|
||||
return {
|
||||
parent = parent,
|
||||
layer = layer,
|
||||
subLayer = subLayer,
|
||||
template = template,
|
||||
resetFunc = resetFunc,
|
||||
capacity = capacity,
|
||||
};
|
||||
end
|
||||
|
||||
function FontStringPoolCollectionMixin:GetOrCreatePool(...)
|
||||
local args = FontStringPoolCollection_ArgsToTable(unpack(arg));
|
||||
return self:GetOrCreatePoolWithArgs(args);
|
||||
end
|
||||
|
||||
function FontStringPoolCollectionMixin:CreatePool(...)
|
||||
local args = FontStringPoolCollection_ArgsToTable(unpack(arg));
|
||||
return self:CreatePoolWithArgs(args);
|
||||
end
|
||||
|
||||
function FontStringPoolCollectionMixin:CreatePoolInternal(args)
|
||||
return CreateUnsecuredFontStringPool(args.parent, args.layer, args.subLayer, args.template, args.resetFunc, args.capacity);
|
||||
end
|
||||
|
||||
function CreateUnsecuredObjectPool(createFunc, resetFunc, capacity)
|
||||
local pool = CreateFromMixins(ObjectPoolMixin);
|
||||
pool:Init(createFunc, resetFunc, capacity);
|
||||
return pool;
|
||||
end
|
||||
|
||||
function CreateUnsecuredFramePool(frameType, parent, template, resetFunc, capacity)
|
||||
local function Create()
|
||||
local name = nil;
|
||||
return CreateFrame(frameType, name, parent, template);
|
||||
end
|
||||
return CreateUnsecuredRegionPoolInstance(template, Create, resetFunc, capacity);
|
||||
end
|
||||
|
||||
function CreateUnsecuredTexturePool(parent, layer, subLayer, template, resetFunc, capacity)
|
||||
local function Create()
|
||||
local name = nil;
|
||||
return parent:CreateTexture(name, layer, template, subLayer);
|
||||
end
|
||||
return CreateUnsecuredRegionPoolInstance(template, Create, resetFunc, capacity);
|
||||
end
|
||||
|
||||
function CreateUnsecuredFontStringPool(parent, layer, subLayer, template, resetFunc, capacity)
|
||||
local function Create()
|
||||
local name = nil;
|
||||
return parent:CreateFontString(name, layer, template, subLayer);
|
||||
end
|
||||
return CreateUnsecuredRegionPoolInstance(template, Create, resetFunc, capacity);
|
||||
end
|
||||
|
||||
-- Stub: 1.12 has no CreateActor (model actors are Cataclysm+). Acquire()
|
||||
-- will raise once it actually tries to call parent:CreateActor — kept so
|
||||
-- that addon code merely referencing the symbol doesn't fail to load.
|
||||
function CreateUnsecuredActorPool(parent, template, resetFunc, capacity)
|
||||
local function Create()
|
||||
local name = nil;
|
||||
return parent:CreateActor(name, template);
|
||||
end
|
||||
return CreateUnsecuredRegionPoolInstance(template, Create, resetFunc or ActorPool_HideAndClearModel, capacity);
|
||||
end
|
||||
|
||||
-- Stub: 1.12 has no CreateMaskTexture (mask textures are post-vanilla).
|
||||
-- Same caveat as CreateUnsecuredActorPool.
|
||||
function CreateUnsecuredMaskTexturePool(parent, layer, subLayer, template, resetFunc, capacity)
|
||||
local function Create()
|
||||
local name = nil;
|
||||
return parent:CreateMaskTexture(name, layer, template, subLayer);
|
||||
end
|
||||
return CreateUnsecuredRegionPoolInstance(template, Create, resetFunc, capacity);
|
||||
end
|
||||
|
||||
function CreateUnsecuredFramePoolCollection()
|
||||
local poolCollection = CreateFromMixins(FramePoolCollectionMixin);
|
||||
poolCollection:Init();
|
||||
return poolCollection;
|
||||
end
|
||||
|
||||
function CreateUnsecuredFontStringPoolCollection()
|
||||
local poolCollection = CreateFromMixins(FontStringPoolCollectionMixin);
|
||||
poolCollection:Init();
|
||||
return poolCollection;
|
||||
end
|
||||
|
||||
-- Canonical API aliases. On modern WoW these point at the Secure variants;
|
||||
-- on 1.12 there's no taint system, so they all go straight to the Unsecured
|
||||
-- implementations.
|
||||
CreateObjectPool = CreateUnsecuredObjectPool;
|
||||
CreateFramePool = CreateUnsecuredFramePool;
|
||||
CreateTexturePool = CreateUnsecuredTexturePool;
|
||||
CreateFontStringPool = CreateUnsecuredFontStringPool;
|
||||
CreateActorPool = CreateUnsecuredActorPool;
|
||||
CreateFramePoolCollection = CreateUnsecuredFramePoolCollection;
|
||||
CreateFontStringPoolCollection = CreateUnsecuredFontStringPoolCollection;
|
||||
CreateMaskTexturePool = CreateUnsecuredMaskTexturePool;
|
||||
@@ -1,222 +0,0 @@
|
||||
-- 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.
|
||||
--
|
||||
-- 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).
|
||||
--
|
||||
-- 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,
|
||||
});
|
||||
|
||||
local STATE_DRIVER_UPDATE_THROTTLE = 0.2;
|
||||
local nextUpdate = 0;
|
||||
|
||||
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
|
||||
|
||||
local function resolveDriver(frame, attribute, 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);
|
||||
end
|
||||
end
|
||||
elseif newValue then
|
||||
if newValue == "nil" then
|
||||
newValue = nil;
|
||||
else
|
||||
newValue = tonumber(newValue) or newValue;
|
||||
end
|
||||
if frame:GetAttribute(attribute) ~= newValue then
|
||||
frame:SetAttribute(attribute, newValue);
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Manager frame
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
SecureStateDriverManager = CreateFrame("Frame", "SecureStateDriverManager");
|
||||
SecureStateDriverManager:Hide(); -- hidden -> no OnUpdate until a driver exists
|
||||
|
||||
SecureStateDriverManager:SetScript("OnUpdate", function()
|
||||
local now = GetTime();
|
||||
if now < nextUpdate then
|
||||
return;
|
||||
end
|
||||
nextUpdate = now + STATE_DRIVER_UPDATE_THROTTLE;
|
||||
|
||||
for frame, drivers in pairs(secureAttributeDrivers) do
|
||||
for attribute, values in pairs(drivers) do
|
||||
resolveDriver(frame, attribute, values);
|
||||
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: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)
|
||||
"ACTIONBAR_PAGE_CHANGED",
|
||||
"UPDATE_BONUS_ACTIONBAR",
|
||||
"PLAYER_ENTERING_WORLD",
|
||||
"UPDATE_STEALTH",
|
||||
"PLAYER_TARGET_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
|
||||
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
|
||||
@@ -1,725 +0,0 @@
|
||||
-- Backport of 3.3.5 FrameXML/TableUtil.lua to vanilla 1.12 / Lua 5.0.
|
||||
--
|
||||
-- Implementation differences from the 3.3.5 source:
|
||||
-- - Lua 5.0 has no length operator (#). Sequence length comes from
|
||||
-- table.getn(t), which honors an explicit .n field when present.
|
||||
-- - Lua 5.0 has no select() and no `...` outside a vararg function
|
||||
-- body; varargs are passed via the implicit `arg` table.
|
||||
-- - 1.12 has no global wipe(); we ship a local Wipe() helper instead.
|
||||
-- - Lua 5.0 has no math.huge; 1/0 yields the same +inf sentinel.
|
||||
|
||||
local tRemove, tInsert, tWipe = table.remove, table.insert, table.wipe
|
||||
local tGetN = table.getn
|
||||
|
||||
TableUtil = TableUtil or {}
|
||||
|
||||
TableUtil.Constants =
|
||||
{
|
||||
AssociativePriorityTable = true,
|
||||
ArraylikePriorityTable = false,
|
||||
IsIndexTable = true,
|
||||
}
|
||||
|
||||
function ipairs_reverse(table)
|
||||
local function Enumerator(table, index)
|
||||
index = index - 1
|
||||
local value = table[index]
|
||||
if value ~= nil then
|
||||
return index, value
|
||||
end
|
||||
end
|
||||
return Enumerator, table, tGetN(table) + 1
|
||||
end
|
||||
|
||||
function CreateTableEnumerator(tbl, minIndex, maxIndex)
|
||||
minIndex = minIndex and (minIndex - 1) or 0
|
||||
maxIndex = maxIndex or math.huge
|
||||
|
||||
local function Enumerator(tbl, index)
|
||||
index = index + 1
|
||||
if index <= maxIndex then
|
||||
local value = tbl[index]
|
||||
if value ~= nil then
|
||||
return index, value
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return Enumerator, tbl, minIndex
|
||||
end
|
||||
|
||||
function CreateTableReverseEnumerator(tbl, minIndex, maxIndex)
|
||||
minIndex = minIndex or 1
|
||||
maxIndex = (maxIndex or tGetN(tbl)) + 1
|
||||
|
||||
local function Enumerator(tbl, index)
|
||||
index = index - 1
|
||||
if index >= minIndex then
|
||||
local value = tbl[index]
|
||||
if value ~= nil then
|
||||
return index, value
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return Enumerator, tbl, maxIndex
|
||||
end
|
||||
|
||||
function tDeleteItem(tbl, item)
|
||||
local size = tGetN(tbl);
|
||||
local index = size;
|
||||
while index > 0 do
|
||||
if item == tbl[index] then
|
||||
tRemove(tbl, index);
|
||||
end
|
||||
index = index - 1;
|
||||
end
|
||||
return size - tGetN(tbl);
|
||||
end
|
||||
|
||||
function tIndexOf(tbl, item)
|
||||
for i, v in ipairs(tbl) do
|
||||
if item == v then
|
||||
return i
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function tContains(tbl, item)
|
||||
for k, v in pairs(tbl) do
|
||||
if item == v then
|
||||
return true;
|
||||
end
|
||||
end
|
||||
return false;
|
||||
end
|
||||
|
||||
function TableUtil.ContainsAllKeys(lhsTable, rhsTable)
|
||||
for key, _ in pairs(lhsTable) do
|
||||
if rhsTable[key] == nil then
|
||||
return false
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
function TableUtil.CompareValuesAsKeys(lhsTable, rhsTable, valueToKeyOp)
|
||||
local lhsKeys = CopyTransformedValuesAsKeys(lhsTable, valueToKeyOp)
|
||||
local rhsKeys = CopyTransformedValuesAsKeys(rhsTable, valueToKeyOp)
|
||||
return TableUtil.ContainsAllKeys(lhsKeys, rhsKeys)
|
||||
end
|
||||
|
||||
function tCompare(lhsTable, rhsTable, depth)
|
||||
depth = depth or 1
|
||||
for key, value in pairs(lhsTable) do
|
||||
if type(value) == "table" then
|
||||
local rhsValue = rhsTable[key]
|
||||
if type(rhsValue) ~= "table" then
|
||||
return false
|
||||
end
|
||||
if depth > 1 then
|
||||
if not tCompare(value, rhsValue, depth - 1) then
|
||||
return false
|
||||
end
|
||||
end
|
||||
elseif value ~= rhsTable[key] then
|
||||
return false
|
||||
end
|
||||
end
|
||||
|
||||
for key, value in pairs(rhsTable) do
|
||||
if lhsTable[key] == nil then
|
||||
return false
|
||||
end
|
||||
end
|
||||
|
||||
return true
|
||||
end
|
||||
|
||||
function tInvert(tbl)
|
||||
local inverted = {}
|
||||
for k, v in pairs(tbl) do
|
||||
inverted[v] = k
|
||||
end
|
||||
return inverted
|
||||
end
|
||||
|
||||
function TableUtil.TrySet(tbl, key)
|
||||
if not tbl[key] then
|
||||
tbl[key] = true
|
||||
return true
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
function TableUtil.CopyUnique(tbl, isIndexTable)
|
||||
local found = {}
|
||||
local function FilterPredicate(value)
|
||||
return TableUtil.TrySet(found, value)
|
||||
end
|
||||
|
||||
return tFilter(tbl, FilterPredicate, isIndexTable)
|
||||
end
|
||||
|
||||
function TableUtil.CopyUniqueByPredicate(tbl, isIndexTable, unaryPredicate)
|
||||
local found = {}
|
||||
local function FilterPredicate(value)
|
||||
return TableUtil.TrySet(found, unaryPredicate(value))
|
||||
end
|
||||
|
||||
return tFilter(tbl, FilterPredicate, isIndexTable)
|
||||
end
|
||||
|
||||
function tFilter(tbl, pred, isIndexTable)
|
||||
local out = {}
|
||||
|
||||
if isIndexTable then
|
||||
local currentIndex = 1
|
||||
for i, v in ipairs(tbl) do
|
||||
if pred(v) then
|
||||
out[currentIndex] = v
|
||||
currentIndex = currentIndex + 1
|
||||
end
|
||||
end
|
||||
else
|
||||
for k, v in pairs(tbl) do
|
||||
if pred(v) then
|
||||
out[k] = v
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return out
|
||||
end
|
||||
|
||||
function tAppendAll(table, addedArray)
|
||||
for i, element in ipairs(addedArray) do
|
||||
tInsert(table, element)
|
||||
end
|
||||
end
|
||||
|
||||
function tInsertUnique(tbl, item)
|
||||
if not tContains(tbl, item) then
|
||||
tInsert(tbl, item)
|
||||
return tGetN(tbl)
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
function tUnorderedRemove(tbl, index)
|
||||
local n = tGetN(tbl)
|
||||
if index ~= n then
|
||||
tbl[index] = tbl[n]
|
||||
end
|
||||
|
||||
tRemove(tbl)
|
||||
end
|
||||
|
||||
function CopyTable(settings, shallow)
|
||||
local copy = {}
|
||||
for k, v in pairs(settings) do
|
||||
if type(v) == "table" and not shallow then
|
||||
copy[k] = CopyTable(v)
|
||||
else
|
||||
copy[k] = v
|
||||
end
|
||||
end
|
||||
return copy
|
||||
end
|
||||
|
||||
function CopyTableSafe(settings, shallow)
|
||||
if not settings then
|
||||
return nil;
|
||||
end
|
||||
|
||||
return CopyTable(settings, shallow);
|
||||
end
|
||||
|
||||
function MergeTable(destination, source)
|
||||
for k, v in pairs(source) do
|
||||
destination[k] = v
|
||||
end
|
||||
end
|
||||
|
||||
function SetTablePairsToTable(destination, source)
|
||||
tWipe(destination)
|
||||
MergeTable(destination, source)
|
||||
end
|
||||
|
||||
function CountTable(tbl)
|
||||
local count = 0;
|
||||
for k, v in pairs(tbl) do
|
||||
count = count + 1;
|
||||
end
|
||||
return count;
|
||||
end
|
||||
|
||||
function Accumulate(tbl)
|
||||
local count = 0
|
||||
for k, v in pairs(tbl) do
|
||||
count = count + v
|
||||
end
|
||||
return count
|
||||
end
|
||||
|
||||
function AccumulateOp(tbl, op)
|
||||
local count = 0
|
||||
for k, v in pairs(tbl) do
|
||||
count = count + op(v)
|
||||
end
|
||||
return count
|
||||
end
|
||||
|
||||
function TableUtil.Execute(tbl, op)
|
||||
for k, v in pairs(tbl) do
|
||||
op(v)
|
||||
end
|
||||
end
|
||||
|
||||
function TableUtil.ExecuteOnKeys(tbl, op)
|
||||
for k in pairs(tbl) do
|
||||
op(k)
|
||||
end
|
||||
end
|
||||
|
||||
function TableUtil.ExecuteUntil(tbl, op)
|
||||
for k, v in pairs(tbl) do
|
||||
local operationResult = op(v)
|
||||
if operationResult then
|
||||
return operationResult
|
||||
end
|
||||
end
|
||||
|
||||
return nil
|
||||
end
|
||||
|
||||
function TableUtil.Transform(tbl, op)
|
||||
local result = {}
|
||||
for k, v in pairs(tbl) do
|
||||
tInsert(result, op(v))
|
||||
return result
|
||||
end
|
||||
end
|
||||
|
||||
-- Returns the value in a table deemed smallest by evaluating each value returned by the op function parameter.
|
||||
-- The return of the op function must return a number.
|
||||
function TableUtil.FindMin(tbl, op)
|
||||
local result = nil;
|
||||
local min = math.huge;
|
||||
for k, v in pairs(tbl) do
|
||||
local value = op(v);
|
||||
if value < min then
|
||||
min = value;
|
||||
result = v;
|
||||
end
|
||||
end
|
||||
return result;
|
||||
end
|
||||
|
||||
-- Returns the value in a table deemed largest by evaluating each value returned by the op function parameter.
|
||||
-- The return of the op function must return a number.
|
||||
function TableUtil.FindMax(tbl, op)
|
||||
local result = nil;
|
||||
local max = -math.huge;
|
||||
for k, v in pairs(tbl) do
|
||||
local value = op(v);
|
||||
if value > max then
|
||||
max = value;
|
||||
result = v;
|
||||
end
|
||||
end
|
||||
return result;
|
||||
end
|
||||
|
||||
function ContainsIf(tbl, pred)
|
||||
for k, v in pairs(tbl) do
|
||||
if pred(v) then
|
||||
return true
|
||||
end
|
||||
end
|
||||
|
||||
return false
|
||||
end
|
||||
|
||||
function FindInTable(tbl, value)
|
||||
for k, v in pairs(tbl) do
|
||||
if v == value then
|
||||
return k, v;
|
||||
end
|
||||
end
|
||||
|
||||
return nil;
|
||||
end
|
||||
|
||||
function FindInTableIf(tbl, pred)
|
||||
for k, v in pairs(tbl) do
|
||||
if pred(v) then
|
||||
return k, v
|
||||
end
|
||||
end
|
||||
|
||||
return nil
|
||||
end
|
||||
|
||||
function FindValueInTableIf(tbl, pred)
|
||||
local _, value = FindInTableIf(tbl, pred)
|
||||
return value
|
||||
end
|
||||
|
||||
local function FindSortedIndexImplementation(tbl, searchComparison, startIndex, rangeStart, rangeEnd)
|
||||
local comparisonResult = searchComparison(tbl[startIndex])
|
||||
if comparisonResult == 0 then
|
||||
return startIndex
|
||||
end
|
||||
|
||||
if comparisonResult > 0 then
|
||||
if startIndex >= rangeEnd then
|
||||
return startIndex + 1
|
||||
end
|
||||
|
||||
rangeStart = startIndex + 1
|
||||
return FindSortedIndexImplementation(tbl, searchComparison, startIndex + math.ceil((rangeEnd - startIndex) / 2), rangeStart, rangeEnd)
|
||||
end
|
||||
|
||||
if startIndex <= rangeStart then
|
||||
return startIndex
|
||||
end
|
||||
|
||||
rangeEnd = startIndex - 1
|
||||
return FindSortedIndexImplementation(tbl, searchComparison, math.floor(startIndex / 2), rangeStart, rangeEnd)
|
||||
end
|
||||
|
||||
function FindSortedIndex(tbl, searchComparison)
|
||||
local numTable = tGetN(tbl)
|
||||
local startingIndex = math.ceil(numTable / 2)
|
||||
if startingIndex == 0 then
|
||||
return 1
|
||||
end
|
||||
|
||||
return FindSortedIndexImplementation(tbl, searchComparison, startingIndex, 1, numTable)
|
||||
end
|
||||
|
||||
function TableIsEmpty(tbl)
|
||||
return next(tbl) == nil
|
||||
end
|
||||
|
||||
function TableHasAnyEntries(tbl)
|
||||
return next(tbl) ~= nil
|
||||
end
|
||||
|
||||
function CopyValuesAsKeys(tbl)
|
||||
local output = {}
|
||||
for k, v in ipairs(tbl) do
|
||||
output[v] = v
|
||||
end
|
||||
return output
|
||||
end
|
||||
|
||||
function CopyTransformedValuesAsKeys(tbl, transformOp)
|
||||
local output = {}
|
||||
for _, v in ipairs(tbl) do
|
||||
output[transformOp(v)] = v
|
||||
end
|
||||
return output
|
||||
end
|
||||
|
||||
function SafePack(...)
|
||||
local tbl = {}
|
||||
for i = 1, arg.n do tbl[i] = arg[i] end
|
||||
tbl.n = arg.n
|
||||
return tbl
|
||||
end
|
||||
|
||||
function SafeUnpack(tbl)
|
||||
return unpack(tbl)
|
||||
end
|
||||
|
||||
-- Returns the length of a table, accounting for the possibility of a table constructed using SafePack.
|
||||
function SafeLength(tbl)
|
||||
if not tbl then
|
||||
return 0;
|
||||
end
|
||||
|
||||
local operatorCount = tGetN(tbl);
|
||||
local safePackCount = tbl.n;
|
||||
|
||||
if safePackCount and operatorCount ~= safePackCount then
|
||||
return safePackCount;
|
||||
end
|
||||
|
||||
return operatorCount;
|
||||
end
|
||||
|
||||
function GetOrCreateTableEntry(table, key, defaultValue)
|
||||
local currentValue = table[key]
|
||||
local isNewValue = (currentValue == nil)
|
||||
if isNewValue then
|
||||
if defaultValue ~= nil then
|
||||
currentValue = defaultValue
|
||||
else
|
||||
currentValue = {}
|
||||
end
|
||||
table[key] = currentValue
|
||||
end
|
||||
|
||||
return currentValue, isNewValue
|
||||
end
|
||||
|
||||
function GetOrCreateTableEntryByCallback(table, key, callback)
|
||||
local currentValue = table[key]
|
||||
local isNewValue = (currentValue == nil)
|
||||
if isNewValue then
|
||||
currentValue = callback(key)
|
||||
table[key] = currentValue
|
||||
end
|
||||
|
||||
return currentValue, isNewValue
|
||||
end
|
||||
|
||||
function GetOrCreateTableEntryByMethod(table, key, method, owner)
|
||||
local currentValue = table[key];
|
||||
local isNewValue = (currentValue == nil);
|
||||
if isNewValue then
|
||||
currentValue = method(owner, key);
|
||||
table[key] = currentValue;
|
||||
end
|
||||
|
||||
return currentValue, isNewValue;
|
||||
end
|
||||
|
||||
function GetRandomArrayEntry(array)
|
||||
return array[math.random(1, tGetN(array))]
|
||||
end
|
||||
|
||||
function GetRandomTableValue(tbl)
|
||||
local value
|
||||
local n = 0
|
||||
for k, v in pairs(tbl) do
|
||||
n = n + 1
|
||||
local r = math.random()
|
||||
if r <= (1 / n) then
|
||||
value = v
|
||||
end
|
||||
end
|
||||
return value
|
||||
end
|
||||
|
||||
function GetKeysArray(tbl)
|
||||
local keysArray = {}
|
||||
for key in pairs(tbl) do
|
||||
tInsert(keysArray, key)
|
||||
end
|
||||
|
||||
return keysArray
|
||||
end
|
||||
|
||||
function GetValuesArray(tbl)
|
||||
local valuesArray = {}
|
||||
for key, value in pairs(tbl) do
|
||||
tInsert(valuesArray, value)
|
||||
end
|
||||
|
||||
return valuesArray
|
||||
end
|
||||
|
||||
function GetPairsArray(tbl)
|
||||
local pairsArray = {}
|
||||
for key, value in pairs(tbl) do
|
||||
tInsert(pairsArray, { key = key, value = value, })
|
||||
end
|
||||
|
||||
return pairsArray
|
||||
end
|
||||
|
||||
function SwapTableEntries(lhsTable, rhsTable, key)
|
||||
local lhsValue = lhsTable[key]
|
||||
lhsTable[key] = rhsTable[key]
|
||||
rhsTable[key] = lhsValue
|
||||
end
|
||||
|
||||
function GetKeysArraySortedByValue(tbl)
|
||||
local keysArray = GetKeysArray(tbl);
|
||||
|
||||
table.sort(keysArray, function(a, b)
|
||||
return tbl[a] < tbl[b];
|
||||
end);
|
||||
|
||||
return keysArray;
|
||||
end
|
||||
|
||||
function TableUtil.GetTableValueListFromEnumeration(tableKey, ...)
|
||||
local values = {}
|
||||
for enumerationKey, tbl in arg[1] do
|
||||
tInsert(values, tbl[tableKey])
|
||||
end
|
||||
|
||||
return values
|
||||
end
|
||||
|
||||
function TableUtil.GetHighestNumericalValueInTable(table)
|
||||
local highestValue = nil;
|
||||
for key, value in pairs(table) do
|
||||
if type(value) == "number" and (not highestValue or value > highestValue) then
|
||||
highestValue = value;
|
||||
end
|
||||
end
|
||||
return highestValue;
|
||||
end
|
||||
|
||||
--[[
|
||||
This utility creates and returns a table of elements that are sorted by value "priority".
|
||||
|
||||
Arguments:
|
||||
comparator - comparator(A, B) returns whether A has higher priority than B
|
||||
isAssociative - whether the table should be associative (true) or array-like (false). Only values have priorities for associative tables, not keys.
|
||||
|
||||
Return usage:
|
||||
t[k]/t:Get(k) - returns the value stored with key/index k
|
||||
t[k] = v - (Associative only) stores the value v at key k, sorting accordingly
|
||||
t:Insert(v) - (Array-like only) inserts the value v, sorting accordingly
|
||||
t:Remove(k) - removes the element at key/index k
|
||||
t:Iterate(cb) - calls function cb on each key/index value pair in sorted priority order
|
||||
t:GetTop() - returns the highest priority element
|
||||
t:Pop() - returns and removes the highest priority element
|
||||
t:GetBottom() - returns the lowest priority element
|
||||
t:Size() - returns the number of stored elements
|
||||
t:Clear() - removes all elements
|
||||
--]]
|
||||
function TableUtil.CreatePriorityTable(comparator, isAssociative)
|
||||
local sortedArray = {}
|
||||
|
||||
local ShiftPositionMap
|
||||
local keyToPosMap
|
||||
if isAssociative then
|
||||
keyToPosMap = {}
|
||||
|
||||
ShiftPositionMap = function(position, shiftUp)
|
||||
local mod = shiftUp and 1 or -1
|
||||
for k, p in pairs(keyToPosMap) do
|
||||
if p >= position then
|
||||
keyToPosMap[k] = p + mod
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function SortedInsert(k, v)
|
||||
if isAssociative then
|
||||
local prevPos = keyToPosMap[k]
|
||||
if prevPos then
|
||||
tRemove(sortedArray, prevPos)
|
||||
local shiftUp = false
|
||||
ShiftPositionMap(prevPos, shiftUp)
|
||||
end
|
||||
end
|
||||
|
||||
local n = tGetN(sortedArray)
|
||||
local top = (n > 0) and (n + 1) or 1
|
||||
local bottom = 1
|
||||
while top ~= bottom do
|
||||
local mid = math.floor((top - bottom) / 2) + bottom
|
||||
if not comparator(v, sortedArray[mid]) then
|
||||
bottom = mid + 1
|
||||
else
|
||||
top = mid
|
||||
end
|
||||
end
|
||||
local idx = bottom
|
||||
tInsert(sortedArray, idx, v)
|
||||
|
||||
if isAssociative then
|
||||
local shiftUp = true
|
||||
ShiftPositionMap(idx, shiftUp)
|
||||
keyToPosMap[k] = idx
|
||||
end
|
||||
end
|
||||
|
||||
local t = {}
|
||||
|
||||
function t:Get(k)
|
||||
local key = isAssociative and keyToPosMap[k] or k
|
||||
return sortedArray[key]
|
||||
end
|
||||
|
||||
if not isAssociative then
|
||||
function t:Insert(v)
|
||||
SortedInsert(nil, v)
|
||||
end
|
||||
end
|
||||
|
||||
function t:Remove(k)
|
||||
local key = isAssociative and keyToPosMap[k] or k
|
||||
tRemove(sortedArray, key)
|
||||
if isAssociative then
|
||||
keyToPosMap[k] = nil
|
||||
local shiftUp = false
|
||||
ShiftPositionMap(key, shiftUp)
|
||||
end
|
||||
end
|
||||
|
||||
function t:GetTop()
|
||||
return tGetN(sortedArray) > 0 and sortedArray[1]
|
||||
end
|
||||
|
||||
function t:GetBottom()
|
||||
local n = tGetN(sortedArray)
|
||||
return n > 0 and sortedArray[n]
|
||||
end
|
||||
|
||||
function t:Pop()
|
||||
if t:Size() == 0 then
|
||||
return nil
|
||||
end
|
||||
|
||||
local top = t:GetTop()
|
||||
local removalKey = isAssociative and tInvert(keyToPosMap)[1] or 1
|
||||
t:Remove(removalKey)
|
||||
return top
|
||||
end
|
||||
|
||||
function t:Iterate(callback)
|
||||
local posToKeyMap = isAssociative and tInvert(keyToPosMap) or nil
|
||||
for pos, v in ipairs(sortedArray) do
|
||||
local key = isAssociative and posToKeyMap[pos] or pos
|
||||
local done = callback(key, v)
|
||||
if done then
|
||||
return
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function t:Size()
|
||||
return tGetN(sortedArray)
|
||||
end
|
||||
|
||||
function t:Clear()
|
||||
sortedArray = {}
|
||||
if isAssociative then
|
||||
keyToPosMap = {}
|
||||
end
|
||||
end
|
||||
|
||||
local mt =
|
||||
{
|
||||
__index = function(t, k)
|
||||
return t:Get(k)
|
||||
end,
|
||||
}
|
||||
if isAssociative then
|
||||
mt.__newindex = function(t, k, v)
|
||||
if v ~= nil then
|
||||
SortedInsert(k, v)
|
||||
else
|
||||
t:Remove(k)
|
||||
end
|
||||
end
|
||||
else
|
||||
mt.__newindex = function(t, k, v)
|
||||
error("Attempted to assign a value to an array-like priority queue index. Use Insert()/Remove() instead.")
|
||||
end
|
||||
end
|
||||
|
||||
setmetatable(t, mt)
|
||||
|
||||
return t
|
||||
end
|
||||
@@ -1,857 +0,0 @@
|
||||
-- Trade-skill *list* links (`|Htrade:...|h`) — backport of the 2.x+ shareable
|
||||
-- profession link. The link is built entirely in the DLL
|
||||
-- (`GetTradeSkillListLink` / `GetCraftListLink`, see src/tradeskill/Link.cpp);
|
||||
-- this file only intercepts clicks on received links and renders the linker's
|
||||
-- recipe list in a scroll frame (the UI half).
|
||||
--
|
||||
-- link: |cffffd000|Htrade:<skillLineID>:<curRank>:<maxRank>:<linkerName>:<base64 bits>|h[Name]|h|r
|
||||
--
|
||||
-- "Which recipes are known" is a bitfield over the skill line's canonical
|
||||
-- recipe list (deterministic per DBC). The viewer lists the recipes the linker
|
||||
-- knows (with an "X of Y" summary of the whole skill line), regardless of what
|
||||
-- the reader can craft themselves.
|
||||
|
||||
-- Frame geometry mirrors the real TradeSkillFrame. Turtle ships an HD
|
||||
-- 768x512 two-column frame (TW-TradeSkill art); stock 1.12.1 only has the
|
||||
-- vanilla 384x512 single-column art, so on that client we fall back to the
|
||||
-- native Blizzard_TradeSkillUI geometry (list on top, detail below) rather
|
||||
-- than stretch the wide art. LO holds every layout value that differs.
|
||||
local TURTLE = (TURTLE_WOW_VERSION ~= nil);
|
||||
local FRAME_W = TURTLE and 768 or 384;
|
||||
local FRAME_H = 512;
|
||||
local NUM_ROWS = TURTLE and 19 or 8;
|
||||
local ROW_HEIGHT = 16;
|
||||
|
||||
local LO = TURTLE and {
|
||||
hit = { 2, 82, 2, 73 },
|
||||
quads = {
|
||||
{ "Interface\\TradeSkillFrame\\TW-TradeSkill-TopLeft", 512, 256, "TOPLEFT" },
|
||||
{ "Interface\\TradeSkillFrame\\TW-TradeSkill-TopRight", 256, 256, "TOPRIGHT" },
|
||||
{ "Interface\\TradeSkillFrame\\TW-TradeSkill-BotLeft2", 512, 256, "BOTTOMLEFT" },
|
||||
{ "Interface\\TradeSkillFrame\\TW-TradeSkill-BotRight2", 256, 256, "BOTTOMRIGHT" },
|
||||
},
|
||||
close = { -77, -8 },
|
||||
bar = { 596, 15, 76, -44 },
|
||||
barBdr = { 604, 22 },
|
||||
summary = { "TOPRIGHT", -110, -70 },
|
||||
drop = { 40, -60 },
|
||||
scroll = { 296, 330, 37, -98 },
|
||||
-- detail scroll frame: { x, y, width, height }. Tall enough that the
|
||||
-- content fits (scrollbar auto-hides) — Turtle's right column is roomy.
|
||||
detail = { 371, -110, 340, 290 },
|
||||
exit = { "CENTER", "BOTTOMRIGHT", -128, 92 },
|
||||
} or {
|
||||
hit = { 0, 34, 0, 75 },
|
||||
quads = {
|
||||
{ "Interface\\ClassTrainerFrame\\UI-ClassTrainer-TopLeft", 256, 256, "TOPLEFT" },
|
||||
{ "Interface\\ClassTrainerFrame\\UI-ClassTrainer-TopRight", 128, 256, "TOPRIGHT" },
|
||||
{ "Interface\\TradeSkillFrame\\UI-TradeSkill-BotLeft", 256, 256, "BOTTOMLEFT" },
|
||||
{ "Interface\\ClassTrainerFrame\\UI-ClassTrainer-BotRight", 128, 256, "BOTTOMRIGHT" },
|
||||
},
|
||||
close = { -29, -8 },
|
||||
bar = { 268, 15, 73, -37 },
|
||||
barBdr = { 278, 22 },
|
||||
summary = { "TOPRIGHT", -40, -58 },
|
||||
drop = { 12, -62 },
|
||||
scroll = { 296, 130, 21, -96 },
|
||||
-- detail scroll frame { x, y, width, height } — native TradeSkillFrame's
|
||||
-- TradeSkillDetailScrollFrame values. Small enough that many-reagent
|
||||
-- recipes scroll (clipping partial rows), like native.
|
||||
detail = { 20, -234, 297, 176 },
|
||||
exit = { "CENTER", "TOPLEFT", 305, -422 },
|
||||
sep = { 15, -221, 331 },
|
||||
};
|
||||
|
||||
-- Reagents render in a 2-column grid inside the detail scroll child (see
|
||||
-- the detail pane below). The detail is a real ScrollFrame like the
|
||||
-- native TradeSkillFrame, so the whole pane pixel-scrolls and clips
|
||||
-- partial reagent rows — `REAGENT_ROW_HEIGHT` is just the vertical stride
|
||||
-- of one reagent row.
|
||||
local REAGENT_ROW_HEIGHT = 43;
|
||||
|
||||
-- Scroll-frame templates. Stock mimics the native TradeSkillFrame, whose
|
||||
-- list/detail scrolls use the ClassTrainer templates (they add the
|
||||
-- decorative UI-ClassTrainer-ScrollBar track). Turtle's HD frame art
|
||||
-- doesn't want that groove, so it keeps the plain templates. Both detail
|
||||
-- templates are real ScrollFrames (ClassTrainerDetail... inherits
|
||||
-- UIPanelScrollFrameTemplate), so the pixel-scroll logic is identical.
|
||||
local LIST_SCROLL_TEMPLATE = TURTLE and "FauxScrollFrameTemplate"
|
||||
or "ClassTrainerListScrollFrameTemplate";
|
||||
local DETAIL_SCROLL_TEMPLATE = TURTLE and "UIPanelScrollFrameTemplate"
|
||||
or "ClassTrainerDetailScrollFrameTemplate";
|
||||
|
||||
local PROFESSION_ICONS = {
|
||||
[171] = "Trade_Alchemy",
|
||||
[164] = "Trade_BlackSmithing",
|
||||
[185] = "INV_Misc_Food_15", -- Cooking
|
||||
[333] = "Trade_Engraving", -- Enchanting
|
||||
[202] = "Trade_Engineering",
|
||||
[129] = "Spell_Holy_SealOfSacrifice", -- First Aid
|
||||
[165] = "INV_Misc_ArmorKit_17", -- Leatherworking
|
||||
[197] = "Trade_Tailoring",
|
||||
[186] = "Trade_Mining",
|
||||
[182] = "Trade_Herbalism",
|
||||
[393] = "INV_Misc_Pelt_Wolf_01", -- Skinning
|
||||
[356] = "Trade_Fishing",
|
||||
};
|
||||
|
||||
if TURTLE then
|
||||
PROFESSION_ICONS[142] = "Trade_Survival"
|
||||
PROFESSION_ICONS[755] = "INV_Misc_Gem_01" -- Jewelcrafting
|
||||
end
|
||||
|
||||
local function ProfessionIcon(skillLineID)
|
||||
local icon = PROFESSION_ICONS[skillLineID];
|
||||
return icon and ("Interface\\Icons\\" .. icon)
|
||||
or "Interface\\Icons\\INV_Misc_QuestionMark";
|
||||
end
|
||||
|
||||
local function DifficultyBand(skill, hi, lo)
|
||||
if not hi or hi <= 0 then
|
||||
return 3;
|
||||
end
|
||||
if not lo or lo == 0 then
|
||||
lo = (hi ~= 25) and (hi - 25) or 0;
|
||||
end
|
||||
local yellow = (hi + lo) / 2;
|
||||
if skill < lo then
|
||||
return 0; -- orange (optimal)
|
||||
elseif skill < yellow then
|
||||
return 1; -- yellow (medium)
|
||||
elseif skill < hi then
|
||||
return 2; -- green (easy)
|
||||
end
|
||||
return 3; -- grey (trivial)
|
||||
end
|
||||
|
||||
local BAND_COLOR = {
|
||||
[0] = DIFFICULT_DIFFICULTY_COLOR, -- orange
|
||||
[1] = FAIR_DIFFICULTY_COLOR, -- yellow
|
||||
[2] = EASY_DIFFICULTY_COLOR, -- green
|
||||
[3] = TRIVIAL_DIFFICULTY_COLOR, -- grey
|
||||
};
|
||||
|
||||
local function CraftableCount(entry)
|
||||
local reagents = entry.reagents;
|
||||
if not reagents or table.getn(reagents) == 0 then
|
||||
return nil;
|
||||
end
|
||||
local best;
|
||||
for i = 1, table.getn(reagents) do
|
||||
local r = reagents[i];
|
||||
local need = r.count or 1;
|
||||
local n = math.floor((C_Item.GetItemCount(r.itemID) or 0) / need);
|
||||
if not best or n < best then
|
||||
best = n;
|
||||
end
|
||||
end
|
||||
return best;
|
||||
end
|
||||
|
||||
local function ParseTradeLink(link)
|
||||
-- Current format, with the linker's name: trade:id:cur:max:Name:bits
|
||||
local _, _, id, cur, max, who, bits =
|
||||
string.find(link, "^trade:(%d+):(%d+):(%d+):([^:]+):([%w%+/]*)$");
|
||||
if not id then
|
||||
-- Legacy format (no name): trade:id:cur:max:bits
|
||||
who = nil;
|
||||
_, _, id, cur, max, bits =
|
||||
string.find(link, "^trade:(%d+):(%d+):(%d+):([%w%+/]*)$");
|
||||
end
|
||||
if not id then
|
||||
return nil;
|
||||
end
|
||||
return tonumber(id), tonumber(cur), tonumber(max), who, bits or "";
|
||||
end
|
||||
|
||||
------------------------------------------------------------------------------
|
||||
-- Display frame (built lazily on first use)
|
||||
------------------------------------------------------------------------------
|
||||
|
||||
local frame;
|
||||
local function ResolveSubclasses(list, onLoaded)
|
||||
local present, subs, anyItem = {}, {}, false;
|
||||
for i = 1, table.getn(list) do
|
||||
local r = list[i];
|
||||
if r.createdItem and r.createdItem > 0 then
|
||||
anyItem = true;
|
||||
if not r.subclass then
|
||||
-- GetItemInfoInstant's 3rd return is the localized subclass
|
||||
-- name (or nil when uncached).
|
||||
local _, _, subType = C_Item.GetItemInfoInstant(r.createdItem);
|
||||
if subType and subType ~= "" then
|
||||
r.subclass = subType;
|
||||
elseif onLoaded then
|
||||
-- Not cached — re-derive when the item loads.
|
||||
Item:CreateFromItemID(r.createdItem):ContinueOnItemLoad(onLoaded);
|
||||
end
|
||||
end
|
||||
if r.subclass and not present[r.subclass] then
|
||||
present[r.subclass] = true;
|
||||
table.insert(subs, r.subclass);
|
||||
end
|
||||
end
|
||||
end
|
||||
table.sort(subs);
|
||||
return subs, anyItem;
|
||||
end
|
||||
|
||||
local SUBCLASS_ALL = {};
|
||||
|
||||
local function SubClassButton_OnClick()
|
||||
local v = this.value;
|
||||
if v == SUBCLASS_ALL then
|
||||
v = nil;
|
||||
end
|
||||
frame.subclassFilter = v;
|
||||
UIDropDownMenu_SetText(v or ALL_SUBCLASSES, frame.dropdown);
|
||||
frame:ApplyFilter();
|
||||
end
|
||||
|
||||
local function SubClassDropDown_Initialize()
|
||||
local info = {};
|
||||
info.text = ALL_SUBCLASSES;
|
||||
info.value = SUBCLASS_ALL;
|
||||
info.checked = (frame.subclassFilter == nil);
|
||||
info.func = SubClassButton_OnClick;
|
||||
UIDropDownMenu_AddButton(info);
|
||||
local subs = frame.subclasses or {};
|
||||
for i = 1, table.getn(subs) do
|
||||
local b = {};
|
||||
b.text = subs[i];
|
||||
b.value = subs[i];
|
||||
b.checked = (frame.subclassFilter == subs[i]);
|
||||
b.func = SubClassButton_OnClick;
|
||||
UIDropDownMenu_AddButton(b);
|
||||
end
|
||||
end
|
||||
|
||||
local function RefreshSubclasses()
|
||||
if not (frame and frame:IsShown() and frame.recipes) then
|
||||
return;
|
||||
end
|
||||
local subs, anyItem = ResolveSubclasses(frame.recipes, RefreshSubclasses);
|
||||
frame.subclasses = subs;
|
||||
if anyItem then
|
||||
UIDropDownMenu_Initialize(frame.dropdown, SubClassDropDown_Initialize);
|
||||
UIDropDownMenu_SetWidth(120, frame.dropdown);
|
||||
UIDropDownMenu_SetText(frame.subclassFilter or ALL_SUBCLASSES, frame.dropdown);
|
||||
frame.dropdown:Show();
|
||||
else
|
||||
frame.dropdown:Hide();
|
||||
end
|
||||
if frame.subclassFilter then
|
||||
frame:ApplyFilter();
|
||||
end
|
||||
end
|
||||
|
||||
local function CreateFrame_TradeSkillLink()
|
||||
local f = CreateFrame("Frame", "ClassicAPITradeSkillLinkFrame", UIParent);
|
||||
f:SetSize(FRAME_W, FRAME_H);
|
||||
f:SetPoint("CENTER");
|
||||
f:SetMovable(true);
|
||||
f:EnableMouse(true);
|
||||
f:SetHitRectInsets(LO.hit[1], LO.hit[2], LO.hit[3], LO.hit[4]);
|
||||
f:RegisterForDrag("LeftButton");
|
||||
f:SetScript("OnDragStart", function() this:StartMoving(); end);
|
||||
f:SetScript("OnDragStop", function() this:StopMovingOrSizing(); end);
|
||||
f:SetFrameStrata("DIALOG");
|
||||
f:Hide();
|
||||
tinsert(UISpecialFrames, f:GetName())
|
||||
|
||||
f:SetScript("OnShow", function() PlaySound("igCharacterInfoOpen"); end);
|
||||
f:SetScript("OnHide", function() PlaySound("igCharacterInfoClose"); end);
|
||||
|
||||
local portrait = f:CreateTexture(nil, "BACKGROUND");
|
||||
portrait:SetSize(60, 60);
|
||||
portrait:SetPoint("TOPLEFT", 7, -6);
|
||||
f.portrait = portrait;
|
||||
|
||||
for i = 1, table.getn(LO.quads) do
|
||||
local q = LO.quads[i];
|
||||
local tx = f:CreateTexture(nil, "BORDER");
|
||||
tx:SetTexture(q[1]);
|
||||
tx:SetSize(q[2], q[3]);
|
||||
tx:SetPoint(q[4]);
|
||||
end
|
||||
|
||||
-- Horizontal divider between the recipe list and the detail pane.
|
||||
-- Stock only (Turtle's HD frame art already has its own).
|
||||
if LO.sep then
|
||||
-- Decoded the BLP: it's a thin divider rod whose graphic lives in the
|
||||
-- top quarter of the 256x64 texture (a 2nd rod fills the next quarter,
|
||||
-- bottom half empty). So sample the top quarter, stretched to width —
|
||||
-- the same region the native TradeSkillFrame uses for this divider.
|
||||
local bar = f:CreateTexture(nil, "ARTWORK");
|
||||
bar:SetTexture("Interface\\ClassTrainerFrame\\UI-ClassTrainer-HorizontalBar");
|
||||
bar:SetTexCoord(0, 1, 0, 0.25);
|
||||
bar:SetSize(LO.sep[3], 16);
|
||||
bar:SetPoint("TOPLEFT", LO.sep[1], LO.sep[2]);
|
||||
end
|
||||
|
||||
local title = f:CreateFontString(nil, "OVERLAY", "GameFontNormal");
|
||||
title:SetPoint("TOP", 0, -18);
|
||||
f.title = title;
|
||||
|
||||
local close = CreateFrame("Button", nil, f, "UIPanelCloseButton");
|
||||
close:SetPoint("TOPRIGHT", LO.close[1], LO.close[2]);
|
||||
|
||||
local exit = CreateFrame("Button", nil, f, "UIPanelButtonTemplate");
|
||||
exit:SetSize(80, 22);
|
||||
exit:SetPoint(LO.exit[1], f, LO.exit[2], LO.exit[3], LO.exit[4]);
|
||||
exit:SetText(EXIT);
|
||||
exit:SetScript("OnClick", function() f:Hide(); end);
|
||||
|
||||
local bar = CreateFrame("StatusBar", nil, f);
|
||||
bar:SetSize(LO.bar[1], LO.bar[2]);
|
||||
bar:SetPoint("TOPLEFT", LO.bar[3], LO.bar[4]);
|
||||
bar:SetStatusBarTexture("Interface\\PaperDollInfoFrame\\UI-Character-Skills-Bar");
|
||||
bar:SetStatusBarColor(0.0, 0.0, 1.0, 0.5);
|
||||
bar:SetMinMaxValues(0, 1);
|
||||
local barBg = bar:CreateTexture(nil, "BACKGROUND");
|
||||
barBg:SetAllPoints(bar);
|
||||
barBg:SetTexture(1, 1, 1, 0.2);
|
||||
barBg:SetVertexColor(0.0, 0.0, 0.75, 0.5);
|
||||
-- Border: tooltip edge around the bar (TradeSkillRankFrameBorder).
|
||||
local border = CreateFrame("Frame", nil, bar);
|
||||
border:SetSize(LO.barBdr[1], LO.barBdr[2]);
|
||||
border:SetPoint("LEFT", -5, 1);
|
||||
border:SetBackdrop({
|
||||
edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border", edgeSize = 16,
|
||||
});
|
||||
border:SetBackdropBorderColor(0.4, 0.4, 0.4);
|
||||
local barName = bar:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall");
|
||||
barName:SetPoint("LEFT", 6, 1);
|
||||
local barRank = bar:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall");
|
||||
barRank:SetJustifyH("LEFT");
|
||||
barRank:SetWidth(128);
|
||||
barRank:SetPoint("LEFT", barName, "RIGHT", 13, 0);
|
||||
f.bar = bar;
|
||||
f.barName = barName;
|
||||
f.barRank = barRank;
|
||||
|
||||
local summary = f:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall");
|
||||
summary:SetPoint(LO.summary[1], LO.summary[2], LO.summary[3]);
|
||||
f.summary = summary;
|
||||
|
||||
local dropdown = CreateFrame("Frame", "ClassicAPITradeSkillLinkSubClass", f,
|
||||
"UIDropDownMenuTemplate");
|
||||
dropdown:SetPoint("TOPLEFT", LO.drop[1], LO.drop[2]);
|
||||
f.dropdown = dropdown;
|
||||
f.subclassFilter = nil; -- nil = all subclasses
|
||||
|
||||
local scroll = CreateFrame("ScrollFrame", "ClassicAPITradeSkillLinkScroll",
|
||||
f, LIST_SCROLL_TEMPLATE);
|
||||
scroll:SetSize(LO.scroll[1], LO.scroll[2]);
|
||||
scroll:SetPoint("TOPLEFT", LO.scroll[3], LO.scroll[4]);
|
||||
scroll:SetScript("OnVerticalScroll", function()
|
||||
FauxScrollFrame_OnVerticalScroll(ROW_HEIGHT, function() f:Refresh(); end)
|
||||
end)
|
||||
f.scroll = scroll;
|
||||
|
||||
f.rows = {};
|
||||
for i = 1, NUM_ROWS do
|
||||
local rowName = "ClassicAPITradeSkillLinkRow" .. i;
|
||||
local row = CreateFrame("Button", rowName, f,
|
||||
"ClassTrainerSkillButtonTemplate");
|
||||
row:SetWidth(290); -- height (16) comes from the template
|
||||
if i == 1 then
|
||||
row:SetPoint("TOPLEFT", scroll, "TOPLEFT", 0, 0);
|
||||
else
|
||||
row:SetPoint("TOPLEFT", f.rows[i - 1], "BOTTOMLEFT", 0, 0);
|
||||
end
|
||||
|
||||
row:SetNormalTexture("");
|
||||
row:SetDisabledTexture("");
|
||||
row:SetHighlightTexture("");
|
||||
|
||||
local txt = getglobal(rowName .. "Text");
|
||||
if txt then
|
||||
txt:ClearAllPoints();
|
||||
txt:SetPoint("LEFT", row, "LEFT", 4, 0);
|
||||
end
|
||||
|
||||
local sel = row:CreateTexture(nil, "BACKGROUND");
|
||||
sel:SetTexture("Interface\\Buttons\\UI-Listbox-Highlight2");
|
||||
sel:SetAllPoints(row);
|
||||
sel:Hide();
|
||||
row.select = sel;
|
||||
|
||||
-- Override the template's trainer scripts with ours.
|
||||
row:SetScript("OnClick", function()
|
||||
if this.entry then
|
||||
f:SelectRecipe(this.entry);
|
||||
end
|
||||
end);
|
||||
|
||||
f.rows[i] = row;
|
||||
end
|
||||
|
||||
-- Detail pane: a real ScrollFrame (like the native TradeSkillFrame's
|
||||
-- TradeSkillDetailScrollFrame) whose scroll child holds the product
|
||||
-- header + reagent grid, so the whole pane pixel-scrolls — clipping
|
||||
-- partial reagent rows — with the standard UIPanelScrollBar. The bar
|
||||
-- auto-hides when the content fits (scrollBarHideable).
|
||||
local detailScroll = CreateFrame("ScrollFrame",
|
||||
"ClassicAPITradeSkillLinkDetailScroll", f, DETAIL_SCROLL_TEMPLATE);
|
||||
detailScroll:SetSize(LO.detail[3], LO.detail[4]);
|
||||
detailScroll:SetPoint("TOPLEFT", LO.detail[1], LO.detail[2]);
|
||||
-- Bar visibility + wheel are driven per-render by SetDetailBarShown (from
|
||||
-- the computed overflow). `scrollBarHideable` still lets the template's
|
||||
-- ScrollFrame_OnScrollRangeChanged manage the slider on range changes.
|
||||
-- Start with the wheel off; the first RenderDetail/ClearDetail sets it.
|
||||
detailScroll.scrollBarHideable = 1;
|
||||
detailScroll:EnableMouseWheel(false);
|
||||
f.detailScroll = detailScroll;
|
||||
|
||||
local detailChild = CreateFrame("Frame",
|
||||
"ClassicAPITradeSkillLinkDetailChild", detailScroll);
|
||||
detailChild:SetSize(LO.detail[3], LO.detail[4]);
|
||||
detailScroll:SetScrollChild(detailChild);
|
||||
f.detailChild = detailChild;
|
||||
|
||||
local prodIcon = CreateFrame("Button", nil, detailChild);
|
||||
prodIcon:SetSize(37, 37); -- native TradeSkillSkillIcon (37x37 @ 8,-3)
|
||||
prodIcon:SetPoint("TOPLEFT", 8, -3);
|
||||
prodIcon:SetNormalTexture("Interface\\Icons\\INV_Misc_QuestionMark");
|
||||
local hdrLeft = detailChild:CreateTexture(nil, "BACKGROUND");
|
||||
hdrLeft:SetTexture("Interface\\ClassTrainerFrame\\UI-ClassTrainer-DetailHeaderLeft");
|
||||
hdrLeft:SetSize(256, 64); -- Blizzard's native fill width (+64 cap = 320 total)
|
||||
hdrLeft:SetPoint("TOPLEFT", prodIcon, "TOPLEFT", -8, 6);
|
||||
local hdrRight = detailChild:CreateTexture(nil, "BACKGROUND");
|
||||
hdrRight:SetTexture("Interface\\ClassTrainerFrame\\UI-ClassTrainer-DetailHeaderRight");
|
||||
hdrRight:SetSize(64, 64);
|
||||
hdrRight:SetPoint("TOPLEFT", hdrLeft, "TOPRIGHT", 0, 0);
|
||||
local prodCount = prodIcon:CreateFontString(nil, "ARTWORK", "NumberFontNormal");
|
||||
prodCount:SetPoint("BOTTOMRIGHT", -5, 2);
|
||||
prodIcon.count = prodCount;
|
||||
f.prodIcon = prodIcon;
|
||||
|
||||
local prodName = detailChild:CreateFontString(nil, "ARTWORK", "GameFontNormal");
|
||||
prodName:SetPoint("LEFT", prodIcon, "RIGHT", 5, 0);
|
||||
prodName:SetWidth(LO.detail[3] - 60);
|
||||
prodName:SetJustifyH("LEFT");
|
||||
prodName:SetJustifyV("MIDDLE");
|
||||
f.prodName = prodName;
|
||||
|
||||
local prodDesc = detailChild:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall");
|
||||
prodDesc:SetPoint("TOPLEFT", prodIcon, "BOTTOMLEFT", 0, -6);
|
||||
prodDesc:SetWidth(LO.detail[3] - 20);
|
||||
prodDesc:SetJustifyH("LEFT");
|
||||
prodDesc:SetJustifyV("TOP");
|
||||
f.prodDesc = prodDesc;
|
||||
|
||||
local reagentLabel = detailChild:CreateFontString(nil, "ARTWORK", "GameFontNormalSmall");
|
||||
reagentLabel:SetPoint("TOPLEFT", prodDesc, "BOTTOMLEFT", 0, -8);
|
||||
reagentLabel:SetText(SPELL_REAGENTS or "Reagents:");
|
||||
f.reagentLabel = reagentLabel;
|
||||
|
||||
prodIcon:SetScript("OnEnter", function()
|
||||
GameTooltip:SetOwner(this, "ANCHOR_RIGHT");
|
||||
if this.itemID then
|
||||
GameTooltip:SetHyperlink("item:"..this.itemID);
|
||||
elseif this.spellID then
|
||||
GameTooltip:SetSpellByID(this.spellID);
|
||||
end
|
||||
GameTooltip:Show();
|
||||
end);
|
||||
prodIcon:SetScript("OnLeave", GameTooltip_Hide);
|
||||
|
||||
-- Reagent buttons live in the scroll child (2 per row), built on
|
||||
-- demand so any reagent count is handled and they scroll/clip with
|
||||
-- the child.
|
||||
f.reagents = {};
|
||||
local function AcquireReagent(i)
|
||||
if f.reagents[i] then
|
||||
return f.reagents[i];
|
||||
end
|
||||
local rowN = math.floor((i - 1) / 2);
|
||||
local col = (i - 1) - rowN * 2;
|
||||
local btn = CreateFrame("Button", nil, detailChild);
|
||||
btn:SetSize(39, 39);
|
||||
btn:SetPoint("TOPLEFT", reagentLabel, "BOTTOMLEFT",
|
||||
col * 134 - 5, -3 - rowN * REAGENT_ROW_HEIGHT);
|
||||
-- Extend the hit area rightward over the name plate so the tooltip
|
||||
-- fires anywhere on the element, not just the icon. Stop short of the
|
||||
-- next column (pitch 134 − icon 39) so hovers don't bleed across.
|
||||
btn:SetHitRectInsets(0, -(134 - 39), 0, 0);
|
||||
btn:SetNormalTexture("Interface\\Icons\\INV_Misc_QuestionMark");
|
||||
local plate = btn:CreateTexture(nil, "BACKGROUND");
|
||||
plate:SetTexture("Interface\\QuestFrame\\UI-QuestItemNameFrame");
|
||||
plate:SetSize(114, 64);
|
||||
plate:SetPoint("LEFT", btn, "RIGHT", -10, 0);
|
||||
local cnt = btn:CreateFontString(nil, "ARTWORK", "NumberFontNormal");
|
||||
cnt:SetPoint("BOTTOMRIGHT", -4, 1);
|
||||
btn.count = cnt;
|
||||
local nm = btn:CreateFontString(nil, "ARTWORK", "GameFontHighlight");
|
||||
nm:SetPoint("LEFT", plate, "LEFT", 15, 0);
|
||||
nm:SetSize(80, 36);
|
||||
nm:SetJustifyH("LEFT");
|
||||
nm:SetJustifyV("MIDDLE");
|
||||
btn.nameText = nm;
|
||||
btn:SetScript("OnEnter", function()
|
||||
if this.itemID then
|
||||
GameTooltip:SetOwner(this, "ANCHOR_RIGHT");
|
||||
GameTooltip:SetHyperlink("item:"..this.itemID);
|
||||
GameTooltip:Show();
|
||||
end
|
||||
end);
|
||||
btn:SetScript("OnClick", function()
|
||||
if this.itemLink and IsShiftKeyDown() and ChatFrameEditBox:IsVisible() then
|
||||
ChatFrameEditBox:Insert(this.itemLink);
|
||||
end
|
||||
end);
|
||||
btn:SetScript("OnLeave", GameTooltip_Hide);
|
||||
f.reagents[i] = btn;
|
||||
return btn;
|
||||
end
|
||||
|
||||
-- Show the detail bar/borders only when the content overflows the pane.
|
||||
-- Driven by our own computed overflow, NOT the engine: scrollBarHideable's
|
||||
-- auto-hide only fires on a range CHANGE (so content that fits from the
|
||||
-- start never hides), and GetVerticalScrollRange isn't reliably readable
|
||||
-- the same tick as UpdateScrollChildRect.
|
||||
function f:SetDetailBarShown(show)
|
||||
self.detailScroll:EnableMouseWheel(show);
|
||||
local base = "ClassicAPITradeSkillLinkDetailScroll";
|
||||
local sb = getglobal(base .. "ScrollBar");
|
||||
if sb then sb:SetShown(show) end
|
||||
local top = getglobal(base .. "Top");
|
||||
if top then top:SetShown(show) end
|
||||
local bottom = getglobal(base .. "Bottom");
|
||||
if bottom then bottom:SetShown(show) end
|
||||
end
|
||||
|
||||
function f:RenderDetail(entry)
|
||||
local function itemInfo(id)
|
||||
local item = Item:CreateFromItemID(id);
|
||||
if not item:IsItemDataCached() then
|
||||
item:ContinueOnItemLoad(function()
|
||||
if self:IsShown() and self.selectedSpellID == entry.spellID then
|
||||
self:RenderDetail(entry);
|
||||
end
|
||||
end);
|
||||
end
|
||||
return item:GetItemName(), item:GetItemIcon(), item:GetItemLink();
|
||||
end
|
||||
|
||||
local prodTex, prodText, prodLink;
|
||||
local created = entry.createdItem or 0;
|
||||
if created > 0 then
|
||||
local name, tex, link = itemInfo(created);
|
||||
prodText = name or entry.name;
|
||||
prodTex = tex;
|
||||
prodLink = link;
|
||||
else
|
||||
prodText = entry.name;
|
||||
prodTex = C_Spell.GetSpellTexture(entry.spellID);
|
||||
end
|
||||
local descText = (created > 0) and ""
|
||||
or (C_Spell.GetSpellDescription(entry.spellID) or "");
|
||||
self.prodDesc:SetText(descText);
|
||||
self.prodIcon:SetNormalTexture(prodTex or
|
||||
"Interface\\Icons\\INV_Misc_QuestionMark");
|
||||
self.prodName:SetText(prodText or "");
|
||||
self.prodName:SetTextColor(NORMAL_FONT_COLOR:GetRGB());
|
||||
self.prodIcon.itemLink = prodLink; -- item tooltip when created > 0
|
||||
self.prodIcon.spellID = entry.spellID; -- else spell tooltip
|
||||
local made = entry.numMade or 0;
|
||||
self.prodIcon.count:SetText(made > 1 and tostring(made) or "");
|
||||
self.prodIcon:Show();
|
||||
|
||||
-- Fill every reagent slot; the scroll child clips/scrolls the
|
||||
-- overflow. Buttons past the count are hidden.
|
||||
local reagents = entry.reagents or {};
|
||||
local total = table.getn(reagents);
|
||||
for i = 1, total do
|
||||
local btn = AcquireReagent(i);
|
||||
local reagent = reagents[i];
|
||||
local name, tex, link = itemInfo(reagent.itemID);
|
||||
btn:SetNormalTexture(tex or "Interface\\Icons\\INV_Misc_QuestionMark");
|
||||
btn.itemLink = link;
|
||||
btn.itemID = reagent.itemID
|
||||
btn.nameText:SetText(name or ("item:" .. reagent.itemID));
|
||||
local need = reagent.count or 1;
|
||||
local have = C_Item.GetItemCount(reagent.itemID) or 0;
|
||||
if have >= need then
|
||||
local r, g, b = HIGHLIGHT_FONT_COLOR:GetRGB()
|
||||
btn:GetNormalTexture():SetVertexColor(r, g, b);
|
||||
btn.nameText:SetTextColor(r, g, b);
|
||||
else
|
||||
local r, g, b = GRAY_FONT_COLOR:GetRGB()
|
||||
btn:GetNormalTexture():SetVertexColor(r, g, b);
|
||||
btn.nameText:SetTextColor(r, g, b);
|
||||
end
|
||||
local haveText = (have >= 100) and "*" or tostring(have);
|
||||
btn.count:SetText(haveText .. " /" .. need);
|
||||
btn:Show();
|
||||
end
|
||||
for i = total + 1, table.getn(self.reagents) do
|
||||
self.reagents[i].itemLink = nil;
|
||||
self.reagents[i].itemID = nil;
|
||||
self.reagents[i]:Hide();
|
||||
end
|
||||
|
||||
local function applyContentHeight()
|
||||
local contentH = LO.detail[4];
|
||||
if total > 0 then
|
||||
local childTop = self.detailChild:GetTop();
|
||||
local lastBtn = self.reagents[total];
|
||||
local lastBottom = lastBtn and lastBtn:GetBottom();
|
||||
if childTop and lastBottom then
|
||||
-- +22: ~12px name-plate overhang below the icon + ~10px pad.
|
||||
contentH = (childTop - lastBottom) + 22;
|
||||
end
|
||||
end
|
||||
self.detailChild:SetHeight(math.max(contentH, LO.detail[4]));
|
||||
-- Recompute the scroll range from the child's new height, then
|
||||
-- show the bar only if the content actually overflows the pane.
|
||||
self.detailScroll:UpdateScrollChildRect();
|
||||
self:SetDetailBarShown(contentH > LO.detail[4] + 0.5);
|
||||
end
|
||||
applyContentHeight();
|
||||
local sb = getglobal("ClassicAPITradeSkillLinkDetailScrollScrollBar");
|
||||
if sb then
|
||||
sb:SetValue(0);
|
||||
end
|
||||
self.detailScroll:SetVerticalScroll(0);
|
||||
RunNextFrame(function()
|
||||
if self:IsShown() and self.selectedSpellID == entry.spellID then
|
||||
applyContentHeight();
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
function f:SelectRecipe(entry)
|
||||
self.selectedSpellID = entry.spellID;
|
||||
self.selectedEntry = entry;
|
||||
self:RenderDetail(entry); -- also resets the detail scroll to top
|
||||
self:Refresh();
|
||||
end
|
||||
|
||||
function f:ClearDetail()
|
||||
self.selectedSpellID = nil;
|
||||
self.selectedEntry = nil;
|
||||
self.prodIcon:Hide();
|
||||
self.prodName:SetText("");
|
||||
self.prodDesc:SetText("");
|
||||
for i = 1, table.getn(self.reagents) do
|
||||
self.reagents[i].itemLink = nil;
|
||||
self.reagents[i].itemID = nil;
|
||||
self.reagents[i]:Hide();
|
||||
end
|
||||
self.detailChild:SetHeight(LO.detail[4]);
|
||||
self.detailScroll:UpdateScrollChildRect();
|
||||
self:SetDetailBarShown(false);
|
||||
self.detailScroll:SetVerticalScroll(0);
|
||||
end
|
||||
|
||||
function f:Refresh()
|
||||
local recipes = self.displayed or {};
|
||||
local total = table.getn(recipes);
|
||||
FauxScrollFrame_Update(self.scroll, total, NUM_ROWS, ROW_HEIGHT);
|
||||
local offset = FauxScrollFrame_GetOffset(self.scroll);
|
||||
for i = 1, NUM_ROWS do
|
||||
local row = self.rows[i];
|
||||
local entry = recipes[offset + i];
|
||||
if entry then
|
||||
-- Append " [N]" when the reader can craft any (Blizzard's list).
|
||||
local craftable = CraftableCount(entry);
|
||||
local label = entry.name or "";
|
||||
if craftable and craftable > 0 then
|
||||
label = label .. " [" .. craftable .. "]";
|
||||
end
|
||||
row:SetText(label);
|
||||
local r, g, b = BAND_COLOR[entry.band or 3]:GetRGB();
|
||||
if self.selectedSpellID and entry.spellID == self.selectedSpellID then
|
||||
row.select:SetVertexColor(r, g, b);
|
||||
row.select:Show();
|
||||
row:SetTextColor(1, 1, 1);
|
||||
else
|
||||
row.select:Hide();
|
||||
row:SetTextColor(r, g, b);
|
||||
end
|
||||
row.spellID = entry.spellID;
|
||||
row.entry = entry;
|
||||
row:Show();
|
||||
else
|
||||
row.spellID = nil;
|
||||
row.entry = nil;
|
||||
row.select:Hide();
|
||||
row:Hide();
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function f:ApplyFilter()
|
||||
local src = self.recipes or {};
|
||||
if not self.subclassFilter then
|
||||
self.displayed = src;
|
||||
else
|
||||
local out = {};
|
||||
for i = 1, table.getn(src) do
|
||||
if src[i].subclass == self.subclassFilter then
|
||||
table.insert(out, src[i]);
|
||||
end
|
||||
end
|
||||
self.displayed = out;
|
||||
end
|
||||
local sb = getglobal("ClassicAPITradeSkillLinkScrollScrollBar");
|
||||
if sb then
|
||||
sb:SetValue(0);
|
||||
end
|
||||
self:Refresh();
|
||||
end
|
||||
|
||||
f:RegisterEvent("BAG_UPDATE_DELAYED");
|
||||
f:SetScript("OnEvent", function()
|
||||
if not f:IsShown() then
|
||||
return;
|
||||
end
|
||||
f:Refresh();
|
||||
if f.selectedEntry then
|
||||
f:RenderDetail(f.selectedEntry);
|
||||
end
|
||||
end);
|
||||
|
||||
return f;
|
||||
end
|
||||
|
||||
local function ShowTradeSkillLink(link, text)
|
||||
local id, cur, max, who, bits = ParseTradeLink(link);
|
||||
if not id then
|
||||
return false;
|
||||
end
|
||||
local recipes = C_TradeSkillUI.GetTradeSkillListRecipes(id, bits);
|
||||
if not recipes then
|
||||
return false;
|
||||
end
|
||||
|
||||
local prof = text and string.match(text, "|h%[(.+)%]|h") or "Trade Skills";
|
||||
local total = table.getn(recipes);
|
||||
local knownList = {};
|
||||
for i = 1, total do
|
||||
local r = recipes[i];
|
||||
if r.isKnown then
|
||||
r.band = DifficultyBand(cur or 0, r.trivialLevel, r.greenLevel);
|
||||
r.name = C_Spell.GetSpellName(r.spellID) or ("spell:" .. r.spellID);
|
||||
table.insert(knownList, r);
|
||||
end
|
||||
end
|
||||
table.sort(knownList, function(a, b)
|
||||
if a.band ~= b.band then
|
||||
return a.band < b.band;
|
||||
end
|
||||
return a.name < b.name;
|
||||
end);
|
||||
local known = table.getn(knownList);
|
||||
|
||||
if not frame then
|
||||
frame = CreateFrame_TradeSkillLink();
|
||||
end
|
||||
frame.title:SetText(who and who ~= "" and (who .. " - " .. prof) or prof);
|
||||
SetPortraitToTexture(frame.portrait, ProfessionIcon(id));
|
||||
frame.bar:SetMinMaxValues(0, (max and max > 0) and max or 1);
|
||||
frame.bar:SetValue(cur or 0);
|
||||
frame.barName:SetText(prof);
|
||||
frame.barRank:SetFormattedText("%d/%d", cur or 0, max or 0);
|
||||
frame.summary:SetFormattedText("%d of %d recipes known", known, total);
|
||||
frame.recipes = knownList;
|
||||
frame.subclassFilter = nil;
|
||||
|
||||
frame:ClearDetail();
|
||||
frame:Show();
|
||||
RefreshSubclasses();
|
||||
frame:ApplyFilter();
|
||||
local first = frame.displayed and frame.displayed[1];
|
||||
if first then
|
||||
frame:SelectRecipe(first);
|
||||
end
|
||||
return true;
|
||||
end
|
||||
|
||||
------------------------------------------------------------------------------
|
||||
-- Click interception: handle `trade:` before the engine's SetHyperlink (which
|
||||
-- in 1.12 only knows item:/enchant: and would reject the link).
|
||||
------------------------------------------------------------------------------
|
||||
|
||||
local originalSetItemRef = SetItemRef;
|
||||
function SetItemRef(link, text, button, chatFrame)
|
||||
if type(link) == "string" and string.sub(link, 1, 6) == "trade:" then
|
||||
if IsShiftKeyDown() and ChatFrameEditBox and ChatFrameEditBox:IsVisible() then
|
||||
ChatFrameEditBox:Insert(text);
|
||||
return;
|
||||
end
|
||||
if ShowTradeSkillLink(link, text) then
|
||||
return;
|
||||
end
|
||||
end
|
||||
return originalSetItemRef(link, text, button, chatFrame);
|
||||
end
|
||||
|
||||
local function CreateProfessionLinkButton(parentName, getLink)
|
||||
local parent = _G[parentName];
|
||||
local btnName = parentName .. "LinkButton";
|
||||
if _G[btnName] or not parent then
|
||||
return;
|
||||
end
|
||||
local title = _G[parentName .. "TitleText"];
|
||||
local btn = CreateFrame("Button", btnName, parent);
|
||||
btn:SetSize(16, 16);
|
||||
|
||||
local function reposition()
|
||||
if not title then
|
||||
return;
|
||||
end
|
||||
btn:ClearAllPoints();
|
||||
if title:GetJustifyH() == "LEFT" then
|
||||
btn:SetPoint("LEFT", title, "LEFT", title:GetStringWidth() + 4, 0);
|
||||
else
|
||||
btn:SetPoint("LEFT", title, "CENTER", title:GetStringWidth() / 2 + 4, 0);
|
||||
end
|
||||
end
|
||||
reposition()
|
||||
btn:SetScript("OnShow", function() RunNextFrame(reposition) end)
|
||||
hooksecurefunc(title, "SetText", function() RunNextFrame(reposition) end)
|
||||
|
||||
local icon = "Interface\\GossipFrame\\PetitionGossipIcon";
|
||||
btn:SetNormalTexture(icon);
|
||||
btn:SetHighlightTexture(icon, "ADD");
|
||||
|
||||
btn:SetScript("OnClick", function()
|
||||
local link = getLink();
|
||||
if not link then
|
||||
return;
|
||||
end
|
||||
if not ChatFrameEditBox:IsVisible() then
|
||||
ChatFrameEditBox:Show();
|
||||
end
|
||||
ChatFrameEditBox:Insert(link);
|
||||
end);
|
||||
btn:SetScript("OnEnter", function()
|
||||
GameTooltip:SetOwner(this, "ANCHOR_TOPLEFT");
|
||||
GameTooltip:SetText(LINK_TRADESKILL_TOOLTIP, nil, nil, nil, nil, 1);
|
||||
GameTooltip:Show();
|
||||
end);
|
||||
btn:SetScript("OnLeave", GameTooltip_Hide);
|
||||
end
|
||||
|
||||
EventUtil.ContinueOnAddOnLoaded("Blizzard_TradeSkillUI", function()
|
||||
CreateProfessionLinkButton("TradeSkillFrame", C_TradeSkillUI.GetTradeSkillListLink);
|
||||
end)
|
||||
|
||||
EventUtil.ContinueOnAddOnLoaded("Blizzard_CraftUI", function()
|
||||
CreateProfessionLinkButton("CraftFrame", C_TradeSkillUI.GetCraftListLink)
|
||||
end)
|
||||
|
||||
EventUtil.ContinueOnAddOnLoaded("AdvancedTradeSkillWindow", function()
|
||||
CreateProfessionLinkButton("ATSWFrame", function()
|
||||
return atsw_oldmode and C_TradeSkillUI.GetCraftListLink() or C_TradeSkillUI.GetTradeSkillListLink()
|
||||
end)
|
||||
end)
|
||||
|
||||
EventUtil.ContinueOnAddOnLoaded("AdvancedTradeSkillWindow2", function()
|
||||
CreateProfessionLinkButton("ATSWFrame", function()
|
||||
return ATSW_TradeSkill() and C_TradeSkillUI.GetTradeSkillListLink() or C_TradeSkillUI.GetCraftListLink()
|
||||
end)
|
||||
end)
|
||||
@@ -1,151 +0,0 @@
|
||||
BINDING_NAME_AOELOOT = "AoE Loot";
|
||||
BINDING_NAME_FOCUSTARGET = "Focus Target";
|
||||
BINDING_NAME_TARGETFOCUS = "Target Focus";
|
||||
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";
|
||||
DEBUFF_SYMBOL_CURSE = "Cu";
|
||||
DEBUFF_SYMBOL_DISEASE = "Di";
|
||||
DEBUFF_SYMBOL_MAGIC = "Ma";
|
||||
DEBUFF_SYMBOL_POISON = "Po";
|
||||
DEBUG_FRAMESTACK = "Frame Stack";
|
||||
EQUIPMENT_MANAGER = "Equipment Manager";
|
||||
EQUIPMENT_MANAGER_IGNORE_SLOT = "Ignore This Slot";
|
||||
EQUIPMENT_MANAGER_IS_DISABLED = "The Equipment Manager is disabled.";
|
||||
EQUIPMENT_MANAGER_ITEMS_MISSING_TOOLTIP = "%d %s |cffff0000(%d missing)|r";
|
||||
EQUIPMENT_MANAGER_PLACE_IN_BAGS = "Place In Bags";
|
||||
EQUIPMENT_MANAGER_UNIGNORE_SLOT = "Include This Slot";
|
||||
EQUIPMENT_SETS = "Equipment Sets: |cFFFFFFFF%s|r";
|
||||
EQUIPMENT_SETS_CANT_RENAME = "An equipment set with that name already exists.";
|
||||
EQUIPMENT_SETS_TOO_MANY = "You cannot create any more new equipment sets.";
|
||||
EQUIPMENT_SET_ASSIGN_TO_SPEC = "Assign to Specialization:";
|
||||
EQUIPMENT_SET_EDIT = "Change Name/Icon";
|
||||
EQUIPMENT_SET_SETTINGS = "Settings";
|
||||
EQUIPSET_EQUIP = "Equip";
|
||||
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";
|
||||
SET_FOCUS = "Set 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";
|
||||
HOURS_MINUTES_SECONDS = "%.2d:%.2d:%.2d";
|
||||
ICON_FILTER_ALL = "All Icons";
|
||||
ICON_FILTER_ITEM = "Items";
|
||||
ICON_FILTER_SPELL = "Spells";
|
||||
ICON_SELECTION_TITLE_CURRENT = "Currently Selected";
|
||||
ITEM_DELTA_DESCRIPTION = "If you replace this item, the following stat changes will occur:";
|
||||
ITEM_MOD_MANA_SHORT = "Mana";
|
||||
ITEM_MOD_HEALTH_SHORT = "Health";
|
||||
ITEM_MOD_AGILITY_SHORT = "Agility";
|
||||
ITEM_MOD_STRENGTH_SHORT = "Strength";
|
||||
ITEM_MOD_INTELLECT_SHORT = "Intellect";
|
||||
ITEM_MOD_SPIRIT_SHORT = "Spirit";
|
||||
ITEM_MOD_STAMINA_SHORT = "Stamina";
|
||||
ITEM_MOD_ATTACK_POWER_SHORT = "Attack Power";
|
||||
ITEM_MOD_RANGED_ATTACK_POWER_SHORT = "Ranged Attack Power";
|
||||
ITEM_MOD_CRIT_MELEE_RATING_SHORT = "Critical Strike (Melee)";
|
||||
ITEM_MOD_CRIT_RANGED_RATING_SHORT = "Critical Strike (Ranged)";
|
||||
ITEM_MOD_HIT_MELEE_RATING_SHORT = "Hit (Melee)";
|
||||
ITEM_MOD_HIT_RANGED_RATING_SHORT = "Hit (Ranged)";
|
||||
ITEM_MOD_HIT_SPELL_RATING_SHORT = "Hit (Spell)";
|
||||
ITEM_MOD_CRIT_SPELL_RATING_SHORT = "Critical Strike (Spell)";
|
||||
ITEM_MOD_SPELL_DAMAGE_DONE_SHORT = "Spell Damage";
|
||||
ITEM_MOD_SPELL_HEALING_DONE_SHORT = "Spell Healing";
|
||||
ITEM_MOD_MANA_REGENERATION_SHORT = "Mana Regeneration";
|
||||
ITEM_MOD_DEFENSE_SKILL_RATING_SHORT = "Defense";
|
||||
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_DAMAGE_PER_SECOND_SHORT = "Damage Per Second";
|
||||
ITEMS_EQUIPPED = "%d |4item:items; equipped";
|
||||
ITEMS_IN_INVENTORY = "%d |4item:items; in inventory";
|
||||
ITEMS_NOT_IN_INVENTORY = "%d |4item:items; missing";
|
||||
ITEMS_VARIABLE_QUANTITY = "%d |4Item:Items;";
|
||||
ITEM_MISSING = "%s missing";
|
||||
ITEM_SLOTS_IGNORED = "%d |4slot:slots; ignored";
|
||||
LARGE_NUMBER_SEPERATOR = ",";
|
||||
MINUTES_SECONDS = "%.2d:%.2d";
|
||||
PAPERDOLL_EQUIPMENTMANAGER = "Equipment Manager";
|
||||
PAPERDOLL_NEWEQUIPMENTSET = "New Set";
|
||||
PERCENTAGE_STRING = "%d%%";
|
||||
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";
|
||||
SLASH_CANCELAURA1 = "/cancelaura";
|
||||
SLASH_CANCELAURA2 = "/cancelaura";
|
||||
SLASH_CANCELFORM1 = "/cancelform";
|
||||
SLASH_CANCELFORM2 = "/cancelform";
|
||||
SLASH_CHANGEACTIONBAR1 = "/changeactionbar";
|
||||
SLASH_CHANGEACTIONBAR2 = "/changeactionbar";
|
||||
SLASH_CLEARFOCUS1 = "/clearfocus";
|
||||
SLASH_CLEARFOCUS2 = "/clearfocus";
|
||||
SLASH_CLEARTARGET1 = "/cleartarget";
|
||||
SLASH_CLEARTARGET2 = "/cleartarget";
|
||||
SLASH_CLICK1 = "/click";
|
||||
SLASH_CLICK2 = "/click";
|
||||
SLASH_DISMOUNT1 = "/dismount";
|
||||
SLASH_DISMOUNT2 = "/dismount";
|
||||
SLASH_EQUIP1 = "/equip";
|
||||
SLASH_EQUIP2 = "/equip";
|
||||
SLASH_EQUIP_SET1 = "/equipset";
|
||||
SLASH_EQUIP_SET2 = "/equipset";
|
||||
SLASH_EQUIP_TO_SLOT1 = "/equipslot";
|
||||
SLASH_EQUIP_TO_SLOT2 = "/equipslot";
|
||||
SLASH_FOCUS1 = "/focus";
|
||||
SLASH_FOCUS2 = "/focus";
|
||||
SLASH_PET_AGGRESSIVE1 = "/petaggressive";
|
||||
SLASH_PET_AGGRESSIVE2 = "/petaggressive";
|
||||
SLASH_PET_ATTACK1 = "/petattack";
|
||||
SLASH_PET_ATTACK2 = "/petattack";
|
||||
SLASH_PET_AUTOCASTOFF1 = "/petautocastoff";
|
||||
SLASH_PET_AUTOCASTOFF2 = "/petautocastoff";
|
||||
SLASH_PET_AUTOCASTON1 = "/petautocaston";
|
||||
SLASH_PET_AUTOCASTON2 = "/petautocaston";
|
||||
SLASH_PET_AUTOCASTTOGGLE1 = "/petautocasttoggle";
|
||||
SLASH_PET_AUTOCASTTOGGLE2 = "/petautocasttoggle";
|
||||
SLASH_PET_DEFENSIVE1 = "/petdefensive";
|
||||
SLASH_PET_DEFENSIVE2 = "/petdefensive";
|
||||
SLASH_PET_FOLLOW1 = "/petfollow";
|
||||
SLASH_PET_FOLLOW2 = "/petfollow";
|
||||
SLASH_PET_PASSIVE1 = "/petpassive";
|
||||
SLASH_PET_PASSIVE2 = "/petpassive";
|
||||
SLASH_PET_STAY1 = "/petstay";
|
||||
SLASH_PET_STAY2 = "/petstay";
|
||||
SLASH_STARTATTACK1 = "/startattack";
|
||||
SLASH_STARTATTACK2 = "/startattack";
|
||||
SLASH_STOPATTACK1 = "/stopattack";
|
||||
SLASH_STOPATTACK2 = "/stopattack";
|
||||
SLASH_STOPCASTING1 = "/stopcasting";
|
||||
SLASH_STOPCASTING2 = "/stopcasting";
|
||||
SLASH_SWAPACTIONBAR1 = "/swapactionbar";
|
||||
SLASH_SWAPACTIONBAR2 = "/swapactionbar";
|
||||
SLASH_TARGET_EXACT1 = "/targetexact";
|
||||
SLASH_TARGET_EXACT2 = "/targetexact";
|
||||
SLASH_TARGET_LAST_ENEMY1 = "/targetlastenemy";
|
||||
SLASH_TARGET_LAST_ENEMY2 = "/targetlastenemy";
|
||||
SLASH_TARGET_LAST_TARGET1 = "/targetlasttarget";
|
||||
SLASH_TARGET_LAST_TARGET2 = "/targetlasttarget";
|
||||
SLASH_TARGET_NEAREST_ENEMY1 = "/targetenemy";
|
||||
SLASH_TARGET_NEAREST_ENEMY2 = "/targetenemy";
|
||||
SLASH_TARGET_NEAREST_ENEMY_PLAYER1 = "/targetenemyplayer";
|
||||
SLASH_TARGET_NEAREST_ENEMY_PLAYER2 = "/targetenemyplayer";
|
||||
SLASH_TARGET_NEAREST_FRIEND1 = "/targetfriend";
|
||||
SLASH_TARGET_NEAREST_FRIEND2 = "/targetfriend";
|
||||
SLASH_TARGET_NEAREST_FRIEND_PLAYER1 = "/targetfriendplayer";
|
||||
SLASH_TARGET_NEAREST_FRIEND_PLAYER2 = "/targetfriendplayer";
|
||||
SLASH_TARGET_NEAREST_PARTY1 = "/targetparty";
|
||||
SLASH_TARGET_NEAREST_PARTY2 = "/targetparty";
|
||||
SLASH_TARGET_NEAREST_RAID1 = "/targetraid";
|
||||
SLASH_TARGET_NEAREST_RAID2 = "/targetraid";
|
||||
SLASH_USE1 = "/use";
|
||||
SLASH_USE2 = "/use";
|
||||
TARGETFOCUS = "Target Focus";
|
||||
LINK_TRADESKILL_TOOLTIP = "Click here to create a link to your profession.";
|
||||
@@ -1,149 +0,0 @@
|
||||
if GetLocale() ~= "ruRU" then return end
|
||||
|
||||
BINDING_NAME_FOCUSTARGET = "Запомненная цель";
|
||||
BINDING_NAME_TARGETFOCUS = "Восстановить цель";
|
||||
CONFIRM_DELETE_EQUIPMENT_SET = "Вы действительно хотите удалить комплект экипировки \"%s\"?";
|
||||
CONFIRM_SAVE_EQUIPMENT_SET = "Хотите сохранить комплект экипировки \"%s\"?";
|
||||
DEBUFF_SYMBOL_CURSE = "Пр";
|
||||
DEBUFF_SYMBOL_DISEASE = "Бз";
|
||||
DEBUFF_SYMBOL_MAGIC = "Мг";
|
||||
DEBUFF_SYMBOL_POISON = "Яд";
|
||||
DEBUG_FRAMESTACK = "Соединение рамок";
|
||||
EQUIPMENT_MANAGER = "Комплекты экипировки";
|
||||
EQUIPMENT_MANAGER_IGNORE_SLOT = "Пропустить ячейку";
|
||||
EQUIPMENT_MANAGER_IS_DISABLED = "Управление экипировкой отключено.";
|
||||
EQUIPMENT_MANAGER_ITEMS_MISSING_TOOLTIP = "%d %s |cffff0000(предмет для ячейки \"%d\" отсутствует)|r";
|
||||
EQUIPMENT_MANAGER_PLACE_IN_BAGS = "Поместить в сумку";
|
||||
EQUIPMENT_MANAGER_UNIGNORE_SLOT = "Учитывать ячейку";
|
||||
EQUIPMENT_SETS = "Комплекты экипировки: |cFFFFFFFF%s|r";
|
||||
EQUIPMENT_SETS_CANT_RENAME = "Это название уже используется для другого комплекта.";
|
||||
EQUIPMENT_SETS_TOO_MANY = "Вы не можете создавать новые комплекты экипировки.";
|
||||
EQUIPMENT_SET_ASSIGN_TO_SPEC = "Выбрать специализацию:";
|
||||
EQUIPMENT_SET_EDIT = "Изменить название/значок";
|
||||
EQUIPMENT_SET_SETTINGS = "Параметры";
|
||||
EQUIPSET_EQUIP = "Надеть";
|
||||
ERR_EQUIPMENT_MANAGER_BAGS_FULL = "Не удалось заменить комплект обмундирования. Инвентарь переполнен.";
|
||||
ERR_EQUIPMENT_MANAGER_COMBAT_SWAP_S = "Некоторые предметы из набора \"%s\" не будут экипированы, поскольку вы участвуете в бою.";
|
||||
ERR_EQUIPMENT_MANAGER_MISSING_ITEM_S = "Недостает одного или более предметов из набора \"%s\".";
|
||||
CLEAR_FOCUS = "Отменить запоминание цели";
|
||||
SET_FOCUS = "Запомнить цель";
|
||||
FOCUSTARGET = "Запомнить цель";
|
||||
ITEMS_VARIABLE_QUANTITY = "%d |4предмет:предмета:предметов;";
|
||||
ITEMS_EQUIPPED = "%d |4предмет экипирован:предмета экипировано:предметов экипировано;";
|
||||
ITEMS_IN_INVENTORY = "%d |4предмет:предмета:предметов; в сумках";
|
||||
ITEM_SLOTS_IGNORED = "%d |4ячейка пропущена:ячейки пропущены:ячейки пропущены;";
|
||||
ITEM_MISSING = "Предмет для ячейки %s отсутствует";
|
||||
ITEMS_NOT_IN_INVENTORY = "%d |4предмет отсутствует:предмета отсутствует:предметов отсутствуют;";
|
||||
TARGETFOCUS = "Восстановить цель";
|
||||
-- BINDING_NAME_AOELOOT = "AoE Loot";
|
||||
COPPER_AMOUNT_SYMBOL = "м";
|
||||
GEARSETS_POPUP_TEXT = "Введите название комплекта (не более 16 символов):";
|
||||
GENERIC_FRACTION_STRING = "%d/%d";
|
||||
GOLD_AMOUNT_SYMBOL = "з";
|
||||
HOURS_MINUTES_SECONDS = "%.2d:%.2d:%.2d";
|
||||
ICON_FILTER_ALL = "Все значки";
|
||||
ICON_FILTER_ITEM = "Предметы";
|
||||
ICON_FILTER_SPELL = "Заклинания";
|
||||
ICON_SELECTION_TITLE_CURRENT = "Текущий выбор";
|
||||
ITEM_DELTA_DESCRIPTION = "Если вы замените этот предмет, произойдут следующие изменения:";
|
||||
ITEM_MOD_MANA_SHORT = "к мане";
|
||||
ITEM_MOD_HEALTH_SHORT = "к здоровью";
|
||||
ITEM_MOD_AGILITY_SHORT = "к ловкости";
|
||||
ITEM_MOD_STRENGTH_SHORT = "к силе";
|
||||
ITEM_MOD_INTELLECT_SHORT = "к интеллекту";
|
||||
ITEM_MOD_SPIRIT_SHORT = "к духу";
|
||||
ITEM_MOD_STAMINA_SHORT = "к выносливости";
|
||||
ITEM_MOD_ATTACK_POWER_SHORT = "к силе атаки";
|
||||
ITEM_MOD_RANGED_ATTACK_POWER_SHORT = "к силе атаки дальнего боя";
|
||||
ITEM_MOD_CRIT_MELEE_RATING_SHORT = "к показателю критического удара в ближнем бою";
|
||||
ITEM_MOD_CRIT_RANGED_RATING_SHORT = "к показателю критического удара в дальнем бою";
|
||||
ITEM_MOD_HIT_MELEE_RATING_SHORT = "к меткости в ближнем бою";
|
||||
ITEM_MOD_HIT_RANGED_RATING_SHORT = "к меткости в дальнем бою";
|
||||
ITEM_MOD_HIT_SPELL_RATING_SHORT = "к меткости заклинаний";
|
||||
ITEM_MOD_CRIT_SPELL_RATING_SHORT = "к критическому эффекту заклинаний";
|
||||
ITEM_MOD_SPELL_DAMAGE_DONE_SHORT = "к дополнительному урону";
|
||||
ITEM_MOD_SPELL_HEALING_DONE_SHORT = "к дополнительному исцелению";
|
||||
ITEM_MOD_MANA_REGENERATION_SHORT = "к восполнению маны";
|
||||
ITEM_MOD_DEFENSE_SKILL_RATING_SHORT = "Защита";
|
||||
ITEM_MOD_DODGE_RATING_SHORT = "Уклонение";
|
||||
ITEM_MOD_PARRY_RATING_SHORT = "Парирование";
|
||||
ITEM_MOD_BLOCK_RATING_SHORT = "Блок";
|
||||
ITEM_MOD_BLOCK_VALUE_SHORT = "к показателю блокирования";
|
||||
ITEM_MOD_DAMAGE_PER_SECOND_SHORT = "к урону в секунду";
|
||||
LARGE_NUMBER_SEPERATOR = "";
|
||||
MINUTES_SECONDS = "%.2d:%.2d";
|
||||
PAPERDOLL_EQUIPMENTMANAGER = "Комплекты экипировки";
|
||||
PAPERDOLL_NEWEQUIPMENTSET = "Новый комплект";
|
||||
PERCENTAGE_STRING = "%d%%";
|
||||
SET_FRIENDNOTE_LABEL = "Заметка о |3-5(%s):";
|
||||
SET_NOTE = "Добавить заметку";
|
||||
SILVER_AMOUNT_SYMBOL = "с";
|
||||
SLASH_CANCELAURA1 = "/снятьауру";
|
||||
SLASH_CANCELAURA2 = "/cancelaura";
|
||||
SLASH_CANCELFORM1 = "/нормоблик";
|
||||
SLASH_CANCELFORM2 = "/cancelform";
|
||||
SLASH_CHANGEACTIONBAR1 = "/сменитьпанель";
|
||||
SLASH_CHANGEACTIONBAR2 = "/changeactionbar";
|
||||
SLASH_CLEARFOCUS1 = "/clearfocus";
|
||||
SLASH_CLEARFOCUS2 = "/сбросфокуса";
|
||||
SLASH_CLEARTARGET1 = "/сбросцели";
|
||||
SLASH_CLEARTARGET2 = "/cleartarget";
|
||||
SLASH_CLICK1 = "/click";
|
||||
SLASH_CLICK2 = "/щелчок";
|
||||
SLASH_DISMOUNT1 = "/спешиться";
|
||||
SLASH_DISMOUNT2 = "/dismount";
|
||||
SLASH_EQUIP1 = "/экип";
|
||||
SLASH_EQUIP2 = "/equip";
|
||||
SLASH_EQUIP_SET1 = "/комплект";
|
||||
SLASH_EQUIP_SET2 = "/equipset";
|
||||
SLASH_EQUIP_TO_SLOT1 = "/надеть";
|
||||
SLASH_EQUIP_TO_SLOT2 = "/equipslot";
|
||||
SLASH_FOCUS1 = "/focus";
|
||||
SLASH_FOCUS2 = "/фокус";
|
||||
SLASH_PET_AGGRESSIVE1 = "/питомецагрессивный";
|
||||
SLASH_PET_AGGRESSIVE2 = "/petaggressive";
|
||||
SLASH_PET_ATTACK1 = "/питомецатака";
|
||||
SLASH_PET_ATTACK2 = "/petattack";
|
||||
SLASH_PET_AUTOCASTOFF1 = "/питомецзаклинаниеоткл";
|
||||
SLASH_PET_AUTOCASTOFF2 = "/petautocastoff";
|
||||
SLASH_PET_AUTOCASTON1 = "/питомецзаклинаниевкл";
|
||||
SLASH_PET_AUTOCASTON2 = "/petautocaston";
|
||||
SLASH_PET_AUTOCASTTOGGLE1 = "/питомецавтозаклинание";
|
||||
SLASH_PET_AUTOCASTTOGGLE2 = "/petautocasttoggle";
|
||||
SLASH_PET_DEFENSIVE1 = "/питомецзащита";
|
||||
SLASH_PET_DEFENSIVE2 = "/petdefensive";
|
||||
SLASH_PET_FOLLOW1 = "/питомецзамной";
|
||||
SLASH_PET_FOLLOW2 = "/petfollow";
|
||||
SLASH_PET_PASSIVE1 = "/питомецпассивный";
|
||||
SLASH_PET_PASSIVE2 = "/petpassive";
|
||||
SLASH_PET_STAY1 = "/питомецстоять";
|
||||
SLASH_PET_STAY2 = "/petstay";
|
||||
SLASH_STARTATTACK1 = "/startattack";
|
||||
SLASH_STARTATTACK2 = "/начатьатаку";
|
||||
SLASH_STOPATTACK1 = "/stopattack";
|
||||
SLASH_STOPATTACK2 = "/стопатака";
|
||||
SLASH_STOPCASTING1 = "/стопзаклинание";
|
||||
SLASH_STOPCASTING2 = "/stopcasting";
|
||||
SLASH_SWAPACTIONBAR1 = "/сменитьпанелькоманд";
|
||||
SLASH_SWAPACTIONBAR2 = "/swapactionbar";
|
||||
SLASH_TARGET_EXACT1 = "/цельточно";
|
||||
SLASH_TARGET_EXACT2 = "/targetexact";
|
||||
SLASH_TARGET_LAST_ENEMY1 = "/цельпослвраг";
|
||||
SLASH_TARGET_LAST_ENEMY2 = "/targetlastenemy";
|
||||
SLASH_TARGET_LAST_TARGET1 = "/цельпослцель";
|
||||
SLASH_TARGET_LAST_TARGET2 = "/targetlasttarget";
|
||||
SLASH_TARGET_NEAREST_ENEMY1 = "/цельвраг";
|
||||
SLASH_TARGET_NEAREST_ENEMY2 = "/targetenemy";
|
||||
SLASH_TARGET_NEAREST_ENEMY_PLAYER1 = "/targetenemyplayer";
|
||||
SLASH_TARGET_NEAREST_ENEMY_PLAYER2 = "/targetenemyplayer";
|
||||
SLASH_TARGET_NEAREST_FRIEND1 = "/цельдруг";
|
||||
SLASH_TARGET_NEAREST_FRIEND2 = "/targetfriend";
|
||||
SLASH_TARGET_NEAREST_FRIEND_PLAYER1 = "/targetfriendplayer";
|
||||
SLASH_TARGET_NEAREST_FRIEND_PLAYER2 = "/targetfriendplayer";
|
||||
SLASH_TARGET_NEAREST_PARTY1 = "/цельгруппа";
|
||||
SLASH_TARGET_NEAREST_PARTY2 = "/targetparty";
|
||||
SLASH_TARGET_NEAREST_RAID1 = "/цельрейд";
|
||||
SLASH_TARGET_NEAREST_RAID2 = "/targetraid";
|
||||
SLASH_USE1 = "/use";
|
||||
SLASH_USE2 = "/использовать";
|
||||
LINK_TRADESKILL_TOOLTIP = "Щелкните здесь, чтобы создать ссылку на вашу профессию.";
|
||||
@@ -1,149 +0,0 @@
|
||||
if GetLocale() ~= "zhCN" then return end
|
||||
|
||||
BINDING_NAME_FOCUSTARGET = "焦点目标";
|
||||
BINDING_NAME_TARGETFOCUS = "目标焦点";
|
||||
CONFIRM_DELETE_EQUIPMENT_SET = "你确认要删除装备方案%s吗?";
|
||||
CONFIRM_SAVE_EQUIPMENT_SET = "你想要保存装备方案\"%s\"吗?";
|
||||
DEBUFF_SYMBOL_CURSE = "诅";
|
||||
DEBUFF_SYMBOL_DISEASE = "疾";
|
||||
DEBUFF_SYMBOL_MAGIC = "魔";
|
||||
DEBUFF_SYMBOL_POISON = "毒";
|
||||
DEBUG_FRAMESTACK = "框架栈";
|
||||
EQUIPMENT_MANAGER = "装备管理";
|
||||
EQUIPMENT_MANAGER_IGNORE_SLOT = "忽略此栏位";
|
||||
EQUIPMENT_MANAGER_IS_DISABLED = "装备管理已禁用。";
|
||||
EQUIPMENT_MANAGER_ITEMS_MISSING_TOOLTIP = "%d %s |cffff0000(缺少%d)|r";
|
||||
EQUIPMENT_MANAGER_PLACE_IN_BAGS = "放入背包";
|
||||
EQUIPMENT_MANAGER_UNIGNORE_SLOT = "包括此栏位";
|
||||
EQUIPMENT_SETS = "装备配置方案:|cFFFFFFFF%s|r";
|
||||
EQUIPMENT_SETS_CANT_RENAME = "一个重名的装备方案已经存在。";
|
||||
EQUIPMENT_SETS_TOO_MANY = "你不能再创建新的装备方案了。";
|
||||
EQUIPMENT_SET_ASSIGN_TO_SPEC = "指定专精:";
|
||||
EQUIPMENT_SET_EDIT = "修改名称/图标";
|
||||
EQUIPMENT_SET_SETTINGS = "设置";
|
||||
EQUIPSET_EQUIP = "装备";
|
||||
ERR_EQUIPMENT_MANAGER_BAGS_FULL = "装备更换失败。背包已满。";
|
||||
ERR_EQUIPMENT_MANAGER_COMBAT_SWAP_S = "装备方案%s中的某些物品不能在战斗中切换。";
|
||||
ERR_EQUIPMENT_MANAGER_MISSING_ITEM_S = "未找到套装方案%s中的一件或多件物品,无法装备。";
|
||||
CLEAR_FOCUS = "清除焦点";
|
||||
SET_FOCUS = "设置焦点";
|
||||
FOCUSTARGET = "设定焦点目标";
|
||||
ITEMS_VARIABLE_QUANTITY = "%d件物品";
|
||||
ITEMS_EQUIPPED = "已装备%d件物品";
|
||||
ITEMS_IN_INVENTORY = "背包中有%d件物品";
|
||||
ITEM_SLOTS_IGNORED = "忽略%d个栏位";
|
||||
ITEM_MISSING = "%s缺失";
|
||||
ITEMS_NOT_IN_INVENTORY = "缺少%d件物品";
|
||||
TARGETFOCUS = "选中焦点目标";
|
||||
-- BINDING_NAME_AOELOOT = "AoE Loot";
|
||||
COPPER_AMOUNT_SYMBOL = "铜";
|
||||
GEARSETS_POPUP_TEXT = "输入方案名称(最多16个字符):";
|
||||
GENERIC_FRACTION_STRING = "%d/%d";
|
||||
GOLD_AMOUNT_SYMBOL = "金";
|
||||
HOURS_MINUTES_SECONDS = "%.2d:%.2d:%.2d";
|
||||
ICON_FILTER_ALL = "所有图标";
|
||||
ICON_FILTER_ITEM = "物品";
|
||||
ICON_FILTER_SPELL = "法术";
|
||||
ICON_SELECTION_TITLE_CURRENT = "当前已选择";
|
||||
ITEM_DELTA_DESCRIPTION = "如果你替换该物品,将会产生以下的属性变更:";
|
||||
ITEM_MOD_MANA_SHORT = "法力值";
|
||||
ITEM_MOD_HEALTH_SHORT = "生命值";
|
||||
ITEM_MOD_AGILITY_SHORT = "敏捷";
|
||||
ITEM_MOD_STRENGTH_SHORT = "力量";
|
||||
ITEM_MOD_INTELLECT_SHORT = "智力";
|
||||
ITEM_MOD_SPIRIT_SHORT = "精神";
|
||||
ITEM_MOD_STAMINA_SHORT = "耐力";
|
||||
ITEM_MOD_ATTACK_POWER_SHORT = "攻击强度";
|
||||
ITEM_MOD_RANGED_ATTACK_POWER_SHORT = "远程攻击强度";
|
||||
ITEM_MOD_CRIT_MELEE_RATING_SHORT = "爆击(近战)";
|
||||
ITEM_MOD_CRIT_RANGED_RATING_SHORT = "爆击(远程)";
|
||||
ITEM_MOD_HIT_MELEE_RATING_SHORT = "命中(近战)";
|
||||
ITEM_MOD_HIT_RANGED_RATING_SHORT = "命中(远程)";
|
||||
ITEM_MOD_HIT_SPELL_RATING_SHORT = "命中(法术)";
|
||||
ITEM_MOD_CRIT_SPELL_RATING_SHORT = "爆击(法术)";
|
||||
ITEM_MOD_SPELL_DAMAGE_DONE_SHORT = "伤害加成";
|
||||
ITEM_MOD_SPELL_HEALING_DONE_SHORT = "治疗加成";
|
||||
ITEM_MOD_MANA_REGENERATION_SHORT = "法力回复";
|
||||
ITEM_MOD_DEFENSE_SKILL_RATING_SHORT = "防御";
|
||||
ITEM_MOD_DODGE_RATING_SHORT = "躲闪";
|
||||
ITEM_MOD_PARRY_RATING_SHORT = "招架";
|
||||
ITEM_MOD_BLOCK_RATING_SHORT = "格挡";
|
||||
ITEM_MOD_BLOCK_VALUE_SHORT = "格挡值";
|
||||
ITEM_MOD_DAMAGE_PER_SECOND_SHORT = "每秒伤害";
|
||||
LARGE_NUMBER_SEPERATOR = ",";
|
||||
MINUTES_SECONDS = "%.2d:%.2d";
|
||||
PAPERDOLL_EQUIPMENTMANAGER = "装备管理";
|
||||
PAPERDOLL_NEWEQUIPMENTSET = "新的方案";
|
||||
PERCENTAGE_STRING = "%d%%";
|
||||
SET_FRIENDNOTE_LABEL = "为%s设置备注:";
|
||||
SET_NOTE = "设置备注";
|
||||
SILVER_AMOUNT_SYMBOL = "银";
|
||||
SLASH_CANCELAURA1 = "/cancelaura";
|
||||
SLASH_CANCELAURA2 = "/cancelaura";
|
||||
SLASH_CANCELFORM1 = "/cancelform";
|
||||
SLASH_CANCELFORM2 = "/cancelform";
|
||||
SLASH_CHANGEACTIONBAR1 = "/changeactionbar";
|
||||
SLASH_CHANGEACTIONBAR2 = "/changeactionbar";
|
||||
SLASH_CLEARFOCUS1 = "/clearfocus";
|
||||
SLASH_CLEARFOCUS2 = "/clearfocus";
|
||||
SLASH_CLEARTARGET1 = "/cleartarget";
|
||||
SLASH_CLEARTARGET2 = "/cleartarget";
|
||||
SLASH_CLICK1 = "/click";
|
||||
SLASH_CLICK2 = "/click";
|
||||
SLASH_DISMOUNT1 = "/dismount";
|
||||
SLASH_DISMOUNT2 = "/dismount";
|
||||
SLASH_EQUIP1 = "/equip";
|
||||
SLASH_EQUIP2 = "/equip";
|
||||
SLASH_EQUIP_SET1 = "/equipset";
|
||||
SLASH_EQUIP_SET2 = "/equipset";
|
||||
SLASH_EQUIP_TO_SLOT1 = "/equipslot";
|
||||
SLASH_EQUIP_TO_SLOT2 = "/equipslot";
|
||||
SLASH_FOCUS1 = "/focus";
|
||||
SLASH_FOCUS2 = "/focus";
|
||||
SLASH_PET_AGGRESSIVE1 = "/petaggressive";
|
||||
SLASH_PET_AGGRESSIVE2 = "/petaggressive";
|
||||
SLASH_PET_ATTACK1 = "/petattack";
|
||||
SLASH_PET_ATTACK2 = "/petattack";
|
||||
SLASH_PET_AUTOCASTOFF1 = "/petautocastoff";
|
||||
SLASH_PET_AUTOCASTOFF2 = "/petautocastoff";
|
||||
SLASH_PET_AUTOCASTON1 = "/petautocaston";
|
||||
SLASH_PET_AUTOCASTON2 = "/petautocaston";
|
||||
SLASH_PET_AUTOCASTTOGGLE1 = "/petautocasttoggle";
|
||||
SLASH_PET_AUTOCASTTOGGLE2 = "/petautocasttoggle";
|
||||
SLASH_PET_DEFENSIVE1 = "/petdefensive";
|
||||
SLASH_PET_DEFENSIVE2 = "/petdefensive";
|
||||
SLASH_PET_FOLLOW1 = "/petfollow";
|
||||
SLASH_PET_FOLLOW2 = "/petfollow";
|
||||
SLASH_PET_PASSIVE1 = "/petpassive";
|
||||
SLASH_PET_PASSIVE2 = "/petpassive";
|
||||
SLASH_PET_STAY1 = "/petstay";
|
||||
SLASH_PET_STAY2 = "/petstay";
|
||||
SLASH_STARTATTACK1 = "/startattack";
|
||||
SLASH_STARTATTACK2 = "/startattack";
|
||||
SLASH_STOPATTACK1 = "/stopattack";
|
||||
SLASH_STOPATTACK2 = "/stopattack";
|
||||
SLASH_STOPCASTING1 = "/stopcasting";
|
||||
SLASH_STOPCASTING2 = "/stopcasting";
|
||||
SLASH_SWAPACTIONBAR1 = "/swapactionbar";
|
||||
SLASH_SWAPACTIONBAR2 = "/swapactionbar";
|
||||
SLASH_TARGET_EXACT1 = "/targetexact";
|
||||
SLASH_TARGET_EXACT2 = "/targetexact";
|
||||
SLASH_TARGET_LAST_ENEMY1 = "/targetlastenemy";
|
||||
SLASH_TARGET_LAST_ENEMY2 = "/targetlastenemy";
|
||||
SLASH_TARGET_LAST_TARGET1 = "/targetlasttarget";
|
||||
SLASH_TARGET_LAST_TARGET2 = "/targetlasttarget";
|
||||
SLASH_TARGET_NEAREST_ENEMY1 = "/targetenemy";
|
||||
SLASH_TARGET_NEAREST_ENEMY2 = "/targetenemy";
|
||||
SLASH_TARGET_NEAREST_ENEMY_PLAYER1 = "/targetenemyplayer";
|
||||
SLASH_TARGET_NEAREST_ENEMY_PLAYER2 = "/targetenemyplayer";
|
||||
SLASH_TARGET_NEAREST_FRIEND1 = "/targetfriend";
|
||||
SLASH_TARGET_NEAREST_FRIEND2 = "/targetfriend";
|
||||
SLASH_TARGET_NEAREST_FRIEND_PLAYER1 = "/targetfriendplayer";
|
||||
SLASH_TARGET_NEAREST_FRIEND_PLAYER2 = "/targetfriendplayer";
|
||||
SLASH_TARGET_NEAREST_PARTY1 = "/targetparty";
|
||||
SLASH_TARGET_NEAREST_PARTY2 = "/targetparty";
|
||||
SLASH_TARGET_NEAREST_RAID1 = "/targetraid";
|
||||
SLASH_TARGET_NEAREST_RAID2 = "/targetraid";
|
||||
SLASH_USE1 = "/use";
|
||||
SLASH_USE2 = "/use";
|
||||
LINK_TRADESKILL_TOOLTIP = "点击这里以创建一个链接到你的专业的快捷方式。";
|
||||
@@ -1,217 +0,0 @@
|
||||
-- AoE Loot Test
|
||||
--
|
||||
-- /aoeloot opens a picker window listing every item in every lootable
|
||||
-- corpse within click range. Clicking a row hands the (guid, itemID)
|
||||
-- pair to C_Loot.LootUnitItem and re-scans so the picker refreshes
|
||||
-- with whatever's left.
|
||||
--
|
||||
-- Known visual: each scan opens / closes loot windows in rapid
|
||||
-- succession, so the Blizzard LootFrame flickers during the scan. This
|
||||
-- addon intentionally doesn't suppress that — the goal is to exercise
|
||||
-- the C++ surface, not to ship polished UI.
|
||||
|
||||
local MAX_ROWS = 24
|
||||
local RESCAN_DELAY = 0.3 -- seconds; lets LootUnitItem complete before re-scan
|
||||
|
||||
-- ---------- UI scaffolding ----------
|
||||
|
||||
-- Frame geometry. Height is recomputed dynamically per scan so the
|
||||
-- window only takes up as much screen real estate as the result count
|
||||
-- needs — see `ResizeForRows`.
|
||||
local FRAME_WIDTH = 320
|
||||
local HEADER_HEIGHT = 64 -- title + status + insets; minimum frame height
|
||||
local ROW_HEIGHT = 22
|
||||
|
||||
local frame = CreateFrame("Frame", "AoELootTestFrame", UIParent)
|
||||
frame:SetWidth(FRAME_WIDTH)
|
||||
frame:SetHeight(HEADER_HEIGHT)
|
||||
frame:SetPoint("CENTER", UIParent, "CENTER", 0, 0)
|
||||
frame:SetBackdrop({
|
||||
bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background",
|
||||
edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border",
|
||||
tile = true, tileSize = 32, edgeSize = 32,
|
||||
insets = { left = 11, right = 12, top = 12, bottom = 11 },
|
||||
})
|
||||
frame:SetMovable(true)
|
||||
frame:EnableMouse(true)
|
||||
frame:RegisterForDrag("LeftButton")
|
||||
-- Vanilla 1.12 fires script handlers with the frame set as the global
|
||||
-- `this`, not as a `self` arg to the function. Passing `frame.StartMoving`
|
||||
-- directly (the modern shortcut) breaks because the C method has no
|
||||
-- `self` to operate on. Wrap in closures so `this:method()` resolves
|
||||
-- correctly inside the handler.
|
||||
frame:SetScript("OnDragStart", function() this:StartMoving() end)
|
||||
frame:SetScript("OnDragStop", function() this:StopMovingOrSizing() end)
|
||||
frame:Hide()
|
||||
|
||||
local title = frame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
|
||||
title:SetPoint("TOP", frame, "TOP", 0, -16)
|
||||
title:SetText("AoE Loot")
|
||||
|
||||
local status = frame:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
|
||||
status:SetPoint("TOPLEFT", frame, "TOPLEFT", 18, -36)
|
||||
status:SetText("")
|
||||
|
||||
local closeBtn = CreateFrame("Button", nil, frame, "UIPanelCloseButton")
|
||||
closeBtn:SetPoint("TOPRIGHT", frame, "TOPRIGHT", -6, -6)
|
||||
|
||||
-- ---------- Row pool ----------
|
||||
|
||||
local rows = {}
|
||||
|
||||
local function CreateRow(parent, idx)
|
||||
local row = CreateFrame("Button", nil, parent)
|
||||
row:SetWidth(290)
|
||||
row:SetHeight(20)
|
||||
row:SetPoint("TOPLEFT", parent, "TOPLEFT", 15,
|
||||
-54 - (idx - 1) * ROW_HEIGHT)
|
||||
|
||||
local icon = row:CreateTexture(nil, "ARTWORK")
|
||||
icon:SetWidth(18); icon:SetHeight(18)
|
||||
icon:SetPoint("LEFT", row, "LEFT", 0, 0)
|
||||
row.icon = icon
|
||||
|
||||
local text = row:CreateFontString(nil, "OVERLAY", "GameFontNormal")
|
||||
text:SetPoint("LEFT", icon, "RIGHT", 6, 0)
|
||||
text:SetPoint("RIGHT", row, "RIGHT", 0, 0)
|
||||
text:SetJustifyH("LEFT")
|
||||
row.text = text
|
||||
|
||||
local hl = row:CreateTexture(nil, "HIGHLIGHT")
|
||||
hl:SetTexture("Interface\\QuestFrame\\UI-QuestTitleHighlight")
|
||||
hl:SetBlendMode("ADD")
|
||||
hl:SetAllPoints(row)
|
||||
|
||||
-- Tooltip on hover. The engine's native `SetHyperlink` does a
|
||||
-- literal `SStrCmpI` of the input's first 5 chars against the
|
||||
-- string `"item:"` at `.rdata` VA `0x00842D60` — anything that
|
||||
-- starts with `|c...` (full link with color) or `|Hitem` (full
|
||||
-- link without color) fails the prefix check with "Unknown link
|
||||
-- type". Only the bare payload form survives.
|
||||
--
|
||||
-- We extract the payload from the engine's full link rather than
|
||||
-- composing `item:ID:0:0:0` ourselves, so per-instance fields
|
||||
-- (enchant / random-suffix / unique) survive round-trip and
|
||||
-- "Stringy Wolf Meat of the Bear" tooltips correctly instead of
|
||||
-- collapsing to the un-suffixed itemID.
|
||||
row:SetScript("OnEnter", function()
|
||||
if this.payload then
|
||||
GameTooltip:SetOwner(this, "ANCHOR_RIGHT")
|
||||
GameTooltip:SetHyperlink(this.payload)
|
||||
GameTooltip:Show()
|
||||
end
|
||||
end)
|
||||
row:SetScript("OnLeave", function() GameTooltip:Hide() end)
|
||||
|
||||
row:Hide()
|
||||
return row
|
||||
end
|
||||
|
||||
for i = 1, MAX_ROWS do
|
||||
rows[i] = CreateRow(frame, i)
|
||||
end
|
||||
|
||||
-- ---------- Render ----------
|
||||
|
||||
-- Tail of a GUID string — last 4 hex chars of the low dword. Lets the
|
||||
-- user tell apart two rows of "Stringy Wolf Meat x1" coming from
|
||||
-- different corpses, without occupying a whole column with the full
|
||||
-- 16-digit GUID.
|
||||
local function ShortGuidSuffix(guid)
|
||||
return "[.." .. string.sub(guid, -4) .. "]"
|
||||
end
|
||||
|
||||
-- Extract the `item:ID:enchant:suffix:unique` payload out of the
|
||||
-- engine's full link string (`|cff...|Hitem:...|h[Name]|h|r`).
|
||||
-- Vanilla `SetHyperlink` requires the input to start literally with
|
||||
-- `"item:"` — so we can't pass the full link, but we also can't drop
|
||||
-- the per-instance fields (random suffix is what distinguishes "of
|
||||
-- the Bear" from "of the Eagle" on otherwise identical itemIDs).
|
||||
-- Returns the payload, or nil if extraction fails.
|
||||
local function PayloadFromLink(link)
|
||||
if not link then return nil end
|
||||
return string.match(link, "|H(item:[^|]+)|h")
|
||||
end
|
||||
|
||||
local function ClearRows()
|
||||
for i = 1, MAX_ROWS do
|
||||
rows[i]:Hide()
|
||||
rows[i]:SetScript("OnClick", nil)
|
||||
rows[i].payload = nil
|
||||
end
|
||||
end
|
||||
|
||||
local function PopulateRows(results)
|
||||
local idx = 0
|
||||
for _, corpse in ipairs(results) do
|
||||
for _, item in ipairs(corpse.items) do
|
||||
idx = idx + 1
|
||||
if idx > MAX_ROWS then break end
|
||||
local row = rows[idx]
|
||||
local name, _, _, _, _, _, _, _, icon = GetItemInfo(item.itemID)
|
||||
row.icon:SetTexture(icon or "Interface\\Icons\\INV_Misc_QuestionMark")
|
||||
local label = name or ("Item #" .. item.itemID)
|
||||
if item.count and item.count > 1 then
|
||||
label = label .. " x" .. item.count
|
||||
end
|
||||
label = label .. " " .. ShortGuidSuffix(corpse.guid)
|
||||
row.text:SetText(label)
|
||||
row.payload = PayloadFromLink(item.link) -- for OnEnter tooltip
|
||||
local guid, itemID = corpse.guid, item.itemID
|
||||
row:SetScript("OnClick", function()
|
||||
C_Loot.LootUnitItem(guid, itemID)
|
||||
C_Timer.After(RESCAN_DELAY, function()
|
||||
if frame:IsShown() then C_Loot.ScanNearbyLoot() end
|
||||
end)
|
||||
end)
|
||||
row:Show()
|
||||
end
|
||||
if idx > MAX_ROWS then break end
|
||||
end
|
||||
for i = idx + 1, MAX_ROWS do rows[i]:Hide() end
|
||||
local shown
|
||||
if idx == 0 then
|
||||
status:SetText("Nothing lootable in range.")
|
||||
shown = 0
|
||||
elseif idx > MAX_ROWS then
|
||||
status:SetText(MAX_ROWS .. "+ items (showing first " .. MAX_ROWS .. ")")
|
||||
shown = MAX_ROWS
|
||||
else
|
||||
status:SetText(idx .. " item(s) available")
|
||||
shown = idx
|
||||
end
|
||||
frame:SetHeight(HEADER_HEIGHT + shown * ROW_HEIGHT)
|
||||
end
|
||||
|
||||
-- ---------- Scan trigger ----------
|
||||
|
||||
local function StartScan()
|
||||
status:SetText("Scanning...")
|
||||
ClearRows()
|
||||
frame:SetHeight(HEADER_HEIGHT) -- collapse while we wait for results
|
||||
if not C_Loot.ScanNearbyLoot() then
|
||||
status:SetText("Scan busy or not in world.")
|
||||
end
|
||||
end
|
||||
|
||||
-- ---------- Event wiring ----------
|
||||
|
||||
local evt = CreateFrame("Frame")
|
||||
evt:RegisterEvent("LOOT_SCAN_COMPLETED")
|
||||
evt:SetScript("OnEvent", function()
|
||||
-- Race guard: a delayed scan may complete after the user closed
|
||||
-- the picker. Just drop the result rather than re-showing.
|
||||
if not frame:IsShown() then return end
|
||||
PopulateRows(C_Loot.GetLastScanResults())
|
||||
end)
|
||||
|
||||
-- ---------- Slash command ----------
|
||||
|
||||
RegisterNewSlashCommand(function()
|
||||
if frame:IsShown() then
|
||||
StartScan() -- already open → just refresh
|
||||
else
|
||||
frame:Show()
|
||||
StartScan()
|
||||
end
|
||||
end, "aoeloot", "aoe")
|
||||
@@ -1,7 +0,0 @@
|
||||
## Interface: 11200
|
||||
## Title: AoE Loot Test
|
||||
## Notes: Test bed for ClassicAPI's C_Loot.ScanNearbyLoot / LootUnitItem. /aoeloot
|
||||
## Dependencies: !!!ClassicAPI
|
||||
## Version: DEV
|
||||
|
||||
AoELootTest.lua
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,11 +0,0 @@
|
||||
## Interface: 11200
|
||||
## Title: UI Debug Tools
|
||||
## Notes: Tools for developing addons (backport of Blizzard_DebugTools 3.3.5 to 1.12.1 / Lua 5.0)
|
||||
## Author: Blizzard Entertainment, backported
|
||||
## Special Thanks: Iriel, Kirov, Esamynn
|
||||
## Version: 1.0
|
||||
## SavedVariables: DebugToolsSavedVars
|
||||
Dump.lua
|
||||
DebugTools.lua
|
||||
TableInspector.lua
|
||||
DebugTools.xml
|
||||
@@ -1,598 +0,0 @@
|
||||
<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">
|
||||
|
||||
<!-- ================================================================ -->
|
||||
<!-- EventTrace -->
|
||||
<!-- ================================================================ -->
|
||||
|
||||
<Button name="EventTraceEventTemplate" virtual="true">
|
||||
<Size x="280" y="16"/>
|
||||
<Layers>
|
||||
<Layer level="ARTWORK">
|
||||
<FontString name="$parentTime" inherits="NumberFontNormalSmall" justifyH="RIGHT">
|
||||
<Anchors>
|
||||
<Anchor point="TOPLEFT"/>
|
||||
<Anchor point="TOPRIGHT" relativePoint="TOPLEFT">
|
||||
<Offset x="62" y="0"/>
|
||||
</Anchor>
|
||||
<Anchor point="BOTTOM"/>
|
||||
</Anchors>
|
||||
</FontString>
|
||||
<FontString name="$parentEvent" inherits="GameFontHighlightSmall" justifyH="LEFT">
|
||||
<Anchors>
|
||||
<Anchor point="TOPRIGHT"/>
|
||||
<Anchor point="TOPLEFT">
|
||||
<Offset x="70" y="0"/>
|
||||
</Anchor>
|
||||
<Anchor point="BOTTOM"/>
|
||||
</Anchors>
|
||||
</FontString>
|
||||
</Layer>
|
||||
</Layers>
|
||||
<Scripts>
|
||||
<OnLoad>
|
||||
this:GetHighlightTexture():SetAlpha(.15);
|
||||
</OnLoad>
|
||||
<OnEnter>EventTraceFrameEvent_OnEnter(this);</OnEnter>
|
||||
<OnLeave>EventTraceFrameEvent_OnLeave(this);</OnLeave>
|
||||
<OnClick>EventTraceFrameEvent_OnClick(this);</OnClick>
|
||||
</Scripts>
|
||||
<HighlightTexture file="Interface\Buttons\UI-Common-MouseHilight" setAllPoints="true" alphaMode="ADD">
|
||||
<Color r=".8" g=".8" b="1" a="1"/>
|
||||
</HighlightTexture>
|
||||
</Button>
|
||||
|
||||
<Frame name="EventTraceFrame" parent="UIParent" movable="true" hidden="true" frameStrata="MEDIUM" toplevel="true">
|
||||
<Size x="306" y="484"/>
|
||||
<Anchors>
|
||||
<Anchor point="LEFT">
|
||||
<Offset x="64" y="0"/>
|
||||
</Anchor>
|
||||
</Anchors>
|
||||
<Backdrop bgFile="Interface\DialogFrame\UI-DialogBox-Background" edgeFile="Interface\Tooltips\UI-Tooltip-Border" tile="true">
|
||||
<BackgroundInsets>
|
||||
<AbsInset left="5" right="5" top="5" bottom="5"/>
|
||||
</BackgroundInsets>
|
||||
<TileSize>
|
||||
<AbsValue val="16"/>
|
||||
</TileSize>
|
||||
<EdgeSize>
|
||||
<AbsValue val="16"/>
|
||||
</EdgeSize>
|
||||
</Backdrop>
|
||||
<Layers>
|
||||
<!-- 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>
|
||||
<Anchor point="TOP">
|
||||
<Offset x="0" y="-6"/>
|
||||
</Anchor>
|
||||
</Anchors>
|
||||
<Color r=".6" g=".6" b=".6" a=".4"/>
|
||||
</Texture>
|
||||
</Layer>
|
||||
<Layer level="OVERLAY">
|
||||
<FontString name="$parentTitle" inherits="GameFontNormal" text="Events">
|
||||
<Anchors>
|
||||
<Anchor point="TOP">
|
||||
<Offset x="0" y="-8"/>
|
||||
</Anchor>
|
||||
</Anchors>
|
||||
</FontString>
|
||||
</Layer>
|
||||
</Layers>
|
||||
<Frames>
|
||||
<Button name="$parentCloseButton" inherits="UIPanelCloseButton">
|
||||
<Anchors>
|
||||
<Anchor point="TOPRIGHT">
|
||||
<Offset x="-2" y="-2"/>
|
||||
</Anchor>
|
||||
</Anchors>
|
||||
</Button>
|
||||
<Frame name="$parentTitleButton">
|
||||
<Size x="280" y="20"/>
|
||||
<Anchors>
|
||||
<Anchor point="TOP">
|
||||
<Offset x="0" y="-6"/>
|
||||
</Anchor>
|
||||
</Anchors>
|
||||
<Scripts>
|
||||
<OnLoad>
|
||||
this:RegisterForDrag("LeftButton");
|
||||
</OnLoad>
|
||||
<OnDragStart>
|
||||
EventTraceFrame.moving = true;
|
||||
EventTraceFrame:StartMoving();
|
||||
</OnDragStart>
|
||||
<OnDragStop>
|
||||
EventTraceFrame.moving = nil;
|
||||
EventTraceFrame:StopMovingOrSizing();
|
||||
</OnDragStop>
|
||||
</Scripts>
|
||||
</Frame>
|
||||
<!-- Pushed down 26px (was y=-28) to make room for the
|
||||
toolbar row of Pause + Args/Time toggles + Search. -->
|
||||
<Slider name="$parentScroll" orientation="VERTICAL">
|
||||
<Size x="16" y="0"/>
|
||||
<Anchors>
|
||||
<Anchor point="TOPRIGHT">
|
||||
<Offset x="-7" y="-54"/>
|
||||
</Anchor>
|
||||
<Anchor point="BOTTOMRIGHT">
|
||||
<Offset x="-7" y="10"/>
|
||||
</Anchor>
|
||||
</Anchors>
|
||||
<Layers>
|
||||
<Layer level="BACKGROUND">
|
||||
<Texture name="$parentBG" setAllPoints="true">
|
||||
<Color r=".8" g=".8" b="1" a="0.1"/>
|
||||
</Texture>
|
||||
</Layer>
|
||||
</Layers>
|
||||
<Scripts>
|
||||
<OnLoad>
|
||||
this:SetFrameLevel(this:GetFrameLevel() + 1);
|
||||
this:SetMinMaxValues(0, 1);
|
||||
this:SetValue(0);
|
||||
this:SetValueStep(1);
|
||||
</OnLoad>
|
||||
<OnValueChanged>
|
||||
EventTraceFrame_Update();
|
||||
</OnValueChanged>
|
||||
</Scripts>
|
||||
<ThumbTexture name="$parentThumb" file="Interface\Buttons\UI-ScrollBar-Knob">
|
||||
<Size x="16" y="16"/>
|
||||
<TexCoords left="0.25" right="0.75" top="0.25" bottom="0.75"/>
|
||||
</ThumbTexture>
|
||||
</Slider>
|
||||
<!-- ===== Toolbar (Pause + Args/Time toggles + Search) ===== -->
|
||||
<Button name="$parentPauseButton" inherits="UIPanelButtonTemplate" text="Pause">
|
||||
<Size x="60" y="20"/>
|
||||
<Anchors>
|
||||
<Anchor point="TOPLEFT">
|
||||
<Offset x="12" y="-30"/>
|
||||
</Anchor>
|
||||
</Anchors>
|
||||
<Scripts>
|
||||
<OnClick>EventTraceFrame_TogglePause();</OnClick>
|
||||
</Scripts>
|
||||
</Button>
|
||||
<!-- `UICheckButtonTemplate`'s `$parentText` FontString is
|
||||
auto-positioned at the right of the box. Vanilla 1.12
|
||||
doesn't read a `text=` XML attribute (that came in
|
||||
TBC); set it from OnLoad via the global lookup
|
||||
instead. The earlier approach of separate sibling
|
||||
FontStrings in the parent's `<Layers>` block fell
|
||||
over because anchors that reference later-defined
|
||||
siblings ($parentArgsCheck etc.) resolve to (0,0)
|
||||
when the anchor is computed before the target exists. -->
|
||||
<!-- Initial checked state is set here from defaults so the
|
||||
first paint matches `_EventTraceFrame.showArguments`
|
||||
/ `showTimestamp`. `_ApplySavedVars` later overrides
|
||||
from `DebugToolsSavedVars` once ADDON_LOADED fires;
|
||||
if the user toggled the box to a non-default value
|
||||
in a prior session, the second SetChecked call wins. -->
|
||||
<CheckButton name="$parentArgsCheck" inherits="UICheckButtonTemplate">
|
||||
<Size x="20" y="20"/>
|
||||
<Anchors>
|
||||
<Anchor point="LEFT" relativeTo="$parentPauseButton" relativePoint="RIGHT">
|
||||
<Offset x="4" y="0"/>
|
||||
</Anchor>
|
||||
</Anchors>
|
||||
<Scripts>
|
||||
<OnLoad>
|
||||
getglobal(this:GetName() .. "Text"):SetText("Args");
|
||||
this:SetChecked(nil); -- showArguments default = false
|
||||
</OnLoad>
|
||||
<OnClick>EventTraceFrame_ToggleArgs(this:GetChecked());</OnClick>
|
||||
</Scripts>
|
||||
</CheckButton>
|
||||
<CheckButton name="$parentTimeCheck" inherits="UICheckButtonTemplate">
|
||||
<Size x="20" y="20"/>
|
||||
<Anchors>
|
||||
<Anchor point="LEFT" relativeTo="$parentArgsCheck" relativePoint="RIGHT">
|
||||
<Offset x="40" y="0"/>
|
||||
</Anchor>
|
||||
</Anchors>
|
||||
<Scripts>
|
||||
<OnLoad>
|
||||
getglobal(this:GetName() .. "Text"):SetText("Time");
|
||||
this:SetChecked(1); -- showTimestamp default = true
|
||||
</OnLoad>
|
||||
<OnClick>EventTraceFrame_ToggleTimestamp(this:GetChecked());</OnClick>
|
||||
</Scripts>
|
||||
</CheckButton>
|
||||
<EditBox name="$parentSearch" inherits="InputBoxTemplate" autoFocus="false">
|
||||
<Size x="100" y="20"/>
|
||||
<Anchors>
|
||||
<Anchor point="LEFT" relativeTo="$parentTimeCheck" relativePoint="RIGHT">
|
||||
<Offset x="48" y="0"/>
|
||||
</Anchor>
|
||||
</Anchors>
|
||||
<Scripts>
|
||||
<OnTextChanged>EventTraceFrame_OnSearchChanged(this);</OnTextChanged>
|
||||
<!-- Escape unfocuses but preserves text — clearing is
|
||||
the X button's job. Modern WoW behaves the same. -->
|
||||
<OnEscapePressed>this:ClearFocus();</OnEscapePressed>
|
||||
</Scripts>
|
||||
<Frames>
|
||||
<!-- Embedded clear button: anchored inside the editbox
|
||||
at the right edge, visible only while there's text.
|
||||
Declared as a child so sibling z-order puts it
|
||||
above the editbox's own backdrop textures. -->
|
||||
<Button name="$parentClear" hidden="true">
|
||||
<Size x="14" y="14"/>
|
||||
<Anchors>
|
||||
<Anchor point="RIGHT">
|
||||
<Offset x="-4" y="0"/>
|
||||
</Anchor>
|
||||
</Anchors>
|
||||
<Layers>
|
||||
<Layer level="OVERLAY">
|
||||
<FontString name="$parentLabel" inherits="GameFontNormalSmall" text="X">
|
||||
<Anchors>
|
||||
<Anchor point="CENTER"/>
|
||||
</Anchors>
|
||||
</FontString>
|
||||
</Layer>
|
||||
</Layers>
|
||||
<Scripts>
|
||||
<OnClick>
|
||||
local eb = getglobal("EventTraceFrameSearch");
|
||||
eb:SetText("");
|
||||
eb:ClearFocus();
|
||||
</OnClick>
|
||||
</Scripts>
|
||||
<HighlightTexture file="Interface\Buttons\UI-Common-MouseHilight" setAllPoints="true" alphaMode="ADD">
|
||||
<Color r="1" g="1" b="1" a=".5"/>
|
||||
</HighlightTexture>
|
||||
</Button>
|
||||
</Frames>
|
||||
</EditBox>
|
||||
</Frames>
|
||||
<Scripts>
|
||||
<OnLoad>EventTraceFrame_OnLoad(this);</OnLoad>
|
||||
<OnEvent>EventTraceFrame_OnEvent(this, event, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9);</OnEvent>
|
||||
<OnUpdate>EventTraceFrame_OnUpdate(this, arg1);</OnUpdate>
|
||||
</Scripts>
|
||||
</Frame>
|
||||
|
||||
<!-- ================================================================ -->
|
||||
<!-- ScriptErrorsFrame -->
|
||||
<!-- ================================================================ -->
|
||||
|
||||
<Frame name="ScriptErrorsFrame" parent="UIParent" movable="true" hidden="true" toplevel="true" frameStrata="DIALOG" enableMouse="true">
|
||||
<Size x="384" y="260"/>
|
||||
<Anchors>
|
||||
<Anchor point="CENTER"/>
|
||||
</Anchors>
|
||||
<Backdrop bgFile="Interface\DialogFrame\UI-DialogBox-Background" edgeFile="Interface\DialogFrame\UI-DialogBox-Border" tile="true">
|
||||
<BackgroundInsets>
|
||||
<AbsInset left="11" right="12" top="12" bottom="11"/>
|
||||
</BackgroundInsets>
|
||||
<TileSize>
|
||||
<AbsValue val="32"/>
|
||||
</TileSize>
|
||||
<EdgeSize>
|
||||
<AbsValue val="32"/>
|
||||
</EdgeSize>
|
||||
</Backdrop>
|
||||
<Layers>
|
||||
<!-- 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>
|
||||
<Anchor point="TOP">
|
||||
<Offset x="0" y="12"/>
|
||||
</Anchor>
|
||||
</Anchors>
|
||||
</Texture>
|
||||
</Layer>
|
||||
<Layer level="ARTWORK">
|
||||
<FontString name="$parentTitle" inherits="GameFontNormal" text="Lua Error">
|
||||
<Anchors>
|
||||
<Anchor point="TOP">
|
||||
<Offset x="0" y="-2"/>
|
||||
</Anchor>
|
||||
</Anchors>
|
||||
</FontString>
|
||||
<FontString name="$parentIndexLabel" inherits="GameFontNormal" justifyH="CENTER">
|
||||
<Size x="70" y="16"/>
|
||||
<Anchors>
|
||||
<Anchor point="BOTTOM">
|
||||
<Offset x="0" y="20"/>
|
||||
</Anchor>
|
||||
</Anchors>
|
||||
</FontString>
|
||||
</Layer>
|
||||
</Layers>
|
||||
<Frames>
|
||||
<Frame name="$parentTitleButton">
|
||||
<Size x="256" y="20"/>
|
||||
<Anchors>
|
||||
<Anchor point="TOP">
|
||||
<Offset x="0" y="0"/>
|
||||
</Anchor>
|
||||
</Anchors>
|
||||
<Scripts>
|
||||
<OnLoad>
|
||||
this:RegisterForDrag("LeftButton");
|
||||
</OnLoad>
|
||||
<OnDragStart>ScriptErrorsFrame_TitleButton_OnDragStart();</OnDragStart>
|
||||
<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="328" y="170"/>
|
||||
<Anchors>
|
||||
<Anchor point="TOPLEFT">
|
||||
<Offset x="16" y="-32"/>
|
||||
</Anchor>
|
||||
</Anchors>
|
||||
<ScrollChild>
|
||||
<EditBox name="$parentText" multiLine="true" letters="4000" autoFocus="false">
|
||||
<Size x="328" y="170"/>
|
||||
<Scripts>
|
||||
<OnEscapePressed>this:ClearFocus();</OnEscapePressed>
|
||||
<OnEditFocusGained>this:HighlightText(0);</OnEditFocusGained>
|
||||
</Scripts>
|
||||
<FontString inherits="GameFontHighlightSmall"/>
|
||||
</EditBox>
|
||||
</ScrollChild>
|
||||
</ScrollFrame>
|
||||
<Button name="$parentPrevious" inherits="UIPanelButtonTemplate" text="Previous" id="2">
|
||||
<Size x="96" y="24"/>
|
||||
<Anchors>
|
||||
<Anchor point="BOTTOMLEFT">
|
||||
<Offset x="16" y="16"/>
|
||||
</Anchor>
|
||||
</Anchors>
|
||||
<Scripts>
|
||||
<OnClick>ScriptErrorsFrameButton_OnClick(this);</OnClick>
|
||||
</Scripts>
|
||||
</Button>
|
||||
<Button name="$parentNext" inherits="UIPanelButtonTemplate" text="Next" id="1">
|
||||
<Size x="96" y="24"/>
|
||||
<Anchors>
|
||||
<Anchor point="BOTTOMLEFT">
|
||||
<Offset x="116" y="16"/>
|
||||
</Anchor>
|
||||
</Anchors>
|
||||
<Scripts>
|
||||
<OnClick>ScriptErrorsFrameButton_OnClick(this);</OnClick>
|
||||
</Scripts>
|
||||
</Button>
|
||||
<Button name="$parentClose" inherits="UIPanelButtonTemplate" text="Close">
|
||||
<Size x="96" y="24"/>
|
||||
<Anchors>
|
||||
<Anchor point="BOTTOMRIGHT">
|
||||
<Offset x="-16" y="16"/>
|
||||
</Anchor>
|
||||
</Anchors>
|
||||
<Scripts>
|
||||
<OnClick>ScriptErrorsFrame:Hide();</OnClick>
|
||||
</Scripts>
|
||||
</Button>
|
||||
</Frames>
|
||||
<Scripts>
|
||||
<OnLoad>ScriptErrorsFrame_OnLoad(this);</OnLoad>
|
||||
<OnShow>ScriptErrorsFrame_OnShow(this);</OnShow>
|
||||
</Scripts>
|
||||
</Frame>
|
||||
|
||||
<!-- ================================================================ -->
|
||||
<!-- TableInspector -->
|
||||
<!-- ================================================================ -->
|
||||
|
||||
<!-- Per-row button shared by every visible entry in the inspector.
|
||||
Two FontStrings: key column on the left, value column on the
|
||||
right. Highlight texture marks the hover row; click drills if
|
||||
the value is a table. -->
|
||||
<Button name="TableInspectorRowTemplate" virtual="true">
|
||||
<Size x="440" y="16"/>
|
||||
<Layers>
|
||||
<Layer level="ARTWORK">
|
||||
<FontString name="$parentKey" inherits="GameFontHighlightSmall" justifyH="LEFT">
|
||||
<Size x="160" y="16"/>
|
||||
<Anchors>
|
||||
<Anchor point="TOPLEFT"/>
|
||||
<Anchor point="BOTTOMLEFT"/>
|
||||
</Anchors>
|
||||
</FontString>
|
||||
<FontString name="$parentValue" inherits="GameFontHighlightSmall" justifyH="LEFT">
|
||||
<Anchors>
|
||||
<Anchor point="TOPLEFT" relativeTo="$parentKey" relativePoint="TOPRIGHT">
|
||||
<Offset x="6" y="0"/>
|
||||
</Anchor>
|
||||
<Anchor point="BOTTOMRIGHT"/>
|
||||
</Anchors>
|
||||
</FontString>
|
||||
</Layer>
|
||||
</Layers>
|
||||
<Scripts>
|
||||
<OnLoad>
|
||||
this:GetHighlightTexture():SetAlpha(.15);
|
||||
</OnLoad>
|
||||
<OnClick>TableInspectorRow_OnClick(this);</OnClick>
|
||||
</Scripts>
|
||||
<HighlightTexture file="Interface\Buttons\UI-Common-MouseHilight" setAllPoints="true" alphaMode="ADD">
|
||||
<Color r=".8" g=".8" b="1" a="1"/>
|
||||
</HighlightTexture>
|
||||
</Button>
|
||||
|
||||
<Frame name="TableInspectorFrame" parent="UIParent" movable="true" hidden="true" frameStrata="MEDIUM" toplevel="true">
|
||||
<Size x="480" y="464"/>
|
||||
<Anchors>
|
||||
<Anchor point="CENTER"/>
|
||||
</Anchors>
|
||||
<Backdrop bgFile="Interface\DialogFrame\UI-DialogBox-Background" edgeFile="Interface\Tooltips\UI-Tooltip-Border" tile="true">
|
||||
<BackgroundInsets>
|
||||
<AbsInset left="5" right="5" top="5" bottom="5"/>
|
||||
</BackgroundInsets>
|
||||
<TileSize>
|
||||
<AbsValue val="16"/>
|
||||
</TileSize>
|
||||
<EdgeSize>
|
||||
<AbsValue val="16"/>
|
||||
</EdgeSize>
|
||||
</Backdrop>
|
||||
<Layers>
|
||||
<!-- 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>
|
||||
<Anchor point="TOP">
|
||||
<Offset x="0" y="-6"/>
|
||||
</Anchor>
|
||||
</Anchors>
|
||||
<Color r=".6" g=".6" b=".6" a=".4"/>
|
||||
</Texture>
|
||||
</Layer>
|
||||
<Layer level="OVERLAY">
|
||||
<FontString name="$parentTitle" inherits="GameFontNormal" text="Table Inspector">
|
||||
<Anchors>
|
||||
<Anchor point="TOP">
|
||||
<Offset x="0" y="-8"/>
|
||||
</Anchor>
|
||||
</Anchors>
|
||||
</FontString>
|
||||
<FontString name="$parentBreadcrumb" inherits="GameFontHighlightSmall" justifyH="LEFT">
|
||||
<Size x="300" y="16"/>
|
||||
<Anchors>
|
||||
<Anchor point="TOPLEFT">
|
||||
<Offset x="156" y="-34"/>
|
||||
</Anchor>
|
||||
</Anchors>
|
||||
</FontString>
|
||||
</Layer>
|
||||
</Layers>
|
||||
<Frames>
|
||||
<Button name="$parentCloseButton" inherits="UIPanelCloseButton">
|
||||
<Anchors>
|
||||
<Anchor point="TOPRIGHT">
|
||||
<Offset x="-2" y="-2"/>
|
||||
</Anchor>
|
||||
</Anchors>
|
||||
<Scripts>
|
||||
<OnClick>TableInspector_Close();</OnClick>
|
||||
</Scripts>
|
||||
</Button>
|
||||
<Frame name="$parentTitleButton">
|
||||
<Size x="280" y="20"/>
|
||||
<Anchors>
|
||||
<Anchor point="TOP">
|
||||
<Offset x="0" y="-6"/>
|
||||
</Anchor>
|
||||
</Anchors>
|
||||
<Scripts>
|
||||
<OnLoad>
|
||||
this:RegisterForDrag("LeftButton");
|
||||
</OnLoad>
|
||||
<OnDragStart>
|
||||
TableInspectorFrame:StartMoving();
|
||||
</OnDragStart>
|
||||
<OnDragStop>
|
||||
TableInspectorFrame:StopMovingOrSizing();
|
||||
</OnDragStop>
|
||||
</Scripts>
|
||||
</Frame>
|
||||
<Button name="$parentBackButton" inherits="UIPanelButtonTemplate" text="< Back">
|
||||
<Size x="60" y="20"/>
|
||||
<Anchors>
|
||||
<Anchor point="TOPLEFT">
|
||||
<Offset x="12" y="-32"/>
|
||||
</Anchor>
|
||||
</Anchors>
|
||||
<Scripts>
|
||||
<OnClick>TableInspector_Back();</OnClick>
|
||||
</Scripts>
|
||||
</Button>
|
||||
<Button name="$parentRefreshButton" inherits="UIPanelButtonTemplate" text="Refresh">
|
||||
<Size x="70" y="20"/>
|
||||
<Anchors>
|
||||
<Anchor point="LEFT" relativeTo="$parentBackButton" relativePoint="RIGHT">
|
||||
<Offset x="4" y="0"/>
|
||||
</Anchor>
|
||||
</Anchors>
|
||||
<Scripts>
|
||||
<OnClick>TableInspector_Refresh();</OnClick>
|
||||
</Scripts>
|
||||
</Button>
|
||||
<Slider name="$parentScroll" orientation="VERTICAL">
|
||||
<Size x="16" y="0"/>
|
||||
<Anchors>
|
||||
<Anchor point="TOPRIGHT">
|
||||
<Offset x="-7" y="-56"/>
|
||||
</Anchor>
|
||||
<Anchor point="BOTTOMRIGHT">
|
||||
<Offset x="-7" y="10"/>
|
||||
</Anchor>
|
||||
</Anchors>
|
||||
<Layers>
|
||||
<Layer level="BACKGROUND">
|
||||
<Texture name="$parentBG" setAllPoints="true">
|
||||
<Color r=".8" g=".8" b="1" a="0.1"/>
|
||||
</Texture>
|
||||
</Layer>
|
||||
</Layers>
|
||||
<Scripts>
|
||||
<OnLoad>
|
||||
this:SetFrameLevel(this:GetFrameLevel() + 1);
|
||||
this:SetMinMaxValues(0, 1);
|
||||
this:SetValue(0);
|
||||
this:SetValueStep(1);
|
||||
</OnLoad>
|
||||
<OnValueChanged>
|
||||
TableInspectorFrame_Update();
|
||||
</OnValueChanged>
|
||||
</Scripts>
|
||||
<ThumbTexture name="$parentThumb" file="Interface\Buttons\UI-ScrollBar-Knob">
|
||||
<Size x="16" y="16"/>
|
||||
<TexCoords left="0.25" right="0.75" top="0.25" bottom="0.75"/>
|
||||
</ThumbTexture>
|
||||
</Slider>
|
||||
</Frames>
|
||||
<Scripts>
|
||||
<OnLoad>TableInspectorFrame_OnLoad(this);</OnLoad>
|
||||
</Scripts>
|
||||
</Frame>
|
||||
|
||||
<!-- ================================================================ -->
|
||||
<!-- Tooltips -->
|
||||
<!-- ================================================================ -->
|
||||
|
||||
<GameTooltip name="FrameStackTooltip" frameStrata="TOOLTIP" hidden="true" parent="UIParent" inherits="GameTooltipTemplate">
|
||||
<Scripts>
|
||||
<OnLoad>DebugTooltip_OnLoad(this);</OnLoad>
|
||||
<OnShow>FrameStackTooltip_OnShow(this);</OnShow>
|
||||
<OnEnter>FrameStackTooltip_OnEnter(this);</OnEnter>
|
||||
<OnUpdate>FrameStackTooltip_OnUpdate(this, arg1);</OnUpdate>
|
||||
</Scripts>
|
||||
</GameTooltip>
|
||||
|
||||
<GameTooltip name="EventTraceTooltip" frameStrata="TOOLTIP" hidden="true" parent="EventTraceFrame" inherits="GameTooltipTemplate">
|
||||
<Scripts>
|
||||
<OnLoad>DebugTooltip_OnLoad(this);</OnLoad>
|
||||
</Scripts>
|
||||
</GameTooltip>
|
||||
|
||||
</Ui>
|
||||
@@ -1,335 +0,0 @@
|
||||
------------------------------------------------------------------------------
|
||||
-- TableInspector.lua
|
||||
--
|
||||
-- Vanilla 1.12 backport of the modern Blizzard_TableInspector UX,
|
||||
-- scoped to the "minimal" feature set: one navigable window with a
|
||||
-- breadcrumb showing the current path, a scrollable list of (key,
|
||||
-- value) rows for the current table, and click-to-drill / Back-to-pop
|
||||
-- navigation through sub-tables.
|
||||
--
|
||||
-- Trade-offs vs the modern source:
|
||||
-- * No DataProvider / ScrollBox infrastructure — we use the same
|
||||
-- fixed-row + slider pattern EventTraceFrame uses (vanilla
|
||||
-- FauxScrollFrame works too but we already validated the slider
|
||||
-- approach in this addon).
|
||||
-- * No anchor / attribute providers, no live polling — open once
|
||||
-- against the current snapshot.
|
||||
-- * No multi-tab or pinning — one window, navigate via Back.
|
||||
--
|
||||
-- API:
|
||||
-- TableInspector_Show(tbl, label) -- open with `tbl` as root, `label` shown in breadcrumb
|
||||
-- TableInspector_Push(tbl, label) -- drill in (called by row click)
|
||||
-- TableInspector_Back() -- pop one level
|
||||
-- TableInspector_Refresh() -- re-read the current level's live table (scroll kept)
|
||||
-- TableInspector_Close() -- hide the window
|
||||
-- /tinspect <luaexpr> -- evaluate `<luaexpr>` as Lua and open if result is a table
|
||||
------------------------------------------------------------------------------
|
||||
|
||||
TABLE_INSPECTOR_ROW_HEIGHT = 16;
|
||||
TABLE_INSPECTOR_NUM_ROWS = 22;
|
||||
|
||||
local _TableInspectorFrame;
|
||||
|
||||
-- Navigation stack — `{ {tbl=..., label=...}, ... }`. The last entry
|
||||
-- is the active view. Push when drilling in, pop on Back.
|
||||
local _navStack = {};
|
||||
|
||||
------------------------------------------------------------------------------
|
||||
-- Key + value formatting
|
||||
------------------------------------------------------------------------------
|
||||
|
||||
-- Returns three lists: numeric keys (sorted ascending), string keys
|
||||
-- (sorted), and other-type keys (booleans, tables-as-keys, etc.).
|
||||
-- The other-type bucket stays unsorted — there's no canonical order
|
||||
-- across types and these are rare in practice.
|
||||
local function _SortedKeys(tbl)
|
||||
local nums, strs, others = {}, {}, {};
|
||||
for k in pairs(tbl) do
|
||||
local t = type(k);
|
||||
if (t == "number") then
|
||||
table.insert(nums, k);
|
||||
elseif (t == "string") then
|
||||
table.insert(strs, k);
|
||||
else
|
||||
table.insert(others, k);
|
||||
end
|
||||
end
|
||||
table.sort(nums);
|
||||
table.sort(strs);
|
||||
return nums, strs, others;
|
||||
end
|
||||
|
||||
-- Returns (displayText, valueType, isDrillable). `isDrillable` is true
|
||||
-- only for tables (the only type that can be navigated into).
|
||||
local function _FormatValue(v)
|
||||
local t = type(v);
|
||||
if (t == "string") then
|
||||
-- Truncate very long strings to keep rows scannable; user can
|
||||
-- always tooltip-hover for the full content if needed.
|
||||
if (string.len(v) > 80) then
|
||||
return string.format('"%s..."', string.sub(v, 1, 77)), "string", false;
|
||||
end
|
||||
return string.format('"%s"', v), "string", false;
|
||||
elseif (t == "number") then
|
||||
return tostring(v), "number", false;
|
||||
elseif (t == "boolean") then
|
||||
return v and "true" or "false", "boolean", false;
|
||||
elseif (t == "table") then
|
||||
return tostring(v), "table", true;
|
||||
elseif (t == "function") then
|
||||
return tostring(v), "function", false;
|
||||
elseif (t == "userdata") then
|
||||
return tostring(v), "userdata", false;
|
||||
end
|
||||
return tostring(v), t, false;
|
||||
end
|
||||
|
||||
local _TYPE_COLORS = {
|
||||
["string"] = { 1.00, 0.75, 0.40 },
|
||||
["number"] = { 0.60, 0.85, 1.00 },
|
||||
["boolean"] = { 0.70, 0.70, 1.00 },
|
||||
["table"] = { 0.60, 1.00, 0.60 },
|
||||
["function"] = { 1.00, 0.60, 0.60 },
|
||||
["userdata"] = { 1.00, 0.60, 0.60 },
|
||||
};
|
||||
|
||||
local function _ValueColor(t)
|
||||
local c = _TYPE_COLORS[t];
|
||||
if (c) then return c[1], c[2], c[3]; end
|
||||
return 1, 1, 1;
|
||||
end
|
||||
|
||||
local function _FormatKey(k)
|
||||
local t = type(k);
|
||||
if (t == "string") then return k; end
|
||||
if (t == "number") then return string.format("[%d]", k); end
|
||||
return string.format("[%s]", tostring(k));
|
||||
end
|
||||
|
||||
------------------------------------------------------------------------------
|
||||
-- View state — manages the flattened (key, value) list for the active
|
||||
-- table. Rebuilt on push / pop, not on every Update tick.
|
||||
------------------------------------------------------------------------------
|
||||
|
||||
-- Cached array of (key, value) tuples for the active table, in the
|
||||
-- sort order returned by _SortedKeys. Re-derived on every navigation
|
||||
-- change so the rows can be rendered by simple `entries[scroll + i]`
|
||||
-- indexing instead of walking `pairs()` mid-frame.
|
||||
local _entries = {};
|
||||
|
||||
local function _RebuildEntries()
|
||||
_entries = {};
|
||||
local top = _navStack[table.getn(_navStack)];
|
||||
if (not top or type(top.tbl) ~= "table") then return; end
|
||||
local nums, strs, others = _SortedKeys(top.tbl);
|
||||
for i = 1, table.getn(nums) do
|
||||
local k = nums[i];
|
||||
table.insert(_entries, { key = k, value = top.tbl[k] });
|
||||
end
|
||||
for i = 1, table.getn(strs) do
|
||||
local k = strs[i];
|
||||
table.insert(_entries, { key = k, value = top.tbl[k] });
|
||||
end
|
||||
for i = 1, table.getn(others) do
|
||||
local k = others[i];
|
||||
table.insert(_entries, { key = k, value = top.tbl[k] });
|
||||
end
|
||||
end
|
||||
|
||||
local function _Breadcrumb()
|
||||
local parts = {};
|
||||
for i = 1, table.getn(_navStack) do
|
||||
table.insert(parts, _navStack[i].label or "?");
|
||||
end
|
||||
return table.concat(parts, " > ");
|
||||
end
|
||||
|
||||
------------------------------------------------------------------------------
|
||||
-- Public API
|
||||
------------------------------------------------------------------------------
|
||||
|
||||
function TableInspector_Show(tbl, label)
|
||||
if (type(tbl) ~= "table") then
|
||||
DEFAULT_CHAT_FRAME:AddMessage(
|
||||
"|cffff8888TableInspector: argument is not a table|r");
|
||||
return;
|
||||
end
|
||||
_navStack = { { tbl = tbl, label = label or tostring(tbl) } };
|
||||
_RebuildEntries();
|
||||
if (_TableInspectorFrame) then
|
||||
_TableInspectorFrame:Show();
|
||||
TableInspectorFrame_Update();
|
||||
end
|
||||
end
|
||||
|
||||
function TableInspector_Push(tbl, label)
|
||||
if (type(tbl) ~= "table") then return; end
|
||||
table.insert(_navStack, { tbl = tbl, label = label or tostring(tbl) });
|
||||
_RebuildEntries();
|
||||
-- Reset scroll to top so the user starts at the beginning of the
|
||||
-- newly-drilled table.
|
||||
local scroll = getglobal("TableInspectorFrameScroll");
|
||||
if (scroll) then scroll:SetValue(0); end
|
||||
TableInspectorFrame_Update();
|
||||
end
|
||||
|
||||
function TableInspector_Back()
|
||||
if (table.getn(_navStack) <= 1) then
|
||||
TableInspector_Close();
|
||||
return;
|
||||
end
|
||||
table.remove(_navStack);
|
||||
_RebuildEntries();
|
||||
local scroll = getglobal("TableInspectorFrameScroll");
|
||||
if (scroll) then scroll:SetValue(0); end
|
||||
TableInspectorFrame_Update();
|
||||
end
|
||||
|
||||
function TableInspector_Refresh()
|
||||
local top = _navStack[table.getn(_navStack)];
|
||||
if (not top or type(top.tbl) ~= "table") then return; end
|
||||
_RebuildEntries();
|
||||
TableInspectorFrame_Update();
|
||||
end
|
||||
|
||||
function TableInspector_Close()
|
||||
if (_TableInspectorFrame) then _TableInspectorFrame:Hide(); end
|
||||
_navStack = {};
|
||||
_entries = {};
|
||||
end
|
||||
|
||||
------------------------------------------------------------------------------
|
||||
-- Frame scripts (called from TableInspector XML in DebugTools.xml)
|
||||
------------------------------------------------------------------------------
|
||||
|
||||
function TableInspectorFrame_OnLoad(self)
|
||||
self.rows = {};
|
||||
_TableInspectorFrame = self;
|
||||
|
||||
self:EnableMouse(true);
|
||||
self:EnableMouseWheel(true);
|
||||
self:SetScript("OnMouseWheel", function()
|
||||
TableInspectorFrame_OnMouseWheel(this, arg1);
|
||||
end);
|
||||
|
||||
for i = 1, TABLE_INSPECTOR_NUM_ROWS do
|
||||
local row = CreateFrame("Button", "TableInspectorFrameRow" .. i, self,
|
||||
"TableInspectorRowTemplate");
|
||||
row:SetPoint("TOPLEFT", 12, -(56 + (i - 1) * TABLE_INSPECTOR_ROW_HEIGHT));
|
||||
row:SetPoint("RIGHT", -28, 0);
|
||||
row.rowIndex = i;
|
||||
table.insert(self.rows, row);
|
||||
end
|
||||
end
|
||||
|
||||
function TableInspectorFrame_Update()
|
||||
if (not _TableInspectorFrame or not _TableInspectorFrame.rows) then return; end
|
||||
|
||||
local scroll = getglobal("TableInspectorFrameScroll");
|
||||
if (not scroll) then return; end
|
||||
|
||||
local total = table.getn(_entries);
|
||||
local visible = TABLE_INSPECTOR_NUM_ROWS;
|
||||
local maxOffset = math.max(0, total - visible);
|
||||
scroll:SetMinMaxValues(0, maxOffset);
|
||||
local offset = math.floor(scroll:GetValue() + 0.5);
|
||||
if (offset > maxOffset) then offset = maxOffset; end
|
||||
if (offset < 0) then offset = 0; end
|
||||
|
||||
-- Update breadcrumb each tick — cheap (string concat over a tiny
|
||||
-- nav stack) and avoids a separate "breadcrumb changed" signal.
|
||||
local crumb = getglobal("TableInspectorFrameBreadcrumb");
|
||||
if (crumb) then
|
||||
crumb:SetText(_Breadcrumb() .. string.format(" (%d entries)", total));
|
||||
end
|
||||
|
||||
for i = 1, visible do
|
||||
local row = _TableInspectorFrame.rows[i];
|
||||
local entry = _entries[offset + i];
|
||||
if (entry) then
|
||||
local keyFS = getglobal(row:GetName() .. "Key");
|
||||
local valFS = getglobal(row:GetName() .. "Value");
|
||||
keyFS:SetText(_FormatKey(entry.key));
|
||||
local disp, vt, drillable = _FormatValue(entry.value);
|
||||
valFS:SetText(disp);
|
||||
valFS:SetTextColor(_ValueColor(vt));
|
||||
row.entryKey = entry.key;
|
||||
row.entryValue = entry.value;
|
||||
row.drillable = drillable;
|
||||
row:Show();
|
||||
else
|
||||
row.entryKey = nil;
|
||||
row.entryValue = nil;
|
||||
row.drillable = false;
|
||||
row:Hide();
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function TableInspectorFrame_OnMouseWheel(self, delta)
|
||||
local scroll = getglobal("TableInspectorFrameScroll");
|
||||
if (not scroll) then return; end
|
||||
local mn, mx = scroll:GetMinMaxValues();
|
||||
local v = scroll:GetValue() - delta * 3;
|
||||
if (v < mn) then v = mn; end
|
||||
if (v > mx) then v = mx; end
|
||||
scroll:SetValue(v);
|
||||
end
|
||||
|
||||
function TableInspectorRow_OnClick(self)
|
||||
if (not self.drillable or type(self.entryValue) ~= "table") then return; end
|
||||
TableInspector_Push(self.entryValue, _FormatKey(self.entryKey));
|
||||
end
|
||||
|
||||
------------------------------------------------------------------------------
|
||||
-- Slash command — /tinspect <luaexpr>
|
||||
--
|
||||
-- Evaluates `<luaexpr>` in a fresh chunk with `return ` prefixed, so
|
||||
-- bare expressions (`_G`, `GameTooltip`, `MyAddOn.foo`) work without
|
||||
-- the user having to write `return ...` themselves.
|
||||
------------------------------------------------------------------------------
|
||||
|
||||
local function _ChatErr(msg)
|
||||
DEFAULT_CHAT_FRAME:AddMessage("|cffff8888TableInspector:|r " .. msg);
|
||||
end
|
||||
|
||||
function TableInspector_HandleSlashCmd(msg)
|
||||
if (not msg) then msg = ""; end
|
||||
msg = string.gsub(msg, "^%s*(.-)%s*$", "%1"); -- trim
|
||||
if (msg == "" or msg == "help") then
|
||||
DEFAULT_CHAT_FRAME:AddMessage(
|
||||
"|cff88ff88/tinspect|r <expr> -- open inspector on the result of <expr>");
|
||||
DEFAULT_CHAT_FRAME:AddMessage(" example: /tinspect _G");
|
||||
DEFAULT_CHAT_FRAME:AddMessage(" example: /tinspect ChatTypeInfo");
|
||||
return;
|
||||
end
|
||||
if (msg == "close") then
|
||||
TableInspector_Close();
|
||||
return;
|
||||
end
|
||||
local chunk, parseErr = loadstring("return " .. msg);
|
||||
if (not chunk) then
|
||||
_ChatErr("parse error: " .. tostring(parseErr));
|
||||
return;
|
||||
end
|
||||
-- Run in the global environment so the user's expression sees
|
||||
-- the usual addon globals. setfenv on the loadstring chunk
|
||||
-- defaults to that already in vanilla, but be explicit.
|
||||
setfenv(chunk, getfenv(0));
|
||||
local ok, result = pcall(chunk);
|
||||
if (not ok) then
|
||||
_ChatErr("eval error: " .. tostring(result));
|
||||
return;
|
||||
end
|
||||
if (type(result) ~= "table") then
|
||||
_ChatErr(string.format(
|
||||
"result is %s (%s), expected table",
|
||||
type(result), tostring(result)));
|
||||
return;
|
||||
end
|
||||
TableInspector_Show(result, msg);
|
||||
end
|
||||
|
||||
SLASH_TINSPECT1 = "/tinspect";
|
||||
SLASH_TINSPECT2 = "/tins";
|
||||
SlashCmdList["TINSPECT"] = TableInspector_HandleSlashCmd;
|
||||
+41
-61
@@ -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,26 @@ 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 the addons under `src/embed/AddOns/`, `src/bindings/Bindings.xml` and
|
||||
# the textures under `src/embed/Textures/` 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\<addon>\`, so the addons load even
|
||||
# when the user doesn't have them 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. `src/texture/Builtin.cpp`
|
||||
# serves each texture at its game path when no file has it.
|
||||
include(cmake/embed_resources.cmake)
|
||||
embed_resources(
|
||||
TARGET ${PROJECT_NAME}
|
||||
ADDONS_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/src/embed/AddOns"
|
||||
ADDONS "!!!ClassicAPI" "ClassicAPI_DebugTools" "ClassicAPI_EventTrace"
|
||||
ADDON_VERSION "${CLASSICAPI_TOC_VERSION}"
|
||||
BINDINGS_XML "${CMAKE_CURRENT_SOURCE_DIR}/src/bindings/Bindings.xml"
|
||||
TEXTURES_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/src/embed/Textures"
|
||||
OUT_DIR "${CMAKE_BINARY_DIR}/generated")
|
||||
|
||||
target_compile_definitions(
|
||||
${PROJECT_NAME}
|
||||
@@ -129,8 +100,7 @@ target_compile_definitions(
|
||||
|
||||
# Stamp the PE VERSIONINFO resource from the same version components, so the
|
||||
# DLL's file/product version (Explorer -> Properties -> Details) matches the
|
||||
# CLASSIC_API_VERSION Lua global. The .rsrc section the resource lands in is
|
||||
# untouched by the .rdata/.pdata section merges below.
|
||||
# CLASSIC_API_VERSION Lua global.
|
||||
set(CLASSICAPI_VER_STRING
|
||||
"${CLASSICAPI_VER_MAJOR}.${CLASSICAPI_VER_MINOR}.${CLASSICAPI_VER_PATCH}.0")
|
||||
set(CLASSICAPI_VERSION_RC "${CMAKE_BINARY_DIR}/generated/version.rc")
|
||||
@@ -140,6 +110,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.
|
||||
@@ -152,16 +128,19 @@ target_include_directories(
|
||||
${CMAKE_BINARY_DIR}/generated
|
||||
external/minhook/include
|
||||
external
|
||||
external/tinycbor/src)
|
||||
external/tinycbor/src
|
||||
external/unordered_dense/include)
|
||||
|
||||
set_target_properties(${PROJECT_NAME} PROPERTIES OUTPUT_NAME "ClassicAPI")
|
||||
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /MT")
|
||||
# /Zi retains full debug info (source file + line numbers, locals, types) in a
|
||||
# separate PDB WITHOUT disabling optimization — the DLL stays a fully optimized
|
||||
# /O2 release build; the symbols just live in ClassicAPI.pdb on the side. Feeds
|
||||
# the linker's /DEBUG below.
|
||||
set(CMAKE_CXX_FLAGS_RELEASE "/MT /O2 /Ob2 /DNDEBUG /Zi")
|
||||
# /O1 optimizes for size: the code is mostly short glue around engine calls,
|
||||
# and /O1 made the DLL 280 KB smaller than /O2 /Ob2 (link-time code generation,
|
||||
# /GL + /LTCG, made it larger again). /Zi retains full debug info (source file +
|
||||
# line numbers, locals, types) in a separate PDB WITHOUT disabling
|
||||
# optimization; the symbols just live in ClassicAPI.pdb on the side. Feeds the
|
||||
# linker's /DEBUG below.
|
||||
set(CMAKE_CXX_FLAGS_RELEASE "/MT /O1 /DNDEBUG /Zi")
|
||||
set(CMAKE_SHARED_LINKER_FLAGS
|
||||
# Two debug artifacts for triaging crashes from a SHIPPED DLL. Both are
|
||||
# published as release artifacts, match this exact build, and have no effect
|
||||
@@ -178,8 +157,9 @@ 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"
|
||||
# The sections keep the standard layout: .text is read + execute only and
|
||||
# constants stay in a read-only .rdata. Nothing writes into this DLL's own
|
||||
# code; engine patches make their target writable themselves
|
||||
# (Common::PatchBytes).
|
||||
"/OPT:REF /OPT:ICF /NODEFAULTLIB:MSVCRT /MAP /DEBUG"
|
||||
)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# ClassicAPI
|
||||
|
||||
ClassicAPI is a DLL for World of Warcraft 1.12.1 (Vanilla / Turtle WoW). It
|
||||
backports a large part of the modern WoW API — 550+ functions and 50+ events,
|
||||
backports a large part of the modern WoW API — 950+ functions and 80+ events,
|
||||
plus much of Lua 5.1 — into the 1.12 client, so addons written for later
|
||||
versions (3.3.5+ or Classic Era) run with little or no change.
|
||||
|
||||
@@ -15,32 +15,29 @@ The headline features. Each one takes effect as soon as the DLL loads, so your
|
||||
existing addons benefit without any code changes. The complete per-function
|
||||
reference is in **[docs/API.md](docs/API.md)**.
|
||||
|
||||
### Lua 5.1 compatibility
|
||||
|
||||
The flagship feature: run modern Lua 5.1 addon code on 1.12's Lua 5.0 VM.
|
||||
|
||||
| Feature | Effect |
|
||||
|---------|--------|
|
||||
| [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. |
|
||||
| [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. |
|
||||
|
||||
### Modern client behaviors
|
||||
|
||||
| Feature | Effect |
|
||||
|---------|--------|
|
||||
| Lua 5.1 code | Addon code written for Lua 5.1 runs on the 1.12 Lua 5.0 VM. It covers the [5.1 syntax](docs/API.md#lua-51-syntax) (`#`, `%`, `...` expressions, `0x` hex, `[=[ ]=]` long brackets), [method calls on strings](docs/API.md#string-methods-supper-sformat) (`msg:match("^!(%w+)")`), [up to 60 upvalues](docs/API.md#upvalue-limit) for each function, and [new `for` loop variables](docs/API.md#for-loop-variables-per-pass) on each pass. Each addon file also gets its `(name, table)` through `...`. |
|
||||
| [Modern script handlers](docs/API.md#setmodernscriptargsenable--getmodernscriptargs) | Frame scripts get their values as arguments, for example `OnClick(self, button, down)` and `OnEvent(self, event, ...)`. [XML script bodies](docs/API.md#xml-script-bodies-see-self-and-their-arguments) such as `<OnLoad>self:Init()</OnLoad>` see `self` and their arguments by name. The `this` / `arg1` globals stay set. `SetModernScriptArgs(false)` restores the vanilla behavior. |
|
||||
| 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. |
|
||||
| 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. |
|
||||
| [Soft targeting](docs/API.md#soft-interact-softinteract--anyinteract) | The Interact Key and soft targets. Bind **Interact With Target** to a key to interact with the nearest NPC, corpse, mailbox, chest or gathering node in front of you. The [`softenemy` and `softfriend`](docs/API.md#soft-enemy-and-soft-friend-softenemy--softfriend--anyenemy--anyfriend) tokens point at the nearest enemy and friendly unit without a change of target. With no target, harmful spells go to `softenemy` and helpful spells go to `softfriend`. `PLAYER_SOFT_*_CHANGED` events fire when the units change. |
|
||||
| [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 | Removes `GameTooltip`'s 30-line limit for every `GameTooltipTemplate` frame (`GameTooltip`, `ShoppingTooltip1/2`, `ItemRefTooltip`, AtlasLoot, …). A tooltip adds a new line pair when it needs one, so long tooltips and comparison blocks (for example, pfUI's eqcompare) keep all their lines. |
|
||||
| [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. `parentArray="Name"` adds the object to a list on its parent. An `<Anchor>` takes `x` and `y` offsets and `relativeKey="$parent.Key"`. `<OnEnter inherit="prepend">` runs the template's handler and then its own, and `inherit="append"` runs them in the other order. A frame with `intrinsic="true"` makes a new frame type. Frames take `scale`, `registerForDrag`, `clipChildren`, `useParentLevel`, `dontSavePosition`, `propagateKeyboardInput`, `propagateMouseInput`, `enableMouseClicks`, `enableMouseMotion` and `motionScriptsWhileDisabled`, and buttons take `registerForClicks`. Textures take `alpha`, `atlas`, `useAtlasSize`, `mask`, `desaturated`, `rotation`, `horizTile`, `vertTile`, `hWrapMode` and `vWrapMode`. Font strings take `alpha`, `wordwrap`, `indented`, `degrees` and `radians`. Status bars take `reverseFill`, `rotatesTexture` and `fillStyle`, and edit boxes take `countInvisibleLetters`. |
|
||||
| [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. |
|
||||
| [`#showtooltip`](docs/API.md#showtooltip-and-show) | A macro button shows the spell or item that its directive resolves to, conditions included: icon, tooltip, cooldown, range, usable state and auto-repeat glow. Action-bar addons get this with no code of their own. Addons with their own macro parser can publish through `C_Macro.SetMacroDisplay`. |
|
||||
| [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. |
|
||||
| [Focus target](docs/API.md#focus) | A sticky focus unit. `FocusUnit("target")` pins it and `ClearFocus()` drops it, with `PLAYER_FOCUS_CHANGED` on every change. The `focus` / `focustarget` tokens resolve with every `UnitX` function and fire unit events (`UNIT_HEALTH`, `UNIT_AURA`, … as `arg1 == "focus"`), and the predefined `FOCUSTARGET` / `TARGETFOCUS` keybinds are ready to set. |
|
||||
| [Combat log events](docs/API.md#combat_log_event_unfiltered--combat_log_event-events) | `COMBAT_LOG_EVENT_UNFILTERED` and `CombatLogGetCurrentEventInfo` give each combat event with GUIDs and `COMBATLOG_OBJECT_*` flags. The values do not depend on the client language, so damage meters do not need to parse chat text. `COMBAT_LOG_EVENT` fires for the events that pass the `CombatLogAddFilter` filters. |
|
||||
| [Retail-like `/reload`](docs/API.md#reload-picks-up-new-addons-and-new-files) | `/reload` picks up addon changes made while the game runs. A new folder under `Interface\AddOns\` registers and loads as a normal addon, new files added to an existing addon's TOC load, a newly installed addon's first SavedVariables save survives `/reload`, `##` metadata edits (`## SavedVariables:`, `## Dependencies:`, `## Title:`, …) take effect, and a deleted addon folder drops from the addon list. |
|
||||
| [Multi-flavor & conditional TOC](docs/API.md#conditional-and-multi-flavor-toc-loading) | Loads modern multi-flavor addons that ship one folder. Selects a version-specific TOC (`<Name>_ClassicAPI.toc` or `<Name>_Turtle.toc`) and the matching keybinding file (`Bindings_ClassicAPI.xml` / `Bindings_Turtle.xml`), accepts a comma-separated `## Interface:` version list (compatible when it includes the client version `11200`), and honors per-line `[AllowLoadGameType]` / `[AllowLoadTextLocale]` conditions and `[Family]` / `[Game]` / `[TextLocale]` path variables inside a TOC. |
|
||||
| [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. |
|
||||
| [Addon memory and CPU usage](docs/API.md#profiling) | Addon managers and performance tools can show how much Lua memory and CPU time each addon uses. `GetAddOnMemoryUsage` gives the memory of each addon. When `scriptProfile` is `1`, the CPU functions give the time of each addon, function, frame, and event. With profiling off, the CPU functions cost nothing. |
|
||||
| [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
|
||||
@@ -48,73 +45,101 @@ heading to expand it. For signatures and return values, see the per-function
|
||||
reference in **[docs/API.md](docs/API.md)**.
|
||||
|
||||
<details>
|
||||
<summary><b>In-game Lua calls</b> — 550+ functions across ~60 namespaces</summary>
|
||||
<summary><b>In-game Lua calls</b> — 950+ functions across ~75 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` |
|
||||
| [Action](docs/API.md#action) | `GetActionInfo`, `IsItemAction`, `IsStackableAction`, `HasBonusActionBar`, `C_ActionBar.EnableActionRangeCheck`, `C_ActionBar.GetSpell`, `C_ActionBar.GetItemActionOnEquipSpellID`, `C_ActionBar.IsStackableAction`, `C_ActionBar.IsMacroActionWithShowTooltip`, `C_ActionBar.FindSpellActionButtons`, `C_ActionBar.HasSpellActionButtons`, `C_ActionBar.IsOnBarOrSpecialBar` |
|
||||
| [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` |
|
||||
| [AuctionHouse](docs/API.md#auctionhouse) | `C_AuctionHouse.PostItem` |
|
||||
| [Bindings](docs/API.md#bindings) | `SetBindingSpell`, `SetBindingItem`, `SetBindingMacro`, `SetBindingClick`, `SetOverrideBinding`, `SetOverrideBindingSpell`, `SetOverrideBindingItem`, `SetOverrideBindingMacro`, `SetOverrideBindingClick`, `ClearOverrideBindings` |
|
||||
| [Chat](docs/API.md#chat) | `GetCurrentChatGUID` |
|
||||
| [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`, `CanCancelAuction` |
|
||||
| [AutoComplete](docs/API.md#autocomplete) | `C_AutoComplete.GetAutoCompleteResults`, `C_AutoComplete.IsRecognizedName`, `C_AutoComplete.GetAutoCompletePresenceID`, `C_AutoComplete.GetAutoCompleteRealms` |
|
||||
| [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) | `GetCurrentChatEvent`, `GetCurrentChatGUID`, `IsChatAFK`, `IsChatDND`, `SendSystemMessage` |
|
||||
| [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` |
|
||||
| [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` |
|
||||
| [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` |
|
||||
| [CombatLog](docs/API.md#combatlog) | `CombatLogGetCurrentEventInfo`, `COMBATLOG_OBJECT_*` (constants) |
|
||||
| [Console](docs/API.md#console) | `CalculateStringEditDistance`, `ConsoleAddMessage`, `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.RemoveTempCVar`, `C_CVar.SetCVar`, `C_CVar.SetCVarBitfield`, `C_CVar.SetTempCVar`, `GetCVar`, `GetCVarDefault` |
|
||||
| [Cursor](docs/API.md#cursor) | `CursorHasMacro`, `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.IsContainerFiltered`, `C_Container.IsContainerItemOpenable`, `C_Container.MoveItem`, `C_Container.PlayerHasHearthstone`, `C_Container.SetBackpackAutosortDisabled`, `C_Container.SetBagPortraitTexture`, `C_Container.SetBankAutosortDisabled`, `C_Container.SetItemSearch`, `C_Container.SetSortBagsRightToLeft`, `C_Container.SortBags`, `C_Container.SortBankBags`, `C_Container.SwapItems`, `C_Container.UseHearthstone`, `GetItemCooldown`, `SetBagPortraitTexture` |
|
||||
| [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` |
|
||||
| [Currency](docs/API.md#currency) | `GetCoinText`, `C_CurrencyInfo.GetCoinText`, `GetCoinTextureString`, `C_CurrencyInfo.GetCoinTextureString`, `Constants.MoneyFormattingConstants` |
|
||||
| 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` |
|
||||
| [DeathInfo](docs/API.md#deathinfo) | `C_DeathInfo.GetSelfResurrectOptions`, `C_DeathInfo.UseSelfResurrectOption` |
|
||||
| [DurationUtil](docs/API.md#durationutil) | `C_DurationUtil.CreateDuration`, `C_DurationUtil.CreateDurationTextBinding` |
|
||||
| [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` |
|
||||
| [Expansion](docs/API.md#expansion) | `ClassicExpansionAtLeast`, `ClassicExpansionAtMost`, `GetAccountExpansionLevel`, `GetClassicExpansionLevel`, `GetExpansionLevel`, `GetMaxPlayerLevel` |
|
||||
| [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`, `CollapseAllFactionHeaders`, `ExpandAllFactionHeaders`, `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), `button:RegisterForClicks("AnyUp"/"AnyDown")`, `GetClickFrame` |
|
||||
| [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` |
|
||||
| [Frame: Region](docs/API.md#regionsetpointpoint-one-argument-form) | `:SetPoint("point")` (one-arg form), `:SetSize` / `:GetSize`, `ignoreRect` on `:GetSize` / `:GetWidth` / `:GetHeight`, `:GetUnscaledWidth` / `:GetUnscaledHeight` / `:GetUnscaledSize`, `:GetRect`, `:GetScaledRect`, `:IsRectValid`, `:GetPointByName`, `:ClearPoint`, `:GetScale` / `:GetEffectiveScale` (on textures and font strings), `:GetDebugName`, `:IsMouseOver`, `:IsDragging`, `:IsProtected` / `:CanChangeProtectedState` |
|
||||
| [Frame: Frame](docs/API.md#createframeframetype--name-parent-template-id) | `CreateFrame` template lists and `id`, `GetMouseFoci`, `:SetShown`, `:SetClampRectInsets` / `:GetClampRectInsets`, `:SetResizeBounds`, `:SetClipsChildren` / `:DoesClipChildren`, `:GetBoundsRect`, `:GetEffectiveAlpha`, `:SetAlphaGradient` / `:ClearAlphaGradient` / `:HasAlphaGradient`, `:DesaturateHierarchy`, `: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`, `:SetTexture` wrap modes, `:SetHorizTile` / `:GetHorizTile`, `:SetVertTile` / `:GetVertTile`, `: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`, `:SetTimerDuration` / `:GetTimerDuration`, `:SetValue` / `:SetMinMaxValues` with `interpolation`, `:GetInterpolatedValue`, `:IsInterpolating`, `:SetToTargetValue` |
|
||||
| [Frame: Slider](docs/API.md#sliderenable--sliderdisable--sliderisenabled) | `:Enable` / `:Disable` / `:IsEnabled` |
|
||||
| [Frame: Cooldown](docs/API.md#createframecooldown--name-parent-template) | `CreateFrame("Cooldown")`, `:SetCooldown`, `:SetCooldownDuration`, `:SetCooldownFromExpirationTime`, `:Clear`, `:GetCooldownTimes`, `:GetCooldownDuration`, `:GetCooldownDisplayDuration`, `:Pause` / `:Resume`, `:SetPaused` / `:IsPaused`, `:SetReverse` / `:GetReverse`, `:SetDrawEdge` / `:GetDrawEdge`, `:SetDrawSwipe` / `:GetDrawSwipe`, `:SetDrawBling` / `:GetDrawBling`, `:SetSwipeColor`, `:SetEdgeColor`, `:SetSwipeTexture`, `:SetEdgeTexture`, `:SetBlingTexture`, `:SetRotation` / `:GetRotation`, `:SetHideCountdownNumbers` / `:GetHideCountdownNumbers`, `:GetCountdownFontString`, `:SetCountdownAbbrevThreshold` / `:GetCountdownAbbrevThreshold`, `:SetCountdownMillisecondsThreshold` / `:GetCountdownMillisecondsThreshold`, `:SetMinimumCountdownDuration` / `:GetMinimumCountdownDuration`, `OnCooldownDone`, `CooldownFrame_Set`, `CooldownFrame_Clear`, `CooldownFrame_SetDisplayAsPercentage` |
|
||||
| [Frame: ScrollingMessageFrame](docs/API.md#smfsethyperlinksenabledenabled--smfgethyperlinksenabled) | `:SetHyperlinksEnabled` / `:GetHyperlinksEnabled`, `:GetMessageInfo` (with the extra `:AddMessage` values), `:BackFillMessage` (adds a message as the oldest), `:RemoveMessagesByPredicate`, `:SetScrollOffset` / `:GetScrollOffset`, `:GetMaxScrollRange`, `:ScrollByAmount`, `:SetInsertMode` / `:GetInsertMode`, `:AddOnDisplayRefreshedCallback` |
|
||||
| [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) | `AddOrRemoveFriend`, `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.GetPoiForUiMapID`, `C_GossipInfo.GetPoiInfo`, `C_GossipInfo.GetText`, `C_GossipInfo.SelectActiveQuest`, `C_GossipInfo.SelectAvailableQuest`, `C_GossipInfo.SelectOption`, `C_GossipInfo.SelectOptionByIndex`, `GetNumGossipActiveQuests`, `GetNumGossipAvailableQuests`, `GetNumGossipOptions` |
|
||||
| [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` |
|
||||
| [Input](docs/API.md#input) | `GetMouseButtonClicked`, `GetMouseButtonName`, `IsLeftAltKeyDown`, `IsLeftControlKeyDown`, `IsLeftShiftKeyDown`, `IsModifierKeyDown`, `IsMouseButtonDown`, `IsRightAltKeyDown`, `IsRightControlKeyDown`, `IsRightShiftKeyDown` |
|
||||
| [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.ItemHasRange`, `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`, `IsCurrentItem`, `IsDressableItem`, `IsEquippedItemType`, `IsHarmfulItem`, `IsHelpfulItem`, `IsUsableItem` |
|
||||
| [Item: inventory](docs/API.md#getaverageitemlevel) | `GetAverageItemLevel`, `GetInventoryItemID`, `GetInventoryItemDurability`, `GetInventoryItemRepairCost`, `GetInventoryItemsForSlot`, `IsDualWielding`, `SetInventoryPortraitTexture` |
|
||||
| [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` |
|
||||
| [Localization](docs/API.md#localization) | `AbbreviateLargeNumbers`, `AbbreviateNumbers`, `BreakUpLargeNumbers`, `C_StringUtil.GetDefaultAbbreviationBreakpoints` |
|
||||
| [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`, `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.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`, `StopMacro` |
|
||||
| [Lua](docs/API.md#lua) | `collectgarbage` (5.1 options), `coroutine.create`, `coroutine.resume`, `coroutine.running`, `coroutine.status`, `coroutine.wrap`, `coroutine.yield`, `CreateFromMixins`, `debuglocals`, `debugstack` (coroutine argument), `difftime`, `GetCallstackHeight`, `GetErrorCallstackHeight`, `gmatch`, `math.cosh`, `math.fmod`, `math.huge`, `math.modf`, `math.sinh`, `math.tanh`, `Mixin`, `newproxy`, `scrub`, `select`, `SetErrorCallstackHeight`, `strbyte` (range args), `strcmputf8i`, `strconcat`, `string.byte` (range args), `string.concat`, `string.format` (two-digit `%n$`), `string.gmatch`, `string.gsub` (table replacement, `%0`), `string.join`, `string.match`, `string.reverse`, `string.split`, `string.trim`, `strjoin`, `strlenutf8`, `strmatch`, `strreplace`, `strrev`, `strsplit`, `strsplittable`, `strtrim`, `table.count`, `table.maxn`, `table.removemulti`, `table.wipe`, `unpack` (range args), `wipe`, `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`, `GetMacroBody`, `GetMacroIcons`, `GetMacroItem`, `GetMacroItemIcons`, `GetMacroSpell`, `GetRunningMacro`, `GetRunningMacroButton`, `RunMacroText`, `SetMacroItem`, `SetMacroSpell`, `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` |
|
||||
| [MerchantFrame](docs/API.md#merchantframe) | `C_MerchantFrame.GetBuybackItemID`, `C_MerchantFrame.GetItemInfo`, `C_MerchantFrame.GetNumJunkItems`, `C_MerchantFrame.IsMerchantItemRefundable`, `C_MerchantFrame.IsSellAllJunkEnabled`, `C_MerchantFrame.SellAllJunkItems` |
|
||||
| [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`, `GetBuybackItemLink` |
|
||||
| [Model](docs/API.md#model) | `DressUpModel:TryOn` (links, recipes, names, hand, enchant glow, result), `DressUpModel:UndressSlot`, `DressUpModel:IsGeoReady`, `DressUpModel:SetSheathed` / `GetSheathed`, `DressUpModel:SetAutoDress` / `GetAutoDress`, `Model:SetGlow`, `PlayerModel:RefreshCamera`, `PlayerModel:SetCamDistanceScale`, `PlayerModel:SetCreature` (`displayID`), `PlayerModel:SetDisplayInfo`, `PlayerModel:SetItem`, `PlayerModel:SetPortraitZoom`, `PlayerModel:SetRotation` (`animate`), `PlayerModel:SetUnit` (result), `PlayerModel:CanSetUnit`, `PlayerModel:GetDisplayInfo`, `PlayerModel:SetAnimation`, `PlayerModel:FreezeAnimation`, `PlayerModel:HasAnimation`, `PlayerModel:SetDoBlend` / `GetDoBlend`, `PlayerModel:SetKeepModelOnHide` / `GetKeepModelOnHide`, `PlayerModel:ApplySpellVisualKit` |
|
||||
| [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` |
|
||||
| [NameCache](docs/API.md#namecache) | `C_PlayerCache.GetPlayerInfoByName`, `C_PlayerCache.IsEnabled`, `C_PlayerCache.RememberPlayer`, `C_PlayerCache.SetEnabled`, `GetPlayerInfoByGUID`, `UnitNameFromGUID` |
|
||||
| [NewItems](docs/API.md#newitems) | `C_NewItems.ClearAll`, `C_NewItems.IsNewItem`, `C_NewItems.RemoveNewItem` |
|
||||
| [PartyInfo](docs/API.md#partyinfo) | `InviteUnit`, `PromoteToLeader`, `UninviteUnit` |
|
||||
| [Pet](docs/API.md#pet) | `IsPetAttackAction`, `IsAtStableMaster` |
|
||||
| [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` |
|
||||
| [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`, `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` |
|
||||
| [Profiling](docs/API.md#profiling) | `GetAddOnCPUUsage`, `GetAddOnMemoryUsage`, `GetEventCPUUsage`, `GetFrameCPUUsage`, `GetFunctionCPUUsage`, `GetScriptCPUUsage`, `ResetCPUUsage`, `UpdateAddOnCPUUsage`, `UpdateAddOnMemoryUsage` |
|
||||
| [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`, `GetQuestLogCompletionText`, `GetQuestLogLeaderBoardID` (Turtle WoW only: `C_QuestLog.GetAllCompletedQuestIDs`, `C_QuestLog.IsQuestFlaggedCompleted`, `GetQuestsCompleted`, `QueryQuestsCompleted`) |
|
||||
| [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`, `CancelUnitBuff`, `CastSpellByID`, `CastSpellNoToggle`, `GetCraftSpellID`, `GetCritChance`, `GetRangedCritChance`, `GetSpellBaseCooldown`, `GetSpellBonusDamage`, `GetSpellBonusHealing`, `GetSpellInfo`, `GetSpellLink`, `GetSpellRadius`, `GetSpellRequiredTargetLevel`, `GetSpellSchool`, `IsAttackSpell`, `IsAutoRepeatSpell`, `IsConsumableSpell`, `IsHarmfulSpell`, `IsHelpfulSpell`, `IsPassiveSpell`, `IsPlayerSpell`, `IsSpellKnown`, `IsUsableSpell`, `SpellHasRange`, `UnitCastingDuration`, `UnitChannelDuration` |
|
||||
| [SpellActivationOverlay](docs/API.md#spellactivationoverlay) | `C_SpellActivationOverlay.IsSpellOverlayed`, `IsSpellOverlayed` |
|
||||
| [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` |
|
||||
| [System](docs/API.md#system) | `CopyToClipboard`, `GetPhysicalScreenSize` |
|
||||
| [State](docs/API.md#state) | `CancelShapeshiftForm`, `Dismount`, `GetMirrorTimerInfo`, `GetMirrorTimerProgress`, `GetShapeshiftForm`, `GetShapeshiftFormID`, `GetSheathState`, `IsAssistingRitual`, `IsFalling`, `IsIndoors`, `IsInGroup`, `IsInRaid`, `IsLoggedIn`, `IsLoggingOut`, `IsMounted`, `IsOutdoors`, `IsPlayerInWorld`, `IsStealthed`, `IsSwimming` |
|
||||
| [SwingTimer](docs/API.md#swingtimer) | `C_SwingTimer.EnableRangeCheck`, `C_SwingTimer.IsTargetWithinSwingRange` |
|
||||
| [System](docs/API.md#system) | `CopyToClipboard`, `FlashClientIcon`, `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` |
|
||||
| [Texture](docs/API.md#texture) | `C_Texture.GetAtlasElementID`, `C_Texture.GetAtlasElements`, `C_Texture.GetAtlasExists`, `C_Texture.GetAtlasID`, `C_Texture.GetAtlasInfo`, `C_Texture.RegisterAtlas`, `SetPortraitTextureFromCreatureDisplayID` |
|
||||
| [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`, `GetTickTime`, `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) | `GetTradeSkillListLink`, `GetCraftListLink`, `GetTradeSkillDescription`, `GetTradeSkillRecipeLink`, `IsTradeSkillLinked`, `IsCraftLinked` |
|
||||
| [Trainer](docs/API.md#trainer) | `GetTrainerServiceItemLink` |
|
||||
| [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` |
|
||||
| [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` |
|
||||
| [Unit](docs/API.md#unit) | `CanBeRaidTarget`, `ClosestUnitPosition`, `GetUnitSpeed`, `IsUnitToken`, `SetUnitCursorTexture`, `UnitClassBase`, `UnitCreatedBySpell`, `UnitCreatureFamilyID`, `UnitCreatureID`, `UnitCreatureTypeID`, `UnitDistanceSquared`, `UnitFacing`, `UnitGUID`, `UnitHasIncomingResurrection`, `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.GetAuraDataByAuraInstanceID`, `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` |
|
||||
|
||||
@@ -134,7 +159,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` |
|
||||
@@ -181,6 +206,57 @@ for what each command does, and
|
||||
|
||||
</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
|
||||
these settings, the player cache and the ClassicAPI key bindings 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. |
|
||||
| [Combat log](docs/API.md#kept-entries) | `combatLogRetentionTime` | `300` | The number of seconds that the combat log keeps an entry. |
|
||||
| [Stand, dismount and form](docs/API.md#stand-dismount-and-form-settings-autostand-autodismount-autounshift) | `autoStand` | `0` | `1` makes you stand up when you cast, loot or open the flight map while you sit. |
|
||||
| | `autoDismount` | `0` | `1` makes you dismount when you cast, use an object, loot, attack or open the flight map while you are mounted. |
|
||||
| | `autoUnshift` | `0` | `1` makes you leave your form when you cast a spell that cannot be cast in it, use an item, or open the flight map. It also lets you talk to NPCs and use objects in druid forms and Ghost Wolf. |
|
||||
| [Bag sorting](docs/API.md#c_containergetsortbagsrighttoleft--c_containersetsortbagsrighttoleftenable) | `sortBagsRightToLeft` | `0` | `1` makes a sort fill your bags from the last slot of the last bag. |
|
||||
| | `backpackAutosortDisabled` | `0` | `1` keeps the items in your backpack in place when you sort your bags. |
|
||||
| | `bankAutosortDisabled` | `0` | `1` keeps the items in the main bank slots in place when you sort your bank. |
|
||||
| [Expanded cursors](docs/API.md#expanded-cursors-expandedcursors) | `expandedCursors` | `0` | `1` makes the cursor show what you can do with an NPC or an object: an anvil for repairs, a hearthstone for an inn, a horseshoe for a stable, `!` or `?` for quests, and a fish hook for your fishing bobber. |
|
||||
| [Equipment sets](docs/API.md#equipment-sets-on-item-tooltips) | `dontShowEquipmentSetsOnItems` | `0` | `1` removes the Equipment Sets line from item tooltips. |
|
||||
| [Name completion](docs/API.md#name-completion-settings) | `autoCompleteResortNamesOnRecency` | `1` | `1` puts the players that you whispered first in `C_AutoComplete` results, the most recent first. `0` uses alphabetical order. |
|
||||
| | `autoCompleteWhenEditingFromCenter` | `1` | `1` also matches the text after the cursor when you type inside a name. |
|
||||
| | `autoCompleteUseContext` | `1` | `0` makes `C_AutoComplete` ignore `includeFlags` and `excludeFlags`. |
|
||||
| [Profiling](docs/API.md#scriptprofile) | `scriptProfile` | `0` | `1` turns on CPU profiling for the `*CPUUsage` functions. The change starts after `/reload`. |
|
||||
| [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. |
|
||||
| [Localization](docs/API.md#breakuplargenumbers-cvar) | `breakUpLargeNumbers` | `1` | `1` puts a separator between each group of three digits in `BreakUpLargeNumbers`. `0` writes no separator. |
|
||||
| [Cooldown](docs/API.md#createframecooldown--name-parent-template) | `countdownForCooldowns` | `0` | `1` shows the time left as numbers on cooldown frames. |
|
||||
| `ScriptAnimationUtil` | `ShakeStrengthUI` | `1` | Scales how far `ScriptAnimationUtil.ShakeFrame` moves a frame. `0` turns the shake off. |
|
||||
| [NamePlate](docs/API.md#nameplate) | `nameplateNotSelectedAlpha` | `0.5` | Alpha of a non-target default nameplate, `0` to `1`. |
|
||||
| | `nameplateSelectedAlpha` | `1` | Alpha of the target's default nameplate, `0` to `1`. |
|
||||
| [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>
|
||||
|
||||
@@ -194,6 +270,9 @@ when launching with `-console`), not as Lua functions. See the
|
||||
| `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>
|
||||
|
||||
@@ -202,9 +281,15 @@ when launching with `-console`), not as Lua functions. See the
|
||||
|
||||
| Event | Payload |
|
||||
|-------|---------|
|
||||
| `ACTION_RANGE_CHECK_UPDATE` | `slot, isInRange, checksRange` (slots with `C_ActionBar.EnableActionRangeCheck` on) |
|
||||
| `ACTION_USABLE_CHANGED` | `changes` (a `{ slot, usable, noMana }` table for each slot that changed) |
|
||||
| `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` |
|
||||
| `DYNAMIC_GOSSIP_POI_UPDATED` | *(none)* |
|
||||
| `EQUIPMENT_SETS_CHANGED` | *(none)* |
|
||||
| `EQUIPMENT_SWAP_PENDING` | `setID` |
|
||||
| `EQUIPMENT_SWAP_FINISHED` | `success, setID` |
|
||||
@@ -212,6 +297,8 @@ when launching with `-console`), not as Lua functions. See the
|
||||
| `GLOBAL_MOUSE_DOWN` | `button` |
|
||||
| `GLOBAL_MOUSE_UP` | `button` |
|
||||
| `HEARTHSTONE_BOUND` | *(none)* |
|
||||
| `INCOMING_RESURRECT_CHANGED` | `unitTarget` |
|
||||
| `INVENTORY_SEARCH_UPDATE` | *(none)* |
|
||||
| `ITEM_DATA_LOAD_RESULT` | `itemID, success` |
|
||||
| `LEARNED_SPELL_IN_SKILL_LINE` | `spellID, skillLineIndex, isGuildPerkSpell` |
|
||||
| `LOOT_HISTORY_ROLL_CHANGED` | `itemIndex, playerIndex` |
|
||||
@@ -219,24 +306,44 @@ 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_MOUNT_DISPLAY_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_QUERY_COMPLETE` | *(none)* (Turtle WoW only) |
|
||||
| `QUEST_REMOVED` | `questID` |
|
||||
| `QUEST_TURNED_IN` | `questID, xpReward, moneyReward` |
|
||||
| `SELF_RES_SPELL_CHANGED` | *(none)* |
|
||||
| `SOUNDKIT_FINISHED` | `soundHandle` (only for sounds played with `runFinishCallback`) |
|
||||
| `SPELL_ACTIVATION_OVERLAY_SHOW` | `spellID, texture, locationType, scale, r, g, b` ([details](docs/API.md#spell_activation_overlay_show--spell_activation_overlay_hide-events)) |
|
||||
| `SPELL_ACTIVATION_OVERLAY_HIDE` | `spellID` (`nil` hides every alert) |
|
||||
| `SPELL_ACTIVATION_OVERLAY_GLOW_SHOW` | `spellID` ([details](docs/API.md#spell_activation_overlay_glow_show--spell_activation_overlay_glow_hide-events)) |
|
||||
| `SPELL_ACTIVATION_OVERLAY_GLOW_HIDE` | `spellID` |
|
||||
| `UI_SCALE_CHANGED` | *(none)* |
|
||||
| `UNIT_AREA_CHANGED` | `unitTarget` |
|
||||
| `UNIT_AURA_DELTA` | `unitTarget, updateInfo` (the instance IDs of the auras added, updated, and removed) |
|
||||
| `UNIT_CONNECTION` | `unitTarget, isConnected` |
|
||||
| `UNIT_DISTANCE_CHECK_UPDATE` | `unitTarget, isInDistance` |
|
||||
| `UNIT_IN_RANGE_UPDATE` | `unitTarget, isInRange` |
|
||||
| `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` |
|
||||
@@ -250,6 +357,14 @@ 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` |
|
||||
| `UNIT_MAXPOWER` | `unitTarget, powerType` |
|
||||
| `UNIT_POWER_FREQUENT` | `unitTarget, powerType` |
|
||||
| `UNIT_POWER_UPDATE` | `unitTarget, powerType` |
|
||||
| `UNIT_SPELL_HASTE` | `unitTarget` |
|
||||
| `UNIT_TARGET` | `unitTarget` |
|
||||
| `UNIT_TARGETABLE_CHANGED` | `unitTarget` |
|
||||
| `UPDATE_INVENTORY_DURABILITY` | *(none)* |
|
||||
| `UPDATE_SHAPESHIFT_FORM` | *(none)* |
|
||||
| `USER_WAYPOINT_UPDATED` | *(none)* |
|
||||
@@ -257,6 +372,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>
|
||||
|
||||
@@ -277,17 +394,24 @@ 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) |
|
||||
| Screen location type | `Enum.ScreenLocationType.{Center,Left,Right,Top,Bottom,TopLeft,TopRight,LeftOutside,RightOutside,LeftRight,TopBottom,LeftRightOutside}` (0–11) |
|
||||
| Self-resurrect option type | `Enum.SelfResurrectOptionType.{Spell,Item}` (0–1) |
|
||||
| Autocomplete entry flag | `Enum.AutoCompleteEntryFlag.{InGroup,InGuild,Friend,Bnet,InteractedWith,Online,InAOI,AccountCharacter,RecentPlayer}` (bits 1–256) |
|
||||
| Autocomplete priority | `Enum.AutoCompletePriority.{Other,Interacted,InGroup,Guild,Friend,AccountCharacter,AccountCharacterSameRealm}` (0–6) |
|
||||
|
||||
</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>
|
||||
|
||||
@@ -330,24 +454,31 @@ Download the prebuilt `ClassicAPI.dll` from the
|
||||
3. Add `ClassicAPI.dll` to `dlls.txt`.
|
||||
4. Launch the game with `VanillaFixes.exe`.
|
||||
|
||||
The bundled `!!!ClassicAPI` addon ships *inside* the DLL — no separate
|
||||
addon download or install step needed.
|
||||
The `!!!ClassicAPI`, `ClassicAPI_DebugTools` and `ClassicAPI_EventTrace`
|
||||
addons are *inside* the DLL. You do not download or install them. The
|
||||
`src/embed/AddOns/` folder in this repository is source code for the DLL.
|
||||
Do not copy it into your game.
|
||||
|
||||
## Bundled addon: !!!ClassicAPI
|
||||
|
||||
The Lua-side companion library lives in
|
||||
[`AddOns/!!!ClassicAPI/`](AddOns/!!!ClassicAPI/). It's a 1.12.1 /
|
||||
[`src/embed/AddOns/!!!ClassicAPI/`](src/embed/AddOns/!!!ClassicAPI/). It's a 1.12.1 /
|
||||
Lua 5.0 backport of the modern Blizzard helpers that aren't engine
|
||||
functions but that consumer code still expects to find as globals —
|
||||
`CallbackRegistryMixin`, `EventRegistry`, `ColorMixin` + `CreateColor`,
|
||||
`Item` / `ItemLocation`, `MathUtil`(`Lerp` / `Clamp` / `CreateCounter`),
|
||||
`TableUtil` (`tCompare`, `MergeTable`, `SafePack`, etc.), and `EventUtil`
|
||||
(`ContinueOnAddOnLoaded` and more). It also holds the conditional slash
|
||||
`TableUtil` (`tCompare`, `MergeTable`, `SafePack`, etc.), `EventUtil`
|
||||
(`ContinueOnAddOnLoaded` and more), `FormattingUtil` (`GetMoneyString`,
|
||||
`FormatLargeNumber` and more), `FrameUtil`, `DataProvider`, `CircularBuffer`,
|
||||
`EasingUtil`, `ScriptAnimationUtil`, `Interpolator`, `EnumUtil`, `StringUtil`, `AnchorUtil`,
|
||||
`GridLayoutUtil`, and the layout frame templates (`VerticalLayoutFrame`,
|
||||
`HorizontalLayoutFrame`, `ResizeLayoutFrame`, `GridLayoutFrame`,
|
||||
`StaticGridLayoutFrame`). It also holds the conditional slash
|
||||
commands and `SecureCmdOptionParse`, the parser that reads `[conditions]`
|
||||
and `@unit` for them.
|
||||
|
||||
**You don't have to install the addon manually** — the DLL embeds
|
||||
the contents of [`AddOns/!!!ClassicAPI/`](AddOns/!!!ClassicAPI/) and
|
||||
the contents of [`src/embed/AddOns/!!!ClassicAPI/`](src/embed/AddOns/!!!ClassicAPI/) and
|
||||
registers them with the engine as a synthetic addon on startup, so
|
||||
the library is always available when the DLL is loaded. It fires
|
||||
`ADDON_LOADED`, supports `SavedVariables`, and is resolvable by name —
|
||||
@@ -364,44 +495,47 @@ can't be switched off. Being hidden means it's omitted from the
|
||||
index-based `GetNumAddOns()` / `GetAddOnInfo(i)` enumeration, but every
|
||||
by-name lookup and dependency reference still resolves normally.
|
||||
|
||||
If you drop the folder into your `Interface/AddOns/` directory, **that
|
||||
copy's files win** — the DLL's embedded version only serves files when
|
||||
the engine's normal scan doesn't already have a newer entry under that
|
||||
name. Useful for editing the Lua locally without rebuilding the DLL.
|
||||
The hidden + force-enabled treatment applies either way (it's keyed to
|
||||
the addon name, not to which copy serves the files), so the local copy
|
||||
is also absent from the AddOns list. The dispatch is transparent:
|
||||
addons consuming `Mixin`, `ColorMixin`, `TableUtil`, etc. behave
|
||||
identically in both cases.
|
||||
For development, you can put a copy of the addon folder in
|
||||
`Interface/AddOns/` and add an empty `.classicapi-dev` file to it. The
|
||||
game then reads the Lua files from that copy, so you can edit them
|
||||
without a DLL rebuild. Without this file, the game uses the copy with the
|
||||
newer `## Version:`. The copy is hidden and always enabled, the same as
|
||||
the embedded addon.
|
||||
|
||||
## Bundled addon: DebugTools
|
||||
## Lua errors
|
||||
|
||||
A 1.12.1 / Lua 5.0 backport of Blizzard's `Blizzard_DebugTools` addon
|
||||
lives in [`AddOns/DebugTools/`](AddOns/DebugTools/).
|
||||
It's an independent addon — it doesn't use anything ClassicAPI adds, and
|
||||
ClassicAPI works fine without it. It's bundled here because it's the
|
||||
natural companion for testing and debugging anything written against the
|
||||
1.12 Lua surface (with or without the ClassicAPI extensions).
|
||||
ClassicAPI replaces the game's Lua error box with a Lua error window. The
|
||||
window opens when an error occurs. It shows the message, the time, the count,
|
||||
the stack and the local variables of each error. You can select and copy the
|
||||
text. The arrow buttons show the previous and the next error. The
|
||||
**Reload UI** button reloads the interface.
|
||||
|
||||
Slash commands provided:
|
||||
If you use `!BugGrabber` (with BugSack), BugGrabber gets the errors and the
|
||||
window does not open. If an addon sets its own error handler, the window also
|
||||
does not open.
|
||||
|
||||
| Command | Purpose |
|
||||
|---------|---------|
|
||||
| `/dump <expr>` | Pretty-print any Lua value, including tables and multi-return tuples. The right tool for inspecting return values from `GetSpellInfo`, `C_Item.GetItemInfoInstant`, etc. |
|
||||
| `/etrace` | Event tracer window. `/etrace start`, `/etrace stop`, `/etrace add EVENT`, etc. |
|
||||
| `/framestack` (or `/fstack`) | Tooltip showing the frame hierarchy under the mouse cursor. |
|
||||
| `/luaerrors` (or `/scripterrors`) | Lua error display window. |
|
||||
| `/luaerrors` (or `/scripterrors`) | Opens or closes the Lua error window. |
|
||||
| `/luaerrors clear` | Removes all errors from the window. |
|
||||
|
||||
Lua globals provided (backports of Blizzard helpers):
|
||||
## Debug tools
|
||||
|
||||
| Global | Purpose |
|
||||
|--------|---------|
|
||||
| `print(...)` | Backport of Blizzard's `print` — concats varargs with `" "` and pushes to `DEFAULT_CHAT_FRAME`. Routes through `setprinthandler`'s handler; falls back via `geterrorhandler` if the handler errors. |
|
||||
| `setprinthandler(func)` / `getprinthandler()` | Install / query a custom print handler. Useful for redirecting print output in tests. |
|
||||
| `tostringall(...)` | Apply `tostring()` to every vararg, preserving the count. Lua 5.0-compatible (uses `arg.n` since `select` doesn't exist in 5.0). |
|
||||
ClassicAPI contains backports of two Blizzard addons: `Blizzard_DebugTools`,
|
||||
with the name `ClassicAPI_DebugTools`, and `Blizzard_EventTrace`, with the
|
||||
name `ClassicAPI_EventTrace`. The DLL contains these addons, so you do not
|
||||
install them. They are not in the AddOns list, and you cannot disable them.
|
||||
|
||||
To install: copy [`AddOns/DebugTools/`](AddOns/DebugTools/) into your
|
||||
`Interface/AddOns/` directory like any other addon.
|
||||
The slash commands are always available. Each addon loads the first time
|
||||
that you use one of its commands:
|
||||
|
||||
| Command | Purpose |
|
||||
|---------|---------|
|
||||
| `/dump <expr>` | Shows a Lua value in the chat frame. It shows tables and all return values. Use it to examine the return values of `GetSpellInfo`, `C_Item.GetItemInfoInstant`, and other functions. |
|
||||
| `/etrace` (or `/eventtrace`) | Opens or closes the event trace window. The window logs each event with its time and its arguments. Move the mouse over an event to see its arguments, and the contents of each table argument. You can search the log, hide events with the filter, and pause the log. `/etrace mark <text>` adds a line of text to the log. |
|
||||
| `/framestack [showHidden [showRegions]]` (or `/fstack`) | Shows a tooltip with a list of the frames under the cursor. A `-->` mark shows one frame, with its anchors and the file and line that made it. Left Alt and Right Alt move the mark. Ctrl opens the marked frame in the table inspector. Shift shows its texture files. The tooltip also shows the addon that made the marked frame. When `scriptProfile` is `1`, it shows the CPU time of the frame scripts. |
|
||||
| `/tinspect [expr]` (or `/tins`) | Opens a table inspector on the result of `expr`. With no table, it opens on the frame under the cursor. The window shows the anchors and the fields of the table, grouped by type. You can edit numbers, strings and booleans, filter the lines, and open a child table or frame. |
|
||||
| `/profiler` (or `/prof`) | Opens the profiler. The profiler shows the Lua memory, the allocations and the CPU time of each addon, frame, event and global function. `/profiler widget` shows a small window with the Lua memory, the frame rate and the addons that use the most. `/profiler reset` sets the counters to zero. CPU times need `scriptProfile` `1`. `/profiler profile on` sets it and reloads the UI. |
|
||||
|
||||
## Building
|
||||
|
||||
|
||||
@@ -5,23 +5,25 @@ Candidates for new DLL functions, prioritized. All are things the
|
||||
addon polyfills badly, hackily, or not at all, and where engine access is the
|
||||
right answer.
|
||||
|
||||
## ~~1. `C_QuestLog.IsQuestFlaggedCompleted(questID)`~~ — NOT FEASIBLE in 1.12
|
||||
## ~~1. `C_QuestLog.IsQuestFlaggedCompleted(questID)`~~ — DONE (Turtle-lineage servers)
|
||||
|
||||
The original TODO note ("engine maintains a completed-quests bitfield in
|
||||
client memory") was based on 3.3.5 / WotLK semantics. Vanilla 1.12 has no
|
||||
equivalent: neither `QueryQuestsCompleted` nor `GetQuestsCompleted`
|
||||
exists, the protocol has no `CMSG_QUERY_QUESTS_COMPLETED`, and the
|
||||
client doesn't track historical completions. The polyfill at
|
||||
`Util/C_QuestLog.lua:5-8` works on Frostmourne (3.3.5a) where those
|
||||
functions exist; on the 1.12 Octo client they're absent.
|
||||
Stock 1.12 has no completed-quests query and keeps no quest history, so
|
||||
this exists only where the server offers the list another way. Turtle WoW
|
||||
and its forks answer the player command `.queststatuses` with `TWQUEST`
|
||||
guild addon messages from the player, split at 2000 characters, the last
|
||||
message always shorter (probed: 2003, 2004, 0) - an exact end marker.
|
||||
|
||||
Servers that want to expose this in 1.12 (notably Turtle WoW) do it
|
||||
via the `CHAT_MSG_ADDON` channel — the addon sends `.queststatus` over
|
||||
guild/whisper chat and the server replies with addon-channel messages
|
||||
the addon parses. Fundamentally async, server-specific, and requires
|
||||
SavedVariables-style persistence across sessions to amortize the
|
||||
round-trip — all of which belong on the Lua side, not in this DLL.
|
||||
There's nothing the DLL can usefully add here.
|
||||
[src/quest/Completed.cpp](src/quest/Completed.cpp) does it all in the DLL,
|
||||
Turtle clients only: it sends the request itself (on
|
||||
SMSG_LOGIN_VERIFY_WORLD, after each turn-in, and from
|
||||
`QueryQuestsCompleted`), reads every answer at the packet funnel (sender
|
||||
must be the player), and keeps the live list behind `GetQuestsCompleted`,
|
||||
`C_QuestLog.IsQuestFlaggedCompleted` and
|
||||
`C_QuestLog.GetAllCompletedQuestIDs`; `QUEST_QUERY_COMPLETE` fires per
|
||||
answer. No disk cache: the first answer lands one round trip after
|
||||
PLAYER_ENTERING_WORLD, because the server sends the player object (which
|
||||
fires PLAYER_LOGIN) before it reads any request. Replaces the closed Lua
|
||||
collector of PR #86.
|
||||
|
||||
## ~~2. `C_Spell.GetSpellDescription(spellID)`~~ — DONE
|
||||
|
||||
@@ -147,7 +149,7 @@ on a frame timer" goal landed as the request/event pair below:
|
||||
cache (or synchronously if it was already loaded).
|
||||
|
||||
Together those replace the polyfill's 180-second polling frame
|
||||
(`ItemEventListener` in `Util/ItemUtil.lua:254-372`) — addons can now
|
||||
(`ItemEventListener`, now in `Util/AsyncCallbackSystem.lua`) — addons can now
|
||||
fire `RequestLoadItemDataByID(id)` and listen for
|
||||
`ITEM_DATA_LOAD_RESULT` instead.
|
||||
|
||||
@@ -455,8 +457,7 @@ the other spell registrations in [src/spell/Info.cpp](src/spell/Info.cpp).
|
||||
## ~~26. `C_Item.IsEquippableItem(item)`~~ — DONE
|
||||
|
||||
Cache-record read of `m_inventoryType` at `OFF_ITEMSTATS_INVENTORY_TYPE`.
|
||||
Non-zero = equippable. Lives in `item/Equipment.cpp` alongside
|
||||
`OffhandHasWeapon` (which uses the same field) and `IsEquippedItem`.
|
||||
Non-zero = equippable. Lives in `item/Equipment.cpp` alongside `IsEquippedItem`.
|
||||
Synchronous; returns `false` on cache miss without firing a load.
|
||||
Namespaced under `C_Item` to match Classic Era 1.15.x.
|
||||
|
||||
@@ -951,88 +952,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
|
||||
|
||||
@@ -1538,20 +1466,12 @@ it on a struct pointer to scan layouts, or from Lua via
|
||||
`_classicapi_HexDump(label, addr, len)` to inspect engine
|
||||
globals without a per-investigation probe module.
|
||||
|
||||
## ~~56. `OffhandHasWeapon()`~~ — DONE
|
||||
## ~~56. `OffhandHasWeapon()`~~ — DROPPED
|
||||
|
||||
Shipped as `src/item/Equipment.cpp`. Resolves the off-hand
|
||||
equipment slot (slot 17) via `Item::Location::ResolveEquipmentSlot`,
|
||||
reads the cached `ItemStats_C` record's `m_inventoryType` at
|
||||
`+0x2C`, and returns true iff it's `INVTYPE_WEAPON` (13) or
|
||||
`INVTYPE_WEAPONOFFHAND` (22). Shields, holdables (tomes/orbs),
|
||||
empty slots, and uncached items all return false.
|
||||
|
||||
No async load is fired — modern API behavior matches; if the
|
||||
off-hand item isn't cached the function silently returns false
|
||||
until something else warms the cache. Typically only matters on
|
||||
first login before the player's own gear is in the cache, which
|
||||
in practice is loaded eagerly anyway.
|
||||
Vanilla already ships it (`0x004C9570`, same body as 3.3.5/4.3.4:
|
||||
off-hand slot item class 2 → `1`, else `nil`). Our override returned
|
||||
booleans and tested inventory type instead; removed so the engine's
|
||||
own global stands.
|
||||
|
||||
## 57. `IsFlying()` — TESTED, DROPPED
|
||||
|
||||
@@ -1740,7 +1660,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:
|
||||
@@ -2018,8 +1945,8 @@ current item/spell/unit. Approach:
|
||||
4. Each match reveals the offset for that state field.
|
||||
|
||||
Once located, `GetItem()`, `GetSpell()`, `GetUnit()` are trivial
|
||||
deref+push. Implementation roughly the same as `OffhandHasWeapon`
|
||||
or `IsEquippedItem` patterns.
|
||||
deref+push. Implementation roughly the same as the `IsEquippedItem`
|
||||
pattern.
|
||||
|
||||
### Risks
|
||||
|
||||
@@ -3833,9 +3760,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`.
|
||||
|
||||
@@ -3883,7 +3811,7 @@ of descriptors feeds the in-game browser, a page generator, and a drift check.
|
||||
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
|
||||
- `src/embed/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.
|
||||
@@ -3978,3 +3906,232 @@ 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`.
|
||||
- **DONE** (`src/scrollingmessageframe/`, retail's shapes).
|
||||
**ScrollingMessageFrame** `GetMessageInfo`, `SetScrollOffset` (1.12's
|
||||
`SetScrollFromBottom`, 0x00793070, under its later name, clamped as
|
||||
retail), `GetScrollOffset`, `GetMaxScrollRange`, `ScrollByAmount`,
|
||||
`AddOnDisplayRefreshedCallback`, `SetInsertMode` / `GetInsertMode` (TOP
|
||||
through a redirect of the layout's one line-anchor call, 0x00788975),
|
||||
`BackFillMessage` (writes 4.3.4's addToTop slot of the ring, the free one
|
||||
before the oldest; a full frame drops it, as retail's CircularBuffer
|
||||
`PushBack` does — 4.3.4 overwrites the oldest there).
|
||||
- **DONE** (`src/scrollingmessageframe/MessageInfo.cpp`).
|
||||
**ScrollingMessageFrame** `RemoveMessagesByPredicate` (retail's shape; it
|
||||
covers 4.3.4's `RemoveMessagesByAccessID` / `RemoveMessagesByExtraData`,
|
||||
whose int fields our retail-shaped records do not have). The compaction
|
||||
is 4.3.4's `RemoveLines` loop over 1.12's ring, then the engine's own
|
||||
layout (0x00788750) at the kept scroll offset and re-arm (0x00788B80),
|
||||
or Clear (0x007882B0) when nothing is kept.
|
||||
- **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,209 @@
|
||||
# embed_resources.cmake — embed the addons, the bindings XML and the
|
||||
# built-in textures as Win32 RCDATA resources.
|
||||
#
|
||||
# Runs at configure time. It writes two files into OUT_DIR:
|
||||
#
|
||||
# embedded.rc one `<id> RCDATA "<path>"` line per pack; rc.exe
|
||||
# reads each gzipped pack 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::Manifest {
|
||||
# constexpr const char *kAddons[] = { ... }; // in ADDONS order
|
||||
# constexpr size_t kAddonCount = ...;
|
||||
# struct File { const char *path; int resourceId; int index; };
|
||||
# constexpr File kFiles[] = { ... };
|
||||
# constexpr size_t kFileCount = ...;
|
||||
# }
|
||||
# namespace Texture::Builtin::Manifest {
|
||||
# struct File { const char *path; int resourceId; int index; };
|
||||
# constexpr File kFiles[] = { ... };
|
||||
# constexpr size_t kFileCount = ...;
|
||||
# }
|
||||
#
|
||||
# Each resource is a pack: one gzip stream of several files, which
|
||||
# pack_files.cmake joins at build time into `OUT_DIR/embed/<name>.pack.gz`.
|
||||
# Resource 1 is the bindings XML, a pack of one; then each addon is one
|
||||
# pack, in ADDONS order; then the textures, one pack. A pack compresses each
|
||||
# file against the files before it, so the addon text packs to about 22% of
|
||||
# its size, against 27% for one gzip stream per file. The DLL inflates a
|
||||
# whole pack with the engine's zlib on first use (src/embed/Resource.cpp),
|
||||
# so the load-on-demand addon costs nothing until it loads.
|
||||
#
|
||||
# Addon file paths are relative to ADDONS_ROOT, in backslash form
|
||||
# (`!!!ClassicAPI\Util\Print.lua`) — the suffix the engine builds after
|
||||
# `Interface\AddOns\`. Texture paths are relative to TEXTURES_ROOT, where
|
||||
# each file sits at its game path (`Interface\Cursor\Quest.blp`), for
|
||||
# src/texture/Builtin.cpp. The DLL compares both ignoring case. A file's
|
||||
# index is its place in its pack, which is in path order.
|
||||
#
|
||||
# Each addon's `.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 tocs stay `DEV`. The developer marker `.classicapi-dev` is
|
||||
# never embedded: it must reflect on-disk presence only (see
|
||||
# DiskHasDevMarker in src/addons/Embedded.cpp).
|
||||
#
|
||||
# Rebuild triggers: adding or removing a file reconfigures through the
|
||||
# CONFIGURE_DEPENDS glob; editing a toc reconfigures through
|
||||
# CMAKE_CONFIGURE_DEPENDS; editing any other file re-packs its addon through
|
||||
# the pack's custom command, which recompiles the .rc through its
|
||||
# OBJECT_DEPENDS.
|
||||
#
|
||||
# Usage:
|
||||
# embed_resources(TARGET <t> ADDONS_ROOT <dir> ADDONS <folder names...>
|
||||
# ADDON_VERSION <v> BINDINGS_XML <file>
|
||||
# TEXTURES_ROOT <dir> OUT_DIR <dir>)
|
||||
|
||||
set(_EMBED_PACK_SCRIPT "${CMAKE_CURRENT_LIST_DIR}/pack_files.cmake")
|
||||
|
||||
# Add the build-time command that packs `ARGN` (absolute paths, in pack
|
||||
# order) into `<out_dir>/embed/<name>.pack.gz`, and set `gz` in the caller
|
||||
# to that path. The paths reach the script through a generated list file:
|
||||
# an addon's paths are too long for one command line.
|
||||
function(_embed_pack out_dir name)
|
||||
set(pack "${out_dir}/embed/${name}.pack")
|
||||
set(list "set(FILES\n")
|
||||
foreach(path ${ARGN})
|
||||
string(APPEND list " [==[${path}]==]\n")
|
||||
endforeach()
|
||||
string(APPEND list ")\n")
|
||||
_embed_write_if_changed("${pack}.cmake" "${list}")
|
||||
add_custom_command(
|
||||
OUTPUT "${pack}.gz"
|
||||
COMMAND "${CMAKE_COMMAND}" "-DLIST=${pack}.cmake" "-DOUT=${pack}.gz"
|
||||
-P "${_EMBED_PACK_SCRIPT}"
|
||||
DEPENDS ${ARGN} "${pack}.cmake" "${_EMBED_PACK_SCRIPT}"
|
||||
VERBATIM)
|
||||
set(gz "${pack}.gz" PARENT_SCOPE)
|
||||
endfunction()
|
||||
|
||||
# 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;ADDONS_ROOT;ADDON_VERSION;BINDINGS_XML;TEXTURES_ROOT;OUT_DIR"
|
||||
"ADDONS" ${ARGN})
|
||||
|
||||
set(rc "// Generated by cmake/embed_resources.cmake - do not edit.\n\n")
|
||||
set(addon_names "")
|
||||
set(manifest "")
|
||||
set(inputs "")
|
||||
|
||||
set(bindings_id 1)
|
||||
_embed_pack("${E_OUT_DIR}" "Bindings.xml" "${E_BINDINGS_XML}")
|
||||
string(APPEND rc "${bindings_id} RCDATA \"${gz}\"\n")
|
||||
list(APPEND inputs "${gz}")
|
||||
|
||||
set(id 2)
|
||||
foreach(addon ${E_ADDONS})
|
||||
string(APPEND addon_names " \"${addon}\",\n")
|
||||
file(GLOB_RECURSE files CONFIGURE_DEPENDS RELATIVE
|
||||
"${E_ADDONS_ROOT}" "${E_ADDONS_ROOT}/${addon}/*")
|
||||
list(FILTER files EXCLUDE REGEX "(^|/)\\.classicapi-dev$")
|
||||
list(SORT files) # deterministic indexes
|
||||
set(paths "")
|
||||
set(index 0)
|
||||
foreach(rel ${files})
|
||||
set(abs "${E_ADDONS_ROOT}/${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()
|
||||
list(APPEND paths "${abs}")
|
||||
string(REPLACE "/" "\\\\" rel_bs "${rel}")
|
||||
string(APPEND manifest " { \"${rel_bs}\", ${id}, ${index} },\n")
|
||||
math(EXPR index "${index} + 1")
|
||||
endforeach()
|
||||
_embed_pack("${E_OUT_DIR}" "${addon}" ${paths})
|
||||
string(APPEND rc "${id} RCDATA \"${gz}\"\n")
|
||||
list(APPEND inputs "${gz}")
|
||||
math(EXPR id "${id} + 1")
|
||||
endforeach()
|
||||
|
||||
file(GLOB_RECURSE textures CONFIGURE_DEPENDS RELATIVE
|
||||
"${E_TEXTURES_ROOT}" "${E_TEXTURES_ROOT}/*")
|
||||
list(SORT textures) # deterministic indexes
|
||||
set(texture_paths "")
|
||||
set(texture_manifest "")
|
||||
set(index 0)
|
||||
foreach(rel ${textures})
|
||||
list(APPEND texture_paths "${E_TEXTURES_ROOT}/${rel}")
|
||||
string(REPLACE "/" "\\\\" rel_bs "${rel}")
|
||||
string(APPEND texture_manifest " { \"${rel_bs}\", ${id}, ${index} },\n")
|
||||
math(EXPR index "${index} + 1")
|
||||
endforeach()
|
||||
_embed_pack("${E_OUT_DIR}" "Textures" ${texture_paths})
|
||||
string(APPEND rc "${id} RCDATA \"${gz}\"\n")
|
||||
list(APPEND inputs "${gz}")
|
||||
|
||||
_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 packs in embedded.rc, and each embedded file's
|
||||
// place in them. Load them through src/embed/Resource.h.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
|
||||
namespace Embed::Ids {
|
||||
constexpr int kBindingsXml = ${bindings_id}; // a pack of the one file
|
||||
} // namespace Embed::Ids
|
||||
|
||||
namespace Addons::Embedded::Manifest {
|
||||
|
||||
// Registration order: the first one registers, and so loads, first.
|
||||
constexpr const char *kAddons[] = {
|
||||
${addon_names}};
|
||||
|
||||
constexpr size_t kAddonCount = sizeof(kAddons) / sizeof(kAddons[0]);
|
||||
|
||||
struct File {
|
||||
const char *path;
|
||||
int resourceId; // its addon's pack
|
||||
int index; // its place in the pack
|
||||
};
|
||||
|
||||
constexpr File kFiles[] = {
|
||||
${manifest}};
|
||||
|
||||
constexpr size_t kFileCount = sizeof(kFiles) / sizeof(kFiles[0]);
|
||||
|
||||
} // namespace Addons::Embedded::Manifest
|
||||
|
||||
namespace Texture::Builtin::Manifest {
|
||||
|
||||
struct File {
|
||||
const char *path; // the game path
|
||||
int resourceId; // the textures' pack
|
||||
int index; // its place in the pack
|
||||
};
|
||||
|
||||
constexpr File kFiles[] = {
|
||||
${texture_manifest}};
|
||||
|
||||
constexpr size_t kFileCount = sizeof(kFiles) / sizeof(kFiles[0]);
|
||||
|
||||
} // namespace Texture::Builtin::Manifest
|
||||
")
|
||||
|
||||
add_custom_target(${E_TARGET}_embed DEPENDS ${inputs})
|
||||
add_dependencies(${E_TARGET} ${E_TARGET}_embed)
|
||||
target_sources(${E_TARGET} PRIVATE "${E_OUT_DIR}/embedded.rc")
|
||||
set_source_files_properties("${E_OUT_DIR}/embedded.rc" PROPERTIES
|
||||
OBJECT_DEPENDS "${inputs}")
|
||||
endfunction()
|
||||
@@ -0,0 +1,50 @@
|
||||
# pack_files.cmake — join files into one gzipped pack at build time, for
|
||||
# embed_resources.cmake.
|
||||
#
|
||||
# cmake -DLIST=<list.cmake> -DOUT=<pack.gz> -P pack_files.cmake
|
||||
#
|
||||
# LIST sets FILES to the paths to join, in order. The pack is one gzip
|
||||
# stream, so each file compresses against the files before it: the addon
|
||||
# text packs about 16% smaller than when each file is gzipped alone. Inside
|
||||
# the stream is an index, each file's size as a decimal line and then an
|
||||
# empty line, followed by the files' bytes in FILES order. The DLL splits
|
||||
# it in src/embed/Resource.cpp.
|
||||
|
||||
include("${LIST}")
|
||||
|
||||
set(index "")
|
||||
foreach(file IN LISTS FILES)
|
||||
file(SIZE "${file}" size)
|
||||
string(APPEND index "${size}\n")
|
||||
endforeach()
|
||||
# Not file(WRITE): on Windows it writes each \n as \r\n.
|
||||
file(CONFIGURE OUTPUT "${OUT}.index" CONTENT "${index}\n" @ONLY NEWLINE_STYLE UNIX)
|
||||
|
||||
# Join `ARGN` byte for byte into `out`.
|
||||
function(cat out)
|
||||
execute_process(COMMAND "${CMAKE_COMMAND}" -E cat ${ARGN}
|
||||
OUTPUT_FILE "${out}" RESULT_VARIABLE rc)
|
||||
if(NOT rc EQUAL 0)
|
||||
message(FATAL_ERROR "pack_files.cmake: cannot join into ${out}: ${rc}")
|
||||
endif()
|
||||
endfunction()
|
||||
|
||||
# `cmake -E cat` takes its files on the command line, which Windows limits
|
||||
# to 32767 characters: join in batches of 100, then join the batches.
|
||||
set(parts "${OUT}.index")
|
||||
list(LENGTH FILES count)
|
||||
set(first 0)
|
||||
while(first LESS count)
|
||||
list(SUBLIST FILES ${first} 100 batch)
|
||||
set(part "${OUT}.part${first}")
|
||||
cat("${part}" ${batch})
|
||||
list(APPEND parts "${part}")
|
||||
math(EXPR first "${first} + 100")
|
||||
endwhile()
|
||||
cat("${OUT}.raw" ${parts})
|
||||
|
||||
# The raw format holds the one file's bytes with no archive entry around
|
||||
# them, so OUT is a plain gzip stream.
|
||||
file(ARCHIVE_CREATE OUTPUT "${OUT}" PATHS "${OUT}.raw" FORMAT raw
|
||||
COMPRESSION GZip COMPRESSION_LEVEL 9)
|
||||
file(REMOVE ${parts} "${OUT}.raw")
|
||||
+10232
-2083
File diff suppressed because it is too large
Load Diff
+198
-135
@@ -27,24 +27,22 @@ The DLL hooks the engine's own text pipeline — no companion addon:
|
||||
pen is lazy and omits the last glyph's own advance, so a coin sat on its
|
||||
digits; the emitter now adds the true terminal advance from the engine's own
|
||||
glyph-advance helpers (`550cf5e`).
|
||||
- **Rendering** — the paint-pass co-hook `FUN_005c8fe0` walks the icon records
|
||||
and queues each to `Text::InlineTexturePool`, which places the region on the
|
||||
next frame tick (never mid-render).
|
||||
- **Chat has no one-frame lag** — a ScrollingMessageFrame re-`SetText`s every
|
||||
visible line on each new message, and the engine builds each line lazily at
|
||||
paint, so a line's icons would land one frame after its glyphs (glyphs draw
|
||||
synchronously; the icon regions are separate objects whose placement is only
|
||||
known once the line builds mid-paint, after the frame's texture pass already
|
||||
drew). A co-hook on the SMF display refresh (`FUN_00788750`, which runs
|
||||
pre-render from the frame's own methods) forces each icon-bearing line to
|
||||
resolve+build and applies its icon placement synchronously — before the frame
|
||||
draws — so icons move in lockstep with their text. It reuses the engine's own
|
||||
`Realize(0)` → `RebuildString` → ensure-built path and the same placement math
|
||||
the paint flush uses (`ComputePlacementsForNode`), so the later flush dedups to
|
||||
a no-op. Additive and best-effort: any line whose rect isn't resolvable in time
|
||||
falls back to the paint + tick pipeline (correct, one-frame lagged). A pure
|
||||
scroll or drag never lagged — the icons are anchored to the line and the engine
|
||||
moves them for free; only content changes on a reused line needed this.
|
||||
- **Rendering** — 4.3.4's `CSimpleEmbeddedTexture` model. Each icon is a
|
||||
pooled `CSimpleTexture` with no frame, anchored to its fontstring: it is in
|
||||
no draw layer, so the fontstring draws it. The fontstring's batch call
|
||||
(`FUN_FONTSTRING_EMIT` `0x00772E50`, 4.3.4's `CSimpleFontString::Draw` →
|
||||
`QueueTextures`) adds the icons right after its text, and only when the text
|
||||
went in, so an icon shows exactly when its line does — hidden, faded out, off
|
||||
screen, or scrolled off the top of a chat frame — in the same frame.
|
||||
- **No one-frame lag** — 4.3.4 sets the embedded textures up in `UpdateString`,
|
||||
right after it builds the string. The `RebuildString` co-hook does the same:
|
||||
a rebuild drops the fontstring's icons, lays the new node out now (the
|
||||
ensure-built call the paint makes) and applies the placements at once, so a
|
||||
string's icons draw with its text wherever it was rebuilt (a chat line laid
|
||||
out by its frame, a tooltip line, a rect change). The paint-pass co-hook
|
||||
`FUN_005c8fe0` still walks the icon records and queues them to
|
||||
`Text::InlineTexturePool` for the next frame tick: the backstop for a string
|
||||
whose placement can't be computed at rebuild time.
|
||||
- **Placement coordinates** — text pen space IS render-target pixels. The
|
||||
engine stores node positions NORMALIZED (fs-local anchor ÷
|
||||
`[0x832A44]`/`[0x832A48]` per axis, `FUN_0041ade0`), and the origin finalize
|
||||
@@ -69,30 +67,37 @@ 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, Ctrl+C
|
||||
drops icons (4.3.4's 0x1500 strip mask), and a multi-line box's caret,
|
||||
selection and click rows follow the lines a tall icon moves (below;
|
||||
4.3.4's own rows do not). 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
|
||||
@@ -100,10 +105,8 @@ Every fs-level measure path now counts icons: width (`FUN_00772890`), height
|
||||
refute that: the GameTooltip auto-size measures each WRAPPED SEGMENT of a
|
||||
wrap-enabled line through it, so icon-bearing wrapped tooltip lines
|
||||
undersized their tooltip until it was hooked too). The Lua control surface is
|
||||
two toggles: `_classicapi_InlineTexEnable` (the whole-feature kill switch; the
|
||||
SEH latch trips it on a flush fault) and `_classicapi_InlineTexEarly` (the
|
||||
SMF-refresh early apply above — on by default, toggle off to A/B the chat lag
|
||||
against the baseline paint+tick pipeline, which keeps running either way). The
|
||||
one toggle: `_classicapi_InlineTexEnable` (the whole-feature kill switch; the
|
||||
SEH latch trips it on a fault). The
|
||||
bring-up tune / stat / probe functions were removed (`5e5677b`, `6800a9a`).
|
||||
|
||||
## REMOVED (bring-up record) — the raw-GxU-quad rendering primitive
|
||||
@@ -171,7 +174,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 +199,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 +226,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 +273,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
|
||||
|
||||
@@ -299,7 +375,7 @@ funnel for exactly 4 callers:
|
||||
|
||||
- `Script_GetStringWidth` (0x0079E510)
|
||||
- the GameTooltip auto-size (0x00530640)
|
||||
- the editbox caret positioner (0x0077DE70)
|
||||
- the editbox selection-piece placer (0x0077DE70, a whole last line's width)
|
||||
- the layout effective-width vmethod (`FUN_00772930` = fs+0x24 vtbl +0x1C,
|
||||
which feeds auto-width fontstring layout)
|
||||
|
||||
@@ -308,13 +384,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 +427,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 +481,81 @@ 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.
|
||||
- **Rows (multi-line)** — `PlaceCaret` (`0x77da80`), `PlaceSelectionPiece`
|
||||
(`0x77de70`) and `GetIndexAtPoint` (`0x77d0d0`) step rows of one height
|
||||
(font height + spacing, pixel-aligned), as 4.3.4's `UpdateVisibleCursor`,
|
||||
`UpdateHighlightArea` and `ConvertCoordinateToIndex` do — while the render
|
||||
moves a tall-icon line and every line after it down by the overflow
|
||||
(`InitializeText`; the emitter co-hook) and the box grows to match (the
|
||||
string-height co-hook). 4.3.4 has that fault too; `EditBox::IconRows`
|
||||
(`src/editbox/IconRows.cpp`) gives each placer the render's move, from
|
||||
`Text::InlineTexture::LineIconShift` over the box's own line table: the
|
||||
click's y is moved onto the uniform row of the icon-aware row under it
|
||||
before the engine maps it; a selection piece is re-anchored after the
|
||||
engine placed it, with the engine's own x; the caret likewise, then
|
||||
`OnCursorChanged` fired once with the moved y through
|
||||
`FUN_FRAME_RUN_SCRIPT_VARIADIC` exactly as `PlaceCaret` fires it (its own
|
||||
fire muted for the call by emptying the slot), so
|
||||
`ScrollingEditBoxMixin:ScrollCursorIntoView` scrolls to the real caret.
|
||||
- **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 +609,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
|
||||
|
||||
|
||||
+3
-3
@@ -178,9 +178,9 @@ behaviour the comment describes (`push 0; mov edx, 1; mov ecx, L`) is
|
||||
| `0x006F4450` | `lua_next` | fastcall | calls `luaH_next` at `0x006FA2A0` | ★ |
|
||||
| `0x006F44E0` | `lua_concat` | fastcall | calls `luaV_concat` at `0x006F84D0` | ★ |
|
||||
| `0x006F4560` | `lua_newuserdata` | fastcall | tag 7; calls `luaS_newudata` at `0x006F9E30` | ★ |
|
||||
| `0x006F45B0` | `lua_getupvalue` | fastcall | reads upvalue from C closure | ◦ |
|
||||
| `0x006F4660` | `lua_setupvalue` | fastcall | | ◦ |
|
||||
| `0x006F46E0` | *internal upvalue helper*| | shared by get/set above | ◦ |
|
||||
| `0x006F45B0` | `lua_pushupvalues` | fastcall | pushes the running C closure's upvalues, returns how many | ★ |
|
||||
| `0x006F4660` | `lua_getupvalue` | fastcall | `(L, funcindex, n)`: pushes upvalue n, returns its name or null | ★ |
|
||||
| `0x006F46E0` | `aux_upvalue` | | finds upvalue n of a function, returns its name | ★ |
|
||||
|
||||
## Auxiliary library (`luaL_*`)
|
||||
|
||||
|
||||
+1
Submodule external/unordered_dense added at ddd49116e6
@@ -14,6 +14,7 @@
|
||||
#include "Common.h"
|
||||
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <windows.h>
|
||||
|
||||
namespace Common {
|
||||
@@ -31,6 +32,65 @@ 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 RedirectJcc(uintptr_t site, uintptr_t expected, const void *target) {
|
||||
const auto *code = reinterpret_cast<const uint8_t *>(site);
|
||||
if (code[0] != 0x0F || (code[1] & 0xF0) != 0x80)
|
||||
return false;
|
||||
const auto dest = [site](int32_t rel) { return site + 6 + static_cast<uintptr_t>(rel); };
|
||||
int32_t rel = 0;
|
||||
std::memcpy(&rel, code + 2, sizeof rel);
|
||||
const uintptr_t to = reinterpret_cast<uintptr_t>(target);
|
||||
if (dest(rel) == to)
|
||||
return true;
|
||||
if (dest(rel) != expected)
|
||||
return false;
|
||||
rel = static_cast<int32_t>(to - (site + 6));
|
||||
return PatchBytes(reinterpret_cast<uint8_t *>(site) + 2, &rel, sizeof rel);
|
||||
}
|
||||
|
||||
bool RedirectSlot(uintptr_t slot, uintptr_t expected, const void *target) {
|
||||
uintptr_t current = 0;
|
||||
std::memcpy(¤t, reinterpret_cast<const void *>(slot), sizeof current);
|
||||
const uintptr_t to = reinterpret_cast<uintptr_t>(target);
|
||||
if (current == to)
|
||||
return true;
|
||||
if (current != expected)
|
||||
return false;
|
||||
return PatchBytes(reinterpret_cast<void *>(slot), &to, sizeof to);
|
||||
}
|
||||
|
||||
bool ReplaceWithCall(uintptr_t site, const uint8_t *original, size_t len, const void *target) {
|
||||
uint8_t code[64];
|
||||
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 +100,33 @@ 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
char FoldPathChar(char c) {
|
||||
if (c == '/')
|
||||
return '\\';
|
||||
if (c >= 'A' && c <= 'Z')
|
||||
return static_cast<char>(c + ('a' - 'A'));
|
||||
return c;
|
||||
}
|
||||
|
||||
bool SamePath(const char *a, const char *b) {
|
||||
for (; FoldPathChar(*a) == FoldPathChar(*b); ++a, ++b) {
|
||||
if (*a == '\0')
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace Common
|
||||
|
||||
@@ -12,15 +12,48 @@
|
||||
// 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);
|
||||
|
||||
// RedirectCall for a `0F 8x rel32` conditional jump: points the taken branch
|
||||
// at `site` to `target` when it still reaches `expected`. Same contract.
|
||||
bool RedirectJcc(uintptr_t site, uintptr_t expected, const void *target);
|
||||
|
||||
// RedirectCall for a function-pointer slot (a vtable entry): points the slot
|
||||
// at `slot` to `target` when it still holds `expected`. Same contract.
|
||||
bool RedirectSlot(uintptr_t slot, uintptr_t expected, const void *target);
|
||||
|
||||
// Writes `call target` plus NOP padding over the `len` bytes (5 to 64) of
|
||||
// code at `site` when they still hold `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);
|
||||
|
||||
// `c` as game paths compare it: '/' as '\', and A-Z as a-z.
|
||||
char FoldPathChar(char c);
|
||||
|
||||
// Whether `a` and `b` are the same game path: equal after FoldPathChar, so
|
||||
// any case and either slash.
|
||||
bool SamePath(const char *a, const char *b);
|
||||
|
||||
} // namespace Common
|
||||
|
||||
+28
-22
@@ -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"
|
||||
@@ -79,15 +80,16 @@ static void __stdcall LoadGlueScriptFunctions_h() {
|
||||
}
|
||||
|
||||
// Every Lua-side `frame:RegisterEvent(...)` is a chance to claim a slot
|
||||
// for any custom event still waiting. By this point the engine's table
|
||||
// is fully populated and SuperWoWhook / other DLLs have done their
|
||||
// post-rebuild writes, so the table state is settled and our backwards
|
||||
// walk finds genuine NULL slots near the tail.
|
||||
// for any custom event still waiting. By the first FrameXML registration
|
||||
// the engine's table is fully populated and SuperWoWhook / other DLLs have
|
||||
// done their post-rebuild writes, so the walk from the low end finds
|
||||
// genuinely free slots. A registration that arrives EARLIER (another DLL's
|
||||
// frame, between LoadScriptFunctions and the table build — issue #134)
|
||||
// still sees glue's 26-entry table; `RetryClaims` refuses that table and
|
||||
// re-validates its cached slots against the live one on every call.
|
||||
static void __fastcall FrameRegisterEvent_h(void *frame, void *edx,
|
||||
const char *eventName) {
|
||||
Event::Custom::RetryClaims();
|
||||
// Throttled-internally; no-op when the cache or scan toggle is off.
|
||||
Player::NameCache::Tick();
|
||||
FrameRegisterEvent_o(frame, edx, eventName);
|
||||
}
|
||||
|
||||
@@ -208,13 +210,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).
|
||||
//
|
||||
@@ -234,16 +237,19 @@ BOOL APIENTRY DllMain(HMODULE hModule, DWORD reason, LPVOID lpReserved) {
|
||||
CloseHandle(worker);
|
||||
}
|
||||
} else if (reason == DLL_PROCESS_DETACH) {
|
||||
// Clean /quit path — only tear down if we actually initialized.
|
||||
// Flush before MH_Uninitialize — the cache's file I/O uses Win32
|
||||
// directly (no MinHook involvement), so either order works in
|
||||
// practice, but flushing first lets us bail early if the hook
|
||||
// teardown ever grows side effects. Hard process termination (task
|
||||
// manager kill) bypasses this path; that's an inherent OS
|
||||
// limitation, and the 5-minute backstop flush in Remember() covers
|
||||
// the worst case there.
|
||||
// Process exit — only tear down if we actually initialized. A
|
||||
// clean /quit already saved the name cache from its atexit handler,
|
||||
// which runs before this; this save covers an exit that skips the
|
||||
// atexit handlers (Storm's fatal exit 0x0064CC80 calls ExitProcess
|
||||
// itself) and a save that failed there. Save before
|
||||
// MH_Uninitialize — the cache's file I/O uses Win32 directly (no
|
||||
// MinHook involvement), so either order works in practice, but
|
||||
// saving first lets us bail early if the hook teardown ever grows
|
||||
// side effects. Hard process termination (task manager kill)
|
||||
// bypasses this path; that's an inherent OS limitation, and the
|
||||
// 5-minute backstop flush covers the worst case there.
|
||||
if (g_mhInitialized) {
|
||||
Player::NameCache::Flush();
|
||||
Player::NameCache::Shutdown();
|
||||
MH_Uninitialize();
|
||||
}
|
||||
}
|
||||
|
||||
+125
-49
@@ -15,6 +15,7 @@
|
||||
#include "MinHook.h"
|
||||
#include "Offsets.h"
|
||||
#include "api/Documentation.h"
|
||||
#include "compat/WowTurbo.h"
|
||||
|
||||
namespace Game {
|
||||
|
||||
@@ -24,6 +25,32 @@ 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;
|
||||
}
|
||||
|
||||
bool StringToFlag(const char *text) {
|
||||
using StringToFlag_t = int(__fastcall *)(const char *text);
|
||||
return reinterpret_cast<StringToFlag_t>(Offsets::FUN_XML_ATTR_TO_BOOL)(text) != 0;
|
||||
}
|
||||
|
||||
int StrCmpI(const char *a, const char *b, int n) {
|
||||
using SStrCmpI_t = int(__stdcall *)(const char *a, const char *b, int n);
|
||||
return reinterpret_cast<SStrCmpI_t>(Offsets::FUN_SSTR_CMP_I)(a, b, n);
|
||||
}
|
||||
|
||||
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
|
||||
@@ -45,28 +72,44 @@ 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(RawSetI, lua_rawseti, LUA_RAW_SET_I) \
|
||||
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) \
|
||||
F(Replace, lua_replace, LUA_REPLACE) \
|
||||
F(GetTop, lua_gettop, LUA_GET_TOP) \
|
||||
F(SetTop, lua_settop, LUA_SET_TOP) \
|
||||
F(Call, lua_call, LUA_CALL) \
|
||||
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) \
|
||||
F(IsCFunction, lua_iscfunction, LUA_IS_C_FUNCTION)\
|
||||
F(ToCFunction, lua_tocfunction, LUA_TO_C_FUNCTION)\
|
||||
F(GetStack, lua_getstack, LUA_GET_STACK) \
|
||||
F(GetInfo, lua_getinfo, LUA_GET_INFO) \
|
||||
F(XMove, lua_xmove, LUA_X_MOVE) \
|
||||
F(NewThread, lua_newthread, LUA_NEW_THREAD) \
|
||||
F(Resume, lua_resume, LUA_RESUME) \
|
||||
F(Yield, lua_yield, LUA_YIELD) \
|
||||
F(ArgError, luaL_argerror, LUAL_ARG_ERROR) \
|
||||
F(CheckLString,luaL_checklstring,LUAL_CHECK_LSTRING)\
|
||||
F(CheckNumber, luaL_checknumber,LUAL_CHECK_NUMBER)\
|
||||
F(OptNumber, luaL_optnumber, LUAL_OPT_NUMBER) \
|
||||
F(SetN, luaL_setn, LUAL_SETN) \
|
||||
F(CheckStack, lua_checkstack, LUA_CHECK_STACK)
|
||||
F(Ref, luaL_ref, LUA_REF_REF) \
|
||||
F(Unref, luaL_unref, LUA_REF_UNREF) \
|
||||
F(CheckStack, lua_checkstack, LUA_CHECK_STACK) \
|
||||
F(Concat, lua_concat, LUA_CONCAT) \
|
||||
F(NewUserdata, lua_newuserdata, LUA_NEW_USERDATA) \
|
||||
F(ToUserdata, lua_touserdata, FUN_FRAMESCRIPT_GET_OBJECT)
|
||||
|
||||
#define CLASSICAPI_BIND_LUA(Name, Typedef, Offset) \
|
||||
const Typedef##_t Name = reinterpret_cast<Typedef##_t>(Offsets::Offset);
|
||||
@@ -100,6 +143,37 @@ void *ResolveObject(void *L, int idx) {
|
||||
return result;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
void PushObject(void *L, void *object) {
|
||||
RawGetI(L, REGISTRY_INDEX, ObjectLuaRef(object));
|
||||
}
|
||||
|
||||
bool ToFlag(void *L, int index, bool defaultValue) {
|
||||
// Returns a full int in EAX on every path (Ghidra's `bool` is wrong).
|
||||
using ToFlag_t = int(__fastcall *)(void *L, int index, int defaultValue);
|
||||
return reinterpret_cast<ToFlag_t>(Offsets::FUN_LUA_TO_BOOLEAN_LOOSE)(L, index,
|
||||
defaultValue ? 1 : 0) != 0;
|
||||
}
|
||||
|
||||
const char *ObjectName(void *object) {
|
||||
using GetName_t = const char *(__thiscall *)(void *);
|
||||
const void *vtable = Game::Read<const void *>(object, 0);
|
||||
return Game::Read<GetName_t>(vtable, Offsets::VTBL_SCRIPTOBJECT_GET_NAME)(object);
|
||||
}
|
||||
|
||||
const char *ObjectDisplayName(void *object) {
|
||||
const char *name = ObjectName(object);
|
||||
return name != nullptr ? name
|
||||
: reinterpret_cast<const char *>(Offsets::VAR_STR_UNNAMED);
|
||||
}
|
||||
|
||||
namespace {
|
||||
using FrameScriptIsA_t = char(__thiscall *)(void *self, int typeId);
|
||||
|
||||
@@ -121,11 +195,8 @@ void *ResolveChecked(void *L, int idx, const uintptr_t *typeIdVars, int count,
|
||||
Error(L, EngineString(Offsets::STR_FS_THIS_NON_OBJECT));
|
||||
return nullptr;
|
||||
}
|
||||
auto **vtable = *reinterpret_cast<void ***>(obj);
|
||||
auto IsA = reinterpret_cast<FrameScriptIsA_t>(
|
||||
vtable[Offsets::OFF_VMT_FRAMESCRIPT_ISA / sizeof(void *)]);
|
||||
for (int i = 0; i < count; ++i) {
|
||||
if (IsA(obj, FrameScriptTypeId(typeIdVars[i])))
|
||||
if (IsA(obj, typeIdVars[i]))
|
||||
return obj;
|
||||
}
|
||||
if (raiseError)
|
||||
@@ -144,6 +215,13 @@ int FrameScriptTypeId(uintptr_t typeIdVar) {
|
||||
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);
|
||||
}
|
||||
@@ -174,6 +252,12 @@ void *ResolveEditBox(void *L, int idx, bool raiseError) {
|
||||
void *ResolveModel(void *L, int idx, bool raiseError) {
|
||||
return ResolveTypedObject(L, idx, Offsets::VAR_MODEL_LUA_TYPE_ID, raiseError);
|
||||
}
|
||||
void *ResolvePlayerModel(void *L, int idx, bool raiseError) {
|
||||
return ResolveTypedObject(L, idx, Offsets::VAR_PLAYERMODEL_LUA_TYPE_ID, raiseError);
|
||||
}
|
||||
void *ResolveDressUpModel(void *L, int idx, bool raiseError) {
|
||||
return ResolveTypedObject(L, idx, Offsets::VAR_DRESSUPMODEL_LUA_TYPE_ID, raiseError);
|
||||
}
|
||||
|
||||
// Looks up `_G[name]`. If absent, creates a fresh table and binds it.
|
||||
// Leaves the resulting table on top of the stack.
|
||||
@@ -283,11 +367,11 @@ void RegisterGlueFunction(const char *name, CFunction func, const Doc::Function
|
||||
Api::Documentation::RecordGlobal(name, doc);
|
||||
}
|
||||
|
||||
void RegisterFrameMethods(void *context, const FrameMethodEntry *table, int count,
|
||||
const Doc::Method *docs, int docCount) {
|
||||
void RegisterFrameMethods(void *context, ArrayRef<FrameMethodEntry> methods,
|
||||
Doc::MethodList docs) {
|
||||
auto fn = reinterpret_cast<RegisterFrameMethods_t>(Offsets::FUN_REGISTER_FRAME_METHODS);
|
||||
fn(table, count, context);
|
||||
Api::Documentation::RecordFrameMethods(context, table, count, docs, docCount);
|
||||
fn(methods.data, methods.count, context);
|
||||
Api::Documentation::RecordFrameMethods(context, methods, docs);
|
||||
}
|
||||
|
||||
// Registers `func` at `_G[tableName][methodName]`. If the namespace
|
||||
@@ -334,12 +418,12 @@ void RegisterGlobalAlias(const char *alias, const char *tableName, const char *m
|
||||
Api::Documentation::RecordGlobal(alias, doc);
|
||||
}
|
||||
|
||||
void RegisterIntegerEnum(const char *parent, const char *sub,
|
||||
const EnumIntegerEntry *entries, int count,
|
||||
const char *docSystem) {
|
||||
// `_G[parent][sub] = { entries }`, creating `_G[parent]` if needed.
|
||||
static bool SetIntegerTable(const char *parent, const char *sub,
|
||||
const EnumIntegerEntry *entries, int count) {
|
||||
void *L = State();
|
||||
if (L == nullptr)
|
||||
return;
|
||||
return false;
|
||||
EnsureGlobalTable(L, parent); // [parentTbl]
|
||||
PushString(L, sub); // [parentTbl, subName]
|
||||
NewTable(L); // [parentTbl, subName, subTbl]
|
||||
@@ -350,7 +434,19 @@ 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);
|
||||
return true;
|
||||
}
|
||||
|
||||
void RegisterIntegerEnum(const char *parent, const char *sub, ArrayRef<EnumIntegerEntry> entries,
|
||||
const char *docSystem) {
|
||||
if (SetIntegerTable(parent, sub, entries.data, entries.count))
|
||||
Api::Documentation::RecordEnum(parent, sub, entries, docSystem);
|
||||
}
|
||||
|
||||
void RegisterConstants(const char *sub, ArrayRef<EnumIntegerEntry> entries,
|
||||
const char *docSystem) {
|
||||
if (SetIntegerTable("Constants", sub, entries.data, entries.count))
|
||||
Api::Documentation::RecordConstants(sub, entries, docSystem);
|
||||
}
|
||||
|
||||
void SetFieldNumber(void *L, const char *key, double value) {
|
||||
@@ -371,6 +467,12 @@ void SetFieldBool(void *L, const char *key, bool value) {
|
||||
SetTable(L, -3);
|
||||
}
|
||||
|
||||
void SetFieldNil(void *L, const char *key) {
|
||||
PushString(L, key);
|
||||
PushNil(L);
|
||||
SetTable(L, -3);
|
||||
}
|
||||
|
||||
void SetGlobalNumber(void *L, const char *name, double value) {
|
||||
PushString(L, name);
|
||||
PushNumber(L, value);
|
||||
@@ -415,45 +517,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
|
||||
|
||||
@@ -461,7 +532,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,
|
||||
@@ -470,10 +541,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 {
|
||||
@@ -523,6 +597,8 @@ HookAutoRegister::HookAutoRegister(uintptr_t target, void *hook, void **original
|
||||
bool RunHookRegistrations() {
|
||||
for (auto *node = g_hookHead; node != nullptr; node = node->next) {
|
||||
auto *targetPtr = reinterpret_cast<LPVOID>(node->target);
|
||||
// A hook must wrap the engine's body, not wow_turbo's reimplementation.
|
||||
Compat::WowTurbo::Reclaim(node->target);
|
||||
if (MH_CreateHook(targetPtr, node->hook,
|
||||
reinterpret_cast<LPVOID *>(node->original)) != MH_OK)
|
||||
return false;
|
||||
|
||||
+192
-28
@@ -58,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"`,
|
||||
@@ -71,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 *)();
|
||||
|
||||
@@ -79,6 +104,19 @@ using LoadScriptFunctions_t = void(__fastcall *)();
|
||||
// registering its 109 glue functions. See FUN_LOAD_GLUE_SCRIPT_FUNCTIONS.
|
||||
using LoadGlueScriptFunctions_t = void(__stdcall *)();
|
||||
|
||||
// The engine's text-to-flag reader (FUN_XML_ATTR_TO_BOOL, 4.3.4's
|
||||
// `StringToBOOL(const char *)`), which XML boolean attributes go through:
|
||||
// true for text starting 1-9/T/Y/t/y or equal to "on"/"enabled" (any case),
|
||||
// false for anything else, including null.
|
||||
bool StringToFlag(const char *text);
|
||||
|
||||
// Storm's case-insensitive compare, SStrCmpI (FUN_SSTR_CMP_I) — the one the
|
||||
// engine uses for names, tokens and tags: at most `n` characters, ASCII case
|
||||
// folded, <0 / 0 / >0 like strcmp. The default `n` is Storm's "whole string".
|
||||
// Always call it through here: the engine function is `__stdcall` (RET 0xC),
|
||||
// and a `__cdecl` declaration drifts ESP by 12 per call.
|
||||
int StrCmpI(const char *a, const char *b, int n = 0x7FFFFFFF);
|
||||
|
||||
// --- API documentation descriptors -----------------------------------------
|
||||
//
|
||||
// Every Lua registration (see the `Register*` functions in `Game::Lua`) can
|
||||
@@ -109,6 +147,18 @@ using LoadGlueScriptFunctions_t = void(__stdcall *)();
|
||||
// literals + file-scope arrays): no heap, no dynamic init.
|
||||
// - Summaries are user-facing text: one sentence, plain words, present
|
||||
// tense, no patch versions.
|
||||
|
||||
// A view over a file-scope `const T[]` that takes its count from the array's
|
||||
// type, so no call site passes one; `{}` means none.
|
||||
template <typename T>
|
||||
struct ArrayRef {
|
||||
const T *data = nullptr;
|
||||
int count = 0;
|
||||
constexpr ArrayRef() = default;
|
||||
template <size_t N>
|
||||
constexpr ArrayRef(const T (&a)[N]) : data(a), count(static_cast<int>(N)) {}
|
||||
};
|
||||
|
||||
namespace Doc {
|
||||
|
||||
struct Field {
|
||||
@@ -134,14 +184,7 @@ 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)) {}
|
||||
};
|
||||
using FieldList = ArrayRef<Field>;
|
||||
|
||||
// A registered function. Positional init: `{summary, args, rets}` for a
|
||||
// table function, `{summary, args, rets, "XGlobals"}` for a global, and
|
||||
@@ -162,6 +205,7 @@ struct Method {
|
||||
const char *name;
|
||||
const Function *doc;
|
||||
};
|
||||
using MethodList = ArrayRef<Method>;
|
||||
|
||||
// A table shape a function returns or accepts → `Tables{Type="Structure"}`
|
||||
// in `system`. Self-registering: nothing binds a structure to Lua, so it
|
||||
@@ -202,7 +246,9 @@ constexpr int UpvalueIndex(int i) { return GLOBALS_INDEX - i; }
|
||||
// `lua_call` / `lua_pcall` nresults sentinel meaning "all".
|
||||
constexpr int MULTRET = -1;
|
||||
|
||||
// Type tag values returned by `Type()` (lua_type).
|
||||
// Type tag values returned by `Type()` (lua_type). TYPE_NONE is an absent
|
||||
// argument (past the top of the stack).
|
||||
constexpr int TYPE_NONE = -1;
|
||||
constexpr int TYPE_NIL = 0;
|
||||
constexpr int TYPE_BOOLEAN = 1;
|
||||
constexpr int TYPE_LIGHTUSERDATA = 2;
|
||||
@@ -229,19 +275,30 @@ 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);
|
||||
// Pops the top value into t[n] for the table at idx, raw.
|
||||
using lua_rawseti_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);
|
||||
using lua_insert_t = void(__fastcall *)(void *L, int idx);
|
||||
using lua_remove_t = void(__fastcall *)(void *L, int idx);
|
||||
// Pops the top value into slot idx.
|
||||
using lua_replace_t = void(__fastcall *)(void *L, int idx);
|
||||
using lua_gettop_t = int(__fastcall *)(void *L);
|
||||
using lua_settop_t = void(__fastcall *)(void *L, int idx);
|
||||
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
|
||||
@@ -253,6 +310,11 @@ using lua_error_t = void(__cdecl *)(void *L, const char *fmt, ...);
|
||||
using lua_topointer_t = const void *(__fastcall *)(void *L, int idx);
|
||||
using lua_tothread_t = void *(__fastcall *)(void *L, int idx);
|
||||
using lua_iscfunction_t = int(__fastcall *)(void *L, int idx);
|
||||
using lua_tocfunction_t = CFunction(__fastcall *)(void *L, int idx);
|
||||
// Fill a lua_Debug (Offsets::SIZEOF_LUA_DEBUG bytes) for a call level /
|
||||
// with the fields `what` names. Level 0 is the running C function.
|
||||
using lua_getstack_t = int(__fastcall *)(void *L, int level, void *ar);
|
||||
using lua_getinfo_t = int(__fastcall *)(void *L, const char *what, void *ar);
|
||||
using lua_xmove_t = void(__fastcall *)(void *from, void *to, int n);
|
||||
// `lua_newthread` returns the new `lua_State *` in eax, but Ghidra
|
||||
// infers `void` because the inner call's value just flows through.
|
||||
@@ -263,8 +325,26 @@ using lua_newthread_t = void *(__fastcall *)(void *L);
|
||||
using lua_resume_t = int(__fastcall *)(void *L, int nargs);
|
||||
using lua_yield_t = int(__fastcall *)(void *L, int nresults);
|
||||
using luaL_argerror_t = void(__fastcall *)(void *L, int narg, const char *msg);
|
||||
// The auxlib argument readers: each raises the engine's own "bad argument"
|
||||
// error. CheckLString's `len` may be null.
|
||||
using luaL_checklstring_t = const char *(__fastcall *)(void *L, int narg, unsigned int *len);
|
||||
using luaL_checknumber_t = double(__fastcall *)(void *L, int narg);
|
||||
using luaL_optnumber_t = double(__fastcall *)(void *L, int narg, double def);
|
||||
using luaL_setn_t = void(__fastcall *)(void *L, int t, int n);
|
||||
// Pops the top value into the table at `t` under a fresh integer key and
|
||||
// returns the key (LUA_REFNIL, -1, for a nil). With REGISTRY_INDEX it anchors
|
||||
// a value across calls; read it back with RawGetI(L, REGISTRY_INDEX, ref).
|
||||
using luaL_ref_t = int(__fastcall *)(void *L, int t);
|
||||
// Releases a key returned by luaL_ref; ignores LUA_REFNIL / LUA_NOREF.
|
||||
using luaL_unref_t = void(__fastcall *)(void *L, int t, int ref);
|
||||
using lua_checkstack_t = int(__fastcall *)(void *L, int size);
|
||||
// Pops the top `n` values and pushes their `..` concatenation; n == 0 pushes
|
||||
// "" and n == 1 leaves the value untouched.
|
||||
using lua_concat_t = void(__fastcall *)(void *L, int n);
|
||||
// Pushes a new full userdata of `size` bytes and returns its block.
|
||||
using lua_newuserdata_t = void *(__fastcall *)(void *L, unsigned int size);
|
||||
// The block of the full userdata at idx, the pointer of a light one, else null.
|
||||
using lua_touserdata_t = void *(__fastcall *)(void *L, int idx);
|
||||
|
||||
extern const lua_isnumber_t IsNumber;
|
||||
extern const lua_isstring_t IsString;
|
||||
@@ -280,6 +360,13 @@ extern const lua_pushboolean_t PushBoolean;
|
||||
// engine's `lua_pushboolean` ABI wants `int` (any non-zero = true), so
|
||||
// this just funnels through the raw binding with a single conversion.
|
||||
inline void PushBool(void *L, bool b) { PushBoolean(L, static_cast<int>(b)); }
|
||||
// The engine's script-flag argument reader (FUN_LUA_TO_BOOLEAN_LOOSE, 4.3.4's
|
||||
// `StringToBOOL(L, index, default)`), which every engine method taking an
|
||||
// optional flag uses: nil is false, a boolean is itself, a number is its
|
||||
// truncated int (so 0.5 is false), a string reads as StringToFlag except that
|
||||
// text it does not recognize is `defaultValue`, and any other type is
|
||||
// `defaultValue`.
|
||||
bool ToFlag(void *L, int index, bool defaultValue = false);
|
||||
extern const lua_pushstring_t PushString;
|
||||
extern const lua_pushlstring_t PushLString;
|
||||
extern const lua_pushvalue_t PushValue;
|
||||
@@ -287,28 +374,44 @@ 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_rawseti_t RawSetI;
|
||||
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;
|
||||
extern const lua_replace_t Replace;
|
||||
extern const lua_gettop_t GetTop;
|
||||
extern const lua_settop_t SetTop;
|
||||
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;
|
||||
extern const lua_iscfunction_t IsCFunction;
|
||||
extern const lua_tocfunction_t ToCFunction;
|
||||
extern const lua_getstack_t GetStack;
|
||||
extern const lua_getinfo_t GetInfo;
|
||||
extern const lua_xmove_t XMove;
|
||||
extern const lua_newthread_t NewThread;
|
||||
extern const lua_resume_t Resume;
|
||||
extern const lua_yield_t Yield;
|
||||
extern const luaL_argerror_t ArgError;
|
||||
extern const luaL_checklstring_t CheckLString;
|
||||
extern const luaL_checknumber_t CheckNumber;
|
||||
extern const luaL_optnumber_t OptNumber;
|
||||
extern const luaL_setn_t SetN;
|
||||
extern const luaL_ref_t Ref;
|
||||
extern const luaL_unref_t Unref;
|
||||
extern const lua_checkstack_t CheckStack;
|
||||
extern const lua_concat_t Concat;
|
||||
extern const lua_newuserdata_t NewUserdata;
|
||||
extern const lua_touserdata_t ToUserdata;
|
||||
|
||||
// Returns the global `lua_State *` (read on demand from the engine's global).
|
||||
// Callable outside a Lua callback, e.g. during LoadScriptFunctions setup.
|
||||
@@ -324,6 +427,21 @@ 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);
|
||||
|
||||
// The object's global name (VTBL_SCRIPTOBJECT_GET_NAME), or nullptr when it
|
||||
// has none.
|
||||
const char *ObjectName(void *object);
|
||||
|
||||
// How the engine names an object in its frame-script usage errors:
|
||||
// `GetName() ?: "<unnamed>"`.
|
||||
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
|
||||
@@ -357,6 +475,9 @@ void *ResolveTypedObjectAny(void *L, int idx, const uintptr_t *typeIdVars,
|
||||
// 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);
|
||||
@@ -366,6 +487,8 @@ 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);
|
||||
void *ResolvePlayerModel(void *L, int idx = 1, bool raiseError = true);
|
||||
void *ResolveDressUpModel(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
|
||||
@@ -410,10 +533,11 @@ 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. `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);
|
||||
// registry address — see Offsets::VAR_*_METHOD_REGISTRY. `methods` and
|
||||
// `docs` are file-scope arrays; `docs` pairs descriptors to the entries by
|
||||
// NAME (any order, any subset).
|
||||
void RegisterFrameMethods(void *context, ArrayRef<FrameMethodEntry> methods,
|
||||
Doc::MethodList docs = {});
|
||||
|
||||
// Registers `func` at `_G[tableName][methodName]`, creating the namespace
|
||||
// table if it doesn't already exist. This is how modern WoW C_*-style APIs
|
||||
@@ -431,9 +555,9 @@ void RegisterTableFunction(const char *tableName, const char *methodName,
|
||||
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
|
||||
// integer the enum field maps to.
|
||||
// Key/value pair for `RegisterIntegerEnum` and `RegisterConstants`. `key`
|
||||
// becomes a field name (PascalCase for Blizzard's `Enum.*`, UPPER_CASE for
|
||||
// its `Constants.*`) and `value` is the integer the field maps to.
|
||||
struct EnumIntegerEntry {
|
||||
const char *key;
|
||||
int value;
|
||||
@@ -444,10 +568,16 @@ struct EnumIntegerEntry {
|
||||
// `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,
|
||||
// `entries` is a file-scope array.
|
||||
void RegisterIntegerEnum(const char *parent, const char *sub, ArrayRef<EnumIntegerEntry> entries,
|
||||
const char *docSystem = nullptr);
|
||||
|
||||
// Registers `Constants[sub] = { entries }`, Blizzard's engine constant
|
||||
// tables (`Constants.MoneyFormattingConstants`). Documented as a "Constants"
|
||||
// table of `docSystem`.
|
||||
void RegisterConstants(const char *sub, ArrayRef<EnumIntegerEntry> entries,
|
||||
const char *docSystem);
|
||||
|
||||
// Set `t[key] = value` on the table currently at stack[-1] (the most
|
||||
// common shape used when populating a struct-style table mid-build).
|
||||
// Pushes the key + value, calls `SetTable(L, -3)`, which pops both and
|
||||
@@ -456,6 +586,10 @@ void RegisterIntegerEnum(const char *parent, const char *sub,
|
||||
void SetFieldNumber(void *L, const char *key, double value);
|
||||
void SetFieldString(void *L, const char *key, const char *value);
|
||||
void SetFieldBool(void *L, const char *key, bool value);
|
||||
// `t[key] = nil` — clears a field a reused (caller-supplied) table may still
|
||||
// hold from an earlier fill. Not for fresh tables: Lua 5.0 inserts a node for
|
||||
// a missing key even when the value is nil.
|
||||
void SetFieldNil(void *L, const char *key);
|
||||
|
||||
// Sets `_G[name] = value` via `lua_rawset` on the globals
|
||||
// pseudo-index. `RawSet` over `SetTable` because the globals table has
|
||||
@@ -483,6 +617,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);
|
||||
|
||||
@@ -510,16 +646,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,
|
||||
@@ -541,9 +678,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
|
||||
|
||||
@@ -630,6 +788,12 @@ bool RunHookRegistrations();
|
||||
// issue #33, Frame::Attributes). A pure-C++ cache keyed by spellID/itemID is
|
||||
// NOT fragile and must not register.
|
||||
//
|
||||
// It runs AFTER the frames are gone: CGGameUI::Shutdown destroys every frame
|
||||
// (and each Model frame's scene with every model in it) before
|
||||
// CGGameUI::Initialize resets the Lua state. So a cleanup here only FORGETS
|
||||
// pointers; it never releases an engine object tied to a frame. Release those
|
||||
// when the frame dies (Model::Teardown for Model frames).
|
||||
//
|
||||
// Same lifetime + ordering rules as ModuleAutoRegister: static-init chaining,
|
||||
// undefined cross-TU order — fine, because each callback only clears its OWN
|
||||
// state. This is the "clear stale state" category only; a save-before-teardown
|
||||
|
||||
+88
-105
@@ -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>
|
||||
|
||||
@@ -29,9 +32,8 @@ namespace {
|
||||
// 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.
|
||||
// purpose. Names with no 1.12 counterpart (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",
|
||||
@@ -50,138 +52,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;
|
||||
}
|
||||
|
||||
@@ -190,7 +167,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
|
||||
+5890
-826
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,90 @@
|
||||
// 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/>.
|
||||
|
||||
// `IsItemAction(slot)` / `HasBonusActionBar()` — the action-bar predicates
|
||||
// from the newer clients' ActionBarFrame_Scripts, read off the same engine
|
||||
// state the 1.12 readers use.
|
||||
//
|
||||
// IsItemAction 1 when the 1-based slot holds an item, else nil; a
|
||||
// non-number slot is a usage error. The item kind is
|
||||
// the 0x80000000 tag in VAR_ACTION_TABLE.
|
||||
// HasBonusActionBar 1 while a bonus bar is active, else nil: the offset
|
||||
// GetBonusBarOffset returns is nonzero.
|
||||
|
||||
#include "Game.h"
|
||||
#include "Offsets.h"
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace Action::Bar {
|
||||
|
||||
namespace {
|
||||
|
||||
int PushFlag(void *L, bool on) {
|
||||
if (on)
|
||||
Game::Lua::PushNumber(L, 1.0);
|
||||
else
|
||||
Game::Lua::PushNil(L);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int __fastcall Script_IsItemAction(void *L) {
|
||||
if (!Game::Lua::IsNumber(L, 1)) {
|
||||
Game::Lua::Error(L, "Usage: IsItemAction(slot)");
|
||||
return 0;
|
||||
}
|
||||
|
||||
const int slot0 = static_cast<int>(Game::Lua::ToNumber(L, 1)) - 1;
|
||||
if (slot0 < 0 || slot0 >= Offsets::ACTION_TABLE_MAX_SLOTS)
|
||||
return PushFlag(L, false);
|
||||
const auto *table = reinterpret_cast<const uint32_t *>(
|
||||
static_cast<uintptr_t>(Offsets::VAR_ACTION_TABLE));
|
||||
return PushFlag(L, (table[slot0] & Offsets::ACTION_TYPE_MASK) ==
|
||||
Offsets::ACTION_TYPE_ITEM_BY_ID);
|
||||
}
|
||||
|
||||
int __fastcall Script_HasBonusActionBar(void *L) {
|
||||
return PushFlag(L, Game::Read<uint32_t>(Offsets::VAR_BONUS_BAR_OFFSET) != 0);
|
||||
}
|
||||
|
||||
// --- Documentation ----------------------------------------------------------
|
||||
|
||||
const Game::Doc::Field kSlotArgs[] = {
|
||||
Game::Doc::Req("slot", "number", "The action slot, 1 to 120."),
|
||||
};
|
||||
const Game::Doc::Field kIsItemRets[] = {
|
||||
Game::Doc::Opt("isItem", "number", nullptr, "1 if the slot holds an item, else nil."),
|
||||
};
|
||||
const Game::Doc::Function kIsItemAction{
|
||||
"Returns 1 if an action slot holds an item.",
|
||||
kSlotArgs, kIsItemRets, "ActionBar"};
|
||||
|
||||
const Game::Doc::Field kHasBonusRets[] = {
|
||||
Game::Doc::Opt("hasBonusBar", "number", nullptr,
|
||||
"1 if a bonus action bar is active, else nil."),
|
||||
};
|
||||
const Game::Doc::Function kHasBonusActionBar{
|
||||
"Returns 1 if a bonus action bar is active, for example in a stance or form.",
|
||||
{}, kHasBonusRets, "ActionBar"};
|
||||
|
||||
} // namespace
|
||||
|
||||
static void RegisterLuaFunctions() {
|
||||
Game::Lua::RegisterGlobalFunction("IsItemAction", &Script_IsItemAction, &kIsItemAction);
|
||||
Game::Lua::RegisterGlobalFunction("HasBonusActionBar", &Script_HasBonusActionBar,
|
||||
&kHasBonusActionBar);
|
||||
}
|
||||
|
||||
static const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
|
||||
|
||||
} // namespace Action::Bar
|
||||
@@ -0,0 +1,178 @@
|
||||
// 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/>.
|
||||
|
||||
// Where a spell sits on the bars.
|
||||
//
|
||||
// FindSpellActionButtons(spell [, set]) the 1-based slots holding the
|
||||
// spell as a spell action, or nothing when none does.
|
||||
// HasSpellActionButtons(spell [, set]) whether any slot does.
|
||||
// IsOnBarOrSpecialBar(spell [, set]) the same, or the spell is on the
|
||||
// shapeshift bar or the pet bar.
|
||||
//
|
||||
// A slot matches on the spell ID it stores, as 4.3.4's PutActionInSlot
|
||||
// compares (IsSpell && GetSpell == spellId): a macro or an item that casts
|
||||
// the spell is not the spell, and a rank matches only itself. The special
|
||||
// bars are the engine's own lists — the shapeshift bar's spell array that
|
||||
// GetShapeshiftFormInfo reads, and the pet bar's spell entries
|
||||
// (GetPetActionInfo's types 1-5) while a pet bar is up.
|
||||
//
|
||||
// `set` is Enum.ActionBarSet, a mask whose Mkb bit is the one set of slots
|
||||
// this client has; Gamepad alone finds no slot.
|
||||
|
||||
#include "Game.h"
|
||||
#include "Offsets.h"
|
||||
#include "spell/Arg.h"
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace Action::Find {
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int ACTION_BAR_SET_MKB = 1;
|
||||
constexpr int ACTION_BAR_SET_GAMEPAD = 2;
|
||||
constexpr int ACTION_BAR_SET_ALL = ACTION_BAR_SET_MKB | ACTION_BAR_SET_GAMEPAD;
|
||||
|
||||
// The spell at stack[1] and whether the set at stack[2] (default All)
|
||||
// covers this client's slots. 0 when the spell does not resolve.
|
||||
int Args(void *L, bool *searchSlots) {
|
||||
const int set = Game::Lua::IsNumber(L, 2) ? static_cast<int>(Game::Lua::ToNumber(L, 2))
|
||||
: ACTION_BAR_SET_ALL;
|
||||
*searchSlots = (set & ACTION_BAR_SET_MKB) != 0;
|
||||
return Spell::Arg::ResolveSpellID(L, 1);
|
||||
}
|
||||
|
||||
bool SlotHolds(int slot0, int spellID) {
|
||||
const uint32_t entry = reinterpret_cast<const uint32_t *>(
|
||||
static_cast<uintptr_t>(Offsets::VAR_ACTION_TABLE))[slot0];
|
||||
return (entry & Offsets::ACTION_TYPE_MASK) == Offsets::ACTION_TYPE_SPELL &&
|
||||
entry == static_cast<uint32_t>(spellID);
|
||||
}
|
||||
|
||||
bool AnySlotHolds(int spellID) {
|
||||
for (int slot0 = 0; slot0 < Offsets::ACTION_TABLE_MAX_SLOTS; ++slot0) {
|
||||
if (SlotHolds(slot0, spellID))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool OnShapeshiftBar(int spellID) {
|
||||
const int count = Game::Read<int>(Offsets::VAR_SHAPESHIFT_BAR_SPELL_COUNT);
|
||||
const auto *spells = Game::Read<const uint32_t *>(Offsets::VAR_SHAPESHIFT_BAR_SPELLS);
|
||||
if (spells == nullptr)
|
||||
return false;
|
||||
for (int i = 0; i < count; ++i) {
|
||||
if (spells[i] == static_cast<uint32_t>(spellID))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool OnPetBar(int spellID) {
|
||||
if (Game::Read<uint64_t>(Offsets::VAR_PET_GUID) == 0)
|
||||
return false;
|
||||
const auto *slots = reinterpret_cast<const uint32_t *>(
|
||||
static_cast<uintptr_t>(Offsets::VAR_PET_ACTION_SLOTS));
|
||||
for (int i = 0; i < Offsets::PET_ACTION_SLOT_COUNT; ++i) {
|
||||
const uint32_t type = (slots[i] >> 24) & 0x3F;
|
||||
if (type >= Offsets::PET_ACTION_TYPE_SPELL_FIRST &&
|
||||
type <= Offsets::PET_ACTION_TYPE_SPELL_LAST &&
|
||||
(slots[i] & 0xFFFF) == static_cast<uint32_t>(spellID))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
int __fastcall Script_FindSpellActionButtons(void *L) {
|
||||
bool searchSlots;
|
||||
const int spellID = Args(L, &searchSlots);
|
||||
if (spellID <= 0 || !searchSlots || !AnySlotHolds(spellID))
|
||||
return 0;
|
||||
Game::Lua::NewTable(L);
|
||||
int index = 0;
|
||||
for (int slot0 = 0; slot0 < Offsets::ACTION_TABLE_MAX_SLOTS; ++slot0) {
|
||||
if (!SlotHolds(slot0, spellID))
|
||||
continue;
|
||||
Game::Lua::PushNumber(L, static_cast<double>(++index));
|
||||
Game::Lua::PushNumber(L, static_cast<double>(slot0 + 1));
|
||||
Game::Lua::RawSet(L, -3);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
int __fastcall Script_HasSpellActionButtons(void *L) {
|
||||
bool searchSlots;
|
||||
const int spellID = Args(L, &searchSlots);
|
||||
Game::Lua::PushBool(L, spellID > 0 && searchSlots && AnySlotHolds(spellID));
|
||||
return 1;
|
||||
}
|
||||
|
||||
int __fastcall Script_IsOnBarOrSpecialBar(void *L) {
|
||||
bool searchSlots;
|
||||
const int spellID = Args(L, &searchSlots);
|
||||
Game::Lua::PushBool(L, spellID > 0 && ((searchSlots && AnySlotHolds(spellID)) ||
|
||||
OnShapeshiftBar(spellID) || OnPetBar(spellID)));
|
||||
return 1;
|
||||
}
|
||||
|
||||
// --- Documentation ----------------------------------------------------------
|
||||
|
||||
const Game::Doc::Field kArgs[] = {
|
||||
Game::Doc::Req("spellID", "SpellIdentifier", "A spell ID, spell link, or spell name."),
|
||||
Game::Doc::Opt("setToSearch", "ActionBarSet", "All"),
|
||||
};
|
||||
const Game::Doc::Field kFindRets[] = {
|
||||
Game::Doc::Req("slots", "table", "The 1-based action slots; nothing when no slot "
|
||||
"holds the spell."),
|
||||
};
|
||||
const Game::Doc::Function kFindSpellActionButtons{
|
||||
"The action slots that hold the spell as a spell action.",
|
||||
kArgs, kFindRets};
|
||||
|
||||
const Game::Doc::Field kHasRets[] = {
|
||||
Game::Doc::Req("hasSpellActionButtons", "bool"),
|
||||
};
|
||||
const Game::Doc::Function kHasSpellActionButtons{
|
||||
"Whether any action slot holds the spell as a spell action.",
|
||||
kArgs, kHasRets};
|
||||
|
||||
const Game::Doc::Field kOnBarRets[] = {
|
||||
Game::Doc::Req("isOnBarOrSpecialBar", "bool"),
|
||||
};
|
||||
const Game::Doc::Function kIsOnBarOrSpecialBar{
|
||||
"Whether the spell is in an action slot, on the shapeshift bar, or on the pet bar.",
|
||||
kArgs, kOnBarRets};
|
||||
|
||||
const Game::Lua::EnumIntegerEntry kActionBarSet[] = {
|
||||
{"None", 0},
|
||||
{"Mkb", ACTION_BAR_SET_MKB},
|
||||
{"Gamepad", ACTION_BAR_SET_GAMEPAD},
|
||||
{"All", ACTION_BAR_SET_ALL},
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
static void RegisterLuaFunctions() {
|
||||
Game::Lua::RegisterTableFunction("C_ActionBar", "FindSpellActionButtons",
|
||||
&Script_FindSpellActionButtons, &kFindSpellActionButtons);
|
||||
Game::Lua::RegisterTableFunction("C_ActionBar", "HasSpellActionButtons",
|
||||
&Script_HasSpellActionButtons, &kHasSpellActionButtons);
|
||||
Game::Lua::RegisterTableFunction("C_ActionBar", "IsOnBarOrSpecialBar",
|
||||
&Script_IsOnBarOrSpecialBar, &kIsOnBarOrSpecialBar);
|
||||
Game::Lua::RegisterIntegerEnum("Enum", "ActionBarSet", kActionBarSet, "ActionBar");
|
||||
}
|
||||
|
||||
static const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
|
||||
|
||||
} // namespace Action::Find
|
||||
+95
-39
@@ -12,42 +12,50 @@
|
||||
// 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.
|
||||
// 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.
|
||||
//
|
||||
// **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.
|
||||
// `C_ActionBar.GetSpell(slot)` — the spell the slot stands for, 0 for none.
|
||||
// It is the engine's own resolver (FUN_ACTION_SLOT_TO_SPELL), which every
|
||||
// action reader (cooldown, usable, range, current) goes through: a spell
|
||||
// action is its spell, a macro is its cached primary spell, and an item is
|
||||
// its first on-use spell — retail's ActionButton.lua calls GetSpell for
|
||||
// exactly that item case. The spellbook flag it also hands back is not part
|
||||
// of the answer.
|
||||
//
|
||||
// `C_ActionBar.IsMacroActionWithShowTooltip(slot)` — the slot holds a macro
|
||||
// whose body carries `#showtooltip`, by the parse `Macro::ShowTooltip` hands
|
||||
// the tooltip over on. `#show` is not it.
|
||||
|
||||
#include "Game.h"
|
||||
#include "Offsets.h"
|
||||
#include "action/Slot.h"
|
||||
#include "equipmentset/Data.h"
|
||||
#include "macro/ShowTooltip.h"
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
@@ -70,16 +78,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 +96,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 +113,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,15 +123,74 @@ int __fastcall Script_GetActionInfo(void *L) {
|
||||
return 2;
|
||||
}
|
||||
|
||||
// Unknown type tag — surface as nil so callers don't get garbage.
|
||||
Game::Lua::PushNil(L);
|
||||
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;
|
||||
}
|
||||
|
||||
int __fastcall Script_GetSpell(void *L) {
|
||||
if (!Game::Lua::IsNumber(L, 1)) {
|
||||
Game::Lua::Error(L, "Usage: C_ActionBar.GetSpell(actionID)");
|
||||
return 0;
|
||||
}
|
||||
// The resolver bounds-checks the slot itself and answers 0 outside it.
|
||||
const int slot0 = static_cast<int>(Game::Lua::ToNumber(L, 1)) - 1;
|
||||
uint32_t petFlag = 0;
|
||||
const uint32_t spellID = reinterpret_cast<SlotToSpell_t>(
|
||||
static_cast<uintptr_t>(Offsets::FUN_ACTION_SLOT_TO_SPELL))(
|
||||
static_cast<uint32_t>(slot0), &petFlag);
|
||||
Game::Lua::PushNumber(L, static_cast<double>(spellID));
|
||||
return 1;
|
||||
}
|
||||
|
||||
int __fastcall Script_IsMacroActionWithShowTooltip(void *L) {
|
||||
if (!Game::Lua::IsNumber(L, 1)) {
|
||||
Game::Lua::Error(L, "Usage: C_ActionBar.IsMacroActionWithShowTooltip(actionID)");
|
||||
return 0;
|
||||
}
|
||||
const int slot0 = static_cast<int>(Game::Lua::ToNumber(L, 1)) - 1;
|
||||
const uint32_t macroID = Action::Slot::MacroIDForSlot(slot0);
|
||||
Game::Lua::PushBool(L, macroID != 0 && Macro::ShowTooltip::HasShowTooltipDirective(macroID));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const Game::Doc::Field kGetSpellArgs[] = {
|
||||
Game::Doc::Req("actionID", "luaIndex"),
|
||||
};
|
||||
const Game::Doc::Field kGetSpellRets[] = {
|
||||
Game::Doc::Req("spellID", "number"),
|
||||
};
|
||||
const Game::Doc::Function kGetSpellDoc{
|
||||
"The spell an action stands for: a spell's own ID, a macro's spell, or an item's "
|
||||
"on-use spell; 0 when there is none.",
|
||||
kGetSpellArgs, kGetSpellRets};
|
||||
|
||||
const Game::Doc::Field kIsMacroActionWithShowTooltipRets[] = {
|
||||
Game::Doc::Req("isMacroActionWithShowTooltip", "bool"),
|
||||
};
|
||||
const Game::Doc::Function kIsMacroActionWithShowTooltipDoc{
|
||||
"Whether the action is a macro with an explicit #showtooltip line.",
|
||||
kGetSpellArgs, kIsMacroActionWithShowTooltipRets};
|
||||
|
||||
} // namespace
|
||||
|
||||
static void RegisterLuaFunctions() {
|
||||
Game::Lua::RegisterGlobalFunction("GetActionInfo", &Script_GetActionInfo);
|
||||
Game::Lua::RegisterTableFunction("C_ActionBar", "GetSpell", &Script_GetSpell, &kGetSpellDoc);
|
||||
Game::Lua::RegisterTableFunction("C_ActionBar", "IsMacroActionWithShowTooltip",
|
||||
&Script_IsMacroActionWithShowTooltip,
|
||||
&kIsMacroActionWithShowTooltipDoc);
|
||||
}
|
||||
|
||||
static const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
|
||||
|
||||
@@ -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
|
||||
@@ -0,0 +1,114 @@
|
||||
// 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 range answer of an action button whose macro is aimed at a unit.
|
||||
//
|
||||
// 4.3.4 keeps that unit on the macro (MACRONODE::m_target: the `[@unit]` of
|
||||
// the clause its display resolved from, or the target SetMacroSpell /
|
||||
// SetMacroItem named), and CGActionBar::HasValidTarget range-checks the slot's
|
||||
// spell against it in place of the current target. 1.12's slot range function
|
||||
// FUN_ACTION_SLOT_RANGE already takes the unit as a GUID for its range check,
|
||||
// and always passes 0, the selection. `Macro::ShowTooltip` keeps the unit (its
|
||||
// `Info::unit`), and this answers for those slots with that GUID, in the
|
||||
// engine's order: the range check, then the implicit-target test, where the
|
||||
// unit standing in for the selection must exist. Every other slot goes to the
|
||||
// engine function unchanged.
|
||||
//
|
||||
// The function's one caller, Script_IsActionInRange, is redirected rather than
|
||||
// the function hooked.
|
||||
|
||||
#include "action/Range.h"
|
||||
|
||||
#include "Common.h"
|
||||
#include "Game.h"
|
||||
#include "Offsets.h"
|
||||
#include "action/Slot.h"
|
||||
#include "macro/ShowTooltip.h"
|
||||
#include "object/Resolve.h"
|
||||
#include "spell/Lookup.h"
|
||||
#include "unit/Identity.h"
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace Action::Range {
|
||||
|
||||
namespace {
|
||||
|
||||
using SlotRange_t = int(__fastcall *)(int slot0, int *inRange);
|
||||
using SlotToSpell_t = int(__fastcall *)(int slot0, uint32_t *outPetFlag);
|
||||
using CheckRange_t = uint8_t(__fastcall *)(const void *caster, const uint8_t *record,
|
||||
uint32_t guidLo, uint32_t guidHi, uint32_t report);
|
||||
|
||||
// The first implicit targets the engine answers for: case 0 of its table.
|
||||
bool TakesUnitTarget(int32_t implicitTarget) {
|
||||
switch (implicitTarget) {
|
||||
case 6: case 21: case 23: case 25: case 26: case 35: case 45: case 57: case 61:
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
uint64_t MacroUnit(int slot0) {
|
||||
const uint32_t macroID = Action::Slot::MacroIDForSlot(slot0);
|
||||
Macro::ShowTooltip::Info info{};
|
||||
// Passive: this runs inside a Lua call, from a button's OnUpdate.
|
||||
if (macroID == 0 || !Macro::ShowTooltip::LookupPassive(macroID, &info))
|
||||
return 0;
|
||||
return info.unit;
|
||||
}
|
||||
|
||||
int __fastcall SlotRange_h(int slot0, int *inRange) {
|
||||
const auto original = reinterpret_cast<SlotRange_t>(Offsets::FUN_ACTION_SLOT_RANGE);
|
||||
if (slot0 < 0 || slot0 >= Offsets::ACTION_TABLE_MAX_SLOTS)
|
||||
return original(slot0, inRange);
|
||||
const uint64_t unit = MacroUnit(slot0);
|
||||
if (unit == 0)
|
||||
return original(slot0, inRange);
|
||||
|
||||
const uint8_t *player = Unit::Identity::PlayerObject();
|
||||
if (player == nullptr)
|
||||
return 0;
|
||||
uint32_t pet = 0;
|
||||
const int spellID =
|
||||
reinterpret_cast<SlotToSpell_t>(Offsets::FUN_ACTION_SLOT_TO_SPELL)(slot0, &pet);
|
||||
const uint8_t *record = ::Spell::Lookup::RecordForID(spellID);
|
||||
if (record == nullptr || pet != 0)
|
||||
return 0;
|
||||
if (!reinterpret_cast<CheckRange_t>(Offsets::FUN_CHECK_SPELL_TARGET_RANGE)(
|
||||
player, record, static_cast<uint32_t>(unit), static_cast<uint32_t>(unit >> 32), 0)) {
|
||||
*inRange = 0;
|
||||
return 1;
|
||||
}
|
||||
const int32_t implicitTarget =
|
||||
Game::Read<int32_t>(record, Offsets::OFF_SPELL_RECORD_EFFECT_IMPLICIT_TARGET_A);
|
||||
if (!TakesUnitTarget(implicitTarget) || Object::ByGuid(Offsets::TYPEMASK_UNIT, unit) == nullptr)
|
||||
return 0;
|
||||
*inRange = 1;
|
||||
return 1;
|
||||
}
|
||||
|
||||
void Register() {
|
||||
Common::RedirectCall(Offsets::CALL_IS_ACTION_IN_RANGE_SLOT_RANGE,
|
||||
Offsets::FUN_ACTION_SLOT_RANGE,
|
||||
reinterpret_cast<const void *>(&SlotRange_h));
|
||||
}
|
||||
|
||||
const Game::ModuleAutoRegister _autoreg{&Register};
|
||||
|
||||
} // namespace
|
||||
|
||||
int Answer(int slot0, int *inRange) { return SlotRange_h(slot0, inRange); }
|
||||
|
||||
} // namespace Action::Range
|
||||
@@ -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 Action::Range {
|
||||
|
||||
// IsActionInRange's answer for a slot (0-based, 0..119): 0 when it has none
|
||||
// (IsActionInRange's nil), else 1 with `*inRange` 0 or 1. A macro aimed at a
|
||||
// unit is checked against that unit.
|
||||
int Answer(int slot0, int *inRange);
|
||||
|
||||
} // namespace Action::Range
|
||||
@@ -0,0 +1,144 @@
|
||||
// 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/>.
|
||||
|
||||
// `C_ActionBar.EnableActionRangeCheck(slot, enable)` and
|
||||
// `ACTION_RANGE_CHECK_UPDATE(slot, isInRange, checksRange)`.
|
||||
//
|
||||
// Nothing in the client reacts to a distance (see Unit::InRangeEvent), so the
|
||||
// enabled slots are checked every world tick, while a frame is registered for
|
||||
// the event, and a slot fires when its answer changes. The answer is
|
||||
// IsActionInRange's (Action::Range::Answer), macro unit included, so a slot
|
||||
// whose action changes fires when the new action's answer differs.
|
||||
//
|
||||
// Enabling is counted per slot, as retail's ActionBarButtonRangeCheckFrame
|
||||
// expects: it enables once for each button on a slot and disables once as
|
||||
// each button leaves. Retail's buttons never call IsActionInRange; they take
|
||||
// their first state from this event. So each enable makes the slot's next
|
||||
// check fire, changed or not. A new Lua state (`/reload`) starts with no slot
|
||||
// enabled.
|
||||
|
||||
#include "Game.h"
|
||||
#include "Offsets.h"
|
||||
#include "action/Range.h"
|
||||
#include "event/Custom.h"
|
||||
#include "tick/WorldTick.h"
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace Action::RangeCheck {
|
||||
|
||||
namespace {
|
||||
|
||||
enum class State : uint8_t { NoCheck, OutOfRange, InRange };
|
||||
|
||||
struct Slot {
|
||||
int refs = 0;
|
||||
bool pending = false; // fire on the next check, changed or not
|
||||
State last = State::NoCheck;
|
||||
};
|
||||
|
||||
Slot g_slots[Offsets::ACTION_TABLE_MAX_SLOTS];
|
||||
|
||||
const Game::Doc::Field kPayload[] = {
|
||||
Game::Doc::Req("slot", "luaIndex"),
|
||||
Game::Doc::Req("isInRange", "bool",
|
||||
"Whether the action's target is in range. Should not be used if checksRange "
|
||||
"is false."),
|
||||
Game::Doc::Req("checksRange", "bool",
|
||||
"False when no range check was made, for example when there is no target."),
|
||||
};
|
||||
const Game::Doc::Event kDoc{
|
||||
"ActionBar",
|
||||
"Fires when an action that has EnableActionRangeCheck on goes in or out of range of its "
|
||||
"target.",
|
||||
kPayload};
|
||||
const Event::Custom::AutoReserve kEvent{"ACTION_RANGE_CHECK_UPDATE", &kDoc};
|
||||
|
||||
State Evaluate(int slot0) {
|
||||
int inRange = 0;
|
||||
if (Action::Range::Answer(slot0, &inRange) == 0)
|
||||
return State::NoCheck;
|
||||
return inRange != 0 ? State::InRange : State::OutOfRange;
|
||||
}
|
||||
|
||||
void OnWorldTick() {
|
||||
const int event = kEvent.Slot();
|
||||
if (!Event::Custom::HasListeners(event))
|
||||
return;
|
||||
void *L = Game::Lua::State();
|
||||
if (L == nullptr)
|
||||
return;
|
||||
const int top = Game::Lua::GetTop(L);
|
||||
for (int slot0 = 0; slot0 < Offsets::ACTION_TABLE_MAX_SLOTS; ++slot0) {
|
||||
Slot &slot = g_slots[slot0];
|
||||
if (slot.refs == 0)
|
||||
continue;
|
||||
const State state = Evaluate(slot0);
|
||||
if (!slot.pending && state == slot.last)
|
||||
continue;
|
||||
slot.pending = false;
|
||||
slot.last = state;
|
||||
Game::Lua::PushNumber(L, static_cast<double>(slot0 + 1));
|
||||
Game::Lua::PushBool(L, state == State::InRange);
|
||||
Game::Lua::PushBool(L, state != State::NoCheck);
|
||||
Event::Custom::FireValues(event, L, top + 1, 3);
|
||||
Game::Lua::SetTop(L, top);
|
||||
}
|
||||
}
|
||||
|
||||
const Tick::WorldTick::AutoSubscribe _tick{&OnWorldTick};
|
||||
|
||||
// --- C_ActionBar.EnableActionRangeCheck(slot, enable) -----------------------
|
||||
|
||||
int __fastcall Script_EnableActionRangeCheck(void *L) {
|
||||
if (!Game::Lua::IsNumber(L, 1)) {
|
||||
Game::Lua::Error(L, "Usage: C_ActionBar.EnableActionRangeCheck(slot, enable)");
|
||||
return 0;
|
||||
}
|
||||
const int slot0 = static_cast<int>(Game::Lua::ToNumber(L, 1)) - 1;
|
||||
if (slot0 < 0 || slot0 >= Offsets::ACTION_TABLE_MAX_SLOTS)
|
||||
return 0;
|
||||
Slot &slot = g_slots[slot0];
|
||||
if (Game::Lua::ToBoolean(L, 2) != 0) {
|
||||
++slot.refs;
|
||||
slot.pending = true;
|
||||
} else if (slot.refs > 0) {
|
||||
--slot.refs;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
const Game::Doc::Field kEnableArgs[] = {
|
||||
Game::Doc::Req("slot", "luaIndex"),
|
||||
Game::Doc::Req("enable", "bool",
|
||||
"True if changes in range for the action should dispatch "
|
||||
"ACTION_RANGE_CHECK_UPDATE. False if the action no longer needs the event."),
|
||||
};
|
||||
const Game::Doc::Function kEnableDoc{
|
||||
"Used with ACTION_RANGE_CHECK_UPDATE to be informed when an action goes in or out of range "
|
||||
"of its target.",
|
||||
kEnableArgs};
|
||||
|
||||
void RegisterLuaFunctions() {
|
||||
for (Slot &slot : g_slots)
|
||||
slot = Slot{};
|
||||
Game::Lua::RegisterTableFunction("C_ActionBar", "EnableActionRangeCheck",
|
||||
&Script_EnableActionRangeCheck, &kEnableDoc);
|
||||
}
|
||||
|
||||
const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
|
||||
|
||||
} // namespace
|
||||
|
||||
} // namespace Action::RangeCheck
|
||||
+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,148 @@
|
||||
// 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 item behind an action slot, 4.3.4's CGActionBar::GetItem: an item-by-ID
|
||||
// action's item, or the item a macro's `#showtooltip` / `#show` resolved to
|
||||
// (1.12 keeps no item per macro, so `Macro::ShowTooltip` holds it). Both
|
||||
// readers below peek the item cache and never query it, as 4.3.4 does.
|
||||
//
|
||||
// IsStackableAction the item's max stack is more than 1 —
|
||||
// 4.3.4's IsStackableAucItem. The global
|
||||
// answers 1/nil, the C_ActionBar form a bool.
|
||||
// GetItemActionOnEquipSpellID the item's first on-equip spell (trigger 1),
|
||||
// nil when it has none.
|
||||
|
||||
#include "Game.h"
|
||||
#include "Offsets.h"
|
||||
#include "item/Record.h"
|
||||
#include "macro/ShowTooltip.h"
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace Action::SlotItem {
|
||||
|
||||
namespace {
|
||||
|
||||
uint32_t ItemForSlot(int slot0) {
|
||||
if (slot0 < 0 || slot0 >= Offsets::ACTION_TABLE_MAX_SLOTS)
|
||||
return 0;
|
||||
const uint32_t entry = reinterpret_cast<const uint32_t *>(
|
||||
static_cast<uintptr_t>(Offsets::VAR_ACTION_TABLE))[slot0];
|
||||
if ((entry & Offsets::ACTION_TYPE_MASK) == Offsets::ACTION_TYPE_ITEM_BY_ID)
|
||||
return entry & Offsets::ACTION_PAYLOAD_MASK_ITEM_BY_ID;
|
||||
Macro::ShowTooltip::Info info;
|
||||
if (Macro::ShowTooltip::ForSlot(slot0, &info) &&
|
||||
info.target == Macro::ShowTooltip::Target::Item)
|
||||
return static_cast<uint32_t>(info.itemID);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Reads the 1-based slot at stack[1]; false (after the usage error) when it
|
||||
// is not a number.
|
||||
bool SlotArg(void *L, const char *usage, int *slot0) {
|
||||
if (!Game::Lua::IsNumber(L, 1)) {
|
||||
Game::Lua::Error(L, usage);
|
||||
return false;
|
||||
}
|
||||
*slot0 = static_cast<int>(Game::Lua::ToNumber(L, 1)) - 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool IsStackable(int slot0) {
|
||||
const uint8_t *record = ::Item::PeekRecord(ItemForSlot(slot0));
|
||||
return record != nullptr && Game::Read<uint32_t>(record, Offsets::OFF_ITEMSTATS_STACKABLE) > 1;
|
||||
}
|
||||
|
||||
int __fastcall Script_IsStackableAction(void *L) {
|
||||
int slot0;
|
||||
if (!SlotArg(L, "Usage: IsStackableAction(slot)", &slot0))
|
||||
return 0;
|
||||
if (IsStackable(slot0))
|
||||
Game::Lua::PushNumber(L, 1.0);
|
||||
else
|
||||
Game::Lua::PushNil(L);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int __fastcall Script_C_IsStackableAction(void *L) {
|
||||
int slot0;
|
||||
if (!SlotArg(L, "Usage: C_ActionBar.IsStackableAction(actionID)", &slot0))
|
||||
return 0;
|
||||
Game::Lua::PushBool(L, IsStackable(slot0));
|
||||
return 1;
|
||||
}
|
||||
|
||||
int __fastcall Script_GetItemActionOnEquipSpellID(void *L) {
|
||||
int slot0;
|
||||
if (!SlotArg(L, "Usage: C_ActionBar.GetItemActionOnEquipSpellID(actionID)", &slot0))
|
||||
return 0;
|
||||
const uint8_t *record = ::Item::PeekRecord(ItemForSlot(slot0));
|
||||
if (record == nullptr)
|
||||
return 0;
|
||||
for (int i = 0; i < Offsets::ITEMSTATS_SPELL_SLOT_COUNT; ++i) {
|
||||
const uint32_t spellID = Game::Read<uint32_t>(record, Offsets::OFF_ITEMSTATS_SPELL_ID + i * 4);
|
||||
const uint32_t trigger = Game::Read<uint32_t>(record, Offsets::OFF_ITEMSTATS_SPELL_TRIGGER + i * 4);
|
||||
if (spellID != 0 && trigger == Offsets::ITEM_SPELLTRIGGER_ON_EQUIP) {
|
||||
Game::Lua::PushNumber(L, static_cast<double>(spellID));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
// --- Documentation ----------------------------------------------------------
|
||||
|
||||
const Game::Doc::Field kSlotArgs[] = {
|
||||
Game::Doc::Req("slot", "number", "The action slot, 1 to 120."),
|
||||
};
|
||||
const Game::Doc::Field kIsStackableRets[] = {
|
||||
Game::Doc::Opt("isStackable", "number", nullptr,
|
||||
"1 if the slot's item stacks, else nil."),
|
||||
};
|
||||
const Game::Doc::Function kIsStackableAction{
|
||||
"Returns 1 if an action slot holds an item that stacks.",
|
||||
kSlotArgs, kIsStackableRets, "ActionBar"};
|
||||
|
||||
const Game::Doc::Field kActionIDArgs[] = {
|
||||
Game::Doc::Req("actionID", "luaIndex"),
|
||||
};
|
||||
const Game::Doc::Field kCIsStackableRets[] = {
|
||||
Game::Doc::Req("isStackableAction", "bool"),
|
||||
};
|
||||
const Game::Doc::Function kCIsStackableAction{
|
||||
"Whether the action's item stacks.",
|
||||
kActionIDArgs, kCIsStackableRets};
|
||||
|
||||
const Game::Doc::Field kOnEquipRets[] = {
|
||||
Game::Doc::Opt("onEquipSpellID", "number", nullptr,
|
||||
"Nil when the action has no item or its item has no on-equip spell."),
|
||||
};
|
||||
const Game::Doc::Function kGetItemActionOnEquipSpellID{
|
||||
"The spell the action's item grants while equipped.",
|
||||
kActionIDArgs, kOnEquipRets};
|
||||
|
||||
} // namespace
|
||||
|
||||
static void RegisterLuaFunctions() {
|
||||
Game::Lua::RegisterGlobalFunction("IsStackableAction", &Script_IsStackableAction,
|
||||
&kIsStackableAction);
|
||||
Game::Lua::RegisterTableFunction("C_ActionBar", "IsStackableAction",
|
||||
&Script_C_IsStackableAction, &kCIsStackableAction);
|
||||
Game::Lua::RegisterTableFunction("C_ActionBar", "GetItemActionOnEquipSpellID",
|
||||
&Script_GetItemActionOnEquipSpellID,
|
||||
&kGetItemActionOnEquipSpellID);
|
||||
}
|
||||
|
||||
static const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
|
||||
|
||||
} // namespace Action::SlotItem
|
||||
@@ -0,0 +1,125 @@
|
||||
// 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/>.
|
||||
|
||||
// `ACTION_USABLE_CHANGED(changes)` — the slots whose usable / noMana pair
|
||||
// changed, as `{ slot, usable, noMana }` entries.
|
||||
//
|
||||
// The engine's bulk refresh FUN_ACTION_UPDATE_USABLE already finds them: it
|
||||
// computes each slot with FUN_ACTION_SLOT_USABLE, compares the pair against
|
||||
// the caches IsUsableAction reads, stores a changed pair, and signals the
|
||||
// argument-less ACTIONBAR_UPDATE_USABLE once when any changed. Two of its
|
||||
// calls are redirected. The per-slot call records the slots whose pair differs
|
||||
// from the caches, the same compare the engine makes next. The signal sends
|
||||
// ACTIONBAR_UPDATE_USABLE unchanged, then this event with the recorded slots.
|
||||
//
|
||||
// The per-slot refresh in FUN_ACTION_SLOT_CHANGED_NOTIFY stores its pair
|
||||
// without this event; it signals ACTIONBAR_SLOT_CHANGED for the slot instead.
|
||||
|
||||
#include "Common.h"
|
||||
#include "Game.h"
|
||||
#include "Offsets.h"
|
||||
#include "event/Custom.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
|
||||
namespace Action::UsableChanged {
|
||||
|
||||
namespace {
|
||||
|
||||
using SlotUsable_t = uint32_t(__fastcall *)(uint32_t slot0, uint32_t *outNoMana);
|
||||
using FireEvent_t = void(__fastcall *)(int eventID);
|
||||
|
||||
struct Change {
|
||||
uint32_t slot0;
|
||||
bool usable;
|
||||
bool noMana;
|
||||
};
|
||||
|
||||
// This refresh's changes. The loop runs slots 0..119 in order, so slot 0
|
||||
// starts a new list.
|
||||
Change g_changes[Offsets::ACTION_TABLE_MAX_SLOTS];
|
||||
int g_count = 0;
|
||||
|
||||
const Game::Doc::Field kStateFields[] = {
|
||||
Game::Doc::Req("slot", "luaIndex"),
|
||||
Game::Doc::Req("usable", "bool"),
|
||||
Game::Doc::Req("noMana", "bool"),
|
||||
};
|
||||
const Game::Doc::Structure kState{"ActionUsableState", "ActionBar", kStateFields};
|
||||
|
||||
const Game::Doc::Field kPayload[] = {
|
||||
Game::Doc::Req("changes", "table", "An ActionUsableState for each slot that changed."),
|
||||
};
|
||||
const Game::Doc::Event kDoc{
|
||||
"ActionBar", "Fires when the usable or noMana state of one or more action slots changes.",
|
||||
kPayload};
|
||||
const Event::Custom::AutoReserve kEvent{"ACTION_USABLE_CHANGED", &kDoc};
|
||||
|
||||
uint32_t __fastcall SlotUsable_h(uint32_t slot0, uint32_t *outNoMana) {
|
||||
const uint32_t usable =
|
||||
reinterpret_cast<SlotUsable_t>(Offsets::FUN_ACTION_SLOT_USABLE)(slot0, outNoMana);
|
||||
if (slot0 == 0)
|
||||
g_count = 0;
|
||||
const auto *usableCache =
|
||||
reinterpret_cast<const uint32_t *>(static_cast<uintptr_t>(Offsets::VAR_ACTION_USABLE));
|
||||
const auto *noManaCache =
|
||||
reinterpret_cast<const uint32_t *>(static_cast<uintptr_t>(Offsets::VAR_ACTION_NO_MANA));
|
||||
if (slot0 < static_cast<uint32_t>(Offsets::ACTION_TABLE_MAX_SLOTS) &&
|
||||
g_count < Offsets::ACTION_TABLE_MAX_SLOTS &&
|
||||
(usable != usableCache[slot0] || *outNoMana != noManaCache[slot0]))
|
||||
g_changes[g_count++] = {slot0, usable != 0, *outNoMana != 0};
|
||||
return usable;
|
||||
}
|
||||
|
||||
void __fastcall FireUsable_h(int eventID) {
|
||||
// Copied first: the handlers below can run another refresh.
|
||||
Change changes[Offsets::ACTION_TABLE_MAX_SLOTS];
|
||||
const int count = g_count;
|
||||
std::memcpy(changes, g_changes, sizeof(Change) * count);
|
||||
g_count = 0;
|
||||
|
||||
reinterpret_cast<FireEvent_t>(Offsets::FUN_FIRE_EVENT_NO_ARGS)(eventID);
|
||||
|
||||
const int event = kEvent.Slot();
|
||||
void *L = Game::Lua::State();
|
||||
if (count == 0 || !Event::Custom::HasListeners(event) || L == nullptr)
|
||||
return;
|
||||
const int top = Game::Lua::GetTop(L);
|
||||
Game::Lua::NewTable(L);
|
||||
for (int i = 0; i < count; ++i) {
|
||||
Game::Lua::PushNumber(L, static_cast<double>(i + 1));
|
||||
Game::Lua::NewTable(L);
|
||||
Game::Lua::SetFieldNumber(L, "slot", static_cast<double>(changes[i].slot0 + 1));
|
||||
Game::Lua::SetFieldBool(L, "usable", changes[i].usable);
|
||||
Game::Lua::SetFieldBool(L, "noMana", changes[i].noMana);
|
||||
Game::Lua::RawSet(L, -3);
|
||||
}
|
||||
Game::Lua::SetN(L, -1, count);
|
||||
Event::Custom::FireValues(event, L, top + 1, 1);
|
||||
Game::Lua::SetTop(L, top);
|
||||
}
|
||||
|
||||
void Register() {
|
||||
Common::RedirectCall(Offsets::CALL_UPDATE_USABLE_SLOT_USABLE, Offsets::FUN_ACTION_SLOT_USABLE,
|
||||
reinterpret_cast<const void *>(&SlotUsable_h));
|
||||
Common::RedirectCall(Offsets::CALL_UPDATE_USABLE_FIRE, Offsets::FUN_FIRE_EVENT_NO_ARGS,
|
||||
reinterpret_cast<const void *>(&FireUsable_h));
|
||||
}
|
||||
|
||||
const Game::ModuleAutoRegister _autoreg{&Register};
|
||||
|
||||
} // namespace
|
||||
|
||||
} // namespace Action::UsableChanged
|
||||
@@ -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
|
||||
+244
-218
@@ -11,31 +11,51 @@
|
||||
// You should have received a copy of the GNU General Public License along with
|
||||
// ClassicAPI. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
// Embedded `!!!ClassicAPI` addon fallback. When the user doesn't have
|
||||
// the addon installed on disk, this module makes the engine think it
|
||||
// does — without writing anything to the filesystem.
|
||||
// Embedded addons. When the user doesn't have an addon installed on disk,
|
||||
// this module makes the engine think they do — without writing anything
|
||||
// to the filesystem. The addons are `Manifest::kAddons` (the `ADDONS`
|
||||
// list in CMakeLists.txt): `!!!ClassicAPI`, which loads at login, and
|
||||
// `ClassicAPI_DebugTools` and `ClassicAPI_EventTrace`, which are
|
||||
// `## LoadOnDemand` behind the `/dump` / `/fstack` / `/etrace` stubs in
|
||||
// `!!!ClassicAPI` — retail's chat-frame + Blizzard_DebugTools /
|
||||
// Blizzard_EventTrace split. (The `Blizzard_` name is not
|
||||
// available to us: the engine moves loose `Interface\AddOns\Blizzard*`
|
||||
// folders aside at startup, `MoveAsideLooseInterface`, and refuses a
|
||||
// `Blizzard_*` TOC without a signature.)
|
||||
//
|
||||
// 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.
|
||||
// 1. The CMake build embeds each listed addon as one RCDATA resource,
|
||||
// a gzipped pack of its files, plus a generated
|
||||
// `{path, resourceId, index}` 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
|
||||
// `Interface\AddOns\!!!ClassicAPI\`, we allocate a Storm buffer
|
||||
// `Interface\AddOns\<embedded addon>\`, we allocate a Storm buffer
|
||||
// via the same allocator the engine itself uses, copy the
|
||||
// embedded content in, and hand it back. The caller's normal
|
||||
// `SMemFree` reclaims it on completion — no special lifetime.
|
||||
// A TOC then goes through `AddOns::TocRewrite`, as an installed
|
||||
// addon's does, so its file lines can carry `[AllowLoadGameType ...]`
|
||||
// / `[ExcludeLoadGameType ...]` conditions.
|
||||
//
|
||||
// 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 each embedded name before the scan runs. The registry
|
||||
// is empty there (the login init resets it just before), so our
|
||||
// entries are the first records and the load pass — which walks the
|
||||
// records in registration order — loads `!!!ClassicAPI` first. The
|
||||
// scan's own `## LoadWith:` pass then sees them like any disk addon.
|
||||
// The parser is dedup-safe: when the user also has an addon on disk,
|
||||
// the scan's call for that folder hits the hash table and is a no-op.
|
||||
//
|
||||
// Every embedded addon is hidden from the addon list and force-enabled,
|
||||
// the way Blizzard's own addons are always available and never listed.
|
||||
//
|
||||
// Same pattern WeirdUtils.dll uses (we reverse-engineered it from
|
||||
// `0x10015A74` while figuring this out). The addon load pass then
|
||||
@@ -43,10 +63,12 @@
|
||||
// `Compat.lua`, `Util\Print.lua`, etc. all surface from
|
||||
// embedded buffers.
|
||||
|
||||
#include "embedded_classicapi.h"
|
||||
#include "embedded_resources.h"
|
||||
|
||||
#include "Common.h"
|
||||
#include "Game.h"
|
||||
#include "Offsets.h"
|
||||
#include "addons/Embedded.h"
|
||||
#include "addons/EngineIO.h"
|
||||
#include "addons/FlavorBindings.h"
|
||||
#include "addons/FlavorToc.h"
|
||||
@@ -54,6 +76,7 @@
|
||||
#include "addons/Toc.h"
|
||||
#include "addons/TocRewrite.h"
|
||||
#include "bindings/Inject.h"
|
||||
#include "embed/Resource.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
@@ -63,69 +86,80 @@ namespace Addons::Embedded {
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr const char *kAddonName = "!!!ClassicAPI";
|
||||
constexpr const char *kAddonTocFile = "!!!ClassicAPI.toc";
|
||||
using Manifest::kAddonCount;
|
||||
using Manifest::kAddons;
|
||||
|
||||
// Developer marker. When this file exists in the on-disk addon folder,
|
||||
// the disk copy wins unconditionally (see `DiskHasDevMarker` /
|
||||
// `DecideSource`). It is gitignored, excluded from the embed, and the
|
||||
// release ships only the DLL — so it can only exist where a developer
|
||||
// deliberately created it, never in a normal user's install.
|
||||
// Developer marker. When this file exists in an on-disk addon folder,
|
||||
// the disk copy of that addon wins unconditionally (see
|
||||
// `DiskHasDevMarker` / `DecideSource`). It is gitignored, excluded from
|
||||
// the embed, and the release ships only the DLL — so it can only exist
|
||||
// where a developer deliberately created it, never in a normal user's
|
||||
// install.
|
||||
constexpr const char *kDevMarkerFile = ".classicapi-dev";
|
||||
|
||||
// `Interface\AddOns\!!!ClassicAPI\` — the prefix the engine
|
||||
// constructs for any of our addon's files. Comparing case-
|
||||
// `Interface\AddOns\` — the prefix the engine constructs for any addon
|
||||
// file; the manifest paths are relative to it. Comparing case-
|
||||
// insensitively because the TOC parser uses `Interface\AddOns\%s\…`
|
||||
// where %s comes from the on-disk directory name, and Windows file
|
||||
// paths are case-insensitive.
|
||||
constexpr const char *kAddonPathPrefix = "Interface\\AddOns\\!!!ClassicAPI\\";
|
||||
constexpr size_t kAddonPathPrefixLen = 30; // length of the literal above
|
||||
constexpr const char *kAddOnsPrefix = "Interface\\AddOns\\";
|
||||
|
||||
char NormalizeChar(char c) {
|
||||
if (c == '/') return '\\';
|
||||
if (c >= 'A' && c <= 'Z') return static_cast<char>(c + 32);
|
||||
return c;
|
||||
// `path` with the case-insensitive `prefix` stripped, NULL when it does
|
||||
// not start with it.
|
||||
const char *StripPrefixCI(const char *path, const char *prefix) {
|
||||
while (*prefix) {
|
||||
if (*path == '\0') return nullptr;
|
||||
if (Common::FoldPathChar(*path) != Common::FoldPathChar(*prefix)) return nullptr;
|
||||
++path; ++prefix;
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
bool PathEqualsCI(const char *a, const char *b) {
|
||||
while (*a && *b) {
|
||||
if (NormalizeChar(*a) != NormalizeChar(*b)) return false;
|
||||
++a; ++b;
|
||||
int IndexOfAddon(const char *name) {
|
||||
for (size_t i = 0; i < kAddonCount; ++i) {
|
||||
if (Common::SamePath(name, kAddons[i]))
|
||||
return static_cast<int>(i);
|
||||
}
|
||||
return *a == *b;
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Strip the `Interface\AddOns\!!!ClassicAPI\` prefix and return the
|
||||
// suffix (e.g. `Util\Print.lua`) on a match, NULL otherwise.
|
||||
const char *StripAddonPrefix(const char *path) {
|
||||
if (path == nullptr) return nullptr;
|
||||
const char *p = path;
|
||||
const char *q = kAddonPathPrefix;
|
||||
while (*q) {
|
||||
if (*p == '\0') return nullptr;
|
||||
if (NormalizeChar(*p) != NormalizeChar(*q)) return nullptr;
|
||||
++p; ++q;
|
||||
// The embedded addon `path` lies in (`Interface\AddOns\<addon>\…`), or -1.
|
||||
// `*relPath` gets the manifest-relative part (`<addon>\Util\Print.lua`).
|
||||
int MatchAddonPath(const char *path, const char **relPath) {
|
||||
if (path == nullptr) return -1;
|
||||
const char *rel = StripPrefixCI(path, kAddOnsPrefix);
|
||||
if (rel == nullptr) return -1;
|
||||
for (size_t i = 0; i < kAddonCount; ++i) {
|
||||
const char *rest = StripPrefixCI(rel, kAddons[i]);
|
||||
if (rest != nullptr && Common::FoldPathChar(*rest) == '\\') {
|
||||
*relPath = rel;
|
||||
return static_cast<int>(i);
|
||||
}
|
||||
}
|
||||
return p;
|
||||
return -1;
|
||||
}
|
||||
|
||||
const ClassicAPIFiles::File *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 nullptr;
|
||||
// The embedded bytes for manifest path `relPath`; `data` is NULL when it
|
||||
// is not embedded.
|
||||
Embed::Bytes LookupEmbedded(const char *relPath) {
|
||||
const Manifest::File *file = Embed::FindFile(Manifest::kFiles, relPath);
|
||||
if (file == nullptr)
|
||||
return {nullptr, 0};
|
||||
return Embed::File(file->resourceId, file->index);
|
||||
}
|
||||
|
||||
// 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 +171,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;
|
||||
}
|
||||
@@ -176,79 +210,63 @@ int CompareVersions(const char *a, const char *b) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Pre-extracted embedded TOC version, populated lazily on first
|
||||
// FileRead_h call under our prefix. Empty until populated.
|
||||
char g_embeddedVersion[64] = "";
|
||||
|
||||
// Which source wins the embed-vs-disk comparison, decided once on
|
||||
// first relevant file read.
|
||||
// Which source wins the embed-vs-disk comparison, decided per addon once
|
||||
// on its first file read.
|
||||
enum class Source { Undecided, Disk, Embedded };
|
||||
Source g_source = Source::Undecided;
|
||||
Source g_source[kAddonCount] = {};
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// True iff the on-disk addon folder contains the `.classicapi-dev`
|
||||
// marker. Read via the ORIGINAL `FUN_FILE_READ` (bypassing our embed
|
||||
// True iff addon `addon`'s on-disk folder contains the `.classicapi-dev`
|
||||
// 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
|
||||
// the release ships only the DLL, so a normal user's install can't
|
||||
// carry it.
|
||||
bool DiskHasDevMarker() {
|
||||
bool DiskHasDevMarker(int addon) {
|
||||
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;
|
||||
std::snprintf(fullPath, sizeof(fullPath), "%s%s\\%s", kAddOnsPrefix,
|
||||
kAddons[addon], kDevMarkerFile);
|
||||
return FileExists_o(fullPath, 1) != 0;
|
||||
}
|
||||
|
||||
// Decide whether disk or embedded should serve all reads for this
|
||||
// addon. Called on the first FileRead_h call with a matching prefix.
|
||||
// The `.classicapi-dev` marker forces disk unconditionally (explicit
|
||||
// developer override). Otherwise reads the on-disk TOC via the original
|
||||
// `FUN_FILE_READ` (bypassing our hook), parses its version, compares to
|
||||
// the embedded version, and caches the newer. If disk has no TOC at
|
||||
// all, embedded wins by default.
|
||||
void DecideSource() {
|
||||
if (g_source != Source::Undecided) return;
|
||||
EnsureEmbeddedVersionExtracted();
|
||||
// Decide whether disk or embedded should serve all reads for addon
|
||||
// `addon`. Called on the first FileRead_h / FileExists_h call under its
|
||||
// folder. The `.classicapi-dev` marker forces disk unconditionally
|
||||
// (explicit developer override). Otherwise reads the on-disk TOC via the
|
||||
// original `FUN_FILE_READ` (bypassing our hook), parses its version,
|
||||
// compares to the embedded version, and caches the newer. If disk has no
|
||||
// TOC at all, embedded wins by default.
|
||||
void DecideSource(int addon) {
|
||||
if (g_source[addon] != Source::Undecided) return;
|
||||
|
||||
// Explicit developer override: disk wins regardless of version. This
|
||||
// is how a dev keeps disk precedence when running local Lua against a
|
||||
// *released* DLL (where the embedded version would otherwise be newer
|
||||
// and win). Dev intent lives in this marker, decoupled from the toc
|
||||
// version — so users never get silently shadowed by a stray copy.
|
||||
if (DiskHasDevMarker()) {
|
||||
g_source = Source::Disk;
|
||||
if (DiskHasDevMarker(addon)) {
|
||||
g_source[addon] = Source::Disk;
|
||||
return;
|
||||
}
|
||||
|
||||
char embeddedVersion[64] = "";
|
||||
char tocRelPath[256];
|
||||
std::snprintf(tocRelPath, sizeof(tocRelPath), "%s\\%s.toc",
|
||||
kAddons[addon], kAddons[addon]);
|
||||
const Embed::Bytes toc = LookupEmbedded(tocRelPath);
|
||||
if (toc.data != nullptr)
|
||||
ExtractTocVersion(reinterpret_cast<const char *>(toc.data), toc.size,
|
||||
embeddedVersion, sizeof(embeddedVersion));
|
||||
|
||||
char fullPath[256];
|
||||
std::snprintf(fullPath, sizeof(fullPath), "%s%s",
|
||||
kAddonPathPrefix, kAddonTocFile);
|
||||
std::snprintf(fullPath, sizeof(fullPath), "%s%s", kAddOnsPrefix,
|
||||
tocRelPath);
|
||||
|
||||
void *diskBuf = nullptr;
|
||||
size_t diskSize = 0;
|
||||
const int ok = FileRead_o(0, fullPath, &diskBuf, &diskSize, 1, 1, 0);
|
||||
if (ok == 0 || diskBuf == nullptr) {
|
||||
g_source = Source::Embedded;
|
||||
g_source[addon] = Source::Embedded;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -265,12 +283,55 @@ void DecideSource() {
|
||||
// Missing or unparseable disk version → assume it's older than
|
||||
// anything we ship, embedded wins.
|
||||
if (diskVersion[0] == '\0') {
|
||||
g_source = Source::Embedded;
|
||||
g_source[addon] = Source::Embedded;
|
||||
return;
|
||||
}
|
||||
|
||||
const int cmp = CompareVersions(g_embeddedVersion, diskVersion);
|
||||
g_source = (cmp > 0) ? Source::Embedded : Source::Disk;
|
||||
const int cmp = CompareVersions(embeddedVersion, diskVersion);
|
||||
g_source[addon] = (cmp > 0) ? Source::Embedded : Source::Disk;
|
||||
}
|
||||
|
||||
// Serves one file of embedded addon `addon` from whichever source won
|
||||
// DecideSource.
|
||||
int ReadAddonFile(int addon, const char *relPath, int unused, const char *path,
|
||||
void **outBuf, size_t *outSize, size_t extraBytes, int flag1,
|
||||
int flag2) {
|
||||
DecideSource(addon);
|
||||
|
||||
if (g_source[addon] == Source::Disk) {
|
||||
// Disk version is at least as new — serve disk. If disk
|
||||
// doesn't have this specific file (e.g. embedded has files
|
||||
// disk doesn't), fall through and try embedded.
|
||||
const int diskResult = FileRead_o(unused, path, outBuf, outSize,
|
||||
extraBytes, flag1, flag2);
|
||||
if (diskResult != 0) return diskResult;
|
||||
}
|
||||
|
||||
// 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 Embed::Bytes entry = LookupEmbedded(relPath);
|
||||
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
|
||||
// missing some file.
|
||||
return FileRead_o(unused, path, outBuf, outSize, extraBytes,
|
||||
flag1, flag2);
|
||||
}
|
||||
|
||||
auto SMemAlloc = reinterpret_cast<SMemAllocFn>(
|
||||
Offsets::FUN_STORM_SMEM_ALLOC);
|
||||
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);
|
||||
if (extraBytes > 0) {
|
||||
std::memset(static_cast<uint8_t *>(buf) + entry.size, 0, extraBytes);
|
||||
}
|
||||
if (outBuf != nullptr) *outBuf = buf;
|
||||
if (outSize != nullptr) *outSize = entry.size;
|
||||
return 1;
|
||||
}
|
||||
|
||||
int __stdcall FileRead_h(int unused, const char *path, void **outBuf,
|
||||
@@ -284,9 +345,10 @@ int __stdcall FileRead_h(int unused, const char *path, void **outBuf,
|
||||
return 1;
|
||||
}
|
||||
|
||||
const char *suffix = StripAddonPrefix(path);
|
||||
if (suffix == nullptr) {
|
||||
// Not our embedded addon. If this is a base-TOC read for a multi-flavor
|
||||
const char *relPath = nullptr;
|
||||
const int addon = MatchAddonPath(path, &relPath);
|
||||
if (addon < 0) {
|
||||
// Not an embedded addon. If this is a base-TOC read for a multi-flavor
|
||||
// addon that ships only `<Name>_Turtle.toc` / `_ClassicAPI.toc`, serve
|
||||
// that in place of the missing `<Name>.toc` so it registers and loads
|
||||
// (see addons/FlavorToc.h).
|
||||
@@ -315,141 +377,96 @@ int __stdcall FileRead_h(int unused, const char *path, void **outBuf,
|
||||
return result;
|
||||
}
|
||||
|
||||
DecideSource();
|
||||
|
||||
if (g_source == Source::Disk) {
|
||||
// Disk version is at least as new — serve disk. If disk
|
||||
// doesn't have this specific file (e.g. embedded has files
|
||||
// disk doesn't), fall through and try embedded.
|
||||
const int diskResult = FileRead_o(unused, path, outBuf, outSize,
|
||||
extraBytes, flag1, flag2);
|
||||
if (diskResult != 0) return diskResult;
|
||||
}
|
||||
|
||||
// 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) {
|
||||
// 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
|
||||
// missing some file.
|
||||
return FileRead_o(unused, path, outBuf, outSize, extraBytes,
|
||||
flag1, flag2);
|
||||
}
|
||||
|
||||
auto SMemAlloc = reinterpret_cast<SMemAllocFn>(
|
||||
Offsets::FUN_STORM_SMEM_ALLOC);
|
||||
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);
|
||||
if (extraBytes > 0) {
|
||||
std::memset(static_cast<uint8_t *>(buf) + entry->size, 0, extraBytes);
|
||||
}
|
||||
if (outBuf != nullptr) *outBuf = buf;
|
||||
if (outSize != nullptr) *outSize = entry->size;
|
||||
return 1;
|
||||
// An embedded addon's TOC takes the same per-line directives as an
|
||||
// installed addon's, whichever source serves it.
|
||||
const int result = ReadAddonFile(addon, relPath, unused, path, outBuf, outSize,
|
||||
extraBytes, flag1, flag2);
|
||||
if (result != 0)
|
||||
AddOns::TocRewrite::Transform(path, outBuf, outSize);
|
||||
return result;
|
||||
}
|
||||
|
||||
// `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 *relPath = nullptr;
|
||||
const int addon = MatchAddonPath(path, &relPath);
|
||||
if (addon < 0) {
|
||||
if (FileExists_o(path, mode) != 0)
|
||||
return 1;
|
||||
return AddOns::FlavorBindings::TryExists(path, mode, FileExists_o) ? 1 : 0;
|
||||
}
|
||||
|
||||
DecideSource(addon);
|
||||
if (g_source[addon] == Source::Disk && FileExists_o(path, mode) != 0)
|
||||
return 1;
|
||||
if (LookupEmbedded(relPath).data != nullptr)
|
||||
return 1;
|
||||
return FileExists_o(path, mode);
|
||||
}
|
||||
|
||||
// `FUN_ADDON_SCAN_FULL` — `void __cdecl()`. We pre-hook it: register the
|
||||
// embedded addons 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
|
||||
// this byte is 0, so setting it hides `!!!ClassicAPI` from the
|
||||
// this byte is 0, so setting it hides an embedded addon from the
|
||||
// character-select AddOns list — there's no checkbox, so it can't be
|
||||
// toggled off. The builder only ever *writes* this byte on the
|
||||
// secure/SMSG path (`entry+0x28 != 0`); our entry is non-secure, so a
|
||||
// manual `1` here is stable across rebuilds. Hiding does NOT stop
|
||||
// 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).
|
||||
// addon hash table, which keeps the entry regardless — `LoadAddOn` of a
|
||||
// hidden load-on-demand entry still works).
|
||||
//
|
||||
// DefaultState (`+0x2b`) needs no write: the entry constructor
|
||||
// `FUN_00520550` stores 1 there, our tocs have 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.
|
||||
void FinalizeEmbeddedEntry() {
|
||||
Addons::ForEachEntry([](uintptr_t entry) -> bool {
|
||||
// Post-registration finalize for the embedded entries: hide them from the
|
||||
// addon list. Combined with the `FUN_ADDON_ENABLE_RESOLVE` co-hook, an
|
||||
// embedded addon is always loadable and never appears as a toggleable
|
||||
// entry.
|
||||
void FinalizeEmbeddedEntries() {
|
||||
Addons::ForEachEntry([](uintptr_t entry) {
|
||||
const char *name = *reinterpret_cast<const char *const *>(
|
||||
entry + Offsets::OFF_ADDON_ENTRY_NAME_PTR);
|
||||
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
|
||||
if (name != nullptr && IndexOfAddon(name) >= 0)
|
||||
*reinterpret_cast<uint8_t *>(
|
||||
entry + Offsets::OFF_ADDON_ENTRY_FILTER_OUT) = 1;
|
||||
});
|
||||
}
|
||||
|
||||
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();
|
||||
for (size_t i = 0; i < kAddonCount; ++i)
|
||||
TocParser(kAddons[i]);
|
||||
FinalizeEmbeddedEntries();
|
||||
AddonScan_o();
|
||||
}
|
||||
|
||||
// `FUN_ADDON_ENABLE_RESOLVE` — per-character enable resolver. We
|
||||
// co-hook it to force-enable `!!!ClassicAPI` regardless of DefaultState
|
||||
// or any stale WTF disable-override, so hiding it from the addon list
|
||||
// can never leave it stuck off. Returns 2 ("enabled for all"); the
|
||||
// load-pass gate only tests `!= 0`. Every other addon falls through to
|
||||
// the original untouched. See the Offsets.h note for the ABI.
|
||||
// co-hook it to force-enable the embedded addons regardless of
|
||||
// DefaultState or any stale WTF disable-override, so hiding them from
|
||||
// the addon list can never leave one stuck off. Returns 2 ("enabled for
|
||||
// all"); the load-pass gate only tests `!= 0`. Every other addon falls
|
||||
// through to the original untouched. See the Offsets.h note for the ABI.
|
||||
using AddonEnableResolve_t =
|
||||
uint32_t(__fastcall *)(const char *name, const char *account, char resolveAll);
|
||||
AddonEnableResolve_t AddonEnableResolve_o = nullptr;
|
||||
|
||||
uint32_t __fastcall AddonEnableResolve_h(const char *name, const char *account,
|
||||
char resolveAll) {
|
||||
if (name != nullptr && PathEqualsCI(name, kAddonName))
|
||||
if (name != nullptr && IndexOfAddon(name) >= 0)
|
||||
return 2;
|
||||
return AddonEnableResolve_o(name, account, resolveAll);
|
||||
}
|
||||
@@ -459,10 +476,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,
|
||||
@@ -471,4 +493,8 @@ const Game::HookAutoRegister _hookEnableResolve{
|
||||
|
||||
} // namespace
|
||||
|
||||
bool IsEmbedded(const char *name) {
|
||||
return name != nullptr && IndexOfAddon(name) >= 0;
|
||||
}
|
||||
|
||||
} // namespace Addons::Embedded
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
// 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 Addons::Embedded {
|
||||
|
||||
// True when `name` is one of the addons embedded in the DLL (compared
|
||||
// ignoring case). Their registry entries are owned by `Addons::Embedded`:
|
||||
// registered first, hidden from the addon list, force-enabled.
|
||||
bool IsEmbedded(const char *name);
|
||||
|
||||
} // namespace Addons::Embedded
|
||||
@@ -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
|
||||
|
||||
+51
-48
@@ -27,6 +27,7 @@
|
||||
#include "Game.h"
|
||||
#include "Offsets.h"
|
||||
#include "addons/LoadState.h"
|
||||
#include "addons/Registry.h"
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
@@ -35,6 +36,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);
|
||||
@@ -43,9 +45,8 @@ using CanLoadFn_t = uint8_t(__fastcall *)(const uint8_t *entry, char fullCheck,
|
||||
const char *accountName);
|
||||
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 + 0x48`), NULL on miss. We use it only to recover the
|
||||
// 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
|
||||
@@ -53,8 +54,7 @@ using ResolveReqDeps_t = uint8_t *(__fastcall *)(const char *nameOrEntry);
|
||||
// a NUL-terminated string starting at the input pointer and case-
|
||||
// insensitively match it against the registry, so either of these
|
||||
// shapes works:
|
||||
// - an AddOnEntry pointer from `GetByIndex` (the entry's first
|
||||
// 12 bytes ARE the inline name buffer)
|
||||
// - the name pointer `GetByIndex` returns (`[entry+0x14]`)
|
||||
// - a raw `const char *` to a Lua string
|
||||
//
|
||||
// Mirrors `Script_GetAddOnInfo`'s own input handling exactly — it
|
||||
@@ -264,11 +264,10 @@ int __fastcall Script_GetAddOnSecurity(void *L) {
|
||||
// tracks from the loader itself.
|
||||
//
|
||||
// Resolves both numeric indices (via `FUN_ADDON_GET_BY_INDEX`) and
|
||||
// string names. `IS_LOADED` accepts an entry pointer as its name arg
|
||||
// because the entry's first 12 bytes are the inline NUL-terminated
|
||||
// directory name (same as the other per-field accessors), so we can
|
||||
// feed it either an entry or a Lua-side string transparently — and that
|
||||
// same pointer is the name `LoadState` matches on.
|
||||
// string names. `FUN_ADDON_GET_BY_INDEX` returns the entry's name
|
||||
// pointer, so `IS_LOADED` (like the other per-field accessors) takes
|
||||
// either that or a Lua-side string transparently — and that same
|
||||
// pointer is the name `LoadState` matches on.
|
||||
int __fastcall Script_IsAddOnLoaded(void *L) {
|
||||
const uint8_t *entry = ResolveAddOnName(L);
|
||||
if (entry == nullptr) {
|
||||
@@ -311,46 +310,20 @@ int __fastcall Script_DoesAddOnExist(void *L) {
|
||||
// `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 = Addons::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 +333,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 = Addons::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 +368,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,11 +405,10 @@ static void RegisterLuaFunctions() {
|
||||
static_cast<uintptr_t>(Offsets::FUN_SCRIPT_LOAD_ADDON)));
|
||||
Game::Lua::RegisterTableFunction("C_AddOns", "GetAddOnOptionalDependencies",
|
||||
&Script_GetAddOnOptionalDependencies);
|
||||
Game::Lua::RegisterIntegerEnum(
|
||||
"Enum", "AddOnSecurityStatus",
|
||||
kAddOnSecurityStatusEntries,
|
||||
sizeof(kAddOnSecurityStatusEntries) /
|
||||
sizeof(kAddOnSecurityStatusEntries[0]));
|
||||
Game::Lua::RegisterTableFunction("C_AddOns", "GetAddOnInterfaceVersion",
|
||||
&Script_GetAddOnInterfaceVersion,
|
||||
&kGetAddOnInterfaceVersion);
|
||||
Game::Lua::RegisterIntegerEnum("Enum", "AddOnSecurityStatus", kAddOnSecurityStatusEntries);
|
||||
}
|
||||
|
||||
static const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
// 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/>.
|
||||
|
||||
// `UpdateAddOnMemoryUsage()` / `GetAddOnMemoryUsage(index or "name")` —
|
||||
// 3.3.5's `Script_UpdateAddOnMemoryUsage` (0x00511510) and
|
||||
// `Script_GetAddOnMemoryUsage` (0x00511530) over `Gc::Tag`.
|
||||
//
|
||||
// An addon's tag is its registry name pointer `[entry+0x14]`: the exact
|
||||
// pointer `FUN_ADDON_LOAD_ONE` installs as the context word while the
|
||||
// addon's files run (and the one 3.3.5's `GetAddOnName` returns), so the
|
||||
// lookup is a pointer match like 3.3.5's `luaC_getsize`. Secure addons run
|
||||
// under context 0, are never tagged, and read 0 — as in 3.3.5.
|
||||
//
|
||||
// 3.3.5's `LoadAddOn` also pins `lua_gctag` to the addon for its whole
|
||||
// file / Bindings / SavedVariables window, so objects made there stay the
|
||||
// addon's even when its code switches the context word (calling into another
|
||||
// addon's function or table makes that addon's word current). The 1.12 loader
|
||||
// has the same window; two 5-byte call patches open and close a `Gc::Tag` pin
|
||||
// at its edges (SITE_ADDON_LOAD_WINDOW_OPEN / _CLOSE).
|
||||
|
||||
#include "Common.h"
|
||||
#include "Game.h"
|
||||
#include "Offsets.h"
|
||||
#include "addons/Registry.h"
|
||||
#include "gc/Tag.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
|
||||
namespace AddOns::MemoryUsage {
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr uintptr_t addrExecContextDepth = Offsets::VAR_FRAMESCRIPT_EXEC_CONTEXT_DEPTH;
|
||||
|
||||
// The loader's own context value: the name for an insecure addon, 0 for a
|
||||
// secure one (3.3.5's `addon->m_status ? addonName : nullptr`). A 0 pin means
|
||||
// "no override", so a secure addon's window keeps following the context word.
|
||||
void __fastcall OpenLoadWindow(const uint8_t *entry) {
|
||||
const bool insecure = Game::Read<uint32_t>(entry, Offsets::OFF_ADDON_ENTRY_STATUS) != 0;
|
||||
Gc::Tag::PushPin(insecure ? Game::Read<const char *>(entry, Offsets::OFF_ADDON_ENTRY_NAME_PTR)
|
||||
: nullptr);
|
||||
}
|
||||
|
||||
void CloseLoadWindow() { Gc::Tag::PopPin(); }
|
||||
|
||||
// Stands in for `xor eax,eax; lea ecx,[ebp-0x18]` at the window's open.
|
||||
// EBX = the entry; EBP is the loader's frame.
|
||||
__declspec(naked) void LoadWindowOpenThunk() {
|
||||
__asm {
|
||||
pushad
|
||||
mov ecx, ebx
|
||||
call OpenLoadWindow
|
||||
popad
|
||||
xor eax, eax
|
||||
lea ecx, [ebp - 18h]
|
||||
ret
|
||||
}
|
||||
}
|
||||
|
||||
// Stands in for `mov eax,[VAR_FRAMESCRIPT_EXEC_CONTEXT_DEPTH]` at the close.
|
||||
__declspec(naked) void LoadWindowCloseThunk() {
|
||||
__asm {
|
||||
pushad
|
||||
call CloseLoadWindow
|
||||
popad
|
||||
mov eax, addrExecContextDepth
|
||||
mov eax, [eax]
|
||||
ret
|
||||
}
|
||||
}
|
||||
|
||||
void PatchLoadWindow() {
|
||||
static const uint8_t kOpen[5] = {0x33, 0xC0, 0x8D, 0x4D, 0xE8};
|
||||
static const uint8_t kClose[5] = {0xA1, 0xC4, 0xEA, 0xCE, 0x00};
|
||||
Common::ReplaceWithCall(Offsets::SITE_ADDON_LOAD_WINDOW_OPEN, kOpen, sizeof kOpen,
|
||||
reinterpret_cast<const void *>(&LoadWindowOpenThunk));
|
||||
Common::ReplaceWithCall(Offsets::SITE_ADDON_LOAD_WINDOW_CLOSE, kClose, sizeof kClose,
|
||||
reinterpret_cast<const void *>(&LoadWindowCloseThunk));
|
||||
}
|
||||
|
||||
int __fastcall Script_UpdateAddOnMemoryUsage(void *L) {
|
||||
Gc::Tag::UpdateUsage(L);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int __fastcall Script_GetAddOnMemoryUsage(void *L) {
|
||||
const uint8_t *record =
|
||||
Addons::ResolveRecord(L, "Usage: GetAddOnMemoryUsage(index or \"name\")");
|
||||
const char *tag =
|
||||
record != nullptr
|
||||
? Game::Read<const char *>(record, Offsets::OFF_ADDON_ENTRY_NAME_PTR)
|
||||
: nullptr;
|
||||
const uint64_t bytes = tag != nullptr ? Gc::Tag::Usage(tag) : 0;
|
||||
Game::Lua::PushNumber(L, static_cast<double>(bytes) * (1.0 / 1024.0));
|
||||
return 1;
|
||||
}
|
||||
|
||||
// `_classicapi_LuaHeapAudit()` → objectBytes, nblocks, taggedObjects.
|
||||
// Sums `Gc::Tag::SizeOf` over every collectable object the engine can
|
||||
// reach. `objectBytes` should sit just under `nblocks` (the engine's own
|
||||
// byte count): the gap is what is not a GC object (string-table buckets,
|
||||
// the main thread and its stack, buffers). A gap that grows with the heap
|
||||
// means a size formula is wrong.
|
||||
int __fastcall Script_LuaHeapAudit(void *L) {
|
||||
uint64_t bytes = 0;
|
||||
Gc::Tag::ForEachObject(L, [&bytes](const void *object) { bytes += Gc::Tag::SizeOf(object); });
|
||||
const uint8_t *g = Game::Read<const uint8_t *>(L, Offsets::OFF_LUA_STATE_G);
|
||||
Game::Lua::PushNumber(L, static_cast<double>(bytes));
|
||||
Game::Lua::PushNumber(L, static_cast<double>(Game::Read<uint32_t>(g, Offsets::OFF_LUA_G_NBLOCKS)));
|
||||
Game::Lua::PushNumber(L, static_cast<double>(Gc::Tag::TaggedCount()));
|
||||
return 3;
|
||||
}
|
||||
|
||||
// `_classicapi_GcTagOf(value)` → the owner tag of a table / function /
|
||||
// userdata / thread: the addon's name when the tag is an addon's, else the
|
||||
// raw context word as "0x…" (e.g. RunScript's), nil when untagged.
|
||||
int __fastcall Script_GcTagOf(void *L) {
|
||||
const char *tag = Gc::Tag::Of(Game::Lua::ToPointer(L, 1));
|
||||
if (tag == nullptr) {
|
||||
Game::Lua::PushNil(L);
|
||||
return 1;
|
||||
}
|
||||
const char *name = nullptr;
|
||||
Addons::ForEachEntry([&](uintptr_t entry) {
|
||||
if (Game::Read<const char *>(entry + Offsets::OFF_ADDON_ENTRY_NAME_PTR) != tag)
|
||||
return true;
|
||||
name = tag;
|
||||
return false;
|
||||
});
|
||||
if (name != nullptr) {
|
||||
Game::Lua::PushString(L, name);
|
||||
} else {
|
||||
char buf[16];
|
||||
std::snprintf(buf, sizeof buf, "0x%08X", static_cast<unsigned>(reinterpret_cast<uintptr_t>(tag)));
|
||||
Game::Lua::PushString(L, buf);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
const Game::Doc::Function kUpdateAddOnMemoryUsage{
|
||||
"Recounts the memory each addon uses; GetAddOnMemoryUsage returns the result of the "
|
||||
"last recount.",
|
||||
{}, {}, "AddOnsGlobals"};
|
||||
|
||||
const Game::Doc::Field kGetArgs[] = {
|
||||
Game::Doc::Req("name", "uiAddon", "An addon index or folder name."),
|
||||
};
|
||||
const Game::Doc::Field kGetRets[] = {
|
||||
Game::Doc::Req("memory", "number",
|
||||
"Kilobytes of Lua memory the addon's code allocated, as of the last "
|
||||
"UpdateAddOnMemoryUsage."),
|
||||
};
|
||||
const Game::Doc::Function kGetAddOnMemoryUsage{
|
||||
"Returns the Lua memory an addon uses, in kilobytes, as of the last "
|
||||
"UpdateAddOnMemoryUsage.",
|
||||
kGetArgs, kGetRets, "AddOnsGlobals"};
|
||||
|
||||
} // namespace
|
||||
|
||||
static void RegisterLuaFunctions() {
|
||||
// Each pass runs before the load pass; the patch is idempotent.
|
||||
PatchLoadWindow();
|
||||
Game::Lua::RegisterGlobalFunction("UpdateAddOnMemoryUsage", &Script_UpdateAddOnMemoryUsage,
|
||||
&kUpdateAddOnMemoryUsage);
|
||||
Game::Lua::RegisterGlobalFunction("GetAddOnMemoryUsage", &Script_GetAddOnMemoryUsage,
|
||||
&kGetAddOnMemoryUsage);
|
||||
Game::Lua::RegisterGlobalFunction("_classicapi_LuaHeapAudit", &Script_LuaHeapAudit);
|
||||
Game::Lua::RegisterGlobalFunction("_classicapi_GcTagOf", &Script_GcTagOf);
|
||||
}
|
||||
|
||||
static const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
|
||||
|
||||
} // namespace AddOns::MemoryUsage
|
||||
@@ -0,0 +1,63 @@
|
||||
// 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 "addons/Registry.h"
|
||||
|
||||
#include "Game.h"
|
||||
|
||||
namespace Addons {
|
||||
|
||||
namespace {
|
||||
|
||||
using GetByIndex_t = void *(__fastcall *)(int idx0Based);
|
||||
using GetAddOnCount_t = int(__fastcall *)();
|
||||
using ResolveReqDeps_t = uint8_t *(__fastcall *)(const char *name);
|
||||
|
||||
} // namespace
|
||||
|
||||
// Either input is 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;
|
||||
}
|
||||
|
||||
} // namespace Addons
|
||||
+13
-4
@@ -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));
|
||||
@@ -47,4 +47,13 @@ template <typename Fn> void ForEachEntry(Fn fn) {
|
||||
}
|
||||
}
|
||||
|
||||
// Resolves Lua arg 1 (index or name) to the addon's registry record, with
|
||||
// the arg handling of stock `Script_GetAddOnDependencies` (`0x0048E5E0`) —
|
||||
// the same shape 3.3.5 gives every `(index or "name")` addon global:
|
||||
// `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.
|
||||
const uint8_t *ResolveRecord(void *L, const char *usage);
|
||||
|
||||
} // namespace Addons
|
||||
|
||||
+32
-76
@@ -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
|
||||
@@ -62,14 +61,14 @@
|
||||
// bytes cleared), and the load pass hasn't — nothing holds entry state.
|
||||
//
|
||||
// Excluded from the evict path (everything else is fair game):
|
||||
// - `!!!ClassicAPI` — embedded; `Addons::Embedded` owns its entry
|
||||
// (head re-link + filter byte);
|
||||
// - the embedded addons — `Addons::Embedded` owns their entries
|
||||
// (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,13 +77,13 @@
|
||||
// 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"
|
||||
#include "addons/Embedded.h"
|
||||
#include "addons/EngineIO.h"
|
||||
#include "addons/Registry.h"
|
||||
|
||||
@@ -102,11 +101,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,53 +158,13 @@ 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.
|
||||
constexpr const char *kEmbeddedAddon = "!!!ClassicAPI";
|
||||
|
||||
// name → FNV-1a hash of the addon's `##` lines, as last parsed.
|
||||
// Per-process on purpose: the registry persists across /reload, and a
|
||||
// stale hash after a full re-login scan only causes one harmless
|
||||
@@ -263,11 +218,12 @@ uint32_t HashTocMetadata(const char *buf, size_t size) {
|
||||
return h;
|
||||
}
|
||||
|
||||
// True when the entry never takes the evict path: the embedded addon
|
||||
// (owned by `Addons::Embedded`) and SMSG-managed secure entries (the
|
||||
// parser cannot restore packet-delivered state).
|
||||
// True when the entry never takes the evict path: the embedded addons
|
||||
// (owned by `Addons::Embedded` — registered first + filter byte) and
|
||||
// SMSG-managed secure entries (the parser cannot restore packet-delivered
|
||||
// state).
|
||||
bool IsRefreshExempt(uintptr_t entry, const char *name) {
|
||||
return name == nullptr || std::strcmp(name, kEmbeddedAddon) == 0 ||
|
||||
return name == nullptr || Addons::Embedded::IsEmbedded(name) ||
|
||||
*reinterpret_cast<const uint8_t *>(
|
||||
entry + Offsets::OFF_ADDON_ENTRY_SECURE) != 0;
|
||||
}
|
||||
@@ -415,7 +371,7 @@ void FixupReverseLoadWith(const std::vector<uintptr_t> &added) {
|
||||
// `FUN_0051DA70` phase 2, mirrored (never call that function itself —
|
||||
// its phase 1 consumes an SMSG_ADDON_INFO packet): rebuild the
|
||||
// `GetNumAddOns`/`GetAddOnInfo(i)` name-pointer array from the linked
|
||||
// list, skipping filtered entries (keeps `!!!ClassicAPI` hidden), then
|
||||
// list, skipping filtered entries (keeps the embedded addons hidden), then
|
||||
// sort with the engine's own comparator to restore alphabetical order.
|
||||
void RebuildDisplayArray() {
|
||||
auto desc = reinterpret_cast<Desc *>(
|
||||
@@ -437,13 +393,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;
|
||||
}
|
||||
|
||||
+34
-27
@@ -14,8 +14,10 @@
|
||||
#include "addons/EngineIO.h"
|
||||
#include "addons/TocRewrite.h"
|
||||
#include "addons/Toc.h"
|
||||
#include "localization/Locale.h"
|
||||
|
||||
#include "Offsets.h"
|
||||
#include "turtle/Detect.h"
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
@@ -33,17 +35,7 @@ using AddOns::Toc::Lower;
|
||||
|
||||
bool IsSpace(char c) { return c == ' ' || c == '\t'; }
|
||||
|
||||
// The client locale code ("enUS", "frFR", …) — the exact string
|
||||
// GetLocale() returns (Offsets.h VAR_LOCALE_NAME_TABLE derivation).
|
||||
const char *ClientLocale() {
|
||||
uint32_t idx = *reinterpret_cast<const uint32_t *>(
|
||||
static_cast<uintptr_t>(Offsets::VAR_LOCALE_INDEX));
|
||||
if (idx > 7) idx = 0; // slot 8 overreads the string pool — clamp
|
||||
const char *const *table = reinterpret_cast<const char *const *>(
|
||||
static_cast<uintptr_t>(Offsets::VAR_LOCALE_NAME_TABLE));
|
||||
const char *s = table[idx];
|
||||
return (s != nullptr) ? s : "enUS";
|
||||
}
|
||||
using Localization::Locale::Client;
|
||||
|
||||
// True iff the comma-separated `list` (spaces allowed) contains `token` (CI).
|
||||
bool ListContains(const char *list, size_t listLen, const char *token) {
|
||||
@@ -65,7 +57,7 @@ bool ListContains(const char *list, size_t listLen, const char *token) {
|
||||
const char *VariableValue(const char *head, size_t headLen) {
|
||||
if (EqCI(head, headLen, "Family")) return "Classic";
|
||||
if (EqCI(head, headLen, "Game")) return "Vanilla";
|
||||
if (EqCI(head, headLen, "TextLocale")) return ClientLocale();
|
||||
if (EqCI(head, headLen, "TextLocale")) return Client();
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
@@ -78,13 +70,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 +100,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,29 +117,39 @@ 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;
|
||||
}
|
||||
|
||||
// True iff the game-type list names a game type this client is: always
|
||||
// `vanilla`, and `turtle` (a ClassicAPI extension, like the `_Turtle.toc`
|
||||
// flavor) on a Turtle client.
|
||||
bool ListContainsGameType(const char *list, size_t listLen) {
|
||||
return ListContains(list, listLen, "vanilla") ||
|
||||
(Turtle::Detected() && ListContains(list, listLen, "turtle"));
|
||||
}
|
||||
|
||||
// Evaluate a `[keyword args]` condition — the return is whether the line should
|
||||
// load. An unrecognized keyword returns false so the caller drops the line (a
|
||||
// condition we cannot confirm must not load — fail safe).
|
||||
bool EvalCondition(const char *head, size_t headLen, const char *args,
|
||||
size_t argsLen) {
|
||||
if (EqCI(head, headLen, "AllowLoadGameType"))
|
||||
return ListContains(args, argsLen, "vanilla");
|
||||
return ListContainsGameType(args, argsLen);
|
||||
if (EqCI(head, headLen, "ExcludeLoadGameType"))
|
||||
return !ListContainsGameType(args, argsLen);
|
||||
if (EqCI(head, headLen, "AllowLoadTextLocale"))
|
||||
return ListContains(args, argsLen, ClientLocale());
|
||||
return ListContains(args, argsLen, Client());
|
||||
if (EqCI(head, headLen, "AllowLoad"))
|
||||
return ListContains(args, argsLen, "game"); // addon files: in-game only
|
||||
return false;
|
||||
|
||||
+16
-7
@@ -42,7 +42,15 @@ namespace AddOns::TocRewrite {
|
||||
// below); metadata-line conditions, added in retail 12.0.7, are out of
|
||||
// scope. What the tokens resolve to on this 1.12 client:
|
||||
//
|
||||
// [AllowLoadGameType ...] keep the line iff the list contains `vanilla`
|
||||
// [AllowLoadGameType ...] keep the line iff the list names a game type
|
||||
// of this client
|
||||
// [ExcludeLoadGameType ...] keep the line iff the list names none
|
||||
// This client is the `vanilla` game type, and
|
||||
// also `turtle` (a ClassicAPI extension, like
|
||||
// the `_Turtle.toc` flavor) when
|
||||
// Turtle::Detected(). So
|
||||
// `[ExcludeLoadGameType turtle]` loads a line
|
||||
// everywhere but Turtle.
|
||||
// [AllowLoadTextLocale ...] keep the line iff the list contains the
|
||||
// client locale (GetLocale() code, e.g. enUS)
|
||||
// [AllowLoad ...] addon files only load in-game, so `game`
|
||||
@@ -59,12 +67,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,915 @@
|
||||
// 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.
|
||||
//
|
||||
// Later clients' additions, on the same objects:
|
||||
// - the target setters (SetTarget, SetTargetName, SetTargetKey,
|
||||
// SetChildKey, SetTargetParent, GetTarget);
|
||||
// - Alpha's fromAlpha / toAlpha. Blizzard's own code starts a fade from
|
||||
// the region's current alpha with SetFromAlpha(region:GetAlpha()), and
|
||||
// its XML fades in with toAlpha="1" alone, so the alpha is absolute (the
|
||||
// target's alpha becomes from + (to - from) x progress) and an unset
|
||||
// fromAlpha is 0. SetChange goes back to 4.3.4's relative change;
|
||||
// - Scale's SetScaleFrom / SetScaleTo. 4.3.4's scale is the case from = 1,
|
||||
// and SetScale sets the end, so its old results do not change.
|
||||
|
||||
#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 <cstdio>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
|
||||
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 --------------------------------------------------------------------
|
||||
|
||||
void Anim::ResolveTarget() {
|
||||
if (!targetKey.empty())
|
||||
target = Region::FindRegionByKey(this, targetKey.c_str());
|
||||
else if (targetName[0] != '\0')
|
||||
target = Region::FindRegionByName(targetName);
|
||||
}
|
||||
|
||||
bool Anim::Play() {
|
||||
ResolveTarget();
|
||||
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:
|
||||
if (alphaFromTo)
|
||||
Region::SetAnimAlpha(region, target, static_cast<uint8_t>((fromAlpha + (toAlpha - fromAlpha) * p) * 255.0f));
|
||||
else
|
||||
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: {
|
||||
// AddAnimScale takes the share of the way to the origin, 1 - scale.
|
||||
const float x = scaleFromX + (scaleToX - scaleFromX) * p;
|
||||
const float y = scaleFromY + (scaleToY - scaleFromY) * p;
|
||||
Region::AddAnimScale(region, target, originPoint, originX, originY, 1.0f - x, 1.0f - y);
|
||||
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;
|
||||
}
|
||||
|
||||
// ---- Target (later clients) ----
|
||||
//
|
||||
// An animation with no target animates its group's region. Each setter
|
||||
// replaces the others' target and returns whether it names a region now;
|
||||
// a name or key is looked up again on Play, as 4.3.4 looks up `target`.
|
||||
|
||||
int PushTargetFound(void *L, const Anim *a) {
|
||||
Game::Lua::PushBool(L, a->target != nullptr);
|
||||
return 1;
|
||||
}
|
||||
|
||||
void *RegionArg(void *L, int idx) {
|
||||
if (Game::Lua::Type(L, idx) != Game::Lua::TYPE_TABLE)
|
||||
return nullptr;
|
||||
void *object = Game::Lua::ResolveObject(L, idx);
|
||||
if (object == nullptr || IsOurs(object) || !Game::Lua::IsA(object, Offsets::VAR_REGION_LUA_TYPE_ID))
|
||||
return nullptr;
|
||||
return object;
|
||||
}
|
||||
|
||||
const char *StringArg(void *L, Anim *a, const char *usage) {
|
||||
if (Game::Lua::IsString(L, 2))
|
||||
return Game::Lua::ToString(L, 2);
|
||||
Game::Lua::Error(L, usage, a->DisplayName());
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
int __fastcall Script_SetTarget(void *L) {
|
||||
Anim *a = Self(L);
|
||||
if (a == nullptr)
|
||||
return 0;
|
||||
void *region = RegionArg(L, 2);
|
||||
if (region == nullptr) {
|
||||
Game::Lua::PushBool(L, false);
|
||||
return 1;
|
||||
}
|
||||
a->targetName[0] = '\0';
|
||||
a->targetKey.clear();
|
||||
a->target = region;
|
||||
return PushTargetFound(L, a);
|
||||
}
|
||||
int __fastcall Script_SetTargetName(void *L) {
|
||||
Anim *a = Self(L);
|
||||
const char *name = a != nullptr ? StringArg(L, a, "Usage: %s:SetTargetName(name)") : nullptr;
|
||||
if (name == nullptr)
|
||||
return 0;
|
||||
std::snprintf(a->targetName, sizeof(a->targetName), "%s", CreateName(name, a).c_str());
|
||||
a->targetKey.clear();
|
||||
a->target = nullptr;
|
||||
a->ResolveTarget();
|
||||
return PushTargetFound(L, a);
|
||||
}
|
||||
int __fastcall Script_SetTargetKey(void *L) {
|
||||
Anim *a = Self(L);
|
||||
const char *key = a != nullptr ? StringArg(L, a, "Usage: %s:SetTargetKey(key)") : nullptr;
|
||||
if (key == nullptr)
|
||||
return 0;
|
||||
a->targetName[0] = '\0';
|
||||
a->targetKey = key;
|
||||
a->target = nullptr;
|
||||
a->ResolveTarget();
|
||||
return PushTargetFound(L, a);
|
||||
}
|
||||
int __fastcall Script_SetChildKey(void *L) {
|
||||
Anim *a = Self(L);
|
||||
const char *key = a != nullptr ? StringArg(L, a, "Usage: %s:SetChildKey(childKey)") : nullptr;
|
||||
if (key == nullptr)
|
||||
return 0;
|
||||
a->targetName[0] = '\0';
|
||||
a->targetKey = std::string("$parent.$parent.") + key;
|
||||
a->target = nullptr;
|
||||
a->ResolveTarget();
|
||||
return PushTargetFound(L, a);
|
||||
}
|
||||
int __fastcall Script_SetTargetParent(void *L) {
|
||||
Anim *a = Self(L);
|
||||
if (a == nullptr)
|
||||
return 0;
|
||||
a->targetName[0] = '\0';
|
||||
a->targetKey.clear();
|
||||
a->target = a->GetRegionParent();
|
||||
return PushTargetFound(L, a);
|
||||
}
|
||||
int __fastcall Script_GetTarget(void *L) {
|
||||
Anim *a = Self(L);
|
||||
if (a == nullptr)
|
||||
return 0;
|
||||
void *region = a->target != nullptr ? a->target : 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);
|
||||
a->alphaFromTo = false;
|
||||
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;
|
||||
}
|
||||
|
||||
// Later clients' absolute alpha. Setting either end turns it on; the other
|
||||
// end keeps its value, 0 until set.
|
||||
void SetAlphaEnd(void *L, float Anim::*end, const char *usage) {
|
||||
Anim *a = SelfOf(L, Anim::s_alphaClass);
|
||||
if (a == nullptr || !NumberArg(L, 2, a, usage))
|
||||
return;
|
||||
const float value = static_cast<float>(Game::Lua::ToNumber(L, 2));
|
||||
a->*end = value < 0.0f ? 0.0f : (value > 1.0f ? 1.0f : value);
|
||||
a->alphaFromTo = true;
|
||||
}
|
||||
int __fastcall Script_SetFromAlpha(void *L) {
|
||||
SetAlphaEnd(L, &Anim::fromAlpha, "Usage: %s:SetFromAlpha(alpha)");
|
||||
return 0;
|
||||
}
|
||||
int __fastcall Script_SetToAlpha(void *L) {
|
||||
SetAlphaEnd(L, &Anim::toAlpha, "Usage: %s:SetToAlpha(alpha)");
|
||||
return 0;
|
||||
}
|
||||
int __fastcall Script_GetFromAlpha(void *L) {
|
||||
Anim *a = SelfOf(L, Anim::s_alphaClass);
|
||||
if (a == nullptr)
|
||||
return 0;
|
||||
Game::Lua::PushNumber(L, a->fromAlpha);
|
||||
return 1;
|
||||
}
|
||||
int __fastcall Script_GetToAlpha(void *L) {
|
||||
Anim *a = SelfOf(L, Anim::s_alphaClass);
|
||||
if (a == nullptr)
|
||||
return 0;
|
||||
Game::Lua::PushNumber(L, a->toAlpha);
|
||||
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: the scale it ends on.
|
||||
const float x = static_cast<float>(Game::Lua::ToNumber(L, 2));
|
||||
const float y = static_cast<float>(Game::Lua::ToNumber(L, 3));
|
||||
a->scaleToX = x >= 0.001f ? x : 0.001f;
|
||||
a->scaleToY = 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, a->scaleToX);
|
||||
Game::Lua::PushNumber(L, a->scaleToY);
|
||||
return 2;
|
||||
}
|
||||
|
||||
// Later clients' SetScaleFrom / SetScaleTo: the scale the animation starts
|
||||
// and ends on, as given.
|
||||
void SetScaleEnd(void *L, float Anim::*x, float Anim::*y, const char *usage) {
|
||||
Anim *a = SelfOf(L, Anim::s_scaleClass);
|
||||
if (a == nullptr)
|
||||
return;
|
||||
if (!Game::Lua::IsNumber(L, 2) || !Game::Lua::IsNumber(L, 3)) {
|
||||
Game::Lua::Error(L, usage, a->DisplayName());
|
||||
return;
|
||||
}
|
||||
a->*x = static_cast<float>(Game::Lua::ToNumber(L, 2));
|
||||
a->*y = static_cast<float>(Game::Lua::ToNumber(L, 3));
|
||||
}
|
||||
int __fastcall Script_SetScaleFrom(void *L) {
|
||||
SetScaleEnd(L, &Anim::scaleFromX, &Anim::scaleFromY, "Usage: %s:SetScaleFrom(x, y)");
|
||||
return 0;
|
||||
}
|
||||
int __fastcall Script_SetScaleTo(void *L) {
|
||||
SetScaleEnd(L, &Anim::scaleToX, &Anim::scaleToY, "Usage: %s:SetScaleTo(x, y)");
|
||||
return 0;
|
||||
}
|
||||
int __fastcall Script_GetScaleFrom(void *L) {
|
||||
Anim *a = SelfOf(L, Anim::s_scaleClass);
|
||||
if (a == nullptr)
|
||||
return 0;
|
||||
Game::Lua::PushNumber(L, a->scaleFromX);
|
||||
Game::Lua::PushNumber(L, a->scaleFromY);
|
||||
return 2;
|
||||
}
|
||||
int __fastcall Script_GetScaleTo(void *L) {
|
||||
Anim *a = SelfOf(L, Anim::s_scaleClass);
|
||||
if (a == nullptr)
|
||||
return 0;
|
||||
Game::Lua::PushNumber(L, a->scaleToX);
|
||||
Game::Lua::PushNumber(L, a->scaleToY);
|
||||
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},
|
||||
{"SetTarget", &Script_SetTarget},
|
||||
{"SetTargetName", &Script_SetTargetName},
|
||||
{"SetTargetKey", &Script_SetTargetKey},
|
||||
{"SetChildKey", &Script_SetChildKey},
|
||||
{"SetTargetParent", &Script_SetTargetParent},
|
||||
{"GetTarget", &Script_GetTarget},
|
||||
{"HasScript", &Script_HasScript},
|
||||
{"GetScript", &Script_GetScript},
|
||||
{"SetScript", &Script_SetScript},
|
||||
{"HookScript", &Script_HookScript},
|
||||
};
|
||||
const Game::Lua::FrameMethodEntry kAlphaMethods[] = {
|
||||
{"SetChange", &Script_SetChange}, {"GetChange", &Script_GetChange},
|
||||
{"SetFromAlpha", &Script_SetFromAlpha}, {"GetFromAlpha", &Script_GetFromAlpha},
|
||||
{"SetToAlpha", &Script_SetToAlpha}, {"GetToAlpha", &Script_GetToAlpha},
|
||||
};
|
||||
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},
|
||||
{"SetScaleFrom", &Script_SetScaleFrom}, {"GetScaleFrom", &Script_GetScaleFrom},
|
||||
{"SetScaleTo", &Script_SetScaleTo}, {"GetScaleTo", &Script_GetScaleTo},
|
||||
};
|
||||
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,231 @@
|
||||
// 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 <string>
|
||||
#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;
|
||||
|
||||
// Later clients' setToFinalAlpha: when the group finishes, its alpha
|
||||
// animations' targets keep the alpha they end on (KeepAnimAlpha).
|
||||
bool setToFinalAlpha = false;
|
||||
|
||||
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 or targetKey on Play
|
||||
char targetName[128] = {}; // m_targetName
|
||||
// Later clients' targetKey: a key path from the animation itself, where
|
||||
// `$parent` steps to the group, then the group's region, then that
|
||||
// region's parent. childKey "Icon" is "$parent.$parent.Icon".
|
||||
std::string targetKey;
|
||||
bool hasSmoother = false;
|
||||
float smoothIn = 0.0f, smoothOut = 0.0f;
|
||||
|
||||
// Resolves targetName or targetKey into target, when either is set.
|
||||
void ResolveTarget();
|
||||
|
||||
// Alpha: m_change, -255..255, or (alphaFromTo) the absolute fromAlpha /
|
||||
// toAlpha, 0..1, that later clients replaced it with.
|
||||
int16_t change = 0;
|
||||
bool alphaFromTo = false;
|
||||
float fromAlpha = 0.0f, toAlpha = 0.0f;
|
||||
// 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;
|
||||
// Scale: from and to, 1 by default. 4.3.4's m_scaleChange (1 - scale)
|
||||
// is the case from = 1; later clients added the from scale.
|
||||
float scaleFromX = 1.0f, scaleFromY = 1.0f;
|
||||
float scaleToX = 1.0f, scaleToY = 1.0f;
|
||||
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,695 @@
|
||||
// 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, with later clients'
|
||||
// SetToFinalAlpha / IsSetToFinalAlpha: the final alpha is kept when the
|
||||
// group finishes (Finish included), and Stop still restores the alpha. No
|
||||
// source on disk says what a later client's Stop does with the flag.
|
||||
|
||||
#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) {
|
||||
// setToFinalAlpha: the alpha each alpha animation's target finished on
|
||||
// becomes what the end restores. Stop restores the alpha as before.
|
||||
if (setToFinalAlpha)
|
||||
for (Anim *anim : animations)
|
||||
if (anim->kind == KIND_ALPHA)
|
||||
Region::KeepAnimAlpha(RegionObject(), anim->target);
|
||||
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)); }
|
||||
|
||||
|
||||
int __fastcall Script_Play(void *L) {
|
||||
if (Group *g = Self(L))
|
||||
g->Play(Game::Lua::ToFlag(L, 2));
|
||||
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 (Game::Lua::ToFlag(L, 2))
|
||||
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;
|
||||
}
|
||||
int __fastcall Script_SetToFinalAlpha(void *L) {
|
||||
if (Group *g = Self(L))
|
||||
g->setToFinalAlpha = Game::Lua::ToFlag(L, 2);
|
||||
return 0;
|
||||
}
|
||||
int __fastcall Script_IsSetToFinalAlpha(void *L) {
|
||||
Group *g = Self(L);
|
||||
if (g == nullptr)
|
||||
return 0;
|
||||
Game::Lua::PushBool(L, g->setToFinalAlpha);
|
||||
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},
|
||||
{"SetToFinalAlpha", &Script_SetToFinalAlpha},
|
||||
{"IsSetToFinalAlpha", &Script_IsSetToFinalAlpha},
|
||||
};
|
||||
|
||||
} // 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,338 @@
|
||||
// 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 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 = Game::Lua::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 = Game::Lua::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,893 @@
|
||||
// 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 "xml/Anchors.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#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;
|
||||
}
|
||||
|
||||
// An unchanged alpha writes nothing. The setter already does nothing when the
|
||||
// one entry it would store is the region's colour, but the getter reads a
|
||||
// gradient back as white, and the setter shrinks a gradient's four entries to
|
||||
// that one (benilla-re ui/texture, "Setting a vertex colour"). So restoring
|
||||
// the stored alpha (PreOnAnimUpdate, AnimDeactivated) on a gradient under an
|
||||
// ancestor's alpha group flattened it to white. 3.3.5's and 4.3.4's
|
||||
// SetVertexColor drop the gradient there too; here only a region that an
|
||||
// animation itself fades loses it. The ancestor's fade still reaches the
|
||||
// gradient: a frame's alpha change refolds every region's entries (0x77FAC0).
|
||||
void SetVertexAlpha(void *region, uint8_t alpha) {
|
||||
const uint32_t color = VertexColor(region);
|
||||
if ((color >> 24) == alpha)
|
||||
return;
|
||||
const uint32_t bgra = (color & 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, kRegionDocs);
|
||||
}
|
||||
|
||||
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)));
|
||||
}
|
||||
|
||||
void SetAnimAlpha(void *region, void *target, uint8_t alpha) {
|
||||
if (IsFrame(region)) {
|
||||
if (target != nullptr && target != region) {
|
||||
ForEachChild(region, [target, alpha](void *child) { SetAnimAlpha(child, target, alpha); });
|
||||
return;
|
||||
}
|
||||
if (alpha != OwnAlpha(region))
|
||||
SetOwnAlpha(region, alpha);
|
||||
return;
|
||||
}
|
||||
if (target != nullptr && target != region)
|
||||
return;
|
||||
SetVertexAlpha(region, alpha);
|
||||
}
|
||||
|
||||
void KeepAnimAlpha(void *region, void *target) {
|
||||
void *shown = target != nullptr ? target : region;
|
||||
AnimData *data = DataOf(shown);
|
||||
if (data != nullptr && data->hasAlpha)
|
||||
data->alpha = IsFrame(shown) ? OwnAlpha(shown) : static_cast<uint8_t>(VertexColor(shown) >> 24);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
// The leading `$parent` steps that stay among our objects (an animation to
|
||||
// its group, a group to its region) are taken here; the rest of the path,
|
||||
// from that region, is the one Xml::Anchors resolves for relativeKey.
|
||||
void *FindRegionByKey(Object *from, const char *path) {
|
||||
if (from == nullptr || path == nullptr)
|
||||
return nullptr;
|
||||
void *current = from;
|
||||
const char *p = path;
|
||||
while (current != nullptr && IsOurs(current)) {
|
||||
const char *dot = std::strchr(p, '.');
|
||||
const std::string part = dot != nullptr ? std::string(p, dot) : std::string(p);
|
||||
if (Game::StrCmpI(part.c_str(), "$parent") != 0)
|
||||
return nullptr; // a key on a group or animation names no region
|
||||
current = static_cast<Object *>(current)->parent;
|
||||
p = dot != nullptr ? dot + 1 : p + part.size();
|
||||
}
|
||||
if (current == nullptr)
|
||||
return nullptr;
|
||||
if (*p != '\0')
|
||||
current = ::Xml::Anchors::ResolveKeyPath(current, p, false);
|
||||
if (current == nullptr || IsOurs(current) || !Game::Lua::IsA(current, Offsets::VAR_REGION_LUA_TYPE_ID))
|
||||
return nullptr;
|
||||
return current;
|
||||
}
|
||||
|
||||
} // namespace Animation::Region
|
||||
@@ -0,0 +1,73 @@
|
||||
// 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;
|
||||
class Object;
|
||||
}
|
||||
|
||||
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);
|
||||
// Later clients' absolute alpha (Alpha fromAlpha / toAlpha): the same target
|
||||
// rule as AddAnimAlpha, but the alpha becomes `alpha` instead of growing.
|
||||
void SetAnimAlpha(void *region, void *target, uint8_t alpha);
|
||||
// AnimationGroup setToFinalAlpha: the alpha that `target` (the group's
|
||||
// `region` when null) shows now becomes the one the group's end restores.
|
||||
void KeepAnimAlpha(void *region, void *target);
|
||||
// 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);
|
||||
// The region a later-client targetKey path names, read from `from`: each
|
||||
// dot-separated part is `$parent` (the object's parent) or a key on the
|
||||
// current object's table. Nullptr unless the path ends on a region.
|
||||
void *FindRegionByKey(Object *from, const char *path);
|
||||
|
||||
} // namespace Animation::Region
|
||||
@@ -0,0 +1,427 @@
|
||||
// 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.
|
||||
//
|
||||
// Later clients' attributes go to the same fields their methods set:
|
||||
// setToFinalAlpha and parentArray on a group; targetKey and childKey on any animation;
|
||||
// fromAlpha / toAlpha on Alpha; fromScaleX / fromScaleY / toScaleX /
|
||||
// toScaleY on Scale. Each applies only when present and non-empty.
|
||||
|
||||
#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);
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
// Later clients' parentArray on a group: appended to object[key], as a
|
||||
// frame or region is.
|
||||
void BindParentArray(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)) {
|
||||
Push(L, child);
|
||||
::Xml::AppendToArray(L, top + 1, key);
|
||||
}
|
||||
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>(Game::Lua::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"));
|
||||
BindParentArray(group->RegionObject(), group, ::Xml::Attr(node, "parentArray"));
|
||||
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);
|
||||
}
|
||||
if (const char *keep = ::Xml::Attr(node, "setToFinalAlpha"); keep != nullptr && *keep != '\0')
|
||||
group->setToFinalAlpha = Game::StringToFlag(keep);
|
||||
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->scaleToX = sx >= 0.001f ? sx : 0.001f;
|
||||
anim->scaleToY = sy >= 0.001f ? sy : 0.001f;
|
||||
// Later clients' from and to scale, each axis when given.
|
||||
FloatAttr(node, "fromScaleX", anim->scaleFromX);
|
||||
FloatAttr(node, "fromScaleY", anim->scaleFromY);
|
||||
FloatAttr(node, "toScaleX", anim->scaleToX);
|
||||
FloatAttr(node, "toScaleY", anim->scaleToY);
|
||||
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());
|
||||
anim->targetKey.clear();
|
||||
}
|
||||
// Later clients' key paths, looked up on Play like `target`.
|
||||
if (const char *key = ::Xml::Attr(node, "targetKey"); key != nullptr && *key != '\0') {
|
||||
anim->targetName[0] = '\0';
|
||||
anim->targetKey = key;
|
||||
}
|
||||
if (const char *key = ::Xml::Attr(node, "childKey"); key != nullptr && *key != '\0') {
|
||||
anim->targetName[0] = '\0';
|
||||
anim->targetKey = std::string("$parent.$parent.") + key;
|
||||
}
|
||||
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 (::Xml::Attr(node, "change") != nullptr)
|
||||
anim->alphaFromTo = false;
|
||||
// Later clients' absolute alpha: either end turns it on.
|
||||
if (FloatAttr(node, "fromAlpha", x)) {
|
||||
anim->fromAlpha = x < 0.0f ? 0.0f : (x > 1.0f ? 1.0f : x);
|
||||
anim->alphaFromTo = true;
|
||||
}
|
||||
if (FloatAttr(node, "toAlpha", x)) {
|
||||
anim->toAlpha = x < 0.0f ? 0.0f : (x > 1.0f ? 1.0f : x);
|
||||
anim->alphaFromTo = true;
|
||||
}
|
||||
}
|
||||
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
|
||||
+76
-21
@@ -36,8 +36,8 @@
|
||||
// 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
|
||||
// - an enum / constants /
|
||||
// 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.
|
||||
@@ -46,7 +46,6 @@
|
||||
|
||||
#include "Game.h"
|
||||
#include "Offsets.h"
|
||||
#include "debug/Log.h"
|
||||
#include "event/Custom.h"
|
||||
|
||||
#include <algorithm>
|
||||
@@ -80,13 +79,20 @@ enum Kind : uint8_t {
|
||||
KIND_TABLE, // RegisterTableFunction
|
||||
KIND_FRAME_METHOD, // RegisterFrameMethods, one per entry
|
||||
KIND_ENUM, // RegisterIntegerEnum
|
||||
KIND_CONSTANTS, // RegisterConstants
|
||||
KIND_ORPHAN_METHOD_DOC // a Doc::Method naming no entry in its table
|
||||
};
|
||||
|
||||
// The value-table kinds, which share the enum* fields of Entry.
|
||||
bool IsValueTable(Kind kind) {
|
||||
return kind == KIND_ENUM || kind == KIND_CONSTANTS;
|
||||
}
|
||||
|
||||
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 *table; // KIND_TABLE: the namespace; KIND_ENUM: the parent ("Enum");
|
||||
// KIND_CONSTANTS: "Constants"
|
||||
const char *name; // registered name / method name / enum sub-name
|
||||
const void *registry; // frame methods only
|
||||
const Function *doc; // nullptr = undocumented
|
||||
@@ -98,7 +104,6 @@ struct Entry {
|
||||
std::vector<Entry> g_entries;
|
||||
Env g_pass = ENV_NONE;
|
||||
unsigned g_sealed = 0;
|
||||
int g_recordedThisPass = 0;
|
||||
|
||||
constexpr const char *kDebugPrefix = "_classicapi_";
|
||||
|
||||
@@ -131,7 +136,6 @@ 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)
|
||||
@@ -162,14 +166,21 @@ const WidgetSystem kWidgetSystems[] = {
|
||||
{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;
|
||||
}
|
||||
|
||||
@@ -191,6 +202,7 @@ const char *SystemOf(const Entry &e) {
|
||||
case KIND_FRAME_METHOD:
|
||||
return WidgetSystemFor(e.registry);
|
||||
case KIND_ENUM:
|
||||
case KIND_CONSTANTS:
|
||||
return e.enumSystem;
|
||||
default:
|
||||
return nullptr;
|
||||
@@ -236,6 +248,7 @@ std::vector<SystemInfo> CollectSystems() {
|
||||
AddSystem(systems, SystemOf(e), nullptr, "ScriptObject", e.env);
|
||||
break;
|
||||
case KIND_ENUM:
|
||||
case KIND_CONSTANTS:
|
||||
AddSystem(systems, e.enumSystem, nullptr, nullptr, 0);
|
||||
break;
|
||||
default:
|
||||
@@ -390,6 +403,25 @@ void PushEnumeration(void *L, const Entry &e) {
|
||||
Lua::SetTable(L, -3);
|
||||
}
|
||||
|
||||
// Pushes { Name, Type = "Constants",
|
||||
// Values = { { Name, Type = "number", Value } } }.
|
||||
void PushConstants(void *L, const Entry &e) {
|
||||
Lua::NewTable(L);
|
||||
Lua::SetFieldString(L, "Name", e.name);
|
||||
Lua::SetFieldString(L, "Type", "Constants");
|
||||
Lua::PushString(L, "Values");
|
||||
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", "number");
|
||||
Lua::SetFieldNumber(L, "Value", 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);
|
||||
@@ -475,10 +507,13 @@ void PushSystem(void *L, const SystemInfo &sys) {
|
||||
Lua::SetTable(L, -3);
|
||||
}
|
||||
for (const Entry &e : g_entries) {
|
||||
if (e.kind != KIND_ENUM || !SameTextNoCase(e.enumSystem, sys.name))
|
||||
if (!IsValueTable(e.kind) || !SameTextNoCase(e.enumSystem, sys.name))
|
||||
continue;
|
||||
Lua::PushNumber(L, static_cast<double>(++n));
|
||||
PushEnumeration(L, e);
|
||||
if (e.kind == KIND_ENUM)
|
||||
PushEnumeration(L, e);
|
||||
else
|
||||
PushConstants(L, e);
|
||||
Lua::SetTable(L, -3);
|
||||
}
|
||||
Lua::SetTable(L, -3);
|
||||
@@ -523,6 +558,7 @@ std::vector<std::string> Undocumented() {
|
||||
break;
|
||||
}
|
||||
case KIND_ENUM:
|
||||
case KIND_CONSTANTS:
|
||||
if (e.enumSystem == nullptr)
|
||||
out.push_back(std::string(e.table) + "." + e.name);
|
||||
break;
|
||||
@@ -612,19 +648,13 @@ const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
|
||||
|
||||
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) {
|
||||
@@ -635,10 +665,15 @@ 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) {
|
||||
void RecordFrameMethods(const void *registry,
|
||||
Game::ArrayRef<Game::Lua::FrameMethodEntry> methods,
|
||||
Game::Doc::MethodList docList) {
|
||||
if (g_pass == ENV_NONE)
|
||||
return;
|
||||
const Game::Lua::FrameMethodEntry *table = methods.data;
|
||||
const int count = methods.count;
|
||||
const Method *docs = docList.data;
|
||||
const int docCount = docList.count;
|
||||
for (int i = 0; i < count; ++i) {
|
||||
const Function *doc = nullptr;
|
||||
for (int d = 0; d < docCount; ++d) {
|
||||
@@ -658,19 +693,27 @@ void RecordFrameMethods(const void *registry, const Game::Lua::FrameMethodEntry
|
||||
}
|
||||
}
|
||||
|
||||
void RecordEnum(const char *parent, const char *sub, const Game::Lua::EnumIntegerEntry *entries,
|
||||
int count, const char *system) {
|
||||
void NameWidgetSystem(const void *registry, const char *system) {
|
||||
if (WidgetSystemFor(registry) != nullptr)
|
||||
return;
|
||||
g_ownWidgetSystems.push_back({reinterpret_cast<uintptr_t>(registry), system});
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
void RecordValueTable(Kind kind, 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)) {
|
||||
if (Entry *e = Find(kind, parent, sub, nullptr)) {
|
||||
e->env |= g_pass;
|
||||
if (e->enumSystem == nullptr)
|
||||
e->enumSystem = system;
|
||||
return;
|
||||
}
|
||||
Entry e{};
|
||||
e.kind = KIND_ENUM;
|
||||
e.kind = kind;
|
||||
e.env = g_pass;
|
||||
e.table = parent;
|
||||
e.name = sub;
|
||||
@@ -680,6 +723,18 @@ void RecordEnum(const char *parent, const char *sub, const Game::Lua::EnumIntege
|
||||
g_entries.push_back(e);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void RecordEnum(const char *parent, const char *sub,
|
||||
Game::ArrayRef<Game::Lua::EnumIntegerEntry> entries, const char *system) {
|
||||
RecordValueTable(KIND_ENUM, parent, sub, entries.data, entries.count, system);
|
||||
}
|
||||
|
||||
void RecordConstants(const char *sub, Game::ArrayRef<Game::Lua::EnumIntegerEntry> entries,
|
||||
const char *system) {
|
||||
RecordValueTable(KIND_CONSTANTS, "Constants", sub, entries.data, entries.count, system);
|
||||
}
|
||||
|
||||
} // namespace Api::Documentation
|
||||
|
||||
// The Structure constructor lives here so the list head is private to this
|
||||
|
||||
+10
-4
@@ -32,9 +32,15 @@ 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);
|
||||
void RecordEnum(const char *parent, const char *sub, const Game::Lua::EnumIntegerEntry *entries,
|
||||
int count, const char *system);
|
||||
void RecordFrameMethods(const void *registry,
|
||||
Game::ArrayRef<Game::Lua::FrameMethodEntry> methods,
|
||||
Game::Doc::MethodList docs);
|
||||
// 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,
|
||||
Game::ArrayRef<Game::Lua::EnumIntegerEntry> entries, const char *system);
|
||||
void RecordConstants(const char *sub, Game::ArrayRef<Game::Lua::EnumIntegerEntry> entries,
|
||||
const char *system);
|
||||
|
||||
} // namespace Api::Documentation
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
// 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 "Common.h"
|
||||
#include "Game.h"
|
||||
#include "Offsets.h"
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
// CanCancelAuction(index) — 4.3.4's Script_CanCancelAuction (0x00975180):
|
||||
// nothing without an auctioneer, nil for an owner-list index with no row or a
|
||||
// sold row, else 1. The gates are 1.12's own Script_CancelAuction (0x004D0260):
|
||||
// auctioneer GUID set, ftol(index) - 1 below the owner count (unsigned, so 0 and
|
||||
// negatives miss), non-null record. 1.12's owner records carry no sold flag, so
|
||||
// that 4.3.4 gate has nothing to read. The cancel-fee money check stays in
|
||||
// CancelAuction, as in 4.3.4.
|
||||
|
||||
namespace AuctionHouse::Cancel {
|
||||
|
||||
namespace {
|
||||
|
||||
int __fastcall Script_CanCancelAuction(void *L) {
|
||||
if (!Game::Lua::IsNumber(L, 1)) {
|
||||
Game::Lua::Error(L, "Usage: CanCancelAuction(index)");
|
||||
return 0;
|
||||
}
|
||||
if (Game::Read<uint32_t>(Offsets::VAR_AUCTION_AUCTIONEER_GUID_LO) == 0 &&
|
||||
Game::Read<uint32_t>(Offsets::VAR_AUCTION_AUCTIONEER_GUID_HI) == 0)
|
||||
return 0;
|
||||
|
||||
const uint32_t index = static_cast<uint32_t>(static_cast<int64_t>(Game::Lua::ToNumber(L, 1))) - 1;
|
||||
const auto *entries = reinterpret_cast<void *const *>(Offsets::VAR_AUCTION_OWNER_ENTRIES);
|
||||
if (index < Game::Read<uint32_t>(Offsets::VAR_AUCTION_OWNER_COUNT) && entries[index] != nullptr)
|
||||
Game::Lua::PushNumber(L, 1.0);
|
||||
else
|
||||
Game::Lua::PushNil(L);
|
||||
return 1;
|
||||
}
|
||||
|
||||
const Game::Doc::Field kArgs[] = {
|
||||
Game::Doc::Req("index", "number", "Row in the \"owner\" auction list, from 1."),
|
||||
};
|
||||
const Game::Doc::Field kRets[] = {
|
||||
Game::Doc::Opt("canCancel", "number", nullptr,
|
||||
"1 when the row is one of the player's auctions, else nil. Nothing when the auction house is closed."),
|
||||
};
|
||||
const Game::Doc::Function kCanCancelAuction{
|
||||
"Returns whether CancelAuction can cancel a row of the owner auction list.", kArgs, kRets,
|
||||
"AuctionHouseGlobals"};
|
||||
|
||||
void RegisterLuaFunctions() {
|
||||
Game::Lua::RegisterGlobalFunction("CanCancelAuction", &Script_CanCancelAuction, &kCanCancelAuction);
|
||||
}
|
||||
|
||||
const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
|
||||
|
||||
} // namespace
|
||||
|
||||
} // namespace AuctionHouse::Cancel
|
||||
+128
-17
@@ -19,24 +19,29 @@
|
||||
//
|
||||
// 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"
|
||||
|
||||
#include "Game.h"
|
||||
#include "Offsets.h"
|
||||
#include "aura/Instance.h"
|
||||
#include "spell/Lookup.h"
|
||||
#include "ui/ColorData.h"
|
||||
#include "unit/Identity.h"
|
||||
|
||||
@@ -74,8 +79,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 +94,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 +122,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).
|
||||
@@ -461,6 +476,46 @@ int PushAuraBySlot(void *L, Data::Emit emit) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
// C_UnitAuras.GetAuraDataByAuraInstanceID(unit, auraInstanceID [, buf])
|
||||
// -> AuraData | nil
|
||||
// With `buf`, the fields go into that table (cleared of any this aura lacks)
|
||||
// and it is returned — the allocation-free form for UNIT_AURA_DELTA handlers
|
||||
// that look up each changed ID. Only auras of a unit in view have IDs.
|
||||
int __fastcall Script_GetAuraDataByAuraInstanceID(void *L) {
|
||||
const char *unitToken = ArgUnit(L, 1);
|
||||
if (unitToken == nullptr || !Game::Lua::IsNumber(L, 2)) {
|
||||
Game::Lua::PushNil(L);
|
||||
return 1;
|
||||
}
|
||||
const auto id = static_cast<uint32_t>(Game::Lua::ToNumber(L, 2));
|
||||
const bool fill = Game::Lua::Type(L, 3) == Game::Lua::TYPE_TABLE;
|
||||
const uint8_t *unit = ResolveUnit(unitToken);
|
||||
const int slot = Aura::Instance::SlotForID(unit, id);
|
||||
if (slot < 0) {
|
||||
Game::Lua::PushNil(L);
|
||||
return 1;
|
||||
}
|
||||
if (fill) {
|
||||
Game::Lua::PushValue(L, 3);
|
||||
Data::Push(L, unit, slot, Data::Emit::Fill);
|
||||
} else {
|
||||
Data::Push(L, unit, slot);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
const Game::Doc::Field kByInstanceIDArgs[] = {
|
||||
Game::Doc::Req("unit", "UnitToken"),
|
||||
Game::Doc::Req("auraInstanceID", "number"),
|
||||
Game::Doc::Opt("buf", "table", nullptr,
|
||||
"A table to write the aura into and return instead of a new one."),
|
||||
};
|
||||
const Game::Doc::Field kByInstanceIDRets[] = {
|
||||
Game::Doc::Opt("aura", "AuraData", nullptr, "Nil when no aura on the unit has that ID."),
|
||||
};
|
||||
const Game::Doc::Function kGetAuraDataByAuraInstanceID{
|
||||
"The aura with the given instance ID on a unit.", kByInstanceIDArgs, kByInstanceIDRets};
|
||||
|
||||
// C_UnitAuras.GetAuraDataBySlot(unit, slot) -> AuraData | nil
|
||||
int __fastcall Script_GetAuraDataBySlot(void *L) {
|
||||
return PushAuraBySlot(L, Data::Emit::Table);
|
||||
@@ -473,14 +528,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++));
|
||||
@@ -596,6 +653,55 @@ int __fastcall Script_GetAuraDispelTypeColor(void *L) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
// CancelUnitBuff(unit, index [, filter]) — 4.3.4's Script_CancelUnitBuff.
|
||||
// Only the player's own auras: its other branch exits a vehicle seat, which
|
||||
// 1.12 has no counterpart for. The index counts in `FindNthSlot` order, the
|
||||
// same order 4.3.4's GetSortedAuraSlot walks, so it matches the
|
||||
// C_UnitAuras by-index getters for the same filter (HELPFUL by default).
|
||||
// The cancel gate is the engine's: the slot's cancelable bit, or the spell's
|
||||
// `SPELL_ATTR_EX_CHANNELED_1`, before the CMSG_CANCEL_AURA sender.
|
||||
int __fastcall Script_CancelUnitBuff(void *L) {
|
||||
if (!Game::Lua::IsString(L, 1) || !Game::Lua::IsNumber(L, 2)) {
|
||||
Game::Lua::Error(L, "Usage: CancelUnitBuff(\"unit\", index[, \"filter\"])");
|
||||
return 0;
|
||||
}
|
||||
const uint8_t *player = Unit::Identity::PlayerObject();
|
||||
if (player == nullptr ||
|
||||
Unit::Identity::GuidForToken(Game::Lua::ToString(L, 1)) !=
|
||||
Unit::Identity::PlayerGuid())
|
||||
return 0;
|
||||
const ParsedFilter pf = ParseFilters(ArgOptString(L, 3));
|
||||
const int slot =
|
||||
Data::FindNthSlot(player, ArgInt(L, 2), RangeFilter(pf), pf.ToMatch());
|
||||
if (slot < 0)
|
||||
return 0;
|
||||
const int spellID = static_cast<int>(Data::ReadSpellID(player, slot));
|
||||
const uint8_t *record = Spell::Lookup::RecordForID(spellID);
|
||||
if (record == nullptr)
|
||||
return 0;
|
||||
const bool cancelable =
|
||||
(Data::SlotNibble(player, slot) & Offsets::UNIT_AURA_FLAG_CANCELABLE) != 0 ||
|
||||
(Game::Read<uint32_t>(record, Offsets::OFF_SPELL_RECORD_ATTRIBUTES_EX) &
|
||||
Offsets::SPELL_ATTR_EX_CHANNELED_1) != 0;
|
||||
if (!cancelable)
|
||||
return 0;
|
||||
using CancelAuraSend_t = void(__fastcall *)(int spellID);
|
||||
reinterpret_cast<CancelAuraSend_t>(
|
||||
static_cast<uintptr_t>(Offsets::FUN_CANCEL_AURA_SEND))(spellID);
|
||||
return 0;
|
||||
}
|
||||
|
||||
const Game::Doc::Field kCancelUnitBuffArgs[] = {
|
||||
Game::Doc::Req("unit", "string", "Must be the player."),
|
||||
Game::Doc::Req("index", "number",
|
||||
"Which aura of the ones `filter` selects, from 1."),
|
||||
Game::Doc::Opt("filter", "string", "\"HELPFUL\"",
|
||||
"Aura filter tokens, the same as `C_UnitAuras.GetAuraDataByIndex`."),
|
||||
};
|
||||
const Game::Doc::Function kCancelUnitBuff{
|
||||
"Cancels one of your own auras by index.", kCancelUnitBuffArgs, {},
|
||||
"SpellGlobals"};
|
||||
|
||||
} // namespace
|
||||
|
||||
static void RegisterLuaFunctions() {
|
||||
@@ -615,6 +721,9 @@ static void RegisterLuaFunctions() {
|
||||
&Script_GetAuraSlots);
|
||||
Game::Lua::RegisterTableFunction("C_UnitAuras", "GetAuraDataBySlot",
|
||||
&Script_GetAuraDataBySlot);
|
||||
Game::Lua::RegisterTableFunction("C_UnitAuras", "GetAuraDataByAuraInstanceID",
|
||||
&Script_GetAuraDataByAuraInstanceID,
|
||||
&kGetAuraDataByAuraInstanceID);
|
||||
Game::Lua::RegisterTableFunction("C_UnitAuras", "UnitAuraBySlot",
|
||||
&Script_UnitAuraBySlot);
|
||||
Game::Lua::RegisterTableFunction("C_UnitAuras", "GetUnitAuraBySpellID",
|
||||
@@ -627,6 +736,8 @@ static void RegisterLuaFunctions() {
|
||||
&Script_GetUnitAuras);
|
||||
Game::Lua::RegisterTableFunction("C_UnitAuras", "GetAuraDispelTypeColor",
|
||||
&Script_GetAuraDispelTypeColor);
|
||||
Game::Lua::RegisterGlobalFunction("CancelUnitBuff", &Script_CancelUnitBuff,
|
||||
&kCancelUnitBuff);
|
||||
}
|
||||
|
||||
static const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
|
||||
|
||||
@@ -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
|
||||
|
||||
+581
-202
File diff suppressed because it is too large
Load Diff
+81
-29
@@ -59,17 +59,27 @@ enum class Filter { Helpful, Harmful };
|
||||
// pushes the Classic-Era `UnitAura` 15-value tuple (net stack +15) with NO table
|
||||
// allocation, for the `C_UnitAuras.UnitAura/UnitBuff/UnitDebuff` accessors that
|
||||
// avoid the per-call GC churn. Selection + timing resolution are identical for
|
||||
// both — only the terminal leaf differs.
|
||||
enum class Emit { Table, Positional };
|
||||
// both — only the terminal leaf differs. `Fill` writes the `AuraData` fields
|
||||
// into the table already on top of the stack instead of a new one (net stack
|
||||
// 0), for getters that take a caller's table to reuse; fields the aura lacks
|
||||
// are cleared to nil.
|
||||
enum class Emit { Table, Positional, Fill };
|
||||
|
||||
// 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,8 +101,16 @@ 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;
|
||||
};
|
||||
|
||||
// The slot's descriptor flag nibble (0 for an empty slot or a null unit).
|
||||
// Bit `UNIT_AURA_FLAG_CANCELABLE` is the cancelable bit on every server.
|
||||
uint8_t SlotNibble(const uint8_t *unit, int slot);
|
||||
|
||||
// Reads the spell ID at the given absolute slot (0..47). Returns 0
|
||||
// if the slot is empty or the unit pointer is null.
|
||||
uint32_t ReadSpellID(const uint8_t *unit, int slot);
|
||||
@@ -117,11 +135,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 +155,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 +167,49 @@ 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.
|
||||
// The server's own timing for the local player's aura in absolute `slot`:
|
||||
// the engine's expiration (what `GetPlayerBuffTimeLeft` counts down) and the
|
||||
// applied duration from the same SMSG_UPDATE_AURA_DURATION, both exact —
|
||||
// diminishing returns and the caster's modifiers included. False when the
|
||||
// slot has no running timer (empty, until-cancelled, or elapsed).
|
||||
// `outDurationMs` is 0 when no duration packet was seen for the slot.
|
||||
bool PlayerAuraTiming(int slot, uint32_t *outExpirationMs, uint32_t *outDurationMs);
|
||||
|
||||
// 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,16 +247,24 @@ 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 `auraInstanceID` from `Aura::Instance` (the table forms only).
|
||||
//
|
||||
// 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
|
||||
// charges=0, maxCharges=0, points=nil,
|
||||
// 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`).
|
||||
// (the Classic-Era `UnitAura` tuple), 0 for `Emit::Fill` — see `Emit`.
|
||||
void Push(void *L, const uint8_t *unit, int slot, Emit emit = Emit::Table);
|
||||
|
||||
// Fallback for the index path when the descriptor has dropped an aura's slot
|
||||
@@ -269,7 +321,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 = {});
|
||||
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
// 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.
|
||||
|
||||
// UNIT_AURA_DELTA(unitTarget, updateInfo) — retail's UNIT_AURA payload under
|
||||
// its own name, so the engine's UNIT_AURA stays exactly as it is.
|
||||
//
|
||||
// Once per frame, from the world tick, each unit whose auras changed fires
|
||||
// once per unit token it has (`Unit::Identity::TokensForGUID`), the way the
|
||||
// engine fires UNIT_AURA. The change set is `Aura::Instance`'s.
|
||||
//
|
||||
// The payload is built to cost no garbage. It carries instance IDs only —
|
||||
// never AuraData; a handler reads the auras it cares about with
|
||||
// `C_UnitAuras.GetAuraDataByAuraInstanceID(unit, id, buf)` — and the
|
||||
// `updateInfo` table and its three ID lists are the same four tables on every
|
||||
// fire, refilled each time. So they are valid only during the handler; a
|
||||
// handler that keeps one must copy it.
|
||||
//
|
||||
// With nothing registered for the event, the tick reads one pointer and stops:
|
||||
// `Aura::Instance` records no change set, and nothing here runs.
|
||||
|
||||
#include "Game.h"
|
||||
#include "aura/Instance.h"
|
||||
#include "event/Custom.h"
|
||||
#include "tick/WorldTick.h"
|
||||
#include "unit/Identity.h"
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace Aura::Delta {
|
||||
|
||||
namespace {
|
||||
|
||||
const Game::Doc::Field kInfoFields[] = {
|
||||
Game::Doc::Req("isFullUpdate", "bool",
|
||||
"True when the unit's auras must be read again in full; the lists are then nil."),
|
||||
Game::Doc::Opt("addedAuraInstanceIDs", "table", nullptr,
|
||||
"Instance IDs of the auras added to the unit."),
|
||||
Game::Doc::Opt("updatedAuraInstanceIDs", "table", nullptr,
|
||||
"Instance IDs of the unit's auras that changed in place."),
|
||||
Game::Doc::Opt("removedAuraInstanceIDs", "table", nullptr,
|
||||
"Instance IDs of the auras removed from the unit."),
|
||||
};
|
||||
const Game::Doc::Structure kInfo{
|
||||
"UnitAuraDeltaInfo", "UnitAuras", kInfoFields,
|
||||
"What changed in a unit's auras. Valid only while the event handler runs."};
|
||||
|
||||
const Game::Doc::Field kPayload[] = {
|
||||
Game::Doc::Req("unitTarget", "UnitToken"),
|
||||
Game::Doc::Req("updateInfo", "UnitAuraDeltaInfo"),
|
||||
};
|
||||
const Game::Doc::Event kDoc{
|
||||
"UnitAuras",
|
||||
"Fires when a unit's auras change, with the instance IDs of the auras that "
|
||||
"were added, changed, or removed.",
|
||||
kPayload};
|
||||
const Event::Custom::AutoReserve _evt{"UNIT_AURA_DELTA", &kDoc};
|
||||
|
||||
// The reused payload tables, anchored in the registry of the Lua state that
|
||||
// made them. LUA_NOREF until first use in each state.
|
||||
constexpr int kNoRef = -2;
|
||||
int g_infoRef = kNoRef;
|
||||
int g_addedRef = kNoRef;
|
||||
int g_updatedRef = kNoRef;
|
||||
int g_removedRef = kNoRef;
|
||||
|
||||
// Pushes the table anchored at `ref`, making it on first use.
|
||||
void PushTable(void *L, int &ref) {
|
||||
if (ref == kNoRef) {
|
||||
Game::Lua::NewTable(L);
|
||||
ref = Game::Lua::Ref(L, Game::Lua::REGISTRY_INDEX);
|
||||
}
|
||||
Game::Lua::RawGetI(L, Game::Lua::REGISTRY_INDEX, ref);
|
||||
}
|
||||
|
||||
// Sets `key` on the table at the top to the list at `ref` refilled with `ids`,
|
||||
// or to nil when there are none.
|
||||
void SetList(void *L, const char *key, int &ref, const uint32_t *ids, int count) {
|
||||
Game::Lua::PushString(L, key);
|
||||
if (count == 0) {
|
||||
Game::Lua::PushNil(L);
|
||||
Game::Lua::SetTable(L, -3);
|
||||
return;
|
||||
}
|
||||
PushTable(L, ref);
|
||||
for (int i = 0; i < count; ++i) {
|
||||
Game::Lua::PushNumber(L, static_cast<double>(i + 1));
|
||||
Game::Lua::PushNumber(L, static_cast<double>(ids[i]));
|
||||
Game::Lua::RawSet(L, -3);
|
||||
}
|
||||
// Clear what lies past the new end: a longer earlier list, or anything a
|
||||
// handler appended.
|
||||
for (int i = count + 1;; ++i) {
|
||||
Game::Lua::RawGetI(L, -1, i);
|
||||
const bool end = Game::Lua::Type(L, -1) == Game::Lua::TYPE_NIL;
|
||||
Game::Lua::SetTop(L, -2);
|
||||
if (end)
|
||||
break;
|
||||
Game::Lua::PushNumber(L, static_cast<double>(i));
|
||||
Game::Lua::PushNil(L);
|
||||
Game::Lua::RawSet(L, -3);
|
||||
}
|
||||
Game::Lua::SetN(L, -1, count);
|
||||
Game::Lua::SetTable(L, -3);
|
||||
}
|
||||
|
||||
void Fire(const Aura::Instance::Delta &d) {
|
||||
char tokens[16][32];
|
||||
const int n = Unit::Identity::TokensForGUID(d.guid, tokens, 16);
|
||||
void *L = Game::Lua::State();
|
||||
if (n == 0 || L == nullptr)
|
||||
return;
|
||||
const int top = Game::Lua::GetTop(L);
|
||||
for (int i = 0; i < n; ++i) {
|
||||
// Refilled for each token: a handler may have changed the tables.
|
||||
Game::Lua::PushString(L, tokens[i]);
|
||||
PushTable(L, g_infoRef);
|
||||
Game::Lua::SetFieldBool(L, "isFullUpdate", d.fullUpdate);
|
||||
SetList(L, "addedAuraInstanceIDs", g_addedRef, d.added, d.addedCount);
|
||||
SetList(L, "updatedAuraInstanceIDs", g_updatedRef, d.updated, d.updatedCount);
|
||||
SetList(L, "removedAuraInstanceIDs", g_removedRef, d.removed, d.removedCount);
|
||||
Event::Custom::FireValues(_evt.Slot(), L, top + 1, 2);
|
||||
Game::Lua::SetTop(L, top);
|
||||
}
|
||||
}
|
||||
|
||||
void OnWorldTick() {
|
||||
const bool listening = Event::Custom::HasListeners(_evt.Slot());
|
||||
Aura::Instance::SetRecording(listening);
|
||||
if (listening)
|
||||
Aura::Instance::Drain(&Fire);
|
||||
}
|
||||
|
||||
const Tick::WorldTick::AutoSubscribe _tick{&OnWorldTick};
|
||||
|
||||
// Each registration pass is a new Lua state; the old state's refs are gone.
|
||||
void ResetRefs() {
|
||||
g_infoRef = g_addedRef = g_updatedRef = g_removedRef = kNoRef;
|
||||
}
|
||||
|
||||
const Game::ModuleAutoRegister _autoreg{&ResetRefs};
|
||||
|
||||
} // namespace
|
||||
|
||||
} // namespace Aura::Delta
|
||||
@@ -0,0 +1,317 @@
|
||||
// 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.
|
||||
|
||||
// Aura instance IDs. See `Instance.h` for the contract.
|
||||
|
||||
#include "Instance.h"
|
||||
|
||||
#include "Game.h"
|
||||
#include "Offsets.h"
|
||||
#include "aura/Data.h"
|
||||
#include "aura/Source.h"
|
||||
#include "object/Resolve.h"
|
||||
#include "tick/WorldTick.h"
|
||||
#include "time/Clock.h"
|
||||
#include "unit/Identity.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace Aura::Instance {
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int kSlots = Offsets::UNIT_AURA_TOTAL;
|
||||
constexpr int kFlagBytes = kSlots / 2; // UNIT_FIELD_AURAFLAGS: a nibble per slot
|
||||
|
||||
// What was last seen of one unit's aura fields, the IDs given to its visible
|
||||
// auras, and (while recording) its change set since the last Drain.
|
||||
struct Tracked {
|
||||
const uint8_t *object = nullptr;
|
||||
uint32_t spell[kSlots] = {};
|
||||
uint8_t flags[kFlagBytes] = {};
|
||||
uint8_t stacks[kSlots] = {};
|
||||
uint32_t id[kSlots] = {}; // 0 = no visible aura in the slot
|
||||
bool full = false;
|
||||
std::vector<uint32_t> added, updated, removed;
|
||||
};
|
||||
|
||||
std::unordered_map<uint64_t, Tracked> g_units;
|
||||
uint32_t g_nextID = 1;
|
||||
bool g_recording = false;
|
||||
|
||||
const uint8_t *Descriptor(const uint8_t *unit) {
|
||||
return Game::Read<const uint8_t *>(unit, Offsets::OFF_CGUNIT_OBJECT_FIELDS);
|
||||
}
|
||||
|
||||
uint8_t Nibble(const uint8_t *flags, int slot) {
|
||||
return (flags[slot / 2] >> ((slot & 1) * 4)) & 0xF;
|
||||
}
|
||||
|
||||
bool Contains(const std::vector<uint32_t> &v, uint32_t id) {
|
||||
return std::find(v.begin(), v.end(), id) != v.end();
|
||||
}
|
||||
|
||||
bool Erase(std::vector<uint32_t> &v, uint32_t id) {
|
||||
const auto it = std::find(v.begin(), v.end(), id);
|
||||
if (it == v.end())
|
||||
return false;
|
||||
v.erase(it);
|
||||
return true;
|
||||
}
|
||||
|
||||
void ClearPending(Tracked &t) {
|
||||
t.full = false;
|
||||
t.added.clear();
|
||||
t.updated.clear();
|
||||
t.removed.clear();
|
||||
}
|
||||
|
||||
// The change-set writes, coalesced within one Drain interval: an aura added and
|
||||
// removed before the consumer heard of it is never reported, and an added or
|
||||
// removed aura is not also reported as updated. A pending full update already
|
||||
// covers everything.
|
||||
void NoteAdded(Tracked &t, uint32_t id) {
|
||||
if (g_recording && !t.full)
|
||||
t.added.push_back(id);
|
||||
}
|
||||
|
||||
void NoteChanged(Tracked &t, uint32_t id) {
|
||||
if (g_recording && !t.full && !Contains(t.added, id) && !Contains(t.updated, id))
|
||||
t.updated.push_back(id);
|
||||
}
|
||||
|
||||
void NoteRemoved(Tracked &t, uint32_t id) {
|
||||
if (!g_recording || t.full || Erase(t.added, id))
|
||||
return;
|
||||
Erase(t.updated, id);
|
||||
t.removed.push_back(id);
|
||||
}
|
||||
|
||||
// Records `unit`'s aura fields as they are now, with a fresh ID for every
|
||||
// visible aura. `full` marks the change set as a full update: the consumer has
|
||||
// never been told about these IDs.
|
||||
void Seed(Tracked &t, const uint8_t *unit, bool full) {
|
||||
const uint8_t *desc = Descriptor(unit);
|
||||
t.object = unit;
|
||||
ClearPending(t);
|
||||
t.full = full && g_recording;
|
||||
if (desc == nullptr) {
|
||||
std::memset(t.spell, 0, sizeof t.spell);
|
||||
std::memset(t.flags, 0, sizeof t.flags);
|
||||
std::memset(t.stacks, 0, sizeof t.stacks);
|
||||
std::memset(t.id, 0, sizeof t.id);
|
||||
return;
|
||||
}
|
||||
std::memcpy(t.spell, desc + Offsets::OFF_UNIT_FIELD_AURA, sizeof t.spell);
|
||||
std::memcpy(t.flags, desc + Offsets::OFF_UNIT_FIELD_AURAFLAGS, sizeof t.flags);
|
||||
std::memcpy(t.stacks, desc + Offsets::OFF_UNIT_FIELD_AURAAPPLICATIONS, sizeof t.stacks);
|
||||
for (int slot = 0; slot < kSlots; ++slot)
|
||||
t.id[slot] = Data::IsSlotPopulated(unit, slot) ? g_nextID++ : 0;
|
||||
}
|
||||
|
||||
// Brings one slot's record in line with the live descriptor. A new spell, or a
|
||||
// visibility change, ends the old instance and starts a new one; the same
|
||||
// visible aura with new flags or stacks is the same instance, updated.
|
||||
void SyncSlot(Tracked &t, const uint8_t *unit, const uint8_t *desc, int slot) {
|
||||
const uint32_t spell = Game::Read<uint32_t>(desc, Offsets::OFF_UNIT_FIELD_AURA + slot * 4);
|
||||
const uint8_t *flags = desc + Offsets::OFF_UNIT_FIELD_AURAFLAGS;
|
||||
const uint8_t nibble = Nibble(flags, slot);
|
||||
const uint8_t stacks = desc[Offsets::OFF_UNIT_FIELD_AURAAPPLICATIONS + slot];
|
||||
if (spell == t.spell[slot] && nibble == Nibble(t.flags, slot)) {
|
||||
if (stacks != t.stacks[slot]) {
|
||||
t.stacks[slot] = stacks;
|
||||
if (t.id[slot] != 0)
|
||||
NoteChanged(t, t.id[slot]);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const bool visible = Data::IsSlotPopulated(unit, slot);
|
||||
if (visible && spell == t.spell[slot] && t.id[slot] != 0) {
|
||||
NoteChanged(t, t.id[slot]);
|
||||
} else {
|
||||
if (t.id[slot] != 0)
|
||||
NoteRemoved(t, t.id[slot]);
|
||||
t.id[slot] = visible ? g_nextID++ : 0;
|
||||
if (t.id[slot] != 0)
|
||||
NoteAdded(t, t.id[slot]);
|
||||
}
|
||||
t.spell[slot] = spell;
|
||||
// Only this slot's nibble: the byte's other half is the neighbour's, which
|
||||
// its own sync records.
|
||||
const uint8_t mask = static_cast<uint8_t>(0xF << ((slot & 1) * 4));
|
||||
t.flags[slot / 2] = static_cast<uint8_t>((t.flags[slot / 2] & ~mask) | (flags[slot / 2] & mask));
|
||||
t.stacks[slot] = stacks;
|
||||
}
|
||||
|
||||
void SyncAll(Tracked &t, const uint8_t *unit) {
|
||||
const uint8_t *desc = Descriptor(unit);
|
||||
if (desc == nullptr)
|
||||
return;
|
||||
// The common case is no change at all: three compares, no per-slot work.
|
||||
if (std::memcmp(t.spell, desc + Offsets::OFF_UNIT_FIELD_AURA, sizeof t.spell) == 0 &&
|
||||
std::memcmp(t.flags, desc + Offsets::OFF_UNIT_FIELD_AURAFLAGS, sizeof t.flags) == 0 &&
|
||||
std::memcmp(t.stacks, desc + Offsets::OFF_UNIT_FIELD_AURAAPPLICATIONS,
|
||||
sizeof t.stacks) == 0)
|
||||
return;
|
||||
for (int slot = 0; slot < kSlots; ++slot)
|
||||
SyncSlot(t, unit, desc, slot);
|
||||
}
|
||||
|
||||
// The record for `unit`, created (seeded from the live fields) on first sight
|
||||
// and re-seeded when its GUID now names a different object — the old one left
|
||||
// view and a new one was built, so nothing recorded of it still holds. A
|
||||
// rebuilt unit is always a full update (the consumer holds its old IDs). For a
|
||||
// first sight, `full` says whether it is news to the consumer: true from the
|
||||
// change handlers (an aura changed on a unit the consumer has no IDs for),
|
||||
// false from the getters (the caller is reading the auras right now).
|
||||
Tracked *Track(const uint8_t *unit, bool full, bool *seeded) {
|
||||
*seeded = false;
|
||||
const uint64_t guid = Unit::Identity::GuidForObject(unit);
|
||||
if (guid == 0 || Descriptor(unit) == nullptr)
|
||||
return nullptr;
|
||||
auto [it, inserted] = g_units.try_emplace(guid);
|
||||
Tracked &t = it->second;
|
||||
if (inserted || t.object != unit) {
|
||||
Seed(t, unit, inserted ? full : true);
|
||||
*seeded = true;
|
||||
}
|
||||
return &t;
|
||||
}
|
||||
|
||||
// The engine's aura handlers name the slot that changed; syncing that slot is
|
||||
// what keeps a spell removed and applied again in one slot two instances (the
|
||||
// two arrive in separate update blocks, so each reaches its own sync).
|
||||
void OnAuraChange(const Aura::Source::Change &c) {
|
||||
if (c.unit == nullptr || c.slot < 0 || c.slot >= kSlots)
|
||||
return;
|
||||
const auto *unit = static_cast<const uint8_t *>(c.unit);
|
||||
bool seeded;
|
||||
Tracked *t = Track(unit, /*full*/ true, &seeded);
|
||||
if (t != nullptr && !seeded)
|
||||
SyncSlot(*t, unit, Descriptor(unit), c.slot);
|
||||
}
|
||||
|
||||
const Aura::Source::AutoObserve _obs{&OnAuraChange};
|
||||
|
||||
// Units that left view are forgotten; one coming back is seeded afresh with new
|
||||
// IDs. While recording, `Drain` does this every frame; otherwise this sweep
|
||||
// keeps the table to the units in view.
|
||||
constexpr uint32_t kSweepIntervalMs = 1000;
|
||||
uint32_t g_lastSweepMs = 0;
|
||||
|
||||
void OnWorldTick() {
|
||||
const uint32_t now = Time::Clock::NowMs();
|
||||
if (Time::Clock::Elapsed(g_lastSweepMs, now) < kSweepIntervalMs)
|
||||
return;
|
||||
g_lastSweepMs = now;
|
||||
for (auto it = g_units.begin(); it != g_units.end();) {
|
||||
if (Object::ByGuid(Offsets::TYPEMASK_UNIT, it->first) == nullptr)
|
||||
it = g_units.erase(it);
|
||||
else
|
||||
++it;
|
||||
}
|
||||
}
|
||||
|
||||
const Tick::WorldTick::AutoSubscribe _tick{&OnWorldTick};
|
||||
|
||||
// A delta copied out of its record, so `Drain`'s callback can run Lua that
|
||||
// grows `g_units` without invalidating it.
|
||||
struct OwnedDelta {
|
||||
uint64_t guid;
|
||||
bool full;
|
||||
std::vector<uint32_t> added, updated, removed;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
uint32_t IDForSlot(const uint8_t *unit, int slot) {
|
||||
if (unit == nullptr || slot < 0 || slot >= kSlots)
|
||||
return 0;
|
||||
bool seeded;
|
||||
Tracked *t = Track(unit, /*full*/ false, &seeded);
|
||||
if (t == nullptr)
|
||||
return 0;
|
||||
if (!seeded)
|
||||
SyncSlot(*t, unit, Descriptor(unit), slot);
|
||||
return t->id[slot];
|
||||
}
|
||||
|
||||
int SlotForID(const uint8_t *unit, uint32_t id) {
|
||||
if (unit == nullptr || id == 0)
|
||||
return -1;
|
||||
bool seeded;
|
||||
Tracked *t = Track(unit, /*full*/ false, &seeded);
|
||||
if (t == nullptr || seeded) // a fresh seed hands out new IDs only
|
||||
return -1;
|
||||
for (int slot = 0; slot < kSlots; ++slot) {
|
||||
if (t->id[slot] != id)
|
||||
continue;
|
||||
SyncSlot(*t, unit, Descriptor(unit), slot);
|
||||
return t->id[slot] == id ? slot : -1;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
void NoteUpdated(uint64_t guid, int slot) {
|
||||
if (slot < 0 || slot >= kSlots)
|
||||
return;
|
||||
const auto it = g_units.find(guid);
|
||||
if (it != g_units.end() && it->second.id[slot] != 0)
|
||||
NoteChanged(it->second, it->second.id[slot]);
|
||||
}
|
||||
|
||||
void SetRecording(bool on) {
|
||||
if (on == g_recording)
|
||||
return;
|
||||
g_recording = on;
|
||||
if (!on)
|
||||
for (auto &[guid, t] : g_units)
|
||||
ClearPending(t);
|
||||
}
|
||||
|
||||
void Drain(void (*fn)(const Delta &delta)) {
|
||||
std::vector<OwnedDelta> out;
|
||||
for (auto it = g_units.begin(); it != g_units.end();) {
|
||||
Tracked &t = it->second;
|
||||
const auto *unit = static_cast<const uint8_t *>(
|
||||
Object::ByGuid(Offsets::TYPEMASK_UNIT, it->first));
|
||||
if (unit == nullptr) {
|
||||
it = g_units.erase(it);
|
||||
continue;
|
||||
}
|
||||
if (unit != t.object)
|
||||
Seed(t, unit, /*full*/ true);
|
||||
else
|
||||
SyncAll(t, unit);
|
||||
if (t.full || !t.added.empty() || !t.updated.empty() || !t.removed.empty()) {
|
||||
out.push_back({it->first, t.full, std::move(t.added), std::move(t.updated),
|
||||
std::move(t.removed)});
|
||||
ClearPending(t);
|
||||
}
|
||||
++it;
|
||||
}
|
||||
for (const OwnedDelta &d : out) {
|
||||
const Delta view{d.guid,
|
||||
d.full,
|
||||
d.added.data(),
|
||||
static_cast<int>(d.added.size()),
|
||||
d.updated.data(),
|
||||
static_cast<int>(d.updated.size()),
|
||||
d.removed.data(),
|
||||
static_cast<int>(d.removed.size())};
|
||||
fn(view);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace Aura::Instance
|
||||
@@ -0,0 +1,75 @@
|
||||
// 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.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
// Aura instance IDs — retail's `auraInstanceID`. 1.12 has no aura identity:
|
||||
// a unit's descriptor holds 48 spell IDs and nothing that tells one application
|
||||
// of a spell from the next. This module gives each aura a number when it lands
|
||||
// in a descriptor slot and keeps it until the aura leaves, so the same aura
|
||||
// reads the same ID from every getter, and an aura removed and applied again
|
||||
// gets a new one. IDs are never reused.
|
||||
//
|
||||
// Only the visible auras of a unit in view get an ID: the slots
|
||||
// `Aura::Data::IsSlotPopulated` accepts (the UnitBuff gate). An aura only the
|
||||
// `Aura::Source` cache or the out-of-range group array knows has none.
|
||||
//
|
||||
// Every change goes through one step: compare what was recorded for a slot
|
||||
// with the live descriptor. The engine's aura handlers (`Aura::Source`'s
|
||||
// Added / Removed / Stacks changes) run it for the slot they name, which is
|
||||
// what tells a removal and re-application of one spell apart; the getters run
|
||||
// it before answering; and `Drain` runs it over every tracked unit, which
|
||||
// catches what no handler reports (a bulk clear, an object rebuilt).
|
||||
//
|
||||
// While recording is on, each unit also collects the change set since the last
|
||||
// `Drain` — what `UNIT_AURA_DELTA` reports.
|
||||
|
||||
namespace Aura::Instance {
|
||||
|
||||
// The instance ID of the aura in absolute descriptor `slot` on `unit`, or 0
|
||||
// when the slot holds no visible aura.
|
||||
uint32_t IDForSlot(const uint8_t *unit, int slot);
|
||||
|
||||
// The absolute descriptor slot holding instance `id` on `unit`, or -1 when no
|
||||
// aura on the unit has that ID.
|
||||
int SlotForID(const uint8_t *unit, uint32_t id);
|
||||
|
||||
// Records the aura in `slot` on `guid` as updated in place — a timing change
|
||||
// with no descriptor change behind it (a refresh, a duration packet). No-op
|
||||
// for a slot with no ID or a unit nobody has asked about.
|
||||
void NoteUpdated(uint64_t guid, int slot);
|
||||
|
||||
// One unit's changes since the last `Drain`. With `fullUpdate` set the lists
|
||||
// are empty and the consumer re-reads every aura (the unit was first seen, or
|
||||
// its object was rebuilt).
|
||||
struct Delta {
|
||||
uint64_t guid;
|
||||
bool fullUpdate;
|
||||
const uint32_t *added;
|
||||
int addedCount;
|
||||
const uint32_t *updated;
|
||||
int updatedCount;
|
||||
const uint32_t *removed;
|
||||
int removedCount;
|
||||
};
|
||||
|
||||
// Turns change collection on or off. Off, no change set is kept, and turning
|
||||
// it off discards what was collected. IDs are assigned either way.
|
||||
void SetRecording(bool on);
|
||||
|
||||
// Reconciles every tracked unit with its descriptor, then hands each unit with
|
||||
// changes to `fn` and clears them. The deltas are copied out first, so `fn`
|
||||
// may run Lua that calls the getters; changes made meanwhile wait for the next
|
||||
// `Drain`.
|
||||
void Drain(void (*fn)(const Delta &delta));
|
||||
|
||||
} // namespace Aura::Instance
|
||||
+317
-70
@@ -18,16 +18,19 @@
|
||||
#include "ComboDuration.h"
|
||||
#include "Data.h"
|
||||
#include "Game.h"
|
||||
#include "Instance.h"
|
||||
#include "Offsets.h"
|
||||
#include "net/PacketDispatch.h"
|
||||
#include "net/PacketReader.h"
|
||||
#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 +63,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 +327,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);
|
||||
}
|
||||
@@ -359,6 +362,11 @@ Entry *Claim(uint32_t now) {
|
||||
// Defined in the duration-modifier section below; used by StoreFromCast's
|
||||
// refresh path too.
|
||||
void SignalAuraChanged(uint64_t guid);
|
||||
void SignalEntryChanged(const Entry &e);
|
||||
void SignalEntryRefreshed(const Entry &e);
|
||||
// Defined with the aura handlers below; used by the refresh flush.
|
||||
Change MakeChange(ChangeType type, void *unit, int slot, uint32_t spellId);
|
||||
void NotifyObservers(const Change &change);
|
||||
|
||||
// Defined with the duration-modifier machinery below. A trigger can CREATE the
|
||||
// aura it then edits, in which case the edit is armed at trigger time and
|
||||
@@ -403,9 +411,10 @@ void StoreFromCast(uint64_t targetGuid, uint32_t spellId, uint64_t casterGuid,
|
||||
// An in-place recast refresh changes no descriptor field, so the engine
|
||||
// fires no UNIT_AURA — event-driven consumers (aura-bar addons counting
|
||||
// down a once-read duration) would never re-read the new timing. Signal it
|
||||
// ourselves (deferred to the world tick, coalesced). A NEW application
|
||||
// doesn't need this: its descriptor write fires the engine's own event.
|
||||
SignalAuraChanged(targetGuid);
|
||||
// ourselves (deferred to the world tick, coalesced), and report the
|
||||
// refresh. A NEW application doesn't need this: its descriptor write
|
||||
// fires the engine's own event.
|
||||
SignalEntryRefreshed(*e);
|
||||
ConsumePendingMods(*e, now);
|
||||
}
|
||||
|
||||
@@ -637,12 +646,68 @@ void SignalAuraChanged(uint64_t guid) {
|
||||
g_pendingSignals[g_pendingSignalCount++] = guid;
|
||||
}
|
||||
|
||||
// An entry's timing changed in place: the unit's UNIT_AURA re-broadcast, and
|
||||
// the instance in the entry's slot reported as updated to UNIT_AURA_DELTA.
|
||||
void SignalEntryChanged(const Entry &e) {
|
||||
Aura::Instance::NoteUpdated(e.targetGuid, e.slot);
|
||||
SignalAuraChanged(e.targetGuid);
|
||||
}
|
||||
|
||||
// The refreshes of this frame (SignalRefreshed), resolved by the flush.
|
||||
struct PendingRefresh {
|
||||
uint64_t guid;
|
||||
uint32_t spellId;
|
||||
int slot;
|
||||
};
|
||||
constexpr int kPendingRefreshMax = 32;
|
||||
PendingRefresh g_pendingRefreshes[kPendingRefreshMax];
|
||||
int g_pendingRefreshCount = 0;
|
||||
|
||||
// A server refresh the entry mirrors — a recast, a mechanic's reset to a full
|
||||
// duration: the timing signal, and a Refreshed change for the observers. Not
|
||||
// for the tick-speed compression's periodic nudge (this client's estimate
|
||||
// moving, no server event) nor a reduction.
|
||||
void SignalEntryRefreshed(const Entry &e) {
|
||||
SignalEntryChanged(e);
|
||||
SignalRefreshed(e.targetGuid, e.spellId, e.slot);
|
||||
}
|
||||
|
||||
// The slot of `unit`'s descriptor holding `spellId`, or -1.
|
||||
int DescriptorSlotOf(const uint8_t *unit, uint32_t spellId) {
|
||||
for (int slot = 0; slot < Offsets::UNIT_AURA_TOTAL; ++slot) {
|
||||
if (Aura::Data::ReadSpellID(unit, slot) == spellId)
|
||||
return slot;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Reports the frame's refreshes whose aura the descriptor still holds, in the
|
||||
// slot that was named when it still holds the spell, else wherever it is now.
|
||||
void FlushRefreshes() {
|
||||
constexpr int kUnitOrPlayerMask =
|
||||
(1 << Offsets::OBJECT_TYPE_UNIT) | (1 << Offsets::OBJECT_TYPE_PLAYER);
|
||||
const int count = g_pendingRefreshCount;
|
||||
g_pendingRefreshCount = 0; // an observer's own action may queue again
|
||||
for (int i = 0; i < count; ++i) {
|
||||
const PendingRefresh &p = g_pendingRefreshes[i];
|
||||
void *unit = Object::ByGuid(kUnitOrPlayerMask, p.guid, nullptr, 0);
|
||||
if (unit == nullptr)
|
||||
continue;
|
||||
const auto *u = static_cast<const uint8_t *>(unit);
|
||||
int slot = p.slot;
|
||||
if (slot < 0 || Aura::Data::ReadSpellID(u, slot) != p.spellId)
|
||||
slot = DescriptorSlotOf(u, p.spellId);
|
||||
if (slot < 0)
|
||||
continue;
|
||||
NotifyObservers(MakeChange(ChangeType::Refreshed, unit, slot, p.spellId));
|
||||
}
|
||||
}
|
||||
|
||||
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));
|
||||
FlushRefreshes();
|
||||
// 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;
|
||||
}
|
||||
|
||||
@@ -651,19 +716,20 @@ void ApplyModOp(Entry &e, int32_t op, int32_t valueMs, uint32_t now) {
|
||||
case MOD_REFRESH:
|
||||
if (e.durationMs > 0) {
|
||||
e.expirationMs = now + e.durationMs; // RefreshHolder → reset to max
|
||||
SignalAuraChanged(e.targetGuid);
|
||||
SignalEntryRefreshed(e);
|
||||
}
|
||||
break;
|
||||
case MOD_SET:
|
||||
e.durationMs = static_cast<uint32_t>(valueMs);
|
||||
e.expirationMs = now + static_cast<uint32_t>(valueMs);
|
||||
SignalAuraChanged(e.targetGuid);
|
||||
SignalEntryRefreshed(e);
|
||||
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);
|
||||
SignalEntryChanged(e);
|
||||
} else {
|
||||
e.used = false; // shaved to/past now → server removes it
|
||||
}
|
||||
@@ -957,16 +1023,9 @@ CompressState *FindOrClaimCompressState(uint64_t targetGuid,
|
||||
// would compress it, this gate excludes it exactly as the server's does.
|
||||
// (Drain Soul passes via its effect-2 periodic damage: aura=[86,3,0].)
|
||||
bool HasPeriodicDamageOrLeech(const uint8_t *rec) {
|
||||
if (rec == nullptr)
|
||||
return false;
|
||||
constexpr int32_t kPeriodicDamage = 3, kPeriodicLeech = 53;
|
||||
for (int i = 0; i < 3; ++i) {
|
||||
const int32_t aura = *reinterpret_cast<const int32_t *>(
|
||||
rec + Offsets::OFF_SPELL_RECORD_EFFECT_APPLY_AURA_NAME + i * 4);
|
||||
if (aura == kPeriodicDamage || aura == kPeriodicLeech)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
return Spell::Lookup::HasAuraEffect(rec, kPeriodicDamage) ||
|
||||
Spell::Lookup::HasAuraEffect(rec, kPeriodicLeech);
|
||||
}
|
||||
|
||||
// Compression pairs by CASTER, mirroring the server (each warlock's Dark
|
||||
@@ -1010,7 +1069,7 @@ void CompressTarget(const TickCompression &c, uint64_t targetGuid,
|
||||
// pollers pick it up on their own. First write nudges immediately.
|
||||
if (s->lastSignalMs == 0 || now - s->lastSignalMs >= 1000) {
|
||||
s->lastSignalMs = now;
|
||||
SignalAuraChanged(e.targetGuid);
|
||||
SignalEntryChanged(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1226,7 +1285,7 @@ int RefreshJudgementsImpl(uint64_t unitGuid, uint64_t attackerGuid, bool adopt)
|
||||
e.casterGuid = attackerGuid; // adoption claim
|
||||
e.expirationMs = now + e.durationMs; // RefreshHolder → own duration
|
||||
e.stampMs = now;
|
||||
SignalAuraChanged(e.targetGuid);
|
||||
SignalEntryRefreshed(e);
|
||||
++refreshed;
|
||||
}
|
||||
return refreshed;
|
||||
@@ -1263,23 +1322,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 {
|
||||
@@ -1336,7 +1378,7 @@ void RefreshTriggeredExisting(uint64_t victim, const TriggeredApplication &r,
|
||||
e.durationMs = newMs;
|
||||
e.expirationMs = now + newMs;
|
||||
e.stampMs = now;
|
||||
SignalAuraChanged(victim);
|
||||
SignalEntryRefreshed(e);
|
||||
break; // one aura instance per (target, spell, caster) — server touches one holder
|
||||
}
|
||||
}
|
||||
@@ -1355,7 +1397,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 +1448,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 +1605,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 +1630,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 +1714,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 +1749,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 +1783,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 +1793,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 +1838,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 +1866,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) {
|
||||
@@ -1792,7 +2020,7 @@ uint32_t RefreshDurationByFamily(uint64_t unitGuid, uint32_t family,
|
||||
// duration, not a five-point one.
|
||||
e.expirationMs = now + e.durationMs;
|
||||
e.stampMs = now;
|
||||
SignalAuraChanged(e.targetGuid);
|
||||
SignalEntryRefreshed(e);
|
||||
return e.spellId;
|
||||
}
|
||||
return 0;
|
||||
@@ -1813,7 +2041,7 @@ void RestampPlayerChannel(uint32_t spellId, uint32_t remainingMs) {
|
||||
continue;
|
||||
e.expirationMs = now + remainingMs;
|
||||
e.stampMs = now;
|
||||
SignalAuraChanged(e.targetGuid);
|
||||
SignalEntryChanged(e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1865,7 +2093,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 +2152,23 @@ void ObserveGroupAuras(uint64_t guid, const uint16_t *auraArray) {
|
||||
snap->touchMs = now;
|
||||
}
|
||||
|
||||
AutoObserve::AutoObserve(ChangeCallback cb) : callback(cb), next(g_observers) {
|
||||
g_observers = this;
|
||||
}
|
||||
|
||||
void SignalRefreshed(uint64_t unitGuid, uint32_t spellId, int slot) {
|
||||
if (unitGuid == 0 || spellId == 0)
|
||||
return;
|
||||
for (int i = 0; i < g_pendingRefreshCount; ++i) {
|
||||
PendingRefresh &p = g_pendingRefreshes[i];
|
||||
if (p.guid == unitGuid && p.spellId == spellId) {
|
||||
if (p.slot < 0)
|
||||
p.slot = slot;
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (g_pendingRefreshCount < kPendingRefreshMax)
|
||||
g_pendingRefreshes[g_pendingRefreshCount++] = {unitGuid, spellId, slot};
|
||||
}
|
||||
|
||||
} // 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,40 @@ 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 — or its
|
||||
// duration set again while it stays (Refreshed, see `SignalRefreshed`).
|
||||
enum class ChangeType { Added, Removed, Stacks, Refreshed };
|
||||
|
||||
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;
|
||||
};
|
||||
|
||||
// A duration set again for an aura already on `unitGuid`: the server's
|
||||
// SMSG_UPDATE_AURA_DURATION for an occupied slot of the player, a recast this
|
||||
// cache refreshed, a server refresh mechanic it mirrors. Observers get it as a
|
||||
// Refreshed change at the world tick, once per aura per frame, and only if the
|
||||
// descriptor then still holds the spell — a slot that changed hands in the
|
||||
// same tick was an application, not a refresh. `slot` may be SLOT_UNBOUND.
|
||||
void SignalRefreshed(uint64_t unitGuid, uint32_t spellId, int slot);
|
||||
|
||||
} // namespace Aura::Source
|
||||
|
||||
@@ -0,0 +1,468 @@
|
||||
// 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/>.
|
||||
|
||||
// C_AutoComplete: the player names an edit box can complete.
|
||||
//
|
||||
// 4.3.4's CGAutoCompleteName keeps its own list of names, each with flag bits
|
||||
// that the party, raid, guild, friend list and chat code add and remove as
|
||||
// those lists change. 1.12 has no such list, but it keeps every list the bits
|
||||
// come from, so a query reads them where the engine keeps them:
|
||||
// - party: the four VAR_PARTY_GUIDS, the name from the name cache, online
|
||||
// from the member stats block (Group::MemberStats) - InGroup;
|
||||
// - raid: the VAR_RAID_MEMBER_PTRS slots and their online bit - InGroup;
|
||||
// - guild roster: each GuildMemberInfo's GUID, name and online word, read
|
||||
// only while the player is in a guild, the test Script_IsInGuild
|
||||
// (0x00516DE0) makes, because the engine keeps the old roster after a
|
||||
// /gquit - InGuild;
|
||||
// - friends list: the social singleton's slots (FriendList.h) - Friend.
|
||||
// The one list the engine does not keep is ours: the players this character
|
||||
// whispered or was whispered by (Chat::Dispatch reports each line), in the
|
||||
// order they were last heard from - InteractedWith. Logging out clears it,
|
||||
// as 4.3.4's ShutdownGame clears its list.
|
||||
//
|
||||
// A player on several lists is one entry with every list's bit. A list that
|
||||
// holds the player decides Online; a player known only from a whisper is
|
||||
// Online, as 4.3.4 sets Online together with InteractedWith.
|
||||
//
|
||||
// Matching is 4.3.4's NodeMatchesParams (the same in 3.3.5's binary,
|
||||
// 0x0057ACA0), with two differences:
|
||||
// - a cursorPosition outside 1..length means the end of the text. Retail's
|
||||
// tell-target extraction (ChatFrameEditBox.lua) passes 0 and expects a
|
||||
// whole-text match;
|
||||
// - the edit-from-center search also tries the last place. The engine's
|
||||
// loop stops one place early, so it never finds the text after the
|
||||
// cursor at the end of a name.
|
||||
// Order is 3.3.5's SortNameNode (0x0057B130): with
|
||||
// autoCompleteResortNamesOnRecency on, the most recent whisper first, then by
|
||||
// name. Retail's client cannot be read, so each result's priority is the
|
||||
// highest Enum.AutoCompletePriority its bits reach, in the enum's own order:
|
||||
// Friend, Guild, InGroup, Interacted, else Other.
|
||||
|
||||
#include "autocomplete/Names.h"
|
||||
|
||||
#include "Game.h"
|
||||
#include "Offsets.h"
|
||||
#include "cvar/Factory.h"
|
||||
#include "friendlist/FriendList.h"
|
||||
#include "group/MemberStats.h"
|
||||
#include "guid/Guid.h"
|
||||
#include "text/Utf8.h"
|
||||
#include "unit/Identity.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace AutoComplete::Names {
|
||||
|
||||
namespace {
|
||||
|
||||
// Enum.AutoCompleteEntryFlag. 1.12 has nothing to fill Bnet, InAOI,
|
||||
// AccountCharacter or RecentPlayer from.
|
||||
enum EntryFlag : uint32_t {
|
||||
FLAG_IN_GROUP = 0x1,
|
||||
FLAG_IN_GUILD = 0x2,
|
||||
FLAG_FRIEND = 0x4,
|
||||
FLAG_BNET = 0x8,
|
||||
FLAG_INTERACTED_WITH = 0x10,
|
||||
FLAG_ONLINE = 0x20,
|
||||
FLAG_IN_AOI = 0x40,
|
||||
FLAG_ACCOUNT_CHARACTER = 0x80,
|
||||
FLAG_RECENT_PLAYER = 0x100,
|
||||
};
|
||||
|
||||
// Enum.AutoCompletePriority.
|
||||
enum Priority {
|
||||
PRIORITY_OTHER = 0,
|
||||
PRIORITY_INTERACTED = 1,
|
||||
PRIORITY_IN_GROUP = 2,
|
||||
PRIORITY_GUILD = 3,
|
||||
PRIORITY_FRIEND = 4,
|
||||
PRIORITY_ACCOUNT_CHARACTER = 5,
|
||||
PRIORITY_ACCOUNT_CHARACTER_SAME_REALM = 6,
|
||||
};
|
||||
|
||||
constexpr int CHAT_MSG_WHISPER = 6;
|
||||
constexpr int CHAT_MSG_WHISPER_INFORM = 7;
|
||||
constexpr int LANGUAGE_ADDON = -1; // the dispatch's addon-message arm
|
||||
|
||||
CVar::Factory::Handle g_resortOnRecency = nullptr;
|
||||
CVar::Factory::Handle g_editFromCenter = nullptr;
|
||||
CVar::Factory::Handle g_useContext = nullptr;
|
||||
|
||||
bool CVarOn(CVar::Factory::Handle cvar) { return CVar::Factory::GetInt(cvar, 1) != 0; }
|
||||
|
||||
// A whisper partner. `order` grows with every whisper, so a larger one was
|
||||
// heard from more recently.
|
||||
struct Interaction {
|
||||
uint64_t guid;
|
||||
std::string name;
|
||||
uint32_t order;
|
||||
};
|
||||
|
||||
std::vector<Interaction> g_interactions;
|
||||
uint32_t g_lastOrder = 0;
|
||||
|
||||
// One player as one list knows them, or, after Merge, as all lists do.
|
||||
struct Entry {
|
||||
uint64_t guid;
|
||||
const char *name; // the list's own storage, valid until Lua runs
|
||||
uint32_t flags; // EntryFlag bits, Online excluded
|
||||
bool listed; // a group, guild or friends list holds the player
|
||||
bool online; // what those lists say
|
||||
uint32_t order; // the Interaction's order, 0 for none
|
||||
};
|
||||
|
||||
bool InGuild() {
|
||||
const uint8_t *player = Unit::Identity::PlayerObject();
|
||||
if (player == nullptr)
|
||||
return false;
|
||||
const auto *info = Game::Read<const uint8_t *>(player, Offsets::OFF_CGPLAYER_INFO);
|
||||
return info != nullptr && Game::Read<uint32_t>(info, Offsets::OFF_PLAYER_INFO_GUILD_KEY) != 0;
|
||||
}
|
||||
|
||||
// Every player whose name `match` accepts, one entry per list that has them.
|
||||
template <typename Match>
|
||||
std::vector<Entry> Collect(Match match) {
|
||||
std::vector<Entry> found;
|
||||
const uint64_t self = Unit::Identity::PlayerGuid();
|
||||
const auto add = [&](uint64_t guid, const char *name, uint32_t flag, bool listed, bool online,
|
||||
uint32_t order) {
|
||||
if (guid == 0 || guid == self || name == nullptr || *name == '\0' || !match(name))
|
||||
return;
|
||||
found.push_back({guid, name, flag, listed, online, order});
|
||||
};
|
||||
|
||||
const auto *party =
|
||||
reinterpret_cast<const uint64_t *>(static_cast<uintptr_t>(Offsets::VAR_PARTY_GUIDS));
|
||||
for (int i = 0; i < Offsets::PARTY_MAX_SLOTS; ++i) {
|
||||
const uint64_t guid = party[i];
|
||||
if (guid != 0)
|
||||
add(guid, Unit::Identity::NameForGuid(guid), FLAG_IN_GROUP, true,
|
||||
Group::MemberStats::Lookup(guid).online, 0);
|
||||
}
|
||||
|
||||
int raidCount = Game::Read<int>(Offsets::VAR_RAID_MEMBER_COUNT);
|
||||
if (raidCount > Offsets::RAID_MAX_SLOTS)
|
||||
raidCount = Offsets::RAID_MAX_SLOTS;
|
||||
const auto *slots = reinterpret_cast<const uint8_t *const *>(
|
||||
static_cast<uintptr_t>(Offsets::VAR_RAID_MEMBER_PTRS));
|
||||
for (int i = 0; i < raidCount; ++i) {
|
||||
if (slots[i] == nullptr)
|
||||
continue;
|
||||
const uint64_t guid = Game::Read<uint64_t>(slots[i], 0);
|
||||
const uint32_t flags = Game::Read<uint32_t>(slots[i], Offsets::OFF_RAID_SLOT_FLAGS);
|
||||
add(guid, Unit::Identity::NameForGuid(guid), FLAG_IN_GROUP, true,
|
||||
(flags & Offsets::RAID_SLOT_FLAG_ONLINE) != 0, 0);
|
||||
}
|
||||
|
||||
if (InGuild()) {
|
||||
auto **roster = Game::Read<const uint8_t **>(Offsets::VAR_GUILD_ROSTER_PTR);
|
||||
const int total = Game::Read<int>(Offsets::VAR_GUILD_ROSTER_TOTAL_COUNT);
|
||||
for (int i = 0; roster != nullptr && i < total; ++i) {
|
||||
const uint8_t *member = roster[i];
|
||||
if (member == nullptr)
|
||||
continue;
|
||||
add(Game::Read<uint64_t>(member, Offsets::OFF_GUILD_MEMBER_GUID),
|
||||
reinterpret_cast<const char *>(member + Offsets::OFF_GUILD_MEMBER_NAME),
|
||||
FLAG_IN_GUILD, true,
|
||||
Game::Read<uint32_t>(member, Offsets::OFF_GUILD_MEMBER_ONLINE) != 0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
const int friends = FriendList::Count();
|
||||
for (int i = 0; i < friends; ++i) {
|
||||
const uint8_t *entry = FriendList::EntryByIndex(i);
|
||||
if (entry == nullptr)
|
||||
break;
|
||||
add(Game::Read<uint64_t>(entry, FriendList::OFF_FRIEND_GUID),
|
||||
Game::Read<const char *>(entry, FriendList::OFF_FRIEND_NAME), FLAG_FRIEND, true,
|
||||
Game::Read<uint8_t>(entry, FriendList::OFF_FRIEND_CONNECTED) != 0, 0);
|
||||
}
|
||||
|
||||
for (const Interaction &i : g_interactions)
|
||||
add(i.guid, i.name.c_str(), FLAG_INTERACTED_WITH, false, false, i.order);
|
||||
|
||||
return found;
|
||||
}
|
||||
|
||||
// One entry per player, with every list's bits and Online decided; then the
|
||||
// include / exclude test, which autoCompleteUseContext turns off.
|
||||
std::vector<Entry> Merge(std::vector<Entry> found, uint32_t include, uint32_t exclude) {
|
||||
std::sort(found.begin(), found.end(),
|
||||
[](const Entry &a, const Entry &b) { return a.guid < b.guid; });
|
||||
std::vector<Entry> merged;
|
||||
for (const Entry &e : found) {
|
||||
if (!merged.empty() && merged.back().guid == e.guid) {
|
||||
Entry &m = merged.back();
|
||||
m.flags |= e.flags;
|
||||
m.listed = m.listed || e.listed;
|
||||
m.online = m.online || e.online;
|
||||
m.order = std::max(m.order, e.order);
|
||||
} else {
|
||||
merged.push_back(e);
|
||||
}
|
||||
}
|
||||
|
||||
const bool useContext = CVarOn(g_useContext);
|
||||
std::vector<Entry> kept;
|
||||
for (Entry &e : merged) {
|
||||
if (e.listed ? e.online : (e.flags & FLAG_INTERACTED_WITH) != 0)
|
||||
e.flags |= FLAG_ONLINE;
|
||||
if (!useContext || ((e.flags & include) != 0 && (e.flags & exclude) == 0))
|
||||
kept.push_back(e);
|
||||
}
|
||||
return kept;
|
||||
}
|
||||
|
||||
int PriorityOf(uint32_t flags) {
|
||||
if (flags & FLAG_FRIEND)
|
||||
return PRIORITY_FRIEND;
|
||||
if (flags & FLAG_IN_GUILD)
|
||||
return PRIORITY_GUILD;
|
||||
if (flags & FLAG_IN_GROUP)
|
||||
return PRIORITY_IN_GROUP;
|
||||
if (flags & FLAG_INTERACTED_WITH)
|
||||
return PRIORITY_INTERACTED;
|
||||
return PRIORITY_OTHER;
|
||||
}
|
||||
|
||||
// Past `chars` code points of `s`, continuation bytes included, stopping at
|
||||
// the terminator. (Storm's SStrAdvanceCharsUTF8 stops one byte into a
|
||||
// multi-byte character.)
|
||||
const char *Advance(const char *s, size_t chars) {
|
||||
for (; *s != '\0' && chars != 0; --chars) {
|
||||
++s;
|
||||
while ((static_cast<uint8_t>(*s) & 0xC0) == 0x80)
|
||||
++s;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
// What the edit box holds: the text and the cursor in it, in code points.
|
||||
struct Typed {
|
||||
const char *text;
|
||||
size_t length;
|
||||
size_t cursor;
|
||||
bool allowFullMatch;
|
||||
bool editFromCenter;
|
||||
};
|
||||
|
||||
bool Completes(const Typed &t, const char *name) {
|
||||
if (!t.allowFullMatch && Text::Utf8::CompareI(t.text, name) == 0)
|
||||
return false;
|
||||
if (!t.editFromCenter || t.cursor == t.length)
|
||||
return Text::Utf8::CompareI(t.text, name, t.length) == 0;
|
||||
|
||||
// The text before the cursor starts the name, and the text after it
|
||||
// follows somewhere later in the name.
|
||||
if (Text::Utf8::CompareI(t.text, name, t.cursor) != 0)
|
||||
return false;
|
||||
const size_t nameLength = Text::Utf8::Length(name);
|
||||
if (nameLength < t.length)
|
||||
return false;
|
||||
const char *tail = Advance(t.text, t.cursor);
|
||||
const size_t tailLength = t.length - t.cursor;
|
||||
const char *at = Advance(name, t.cursor);
|
||||
for (size_t places = nameLength - t.length + 1; places != 0; --places) {
|
||||
if (Text::Utf8::CompareI(at, tail, tailLength) == 0)
|
||||
return true;
|
||||
at = Advance(at, 1);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// A flag mask from Lua: bit.bor results above 0x7FFFFFFF arrive negative.
|
||||
uint32_t FlagArg(void *L, int index) {
|
||||
return static_cast<uint32_t>(static_cast<int64_t>(Game::Lua::ToNumber(L, index)));
|
||||
}
|
||||
|
||||
// C_AutoComplete.GetAutoCompleteResults(name, numResults, cursorPosition,
|
||||
// allowFullMatch, includeFlags, excludeFlags) -> results
|
||||
// A numResults of 0 or less returns every match, as the engine's count test
|
||||
// (`++count == numReturns`) does.
|
||||
int __fastcall Script_GetAutoCompleteResults(void *L) {
|
||||
if (!Game::Lua::IsString(L, 1) || !Game::Lua::IsNumber(L, 2) || !Game::Lua::IsNumber(L, 3) ||
|
||||
!Game::Lua::IsNumber(L, 5) || !Game::Lua::IsNumber(L, 6)) {
|
||||
Game::Lua::Error(L, "Usage: C_AutoComplete.GetAutoCompleteResults(name, numResults, "
|
||||
"cursorPosition, allowFullMatch, includeFlags, excludeFlags)");
|
||||
return 0;
|
||||
}
|
||||
Typed typed;
|
||||
typed.text = Game::Lua::ToString(L, 1);
|
||||
typed.length = Text::Utf8::Length(typed.text);
|
||||
const double cursor = Game::Lua::ToNumber(L, 3);
|
||||
typed.cursor = cursor >= 1 && cursor <= static_cast<double>(typed.length)
|
||||
? static_cast<size_t>(cursor)
|
||||
: typed.length;
|
||||
typed.allowFullMatch = Game::Lua::ToBoolean(L, 4) != 0;
|
||||
typed.editFromCenter = CVarOn(g_editFromCenter);
|
||||
const int numResults = static_cast<int>(Game::Lua::ToNumber(L, 2));
|
||||
|
||||
std::vector<Entry> matches =
|
||||
Merge(Collect([&](const char *name) { return Completes(typed, name); }), FlagArg(L, 5),
|
||||
FlagArg(L, 6));
|
||||
const bool recency = CVarOn(g_resortOnRecency);
|
||||
std::sort(matches.begin(), matches.end(), [recency](const Entry &a, const Entry &b) {
|
||||
if (recency && a.order != b.order)
|
||||
return a.order > b.order;
|
||||
return Text::Utf8::CompareI(a.name, b.name) < 0;
|
||||
});
|
||||
if (numResults > 0 && matches.size() > static_cast<size_t>(numResults))
|
||||
matches.resize(numResults);
|
||||
|
||||
Game::Lua::NewTable(L);
|
||||
for (size_t i = 0; i < matches.size(); ++i) {
|
||||
Game::Lua::PushNumber(L, static_cast<double>(i + 1));
|
||||
Game::Lua::NewTable(L);
|
||||
Game::Lua::SetFieldString(L, "name", matches[i].name);
|
||||
Game::Lua::SetFieldNumber(L, "priority", PriorityOf(matches[i].flags));
|
||||
Game::Lua::SetFieldNumber(L, "bnetID", 0);
|
||||
Game::Lua::RawSet(L, -3);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
// C_AutoComplete.IsRecognizedName(name, includeFlags, excludeFlags) -> bool
|
||||
int __fastcall Script_IsRecognizedName(void *L) {
|
||||
if (!Game::Lua::IsString(L, 1) || !Game::Lua::IsNumber(L, 2) || !Game::Lua::IsNumber(L, 3)) {
|
||||
Game::Lua::Error(L,
|
||||
"Usage: C_AutoComplete.IsRecognizedName(name, includeFlags, excludeFlags)");
|
||||
return 0;
|
||||
}
|
||||
const char *text = Game::Lua::ToString(L, 1);
|
||||
const std::vector<Entry> matches =
|
||||
Merge(Collect([text](const char *name) { return Text::Utf8::CompareI(text, name) == 0; }),
|
||||
FlagArg(L, 2), FlagArg(L, 3));
|
||||
Game::Lua::PushBool(L, !matches.empty());
|
||||
return 1;
|
||||
}
|
||||
|
||||
void ClearOnLogout() {
|
||||
g_interactions.clear();
|
||||
g_lastOrder = 0;
|
||||
}
|
||||
|
||||
const Game::GlueModuleAutoRegister _clearOnLogout{&ClearOnLogout};
|
||||
|
||||
// --- Documentation ----------------------------------------------------------
|
||||
|
||||
const Game::Doc::Field kResultFields[] = {
|
||||
Game::Doc::Req("name", "string"),
|
||||
Game::Doc::Req("priority", "AutoCompletePriority",
|
||||
"The closest tie to the player: friend, guild, group, whisper, or none."),
|
||||
Game::Doc::Req("bnetID", "number", "Always 0."),
|
||||
};
|
||||
const Game::Doc::Structure kResult{"AutoCompleteResult", "AutoComplete", kResultFields};
|
||||
|
||||
const Game::Doc::Field kResultsArgs[] = {
|
||||
Game::Doc::Req("name", "string", "The text typed so far."),
|
||||
Game::Doc::Req("numResults", "number", "The most results to return; 0 returns all."),
|
||||
Game::Doc::Req("cursorPosition", "number", "The cursor's place in the text, in characters."),
|
||||
Game::Doc::Req("allowFullMatch", "bool", "Whether a name equal to the text can be a result."),
|
||||
Game::Doc::Req("includeFlags", "number",
|
||||
"Enum.AutoCompleteEntryFlag bits; a result has at least one."),
|
||||
Game::Doc::Req("excludeFlags", "number",
|
||||
"Enum.AutoCompleteEntryFlag bits; a result has none."),
|
||||
};
|
||||
const Game::Doc::Field kResultsRets[] = {
|
||||
Game::Doc::Req("results", "table", "Array of AutoCompleteResult."),
|
||||
};
|
||||
const Game::Doc::Function kGetAutoCompleteResults{
|
||||
"The known players whose names complete the typed text.", kResultsArgs, kResultsRets};
|
||||
|
||||
const Game::Doc::Field kRecognizedArgs[] = {
|
||||
Game::Doc::Req("name", "string"),
|
||||
Game::Doc::Req("includeFlags", "number",
|
||||
"Enum.AutoCompleteEntryFlag bits; the player has at least one."),
|
||||
Game::Doc::Req("excludeFlags", "number",
|
||||
"Enum.AutoCompleteEntryFlag bits; the player has none."),
|
||||
};
|
||||
const Game::Doc::Field kRecognizedRets[] = {
|
||||
Game::Doc::Req("isRecognizedName", "bool"),
|
||||
};
|
||||
const Game::Doc::Function kIsRecognizedName{"Whether a known player has exactly this name.",
|
||||
kRecognizedArgs, kRecognizedRets};
|
||||
|
||||
const Game::Lua::EnumIntegerEntry kEntryFlagEntries[] = {
|
||||
{"InGroup", FLAG_IN_GROUP},
|
||||
{"InGuild", FLAG_IN_GUILD},
|
||||
{"Friend", FLAG_FRIEND},
|
||||
{"Bnet", FLAG_BNET},
|
||||
{"InteractedWith", FLAG_INTERACTED_WITH},
|
||||
{"Online", FLAG_ONLINE},
|
||||
{"InAOI", FLAG_IN_AOI},
|
||||
{"AccountCharacter", FLAG_ACCOUNT_CHARACTER},
|
||||
{"RecentPlayer", FLAG_RECENT_PLAYER},
|
||||
};
|
||||
|
||||
const Game::Lua::EnumIntegerEntry kPriorityEntries[] = {
|
||||
{"Other", PRIORITY_OTHER},
|
||||
{"Interacted", PRIORITY_INTERACTED},
|
||||
{"InGroup", PRIORITY_IN_GROUP},
|
||||
{"Guild", PRIORITY_GUILD},
|
||||
{"Friend", PRIORITY_FRIEND},
|
||||
{"AccountCharacter", PRIORITY_ACCOUNT_CHARACTER},
|
||||
{"AccountCharacterSameRealm", PRIORITY_ACCOUNT_CHARACTER_SAME_REALM},
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
void OnChat(int chatType, int languageID, const char *name, uint64_t guid) {
|
||||
if (chatType != CHAT_MSG_WHISPER && chatType != CHAT_MSG_WHISPER_INFORM)
|
||||
return;
|
||||
if (languageID == LANGUAGE_ADDON || guid == 0 || !Guid::IsPlayer(guid) || name == nullptr ||
|
||||
*name == '\0')
|
||||
return;
|
||||
++g_lastOrder;
|
||||
for (Interaction &i : g_interactions) {
|
||||
if (i.guid == guid) {
|
||||
i.name = name;
|
||||
i.order = g_lastOrder;
|
||||
return;
|
||||
}
|
||||
}
|
||||
g_interactions.push_back({guid, name, g_lastOrder});
|
||||
}
|
||||
|
||||
static void RegisterLuaFunctions() {
|
||||
// Retail's help lines and category (Ketho's CVars.lua dump).
|
||||
g_resortOnRecency = CVar::Factory::Register(
|
||||
"autoCompleteResortNamesOnRecency",
|
||||
"Shows people you recently spoke with higher up on the AutoComplete list.",
|
||||
Offsets::CVAR_CATEGORY_GAME, "1");
|
||||
g_editFromCenter = CVar::Factory::Register(
|
||||
"autoCompleteWhenEditingFromCenter",
|
||||
"If you edit a name by inserting characters into the center, a smarter auto-complete "
|
||||
"will occur.",
|
||||
Offsets::CVAR_CATEGORY_GAME, "1");
|
||||
g_useContext = CVar::Factory::Register(
|
||||
"autoCompleteUseContext",
|
||||
"The system will, for example, only show people in your guild when you are typing "
|
||||
"/gpromote. Names will also never be removed.",
|
||||
Offsets::CVAR_CATEGORY_GAME, "1");
|
||||
|
||||
Game::Lua::RegisterTableFunction("C_AutoComplete", "GetAutoCompleteResults",
|
||||
&Script_GetAutoCompleteResults, &kGetAutoCompleteResults);
|
||||
Game::Lua::RegisterTableFunction("C_AutoComplete", "IsRecognizedName", &Script_IsRecognizedName,
|
||||
&kIsRecognizedName);
|
||||
Game::Lua::RegisterIntegerEnum(
|
||||
"Enum", "AutoCompleteEntryFlag", kEntryFlagEntries, "AutoComplete");
|
||||
Game::Lua::RegisterIntegerEnum(
|
||||
"Enum", "AutoCompletePriority", kPriorityEntries, "AutoComplete");
|
||||
}
|
||||
|
||||
static const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions};
|
||||
|
||||
} // namespace AutoComplete::Names
|
||||
@@ -0,0 +1,27 @@
|
||||
// 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>
|
||||
|
||||
namespace AutoComplete::Names {
|
||||
|
||||
// Chat::Dispatch calls this for every dispatched chat line, before the engine
|
||||
// fires its CHAT_MSG_* event. A whisper to or from a player (`guid` is the
|
||||
// other player: Chat::Dispatch's sender) makes that player an InteractedWith
|
||||
// name, most recent first — 4.3.4's ChatFrame does the same in its message
|
||||
// handler. Every other line is ignored.
|
||||
void OnChat(int chatType, int languageID, const char *name, uint64_t guid);
|
||||
|
||||
} // namespace AutoComplete::Names
|
||||
+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};
|
||||
|
||||
|
||||
@@ -19,8 +19,9 @@
|
||||
// the `BAG_UPDATE_DELAYED` event. Subscribe here to run C++ work exactly once
|
||||
// per frame in which any bag actually changed, instead of polling every frame.
|
||||
//
|
||||
// Callbacks fire at the tail of the world tick, after every BAG_UPDATE for the
|
||||
// frame has already fired (so bag contents are settled). No firing on frames
|
||||
// Callbacks fire from the world tick's subscription, after the frame's UI draw
|
||||
// and after every BAG_UPDATE for the frame has already fired (so bag contents
|
||||
// are settled). No firing on frames
|
||||
// where nothing changed. Order across subscribers is unspecified.
|
||||
//
|
||||
// Module pattern, matching `Tick::WorldTick::AutoSubscribe`: declare a
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
// 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/>.
|
||||
|
||||
// `debuglocals([level [, skipFunctionsAndUserdata]])` — the locals and then
|
||||
// the upvalues of a call level as text, one `name=value` line each, for an
|
||||
// error report. 4.3.4's Script_debuglocals and the FrameScript_PackVariable
|
||||
// it formats with, in retail's spacing (probed: `n=7`, `s="hi"`,
|
||||
// `t=<table>{`, ` k=1`, `}`; 4.3.4 writes `n = 7` and `t = <table> {`):
|
||||
// - Only while an error handler runs; otherwise it returns nothing. 4.3.4
|
||||
// tests a flag its error function sets around the handler call. 1.12's
|
||||
// error function sets none, but while a handler runs that function's
|
||||
// level is on the stack (ErrorCallstack::ErrorFunctionLevel).
|
||||
// - `level` counts as lua_getstack and debugstack do: 1 is the caller.
|
||||
// Less than 1 is 1.
|
||||
// - A table prints as `name=<table>{`, or with the frame's name for a
|
||||
// frame (t[0], as FrameScript_GetObject reads it), then its fields one
|
||||
// space in at the top level only, then `}`. A function prints where it
|
||||
// is defined. The text stops at 4095 bytes, each line at 1023.
|
||||
// Retail's second argument, which its Blizzard_ScriptErrors passes as true,
|
||||
// leaves out the function and userdata values, at the top level and in
|
||||
// tables.
|
||||
//
|
||||
// A number key in int range prints truncated with %d, as 4.3.4's
|
||||
// IsIntegerNumber tests only the range: 2.5 prints as 2. Two departures from
|
||||
// 4.3.4, both where it would fail inside the handler: a number key outside
|
||||
// that range is formatted from a copy, not converted in place (that breaks
|
||||
// lua_next), and a key that is not a number or string prints as its type in
|
||||
// angle brackets (4.3.4 formats a null string).
|
||||
//
|
||||
// Retail also lists `(*temporary)` lines: 5.1's lua_getlocal names each stack
|
||||
// slot past a level's locals so, a C level's arguments included (an
|
||||
// `error("x")` report shows `(*temporary)="x"`). 1.12's lua_getlocal
|
||||
// (0x6FBB20) is 5.0's, which names declared locals only. Those slots are
|
||||
// the compiler's registers, which 5.0 and 5.1 allocate differently, so they
|
||||
// are left out rather than imitated.
|
||||
//
|
||||
// Registered on both Lua states, like the base-library helpers.
|
||||
|
||||
#include "Game.h"
|
||||
#include "Offsets.h"
|
||||
#include "baselib/ErrorCallstack.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
|
||||
namespace BaseLib::DebugLocals {
|
||||
|
||||
namespace {
|
||||
|
||||
namespace Lua = Game::Lua;
|
||||
|
||||
using lua_getlocal_t = const char *(__fastcall *)(void *L, const void *ar, int n);
|
||||
using lua_getupvalue_t = const char *(__fastcall *)(void *L, int funcindex, int n);
|
||||
|
||||
const auto GetLocal = reinterpret_cast<lua_getlocal_t>(Offsets::LUA_GET_LOCAL);
|
||||
const auto GetUpvalue = reinterpret_cast<lua_getupvalue_t>(Offsets::LUA_GET_UPVALUE);
|
||||
|
||||
constexpr size_t kTextMax = 4095; // 4.3.4's 4096-byte buffer, less its NUL
|
||||
constexpr size_t kLineSize = 1024;
|
||||
|
||||
struct Packer {
|
||||
void *L;
|
||||
bool skipFunctionsAndUserdata;
|
||||
std::string text;
|
||||
|
||||
void Line(const char *fmt, const char *indent, const char *name, const char *value = "",
|
||||
int number = 0) {
|
||||
char line[kLineSize];
|
||||
std::snprintf(line, sizeof line, fmt, indent, name, value, number);
|
||||
const size_t room = kTextMax - text.size();
|
||||
text.append(line, std::min(room, std::strlen(line)));
|
||||
}
|
||||
|
||||
// The value on the stack top, as 4.3.4's FrameScript_PackVariable.
|
||||
void Pack(const char *name, int depth) {
|
||||
const char *indent = depth > 0 ? " " : "";
|
||||
switch (Lua::Type(L, -1)) {
|
||||
case Lua::TYPE_NIL:
|
||||
Line("%s%s=nil\n", indent, name);
|
||||
break;
|
||||
case Lua::TYPE_BOOLEAN:
|
||||
Line("%s%s=%s\n", indent, name, Lua::ToBoolean(L, -1) ? "true" : "false");
|
||||
break;
|
||||
case Lua::TYPE_LIGHTUSERDATA:
|
||||
case Lua::TYPE_USERDATA:
|
||||
if (!skipFunctionsAndUserdata)
|
||||
Line("%s%s=<userdata>\n", indent, name);
|
||||
break;
|
||||
case Lua::TYPE_NUMBER:
|
||||
Line("%s%s=%s\n", indent, name, Lua::ToString(L, -1)); // a copy: safe to convert
|
||||
break;
|
||||
case Lua::TYPE_STRING:
|
||||
Line("%s%s=\"%s\"\n", indent, name, Lua::ToString(L, -1));
|
||||
break;
|
||||
case Lua::TYPE_TABLE:
|
||||
PackTable(name, depth, indent);
|
||||
break;
|
||||
case Lua::TYPE_FUNCTION:
|
||||
if (!skipFunctionsAndUserdata)
|
||||
PackFunction(name, indent);
|
||||
break;
|
||||
default:
|
||||
Line("%s%s=<%s>\n", indent, name, Lua::TypeName(L, Lua::Type(L, -1)));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void PackTable(const char *name, int depth, const char *indent) {
|
||||
void *object = Lua::ResolveObject(L, -1);
|
||||
Line("%s%s=%s{\n", indent, name, object ? Lua::ObjectDisplayName(object) : "<table>");
|
||||
if (depth == 0) {
|
||||
Lua::PushNil(L);
|
||||
while (Lua::Next(L, -2) != 0) {
|
||||
char key[32];
|
||||
const char *keyName = key;
|
||||
const int keyType = Lua::Type(L, -2);
|
||||
const double number = keyType == Lua::TYPE_NUMBER ? Lua::ToNumber(L, -2) : 0;
|
||||
if (keyType == Lua::TYPE_NUMBER && std::isfinite(number) && number >= -2147483648.0 &&
|
||||
number <= 2147483647.0) {
|
||||
std::snprintf(key, sizeof key, "%d", static_cast<int>(number));
|
||||
} else if (keyType == Lua::TYPE_STRING) {
|
||||
keyName = Lua::ToString(L, -2);
|
||||
} else if (keyType == Lua::TYPE_NUMBER) {
|
||||
Lua::PushValue(L, -2);
|
||||
std::snprintf(key, sizeof key, "%s", Lua::ToString(L, -1));
|
||||
Lua::SetTop(L, -2);
|
||||
} else {
|
||||
std::snprintf(key, sizeof key, "<%s>", Lua::TypeName(L, keyType));
|
||||
}
|
||||
Pack(keyName, 1);
|
||||
Lua::SetTop(L, -2); // the value; the key stays for lua_next
|
||||
}
|
||||
}
|
||||
Line("%s}\n", indent, "");
|
||||
}
|
||||
|
||||
void PackFunction(const char *name, const char *indent) {
|
||||
alignas(4) uint8_t ar[Offsets::SIZEOF_LUA_DEBUG];
|
||||
Lua::PushValue(L, -1);
|
||||
Lua::GetInfo(L, ">nS", ar); // pops the copy
|
||||
const auto field = [&ar](uintptr_t offset) { return Game::Read<const char *>(ar, offset); };
|
||||
const char *source = field(Offsets::OFF_LUA_DEBUG_SOURCE);
|
||||
const int line = Game::Read<int>(ar, Offsets::OFF_LUA_DEBUG_LINEDEFINED);
|
||||
if (const char *fn = field(Offsets::OFF_LUA_DEBUG_NAME)) {
|
||||
char named[kLineSize];
|
||||
std::snprintf(named, sizeof named, "%s() defined %s", fn, source ? source : "?");
|
||||
Line("%s%s=%s:%d\n", indent, name, named, line);
|
||||
} else {
|
||||
Line("%s%s=<function> defined %s:%d\n", indent, name, source ? source : "?", line);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
int __fastcall Script_debuglocals(void *L) {
|
||||
if (ErrorCallstack::ErrorFunctionLevel(L) == 0)
|
||||
return 0;
|
||||
int level = static_cast<int>(Lua::ToNumber(L, 1));
|
||||
if (level <= 0)
|
||||
level = 1;
|
||||
Packer packer{L, Lua::ToBoolean(L, 2) != 0, {}};
|
||||
|
||||
alignas(4) uint8_t ar[Offsets::SIZEOF_LUA_DEBUG];
|
||||
if (Lua::GetStack(L, level, ar)) {
|
||||
const char *name;
|
||||
for (int i = 1; (name = GetLocal(L, ar, i)) != nullptr; i++) {
|
||||
packer.Pack(name, 0);
|
||||
Lua::SetTop(L, -2);
|
||||
}
|
||||
Lua::GetInfo(L, "f", ar); // the level's function
|
||||
for (int i = 1; (name = GetUpvalue(L, -1, i)) != nullptr; i++) {
|
||||
packer.Pack(name, 0);
|
||||
Lua::SetTop(L, -2);
|
||||
}
|
||||
Lua::SetTop(L, -2);
|
||||
}
|
||||
Lua::PushLString(L, packer.text.data(), static_cast<unsigned int>(packer.text.size()));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const Game::Doc::Field kDebuglocalsArgs[] = {
|
||||
Game::Doc::Opt("level", "number", "1", "The call level, as debugstack counts it."),
|
||||
Game::Doc::Opt("skipFunctionsAndUserdata", "boolean", "false",
|
||||
"Leaves out function and userdata values."),
|
||||
};
|
||||
const Game::Doc::Field kDebuglocalsRets[] = {
|
||||
Game::Doc::Opt("locals", "string", nullptr,
|
||||
"One `name=value` line for each local and upvalue. Nothing outside an "
|
||||
"error handler."),
|
||||
};
|
||||
const Game::Doc::Function kDebuglocals{
|
||||
"The local variables and upvalues of a call level as text, for an error report.",
|
||||
kDebuglocalsArgs, kDebuglocalsRets, "LuaGlobals"};
|
||||
|
||||
void RegisterInGame() {
|
||||
Game::Lua::RegisterGlobalFunction("debuglocals", &Script_debuglocals, &kDebuglocals);
|
||||
}
|
||||
|
||||
void RegisterGlue() {
|
||||
Game::Lua::RegisterGlueFunction("debuglocals", &Script_debuglocals, &kDebuglocals);
|
||||
}
|
||||
|
||||
const Game::ModuleAutoRegister _autoreg{&RegisterInGame};
|
||||
const Game::GlueModuleAutoRegister _autoregGlue{&RegisterGlue};
|
||||
|
||||
} // namespace
|
||||
|
||||
} // namespace BaseLib::DebugLocals
|
||||
@@ -0,0 +1,102 @@
|
||||
// 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/>.
|
||||
|
||||
// `debugstack([thread,] [start [, count1 [, count2]]])` — the stack of a
|
||||
// coroutine, as 4.3.4's Script_debugstack takes it: with a thread first,
|
||||
// the levels are that thread's and `start` defaults to 0 (the thread's
|
||||
// innermost level) instead of 1.
|
||||
//
|
||||
// 1.12's debugstack (FUN_SCRIPT_DEBUGSTACK) has no thread argument, and a
|
||||
// thread falls through its argument checks so that it returns the thread
|
||||
// itself: `msg .. debugstack(co)` raises "attempt to concatenate a thread
|
||||
// value" in the coroutine error paths of WeakAuras, Questie's ThreadLib,
|
||||
// MRT and Zygor.
|
||||
//
|
||||
// The engine's function still does the work, so its text and its head and
|
||||
// tail windows stay exactly as they are. It reads levels through six calls
|
||||
// (five lua_getstack, one lua_getinfo), and those calls are redirected to
|
||||
// read from the state Script_debugstack names for the call: the thread, or
|
||||
// the calling state when there is none. Script_debugstack replaces the
|
||||
// global and is the engine function's only way in, so the state is set for
|
||||
// every call; an error part way cannot leave a thread behind for the next.
|
||||
//
|
||||
// Registered on both Lua states, like the base-library helpers.
|
||||
|
||||
#include "Common.h"
|
||||
#include "Game.h"
|
||||
#include "Offsets.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <initializer_list>
|
||||
|
||||
namespace BaseLib::DebugStack {
|
||||
|
||||
namespace {
|
||||
|
||||
namespace Lua = Game::Lua;
|
||||
|
||||
// The state whose levels the engine's debugstack reads, or null for its own.
|
||||
void *g_levelsOf = nullptr;
|
||||
|
||||
int __fastcall GetStack(void *L, int level, void *ar) {
|
||||
return Lua::GetStack(g_levelsOf ? g_levelsOf : L, level, ar);
|
||||
}
|
||||
|
||||
int __fastcall GetInfo(void *L, const char *what, void *ar) {
|
||||
return Lua::GetInfo(g_levelsOf ? g_levelsOf : L, what, ar);
|
||||
}
|
||||
|
||||
int __fastcall Script_debugstack(void *L) {
|
||||
const auto engineDebugStack =
|
||||
reinterpret_cast<Lua::CFunction>(Offsets::FUN_SCRIPT_DEBUGSTACK);
|
||||
g_levelsOf = nullptr;
|
||||
if (Lua::Type(L, 1) == Lua::TYPE_THREAD) {
|
||||
g_levelsOf = Lua::ToThread(L, 1);
|
||||
Lua::Remove(L, 1);
|
||||
if (!Lua::IsNumber(L, 1)) { // start defaults to 0 for a thread
|
||||
Lua::PushNumber(L, 0);
|
||||
Lua::Insert(L, 1);
|
||||
}
|
||||
}
|
||||
const int results = engineDebugStack(L);
|
||||
g_levelsOf = nullptr;
|
||||
return results;
|
||||
}
|
||||
|
||||
void Apply() {
|
||||
const auto getStack = reinterpret_cast<const void *>(&GetStack);
|
||||
for (const uintptr_t site :
|
||||
{Offsets::CALL_DEBUGSTACK_GETSTACK_FIRST, Offsets::CALL_DEBUGSTACK_GETSTACK_TAIL_PROBE,
|
||||
Offsets::CALL_DEBUGSTACK_GETSTACK_TAIL_START, Offsets::CALL_DEBUGSTACK_GETSTACK_TAIL_SKIP,
|
||||
Offsets::CALL_DEBUGSTACK_GETSTACK_NEXT})
|
||||
Common::RedirectCall(site, Offsets::LUA_GET_STACK, getStack);
|
||||
Common::RedirectCall(Offsets::CALL_DEBUGSTACK_GETINFO, Offsets::LUA_GET_INFO,
|
||||
reinterpret_cast<const void *>(&GetInfo));
|
||||
}
|
||||
|
||||
void RegisterInGame() {
|
||||
Apply();
|
||||
Lua::RegisterGlobalFunction("debugstack", &Script_debugstack);
|
||||
}
|
||||
|
||||
void RegisterGlue() {
|
||||
Apply();
|
||||
Lua::RegisterGlueFunction("debugstack", &Script_debugstack);
|
||||
}
|
||||
|
||||
const Game::ModuleAutoRegister _autoreg{&RegisterInGame};
|
||||
const Game::GlueModuleAutoRegister _autoregGlue{&RegisterGlue};
|
||||
|
||||
} // namespace
|
||||
|
||||
} // namespace BaseLib::DebugStack
|
||||
@@ -0,0 +1,58 @@
|
||||
// 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/>.
|
||||
|
||||
// `difftime(t2 [, t1])` — the seconds from `t1` (0 by default) to `t2`, the
|
||||
// companion of the engine's `date` and `time` globals. 4.3.4's
|
||||
// Script_difftime: C `difftime` over the two arguments as time_t.
|
||||
//
|
||||
// Registered on BOTH states, as the engine registers `date` and `time`.
|
||||
|
||||
#include "Game.h"
|
||||
|
||||
#include <ctime>
|
||||
|
||||
namespace BaseLib::DiffTime {
|
||||
|
||||
namespace {
|
||||
|
||||
int __fastcall Script_difftime(void *L) {
|
||||
const auto t2 = static_cast<time_t>(Game::Lua::CheckNumber(L, 1));
|
||||
const auto t1 = static_cast<time_t>(Game::Lua::OptNumber(L, 2, 0));
|
||||
Game::Lua::PushNumber(L, std::difftime(t2, t1));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const Game::Doc::Field kDifftimeArgs[] = {
|
||||
Game::Doc::Req("time2", "number", "A time in seconds, as `time()` returns."),
|
||||
Game::Doc::Opt("time1", "number", "0"),
|
||||
};
|
||||
const Game::Doc::Field kDifftimeRets[] = {
|
||||
Game::Doc::Req("seconds", "number", "time2 minus time1."),
|
||||
};
|
||||
const Game::Doc::Function kDifftime{"The number of seconds from time1 to time2.",
|
||||
kDifftimeArgs, kDifftimeRets, "LuaGlobals"};
|
||||
|
||||
void RegisterInGame() {
|
||||
Game::Lua::RegisterGlobalFunction("difftime", &Script_difftime, &kDifftime);
|
||||
}
|
||||
|
||||
void RegisterGlue() {
|
||||
Game::Lua::RegisterGlueFunction("difftime", &Script_difftime, &kDifftime);
|
||||
}
|
||||
|
||||
const Game::ModuleAutoRegister _autoreg{&RegisterInGame};
|
||||
const Game::GlueModuleAutoRegister _autoregGlue{&RegisterGlue};
|
||||
|
||||
} // namespace
|
||||
|
||||
} // namespace BaseLib::DiffTime
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user