79a224d63c39b7e5b75f85d32226b6d167679883
[blender.git] / release / scripts / export_obj.py
1 #!BPY
2
3 """
4 Name: 'Wavefront (.obj)...'
5 Blender: 248
6 Group: 'Export'
7 Tooltip: 'Save a Wavefront OBJ File'
8 """
9
10 __author__ = "Campbell Barton, Jiri Hnidek"
11 __url__ = ['http://wiki.blender.org/index.php/Scripts/Manual/Export/wavefront_obj', 'www.blender.org', 'blenderartists.org']
12 __version__ = "1.2"
13
14 __bpydoc__ = """\
15 This script is an exporter to OBJ file format.
16
17 Usage:
18
19 Select the objects you wish to export and run this script from "File->Export" menu.
20 Selecting the default options from the popup box will be good in most cases.
21 All objects that can be represented as a mesh (mesh, curve, metaball, surface, text3d)
22 will be exported as mesh data.
23 """
24
25
26 # --------------------------------------------------------------------------
27 # OBJ Export v1.1 by Campbell Barton (AKA Ideasman)
28 # --------------------------------------------------------------------------
29 # ***** BEGIN GPL LICENSE BLOCK *****
30 #
31 # This program is free software; you can redistribute it and/or
32 # modify it under the terms of the GNU General Public License
33 # as published by the Free Software Foundation; either version 2
34 # of the License, or (at your option) any later version.
35 #
36 # This program is distributed in the hope that it will be useful,
37 # but WITHOUT ANY WARRANTY; without even the implied warranty of
38 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
39 # GNU General Public License for more details.
40 #
41 # You should have received a copy of the GNU General Public License
42 # along with this program; if not, write to the Free Software Foundation,
43 # Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
44 #
45 # ***** END GPL LICENCE BLOCK *****
46 # --------------------------------------------------------------------------
47
48
49 import Blender
50 from Blender import Mesh, Scene, Window, sys, Image, Draw
51 import BPyMesh
52 import BPyObject
53 import BPySys
54 import BPyMessages
55
56 # Returns a tuple - path,extension.
57 # 'hello.obj' >  ('hello', '.obj')
58 def splitExt(path):
59         dotidx = path.rfind('.')
60         if dotidx == -1:
61                 return path, ''
62         else:
63                 return path[:dotidx], path[dotidx:] 
64
65 def fixName(name):
66         if name == None:
67                 return 'None'
68         else:
69                 return name.replace(' ', '_')
70
71 # A Dict of Materials
72 # (material.name, image.name):matname_imagename # matname_imagename has gaps removed.
73 MTL_DICT = {} 
74
75 def write_mtl(filename):
76         
77         world = Blender.World.GetCurrent()
78         if world:
79                 worldAmb = world.getAmb()
80         else:
81                 worldAmb = (0,0,0) # Default value
82         
83         file = open(filename, "w")
84         file.write('# Blender3D MTL File: %s\n' % Blender.Get('filename').split('\\')[-1].split('/')[-1])
85         file.write('# Material Count: %i\n' % len(MTL_DICT))
86         # Write material/image combinations we have used.
87         for key, (mtl_mat_name, mat, img) in MTL_DICT.iteritems():
88                 
89                 # Get the Blender data for the material and the image.
90                 # Having an image named None will make a bug, dont do it :)
91                 
92                 file.write('newmtl %s\n' % mtl_mat_name) # Define a new material: matname_imgname
93                 
94                 if mat:
95                         file.write('Ns %.6f\n' % ((mat.getHardness()-1) * 1.9607843137254901) ) # Hardness, convert blenders 1-511 to MTL's 
96                         file.write('Ka %.6f %.6f %.6f\n' %  tuple([c*mat.amb for c in worldAmb])  ) # Ambient, uses mirror colour,
97                         file.write('Kd %.6f %.6f %.6f\n' % tuple([c*mat.ref for c in mat.rgbCol]) ) # Diffuse
98                         file.write('Ks %.6f %.6f %.6f\n' % tuple([c*mat.spec for c in mat.specCol]) ) # Specular
99                         file.write('Ni %.6f\n' % mat.IOR) # Refraction index
100                         file.write('d %.6f\n' % mat.alpha) # Alpha (obj uses 'd' for dissolve)
101                         
102                         # 0 to disable lighting, 1 for ambient & diffuse only (specular color set to black), 2 for full lighting.
103                         if mat.getMode() & Blender.Material.Modes['SHADELESS']:
104                                 file.write('illum 0\n') # ignore lighting
105                         elif mat.getSpec() == 0:
106                                 file.write('illum 1\n') # no specular.
107                         else:
108                                 file.write('illum 2\n') # light normaly 
109                 
110                 else:
111                         #write a dummy material here?
112                         file.write('Ns 0\n')
113                         file.write('Ka %.6f %.6f %.6f\n' %  tuple([c for c in worldAmb])  ) # Ambient, uses mirror colour,
114                         file.write('Kd 0.8 0.8 0.8\n')
115                         file.write('Ks 0.8 0.8 0.8\n')
116                         file.write('d 1\n') # No alpha
117                         file.write('illum 2\n') # light normaly
118                 
119                 # Write images!
120                 if img:  # We have an image on the face!
121                         file.write('map_Kd %s\n' % img.filename.split('\\')[-1].split('/')[-1]) # Diffuse mapping image                 
122                 
123                 elif not mat: # No face image. if we havea material search for MTex image.
124                         for mtex in mat.getTextures():
125                                 if mtex and mtex.tex.type == Blender.Texture.Types.IMAGE:
126                                         try:
127                                                 filename = mtex.tex.image.filename.split('\\')[-1].split('/')[-1]
128                                                 file.write('map_Kd %s\n' % filename) # Diffuse mapping image
129                                                 break
130                                         except:
131                                                 # Texture has no image though its an image type, best ignore.
132                                                 pass
133                 
134                 file.write('\n\n')
135         
136         file.close()
137
138 def copy_file(source, dest):
139         file = open(source, 'rb')
140         data = file.read()
141         file.close()
142         
143         file = open(dest, 'wb')
144         file.write(data)
145         file.close()
146
147
148 def copy_images(dest_dir):
149         if dest_dir[-1] != sys.sep:
150                 dest_dir += sys.sep
151         
152         # Get unique image names
153         uniqueImages = {}
154         for matname, mat, image in MTL_DICT.itervalues(): # Only use image name
155                 # Get Texface images
156                 if image:
157                         uniqueImages[image] = image # Should use sets here. wait until Python 2.4 is default.
158                 
159                 # Get MTex images
160                 if mat:
161                         for mtex in mat.getTextures():
162                                 if mtex and mtex.tex.type == Blender.Texture.Types.IMAGE:
163                                         image_tex = mtex.tex.image
164                                         if image_tex:
165                                                 try:
166                                                         uniqueImages[image_tex] = image_tex
167                                                 except:
168                                                         pass
169         
170         # Now copy images
171         copyCount = 0
172         
173         for bImage in uniqueImages.itervalues():
174                 image_path = sys.expandpath(bImage.filename)
175                 if sys.exists(image_path):
176                         # Make a name for the target path.
177                         dest_image_path = dest_dir + image_path.split('\\')[-1].split('/')[-1]
178                         if not sys.exists(dest_image_path): # Image isnt alredy there
179                                 print '\tCopying "%s" > "%s"' % (image_path, dest_image_path)
180                                 copy_file(image_path, dest_image_path)
181                                 copyCount+=1
182         print '\tCopied %d images' % copyCount
183
184 def write(filename, objects,\
185 EXPORT_TRI=False,  EXPORT_EDGES=False,  EXPORT_NORMALS=False,  EXPORT_NORMALS_HQ=False,\
186 EXPORT_UV=True,  EXPORT_MTL=True,  EXPORT_COPY_IMAGES=False,\
187 EXPORT_APPLY_MODIFIERS=True, EXPORT_ROTX90=True, EXPORT_BLEN_OBS=True,\
188 EXPORT_GROUP_BY_OB=False,  EXPORT_GROUP_BY_MAT=False, EXPORT_KEEP_VERT_ORDER=False):
189         '''
190         Basic write function. The context and options must be alredy set
191         This can be accessed externaly
192         eg.
193         write( 'c:\\test\\foobar.obj', Blender.Object.GetSelected() ) # Using default options.
194         '''
195         
196         def veckey3d(v):
197                 return round(v.x, 6), round(v.y, 6), round(v.z, 6)
198                 
199         def veckey2d(v):
200                 return round(v.x, 6), round(v.y, 6)
201         
202         print 'OBJ Export path: "%s"' % filename
203         temp_mesh_name = '~tmp-mesh'
204
205         time1 = sys.time()
206         scn = Scene.GetCurrent()
207
208         file = open(filename, "w")
209         
210         # Write Header
211         file.write('# Blender3D v%s OBJ File: %s\n' % (Blender.Get('version'), Blender.Get('filename').split('/')[-1].split('\\')[-1] ))
212         file.write('# www.blender3d.org\n')
213
214         # Tell the obj file what material file to use.
215         if EXPORT_MTL:
216                 mtlfilename = '%s.mtl' % '.'.join(filename.split('.')[:-1])
217                 file.write('mtllib %s\n' % ( mtlfilename.split('\\')[-1].split('/')[-1] ))
218         
219         # Get the container mesh. - used for applying modifiers and non mesh objects.
220         containerMesh = meshName = tempMesh = None
221         for meshName in Blender.NMesh.GetNames():
222                 if meshName.startswith(temp_mesh_name):
223                         tempMesh = Mesh.Get(meshName)
224                         if not tempMesh.users:
225                                 containerMesh = tempMesh
226         if not containerMesh:
227                 containerMesh = Mesh.New(temp_mesh_name)
228         
229         if EXPORT_ROTX90:
230                 mat_xrot90= Blender.Mathutils.RotationMatrix(-90, 4, 'x')
231                 
232         del meshName
233         del tempMesh
234         
235         # Initialize totals, these are updated each object
236         totverts = totuvco = totno = 1
237         
238         face_vert_index = 1
239         
240         globalNormals = {}
241         
242         # Get all meshs
243         for ob_main in objects:
244                 for ob, ob_mat in BPyObject.getDerivedObjects(ob_main):
245                         # Will work for non meshes now! :)
246                         # getMeshFromObject(ob, container_mesh=None, apply_modifiers=True, vgroups=True, scn=None)
247                         me= BPyMesh.getMeshFromObject(ob, containerMesh, EXPORT_APPLY_MODIFIERS, False, scn)
248                         if not me:
249                                 continue
250                         
251                         if EXPORT_UV:
252                                 faceuv= me.faceUV
253                         else:
254                                 faceuv = False
255                         
256                         # We have a valid mesh
257                         if EXPORT_TRI and me.faces:
258                                 # Add a dummy object to it.
259                                 has_quads = False
260                                 for f in me.faces:
261                                         if len(f) == 4:
262                                                 has_quads = True
263                                                 break
264                                 
265                                 if has_quads:
266                                         oldmode = Mesh.Mode()
267                                         Mesh.Mode(Mesh.SelectModes['FACE'])
268                                         
269                                         me.sel = True
270                                         tempob = scn.objects.new(me)
271                                         me.quadToTriangle(0) # more=0 shortest length
272                                         oldmode = Mesh.Mode(oldmode)
273                                         scn.objects.unlink(tempob)
274                                         
275                                         Mesh.Mode(oldmode)
276                         
277                         # Make our own list so it can be sorted to reduce context switching
278                         faces = [ f for f in me.faces ]
279                         
280                         if EXPORT_EDGES:
281                                 edges = me.edges
282                         else:
283                                 edges = []
284                         
285                         if not (len(faces)+len(edges)+len(me.verts)): # Make sure there is somthing to write
286                                 continue # dont bother with this mesh.
287                         
288                         if EXPORT_ROTX90:
289                                 me.transform(ob_mat*mat_xrot90)
290                         else:
291                                 me.transform(ob_mat)
292                         
293                         # High Quality Normals
294                         if EXPORT_NORMALS and faces:
295                                 if EXPORT_NORMALS_HQ:
296                                         BPyMesh.meshCalcNormals(me)
297                                 else:
298                                         # transforming normals is incorrect
299                                         # when the matrix is scaled,
300                                         # better to recalculate them
301                                         me.calcNormals()
302                         
303                         # # Crash Blender
304                         #materials = me.getMaterials(1) # 1 == will return None in the list.
305                         materials = me.materials
306                         
307                         materialNames = []
308                         materialItems = materials[:]
309                         if materials:
310                                 for mat in materials:
311                                         if mat: # !=None
312                                                 materialNames.append(mat.name)
313                                         else:
314                                                 materialNames.append(None)
315                                 # Cant use LC because some materials are None.
316                                 # materialNames = map(lambda mat: mat.name, materials) # Bug Blender, dosent account for null materials, still broken.  
317                         
318                         # Possible there null materials, will mess up indicies
319                         # but at least it will export, wait until Blender gets fixed.
320                         materialNames.extend((16-len(materialNames)) * [None])
321                         materialItems.extend((16-len(materialItems)) * [None])
322                         
323                         # Sort by Material, then images
324                         # so we dont over context switch in the obj file.
325                         if EXPORT_KEEP_VERT_ORDER:
326                                 pass
327                         elif faceuv:
328                                 try:    faces.sort(key = lambda a: (a.mat, a.image, a.smooth))
329                                 except: faces.sort(lambda a,b: cmp((a.mat, a.image, a.smooth), (b.mat, b.image, b.smooth)))
330                         elif len(materials) > 1:
331                                 try:    faces.sort(key = lambda a: (a.mat, a.smooth))
332                                 except: faces.sort(lambda a,b: cmp((a.mat, a.smooth), (b.mat, b.smooth)))
333                         else:
334                                 # no materials
335                                 try:    faces.sort(key = lambda a: a.smooth)
336                                 except: faces.sort(lambda a,b: cmp(a.smooth, b.smooth))
337                         
338                         # Set the default mat to no material and no image.
339                         contextMat = (0, 0) # Can never be this, so we will label a new material teh first chance we get.
340                         contextSmooth = None # Will either be true or false,  set bad to force initialization switch.
341                         
342                         if EXPORT_BLEN_OBS or EXPORT_GROUP_BY_OB:
343                                 name1 = ob.name
344                                 name2 = ob.getData(1)
345                                 if name1 == name2:
346                                         obnamestring = fixName(name1)
347                                 else:
348                                         obnamestring = '%s_%s' % (fixName(name1), fixName(name2))
349                                 
350                                 if EXPORT_BLEN_OBS:
351                                         file.write('o %s\n' % obnamestring) # Write Object name
352                                 else: # if EXPORT_GROUP_BY_OB:
353                                         file.write('g %s\n' % obnamestring)
354                         
355                         
356                         # Vert
357                         for v in me.verts:
358                                 file.write('v %.6f %.6f %.6f\n' % tuple(v.co))
359                         
360                         # UV
361                         if faceuv:
362                                 uv_face_mapping = [[0,0,0,0] for f in faces] # a bit of a waste for tri's :/
363                                 
364                                 uv_dict = {} # could use a set() here
365                                 for f_index, f in enumerate(faces):
366                                         
367                                         for uv_index, uv in enumerate(f.uv):
368                                                 uvkey = veckey2d(uv)
369                                                 try:
370                                                         uv_face_mapping[f_index][uv_index] = uv_dict[uvkey]
371                                                 except:
372                                                         uv_face_mapping[f_index][uv_index] = uv_dict[uvkey] = len(uv_dict)
373                                                         file.write('vt %.6f %.6f\n' % tuple(uv))
374                                 
375                                 uv_unique_count = len(uv_dict)
376                                 del uv, uvkey, uv_dict, f_index, uv_index
377                                 # Only need uv_unique_count and uv_face_mapping
378                         
379                         # NORMAL, Smooth/Non smoothed.
380                         if EXPORT_NORMALS:
381                                 for f in faces:
382                                         if f.smooth:
383                                                 for v in f:
384                                                         noKey = veckey3d(v.no)
385                                                         if not globalNormals.has_key( noKey ):
386                                                                 globalNormals[noKey] = totno
387                                                                 totno +=1
388                                                                 file.write('vn %.6f %.6f %.6f\n' % noKey)
389                                         else:
390                                                 # Hard, 1 normal from the face.
391                                                 noKey = veckey3d(f.no)
392                                                 if not globalNormals.has_key( noKey ):
393                                                         globalNormals[noKey] = totno
394                                                         totno +=1
395                                                         file.write('vn %.6f %.6f %.6f\n' % noKey)
396                         
397                         if not faceuv:
398                                 f_image = None
399                         
400                         for f_index, f in enumerate(faces):
401                                 f_v= f.v
402                                 f_smooth= f.smooth
403                                 f_mat = min(f.mat, len(materialNames)-1)
404                                 if faceuv:
405                                         f_image = f.image
406                                         f_uv= f.uv
407                                 
408                                 # MAKE KEY
409                                 if faceuv and f_image: # Object is always true.
410                                         key = materialNames[f_mat],  f_image.name
411                                 else:
412                                         key = materialNames[f_mat],  None # No image, use None instead.
413                                 
414                                 # CHECK FOR CONTEXT SWITCH
415                                 if key == contextMat:
416                                         pass # Context alredy switched, dont do anythoing
417                                 else:
418                                         if key[0] == None and key[1] == None:
419                                                 # Write a null material, since we know the context has changed.
420                                                 if EXPORT_GROUP_BY_MAT:
421                                                         file.write('g %s_%s\n' % (fixName(ob.name), fixName(ob.getData(1))) ) # can be mat_image or (null)
422                                                 file.write('usemtl (null)\n') # mat, image
423                                                 
424                                         else:
425                                                 mat_data= MTL_DICT.get(key)
426                                                 if not mat_data:
427                                                         # First add to global dict so we can export to mtl
428                                                         # Then write mtl
429                                                         
430                                                         # Make a new names from the mat and image name,
431                                                         # converting any spaces to underscores with fixName.
432                                                         
433                                                         # If none image dont bother adding it to the name
434                                                         if key[1] == None:
435                                                                 mat_data = MTL_DICT[key] = ('%s'%fixName(key[0])), materialItems[f_mat], f_image
436                                                         else:
437                                                                 mat_data = MTL_DICT[key] = ('%s_%s' % (fixName(key[0]), fixName(key[1]))), materialItems[f_mat], f_image
438                                                 
439                                                 if EXPORT_GROUP_BY_MAT:
440                                                         file.write('g %s_%s_%s\n' % (fixName(ob.name), fixName(ob.getData(1)), mat_data[0]) ) # can be mat_image or (null)
441                                                 file.write('usemtl %s\n' % mat_data[0]) # can be mat_image or (null)
442                                         
443                                 contextMat = key
444                                 if f_smooth != contextSmooth:
445                                         if f_smooth: # on now off
446                                                 file.write('s 1\n')
447                                                 contextSmooth = f_smooth
448                                         else: # was off now on
449                                                 file.write('s off\n')
450                                                 contextSmooth = f_smooth
451                                 
452                                 file.write('f')
453                                 if faceuv:
454                                         if EXPORT_NORMALS:
455                                                 if f_smooth: # Smoothed, use vertex normals
456                                                         for vi, v in enumerate(f_v):
457                                                                 file.write( ' %d/%d/%d' % (\
458                                                                   v.index+totverts,\
459                                                                   totuvco + uv_face_mapping[f_index][vi],\
460                                                                   globalNormals[ veckey3d(v.no) ])) # vert, uv, normal
461                                                         
462                                                 else: # No smoothing, face normals
463                                                         no = globalNormals[ veckey3d(f.no) ]
464                                                         for vi, v in enumerate(f_v):
465                                                                 file.write( ' %d/%d/%d' % (\
466                                                                   v.index+totverts,\
467                                                                   totuvco + uv_face_mapping[f_index][vi],\
468                                                                   no)) # vert, uv, normal
469                                         
470                                         else: # No Normals
471                                                 for vi, v in enumerate(f_v):
472                                                         file.write( ' %d/%d' % (\
473                                                           v.index+totverts,\
474                                                           totuvco + uv_face_mapping[f_index][vi])) # vert, uv
475                                         
476                                         face_vert_index += len(f_v)
477                                 
478                                 else: # No UV's
479                                         if EXPORT_NORMALS:
480                                                 if f_smooth: # Smoothed, use vertex normals
481                                                         for v in f_v:
482                                                                 file.write( ' %d//%d' % (\
483                                                                   v.index+totverts,\
484                                                                   globalNormals[ veckey3d(v.no) ]))
485                                                 else: # No smoothing, face normals
486                                                         no = globalNormals[ veckey3d(f.no) ]
487                                                         for v in f_v:
488                                                                 file.write( ' %d//%d' % (\
489                                                                   v.index+totverts,\
490                                                                   no))
491                                         else: # No Normals
492                                                 for v in f_v:
493                                                         file.write( ' %d' % (\
494                                                           v.index+totverts))
495                                                 
496                                 file.write('\n')
497                         
498                         # Write edges.
499                         if EXPORT_EDGES:
500                                 LOOSE= Mesh.EdgeFlags.LOOSE
501                                 for ed in edges:
502                                         if ed.flag & LOOSE:
503                                                 file.write('f %d %d\n' % (ed.v1.index+totverts, ed.v2.index+totverts))
504                                 
505                         # Make the indicies global rather then per mesh
506                         totverts += len(me.verts)
507                         if faceuv:
508                                 totuvco += uv_unique_count
509                         me.verts= None
510         file.close()
511         
512         
513         # Now we have all our materials, save them
514         if EXPORT_MTL:
515                 write_mtl(mtlfilename)
516         if EXPORT_COPY_IMAGES:
517                 dest_dir = filename
518                 # Remove chars until we are just the path.
519                 while dest_dir and dest_dir[-1] not in '\\/':
520                         dest_dir = dest_dir[:-1]
521                 if dest_dir:
522                         copy_images(dest_dir)
523                 else:
524                         print '\tError: "%s" could not be used as a base for an image path.' % filename
525         
526         print "OBJ Export time: %.2f" % (sys.time() - time1)
527         
528         
529
530 def write_ui(filename):
531         
532         if not filename.lower().endswith('.obj'):
533                 filename += '.obj'
534         
535         if not BPyMessages.Warning_SaveOver(filename):
536                 return
537         
538         global EXPORT_APPLY_MODIFIERS, EXPORT_ROTX90, EXPORT_TRI, EXPORT_EDGES,\
539                 EXPORT_NORMALS, EXPORT_NORMALS_HQ, EXPORT_UV,\
540                 EXPORT_MTL, EXPORT_SEL_ONLY, EXPORT_ALL_SCENES,\
541                 EXPORT_ANIMATION, EXPORT_COPY_IMAGES, EXPORT_BLEN_OBS,\
542                 EXPORT_GROUP_BY_OB, EXPORT_GROUP_BY_MAT, EXPORT_KEEP_VERT_ORDER
543         
544         EXPORT_APPLY_MODIFIERS = Draw.Create(0)
545         EXPORT_ROTX90 = Draw.Create(1)
546         EXPORT_TRI = Draw.Create(0)
547         EXPORT_EDGES = Draw.Create(1)
548         EXPORT_NORMALS = Draw.Create(0)
549         EXPORT_NORMALS_HQ = Draw.Create(0)
550         EXPORT_UV = Draw.Create(1)
551         EXPORT_MTL = Draw.Create(1)
552         EXPORT_SEL_ONLY = Draw.Create(1)
553         EXPORT_ALL_SCENES = Draw.Create(0)
554         EXPORT_ANIMATION = Draw.Create(0)
555         EXPORT_COPY_IMAGES = Draw.Create(0)
556         EXPORT_BLEN_OBS = Draw.Create(0)
557         EXPORT_GROUP_BY_OB = Draw.Create(0)
558         EXPORT_GROUP_BY_MAT = Draw.Create(0)
559         EXPORT_KEEP_VERT_ORDER = Draw.Create(1)
560         
561         # Old UI
562         '''
563         # removed too many options are bad!
564         
565         # Get USER Options
566         pup_block = [\
567         ('Context...'),\
568         ('Selection Only', EXPORT_SEL_ONLY, 'Only export objects in visible selection. Else export whole scene.'),\
569         ('All Scenes', EXPORT_ALL_SCENES, 'Each scene as a separate OBJ file.'),\
570         ('Animation', EXPORT_ANIMATION, 'Each frame as a numbered OBJ file.'),\
571         ('Object Prefs...'),\
572         ('Apply Modifiers', EXPORT_APPLY_MODIFIERS, 'Use transformed mesh data from each object. May break vert order for morph targets.'),\
573         ('Rotate X90', EXPORT_ROTX90 , 'Rotate on export so Blenders UP is translated into OBJs UP'),\
574         ('Keep Vert Order', EXPORT_KEEP_VERT_ORDER, 'Keep vert and face order, disables some other options.'),\
575         ('Extra Data...'),\
576         ('Edges', EXPORT_EDGES, 'Edges not connected to faces.'),\
577         ('Normals', EXPORT_NORMALS, 'Export vertex normal data (Ignored on import).'),\
578         ('High Quality Normals', EXPORT_NORMALS_HQ, 'Calculate high quality normals for rendering.'),\
579         ('UVs', EXPORT_UV, 'Export texface UV coords.'),\
580         ('Materials', EXPORT_MTL, 'Write a separate MTL file with the OBJ.'),\
581         ('Copy Images', EXPORT_COPY_IMAGES, 'Copy image files to the export directory, never overwrite.'),\
582         ('Triangulate', EXPORT_TRI, 'Triangulate quads.'),\
583         ('Grouping...'),\
584         ('Objects', EXPORT_BLEN_OBS, 'Export blender objects as "OBJ objects".'),\
585         ('Object Groups', EXPORT_GROUP_BY_OB, 'Export blender objects as "OBJ Groups".'),\
586         ('Material Groups', EXPORT_GROUP_BY_MAT, 'Group by materials.'),\
587         ]
588         
589         if not Draw.PupBlock('Export...', pup_block):
590                 return
591         '''
592         
593         # BEGIN ALTERNATIVE UI *******************
594         if True: 
595                 
596                 EVENT_NONE = 0
597                 EVENT_EXIT = 1
598                 EVENT_REDRAW = 2
599                 EVENT_EXPORT = 3
600                 
601                 GLOBALS = {}
602                 GLOBALS['EVENT'] = EVENT_REDRAW
603                 #GLOBALS['MOUSE'] = Window.GetMouseCoords()
604                 GLOBALS['MOUSE'] = [i/2 for i in Window.GetScreenSize()]
605                 
606                 def obj_ui_set_event(e,v):
607                         GLOBALS['EVENT'] = e
608                 
609                 def do_split(e,v):
610                         global EXPORT_BLEN_OBS, EXPORT_GROUP_BY_OB, EXPORT_GROUP_BY_MAT, EXPORT_APPLY_MODIFIERS, KEEP_VERT_ORDER
611                         if EXPORT_BLEN_OBS.val or EXPORT_GROUP_BY_OB.val or EXPORT_GROUP_BY_MAT.val or EXPORT_APPLY_MODIFIERS.val:
612                                 EXPORT_KEEP_VERT_ORDER.val = 0
613                         else:
614                                 EXPORT_KEEP_VERT_ORDER.val = 1
615                         
616                 def do_vertorder(e,v):
617                         global EXPORT_BLEN_OBS, EXPORT_GROUP_BY_OB, EXPORT_GROUP_BY_MAT, EXPORT_APPLY_MODIFIERS, KEEP_VERT_ORDER
618                         if EXPORT_KEEP_VERT_ORDER.val:
619                                 EXPORT_BLEN_OBS.val = EXPORT_GROUP_BY_OB.val = EXPORT_GROUP_BY_MAT.val = EXPORT_APPLY_MODIFIERS.val = 0
620                         else:
621                                 if not (EXPORT_BLEN_OBS.val or EXPORT_GROUP_BY_OB.val or EXPORT_GROUP_BY_MAT.val or EXPORT_APPLY_MODIFIERS.val):
622                                         EXPORT_KEEP_VERT_ORDER.val = 1
623                         
624                 def do_help(e,v):
625                         url = __url__[0]
626                         print 'Trying to open web browser with documentation at this address...'
627                         print '\t' + url
628                         
629                         try:
630                                 import webbrowser
631                                 webbrowser.open(url)
632                         except:
633                                 print '...could not open a browser window.'
634                 
635                 def obj_ui():
636                         ui_x, ui_y = GLOBALS['MOUSE']
637                         
638                         # Center based on overall pup size
639                         ui_x -= 165
640                         ui_y -= 110
641                         
642                         global EXPORT_APPLY_MODIFIERS, EXPORT_ROTX90, EXPORT_TRI, EXPORT_EDGES,\
643                                 EXPORT_NORMALS, EXPORT_NORMALS_HQ, EXPORT_UV,\
644                                 EXPORT_MTL, EXPORT_SEL_ONLY, EXPORT_ALL_SCENES,\
645                                 EXPORT_ANIMATION, EXPORT_COPY_IMAGES, EXPORT_BLEN_OBS,\
646                                 EXPORT_GROUP_BY_OB, EXPORT_GROUP_BY_MAT, EXPORT_KEEP_VERT_ORDER
647
648                         Draw.Label('Context...', ui_x+9, ui_y+209, 220, 20)
649                         Draw.BeginAlign()
650                         EXPORT_SEL_ONLY = Draw.Toggle('Selection Only', EVENT_NONE, ui_x+9, ui_y+189, 110, 20, EXPORT_SEL_ONLY.val, 'Only export objects in visible selection. Else export whole scene.')
651                         EXPORT_ALL_SCENES = Draw.Toggle('All Scenes', EVENT_NONE, ui_x+119, ui_y+189, 110, 20, EXPORT_ALL_SCENES.val, 'Each scene as a separate OBJ file.')
652                         EXPORT_ANIMATION = Draw.Toggle('Animation', EVENT_NONE, ui_x+229, ui_y+189, 110, 20, EXPORT_ANIMATION.val, 'Each frame as a numbered OBJ file.')
653                         Draw.EndAlign()
654                         
655                         
656                         Draw.Label('Output Options...', ui_x+9, ui_y+159, 220, 20)
657                         Draw.BeginAlign()
658                         EXPORT_APPLY_MODIFIERS = Draw.Toggle('Apply Modifiers', EVENT_REDRAW, ui_x+9, ui_y+140, 110, 20, EXPORT_APPLY_MODIFIERS.val, 'Use transformed mesh data from each object. May break vert order for morph targets.', do_split)
659                         EXPORT_ROTX90 = Draw.Toggle('Rotate X90', EVENT_NONE, ui_x+119, ui_y+140, 110, 20, EXPORT_ROTX90.val, 'Rotate on export so Blenders UP is translated into OBJs UP')
660                         EXPORT_COPY_IMAGES = Draw.Toggle('Copy Images', EVENT_NONE, ui_x+229, ui_y+140, 110, 20, EXPORT_COPY_IMAGES.val, 'Copy image files to the export directory, never overwrite.')
661                         Draw.EndAlign()
662                         
663                         
664                         Draw.Label('Export...', ui_x+9, ui_y+109, 220, 20)
665                         Draw.BeginAlign()
666                         EXPORT_EDGES = Draw.Toggle('Edges', EVENT_NONE, ui_x+9, ui_y+90, 50, 20, EXPORT_EDGES.val, 'Edges not connected to faces.')
667                         EXPORT_TRI = Draw.Toggle('Triangulate', EVENT_NONE, ui_x+59, ui_y+90, 70, 20, EXPORT_TRI.val, 'Triangulate quads.')
668                         Draw.EndAlign()
669                         Draw.BeginAlign()
670                         EXPORT_MTL = Draw.Toggle('Materials', EVENT_NONE, ui_x+139, ui_y+90, 70, 20, EXPORT_MTL.val, 'Write a separate MTL file with the OBJ.')
671                         EXPORT_UV = Draw.Toggle('UVs', EVENT_NONE, ui_x+209, ui_y+90, 31, 20, EXPORT_UV.val, 'Export texface UV coords.')
672                         Draw.EndAlign()
673                         Draw.BeginAlign()
674                         EXPORT_NORMALS = Draw.Toggle('Normals', EVENT_NONE, ui_x+250, ui_y+90, 59, 20, EXPORT_NORMALS.val, 'Export vertex normal data (Ignored on import).')
675                         EXPORT_NORMALS_HQ = Draw.Toggle('HQ', EVENT_NONE, ui_x+309, ui_y+90, 31, 20, EXPORT_NORMALS_HQ.val, 'Calculate high quality normals for rendering.')
676                         Draw.EndAlign()
677                         
678                         
679                         Draw.Label('Blender Objects as OBJ:', ui_x+9, ui_y+59, 220, 20)
680                         Draw.BeginAlign()
681                         EXPORT_BLEN_OBS = Draw.Toggle('Objects', EVENT_REDRAW, ui_x+9, ui_y+39, 60, 20, EXPORT_BLEN_OBS.val, 'Export blender objects as "OBJ objects".', do_split)
682                         EXPORT_GROUP_BY_OB = Draw.Toggle('Groups', EVENT_REDRAW, ui_x+69, ui_y+39, 60, 20, EXPORT_GROUP_BY_OB.val, 'Export blender objects as "OBJ Groups".', do_split)
683                         EXPORT_GROUP_BY_MAT = Draw.Toggle('Material Groups', EVENT_REDRAW, ui_x+129, ui_y+39, 100, 20, EXPORT_GROUP_BY_MAT.val, 'Group by materials.', do_split)
684                         Draw.EndAlign()
685                         
686                         EXPORT_KEEP_VERT_ORDER = Draw.Toggle('Keep Vert Order', EVENT_REDRAW, ui_x+239, ui_y+39, 100, 20, EXPORT_KEEP_VERT_ORDER.val, 'Keep vert and face order, disables some other options. Use for morph targets.', do_vertorder)
687                         
688                         Draw.BeginAlign()
689                         Draw.PushButton('Online Help', EVENT_REDRAW, ui_x+9, ui_y+9, 110, 20, 'Load the wiki page for this script', do_help)
690                         Draw.PushButton('Cancel', EVENT_EXIT, ui_x+119, ui_y+9, 110, 20, '', obj_ui_set_event)
691                         Draw.PushButton('Export', EVENT_EXPORT, ui_x+229, ui_y+9, 110, 20, 'Export with these settings', obj_ui_set_event)
692                         Draw.EndAlign()
693
694                 
695                 # hack so the toggle buttons redraw. this is not nice at all
696                 while GLOBALS['EVENT'] not in (EVENT_EXIT, EVENT_EXPORT):
697                         Draw.UIBlock(obj_ui)
698                 
699                 if GLOBALS['EVENT'] != EVENT_EXPORT:
700                         return
701                 
702         # END ALTERNATIVE UI *********************
703         
704         
705         if EXPORT_KEEP_VERT_ORDER.val:
706                 EXPORT_BLEN_OBS.val = False
707                 EXPORT_GROUP_BY_OB.val = False
708                 EXPORT_GROUP_BY_MAT.val = False
709                 EXPORT_APPLY_MODIFIERS.val = False
710         
711         Window.EditMode(0)
712         Window.WaitCursor(1)
713         
714         EXPORT_APPLY_MODIFIERS = EXPORT_APPLY_MODIFIERS.val
715         EXPORT_ROTX90 = EXPORT_ROTX90.val
716         EXPORT_TRI = EXPORT_TRI.val
717         EXPORT_EDGES = EXPORT_EDGES.val
718         EXPORT_NORMALS = EXPORT_NORMALS.val
719         EXPORT_NORMALS_HQ = EXPORT_NORMALS_HQ.val
720         EXPORT_UV = EXPORT_UV.val
721         EXPORT_MTL = EXPORT_MTL.val
722         EXPORT_SEL_ONLY = EXPORT_SEL_ONLY.val
723         EXPORT_ALL_SCENES = EXPORT_ALL_SCENES.val
724         EXPORT_ANIMATION = EXPORT_ANIMATION.val
725         EXPORT_COPY_IMAGES = EXPORT_COPY_IMAGES.val
726         EXPORT_BLEN_OBS = EXPORT_BLEN_OBS.val
727         EXPORT_GROUP_BY_OB = EXPORT_GROUP_BY_OB.val
728         EXPORT_GROUP_BY_MAT = EXPORT_GROUP_BY_MAT.val
729         EXPORT_KEEP_VERT_ORDER = EXPORT_KEEP_VERT_ORDER.val
730         
731         
732         
733         base_name, ext = splitExt(filename)
734         context_name = [base_name, '', '', ext] # basename, scene_name, framenumber, extension
735         
736         # Use the options to export the data using write()
737         # def write(filename, objects, EXPORT_EDGES=False, EXPORT_NORMALS=False, EXPORT_MTL=True, EXPORT_COPY_IMAGES=False, EXPORT_APPLY_MODIFIERS=True):
738         orig_scene = Scene.GetCurrent()
739         if EXPORT_ALL_SCENES:
740                 export_scenes = Scene.Get()
741         else:
742                 export_scenes = [orig_scene]
743         
744         # Export all scenes.
745         for scn in export_scenes:
746                 scn.makeCurrent() # If alredy current, this is not slow.
747                 context = scn.getRenderingContext()
748                 orig_frame = Blender.Get('curframe')
749                 
750                 if EXPORT_ALL_SCENES: # Add scene name into the context_name
751                         context_name[1] = '_%s' % BPySys.cleanName(scn.name) # WARNING, its possible that this could cause a collision. we could fix if were feeling parranoied.
752                 
753                 # Export an animation?
754                 if EXPORT_ANIMATION:
755                         scene_frames = xrange(context.startFrame(), context.endFrame()+1) # up to and including the end frame.
756                 else:
757                         scene_frames = [orig_frame] # Dont export an animation.
758                 
759                 # Loop through all frames in the scene and export.
760                 for frame in scene_frames:
761                         if EXPORT_ANIMATION: # Add frame to the filename.
762                                 context_name[2] = '_%.6d' % frame
763                         
764                         Blender.Set('curframe', frame)
765                         if EXPORT_SEL_ONLY:
766                                 export_objects = scn.objects.context
767                         else:   
768                                 export_objects = scn.objects
769                         
770                         full_path= ''.join(context_name)
771                         
772                         # erm... bit of a problem here, this can overwrite files when exporting frames. not too bad.
773                         # EXPORT THE FILE.
774                         write(full_path, export_objects,\
775                         EXPORT_TRI, EXPORT_EDGES, EXPORT_NORMALS,\
776                         EXPORT_NORMALS_HQ, EXPORT_UV, EXPORT_MTL,\
777                         EXPORT_COPY_IMAGES, EXPORT_APPLY_MODIFIERS,\
778                         EXPORT_ROTX90, EXPORT_BLEN_OBS,\
779                         EXPORT_GROUP_BY_OB, EXPORT_GROUP_BY_MAT, EXPORT_KEEP_VERT_ORDER)
780                 
781                 Blender.Set('curframe', orig_frame)
782         
783         # Restore old active scene.
784         orig_scene.makeCurrent()
785         Window.WaitCursor(0)
786
787
788 if __name__ == '__main__':
789         Window.FileSelector(write_ui, 'Export Wavefront OBJ', sys.makename(ext='.obj'))