-
Notifications
You must be signed in to change notification settings - Fork 5
/
io_import_z64.py
1836 lines (1703 loc) · 89.3 KB
/
io_import_z64.py
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
bl_info = {
"name": "Zelda64 Importer",
"version": (2, 1),
"author": "SoulofDeity",
"blender": (2, 6, 0),
"location": "File > Import-Export",
"description": "Import Zelda64 - updated in 2020",
"warning": "",
"wiki_url": "https://github.com/Dragorn421/zelda64-import-blender",
"tracker_url": "https://github.com/Dragorn421/zelda64-import-blender",
"support": 'COMMUNITY',
"category": "Import-Export"}
"""Anim stuff: RodLima http://www.facebook.com/rod.lima.96?ref=tn_tnmn"""
import bpy, os, struct, time
import mathutils
from bpy import ops
from bpy.props import *
from bpy_extras.image_utils import load_image
from bpy_extras.io_utils import ExportHelper, ImportHelper
from math import *
from mathutils import *
from struct import pack, unpack_from
from mathutils import Vector, Euler, Matrix
# logging stuff, code mostly uses getLogger()
import logging
# https://stackoverflow.com/questions/2183233/how-to-add-a-custom-loglevel-to-pythons-logging-facility
logging_trace_level = 5
logging.addLevelName(logging_trace_level, 'TRACE')
def getLogger(name):
global root_logger
log = root_logger.getChild(name)
def trace(message, *args, **kws):
if log.isEnabledFor(logging_trace_level):
log._log(logging_trace_level, message, args, **kws)
log.trace = trace
return log
def registerLogging(level=logging.INFO):
global root_logger, root_logger_formatter, root_logger_stream_handler, root_logger_file_handler
root_logger = logging.getLogger('z64import')
root_logger_stream_handler = logging.StreamHandler()
root_logger_file_handler = None
root_logger_formatter = logging.Formatter('%(levelname)s:%(name)s: %(message)s')
root_logger_stream_handler.setFormatter(root_logger_formatter)
root_logger.addHandler(root_logger_stream_handler)
root_logger.setLevel(1) # actual level filtering is left to handlers
root_logger_stream_handler.setLevel(level)
getLogger('setupLogging').debug('Logging OK')
def setLoggingLevel(level):
global root_logger_stream_handler
root_logger_stream_handler.setLevel(level)
def setLogFile(path):
global root_logger, root_logger_formatter, root_logger_file_handler
if root_logger_file_handler:
root_logger.removeHandler(root_logger_file_handler)
root_logger_file_handler = None
if path:
root_logger_file_handler = logging.FileHandler(path, mode='w')
root_logger_file_handler.setFormatter(root_logger_formatter)
root_logger.addHandler(root_logger_file_handler)
# fixme logfile isn't logging TRACE
root_logger_file_handler.setLevel(1)
def unregisterLogging():
global root_logger, root_logger_stream_handler
setLogFile(None)
root_logger.removeHandler(root_logger_stream_handler)
#
def splitOffset(offset):
return offset >> 24, offset & 0x00FFFFFF
def translateRotation(rot):
""" axis, angle """
return Matrix.Rotation(rot[3], 4, Vector(rot[:3]))
def validOffset(segment, offset):
seg, offset = splitOffset(offset)
if seg > 15:
return False
if offset >= len(segment[seg]):
return False
return True
def pow2(val):
i = 1
while i < val:
i <<= 1
return int(i)
def powof(val):
num, i = 1, 0
while num < val:
num <<= 1
i += 1
return int(i)
def checkUseVertexAlpha():
global useVertexAlpha
return useVertexAlpha
class Tile:
def __init__(self):
self.texFmt, self.texBytes = 0x00, 0
self.width, self.height = 0, 0
self.rWidth, self.rHeight = 0, 0
self.txlSize = 0
self.lineSize = 0
self.rect = Vector([0, 0, 0, 0])
self.scale = Vector([1, 1])
self.ratio = Vector([1, 1])
self.clip = Vector([0, 0])
self.mask = Vector([0, 0])
self.shift = Vector([0, 0])
self.tshift = Vector([0, 0])
self.offset = Vector([0, 0])
self.data = 0x00000000
self.palette = 0x00000000
def create(self, segment):
# todo texture files are written several times, at each usage
log = getLogger('Tile.create')
if exportTextures:
try:
os.mkdir(fpath + "/textures")
except FileExistsError:
pass
except:
log.exception('Could not create textures directory %s' % (fpath + "/textures"))
pass
#Noka here
extrastring = ""
w = self.rWidth
if int(self.clip.x) & 1 != 0:
if replicateTexMirrorBlender:
w <<= 1
if enableTexMirrorSharpOcarinaTags:
extrastring += "#MirrorX"
h = self.rHeight
if int(self.clip.y) & 1 != 0:
if replicateTexMirrorBlender:
h <<= 1
if enableTexMirrorSharpOcarinaTags:
extrastring += "#MirrorY"
if int(self.clip.x) & 2 != 0 and enableTexClampSharpOcarinaTags:
extrastring += "#ClampX"
if int(self.clip.y) & 2 != 0 and enableTexClampSharpOcarinaTags:
extrastring += "#ClampY"
self.current_texture_file_path = fpath + ("/textures/%08X" % self.data) + str(extrastring) + ".tga"
log.debug('Writing texture %s (format 0x%02X)' % (self.current_texture_file_path, self.texFmt))
file = open(self.current_texture_file_path, 'wb')
if self.texFmt in (0x40, 0x48, 0x50):
file.write(pack("<BBBHHBHHHHBB", 0, 1, 1, 0, 256, 24, 0, 0, w, h, 8, 0))
self.writePalette(file, segment)
else:
file.write(pack("<BBBHHBHHHHBB", 0, 0, 2, 0, 0, 0, 0, 0, w, h, 32, 8))
if int(self.clip.y) & 1 != 0 and replicateTexMirrorBlender:
self.writeImageData(file, segment, True)
else:
self.writeImageData(file, segment)
file.close()
try:
tex = bpy.data.textures.new(name="tex_%08X" % self.data, type='IMAGE')
img = load_image(fpath + ("/textures/%08X" % self.data) + str(extrastring) + ".tga")
if img:
tex.image = img
if int(self.clip.x) & 2 != 0 and enableTexClampBlender:
img.use_clamp_x = True
if int(self.clip.y) & 2 != 0 and enableTexClampBlender:
img.use_clamp_y = True
mtl = bpy.data.materials.new(name="mtl_%08X" % self.data)
if enableShadelessMaterials:
mtl.use_shadeless = True
mt = mtl.texture_slots.add()
mt.texture = tex
mt.texture_coords = 'UV'
mt.use_map_color_diffuse = True
if self.texFmt in (0x40,0x60,0x48,0x50,0x00,0x08,0x10,0x68,0x70,0x18):
mt.use_map_alpha = True
tex.use_mipmap = True
tex.use_interpolation = True
tex.use_alpha = True
mtl.use_transparency = True
mtl.alpha = 0.0
mtl.game_settings.alpha_blend = 'ALPHA'
return mtl
except:
log.exception('Failed to create material mtl_%08X %r', self.data)
return None
def calculateSize(self):
maxTxl, lineShift = 0, 0
if self.texFmt == 0x00 or self.texFmt == 0x40:
maxTxl = 4096
lineShift = 4
elif self.texFmt == 0x60 or self.texFmt == 0x80:
maxTxl = 8192
lineShift = 4
elif self.texFmt == 0x08 or self.texFmt == 0x48:
maxTxl = 2048
lineShift = 3
elif self.texFmt == 0x68 or self.texFmt == 0x88:
maxTxl = 4096
lineShift = 3
elif self.texFmt == 0x10 or self.texFmt == 0x70:
maxTxl = 2048
lineShift = 2
elif self.texFmt == 0x50 or self.texFmt == 0x90:
maxTxl = 2048
lineShift = 0
elif self.texFmt == 0x18:
maxTxl = 1024
lineShift = 2
else:
log.warning('Unknown size for texture %s with format 0x%02X' % (self.current_texture_file_path, self.texFmt))
lineWidth = self.lineSize << lineShift
self.lineSize = lineWidth
tileWidth = self.rect.z - self.rect.x + 1
tileHeight = self.rect.w - self.rect.y + 1
maskWidth = 1 << int(self.mask.x)
maskHeight = 1 << int(self.mask.y)
lineHeight = 0
if lineWidth > 0:
lineHeight = min(int(maxTxl / lineWidth), tileHeight)
if self.mask.x > 0 and (maskWidth * maskHeight) <= maxTxl:
self.width = maskWidth
elif (tileWidth * tileHeight) <= maxTxl:
self.width = tileWidth
else:
self.width = lineWidth
if self.mask.y > 0 and (maskWidth * maskHeight) <= maxTxl:
self.height = maskHeight
elif (tileWidth * tileHeight) <= maxTxl:
self.height = tileHeight
else:
self.height = lineHeight
clampWidth, clampHeight = 0, 0
if self.clip.x == 1:
clampWidth = tileWidth
else:
clampWidth = self.width
if self.clip.y == 1:
clampHeight = tileHeight
else:
clampHeight = self.height
if maskWidth > self.width:
self.mask.x = powof(self.width)
maskWidth = 1 << int(self.mask.x)
if maskHeight > self.height:
self.mask.y = powof(self.height)
maskHeight = 1 << int(self.mask.y)
if int(self.clip.x) & 2 != 0:
self.rWidth = pow2(clampWidth)
elif int(self.clip.x) & 1 != 0:
self.rWidth = pow2(maskWidth)
else:
self.rWidth = pow2(self.width)
if int(self.clip.y) & 2 != 0:
self.rHeight = pow2(clampHeight)
elif int(self.clip.y) & 1 != 0:
self.rHeight = pow2(maskHeight)
else:
self.rHeight = pow2(self.height)
self.shift.x, self.shift.y = 1.0, 1.0
if self.tshift.x > 10:
self.shift.x = 1 << int(16 - self.tshift.x)
elif self.tshift.x > 0:
self.shift.x /= 1 << int(self.tshift.x)
if self.tshift.y > 10:
self.shift.y = 1 << int(16 - self.tshift.y)
elif self.tshift.y > 0:
self.shift.y /= 1 << int(self.tshift.y)
self.ratio.x = (self.scale.x * self.shift.x) / self.rWidth
if not enableToon:
self.ratio.x /= 32;
if int(self.clip.x) & 1 != 0 and replicateTexMirrorBlender:
self.ratio.x /= 2
self.offset.x = self.rect.x
self.ratio.y = (self.scale.y * self.shift.y) / self.rHeight
if not enableToon:
self.ratio.y /= 32;
if int(self.clip.y) & 1 != 0 and replicateTexMirrorBlender:
self.ratio.y /= 2
self.offset.y = 1.0 + self.rect.y
def writePalette(self, file, segment):
log = getLogger('Tile.writePalette')
if self.texFmt == 0x40:
palSize = 16
else:
palSize = 256
if not validOffset(segment, self.palette + int(palSize * 2) - 1):
log.error('Segment offsets 0x%X-0x%X are invalid, writing black palette to %s (has the segment data been loaded?)' % (self.palette, self.palette + int(palSize * 2) - 1, self.current_texture_file_path))
for i in range(256):
file.write(pack("L", 0))
return
seg, offset = splitOffset(self.palette)
for i in range(256):
if i < palSize:
color = unpack_from(">H", segment[seg], offset + (i << 1))[0]
r = int(8 * ((color >> 11) & 0x1F))
g = int(8 * ((color >> 6) & 0x1F))
b = int(8 * ((color >> 1) & 0x1F))
file.write(pack("BBB", b, g, r))
else:
file.write(pack("BBB", 0, 0, 0))
def writeImageData(self, file, segment, fy=False, df=False):
log = getLogger('Tile.writeImageData')
if fy == True:
dir = (0, self.rHeight, 1)
else:
dir = (self.rHeight - 1, -1, -1)
if self.texFmt in (0x40, 0x60, 0x80, 0x90):
bpp = 0.5
elif self.texFmt in (0x00, 0x08, 0x10, 0x70):
bpp = 2
elif self.texFmt in (0x48, 0x50, 0x68, 0x88):
bpp = 1
elif self.texFmt in (0x18,):
bpp = 4
else:
log.warning('Unknown texture format 0x%02X for texture %s' % (self.texFmt, self.current_texture_file_path))
bpp = 4
lineSize = self.rWidth * bpp
if not validOffset(segment, self.data + int(self.rHeight * lineSize) - 1):
log.error('Segment offsets 0x%X-0x%X are invalid, writing default fallback colors to %s (has the segment data been loaded?)' % (self.data, self.data + int(self.rHeight * lineSize) - 1, self.current_texture_file_path))
size = self.rWidth * self.rHeight
if int(self.clip.x) & 1 != 0 and replicateTexMirrorBlender:
size *= 2
if int(self.clip.y) & 1 != 0 and replicateTexMirrorBlender:
size *= 2
for i in range(size):
if self.texFmt == 0x40 or self.texFmt == 0x48 or self.texFmt == 0x50:
file.write(pack("B", 0))
else:
file.write(pack(">L", 0x000000FF))
return
seg, offset = splitOffset(self.data)
for i in range(dir[0], dir[1], dir[2]):
off = offset + int(i * lineSize)
line = []
j = 0
while j < int(self.rWidth * bpp):
if bpp < 2:
color = unpack_from("B", segment[seg], off + int(floor(j)))[0]
elif bpp == 2:
color = unpack_from(">H", segment[seg], off + j)[0]
else:
color = unpack_from(">L", segment[seg], off + j)[0]
if self.texFmt == 0x40:
if floor(j) == j:
a = color >> 4
else:
a = color & 0x0F
# IA4
elif self.texFmt == 0x60:
if floor(j) == j:
color = color >> 4
r = int(((color >> 1) & 0b111) * 255 / 7)
g = r
b = r
a = 255 if color & 1 else 0
elif self.texFmt == 0x48 or self.texFmt == 0x50:
a = color
elif self.texFmt == 0x00 or self.texFmt == 0x08 or self.texFmt == 0x10:
r = int(8 * ((color >> 11) & 0x1F))
g = int(8 * ((color >> 6) & 0x1F))
b = int(8 * ((color >> 1) & 0x1F))
a = int(255 * (color & 0x01))
elif self.texFmt == 0x80:
if floor(j) == j:
r = int(16 * (color >> 4))
else:
r = int(16 * (color & 0x0F))
g = r
b = g
a = 0xFF
elif self.texFmt == 0x88:
r = color
g = r
b = g
a = 0xFF
elif self.texFmt == 0x68:
r = int(16 * (color >> 4))
g = r
b = g
a = int(16 * (color & 0x0F))
elif self.texFmt == 0x70:
r = color >> 8
g = r
b = g
a = color & 0xFF
elif self.texFmt == 0x18:
r = color >> 24
g = (color >> 16) & 0xFF
b = (color >> 8) & 0xFF
a = color & 0xFF
else:
r = 0
g = 0
b = 0
a = 0xFF
if self.texFmt == 0x40 or self.texFmt == 0x48 or self.texFmt == 0x50:
line.append(a)
else:
line.append((b << 24) | (g << 16) | (r << 8) | a)
j += bpp
if self.texFmt == 0x40 or self.texFmt == 0x48 or self.texFmt == 0x50:
file.write(pack("B" * len(line), *line))
else:
file.write(pack(">" + "L" * len(line), *line))
if int(self.clip.x) & 1 != 0 and replicateTexMirrorBlender:
line.reverse()
if self.texFmt == 0x40 or self.texFmt == 0x48 or self.texFmt == 0x50:
file.write(pack("B" * len(line), *line))
else:
file.write(pack(">" + "L" * len(line), *line))
if int(self.clip.y) & 1 != 0 and df == False and replicateTexMirrorBlender:
if fy == True:
self.writeImageData(file, segment, False, True)
else:
self.writeImageData(file, segment, True, True)
class Vertex:
def __init__(self):
self.pos = Vector([0, 0, 0])
self.uv = Vector([0, 0])
self.normal = Vector([0, 0, 0])
self.color = [0, 0, 0, 0]
self.limb = None
def read(self, segment, offset):
log = getLogger('Vertex.read')
if not validOffset(segment, offset + 16):
log.warning('Invalid segmented offset 0x%X for vertex' % (offset + 16))
return
seg, offset = splitOffset(offset)
self.pos.x = unpack_from(">h", segment[seg], offset)[0]
self.pos.z = unpack_from(">h", segment[seg], offset + 2)[0]
self.pos.y = -unpack_from(">h", segment[seg], offset + 4)[0]
global scaleFactor
self.pos *= scaleFactor
self.uv.x = float(unpack_from(">h", segment[seg], offset + 8)[0])
self.uv.y = float(unpack_from(">h", segment[seg], offset + 10)[0])
self.normal.x = 0.00781250 * unpack_from("b", segment[seg], offset + 12)[0]
self.normal.z = 0.00781250 * unpack_from("b", segment[seg], offset + 13)[0]
self.normal.y = 0.00781250 * unpack_from("b", segment[seg], offset + 14)[0]
self.color[0] = min(0.00392157 * segment[seg][offset + 12], 1.0)
self.color[1] = min(0.00392157 * segment[seg][offset + 13], 1.0)
self.color[2] = min(0.00392157 * segment[seg][offset + 14], 1.0)
if checkUseVertexAlpha():
self.color[3] = min(0.00392157 * segment[seg][offset + 15], 1.0)
class Mesh:
def __init__(self):
self.verts, self.uvs, self.colors, self.faces = [], [], [], []
self.faces_use_smooth = []
self.vgroups = {}
# import normals
self.normals = []
def create(self, hierarchy, offset):
log = getLogger('Mesh.create')
if len(self.faces) == 0:
log.trace('Skipping empty mesh %08X', offset)
return
log.trace('Creating mesh %08X', offset)
me = bpy.data.meshes.new("me_%08X" % offset)
ob = bpy.data.objects.new("ob_%08X" % offset, me)
bpy.context.scene.objects.link(ob)
bpy.context.scene.objects.active = ob
me.vertices.add(len(self.verts))
for i in range(len(self.verts)):
me.vertices[i].co = self.verts[i]
me.tessfaces.add(len(self.faces))
vcd = me.tessface_vertex_colors.new().data
for i in range(len(self.faces)):
me.tessfaces[i].vertices = self.faces[i]
me.tessfaces[i].use_smooth = self.faces_use_smooth[i]
vcd[i].color1 = self.colors[i * 3 + 2]
vcd[i].color2 = self.colors[i * 3 + 1]
vcd[i].color3 = self.colors[i * 3]
uvd = me.tessface_uv_textures.new().data
for i in range(len(self.faces)):
if self.uvs[i * 4 + 3]:
if not self.uvs[i * 4 + 3].name in me.materials:
me.materials.append(self.uvs[i * 4 + 3])
uvd[i].image = self.uvs[i * 4 + 3].texture_slots[0].texture.image
uvd[i].uv[0] = self.uvs[i * 4 + 2]
uvd[i].uv[1] = self.uvs[i * 4 + 1]
uvd[i].uv[2] = self.uvs[i * 4]
me.calc_normals()
me.validate()
me.update()
# todo import normals (saving them in blender is the weird part)
"""
# doesn't work, blender eventually automatically recalculates normals
for i in range(len(self.verts)):
print(i)
print(self.normals[i])
me.vertices[i].normal = self.normals[i]
print(me.vertices[i].normal)
"""
"""
# https://blender.stackexchange.com/questions/104650/there-is-a-way-to-add-custom-split-normal-use-python-api/104664#104664
# this does set normals in a way that would carry through to oot
# however it seems like removing double vertices ruins most of it
me.normals_split_custom_set([(0, 0, 0) for l in me.loops])
me.normals_split_custom_set_from_vertices(self.normals)
"""
if hierarchy:
for name, vgroup in self.vgroups.items():
grp = ob.vertex_groups.new(name)
for v in vgroup:
grp.add([v], 1.0, 'REPLACE')
ob.parent = hierarchy.armature
mod = ob.modifiers.new(hierarchy.name, 'ARMATURE')
mod.object = hierarchy.armature
mod.use_bone_envelopes = False
mod.use_vertex_groups = True
mod.show_in_editmode = True
mod.show_on_cage = True
class Limb:
def __init__(self):
self.parent, self.child, self.sibling = -1, -1, -1
self.pos = Vector([0, 0, 0])
self.near, self.far = 0x00000000, 0x00000000
self.poseBone = None
self.poseLocPath, self.poseRotPath = None, None
self.poseLoc, self.poseRot = Vector([0, 0, 0]), None
def read(self, segment, offset, actuallimb, BoneCount):
seg, offset = splitOffset(offset)
rot_offset = offset & 0xFFFFFF
rot_offset += (0 * (BoneCount * 6 + 8));
self.pos.x = unpack_from(">h", segment[seg], offset)[0]
self.pos.z = unpack_from(">h", segment[seg], offset + 2)[0]
self.pos.y = -unpack_from(">h", segment[seg], offset + 4)[0]
global scaleFactor
self.pos *= scaleFactor
self.child = unpack_from("b", segment[seg], offset + 6)[0]
self.sibling = unpack_from("b", segment[seg], offset + 7)[0]
self.near = unpack_from(">L", segment[seg], offset + 8)[0]
self.far = unpack_from(">L", segment[seg], offset + 12)[0]
self.poseLoc.x = unpack_from(">h", segment[seg], rot_offset)[0]
self.poseLoc.z = unpack_from(">h", segment[seg], rot_offset + 2)[0]
self.poseLoc.y = unpack_from(">h", segment[seg], rot_offset + 4)[0]
getLogger('Limb.read').trace(" Limb %r: %f,%f,%f", (actuallimb, self.poseLoc.x, self.poseLoc.z, self.poseLoc.y))
class Hierarchy:
def __init__(self):
self.name, self.offset = "", 0x00000000
self.limbCount, self.dlistCount = 0x00, 0x00
self.limb = []
self.armature = None
def read(self, segment, offset):
log = getLogger('Hierarchy.read')
self.dlistCount = None
if not validOffset(segment, offset + 5):
log.error('Invalid segmented offset 0x%X for hierarchy' % (offset + 5))
return False
if not validOffset(segment, offset + 9):
log.warning('Invalid segmented offset 0x%X for hierarchy (incomplete header), still trying to import ignoring dlistCount' % (offset + 9))
self.dlistCount = 1
self.name = "sk_%08X" % offset
self.offset = offset
seg, offset = splitOffset(offset)
limbIndex_offset = unpack_from(">L", segment[seg], offset)[0]
if not validOffset(segment, limbIndex_offset):
log.error(" ERROR: Limb index table 0x%08X out of range" % limbIndex_offset)
return False
limbIndex_seg, limbIndex_offset = splitOffset(limbIndex_offset)
self.limbCount = segment[seg][offset + 4]
if not self.dlistCount:
self.dlistCount = segment[seg][offset + 8]
for i in range(self.limbCount):
limb_offset = unpack_from(">L", segment[limbIndex_seg], limbIndex_offset + 4 * i)[0]
limb = Limb()
limb.index = i
self.limb.append(limb)
if validOffset(segment, limb_offset + 12):
limb.read(segment, limb_offset, i, self.limbCount)
else:
log.error(" ERROR: Limb 0x%02X offset 0x%08X out of range" % (i, limb_offset))[0]
self.limb[0].pos = Vector([0, 0, 0])
self.initLimbs(0x00)
return True
def create(self):
rx, ry, rz = 90,0,0
if (bpy.context.active_object):
bpy.ops.object.mode_set(mode='OBJECT', toggle=False)
for i in bpy.context.selected_objects:
i.select = False
self.armature = bpy.data.objects.new(self.name, bpy.data.armatures.new("%s_armature" % self.name))
self.armature.show_x_ray = True
self.armature.data.draw_type = 'STICK'
bpy.context.scene.objects.link(self.armature)
bpy.context.scene.objects.active = self.armature
bpy.ops.object.mode_set(mode='EDIT', toggle=False)
for i in range(self.limbCount):
bone = self.armature.data.edit_bones.new("limb_%02i" % i)
bone.use_deform = True
bone.head = self.limb[i].pos
for i in range(self.limbCount):
bone = self.armature.data.edit_bones["limb_%02i" % i]
if (self.limb[i].parent != -1):
bone.parent = self.armature.data.edit_bones["limb_%02i" % self.limb[i].parent]
bone.use_connect = False
bone.tail = bone.head + Vector([0, 0, 0.0001])
bpy.ops.object.mode_set(mode='OBJECT')
def initLimbs(self, i):
if (self.limb[i].child > -1 and self.limb[i].child != i):
self.limb[self.limb[i].child].parent = i
self.limb[self.limb[i].child].pos += self.limb[i].pos
self.initLimbs(self.limb[i].child)
if (self.limb[i].sibling > -1 and self.limb[i].sibling != i):
self.limb[self.limb[i].sibling].parent = self.limb[i].parent
self.limb[self.limb[i].sibling].pos += self.limb[self.limb[i].parent].pos
self.initLimbs(self.limb[i].sibling)
def getMatrixLimb(self, offset):
j = 0
index = (offset & 0x00FFFFFF) / 0x40
for i in range(self.limbCount):
if self.limb[i].near != 0:
if (j == index):
return self.limb[i]
j += 1
return self.limb[0]
class F3DZEX:
def __init__(self):
self.segment, self.vbuf, self.tile = [], [], []
self.geometryModeFlags = None
self.animTotal = 0
self.TimeLine = 0
self.TimeLinePosition = 0
self.displaylists = []
for i in range(16):
self.segment.append([])
self.vbuf.append(Vertex())
for i in range(2):
self.tile.append(Tile())
self.vbuf.append(Vertex())
for i in range(14 + 32):
self.vbuf.append(Vertex())
self.curTile = 0
self.material = []
self.hierarchy = []
self.resetCombiner()
def loaddisplaylists(self, path):
log = getLogger('F3DZEX.loaddisplaylists')
try:
file = open(path, 'rb')
self.displaylists = file.readlines()
file.close()
log.info("Loaded the display list list successfully!")
except:
log.info("Did not find displaylists.txt!")
pass
def loadSegment(self, seg, path):
try:
file = open(path, 'rb')
self.segment[seg] = file.read()
file.close()
except:
getLogger('F3DZEX.loadSegment').error('Could not load segment 0x%02X data from %s' % (seg, path))
pass
def locateHierarchies(self):
log = getLogger('F3DZEX.locateHierarchies')
data = self.segment[0x06]
for i in range(0, len(data), 4):
# test for header "bboooooo pp000000 xx000000": if segment bb=0x06 and offset oooooo 4-aligned and not zero parts (pp!=0)
if data[i] == 0x06 and (data[i+3] & 3) == 0 and data[i+4] != 0:
offset = unpack_from(">L", data, i)[0] & 0x00FFFFFF
if offset < len(data):
# each Limb index entry is 4 bytes starting at offset
offset_end = offset + (data[i+4] << 2)
if offset_end <= len(data):
j = offset
while j < offset_end:
# test for limb entry "bboooooo": valid limb entry table as long as segment bb=0x06 and offset oooooo 4-aligned and offset is valid
if data[j] != 0x06 or (data[j+3] & 3) != 0 or (unpack_from(">L", data, j)[0] & 0x00FFFFFF) > len(data):
break
j += 4
if (j == i):
j |= 0x06000000
log.info(" hierarchy found at 0x%08X", j)
h = Hierarchy()
if h.read(self.segment, j):
self.hierarchy.append(h)
else:
log.warning('Skipping hierarchy at 0x%08X', j)
def locateAnimations(self):
log = getLogger('F3DZEX.locateAnimations')
data = self.segment[0x06]
self.animation = []
self.offsetAnims = []
self.durationAnims = []
for i in range(0, len(data), 4):
if ((data[i] == 0) and (data[i+1] > 1) and
(data[i+2] == 0) and (data[i+3] == 0) and
(data[i+4] == 0x06) and
(((data[i+5] << 16)|(data[i+6] << 8)|data[i+7]) < len(data)) and
(data[i+8] == 0x06) and
(((data[i+9] << 16)|(data[i+10] << 8)|data[i+11]) < len(data)) and
(data[i+14] == 0) and (data[i+15] == 0)):
log.info(" Anims found at %08X Frames: %d", i, data[i+1] & 0x00FFFFFF)
self.animation.append(i)
self.offsetAnims.append(i)
self.offsetAnims[self.animTotal] = (0x06 << 24) | i
self.durationAnims.append(data[i+1] & 0x00FFFFFF)
self.animTotal += 1
if(self.animTotal > 0):
log.info(" Total Anims : %d", self.animTotal)
def locateExternAnimations(self):
log = getLogger('F3DZEX.locateExternAnimations')
data = self.segment[0x0F]
self.animation = []
self.offsetAnims = []
for i in range(0, len(data), 4):
if ((data[i] == 0) and (data[i+1] > 1) and
(data[i+2] == 0) and (data[i+3] == 0) and
(data[i+4] == 0x06) and
(((data[i+5] << 16)|(data[i+6] << 8)|data[i+7]) < len(data)) and
(data[i+8] == 0x06) and
(((data[i+9] << 16)|(data[i+10] << 8)|data[i+11]) < len(data)) and
(data[i+14] == 0) and (data[i+15] == 0)):
log.info(" Ext Anims found at %08X" % i, "Frames:", data[i+1] & 0x00FFFFFF)
self.animation.append(i)
self.offsetAnims.append(i)
self.offsetAnims[self.animTotal] = (0x0F << 24) | i
self.animTotal += 1
if(self.animTotal > 0):
log.info(" Total Anims :", self.animTotal)
def locateLinkAnimations(self):
log = getLogger('F3DZEX.locateLinkAnimations')
data = self.segment[0x04]
self.animation = []
self.offsetAnims = []
self.animFrames = []
self.animTotal = -1
if (len( self.segment[0x04] ) > 0):
if (MajorasAnims):
for i in range(0xD000, 0xE4F8, 8):
self.animTotal += 1
self.animation.append(self.animTotal)
self.animFrames.append(self.animTotal)
self.offsetAnims.append(self.animTotal)
self.offsetAnims[self.animTotal] = unpack_from(">L", data, i + 4)[0]
self.animFrames[self.animTotal] = unpack_from(">h", data, i)[0]
log.debug('- Animation #%d offset: %07X frames: %d', self.animTotal+1, self.offsetAnims[self.animTotal], self.animFrames[self.animTotal])
else:
for i in range(0x2310, 0x34F8, 8):
self.animTotal += 1
self.animation.append(self.animTotal)
self.animFrames.append(self.animTotal)
self.offsetAnims.append(self.animTotal)
self.offsetAnims[self.animTotal] = unpack_from(">L", data, i + 4)[0]
self.animFrames[self.animTotal] = unpack_from(">h", data, i)[0]
log.debug('- Animation #%d offset: %07X frames: %d', self.animTotal+1, self.offsetAnims[self.animTotal], self.animFrames[self.animTotal])
log.info(" Link has come to town!!!!")
if ( (len( self.segment[0x07] ) > 0) and (self.animTotal > 0)):
self.buildLinkAnimations(self.hierarchy[0], 0)
def importMap(self):
log = getLogger('F3DZEX.importMap')
data = self.segment[0x03]
for i in range(0, len(data), 8):
if (data[i] == 0x0A and data[i+4] == 0x03):
mho = (data[i+5] << 16) | (data[i+6] << 8) | data[i+7]
if (mho < len(data)):
type = data[mho]
count = data[mho+1]
seg = data[mho+4]
start = (data[mho+5] << 16) | (data[mho+6] << 8) | data[mho+7]
end = (data[mho+9] << 16) | (data[mho+10] << 8) | data[mho+11]
log.info(" Mesh Type: %02X" % type)
if (data[mho+4] == 0x03 and start < end and end < len(data)):
log.info(" start %08X" % start)
log.info(" end %08X" % end)
if (type == 0):
for j in range(start, end, 4):
self.buildDisplayList(None, [None], unpack_from(">L", data, j)[0], False)
elif (type == 1 and count == 1):
#Noka here
end = start + 8
for j in range(start, end, 4):
self.buildDisplayList(None, [None], unpack_from(">L", data, j)[0], False)
elif (type == 2):
for j in range(start, end, 16):
near = (data[j+8] << 24)|(data[j+9] << 16)|(data[j+10] << 8)|data[j+11]
far = (data[j+12] << 24)|(data[j+13] << 16)|(data[j+14] << 8)|data[j+15]
if (near != 0):
self.buildDisplayList(None, [None], near, False)
elif (far != 0):
self.buildDisplayList(None, [None], far, False)
return
elif (data[i] == 0x14):
break
log.error("ERROR: Map header not found")
def importObj(self):
log = getLogger('F3DZEX.importObj')
log.info("Locating hierarchies...")
self.locateHierarchies()
if len(self.hierarchy) == 0:
log.info("Found zilch. Using display lists, then...")
if len(self.displaylists) == 0:
log.info("...but none were found...")
for dll in self.displaylists:
s = dll.decode("utf-8")
self.buildDisplayList(None, 0, int(s, 0), True)
return
for hierarchy in self.hierarchy:
log.info("Building hierarchy '%s'..." % hierarchy.name)
hierarchy.create()
for i in range(hierarchy.limbCount):
limb = hierarchy.limb[i]
if limb.near != 0:
if validOffset(self.segment, limb.near):
log.info(" 0x%02X : building display lists..." % i)
self.resetCombiner()
self.buildDisplayList(hierarchy, limb, limb.near, False)
else:
log.info(" 0x%02X : out of range" % i)
else:
log.info(" 0x%02X : n/a" % i)
if len(self.hierarchy) > 0:
bpy.context.scene.objects.active = self.hierarchy[0].armature
self.hierarchy[0].armature.select = True
bpy.ops.object.mode_set(mode='POSE', toggle=False)
global AnimtoPlay
if (AnimtoPlay > 0):
bpy.context.scene.frame_end = 1
if(ExternalAnimes and len(self.segment[0x0F]) > 0):
self.locateExternAnimations()
else:
self.locateAnimations()
if len(self.animation) > 0:
for h in self.hierarchy:
if h.armature.animation_data is None:
h.armature.animation_data_create()
# use the hierarchy with most bones
# this works for building any animation regardless of its target skeleton (bone positions) because all limbs are named limb_XX, so the hierarchy with most bones has bones with same names as every other armature
# and the rotation and root location animated values don't rely on the actual armature used
# and in blender each action can be used for any armature, vertex groups/bone names just have to match
# this is useful for iron knuckles and anything with several hierarchies, although an unedited iron kunckles zobj won't work
hierarchy = max(self.hierarchy, key=lambda h:h.limbCount)
armature = hierarchy.armature
log.info('Building animations using armature %s in %s', armature.data.name, armature.name)
for i in range(len(self.animation)):
AnimtoPlay = i + 1
log.info(" Loading animation %d/%d", AnimtoPlay, len(self.animation))
action = bpy.data.actions.new('anim%d_%d' % (AnimtoPlay, self.durationAnims[i]))
# not sure what users an action is supposed to have, or what it should be linked to
action.use_fake_user = True
armature.animation_data.action = action
self.buildAnimations(hierarchy, 0)
for h in self.hierarchy:
h.armature.animation_data.action = action
bpy.context.scene.frame_end = max(self.durationAnims)
else:
self.locateLinkAnimations()
else:
log.info(" Load anims OFF.")
def resetCombiner(self):
self.primColor = Vector([1.0, 1.0, 1.0, 1.0])
self.envColor = Vector([1.0, 1.0, 1.0, 1.0])
if checkUseVertexAlpha():
self.vertexColor = Vector([1.0, 1.0, 1.0, 1.0])
else:
self.vertexColor = Vector([1.0, 1.0, 1.0])
self.shadeColor = Vector([1.0, 1.0, 1.0])
def getCombinerColor(self):
def mult4d(v1, v2):
return Vector([v1[i] * v2[i] for i in range(4)])
cc = Vector([1.0, 1.0, 1.0, 1.0])
# todo these have an effect even if vertexMode == 'NONE' ?
if enablePrimColor:
cc = mult4d(cc, self.primColor)
if enableEnvColor:
cc = mult4d(cc, self.envColor)
# todo assume G_LIGHTING means normals if set, and colors if clear, but G_SHADE may play a role too?
if vertexMode == 'COLORS' or (vertexMode == 'AUTO' and 'G_LIGHTING' not in self.geometryModeFlags):
cc = mult4d(cc, self.vertexColor.to_4d())
elif vertexMode == 'NORMALS' or (vertexMode == 'AUTO' and 'G_LIGHTING' in self.geometryModeFlags):
cc = mult4d(cc, self.shadeColor.to_4d())
if checkUseVertexAlpha():
return cc
else:
return cc.xyz
def buildDisplayList(self, hierarchy, limb, offset, static):
log = getLogger('F3DZEX.buildDisplayList')
if static:
data = self.segment[0x6]
else:
data = self.segment[offset >> 24]
mesh = Mesh()
has_tex = False
material = None
if hierarchy:
matrix = [limb]
else:
matrix = [None]
if self.geometryModeFlags is None:
self.geometryModeFlags = set()
log.debug('Reading dlists from 0x%08X', offset)
for i in range(offset & 0x00FFFFFF, len(data), 8):
w0 = unpack_from(">L", data, i)[0]
w1 = unpack_from(">L", data, i + 4)[0]
if data[i] == 0x01:
count = (w0 >> 12) & 0xFF
index = ((w0 & 0xFF) >> 1) - count
vaddr = w1
if validOffset(self.segment, vaddr + int(16 * count) - 1):
for j in range(count):
self.vbuf[index + j].read(self.segment, vaddr + 16 * j)
if hierarchy:
self.vbuf[index + j].limb = matrix[len(matrix) - 1]
if self.vbuf[index + j].limb:
self.vbuf[index + j].pos += self.vbuf[index + j].limb.pos
elif data[i] == 0x02:
index = ((data[i + 2] & 0x0F) << 3) | (data[i + 3] >> 1)
if data[i + 1] == 0x10:
self.vbuf[index].normal.x = 0.00781250 * unpack_from("b", data, i + 4)[0]
self.vbuf[index].normal.z = 0.00781250 * unpack_from("b", data, i + 5)[0]
self.vbuf[index].normal.y = 0.00781250 * unpack_from("b", data, i + 6)[0]
self.vbuf[index].color = 0.00392157 * unpack_from("BBBB", data, i + 4)[0]
elif data[i + 1] == 0x14:
self.vbuf[index].uv.x = float(unpack_from(">h", data, i + 4)[0])
self.vbuf[index].uv.y = float(unpack_from(">h", data, i + 6)[0])
elif data[i] == 0x05 or data[i] == 0x06:
if has_tex:
material = None
for j in range(len(self.material)):
if self.material[j].name == "mtl_%08X" % self.tile[0].data:
material = self.material[j]
break
if material == None:
material = self.tile[0].create(self.segment)
if material:
self.material.append(material)
has_tex = False
v1, v2 = None, None
vi1, vi2 = -1, -1
if not importTextures:
material = None
count = 0
try:
for j in range(1, (data[i] - 4) * 4):
if j != 4:
v3 = self.vbuf[data[i + j] >> 1]
vi3 = -1
for k in range(len(mesh.verts)):
if mesh.verts[k] == (v3.pos.x, v3.pos.y, v3.pos.z):
vi3 = k
break
if vi3 == -1:
mesh.verts.append((v3.pos.x, v3.pos.y, v3.pos.z))
# import normals