File size: 8,262 Bytes
95ce89e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 | #!/usr/bin/env python3
"""Unify and recompress event picture DDS files to DXT5 + 10 mip chain.
Reads every .dds under `gfx/event_pictures/`, normalizes to 512x256 with
a 10-level mip chain, and re-encodes as DXT5 (BC3). Alpha channel is
preserved for every file (DXT5 is lossless on alpha within the codec's
quantization, but at 512x256 the visual delta from full BGRA is below
perception for the kinds of content in this mod).
Existing files that already match the target (BC3 + 512x256 + 10 mips)
are skipped to avoid needless re-encoding.
Usage:
python convert_eventpicture_dds.py # process all under gfx/event_pictures/
python convert_eventpicture_dds.py <dir> # process all .dds under <dir>
python convert_eventpicture_dds.py <dir> --dry-run # report only, do not write
python convert_eventpicture_dds.py <dir> -j 8 # 8 worker threads (default 4)
Requires tools/bin/texconv.exe next to this script.
"""
import argparse
import collections
import concurrent.futures
import glob
import os
import struct
import subprocess
import sys
import tempfile
import threading
import time
from PIL import Image
HERE = os.path.dirname(os.path.abspath(__file__))
TEXCONV = os.path.join(HERE, "bin", "texconv.exe")
TARGET_W, TARGET_H = 512, 256
TARGET_MIPS = 10
TARGET_FOURCC = b"DXT5"
def read_dds_header(path: str) -> dict | None:
with open(path, "rb") as f:
data = f.read(128)
if len(data) < 128 or data[:4] != b"DDS ":
return None
h, w, _, _, mipmap_count = struct.unpack("<IIIII", data[12:32])
_, _, fourcc, _, *_ = struct.unpack("<II4s5I", data[76:108])
return dict(w=w, h=h, mips=mipmap_count, fourcc=fourcc)
def is_target_format(hdr: dict) -> bool:
return (
hdr["w"] == TARGET_W
and hdr["h"] == TARGET_H
and hdr["mips"] == TARGET_MIPS
and hdr["fourcc"] == TARGET_FOURCC
)
def decode_to_png(src_dds: str, tmpdir: str) -> str:
"""texconv decodes any DDS variant to a PNG inside tmpdir."""
cmd = [TEXCONV, "-ft", "png", "-y", "-o", tmpdir, src_dds]
r = subprocess.run(cmd, capture_output=True, text=True)
if r.returncode != 0:
raise RuntimeError(
f"texconv decode failed for {src_dds}\nstdout: {r.stdout}\nstderr: {r.stderr}"
)
base = os.path.splitext(os.path.basename(src_dds))[0]
produced = os.path.join(tmpdir, base + ".png")
if not os.path.isfile(produced):
raise RuntimeError(f"texconv produced no PNG for {src_dds}")
return produced
def encode_dds(png_path: str, tmpdir: str) -> str:
"""texconv encodes a PNG as DXT5 with full mip chain."""
cmd = [
TEXCONV,
"-f", "DXT5",
"-m", "0", # full mip chain
"-ft", "dds",
"-y",
"-o", tmpdir,
png_path,
]
r = subprocess.run(cmd, capture_output=True, text=True)
if r.returncode != 0:
raise RuntimeError(
f"texconv encode failed for {png_path}\nstdout: {r.stdout}\nstderr: {r.stderr}"
)
base = os.path.splitext(os.path.basename(png_path))[0]
produced = os.path.join(tmpdir, base + ".dds")
if not os.path.isfile(produced):
raise RuntimeError(f"texconv produced no DDS for {png_path}")
return produced
def prepare_png(src_png: str, tmpdir: str) -> str:
"""Center-crop to 2:1, resize to 512x256, return staged PNG path."""
im = Image.open(src_png)
if im.mode not in ("RGB", "RGBA"):
im = im.convert("RGB")
sw, sh = im.size
target_ar = TARGET_W / TARGET_H # 2.0
src_ar = sw / sh if sh else 1.0
if abs(src_ar - target_ar) > 0.01:
if src_ar > target_ar:
new_w = round(sh * target_ar)
x0 = (sw - new_w) // 2
im = im.crop((x0, 0, x0 + new_w, sh))
else:
new_h = round(sw / target_ar)
y0 = (sh - new_h) // 2
im = im.crop((0, y0, sw, y0 + new_h))
im = im.resize((TARGET_W, TARGET_H), Image.LANCZOS)
staged = os.path.join(tmpdir, "stage.png")
im.save(staged, format="PNG")
return staged
_print_lock = threading.Lock()
def _log(msg: str) -> None:
with _print_lock:
print(msg, file=sys.stderr, flush=True)
def process_one(src_dds: str, dry_run: bool) -> tuple[str, str]:
"""Return (status, reason). status is one of: skip / wrote / error."""
hdr = read_dds_header(src_dds)
if hdr is None:
return ("error", "not a DDS")
if is_target_format(hdr):
return ("skip", f"already {TARGET_FOURCC.decode()}+{TARGET_W}x{TARGET_H}+{TARGET_MIPS}mip")
if dry_run:
return (
"would-write",
f"{hdr['w']}x{hdr['h']} mip={hdr['mips']} -> DXT5+10mip",
)
# Each file gets its own ASCII temp dir to keep texconv happy with
# unicode source paths.
with tempfile.TemporaryDirectory() as tmp:
try:
decoded = decode_to_png(src_dds, tmp)
except Exception as e:
return ("error", f"decode: {e}")
try:
staged = prepare_png(decoded, tmp)
except Exception as e:
return ("error", f"prepare: {e}")
try:
new_dds = encode_dds(staged, tmp)
except Exception as e:
return ("error", f"encode: {e}")
os.replace(new_dds, src_dds)
return ("wrote", "ok")
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0])
ap.add_argument(
"root",
nargs="?",
default=os.path.normpath(
os.path.join(HERE, "..", "gfx", "event_pictures")
),
help="Directory to scan for .dds (default: gfx/event_pictures).",
)
ap.add_argument(
"--dry-run",
action="store_true",
help="Report what would happen without writing anything.",
)
ap.add_argument(
"-j",
"--jobs",
type=int,
default=4,
help="Number of worker threads (default: 4).",
)
args = ap.parse_args()
if not os.path.isfile(TEXCONV):
print(f"error: texconv not found at {TEXCONV}", file=sys.stderr)
return 1
if not os.path.isdir(args.root):
print(f"error: directory not found: {args.root}", file=sys.stderr)
return 1
paths = sorted(glob.glob(os.path.join(args.root, "**", "*.dds"), recursive=True))
print(f"scanning: {args.root}")
print(f"found: {len(paths)} dds files")
print(f"target: DXT5 (BC3) {TARGET_W}x{TARGET_H} + {TARGET_MIPS}-level mip chain")
print(f"workers: {args.jobs}")
if args.dry_run:
print("(dry run; no files will be written)")
counts: collections.Counter = collections.Counter()
error_samples: list[tuple[str, str]] = []
started = time.time()
def work(p: str) -> tuple[str, str, str]:
status, reason = process_one(p, args.dry_run)
return (p, status, reason)
completed = 0
with concurrent.futures.ThreadPoolExecutor(max_workers=args.jobs) as ex:
futures = {ex.submit(work, p): p for p in paths}
for fut in concurrent.futures.as_completed(futures):
p, status, reason = fut.result()
counts[status] += 1
completed += 1
if status == "error":
_log(f" ERROR {p}: {reason}")
if len(error_samples) < 5:
error_samples.append((p, reason))
if completed % 100 == 0 or completed == len(paths):
elapsed = time.time() - started
rate = completed / elapsed if elapsed else 0
eta = (len(paths) - completed) / rate if rate else 0
_log(
f" ... {completed}/{len(paths)} "
f"({rate:.1f}/s, eta {eta/60:.1f} min)"
)
elapsed = time.time() - started
print()
print("=== summary ===")
for k in ("skip", "would-write", "wrote", "error"):
print(f" {k}: {counts[k]}")
print(f" elapsed: {elapsed/60:.1f} min")
if error_samples:
print()
print("=== first errors ===")
for p, reason in error_samples:
print(f" {p}: {reason}")
return 0 if counts["error"] == 0 else 2
if __name__ == "__main__":
raise SystemExit(main())
|