Files
mortal-maze-the-game/tools/generate_band_art.py
T

387 lines
20 KiB
Python

"""Genera los cuatro atlas SVG y SpriteFrames a partir del pixel art original.
Uso: python tools/generate_band_art.py (requiere Pillow solo para regenerar arte).
El juego consume los SVG/.tres ya versionados; nunca ejecuta este programa.
Diego conserva exactamente sus celdas originales salvo la caida ofensiva.
Las demas apariencias reutilizan las poses comunes y el mismo punetazo.
"""
from __future__ import annotations
from collections import defaultdict
from pathlib import Path
import math
import re
import xml.etree.ElementTree as ET
from PIL import Image, ImageDraw
ROOT = Path(__file__).resolve().parents[1]
SOURCE = ROOT / "assets/characters/ankarde/player_pixel.svg"
DESTINATION = ROOT / "assets/characters/band"
ROLES = ("guitarist", "drummer", "bassist", "singer")
OUTLINE = "#161723"
SKIN = "#ecb78b"
SKIN_LIGHT = "#ffdab0"
SKIN_DARK = "#b57964"
SHIRT = "#252b39"
SHIRT_LIGHT = "#3e475c"
HAIR = ("#30242a", "#543933", "#805345")
CELL = 64
def rgba(color: str) -> tuple[int, int, int, int]:
return tuple(bytes.fromhex(color[1:])) + (255,)
def read_source() -> dict[str, Image.Image]:
"""Reconstruye las celdas originales sin rasterizadores ni dependencias de SVG."""
result = {}
for group in ET.parse(SOURCE).getroot().findall("{*}g"):
image = Image.new("RGBA", (CELL, CELL))
draw = ImageDraw.Draw(image)
for path in group:
if not path.tag.endswith("path"):
continue
commands = path.attrib["d"]
pattern = r"M(-?\d+) (-?\d+)h(\d+)v(\d+)h-\d+z"
if re.sub(pattern, "", commands):
raise ValueError("El atlas original ya no usa rectangulos enteros: " + group.attrib["id"])
for x, y, width, height in re.findall(pattern, commands):
x, y, width, height = map(int, (x, y, width, height))
draw.rectangle((x, y, x + width - 1, y + height - 1), fill=path.attrib["fill"])
result[group.attrib["id"]] = image
return result
def appearance(source: Image.Image, role: str, pose_name: str) -> Image.Image:
"""Cambia pelo/ropa sin alterar la trayectoria de brazos del punetazo comun."""
if role == "guitarist":
return source.copy()
image = source.copy()
pixels = image.load()
hair_colors = tuple(rgba(color) for color in HAIR)
hair_points = [(x, y) for y in range(35) for x in range(CELL) if pixels[x, y] in hair_colors]
top = min(y for _, y in hair_points) - 1
left = min(x for x, _ in hair_points)
right = max(x for x, _ in hair_points)
new_hair = ("#78532b", "#d5a442", "#ffe07c") if role == "singer" else ("#10121a", "#20212c", "#3f4353")
palette = dict(zip(hair_colors, map(rgba, new_hair)))
shirt_palette = {rgba(SHIRT): rgba(SKIN_DARK), rgba(SHIRT_LIGHT): rgba(SKIN), rgba("#667185"): rgba(SKIN_LIGHT)}
for y in range(CELL):
for x in range(CELL):
color = pixels[x, y]
if y < top + 30 and color in palette:
pixels[x, y] = palette[color]
# Las camisetas acaban a mitad del brazo: el antebrazo queda descubierto.
if role in ("singer", "bassist") and color in shirt_palette:
forearm = top + 31 <= y <= top + 41 and (x < 28 or x >= 40)
extended = pose_name.startswith("punch") and x >= 45 and top + 23 <= y <= top + 33
if forearm or extended:
pixels[x, y] = shirt_palette[color]
if color == rgba("#35576d"):
pixels[x, y] = rgba("#424b36" if role == "singer" else "#363849")
elif color == rgba("#60869c"):
pixels[x, y] = rgba("#7a8664" if role == "singer" else "#686b83")
draw = ImageDraw.Draw(image)
if role == "bassist":
# Rizos a ambos lados hasta los hombros, no solo un cambio de color de Diego.
for side, x in ((-1, left - 1), (1, right + 1)):
for index, y in enumerate(range(top + 6, top + 34, 5)):
cx = x + (index % 2) * side
draw.ellipse((cx - 3, y - 2, cx + 3, y + 3), fill="#10121a")
draw.line((cx - 1, y - 1, cx + 1, y - 1, cx + 1, y + 1), fill="#414454", width=1)
for index in range(5):
x = left + 3 + index * 3
y = top + 2 + index % 2
draw.rectangle((x, y, x + 2, y + 2), fill="#20212c")
draw.point((x, y), fill="#454957")
elif role == "drummer":
# Hebras rectas, negras y largas; el brillo no se convierte en rizos.
for x in (left + 1, left + 3):
for y in range(top + 10, top + 25):
if pixels[x, y] in tuple(map(rgba, new_hair)):
pixels[x, y] = rgba("#3b3e4b")
add_wristbands(image, top)
return image
def add_wristbands(image: Image.Image, head_top: int) -> None:
"""Localiza manos de las poses originales y coloca la munequera junto al punio."""
skin_colors = {rgba(SKIN), rgba(SKIN_LIGHT), rgba(SKIN_DARK)}
pending = {(x, y) for y in range(head_top + 23, min(head_top + 43, 48))
for x in range(CELL) if image.getpixel((x, y)) in skin_colors and (x < 29 or x > 39)}
draw = ImageDraw.Draw(image)
while pending:
start = pending.pop()
component, stack = [start], [start]
while stack:
x, y = stack.pop()
for point in ((x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)):
if point in pending:
pending.remove(point)
stack.append(point)
component.append(point)
if len(component) < 5:
continue
x0, x1 = min(x for x, _ in component), max(x for x, _ in component)
y0, y1 = min(y for _, y in component), max(y for _, y in component)
if x1 - x0 > 10 or y1 - y0 > 9:
continue
if x0 > 44 and y0 < 40:
draw.rectangle((x0 - 2, y0 - 1, x0, y1 + 1), fill="#10121a")
draw.point((x0 - 1, y0 + 1), fill="#a0a5b3")
else:
draw.rectangle((x0 - 1, y0 - 2, x1 + 1, y0), fill="#10121a")
draw.point((x0, y0 - 1), fill="#a0a5b3")
def limb(draw: ImageDraw.ImageDraw, points: list[tuple[int, int]], color: str, width: int = 6) -> None:
draw.line(points, fill=OUTLINE, width=width + 2)
draw.line(points, fill=color, width=width)
def arm(draw: ImageDraw.ImageDraw, points: list[tuple[int, int]], role: str) -> None:
shoulder, elbow, hand = points
limb(draw, points, SHIRT)
if role in ("singer", "bassist"):
limb(draw, [elbow, hand], SKIN, 5)
sleeve = ((shoulder[0] + elbow[0]) // 2, (shoulder[1] + elbow[1]) // 2)
draw.line([shoulder, sleeve], fill=SHIRT_LIGHT, width=4)
x, y = hand
if role == "drummer":
band = (round(elbow[0] * .22 + x * .78), round(elbow[1] * .22 + y * .78))
draw.rectangle((band[0] - 3, band[1] - 2, band[0] + 3, band[1] + 2), fill="#10121a")
draw.point((band[0] - 2, band[1] - 1), fill="#b7bfcb")
draw.rectangle((x - 3, y - 3, x + 3, y + 2), fill=OUTLINE)
draw.rectangle((x - 2, y - 2, x + 2, y + 1), fill=SKIN)
draw.line((x - 1, y - 2, x + 2, y - 2), fill=SKIN_LIGHT)
def posed_body(idle: Image.Image, role: str, *, shift=(0, 0), hip=44,
legs=None, arms=None) -> Image.Image:
"""Poses exclusivas de ataques; el cuerpo de colision no cambia de tamano."""
dx, dy = shift
image = Image.new("RGBA", (CELL, CELL))
draw = ImageDraw.Draw(image)
if legs is None:
legs = [[(27, hip), (26, 51), (27, 57)], [(38, hip), (40, 51), (41, 57)]]
shorts = "#424b36" if role == "singer" else "#363849"
for thigh, knee, ankle in legs:
limb(draw, [thigh, knee, ankle], SKIN, 6)
midpoint = ((thigh[0] + knee[0]) // 2, (thigh[1] + knee[1]) // 2)
draw.line([thigh, midpoint], fill=shorts, width=7)
x, y = ankle
draw.rectangle((x - 4, y - 2, x + 7, y + 3), fill=OUTLINE)
draw.rectangle((x - 2, y - 2, x + 3, y), fill=SHIRT_LIGHT)
draw.line((x - 3, y + 3, x + 7, y + 3), fill="#667185")
shoulder_y = 30 + dy
draw.polygon([(25 + dx, shoulder_y - 2), (39 + dx, shoulder_y - 2),
(42 + dx, hip - 1), (23 + dx, hip - 1)], fill=OUTLINE)
draw.polygon([(26 + dx, shoulder_y), (38 + dx, shoulder_y),
(40 + dx, hip - 3), (25 + dx, hip - 3)], fill=SHIRT)
draw.line((27 + dx, shoulder_y, 26 + dx, hip - 4), fill=SHIRT_LIGHT, width=2)
draw.rectangle((25 + dx, hip - 2, 40 + dx, hip + 2), fill=OUTLINE)
draw.rectangle((26 + dx, hip - 1, 39 + dx, hip + 1), fill=shorts)
draw.point((33 + dx, hip - 1), fill="#b4b6bd")
# Pequeno emblema metalero, dibujado en pixeles y sin fuentes externas.
cy = shoulder_y + 3
draw.rectangle((31 + dx, cy, 35 + dx, cy + 4), fill="#f6ead4")
draw.point((32 + dx, cy + 1), fill=OUTLINE)
draw.point((35 + dx, cy + 1), fill=OUTLINE)
draw.rectangle((32 + dx, cy + 5, 34 + dx, cy + 6), fill="#f6ead4")
head = idle.crop((0, 0, 64, 29))
image.alpha_composite(head, (dx, dy))
if arms is None:
arms = [[(24 + dx, shoulder_y), (22 + dx, shoulder_y + 8), (23 + dx, hip - 1)],
[(40 + dx, shoulder_y), (43 + dx, shoulder_y + 8), (43 + dx, hip - 1)]]
for points in arms:
arm(draw, points, role)
return image
def instrument(image: Image.Image, body: tuple[int, int], neck: tuple[int, int], *, bass=False) -> None:
"""Guitarra roja o bajo de cuatro cuerdas; geometria entera para conservar el pixel art."""
draw = ImageDraw.Draw(image)
bx, by = body
nx, ny = neck
length = math.hypot(nx - bx, ny - by)
ux, uy = (nx - bx) / length, (ny - by) / length
px, py = -uy, ux
def point(a, b):
return (round(bx + px * a + ux * b), round(by + py * a + uy * b))
shape = [(-8, -6), (-8, 2), (-3, 9), (1, 6), (7, 8), (6, -7), (2, -4), (-2, -8)]
if bass:
shape = [(-6, -7), (-8, -1), (-6, 6), (-2, 9), (2, 6), (6, 8), (7, -1), (4, -7)]
draw.polygon([point(a, b) for a, b in shape], fill=OUTLINE)
inner = [point(a * .78, b * .80) for a, b in shape]
draw.polygon(inner, fill="#635486" if bass else "#e54f64")
draw.line([point(0, -5), neck], fill=OUTLINE, width=6 if bass else 5)
draw.line([point(0, -4), neck], fill="#b59164", width=3)
draw.line([point(-1, -3), (nx - 1, ny)], fill="#efe0b2", width=1)
draw.line([point(1, -3), (nx + 1, ny)], fill="#f7ecc8", width=1)
draw.polygon([point(-3, length - 2), point(-3, length + 4), point(2, length + 5),
point(3, length - 2)], fill=OUTLINE)
draw.line([point(0, length - 1), point(0, length + 3)], fill="#f0cd7b", width=3)
for index in range(4 if bass else 3):
draw.line([point(-3, length - 1 + index), point(-5, length - 1 + index)], fill="#b5bfca", width=1)
draw.line([point(-4, -2), point(4, -2)], fill="#efe7df", width=2)
draw.point(point(4, -4), fill="#efc45e")
def special_pose(idle: Image.Image, role: str, phase: str, index: int) -> Image.Image:
"""Sacar instrumento, tocar/gritar y recogerlo conservan las fases comunes del especial."""
progress = (index + 1) / 3 if phase == "special_start" else (1 - (index + 1) / 3 if phase == "special_end" else 1)
beat = index % 2 if phase == "special" else 0
if role == "singer":
hand_y = round(42 - 17 * progress) + beat
image = posed_body(idle, role, arms=[[(24, 30), (19, 37), (20, 32 + beat)],
[(40, 30), (47, 35), (47, hand_y)]])
draw = ImageDraw.Draw(image)
draw.line([(48, hand_y + 3), (52, 48), (49, 56), (39, 58)], fill="#697080", width=1)
draw.line((48, hand_y + 2, 46, hand_y - 5), fill=OUTLINE, width=5)
draw.line((48, hand_y + 1, 46, hand_y - 5), fill="#9ea8b9", width=2)
draw.ellipse((42, hand_y - 10, 49, hand_y - 4), fill=OUTLINE)
draw.rectangle((44, hand_y - 9, 47, hand_y - 5), fill="#c6d1df")
draw.line((44, hand_y - 7, 47, hand_y - 7), fill="#697584")
if phase == "special":
draw.rectangle((37, 21, 40, 23 + beat), fill=OUTLINE)
draw.point((38, 23), fill="#e8868c")
return image
if role == "drummer":
left = (18, round(40 - 18 * progress) + beat * 12)
right = (48, round(40 - 6 * progress) - beat * 12)
image = posed_body(idle, role, arms=[[(24, 30), (18, 29), left], [(40, 30), (47, 29), right]])
draw = ImageDraw.Draw(image)
for hand, side in ((left, -1), (right, 1)):
tip = (hand[0] + side * 6, max(2, hand[1] - 16))
draw.line([hand, tip], fill=OUTLINE, width=3)
draw.line([hand, tip], fill="#e7bd76", width=1)
draw.point(tip, fill="#fff0bd")
return image
strum = (3, 2, 0, -1, -1, 0)[index] if phase == "special" else 0
image = posed_body(idle, role, arms=[[(24, 30), (25, 40), (30, 45 + strum)],
[(40, 30), (44, 35), (46, 30)]])
instrument(image, (29, 49), (55, round(33 - 12 * progress)), bass=True)
draw = ImageDraw.Draw(image)
draw.rectangle((28, 43 + strum, 33, 45 + strum), fill=SKIN_LIGHT)
draw.rectangle((44, 31, 47, 34), fill=SKIN)
return image
def pound_pose(idle: Image.Image, role: str, index: int, *, landing=False) -> Image.Image:
if role == "guitarist":
if landing:
image = posed_body(idle, role, shift=(-1, 4), hip=47,
legs=[[(26, 46), (22, 51), (20, 57)], [(37, 46), (40, 51), (42, 57)]],
arms=[[(23, 34), (29, 39), (38, 38)], [(39, 34), (43, 38), (44, 45)]])
instrument(image, (50 - index, 53 - max(index - 1, 0) * 5), (37, 26))
ImageDraw.Draw(image).rectangle((38, 36, 42, 39), fill=SKIN_LIGHT)
else:
image = posed_body(idle, role, arms=[[(24, 30), (24, 18), (40, 22)],
[(40, 30), (47, 30), (48, 21 + index * 3)]])
instrument(image, (51, 25 + index * 4), (47 - index * 3, 5 + index))
return image
if role == "singer":
if landing:
image = posed_body(idle, role, shift=(-4, 8 - (2 if index == 2 else 0)), hip=51,
legs=[[(24, 50), (19, 54), (17, 57)], [(35, 50), (39, 52), (36, 57)]],
arms=[[(20, 38), (17, 43), (24, 42)], [(36, 38), (44, 45), (48, 57 - index)]])
else:
image = posed_body(idle, role, hip=43,
legs=[[(27, 43), (22, 47), (25, 53)], [(38, 43), (43, 46), (46, 51)]],
arms=[[(24, 30), (18, 34), (22, 30)], [(40, 30), (45, 38), (47, 46 + index)]])
return image
if landing:
return posed_body(idle, role, shift=(-1, 11 - index // 2), hip=55,
legs=[[(27, 55), (35, 54), (39, 57)], [(38, 55), (49, 51), (52, 57)]],
arms=[[(23, 41), (20, 49), (24, 54)], [(39, 41), (45, 47), (44, 52)]])
return posed_body(idle, role, hip=43,
legs=[[(27, 43), (22, 42), (23, 51)], [(38, 43), (47, 42), (50, 51)]],
arms=[[(24, 30), (20, 36), (23, 41)], [(40, 30), (46, 36), (46, 41)]])
def svg_group(name: str, image: Image.Image, index: int) -> str:
"""Agrupa tramos horizontales por color para obtener SVG de texto compacto."""
paths = defaultdict(list)
for y in range(CELL):
x = 0
while x < CELL:
color = image.getpixel((x, y))
end = x + 1
while end < CELL and image.getpixel((end, y)) == color:
end += 1
if color[3]:
hex_color = "#%02x%02x%02x" % color[:3]
paths[hex_color].append(f"M{x} {y}h{end-x}v1h-{end-x}z")
x = end
result = [f'<g id="{name}" transform="translate({index%8*64} {index//8*64})">']
for color, runs in sorted(paths.items()):
result.append(f'<path fill="{color}" d="{"".join(runs)}"/>')
result.append("</g>")
return "\n".join(result)
def write_frames(role: str, names: list[str]) -> None:
"""Los tiempos y duraciones comunes son los mismos que en el atlas original."""
text = ['[gd_resource type="SpriteFrames" load_steps=42 format=3]', '',
f'[ext_resource type="Texture2D" path="res://assets/characters/band/{role}.svg" id="atlas"]', '']
for index, name in enumerate(names):
text += [f'[sub_resource type="AtlasTexture" id="{name}"]', 'atlas = ExtResource("atlas")',
f'region = Rect2({index%8*64}, {index//8*64}, 64, 64)', 'filter_clip = true', '']
animations = {
'fall': (7, True), 'ground_pound': (12, True), 'hurt': (12, False), 'idle': (5, True),
'jump': (9, False), 'land': (16, False), 'punch': (18, False), 'special': (12, True),
'special_end': (7, False), 'special_start': (9, False), 'walk': (10, True),
'pound_land': (12, False),
}
serialized = []
for animation, (speed, loop) in animations.items():
# Fer toca una nota por pulso; Player reinicia la pose, no un bucle visual.
if role == 'bassist' and animation == 'special':
loop = False
cells = [n for n in names if n.rsplit('_', 1)[0] == animation]
durations = [1.0, .75, 1.15, .8, 1.3] if animation == 'punch' else [1.0] * len(cells)
frames = ', '.join('{"duration": %s, "texture": SubResource("%s")}' % (duration, name)
for duration, name in zip(durations, cells))
serialized.append('{\n"frames": [' + frames + '],\n"loop": ' + str(loop).lower()
+ f',\n"name": &"{animation}",\n"speed": {speed}.0\n' + '}')
text += ['[resource]', 'animations = [' + ', '.join(serialized) + ']\n']
(ROOT/'player/characters/animations').mkdir(parents=True, exist_ok=True)
(ROOT/f'player/characters/animations/{role}_frames.tres').write_text('\n'.join(text), encoding='utf-8')
def main() -> None:
originals = read_source()
# Para Diego se conserva tambien el texto SVG de cada celda no modificada.
raw_groups = {name: match.group(0) for name in originals
if (match := re.search(r'<g id="' + re.escape(name) + r'".*?</g>', SOURCE.read_text(), re.S))}
DESTINATION.mkdir(parents=True, exist_ok=True)
for role in ROLES:
frames = {name: appearance(image, role, name) for name, image in originals.items()}
idle = frames['idle_0']
for index in range(2):
if role != 'drummer':
frames[f'ground_pound_{index}'] = pound_pose(idle, role, index)
for index in range(3):
frames[f'pound_land_{index}'] = frames[f'land_{index}'].copy() if role == 'drummer' else pound_pose(idle, role, index, landing=True)
if role != 'guitarist':
for phase, count in (('special_start', 3), ('special', 6), ('special_end', 2)):
for index in range(count):
frames[f'{phase}_{index}'] = special_pose(idle, role, phase, index)
output = ['<svg xmlns="http://www.w3.org/2000/svg" width="512" height="320" viewBox="0 0 512 320" shape-rendering="crispEdges">',
f'<title>{role}: band member animations</title>',
'<!-- Celdas de 64x64. Regenerar con tools/generate_band_art.py. -->']
for index, (name, image) in enumerate(frames.items()):
if role == 'guitarist' and name in originals and not name.startswith('ground_pound'):
output.append(raw_groups[name])
else:
output.append(svg_group(name, image, index))
output.append('</svg>\n')
(DESTINATION/f'{role}.svg').write_text('\n'.join(output), encoding='utf-8')
write_frames(role, list(frames))
print('Generados cuatro atlas y cuatro recursos SpriteFrames; no se ha ejecutado Godot.')
if __name__ == '__main__':
main()