# -*- coding: utf-8 -*- # view/assets_manager.py from __future__ import annotations from pathlib import Path import tkinter as tk from PIL import Image, ImageChops, ImageDraw, ImageTk from models.resource_manager import ResourceManager from resources.code_res.game_constants import ( CARD_FILE_PATTERN, FONT_COLOR_BODY_DEFAULT, FONT_LETTER_SPACING_PX, FONT_OUTLINE_THICKNESS_PX, FONT_SHADOW_OFFSET_DEFAULT, OUTCOME_GIF_SIZE, PLAYING_CARD_SIZE, ) from view.goth_text_renderer import GothTextRenderer 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, } BOX_TARGET_CORNER_SPEC = { "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), } def _clean_box_matte_fast(pil_img: Image.Image | None, hollow_center: bool = True) -> Image.Image | None: if pil_img is None: return None rgba = pil_img.convert("RGBA") w, h = rgba.size if w < 8 or h < 8: return rgba r, g, b, a = rgba.split() luma = ImageChops.lighter(ImageChops.lighter(r, g), b) seed_img = luma.point(lambda p: 0 if p < 18 else 255) seeds = [(0, 0), (w - 1, 0), (0, h - 1), (w - 1, h - 1)] if hollow_center: seeds.append((w // 2, h // 2)) changed = False for sx, sy in seeds: if rgba.getpixel((sx, sy))[3] > 240 and seed_img.getpixel((sx, sy)) == 0: ImageDraw.floodfill(seed_img, (sx, sy), 128) changed = True if changed: ext_alpha = seed_img.point(lambda p: 0 if p == 128 else 255) rgba.putalpha(ImageChops.darker(a, ext_alpha)) return rgba class AssetManager: def __init__(self, root_dir: Path): self.root_dir = root_dir self.res = ResourceManager(root_dir) self._tk_cache: dict = {} self._pil_cache: dict = {} self._raw_card_cache: dict[str, Image.Image | None] = {} self._bg_scaled_key: tuple[bool, int, int] | None = None self._bg_scaled_pil: Image.Image | None = None self._text_renderer = GothTextRenderer(root_dir, self._pil_cache, self._tk_cache) 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 = None self.raw_poker_table = self._load_ui_flexible("poker_table", "poker_table") 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") self.raw_boxes: dict[str, Image.Image | None] = { "box_big": _clean_box_matte_fast( self._load_ui_flexible("box_big", "box_big"), hollow_center=True ), "box_gold_small": _clean_box_matte_fast( self._load_ui_flexible("box_gold_small", "box_gold_smal", "box_gold_small"), hollow_center=True ), "box_gold_double": _clean_box_matte_fast( self._load_ui_flexible("box_gold_double", "box_gold_small_double"), hollow_center=True ), "box_purple": _clean_box_matte_fast( self._load_ui_flexible("box_purple", "box_small_purple"), hollow_center=True ), "dropdown_box": _clean_box_matte_fast( self._load_ui_flexible("dropdown_box", "dropdown_box"), hollow_center=False ), } self.raw_chat_frame = self.raw_boxes["box_big"] 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") self._optimize_raw_for_display() 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 @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: 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 def _optimize_raw_for_display(self): try: r = tk._default_root sw = r.winfo_screenwidth() if r else 1920 sh = r.winfo_screenheight() if r else 1080 except Exception: sw, sh = 1920, 1080 btn_cap_h = 200 if max(sw, sh) >= 2500 else 130 for attr in ("raw_btn_default", "raw_btn_purple", "raw_btn_fire"): img = getattr(self, attr, None) if img is not None and img.height > btn_cap_h: nw = max(1, int(round(img.width * (btn_cap_h / img.height)))) setattr(self, attr, img.resize((nw, btn_cap_h), Image.Resampling.LANCZOS)) if max(sw, sh) >= 2500: return max_bg_w, max_bg_h = int(sw * 1.15), int(sh * 1.15) for attr in ("raw_bg_horizontal", "raw_bg_vertical", "raw_bg", "raw_poker_table"): img = getattr(self, attr, None) if img is not None and (img.width > max_bg_w or img.height > max_bg_h): ratio = min(max_bg_w / img.width, max_bg_h / img.height) nw, nh = max(1, int(round(img.width * ratio))), max(1, int(round(img.height * ratio))) setattr(self, attr, img.resize((nw, nh), Image.Resampling.LANCZOS)) # --- Hintergrund-Cache & Modal-Abdunklung --- def get_window_bg_pil(self, rw: int, rh: int) -> Image.Image | None: rw, rh = max(64, int(rw)), max(64, int(rh)) is_vert = bool(rh > rw and self.raw_bg_vertical is not None) key = (is_vert, rw, rh) if key == self._bg_scaled_key and self._bg_scaled_pil is not None: return self._bg_scaled_pil src = self.raw_bg_vertical if is_vert else (self.raw_bg_horizontal or self.raw_bg) if src is None: return None rgb_src = src.convert("RGB") if src.mode != "RGB" else src self._bg_scaled_pil = rgb_src.resize((rw, rh), Image.Resampling.BILINEAR) self._bg_scaled_key = key return self._bg_scaled_pil def get_bg_patch_photo(self, rw: int, rh: int, ox: int, oy: int, w: int, h: int) -> ImageTk.PhotoImage | None: w, h = max(1, int(w)), max(1, int(h)) rw, rh = max(w, int(rw)), max(h, int(rh)) ox, oy = max(0, min(rw - w, int(ox))), max(0, min(rh - h, int(oy))) tk_key = ("bg_patch", rw, rh, ox, oy, w, h) if tk_key in self._tk_cache: return self._tk_cache[tk_key] base = self.get_window_bg_pil(rw, rh) if base is None: return None if len(self._tk_cache) > 360: stale = [k for k in self._tk_cache if isinstance(k, tuple) and k and k[0] == "bg_patch"] for k in stale[:-12]: self._tk_cache.pop(k, None) photo = ImageTk.PhotoImage(base.crop((ox, oy, ox + w, oy + h))) self._tk_cache[tk_key] = photo return photo def get_dim_veil_photo(self, width: int, height: int, alpha: int = 148) -> ImageTk.PhotoImage: w, h = max(8, int(width)), max(8, int(height)) a = max(0, min(240, int(alpha))) tk_key = ("dim_veil", w, h, a) if tk_key not in self._tk_cache: stale = [k for k in self._tk_cache if isinstance(k, tuple) and k and k[0] == "dim_veil"] for k in stale[:-6]: self._tk_cache.pop(k, None) self._tk_cache[tk_key] = ImageTk.PhotoImage(Image.new("RGBA", (w, h), (10, 8, 16, a))) return self._tk_cache[tk_key] # --- Delegatoren an GothTextRenderer --- sanitize_goth_case = staticmethod(GothTextRenderer.sanitize_goth_case) def get_pil_font(self, size_px: int, alternate: bool = False): return self._text_renderer.get_pil_font(size_px, alternate=alternate) 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, uncached: bool = False, ) -> Image.Image: return self._text_renderer.render_pil( text, size_px, color, max_width, align, shadow_offset, outline_px, letter_spacing, alternate, uncached ) 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: return self._text_renderer.get_photo( text, size_px, color, max_width, align, shadow_offset, outline_px, letter_spacing, alternate ) # --- 9-Slice Rahmen-Scaler --- 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: 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 sc = max(12, int(round(min(sw, sh) * src_ratio))) rel_target, min_dc, max_dc = BOX_TARGET_CORNER_SPEC.get(box_key, (0.14, 12, 36)) dc = max(min_dc, min(max_dc, int(round(min(tw, th) * rel_target * border_scale)))) dc = min(dc, sc, tw // 2 - 1, th // 2 - 1) if dc < 6: out = src.resize((tw, th), Image.Resampling.BILINEAR) self._pil_cache[pil_key] = out return out out = Image.new("RGBA", (tw, th), (0, 0, 0, 0)) out.paste(src.crop((0, 0, sc, sc)).resize((dc, dc), Image.Resampling.LANCZOS), (0, 0)) out.paste(src.crop((sw - sc, 0, sw, sc)).resize((dc, dc), Image.Resampling.LANCZOS), (tw - dc, 0)) out.paste(src.crop((0, sh - sc, sc, sh)).resize((dc, dc), Image.Resampling.LANCZOS), (0, th - dc)) out.paste(src.crop((sw - sc, sh - sc, sw, sh)).resize((dc, dc), Image.Resampling.LANCZOS), (tw - dc, th - dc)) mid_w, mid_h = tw - 2 * dc, th - 2 * dc if mid_w > 0: out.paste(src.crop((sc, 0, sw - sc, sc)).resize((mid_w, dc), Image.Resampling.BILINEAR), (dc, 0)) out.paste(src.crop((sc, sh - sc, sw - sc, sh)).resize((mid_w, dc), Image.Resampling.BILINEAR), (dc, th - dc)) if mid_h > 0: out.paste(src.crop((0, sc, sc, sh - sc)).resize((dc, mid_h), Image.Resampling.BILINEAR), (0, dc)) out.paste(src.crop((sw - sc, sc, sw, sh - sc)).resize((dc, mid_h), Image.Resampling.BILINEAR), (tw - dc, dc)) if mid_w > 0 and mid_h > 0 and box_key == "dropdown_box": out.paste(src.crop((sc, sc, sw - sc, sh - sc)).resize((mid_w, mid_h), Image.Resampling.BILINEAR), (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) # --- Karten, Banner & Animationen --- def _get_raw_card_pil(self, path: Path | None) -> Image.Image | None: if not path: return None key = str(path) if key not in self._raw_card_cache: pil = self._load_pil(path) if pil is not None and pil.width > 340: nh = max(1, int(round(pil.height * (340.0 / pil.width)))) pil = pil.resize((340, nh), Image.Resampling.LANCZOS) self._raw_card_cache[key] = pil return self._raw_card_cache[key] 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._get_raw_card_pil(self.res.get_card_path(card_filename)) if pil: self._tk_cache[key] = ImageTk.PhotoImage(pil.resize(size, Image.Resampling.BILINEAR)) 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._get_raw_card_pil(self.res.get_card_back_path(color)) if pil: self._tk_cache[key] = ImageTk.PhotoImage(pil.resize(size, Image.Resampling.BILINEAR)) 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: if not pil_img or target_width <= 10: return None src_w, src_h = pil_img.size return self.get_scaled_photo(name, pil_img, (target_width, max(1, int(round(target_width * (src_h / src_w)))))) 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: list[ImageTk.PhotoImage] = [] 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: frames.append(ImageTk.PhotoImage(gif.copy().convert("RGBA").resize(size, Image.Resampling.BILINEAR))) idx += 1 gif.seek(idx) except EOFError: pass except Exception: pass self._tk_cache[cache_key] = frames return self._tk_cache[cache_key] def get_win_lose_gif_sequence( self, stem_or_filename: str, size: tuple[int, int] ) -> tuple[list[ImageTk.PhotoImage], list[int]]: tw, th = max(24, int(size[0])), max(24, int(size[1])) cache_key = ("win_lose_gif", stem_or_filename, (tw, th)) if cache_key in self._tk_cache: return self._tk_cache[cache_key] raw_pil_key = ("win_lose_raw_pil", stem_or_filename) if raw_pil_key not in self._pil_cache: raw_frames: list[Image.Image] = [] raw_durs: list[int] = [] path = self.res.get_win_lose_gif_path(stem_or_filename) if path.is_file(): try: with Image.open(path) as gif: idx = 0 while True: dur = max(35, min(200, int(gif.info.get("duration", 65) or 65))) raw_frames.append(gif.copy().convert("RGBA")) raw_durs.append(dur) idx += 1 gif.seek(idx) except EOFError: pass except Exception: pass self._pil_cache[raw_pil_key] = (raw_frames, raw_durs) src_frames, src_durs = self._pil_cache[raw_pil_key] tk_frames = [ImageTk.PhotoImage(fr.resize((tw, th), Image.Resampling.LANCZOS)) for fr in src_frames] self._tk_cache[cache_key] = (tk_frames, list(src_durs)) return self._tk_cache[cache_key] def preload_startup_assets(self, init_win_size: tuple[int, int] = (1280, 760), on_step=None): from resources.code_res.game_constants import SUITS, RANKS from resources.code_res.i18n import t from view.widgets.image_button import ImageButton, _trim_button_art from view.widgets.goth_dropdown import _trim_outer_black_bbox if callable(on_step): on_step("Fonts...") for px in (14, 15, 16, 18, 20, 22, 24, 26, 30, 34, 38): self.get_pil_font(px, alternate=False) if callable(on_step): on_step("Background...") w, h = max(800, init_win_size[0]), max(600, init_win_size[1]) self.get_bg_patch_photo(w, h, 0, 0, w, h) if self.raw_title is not None: self.get_proportional_photo("title_main_header", self.raw_title, 265) if callable(on_step): on_step("UI Controls...") for raw_b in (self.raw_btn_default, self.raw_btn_purple, self.raw_btn_fire): if raw_b is not None: _trim_button_art(raw_b) for raw_dd in ( self.raw_dropdown_closed, self.raw_dropdown_closed_btn, self.raw_dropdown_open, self.raw_dropdown_open_btn, ): if raw_dd is not None: _trim_outer_black_bbox(raw_dd) dummy_root = tk._default_root if dummy_root is not None and self.raw_btn_default is not None: for lbl, bw, bh in ( (t("btn_back_main"), 110, 32), (t("btn_back_game_menu"), 108, 32), (t("btn_stats"), 96, 32), (t("btn_settings"), 122, 32), (t("btn_switch_profile"), 124, 34), ): tmp = ImageButton( dummy_root, lbl, self.raw_btn_default, self.raw_btn_purple, None, width=bw, height=bh, style="amethyst", ) tmp._ensure_hover() tmp.destroy() if callable(on_step): on_step("Cards...") for suit in SUITS: for rank in RANKS: p = self.res.get_card_path(CARD_FILE_PATTERN.format(suit=suit, rank=rank)) if p and p.is_file(): self._get_raw_card_pil(p) for back_col in ("Black", "Red", "Blue", "Purple", "Gold"): bp = self.res.get_card_back_path(back_col) if bp and bp.is_file(): self._get_raw_card_pil(bp) if callable(on_step): on_step("Animations...")