All negative vert indicies are assumed relative, removed relative vert option.
[blender.git] / release / scripts / obj_import.py
1 #!BPY
2  
3 """
4 Name: 'Wavefront (.obj)...'
5 Blender: 237
6 Group: 'Import'
7 Tooltip: 'Load a Wavefront OBJ File, Shift: batch import all dir.'
8 """
9
10 __author__= "Campbell Barton"
11 __url__= ["blender", "elysiun"]
12 __version__= "1.0"
13
14 __bpydoc__= """\
15 This script imports OBJ files to Blender.
16
17 Usage:
18
19 Run this script from "File->Import" menu and then load the desired OBJ file.
20 """
21
22 # $Id$
23 #
24 # --------------------------------------------------------------------------
25 # OBJ Import v1.0 by Campbell Barton (AKA Ideasman)
26 # --------------------------------------------------------------------------
27 # ***** BEGIN GPL LICENSE BLOCK *****
28 #
29 # This program is free software; you can redistribute it and/or
30 # modify it under the terms of the GNU General Public License
31 # as published by the Free Software Foundation; either version 2
32 # of the License, or (at your option) any later version.
33 #
34 # This program is distributed in the hope that it will be useful,
35 # but WITHOUT ANY WARRANTY; without even the implied warranty of
36 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
37 # GNU General Public License for more details.
38 #
39 # You should have received a copy of the GNU General Public License
40 # along with this program; if not, write to the Free Software Foundation,
41 # Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
42 #
43 # ***** END GPL LICENCE BLOCK *****
44 # --------------------------------------------------------------------------
45
46
47 #==============================================#
48 # Return directory, where the file is          #
49 #==============================================#
50 def stripFile(path):
51         lastSlash= max(path.rfind('\\'), path.rfind('/'))
52         if lastSlash != -1:
53                 path= path[:lastSlash]
54         return '%s%s' % (path, sys.sep)
55
56 #==============================================#
57 # Strips the slashes from the back of a string #
58 #==============================================#
59 def stripPath(path):
60         return path.split('/')[-1].split('\\')[-1]
61         
62 #====================================================#
63 # Strips the prefix off the name before writing      #
64 #====================================================#
65 def stripExt(name): # name is a string
66         index= name.rfind('.')
67         if index != -1:
68                 return name[ : index ]
69         else:
70                 return name
71
72
73 from Blender import *
74 import BPyImage
75 reload(BPyImage)
76 import BPyMesh
77
78 try:
79         import os
80 except:
81         # So we know if os exists.
82         print 'Module "os" not found, install python to enable comprehensive image finding and batch loading.'
83         os= None
84
85
86 #==================================================================================#
87 # This function sets textures defined in .mtl file                                 #
88 #==================================================================================#
89 def loadMaterialImage(mat, img_fileName, type, meshDict, dir):
90         TEX_ON_FLAG= NMesh.FaceModes['TEX']
91         
92         texture= Texture.New(type)
93         texture.setType('Image')
94         
95         # Absolute path - c:\.. etc would work here
96         image= BPyImage.comprehensiveImageLoad(img_fileName, dir)
97         
98         if image:
99                 texture.image= image
100                 
101         # adds textures to faces (Textured/Alt-Z mode)
102         # Only apply the diffuse texture to the face if the image has not been set with the inline usemat func.
103         if image and type == 'Kd':
104                 for meshPair in meshDict.itervalues():
105                         for f in meshPair[0].faces:
106                                 #print meshPair[0].materials[f.mat].name, mat.name
107                                 if meshPair[0].materials[f.mat].name == mat.name:
108                                         # the inline usemat command overides the material Image
109                                         if not f.image:
110                                                 f.mode |= TEX_ON_FLAG
111                                                 f.image= image
112         
113         # adds textures for materials (rendering)
114         elif type == 'Ka':
115                 mat.setTexture(0, texture, Texture.TexCo.UV, Texture.MapTo.CMIR) # TODO- Add AMB to BPY API
116         elif type == 'Kd':
117                 mat.setTexture(1, texture, Texture.TexCo.UV, Texture.MapTo.COL)
118         elif type == 'Ks':
119                 mat.setTexture(2, texture, Texture.TexCo.UV, Texture.MapTo.SPEC)
120         
121         elif type == 'Bump': # New Additions
122                 mat.setTexture(3, texture, Texture.TexCo.UV, Texture.MapTo.NOR)         
123         elif type == 'D':
124                 mat.setTexture(4, texture, Texture.TexCo.UV, Texture.MapTo.ALPHA)                               
125         elif type == 'refl':
126                 mat.setTexture(5, texture, Texture.TexCo.UV, Texture.MapTo.REF)                         
127         
128
129 #==================================================================================#
130 # This function loads materials from .mtl file (have to be defined in obj file)    #
131 #==================================================================================#
132 def load_mtl(dir, mtl_file, meshDict, materialDict):
133         
134         #===============================================================================#
135         # This gets a mat or creates one of the requested name if none exist.           #
136         #===============================================================================#
137         def getMat(matName, materialDict):
138                 # Make a new mat
139                 try:
140                         return materialDict[matName]
141                 #except NameError or KeyError:
142                 except: # Better do any exception
143                         # Do we realy need to keep the dict up to date?, not realy but keeps consuistant.
144                         mat= materialDict[matName]= Material.New(matName)
145                         return mat
146                 
147                         
148         mtl_file= stripPath(mtl_file)
149         mtl_fileName= dir + mtl_file
150         
151         try:
152                 fileLines= open(mtl_fileName, 'r').readlines()
153         except IOError:
154                 print '\tunable to open referenced material file: "%s"' % mtl_fileName
155                 return
156         
157         try:
158                 lIdx=0
159                 while lIdx < len(fileLines):
160                         l= fileLines[lIdx].split()
161                         
162                         # Detect a line that will be ignored
163                         if len(l) == 0 or l[0].startswith('#'):
164                                 pass
165                         elif l[0] == 'newmtl':
166                                 currentMat= getMat('_'.join(l[1:]), materialDict) # Material should alredy exist.
167                         elif l[0] == 'Ka':
168                                 currentMat.setMirCol((float(l[1]), float(l[2]), float(l[3])))
169                         elif l[0] == 'Kd':
170                                 currentMat.setRGBCol((float(l[1]), float(l[2]), float(l[3])))
171                         elif l[0] == 'Ks':
172                                 currentMat.setSpecCol((float(l[1]), float(l[2]), float(l[3])))
173                         elif l[0] == 'Ns':
174                                 currentMat.setHardness( int((float(l[1])*0.51)) )
175                         elif l[0] == 'Ni': # Refraction index
176                                 currentMat.setIOR( max(1, min(float(l[1]), 3))) # Between 1 and 3
177                         elif l[0] == 'd':
178                                 currentMat.setAlpha(float(l[1]))
179                         elif l[0] == 'Tr':
180                                 currentMat.setAlpha(float(l[1]))
181                         elif l[0] == 'map_Ka':
182                                 img_fileName= ' '.join(l[1:])
183                                 loadMaterialImage(currentMat, img_fileName, 'Ka', meshDict, dir)
184                         elif l[0] == 'map_Ks':
185                                 img_fileName= ' '.join(l[1:])
186                                 loadMaterialImage(currentMat, img_fileName, 'Ks', meshDict, dir)
187                         elif l[0] == 'map_Kd':
188                                 img_fileName= ' '.join(l[1:])
189                                 loadMaterialImage(currentMat, img_fileName, 'Kd', meshDict, dir)
190                         
191                         # new additions
192                         elif l[0] == 'map_Bump': # Bumpmap
193                                 img_fileName= ' '.join(l[1:])                   
194                                 loadMaterialImage(currentMat, img_fileName, 'Bump', meshDict, dir)
195                         elif l[0] == 'map_D': # Alpha map - Dissolve
196                                 img_fileName= ' '.join(l[1:])                   
197                                 loadMaterialImage(currentMat, img_fileName, 'D', meshDict, dir)
198
199                         elif l[0] == 'refl': # Reflectionmap
200                                 img_fileName= ' '.join(l[1:])                   
201                                 loadMaterialImage(currentMat, img_fileName, 'refl', meshDict, dir)
202                         
203                         lIdx+=1
204         except:
205                 print '\tERROR: Unable to parse MTL file: "%s"' % mtl_file
206                 return
207         print '\tUsing MTL: "%s"' % mtl_file
208 #===========================================================================#
209 # Returns unique name of object/mesh (preserve overwriting existing meshes) #
210 #===========================================================================#
211 def getUniqueName(name):
212         newName= name[:19] # 19 chars is the longest name.
213         uniqueInt= 0
214         while newName in getUniqueName.uniqueNames:
215                 newName= '%s.%.3i' % (name[:15], uniqueInt)
216                 uniqueInt +=1
217         getUniqueName.uniqueNames.append(newName)
218         return newName
219 getUniqueName.uniqueNames= []
220
221 #==================================================================================#
222 # This loads data from .obj file                                                   #
223 #==================================================================================#
224 def load_obj(file, IMPORT_MTL=1, IMPORT_EDGES=1, IMPORT_SMOOTH_ALL=0, IMPORT_FGON=1, IMPORT_SMOOTH_GROUPS=0, IMPORT_MTL_SPLIT=0):
225         global currentMesh,\
226         currentUsedVertList,\
227         currentUsedVertListSmoothGroup,\
228         meshDict,\
229         contextMeshMatIdx,\
230         currentMaterialMeshMapping
231         
232         print '\nImporting OBJ file: "%s"' % file
233         
234         time1= sys.time()
235         
236         getUniqueName.uniqueNames.extend( [ob.name for ob in Object.Get()] )
237         getUniqueName.uniqueNames.extend( NMesh.GetNames() )
238         
239         # Deselect all objects in the scene.
240         # do this first so we dont have to bother, with objects we import
241         for ob in Scene.GetCurrent().getChildren():
242                 ob.sel= 0
243         
244         TEX_OFF_FLAG= ~NMesh.FaceModes['TEX']
245         
246         # Get the file name with no path or .obj
247         fileName= stripExt( stripPath(file) )
248
249         mtl_fileName= [] # Support multiple mtl files if needed.
250
251         DIR= stripFile(file)
252         
253         tempFile= open(file, 'r')
254         fileLines= tempFile.readlines() 
255         tempFile.close()
256         del tempFile
257         uvMapList= [] # store tuple uv pairs here
258         
259         # This dummy vert makes life a whole lot easier-
260         # pythons index system then aligns with objs, remove later
261         vertList= [] # Could havea vert but since this is a placeholder theres no Point
262         
263         
264         # Store all imported images in a dict, names are key
265         imageDict= {}
266         
267         # This stores the index that the current mesh has for the current material.
268         # if the mesh does not have the material then set -1
269         contextMeshMatIdx= -1
270         
271         # Keep this out of the dict for easy accsess.
272         nullMat= Material.New('(null)')
273         
274         currentMat= nullMat # Use this mat.
275         currentImg= None # Null image is a string, otherwise this should be set to an image object.\
276         if IMPORT_SMOOTH_ALL:
277                 currentSmooth= True
278         else:
279                 currentSmooth= False
280         
281         # Store a list of unnamed names
282         currentUnnamedGroupIdx= 1
283         currentUnnamedObjectIdx= 1
284         
285         quadList= (0, 1, 2, 3)
286         
287         faceQuadVList= [None, None, None, None]
288         faceTriVList= [None, None, None]
289         
290         #==================================================================================#
291         # Load all verts first (texture verts too)                                         #
292         #==================================================================================#
293         print '\tfile length: %d' % len(fileLines)
294         # Ignore normals and comments.
295         fileLines= [lsplit for l in fileLines if not l.startswith('vn') if not l.startswith('#') for lsplit in (l.split(),) if lsplit]
296         Vert= NMesh.Vert
297         try:
298                 vertList= [Vert(float(l[1]), float(l[2]), float(l[3]) ) for l in fileLines if l[0] == 'v']
299         except ValueError:
300                 # What??? Maya 7 uses "6,45" instead of "6.45"
301                 vertList= [Vert(float(l[1].replace(',', '.')), float(l[2].replace(',', '.')), float(l[3].replace(',', '.')) ) for l in fileLines if l[0] == 'v']
302                 
303         try:
304                 uvMapList= [(float(l[1]), float(l[2])) for l in fileLines if l[0] == 'vt']
305         except ValueError:
306                 # Same amazement as above. call that a float?
307                 uvMapList= [(float(l[1].replace(',', '.')), float(l[2].replace(',', '.'))) for l in fileLines if l[0] == 'vt']
308                 
309         if IMPORT_SMOOTH_GROUPS:
310                 smoothingGroups=  dict([('_'.join(l[1:]), None) for l in fileLines if l[0] == 's' ])
311         else:
312                 smoothingGroups= {}
313         materialDict=     dict([('_'.join(l[1:]), None) for l in fileLines if l[0] == 'usemtl']) # Store all imported materials as unique dict, names are key
314         print '\tvert:%i  texverts:%i  smoothgroups:%i  materials:%s' % (len(vertList), len(uvMapList), len(smoothingGroups), len(materialDict))
315         
316         # Replace filelines, Excluding v excludes "v ", "vn " and "vt "
317         # Remove any variables we may have created.
318         try: del _dummy
319         except: pass
320         try: del _x
321         except: pass
322         try: del _y
323         except: pass
324         try: del _z
325         except: pass
326         try: del lsplit
327         except: pass
328         del Vert
329         
330         
331         # With negative values this is used a lot. make faster access.
332         len_uvMapList= len(uvMapList)
333         len_vertList= len(vertList)
334         
335         #  Only want unique keys anyway
336         smoothingGroups['(null)']= None # Make sure we have at least 1.
337         smoothingGroups= smoothingGroups.keys()
338         print '\tfound %d smoothing groups.' % (len(smoothingGroups) -1)
339         
340         # Add materials to Blender for later is in teh OBJ
341         for k in materialDict.iterkeys():
342                 materialDict[k]= Material.New(k)
343         
344         
345         # Make a list of all unused vert indices that we can copy from
346         VERT_USED_LIST= [-1]*len_vertList
347         
348         # Here we store a boolean list of which verts are used or not
349         # no we know weather to add them to the current mesh
350         # This is an issue with global vertex indices being translated to per mesh indices
351         # like blenders, we start with a dummy just like the vert.
352         # -1 means unused, any other value refers to the local mesh index of the vert.
353
354         # currentObjectName has a char in front of it that determins weather its a group or object.
355         # We ignore it when naming the object.
356         currentObjectName= 'unnamed_obj_0' # If we cant get one, use this
357         
358         if IMPORT_MTL_SPLIT:
359                 currentObjectName_real= currentObjectName
360         
361         #meshDict= {} # The 3 variables below are stored in a tuple within this dict for each mesh
362         currentMesh= NMesh.GetRaw() # The NMesh representation of the OBJ group/Object
363         #currentUsedVertList= {} # A Dict of smooth groups, each smooth group has a list of used verts and they are generated on demand so as to save memory.
364         currentMaterialMeshMapping= {} # Used to store material indices so we dont have to search the mesh for materials every time.
365         
366         # Every mesh has a null smooth group, this is used if there are no smooth groups in the OBJ file.
367         # and when for faces where no smooth group is used.
368         currentSmoothGroup= '(null)' # The Name of the current smooth group
369         
370         # For direct accsess to the Current Meshes, Current Smooth Groups- Used verts.
371         # This is of course context based and changes on the fly.
372         # Set the initial '(null)' Smooth group, every mesh has one.
373         currentUsedVertListSmoothGroup= VERT_USED_LIST[:]
374         currentUsedVertList= {currentSmoothGroup: currentUsedVertListSmoothGroup }
375         
376         # 0:NMesh, 1:SmoothGroups[UsedVerts[0,0,0,0]], 2:materialMapping['matname':matIndexForThisNMesh]
377         meshDict= {currentObjectName: (currentMesh, currentUsedVertList, currentMaterialMeshMapping) }
378         
379         # Only show the bad uv error once 
380         badObjUvs= 0
381         badObjFaceVerts= 0
382         badObjFaceTexCo= 0
383         
384         
385         #currentMesh.verts.append(vertList[0]) # So we can sync with OBJ indices where 1 is the first item.
386         if len_uvMapList > 1:
387                 currentMesh.hasFaceUV(1) # Turn UV's on if we have ANY texture coords in this obj file.
388         
389         
390         
391         # Heres the code that gets a mesh, creating a new one if needed.
392         # may_exist is used to avoid a dict looup.
393         # if the mesh is unnamed then we generate a new name and dont bother looking
394         # to see if its alredy there.
395         def obj_getmesh(may_exist):
396                 global currentMesh,\
397                 currentUsedVertList,\
398                 currentUsedVertListSmoothGroup,\
399                 meshDict,\
400                 contextMeshMatIdx,\
401                 currentMaterialMeshMapping
402                 
403                 #print 'getting mesh,', currentObjectName
404                 
405                 # If we havnt written to this mesh before then do so.
406                 # if we have then we'll just keep appending to it, this is required for soem files.
407                 
408                 # If we are new, or we are not yet in the list of added meshes
409                 # then make us new mesh.
410                 if (not may_exist) or (not meshDict.has_key(currentObjectName)):
411                         currentMesh= NMesh.GetRaw()
412                         
413                         currentUsedVertList= {}
414                         
415                         # SmoothGroup is a string
416                         ########currentSmoothGroup= '(null)' # From examplesm changing the g/o shouldent change the smooth group.
417                         currentUsedVertList[currentSmoothGroup]= currentUsedVertListSmoothGroup= VERT_USED_LIST[:]                                              
418                         
419                         currentMaterialMeshMapping= {}
420                         meshDict[currentObjectName]= (currentMesh, currentUsedVertList, currentMaterialMeshMapping)
421                         currentMesh.hasFaceUV(1)
422                         contextMeshMatIdx= -1
423                         
424                 else: 
425                         # Since we have this in Blender then we will check if the current Mesh has the material.
426                         # set the contextMeshMatIdx to the meshs index but only if we have it.
427                         currentMesh, currentUsedVertList, currentMaterialMeshMapping= meshDict[currentObjectName]
428                         #getMeshMaterialIndex(currentMesh, currentMat)
429                         
430                         try:
431                                 contextMeshMatIdx= currentMaterialMeshMapping[currentMat.name] #getMeshMaterialIndex(currentMesh, currentMat)
432                         except KeyError:
433                                 contextMeshMatIdx -1
434                         
435                         # For new meshes switch smoothing groups to null
436                         ########currentSmoothGroup= '(null)'  # From examplesm changing the g/o shouldent change the smooth group.
437                         try:
438                                 currentUsedVertListSmoothGroup= currentUsedVertList[currentSmoothGroup]
439                         except:
440                                 currentUsedVertList[currentSmoothGroup]= currentUsedVertListSmoothGroup= VERT_USED_LIST[:]                                              
441                 
442         
443         
444         
445         
446         
447         
448         #==================================================================================#
449         # Load all faces into objects, main loop                                           #
450         #==================================================================================#
451         lIdx= 0
452         EDGE_FGON_FLAG= NMesh.EdgeFlags['FGON']
453         EDGE_DRAW_FLAG= NMesh.EdgeFlags['EDGEDRAW']
454         
455         REL_VERT_COUNT= REL_TVERT_COUNT=0
456         
457         while lIdx < len(fileLines):
458                 l= fileLines[lIdx]
459                 #for l in fileLines:
460                 if len(l) == 0:
461                         continue
462                 # FACE
463                 elif l[0] == 'v':
464                         REL_VERT_COUNT+=1
465                 elif l[0] == 'vt':
466                         REL_TVERT_COUNT+=1
467                 
468                 elif l[0] == 'f' or l[0] == 'fo': # fo is not standard. saw it used once.
469                         # Make a face with the correct material.
470                         
471                         # Add material to mesh
472                         if contextMeshMatIdx == -1:
473                                 tmpMatLs= currentMesh.materials
474                                 
475                                 if len(tmpMatLs) == 16:
476                                         contextMeshMatIdx= 0 # Use first material
477                                         print 'material overflow, attempting to use > 16 materials. defaulting to first.'
478                                 else:
479                                         contextMeshMatIdx= len(tmpMatLs)
480                                         currentMaterialMeshMapping[currentMat.name]= contextMeshMatIdx
481                                         currentMesh.addMaterial(currentMat)
482                         
483                         # Set up vIdxLs : Verts
484                         # Set up vtIdxLs : UV
485                         # Start with a dummy objects so python accepts OBJs 1 is the first index.
486                         vIdxLs= []
487                         vtIdxLs= []
488                         
489                         
490                         fHasUV= len_uvMapList # Assume the face has a UV until it sho it dosent, if there are no UV coords then this will start as 0.
491                         
492                         # Support stupid multiline faces
493                         # not an obj spec but some objs exist that do this.
494                         # f 1 2 3 \ 
495                         #   4 5 6 \
496                         # ..... instead of the more common and sane.
497                         # f 1 2 3 4 5 6
498                         #
499                         # later lines are not modified, just skepped by advancing "lIdx"
500                         while l[-1] == '\\':
501                                 l.pop()
502                                 lIdx+=1
503                                 l.extend(fileLines[lIdx])
504                         # Done supporting crappy obj faces over multiple lines.
505                         
506                         for v in l:
507                                 if v is not 'f': # Only the first v will be f, any better ways to skip it?
508                                         # OBJ files can have // or / to seperate vert/texVert/normal
509                                         # this is a bit of a pain but we must deal with it.
510                                         objVert= v.split('/')
511                                         
512                                         # Vert Index - OBJ supports negative index assignment (like python)
513                                         index= int(objVert[0])-1
514                                         # Account for negative indices.
515                                         if index < 0:
516                                                 # Assume negative verts are relative.
517                                                 index= REL_VERT_COUNT+index+1
518                                         
519                                         vIdxLs.append(index)
520                                         if fHasUV:
521                                                 # UV
522                                                 index= 0 # Dummy var
523                                                 if len(objVert) == 1:
524                                                         index= vIdxLs[-1]
525                                                 elif objVert[1]: # != '' # Its possible that theres no texture vert just he vert and normal eg 1//2
526                                                         index= int(objVert[1])-1
527                                                         if index < 0:
528                                                                 # Assume negative verts are relative
529                                                                 index= REL_TVERT_COUNT+index+1
530                                                         
531                                                 if len_uvMapList > index:
532                                                         vtIdxLs.append(index) # Seperate UV coords
533                                                 else:
534                                                         # BAD FILE, I have found this so I account for it.
535                                                         # INVALID UV COORD
536                                                         # Could ignore this- only happens with 1 in 1000 files.
537                                                         badObjFaceTexCo +=1
538                                                         vtIdxLs.append(1)
539                                                         
540                                                         fHasUV= 0
541                 
542                                                 # Dont add a UV to the face if its larger then the UV coord list
543                                                 # The OBJ file would have to be corrupt or badly written for thi to happen
544                                                 # but account for it anyway.
545                                                 if len(vtIdxLs) > 0:
546                                                         if vtIdxLs[-1] > len_uvMapList:
547                                                                 fHasUV= 0
548                                                                 
549                                                                 badObjUvs +=1 # ERROR, Cont
550                         
551                         # Quads only, we could import quads using the method below but it polite to import a quad as a quad.
552                         #print lIdx, len(vIdxLs), len(currentUsedVertListSmoothGroup)
553                         #print fileLines[lIdx]
554                         
555                         # Add all the verts we need,
556                         # dont edd edge verts if were not importing them.
557                         face_vert_count= len(vIdxLs)
558                         if (not IMPORT_EDGES) and face_vert_count == 2:
559                                 pass
560                         else:
561                                 # Add the verts that arnt alredy added.
562                                 for i in vIdxLs:
563                                         if currentUsedVertListSmoothGroup[i] == -1:
564                                                 v= vertList[i]
565                                                 currentMesh.verts.append(v)
566                                                 currentUsedVertListSmoothGroup[i]= len(currentMesh.verts)-1
567                         
568                         if face_vert_count == 2:
569                                 if IMPORT_EDGES and vIdxLs[0]!=vIdxLs[1]:
570                                         # Edge
571                                         currentMesh.addEdge(\
572                                         currentMesh.verts[currentUsedVertListSmoothGroup[vIdxLs[0]]],\
573                                         currentMesh.verts[currentUsedVertListSmoothGroup[vIdxLs[0]]]) 
574                                         
575                         elif face_vert_count == 4:
576                                 
577                                 # Have found some files where wach face references the same vert
578                                 # - This causes a bug and stopts the import so lets check here
579                                 if vIdxLs[0] == vIdxLs[1] or\
580                                 vIdxLs[0] == vIdxLs[2] or\
581                                 vIdxLs[0] == vIdxLs[3] or\
582                                 vIdxLs[1] == vIdxLs[2] or\
583                                 vIdxLs[1] == vIdxLs[3] or\
584                                 vIdxLs[2] == vIdxLs[3]:
585                                         badObjFaceVerts+=1
586                                 else:
587                                         for i in quadList: #  quadList == [0,1,2,3] 
588                                                 faceQuadVList[i]= currentMesh.verts[currentUsedVertListSmoothGroup[vIdxLs[i]]]
589                                         
590                                         f= NMesh.Face(faceQuadVList)
591                                         # UV MAPPING
592                                         if fHasUV:
593                                                 f.uv= [uvMapList[ vtIdxLs[0] ],uvMapList[ vtIdxLs[1] ],uvMapList[ vtIdxLs[2] ],uvMapList[ vtIdxLs[3] ]]
594                                                 if currentImg:
595                                                         f.image= currentImg
596                                                 else:
597                                                         f.mode &= TEX_OFF_FLAG
598                                         
599                                         f.mat= contextMeshMatIdx
600                                         f.smooth= currentSmooth
601                                         currentMesh.faces.append(f) # move the face onto the mesh
602                         
603                         elif face_vert_count == 3: # This handles tri's and fans, dont use fans anymore.
604                                 for i in range(face_vert_count-2):
605                                         if vIdxLs[0] == vIdxLs[i+1] or\
606                                         vIdxLs[0] == vIdxLs[i+2] or\
607                                         vIdxLs[i+1] == vIdxLs[i+2]:
608                                                 badObjFaceVerts+=1
609                                         else:
610                                                 for k, j in [(0,0), (1,i+1), (2,i+2)]:
611                                                         faceTriVList[k]= currentMesh.verts[currentUsedVertListSmoothGroup[vIdxLs[j]]]   
612                                                 
613                                                 f= NMesh.Face(faceTriVList)     
614                                                 
615                                                 # UV MAPPING
616                                                 if fHasUV:
617                                                         f.uv= [uvMapList[vtIdxLs[0]], uvMapList[vtIdxLs[i+1]], uvMapList[vtIdxLs[i+2]]]
618                                                         if currentImg:
619                                                                 f.image= currentImg
620                                                         else:
621                                                                 f.mode &= TEX_OFF_FLAG
622                                                 
623                                                 f.mat= contextMeshMatIdx
624                                                 f.smooth= currentSmooth
625                                                 currentMesh.faces.append(f) # move the face onto the mesh
626                         
627                         elif face_vert_count > 4: # NGons.
628                                 # we need to map indices to uv coords.
629                                 currentMeshRelativeIdxs= [currentUsedVertListSmoothGroup[i] for i in vIdxLs]
630                                 
631                                 if fHasUV:
632                                         vert2UvMapping=dict( [ (currentMeshRelativeIdxs[i],vtIdxLs[i]) for i in xrange(face_vert_count)] )
633                                 
634                                 ngon_face_indices= BPyMesh.ngon(currentMesh, currentMeshRelativeIdxs)
635                                 
636                                 
637                                 # At the moment scanfill always makes tri's but dont count on it
638                                 for fillFace in ngon_face_indices:
639                                         f= NMesh.Face([currentMesh.verts[currentMeshRelativeIdxs[i]] for i in fillFace])
640                                         
641                                         if fHasUV:
642                                                 f.uv= [uvMapList[vert2UvMapping[currentMeshRelativeIdxs[i]]] for i in fillFace]
643                                                 if currentImg:
644                                                         f.image= currentImg
645                                                 else:
646                                                         f.mode &= TEX_OFF_FLAG
647                                         
648                                         f.mat= contextMeshMatIdx
649                                         f.smooth= currentSmooth
650                                         currentMesh.faces.append(f) # move the face onto the mesh
651                                 
652                                 # Set fgon flag.
653                                 if IMPORT_FGON:
654                                         edgeUsers={}
655                                         for fillFace in ngon_face_indices:
656                                                 for i in xrange(len(fillFace)): # Should always be 3
657                                                         i1= currentMeshRelativeIdxs[fillFace[i]]
658                                                         i2= currentMeshRelativeIdxs[fillFace[i-1]]
659                                                         
660                                                         # Sort the pair so thet always match.
661                                                         if i1>i2: i1,i2=i2,i1
662                                                                 
663                                                         try:
664                                                                 edgeUsers[i1,i2]+= 1
665                                                         except:
666                                                                 edgeUsers[i1,i2]= 0
667                                         
668                                         for edgeVerts, users in edgeUsers.iteritems():
669                                                 if users:
670                                                         ed= currentMesh.addEdge(\
671                                                          currentMesh.verts[edgeVerts[0]],\
672                                                          currentMesh.verts[edgeVerts[1]])
673                                                         
674                                                         ed.flag|= EDGE_FGON_FLAG
675                         
676                 # FACE SMOOTHING
677                 elif l[0] == 's' and IMPORT_SMOOTH_GROUPS:
678                         # No value? then turn on.
679                         if len(l) == 1:
680                                 currentSmooth= True
681                                 currentSmoothGroup= '(null)'
682                         else:
683                                 if l[1] == 'off': # We all have a null group so dont need to try, will try anyway to avoid code duplication.
684                                         if not IMPORT_SMOOTH_ALL:
685                                                 currentSmooth= False
686                                         currentSmoothGroup= '(null)'
687                                 else: 
688                                         currentSmooth= True
689                                         currentSmoothGroup= '_'.join(l[1:])
690                         try:
691                                 currentUsedVertListSmoothGroup= currentUsedVertList[currentSmoothGroup]
692                         except KeyError:
693                                 currentUsedVertList[currentSmoothGroup]= currentUsedVertListSmoothGroup= VERT_USED_LIST[:]
694                 
695                 
696                 # OBJECT / GROUP
697                 elif l[0] == 'o' or l[0] == 'g':
698                         
699                         # Forget about the current image
700                         currentImg= None
701                         
702                         # This makes sure that if an object and a group have the same name then
703                         # they are not put into the same object.
704                         
705                         # Only make a new group.object name if the verts in the existing object have been used, this is obscure
706                         # but some files face groups seperating verts and faces which results in silly things. (no groups have names.)
707                         if len(l) == 1:
708                                 # Make a new empty name
709                                 if l[0] == 'g': # Make a blank group name
710                                         currentObjectName= 'unnamed_grp_%.4d' % currentUnnamedGroupIdx
711                                         currentUnnamedGroupIdx +=1
712                                 else: # is an object.
713                                         currentObjectName= 'unnamed_ob_%.4d' % currentUnnamedObjectIdx
714                                         currentUnnamedObjectIdx +=1
715                                 may_exist= False # we know the model is new.
716                         else: # No name given
717                                 currentObjectName= '_'.join(l[1:])
718                                 may_exist= True
719                         
720                         if IMPORT_MTL_SPLIT:
721                                 currentObjectName_real= currentObjectName
722                                 currentObjectName += '_'+currentMat.name
723                         
724                         obj_getmesh(may_exist)
725                                 
726                 
727                 # MATERIAL
728                 elif l[0] == 'usemtl':
729                         if len(l) == 1 or l[1] == '(null)':
730                                 currentMat= nullMat # We know we have a null mat.
731                         else:
732                                 currentMat= materialDict['_'.join(l[1:])]
733                                 try:
734                                         contextMeshMatIdx= currentMaterialMeshMapping[currentMat.name]
735                                 except KeyError:
736                                         contextMeshMatIdx= -1 #getMeshMaterialIndex(currentMesh, currentMat)
737                         
738                         # Check if we are splitting by material.
739                         if IMPORT_MTL_SPLIT:
740                                 currentObjectName= '%s_%s' % (currentObjectName_real, currentMat.name)
741                                 obj_getmesh(True)
742                         
743                         
744                 # IMAGE
745                 elif l[0] == 'usemat' or l[0] == 'usemap':
746                         if len(l) == 1 or l[1] == '(null)' or l[1] == 'off':
747                                 currentImg= None
748                         else:
749                                 # Load an image.
750                                 newImgName= stripPath(' '.join(l[1:])) # Use space since its a file name.
751                                 
752                                 try:
753                                         # Assume its alredy set in the dict (may or maynot be loaded)
754                                         currentImg= imageDict[newImgName]
755                                 
756                                 except KeyError: # Not in dict, add for first time.
757                                         # Image has not been added, Try and load the image
758                                         currentImg= BPyImage.comprehensiveImageLoad(newImgName, DIR) # Use join in case of spaces 
759                                         imageDict[newImgName]= currentImg
760                                         # These may be None, thats okay.
761                 
762                 # MATERIAL FILE
763                 elif l[0] == 'mtllib' and IMPORT_MTL and len(l)>1:
764                         mtl_fileName.append(' '.join(l[1:]) ) # Support for multiple MTL's
765                 lIdx+=1
766                 
767         # Applies material properties to materials alredy on the mesh as well as Textures.
768         if IMPORT_MTL:
769                 for mtl in mtl_fileName:
770                         load_mtl(DIR, mtl, meshDict, materialDict)      
771         
772         importedObjects= []
773         for mk, me in meshDict.iteritems():
774                 nme= me[0]
775                 
776                 # Ignore no vert meshes.
777                 if not nme.verts: # == []
778                         continue
779                 name= getUniqueName(mk)
780                 ob= NMesh.PutRaw(nme, name)
781                 ob.name= name
782                 
783                 importedObjects.append(ob)
784         
785         # Select all imported objects.
786         for ob in importedObjects:
787                 ob.sel= 1
788         if badObjUvs > 0:
789                 print '\tERROR: found %d faces with badly formatted UV coords. everything else went okay.' % badObjUvs
790         
791         if badObjFaceVerts > 0:
792                 print '\tERROR: found %d faces reusing the same vertex. everything else went okay.' % badObjFaceVerts
793         
794         if badObjFaceTexCo > 0:
795                 print '\tERROR: found %d faces with invalit texture coords. everything else went okay.' % badObjFaceTexCo               
796         
797         
798         print "obj import time: ", sys.time() - time1
799
800 def load_obj_ui(file):
801         
802         IMPORT_MTL= Draw.Create(1)
803         IMPORT_DIR= Draw.Create(0)
804         IMPORT_NEW_SCENE= Draw.Create(0)
805         IMPORT_EDGES= Draw.Create(1)
806         IMPORT_SMOOTH_ALL= Draw.Create(1)
807         IMPORT_FGON= Draw.Create(1)
808         IMPORT_SMOOTH_GROUPS= Draw.Create(0)
809         IMPORT_MTL_SPLIT= Draw.Create(0)
810         
811         # Get USER Options
812         pup_block= [\
813         ('Material (*.mtl)', IMPORT_MTL, 'Imports material settings and images from the obj\'s .mtl file'),\
814         ('All *.obj\'s in dir', IMPORT_DIR, 'Import all obj files in this dir (avoid overlapping data with "Create scene")'),\
815         ('Create scene', IMPORT_NEW_SCENE, 'Imports each obj into its own scene, named from the file'),\
816         'Geometry...',\
817         ('Edges', IMPORT_EDGES, 'Import faces with 2 verts as in edge'),\
818         ('Smooths all faces', IMPORT_SMOOTH_ALL, 'Smooth all faces even if they are not in a smoothing group'),\
819         ('Create FGons', IMPORT_FGON, 'Import faces with more then 4 verts as fgons.'),\
820         ('Smooth Groups', IMPORT_SMOOTH_GROUPS, 'Only Share verts within smooth groups. (Warning, Hogs Memory)'),\
821         ('Split by Material', IMPORT_MTL_SPLIT, 'Import each material into a seperate mesh (Avoids >16 meterials per mesh problem)'),\
822         ]
823         
824         if not os:
825                 pup_block.pop(2) # Make sure this is the IMPORT_DIR option that requires OS
826         
827         if not Draw.PupBlock('Import OBJ...', pup_block):
828                 return
829         
830         Window.WaitCursor(1)
831         Window.DrawProgressBar(0, '')
832         time= sys.time()
833         
834         IMPORT_MTL= IMPORT_MTL.val
835         IMPORT_DIR= IMPORT_DIR.val
836         IMPORT_NEW_SCENE= IMPORT_NEW_SCENE.val
837         IMPORT_EDGES= IMPORT_EDGES.val
838         IMPORT_SMOOTH_ALL= IMPORT_SMOOTH_ALL.val
839         IMPORT_FGON= IMPORT_FGON.val
840         IMPORT_SMOOTH_GROUPS= IMPORT_SMOOTH_GROUPS.val
841         IMPORT_MTL_SPLIT= IMPORT_MTL_SPLIT.val
842         orig_scene= Scene.GetCurrent()
843         
844         obj_dir= stripFile(file)
845         if IMPORT_DIR:
846                 obj_files= [(obj_dir,f) for f in os.listdir(obj_dir) if f.lower().endswith('obj')]
847         else:
848                 obj_files= [(obj_dir,stripPath(file))]
849         
850         obj_len= len(obj_files)
851         count= 0
852         for d, f in obj_files:
853                 count+= 1
854                 if not sys.exists(d+f):
855                         print 'Error: "%s%s" does not exist' % (d,f)
856                 else:
857                         if IMPORT_NEW_SCENE:
858                                 scn= Scene.New('.'.join(f.split('.')[0:-1]))
859                                 scn.makeCurrent()
860                         
861                         Window.DrawProgressBar((float(count)/obj_len) - 0.01, '%s: %i of %i' % (f, count, obj_len))
862                         load_obj(d+f, IMPORT_MTL, IMPORT_EDGES, IMPORT_SMOOTH_ALL, IMPORT_FGON, IMPORT_SMOOTH_GROUPS, IMPORT_MTL_SPLIT)
863                         
864         
865         orig_scene.makeCurrent() # We can leave them in there new scene.
866         Window.DrawProgressBar(1, '')
867         Window.WaitCursor(0)
868         
869         print 'Total obj import "%s" dir: %.2f' % (obj_dir, sys.time() - time)
870
871
872 def main():
873         Window.FileSelector(load_obj_ui, 'Import a Wavefront OBJ', '*.obj')
874
875 if __name__ == '__main__':
876         main()