Les bandes de PANEL1/PANEL2 sont séparées par des lignes unies vertes que le jeu n'affiche jamais ; l'agrandissement les faisait baver sur la dernière ligne de la barre. Elles sont remplacées par la ligne voisine avant export. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
499 lines
22 KiB
Python
499 lines
22 KiB
Python
r"""Exporte les images du jeu en PNG, point de départ d'un pack HD.
|
||
|
||
Les images viennent des fichiers du joueur et restent sur sa machine : rien n'est redistribué.
|
||
On les agrandit ensuite avec l'outil de son choix (dessin à la main, Real-ESRGAN, waifu2x, xBRZ…)
|
||
puis on les dépose dans mods/<nom_du_mod>/hd/ sous le même nom et le même dossier. Voir docs/MODS.md.
|
||
|
||
python tools/hd_export.py DOSSIER_DU_JEU DOSSIER_SORTIE [--motif MOTIF[,MOTIF…]] [--echelle 1|2|4]
|
||
[--sprites [MOTIF]] [--planches [MOTIF]] [--sans-decors]
|
||
[--upscayl [MODELE]] [--upscayl-bin CHEMIN] [--reparer]
|
||
|
||
--motif images plein écran à exporter, liste séparée par des virgules -> SORTIE/LOC01.png
|
||
(défaut : LOC*, les décors des pièces, et les images fixes des cinématiques : CLIO1, MAP1,
|
||
NEWS1, PT1BAK…, voir CINEMATIQUES, et la barre d'actions PANEL1, PANEL2)
|
||
--sprites fichiers SPRITES\*.SPR à exporter (défaut : tous) -> SORTIE/SPRITES/<NOM>.png, une planche
|
||
par fichier (puis <NOM>_P1.png… si elle déborde), images rangées comme le jeu les cherche
|
||
--planches planches de sprites PCX (Bud, objets, curseur…) -> SORTIE/SHEETS/<NOM>.png
|
||
(défaut : BUD_*,BUDL00_*,PEG_*,MAC_*,SCROBJ*,PANOBJS*,POINTER,CHARSET*,CHAR2,CLIO*,COGS*)
|
||
--sans-decors n'exporte pas les décors (seulement sprites et planches)
|
||
--echelle 1 = taille d'origine (à agrandir soi-même) ; 2 ou 4 = agrandissement Scale2x
|
||
intégré (contours en escalier adoucis, sans flou), pour tester un pack tout de suite
|
||
--upscayl agrandit ×4 avec Upscayl (Real-ESRGAN) s'il est installé ; modèle par défaut
|
||
digital-art-4x (autres : ultrasharp-4x, remacri-4x, high-fidelity-4x, upscayl-standard-4x…)
|
||
--upscayl-bin chemin de upscayl-bin.exe s'il n'est pas trouvé tout seul
|
||
--reparer refait seulement les images vides (entièrement transparentes) d'un pack existant :
|
||
Upscayl en rend parfois sans signaler d'erreur ; elles sont désormais détectées et
|
||
reprises avec des tuiles plus petites, sinon retirées (le jeu garde alors l'original)
|
||
|
||
Exemples :
|
||
python tools/hd_export.py ..\extracted\iso\TUCKER mods\hd_upscayl\hd --upscayl
|
||
python tools/hd_export.py ..\extracted\iso\TUCKER mods\hd_upscayl\hd --sans-decors --sprites A01_* --planches --upscayl
|
||
python tools/hd_export.py ..\extracted\iso\TUCKER mods\hd_upscayl\hd --reparer --upscayl
|
||
|
||
Décors : seules les images plein écran 320×200 servent, les autres sont ignorées. Sprites et planches sont
|
||
transparents (indice 0) ; la couleur des pixels transparents est prolongée depuis les bords pour éviter un
|
||
liseré sombre une fois agrandis. Toutes les images de sprites (55 millions de pixels) prennent du temps à
|
||
agrandir : commencer par une pièce (--sprites A01_*). Sprites et planches demandent numpy.
|
||
"""
|
||
import argparse
|
||
import fnmatch
|
||
import os
|
||
import re
|
||
import shutil
|
||
import struct
|
||
import subprocess
|
||
import sys
|
||
import tempfile
|
||
import time
|
||
import zlib
|
||
|
||
# mise en page des planches SPR : doit rester identique à make_layout() de runtime/sprites.c
|
||
SPR_PAGE_W = 1024
|
||
SPR_PAGE_H = 1024
|
||
SPR_PAD = 8
|
||
UPSCAYL_TUILES = (128, 64) # taille des tuiles Upscayl, puis reprise plus petite
|
||
UPSCAYL_PAUSE = 0.3 # secondes rendues à l'affichage entre deux calculs
|
||
UPSCAYL_ARRET = 3 # images ratées d'affilée avant d'arrêter
|
||
SHEETS = "BUD_*,BUDL00_*,PEG_*,MAC_*,SCROBJ*,PANOBJS*,POINTER,CHARSET*,CHAR2,CLIO*,COGS*"
|
||
|
||
|
||
def read_pcx(path):
|
||
"""PCX 8 bits 1 plan compressé RLE → (largeur, hauteur, indices, palette 768 octets)."""
|
||
d = open(path, "rb").read()
|
||
if len(d) < 128 + 769 or d[0] != 10 or d[3] != 8 or d[65] != 1:
|
||
raise ValueError("PCX 8 bits attendu : %s" % path)
|
||
x0, y0, x1, y1 = struct.unpack("<4H", d[4:12])
|
||
w, h = x1 - x0 + 1, y1 - y0 + 1
|
||
bpl = struct.unpack("<H", d[66:68])[0]
|
||
out, i, need = bytearray(), 128, bpl * h
|
||
while len(out) < need and i < len(d) - 769:
|
||
b = d[i]
|
||
i += 1
|
||
if b >= 0xC0:
|
||
out += bytes([d[i]]) * (b & 0x3F)
|
||
i += 1
|
||
else:
|
||
out.append(b)
|
||
out = out[:need].ljust(need, b"\0")
|
||
pix = b"".join(bytes(out[y * bpl:y * bpl + w]) for y in range(h))
|
||
if d[-769] != 12:
|
||
raise ValueError("palette absente : %s" % path)
|
||
return w, h, pix, d[-768:]
|
||
|
||
|
||
def read_spr(path):
|
||
"""Fichier SPR → [(largeur, hauteur, indices)] ; image : en-tête de 12 octets (u16 largeur, hauteur, …)
|
||
puis RLE : octet non nul = pixel, 00 n = n pixels transparents (lecture de la routine du jeu)."""
|
||
d = open(path, "rb").read()
|
||
n = struct.unpack_from("<I", d, 0)[0]
|
||
if n == 0 or 4 + 4 * n > len(d):
|
||
raise ValueError("SPR invalide : %s" % path)
|
||
out = []
|
||
for k in range(n):
|
||
o = struct.unpack_from("<I", d, 4 + 4 * k)[0]
|
||
w, h = struct.unpack_from("<2H", d, o)
|
||
total, i, px = w * h, o + 12, bytearray()
|
||
while len(px) < total and i < len(d):
|
||
b = d[i]
|
||
i += 1
|
||
if b:
|
||
px.append(b)
|
||
else:
|
||
run = d[i] if i < len(d) else 0
|
||
i += 1
|
||
px += bytes(min(run, total - len(px)))
|
||
out.append((w, h, bytes(px.ljust(total, b"\0"))))
|
||
return out
|
||
|
||
|
||
def layout(sizes):
|
||
"""Images (largeur, hauteur) → [(page, x, y)], [(largeur, hauteur) par page]. Comme make_layout()."""
|
||
total_w = SPR_PAD + sum(w + SPR_PAD for w, _ in sizes)
|
||
pw = min(total_w, SPR_PAGE_W)
|
||
page, x, y, rowh, lay, pages = 0, SPR_PAD, SPR_PAD, 0, [], []
|
||
for w, h in sizes:
|
||
if x + w + SPR_PAD > pw and x > SPR_PAD:
|
||
x, y, rowh = SPR_PAD, y + rowh + SPR_PAD, 0
|
||
if y + h + SPR_PAD > SPR_PAGE_H and y > SPR_PAD:
|
||
pages.append((pw, y + rowh + SPR_PAD))
|
||
page, x, y, rowh = page + 1, SPR_PAD, SPR_PAD, 0
|
||
lay.append((page, x, y))
|
||
x += w + SPR_PAD
|
||
rowh = max(rowh, h)
|
||
pages.append((pw, y + rowh + SPR_PAD))
|
||
return lay, pages
|
||
|
||
|
||
def find_file(folder, name):
|
||
"""Nom de fichier du jeu, casse indifférente ; None si absent."""
|
||
want = name.upper()
|
||
for f in os.listdir(folder):
|
||
if f.upper() == want:
|
||
return os.path.join(folder, f)
|
||
return None
|
||
|
||
|
||
_pals = {}
|
||
|
||
|
||
def pcx_palette(game, name):
|
||
if name not in _pals:
|
||
p = find_file(game, name + ".PCX")
|
||
_pals[name] = read_pcx(p)[3] if p else None
|
||
return _pals[name]
|
||
|
||
|
||
def palette_for(game, name):
|
||
"""Palette d'un fichier SPR : décor de la pièce indiquée par le nom (A01_02 -> LOC01, LOC03A si LOC03
|
||
n'existe pas), PARTONE/PARTTWO/PARTTHR -> PT1BAK/PT2BAK/PT3BAK, sinon LOC01. Comme spr_palette() de
|
||
runtime/sprites.c, qui compare les couleurs affichées à celles-ci (fondus)."""
|
||
special = {"PARTONE": "PT1BAK", "PARTTWO": "PT2BAK", "PARTTHR": "PT3BAK"}
|
||
if name in special:
|
||
return pcx_palette(game, special[name])
|
||
m = re.search(r"\d", name)
|
||
if not m or not name[m.start():m.start() + 2].isdigit():
|
||
return pcx_palette(game, "LOC01")
|
||
room = "LOC" + name[m.start():m.start() + 2]
|
||
return pcx_palette(game, room) or pcx_palette(game, room + "A")
|
||
|
||
|
||
def scale2x(w, h, px):
|
||
"""Scale2x (EPX) sur une liste de couleurs : chaque pixel devient 2×2 selon ses voisins."""
|
||
out = [0] * (4 * w * h)
|
||
W = 2 * w
|
||
for y in range(h):
|
||
row, up, dn = y * w, max(y - 1, 0) * w, min(y + 1, h - 1) * w
|
||
for x in range(w):
|
||
p = px[row + x]
|
||
a = px[up + x]
|
||
b = px[row + min(x + 1, w - 1)]
|
||
c = px[row + max(x - 1, 0)]
|
||
d = px[dn + x]
|
||
e0 = e1 = e2 = e3 = p
|
||
if c == a and c != d and a != b: e0 = a
|
||
if a == b and a != c and b != d: e1 = b
|
||
if d == c and d != b and c != a: e2 = c
|
||
if b == d and b != a and d != c: e3 = d
|
||
o = 2 * y * W + 2 * x
|
||
out[o], out[o + 1], out[o + W], out[o + W + 1] = e0, e1, e2, e3
|
||
return 2 * w, 2 * h, out
|
||
|
||
|
||
def write_png(path, w, h, data, alpha=False):
|
||
"""data : RVB (3 octets par pixel) ou RVBA si alpha."""
|
||
raw = bytearray()
|
||
stride = (4 if alpha else 3) * w
|
||
for y in range(h):
|
||
raw.append(0)
|
||
raw += data[y * stride:(y + 1) * stride]
|
||
|
||
def chunk(tag, payload):
|
||
c = tag + payload
|
||
return struct.pack(">I", len(payload)) + c + struct.pack(">I", zlib.crc32(c) & 0xFFFFFFFF)
|
||
|
||
png = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 6 if alpha else 2, 0, 0, 0))
|
||
png += chunk(b"IDAT", zlib.compress(bytes(raw), 9)) + chunk(b"IEND", b"")
|
||
with open(path, "wb") as f:
|
||
f.write(png)
|
||
|
||
|
||
def rgba_image(np, idx, pal):
|
||
"""Indices (h, w) → RVBA, indice 0 transparent, couleur des pixels transparents prolongée depuis les
|
||
pixels opaques voisins (12 passes) pour qu'un agrandissement ne fasse pas de liseré sombre."""
|
||
p = np.frombuffer(pal, dtype=np.uint8).reshape(256, 3).astype(np.float32)
|
||
col = p[idx]
|
||
filled = idx != 0
|
||
for _ in range(12):
|
||
if filled.all():
|
||
break
|
||
acc = np.zeros_like(col)
|
||
cnt = np.zeros(idx.shape, dtype=np.float32)
|
||
f = filled.astype(np.float32)
|
||
for dy, dx in ((-1, 0), (1, 0), (0, -1), (0, 1), (-1, -1), (-1, 1), (1, -1), (1, 1)):
|
||
src = (slice(max(dy, 0), idx.shape[0] + min(dy, 0)), slice(max(dx, 0), idx.shape[1] + min(dx, 0)))
|
||
dst = (slice(max(-dy, 0), idx.shape[0] + min(-dy, 0)), slice(max(-dx, 0), idx.shape[1] + min(-dx, 0)))
|
||
acc[dst] += col[src] * f[src][..., None]
|
||
cnt[dst] += f[src]
|
||
new = (~filled) & (cnt > 0)
|
||
col[new] = acc[new] / cnt[new][..., None]
|
||
filled = filled | new
|
||
out = np.zeros(idx.shape + (4,), dtype=np.uint8)
|
||
out[..., :3] = np.clip(col + 0.5, 0, 255).astype(np.uint8)
|
||
out[..., 3] = np.where(idx != 0, 255, 0)
|
||
return out
|
||
|
||
|
||
def upscale_indices(np, idx, scale):
|
||
if scale == 1:
|
||
return idx
|
||
h, w = idx.shape
|
||
px = idx.reshape(-1).tolist()
|
||
s = 1
|
||
while s < scale:
|
||
w, h, px = scale2x(w, h, px)
|
||
s *= 2
|
||
return np.array(px, dtype=np.uint8).reshape(h, w)
|
||
|
||
|
||
def export_sprites(np, game, out, motif, scale):
|
||
folder = find_file(game, "SPRITES")
|
||
if not folder:
|
||
sys.exit("dossier SPRITES introuvable dans %s" % game)
|
||
pats = [m.strip().upper() for m in motif.split(",")]
|
||
names = sorted(f for f in os.listdir(folder) if f.upper().endswith(".SPR")
|
||
and any(fnmatch.fnmatch(f.upper()[:-4], p) or fnmatch.fnmatch(f.upper(), p) for p in pats))
|
||
os.makedirs(os.path.join(out, "SPRITES"), exist_ok=True)
|
||
n_img = 0
|
||
for f in names:
|
||
name = f.upper()[:-4]
|
||
frames = read_spr(os.path.join(folder, f))
|
||
pal = palette_for(game, name)
|
||
if pal is None:
|
||
print("%s : pas de palette, ignoré" % f)
|
||
continue
|
||
lay, pages = layout([(w, h) for w, h, _ in frames])
|
||
atlas = [np.zeros((ph, pw), dtype=np.uint8) for pw, ph in pages]
|
||
for (w, h, px), (pg, x, y) in zip(frames, lay):
|
||
if w and h:
|
||
atlas[pg][y:y + h, x:x + w] = np.frombuffer(px, dtype=np.uint8).reshape(h, w)
|
||
for pg, idx in enumerate(atlas):
|
||
img = rgba_image(np, upscale_indices(np, idx, scale), pal)
|
||
path = os.path.join(out, "SPRITES", name + ("_P%d" % pg if pg else "") + ".png")
|
||
write_png(path, img.shape[1], img.shape[0], img.tobytes(), alpha=True)
|
||
n_img += 1
|
||
print("%s : %d image(s), %d planche(s)" % (f, len(frames), len(pages)))
|
||
return n_img
|
||
|
||
|
||
def export_sheets(np, game, out, motif, scale):
|
||
pats = [m.strip().upper() for m in motif.split(",")]
|
||
names = sorted(f for f in os.listdir(game) if f.upper().endswith(".PCX")
|
||
and any(fnmatch.fnmatch(f.upper()[:-4], p) for p in pats))
|
||
os.makedirs(os.path.join(out, "SHEETS"), exist_ok=True)
|
||
for f in names:
|
||
w, h, pix, pal = read_pcx(os.path.join(game, f))
|
||
if (w, h) != (320, 200):
|
||
print("%s ignoré (%d×%d)" % (f, w, h))
|
||
continue
|
||
idx = upscale_indices(np, np.frombuffer(pix, dtype=np.uint8).reshape(h, w), scale)
|
||
img = rgba_image(np, idx, pal)
|
||
write_png(os.path.join(out, "SHEETS", f.upper()[:-4] + ".png"), img.shape[1], img.shape[0], img.tobytes(), alpha=True)
|
||
print("%s -> SHEETS" % f)
|
||
return len(names)
|
||
|
||
|
||
# Images fixes plein écran des cinématiques et des écrans de partie (« PART ONE… », journaux, cartes…).
|
||
# Écartés : PT03A… ROCHPATH, PLATFORM (masques et chemins, jamais affichés).
|
||
CINEMATIQUES = ("CLIO1,CLIO2,DICKDIGS,MAP1,MAP2,MEANW01,MEANW02,MEANW03,SOME01,SOME02,SOME03,NEWS1,NEWS2,"
|
||
"PAPER_3,PHOTO,MEMO,POSTIT,PROFNOTE,PARTSCR,PT1BAK,PT2BAK,PT3BAK,CONGRAT,CONGRATS")
|
||
# Barre d'actions et panneau d'options : verbes en texte (PANEL1) et en icônes (PANEL2), copiés par bandes sous le décor.
|
||
PANNEAUX = "PANEL1,PANEL2"
|
||
|
||
|
||
def export_backgrounds(game, out, motif, scale):
|
||
pats = [m.strip().upper() for m in motif.split(",") if m.strip()]
|
||
pats = [p if p.endswith(".PCX") else p + ".PCX" for p in pats]
|
||
names = sorted(n for n in os.listdir(game)
|
||
if n.upper().endswith(".PCX") and any(fnmatch.fnmatch(n.upper(), p) for p in pats))
|
||
if not names:
|
||
sys.exit("aucun PCX ne correspond à %s dans %s" % (motif, game))
|
||
for n in names:
|
||
w, h, pix, pal = read_pcx(os.path.join(game, n))
|
||
if (w, h) != (320, 200):
|
||
print("%s ignoré (%d×%d, pas un décor plein écran)" % (n, w, h))
|
||
continue
|
||
px = list(pix)
|
||
if os.path.splitext(n)[0].upper() in PANNEAUX.split(","):
|
||
# planches de la barre : bandes séparées par des lignes unies (vertes) que le jeu n'affiche jamais ;
|
||
# elles sont remplacées par la ligne voisine, sinon l'agrandissement les fait baver sur le bord des bandes
|
||
flat = [len(set(px[y * w:(y + 1) * w])) == 1 for y in range(h)]
|
||
for y in range(h):
|
||
if flat[y]:
|
||
src = next((v for v in range(y - 1, -1, -1) if not flat[v]),
|
||
next((v for v in range(y + 1, h) if not flat[v]), y))
|
||
px[y * w:(y + 1) * w] = px[src * w:(src + 1) * w]
|
||
s = 1
|
||
while s < scale:
|
||
w, h, px = scale2x(w, h, px)
|
||
s *= 2
|
||
rgb = bytearray(3 * w * h)
|
||
for i, c in enumerate(px):
|
||
rgb[3 * i:3 * i + 3] = pal[3 * c:3 * c + 3]
|
||
path = os.path.join(out, os.path.splitext(n)[0].upper() + ".png")
|
||
write_png(path, w, h, rgb)
|
||
print("%s -> %s (%d×%d)" % (n, path, w, h))
|
||
|
||
|
||
def find_upscayl(explicit):
|
||
"""upscayl-bin.exe : option, variable UPSCAYL_BIN, puis emplacements d'installation habituels."""
|
||
cands = [explicit, os.environ.get("UPSCAYL_BIN")]
|
||
for base in (os.environ.get("ProgramFiles"), os.environ.get("ProgramFiles(x86)"),
|
||
os.path.join(os.environ.get("LOCALAPPDATA", ""), "Programs")):
|
||
if base:
|
||
cands.append(os.path.join(base, "Upscayl", "resources", "bin", "upscayl-bin.exe"))
|
||
cands += ["/opt/Upscayl/resources/bin/upscayl-bin", "/Applications/Upscayl.app/Contents/Resources/bin/upscayl-bin",
|
||
shutil.which("upscayl-bin") or ""]
|
||
for c in cands:
|
||
if c and os.path.isfile(c):
|
||
return c
|
||
return None
|
||
|
||
|
||
class GpuArret(Exception):
|
||
"""Plusieurs images ratées d'affilée : le pilote graphique a probablement décroché."""
|
||
|
||
|
||
def run_upscayl(upscayl, models, model, src, dst):
|
||
"""Une image par appel, tuiles petites, pause entre deux images, priorité basse.
|
||
|
||
Upscayl (Vulkan) peut occuper la carte graphique au point que le pilote se réinitialise
|
||
(écrans noirs, voire PC à redémarrer) : de petites tuiles gardent chaque calcul court et la
|
||
mémoire vidéo basse, la pause rend la main à l'affichage, et l'export s'arrête dès que
|
||
plusieurs images de suite échouent au lieu de continuer à solliciter un pilote en difficulté.
|
||
"""
|
||
pngs = sorted(f for f in os.listdir(src) if f.lower().endswith(".png"))
|
||
if not pngs:
|
||
return 0
|
||
os.makedirs(dst, exist_ok=True)
|
||
print("Upscayl (%s) : %d image(s) %s -> %s" % (model, len(pngs), src, dst))
|
||
prio = getattr(subprocess, "BELOW_NORMAL_PRIORITY_CLASS", 0)
|
||
|
||
def run(f, tile):
|
||
o = os.path.join(dst, f)
|
||
r = subprocess.run([upscayl, "-i", os.path.join(src, f), "-o", o, "-m", models, "-n", model,
|
||
"-s", "4", "-f", "png", "-t", str(tile), "-j", "1:1:1"],
|
||
stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True, errors="replace",
|
||
creationflags=prio)
|
||
# Upscayl rend parfois une image entièrement transparente sans signaler d'erreur :
|
||
# elle compte comme ratée si l'image source ne l'est pas
|
||
ok = (r.returncode == 0 and os.path.exists(o)
|
||
and (not png_empty(o) or png_empty(os.path.join(src, f))))
|
||
return ok, r.stderr
|
||
|
||
ratees, suite = [], 0
|
||
for i, f in enumerate(pngs):
|
||
ok = False
|
||
for tile in UPSCAYL_TUILES:
|
||
ok, err = run(f, tile)
|
||
time.sleep(UPSCAYL_PAUSE)
|
||
if ok:
|
||
break
|
||
if ok:
|
||
suite = 0
|
||
else:
|
||
ratees.append(f)
|
||
suite += 1
|
||
try: # pas d'image vide dans le pack : le jeu garde l'original
|
||
os.remove(os.path.join(dst, f))
|
||
except OSError:
|
||
pass
|
||
if suite >= UPSCAYL_ARRET:
|
||
print("Upscayl : %d images ratées d'affilée, arrêt pour ne pas surcharger la carte graphique." % suite)
|
||
if err:
|
||
print(err[-600:])
|
||
raise GpuArret()
|
||
if (i + 1) % 25 == 0:
|
||
print(" %d/%d" % (i + 1, len(pngs)))
|
||
if ratees:
|
||
print("Upscayl a échoué pour %d image(s) (non copiées, le jeu garde l'original) : %s"
|
||
% (len(ratees), ", ".join(ratees[:20]) + (" …" if len(ratees) > 20 else "")))
|
||
return len(pngs) - len(ratees)
|
||
|
||
|
||
def png_empty(path):
|
||
"""Vrai si les données image d'un PNG sont toutes nulles (noir transparent), octets de filtre exceptés."""
|
||
try:
|
||
d = open(path, "rb").read()
|
||
i, idat, h = 8, [], 0
|
||
while i < len(d):
|
||
n, t = struct.unpack(">I4s", d[i:i + 8])
|
||
if t == b"IHDR":
|
||
h = struct.unpack(">I", d[i + 12:i + 16])[0]
|
||
elif t == b"IDAT":
|
||
idat.append(d[i + 8:i + 8 + n])
|
||
i += 12 + n
|
||
raw = zlib.decompress(b"".join(idat))
|
||
except (OSError, struct.error, zlib.error):
|
||
return False
|
||
st = len(raw) // h if h else 0
|
||
return st > 0 and not any(raw[y * st + 1:(y + 1) * st].strip(b"\0") for y in range(h))
|
||
|
||
|
||
def main():
|
||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||
ap.add_argument("jeu")
|
||
ap.add_argument("sortie")
|
||
ap.add_argument("--motif", default="LOC*," + CINEMATIQUES + "," + PANNEAUX)
|
||
ap.add_argument("--echelle", type=int, choices=(1, 2, 4), default=1)
|
||
ap.add_argument("--sprites", nargs="?", const="*", metavar="MOTIF")
|
||
ap.add_argument("--planches", nargs="?", const=SHEETS, metavar="MOTIF")
|
||
ap.add_argument("--sans-decors", action="store_true")
|
||
ap.add_argument("--upscayl", nargs="?", const="digital-art-4x", metavar="MODELE")
|
||
ap.add_argument("--upscayl-bin")
|
||
ap.add_argument("--reparer", action="store_true")
|
||
a = ap.parse_args()
|
||
try:
|
||
sys.stdout.reconfigure(errors="replace")
|
||
except AttributeError:
|
||
pass
|
||
if a.reparer: # seulement les images vides du pack existant
|
||
vides = {}
|
||
for sub in ("", "SPRITES", "SHEETS"):
|
||
d = os.path.join(a.sortie, sub)
|
||
if os.path.isdir(d):
|
||
vides[sub] = sorted(f[:-4].upper() for f in os.listdir(d)
|
||
if f.lower().endswith(".png") and png_empty(os.path.join(d, f)))
|
||
spr = sorted({re.sub(r"_P\d+$", "", n) for n in vides.get("SPRITES", [])})
|
||
a.sprites = ",".join(spr) or None
|
||
a.planches = ",".join(vides.get("SHEETS", [])) or None
|
||
a.motif = ",".join(vides.get("", []))
|
||
a.sans_decors = not a.motif
|
||
n = sum(len(v) for v in vides.values())
|
||
if not n:
|
||
print("Aucune image vide dans %s" % a.sortie)
|
||
return
|
||
print("%d image(s) vide(s) à refaire : %s" % (n, ", ".join(spr + vides.get("SHEETS", []) + vides.get("", []))[:400]))
|
||
np = None
|
||
if a.sprites or a.planches:
|
||
try:
|
||
import numpy as np
|
||
except ImportError:
|
||
sys.exit("--sprites et --planches demandent numpy (pip install numpy)")
|
||
upscayl = models = None
|
||
if a.upscayl:
|
||
upscayl = find_upscayl(a.upscayl_bin)
|
||
if not upscayl:
|
||
sys.exit("Upscayl introuvable : indiquez --upscayl-bin CHEMIN (upscayl-bin.exe)")
|
||
models = os.path.join(os.path.dirname(os.path.dirname(upscayl)), "models")
|
||
if not os.path.isfile(os.path.join(models, a.upscayl + ".param")):
|
||
dispo = sorted(f[:-6] for f in os.listdir(models) if f.endswith(".param")) if os.path.isdir(models) else []
|
||
sys.exit("modèle Upscayl inconnu : %s (disponibles : %s)" % (a.upscayl, ", ".join(dispo) or "aucun"))
|
||
a.echelle = 1
|
||
final = a.sortie
|
||
if upscayl:
|
||
a.sortie = tempfile.mkdtemp(prefix="hd_export_")
|
||
os.makedirs(a.sortie, exist_ok=True)
|
||
if not a.sans_decors:
|
||
export_backgrounds(a.jeu, a.sortie, a.motif, a.echelle)
|
||
if a.sprites:
|
||
export_sprites(np, a.jeu, a.sortie, a.sprites, a.echelle)
|
||
if a.planches:
|
||
export_sheets(np, a.jeu, a.sortie, a.planches, a.echelle)
|
||
if upscayl:
|
||
n = 0
|
||
try:
|
||
for sub in ("", "SPRITES", "SHEETS"):
|
||
src = os.path.join(a.sortie, sub)
|
||
if os.path.isdir(src):
|
||
n += run_upscayl(upscayl, models, a.upscayl, src, os.path.join(final, sub))
|
||
except GpuArret:
|
||
shutil.rmtree(a.sortie, ignore_errors=True)
|
||
sys.exit("Export interrompu (%d image(s) faites). Fermez les jeux et applications 3D ouverts, "
|
||
"puis relancez avec --reparer pour reprendre." % n)
|
||
shutil.rmtree(a.sortie, ignore_errors=True)
|
||
print("%d image(s) HD dans %s" % (n, final))
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|