Compare commits

14 Commits

Author SHA1 Message Date
bionickatana 7279b3c207 Working advanced tracking code
Build / Build source distribution (push) Failing after 13s
Build / Execute unit tests (push) Failing after 8s
Build / Verify generated game data is current (push) Failing after 7s
Build / Upload Release Asset (push) Has been skipped
Build / upload_pypi (push) Has been skipped
2026-10-13 09:08:38 -06:00
bionickatana f3114b076a Added 'damage taken' section to the UI
Build / Build source distribution (push) Failing after 8s
Build / Execute unit tests (push) Failing after 6s
Build / Upload Release Asset (push) Has been skipped
Build / upload_pypi (push) Has been skipped
2026-10-10 23:38:32 -06:00
bionickatana fbfa90edec Added replay ability 2026-10-10 23:00:04 -06:00
bionickatana 13b1dcdd97 Fixed UI crash
Build / Build source distribution (push) Failing after 9s
Build / Execute unit tests (push) Failing after 7s
Build / Upload Release Asset (push) Has been skipped
Build / upload_pypi (push) Has been skipped
2026-10-10 20:39:02 -06:00
bionickatana 887667af07 Working on fixing crashing
Build / Build source distribution (push) Failing after 1m31s
Build / Execute unit tests (push) Failing after 6s
Build / Upload Release Asset (push) Has been skipped
Build / upload_pypi (push) Has been skipped
2026-10-10 15:28:56 -06:00
bionickatana 60137a2de4 Working on party stuff, mostly works 2026-10-10 14:07:14 -06:00
bionickatana 85a844208a Updated silver and item collection 2026-10-10 12:10:06 -06:00
bionickatana 59a9fa4098 Made application maximized when opened 2026-10-10 00:39:31 -06:00
bionickatana 6e78b282a6 Made application fullscreen 2026-10-10 00:24:58 -06:00
bionickatana 774f596c09 Fixed healing and started working on item collection tracking 2026-10-10 00:17:53 -06:00
bionickatana 3e0ad62cf2 Base working for damage 2026-10-09 23:10:40 -06:00
Wiktor Mazur 2895be91c4 Updated launcher 2021-11-11 19:33:55 +01:00
Wiktor Mazur c582677329 Version update 2021-10-21 21:41:58 +02:00
Wiktor Mazur ac487adf5a pyside2 -> pyside6 2021-10-09 15:20:26 +02:00
79 changed files with 341814 additions and 399 deletions
+16
View File
@@ -35,6 +35,22 @@ jobs:
python -m pip install --upgrade tox python -m pip install --upgrade tox
- name: Run unit tests - name: Run unit tests
run: python -m tox -e ut run: python -m tox -e ut
gamedata:
name: Verify generated game data is current
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-python@v2
name: Install Python
with:
python-version: '3.7'
# The tables under src/static are generated from the game data dumps.
# They are committed, so this job fails if someone edits them by hand or
# if upstream game data moved on and nobody regenerated them.
- name: Check committed tables match the dumps
run: make gamedata-check
upload_pypi: upload_pypi:
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags') if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags')
needs: [build_sdist] needs: [build_sdist]
+3 -1
View File
@@ -14,4 +14,6 @@ albion-online-stats.cfg
.mypy_cache .mypy_cache
aoaddons.log aoaddons.log
.eggs .eggs
.idea .idea
# fetched game data dumps (scripts/fetch_gamedata.py)
.cache
+1
View File
@@ -0,0 +1 @@
3.10
+3 -1
View File
@@ -1,2 +1,4 @@
include README.md include README.md
include src/assets/*.png include src/assets/*.png
include src/static/*
include src/scripts/*
+32
View File
@@ -0,0 +1,32 @@
PYTHON ?= python3
CACHE ?= .cache/gamedata
.PHONY: help gamedata gamedata-check gamedata-force test lint clean-gamedata
help:
@echo 'Targets:'
@echo ' gamedata regenerate src/static tables from the game dumps'
@echo ' gamedata-check verify the committed tables are up to date'
@echo ' test run the unit tests'
# Regenerate the shipped lookup tables. Fetches the game dumps first if the
# cache is missing. Tables land in src/static and should be committed.
gamedata:
$(PYTHON) scripts/fetch_gamedata.py --cache $(CACHE)
$(PYTHON) scripts/gen_gamedata.py --cache $(CACHE)
# Regenerate from a fresh checkout of the dumps.
gamedata-force:
$(PYTHON) scripts/fetch_gamedata.py --cache $(CACHE) --force
$(PYTHON) scripts/gen_gamedata.py --cache $(CACHE)
# CI guard: fail if the committed tables have drifted from the dumps.
gamedata-check:
$(PYTHON) scripts/fetch_gamedata.py --cache $(CACHE)
$(PYTHON) scripts/gen_gamedata.py --cache $(CACHE) --check
test:
$(PYTHON) -m pytest tests
clean-gamedata:
rm -rf .cache
+98 -6
View File
@@ -7,6 +7,10 @@
**Powered by** <a href="https://github.com/mazurwiktor/aoaddons-python"> **pyaoaddons** </a> & <a href="https://github.com/mazurwiktor/albion-online-addons"> **albion online addons** </a> **Powered by** <a href="https://github.com/mazurwiktor/aoaddons-python"> **pyaoaddons** </a> & <a href="https://github.com/mazurwiktor/albion-online-addons"> **albion online addons** </a>
> On Linux the app no longer depends on `pyaoaddons`: it ships a pure-Python
> Protocol18 decoder and captures packets directly through `AF_PACKET`
> (no libpcap needed). `pyaoaddons` is still used on Windows and macOS.
[![Discord](https://discordapp.com/api/guilds/639922572368150552/widget.png?style=banner2)](https://discord.gg/3U2rpyV) [![Discord](https://discordapp.com/api/guilds/639922572368150552/widget.png?style=banner2)](https://discord.gg/3U2rpyV)
@@ -30,15 +34,91 @@ Albion online stats is an extension to MMORPG game - Albion Online. It tracks ne
## Installation ## Installation
1. On windows make sure that WinPcap is installed in your system. [Npcap 0.9983 installer for Windows Vista/2008, 7/2008R2, 8/2012, 8.1/2012R2, 10/2016 (x86 and x64)](https://nmap.org/npcap/dist/npcap-0.9983.exe) **Make sure to install with the "Install Npcap in WinPcap API-compatible Mode"** ### Windows
1. Make sure that WinPcap is installed in your system. [Npcap 0.9983 installer for Windows Vista/2008, 7/2008R2, 8/2012, 8.1/2012R2, 10/2016 (x86 and x64)](https://nmap.org/npcap/dist/npcap-0.9983.exe) **Make sure to install with the "Install Npcap in WinPcap API-compatible Mode"**
2. Install python [all platforms installation instructions](https://docs.python.org/3/using/) or via [Microsoft Store](https://www.microsoft.com/en-us/p/python-39/9p7qfqmjrfp7). 2. Install python [all platforms installation instructions](https://docs.python.org/3/using/) or via [Microsoft Store](https://www.microsoft.com/en-us/p/python-39/9p7qfqmjrfp7).
3. Download latest launcher from https://github.com/mazurwiktor/albion-online-stats/releases/latest (albion-online-stats.bat for windows albion-online-stats.sh for linux and mac) 3. Download the latest launcher from https://github.com/mazurwiktor/albion-online-stats/releases/latest (`albion-online-stats.bat`).
3. Enjoy :) 4. Enjoy :)
### Linux / macOS
1. Install python 3 and the `venv` module with your package manager. On macOS also install libpcap:
```shell
# Debian / Ubuntu
sudo apt install python3 python3-venv python3-pip
# Fedora
sudo dnf install python3 python3-pip
# Arch
sudo pacman -S python
# macOS
brew install libpcap
```
2. Capturing network traffic requires elevated privileges. Either run the app with `sudo`, or grant the Python interpreter the capabilities it needs:
```shell
sudo setcap cap_net_raw,cap_net_admin=eip "$(readlink -f "$(command -v python3)")"
```
The app can do this for you from the **Fix capture permissions** button in its error dialog.
3. Download the latest launcher from https://github.com/mazurwiktor/albion-online-stats/releases/latest (`albion-online-stats.sh`), make it executable and run it:
```shell
chmod +x albion-online-stats.sh
./albion-online-stats.sh
```
4. Enjoy :)
> **Note:** on macOS (and Windows) the packet capture backend (`pyaoaddons`) only ships prebuilt wheels for CPython 3.6-3.10. If you use a newer Python, `pyaoaddons` is not installed automatically and the app will report that the backend is missing. Either use Python 3.10 (or older) or build `pyaoaddons` from source (requires a Rust toolchain). This does not affect Linux, where the built-in decoder is used.
## Configuration ## Configuration
After first execution the app is going to create default configuration file named `albion-online-stats.cfg`. Feel free to edit it according to your needs. After first execution the app is going to create default configuration file named `albion-online-stats.cfg`. Feel free to edit it according to your needs.
## Debugging
Start the app with `--verbose` (or set `AOSTATS_VERBOSE=1`) to enable detailed logging of the app and the packet capture backend:
```shell
aostats --verbose
```
This prints the backend initialization result, the capture-permission probe, and every received game event to the terminal. On Windows/macOS the capture backend also writes its own log to `aoaddons.log` in the current working directory.
On Linux the app uses its own `AF_PACKET` capture and Protocol18 decoder; every interface it listens on and every decoded event is logged with `--verbose`.
To collect packet-discovery data for decoding new features such as silver and item pickup tracking, pass a JSONL log path:
```shell
aostats --verbose --log-path /tmp/aostats-discovery.jsonl
```
This writes raw UDP payloads, decoded Photon messages, translated game messages, emitted app events, and possible item-id annotations to the JSONL file. If `--verbose` is also set, normal app logs are written to `/tmp/aostats-discovery.jsonl.app.log`.
On Linux, when the app has no permission to capture packets the backend still reports successful initialization; the app detects this and shows a "Fix capture permissions" button regardless.
### Replaying a captured log
To debug the decoder and stats without being in game, replay a captured log as if the packets were arriving from the server:
```shell
aostats --replay /tmp/aostats-discovery.jsonl
```
The app opens normally but feeds the log's packets through the same decode pipeline, so every page updates exactly as it would live. Packets are replayed as fast as possible by default; use `--replay-speed 1` to follow the log's original timing, or any other multiplier (for example `--replay-speed 4` for four times faster). No packet-capture permissions are needed while replaying.
For a quick, scriptable report without the GUI, add `--replay-headless`:
```shell
aostats --replay /tmp/aostats-discovery.jsonl --replay-headless
```
This prints packet/event counts together with the fame, silver and damage totals and then exits. Both the discovery JSONL format and the legacy aoaddons `Raw payload: [...]` text logs are supported. Avoid pointing `--log-path` at the same file you are replaying; the app refuses to overwrite its own replay source.
## Is This Allowed ## Is This Allowed
<p align="center"> <p align="center">
<img src="assets/sbistatement.png"> <img src="assets/sbistatement.png">
@@ -60,8 +140,9 @@ After first execution the app is going to create default configuration file name
## Prerequisites ## Prerequisites
- Python installed (python3.6+) - Python installed (python3.6+). On Linux the built-in decoder requires no extra runtime. On Windows/macOS use CPython 3.6-3.10 to get the `pyaoaddons` capture backend as a prebuilt wheel; newer versions require building it from source.
- *Windows only prerequisites* https://github.com/libpnet/libpnet#windows - *Windows only prerequisites* https://github.com/libpnet/libpnet#windows
- *macOS only prerequisites* libpcap (`brew install libpcap`)
## All platforms ## All platforms
@@ -79,10 +160,21 @@ After first execution the app is going to create default configuration file name
``` ```
3. Install package 3. Install the package with pip (this also installs the dependencies).
On Linux this is all you need. On Windows/macOS, use Python 3.6-3.10 to get the `pyaoaddons` capture backend automatically.
```shell ```shell
python setup.py install python -m pip install .
```
On Windows/macOS with Python 3.11+ the capture backend is not installed
automatically. Either use a Python 3.6-3.10 interpreter, or build
`pyaoaddons` from source first:
```shell
pip install setuptools-rust
pip install --no-build-isolation git+https://github.com/mazurwiktor/aoaddons-python.git
python -m pip install ".[capture]"
``` ```
4. Run the application 4. Run the application
+4 -1
View File
@@ -14,9 +14,12 @@ if not defined FOUND_PYTHON (goto python_not_found)
%FOUND_PYTHON% -m venv python_env %FOUND_PYTHON% -m venv python_env
call .\python_env\Scripts\activate.bat call .\python_env\Scripts\activate.bat
for /f "tokens=* delims=" %%a in ('python --version') do (echo Python version: %%a)
for /f "tokens=* delims=" %%a in ('python -m pip --version') do (echo Pip version: %%a)
echo Installing newest version of aostats... echo Installing newest version of aostats...
python -m pip install --upgrade pip python -m pip install --upgrade pip
python -m pip install aostats python -m pip install aostats
python -m pip install --upgrade aostats python -m pip install --upgrade aostats
goto execute goto execute
Regular → Executable
+45 -5
View File
@@ -1,10 +1,50 @@
#!/bin/bash #!/usr/bin/env bash
#
# Albion Online Stats launcher for Linux and macOS.
python -m venv python_env set -eu
source python_env/bin/activate FOUND_PYTHON=""
python -m pip install aostats for app in python3 python; do
if command -v "$app" >/dev/null 2>&1; then
if "$app" -c 'import sys; sys.exit(0 if sys.version_info[0] == 3 else 1)' >/dev/null 2>&1; then
FOUND_PYTHON="$app"
break
fi
fi
done
if [ -z "$FOUND_PYTHON" ]; then
echo "Error: python 3 was not found in the system." >&2
echo "Install it with your package manager, e.g.:" >&2
echo " Debian/Ubuntu: sudo apt install python3 python3-venv python3-pip" >&2
echo " Fedora: sudo dnf install python3 python3-pip" >&2
echo " Arch: sudo pacman -S python" >&2
exit 1
fi
echo "Found python: $FOUND_PYTHON ($("$FOUND_PYTHON" --version 2>&1))"
if ! "$FOUND_PYTHON" -m venv --help >/dev/null 2>&1; then
echo "Error: the python 'venv' module is not available." >&2
echo "On Debian/Ubuntu install it with: sudo apt install python3-venv" >&2
exit 1
fi
# The pyaoaddons capture backend is only used on macOS now (Linux uses the
# built-in AF_PACKET decoder and has no pyaoaddons wheel requirement).
echo "Creating python virtual environment..."
"$FOUND_PYTHON" -m venv python_env
# shellcheck disable=SC1091
. ./python_env/bin/activate
echo "Installing albion online stats..."
python -m pip install --upgrade pip
python -m pip install aostats
python -m pip install --upgrade aostats python -m pip install --upgrade aostats
aostats echo "Starting Albion Online Stats..."
aostats "$@"
+141
View File
@@ -0,0 +1,141 @@
"""Fetch the large game data dumps that generated tables are built from.
The app ships small, generated lookup tables (see ``src/static/vendor``). The
dumps they are derived from are far too large to version, so they are fetched
on demand into a gitignored cache.
This is a shallow, blobless, sparse clone, so it transfers only the handful of
files listed below rather than the repository's full history.
Usage:
python scripts/fetch_gamedata.py [--cache DIR] [--force] [--check]
"""
import argparse
import hashlib
import json
import os
import shutil
import subprocess
import sys
UPSTREAM_URL = 'https://github.com/ao-data/ao-bin-dumps.git'
PINNED_COMMIT = '47e4f5aca4d30b7495afa5a625ce0d5795e32050'
# Only what the generators actually read. `localization.json` is deliberately
# absent: it is 90 MB, and it cannot supply a display name for every mob
# anyway (883 of 5479 mob definitions have no namelocatag). Nothing in
# attribution depends on it. See src/static/vendor/PROVENANCE.md.
REQUIRED_FILES = (
'items.json',
'spells.json',
'mobs.json',
'gamedata.json',
# Source for the vendored src/static/vendor/item_ids.txt.
'formatted/items.txt',
)
# Anchored to the repo root. Without the leading slash gitcone matches the
# basename anywhere in the tree, which drags in the redundant 24 MB
# formatted/items.json alongside the root one.
SPARSE_PATTERNS = tuple('/' + name for name in REQUIRED_FILES)
DEFAULT_CACHE = os.path.join('.cache', 'gamedata')
def _run(args, cwd=None):
result = subprocess.run(
args,
cwd=cwd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
if result.returncode != 0:
sys.stderr.write(result.stdout.decode('utf-8', 'replace'))
raise SystemExit('command failed: {}'.format(' '.join(args)))
return result.stdout.decode('utf-8', 'replace')
def _checksums(directory):
"""Map of filename -> sha256 for the required files."""
digests = {}
for name in REQUIRED_FILES:
path = os.path.join(directory, name)
digest = hashlib.sha256()
with open(path, 'rb') as handle:
for chunk in iter(lambda: handle.read(1 << 20), b''):
digest.update(chunk)
digests[name] = digest.hexdigest()
return digests
def is_populated(directory):
return all(os.path.exists(os.path.join(directory, name))
for name in REQUIRED_FILES)
def fetch(cache_dir, force=False):
"""Ensure the dumps are present in ``cache_dir`` and return that path."""
if force and os.path.isdir(cache_dir):
shutil.rmtree(cache_dir)
elif is_populated(cache_dir):
return cache_dir
parent = os.path.dirname(os.path.abspath(cache_dir)) or '.'
os.makedirs(parent, exist_ok=True)
if os.path.isdir(cache_dir):
shutil.rmtree(cache_dir)
# --filter=blob:none avoids the full history; --sparse plus the final
# checkout limits us to the files we name.
_run([
'git', 'clone',
'--filter=blob:none',
'--no-checkout',
'--depth', '1',
UPSTREAM_URL,
cache_dir,
])
_run(['git', 'sparse-checkout', 'set', '--no-cone', *SPARSE_PATTERNS],
cwd=cache_dir)
_run(['git', 'checkout', PINNED_COMMIT], cwd=cache_dir)
missing = [name for name in REQUIRED_FILES
if not os.path.exists(os.path.join(cache_dir, name))]
if missing:
raise SystemExit('fetch incomplete, missing: {}'.format(missing))
return cache_dir
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--cache', default=DEFAULT_CACHE,
help='cache directory (default: %(default)s)')
parser.add_argument('--force', action='store_true',
help='re-fetch even if the cache is already populated')
parser.add_argument('--check', action='store_true',
help='verify the cache matches the pinned commit, '
'without fetching')
args = parser.parse_args(argv)
if args.check:
if not is_populated(args.cache):
print('cache is not populated: {}'.format(args.cache))
return 1
head = _run(['git', 'rev-parse', 'HEAD'], cwd=args.cache).strip()
if head != PINNED_COMMIT:
print('cache at {}, expected {}'.format(head, PINNED_COMMIT))
return 1
print('cache OK at {}'.format(PINNED_COMMIT))
print(json.dumps(_checksums(args.cache), indent=2, sort_keys=True))
return 0
fetch(args.cache, force=args.force)
print('game data ready in {}'.format(args.cache))
return 0
if __name__ == '__main__':
raise SystemExit(main())
+466
View File
@@ -0,0 +1,466 @@
"""Generate the small game-data lookup tables the app actually ships.
The raw dumps are ~50 MB and are fetched on demand (see fetch_gamedata.py).
This reduces them to a handful of compact tables under ``src/static``.
Everything here is derived mechanically from the dumps. There are no
hand-written mappings, and no observed damage is ever used to infer a value --
strength comes from item power, which is a property of the item definition.
Usage:
python scripts/gen_gamedata.py [--cache DIR] [--check]
"""
import argparse
import json
import os
import re
import sys
STATIC_DIR = os.path.join('src', 'static')
DEFAULT_CACHE = os.path.join('.cache', 'gamedata')
# Mob template IDs are the enumeration index of the mobs.bin XML, which differs
# from the order of mobs.json by a constant. Six independent template IDs seen
# in real captures resolve to the correct mob on both name and max HP with this
# offset, across ~2300 entries of the file. The rule producing it is not
# understood -- the 16 skipped entries are all category=roaming, which is the
# signature of a filtered enumeration rather than a statement of the filter.
# Accepted as a constant by decision; see .opencode/plans/effective-damage.md.
MOB_TEMPLATE_OFFSET = 16
ARMOR_TYPES = ('physicalarmor', 'magicresistance')
_ITEM_LINE = re.compile(r'\s*(\d+):\s*(\S+?)\s*(?::|$)')
def _load(cache_dir, name):
with open(os.path.join(cache_dir, name), encoding='utf-8') as handle:
return json.load(handle)
def _as_list(value):
if value is None:
return []
if isinstance(value, list):
return value
return [value]
# --------------------------------------------------------------------------
# item_ids.txt
# --------------------------------------------------------------------------
def gen_item_ids(cache_dir):
"""Rewrite src/static/item_ids.txt in the format the app reads.
The app's loader expects ``<id>,<uniquename>``. Upstream ships
`` <id>: <uniquename> : <display name>``; 846 entries have no display
name and end after the unique name.
"""
out_path = os.path.join(STATIC_DIR, 'item_ids.txt')
lines = []
src = os.path.join(cache_dir, 'formatted', 'items.txt')
with open(src, encoding='utf-8', errors='replace') as handle:
for line in handle:
match = _ITEM_LINE.match(line)
if match:
lines.append('{},{}'.format(match.group(1), match.group(2)))
lines.sort(key=lambda entry: int(entry.split(',', 1)[0]))
_write_text(out_path, '\n'.join(lines) + '\n')
return out_path, len(lines)
# --------------------------------------------------------------------------
# item_spells.json
# --------------------------------------------------------------------------
def _index_items(items_root):
"""Unique name -> definition, in document order across all groups."""
index = {}
for group, value in items_root.items():
if group.startswith('@') or group == 'shopcategories':
continue
for entry in _as_list(value):
if isinstance(entry, dict) and entry.get('@uniquename'):
index[entry['@uniquename']] = entry
return index
def _resolve_spells(item_index, name, depth=0, seen=None):
"""Flatten craftingspelllist, following @reference and removespell.
Most weapons carry no spells of their own -- they inherit a whole ability
set from a base item. Resolving that inheritance is what turns 471 weapons
with an apparently empty spell list into full coverage.
"""
seen = seen if seen is not None else set()
if name in seen or depth > 12:
return []
seen.add(name)
entry = item_index.get(name)
if not entry:
return []
spell_list = entry.get('craftingspelllist')
if not spell_list:
return []
if not isinstance(spell_list, dict):
return []
spells = []
reference = spell_list.get('@reference')
if reference:
spells += _resolve_spells(item_index, reference, depth + 1, seen)
removed = set()
for rem in _as_list(spell_list.get('removespell')):
if isinstance(rem, dict) and rem.get('@uniquename'):
removed.add(rem['@uniquename'])
for craft in _as_list(spell_list.get('craftspell')):
if isinstance(craft, dict) and craft.get('@uniquename'):
spells.append(craft)
return [s for s in spells if s['@uniquename'] not in removed]
def gen_item_spells(cache_dir):
item_index = _index_items(_load(cache_dir, 'items.json')['items'])
result = {}
for name in item_index:
spells = _resolve_spells(item_index, name)
if not spells:
continue
entries = [{'slot': s.get('@slots'), 'spell': s['@uniquename']}
for s in spells]
result[name] = entries
# A packet identifies an enchanted item as BASE@LEVEL, but only the
# base item exists in the dump. Emit the variants as aliases so a
# lookup straight from a packet id finds the abilities, rather than
# silently getting nothing.
enchantments = item_index[name].get('enchantments')
if not enchantments:
continue
variants = _as_list(
enchantments.get('enchantment') if isinstance(enchantments, dict)
else enchantments)
for variant in variants:
if isinstance(variant, dict) and variant.get('@enchantmentlevel'):
result['{}@{}'.format(name, variant['@enchantmentlevel'])] = \
entries
out_path = os.path.join(STATIC_DIR, 'item_spells.json')
_write_json(out_path, result, sort_keys=True)
return out_path, len(result)
# --------------------------------------------------------------------------
# debuff_spells.json
# --------------------------------------------------------------------------
def _index_spells(spells_root):
index = {}
for group in ('activespell', 'passivespell', 'togglespell'):
for spell in spells_root.get(group) or []:
if spell.get('@uniquename'):
index[spell['@uniquename']] = spell
return index
def _spell_links(spell_index, name):
"""Spells one hop downstream of ``name``.
An ability rarely carries its debuff directly. ARMORPIERCER declares no
buffovertime at all: it points at ARMORPIERCER_EFFECT via spelleffectarea,
which in turn applies ARMORPIERCER_DEBUFF_EFFECT via applyspell. Only the
last link actually holds the armour numbers, so every hop has to be walked.
"""
spell = spell_index.get(name)
if not spell:
return []
out = []
for applied in _as_list(spell.get('applyspell')):
if isinstance(applied, dict) and applied.get('@spell'):
out.append(applied['@spell'])
for area in _as_list(spell.get('spelleffectarea')):
if isinstance(area, dict) and area.get('@effect'):
out.append(area['@effect'])
return out
def _collect_debuffs(spell_index, name, depth=0, seen=None):
"""Negative armour/resistance effects reachable from ``name``."""
seen = seen if seen is not None else set()
if name in seen or depth > 3:
return []
seen.add(name)
found = []
spell = spell_index.get(name)
if spell:
for effect in _as_list(spell.get('buffovertime')):
if not isinstance(effect, dict):
continue
if effect.get('@type') not in ARMOR_TYPES:
continue
try:
value = float(effect.get('@value') or 0)
except ValueError:
continue
if value < 0:
found.append((name, effect))
for nxt in _spell_links(spell_index, name):
found += _collect_debuffs(spell_index, nxt, depth + 1, seen)
return found
def _flatten_effect(effect):
flat = {
'type': effect.get('@type'),
'value': float(effect.get('@value') or 0),
'time': float(effect.get('@time') or 0),
}
# Armour Piercer scales with how many targets the caster hit, so its
# magnitude must be read off the observed effect, never assumed.
bonus = effect.get('@targetcountvaluebonusfactor')
if bonus:
flat['targetcountvaluebonusfactor'] = float(bonus)
# SUNDERARMOR2 is weaker against players than mobs; pick per victim type.
target_type = effect.get('IfTargetType')
if isinstance(target_type, dict) and target_type.get('@type'):
flat['iftargettype'] = target_type['@type']
target = effect.get('@target')
if target:
flat['target'] = target
return flat
def gen_debuff_spells(cache_dir):
item_index = _index_items(_load(cache_dir, 'items.json')['items'])
spell_index = _index_spells(_load(cache_dir, 'spells.json')['spells'])
abilities = set()
for name in item_index:
for spell in _resolve_spells(item_index, name):
unique = spell.get('@uniquename')
if unique and not unique.startswith('PASSIVE'):
abilities.add(unique)
# effect spell -> abilities that produce it
producers = {}
for ability in abilities:
for effect_name, effect in _collect_debuffs(spell_index, ability):
producers.setdefault(effect_name, {}).setdefault(
ability, []).append(_flatten_effect(effect))
result = {}
for effect_name, by_ability in sorted(producers.items()):
spell = spell_index.get(effect_name, {})
result[effect_name] = {
'abilities': sorted(by_ability),
'category': spell.get('@category'),
'uitype': spell.get('@uitype'),
'maxstack': _maybe_int(spell.get('@maxstack')),
'maxcharges': _maybe_int(spell.get('@maxcharges')),
'effects': sorted(
{json.dumps(e, sort_keys=True): e
for group in by_ability.values() for e in group}.values(),
key=lambda e: (e['type'], e['value']),
),
}
out_path = os.path.join(STATIC_DIR, 'debuff_spells.json')
_write_json(out_path, result, sort_keys=True)
return out_path, len(result)
def _maybe_int(value):
if value in (None, ''):
return None
try:
return int(value)
except (TypeError, ValueError):
return None
# --------------------------------------------------------------------------
# progression.json
# --------------------------------------------------------------------------
def gen_progression(cache_dir):
"""Item-power progression constants for armour and damage.
Albion scales a character's stats from item power, so attacker strength is
a property of the equipped item and not of any observed hit. This keeps the
arithmetic correct as players level their gear.
"""
game = _load(cache_dir, 'gamedata.json')['AO-GameData']
source = game['Items']['ItemPowerProgression']
result = {'slots': {}, 'shares': {}}
for key, value in source.items():
if key in ('armorshare', 'ccrshare', 'hitpointsshare', 'energyshare',
'trackingtime'):
result['shares'][key] = value
elif isinstance(value, dict) and '@armorbase' in value:
result['slots'][key] = {
'armorbase': float(value['@armorbase']),
'armorprogression': float(value['@armorprogression']),
'attackdamageprogression': float(
value.get('@attackdamageprogression') or 0),
'hitpointsprogression': float(
value.get('@hitpointsprogression') or 0),
}
out_path = os.path.join(STATIC_DIR, 'progression.json')
_write_json(out_path, result, sort_keys=True)
return out_path, len(result['slots'])
# --------------------------------------------------------------------------
# mob_armor.json
# --------------------------------------------------------------------------
def gen_mob_armor(cache_dir):
mobs = _load(cache_dir, 'mobs.json')['Mobs']['Mob']
result = {}
for position, mob in enumerate(mobs):
template_id = position + MOB_TEMPLATE_OFFSET
result[str(template_id)] = {
'name': mob.get('@uniquename'),
'tier': _maybe_int(mob.get('@tier')),
'armor': _maybe_int(mob.get('@physicalarmor')),
'resistance': _maybe_int(mob.get('@magicresistance')),
'hitpointsmax': _maybe_int(mob.get('@hitpointsmax')),
'category': mob.get('@category'),
}
out_path = os.path.join(STATIC_DIR, 'mob_armor.json')
_write_json(out_path, result, sort_keys=True)
return out_path, len(result)
# --------------------------------------------------------------------------
# item_power.json
# --------------------------------------------------------------------------
def gen_item_power(cache_dir):
"""Item power per unique name, including enchantment variants.
A packet carries the enchanted variant as part of the item id
(``T5_MAIN_HOLYSTAFF_AVALON@1``), and item power scales with the
enchantment level, so both are needed.
"""
item_index = _index_items(_load(cache_dir, 'items.json')['items'])
result = {}
for name, entry in item_index.items():
base = _maybe_int(entry.get('@itempower'))
if base is not None:
result[name] = base
enchantments = entry.get('enchantments')
if not enchantments:
continue
for variant in _as_list(enchantments.get('enchantment')
if isinstance(enchantments, dict)
else enchantments):
if not isinstance(variant, dict):
continue
level = variant.get('@enchantmentlevel')
power = _maybe_int(variant.get('@itempower'))
if level is None or power is None:
continue
result['{}@{}'.format(name, level)] = power
out_path = os.path.join(STATIC_DIR, 'item_power.json')
_write_json(out_path, result, sort_keys=True)
return out_path, len(result)
# --------------------------------------------------------------------------
def _write_json(path, data, sort_keys=True):
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, 'w', encoding='utf-8') as handle:
json.dump(data, handle, indent=1, sort_keys=sort_keys)
handle.write('\n')
def _write_text(path, text):
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, 'w', encoding='utf-8') as handle:
handle.write(text)
GENERATORS = (
('item_ids.txt', gen_item_ids),
('item_spells.json', gen_item_spells),
('debuff_spells.json', gen_debuff_spells),
('progression.json', gen_progression),
('mob_armor.json', gen_mob_armor),
('item_power.json', gen_item_power),
)
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--cache', default=DEFAULT_CACHE)
parser.add_argument('--check', action='store_true',
help='regenerate into a temp dir and report drift '
'instead of overwriting the committed tables')
args = parser.parse_args(argv)
if not os.path.isdir(args.cache):
raise SystemExit(
'no game data at {}; run scripts/fetch_gamedata.py first'.format(
args.cache))
if args.check:
return _check(args.cache)
for label, generator in GENERATORS:
path, count = generator(args.cache)
print('{:24s} {:>7d} entries {}'.format(
label, count, os.path.relpath(path)))
return 0
def _check(cache_dir):
import tempfile
import shutil
global STATIC_DIR
original = STATIC_DIR
drifted = []
tmp = tempfile.mkdtemp(prefix='gamedata-check-')
try:
STATIC_DIR = tmp
for label, generator in GENERATORS:
generated, _ = generator(cache_dir)
committed = os.path.join(original, label)
if not os.path.exists(committed):
drifted.append('{}: missing from src/static'.format(label))
elif _read(generated) != _read(committed):
drifted.append('{}: committed copy is stale'.format(label))
finally:
STATIC_DIR = original
shutil.rmtree(tmp, ignore_errors=True)
if drifted:
print('game data is out of date:')
for line in drifted:
print(' - {}'.format(line))
print('\nrun: make gamedata')
return 1
print('game data tables are up to date')
return 0
def _read(path):
with open(path, encoding='utf-8') as handle:
return handle.read()
if __name__ == '__main__':
sys.exit(main())
+18 -5
View File
@@ -3,13 +3,25 @@ from setuptools import setup, find_packages
from src.version import version from src.version import version
install_requires = [ install_requires = [
"requests==2.26.0", "requests>=2.26",
"pyside2==5.15.2", "PySide6==6.7.3",
"toml==0.10.2", "shiboken6==6.7.3",
"pillow==8.3.1", "toml>=0.10.2",
"pyaoaddons==0.2.7.dev" "pillow>=8.4",
# On Linux the app ships a pure-Python Protocol18 decoder and captures with
# AF_PACKET directly, so no native backend is needed. On Windows/macOS the
# pyaoaddons packet capture backend is still used; only 0.2.8 is released
# and it ships prebuilt wheels for CPython 3.6-3.10 only. On newer Python
# versions it must be built from source (see the 'capture' extra).
"pyaoaddons==0.2.8; python_version < '3.11' and sys_platform != 'linux'",
] ]
extras_require = {
# Force installation of the packet capture backend, e.g. when building
# pyaoaddons from source or using an unsupported Python version.
'capture': ['pyaoaddons==0.2.8'],
}
this_directory = path.abspath(path.dirname(__file__)) this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f: with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
long_description = f.read() long_description = f.read()
@@ -25,6 +37,7 @@ with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
packages=find_packages('.', include=('src*')), packages=find_packages('.', include=('src*')),
include_package_data=True, include_package_data=True,
install_requires=install_requires, install_requires=install_requires,
extras_require=extras_require,
entry_points={ entry_points={
'console_scripts': [ 'console_scripts': [
'aostats = src.__main__:run' 'aostats = src.__main__:run'
+13 -1
View File
@@ -1,4 +1,16 @@
from .gui.app import run import sys
from .environment import replay_path, replay_headless
def run():
if replay_path() and replay_headless():
from .replay_cli import run_headless
sys.exit(run_headless())
from .gui.app import run as run_gui
run_gui()
if __name__ == '__main__': if __name__ == '__main__':
run() run()
+91 -14
View File
@@ -1,6 +1,27 @@
import logging
from .environment import TEST_ENV_ENABLED
from . import environment
from .utils import platform_utils
logger = logging.getLogger(__name__)
class InitializationResult:
Ok = 0
UnknownFailure = 1
NetworkInterfaceListMissing = 2
BackendNotInstalled = 3
try: try:
import pyaoaddons # type: ignore import pyaoaddons # type: ignore
except:
BACKEND_AVAILABLE = True
except ImportError:
BACKEND_AVAILABLE = False
class pyaoaddons: # type: ignore class pyaoaddons: # type: ignore
@staticmethod @staticmethod
def initialize(): def initialize():
@@ -10,15 +31,6 @@ except:
def subscribe(_): def subscribe(_):
pass pass
from .environment import TEST_ENV_ENABLED
from . import environment
class InitializationResult:
Ok = 0
UnknownFailure = 1
NetworkInterfaceListMissing = 2
INITIALIZATION_RESULT = { INITIALIZATION_RESULT = {
0: InitializationResult.Ok, 0: InitializationResult.Ok,
@@ -26,24 +38,89 @@ INITIALIZATION_RESULT = {
2: InitializationResult.NetworkInterfaceListMissing 2: InitializationResult.NetworkInterfaceListMissing
} }
# On Linux we ship a pure-Python Protocol18 decoder and use AF_PACKET directly,
# so pyaoaddons is not required.
NATIVE_BACKEND_AVAILABLE = platform_utils.is_linux()
_capture = None
_replay = None
def initialize(): def initialize():
if environment.replay_path():
return InitializationResult.Ok
if TEST_ENV_ENABLED: if TEST_ENV_ENABLED:
return InitializationResult.Ok return InitializationResult.Ok
if NATIVE_BACKEND_AVAILABLE:
return InitializationResult.Ok
if not BACKEND_AVAILABLE:
return InitializationResult.BackendNotInstalled
try: try:
result = pyaoaddons.initialize() result = pyaoaddons.initialize()
return INITIALIZATION_RESULT[result] return INITIALIZATION_RESULT[result]
except: except Exception:
pass return InitializationResult.UnknownFailure
def subscribe(callback): def subscribe(callback):
if TEST_ENV_ENABLED: if TEST_ENV_ENABLED:
return _testing_call_sequence(callback) _testing_call_sequence(callback)
return True
pyaoaddons.subscribe(callback) if environment.replay_path():
return _start_replay_backend(callback)
if NATIVE_BACKEND_AVAILABLE:
return _start_native_backend(callback)
if BACKEND_AVAILABLE:
pyaoaddons.subscribe(callback)
return True
return False
def _start_native_backend(callback):
global _capture
if _capture is not None:
return True
from .decode.pipeline import Pipeline
from .net.capture import CaptureEngine
pipeline = Pipeline(callback)
capture = CaptureEngine(pipeline.on_udp)
if not capture.start():
logger.error(
"native capture backend could not start; "
"check packet capture permissions")
return False
_capture = capture
return True
def _start_replay_backend(callback):
global _replay
if _replay is not None:
return True
from .decode.pipeline import Pipeline
from .net.replay import ReplayEngine
pipeline = Pipeline(callback)
replay = ReplayEngine(pipeline.on_udp)
if not replay.start():
logger.error("replay backend could not start; check the log path")
return False
_replay = replay
return True
def _testing_call_sequence(callback): def _testing_call_sequence(callback):
+7
View File
@@ -1,6 +1,7 @@
EvNameMainPlayerAppeared: str = 'MainPlayerAppeared' EvNameMainPlayerAppeared: str = 'MainPlayerAppeared'
EvNamePlayerAppeared: str = 'PlayerAppeared' EvNamePlayerAppeared: str = 'PlayerAppeared'
EvNameDamageDone: str = 'DamageDone' EvNameDamageDone: str = 'DamageDone'
EvNameDamageTaken: str = 'DamageTaken'
EvNameHealthReceived: str = 'HealthReceived' EvNameHealthReceived: str = 'HealthReceived'
EvNameZoneChange: str = 'ZoneChange' EvNameZoneChange: str = 'ZoneChange'
EvNameEnterCombat: str = 'EnterCombat' EvNameEnterCombat: str = 'EnterCombat'
@@ -8,6 +9,8 @@ EvNameLeaveCombat: str = 'LeaveCombat'
EvNameUpdateFame: str = 'UpdateFame' EvNameUpdateFame: str = 'UpdateFame'
EvNameUpdateItems: str = 'UpdateItems' EvNameUpdateItems: str = 'UpdateItems'
EvNameUpdateParty: str = 'UpdateParty' EvNameUpdateParty: str = 'UpdateParty'
EvNameSilverGained: str = 'SilverGained'
EvNameItemCollected: str = 'ItemCollected'
EvKeyName: str = 'name' EvKeyName: str = 'name'
EvKeyValue: str = 'value' EvKeyValue: str = 'value'
@@ -15,3 +18,7 @@ EvKeySource: str = 'source'
EvKeyTarget: str = 'target' EvKeyTarget: str = 'target'
EvKeyId: str = 'id' EvKeyId: str = 'id'
EvKeyPlayerNames: str = 'player_names' EvKeyPlayerNames: str = 'player_names'
EvKeyItemId: str = 'item_id'
EvKeyItemName: str = 'item_name'
EvKeyQuantity: str = 'quantity'
EvKeySilverType: str = 'silver_type'
+2
View File
@@ -0,0 +1,2 @@
from .photon import PhotonDecoder, PhotonMessage
from .world import World
+122
View File
@@ -0,0 +1,122 @@
import json
import os
import threading
from datetime import datetime, timezone
from typing import Any, Dict, List
from ..environment import discovery_log_path, replay_path
from . import items as itemdb
_lock = threading.Lock()
_initialized = False
def enabled() -> bool:
return bool(discovery_log_path())
def _same_file(a: str, b: str) -> bool:
try:
return os.path.abspath(a) == os.path.abspath(b)
except (TypeError, ValueError):
return False
def log(record_type: str, **fields):
path = discovery_log_path()
if not path:
return
# Never clobber the log we are replaying from.
source = replay_path()
if source and _same_file(path, source):
return
global _initialized
with _lock:
log_dir = os.path.dirname(path)
if log_dir:
os.makedirs(log_dir, exist_ok=True)
mode = 'a' if _initialized else 'w'
with open(path, mode, encoding='utf-8') as out:
if not _initialized:
out.write(json.dumps({
'type': 'session_start',
'timestamp': _timestamp(),
'format': 'aostats-discovery-jsonl-v1',
}, sort_keys=True) + '\n')
_initialized = True
out.write(json.dumps({
'type': record_type,
'timestamp': _timestamp(),
**_clean(fields),
}, sort_keys=True) + '\n')
def message_record(message) -> Dict[str, Any]:
params = getattr(message, 'params', {}) or {}
return {
'kind': getattr(message, 'kind', None),
'code': getattr(message, 'code', None),
'return_code': getattr(message, 'return_code', None),
'debug_message': _clean(getattr(message, 'debug_message', None)),
'params': _clean(params),
'item_id_candidates': item_candidates(params),
}
def game_message_record(game_message) -> Dict[str, Any]:
params = getattr(game_message, 'params', {}) or {}
return {
'name': getattr(game_message, 'name', None),
'code': getattr(game_message, 'code', None),
'params': _clean(params),
'item_id_candidates': item_candidates(params),
}
def item_candidates(params: Dict[Any, Any]) -> List[Dict[str, Any]]:
db = itemdb.get_db()
found: List[Dict[str, Any]] = []
for key, value in (params or {}).items():
for path, number in _walk_numbers(value, str(key)):
if number in db:
found.append({
'path': path,
'id': number,
'unique_name': db[number],
})
return found
def _timestamp() -> str:
return datetime.now(timezone.utc).isoformat(timespec='milliseconds')
def _clean(value):
if isinstance(value, bytes):
return {'bytes_hex': value.hex(), 'len': len(value)}
if isinstance(value, dict):
return {str(k): _clean(v) for k, v in value.items()}
if isinstance(value, (list, tuple)):
return [_clean(v) for v in value]
return value
def _walk_numbers(value, path: str):
if isinstance(value, bool):
return
if isinstance(value, int):
yield path, value
return
if isinstance(value, float) and value.is_integer():
yield path, int(value)
return
if isinstance(value, dict):
for key, item in value.items():
yield from _walk_numbers(item, f'{path}.{key}')
return
if isinstance(value, (list, tuple)):
for i, item in enumerate(value):
yield from _walk_numbers(item, f'{path}[{i}]')
+66
View File
@@ -0,0 +1,66 @@
import os
from typing import Dict, Optional
_ITEM_DB: Optional[Dict[int, str]] = None
_ITEM_NAME_DB: Optional[Dict[int, str]] = None
_ITEM_DB_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'static', 'item_ids.txt')
_ITEM_NAMES_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'static', 'item_names.txt')
def _load_file(path: str) -> Dict[int, str]:
db = {}
with open(path, encoding='utf-8') as f:
for line in f:
parts = line.strip().split(',', 1)
if len(parts) != 2:
continue
try:
_id = int(parts[0])
except ValueError:
continue
name = parts[1].strip()
if name:
db[_id] = name
return db
def get_db() -> Dict[int, str]:
global _ITEM_DB
if _ITEM_DB is None:
_ITEM_DB = _load_file(_ITEM_DB_PATH)
return _ITEM_DB
def get_name_db() -> Dict[int, str]:
global _ITEM_NAME_DB
if _ITEM_NAME_DB is None:
if os.path.exists(_ITEM_NAMES_PATH):
_ITEM_NAME_DB = _load_file(_ITEM_NAMES_PATH)
else:
_ITEM_NAME_DB = {}
return _ITEM_NAME_DB
def display_name(item_id: int) -> str:
return get_name_db().get(item_id) or get_db().get(item_id) or str(item_id)
ITEMS_SLOTS = ('weapon', 'offhand', 'helmet', 'armor', 'boots', 'bag', 'cape', 'mount', 'potion', 'food')
def decode_items(item_array) -> Dict[str, Optional[str]]:
"""Maps an equipment number array to slot -> item unique name.
Always returns all slots (aoaddons' ``Items`` struct keeps every field,
using ``None`` for empty/missing equipment) so downstream consumers can
index ``items['weapon']`` unconditionally.
"""
db = get_db()
items: Dict[str, Optional[str]] = {slot: None for slot in ITEMS_SLOTS}
for slot, _id in enumerate(ITEMS_SLOTS):
if item_array is None or slot >= len(item_array):
break
code = item_array[slot]
if code and code in db:
items[_id] = db[code]
return items
+68
View File
@@ -0,0 +1,68 @@
import json
import logging
import os
from typing import List
from ..utils import platform_utils
FILE_NAME = 'last-party.json'
logger = logging.getLogger(__name__)
def memory_path() -> str:
cfg_dir = platform_utils.config_dir()
if not cfg_dir:
cfg_dir = os.getcwd()
return os.path.join(cfg_dir, FILE_NAME)
def load_last_party() -> List[str]:
try:
with open(memory_path(), 'r') as party_file:
data = json.load(party_file)
except (OSError, json.JSONDecodeError):
logger.debug("no readable remembered party at %s", memory_path())
return []
names = data.get('player_names') if isinstance(data, dict) else None
if not isinstance(names, list):
logger.debug("remembered party file has no player_names: %s", memory_path())
return []
clean_names = _clean_names(names)
logger.debug("loaded remembered party from %s: %s", memory_path(), clean_names)
return clean_names
def save_last_party(names: List[str]):
clean_names = _clean_names(names)
if not clean_names:
clear_last_party()
return
path = memory_path()
directory = os.path.dirname(path)
if directory:
os.makedirs(directory, exist_ok=True)
with open(path, 'w') as party_file:
json.dump({'player_names': clean_names}, party_file)
logger.debug("saved remembered party to %s: %s", path, clean_names)
def clear_last_party():
try:
os.remove(memory_path())
except FileNotFoundError:
pass
except OSError:
pass
else:
logger.debug("cleared remembered party at %s", memory_path())
def _clean_names(names: List[str]) -> List[str]:
out = []
seen = set()
for name in names:
if not isinstance(name, str) or not name or name in seen:
continue
seen.add(name)
out.append(name)
return out
+386
View File
@@ -0,0 +1,386 @@
import struct
import logging
from collections import namedtuple
from typing import Dict, List, Optional
logger = logging.getLogger(__name__)
PROTOCOL18_SIGNAL = 0xF3
# Photon command types inside an eNet envelope
CMD_SEND_RELIABLE = 0x06
CMD_SEND_UNRELIABLE = 0x07
CMD_SEND_FRAGMENT = 0x08
CMD_SEND_UNRELIABLE_FRAGMENT = 0x0B
CMD_ACKNOWLEDGE = 0x03
CMD_PING = 0x05
CMD_LOGOUT = 0x04
# Photon message types
MSG_OPERATION_REQUEST = 0x02
MSG_OPERATION_RESPONSE = 0x03
MSG_EVENT_DATA = 0x04
MSG_INTERNAL_REQUEST = 0x06
MSG_INTERNAL_RESPONSE = 0x07
P18 = {
'Boolean': 2, 'Byte': 3, 'Short': 4, 'Float': 5, 'Double': 6, 'String': 7,
'Null': 8, 'CompressedInt': 9, 'CompressedLong': 10, 'Int1': 11, 'Int1Neg': 12,
'Int2': 13, 'Int2Neg': 14, 'Long1': 15, 'Long1Neg': 16, 'Long2': 17, 'Long2Neg': 18,
'Custom': 19, 'Dictionary': 20, 'Hashtable': 21, 'ObjectArray': 23,
'OperationRequest': 24, 'OperationResponse': 25, 'EventData': 26,
'BooleanFalse': 27, 'BooleanTrue': 28, 'ShortZero': 29, 'IntZero': 30,
'LongZero': 31, 'FloatZero': 32, 'DoubleZero': 33, 'ByteZero': 34,
'Array': 64, 'BooleanArray': 66, 'ByteArray': 67, 'ShortArray': 68,
'FloatArray': 69, 'DoubleArray': 70, 'StringArray': 71, 'CompressedIntArray': 73,
'CompressedLongArray': 74, 'CustomTypeArray': 83, 'DictionaryArray': 84,
'HashtableArray': 85, 'CustomTypeSlim': 128,
}
PhotonMessage = namedtuple(
'PhotonMessage', ('kind', 'code', 'params', 'return_code', 'debug_message'))
GAME_PORT = 5056
FRAG_HEADER_LEN = 20 # 5 x u32
class DecodeError(Exception):
pass
def _need(buf: bytes, pos: int, n: int, what: str):
if pos + n > len(buf):
raise DecodeError(f"not enough bytes for {what} at {pos}")
def rd_u8(buf: bytes, pos: int):
_need(buf, pos, 1, "u8")
return buf[pos], pos + 1
def rd_i16le(buf: bytes, pos: int):
_need(buf, pos, 2, "i16le")
return struct.unpack("<h", buf[pos:pos + 2])[0], pos + 2
def rd_u16le(buf: bytes, pos: int):
_need(buf, pos, 2, "u16le")
return struct.unpack("<H", buf[pos:pos + 2])[0], pos + 2
def rd_u16be(buf: bytes, pos: int):
_need(buf, pos, 2, "u16be")
return struct.unpack(">H", buf[pos:pos + 2])[0], pos + 2
def rd_u32be(buf: bytes, pos: int):
_need(buf, pos, 4, "u32be")
return struct.unpack(">I", buf[pos:pos + 4])[0], pos + 4
def rd_u32le(buf: bytes, pos: int):
_need(buf, pos, 4, "u32le")
return struct.unpack("<I", buf[pos:pos + 4])[0], pos + 4
def rd_f32le(buf: bytes, pos: int):
_need(buf, pos, 4, "f32le")
return struct.unpack("<f", buf[pos:pos + 4])[0], pos + 4
def rd_f64le(buf: bytes, pos: int):
_need(buf, pos, 8, "f64le")
return struct.unpack("<d", buf[pos:pos + 8])[0], pos + 8
def rd_varint(buf: bytes, pos: int):
value = 0
for shift in range(0, 64, 7):
b, pos = rd_u8(buf, pos)
if b & 0x80 == 0:
return value | (b << shift), pos
value |= (b & 0x7F) << shift
raise DecodeError("varint overflow")
def zigzag(v):
return (v >> 1) ^ (-(v & 1))
def read_string18(buf: bytes, pos: int):
slen, pos = rd_varint(buf, pos)
if slen == 0:
return "", pos
_need(buf, pos, slen, "string")
return buf[pos:pos + slen].decode('utf-8', 'replace'), pos + slen
def deserialize18(buf: bytes, pos: int, tc: int):
if tc >= P18['CustomTypeSlim']:
return ('custom', tc - P18['CustomTypeSlim']), pos
if tc == P18['Boolean']:
v, p = rd_u8(buf, pos)
return bool(v), p
if tc in (P18['Byte'], P18['ByteZero']):
if tc == P18['ByteZero']:
return 0, pos
return rd_u8(buf, pos)
if tc == P18['Short']:
return rd_i16le(buf, pos)
if tc == P18['Float']:
return rd_f32le(buf, pos)
if tc == P18['Double']:
return rd_f64le(buf, pos)
if tc == P18['String']:
return read_string18(buf, pos)
if tc == P18['Null']:
return None, pos
if tc == P18['BooleanFalse']:
return False, pos
if tc == P18['BooleanTrue']:
return True, pos
if tc in (P18['ShortZero'], P18['IntZero'], P18['LongZero']):
return 0, pos
if tc in (P18['FloatZero'], P18['DoubleZero']):
return 0.0, pos
if tc == P18['CompressedInt']:
v, p = rd_varint(buf, pos)
return zigzag(v), p
if tc == P18['CompressedLong']:
v, p = rd_varint(buf, pos)
return zigzag(v), p
if tc in (P18['Int1'], P18['Long1']):
return rd_u8(buf, pos)
if tc == P18['Int1Neg'] or tc == P18['Long1Neg']:
v, p = rd_u8(buf, pos)
return -v, p
if tc in (P18['Int2'], P18['Long2']):
return rd_u16le(buf, pos)
if tc == P18['Int2Neg'] or tc == P18['Long2Neg']:
v, p = rd_u16le(buf, pos)
return -v, p
if tc == P18['ByteArray']:
n, p = rd_varint(buf, pos)
_need(buf, p, n, "byte array")
return bytes(buf[p:p + n]), p + n
if tc == P18['ShortArray']:
return _read_number_array(buf, pos, lambda b, p: rd_i16le(b, p), "short array")
if tc == P18['FloatArray']:
return _read_number_array(buf, pos, rd_f32le, "float array")
if tc == P18['DoubleArray']:
return _read_number_array(buf, pos, rd_f64le, "double array")
if tc == P18['StringArray']:
n, p = rd_varint(buf, pos)
out = []
for _ in range(n):
s, p = read_string18(buf, p)
out.append(s)
return out, p
if tc == P18['CompressedIntArray']:
n, p = rd_varint(buf, pos)
out = []
for _ in range(n):
v, p = rd_varint(buf, p)
out.append(zigzag(v))
return out, p
if tc == P18['CompressedLongArray']:
n, p = rd_varint(buf, pos)
out = []
for _ in range(n):
v, p = rd_varint(buf, p)
out.append(zigzag(v))
return out, p
if tc == P18['BooleanArray']:
n, p = rd_varint(buf, pos)
out = []
for _ in range(n):
v, p = rd_u8(buf, p)
out.append(bool(v))
return out, p
if tc in (P18['Array'], P18['ObjectArray'], P18['CustomTypeArray']):
n, p = rd_varint(buf, pos)
out = []
for _ in range(n):
et, p = rd_u8(buf, p)
v, p = deserialize18(buf, p, et)
out.append(v)
return out, p
if tc in (P18['Dictionary'], P18['Hashtable'], P18['DictionaryArray'], P18['HashtableArray']):
return _decode_map18(buf, pos, tc)
if tc == P18['Custom']:
t, p = rd_u8(buf, pos)
n, p = rd_varint(buf, p)
_need(buf, p, n, "custom")
return ('custom', t, bytes(buf[p:p + n])), p + n
raise DecodeError(f"unhandled P18 type 0x{tc:02X} at {pos}")
def _read_number_array(buf: bytes, pos: int, reader, what: str):
n, p = rd_varint(buf, pos)
out = []
for _ in range(n):
v, p = reader(buf, p)
out.append(v)
return out, p
def _decode_map18(buf: bytes, pos: int, tc: int):
if tc in (P18['Dictionary'], P18['DictionaryArray']):
kt, pos0 = rd_u8(buf, pos)
vt, p = rd_u8(buf, pos0)
n, p = rd_varint(buf, p)
out = {}
for _ in range(n):
if kt == 0:
kt2, p = rd_u8(buf, p)
k, p = deserialize18(buf, p, kt2)
else:
k, p = deserialize18(buf, p, kt)
if vt == 0:
vt2, p = rd_u8(buf, p)
v, p = deserialize18(buf, p, vt2)
else:
v, p = deserialize18(buf, p, vt)
out[k] = v
return out, p
n, p = rd_varint(buf, pos)
out = {}
for _ in range(n):
kt, p = rd_u8(buf, p)
k, p = deserialize18(buf, p, kt)
vt, p = rd_u8(buf, p)
v, p = deserialize18(buf, p, vt)
out[k] = v
return out, p
def decode_params18(buf: bytes, pos: int):
size, pos = rd_u8(buf, pos)
out = {}
for _ in range(size):
key, pos = rd_u8(buf, pos)
tc, pos = rd_u8(buf, pos)
val, pos = deserialize18(buf, pos, tc)
out[key] = val
return out, pos
def decode_message18(buf: bytes, pos: int):
_, pos = rd_u8(buf, pos) # signal byte 0xF3
msg_type, pos = rd_u8(buf, pos)
msg_type &= 0x7F
if msg_type in (MSG_OPERATION_REQUEST, MSG_INTERNAL_REQUEST):
code, pos = rd_u8(buf, pos)
params, pos = decode_params18(buf, pos)
return PhotonMessage('Request', code, params, None, None), pos
if msg_type in (MSG_OPERATION_RESPONSE, MSG_INTERNAL_RESPONSE):
code, pos = rd_u8(buf, pos)
ret, pos = rd_i16le(buf, pos)
dv_type, pos = rd_u8(buf, pos)
dv, pos = deserialize18(buf, pos, dv_type)
params, pos = decode_params18(buf, pos)
return PhotonMessage('Response', code, params, ret, dv), pos
if msg_type == MSG_EVENT_DATA:
code, pos = rd_u8(buf, pos)
params, pos = decode_params18(buf, pos)
return PhotonMessage('Event', code, params, None, None), pos
raise DecodeError(f"unknown message type 0x{msg_type:02X}")
class FragmentAssembler:
"""Reassembles eNet SendFragment sequences into whole Photon messages."""
def __init__(self):
self._fragments: Dict[tuple, dict] = {}
def add(self, peer: int, start_seq: int, fragment_count: int,
fragment_number: int, total_length: int, data: bytes):
key = (peer, start_seq)
group = self._fragments.setdefault(
key, {'count': fragment_count, 'parts': {}, 'total': total_length})
if group['count'] != fragment_count:
self._fragments.pop(key, None)
return None
group['parts'][fragment_number] = data
if len(group['parts']) < group['count']:
return None
payload = b''.join(group['parts'][i] for i in range(group['count']))
self._fragments.pop(key, None)
return payload
class PhotonDecoder:
def __init__(self):
self.assembler = FragmentAssembler()
def decode_packet(self, payload: bytes, peer: int = 0) -> List[PhotonMessage]:
messages: List[PhotonMessage] = []
try:
return self._decode_packet(payload, peer, messages)
except DecodeError as e:
logger.debug("dropping undecodable UDP payload: %s", e)
return messages
def _decode_packet(self, payload: bytes, peer: int,
messages: List[PhotonMessage]) -> List[PhotonMessage]:
pos = 0
_peer, pos = rd_u16be(payload, pos)
crc, pos = rd_u8(payload, pos)
count, pos = rd_u8(payload, pos)
_ts, pos = rd_u32be(payload, pos)
_ch, pos = rd_u32be(payload, pos)
for _ in range(count):
cmd_type, pos = rd_u8(payload, pos)
_channel, pos = rd_u8(payload, pos)
_flags, pos = rd_u8(payload, pos)
_reserved, pos = rd_u8(payload, pos)
length, pos = rd_u32be(payload, pos)
_seq, pos = rd_u32be(payload, pos)
data_len = length - 12
if cmd_type == CMD_SEND_FRAGMENT:
start_seq, pos = rd_u32be(payload, pos)
fragment_count, pos = rd_u32be(payload, pos)
fragment_number, pos = rd_u32be(payload, pos)
total_length, pos = rd_u32be(payload, pos)
_offset, pos = rd_u32be(payload, pos)
data = payload[pos:pos + data_len - FRAG_HEADER_LEN]
pos += data_len - FRAG_HEADER_LEN
reassembled = self.assembler.add(
peer, start_seq, fragment_count, fragment_number, total_length, data)
if reassembled is not None:
messages.extend(self._decode_message(reassembled, peer))
continue
if cmd_type in (CMD_ACKNOWLEDGE, CMD_PING):
pos += data_len
continue
if cmd_type == CMD_LOGOUT:
continue
if cmd_type in (CMD_SEND_RELIABLE, CMD_SEND_UNRELIABLE,
CMD_SEND_UNRELIABLE_FRAGMENT):
if cmd_type in (CMD_SEND_UNRELIABLE,
CMD_SEND_UNRELIABLE_FRAGMENT):
pos += 4 # unknown/unreliable sequence trailers
data_len -= 4
msg_bytes = payload[pos:pos + data_len]
pos += data_len
messages.extend(self._decode_message(msg_bytes, peer))
continue
pos += data_len
return messages
def _decode_message(self, msg_bytes: bytes, peer: int) -> List[PhotonMessage]:
if not msg_bytes:
return []
signal = msg_bytes[0]
if signal != PROTOCOL18_SIGNAL:
logger.debug("dropping message with unknown signal 0x%02X", signal)
return []
try:
msg, _ = decode_message18(msg_bytes, 0)
except DecodeError as e:
logger.debug("dropping undecodable Photon message: %s", e)
return []
logger.debug("decoded Photon message: %s", msg)
return [msg]
+67
View File
@@ -0,0 +1,67 @@
import threading
import logging
from typing import Callable, List
from .photon import PhotonDecoder, PhotonMessage
from .translate import into_game_message
from .world import World
from . import discovery
logger = logging.getLogger(__name__)
class Pipeline:
"""Decodes captured UDP payloads into app events (aoaddons lib.rs flow)."""
def __init__(self, emit: Callable[[dict], None]):
self.emit = emit
self.decoder = PhotonDecoder()
self.world = World()
self._lock = threading.RLock()
self._warned_unknown = set()
def on_udp(self, payload: bytes):
logger.debug("received UDP payload: %d bytes", len(payload))
discovery.log(
'udp_payload',
length=len(payload),
payload_hex=payload.hex())
messages = self.decoder.decode_packet(payload)
if not messages:
return
with self._lock:
for message in messages:
discovery.log(
'photon_message',
message=discovery.message_record(message))
for event in self._events_from_message(message):
self.emit(event)
def _events_from_message(self, message: PhotonMessage) -> List[dict]:
game_message = into_game_message(message)
if game_message is None:
self._warn_unknown_game_message(message)
return []
discovery.log(
'game_message',
message=discovery.game_message_record(game_message))
logger.debug("translated game message: %s", game_message)
events = self.world.transform(game_message)
for event in events:
discovery.log('app_event', event=event)
logger.debug("emitting app event: %s", event)
return events
def _warn_unknown_game_message(self, message: PhotonMessage):
if message.kind == 'Event':
key = ('Event', message.code, message.params.get(252))
elif message.kind in ('Request', 'Response'):
key = (message.kind, message.code, message.params.get(253))
else:
return
if key in self._warned_unknown:
return
self._warned_unknown.add(key)
logger.warning("ignoring unknown Photon game message: kind=%s code=%s opcode=%s params=%s",
key[0], key[1], key[2], message.params)
+446
View File
@@ -0,0 +1,446 @@
from dataclasses import dataclass, field
from typing import Optional, List
from .photon import PhotonMessage
# Photon message code used for game traffic (aoaddons pipeline guard)
PHOTON_GAME_CODE = 1
# Current opcodes (albion-lens numbering, verified against captured traffic)
EVENT_LEAVE = 1
EVENT_HEALTH_UPDATE = 6
EVENT_BATCHED_HEALTH_UPDATE = 7
EVENT_EFFECT_STACK_UPDATE = 22
EVENT_NEW_CHARACTER = 29
EVENT_ITEM_GAINED = 32
EVENT_TAKE_SILVER = 62
EVENT_UPDATE_FAME = 82
EVENT_CHARACTER_EQUIPMENT_CHANGED = 90
EVENT_REGENERATION_HEALTH_CHANGED = 91
EVENT_MOB_SPAWNED = 123
EVENT_KNOCKED_DOWN = 166
EVENT_PARTY_INVITATION = 229
EVENT_PARTY_JOIN_REQUEST = 230
EVENT_PARTY_JOINED = 231
EVENT_PARTY_DISBANDED = 232
EVENT_PARTY_PLAYER_JOINED = 233
EVENT_PARTY_CHANGED_ORDER = 234
EVENT_PARTY_PLAYER_LEFT = 235
# Operation codes (response parameter 253)
OPERATION_JOIN = 2
OPERATION_CHANGE_CLUSTER = 41
def _int(value) -> Optional[int]:
if isinstance(value, bool):
return int(value)
if isinstance(value, (int, float)):
return int(value)
return None
def _float(value) -> Optional[float]:
if isinstance(value, bool):
return float(value)
if isinstance(value, (int, float)):
return float(value)
return None
def _string(value) -> Optional[str]:
if isinstance(value, str):
return value
return None
def _string_list(value) -> List[str]:
if not isinstance(value, list):
return []
out = []
for item in value:
s = _string(item)
if s:
out.append(s)
return out
def _as_int_list(value) -> List[int]:
if isinstance(value, bytes):
return list(value)
if isinstance(value, list):
out = []
for v in value:
i = _int(v)
if i is not None:
out.append(i)
return out
return []
def _as_byte_list(value) -> List[int]:
"""Unpack a Photon byte array into ints.
Batched health-update params arrive either as ``bytes`` or as a dict with a
``bytes_hex`` field (which is how the discovery log serialises them), and
occasionally as an already-decoded list. All three shapes occur for the
same parameter, so accept each of them.
"""
if isinstance(value, (bytes, bytearray)):
return list(value)
if isinstance(value, dict):
raw = value.get('bytes_hex')
if isinstance(raw, str):
return [int(raw[i:i + 2], 16) for i in range(0, len(raw) - 1, 2)]
return []
return _as_int_list(value)
@dataclass
class GameMessage:
name: str
code: int
params: dict = field(default_factory=dict)
def param(self, key: int):
return self.params.get(key)
@dataclass(frozen=True)
class EffectApplication:
"""One entry of a victim's active effect list.
``applier`` is the entity that put the effect on the target; the game
sends it explicitly rather than leaving it to be inferred.
"""
applier: int
effect_id: int
def into_game_message(message: PhotonMessage) -> Optional[GameMessage]:
if message.code != PHOTON_GAME_CODE:
return None
if message.kind == 'Event':
code = _int(message.params.get(252))
if code is None:
names = msg_party_roster_names_from_params(message.params)
if names:
return GameMessage('PartyRoster', 0, message.params)
return None
name = EVENT_NAMES.get(code)
if name is None:
return None
return GameMessage(name, code, message.params)
if message.kind in ('Request', 'Response'):
code = _int(message.params.get(253))
if code is None:
return None
name = OPERATION_NAMES.get(code)
if name is None:
return None
return GameMessage(name, code, message.params)
return None
EVENT_NAMES = {
EVENT_LEAVE: 'Leave',
EVENT_HEALTH_UPDATE: 'HealthUpdate',
EVENT_BATCHED_HEALTH_UPDATE: 'BatchedHealthUpdate',
EVENT_EFFECT_STACK_UPDATE: 'EffectStackUpdate',
EVENT_NEW_CHARACTER: 'NewCharacter',
EVENT_ITEM_GAINED: 'ItemGained',
EVENT_TAKE_SILVER: 'TakeSilver',
EVENT_UPDATE_FAME: 'UpdateFame',
EVENT_CHARACTER_EQUIPMENT_CHANGED: 'CharacterEquipmentChanged',
EVENT_REGENERATION_HEALTH_CHANGED: 'RegenerationHealthChanged',
EVENT_MOB_SPAWNED: 'MobSpawned',
EVENT_KNOCKED_DOWN: 'KnockedDown',
EVENT_PARTY_INVITATION: 'PartyInvitation',
EVENT_PARTY_JOIN_REQUEST: 'PartyJoinRequest',
EVENT_PARTY_JOINED: 'PartyJoined',
EVENT_PARTY_DISBANDED: 'PartyDisbanded',
EVENT_PARTY_PLAYER_JOINED: 'PartyPlayerJoined',
EVENT_PARTY_CHANGED_ORDER: 'PartyChangedOrder',
EVENT_PARTY_PLAYER_LEFT: 'PartyPlayerLeft',
}
OPERATION_NAMES = {
OPERATION_JOIN: 'Join',
OPERATION_CHANGE_CLUSTER: 'ChangeCluster',
}
# Parameter accessors used by the world state machine. Field names follow
# aoaddons' messages.json layouts, with the current opcode space from albion-lens.
#
# Naming note: the older messages.json labelled HealthUpdate params as
# ``source@0`` / ``target@6``, but the capture data shows the opposite of what
# those names suggest -- param 0 is the entity whose health changed (the victim)
# and param 6 is the entity that caused it (the attacker). The accessors below
# are named for what the wire actually carries.
def msg_subject_id(msg: GameMessage) -> int:
"""Param 0: the entity the event is about.
For most events that is simply the subject (the character that joined, left,
or changed equipment). For HealthUpdate it is the *victim*.
"""
v = _int(msg.params.get(0))
return v if v is not None else 0
def msg_character_name(msg: GameMessage) -> str:
v = _string(msg.params.get(2))
return v if v is not None else ''
def msg_new_character_name(msg: GameMessage) -> str:
v = _string(msg.params.get(1))
return v if v is not None else ''
def msg_map_index(msg: GameMessage) -> Optional[str]:
return _string(msg.params.get(8))
def msg_attacker_id(msg: GameMessage) -> int:
"""Param 6: the entity responsible for a health change (attacker or healer)."""
v = _int(msg.params.get(6))
return v if v is not None else 0
def msg_value(msg: GameMessage) -> float:
"""Param 2: the signed health delta. Negative is damage, positive is healing."""
v = _float(msg.params.get(2))
return v if v is not None else 0.0
def msg_health_after(msg: GameMessage) -> Optional[float]:
"""Param 3: the victim's health once the hit has been applied."""
return _float(msg.params.get(3))
def msg_hit_type(msg: GameMessage) -> Optional[int]:
"""Param 5: hit-type enum.
Observed values split into two groups. ``0`` and ``1`` accompany basic
attacks (median damage ~45) and always carry ``-1`` for param 7; ``2``, ``3``,
``5`` and ``6`` accompany ability hits (median ~164-242). The exact meaning
of each value is not yet known, so it is carried through untranslated.
"""
return _int(msg.params.get(5))
def msg_batched_victim_id(msg: GameMessage) -> int:
"""Param 0 of a batched health update: the entity every hit landed on."""
return msg_subject_id(msg)
def msg_batched_ticks(msg: GameMessage) -> List[int]:
"""Param 1: one tick counter per hit."""
return _as_int_list(msg.params.get(1))
def msg_batched_values(msg: GameMessage) -> List[float]:
"""Param 2: one signed health delta per hit."""
v = msg.params.get(2)
if not isinstance(v, list):
return []
out = []
for item in v:
f = _float(item)
if f is not None:
out.append(f)
return out
def msg_batched_health_after(msg: GameMessage) -> List[float]:
"""Param 3: one resulting-health value per hit."""
v = msg.params.get(3)
if not isinstance(v, list):
return []
out = []
for item in v:
f = _float(item)
if f is not None:
out.append(f)
return out
def msg_batched_hit_types(msg: GameMessage) -> List[int]:
"""Param 5: one hit-type enum per hit.
These arrive as a raw byte array rather than a decoded list, so they need
unpacking rather than the usual int coercion.
"""
return _as_byte_list(msg.params.get(5))
def msg_batched_attacker_ids(msg: GameMessage) -> List[int]:
"""Param 6: one attacker entity id per hit.
Also a raw byte array. Unlike param 2/3/5 the decoder sometimes produces a
plain list here instead, so both shapes are accepted.
"""
return _as_byte_list(msg.params.get(6))
def msg_effect_stack_appliers(msg: GameMessage) -> List[int]:
"""Param 1: the entity responsible for each effect on the victim.
Index-aligned with ``msg_effect_stack_ids``. The game sends the applier
outright, so attribution does not have to infer who applied a debuff from
the attacker's weapon -- which is what the original plan assumed.
"""
return _as_int_list(msg.params.get(1))
def msg_effect_stack_ids(msg: GameMessage) -> List[int]:
"""Param 2: one effect id per entry in the victim's active effect list.
These are runtime-assigned ids. They are stable for the life of a session
and usually unique to one (spell, caster) pair, but they are not the spell
ids used by the game data files, so they cannot be looked up statically.
"""
return _as_int_list(msg.params.get(2))
def msg_effect_stack_applications(msg: GameMessage) -> List[EffectApplication]:
"""Pair up the applier and effect id lists.
The two arrays are index-aligned and the same length on every observed
message. If a capture ever produced a ragged pair the mismatched tail is
dropped rather than guessed at.
"""
appliers = msg_effect_stack_appliers(msg)
effects = msg_effect_stack_ids(msg)
return [EffectApplication(applier, effect)
for applier, effect in zip(appliers, effects)]
def msg_mob_template_id(msg: GameMessage) -> Optional[int]:
"""Param 1: the numeric mob template this entity spawned from.
Template ids are the enumeration index of the mob table. They are a
different id space from item ids -- 454 is the Giant Snake as a mob but a
gathering skillbook as an item -- so this must never be resolved through
the item table.
"""
return _int(msg.params.get(1))
def msg_mob_hitpoints_max(msg: GameMessage) -> Optional[float]:
"""Param 13: the mob's maximum hit points at spawn.
Doubles as a cross-check on the template id: the two must agree.
"""
return _float(msg.params.get(13))
def msg_items(msg: GameMessage) -> List[int]:
return _as_int_list(msg.params.get(2))
def msg_new_character_items(msg: GameMessage) -> List[int]:
return _as_int_list(msg.params.get(33))
def msg_regeneration_rate(msg: GameMessage) -> Optional[float]:
if 4 not in msg.params:
return None
return _float(msg.params.get(4))
def msg_total_fame(msg: GameMessage) -> int:
v = _int(msg.params.get(1))
return v if v is not None else 0
def msg_fame_gained(msg: GameMessage) -> Optional[int]:
if 2 not in msg.params:
return None
return _int(msg.params.get(2))
def msg_fame_is_premium(msg: GameMessage) -> bool:
return msg.params.get(5) is True
def msg_fame_satchel(msg: GameMessage) -> int:
v = _int(msg.params.get(10))
return v if v is not None else 0
def msg_fame_bonus_factor(msg: GameMessage) -> float:
if 17 not in msg.params:
return 0.0
v = _float(msg.params.get(17))
return v if v is not None else 0.0
def msg_collected_item_id(msg: GameMessage) -> Optional[int]:
return _int(msg.params.get(1))
def msg_collected_item_quantity(msg: GameMessage) -> Optional[int]:
return _int(msg.params.get(2))
def msg_collected_item_value(msg: GameMessage) -> Optional[int]:
return _int(msg.params.get(4))
def msg_silver_yield_pre_tax(msg: GameMessage) -> Optional[int]:
return _int(msg.params.get(3))
def msg_silver_cluster_tax(msg: GameMessage) -> int:
v = _int(msg.params.get(4))
return v if v is not None else 0
def msg_silver_guild_tax(msg: GameMessage) -> int:
v = _int(msg.params.get(5))
return v if v is not None else 0
def msg_silver_alliance_penalty(msg: GameMessage) -> int:
v = _int(msg.params.get(6))
return v if v is not None else 0
def msg_party_structures(msg: GameMessage) -> List[List[int]]:
out = []
for item in msg.params.get(4, []) or []:
out.append(_as_int_list(item))
return out
def msg_party_names(msg: GameMessage) -> List[str]:
out = []
for item in msg.params.get(5, []) or []:
s = _string(item)
if s is not None:
out.append(s)
return out
def msg_party_structure(msg: GameMessage) -> List[int]:
return _as_int_list(msg.params.get(1))
def msg_party_name(msg: GameMessage) -> str:
v = _string(msg.params.get(2))
return v if v is not None else ''
def msg_party_roster_names_from_params(params: dict) -> List[str]:
names = _string_list(params.get(9))
if len(names) < 2:
return []
if any(name.startswith('UNLOCKED_') for name in names):
return []
return names
def msg_party_roster_names(msg: GameMessage) -> List[str]:
return msg_party_roster_names_from_params(msg.params)
+537
View File
@@ -0,0 +1,537 @@
import logging
from typing import Dict, List, Optional
from .. import environment
from . import items as itemdb
from . import party_memory
from . import translate
from .translate import GameMessage
FIX_POINT = 10000.0
FAME_MIN_TOTAL = 1000000 # albion-lens sanity filter for UpdateFame events
logger = logging.getLogger(__name__)
class IdCache:
"""Maps dynamic (per-session) ids to stable ids and names.
Mirrors aoaddons src/game/id_cache.rs: ids are assigned sequentially by
player name, so reconnecting to a zone keeps the same id for a player.
"""
def __init__(self):
self.dyn_to_static: Dict[int, int] = {}
self.static_to_name: Dict[int, str] = {}
self.static_to_dyn: Dict[int, int] = {}
self.last_id = 0
def save(self, dynamic_id: int, name: str):
if not name:
return
static_id = self._find_static_id(name)
if static_id is not None:
old_dyn = self.static_to_dyn.get(static_id)
if old_dyn is not None:
self.dyn_to_static.pop(old_dyn, None)
self.dyn_to_static[dynamic_id] = static_id
self.static_to_dyn[static_id] = dynamic_id
return
static_id = self.last_id
self.last_id += 1
self.dyn_to_static[dynamic_id] = static_id
self.static_to_dyn[static_id] = dynamic_id
self.static_to_name[static_id] = name
def _find_static_id(self, name: str) -> Optional[int]:
for sid, sid_name in self.static_to_name.items():
if sid_name == name:
return sid
return None
def get_static_id(self, dynamic_id: int) -> Optional[int]:
return self.dyn_to_static.get(dynamic_id)
def get_name(self, static_id: int) -> Optional[str]:
return self.static_to_name.get(static_id)
class Party:
"""Tracks party membership from party events (aoaddons src/game/party.rs)."""
def __init__(self):
self.main_player_name: Optional[str] = None
self.items: List[dict] = [] # {'name', 'id'}
self.last_names: List[str] = []
def set_main_player_name(self, name: str):
self.main_player_name = name
def _game_event(self) -> dict:
self.last_names = _unique_names([item['name'] for item in self.items])
return {'name': 'UpdateParty', 'value': {
'player_names': self.last_names}}
def set_names(self, names: List[str]):
self.items = [
{'name': name, 'id': index}
for index, name in enumerate(_unique_names(names))
]
self.last_names = [item['name'] for item in self.items]
def joined(self, msg: GameMessage) -> Optional[dict]:
structures = translate.msg_party_structures(msg)
names = translate.msg_party_names(msg)
self.items = []
for structure, name in zip(structures, names):
self.items.append({'name': name, 'id': _party_id(structure)})
return self._game_event()
def disbanded(self) -> Optional[dict]:
self.items = []
self.last_names = []
return self._game_event()
def player_left(self, msg: GameMessage) -> Optional[dict]:
if self.main_player_name is None:
return None
structure_id = _party_id(translate.msg_party_structure(msg))
party_item = next((i for i in self.items if i['id'] == structure_id), None)
if party_item is None:
return None
if party_item['name'] == self.main_player_name:
return self.disbanded()
self.items = [i for i in self.items if i['id'] != structure_id]
return self._game_event()
def single_player_joined(self, msg: GameMessage) -> Optional[dict]:
self.items.append({
'name': translate.msg_party_name(msg),
'id': _party_id(translate.msg_party_structure(msg)),
})
return self._game_event()
def roster(self, msg: GameMessage) -> Optional[dict]:
self.set_names(translate.msg_party_roster_names(msg))
return self._game_event()
def remembered(self, names: List[str]) -> Optional[dict]:
self.set_names(names)
return self._game_event()
class UnconsumedMessages:
"""Buffers messages tagged with a dynamic id whose static id is unknown.
Replayed once the id is resolved (aoaddons src/game/unconsumed_messages.rs).
"""
def __init__(self):
self._messages: Dict[int, List[GameMessage]] = {}
def add(self, dynamic_id: int, msg: GameMessage):
self._messages.setdefault(dynamic_id, []).append(msg)
def get_for_id(self, dynamic_id: int) -> List[GameMessage]:
return self._messages.get(dynamic_id, [])
class World:
"""Transforms translated game messages into app events (aoaddons world.rs)."""
def __init__(self, remember_last_party: Optional[bool] = None):
self.cache = IdCache()
self.party = Party()
self.unconsumed_messages = UnconsumedMessages()
self.main_player_id: Optional[int] = None
self._main_player_joined = False
self._fame_totals: Dict[int, int] = {}
self._seen_item_pickups = set()
self._remember_last_party = (environment.remember_last_party()
if remember_last_party is None
else remember_last_party)
self._remembered_party_names = (party_memory.load_last_party()
if self._remember_last_party else [])
if self._remember_last_party:
logger.debug("remember_last_party enabled; loaded names: %s",
self._remembered_party_names)
else:
logger.debug("remember_last_party disabled; saved party will not autoload")
self._zone_candidate_names: List[str] = []
self._explicit_party_seen = False
self._party_inferred = False
def transform(self, message: GameMessage) -> List[dict]:
if message.name == 'NewCharacter':
return self._on_new_character(message)
if message.name == 'Join':
return self._on_join(message)
if message.name == 'ChangeCluster':
return self._on_change_cluster(message)
if message.name == 'Leave':
return self._on_leave(message)
if message.name == 'HealthUpdate':
return self._on_health_update(message)
if message.name == 'BatchedHealthUpdate':
return self._on_batched_health_update(message)
if message.name == 'RegenerationHealthChanged':
return self._on_regeneration(message)
if message.name == 'KnockedDown':
return self._on_knocked_down(message)
if message.name == 'UpdateFame':
return self._on_update_fame(message)
if message.name == 'ItemGained':
return self._on_item_gained(message)
if message.name == 'TakeSilver':
return self._on_take_silver(message)
if message.name == 'CharacterEquipmentChanged':
return self._on_character_equipment_changed(message)
if message.name == 'PartyJoined':
return self._explicit_party_event(self.party.joined(message))
if message.name == 'PartyDisbanded':
return self._explicit_party_event(self.party.disbanded())
if message.name == 'PartyPlayerJoined':
return self._explicit_party_event(self.party.single_player_joined(message))
if message.name == 'PartyPlayerLeft':
return self._explicit_party_event(self.party.player_left(message))
if message.name == 'PartyRoster':
return self._explicit_party_event(self.party.roster(message))
return []
def _party_event(self, event: Optional[dict]) -> List[dict]:
return [event] if event is not None else []
def _explicit_party_event(self, event: Optional[dict]) -> List[dict]:
self._explicit_party_seen = True
self._party_inferred = False
self._remember_party_event(event)
return self._party_event(event)
def _on_new_character(self, msg: GameMessage) -> List[dict]:
name = translate.msg_new_character_name(msg)
dynamic_id = _dyn(translate.msg_subject_id(msg))
if not name:
return []
self.cache.save(dynamic_id, name)
static_id = self.cache.get_static_id(dynamic_id)
if static_id is None:
return []
result = [{
'name': 'PlayerAppeared',
'value': {'id': static_id, 'name': name},
}]
result.extend(self._infer_party_from_zone_name(name))
items = itemdb.decode_items(translate.msg_new_character_items(msg))
if items:
result.append({
'name': 'UpdateItems',
'value': {'source': static_id, 'value': items},
})
result.extend(self._replay(dynamic_id))
if self.main_player_id is None:
self.main_player_id = static_id
return result
def _on_join(self, msg: GameMessage) -> List[dict]:
name = translate.msg_character_name(msg)
dynamic_id = _dyn(translate.msg_subject_id(msg))
if not name:
return []
self.cache.save(dynamic_id, name)
static_id = self.cache.get_static_id(dynamic_id)
if static_id is None:
return []
self.party.set_main_player_name(name)
result = []
if not self._main_player_joined:
result.append({'name': 'ZoneChange'})
self.main_player_id = static_id
self._main_player_joined = True
self._zone_candidate_names = _unique_names(self._zone_candidate_names + [name])
self._explicit_party_seen = False
self._party_inferred = False
self._seen_item_pickups.clear()
result.append({
'name': 'MainPlayerAppeared',
'value': {'id': static_id, 'name': name},
})
result.extend(self._remembered_party_events(name))
result.extend(self._infer_party_from_zone_name(name))
result.extend(self._replay(dynamic_id))
return result
def _on_change_cluster(self, msg: GameMessage) -> List[dict]:
if self.main_player_id is None:
return []
self._reset_zone_party_inference()
self._seen_item_pickups.clear()
return [{'name': 'ZoneChange'}]
def _on_leave(self, msg: GameMessage) -> List[dict]:
dynamic_id = _dyn(translate.msg_subject_id(msg))
static_id = self.cache.get_static_id(dynamic_id)
if static_id is None:
return []
if self.main_player_id == static_id:
self.main_player_id = None
self._main_player_joined = False
self._reset_zone_party_inference()
self._seen_item_pickups.clear()
return [{'name': 'ZoneChange'}]
return []
def _on_health_update(self, msg: GameMessage) -> List[dict]:
# Params: [0]=victim (entity whose health changed), [2]=signed delta,
# [3]=victim health after the hit, [5]=hit type, [6]=attacker/healer.
value = translate.msg_value(msg)
if value == 0.0:
return []
victim_id = _dyn(translate.msg_subject_id(msg))
attacker_id = _dyn(translate.msg_attacker_id(msg))
hit_type = translate.msg_hit_type(msg)
health_after = translate.msg_health_after(msg)
return self._health_events(
attacker_id=attacker_id,
victim_id=victim_id,
value=value,
hit_type=hit_type,
health_after=health_after)
def _on_batched_health_update(self, msg: GameMessage) -> List[dict]:
# Batched form of HealthUpdate: one victim, several hits delivered in a
# single packet, with parallel arrays indexed per hit. Verified against
# captures to be additional damage rather than a repeat of the scalar
# form -- see PLAN.md F2.
values = translate.msg_batched_values(msg)
if not values:
return []
victim_id = _dyn(translate.msg_batched_victim_id(msg))
health_after = translate.msg_batched_health_after(msg)
hit_types = translate.msg_batched_hit_types(msg)
attackers = translate.msg_batched_attacker_ids(msg)
events: List[dict] = []
for index, value in enumerate(values):
if value == 0.0:
continue
attacker = attackers[index] if index < len(attackers) else None
hit_type = hit_types[index] if index < len(hit_types) else None
after = health_after[index] if index < len(health_after) else None
events.extend(self._health_events(
attacker_id=_dyn(attacker) if attacker is not None else None,
victim_id=victim_id,
value=value,
hit_type=hit_type,
health_after=after))
return events
def _health_events(self, attacker_id: Optional[int], victim_id: int,
value: float, hit_type: Optional[int],
health_after: Optional[float]) -> List[dict]:
"""Build the damage/heal events for a single health change.
``DamageDone`` and ``DamageTaken`` are emitted independently so a hit
from an unknown attacker (a mob, say) still registers against a tracked
victim, and a hit on an untracked victim still registers for a tracked
attacker.
"""
attacker_static = (self.cache.get_static_id(attacker_id)
if attacker_id is not None else None)
victim_static = self.cache.get_static_id(victim_id)
events = []
if attacker_static is not None:
payload = {'source': attacker_static,
'target': victim_static,
'value': float(abs(value)),
'hit_type': hit_type,
'health_after': health_after}
events.append({
'name': 'DamageDone' if value < 0.0 else 'HealthReceived',
'value': payload,
})
if value < 0.0 and victim_static is not None:
events.append({
'name': 'DamageTaken',
'value': {'source': victim_static,
'value': float(abs(value)),
'hit_type': hit_type},
})
return events
def _on_regeneration(self, msg: GameMessage) -> List[dict]:
dynamic_id = _dyn(translate.msg_subject_id(msg))
static_id = self.cache.get_static_id(dynamic_id)
if static_id is None:
return []
name = self.cache.get_name(static_id) or ''
if not name:
return []
event_name = ('LeaveCombat' if translate.msg_regeneration_rate(msg) is not None
else 'EnterCombat')
return [{'name': event_name, 'value': {'id': static_id, 'name': name}}]
def _on_knocked_down(self, msg: GameMessage) -> List[dict]:
dynamic_id = _dyn(translate.msg_subject_id(msg))
static_id = self.cache.get_static_id(dynamic_id)
if static_id is None:
return []
name = self.cache.get_name(static_id) or ''
if not name:
return []
return [{'name': 'LeaveCombat', 'value': {'id': static_id, 'name': name}}]
def _on_update_fame(self, msg: GameMessage) -> List[dict]:
dynamic_id = _dyn(translate.msg_subject_id(msg))
static_id = self.cache.get_static_id(dynamic_id)
if static_id is None:
return []
total = translate.msg_total_fame(msg)
if total < FAME_MIN_TOTAL:
return []
prev = self._fame_totals.get(static_id)
if prev == total:
return []
gained = translate.msg_fame_gained(msg)
self._fame_totals[static_id] = total
if gained is None:
if prev is None or total < prev:
return []
gained = total - prev
if gained <= 0:
return []
# Match the in-game display: zone/event bonus factor and premium are
# applied on top of the base fame, plus any satchel (insight bag) fame.
value = float(gained)
if translate.msg_fame_is_premium(msg):
value *= 1.5
value += float(translate.msg_fame_satchel(msg))
value *= 1.0 + translate.msg_fame_bonus_factor(msg)
return [{'name': 'UpdateFame', 'value': {'value': value / FIX_POINT}}]
def _on_item_gained(self, msg: GameMessage) -> List[dict]:
if not self._main_player_joined:
return []
source_id = _dyn(translate.msg_subject_id(msg))
item_id = translate.msg_collected_item_id(msg)
quantity = translate.msg_collected_item_quantity(msg)
if item_id is None or quantity is None or quantity <= 0:
return []
pickup_key = (source_id, item_id, quantity)
if pickup_key in self._seen_item_pickups:
return []
self._seen_item_pickups.add(pickup_key)
item_name = itemdb.display_name(item_id)
value = {
'item_id': item_id,
'item_name': item_name,
'quantity': quantity,
}
estimated_value = translate.msg_collected_item_value(msg)
if estimated_value is not None:
value['estimated_value'] = estimated_value
return [{'name': 'ItemCollected', 'value': value}]
def _on_take_silver(self, msg: GameMessage) -> List[dict]:
if not self._main_player_joined:
return []
dynamic_id = _dyn(translate.msg_subject_id(msg))
static_id = self.cache.get_static_id(dynamic_id)
if static_id is None or static_id != self.main_player_id:
return []
yield_pre_tax = translate.msg_silver_yield_pre_tax(msg)
if yield_pre_tax is None or yield_pre_tax <= 0:
return []
taxes = (translate.msg_silver_cluster_tax(msg)
+ translate.msg_silver_guild_tax(msg)
+ translate.msg_silver_alliance_penalty(msg))
gained = max(0, yield_pre_tax - taxes)
if gained <= 0:
return []
return [{'name': 'SilverGained', 'value': {
'value': float(gained / FIX_POINT),
'silver_type': 'looted',
}}]
def _on_character_equipment_changed(self, msg: GameMessage) -> List[dict]:
dynamic_id = _dyn(translate.msg_subject_id(msg))
static_id = self.cache.get_static_id(dynamic_id)
if static_id is None:
self.unconsumed_messages.add(dynamic_id, msg)
return []
items = itemdb.decode_items(translate.msg_items(msg))
return [{'name': 'UpdateItems', 'value': {'source': static_id, 'value': items}}]
def _replay(self, dynamic_id: int) -> List[dict]:
result: List[dict] = []
for msg in self.unconsumed_messages.get_for_id(dynamic_id):
result.extend(self.transform(msg))
return result
def _remembered_party_events(self, main_player_name: str) -> List[dict]:
if not self._remember_last_party or not self._remembered_party_names:
return []
if main_player_name not in self._remembered_party_names:
return []
event = self.party.remembered(self._remembered_party_names)
return self._party_event(event)
def _infer_party_from_zone_name(self, name: str) -> List[dict]:
if not self._remember_last_party or self._explicit_party_seen:
return []
if name:
self._zone_candidate_names = _unique_names(
self._zone_candidate_names + [name])
if not self._main_player_joined:
return []
if self.party.last_names and not self._party_inferred:
return []
if self._remembered_party_names and not self._party_inferred:
names = [n for n in self._remembered_party_names
if n in self._zone_candidate_names]
if self.party.main_player_name in self._remembered_party_names:
names = self._remembered_party_names
else:
names = self._zone_candidate_names
if len(names) < 2 or len(names) > 5:
return []
event = self.party.remembered(names)
self._party_inferred = True
self._remember_party_event(event)
return self._party_event(event)
def _remember_party_event(self, event: Optional[dict]):
if event is None:
return
names = event.get('value', {}).get('player_names', [])
remembered_names = _unique_names(names)
if remembered_names:
self._remembered_party_names = remembered_names
party_memory.save_last_party(remembered_names)
elif self._remember_last_party:
self._remembered_party_names = []
logger.debug("empty party event cleared in-memory party only")
def _reset_zone_party_inference(self):
self._zone_candidate_names = []
self._explicit_party_seen = False
self._party_inferred = False
self.party.items = []
self.party.last_names = []
def _dyn(value) -> int:
return int(value) & 0xFFFFFFFF
def _party_id(party_structure: List[int]) -> int:
return sum(party_structure)
def _unique_names(names: List[str]) -> List[str]:
out = []
seen = set()
for name in names:
if not name or name in seen:
continue
seen.add(name)
out.append(name)
return out
+97 -7
View File
@@ -1,3 +1,4 @@
import logging
from typing import Iterable from typing import Iterable
from dataclasses import dataclass from dataclasses import dataclass
from queue import Queue from queue import Queue
@@ -8,12 +9,15 @@ from .environment import TEST_ENV_ENABLED
from . import backend_proxy from . import backend_proxy
from .backend_proxy import InitializationResult, INITIALIZATION_RESULT from .backend_proxy import InitializationResult, INITIALIZATION_RESULT
from .stats import combat_stats, fame_stats, time_stats, combat_state from .stats import combat_stats, economy_stats, fame_stats, time_stats, combat_state
from .consts import events as ev_consts from .consts import events as ev_consts
from .event_receiver import VisibilityEventReceiver from .event_receiver import VisibilityEventReceiver
from .stats.visibility import Visibility from .stats.visibility import Visibility
logger = logging.getLogger(__name__)
@dataclass(frozen=True) @dataclass(frozen=True)
class VisibilityType: class VisibilityType:
LastFight: str = 'last_fight' LastFight: str = 'last_fight'
@@ -26,11 +30,13 @@ class StatType:
Combat: str = 'Combat' Combat: str = 'Combat'
Fame: str = 'Fame' Fame: str = 'Fame'
Time: str = 'Time' Time: str = 'Time'
Economy: str = 'Economy'
@dataclass(frozen=True) @dataclass(frozen=True)
class CombatStatType: class CombatStatType:
Damage: str = 'Damage' Damage: str = 'Damage'
DamageTaken: str = 'DamageTaken'
Healing: str = 'Healing' Healing: str = 'Healing'
@@ -42,16 +48,19 @@ class GameStats():
StatType.Combat: combat_stats.CombatStats(self.visibility), StatType.Combat: combat_stats.CombatStats(self.visibility),
StatType.Fame: fame_stats.FameStats(), StatType.Fame: fame_stats.FameStats(),
StatType.Time: time_stats.TimeStats(), StatType.Time: time_stats.TimeStats(),
StatType.Economy: economy_stats.EconomyStats(),
} }
self.last_fight = { self.last_fight = {
StatType.Combat: combat_stats.CombatStats(self.visibility), StatType.Combat: combat_stats.CombatStats(self.visibility),
StatType.Fame: fame_stats.FameStats(), StatType.Fame: fame_stats.FameStats(),
StatType.Time: time_stats.TimeStats(), StatType.Time: time_stats.TimeStats(),
StatType.Economy: economy_stats.EconomyStats(),
} }
self.history = { self.history = {
StatType.Combat: combat_stats.CombatStats(self.visibility), StatType.Combat: combat_stats.CombatStats(self.visibility),
StatType.Fame: fame_stats.FameStats(), StatType.Fame: fame_stats.FameStats(),
StatType.Time: time_stats.TimeStats(), StatType.Time: time_stats.TimeStats(),
StatType.Economy: economy_stats.EconomyStats(),
} }
def register_event(self, event): def register_event(self, event):
@@ -64,6 +73,7 @@ class GameStats():
self.zone[StatType.Combat]) self.zone[StatType.Combat])
self.history[StatType.Fame].update(self.zone[StatType.Fame]) self.history[StatType.Fame].update(self.zone[StatType.Fame])
self.history[StatType.Time].update(self.zone[StatType.Time]) self.history[StatType.Time].update(self.zone[StatType.Time])
self.history[StatType.Economy].update(self.zone[StatType.Economy])
self._construct_new_stats([VisibilityType.Zone]) self._construct_new_stats([VisibilityType.Zone])
@@ -71,11 +81,13 @@ class GameStats():
self.last_fight[StatType.Combat].receive(event) self.last_fight[StatType.Combat].receive(event)
self.zone[StatType.Fame].receive(event) self.zone[StatType.Fame].receive(event)
self.last_fight[StatType.Fame].receive(event) self.last_fight[StatType.Fame].receive(event)
self.zone[StatType.Economy].receive(event)
self.last_fight[StatType.Economy].receive(event)
self.visibility.receive(event) self.visibility.receive(event)
def reset(self, stat_type): def reset(self, stat_type):
if stat_type == VisibilityType.Zone: if stat_type == VisibilityType.Zone:
for t in (StatType.Combat, StatType.Time, StatType.Fame): for t in (StatType.Combat, StatType.Time, StatType.Fame, StatType.Economy):
self.history[t].update(self.zone[t]) self.history[t].update(self.zone[t])
self._construct_new_stats( self._construct_new_stats(
(VisibilityType.Zone, VisibilityType.LastFight)) (VisibilityType.Zone, VisibilityType.LastFight))
@@ -93,6 +105,14 @@ class GameStats():
elif stat_type == VisibilityType.Overall: elif stat_type == VisibilityType.Overall:
return self.history[StatType.Combat].combined(self.zone[StatType.Combat]).players_damage() return self.history[StatType.Combat].combined(self.zone[StatType.Combat]).players_damage()
def get_damage_taken_stats(self, stat_type):
if stat_type == VisibilityType.Zone:
return self.zone[StatType.Combat].players_damage_taken()
elif stat_type == VisibilityType.LastFight:
return self.last_fight[StatType.Combat].players_damage_taken()
elif stat_type == VisibilityType.Overall:
return self.history[StatType.Combat].combined(self.zone[StatType.Combat]).players_damage_taken()
def get_healing_stats(self, stat_type): def get_healing_stats(self, stat_type):
if stat_type == VisibilityType.Zone: if stat_type == VisibilityType.Zone:
return self.zone[StatType.Combat].players_healing() return self.zone[StatType.Combat].players_healing()
@@ -101,6 +121,14 @@ class GameStats():
elif stat_type == VisibilityType.Overall: elif stat_type == VisibilityType.Overall:
return self.history[StatType.Combat].combined(self.zone[StatType.Combat]).players_healing() return self.history[StatType.Combat].combined(self.zone[StatType.Combat]).players_healing()
def get_total_healing_stats(self, stat_type):
if stat_type == VisibilityType.Zone:
return self.zone[StatType.Combat].players_total_healing()
elif stat_type == VisibilityType.LastFight:
return self.last_fight[StatType.Combat].players_total_healing()
elif stat_type == VisibilityType.Overall:
return self.history[StatType.Combat].combined(self.zone[StatType.Combat]).players_total_healing()
def fame_stats(self, stat_type): def fame_stats(self, stat_type):
if stat_type == VisibilityType.Zone: if stat_type == VisibilityType.Zone:
return self.zone[StatType.Fame].stats() return self.zone[StatType.Fame].stats()
@@ -117,8 +145,32 @@ class GameStats():
elif stat_type == VisibilityType.Overall: elif stat_type == VisibilityType.Overall:
return self.history[StatType.Time].combined(self.zone[StatType.Time]).stats() return self.history[StatType.Time].combined(self.zone[StatType.Time]).stats()
def economy_stats(self, stat_type):
if stat_type == VisibilityType.Zone:
return self.zone[StatType.Economy].stats()
elif stat_type == VisibilityType.LastFight:
return self.last_fight[StatType.Economy].stats()
elif stat_type == VisibilityType.Overall:
return self.history[StatType.Economy].combined(self.zone[StatType.Economy]).stats()
def item_stats(self, stat_type):
if stat_type == VisibilityType.Zone:
return self.zone[StatType.Economy].item_list()
elif stat_type == VisibilityType.LastFight:
return self.last_fight[StatType.Economy].item_list()
elif stat_type == VisibilityType.Overall:
return self.history[StatType.Economy].combined(self.zone[StatType.Economy]).item_list()
def silver_stats(self, stat_type):
if stat_type == VisibilityType.Zone:
return self.zone[StatType.Economy].silver_list()
elif stat_type == VisibilityType.LastFight:
return self.last_fight[StatType.Economy].silver_list()
elif stat_type == VisibilityType.Overall:
return self.history[StatType.Economy].combined(self.zone[StatType.Economy]).silver_list()
def _construct_new_stats(self, scope: Iterable[str]): def _construct_new_stats(self, scope: Iterable[str]):
types = (StatType.Combat, StatType.Time, StatType.Fame) types = (StatType.Combat, StatType.Time, StatType.Fame, StatType.Economy)
for s in scope: for s in scope:
for t in types: for t in types:
if t == StatType.Time: if t == StatType.Time:
@@ -128,6 +180,8 @@ class GameStats():
getattr(self, s)[t]) getattr(self, s)[t])
elif t == StatType.Fame: elif t == StatType.Fame:
getattr(self, s)[t] = fame_stats.FameStats() getattr(self, s)[t] = fame_stats.FameStats()
elif t == StatType.Economy:
getattr(self, s)[t] = economy_stats.EconomyStats()
game_stats = GameStats() game_stats = GameStats()
@@ -152,18 +206,34 @@ def last_fight_stats(combat_stat_type: str):
return get_stats(VisibilityType.LastFight, combat_stat_type) return get_stats(VisibilityType.LastFight, combat_stat_type)
def zone_total_healing_stats():
return game_stats.get_total_healing_stats(VisibilityType.Zone)
def overall_total_healing_stats():
return game_stats.get_total_healing_stats(VisibilityType.Overall)
def last_fight_total_healing_stats():
return game_stats.get_total_healing_stats(VisibilityType.LastFight)
cached_players = () # do not compute values if there is nothing in queue cached_players = () # do not compute values if there is nothing in queue
cached_stat_type = None cached_stat_type = None
cached_combat_stat_type = None cached_combat_stat_type = None
def get_stats(stat_type: str, combat_stat_type: str): def _drain_events():
global cached_players, cached_stat_type, cached_combat_stat_type
new_events = False new_events = False
while not event_queue.empty(): while not event_queue.empty():
new_events = True new_events = True
game_stats.register_event(event_queue.get_nowait()) game_stats.register_event(event_queue.get_nowait())
return new_events
def get_stats(stat_type: str, combat_stat_type: str):
global cached_players, cached_stat_type, cached_combat_stat_type
new_events = _drain_events()
fame = game_stats.fame_stats(stat_type) fame = game_stats.fame_stats(stat_type)
time = game_stats.time_stats(stat_type)['seconds_in_game'] time = game_stats.time_stats(stat_type)['seconds_in_game']
@@ -175,6 +245,7 @@ def get_stats(stat_type: str, combat_stat_type: str):
cached_players = { cached_players = {
CombatStatType.Damage: lambda stat_type: game_stats.get_damage_stats(stat_type), CombatStatType.Damage: lambda stat_type: game_stats.get_damage_stats(stat_type),
CombatStatType.DamageTaken: lambda stat_type: game_stats.get_damage_taken_stats(stat_type),
CombatStatType.Healing: lambda stat_type: game_stats.get_healing_stats( CombatStatType.Healing: lambda stat_type: game_stats.get_healing_stats(
stat_type) stat_type)
}[combat_stat_type](stat_type) }[combat_stat_type](stat_type)
@@ -185,8 +256,24 @@ def get_stats(stat_type: str, combat_stat_type: str):
return (cached_players, fame, time) return (cached_players, fame, time)
def economy_stats_for(stat_type: str):
_drain_events()
return game_stats.economy_stats(stat_type)
def item_stats_for(stat_type: str):
_drain_events()
return game_stats.item_stats(stat_type)
def silver_stats_for(stat_type: str):
_drain_events()
return game_stats.silver_stats(stat_type)
def queue_an_event(event): def queue_an_event(event):
event_queue.put(event) event_queue.put(event)
logger.debug("event received: %s", event.get(ev_consts.EvKeyName))
def reset_zone_stats(): def reset_zone_stats():
@@ -207,5 +294,8 @@ def is_ready():
def initialize(): def initialize():
initialization_result = backend_proxy.initialize() initialization_result = backend_proxy.initialize()
backend_proxy.subscribe(queue_an_event) if not backend_proxy.subscribe(queue_an_event):
logger.error("packet capture backend subscription failed")
if initialization_result == InitializationResult.Ok:
return InitializationResult.UnknownFailure
return initialization_result return initialization_result
+178 -2
View File
@@ -1,7 +1,184 @@
import faulthandler
import logging
import os import os
import signal
import sys
from typing import List, Optional
TEST_ENV_ENABLED = bool(os.getenv('TESTING')) TEST_ENV_ENABLED = bool(os.getenv('TESTING'))
# Verbose debugging flag, e.g. ``aostats --verbose``.
VERBOSE = bool(
os.getenv('AOSTATS_VERBOSE') or
'--verbose' in sys.argv or
'-v' in sys.argv
)
def _arg_value(name: str) -> Optional[str]:
prefix = name + '='
for i, arg in enumerate(sys.argv):
if arg.startswith(prefix):
return arg[len(prefix):]
if arg == name and i + 1 < len(sys.argv):
return sys.argv[i + 1]
return None
DISCOVERY_LOG_PATH = (
os.getenv('AOSTATS_LOG_PATH') or
_arg_value('--log-path')
)
REMEMBER_LAST_PARTY = bool(
os.getenv('AOSTATS_REMEMBER_LAST_PARTY') or
'--remember-last-party' in sys.argv
)
# Replay a captured discovery log instead of capturing live packets, e.g.
# ``aostats --replay /tmp/capture.jsonl``.
REPLAY_PATH = (
os.getenv('AOSTATS_REPLAY') or
_arg_value('--replay')
)
def _float_arg(name: str) -> Optional[float]:
value = _arg_value(name)
if value is None:
return None
try:
return float(value)
except ValueError:
return None
# Replay pacing: 0 means as fast as possible (default), 1.0 means real time
# (honour the timestamps in the log), N means N times faster than real time.
REPLAY_SPEED = _float_arg('--replay-speed') or 0.0
# When replaying, ``--replay-headless`` prints a summary and exits instead of
# opening the GUI.
REPLAY_HEADLESS = bool(
os.getenv('AOSTATS_REPLAY_HEADLESS') or
'--replay-headless' in sys.argv
)
_fault_file = None
def is_verbose():
return VERBOSE
def discovery_log_path():
return DISCOVERY_LOG_PATH
def remember_last_party():
return REMEMBER_LAST_PARTY
def replay_path() -> Optional[str]:
return REPLAY_PATH
def replay_speed() -> float:
return REPLAY_SPEED
def replay_headless() -> bool:
return REPLAY_HEADLESS
def app_log_path() -> Optional[str]:
if not DISCOVERY_LOG_PATH:
return None
return DISCOVERY_LOG_PATH + '.app.log'
def qt_args(argv: List[str]) -> List[str]:
"""Return argv with app-specific options removed before Qt sees them."""
result = []
skip_next = False
for arg in argv:
if skip_next:
skip_next = False
continue
if arg in ('--verbose', '-v'):
continue
if arg == '--log-path':
skip_next = True
continue
if arg.startswith('--log-path='):
continue
if arg == '--remember-last-party':
continue
if arg == '--replay' or arg == '--replay-speed':
skip_next = True
continue
if arg.startswith('--replay=') or arg.startswith('--replay-speed='):
continue
if arg == '--replay-headless':
continue
result.append(arg)
return result
def setup_logging():
"""Enable verbose logging for the app and the packet capture backend.
The Rust backend reads the ``BACKEND_LOG_LEVEL`` environment variable when
it initializes, so it must be set before ``initialize()`` is called.
"""
if not VERBOSE:
return
os.environ['BACKEND_LOG_LEVEL'] = 'debug'
handlers = [logging.StreamHandler()]
if DISCOVERY_LOG_PATH:
log_dir = os.path.dirname(DISCOVERY_LOG_PATH)
if log_dir:
os.makedirs(log_dir, exist_ok=True)
handlers.append(logging.FileHandler(app_log_path()))
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s %(levelname)-8s %(name)s: %(message)s',
datefmt='%H:%M:%S',
handlers=handlers)
_install_crash_diagnostics()
def _install_crash_diagnostics():
global _fault_file
log_path = app_log_path()
_fault_file = None
if log_path:
_fault_file = open(log_path, 'a')
faulthandler.enable(file=_fault_file, all_threads=True)
else:
faulthandler.enable(all_threads=True)
for sig_name in ('SIGSEGV', 'SIGABRT', 'SIGBUS', 'SIGFPE'):
sig = getattr(signal, sig_name, None)
if sig is None:
continue
try:
faulthandler.register(sig, file=_fault_file, all_threads=True,
chain=True)
except (RuntimeError, ValueError, OSError):
pass
def excepthook(exc_type, exc, tb):
logging.getLogger(__name__).critical(
"unhandled exception", exc_info=(exc_type, exc, tb))
sys.__excepthook__(exc_type, exc, tb)
sys.excepthook = excepthook
class TestType: class TestType:
Simple = 'simple' Simple = 'simple'
@@ -19,7 +196,6 @@ if TEST_ENV_ENABLED:
test_type = os.getenv('TESTING') test_type = os.getenv('TESTING')
if test_type not in _test_types: if test_type not in _test_types:
raise Exception('Unavailable GUI test type, avaliable values: {}'.format( raise Exception(f'Unavailable GUI test type: {test_type}, avaliable values: {",".join(_test_types.keys())}')
','.join(_test_types.keys())))
TEST_TYPE = _test_types[test_type.lower()] TEST_TYPE = _test_types[test_type.lower()]
+27
View File
@@ -44,6 +44,26 @@ class FameEventReceiver(EventReceiver):
pass pass
class EconomyEventReceiver(EventReceiver):
def on_event(self, event_name: str, value: dict):
if event_name == consts.EvNameSilverGained:
self.on_silver_gained(
value[consts.EvKeyValue], value[consts.EvKeySilverType])
elif event_name == consts.EvNameItemCollected:
self.on_item_collected(
value[consts.EvKeyItemId], value[consts.EvKeyItemName],
value[consts.EvKeyQuantity])
@abc.abstractmethod
def on_silver_gained(self, value: float, silver_type: str):
pass
@abc.abstractmethod
def on_item_collected(self, item_id: int, item_name: str, quantity: int):
pass
class CombatEventReceiver(EventReceiver): class CombatEventReceiver(EventReceiver):
def on_event(self, event_name: str, value: dict): def on_event(self, event_name: str, value: dict):
@@ -56,6 +76,9 @@ class CombatEventReceiver(EventReceiver):
elif event_name == consts.EvNameDamageDone: elif event_name == consts.EvNameDamageDone:
self.on_damage_done( self.on_damage_done(
value[consts.EvKeySource], value[consts.EvKeyValue]) value[consts.EvKeySource], value[consts.EvKeyValue])
elif event_name == consts.EvNameDamageTaken:
self.on_damage_taken(
value[consts.EvKeySource], value[consts.EvKeyValue])
elif event_name == consts.EvNameHealthReceived: elif event_name == consts.EvNameHealthReceived:
self.on_health_received( self.on_health_received(
value[consts.EvKeySource], value[consts.EvKeyTarget], value[consts.EvKeyValue]) value[consts.EvKeySource], value[consts.EvKeyTarget], value[consts.EvKeyValue])
@@ -75,6 +98,10 @@ class CombatEventReceiver(EventReceiver):
def on_damage_done(self, id: int, damage: float): def on_damage_done(self, id: int, damage: float):
pass pass
@abc.abstractmethod
def on_damage_taken(self, id: int, damage: float):
pass
@abc.abstractmethod @abc.abstractmethod
def on_health_received(self, id: int, target_id: int, health: float): def on_health_received(self, id: int, target_id: int, health: float):
pass pass
+130 -27
View File
@@ -1,18 +1,25 @@
import logging
import os import os
import platform import subprocess
import sys import sys
import requests import requests
from PySide2 import QtCore # type: ignore try:
from PySide2.QtCore import Qt # type: ignore import resource
from PySide2 import QtGui # type: ignore except ImportError: # pragma: no cover - Windows fallback
from PySide2.QtWidgets import QApplication # type: ignore resource = None
from PySide2.QtWidgets import QMessageBox # type: ignore
from PySide2.QtWidgets import QPushButton # type: ignore from PySide6 import QtCore # type: ignore
from PySide6.QtCore import Qt # type: ignore
from PySide6 import QtGui # type: ignore
from PySide6.QtWidgets import QApplication # type: ignore
from PySide6.QtWidgets import QMessageBox # type: ignore
from PySide6.QtWidgets import QPushButton # type: ignore
from ..engine import InitializationResult from ..engine import InitializationResult
from ..engine import initialize from ..engine import initialize
from ..utils.config import config from ..utils.config import config
from ..environment import is_verbose, qt_args, remember_last_party, replay_path, setup_logging
from .modules.main import MainWidget from .modules.main import MainWidget
from .styling import style from .styling import style
@@ -20,17 +27,62 @@ from ..utils.version import current_version as get_current_version
from ..utils.version import latest_version as get_latest_version from ..utils.version import latest_version as get_latest_version
from ..utils.assets import path from ..utils.assets import path
from ..utils.assets import scripts from ..utils.assets import scripts
from ..utils import platform_utils
from ..utils.platform_utils import capture_permissions_ok
sys.path.append(os.path.dirname(os.path.abspath('__file__'))) sys.path.append(os.path.dirname(os.path.abspath('__file__')))
logger = logging.getLogger(__name__)
def _qt_message_handler(mode, context, message):
logger.debug("qt message[%s] %s:%s %s", mode, context.file,
context.line, message)
def _install_heartbeat(app):
if not is_verbose():
return
timer = QtCore.QTimer(app)
def heartbeat():
rss_kb = (resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
if resource else None)
logger.debug("heartbeat pid=%s rss_kb=%s", os.getpid(), rss_kb)
timer.timeout.connect(heartbeat)
timer.start(10000)
app._aostats_heartbeat_timer = timer
def fix_network():
script_name = platform_utils.repair_script()
if not script_name:
sys.exit(0)
script_path = scripts(script_name)
if platform_utils.is_windows():
os.system(script_path)
else:
subprocess.call(['sh', script_path, sys.executable])
def fix_npcap():
os.system(scripts('fixnpcap.bat'))
sys.exit(0) sys.exit(0)
def run(): def run():
initialization_result = initialize() setup_logging()
app_argv = qt_args(sys.argv)
logger.info("Albion Online Stats v%s starting", get_current_version())
logger.debug("pid: %s", os.getpid())
logger.debug("argv: %s", sys.argv)
logger.debug("remember_last_party: %s", remember_last_party())
logger.debug("python: %s (%s)", sys.executable, sys.version)
logger.debug("platform: %s", platform_utils.system())
replaying = bool(replay_path())
conf = config() conf = config()
window_config = conf['window'] window_config = conf['window']
@@ -38,19 +90,29 @@ def run():
WIDTH = window_config['width'] WIDTH = window_config['width']
HEIGHT = window_config['height'] HEIGHT = window_config['height']
app = QApplication(sys.argv) app = QApplication(app_argv)
QtCore.qInstallMessageHandler(_qt_message_handler)
_install_heartbeat(app)
perms_ok = True
if platform_utils.is_linux() and not replaying:
perms_ok = capture_permissions_ok()
logger.debug("capture permissions probe: %s", perms_ok)
initialization_result = initialize()
logger.debug("backend initialization result: %s", initialization_result)
app.setStyleSheet(style) app.setStyleSheet(style)
geometry = app.screens()[0].size()
clipboard = app.clipboard() clipboard = app.clipboard()
widget = MainWidget(clipboard) widget = MainWidget(clipboard)
widget.setWindowOpacity(window_config['opacity']) widget.setWindowOpacity(window_config['opacity'])
widget.resize(WIDTH, HEIGHT)
widget.move(0, geometry.height() - HEIGHT - 280)
widget.setWindowTitle('Albion Online Stats') title = 'Albion Online Stats'
if replaying:
title += ' (replay)'
widget.setWindowTitle(title)
widget.setWindowIcon(QtGui.QIcon(path('albion-stats-icon.png'))) widget.setWindowIcon(QtGui.QIcon(path('albion-stats-icon.png')))
if window_config['always_on_top']: if window_config['always_on_top']:
@@ -58,7 +120,11 @@ def run():
if window_config['frameless']: if window_config['frameless']:
widget.setWindowFlag(Qt.FramelessWindowHint) widget.setWindowFlag(Qt.FramelessWindowHint)
widget.show() if window_config.get('fullscreen', True):
widget.showMaximized()
else:
widget.resize(WIDTH, HEIGHT)
widget.show()
current_version, latest_version = ( current_version, latest_version = (
get_current_version(), get_latest_version()) get_current_version(), get_latest_version())
@@ -73,21 +139,58 @@ def run():
msg.setStandardButtons(QMessageBox.Ok) msg.setStandardButtons(QMessageBox.Ok)
msg.show() msg.show()
if initialization_result == InitializationResult.NetworkInterfaceListMissing: need_capture_fix = not replaying and (
initialization_result != InitializationResult.Ok
or (platform_utils.is_linux() and not perms_ok)
)
if need_capture_fix:
msg = QMessageBox() msg = QMessageBox()
msg.setIcon(QMessageBox.Critical) msg.setIcon(QMessageBox.Critical)
msg.setWindowTitle("Unable to track network traffic data!") msg.setWindowTitle("Unable to track network traffic data!")
msg.setText(
"On windows make sure that WinPcap is installed in your system.")
msg.setInformativeText("WinPcap can be installed from <a href='{}'>here</a> <br>\
<b>Make sure to install with the \"Install Npcap in WinPcap API-compatible Mode\"<b> option<br><br>\
In case where npcap is installed try to fix npcap and restart the app"
.format('https://nmap.org/npcap/dist/npcap-0.9990.exe'))
msg.setStandardButtons(QMessageBox.Ok)
button = QPushButton("Fix npcap")
button.clicked.connect(fix_npcap) if initialization_result == InitializationResult.BackendNotInstalled:
msg.addButton(button, QMessageBox.NoRole) msg.setText(
"The packet capture backend (pyaoaddons) is not installed.")
msg.setInformativeText(
"pyaoaddons 0.2.8 ships prebuilt wheels only for CPython 3.6-3.10.<br>\
Use one of those Python versions and reinstall the app \
(<code>python -m pip install .</code>), or build pyaoaddons from source.<br><br>\
See the README for details.")
msg.setStandardButtons(QMessageBox.Ok)
elif platform_utils.is_windows():
msg.setText(
"On Windows make sure that Npcap is installed in your system.")
msg.setInformativeText("Npcap can be installed from <a href='{}'>here</a> <br>\
<b>Make sure to install with the \"Install Npcap in WinPcap API-compatible Mode\"</b> option<br><br>\
In case where npcap is installed try to fix npcap and restart the app"
.format('https://nmap.org/npcap/dist/npcap-0.9990.exe'))
msg.setStandardButtons(QMessageBox.Ok)
button = QPushButton("Fix npcap")
button.clicked.connect(fix_network)
msg.addButton(button, QMessageBox.NoRole)
else:
permissions_missing = platform_utils.is_linux() and not perms_ok
if permissions_missing:
msg.setText(
"The app does not have permission to capture network packets.")
msg.setInformativeText(
"Capturing packets requires elevated privileges. Use the button below \
to grant the Python interpreter the needed capabilities \
(or run the app with <code>sudo</code>).")
else:
msg.setText(
"Make sure that libpcap is installed and network interfaces are available.")
msg.setInformativeText(
"Install libpcap:<br>\
<b>Debian/Ubuntu:</b> <code>sudo apt install libpcap0.8</code><br>\
<b>Fedora:</b> <code>sudo dnf install libpcap</code><br>\
<b>Arch:</b> <code>sudo pacman -S libpcap</code>")
msg.setStandardButtons(QMessageBox.Ok)
if platform_utils.repair_script():
button = QPushButton("Fix capture permissions")
button.clicked.connect(fix_network)
msg.addButton(button, QMessageBox.NoRole)
msg.show() msg.show()
sys.exit(app.exec_()) sys.exit(app.exec_())
+1 -1
View File
@@ -1,4 +1,4 @@
from PySide2.QtWidgets import QMessageBox # noqa type: ignore from PySide6.QtWidgets import QMessageBox # noqa type: ignore
from ...utils.version import get_version from ...utils.version import get_version
+499 -103
View File
@@ -1,143 +1,539 @@
import sys
import functools import functools
import sys
from PySide2 import QtGui # type: ignore from PySide6 import QtGui # type: ignore
from PySide2.QtCore import Qt # type: ignore from PySide6.QtCore import Qt # type: ignore
from PySide2.QtCore import QTimer # type: ignore from PySide6.QtCore import QTimer # type: ignore
from PySide2.QtWidgets import QComboBox # type: ignore from PySide6.QtWidgets import QButtonGroup # type: ignore
from PySide2.QtWidgets import QHBoxLayout # type: ignore from PySide6.QtWidgets import QFrame # type: ignore
from PySide2.QtWidgets import QPushButton # type: ignore from PySide6.QtWidgets import QGridLayout # type: ignore
from PySide2.QtWidgets import QVBoxLayout # type: ignore from PySide6.QtWidgets import QHBoxLayout # type: ignore
from PySide2.QtWidgets import QWidget # type: ignore from PySide6.QtWidgets import QLabel # type: ignore
from PySide6.QtWidgets import QPushButton # type: ignore
from PySide6.QtWidgets import QScrollArea # type: ignore
from PySide6.QtWidgets import QVBoxLayout # type: ignore
from PySide6.QtWidgets import QWidget # type: ignore
from ... import engine from ... import engine
from ...utils import assets from ...utils import assets
from ...utils.config import config from ...utils.config import config
from ...utils.number import Number
from .view_type import ViewType
from .views import ModeBasedListView
from .views import StatsType
from . import about from . import about
from .view_type import ViewType
from .views import StatsType
from .views.list_view import ListItemView
class AboutButton(QPushButton): class Page:
def __init__(self): Overview = 'overview'
QPushButton.__init__(self) Damage = 'damage'
DamageTaken = 'damage_taken'
self.about = about.About() Healing = 'healing'
self.setIcon(QtGui.QIcon(assets.path('about.png'))) Economy = 'economy'
self.setToolTip("About") Items = 'items'
self.clicked.connect(self.about.show) Settings = 'settings'
class CloseButton(QPushButton): PAGE_LABELS = {
def __init__(self, is_visible): Page.Overview: ('O', 'Overview'),
QPushButton.__init__(self) Page.Damage: ('D', 'Damage Done'),
Page.DamageTaken: ('T', 'Damage Taken'),
self.setIcon(QtGui.QIcon(assets.path('close.png'))) Page.Healing: ('H', 'Healing Done'),
self.setToolTip("Close") Page.Economy: ('$', 'Economy'),
self.clicked.connect(self.close) Page.Items: ('I', 'Items Collected'),
if not is_visible: Page.Settings: ('S', 'Settings'),
self.hide() }
def close(self):
sys.exit(0)
class ViewTypeWidget(QComboBox): SCOPE_LABELS = {
def __init__(self): StatsType.ZONE: 'Current Zone',
QComboBox.__init__(self) StatsType.LAST_FIGHT: 'Last Fight',
self.addItem(ViewType.DMG) StatsType.OVERALL: 'Overall Session',
self.addItem(ViewType.HEALING_DONE) }
def get_view_type(self):
return self.currentText()
class TopBar(QWidget): class Sidebar(QWidget):
def __init__(self, on_page_changed, on_scope_changed):
QWidget.__init__(self)
self.setObjectName('Sidebar')
self.expanded = True
self.on_page_changed = on_page_changed
self.on_scope_changed = on_scope_changed
self.page_buttons = {}
self.scope_buttons = {}
self.layout = QVBoxLayout()
self.layout.setContentsMargins(14, 14, 14, 14)
self.layout.setSpacing(8)
self.toggle_button = QPushButton('Collapse')
self.toggle_button.setObjectName('SidebarToggle')
self.toggle_button.clicked.connect(self.toggle)
self.layout.addWidget(self.toggle_button)
self.title = QLabel('AO Stats')
self.title.setObjectName('SidebarTitle')
self.layout.addWidget(self.title)
self.page_group = QButtonGroup(self)
self.page_group.setExclusive(True)
for page, (_short, label) in PAGE_LABELS.items():
button = QPushButton(label)
button.setCheckable(True)
button.clicked.connect(functools.partial(self._select_page, page))
self.page_group.addButton(button)
self.page_buttons[page] = button
self.layout.addWidget(button)
self.scope_label = QLabel('Scope')
self.scope_label.setObjectName('SidebarSection')
self.layout.addWidget(self.scope_label)
self.scope_group = QButtonGroup(self)
self.scope_group.setExclusive(True)
for scope, label in SCOPE_LABELS.items():
button = QPushButton(label)
button.setCheckable(True)
button.clicked.connect(functools.partial(self._select_scope, scope))
self.scope_group.addButton(button)
self.scope_buttons[scope] = button
self.layout.addWidget(button)
self.layout.addStretch(1)
self.setLayout(self.layout)
def set_initial(self, page, scope):
self.page_buttons[page].setChecked(True)
self.scope_buttons[scope].setChecked(True)
def _select_page(self, page):
self.on_page_changed(page)
def _select_scope(self, scope):
self.on_scope_changed(scope)
def toggle(self):
self.expanded = not self.expanded
self.setFixedWidth(220 if self.expanded else 72)
self.toggle_button.setText('Collapse' if self.expanded else '>>')
self.title.setVisible(self.expanded)
self.scope_label.setVisible(self.expanded)
for page, button in self.page_buttons.items():
short, label = PAGE_LABELS[page]
button.setText(label if self.expanded else short)
for scope, button in self.scope_buttons.items():
button.setText(SCOPE_LABELS[scope] if self.expanded else scope[:1])
class StatCard(QFrame):
def __init__(self, title):
QFrame.__init__(self)
self.setObjectName('StatCard')
self.layout = QVBoxLayout()
self.layout.setContentsMargins(16, 12, 16, 12)
self.title = QLabel(title)
self.title.setObjectName('CardTitle')
self.value = QLabel('0')
self.value.setObjectName('CardValue')
self.layout.addWidget(self.title)
self.layout.addWidget(self.value)
self.setLayout(self.layout)
def update_value(self, value):
_set_text(self.value, str(value))
class HeaderBar(QWidget):
def __init__(self): def __init__(self):
QWidget.__init__(self) QWidget.__init__(self)
self.view_type = ViewTypeWidget()
self.layout = QHBoxLayout() self.layout = QHBoxLayout()
self.layout.setSpacing(0) self.layout.setContentsMargins(0, 0, 0, 0)
self.layout.setMargin(0) self.title = QLabel('Albion Online Stats')
self.layout.addWidget(self.view_type) self.title.setObjectName('HeaderTitle')
self.status = QLabel('Waiting for zone change')
self.status.setObjectName('HeaderStatus')
self.layout.addWidget(self.title)
self.layout.addStretch(1)
self.layout.addWidget(self.status)
self.setLayout(self.layout)
self.about_button = AboutButton() def update_status(self):
self.layout.addWidget(self.about_button) if engine.is_ready():
_set_text(self.status, 'Tracking live Albion Online traffic')
else:
_set_text(
self.status,
'Waiting for zone change to identify your character')
self.close_button = CloseButton(config()['window']['frameless'])
self.layout.addWidget(self.close_button)
class ItemsPanel(QFrame):
def __init__(self):
QFrame.__init__(self)
self.setObjectName('ItemsPanel')
self.layout = QVBoxLayout()
self.layout.setContentsMargins(16, 16, 16, 16)
title = QLabel('Items Collected')
title.setObjectName('PanelTitle')
self.layout.addWidget(title)
self.list = PlainStatsListView()
self.layout.addWidget(self.list, 1)
self.layout.addStretch(1)
self.setLayout(self.layout)
def update(self, items):
self.list.update(items)
class PlainStatsListView(QLabel):
def __init__(self):
QLabel.__init__(self)
self._last_text = None
self.setObjectName('MutedText')
self.setAlignment(Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignLeft)
self.setWordWrap(True)
def update(self, items):
if not items:
text = 'No entries yet.'
else:
text = '\n'.join(
f'{item.name} {item.value} ({item.percentage}%)'
for item in items)
if text == self._last_text:
return
self._last_text = text
self.setText(text)
class SettingsPanel(QWidget):
def __init__(self, clipboard):
QWidget.__init__(self)
self.clipboard = clipboard
self.about = about.About()
self.layout = QVBoxLayout()
self.layout.setSpacing(12)
description = QLabel(
'Use this page for session actions. Fullscreen dashboard mode is the default; '
'set window.fullscreen = false in the config file to use a normal window.')
description.setWordWrap(True)
description.setObjectName('PageDescription')
self.layout.addWidget(description)
reset_zone = QPushButton('Reset Current Zone')
reset_zone.clicked.connect(engine.reset_zone_stats)
self.layout.addWidget(reset_zone)
reset_fight = QPushButton('Reset Last Fight')
reset_fight.clicked.connect(engine.reset_last_fight_stats)
self.layout.addWidget(reset_fight)
reset_all = QPushButton('Reset Overall Session')
reset_all.clicked.connect(engine.reset_stats)
self.layout.addWidget(reset_all)
about_button = QPushButton('About Albion Online Stats')
about_button.clicked.connect(self.about.show)
self.layout.addWidget(about_button)
if not config()['window']['fullscreen']:
close_button = QPushButton('Close')
close_button.setIcon(QtGui.QIcon(assets.path('close.png')))
close_button.clicked.connect(lambda: sys.exit(0))
self.layout.addWidget(close_button)
self.layout.addStretch(1)
self.setLayout(self.layout) self.setLayout(self.layout)
class MainWidget(QWidget): class MainWidget(QWidget):
def __init__(self, clipboard): def __init__(self, clipboard):
QWidget.__init__(self) QWidget.__init__(self)
self.clipboard = clipboard
self.current_page = Page.Overview
self.current_scope = StatsType.ZONE
self._layout_key = None
self._last_snapshot = None
self.mouse_pos = None self.root_layout = QHBoxLayout()
self.root_layout.setContentsMargins(0, 0, 0, 0)
self.root_layout.setSpacing(0)
self.layout = QVBoxLayout() self.sidebar = Sidebar(self.set_page, self.set_scope)
self.top_bar = TopBar() self.sidebar.set_initial(self.current_page, self.current_scope)
self.layout.addWidget(self.top_bar) self.root_layout.addWidget(self.sidebar)
self.view = ModeBasedListView(clipboard) self.main_area = QWidget()
self.layout.addWidget(self.view) self.main_layout = QVBoxLayout()
self.main_layout.setContentsMargins(22, 18, 22, 18)
self.main_layout.setSpacing(14)
self.main_area.setLayout(self.main_layout)
self.header = HeaderBar()
self.main_layout.addWidget(self.header)
self.cards_layout = QGridLayout()
self.cards_layout.setSpacing(12)
self.elapsed_card = StatCard('Time in selected scope')
self.fame_card = StatCard('Fame gained')
self.fph_card = StatCard('Fame per hour')
self.ready_card = StatCard('Tracking status')
self.cards_layout.addWidget(self.elapsed_card, 0, 0)
self.cards_layout.addWidget(self.fame_card, 0, 1)
self.cards_layout.addWidget(self.fph_card, 0, 2)
self.cards_layout.addWidget(self.ready_card, 0, 3)
self.main_layout.addLayout(self.cards_layout)
self.page_title = QLabel('Overview')
self.page_title.setObjectName('PageTitle')
self.page_description = QLabel('')
self.page_description.setObjectName('PageDescription')
self.page_description.setWordWrap(True)
self.main_layout.addWidget(self.page_title)
self.main_layout.addWidget(self.page_description)
self.primary_label = QLabel('')
self.primary_label.setObjectName('PanelTitle')
self.main_layout.addWidget(self.primary_label)
self.primary_list = ListItemView()
self.main_layout.addWidget(self.primary_list, 1)
self.plain_list = PlainStatsListView()
self.main_layout.addWidget(self.plain_list, 1)
self.total_healing_label = QLabel('Total Healing')
self.total_healing_label.setObjectName('PanelTitle')
self.total_healing_list = ListItemView()
self.main_layout.addWidget(self.total_healing_label)
self.main_layout.addWidget(self.total_healing_list, 1)
self.damage_taken_list = ListItemView(show_per_second=False)
self.main_layout.addWidget(self.damage_taken_list, 1)
self.damage_taken_total_label = QLabel('')
self.damage_taken_total_label.setObjectName('PanelTitle')
self.main_layout.addWidget(self.damage_taken_total_label)
self.placeholder = QLabel('')
self.placeholder.setObjectName('MutedText')
self.placeholder.setWordWrap(True)
self.main_layout.addWidget(self.placeholder, 1)
self.settings_panel = SettingsPanel(clipboard)
self.main_layout.addWidget(self.settings_panel, 1)
self.root_layout.addWidget(self.main_area, 1)
self.items_panel = ItemsPanel()
self.root_layout.addWidget(self.items_panel)
self.setLayout(self.root_layout)
self.setLayout(self.layout)
self.refresh() self.refresh()
timer = QTimer(self) timer = QTimer(self)
timer.timeout.connect(self.refresh) timer.timeout.connect(self.refresh)
timer.start(500) timer.start(1000)
def set_page(self, page):
self.current_page = page
self.refresh()
def set_scope(self, scope):
self.current_scope = scope
self.refresh()
def refresh(self): def refresh(self):
player_list_items, fame_stat, elapsed = self.damage_stats() players, fame_stat, elapsed = self.primary_stats()
self.view.update( total_healing = self.total_healing_stats()
self.top_bar.view_type.get_view_type(), silver = self.silver_stats()
elapsed, items = self.item_stats()
fame_stat.fame,
fame_stat.fame_per_hour, snapshot = self._snapshot(
player_list_items players, total_healing, silver, items, fame_stat, elapsed)
if snapshot == self._last_snapshot:
return
self._last_snapshot = snapshot
self.header.update_status()
self.elapsed_card.update_value(self._format_time(elapsed))
self.fame_card.update_value(fame_stat.fame)
self.fph_card.update_value(fame_stat.fame_per_hour)
self.ready_card.update_value('Ready' if engine.is_ready() else 'Not ready')
self.items_panel.update(items)
self._ensure_page_layout()
self._update_page_data(players, total_healing, silver, items)
def _snapshot(self, players, total_healing, silver, items, fame_stat, elapsed):
return (
self.current_page,
self.current_scope,
engine.is_ready(),
self._format_time(elapsed),
str(fame_stat.fame),
str(fame_stat.fame_per_hour),
_list_signature(players),
_list_signature(total_healing),
_list_signature(silver),
_list_signature(items),
) )
def mousePressEvent(self, event): def primary_stats(self):
self.mouse_pos = event.pos() stat_kind = {
Page.Overview: engine.CombatStatType.Damage,
def mouseMoveEvent(self, event): Page.Damage: engine.CombatStatType.Damage,
invalid_regions = ( Page.DamageTaken: engine.CombatStatType.DamageTaken,
self.top_bar.geometry(), Page.Healing: engine.CombatStatType.Healing,
self.view.geometry(), Page.Economy: engine.CombatStatType.Damage,
) Page.Items: engine.CombatStatType.Damage,
Page.Settings: engine.CombatStatType.Damage,
if any(region.contains(event.pos()) for region in invalid_regions): }[self.current_page]
return getters = {
if not self.mouse_pos: StatsType.ZONE: functools.partial(engine.zone_stats, stat_kind),
return StatsType.LAST_FIGHT: functools.partial(engine.last_fight_stats, stat_kind),
if any(region.contains(self.mouse_pos) for region in invalid_regions): StatsType.OVERALL: functools.partial(engine.overall_stats, stat_kind),
return
if event.buttons() & Qt.LeftButton:
diff = event.pos() - self.mouse_pos
newpos = self.pos() + diff
self.move(newpos)
def damage_stats(self):
stats = {
ViewType.DMG: {
StatsType.ZONE: functools.partial(engine.zone_stats, engine.CombatStatType.Damage),
StatsType.LAST_FIGHT: functools.partial(engine.last_fight_stats, engine.CombatStatType.Damage),
StatsType.OVERALL: functools.partial(engine.overall_stats, engine.CombatStatType.Damage),
},
ViewType.HEALING_DONE: {
StatsType.ZONE: functools.partial(engine.zone_stats, engine.CombatStatType.Healing),
StatsType.LAST_FIGHT: functools.partial(engine.last_fight_stats, engine.CombatStatType.Healing),
StatsType.OVERALL: functools.partial(engine.overall_stats, engine.CombatStatType.Healing),
}
} }
return getters[self.current_scope]()
return stats[self.top_bar.view_type.get_view_type()][self.view.get_mode()]() def total_healing_stats(self):
getters = {
StatsType.ZONE: engine.zone_total_healing_stats,
StatsType.LAST_FIGHT: engine.last_fight_total_healing_stats,
StatsType.OVERALL: engine.overall_total_healing_stats,
}
return getters[self.current_scope]()
def silver_stats(self):
getters = {
StatsType.ZONE: functools.partial(engine.silver_stats_for, engine.VisibilityType.Zone),
StatsType.LAST_FIGHT: functools.partial(engine.silver_stats_for, engine.VisibilityType.LastFight),
StatsType.OVERALL: functools.partial(engine.silver_stats_for, engine.VisibilityType.Overall),
}
return getters[self.current_scope]()
def item_stats(self):
getters = {
StatsType.ZONE: functools.partial(engine.item_stats_for, engine.VisibilityType.Zone),
StatsType.LAST_FIGHT: functools.partial(engine.item_stats_for, engine.VisibilityType.LastFight),
StatsType.OVERALL: functools.partial(engine.item_stats_for, engine.VisibilityType.Overall),
}
return getters[self.current_scope]()
def _ensure_page_layout(self):
layout_key = (self.current_page, self.current_scope)
if layout_key == self._layout_key:
return
self._layout_key = layout_key
_set_visible(self.primary_list, False)
_set_visible(self.plain_list, False)
_set_visible(self.primary_label, False)
_set_visible(self.total_healing_label, False)
_set_visible(self.total_healing_list, False)
_set_visible(self.damage_taken_list, False)
_set_visible(self.damage_taken_total_label, False)
_set_visible(self.placeholder, False)
_set_visible(self.settings_panel, False)
if self.current_page == Page.Overview:
_set_text(self.page_title, 'Overview')
_set_text(self.page_description,
'A quick session summary for the selected scope. Use the left menu to inspect damage, healing, economy, and loot in more detail.')
_set_text(self.primary_label, 'Top Damage Dealers')
_set_visible(self.primary_label, True)
_set_visible(self.primary_list, True)
return
if self.current_page == Page.Damage:
_set_text(self.page_title, 'Damage Done')
_set_text(self.page_description,
'Damage attributed to each visible tracked player during the selected scope. DPS is based on combat time.')
_set_text(self.primary_label, 'Damage by Player')
_set_visible(self.primary_label, True)
_set_visible(self.primary_list, True)
return
if self.current_page == Page.DamageTaken:
_set_text(self.page_title, 'Damage Taken')
_set_text(self.page_description,
'Damage taken by each visible tracked player during the selected scope. Includes damage from mobs and other players.')
_set_text(self.primary_label, 'Damage Taken by Player')
_set_visible(self.primary_label, True)
_set_visible(self.damage_taken_list, True)
_set_visible(self.damage_taken_total_label, True)
return
if self.current_page == Page.Healing:
_set_text(self.page_title, 'Healing Done')
_set_text(self.page_description,
'Combat healing counts healing during fights. Total healing includes self-healing and post-fight recovery.')
_set_text(self.primary_label, 'Combat Healing')
_set_visible(self.primary_label, True)
_set_visible(self.primary_list, True)
_set_visible(self.total_healing_label, True)
_set_visible(self.total_healing_list, True)
return
if self.current_page == Page.Economy:
_set_text(self.page_title, 'Economy')
_set_text(self.page_description,
'Silver tracking is active with conservative packet filters. Looted Silver and Other Silver are separated for validation against your next capture.')
_set_text(self.primary_label, 'Silver Gained')
_set_visible(self.primary_label, True)
_set_visible(self.plain_list, True)
return
if self.current_page == Page.Items:
_set_text(self.page_title, 'Items Collected')
_set_text(self.page_description,
'Collected item quantities from item pickup packets. The right panel shows selected-scope item totals on every page.')
_set_text(self.primary_label, 'Items by Quantity')
_set_visible(self.primary_label, True)
_set_visible(self.plain_list, True)
return
_set_text(self.page_title, 'Settings')
_set_text(self.page_description,
'Reset scopes, view app information, and configure dashboard behavior.')
_set_visible(self.settings_panel, True)
def _update_page_data(self, players, total_healing, silver, items):
if self.current_page in (Page.Overview, Page.Damage):
self.primary_list.update(players)
elif self.current_page == Page.DamageTaken:
self.damage_taken_list.update(players)
total = sum(player.value.number for player in players)
self.damage_taken_total_label.setText(
'Party Total: {}'.format(Number(total)))
elif self.current_page == Page.Healing:
self.primary_list.update(players)
self.total_healing_list.update(total_healing)
elif self.current_page == Page.Economy:
self.plain_list.update(silver)
elif self.current_page == Page.Items:
self.plain_list.update(items)
def _format_time(self, seconds):
seconds = int(seconds or 0)
hours = seconds // 3600
minutes = (seconds % 3600) // 60
remainder = seconds % 60
if hours:
return f'{hours}h {minutes}m {remainder}s'
return f'{minutes}m {remainder}s'
def _set_text(widget, text):
if widget.text() != text:
widget.setText(text)
def _set_visible(widget, visible):
if widget.isVisible() != visible:
widget.setVisible(visible)
def _list_signature(items):
return tuple(
(item.name, str(item.value), str(item.value_per_second),
str(item.percentage), item.combat_state)
for item in items)
+2 -2
View File
@@ -1,6 +1,6 @@
from PySide2.QtWidgets import QPushButton # type: ignore from PySide6.QtWidgets import QPushButton # type: ignore
from PySide2 import QtGui # type: ignore from PySide6 import QtGui # type: ignore
from ....utils import assets from ....utils import assets
from ....stats.list_item import PlayerListItem from ....stats.list_item import PlayerListItem
+6 -1
View File
@@ -1,6 +1,6 @@
from io import BytesIO from io import BytesIO
from PIL import Image, ImageQt # type: ignore from PIL import Image, ImageQt # type: ignore
from PySide2 import QtGui # type: ignore from PySide6 import QtGui # type: ignore
from .....utils import async_request from .....utils import async_request
@@ -11,6 +11,9 @@ icon_cache = {}
def get_weapon_icon(weapon): def get_weapon_icon(weapon):
global icon_cache global icon_cache
if not weapon:
return None
url = f'https://albiononline2d.ams3.cdn.digitaloceanspaces.com/thumbnails/orig/{weapon}' url = f'https://albiononline2d.ams3.cdn.digitaloceanspaces.com/thumbnails/orig/{weapon}'
if weapon in icon_cache: if weapon in icon_cache:
@@ -18,6 +21,8 @@ def get_weapon_icon(weapon):
try: try:
r = async_request.get(url) r = async_request.get(url)
if r is None or not r.ok:
return None
img = Image.open(BytesIO(r.content)) img = Image.open(BytesIO(r.content))
img_qt = ImageQt.ImageQt(img) img_qt = ImageQt.ImageQt(img)
+39 -156
View File
@@ -1,168 +1,51 @@
import collections
import functools
import re
from typing import List from typing import List
from PySide2 import QtCore # type: ignore from PySide6.QtCore import Qt # type: ignore
from PySide2 import QtGui # type: ignore from PySide6.QtWidgets import QLabel # type: ignore
from PySide2.QtCore import Qt # type: ignore
from PySide2.QtGui import QStandardItem # type: ignore
from PySide2.QtGui import QStandardItemModel # type: ignore
from PySide2.QtWidgets import QApplication # type: ignore
from PySide2.QtWidgets import QComboBox # type: ignore
from PySide2.QtWidgets import QHBoxLayout # type: ignore
from PySide2.QtWidgets import QLabel # type: ignore
from PySide2.QtWidgets import QListView # type: ignore
from PySide2.QtWidgets import QMessageBox # type: ignore
from PySide2.QtWidgets import QProgressBar # type: ignore
from PySide2.QtWidgets import QPushButton # type: ignore
from PySide2.QtWidgets import QVBoxLayout # type: ignore
from .....stats.list_item import PlayerListItem from .....stats.list_item import PlayerListItem
from .....utils import assets
from .....utils import names
from .....utils import weapon
from .icon import get_weapon_icon as player_icon
Style = collections.namedtuple('Style', ['bg', 'fg'])
enchant_re = re.compile(r"(.*)@(\d+)")
def map_name(name): class ListItemView(QLabel):
def __init__(self, show_per_second: bool = True):
match = enchant_re.match(name) QLabel.__init__(self)
if match: self._show_per_second = show_per_second
return names.map_name(match[1]) self._last_signature = None
self._players: List[PlayerListItem] = []
return names.map_name(name) self.setAlignment(Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignLeft)
self.setWordWrap(True)
self.setText('No entries yet.')
def player_style(items):
weapon_type = weapon.get_weapon_type(items)
if weapon_type == weapon.WeaponType.Arcane:
return Style(bg='#f032e6', fg='#ffffff')
elif weapon_type == weapon.WeaponType.Axe:
return Style(bg='#800000', fg='#7fffff')
elif weapon_type == weapon.WeaponType.Bow:
return Style(bg='#469990', fg='#ED9247')
elif weapon_type == weapon.WeaponType.Crossbow:
return Style(bg='#000075', fg='#ffff8a')
elif weapon_type == weapon.WeaponType.Curse:
return Style(bg='#911eb4', fg='#6ee14b')
elif weapon_type == weapon.WeaponType.Dagger:
return Style(bg='#4d5f20', fg='#ffffff')
elif weapon_type == weapon.WeaponType.Fire:
return Style(bg='#e6194B', fg='#4763ED')
elif weapon_type == weapon.WeaponType.Frost:
return Style(bg='#4363d8', fg='#eeeeee')
elif weapon_type == weapon.WeaponType.Hammer:
return Style(bg='#9A6324', fg='#2FEAED')
elif weapon_type == weapon.WeaponType.Holy:
return Style(bg='#42d4f4', fg='#bd2b0b')
elif weapon_type == weapon.WeaponType.Mace:
return Style(bg='#808000', fg='#2FEAED')
elif weapon_type == weapon.WeaponType.Nature:
return Style(bg='#3cb44b', fg='#EDC647')
elif weapon_type == weapon.WeaponType.Quarterstaff:
return Style(bg='#f58231', fg='#0a7dce')
elif weapon_type == weapon.WeaponType.Spear:
return Style(bg='#a9a9a9', fg='#18ED54')
elif weapon_type == weapon.WeaponType.Sword:
return Style(bg='#b59d00', fg='#4a62ff')
else:
return Style(bg='#42413c', fg='#bdbec3')
class ListItemView(QListView):
class Item(QtGui.QStandardItem):
def __init__(self, player, parent):
QtGui.QStandardItem .__init__(self)
self.parent = parent
self.player = player
self.update(player)
self.setFlags(self.flags() & ~Qt.ItemIsSelectable)
self.setTextAlignment(
QtCore.Qt.AlignmentFlag.AlignHCenter | QtCore.Qt.AlignmentFlag.AlignVCenter)
def update(self, player):
self.player = player
self.setText("{} {} ({}, {}%)".format(
self.player.name, self.player.value, self.player.value_per_second, self.player.percentage
))
self.refresh()
def refresh(self):
value = round(self.player.value / self.player.best_value, 2)
QRectF = QtCore.QRectF(self.parent.rect())
gradient = QtGui.QLinearGradient(
QRectF.topLeft(), QRectF.topRight())
gradient.setColorAt(value-0.001 if value > 0 else 0,
QtGui.QColor(player_style(self.player.items).bg))
gradient.setColorAt(value, QtGui.QColor('#000000'))
gradient.setColorAt(value+0.001 if value <
1 else 1, QtGui.QColor('#000000'))
brush = QtGui.QBrush(gradient)
self.setBackground(brush)
brush_fg = QtGui.QBrush(QtGui.QColor(
player_style(self.player.items).fg))
self.setForeground(brush_fg)
icon = player_icon(self.player.items['weapon'])
self.setToolTip('\n'.join(
[f'{k}: {map_name(v)}' for (k, v) in self.player.items.items() if v]))
if icon:
self.setIcon(icon)
class SortProxyModel(QtCore.QSortFilterProxyModel):
def lessThan(self, left, right):
l = self.sourceModel().item(left.row())
r = self.sourceModel().item(right.row())
return l.player.percentage < r.player.percentage
class ItemModel(QStandardItemModel):
def __init__(self, view):
QStandardItemModel .__init__(self, view)
def __init__(self):
QListView .__init__(self)
self.setIconSize(QtCore.QSize(20, 20))
self.model = self.ItemModel(self)
self.proxy = self.SortProxyModel()
self.proxy.setSourceModel(self.model)
self.setModel(self.proxy)
def update(self, players: List[PlayerListItem]): def update(self, players: List[PlayerListItem]):
if not players: sorted_players = sorted(players, key=lambda p: p.value, reverse=True)
self.model.clear() signature = tuple(_player_signature(p) for p in sorted_players)
if signature == self._last_signature:
return return
self._last_signature = signature
self._players = sorted_players
visible_names = [] if not sorted_players:
for player in players: self.setText('No entries yet.')
items = (self.model.item(i) for i in range(self.model.rowCount())) return
found = next( self.setText('\n'.join(_player_line(p, self._show_per_second) for p in sorted_players))
(i for i in items if i.player.name == player.name), None)
if found:
found.update(player)
else:
self.model.appendRow(self.Item(player, self))
visible_names.append(player.name)
for i in range(self.model.rowCount()):
item = self.model.item(i)
if hasattr(item, 'player') and hasattr(item.player, 'name') and item.player.name not in visible_names:
self.model.removeRow(i)
self.proxy.sort(0, QtCore.Qt.DescendingOrder)
def get_player_list_items(self) -> List[PlayerListItem]: def get_player_list_items(self) -> List[PlayerListItem]:
return sorted( return list(self._players)
[self.model.item(i).player for i in range(self.model.rowCount())],
key=lambda i: i.value,
reverse=True) def _player_signature(player: PlayerListItem):
return (
player.name,
str(player.value),
str(player.value_per_second),
str(player.percentage),
player.combat_state,
)
def _player_line(player: PlayerListItem, show_per_second: bool = True):
if show_per_second:
return "{} {} ({}, {}%)".format(
player.name, player.value, player.value_per_second, player.percentage)
return "{} {} ({}%)".format(
player.name, player.value, player.percentage)
+28 -8
View File
@@ -1,14 +1,16 @@
# from PySide2.QtCore import QTimer # from PySide6.QtCore import QTimer
# from PySide2.QtCore import Qt # from PySide6.QtCore import Qt
from typing import Callable from typing import Callable
from PySide2.QtWidgets import QHBoxLayout # type: ignore from PySide6.QtWidgets import QHBoxLayout # type: ignore
from PySide2.QtWidgets import QVBoxLayout # type: ignore from PySide6.QtWidgets import QVBoxLayout # type: ignore
from PySide2.QtWidgets import QComboBox # type: ignore from PySide6.QtWidgets import QComboBox # type: ignore
from PySide2.QtWidgets import QWidget # type: ignore from PySide6.QtWidgets import QLabel # type: ignore
from PySide6.QtWidgets import QWidget # type: ignore
from ....stats.list_item import PlayerListItem from ....stats.list_item import PlayerListItem
from ..view_type import ViewType
from .list_view import ListItemView from .list_view import ListItemView
from .stats_type import StatsType from .stats_type import StatsType
@@ -56,20 +58,38 @@ class ModeBasedListView(QWidget):
QWidget.__init__(self) QWidget.__init__(self)
self.layout = QVBoxLayout() self.layout = QVBoxLayout()
self.layout.setSpacing(0) self.layout.setSpacing(0)
self.layout.setMargin(0) self.layout.setContentsMargins(0, 0, 0, 0)
self.session_bar = SessionBar(clipboard) self.session_bar = SessionBar(clipboard)
self.layout.addWidget(self.session_bar) self.layout.addWidget(self.session_bar)
self.list_view = ListItemView() self.list_view = ListItemView()
self.layout.addWidget(self.list_view) self.layout.addWidget(self.list_view)
self.total_healing_label = QLabel('Total Healing')
self.layout.addWidget(self.total_healing_label)
self.total_healing_view = ListItemView()
self.layout.addWidget(self.total_healing_view)
self.total_healing_label.hide()
self.total_healing_view.hide()
self.setLayout(self.layout) self.setLayout(self.layout)
def update(self, prefix, elapsed, fame, fame_per_hour, players: PlayerListItem): def update(self, prefix, elapsed, fame, fame_per_hour,
players: PlayerListItem, total_healing: PlayerListItem):
self.session_bar.player_stats.update(elapsed, fame, fame_per_hour) self.session_bar.player_stats.update(elapsed, fame, fame_per_hour)
self.session_bar.copy_button.update( self.session_bar.copy_button.update(
prefix, self.list_view.get_player_list_items(), self.session_bar.mode.get_mode(), fame) prefix, self.list_view.get_player_list_items(), self.session_bar.mode.get_mode(), fame)
self.list_view.update(players) self.list_view.update(players)
if prefix == ViewType.HEALING_DONE and total_healing:
self.total_healing_label.show()
self.total_healing_view.show()
self.total_healing_view.update(total_healing)
else:
self.total_healing_label.hide()
self.total_healing_view.hide()
self.total_healing_view.update([])
self.session_bar.update() self.session_bar.update()
def get_mode(self) -> str: def get_mode(self) -> str:
+3 -3
View File
@@ -1,8 +1,8 @@
import datetime import datetime
from PySide2.QtWidgets import QLabel # type: ignore from PySide6.QtWidgets import QLabel # type: ignore
from PySide2 import QtGui # type: ignore from PySide6 import QtGui # type: ignore
from PySide2 import QtCore # type: ignore from PySide6 import QtCore # type: ignore
from src.utils import assets, number from src.utils import assets, number
from src.stats.list_item import PlayerListItem from src.stats.list_item import PlayerListItem
+2 -2
View File
@@ -1,8 +1,8 @@
from typing import Callable from typing import Callable
from PySide2.QtWidgets import QPushButton # type: ignore from PySide6.QtWidgets import QPushButton # type: ignore
from PySide2 import QtGui # type: ignore from PySide6 import QtGui # type: ignore
from ....utils import assets from ....utils import assets
from ....stats.list_item import PlayerListItem from ....stats.list_item import PlayerListItem
+114 -17
View File
@@ -6,31 +6,128 @@ font_size = cfg['window']['font-size']
style = """ style = """
QWidget { QWidget {
font-size: %s; font-size: %s;
background-color: black; background-color: #0f172a;
color: white; color: #e5edf8;
} }
#Motd, #Motd > * { QPushButton {
background-color: none; background-color: #182235;
color: none; border: 1px solid #2a3a54;
font-size: auto; border-radius: 8px;
padding: 10px 12px;
text-align: left;
color: #e5edf8;
} }
QListView { QPushButton:hover {
min-height: 100px; background-color: #24324a;
} }
QListView::item:selected:active { QPushButton:checked {
background-color: black; background-color: #f5b942;
} border-color: #f5b942;
color: #111827;
QListView::item:selected { font-weight: 700;
background-color: black;
} }
#Sidebar {
background-color: #111827;
border-right: 1px solid #263449;
min-width: 220px;
max-width: 220px;
}
#SidebarToggle {
text-align: center;
}
#SidebarTitle {
color: #f5b942;
font-size: 22px;
font-weight: 800;
padding: 10px 4px 16px 4px;
}
#SidebarSection {
color: #93a4bd;
font-weight: 700;
padding: 18px 4px 4px 4px;
text-transform: uppercase;
}
#HeaderTitle {
font-size: 28px;
font-weight: 800;
color: #ffffff;
}
#HeaderStatus {
color: #9fb0c8;
font-weight: 600;
}
#StatCard, #ItemsPanel {
background-color: #182235;
border: 1px solid #293951;
border-radius: 14px;
}
#ItemsPanel {
min-width: 300px;
max-width: 360px;
}
#CardTitle {
color: #9fb0c8;
font-size: 13px;
font-weight: 700;
text-transform: uppercase;
}
#CardValue {
color: #ffffff;
font-size: 24px;
font-weight: 800;
}
#PageTitle {
font-size: 24px;
font-weight: 800;
color: #ffffff;
padding-top: 8px;
}
#PageDescription, #MutedText {
color: #a9b7ca;
line-height: 1.35;
}
#PanelTitle {
color: #f5b942;
font-size: 18px;
font-weight: 800;
padding-top: 8px;
}
QListView {
background-color: #121c2e;
border: 1px solid #293951;
border-radius: 12px;
padding: 8px;
min-height: 160px;
}
QListView::item {
min-height: 36px;
border-radius: 6px;
margin: 3px;
padding: 4px;
}
QListView::item:selected:active,
QListView::item:selected,
QListView::item:selected:!active { QListView::item:selected:!active {
background-color: black; background-color: #24324a;
color: white; color: #ffffff;
} }
""" % (font_size) """ % (font_size)
View File
+155
View File
@@ -0,0 +1,155 @@
import logging
import socket
import struct
import threading
from typing import Callable, List, Optional
logger = logging.getLogger(__name__)
GAME_PORT = 5056
PROTO_IPV4 = 0x0800
PROTO_IPV6 = 0x86DD
PROTO_VLAN = 0x8100
PROTO_QINQ = 0x88A8
IPPROTO_UDP = 17
ETH_P_ALL = 0x0003
MAX_FRAME = 65535
def _extract_udp_payload(frame: bytes) -> Optional[bytes]:
"""Returns the UDP payload if the ethernet frame carries UDP on port 5056.
Handles Ethernet, VLAN tags, IPv4 and IPv6 with basic extension handling.
"""
pos = 0
if len(frame) < 14:
return None
ethertype = struct.unpack(">H", frame[12:14])[0]
pos = 14
while ethertype in (PROTO_VLAN, PROTO_QINQ):
if len(frame) < pos + 4:
return None
ethertype = struct.unpack(">H", frame[pos + 2:pos + 4])[0]
pos += 4
if ethertype == PROTO_IPV4:
if len(frame) < pos + 20:
return None
version_ihl = frame[pos]
header_len = (version_ihl & 0x0F) * 4
protocol = frame[pos + 9]
payload = frame[pos + header_len:]
elif ethertype == PROTO_IPV6:
if len(frame) < pos + 40:
return None
next_header = frame[pos + 6]
header_len = 40
while next_header in (0, 43, 44, 60):
if len(frame) < pos + header_len + 8:
return None
hdr_ext_len = (frame[pos + header_len + 1] + 1) * 8
if next_header == 44:
next_header = frame[pos + header_len]
header_len += 8
continue
next_header = frame[pos + header_len]
header_len += hdr_ext_len
protocol = next_header
payload = frame[pos + header_len:]
else:
return None
if protocol != IPPROTO_UDP:
return None
if len(payload) < 8:
return None
src_port, dst_port, length = struct.unpack(">HHH", payload[0:6])
if src_port != GAME_PORT and dst_port != GAME_PORT:
return None
udp_len = length
if udp_len < 8 or udp_len > len(payload):
return None
return bytes(payload[8:udp_len])
class CaptureEngine:
"""Listens for Albion Online traffic on all non-loopback interfaces.
Mirrors the aoaddons packet sniffer: one AF_PACKET socket per interface,
forwarding only UDP packets on port 5056 to a shared decode pipeline.
"""
def __init__(self, on_udp: Callable[[bytes], None]):
self._on_udp = on_udp
self._sockets: List[socket.socket] = []
self._threads: List[threading.Thread] = []
self._stop = threading.Event()
@staticmethod
def interface_names() -> List[str]:
names = []
try:
for _index, name in socket.if_nameindex():
if name and name != 'lo':
names.append(name)
except OSError:
logger.warning("unable to enumerate network interfaces")
return names
def start(self) -> bool:
names = self.interface_names()
if not names:
logger.warning("no network interfaces available for capture")
return False
for name in names:
try:
sock = socket.socket(
socket.AF_PACKET, socket.SOCK_RAW, socket.htons(ETH_P_ALL))
sock.bind((name, ETH_P_ALL))
sock.settimeout(1.0)
except OSError as e:
logger.warning("unable to bind %s: %s", name, e)
continue
self._sockets.append(sock)
thread = threading.Thread(
target=self._run_interface, args=(sock, name), daemon=True)
thread.start()
self._threads.append(thread)
logger.info("capturing on interface %s", name)
if not self._sockets:
logger.error("no interfaces could be captured (permissions?)")
return False
return True
def stop(self):
self._stop.set()
for sock in self._sockets:
try:
sock.close()
except OSError:
pass
for thread in self._threads:
thread.join(timeout=2.0)
self._sockets = []
self._threads = []
def _run_interface(self, sock: socket.socket, interface_name: str):
logger.debug("capture thread started for %s", interface_name)
try:
while not self._stop.is_set():
try:
frame = sock.recv(MAX_FRAME)
except socket.timeout:
continue
except OSError:
break
payload = _extract_udp_payload(frame)
if payload is None:
continue
try:
self._on_udp(payload)
except Exception:
logger.exception("error handling UDP payload")
finally:
logger.debug("capture thread stopped for %s", interface_name)
+139
View File
@@ -0,0 +1,139 @@
import json
import logging
import os
import re
import threading
from datetime import datetime
from typing import Callable, Iterator, List, Optional, Tuple
from .. import environment
logger = logging.getLogger(__name__)
_RAW_PAYLOAD_RE = re.compile(r'Raw payload:\s*\[([0-9,\s]*)\]')
def _record_timestamp(record: dict) -> Optional[float]:
raw = record.get('timestamp')
if not raw:
return None
try:
return datetime.fromisoformat(raw).timestamp()
except ValueError:
return None
def _json_payload(record: dict) -> Optional[bytes]:
if record.get('type') != 'udp_payload':
return None
payload_hex = record.get('payload_hex')
if not payload_hex:
return None
return bytes.fromhex(payload_hex)
def _raw_payload(line: str) -> Optional[bytes]:
match = _RAW_PAYLOAD_RE.search(line)
if not match:
return None
parts = [part.strip() for part in match.group(1).split(',')]
numbers = [int(part) for part in parts if part]
if not numbers:
return None
return bytes(numbers)
def iter_records(path: str) -> Iterator[Tuple[bytes, Optional[float]]]:
"""Yield ``(payload, timestamp)`` for every captured packet in ``path``.
Supports both the discovery JSONL format (records of ``type``
``udp_payload`` with a ``payload_hex`` field) and the legacy aoaddons
``Raw payload: [...]`` text format. All other record types are ignored.
"""
with open(path, encoding='utf-8', errors='replace') as log:
for line in log:
line = line.strip()
if not line:
continue
if line.startswith('{'):
try:
record = json.loads(line)
except json.JSONDecodeError:
record = None
if isinstance(record, dict):
payload = _json_payload(record)
if payload is not None:
yield payload, _record_timestamp(record)
continue
payload = _raw_payload(line)
if payload is not None:
yield payload, None
def load_payloads(path: str) -> List[bytes]:
"""Return every captured UDP payload from ``path`` in order."""
return [payload for payload, _ in iter_records(path)]
class ReplayEngine:
"""Feeds previously captured UDP payloads into a decode callback.
Mirrors :class:`src.net.capture.CaptureEngine` so the rest of the app can
treat a replayed log exactly like live traffic.
"""
def __init__(self, on_udp: Callable[[bytes], None],
path: Optional[str] = None,
speed: Optional[float] = None):
self._on_udp = on_udp
self._path = path if path is not None else environment.replay_path()
self._speed = speed if speed is not None else environment.replay_speed()
self._stop = threading.Event()
self._thread: Optional[threading.Thread] = None
self.packet_count = 0
def start(self) -> bool:
if self._thread is not None:
return True
if not self._path:
logger.error("replay requested but no log path was given")
return False
if not os.path.isfile(self._path):
logger.error("replay log does not exist: %s", self._path)
return False
self._thread = threading.Thread(
target=self._run, name='aostats-replay', daemon=True)
self._thread.start()
return True
def stop(self):
self._stop.set()
def wait(self, timeout: Optional[float] = None):
if self._thread is not None:
self._thread.join(timeout)
def _run(self):
logger.info("replaying %s (speed=%s)", self._path, self._speed)
previous: Optional[float] = None
try:
for payload, timestamp in iter_records(self._path):
if self._stop.is_set():
return
if self._speed and self._speed > 0 \
and timestamp is not None and previous is not None:
delay = (timestamp - previous) / self._speed
if delay > 0 and self._stop.wait(delay):
return
if timestamp is not None:
previous = timestamp
try:
self._on_udp(payload)
except Exception:
logger.exception("error replaying payload")
self.packet_count += 1
except OSError:
logger.exception("unable to read replay log: %s", self._path)
return
logger.info("replay finished: %d packets", self.packet_count)
+135
View File
@@ -0,0 +1,135 @@
import sys
from collections import Counter
from typing import List, Optional
from .consts import events as consts
from .decode.pipeline import Pipeline
from .net.replay import load_payloads
from .environment import replay_path, setup_logging
def _fmt(value: float) -> str:
return f'{value:.2f}'
def _event_value(event: dict) -> dict:
return event.get(consts.EvKeyValue) or {}
def _player_names(events: List[dict]) -> dict:
"""Map static player ids to names using the appearance events."""
names = {}
for event in events:
name = event[consts.EvKeyName]
if name in (consts.EvNamePlayerAppeared, consts.EvNameMainPlayerAppeared):
value = _event_value(event)
if value.get('id') is not None and value.get('name'):
names[value['id']] = value['name']
return names
def _damage_by_player(events: List[dict], names: dict, event_name: str):
"""Total damage per player, most first.
Reporting only a combined figure is misleading: the summary sits next to
"main player: <name>", so a party-wide total reads as if it belonged to
that one player.
"""
totals = Counter()
for event in events:
if event[consts.EvKeyName] != event_name:
continue
totals[_event_value(event).get(consts.EvKeySource, 0)] += \
_event_value(event).get('value', 0.0)
return totals, names
def _format_player_lines(totals, names: dict, limit: int = 8) -> List[str]:
if not totals:
return [' (none)']
ordered = sorted(totals.items(), key=lambda item: item[1], reverse=True)
lines = []
for player_id, total in ordered[:limit]:
label = names.get(player_id, f'player #{player_id}')
lines.append(f' {label}: {_fmt(total)}')
if len(ordered) > limit:
lines.append(f' ... and {len(ordered) - limit} more')
return lines
def summarize(events: List[dict], path: Optional[str] = None,
packet_count: Optional[int] = None) -> str:
"""Build a human readable summary of the events produced by a replay."""
counts = Counter(event[consts.EvKeyName] for event in events)
fame = sum(_event_value(e).get('value', 0.0)
for e in events if e[consts.EvKeyName] == consts.EvNameUpdateFame)
silver = sum(_event_value(e).get('value', 0.0)
for e in events
if e[consts.EvKeyName] == consts.EvNameSilverGained)
damage = sum(_event_value(e).get('value', 0.0)
for e in events
if e[consts.EvKeyName] == consts.EvNameDamageDone)
damage_taken = sum(_event_value(e).get('value', 0.0)
for e in events
if e[consts.EvKeyName] == consts.EvNameDamageTaken)
main_player = None
for event in events:
if event[consts.EvKeyName] == consts.EvNameMainPlayerAppeared:
main_player = _event_value(event).get('name')
break
names = _player_names(events)
damage_by_player, _ = _damage_by_player(
events, names, consts.EvNameDamageDone)
damage_taken_by_player, _ = _damage_by_player(
events, names, consts.EvNameDamageTaken)
lines = ['Replay summary']
if path:
lines.append(f' log: {path}')
if packet_count is not None:
lines.append(f' packets: {packet_count}')
lines.append(f' events: {len(events)}')
lines.append(f' main player: {main_player or "(unknown)"}')
lines.append(f' zone changes: {counts.get(consts.EvNameZoneChange, 0)}')
lines.append(f' fame gained: {_fmt(fame)}')
lines.append(f' silver looted: {_fmt(silver)}')
lines.append(f' damage done: {_fmt(damage)} (all players)')
lines.append(f' damage taken: {_fmt(damage_taken)} (all players)')
lines.append(' damage done by player:')
lines.extend(_format_player_lines(damage_by_player, names))
lines.append(' damage taken by player:')
lines.extend(_format_player_lines(damage_taken_by_player, names))
top = counts.most_common(8)
if top:
lines.append(' top events:')
for name, count in top:
lines.append(f' {name}: {count}')
return '\n'.join(lines)
def run_headless() -> int:
"""Replay the configured log through the pipeline and print a summary."""
setup_logging()
path = replay_path()
if not path:
print('--replay requires a log path', file=sys.stderr)
return 2
try:
packets = load_payloads(path)
except OSError as error:
print(f'unable to read replay log {path}: {error}', file=sys.stderr)
return 1
events: List[dict] = []
pipeline = Pipeline(events.append)
for payload in packets:
pipeline.on_udp(payload)
print(summarize(events, path=path, packet_count=len(packets)))
return 0
+55
View File
@@ -0,0 +1,55 @@
#!/bin/sh
# Grant the Python interpreter the capabilities required to capture network
# traffic, so that Albion Online Stats does not have to run as root.
#
# Usage: fixlibpcap.sh [path-to-python-interpreter]
PYTHON="${1:-$(command -v python3)}"
if [ -z "$PYTHON" ]; then
echo "Could not determine the python interpreter path." >&2
exit 1
fi
if [ ! -x "$PYTHON" ]; then
echo "Python interpreter '$PYTHON' is not executable." >&2
exit 1
fi
# Resolve symlinks (e.g. venv/bin/python -> /usr/bin/python3). setcap has to be
# applied to the real binary, not to a symlink.
if readlink -f "$PYTHON" >/dev/null 2>&1; then
PYTHON="$(readlink -f "$PYTHON")"
elif command -v python3 >/dev/null 2>&1; then
PYTHON="$(python3 -c 'import os, sys; print(os.path.realpath(sys.executable))' 2>/dev/null || echo "$PYTHON")"
fi
if ! command -v setcap >/dev/null 2>&1; then
echo "The 'setcap' tool was not found." >&2
echo "Install libcap before retrying:" >&2
echo " Debian/Ubuntu: sudo apt install libcap2-bin" >&2
echo " Fedora: sudo dnf install libcap" >&2
echo " Arch: sudo pacman -S libcap" >&2
exit 1
fi
echo "Granting packet capture capabilities to: $PYTHON"
echo "You may be asked for a password."
# pkexec shows a graphical authentication dialog, which works even when the app
# was not started from a terminal. Fall back to sudo otherwise.
if command -v pkexec >/dev/null 2>&1; then
pkexec setcap cap_net_raw,cap_net_admin=eip "$PYTHON"
status=$?
else
sudo setcap cap_net_raw,cap_net_admin=eip "$PYTHON"
status=$?
fi
if [ "$status" -ne 0 ]; then
echo "Failed to set capture capabilities. Try running the app with sudo:" >&2
echo " sudo $(command -v aostats 2>/dev/null || echo 'python -m aostats')" >&2
exit "$status"
fi
echo "Done. Please restart Albion Online Stats."
+372
View File
@@ -0,0 +1,372 @@
{
"ACID_BOMB_EFFECT": {
"abilities": [
"ACID_BOMB"
],
"category": "instant",
"effects": [
{
"target": "enemy",
"targetcountvaluebonusfactor": 0.08,
"time": 3.5,
"type": "magicresistance",
"value": -0.14
},
{
"target": "enemy",
"targetcountvaluebonusfactor": 0.08,
"time": 3.5,
"type": "physicalarmor",
"value": -0.14
}
],
"maxcharges": null,
"maxstack": null,
"uitype": "damage"
},
"ARMORPIERCER_DEBUFF_EFFECT": {
"abilities": [
"ARMORPIERCER"
],
"category": "debuff",
"effects": [
{
"target": "enemy",
"targetcountvaluebonusfactor": 0.08,
"time": 4.0,
"type": "magicresistance",
"value": -0.17
},
{
"target": "enemy",
"targetcountvaluebonusfactor": 0.08,
"time": 4.0,
"type": "physicalarmor",
"value": -0.17
}
],
"maxcharges": null,
"maxstack": null,
"uitype": "debuff"
},
"AXESMASH_EFFECT": {
"abilities": [
"AXESMASH"
],
"category": "debuff",
"effects": [
{
"target": "enemy",
"time": 8.0,
"type": "magicresistance",
"value": -0.16
},
{
"target": "enemy",
"time": 8.0,
"type": "physicalarmor",
"value": -0.16
}
],
"maxcharges": null,
"maxstack": null,
"uitype": "debuff"
},
"BEARTRAP_HIDEMOB_BONUS": {
"abilities": [
"BEARTRAP"
],
"category": "crowdcontrol",
"effects": [
{
"target": "enemy",
"time": 8.0,
"type": "magicresistance",
"value": -0.55
},
{
"target": "enemy",
"time": 8.0,
"type": "physicalarmor",
"value": -0.55
}
],
"maxcharges": null,
"maxstack": 3,
"uitype": "crowdcontrol"
},
"CURSEULTIMATE_EFFECT": {
"abilities": [
"CURSEULTIMATE"
],
"category": "damage",
"effects": [
{
"target": "enemy",
"targetcountvaluebonusfactor": 0.08,
"time": 6.0,
"type": "magicresistance",
"value": -0.18
},
{
"target": "enemy",
"targetcountvaluebonusfactor": 0.08,
"time": 6.0,
"type": "physicalarmor",
"value": -0.18
}
],
"maxcharges": null,
"maxstack": 1,
"uitype": "damage"
},
"DEADLYSHOT_DEBUFF": {
"abilities": [
"DEADLYSHOT"
],
"category": "debuff",
"effects": [
{
"target": "enemy",
"targetcountvaluebonusfactor": 0.08,
"time": 5.0,
"type": "magicresistance",
"value": -0.03
},
{
"target": "enemy",
"targetcountvaluebonusfactor": 0.08,
"time": 5.0,
"type": "physicalarmor",
"value": -0.03
}
],
"maxcharges": 3,
"maxstack": 5,
"uitype": "debuff"
},
"FROST_LANCE_EFFECT": {
"abilities": [
"FROST_LANCE"
],
"category": "debuff",
"effects": [
{
"target": "enemy",
"targetcountvaluebonusfactor": 0.08,
"time": 3.0,
"type": "magicresistance",
"value": -0.12
},
{
"target": "enemy",
"targetcountvaluebonusfactor": 0.08,
"time": 3.0,
"type": "physicalarmor",
"value": -0.12
}
],
"maxcharges": 1,
"maxstack": 1,
"uitype": "damage"
},
"IRONBREAKER_EFFECT": {
"abilities": [
"IRONBREAKER"
],
"category": "debuff",
"effects": [
{
"target": "enemy",
"targetcountvaluebonusfactor": 0.08,
"time": 4.0,
"type": "magicresistance",
"value": -0.12
},
{
"target": "enemy",
"targetcountvaluebonusfactor": 0.08,
"time": 4.0,
"type": "physicalarmor",
"value": -0.12
}
],
"maxcharges": null,
"maxstack": null,
"uitype": "debuff"
},
"SHAPE_Q_CONE_PIERCE": {
"abilities": [
"SHAPE_Q_CONE_MELEE"
],
"category": "debuff",
"effects": [
{
"target": "enemy",
"time": 6.0,
"type": "magicresistance",
"value": -0.02
},
{
"target": "enemy",
"time": 6.0,
"type": "physicalarmor",
"value": -0.02
}
],
"maxcharges": 3,
"maxstack": null,
"uitype": "damage"
},
"SMELLOFBLOOD_DEBUFF": {
"abilities": [
"SMELLOFBLOOD"
],
"category": "debuff",
"effects": [
{
"target": "enemy",
"time": 4.0,
"type": "magicresistance",
"value": -0.35
},
{
"target": "enemy",
"time": 4.0,
"type": "physicalarmor",
"value": -0.35
}
],
"maxcharges": null,
"maxstack": null,
"uitype": "debuff"
},
"SNIPESHOT_CROSSBOW_DEBUFF": {
"abilities": [
"SNIPESHOT_CROSSBOW"
],
"category": "damage",
"effects": [
{
"target": "enemy",
"time": 4.0,
"type": "magicresistance",
"value": -0.15
},
{
"target": "enemy",
"time": 4.0,
"type": "physicalarmor",
"value": -0.15
}
],
"maxcharges": null,
"maxstack": null,
"uitype": "debuff"
},
"SUNDERARMOR2": {
"abilities": [
"SUNDERARMOR2"
],
"category": "debuff",
"effects": [
{
"iftargettype": "mob",
"target": "enemy",
"time": 8.0,
"type": "magicresistance",
"value": -0.06
},
{
"iftargettype": "player",
"target": "enemy",
"time": 8.0,
"type": "magicresistance",
"value": -0.04
},
{
"iftargettype": "mob",
"target": "enemy",
"time": 8.0,
"type": "physicalarmor",
"value": -0.06
},
{
"iftargettype": "player",
"target": "enemy",
"time": 8.0,
"type": "physicalarmor",
"value": -0.04
}
],
"maxcharges": 3,
"maxstack": 3,
"uitype": "debuff"
},
"SUNDERSHOT_DEBUFF": {
"abilities": [
"SUNDERSHOT"
],
"category": "debuff",
"effects": [
{
"target": "enemy",
"time": 4.0,
"type": "magicresistance",
"value": -0.027
},
{
"target": "enemy",
"time": 4.0,
"type": "physicalarmor",
"value": -0.027
}
],
"maxcharges": 10,
"maxstack": null,
"uitype": "debuff"
},
"TAINTED_STEEL_AREA": {
"abilities": [
"TAINTED_STEEL"
],
"category": "instant",
"effects": [
{
"target": "enemy",
"targetcountvaluebonusfactor": 0.08,
"time": 4.0,
"type": "magicresistance",
"value": -0.04
}
],
"maxcharges": null,
"maxstack": 1,
"uitype": "damage"
},
"TAINTED_STEEL_EFFECT": {
"abilities": [
"TAINTED_STEEL"
],
"category": "debuff",
"effects": [
{
"target": "enemy",
"targetcountvaluebonusfactor": 0.08,
"time": 4.0,
"type": "magicresistance",
"value": -0.12
},
{
"target": "enemy",
"targetcountvaluebonusfactor": 0.08,
"time": 4.0,
"type": "physicalarmor",
"value": -0.12
}
],
"maxcharges": null,
"maxstack": null,
"uitype": "damage"
}
}
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
+1
View File
@@ -0,0 +1 @@
11898,Keeper Memory - Shameless or Daring
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
+195
View File
@@ -0,0 +1,195 @@
{
"shares": {
"armorshare": {
"@armor": "1.0",
"@avalonshield": "0",
"@book": "0",
"@cane": "0",
"@cape": "0",
"@censer": "0",
"@crystalbook": "0",
"@crystalshield": "0",
"@crystaltorch": "0",
"@demonskull": "0",
"@head": "0",
"@horn": "0",
"@lamp": "0",
"@mainhand": "0",
"@orb": "0",
"@prototype": "0",
"@shield": "0",
"@shoes": "0",
"@skullshield": "0",
"@spikedshield": "0",
"@talisman": "0",
"@torch": "0",
"@totem": "0",
"@towershield": "0",
"@transformation": "1.0"
},
"ccrshare": {
"@armor": "1.0",
"@avalonshield": "0",
"@book": "0",
"@cane": "0",
"@cape": "0",
"@censer": "0",
"@crystalbook": "0",
"@crystalshield": "0",
"@crystaltorch": "-1.2",
"@demonskull": "0",
"@head": "0",
"@horn": "0",
"@lamp": "0",
"@mainhand": "0",
"@orb": "0",
"@prototype": "0",
"@shield": "0.60",
"@shoes": "0",
"@skullshield": "0",
"@spikedshield": "0",
"@talisman": "1.8",
"@torch": "0",
"@totem": "0",
"@towershield": "0",
"@transformation": "1.0"
},
"energyshare": {
"@armor": "0.25",
"@avalonshield": "0",
"@book": "0.15",
"@cane": "0",
"@cape": "0.10",
"@censer": "0",
"@crystalbook": "0",
"@crystalshield": "0.125",
"@crystaltorch": "0",
"@demonskull": "0",
"@head": "0.5",
"@horn": "0",
"@lamp": "0",
"@mainhand": "0",
"@orb": "0.5",
"@prototype": "0",
"@shield": "0",
"@shoes": "0.15",
"@skullshield": "0",
"@spikedshield": "0",
"@talisman": "0",
"@torch": "0",
"@totem": "0",
"@towershield": "0",
"@transformation": "1.0"
},
"hitpointsshare": {
"@armor": "0.5",
"@avalonshield": "0",
"@book": "0",
"@cane": "0",
"@cape": "0",
"@censer": "0",
"@crystalbook": "0",
"@crystalshield": "0",
"@crystaltorch": "0",
"@demonskull": "0",
"@head": "0.25",
"@horn": "0",
"@lamp": "0",
"@mainhand": "0",
"@orb": "0",
"@prototype": "0.125",
"@shield": "0",
"@shoes": "0.25",
"@skullshield": "0",
"@spikedshield": "0",
"@talisman": "0",
"@torch": "0",
"@totem": "0.25",
"@towershield": "0",
"@transformation": "1.0"
},
"trackingtime": {
"@base": "0"
}
},
"slots": {
"armor": {
"armorbase": 100.0,
"armorprogression": 1.03,
"attackdamageprogression": 1.0918,
"hitpointsprogression": 1.06
},
"bag": {
"armorbase": 100.0,
"armorprogression": 1.03,
"attackdamageprogression": 1.0918,
"hitpointsprogression": 1.06
},
"cape": {
"armorbase": 100.0,
"armorprogression": 1.03,
"attackdamageprogression": 1.0918,
"hitpointsprogression": 1.06
},
"food": {
"armorbase": 100.0,
"armorprogression": 1.03,
"attackdamageprogression": 1.0918,
"hitpointsprogression": 1.06
},
"head": {
"armorbase": 100.0,
"armorprogression": 1.03,
"attackdamageprogression": 1.0918,
"hitpointsprogression": 1.06
},
"legendaryitemtraits": {
"armorbase": 100.0,
"armorprogression": 1.03,
"attackdamageprogression": 1.0918,
"hitpointsprogression": 1.06
},
"mainhand_1h": {
"armorbase": 100.0,
"armorprogression": 1.03,
"attackdamageprogression": 1.0825,
"hitpointsprogression": 1.06
},
"mainhand_2h": {
"armorbase": 100.0,
"armorprogression": 1.03,
"attackdamageprogression": 1.0918,
"hitpointsprogression": 1.06
},
"mount": {
"armorbase": 100.0,
"armorprogression": 1.03,
"attackdamageprogression": 1.0918,
"hitpointsprogression": 1.06
},
"offhand": {
"armorbase": 100.0,
"armorprogression": 1.03,
"attackdamageprogression": 1.0918,
"hitpointsprogression": 1.06
},
"potion": {
"armorbase": 100.0,
"armorprogression": 1.03,
"attackdamageprogression": 1.0918,
"hitpointsprogression": 1.06
},
"shoes": {
"armorbase": 100.0,
"armorprogression": 1.03,
"attackdamageprogression": 1.0918,
"hitpointsprogression": 1.06
},
"transformation": {
"armorbase": 100.0,
"armorprogression": 1.03,
"attackdamageprogression": 1.0918,
"hitpointsprogression": 1.06
}
}
}
+60
View File
@@ -0,0 +1,60 @@
# Game data provenance
This directory contains data vendored from the Albion Online game client.
It is **not** hand-maintained and must not be edited by hand.
## `item_ids.txt`
| | |
| --- | --- |
| Upstream | [`ao-data/ao-bin-dumps`](https://github.com/ao-data/ao-bin-dumps) |
| Path in upstream | `formatted/items.txt` |
| Commit | `47e4f5aca4d30b7495afa5a625ce0d5795e32050` |
| Commit date | 2026-09-23 |
| Retrieved | 2026-10-11 |
| Licence | MIT |
| Entries | 12,237 (IDs 1–12237, contiguous, no duplicates) |
Format is ` <id>: <uniquename> : <localized display name>`. Some entries have
no display name (846 of them), in which case the line ends after the unique
name.
`src/static/item_ids.txt` is generated from this file by `make gamedata`. It is
what the app reads, in the `<id>,<uniquename>` form its loader expects.
### Why this replaces the previous table
The table previously committed at `src/static/item_ids.txt` held 7,493 entries
and was a valid **older build** of this same data. Albion re-orders IDs between
builds, so the two agree on almost nothing: on the overlapping 7,239 IDs they
disagree on **100%**.
It is not merely stale — it is actively wrong. Scoring both tables against a
real equipment array from a capture, where each slot's position is known:
- this file: **8/8** slots resolve to the correct item and slot
- the old table: **0/8** (a helmet resolved to a firestaff, armor to a backpack)
Regenerate with `make gamedata`; the same command rewrites this file.
## Everything else is fetched, not committed
The remaining game data is too large to version, so `scripts/fetch_gamedata.py`
pulls it at build time into a gitignored cache:
| File | Size | Used for |
| --- | --- | --- |
| `items.json` | 17 MB | item → ability-slot bindings |
| `spells.json` | 15 MB | spell and debuff effect definitions |
| `mobs.json` | 19 MB | mob armor/resistance, mob template IDs |
| `gamedata.json` | 184 KB | item-power → armor/damage progression constants |
`localization.json` (90 MB) is deliberately **not** fetched. It is only needed
for localized display strings, and it cannot supply a display name for every
mob anyway — 883 of 5,479 mob definitions have no `namelocatag` at all,
including `T5_MOB_HIDE_SWAMP_GIANTSNAKE`. Nothing in attribution depends on it.
## Attribution
MIT, from the upstream repositories. See the upstream `LICENSE` file for the
authoritative text.
+12237
View File
File diff suppressed because it is too large Load Diff
+46 -3
View File
@@ -30,8 +30,8 @@ class Party:
self.get_visible_players = get_visible_players self.get_visible_players = get_visible_players
def combat_state(self) -> int: def combat_state(self) -> int:
return CombatState.OutOfCombat if all( return CombatState.InCombat if any(
player.combat_state == CombatState.InCombat for player in self.get_visible_players()) else CombatState.InCombat player.combat_state == CombatState.InCombat for player in self.get_visible_players()) else CombatState.OutOfCombat
def time_in_combat(self) -> float: def time_in_combat(self) -> float:
longest = 0.0 longest = 0.0
@@ -49,7 +49,9 @@ class Player(Stats):
party: Party party: Party
items: dict = field(default_factory=lambda: {'weapon': None}) items: dict = field(default_factory=lambda: {'weapon': None})
damage_done: float = 0.0 damage_done: float = 0.0
damage_taken: float = 0.0
healing_done: float = 0.0 healing_done: float = 0.0
total_healing_done: float = 0.0
combat_time: CombatTime = field(default_factory=lambda: CombatTime()) combat_time: CombatTime = field(default_factory=lambda: CombatTime())
combat_state: int = CombatState.OutOfCombat combat_state: int = CombatState.OutOfCombat
active: bool = False active: bool = False
@@ -61,7 +63,7 @@ class Player(Stats):
return self.active return self.active
def has_stats(self) -> bool: def has_stats(self) -> bool:
return bool(self.damage_done or self.healing_done) return bool(self.damage_done or self.damage_taken or self.healing_done or self.total_healing_done)
@staticmethod @staticmethod
def new(self): def new(self):
@@ -74,7 +76,9 @@ class Player(Stats):
def update(self, other): def update(self, other):
self.name = other.name self.name = other.name
self.damage_done += other.damage_done self.damage_done += other.damage_done
self.damage_taken += other.damage_taken
self.healing_done += other.healing_done self.healing_done += other.healing_done
self.total_healing_done += other.total_healing_done
self.combat_state = other.combat_state self.combat_state = other.combat_state
self.combat_time.entered_combat = other.combat_time.entered_combat self.combat_time.entered_combat = other.combat_time.entered_combat
self.combat_time.time_in_combat += other.combat_time.time_in_combat self.combat_time.time_in_combat += other.combat_time.time_in_combat
@@ -92,10 +96,16 @@ class Player(Stats):
self.activate() self.activate()
def register_healing_done(self, value): def register_healing_done(self, value):
self.total_healing_done += value
self.activate()
if self.party.combat_state() == CombatState.OutOfCombat: if self.party.combat_state() == CombatState.OutOfCombat:
return return
self.healing_done += value self.healing_done += value
def register_damage_taken(self, value):
self.damage_taken += value
self.activate() self.activate()
def enter_combat(self): def enter_combat(self):
@@ -112,10 +122,19 @@ class Player(Stats):
return StandalonePlayerListItem( return StandalonePlayerListItem(
self.name, self.items, self.damage_done, self.dps, self.combat_state) self.name, self.items, self.damage_done, self.dps, self.combat_state)
def into_damage_taken_list_item(self) -> StandalonePlayerListItem:
return StandalonePlayerListItem(
self.name, self.items, self.damage_taken, 0.0, self.combat_state)
def into_healing_list_item(self) -> StandalonePlayerListItem: def into_healing_list_item(self) -> StandalonePlayerListItem:
return StandalonePlayerListItem( return StandalonePlayerListItem(
self.name, self.items, self.healing_done, self.hps, self.combat_state) self.name, self.items, self.healing_done, self.hps, self.combat_state)
def into_total_healing_list_item(self) -> StandalonePlayerListItem:
return StandalonePlayerListItem(
self.name, self.items, self.total_healing_done, self.total_hps,
self.combat_state)
@property @property
def time_in_combat(self): def time_in_combat(self):
if self.combat_state == CombatState.InCombat: if self.combat_state == CombatState.InCombat:
@@ -140,6 +159,16 @@ class Player(Stats):
return time_utils.as_milliseconds(self.healing_done / time_in_combat) return time_utils.as_milliseconds(self.healing_done / time_in_combat)
@property
def total_hps(self):
time_in_combat = self.party.time_in_combat()
if time_in_combat == 0.0:
return 0.0
return time_utils.as_milliseconds(
self.total_healing_done / time_in_combat)
class CombatStats(CombatEventReceiver, Stats): class CombatStats(CombatEventReceiver, Stats):
def __init__(self, visibility, players=None): def __init__(self, visibility, players=None):
@@ -185,9 +214,20 @@ class CombatStats(CombatEventReceiver, Stats):
for player in self.visible_players() for player in self.visible_players()
]) ])
def players_damage_taken(self) -> List[PlayerListItem]:
return to_player_list_items([player.into_damage_taken_list_item()
for player in self.visible_players()
])
def players_healing(self) -> List[PlayerListItem]: def players_healing(self) -> List[PlayerListItem]:
return to_player_list_items([player.into_healing_list_item() return to_player_list_items([player.into_healing_list_item()
for player in self.visible_players()
])
def players_total_healing(self) -> List[PlayerListItem]:
return to_player_list_items([player.into_total_healing_list_item()
for player in self.visible_players() for player in self.visible_players()
if player.total_healing_done
]) ])
def party_combat_state(self): def party_combat_state(self):
@@ -205,6 +245,9 @@ class CombatStats(CombatEventReceiver, Stats):
def on_damage_done(self, id: int, damage: float): def on_damage_done(self, id: int, damage: float):
self.players[id].register_damage_done(damage) self.players[id].register_damage_done(damage)
def on_damage_taken(self, id: int, damage: float):
self.players[id].register_damage_taken(damage)
def on_health_received(self, id: int, target_id: int, health: float): def on_health_received(self, id: int, target_id: int, health: float):
self.players[id].register_healing_done(health) self.players[id].register_healing_done(health)
+92
View File
@@ -0,0 +1,92 @@
from dataclasses import dataclass, field
from typing import Dict
from ..event_receiver import EconomyEventReceiver
from .combat_state import CombatState
from .list_item import PlayerListItem, StandalonePlayerListItem, to_player_list_items
from .statistics import Stats
@dataclass
class ItemTotal:
item_id: int
item_name: str
quantity: int = 0
@dataclass
class EconomyStats(EconomyEventReceiver, Stats):
looted_silver: float = 0.0
other_silver: float = 0.0
items: Dict[int, ItemTotal] = field(default_factory=dict)
@classmethod
def new(self):
return EconomyStats()
@classmethod
def from_other(other):
return EconomyStats(
looted_silver=other.looted_silver,
other_silver=other.other_silver,
items={k: ItemTotal(v.item_id, v.item_name, v.quantity)
for k, v in other.items.items()},
)
def update(self, other):
self.looted_silver += other.looted_silver
self.other_silver += other.other_silver
for item_id, item in other.items.items():
if item_id not in self.items:
self.items[item_id] = ItemTotal(item.item_id, item.item_name)
self.items[item_id].quantity += item.quantity
def on_silver_gained(self, value: float, silver_type: str):
if silver_type == 'looted':
self.looted_silver += value
else:
self.other_silver += value
def on_item_collected(self, item_id: int, item_name: str, quantity: int):
if item_id not in self.items:
self.items[item_id] = ItemTotal(item_id, item_name)
self.items[item_id].quantity += quantity
def stats(self):
return {
'looted_silver': self.looted_silver,
'other_silver': self.other_silver,
'total_silver': self.looted_silver + self.other_silver,
}
def item_list(self):
standalone = [
StandalonePlayerListItem(
item.item_name,
{'weapon': None},
float(item.quantity),
0.0,
CombatState.OutOfCombat,
)
for item in self.items.values()
if item.quantity > 0
]
return to_player_list_items(standalone)
def silver_list(self):
values = [
('Looted Silver', self.looted_silver),
('Other Silver', self.other_silver),
]
standalone = [
StandalonePlayerListItem(
name,
{'weapon': None},
value,
0.0,
CombatState.OutOfCombat,
)
for name, value in values
if value > 0
]
return to_player_list_items(standalone)
+4 -10
View File
@@ -3,7 +3,6 @@ import functools
from dataclasses import dataclass, field from dataclasses import dataclass, field
from typing import List from typing import List
import re
from src.utils.config import config from src.utils.config import config
from ..event_receiver import VisibilityEventReceiver from ..event_receiver import VisibilityEventReceiver
@@ -24,13 +23,13 @@ class Visibility(VisibilityEventReceiver):
if _is_visible_by_config(): # Note: only for testing purposes if _is_visible_by_config(): # Note: only for testing purposes
return True return True
pattern = '|'.join(self.visible_players) + '|{}'.format( visible = set(self.visible_players)
self.main_player_name) if self.visible_players else self.main_player_name visible.add(self.main_player_name)
return self.main_player_name and bool(_compile_pattern(pattern).match(name)) return bool(self.main_player_name and name in visible)
@property @property
def is_main_player_visible(self) -> bool: def is_main_player_visible(self) -> bool:
return self.main_player_name is not "" return self.main_player_name != ""
@functools.lru_cache(maxsize=128) @functools.lru_cache(maxsize=128)
@@ -39,8 +38,3 @@ def _is_visible_by_config():
return True return True
return False return False
@functools.lru_cache(maxsize=128)
def _compile_pattern(pattern: str):
return re.compile(pattern)
+9 -1
View File
@@ -2,6 +2,10 @@ import threading
import queue import queue
import requests import requests
import collections import collections
import logging
logger = logging.getLogger(__name__)
Item = collections.namedtuple('Item', 'key value') Item = collections.namedtuple('Item', 'key value')
@@ -26,7 +30,11 @@ _update_thread.start()
def _async_req(url): def _async_req(url):
req = requests.get(url) try:
req = requests.get(url, timeout=5)
except requests.RequestException as e:
logger.debug("async request failed for %s: %s", url, e)
req = None
_queue.put(Item(key=url, value=req)) _queue.put(Item(key=url, value=req))
+20 -10
View File
@@ -1,15 +1,20 @@
import os import os
import platform
import sys import sys
import toml import toml
CFG_VERSION = '0.7' from . import platform_utils
CFG_VERSION = '0.8'
default = """ default = """
[window] [window]
width = 300 width = 1280
height = 220 height = 720
font-size = '10px' font-size = '14px'
fullscreen = true
# When true, the dashboard opens maximized so it can still be moved between
# desktops/monitors by the window manager. Set false to use width/height.
# Note: do not change! # Note: do not change!
# options bellow are here only for testing purposes # options bellow are here only for testing purposes
@@ -33,11 +38,12 @@ _config = None
def get_config_path(): def get_config_path():
cfg_file_name = 'albion-online-stats.cfg' cfg_file_name = 'albion-online-stats.cfg'
script_dir = os.path.dirname(_script_path)
if platform.system() == 'Windows': cfg_dir = platform_utils.config_dir()
return os.path.join(os.getenv('APPDATA', script_dir), cfg_file_name) if not cfg_dir:
else: cfg_dir = os.path.dirname(os.path.abspath(_script_path))
return os.path.join(script_dir, cfg_file_name)
return os.path.join(cfg_dir, cfg_file_name)
def config(): def config():
@@ -48,6 +54,10 @@ def config():
conf_file = get_config_path() conf_file = get_config_path()
conf_dir = os.path.dirname(conf_file)
if conf_dir:
os.makedirs(conf_dir, exist_ok=True)
try: try:
with open(conf_file, "r") as cfg_file: with open(conf_file, "r") as cfg_file:
cfg = toml.load(cfg_file) cfg = toml.load(cfg_file)
+10 -2
View File
@@ -1,9 +1,17 @@
import json import json
import os
try: try:
from pyaoaddons import localization_mapping from pyaoaddons import localization_mapping
except: except Exception:
localization_mapping = {} _PATH = os.path.join(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
'static', 'localization_mapping.json')
try:
with open(_PATH, encoding='utf-8') as _f:
localization_mapping = json.load(_f)
except (OSError, ValueError):
localization_mapping = {}
from . import assets from . import assets
+89
View File
@@ -0,0 +1,89 @@
import os
import platform
import socket
from typing import Optional
WINDOWS = 'Windows'
LINUX = 'Linux'
MACOS = 'Darwin'
APP_DIR_NAME = 'albion-online-stats'
# Name of the platform specific script used to repair packet capture
# permissions. ``None`` means that no automatic repair is available.
_REPAIR_SCRIPTS = {
WINDOWS: 'fixnpcap.bat',
LINUX: 'fixlibpcap.sh',
MACOS: 'fixlibpcap.sh',
}
def system() -> str:
return platform.system()
def is_windows() -> bool:
return system() == WINDOWS
def is_linux() -> bool:
return system() == LINUX
def is_macos() -> bool:
return system() == MACOS
def repair_script() -> Optional[str]:
return _REPAIR_SCRIPTS.get(system())
def capture_permissions_ok() -> bool:
"""Return True when the current process may capture network packets.
The packet capture backend starts background sniffing threads and reports
initialization as successful even when it later fails to open a socket, so
on Linux this explicitly probes for ``CAP_NET_RAW`` (required to open
``AF_PACKET`` raw sockets). On other platforms there is no easy probe, so
``True`` is returned.
"""
if not is_linux():
return True
euid = getattr(os, 'geteuid', lambda: -1)()
if euid == 0:
return True
try:
sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW)
sock.close()
return True
except (PermissionError, OSError):
return False
def config_dir() -> Optional[str]:
"""Return the platform specific directory used to store the config.
Returns ``None`` when no standard per-user directory can be determined.
"""
if is_windows():
base = os.getenv('APPDATA')
return os.path.join(base, APP_DIR_NAME) if base else None
if is_macos():
home = os.path.expanduser('~')
if not home or home == '~':
return None
return os.path.join(home, 'Library', 'Application Support', APP_DIR_NAME)
if is_linux():
base = os.getenv('XDG_CONFIG_HOME')
if not base:
home = os.path.expanduser('~')
if not home or home == '~':
return None
base = os.path.join(home, '.config')
return os.path.join(base, APP_DIR_NAME)
return None
+11 -9
View File
@@ -1,11 +1,17 @@
import json import json
import os
try: try:
from pyaoaddons import item_category_mapping from pyaoaddons import item_category_mapping
except: except Exception:
item_category_mapping = {} _PATH = os.path.join(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
from . import assets 'static', 'item_category_mapping.json')
try:
with open(_PATH, encoding='utf-8') as _f:
item_category_mapping = json.load(_f)
except (OSError, ValueError):
item_category_mapping = {}
class WeaponType: class WeaponType:
@@ -26,12 +32,8 @@ class WeaponType:
Sword = 'sword' Sword = 'sword'
def map_weapon(weapon):
return item_category_mapping[weapon] if weapon in item_category_mapping else None
def get_weapon_type(items): def get_weapon_type(items):
weapon = map_weapon(items['weapon']) weapon = item_category_mapping.get(items.get('weapon', None), None)
if weapon == WeaponType.Arcane: if weapon == WeaponType.Arcane:
return WeaponType.Arcane return WeaponType.Arcane
+1 -1
View File
@@ -1 +1 @@
version = "1.0.4" version = "1.0.5"
+242
View File
@@ -0,0 +1,242 @@
"""Helpers for analysing captured discovery logs.
Captures are large (tens of MB) and live outside the repository, so tests that
use them skip themselves when none are available. Set ``AOSTATS_CAPTURE_GLOB``
to point at a different location, e.g.::
AOSTATS_CAPTURE_GLOB='/tmp/aostats-in-party*.jsonl' pytest tests
Records are read from the ``photon_message`` stream rather than the decoder's
``game_message`` stream. That matters for opcode research: ``game_message`` only
contains opcodes that ``src/decode/translate.py`` currently knows about, which
is exactly the set we are trying to extend.
"""
import glob
import json
import os
from dataclasses import dataclass
from typing import Any, Dict, Iterator, List, Optional
CAPTURE_GLOB_ENV = 'AOSTATS_CAPTURE_GLOB'
DEFAULT_CAPTURE_GLOB = '/tmp/aostats-in-party-with-items-and-silver*.jsonl'
# Opcodes under investigation, by Photon parameter id.
EVENT_PARAM = 252
OPCODE_HEALTH_UPDATE = 6
OPCODE_DAMAGE_BATCH = 7
OPCODE_ENTITY_STATS = 18
@dataclass(frozen=True)
class DecodedMessage:
"""A Photon message as captured, before opcode translation."""
timestamp: str
kind: str
opcode: Optional[int]
params: Dict[str, Any]
@dataclass(frozen=True)
class DamageHit:
"""One damage or healing tick against a victim.
``opcode`` is retained so a hit can be attributed to either the scalar
(``OPCODE_HEALTH_UPDATE``) or batched (``OPCODE_DAMAGE_BATCH``) encoding.
"""
timestamp: str
opcode: int
victim: Any
attacker: Any
delta: float
health_after: Optional[float]
def capture_glob() -> str:
return os.getenv(CAPTURE_GLOB_ENV) or DEFAULT_CAPTURE_GLOB
def capture_paths() -> List[str]:
return sorted(path for path in glob.glob(capture_glob()) if not path.endswith('.app.log'))
def captures_available() -> bool:
return bool(capture_paths())
def param(params: Dict[str, Any], key: int, default: Any = None) -> Any:
"""Read a Photon parameter by numeric id (JSON keys are strings)."""
return params.get(str(key), default)
def byte_list(value: Any) -> List[int]:
"""Normalise a parameter that may arrive as raw bytes or a decoded list."""
if isinstance(value, dict) and 'bytes_hex' in value:
raw = value['bytes_hex']
return [int(raw[i:i + 2], 16) for i in range(0, len(raw), 2)]
if isinstance(value, list):
return [v for v in value if isinstance(v, int)]
return []
def iter_messages(path: str) -> Iterator[DecodedMessage]:
"""Yield every captured Photon message in ``path`` in arrival order."""
with open(path, encoding='utf-8', errors='replace') as log:
for line in log:
if '"photon_message"' not in line:
continue
try:
record = json.loads(line)
except json.JSONDecodeError:
continue
message = record.get('message') or {}
params = message.get('params') or {}
kind = message.get('kind')
if kind == 'Event':
opcode = param(params, EVENT_PARAM)
elif kind in ('Request', 'Response'):
opcode = param(params, 253)
else:
opcode = None
yield DecodedMessage(
timestamp=record.get('timestamp') or '',
kind=kind,
opcode=opcode if isinstance(opcode, int) else None,
params=params,
)
def damage_hits(path: str) -> Iterator[DamageHit]:
"""Yield every damage/healing tick from both health-update encodings."""
for message in iter_messages(path):
if message.kind != 'Event':
continue
if message.opcode == OPCODE_HEALTH_UPDATE:
delta = param(message.params, 2)
health_after = param(message.params, 3)
if not isinstance(delta, (int, float)):
continue
yield DamageHit(
timestamp=message.timestamp,
opcode=OPCODE_HEALTH_UPDATE,
victim=param(message.params, 0),
attacker=param(message.params, 6),
delta=float(delta),
health_after=health_after if isinstance(health_after, (int, float)) else None,
)
elif message.opcode == OPCODE_DAMAGE_BATCH:
deltas = param(message.params, 2) or []
health_afters = param(message.params, 3) or []
attackers = byte_list(param(message.params, 6))
for index, delta in enumerate(deltas):
if not isinstance(delta, (int, float)):
continue
attacker = attackers[index] if index < len(attackers) else None
health_after = health_afters[index] if index < len(health_afters) else None
yield DamageHit(
timestamp=message.timestamp,
opcode=OPCODE_DAMAGE_BATCH,
victim=param(message.params, 0),
attacker=attacker,
delta=float(delta),
health_after=health_after if isinstance(health_after, (int, float)) else None,
)
def entity_multipliers(path: str) -> Iterator[tuple]:
"""Yield ``(timestamp, entity, multiplier)`` from the entity-stats opcode."""
for message in iter_messages(path):
if message.kind != 'Event' or message.opcode != OPCODE_ENTITY_STATS:
continue
multiplier = param(message.params, 6)
if isinstance(multiplier, (int, float)):
yield message.timestamp, param(message.params, 0), float(multiplier)
def damage_type(message: DecodedMessage) -> Any:
"""Param 5 of a health update: an ability/hit category enum."""
return param(message.params, 5)
def perfect_scalar_chains(path: str, min_steps: int = 5) -> List[List[DamageHit]]:
"""Victims whose scalar-opcode health chain is perfectly consistent.
These are the calibration set for the duplicate test: a stream that merely
repeats known hits cannot survive being injected into an already-exact
chain, so the damage a stream adds to this set is genuine.
"""
by_victim: Dict[Any, List[DamageHit]] = {}
for hit in damage_hits(path):
by_victim.setdefault(hit.victim, []).append(hit)
perfect = []
for victim_hits in by_victim.values():
scalar = check_chain(victim_hits, include_batched=False)
if scalar.steps >= min_steps and scalar.breaks == 0:
perfect.append(victim_hits)
return perfect
@dataclass
class ChainReport:
"""Whether each victim's reported health can be explained by observed hits.
Every health update reports the health the victim was left at. Walking a
victim's hits in time order and applying each delta to the running total
should land exactly on the next reported value:
previous.health_after + delta == health_after
When it does not, something moved the victim's health that we did not
observe -- regeneration, food, an offline update, or simply a hit missing
from this stream. Those are ``breaks``.
The decisive property: a stream that is a *duplicate* of another adds no
information while perturbing the running total, so it can only increase
breaks. The correct encoding therefore has the fewest breaks.
"""
steps: int = 0
breaks: int = 0
@property
def break_rate(self) -> float:
return self.breaks / self.steps if self.steps else 0.0
def merge(self, other: 'ChainReport') -> 'ChainReport':
return ChainReport(self.steps + other.steps, self.breaks + other.breaks)
def check_chain(hits: List[DamageHit],
include_batched: bool) -> ChainReport:
"""Walk each victim's health chain using one encoding or both.
Healing is included in the walk (it is a real health change) but a step is
only counted when both endpoints reported their resulting health.
"""
by_victim: Dict[Any, List[DamageHit]] = {}
for hit in hits:
if not include_batched and hit.opcode == OPCODE_DAMAGE_BATCH:
continue
by_victim.setdefault(hit.victim, []).append(hit)
report = ChainReport()
for victim_hits in by_victim.values():
ordered = sorted(victim_hits, key=lambda h: (h.timestamp, h.opcode))
previous = ordered[0]
if previous.health_after is None:
continue
running = previous.health_after
for current in ordered[1:]:
if current.health_after is None:
previous = current
continue
report.steps += 1
if abs(running + current.delta - current.health_after) > 0.01:
report.breaks += 1
# Trust the server's reported value; re-anchor after any break.
running = current.health_after
previous = current
return report
+196
View File
@@ -0,0 +1,196 @@
"""End-to-end findings from the Armor Piercer capture.
Source: /tmp/aostats-party01.jsonl, a T5 Morgana dungeon run. bionicKatana
wore a T6_MAIN_CURSEDSTAFF@1 (Armor Piercer) from 16:48:10 to 16:52:40;
Froedrick712 shared the party and finished the mobs.
These tests establish the premise the whole effective-damage feature rests on:
that applying a debuff measurably raises another player's damage, that the
debuff's lifetime is visible, and that the responsible player is recoverable
from the packets.
The capture lives outside the repository, so everything here is skipped when it
is absent.
"""
import collections
import json
import os
import statistics
import pytest
CAPTURE = '/tmp/aostats-party01.jsonl'
BIOMIC = 90547
FROEDRICK = 90362
# Effect ids bionicKatana applies only while holding the cursed staff. They
# appear together on several victims within a millisecond, which is the
# multi-target beam of Armor Piercer.
ARMOR_PIERCER_EFFECTS = (3097, 3098, 3099)
# Armor Piercer's debuff lasts 4 seconds.
DEBUFF_SECONDS = 4.0
pytestmark = pytest.mark.skipif(
not os.path.exists(CAPTURE), reason='Armor Piercer capture not available')
def _records():
with open(CAPTURE, errors='replace') as handle:
for line in handle:
try:
yield json.loads(line)
except ValueError:
continue
def _is_photon_event(record, opcode):
if record.get('type') != 'photon_message':
return False
message = record.get('message') or {}
if message.get('code') != 1 or message.get('kind') != 'Event':
return False
return (message.get('params') or {}).get('252') == opcode
def effect_windows():
"""Victim -> timestamps at which Armor Piercer landed on it."""
windows = collections.defaultdict(list)
for record in _records():
if not _is_photon_event(record, 22):
continue
params = (record.get('message') or {}).get('params') or {}
appliers, effects = params.get('1'), params.get('2')
if not isinstance(appliers, list) or not isinstance(effects, list):
continue
if len(appliers) != len(effects):
continue
if BIOMIC in appliers and any(
e in ARMOR_PIERCER_EFFECTS for e in effects):
windows[params.get('0')].append(_ts(record['timestamp']))
return windows
def basic_hits(attacker):
"""(timestamp, victim, damage) for basic auto-attacks."""
out = []
for record in _records():
if record.get('type') != 'game_message':
continue
message = record.get('message') or {}
if message.get('name') != 'HealthUpdate':
continue
params = message.get('params') or {}
if params.get('6') != attacker or params.get('5') != 0:
continue
out.append((_ts(record['timestamp']), params.get('0'),
abs(params.get('2') or 0)))
return out
def _ts(stamp):
import datetime
return datetime.datetime.fromisoformat(stamp).timestamp()
def _static(name):
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
with open(os.path.join(root, 'src', 'static', name),
encoding='utf-8') as handle:
return json.load(handle)
# --- the premise -------------------------------------------------------------
def test_debuff_raises_another_players_damage():
"""The whole feature depends on this being true and measurable.
Froedrick712's basic hits on mob 78724 go 35 -> 48 -> 35 across a single
Armor Piercer application. Mob 78724 is a
T5_MOB_ROAMING_KEEPER_GIANT_CHAMPION with 136 armour.
"""
windows = effect_windows()
assert windows.get(78724), 'no Armor Piercer application found on 78724'
hits = [h for h in basic_hits(FROEDRICK) if h[1] == 78724]
applied = windows[78724][0]
inside = [d for t, _, d in hits
if 0 <= t - applied <= DEBUFF_SECONDS]
before = [d for t, _, d in hits if applied - 60 <= t < applied]
assert before, 'no baseline hits before the debuff'
assert inside, 'no hits inside the debuff window'
assert statistics.median(inside) > statistics.median(before)
def test_damage_returns_to_baseline_after_the_debuff():
"""The debuff expires, and the return to baseline is observable.
This is what makes the magnitude recoverable from data rather than needing
the spell definition: compare a victim's hits inside and outside the
window instead of trusting a static table.
"""
windows = effect_windows()
hits = [h for h in basic_hits(FROEDRICK) if h[1] == 78724]
applied = windows[78724][0]
inside = [d for t, _, d in hits
if 0 <= t - applied <= DEBUFF_SECONDS]
after = [d for t, _, d in hits if t - applied > DEBUFF_SECONDS]
assert inside and after
assert statistics.median(after) < statistics.median(inside)
def test_surplus_is_positive_across_the_capture():
"""Not a one-mob fluke: the same shift shows up over the whole run."""
windows = effect_windows()
hits = basic_hits(FROEDRICK)
def in_window(t, victim):
return any(0 <= t - applied <= DEBUFF_SECONDS
for applied in windows.get(victim, []))
inside = [d for t, v, d in hits if in_window(t, v)]
outside = [d for t, v, d in hits if not in_window(t, v)]
assert len(inside) >= 10
assert statistics.median(inside) > statistics.median(outside)
# Every hit inside a debuff window beats the outside median, which is what
# a genuine shift in the damage model looks like.
assert min(inside) > statistics.median(outside)
# --- the attribution chain ---------------------------------------------------
def test_applier_is_recoverable_without_inference():
"""The responsible player comes from the packet, not from the weapon.
This is better than the plan assumed: it removes the need to match spells
to equipped weapons for the common case.
"""
windows = effect_windows()
assert windows, 'no Armor Piercer applications found'
for victim, applied in windows.items():
assert victim is not None
assert applied
def test_mob_template_and_max_health_agree():
"""Mob 78724's template must agree with the hit points in the spawn."""
mob_armor = _static('mob_armor.json')
for record in _records():
if not _is_photon_event(record, 123):
continue
params = (record.get('message') or {}).get('params') or {}
if params.get('0') != 78724:
continue
entry = mob_armor[str(params.get('1'))]
assert entry['hitpointsmax'] == pytest.approx(params.get('13'))
assert entry['name'] == 'T5_MOB_ROAMING_KEEPER_GIANT_CHAMPION'
assert entry['armor'] == 136
return
pytest.fail('mob 78724 spawn not found in capture')
+31
View File
@@ -0,0 +1,31 @@
import requests
from src.gui.modules.views.list_view import icon
from src.utils import async_request
def test_get_weapon_icon_ignores_missing_weapon(monkeypatch):
called = []
monkeypatch.setattr(icon.async_request, 'get', lambda url: called.append(url))
assert icon.get_weapon_icon(None) is None
assert called == []
def test_async_request_catches_request_errors(monkeypatch):
queued = []
def raise_connection_error(_url, timeout=None):
raise requests.ConnectionError('dns failed')
class FakeQueue:
def put(self, item):
queued.append(item)
monkeypatch.setattr(async_request.requests, 'get', raise_connection_error)
monkeypatch.setattr(async_request, '_queue', FakeQueue())
async_request._async_req('https://example.invalid/icon')
assert queued[0].key == 'https://example.invalid/icon'
assert queued[0].value is None
+167
View File
@@ -0,0 +1,167 @@
import pytest
from src import backend_proxy
from src import engine
def test_native_backend_available_on_linux():
import src.utils.platform_utils as pu
assert backend_proxy.NATIVE_BACKEND_AVAILABLE == pu.is_linux()
def test_initialize_ok_with_native_backend(monkeypatch):
monkeypatch.setattr(backend_proxy, 'NATIVE_BACKEND_AVAILABLE', True)
assert backend_proxy.initialize() == backend_proxy.InitializationResult.Ok
def test_initialize_without_backend_returns_not_installed(monkeypatch):
if backend_proxy.BACKEND_AVAILABLE:
pytest.skip('pyaoaddons is installed')
monkeypatch.setattr(backend_proxy, 'NATIVE_BACKEND_AVAILABLE', False)
assert backend_proxy.initialize() == \
backend_proxy.InitializationResult.BackendNotInstalled
def test_subscribe_starts_native_backend(monkeypatch):
started = []
monkeypatch.setattr(backend_proxy, 'NATIVE_BACKEND_AVAILABLE', True)
monkeypatch.setattr(
backend_proxy, '_start_native_backend',
lambda callback: started.append(callback) or True)
callback = lambda event: event
result = backend_proxy.subscribe(callback)
assert started == [callback]
assert result is True
def test_subscribe_is_noop_without_backend(monkeypatch):
if backend_proxy.BACKEND_AVAILABLE:
pytest.skip('pyaoaddons is installed')
monkeypatch.setattr(backend_proxy, 'NATIVE_BACKEND_AVAILABLE', False)
assert backend_proxy.subscribe(lambda event: event) is False
def test_start_native_backend_uses_pipeline(monkeypatch):
import src.net.capture as capture_mod
monkeypatch.setattr(backend_proxy, '_capture', None)
created = {}
class FakeCapture:
def __init__(self, on_udp):
created['on_udp'] = on_udp
def start(self):
created['started'] = True
return True
monkeypatch.setattr(capture_mod, 'CaptureEngine', FakeCapture)
events = []
assert backend_proxy._start_native_backend(events.append) is True
assert created['started'] is True
assert callable(created['on_udp'])
assert backend_proxy._capture is not None
backend_proxy._capture = None
def test_start_native_backend_reports_start_failure(monkeypatch):
import src.net.capture as capture_mod
monkeypatch.setattr(backend_proxy, '_capture', None)
class FakeCapture:
def __init__(self, on_udp):
self.on_udp = on_udp
def start(self):
return False
monkeypatch.setattr(capture_mod, 'CaptureEngine', FakeCapture)
assert backend_proxy._start_native_backend(lambda event: event) is False
assert backend_proxy._capture is None
def test_initialize_ok_with_replay(monkeypatch):
monkeypatch.setattr(
backend_proxy.environment, 'replay_path', lambda: '/tmp/x.jsonl')
assert backend_proxy.initialize() == backend_proxy.InitializationResult.Ok
def test_subscribe_starts_replay_backend(monkeypatch):
monkeypatch.setattr(
backend_proxy.environment, 'replay_path', lambda: '/tmp/x.jsonl')
started = []
monkeypatch.setattr(
backend_proxy, '_start_replay_backend',
lambda callback: started.append(callback) or True)
callback = lambda event: event
assert backend_proxy.subscribe(callback) is True
assert started == [callback]
def test_start_replay_backend_uses_pipeline(monkeypatch):
import src.net.replay as replay_mod
monkeypatch.setattr(backend_proxy, '_replay', None)
created = {}
class FakeReplay:
def __init__(self, on_udp):
created['on_udp'] = on_udp
def start(self):
created['started'] = True
return True
monkeypatch.setattr(replay_mod, 'ReplayEngine', FakeReplay)
assert backend_proxy._start_replay_backend(lambda event: event) is True
assert created['started'] is True
assert callable(created['on_udp'])
assert backend_proxy._replay is not None
backend_proxy._replay = None
def test_start_replay_backend_reports_start_failure(monkeypatch):
import src.net.replay as replay_mod
monkeypatch.setattr(backend_proxy, '_replay', None)
class FakeReplay:
def __init__(self, on_udp):
self.on_udp = on_udp
def start(self):
return False
monkeypatch.setattr(replay_mod, 'ReplayEngine', FakeReplay)
assert backend_proxy._start_replay_backend(lambda event: event) is False
assert backend_proxy._replay is None
def test_engine_initialize_reports_subscribe_failure(monkeypatch):
monkeypatch.setattr(
engine.backend_proxy, 'initialize',
lambda: backend_proxy.InitializationResult.Ok)
monkeypatch.setattr(
engine.backend_proxy, 'subscribe',
lambda callback: False)
assert engine.initialize() == backend_proxy.InitializationResult.UnknownFailure
+249
View File
@@ -0,0 +1,249 @@
"""Findings about the Albion health-update protocol, verified against captures.
These tests double as the specification for the Phase 1 decode work. They read
raw ``photon_message`` records rather than the decoder's ``game_message``
stream, because several of the behaviours under test concern opcodes that
``src/decode/translate.py`` does not handle yet.
Captures live outside the repository and are skipped when absent.
"""
import collections
import statistics
import pytest
from capture_analysis import (
OPCODE_DAMAGE_BATCH,
OPCODE_ENTITY_STATS,
OPCODE_HEALTH_UPDATE,
DamageHit,
capture_paths,
check_chain,
damage_hits,
damage_type,
iter_messages,
param,
perfect_scalar_chains,
)
pytestmark = pytest.mark.skipif(
not capture_paths(),
reason='discovery captures are not available')
def _scalar_messages():
for path in capture_paths():
for message in iter_messages(path):
if message.opcode == OPCODE_HEALTH_UPDATE:
yield message
def _all_hits():
for path in capture_paths():
for hit in damage_hits(path):
yield hit
# --- Opcode 7 is additional damage, not a repeat of opcode 6 ---------------
def test_batched_damage_is_not_a_duplicate_of_scalar_damage():
"""Echoing known hits destroys an exact health chain; real E7 does not.
Each victim picked here has a scalar-opcode health chain that reconciles
perfectly. Injecting a stream that merely repeats those same hits makes
every step inconsistent, because the repeated delta is applied twice. If
the batched opcode were such a repeat it would behave the same way.
Rates are pooled across captures rather than compared per capture: a
single-break sample from a two-step victim would otherwise dominate.
"""
real_breaks = real_steps = 0
synthetic_breaks = synthetic_steps = 0
for path in capture_paths():
for group in perfect_scalar_chains(path):
base = check_chain(group, include_batched=False)
actual = check_chain(group, include_batched=True)
real_steps += actual.steps - base.steps
real_breaks += actual.breaks - base.breaks
echoed = list(group) + [
DamageHit(h.timestamp, OPCODE_DAMAGE_BATCH, h.victim,
h.attacker, h.delta, h.health_after)
for h in group]
doubled = check_chain(echoed, include_batched=True)
synthetic_steps += doubled.steps - base.steps
synthetic_breaks += doubled.breaks - base.breaks
assert real_steps > 20, f'only {real_steps} extra steps introduced'
assert synthetic_steps > 20, f'only {synthetic_steps} synthetic steps'
real_rate = real_breaks / real_steps
synthetic_rate = synthetic_breaks / synthetic_steps
assert real_rate < 0.25, \
f'real batched damage should not double-count, got {real_rate:.2%}'
assert synthetic_rate > 0.75, \
f'a genuine duplicate should double-count, got {synthetic_rate:.2%}'
def test_batched_damage_carries_substantial_volume():
"""The batched opcode accounts for a large share of total damage.
This is the size of the undercount that Phase 1 exists to fix.
"""
scalar = batched = 0.0
for hit in _all_hits():
if hit.delta >= 0:
continue
if hit.opcode == OPCODE_HEALTH_UPDATE:
scalar += -hit.delta
else:
batched += -hit.delta
assert scalar > 0 and batched > 0
share = batched / (scalar + batched)
assert 0.3 < share < 0.5, f'batched share of damage drifted to {share:.2%}'
def test_batched_damage_reports_health_after_each_hit():
"""Every batched hit carries its own resulting health and attacker.
These are the fields Phase 1 needs to credit damage without guessing.
"""
checked = 0
for hit in _all_hits():
if hit.opcode != OPCODE_DAMAGE_BATCH or hit.delta >= 0:
continue
assert hit.health_after is not None, 'batched hit without resulting health'
assert hit.attacker is not None, 'batched hit without an attacker'
checked += 1
assert checked > 100, f'only {checked} batched damage hits to check'
# --- Health-update parameter layout ---------------------------------------
def test_health_after_param_reconciles_with_deltas():
"""Param 3 is the victim's health once the hit has been applied."""
report = check_chain(list(_all_hits()), include_batched=False)
assert report.steps > 1000, f'only {report.steps} steps to reconcile'
assert report.break_rate < 0.6, \
f'param 3 does not reconcile (break rate {report.break_rate:.2%})'
def test_damage_type_separates_basic_hits_from_abilities():
"""Param 5 splits basic attacks (0, 1) from ability hits (2+).
The groups do not overlap and differ sharply in magnitude, which is what
makes param 5 useful for splitting damage by hit type.
"""
magnitudes = collections.defaultdict(list)
for message in _scalar_messages():
delta = param(message.params, 2)
if not isinstance(delta, (int, float)) or delta >= 0:
continue
magnitudes[damage_type(message)].append(-delta)
assert set(magnitudes) >= {0, 1, 2, 3}, f'unexpected param 5 domain: {sorted(magnitudes)}'
basic = magnitudes[0] + magnitudes[1]
abilities = magnitudes[2] + magnitudes[3]
assert statistics.median(basic) < statistics.median(abilities) * 0.5, \
f'basic {statistics.median(basic):.0f} vs ability ' \
f'{statistics.median(abilities):.0f} are not separable'
def test_max_health_param_presence_is_a_function_of_damage_type():
"""Param 7 is populated for exactly the param 5 values 2 and above.
"Populated" means a value of at least zero; basic hits carry -1 as a
placeholder. Presence therefore carries no information beyond param 5, so
param 7 adds no independent damage signal. Recorded so Phase 1 does not
model the same partition twice.
"""
populated = collections.defaultdict(set)
for message in _scalar_messages():
value = damage_type(message)
raw = param(message.params, 7)
populated[value].add(isinstance(raw, (int, float)) and raw >= 0)
for value, flags in populated.items():
assert len(flags) == 1, \
f'param 7 presence varies within param 5={value}: {flags}'
absent = {value for value, flags in populated.items() if flags == {False}}
assert absent == {0, 1}, f'param 7 absent for {sorted(absent)}, expected 0 and 1'
# --- Opcode 18 param 6 is not a damage multiplier --------------------------
def test_entity_stats_multiplier_does_not_track_damage():
"""Damage does not change across opcode 18 multiplier transitions.
This refutes the Phase 0 hypothesis that opcode 18 carries a live incoming
damage multiplier. The multiplier moves while the median damage either side
of the transition stays flat, so it cannot be used to infer mitigation
state. Recorded here so Phase 2 does not build on it.
"""
import statistics as stats
followed = 0
for path in capture_paths():
multipliers = collections.defaultdict(list)
damage = collections.defaultdict(list)
for message in iter_messages(path):
if message.opcode == OPCODE_ENTITY_STATS:
value = param(message.params, 6)
if isinstance(value, (int, float)):
multipliers[param(message.params, 0)].append(
(message.timestamp, value))
for hit in damage_hits(path):
damage[hit.victim].append((hit.timestamp, hit))
for entity, sequence in multipliers.items():
if not damage.get(entity):
continue
for index in range(1, len(sequence)):
(before_ts, before_m), (after_ts, after_m) = sequence[index - 1], sequence[index]
if before_m == after_m:
continue
earlier = [-hit.delta for ts, hit in damage[entity]
if hit.delta < 0 and before_ts < ts <= after_ts]
later = [-hit.delta for ts, hit in damage[entity]
if hit.delta < 0 and ts > after_ts][:20]
if len(earlier) < 3 or len(later) < 3:
continue
followed += 1
expected = abs(after_m / before_m)
observed = abs(stats.median(later) / stats.median(earlier))
assert abs(observed - expected) > 0.2 * max(expected, 1e-9), \
f'damage tracked the multiplier x{expected:.2f} ' \
f'(observed x{observed:.2f}) -- it may be a damage multiplier'
assert followed > 0, 'no opcode 18 multiplier transitions with surrounding damage'
def test_entity_stats_multiplier_is_often_constant_per_entity():
"""Where param 6 varies, it is a minority of samples for that entity.
Consistent with a cosmetic or interpolation factor rather than a
continuously tracked combat statistic.
"""
unstable = seen = 0
for path in capture_paths():
per_entity = collections.defaultdict(collections.Counter)
for message in iter_messages(path):
if message.opcode != OPCODE_ENTITY_STATS:
continue
value = param(message.params, 6)
if isinstance(value, (int, float)):
per_entity[param(message.params, 0)][round(value, 4)] += 1
for counts in per_entity.values():
seen += 1
if len(counts) > 1:
unstable += 1
assert seen > 0, 'no opcode 18 records found'
assert unstable / seen < 0.5, \
f'{unstable}/{seen} entities vary, too many for a cosmetic value'
+74
View File
@@ -0,0 +1,74 @@
from src.stats.combat_stats import CombatStats
class VisibleAll:
def test(self, _name):
return True
class VisibleNone:
def test(self, _name):
return False
def test_self_healing_counts_while_in_combat():
stats = CombatStats(VisibleAll())
stats.on_player_appeared(0, 'Healer')
stats.on_enter_combat(0)
stats.on_health_received(0, 0, 100.0)
combat_healing = stats.players_healing()
total_healing = stats.players_total_healing()
assert combat_healing[0].name == 'Healer'
assert combat_healing[0].value == 100.0
assert total_healing[0].value == 100.0
def test_total_healing_includes_post_combat_healing():
stats = CombatStats(VisibleAll())
stats.on_player_appeared(0, 'Healer')
stats.on_enter_combat(0)
stats.on_health_received(0, 0, 100.0)
stats.on_leave_combat(0)
stats.on_health_received(0, 0, 50.0)
combat_healing = stats.players_healing()
total_healing = stats.players_total_healing()
assert combat_healing[0].value == 100.0
assert total_healing[0].value == 150.0
def test_damage_taken_accumulates_per_player():
stats = CombatStats(VisibleAll())
stats.on_player_appeared(0, 'Tank')
stats.on_damage_taken(0, 250.0)
stats.on_damage_taken(0, 150.0)
damage_taken = stats.players_damage_taken()
assert damage_taken[0].name == 'Tank'
assert damage_taken[0].value == 400.0
assert damage_taken[0].value_per_second == 0.0
def test_damage_taken_counts_out_of_combat():
stats = CombatStats(VisibleAll())
stats.on_player_appeared(0, 'Tank')
stats.on_damage_taken(0, 75.0)
assert stats.players_damage_taken()[0].value == 75.0
def test_damage_taken_excludes_non_visible_players():
stats = CombatStats(VisibleNone())
stats.on_player_appeared(0, 'Enemy')
stats.on_damage_taken(0, 300.0)
assert stats.players_damage_taken() == []
+58
View File
@@ -0,0 +1,58 @@
import os
from src.utils import config
from src.utils import platform_utils
def _set_os(monkeypatch, system):
monkeypatch.setattr(platform_utils, 'system', lambda: system)
def test_config_path_linux_uses_xdg_config_home(monkeypatch, tmp_path):
_set_os(monkeypatch, platform_utils.LINUX)
monkeypatch.setenv('XDG_CONFIG_HOME', str(tmp_path))
assert config.get_config_path() == os.path.join(
str(tmp_path), platform_utils.APP_DIR_NAME, 'albion-online-stats.cfg')
def test_config_path_linux_falls_back_to_home(monkeypatch, tmp_path):
_set_os(monkeypatch, platform_utils.LINUX)
monkeypatch.delenv('XDG_CONFIG_HOME', raising=False)
monkeypatch.setenv('HOME', str(tmp_path))
assert config.get_config_path() == os.path.join(
str(tmp_path), '.config', platform_utils.APP_DIR_NAME,
'albion-online-stats.cfg')
def test_config_path_windows_uses_appdata(monkeypatch, tmp_path):
_set_os(monkeypatch, platform_utils.WINDOWS)
monkeypatch.setenv('APPDATA', str(tmp_path))
assert config.get_config_path() == os.path.join(
str(tmp_path), platform_utils.APP_DIR_NAME, 'albion-online-stats.cfg')
def test_config_path_falls_back_to_script_dir(monkeypatch):
_set_os(monkeypatch, 'SomethingElse')
assert os.path.basename(config.get_config_path()) == 'albion-online-stats.cfg'
def test_config_creates_missing_directory(monkeypatch, tmp_path):
_set_os(monkeypatch, platform_utils.LINUX)
monkeypatch.setenv('XDG_CONFIG_HOME', str(tmp_path))
monkeypatch.setattr(config, '_config', None)
expected = os.path.join(
str(tmp_path), platform_utils.APP_DIR_NAME, 'albion-online-stats.cfg')
cfg = config.config()
assert os.path.isfile(expected)
assert cfg['window']['width'] == 1280
assert cfg['window']['height'] == 720
assert cfg['window']['fullscreen'] is True
config._config = None
+721
View File
@@ -0,0 +1,721 @@
import struct
import pytest
from src.decode import photon
from src.decode import party_memory
from src.decode import translate
from src.decode.photon import PhotonDecoder, decode_message18
from src.decode.translate import into_game_message
from src.decode.world import IdCache, World
from src.net.capture import _extract_udp_payload
from src.utils import platform_utils
# --- Protocol18 value builders -------------------------------------------------
def p18_short(value):
return bytes([photon.P18['Short']]) + struct.pack('<h', value)
def p18_string(value):
data = value.encode('utf-8')
return bytes([photon.P18['String']]) + bytes([len(data)]) + data
def p18_compressed_int(value):
zz = (value << 1) if value >= 0 else ((-value << 1) - 1)
out = bytes([photon.P18['CompressedInt']])
while True:
b = zz & 0x7F
zz >>= 7
if zz:
out += bytes([b | 0x80])
else:
return out + bytes([b])
def params_table(entries):
out = bytes([len(entries)])
for key, encoded in entries:
out += bytes([key]) + encoded
return out
def event_payload(opcode, entries):
table = params_table([(252, p18_short(opcode))] + list(entries))
return bytes([0xF3, 0x04, 0x01]) + table
def flagged_event_payload(opcode, entries):
table = params_table([(252, p18_short(opcode))] + list(entries))
return bytes([0xF3, 0x84, 0x01]) + table
def response_payload(opcode, entries):
table = params_table([(253, p18_short(opcode))] + list(entries))
debug = bytes([photon.P18['Null']])
return bytes([0xF3, 0x03, 0x01]) + struct.pack('<h', 0) + debug + table
def enet_packet(command, msg_bytes):
length = 12 + len(msg_bytes)
header = struct.pack('>HBBI', 0, 0, 1, 0) + struct.pack('>I', 0)
command_header = struct.pack('>BBBB', command, 0, 0, 0)
command_header += struct.pack('>I', length) + struct.pack('>I', 0)
return header + command_header + msg_bytes
def enet_unreliable_packet(command, msg_bytes):
unreliable_seq = struct.pack('>I', 17)
length = 12 + len(unreliable_seq) + len(msg_bytes)
header = struct.pack('>HBBI', 0, 0, 1, 0) + struct.pack('>I', 0)
command_header = struct.pack('>BBBB', command, 0, 0, 0)
command_header += struct.pack('>I', length) + struct.pack('>I', 0)
return header + command_header + unreliable_seq + msg_bytes
# --- Protocol18 primitives ------------------------------------------------------
def test_varint_roundtrip():
assert photon.rd_varint(bytes([0x00]), 0) == (0, 1)
assert photon.rd_varint(bytes([0x80, 0x01]), 0) == (128, 2)
assert photon.rd_varint(bytes([0xAC, 0x02]), 0) == (300, 2)
def test_zigzag():
assert photon.zigzag(0) == 0
assert photon.zigzag(1) == -1
assert photon.zigzag(2) == 1
assert photon.zigzag(3) == -2
def test_decode_params_and_compressed_int():
table = params_table([(0, p18_compressed_int(280962)),
(2, p18_string('bionicKatana')),
(3, p18_compressed_int(4))])
params, pos = photon.decode_params18(table, 0)
assert params[0] == 280962
assert params[2] == 'bionicKatana'
assert params[3] == 4
assert pos == len(table)
def test_decode_message18_event():
payload = event_payload(1, [(0, p18_compressed_int(277536))])
message, pos = decode_message18(payload, 0)
assert message.kind == 'Event'
assert message.code == 1
assert message.params[252] == 1
assert message.params[0] == 277536
assert pos == len(payload)
def test_decode_message18_flagged_event():
payload = flagged_event_payload(1, [(0, p18_compressed_int(277536))])
message, pos = decode_message18(payload, 0)
assert message.kind == 'Event'
assert message.params[252] == 1
assert message.params[0] == 277536
assert pos == len(payload)
# --- eNet envelope + fragments --------------------------------------------------
def test_decode_packet_reliable():
decoder = PhotonDecoder()
packet = enet_packet(
photon.CMD_SEND_RELIABLE, event_payload(90, [(0, p18_short(7))]))
messages = decoder.decode_packet(packet)
assert len(messages) == 1
assert messages[0].params[252] == 90
def test_decode_packet_observed_unreliable_fragment_command():
decoder = PhotonDecoder()
packet = enet_unreliable_packet(
photon.CMD_SEND_UNRELIABLE_FRAGMENT,
flagged_event_payload(1, [(0, p18_short(7))]))
messages = decoder.decode_packet(packet)
assert len(messages) == 1
assert messages[0].params[252] == 1
assert messages[0].params[0] == 7
def test_fragment_reassembly():
decoder = PhotonDecoder()
full = event_payload(29, [(0, p18_short(1234))])
split = 5
parts = [full[i:i + split] for i in range(0, len(full), split)]
messages = []
for i, part in enumerate(parts):
start_seq, count = 5, len(parts)
length = 12 + photon.FRAG_HEADER_LEN + len(part)
header = struct.pack('>HBBI', 0, 0, 1, 0) + struct.pack('>I', 0)
cmd = struct.pack('>BBBB', photon.CMD_SEND_FRAGMENT, 0, 0, 0)
cmd += struct.pack('>I', length) + struct.pack('>I', 0)
cmd += struct.pack('>IIIII', start_seq, count, i, len(full), i * split)
messages.extend(decoder.decode_packet(header + cmd + part))
assert len(messages) == 1
assert messages[0].params[252] == 29
assert messages[0].params[0] == 1234
# --- translate ------------------------------------------------------------------
@pytest.mark.parametrize('opcode,name', [
(1, 'Leave'),
(6, 'HealthUpdate'),
(29, 'NewCharacter'),
(32, 'ItemGained'),
(62, 'TakeSilver'),
(82, 'UpdateFame'),
(90, 'CharacterEquipmentChanged'),
(91, 'RegenerationHealthChanged'),
(166, 'KnockedDown'),
(231, 'PartyJoined'),
(233, 'PartyPlayerJoined'),
(235, 'PartyPlayerLeft'),
])
def test_event_opcode_translation(opcode, name):
message, _ = decode_message18(event_payload(opcode, []), 0)
game = into_game_message(message)
assert game is not None
assert game.name == name
def test_operation_translation():
message, _ = decode_message18(response_payload(2, [(0, p18_short(63))]), 0)
game = into_game_message(message)
assert game is not None
assert game.name == 'Join'
def test_unknown_opcode_ignored():
message, _ = decode_message18(event_payload(9999, []), 0)
assert into_game_message(message) is None
def test_party_roster_without_opcode_translates():
message = photon.PhotonMessage('Event', 1, {
0: 123,
9: ['bionicKatana', 'Sweetpea23042'],
}, None, None)
game = into_game_message(message)
assert game is not None
assert game.name == 'PartyRoster'
assert translate.msg_party_roster_names(game) == [
'bionicKatana', 'Sweetpea23042']
def test_unlock_response_string_lists_are_not_party_rosters():
message = photon.PhotonMessage('Response', 1, {
9: ['UNLOCKED_CLAIMABLE', 'UNLOCKED_CLAIMABLE'],
}, None, None)
assert into_game_message(message) is None
# --- world ----------------------------------------------------------------------
def game(name, params=None):
return translate.GameMessage(name, 0, params or {})
def test_id_cache_reuses_id_for_name():
cache = IdCache()
cache.save(100, 'Alice')
assert cache.get_static_id(100) == 0
cache.save(200, 'Alice')
assert cache.get_static_id(200) == 0
assert cache.get_static_id(100) is None
assert cache.get_static_id(300) is None
def test_world_new_character_player_appeared():
world = World()
events = world.transform(game('NewCharacter', {0: 1234, 1: 'Alice'}))
names = [e['name'] for e in events]
assert 'PlayerAppeared' in names
appeared = next(e for e in events if e['name'] == 'PlayerAppeared')
assert appeared['value'] == {'id': 0, 'name': 'Alice'}
def test_world_join_emits_zone_change_and_main_player():
world = World()
events = world.transform(game('Join', {0: 63, 2: 'Alice'}))
assert events[0] == {'name': 'ZoneChange'}
assert events[1]['name'] == 'MainPlayerAppeared'
assert world.main_player_id == 0
second = world.transform(game('Join', {0: 77, 2: 'Alice'}))
assert {'name': 'ZoneChange'} not in second
def test_world_main_player_leave_emits_zone_change():
world = World()
world.transform(game('Join', {0: 63, 2: 'Alice'}))
events = world.transform(game('Leave', {0: 63}))
assert events == [{'name': 'ZoneChange'}]
def test_world_health_update_damage_and_heal():
world = World()
world.transform(game('NewCharacter', {0: 10, 1: 'Victim'}))
world.transform(game('NewCharacter', {0: 20, 1: 'Attacker'}))
damage = world.transform(game('HealthUpdate', {0: 10, 6: 20, 2: -80.0}))
assert damage[0]['name'] == 'DamageDone'
assert damage[0]['value']['source'] == 1 # attacker
assert damage[0]['value']['target'] == 0 # victim
assert damage[0]['value']['value'] == 80.0
assert damage[1]['name'] == 'DamageTaken'
assert damage[1]['value']['source'] == 0 # victim
assert damage[1]['value']['value'] == 80.0
heal = world.transform(game('HealthUpdate', {0: 10, 6: 20, 2: 40.0}))
assert heal[0]['name'] == 'HealthReceived'
assert heal[0]['value']['source'] == 1
assert heal[0]['value']['value'] == 40.0
assert len(heal) == 1 # healing is not damage taken
def test_world_health_update_unknown_actor_emits_damage_taken():
world = World()
world.transform(game('NewCharacter', {0: 10, 1: 'Victim'}))
events = world.transform(game('HealthUpdate', {0: 10, 6: 999, 2: -50.0}))
assert len(events) == 1
assert events[0]['name'] == 'DamageTaken'
assert events[0]['value']['source'] == 0
assert events[0]['value']['value'] == 50.0
def test_world_health_update_unknown_victim_and_actor_dropped():
world = World()
# neither the attacker nor the victim has a known static id
assert world.transform(game('HealthUpdate', {0: 999, 6: 888, 2: -50.0})) == []
def test_world_health_update_known_actor_unknown_target_emits_damage_done():
world = World()
world.transform(game('NewCharacter', {0: 20, 1: 'Attacker'}))
events = world.transform(game('HealthUpdate', {0: 999, 6: 20, 2: -50.0}))
assert len(events) == 1
assert events[0]['name'] == 'DamageDone'
assert events[0]['value']['source'] == 0
assert events[0]['value']['target'] is None
# --- Health update accessors ---------------------------------------------------
def test_health_update_accessors():
msg = game('HealthUpdate', {0: 10, 2: -80.0, 3: 420.0, 5: 3, 6: 20, 7: -1})
assert translate.msg_subject_id(msg) == 10 # param 0 is the victim
assert translate.msg_attacker_id(msg) == 20 # param 6 is the attacker
assert translate.msg_value(msg) == -80.0
assert translate.msg_health_after(msg) == 420.0
assert translate.msg_hit_type(msg) == 3
def test_health_update_accessors_tolerate_missing_params():
msg = game('HealthUpdate', {})
assert translate.msg_subject_id(msg) == 0
assert translate.msg_attacker_id(msg) == 0
assert translate.msg_value(msg) == 0.0
assert translate.msg_health_after(msg) is None
assert translate.msg_hit_type(msg) is None
def test_byte_list_unpacks_every_encoded_shape():
# Batched params arrive as raw bytes, as the discovery log's dict form, or
# as an already-decoded list depending on the decoder path.
assert translate._as_byte_list(b'\x01\x02') == [1, 2]
assert translate._as_byte_list({'bytes_hex': 'c5c5', 'len': 2}) == [197, 197]
assert translate._as_byte_list([3, 4]) == [3, 4]
assert translate._as_byte_list(None) == []
def test_batched_health_update_accessors():
msg = game('BatchedHealthUpdate', {
0: 76,
1: [11, 12],
2: [-41.0, -135.0],
3: [3416.0, 3281.0],
5: b'\x00\x02',
6: b'\xc5\x58',
})
assert translate.msg_batched_victim_id(msg) == 76
assert translate.msg_batched_ticks(msg) == [11, 12]
assert translate.msg_batched_values(msg) == [-41.0, -135.0]
assert translate.msg_batched_health_after(msg) == [3416.0, 3281.0]
assert translate.msg_batched_hit_types(msg) == [0, 2]
assert translate.msg_batched_attacker_ids(msg) == [197, 88]
# --- Batched health update -----------------------------------------------------
def test_world_batched_health_update_emits_one_event_per_hit():
world = World()
world.transform(game('NewCharacter', {0: 10, 1: 'Victim'}))
world.transform(game('NewCharacter', {0: 20, 1: 'Attacker'}))
world.transform(game('NewCharacter', {0: 30, 1: 'Other'}))
events = world.transform(game('BatchedHealthUpdate', {
0: 10,
2: [-41.0, -135.0],
3: [3416.0, 3281.0],
5: b'\x00\x02',
6: b'\x14\x1e',
}))
# two hits, each producing DamageDone and DamageTaken
assert len(events) == 4
assert [e['name'] for e in events] == [
'DamageDone', 'DamageTaken', 'DamageDone', 'DamageTaken']
assert [e['value']['value'] for e in events] == [41.0, 41.0, 135.0, 135.0]
# the attacker differs per hit and must be credited per hit, not per packet
assert events[0]['value']['source'] == 1 # attacker 20
assert events[2]['value']['source'] == 2 # attacker 30
assert [e['value']['hit_type'] for e in (events[0], events[2])] == [0, 2]
assert [e['value']['health_after'] for e in (events[0], events[2])] == [3416.0, 3281.0]
def test_world_batched_health_update_skips_zero_and_unknown():
world = World()
world.transform(game('NewCharacter', {0: 10, 1: 'Victim'}))
world.transform(game('NewCharacter', {0: 20, 1: 'Attacker'}))
events = world.transform(game('BatchedHealthUpdate', {
0: 10, 2: [0.0, -25.0], 3: [500.0, 475.0], 6: b'\x14\x14'}))
assert [e['name'] for e in events] == ['DamageDone', 'DamageTaken']
assert events[0]['value']['value'] == 25.0
# a victim nobody tracks, hit by nobody tracked, produces nothing
assert world.transform(game('BatchedHealthUpdate', {
0: 777, 2: [-10.0], 3: [90.0], 6: b'\x88'})) == []
def test_world_batched_health_update_tolerates_short_arrays():
"""A missing attacker list must not raise or misattribute the hit."""
world = World()
world.transform(game('NewCharacter', {0: 10, 1: 'Victim'}))
events = world.transform(game('BatchedHealthUpdate', {
0: 10, 2: [-25.0], 3: [475.0]}))
assert [e['name'] for e in events] == ['DamageTaken']
assert events[0]['value']['source'] == 0
def test_world_batched_health_update_empty_yields_nothing():
world = World()
world.transform(game('NewCharacter', {0: 10, 1: 'Victim'}))
assert world.transform(game('BatchedHealthUpdate', {0: 10, 2: []})) == []
def test_batched_health_update_opcode_is_translated():
from src.decode.pipeline import Pipeline
events = []
pipeline = Pipeline(events.append)
payload = enet_unreliable_packet(
0x07, event_payload(7, [(0, p18_short(76)), (2, p18_string('x'))]))
pipeline.on_udp(payload)
# recognised as a game message even though it carries no usable deltas
assert events == []
def test_world_regeneration_combat_states():
world = World()
world.transform(game('NewCharacter', {0: 10, 1: 'Alice'}))
enter = world.transform(game('RegenerationHealthChanged', {0: 10}))
assert enter[0]['name'] == 'EnterCombat'
leave = world.transform(game('RegenerationHealthChanged', {0: 10, 4: 5.0}))
assert leave[0]['name'] == 'LeaveCombat'
def test_world_knocked_down_leaves_combat():
world = World()
world.transform(game('NewCharacter', {0: 10, 1: 'Alice'}))
events = world.transform(game('KnockedDown', {0: 10}))
assert events[0]['name'] == 'LeaveCombat'
def test_world_update_fame_uses_gained():
world = World()
world.transform(game('NewCharacter', {0: 10, 1: 'Alice'}))
events = world.transform(game('UpdateFame', {0: 10, 1: 5000000, 2: 30000}))
assert events[0]['name'] == 'UpdateFame'
assert events[0]['value']['value'] == pytest.approx(3.0)
def test_world_update_fame_delta_from_total():
world = World()
world.transform(game('NewCharacter', {0: 10, 1: 'Alice'}))
assert world.transform(game('UpdateFame', {0: 10, 1: 2000000})) == []
events = world.transform(game('UpdateFame', {0: 10, 1: 2001000}))
assert events[0]['value']['value'] == pytest.approx(0.1)
def test_world_update_fame_applies_bonus_factor():
world = World()
world.transform(game('NewCharacter', {0: 10, 1: 'Alice'}))
events = world.transform(
game('UpdateFame', {0: 10, 1: 5000000, 2: 30000, 17: 0.25}))
assert events[0]['value']['value'] == pytest.approx(3.75)
def test_world_update_fame_applies_premium_and_satchel():
world = World()
world.transform(game('NewCharacter', {0: 10, 1: 'Alice'}))
events = world.transform(
game('UpdateFame', {0: 10, 1: 5000000, 2: 30000, 5: True, 10: 10000}))
assert events[0]['value']['value'] == pytest.approx(5.5)
def test_world_item_gained_emits_collected_item():
world = World()
world.transform(game('Join', {0: 63, 2: 'Alice'}))
events = world.transform(game('ItemGained', {1: 522, 2: 3, 4: 10000000}))
# Item 522 is T1_SILVERBAG_NONTRADABLE in the current game data. This test
# previously expected T4_MEAL_SALAD_FISH@3, which is what the stale item id
# table claimed; ids are reassigned between game builds, and that table
# resolved 0 of 8 slots on a real equipment array.
assert events == [{
'name': 'ItemCollected',
'value': {
'item_id': 522,
'item_name': 'T1_SILVERBAG_NONTRADABLE',
'quantity': 3,
'estimated_value': 10000000,
},
}]
def test_world_item_gained_waits_for_main_player_join():
world = World()
assert world.transform(game('ItemGained', {0: 293153, 1: 11898, 2: 1})) == []
world.transform(game('NewCharacter', {0: 10, 1: 'SomeoneElse'}))
assert world.transform(game('ItemGained', {0: 293153, 1: 11898, 2: 1})) == []
def test_world_item_gained_uses_display_name_and_deduplicates():
world = World()
world.transform(game('Join', {0: 63, 2: 'Alice'}))
first = world.transform(game('ItemGained', {0: 293153, 1: 11898, 2: 1}))
duplicate = world.transform(game('ItemGained', {0: 293153, 1: 11898, 2: 1}))
assert first == [{
'name': 'ItemCollected',
'value': {
'item_id': 11898,
'item_name': 'Keeper Memory - Shameless or Daring',
'quantity': 1,
},
}]
assert duplicate == []
def test_world_take_silver_tracks_main_player():
world = World()
world.transform(game('Join', {0: 63, 2: 'Alice'}))
events = world.transform(game('TakeSilver', {0: 63, 3: 648351}))
assert events[0]['name'] == 'SilverGained'
assert events[0]['value']['silver_type'] == 'looted'
assert events[0]['value']['value'] == pytest.approx(64.8351)
def test_world_take_silver_subtracts_taxes():
world = World()
world.transform(game('Join', {0: 63, 2: 'Alice'}))
events = world.transform(
game('TakeSilver', {0: 63, 3: 500000, 4: 20000, 5: 10000, 6: 5000}))
assert events[0]['value']['value'] == pytest.approx(46.5)
def test_world_take_silver_ignores_other_players():
world = World()
world.transform(game('Join', {0: 63, 2: 'Alice'}))
world.transform(game('NewCharacter', {0: 70, 1: 'Bob'}))
assert world.transform(game('TakeSilver', {0: 70, 3: 450000})) == []
def test_world_take_silver_waits_for_main_player_join():
world = World()
assert world.transform(game('TakeSilver', {0: 63, 3: 450000})) == []
def test_world_unconsumed_equipment_replayed_on_new_character():
world = World()
# equipment arrives before the player is named -> buffered
assert world.transform(
game('CharacterEquipmentChanged', {0: 55, 2: [0, 1]})) == []
events = world.transform(game('NewCharacter', {0: 55, 1: 'Alice'}))
names = [e['name'] for e in events]
assert 'PlayerAppeared' in names
assert 'UpdateItems' in names
def test_party_events_from_structures():
world = World()
world.party.set_main_player_name('Alice')
world.cache.save(1, 'Alice')
joined = world.transform(
game('PartyJoined', {4: [[1, 0], [2, 0]], 5: ['Alice', 'Bob']}))
assert joined[0]['name'] == 'UpdateParty'
assert joined[0]['value']['player_names'] == ['Alice', 'Bob']
left = world.transform(game('PartyPlayerLeft', {1: [2, 0]}))
assert left[0]['value']['player_names'] == ['Alice']
def test_party_roster_event_updates_party():
world = World()
events = world.transform(game('PartyRoster', {
9: ['bionicKatana', 'Sweetpea23042'],
}))
assert events == [{
'name': 'UpdateParty',
'value': {'player_names': ['bionicKatana', 'Sweetpea23042']},
}]
def test_remembered_party_reemits_on_join(monkeypatch, tmp_path):
monkeypatch.setattr(platform_utils, 'config_dir', lambda: str(tmp_path))
party_memory.save_last_party([
'bionicKatana', 'fatbrick', 'Froedrick712', 'rainbowShade'])
world = World(remember_last_party=True)
events = world.transform(game('Join', {0: 98, 2: 'bionicKatana'}))
assert events[-1] == {
'name': 'UpdateParty',
'value': {'player_names': [
'bionicKatana', 'fatbrick', 'Froedrick712', 'rainbowShade']},
}
def test_party_inference_grows_during_zone_load(monkeypatch, tmp_path):
monkeypatch.setattr(platform_utils, 'config_dir', lambda: str(tmp_path))
world = World(remember_last_party=True)
world.transform(game('NewCharacter', {0: 97, 1: 'rainbowShade'}))
join = world.transform(game('Join', {0: 98, 2: 'bionicKatana'}))
fatbrick = world.transform(game('NewCharacter', {0: 161, 1: 'fatbrick'}))
froedrick = world.transform(game('NewCharacter', {0: 211, 1: 'Froedrick712'}))
assert _last_party_names(join) == [
'rainbowShade', 'bionicKatana']
assert _last_party_names(fatbrick) == [
'rainbowShade', 'bionicKatana', 'fatbrick']
assert _last_party_names(froedrick) == [
'rainbowShade', 'bionicKatana', 'fatbrick', 'Froedrick712']
assert party_memory.load_last_party() == [
'rainbowShade', 'bionicKatana', 'fatbrick', 'Froedrick712']
def test_party_roster_saves_even_when_autoload_disabled(monkeypatch, tmp_path):
monkeypatch.setattr(platform_utils, 'config_dir', lambda: str(tmp_path))
world = World(remember_last_party=False)
world.transform(game('PartyRoster', {
9: ['bionicKatana', 'rainbowShade', 'fatbrick', 'Froedrick712'],
}))
assert party_memory.load_last_party() == [
'bionicKatana', 'rainbowShade', 'fatbrick', 'Froedrick712']
restarted = World(remember_last_party=True)
events = restarted.transform(game('Join', {0: 98, 2: 'bionicKatana'}))
assert events[-1]['value']['player_names'] == [
'bionicKatana', 'rainbowShade', 'fatbrick', 'Froedrick712']
def test_party_disband_preserves_remembered_party(monkeypatch, tmp_path):
monkeypatch.setattr(platform_utils, 'config_dir', lambda: str(tmp_path))
world = World(remember_last_party=True)
world.transform(game('PartyRoster', {
9: ['bionicKatana', 'fatbrick'],
}))
assert party_memory.load_last_party() == ['bionicKatana', 'fatbrick']
world.transform(game('PartyDisbanded'))
assert party_memory.load_last_party() == ['bionicKatana', 'fatbrick']
assert world.party.last_names == []
def _last_party_names(events):
party_events = [e for e in events if e['name'] == 'UpdateParty']
return party_events[-1]['value']['player_names']
def test_party_main_player_left_disbands():
world = World()
world.party.set_main_player_name('Alice')
world.transform(game('PartyJoined', {4: [[1, 0], [2, 0]],
5: ['Alice', 'Bob']}))
events = world.transform(game('PartyPlayerLeft', {1: [1, 0]}))
assert events[0]['value']['player_names'] == []
# --- capture frame extraction ---------------------------------------------------
def build_ethernet_ipv4_udp(src_port, dst_port, payload):
udp = struct.pack('>HHHH', src_port, dst_port, 8 + len(payload), 0) + payload
ip = bytearray(20)
ip[0] = 0x45
ip[2:4] = struct.pack('>H', 20 + len(udp))
ip[9] = 17
ip[12:16] = bytes([10, 0, 0, 1])
ip[16:20] = bytes([10, 0, 0, 2])
ethernet = bytes(12) + struct.pack('>H', 0x0800)
return ethernet + bytes(ip) + udp
def test_extract_udp_payload_game_port():
frame = build_ethernet_ipv4_udp(12345, 5056, b'hello')
assert _extract_udp_payload(frame) == b'hello'
def test_extract_udp_payload_other_port_ignored():
frame = build_ethernet_ipv4_udp(12345, 1234, b'hello')
assert _extract_udp_payload(frame) is None
def test_extract_udp_payload_with_vlan():
inner = build_ethernet_ipv4_udp(5056, 12345, b'world')
header = inner[:12]
tagged = header + struct.pack('>H', 0x8100) + struct.pack('>H', 42) + inner[12:]
assert _extract_udp_payload(tagged) == b'world'
def build_ethernet_ipv6_udp(src_port, dst_port, payload):
udp = struct.pack('>HHHH', src_port, dst_port, 8 + len(payload), 0) + payload
ip = bytearray(40)
ip[0] = 0x60
ip[6] = 17
ip[8:24] = bytes.fromhex('fe800000000000000000000000000001')
ip[24:40] = bytes.fromhex('fe800000000000000000000000000002')
ethernet = bytes(12) + struct.pack('>H', 0x86DD)
return ethernet + bytes(ip) + udp
def test_extract_udp_payload_ipv6():
frame = build_ethernet_ipv6_udp(5056, 12345, b'v6')
assert _extract_udp_payload(frame) == b'v6'
def test_interface_names_excludes_loopback():
from src.net.capture import CaptureEngine
names = CaptureEngine.interface_names()
assert isinstance(names, list)
assert 'lo' not in names
+42
View File
@@ -0,0 +1,42 @@
import json
from src import environment
from src.decode import discovery
def test_qt_args_removes_app_specific_options():
assert environment.qt_args([
'aostats', '--verbose', '--log-path', '/tmp/capture.jsonl',
'--style', 'fusion']) == ['aostats', '--style', 'fusion']
assert environment.qt_args([
'aostats', '--log-path=/tmp/capture.jsonl']) == ['aostats']
def test_discovery_log_skips_replay_source(monkeypatch, tmp_path):
path = tmp_path / 'capture.jsonl'
monkeypatch.setattr(discovery, 'discovery_log_path', lambda: str(path))
monkeypatch.setattr(discovery, 'replay_path', lambda: str(path))
monkeypatch.setattr(discovery, '_initialized', False)
discovery.log('game_message', params={})
assert not path.exists()
def test_discovery_log_writes_jsonl_with_item_annotations(monkeypatch, tmp_path):
path = tmp_path / 'capture.jsonl'
monkeypatch.setattr(discovery, 'discovery_log_path', lambda: str(path))
monkeypatch.setattr(discovery, '_initialized', False)
monkeypatch.setattr(discovery.itemdb, 'get_db', lambda: {836: 'T6_STONEBLOCK'})
discovery.log('game_message', params={1: [836], 2: b'\x01'})
rows = [json.loads(line) for line in path.read_text().splitlines()]
assert rows[0]['type'] == 'session_start'
assert rows[1]['type'] == 'game_message'
assert discovery.item_candidates({1: [836]}) == [{
'path': '1[0]',
'id': 836,
'unique_name': 'T6_STONEBLOCK',
}]
+29
View File
@@ -0,0 +1,29 @@
from src.stats.economy_stats import EconomyStats
def test_economy_stats_accumulates_silver_and_items():
stats = EconomyStats()
stats.receive({'name': 'SilverGained', 'value': {
'value': 45.0, 'silver_type': 'looted'}})
stats.receive({'name': 'SilverGained', 'value': {
'value': 12.0, 'silver_type': 'other'}})
stats.receive({'name': 'ItemCollected', 'value': {
'item_id': 522,
'item_name': 'T4_MEAL_SALAD_FISH@3',
'quantity': 3,
}})
stats.receive({'name': 'ItemCollected', 'value': {
'item_id': 522,
'item_name': 'T4_MEAL_SALAD_FISH@3',
'quantity': 4,
}})
assert stats.stats() == {
'looted_silver': 45.0,
'other_silver': 12.0,
'total_silver': 57.0,
}
items = stats.item_list()
assert len(items) == 1
assert items[0].name == 'T4_MEAL_SALAD_FISH@3'
assert items[0].value == 7.0
+171
View File
@@ -0,0 +1,171 @@
"""Protocol tests for the effect stack and mob spawn opcodes.
Both were identified from /tmp/aostats-party01.jsonl, a T5 Morgana dungeon run
in which one player applied Armor Piercer and a party mate finished the mobs.
Every assertion here is anchored to a specific observation in that capture.
"""
import json
import pytest
from src.decode.translate import (
EffectApplication,
GameMessage,
into_game_message,
msg_effect_stack_applications,
msg_mob_hitpoints_max,
msg_mob_template_id,
)
def effect_msg(victim, appliers, effect_ids, flags='00', values='00'):
"""Build the EffectStackUpdate shape seen on the wire."""
n = len(appliers)
return GameMessage('EffectStackUpdate', 22, {
0: victim,
1: list(appliers),
2: list(effect_ids),
3: {'bytes_hex': flags * n, 'len': n},
4: {'bytes_hex': values * n, 'len': n},
})
def mob_msg(entity, template, hitpoints_max):
return GameMessage('MobSpawned', 123, {
0: entity,
1: template,
2: 255,
13: float(hitpoints_max),
14: float(hitpoints_max),
})
# --- effect stack ------------------------------------------------------------
def test_effect_stack_pairs_applier_with_effect():
msg = effect_msg(78724, [90362, 90547, 90547], [3163, 3097, 3098])
assert msg_effect_stack_applications(msg) == [
EffectApplication(applier=90362, effect_id=3163),
EffectApplication(applier=90547, effect_id=3097),
EffectApplication(applier=90547, effect_id=3098),
]
def test_applier_is_sent_explicitly():
"""Attribution does not have to guess who applied a debuff.
This is the reason the game sends the applier per effect. The original
plan assumed it would have to be inferred from the attacker's equipped
weapon; the packets do not require that.
"""
msg = effect_msg(78724, [90547, 90547, 90547], [3097, 3098, 3099])
appliers = {a.applier for a in msg_effect_stack_applications(msg)}
assert appliers == {90547}
def test_one_applier_can_hold_several_effects():
"""Armor Piercer is a beam that hits several targets at once.
Observed at 16:49:54.256: bionicKatana's three effect ids landed on three
different victims within a millisecond of each other, which is the
multi-target shape of the spell.
"""
msg = effect_msg(78724,
[90547, 90547, 90547, 90547, 90547],
[3097, 3098, 3099, 3092, 3093])
apps = msg_effect_stack_applications(msg)
assert len(apps) == 5
assert all(a.applier == 90547 for a in apps)
assert {a.effect_id for a in apps} == {3092, 3093, 3097, 3098, 3099}
def test_ragged_arrays_are_truncated_not_guessed():
"""A mismatched pair drops the tail rather than pairing unrelated ids."""
msg = effect_msg(78724, [90547, 90547, 90547], [3097, 3098])
assert len(msg_effect_stack_applications(msg)) == 2
def test_effect_stack_opcode_is_named():
"""Opcode 22 resolves to a name instead of being dropped."""
raw = _photon(code=1, kind='Event',
params={0: 78724, 1: [90547], 2: [3097], 252: 22})
msg = into_game_message(raw)
assert msg is not None
assert msg.name == 'EffectStackUpdate'
# --- mob spawn ---------------------------------------------------------------
def test_mob_spawn_carries_template_and_max_hp():
"""Template 2501 is a T5 Keeper Giant Champion, and max HP agrees.
Both fields were cross-checked against the packet, which is what makes the
template id safe to trust.
"""
msg = mob_msg(78724, 2501, 3282.0)
assert msg_mob_template_id(msg) == 2501
assert msg_mob_hitpoints_max(msg) == pytest.approx(3282.0)
def test_mob_spawn_opcode_is_named():
raw = _photon(code=1, kind='Event',
params={0: 78724, 1: 2501, 13: 3282.0, 252: 123})
msg = into_game_message(raw)
assert msg is not None
assert msg.name == 'MobSpawned'
def test_mob_template_is_not_an_item_id():
"""Mob template ids and item ids are different id spaces.
The discovery logger labels every integer it sees using the item table, so
this separation has to hold or every spawned mob would be reported as
whatever item happens to share its number.
"""
from src.decode import items as itemdb
db = itemdb.get_db()
# 454 was observed as a mob template for a Giant Snake...
msg = mob_msg(1, 454, 1162.0)
assert msg_mob_template_id(msg) == 454
# ...while item 454 is something else entirely.
assert db[454] == 'T5_SKILLBOOK_GATHER_FIBER'
assert mob_armor_name(454) == 'T5_MOB_HIDE_SWAMP_GIANTSNAKE'
def mob_armor_name(template_id):
with open(_static_path('mob_armor.json'), encoding='utf-8') as handle:
return json.load(handle)[str(template_id)]['name']
def _static_path(name):
import os
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
return os.path.join(root, 'src', 'static', name)
# --- capture-derived findings ------------------------------------------------
@pytest.mark.parametrize('applier,effect_ids', [
(90547, [3097, 3098, 3099]),
(90547, [3092, 3093]),
(90362, [3163]),
])
def test_real_payload_shapes_decode(applier, effect_ids):
"""Shapes taken verbatim from the capture still decode cleanly."""
msg = effect_msg(78724, [applier] * len(effect_ids), effect_ids)
apps = msg_effect_stack_applications(msg)
assert [a.effect_id for a in apps] == effect_ids
assert all(a.applier == applier for a in apps)
def _photon(code, kind, params):
class Raw:
pass
raw = Raw()
raw.code = code
raw.kind = kind
raw.params = params
raw.debug_message = None
return raw
+44
View File
@@ -0,0 +1,44 @@
import importlib
import sys
import src.environment as environment
def test_remember_last_party_flag_is_removed_from_qt_args(monkeypatch):
monkeypatch.setattr(sys, 'argv', ['aostats', '--remember-last-party'])
reloaded = importlib.reload(environment)
assert reloaded.remember_last_party() is True
assert reloaded.qt_args(['aostats', '--remember-last-party', '--verbose']) == [
'aostats']
sys.argv = ['aostats']
importlib.reload(environment)
def test_replay_flags_are_parsed_and_removed_from_qt_args(monkeypatch):
monkeypatch.setattr(sys, 'argv', [
'aostats', '--replay', '/tmp/capture.jsonl',
'--replay-speed', '2', '--replay-headless'])
reloaded = importlib.reload(environment)
assert reloaded.replay_path() == '/tmp/capture.jsonl'
assert reloaded.replay_speed() == 2.0
assert reloaded.replay_headless() is True
assert reloaded.qt_args(sys.argv) == ['aostats']
sys.argv = ['aostats']
importlib.reload(environment)
def test_replay_equals_syntax_and_default_speed(monkeypatch):
monkeypatch.setattr(sys, 'argv', ['aostats', '--replay=/tmp/x.jsonl'])
reloaded = importlib.reload(environment)
assert reloaded.replay_path() == '/tmp/x.jsonl'
assert reloaded.replay_speed() == 0.0
assert reloaded.replay_headless() is False
assert reloaded.qt_args(['aostats', '--replay=/tmp/x.jsonl']) == ['aostats']
sys.argv = ['aostats']
importlib.reload(environment)
+312
View File
@@ -0,0 +1,312 @@
"""Regression tests for the generated game data tables.
These assert facts established against real captures. Each one is anchored to a
specific observation, and the item-id assertions in particular fail against the
table this project used to ship -- which is the point: that table was silently
wrong, and nothing caught it.
"""
import json
import os
import pytest
from src.decode import items as itemdb
_ARMOR_TYPES = ('physicalarmor', 'magicresistance')
_REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC = os.path.join(_REPO, 'src', 'static')
def _load(name):
with open(os.path.join(STATIC, name), encoding='utf-8') as handle:
return json.load(handle)
@pytest.fixture(scope='module')
def item_spells():
return _load('item_spells.json')
@pytest.fixture(scope='module')
def debuff_spells():
return _load('debuff_spells.json')
@pytest.fixture(scope='module')
def mob_armor():
return _load('mob_armor.json')
@pytest.fixture(scope='module')
def item_power():
return _load('item_power.json')
@pytest.fixture(scope='module')
def progression():
return _load('progression.json')
# --- item ids ----------------------------------------------------------------
def test_real_equipment_array_resolves_by_position():
"""Every slot of a real equipment array resolves to the matching item.
The array is the equipment payload from a capture in
/tmp/aostats-debuff-test03, in wire order: weapon, offhand, helmet, armor,
boots, bag, cape, mount. The table this replaces scored 0 of these 8; it
reported a helmet as a firestaff and armor as a backpack.
"""
array = [7739, 2372, 5054, 4168, 4648, 2888, 2600, 3030]
expected = [
'T5_MAIN_HOLYSTAFF_AVALON@1',
'T7_OFF_TORCH',
'T7_HEAD_CLOTH_HELL',
'T6_ARMOR_LEATHER_SET2',
'T7_SHOES_LEATHER_AVALON',
'T4_BAG',
'T7_CAPEITEM_FW_LYMHURST@1',
'T5_MOUNT_HORSE',
]
assert [itemdb.get_db()[i] for i in array] == expected
def test_cursed_staff_resolves_to_armor_piercer(item_spells):
"""The weapon that actually cast Armor Piercer in the capture.
The packet carries the enchanted variant, T6_MAIN_CURSEDSTAFF@1, but only
the base item exists in the dump -- so the table aliases the variants.
Without that alias a lookup straight from a packet id finds nothing.
"""
assert item_spells['T6_MAIN_CURSEDSTAFF@1'] == \
item_spells['T6_MAIN_CURSEDSTAFF']
by_slot = {}
for entry in item_spells['T6_MAIN_CURSEDSTAFF@1']:
by_slot.setdefault(entry['slot'], []).append(entry['spell'])
assert by_slot['2'] == ['ARMORPIERCER', 'CURSENOVA', 'CURSEDHANDS_STACKUP',
'CURSEDBEAM', 'DARKMATTER']
assert by_slot['3'] == ['DEATHCURSE2']
def test_enchantment_variants_have_distinct_ids():
"""Enchantment level is in the item id, not folded into the base."""
db = itemdb.get_db()
assert db[7738] == 'T5_MAIN_HOLYSTAFF_AVALON'
assert db[7739] == 'T5_MAIN_HOLYSTAFF_AVALON@1'
assert db[7740] == 'T5_MAIN_HOLYSTAFF_AVALON@2'
# --- item power --------------------------------------------------------------
def test_item_power_follows_enchantment(item_power):
"""Item power scales with enchantment, so it can anchor damage maths.
This is what keeps the model correct as a player levels their weapon,
rather than inferring a constant from observed hits.
"""
assert item_power['T5_MAIN_HOLYSTAFF_AVALON'] == 900
assert item_power['T5_MAIN_HOLYSTAFF_AVALON@1'] == 1000
assert item_power['T5_MAIN_HOLYSTAFF_AVALON@4'] == 1300
# --- item -> spell binding ---------------------------------------------------
def test_spell_binding_follows_reference_inheritance(item_spells):
"""T5_MAIN_HOLYSTAFF_AVALON has no craftingspelllist of its own.
It inherits through two levels of @reference, and only the base carries
the abilities. Unresolved, it would have no spells at all.
"""
spells = item_spells['T5_MAIN_HOLYSTAFF_AVALON']
assert spells, 'inherited spell list is empty'
by_slot = {}
for entry in spells:
by_slot.setdefault(entry['slot'], []).append(entry['spell'])
assert 'HEALINGBEAM' in by_slot['2']
assert 'DIVINE_JUMP' in by_slot['3']
def test_removespell_drops_inherited_ability(item_spells):
"""T4_MAIN_HOLYSTAFF_AVALON inherits the base but drops one spell."""
inherited = {e['spell'] for e in item_spells['T4_MAIN_HOLYSTAFF']}
avalon = {e['spell'] for e in item_spells['T4_MAIN_HOLYSTAFF_AVALON']}
assert 'HOLYDESPERATEPRAYER2' in inherited
assert 'HOLYDESPERATEPRAYER2' not in avalon
assert 'DIVINE_JUMP' in avalon
def test_every_spell_bearing_item_resolves(item_spells):
"""100% coverage: no item that has ability slots lacks its spell list.
Naively 471 weapons look empty until @reference is resolved.
"""
cache = os.path.join('.cache', 'gamedata', 'items.json')
if not os.path.exists(cache):
pytest.skip('game data cache absent; run scripts/fetch_gamedata.py')
with open(cache, encoding='utf-8') as handle:
items_root = json.load(handle)['items']
index = {}
for group, value in items_root.items():
if group.startswith('@') or group == 'shopcategories':
continue
entries = value if isinstance(value, list) else (
[value] if isinstance(value, dict) else [])
for entry in entries:
if isinstance(entry, dict) and entry.get('@uniquename'):
index[entry['@uniquename']] = entry
missing = []
for name, entry in index.items():
slots = entry.get('@activespellslots')
if not slots or str(slots) in ('0', ''):
continue
if not item_spells.get(name):
missing.append(name)
assert not missing, 'items with ability slots but no spells: {}'.format(
missing[:5])
# --- debuff resolution ------------------------------------------------------
def test_debuff_reached_through_spell_chain(debuff_spells):
"""ARMORPIERCER carries no buffovertime of its own.
The armour numbers live two hops away:
ARMORPIERCER -> spelleffectarea -> ARMORPIERCER_EFFECT
-> applyspell -> ARMORPIERCER_DEBUFF_EFFECT
Matching only an ability's own effects would find nothing at all.
"""
entry = debuff_spells['ARMORPIERCER_DEBUFF_EFFECT']
assert entry['abilities'] == ['ARMORPIERCER']
physical = [e for e in entry['effects'] if e['type'] == 'physicalarmor']
assert len(physical) == 1
assert physical[0]['value'] == pytest.approx(-0.17)
assert physical[0]['time'] == pytest.approx(4.0)
def test_debuff_magnitude_scaling_is_preserved(debuff_spells):
"""Armor Piercer is stronger against more targets.
The multiplier must be carried through, because attribution has to read the
magnitude off the observed effect rather than assume the base value.
"""
for effect in debuff_spells['ARMORPIERCER_DEBUFF_EFFECT']['effects']:
assert effect['targetcountvaluebonusfactor'] == pytest.approx(0.08)
def test_mob_and_player_variants_are_distinguished(debuff_spells):
"""SUNDERARMOR2 is weaker against players than against mobs."""
effects = debuff_spells['SUNDERARMOR2']['effects']
by_target = {}
for effect in effects:
if effect['type'] == 'physicalarmor':
by_target[effect.get('iftargettype')] = effect['value']
assert by_target['player'] == pytest.approx(-0.04)
assert by_target['mob'] == pytest.approx(-0.06)
assert debuff_spells['SUNDERARMOR2']['maxstack'] == 3
def test_every_debuff_is_attributable_to_an_ability(debuff_spells):
"""Each debuff effect names the ability that caused it.
That link is what turns an observed effect into a player, via the ability's
slot on the attacker's weapon.
"""
for name, entry in debuff_spells.items():
assert entry['abilities'], '{} has no producing ability'.format(name)
assert entry['effects'], '{} has no effects'.format(name)
def test_armour_debuffs_combine_additively(debuff_spells):
"""No armour debuff uses a stacking rule.
Absence of @stackingrule means same-type effects sum, which is what makes
the combined victim reduction a plain sum rather than a priority puzzle.
"""
cache = os.path.join('.cache', 'gamedata', 'spells.json')
if not os.path.exists(cache):
pytest.skip('game data cache absent; run scripts/fetch_gamedata.py')
with open(cache, encoding='utf-8') as handle:
spells_root = json.load(handle)['spells']
checked = 0
for group in ('activespell', 'passivespell', 'togglespell'):
for spell in spells_root.get(group) or []:
bot = spell.get('buffovertime')
entries = bot if isinstance(bot, list) else ([bot] if bot else [])
if not any(isinstance(e, dict)
and e.get('@type') in _ARMOR_TYPES
for e in entries):
continue
checked += 1
assert not spell.get('@stackingrule'), (
'armour debuff {} declares a stacking rule'.format(
spell.get('@uniquename')))
assert not spell.get('@stackinggroup'), (
'armour debuff {} declares a stacking group'.format(
spell.get('@uniquename')))
assert checked > 100
# --- mob templates ----------------------------------------------------------
def test_mob_template_resolves_to_known_mob(mob_armor):
"""Template 454 is the Giant Snake from the controlled capture.
Opcode 252/123 carries the template id in param 1 and max HP in param 13;
both were cross-checked against the packet.
"""
assert mob_armor['454'] == {
'name': 'T5_MOB_HIDE_SWAMP_GIANTSNAKE',
'tier': 5,
'armor': 136,
'resistance': 136,
'hitpointsmax': 1162,
'category': 'hidemob',
}
@pytest.mark.parametrize('template_id,expected_name,expected_hp', [
('448', 'T1_MOB_HIDE_SWAMP_TOAD', 20),
('2722', 'T5_MOB_CITY_SWAMP_GUARD', 1509),
('2724', 'T4_MOB_CITY_SWAMP_KNIGHT_ELITE', 11606),
('2725', 'T5_MOB_CITY_SWAMP_BOSS', 27795),
('2757', 'T6_MOB_GUARD_TOWER', 153572),
])
def test_mob_templates_match_observed_max_hp(
mob_armor, template_id, expected_name, expected_hp):
"""Each was seen in a capture alongside its max HP."""
entry = mob_armor[template_id]
assert entry['name'] == expected_name
assert entry['hitpointsmax'] == expected_hp
def test_mob_and_item_ids_are_separate_spaces(mob_armor):
"""Template 454 and item 454 are different things.
Worth pinning: the discovery logger walks every integer in every message
and labels it with the item table, so decoding opcode 123 naively would
report the Giant Snake as a gathering skillbook.
"""
assert mob_armor['454']['name'] == 'T5_MOB_HIDE_SWAMP_GIANTSNAKE'
assert itemdb.get_db()[454] == 'T5_SKILLBOOK_GATHER_FIBER'
# --- progression ------------------------------------------------------------
def test_progression_constants_present(progression):
"""Armour and damage scale off item power using these constants."""
slot = progression['slots']['mainhand_2h']
assert slot['armorbase'] == pytest.approx(100.0)
assert slot['armorprogression'] == pytest.approx(1.03)
assert slot['attackdamageprogression'] == pytest.approx(1.0918)
share = progression['shares']['armorshare']
assert float(share['@armor']) == pytest.approx(1.0)
assert float(share['@head']) == pytest.approx(0.0)
+57
View File
@@ -0,0 +1,57 @@
import os
import re
from collections import Counter
import pytest
from src.decode.pipeline import Pipeline
LOG_PATH = os.path.join(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'aoaddons.log')
pytestmark = pytest.mark.skipif(
not os.path.exists(LOG_PATH),
reason='aoaddons.log capture fixture is not available')
def _raw_payloads():
payloads = []
pattern = re.compile(r'Raw payload: \[([0-9, ]+)\]')
with open(LOG_PATH, encoding='utf-8', errors='replace') as log:
for line in log:
match = pattern.search(line)
if match:
payloads.append(
bytes(int(part) for part in match.group(1).split(',')))
return payloads
def test_offline_capture_produces_expected_events():
payloads = _raw_payloads()
assert payloads, 'no raw payloads found in aoaddons.log'
events = []
pipeline = Pipeline(events.append)
for payload in payloads:
pipeline.on_udp(payload)
counts = Counter(event['name'] for event in events)
assert counts['MainPlayerAppeared'] >= 1
assert counts['PlayerAppeared'] == 2
assert counts['ZoneChange'] == 3
assert counts['UpdateItems'] >= 4
def test_offline_capture_main_player_stream_is_consistent():
events = []
pipeline = Pipeline(events.append)
for payload in _raw_payloads():
pipeline.on_udp(payload)
assert any(e['name'] == 'ZoneChange' for e in events)
main = next(e for e in events if e['name'] == 'MainPlayerAppeared')
assert main['value']['name']
appeared = [e['value']['id'] for e in events
if e['name'] == 'PlayerAppeared']
assert appeared == [0, 1]
+27
View File
@@ -0,0 +1,27 @@
import os
from src.decode import party_memory
from src.utils import platform_utils
def test_party_memory_save_load_and_clear(monkeypatch, tmp_path):
monkeypatch.setattr(platform_utils, 'config_dir', lambda: str(tmp_path))
party_memory.save_last_party([
'bionicKatana', 'fatbrick', 'fatbrick', '', None])
assert party_memory.load_last_party() == ['bionicKatana', 'fatbrick']
assert os.path.isfile(tmp_path / 'last-party.json')
party_memory.clear_last_party()
assert party_memory.load_last_party() == []
assert not os.path.exists(tmp_path / 'last-party.json')
def test_party_memory_ignores_corrupt_file(monkeypatch, tmp_path):
monkeypatch.setattr(platform_utils, 'config_dir', lambda: str(tmp_path))
path = tmp_path / 'last-party.json'
path.write_text('{not json')
assert party_memory.load_last_party() == []
+43
View File
@@ -0,0 +1,43 @@
from src.utils import platform_utils
def test_capture_permissions_ok_when_root(monkeypatch):
monkeypatch.setattr(platform_utils, 'is_linux', lambda: True)
monkeypatch.setattr(platform_utils.os, 'geteuid', lambda: 0)
assert platform_utils.capture_permissions_ok() is True
def test_capture_permissions_ok_when_socket_opens(monkeypatch):
monkeypatch.setattr(platform_utils, 'is_linux', lambda: True)
monkeypatch.setattr(platform_utils.os, 'geteuid', lambda: 1000)
monkeypatch.setattr(
platform_utils.socket,
'socket',
lambda *a, **k: _StubSocket(raise_error=False),
)
assert platform_utils.capture_permissions_ok() is True
def test_capture_permissions_ok_when_permission_denied(monkeypatch):
monkeypatch.setattr(platform_utils, 'is_linux', lambda: True)
monkeypatch.setattr(platform_utils.os, 'geteuid', lambda: 1000)
monkeypatch.setattr(
platform_utils.socket,
'socket',
lambda *a, **k: _StubSocket(raise_error=True),
)
assert platform_utils.capture_permissions_ok() is False
def test_capture_permissions_ok_skips_probe_on_other_platforms(monkeypatch):
monkeypatch.setattr(platform_utils, 'is_linux', lambda: False)
assert platform_utils.capture_permissions_ok() is True
class _StubSocket:
def __init__(self, raise_error=False):
self._raise_error = raise_error
def close(self):
if self._raise_error:
raise PermissionError('Operation not permitted')
+193
View File
@@ -0,0 +1,193 @@
import json
import os
import re
import time
from collections import Counter
import pytest
from src.decode.pipeline import Pipeline
from src.net.replay import ReplayEngine, load_payloads
from src.replay_cli import summarize
RAW_LOG_PATH = os.path.join(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'aoaddons.log')
def _write_jsonl(path, payloads):
with open(path, 'w', encoding='utf-8') as out:
out.write(json.dumps({'type': 'session_start'}) + '\n')
for i, payload in enumerate(payloads):
out.write(json.dumps({
'type': 'udp_payload',
'timestamp': f'2026-10-10T00:00:{i:02d}.000+00:00',
'payload_hex': payload.hex(),
}) + '\n')
out.write(json.dumps({'type': 'game_message', 'name': 'UpdateFame'}) + '\n')
def test_load_payloads_reads_jsonl_and_ignores_other_records(tmp_path):
path = tmp_path / 'capture.jsonl'
_write_jsonl(str(path), [b'\x01\x02', b'\x03\x04\x05'])
assert load_payloads(str(path)) == [b'\x01\x02', b'\x03\x04\x05']
def test_load_payloads_supports_legacy_raw_format(tmp_path):
path = tmp_path / 'aoaddons.log'
path.write_text(
'some log line\n'
'Raw payload: [1, 2, 3]\n'
'unrelated\n'
'Raw payload: [4, 5]\n',
encoding='utf-8')
assert load_payloads(str(path)) == [b'\x01\x02\x03', b'\x04\x05']
def test_replay_engine_start_fails_for_missing_file():
engine = ReplayEngine(lambda payload: None, path='/does/not/exist.jsonl')
assert engine.start() is False
def test_replay_engine_feeds_payloads_in_order(tmp_path):
path = tmp_path / 'capture.jsonl'
_write_jsonl(str(path), [b'\xaa', b'\xbb', b'\xcc'])
received = []
engine = ReplayEngine(received.append, path=str(path), speed=0.0)
assert engine.start() is True
engine.wait(timeout=5)
assert received == [b'\xaa', b'\xbb', b'\xcc']
assert engine.packet_count == 3
def test_replay_engine_paces_with_timestamps(tmp_path):
path = tmp_path / 'capture.jsonl'
with open(path, 'w', encoding='utf-8') as out:
out.write(json.dumps({'type': 'session_start'}) + '\n')
for i in range(3):
out.write(json.dumps({
'type': 'udp_payload',
'timestamp': f'2026-10-10T00:00:00.{i * 100:03d}+00:00',
'payload_hex': 'aa',
}) + '\n')
started = time.monotonic()
engine = ReplayEngine(lambda payload: None, path=str(path), speed=1.0)
engine.start()
engine.wait(timeout=5)
elapsed = time.monotonic() - started
assert elapsed >= 0.15
def test_replay_engine_ignores_duplicate_start(tmp_path):
path = tmp_path / 'capture.jsonl'
_write_jsonl(str(path), [b'\xaa'])
engine = ReplayEngine(lambda payload: None, path=str(path))
assert engine.start() is True
assert engine.start() is True
engine.wait(timeout=5)
assert engine.packet_count == 1
def test_summarize_reports_fame_silver_and_player():
events = [
{'name': 'MainPlayerAppeared', 'value': {'id': 0, 'name': 'Alice'}},
{'name': 'ZoneChange'},
{'name': 'UpdateFame', 'value': {'value': 857.472}},
{'name': 'SilverGained', 'value': {
'value': 64.8351, 'silver_type': 'looted'}},
{'name': 'DamageDone', 'value': {'source': 1, 'value': 120.0}},
]
report = summarize(events, path='/tmp/capture.jsonl', packet_count=42)
assert 'Alice' in report
assert '857.47' in report
assert '64.84' in report
assert '120.00' in report
assert 'packets: 42' in report
def test_summarize_breaks_damage_down_per_player():
"""A combined total next to "main player" reads as that player's damage.
Two players damaged a mob; the report must attribute each share rather
than printing one ambiguous number.
"""
events = [
{'name': 'MainPlayerAppeared', 'value': {'id': 0, 'name': 'Alice'}},
{'name': 'PlayerAppeared', 'value': {'id': 1, 'name': 'Bob'}},
{'name': 'DamageDone', 'value': {'source': 1, 'value': 1309.0}},
{'name': 'DamageDone', 'value': {'source': 1, 'value': 100.0}},
{'name': 'DamageDone', 'value': {'source': 0, 'value': 232.0}},
{'name': 'DamageTaken', 'value': {'source': 1, 'value': 244.0}},
]
report = summarize(events)
assert 'Bob: 1409.00' in report
assert 'Alice: 232.00' in report
# the party-wide figure is still reported, but labelled as such
assert 'damage done: 1641.00 (all players)' in report
assert 'damage taken by player:' in report
assert 'Bob: 244.00' in report
def test_summarize_labels_unknown_player_ids():
events = [
{'name': 'MainPlayerAppeared', 'value': {'id': 0, 'name': 'Alice'}},
{'name': 'DamageDone', 'value': {'source': 7, 'value': 50.0}},
]
report = summarize(events)
# no appearance event for id 7, so it must not be silently attributed
assert 'player #7: 50.00' in report
def test_summarize_reports_empty_damage_sections():
report = summarize([
{'name': 'MainPlayerAppeared', 'value': {'id': 0, 'name': 'Alice'}},
])
assert 'damage done by player:' in report
assert 'damage taken by player:' in report
assert '(none)' in report
pytestmark = pytest.mark.skipif(
not os.path.exists(RAW_LOG_PATH),
reason='aoaddons.log capture fixture is not available')
def _raw_payloads():
payloads = []
pattern = re.compile(r'Raw payload: \[([0-9, ]+)\]')
with open(RAW_LOG_PATH, encoding='utf-8', errors='replace') as log:
for line in log:
match = pattern.search(line)
if match:
payloads.append(
bytes(int(part) for part in match.group(1).split(',')))
return payloads
def test_replay_engine_integration_produces_events(tmp_path):
path = tmp_path / 'capture.jsonl'
_write_jsonl(str(path), _raw_payloads())
events = []
pipeline = Pipeline(events.append)
engine = ReplayEngine(pipeline.on_udp, path=str(path), speed=0.0)
assert engine.start() is True
engine.wait(timeout=10)
counts = Counter(event['name'] for event in events)
assert counts['MainPlayerAppeared'] >= 1
assert counts['PlayerAppeared'] == 2
assert counts['ZoneChange'] == 3
+32
View File
@@ -0,0 +1,32 @@
from src.stats import visibility as visibility_module
from src.stats.visibility import Visibility
def test_visibility_uses_exact_names(monkeypatch):
monkeypatch.delenv('TESTING', raising=False)
monkeypatch.setattr(visibility_module, 'config', lambda: {'app': {}})
visibility_module._is_visible_by_config.cache_clear()
visibility = Visibility()
visibility.on_player_appeared('bionicKatana')
visibility.on_visible_players_changed(['Sweetpea23042'])
assert visibility.test('bionicKatana')
assert visibility.test('Sweetpea23042')
assert not visibility.test('Sweetpea')
assert not visibility.test('bionicKatanaExtra')
def test_visibility_treats_regex_characters_as_plain_names(monkeypatch):
monkeypatch.delenv('TESTING', raising=False)
monkeypatch.setattr(visibility_module, 'config', lambda: {'app': {}})
visibility_module._is_visible_by_config.cache_clear()
visibility = Visibility()
visibility.on_player_appeared('main.player')
visibility.on_visible_players_changed(['Arcane+Fire'])
assert visibility.test('main.player')
assert visibility.test('Arcane+Fire')
assert not visibility.test('mainXplayer')
assert not visibility.test('ArcaneeeFire')
+1
View File
@@ -17,5 +17,6 @@ commands =
[testenv:ut] [testenv:ut]
deps = deps =
pytest pytest
toml
commands = commands =
python -m pytest tests python -m pytest tests