-
Notifications
You must be signed in to change notification settings - Fork 5
/
io_import_z64.py
2345 lines (2180 loc) · 116 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
# zelda64-import-blender
# Import models from Zelda64 files into Blender
# Copyright (C) 2013 SoulofDeity
# Copyright (C) 2020 Dragorn421
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>
bl_info = {
"name": "Zelda64 Importer",
"version": (2, 5),
"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
import re
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_operator_report_handler
root_logger = logging.getLogger('z64import')
root_logger_stream_handler = logging.StreamHandler()
root_logger_file_handler = None
root_logger_operator_report_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)
root_logger_file_handler.setLevel(1)
class OperatorReportLogHandler(logging.Handler):
def __init__(self, operator):
super().__init__()
self.operator = operator
def flush(self):
pass
def emit(self, record):
try:
type = 'DEBUG'
for levelType, minLevel in (
('ERROR', logging.WARNING), # comment to allow calling bpy.ops.file.zobj2020 without RuntimeError (makes WARNING the highest report level instead of ERROR)
('WARNING', logging.INFO),
('INFO', logging.DEBUG)
):
if record.levelno > minLevel:
type = levelType
break
msg = self.format(record)
self.operator.report({type}, msg)
except Exception:
self.handleError(record)
def setLogOperator(operator, level=logging.INFO):
global root_logger, root_logger_formatter, root_logger_operator_report_handler
if root_logger_operator_report_handler:
root_logger.removeHandler(root_logger_operator_report_handler)
root_logger_operator_report_handler = None
if operator:
root_logger_operator_report_handler = OperatorReportLogHandler(operator)
root_logger_operator_report_handler.setFormatter(root_logger_formatter)
root_logger_operator_report_handler.setLevel(level)
root_logger.addHandler(root_logger_operator_report_handler)
def unregisterLogging():
global root_logger, root_logger_stream_handler
setLogFile(None)
setLogOperator(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.current_texture_file_path = None
self.texFmt, self.texBytes = 0x00, 0
self.width, self.height = 0, 0
self.rWidth, self.rHeight = 0, 0
self.texSiz = 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 getFormatName(self):
fmt = ['RGBA','YUV','CI','IA','I']
siz = ['4','8','16','32']
return '%s%s' % (
fmt[self.texFmt] if self.texFmt < len(fmt) else 'UnkFmt',
siz[self.texSiz] if self.texSiz < len(siz) else '_UnkSiz'
)
def create(self, segment, use_transparency, prefix=""):
# todo texture files are written several times, at each usage
log = getLogger('Tile.create')
fmtName = self.getFormatName()
#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 = (
'%s/textures/%s%s_%08X%s%s.tga'
% (fpath, prefix, fmtName, self.data,
('_pal%08X' % self.palette) if self.texFmt == 2 else '',
extrastring))
if exportTextures: # fixme exportTextures == False breaks the script
try:
os.mkdir(fpath + "/textures")
except FileExistsError:
pass
except:
log.exception('Could not create textures directory %s' % (fpath + "/textures"))
pass
if not os.path.isfile(self.current_texture_file_path):
log.debug('Writing texture %s (format 0x%02X)' % (self.current_texture_file_path, self.texFmt))
file = open(self.current_texture_file_path, 'wb')
self.write_error_encountered = False
if self.texFmt == 2:
if self.texSiz not in (0, 1):
log.error('Unknown texture format %d with pixel size %d', self.texFmt, self.texSiz)
p = 16 if self.texSiz == 0 else 256
file.write(pack("<BBBHHBHHHHBB",
0, # image comment length
1, # 1 = paletted
1, # 1 = indexed uncompressed colors
0, # index of first palette entry (?)
p, # amount of entries in palette
32, # bits per pixel
0, # bottom left X (?)
0, # bottom left Y (?)
w, # width
h, # height
8, # pixel depth
8 # 8 bits alpha hopefully?
))
self.writePalette(file, segment, p)
else:
file.write(pack("<BBBHHBHHHHBB",
0, # image comment length
0, # no palette
2, # uncompressed Truecolor (24-32 bits)
0, # irrelevant, no palette
0, # irrelevant, no palette
0, # irrelevant, no palette
0, # bottom left X (?)
0, # bottom left Y (?)
w, # width
h, # height
32,# pixel depth
8 # 8 bits alpha (?)
))
if int(self.clip.y) & 1 != 0 and replicateTexMirrorBlender:
self.writeImageData(file, segment, True)
else:
self.writeImageData(file, segment)
file.close()
if self.write_error_encountered:
oldName = self.current_texture_file_path
oldNameDir, oldNameBase = os.path.split(oldName)
newName = oldNameDir + '/' + prefix + 'fallback_' + oldNameBase
log.warning('Moving failed texture file import from %s to %s', oldName, newName)
if os.path.isfile(newName):
os.remove(newName)
os.rename(oldName, newName)
self.current_texture_file_path = newName
try:
tex_name = prefix + ('tex_%s_%08X' % (fmtName,self.data))
tex = bpy.data.textures.new(name=tex_name, type='IMAGE')
img = load_image(self.current_texture_file_path)
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_name = prefix + ('mtl_%08X' % self.data)
mtl = bpy.data.materials.new(name=mtl_name)
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 use_transparency:
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):
log = getLogger('Tile.calculateSize')
maxTxl, lineShift = 0, 0
# fixme what is maxTxl? this whole function is rather mysterious, not sure how/why it works
#texFmt 0 2 texSiz 0
# RGBA CI 4b
if (self.texFmt == 0 or self.texFmt == 2) and self.texSiz == 0:
maxTxl = 4096
lineShift = 4
# texFmt 3 4 texSiz 0
# IA I 4b
elif (self.texFmt == 3 or self.texFmt == 4) and self.texSiz == 0:
maxTxl = 8192
lineShift = 4
# texFmt 0 2 texSiz 1
# RGBA CI 8b
elif (self.texFmt == 0 or self.texFmt == 2) and self.texSiz == 1:
maxTxl = 2048
lineShift = 3
# texFmt 3 4 texSiz 1
# IA I 8b
elif (self.texFmt == 3 or self.texFmt == 4) and self.texSiz == 1:
maxTxl = 4096
lineShift = 3
# texFmt 0 3 texSiz 2
# RGBA IA 16b
elif (self.texFmt == 0 or self.texFmt == 3) and self.texSiz == 2:
maxTxl = 2048
lineShift = 2
# texFmt 2 4 texSiz 2
# CI I 16b
elif (self.texFmt == 2 or self.texFmt == 4) and self.texSiz == 2:
maxTxl = 2048
lineShift = 0
# texFmt 0 texSiz 3
# RGBA 32b
elif self.texFmt == 0 and self.texSiz == 3:
maxTxl = 1024
lineShift = 2
else:
log.warning('Unknown format for texture %s texFmt %d texSiz %d', self.current_texture_file_path, self.texFmt, self.texSiz)
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, palSize):
log = getLogger('Tile.writePalette')
if not validOffset(segment, self.palette + 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 + palSize * 2 - 1, self.current_texture_file_path))
for i in range(palSize):
file.write(pack("L", 0))
self.write_error_encountered = True
return
seg, offset = splitOffset(self.palette)
for i in range(palSize):
color = unpack_from(">H", segment[seg], offset + i * 2)[0]
r = int(255/31 * ((color >> 11) & 0b11111))
g = int(255/31 * ((color >> 6) & 0b11111))
b = int(255/31 * ((color >> 1) & 0b11111))
a = 255 * (color & 1)
file.write(pack("BBBB", b, g, r, a))
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.texSiz <= 3:
bpp = (0.5,1,2,4)[self.texSiz] # bytes (not bits) per pixel
else:
log.warning('Unknown texSiz %d for texture %s, defaulting to 4 bytes per pixel' % (self.texSiz, self.current_texture_file_path))
bpp = 4
lineSize = self.rWidth * bpp
writeFallbackData = False
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))
writeFallbackData = True
if (self.texFmt,self.texSiz) not in (
(0,2), (0,3), # RGBA16, RGBA32
#(1,-1), # YUV ? "not used in z64 games"
(2,0), (2,1), # CI4, CI8
(3,0), (3,1), (3,2), # IA4, IA8, IA16
(4,0), (4,1), # I4, I8
):
log.error('Unknown fmt/siz combination %d/%d (%s?)', self.texFmt, self.texSiz, self.getFormatName())
writeFallbackData = True
if writeFallbackData:
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 == 2: # CI (paletted)
file.write(pack("B", 0))
else:
file.write(pack(">L", 0x000000FF))
self.write_error_encountered = True
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: # 0.5, 1
color = unpack_from("B", segment[seg], off + int(floor(j)))[0]
if bpp == 0.5:
color = ((color >> 4) if j % 1 == 0 else color) & 0xF
elif bpp == 2:
color = unpack_from(">H", segment[seg], off + j)[0]
else: # 4
color = unpack_from(">L", segment[seg], off + j)[0]
if self.texFmt == 0: # RGBA
if self.texSiz == 2: # RGBA16
r = ((color >> 11) & 0b11111) * 255 // 31
g = ((color >> 6) & 0b11111) * 255 // 31
b = ((color >> 1) & 0b11111) * 255 // 31
a = (color & 1) * 255
elif self.texSiz == 3: # RGBA32
r = (color >> 24) & 0xFF
g = (color >> 16) & 0xFF
b = (color >> 8) & 0xFF
a = color & 0xFF
elif self.texFmt == 2: # CI
if self.texSiz == 0: # CI4
p = color
elif self.texSiz == 1: # CI8
p = color
elif self.texFmt == 3: # IA
if self.texSiz == 0: # IA4
r = g = b = (color >> 1) * 255 // 7
a = (color & 1) * 255
elif self.texSiz == 1: # IA8
r = g = b = (color >> 4) * 255 // 15
a = (color & 0xF) * 255 // 15
elif self.texSiz == 2: # IA16
r = g = b = color >> 8
a = color & 0xFF
elif self.texFmt == 4: # I
if self.texSiz == 0: # I4
r = g = b = a = color * 255 // 15
elif self.texSiz == 1: # I8
r = g = b = a = color
try:
if self.texFmt == 2: # CI
line.append(p)
else:
line.append((b << 24) | (g << 16) | (r << 8) | a)
except UnboundLocalError:
log.error('Unknown format texFmt %d texSiz %d', self.texFmt, self.texSiz)
raise
"""
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 == 2: # CI # in (0x40, 0x48, 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 == 2: # CI # in (0x40, 0x48, 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 = unpack_from("b", segment[seg], offset + 12)[0] / 128
self.normal.z = unpack_from("b", segment[seg], offset + 13)[0] / 128
self.normal.y = -unpack_from("b", segment[seg], offset + 14)[0] / 128
self.color[0] = min(segment[seg][offset + 12] / 255, 1.0)
self.color[1] = min(segment[seg][offset + 13] / 255, 1.0)
self.color[2] = min(segment[seg][offset + 14] / 255, 1.0)
if checkUseVertexAlpha():
self.color[3] = min(segment[seg][offset + 15] / 255, 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, name_format, hierarchy, offset, use_normals, prefix=""):
log = getLogger('Mesh.create')
if len(self.faces) == 0:
log.trace('Skipping empty mesh %08X', offset)
if self.verts:
log.warning('Discarding unused vertices, no faces')
return
log.trace('Creating mesh %08X', offset)
me_name = prefix + (name_format % ('me_%08X' % offset))
me = bpy.data.meshes.new(me_name)
ob = bpy.data.objects.new(prefix + (name_format % ('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]
vcd[i].color2 = self.colors[i * 3 + 1]
vcd[i].color3 = self.colors[i * 3 + 2]
uvd = me.tessface_uv_textures.new().data
for i in range(len(self.faces)):
material = self.uvs[i * 4]
if material:
if not material.name in me.materials:
me.materials.append(material)
uvd[i].image = material.texture_slots[0].texture.image
uvd[i].uv[0] = self.uvs[i * 4 + 1]
uvd[i].uv[1] = self.uvs[i * 4 + 2]
uvd[i].uv[2] = self.uvs[i * 4 + 3]
me.calc_normals()
me.validate()
me.update()
log.debug('me =\n%r', me)
log.debug('verts =\n%r', self.verts)
log.debug('faces =\n%r', self.faces)
log.debug('normals =\n%r', self.normals)
if use_normals:
# fixme make sure normals are set in the right order
# fixme duplicate faces make normal count not the loop count
loop_normals = []
for face_normals in self.normals:
loop_normals.extend(n for vi,n in face_normals)
me.use_auto_smooth = True
try:
me.normals_split_custom_set(loop_normals)
except:
log.exception('normals_split_custom_set failed, known issue due to duplicate faces')
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, prefix=""):
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 = prefix + ("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, prefix=""):
self.prefix = prefix
self.use_transparency = detectedDisplayLists_use_transparency
self.alreadyRead = []
self.segment, self.vbuf, self.tile = [], [], []
self.geometryModeFlags = set()
self.animTotal = 0
self.TimeLine = 0
self.TimeLinePosition = 0
self.displaylists = []
for i in range(16):
self.alreadyRead.append([])
self.segment.append([])
self.vbuf.append(Vertex())
for i in range(2):
self.tile.append(Tile())
pass#self.vbuf.append(Vertex())
for i in range(14 + 32):
pass#self.vbuf.append(Vertex())
while len(self.vbuf) < 32:
self.vbuf.append(Vertex())
self.curTile = 0
self.material = []
self.hierarchy = []
self.resetCombiner()
def loaddisplaylists(self, path):
log = getLogger('F3DZEX.loaddisplaylists')
if not os.path.isfile(path):
log.info('Did not find %s (use to manually set offsets of display lists to import)', path)
self.displaylists = []
return
try:
file = open(path)
self.displaylists = file.readlines()
file.close()
log.info("Loaded the display list list successfully!")
except:
log.exception('Could not read displaylists.txt')
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)-11, 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, prefix=self.prefix):
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)-15, 4):
# detect animation header
# ffff0000 rrrrrrrr iiiiiiii llll0000
# fixme data[i] == 0 but should be first byte of ffff
# fixme data[i+1] > 1 but why not 1 (or 0)
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
# fixme it's two bytes, not one
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)-15, 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 importJFIF(self, data, initPropsOffset, name_format='bg_%08X'):
log = getLogger('F3DZEX.importJFIF')
( imagePtr,
unknown, unknown2,
background_width, background_height,
imageFmt, imageSiz, imagePal, imageFlip
) = struct.unpack_from('>IIiHHBBHH', data, initPropsOffset)
t = Tile()
t.texFmt = imageFmt
t.texSiz = imageSiz
log.debug(
'JFIF background image init properties\n'
'imagePtr=0x%X size=%dx%d fmt=%d, siz=%d (%s) imagePal=%d imageFlip=%d',
imagePtr, background_width, background_height,
imageFmt, imageSiz, t.getFormatName(), imagePal, imageFlip
)
if imagePtr >> 24 != 0x03:
log.error('Skipping JFIF background image, pointer 0x%08X is not in segment 0x03', imagePtr)
return False
jfifDataStart = imagePtr & 0xFFFFFF
# read header just for sanity checks
# source: CloudModding wiki https://wiki.cloudmodding.com/oot/JFIF_Backgrounds
( marker_begin,
marker_begin_header, header_length,
jfif, null, version,
dens, densx, densy,
thumbnail_width, thumbnail_height,
marker_end_header
) = struct.unpack_from('>HHHIBHBHHBBH', data, jfifDataStart)
badJfif = []
if marker_begin != 0xFFD8:
badJfif.append('Expected marker_begin=0xFFD8 instead of 0x%04X' % marker_begin)
if marker_begin_header != 0xFFE0:
badJfif.append('Expected marker_begin_header=0xFFE0 instead of 0x%04X' % marker_begin_header)
if header_length != 16:
badJfif.append('Expected header_length=16 instead of %d=0x%04X' % (header_length, header_length))
if jfif != 0x4A464946: # JFIF
badJfif.append('Expected jfif=0x4A464946="JFIF" instead of 0x%08X' % jfif)
if null != 0:
badJfif.append('Expected null=0 instead of 0x%02X' % null)
if version != 0x0101:
badJfif.append('Expected version=0x0101 instead of 0x%04X' % version)
if dens != 0:
badJfif.append('Expected dens=0 instead of %d=0x%02X' % (dens, dens))
if densx != 1:
badJfif.append('Expected densx=1 instead of %d=0x%04X' % (densx, densx))
if densy != 1:
badJfif.append('Expected densy=1 instead of %d=0x%04X' % (densy, densy))
if thumbnail_width != 0:
badJfif.append('Expected thumbnail_width=0 instead of %d=0x%02X' % (thumbnail_width, thumbnail_width))
if thumbnail_height != 0:
badJfif.append('Expected thumbnail_height=0 instead of %d=0x%02X' % (thumbnail_height, thumbnail_height))
if marker_end_header != 0xFFDB:
badJfif.append('Expected marker_end_header=0xFFDB instead of 0x%04X' % marker_end_header)
if badJfif:
log.error('Bad JFIF format for background image at 0x%X:', jfifDataStart)
for badJfifMessage in badJfif:
log.error(badJfifMessage)
return False
jfifData = None
i = jfifDataStart
for i in range(jfifDataStart, len(data)-1):