Python bpy.path() Examples

The following are 14 code examples of bpy.path(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module bpy , or try the search function .
Example #1
Source File: util.py    From leomoon-lightstudio with GNU General Public License v3.0 7 votes vote down vote up
def path_relative_to_export(p):
    """Return a path that is relative to the export path"""
    global export_path
    p = filesystem_path(p)
    ep = os.path.dirname(export_path)

    if os.sys.platform[:3] == "win":
        # Prevent an error whereby python thinks C: and c: are different drives
        if p[1] == ':': p = p[0].lower() + p[1:]
        if ep[1] == ':': ep = ep[0].lower() + ep[1:]

    try:
        relp = os.path.relpath(p, ep)
    except ValueError: # path on different drive on windows
        relp = p

    return relp.replace('\\', '/') 
Example #2
Source File: BioBlender2.py    From BioBlender with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def pdbdotorg(id):
	print("pdbdotorg")
	url1 = str("http://www.pdb.org/pdb/files/"+id+".pdb")
	save1 = str(homePath+"fetched" + os.sep + id +".pdb")
	if opSystem == "linux":
		if not os.path.isdir(quotedPath(homePath+"fetched")):
			os.mkdir(quotedPath(homePath + "fetched"))
	elif opSystem == "darwin":
		if not os.path.isdir(quotedPath(homePath+"fetched")):
			os.mkdir(quotedPath(homePath + "fetched"))
	else:
		if not os.path.isdir(r"\\?\\" + homePath+"fetched"):
			os.mkdir(r"\\?\\" + homePath+"fetched")
	# get file from the web
	try:
		filename, header = urlretrieve(url1, save1)
		bpy.context.scene.BBImportPath = save1
		importPreview(False, True)
		return filename
	except:
		return False 
Example #3
Source File: image.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def new(path, name=False, relative = True) :
    path = fs.clean(path)
    # check file
    if fs.isfile(path) == False :
        dprint('Texture image not found')
        return False

    if relative :
        try :
            path = bpy.path.relpath(path)
            path = fs.clean(path)
        except : 
            print('cant turn path into relative one (.blend and img path drive letters ?) ')
        
    # retrieve paths to image file from existing image slot
    # returns img if paths match
    for img in bpy.data.images :
        if img.filepath != '' :
            if bpy.path.abspath(path) == bpy.path.abspath(fs.clean(img.filepath)) :
                return img

    # create a unique name in image slot
    if name == False : 
        name = bpy.path.basename(path)
    name = bel.bpyname(name,bpy.data.images.keys())

    # finally :
    img = bpy.data.images.load(filepath=path)
    img.name = name
    return img 
Example #4
Source File: util.py    From leomoon-lightstudio with GNU General Public License v3.0 5 votes vote down vote up
def filesystem_path(p):
    """Resolve a relative Blender path to a real filesystem path"""
    if p.startswith('//'):
        pout = bpy.path.abspath(p)
    else:
        pout = os.path.realpath(p)

    return pout.replace('\\', '/')

# TODO: - somehow specify TYPES to get/set from config 
Example #5
Source File: util.py    From leomoon-lightstudio with GNU General Public License v3.0 5 votes vote down vote up
def find_config_value(module, section, key, default):
    """Attempt to find the configuration value specified by string key
    in the specified section of module's configuration file. If it is
    not found, return default.

    """
    global config_paths
    fc = []
    for p in config_paths:
        if os.path.exists(p) and os.path.isdir(p) and os.access(p, os.W_OK):
            fc.append( '/'.join([p, '%s.cfg' % module]))

    if len(fc) < 1:
        print('Cannot find %s config file path' % module)
        return default

    cp = configparser.SafeConfigParser()

    cfg_files = cp.read(fc)
    if len(cfg_files) > 0:
        try:
            val = cp.get(section, key)
            if val == 'true':
                return True
            elif val == 'false':
                return False
            else:
                return val
        except:
            return default
    else:
        return default 
Example #6
Source File: util.py    From leomoon-lightstudio with GNU General Public License v3.0 5 votes vote down vote up
def write_config_value(module, section, key, value):
    """Attempt to write the configuration value specified by string key
    in the specified section of module's configuration file.

    """
    global config_paths
    fc = []
    for p in config_paths:
        if os.path.exists(p) and os.path.isdir(p) and os.access(p, os.W_OK):
            fc.append( '/'.join([p, '%s.cfg' % module]))

    if len(fc) < 1:
        raise Exception('Cannot find a writable path to store %s config file' %
            module)

    cp = configparser.SafeConfigParser()

    cfg_files = cp.read(fc)

    if not cp.has_section(section):
        cp.add_section(section)

    if value == True:
        cp.set(section, key, 'true')
    elif value == False:
        cp.set(section, key, 'false')
    else:
        cp.set(section, key, value)

    if len(cfg_files) < 1:
        cfg_files = fc

    fh=open(cfg_files[0],'w')
    cp.write(fh)
    fh.close()

    return True 
Example #7
Source File: util.py    From leomoon-lightstudio with GNU General Public License v3.0 5 votes vote down vote up
def scene_filename():
    """Construct a safe scene filename, using 'untitled' instead of ''"""
    filename = os.path.splitext(os.path.basename(bpy.data.filepath))[0]
    if filename == '':
        filename = 'untitled'
    return bpy.path.clean_name(filename) 
Example #8
Source File: exporter.py    From cats-blender-plugin with MIT License 5 votes vote down vote up
def __exportTexture(self, filepath):
        if filepath.strip() == '':
            return -1
        # Use bpy.path to resolve '//' in .blend relative filepaths
        filepath = bpy.path.abspath(filepath)
        filepath = os.path.abspath(filepath)
        for i, tex in enumerate(self.__model.textures):
            if os.path.normcase(tex.path) == os.path.normcase(filepath):
                return i
        t = pmx.Texture()
        t.path = filepath
        self.__model.textures.append(t)
        if not os.path.isfile(t.path):
            logging.warning('  The texture file does not exist: %s', t.path)
        return len(self.__model.textures) - 1 
Example #9
Source File: BioBlender2.py    From BioBlender with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def core_parseTXT(filePath):
	tmpPDBmodelDictionary = {}
	global pdbIDmodelsDictionary
	# Parse text files sequence
	tmpPDBmodelImportOrder = bpy.context.scene.BBImportOrder.split(',')
	for fileName in tmpPDBmodelImportOrder:
		# open each file from the list
		with open(os.path.dirname(filePath)+"/"+fileName.strip(),"r") as f:
			atomCounter = 0
			# force the atom type
			char = C
			# for each line of the file
			for line in f:
				tmpPDBobjectName = bpy.context.scene.BBModelRemark
				key = str(tmpPDBobjectName) + "#" + str(atomCounter).rjust(5, "0")
				line = line.replace('"', "")	# cleanup some unconforming data
				split_line = line.split()
				x = "%8.3f" % float(split_line[0])
				y = "%8.3f" % float(split_line[1])
				z = "%8.3f" % float(split_line[2])
				# a somewhat hackish way to generate a PDB-conformant string for the unified reader to use
				line = PDBString("ATOM                                                                         " + char)
				# insert location in-situ
				line = line.set(30,x)
				line = line.set(38,y)
				line = line.set(46,z)
				tmpPDBmodelDictionary[key] = line
				atomCounter += 1
			(pdbIDmodelsDictionary[pdbID])[0] = tmpPDBmodelDictionary
			tmpPDBmodelDictionary = {}
	core_sort_hr() 
Example #10
Source File: BioBlender2.py    From BioBlender with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def exportPDB(path = homePath+"tmp" + os.sep + "tmp.pdb", tag = None, verbose = False, sPid = None):
	print("=============== exporting PDB")
	print("Exporting model '%s' to %s" %(tag, path))
		
	outPath = abspath(path)
	# Questo e' un singolo PDB, di un singolo MODEL (quello corrente), quindi penso si possa procedere in maniera molto semplice...
	#if not tag:	
	#	for model in modelContainer:
	#		tag = model
	#model = modelContainer[tag]
	#ordered = sorted(model.keys())
	print("=======outPath = " + str(outPath))
	with open(outPath, "w") as outFile:
		for o in bpy.data.objects:
			try:
				if((o.bb2_pdbID == sPid) and (o.bb2_objectType=="ATOM")):
					loc = o.location
					info = o.BBInfo
					x = "%8.3f" % loc[0]
					y = "%8.3f" % loc[1]
					z = "%8.3f" % loc[2]
					# convert line to pdbstring class
					line = PDBString(info)
					# clear location column
					line = line.set(30,"                         ")
					# insert new location
					line = line.set(30,x)
					line = line.set(38,y)
					line = line.set(46,z)
					outFile.write (line+"\n")
			except Exception as E:
				str4 = str(E)	# Do nothing...
		outFile.write("ENDMDL"+"\n")



# Import the surface generated from PyMol 
Example #11
Source File: BioBlender2.py    From BioBlender with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def exportOBJ(path):
	vertexData = []		# list of list[3] (wrl vertices data)
	# read wrl file
	with open(path+".wrl") as wrl:
		found = False
		for line in wrl:
			# skip to coord section of the file
			if not found:
				if "coord" in line:
					wrl.readline()
					found = True
			# when in the coord section of the file
			else:
				if "]" not in line:
					# convert vertexData from string to a list of float
					entry = line[:-2].split()
					entryFloat = [float(coord) for coord in entry]
					vertexData.append(entryFloat)
				else:
					# end document processing
					break

	# write obj file: vertex data
	with open(path+".obj", mode="w") as obj:
		for entry in vertexData:
			out = "v %f %f %f\n" % (entry[0], entry[1], entry[2])
			obj.write(out)

		# face data
		i = 0
		while (i < len(vertexData)):
			out = "f %d/%d %d/%d %d/%d\n" % (i+1,i+1,i+2,i+2,i+3,i+3)
			obj.write(out)
			i = i + 3 
Example #12
Source File: exporter.py    From cats-blender-plugin with MIT License 4 votes vote down vote up
def __copy_textures(self, output_dir, base_folder=''):
        tex_dir_fallback = os.path.join(output_dir, 'textures')
        tex_dir_preference = bpyutils.addon_preferences('base_texture_folder', '')

        path_set = set() # to prevent overwriting
        tex_copy_list = []
        for texture in self.__model.textures:
            path = texture.path
            tex_dir = output_dir  # restart to the default directory at each loop
            if not os.path.isfile(path):
                logging.warning('*** skipping texture file which does not exist: %s', path)
                path_set.add(os.path.normcase(path))
                continue
            dst_name = os.path.basename(path)
            if base_folder:
                dst_name = saferelpath(path, base_folder, strategy='outside')
                if dst_name.startswith('..'):
                    # Check if the texture comes from the preferred folder
                    if tex_dir_preference:
                        dst_name = saferelpath(path, tex_dir_preference, strategy='outside')
                    if dst_name.startswith('..'):
                        # If the code reaches here the texture is somewhere else
                        logging.warning('The texture %s is not inside the base texture folder', path)
                        # Fall back to basename and textures folder
                        dst_name = os.path.basename(path)
                        tex_dir = tex_dir_fallback
            else:
                tex_dir = tex_dir_fallback
            dest_path = os.path.join(tex_dir, dst_name)
            if os.path.normcase(path) != os.path.normcase(dest_path): # Only copy if the paths are different
                tex_copy_list.append((texture, path, dest_path))
            else:
                path_set.add(os.path.normcase(path))

        for texture, path, dest_path in tex_copy_list:
            counter = 1
            base, ext = os.path.splitext(dest_path)
            while os.path.normcase(dest_path) in path_set:
                dest_path = '%s_%d%s'%(base, counter, ext)
                counter += 1
            path_set.add(os.path.normcase(dest_path))
            os.makedirs(os.path.dirname(dest_path), exist_ok=True)
            shutil.copyfile(path, dest_path)
            logging.info('Copy file %s --> %s', path, dest_path)
            texture.path = dest_path 
Example #13
Source File: exporter.py    From cats-blender-plugin with MIT License 4 votes vote down vote up
def execute(self, filepath, **args):
        root = args.get('root', None)
        self.__model = pmx.Model()
        self.__model.name = 'test'
        self.__model.name_e = 'test eng'
        self.__model.comment = 'exported by mmd_tools'
        self.__model.comment_e = 'exported by mmd_tools'

        if root is not None:
            self.__model.name = root.mmd_root.name or root.name
            self.__model.name_e = root.mmd_root.name_e
            txt = bpy.data.texts.get(root.mmd_root.comment_text, None)
            if txt:
                self.__model.comment = txt.as_string().replace('\n', '\r\n')
            txt = bpy.data.texts.get(root.mmd_root.comment_e_text, None)
            if txt:
                self.__model.comment_e = txt.as_string().replace('\n', '\r\n')

        self.__armature = args.get('armature', None)
        meshes = sorted(args.get('meshes', []), key=lambda x: x.name)
        rigids = sorted(args.get('rigid_bodies', []), key=lambda x: x.name)
        joints = sorted(args.get('joints', []), key=lambda x: x.name)

        self.__scale = args.get('scale', 1.0)
        self.__disable_specular = args.get('disable_specular', False)
        sort_vertices = args.get('sort_vertices', 'NONE')
        if sort_vertices != 'NONE':
            self.__vertex_order_map = {'method':sort_vertices}

        nameMap = self.__exportBones(meshes)

        mesh_data = [self.__loadMeshData(i, nameMap) for i in meshes]
        self.__exportMeshes(mesh_data, nameMap)
        if args.get('sort_materials', False):
            self.__sortMaterials()

        self.__exportVertexMorphs(mesh_data, root)
        if root is not None:
            self.__export_bone_morphs(root)
            self.__export_material_morphs(root)
            self.__export_uv_morphs(root)
            self.__export_group_morphs(root)
            self.__exportDisplayItems(root, nameMap)

        rigid_map = self.__exportRigidBodies(rigids, nameMap)
        self.__exportJoints(joints, rigid_map)

        if args.get('copy_textures', False):
            output_dir = os.path.dirname(filepath)
            import_folder = root.get('import_folder', '') if root else ''
            base_folder = bpyutils.addon_preferences('base_texture_folder', '')
            self.__copy_textures(output_dir, import_folder or base_folder)

        pmx.save(filepath, self.__model, add_uv_count=self.__add_uv_count) 
Example #14
Source File: BioBlender2.py    From BioBlender with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def scenewideSetup():
	path = homePath+"tmp" + os.sep + "scenewide.pdb"
	# Actually, this is a custom "exportPDB" function, without instructions which were present in original "setup" function...
	print("=============== exporting PDB")
	print("Exporting scene to: " + str(path))
		
	outPath = abspath(path)
	print("=======outPath = " + str(outPath))
	i = 1
	with open(outPath, "w") as outFile:
		for o in bpy.data.objects:
			try:
				if(o.bb2_objectType=="ATOM"):
					loc = trueSphereOrigin(o)
					info = o.BBInfo
					x = "%8.3f" % loc[0]
					y = "%8.3f" % loc[1]
					z = "%8.3f" % loc[2]
					# convert line to pdbstring class
					line = PDBString(info)
					# Recalculate ATOM id number...
					line = line.set(1,"           ")
					if (i<10):
						tmpString = "ATOM      " + str(i)
					elif(i>9 and i<100):
						tmpString = "ATOM     " + str(i)
					elif(i>99 and i<1000):
						tmpString = "ATOM    " + str(i)
					else:
						tmpString = "ATOM   " + str(i)
					line = line.set(0,tmpString)
					# clear location column
					line = line.set(30,"                         ")
					# insert new location
					line = line.set(30,x)
					line = line.set(38,y)
					line = line.set(46,z)
					outFile.write (line+"\n")
					i = i+1
			except Exception as E:
				str4 = str(E)	
				print("An error occured in sceneWideSetup: " + str4)
		outFile.write("ENDMDL"+"\n")
	print("scenewideSetup is complete!")


# Import the surface generated from PyMol