forked from RainWarrior/B3DExport
-
Notifications
You must be signed in to change notification settings - Fork 16
/
B3DExport.py
1539 lines (1150 loc) · 56.7 KB
/
B3DExport.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
#!BPY
"""
Name: 'B3D Exporter (.b3d)...'
Blender: 259
Group: 'Export'
Tooltip: 'Export to Blitz3D file format (.b3d)'
"""
__author__ = ["iego 'GaNDaLDF' Parisi, MTLZ (is06), Joerg Henrichs, Marianne Gagnon"]
__url__ = ["www.gandaldf.com"]
__version__ = "3.0"
__bpydoc__ = """\
"""
# BLITZ3D EXPORTER 3.0
# Copyright (C) 2009 by Diego "GaNDaLDF" Parisi - www.gandaldf.com
# Lightmap issue fixed by Capricorn 76 Pty. Ltd. - www.capricorn76.com
# Blender 2.63 compatiblity based on work by MTLZ, www.is06.com
# With changes by Marianne Gagnon and Joerg Henrichs, supertuxkart.sf.net (Copyright (C) 2011-2012)
#
# LICENSE:
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
bl_info = {
"name": "B3D (BLITZ3D) Model Exporter",
"description": "Exports a blender scene or object to the B3D (BLITZ3D) format",
"author": "Diego 'GaNDaLDF' Parisi, MTLZ (is06), Joerg Henrichs, Marianne Gagnon",
"version": (3,1),
"blender": (2, 5, 9),
"api": 31236,
"location": "File > Export",
"warning": '', # used for warning icon and text in addons panel
"wiki_url": "http://supertuxkart.sourceforge.net/Get_involved",
"tracker_url": "https://sourceforge.net/apps/trac/supertuxkart/",
"category": "Import-Export"}
import bpy
import sys,os,os.path,struct,math,string
import mathutils
import math
if not hasattr(sys,"argv"): sys.argv = ["???"]
#Global Stacks
b3d_parameters = {}
texture_flags = []
texs_stack = {}
brus_stack = []
vertex_groups = []
bone_stack = {}
keys_stack = []
texture_count = 0
# bone_stack indices constants
BONE_PARENT_MATRIX = 0
BONE_PARENT = 1
BONE_ITSELF = 2
# texture stack indices constants
TEXTURE_ID = 0
TEXTURE_FLAGS = 1
per_face_vertices = {}
the_scene = None
#Transformation Matrix
TRANS_MATRIX = mathutils.Matrix([[1,0,0,0],[0,0,1,0],[0,1,0,0],[0,0,0,1]])
BONE_TRANS_MATRIX = mathutils.Matrix([[-1,0,0,0],[0,0,-1,0],[0,-1,0,0],[0,0,0,1]])
DEBUG = False
PROGRESS = True
PROGRESS_VERBOSE = False
tesselated_objects = {}
#Support Functions
def write_int(value):
return struct.pack("<i",value)
def write_float(value):
return struct.pack("<f",value)
def write_float_couple(value1, value2):
return struct.pack("<ff", value1, value2)
def write_float_triplet(value1, value2, value3):
return struct.pack("<fff", value1, value2, value3)
def write_float_quad(value1, value2, value3, value4):
return struct.pack("<ffff", value1, value2, value3, value4)
def write_string(value):
binary_format = "<%ds"%(len(value)+1)
return struct.pack(binary_format, str.encode(value))
def write_chunk(name,value):
dummy = bytearray()
return dummy + name + write_int(len(value)) + value
trimmed_paths = {}
def getArmatureAnimationEnd(armature):
end_frame = 1
if armature.animation_data.action:
ipo = armature.animation_data.action.fcurves
for curve in ipo:
if "pose" in curve.data_path:
end_frame = max(end_frame, curve.keyframe_points[-1].co[0])
for nla_track in armature.animation_data.nla_tracks:
if len(nla_track.strips) > 0:
end_frame = max(end_frame, nla_track.strips[-1].frame_end)
return end_frame
# ==== Write B3D File ====
# (main exporter function)
def write_b3d_file(filename, objects=[]):
global texture_flags, texs_stack, trimmed_paths, tesselated_objects
global brus_stack, vertex_groups, bone_stack, keys_stack
#Global Stacks
texture_flags = []
texs_stack = {}
brus_stack = []
vertex_groups = []
bone_stack = []
keys_stack = []
trimmed_paths = {}
file_buf = bytearray()
temp_buf = bytearray()
tesselated_objects = {}
import time
start = time.time()
temp_buf += write_int(1) #Version
temp_buf += write_texs(objects) #TEXS
temp_buf += write_brus(objects) #BRUS
temp_buf += write_node(objects) #NODE
if len(temp_buf) > 0:
file_buf += write_chunk(b"BB3D",temp_buf)
temp_buf = ""
file = open(filename,'wb')
file.write(file_buf)
file.close()
# free memory
trimmed_paths = {}
end = time.time()
print("Exported in", (end - start))
def tesselate_if_needed(objdata):
if objdata not in tesselated_objects:
objdata.calc_tessface()
tesselated_objects[objdata] = True
return objdata
def getUVTextures(obj_data):
# BMesh in blender 2.63 broke this
if bpy.app.version[1] >= 63:
return tesselate_if_needed(obj_data).tessface_uv_textures
else:
return obj_data.uv_textures
def getFaces(obj_data):
# BMesh in blender 2.63 broke this
if bpy.app.version[1] >= 63:
return tesselate_if_needed(obj_data).tessfaces
else:
return obj_data.faces
def getVertexColors(obj_data):
# BMesh in blender 2.63 broke this
if bpy.app.version[1] >= 63:
return tesselate_if_needed(obj_data).tessface_vertex_colors
else:
return obj_data.vertex_colors
# ==== Write TEXS Chunk ====
def write_texs(objects=[]):
global b3d_parameters
global trimmed_paths
global texture_count
texs_buf = bytearray()
temp_buf = bytearray()
layer_max = 0
obj_count = 0
set_wrote = 0
if objects:
exp_obj = objects
else:
if b3d_parameters.get("export-selected"):
exp_obj = [ob for ob in bpy.data.objects if ob.select]
else:
exp_obj = bpy.data.objects
if PROGRESS: print(len(exp_obj),"TEXS")
if PROGRESS_VERBOSE: progress = 0
for obj in exp_obj:
if PROGRESS_VERBOSE:
progress = progress + 1
if (progress % 10 == 0): print("TEXS",progress,"/",len(exp_obj))
if obj.type == "MESH":
set_count = 0
set_wrote = 0
#data = obj.getData(mesh = True)
data = obj.data
# FIXME?
#orig_uvlayer = data.activeUVLayer
layer_set = [[],[],[],[],[],[],[],[]]
# 8 UV layers are supported
texture_flags.append([None,None,None,None,None,None,None,None])
#if len(data.getUVLayerNames()) <= 8:
uv_textures = getUVTextures(data)
if len(uv_textures) <= 8:
if len(uv_textures) > layer_max:
layer_max = len(uv_textures)
else:
layer_max = 8
for face in getFaces(data):
for iuvlayer,uvlayer in enumerate(uv_textures):
if iuvlayer < 8:
# FIXME?
#data.activeUVLayer = uvlayer
#layer_set[iuvlayer].append(face.uv)
new_data = None
try:
new_data = uvlayer.data[face.index].uv
except:
pass
layer_set[iuvlayer].append( new_data )
for i in range(len(uv_textures)):
if set_wrote:
set_count += 1
set_wrote = 0
for iuvlayer in range(i,len(uv_textures)):
if layer_set[i] == layer_set[iuvlayer]:
if texture_flags[obj_count][iuvlayer] is None:
if set_count == 0:
tex_flag = 1
elif set_count == 1:
tex_flag = 65536
elif set_count > 1:
tex_flag = 1
if b3d_parameters.get("mipmap"):
enable_mipmaps=8
else:
enable_mipmaps=0
texture_flags[obj_count][iuvlayer] = tex_flag | enable_mipmaps
set_wrote = 1
for face in getFaces(data):
for iuvlayer,uvlayer in enumerate(uv_textures):
if iuvlayer < 8:
if not (iuvlayer < len(uv_textures)):
continue
# FIXME?
#data.activeUVLayer = uvlayer
#if DEBUG: print("<uv face=", face.index, ">")
img = getUVTextures(data)[iuvlayer].data[face.index].image
if img and b3d_parameters.get("export-textures"):
if img.filepath in trimmed_paths:
img_name = trimmed_paths[img.filepath]
else:
img_name = bpy.path.basename(img.filepath)
trimmed_paths[img.filepath] = img_name
if not img_name in texs_stack:
texs_stack[img_name] = [len(texs_stack), texture_flags[obj_count][iuvlayer]]
temp_buf += write_string(img_name) #Texture File Name
temp_buf += write_int(texture_flags[obj_count][iuvlayer]) #Flags
temp_buf += write_int(2) #Blend
temp_buf += write_float(0) #X_Pos
temp_buf += write_float(0) #Y_Pos
temp_buf += write_float(1) #X_Scale
temp_buf += write_float(1) #Y_Scale
temp_buf += write_float(0) #Rotation
#else:
# if DEBUG: print(" <image id=(previous)","name=","'"+img_name+"'","/>")
#if DEBUG: print("</uv>")
obj_count += 1
#FIXME?
#if orig_uvlayer:
# data.activeUVLayer = orig_uvlayer
texture_count = layer_max
if len(temp_buf) > 0:
texs_buf += write_chunk(b"TEXS",temp_buf)
temp_buf = ""
return texs_buf
# ==== Write BRUS Chunk ====
def write_brus(objects=[]):
global b3d_parameters
global trimmed_paths
global texture_count
brus_buf = bytearray()
temp_buf = bytearray()
mat_count = 0
obj_count = 0
if DEBUG: print("<!-- BRUS chunk -->")
if objects:
exp_obj = objects
else:
if b3d_parameters.get("export-selected"):
exp_obj = [ob for ob in bpy.data.objects if ob.select]
else:
exp_obj = bpy.data.objects
if PROGRESS: print(len(exp_obj),"BRUS")
if PROGRESS_VERBOSE: progress = 0
for obj in exp_obj:
if PROGRESS_VERBOSE:
progress += 1
if (progress % 10 == 0): print("BRUS",progress,"/",len(exp_obj))
if obj.type == "MESH":
data = obj.data
uv_textures = getUVTextures(data)
if len(uv_textures) <= 0:
continue
if DEBUG: print("<obj name=",obj.name,">")
img_found = 0
for face in getFaces(data):
face_stack = []
for iuvlayer,uvlayer in enumerate(uv_textures):
if iuvlayer < 8:
img_id = -1
if face.index >= len(uv_textures[iuvlayer].data):
continue
img = uv_textures[iuvlayer].data[face.index].image
if not img:
continue
img_found = 1
if img.filepath in trimmed_paths:
img_name = trimmed_paths[img.filepath]
else:
img_name = os.path.basename(img.filepath)
trimmed_paths[img.filepath] = img_name
if DEBUG: print(" <!-- Building FACE 'stack' -->")
if img_name in texs_stack:
img_id = texs_stack[img_name][TEXTURE_ID]
face_stack.insert(iuvlayer,img_id)
if DEBUG: print(" <uv face=",face.index,"layer=", iuvlayer, " imgid=", img_id, "/>")
for i in range(len(face_stack),texture_count):
face_stack.append(-1)
if DEBUG: print(" <!-- Writing chunk -->")
if not img_found:
if data.materials:
if data.materials[face.material_index]:
mat_data = data.materials[face.material_index]
mat_colr = mat_data.diffuse_color[0]
mat_colg = mat_data.diffuse_color[1]
mat_colb = mat_data.diffuse_color[2]
mat_alpha = mat_data.alpha
mat_name = mat_data.name
if not mat_name in brus_stack:
brus_stack.append(mat_name)
temp_buf += write_string(mat_name) #Brush Name
temp_buf += write_float(mat_colr) #Red
temp_buf += write_float(mat_colg) #Green
temp_buf += write_float(mat_colb) #Blue
temp_buf += write_float(mat_alpha) #Alpha
temp_buf += write_float(0) #Shininess
temp_buf += write_int(1) #Blend
if b3d_parameters.get("vertex-colors") and len(getVertexColors(data)):
temp_buf += write_int(2) #Fx
else:
temp_buf += write_int(0) #Fx
for i in face_stack:
temp_buf += write_int(i) #Texture ID
else:
if b3d_parameters.get("vertex-colors") and len(getVertexColors(data)) > 0:
if not face_stack in brus_stack:
brus_stack.append(face_stack)
mat_count += 1
temp_buf += write_string("Brush.%.3i"%mat_count) #Brush Name
temp_buf += write_float(1) #Red
temp_buf += write_float(1) #Green
temp_buf += write_float(1) #Blue
temp_buf += write_float(1) #Alpha
temp_buf += write_float(0) #Shininess
temp_buf += write_int(1) #Blend
temp_buf += write_int(2) #Fx
for i in face_stack:
temp_buf += write_int(i) #Texture ID
else: # img_found
if not face_stack in brus_stack:
brus_stack.append(face_stack)
mat_count += 1
temp_buf += write_string("Brush.%.3i"%mat_count) #Brush Name
temp_buf += write_float(1) #Red
temp_buf += write_float(1) #Green
temp_buf += write_float(1) #Blue
temp_buf += write_float(1) #Alpha
temp_buf += write_float(0) #Shininess
temp_buf += write_int(1) #Blend
if DEBUG: print(" <brush id=",len(brus_stack),">")
if b3d_parameters.get("vertex-colors") and len(getVertexColors(data)) > 0:
temp_buf += write_int(2) #Fx
else:
temp_buf += write_int(0) #Fx
for i in face_stack:
temp_buf += write_int(i) #Texture ID
if DEBUG: print(" <texture id=",i,">")
if DEBUG: print(" </brush>")
if DEBUG: print("")
if DEBUG: print("</obj>")
obj_count += 1
#FIXME?
#if orig_uvlayer:
# data.activeUVLayer = orig_uvlayer
if len(temp_buf) > 0:
brus_buf += write_chunk(b"BRUS",write_int(texture_count) + temp_buf) #N Texs
temp_buf = ""
return brus_buf
# ==== Write NODE Chunk ====
def write_node(objects=[]):
global bone_stack
global keys_stack
global b3d_parameters
global the_scene
root_buf = []
node_buf = []
main_buf = bytearray()
temp_buf = []
obj_count = 0
amb_light = 0
num_mesh = 0
num_ligs = 0
num_cams = 0
num_lorc = 0
#exp_scn = Blender.Scene.GetCurrent()
#exp_scn = the_scene
#exp_con = exp_scn.getRenderingContext()
#first_frame = Blender.Draw.Create(exp_con.startFrame())
#last_frame = Blender.Draw.Create(exp_con.endFrame())
#num_frames = last_frame.val - first_frame.val
first_frame = the_scene.frame_start
if DEBUG: print("<node first_frame=", first_frame, ">")
if objects:
exp_obj = objects
else:
if b3d_parameters.get("export-selected"):
exp_obj = [ob for ob in bpy.data.objects if ob.select]
else:
exp_obj = bpy.data.objects
for obj in exp_obj:
if obj.type == "MESH":
num_mesh += 1
if obj.type == "CAMERA":
num_cams += 1
if obj.type == "LAMP":
num_ligs += 1
if b3d_parameters.get("cameras"):
num_lorc += num_cams
if b3d_parameters.get("lights"):
num_lorc += 1
num_lorc += num_ligs
if num_mesh + num_lorc > 1:
exp_root = 1
else:
exp_root = 0
if exp_root:
root_buf.append(write_string("ROOT")) #Node Name
root_buf.append(write_float_triplet(0, 0, 0)) #Position X,Y,Z
root_buf.append(write_float_triplet(1, 1, 1)) #Scale X, Y, Z
root_buf.append(write_float_quad(1, 0, 0, 0)) #Rotation W, X, Y, Z
if PROGRESS: progress = 0
for obj in exp_obj:
if PROGRESS:
progress += 1
print("NODE:",progress,"/",len(exp_obj))
if obj.type == "MESH":
if DEBUG: print(" <mesh name=",obj.name,">")
bone_stack = {}
keys_stack = []
anim_data = None
# check if this object has an armature modifier
for curr_mod in obj.modifiers:
if curr_mod.type == 'ARMATURE':
arm = curr_mod.object
if arm is not None:
anim_data = arm.animation_data
# check if this object has an armature parent (second way to do armature animations in blender)
if anim_data is None:
if obj.parent:
if obj.parent.type == "ARMATURE":
arm = obj.parent
if arm.animation_data:
anim_data = arm.animation_data
if anim_data:
matrix = mathutils.Matrix()
temp_buf.append(write_string(obj.name)) #Node Name
position = matrix.to_translation()
temp_buf.append(write_float_triplet(position[0], position[1], position[2])) #Position X, Y, Z
scale = matrix.to_scale()
temp_buf.append(write_float_triplet(scale[0], scale[2], scale[1])) #Scale X, Y, Z
if DEBUG: print(" <arm name=", obj.name, " loc=", -position[0], position[1], position[2], " scale=", scale[0], scale[1], scale[2], "/>")
quat = matrix.to_quaternion()
quat.normalize()
temp_buf.append(write_float_quad(quat.w, quat.x, quat.z, quat.y))
else:
if b3d_parameters.get("local-space"):
matrix = TRANS_MATRIX.copy()
scale_matrix = mathutils.Matrix()
else:
matrix = obj.matrix_world*TRANS_MATRIX
scale_matrix = obj.matrix_world.copy()
if bpy.app.version[1] >= 62:
# blender 2.62 broke the API : Column-major access was changed to row-major access
tmp = mathutils.Vector([matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1]])
matrix[0][1] = matrix[0][2]
matrix[1][1] = matrix[1][2]
matrix[2][1] = matrix[2][2]
matrix[3][1] = matrix[3][2]
matrix[0][2] = tmp[0]
matrix[1][2] = tmp[1]
matrix[2][2] = tmp[2]
matrix[3][2] = tmp[3]
else:
tmp = mathutils.Vector(matrix[1])
matrix[1] = matrix[2]
matrix[2] = tmp
temp_buf.append(write_string(obj.name)) #Node Name
#print("Matrix : ", matrix)
position = matrix.to_translation()
temp_buf.append(write_float_triplet(position[0], position[2], position[1]))
scale = scale_matrix.to_scale()
temp_buf.append(write_float_triplet(scale[0], scale[2], scale[1]))
quat = matrix.to_quaternion()
quat.normalize()
temp_buf.append(write_float_quad(quat.w, quat.x, quat.z, quat.y))
if DEBUG:
print(" <position>",position[0],position[2],position[1],"</position>")
print(" <scale>",scale[0],scale[1],scale[2],"</scale>")
print(" <rotation>", quat.w, quat.x, quat.y, quat.z, "</rotation>")
if anim_data:
the_scene.frame_set(1,subframe=0.0)
arm_matrix = arm.matrix_world
if b3d_parameters.get("local-space"):
arm_matrix = mathutils.Matrix()
def read_armature(arm_matrix,bone,parent = None):
if (parent and not bone.parent.name == parent.name):
return
matrix = mathutils.Matrix(bone.matrix)
if parent:
#print("==== "+bone.name+" ====")
a = (bone.matrix_local)
#print("A : [%.2f %.2f %.2f %.2f]" % (a[0][0], a[0][1], a[0][2], a[0][3]))
#print(" [%.2f %.2f %.2f %.2f]" % (a[1][0], a[1][1], a[1][2], a[1][3]))
#print(" [%.2f %.2f %.2f %.2f]" % (a[2][0], a[2][1], a[2][2], a[2][3]))
#print(" [%.2f %.2f %.2f %.2f]" % (a[3][0], a[3][1], a[3][2], a[3][3]))
b = (parent.matrix_local.inverted().to_4x4())
#print("B : [%.2f %.2f %.2f %.2f]" % (b[0][0], b[0][1], b[0][2], b[0][3]))
#print(" [%.2f %.2f %.2f %.2f]" % (b[1][0], b[1][1], b[1][2], b[1][3]))
#print(" [%.2f %.2f %.2f %.2f]" % (b[2][0], b[2][1], b[2][2], b[2][3]))
#print(" [%.2f %.2f %.2f %.2f]" % (b[3][0], b[3][1], b[3][2], b[3][3]))
par_matrix = b * a
transform = mathutils.Matrix([[1,0,0,0],[0,0,-1,0],[0,-1,0,0],[0,0,0,1]])
par_matrix = transform*par_matrix*transform
# FIXME: that's ugly, find a clean way to change the matrix.....
if bpy.app.version[1] >= 62:
# blender 2.62 broke the API : Column-major access was changed to row-major access
# TODO: test me
par_matrix[1][3] = -par_matrix[1][3]
par_matrix[2][3] = -par_matrix[2][3]
else:
par_matrix[3][1] = -par_matrix[3][1]
par_matrix[3][2] = -par_matrix[3][2]
#c = par_matrix
#print("With parent")
#print("C : [%.3f %.3f %.3f %.3f]" % (c[0][0], c[0][1], c[0][2], c[0][3]))
#print(" [%.3f %.3f %.3f %.3f]" % (c[1][0], c[1][1], c[1][2], c[1][3]))
#print(" [%.3f %.3f %.3f %.3f]" % (c[2][0], c[2][1], c[2][2], c[2][3]))
#print(" [%.3f %.3f %.3f %.3f]" % (c[3][0], c[3][1], c[3][2], c[3][3]))
else:
#print("==== "+bone.name+" ====")
#print("Without parent")
m = arm_matrix*bone.matrix_local
#c = arm.matrix_world
#print("A : [%.3f %.3f %.3f %.3f]" % (c[0][0], c[0][1], c[0][2], c[0][3]))
#print(" [%.3f %.3f %.3f %.3f]" % (c[1][0], c[1][1], c[1][2], c[1][3]))
#print(" [%.3f %.3f %.3f %.3f]" % (c[2][0], c[2][1], c[2][2], c[2][3]))
#print(" [%.3f %.3f %.3f %.3f]" % (c[3][0], c[3][1], c[3][2], c[3][3]))
#c = bone.matrix_local
#print("B : [%.3f %.3f %.3f %.3f]" % (c[0][0], c[0][1], c[0][2], c[0][3]))
#print(" [%.3f %.3f %.3f %.3f]" % (c[1][0], c[1][1], c[1][2], c[1][3]))
#print(" [%.3f %.3f %.3f %.3f]" % (c[2][0], c[2][1], c[2][2], c[2][3]))
#print(" [%.3f %.3f %.3f %.3f]" % (c[3][0], c[3][1], c[3][2], c[3][3]))
par_matrix = m*mathutils.Matrix([[-1,0,0,0],[0,0,1,0],[0,1,0,0],[0,0,0,1]])
#c = par_matrix
#print("C : [%.3f %.3f %.3f %.3f]" % (c[0][0], c[0][1], c[0][2], c[0][3]))
#print(" [%.3f %.3f %.3f %.3f]" % (c[1][0], c[1][1], c[1][2], c[1][3]))
#print(" [%.3f %.3f %.3f %.3f]" % (c[2][0], c[2][1], c[2][2], c[2][3]))
#print(" [%.3f %.3f %.3f %.3f]" % (c[3][0], c[3][1], c[3][2], c[3][3]))
bone_stack[bone.name] = [par_matrix,parent,bone]
if bone.children:
for child in bone.children: read_armature(arm_matrix,child,bone)
for bone in arm.data.bones.values():
if not bone.parent:
read_armature(arm_matrix,bone)
frame_count = first_frame
last_frame = int(getArmatureAnimationEnd(arm))
num_frames = last_frame - first_frame
while frame_count <= last_frame:
the_scene.frame_set(int(frame_count), subframe=0.0)
if DEBUG: print(" <frame id=", int(frame_count), ">")
arm_pose = arm.pose
arm_matrix = arm.matrix_world
transform = mathutils.Matrix([[-1,0,0,0],[0,0,1,0],[0,1,0,0],[0,0,0,1]])
arm_matrix = transform*arm_matrix
for bone_name in arm.data.bones.keys():
#bone_matrix = mathutils.Matrix(arm_pose.bones[bone_name].poseMatrix)
bone_matrix = mathutils.Matrix(arm_pose.bones[bone_name].matrix)
#print("(outer loop) bone_matrix for",bone_name,"=", bone_matrix)
#print(bone_name,":",bone_matrix)
#bone_matrix = bpy.data.scenes[0].objects[0].pose.bones['Bone'].matrix
for ibone in bone_stack:
bone = bone_stack[ibone]
if bone[BONE_ITSELF].name == bone_name:
if DEBUG: print(" <bone id=",ibone,"name=",bone_name,">")
# == 2.4 exporter ==
#if bone_stack[ibone][1]:
# par_matrix = Blender.Mathutils.Matrix(arm_pose.bones[bone_stack[ibone][1].name].poseMatrix)
# bone_matrix *= par_matrix.invert()
#else:
# if b3d_parameters.get("local-space"):
# bone_matrix *= TRANS_MATRIX
# else:
# bone_matrix *= arm_matrix
#bone_loc = bone_matrix.translationPart()
#bone_rot = bone_matrix.rotationPart().toQuat()
#bone_rot.normalize()
#bone_sca = bone_matrix.scalePart()
#keys_stack.append([frame_count - first_frame.val+1,bone_name,bone_loc,bone_sca,bone_rot])
# if has parent
if bone[BONE_PARENT]:
par_matrix = mathutils.Matrix(arm_pose.bones[bone[BONE_PARENT].name].matrix)
bone_matrix = par_matrix.inverted()*bone_matrix
else:
if b3d_parameters.get("local-space"):
bone_matrix = bone_matrix*mathutils.Matrix([[-1,0,0,0],[0,0,1,0],[0,1,0,0],[0,0,0,1]])
else:
#if frame_count == 1:
# print("====",bone_name,"====")
# print("arm_matrix = ", arm_matrix)
# print("bone_matrix = ", bone_matrix)
bone_matrix = arm_matrix*bone_matrix
#if frame_count == 1:
# print("arm_matrix*bone_matrix", bone_matrix)
#print("bone_matrix =", bone_matrix)
bone_sca = bone_matrix.to_scale()
bone_loc = bone_matrix.to_translation()
# FIXME: silly tweaks to resemble the Blender 2.4 exporter output
if b3d_parameters.get("local-space"):
bone_rot = bone_matrix.to_quaternion()
bone_rot.normalize()
if not bone[BONE_PARENT]:
tmp = bone_rot.z
bone_rot.z = bone_rot.y
bone_rot.y = tmp
bone_rot.x = -bone_rot.x
else:
tmp = bone_loc.z
bone_loc.z = bone_loc.y
bone_loc.y = tmp
else:
bone_rot = bone_matrix.to_quaternion()
bone_rot.normalize()
keys_stack.append([frame_count - first_frame+1, bone_name, bone_loc, bone_sca, bone_rot])
if DEBUG: print(" <loc>", bone_loc, "</loc>")
if DEBUG: print(" <rot>", bone_rot, "</rot>")
if DEBUG: print(" <scale>", bone_sca, "</scale>")
if DEBUG: print(" </bone>")
frame_count += 1
if DEBUG: print(" </frame>")
#Blender.Set("curframe",0)
#Blender.Window.Redraw()
temp_buf.append(write_node_mesh(obj,obj_count,anim_data,exp_root)) #NODE MESH
if anim_data:
temp_buf.append(write_node_anim(num_frames)) #NODE ANIM
for ibone in bone_stack:
if not bone_stack[ibone][BONE_PARENT]:
temp_buf.append(write_node_node(ibone)) #NODE NODE
obj_count += 1
if len(temp_buf) > 0:
node_buf.append(write_chunk(b"NODE",b"".join(temp_buf)))
temp_buf = []
if DEBUG: print(" </mesh>")
if b3d_parameters.get("cameras"):
if obj.type == "CAMERA":
data = obj.data
matrix = obj.getMatrix("worldspace")
matrix *= TRANS_MATRIX
if data.type == "ORTHO":
cam_type = 2
cam_zoom = round(data.scale,4)
else:
cam_type = 1
cam_zoom = round(data.lens,4)
cam_near = round(data.clipStart,4)
cam_far = round(data.clipEnd,4)
node_name = ("CAMS"+"\n%s"%obj.name+"\n%s"%cam_type+\
"\n%s"%cam_zoom+"\n%s"%cam_near+"\n%s"%cam_far)
temp_buf.append(write_string(node_name)) #Node Name
position = matrix.translation_part()
temp_buf.append(write_float_triplet(-position[0], position[1], position[2]))
scale = matrix.scale_part()
temp_buf.append(write_float_triplet(scale[0], scale[1], scale[2]))
matrix *= mathutils.Matrix.Rotation(180,4,'Y')
quat = matrix.to_quat()
quat.normalize()
temp_buf.append(write_float_quad(quat.w, quat.x, quat.y, -quat.z))
if len(temp_buf) > 0:
node_buf.append(write_chunk(b"NODE",b"".join(temp_buf)))
temp_buf = []
if b3d_parameters.get("lights"):
if amb_light == 0:
data = Blender.World.GetCurrent()
amb_light = 1
amb_color = (int(data.amb[2]*255) |(int(data.amb[1]*255) << 8) | (int(data.amb[0]*255) << 16))
node_name = (b"AMBI"+"\n%s"%amb_color)
temp_buf.append(write_string(node_name)) #Node Name
temp_buf.append(write_float_triplet(0, 0, 0)) #Position X, Y, Z
temp_buf.append(write_float_triplet(1, 1, 1)) #Scale X, Y, Z
temp_buf.append(write_float_quad(1, 0, 0, 0)) #Rotation W, X, Y, Z
if len(temp_buf) > 0:
node_buf.append(write_chunk(b"NODE",b"".join(temp_buf)))
temp_buf = []
if obj.type == "LAMP":
data = obj.getData()
matrix = obj.getMatrix("worldspace")
matrix *= TRANS_MATRIX
if data.type == 0:
lig_type = 2
elif data.type == 2:
lig_type = 3
else:
lig_type = 1
lig_angle = round(data.spotSize,4)
lig_color = (int(data.b*255) |(int(data.g*255) << 8) | (int(data.r*255) << 16))
lig_range = round(data.dist,4)
node_name = ("LIGS"+"\n%s"%obj.name+"\n%s"%lig_type+\
"\n%s"%lig_angle+"\n%s"%lig_color+"\n%s"%lig_range)
temp_buf.append(write_string(node_name)) #Node Name
position = matrix.translation_part()
temp_buf.append(write_float_triplet(-position[0], position[1], position[2]))
if DEBUG: print(" <position>",-position[0],position[1],position[2],"</position>")
scale = matrix.scale_part()
temp_buf.append(write_float_triplet(scale[0], scale[1], scale[2]))
if DEBUG: print(" <scale>",scale[0],scale[1],scale[2],"</scale>")
matrix *= mathutils.Matrix.Rotation(180,4,'Y')
quat = matrix.toQuat()
quat.normalize()
temp_buf.append(write_float_quad(quat.w, quat.x, quat.y, -quat.z))
if DEBUG: print(" <rotation>", quat.w, quat.x, quat.y, quat.z, "</rotation>")
if len(temp_buf) > 0:
node_buf.append(write_chunk(b"NODE","b".join(temp_buf)))
temp_buf = []
if len(node_buf) > 0:
if exp_root:
main_buf += write_chunk(b"NODE",b"".join(root_buf) + b"".join(node_buf))
else:
main_buf += b"".join(node_buf)
node_buf = []
root_buf = []
if DEBUG: print("</node>")
return main_buf
# ==== Write NODE MESH Chunk ====
def write_node_mesh(obj,obj_count,arm_action,exp_root):
global vertex_groups
vertex_groups = []
mesh_buf = bytearray()
temp_buf = bytearray()
if arm_action:
data = obj.data
else:
data = obj.to_mesh(the_scene, True, 'PREVIEW')
temp_buf += write_int(-1) #Brush ID
temp_buf += write_node_mesh_vrts(obj, data, obj_count, arm_action, exp_root) #NODE MESH VRTS
temp_buf += write_node_mesh_tris(obj, data, obj_count, arm_action, exp_root) #NODE MESH TRIS