main init
This commit is contained in:
21
Itch/README.md
Normal file
21
Itch/README.md
Normal file
@@ -0,0 +1,21 @@
|
||||
# Itch – Werkzeuge für itch.io-Seiten
|
||||
|
||||
Alles, um ein Projekt auf itch.io zu bringen. Ablauf steuert der Skill **`itchiocreater`**; Ergebnis landet
|
||||
im Projekt unter `docs\itchio\`. Motive für Cover/Banner kommen aus ComfyGen (`gen generate itch_keyart`).
|
||||
|
||||
| Ich brauche … | Werkzeug | Beispiel |
|
||||
|---|---|---|
|
||||
| Cover 630×500, Banner 960×256 + 1920×512, Hintergrund 1920×1200 mit Titel | `itch_images.py` | `py -3.12 itch_images.py --title "X" --tagline "…" --backdrop keyart.png [--cover-art cover.png] [--hero figur.png] [--font f.ttf] [--color "#hex"] --out docs\itchio` |
|
||||
| Echte Screenshots eines HTML-Spiels (automatisch, Headless-Edge) | `itch_screens.mjs` | `node itch_screens.mjs docs\itchio\shots.json` (Format im Dateikopf: Seite, Größe, pro Bild Query/Tasten/Klicks/JS) |
|
||||
| Screenshots eines exe-Spiels, während man spielt | `itch_capture.ps1` | `itch_capture.ps1 -Exe release\Spiel.exe -Every 4 -Count 20` · `-Hotkey` (F9 = Bild, Esc = Ende) · `-Title "Fenstertitel"` |
|
||||
| Screenshots im Rahmen mit Bildunterschrift (Store-Look) | `itch_promo.py` | `py -3.12 itch_promo.py --shots …\screenshots --captions captions.txt --backdrop keyart.png --out …\promo` |
|
||||
| Trailer-MP4 aus Screenshots + Musik (für YouTube-Link) | `itch_trailer.py` | `py -3.12 itch_trailer.py --shots … --music m.mp3 --title "X" --tagline "…" --footer "sn09.itch.io/x" --out trailer.mp4` |
|
||||
| Prüfen vor dem Upload | `itch_check.py` | `py -3.12 itch_check.py docs\itchio --upload release\x-web.zip --upload release\X.exe` |
|
||||
|
||||
Regeln:
|
||||
- Screenshots zeigen immer das **echte Spiel** (itch.io-Regel, sonst irreführend). KI-Bilder nur für Cover,
|
||||
Banner, Hintergrund und den Rahmen der Promo-Bilder.
|
||||
- KI-Offenlegung auf itch.io immer **Yes** (Grafik/Sound mit ComfyUI).
|
||||
- Voraussetzungen: Python 3.12 + Pillow, Node 18+, Microsoft Edge (Screenshots), ffmpeg (Trailer).
|
||||
|
||||
Vorbilder: `GladiatorIdle\docs\itchio\` (vollständig inkl. Trailer, install.html), `Pipefix\docs\itchio\`.
|
||||
94
Itch/itch_capture.ps1
Normal file
94
Itch/itch_capture.ps1
Normal file
@@ -0,0 +1,94 @@
|
||||
<#
|
||||
Screenshots of a running Windows game (exe) for itch.io: starts the game (or uses a running
|
||||
window), then saves the game window every few seconds while you play. Afterwards pick the best.
|
||||
|
||||
D:\Oculusquest\Projekt\_Tools\Itch\itch_capture.ps1 -Exe release\Spiel.exe -Out docs\itchio\screenshots
|
||||
... -Title "Gladiator" use an already running window whose title contains this text
|
||||
... -Every 4 -Count 30 -Delay 8 first shot after 8 s, then every 4 s, 30 shots
|
||||
... -Hotkey instead of a timer: one shot per press of F9 (Esc ends)
|
||||
|
||||
Captures what is on screen in the window rectangle (the window must be visible, not covered).
|
||||
Files: raw_001.png, raw_002.png, ... (existing ones are kept, numbering continues).
|
||||
#>
|
||||
param(
|
||||
[string]$Exe,
|
||||
[string]$Title,
|
||||
[string]$Out = 'docs\itchio\screenshots',
|
||||
[int]$Every = 4,
|
||||
[int]$Count = 20,
|
||||
[int]$Delay = 8,
|
||||
[switch]$Hotkey
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
Add-Type @'
|
||||
using System; using System.Runtime.InteropServices;
|
||||
public static class W32 {
|
||||
[StructLayout(LayoutKind.Sequential)] public struct RECT { public int L, T, R, B; }
|
||||
[DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr h, out RECT r);
|
||||
[DllImport("dwmapi.dll")] public static extern int DwmGetWindowAttribute(IntPtr h, int a, out RECT r, int s);
|
||||
[DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h);
|
||||
[DllImport("user32.dll")] public static extern short GetAsyncKeyState(int k);
|
||||
[DllImport("user32.dll")] public static extern bool SetProcessDPIAware();
|
||||
}
|
||||
'@
|
||||
[W32]::SetProcessDPIAware() | Out-Null
|
||||
|
||||
New-Item -ItemType Directory -Force $Out | Out-Null
|
||||
$proc = $null
|
||||
if ($Exe) {
|
||||
$exePath = (Resolve-Path $Exe).Path
|
||||
$proc = Start-Process $exePath -WorkingDirectory (Split-Path $exePath) -PassThru
|
||||
"Gestartet: $exePath - warte auf das Fenster ..."
|
||||
}
|
||||
function Find-Window {
|
||||
if ($proc) { $proc.Refresh(); if ($proc.MainWindowHandle -ne 0) { return $proc.MainWindowHandle } }
|
||||
if ($Title) {
|
||||
$p = Get-Process | Where-Object { $_.MainWindowHandle -ne 0 -and $_.MainWindowTitle -like "*$Title*" } | Select-Object -First 1
|
||||
if ($p) { return $p.MainWindowHandle }
|
||||
}
|
||||
if ($proc) { # launchers: the window may belong to a child process with the same name
|
||||
$p = Get-Process -Name $proc.ProcessName -ErrorAction SilentlyContinue | Where-Object MainWindowHandle -ne 0 | Select-Object -First 1
|
||||
if ($p) { return $p.MainWindowHandle }
|
||||
}
|
||||
return [IntPtr]::Zero
|
||||
}
|
||||
$h = [IntPtr]::Zero
|
||||
for ($i = 0; $i -lt 60 -and $h -eq [IntPtr]::Zero; $i++) { Start-Sleep -Milliseconds 500; $h = Find-Window }
|
||||
if ($h -eq [IntPtr]::Zero) { throw 'Kein Spielfenster gefunden (-Exe oder -Title angeben).' }
|
||||
|
||||
$n = (Get-ChildItem $Out -Filter 'raw_*.png' -ErrorAction SilentlyContinue | Measure-Object).Count
|
||||
function Snap {
|
||||
$r = New-Object W32+RECT
|
||||
# DWM bounds exclude the invisible resize border of Windows 10/11 windows
|
||||
if ([W32]::DwmGetWindowAttribute($h, 9, [ref]$r, 16) -ne 0) { [W32]::GetWindowRect($h, [ref]$r) | Out-Null }
|
||||
$w = $r.R - $r.L; $hh = $r.B - $r.T
|
||||
if ($w -lt 50 -or $hh -lt 50) { return }
|
||||
$bmp = New-Object System.Drawing.Bitmap $w, $hh
|
||||
$g = [System.Drawing.Graphics]::FromImage($bmp)
|
||||
$g.CopyFromScreen($r.L, $r.T, 0, 0, $bmp.Size)
|
||||
$script:n++
|
||||
$file = Join-Path $Out ('raw_{0:000}.png' -f $script:n)
|
||||
$bmp.Save($file, [System.Drawing.Imaging.ImageFormat]::Png)
|
||||
$g.Dispose(); $bmp.Dispose()
|
||||
" $file ($w x $hh)"
|
||||
}
|
||||
|
||||
[W32]::SetForegroundWindow($h) | Out-Null
|
||||
if ($Hotkey) {
|
||||
'F9 = Screenshot, Esc = fertig. Spiel jetzt im Vordergrund lassen.'
|
||||
while ($true) {
|
||||
if ([W32]::GetAsyncKeyState(0x78) -band 1) { Snap } # F9
|
||||
if ([W32]::GetAsyncKeyState(0x1B) -band 0x8000) { break } # Esc
|
||||
Start-Sleep -Milliseconds 30
|
||||
}
|
||||
} else {
|
||||
"Erster Screenshot in $Delay s, dann alle $Every s ($Count Stück). Einfach spielen."
|
||||
Start-Sleep -Seconds $Delay
|
||||
for ($i = 0; $i -lt $Count; $i++) {
|
||||
if ($proc -and $proc.HasExited -and (Find-Window) -eq [IntPtr]::Zero) { 'Spiel beendet.'; break }
|
||||
Snap
|
||||
Start-Sleep -Seconds $Every
|
||||
}
|
||||
}
|
||||
"Fertig: $script:n Screenshots in $((Resolve-Path $Out).Path) - die besten 5-8 behalten, Rest loeschen."
|
||||
101
Itch/itch_check.py
Normal file
101
Itch/itch_check.py
Normal file
@@ -0,0 +1,101 @@
|
||||
"""Pre-flight check of an itch.io package folder (docs/itchio) before uploading.
|
||||
|
||||
py -3.12 itch_check.py docs/itchio [--upload release/game-web.zip] [--upload release/Game.exe]
|
||||
|
||||
Checks: cover size/ratio, banner/background, screenshot count and size, description.html
|
||||
(no <script>, size, links), README fields filled, uploads exist (zip has index.html at the top,
|
||||
size limits). Prints OK / WARN / FEHLT lines - short on purpose.
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
import zipfile
|
||||
|
||||
from PIL import Image
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("folder")
|
||||
ap.add_argument("--upload", action="append", default=[])
|
||||
a = ap.parse_args()
|
||||
f = a.folder
|
||||
out = []
|
||||
ok = lambda s: out.append("OK " + s)
|
||||
warn = lambda s: out.append("WARN " + s)
|
||||
miss = lambda s: out.append("FEHLT " + s)
|
||||
|
||||
def img(name):
|
||||
p = os.path.join(f, name)
|
||||
return Image.open(p).size if os.path.exists(p) else None
|
||||
|
||||
c = img("cover.png")
|
||||
if not c:
|
||||
miss("cover.png (630x500)")
|
||||
elif c[0] < 315 or abs(c[0] / c[1] - 630 / 500) > 0.03:
|
||||
warn(f"cover.png {c[0]}x{c[1]} - empfohlen 630x500 (mind. 315x250, Verhältnis 1.26)")
|
||||
else:
|
||||
ok(f"cover.png {c[0]}x{c[1]}")
|
||||
for n in ("banner_960x256.png", "background_1920x1200.jpg"):
|
||||
(ok if img(n) else warn)(n + ("" if img(n) else " fehlt (nur für Edit theme)"))
|
||||
|
||||
shots = []
|
||||
for d in ("screenshots", "promo", "screens"):
|
||||
p = os.path.join(f, d)
|
||||
if os.path.isdir(p):
|
||||
shots += [os.path.join(p, x) for x in os.listdir(p) if x.lower().endswith((".png", ".jpg", ".gif")) and not x.startswith("raw_")]
|
||||
raws = [x for d in ("screenshots",) if os.path.isdir(os.path.join(f, d)) for x in os.listdir(os.path.join(f, d)) if x.startswith("raw_")]
|
||||
if len(shots) < 3:
|
||||
miss(f"Screenshots: {len(shots)} (mind. 3, gut 5-8)")
|
||||
else:
|
||||
small = [os.path.basename(s) for s in shots if Image.open(s).size[0] < 1280]
|
||||
big = [os.path.basename(s) for s in shots if os.path.getsize(s) > 3 * 1024 * 1024]
|
||||
ok(f"{len(shots)} Screenshots")
|
||||
if small:
|
||||
warn("klein (<1280 breit): " + ", ".join(small[:5]))
|
||||
if big:
|
||||
warn("über 3 MB (itch-Limit ok, aber langsam): " + ", ".join(big[:5]))
|
||||
if raws:
|
||||
warn(f"{len(raws)} raw_*.png aus itch_capture noch nicht aussortiert")
|
||||
|
||||
desc = os.path.join(f, "description.html")
|
||||
if not os.path.exists(desc):
|
||||
miss("description.html")
|
||||
else:
|
||||
t = open(desc, encoding="utf-8-sig").read()
|
||||
body = re.sub(r"(?is)^.*<body[^>]*>|</body>.*$", "", t)
|
||||
if re.search(r"<script|<iframe|<style", body, re.I):
|
||||
warn("description.html: <script>/<iframe>/<style> - itch entfernt das")
|
||||
if len(re.sub(r"<[^>]+>", "", t)) < 400:
|
||||
warn("description.html sehr kurz")
|
||||
if re.search(r"TODO|XXX|\{\{", t):
|
||||
warn("description.html enthält Platzhalter")
|
||||
ok(f"description.html ({len(t)} Zeichen)")
|
||||
|
||||
readme = os.path.join(f, "README.md")
|
||||
if not os.path.exists(readme):
|
||||
miss("README.md (Felder für Edit game)")
|
||||
else:
|
||||
t = open(readme, encoding="utf-8-sig").read()
|
||||
holes = re.findall(r"\|\s*([^|\n]+?)\s*\|\s*(?:_[^_]*_|…|TODO|\?)\s*\|", t)
|
||||
(warn("README: offene Felder: " + ", ".join(h.strip("* ") for h in holes[:8])) if holes else ok("README.md Felder ausgefüllt"))
|
||||
|
||||
for u in a.upload:
|
||||
if not os.path.exists(u):
|
||||
miss(f"Upload {u}")
|
||||
continue
|
||||
mb = os.path.getsize(u) / 1024 / 1024
|
||||
if u.lower().endswith(".zip"):
|
||||
with zipfile.ZipFile(u) as z:
|
||||
names = z.namelist()
|
||||
if "index.html" not in names:
|
||||
warn(f"{u}: kein index.html auf oberster Ebene (für Browser-Spiele nötig)")
|
||||
if len(names) > 1000:
|
||||
warn(f"{u}: {len(names)} Dateien (itch: max. 1000 für HTML-Spiele)")
|
||||
(warn if mb > 1000 else ok)(f"Upload {os.path.basename(u)} {mb:.1f} MB" + (" - über 1 GB: butler nötig" if mb > 1000 else ""))
|
||||
|
||||
print("\n".join(out))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
141
Itch/itch_images.py
Normal file
141
Itch/itch_images.py
Normal file
@@ -0,0 +1,141 @@
|
||||
"""itch.io page images from one backdrop picture + the game title.
|
||||
|
||||
py -3.12 itch_images.py --title "Pipefix" --tagline "Lay the pipes. Beat the flow." \
|
||||
--backdrop sprite-generator/output/backdrop_raw_00001_.png --out docs/itchio \
|
||||
[--font Assets/Fonts/PressStart2P-Regular.ttf] [--text-font ...] [--color "#d9a441"] \
|
||||
[--hero game/assets/Sprites/player.png] [--cover-art sprite-generator/output/itch_cover_raw_00001_.png]
|
||||
|
||||
Writes cover.png (630x500), banner_960x256.png, banner_1920x512.png, background_1920x1200.jpg.
|
||||
--cover-art: own picture for the cover (otherwise the backdrop). Title on the cover at the top,
|
||||
so the motif should leave the upper third calm. Use --cover-plain to keep the cover without text.
|
||||
Without --font a Windows system font (Segoe UI Black / Arial Bold) is used.
|
||||
Generalised from Pipefix/docs/itchio/make_images.py (that one also frames a board screenshot).
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
|
||||
from PIL import Image, ImageDraw, ImageEnhance, ImageFilter, ImageFont
|
||||
|
||||
SYSTEM_FONTS = [r"C:\Windows\Fonts\seguibl.ttf", r"C:\Windows\Fonts\arialbd.ttf"]
|
||||
SYSTEM_TEXT = [r"C:\Windows\Fonts\segoeui.ttf", r"C:\Windows\Fonts\arial.ttf"]
|
||||
|
||||
|
||||
def first_existing(paths):
|
||||
for p in paths:
|
||||
if p and os.path.exists(p):
|
||||
return p
|
||||
raise SystemExit("no font found - pass --font")
|
||||
|
||||
|
||||
def hex_rgb(s):
|
||||
s = s.lstrip("#")
|
||||
return tuple(int(s[i:i + 2], 16) for i in (0, 2, 4))
|
||||
|
||||
|
||||
def cover_crop(img, w, h):
|
||||
k = max(w / img.width, h / img.height)
|
||||
img = img.resize((round(img.width * k), round(img.height * k)), Image.LANCZOS)
|
||||
x, y = (img.width - w) // 2, (img.height - h) // 2
|
||||
return img.crop((x, y, x + w, y + h))
|
||||
|
||||
|
||||
def backdrop(src, w, h, dark=0.55, blur=0):
|
||||
img = cover_crop(src, w, h)
|
||||
if blur:
|
||||
img = img.filter(ImageFilter.GaussianBlur(blur))
|
||||
img = ImageEnhance.Brightness(img).enhance(dark)
|
||||
vig = Image.new("L", (w, h), 0)
|
||||
ImageDraw.Draw(vig).ellipse((-w * 0.25, -h * 0.35, w * 1.25, h * 1.35), fill=255)
|
||||
vig = vig.filter(ImageFilter.GaussianBlur(min(w, h) * 0.18))
|
||||
return Image.composite(img, Image.new("RGB", (w, h), (0, 0, 0)), vig)
|
||||
|
||||
|
||||
def fit_font(path, text, size, max_w):
|
||||
while size > 8:
|
||||
f = ImageFont.truetype(path, size)
|
||||
if f.getbbox(text)[2] <= max_w:
|
||||
return f
|
||||
size -= 2
|
||||
return ImageFont.truetype(path, size)
|
||||
|
||||
|
||||
def title(draw, xy, text, font, color, anchor="mm"):
|
||||
size = font.size
|
||||
off = max(2, size // 12)
|
||||
shadow = (12, 8, 4)
|
||||
dark = tuple(c // 3 for c in color)
|
||||
x, y = xy
|
||||
draw.text((x + off, y + off), text, font=font, fill=shadow, anchor=anchor)
|
||||
draw.text((x, y + off // 2), text, font=font, fill=dark, anchor=anchor)
|
||||
draw.text((x, y), text, font=font, fill=color, anchor=anchor, stroke_width=max(1, size // 24), stroke_fill=shadow)
|
||||
|
||||
|
||||
def text(draw, xy, s, font, fill=(230, 225, 215), anchor="mm"):
|
||||
draw.text((xy[0] + 2, xy[1] + 2), s, font=font, fill=(10, 8, 6), anchor=anchor)
|
||||
draw.text(xy, s, font=font, fill=fill, anchor=anchor)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--title", required=True)
|
||||
ap.add_argument("--tagline", default="")
|
||||
ap.add_argument("--backdrop", required=True)
|
||||
ap.add_argument("--out", default=".")
|
||||
ap.add_argument("--font")
|
||||
ap.add_argument("--text-font")
|
||||
ap.add_argument("--color", default="#4fd8ff")
|
||||
ap.add_argument("--hero", help="transparent PNG placed bottom-left on cover and banner")
|
||||
ap.add_argument("--cover-art", help="own picture for the cover (default: backdrop)")
|
||||
ap.add_argument("--cover-plain", action="store_true", help="cover without title/tagline")
|
||||
a = ap.parse_args()
|
||||
|
||||
os.makedirs(a.out, exist_ok=True)
|
||||
src = Image.open(a.backdrop).convert("RGB")
|
||||
tfont = first_existing([a.font] + SYSTEM_FONTS)
|
||||
xfont = first_existing([a.text_font, a.font] + SYSTEM_TEXT)
|
||||
color = hex_rgb(a.color)
|
||||
hero = Image.open(a.hero).convert("RGBA") if a.hero else None
|
||||
|
||||
def place_hero(img, size, xy):
|
||||
if hero:
|
||||
h = hero.copy()
|
||||
h.thumbnail((size, size), Image.LANCZOS)
|
||||
img.alpha_composite(h, xy)
|
||||
|
||||
# cover 630x500
|
||||
w, h = 630, 500
|
||||
csrc = Image.open(a.cover_art).convert("RGB") if a.cover_art else src
|
||||
img = backdrop(csrc, w, h, 1.0 if a.cover_art else 0.7).convert("RGBA")
|
||||
if not a.cover_art:
|
||||
place_hero(img, 220, (30, h - 250))
|
||||
if not a.cover_plain:
|
||||
if a.cover_art: # darken the top behind the title, keep the motif bright
|
||||
shade = Image.new("L", (w, h), 0)
|
||||
ImageDraw.Draw(shade).rectangle((0, 0, w, int(h * 0.42)), fill=150)
|
||||
shade = shade.filter(ImageFilter.GaussianBlur(40))
|
||||
img = Image.composite(Image.new("RGBA", (w, h), (0, 0, 0, 255)), img, shade)
|
||||
d = ImageDraw.Draw(img)
|
||||
ty = 80 if a.cover_art else 150
|
||||
title(d, (w // 2, ty), a.title, fit_font(tfont, a.title, 80, w - 60), color)
|
||||
if a.tagline:
|
||||
text(d, (w // 2, ty + 72), a.tagline, fit_font(xfont, a.tagline, 30, w - 60))
|
||||
img.convert("RGB").save(os.path.join(a.out, "cover.png"), optimize=True)
|
||||
|
||||
# banners
|
||||
for bw, bh in ((960, 256), (1920, 512)):
|
||||
k = bh / 256
|
||||
img = backdrop(src, bw, bh, 0.6).convert("RGBA")
|
||||
place_hero(img, round(200 * k), (round(24 * k), round(40 * k)))
|
||||
left = round((250 if hero else 40) * k)
|
||||
d = ImageDraw.Draw(img)
|
||||
title(d, (left, round(100 * k)), a.title, fit_font(tfont, a.title, round(70 * k), bw - left - 40), color, anchor="lm")
|
||||
if a.tagline:
|
||||
text(d, (left + 2, round(170 * k)), a.tagline, fit_font(xfont, a.tagline, round(32 * k), bw - left - 40), anchor="lm")
|
||||
img.convert("RGB").save(os.path.join(a.out, f"banner_{bw}x{bh}.png"), optimize=True)
|
||||
|
||||
backdrop(src, 1920, 1200, 0.45, blur=3).save(os.path.join(a.out, "background_1920x1200.jpg"), quality=86)
|
||||
print("ok ->", os.path.abspath(a.out))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
84
Itch/itch_promo.py
Normal file
84
Itch/itch_promo.py
Normal file
@@ -0,0 +1,84 @@
|
||||
"""Promo screenshots: real game screenshots framed on a (ComfyUI) backdrop with a short caption -
|
||||
the store look. The game image itself is never altered.
|
||||
|
||||
py -3.12 itch_promo.py --shots docs/itchio/screenshots --captions docs/itchio/captions.txt \
|
||||
--backdrop sprite-generator/output/itch_keyart_raw_00001_.png --out docs/itchio/promo \
|
||||
[--size 1920x1080] [--font C:/Windows/Fonts/seguibl.ttf] [--color "#4fd8ff"]
|
||||
|
||||
captions.txt: one line per screenshot, "file.png | Caption text" (files without a line are skipped).
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
|
||||
from PIL import Image, ImageDraw, ImageEnhance, ImageFilter, ImageFont
|
||||
|
||||
SYSTEM_FONTS = [r"C:\Windows\Fonts\seguibl.ttf", r"C:\Windows\Fonts\arialbd.ttf"]
|
||||
|
||||
|
||||
def hex_rgb(s):
|
||||
s = s.lstrip("#")
|
||||
return tuple(int(s[i:i + 2], 16) for i in (0, 2, 4))
|
||||
|
||||
|
||||
def cover_crop(img, w, h):
|
||||
k = max(w / img.width, h / img.height)
|
||||
img = img.resize((round(img.width * k), round(img.height * k)), Image.LANCZOS)
|
||||
x, y = (img.width - w) // 2, (img.height - h) // 2
|
||||
return img.crop((x, y, x + w, y + h))
|
||||
|
||||
|
||||
def fit_font(path, text, size, max_w):
|
||||
while size > 10:
|
||||
f = ImageFont.truetype(path, size)
|
||||
if f.getbbox(text)[2] <= max_w:
|
||||
return f
|
||||
size -= 2
|
||||
return ImageFont.truetype(path, size)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--shots", required=True)
|
||||
ap.add_argument("--captions", required=True)
|
||||
ap.add_argument("--backdrop", required=True)
|
||||
ap.add_argument("--out", required=True)
|
||||
ap.add_argument("--size", default="1920x1080")
|
||||
ap.add_argument("--font")
|
||||
ap.add_argument("--color", default="#4fd8ff")
|
||||
a = ap.parse_args()
|
||||
|
||||
W, H = map(int, a.size.lower().split("x"))
|
||||
font_path = a.font if a.font and os.path.exists(a.font) else next(p for p in SYSTEM_FONTS if os.path.exists(p))
|
||||
accent = hex_rgb(a.color)
|
||||
bg = cover_crop(Image.open(a.backdrop).convert("RGB"), W, H).filter(ImageFilter.GaussianBlur(6))
|
||||
bg = ImageEnhance.Brightness(bg).enhance(0.45)
|
||||
os.makedirs(a.out, exist_ok=True)
|
||||
|
||||
lines = [l.split("|", 1) for l in open(a.captions, encoding="utf-8-sig").read().splitlines() if "|" in l]
|
||||
for i, (fname, caption) in enumerate(lines, 1):
|
||||
fname, caption = fname.strip(), caption.strip()
|
||||
shot = Image.open(os.path.join(a.shots, fname)).convert("RGB")
|
||||
top = int(H * 0.19) # caption band
|
||||
maxw, maxh = int(W * 0.86), H - top - int(H * 0.06)
|
||||
k = min(maxw / shot.width, maxh / shot.height)
|
||||
shot = shot.resize((round(shot.width * k), round(shot.height * k)), Image.LANCZOS)
|
||||
img = bg.copy().convert("RGBA")
|
||||
x, y = (W - shot.width) // 2, top
|
||||
# shadow + thin accent frame
|
||||
sh = Image.new("RGBA", (shot.width + 80, shot.height + 80), (0, 0, 0, 0))
|
||||
ImageDraw.Draw(sh).rectangle((40, 40, 40 + shot.width, 40 + shot.height), fill=(0, 0, 0, 190))
|
||||
img.alpha_composite(sh.filter(ImageFilter.GaussianBlur(22)), (x - 40 + 10, y - 40 + 16))
|
||||
ImageDraw.Draw(img).rectangle((x - 4, y - 4, x + shot.width + 3, y + shot.height + 3), outline=accent, width=4)
|
||||
img.paste(shot, (x, y))
|
||||
d = ImageDraw.Draw(img)
|
||||
f = fit_font(font_path, caption, int(H * 0.07), int(W * 0.9))
|
||||
cy = top // 2
|
||||
d.text((W // 2 + 3, cy + 3), caption, font=f, fill=(0, 0, 0), anchor="mm")
|
||||
d.text((W // 2, cy), caption, font=f, fill=(255, 255, 255), anchor="mm", stroke_width=2, stroke_fill=(0, 0, 0))
|
||||
out = os.path.join(a.out, f"promo_{i:02d}.png")
|
||||
img.convert("RGB").save(out, optimize=True)
|
||||
print(out)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
86
Itch/itch_screens.mjs
Normal file
86
Itch/itch_screens.mjs
Normal file
@@ -0,0 +1,86 @@
|
||||
// Real screenshots of an HTML game for itch.io - headless Edge over the DevTools protocol,
|
||||
// no Playwright needed. Each shot loads the page fresh (own query string), runs its steps
|
||||
// (keys, clicks, JS, waits) and saves a PNG at the exact size.
|
||||
//
|
||||
// node D:\Oculusquest\Projekt\_Tools\Itch\itch_screens.mjs docs\itchio\shots.json
|
||||
//
|
||||
// shots.json (paths relative to the json file's project = cwd):
|
||||
// {
|
||||
// "page": "game/index.html", // or "release/x.html", or "http://localhost:5173/"
|
||||
// "size": "1920x1080", // viewport = image size
|
||||
// "out": "docs/itchio/screenshots",
|
||||
// "shots": [
|
||||
// { "name": "01_menu", "wait": 1500 },
|
||||
// { "name": "02_play", "query": "?play&level=3", "steps": [
|
||||
// { "key": "ArrowRight", "hold": 900 }, { "key": " " }, { "click": [960, 540] },
|
||||
// { "eval": "Kit.audio && 0" }, { "wait": 700 } ] }
|
||||
// ]
|
||||
// }
|
||||
// Step "key": name as in KeyboardEvent.key; "hold" ms keeps it pressed. "eval" runs JS in the
|
||||
// page (e.g. set a level, give coins - only to reach a real scene faster, never to fake one).
|
||||
import { spawn } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
|
||||
const specFile = process.argv[2];
|
||||
if (!specFile) { console.error('usage: node itch_screens.mjs <shots.json>'); process.exit(2); }
|
||||
const spec = JSON.parse(fs.readFileSync(specFile, 'utf8').replace(/^/, '')); // PowerShell writes a BOM
|
||||
const root = process.cwd();
|
||||
const [W, H] = (spec.size || '1920x1080').split('x').map(Number);
|
||||
const outDir = path.resolve(root, spec.out || 'docs/itchio/screenshots');
|
||||
fs.mkdirSync(outDir, { recursive: true });
|
||||
const pageUrl = /^https?:/.test(spec.page) ? spec.page : pathToFileURL(path.resolve(root, spec.page)).href;
|
||||
|
||||
const EDGE = ['C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe', 'C:/Program Files/Microsoft/Edge/Application/msedge.exe'].find(fs.existsSync);
|
||||
if (!EDGE) { console.error('Microsoft Edge nicht gefunden'); process.exit(1); }
|
||||
const PORT = 9300 + Math.floor(Math.random() * 500);
|
||||
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||
const KEYCODES = { ArrowLeft: 37, ArrowUp: 38, ArrowRight: 39, ArrowDown: 40, Enter: 13, Escape: 27, ' ': 32, Tab: 9, Shift: 16, Control: 17 };
|
||||
const codeOf = k => k === ' ' ? 'Space' : k.startsWith('Arrow') || k.length > 1 ? k : /[a-z]/i.test(k) ? 'Key' + k.toUpperCase() : /\d/.test(k) ? 'Digit' + k : k;
|
||||
|
||||
const prof = fs.mkdtempSync(path.join(os.tmpdir(), 'itchshots-'));
|
||||
const edge = spawn(EDGE, ['--headless=new', `--remote-debugging-port=${PORT}`, `--user-data-dir=${prof}`, '--allow-file-access-from-files',
|
||||
'--autoplay-policy=no-user-gesture-required', '--hide-scrollbars', '--mute-audio', `--window-size=${W},${H}`, 'about:blank']);
|
||||
const cleanup = () => { try { edge.kill(); } catch {} setTimeout(() => fs.rmSync(prof, { recursive: true, force: true }), 500); };
|
||||
|
||||
try {
|
||||
let targets;
|
||||
for (let i = 0; i < 60 && !targets; i++) { try { targets = await (await fetch(`http://127.0.0.1:${PORT}/json/list`)).json(); } catch { await sleep(200); } }
|
||||
const ws = new WebSocket(targets.find(t => t.type === 'page').webSocketDebuggerUrl);
|
||||
await new Promise(r => ws.addEventListener('open', r));
|
||||
let id = 0; const pending = {}; const errors = [];
|
||||
ws.addEventListener('message', ev => {
|
||||
const m = JSON.parse(ev.data);
|
||||
if (m.id && pending[m.id]) { pending[m.id](m); delete pending[m.id]; }
|
||||
if (m.method === 'Runtime.exceptionThrown') errors.push(m.params.exceptionDetails.exception?.description || m.params.exceptionDetails.text);
|
||||
});
|
||||
const send = (method, params = {}) => new Promise(r => { const i = ++id; pending[i] = r; ws.send(JSON.stringify({ id: i, method, params })); });
|
||||
await send('Runtime.enable');
|
||||
await send('Emulation.setDeviceMetricsOverride', { width: W, height: H, deviceScaleFactor: 1, mobile: false });
|
||||
|
||||
const key = async (k, type) => send('Input.dispatchKeyEvent', { type, key: k, code: codeOf(k), windowsVirtualKeyCode: KEYCODES[k] ?? k.toUpperCase().charCodeAt(0), text: type === 'keyDown' && k.length === 1 ? k : undefined });
|
||||
for (const shot of spec.shots) {
|
||||
errors.length = 0;
|
||||
await send('Page.navigate', { url: pageUrl + (shot.query || '') });
|
||||
await sleep(shot.load ?? 1200);
|
||||
for (const s of shot.steps || []) {
|
||||
if (s.wait) await sleep(s.wait);
|
||||
if (s.key) { await key(s.key, 'keyDown'); await sleep(s.hold ?? 60); await key(s.key, 'keyUp'); }
|
||||
if (s.click) for (const type of ['mousePressed', 'mouseReleased']) await send('Input.dispatchMouseEvent', { type, x: s.click[0], y: s.click[1], button: 'left', clickCount: 1 });
|
||||
if (s.eval) await send('Runtime.evaluate', { expression: s.eval, awaitPromise: true });
|
||||
if (s.after) await sleep(s.after);
|
||||
}
|
||||
await sleep(shot.wait ?? 300);
|
||||
const r = await send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false });
|
||||
const file = path.join(outDir, `${shot.name}.png`);
|
||||
fs.writeFileSync(file, Buffer.from(r.result.data, 'base64'));
|
||||
console.log(`${shot.name}.png${errors.length ? ` (Fehler im Spiel: ${errors[0].split('\n')[0]})` : ''}`);
|
||||
}
|
||||
ws.close();
|
||||
console.log(`Fertig: ${spec.shots.length} Screenshots in ${outDir} (${W}x${H})`);
|
||||
} catch (e) {
|
||||
console.error('FAIL', e.message || e);
|
||||
process.exitCode = 1;
|
||||
} finally { cleanup(); }
|
||||
122
Itch/itch_trailer.py
Normal file
122
Itch/itch_trailer.py
Normal file
@@ -0,0 +1,122 @@
|
||||
"""Trailer (MP4, 1920x1080) from screenshots: slow Ken-Burns move per image, soft cross-fades,
|
||||
music, end card with title + tagline + footer. Generalised from GladiatorIdle/docs/itchio/make_trailer.py.
|
||||
Upload to YouTube, put the link into itch.io "Gameplay video or trailer". Needs ffmpeg in PATH.
|
||||
|
||||
py -3.12 itch_trailer.py --shots docs/itchio/screenshots --music game/assets/Audio/music_game.mp3 \
|
||||
--title "PIPEFIX" --tagline "Lay the pipes. Beat the flow." --footer "sn09.itch.io/pipefix" \
|
||||
--out docs/itchio/trailer.mp4 [--order 01_menu,03_play,...] [--secs 3.2] [--card-bg background_1920x1200.jpg]
|
||||
[--font C:/Windows/Fonts/seguibl.ttf] [--color "#4fd8ff"]
|
||||
Without --order all PNG/JPG in --shots are used in name order.
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFont, ImageFilter
|
||||
|
||||
FADE, FPS = 0.6, 30
|
||||
|
||||
|
||||
def hex_rgb(s):
|
||||
s = s.lstrip("#")
|
||||
return tuple(int(s[i:i + 2], 16) for i in (0, 2, 4))
|
||||
|
||||
|
||||
def fit(path, text, size, max_w):
|
||||
while size > 12:
|
||||
f = ImageFont.truetype(path, size)
|
||||
if f.getbbox(text)[2] <= max_w:
|
||||
return f
|
||||
size -= 4
|
||||
return ImageFont.truetype(path, size)
|
||||
|
||||
|
||||
def end_card(path, a, first_shot):
|
||||
src = a.card_bg or first_shot
|
||||
im = Image.open(src).convert("RGB")
|
||||
k = max(1920 / im.width, 1080 / im.height)
|
||||
im = im.resize((round(im.width * k), round(im.height * k)), Image.LANCZOS)
|
||||
im = im.crop(((im.width - 1920) // 2, (im.height - 1080) // 2, (im.width - 1920) // 2 + 1920, (im.height - 1080) // 2 + 1080))
|
||||
im = Image.blend(im.filter(ImageFilter.GaussianBlur(4)), Image.new("RGB", im.size, (0, 0, 0)), 0.6)
|
||||
d = ImageDraw.Draw(im)
|
||||
bold = a.font if a.font and os.path.exists(a.font) else r"C:\Windows\Fonts\seguibl.ttf"
|
||||
regular = r"C:\Windows\Fonts\segoeui.ttf"
|
||||
rows = [(a.title, fit(bold, a.title, 150, 1700), 400, hex_rgb(a.color)),
|
||||
(a.tagline, fit(bold, a.tagline, 56, 1700), 560, (240, 236, 228)),
|
||||
(a.footer, fit(regular, a.footer, 40, 1700), 780, (200, 196, 188))]
|
||||
for txt, f, y, col in rows:
|
||||
if not txt:
|
||||
continue
|
||||
d.text((964, y + 4), txt, font=f, fill=(0, 0, 0), anchor="mm")
|
||||
d.text((960, y), txt, font=f, fill=col, anchor="mm")
|
||||
im.save(path)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--shots", required=True)
|
||||
ap.add_argument("--music")
|
||||
ap.add_argument("--title", required=True)
|
||||
ap.add_argument("--tagline", default="")
|
||||
ap.add_argument("--footer", default="")
|
||||
ap.add_argument("--out", required=True)
|
||||
ap.add_argument("--order")
|
||||
ap.add_argument("--secs", type=float, default=3.2)
|
||||
ap.add_argument("--card-bg")
|
||||
ap.add_argument("--font")
|
||||
ap.add_argument("--color", default="#4fd8ff")
|
||||
a = ap.parse_args()
|
||||
|
||||
if a.order:
|
||||
names = [n.strip() for n in a.order.split(",") if n.strip()]
|
||||
imgs = []
|
||||
for n in names:
|
||||
p = next((os.path.join(a.shots, n + e) for e in ("", ".png", ".jpg") if os.path.isfile(os.path.join(a.shots, n + e))), None)
|
||||
if not p:
|
||||
raise SystemExit(f"fehlt: {n}")
|
||||
imgs.append(p)
|
||||
else:
|
||||
imgs = sorted(os.path.join(a.shots, f) for f in os.listdir(a.shots) if f.lower().endswith((".png", ".jpg")))
|
||||
if not imgs:
|
||||
raise SystemExit("keine Screenshots")
|
||||
|
||||
dur = a.secs
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
card = os.path.join(t, "end.png")
|
||||
end_card(card, a, imgs[0])
|
||||
clips = []
|
||||
for i, p in enumerate(imgs + [card]):
|
||||
c = os.path.join(t, f"c{i:02d}.mp4")
|
||||
frames = int((dur + FADE) * FPS)
|
||||
z = "if(eq(on,0),1.0,min(zoom+0.0009,1.12))" if i % 2 == 0 else "if(eq(on,0),1.12,max(zoom-0.0009,1.0))"
|
||||
vf = (f"scale=3840:2160:force_original_aspect_ratio=increase,crop=3840:2160,"
|
||||
f"zoompan=z='{z}':x='iw/2-(iw/zoom/2)':y='ih/2-(ih/zoom/2)':d={frames}:s=1920x1080:fps={FPS},format=yuv420p")
|
||||
subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-loop", "1", "-i", p, "-vf", vf, "-frames:v", str(frames),
|
||||
"-c:v", "libx264", "-preset", "medium", "-crf", "18", c], check=True)
|
||||
clips.append(c)
|
||||
args = ["ffmpeg", "-y", "-loglevel", "error"]
|
||||
for c in clips:
|
||||
args += ["-i", c]
|
||||
filt, last, off = [], "[0:v]", dur
|
||||
for i in range(1, len(clips)):
|
||||
out = f"[v{i}]"
|
||||
filt.append(f"{last}[{i}:v]xfade=transition=fade:duration={FADE}:offset={off:.2f}{out}")
|
||||
last, off = out, off + dur
|
||||
total = off + FADE
|
||||
if len(clips) == 1:
|
||||
filt, last = ["[0:v]null[v0]"], "[v0]"
|
||||
if a.music:
|
||||
args += ["-i", a.music, "-filter_complex",
|
||||
";".join(filt) + f";[{len(clips)}:a]atrim=0:{total:.2f},afade=t=in:d=1,afade=t=out:st={max(0, total - 2.5):.2f}:d=2.5[a]",
|
||||
"-map", last, "-map", "[a]", "-c:a", "aac", "-b:a", "192k", "-shortest"]
|
||||
else:
|
||||
args += ["-filter_complex", ";".join(filt), "-map", last]
|
||||
args += ["-c:v", "libx264", "-preset", "medium", "-crf", "18", "-pix_fmt", "yuv420p", a.out]
|
||||
os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True)
|
||||
subprocess.run(args, check=True)
|
||||
print("ok", a.out, f"{total:.0f} s")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user