Recreate-AAA / bench_builder /input_response.py
CharlieDreemur's picture
RecreateAAA 0.1.0 from Recreate-AAA/Recreate-AAA@7da1a3d
966b234 verified
Raw History Blame Contribute Delete
24 kB
"""How the picture answers each input, for any game: the source's response, and a build's beside it.
A recording carries the player's inputs next to the picture. For every input that was really used (each
stick axis, each held key, the mouse) this measures what the picture does while it is applied: how fast it
pans, tilts and expands (``motion_track``), per amount of input, and how long after the input. That is the
game's feel in numbers, and it needs no knowledge of the game: in a first-person game the look stick pans
the picture, in a side-scroller the move key does, in a driving game the throttle expands it.
A replay plays the same inputs into the build, so the build's video is measured with the same inputs and
the two responses are compared pair by pair (``compare``): the same stick push that pans the source at
0.42 frame-widths a second must pan the build at 0.42, after the same delay.
Units are the motion track's: pan and tilt in frame-widths (frame-heights) per second, expand per second.
"""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any, Mapping, Sequence
import numpy as np
SCHEMA = "gamedevbench.input-response.v1"
COMPARE_SCHEMA = "gamedevbench.input-response-compare.v1"
SAMPLE_HZ = 30.0
COMPONENTS = ("pan", "tilt", "expand")
DEFLECTIONS = (0.05, 0.2, 0.35, 0.5, 0.75, 1.01)
STICK_KEYS = frozenset("wasdijkl") # the keys a stick becomes in a trace made from a gamepad
MIN_ACTIVE_SECONDS = 3.0 # an input applied for less is not modelled
MIN_CORRELATION = 0.3 # the input explains the picture's motion at least this well
MIN_GAIN = {"pan": 0.02, "tilt": 0.02, "expand": 0.03, "energy": 0.01}
MAX_LAG = 0.4
LATE_SECONDS = 0.15 # a build answering this much later than the source is told so
AGREE = 0.7 # pairs below this agreement are listed for the builder
IMPULSE_SECONDS = 1.2 # how long after a press the picture's motion is followed
# An action (an attack, a dodge, a reload) often leaves the camera alone: what the press starts is motion in
# the picture. Its overall motion is followed for longer, and its timing (peak, how long it lasts) compared.
ACTION = "energy"
ACTION_SECONDS = 2.0
MIN_PRESSES = 4 # presses a key needs for its averaged motion to be judged
IMPULSE_Z = 4.0 # the averaged motion stands this far above random moments
# Share of picture blocks that found themselves in the next frame. Below this (dark or flat frames) the
# motion track reads a real turn as none: measured against a build's own camera, it reported 0.82 of the
# true pan at 0.8 and above, and 0.07 or less under it. Such rows are left out, not read as "no motion".
_CONFIDENT = 0.8
_FROZEN_CHANGE = 0.002 # mean luma change per step (motion_track's ``change``) of a picture that does not
# change at all: encoder noise only, a sixth of what the motion track calls still
_WORDS = {"pan": ("pans right", "pans left"), "tilt": ("tilts down", "tilts up"),
"expand": ("moves forward (expands)", "moves back (contracts)"),
"energy": ("is in motion", "comes to rest")}
_NAMES = {"left_x": "left stick right", "left_up": "left stick up", "right_x": "right stick right",
"right_up": "right stick up", "mouse_x": "mouse right", "mouse_y": "mouse down"}
def channel_name(channel: str) -> str:
return _NAMES.get(channel) or ("holding " + channel.removeprefix("key:").removeprefix("Key")
if channel.startswith("key:") else channel)
# Inputs ---------------------------------------------------------------------------------------
def _events(trace: Path) -> list[dict[str, Any]]:
return [json.loads(line) for line in Path(trace).read_text(encoding="utf-8").splitlines() if line.strip()]
def input_channels(session: Path, start: float = 0.0, end: float | None = None
) -> tuple[np.ndarray, dict[str, dict[str, Any]]]:
"""``(times, {channel: {"kind", "values"}})`` on a 30 Hz grid of recording seconds.
Stick axes come from ``nitrogen/gamepad.jsonl`` (x right and y up are positive), held keys and mouse
travel from ``input.jsonl``. With a gamepad file the keys its sticks became are left out."""
session = Path(session)
pad, trace = session / "nitrogen" / "gamepad.jsonl", session / "input.jsonl"
events = _events(trace) if trace.is_file() else []
rows = _events(pad) if pad.is_file() else []
last = max([float(e.get("time_ns", 0)) / 1e9 for e in events] + [float(r["time_ns"]) / 1e9 for r in rows] + [0.0])
stop = last if end is None else min(float(end), last)
times = np.arange(float(start), max(stop, float(start)) + 1e-9, 1.0 / SAMPLE_HZ)
channels: dict[str, dict[str, Any]] = {}
if len(rows) >= 2:
at = np.array([float(r["time_ns"]) / 1e9 for r in rows])
index = np.clip(np.searchsorted(at, times, side="right") - 1, 0, len(rows) - 1)
sticks = np.array([[*(r.get("left_stick") or [0, 0]), *(r.get("right_stick") or [0, 0])] for r in rows], float)
for column, (name, sign) in enumerate((("left_x", 1), ("left_up", -1), ("right_x", 1), ("right_up", -1))):
channels[name] = {"kind": "analog", "values": sign * sticks[index, column]}
held: dict[str, float] = {}
keys: dict[str, np.ndarray] = {}
mouse = np.zeros((len(times), 2))
for event in sorted(events, key=lambda e: int(e.get("time_ns", 0))):
t, kind = float(event.get("time_ns", 0)) / 1e9, event.get("event")
code = str(event.get("code") or event.get("key") or "")
if kind == "key_press" and code and code not in held:
held[code] = t
elif kind == "key_release" and code in held:
series = keys.setdefault(code, np.zeros(len(times)))
series[(times >= held.pop(code)) & (times < t)] = 1.0
elif kind == "mouse_move":
slot = int((t - float(start)) * SAMPLE_HZ)
if 0 <= slot < len(times):
mouse[slot] += (float(event.get("dx") or 0), float(event.get("dy") or 0))
for code, since in held.items():
keys.setdefault(code, np.zeros(len(times)))[times >= since] = 1.0
for code, series in keys.items():
letter = code.removeprefix("Key").casefold()
if rows and letter in STICK_KEYS:
continue
channels[f"key:{code}"] = {"kind": "held", "values": series}
if np.abs(mouse).sum() > 0:
for column, name in enumerate(("mouse_x", "mouse_y")):
channels[name] = {"kind": "mouse", "values": mouse[:, column] * SAMPLE_HZ / 1000.0} # 1000 px per second
return times, channels
# Response -------------------------------------------------------------------------------------
def _per_row(times: np.ndarray, values: np.ndarray, rows: np.ndarray, step: float, lag: float) -> np.ndarray:
"""Mean of ``values`` over each motion row's interval, read ``lag`` seconds earlier."""
total = np.concatenate([[0.0], np.cumsum(values)])
low = np.searchsorted(times, rows - step / 2 - lag)
high = np.searchsorted(times, rows + step / 2 - lag)
return (total[high] - total[low]) / np.maximum(high - low, 1)
def _motion(motion: Mapping[str, Any], shift: float = 0.0) -> dict[str, np.ndarray]:
rows = motion.get("rows") or []
arrays = {key: np.array([float(row.get(key) or 0.0) for row in rows]) for key in ("t", *COMPONENTS, ACTION, "confidence")}
arrays["t"] = arrays["t"] + shift
arrays["sure"] = (arrays["confidence"] > _CONFIDENT) & ~np.array([bool(row.get("cut")) for row in rows], bool)
return arrays
def _threshold(kind: str, values: np.ndarray) -> float:
if kind == "analog":
return DEFLECTIONS[0]
if kind == "held":
return 0.5
return max(0.02, float(np.percentile(np.abs(values), 90)) * 0.1)
def _gain(kind: str, x: np.ndarray, y: np.ndarray, sure: np.ndarray, threshold: float) -> list[dict[str, Any]]:
"""What the picture does per amount of input: by deflection for a stick, held against not held for a key,
per 1000 pixels a second for the mouse."""
if kind == "analog":
signed = np.sign(x) * y
rows = []
for low, high in zip(DEFLECTIONS, DEFLECTIONS[1:]):
chosen = sure & (np.abs(x) >= low) & (np.abs(x) < high)
if chosen.sum() >= 8:
rows.append({"from": low, "to": min(high, 1.0), "value": round(float(np.median(signed[chosen])), 4),
"samples": int(chosen.sum())})
return rows
active = sure & (np.abs(x) > threshold)
if active.sum() < 8:
return []
if kind == "held":
rest = sure & (np.abs(x) < 0.05)
base = float(np.median(y[rest])) if rest.sum() >= 8 else 0.0
return [{"value": round(float(np.median(y[active])) - base, 4), "samples": int(active.sum())}]
slope = float(np.sum(x[active] * y[active]) / max(float(np.sum(x[active] ** 2)), 1e-9))
return [{"value": round(slope, 4), "samples": int(active.sum())}]
def _pair(times: np.ndarray, channel: Mapping[str, Any], m: Mapping[str, np.ndarray], component: str,
lags: Sequence[float]) -> dict[str, Any] | None:
step = float(np.median(np.diff(m["t"])))
values, kind, sure, y = channel["values"], channel["kind"], m["sure"], m[component]
threshold = _threshold(kind, values)
if sure.sum() < 8:
return None
best: tuple[float, float, np.ndarray] | None = None
for lag in lags:
x = _per_row(times, values, m["t"], step, float(lag))
if x[sure].std() < 1e-9 or y[sure].std() < 1e-9:
return None
value = float(np.corrcoef(x[sure], y[sure])[0, 1])
if best is None or abs(value) > abs(best[1]):
best = (float(lag), value, x)
lag, correlation, x = best
active = float((sure & (np.abs(x) > threshold)).sum()) * step
gain = _gain(kind, x, y, sure, threshold)
if not gain:
return None
return {"component": component, "lag_s": round(lag, 2), "correlation": round(correlation, 3),
"active_seconds": round(active, 1), "gain": gain}
def _presses(times: np.ndarray, values: np.ndarray) -> np.ndarray:
return times[1:][(values[1:] > 0.5) & (values[:-1] <= 0.5)]
def _lasts(course: Sequence[float], step: float) -> float:
"""Seconds from the press until the motion it started has fallen back under half its peak."""
course = np.abs(np.asarray(course, float))
peak = int(np.argmax(course))
below = np.where(course[peak:] < 0.5 * course[peak])[0]
return round(((peak + below[0]) if len(below) else len(course)) * step, 2)
def _after(moments: np.ndarray, m: Mapping[str, np.ndarray], component: str, count: int) -> np.ndarray | None:
"""The component's mean course over the ``count`` rows after each moment, from its value just before."""
courses = []
for moment in moments:
first = int(np.searchsorted(m["t"], moment))
if first < 1 or first + count > len(m["t"]) or not m["sure"][first - 1:first + count].all():
continue
courses.append(m[component][first:first + count] - m[component][first - 1])
return np.mean(courses, axis=0) if len(courses) >= MIN_PRESSES else None
def _impulses(times: np.ndarray, channels: Mapping[str, Mapping[str, Any]], m: Mapping[str, np.ndarray],
significant: bool) -> list[dict[str, Any]]:
"""What the picture does in the second after a key goes down, averaged over its presses: a jump's rise and
fall, a dash, a recoil kick. With ``significant`` only courses that stand out against random moments."""
if len(m["t"]) < 30:
return []
step = float(np.median(np.diff(m["t"])))
rng = np.random.default_rng(7)
found = []
for name, channel in channels.items():
if channel["kind"] != "held":
continue
moments = _presses(times, channel["values"])
if len(moments) < MIN_PRESSES:
continue
for component in (*COMPONENTS, ACTION):
count = max(3, round((ACTION_SECONDS if component == ACTION else IMPULSE_SECONDS) / step))
course = _after(moments, m, component, count)
if course is None:
continue
peak = int(np.argmax(np.abs(course)))
if significant:
chance = [c for c in (_after(rng.uniform(m["t"][1], m["t"][-count - 1], len(moments)), m, component, count)
for _ in range(60)) if c is not None]
if len(chance) < 20 or abs(course[peak]) < MIN_GAIN[component]:
continue
noise = float(np.std([c[peak] for c in chance])) or 1e-9
if abs(course[peak]) / noise < IMPULSE_Z:
continue
found.append({"channel": name, "component": component, "presses": int(len(moments)),
"step_s": round(step, 3), "course": [round(float(v), 4) for v in course],
"peak": round(float(course[peak]), 4), "peak_s": round((peak + 0.5) * step, 2),
**({"lasts_s": _lasts(course, step)} if component == ACTION else {})})
return found
def measure(session: Path, motion: Mapping[str, Any], start: float = 0.0, end: float | None = None) -> dict[str, Any]:
"""The response of the recording in ``session`` (its inputs) whose picture moved as ``motion`` says."""
times, channels = input_channels(session, start, end)
m = _motion(motion)
pairs: list[dict[str, Any]] = []
if len(m["t"]) >= 30 and len(times) >= 30:
lags = np.arange(0.0, MAX_LAG + 1e-9, 0.05)
for name, channel in channels.items():
for component in COMPONENTS:
pair = _pair(times, channel, m, component, lags)
if (pair and pair["active_seconds"] >= MIN_ACTIVE_SECONDS
and abs(pair["correlation"]) >= MIN_CORRELATION
and max(abs(row["value"]) for row in pair["gain"]) >= MIN_GAIN[component]):
pairs.append({"channel": name, "kind": channel["kind"], **pair})
pairs.sort(key=lambda pair: -abs(pair["correlation"]))
return {"schema": SCHEMA, "channels": {name: channel["kind"] for name, channel in channels.items()}, "pairs": pairs,
"impulses": _impulses(times, channels, m, significant=True)}
def _amount(pair: Mapping[str, Any], row: Mapping[str, Any]) -> str:
if pair["kind"] == "analog":
return f"at a {row['from']:g}-{row['to']:g} push"
return "per 1000 px/s" if pair["kind"] == "mouse" else "while held"
def _press_name(impulse: Mapping[str, Any]) -> str:
return "Pressing " + channel_name(impulse["channel"]).removeprefix("holding ")
def _impulse_words(impulse: Mapping[str, Any]) -> str:
return _WORDS[impulse["component"]][0 if impulse["peak"] > 0 else 1]
def _direction(pair: Mapping[str, Any]) -> str:
strongest = max(pair["gain"], key=lambda row: abs(row["value"]))["value"]
return _WORDS[pair["component"]][0 if strongest > 0 else 1]
def describe(response: Mapping[str, Any] | None, limit: int = 8) -> list[str]:
"""One line per input the source answers, strongest first."""
lines = []
for pair in ((response or {}).get("pairs") or [])[:limit]:
gains = ", ".join(f"{abs(row['value']):.2f}/s {_amount(pair, row)}" for row in pair["gain"])
lines.append(f"{channel_name(pair['channel']).capitalize()}: the picture {_direction(pair)} ({gains}), "
f"{pair['lag_s']:g} s after the input (correlation {pair['correlation']:+.2f}).")
for impulse in ((response or {}).get("impulses") or [])[:limit]:
if impulse["component"] == ACTION:
lines.append(f"{_press_name(impulse)} starts an action: the picture's motion peaks {impulse['peak_s']:g} s "
f"after the press and has settled after {impulse['lasts_s']:g} s "
f"(mean of {impulse['presses']} presses).")
continue
lines.append(f"{_press_name(impulse)}: the picture {_impulse_words(impulse)}, peaking at "
f"{abs(impulse['peak']):.2f}/s {impulse['peak_s']:g} s after the press "
f"(mean of {impulse['presses']} presses).")
return lines
def compare(session: Path, source_motion: Mapping[str, Any], build_motion: Mapping[str, Any],
offset: float = 0.0, seconds: float | None = None) -> dict[str, Any]:
"""The build's response beside the source's for the same inputs; ``build`` video time - ``offset`` =
recording time. ``score`` is the agreement of the gains over every input the source answers (1 = the
same amounts in the same directions); ``worst`` are lines for the builder."""
source = measure(session, source_motion, 0.0, seconds)
if not source["pairs"] and not source["impulses"]:
return {"schema": COMPARE_SCHEMA, "score": None,
"reason": "no recorded input explains the source picture's motion well enough to compare"}
times, channels = input_channels(session, 0.0, seconds)
m = _motion(build_motion, shift=-float(offset))
lags = np.arange(0.0, MAX_LAG + 0.2 + 1e-9, 0.05)
pairs, worst, total, weight = [], [], 0.0, 0.0
unseen: list[str] = []
for expected in source["pairs"]:
own = _pair(times, channels[expected["channel"]], m, expected["component"], lags) if len(m["t"]) >= 30 else None
theirs = {(row.get("from"), row.get("to")): row for row in (own or {}).get("gain") or []}
agreement, samples, shown = 0.0, 0, None
for row in expected["gain"]:
build_row = theirs.get((row.get("from"), row.get("to")))
if build_row is None: # the build's picture was too dark or flat to measure at this amount
continue
s, b = float(row["value"]), float(build_row["value"])
match = 0.0 if s * b <= 0 else min(abs(b) / abs(s), abs(s) / abs(b))
agreement += match * row["samples"]
samples += row["samples"]
if shown is None or abs(s) > abs(shown[0]):
shown = (s, b, row)
if not samples:
unseen.append(channel_name(expected["channel"]))
continue
agreement = agreement / samples
late = (own["lag_s"] - expected["lag_s"]) if own and abs(own["correlation"]) >= MIN_CORRELATION else None
pairs.append({"channel": expected["channel"], "component": expected["component"],
"agreement": round(agreement, 3), "source": expected["gain"], "build": (own or {}).get("gain"),
"source_lag_s": expected["lag_s"], "build_lag_s": (own or {}).get("lag_s") if late is not None else None,
"source_correlation": expected["correlation"], "build_correlation": (own or {}).get("correlation")})
share = abs(float(expected["correlation"]))
total += agreement * share
weight += share
if agreement < AGREE and shown:
s, b, row = shown
what = f"{channel_name(expected['channel']).capitalize()}: the source's picture {_direction(expected)}"
ratio = f"{abs(b) / abs(s):.2f}x" if s * b > 0 else "the other way" if b * s < 0 else "not at all"
worst.append((agreement, f"{what} at {abs(s):.2f}/s {_amount(expected, row)}; yours does "
f"{abs(b):.2f}/s ({ratio})."))
elif late is not None and late >= LATE_SECONDS:
worst.append((agreement, f"{channel_name(expected['channel']).capitalize()}: your picture answers "
f"{late:.2f} s later than the source's ({own['lag_s']:g} s against "
f"{expected['lag_s']:g} s)."))
own_impulses = {(i["channel"], i["component"]): i for i in _impulses(times, channels, m, significant=False)}
impulses = []
for expected in source["impulses"]:
own = own_impulses.get((expected["channel"], expected["component"]))
if own is None:
unseen.append(_press_name(expected).casefold())
continue
s_course, b_course = np.array(expected["course"]), np.array(own["course"])
if expected["component"] == ACTION:
# How much the picture moves depends on what is drawn (texture, contrast); the shape over time does not.
s_course = s_course / max(float(np.abs(s_course).max()), 1e-9)
b_course = b_course / max(float(np.abs(b_course).max()), 1e-9)
agreement = max(0.0, 1.0 - float(np.abs(s_course - b_course).sum())
/ max(float((np.abs(s_course) + np.abs(b_course)).sum()), 1e-9))
b_peak = float(b_course[int(np.argmax(np.abs(s_course)))])
impulses.append({"channel": expected["channel"], "component": expected["component"],
"agreement": round(agreement, 3), "source": expected["course"], "build": own["course"]})
total += agreement * 0.5
weight += 0.5
if expected["component"] == ACTION:
# An action is judged on its timing: when it peaks and how long it lasts.
if abs(own["peak_s"] - expected["peak_s"]) > LATE_SECONDS or abs(own["lasts_s"] - expected["lasts_s"]) > 0.25:
worst.append((min(agreement, AGREE - 0.01), f"{_press_name(expected)}: the source's action peaks "
f"{expected['peak_s']:g} s after the press and lasts {expected['lasts_s']:g} s; yours "
f"peaks at {own['peak_s']:g} s and lasts {own['lasts_s']:g} s."))
elif agreement < AGREE:
ratio = (f"{abs(b_peak) / abs(expected['peak']):.2f}x" if b_peak * expected["peak"] > 0
else "the other way" if b_peak * expected["peak"] < 0 else "not at all")
worst.append((agreement, f"{_press_name(expected)}: the source's picture {_impulse_words(expected)}, peaking "
f"at {abs(expected['peak']):.2f}/s {expected['peak_s']:g} s after the press; "
f"yours is at {abs(b_peak):.2f}/s then ({ratio}; course agreement {agreement:.2f})."))
changes = [float(row["change"]) for row in build_motion.get("rows") or []
if isinstance(row.get("change"), (int, float))]
frozen = bool(changes) and float(np.median(changes)) < _FROZEN_CHANGE
if unseen:
names = ", ".join(dict.fromkeys(unseen)) + "."
worst.append((1.0, ("Your picture does not change at all while these inputs are applied (frozen, paused, "
"blank, or not taking the input), so there is no answer to measure: " if frozen else
"Not measurable in your picture (too dark or too flat to show motion while the input "
"is applied): ") + names))
return {"schema": COMPARE_SCHEMA, "score": round(total / weight, 3) if weight else None, "pairs": pairs,
"impulses": impulses,
# The source answers inputs and nothing of it could be measured in the build: a review counts
# that as 0 for this part, not as "no target".
**({"build_unmeasured": True, "build_frozen": frozen} if not weight and unseen else {}),
"worst": [line for _agreement, line in sorted(worst, key=lambda item: item[0])],
"how_to_read": "Each pair is one input the source's picture answers (a stick axis, a held key, the mouse) "
"and one way it answers (pan, tilt, expand), measured on both videos with the same "
"recorded inputs. `source` and `build` are the picture's speed per amount of input "
"(frame-widths per second); agreement 1 means the same speed in the same direction."}