operators were copying the properties from the rna operator into the class instance.
[blender.git] / release / scripts / io / export_fbx.py
1 # ##### BEGIN GPL LICENSE BLOCK #####
2 #
3 #  This program is free software; you can redistribute it and/or
4 #  modify it under the terms of the GNU General Public License
5 #  as published by the Free Software Foundation; either version 2
6 #  of the License, or (at your option) any later version.
7
8 #  This program is distributed in the hope that it will be useful,
9 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
10 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 #  GNU General Public License for more details.
12
13 #  You should have received a copy of the GNU General Public License
14 #  along with this program; if not, write to the Free Software Foundation,
15 #  Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
16 #
17 # ##### END GPL LICENSE BLOCK #####
18
19 __author__ = "Campbell Barton"
20 __url__ = ['www.blender.org', 'blenderartists.org']
21 __version__ = "1.2"
22
23 __bpydoc__ = """\
24 This script is an exporter to the FBX file format.
25
26 http://wiki.blender.org/index.php/Scripts/Manual/Export/autodesk_fbx
27 """
28 # --------------------------------------------------------------------------
29 # FBX Export v0.1 by Campbell Barton (AKA Ideasman)
30 # --------------------------------------------------------------------------
31 # ***** BEGIN GPL LICENSE BLOCK *****
32 #
33 # This program is free software; you can redistribute it and/or
34 # modify it under the terms of the GNU General Public License
35 # as published by the Free Software Foundation; either version 2
36 # of the License, or (at your option) any later version.
37 #
38 # This program is distributed in the hope that it will be useful,
39 # but WITHOUT ANY WARRANTY; without even the implied warranty of
40 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
41 # GNU General Public License for more details.
42 #
43 # You should have received a copy of the GNU General Public License
44 # along with this program; if not, write to the Free Software Foundation,
45 # Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
46 #
47 # ***** END GPL LICENCE BLOCK *****
48 # --------------------------------------------------------------------------
49
50 import os
51 import time
52 import math # math.pi
53 import shutil # for file copying
54
55 # try:
56 #       import time
57 #       # import os # only needed for batch export, nbot used yet
58 # except:
59 #       time = None # use this to check if they have python modules installed
60
61 # for python 2.3 support
62 try:
63         set()
64 except:
65         try:
66                 from sets import Set as set
67         except:
68                 set = None # so it complains you dont have a !
69
70 # # os is only needed for batch 'own dir' option
71 # try:
72 #       import os
73 # except:
74 #       os = None
75
76 # import Blender
77 import bpy
78 import Mathutils
79 # from Blender.Mathutils import Matrix, Vector, RotationMatrix
80
81 # import BPyObject
82 # import BPyMesh
83 # import BPySys
84 # import BPyMessages
85
86 ## This was used to make V, but faster not to do all that
87 ##valid = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_,.()[]{}'
88 ##v = range(255)
89 ##for c in valid: v.remove(ord(c))
90 v = [0,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,42,43,47,58,59,60,61,62,63,64,92,94,96,124,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]
91 invalid = ''.join([chr(i) for i in v])
92 def cleanName(name):
93         for ch in invalid:      name = name.replace(ch, '_')
94         return name
95 # del v, i
96
97
98 def copy_file(source, dest):
99         file = open(source, 'rb')
100         data = file.read()
101         file.close()
102         
103         file = open(dest, 'wb')
104         file.write(data)
105         file.close()
106
107
108 # XXX not used anymore, images are copied one at a time
109 def copy_images(dest_dir, textures):
110         if not dest_dir.endswith(os.sep):
111                 dest_dir += os.sep
112         
113         image_paths = set()
114         for tex in textures:
115                 image_paths.add(Blender.sys.expandpath(tex.filename))
116         
117         # Now copy images
118         copyCount = 0
119         for image_path in image_paths:
120                 if Blender.sys.exists(image_path):
121                         # Make a name for the target path.
122                         dest_image_path = dest_dir + image_path.split('\\')[-1].split('/')[-1]
123                         if not Blender.sys.exists(dest_image_path): # Image isnt alredy there
124                                 print('\tCopying "%s" > "%s"' % (image_path, dest_image_path))
125                                 try:
126                                         copy_file(image_path, dest_image_path)
127                                         copyCount+=1
128                                 except:
129                                         print('\t\tWarning, file failed to copy, skipping.')
130         
131         print('\tCopied %d images' % copyCount)
132
133 # I guess FBX uses degrees instead of radians (Arystan).
134 # Call this function just before writing to FBX.
135 def eulerRadToDeg(eul):
136         ret = Mathutils.Euler()
137
138         ret.x = 180 / math.pi * eul[0]
139         ret.y = 180 / math.pi * eul[1]
140         ret.z = 180 / math.pi * eul[2]
141
142         return ret
143
144 mtx4_identity = Mathutils.Matrix()
145
146 # testing
147 mtx_x90         = Mathutils.RotationMatrix( math.pi/2, 3, 'x') # used
148 #mtx_x90n       = RotationMatrix(-90, 3, 'x')
149 #mtx_y90        = RotationMatrix( 90, 3, 'y')
150 #mtx_y90n       = RotationMatrix(-90, 3, 'y')
151 #mtx_z90        = RotationMatrix( 90, 3, 'z')
152 #mtx_z90n       = RotationMatrix(-90, 3, 'z')
153
154 #mtx4_x90       = RotationMatrix( 90, 4, 'x')
155 mtx4_x90n       = Mathutils.RotationMatrix(-math.pi/2, 4, 'x') # used
156 #mtx4_y90       = RotationMatrix( 90, 4, 'y')
157 mtx4_y90n       = Mathutils.RotationMatrix(-math.pi/2, 4, 'y') # used
158 mtx4_z90        = Mathutils.RotationMatrix( math.pi/2, 4, 'z') # used
159 mtx4_z90n       = Mathutils.RotationMatrix(-math.pi/2, 4, 'z') # used
160
161 # def strip_path(p):
162 #       return p.split('\\')[-1].split('/')[-1]
163
164 # Used to add the scene name into the filename without using odd chars  
165 sane_name_mapping_ob = {}
166 sane_name_mapping_mat = {}
167 sane_name_mapping_tex = {}
168 sane_name_mapping_take = {}
169 sane_name_mapping_group = {}
170
171 # Make sure reserved names are not used
172 sane_name_mapping_ob['Scene'] = 'Scene_'
173 sane_name_mapping_ob['blend_root'] = 'blend_root_'
174
175 def increment_string(t):
176         name = t
177         num = ''
178         while name and name[-1].isdigit():
179                 num = name[-1] + num
180                 name = name[:-1]
181         if num: return '%s%d' % (name, int(num)+1)      
182         else:   return name + '_0'
183
184
185
186 # todo - Disallow the name 'Scene' and 'blend_root' - it will bugger things up.
187 def sane_name(data, dct):
188         #if not data: return None
189         
190         if type(data)==tuple: # materials are paired up with images
191                 data, other = data
192                 use_other = True
193         else:
194                 other = None
195                 use_other = False
196         
197         if data:        name = data.name
198         else:           name = None
199         orig_name = name
200         
201         if other:
202                 orig_name_other = other.name
203                 name = '%s #%s' % (name, orig_name_other)
204         else:
205                 orig_name_other = None
206         
207         # dont cache, only ever call once for each data type now,
208         # so as to avoid namespace collision between types - like with objects <-> bones
209         #try:           return dct[name]
210         #except:                pass
211         
212         if not name:
213                 name = 'unnamed' # blank string, ASKING FOR TROUBLE!
214         else:
215                 #name = BPySys.cleanName(name)
216                 name = cleanName(name) # use our own
217         
218         while name in iter(dct.values()):       name = increment_string(name)
219         
220         if use_other: # even if other is None - orig_name_other will be a string or None
221                 dct[orig_name, orig_name_other] = name
222         else:
223                 dct[orig_name] = name
224                 
225         return name
226
227 def sane_obname(data):          return sane_name(data, sane_name_mapping_ob)
228 def sane_matname(data):         return sane_name(data, sane_name_mapping_mat)
229 def sane_texname(data):         return sane_name(data, sane_name_mapping_tex)
230 def sane_takename(data):        return sane_name(data, sane_name_mapping_take)
231 def sane_groupname(data):       return sane_name(data, sane_name_mapping_group)
232
233 # def derived_paths(fname_orig, basepath, FORCE_CWD=False):
234 #       '''
235 #       fname_orig - blender path, can be relative
236 #       basepath - fname_rel will be relative to this
237 #       FORCE_CWD - dont use the basepath, just add a ./ to the filename.
238 #               use when we know the file will be in the basepath.
239 #       '''
240 #       fname = bpy.utils.expandpath(fname_orig)
241 # #     fname = Blender.sys.expandpath(fname_orig)
242 #       fname_strip = os.path.basename(fname)
243 # #     fname_strip = strip_path(fname)
244 #       if FORCE_CWD:
245 #               fname_rel = '.' + os.sep + fname_strip
246 #       else:
247 #               fname_rel = bpy.utils.relpath(fname, basepath)
248 # #             fname_rel = Blender.sys.relpath(fname, basepath)
249 #       if fname_rel.startswith('//'): fname_rel = '.' + os.sep + fname_rel[2:]
250 #       return fname, fname_strip, fname_rel
251
252
253 def mat4x4str(mat):
254         return '%.15f,%.15f,%.15f,%.15f,%.15f,%.15f,%.15f,%.15f,%.15f,%.15f,%.15f,%.15f,%.15f,%.15f,%.15f,%.15f' % tuple([ f for v in mat for f in v ])
255
256 # XXX not used
257 # duplicated in OBJ exporter
258 def getVertsFromGroup(me, group_index):
259         ret = []
260
261         for i, v in enumerate(me.verts):
262                 for g in v.groups:
263                         if g.group == group_index:
264                                 ret.append((i, g.weight))
265
266                 return ret
267
268 # ob must be OB_MESH
269 def BPyMesh_meshWeight2List(ob):
270         ''' Takes a mesh and return its group names and a list of lists, one list per vertex.
271         aligning the each vert list with the group names, each list contains float value for the weight.
272         These 2 lists can be modified and then used with list2MeshWeight to apply the changes.
273         '''
274
275         me = ob.data
276
277         # Clear the vert group.
278         groupNames= [g.name for g in ob.vertex_groups]
279         len_groupNames= len(groupNames)
280         
281         if not len_groupNames:
282                 # no verts? return a vert aligned empty list
283                 return [[] for i in range(len(me.verts))], []
284         else:
285                 vWeightList= [[0.0]*len_groupNames for i in range(len(me.verts))]
286
287         for i, v in enumerate(me.verts):
288                 for g in v.groups:
289                         vWeightList[i][g.group] = g.weight
290
291         return groupNames, vWeightList
292
293 def meshNormalizedWeights(me):
294         try: # account for old bad BPyMesh
295                 groupNames, vWeightList = BPyMesh_meshWeight2List(me)
296 #               groupNames, vWeightList = BPyMesh.meshWeight2List(me)
297         except:
298                 return [],[]
299         
300         if not groupNames:
301                 return [],[]
302         
303         for i, vWeights in enumerate(vWeightList):
304                 tot = 0.0
305                 for w in vWeights:
306                         tot+=w
307                 
308                 if tot:
309                         for j, w in enumerate(vWeights):
310                                 vWeights[j] = w/tot
311         
312         return groupNames, vWeightList
313
314 header_comment = \
315 '''; FBX 6.1.0 project file
316 ; Created by Blender FBX Exporter
317 ; for support mail: ideasman42@gmail.com
318 ; ----------------------------------------------------
319
320 '''
321
322 # This func can be called with just the filename
323 def write(filename, batch_objects = None, \
324                 context = None,
325                 EXP_OBS_SELECTED =                      True,
326                 EXP_MESH =                                      True,
327                 EXP_MESH_APPLY_MOD =            True,
328 #               EXP_MESH_HQ_NORMALS =           False,
329                 EXP_ARMATURE =                          True,
330                 EXP_LAMP =                                      True,
331                 EXP_CAMERA =                            True,
332                 EXP_EMPTY =                                     True,
333                 EXP_IMAGE_COPY =                        False,
334                 GLOBAL_MATRIX =                         Mathutils.Matrix(),
335                 ANIM_ENABLE =                           True,
336                 ANIM_OPTIMIZE =                         True,
337                 ANIM_OPTIMIZE_PRECISSION =      6,
338                 ANIM_ACTION_ALL =                       False,
339                 BATCH_ENABLE =                          False,
340                 BATCH_GROUP =                           True,
341                 BATCH_FILE_PREFIX =                     '',
342                 BATCH_OWN_DIR =                         False
343         ):
344         
345         # ----------------- Batch support!
346         if BATCH_ENABLE:
347                 if os == None:  BATCH_OWN_DIR = False
348                 
349                 fbxpath = filename
350                 
351                 # get the path component of filename
352                 tmp_exists = bpy.utils.exists(fbxpath)
353 #               tmp_exists = Blender.sys.exists(fbxpath)
354                 
355                 if tmp_exists != 2: # a file, we want a path
356                         fbxpath = os.path.dirname(fbxpath)
357 #                       while fbxpath and fbxpath[-1] not in ('/', '\\'):
358 #                               fbxpath = fbxpath[:-1]
359                         if not fbxpath:
360 #                       if not filename:
361                                 # XXX
362                                 print('Error%t|Directory does not exist!')
363 #                               Draw.PupMenu('Error%t|Directory does not exist!')
364                                 return
365
366                         tmp_exists = bpy.utils.exists(fbxpath)
367 #                       tmp_exists = Blender.sys.exists(fbxpath)
368                 
369                 if tmp_exists != 2:
370                         # XXX
371                         print('Error%t|Directory does not exist!')
372 #                       Draw.PupMenu('Error%t|Directory does not exist!')
373                         return
374                 
375                 if not fbxpath.endswith(os.sep):
376                         fbxpath += os.sep
377                 del tmp_exists
378                 
379                 
380                 if BATCH_GROUP:
381                         data_seq = bpy.data.groups
382                 else:
383                         data_seq = bpy.data.scenes
384                 
385                 # call this function within a loop with BATCH_ENABLE == False
386                 orig_sce = context.scene
387 #               orig_sce = bpy.data.scenes.active
388                 
389                 
390                 new_fbxpath = fbxpath # own dir option modifies, we need to keep an original
391                 for data in data_seq: # scene or group
392                         newname = BATCH_FILE_PREFIX + cleanName(data.name)
393 #                       newname = BATCH_FILE_PREFIX + BPySys.cleanName(data.name)
394                         
395                         
396                         if BATCH_OWN_DIR:
397                                 new_fbxpath = fbxpath + newname + os.sep
398                                 # path may alredy exist
399                                 # TODO - might exist but be a file. unlikely but should probably account for it.
400
401                                 if bpy.utils.exists(new_fbxpath) == 0:
402 #                               if Blender.sys.exists(new_fbxpath) == 0:
403                                         os.mkdir(new_fbxpath)
404                                 
405                         
406                         filename = new_fbxpath + newname + '.fbx'
407                         
408                         print('\nBatch exporting %s as...\n\t"%s"' % (data, filename))
409
410                         # XXX don't know what to do with this, probably do the same? (Arystan)
411                         if BATCH_GROUP: #group
412                                 # group, so objects update properly, add a dummy scene.
413                                 sce = bpy.data.scenes.new()
414                                 sce.Layers = (1<<20) -1
415                                 bpy.data.scenes.active = sce
416                                 for ob_base in data.objects:
417                                         sce.objects.link(ob_base)
418                                 
419                                 sce.update(1)
420                                 
421                                 # TODO - BUMMER! Armatures not in the group wont animate the mesh
422                                 
423                         else:# scene
424                                 
425                                 
426                                 data_seq.active = data
427                         
428                         
429                         # Call self with modified args
430                         # Dont pass batch options since we alredy usedt them
431                         write(filename, data.objects,
432                                 context,
433                                 False,
434                                 EXP_MESH,
435                                 EXP_MESH_APPLY_MOD,
436 #                               EXP_MESH_HQ_NORMALS,
437                                 EXP_ARMATURE,
438                                 EXP_LAMP,
439                                 EXP_CAMERA,
440                                 EXP_EMPTY,
441                                 EXP_IMAGE_COPY,
442                                 GLOBAL_MATRIX,
443                                 ANIM_ENABLE,
444                                 ANIM_OPTIMIZE,
445                                 ANIM_OPTIMIZE_PRECISSION,
446                                 ANIM_ACTION_ALL
447                         )
448                         
449                         if BATCH_GROUP:
450                                 # remove temp group scene
451                                 bpy.data.remove_scene(sce)
452 #                               bpy.data.scenes.unlink(sce)
453                 
454                 bpy.data.scenes.active = orig_sce
455                 
456                 return # so the script wont run after we have batch exported.
457         
458         # end batch support
459         
460         # Use this for working out paths relative to the export location
461         basepath = os.path.dirname(filename) or '.'
462         basepath += os.sep
463 #       basepath = Blender.sys.dirname(filename)
464         
465         # ----------------------------------------------
466         # storage classes
467         class my_bone_class:
468                 __slots__ =(\
469                   'blenName',\
470                   'blenBone',\
471                   'blenMeshes',\
472                   'restMatrix',\
473                   'parent',\
474                   'blenName',\
475                   'fbxName',\
476                   'fbxArm',\
477                   '__pose_bone',\
478                   '__anim_poselist')
479                 
480                 def __init__(self, blenBone, fbxArm):
481                         
482                         # This is so 2 armatures dont have naming conflicts since FBX bones use object namespace
483                         self.fbxName = sane_obname(blenBone)
484                         
485                         self.blenName =                 blenBone.name
486                         self.blenBone =                 blenBone
487                         self.blenMeshes =               {}                                      # fbxMeshObName : mesh
488                         self.fbxArm =                   fbxArm
489                         self.restMatrix =               blenBone.armature_matrix
490 #                       self.restMatrix =               blenBone.matrix['ARMATURESPACE']
491                         
492                         # not used yet
493                         # self.restMatrixInv =  self.restMatrix.copy().invert()
494                         # self.restMatrixLocal =        None # set later, need parent matrix
495                         
496                         self.parent =                   None
497                         
498                         # not public
499                         pose = fbxArm.blenObject.pose
500 #                       pose = fbxArm.blenObject.getPose()
501                         self.__pose_bone =              pose.bones[self.blenName]
502                         
503                         # store a list if matricies here, (poseMatrix, head, tail)
504                         # {frame:posematrix, frame:posematrix, ...}
505                         self.__anim_poselist = {}
506                 
507                 '''
508                 def calcRestMatrixLocal(self):
509                         if self.parent:
510                                 self.restMatrixLocal = self.restMatrix * self.parent.restMatrix.copy().invert()
511                         else:
512                                 self.restMatrixLocal = self.restMatrix.copy()
513                 '''
514                 def setPoseFrame(self, f):
515                         # cache pose info here, frame must be set beforehand
516                         
517                         # Didnt end up needing head or tail, if we do - here it is.
518                         '''
519                         self.__anim_poselist[f] = (\
520                                 self.__pose_bone.poseMatrix.copy(),\
521                                 self.__pose_bone.head.copy(),\
522                                 self.__pose_bone.tail.copy() )
523                         '''
524
525                         self.__anim_poselist[f] = self.__pose_bone.pose_matrix.copy()
526 #                       self.__anim_poselist[f] = self.__pose_bone.poseMatrix.copy()
527                 
528                 # get pose from frame.
529                 def getPoseMatrix(self, f):# ----------------------------------------------
530                         return self.__anim_poselist[f]
531                 '''
532                 def getPoseHead(self, f):
533                         #return self.__pose_bone.head.copy()
534                         return self.__anim_poselist[f][1].copy()
535                 def getPoseTail(self, f):
536                         #return self.__pose_bone.tail.copy()
537                         return self.__anim_poselist[f][2].copy()
538                 '''
539                 # end
540                 
541                 def getAnimParRelMatrix(self, frame):
542                         #arm_mat = self.fbxArm.matrixWorld
543                         #arm_mat = self.fbxArm.parRelMatrix()
544                         if not self.parent:
545                                 #return mtx4_z90 * (self.getPoseMatrix(frame) * arm_mat) # dont apply arm matrix anymore
546                                 return mtx4_z90 * self.getPoseMatrix(frame)
547                         else:
548                                 #return (mtx4_z90 * ((self.getPoseMatrix(frame) * arm_mat)))  *  (mtx4_z90 * (self.parent.getPoseMatrix(frame) * arm_mat)).invert()
549                                 return (mtx4_z90 * (self.getPoseMatrix(frame)))  *  (mtx4_z90 * self.parent.getPoseMatrix(frame)).invert()
550                 
551                 # we need thes because cameras and lights modified rotations
552                 def getAnimParRelMatrixRot(self, frame):
553                         return self.getAnimParRelMatrix(frame)
554                 
555                 def flushAnimData(self):
556                         self.__anim_poselist.clear()
557
558
559         class my_object_generic:
560                 # Other settings can be applied for each type - mesh, armature etc.
561                 def __init__(self, ob, matrixWorld = None):
562                         self.fbxName = sane_obname(ob)
563                         self.blenObject = ob
564                         self.fbxGroupNames = []
565                         self.fbxParent = None # set later on IF the parent is in the selection.
566                         if matrixWorld:         self.matrixWorld = matrixWorld * GLOBAL_MATRIX
567                         else:                           self.matrixWorld = ob.matrix * GLOBAL_MATRIX
568 #                       else:                           self.matrixWorld = ob.matrixWorld * GLOBAL_MATRIX
569                         self.__anim_poselist = {} # we should only access this
570                 
571                 def parRelMatrix(self):
572                         if self.fbxParent:
573                                 return self.matrixWorld * self.fbxParent.matrixWorld.copy().invert()
574                         else:
575                                 return self.matrixWorld
576                 
577                 def setPoseFrame(self, f):
578                         self.__anim_poselist[f] =  self.blenObject.matrix.copy()
579 #                       self.__anim_poselist[f] =  self.blenObject.matrixWorld.copy()
580                 
581                 def getAnimParRelMatrix(self, frame):
582                         if self.fbxParent:
583                                 #return (self.__anim_poselist[frame] * self.fbxParent.__anim_poselist[frame].copy().invert() ) * GLOBAL_MATRIX
584                                 return (self.__anim_poselist[frame] * GLOBAL_MATRIX) * (self.fbxParent.__anim_poselist[frame] * GLOBAL_MATRIX).invert()
585                         else:
586                                 return self.__anim_poselist[frame] * GLOBAL_MATRIX
587                 
588                 def getAnimParRelMatrixRot(self, frame):
589                         type = self.blenObject.type
590                         if self.fbxParent:
591                                 matrix_rot = (((self.__anim_poselist[frame] * GLOBAL_MATRIX) * (self.fbxParent.__anim_poselist[frame] * GLOBAL_MATRIX).invert())).rotationPart()
592                         else:
593                                 matrix_rot = (self.__anim_poselist[frame] * GLOBAL_MATRIX).rotationPart()
594                         
595                         # Lamps need to be rotated
596                         if type =='LAMP':
597                                 matrix_rot = mtx_x90 * matrix_rot
598                         elif type =='CAMERA':
599 #                       elif ob and type =='Camera':
600                                 y = Mathutils.Vector(0,1,0) * matrix_rot
601                                 matrix_rot = matrix_rot * Mathutils.RotationMatrix(math.pi/2, 3, 'r', y)
602                         
603                         return matrix_rot
604                         
605         # ----------------------------------------------
606         
607         
608         
609         
610         
611         print('\nFBX export starting...', filename)
612         start_time = time.clock()
613 #       start_time = Blender.sys.time()
614         try:
615                 file = open(filename, 'w')
616         except:
617                 return False
618
619         sce = context.scene
620 #       sce = bpy.data.scenes.active
621         world = sce.world
622         
623         
624         # ---------------------------- Write the header first
625         file.write(header_comment)
626         if time:
627                 curtime = time.localtime()[0:6]
628         else:
629                 curtime = (0,0,0,0,0,0)
630         # 
631         file.write(\
632 '''FBXHeaderExtension:  {
633         FBXHeaderVersion: 1003
634         FBXVersion: 6100
635         CreationTimeStamp:  {
636                 Version: 1000
637                 Year: %.4i
638                 Month: %.2i
639                 Day: %.2i
640                 Hour: %.2i
641                 Minute: %.2i
642                 Second: %.2i
643                 Millisecond: 0
644         }
645         Creator: "FBX SDK/FBX Plugins build 20070228"
646         OtherFlags:  {
647                 FlagPLE: 0
648         }
649 }''' % (curtime))
650         
651         file.write('\nCreationTime: "%.4i-%.2i-%.2i %.2i:%.2i:%.2i:000"' % curtime)
652         file.write('\nCreator: "Blender3D version 2.5"')
653 #       file.write('\nCreator: "Blender3D version %.2f"' % Blender.Get('version'))
654         
655         pose_items = [] # list of (fbxName, matrix) to write pose data for, easier to collect allong the way
656         
657         # --------------- funcs for exporting
658         def object_tx(ob, loc, matrix, matrix_mod = None):
659                 '''
660                 Matrix mod is so armature objects can modify their bone matricies
661                 '''
662                 if isinstance(ob, bpy.types.Bone):
663 #               if isinstance(ob, Blender.Types.BoneType):
664                         
665                         # we know we have a matrix
666                         # matrix = mtx4_z90 * (ob.matrix['ARMATURESPACE'] * matrix_mod)
667                         matrix = mtx4_z90 * ob.armature_matrix # dont apply armature matrix anymore
668 #                       matrix = mtx4_z90 * ob.matrix['ARMATURESPACE'] # dont apply armature matrix anymore
669                         
670                         parent = ob.parent
671                         if parent:
672                                 #par_matrix = mtx4_z90 * (parent.matrix['ARMATURESPACE'] * matrix_mod)
673                                 par_matrix = mtx4_z90 * parent.armature_matrix # dont apply armature matrix anymore
674 #                               par_matrix = mtx4_z90 * parent.matrix['ARMATURESPACE'] # dont apply armature matrix anymore
675                                 matrix = matrix * par_matrix.copy().invert()
676                                 
677                         matrix_rot =    matrix.rotationPart()
678                         
679                         loc =                   tuple(matrix.translationPart())
680                         scale =                 tuple(matrix.scalePart())
681                         rot =                   tuple(matrix_rot.toEuler())
682                         
683                 else:
684                         # This is bad because we need the parent relative matrix from the fbx parent (if we have one), dont use anymore
685                         #if ob and not matrix: matrix = ob.matrixWorld * GLOBAL_MATRIX
686                         if ob and not matrix: raise Exception("error: this should never happen!")
687                         
688                         matrix_rot = matrix
689                         #if matrix:
690                         #       matrix = matrix_scale * matrix
691                         
692                         if matrix:
693                                 loc = tuple(matrix.translationPart())
694                                 scale = tuple(matrix.scalePart())
695                                 
696                                 matrix_rot = matrix.rotationPart()
697                                 # Lamps need to be rotated
698                                 if ob and ob.type =='Lamp':
699                                         matrix_rot = mtx_x90 * matrix_rot
700                                         rot = tuple(matrix_rot.toEuler())
701                                 elif ob and ob.type =='Camera':
702                                         y = Mathutils.Vector(0,1,0) * matrix_rot
703                                         matrix_rot = matrix_rot * Mathutils.RotationMatrix(math.pi/2, 3, 'r', y)
704                                         rot = tuple(matrix_rot.toEuler())
705                                 else:
706                                         rot = tuple(matrix_rot.toEuler())
707                         else:
708                                 if not loc:
709                                         loc = 0,0,0
710                                 scale = 1,1,1
711                                 rot = 0,0,0
712                 
713                 return loc, rot, scale, matrix, matrix_rot
714         
715         def write_object_tx(ob, loc, matrix, matrix_mod= None):
716                 '''
717                 We have loc to set the location if non blender objects that have a location
718                 
719                 matrix_mod is only used for bones at the moment
720                 '''
721                 loc, rot, scale, matrix, matrix_rot = object_tx(ob, loc, matrix, matrix_mod)
722                 
723                 file.write('\n\t\t\tProperty: "Lcl Translation", "Lcl Translation", "A+",%.15f,%.15f,%.15f' % loc)
724                 file.write('\n\t\t\tProperty: "Lcl Rotation", "Lcl Rotation", "A+",%.15f,%.15f,%.15f' % tuple(eulerRadToDeg(rot)))
725 #               file.write('\n\t\t\tProperty: "Lcl Rotation", "Lcl Rotation", "A+",%.15f,%.15f,%.15f' % rot)
726                 file.write('\n\t\t\tProperty: "Lcl Scaling", "Lcl Scaling", "A+",%.15f,%.15f,%.15f' % scale)
727                 return loc, rot, scale, matrix, matrix_rot
728         
729         def write_object_props(ob=None, loc=None, matrix=None, matrix_mod=None):
730                 # if the type is 0 its an empty otherwise its a mesh
731                 # only difference at the moment is one has a color
732                 file.write('''
733                 Properties60:  {
734                         Property: "QuaternionInterpolate", "bool", "",0
735                         Property: "Visibility", "Visibility", "A+",1''')
736                 
737                 loc, rot, scale, matrix, matrix_rot = write_object_tx(ob, loc, matrix, matrix_mod)
738                 
739                 # Rotation order, note, for FBX files Iv loaded normal order is 1
740                 # setting to zero.
741                 # eEULER_XYZ = 0
742                 # eEULER_XZY
743                 # eEULER_YZX
744                 # eEULER_YXZ
745                 # eEULER_ZXY
746                 # eEULER_ZYX
747                 
748                 file.write('''
749                         Property: "RotationOffset", "Vector3D", "",0,0,0
750                         Property: "RotationPivot", "Vector3D", "",0,0,0
751                         Property: "ScalingOffset", "Vector3D", "",0,0,0
752                         Property: "ScalingPivot", "Vector3D", "",0,0,0
753                         Property: "TranslationActive", "bool", "",0
754                         Property: "TranslationMin", "Vector3D", "",0,0,0
755                         Property: "TranslationMax", "Vector3D", "",0,0,0
756                         Property: "TranslationMinX", "bool", "",0
757                         Property: "TranslationMinY", "bool", "",0
758                         Property: "TranslationMinZ", "bool", "",0
759                         Property: "TranslationMaxX", "bool", "",0
760                         Property: "TranslationMaxY", "bool", "",0
761                         Property: "TranslationMaxZ", "bool", "",0
762                         Property: "RotationOrder", "enum", "",0
763                         Property: "RotationSpaceForLimitOnly", "bool", "",0
764                         Property: "AxisLen", "double", "",10
765                         Property: "PreRotation", "Vector3D", "",0,0,0
766                         Property: "PostRotation", "Vector3D", "",0,0,0
767                         Property: "RotationActive", "bool", "",0
768                         Property: "RotationMin", "Vector3D", "",0,0,0
769                         Property: "RotationMax", "Vector3D", "",0,0,0
770                         Property: "RotationMinX", "bool", "",0
771                         Property: "RotationMinY", "bool", "",0
772                         Property: "RotationMinZ", "bool", "",0
773                         Property: "RotationMaxX", "bool", "",0
774                         Property: "RotationMaxY", "bool", "",0
775                         Property: "RotationMaxZ", "bool", "",0
776                         Property: "RotationStiffnessX", "double", "",0
777                         Property: "RotationStiffnessY", "double", "",0
778                         Property: "RotationStiffnessZ", "double", "",0
779                         Property: "MinDampRangeX", "double", "",0
780                         Property: "MinDampRangeY", "double", "",0
781                         Property: "MinDampRangeZ", "double", "",0
782                         Property: "MaxDampRangeX", "double", "",0
783                         Property: "MaxDampRangeY", "double", "",0
784                         Property: "MaxDampRangeZ", "double", "",0
785                         Property: "MinDampStrengthX", "double", "",0
786                         Property: "MinDampStrengthY", "double", "",0
787                         Property: "MinDampStrengthZ", "double", "",0
788                         Property: "MaxDampStrengthX", "double", "",0
789                         Property: "MaxDampStrengthY", "double", "",0
790                         Property: "MaxDampStrengthZ", "double", "",0
791                         Property: "PreferedAngleX", "double", "",0
792                         Property: "PreferedAngleY", "double", "",0
793                         Property: "PreferedAngleZ", "double", "",0
794                         Property: "InheritType", "enum", "",0
795                         Property: "ScalingActive", "bool", "",0
796                         Property: "ScalingMin", "Vector3D", "",1,1,1
797                         Property: "ScalingMax", "Vector3D", "",1,1,1
798                         Property: "ScalingMinX", "bool", "",0
799                         Property: "ScalingMinY", "bool", "",0
800                         Property: "ScalingMinZ", "bool", "",0
801                         Property: "ScalingMaxX", "bool", "",0
802                         Property: "ScalingMaxY", "bool", "",0
803                         Property: "ScalingMaxZ", "bool", "",0
804                         Property: "GeometricTranslation", "Vector3D", "",0,0,0
805                         Property: "GeometricRotation", "Vector3D", "",0,0,0
806                         Property: "GeometricScaling", "Vector3D", "",1,1,1
807                         Property: "LookAtProperty", "object", ""
808                         Property: "UpVectorProperty", "object", ""
809                         Property: "Show", "bool", "",1
810                         Property: "NegativePercentShapeSupport", "bool", "",1
811                         Property: "DefaultAttributeIndex", "int", "",0''')
812                 if ob and not isinstance(ob, bpy.types.Bone):
813 #               if ob and type(ob) != Blender.Types.BoneType:
814                         # Only mesh objects have color 
815                         file.write('\n\t\t\tProperty: "Color", "Color", "A",0.8,0.8,0.8')
816                         file.write('\n\t\t\tProperty: "Size", "double", "",100')
817                         file.write('\n\t\t\tProperty: "Look", "enum", "",1')
818                 
819                 return loc, rot, scale, matrix, matrix_rot
820         
821         
822         # -------------------------------------------- Armatures
823         #def write_bone(bone, name, matrix_mod):
824         def write_bone(my_bone):
825                 file.write('\n\tModel: "Model::%s", "Limb" {' % my_bone.fbxName)
826                 file.write('\n\t\tVersion: 232')
827                 
828                 #poseMatrix = write_object_props(my_bone.blenBone, None, None, my_bone.fbxArm.parRelMatrix())[3]
829                 poseMatrix = write_object_props(my_bone.blenBone)[3] # dont apply bone matricies anymore
830                 pose_items.append( (my_bone.fbxName, poseMatrix) )
831                 
832                 
833                 # file.write('\n\t\t\tProperty: "Size", "double", "",%.6f' % ((my_bone.blenData.head['ARMATURESPACE'] - my_bone.blenData.tail['ARMATURESPACE']) * my_bone.fbxArm.parRelMatrix()).length)
834                 file.write('\n\t\t\tProperty: "Size", "double", "",1')
835                 
836                 #((my_bone.blenData.head['ARMATURESPACE'] * my_bone.fbxArm.matrixWorld) - (my_bone.blenData.tail['ARMATURESPACE'] * my_bone.fbxArm.parRelMatrix())).length)
837                 
838                 """
839                 file.write('\n\t\t\tProperty: "LimbLength", "double", "",%.6f' %\
840                         ((my_bone.blenBone.head['ARMATURESPACE'] - my_bone.blenBone.tail['ARMATURESPACE']) * my_bone.fbxArm.parRelMatrix()).length)
841                 """
842                 
843                 file.write('\n\t\t\tProperty: "LimbLength", "double", "",%.6f' %
844                                    (my_bone.blenBone.armature_head - my_bone.blenBone.armature_tail).length)
845 #                       (my_bone.blenBone.head['ARMATURESPACE'] - my_bone.blenBone.tail['ARMATURESPACE']).length)
846                 
847                 #file.write('\n\t\t\tProperty: "LimbLength", "double", "",1')
848                 file.write('\n\t\t\tProperty: "Color", "ColorRGB", "",0.8,0.8,0.8')
849                 file.write('\n\t\t\tProperty: "Color", "Color", "A",0.8,0.8,0.8')
850                 file.write('\n\t\t}')
851                 file.write('\n\t\tMultiLayer: 0')
852                 file.write('\n\t\tMultiTake: 1')
853                 file.write('\n\t\tShading: Y')
854                 file.write('\n\t\tCulling: "CullingOff"')
855                 file.write('\n\t\tTypeFlags: "Skeleton"')
856                 file.write('\n\t}')
857         
858         def write_camera_switch():
859                 file.write('''
860         Model: "Model::Camera Switcher", "CameraSwitcher" {
861                 Version: 232''')
862                 
863                 write_object_props()
864                 file.write('''
865                         Property: "Color", "Color", "A",0.8,0.8,0.8
866                         Property: "Camera Index", "Integer", "A+",100
867                 }
868                 MultiLayer: 0
869                 MultiTake: 1
870                 Hidden: "True"
871                 Shading: W
872                 Culling: "CullingOff"
873                 Version: 101
874                 Name: "Model::Camera Switcher"
875                 CameraId: 0
876                 CameraName: 100
877                 CameraIndexName: 
878         }''')
879         
880         def write_camera_dummy(name, loc, near, far, proj_type, up):
881                 file.write('\n\tModel: "Model::%s", "Camera" {' % name )
882                 file.write('\n\t\tVersion: 232')
883                 write_object_props(None, loc)
884                 
885                 file.write('\n\t\t\tProperty: "Color", "Color", "A",0.8,0.8,0.8')
886                 file.write('\n\t\t\tProperty: "Roll", "Roll", "A+",0')
887                 file.write('\n\t\t\tProperty: "FieldOfView", "FieldOfView", "A+",40')
888                 file.write('\n\t\t\tProperty: "FieldOfViewX", "FieldOfView", "A+",1')
889                 file.write('\n\t\t\tProperty: "FieldOfViewY", "FieldOfView", "A+",1')
890                 file.write('\n\t\t\tProperty: "OpticalCenterX", "Real", "A+",0')
891                 file.write('\n\t\t\tProperty: "OpticalCenterY", "Real", "A+",0')
892                 file.write('\n\t\t\tProperty: "BackgroundColor", "Color", "A+",0.63,0.63,0.63')
893                 file.write('\n\t\t\tProperty: "TurnTable", "Real", "A+",0')
894                 file.write('\n\t\t\tProperty: "DisplayTurnTableIcon", "bool", "",1')
895                 file.write('\n\t\t\tProperty: "Motion Blur Intensity", "Real", "A+",1')
896                 file.write('\n\t\t\tProperty: "UseMotionBlur", "bool", "",0')
897                 file.write('\n\t\t\tProperty: "UseRealTimeMotionBlur", "bool", "",1')
898                 file.write('\n\t\t\tProperty: "ResolutionMode", "enum", "",0')
899                 file.write('\n\t\t\tProperty: "ApertureMode", "enum", "",2')
900                 file.write('\n\t\t\tProperty: "GateFit", "enum", "",0')
901                 file.write('\n\t\t\tProperty: "FocalLength", "Real", "A+",21.3544940948486')
902                 file.write('\n\t\t\tProperty: "CameraFormat", "enum", "",0')
903                 file.write('\n\t\t\tProperty: "AspectW", "double", "",320')
904                 file.write('\n\t\t\tProperty: "AspectH", "double", "",200')
905                 file.write('\n\t\t\tProperty: "PixelAspectRatio", "double", "",1')
906                 file.write('\n\t\t\tProperty: "UseFrameColor", "bool", "",0')
907                 file.write('\n\t\t\tProperty: "FrameColor", "ColorRGB", "",0.3,0.3,0.3')
908                 file.write('\n\t\t\tProperty: "ShowName", "bool", "",1')
909                 file.write('\n\t\t\tProperty: "ShowGrid", "bool", "",1')
910                 file.write('\n\t\t\tProperty: "ShowOpticalCenter", "bool", "",0')
911                 file.write('\n\t\t\tProperty: "ShowAzimut", "bool", "",1')
912                 file.write('\n\t\t\tProperty: "ShowTimeCode", "bool", "",0')
913                 file.write('\n\t\t\tProperty: "NearPlane", "double", "",%.6f' % near)
914                 file.write('\n\t\t\tProperty: "FarPlane", "double", "",%.6f' % far)
915                 file.write('\n\t\t\tProperty: "FilmWidth", "double", "",0.816')
916                 file.write('\n\t\t\tProperty: "FilmHeight", "double", "",0.612')
917                 file.write('\n\t\t\tProperty: "FilmAspectRatio", "double", "",1.33333333333333')
918                 file.write('\n\t\t\tProperty: "FilmSqueezeRatio", "double", "",1')
919                 file.write('\n\t\t\tProperty: "FilmFormatIndex", "enum", "",4')
920                 file.write('\n\t\t\tProperty: "ViewFrustum", "bool", "",1')
921                 file.write('\n\t\t\tProperty: "ViewFrustumNearFarPlane", "bool", "",0')
922                 file.write('\n\t\t\tProperty: "ViewFrustumBackPlaneMode", "enum", "",2')
923                 file.write('\n\t\t\tProperty: "BackPlaneDistance", "double", "",100')
924                 file.write('\n\t\t\tProperty: "BackPlaneDistanceMode", "enum", "",0')
925                 file.write('\n\t\t\tProperty: "ViewCameraToLookAt", "bool", "",1')
926                 file.write('\n\t\t\tProperty: "LockMode", "bool", "",0')
927                 file.write('\n\t\t\tProperty: "LockInterestNavigation", "bool", "",0')
928                 file.write('\n\t\t\tProperty: "FitImage", "bool", "",0')
929                 file.write('\n\t\t\tProperty: "Crop", "bool", "",0')
930                 file.write('\n\t\t\tProperty: "Center", "bool", "",1')
931                 file.write('\n\t\t\tProperty: "KeepRatio", "bool", "",1')
932                 file.write('\n\t\t\tProperty: "BackgroundMode", "enum", "",0')
933                 file.write('\n\t\t\tProperty: "BackgroundAlphaTreshold", "double", "",0.5')
934                 file.write('\n\t\t\tProperty: "ForegroundTransparent", "bool", "",1')
935                 file.write('\n\t\t\tProperty: "DisplaySafeArea", "bool", "",0')
936                 file.write('\n\t\t\tProperty: "SafeAreaDisplayStyle", "enum", "",1')
937                 file.write('\n\t\t\tProperty: "SafeAreaAspectRatio", "double", "",1.33333333333333')
938                 file.write('\n\t\t\tProperty: "Use2DMagnifierZoom", "bool", "",0')
939                 file.write('\n\t\t\tProperty: "2D Magnifier Zoom", "Real", "A+",100')
940                 file.write('\n\t\t\tProperty: "2D Magnifier X", "Real", "A+",50')
941                 file.write('\n\t\t\tProperty: "2D Magnifier Y", "Real", "A+",50')
942                 file.write('\n\t\t\tProperty: "CameraProjectionType", "enum", "",%i' % proj_type)
943                 file.write('\n\t\t\tProperty: "UseRealTimeDOFAndAA", "bool", "",0')
944                 file.write('\n\t\t\tProperty: "UseDepthOfField", "bool", "",0')
945                 file.write('\n\t\t\tProperty: "FocusSource", "enum", "",0')
946                 file.write('\n\t\t\tProperty: "FocusAngle", "double", "",3.5')
947                 file.write('\n\t\t\tProperty: "FocusDistance", "double", "",200')
948                 file.write('\n\t\t\tProperty: "UseAntialiasing", "bool", "",0')
949                 file.write('\n\t\t\tProperty: "AntialiasingIntensity", "double", "",0.77777')
950                 file.write('\n\t\t\tProperty: "UseAccumulationBuffer", "bool", "",0')
951                 file.write('\n\t\t\tProperty: "FrameSamplingCount", "int", "",7')
952                 file.write('\n\t\t}')
953                 file.write('\n\t\tMultiLayer: 0')
954                 file.write('\n\t\tMultiTake: 0')
955                 file.write('\n\t\tHidden: "True"')
956                 file.write('\n\t\tShading: Y')
957                 file.write('\n\t\tCulling: "CullingOff"')
958                 file.write('\n\t\tTypeFlags: "Camera"')
959                 file.write('\n\t\tGeometryVersion: 124')
960                 file.write('\n\t\tPosition: %.6f,%.6f,%.6f' % loc)
961                 file.write('\n\t\tUp: %i,%i,%i' % up)
962                 file.write('\n\t\tLookAt: 0,0,0')
963                 file.write('\n\t\tShowInfoOnMoving: 1')
964                 file.write('\n\t\tShowAudio: 0')
965                 file.write('\n\t\tAudioColor: 0,1,0')
966                 file.write('\n\t\tCameraOrthoZoom: 1')
967                 file.write('\n\t}')
968         
969         def write_camera_default():
970                 # This sucks but to match FBX converter its easier to
971                 # write the cameras though they are not needed.
972                 write_camera_dummy('Producer Perspective',      (0,71.3,287.5), 10, 4000, 0, (0,1,0))
973                 write_camera_dummy('Producer Top',                      (0,4000,0), 1, 30000, 1, (0,0,-1))
974                 write_camera_dummy('Producer Bottom',                   (0,-4000,0), 1, 30000, 1, (0,0,-1))
975                 write_camera_dummy('Producer Front',                    (0,0,4000), 1, 30000, 1, (0,1,0))
976                 write_camera_dummy('Producer Back',                     (0,0,-4000), 1, 30000, 1, (0,1,0))
977                 write_camera_dummy('Producer Right',                    (4000,0,0), 1, 30000, 1, (0,1,0))
978                 write_camera_dummy('Producer Left',                     (-4000,0,0), 1, 30000, 1, (0,1,0))
979         
980         def write_camera(my_cam):
981                 '''
982                 Write a blender camera
983                 '''
984                 render = sce.render_data
985                 width   = render.resolution_x
986                 height  = render.resolution_y
987 #               render = sce.render
988 #               width   = render.sizeX
989 #               height  = render.sizeY
990                 aspect  = float(width)/height
991                 
992                 data = my_cam.blenObject.data
993                 
994                 file.write('\n\tModel: "Model::%s", "Camera" {' % my_cam.fbxName )
995                 file.write('\n\t\tVersion: 232')
996                 loc, rot, scale, matrix, matrix_rot = write_object_props(my_cam.blenObject, None, my_cam.parRelMatrix())
997                 
998                 file.write('\n\t\t\tProperty: "Roll", "Roll", "A+",0')
999                 file.write('\n\t\t\tProperty: "FieldOfView", "FieldOfView", "A+",%.6f' % data.angle)
1000                 file.write('\n\t\t\tProperty: "FieldOfViewX", "FieldOfView", "A+",1')
1001                 file.write('\n\t\t\tProperty: "FieldOfViewY", "FieldOfView", "A+",1')
1002                 file.write('\n\t\t\tProperty: "FocalLength", "Real", "A+",14.0323972702026')
1003                 file.write('\n\t\t\tProperty: "OpticalCenterX", "Real", "A+",%.6f' % data.shift_x) # not sure if this is in the correct units?
1004 #               file.write('\n\t\t\tProperty: "OpticalCenterX", "Real", "A+",%.6f' % data.shiftX) # not sure if this is in the correct units?
1005                 file.write('\n\t\t\tProperty: "OpticalCenterY", "Real", "A+",%.6f' % data.shift_y) # ditto 
1006 #               file.write('\n\t\t\tProperty: "OpticalCenterY", "Real", "A+",%.6f' % data.shiftY) # ditto 
1007                 file.write('\n\t\t\tProperty: "BackgroundColor", "Color", "A+",0,0,0')
1008                 file.write('\n\t\t\tProperty: "TurnTable", "Real", "A+",0')
1009                 file.write('\n\t\t\tProperty: "DisplayTurnTableIcon", "bool", "",1')
1010                 file.write('\n\t\t\tProperty: "Motion Blur Intensity", "Real", "A+",1')
1011                 file.write('\n\t\t\tProperty: "UseMotionBlur", "bool", "",0')
1012                 file.write('\n\t\t\tProperty: "UseRealTimeMotionBlur", "bool", "",1')
1013                 file.write('\n\t\t\tProperty: "ResolutionMode", "enum", "",0')
1014                 file.write('\n\t\t\tProperty: "ApertureMode", "enum", "",2')
1015                 file.write('\n\t\t\tProperty: "GateFit", "enum", "",0')
1016                 file.write('\n\t\t\tProperty: "CameraFormat", "enum", "",0')
1017                 file.write('\n\t\t\tProperty: "AspectW", "double", "",%i' % width)
1018                 file.write('\n\t\t\tProperty: "AspectH", "double", "",%i' % height)
1019                 
1020                 '''Camera aspect ratio modes.
1021                         0 If the ratio mode is eWINDOW_SIZE, both width and height values aren't relevant.
1022                         1 If the ratio mode is eFIXED_RATIO, the height value is set to 1.0 and the width value is relative to the height value.
1023                         2 If the ratio mode is eFIXED_RESOLUTION, both width and height values are in pixels.
1024                         3 If the ratio mode is eFIXED_WIDTH, the width value is in pixels and the height value is relative to the width value.
1025                         4 If the ratio mode is eFIXED_HEIGHT, the height value is in pixels and the width value is relative to the height value. 
1026                 
1027                 Definition at line 234 of file kfbxcamera.h. '''
1028                 
1029                 file.write('\n\t\t\tProperty: "PixelAspectRatio", "double", "",2')
1030                 
1031                 file.write('\n\t\t\tProperty: "UseFrameColor", "bool", "",0')
1032                 file.write('\n\t\t\tProperty: "FrameColor", "ColorRGB", "",0.3,0.3,0.3')
1033                 file.write('\n\t\t\tProperty: "ShowName", "bool", "",1')
1034                 file.write('\n\t\t\tProperty: "ShowGrid", "bool", "",1')
1035                 file.write('\n\t\t\tProperty: "ShowOpticalCenter", "bool", "",0')
1036                 file.write('\n\t\t\tProperty: "ShowAzimut", "bool", "",1')
1037                 file.write('\n\t\t\tProperty: "ShowTimeCode", "bool", "",0')
1038                 file.write('\n\t\t\tProperty: "NearPlane", "double", "",%.6f' % data.clip_start)
1039 #               file.write('\n\t\t\tProperty: "NearPlane", "double", "",%.6f' % data.clipStart)
1040                 file.write('\n\t\t\tProperty: "FarPlane", "double", "",%.6f' % data.clip_end)
1041 #               file.write('\n\t\t\tProperty: "FarPlane", "double", "",%.6f' % data.clipStart)
1042                 file.write('\n\t\t\tProperty: "FilmWidth", "double", "",1.0')
1043                 file.write('\n\t\t\tProperty: "FilmHeight", "double", "",1.0')
1044                 file.write('\n\t\t\tProperty: "FilmAspectRatio", "double", "",%.6f' % aspect)
1045                 file.write('\n\t\t\tProperty: "FilmSqueezeRatio", "double", "",1')
1046                 file.write('\n\t\t\tProperty: "FilmFormatIndex", "enum", "",0')
1047                 file.write('\n\t\t\tProperty: "ViewFrustum", "bool", "",1')
1048                 file.write('\n\t\t\tProperty: "ViewFrustumNearFarPlane", "bool", "",0')
1049                 file.write('\n\t\t\tProperty: "ViewFrustumBackPlaneMode", "enum", "",2')
1050                 file.write('\n\t\t\tProperty: "BackPlaneDistance", "double", "",100')
1051                 file.write('\n\t\t\tProperty: "BackPlaneDistanceMode", "enum", "",0')
1052                 file.write('\n\t\t\tProperty: "ViewCameraToLookAt", "bool", "",1')
1053                 file.write('\n\t\t\tProperty: "LockMode", "bool", "",0')
1054                 file.write('\n\t\t\tProperty: "LockInterestNavigation", "bool", "",0')
1055                 file.write('\n\t\t\tProperty: "FitImage", "bool", "",0')
1056                 file.write('\n\t\t\tProperty: "Crop", "bool", "",0')
1057                 file.write('\n\t\t\tProperty: "Center", "bool", "",1')
1058                 file.write('\n\t\t\tProperty: "KeepRatio", "bool", "",1')
1059                 file.write('\n\t\t\tProperty: "BackgroundMode", "enum", "",0')
1060                 file.write('\n\t\t\tProperty: "BackgroundAlphaTreshold", "double", "",0.5')
1061                 file.write('\n\t\t\tProperty: "ForegroundTransparent", "bool", "",1')
1062                 file.write('\n\t\t\tProperty: "DisplaySafeArea", "bool", "",0')
1063                 file.write('\n\t\t\tProperty: "SafeAreaDisplayStyle", "enum", "",1')
1064                 file.write('\n\t\t\tProperty: "SafeAreaAspectRatio", "double", "",%.6f' % aspect)
1065                 file.write('\n\t\t\tProperty: "Use2DMagnifierZoom", "bool", "",0')
1066                 file.write('\n\t\t\tProperty: "2D Magnifier Zoom", "Real", "A+",100')
1067                 file.write('\n\t\t\tProperty: "2D Magnifier X", "Real", "A+",50')
1068                 file.write('\n\t\t\tProperty: "2D Magnifier Y", "Real", "A+",50')
1069                 file.write('\n\t\t\tProperty: "CameraProjectionType", "enum", "",0')
1070                 file.write('\n\t\t\tProperty: "UseRealTimeDOFAndAA", "bool", "",0')
1071                 file.write('\n\t\t\tProperty: "UseDepthOfField", "bool", "",0')
1072                 file.write('\n\t\t\tProperty: "FocusSource", "enum", "",0')
1073                 file.write('\n\t\t\tProperty: "FocusAngle", "double", "",3.5')
1074                 file.write('\n\t\t\tProperty: "FocusDistance", "double", "",200')
1075                 file.write('\n\t\t\tProperty: "UseAntialiasing", "bool", "",0')
1076                 file.write('\n\t\t\tProperty: "AntialiasingIntensity", "double", "",0.77777')
1077                 file.write('\n\t\t\tProperty: "UseAccumulationBuffer", "bool", "",0')
1078                 file.write('\n\t\t\tProperty: "FrameSamplingCount", "int", "",7')
1079                 
1080                 file.write('\n\t\t}')
1081                 file.write('\n\t\tMultiLayer: 0')
1082                 file.write('\n\t\tMultiTake: 0')
1083                 file.write('\n\t\tShading: Y')
1084                 file.write('\n\t\tCulling: "CullingOff"')
1085                 file.write('\n\t\tTypeFlags: "Camera"')
1086                 file.write('\n\t\tGeometryVersion: 124')
1087                 file.write('\n\t\tPosition: %.6f,%.6f,%.6f' % loc)
1088                 file.write('\n\t\tUp: %.6f,%.6f,%.6f' % tuple(Mathutils.Vector(0,1,0) * matrix_rot) )
1089                 file.write('\n\t\tLookAt: %.6f,%.6f,%.6f' % tuple(Mathutils.Vector(0,0,-1)*matrix_rot) )
1090                 
1091                 #file.write('\n\t\tUp: 0,0,0' )
1092                 #file.write('\n\t\tLookAt: 0,0,0' )
1093                 
1094                 file.write('\n\t\tShowInfoOnMoving: 1')
1095                 file.write('\n\t\tShowAudio: 0')
1096                 file.write('\n\t\tAudioColor: 0,1,0')
1097                 file.write('\n\t\tCameraOrthoZoom: 1')
1098                 file.write('\n\t}')
1099         
1100         def write_light(my_light):
1101                 light = my_light.blenObject.data
1102                 file.write('\n\tModel: "Model::%s", "Light" {' % my_light.fbxName)
1103                 file.write('\n\t\tVersion: 232')
1104                 
1105                 write_object_props(my_light.blenObject, None, my_light.parRelMatrix())
1106                 
1107                 # Why are these values here twice?????? - oh well, follow the holy sdk's output
1108                 
1109                 # Blender light types match FBX's, funny coincidence, we just need to
1110                 # be sure that all unsupported types are made into a point light
1111                 #ePOINT, 
1112                 #eDIRECTIONAL
1113                 #eSPOT
1114                 light_type_items = {'POINT': 0, 'SUN': 1, 'SPOT': 2, 'HEMI': 3, 'AREA': 4}
1115                 light_type = light_type_items[light.type]
1116 #               light_type = light.type
1117                 if light_type > 2: light_type = 1 # hemi and area lights become directional
1118
1119 #               mode = light.mode
1120                 if light.shadow_method == 'RAY_SHADOW' or light.shadow_method == 'BUFFER_SHADOW':
1121 #               if mode & Blender.Lamp.Modes.RayShadow or mode & Blender.Lamp.Modes.Shadows:
1122                         do_shadow = 1
1123                 else:
1124                         do_shadow = 0
1125
1126                 if light.only_shadow or (not light.diffuse and not light.specular):
1127 #               if mode & Blender.Lamp.Modes.OnlyShadow or (mode & Blender.Lamp.Modes.NoDiffuse and mode & Blender.Lamp.Modes.NoSpecular):
1128                         do_light = 0
1129                 else:
1130                         do_light = 1
1131                 
1132                 scale = abs(GLOBAL_MATRIX.scalePart()[0]) # scale is always uniform in this case
1133                 
1134                 file.write('\n\t\t\tProperty: "LightType", "enum", "",%i' % light_type)
1135                 file.write('\n\t\t\tProperty: "CastLightOnObject", "bool", "",1')
1136                 file.write('\n\t\t\tProperty: "DrawVolumetricLight", "bool", "",1')
1137                 file.write('\n\t\t\tProperty: "DrawGroundProjection", "bool", "",1')
1138                 file.write('\n\t\t\tProperty: "DrawFrontFacingVolumetricLight", "bool", "",0')
1139                 file.write('\n\t\t\tProperty: "GoboProperty", "object", ""')
1140                 file.write('\n\t\t\tProperty: "Color", "Color", "A+",1,1,1')
1141                 file.write('\n\t\t\tProperty: "Intensity", "Intensity", "A+",%.2f' % (min(light.energy*100, 200))) # clamp below 200
1142                 if light.type == 'SPOT':
1143                         file.write('\n\t\t\tProperty: "Cone angle", "Cone angle", "A+",%.2f' % (light.spot_size * scale))
1144 #               file.write('\n\t\t\tProperty: "Cone angle", "Cone angle", "A+",%.2f' % (light.spotSize * scale))
1145                 file.write('\n\t\t\tProperty: "Fog", "Fog", "A+",50')
1146                 file.write('\n\t\t\tProperty: "Color", "Color", "A",%.2f,%.2f,%.2f' % tuple(light.color))
1147 #               file.write('\n\t\t\tProperty: "Color", "Color", "A",%.2f,%.2f,%.2f' % tuple(light.col))
1148                 file.write('\n\t\t\tProperty: "Intensity", "Intensity", "A+",%.2f' % (min(light.energy*100, 200))) # clamp below 200
1149
1150                 # duplication? see ^ (Arystan)
1151 #               file.write('\n\t\t\tProperty: "Cone angle", "Cone angle", "A+",%.2f' % (light.spotSize * scale))
1152                 file.write('\n\t\t\tProperty: "Fog", "Fog", "A+",50')
1153                 file.write('\n\t\t\tProperty: "LightType", "enum", "",%i' % light_type)
1154                 file.write('\n\t\t\tProperty: "CastLightOnObject", "bool", "",%i' % do_light)
1155                 file.write('\n\t\t\tProperty: "DrawGroundProjection", "bool", "",1')
1156                 file.write('\n\t\t\tProperty: "DrawFrontFacingVolumetricLight", "bool", "",0')
1157                 file.write('\n\t\t\tProperty: "DrawVolumetricLight", "bool", "",1')
1158                 file.write('\n\t\t\tProperty: "GoboProperty", "object", ""')
1159                 file.write('\n\t\t\tProperty: "DecayType", "enum", "",0')
1160                 file.write('\n\t\t\tProperty: "DecayStart", "double", "",%.2f' % light.distance)
1161 #               file.write('\n\t\t\tProperty: "DecayStart", "double", "",%.2f' % light.dist)
1162                 file.write('\n\t\t\tProperty: "EnableNearAttenuation", "bool", "",0')
1163                 file.write('\n\t\t\tProperty: "NearAttenuationStart", "double", "",0')
1164                 file.write('\n\t\t\tProperty: "NearAttenuationEnd", "double", "",0')
1165                 file.write('\n\t\t\tProperty: "EnableFarAttenuation", "bool", "",0')
1166                 file.write('\n\t\t\tProperty: "FarAttenuationStart", "double", "",0')
1167                 file.write('\n\t\t\tProperty: "FarAttenuationEnd", "double", "",0')
1168                 file.write('\n\t\t\tProperty: "CastShadows", "bool", "",%i' % do_shadow)
1169                 file.write('\n\t\t\tProperty: "ShadowColor", "ColorRGBA", "",0,0,0,1')
1170                 file.write('\n\t\t}')
1171                 file.write('\n\t\tMultiLayer: 0')
1172                 file.write('\n\t\tMultiTake: 0')
1173                 file.write('\n\t\tShading: Y')
1174                 file.write('\n\t\tCulling: "CullingOff"')
1175                 file.write('\n\t\tTypeFlags: "Light"')
1176                 file.write('\n\t\tGeometryVersion: 124')
1177                 file.write('\n\t}')
1178         
1179         # matrixOnly is not used at the moment
1180         def write_null(my_null = None, fbxName = None, matrixOnly = None):
1181                 # ob can be null
1182                 if not fbxName: fbxName = my_null.fbxName
1183                 
1184                 file.write('\n\tModel: "Model::%s", "Null" {' % fbxName)
1185                 file.write('\n\t\tVersion: 232')
1186                 
1187                 # only use this for the root matrix at the moment
1188                 if matrixOnly:
1189                         poseMatrix = write_object_props(None, None, matrixOnly)[3]
1190                 
1191                 else: # all other Null's
1192                         if my_null:             poseMatrix = write_object_props(my_null.blenObject, None, my_null.parRelMatrix())[3]
1193                         else:                   poseMatrix = write_object_props()[3]
1194                 
1195                 pose_items.append((fbxName, poseMatrix))
1196                 
1197                 file.write('''
1198                 }
1199                 MultiLayer: 0
1200                 MultiTake: 1
1201                 Shading: Y
1202                 Culling: "CullingOff"
1203                 TypeFlags: "Null"
1204         }''')
1205         
1206         # Material Settings
1207         if world:       world_amb = tuple(world.ambient_color)
1208 #       if world:       world_amb = world.getAmb()
1209         else:           world_amb = (0,0,0) # Default value
1210         
1211         def write_material(matname, mat):
1212                 file.write('\n\tMaterial: "Material::%s", "" {' % matname)
1213                 
1214                 # Todo, add more material Properties.
1215                 if mat:
1216                         mat_cold = tuple(mat.diffuse_color)
1217 #                       mat_cold = tuple(mat.rgbCol)
1218                         mat_cols = tuple(mat.specular_color)
1219 #                       mat_cols = tuple(mat.specCol)
1220                         #mat_colm = tuple(mat.mirCol) # we wont use the mirror color
1221                         mat_colamb = world_amb
1222 #                       mat_colamb = tuple([c for c in world_amb])
1223
1224                         mat_dif = mat.diffuse_intensity
1225 #                       mat_dif = mat.ref
1226                         mat_amb = mat.ambient
1227 #                       mat_amb = mat.amb
1228                         mat_hard = (float(mat.specular_hardness)-1)/5.10
1229 #                       mat_hard = (float(mat.hard)-1)/5.10
1230                         mat_spec = mat.specular_intensity/2.0
1231 #                       mat_spec = mat.spec/2.0
1232                         mat_alpha = mat.alpha
1233                         mat_emit = mat.emit
1234                         mat_shadeless = mat.shadeless
1235 #                       mat_shadeless = mat.mode & Blender.Material.Modes.SHADELESS
1236                         if mat_shadeless:
1237                                 mat_shader = 'Lambert'
1238                         else:
1239                                 if mat.diffuse_shader == 'LAMBERT':
1240 #                               if mat.diffuseShader == Blender.Material.Shaders.DIFFUSE_LAMBERT:
1241                                         mat_shader = 'Lambert'
1242                                 else:
1243                                         mat_shader = 'Phong'
1244                 else:
1245                         mat_cols = mat_cold = 0.8, 0.8, 0.8
1246                         mat_colamb = 0.0,0.0,0.0
1247                         # mat_colm 
1248                         mat_dif = 1.0
1249                         mat_amb = 0.5
1250                         mat_hard = 20.0
1251                         mat_spec = 0.2
1252                         mat_alpha = 1.0
1253                         mat_emit = 0.0
1254                         mat_shadeless = False
1255                         mat_shader = 'Phong'
1256                 
1257                 file.write('\n\t\tVersion: 102')
1258                 file.write('\n\t\tShadingModel: "%s"' % mat_shader.lower())
1259                 file.write('\n\t\tMultiLayer: 0')
1260                 
1261                 file.write('\n\t\tProperties60:  {')
1262                 file.write('\n\t\t\tProperty: "ShadingModel", "KString", "", "%s"' % mat_shader)
1263                 file.write('\n\t\t\tProperty: "MultiLayer", "bool", "",0')
1264                 file.write('\n\t\t\tProperty: "EmissiveColor", "ColorRGB", "",%.4f,%.4f,%.4f' % mat_cold) # emit and diffuse color are he same in blender
1265                 file.write('\n\t\t\tProperty: "EmissiveFactor", "double", "",%.4f' % mat_emit)
1266                 
1267                 file.write('\n\t\t\tProperty: "AmbientColor", "ColorRGB", "",%.4f,%.4f,%.4f' % mat_colamb)
1268                 file.write('\n\t\t\tProperty: "AmbientFactor", "double", "",%.4f' % mat_amb)
1269                 file.write('\n\t\t\tProperty: "DiffuseColor", "ColorRGB", "",%.4f,%.4f,%.4f' % mat_cold)
1270                 file.write('\n\t\t\tProperty: "DiffuseFactor", "double", "",%.4f' % mat_dif)
1271                 file.write('\n\t\t\tProperty: "Bump", "Vector3D", "",0,0,0')
1272                 file.write('\n\t\t\tProperty: "TransparentColor", "ColorRGB", "",1,1,1')
1273                 file.write('\n\t\t\tProperty: "TransparencyFactor", "double", "",%.4f' % (1.0 - mat_alpha))
1274                 if not mat_shadeless:
1275                         file.write('\n\t\t\tProperty: "SpecularColor", "ColorRGB", "",%.4f,%.4f,%.4f' % mat_cols)
1276                         file.write('\n\t\t\tProperty: "SpecularFactor", "double", "",%.4f' % mat_spec)
1277                         file.write('\n\t\t\tProperty: "ShininessExponent", "double", "",80.0')
1278                         file.write('\n\t\t\tProperty: "ReflectionColor", "ColorRGB", "",0,0,0')
1279                         file.write('\n\t\t\tProperty: "ReflectionFactor", "double", "",1')
1280                 file.write('\n\t\t\tProperty: "Emissive", "ColorRGB", "",0,0,0')
1281                 file.write('\n\t\t\tProperty: "Ambient", "ColorRGB", "",%.1f,%.1f,%.1f' % mat_colamb)
1282                 file.write('\n\t\t\tProperty: "Diffuse", "ColorRGB", "",%.1f,%.1f,%.1f' % mat_cold)
1283                 if not mat_shadeless:
1284                         file.write('\n\t\t\tProperty: "Specular", "ColorRGB", "",%.1f,%.1f,%.1f' % mat_cols)
1285                         file.write('\n\t\t\tProperty: "Shininess", "double", "",%.1f' % mat_hard)
1286                 file.write('\n\t\t\tProperty: "Opacity", "double", "",%.1f' % mat_alpha)
1287                 if not mat_shadeless:
1288                         file.write('\n\t\t\tProperty: "Reflectivity", "double", "",0')
1289
1290                 file.write('\n\t\t}')
1291                 file.write('\n\t}')
1292
1293         def copy_image(image):
1294
1295                 rel = image.get_export_path(basepath, True)
1296                 base = os.path.basename(rel)
1297
1298                 if EXP_IMAGE_COPY:
1299                         absp = image.get_export_path(basepath, False)
1300                         if not os.path.exists(absp):
1301                                 shutil.copy(image.get_abs_filename(), absp)
1302
1303                 return (rel, base)
1304
1305         # tex is an Image (Arystan)
1306         def write_video(texname, tex):
1307                 # Same as texture really!
1308                 file.write('\n\tVideo: "Video::%s", "Clip" {' % texname)
1309                 
1310                 file.write('''
1311                 Type: "Clip"
1312                 Properties60:  {
1313                         Property: "FrameRate", "double", "",0
1314                         Property: "LastFrame", "int", "",0
1315                         Property: "Width", "int", "",0
1316                         Property: "Height", "int", "",0''')
1317                 if tex:
1318                         fname_rel, fname_strip = copy_image(tex)
1319 #                       fname, fname_strip, fname_rel = derived_paths(tex.filename, basepath, EXP_IMAGE_COPY)
1320                 else:
1321                         fname = fname_strip = fname_rel = ''
1322                 
1323                 file.write('\n\t\t\tProperty: "Path", "charptr", "", "%s"' % fname_strip)
1324                 
1325                 
1326                 file.write('''
1327                         Property: "StartFrame", "int", "",0
1328                         Property: "StopFrame", "int", "",0
1329                         Property: "PlaySpeed", "double", "",1
1330                         Property: "Offset", "KTime", "",0
1331                         Property: "InterlaceMode", "enum", "",0
1332                         Property: "FreeRunning", "bool", "",0
1333                         Property: "Loop", "bool", "",0
1334                         Property: "AccessMode", "enum", "",0
1335                 }
1336                 UseMipMap: 0''')
1337                 
1338                 file.write('\n\t\tFilename: "%s"' % fname_strip)
1339                 if fname_strip: fname_strip = '/' + fname_strip
1340                 file.write('\n\t\tRelativeFilename: "%s"' % fname_rel) # make relative
1341                 file.write('\n\t}')
1342
1343         
1344         def write_texture(texname, tex, num):
1345                 # if tex == None then this is a dummy tex
1346                 file.write('\n\tTexture: "Texture::%s", "TextureVideoClip" {' % texname)
1347                 file.write('\n\t\tType: "TextureVideoClip"')
1348                 file.write('\n\t\tVersion: 202')
1349                 # TODO, rare case _empty_ exists as a name.
1350                 file.write('\n\t\tTextureName: "Texture::%s"' % texname)
1351                 
1352                 file.write('''
1353                 Properties60:  {
1354                         Property: "Translation", "Vector", "A+",0,0,0
1355                         Property: "Rotation", "Vector", "A+",0,0,0
1356                         Property: "Scaling", "Vector", "A+",1,1,1''')
1357                 file.write('\n\t\t\tProperty: "Texture alpha", "Number", "A+",%i' % num)
1358                 
1359                 
1360                 # WrapModeU/V 0==rep, 1==clamp, TODO add support
1361                 file.write('''
1362                         Property: "TextureTypeUse", "enum", "",0
1363                         Property: "CurrentTextureBlendMode", "enum", "",1
1364                         Property: "UseMaterial", "bool", "",0
1365                         Property: "UseMipMap", "bool", "",0
1366                         Property: "CurrentMappingType", "enum", "",0
1367                         Property: "UVSwap", "bool", "",0''')
1368
1369                 file.write('\n\t\t\tProperty: "WrapModeU", "enum", "",%i' % tex.clamp_x)
1370 #               file.write('\n\t\t\tProperty: "WrapModeU", "enum", "",%i' % tex.clampX)
1371                 file.write('\n\t\t\tProperty: "WrapModeV", "enum", "",%i' % tex.clamp_y)
1372 #               file.write('\n\t\t\tProperty: "WrapModeV", "enum", "",%i' % tex.clampY)
1373                 
1374                 file.write('''
1375                         Property: "TextureRotationPivot", "Vector3D", "",0,0,0
1376                         Property: "TextureScalingPivot", "Vector3D", "",0,0,0
1377                         Property: "VideoProperty", "object", ""
1378                 }''')
1379                 
1380                 file.write('\n\t\tMedia: "Video::%s"' % texname)
1381                 
1382                 if tex:
1383                         fname_rel, fname_strip = copy_image(tex)
1384 #                       fname, fname_strip, fname_rel = derived_paths(tex.filename, basepath, EXP_IMAGE_COPY)
1385                 else:
1386                         fname = fname_strip = fname_rel = ''
1387                 
1388                 file.write('\n\t\tFileName: "%s"' % fname_strip)
1389                 file.write('\n\t\tRelativeFilename: "%s"' % fname_rel) # need some make relative command
1390                 
1391                 file.write('''
1392                 ModelUVTranslation: 0,0
1393                 ModelUVScaling: 1,1
1394                 Texture_Alpha_Source: "None"
1395                 Cropping: 0,0,0,0
1396         }''')
1397
1398         def write_deformer_skin(obname):
1399                 '''
1400                 Each mesh has its own deformer
1401                 '''
1402                 file.write('\n\tDeformer: "Deformer::Skin %s", "Skin" {' % obname)
1403                 file.write('''
1404                 Version: 100
1405                 MultiLayer: 0
1406                 Type: "Skin"
1407                 Properties60:  {
1408                 }
1409                 Link_DeformAcuracy: 50
1410         }''')
1411         
1412         # in the example was 'Bip01 L Thigh_2'
1413         def write_sub_deformer_skin(my_mesh, my_bone, weights):
1414         
1415                 '''
1416                 Each subdeformer is spesific to a mesh, but the bone it links to can be used by many sub-deformers
1417                 So the SubDeformer needs the mesh-object name as a prefix to make it unique
1418                 
1419                 Its possible that there is no matching vgroup in this mesh, in that case no verts are in the subdeformer,
1420                 a but silly but dosnt really matter
1421                 '''
1422                 file.write('\n\tDeformer: "SubDeformer::Cluster %s %s", "Cluster" {' % (my_mesh.fbxName, my_bone.fbxName))
1423                 
1424                 file.write('''
1425                 Version: 100
1426                 MultiLayer: 0
1427                 Type: "Cluster"
1428                 Properties60:  {
1429                         Property: "SrcModel", "object", ""
1430                         Property: "SrcModelReference", "object", ""
1431                 }
1432                 UserData: "", ""''')
1433                 
1434                 # Support for bone parents
1435                 if my_mesh.fbxBoneParent:
1436                         if my_mesh.fbxBoneParent == my_bone:
1437                                 # TODO - this is a bit lazy, we could have a simple write loop
1438                                 # for this case because all weights are 1.0 but for now this is ok
1439                                 # Parent Bones arent used all that much anyway.
1440                                 vgroup_data = [(j, 1.0) for j in range(len(my_mesh.blenData.verts))]
1441                         else:
1442                                 # This bone is not a parent of this mesh object, no weights
1443                                 vgroup_data = []
1444                         
1445                 else:
1446                         # Normal weight painted mesh
1447                         if my_bone.blenName in weights[0]:
1448                                 # Before we used normalized wright list
1449                                 #vgroup_data = me.getVertsFromGroup(bone.name, 1)
1450                                 group_index = weights[0].index(my_bone.blenName)
1451                                 vgroup_data = [(j, weight[group_index]) for j, weight in enumerate(weights[1]) if weight[group_index]] 
1452                         else:
1453                                 vgroup_data = []
1454                 
1455                 file.write('\n\t\tIndexes: ')
1456                 
1457                 i = -1
1458                 for vg in vgroup_data:
1459                         if i == -1:
1460                                 file.write('%i'  % vg[0])
1461                                 i=0
1462                         else:
1463                                 if i==23:
1464                                         file.write('\n\t\t')
1465                                         i=0
1466                                 file.write(',%i' % vg[0])
1467                         i+=1
1468                 
1469                 file.write('\n\t\tWeights: ')
1470                 i = -1
1471                 for vg in vgroup_data:
1472                         if i == -1:
1473                                 file.write('%.8f'  % vg[1])
1474                                 i=0
1475                         else:
1476                                 if i==38:
1477                                         file.write('\n\t\t')
1478                                         i=0
1479                                 file.write(',%.8f' % vg[1])
1480                         i+=1
1481                 
1482                 if my_mesh.fbxParent:
1483                         # TODO FIXME, this case is broken in some cases. skinned meshes just shouldnt have parents where possible!
1484                         m = mtx4_z90 * (my_bone.restMatrix * my_bone.fbxArm.matrixWorld.copy() * my_mesh.matrixWorld.copy().invert() )
1485                 else:
1486                         # Yes! this is it...  - but dosnt work when the mesh is a.
1487                         m = mtx4_z90 * (my_bone.restMatrix * my_bone.fbxArm.matrixWorld.copy() * my_mesh.matrixWorld.copy().invert() )
1488                 
1489                 #m = mtx4_z90 * my_bone.restMatrix
1490                 matstr = mat4x4str(m)
1491                 matstr_i = mat4x4str(m.invert())
1492                 
1493                 file.write('\n\t\tTransform: %s' % matstr_i) # THIS IS __NOT__ THE GLOBAL MATRIX AS DOCUMENTED :/
1494                 file.write('\n\t\tTransformLink: %s' % matstr)
1495                 file.write('\n\t}')
1496         
1497         def write_mesh(my_mesh):
1498                 
1499                 me = my_mesh.blenData
1500                 
1501                 # if there are non NULL materials on this mesh
1502                 if my_mesh.blenMaterials:       do_materials = True
1503                 else:                                           do_materials = False
1504                 
1505                 if my_mesh.blenTextures:        do_textures = True
1506                 else:                                           do_textures = False     
1507                 
1508                 do_uvs = len(me.uv_textures) > 0
1509 #               do_uvs = me.faceUV
1510                 
1511                 
1512                 file.write('\n\tModel: "Model::%s", "Mesh" {' % my_mesh.fbxName)
1513                 file.write('\n\t\tVersion: 232') # newline is added in write_object_props
1514                 
1515                 poseMatrix = write_object_props(my_mesh.blenObject, None, my_mesh.parRelMatrix())[3]
1516                 pose_items.append((my_mesh.fbxName, poseMatrix))
1517                 
1518                 file.write('\n\t\t}')
1519                 file.write('\n\t\tMultiLayer: 0')
1520                 file.write('\n\t\tMultiTake: 1')
1521                 file.write('\n\t\tShading: Y')
1522                 file.write('\n\t\tCulling: "CullingOff"')
1523                 
1524                 
1525                 # Write the Real Mesh data here
1526                 file.write('\n\t\tVertices: ')
1527                 i=-1
1528                 
1529                 for v in me.verts:
1530                         if i==-1:
1531                                 file.write('%.6f,%.6f,%.6f' % tuple(v.co));     i=0
1532                         else:
1533                                 if i==7:
1534                                         file.write('\n\t\t');   i=0
1535                                 file.write(',%.6f,%.6f,%.6f'% tuple(v.co))
1536                         i+=1
1537                                 
1538                 file.write('\n\t\tPolygonVertexIndex: ')
1539                 i=-1
1540                 for f in me.faces:
1541                         fi = f.verts
1542                         # fi = [v_index for j, v_index in enumerate(f.verts) if v_index != 0 or j != 3]
1543 #                       fi = [v.index for v in f]
1544
1545                         # flip the last index, odd but it looks like
1546                         # this is how fbx tells one face from another
1547                         fi[-1] = -(fi[-1]+1)
1548                         fi = tuple(fi)
1549                         if i==-1:
1550                                 if len(fi) == 3:        file.write('%i,%i,%i' % fi )
1551 #                               if len(f) == 3:         file.write('%i,%i,%i' % fi )
1552                                 else:                           file.write('%i,%i,%i,%i' % fi )
1553                                 i=0
1554                         else:
1555                                 if i==13:
1556                                         file.write('\n\t\t')
1557                                         i=0
1558                                 if len(fi) == 3:        file.write(',%i,%i,%i' % fi )
1559 #                               if len(f) == 3:         file.write(',%i,%i,%i' % fi )
1560                                 else:                           file.write(',%i,%i,%i,%i' % fi )
1561                         i+=1
1562                 
1563                 file.write('\n\t\tEdges: ')
1564                 i=-1
1565                 for ed in me.edges:
1566                                 if i==-1:
1567                                         file.write('%i,%i' % (ed.verts[0], ed.verts[1]))
1568 #                                       file.write('%i,%i' % (ed.v1.index, ed.v2.index))
1569                                         i=0
1570                                 else:
1571                                         if i==13:
1572                                                 file.write('\n\t\t')
1573                                                 i=0
1574                                         file.write(',%i,%i' % (ed.verts[0], ed.verts[1]))
1575 #                                       file.write(',%i,%i' % (ed.v1.index, ed.v2.index))
1576                                 i+=1
1577                 
1578                 file.write('\n\t\tGeometryVersion: 124')
1579                 
1580                 file.write('''
1581                 LayerElementNormal: 0 {
1582                         Version: 101
1583                         Name: ""
1584                         MappingInformationType: "ByVertice"
1585                         ReferenceInformationType: "Direct"
1586                         Normals: ''')
1587                 
1588                 i=-1
1589                 for v in me.verts:
1590                         if i==-1:
1591                                 file.write('%.15f,%.15f,%.15f' % tuple(v.normal));      i=0
1592 #                               file.write('%.15f,%.15f,%.15f' % tuple(v.no));  i=0
1593                         else:
1594                                 if i==2:
1595                                         file.write('\n                   ');    i=0
1596                                 file.write(',%.15f,%.15f,%.15f' % tuple(v.normal))
1597 #                               file.write(',%.15f,%.15f,%.15f' % tuple(v.no))
1598                         i+=1
1599                 file.write('\n\t\t}')
1600                 
1601                 # Write Face Smoothing
1602                 file.write('''
1603                 LayerElementSmoothing: 0 {
1604                         Version: 102
1605                         Name: ""
1606                         MappingInformationType: "ByPolygon"
1607                         ReferenceInformationType: "Direct"
1608                         Smoothing: ''')
1609                 
1610                 i=-1
1611                 for f in me.faces:
1612                         if i==-1:
1613                                 file.write('%i' % f.smooth);    i=0
1614                         else:
1615                                 if i==54:
1616                                         file.write('\n                   ');    i=0
1617                                 file.write(',%i' % f.smooth)
1618                         i+=1
1619                 
1620                 file.write('\n\t\t}')
1621                 
1622                 # Write Edge Smoothing
1623                 file.write('''
1624                 LayerElementSmoothing: 0 {
1625                         Version: 101
1626                         Name: ""
1627                         MappingInformationType: "ByEdge"
1628                         ReferenceInformationType: "Direct"
1629                         Smoothing: ''')
1630                 
1631 #               SHARP = Blender.Mesh.EdgeFlags.SHARP
1632                 i=-1
1633                 for ed in me.edges:
1634                         if i==-1:
1635                                 file.write('%i' % (ed.sharp));  i=0
1636 #                               file.write('%i' % ((ed.flag&SHARP)!=0));        i=0
1637                         else:
1638                                 if i==54:
1639                                         file.write('\n                   ');    i=0
1640                                 file.write(',%i' % (ed.sharp))
1641 #                               file.write(',%i' % ((ed.flag&SHARP)!=0))
1642                         i+=1
1643                 
1644                 file.write('\n\t\t}')
1645 #               del SHARP
1646
1647                 # small utility function
1648                 # returns a slice of data depending on number of face verts
1649                 # data is either a MeshTextureFace or MeshColor
1650                 def face_data(data, face):
1651                         totvert = len(f.verts)
1652                                                 
1653                         return data[:totvert]
1654
1655                 
1656                 # Write VertexColor Layers
1657                 # note, no programs seem to use this info :/
1658                 collayers = []
1659                 if len(me.vertex_colors):
1660 #               if me.vertexColors:
1661                         collayers = me.vertex_colors
1662 #                       collayers = me.getColorLayerNames()
1663                         collayer_orig = me.active_vertex_color
1664 #                       collayer_orig = me.activeColorLayer
1665                         for colindex, collayer in enumerate(collayers):
1666 #                               me.activeColorLayer = collayer
1667                                 file.write('\n\t\tLayerElementColor: %i {' % colindex)
1668                                 file.write('\n\t\t\tVersion: 101')
1669                                 file.write('\n\t\t\tName: "%s"' % collayer.name)
1670 #                               file.write('\n\t\t\tName: "%s"' % collayer)
1671                                 
1672                                 file.write('''
1673                         MappingInformationType: "ByPolygonVertex"
1674                         ReferenceInformationType: "IndexToDirect"
1675                         Colors: ''')
1676                         
1677                                 i = -1
1678                                 ii = 0 # Count how many Colors we write
1679
1680                                 for f, cf in zip(me.faces, collayer.data):
1681                                         colors = [cf.color1, cf.color2, cf.color3, cf.color4]
1682
1683                                         # determine number of verts
1684                                         colors = face_data(colors, f)
1685
1686                                         for col in colors:
1687                                                 if i==-1:
1688                                                         file.write('%.4f,%.4f,%.4f,1' % tuple(col))
1689                                                         i=0
1690                                                 else:
1691                                                         if i==7:
1692                                                                 file.write('\n\t\t\t\t')
1693                                                                 i=0
1694                                                         file.write(',%.4f,%.4f,%.4f,1' % tuple(col))
1695                                                 i+=1
1696                                                 ii+=1 # One more Color
1697
1698 #                               for f in me.faces:
1699 #                                       for col in f.col:
1700 #                                               if i==-1:
1701 #                                                       file.write('%.4f,%.4f,%.4f,1' % (col[0]/255.0, col[1]/255.0, col[2]/255.0))
1702 #                                                       i=0
1703 #                                               else:
1704 #                                                       if i==7:
1705 #                                                               file.write('\n\t\t\t\t')
1706 #                                                               i=0
1707 #                                                       file.write(',%.4f,%.4f,%.4f,1' % (col[0]/255.0, col[1]/255.0, col[2]/255.0))
1708 #                                               i+=1
1709 #                                               ii+=1 # One more Color
1710                                 
1711                                 file.write('\n\t\t\tColorIndex: ')
1712                                 i = -1
1713                                 for j in range(ii):
1714                                         if i == -1:
1715                                                 file.write('%i' % j)
1716                                                 i=0
1717                                         else:
1718                                                 if i==55:
1719                                                         file.write('\n\t\t\t\t')
1720                                                         i=0
1721                                                 file.write(',%i' % j)
1722                                         i+=1
1723                                 
1724                                 file.write('\n\t\t}')
1725                 
1726                 
1727                 
1728                 # Write UV and texture layers.
1729                 uvlayers = []
1730                 if do_uvs:
1731                         uvlayers = me.uv_textures
1732 #                       uvlayers = me.getUVLayerNames()
1733                         uvlayer_orig = me.active_uv_texture
1734 #                       uvlayer_orig = me.activeUVLayer
1735                         for uvindex, uvlayer in enumerate(me.uv_textures):
1736 #                       for uvindex, uvlayer in enumerate(uvlayers):
1737 #                               me.activeUVLayer = uvlayer
1738                                 file.write('\n\t\tLayerElementUV: %i {' % uvindex)
1739                                 file.write('\n\t\t\tVersion: 101')
1740                                 file.write('\n\t\t\tName: "%s"' % uvlayer.name)
1741 #                               file.write('\n\t\t\tName: "%s"' % uvlayer)
1742                                 
1743                                 file.write('''
1744                         MappingInformationType: "ByPolygonVertex"
1745                         ReferenceInformationType: "IndexToDirect"
1746                         UV: ''')
1747                         
1748                                 i = -1
1749                                 ii = 0 # Count how many UVs we write
1750                                 
1751                                 for uf in uvlayer.data:
1752 #                               for f in me.faces:
1753                                         for uv in uf.uv:
1754 #                                       for uv in f.uv:
1755                                                 if i==-1:
1756                                                         file.write('%.6f,%.6f' % tuple(uv))
1757                                                         i=0
1758                                                 else:
1759                                                         if i==7:
1760                                                                 file.write('\n                   ')
1761                                                                 i=0
1762                                                         file.write(',%.6f,%.6f' % tuple(uv))
1763                                                 i+=1
1764                                                 ii+=1 # One more UV
1765                                 
1766                                 file.write('\n\t\t\tUVIndex: ')
1767                                 i = -1
1768                                 for j in range(ii):
1769                                         if i == -1:
1770                                                 file.write('%i'  % j)
1771                                                 i=0
1772                                         else:
1773                                                 if i==55:
1774                                                         file.write('\n\t\t\t\t')
1775                                                         i=0
1776                                                 file.write(',%i' % j)
1777                                         i+=1
1778                                 
1779                                 file.write('\n\t\t}')
1780                                 
1781                                 if do_textures:
1782                                         file.write('\n\t\tLayerElementTexture: %i {' % uvindex)
1783                                         file.write('\n\t\t\tVersion: 101')
1784                                         file.write('\n\t\t\tName: "%s"' % uvlayer.name)
1785 #                                       file.write('\n\t\t\tName: "%s"' % uvlayer)
1786                                         
1787                                         if len(my_mesh.blenTextures) == 1:
1788                                                 file.write('\n\t\t\tMappingInformationType: "AllSame"')
1789                                         else:
1790                                                 file.write('\n\t\t\tMappingInformationType: "ByPolygon"')
1791                                         
1792                                         file.write('\n\t\t\tReferenceInformationType: "IndexToDirect"')
1793                                         file.write('\n\t\t\tBlendMode: "Translucent"')
1794                                         file.write('\n\t\t\tTextureAlpha: 1')
1795                                         file.write('\n\t\t\tTextureId: ')
1796                                         
1797                                         if len(my_mesh.blenTextures) == 1:
1798                                                 file.write('0')
1799                                         else:
1800                                                 texture_mapping_local = {None:-1}
1801                                                 
1802                                                 i = 0 # 1 for dummy
1803                                                 for tex in my_mesh.blenTextures:
1804                                                         if tex: # None is set above
1805                                                                 texture_mapping_local[tex] = i
1806                                                                 i+=1
1807                                                 
1808                                                 i=-1
1809                                                 for f in uvlayer.data:
1810 #                                               for f in me.faces:
1811                                                         img_key = f.image
1812                                                         
1813                                                         if i==-1:
1814                                                                 i=0
1815                                                                 file.write( '%s' % texture_mapping_local[img_key])
1816                                                         else:
1817                                                                 if i==55:
1818                                                                         file.write('\n                   ')
1819                                                                         i=0
1820                                                                 
1821                                                                 file.write(',%s' % texture_mapping_local[img_key])
1822                                                         i+=1
1823                                 
1824                                 else:
1825                                         file.write('''
1826                 LayerElementTexture: 0 {
1827                         Version: 101
1828                         Name: ""
1829                         MappingInformationType: "NoMappingInformation"
1830                         ReferenceInformationType: "IndexToDirect"
1831                         BlendMode: "Translucent"
1832                         TextureAlpha: 1
1833                         TextureId: ''')
1834                                 file.write('\n\t\t}')
1835                         
1836 #                       me.activeUVLayer = uvlayer_orig
1837                         
1838                 # Done with UV/textures.
1839                 
1840                 if do_materials:
1841                         file.write('\n\t\tLayerElementMaterial: 0 {')
1842                         file.write('\n\t\t\tVersion: 101')
1843                         file.write('\n\t\t\tName: ""')
1844                         
1845                         if len(my_mesh.blenMaterials) == 1:
1846                                 file.write('\n\t\t\tMappingInformationType: "AllSame"')
1847                         else:
1848                                 file.write('\n\t\t\tMappingInformationType: "ByPolygon"')
1849                         
1850                         file.write('\n\t\t\tReferenceInformationType: "IndexToDirect"')
1851                         file.write('\n\t\t\tMaterials: ')
1852                         
1853                         if len(my_mesh.blenMaterials) == 1:
1854                                 file.write('0')
1855                         else:
1856                                 # Build a material mapping for this 
1857                                 material_mapping_local = {} # local-mat & tex : global index.
1858                                 
1859                                 for j, mat_tex_pair in enumerate(my_mesh.blenMaterials):
1860                                         material_mapping_local[mat_tex_pair] = j
1861                                 
1862                                 len_material_mapping_local = len(material_mapping_local)
1863                                 
1864                                 mats = my_mesh.blenMaterialList
1865
1866                                 if me.active_uv_texture:
1867                                         uv_faces = me.active_uv_texture.data
1868                                 else:
1869                                         uv_faces = [None] * len(me.faces)
1870                                 
1871                                 i=-1
1872                                 for f, uf in zip(me.faces, uv_faces):
1873 #                               for f in me.faces:
1874                                         try:    mat = mats[f.material_index]
1875 #                                       try:    mat = mats[f.mat]
1876                                         except:mat = None
1877                                         
1878                                         if do_uvs: tex = uf.image # WARNING - MULTI UV LAYER IMAGES NOT SUPPORTED :/
1879 #                                       if do_uvs: tex = f.image # WARNING - MULTI UV LAYER IMAGES NOT SUPPORTED :/
1880                                         else: tex = None
1881                                         
1882                                         if i==-1:
1883                                                 i=0
1884                                                 file.write( '%s' % (material_mapping_local[mat, tex])) # None for mat or tex is ok
1885                                         else:
1886                                                 if i==55:
1887                                                         file.write('\n\t\t\t\t')
1888                                                         i=0
1889                                                 
1890                                                 file.write(',%s' % (material_mapping_local[mat, tex]))
1891                                         i+=1
1892                         
1893                         file.write('\n\t\t}')
1894                 
1895                 file.write('''
1896                 Layer: 0 {
1897                         Version: 100
1898                         LayerElement:  {
1899                                 Type: "LayerElementNormal"
1900                                 TypedIndex: 0
1901                         }''')
1902                 
1903                 if do_materials:
1904                         file.write('''
1905                         LayerElement:  {
1906                                 Type: "LayerElementMaterial"
1907                                 TypedIndex: 0
1908                         }''')
1909                         
1910                 # Always write this
1911                 if do_textures:
1912                         file.write('''
1913                         LayerElement:  {
1914                                 Type: "LayerElementTexture"
1915                                 TypedIndex: 0
1916                         }''')
1917                 
1918                 if me.vertex_colors:
1919 #               if me.vertexColors:
1920                         file.write('''
1921                         LayerElement:  {
1922                                 Type: "LayerElementColor"
1923                                 TypedIndex: 0
1924                         }''')
1925                 
1926                 if do_uvs: # same as me.faceUV
1927                         file.write('''
1928                         LayerElement:  {
1929                                 Type: "LayerElementUV"
1930                                 TypedIndex: 0
1931                         }''')
1932                 
1933                 
1934                 file.write('\n\t\t}')
1935                 
1936                 if len(uvlayers) > 1:
1937                         for i in range(1, len(uvlayers)):
1938                                 
1939                                 file.write('\n\t\tLayer: %i {' % i)
1940                                 file.write('\n\t\t\tVersion: 100')
1941                                 
1942                                 file.write('''
1943                         LayerElement:  {
1944                                 Type: "LayerElementUV"''')
1945                                 
1946                                 file.write('\n\t\t\t\tTypedIndex: %i' % i)
1947                                 file.write('\n\t\t\t}')
1948                                 
1949                                 if do_textures:
1950                                         
1951                                         file.write('''
1952                         LayerElement:  {
1953                                 Type: "LayerElementTexture"''')
1954                                         
1955                                         file.write('\n\t\t\t\tTypedIndex: %i' % i)
1956                                         file.write('\n\t\t\t}')
1957                                 
1958                                 file.write('\n\t\t}')
1959                 
1960                 if len(collayers) > 1:
1961                         # Take into account any UV layers
1962                         layer_offset = 0
1963                         if uvlayers: layer_offset = len(uvlayers)-1
1964                         
1965                         for i in range(layer_offset, len(collayers)+layer_offset):
1966                                 file.write('\n\t\tLayer: %i {' % i)
1967                                 file.write('\n\t\t\tVersion: 100')
1968                                 
1969                                 file.write('''
1970                         LayerElement:  {
1971                                 Type: "LayerElementColor"''')
1972                                 
1973                                 file.write('\n\t\t\t\tTypedIndex: %i' % i)
1974                                 file.write('\n\t\t\t}')
1975                                 file.write('\n\t\t}')
1976                 file.write('\n\t}')
1977         
1978         def write_group(name):
1979                 file.write('\n\tGroupSelection: "GroupSelection::%s", "Default" {' % name)
1980                 
1981                 file.write('''
1982                 Properties60:  {
1983                         Property: "MultiLayer", "bool", "",0
1984                         Property: "Pickable", "bool", "",1
1985                         Property: "Transformable", "bool", "",1
1986                         Property: "Show", "bool", "",1
1987                 }
1988                 MultiLayer: 0
1989         }''')
1990         
1991         
1992         # add meshes here to clear because they are not used anywhere.
1993         meshes_to_clear = []
1994         
1995         ob_meshes = []  
1996         ob_lights = []
1997         ob_cameras = []
1998         # in fbx we export bones as children of the mesh
1999         # armatures not a part of a mesh, will be added to ob_arms
2000         ob_bones = [] 
2001         ob_arms = []
2002         ob_null = [] # emptys
2003         
2004         # List of types that have blender objects (not bones)
2005         ob_all_typegroups = [ob_meshes, ob_lights, ob_cameras, ob_arms, ob_null]
2006         
2007         groups = [] # blender groups, only add ones that have objects in the selections
2008         materials = {} # (mat, image) keys, should be a set()
2009         textures = {} # should be a set()
2010         
2011         tmp_ob_type = ob_type = None # incase no objects are exported, so as not to raise an error
2012         
2013         # if EXP_OBS_SELECTED is false, use sceens objects
2014         if not batch_objects:
2015                 if EXP_OBS_SELECTED:    tmp_objects = context.selected_objects
2016 #               if EXP_OBS_SELECTED:    tmp_objects = sce.objects.context
2017                 else:                                   tmp_objects = sce.objects
2018         else:
2019                 tmp_objects = batch_objects
2020         
2021         if EXP_ARMATURE:
2022                 # This is needed so applying modifiers dosnt apply the armature deformation, its also needed
2023                 # ...so mesh objects return their rest worldspace matrix when bone-parents are exported as weighted meshes.
2024                 # set every armature to its rest, backup the original values so we done mess up the scene
2025                 ob_arms_orig_rest = [arm.rest_position for arm in bpy.data.armatures]
2026 #               ob_arms_orig_rest = [arm.restPosition for arm in bpy.data.armatures]
2027                 
2028                 for arm in bpy.data.armatures:
2029                         arm.rest_position = True
2030 #                       arm.restPosition = True
2031                 
2032                 if ob_arms_orig_rest:
2033                         for ob_base in bpy.data.objects:
2034                                 #if ob_base.type == 'Armature':
2035                                 ob_base.make_display_list()
2036 #                               ob_base.makeDisplayList()
2037                                         
2038                         # This causes the makeDisplayList command to effect the mesh
2039                         sce.set_frame(sce.current_frame)
2040 #                       Blender.Set('curframe', Blender.Get('curframe'))
2041                         
2042         
2043         for ob_base in tmp_objects:
2044
2045                 # ignore dupli children
2046                 if ob_base.parent and ob_base.parent.dupli_type != 'NONE':
2047                         continue
2048
2049                 obs = [(ob_base, ob_base.matrix)]
2050                 if ob_base.dupli_type != 'NONE':
2051                         ob_base.create_dupli_list()
2052                         obs = [(dob.object, dob.matrix) for dob in ob_base.dupli_list]
2053
2054                 for ob, mtx in obs:
2055 #               for ob, mtx in BPyObject.getDerivedObjects(ob_base):
2056                         tmp_ob_type = ob.type
2057                         if tmp_ob_type == 'CAMERA':
2058 #                       if tmp_ob_type == 'Camera':
2059                                 if EXP_CAMERA:
2060                                         ob_cameras.append(my_object_generic(ob, mtx))
2061                         elif tmp_ob_type == 'LAMP':
2062 #                       elif tmp_ob_type == 'Lamp':
2063                                 if EXP_LAMP:
2064                                         ob_lights.append(my_object_generic(ob, mtx))
2065                         elif tmp_ob_type == 'ARMATURE':
2066 #                       elif tmp_ob_type == 'Armature':
2067                                 if EXP_ARMATURE:
2068                                         # TODO - armatures dont work in dupligroups!
2069                                         if ob not in ob_arms: ob_arms.append(ob)
2070                                         # ob_arms.append(ob) # replace later. was "ob_arms.append(sane_obname(ob), ob)"
2071                         elif tmp_ob_type == 'EMPTY':
2072 #                       elif tmp_ob_type == 'Empty':
2073                                 if EXP_EMPTY:
2074                                         ob_null.append(my_object_generic(ob, mtx))
2075                         elif EXP_MESH:
2076                                 origData = True
2077                                 if tmp_ob_type != 'MESH':
2078 #                               if tmp_ob_type != 'Mesh':
2079 #                                       me = bpy.data.meshes.new()
2080                                         try:    me = ob.create_mesh(True, 'PREVIEW')
2081 #                                       try:    me.getFromObject(ob)
2082                                         except: me = None
2083                                         if me:
2084                                                 meshes_to_clear.append( me )
2085                                                 mats = me.materials
2086                                                 origData = False
2087                                 else:
2088                                         # Mesh Type!
2089                                         if EXP_MESH_APPLY_MOD:
2090 #                                               me = bpy.data.meshes.new()
2091                                                 me = ob.create_mesh(True, 'PREVIEW')
2092 #                                               me.getFromObject(ob)
2093                                                 
2094                                                 # so we keep the vert groups
2095 #                                               if EXP_ARMATURE:
2096 #                                                       orig_mesh = ob.getData(mesh=1)
2097 #                                                       if orig_mesh.getVertGroupNames():
2098 #                                                               ob.copy().link(me)
2099 #                                                               # If new mesh has no vgroups we can try add if verts are teh same
2100 #                                                               if not me.getVertGroupNames(): # vgroups were not kept by the modifier
2101 #                                                                       if len(me.verts) == len(orig_mesh.verts):
2102 #                                                                               groupNames, vWeightDict = BPyMesh.meshWeight2Dict(orig_mesh)
2103 #                                                                               BPyMesh.dict2MeshWeight(me, groupNames, vWeightDict)
2104                                                 
2105                                                 # print ob, me, me.getVertGroupNames()
2106                                                 meshes_to_clear.append( me )
2107                                                 origData = False
2108                                                 mats = me.materials
2109                                         else:
2110                                                 me = ob.data
2111 #                                               me = ob.getData(mesh=1)
2112                                                 mats = me.materials
2113                                                 
2114 #                                               # Support object colors
2115 #                                               tmp_colbits = ob.colbits
2116 #                                               if tmp_colbits:
2117 #                                                       tmp_ob_mats = ob.getMaterials(1) # 1 so we get None's too.
2118 #                                                       for i in xrange(16):
2119 #                                                               if tmp_colbits & (1<<i):
2120 #                                                                       mats[i] = tmp_ob_mats[i]
2121 #                                                       del tmp_ob_mats
2122 #                                               del tmp_colbits
2123                                                         
2124                                         
2125                                 if me:
2126 #                                       # This WILL modify meshes in blender if EXP_MESH_APPLY_MOD is disabled.
2127 #                                       # so strictly this is bad. but only in rare cases would it have negative results
2128 #                                       # say with dupliverts the objects would rotate a bit differently
2129 #                                       if EXP_MESH_HQ_NORMALS:
2130 #                                               BPyMesh.meshCalcNormals(me) # high quality normals nice for realtime engines.
2131                                         
2132                                         texture_mapping_local = {}
2133                                         material_mapping_local = {}
2134                                         if len(me.uv_textures) > 0:
2135 #                                       if me.faceUV:
2136                                                 uvlayer_orig = me.active_uv_texture
2137 #                                               uvlayer_orig = me.activeUVLayer
2138                                                 for uvlayer in me.uv_textures:
2139 #                                               for uvlayer in me.getUVLayerNames():
2140 #                                                       me.activeUVLayer = uvlayer
2141                                                         for f, uf in zip(me.faces, uvlayer.data):
2142 #                                                       for f in me.faces:
2143                                                                 tex = uf.image
2144 #                                                               tex = f.image
2145                                                                 textures[tex] = texture_mapping_local[tex] = None
2146                                                                 
2147                                                                 try: mat = mats[f.material_index]
2148 #                                                               try: mat = mats[f.mat]
2149                                                                 except: mat = None
2150                                                                 
2151                                                                 materials[mat, tex] = material_mapping_local[mat, tex] = None # should use sets, wait for blender 2.5
2152                                                                         
2153                                                         
2154 #                                                       me.activeUVLayer = uvlayer_orig
2155                                         else:
2156                                                 for mat in mats:
2157                                                         # 2.44 use mat.lib too for uniqueness
2158                                                         materials[mat, None] = material_mapping_local[mat, None] = None
2159                                                 else:
2160                                                         materials[None, None] = None
2161                                         
2162                                         if EXP_ARMATURE:
2163                                                 armob = ob.find_armature()
2164                                                 blenParentBoneName = None
2165                                                 
2166                                                 # parent bone - special case
2167                                                 if (not armob) and ob.parent and ob.parent.type == 'ARMATURE' and \
2168                                                                 ob.parent_type == 'BONE':
2169 #                                               if (not armob) and ob.parent and ob.parent.type == 'Armature' and ob.parentType == Blender.Object.ParentTypes.BONE:
2170                                                         armob = ob.parent
2171                                                         blenParentBoneName = ob.parent_bone
2172 #                                                       blenParentBoneName = ob.parentbonename
2173                                                 
2174                                                         
2175                                                 if armob and armob not in ob_arms:
2176                                                         ob_arms.append(armob)
2177                                         
2178                                         else:
2179                                                 blenParentBoneName = armob = None
2180                                         
2181                                         my_mesh = my_object_generic(ob, mtx)
2182                                         my_mesh.blenData =              me
2183                                         my_mesh.origData =              origData
2184                                         my_mesh.blenMaterials = list(material_mapping_local.keys())
2185                                         my_mesh.blenMaterialList = mats
2186                                         my_mesh.blenTextures =  list(texture_mapping_local.keys())
2187                                         
2188                                         # if only 1 null texture then empty the list
2189                                         if len(my_mesh.blenTextures) == 1 and my_mesh.blenTextures[0] == None:
2190                                                 my_mesh.blenTextures = []
2191                                         
2192                                         my_mesh.fbxArm =        armob                                   # replace with my_object_generic armature instance later
2193                                         my_mesh.fbxBoneParent = blenParentBoneName      # replace with my_bone instance later
2194                                         
2195                                         ob_meshes.append( my_mesh )
2196
2197                 # not forgetting to free dupli_list
2198                 if ob_base.dupli_list: ob_base.free_dupli_list()
2199
2200
2201         if EXP_ARMATURE:
2202                 # now we have the meshes, restore the rest arm position
2203                 for i, arm in enumerate(bpy.data.armatures):
2204                         arm.rest_position = ob_arms_orig_rest[i]
2205 #                       arm.restPosition = ob_arms_orig_rest[i]
2206                         
2207                 if ob_arms_orig_rest:
2208                         for ob_base in bpy.data.objects:
2209                                 if ob_base.type == 'ARMATURE':
2210 #                               if ob_base.type == 'Armature':
2211                                         ob_base.make_display_list()
2212 #                                       ob_base.makeDisplayList()
2213                         # This causes the makeDisplayList command to effect the mesh
2214                         sce.set_frame(sce.current_frame)
2215 #                       Blender.Set('curframe', Blender.Get('curframe'))
2216         
2217         del tmp_ob_type, tmp_objects
2218         
2219         # now we have collected all armatures, add bones
2220         for i, ob in enumerate(ob_arms):
2221                 
2222                 ob_arms[i] = my_arm = my_object_generic(ob)
2223                 
2224                 my_arm.fbxBones =               []
2225                 my_arm.blenData =               ob.data
2226                 if ob.animation_data:
2227                         my_arm.blenAction =     ob.animation_data.action
2228                 else:
2229                         my_arm.blenAction = None
2230 #               my_arm.blenAction =             ob.action
2231                 my_arm.blenActionList = []
2232                 
2233                 # fbxName, blenderObject, my_bones, blenderActions
2234                 #ob_arms[i] = fbxArmObName, ob, arm_my_bones, (ob.action, [])
2235                 
2236                 for bone in my_arm.blenData.bones:
2237 #               for bone in my_arm.blenData.bones.values():
2238                         my_bone = my_bone_class(bone, my_arm)
2239                         my_arm.fbxBones.append( my_bone )
2240                         ob_bones.append( my_bone )
2241         
2242         # add the meshes to the bones and replace the meshes armature with own armature class
2243         #for obname, ob, mtx, me, mats, arm, armname in ob_meshes:
2244         for my_mesh in ob_meshes:
2245                 # Replace 
2246                 # ...this could be sped up with dictionary mapping but its unlikely for
2247                 # it ever to be a bottleneck - (would need 100+ meshes using armatures)
2248                 if my_mesh.fbxArm:
2249                         for my_arm in ob_arms:
2250                                 if my_arm.blenObject == my_mesh.fbxArm:
2251                                         my_mesh.fbxArm = my_arm
2252                                         break
2253                 
2254                 for my_bone in ob_bones:
2255                         
2256                         # The mesh uses this bones armature!
2257                         if my_bone.fbxArm == my_mesh.fbxArm:
2258                                 my_bone.blenMeshes[my_mesh.fbxName] = me
2259                                 
2260                                 
2261                                 # parent bone: replace bone names with our class instances
2262                                 # my_mesh.fbxBoneParent is None or a blender bone name initialy, replacing if the names match.
2263                                 if my_mesh.fbxBoneParent == my_bone.blenName:
2264                                         my_mesh.fbxBoneParent = my_bone
2265         
2266         bone_deformer_count = 0 # count how many bones deform a mesh
2267         my_bone_blenParent = None
2268         for my_bone in ob_bones:
2269                 my_bone_blenParent = my_bone.blenBone.parent
2270                 if my_bone_blenParent:
2271                         for my_bone_parent in ob_bones:
2272                                 # Note 2.45rc2 you can compare bones normally
2273                                 if my_bone_blenParent.name == my_bone_parent.blenName and my_bone.fbxArm == my_bone_parent.fbxArm:
2274                                         my_bone.parent = my_bone_parent
2275                                         break
2276                 
2277                 # Not used at the moment
2278                 # my_bone.calcRestMatrixLocal()
2279                 bone_deformer_count += len(my_bone.blenMeshes)
2280         
2281         del my_bone_blenParent 
2282         
2283         
2284         # Build blenObject -> fbxObject mapping
2285         # this is needed for groups as well as fbxParenting
2286 #       for ob in bpy.data.objects:     ob.tag = False
2287 #       bpy.data.objects.tag = False
2288
2289         # using a list of object names for tagging (Arystan)
2290         tagged_objects = []
2291
2292         tmp_obmapping = {}
2293         for ob_generic in ob_all_typegroups:
2294                 for ob_base in ob_generic:
2295                         tagged_objects.append(ob_base.blenObject.name)
2296 #                       ob_base.blenObject.tag = True
2297                         tmp_obmapping[ob_base.blenObject] = ob_base
2298         
2299         # Build Groups from objects we export
2300         for blenGroup in bpy.data.groups:
2301                 fbxGroupName = None
2302                 for ob in blenGroup.objects:
2303                         if ob.name in tagged_objects:
2304 #                       if ob.tag:
2305                                 if fbxGroupName == None:
2306                                         fbxGroupName = sane_groupname(blenGroup)
2307                                         groups.append((fbxGroupName, blenGroup))
2308                                 
2309                                 tmp_obmapping[ob].fbxGroupNames.append(fbxGroupName) # also adds to the objects fbxGroupNames
2310         
2311         groups.sort() # not really needed
2312         
2313         # Assign parents using this mapping
2314         for ob_generic in ob_all_typegroups:
2315                 for my_ob in ob_generic:
2316                         parent = my_ob.blenObject.parent
2317                         if parent and parent.name in tagged_objects: # does it exist and is it in the mapping
2318 #                       if parent and parent.tag: # does it exist and is it in the mapping
2319                                 my_ob.fbxParent = tmp_obmapping[parent]
2320         
2321         
2322         del tmp_obmapping
2323         # Finished finding groups we use
2324         
2325         
2326         materials =     [(sane_matname(mat_tex_pair), mat_tex_pair) for mat_tex_pair in materials.keys()]
2327         textures =      [(sane_texname(tex), tex) for tex in textures.keys()  if tex]
2328         materials.sort() # sort by name
2329         textures.sort()
2330         
2331         camera_count = 8
2332         file.write('''
2333
2334 ; Object definitions
2335 ;------------------------------------------------------------------
2336
2337 Definitions:  {
2338         Version: 100
2339         Count: %i''' % (\
2340                 1+1+camera_count+\
2341                 len(ob_meshes)+\
2342                 len(ob_lights)+\
2343                 len(ob_cameras)+\
2344                 len(ob_arms)+\
2345                 len(ob_null)+\
2346                 len(ob_bones)+\
2347                 bone_deformer_count+\
2348                 len(materials)+\
2349                 (len(textures)*2))) # add 1 for the root model 1 for global settings
2350         
2351         del bone_deformer_count
2352         
2353         file.write('''
2354         ObjectType: "Model" {
2355                 Count: %i
2356         }''' % (\
2357                 1+camera_count+\
2358                 len(ob_meshes)+\
2359                 len(ob_lights)+\
2360                 len(ob_cameras)+\
2361                 len(ob_arms)+\
2362                 len(ob_null)+\
2363                 len(ob_bones))) # add 1 for the root model
2364         
2365         file.write('''
2366         ObjectType: "Geometry" {
2367                 Count: %i
2368         }''' % len(ob_meshes))
2369         
2370         if materials:
2371                 file.write('''
2372         ObjectType: "Material" {
2373                 Count: %i
2374         }''' % len(materials))
2375         
2376         if textures:
2377                 file.write('''
2378         ObjectType: "Texture" {
2379                 Count: %i
2380         }''' % len(textures)) # add 1 for an empty tex
2381                 file.write('''
2382         ObjectType: "Video" {
2383                 Count: %i
2384         }''' % len(textures)) # add 1 for an empty tex
2385         
2386         tmp = 0
2387         # Add deformer nodes
2388         for my_mesh in ob_meshes:
2389                 if my_mesh.fbxArm:
2390                         tmp+=1
2391         
2392         # Add subdeformers
2393         for my_bone in ob_bones:
2394                 tmp += len(my_bone.blenMeshes)
2395         
2396         if tmp:
2397                 file.write('''
2398         ObjectType: "Deformer" {
2399                 Count: %i
2400         }''' % tmp)
2401         del tmp
2402         
2403         # we could avoid writing this possibly but for now just write it
2404         
2405         file.write('''
2406         ObjectType: "Pose" {
2407                 Count: 1
2408         }''')
2409         
2410         if groups:
2411                 file.write('''
2412         ObjectType: "GroupSelection" {
2413                 Count: %i
2414         }''' % len(groups))
2415         
2416         file.write('''
2417         ObjectType: "GlobalSettings" {
2418                 Count: 1
2419         }
2420 }''')
2421
2422         file.write('''
2423
2424 ; Object properties
2425 ;------------------------------------------------------------------
2426
2427 Objects:  {''')
2428         
2429         # To comply with other FBX FILES
2430         write_camera_switch()
2431         
2432         # Write the null object
2433         write_null(None, 'blend_root')# , GLOBAL_MATRIX) 
2434         
2435         for my_null in ob_null:
2436                 write_null(my_null)
2437         
2438         for my_arm in ob_arms:
2439                 write_null(my_arm)
2440         
2441         for my_cam in ob_cameras:
2442                 write_camera(my_cam)
2443
2444         for my_light in ob_lights:
2445                 write_light(my_light)
2446         
2447         for my_mesh in ob_meshes:
2448                 write_mesh(my_mesh)
2449
2450         #for bonename, bone, obname, me, armob in ob_bones:
2451         for my_bone in ob_bones:
2452                 write_bone(my_bone)
2453         
2454         write_camera_default()
2455         
2456         for matname, (mat, tex) in materials:
2457                 write_material(matname, mat) # We only need to have a material per image pair, but no need to write any image info into the material (dumb fbx standard)
2458         
2459         # each texture uses a video, odd
2460         for texname, tex in textures:
2461                 write_video(texname, tex)
2462         i = 0
2463         for texname, tex in textures:
2464                 write_texture(texname, tex, i)
2465                 i+=1
2466         
2467         for groupname, group in groups:
2468                 write_group(groupname)
2469         
2470         # NOTE - c4d and motionbuilder dont need normalized weights, but deep-exploration 5 does and (max?) do.
2471         
2472         # Write armature modifiers
2473         # TODO - add another MODEL? - because of this skin definition.
2474         for my_mesh in ob_meshes:
2475                 if my_mesh.fbxArm:
2476                         write_deformer_skin(my_mesh.fbxName)
2477                         
2478                         # Get normalized weights for temorary use
2479                         if my_mesh.fbxBoneParent:
2480                                 weights = None
2481                         else:
2482                                 weights = meshNormalizedWeights(my_mesh.blenObject)
2483 #                               weights = meshNormalizedWeights(my_mesh.blenData)
2484                         
2485                         #for bonename, bone, obname, bone_mesh, armob in ob_bones:
2486                         for my_bone in ob_bones:
2487                                 if me in iter(my_bone.blenMeshes.values()):
2488                                         write_sub_deformer_skin(my_mesh, my_bone, weights)
2489         
2490         # Write pose's really weired, only needed when an armature and mesh are used together
2491         # each by themselves dont need pose data. for now only pose meshes and bones
2492         
2493         file.write('''
2494         Pose: "Pose::BIND_POSES", "BindPose" {
2495                 Type: "BindPose"
2496                 Version: 100
2497                 Properties60:  {
2498                 }
2499                 NbPoseNodes: ''')
2500         file.write(str(len(pose_items)))
2501         
2502
2503         for fbxName, matrix in pose_items:
2504                 file.write('\n\t\tPoseNode:  {')
2505                 file.write('\n\t\t\tNode: "Model::%s"' % fbxName )
2506                 if matrix:              file.write('\n\t\t\tMatrix: %s' % mat4x4str(matrix))
2507                 else:                   file.write('\n\t\t\tMatrix: %s' % mat4x4str(mtx4_identity))
2508                 file.write('\n\t\t}')
2509         
2510         file.write('\n\t}')
2511         
2512         
2513         # Finish Writing Objects
2514         # Write global settings
2515         file.write('''
2516         GlobalSettings:  {
2517                 Version: 1000
2518                 Properties60:  {
2519                         Property: "UpAxis", "int", "",1
2520                         Property: "UpAxisSign", "int", "",1
2521                         Property: "FrontAxis", "int", "",2
2522                         Property: "FrontAxisSign", "int", "",1
2523                         Property: "CoordAxis", "int", "",0
2524                         Property: "CoordAxisSign", "int", "",1
2525                         Property: "UnitScaleFactor", "double", "",100
2526                 }
2527         }
2528 ''')    
2529         file.write('}')
2530         
2531         file.write('''
2532
2533 ; Object relations
2534 ;------------------------------------------------------------------
2535
2536 Relations:  {''')
2537
2538         file.write('\n\tModel: "Model::blend_root", "Null" {\n\t}')
2539
2540         for my_null in ob_null:
2541                 file.write('\n\tModel: "Model::%s", "Null" {\n\t}' % my_null.fbxName)
2542
2543         for my_arm in ob_arms:
2544                 file.write('\n\tModel: "Model::%s", "Null" {\n\t}' % my_arm.fbxName)
2545
2546         for my_mesh in ob_meshes:
2547                 file.write('\n\tModel: "Model::%s", "Mesh" {\n\t}' % my_mesh.fbxName)
2548
2549         # TODO - limbs can have the same name for multiple armatures, should prefix.
2550         #for bonename, bone, obname, me, armob in ob_bones:
2551         for my_bone in ob_bones:
2552                 file.write('\n\tModel: "Model::%s", "Limb" {\n\t}' % my_bone.fbxName)
2553         
2554         for my_cam in ob_cameras:
2555                 file.write('\n\tModel: "Model::%s", "Camera" {\n\t}' % my_cam.fbxName)
2556         
2557         for my_light in ob_lights:
2558                 file.write('\n\tModel: "Model::%s", "Light" {\n\t}' % my_light.fbxName)
2559         
2560         file.write('''
2561         Model: "Model::Producer Perspective", "Camera" {
2562         }
2563         Model: "Model::Producer Top", "Camera" {
2564         }
2565         Model: "Model::Producer Bottom", "Camera" {
2566         }
2567         Model: "Model::Producer Front", "Camera" {
2568         }
2569         Model: "Model::Producer Back", "Camera" {
2570         }
2571         Model: "Model::Producer Right", "Camera" {
2572         }
2573         Model: "Model::Producer Left", "Camera" {
2574         }
2575         Model: "Model::Camera Switcher", "CameraSwitcher" {
2576         }''')
2577         
2578         for matname, (mat, tex) in materials:
2579                 file.write('\n\tMaterial: "Material::%s", "" {\n\t}' % matname)
2580
2581         if textures:
2582                 for texname, tex in textures:
2583                         file.write('\n\tTexture: "Texture::%s", "TextureVideoClip" {\n\t}' % texname)
2584                 for texname, tex in textures:
2585                         file.write('\n\tVideo: "Video::%s", "Clip" {\n\t}' % texname)
2586
2587         # deformers - modifiers
2588         for my_mesh in ob_meshes:
2589                 if my_mesh.fbxArm:
2590                         file.write('\n\tDeformer: "Deformer::Skin %s", "Skin" {\n\t}' % my_mesh.fbxName)
2591         
2592         #for bonename, bone, obname, me, armob in ob_bones:
2593         for my_bone in ob_bones:
2594                 for fbxMeshObName in my_bone.blenMeshes: # .keys() - fbxMeshObName
2595                         # is this bone effecting a mesh?
2596                         file.write('\n\tDeformer: "SubDeformer::Cluster %s %s", "Cluster" {\n\t}' % (fbxMeshObName, my_bone.fbxName))
2597         
2598         # This should be at the end
2599         # file.write('\n\tPose: "Pose::BIND_POSES", "BindPose" {\n\t}')
2600         
2601         for groupname, group in groups:
2602                 file.write('\n\tGroupSelection: "GroupSelection::%s", "Default" {\n\t}' % groupname)
2603         
2604         file.write('\n}')
2605         file.write('''
2606
2607 ; Object connections
2608 ;------------------------------------------------------------------
2609
2610 Connections:  {''')
2611         
2612         # NOTE - The FBX SDK dosnt care about the order but some importers DO!
2613         # for instance, defining the material->mesh connection
2614         # before the mesh->blend_root crashes cinema4d
2615         
2616
2617         # write the fake root node
2618         file.write('\n\tConnect: "OO", "Model::blend_root", "Model::Scene"')
2619         
2620         for ob_generic in ob_all_typegroups: # all blender 'Object's we support
2621                 for my_ob in ob_generic:
2622                         if my_ob.fbxParent:
2623                                 file.write('\n\tConnect: "OO", "Model::%s", "Model::%s"' % (my_ob.fbxName, my_ob.fbxParent.fbxName))
2624                         else:
2625                                 file.write('\n\tConnect: "OO", "Model::%s", "Model::blend_root"' % my_ob.fbxName)
2626         
2627         if materials:
2628                 for my_mesh in ob_meshes:
2629                         # Connect all materials to all objects, not good form but ok for now.
2630                         for mat, tex in my_mesh.blenMaterials:
2631                                 if mat: mat_name = mat.name
2632                                 else:   mat_name = None
2633                                 
2634                                 if tex: tex_name = tex.name
2635                                 else:   tex_name = None
2636                                 
2637                                 file.write('\n\tConnect: "OO", "Material::%s", "Model::%s"' % (sane_name_mapping_mat[mat_name, tex_name], my_mesh.fbxName))
2638         
2639         if textures:
2640                 for my_mesh in ob_meshes:
2641                         if my_mesh.blenTextures:
2642                                 # file.write('\n\tConnect: "OO", "Texture::_empty_", "Model::%s"' % my_mesh.fbxName)
2643                                 for tex in my_mesh.blenTextures:
2644                                         if tex:
2645                                                 file.write('\n\tConnect: "OO", "Texture::%s", "Model::%s"' % (sane_name_mapping_tex[tex.name], my_mesh.fbxName))
2646                 
2647                 for texname, tex in textures:
2648                         file.write('\n\tConnect: "OO", "Video::%s", "Texture::%s"' % (texname, texname))
2649         
2650         for my_mesh in ob_meshes:
2651                 if my_mesh.fbxArm:
2652                         file.write('\n\tConnect: "OO", "Deformer::Skin %s", "Model::%s"' % (my_mesh.fbxName, my_mesh.fbxName))
2653         
2654         #for bonename, bone, obname, me, armob in ob_bones:
2655         for my_bone in ob_bones:
2656                 for fbxMeshObName in my_bone.blenMeshes: # .keys()
2657                         file.write('\n\tConnect: "OO", "SubDeformer::Cluster %s %s", "Deformer::Skin %s"' % (fbxMeshObName, my_bone.fbxName, fbxMeshObName))
2658         
2659         # limbs -> deformers
2660         # for bonename, bone, obname, me, armob in ob_bones:
2661         for my_bone in ob_bones:
2662                 for fbxMeshObName in my_bone.blenMeshes: # .keys()
2663                         file.write('\n\tConnect: "OO", "Model::%s", "SubDeformer::Cluster %s %s"' % (my_bone.fbxName, fbxMeshObName, my_bone.fbxName))
2664         
2665         
2666         #for bonename, bone, obname, me, armob in ob_bones:
2667         for my_bone in ob_bones:
2668                 # Always parent to armature now
2669                 if my_bone.parent:
2670                         file.write('\n\tConnect: "OO", "Model::%s", "Model::%s"' % (my_bone.fbxName, my_bone.parent.fbxName) )
2671                 else:
2672                         # the armature object is written as an empty and all root level bones connect to it
2673                         file.write('\n\tConnect: "OO", "Model::%s", "Model::%s"' % (my_bone.fbxName, my_bone.fbxArm.fbxName) )
2674         
2675         # groups
2676         if groups:
2677                 for ob_generic in ob_all_typegroups:
2678                         for ob_base in ob_generic:
2679                                 for fbxGroupName in ob_base.fbxGroupNames:
2680                                         file.write('\n\tConnect: "OO", "Model::%s", "GroupSelection::%s"' % (ob_base.fbxName, fbxGroupName))
2681         
2682         for my_arm in ob_arms:
2683                 file.write('\n\tConnect: "OO", "Model::%s", "Model::blend_root"' % my_arm.fbxName)
2684         
2685         file.write('\n}')
2686         
2687         
2688         # Needed for scene footer as well as animation
2689         render = sce.render_data
2690 #       render = sce.render
2691         
2692         # from the FBX sdk
2693         #define KTIME_ONE_SECOND        KTime (K_LONGLONG(46186158000))
2694         def fbx_time(t):
2695                 # 0.5 + val is the same as rounding.
2696                 return int(0.5 + ((t/fps) * 46186158000))
2697         
2698         fps = float(render.fps) 
2699         start = sce.start_frame
2700 #       start = render.sFrame
2701         end =   sce.end_frame
2702 #       end =   render.eFrame
2703         if end < start: start, end = end, start
2704         if start==end: ANIM_ENABLE = False
2705         
2706         # animations for these object types
2707         ob_anim_lists = ob_bones, ob_meshes, ob_null, ob_cameras, ob_lights, ob_arms
2708         
2709         if ANIM_ENABLE and [tmp for tmp in ob_anim_lists if tmp]:
2710                 
2711                 frame_orig = sce.current_frame
2712 #               frame_orig = Blender.Get('curframe')
2713                 
2714                 if ANIM_OPTIMIZE:
2715                         ANIM_OPTIMIZE_PRECISSION_FLOAT = 0.1 ** ANIM_OPTIMIZE_PRECISSION
2716                 
2717                 # default action, when no actions are avaioable
2718                 tmp_actions = [None] # None is the default action
2719                 blenActionDefault = None
2720                 action_lastcompat = None
2721
2722                 # instead of tagging
2723                 tagged_actions = []
2724                 
2725                 if ANIM_ACTION_ALL:
2726 #                       bpy.data.actions.tag = False
2727                         tmp_actions = list(bpy.data.actions)
2728                         
2729                         
2730                         # find which actions are compatible with the armatures
2731                         # blenActions is not yet initialized so do it now.
2732                         tmp_act_count = 0
2733                         for my_arm in ob_arms:
2734                                 
2735                                 # get the default name
2736                                 if not blenActionDefault:
2737                                         blenActionDefault = my_arm.blenAction
2738                                 
2739                                 arm_bone_names = set([my_bone.blenName for my_bone in my_arm.fbxBones])
2740                                 
2741                                 for action in tmp_actions:
2742
2743                                         action_chan_names = arm_bone_names.intersection( set([g.name for g in action.groups]) )
2744 #                                       action_chan_names = arm_bone_names.intersection( set(action.getChannelNames()) )
2745                                         
2746                                         if action_chan_names: # at least one channel matches.
2747                                                 my_arm.blenActionList.append(action)
2748                                                 tagged_actions.append(action.name)
2749 #                                               action.tag = True
2750                                                 tmp_act_count += 1
2751                                                 
2752                                                 # incase there is no actions applied to armatures
2753                                                 action_lastcompat = action