"""How the picture answers each input, for any game (bench_builder.input_response), and how it counts.""" from __future__ import annotations import json import math import pytest from bench_builder import independent_review, input_response from bench_builder.independent_review import PLAY_SHARE, apply_play_score, channel_feedback, play_feedback, play_score from bench_builder.replay_compare_tools import play_parts, scorecard SECONDS = 60 @pytest.fixture(autouse=True) def no_play_ceilings(tmp_path, monkeypatch): """Tests never read a calibration file a developer measured into the package.""" monkeypatch.setattr(independent_review, "PLAY_CEILINGS_FILE", tmp_path / "play_ceilings.json") def _stick(t: float) -> float: """A look stick that sweeps through every deflection, both ways.""" return round(math.sin(t * 0.9) * (0.25 + 0.75 * abs(math.sin(t * 0.13))), 3) def _presses() -> list[float]: return [3.0 + 4.5 * k for k in range(12)] def _session(tmp_path, *, pad: bool): session = tmp_path / "session" (session / "nitrogen").mkdir(parents=True) events = [] for at in _presses(): # a tapped jump key events += [{"event": "key_press", "code": "Space", "time_ns": int(at * 1e9)}, {"event": "key_release", "code": "Space", "time_ns": int((at + 0.15) * 1e9)}] for start in range(2, SECONDS - 4, 8): # a held move key, four seconds on, four off events += [{"event": "key_press", "code": "ArrowRight", "time_ns": int(start * 1e9)}, {"event": "key_release", "code": "ArrowRight", "time_ns": int((start + 4) * 1e9)}] events.sort(key=lambda event: event["time_ns"]) (session / "input.jsonl").write_text("\n".join(json.dumps(event) for event in events) + "\n") if pad: rows = [{"frame": i, "time_ns": int(i / 30 * 1e9), "buttons": [], "left_stick": [0, 0], "right_stick": [_stick(i / 30), 0]} for i in range(SECONDS * 30)] (session / "nitrogen" / "gamepad.jsonl").write_text("\n".join(json.dumps(row) for row in rows) + "\n") return session def _motion(*, look: float = 0.0, lag: float = 0.1, run: float = 0.0, jump: float = 0.0, confidence: float = 0.95): """A motion track whose pan follows the look stick and the held key, and whose tilt bumps after each press.""" rows = [] for index in range(SECONDS * 6): t = index / 6 + 1 / 12 held = any(start <= t - 0.05 < start + 4 for start in range(2, SECONDS - 4, 8)) since = min((t - at for at in _presses() if t >= at), default=9.0) tilt = -jump * math.sin(math.pi * since / 0.8) if since < 0.8 else 0.0 rows.append({"t": round(t, 3), "pan": look * _stick(t - lag) + (run if held else 0.0), "tilt": tilt, "expand": 0.0, "confidence": confidence, "cut": False}) return {"fps": 6.0, "rows": rows} def test_a_stick_a_held_key_and_a_tapped_key_each_get_their_answer_measured(tmp_path): session = _session(tmp_path, pad=True) response = input_response.measure(session, _motion(look=0.9, jump=0.4)) assert response["channels"]["right_x"] == "analog" and response["channels"]["key:Space"] == "held" look = next(pair for pair in response["pairs"] if (pair["channel"], pair["component"]) == ("right_x", "pan")) assert look["correlation"] > 0.9 and look["lag_s"] == pytest.approx(0.1, abs=0.06) full = look["gain"][-1] assert (full["from"], full["to"]) == (0.75, 1.0) and full["value"] == pytest.approx(0.9 * 0.85, abs=0.12) assert [row["value"] for row in look["gain"]] == sorted(row["value"] for row in look["gain"]) # more push, more turn jump = next(i for i in response["impulses"] if i["channel"] == "key:Space") assert jump["component"] == "tilt" and jump["peak"] < 0 and jump["presses"] == 12 lines = input_response.describe(response) assert any(line.startswith("Right stick right: the picture pans right") for line in lines) assert any(line.startswith("Pressing Space: the picture tilts up") for line in lines) def test_a_build_is_compared_input_by_input_with_the_same_recorded_hands(tmp_path): session = _session(tmp_path, pad=True) source = _motion(look=0.9, jump=0.4) assert input_response.compare(session, source, source)["score"] == pytest.approx(1.0) slow = input_response.compare(session, source, _motion(look=0.45, jump=0.4)) assert slow["score"] == pytest.approx(0.67, abs=0.08) # the look is half as fast, the jump is right assert "pans right" in slow["worst"][0] and "(0.50x)" in slow["worst"][0] late = input_response.compare(session, source, _motion(look=0.9, lag=0.4, jump=0.4)) assert any("later than the source's" in line for line in late["worst"]) mirrored = input_response.compare(session, source, _motion(look=-0.9, jump=0.4)) assert "the other way" in mirrored["worst"][0] no_jump = input_response.compare(session, source, _motion(look=0.9, jump=0.0)) assert any(line.startswith("Pressing Space") and "not at all" in line for line in no_jump["worst"]) # A picture too dark to measure is never read as "does not move", but the source set a target the build # could not be measured against, and the report says so (a review counts that part as 0). dark = input_response.compare(session, source, _motion(look=0.9, jump=0.4, confidence=0.3)) assert dark["score"] is None and "Not measurable in your picture" in dark["worst"][-1] assert dark["build_unmeasured"] is True and dark["build_frozen"] is False assert "build_unmeasured" not in slow def test_a_picture_that_never_changes_is_called_frozen_not_dark(tmp_path): session = tmp_path / "session" session.mkdir() events = [{"event": "mouse_move", "dx": 40 * math.sin(k / 60), "dy": 0, "time_ns": int(k / 30 * 1e9)} for k in range(SECONDS * 30)] (session / "input.jsonl").write_text("\n".join(json.dumps(event) for event in events) + "\n") rows = [{"t": i / 6, "pan": 0.25 * math.sin(i / 12), "tilt": 0.0, "expand": 0.0, "confidence": 1.0, "change": 0.04} for i in range(SECONDS * 6)] still = [{**row, "pan": 0.0, "change": 0.0003} for row in rows] frozen = input_response.compare(session, {"fps": 6.0, "rows": rows}, {"fps": 6.0, "rows": still}) assert frozen["score"] is None and frozen["build_unmeasured"] is True and frozen["build_frozen"] is True assert "does not change at all while these inputs are applied" in frozen["worst"][-1] assert "too dark" not in frozen["worst"][-1] and "mouse right" in frozen["worst"][-1] def test_a_keyboard_only_game_is_measured_from_its_held_keys(tmp_path): session = _session(tmp_path, pad=False) # no gamepad file: a side-scroller played on keys source = _motion(run=0.5, jump=0.3) response = input_response.measure(session, source) run = next(pair for pair in response["pairs"] if pair["channel"] == "key:ArrowRight") assert run["kind"] == "held" and run["component"] == "pan" and run["gain"][0]["value"] == pytest.approx(0.5, abs=0.05) half = input_response.compare(session, source, _motion(run=0.25, jump=0.3)) assert "Holding arrowright" in half["worst"][0] and "(0.50x)" in half["worst"][0] still = _motion() assert input_response.compare(session, still, still)["score"] is None # nothing in the picture answers def test_how_the_build_plays_is_part_of_completion(): channels = {"response": {"score": 0.4, "worst": ["Right stick right: the source's picture pans right at 1.08/s"]}, "feedback": {"score": 1.0}, "motion": {"score": 0.75}, "audio": {"score": None}} assert play_parts({"response_check": {"score": 0.4}, "motion_check": {"score": 0.75}}) == {"response": 0.4, "motion": 0.5} review = {"weighted_confirmed_percent": 95.0, "target_percent": 90, "fidelity_mean": 2.5, "min_fidelity": 2.0, "samples": [{"t": 0}], "missing_samples": [], "counts": {"missing": 0}, "confirmed": True, "channels": channels, "controls": {"status": "measured", "passed": 15, "failed": 5}} play = play_score(review) assert play["parts"] == {"response": 0.4, "motion": 0.5, "controls": 0.75, "feedback": 1.0} assert play["score"] == pytest.approx(0.662, abs=0.001) scored = apply_play_score(dict(review)) assert scored["weighted_confirmed_percent"] == pytest.approx((1 - PLAY_SHARE) * 95 + PLAY_SHARE * 66.2, abs=0.1) # Without measured ceilings the blend is reported, and the requirement list alone decides. assert scored["requirements_weighted_percent"] == 95.0 and scored["confirmed"] is True assert play["calibrated"] is False and independent_review.play_ceilings() is None assert "**Scene 95% ยท Control 0.66** make completion 86.4%" in play_feedback(scored)[1] assert "decides completion on the scene alone" in play_feedback(scored)[1] assert independent_review.three_scores(scored) == {"scene": 95.0, "control": pytest.approx(0.662, abs=0.001), "audio": None} # With ceilings (what a perfect build scores, as the channels report it) the blended number decides: # 95% on the requirement list no longer completes a build that plays at 0.66. independent_review.PLAY_CEILINGS_FILE.write_text("{}") decided = apply_play_score(dict(review)) assert decided["play"]["calibrated"] is True and decided["confirmed"] is False assert "not calibrated" not in play_feedback(decided)[1] and "not calibrated" in play_feedback(scored)[1] independent_review.PLAY_CEILINGS_FILE.write_text(json.dumps({"motion": 0.75, "response": 0.8, "controls": 0.6, "audio": "loud", "feedback": 0})) assert independent_review.play_ceilings() == {"motion": 0.75, "response": 0.8, "controls": 0.6} assert play_score(review)["parts"] == {"response": 0.5, "motion": 1.0, "controls": 1.0, "feedback": 1.0} assert apply_play_score(dict(review))["confirmed"] is True # 0.7 * 95 + 30 * 0.875 independent_review.PLAY_CEILINGS_FILE.unlink() # A part the source sets a target for and the build could not be measured on counts as 0, by name. hidden = play_score({**review, "controls": {"status": "error", "reason": "the browser did not finish"}, "channels": {"response": {"score": None, "build_unmeasured": True}, "feedback": {"score": 1.0}, "audio": {"score": None, "build_unmeasured": True}, "motion": {"score": None, "reason": "too little to compare"}}}) assert hidden["parts"] == {"response": 0.0, "audio": 0.0, "controls": 0.0, "feedback": 1.0} assert hidden["unmeasured"] == ["response", "audio", "controls"] and hidden["score"] == 0.25 assert "could not be measured there: response, audio, controls." in play_feedback( {**review, "play": hidden, "requirements_weighted_percent": 95.0})[1] assert any("pans right at 1.08/s" in line for line in channel_feedback(channels)) good = apply_play_score({**review, "channels": {"response": {"score": 0.95}, "feedback": {"score": 1.0}}, "controls": {"status": "measured", "passed": 20, "failed": 0}}) assert good["confirmed"] is True unmeasured = {key: value for key, value in review.items() if key not in ("channels", "controls")} assert apply_play_score(dict(unmeasured)) == unmeasured # nothing measured, nothing changed def test_a_replay_has_one_scorecard_and_says_what_moved(): report = {"fidelity_metric": {"mean": 0.49}, "response_check": {"score": 0.7}, "feedback_check": {"score": 0.0}, "motion_check": {"score": 0.76}, "beats_summary": {"expected": 4, "on_time": 1}, "spatial": {"summary": {"placement_score": 0.2}}} card = scorecard(report) # Three numbers; what they are made of is in parts. assert card["values"] == {"scene": 0.49, "control": 0.367} assert card["parts"] == {"response": 0.7, "feedback": 0.0, "motion": 0.52, "beats": 0.25, "placement": 0.2} assert card["weakest"] == "control" and card["weakest_part"] == "feedback" and "since_last_replay" not in card better = scorecard({**report, "feedback_check": {"score": 1.0}, "audio_check": {"score": 0.9}}, {"scorecard": card}) assert better["values"]["audio"] == 0.8 and better["since_last_replay"] == {"control": 0.25} # only what moved assert scorecard({**report, "fidelity_metric": {"mean": 0.495}}, {"scorecard": card})["since_last_replay"] == {} def test_an_action_is_compared_on_when_it_peaks_and_how_long_it_lasts(tmp_path): """A press that starts motion in the picture without moving the camera (an attack, a dodge).""" session = _session(tmp_path, pad=False) def swing(peak: float, lasts: float) -> dict: rows = [] for index in range(SECONDS * 6): t = index / 6 + 1 / 12 since = min((t - at for at in _presses() if t >= at), default=9.0) energy = 0.2 * math.sin(math.pi * min(since / (2 * peak), 0.5 + (since - peak) / (2 * (lasts - peak)))) \ if since < lasts else 0.0 rows.append({"t": round(t, 3), "pan": 0.0, "tilt": 0.0, "expand": 0.0, "energy": max(0.0, energy), "confidence": 0.95, "cut": False}) return {"rows": rows} source = input_response.measure(session, swing(0.4, 1.2)) action = next(i for i in source["impulses"] if i["component"] == "energy") assert action["peak_s"] == pytest.approx(0.4, abs=0.1) and action["lasts_s"] == pytest.approx(0.95, abs=0.2) assert any("starts an action" in line for line in input_response.describe(source)) same = input_response.compare(session, swing(0.4, 1.2), swing(0.4, 1.2), 0.0, SECONDS) assert not [line for line in same["worst"] if "action" in line] short = input_response.compare(session, swing(0.4, 1.2), swing(0.15, 0.4), 0.0, SECONDS) assert any("the source's action peaks" in line and "yours peaks" in line for line in short["worst"]) assert short["score"] < same["score"]