forked from HarbourMasters/fast64
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsoh_xml_exporter.py
More file actions
1726 lines (1411 loc) · 50.1 KB
/
Copy pathsoh_xml_exporter.py
File metadata and controls
1726 lines (1411 loc) · 50.1 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
"""SOH XML export extensions for F3D GBI classes.
Monkey-patches to_soh_xml() and related methods onto F3D classes at registration time.
All methods are removed at unregistration time.
"""
import os
import bpy
from html import escape
from pathlib import Path
from struct import pack
import xml.etree.ElementTree as ET
from ...f3d.f3d_gbi import (
DPFullSync,
DPLoadBlock,
DPLoadSync,
DPLoadTLUTCmd,
DPLoadTile,
DPPipeSync,
DPSetCombineMode,
DPSetEnvColor,
DPSetPrimColor,
DPSetTextureImage,
DPSetTextureLUT,
DPSetTile,
DPSetTileSize,
DPTileSync,
FImageKey,
FLODGroup,
FMaterial,
FMesh,
FModel,
FPaletteKey,
FScrollData,
FSetTileSizeScrollField,
FTriGroup,
GfxList,
SP1Triangle,
SP2Triangles,
SPBranchList,
SPClearGeometryMode,
SPCullDisplayList,
SPDisplayList,
SPEndDisplayList,
SPLoadGeometryMode,
SPMatrix,
SPSetGeometryMode,
SPSetLights,
SPSetOtherMode,
SPTexture,
SPVertex,
Vtx,
VtxList,
FTexRect,
FLODGroup,
Light,
Ambient,
Hilite,
Lights,
LookAt,
SPMatrix,
SPViewport,
SPDisplayList,
SPLine3D,
SPLineW3D,
SPSegment,
SPClipRatio,
SPAlphaCompareCull,
SPModifyVertex,
SPBranchLessZraw,
SPNumLights,
SPLight,
SPLightColor,
SPSetLights,
SPLookAt,
DPSetHilite1Tile,
DPSetHilite2Tile,
SPFogFactor,
SPFogPosition,
SPPerspNormalize,
SPGeometryMode,
DPPipelineMode,
DPSetCycleType,
DPSetTexturePersp,
DPSetTextureDetail,
DPSetTextureLOD,
DPSetTextureFilter,
DPSetTextureConvert,
DPSetCombineKey,
DPSetColorDither,
DPSetAlphaDither,
DPSetAlphaCompare,
DPSetDepthSource,
DPSetRenderMode,
DPSetCombineMode,
DPSetBlendColor,
DPSetFogColor,
DPSetFillColor,
DPSetPrimDepth,
DPSetOtherMode,
DPSetTileSize,
DPSetTile,
DPLoadTextureBlock,
DPLoadTextureBlockYuv,
_DPLoadTextureBlock,
DPLoadTextureBlock_4b,
DPLoadTextureTile,
DPLoadTextureTile_4b,
DPLoadTLUT_pal16,
DPLoadTLUT_pal256,
DPLoadTLUT,
DPSetConvert,
DPSetKeyR,
DPSetKeyGB,
SPTextureRectangle,
SPScisTextureRectangle,
format_asset_path,
get_image_from_image_key,
)
from ...utility import (
PluginError,
writeXMLData,
resolve_internal_export_path,
)
from ...z64.exporter.skeleton.classes import OOTSkeleton, OOTLimb
# --- Helper functions ---
def getDynamicCosmeticXmlAttrs(cosmeticEntry: str, cosmeticCategory: str):
entry = escape(cosmeticEntry.strip(), quote=True) if cosmeticEntry else ""
if not entry:
return ""
attrs = f' CosmeticEntry="{entry}"'
category = escape(cosmeticCategory.strip(), quote=True) if cosmeticCategory else ""
if category:
attrs += f' CosmeticCategory="{category}"'
return attrs
def _get_cosmetic_manifest_path(modelDirPath: str, objectPath: str) -> str:
model_path = Path(modelDirPath)
object_parts = [part for part in (objectPath or "").replace("\\", "/").split("/") if part]
if not object_parts:
manifest_root = model_path.parent if model_path.name.lower() == "alt" else model_path
return str(manifest_root / "CosmeticEntries")
model_parts = list(model_path.parts)
if len(model_parts) >= len(object_parts):
tail = model_parts[-len(object_parts) :]
if [part.lower() for part in tail] == [part.lower() for part in object_parts]:
manifest_root = Path(*model_parts[: len(model_parts) - len(object_parts)])
if manifest_root.name.lower() == "alt":
manifest_root = manifest_root.parent
return str(manifest_root / "CosmeticEntries")
manifest_root = model_path.parent if model_path.name.lower() == "alt" else model_path
return str(manifest_root / "CosmeticEntries")
def _read_existing_cosmetic_manifest_entries(manifestPath: str) -> list[dict[str, str]]:
if not os.path.exists(manifestPath):
return []
try:
root = ET.parse(manifestPath).getroot()
except ET.ParseError as exc:
raise PluginError(f"Unable to parse existing cosmetic manifest at {manifestPath}: {exc}") from exc
if root.tag != "CustomCosmetics":
raise PluginError(f'Unexpected cosmetic manifest root "{root.tag}" in {manifestPath}.')
entries: list[dict[str, str]] = []
for entry in root.findall("Entry"):
entries.append(
{
"CosmeticCategory": entry.get("CosmeticCategory", ""),
"CosmeticEntry": entry.get("CosmeticEntry", ""),
"MaterialPath": entry.get("MaterialPath", ""),
"CosmeticType": entry.get("CosmeticType", ""),
}
)
return entries
def _serialize_cosmetic_manifest(entries: list[dict[str, str]]) -> str:
lines = ["<CustomCosmetics>"]
for entry in entries:
attrs = " ".join(
[
f'CosmeticCategory="{escape(entry["CosmeticCategory"], quote=True)}"',
f'CosmeticEntry="{escape(entry["CosmeticEntry"], quote=True)}"',
f'MaterialPath="{escape(entry["MaterialPath"], quote=True)}"',
f'CosmeticType="{escape(entry["CosmeticType"], quote=True)}"',
]
)
lines.append(f" <Entry {attrs} />")
lines.append("</CustomCosmetics>")
return "\n".join(lines)
def _collect_material_cosmetic_manifest_entries(fMaterial, objectPath: str) -> list[dict[str, str]]:
materialPath = format_asset_path(objectPath, fMaterial.material.name)
entries: list[dict[str, str]] = []
for command in fMaterial.material.commands:
cosmeticType = None
if isinstance(command, DPSetPrimColor):
cosmeticType = "Prim"
elif isinstance(command, DPSetEnvColor):
cosmeticType = "Env"
if cosmeticType is None:
continue
cosmeticEntry = (getattr(command, "cosmeticEntry", "") or "").strip()
if not cosmeticEntry:
continue
entries.append(
{
"CosmeticCategory": (getattr(command, "cosmeticCategory", "") or "").strip(),
"CosmeticEntry": cosmeticEntry,
"MaterialPath": materialPath,
"CosmeticType": cosmeticType,
}
)
return entries
def _write_custom_cosmetics_manifest(modelDirPath: str, objectPath: str, manifestEntries: list[dict[str, str]]):
if not manifestEntries:
return
manifestPath = _get_cosmetic_manifest_path(modelDirPath, objectPath)
existingEntries = _read_existing_cosmetic_manifest_entries(manifestPath)
mergedEntries = list(existingEntries)
existingKeys = {
(
entry["CosmeticCategory"],
entry["CosmeticEntry"],
entry["MaterialPath"],
entry["CosmeticType"],
)
for entry in existingEntries
}
for entry in manifestEntries:
key = (
entry["CosmeticCategory"],
entry["CosmeticEntry"],
entry["MaterialPath"],
entry["CosmeticType"],
)
if key in existingKeys:
continue
existingKeys.add(key)
mergedEntries.append(entry)
writeXMLData(_serialize_cosmetic_manifest(mergedEntries), manifestPath)
# --- Extracted methods ---
# FSetTileSizeScrollField.to_soh_xml
def _FSetTileSizeScrollField_to_soh_xml(self, tex_index, dimensions):
"""Export scroll data for a single texture as XML for SOH.
Args:
tex_index: Texture index (0 for TEXEL0, 1 for TEXEL1)
dimensions: Tuple of (width, height) in texels
Returns:
XML string with TexScroll element, or empty string if no scrolling
"""
width, height = dimensions
if self.s == 0 and self.t == 0:
return "" # No scrolling, don't export
return f'<TexScroll TexIndex="{tex_index}" S="{self.s}" T="{self.t}" Width="{width}" Height="{height}" Interval="{self.interval}"/>\n'
# Vtx.to_soh_xml
def _Vtx_to_soh_xml(self):
baseStr = '<Vtx X="{pX}" Y="{pY}" Z="{pZ}" S="{s}" T="{t}" R="{r}" G="{g}" B="{b}" A="{a}"/>'
return baseStr.format(
pX=self.position[0],
pY=self.position[1],
pZ=self.position[2],
s=self.uv[0],
t=self.uv[1],
r=self.colorOrNormal[0],
g=self.colorOrNormal[1],
b=self.colorOrNormal[2],
a=self.colorOrNormal[3],
)
# VtxList.to_soh_xml
def _VtxList_to_soh_xml(self):
data = '<Vertex Version="0">\n'
for vert in self.vertices:
data += "\t" + vert.to_soh_xml() + "\n"
data += "</Vertex>\n"
return data
# GfxList.to_soh_xml
def _GfxList_to_soh_xml(self, modelDirPath, objectPath):
data = '<DisplayList Version="0">\n'
for command in self.commands:
if isinstance(command, (SPDisplayList, SPBranchList, SPVertex, DPSetTextureImage)):
data += "\t" + command.to_soh_xml(objectPath) + "\n"
else:
data += "\t" + command.to_soh_xml() + "\n"
data += "</DisplayList>\n\n"
return data
# FModel.to_soh_xml
def _FModel_to_soh_xml(self, modelDirPath, objectPath, include_cull_vertices=True, combine_root_meshes=False):
data = ""
if combine_root_meshes:
combined_call_lines = []
combined_other_lines = []
for mesh in self.meshes.values():
data += mesh.to_soh_xml(modelDirPath, objectPath, include_cull_vertices, write_root_draw=False)
call_lines, other_lines = mesh.get_soh_root_draw_lines(objectPath)
combined_call_lines.extend(call_lines)
if call_lines or other_lines:
combined_other_lines = other_lines
if combined_call_lines or combined_other_lines:
data += (
'<DisplayList Version="0">\n'
+ "".join(combined_call_lines + combined_other_lines)
+ "</DisplayList>\n\n"
)
else:
for mesh in self.meshes.values():
data += mesh.to_soh_xml(modelDirPath, objectPath, include_cull_vertices)
for lod in self.LODGroups.values():
data += lod.to_soh_xml(modelDirPath)
for fMaterial, _ in self.materials.values():
data += fMaterial.to_soh_xml(modelDirPath, objectPath)
self.texturesSavedLastExport = self.save_soh_textures(modelDirPath)
self.save_soh_palettes(modelDirPath)
self.freePalettes()
return data
# FModel.save_soh_textures
def _FModel_save_soh_textures(self, exportPath):
texturesSaved = 0
for key, texture in self.textures.items():
if isinstance(key, FPaletteKey):
continue
if not isinstance(key, FImageKey):
continue
if getattr(texture, "skip_export", False):
continue
image = get_image_from_image_key(key)
imageFileName = texture.name
fmt_code = -1
if texture.fmt == "G_IM_FMT_RGBA":
if texture.bitSize == "G_IM_SIZ_16b":
fmt_code = 2
elif texture.bitSize == "G_IM_SIZ_32b":
fmt_code = 1
elif texture.fmt == "G_IM_FMT_CI":
if texture.bitSize == "G_IM_SIZ_4b":
fmt_code = 3
elif texture.bitSize == "G_IM_SIZ_8b":
fmt_code = 4
elif texture.fmt == "G_IM_FMT_I":
if texture.bitSize == "G_IM_SIZ_4b":
fmt_code = 5
elif texture.bitSize == "G_IM_SIZ_8b":
fmt_code = 6
elif texture.fmt == "G_IM_FMT_IA":
if texture.bitSize == "G_IM_SIZ_4b":
fmt_code = 7
elif texture.bitSize == "G_IM_SIZ_8b":
fmt_code = 8
elif texture.bitSize == "G_IM_SIZ_16b":
fmt_code = 9
if fmt_code == -1:
raise PluginError(
f"Unsupported texture format {texture.fmt}/{texture.bitSize} when exporting SOH XML textures."
)
bpy.path.abspath(image.filepath)
internal_path = getattr(texture, "internal_path", "")
targetPath = bpy.path.abspath(resolve_internal_export_path(exportPath, internal_path, imageFileName))
targetDir = os.path.dirname(targetPath)
if targetDir and not os.path.exists(targetDir):
os.makedirs(targetDir, exist_ok=True)
isPacked = image.packed_file is not None
if not isPacked:
image.pack()
oldpath = image.filepath
try:
image.filepath = targetPath
with open(targetPath, "wb") as file:
file.write(
pack(
"<IIIQIQIQQQIIIIIffI",
0,
0x4F544558,
1,
0xDEADBEEFDEADBEEF,
0,
0,
0,
0,
0,
0,
0,
fmt_code,
texture.width,
texture.height,
0,
1.0,
1.0,
len(texture.data),
)
+ texture.data
)
texturesSaved += 1
if not isPacked:
old_dir = ""
unpack_path = oldpath or targetPath
if oldpath:
old_dir = os.path.dirname(bpy.path.abspath(oldpath))
else:
old_dir = os.path.dirname(bpy.path.abspath(targetPath))
if old_dir and not os.path.exists(old_dir):
os.makedirs(old_dir, exist_ok=True)
image.filepath = unpack_path
try:
image.unpack()
except RuntimeError:
pass
except Exception as exc:
image.filepath = oldpath
raise Exception(str(exc))
image.filepath = oldpath
return texturesSaved
# FModel.save_soh_palettes
def _FModel_save_soh_palettes(self, exportPath):
palettesSaved = 0
for key, texture in self.textures.items():
if not isinstance(key, FPaletteKey):
continue
if getattr(texture, "skip_export", False):
continue
palette_name = texture.filename or texture.name
if not palette_name:
continue
if palette_name.endswith(".inc.c"):
palette_filename = palette_name[:-6]
else:
palette_filename = os.path.splitext(palette_name)[0]
fmt_code = -1
if texture.fmt == "G_IM_FMT_RGBA":
if texture.bitSize == "G_IM_SIZ_16b":
fmt_code = 2
elif texture.bitSize == "G_IM_SIZ_32b":
fmt_code = 1
elif texture.fmt == "G_IM_FMT_CI":
if texture.bitSize == "G_IM_SIZ_4b":
fmt_code = 3
elif texture.bitSize == "G_IM_SIZ_8b":
fmt_code = 4
elif texture.fmt == "G_IM_FMT_I":
if texture.bitSize == "G_IM_SIZ_4b":
fmt_code = 5
elif texture.bitSize == "G_IM_SIZ_8b":
fmt_code = 6
elif texture.fmt == "G_IM_FMT_IA":
if texture.bitSize == "G_IM_SIZ_4b":
fmt_code = 7
elif texture.bitSize == "G_IM_SIZ_8b":
fmt_code = 8
elif texture.bitSize == "G_IM_SIZ_16b":
fmt_code = 9
if fmt_code == -1:
raise PluginError(
f"Unsupported palette format {texture.fmt}/{texture.bitSize} when exporting SOH XML textures."
)
internal_path = getattr(texture, "internal_path", "")
targetPath = bpy.path.abspath(resolve_internal_export_path(exportPath, internal_path, palette_filename))
targetDir = os.path.dirname(targetPath)
if targetDir and not os.path.exists(targetDir):
os.makedirs(targetDir, exist_ok=True)
try:
with open(targetPath, "wb") as file:
file.write(
pack(
"<IIIQIQIQQQIIIIIffI",
0,
0x4F544558,
1,
0xDEADBEEFDEADBEEF,
0,
0,
0,
0,
0,
0,
0,
fmt_code,
texture.width,
texture.height,
0,
1.0,
1.0,
len(texture.data),
)
+ texture.data
)
palettesSaved += 1
except Exception as exc:
raise Exception(str(exc))
return palettesSaved
# FMesh.get_soh_root_draw_lines
def _FMesh_get_soh_root_draw_lines(self, objectPath):
def command_xml(command):
if isinstance(command, (SPDisplayList, SPBranchList, DPSetTextureImage)):
return "\t" + command.to_soh_xml(objectPath) + "\n"
return "\t" + command.to_soh_xml() + "\n"
call_lines = []
other_lines = []
for command in self.draw.commands:
if isinstance(command, (SPVertex, SPCullDisplayList)):
continue
line = command_xml(command)
if isinstance(command, (SPDisplayList, SPBranchList)):
call_lines.append(line)
else:
other_lines.append(line)
return call_lines, other_lines
# FMesh.to_soh_xml
def _FMesh_to_soh_xml(self, modelDirPath, objectPath, include_cull_vertices=True, write_root_draw=True):
if include_cull_vertices and self.cullVertexList is not None:
cullData = self.cullVertexList.to_soh_xml()
writeXMLData(cullData, os.path.join(modelDirPath, self.cullVertexList.name))
for triGroup in self.triangleGroups:
triGroup.to_soh_xml(modelDirPath, objectPath)
for drawOverride in self.draw_overrides:
overrideData = drawOverride.to_soh_xml(modelDirPath)
writeXMLData(overrideData, os.path.join(modelDirPath, drawOverride.name))
if not write_root_draw:
return ""
call_lines, other_lines = self.get_soh_root_draw_lines(objectPath)
drawData = '<DisplayList Version="0">\n' + "".join(call_lines + other_lines) + "</DisplayList>\n\n"
writeXMLData(drawData, os.path.join(modelDirPath, self.draw.name))
return drawData
# FTriGroup.to_soh_xml
def _FTriGroup_to_soh_xml(self, modelDirPath, objectPath):
vtxData = self.vertexList.to_soh_xml()
writeXMLData(vtxData, os.path.join(modelDirPath, self.vertexList.name))
triListData = self.triList.to_soh_xml(modelDirPath, objectPath)
writeXMLData(triListData, os.path.join(modelDirPath, self.triList.name))
return ""
# FScrollData.to_soh_xml
def _FScrollData_to_soh_xml(self):
"""Export all tile scroll data as XML for SOH.
Returns:
XML string with TexScroll elements for each texture that has scrolling,
or empty string if no scrolling is present
"""
data = ""
# Export tex0 scroll if present
if self.tile_scroll_tex0.s != 0 or self.tile_scroll_tex0.t != 0:
data += "\t\t" + self.tile_scroll_tex0.to_soh_xml(0, self.dimensions)
# Export tex1 scroll if present
if self.tile_scroll_tex1.s != 0 or self.tile_scroll_tex1.t != 0:
data += "\t\t" + self.tile_scroll_tex1.to_soh_xml(1, self.dimensions)
return data
# FMaterial.to_soh_xml
def _FMaterial_to_soh_xml(self, modelDirPath, objectPath):
data = ""
if self.material.tag.Export:
matData = self.material.to_soh_xml(modelDirPath, objectPath)
# Insert scroll data before closing DisplayList tag if present
if self.scrollData.has_scroll_data():
scrollData = self.scrollData.to_soh_xml()
matData = matData.replace("</DisplayList>", scrollData + "</DisplayList>")
writeXMLData(matData, os.path.join(modelDirPath, self.material.name))
_write_custom_cosmetics_manifest(
modelDirPath,
objectPath,
_collect_material_cosmetic_manifest_entries(self, objectPath),
)
if self.revert is not None and self.revert.tag.Export:
revData = self.revert.to_soh_xml(modelDirPath, objectPath)
writeXMLData(revData, os.path.join(modelDirPath, self.revert.name))
return data
# SPMatrix.to_soh_xml
def _SPMatrix_to_soh_xml(self, objectPath=""):
name = self.matrix
path = f"{objectPath}/{name}" if objectPath else f">{name}"
return f'<Matrix Path="{path}" Param="{self.param}"/>'
# SPVertex.to_soh_xml
def _SPVertex_to_soh_xml(self, objectPath=""):
baseStr = '<LoadVertices Path="{parent}/{vertexPath}" VertexBufferIndex="{bufferIndex}" VertexOffset="{vertexOffset}" Count="{count}"/>'
return baseStr.format(
parent=objectPath,
vertexPath=self.vertList.name,
bufferIndex=self.index,
vertexOffset=self.offset,
count=self.count,
)
# SPDisplayList.to_soh_xml
def _SPDisplayList_to_soh_xml(self, objectPath=""):
name = self.displayList.name
path = format_asset_path(objectPath, name)
return f'<CallDisplayList Path="{path}"/>'
# SPEndDisplayList.to_soh_xml
def _SPEndDisplayList_to_soh_xml(self):
return "<EndDisplayList/>"
# SP1Triangle.to_soh_xml
def _SP1Triangle_to_soh_xml(self, objectPath=""):
return f'<Triangle1 V00="{self.v0}" V01="{self.v1}" V02="{self.v2}"/>'
# SP2Triangles.to_soh_xml
def _SP2Triangles_to_soh_xml(self, objectPath=""):
first = f'<Triangle1 V00="{self.v00}" V01="{self.v01}" V02="{self.v02}"/>'
second = f'<Triangle1 V00="{self.v10}" V01="{self.v11}" V02="{self.v12}"/>'
return first + "\n\t" + second
# SPCullDisplayList.to_soh_xml
def _SPCullDisplayList_to_soh_xml(self, objectPath=""):
return f'<CullDisplayList Start="{self.vstart}" End="{self.vend}"/>'
# SPSetLights.to_soh_xml
def _SPSetLights_to_soh_xml(self, objectPath=""):
return ""
# SPTexture.to_soh_xml
def _SPTexture_to_soh_xml(self, objectPath=""):
return f'<Texture S="{self.s}" T="{self.t}" Level="{self.level}" Tile="{self.tile}" On="{self.on}"/>'
# SPSetGeometryMode.to_soh_xml
def _SPSetGeometryMode_to_soh_xml(self, objectPath=""):
if not self.flagList:
return "<SetGeometryMode/>"
flags = " ".join(f'{flag}="1"' for flag in sorted(self.flagList, key=str))
return f"<SetGeometryMode {flags}/>"
# SPClearGeometryMode.to_soh_xml
def _SPClearGeometryMode_to_soh_xml(self, objectPath=""):
if not self.flagList:
return "<ClearGeometryMode/>"
flags = " ".join(f'{flag}="1"' for flag in sorted(self.flagList, key=str))
return f"<ClearGeometryMode {flags}/>"
# SPLoadGeometryMode.to_soh_xml
def _SPLoadGeometryMode_to_soh_xml(self, objectPath=""):
flags = ",".join(sorted(self.flagList))
return f'<GeometryFlags Mode="Load" Flags="{flags}"/>'
# SPSetOtherMode.to_soh_xml
def _SPSetOtherMode_to_soh_xml(self, objectPath=""):
if not self.flagList:
return f'<SetOtherMode Cmd="{self.cmd}" Sft="{self.sft}" Length="{self.length}"/>'
flags = " ".join(f'{flag}="1"' for flag in sorted(self.flagList, key=str))
return f'<SetOtherMode Cmd="{self.cmd}" Sft="{self.sft}" Length="{self.length}" {flags}/>'
# DPSetTextureLUT.to_soh_xml
def _DPSetTextureLUT_to_soh_xml(self, objectPath=""):
return f'<SetTextureLUT Mode="{self.mode}"/>'
# DPSetTextureImage.to_soh_xml
def _DPSetTextureImage_to_soh_xml(self, objectPath=""):
prefix = (
self.image.internal_path
if self.image.internal_path
else (objectPath if self.image.filename is not None else "")
)
imagePath = format_asset_path(prefix, self.image.name if self.image.name else "")
return f'<SetTextureImage Path="{imagePath}" Format="{self.fmt}" Size="{self.siz}" Width="{self.width}"/>'
# DPSetCombineMode.to_soh_xml
def _DPSetCombineMode_to_soh_xml(self, objectPath=""):
def _cc(name: str) -> str:
return name if name.startswith("G_CCMUX_") else f"G_CCMUX_{name}"
def _ac(name: str) -> str:
return name if name.startswith("G_ACMUX_") else f"G_ACMUX_{name}"
return (
"<SetCombineLERP "
f'A0="{_cc(self.a0)}" B0="{_cc(self.b0)}" C0="{_cc(self.c0)}" D0="{_cc(self.d0)}" '
f'Aa0="{_ac(self.Aa0)}" Ab0="{_ac(self.Ab0)}" Ac0="{_ac(self.Ac0)}" Ad0="{_ac(self.Ad0)}" '
f'A1="{_cc(self.a1)}" B1="{_cc(self.b1)}" C1="{_cc(self.c1)}" D1="{_cc(self.d1)}" '
f'Aa1="{_ac(self.Aa1)}" Ab1="{_ac(self.Ab1)}" Ac1="{_ac(self.Ac1)}" Ad1="{_ac(self.Ad1)}"/>'
)
# DPSetEnvColor.to_soh_xml
def _DPSetEnvColor_to_soh_xml(self, objectPath=""):
return (
f'<SetEnvColor R="{self.r}" G="{self.g}" B="{self.b}" A="{self.a}"'
f"{getDynamicCosmeticXmlAttrs(self.cosmeticEntry, self.cosmeticCategory)}/>"
)
# DPSetPrimColor.to_soh_xml
def _DPSetPrimColor_to_soh_xml(self, objectPath=""):
return (
f'<SetPrimColor M="{self.m}" L="{self.l}" R="{self.r}" G="{self.g}" B="{self.b}" A="{self.a}"'
f"{getDynamicCosmeticXmlAttrs(self.cosmeticEntry, self.cosmeticCategory)}/>"
)
# DPSetTileSize.to_soh_xml
def _DPSetTileSize_to_soh_xml(self, objectPath=""):
return f'<SetTileSize T="{self.tile}" Uls="{self.uls}" Ult="{self.ult}" ' f'Lrs="{self.lrs}" Lrt="{self.lrt}"/>'
# DPLoadTile.to_soh_xml
def _DPLoadTile_to_soh_xml(self, objectPath=""):
return f'<LoadTile Tile="{self.tile}" Uls="{self.uls}" Ult="{self.ult}" ' f'Lrs="{self.lrs}" Lrt="{self.lrt}"/>'
# DPSetTile.to_soh_xml
def _DPSetTile_to_soh_xml(self, objectPath=""):
return (
f'<SetTile Format="{self.fmt}" Size="{self.siz}" Line="{self.line}" TMem="{self.tmem}" '
f'Tile="{self.tile}" Palette="{self.palette}" Cms0="{self.cms[0]}" Cms1="{self.cms[1]}" '
f'Cmt0="{self.cmt[0]}" Cmt1="{self.cmt[1]}" MaskS="{self.masks}" ShiftS="{self.shifts}" '
f'MaskT="{self.maskt}" ShiftT="{self.shiftt}"/>'
)
# DPLoadBlock.to_soh_xml
def _DPLoadBlock_to_soh_xml(self, objectPath=""):
return f'<LoadBlock Tile="{self.tile}" Uls="{self.uls}" Ult="{self.ult}" ' f'Lrs="{self.lrs}" Dxt="{self.dxt}" />'
# DPLoadTLUTCmd.to_soh_xml
def _DPLoadTLUTCmd_to_soh_xml(self, objectPath=""):
return f'<LoadTLUTCmd Tile="{self.tile}" Count="{self.count}"/>'
# DPFullSync.to_soh_xml
def _DPFullSync_to_soh_xml(self):
return "<FullSync/>"
# DPTileSync.to_soh_xml
def _DPTileSync_to_soh_xml(self):
return "<TileSync/>"
# DPPipeSync.to_soh_xml
def _DPPipeSync_to_soh_xml(self):
return "<PipeSync/>"
# DPLoadSync.to_soh_xml
def _DPLoadSync_to_soh_xml(self):
return "<LoadSync/>"
# OOTSkeleton.toSohXML
def _OOTSkeleton_toSohXML(self, modelDirPath, objectPath):
limbData = ""
data = ""
if self.limbRoot is None:
return data
limbList = self.createLimbList()
isFlex = self.isFlexSkeleton()
limbData += '<Skeleton Version="0" Type="'
if isFlex:
limbData += 'Flex" LimbCount="{lc}" DisplayListCount="{dlC}">\n'.format(
lc=self.getNumLimbs(), dlC=self.getNumDLs()
)
else:
limbData += 'Normal" LimbCount="{lc}">\n'.format(lc=self.getNumLimbs())
for limb in limbList:
indLimbData = limb.toSohXML(self.hasLOD, objectPath)
writeXMLData(indLimbData, os.path.join(modelDirPath, limb.name()))
limbData += '\t<SkeletonLimb Path="{path}/{name}"/>\n'.format(
path=objectPath if len(objectPath) > 0 else ">", name=limb.name()
)
limbData += "</Skeleton>"
return limbData
# OOTLimb.toSohXML
def _OOTLimb_toSohXML(self, isLOD, objectPath):
data = '<SkeletonLimb Version="0" Type="'
if not isLOD:
data += 'Standard" '
else:
data += 'Lod" '
DLName = self.DL.name if self.DL is not None else "gEmptyDL"
if DLName != "gEmptyDL":
DLName = (objectPath + "/" if len(objectPath) > 0 else ">") + DLName
data += (
'LegTransX="{legTransX}" LegTransY="{legTransY}" LegTransZ="{legTransZ}" '
'ChildIndex="{firstChildIndex}" SiblingIndex="{siblingIndex}" DisplayList1="{displayList1}"/>\n'
).format(
legTransX=int(round(self.translation[0])),
legTransY=int(round(self.translation[1])),
legTransZ=int(round(self.translation[2])),
firstChildIndex=self.firstChildIndex,
siblingIndex=self.nextSiblingIndex,
displayList1=DLName,
)
return data
# FTexRectdef.to_soh_xml
def _FTexRect_to_soh_xml(self, savePNG, texDir):
data = ""
for info, texture in self.textures.items():
if savePNG:
data += texture.to_xml(texDir)
else:
data += texture.to_xml(texDir)
dynamicData = self.draw.to_xml(texDir)
writeXMLData(dynamicData, os.path.join(texDir, self.draw.name))
return data
# FLODGroup.to_soh_xml
def _FLODGroup_to_soh_xml(self, f3d):
self.create_data()
dynamicData = ""
staticData = self.vertexList.to_xml()
for displayList in self.subdraws:
if displayList is not None:
dynamicData += displayList.to_xml(f3d)
dynamicData += self.draw.to_xml(f3d)
return staticData, dynamicData
# Light.to_soh_xml
def _Light_to_soh_xml(self):
return f'<Light Color0="{self.color[0]}" Color1="{self.color[1]}" Color2="{self.color[2]}" Normal0="{self.normal[0]}" Normal1="{self.normal[1]}" Normal2="{self.normal[2]}"/>'
# Ambient.to_soh_xml
def _Ambient_to_soh_xml(self):
return f'<Ambient Color0="{self.color[0]}" Color1="{self.color[1]}" Color2="{self.color[2]}"/>'
# Hilite.to_soh_xml
def _Hilite_to_soh_xml(self):
return f'<Hilite X1="{self.x1}" Y1="{self.y1}" X2="{self.x2}" Y2="{self.y2}"/>'
# Lights.to_soh_xml
def _Lights_to_soh_xml(self):
data = "<Lights Size={l}>".format(len(self.l))
for light in self.l:
data += "\t" + light.to_xml() + "\n"
data += "</Lights>"
return data
# LookAt.to_soh_xml
def _LookAt_to_soh_xml(self):
data = "<LookAt>"
for light in self.l:
data += "\t" + light.to_xml() + "\n"
data += "</LookAt>"
return data
# SPMatrix.to_soh_xml
def _SPMatrix_to_soh_xml(self):
return f'<Matrix Path=">{str(self.matrix)}" Param="{self.param}"/>'
# SPViewport.to_soh_xml
def _SPViewport_to_soh_xml(self):
return f'<Viewport Path="{self.viewport.name}"/>'
# SPDisplayList.to_soh_xml
def _SPDisplayList_to_soh_xml(self, objectPath):
name = self.displayList.name
baseStr = '<CallDisplayList Path="{path}"/>'
data = baseStr.format(path=">" + name if "0x" in name else (objectPath + "/" + name))
return data
# SPLine3D.to_soh_xml
def _SPLine3D_to_soh_xml(self):
return f'<Line3D V0="{self.v0}" V1="{self.v1}" Flag="{self.flag}"/>'
# SPLineW3D.to_soh_xml
def _SPLineW3D_to_soh_xml(self):
return f'<Line3D V0="{self.v0}" V1="{self.v1}" WD="{self.wd}" Flag="{self.flag}"/>'
# SPSegment.to_soh_xml
def _SPSegment_to_soh_xml(self):
return f'<Segment Seg="{self.segment}" Base="{self.base}"/>'
# SPClipRatio.to_soh_xml
def _SPClipRatio_to_soh_xml(self):
return f'<ClipRatio Ratio="{self.ratio}"/>'
# SPAlphaCompareCull.to_soh_xml
def _SPAlphaCompareCull_to_soh_xml(self):
return "<!-- SPAlphaCompareCull is not implemented -->"