Show live Horizon terrain and radar views in the web panel
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
"""Single local game bridge. HTTP clients only see cached projections and the archive."""
|
||||
from collections import deque
|
||||
from dataclasses import dataclass, replace
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import queue
|
||||
@@ -10,6 +11,7 @@ import socket
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
from .terrain import TerrainTiles
|
||||
|
||||
TOKEN = re.compile(r"[0-9a-f]{16,32}\Z")
|
||||
MAX_PACKET = 1 << 20
|
||||
@@ -22,6 +24,14 @@ def local_chat(endpoint: Path, text: str):
|
||||
"""Use Horizon's local transport, with no arbitrary commands from HTTP."""
|
||||
if not text.startswith("chat /airdef panel ") or "\n" in text or "\r" in text:
|
||||
raise ValueError("Invalid local bridge command")
|
||||
return _local_request(endpoint, text)
|
||||
|
||||
|
||||
def local_terrain(endpoint, x, z, step):
|
||||
return _local_request(endpoint, f"terrain-tile {x:d} {z:d} {step:d}")
|
||||
|
||||
|
||||
def _local_request(endpoint, text):
|
||||
if os.name == "nt" or endpoint.suffix == ".json":
|
||||
config = read_json(endpoint, 4096)
|
||||
port, token = config["port"], config["token"]
|
||||
@@ -84,10 +94,14 @@ def validate_wave(payload, catalog):
|
||||
|
||||
|
||||
def public_view(raw):
|
||||
world, dimension = raw.get("terrainWorld"), raw.get("terrainDimension")
|
||||
scope = f'{raw["session"]}\0{world}\0{dimension}'.encode("utf-8")
|
||||
return {
|
||||
"version": 1, "session": raw["session"], "world": raw["world"], "tick": raw["tick"],
|
||||
"frame": raw["live"], "catalog": raw["catalog"],
|
||||
"selected": raw.get("selected"), "canLaunch": raw["canLaunch"],
|
||||
"terrain": hashlib.blake2s(scope, digest_size=12).hexdigest() if world and dimension else None,
|
||||
"mapCenter": raw.get("mapCenter"),
|
||||
}
|
||||
|
||||
|
||||
@@ -154,7 +168,8 @@ class LiveRevision:
|
||||
|
||||
|
||||
class Bridge:
|
||||
def __init__(self, endpoint, data, store, *, debug=False, interval=1.0, transport=local_chat):
|
||||
def __init__(self, endpoint, data, store, *, debug=False, interval=0.5, transport=local_chat,
|
||||
terrain_transport=local_terrain):
|
||||
self.endpoint, self.data, self.store = endpoint, data, store
|
||||
self.debug, self.interval, self.transport = debug, interval, transport
|
||||
self.lock = threading.Lock()
|
||||
@@ -163,6 +178,11 @@ class Bridge:
|
||||
self.revisions = deque([LiveRevision(0, {})], maxlen=LIVE_REVISIONS)
|
||||
self.epoch = secrets.token_hex(8)
|
||||
self.cursors = {}
|
||||
self.terrain = TerrainTiles(complete_ttl=30, partial_ttl=2)
|
||||
self.terrain_transport = terrain_transport
|
||||
self.terrain_world = None
|
||||
self.terrain_dimension = None
|
||||
self.next_frame = 0.0
|
||||
self.thread = threading.Thread(target=self.worker, name="airdef-local-bridge", daemon=True)
|
||||
|
||||
def begin(self):
|
||||
@@ -175,6 +195,7 @@ class Bridge:
|
||||
|
||||
def worker(self):
|
||||
next_poll = time.monotonic()
|
||||
next_tile = next_poll
|
||||
backoff = self.interval
|
||||
while not self.stop.is_set():
|
||||
now = time.monotonic()
|
||||
@@ -187,8 +208,13 @@ class Bridge:
|
||||
self.disconnect()
|
||||
next_poll = time.monotonic() + backoff
|
||||
try:
|
||||
job = self.queue.get(timeout=min(0.25, self.interval))
|
||||
job = self.queue.get(timeout=max(0.01, min(0.10, next_poll - time.monotonic())))
|
||||
except queue.Empty:
|
||||
now = time.monotonic()
|
||||
if next_tile <= now < next_poll:
|
||||
scope, world, dimension = self.terrain_source()
|
||||
if scope and self.terrain.work(scope, lambda x, z, step: self.read_terrain(world, dimension, x, z, step)):
|
||||
next_tile = time.monotonic() + 0.34
|
||||
continue
|
||||
self.dispatch(*job)
|
||||
|
||||
@@ -202,12 +228,37 @@ class Bridge:
|
||||
if raw.get("nonce") != nonce or raw.get("version") != 1 or not TOKEN.fullmatch(raw["session"]):
|
||||
raise ValueError("Snapshot does not belong to this request")
|
||||
public = public_view(raw)
|
||||
self.store.append(raw, public)
|
||||
public["sampleMs"] = round(self.interval * 1000)
|
||||
now = time.monotonic()
|
||||
capture = raw["session"] != session or now >= self.next_frame
|
||||
self.store.append(raw, public, capture_frame=capture)
|
||||
if capture:
|
||||
self.next_frame = now + 1.0
|
||||
self.cursors = {raid["id"]: raid["next"] for raid in raw["raids"]}
|
||||
with self.lock:
|
||||
number = self.revisions[-1].number + 1
|
||||
self.terrain_world = raw.get("terrainWorld")
|
||||
self.terrain_dimension = raw.get("terrainDimension")
|
||||
self.revisions.append(LiveRevision(number, public, raw.get("enemy"), raw.get("truth"), True, time.time()))
|
||||
|
||||
def terrain_source(self):
|
||||
with self.lock:
|
||||
state = self.revisions[-1]
|
||||
return (state.network.get("terrain"), self.terrain_world, self.terrain_dimension) if state.connected else (None, None, None)
|
||||
|
||||
def read_terrain(self, world, dimension, x, z, step):
|
||||
result = self.terrain_transport(self.endpoint, x, z, step)
|
||||
if result.get("world") != world or result.get("dimension") != dimension:
|
||||
raise ValueError("Terrain belongs to a different world")
|
||||
return result
|
||||
|
||||
def terrain_tile(self, scope, x, z, step):
|
||||
with self.lock:
|
||||
state = self.revisions[-1]
|
||||
if not state.connected or state.network.get("terrain") != scope:
|
||||
raise ValueError("Рельеф доступен для текущего мира")
|
||||
return self.terrain.get(scope, x, z, step)
|
||||
|
||||
def disconnect(self):
|
||||
with self.lock:
|
||||
current = self.revisions[-1]
|
||||
|
||||
Reference in New Issue
Block a user