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