mirrored from https://projects.blender.org/blender/blender-addons.git
-
Notifications
You must be signed in to change notification settings - Fork 193
/
Copy pathexport_3ds.py
2068 lines (1693 loc) · 87.2 KB
/
export_3ds.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
# SPDX-FileCopyrightText: 2005 Bob Holcomb
#
# SPDX-License-Identifier: GPL-2.0-or-later
"""
Exporting is based on 3ds loader from www.gametutorials.com(Thanks DigiBen) and using information
from the lib3ds project (http://lib3ds.sourceforge.net/) sourcecode.
"""
import bpy
import time
import math
import struct
import mathutils
import bpy_extras
from bpy_extras import node_shader_utils
###################
# Data Structures #
###################
# Some of the chunks that we will export
# >----- Primary Chunk, at the beginning of each file
PRIMARY = 0x4D4D
# >----- Main Chunks
OBJECTINFO = 0x3D3D # Main mesh object chunk before material and object information
MESHVERSION = 0x3D3E # This gives the version of the mesh
VERSION = 0x0002 # This gives the version of the .3ds file
KFDATA = 0xB000 # This is the header for all of the keyframe info
# >----- sub defines of OBJECTINFO
BITMAP = 0x1100 # The background image name
USE_BITMAP = 0x1101 # The background image flag
SOLIDBACKGND = 0x1200 # The background color (RGB)
USE_SOLIDBGND = 0x1201 # The background color flag
VGRADIENT = 0x1300 # The background gradient colors
USE_VGRADIENT = 0x1301 # The background gradient flag
O_CONSTS = 0x1500 # The origin of the 3D cursor
AMBIENTLIGHT = 0x2100 # The color of the ambient light
FOG = 0x2200 # The fog atmosphere settings
USE_FOG = 0x2201 # The fog atmosphere flag
DISTANCE_CUE = 0x2300 # The distance cue atmosphere settings
USE_DISTANCE_CUE = 0x2301 # The distance cue atmosphere flag
LAYER_FOG = 0x2302 # The fog layer atmosphere settings
USE_LAYER_FOG = 0x2303 # The fog layer atmosphere flag
MATERIAL = 45055 # 0xAFFF // This stored the texture info
OBJECT = 16384 # 0x4000 // This stores the faces, vertices, etc...
# >------ sub defines of MATERIAL
MATNAME = 0xA000 # This holds the material name
MATAMBIENT = 0xA010 # Ambient color of the object/material
MATDIFFUSE = 0xA020 # This holds the color of the object/material
MATSPECULAR = 0xA030 # Specular color of the object/material
MATSHINESS = 0xA040 # Specular intensity of the object/material (percent)
MATSHIN2 = 0xA041 # Reflection of the object/material (percent)
MATSHIN3 = 0xA042 # metallic/mirror of the object/material (percent)
MATTRANS = 0xA050 # Transparency value (100-OpacityValue) (percent)
MATXPFALL = 0xA052 # Transparency falloff ratio (percent)
MATREFBLUR = 0xA053 # Reflection blurring ratio (percent)
MATSELFILLUM = 0xA080 # # Material self illumination flag
MATSELFILPCT = 0xA084 # Self illumination strength (percent)
MATWIRE = 0xA085 # Material wireframe rendered flag
MATFACEMAP = 0xA088 # Face mapped textures flag
MATPHONGSOFT = 0xA08C # Phong soften material flag
MATWIREABS = 0xA08E # Wire size in units flag
MATWIRESIZE = 0xA087 # Rendered wire size in pixels
MATSHADING = 0xA100 # Material shading method
# >------ sub defines of MAT_MAP
MAT_DIFFUSEMAP = 0xA200 # This is a header for a new diffuse texture
MAT_SPECMAP = 0xA204 # head for specularity map
MAT_OPACMAP = 0xA210 # head for opacity map
MAT_REFLMAP = 0xA220 # head for reflect map
MAT_BUMPMAP = 0xA230 # head for normal map
MAT_BUMP_PERCENT = 0xA252 # Normalmap strength (percent)
MAT_TEX2MAP = 0xA33A # head for secondary texture
MAT_SHINMAP = 0xA33C # head for roughness map
MAT_SELFIMAP = 0xA33D # head for emission map
MAT_MAP_FILE = 0xA300 # This holds the file name of a texture
MAT_MAP_TILING = 0xa351 # 2nd bit (from LSB) is mirror UV flag
MAT_MAP_TEXBLUR = 0xA353 # Texture blurring factor
MAT_MAP_USCALE = 0xA354 # U axis scaling
MAT_MAP_VSCALE = 0xA356 # V axis scaling
MAT_MAP_UOFFSET = 0xA358 # U axis offset
MAT_MAP_VOFFSET = 0xA35A # V axis offset
MAT_MAP_ANG = 0xA35C # UV rotation around the z-axis in rad
MAP_COL1 = 0xA360 # Tint Color1
MAP_COL2 = 0xA362 # Tint Color2
MAP_RCOL = 0xA364 # Red tint
MAP_GCOL = 0xA366 # Green tint
MAP_BCOL = 0xA368 # Blue tint
RGB = 0x0010 # RGB float Color1
RGB1 = 0x0011 # RGB int Color1
RGBI = 0x0012 # RGB int Color2
RGBF = 0x0013 # RGB float Color2
PCT = 0x0030 # Percent chunk
PCTF = 0x0031 # Percent float
MASTERSCALE = 0x0100 # Master scale factor
# >------ sub defines of OBJECT
OBJECT_MESH = 0x4100 # This lets us know that we are reading a new object
OBJECT_LIGHT = 0x4600 # This lets us know we are reading a light object
OBJECT_CAMERA = 0x4700 # This lets us know we are reading a camera object
OBJECT_HIERARCHY = 0x4F00 # Hierarchy id of the object
OBJECT_PARENT = 0x4F10 # Parent id of the object
# >------ Sub defines of LIGHT
LIGHT_MULTIPLIER = 0x465B # The light energy factor
LIGHT_INNER_RANGE = 0x4659 # Light inner range value
LIGHT_OUTER_RANGE = 0x465A # Light outer range value
LIGHT_ATTENUATE = 0x4625 # Light attenuation flag
LIGHT_SPOTLIGHT = 0x4610 # The target of a spotlight
LIGHT_SPOT_ROLL = 0x4656 # Light spot roll angle
LIGHT_SPOT_SHADOWED = 0x4630 # Light spot shadow flag
LIGHT_SPOT_LSHADOW = 0x4641 # Light spot shadow parameters
LIGHT_SPOT_SEE_CONE = 0x4650 # Light spot show cone flag
LIGHT_SPOT_RECTANGLE = 0x4651 # Light spot rectangle flag
LIGHT_SPOT_OVERSHOOT = 0x4652 # Light spot overshoot flag
LIGHT_SPOT_PROJECTOR = 0x4653 # Light spot projection bitmap
LIGHT_SPOT_ASPECT = 0x4657 # Light spot aspect ratio
# >------ sub defines of CAMERA
OBJECT_CAM_RANGES = 0x4720 # The camera range values
# >------ sub defines of OBJECT_MESH
OBJECT_VERTICES = 0x4110 # The objects vertices
OBJECT_VERTFLAGS = 0x4111 # The objects vertex flags
OBJECT_FACES = 0x4120 # The objects faces
OBJECT_MATERIAL = 0x4130 # This is found if the object has a material, either texture map or color
OBJECT_UV = 0x4140 # The UV texture coordinates
OBJECT_SMOOTH = 0x4150 # The objects smooth groups
OBJECT_TRANS_MATRIX = 0x4160 # The Object Matrix
# >------ sub defines of KFDATA
AMBIENT_NODE_TAG = 0xB001 # Ambient node tag
OBJECT_NODE_TAG = 0xB002 # Object tree tag
CAMERA_NODE_TAG = 0xB003 # Camera object tag
TARGET_NODE_TAG = 0xB004 # Camera target tag
LIGHT_NODE_TAG = 0xB005 # Light object tag
LTARGET_NODE_TAG = 0xB006 # Light target tag
SPOT_NODE_TAG = 0xB007 # Spotlight tag
KFDATA_KFSEG = 0xB008 # Frame start & end
KFDATA_KFCURTIME = 0xB009 # Frame current
KFDATA_KFHDR = 0xB00A # Keyframe header
# >------ sub defines of OBJECT_NODE_TAG
OBJECT_NODE_ID = 0xB030 # Object hierachy ID
OBJECT_NODE_HDR = 0xB010 # Hierachy tree header
OBJECT_INSTANCE_NAME = 0xB011 # Object instance name
OBJECT_PARENT_NAME = 0x80F0 # Object parent name
OBJECT_PIVOT = 0xB013 # Object pivot position
OBJECT_BOUNDBOX = 0xB014 # Object boundbox
OBJECT_MORPH_SMOOTH = 0xB015 # Object smooth angle
POS_TRACK_TAG = 0xB020 # Position transform tag
ROT_TRACK_TAG = 0xB021 # Rotation transform tag
SCL_TRACK_TAG = 0xB022 # Scale transform tag
FOV_TRACK_TAG = 0xB023 # Field of view tag
ROLL_TRACK_TAG = 0xB024 # Roll transform tag
COL_TRACK_TAG = 0xB025 # Color transform tag
HOTSPOT_TRACK_TAG = 0xB027 # Hotspot transform tag
FALLOFF_TRACK_TAG = 0xB028 # Falloff transform tag
ROOT_OBJECT = 0xFFFF # Root object
EMPTYS = {'EMPTY'}
DUMMYS = {'ARMATURE', 'LATTICE', 'SPEAKER', 'VOLUME'}
OTHERS = {'CURVE', 'SURFACE', 'FONT', 'META'}
# So 3ds max can open files, limit names to 12 in length
# this is very annoying for filenames!
name_unique = [] # stores str, ascii only
name_mapping = {} # stores {orig: byte} mapping
def sane_name(name):
name_fixed = name_mapping.get(name)
if name_fixed is not None:
return name_fixed
# Strip non ascii chars
new_name_clean = new_name = name.encode("ASCII", "replace").decode("ASCII")[:16]
i = 0
while new_name in name_unique:
new_name = new_name_clean + '.%.3d' % i
i += 1
# Note, appending the 'str' version
name_unique.append(new_name)
name_mapping[name] = new_name = new_name.encode("ASCII", "replace")
return new_name
def uv_key(uv):
return round(uv[0], 6), round(uv[1], 6)
# Size defines
SZ_SHORT = 2
SZ_INT = 4
SZ_FLOAT = 4
class _3ds_ushort(object):
"""Class representing a short (2-byte integer) for a 3ds file."""
__slots__ = ("value", )
def __init__(self, val=0):
self.value = val
def get_size(self):
return SZ_SHORT
def write(self, file):
file.write(struct.pack('<H', self.value))
def __str__(self):
return str(self.value)
class _3ds_uint(object):
"""Class representing an int (4-byte integer) for a 3ds file."""
__slots__ = ("value", )
def __init__(self, val):
self.value = val
def get_size(self):
return SZ_INT
def write(self, file):
file.write(struct.pack('<I', self.value))
def __str__(self):
return str(self.value)
class _3ds_float(object):
"""Class representing a 4-byte IEEE floating point number for a 3ds file."""
__slots__ = ("value", )
def __init__(self, val):
self.value = val
def get_size(self):
return SZ_FLOAT
def write(self, file):
file.write(struct.pack('<f', self.value))
def __str__(self):
return str(self.value)
class _3ds_string(object):
"""Class representing a zero-terminated string for a 3ds file."""
__slots__ = ("value", )
def __init__(self, val):
assert type(val) == bytes
self.value = val
def get_size(self):
return (len(self.value) + 1)
def write(self, file):
binary_format = '<%ds' % (len(self.value) + 1)
file.write(struct.pack(binary_format, self.value))
def __str__(self):
return str((self.value).decode("ASCII"))
class _3ds_point_3d(object):
"""Class representing a three-dimensional point for a 3ds file."""
__slots__ = "x", "y", "z"
def __init__(self, point):
self.x, self.y, self.z = point
def get_size(self):
return 3 * SZ_FLOAT
def write(self, file):
file.write(struct.pack('<3f', self.x, self.y, self.z))
def __str__(self):
return '(%f, %f, %f)' % (self.x, self.y, self.z)
# Used for writing a track
class _3ds_point_4d(object):
"""Class representing a four-dimensional point for a 3ds file, for instance a quaternion."""
__slots__ = "w", "x", "y", "z"
def __init__(self, point):
self.w, self.x, self.y, self.z = point
def get_size(self):
return 4 * SZ_FLOAT
def write(self,file):
data=struct.pack('<4f', self.w, self.x, self.y, self.z)
file.write(data)
def __str__(self):
return '(%f, %f, %f, %f)' % (self.w, self.x, self.y, self.z)
class _3ds_point_uv(object):
"""Class representing a UV-coordinate for a 3ds file."""
__slots__ = ("uv", )
def __init__(self, point):
self.uv = point
def get_size(self):
return 2 * SZ_FLOAT
def write(self, file):
data = struct.pack('<2f', self.uv[0], self.uv[1])
file.write(data)
def __str__(self):
return '(%g, %g)' % self.uv
class _3ds_float_color(object):
"""Class representing a rgb float color for a 3ds file."""
__slots__ = "r", "g", "b"
def __init__(self, col):
self.r, self.g, self.b = col
def get_size(self):
return 3 * SZ_FLOAT
def write(self, file):
file.write(struct.pack('<3f', self.r, self.g, self.b))
def __str__(self):
return '{%f, %f, %f}' % (self.r, self.g, self.b)
class _3ds_rgb_color(object):
"""Class representing a (24-bit) rgb color for a 3ds file."""
__slots__ = "r", "g", "b"
def __init__(self, col):
self.r, self.g, self.b = col
def get_size(self):
return 3
def write(self, file):
file.write(struct.pack('<3B', int(255 * self.r), int(255 * self.g), int(255 * self.b)))
def __str__(self):
return '{%f, %f, %f}' % (self.r, self.g, self.b)
class _3ds_face(object):
"""Class representing a face for a 3ds file."""
__slots__ = ("vindex", "flag", )
def __init__(self, vindex, flag):
self.vindex = vindex
self.flag = flag
def get_size(self):
return 4 * SZ_SHORT
# No need to validate every face vert, the oversized array will catch this problem
def write(self, file):
# The last short is used for face flags
file.write(struct.pack('<4H', self.vindex[0], self.vindex[1], self.vindex[2], self.flag))
def __str__(self):
return '[%d %d %d %d]' % (self.vindex[0], self.vindex[1], self.vindex[2], self.flag)
class _3ds_array(object):
"""Class representing an array of variables for a 3ds file.
Consists of a _3ds_ushort to indicate the number of items, followed by the items themselves."""
__slots__ = "values", "size"
def __init__(self):
self.values = []
self.size = SZ_SHORT
# Add an item
def add(self, item):
self.values.append(item)
self.size += item.get_size()
def get_size(self):
return self.size
def validate(self):
return len(self.values) <= 65535
def write(self, file):
_3ds_ushort(len(self.values)).write(file)
for value in self.values:
value.write(file)
# To not overwhelm the output in a dump, a _3ds_array only
# outputs the number of items, not all of the actual items
def __str__(self):
return '(%d items)' % len(self.values)
class _3ds_named_variable(object):
"""Convenience class for named variables."""
__slots__ = "value", "name"
def __init__(self, name, val=None):
self.name = name
self.value = val
def get_size(self):
if self.value is None:
return 0
else:
return self.value.get_size()
def write(self, file):
if self.value is not None:
self.value.write(file)
def dump(self, indent):
if self.value is not None:
print(indent * " ",
self.name if self.name else "[unnamed]",
" = ",
self.value)
# The chunk class
class _3ds_chunk(object):
"""Class representing a chunk in a 3ds file.
Chunks contain zero or more variables, followed by zero or more subchunks."""
__slots__ = "ID", "size", "variables", "subchunks"
def __init__(self, chunk_id=0):
self.ID = _3ds_ushort(chunk_id)
self.size = _3ds_uint(0)
self.variables = []
self.subchunks = []
def add_variable(self, name, var):
"""Add a named variable.
The name is mostly for debugging purposes."""
self.variables.append(_3ds_named_variable(name, var))
def add_subchunk(self, chunk):
"""Add a subchunk."""
self.subchunks.append(chunk)
def get_size(self):
"""Calculate the size of the chunk and return it.
The sizes of the variables and subchunks are used to determine this chunk's size."""
tmpsize = self.ID.get_size() + self.size.get_size()
for variable in self.variables:
tmpsize += variable.get_size()
for subchunk in self.subchunks:
tmpsize += subchunk.get_size()
self.size.value = tmpsize
return self.size.value
def validate(self):
for var in self.variables:
func = getattr(var.value, "validate", None)
if (func is not None) and not func():
return False
for chunk in self.subchunks:
func = getattr(chunk, "validate", None)
if (func is not None) and not func():
return False
return True
def write(self, file):
"""Write the chunk to a file.
Uses the write function of the variables and the subchunks to do the actual work."""
# Write header
self.ID.write(file)
self.size.write(file)
for variable in self.variables:
variable.write(file)
for subchunk in self.subchunks:
subchunk.write(file)
def dump(self, indent=0):
"""Write the chunk to a file.
Dump is used for debugging purposes, to dump the contents of a chunk to the standard output.
Uses the dump function of the named variables and the subchunks to do the actual work."""
print(indent * " ",
'ID=%r' % hex(self.ID.value),
'size=%r' % self.get_size())
for variable in self.variables:
variable.dump(indent + 1)
for subchunk in self.subchunks:
subchunk.dump(indent + 1)
#############
# MATERIALS #
#############
def get_material_image(material):
""" Get images from paint slots."""
if material:
pt = material.paint_active_slot
tex = material.texture_paint_images
if pt < len(tex):
slot = tex[pt]
if slot.type == 'IMAGE':
return slot
def get_uv_image(ma):
""" Get image from material wrapper."""
if ma and ma.use_nodes:
mat_wrap = node_shader_utils.PrincipledBSDFWrapper(ma)
mat_tex = mat_wrap.base_color_texture
if mat_tex and mat_tex.image is not None:
return mat_tex.image
else:
return get_material_image(ma)
def make_material_subchunk(chunk_id, color):
"""Make a material subchunk.
Used for color subchunks, such as diffuse color or ambient color subchunks."""
mat_sub = _3ds_chunk(chunk_id)
col1 = _3ds_chunk(RGB1)
col1.add_variable("color1", _3ds_rgb_color(color))
mat_sub.add_subchunk(col1)
# Optional
# col2 = _3ds_chunk(RGBI)
# col2.add_variable("color2", _3ds_rgb_color(color))
# mat_sub.add_subchunk(col2)
return mat_sub
def make_percent_subchunk(chunk_id, percent):
"""Make a percentage based subchunk."""
pct_sub = _3ds_chunk(chunk_id)
pcti = _3ds_chunk(PCT)
pcti.add_variable("percent", _3ds_ushort(int(round(percent * 100, 0))))
pct_sub.add_subchunk(pcti)
# Optional
# pctf = _3ds_chunk(PCTF)
# pctf.add_variable("pctfloat", _3ds_float(round(percent, 6)))
# pct_sub.add_subchunk(pctf)
return pct_sub
def make_texture_chunk(chunk_id, teximages, pct):
"""Make Material Map texture chunk."""
# Add texture percentage value (100 = 1.0)
mat_sub = make_percent_subchunk(chunk_id, pct)
has_entry = False
def add_image(img, extension):
filename = bpy.path.basename(img.filepath)
mat_sub_file = _3ds_chunk(MAT_MAP_FILE)
mat_sub_tiling = _3ds_chunk(MAT_MAP_TILING)
mat_sub_file.add_variable("image", _3ds_string(sane_name(filename)))
mat_sub.add_subchunk(mat_sub_file)
tiling = 0
if extension == 'EXTEND': # decal flag
tiling |= 0x1
if extension == 'MIRROR': # mirror flag
tiling |= 0x2
if extension == 'CLIP': # no wrap
tiling |= 0x10
mat_sub_tiling.add_variable("tiling", _3ds_ushort(tiling))
mat_sub.add_subchunk(mat_sub_tiling)
for tex in teximages:
extend = tex.extension
add_image(tex.image, extend)
has_entry = True
return mat_sub if has_entry else None
def make_material_texture_chunk(chunk_id, texslots, pct):
"""Make Material Map texture chunk given a seq. of MaterialTextureSlot's
Paint slots are optionally used as image source if no nodes are used."""
# Add texture percentage value
mat_sub = make_percent_subchunk(chunk_id, pct)
has_entry = False
def add_texslot(texslot):
image = texslot.image
socket = None
filename = bpy.path.basename(image.filepath)
mat_sub_file = _3ds_chunk(MAT_MAP_FILE)
mat_sub_file.add_variable("mapfile", _3ds_string(sane_name(filename)))
mat_sub.add_subchunk(mat_sub_file)
for link in texslot.socket_dst.links:
socket = link.from_socket.identifier
mat_sub_mapflags = _3ds_chunk(MAT_MAP_TILING)
"""Control bit flags, where 0x1 activates decaling, 0x2 activates mirror,
0x8 activates inversion, 0x10 deactivates tiling, 0x20 activates summed area sampling,
0x40 activates alpha source, 0x80 activates tinting, 0x100 ignores alpha, 0x200 activates RGB tint.
Bits 0x80, 0x100, and 0x200 are only used with TEXMAP, TEX2MAP, and SPECMAP chunks.
0x40, when used with a TEXMAP, TEX2MAP, or SPECMAP chunk must be accompanied with a tint bit,
either 0x100 or 0x200, tintcolor will be processed if a tintflag was created."""
mapflags = 0
if texslot.extension == 'EXTEND':
mapflags |= 0x1
if texslot.extension == 'MIRROR':
mapflags |= 0x2
if texslot.extension == 'CLIP':
mapflags |= 0x10
if socket == 'Alpha':
mapflags |= 0x40
if texslot.socket_dst.identifier in {'Base Color', 'Specular Tint'}:
mapflags |= 0x80 if image.colorspace_settings.name == 'Non-Color' else 0x200
mat_sub_mapflags.add_variable("mapflags", _3ds_ushort(mapflags))
mat_sub.add_subchunk(mat_sub_mapflags)
texblur = 0.0
mat_sub_texblur = _3ds_chunk(MAT_MAP_TEXBLUR)
if texslot.socket_dst.identifier in {'Base Color', 'Specular Tint'}:
texblur = texslot.node_dst.inputs['Sheen Weight'].default_value
mat_sub_texblur.add_variable("maptexblur", _3ds_float(round(texblur, 6)))
mat_sub.add_subchunk(mat_sub_texblur)
mat_sub_uscale = _3ds_chunk(MAT_MAP_USCALE)
mat_sub_uscale.add_variable("mapuscale", _3ds_float(round(texslot.scale[0], 6)))
mat_sub.add_subchunk(mat_sub_uscale)
mat_sub_vscale = _3ds_chunk(MAT_MAP_VSCALE)
mat_sub_vscale.add_variable("mapvscale", _3ds_float(round(texslot.scale[1], 6)))
mat_sub.add_subchunk(mat_sub_vscale)
mat_sub_uoffset = _3ds_chunk(MAT_MAP_UOFFSET)
mat_sub_uoffset.add_variable("mapuoffset", _3ds_float(round(texslot.translation[0], 6)))
mat_sub.add_subchunk(mat_sub_uoffset)
mat_sub_voffset = _3ds_chunk(MAT_MAP_VOFFSET)
mat_sub_voffset.add_variable("mapvoffset", _3ds_float(round(texslot.translation[1], 6)))
mat_sub.add_subchunk(mat_sub_voffset)
mat_sub_angle = _3ds_chunk(MAT_MAP_ANG)
mat_sub_angle.add_variable("mapangle", _3ds_float(round(texslot.rotation[2], 6)))
mat_sub.add_subchunk(mat_sub_angle)
if texslot.socket_dst.identifier in {'Base Color', 'Specular Tint'}: # Add tint color
tint = texslot.socket_dst.identifier == 'Base Color' and texslot.image.colorspace_settings.name == 'Non-Color'
if tint or texslot.socket_dst.identifier == 'Specular Tint':
tint1 = _3ds_chunk(MAP_COL1)
tint2 = _3ds_chunk(MAP_COL2)
tint1.add_variable("tint1", _3ds_rgb_color(texslot.node_dst.inputs['Coat Tint'].default_value[:3]))
tint2.add_variable("tint2", _3ds_rgb_color(texslot.node_dst.inputs['Sheen Tint'].default_value[:3]))
mat_sub.add_subchunk(tint1)
mat_sub.add_subchunk(tint2)
# Store all textures for this mapto in order. This at least is what the
# 3DS exporter did so far, afaik most readers will just skip over 2nd textures
for slot in texslots:
if slot.image is not None:
add_texslot(slot)
has_entry = True
return mat_sub if has_entry else None
def make_material_chunk(material, image):
"""Make a material chunk out of a blender material.
Shading method is required for 3ds max, 0 for wireframe.
0x1 for flat, 0x2 for gouraud, 0x3 for phong and 0x4 for metal."""
material_chunk = _3ds_chunk(MATERIAL)
name = _3ds_chunk(MATNAME)
shading = _3ds_chunk(MATSHADING)
name_str = material.name if material else "None"
name.add_variable("name", _3ds_string(sane_name(name_str)))
material_chunk.add_subchunk(name)
if not material:
shading.add_variable("shading", _3ds_ushort(1)) # Flat shading
material_chunk.add_subchunk(make_material_subchunk(MATAMBIENT, (0.0, 0.0, 0.0)))
material_chunk.add_subchunk(make_material_subchunk(MATDIFFUSE, (0.8, 0.8, 0.8)))
material_chunk.add_subchunk(make_material_subchunk(MATSPECULAR, (1.0, 1.0, 1.0)))
material_chunk.add_subchunk(make_percent_subchunk(MATSHINESS, 0.8))
material_chunk.add_subchunk(make_percent_subchunk(MATSHIN2, 0.5))
material_chunk.add_subchunk(shading)
elif material and material.use_nodes:
wrap = node_shader_utils.PrincipledBSDFWrapper(material)
shading.add_variable("shading", _3ds_ushort(3)) # Phong shading
material_chunk.add_subchunk(make_material_subchunk(MATAMBIENT, wrap.emission_color[:3]))
material_chunk.add_subchunk(make_material_subchunk(MATDIFFUSE, wrap.base_color[:3]))
material_chunk.add_subchunk(make_material_subchunk(MATSPECULAR, wrap.specular_tint[:3]))
material_chunk.add_subchunk(make_percent_subchunk(MATSHINESS, 1 - wrap.roughness))
material_chunk.add_subchunk(make_percent_subchunk(MATSHIN2, wrap.specular))
material_chunk.add_subchunk(make_percent_subchunk(MATSHIN3, wrap.metallic))
material_chunk.add_subchunk(make_percent_subchunk(MATTRANS, 1 - wrap.alpha))
if wrap.node_principled_bsdf is not None:
material_chunk.add_subchunk(make_percent_subchunk(MATXPFALL, wrap.transmission))
material_chunk.add_subchunk(make_percent_subchunk(MATSELFILPCT, wrap.emission_strength))
material_chunk.add_subchunk(make_percent_subchunk(MATREFBLUR, wrap.node_principled_bsdf.inputs['Coat Weight'].default_value))
material_chunk.add_subchunk(shading)
primary_tex = False
mtype = 'MIX', 'MIX_RGB'
mtlks = material.node_tree.links
mxtex = [lk.from_node for lk in mtlks if lk.from_node.type == 'TEX_IMAGE' and lk.to_socket.identifier in {'Color2', 'B_Color'}]
mxpct = next((lk.from_node.inputs[0].default_value for lk in mtlks if lk.from_node.type in mtype and lk.to_node.type == 'BSDF_PRINCIPLED'), 0.5)
if wrap.base_color_texture:
color = [wrap.base_color_texture]
c_pct = 0.7 + sum(wrap.base_color[:]) * 0.1
matmap = make_material_texture_chunk(MAT_DIFFUSEMAP, color, c_pct)
if matmap:
material_chunk.add_subchunk(matmap)
primary_tex = True
if mxtex and not primary_tex:
material_chunk.add_subchunk(make_texture_chunk(MAT_DIFFUSEMAP, mxtex, mxpct))
primary_tex = True
if wrap.specular_tint_texture:
spec = [wrap.specular_tint_texture]
s_pct = material.specular_intensity
matmap = make_material_texture_chunk(MAT_SPECMAP, spec, s_pct)
if matmap:
material_chunk.add_subchunk(matmap)
if wrap.alpha_texture:
alpha = [wrap.alpha_texture]
a_pct = material.diffuse_color[3]
matmap = make_material_texture_chunk(MAT_OPACMAP, alpha, a_pct)
if matmap:
material_chunk.add_subchunk(matmap)
if wrap.metallic_texture:
metallic = [wrap.metallic_texture]
m_pct = material.metallic
matmap = make_material_texture_chunk(MAT_REFLMAP, metallic, m_pct)
if matmap:
material_chunk.add_subchunk(matmap)
if wrap.normalmap_texture:
normal = [wrap.normalmap_texture]
b_pct = wrap.normalmap_strength
matmap = make_material_texture_chunk(MAT_BUMPMAP, normal, b_pct)
if matmap:
material_chunk.add_subchunk(matmap)
material_chunk.add_subchunk(make_percent_subchunk(MAT_BUMP_PERCENT, b_pct))
if wrap.roughness_texture:
roughness = [wrap.roughness_texture]
r_pct = 1 - material.roughness
matmap = make_material_texture_chunk(MAT_SHINMAP, roughness, r_pct)
if matmap:
material_chunk.add_subchunk(matmap)
if wrap.emission_color_texture:
emission = [wrap.emission_color_texture]
e_pct = wrap.emission_strength
matmap = make_material_texture_chunk(MAT_SELFIMAP, emission, e_pct)
if matmap:
material_chunk.add_subchunk(matmap)
# Make sure no textures are lost. Everything that doesn't fit
# into a channel is exported as secondary texture
matmap = None
for link in mtlks:
mxsecondary = link.from_node if link.from_node.type == 'TEX_IMAGE' and link.to_socket.identifier in {'Color1', 'A_Color'} else False
if mxsecondary:
matmap = make_texture_chunk(MAT_TEX2MAP, [mxsecondary], 1 - mxpct)
if primary_tex and matmap:
material_chunk.add_subchunk(matmap)
else:
shading.add_variable("shading", _3ds_ushort(2)) # Gouraud shading
material_chunk.add_subchunk(make_material_subchunk(MATAMBIENT, material.line_color[:3]))
material_chunk.add_subchunk(make_material_subchunk(MATDIFFUSE, material.diffuse_color[:3]))
material_chunk.add_subchunk(make_material_subchunk(MATSPECULAR, material.specular_color[:]))
material_chunk.add_subchunk(make_percent_subchunk(MATSHINESS, 1 - material.roughness))
material_chunk.add_subchunk(make_percent_subchunk(MATSHIN2, material.specular_intensity))
material_chunk.add_subchunk(make_percent_subchunk(MATSHIN3, material.metallic))
material_chunk.add_subchunk(make_percent_subchunk(MATTRANS, 1 - material.diffuse_color[3]))
material_chunk.add_subchunk(shading)
slots = [get_material_image(material)] # Can be None
if image:
material_chunk.add_subchunk(make_texture_chunk(MAT_DIFFUSEMAP, slots))
return material_chunk
#############
# MESH DATA #
#############
class tri_wrapper(object):
"""Class representing a triangle.
Used when converting faces to triangles"""
__slots__ = "vertex_index", "ma", "image", "faceuvs", "offset", "flag", "group"
def __init__(self, vindex=(0, 0, 0), ma=None, image=None, faceuvs=None, flag=0, group=0):
self.vertex_index = vindex
self.ma = ma
self.image = image
self.faceuvs = faceuvs
self.offset = [0, 0, 0] # Offset indices
self.flag = flag
self.group = group
def extract_triangles(mesh):
"""Extract triangles from a mesh."""
mesh.calc_loop_triangles()
(polygroup, count) = mesh.calc_smooth_groups(use_bitflags=True)
tri_list = []
do_uv = bool(mesh.uv_layers)
img = None
for i, face in enumerate(mesh.loop_triangles):
f_v = face.vertices
v1, v2, v3 = f_v
uf = mesh.uv_layers.active.data if do_uv else None
if do_uv:
f_uv = [uf[lp].uv for lp in face.loops]
for ma in mesh.materials:
img = get_uv_image(ma) if uf else None
if img is not None:
img = img.name
uv1, uv2, uv3 = f_uv
"""Flag 0x1 sets CA edge visible, Flag 0x2 sets BC edge visible, Flag 0x4 sets AB edge visible
Flag 0x8 indicates a U axis texture wrap seam and Flag 0x10 indicates a V axis texture wrap seam
In Blender we use the edge CA, BC, and AB flags for sharp edges flags."""
a_b = mesh.edges[mesh.loops[face.loops[0]].edge_index]
b_c = mesh.edges[mesh.loops[face.loops[1]].edge_index]
c_a = mesh.edges[mesh.loops[face.loops[2]].edge_index]
if v3 == 0:
v1, v2, v3 = v3, v1, v2
a_b, b_c, c_a = c_a, a_b, b_c
if do_uv:
uv1, uv2, uv3 = uv3, uv1, uv2
faceflag = 0
if c_a.use_edge_sharp:
faceflag |= 0x1
if b_c.use_edge_sharp:
faceflag |= 0x2
if a_b.use_edge_sharp:
faceflag |= 0x4
smoothgroup = polygroup[face.polygon_index]
if len(f_v) == 3:
new_tri = tri_wrapper((v1, v2, v3), face.material_index, img)
if (do_uv):
new_tri.faceuvs = uv_key(uv1), uv_key(uv2), uv_key(uv3)
new_tri.flag = faceflag
new_tri.group = smoothgroup if face.use_smooth else 0
tri_list.append(new_tri)
return tri_list
def remove_face_uv(verts, tri_list):
"""Remove face UV coordinates from a list of triangles.
Since 3ds files only support one pair of uv coordinates for each vertex, face uv coordinates
need to be converted to vertex uv coordinates. That means that vertices need to be duplicated when
there are multiple uv coordinates per vertex."""
# Initialize a list of UniqueUVs, one per vertex
unique_uvs = [{} for i in range(len(verts))]
# For each face uv coordinate, add it to the UniqueList of the vertex
for tri in tri_list:
for i in range(3):
# Store the index into the UniqueList for future reference
# offset.append(uv_list[tri.vertex_index[i]].add(_3ds_point_uv(tri.faceuvs[i])))
context_uv_vert = unique_uvs[tri.vertex_index[i]]
uvkey = tri.faceuvs[i]
offset_index__uv_3ds = context_uv_vert.get(uvkey)
if not offset_index__uv_3ds:
offset_index__uv_3ds = context_uv_vert[uvkey] = len(context_uv_vert), _3ds_point_uv(uvkey)
tri.offset[i] = offset_index__uv_3ds[0]
# At this point each vertex has a UniqueList containing every uv coord associated with it only once
# Now we need to duplicate every vertex as many times as it has uv coordinates and make sure the
# faces refer to the new face indices
vert_index = 0
vert_array = _3ds_array()
uv_array = _3ds_array()
index_list = []
for i, vert in enumerate(verts):
index_list.append(vert_index)
pt = _3ds_point_3d(vert.co) # reuse, should be ok
uvmap = [None] * len(unique_uvs[i])
for ii, uv_3ds in unique_uvs[i].values():
# Add a vertex duplicate to the vertex_array for every uv associated with this vertex
vert_array.add(pt)
# Add the uv coordinate to the uv array, this for loop does not give
# uv's ordered by ii, so we create a new map and add the uv's later
uvmap[ii] = uv_3ds
# Add uv's in the correct order and add coordinates to the uv array
for uv_3ds in uvmap:
uv_array.add(uv_3ds)
vert_index += len(unique_uvs[i])
# Make sure the triangle vertex indices now refer to the new vertex list
for tri in tri_list:
for i in range(3):
tri.offset[i] += index_list[tri.vertex_index[i]]
tri.vertex_index = tri.offset
return vert_array, uv_array, tri_list
def make_faces_chunk(tri_list, mesh, materialDict):
"""Make a chunk for the faces.
Also adds subchunks assigning materials to all faces."""
do_smooth = False
use_smooth = [poly.use_smooth for poly in mesh.polygons]
if True in use_smooth:
do_smooth = True
materials = mesh.materials
if not materials:
ma = None
face_chunk = _3ds_chunk(OBJECT_FACES)
face_list = _3ds_array()
if mesh.uv_layers:
# Gather materials used in this mesh - mat/image pairs
unique_mats = {}
for i, tri in enumerate(tri_list):
face_list.add(_3ds_face(tri.vertex_index, tri.flag))
if materials:
ma = materials[tri.ma]
if ma:
ma = ma.name
img = tri.image
try:
context_face_array = unique_mats[ma, img][1]
except:
name_str = ma if ma else "None"
context_face_array = _3ds_array()
unique_mats[ma, img] = _3ds_string(sane_name(name_str)), context_face_array
context_face_array.add(_3ds_ushort(i))
face_chunk.add_variable("faces", face_list)
for ma_name, ma_faces in unique_mats.values():
obj_material_chunk = _3ds_chunk(OBJECT_MATERIAL)
obj_material_chunk.add_variable("name", ma_name)
obj_material_chunk.add_variable("face_list", ma_faces)
face_chunk.add_subchunk(obj_material_chunk)
else:
obj_material_faces = []
obj_material_names = []
for m in materials:
if m:
obj_material_names.append(_3ds_string(sane_name(m.name)))
obj_material_faces.append(_3ds_array())
n_materials = len(obj_material_names)
for i, tri in enumerate(tri_list):
face_list.add(_3ds_face(tri.vertex_index, tri.flag))
if (tri.ma < n_materials):
obj_material_faces[tri.ma].add(_3ds_ushort(i))