gen_models --check: compare PNGs by their pixels, not their bytes (#92)
build / mod (push) Successful in 22m10s
build / mod (push) Successful in 22m10s
With Pillow installable again, build.yml failed one step later: on the Linux runner 171 generated PNGs (every item icon) differed from the committed files. Their pixels are identical (sha256 of the decoded rasters matches the macOS ones byte for byte); only the deflate stream differs, because the zlib inside the Pillow wheel is built per platform and Python version. The manifest's byte hashes are not portable, so the check could only pass where the assets had been generated. --check now treats a PNG whose bytes differ as unchanged when it decodes to the same mode, size and pixels, and only while the file still matches its manifest row: a hand-edited file stays a conflict. Writing (a run without --check) and the manifest stay byte-exact. Verified: a copy of airdef-mod with all 175 manifest PNGs re-encoded (stored blocks) and the manifest rows updated passes --check; the real tree still reports no differences; tools/test_gen_assets.py OK (12 tests, two new: a re-encoded icon is accepted and then rewritten by a real run, another picture and a hand-edited icon are still reported).
This commit is contained in:
+1
-1
@@ -36,7 +36,7 @@
|
||||
- `python3 -m pip install -r tools/requirements.txt` — зависимости генератора (закреплён Pillow).
|
||||
- `python3 tools/gen_catalog.py` — обновить Rust-константы после изменений `catalog/content.json`, `catalog/specs.json` или `catalog/sounds.json`; `--check` проверяет актуальность.
|
||||
- `python3 tools/gen_models.py` — перегенерировать.
|
||||
- `python3 tools/gen_models.py --check` — только сравнить, выход 1 при различиях.
|
||||
- `python3 tools/gen_models.py --check` — только сравнить, выход 1 при различиях. PNG сверяются по пикселям: байты файла зависят от zlib в сборке Pillow, и Linux (CI) или Windows сжимают те же пиксели иначе, чем macOS. Правленными вручную считаются только файлы, чьи байты разошлись со своей строкой manifest. Сама запись (`gen_models.py` без `--check`) и manifest остаются побайтовыми.
|
||||
|
||||
`catalog/specs.json` — единственный источник числовых профилей симуляции: строки `DroneSpec`, `MissileSpec`/`MissileKind` (включая RCS, seeker, звук пуска и голос мотора), `SamSpec` (оружие, части моделей, приводы, датчик), общие константы (гравитация, высота раскрытия «Орешника», логистика) и именованные наборы частей. `tools/gen_catalog.py` создаёт из него `airdef-mod/src/sim/specs_generated.rs` (включается в `mod.rs`; тот же файл компилирует `airdef-core`) и `airdef-mod/src/sim/unit_specs_generated.rs` (включается в `units.rs`). Эти два файла не редактировать вручную. `tools/airdef_assets/catalog.py::load_specs` проверяет схему, звуковые ссылки, наборы kinds против `content.json`, ссылки на именованные части и заполненность всех строк; `gen_catalog.py --check` в CI ловит расхождение. Значения — игровой масштаб, не реальные характеристики техники.
|
||||
|
||||
|
||||
@@ -12,6 +12,8 @@
|
||||
с sha256 лежит в airdef-mod/generated-manifest.txt (формат sha256sum). Удаляются и перезаписываются только файлы
|
||||
из этого списка и только если их не правили вручную; чужой файл на пути генерируемого останавливает запуск.
|
||||
--check ничего не пишет и выходит с кодом 1, если airdef-mod/ отличается от того, что дал бы запуск.
|
||||
PNG при этом сравниваются по пикселям: байты файла зависят от zlib в сборке Pillow, и Linux или Windows
|
||||
сжимают те же пиксели иначе, чем macOS. Запись и manifest остаются побайтовыми.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
@@ -1202,6 +1204,15 @@ def prune_empty(root, path):
|
||||
d = os.path.dirname(d)
|
||||
|
||||
|
||||
def same_picture(committed, staged):
|
||||
"""True, если два PNG декодируются в тот же режим, размер и пиксели."""
|
||||
try:
|
||||
with Image.open(committed) as a, Image.open(staged) as b:
|
||||
return a.mode == b.mode and a.size == b.size and a.tobytes() == b.tobytes()
|
||||
except (OSError, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
def regenerate(root=ROOT, source_root=None, manifest=None, *, check=False, report=False):
|
||||
"""Build, validate, plan and install one complete generated runtime tree."""
|
||||
root = os.path.abspath(root)
|
||||
@@ -1225,6 +1236,16 @@ def regenerate(root=ROOT, source_root=None, manifest=None, *, check=False, repor
|
||||
for name in sorted(names):
|
||||
path = os.path.join(dirpath, name)
|
||||
new[os.path.relpath(path, stage).replace(os.sep, "/")] = pipeline.sha256(path)
|
||||
if check:
|
||||
# Байты PNG непереносимы между платформами (zlib в сборке Pillow). Проверка спрашивает, показывает ли
|
||||
# airdef-mod/ ту же картинку, что рисует генератор, поэтому PNG с теми же пикселями считается
|
||||
# неизменённым — но только пока файл побайтово совпадает с manifest: правленный вручную остаётся конфликтом.
|
||||
for rel, digest in new.items():
|
||||
target = os.path.join(root, rel)
|
||||
if (rel.endswith(".png") and old.get(rel) not in (None, digest) and os.path.isfile(target)
|
||||
and pipeline.sha256(target) == old[rel]
|
||||
and same_picture(target, os.path.join(stage, rel))):
|
||||
new[rel] = old[rel]
|
||||
plan = pipeline.make_plan(root, old, new)
|
||||
create, update, same = plan.create, plan.update, plan.same
|
||||
conflict, remove, keep = plan.conflict, plan.remove, plan.keep
|
||||
|
||||
@@ -189,5 +189,60 @@ class ReproducibilityTests(unittest.TestCase):
|
||||
self.assertEqual(outputs[0], outputs[1])
|
||||
|
||||
|
||||
class PortableCheckTests(unittest.TestCase):
|
||||
"""`--check` goes by the picture: another platform's Pillow compresses the same pixels into other bytes."""
|
||||
|
||||
ICON = "assets/airdef/textures/item/deploy_gepard.png"
|
||||
|
||||
def installed(self, root):
|
||||
source, manifest = root / "source-assets", root / "generated-manifest.txt"
|
||||
gen_models.regenerate(root, source, manifest)
|
||||
return source, manifest
|
||||
|
||||
def rewrite_with_manifest(self, root, manifest, rel, image):
|
||||
image.save(root / rel, compress_level=0)
|
||||
entries = pipeline.read_manifest(manifest)
|
||||
entries[rel] = pipeline.sha256(root / rel)
|
||||
manifest.write_text(pipeline.manifest_text(entries), encoding="utf-8")
|
||||
|
||||
def test_check_accepts_a_png_that_differs_from_the_generator_only_in_its_bytes(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp) / "mod"
|
||||
root.mkdir()
|
||||
source, manifest = self.installed(root)
|
||||
icon = root / self.ICON
|
||||
generated = icon.read_bytes()
|
||||
picture = Image.open(icon)
|
||||
picture.load()
|
||||
self.rewrite_with_manifest(root, manifest, self.ICON, picture)
|
||||
reencoded = icon.read_bytes()
|
||||
self.assertNotEqual(reencoded, generated) # stored blocks instead of this Pillow's deflate
|
||||
|
||||
self.assertFalse(gen_models.regenerate(root, source, manifest, check=True, report=True))
|
||||
self.assertEqual(icon.read_bytes(), reencoded)
|
||||
# Writing is still byte-exact: a real run installs this platform's encoding.
|
||||
self.assertTrue(gen_models.regenerate(root, source, manifest))
|
||||
self.assertEqual(icon.read_bytes(), generated)
|
||||
self.assertFalse(gen_models.regenerate(root, source, manifest, check=True))
|
||||
|
||||
def test_check_still_reports_another_picture_and_a_hand_edited_png(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp) / "mod"
|
||||
root.mkdir()
|
||||
source, manifest = self.installed(root)
|
||||
icon = root / self.ICON
|
||||
self.rewrite_with_manifest(root, manifest, self.ICON, Image.new("RGBA", (16, 16), (200, 10, 10, 255)))
|
||||
self.assertTrue(gen_models.regenerate(root, source, manifest, check=True, report=True))
|
||||
|
||||
picture = Image.open(icon)
|
||||
picture.load()
|
||||
self.rewrite_with_manifest(root, manifest, self.ICON, picture)
|
||||
entries = pipeline.read_manifest(manifest)
|
||||
entries[self.ICON] = "0" * 64 # the file no longer matches its manifest row: a hand edit
|
||||
manifest.write_text(pipeline.manifest_text(entries), encoding="utf-8")
|
||||
with self.assertRaisesRegex(RuntimeError, "КОНФЛИКТ"):
|
||||
gen_models.regenerate(root, source, manifest, check=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
Reference in New Issue
Block a user