Share aircraft and item catalog with asset generation
build / mod (push) Failing after 20s

Co-Authored-By: Codex <noreply@openai.com>
This commit is contained in:
2026-11-04 15:54:31 +03:00
parent cb73cb7ccc
commit eea1b3692e
9 changed files with 519 additions and 64 deletions
+25
View File
@@ -0,0 +1,25 @@
"""Shared content identities and item presentation used by runtime and assets."""
import json
from pathlib import Path
PATH = Path(__file__).resolve().parents[2] / "catalog" / "content.json"
def load():
data = json.loads(PATH.read_text(encoding="utf-8"))
items = data["items"]
ids = [item["id"] for item in items]
if len(ids) != len(set(ids)):
raise ValueError("duplicate item ID in content catalog")
referenced = []
for group in (data["aircraft"], data["units"]):
kinds = [entry["kind"] for entry in group]
if len(kinds) != len(set(kinds)):
raise ValueError("duplicate kind in content catalog")
referenced.extend(entry["item"] for entry in group if entry["item"] is not None)
if len(referenced) != len(set(referenced)) or not set(referenced) <= set(ids):
raise ValueError("duplicate or unregistered content item")
for item in items:
if len(item["color"]) != 3 or any(not isinstance(c, int) or not 0 <= c <= 255 for c in item["color"]):
raise ValueError(f"invalid icon color for {item['id']}")
return data
+4 -32
View File
@@ -6,38 +6,10 @@ from PIL import Image
from .texture_catalog import clamp
# Предметы: (id, название, цвет иконки)
ITEMS = [
("designator", "Целеуказатель", (220, 50, 50)),
("launch_shahed", "Пуск: Шахед-136", (90, 92, 96)),
("launch_geran3", "Пуск: Герань-3", (30, 30, 34)),
("deploy_patriot", "Развернуть Patriot", (76, 86, 58)),
("deploy_gepard", "Развернуть Гепард", (104, 84, 54)),
("deploy_pantsir", "Развернуть Панцирь-С1", (82, 96, 60)),
("deploy_s400", "Развернуть С-400", (60, 80, 50)),
("deploy_s500", "Развернуть С-500", (108, 110, 80)),
("launch_lancet", "Пуск: Ланцет-3", (70, 78, 66)),
("launch_kh101", "Пуск: Х-101", (84, 88, 92)),
("launch_kalibr", "Пуск: Калибр", (150, 154, 156)),
("launch_kh22", "Пуск: Х-22", (226, 228, 222)),
("launch_zircon", "Пуск: Циркон", (52, 54, 52)),
("launch_iskander", "Пуск: Искандер-М", (108, 110, 80)),
("launch_kinzhal", "Пуск: Кинжал", (60, 62, 60)),
("launch_oreshnik", "Пуск: Орешник", (230, 120, 40)),
("deploy_irist", "Развернуть IRIS-T SLM", (76, 86, 58)),
("deploy_nasams", "Развернуть NASAMS", (76, 86, 58)),
("deploy_buk", "Развернуть Бук-М2", (82, 96, 60)),
("deploy_tor", "Развернуть Тор-М2", (108, 110, 80)),
("deploy_p1sun", "Развернуть P1-SUN", (52, 54, 52)),
("deploy_radar", "Развернуть РЛС дальнего обнаружения", (108, 110, 80)),
("deploy_depot", "Развернуть склад боеприпасов", (92, 78, 48)),
("deploy_tzm", "Развернуть ТЗМ", (82, 96, 60)),
("deploy_ew", "Развернуть станцию РЭБ", (108, 110, 80)),
("deploy_light", "Развернуть прожектор", (52, 54, 52)),
("mover", "Пульт перемещения", (60, 140, 220)),
("flare_gun", "Осветительная ракета", (255, 240, 180)),
("remover", "Свернуть ПВО", (200, 200, 200)),
]
# Presentation follows the shared content catalog; order keeps generated assets stable.
from .catalog import load as load_catalog
ITEMS = [(item["id"], item["title"], tuple(item["color"])) for item in load_catalog()["items"]]
# Иконки 16×16 без сглаживания. Каждый предмет рисуется своей функцией: категория задаёт основу
+45
View File
@@ -0,0 +1,45 @@
#!/usr/bin/env python3
"""Generate Rust content entries from the shared catalog; --check detects drift."""
import argparse
from pathlib import Path
import re
from airdef_assets.catalog import load
OUTPUT = Path(__file__).resolve().parents[1] / "airdef-mod/src/sim/catalog_entries.rs"
def generate(data):
lines = ["// Generated by tools/gen_catalog.py from catalog/content.json. Do not edit.",
"pub const AIRCRAFT: &[Aircraft] = &["]
for entry in data["aircraft"]:
kind, item = entry["kind"], entry["item"]
if not re.fullmatch(r"[A-Z][A-Za-z0-9]*", kind):
raise ValueError(f"invalid Rust kind {kind!r}")
if item is not None and not re.fullmatch(r"[a-z0-9_]+", item):
raise ValueError(f"invalid item ID {item!r}")
item_expr = f'Some("airdef:{item}")' if item is not None else "None"
lines.append(f' Aircraft {{ kind: {kind}, launch_item: {item_expr}, raid: {str(entry["raid"]).lower()} }},')
lines += ["];", "", "pub const UNITS: &[Unit] = &["]
for entry in data["units"]:
kind, item = entry["kind"], entry["item"]
if not re.fullmatch(r"[A-Z][A-Za-z0-9]*", kind) or not re.fullmatch(r"[a-z0-9_]+", item):
raise ValueError(f"invalid unit {entry!r}")
lines.append(f' Unit {{ kind: SamKind::{kind}, deploy_item: "airdef:{item}" }},')
return "\n".join(lines + ["];", ""])
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--check", action="store_true")
args = parser.parse_args()
generated = generate(load())
if args.check:
if not OUTPUT.exists() or OUTPUT.read_text(encoding="utf-8") != generated:
parser.exit(1, f"{OUTPUT} is stale; run python3 tools/gen_catalog.py\n")
else:
OUTPUT.write_text(generated, encoding="utf-8")
if __name__ == "__main__":
main()
+12
View File
@@ -2,6 +2,8 @@
import hashlib
import importlib.util
import json
import subprocess
import os
import sys
import tempfile
@@ -22,6 +24,16 @@ gen_models = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(gen_models)
class ContentCatalogTests(unittest.TestCase):
def test_catalog_rust_entries_are_current_and_registered_items_match_assets(self):
root = TOOLS.parent
subprocess.run([sys.executable, str(TOOLS / "gen_catalog.py"), "--check"], check=True)
language = json.loads((root / "airdef-mod/assets/airdef/lang/ru_ru.json").read_text(encoding="utf-8"))
for name, title, _ in icons.ITEMS:
self.assertEqual(language[f"item.airdef.{name}"], title)
self.assertTrue((root / "airdef-mod/data/airdef/horizon/item" / (name + ".json")).is_file())
class ManifestTests(unittest.TestCase):
def test_manifest_rejects_traversal_and_duplicate_paths(self):
with tempfile.TemporaryDirectory() as tmp: