the_goth_cardgame_collection/view/assets_manager.py

484 lines
20 KiB
Python

# -*- coding: utf-8 -*-
# view/assets_manager.py
from __future__ import annotations
import re
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont, ImageTk
from models.resource_manager import ResourceManager
from resources.code_res.game_constants import (
FONTS_REL_DIR,
FONT_COLOR_BODY_DEFAULT,
FONT_FILE_ALTERNATE,
FONT_FILE_PRIMARY,
FONT_FORCE_MIXED_CASE,
FONT_LETTER_SPACING_PX,
FONT_LINE_HEIGHT_FACTOR,
FONT_OUTLINE_COLOR,
FONT_OUTLINE_THICKNESS_PX,
FONT_SHADOW_COLOR,
FONT_SHADOW_ENABLED,
FONT_SHADOW_OFFSET_DEFAULT,
FONT_VERTICAL_OFFSET_PX,
OUTCOME_GIF_SIZE,
PLAYING_CARD_SIZE,
)
# Anteil der Ecke im hochauflösenden Quellbild (damit das komplette Eck-Ornament erfasst wird)
BOX_SOURCE_CORNER_RATIO = {
"box_big": 0.16,
"box_gold_small": 0.24,
"box_gold_double": 0.16,
"box_purple": 0.22,
"dropdown_box": 0.085,
}
# Ziel-Eckgröße im UI: skaliert relativ zur Boxgröße herunter und deckelt die maximale Rahmendicke!
BOX_TARGET_CORNER_SPEC = {
# box_key: (relativer_anteil_an_kleinerer_zielkante, min_px, max_px)
"box_big": (0.14, 18, 46),
"box_gold_small": (0.22, 14, 34),
"box_gold_double": (0.18, 12, 26),
"box_purple": (0.18, 14, 32),
"dropdown_box": (0.10, 10, 18), # Sehr feiner Rahmen (10..18px statt ~82px!)
}
_ALL_CAPS_WORD_RE = re.compile(r"\b[A-ZÄÖÜ]{4,}\b")
class AssetManager:
def __init__(self, root_dir: Path):
self.root_dir = root_dir
self.res = ResourceManager(root_dir)
# --- Hintergründe & Spieltische ---
self.raw_bg_horizontal = self._load_ui_flexible("bg_horizontal", "background_horizontal")
self.raw_bg_vertical = self._load_ui_flexible("bg_vertical", "background_vertical")
self.raw_bg = self.raw_bg_horizontal or self._load_ui_flexible("background", "background")
self.raw_title = self._load_ui_flexible("title", "title")
self.raw_general_table = self._load_ui_flexible("general_table", "general_table")
self.raw_poker_table = self._load_ui_flexible("poker_table", "poker_table")
# --- Neue Buttons (Default, Amethyst-Hover, Feuer-Highlight) ---
self.raw_btn_default = self._load_ui_flexible("btn_default", "button")
self.raw_btn_purple = self._load_ui_flexible("btn_purple", "button_highlighted_purple")
self.raw_btn_fire = self._load_ui_flexible("btn_fire", "button_highlighted_fire")
# Abwärtskompatible Aliase für bestehende Views:
self.raw_btn = self.raw_btn_fire or self.raw_btn_default
self.raw_btn_active = self.raw_btn_fire or self.raw_btn_purple
self.raw_sel = self.raw_btn_default
self.raw_sel_active = self.raw_btn_purple or self.raw_btn_default
# --- Transparente Zierrahmen (9-Slice) ---
self.raw_boxes: dict[str, Image.Image | None] = {
"box_big": self._load_ui_flexible("box_big", "box_big"),
"box_gold_small": self._load_ui_flexible("box_gold_small", "box_gold_smal", "box_gold_small"),
"box_gold_double": self._load_ui_flexible("box_gold_double", "box_gold_small_double"),
"box_purple": self._load_ui_flexible("box_purple", "box_small_purple"),
"dropdown_box": self._load_ui_flexible("dropdown_box", "dropdown_box"),
}
self.raw_chat_frame = self.raw_boxes["box_big"]
# --- Formular-Assets (Input & geteiltes Dropdown) ---
self.raw_input = self._load_ui_flexible("input_field", "input")
self.raw_dropdown_closed = self._load_ui_flexible("dropdown_closed", "dropdown_closed")
self.raw_dropdown_closed_btn = self._load_ui_flexible("dropdown_closed_btn", "dropdown_closed_button")
self.raw_dropdown_open = self._load_ui_flexible(
"dropdown_open", "dropdown_box_hightlighted", "dropdown_box_highlighted"
)
self.raw_dropdown_open_btn = self._load_ui_flexible(
"dropdown_open_btn", "dropdown_box_hightlighted_button", "dropdown_box_highlighted_button"
)
self.raw_dropdown_box = self.raw_boxes["dropdown_box"]
self.raw_dropdown_selection = self._load_ui_flexible("dropdown_selection", "dropdown_selection")
# --- Caches ---
self._tk_cache: dict = {}
self._pil_cache: dict = {}
self._font_cache: dict[tuple[bool, int], ImageFont.FreeTypeFont | ImageFont.ImageFont] = {}
@staticmethod
def _load_pil(path: Path | None) -> Image.Image | None:
if path and path.is_file():
try:
return Image.open(path).convert("RGBA")
except Exception:
return None
return None
def _load_ui_flexible(self, ui_key: str, *stem_fallbacks: str) -> Image.Image | None:
"""
Versucht zuerst den Pfad aus UI_IMAGES via ResourceManager zu laden und prüft
anschließend Fallback-Dateinamen mit .png / .jpg / .jpeg in resources/images/.
"""
try:
p = self.res.get_ui_image_path(ui_key)
pil = self._load_pil(p)
if pil is not None:
return pil
except Exception:
pass
img_dir = self.root_dir / "resources" / "images"
for stem in stem_fallbacks:
for ext in (".png", ".jpg", ".jpeg"):
cand = img_dir / f"{stem}{ext}"
if cand.is_file():
loaded = self._load_pil(cand)
if loaded is not None:
return loaded
return None
# ------------------------------------------------------------------
# FONT-LOADER & OLD-LONDON TEXT-RENDERER (PIL RGBA)
# ------------------------------------------------------------------
def get_pil_font(self, size_px: int, alternate: bool = False) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:
size_px = max(12, int(size_px))
key = (alternate, size_px)
if key not in self._font_cache:
fname = FONT_FILE_ALTERNATE if alternate else FONT_FILE_PRIMARY
fpath = self.root_dir / FONTS_REL_DIR / fname
if not fpath.is_file():
fpath = self.root_dir / FONTS_REL_DIR / FONT_FILE_PRIMARY
try:
self._font_cache[key] = ImageFont.truetype(str(fpath), size_px)
except Exception:
self._font_cache[key] = ImageFont.load_default()
return self._font_cache[key]
@staticmethod
def sanitize_goth_case(text: str) -> str:
"""Verhindert unlesbare Fraktur-Versalienketten (z.B. 'GOLD-POT' -> 'Gold-Pot'), lässt Kürzel wie 'XP'/'DE' stehen."""
if not text or not FONT_FORCE_MIXED_CASE:
return text
return _ALL_CAPS_WORD_RE.sub(lambda m: m.group(0).capitalize(), text)
def _measure_tracked_line(
self,
draw: ImageDraw.ImageDraw,
line: str,
font: ImageFont.FreeTypeFont | ImageFont.ImageFont,
letter_spacing: int,
) -> float:
if not line:
return 0.0
total = 0.0
for idx, ch in enumerate(line):
total += draw.textlength(ch, font=font)
if idx < len(line) - 1:
total += letter_spacing
return total
def _draw_tracked_line(
self,
draw: ImageDraw.ImageDraw,
x: float,
y: float,
line: str,
font: ImageFont.FreeTypeFont | ImageFont.ImageFont,
fill: str,
letter_spacing: int,
shadow_offset: tuple[int, int] | None,
outline_px: int,
):
cur_x = x
for ch in line:
if FONT_SHADOW_ENABLED and shadow_offset and (shadow_offset[0] or shadow_offset[1]):
draw.text(
(cur_x + shadow_offset[0], y + shadow_offset[1]),
ch,
font=font,
fill=FONT_SHADOW_COLOR,
)
if outline_px > 0:
draw.text(
(cur_x, y),
ch,
font=font,
fill=fill,
stroke_width=outline_px,
stroke_fill=FONT_OUTLINE_COLOR,
)
else:
draw.text((cur_x, y), ch, font=font, fill=fill)
cur_x += draw.textlength(ch, font=font) + letter_spacing
def render_goth_text_pil(
self,
text: str,
size_px: int,
color: str = FONT_COLOR_BODY_DEFAULT,
max_width: int | None = None,
align: str = "center",
shadow_offset: tuple[int, int] | None = FONT_SHADOW_OFFSET_DEFAULT,
outline_px: int = FONT_OUTLINE_THICKNESS_PX,
letter_spacing: int = FONT_LETTER_SPACING_PX,
alternate: bool = False,
) -> Image.Image:
"""
Rendert Old-London-Text als scharfes, transparentes RGBA-PIL-Bild ohne jegliches
Plattform-/Xft-Clipping an Ober- oder Unterlängen.
"""
clean_text = self.sanitize_goth_case(str(text or ""))
cache_key = (
"goth_txt_pil", clean_text, size_px, color, max_width,
align, shadow_offset, outline_px, letter_spacing, alternate
)
if cache_key in self._pil_cache:
return self._pil_cache[cache_key]
font = self.get_pil_font(size_px, alternate=alternate)
dummy = Image.new("RGBA", (8, 8), (0, 0, 0, 0))
d_draw = ImageDraw.Draw(dummy)
# Automatischer Zeilenumbruch bei max_width
raw_paragraphs = clean_text.split("\n")
lines: list[str] = []
for para in raw_paragraphs:
if not max_width or max_width <= 20 or not para.strip():
lines.append(para)
continue
words = para.split(" ")
cur = ""
for w in words:
cand = f"{cur} {w}".strip() if cur else w
if self._measure_tracked_line(d_draw, cand, font, letter_spacing) <= max_width or not cur:
cur = cand
else:
lines.append(cur)
cur = w
lines.append(cur)
if not lines:
lines = [""]
try:
ascent, descent = font.getmetrics() # type: ignore[attr-defined]
except Exception:
ascent, descent = size_px, max(6, size_px // 3)
base_line_h = max(size_px + 4, ascent + descent)
step_y = int(round(base_line_h * FONT_LINE_HEIGHT_FACTOR))
pad_x = max(6, outline_px * 2 + (abs(shadow_offset[0]) if shadow_offset else 0) + 4)
pad_top = max(6, outline_px * 2 + 4)
pad_bot = max(8, descent // 2 + outline_px * 2 + (abs(shadow_offset[1]) if shadow_offset else 0) + 6)
line_widths = [self._measure_tracked_line(d_draw, ln, font, letter_spacing) for ln in lines]
content_w = int(round(max(line_widths, default=1.0)))
img_w = max(4, content_w + pad_x * 2)
img_h = max(4, pad_top + base_line_h + max(0, len(lines) - 1) * step_y + pad_bot)
canvas_img = Image.new("RGBA", (img_w, img_h), (0, 0, 0, 0))
draw = ImageDraw.Draw(canvas_img)
for idx, (ln, lw) in enumerate(zip(lines, line_widths)):
if align == "left":
lx = float(pad_x)
elif align == "right":
lx = float(img_w - pad_x) - lw
else:
lx = (img_w - lw) / 2.0
ly = float(pad_top + idx * step_y + FONT_VERTICAL_OFFSET_PX)
self._draw_tracked_line(
draw, lx, ly, ln, font, color, letter_spacing, shadow_offset, outline_px
)
self._pil_cache[cache_key] = canvas_img
return canvas_img
def get_goth_text_photo(
self,
text: str,
size_px: int,
color: str = FONT_COLOR_BODY_DEFAULT,
max_width: int | None = None,
align: str = "center",
shadow_offset: tuple[int, int] | None = FONT_SHADOW_OFFSET_DEFAULT,
outline_px: int = FONT_OUTLINE_THICKNESS_PX,
letter_spacing: int = FONT_LETTER_SPACING_PX,
alternate: bool = False,
) -> ImageTk.PhotoImage:
tk_key = (
"goth_txt_tk", text, size_px, color, max_width,
align, shadow_offset, outline_px, letter_spacing, alternate
)
if tk_key not in self._tk_cache:
pil_img = self.render_goth_text_pil(
text=text,
size_px=size_px,
color=color,
max_width=max_width,
align=align,
shadow_offset=shadow_offset,
outline_px=outline_px,
letter_spacing=letter_spacing,
alternate=alternate,
)
self._tk_cache[tk_key] = ImageTk.PhotoImage(pil_img)
return self._tk_cache[tk_key]
# ------------------------------------------------------------------
# 9-SLICE RAHMEN-SCALER FÜR TRANSPARENTE BOXEN (box_*.png)
# ------------------------------------------------------------------
# ------------------------------------------------------------------
# 9-SLICE RAHMEN-SCALER FÜR TRANSPARENTE BOXEN (fein herunterskaliert!)
# ------------------------------------------------------------------
def get_9slice_pil(
self,
box_key: str,
target_size: tuple[int, int],
corner_ratio: float | None = None,
border_scale: float = 1.0,
) -> Image.Image | None:
"""
Skaliert einen hochauflösenden Zierrahmen per 9-Slice proportional zur Zielgröße
herunter, sodass Rahmen & Ecken fein bleiben statt klobig zu wirken.
"""
src = self.raw_boxes.get(box_key)
tw, th = max(16, int(target_size[0])), max(16, int(target_size[1]))
if src is None:
return None
src_ratio = corner_ratio if corner_ratio is not None else BOX_SOURCE_CORNER_RATIO.get(box_key, 0.16)
pil_key = ("9slice_pil", box_key, (tw, th), src_ratio, round(border_scale, 3))
if pil_key in self._pil_cache:
return self._pil_cache[pil_key]
sw, sh = src.size
# 1. Quell-Ausschnitt der Ecke im Originalbild (erfasst das volle Eck-Ornament)
sc = max(12, int(round(min(sw, sh) * src_ratio)))
# 2. Ziel-Größe der Ecke im UI relativ zur Boxgröße klein halten (herunterskalieren!)
rel_target, min_dc, max_dc = BOX_TARGET_CORNER_SPEC.get(box_key, (0.14, 12, 36))
scaled_dc = int(round(min(tw, th) * rel_target * border_scale))
dc = max(min_dc, min(max_dc, scaled_dc))
dc = min(dc, sc, tw // 2 - 1, th // 2 - 1)
if dc < 6:
out = src.resize((tw, th), Image.Resampling.LANCZOS)
self._pil_cache[pil_key] = out
return out
out = Image.new("RGBA", (tw, th), (0, 0, 0, 0))
# 4 Ecken sauber mit LANCZOS herunterskalieren
tl = src.crop((0, 0, sc, sc)).resize((dc, dc), Image.Resampling.LANCZOS)
tr = src.crop((sw - sc, 0, sw, sc)).resize((dc, dc), Image.Resampling.LANCZOS)
bl = src.crop((0, sh - sc, sc, sh)).resize((dc, dc), Image.Resampling.LANCZOS)
br = src.crop((sw - sc, sh - sc, sw, sh)).resize((dc, dc), Image.Resampling.LANCZOS)
out.paste(tl, (0, 0))
out.paste(tr, (tw - dc, 0))
out.paste(bl, (0, th - dc))
out.paste(br, (tw - dc, th - dc))
# Obere & untere Kante (Dicke = dc -> exakt passend zu den verkleinerten Ecken!)
mid_w = tw - 2 * dc
if mid_w > 0:
top_edge = src.crop((sc, 0, sw - sc, sc)).resize((mid_w, dc), Image.Resampling.LANCZOS)
bot_edge = src.crop((sc, sh - sc, sw - sc, sh)).resize((mid_w, dc), Image.Resampling.LANCZOS)
out.paste(top_edge, (dc, 0))
out.paste(bot_edge, (dc, th - dc))
# Linke & rechte Kante (Breite = dc)
mid_h = th - 2 * dc
if mid_h > 0:
left_edge = src.crop((0, sc, sc, sh - sc)).resize((dc, mid_h), Image.Resampling.LANCZOS)
right_edge = src.crop((sw - sc, sc, sw, sh - sc)).resize((dc, mid_h), Image.Resampling.LANCZOS)
out.paste(left_edge, (0, dc))
out.paste(right_edge, (tw - dc, dc))
# Mittelstück bei dropdown_box.png füllen
if mid_w > 0 and mid_h > 0 and box_key == "dropdown_box":
center_patch = src.crop((sc, sc, sw - sc, sh - sc)).resize((mid_w, mid_h), Image.Resampling.BILINEAR)
out.paste(center_patch, (dc, dc))
self._pil_cache[pil_key] = out
return out
def get_box_photo(
self,
box_key: str,
size: tuple[int, int],
corner_ratio: float | None = None,
border_scale: float = 1.0,
) -> ImageTk.PhotoImage | None:
tk_key = ("9slice_tk", box_key, size, corner_ratio, round(border_scale, 3))
if tk_key not in self._tk_cache:
pil_box = self.get_9slice_pil(
box_key, size, corner_ratio=corner_ratio, border_scale=border_scale
)
if pil_box is not None:
self._tk_cache[tk_key] = ImageTk.PhotoImage(pil_box)
return self._tk_cache.get(tk_key)
def get_box_photo(
self,
box_key: str,
size: tuple[int, int],
corner_ratio: float | None = None,
) -> ImageTk.PhotoImage | None:
tk_key = ("9slice_tk", box_key, size, corner_ratio)
if tk_key not in self._tk_cache:
pil_box = self.get_9slice_pil(box_key, size, corner_ratio=corner_ratio)
if pil_box is not None:
self._tk_cache[tk_key] = ImageTk.PhotoImage(pil_box)
return self._tk_cache.get(tk_key)
# ------------------------------------------------------------------
# KARTEN, BANNER & GIFS
# ------------------------------------------------------------------
def get_card_photo(self, card_filename: str, size=PLAYING_CARD_SIZE) -> ImageTk.PhotoImage | None:
key = ("card", self.res.card_theme, card_filename, size)
if key not in self._tk_cache:
pil = self._load_pil(self.res.get_card_path(card_filename))
if pil:
self._tk_cache[key] = ImageTk.PhotoImage(pil.resize(size, Image.Resampling.LANCZOS))
return self._tk_cache.get(key)
def get_card_back_photo(self, color: str = "Black", size=PLAYING_CARD_SIZE) -> ImageTk.PhotoImage | None:
key = ("card_back", self.res.card_theme, color, size)
if key not in self._tk_cache:
pil = self._load_pil(self.res.get_card_back_path(color))
if pil:
self._tk_cache[key] = ImageTk.PhotoImage(pil.resize(size, Image.Resampling.LANCZOS))
return self._tk_cache.get(key)
def get_scaled_photo(self, name: str, pil_img, size: tuple[int, int]) -> ImageTk.PhotoImage | None:
if not pil_img:
return None
key = (name, size)
if key not in self._tk_cache:
self._tk_cache[key] = ImageTk.PhotoImage(pil_img.resize(size, Image.Resampling.LANCZOS))
return self._tk_cache[key]
def get_proportional_photo(self, name: str, pil_img, target_width: int) -> ImageTk.PhotoImage | None:
"""Skaliert ein Banner (z.B. title.jpg) exakt im Original-Seitenverhältnis auf target_width."""
if not pil_img or target_width <= 10:
return None
src_w, src_h = pil_img.size
target_height = max(1, int(round(target_width * (src_h / src_w))))
return self.get_scaled_photo(name, pil_img, (target_width, target_height))
def get_gif_frames(self, key_or_filename: str, size=OUTCOME_GIF_SIZE) -> list[ImageTk.PhotoImage]:
cache_key = ("gif", key_or_filename, size)
if cache_key not in self._tk_cache:
frames = []
path = self.res.get_ui_image_path(key_or_filename)
if path.is_file():
try:
with Image.open(path) as gif:
idx = 0
while True:
frame = gif.copy().convert("RGBA").resize(size, Image.Resampling.LANCZOS)
frames.append(ImageTk.PhotoImage(frame))
idx += 1
gif.seek(idx)
except EOFError:
pass
except Exception:
pass
self._tk_cache[cache_key] = frames
return self._tk_cache[cache_key]