Replays: smoke rebuilt from the recording, recorded objects and searchlights, film cut in true order, export sessions guarded, gun camera above water; export keeps its last frames; hd_bench no longer excuses strong flicker (#76-#84, fork patch 35)
build / mod (push) Successful in 3m49s
build / mod (push) Successful in 3m49s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+36
-6
@@ -20,7 +20,11 @@
|
||||
Поэтому кадры не сравниваются целиком: по кадрам одного прогона пиксель, у которого размах значений между
|
||||
кадрами больше --motion-level (16 из 255), считается движущимся (вода, облака, листва). Такие пиксели не
|
||||
участвуют в сравнении с базой (ни в одном из двух прогонов). Мерцание считается по остальным пикселям:
|
||||
размах между кадрами больше --flicker-level (6 из 255) и не больше --motion-level. Для движущейся части
|
||||
размах между кадрами больше --flicker-level (6 из 255) и не больше --motion-level. Сильное мерцание
|
||||
по кадрам одного прогона от движения не отличить, поэтому «движение» само ограничено: доля непроверенных
|
||||
пикселей (--max-animated), сумма «неустойчивых» (--max-flicker), пиксели, ставшие движущимися против
|
||||
БАЗЫ (--max-new-animated: маска берётся из базы, не из проверяемого прогона), и доля проверяемых
|
||||
пикселей (--min-static: ноль статичных — не «ноль ошибки», а провал). Для движущейся части
|
||||
выводится отдельная средняя разница, только для информации. Картинка `<сцена>_motion.png` показывает маску.
|
||||
|
||||
Коды выхода: 0 — всё в порогах и бюджете; 1 — есть превышение; 2 — ошибка запуска или аргументов.
|
||||
@@ -337,19 +341,31 @@ def motion_range(rgbs):
|
||||
|
||||
|
||||
def flicker_stats(rng, w, h, n_frames, motion_level, flicker_level):
|
||||
"""По размаху каждого пикселя между кадрами одного прогона. `pct` — мерцание: размах в
|
||||
(flicker_level, motion_level]; `animated_pct` — выше motion_level (движение: вода, облака,
|
||||
листва; ИЛИ очень сильное мерцание — по одному прогону их не различить). `unsteady_pct` — сумма
|
||||
обоих: все пиксели с размахом выше flicker_level, она не падает, когда мерцание усиливается и
|
||||
переходит из одной корзины в другую. `unverified_pct` — доля пикселей, которые этот прогон
|
||||
ничем не проверяет (то же, что animated_pct); `static_pct` — доля проверяемых."""
|
||||
npx = w * h
|
||||
flick = sum(1 for r in rng if flicker_level < r <= motion_level)
|
||||
moving = sum(1 for r in rng if r > motion_level)
|
||||
return {"pct": 100.0 * flick / npx, "animated_pct": 100.0 * moving / npx,
|
||||
"unsteady_pct": 100.0 * (flick + moving) / npx,
|
||||
"unverified_pct": 100.0 * moving / npx, "static_pct": 100.0 * (npx - moving) / npx,
|
||||
"frames": n_frames, "size": [w, h]}
|
||||
|
||||
|
||||
def compare_runs(cur_rgb, cur_rng, base_rgb, base_rng, w, h, motion_level, diff_out=None, motion_out=None):
|
||||
"""Первый кадр текущего прогона против первого кадра базы. Движущиеся пиксели (в любом из двух
|
||||
прогонов) в сравнении не участвуют: mean и pct — только по статичным; для движущихся — отдельная
|
||||
средняя разница (информация, не порог)."""
|
||||
"""Первый кадр текущего прогона против первого кадра базы. Из сравнения исключаются только
|
||||
пиксели, которые двигались уже в БАЗЕ (маска воспроизводимая, не зависит от того, что показал
|
||||
проверяемый прогон): mean и pct — по остальным; для движущихся — отдельная средняя разница
|
||||
(информация, не порог). Пиксель, ставший «движущимся» только в текущем прогоне (мерцание,
|
||||
призраки TAA), из сравнения не исключается и считается в new_animated_pct. Доля проверяемых
|
||||
пикселей — static_pct: при нуле mean не «0 ошибки», а отсутствие проверки (см. judge)."""
|
||||
npx = w * h
|
||||
static = bytes(1 if (a <= motion_level and b <= motion_level) else 0 for a, b in zip(cur_rng, base_rng))
|
||||
static = bytes(1 if b <= motion_level else 0 for b in base_rng)
|
||||
new_anim = sum(1 for a, b in zip(cur_rng, base_rng) if a > motion_level and b <= motion_level)
|
||||
d = bytes(map(abs, map(operator.sub, cur_rgb[0], base_rgb[0])))
|
||||
dpix = _per_pixel_max(d)
|
||||
n_static = sum(static)
|
||||
@@ -358,6 +374,7 @@ def compare_runs(cur_rgb, cur_rng, base_rgb, base_rng, w, h, motion_level, diff_
|
||||
over = sum(1 for p, s in zip(dpix, static) if s and p > DIFF_LEVEL)
|
||||
moving_mean = (sum(itertools.compress(d, _expand3(bytes(1 - s for s in static)))) / (3.0 * n_moving)
|
||||
if n_moving else 0.0)
|
||||
cur_anim = sum(1 for a in cur_rng if a > motion_level)
|
||||
if diff_out:
|
||||
img = bytearray(min(255, v * DIFF_GAIN) for v in d)
|
||||
for i, s in enumerate(static):
|
||||
@@ -368,7 +385,9 @@ def compare_runs(cur_rgb, cur_rng, base_rgb, base_rng, w, h, motion_level, diff_
|
||||
if motion_out:
|
||||
write_png_rgb(motion_out, w, h, bytes(_expand3(bytes(0 if s else 255 for s in static))))
|
||||
return {"mean": mean, "pct": 100.0 * over / npx, "animated_pct": 100.0 * n_moving / npx,
|
||||
"animated_mean": moving_mean, "size": [w, h]}
|
||||
"animated_mean": moving_mean, "static_pct": 100.0 * n_static / npx,
|
||||
"new_animated_pct": 100.0 * new_anim / npx, "cur_animated_pct": 100.0 * cur_anim / npx,
|
||||
"size": [w, h]}
|
||||
|
||||
|
||||
# --- тайминги -----------------------------------------------------------------------------------
|
||||
@@ -482,11 +501,17 @@ def judge(entry, args):
|
||||
fl = entry.get("flicker")
|
||||
if fl and args.max_flicker is not None and fl["pct"] > args.max_flicker:
|
||||
reasons.append(f"мерцание статичных пикселей {fl['pct']:.2f}% > {args.max_flicker:g}%")
|
||||
if fl and fl["animated_pct"] > args.max_animated:
|
||||
reasons.append(f"не проверено (размах > {args.motion_level}/255) {fl['animated_pct']:.1f}% кадра > {args.max_animated:g}%")
|
||||
base = entry.get("vs_baseline")
|
||||
if base:
|
||||
if base.get("error"):
|
||||
reasons.append(base["error"])
|
||||
else:
|
||||
if base["static_pct"] < args.min_static:
|
||||
reasons.append(f"проверяемых пикселей {base['static_pct']:.1f}% < {args.min_static:g}%: сравнение с базой ничего не доказывает")
|
||||
if base["new_animated_pct"] > args.max_new_animated:
|
||||
reasons.append(f"новых движущихся пикселей против базы {base['new_animated_pct']:.2f}% > {args.max_new_animated:g}%")
|
||||
if base["mean"] > args.max_mean:
|
||||
reasons.append(f"разница с базой (статика) {base['mean']:.2f} > {args.max_mean:g}")
|
||||
if base["pct"] > args.max_pct:
|
||||
@@ -522,6 +547,8 @@ def write_report(out, entries, args, env_extra, size, baseline, meta):
|
||||
fl = f"{e['flicker']['pct']:.2f}" if e.get("flicker") else "-"
|
||||
mv = f"{e['flicker']['animated_pct']:.2f}" if e.get("flicker") else "-"
|
||||
b = e.get("vs_baseline") or {}
|
||||
if "new_animated_pct" in b: # what the baseline comparison covers and what grew
|
||||
mv += f" (проверено {b['static_pct']:.0f}%, новых {b['new_animated_pct']:.2f}%)"
|
||||
bm = f"{b['mean']:.2f}" if "mean" in b else "-"
|
||||
bp = f"{b['pct']:.2f}" if "pct" in b else "-"
|
||||
status = "OK" if not e["fail"] else "FAIL: " + "; ".join(e["fail"])
|
||||
@@ -584,6 +611,9 @@ def parse_args(argv):
|
||||
p.add_argument("--max-mean", type=float, default=3.0, help="порог средней разницы статичных пикселей с базой, 0..255")
|
||||
p.add_argument("--max-pct", type=float, default=5.0, help="порог статичных пикселей >20/255 с базой, %%")
|
||||
p.add_argument("--max-flicker", type=float, default=None, help="порог мерцания статичных пикселей, %%; без него мерцание только в отчёте (порог пока не откалиброван двумя одинаковыми прогонами)")
|
||||
p.add_argument("--max-animated", type=float, default=60.0, help="порог доли кадра, которую прогон не проверяет (размах выше --motion-level), %%; не откалиброван")
|
||||
p.add_argument("--max-new-animated", type=float, default=2.0, help="порог пикселей, статичных в базе и движущихся в прогоне, %%; не откалиброван")
|
||||
p.add_argument("--min-static", type=float, default=10.0, help="наименьшая доля проверяемых (статичных в базе) пикселей, %%")
|
||||
p.add_argument("--no-freeze", action="store_true",
|
||||
help="не замораживать игровое время и погоду (живой замер производительности, не снимки)")
|
||||
p.add_argument("--no-pass-timing", action="store_true", help="не включать HORIZON_SHADER_PACK_TIMING")
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
"""Tests of tools/hd_bench.py's comparison (#82): `python3 -m unittest tools/test_hd_bench.py`."""
|
||||
import argparse
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import hd_bench as hb # noqa: E402
|
||||
|
||||
|
||||
def frame(w, h, v):
|
||||
return bytes([v]) * (3 * w * h)
|
||||
|
||||
|
||||
def args(**kw):
|
||||
a = argparse.Namespace(budget_ms=18.0, max_flicker=1.0, max_animated=60.0, max_mean=3.0,
|
||||
max_pct=5.0, max_new_animated=2.0, min_static=10.0, motion_level=hb.MOTION_LEVEL)
|
||||
a.__dict__.update(kw)
|
||||
return a
|
||||
|
||||
|
||||
def judged(rgbs, base_rgbs, w=2, h=2):
|
||||
rng = hb.motion_range(rgbs)
|
||||
brng = hb.motion_range(base_rgbs)
|
||||
entry = {"gpu_avg_ms": 1.0}
|
||||
entry["flicker"] = hb.flicker_stats(rng, w, h, len(rgbs), hb.MOTION_LEVEL, hb.FLICKER_LEVEL)
|
||||
entry["vs_baseline"] = hb.compare_runs(rgbs, rng, base_rgbs, brng, w, h, hb.MOTION_LEVEL)
|
||||
return entry, hb.judge(entry, args())
|
||||
|
||||
|
||||
class FlickerIsNotAnimation(unittest.TestCase):
|
||||
def test_the_issues_black_white_strobe_fails(self):
|
||||
# The issue: a 2x2 frame, the baseline steadily black, the run alternating black and white.
|
||||
entry, reasons = judged([frame(2, 2, 0), frame(2, 2, 255)] * 2, [frame(2, 2, 0)] * 3)
|
||||
self.assertEqual(entry["flicker"]["pct"], 0.0) # the old blind spot is still in these two numbers ...
|
||||
self.assertEqual(entry["flicker"]["animated_pct"], 100.0)
|
||||
self.assertEqual(entry["flicker"]["unsteady_pct"], 100.0)
|
||||
self.assertEqual(entry["vs_baseline"]["new_animated_pct"], 100.0)
|
||||
self.assertTrue(reasons, "... but the verdict is a failure")
|
||||
|
||||
def test_stronger_flicker_never_starts_passing(self):
|
||||
w = h = 4
|
||||
base = [frame(w, h, 100)] * 3
|
||||
failed = []
|
||||
unsteady = []
|
||||
for amp in (8, 16, 32, 255):
|
||||
lo, hi = 100 - min(amp // 2, 100), min(255, 100 + (amp + 1) // 2)
|
||||
run = [frame(w, h, lo), frame(w, h, hi), frame(w, h, lo)]
|
||||
entry, reasons = judged(run, base, w, h)
|
||||
failed.append(bool(reasons))
|
||||
unsteady.append(entry["flicker"]["unsteady_pct"])
|
||||
self.assertEqual(failed, [True] * 4, failed)
|
||||
self.assertEqual(unsteady, sorted(unsteady))
|
||||
|
||||
def test_a_fully_dynamic_frame_is_not_a_zero_error(self):
|
||||
w = h = 2
|
||||
moving = [frame(w, h, 0), frame(w, h, 255)]
|
||||
entry, reasons = judged(moving, moving)
|
||||
self.assertEqual(entry["vs_baseline"]["static_pct"], 0.0)
|
||||
self.assertTrue(any("проверяемых" in r for r in reasons), reasons)
|
||||
|
||||
def test_water_and_foliage_that_also_move_in_the_baseline_pass(self):
|
||||
w, h = 10, 10
|
||||
n = w * h
|
||||
def mixed(a, b): # the left 20% animates (water), the rest is still
|
||||
f = bytearray(frame(w, h, 90))
|
||||
for px in range(n // 5):
|
||||
f[3 * px:3 * px + 3] = bytes([a]) * 3
|
||||
return bytes(f)
|
||||
run = [mixed(40, 40), mixed(120, 40), mixed(60, 40)]
|
||||
base = [mixed(30, 40), mixed(130, 40), mixed(70, 40)]
|
||||
entry, reasons = judged(run, base, w, h)
|
||||
self.assertEqual(entry["vs_baseline"]["new_animated_pct"], 0.0)
|
||||
self.assertEqual(reasons, [])
|
||||
|
||||
def test_the_mask_comes_from_the_baseline_not_from_the_run(self):
|
||||
# Growth of the animated area against the baseline is counted and bounded.
|
||||
w = h = 10
|
||||
base = [frame(w, h, 90)] * 3
|
||||
f = bytearray(frame(w, h, 90))
|
||||
f[0:30] = bytes([250]) * 30 # 10% of the pixels
|
||||
run = [bytes(f), frame(w, h, 90), bytes(f)]
|
||||
entry, reasons = judged(run, base, w, h)
|
||||
self.assertAlmostEqual(entry["vs_baseline"]["new_animated_pct"], 10.0)
|
||||
self.assertTrue(reasons)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user