def copy_images(dest_dir): if dest_dir[-1] != sys.sep: dest_dir += sys.sep # Get unique image names uniqueImages = {} for matname, mat, image in MTL_DICT.itervalues(): # Only use image name # Get Texface images if image: uniqueImages[image] = image # Should use sets here. wait until Python 2.4 is default. # Get MTex images if mat: for mtex in mat.getTextures(): if mtex and mtex.tex.type == Blender.Texture.Types.IMAGE: image_tex = mtex.tex.image if image_tex: try: uniqueImages[image_tex] = image_tex except: pass # Now copy images copyCount = 0 for bImage in uniqueImages.itervalues(): image_path = sys.expandpath(bImage.filename) if sys.exists(image_path): # Make a name for the target path. dest_image_path = dest_dir + image_path.split('\\')[-1].split('/')[-1] if not sys.exists(dest_image_path): # Image isnt alredy there print '\tCopying "%s" > "%s"' % (image_path, dest_image_path) copy_file(image_path, dest_image_path) copyCount+=1 print '\tCopied %d images' % copyCount
def track_export_path(): global settings, track_info tracks_dir = "%s/tracks" % (settings["VDrift_data_directory"]) if not sys.exists(tracks_dir): raise Exception("Couldn't find VDrift tracks directory '%s'." % (tracks_dir)) if not track_info["short_name"]: raise Exception("The short name is not set for this track. Set it in Track Info.") if re.search("[^a-zA-Z0-9-_\.]", track_info["short_name"]): raise Exception("The short name contains characters other than letters, numbers, '-', '_', and '.'.") path = "%s/%s" % (tracks_dir, track_info["short_name"]) objects_path = "%s/objects" % (path) if not sys.exists(objects_path): os.makedirs(objects_path) return path
def export_texture(self, texture, material): image = texture.getImage() image_path = sys.expandpath(image.filename) dest_path = self.texture_dir + image_path.split('\\')[-1].split('/')[-1] texture_id = texture.getName() if material.getName() == texture_id: texture_id += "Texture" self.out.write("\t\t<texture id=\""+ texture_id +"\" src=\"images"+os.sep+os.path.basename(image.getFilename())+"\" />\n") self.out.write("\t\t<material_layer texture=\"#"+ texture_id +"\" mapinput=\"UV1\" mapto=\"M_COLOR\" />\n") if sys.exists(image_path) and not sys.exists(dest_path): copy_file(image_path, dest_path)
def fs_callback(filename): global cmd, extension, scriptsdir if not filename.endswith(extension): filename = '%s%s' % (filename, extension) if bsys.exists(filename): if Blender.Draw.PupMenu('OVERWRITE?%t|File exists') != 1: return if cmd: tmp = bsys.join(scriptsdir, "tmp.xml") write_obj(tmp) print "running glexemel" cmd = [cmd, tmp, filename] print cmd p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out = p.stdout.read() err = p.stderr.read() res = p.wait() if res != 0 or err: s = '' if out: s += out.replace('\n', '|') if err: s += err.replace('\n', '|') Blender.Draw.PupMenu('glexemel error: see console%t|' + s) print out print err print res else: write_obj(filename) print "glexemel not found"
def imageLoad(path): #if path.endswith('\\') or path.endswith('/'): # raise 'INVALID PATH' if CONVERT_CALLBACK: path = CONVERT_CALLBACK(path) try: img = bpy.data.images.new(filename=path) if VERBOSE: print '\t\tImage loaded "%s"' % path return img except: if VERBOSE: if sys.exists(path): print '\t\tImage failed loading "%s", mabe its not a format blender can read.' % ( path) else: print '\t\tImage not found, making a place holder "%s"' % ( path) if PLACE_HOLDER: img = bpy.data.images.new(stripPath(path), 4, 4) img.filename = path return img #blank image else: return None
def fs_callback(filename): global EXPORT_DIR, OBJS, CONFIRM_OVERWRITE, VERBOSE if not filename.endswith('.ac'): filename = '%s.ac' % filename if bsys.exists(filename) and CONFIRM_OVERWRITE: if Blender.Draw.PupMenu('OVERWRITE?%t|File exists') != 1: return Blender.Window.WaitCursor(1) starttime = bsys.time() export_dir = bsys.dirname(filename) if export_dir != EXPORT_DIR: EXPORT_DIR = export_dir update_RegistryInfo() try: file = open(filename, 'w') except IOError, (errno, strerror): error = "IOError #%s: %s" % (errno, strerror) REPORT_DATA['errors'].append("Saving failed - %s." % error) error_msg = "Couldn't save file!%%t|%s" % error Blender.Draw.PupMenu(error_msg) return
def RemoveConfigData(key=None): """ Remove this key's config file from the <(u)datadir>/config/ folder. @type key: string @param key: the name of the key to be removed. If None (default) all available config files are deleted. """ _check_dir() if not key: files = \ [bsys.join(_CFG_DIR, f) for f in os.listdir(_CFG_DIR) if f.endswith(_EXT)] else: files = [] fname = bsys.join(_CFG_DIR, "%s%s" % (key, _EXT)) if bsys.exists(fname): files.append(fname) import os try: for p in files: os.remove(p) # remove the file(s) except Exception, e: raise Warning(e) # Resend exception as warning
def LoadConfigData(key=None): """ Load config data from file(s) to the Registry dictionary. @type key: string @param key: a given key name. If None (default), all available keys are loaded. @returns: None """ _check_dir() import os if not key: files = \ [bsys.join(_CFG_DIR, f) for f in os.listdir(_CFG_DIR) if f.endswith(_EXT)] else: files = [] fname = bsys.join(_CFG_DIR, "%s%s" % (key, _EXT)) if bsys.exists(fname): files.append(fname) for p in files: try: f = file(p, 'r') lines = f.readlines() f.close() if lines: # Lines may be blank mainkey = lines[0].split('=')[0].strip() pysrc = "\n".join(lines) exec(pysrc) exec("Registry.SetKey('%s', %s)" % (str(mainkey), mainkey)) except Exception, e: raise Warning(e) # Resend exception as warning
def LoadConfigData (key = None): """ Load config data from file(s) to the Registry dictionary. @type key: string @param key: a given key name. If None (default), all available keys are loaded. @returns: None """ _check_dir() import os if not key: files = \ [bsys.join(_CFG_DIR, f) for f in os.listdir(_CFG_DIR) if f.endswith(_EXT)] else: files = [] fname = bsys.join(_CFG_DIR, "%s%s" % (key, _EXT)) if bsys.exists(fname): files.append(fname) for p in files: try: f = file(p, 'r') lines = f.readlines() f.close() if lines: # Lines may be blank mainkey = lines[0].split('=')[0].strip() pysrc = "\n".join(lines) exec(pysrc) exec("Registry.SetKey('%s', %s)" % (str(mainkey), mainkey)) except Exception, e: raise Warning(e) # Resend exception as warning
def RemoveConfigData (key = None): """ Remove this key's config file from the <(u)datadir>/config/ folder. @type key: string @param key: the name of the key to be removed. If None (default) all available config files are deleted. """ _check_dir() if not key: files = \ [bsys.join(_CFG_DIR, f) for f in os.listdir(_CFG_DIR) if f.endswith(_EXT)] else: files = [] fname = bsys.join(_CFG_DIR, "%s%s" % (key, _EXT)) if bsys.exists(fname): files.append(fname) import os try: for p in files: os.remove(p) # remove the file(s) except Exception, e: raise Warning(e) # Resend exception as warning
def Warning_SaveOver(path): '''Returns - True to save, False dont save''' if sys.exists(sys.expandpath(path)): ret= Draw.PupMenu('Save over%t|' + path) if ret == -1: return False return True
def Warning_SaveOver(path): '''Returns - True to save, False dont save''' if sys.exists(sys.expandpath(path)): ret = Draw.PupMenu('Save over%t|' + path) if ret == -1: return False return True
def Error_NoFile(path): '''True if file missing, False if files there Use simply by doing... if Error_NoFile(path): return ''' if not sys.exists(sys.expandpath(path)): Draw.PupMenu("Error%t|Can't open file: " + path) return True return False
def Error_NoDir(path): '''True if dirs missing, False if dirs there Use simply by doing... if Error_NoDir(path): return ''' if not sys.exists(sys.expandpath(path)): Draw.PupMenu("Error%t|Path does not exist: " + path) return True return False
def select_file(filename): if sys.exists(filename) and _safeOverwrite: result = \ Draw.PupMenu("File Already Exists, Overwrite?%t|Yes%x1|No%x0") if (result != 1): return if not filename.endswith(extension): filename += extension wrlexport = VRML2Export(filename) wrlexport.export(scene, world, worldmat)
def select_file(filename): if sys.exists(filename) and _safeOverwrite: result = \ Draw.PupMenu("File Already Exists, Overwrite?%t|Yes%x1|No%x0") if(result != 1): return if not filename.endswith(extension): filename += extension wrlexport=VRML2Export(filename) wrlexport.export(scene, world, worldmat)
def fill_scripts_dict(): global ALL_SCRIPTS, ALL_GROUPS group = '' group_len = 0 sep = bsys.sep home = Blender.Get('homedir') if not home: errmsg = """ Can't find Blender's home dir and so can't find the Bpymenus file automatically stored inside it, which is needed by this script. Please run the Help -> System -> System Information script to get information about how to fix this. """ raise SystemError, errmsg fname = bsys.join(home, 'Bpymenus') if not bsys.exists(fname): return False f = file(fname, 'r') lines = f.readlines() f.close() for l in lines: if l.rfind('{') > 0: group = l.split()[0] ALL_GROUPS.append(group) group_len += 1 continue elif l[0] != "'": continue fields = l.split("'") if len(fields) > 2: menuname = fields[1].replace('...', '') fields = fields[2].split() if len(fields) > 1: fname = fields[1].split(sep)[-1] i = 1 while not fname.endswith('.py'): i += 1 fname = "%s %s" % (fname, fields[i]) ALL_SCRIPTS[fname] = (menuname, group_len - 1) return True
def imageLoad(path): #if path.endswith('\\') or path.endswith('/'): # raise 'INVALID PATH' if CONVERT_CALLBACK: path = CONVERT_CALLBACK(path) try: img = bpy.data.images.new(filename=path) if VERBOSE: print '\t\tImage loaded "%s"' % path return img except: if VERBOSE: if sys.exists(path): print '\t\tImage failed loading "%s", mabe its not a format blender can read.' % (path) else: print '\t\tImage not found, making a place holder "%s"' % (path) if PLACE_HOLDER: img= bpy.data.images.new(stripPath(path),4,4) img.filename= path return img #blank image else: return None
def fill_scripts_dict(): global ALL_SCRIPTS, ALL_GROUPS group = '' group_len = 0 sep = bsys.sep home = Blender.Get('homedir') if not home: errmsg = """ Can't find Blender's home dir and so can't find the Bpymenus file automatically stored inside it, which is needed by this script. Please run the Help -> System -> System Information script to get information about how to fix this. """ raise SystemError, errmsg fname = bsys.join(home, 'Bpymenus') if not bsys.exists(fname): return False f = file(fname, 'r') lines = f.readlines() f.close() for l in lines: if l.rfind('{') > 0: group = l.split()[0] ALL_GROUPS.append(group) group_len += 1 continue elif l[0] != "'": continue fields = l.split("'") if len(fields) > 2: menuname = fields[1].replace('...','') fields = fields[2].split() if len(fields) > 1: fname = fields[1].split(sep)[-1] i = 1 while not fname.endswith('.py'): i += 1 fname = "%s %s" % (fname, fields[i]) ALL_SCRIPTS[fname] = (menuname, group_len - 1) return True
def HasConfigData(key): """ Check if the given key exists, either already loaded in the Registry dict or as a file in the script data config dir. @type key: string @param key: a given key name. @returns: - 0: key does not exist; - 1: key exists in the Registry dict only; - 2: key exists as a file only; - 3: key exists in the Registry dict and also as a file. @note: for readability it's better to check against the constant bitmasks BPY_KEY_MISSING = 0, BPY_KEY_IN_REGISTRY = 1 and BPY_KEY_IN_FILE = 2. """ fname = bsys.join(_CFG_DIR, "%s%s" % (key, _EXT)) result = BPY_KEY_MISSING if key in Registry.Keys(): result |= BPY_KEY_IN_REGISTRY if bsys.exists(fname): result |= BPY_KEY_IN_FILE return result
def HasConfigData (key): """ Check if the given key exists, either already loaded in the Registry dict or as a file in the script data config dir. @type key: string @param key: a given key name. @returns: - 0: key does not exist; - 1: key exists in the Registry dict only; - 2: key exists as a file only; - 3: key exists in the Registry dict and also as a file. @note: for readability it's better to check against the constant bitmasks BPY_KEY_MISSING = 0, BPY_KEY_IN_REGISTRY = 1 and BPY_KEY_IN_FILE = 2. """ fname = bsys.join(_CFG_DIR, "%s%s" % (key, _EXT)) result = BPY_KEY_MISSING if key in Registry.Keys(): result |= BPY_KEY_IN_REGISTRY if bsys.exists(fname): result |= BPY_KEY_IN_FILE return result
folders scripts/, plugins/ and locale/ and files .Blanguages and .bfont.ttf are located. It's also where Blender stores the Bpymenus file with information about registered scripts, so it only needs to scan scripts dir(s) when they are modified. """ output.write(outmsg) has_uconfdir = False if has_dir['udatadir']: uconfigdir = bsys.join(Blender.Get('udatadir'), 'config') output.write("\n\n User defined config data dir:") if bsys.exists(uconfigdir): has_uconfdir = True output.write(" %s" % uconfigdir) else: notices += 1 output.write(""" <NOTICE> -- not found. bpydata/config/ should be inside the user defined scripts dir. It's used by Blender to store scripts configuration data. (Since it is on the user defined dir, a new Blender installation won't overwrite the data.) """) configdir = bsys.join(Blender.Get('datadir'), 'config') output.write('\n\n Default config data "bpydata/config/" dir:\n') if bsys.exists(configdir):
def comprehensiveImageLoad( imagePath, filePath, PLACE_HOLDER=True, RECURSIVE=True, VERBOSE=False, CONVERT_CALLBACK=None ): """ imagePath: The image filename If a path precedes it, this will be searched as well. filePath: is the directory where the image may be located - any file at teh end will be ignored. PLACE_HOLDER: if True a new place holder image will be created. this is usefull so later you can relink the image to its original data. VERBOSE: If True debug info will be printed. RECURSIVE: If True, directories will be recursivly searched. Be carefull with this if you have files in your root directory because it may take a long time. CASE_INSENSITIVE: for non win32 systems, find the correct case for the file. CONVERT_CALLBACK: a function that takes an existing path and returns a new one. Use this when loading image formats blender may not support, the CONVERT_CALLBACK can take the path for a GIF (for example), convert it to a PNG and return the PNG's path. For formats blender can read, simply return the path that is given. """ # VERBOSE = True if VERBOSE: print "img:", imagePath, "file:", filePath if os == None and CASE_INSENSITIVE: CASE_INSENSITIVE = True # When we have the file load it with this. try/except niceness. def imageLoad(path): # if path.endswith('\\') or path.endswith('/'): # raise 'INVALID PATH' if CONVERT_CALLBACK: path = CONVERT_CALLBACK(path) try: img = bpy.data.images.new(filename=path) if VERBOSE: print '\t\tImage loaded "%s"' % path return img except: if VERBOSE: if sys.exists(path): print '\t\tImage failed loading "%s", mabe its not a format blender can read.' % (path) else: print '\t\tImage not found, making a place holder "%s"' % (path) if PLACE_HOLDER: img = bpy.data.images.new(stripPath(path), 4, 4) img.filename = path return img # blank image else: return None # Image formats blender can read IMAGE_EXT = [ "jpg", "jpeg", "png", "tga", "bmp", "rgb", "sgi", "bw", "iff", "lbm", # Blender Internal "gif", "psd", "tif", "tiff", "pct", "pict", "pntg", "qtif", ] # Quacktime, worth a try. imageFileName = stripPath(imagePath) # image path only imageFileName_lower = imageFileName.lower() # image path only if VERBOSE: print '\tSearchingExisting Images for "%s"' % imagePath for i in bpy.data.images: if stripPath(i.filename.lower()) == imageFileName_lower: if VERBOSE: print "\t\tUsing existing image." return i if VERBOSE: print '\tAttempting to load "%s"' % imagePath if sys.exists(imagePath): if VERBOSE: print '\t\tFile found where expected "%s".' % imagePath return imageLoad(imagePath) imageFileName_noext = stripExt(imageFileName) # With no extension. imageFileName_noext_lower = stripExt(imageFileName_lower) # With no extension. imageFilePath = stripFile(imagePath) # Remove relative path from image path if imageFilePath.startswith("./") or imageFilePath.startswith(".\\"): imageFilePath = imageFilePath[2:] # Attempt to load from obj path. tmpPath = stripFile(filePath) + stripPath(imageFileName) if sys.exists(tmpPath): if VERBOSE: print '\t\tFile found in path (1)"%s".' % tmpPath return imageLoad(tmpPath) # os needed if we go any further. if not os: if VERBOSE: print '\t\tCreating a placeholder with a face path: "%s".' % imagePath return imageLoad(imagePath) # Will jus treturn a placeholder. # We have os. # GATHER PATHS. paths = {} # Store possible paths we may use, dict for no doubles. tmpPath = addSlash(sys.expandpath("//")) # Blenders path if sys.exists(tmpPath): if VERBOSE: print "\t\tSearching in %s" % tmpPath paths[tmpPath] = [os.listdir(tmpPath)] # Orig name for loading paths[tmpPath].append([f.lower() for f in paths[tmpPath][0]]) # Lower case list. paths[tmpPath].append([stripExt(f) for f in paths[tmpPath][1]]) # Lower case no ext else: if VERBOSE: print '\tNo Path: "%s"' % tmpPath tmpPath = imageFilePath if sys.exists(tmpPath): if VERBOSE: print "\t\tSearching in %s" % tmpPath paths[tmpPath] = [os.listdir(tmpPath)] # Orig name for loading paths[tmpPath].append([f.lower() for f in paths[tmpPath][0]]) # Lower case list. paths[tmpPath].append([stripExt(f) for f in paths[tmpPath][1]]) # Lower case no ext else: if VERBOSE: print '\tNo Path: "%s"' % tmpPath tmpPath = stripFile(filePath) if sys.exists(tmpPath): if VERBOSE: print "\t\tSearching in %s" % tmpPath paths[tmpPath] = [os.listdir(tmpPath)] # Orig name for loading paths[tmpPath].append([f.lower() for f in paths[tmpPath][0]]) # Lower case list. paths[tmpPath].append([stripExt(f) for f in paths[tmpPath][1]]) # Lower case no ext else: if VERBOSE: print '\tNo Path: "%s"' % tmpPath tmpPath = addSlash(bpy.config.textureDir) if tmpPath and sys.exists(tmpPath): if VERBOSE: print "\t\tSearching in %s" % tmpPath paths[tmpPath] = [os.listdir(tmpPath)] # Orig name for loading paths[tmpPath].append([f.lower() for f in paths[tmpPath][0]]) # Lower case list. paths[tmpPath].append([stripExt(f) for f in paths[tmpPath][1]]) # Lower case no ext else: if VERBOSE: print '\tNo Path: "%s"' % tmpPath # Add path if relative image patrh was given. tmp_paths = paths.keys() for k in tmp_paths: tmpPath = k + imageFilePath if sys.exists(tmpPath): paths[tmpPath] = [os.listdir(tmpPath)] # Orig name for loading paths[tmpPath].append([f.lower() for f in paths[tmpPath][0]]) # Lower case list. paths[tmpPath].append([stripExt(f) for f in paths[tmpPath][1]]) # Lower case no ext else: if VERBOSE: print '\tNo Path: "%s"' % tmpPath # DONE # for path, files in paths.iteritems(): if sys.exists(path + imageFileName): if VERBOSE: print '\tFound image at path: "%s" file" "%s"' % (path, imageFileName) return imageLoad(path + imageFileName) # If the files not there then well do a case insensitive seek. filesOrigCase = files[0] filesLower = files[1] filesLowerNoExt = files[2] # We are going to try in index the file directly, if its not there just keep on index = None try: # Is it just a case mismatch? index = filesLower.index(imageFileName_lower) except: try: # Have the extensions changed? index = filesLowerNoExt.index(imageFileName_noext_lower) ext = getExt(filesLower[index]) # Get the extension of the file that matches all but ext. # Check that the ext is useable eg- not a 3ds file :) if ext.lower() not in IMAGE_EXT: index = None except: index = None if index != None: tmpPath = path + filesOrigCase[index] img = imageLoad(tmpPath) if img != None: if VERBOSE: print '\t\tImage Found "%s"' % tmpPath return img if RECURSIVE: # IMAGE NOT FOUND IN ANY OF THE DIRS!, DO A RECURSIVE SEARCH. if VERBOSE: print "\t\tImage Not Found in any of the dirs, doing a recusrive search" for path in paths.iterkeys(): # Were not going to use files if path == "/" or len(path) == 3 and path[1:] == ":\\": continue # print path , 'ASS' # ------------------ # finds the file starting at the root. # def findImage(findRoot, imagePath): # W--------------- # ROOT, DIRS, FILES pathWalk = os.walk(path) pathList = [True] matchList = [] # Store a list of (match, size), choose the biggest. while True: try: pathList = pathWalk.next() except: break for file in pathList[2]: file_lower = file.lower() # FOUND A MATCH if (file_lower == imageFileName_lower) or ( stripExt(file_lower) == imageFileName_noext_lower and getExt(file_lower) in IMAGE_EXT ): name = pathList[0] + sys.sep + file size = os.path.getsize(name) if VERBOSE: print "\t\t\tfound:", name matchList.append((name, size)) if matchList: # Sort by file size matchList.sort(lambda A, B: cmp(B[1], A[1])) if VERBOSE: print '\t\tFound "%s"' % matchList[0][0] # Loop through all we have found img = None for match in matchList: img = imageLoad(match[0]) # 0 - first, 0 - pathname if img != None: break return img # No go. if VERBOSE: print '\t\tImage Not Found after looking everywhere! "%s"' % imagePath return imageLoad(imagePath) # Will jus treturn a placeholder.
def edit_extern(image=None): if not image: image = Image.GetCurrent() if not image: # Image is None Draw.PupMenu('ERROR: Please select active Image.') return if image.packed: Draw.PupMenu('ERROR: Image is packed, unpack before editing.') return imageFileName = sys.expandpath( image.filename ) if not sys.exists(imageFileName): Draw.PupMenu('ERROR: Image path does not exist.') return pupblock = [imageFileName.split('/')[-1].split('\\')[-1]] new_text= False try: appstring = Registry.GetKey('ExternalImageEditor', True) appstring = appstring['path'] # for ZanQdo if he removed the path from the textbox totaly. ;) - Cam if not appstring or appstring.find('%f')==-1: new_text= True except: new_text= True if new_text: pupblock.append('first time, set path.') if platform == 'win32': # Example of path to popular image editor... ;-) # appstring = '"C:\\Program Files\\Adobe\\Photoshop CS\\photoshop.exe" "%f"' # Have to add "cmd /c" to make sure we're using Windows shell. appstring = 'cmd /c start "" /B "%f"' elif platform == 'darwin': appstring = 'open "%f"' else: appstring = 'gimp %f' appstring_but = Draw.Create(appstring) save_default_but = Draw.Create(0) pupblock.append(('editor: ', appstring_but, 0, 99, 'Path to application, %f will be replaced with the image path.')) pupblock.append(('Set Default', save_default_but, 'Store this path in the blender registry.')) # Only configure if Shift is held, if Blender.Window.GetKeyQualifiers() & Blender.Window.Qual.SHIFT: if not Draw.PupBlock('External Image Editor...', pupblock): return appstring = appstring_but.val save_default= save_default_but.val if save_default: Registry.SetKey('ExternalImageEditor', {'path':appstring}, True) if appstring.find('%f') == -1: Draw.PupMenu('ERROR: No filename specified! ("%f")') return # ------------------------------- os_run(appstring, imageFileName)
def load_data(file): # global import_dir,weather global import_dir, tipo for line in file: if line.find('Type') >= 0: tipo = line.split('=')[1].replace('"', '').replace(' ', '') found = 1 break # if not found: # weather = 'DF' file.next() for line in file: if line.find('Materials') >= 0: materials = int(line.split('=')[1]) found = 1 break file.next() for mt in range(materials): line = file.next() m = mat() m.name = "%s" % line.split()[0] if len(line.split()) == 2: m.tex = line.split()[1] elif len(line.split()) > 2: m.tex = line.split()[1] for n in xrange(len(line.split()) - 2): m.tex += " " + line.split()[n + 2] else: Blender.Draw.PupMenu('Error: Loading textures.') return -1 m.tex = m.tex.replace('"', '') if not bsys.exists(m.tex): Blender.Draw.PupMenu('Error:' + m.tex + ' not found.') return -1 mats.append(m) for line in file: if line.find('Meshes') >= 0: meshes = int(line.split('=')[1]) found = 1 break if not found: Blender.Draw.PupMenu('Meshes not found in file') return -1 file.next() for objs in range(meshes): line = file.next() line = line.split('=')[1] g = grp() g.name = line.split()[0].replace('"', '') g.obj_count = int(line.split()[1]) for gr in range(g.obj_count): new = Obj() new.vlist = [] new.uvlist = [] new.vcol = [] new.flist = [] vertex = 0 faces = 0 line = file.next() new.name = g.name + '-' + line.split()[0] new.mat = line.split()[1] line = file.next() vertex = int(line) for ver in range(vertex): line = file.next() try: x, y, z, u, v = float(line.split()[0]), float( line.split()[1]), float(line.split()[2]), float( line.split()[3]), 1 - float(line.split()[4]) new.vlist.append((x, y, z)) new.uvlist.append((u, v)) new.vcol.append(line.split()[5]) except: Blender.Draw.PupMenu('Error importing Vertex list.') return -1 line = file.next() faces = int(line) for fac in range(faces): try: line = file.next() if len(map(int, line.split())) > 3: a, b, c, d = map(int, line.split()) new.flist.append((a, b, c, d)) else: a, b, c = map(int, line.split()) new.flist.append((a, b, c)) except: Blender.Draw.PupMenu('Error importing Faces.') return -1 g.obj_list.append(new) groups.append(g) mats.sort() found = -1 return 1
def create_materials(filepath, material_libs, unique_materials, unique_material_images, IMAGE_SEARCH): ''' Create all the used materials in this obj, assign colors and images to the materials from all referenced material libs ''' DIR = stripFile(filepath) #==================================================================================# # This function sets textures defined in .mtl file # #==================================================================================# def load_material_image(blender_material, context_material_name, imagepath, type): texture = bpy.data.textures.new(type) texture.setType('Image') # Absolute path - c:\.. etc would work here image = obj_image_load(imagepath, DIR, IMAGE_SEARCH) has_data = image.has_data texture.image = image if not has_data: try: # first time using this image. We need to load it first image.glLoad() except: # probably the image is crashed pass else: has_data = image.has_data # Adds textures for materials (rendering) if type == 'Kd': if has_data and image.depth == 32: # Image has alpha blender_material.setTexture( 0, texture, Texture.TexCo.UV, Texture.MapTo.COL | Texture.MapTo.ALPHA) texture.setImageFlags('MipMap', 'InterPol', 'UseAlpha') blender_material.mode |= Material.Modes.ZTRANSP blender_material.alpha = 0.0 else: blender_material.setTexture(0, texture, Texture.TexCo.UV, Texture.MapTo.COL) # adds textures to faces (Textured/Alt-Z mode) # Only apply the diffuse texture to the face if the image has not been set with the inline usemat func. unique_material_images[ context_material_name] = image, has_data # set the texface image elif type == 'Ka': blender_material.setTexture( 1, texture, Texture.TexCo.UV, Texture.MapTo.CMIR) # TODO- Add AMB to BPY API elif type == 'Ks': blender_material.setTexture(2, texture, Texture.TexCo.UV, Texture.MapTo.SPEC) elif type == 'Bump': blender_material.setTexture(3, texture, Texture.TexCo.UV, Texture.MapTo.NOR) elif type == 'D': blender_material.setTexture(4, texture, Texture.TexCo.UV, Texture.MapTo.ALPHA) blender_material.mode |= Material.Modes.ZTRANSP blender_material.alpha = 0.0 # Todo, unset deffuse material alpha if it has an alpha channel elif type == 'refl': blender_material.setTexture(5, texture, Texture.TexCo.UV, Texture.MapTo.REF) # Add an MTL with the same name as the obj if no MTLs are spesified. temp_mtl = stripExt(stripPath(filepath)) + '.mtl' if sys.exists(DIR + temp_mtl) and temp_mtl not in material_libs: material_libs.append(temp_mtl) del temp_mtl #Create new materials for name in unique_materials: # .keys() if name != None: unique_materials[name] = bpy.data.materials.new(name) unique_material_images[ name] = None, False # assign None to all material images to start with, add to later. unique_materials[None] = None unique_material_images[None] = None, False for libname in material_libs: mtlpath = DIR + libname if not sys.exists(mtlpath): #print '\tError Missing MTL: "%s"' % mtlpath pass else: #print '\t\tloading mtl: "%s"' % mtlpath context_material = None mtl = open(mtlpath, 'rU') for line in mtl: #.xreadlines(): if line.startswith('newmtl'): context_material_name = line_value(line.split()) if unique_materials.has_key(context_material_name): context_material = unique_materials[ context_material_name] else: context_material = None elif context_material: # we need to make a material to assign properties to it. line_split = line.split() line_lower = line.lower().lstrip() if line_lower.startswith('ka'): context_material.setMirCol( (float(line_split[1]), float(line_split[2]), float(line_split[3]))) elif line_lower.startswith('kd'): context_material.setRGBCol( (float(line_split[1]), float(line_split[2]), float(line_split[3]))) elif line_lower.startswith('ks'): context_material.setSpecCol( (float(line_split[1]), float(line_split[2]), float(line_split[3]))) elif line_lower.startswith('ns'): context_material.setHardness( int((float(line_split[1]) * 0.51))) elif line_lower.startswith('ni'): # Refraction index context_material.setIOR( max(1, min(float(line_split[1]), 3))) # Between 1 and 3 elif line_lower.startswith('d') or line_lower.startswith( 'tr'): context_material.setAlpha(float(line_split[1])) context_material.mode |= Material.Modes.ZTRANSP elif line_lower.startswith('map_ka'): img_filepath = line_value(line.split()) if img_filepath: load_material_image(context_material, context_material_name, img_filepath, 'Ka') elif line_lower.startswith('map_ks'): img_filepath = line_value(line.split()) if img_filepath: load_material_image(context_material, context_material_name, img_filepath, 'Ks') elif line_lower.startswith('map_kd'): img_filepath = line_value(line.split()) if img_filepath: load_material_image(context_material, context_material_name, img_filepath, 'Kd') elif line_lower.startswith('map_bump'): img_filepath = line_value(line.split()) if img_filepath: load_material_image(context_material, context_material_name, img_filepath, 'Bump') elif line_lower.startswith( 'map_d') or line_lower.startswith( 'map_tr'): # Alpha map - Dissolve img_filepath = line_value(line.split()) if img_filepath: load_material_image(context_material, context_material_name, img_filepath, 'D') elif line_lower.startswith('refl'): # Reflectionmap img_filepath = line_value(line.split()) if img_filepath: load_material_image(context_material, context_material_name, img_filepath, 'refl') mtl.close()
def create_materials(filepath, material_libs, unique_materials, unique_material_images, IMAGE_SEARCH): ''' Create all the used materials in this obj, assign colors and images to the materials from all referenced material libs ''' DIR= stripFile(filepath) #==================================================================================# # This function sets textures defined in .mtl file # #==================================================================================# def load_material_image(blender_material, context_material_name, imagepath, type): texture= bpy.data.textures.new(type) texture.setType('Image') # Absolute path - c:\.. etc would work here image= obj_image_load(imagepath, DIR, IMAGE_SEARCH) has_data = image.has_data texture.image = image if not has_data: try: # first time using this image. We need to load it first image.glLoad() except: # probably the image is crashed pass else: has_data = image.has_data # Adds textures for materials (rendering) if type == 'Kd': if has_data and image.depth == 32: # Image has alpha blender_material.setTexture(0, texture, Texture.TexCo.UV, Texture.MapTo.COL | Texture.MapTo.ALPHA) texture.setImageFlags('MipMap', 'InterPol', 'UseAlpha') blender_material.mode |= Material.Modes.ZTRANSP blender_material.alpha = 0.0 else: blender_material.setTexture(0, texture, Texture.TexCo.UV, Texture.MapTo.COL) # adds textures to faces (Textured/Alt-Z mode) # Only apply the diffuse texture to the face if the image has not been set with the inline usemat func. unique_material_images[context_material_name]= image, has_data # set the texface image elif type == 'Ka': blender_material.setTexture(1, texture, Texture.TexCo.UV, Texture.MapTo.CMIR) # TODO- Add AMB to BPY API elif type == 'Ks': blender_material.setTexture(2, texture, Texture.TexCo.UV, Texture.MapTo.SPEC) elif type == 'Bump': blender_material.setTexture(3, texture, Texture.TexCo.UV, Texture.MapTo.NOR) elif type == 'D': blender_material.setTexture(4, texture, Texture.TexCo.UV, Texture.MapTo.ALPHA) blender_material.mode |= Material.Modes.ZTRANSP blender_material.alpha = 0.0 # Todo, unset deffuse material alpha if it has an alpha channel elif type == 'refl': blender_material.setTexture(5, texture, Texture.TexCo.UV, Texture.MapTo.REF) # Add an MTL with the same name as the obj if no MTLs are spesified. temp_mtl= stripExt(stripPath(filepath))+ '.mtl' if sys.exists(DIR + temp_mtl) and temp_mtl not in material_libs: material_libs.append( temp_mtl ) del temp_mtl #Create new materials for name in unique_materials: # .keys() if name != None: unique_materials[name]= bpy.data.materials.new(name) unique_material_images[name]= None, False # assign None to all material images to start with, add to later. unique_materials[None]= None unique_material_images[None]= None, False for libname in material_libs: mtlpath= DIR + libname if not sys.exists(mtlpath): #print '\tError Missing MTL: "%s"' % mtlpath pass else: #print '\t\tloading mtl: "%s"' % mtlpath context_material= None mtl= open(mtlpath, 'rU') for line in mtl: #.xreadlines(): if line.startswith('newmtl'): context_material_name= line_value(line.split()) if unique_materials.has_key(context_material_name): context_material = unique_materials[ context_material_name ] else: context_material = None elif context_material: # we need to make a material to assign properties to it. line_split= line.split() line_lower= line.lower().lstrip() if line_lower.startswith('ka'): context_material.setMirCol((float(line_split[1]), float(line_split[2]), float(line_split[3]))) elif line_lower.startswith('kd'): context_material.setRGBCol((float(line_split[1]), float(line_split[2]), float(line_split[3]))) elif line_lower.startswith('ks'): context_material.setSpecCol((float(line_split[1]), float(line_split[2]), float(line_split[3]))) elif line_lower.startswith('ns'): context_material.setHardness( int((float(line_split[1])*0.51)) ) elif line_lower.startswith('ni'): # Refraction index context_material.setIOR( max(1, min(float(line_split[1]), 3))) # Between 1 and 3 elif line_lower.startswith('d') or line_lower.startswith('tr'): context_material.setAlpha(float(line_split[1])) context_material.mode |= Material.Modes.ZTRANSP elif line_lower.startswith('map_ka'): img_filepath= line_value(line.split()) if img_filepath: load_material_image(context_material, context_material_name, img_filepath, 'Ka') elif line_lower.startswith('map_ks'): img_filepath= line_value(line.split()) if img_filepath: load_material_image(context_material, context_material_name, img_filepath, 'Ks') elif line_lower.startswith('map_kd'): img_filepath= line_value(line.split()) if img_filepath: load_material_image(context_material, context_material_name, img_filepath, 'Kd') elif line_lower.startswith('map_bump'): img_filepath= line_value(line.split()) if img_filepath: load_material_image(context_material, context_material_name, img_filepath, 'Bump') elif line_lower.startswith('map_d') or line_lower.startswith('map_tr'): # Alpha map - Dissolve img_filepath= line_value(line.split()) if img_filepath: load_material_image(context_material, context_material_name, img_filepath, 'D') elif line_lower.startswith('refl'): # Reflectionmap img_filepath= line_value(line.split()) if img_filepath: load_material_image(context_material, context_material_name, img_filepath, 'refl') mtl.close()
def fs_callback(filename): global EXPORT_DIR if not filename.endswith('.fef'): filename = '%s.fef' % filename if bsys.exists(filename): if Blender.Draw.PupMenu('OVERWRITE?%t|File exists') != 1: return editmode = Blender.Window.EditMode() # are we in edit mode? If so ... if editmode: Blender.Window.EditMode(0) # leave edit mode before getting the mesh starttime = bsys.time() export_dir = bsys.dirname(filename) if export_dir != EXPORT_DIR: EXPORT_DIR = export_dir update_RegistryInfo() objs_count = 0 for o in objs: objs_count += 1 #Order parts to assing textures starting from LEFT_EYE grp_mat = ["F00", "F01", "F02", "F03", "F04", "F05", "F06"] #Ordered Parts to meet order in faces grp_names = ["F00", "F01", "F02", "F03", "F04", "F05", "F06"] name = "F00 %x0|F01 %x1|F02 %x2|F03 %x3|F04 %x4|F05 %x5|F06 %x6" new_names = ["F00", "F01", "F02", "F03", "F04", "F05", "F06"] #asign array names tmp_name = '' #check for correct names for o in objs: if o.getType() == "Empty": if o.getName() not in (grp_names): tmp_name = "Part Name %s is wrong, Please Select the one that matches. " % o.getName( ) tmp_name += "%t|" tmp_name += name result = Blender.Draw.PupMenu(tmp_name, 10) if result != -1: o.setName(new_names[result]) else: return del new_names del name del tmp_name Blender.Window.WaitCursor(1) for o in objs: g = grp() g.name = o.getName() if load_objs(o, g) == -1: return groups.append(g) if len(mat_list) > 51: Blender.Draw.PupMenu( 'ERROR:%t| Cant use more than 51 Textures,|%l|Please, fix it before export. ' ) return groups_ordered_mat = [] for order in range(len(grp_mat)): for gr in groups: if gr.name == grp_mat[order]: groups_ordered_mat.append(gr) break tipo = tp.getName() tipo = tipo.split('-')[1] if tipo[0] == "F": tex_id = 0x2752 else: tex_id = 0x2753 for gr in groups_ordered_mat: gr.obj_list.sort(key=lambda obj: obj.name) for o in gr.obj_list: for m in mat_list: if o.tex == m.texture: if m.newname == '': m.newname = "%04x" % tex_id tex_id += 1 o.tex = m.newname break mat_list.sort(key=lambda obj: obj.newname) groups_ordered = [] for order in range(len(grp_names)): for gr in groups_ordered_mat: if gr.name == grp_names[order]: groups_ordered.append(gr) break del groups_ordered_mat file = open(filename, "w") file.write("//Face and Hair Exchange File (c)2010 by Skunk\n\n") tipo = tp.getName() tipo = tipo.split('-')[1] file.write("Type = \"%s\"\n\n" % tipo.replace("\n", "")) file.write("Materials = %d\n\n" % len(mat_list)) for m in mat_list: file.write("%s \"%s\"\n" % (m.newname, m.texture)) o_count = 0 for gr_o in groups_ordered: if gr_o.obj_count > 0: o_count += 1 file.write("\nMeshes = %d\n\n" % o_count) for gr_o in groups_ordered: save_file(file, gr_o) file.close() endtime = bsys.time() - starttime print "Data exported in %.3f seconds." % endtime Blender.Window.WaitCursor(0) return
# Image formats blender can read IMAGE_EXT = ['jpg', 'jpeg', 'png', 'tga', 'bmp', 'rgb', 'sgi', 'bw', 'iff', 'lbm', # Blender Internal 'gif', 'psd', 'tif', 'tiff', 'pct', 'pict', 'pntg', 'qtif'] # Quacktime, worth a try. imageFileName = stripPath(imagePath) # image path only imageFileName_lower = imageFileName.lower() # image path only if VERBOSE: print '\tSearchingExisting Images for "%s"' % imagePath for i in bpy.data.images: if stripPath(i.filename.lower()) == imageFileName_lower: if VERBOSE: print '\t\tUsing existing image.' return i if VERBOSE: print '\tAttempting to load "%s"' % imagePath if sys.exists(imagePath): if VERBOSE: print '\t\tFile found where expected "%s".' % imagePath return imageLoad(imagePath) imageFileName_noext = stripExt(imageFileName) # With no extension. imageFileName_noext_lower = stripExt(imageFileName_lower) # With no extension. imageFilePath = stripFile(imagePath) # Remove relative path from image path if imageFilePath.startswith('./') or imageFilePath.startswith('.\\'): imageFilePath = imageFilePath[2:] # Attempt to load from obj path.
def testAC3DImport(self): FACE_TWOSIDE = Mesh.FaceModes['TWOSIDE'] FACE_TEX = Mesh.FaceModes['TEX'] MESH_AUTOSMOOTH = Mesh.Modes['AUTOSMOOTH'] MAT_MODE_ZTRANSP = Material.Modes['ZTRANSP'] MAT_MODE_TRANSPSHADOW = Material.Modes['TRANSPSHADOW'] scene = self.scene bl_images = {} # loaded texture images missing_textures = [] # textures we couldn't find objlist = self.objlist[1:] # skip 'world' bmat = [] has_transp_mats = False for mat in self.mlist: name = mat[0] m = Material.New(name) m.rgbCol = (mat[1][0], mat[1][1], mat[1][2]) m.amb = mat[2] m.emit = mat[3] m.specCol = (mat[4][0], mat[4][1], mat[4][2]) m.spec = mat[5] m.alpha = mat[6] if m.alpha < 1.0: m.mode |= MAT_MODE_ZTRANSP has_transp_mats = True bmat.append(m) if has_transp_mats: for mat in bmat: mat.mode |= MAT_MODE_TRANSPSHADOW obj_idx = 0 # index of current obj in loop for obj in objlist: if obj.type == AC_GROUP: continue elif obj.type == AC_LIGHT: light = Lamp.New('Lamp') object = scene.objects.new(light, obj.name) #object.select(True) obj.bl_obj = object if obj.data: light.name = obj.data continue # type AC_POLY: # old .ac files used empty meshes as groups, convert to a real ac group if not obj.vlist and obj.kids: obj.type = AC_GROUP continue mesh = Mesh.New() object = scene.objects.new(mesh, obj.name) #object.select(True) obj.bl_obj = object if obj.data: mesh.name = obj.data mesh.degr = obj.crease # will auto clamp to [1, 80] if not obj.vlist: # no vertices? nothing more to do continue mesh.verts.extend(obj.vlist) objmat_indices = [] for mat in bmat: if bmat.index(mat) in obj.matlist: objmat_indices.append(bmat.index(mat)) mesh.materials += [mat] if DISPLAY_TRANSP and mat.alpha < 1.0: object.transp = True for e in obj.elist: mesh.edges.extend(e) if obj.flist_v: mesh.faces.extend(obj.flist_v) facesnum = len(mesh.faces) if facesnum == 0: # shouldn't happen, of course continue mesh.faceUV = True # checking if the .ac file had duplicate faces (Blender ignores them) if facesnum != len(obj.flist_v): # it has, ugh. Let's clean the uv list: lenfl = len(obj.flist_v) flist = obj.flist_v uvlist = obj.flist_uv cfglist = obj.flist_cfg for f in flist: f.sort() fi = lenfl while fi > 0: # remove data related to duplicates fi -= 1 if flist[fi] in flist[:fi]: uvlist.pop(fi) cfglist.pop(fi) img = None if obj.tex != '': if obj.tex in bl_images.keys(): img = bl_images[obj.tex] elif obj.tex not in missing_textures: texfname = None objtex = obj.tex baseimgname = bsys.basename(objtex) if bsys.exists(objtex) == 1: texfname = objtex elif bsys.exists(bsys.join(self.importdir, objtex)): texfname = bsys.join(self.importdir, objtex) else: if baseimgname.find('\\') > 0: baseimgname = bsys.basename(objtex.replace('\\','/')) objtex = bsys.join(self.importdir, baseimgname) if bsys.exists(objtex) == 1: texfname = objtex else: objtex = bsys.join(TEXTURES_DIR, baseimgname) if bsys.exists(objtex): texfname = objtex if texfname: try: img = Image.Load(texfname) # Commented because it's unnecessary: #img.xrep = int(obj.texrep[0]) #img.yrep = int(obj.texrep[1]) if img: bl_images[obj.tex] = img except: inform("Couldn't load texture: %s" % baseimgname) else: missing_textures.append(obj.tex) inform("Couldn't find texture: %s" % baseimgname) for i in range(facesnum): f = obj.flist_cfg[i] fmat = f[0] is_smooth = f[1] twoside = f[2] bface = mesh.faces[i] bface.smooth = is_smooth if twoside: bface.mode |= FACE_TWOSIDE if img: bface.mode |= FACE_TEX bface.image = img bface.mat = objmat_indices.index(fmat) fuv = obj.flist_uv[i] if obj.texoff: uoff = obj.texoff[0] voff = obj.texoff[1] urep = obj.texrep[0] vrep = obj.texrep[1] for uv in fuv: uv[0] *= urep uv[1] *= vrep uv[0] += uoff uv[1] += voff mesh.faces[i].uv = fuv # finally, delete the 1st vertex we added to prevent vindices == 0 mesh.verts.delete(0) mesh.calcNormals() mesh.mode = MESH_AUTOSMOOTH # subdiv: create SUBSURF modifier in Blender if SUBDIV and obj.subdiv > 0: subdiv = obj.subdiv subdiv_render = subdiv # just to be safe: if subdiv_render > 6: subdiv_render = 6 if subdiv > 3: subdiv = 3 modif = object.modifiers.append(Modifier.Types.SUBSURF) modif[Modifier.Settings.LEVELS] = subdiv modif[Modifier.Settings.RENDLEVELS] = subdiv_render obj_idx += 1 self.build_hierarchy() scene.update()
# # Check the Blender.Registry documentation for more information. import Blender from Blender import Registry, sys as bsys _EXT = '.cfg' # file extension for saved config data # limits: #MAX_ITEMS_NUM = 60 # max number of keys per dict and itens per list and tuple #MAX_STR_LEN = 300 # max string length (remember this is just for config data) _CFG_DIR = '' if Blender.Get('udatadir'): _CFG_DIR = Blender.sys.join(Blender.Get('udatadir'), 'config') if not _CFG_DIR or not bsys.exists(_CFG_DIR): _CFG_DIR = Blender.sys.join(Blender.Get('datadir'), 'config') if not bsys.exists(_CFG_DIR): _CFG_DIR = '' # to compare against, so we don't write to a cvs tree: _CVS_SUBPATH = 'release/scripts/bpydata/config/' if bsys.dirsep == '\\': _CVS_SUBPATH = _CVS_SUBPATH.replace('/', '\\') _KEYS = [k for k in Registry.Keys() if k[0] != '_'] # _ITEMS_NUM = 0 def _sanitize(o):
def parse_help_info(script): global PATHS, SCRIPT_INFO if script.userdir: path = PATHS['uscripts'] else: path = PATHS['scripts'] fname = bsys.join(path, script.fname) if not bsys.exists(fname): Draw.PupMenu('IO Error: couldn\'t find script %s' % fname) return None f = file(fname, 'r') lines = f.readlines() f.close() # fix line endings: if lines[0].find('\r'): unixlines = [] for l in lines: unixlines.append(l.replace('\r', '')) lines = unixlines llen = len(lines) has_doc = 0 doc_data = { '__author__': '', '__version__': '', '__url__': '', '__email__': '', '__bpydoc__': '', '__doc__': '' } i = 0 while i < llen: l = lines[i] incr = 1 for k in doc_data.keys(): if l.find(k, 0, 20) == 0: value, incr = parse_pyobj(k, lines, i) exec("doc_data['%s'] = %s" % (k, value)) has_doc = 1 break i += incr # fix these to seqs, simplifies coding elsewhere for w in ['__author__', '__url__', '__email__']: val = doc_data[w] if val and type(val) == str: doc_data[w] = [doc_data[w]] if not doc_data['__bpydoc__']: if doc_data['__doc__']: doc_data['__bpydoc__'] = doc_data['__doc__'] if has_doc: # any data, maybe should confirm at least doc/bpydoc info = BPy_Info(script, doc_data) SCRIPT_INFO = info return True else: return False
def testAC3DImport(self): FACE_TWOSIDE = Mesh.FaceModes['TWOSIDE'] FACE_TEX = Mesh.FaceModes['TILES'] #FACE_TEX = Mesh.FaceModes['TEX'] MESH_AUTOSMOOTH = Mesh.Modes['AUTOSMOOTH'] MAT_MODE_ZTRANSP = Material.Modes['ZTRANSP'] MAT_MODE_TRANSPSHADOW = Material.Modes['TRANSPSHADOW'] scene = self.scene bl_images = {} # loaded texture images missing_textures = [] # textures we couldn't find bl_textures = {} # loaded textures objlist = self.objlist[1:] # skip 'world' #bmat = [] bmat = {} m = None has_transp_mats = False for mat in self.mlist: name = mat[0] # if name=='': name = 'BaseMaterial' if m == None: m = Material.New(name) m.rgbCol = (mat[1][0], mat[1][1], mat[1][2]) m.amb = mat[2] m.emit = mat[3] m.specCol = (mat[4][0], mat[4][1], mat[4][2]) m.spec = mat[5] m.alpha = mat[6] #force it to zero because that is how Speed Dreams / Torcs work m.alpha = 0.0 if m.alpha < 1.0: m.mode |= MAT_MODE_ZTRANSP has_transp_mats = True # bmat[name]=m # if has_transp_mats: # for mat in bmat: # mat.mode |= MAT_MODE_TRANSPSHADOW obj_idx = 0 # index of current obj in loop for obj in objlist: if obj.type == AC_GROUP: continue elif obj.type == AC_LIGHT: light = Lamp.New('Lamp') object = scene.objects.new(light, obj.name) #object.select(True) obj.bl_obj = object if obj.data: light.name = obj.data continue # type AC_POLY: # old .ac files used empty meshes as groups, convert to a real ac group if not obj.vlist and obj.kids: obj.type = AC_GROUP continue mesh = Mesh.New() object = scene.objects.new(mesh, obj.name) #object.select(True) obj.bl_obj = object if obj.data: mesh.name = obj.data mesh.degr = obj.crease # will auto clamp to [1, 80] if not obj.vlist: # no vertices? nothing more to do continue #Setup UV Layers mesh.addUVLayer("ImageUV") mesh.addUVLayer("ShadowUV") mesh.activeUVLayer = "ImageUV" mesh.verts.extend(obj.vlist) objmat_indices = [] for e in obj.elist: mesh.edges.extend(e) if obj.flist_v: mesh.faces.extend(obj.flist_v) facesnum = len(mesh.faces) if facesnum == 0: # shouldn't happen, of course continue mesh.faceUV = True # checking if the .ac file had duplicate faces (Blender ignores them) if facesnum != len(obj.flist_v): # it has, ugh. Let's clean the uv list: lenfl = len(obj.flist_v) flist = obj.flist_v uvlist = obj.flist_uv uvlist2 = obj.flist_uv2 cfglist = obj.flist_cfg for f in flist: f.sort() fi = lenfl while fi > 0: # remove data related to duplicates fi -= 1 if flist[fi] in flist[:fi]: uvlist.pop(fi) cfglist.pop(fi) if len(uvlist2) > 0: uvlist2.pop(fi) img = None img2 = None if obj.tex != '': if obj.tex in bl_images.keys(): img = bl_images[obj.tex] elif obj.tex not in missing_textures: texfname = None objtex = obj.tex baseimgname = bsys.basename(objtex) if bsys.exists(objtex) == 1: texfname = objtex else: if baseimgname.find('\\') > 0: baseimgname = bsys.basename( objtex.replace('\\', '/')) objtex = bsys.join(self.importdir, baseimgname) if bsys.exists(objtex) == 1: texfname = objtex else: objtex = bsys.join(TEXTURES_DIR2, baseimgname) if bsys.exists(objtex): texfname = objtex else: inform( "Couldn't find texture in alt path %s" % TEXTURES_DIR2) if texfname: try: img = Image.Load(texfname) # Commented because it's unnecessary: #img.xrep = int(obj.texrep[0]) #img.yrep = int(obj.texrep[1]) if img: bl_images[obj.tex] = img except: inform("THROW: Couldn't load texture: %s" % baseimgname) else: missing_textures.append(obj.tex) inform("Couldn't find texture: %s" % baseimgname) if obj.tex2 != '': if obj.tex2 in bl_images.keys(): img2 = bl_images[obj.tex2] elif obj.tex2 not in missing_textures: texfname = None objtex2 = obj.tex2 baseimgname = bsys.basename(objtex2) if bsys.exists(objtex2) == 1: texfname = objtex2 else: if baseimgname.find('\\') > 0: baseimgname = bsys.basename( objtex2.replace('\\', '/')) objtex2 = bsys.join(self.importdir, baseimgname) if bsys.exists(objtex) == 1: texfname = objtex2 else: objtex2 = bsys.join(TEXTURES_DIR2, baseimgname) if bsys.exists(objtex2): texfname = objtex2 else: inform( "Couldn't find texture in alt path %s" % objtex2) if texfname: try: img2 = Image.Load(texfname) # Commented because it's unnecessary: #img.xrep = int(obj.texrep[0]) #img.yrep = int(obj.texrep[1]) if img2: bl_images[obj.tex2] = img2 except: inform("THROW: Couldn't load texture: %s" % baseimgname) else: missing_textures.append(obj.tex2) inform("Couldn't find texture: %s" % baseimgname) if obj.tex not in bmat.keys(): if img: #Create a new material with a texture attached to it m1 = Material.New(obj.tex) m1.rgbCol = m.rgbCol m1.amb = m.amb m1.emit = m.emit m1.specCol = m.specCol m1.spec = m.spec m1.alpha = m.alpha texname = 'Tex%s' % obj.tex texname2 = 'Tex2%s' % obj.tex if img: iname = img.getName() if iname not in bl_textures.keys(): basetex = Texture.New(iname) basetex.setType('Image') map1 = Texture.MapTo.COL | Texture.MapTo.ALPHA basetex.image = img bl_textures[iname] = basetex basetex = bl_textures[iname] m1.setTexture(0, basetex, Texture.TexCo.UV, map1) if img2: iname2 = img2.getName() if iname2 not in bl_textures.keys(): basetex2 = Texture.New(iname2) basetex2.setType('Image') map2 = Texture.MapTo.COL basetex2.image = img2 bl_textures[iname2] = basetex2 else: map2 = Texture.MapTo.COL basetex2 = bl_textures[iname2] m1.setTexture(1, basetex2, Texture.TexCo.UV, map2) if m1.alpha < 1.0: m1.mode |= MAT_MODE_ZTRANSP has_transp_mats = True mtextures = m1.getTextures() tunit = 0 for mtex in mtextures: if not (mtex == None): if tunit == 1: mtex.uvlayer = "ShadowUV" mtex.colfac = 0.3 tunit = tunit + 1 if tunit == 0: mtex.uvlayer = "ImageUV" tunit = tunit + 1 bmat[obj.tex] = m1 if obj.tex != '': if obj.tex in bl_images.keys(): img = bl_images[obj.tex] #TODO attach correct materials to objects if obj.tex in bmat.keys(): mat1 = bmat[obj.tex] if len(mesh.materials) == 0: mesh.materials += [mat1] else: inform('Material %s not found\n' % obj.tex) for i in range(facesnum): f = obj.flist_cfg[i] fmat = f[0] is_smooth = f[1] twoside = f[2] bface = mesh.faces[i] bface.smooth = is_smooth if twoside: bface.mode |= FACE_TWOSIDE if img: bface.mode |= FACE_TEX bface.image = img #TODO handle material properly #bface.mat = objmat_indices.index(fmat) bface.mat = 0 fuv = obj.flist_uv[i] if len(obj.flist_uv2) > 0: fuv2 = obj.flist_uv2[i] if obj.texoff: uoff = obj.texoff[0] voff = obj.texoff[1] urep = obj.texrep[0] vrep = obj.texrep[1] for uv in fuv: uv[0] *= urep uv[1] *= vrep uv[0] += uoff uv[1] += voff if len(fuv2) > 0: for uv2 in fuv2: uv2[0] *= urep uv2[1] *= vrep uv2[0] += uoff uv2[1] += voff mesh.activeUVLayer = "ImageUV" mesh.faces[i].uv = fuv if len(fuv2) > 0: mesh.activeUVLayer = "ShadowUV" mesh.faces[i].uv = fuv2 # for uv2 in fuv2: # inform('UV2 coords %.5f %.5f\n' % (uv2[0],uv2[1])) mesh.activeUVLayer = "ImageUV" # finally, delete the 1st vertex we added to prevent vindices == 0 mesh.verts.delete(0) mesh.calcNormals() mesh.mode = MESH_AUTOSMOOTH obj_idx += 1 self.build_hierarchy() scene.update()
# # Check the Blender.Registry documentation for more information. import Blender from Blender import Registry, sys as bsys _EXT = '.cfg' # file extension for saved config data # limits: #MAX_ITEMS_NUM = 60 # max number of keys per dict and itens per list and tuple #MAX_STR_LEN = 300 # max string length (remember this is just for config data) _CFG_DIR = '' if Blender.Get('udatadir'): _CFG_DIR = Blender.sys.join(Blender.Get('udatadir'), 'config') if not _CFG_DIR or not bsys.exists(_CFG_DIR): _CFG_DIR = Blender.sys.join(Blender.Get('datadir'), 'config') if not bsys.exists(_CFG_DIR): _CFG_DIR = '' # to compare against, so we don't write to a cvs tree: _CVS_SUBPATH = 'release/scripts/bpydata/config/' if bsys.dirsep == '\\': _CVS_SUBPATH = _CVS_SUBPATH.replace('/', '\\') _KEYS = [k for k in Registry.Keys() if k[0] != '_'] # _ITEMS_NUM = 0 def _sanitize(o): "Check recursively that all objects are valid, set invalid ones to None"
# result to <path-of-blend-file>/render # # Copyright (C) 2009 Sergey I. Sharybin <*****@*****.**> # # This script is covered by GNU General Public License v2 and higher # import Blender, os from Blender import sys, Scene from Blender.Scene import Render from stat import * path = sys.dirname(Blender.Get("filename")) + sys.dirsep + "render" # Check existment of destination directory if not sys.exists(path): os.mkdir(path) mode = os.stat(path)[ST_MODE] if S_ISDIR(mode): scene = Scene.GetCurrent() context = scene.getRenderingContext() savedDisplayMode = context.displayMode context.displayMode = 2 context.setRenderPath(path) # Store currently active camera savedCamera = scene.objects.camera
def import2blender(): global import_dir, tipo scene_name = 'FEI-%s' % tipo sc = Scene.New(scene_name) sc.makeCurrent() #sc = Scene.GetCurrent() screen_list = Window.GetScreens() for screens in screen_list: Window.SetScreen(screens) sc.makeCurrent() Window.SetScreen(screen_list[2]) # Load Materials mat = [] for m in mats: material = Material.New(m.name) material.rgbCol = [1.0, 1.0, 1.0] texture = Texture.New(m.name) texture.setType('Image') texture.useAlpha #print m.tex if bsys.exists(m.tex): img = Image.Load(m.tex) texture.image = img texture.imageFlags |= Blender.Texture.ImageFlags.USEALPHA material.setTexture(0, texture, Texture.TexCo.UV, Texture.MapTo.ALPHA | Texture.MapTo.COL) else: Blender.Draw.PupMenu('Could not load %s texture' % (m.tex)) mat.append(material) #Load mesh structures to Blender for g in groups: ob_list = [] for o in g.obj_list: mesh = Blender.NMesh.New() mesh.name = o.name mesh.hasFaceUV(1) mesh.hasVertexColours(1) #Assign Material to Mesh and load Texture for UVs tex = '' for m in mat: if o.mat == m.name: mesh.materials.append(m) textu = m.getTextures() if bsys.exists(textu[0].tex.image.filename): tex = textu[0].tex.image break if not mesh.materials: try: newmat = Material.Get(o.mat) except: newmat = Material.New(o.mat) mesh.materials.append(newmat) #Import Vertices for ver in o.vlist: bvert = Blender.NMesh.Vert(ver[0], ver[1], ver[2]) mesh.verts.append(bvert) #Import faces with UV and Vertex Colours for fac in o.flist: bface = Blender.NMesh.Face() bface.mode |= Blender.NMesh.FaceModes['TWOSIDE'] if tex: bface.mode |= Blender.NMesh.FaceModes['TEX'] bface.transp = Blender.NMesh.FaceTranspModes['ALPHA'] bface.image = tex for fa in range(len(fac)): bface.v.append(mesh.verts[fac[fa]]) bface.uv.append(o.uvlist[fac[fa]]) col = Blender.NMesh.Col() col.r = int((o.vcol[fac[fa]][4] + o.vcol[fac[fa]][5]), 16) col.g = int((o.vcol[fac[fa]][6] + o.vcol[fac[fa]][7]), 16) col.b = int((o.vcol[fac[fa]][8] + o.vcol[fac[fa]][9]), 16) col.a = int((o.vcol[fac[fa]][2] + o.vcol[fac[fa]][3]), 16) bface.col.append(col) mesh.faces.append(bface) mesh.mode = 0 object = Blender.NMesh.PutRaw(mesh) object.setName(o.name) ob_list.append(object) # Create a group for this import. grp = Object.New("Empty", g.name) sc.link(grp) grp.makeParent(ob_list) return 1
def comprehensiveImageLoad(imagePath, filePath, PLACE_HOLDER=True, RECURSIVE=True, VERBOSE=False, CONVERT_CALLBACK=None): ''' imagePath: The image filename If a path precedes it, this will be searched as well. filePath: is the directory where the image may be located - any file at teh end will be ignored. PLACE_HOLDER: if True a new place holder image will be created. this is usefull so later you can relink the image to its original data. VERBOSE: If True debug info will be printed. RECURSIVE: If True, directories will be recursivly searched. Be carefull with this if you have files in your root directory because it may take a long time. CASE_INSENSITIVE: for non win32 systems, find the correct case for the file. CONVERT_CALLBACK: a function that takes an existing path and returns a new one. Use this when loading image formats blender may not support, the CONVERT_CALLBACK can take the path for a GIF (for example), convert it to a PNG and return the PNG's path. For formats blender can read, simply return the path that is given. ''' # VERBOSE = True if VERBOSE: print 'img:', imagePath, 'file:', filePath CASE_INSENSITIVE = True if os == None and CASE_INSENSITIVE: CASE_INSENSITIVE = True # When we have the file load it with this. try/except niceness. def imageLoad(path): #if path.endswith('\\') or path.endswith('/'): # raise 'INVALID PATH' if CONVERT_CALLBACK: path = CONVERT_CALLBACK(path) try: img = bpy.data.images.new(filename=path) if VERBOSE: print '\t\tImage loaded "%s"' % path return img except: if VERBOSE: if sys.exists(path): print '\t\tImage failed loading "%s", mabe its not a format blender can read.' % ( path) else: print '\t\tImage not found, making a place holder "%s"' % ( path) if PLACE_HOLDER: img = bpy.data.images.new(stripPath(path), 4, 4) img.filename = path return img #blank image else: return None # Image formats blender can read IMAGE_EXT = [ 'jpg', 'jpeg', 'png', 'tga', 'bmp', 'rgb', 'sgi', 'bw', 'iff', 'lbm', # Blender Internal 'gif', 'psd', 'tif', 'tiff', 'pct', 'pict', 'pntg', 'qtif' ] # Quacktime, worth a try. imageFileName = stripPath(imagePath) # image path only imageFileName_lower = imageFileName.lower() # image path only if VERBOSE: print '\tSearchingExisting Images for "%s"' % imagePath for i in bpy.data.images: if stripPath(i.filename.lower()) == imageFileName_lower: if VERBOSE: print '\t\tUsing existing image.' return i if VERBOSE: print '\tAttempting to load "%s"' % imagePath if sys.exists(imagePath): if VERBOSE: print '\t\tFile found where expected "%s".' % imagePath return imageLoad(imagePath) imageFileName_noext = stripExt(imageFileName) # With no extension. imageFileName_noext_lower = stripExt( imageFileName_lower) # With no extension. imageFilePath = stripFile(imagePath) # Remove relative path from image path if imageFilePath.startswith('./') or imageFilePath.startswith('.\\'): imageFilePath = imageFilePath[2:] # Attempt to load from obj path. tmpPath = stripFile(filePath) + stripPath(imageFileName) if sys.exists(tmpPath): if VERBOSE: print '\t\tFile found in path (1)"%s".' % tmpPath return imageLoad(tmpPath) # os needed if we go any further. if not os: if VERBOSE: print '\t\tCreating a placeholder with a face path: "%s".' % imagePath return imageLoad(imagePath) # Will jus treturn a placeholder. # We have os. # GATHER PATHS. paths = {} # Store possible paths we may use, dict for no doubles. tmpPath = addSlash(sys.expandpath('//')) # Blenders path if sys.exists(tmpPath): if VERBOSE: print '\t\tSearching in %s' % tmpPath paths[tmpPath] = [os.listdir(tmpPath)] # Orig name for loading paths[tmpPath].append([f.lower() for f in paths[tmpPath][0]]) # Lower case list. paths[tmpPath].append([stripExt(f) for f in paths[tmpPath][1] ]) # Lower case no ext else: if VERBOSE: print '\tNo Path: "%s"' % tmpPath tmpPath = imageFilePath if sys.exists(tmpPath): if VERBOSE: print '\t\tSearching in %s' % tmpPath paths[tmpPath] = [os.listdir(tmpPath)] # Orig name for loading paths[tmpPath].append([f.lower() for f in paths[tmpPath][0]]) # Lower case list. paths[tmpPath].append([stripExt(f) for f in paths[tmpPath][1] ]) # Lower case no ext else: if VERBOSE: print '\tNo Path: "%s"' % tmpPath tmpPath = stripFile(filePath) if sys.exists(tmpPath): if VERBOSE: print '\t\tSearching in %s' % tmpPath paths[tmpPath] = [os.listdir(tmpPath)] # Orig name for loading paths[tmpPath].append([f.lower() for f in paths[tmpPath][0]]) # Lower case list. paths[tmpPath].append([stripExt(f) for f in paths[tmpPath][1] ]) # Lower case no ext else: if VERBOSE: print '\tNo Path: "%s"' % tmpPath tmpPath = addSlash(bpy.config.textureDir) if tmpPath and sys.exists(tmpPath): if VERBOSE: print '\t\tSearching in %s' % tmpPath paths[tmpPath] = [os.listdir(tmpPath)] # Orig name for loading paths[tmpPath].append([f.lower() for f in paths[tmpPath][0]]) # Lower case list. paths[tmpPath].append([stripExt(f) for f in paths[tmpPath][1] ]) # Lower case no ext else: if VERBOSE: print '\tNo Path: "%s"' % tmpPath # Add path if relative image patrh was given. tmp_paths = paths.keys() for k in tmp_paths: tmpPath = k + imageFilePath if sys.exists(tmpPath): paths[tmpPath] = [os.listdir(tmpPath)] # Orig name for loading paths[tmpPath].append([f.lower() for f in paths[tmpPath][0] ]) # Lower case list. paths[tmpPath].append([stripExt(f) for f in paths[tmpPath][1] ]) # Lower case no ext else: if VERBOSE: print '\tNo Path: "%s"' % tmpPath # DONE # for path, files in paths.iteritems(): if sys.exists(path + imageFileName): if VERBOSE: print '\tFound image at path: "%s" file" "%s"' % ( path, imageFileName) return imageLoad(path + imageFileName) # If the files not there then well do a case insensitive seek. filesOrigCase = files[0] filesLower = files[1] filesLowerNoExt = files[2] # We are going to try in index the file directly, if its not there just keep on index = None try: # Is it just a case mismatch? index = filesLower.index(imageFileName_lower) except: try: # Have the extensions changed? index = filesLowerNoExt.index(imageFileName_noext_lower) ext = getExt( filesLower[index] ) # Get the extension of the file that matches all but ext. # Check that the ext is useable eg- not a 3ds file :) if ext.lower() not in IMAGE_EXT: index = None except: index = None if index != None: tmpPath = path + filesOrigCase[index] img = imageLoad(tmpPath) if img != None: if VERBOSE: print '\t\tImage Found "%s"' % tmpPath return img if RECURSIVE: # IMAGE NOT FOUND IN ANY OF THE DIRS!, DO A RECURSIVE SEARCH. if VERBOSE: print '\t\tImage Not Found in any of the dirs, doing a recusrive search' for path in paths.iterkeys(): # Were not going to use files if path == '/' or len(path) == 3 and path[1:] == ':\\': continue # print path , 'ASS' #------------------ # finds the file starting at the root. # def findImage(findRoot, imagePath): #W--------------- # ROOT, DIRS, FILES pathWalk = os.walk(path) pathList = [True] matchList = [ ] # Store a list of (match, size), choose the biggest. while True: try: pathList = pathWalk.next() except: break for file in pathList[2]: file_lower = file.lower() # FOUND A MATCH if (file_lower == imageFileName_lower) or\ (stripExt(file_lower) == imageFileName_noext_lower and getExt(file_lower) in IMAGE_EXT): name = pathList[0] + sys.sep + file size = os.path.getsize(name) if VERBOSE: print '\t\t\tfound:', name matchList.append((name, size)) if matchList: # Sort by file size matchList.sort(lambda A, B: cmp(B[1], A[1])) if VERBOSE: print '\t\tFound "%s"' % matchList[0][0] # Loop through all we have found img = None for match in matchList: img = imageLoad(match[0]) # 0 - first, 0 - pathname if img != None: break return img # No go. if VERBOSE: print '\t\tImage Not Found after looking everywhere! "%s"' % imagePath return imageLoad(imagePath) # Will jus treturn a placeholder.
def edit_extern(image=None): if not image: image = Image.GetCurrent() if not image: # Image is None Draw.PupMenu('ERROR: You must select an active Image.') return if image.packed: Draw.PupMenu('ERROR: Image is packed, unpack before editing.') return imageFileName = sys.expandpath(image.filename) if not sys.exists(imageFileName): Draw.PupMenu('ERROR: Image path does not exist.') return pupblock = [imageFileName.split('/')[-1].split('\\')[-1]] new_text = False try: appstring = Registry.GetKey('ExternalImageEditor', True) appstring = appstring['path'] # for ZanQdo if he removed the path from the textbox totaly. ;) - Cam if not appstring or appstring.find('%f') == -1: new_text = True except: new_text = True if new_text: pupblock.append('first time, set path.') if platform == 'win32': appstring = 'start "" /B "%f"' elif platform == 'darwin': appstring = 'open "%f"' else: appstring = 'gimp-remote "%f"' appstring_but = Draw.Create(appstring) save_default_but = Draw.Create(0) pupblock.append( ('editor: ', appstring_but, 0, 48, 'Path to application, %f will be replaced with the image path.')) pupblock.append(('Set Default', save_default_but, 'Store this path in the blender registry.')) # Only configure if Shift is held, if Blender.Window.GetKeyQualifiers() & Blender.Window.Qual.SHIFT: if not Draw.PupBlock('External Image Editor...', pupblock): return appstring = appstring_but.val save_default = save_default_but.val if save_default: Registry.SetKey('ExternalImageEditor', {'path': appstring}, True) if appstring.find('%f') == -1: Draw.PupMenu( 'ERROR: The comment you entered did not contain the filename ("%f")' ) return # ------------------------------- appstring = appstring.replace('%f', imageFileName) print '\tediting image with command "%s"' % appstring os.system(appstring)
def testAC3DImport(self): FACE_TWOSIDE = Mesh.FaceModes['TWOSIDE'] FACE_TEX = Mesh.FaceModes['TILES'] #FACE_TEX = Mesh.FaceModes['TEX'] MESH_AUTOSMOOTH = Mesh.Modes['AUTOSMOOTH'] MAT_MODE_ZTRANSP = Material.Modes['ZTRANSP'] MAT_MODE_TRANSPSHADOW = Material.Modes['TRANSPSHADOW'] scene = self.scene bl_images = {} # loaded texture images missing_textures = [] # textures we couldn't find bl_textures = {} # loaded textures objlist = self.objlist[1:] # skip 'world' #bmat = [] bmat = {} m = None has_transp_mats = False for mat in self.mlist: name = mat[0] # if name=='': name = 'BaseMaterial' if m== None: m = Material.New(name) m.rgbCol = (mat[1][0], mat[1][1], mat[1][2]) m.amb = mat[2] m.emit = mat[3] m.specCol = (mat[4][0], mat[4][1], mat[4][2]) m.spec = mat[5] m.alpha = mat[6] #force it to zero because that is how Speed Dreams / Torcs work m.alpha = 0.0 if m.alpha < 1.0: m.mode |= MAT_MODE_ZTRANSP has_transp_mats = True # bmat[name]=m # if has_transp_mats: # for mat in bmat: # mat.mode |= MAT_MODE_TRANSPSHADOW obj_idx = 0 # index of current obj in loop for obj in objlist: if obj.type == AC_GROUP: continue elif obj.type == AC_LIGHT: light = Lamp.New('Lamp') object = scene.objects.new(light, obj.name) #object.select(True) obj.bl_obj = object if obj.data: light.name = obj.data continue # type AC_POLY: # old .ac files used empty meshes as groups, convert to a real ac group if not obj.vlist and obj.kids: obj.type = AC_GROUP continue mesh = Mesh.New() object = scene.objects.new(mesh, obj.name) #object.select(True) obj.bl_obj = object if obj.data: mesh.name = obj.data mesh.degr = obj.crease # will auto clamp to [1, 80] if not obj.vlist: # no vertices? nothing more to do continue #Setup UV Layers mesh.addUVLayer("ImageUV") mesh.addUVLayer("ShadowUV") mesh.activeUVLayer ="ImageUV" mesh.verts.extend(obj.vlist) objmat_indices = [] for e in obj.elist: mesh.edges.extend(e) if obj.flist_v: mesh.faces.extend(obj.flist_v) facesnum = len(mesh.faces) if facesnum == 0: # shouldn't happen, of course continue mesh.faceUV = True # checking if the .ac file had duplicate faces (Blender ignores them) if facesnum != len(obj.flist_v): # it has, ugh. Let's clean the uv list: lenfl = len(obj.flist_v) flist = obj.flist_v uvlist = obj.flist_uv uvlist2 = obj.flist_uv2 cfglist = obj.flist_cfg for f in flist: f.sort() fi = lenfl while fi > 0: # remove data related to duplicates fi -= 1 if flist[fi] in flist[:fi]: uvlist.pop(fi) cfglist.pop(fi) if len(uvlist2)>0: uvlist2.pop(fi) img = None img2 = None if obj.tex != '': if obj.tex in bl_images.keys(): img = bl_images[obj.tex] elif obj.tex not in missing_textures: texfname = None objtex = obj.tex baseimgname = bsys.basename(objtex) if bsys.exists(objtex) == 1: texfname = objtex else: if baseimgname.find('\\') > 0: baseimgname = bsys.basename(objtex.replace('\\','/')) objtex = bsys.join(self.importdir, baseimgname) if bsys.exists(objtex) == 1: texfname = objtex else: objtex = bsys.join(TEXTURES_DIR2, baseimgname) if bsys.exists(objtex): texfname = objtex else: inform("Couldn't find texture in alt path %s" % TEXTURES_DIR2) if texfname: try: img = Image.Load(texfname) # Commented because it's unnecessary: #img.xrep = int(obj.texrep[0]) #img.yrep = int(obj.texrep[1]) if img: bl_images[obj.tex] = img except: inform("THROW: Couldn't load texture: %s" % baseimgname) else: missing_textures.append(obj.tex) inform("Couldn't find texture: %s" % baseimgname) if obj.tex2 != '': if obj.tex2 in bl_images.keys(): img2 = bl_images[obj.tex2] elif obj.tex2 not in missing_textures: texfname = None objtex2 = obj.tex2 baseimgname = bsys.basename(objtex2) if bsys.exists(objtex2) == 1: texfname = objtex2 else: if baseimgname.find('\\') > 0: baseimgname = bsys.basename(objtex2.replace('\\','/')) objtex2 = bsys.join(self.importdir, baseimgname) if bsys.exists(objtex) == 1: texfname = objtex2 else: objtex2 = bsys.join(TEXTURES_DIR2, baseimgname) if bsys.exists(objtex2): texfname = objtex2 else: inform("Couldn't find texture in alt path %s" % objtex2) if texfname: try: img2 = Image.Load(texfname) # Commented because it's unnecessary: #img.xrep = int(obj.texrep[0]) #img.yrep = int(obj.texrep[1]) if img2: bl_images[obj.tex2] = img2 except: inform("THROW: Couldn't load texture: %s" % baseimgname) else: missing_textures.append(obj.tex2) inform("Couldn't find texture: %s" % baseimgname) if obj.tex not in bmat.keys(): if img: #Create a new material with a texture attached to it m1 = Material.New(obj.tex) m1.rgbCol = m.rgbCol m1.amb = m.amb m1.emit = m.emit m1.specCol = m.specCol m1.spec = m.spec m1.alpha = m.alpha texname = 'Tex%s' %obj.tex texname2 = 'Tex2%s' %obj.tex if img: iname = img.getName() if iname not in bl_textures.keys(): basetex = Texture.New(iname) basetex.setType('Image') map1=Texture.MapTo.COL|Texture.MapTo.ALPHA basetex.image = img bl_textures[iname] = basetex basetex = bl_textures[iname] m1.setTexture(0,basetex,Texture.TexCo.UV,map1) if img2: iname2 = img2.getName() if iname2 not in bl_textures.keys(): basetex2 = Texture.New(iname2) basetex2.setType('Image') map2=Texture.MapTo.COL basetex2.image = img2 bl_textures[iname2] = basetex2 else: map2=Texture.MapTo.COL basetex2 = bl_textures[iname2] m1.setTexture(1,basetex2,Texture.TexCo.UV,map2) if m1.alpha < 1.0: m1.mode |= MAT_MODE_ZTRANSP has_transp_mats = True mtextures = m1.getTextures() tunit = 0 for mtex in mtextures: if not ( mtex == None ): if tunit == 1: mtex.uvlayer ="ShadowUV" mtex.colfac=0.3 tunit = tunit+1 if tunit ==0: mtex.uvlayer ="ImageUV" tunit = tunit+1 bmat[obj.tex]=m1 if obj.tex != '': if obj.tex in bl_images.keys(): img = bl_images[obj.tex] #TODO attach correct materials to objects if obj.tex in bmat.keys(): mat1 = bmat[obj.tex] if len(mesh.materials)==0: mesh.materials+= [mat1] else: inform('Material %s not found\n' % obj.tex) for i in range(facesnum): f = obj.flist_cfg[i] fmat = f[0] is_smooth = f[1] twoside = f[2] bface = mesh.faces[i] bface.smooth = is_smooth if twoside: bface.mode |= FACE_TWOSIDE if img: bface.mode |= FACE_TEX bface.image = img #TODO handle material properly #bface.mat = objmat_indices.index(fmat) bface.mat = 0 fuv = obj.flist_uv[i] if len(obj.flist_uv2)>0: fuv2 = obj.flist_uv2[i] if obj.texoff: uoff = obj.texoff[0] voff = obj.texoff[1] urep = obj.texrep[0] vrep = obj.texrep[1] for uv in fuv: uv[0] *= urep uv[1] *= vrep uv[0] += uoff uv[1] += voff if len(fuv2)>0: for uv2 in fuv2: uv2[0] *= urep uv2[1] *= vrep uv2[0] += uoff uv2[1] += voff mesh.activeUVLayer ="ImageUV" mesh.faces[i].uv = fuv if len(fuv2)>0: mesh.activeUVLayer ="ShadowUV" mesh.faces[i].uv = fuv2 # for uv2 in fuv2: # inform('UV2 coords %.5f %.5f\n' % (uv2[0],uv2[1])) mesh.activeUVLayer ="ImageUV" # finally, delete the 1st vertex we added to prevent vindices == 0 mesh.verts.delete(0) mesh.calcNormals() mesh.mode = MESH_AUTOSMOOTH obj_idx += 1 self.build_hierarchy() scene.update()
def parse_help_info(script): global PATHS, SCRIPT_INFO if script.userdir: path = PATHS['uscripts'] else: path = PATHS['scripts'] fname = bsys.join(path, script.fname) if not bsys.exists(fname): Draw.PupMenu('IO Error: couldn\'t find script %s' % fname) return None f = file(fname, 'r') lines = f.readlines() f.close() # fix line endings: if lines[0].find('\r'): unixlines = [] for l in lines: unixlines.append(l.replace('\r','')) lines = unixlines llen = len(lines) has_doc = 0 doc_data = { '__author__': '', '__version__': '', '__url__': '', '__email__': '', '__bpydoc__': '', '__doc__': '' } i = 0 while i < llen: l = lines[i] incr = 1 for k in doc_data.keys(): if l.find(k, 0, 20) == 0: value, incr = parse_pyobj(k, lines, i) exec("doc_data['%s'] = %s" % (k, value)) has_doc = 1 break i += incr # fix these to seqs, simplifies coding elsewhere for w in ['__author__', '__url__', '__email__']: val = doc_data[w] if val and type(val) == str: doc_data[w] = [doc_data[w]] if not doc_data['__bpydoc__']: if doc_data['__doc__']: doc_data['__bpydoc__'] = doc_data['__doc__'] if has_doc: # any data, maybe should confirm at least doc/bpydoc info = BPy_Info(script, doc_data) SCRIPT_INFO = info return True else: return False
def testAC3DImport(self): FACE_TWOSIDE = Mesh.FaceModes['TWOSIDE'] FACE_TEX = Mesh.FaceModes['TEX'] MESH_AUTOSMOOTH = Mesh.Modes['AUTOSMOOTH'] MAT_MODE_ZTRANSP = Material.Modes['ZTRANSP'] MAT_MODE_TRANSPSHADOW = Material.Modes['TRANSPSHADOW'] scene = self.scene bl_images = {} # loaded texture images missing_textures = [] # textures we couldn't find objlist = self.objlist[1:] # skip 'world' bmat = [] has_transp_mats = False for mat in self.mlist: name = mat[0] m = Material.New(name) m.rgbCol = (mat[1][0], mat[1][1], mat[1][2]) m.amb = mat[2] m.emit = mat[3] m.specCol = (mat[4][0], mat[4][1], mat[4][2]) m.spec = mat[5] m.mirCol = (mat[6][0], mat[6][1], mat[6][2]) m.alpha = mat[7] if m.alpha < 1.0: m.mode |= MAT_MODE_ZTRANSP has_transp_mats = True bmat.append(m) if has_transp_mats: for mat in bmat: mat.mode |= MAT_MODE_TRANSPSHADOW obj_idx = 0 # index of current obj in loop for obj in objlist: if obj.type == AC_GROUP: continue elif obj.type == AC_LIGHT: light = Lamp.New('Lamp') object = scene.objects.new(light, obj.name) #object.select(True) obj.bl_obj = object if obj.data: light.name = obj.data continue # type AC_POLY: # old .ac files used empty meshes as groups, convert to a real ac group if not obj.vlist and obj.kids: obj.type = AC_GROUP continue mesh = Mesh.New() object = scene.objects.new(mesh, obj.name) #object.select(True) obj.bl_obj = object if obj.data: mesh.name = obj.data mesh.degr = obj.crease # will auto clamp to [1, 80] if not obj.vlist: # no vertices? nothing more to do continue mesh.verts.extend(obj.vlist) objmat_indices = [] for mat in bmat: if bmat.index(mat) in obj.matlist: objmat_indices.append(bmat.index(mat)) mesh.materials += [mat] if DISPLAY_TRANSP and mat.alpha < 1.0: object.transp = True for e in obj.elist: mesh.edges.extend(e) if obj.flist_v: mesh.faces.extend(obj.flist_v) facesnum = len(mesh.faces) if facesnum == 0: # shouldn't happen, of course continue mesh.faceUV = True # checking if the .ac file had duplicate faces (Blender ignores them) if facesnum != len(obj.flist_v): # it has, ugh. Let's clean the uv list: lenfl = len(obj.flist_v) flist = obj.flist_v uvlist = obj.flist_uv cfglist = obj.flist_cfg for f in flist: f.sort() fi = lenfl while fi > 0: # remove data related to duplicates fi -= 1 if flist[fi] in flist[:fi]: uvlist.pop(fi) cfglist.pop(fi) img = None if obj.tex != '': if obj.tex in bl_images.keys(): img = bl_images[obj.tex] elif obj.tex not in missing_textures: texfname = None objtex = obj.tex baseimgname = bsys.basename(objtex) if bsys.exists(objtex) == 1: texfname = objtex elif bsys.exists(bsys.join(self.importdir, objtex)): texfname = bsys.join(self.importdir, objtex) else: if baseimgname.find('\\') > 0: baseimgname = bsys.basename(objtex.replace('\\','/')) objtex = bsys.join(self.importdir, baseimgname) if bsys.exists(objtex) == 1: texfname = objtex else: objtex = bsys.join(TEXTURES_DIR, baseimgname) if bsys.exists(objtex): texfname = objtex if texfname: try: img = Image.Load(texfname) # Commented because it's unnecessary: #img.xrep = int(obj.texrep[0]) #img.yrep = int(obj.texrep[1]) if img: bl_images[obj.tex] = img except: inform("Couldn't load texture: %s" % baseimgname) else: missing_textures.append(obj.tex) inform("Couldn't find texture: %s" % baseimgname) for i in range(facesnum): f = obj.flist_cfg[i] fmat = f[0] is_smooth = f[1] twoside = f[2] bface = mesh.faces[i] bface.smooth = is_smooth if twoside: bface.mode |= FACE_TWOSIDE if img: bface.mode |= FACE_TEX bface.image = img bface.mat = objmat_indices.index(fmat) fuv = obj.flist_uv[i] if obj.texoff: uoff = obj.texoff[0] voff = obj.texoff[1] urep = obj.texrep[0] vrep = obj.texrep[1] for uv in fuv: uv[0] *= urep uv[1] *= vrep uv[0] += uoff uv[1] += voff mesh.faces[i].uv = fuv # finally, delete the 1st vertex we added to prevent vindices == 0 mesh.verts.delete(0) mesh.calcNormals() mesh.mode = MESH_AUTOSMOOTH # subdiv: create SUBSURF modifier in Blender if SUBDIV and obj.subdiv > 0: subdiv = obj.subdiv subdiv_render = subdiv # just to be safe: if subdiv_render > 6: subdiv_render = 6 if subdiv > 3: subdiv = 3 modif = object.modifiers.append(Modifier.Types.SUBSURF) modif[Modifier.Settings.LEVELS] = subdiv modif[Modifier.Settings.RENDLEVELS] = subdiv_render obj_idx += 1 self.build_hierarchy() scene.update()