Take over the tools of the other projects

AquaNova, AquaNovaAndroid, Atlas Legends, TinyWold and XP-Battleship now
use ComfyGen instead of their own copies. Added from them, with paths
taken from the project's config: generate_mesh (Hunyuan3D), mesh_prep,
trim, largest, uncut, level. generate.py defaults to the "prompts"
module; generate_audio and level honour AUDIO_SUBDIR (Atlas Legends
keeps its tracks in output/music).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-10-02 09:56:45 +02:00
parent e3d21e55c9
commit 9b35c3a7cc
9 changed files with 784 additions and 12 deletions

View File

@@ -13,11 +13,21 @@ das aktuelle Verzeichnis oder `--project <ordner>` (siehe `_bootstrap.py`).
| `generate_audio.py` / `adopt_audio.py` | Musik, Effekte | Stable Audio 3 | `AUDIO_MODULE` | | `generate_audio.py` / `adopt_audio.py` | Musik, Effekte | Stable Audio 3 | `AUDIO_MODULE` |
| `generate_voice.py` | Erzählstimme mit Whisper-Prüfung | Chatterbox (+ Kokoro-Referenzen) | `VOICE_MODULE`, `LANG_DIR`, `CARDS_FILE` | | `generate_voice.py` | Erzählstimme mit Whisper-Prüfung | Chatterbox (+ Kokoro-Referenzen) | `VOICE_MODULE`, `LANG_DIR`, `CARDS_FILE` |
| `make_voice_refs.py` | Referenzstimmen in `voice_refs/` | Kokoro | – | | `make_voice_refs.py` | Referenzstimmen in `voice_refs/` | Kokoro | – |
| `generate_mesh.py` | 3D-Modell (GLB, nur Form) aus einem Bild | Hunyuan3D v2 | – |
| `mesh_prep.py` | Mesh vereinfachen und einfärben (Low-Poly) | trimesh | – |
| `cutout.py <name> --holes` | Ausschnitt per Flood-Fill, auch eingeschlossene Löcher | – | – |
| `trim.py` / `largest.py` / `uncut.py` | Ränder abschneiden, Splitter entfernen, Ausschnitt reparieren | – | – |
| `level.py <name> [peak]` | Lautstärke eines Clips angleichen | ffmpeg | `AUDIO_SUBDIR` |
Benötigte Pfade in der Projekt-`config.py`: `OUTPUT_DIR`, `ASSETS_DIR`, für Stimmen `LANG_DIR`, `CARDS_FILE`. Projekt-`config.py`:
- immer `OUTPUT_DIR`
- `PROMPTS_MODULE` (Standard `prompts`), `AUDIO_MODULE`, optional `AUDIO_SUBDIR` (Standard `audio`)
- für `adopt*` / Portraits / Vintage `ASSETS_DIR`, für Stimmen `LANG_DIR` und `CARDS_FILE`
Jedes Projekt hat einen Starter `gen.cmd` (Vorlage: ein beliebiges Projekt kopieren), z. B. `gen generate <name>`.
Stimmen laufen in der gemeinsamen Umgebung `.venv-tts` (torch 2.6 für Chatterbox, ~6 GB, nicht in git). Stimmen laufen in der gemeinsamen Umgebung `.venv-tts` (torch 2.6 für Chatterbox, ~6 GB, nicht in git).
Neu anlegen: `py -3.12 -m venv .venv-tts`, dann torch 2.6 cu124, `chatterbox-tts`, `faster-whisper`, `kokoro`. Neu anlegen: `py -3.12 -m venv .venv-tts`, dann torch 2.6 cu124, `chatterbox-tts`, `faster-whisper`, `kokoro`.
Projekte, die schon umgestellt sind: YourlifeisGame. Ältere Projekte (AquaNova, TinyWold, …) haben noch Genutzt von: YourlifeisGame (`Spritegenerator\`), AquaNova, AquaNovaAndroid, Atlas Legends,
eigene Kopien in ihrem `sprite-generator` und können einzeln umziehen. TinyWold, XP-Battleship (je `sprite-generator\`).

View File

@@ -1,14 +1,14 @@
""" """
Atlas Legends sprite generator - talks directly to a local ComfyUI server. ComfyGen sprite generator - talks directly to a local ComfyUI server.
Usage: Usage:
python generate.py generate every prompt in prompts_life.py python generate.py generate every prompt in the project's PROMPTS_MODULE
python generate.py <name> generate just one prompt by name python generate.py <name> generate just one prompt by name
python generate.py --list-models list installed checkpoints python generate.py --list-models list installed checkpoints
Setup: Setup:
- Pick a checkpoint and workflow in config.py. - Pick a checkpoint and workflow in config.py.
- Add prompts to PROMPTS in prompts_life.py (name, positive_prompt) tuples. - Add prompts to PROMPTS in the project's prompts module (name, positive_prompt) tuples.
- Drop additional workflow templates into workflows/ - see README.md for - Drop additional workflow templates into workflows/ - see README.md for
the {{PLACEHOLDER}} convention they need to follow. the {{PLACEHOLDER}} convention they need to follow.
@@ -32,7 +32,7 @@ import urllib.parse
import _bootstrap # Projektordner (config.py, Listen) vor allen anderen Modulen import _bootstrap # Projektordner (config.py, Listen) vor allen anderen Modulen
import config import config
prompts = importlib.import_module(getattr(config, "PROMPTS_MODULE", "prompts_life")) prompts = importlib.import_module(getattr(config, "PROMPTS_MODULE", "prompts"))
def load_workflow_template(): def load_workflow_template():
@@ -150,7 +150,7 @@ if __name__ == "__main__":
everything = list(prompts.PROMPTS) + list(getattr(prompts, "BACKDROPS", [])) everything = list(prompts.PROMPTS) + list(getattr(prompts, "BACKDROPS", []))
todo = [p for p in everything if (p[0] == arg if arg else p in prompts.PROMPTS)] todo = [p for p in everything if (p[0] == arg if arg else p in prompts.PROMPTS)]
if not todo: if not todo:
print(f"No prompt named '{arg}' in prompts_life.py" if arg else "prompts_life.py has no PROMPTS entries.") print(f"No prompt named '{arg}' in {prompts.__name__}.py" if arg else f"{prompts.__name__}.py has no PROMPTS entries.")
sys.exit(1) sys.exit(1)
for entry in todo: for entry in todo:

View File

@@ -1,7 +1,7 @@
# Music + SFX generation via ComfyUI's Stable Audio pipeline (checkpoint # Music + SFX generation via ComfyUI's Stable Audio pipeline (checkpoint
# stable_audio_3_medium_base.safetensors). Same server as generate.py. # stable_audio_3_medium_base.safetensors). Same server as generate.py.
# Results land in output/audio/. Usage: # Results land in output/<AUDIO_SUBDIR>/ (default "audio"). Usage:
# python generate_audio.py # everything in audio_life.py # python generate_audio.py # everything in the project's AUDIO_MODULE
# python generate_audio.py sfx_click # single entry # python generate_audio.py sfx_click # single entry
import json import json
import os import os
@@ -15,13 +15,13 @@ import _bootstrap # Projektordner (config.py, Listen) vor allen anderen Modulen
import config import config
HOST = "http://127.0.0.1:8188" HOST = "http://127.0.0.1:8188"
OUT_DIR = os.path.join(config.OUTPUT_DIR, "audio") OUT_DIR = os.path.join(config.OUTPUT_DIR, getattr(config, "AUDIO_SUBDIR", "audio"))
CLIP_NAME = "t5gemma_b_b_ul2.safetensors" CLIP_NAME = "t5gemma_b_b_ul2.safetensors"
import importlib import importlib
# Die Clip-Liste dieses Spiels: (name, prompt, seconds, negative) — siehe audio_life.py # Die Clip-Liste des Projekts: (name, prompt, seconds, negative) — config.AUDIO_MODULE
CLIPS = importlib.import_module(getattr(config, "AUDIO_MODULE", "audio_life")).CLIPS CLIPS = importlib.import_module(getattr(config, "AUDIO_MODULE", "audio_life")).CLIPS

181
generate_mesh.py Normal file
View File

@@ -0,0 +1,181 @@
"""Image to 3D model, through the same local ComfyUI the sprites come from.
Usage:
python generate_mesh.py <image> [name] [--octree=256]
<image> a PNG on disk - a clean render of one object, ideally on a plain
or transparent background. What the sprite generator already
produces, in other words.
[name] what the GLB is called. Defaults to the image's own stem.
Hunyuan3D v2 turns one picture into geometry: image -> CLIP vision -> a
diffusion pass in a 3D latent -> voxels -> a mesh, saved as a GLB. It produces
*shape only*. There is no texture, no material and no vertex colour, which
matters when deciding what to do with the result - see the note in the
TinyWorld GLB loader. Results land in the project's OUTPUT_DIR.
The workflow is workflows/Image to 3D - Hunyuan3D.json in the API format the
rest of this tool uses. Written out from the UI export in the same folder,
because ComfyUI's /prompt endpoint takes the API format and the editor saves
the other one.
"""
import json
import os
import random
import sys
import time
import urllib.parse
import urllib.request
import uuid
import _bootstrap # Projektordner (config.py, Listen) vor allen anderen Modulen
import config
CHECKPOINT = "hunyuan3d-dit-v2-0-fp16.safetensors"
WORKFLOW = "Image to 3D - Hunyuan3D.json"
def post_json(url, payload):
data = json.dumps(payload).encode("utf-8")
req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req) as resp:
return json.loads(resp.read().decode("utf-8"))
def get_json(url):
with urllib.request.urlopen(url) as resp:
return json.loads(resp.read().decode("utf-8"))
def upload_image(path):
"""Puts the file in ComfyUI's input folder and answers with its name there.
Multipart by hand: this tool has no third-party dependencies and one
boundary is cheaper than adding requests to the setup instructions.
"""
name = os.path.basename(path)
boundary = uuid.uuid4().hex
with open(path, "rb") as handle:
blob = handle.read()
parts = []
parts.append(f"--{boundary}\r\n".encode())
parts.append(
f'Content-Disposition: form-data; name="image"; filename="{name}"\r\n'.encode())
parts.append(b"Content-Type: image/png\r\n\r\n")
parts.append(blob)
parts.append(f"\r\n--{boundary}\r\n".encode())
parts.append(b'Content-Disposition: form-data; name="overwrite"\r\n\r\n')
parts.append(b"true")
parts.append(f"\r\n--{boundary}--\r\n".encode())
body = b"".join(parts)
req = urllib.request.Request(
f"{config.HOST}/upload/image", data=body,
headers={"Content-Type": f"multipart/form-data; boundary={boundary}"})
with urllib.request.urlopen(req) as resp:
answer = json.loads(resp.read().decode("utf-8"))
return answer.get("name", name)
def build(image_name, name, seed, octree):
path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "workflows", WORKFLOW)
with open(path, "r", encoding="utf-8") as handle:
text = handle.read()
text = text.replace("{{CHECKPOINT}}", CHECKPOINT)
text = text.replace("{{IMAGE}}", image_name.replace("\\", "\\\\").replace('"', '\\"'))
text = text.replace("{{NAME}}", name)
text = text.replace("{{SEED}}", str(seed))
text = text.replace("{{OCTREE}}", str(octree))
return json.loads(text)
def queue_and_wait(name, workflow, timeout=1200):
result = post_json(f"{config.HOST}/prompt", {"prompt": workflow})
if "error" in result:
print(f"[{name}] SUBMIT ERROR: {json.dumps(result)[:800]}")
return []
pid = result["prompt_id"]
print(f"[{name}] queued as {pid}")
start = time.time()
while time.time() - start < timeout:
history = get_json(f"{config.HOST}/history/{pid}")
if pid in history:
entry = history[pid]
status = entry.get("status", {})
files = []
for node_out in entry.get("outputs", {}).values():
# SaveGLB reports under "3d" on some builds and "result" on
# others; both carry the same {filename, subfolder, type}.
for key in ("3d", "result", "images", "gltf"):
for item in node_out.get(key, []) or []:
if isinstance(item, dict) and "filename" in item:
files.append(item)
if files:
return files
if status.get("status_str") == "error":
for kind, data in status.get("messages", []):
if kind == "execution_error":
print(f"[{name}] ERROR in {data.get('node_type')}: "
f"{data.get('exception_message')}")
return []
print(f"[{name}] ERROR: {json.dumps(status)[:600]}")
return []
if status.get("completed"):
print(f"[{name}] finished with nothing to download: "
f"{json.dumps(entry)[:600]}")
return []
time.sleep(3)
print(f"[{name}] TIMEOUT")
return []
def download(info, dest_dir):
query = urllib.parse.urlencode({
"filename": info["filename"],
"subfolder": info.get("subfolder", ""),
"type": info.get("type", "output"),
})
with urllib.request.urlopen(f"{config.HOST}/view?{query}") as resp:
blob = resp.read()
dest = os.path.join(dest_dir, os.path.basename(info["filename"]))
with open(dest, "wb") as handle:
handle.write(blob)
return dest
def main():
args = [a for a in sys.argv[1:] if not a.startswith("--")]
flags = [a for a in sys.argv[1:] if a.startswith("--")]
if not args:
print(__doc__)
return 1
source = args[0]
if not os.path.isfile(source):
print(f"no such image: {source}")
return 1
name = args[1] if len(args) > 1 else os.path.splitext(os.path.basename(source))[0]
octree = 256
for flag in flags:
if flag.startswith("--octree="):
octree = int(flag.split("=", 1)[1])
os.makedirs(config.OUTPUT_DIR, exist_ok=True)
uploaded = upload_image(source)
print(f"[{name}] uploaded {uploaded}")
workflow = build(uploaded, name, random.randint(1, 2 ** 32 - 1), octree)
files = queue_and_wait(name, workflow)
if not files:
print(f"[{name}] FAILED")
return 1
for info in files:
print(f"[{name}] saved -> {download(info, config.OUTPUT_DIR)}")
return 0
if __name__ == "__main__":
raise SystemExit(main())

68
largest.py Normal file
View File

@@ -0,0 +1,68 @@
"""Keeps the biggest thing in a cutout and throws the rest away.
The background remover leaves specks: a corner of the object that got separated
from it, a rim of the black backdrop that survived. They are invisible against a
dark game screen and they are also opaque, so trim.py measures the bounding box
of the whole scatter and the object ends up somewhere off-centre inside a canvas
mostly made of nothing. That is what happened to the book: the sheet drew
centred and the painted book sat in the right-hand third of it.
Run after trim.py:
py -3.12 largest.py tw_book_sheet
"""
import os
import sys
import _bootstrap # Projektordner (config.py, Listen) vor allen anderen Modulen
import config
import numpy as np
from PIL import Image
from scipy import ndimage
MIN_ALPHA = 40
def clean(path: str, out: str) -> None:
image = Image.open(path).convert("RGBA")
pixels = np.array(image)
solid = pixels[:, :, 3] > MIN_ALPHA
# Eight-connected, so a diagonal thread still counts as joined - a hinge or
# a strap one pixel wide is part of the object, not a speck.
labels, count = ndimage.label(solid, structure=np.ones((3, 3), dtype=int))
if count == 0:
print(f" {path}: nothing opaque")
return
sizes = ndimage.sum(solid, labels, range(1, count + 1))
keep = int(np.argmax(sizes)) + 1
biggest = labels == keep
dropped = int(solid.sum() - biggest.sum())
pixels[~biggest] = 0
rows = np.any(biggest, axis=1)
cols = np.any(biggest, axis=0)
top, bottom = np.where(rows)[0][[0, -1]]
left, right = np.where(cols)[0][[0, -1]]
cropped = Image.fromarray(pixels).crop((left, top, right + 1, bottom + 1))
cropped.save(out)
print(f" {path}: {count} pieces, kept the largest, dropped {dropped} px "
f"-> {cropped.width}x{cropped.height}")
def main() -> int:
if len(sys.argv) < 2:
print(__doc__)
return 1
for name in sys.argv[1:]:
path = os.path.join(config.OUTPUT_DIR, f"{name}_trimmed.png")
clean(path, path)
return 0
if __name__ == "__main__":
raise SystemExit(main())

95
level.py Normal file
View File

@@ -0,0 +1,95 @@
"""Set a generated clip to a known peak, so 'too loud' is a number.
The audio counterpart of trim.py. Stable Audio renders whatever level the prompt
suggests to it, and the prompt is about the *sound* rather than about the level:
asking for "a big bright water impact" gave a clip pinned at 0 dB with a hard
transient, and asking for the same moment gently gave three rolls in a row at
around -35 dB mean, quieter than the click on a menu button. Neither is a thing
to fix by re-rolling, because neither is what the prompt is for.
So the prompt decides what it sounds like and this decides how loud it is. One
gain applied to the whole clip - no compression, no limiting, nothing that
changes the shape of it, because the shape is what came out of the model and is
the part worth keeping.
py level.py aq_sfx_intro_hit # newest roll, to the default peak
py level.py aq_sfx_intro_hit -6 # to -6 dB instead
py level.py assets/sounds/aq_sfx_won.mp3 -3
Writes `<name>_levelled.mp3` beside the source. Copy into the game by hand -
nothing here touches assets/.
"""
import glob
import os
import re
import subprocess
import sys
import _bootstrap # Projektordner (config.py, Listen) vor allen anderen Modulen
import config
OUT = os.path.join(config.OUTPUT_DIR, getattr(config, "AUDIO_SUBDIR", "audio"))
# Where a one-off sound sits. Not 0: a clip that touches the ceiling has nothing
# left for the mixer, and everything in this game can play over something else.
DEFAULT_PEAK = -3.0
def measured(path):
"""The clip's peak and mean, in dB, as ffmpeg reports them."""
run = subprocess.run(
["ffmpeg", "-hide_banner", "-i", path, "-af", "volumedetect", "-f", "null", "-"],
capture_output=True, text=True, check=False)
def find(what):
hit = re.search(rf"{what}:\s*(-?[\d.]+) dB", run.stderr)
return float(hit.group(1)) if hit else None
return find("max_volume"), find("mean_volume")
def level(path, peak):
top, mean = measured(path)
if top is None:
print(f" {os.path.basename(path)}: could not be measured, skipped")
return
gain = peak - top
stem = re.sub(r"_\d+$", "", os.path.splitext(os.path.basename(path))[0])
dest = os.path.join(os.path.dirname(path), f"{stem}_levelled.mp3")
subprocess.run(
["ffmpeg", "-hide_banner", "-loglevel", "error", "-y", "-i", path,
"-af", f"volume={gain:.2f}dB", "-codec:a", "libmp3lame", "-q:a", "2", dest],
check=True)
after, afterMean = measured(dest)
print(f" {stem:24s} peak {top:6.1f} -> {after:6.1f} dB "
f"mean {mean:6.1f} -> {afterMean:6.1f} dB ({gain:+.1f} dB)")
def main():
if len(sys.argv) < 2:
print(__doc__)
return 1
name = sys.argv[1]
peak = float(sys.argv[2]) if len(sys.argv) > 2 else DEFAULT_PEAK
if os.path.isfile(name):
level(name, peak)
return 0
# A name rather than a path: the newest roll of it in output/audio.
found = sorted(glob.glob(os.path.join(OUT, f"{name}*.mp3")))
found = [f for f in found if not f.endswith("_levelled.mp3")]
if not found:
print(f"no clip found for {name} in {OUT}")
return 1
level(found[-1], peak)
return 0
if __name__ == "__main__":
raise SystemExit(main())

273
mesh_prep.py Normal file
View File

@@ -0,0 +1,273 @@
"""Turns a generated GLB into something this game can actually draw.
py -3.12 mesh_prep.py <in.glb> <out.glb> [--faces=2500] [--height=3.6]
[--paint=balloon] [--flame]
Hunyuan3D gives shape and nothing else: a quarter of a million triangles, no
normals, no colours, no material. This game draws flat-faceted, brightly
coloured, low-poly meshes at two hundred triangles apiece. So the raw output
needs three things doing to it before it is a prop:
* **Fewer triangles.** By vertex clustering - snap every vertex to a grid,
merge, throw away the triangles that collapse. Cheap, needs nothing but
numpy, and its failure mode is *more* faceted, which is this game's look.
* **Flat normals.** Every triangle gets its own three vertices and its own
face normal, exactly as MeshBuilder does for the hand-built props.
* **Colour.** The one thing a generated mesh cannot have and the one thing
this game's art is made of. Painted here from the shape itself: see
`paint_balloon` - height says basket, ropes or envelope, and the angle round
the middle says which gore.
The result is a GLB with POSITION, NORMAL and COLOR_0, which is what
Engine/Renderer/GltfMesh.cpp reads.
"""
import math
import sys
import numpy as np
import trimesh
# The palette the hand-built balloon uses (Engine/Renderer/MeshPrimitives.cpp),
# so a generated one sits beside the rest of the village rather than beside
# nothing.
CLOTH = (0.86, 0.32, 0.26)
CLOTH_ALT = (0.94, 0.82, 0.42)
WICKER = (0.62, 0.45, 0.24)
ROPE = (0.74, 0.68, 0.52)
FLAME = (0.96, 0.55, 0.15)
FLAME_HEART = (1.00, 0.90, 0.52)
WALL = (0.90, 0.85, 0.72)
ROOF = (0.72, 0.26, 0.22)
THATCH = (0.86, 0.72, 0.34)
STONE = (0.55, 0.55, 0.58)
WOOD = (0.55, 0.38, 0.24)
SAIL = (0.86, 0.82, 0.70)
def cluster(vertices, faces, cells):
"""Vertex-cluster decimation on a `cells`-per-side grid."""
low = vertices.min(axis=0)
high = vertices.max(axis=0)
span = np.maximum(high - low, 1e-6)
keys = np.floor((vertices - low) / span * (cells - 1) + 0.5).astype(np.int64)
flat = (keys[:, 0] * cells + keys[:, 1]) * cells + keys[:, 2]
unique, inverse = np.unique(flat, return_inverse=True)
# Each cell keeps the average of what landed in it, which rounds corners
# far less than keeping the first vertex would.
merged = np.zeros((len(unique), 3), dtype=np.float64)
counts = np.zeros(len(unique), dtype=np.int64)
np.add.at(merged, inverse, vertices)
np.add.at(counts, inverse, 1)
merged /= counts[:, None]
remapped = inverse[faces]
# Anything that collapsed to a line or a point is gone.
keep = ((remapped[:, 0] != remapped[:, 1]) &
(remapped[:, 1] != remapped[:, 2]) &
(remapped[:, 2] != remapped[:, 0]))
return merged, remapped[keep]
def decimate_to(mesh, target_faces):
"""Clusters at whatever grid gets nearest to `target_faces` from below."""
vertices = np.asarray(mesh.vertices, dtype=np.float64)
faces = np.asarray(mesh.faces, dtype=np.int64)
best = (vertices, faces)
for cells in range(8, 129, 2):
merged, kept = cluster(vertices, faces, cells)
if len(kept) == 0:
continue
best = (merged, kept)
if len(kept) >= target_faces:
break
return best
def paint_balloon(points):
"""A colour per vertex, from where the vertex is on the balloon.
The shape is known even though the mesh is not: a basket at the bottom, a
thin waist of ropes and burner above it, and an envelope over that. Height
picks the part; the angle round the middle cuts the envelope into gores.
"""
low = points[:, 1].min()
high = points[:, 1].max()
t = (points[:, 1] - low) / max(high - low, 1e-6)
angle = np.arctan2(points[:, 2], points[:, 0])
gore = np.floor((angle + math.pi) / (2.0 * math.pi) * 8.0).astype(np.int64) % 2
colours = np.zeros((len(points), 3), dtype=np.float32)
colours[:] = CLOTH
colours[gore == 1] = CLOTH_ALT
colours[t < 0.42] = ROPE
colours[t < 0.30] = WICKER
return colours
def paint_building(points, faces, roof, wall, base=STONE, sails=None, roof_at=1.01,
slope=0.25):
"""A colour per *face*, from which way the face points.
Height alone is the obvious rule and it is wrong on the first building that
has a tower: everything above the eaves goes roof-coloured, including the
tower's walls. What actually separates a roof from a wall is that one is
sloped and the other is upright, so that is what this asks - the normal
decides the material and the height only breaks ties.
`sails` paints whatever sticks out sideways high up, which is a windmill's
arms and nothing else on a building.
"""
corners = points[faces]
normals = np.cross(corners[:, 1] - corners[:, 0], corners[:, 2] - corners[:, 0])
normals /= np.maximum(np.linalg.norm(normals, axis=1, keepdims=True), 1e-9)
middles = corners.mean(axis=1)
low = points[:, 1].min()
high = points[:, 1].max()
t = (middles[:, 1] - low) / max(high - low, 1e-6)
# The absolute value, not the signed one.
#
# A generated mesh has no consistent winding - surface net gives whichever
# way round each quad came out - so "points upwards" is a coin toss and
# painting on it speckled the walls with roof. What is actually being
# asked is "is this face flat or upright", and that question has the same
# answer either way round.
colours = np.tile(np.asarray(wall, dtype=np.float32), (len(faces), 1))
# Two ways to be a roof, because one is not enough.
#
# The slope test is the honest one and it is not sufficient: these gables
# are steep enough that their normals barely tilt off the horizontal, so
# anything strict enough to exclude a wall also excludes the roof. `roof_at`
# is the blunt half - above this height it is roof whatever it points at -
# and it is set per building from what the thing actually looks like.
colours[(np.abs(normals[:, 1]) > slope) & (t > 0.34)] = roof
colours[t > roof_at] = roof
colours[t < 0.09] = base
if sails is not None:
radius = np.linalg.norm(middles[:, [0, 2]], axis=1)
reach = np.linalg.norm(points[:, [0, 2]], axis=1).max()
colours[(radius > reach * 0.56) & (t > 0.42)] = sails
return colours
def flame(at_y, radius, height, colour, segments=7):
"""A cone, as a mesh, for the burner under the mouth."""
cone = trimesh.creation.cone(radius=radius, height=height, sections=segments)
cone.apply_translation((0.0, 0.0, 0.0))
# trimesh cones stand along +Z; this game is Y-up.
cone.apply_transform(trimesh.transformations.rotation_matrix(-math.pi / 2.0, (1, 0, 0)))
cone.apply_translation((0.0, at_y, 0.0))
return cone, np.tile(np.asarray(colour, dtype=np.float32), (len(cone.vertices), 1))
def main():
args = [a for a in sys.argv[1:] if not a.startswith("--")]
flags = {a.split("=", 1)[0]: (a.split("=", 1)[1] if "=" in a else True)
for a in sys.argv[1:] if a.startswith("--")}
if len(args) < 2:
print(__doc__)
return 1
target = int(flags.get("--faces", 2500))
height = float(flags.get("--height", 3.6))
paint = flags.get("--paint", "balloon")
mesh = trimesh.load(args[0], force="mesh")
print(f"in : {len(mesh.vertices)} vertices, {len(mesh.faces)} faces")
points, faces = decimate_to(mesh, target)
print(f"cut : {len(points)} vertices, {len(faces)} faces")
# Winding, made consistent and turned outwards.
#
# Surface net hands back each quad in whichever order it came out, so half
# the face normals point into the model. Nothing notices until the mesh is
# flat-shaded and lit: then half the faces are lit as though the sun were
# underground, and the prop reads as a blotchy mess whatever it is painted.
# trimesh knows how to do this; doing it here means the game's loader never
# has to care.
fixed = trimesh.Trimesh(vertices=points, faces=faces, process=False)
trimesh.repair.fix_winding(fixed)
trimesh.repair.fix_inversion(fixed, multibody=True)
points = np.asarray(fixed.vertices, dtype=np.float64)
faces = np.asarray(fixed.faces, dtype=np.int64)
# Stood on the ground and scaled to the size the rest of the village is
# built at. The generator works in a unit box; this game works in metres.
points = points - np.array([
(points[:, 0].min() + points[:, 0].max()) * 0.5,
points[:, 1].min(),
(points[:, 2].min() + points[:, 2].max()) * 0.5,
])
scale = height / max(points[:, 1].max(), 1e-6)
points *= scale
# Two kinds of painter. The balloon's is per vertex, because a gore is a
# wedge of the shape rather than a set of faces; a building's is per face,
# because a roof is a face that points upwards.
face_colours = None
colours = None
if paint == "balloon":
colours = paint_balloon(points)
elif paint == "hall":
# The eaves sit low on a hall this steep: nearly half of it is roof.
face_colours = paint_building(points, faces, roof=THATCH, wall=WALL, roof_at=0.46)
elif paint == "mill":
# Height only, and high. A mill tower tapers, so its walls are sloped
# too and the slope test cannot tell them from the cap - it painted two
# thirds of the tower red. The cap is simply the top fifth.
face_colours = paint_building(points, faces, roof=ROOF, wall=WALL, sails=WOOD,
roof_at=0.79, slope=2.0)
else:
colours = np.tile(np.asarray(WALL, dtype=np.float32), (len(points), 1))
if flags.get("--flame") and colours is not None:
# The burner, in finished units - this runs after the scaling above, so
# a flame written as "a tenth of the balloon" stays a tenth of it
# whatever the model came out as. It was written before the scaling
# once, in generator units multiplied by the scale, and produced a cone
# taller than the envelope.
tall = points[:, 1].max()
mouth = tall * 0.37
for radius, length, colour in ((tall * 0.080, tall * 0.17, FLAME),
(tall * 0.045, tall * 0.11, FLAME_HEART)):
cone, cone_colours = flame(mouth, radius, length, colour)
offset = len(points)
points = np.vstack([points, np.asarray(cone.vertices)])
colours = np.vstack([colours, cone_colours])
faces = np.vstack([faces, np.asarray(cone.faces) + offset])
print(f"lit : {len(points)} vertices, {len(faces)} faces")
# Flat shading: one triangle, three vertices of its own, one normal.
corners = points[faces]
normals = np.cross(corners[:, 1] - corners[:, 0], corners[:, 2] - corners[:, 0])
lengths = np.linalg.norm(normals, axis=1, keepdims=True)
normals = np.divide(normals, np.maximum(lengths, 1e-9))
flat_points = corners.reshape(-1, 3).astype(np.float32)
flat_normals = np.repeat(normals, 3, axis=0).astype(np.float32)
flat_colours = (np.repeat(face_colours, 3, axis=0) if face_colours is not None
else colours[faces].reshape(-1, 3)).astype(np.float32)
flat_faces = np.arange(len(flat_points), dtype=np.uint32).reshape(-1, 3)
out = trimesh.Trimesh(vertices=flat_points, faces=flat_faces, process=False)
out.visual = trimesh.visual.ColorVisuals(
mesh=out, vertex_colors=(np.clip(flat_colours, 0.0, 1.0) * 255).astype(np.uint8))
out.vertex_normals = flat_normals
with open(args[1], "wb") as handle:
handle.write(trimesh.exchange.gltf.export_glb(out, include_normals=True))
print(f"out : {len(flat_points)} vertices, {len(flat_faces)} faces -> {args[1]}")
return 0
if __name__ == "__main__":
raise SystemExit(main())

72
trim.py Normal file
View File

@@ -0,0 +1,72 @@
"""Trim the transparent margin off a cutout, so the asset is the object.
The generator always renders into a 1024x1024 frame and `cutout.py` only
removes the backdrop - it leaves the object floating in a square with a wide
transparent border. Every asset in `assets/ui/` was cropped to its object by
hand afterwards, which is why they have aspect ratios like 939x454.
Doing it by hand is fine once. Doing it for a plate whose aspect ratio the
layout code then has to match is a good way to get a frame that is two pixels
lopsided, so this does it from the alpha channel instead.
py -3.12 trim.py tw_hud_plate one cutout, by name
py -3.12 trim.py every *_cutout_*.png in output/
Writes `<name>_trimmed.png` beside the cutout. Copy into the game by hand -
nothing here touches assets/.
"""
import glob
import os
import sys
from PIL import Image
import _bootstrap # Projektordner (config.py, Listen) vor allen anderen Modulen
import config
OUT = config.OUTPUT_DIR
# Alpha at or below this counts as background. Not zero: the matting model
# leaves a fringe of nearly-transparent pixels around the object, and trimming
# to alpha > 0 keeps a halo several pixels wide.
THRESHOLD = 8
def trim(path):
image = Image.open(path).convert("RGBA")
alpha = image.getchannel("A").point(lambda v: 255 if v > THRESHOLD else 0)
box = alpha.getbbox()
if box is None:
print(f" {os.path.basename(path)}: fully transparent, skipped")
return
cropped = image.crop(box)
stem = os.path.basename(path).split("_cutout_")[0]
dest = os.path.join(OUT, f"{stem}_trimmed.png")
cropped.save(dest)
width, height = cropped.size
print(f" {stem:20s} {image.size[0]}x{image.size[1]} -> {width}x{height}"
f" ({width / height:.2f}:1)")
def main():
if len(sys.argv) > 1:
targets = []
for name in sys.argv[1:]:
found = sorted(glob.glob(os.path.join(OUT, f"{name}_cutout_*.png")))
if not found:
print(f"no cutout found for {name}")
return 1
targets.append(found[-1])
else:
targets = sorted(glob.glob(os.path.join(OUT, "*_cutout_*.png")))
for path in targets:
trim(path)
return 0
if __name__ == "__main__":
raise SystemExit(main())

73
uncut.py Normal file
View File

@@ -0,0 +1,73 @@
"""Cuts a black backdrop out of a texture that was never background-removed.
Some art in assets/ui went in straight from the generator with its backdrop
still on. On a panel drawn over the world that shows as a hard black rectangle
round the painting - which is what map_sheet.png was doing: nought per cent
transparent, forty-two per cent opaque black.
The backdrop is the dark region *connected to the border*, not every dark pixel:
a compass rose has black in it and a shadow under a torn edge is meant to be
there. Flood from the edge and take only what it reaches.
py -3.12 uncut.py ../assets/ui/map_sheet.png
"""
import sys
import numpy as np
from PIL import Image
from scipy import ndimage
# Dark enough to be backdrop rather than ink. The paintings here are lit
# objects on black; anything this dark is not part of one.
DARK = 42
# The edge between backdrop and painting is a gradient a few pixels wide.
# Feathering it stops the cut showing as a hard fringe.
FEATHER = 2
def cut(path: str) -> None:
image = Image.open(path).convert("RGBA")
pixels = np.array(image)
height, width = pixels.shape[:2]
dark = pixels[:, :, :3].mean(axis=2) < DARK
labels, count = ndimage.label(dark)
if count == 0:
print(f" {path}: nothing dark to cut")
return
# Every component touching any edge of the image.
border = set(labels[0, :]) | set(labels[-1, :]) | set(labels[:, 0]) | set(labels[:, -1])
border.discard(0)
if not border:
print(f" {path}: no dark region reaches the edge - nothing to cut")
return
backdrop = np.isin(labels, list(border))
alpha = pixels[:, :, 3].astype(np.float32)
alpha[backdrop] = 0.0
# Soften the boundary: whatever is left near the cut loses some alpha too.
near = ndimage.binary_dilation(backdrop, iterations=FEATHER) & ~backdrop
alpha[near] *= 0.5
pixels[:, :, 3] = np.clip(alpha, 0, 255).astype(np.uint8)
Image.fromarray(pixels).save(path)
print(f" {path}: cut {backdrop.mean() * 100:.1f}% to transparent")
def main() -> int:
if len(sys.argv) < 2:
print(__doc__)
return 1
for path in sys.argv[1:]:
cut(path)
return 0
if __name__ == "__main__":
raise SystemExit(main())