diff --git a/scripts/test_tools_e2e.py b/scripts/test_tools_e2e.py index 765f1ff7..be7930b3 100755 --- a/scripts/test_tools_e2e.py +++ b/scripts/test_tools_e2e.py @@ -856,37 +856,144 @@ def test_05_standalone_mugen_extractor(self) -> None: except ImportError: self.skipTest("Pillow not installed in test Python environment") - char_dir = os.path.join(self.work_dir, "chars", "ken_e2e") + import gzip + + chars_root = os.path.join(self.work_dir, "chars") + char_dir = os.path.join(chars_root, "ken_e2e") os.makedirs(char_dir, exist_ok=True) + # Build a fighter whose SFF embedded palette is a corrupted cyan ramp, + # while Classic1P.act stores authentic 1P colors in official Elecbyte reverse order (dest = 255 - i) + # AND stores a flashy neon yellow ramp at raw .act bytes 0..47 (slots 255..240). spr = Image.new("P", (16, 24), 0) - pal = [0, 0, 0] * 256 - pal[3:6] = [230, 40, 40] - pal[6:9] = [245, 220, 60] - spr.putpalette(pal) + corrupted_sff_pal = [0, 255, 255] * 256 + corrupted_sff_pal[0:3] = [0, 0, 0] + spr.putpalette(corrupted_sff_pal) for y in range(4, 22): for x in range(4, 12): - spr.putpixel((x, y), 1) - for x in range(4, 12): - spr.putpixel((x, 4), 2) + spr.putpixel((x, y), 1) # Navy/Red gi + for x in range(5, 11): + spr.putpixel((x, 4), 2) # Blonde hair + spr.putpixel((x, 6), 3) # Natural skin + spr.putpixel((x, 7), 3) + spr.putpixel((x, 21), 4) # Dark outline + spr.putpixel((x, 12), 5) # Belt pcx_buf = io.BytesIO() spr.save(pcx_buf, format="PCX") pcx_bytes = pcx_buf.getvalue() - sff_hdr = bytearray(512) - sff_hdr[0:12] = b"ElecbyteSpr\x00" - struct.pack_into(" bytes: + hdr = bytearray(512) + hdr[0:12] = b"ElecbyteSpr\x00" + struct.pack_into(" None: sys.executable, mugen_py, "--src", - os.path.dirname(char_dir), + chars_root, "--dest", out_fgt_dir, "--mode", "FULLSIZE", + "--scale", + "1.0", "--compress", "--workers", "1", @@ -910,8 +1019,34 @@ def test_05_standalone_mugen_extractor(self) -> None: timeout=30, ) self.assertEqual(r_mugen.returncode, 0, f"mugen_extractor.py failed:\n{r_mugen.stdout}\n{r_mugen.stderr}") - idx_txt = read_text(os.path.join(out_fgt_dir, "index.txt")).strip() - self.assertTrue(idx_txt.startswith("ken_e2e,"), f"Unexpected fighters index.txt: {idx_txt}") + idx_lines = sorted(read_text(os.path.join(out_fgt_dir, "index.txt")).strip().splitlines()) + self.assertEqual(len(idx_lines), 2, f"Expected both characters extracted, got: {idx_lines}") + + def unpack_fgt_gz_colors(fgt_gz_file: str) -> tuple[int, int, int, set[tuple[int, int, int]]]: + raw = gzip.decompress(read_bytes(fgt_gz_file)) + self.assertEqual(raw[:4], b"FGT\x01") + w_f, h_f, nf_f, _ = struct.unpack("> 11) & 0x1F) * 255 // 31 + g8 = ((c565 >> 5) & 0x3F) * 255 // 63 + b8 = (c565 & 0x1F) * 255 // 31 + rgbs.add((r8, g8, b8)) + return w_f, h_f, nf_f, rgbs + + w_k, h_k, _nf_k, ken_cols = unpack_fgt_gz_colors(os.path.join(out_fgt_dir, "ken_e2e", "stand.fgt.gz")) + self.assertLessEqual(w_k, 64) + self.assertLessEqual(h_k, 64) + self.assertTrue(any(b > 160 and r < 60 for r, g, b in ken_cols), f"Expected 1P colors from reversed .act, got {ken_cols}") + self.assertFalse(any(r > 230 and g > 230 and b < 30 for r, g, b in ken_cols), f"Un-reversed .act yellow FX ramp leaked: {ken_cols}") + self.assertFalse(any(r < 20 and g > 230 and b > 230 for r, g, b in ken_cols), f"Corrupted SFF cyan leaked: {ken_cols}") + + _wc, _hc, nfc, chain_cols = unpack_fgt_gz_colors(os.path.join(out_fgt_dir, "sff_chain_e2e", "stand.fgt.gz")) + self.assertEqual(nfc, 2) + self.assertTrue(any(b > 160 and r < 60 for r, g, b in chain_cols)) if __name__ == "__main__": diff --git a/tools/mugen_extractor/ARCHITECTURE.md b/tools/mugen_extractor/ARCHITECTURE.md index d9481168..0072ccda 100644 --- a/tools/mugen_extractor/ARCHITECTURE.md +++ b/tools/mugen_extractor/ARCHITECTURE.md @@ -43,10 +43,10 @@ The **`mugen_extractor.py`** script is designed to convert fighting game charact | v [ resolve_master_palette() ] - - Heuristic scoring (score_palette) - - Modulo Bank Expansion (16/32/64c) - - Dynamic Offset Shifting - - Priority to pal.defaults + - Elecbyte .act reverse decode (255 - i) + - SFFv1 shared initial_palette chaining + - Canonical 1P & pal.defaults hierarchy + - Index-collapse & all-hue wash guard | +-------------------+-------------------+ | | @@ -140,33 +140,27 @@ The `.fgt` format is a compact, streamable binary animation format engineered fo ## 5. Palette Resolution Algorithm (`resolve_master_palette`) -To ensure 100% authentic color rendering and eliminate fluorescent/neon artifacts across all MUGEN characters (arcade rips, digitized captures, and original creations): - -1. **Body Reference Sprite Selection:** - * Prioritizes key body animation groups (`0`, `1`, `5`, `10`, `20`, `21`, `40`, `100`, `200`, `5000`). - * Prioritizes canonical stance frame `(0,0)`, then evaluates the frame with the maximum count of distinct pixel indices. - * Systematically excludes group `9000` (portraits / select icons) to avoid contamination. - -2. **Canonical Candidate Hierarchy:** - * **1. Canonical SFF Palette (`sff.stand_palette`):** Embedded palette in sprite `(0,0)` of the `.sff` file validated by `0x0C` marker and anti-RLE check. Absolute priority (**+100 pts**). - * **2. Official DEF Palettes (`DEF(pal.defaults)`):** Palettes declared in `[Info]` `pal.defaults` (**+80 pts**). - * **3. Standard DEF Palettes (`DEF(pal1..12)`):** Palettes declared in `[Files]` (**+75 pts**). - * **4. SFF Big Portrait (`SFF(9000,1)`):** Palette of official full-size character portrait (**+70 pts**). - * **5. SFF First Palette (`sff.first_palette`):** First valid palette in the SFF container (**+60 pts**). - * **6. SFF Small Portrait (`SFF(9000,0)`):** Palette of 25x25 select icon (**+50 pts**). - * **7. Additional `.act` Files:** Extra palettes in character folder (**+30 pts**). - -3. **Anti-Fluorescent Evaluation & Scoring Function (`score_palette`):** - * **Anti-RLE Filter (`is_rle_garbage`):** Immediate rejection of fake PCX palettes consisting of compressed image data (> 35% bytes $\ge 192$ and > 25% bytes $\le 15$). - * **Monochrome / Empty Palette Rejection:** If the palette produces only a single color shade (`u_colors <= 1`) while the sprite has multiple indices, score = **-9999**. - * **Residual Neon / Chroma Mask Rejection:** If more than 5% of body pixels resolve to pure primary neon colors (pure magenta `255,0,255`, pure cyan `0,255,255`, pure green `0,255,0`), the palette is rejected. - * **Shifted / Mostly-Black Palette Rejection:** If more than 60% of pixels in a non-trivial sprite map to pure black `(0,0,0)`, the palette is rejected. - * **Coverage Score Formula:** - $$\text{Coverage Ratio} = \min\left(1.0, \frac{\text{Unique Colors}}{\text{Unique Indices}}\right)$$ - $$\text{Base Score} = \text{Coverage Ratio} \times 100 + \min(\text{Unique Colors}, \text{Unique Indices}) \times 2$$ - $$\text{Luminance Bonus} = +30 \quad \text{if } 15 \le \text{Mean Luminance} \le 215$$ - $$\text{Over/Under-exposure Penalty} = -50 \quad \text{if } L < 10 \text{ or } L > 240$$ - * `ACT(folder)`: **+10 pts** +To guarantee authentic 1P color rendering and eliminate fluorescent/monochrome silhouettes across all MUGEN characters (arcade rips, digitized captures, and custom edits): + +1. **Elecbyte `.act` Reverse Index Decoding (`decode_mugen_act`) & SFFv1 Shared Chaining:** + * In official MUGEN `SFFv1` external `.act` files (768 bytes = 256 RGB triplets), entries are stored in **reverse palette order**: entry `i` in the `.act` file maps to sprite palette index `255 - i` (with index `0` reserved for transparency). + * In `SFFv1Parser`, when stance sprite `(0,0)` has `same_pal != 0` (shared palette without a local `0x0C` trailer), it inherits Sprite `#0`'s `initial_palette`, and linked frames (`data_length == 0`) reuse `sprite_list[prev]`. + +2. **Multi-Pose Body Reference & Canonical 1P Hierarchy:** + * Samples pixel indices across stance `(0,0)` plus `walk`/`attack` body sprites while excluding group `9000` portraits. + * Ranks candidates by 1P authority (with non-standard forward `.act` files kept strictly as last-resort fallbacks): + * **1. Explicit Canonical 1P DEF Filenames (`Normal.act`, `Default.act`, `Classic.act`, `Original.act`):** **+220 pts** + * **2. `DEF(pal1) == SFF(stand)` Consensus** (when `pal.defaults` was customized to a high slot): **+215 pts** + * **3. Capcom 6-Button LP (`pal4 = *01.act` when `pal1 = *04.act`):** **+210 pts** + * **4. Primary `DEF(pal.defaults[0])`:** **+200 pts** (secondary `pal.defaults`: **+150 pts**) + * **5. Canonical SFF Stance Palette (`sff.stand_palette`):** **+196 pts** + * **6. Non-default DEF Slots / Extra Folder `.act` / SFF Fallbacks:** **+65..+130 pts** + +3. **Structural & Perceptual Validation (`score_palette`, `[0..32]` pts or `-9999`):** + * **Anti-RLE Filter (`is_rle_garbage`):** Rejects compressed PCX pixel streams misidentified as palettes. + * **Index-Collapse Guard:** Rejects palettes where $\ge 4$ distinct non-zero sprite indices collapse onto `(0,0,0)` (`> 32%` black) or onto a single identical fill color (`> 40%` of pixels), while preserving intentional dark outfits that use 1–2 black indices. + * **Chroma-Key & All-Hue Monochrome Ramp Guard:** Rejects chroma-key background leaks (`> 3%` pure magenta/green/cyan) and single-hue neon FX ramps across all hues without penalizing warm Red/Orange + natural Skin 1P costumes. + * **Disembodied Helper & Fullscreen Cut-In Filtering:** `special1..3` and `super1..3` selection skips pure additive (`blend = A/S`) projectile helpers, `1x1` AI dummy actions, and `320x240` / `640x480` fullscreen super cut-ins. --- diff --git a/tools/mugen_extractor/ARCHITECTURE_ES.md b/tools/mugen_extractor/ARCHITECTURE_ES.md index 77948ee8..da8a04fe 100644 --- a/tools/mugen_extractor/ARCHITECTURE_ES.md +++ b/tools/mugen_extractor/ARCHITECTURE_ES.md @@ -43,10 +43,10 @@ El script **`mugen_extractor.py`** tiene como misión convertir personajes dise | v [ resolve_master_palette() ] - - Puntuación heurística (score_palette) - - Expansión Modulo Bank (16/32/64c) - - Desplazamiento dinámico (Offset Shift) - - Prioridad pal.defaults + - Decodificación inversa .act (255 - i) + - Encadenamiento SFFv1 initial_palette + - Jerarquía 1P canónica y pal.defaults + - Filtro de colapso de índices y monocromo | +-------------------+-------------------+ | | @@ -134,36 +134,33 @@ El formato `.fgt` es un formato de animación compacto y secuencial diseñado pa | `0x0C` | `2 * num_frames` | uint16 LE[] | Tabla de retrasos de cada cuadro (en ticks) | | `0x0C + (2*N)` | `N * W * H * 2` | uint16 LE[] | Flujo continuo de píxeles RGB565 para cada cuadro | -> **Nota sobre compresión:** La opción `--compress` genera archivos `.fgt.gz` mediante gzip +> **Nota sobre compresión:** La opción `--compress` genera archivos `.fgt.gz` mediante gzip estándar, ideal para Raspberry Pi y tarjetas SD. + +--- ## 5. Algoritmo de Resolución de Paletas (`resolve_master_palette`) -Para garantizar una representación 100% fiel y sin artefactos fluorescentes/neón en todos los personajes MUGEN (rips arcade, digitalizaciones y creaciones originales): - -1. **Selección del Sprite de Referencia del Cuerpo:** - * Prioriza los cuadros corporales clave (grupos `0`, `1`, `5`, `10`, `20`, `21`, `40`, `100`, `200`, `5000`). - * Busca con prioridad la postura canónica de guardia `(0,0)`, y evalúa el cuadro con el mayor número de índices de píxeles distintos. - * Excluye sistemáticamente el grupo `9000` (retratos / iconos de selección) para evitar contaminación. - -2. **Jerarquía Canónica de Candidatos:** - * **1. Paleta Canónica SFF (`sff.stand_palette`):** Paleta integrada en el sprite `(0,0)` del archivo `.sff` validada con marcador `0x0C` y filtro anti-RLE. Prioridad absoluta (**+100 pts**). - * **2. Paletas Oficiales DEF (`DEF(pal.defaults)`):** Paletas declaradas en `[Info]` `pal.defaults` (**+80 pts**). - * **3. Paletas Estándar DEF (`DEF(pal1..12)`):** Palettes declaradas en `[Files]` (**+75 pts**). - * **4. Retrato Grande SFF (`SFF(9000,1)`):** Paleta del retrato oficial de cuerpo completo (**+70 pts**). - * **5. Primera Paleta SFF (`sff.first_palette`):** Primera paleta válida del contenedor SFF (**+60 pts**). - * **6. Icono Pequeño SFF (`SFF(9000,0)`):** Paleta del icono 25x25 (**+50 pts**). - * **7. Archivos `.act` Adicionales:** Paletas presentes en la carpeta (**+30 pts**). - -3. **Función de Evaluación y Filtrado Anti-Fluorescente (`score_palette`):** - * **Filtro Anti-RLE (`is_rle_garbage`):** Rechazo inmediato de falsas paletas PCX compuestas por datos comprimidos de imagen (> 35% bytes $\ge 192$ y > 25% bytes $\le 15$). - * **Rechazo de paletas monocromáticas / vacías:** Si la paleta genera un solo tono (`u_colors <= 1`) cuando el sprite tiene múltiples índices, puntuación = **-9999**. - * **Rechazo de máscaras neón / croma residuales:** Si más del 5% de los píxeles del cuerpo usan colores primarios puros neón (magenta puro `255,0,255`, cian puro `0,255,255`, verde puro `0,255,0`), la paleta es rechazada. - * **Rechazo de paletas desplazadas / mayoritariamente negras:** Si más del 60% de los píxeles de un sprite complejo se asignan a negro puro `(0,0,0)`, la paleta es rechazada. - * **Fórmula de Puntuación de Cobertura:** - $$\text{Coverage Ratio} = \min\left(1.0, \frac{\text{Colores Únicos}}{\text{Índices Únicos}}\right)$$ - $$\text{Puntuación Base} = \text{Coverage Ratio} \times 100 + \min(\text{Colores Únicos}, \text{Índices Únicos}) \times 2$$ - $$\text{Bono Luminancia} = +30 \quad \text{si } 15 \le \text{Luminancia Media} \le 215$$ - $$\text{Penalización Sub/Sobre-exposición} = -50 \quad \text{si } L < 10 \text{ o } L > 240$$ +Para garantizar una representación 1P auténtica y eliminar siluetas fluorescentes o monocromáticas en todos los personajes MUGEN (rips arcade, digitalizaciones y ediciones): + +1. **Decodificación Inversa `.act` de Elecbyte (`decode_mugen_act`) y Encadenamiento SFFv1:** + * En la especificación oficial MUGEN `SFFv1`, los archivos externos `.act` (768 bytes = 256 tripletes RGB) se almacenan en **orden de índice inverso**: la entrada `i` del archivo `.act` corresponde al índice de paleta `255 - i` del sprite (con el índice `0` transparente). + * En `SFFv1Parser`, cuando el sprite de guardia `(0,0)` tiene `same_pal != 0` (paleta compartida sin marcador `0x0C` local), hereda la `initial_palette` del Sprite `#0`, y los cuadros enlazados (`data_length == 0`) reutilizan `sprite_list[prev]`. + +2. **Muestreo Corporal Multi-Pose y Jerarquía 1P Canónica:** + * Muestra los índices de píxeles en la postura `(0,0)` junto con poses `walk`/`attack`, excluyendo el grupo `9000` (retratos). + * Clasifica los candidatos por autoridad 1P (dejando los `.act` directos no estándar solo como último recurso): + * **1. Nombres 1P explícitos en DEF (`Normal.act`, `Default.act`, `Classic.act`, `Original.act`):** **+220 pts** + * **2. Consenso `DEF(pal1) == SFF(stand)`** (cuando `pal.defaults` apunta a una ranura alta personalizada): **+215 pts** + * **3. Convención Capcom de 6 botones LP (`pal4 = *01.act` cuando `pal1 = *04.act`):** **+210 pts** + * **4. Ranura principal `DEF(pal.defaults[0])`:** **+200 pts** (`pal.defaults` secundarios: **+150 pts**) + * **5. Paleta Canónica SFF (`sff.stand_palette`):** **+196 pts** + * **6. Otras ranuras DEF / archivos `.act` de carpeta / respaldos SFF:** **+65..+130 pts** + +3. **Validación Estructural y Perceptual (`score_palette`, `[0..32]` pts o `-9999`):** + * **Filtro Anti-RLE (`is_rle_garbage`):** Rechaza flujos de píxeles PCX comprimidos tomados erróneamente como paletas. + * **Filtro de Colapso de Índices:** Rechaza paletas donde $\ge 4$ índices distintos se colapsan en `(0,0,0)` (`> 32%` negro) o en un mismo color de relleno idéntico (`> 40%` de píxeles), preservando trajes oscuros intencionales de 1–2 índices negros. + * **Filtro de Croma y Degradados Monocromáticos en Todos los Tonos:** Rechaza fugas de fondo croma (`> 3%` magenta/verde/cian puros) y rampas de efectos neón de un solo tono sin penalizar trajes 1P cálidos Rojo/Naranja + Piel natural. + * **Filtrado de Helpers y Cut-Ins de Pantalla Completa:** La selección de `special1..3` y `super1..3` descarta proyectiles puramente aditivos (`blend = A/S`), helpers invisibles `1x1` y fondos de super `320x240` / `640x480`. --- diff --git a/tools/mugen_extractor/ARCHITECTURE_FR.md b/tools/mugen_extractor/ARCHITECTURE_FR.md index 4928f436..84d9ecc6 100644 --- a/tools/mugen_extractor/ARCHITECTURE_FR.md +++ b/tools/mugen_extractor/ARCHITECTURE_FR.md @@ -43,10 +43,10 @@ Le script **`mugen_extractor.py`** a pour mission de convertir des personnages c | v [ resolve_master_palette() ] - - Scoring heuristique (score_palette) - - Expansion Modulo Bank (16/32/64c) - - Offset Shifting dynamique - - Priorité pal.defaults + - Décodage inverse .act Elecbyte (255 - i) + - Chaînage SFFv1 initial_palette (same_pal) + - Hiérarchie 1P canonique & pal.defaults + - Garde anti-effondrement & anti-monochrome | +-------------------+-------------------+ | | @@ -140,32 +140,27 @@ Le format `.fgt` est un format d'animation compact et streamable conçu pour min ## 5. Algorithme de Résolution des Palettes (`resolve_master_palette`) -Pour garantir un rendu 100% fidèle et sans artefacts fluorescents/néon sur tous les personnages MUGEN (rips arcade, captures digitalisées et créations originales) : - -1. **Sélection du Sprite de Référence Corps :** - * Priorité aux frames du corps (groupes clés `0`, `1`, `5`, `10`, `20`, `21`, `40`, `100`, `200`, `5000`). - * Recherche en priorité la posture d'attente canonique `(0,0)`, puis évalue la frame possédant le plus grand nombre d'indices de pixels distincts. - * Exclut systématiquement le groupe `9000` (portraits / icônes de sélection) afin d'éviter toute contamination. - -2. **Hiérarchie Canonique des Candidats :** - * **1. Palette Canonique SFF (`sff.stand_palette`) :** Palette intégrée au sprite `(0,0)` dans le fichier `.sff` validée par l'octet magique `0x0C` et non-RLE. Priorité absolue (**+100 pts**). - * **2. Palettes Officielles DEF (`DEF(pal.defaults)`) :** Palettes déclarées dans `[Info]` `pal.defaults` de l'auteur (**+80 pts**). - * **3. Palettes Standard DEF (`DEF(pal1..12)`) :** Palettes déclarées dans `[Files]` (**+75 pts**). - * **4. Grand Portrait SFF (`SFF(9000,1)`) :** Palette du grand portrait officiel (**+70 pts**). - * **5. Première Palette SFF (`sff.first_palette`) :** Première palette valide du conteneur SFF (**+60 pts**). - * **6. Petit Portrait SFF (`SFF(9000,0)`) :** Palette de l'icône de sélection (**+50 pts**). - * **7. Fichiers `.act` additionnels :** Palettes présentes dans le dossier (**+30 pts**). - -3. **Fonction d'Évaluation & Filtrage Anti-Fluorescent (`score_palette`) :** - * **Filtre Anti-RLE (`is_rle_garbage`) :** Rejet immédiat des faux flux PCX où les pixels compressés sont pris pour une palette (> 35% d'octets $\ge 192$ et > 25% d'octets $\le 15$). - * **Rejet des palettes monochromes / vides :** Si la palette ne génère qu'une seule nuance (`u_colors <= 1`) alors que le sprite a plusieurs indices, score = **-9999**. - * **Rejet des masques néon / chroma résiduels :** Si plus de 5% des pixels du corps utilisent des couleurs primaires pures néon (magenta pur `255,0,255`, cyan pur `0,255,255`, vert pur `0,255,0`), la palette est rejetée. - * **Rejet des palettes décalées / majoritairement noires :** Si plus de 60% des pixels d'un sprite complexe sont mappés sur du noir absolu `(0,0,0)`, la palette est rejetée. - * **Calcul du Score de Couverture :** - $$\text{Coverage Ratio} = \min\left(1.0, \frac{\text{Couleurs Uniques}}{\text{Indices Uniques}}\right)$$ - $$\text{Base Score} = \text{Coverage Ratio} \times 100 + \min(\text{Couleurs Uniques}, \text{Indices Uniques}) \times 2$$ - $$\text{Bonus Luminance} = +30 \quad \text{si } 15 \le \text{Luminance Moyenne} \le 215$$ - $$\text{Pénalité Sous/Sur-exposition} = -50 \quad \text{si } L < 10 \text{ ou } L > 240$$ +Pour garantir un rendu 1P authentique et éliminer les silhouettes fluorescentes ou monochromes sur tous les personnages MUGEN (rips arcade, captures digitalisées et créations originales) : + +1. **Décodage Inverse `.act` Elecbyte (`decode_mugen_act`) & Chaînage Partagé SFFv1 :** + * Dans la spécification officielle MUGEN `SFFv1`, les fichiers `.act` externes (768 octets = 256 triplets RGB) sont stockés en **ordre d'index inversé** : l'entrée `i` du fichier `.act` correspond à l'index de palette `255 - i` du sprite (l'index `0` étant toujours transparent). + * Dans `SFFv1Parser`, lorsque le sprite de garde `(0,0)` possède `same_pal != 0` (palette partagée sans marqueur `0x0C` local), il hérite de l'`initial_palette` du Sprite `#0`, et les frames liées (`data_length == 0`) réutilisent `sprite_list[prev]`. + +2. **Échantillonnage Multi-Poses du Corps & Hiérarchie 1P Canonique :** + * Échantillonne les indices de pixels sur la posture `(0,0)` ainsi que sur les poses `walk`/`attack`, en excluant le groupe `9000` (portraits). + * Classe les candidats par autorité 1P (les rares `.act` non-standards en ordre direct restant uniquement en dernier recours) : + * **1. Noms 1P explicites dans le DEF (`Normal.act`, `Default.act`, `Classic.act`, `Original.act`) :** **+220 pts** + * **2. Consensus `DEF(pal1) == SFF(stand)`** (quand `pal.defaults` a été modifié vers un slot alternatif élevé) : **+215 pts** + * **3. Convention Capcom 6 boutons LP (`pal4 = *01.act` quand `pal1 = *04.act`) :** **+210 pts** + * **4. Slot principal `DEF(pal.defaults[0])` :** **+200 pts** (`pal.defaults` secondaires : **+150 pts**) + * **5. Palette SFF Canonique (`sff.stand_palette`) :** **+196 pts** + * **6. Autres slots DEF / fichiers `.act` du dossier / replis SFF :** **+65..+130 pts** + +3. **Validation Structurelle & Perceptuelle (`score_palette`, `[0..32]` pts ou `-9999`) :** + * **Filtre Anti-RLE (`is_rle_garbage`) :** Rejette les flux de pixels PCX compressés pris à tort pour une palette. + * **Garde Anti-Effondrement d'Index :** Rejette toute palette où $\ge 4$ indices distincts du sprite s'effondrent sur `(0,0,0)` (`> 32 %` de noir) ou sur un unique triplet de remplissage identique (`> 40 %` des pixels), tout en préservant les tenues volontairement sombres utilisant 1 à 2 indices noirs. + * **Garde Anti-Masque Chroma & Anti-Dégradé Monochrome Toutes Teintes :** Rejette les fuites de fond chroma (`> 3 %` magenta/vert/cyan purs) et les dégradés d'effets néon à teinte unique sans pénaliser les costumes 1P chauds Rouge/Orange + Peau naturelle. + * **Filtrage des Helpers Déportés & Cut-Ins Plein Écran :** La sélection de `special1..3` et `super1..3` écarte les projectiles purement additifs (`blend = A/S`), les helpers invisibles `1x1` et les écrans de super plein écran `320x240` / `640x480`. --- diff --git a/tools/mugen_extractor/mugen_extractor.py b/tools/mugen_extractor/mugen_extractor.py index c159930d..6b208309 100644 --- a/tools/mugen_extractor/mugen_extractor.py +++ b/tools/mugen_extractor/mugen_extractor.py @@ -46,6 +46,7 @@ def __init__(self, char_dir): self.air_file = None self.cns_files = [] self.palettes = {} # slot_int (1..12) -> absolute_path + self.all_def_palettes = [] # ordered list of (slot_int, absolute_path) self.def_path = None self.parse() @@ -58,7 +59,8 @@ def parse(self): def score_def(p): base = os.path.splitext(os.path.basename(p))[0].lower() if base == char_name.lower(): return 0 - if any(k in base for k in ['intro', 'select', 'menu', 'opt', 'cursor', 'stage']): return 99 + if any(k in base for k in ['intro', 'select', 'menu', 'opt', 'cursor', 'stage', 'ending']): return 99 + if any(base.endswith(suf) for suf in ['_ex', '_boss', '_ai', '_normal', '-ex']): return 40 return 10 candidate_defs.sort(key=score_def) @@ -108,7 +110,10 @@ def score_def(p): if slot_str.isdigit(): p = find_file_case_insensitive(self.char_dir, v) if p and os.path.isfile(p): - self.palettes[int(slot_str)] = p + slot_num = int(slot_str) + self.palettes[slot_num] = p + if (slot_num, p) not in self.all_def_palettes: + self.all_def_palettes.append((slot_num, p)) class CnsParser: """ @@ -247,26 +252,48 @@ def is_rle_garbage(pal_bytes): return True return False +def decode_mugen_act(raw_bytes): + """ + Decode a MUGEN .act palette file following the official Elecbyte / Ikemen-GO specification: + Up to 256 RGB triplets (first 768 bytes) are mapped in reverse index order: + entry i in the .act file corresponds to sprite palette index (255 - i). + """ + if not raw_bytes or len(raw_bytes) < 48: + return None + data = raw_bytes[:768] + count = len(data) // 3 + pal = bytearray(768) + for i in range(count): + dst = (255 - i) * 3 + src = i * 3 + pal[dst:dst + 3] = data[src:src + 3] + return bytes(pal) + + class SFFv1Parser: def __init__(self, filepath): self.filepath = filepath self.images = {} + self.initial_palette = None # palette from sprite #0 (shared SFFv1 base location) self.first_palette = None - self.stand_palette = None # palette from group 0, image 0 - self.candidate_palettes = [] # list of (source_name, 768_bytes) + self.stand_palette = None # effective palette of stance sprite (0,0) following same_pal + self.candidate_palettes = [] # list of (source_name, 768_bytes) self.parse() def parse(self): seen_pals = set() + sprite_list = [] with open(self.filepath, 'rb') as f: header = f.read(512) if not header.startswith(b'ElecbyteSpr'): return + # Ensure SFFv1 header layout (SFFv2 has version[3] == 2 at offset 15) + if len(header) >= 16 and header[15] not in (0, 1): return num_images = struct.unpack(' 0: pcx_data = f.read(data_length) - # A PCX 256-color palette MUST have the 0x0C (12) marker at offset -769 and not be RLE garbage + # A PCX 256-color palette has the 0x0C (12) marker at offset -769 (or sprite #0 legacy tail) if len(pcx_data) > 769 and pcx_data[-769] == 12: - pal = pcx_data[-768:] - if not is_rle_garbage(pal): - if not self.first_palette and grp < 9000: - self.first_palette = pal - if grp == 0 and not self.stand_palette: - self.stand_palette = pal - # Master character palettes come from stance (grp 0), portraits (grp 9000 img 0/1) or first valid sprite - if (grp == 0 or (grp == 9000 and img in (0, 1)) or not self.candidate_palettes) and pal not in seen_pals: - seen_pals.add(pal) - self.candidate_palettes.append((f"SFF({grp},{img})", pal)) - + cand_pal = pcx_data[-768:] + if not is_rle_garbage(cand_pal): + own_pal = cand_pal + elif idx == 0 and len(pcx_data) >= 768: + cand_pal = pcx_data[-768:] + if not is_rle_garbage(cand_pal): + own_pal = cand_pal + + if idx == 0 and own_pal is not None: + self.initial_palette = own_pal + + if own_pal is not None and (idx == 0 or same_pal == 0): + if not self.first_palette and grp < 9000: + self.first_palette = own_pal + if (grp == 0 or (grp == 9000 and img in (0, 1)) or not self.candidate_palettes) and own_pal not in seen_pals: + seen_pals.add(own_pal) + self.candidate_palettes.append((f"SFF({grp},{img})", own_pal)) + elif 0 <= prev < len(sprite_list): + # Linked SFFv1 sprite reuses the pixel buffer of sprite_list[prev] + pcx_data = sprite_list[prev] + + sprite_list.append(pcx_data) + + # Resolve effective stance (grp 0) palette following Elecbyte / Ikemen-GO sffv1PalState: + # If (0,0) has same_pal != 0 (shared), it inherits sprite #0's initial_palette! + if grp == 0 and self.stand_palette is None: + if same_pal == 0 and own_pal is not None: + self.stand_palette = own_pal + elif self.initial_palette is not None: + self.stand_palette = self.initial_palette + elif own_pal is not None: + self.stand_palette = own_pal + + if pcx_data and (grp, img) not in self.images: self.images[(grp, img)] = { 'x': x, 'y': y, @@ -344,8 +396,11 @@ def parse(self): def score_palette(pal_bytes, indices, trans_idx=0): """ - Score how well a 768-byte palette renders a sprite given its pixel indices. - Returns a float score in [0..50] for valid palettes, or -9999.0 if rejected. + Score how well a 768-byte palette renders a character's body sprites given pixel indices. + Detects index collapse (multiple distinct sprite indices mapping to zero/fill triplets), + chroma-key masks, and single-hue monochromatic ramps across ALL hues (red, yellow, green, + cyan, blue, magenta). + Returns a float quality score in [0..55] for valid palettes, or -9999.0 if rejected. """ if not pal_bytes or len(pal_bytes) < 768: return -9999.0 @@ -359,111 +414,180 @@ def score_palette(pal_bytes, indices, trans_idx=0): trans_set = {0} if trans_idx is not None: trans_set.add(trans_idx) - # If index 255 is a pure chroma key background mask, treat as transparent - if len(pal_bytes) >= 768: - r255, g255, b255 = pal_bytes[765], pal_bytes[766], pal_bytes[767] - if (r255, g255, b255) in [(255, 0, 255), (0, 255, 255), (0, 255, 0)]: - trans_set.add(255) - used_indices = [idx for idx in indices if idx not in trans_set] + used_indices = [idx for idx in indices if isinstance(idx, int) and idx not in trans_set] if not used_indices: return -9999.0 unique_indices = set(used_indices) - colors = set() + idx_to_rgb = {} + for idx in unique_indices: + if idx * 3 + 2 < len(pal_bytes): + idx_to_rgb[idx] = (pal_bytes[idx * 3], pal_bytes[idx * 3 + 1], pal_bytes[idx * 3 + 2]) + + if not idx_to_rgb: + return -9999.0 + + colors = set(idx_to_rgb.values()) + u_colors = len(colors) + n_unique_idx = len(idx_to_rgb) + + # 1. Hard rejection for solid monochrome or severe index collapse + # (e.g. 15 distinct sprite indices collapsing onto <= 4 fill colors) + if u_colors <= 2 and n_unique_idx > 2: + return -9999.0 + if n_unique_idx >= 6 and (u_colors / n_unique_idx) < 0.35: + return -9999.0 + + # Check how many distinct indices collapse onto pure (0,0,0) or onto a single identical fill triplet + zero_idx_count = sum(1 for rgb in idx_to_rgb.values() if rgb == (0, 0, 0)) + rgb_idx_counts = {} + for rgb in idx_to_rgb.values(): + rgb_idx_counts[rgb] = rgb_idx_counts.get(rgb, 0) + 1 + + total = len(used_indices) total_lum = 0.0 - neon_count = 0 + total_lum_sq = 0.0 + chroma_mask_count = 0 black_count = 0 - total = len(used_indices) - - skin_pixel_count = 0 neutral_pixel_count = 0 - blue_purple_count = 0 - green_count = 0 - + skin_pixel_count = 0 + dark_anchor_count = 0 + bright_anchor_count = 0 + hue_bins = [0] * 12 # 12 x 30-degree HSV hue sectors + chromatic_sat_sum = 0.0 + chromatic_count = 0 + color_pixel_counts = {} + for idx in used_indices: - if not isinstance(idx, int): + rgb = idx_to_rgb.get(idx) + if rgb is None: continue - if idx * 3 + 2 < len(pal_bytes): - r, g, b = pal_bytes[idx * 3], pal_bytes[idx * 3 + 1], pal_bytes[idx * 3 + 2] - colors.add((r, g, b)) - total_lum += (0.299 * r + 0.587 * g + 0.114 * b) - # Pure black - if r == 0 and g == 0 and b == 0: - black_count += 1 - # Pure neon / chroma key masks (e.g. pure magenta, pure green, screaming cyan/yellow) - if (r >= 190 and g <= 15 and b >= 190) or \ - (r <= 15 and g >= 190 and b <= 15) or \ - (r <= 15 and g >= 235 and b >= 235) or \ - (r >= 235 and g >= 235 and b <= 15): - neon_count += 1 - - # Classify neutral vs chromatic pixels - if (r < 25 and g < 25 and b < 25) or (r > 230 and g > 230 and b > 230) or (abs(r-g)<15 and abs(g-b)<15 and abs(r-b)<15): - neutral_pixel_count += 1 - else: - h, s, v = colorsys.rgb_to_hsv(r/255.0, g/255.0, b/255.0) - if s > 0.15 and v > 0.15: - hue_deg = h * 360.0 - # Warm skin / flesh tone range (10° to 45°, R > G > B) - if 10.0 <= hue_deg <= 45.0 and r > g >= b: - skin_pixel_count += 1 - elif 180.0 <= hue_deg <= 320.0: - blue_purple_count += 1 - elif 70.0 <= hue_deg <= 165.0: - green_count += 1 - - u_colors = len(colors) - if u_colors <= 2 and len(unique_indices) > 2: - return -9999.0 # Solid monochrome / broken empty palette - - neon_ratio = neon_count / total + r, g, b = rgb + color_pixel_counts[rgb] = color_pixel_counts.get(rgb, 0) + 1 + lum = 0.299 * r + 0.587 * g + 0.114 * b + total_lum += lum + total_lum_sq += lum * lum + + if r == 0 and g == 0 and b == 0: + black_count += 1 + if lum < 65.0: + dark_anchor_count += 1 + elif lum > 145.0: + bright_anchor_count += 1 + + # Pure MUGEN chroma-key background masks: pure magenta, pure green, pure cyan + # (Note: bright yellow (255,255,0) is legitimate for hair/visors/armor and is NOT a chroma mask) + if (r >= 220 and g <= 15 and b >= 220) or \ + (r <= 15 and g >= 220 and b <= 15) or \ + (r <= 15 and g >= 240 and b >= 240): + chroma_mask_count += 1 + + # Classify neutral (achromatic outlines/whites/greys/blacks) vs chromatic pixels + if (r < 28 and g < 28 and b < 28) or (r > 232 and g > 232 and b > 232) or \ + (abs(r - g) < 16 and abs(g - b) < 16 and abs(r - b) < 16): + neutral_pixel_count += 1 + else: + h, s, v = colorsys.rgb_to_hsv(r / 255.0, g / 255.0, b / 255.0) + if s > 0.20 and v > 0.16: + b_idx = int(h * 12.0) % 12 + hue_bins[b_idx] += 1 + chromatic_count += 1 + chromatic_sat_sum += s + hue_deg = h * 360.0 + if 10.0 <= hue_deg <= 42.0 and r > g >= b and 0.20 <= s <= 0.78 and v >= 0.35: + skin_pixel_count += 1 + + chroma_mask_ratio = chroma_mask_count / total black_ratio = black_count / total - - # Reject palettes with excessive pure neon chroma masks (> 3% of body pixels) - if neon_ratio > 0.03: + neutral_ratio = neutral_pixel_count / total + chrom_ratio = chromatic_count / total + + # 2. Reject palettes with chroma-key background leaks (> 3% pure magenta/green/cyan) + if chroma_mask_ratio > 0.03: return -9999.0 - - # Reject palettes where > 80% of body pixels map to pure black or monochrome empty ACT - if (black_ratio > 0.85 or (black_ratio > 0.70 and u_colors <= 3)) and len(unique_indices) >= 5: + + # 3. Reject unpopulated zero-padding collapse while preserving intentional dark outfits + # (Intentional black outfits map 1-2 black indices; broken palettes collapse >= 4 indices onto (0,0,0)) + if (zero_idx_count >= 4 and black_ratio > 0.32) or (black_ratio > 0.82 and n_unique_idx >= 5): return -9999.0 - - non_neutral = total - neutral_pixel_count - # Monochromatic wash filter: If > 80% of chromatic pixels are a single blue/purple/green wash with zero skin tones - if non_neutral > 0 and skin_pixel_count == 0 and u_colors >= 6: - if (blue_purple_count / non_neutral) > 0.80 or (green_count / non_neutral) > 0.80: + + # Reject non-zero fill padding collapse (>= 4 distinct indices mapping to the exact same color on > 40% of body) + for rgb, idx_cnt in rgb_idx_counts.items(): + if idx_cnt >= 4 and (color_pixel_counts.get(rgb, 0) / total) > 0.40: return -9999.0 - + + # 4. All-hue monochromatic ramp detection (catches 15-shade yellow/red/cyan/blue FX gradients + # without penalizing legitimate warm Red/Orange + natural Skin 1P outfits) + mono_penalty = 0.0 + distinct_hue_families = 0 + if chromatic_count > 0: + max_2bin = max(hue_bins[i] + hue_bins[(i + 1) % 12] for i in range(12)) + max_band_ratio = max_2bin / chromatic_count + avg_sat = chromatic_sat_sum / chromatic_count + distinct_hue_families = sum(1 for c in hue_bins if (c / chromatic_count) >= 0.06) + + if max_band_ratio > 0.94 and n_unique_idx >= 5: + # Pure hyper-saturated neon ramp (avg_sat > 0.92 with almost no neutral outlines) + if avg_sat > 0.92 and neutral_ratio < 0.08: + return -9999.0 + # Washed-out monochrome ramp with zero warm skin tones (e.g. all-blue, all-green, all-cyan, blown-out yellow) + if skin_pixel_count == 0 and neutral_ratio < 0.18: + if max_band_ratio > 0.98 and neutral_ratio < 0.06: + return -9999.0 + mono_penalty = 35.0 + elif max_band_ratio > 0.88 and neutral_ratio < 0.18 and distinct_hue_families <= 1 and skin_pixel_count == 0: + mono_penalty = 25.0 + avg_lum = total_lum / total - - # Quality score bounded in [0..50] - coverage = min(1.0, u_colors / max(len(unique_indices), 1)) - score = coverage * 35.0 - - if 15 <= avg_lum <= 215: - score += 15.0 - elif avg_lum < 10 or avg_lum > 240: + lum_var = max(0.0, (total_lum_sq / total) - (avg_lum * avg_lum)) + lum_std = lum_var ** 0.5 + + # 5. Composite perceptual quality score bounded in [0..32] + coverage = min(1.0, u_colors / max(n_unique_idx, 1)) + score = coverage * 18.0 + + # Multi-hue richness & natural skin anchoring + score += min(3, distinct_hue_families) * 2.5 + if skin_pixel_count > 0 and (0.04 <= (skin_pixel_count / total) <= 0.75): + score += 3.5 + + # Contrast & exposure bonus for crisp LED matrix rendering + if 20.0 <= avg_lum <= 210.0: + score += 4.0 + elif avg_lum < 12.0 or avg_lum > 225.0: score -= 20.0 - - return score + + if lum_std >= 32.0 and dark_anchor_count > 0 and bright_anchor_count > 0: + score += 3.0 + + return score - mono_penalty + + +def _palettes_match_on_indices(pal_a, pal_b, unique_indices): + if not pal_a or not pal_b or len(pal_a) < 768 or len(pal_b) < 768 or not unique_indices: + return False + matches = 0 + checked = 0 + for idx in unique_indices: + if idx > 0 and idx * 3 + 2 < 768: + checked += 1 + if pal_a[idx * 3 : idx * 3 + 3] == pal_b[idx * 3 : idx * 3 + 3]: + matches += 1 + return checked > 0 and (matches / checked) >= 0.90 + def resolve_master_palette(char_dir, sff, def_parser=None): """ - Resolve the best palette for a character using the Unified MUGEN Palette Theorem & Reciprocal. - - Authority Hierarchy: - 1. DEF pal1 / 1P official palette (+150) - 2. SFF Stand Palette (group 0 with 0x0C marker) - Canonical internal sprite palette (+120) - 3. DEF pal.defaults (+110) - 4. Other DEF pal slots (+100) - 5. SFF First Palette (+80) - 6. SFF Big Portrait (9000,1) (+40 - fallback only) - 7. SFF Small Portrait (9000,0) and other sprites (+20) - 8. Character folder .act palettes (+10) + Resolve the authentic 1P master palette for a MUGEN character: + - Decodes external .act files using Elecbyte / Ikemen-GO reverse index order (dest = 255 - i) + - Honors explicit canonical 1P filenames (Normal/Default/Classic/Original), pal.defaults, + Capcom 6-button LP (pal4 = *01.act) conventions, and SFFv1 shared stance palette consensus + - Validates candidates across multiple body frames (stance + walk + attack) """ char_name = os.path.basename(char_dir) - # Priority order for reference sprite: (0,0), then other (0,x), (5,x), (10,x), (20,x), then any < 9000 + # Sample pixel indices across stance (0,0) + walk/attack body sprites for robust multi-pose validation candidate_keys = [] if (0, 0) in sff.images: candidate_keys.append((0, 0)) @@ -475,8 +599,8 @@ def resolve_master_palette(char_dir, sff, def_parser=None): candidate_keys.append(k) best_indices = [] - best_key = None - max_unique = 0 + sampled_poses = 0 + anchor_band = None for k in candidate_keys: info = sff.images[k] @@ -484,22 +608,29 @@ def resolve_master_palette(char_dir, sff, def_parser=None): im = Image.open(io.BytesIO(info['data'])) im.load() ind = list(im.get_flattened_data()) if hasattr(im, 'get_flattened_data') else list(im.getdata()) - # If sprite is truecolor tuples, return SFF palette directly if ind and isinstance(ind[0], (tuple, list)): return sff.stand_palette or sff.first_palette or (b'\x00' * 768) - u = len(set(ind) - {0}) - if u > max_unique: - max_unique = u - best_key = k - best_indices = ind - if u >= 10: # Sufficient complexity body sprite + non_zero = [x for x in ind if isinstance(x, int) and x != 0] + u_set = set(non_zero) + if len(u_set) >= 6: + if anchor_band is None: + anchor_band = u_set + best_indices.extend(ind) + sampled_poses += 1 + elif len(u_set & anchor_band) >= max(2, int(len(anchor_band) * 0.4)) and k[0] in (20, 21, 200, 210): + best_indices.extend(ind) + sampled_poses += 1 + if sampled_poses >= 3: break + elif not best_indices and u_set: + best_indices = list(ind) except: pass if not best_indices: return sff.stand_palette or sff.first_palette or (b'\x00' * 768) - + + unique_used = {x for x in best_indices if isinstance(x, int) and x != 0} candidates = [] seen = set() @@ -510,65 +641,90 @@ def add_cand(name, p_bytes, bonus): if p_slice not in seen: seen.add(p_slice) candidates.append((name, p_slice, bonus)) - - # 1. DEF Official Palettes (pal1: +150, pal.defaults: +110, other slots: +100) - if def_parser and def_parser.palettes: - if 1 in def_parser.palettes and os.path.exists(def_parser.palettes[1]): - try: - with open(def_parser.palettes[1], 'rb') as f: - d = f.read(768) - if len(d) == 768: - add_cand(f"DEF(pal1: {os.path.basename(def_parser.palettes[1])})", d, 150.0) - except: - pass - for slot in def_parser.pal_defaults: - if slot != 1 and slot in def_parser.palettes and os.path.exists(def_parser.palettes[slot]): - try: - with open(def_parser.palettes[slot], 'rb') as f: - d = f.read(768) - if len(d) == 768: - add_cand(f"DEF(pal{slot}:default)", d, 110.0) - except: - pass - for slot in sorted(def_parser.palettes.keys()): - if slot != 1 and slot not in def_parser.pal_defaults: - p = def_parser.palettes[slot] - if os.path.exists(p): - try: - with open(p, 'rb') as f: - d = f.read(768) - if len(d) == 768: - add_cand(f"DEF(pal{slot})", d, 100.0) - except: - pass - - # 2. SFF Canonical Stand Palette (group 0 with 0x0C marker) (+120) + + def read_act_pair(path): + try: + with open(path, 'rb') as f: + raw = f.read(1024) + rev = decode_mugen_act(raw) + fwd = raw[:768] if len(raw) >= 768 else None + return rev, fwd + except: + return None, None + + canonical_1p_stems = ('normal', 'default', 'classic', 'original') + fallback_fwd_cands = [] + + if def_parser and (def_parser.palettes or getattr(def_parser, 'all_def_palettes', None)): + by_slot = def_parser.palettes + all_entries = getattr(def_parser, 'all_def_palettes', None) or list(sorted(by_slot.items())) + + # 1. Explicit canonical 1P filename in DEF (e.g. Normal.act, Default.act, Classic.act, Original.act, CammyDefault.act) (+220) + for slot, p in all_entries: + stem = os.path.splitext(os.path.basename(p))[0].lower() + if stem in canonical_1p_stems or any(stem.endswith(kw) for kw in canonical_1p_stems): + rev, fwd = read_act_pair(p) + add_cand(f"DEF(1P:{os.path.basename(p)})", rev, 220.0) + if fwd: + fallback_fwd_cands.append((f"DEF_FWD(1P:{os.path.basename(p)})", fwd, 30.0)) + + # 2. SFF(stand) == DEF(pal1) 2-of-2 consensus when pal.defaults was customized to a high slot (+215) + if 1 in by_slot and sff.stand_palette: + rev1, _ = read_act_pair(by_slot[1]) + pd0 = def_parser.pal_defaults[0] if def_parser.pal_defaults else None + if rev1 and pd0 not in (None, 1, 4) and _palettes_match_on_indices(rev1, sff.stand_palette, unique_used): + add_cand(f"DEF(pal1==SFF:{os.path.basename(by_slot[1])})", rev1, 215.0) + + # 3. Capcom 6-button LP=pal4 convention when pal.defaults is omitted or left at [1,2,3...] + # while pal1 is *04.act / *4.act (LK alt) and pal4 is *01.act / .act (LP 1P) (+210) + if 4 in by_slot: + n4 = os.path.splitext(os.path.basename(by_slot[4]))[0].lower() + n1 = os.path.splitext(os.path.basename(by_slot[1]))[0].lower() if 1 in by_slot else "" + pd0 = def_parser.pal_defaults[0] if def_parser.pal_defaults else None + if (pd0 is None and n4.endswith('01')) or \ + (pd0 == 1 and (n1.endswith('04') or n1.endswith('4')) and (n4.endswith('01') or not any(c.isdigit() for c in n4))): + rev4, fwd4 = read_act_pair(by_slot[4]) + add_cand(f"DEF(pal4_1P:{os.path.basename(by_slot[4])})", rev4, 210.0) + if fwd4: + fallback_fwd_cands.append((f"DEF_FWD(pal4:{os.path.basename(by_slot[4])})", fwd4, 28.0)) + + # 4. Author's pal.defaults order (primary 1P slot +200; secondary defaults +150 so alts never override valid 1P) + for idx_d, slot in enumerate(def_parser.pal_defaults): + if slot in by_slot: + rev, fwd = read_act_pair(by_slot[slot]) + bonus = 200.0 if idx_d == 0 else 150.0 + add_cand(f"DEF(pal{slot}:default:{os.path.basename(by_slot[slot])})", rev, bonus) + if fwd: + fallback_fwd_cands.append((f"DEF_FWD(pal{slot}:default)", fwd, 25.0)) + + # 5. Remaining non-default DEF alt slots (+120..+130 — only win if 1P default & SFF are invalid) + for slot, p in all_entries: + rev, fwd = read_act_pair(p) + slot_bonus = 130.0 if slot in (1, 4) else 120.0 + add_cand(f"DEF(pal{slot}:{os.path.basename(p)})", rev, slot_bonus) + if fwd: + fallback_fwd_cands.append((f"DEF_FWD(pal{slot})", fwd, 20.0)) + + # 6. SFF Canonical Stand Palette (group 0 or inherited sprite #0 shared palette) (+196) if sff.stand_palette: - add_cand("SFF(stand)", sff.stand_palette, 120.0) + add_cand("SFF(stand)", sff.stand_palette, 196.0) - # 3. SFF First Palette (+80) + # 7. SFF First Body Palette (+95) & Candidate SFF Palettes (+65..+80) if sff.first_palette: - add_cand("SFF(first)", sff.first_palette, 80.0) - - # 4. SFF Big Portrait (9000,1) (+40 - fallback only) + add_cand("SFF(first)", sff.first_palette, 95.0) for cname, pdata in sff.candidate_palettes: - if "9000,1" in cname: - add_cand(cname, pdata, 40.0) + add_cand(cname, pdata, 80.0 if "9000,1" in cname else 65.0) - # 5. SFF Small Portrait (9000,0) and other valid SFF sprites (+20) - for cname, pdata in sff.candidate_palettes: - if "9000,1" not in cname: - add_cand(cname, pdata, 20.0) - - # 6. Additional .act in char folder (+10) - for af in glob.glob(os.path.join(char_dir, "*.act")) + glob.glob(os.path.join(char_dir, "*.ACT")): - try: - with open(af, "rb") as f: - d = f.read(768) - if len(d) == 768: - add_cand(f"ACT({os.path.basename(af)})", d, 10.0) - except: - pass + # 8. Additional .act files in character folder (+70 reversed, +15 forward fallback) + for af in sorted(glob.glob(os.path.join(char_dir, "*.act")) + glob.glob(os.path.join(char_dir, "*.ACT"))): + rev, fwd = read_act_pair(af) + add_cand(f"ACT({os.path.basename(af)})", rev, 70.0) + if fwd: + fallback_fwd_cands.append((f"ACT_FWD({os.path.basename(af)})", fwd, 15.0)) + + # 9. Non-standard forward-ordered .act fallbacks (only win if all canonical MUGEN palettes fail) + for fname, fpal, fbonus in fallback_fwd_cands: + add_cand(fname, fpal, fbonus) if not candidates: return sff.stand_palette or sff.first_palette or (b'\x00' * 768) @@ -730,18 +886,93 @@ def process_character(char_dir, out_dir, target_height=None, extract_mode=None, if win_anim_id is not None: required_anims[win_anim_id] = 'win' + # Collect reference body pixel indices and stance dimensions from stand/walk so special/super + # selection and Pass 1 skip disembodied MUGEN Helpers, projectiles, and 320x240/640x480 fullscreen cut-ins + body_ref_indices = set() + ref_stand_w, ref_stand_h = 0, 0 + for base_aid in [a for a, n in required_anims.items() if n in ('stand', 'walk')]: + for fr in air.animations.get(base_aid, [])[:8]: + if (fr['grp'], fr['img']) in sff.images: + try: + im_b = Image.open(io.BytesIO(sff.images[(fr['grp'], fr['img'])]['data'])) + ref_stand_w = max(ref_stand_w, im_b.width) + ref_stand_h = max(ref_stand_h, im_b.height) + ind_b = list(im_b.get_flattened_data()) if hasattr(im_b, 'get_flattened_data') else list(im_b.getdata()) + body_ref_indices.update(x for x in ind_b if isinstance(x, int) and x != 0) + except: + pass + + max_allowed_frame_w = max(280, int(ref_stand_w * 3.0)) if ref_stand_w > 0 else 400 + max_allowed_frame_h = max(240, int(ref_stand_h * 2.6)) if ref_stand_h > 0 else 320 + + def is_body_animation(act_id): + frs = air.animations.get(act_id) + if not frs: + return False + sff_frs = [fr for fr in frs if (fr['grp'], fr['img']) in sff.images] + if not sff_frs: + return False + # Reject pure additive/subtractive FX animations (100% blend='A'/'S' beams, sparks, slashes) + non_blend_frs = [fr for fr in sff_frs if not fr.get('blend', '').startswith(('A', 'S'))] + if not non_blend_frs: + return False + anim_indices = set() + max_w, max_h = 0, 0 + kept_body_frames = 0 + has_truecolor = False + nz_pixels = 0 + black_pixels = 0 + black_collapse_indices = set() + for fr in non_blend_frs[:12]: + try: + im_c = Image.open(io.BytesIO(sff.images[(fr['grp'], fr['img'])]['data'])) + if im_c.width > max_allowed_frame_w or im_c.height > max_allowed_frame_h: + continue + kept_body_frames += 1 + max_w = max(max_w, im_c.width) + max_h = max(max_h, im_c.height) + ind_c = list(im_c.get_flattened_data()) if hasattr(im_c, 'get_flattened_data') else list(im_c.getdata()) + if ind_c and isinstance(ind_c[0], (tuple, list)): + has_truecolor = True + else: + for x in ind_c: + if isinstance(x, int) and x != 0: + anim_indices.add(x) + nz_pixels += 1 + if x * 3 + 2 < len(master_palette) and ( + master_palette[x * 3], + master_palette[x * 3 + 1], + master_palette[x * 3 + 2], + ) == (0, 0, 0): + black_pixels += 1 + black_collapse_indices.add(x) + except: + pass + # Reject invisible 1x1 / tiny helper dummy sprites or purely fullscreen cut-in actions + if kept_body_frames == 0 or max_w < 8 or max_h < 12: + return False + if not has_truecolor: + # Reject separate-palette Helper animations whose indices collapse onto unallocated (0,0,0) slots + if nz_pixels > 0 and len(black_collapse_indices) >= 4 and (black_pixels / nz_pixels) > 0.60: + return False + if body_ref_indices: + overlap = len(anim_indices & body_ref_indices) + if overlap < min(2, len(body_ref_indices)) or (overlap / max(1, len(body_ref_indices))) < 0.20: + return False + return True + # 7. Specials (Primary: CNS States 1000..2999 -> Heuristic: 1000..2999) special_count = 0 for st_id in range(1000, 3000): for a_id in cns.state_anims.get(st_id, []): - if a_id in air.animations and a_id not in required_anims and len(air.animations[a_id]) > 0: + if a_id in air.animations and a_id not in required_anims and is_body_animation(a_id): special_count += 1 required_anims[a_id] = f'special{special_count}' if special_count >= 3: break if special_count >= 3: break if special_count < 3: for act_id in range(1000, 3000): - if act_id in air.animations and act_id not in required_anims and len(air.animations[act_id]) > 0: + if act_id in air.animations and act_id not in required_anims and is_body_animation(act_id): special_count += 1 required_anims[act_id] = f'special{special_count}' if special_count >= 3: break @@ -750,14 +981,14 @@ def process_character(char_dir, out_dir, target_height=None, extract_mode=None, super_count = 0 for st_id in range(3000, 5000): for a_id in cns.state_anims.get(st_id, []): - if a_id in air.animations and a_id not in required_anims and len(air.animations[a_id]) > 0: + if a_id in air.animations and a_id not in required_anims and is_body_animation(a_id): super_count += 1 required_anims[a_id] = f'super{super_count}' if super_count >= 3: break if super_count >= 3: break if super_count < 3: for act_id in range(3000, 5000): - if act_id in air.animations and act_id not in required_anims and len(air.animations[act_id]) > 0: + if act_id in air.animations and act_id not in required_anims and is_body_animation(act_id): super_count += 1 required_anims[act_id] = f'super{super_count}' if super_count >= 3: break @@ -779,6 +1010,12 @@ def process_character(char_dir, out_dir, target_height=None, extract_mode=None, img_info = sff.images[(f['grp'], f['img'])] try: img_obj = Image.open(io.BytesIO(img_info['data'])) + + # Skip 320x240 / 640x480 fullscreen super cut-in / stage blackout background sprites + if anim_name not in ('stand', 'walk') and ( + img_obj.width > max_allowed_frame_w or img_obj.height > max_allowed_frame_h + ): + continue # Apply flip if specified in .air flip = f.get('flip', '') @@ -789,10 +1026,29 @@ def process_character(char_dir, out_dir, target_height=None, extract_mode=None, elif 'V' in flip: img_obj = img_obj.transpose(Image.Transpose.FLIP_TOP_BOTTOM) - # Detect broken palettes (solid silhouettes with <= 2 colors including transparency) - colors = img_obj.convert('RGB').getcolors(256) - if colors is not None and len(colors) <= 2: + raw_ind = list(img_obj.get_flattened_data()) if hasattr(img_obj, 'get_flattened_data') else list(img_obj.getdata()) + if not raw_ind: continue + if isinstance(raw_ind[0], (tuple, list)): + colors = img_obj.convert('RGB').getcolors(256) + if colors is not None and len(colors) <= 2: + continue + else: + frame_nz = {int(v) for v in raw_ind if int(v) != 0} + if not frame_nz: + continue + # Skip disembodied additive/subtractive FX flash frames inserted mid-animation + if f.get('blend', '').startswith(('A', 'S')) and body_ref_indices and not (frame_nz & body_ref_indices): + continue + mapped_cols = { + (master_palette[idx * 3], master_palette[idx * 3 + 1], master_palette[idx * 3 + 2]) + for idx in frame_nz + if idx * 3 + 2 < len(master_palette) + and (master_palette[idx * 3], master_palette[idx * 3 + 1], master_palette[idx * 3 + 2]) + not in ((0, 0, 0), (255, 0, 255), (0, 255, 255), (0, 255, 0)) + } + if len(mapped_cols) < 2 and len(frame_nz) > 2: + continue except Exception as e: continue @@ -804,7 +1060,12 @@ def process_character(char_dir, out_dir, target_height=None, extract_mode=None, max_x = img_obj.width - ox max_y = img_obj.height - oy - # Skip crazy frames (projectiles far away) + # Skip crazy off-screen helper/projectile coordinates + if anim_name not in ('stand', 'walk') and ( + min_x < -max_allowed_frame_w or min_y < -max_allowed_frame_h + or max_x > max_allowed_frame_w or max_y > max_allowed_frame_h + ): + continue if min_x < -1000 or min_y < -1000 or max_x > 1000 or max_y > 1000: continue @@ -992,7 +1253,7 @@ def process_character(char_dir, out_dir, target_height=None, extract_mode=None, if orig_w != canvas_w or orig_h != canvas_h: rgba_canvas = rgba_canvas.resize((canvas_w, canvas_h), Image.Resampling.NEAREST) - cropped_data = rgba_canvas.getdata() + cropped_data = rgba_canvas.get_flattened_data() if hasattr(rgba_canvas, 'get_flattened_data') else rgba_canvas.getdata() for r, g, b, a in cropped_data: if a < 128: f.write(struct.pack('