Playtest fixes: smoke by engine, searchlights, far launch sites that load their chunks, air defence balance, last chance and radar-cued shots, radars in smart raids, echo, Windows release build from a tag
build / mod (push) Successful in 4m4s
release / windows (push) Successful in 23m13s

Smoke: one rule by engine, no heat on trails, no trail on P1-SUN. Searchlights: two lamps a target, off with an empty sky. Halos fade before their reach and their sum is limited. Launch sites load chunks through the server thread, go off-map as a last resort, and reach 4000 blocks. Air defence: ranges x1.5, shots grow with urgency, claims released, /airdef lastchance, long shots on a big radar's tracks. Build: rust-toolchain.toml, airdef.py check, generator manifest and --check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-30 23:44:14 +03:00
parent 5003376e70
commit ccc3e20902
67 changed files with 4573 additions and 328 deletions
+66 -2
View File
@@ -9,6 +9,14 @@
Для каждой дорожки считается энергия левого канала в четырёх полосах (до 300 Гц, 300-1500, 1500-5000, выше
5000) и разница в дБ между дорожками. Преграда должна срезать верхи (выше 5 кГц не меньше чем на 15 дБ) и
оставить низы (до 300 Гц теряют не больше 8 дБ). Коды выхода: 0 — в порогах, 1 — нет, 2 — ошибка аргументов.
Режим `--echo` (стадия 2): в дорожке с одним щелчком ищутся пики огибающей после прямого звука, их задержки
(мс от прямого) сравниваются с ожидаемыми от геометрии:
python3 tools/acoustics_check.py --echo gorge.raw --expect 187.3,254.1 [--tol 1.0]
python3 tools/acoustics_check.py --echo field.raw --expect none
python3 tools/acoustics_check.py --echo-dir папка # gorge/field/room и expected.txt из export_echo_tracks
Дорожки пишет `audio::tests::export_echo_tracks` (HORIZON_ACOUSTICS_OUT=папка). Коды выхода те же.
Только стандартная библиотека.
"""
import argparse
@@ -53,19 +61,75 @@ def bands(path, rate, channels):
return out
def echo_peaks(path, rate, channels, min_gap_ms=10.0, rel=0.02):
"""Delays (ms from the first peak) of the peaks of the smoothed envelope of a track."""
raw = array.array("h")
with open(path, "rb") as f:
data = f.read()
raw.frombytes(data[: len(data) // 2 * 2])
frames = [sum(abs(raw[i + c]) for c in range(channels)) / 32768.0 for i in range(0, len(raw) - channels + 1, channels)]
win = max(1, rate // 1000) # 1 ms
env = []
acc = 0.0
for i, v in enumerate(frames):
acc += v
if i >= win:
acc -= frames[i - win]
env.append(acc / win)
first = max(range(min(len(env), rate // 20)), key=env.__getitem__) # the direct sound: loudest in the first 50 ms
top = env[first]
gap = int(min_gap_ms * rate / 1000)
peaks, i = [], first + int(0.02 * rate)
while i < len(env):
if env[i] >= rel * top:
j = max(range(i, min(len(env), i + gap)), key=env.__getitem__)
peaks.append((j - first) * 1000.0 / rate)
i = j + gap
else:
i += 1
return peaks
def check_echo(path, expect, tol, rate, channels):
peaks = echo_peaks(path, rate, channels)
print(f"{path}: peaks at {', '.join(f'{p:.1f}' for p in peaks) or 'none'} ms; expected {', '.join(f'{e:.1f}' for e in expect) or 'none'} ms")
ok = len(peaks) == len(expect) and all(abs(p - e) <= tol for p, e in zip(peaks, expect))
print(f" {'ok' if ok else 'FAIL'} (tolerance {tol} ms)")
return ok
def db(a, b):
return 10 * math.log10(max(a, 1e-20) / max(b, 1e-20))
def main():
p = argparse.ArgumentParser(description=__doc__.split("\n")[0])
p.add_argument("open")
p.add_argument("wall")
p.add_argument("open", nargs="?")
p.add_argument("wall", nargs="?")
p.add_argument("--echo", help="track with one click: check the delays of its echoes")
p.add_argument("--echo-dir", help="folder written by export_echo_tracks: check gorge, field and room")
p.add_argument("--expect", default="none", help="expected delays in ms, comma separated, or none")
p.add_argument("--tol", type=float, default=1.0, help="ms a peak may be off")
p.add_argument("--rate", type=int, default=48000)
p.add_argument("--channels", type=int, default=2)
p.add_argument("--min-high-cut", type=float, default=15.0, help="dB the band above 5 kHz must drop")
p.add_argument("--max-low-loss", type=float, default=8.0, help="dB the band below 300 Hz may drop")
a = p.parse_args()
if a.echo_dir:
import os
ok = True
with open(os.path.join(a.echo_dir, "expected.txt")) as f:
for line in f:
name, _, vals = line.strip().partition(" ")
want = [float(v) for v in vals.split(",") if v]
# The ms in the room are for the walls the geometry says; only the first peak is compared there.
ok &= check_echo(os.path.join(a.echo_dir, name + ".raw"), want, a.tol, a.rate, a.channels)
return 0 if ok else 1
if a.echo:
want = [] if a.expect == "none" else [float(v) for v in a.expect.split(",")]
return 0 if check_echo(a.echo, want, a.tol, a.rate, a.channels) else 1
if not a.open or not a.wall:
p.error("give open.raw and wall.raw, or --echo / --echo-dir")
o, w = bands(a.open, a.rate, a.channels), bands(a.wall, a.rate, a.channels)
print(f"{'band, Hz':>10} {'open dB':>9} {'wall dB':>9} {'change dB':>10}")
ref = max(o)
+116 -1
View File
@@ -7,17 +7,21 @@
python3 tools/airdef.py install # положить мод в папку игры и включить
python3 tools/airdef.py play [аргументы игры] # запустить форк на папке игры
python3 tools/airdef.py all # всё по порядку: fork, game, mod, install
python3 tools/airdef.py check # совпадают ли форк, упаковщик, уровень API мода и ресурсы
Переменные окружения: HORIZON_HOME (папка игры), HORIZON_RESOURCES (подготовленные ресурсы
Minecraft 26.3), AIRDEF_GAME (готовый horizon-client вместо собранного).
"""
import glob
import hashlib
import json
import os
import platform
import re
import shutil
import subprocess
import sys
import zipfile
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
@@ -165,11 +169,122 @@ def play(args):
run([exe, "--resources", resources(), *args], cwd=home)
def fork_api():
"""Новейший уровень API форка и его таблица функций (horizon-mods/src/api_level.rs); None без форка."""
try:
text = (FORK / "crates" / "horizon-mods" / "src" / "api_level.rs").read_text(encoding="utf-8")
except OSError:
return None
try:
level = int(re.search(r"pub const LEVEL: u32 = (\d+);", text).group(1))
table = text[text.index("pub const FUNCTIONS"):]
table = table[:table.index("];")]
except (AttributeError, ValueError):
return None
return level, [(name, int(lvl)) for name, lvl in re.findall(r'\("([a-z.\-]+)", (\d+)\)', table)]
def needed_level(wasm: bytes, table) -> tuple:
"""Уровень, который нужен модулю: самая новая функция, которую он импортирует (как api_level::needed).
В компоненте имя функции записано как 0x00, длина, UTF-8 имя; по этим байтам и ищем."""
need = (0, None)
for name, level in table:
part = name.split(".", 1)[1].encode()
if level > need[0] and b"\x00" + bytes([len(part)]) + part in wasm:
need = (level, name)
return need
def game_level():
"""Уровень, который игра записала в себя (метка horizon-mod-api-level:NNNN;); None, если игры нет.
Игра без метки считается уровня 0, как в api_level::read_mark."""
try:
exe = built_game()
except SystemExit:
return None
if not exe.exists():
return None
found = re.search(rb"horizon-mod-api-level:(\d{4});", exe.read_bytes())
return int(found.group(1)) if found else 0
def check():
"""Говорит прямо, совпадают ли форк, упаковщик, уровень API мода с игрой и ресурсы. Код 0 — да, 1 — нет."""
commit = (ROOT / "HORIZON_COMMIT").read_text().strip()
patches = sorted((ROOT / "horizon-patches").glob("*.patch"))
stamp = fork_stamp(commit, patches)
problems = []
def line(name, ok, text):
print(f"[{'ok' if ok else 'нет'}] {name}: {text}")
if not ok:
problems.append(name)
stamp_file = FORK / ".git" / "airdef-stamp"
fork_ok = stamp_file.exists() and stamp_file.read_text().strip() == stamp
line("форк", fork_ok, f"коммит {commit[:12]}, патчей {len(patches)}" if fork_ok else
"horizon/ не собран из HORIZON_COMMIT и horizon-patches/: python3 tools/airdef.py fork")
tool = shutil.which("cargo-horizon-mod") or str(Path.home() / ".cargo" / "bin" / ("cargo-horizon-mod" + EXE))
packer_stamp = FORK / ".git" / "airdef-packer-stamp"
packer_ok = Path(tool).exists() and packer_stamp.exists() and packer_stamp.read_text().strip() == stamp
line("упаковщик", packer_ok, "собран из этого форка" if packer_ok else
"не установлен или собран из другого форка: python3 tools/airdef.py mod")
api = fork_api()
try:
mod_file = hmod()
except SystemExit:
mod_file = None
if api is None:
line("уровень API", False, "нет или не читается horizon/crates/horizon-mods/src/api_level.rs: python3 tools/airdef.py fork")
elif mod_file is None:
line("уровень API", False, "нет airdef.hmod: python3 tools/airdef.py mod")
else:
level, table = api
with zipfile.ZipFile(mod_file) as z:
wasm = z.read("mod.wasm") if "mod.wasm" in z.namelist() else b""
need, function = needed_level(wasm, table)
game = game_level()
text = f"мод нужен {need} ({function}), форк {level}, игра " + ("не собрана" if game is None else str(game))
if game is None:
line("уровень API", False, text + ": python3 tools/airdef.py game")
else:
# Сравнивается уровень, не код: одинаковый уровень не доказывает одинаковые патчи.
supported = need <= game and game == level
line("уровень API", supported, text if supported else
text + ": игра не поддерживает мод или собрана из другого форка")
try:
res = resources()
except SystemExit as e:
res = None
line("ресурсы", False, str(e.code))
if res is not None:
try:
preparer = (FORK / "crates" / "horizon-prepare" / "src" / "lib.rs").read_text(encoding="utf-8")
schema = int(re.search(r"pub const SCHEMA: i64 = (\d+);", preparer).group(1))
except (OSError, AttributeError):
schema = None
try:
manifest = json.loads((res / "horizon-resources.json").read_text(encoding="utf-8"))
except (OSError, ValueError):
manifest = {}
ok = schema is not None and manifest.get("schema") == schema and manifest.get("minecraft") == "26.3"
line("ресурсы", ok, f"{res}, схема {schema}, Minecraft 26.3" if ok else
f"{res}: схема {manifest.get('schema')}, Minecraft {manifest.get('minecraft')}; нужны схема {schema} и Minecraft 26.3")
if problems:
sys.exit("Не совпадает: " + ", ".join(problems) + ".")
print("Всё совпадает: форк, упаковщик, уровень API мода и ресурсы.")
def main():
if len(sys.argv) < 2:
sys.exit(__doc__)
cmd, rest = sys.argv[1], sys.argv[2:]
steps = {"fork": fork, "game": game, "mod": mod, "install": install}
steps = {"fork": fork, "game": game, "mod": mod, "install": install, "check": check}
if cmd == "play":
play(rest)
elif cmd == "all":
+117 -9
View File
@@ -5,14 +5,21 @@
Поворачивает и масштабирует их движок форка (render.set-models), так что ракурсы больше не нужны.
Координаты элементов — в пределах -16..32 (иначе Horizon отбрасывает модель).
Запуск: python3 tools/gen_models.py
Запуск: python3 tools/gen_models.py [--check]
Скрипт пишет во временный каталог и только потом переносит результат в airdef-mod/. Список созданных им файлов
с sha256 лежит в airdef-mod/generated-manifest.txt (формат sha256sum). Удаляются и перезаписываются только файлы
из этого списка и только если их не правили вручную; чужой файл на пути генерируемого останавливает запуск.
--check ничего не пишет и выходит с кодом 1, если airdef-mod/ отличается от того, что дал бы запуск.
"""
import hashlib
import json
import math
import os
import sys
import random
import shutil
import tempfile
import zlib
from PIL import Image
@@ -1692,13 +1699,10 @@ def write_json(path, obj):
json.dump(obj, f, ensure_ascii=False, indent=1)
def main():
# Только своё: звуки (tools/gen_sounds.py) и sounds.json не трогаем.
for sub in ("blockstates", "items", "lang", "models", "textures"):
shutil.rmtree(os.path.join(ROOT, "assets", NS, sub), ignore_errors=True)
shutil.rmtree(os.path.join(ROOT, "data"), ignore_errors=True)
a = os.path.join(ROOT, "assets", NS)
d = os.path.join(ROOT, "data", NS, "horizon")
def generate(out):
# Пишет весь набор в каталог out (зеркало airdef-mod/). Звуки (tools/gen_sounds.py) и sounds.json не трогаем.
a = os.path.join(out, "assets", NS)
d = os.path.join(out, "data", NS, "horizon")
os.makedirs(os.path.join(a, "textures", "block"))
os.makedirs(os.path.join(a, "textures", "item"))
lang = {}
@@ -1738,7 +1742,111 @@ def main():
lang[f"item.{NS}.cam_{name}"] = title
write_json(os.path.join(a, "lang", "en_us.json"), lang)
write_json(os.path.join(a, "lang", "ru_ru.json"), lang)
print(f"{len(MODELS)} моделей, {len(ITEMS)} предметов, {len(TEXTURES)} текстур -> {ROOT}")
return len(MODELS), len(ITEMS), len(TEXTURES)
MANIFEST = os.path.join(ROOT, "generated-manifest.txt")
def file_sha(path):
with open(path, "rb") as f:
return hashlib.sha256(f.read()).hexdigest()
def read_manifest():
# Строки "<sha256> <путь от airdef-mod>", как у sha256sum. Только файлы, которые записал этот скрипт.
if not os.path.exists(MANIFEST):
return {}
entries = {}
with open(MANIFEST, encoding="utf-8") as f:
for line in f:
digest, rel = line.rstrip("\n").split(" ", 1)
if rel.startswith("/") or ".." in rel.split("/"):
sys.exit(f"{MANIFEST}: недопустимый путь {rel}")
entries[rel] = digest
return entries
def prune_empty(path):
d = os.path.dirname(path)
while d != ROOT and os.path.isdir(d) and not os.listdir(d):
os.rmdir(d)
d = os.path.dirname(d)
def main():
args = sys.argv[1:]
if any(arg != "--check" for arg in args):
sys.exit("Использование: python3 tools/gen_models.py [--check]")
check = "--check" in args
old = read_manifest()
with tempfile.TemporaryDirectory() as stage:
counts = generate(stage)
new = {}
for dirpath, dirs, names in os.walk(stage):
dirs.sort()
for name in sorted(names):
path = os.path.join(dirpath, name)
new[os.path.relpath(path, stage).replace(os.sep, "/")] = file_sha(path)
# create: файла нет; update: файл записан генератором и с тех пор не менялся; same: уже совпадает;
# conflict: на пути лежит чужой или вручную правленный файл, поэтому ничего не пишем.
create, update, same, conflict = [], [], [], []
for rel in sorted(new):
target = os.path.join(ROOT, rel)
if not os.path.exists(target):
create.append(rel)
elif not os.path.isfile(target):
conflict.append(rel)
else:
cur = file_sha(target)
if cur == new[rel]:
same.append(rel)
elif rel in old and old[rel] == cur:
update.append(rel)
else:
conflict.append(rel)
# remove: генератор больше не создаёт файл и он не менялся; keep: не создаёт, но правлен вручную, оставляем.
remove, keep = [], []
for rel in sorted(old):
target = os.path.join(ROOT, rel)
if rel in new or not os.path.isfile(target):
continue
(remove if file_sha(target) == old[rel] else keep).append(rel)
if conflict:
for rel in conflict:
print(f"КОНФЛИКТ: {rel} занят файлом, которого нет в manifest (или он правлен вручную)")
sys.exit("Ничего не записано. Уберите или переименуйте эти файлы и запустите снова.")
manifest_text = "".join(f"{new[rel]} {rel}\n" for rel in sorted(new))
manifest_old = None
if os.path.exists(MANIFEST):
with open(MANIFEST, encoding="utf-8") as f:
manifest_old = f.read()
manifest_changed = manifest_text != manifest_old
for rel in keep:
print(f"ВНИМАНИЕ: {rel} больше не генерируется, но правлен вручную: оставлен, из manifest убран")
for label, rels in (("новый", create), ("обновить", update), ("удалить", remove)):
for rel in rels:
print(f"{label}: {rel}")
if manifest_changed:
print("manifest: обновить")
if check:
differs = create or update or remove or manifest_changed
print("различий нет" if not differs else "различия с генератором: см. выше")
sys.exit(1 if differs else 0)
for rel in create + update:
dst = os.path.join(ROOT, rel)
os.makedirs(os.path.dirname(dst), exist_ok=True)
shutil.copyfile(os.path.join(stage, rel), dst)
for rel in remove:
path = os.path.join(ROOT, rel)
os.remove(path)
prune_empty(path)
if manifest_changed:
with open(MANIFEST, "w", encoding="utf-8", newline="\n") as f:
f.write(manifest_text)
models, items, textures = counts
print(f"{models} моделей, {items} предметов, {textures} текстур -> {ROOT}: "
f"создано {len(create)}, обновлено {len(update)}, удалено {len(remove)}, без изменений {len(same)}")
if __name__ == "__main__":