"""Android performans profili: oyunu telefona göre hazırlar. Godot oyunları çoğu zaman yalnız masaüstü için dışa aktarılır. Telefonda üç şey yavaşlatır, bu modül üçünü de derleme sırasında düzeltir: 1. Dokular: masaüstü dışa aktarması VRAM dokularını yalnız S3TC/BPTC (BCn) olarak yazar (`.import` içinde `path.s3tc` / `path.bptc`). Telefon GPU'larının çoğu BCn okuyamaz; Godot da dokuyu yükleme anında işlemcide açar (ResourceFormatImporter "decomp_path"), sıkıştırmasız dört-sekiz kat VRAM'e koyar. Burada bloklar çözülüp ETC2/EAC'ye (her Android GPU'sunun desteklediği biçim) çevrilir ve `.import` satırı `path.etc2` olur. Bayt düzeni Godot 4.5 ResourceImporterTexture::_save_ctex ile aynıdır. 2. Paketleme: Gradle şablonu assets/ dosyalarını sıkıştırır; Godot editörü ise .ctex/.scn/.webp/.cfb/.pck'yi sıkıştırmadan koyar (export_plugin.cpp _should_compress_asset). Aynı liste build.gradle'a `noCompress` olarak eklenir; yalnız .ctex sıkıştırılır: bizim ETC2'ye çevirdiğimiz dokular (saydam/boş alanlar) deflate ile ~20 kat küçülüyor (Captive Lili APK'sı 1.4 GB → ~0.5 GB). 3. Proje ayarları: 2D oyunda OpenGL (gl_compatibility), `hdr_2d` kapalı; 3D oyunda Vulkan Mobil + düşük çözünürlük ölçeği ve pahalı efektler kısık. """ from __future__ import annotations import re import struct from dataclasses import dataclass, field from pathlib import Path import godot_project as gpj # CompressedTexture2D: "GST2", sürüm, genişlik, yükseklik, bayraklar, mip sınırı, 3 ayrılmış # alan; ardından veri biçimi, uint16 en/boy, mip sayısı, Image::Format, veri. CTEX_HEADER = 36 DATA_FORMAT_IMAGE, DATA_FORMAT_PNG, DATA_FORMAT_WEBP = 0, 1, 2 # Image::Format (core/io/image.h, 4.0-4.7 aynı). DXT1, DXT5, RGTC_R, RGTC_RG, BPTC_RGBA = 17, 19, 20, 21, 22 RGB8, RGBA8 = 4, 5 ETC2_RGB8, ETC2_RGBA8 = 30, 31 # Bundan küçük kayıpsız dokular (arayüz, piksel sanatı) kayıpsız kalır: ETC2 blok izi orada göze batar, # kazanç da önemsiz. 512x512 RGBA8 = 1 MB görüntü belleği. PORTABLE_MIN_PIXELS = 512 * 512 PORTABLE_MAX_EDGE = 8192 # birçok telefon GPU'sunun en büyük doku kenarı # kaynak biçim → (texture2ddecoder çözücüsü, etcpak kodlayıcısı, hedef biçim). # Çözücüler BGRA verir, etcpak'ın ETC2 kodlayıcıları RGBA ister. RGTC (BC4/BC5, 3D normal ve # pürüzlülük haritaları) çevrilmez: etcpak'ın EAC kodlayıcısı yanlış kanal üretiyor; Godot # bunları telefonda kendisi açar. CONVERSIONS = { DXT1: ("decode_bc1", "compress_etc2_rgb", ETC2_RGB8), DXT5: ("decode_bc3", "compress_etc2_rgba", ETC2_RGBA8), BPTC_RGBA: ("decode_bc7", "compress_etc2_rgba", ETC2_RGBA8), } # Image::get_format_pixel_size / get_format_pixel_rshift: blok başına bayt = 16 * piksel / 2^shift. BITS_PER_PIXEL = {DXT1: 4, DXT5: 8, BPTC_RGBA: 8, ETC2_RGB8: 4, ETC2_RGBA8: 8} DESKTOP_FEATURES = ("s3tc", "bptc") MOBILE_FEATURES = ("etc2", "astc") _REMAP_LINE = re.compile(r'^path\.(s3tc|bptc)="(res://[^"]+)"\s*$', re.M) _PLAIN_PATH_LINE = re.compile(r'^path="(res://[^"]+\.ctex)"\s*$', re.M) # Godot editörünün Android dışa aktarmasında sıkıştırmadığı Godot'ya özgü uzantılar # (medya uzantılarını AGP zaten sıkıştırmaz); .ctex bilerek dışarıda (bkz. madde 2). NO_COMPRESS = [".webp", ".cfb", ".scn", ".pck"] RENDERERS = ("auto", "gl_compatibility", "mobile", "keep") # Sahne/kaynaklarda bu sınıflardan biri geçiyorsa oyun 3D sayılır. _3D_MARKERS = (b"Camera3D", b"MeshInstance3D", b"MultiMeshInstance3D", b"CSGShape3D", b"GridMap") _SCENE_SUFFIXES = (".tscn", ".scn", ".res", ".tres") class TextureError(Exception): pass @dataclass class TextureReport: converted: int = 0 skipped: list[str] = field(default_factory=list) bytes_before: int = 0 bytes_after: int = 0 compressed: int = 0 # kayıpsız → ETC2 vram_saved: int = 0 def codecs_available() -> bool: try: import etcpak # noqa: F401 import texture2ddecoder # noqa: F401 except ImportError: return False return True def _level_sizes(width: int, height: int, mipmaps: int): """Image::_get_dst_image_size: her seviye 4x4 bloğa yuvarlanır, en küçük 1 px.""" w, h = width, height for _ in range(mipmaps + 1): yield (w + 3) // 4 * 4, (h + 3) // 4 * 4 w, h = max(1, w >> 1), max(1, h >> 1) def _swap_rb(buf: bytes) -> bytes: out = bytearray(buf) out[0::4], out[2::4] = buf[2::4], buf[0::4] return bytes(out) def convert_ctex(data: bytes) -> bytes: """BCn biçimli .ctex'i ETC2/EAC .ctex'e çevirir (başlık ve mip yapısı korunur).""" import etcpak import texture2ddecoder if len(data) < CTEX_HEADER + 16 or data[:4] != b"GST2": raise TextureError("GST2 başlığı yok") df, w, h, mipmaps, fmt = struct.unpack_from(" bytes: """Kayıpsız/kayıplı (WebP/PNG) büyük dokuyu ETC2'ye çevirir: telefonda RGBA8 yerine 4-8 bit/piksel. Godot 2D dokuları varsayılan olarak kayıpsız içe aktarır; motor bunları GPU'ya sıkıştırmadan (32 bit/piksel) yükler. Başlıktaki mantıksal boyut korunur (texture_set_size_override). """ import io import etcpak from PIL import Image if len(data) < CTEX_HEADER + 20 or data[:4] != b"GST2": raise TextureError("GST2 başlığı yok") df, w, h, mipmaps, fmt = struct.unpack_from(" PORTABLE_MAX_EDGE: # Telefonda yüklenemez; katman (riaslink.gd _genis_dokulari_bol) çalışırken karelere keser # ve bunun için gömülü PNG/WebP'yi okur. raise TextureError("8192'den geniş doku (kayıpsız kalır)") size = struct.unpack_from(" int: """Dokunun GPU'da kapladığı yaklaşık bayt (yalnız mipmap'siz tek seviye).""" _, w, h, _, fmt = struct.unpack_from(" None: m = _PLAIN_PATH_LINE.search(imp_text) if not m: return src = assets / m.group(1)[len("res://"):] if not src.is_file(): return data = src.read_bytes() try: new = convert_portable_ctex(data) except TextureError: return # küçük/uygunsuz doku: olduğu gibi kalır, hata değil src.write_bytes(new) report.compressed += 1 report.vram_saved += _vram_size(data) - _vram_size(new) def convert_textures(assets: Path, log, portable: bool = True) -> TextureReport: """Masaüstü biçimli (BCn) dokuları ETC2'ye çevirir; portable ise büyük kayıpsız dokuları da.""" report = TextureReport() for imp in sorted(assets.rglob("*.import")): text = imp.read_text("utf-8", "replace") if 'type="CompressedTexture2D"' not in text or any(f"path.{f}=" in text for f in MOBILE_FEATURES): continue m = _REMAP_LINE.search(text) if not m: if portable: _compress_portable(assets, text, report) continue rel = m.group(2)[len("res://"):] src = assets / rel if not src.is_file(): report.skipped.append(f"{rel} (dosya yok)") continue data = src.read_bytes() try: new = convert_ctex(data) except TextureError as exc: report.skipped.append(f"{rel} ({exc})") continue new_rel = re.sub(r"\.(s3tc|bptc)\.ctex$", ".etc2.ctex", rel) if new_rel == rel: new_rel = rel[:-len(".ctex")] + ".etc2.ctex" (assets / new_rel).write_bytes(new) src.unlink() text = text[:m.start()] + f'path.etc2="res://{new_rel}"' + text[m.end():] text = re.sub(r'"imported_formats": \[[^\]]*\]', '"imported_formats": ["etc2_astc"]', text) imp.write_text(text, "utf-8") report.converted += 1 report.bytes_before += len(data) report.bytes_after += len(new) return report def disable_asset_compression(build_gradle: Path) -> bool: """aaptOptions bloğuna noCompress ekler; blok bulunamazsa False.""" text = build_gradle.read_text("utf-8") if "noCompress" in text: return True line = "noCompress " + ", ".join(f"'{e}'" for e in NO_COMPRESS) new, n = re.subn(r"^(\s*)(aaptOptions|androidResources)\s*\{\s*\n", lambda m: f"{m.group(0)}{m.group(1)} {line}\n", text, count=1, flags=re.M) if not n: return False build_gradle.write_text(new, "utf-8") return True _REMAP_PATH = re.compile(rb'^path="res://([^"]+)"', re.M) def _addon_exports(assets: Path) -> set[str]: """Eklenti sahnelerinin dışa aktarılmış kopyaları (.godot/exported/...): addons/*.remap hedefleri.""" out = set() addons = assets / "addons" for r in addons.rglob("*.remap") if addons.is_dir() else (): m = _REMAP_PATH.search(r.read_bytes()) if m: out.add(m.group(1).decode("utf-8", "replace")) return out def is_3d(assets: Path) -> bool: """Eklenti (addons/) örnekleri dışındaki sahnelerde 3D düğüm var mı.""" skip = _addon_exports(assets) for p in assets.rglob("*"): if p.suffix not in _SCENE_SUFFIXES and not p.name.endswith(".remap"): continue rel = p.relative_to(assets).as_posix() if rel.startswith("addons/") or rel in skip or not p.is_file(): continue data = p.read_bytes() if any(mk in data for mk in _3D_MARKERS): return True return False def choose_renderer(choice: str, three_d: bool) -> str: if choice not in RENDERERS: raise ValueError(f"Bilinmeyen görüntü motoru: {choice}") if choice == "auto": return "mobile" if three_d else "gl_compatibility" return choice def apply_profile(project: gpj.ProjectBinary, renderer: str, three_d: bool) -> list[str]: """Mobil proje ayarlarını yazar; günlüğe yazılacak kısa notları döndürür.""" notes = [] if renderer != "keep": for key in ("rendering/renderer/rendering_method", "rendering/renderer/rendering_method.mobile"): project.set_string(key, renderer) notes.append("görüntü motoru " + ("OpenGL (uyumluluk)" if renderer == "gl_compatibility" else "Vulkan Mobil")) if renderer == "mobile": project.set_bool("rendering/rendering_device/fallback_to_opengl3", True) if project.get_value("rendering/viewport/hdr_2d"): project.set_bool("rendering/viewport/hdr_2d", False) notes.append("hdr_2d kapalı") msaa_2d = project.get_value("rendering/anti_aliasing/quality/msaa_2d") if isinstance(msaa_2d, int) and msaa_2d > 0: project.set_int("rendering/anti_aliasing/quality/msaa_2d", 0) notes.append("2D kenar yumuşatma (MSAA) kapalı") if three_d: scale = project.get_value("rendering/scaling_3d/scale") if not isinstance(scale, float) or scale > 0.75: project.set_float("rendering/scaling_3d/scale", 0.75) for key in ("rendering/anti_aliasing/quality/msaa_3d", "rendering/anti_aliasing/quality/screen_space_aa", "rendering/environment/ssao/quality", "rendering/environment/ssil/quality", "rendering/environment/screen_space_reflection/roughness_quality", "rendering/lights_and_shadows/directional_shadow/soft_shadow_filter_quality", "rendering/lights_and_shadows/positional_shadow/soft_shadow_filter_quality"): project.set_int(key, 0) for key in ("rendering/lights_and_shadows/directional_shadow/size", "rendering/lights_and_shadows/positional_shadow/atlas_size"): size = project.get_value(key) if not isinstance(size, int) or size > 2048: project.set_int(key, 2048) notes.append("3D: çözünürlük %75, kenar yumuşatma/SSAO/SSR kapalı, gölge ≤2048") return notes