-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathtexture_analyzer.py
More file actions
1567 lines (1284 loc) · 69.5 KB
/
texture_analyzer.py
File metadata and controls
1567 lines (1284 loc) · 69.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Habilitar referencias adelantadas en anotaciones de tipo
from __future__ import annotations
import os
import re
import json
import struct
import shutil
import binascii
import importlib.util
import subprocess
import sys
import time
import tempfile
import glob
from typing import Dict, List, Set, Tuple, Optional, Any
from pathlib import Path
import logging
import argparse
# Global para indicar si ssbh_data_py está disponible
SSBH_DATA_PY_AVAILABLE = None
def install_ssbh_data_py() -> bool:
"""Instala la biblioteca ssbh_data_py si no está disponible"""
try:
import ssbh_data_py
return True
except ImportError:
print("Instalando la biblioteca ssbh_data_py...")
try:
subprocess.check_call([sys.executable, "-m", "pip", "install", "ssbh_data_py"])
return True
except Exception as e:
print(f"Error al instalar ssbh_data_py: {e}")
return False
def check_ssbh_data_py_available() -> bool:
"""Comprueba si ssbh_data_py está disponible"""
global SSBH_DATA_PY_AVAILABLE
if SSBH_DATA_PY_AVAILABLE is None:
try:
import ssbh_data_py
SSBH_DATA_PY_AVAILABLE = True
except ImportError:
SSBH_DATA_PY_AVAILABLE = False
return SSBH_DATA_PY_AVAILABLE
def try_read_matl_with_ssbh(file_path: str) -> List[TextureReference]:
"""
Intenta leer un archivo .numatb usando ssbh_data_py y devuelve una lista de referencias a texturas.
"""
if not check_ssbh_data_py_available():
return []
try:
import ssbh_data_py
matl = ssbh_data_py.matl_data.read_matl(file_path)
references = []
for entry in matl.entries:
material_label = entry.material_label
for texture in entry.textures:
# Convertir ParamId a string para mejor legibilidad
param_id = str(texture.param_id)
texture_path = texture.data
ref = TextureReference(
texture_path=texture_path,
parameter_name=param_id,
material_label=material_label,
file_path=file_path
)
references.append(ref)
return references
except Exception as e:
print(f"Error al leer {file_path} con ssbh_data_py: {e}")
return []
def try_read_anim_with_ssbh(file_path: str) -> Dict[str, Any]:
"""
Intenta leer un archivo .nuanmb usando ssbh_data_py y devuelve la información de animación.
"""
if not check_ssbh_data_py_available():
return {}
try:
import ssbh_data_py
print(f"Leyendo archivo de animación: {file_path}")
anim = ssbh_data_py.anim_data.read_anim(file_path)
# Crear un diccionario con la información disponible
anim_info = {
"name": os.path.basename(file_path),
"attributes": [],
"file_path": file_path
}
# Listar todos los atributos disponibles en este objeto
print(f"Extrayendo atributos de {os.path.basename(file_path)}...")
for attr_name in dir(anim):
if not attr_name.startswith("_"): # Ignorar atributos privados
try:
attr_value = getattr(anim, attr_name)
attr_type = type(attr_value).__name__
is_callable = callable(attr_value)
anim_info["attributes"].append(f"{attr_name}: {attr_type} {'(callable)' if is_callable else ''}")
# Guardar valores simples directamente
if not is_callable and attr_type in ["int", "float", "str", "bool"]:
anim_info[attr_name] = attr_value
print(f" - Atributo simple: {attr_name} = {attr_value}")
except Exception as e:
print(f" - Error al acceder a {attr_name}: {e}")
# Examinar la estructura de los grupos
if hasattr(anim, 'groups') and anim.groups:
print(f"Encontrados {len(anim.groups)} grupos de animación")
anim_info["groups"] = []
for i, group in enumerate(anim.groups):
group_info = {"index": i}
# Intentar extraer información básica del grupo
if hasattr(group, 'name'):
group_info["name"] = group.name
# Buscar referencias a materiales o texturas
materials_found = []
if hasattr(group, 'nodes'):
group_info["nodes"] = []
for node in group.nodes:
node_info = {}
if hasattr(node, 'name'):
node_info["name"] = node.name
# Buscar visibilidad de materiales
if hasattr(node, 'material_visibilities'):
node_info["material_visibilities"] = []
for mat_vis in node.material_visibilities:
if hasattr(mat_vis, 'material_name'):
mat_name = mat_vis.material_name
node_info["material_visibilities"].append(mat_name)
materials_found.append(mat_name)
group_info["nodes"].append(node_info)
# Añadir información de texturas o materiales encontrados
if materials_found:
group_info["materials_referenced"] = materials_found
anim_info["groups"].append(group_info)
# Examinar la estructura de los tracks o pistas
if hasattr(anim, 'tracks') and anim.tracks:
print(f"Encontrados {len(anim.tracks)} tracks de animación")
anim_info["tracks"] = []
for i, track in enumerate(anim.tracks):
track_info = {"index": i}
# Extraer atributos básicos del track
if hasattr(track, 'name'):
track_info["name"] = track.name
print(f" - Track: {track.name}")
# Examinar visibilidad de materiales
materials_found = []
if hasattr(track, 'material_visibility_entries') and track.material_visibility_entries:
track_info["material_visibility_entries"] = []
print(f" - Encontradas {len(track.material_visibility_entries)} entradas de visibilidad de materiales")
for entry in track.material_visibility_entries:
entry_info = {}
if hasattr(entry, 'name'):
entry_info["name"] = entry.name
materials_found.append(entry.name)
print(f" - Material: {entry.name}")
# Intentar obtener frames de visibilidad si existen
if hasattr(entry, 'visibility_frames'):
entry_info["frame_count"] = len(entry.visibility_frames)
track_info["material_visibility_entries"].append(entry_info)
# Reunir los materiales encontrados para facilidad de uso
if materials_found:
track_info["materials_referenced"] = materials_found
anim_info["tracks"].append(track_info)
return anim_info
except Exception as e:
print(f"Error al leer {file_path} con ssbh_data_py: {e}")
# Intentar método alternativo
try:
print(f"Intentando método alternativo para {file_path}...")
# Examinar el archivo binario para buscar nombres de materiales
with open(file_path, 'rb') as f:
data = f.read()
# Buscar posibles cadenas que parezcan nombres de materiales
material_pattern = re.compile(b'(def|mat)_[a-zA-Z0-9_]+')
matches = material_pattern.findall(data)
# Crear estructura simple
anim_info = {
"name": os.path.basename(file_path),
"method": "binary_search",
"possible_materials": [m.decode('utf-8', errors='ignore') for m in set(matches)]
}
return anim_info
except Exception as fallback_error:
print(f"Error también en método alternativo: {fallback_error}")
return {}
def convert_numatb_to_json(file_path: str, output_dir: str) -> Optional[str]:
"""
Convierte un archivo .numatb a JSON usando ssbh_data_py.
Args:
file_path: Ruta al archivo .numatb
output_dir: Directorio donde guardar el archivo JSON
Returns:
Ruta al archivo JSON o None si hubo un error
"""
if not check_ssbh_data_py_available():
print("ssbh_data_py no está disponible, no se puede convertir a JSON")
return None
try:
import ssbh_data_py
matl = ssbh_data_py.matl_data.read_matl(file_path)
materials = []
for entry in matl.entries:
material_info = {
"material_label": entry.material_label,
"shader_label": entry.shader_label,
"textures": []
}
# Extraer texturas
for texture in entry.textures:
# Convertir ParamId a string para hacerlo serializable
param_id_str = str(texture.param_id)
texture_info = {
"param_id": param_id_str,
"texture_path": texture.data
}
material_info["textures"].append(texture_info)
# Extraer otros parámetros si están disponibles
if hasattr(entry, 'vectors') and entry.vectors:
material_info["vectors"] = []
for vector in entry.vectors:
material_info["vectors"].append({
"param_id": str(vector.param_id),
"data": [vector.data.x, vector.data.y, vector.data.z, vector.data.w] if hasattr(vector.data, 'x') else str(vector.data)
})
if hasattr(entry, 'floats') and entry.floats:
material_info["floats"] = []
for float_param in entry.floats:
material_info["floats"].append({
"param_id": str(float_param.param_id),
"data": float_param.data
})
if hasattr(entry, 'booleans') and entry.booleans:
material_info["booleans"] = []
for bool_param in entry.booleans:
material_info["booleans"].append({
"param_id": str(bool_param.param_id),
"data": bool_param.data
})
# Agregar los samplers para análisis adicional
if hasattr(entry, 'samplers') and entry.samplers:
material_info["samplers"] = []
for sampler in entry.samplers:
material_info["samplers"].append({
"param_id": str(sampler.param_id),
"data": {
"wrap_s": str(sampler.data.wraps) if hasattr(sampler.data, 'wraps') else None,
"wrap_t": str(sampler.data.wrapt) if hasattr(sampler.data, 'wrapt') else None,
"min_filter": str(sampler.data.min_filter) if hasattr(sampler.data, 'min_filter') else None,
"mag_filter": str(sampler.data.mag_filter) if hasattr(sampler.data, 'mag_filter') else None
}
})
materials.append(material_info)
# Crear nombre del archivo JSON basado en el original
base_name = os.path.basename(file_path)
json_name = f"{os.path.splitext(base_name)[0]}.json"
json_path = os.path.join(output_dir, json_name)
# Guardar en formato JSON
with open(json_path, 'w', encoding='utf-8') as f:
json.dump(materials, f, indent=2)
print(f"Convertido {file_path} a JSON: {json_path}")
return json_path
except Exception as e:
print(f"Error al convertir {file_path} a JSON: {e}")
# Intentar método alternativo usando análisis binario
try:
print(f"Intentando método alternativo para {file_path}...")
parser = MatlParser(file_path)
texture_refs = parser.parse()
# Crear estructura simple para guardar
materials = []
material_refs = {}
for ref in texture_refs:
if ref.material_label not in material_refs:
material_refs[ref.material_label] = {
"material_label": ref.material_label,
"textures": []
}
material_refs[ref.material_label]["textures"].append({
"param_id": ref.parameter_name,
"texture_path": ref.texture_path
})
for material_label, material_data in material_refs.items():
materials.append(material_data)
# Crear nombre del archivo JSON basado en el original
base_name = os.path.basename(file_path)
json_name = f"{os.path.splitext(base_name)[0]}_fallback.json"
json_path = os.path.join(output_dir, json_name)
# Guardar en formato JSON
with open(json_path, 'w', encoding='utf-8') as f:
json.dump(materials, f, indent=2)
print(f"Convertido {file_path} a JSON usando método alternativo: {json_path}")
return json_path
except Exception as fallback_error:
print(f"Error también en método alternativo: {fallback_error}")
return None
def convert_nuanmb_to_text(file_path: str, output_dir: str) -> Optional[str]:
"""
Convierte un archivo .nuanmb a texto usando ssbh_data_py.
Args:
file_path: Ruta al archivo .nuanmb
output_dir: Directorio donde guardar el archivo de texto
Returns:
Ruta al archivo de texto o None si hubo un error
"""
if not check_ssbh_data_py_available():
print("ssbh_data_py no está disponible, no se puede convertir a texto")
return None
try:
anim_info = try_read_anim_with_ssbh(file_path)
if not anim_info:
return None
# Crear nombre del archivo de texto basado en el original
base_name = os.path.basename(file_path)
txt_name = f"{os.path.splitext(base_name)[0]}.txt"
txt_path = os.path.join(output_dir, txt_name)
# Generar texto formateado
with open(txt_path, 'w', encoding='utf-8') as f:
f.write(f"Archivo: {base_name}\n")
f.write(f"Ruta: {file_path}\n\n")
# Escribir información básica
basic_keys = ['name', 'major_version', 'minor_version', 'frames']
for key in basic_keys:
if key in anim_info:
f.write(f"{key}: {anim_info[key]}\n")
# Separador
f.write("\n--- INFORMACIÓN DETALLADA ---\n\n")
# Escribir información de los atributos disponibles
f.write("Atributos disponibles:\n")
for attr in anim_info.get("attributes", []):
f.write(f"- {attr}\n")
# Información detallada de los grupos
if "groups" in anim_info and anim_info["groups"]:
f.write(f"\nGrupos de animación ({len(anim_info['groups'])}):\n")
for i, group in enumerate(anim_info["groups"]):
f.write(f"- Grupo {i+1}: {group.get('name', 'Sin nombre')}\n")
# Listar materiales en este grupo
if "materials_referenced" in group and group["materials_referenced"]:
f.write(f" Materiales referenciados en este grupo ({len(group['materials_referenced'])}):\n")
for material in group["materials_referenced"]:
f.write(f" * {material}\n")
# Información detallada de los tracks
if "tracks" in anim_info and anim_info["tracks"]:
f.write(f"\nPistas de animación ({len(anim_info['tracks'])}):\n")
for i, track in enumerate(anim_info["tracks"]):
f.write(f"- Pista {i+1}: {track.get('name', 'Sin nombre')}\n")
# Listar materiales con visibilidad animada en este track
if "materials_referenced" in track and track["materials_referenced"]:
f.write(f" Materiales con visibilidad animada ({len(track['materials_referenced'])}):\n")
for material in track["materials_referenced"]:
f.write(f" * {material}\n")
# Si es método alternativo
if "method" in anim_info and anim_info["method"] == "binary_search":
f.write("\nMétodo alternativo - Posibles nombres de materiales encontrados:\n")
for material in anim_info.get("possible_materials", []):
if material.startswith(("def_", "mat_")):
f.write(f"* {material}\n")
# Intentar extraer todo lo posible como información adicional
import json
try:
f.write("\nInformación completa (JSON):\n")
# Eliminar atributos que pueden ser demasiado grandes
info_copy = anim_info.copy()
if "attributes" in info_copy:
del info_copy["attributes"]
if "file_path" in info_copy:
del info_copy["file_path"]
json_str = json.dumps(info_copy, indent=2, default=str)
f.write(json_str)
except Exception as e:
f.write(f"Error al convertir a JSON: {e}")
print(f"Generado archivo de texto: {txt_path}")
return txt_path
except Exception as e:
print(f"Error al convertir {file_path} a texto: {e}")
return None
def try_read_modl_with_ssbh(file_path: str) -> Dict[str, Any]:
"""
Intenta leer un archivo .numdlb usando ssbh_data_py y devuelve la información del modelo.
"""
if not check_ssbh_data_py_available():
return {}
try:
import ssbh_data_py
print(f"Leyendo archivo de modelo: {file_path}")
modl = ssbh_data_py.modl_data.read_modl(file_path)
# Crear un diccionario con la información disponible
modl_info = {
"name": os.path.basename(file_path),
"attributes": [],
"file_path": file_path
}
# Listar todos los atributos disponibles en este objeto
print(f"Extrayendo atributos de {os.path.basename(file_path)}...")
for attr_name in dir(modl):
if not attr_name.startswith("_"): # Ignorar atributos privados
try:
attr_value = getattr(modl, attr_name)
attr_type = type(attr_value).__name__
is_callable = callable(attr_value)
modl_info["attributes"].append(f"{attr_name}: {attr_type} {'(callable)' if is_callable else ''}")
# Guardar valores simples directamente
if not is_callable and attr_type in ["int", "float", "str", "bool"]:
modl_info[attr_name] = attr_value
print(f" - Atributo simple: {attr_name} = {attr_value}")
except Exception as e:
print(f" - Error al acceder a {attr_name}: {e}")
# Buscar referencias a materiales
material_refs = []
# Examinar mallas (meshes)
if hasattr(modl, 'meshes') and modl.meshes:
print(f"Encontradas {len(modl.meshes)} mallas")
modl_info["meshes"] = []
for i, mesh in enumerate(modl.meshes):
mesh_info = {"index": i}
# Extraer nombre si está disponible
if hasattr(mesh, 'name'):
mesh_info["name"] = mesh.name
# Extraer material si está disponible
if hasattr(mesh, 'material_label'):
mesh_info["material_label"] = mesh.material_label
material_refs.append(mesh.material_label)
# Extraer atributos adicionales
if hasattr(mesh, 'bounding_radius'):
mesh_info["bounding_radius"] = mesh.bounding_radius
modl_info["meshes"].append(mesh_info)
# Examinar huesos (bones)
if hasattr(modl, 'bones') and modl.bones:
print(f"Encontrados {len(modl.bones)} huesos")
modl_info["bones"] = []
for i, bone in enumerate(modl.bones):
bone_info = {"index": i}
if hasattr(bone, 'name'):
bone_info["name"] = bone.name
if hasattr(bone, 'parent_index'):
bone_info["parent_index"] = bone.parent_index
modl_info["bones"].append(bone_info)
# Añadir lista unificada de materiales
if material_refs:
modl_info["material_references"] = list(set(material_refs))
return modl_info
except Exception as e:
print(f"Error al leer {file_path} con ssbh_data_py: {e}")
# Intentar método alternativo
try:
print(f"Intentando método alternativo para {file_path}...")
# Examinar el archivo binario para buscar nombres de materiales
with open(file_path, 'rb') as f:
data = f.read()
# Buscar posibles cadenas que parezcan nombres de materiales
material_pattern = re.compile(b'(def|mat)_[a-zA-Z0-9_]+')
matches = material_pattern.findall(data)
# Crear estructura simple
modl_info = {
"name": os.path.basename(file_path),
"method": "binary_search",
"possible_materials": [m.decode('utf-8', errors='ignore') for m in set(matches)]
}
return modl_info
except Exception as fallback_error:
print(f"Error también en método alternativo: {fallback_error}")
return {}
def convert_numdlb_to_text(file_path: str, output_dir: str) -> Optional[str]:
"""
Convierte un archivo .numdlb a texto usando ssbh_data_py.
Args:
file_path: Ruta al archivo .numdlb
output_dir: Directorio donde guardar el archivo de texto
Returns:
Ruta al archivo de texto o None si hubo un error
"""
if not check_ssbh_data_py_available():
print("ssbh_data_py no está disponible, no se puede convertir a texto")
return None
try:
modl_info = try_read_modl_with_ssbh(file_path)
if not modl_info:
return None
# Crear nombre del archivo de texto basado en el original
base_name = os.path.basename(file_path)
txt_name = f"{os.path.splitext(base_name)[0]}_model.txt"
txt_path = os.path.join(output_dir, txt_name)
# Generar texto formateado
with open(txt_path, 'w', encoding='utf-8') as f:
f.write(f"Archivo de modelo: {base_name}\n")
f.write(f"Ruta: {file_path}\n\n")
# Escribir información básica
basic_keys = ['name', 'major_version', 'minor_version']
for key in basic_keys:
if key in modl_info:
f.write(f"{key}: {modl_info[key]}\n")
# Separador
f.write("\n--- INFORMACIÓN DETALLADA DEL MODELO ---\n\n")
# Escribir información de los atributos disponibles
f.write("Atributos disponibles:\n")
for attr in modl_info.get("attributes", []):
f.write(f"- {attr}\n")
# Información de materiales
if "material_references" in modl_info and modl_info["material_references"]:
f.write(f"\nMateriales referenciados ({len(modl_info['material_references'])}):\n")
for material in modl_info["material_references"]:
f.write(f"* {material}\n")
# Información de mallas
if "meshes" in modl_info and modl_info["meshes"]:
f.write(f"\nMallas ({len(modl_info['meshes'])}):\n")
for i, mesh in enumerate(modl_info["meshes"]):
f.write(f"- Malla {i+1}: {mesh.get('name', 'Sin nombre')}\n")
if "material_label" in mesh:
f.write(f" Material: {mesh['material_label']}\n")
if "bounding_radius" in mesh:
f.write(f" Radio de límite: {mesh['bounding_radius']}\n")
# Información de huesos
if "bones" in modl_info and modl_info["bones"]:
f.write(f"\nHuesos ({len(modl_info['bones'])}):\n")
for i, bone in enumerate(modl_info["bones"]):
parent_info = f", Padre: {bone['parent_index']}" if "parent_index" in bone else ""
f.write(f"- Hueso {i}: {bone.get('name', 'Sin nombre')}{parent_info}\n")
# Si es método alternativo
if "method" in modl_info and modl_info["method"] == "binary_search":
f.write("\nMétodo alternativo - Posibles nombres de materiales encontrados:\n")
for material in modl_info.get("possible_materials", []):
if material.startswith(("def_", "mat_")):
f.write(f"* {material}\n")
# Intentar extraer todo lo posible como información adicional
import json
try:
f.write("\nInformación completa (JSON):\n")
# Eliminar atributos que pueden ser demasiado grandes
info_copy = modl_info.copy()
if "attributes" in info_copy:
del info_copy["attributes"]
if "file_path" in info_copy:
del info_copy["file_path"]
json_str = json.dumps(info_copy, indent=2, default=str)
f.write(json_str)
except Exception as e:
f.write(f"Error al convertir a JSON: {e}")
print(f"Generado archivo de texto para modelo: {txt_path}")
return txt_path
except Exception as e:
print(f"Error al convertir {file_path} a texto: {e}")
return None
class TextureReference:
"""Representa una referencia a una textura en un archivo de material"""
def __init__(self, texture_path: str, parameter_name: str, material_label: str = "", file_path: str = ""):
self.texture_path = texture_path # Ruta del archivo de textura
self.parameter_name = parameter_name # Nombre del parámetro (ej: "Texture0")
self.material_label = material_label # Etiqueta del material al que pertenece
self.file_path = file_path # Ruta del archivo de material
def __str__(self) -> str:
return f"{self.material_label} -> {self.parameter_name}: {self.texture_path}"
class MatlHeader:
"""Encabezado de un archivo MATL de Smash Ultimate"""
def __init__(self):
self.magic = b'' # Marca de identificación del archivo (debe ser 'LTAM')
self.version = 0 # Versión del formato
self.entry_count = 0 # Número de entradas de materiales
@classmethod
def from_binary(cls, data: bytes) -> 'MatlHeader':
"""Crea un MatlHeader desde datos binarios"""
header = cls()
if len(data) >= 12:
header.magic = data[0:4]
header.version = int.from_bytes(data[4:8], byteorder='little')
header.entry_count = int.from_bytes(data[8:12], byteorder='little')
return header
class MatlEntryInfo:
"""Información básica sobre una entrada de material en un archivo MATL"""
def __init__(self):
self.material_label = "" # Etiqueta del material
self.shader_label = "" # Etiqueta del shader utilizado
class MatlParser:
"""Parser simple para archivos NUMATB."""
def __init__(self, filepath: str):
self.filepath = filepath
def parse(self) -> List[TextureReference]:
"""
Parsea un archivo .numatb y devuelve una lista de referencias a texturas.
Este es un analizador de respaldo en caso de que ssbh_data_py no esté disponible.
"""
references = []
try:
# Primero intentar con ssbh_data_py
if check_ssbh_data_py_available():
refs = try_read_matl_with_ssbh(self.filepath)
if refs:
return refs
# Si falla, intentar con análisis binario básico
with open(self.filepath, 'rb') as f:
data = f.read()
# Buscar cadenas que parezcan nombres de materiales o texturas
material_pattern = re.compile(b'(def|mat)_[a-zA-Z0-9_]+')
texture_pattern = re.compile(b'[a-zA-Z0-9_/]+\.(bntx|nutexb)')
materials = material_pattern.findall(data)
textures = texture_pattern.findall(data)
# Convertir a strings
material_strs = [m.decode('utf-8', errors='ignore') for m in materials]
texture_strs = [t.decode('utf-8', errors='ignore') for t in textures]
# Filtrar duplicados
material_strs = list(set(material_strs))
texture_strs = list(set(texture_strs))
# Si no se encontraron materiales explícitos, usar "default"
if not material_strs:
material_strs = ["default_material"]
# Crear referencias para cada combinación material-textura
for material in material_strs:
for i, texture in enumerate(texture_strs):
ref = TextureReference(
texture_path=texture,
parameter_name=f"Texture{i}",
material_label=material,
file_path=self.filepath
)
references.append(ref)
except Exception as e:
print(f"Error al parsear {self.filepath}: {e}")
return references
class TextureAnalyzer:
"""Analizador de archivos de texturas para Smash Ultimate"""
def __init__(self, mod_directory: str, debug: bool = False):
self.mod_directory = mod_directory
self.junk_dir = os.path.join(mod_directory, "junk")
self.temp_dir = None
self.use_ssbh = check_ssbh_data_py_available()
self.debug = debug
if not self.use_ssbh:
print("La biblioteca ssbh_data_py no está instalada.")
print("Esta biblioteca permite una detección mucho más precisa de texturas.")
self.use_ssbh = install_ssbh_data_py()
# Crear carpeta junk si no existe
if not os.path.exists(self.junk_dir):
os.makedirs(self.junk_dir)
def create_temp_dir(self):
"""Crea un directorio temporal para los archivos JSON"""
if self.temp_dir is None:
self.temp_dir = os.path.join(tempfile.gettempdir(), f"texture_analyzer_{int(time.time())}")
os.makedirs(self.temp_dir, exist_ok=True)
return self.temp_dir
def cleanup_temp_dir(self):
"""Limpia el directorio temporal"""
if self.temp_dir and os.path.exists(self.temp_dir):
try:
shutil.rmtree(self.temp_dir)
self.temp_dir = None
except Exception as e:
print(f"Error al limpiar directorio temporal: {e}")
def analyze_alt(self, fighter_name, model_paths, etc_paths,
analyze_numatb=True, analyze_nuanmb=False, analyze_numdlb=True,
convert_to_json=None, convert_to_txt=None,
aggressive_mode=False, ultra_aggressive_mode=False):
"""
Analiza archivos de un alt específico para encontrar referencias a texturas
Args:
fighter_name: Nombre del luchador (por ejemplo, "wolf")
model_paths: Lista de rutas a archivos de modelo y material
etc_paths: Lista de rutas a otros archivos (animación, etc.)
analyze_numatb: Si es True, analiza archivos de material (.numatb)
analyze_nuanmb: Si es True, analiza archivos de animación (.nuanmb) - NO USADO
analyze_numdlb: Si es True, analiza archivos de modelo (.numdlb)
convert_to_json: Si se proporciona una ruta, convierte los resultados a JSON
convert_to_txt: Si se proporciona una ruta, convierte los resultados a texto plano
aggressive_mode: Si es True, usa reglas más agresivas para marcar texturas como no utilizadas
ultra_aggressive_mode: Si es True, usa reglas extremadamente agresivas
Returns:
Tuple con dos listas: (referencias_texturas, archivos_textura_encontrados)
"""
print(f"Analizando archivos para {fighter_name}...")
# Si estamos en modo ultra agresivo, activar también el modo agresivo
if ultra_aggressive_mode:
aggressive_mode = True
# Crear directorio temporal para los archivos procesados si es necesario
temp_dir = None
if convert_to_json or convert_to_txt:
temp_dir = self.create_temp_dir()
# Nombres de archivos de material principales a priorizar
core_material_files = ["dark_model.numatb", "light_model.numatb", "model.numatb", "metamon_model.numatb"]
# Lista de patrones para archivos que siempre se deben mantener
always_keep_patterns = [
"_eye_", # Texturas de ojos
"_eye.", # Texturas de ojos
"eye_", # Texturas de ojos
"expression", # Expresiones faciales
]
# Si no estamos en modo ultra agresivo, añadir más patrones a conservar
if not ultra_aggressive_mode:
always_keep_patterns.extend([
"_brow_", # Cejas
"_face_", # Caras
"_head_", # Cabeza
"common/", # Archivos comunes
"ui/", # Archivos de interfaz
"preview_", # Vistas previas
"thumb_", # Miniaturas
"_icon_", # Íconos
"_stock_", # Íconos de stock
])
# Patrones adicionales para modo conservador (no agresivo)
if not aggressive_mode:
always_keep_patterns.extend([
"_wp.", # Armas
"_weapon", # Armas
"light", # Efectos de luz
"aura", # Auras
"glow", # Brillos
"fire", # Fuego
"effect" # Efectos
])
# Lista de nombres base específicos que se deben tratar como no utilizados en modo agresivo
potentially_unused_bases = set([
"belt", # Cinturones
"bust", # Bustos
"pants", # Pantalones
"boots", # Botas
"necklace", # Collares
"jewelry", # Joyería
"cloth", # Telas
"skirt", # Faldas
"chain", # Cadenas
"accessory", # Accesorios
"scarf", # Bufandas
"emblem", # Emblemas
"badge", # Insignias
"armor", # Armadura
"metal", # Metal
"fur", # Pelaje
"cape", # Capas
"coat", # Abrigos
"hair", # Pelo (en modo ultra agresivo)
"hand", # Manos (en modo ultra agresivo)
"arm", # Brazos (en modo ultra agresivo)
"leg", # Piernas (en modo ultra agresivo)
"foot", # Pies (en modo ultra agresivo)
"body", # Cuerpo (en modo ultra agresivo)
])
# Separar los archivos por tipo
material_files = []
model_files = []
for path in model_paths:
if path.endswith('.numatb') and analyze_numatb:
material_files.append(path)
elif path.endswith('.numdlb') and analyze_numdlb:
model_files.append(path)
print(f"Encontrados {len(material_files)} archivos de material y {len(model_files)} modelos")
# Crear un diccionario para acceder a los archivos por nombre
material_files_by_name = {}
for material_file in material_files:
base_name = os.path.basename(material_file)
material_files_by_name[base_name] = material_file
# Encontrar todas las texturas disponibles
all_textures = []
fighter_dir = os.path.join(self.mod_directory, f"fighter/{fighter_name}")
# Buscar en directorios de modelo para texturas
for root, _, files in os.walk(os.path.join(fighter_dir, "model")):
for file in files:
if file.endswith(".nutexb"):
# Guardar la ruta relativa al mod_directory
rel_path = os.path.relpath(os.path.join(root, file), self.mod_directory)
all_textures.append(rel_path)
print(f"Encontradas {len(all_textures)} texturas en total")
# Extraer referencias a texturas de los archivos .numatb
used_textures = set()
all_texture_refs = []
# Diccionario para rastrear texturas por nombre base (sin sufijos ni extensiones)
base_name_to_textures = {}
# Organizar las texturas por nombre base para facilitar la búsqueda de variantes
for texture in all_textures:
file_name = os.path.basename(texture)
file_base, _ = os.path.splitext(file_name)
# Eliminar sufijos comunes para obtener el nombre base más puro
base_name = file_base
for suffix in ['_col', '_nor', '_prm', '_emi', '_gao', '_inca', '_mask']:
if base_name.lower().endswith(suffix):
base_name = base_name[:-len(suffix)]
break
if base_name not in base_name_to_textures:
base_name_to_textures[base_name] = []
base_name_to_textures[base_name].append(texture)
# Llevar conteo de las referencias encontradas por cada archivo principal
core_file_refs = {file: 0 for file in core_material_files}
# Asegurarse de procesar primero los archivos core para aumentar sus prioridades
prioritized_material_files = []
for core_file in core_material_files:
if core_file in material_files_by_name:
print(f"✓ Archivo principal encontrado: {core_file}")
prioritized_material_files.append(material_files_by_name[core_file])
else:
print(f"✗ Archivo principal NO encontrado: {core_file}")
# Agregar el resto de archivos de material
for material_file in material_files:
if material_file not in prioritized_material_files:
prioritized_material_files.append(material_file)
# Primero, convertir todos los archivos .numatb a JSON para un análisis más preciso
json_files = []
output_dir = convert_to_json if convert_to_json else temp_dir
for material_file in prioritized_material_files:
if output_dir:
json_path = convert_numatb_to_json(material_file, output_dir)
if json_path:
json_files.append((material_file, json_path))
# Conteo de referencias a cada textura para detectar las que son realmente críticas
texture_reference_count = {}
# Conjunto para almacenar texturas directamente utilizadas por model.numatb
model_direct_textures = set()
# Ahora, analizar los archivos JSON para encontrar referencias a texturas
for original_file, json_file in json_files:
file_name = os.path.basename(original_file)
print(f"Analizando archivo de material: {file_name}")
is_core_file = file_name in core_material_files
is_model_file = file_name == "model.numatb" # Marcar específicamente model.numatb
file_refs_count = 0
try:
with open(json_file, 'r') as f:
materials = json.load(f)
print(f" - Usando conversión JSON para análisis de precisión")
for material in materials:
material_label = material["material_label"]
for texture in material["textures"]:
param_id = texture["param_id"]
texture_path = texture["texture_path"]
# Crear objeto TextureReference
texture_ref = TextureReference(
texture_path=texture_path,
parameter_name=param_id,
material_label=material_label,
file_path=original_file
)
all_texture_refs.append(texture_ref)
# Convertir la ruta de textura en una ruta relativa completa
resolved_path = self._resolve_texture_path(texture_path, os.path.dirname(original_file),