def execute(self, context): #CREATING NEW FILES------> if self.action == "NEW": #Checking if file is already existing if not os.path.isfile(bpy.context.scene.newF): print("create directories") interface.create_naming(bpy.context,bpy.context,'CREATE',ressources.path,ressources.command) p = bpy.context.scene.newF print("saving file to :"+str(p)) for x in range(0,len(addon_utils.paths())): print(addon_utils.paths()[x]+'/addon/base.blend') if os.path.isfile(addon_utils.paths()[x]+'/addon/base.blend'): shutil.copyfile(addon_utils.paths()[x]+'/addon/base.blend',p) print("new file copied") ressources.command.append("new file copied") break else: print("copy error") ressources.command.append("Copy error") bpy.ops.wm.open_mainfile(filepath = p) else: ressources.command.append("File already EXIST !") #OPENING FILES-----------> elif self.action == "OPEN": print("opening file") file_name = bpy.context.scene.custom[bpy.context.scene.custom_index].name if len(file_name) > 3: #checking if a file is selected p = files.getPath(bpy.context.scene.newF)+file_name #Checking file existence if os.path.isfile(p): ressources.command.append("opening file :"+str(p)) bpy.ops.wm.open_mainfile(filepath = p) #Refresh ans asset LIST UI List before breaking files.Update_ListFile(bpy.context.scene.newF) interface.UpdateEnum('',ressources.Items_asset,'asset','','') else: ressources.command.append("unknown directory :"+str(p)) else: print('no file selected') #SAVE8AS FILES-----------> elif self.action == "SAVE_AS": file_name = bpy.context.scene.newF.split("/") p = bpy.context.scene.newF if os.path.isfile(p): ressources.command.append("File already exist") bpy.ops.object.dialog_operator('INVOKE_DEFAULT') #calls the popup else: ressources.command.append("saving file to :"+str(p)) interface.create_naming(bpy.context,bpy.context,'CREATE',ressources.path,ressources.command) print("saving file to :"+str(p)) bpy.ops.wm.save_as_mainfile(filepath=p) files.Update_ListFile(bpy.context.scene.newF) #__init__.update_naming(self,context) return {"FINISHED"}
def preset_paths(subdir): """ Returns a list of paths for a specific preset. :arg subdir: preset subdirectory (must not be an absolute path). :type subdir: string :return: script paths. :rtype: list """ dirs = [] for path in script_paths("presets", check_all=True): directory = _os.path.join(path, subdir) if not directory.startswith(path): raise Exception("invalid subdir given %r" % subdir) elif _os.path.isdir(directory): dirs.append(directory) # Find addons preset paths import addon_utils for path in addon_utils.paths(): directory = _os.path.join(path, "presets", subdir) if _os.path.isdir(directory): dirs.append(directory) return dirs
def checkMakeSkinAvailable(): for path in paths(): for mod_name, mod_path in bpy.path.module_names(path): is_enabled, is_loaded = check(mod_name) if mod_name == "makeskin": return is_enabled and is_loaded return False
def __init__(self, hand, blinker, default='mouse here to activates me', fontname="verdana.ttf", fontsize=12, bold=False, italic=False): bounds = Rectangle(Point(0,0),Point(800,30)) super(StringInput, self).__init__(bounds = bounds) tmp = addon_utils.paths()[0] + "/Ephestos/fonts/verdana.ttf" self.font = blf.load(tmp) self.info = default self.activated = False self.hand = hand self.blinker = blinker self.kbd_listener = hand.kbd_listener self.default = default self.fontname = fontname self.fontsize = fontsize self.bold = bold self.italic = italic # self.color = (0.9, 0.1, 0.1, 1) #??? why standard color? shown???? self.add(blinker) #PKHG>??? 3jul, yes wanted ... self.is_activated = False self.activation_info = Morph(bounds = Rectangle(Point(0,0),Point(20,20)), with_name = False) self.activation_info.set_position(self.bounds.origin - Point(0,25)) self.activation_info.is_visible = False self.activation_info.set_color("red") self.add(self.activation_info) self.relative_pos_of_chars = [0] self.mouse_click_left_toggle = False self.prefix = "" self.postfix = "" self.text = "" self.width = 0
def get_loaded_addons(): paths_list = paths() addon_list = [] for path in paths_list: for mod_name, mod_path in bpy.path.module_names(path): is_enabled, is_loaded = check(mod_name) if is_enabled and is_loaded: addon_list.append(mod_name) return addon_list
def get_all_addons(): import sys paths_list = paths() addon_list = [] for path in paths_list: bpy.utils._sys_path_ensure(path) for mod_name, mod_path in bpy.path.module_names(path): is_enabled, is_loaded = check(mod_name) addon_list.append(mod_name) return (addon_list)
def test_font(self): print("test_font") import blf import addon_utils #PKHG.e.g. paths() check_contains(addon_utils,'addons') addon_path = addon_utils.paths()[0] local_font_path = addon_path +"/Ephestos/fonts" verdana = local_font_path + "/verdana.ttf" res = blf.load(verdana) self.assertNotEqual(res, -1)
def get_all_addons(display=False): paths_list = paths() addon_list = [] for path in paths_list: _bpy.utils._sys_path_ensure(path) for mod_name, mod_path in _bpy.path.module_names(path): is_enabled, is_loaded = check(mod_name) addon_list.append(mod_name) if display: # for example print("%s default:%s loaded:%s" % (mod_name, is_enabled, is_loaded)) return addon_list
def execute(self, context): # execute() is called when running the operator. import sys paths_list = addon_utils.paths() addon_list = [] for path in paths_list: bpy.utils._sys_path_ensure(path) for mod_name, mod_path in bpy.path.module_names(path): is_enabled, is_loaded = addon_utils.check(mod_name) addon_list.append(mod_name) print("%s default:%s loaded:%s"%(mod_name,is_enabled,is_loaded)) return {'FINISHED'}
def loadFile(self, context, exampleName): blenderAddonPaths = addon_utils.paths() for path in blenderAddonPaths: basePath = os.path.join(path, "PRMan-for-Blender", "examples") exists = os.path.exists(basePath) if exists: examplePath = os.path.join( basePath, exampleName, exampleName + ".blend") if(os.path.exists(examplePath)): bpy.ops.wm.open_mainfile(filepath=examplePath) return True else: return False
def loadFile(self, context, exampleName): blenderAddonPaths = addon_utils.paths() for path in blenderAddonPaths: basePath = os.path.join(path, "PRMan-for-Blender", "examples") exists = os.path.exists(basePath) if exists: examplePath = os.path.join(basePath, exampleName, exampleName + ".blend") if (os.path.exists(examplePath)): bpy.ops.wm.open_mainfile(filepath=examplePath) return True else: return False
def refresh_script_paths(): """ Run this after creating new script paths to update sys.path """ for base_path in script_paths(): for path_subdir in _script_module_dirs: path = _os.path.join(base_path, path_subdir) if _os.path.isdir(path): _sys_path_ensure(path) for path in _addon_utils.paths(): _sys_path_ensure(path) path = _os.path.join(path, "modules") if _os.path.isdir(path): _sys_path_ensure(path)
def Leelooer(): addonpath = addon_utils.paths()[1] leeloopath = addonpath + "/Leeloo.blend\\NodeTree\\" if bpy.data.filepath == "": bpy.ops.object.notsaved_operator('INVOKE_DEFAULT') else: if 'Leeloo' not in bpy.data.node_groups: bpy.ops.wm.append(directory=leeloopath, filename="Leeloo", link=False) Lilu = bpy.data.node_groups["Leeloo"] filelength = len(bpy.data.filepath) blendfilename = bpy.data.filepath[0: filelength - 6] Lilu.nodes["Passes Output"].base_path = blendfilename + "_" + "Multipass/" pilist = [] x = "" for i in bpy.data.objects: if i.pass_index not in pilist: pilist.append(i.pass_index) print(pilist) for i in range(10): if i in pilist: x = "IOB" + str(i) print(x) Lilu.nodes[x].outputs[0].enabled = True Lilu.links.new(Lilu.nodes["Passes Output"].inputs[8+i], Lilu.nodes[x].outputs[0]) else: x = "IOB" + str(i) Lilu.nodes[x].outputs[0].enabled = False malist = [] x = "" for i in bpy.data.materials: if i.pass_index not in malist: malist.append(i.pass_index) print(malist) for i in range(10): if i in malist: x = "IMA" + str(i) print(x) Lilu.nodes[x].outputs[0].enabled = True Lilu.links.new(Lilu.nodes["Passes Output"].inputs[18+i], Lilu.nodes[x].outputs[0]) else: x = "IMA" + str(i) Lilu.nodes[x].outputs[0].enabled = False
def main(): bpy.context.scene.render.engine = 'CYCLES' bpy.context.scene.cycles.device = 'GPU' bpy.context.user_preferences.addons[ 'cycles'].preferences.compute_device_type = 'CUDA' #bpy.context.user_preferences.addons['cycles'].preferences.devices[1].use = True prefs = bpy.context.user_preferences.addons['cycles'].preferences print(prefs.compute_device_type) for d in prefs.devices: print(d.name) bpy.ops.wm.save_userpref() bpy.ops.wm.addon_enable(module='materials_utils') for arg in sys.argv: if "scene-dir" in arg: scene_dir = arg.split("=")[1] print(addon_utils.paths()) generator = SceneGenerator() for i in range(10000): generator.random_render(str(i)) generator.render_envmap(str(i))
def __init__( self, text, fontname="arialbd.ttf", fontsize=24, bold=False, italic=False, alignment="left", # PKHG.INFO a real Text needs a max_with > 0 !!! max_width=200, ): #### PKHG idea to make scrolling easy? """ max_nr_of_lines >= 1 show lines from startline >= 0 show_nr_of_lines show_upto = min(startline + show_nr_of_lines, max_nr_of_lines) ==> range(startline,show_upto,1) problem, if because of width lines were added?! """ super(Text, self).__init__() tmp = addon_utils.paths()[0] + "/Ephestos/fonts/" + fontname self.font = blf.load(tmp) blf.size(self.font, fontsize, 72) # DPI = 72 !! self.background_color = [0, 0, 0, 1] # PKHG.??? if a of background_color not 1 strange things can happen # 4jul12 show about use input move about =>strange behavior self.text = text self.words = [] self.lines = [] self.fontname = fontname self.fontsize = fontsize self.bold = bold self.italic = italic self.alignment = alignment self.max_width = max(20, min(max_width, 800)) # self.color = (.0, 1.0, 1.0, 1.0) #PKHG 7jul12 white forced in draw self.max_line_width = 0 self.adjust_text(text)
def load_addons(self): # pylint: disable=assignment-from-no-return addon_paths = addon_utils.paths() print("\nThe following paths are now being considered for Addons:") for i, addon_path in enumerate(addon_paths): path = os.path.normpath(addon_path) print("\t{0:02d} {1}".format(i, path)) print("\nNow loading the following plugins:") for i, addon in enumerate(get_addon_configurations()): if addon.name: print("\n\t{0:02d} {1}".format(i, addon.name)) if addon.startup: print("\t\tExecuting the following code:") [print("\t\t\t", line) for line in addon.code.split(";")] exec(addon.code) if addon.enable: addon_utils.enable( module_name=addon.name, persistent=addon.persistent, default_set=False, handle_error=None)
def refresh_script_paths(): """ Run this after creating new script paths to update sys.path """ for path in _sys_path_ensure_paths: try: _sys.path.remove(path) except ValueError: pass _sys_path_ensure_paths.clear() for base_path in script_paths(): for path_subdir in _script_module_dirs: path = _os.path.join(base_path, path_subdir) if _os.path.isdir(path): _sys_path_ensure_prepend(path) for path in _addon_utils.paths(): _sys_path_ensure_append(path) path = _os.path.join(path, "modules") if _os.path.isdir(path): _sys_path_ensure_append(path)
def __init__(self, target=None, action='nop', #PKHG.??? was None label='trigger', fontname="verdana.ttf", fontsize=10, bold=False, italic=False): #PKHG>??? once and for all that font stuff? super(Trigger, self).__init__() import addon_utils path_to_local_fonts = addon_utils.paths()[0] + "/Ephestos/fonts" font = path_to_local_fonts + "/" + fontname font_id = blf.load(font) blf.size(font_id, 16, 72) #pKHG needed to adjust text with! dims_x,dims_y = blf.dimensions(font_id, label) # self.my_name_size = dims_x # mylabel_width = int(dims_x) + 75 # bounds = Rectangle(Point(0,0),Point(mylabel_width, int(dims_y) + 20)) # super(Trigger, self).__init__(bounds = bounds) self.set_width(int(dims_x) + 2) self.set_height(int(dims_y) + 15) #PKHG old: 20) self.name = label self.action = action
def execute(self, context): #CREATING NEW FILES------> if self.action == "NEW": #Checking if file is already existing if not os.path.isfile(bpy.context.scene.newF): print("create directories") interface.create_naming(bpy.context, bpy.context, 'CREATE', ressources.path, ressources.command) p = bpy.context.scene.newF print("saving file to :" + str(p)) for x in range(0, len(addon_utils.paths())): print(addon_utils.paths()[x] + '/addon/base.blend') if os.path.isfile(addon_utils.paths()[x] + '/addon/base.blend'): shutil.copyfile( addon_utils.paths()[x] + '/addon/base.blend', p) print("new file copied") ressources.command.append("new file copied") break else: print("copy error") ressources.command.append("Copy error") bpy.ops.wm.open_mainfile(filepath=p) else: ressources.command.append("File already EXIST !") #OPENING FILES-----------> elif self.action == "OPEN": print("opening file") file_name = bpy.context.scene.custom[ bpy.context.scene.custom_index].name if len(file_name) > 3: #checking if a file is selected p = files.getPath(bpy.context.scene.newF) + file_name #Checking file existence if os.path.isfile(p): ressources.command.append("opening file :" + str(p)) bpy.ops.wm.open_mainfile(filepath=p) #Refresh ans asset LIST UI List before breaking files.Update_ListFile(bpy.context.scene.newF) interface.UpdateEnum('', ressources.Items_asset, 'asset', '', '') else: ressources.command.append("unknown directory :" + str(p)) else: print('no file selected') #SAVE8AS FILES-----------> elif self.action == "SAVE_AS": file_name = bpy.context.scene.newF.split("/") p = bpy.context.scene.newF if os.path.isfile(p): ressources.command.append("File already exist") bpy.ops.object.dialog_operator( 'INVOKE_DEFAULT') #calls the popup else: ressources.command.append("saving file to :" + str(p)) interface.create_naming(bpy.context, bpy.context, 'CREATE', ressources.path, ressources.command) print("saving file to :" + str(p)) bpy.ops.wm.save_as_mainfile(filepath=p) files.Update_ListFile(bpy.context.scene.newF) #__init__.update_naming(self,context) return {"FINISHED"}
# knowledge of the CeCILL license and that you accept its terms. import bpy from bpy.props import * import os.path #Files functions of os lib import sys import addon_utils #utils to find addons path import shutil #Used to copy files from . import files from . import gui from . import interface from . import ressources from . import persistence for x in range(len(addon_utils.paths())): appending = sys.path.append(addon_utils.paths()[x]+'/addon/python3x') #Appending naming libs print(appending) '''<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< HELP OPERATOR >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>''' class Help(bpy.types.Operator): bl_idname = "scene.help" bl_label = "help" def execute(self, context): bpy.ops.wm.url_open(url="http://les-fees-speciales.coop/wiki/")
def show_paths(): for p in addon_utils.paths(): print("MMPATH:",p)
def execute(self, context): if (not self.newError): zFile = self.zFile loop = self.loop flip = self.flip tran = self.tran verts = [] faces = [] uNum = 0 vNum = 0 if (self.firstCall): self.firstCall = False successFlag = False for it_path in addon_utils.paths(): if (successFlag): break; # successfully loaded, no need to continue zFile = it_path+"/add_mesh_DataSurface/csvdata.csv" self.zFile = zFile; try: uNum, vNum, zValue, xValue, yValue = loadZData(zFile) successFlag = True except FileNotFoundError as e: successFlag = False except: import traceback self.report({'ERROR'}, "Error parsing coordinate data: " + traceback.format_exc(limit=1)) self.newError = True return {'CANCELLED'} if (not successFlag): errStr = "Fail to find example data files: \nI have searched in following paths:\n" for it_path in addon_utils.paths(): errStr += " \t" + it_path+"/add_mesh_DataSurface/csvdata.csv\n" self.report({'ERROR'}, errStr) self.newError = True return {'CANCELLED'} else: try: uNum, vNum, zValue, xValue, yValue = loadZData(zFile) successFlag = True except FileNotFoundError as e: successFlag = False except: import traceback self.report({'ERROR'}, "Error parsing coordinate data: " + traceback.format_exc(limit=1)) self.newError = True return {'CANCELLED'} itVertIdsPre = [] if tran: for itV in range(vNum): itVertIdsCur = [] for itU in range(uNum): itVertIdsCur.append(len(verts)) verts.append( (yValue[itV],xValue[itU],zValue[itV][itU]) ) if len(itVertIdsPre)>0: faces.extend(makeFaces(itVertIdsPre,itVertIdsCur,loop,flip)) itVertIdsPre = itVertIdsCur else: for itU in range(uNum): itVertIdsCur = [] for itV in range(vNum): itVertIdsCur.append(len(verts)) verts.append( (xValue[itU],yValue[itV],zValue[itV][itU]) ) if len(itVertIdsPre)>0: faces.extend(makeFaces(itVertIdsPre,itVertIdsCur,loop,flip)) itVertIdsPre = itVertIdsCur if not verts: self.newError = True return {'CANCELLED'} the_object = create_mesh_and_object(context, verts, [], faces, "ZDataSurface") return {'FINISHED'} else: self.newError = False # self.report({'INFO'}, "Edit Over? Try it again.") return {'FINISHED'}
for mod in addon_utils.modules(): if addon_utils.module_bl_info(mod)['blender'] < (2, 80, 0): BLACKLIST.add(mod.__name__) # Some modules need to add to the `sys.path`. MODULE_SYS_PATHS = { # Runs in a Python subprocess, so its expected its basedir can be imported. "io_blend_utils.blendfile_pack": ".", } if not bpy.app.build_options.freestyle: BLACKLIST.add("render_freestyle_svg") BLACKLIST_DIRS = (os.path.join(bpy.utils.resource_path('USER'), "scripts"), ) + tuple(addon_utils.paths()[1:]) def module_names_recursive(mod_dir, *, parent=None): """ a version of bpy.path.module_names that includes non-packages """ is_package = os.path.exists(os.path.join(mod_dir, "__init__.py")) for n in os.listdir(mod_dir): if not n.startswith((".", "_")): submod_full = os.path.join(mod_dir, n) if os.path.isdir(submod_full): if not parent: subparent = n
def execute(self, context): if (not self.newError): zFile = self.zFile loop = self.loop flip = self.flip tran = self.tran verts = [] faces = [] uNum = 0 vNum = 0 if (self.firstCall): self.firstCall = False successFlag = False for it_path in addon_utils.paths(): if (successFlag): break # successfully loaded, no need to continue zFile = it_path + "/add_mesh_DataSurface/csvdata.csv" self.zFile = zFile try: uNum, vNum, zValue, xValue, yValue = loadZData(zFile) successFlag = True except FileNotFoundError as e: successFlag = False except: import traceback self.report({'ERROR'}, "Error parsing coordinate data: " + traceback.format_exc(limit=1)) self.newError = True return {'CANCELLED'} if (not successFlag): errStr = "Fail to find example data files: \nI have searched in following paths:\n" for it_path in addon_utils.paths(): errStr += " \t" + it_path + "/add_mesh_DataSurface/csvdata.csv\n" self.report({'ERROR'}, errStr) self.newError = True return {'CANCELLED'} else: try: uNum, vNum, zValue, xValue, yValue = loadZData(zFile) successFlag = True except FileNotFoundError as e: successFlag = False except: import traceback self.report({'ERROR'}, "Error parsing coordinate data: " + traceback.format_exc(limit=1)) self.newError = True return {'CANCELLED'} itVertIdsPre = [] if tran: for itV in range(vNum): itVertIdsCur = [] for itU in range(uNum): itVertIdsCur.append(len(verts)) verts.append( (yValue[itV], xValue[itU], zValue[itV][itU])) if len(itVertIdsPre) > 0: faces.extend( makeFaces(itVertIdsPre, itVertIdsCur, loop, flip)) itVertIdsPre = itVertIdsCur else: for itU in range(uNum): itVertIdsCur = [] for itV in range(vNum): itVertIdsCur.append(len(verts)) verts.append( (xValue[itU], yValue[itV], zValue[itV][itU])) if len(itVertIdsPre) > 0: faces.extend( makeFaces(itVertIdsPre, itVertIdsCur, loop, flip)) itVertIdsPre = itVertIdsCur if not verts: self.newError = True return {'CANCELLED'} the_object = create_mesh_and_object(context, verts, [], faces, "ZDataSurface") return {'FINISHED'} else: self.newError = False # self.report({'INFO'}, "Edit Over? Try it again.") return {'FINISHED'}
def execute(self, context): import addon_utils import traceback import zipfile import shutil import os pyfile = self.filepath if self.target == 'DEFAULT': # don't use bpy.utils.script_paths("addons") because we may not be able to write to it. path_addons = bpy.utils.user_resource('SCRIPTS', "addons", create=True) else: path_addons = context.preferences.filepaths.script_directory if path_addons: path_addons = os.path.join(path_addons, "addons") if not path_addons: self.report({'ERROR'}, "Failed to get add-ons path") return {'CANCELLED'} if not os.path.isdir(path_addons): try: os.makedirs(path_addons, exist_ok=True) except: traceback.print_exc() # Check if we are installing from a target path, # doing so causes 2+ addons of same name or when the same from/to # location is used, removal of the file! addon_path = "" pyfile_dir = os.path.dirname(pyfile) for addon_path in addon_utils.paths(): if os.path.samefile(pyfile_dir, addon_path): self.report({'ERROR'}, "Source file is in the add-on search path: %r" % addon_path) return {'CANCELLED'} del addon_path del pyfile_dir # done checking for exceptional case addons_old = {mod.__name__ for mod in addon_utils.modules()} # check to see if the file is in compressed format (.zip) if zipfile.is_zipfile(pyfile): try: file_to_extract = zipfile.ZipFile(pyfile, 'r') except: traceback.print_exc() return {'CANCELLED'} if self.overwrite: for f in file_to_extract.namelist(): module_filesystem_remove(path_addons, f) else: for f in file_to_extract.namelist(): path_dest = os.path.join(path_addons, os.path.basename(f)) if os.path.exists(path_dest): self.report({'WARNING'}, "File already installed to %r\n" % path_dest) return {'CANCELLED'} try: # extract the file to "addons" file_to_extract.extractall(path_addons) except: traceback.print_exc() return {'CANCELLED'} else: path_dest = os.path.join(path_addons, os.path.basename(pyfile)) if self.overwrite: module_filesystem_remove(path_addons, os.path.basename(pyfile)) elif os.path.exists(path_dest): self.report({'WARNING'}, "File already installed to %r\n" % path_dest) return {'CANCELLED'} # if not compressed file just copy into the addon path try: shutil.copyfile(pyfile, path_dest) except: traceback.print_exc() return {'CANCELLED'} addons_new = {mod.__name__ for mod in addon_utils.modules()} - addons_old addons_new.discard("modules") # disable any addons we may have enabled previously and removed. # this is unlikely but do just in case. bug [#23978] for new_addon in addons_new: addon_utils.disable(new_addon, default_set=True) # possible the zip contains multiple addons, we could disallow this # but for now just use the first for mod in addon_utils.modules(refresh=False): if mod.__name__ in addons_new: info = addon_utils.module_bl_info(mod) # show the newly installed addon. context.window_manager.addon_filter = 'All' context.window_manager.addon_search = info["name"] break # in case a new module path was created to install this addon. bpy.utils.refresh_script_paths() # print message msg = ( tip_("Modules Installed (%s) from %r into %r") % (", ".join(sorted(addons_new)), pyfile, path_addons) ) print(msg) self.report({'INFO'}, msg) return {'FINISHED'}
def pipeline(self, context): input_DEM = self.filepath #if input_DEM != bpy.path.ensure_ext(input_DEM, ".IMG"): #return {'CANCELLED'} dtm_location = input_DEM texture_location = '' merge_location ='' color_file = '' hill_shade = 'hillshade.tiff' color_relief = 'colorrelief.tiff' project_location = os.path.dirname(__file__) ################################################################################ ## Use the GDAL tools to create hill-shade and color-relief and merge them with ## hsv_merge.py to use as a texture for the DTM. Creates DTM_TEXTURE.tiff ################################################################################ if self.texture != None: texture_location = os.path.join(os.path.dirname(self.filepath), os.path.basename(self.texture)) elif self.color_pattern == 'NoColorPattern': texture_location=None else: # If user selected a colr we are going to run the gdal and merge processes # We need to dtermine which OS is being used and set the location of color files # and the merge script accordingly paths = addon_utils.paths() if _platform == "linux" or _platform == "linux2": # linux # Strip out the image name to set texture location and append color choice. texture_location = self.filepath.split('/')[-1:] texture_location = texture_location[0].split('.')[:1] texture_location = os.getcwd()+'/'+texture_location[0]+'_'+self.color_pattern+'.tiff' for path in paths: try: color_file = path + '/SpaceBlender/color_maps/' + self.color_pattern + '.txt' merge_location = path + '/SpaceBlender/hsv_merge.py' except: raise NameError("Could not load color maps (color_file) or merge script (merge_location)", color_file, merge_location) elif _platform == "darwin": # OS X # Strip out the image name to set texture location and append color choice. texture_location = self.filepath.split('/')[-1:] texture_location = texture_location[0].split('.')[:1] texture_location = os.getcwd()+'/'+texture_location[0]+'_'+self.color_pattern+'.tiff' for path in paths: try: color_file = path + '/SpaceBlender/color_maps/' + self.color_pattern + '.txt' merge_location = path + '/SpaceBlender/hsv_merge.py' except: raise NameError("Could not load color maps (color_file) or merge script (merge_location)", color_file, merge_location) elif _platform == "win32": # Windows. # Strip out the image name to set texture location and append color choice. texture_location = self.filepath.split('\\')[-1:] texture_location = texture_location[0].split('.')[:1] texture_location = os.getcwd()+'\\'+texture_location[0]+'_'+self.color_pattern+'.tiff' for path in paths: try: color_file = '"'+ path + '\\SpaceBlender\\color_maps\\'+self.color_pattern + '.txt'+'"' merge_location = '"'+ path + '\\SpaceBlender\\hsv_merge.py'+'"' except: raise NameError("Could not load color maps (color_file) or merge script (merge_location)", color_file, merge_location) gdal = gdal_module.GDALDriver(dtm_location) gdal.gdal_hillshade(hill_shade) gdal.gdal_color_relief(color_file, color_relief) gdal.hsv_merge(merge_location, hill_shade, color_relief, texture_location) print('\nSaving texture at: ' + texture_location) gdal.gdal_clean_up(hill_shade, color_relief) ################################################################################ ####################Execute DEM Importer and Blender Module##################### blender_module.load(self, context, filepath=self.filepath, scale=self.zscale, image_sample=self.scale, interp_method = self.interp, color_pattern=self.color_pattern, flyover_pattern=self.flyover_pattern, texture_location=texture_location, cropVars=False, resolution=self.resolution, stars=self.stars, mist=self.mist, render=True, animation=self.animation) return {'FINISHED'}
class AddTextDataSurface(bpy.types.Operator): """Add a surface from text data files.""" bl_idname = "mesh.primitive_text_data_surface" bl_label = "Add Text Data Surface" bl_options = {'REGISTER', 'UNDO', 'PRESET'} xFile = StringProperty( name="Data File of X(U,V)", description= "U,V: index coordinates of nodes; X: x coordinate of nodes. (Matrix Text)", default=addon_utils.paths()[0] + "/add_mesh_DataSurface/Xdata.txt", subtype="FILE_PATH") yFile = StringProperty( name="Data File of Y(U,V)", description= "U,V: index coordinates of nodes; Y: y coordinate of nodes. (Matrix Text)", default=addon_utils.paths()[0] + "/add_mesh_DataSurface/Ydata.txt", subtype="FILE_PATH") zFile = StringProperty( name="Data File of Z(U,V)", description= "U,V: index coordinates of nodes; Z: z coordinate of nodes. (Matrix Text)", default=addon_utils.paths()[0] + "/add_mesh_DataSurface/Zdata.txt", subtype="FILE_PATH") loop = BoolProperty(name="Loop in U Direction", description="Loop in U direction or not?", default=False) flip = BoolProperty( name="Flip Normal Vector", description="Flip the normal vector of surfaces or not?", default=False) def execute(self, context): xFile = self.xFile yFile = self.yFile zFile = self.zFile loop = self.loop flip = self.flip verts = [] faces = [] uNum = 0 vNum = 0 try: uNum, vNum, xValue = loadTextData(xFile) uNu2, vNu2, yValue = loadTextData(yFile) if (uNum != uNu2): raise Exception( "Error: U number not match between x and y.", "Hint: number of vertices in each x,y,z data should be the same." ) if (vNum != vNu2): raise Exception( "Error: V number not match between x and y.", "Hint: number of vertices in each x,y,z data should be the same." ) uNu3, vNu3, zValue = loadTextData(zFile) if (uNum != uNu3): raise Exception( "Error: U number not match between x and z.", "Hint: number of vertices in each x,y,z data should be the same." ) if (vNum != vNu3): raise Exception( "Error: V number not match between x and z.", "Hint: number of vertices in each x,y,z data should be the same." ) except: import traceback self.report({'ERROR'}, "Error combining coordinate data: " + traceback.format_exc(limit=1)) return {'CANCELLED'} itVertIdsPre = [] for itU in range(uNum): itVertIdsCur = [] for itV in range(vNum): itVertIdsCur.append(len(verts)) verts.append( (xValue[itV][itU], yValue[itV][itU], zValue[itV][itU])) if len(itVertIdsPre) > 0: faces.extend(makeFaces(itVertIdsPre, itVertIdsCur, loop, flip)) itVertIdsPre = itVertIdsCur if not verts: return {'CANCELLED'} the_object = create_mesh_and_object(context, verts, [], faces, "TextDataSurface") return {'FINISHED'}
class PresetsMenu(bpy.types.Menu): bl_label = "Renderman Presets" bl_idname = "presets" preset_subdir = os.path.join("renderman", "render") preset_operator = "script.execute_preset" draw = bpy.types.Menu.draw_preset ################# # Sample scenes menu. ################# # Watch out for global list!! # Its name should be too long to be accedenty called but you never know. blenderAddonPaths = addon_utils.paths() rendermanExampleFilesList = [] names = [] for path in blenderAddonPaths: basePath = os.path.join(path, "PRMan-for-Blender", "examples") exists = os.path.exists(basePath) if exists: names = get_Files_in_Directory(basePath) for name in names: class examplesRenderman(bpy.types.Operator): bl_idname = ("rendermanexamples." + name.lower()) bl_label = name bl_description = name def invoke(self, context, event): sucess = self.loadFile(self, self.bl_label)
import bpy import sys import addon_utils from pathlib import Path python_path = Path(sys.executable) blender_path = Path(bpy.app.binary_path) blender_directory = blender_path.parent use_own_python = blender_directory in python_path.parents version = bpy.app.version scripts_folder = blender_path.parent / f"{version[0]}.{version[1]}" / "scripts" user_addon_directory = Path(bpy.utils.user_resource('SCRIPTS', "addons")) addon_directories = tuple(map(Path, addon_utils.paths()))
def execute(self, context): if (not self.newError): xFile = self.xFile yFile = self.yFile zFile = self.zFile loop = self.loop flip = self.flip verts = [] faces = [] uNum = 0 vNum = 0 if (self.firstCall): self.firstCall = False successFlag = False for it_path in addon_utils.paths(): if (successFlag): break # successfully loaded, no need to continue xFile = it_path + "/add_mesh_DataSurface/Xdata.txt" yFile = it_path + "/add_mesh_DataSurface/Ydata.txt" zFile = it_path + "/add_mesh_DataSurface/Zdata.txt" self.xFile = xFile self.yFile = yFile self.zFile = zFile try: uNum, vNum, xValue = loadTextData(xFile) uNu2, vNu2, yValue = loadTextData(yFile) if (uNum != uNu2): raise Exception( "Error: U number not match between x and y.", "Hint: number of vertices in each x,y,z data should be the same." ) if (vNum != vNu2): raise Exception( "Error: V number not match between x and y.", "Hint: number of vertices in each x,y,z data should be the same." ) uNu3, vNu3, zValue = loadTextData(zFile) if (uNum != uNu3): raise Exception( "Error: U number not match between x and z.", "Hint: number of vertices in each x,y,z data should be the same." ) if (vNum != vNu3): raise Exception( "Error: V number not match between x and z.", "Hint: number of vertices in each x,y,z data should be the same." ) successFlag = True except FileNotFoundError as e: successFlag = False except: import traceback self.report({'ERROR'}, "Error combining coordinate data: " + traceback.format_exc(limit=1)) self.newError = True return {'CANCELLED'} if (not successFlag): errStr = "Fail to find example data files: \nI have searched in following paths:\n" for it_path in addon_utils.paths(): errStr += " " + it_path + "/add_mesh_DataSurface/Xdata.txt\n" self.report({'ERROR'}, errStr) self.newError = True return {'CANCELLED'} else: try: uNum, vNum, xValue = loadTextData(xFile) uNu2, vNu2, yValue = loadTextData(yFile) if (uNum != uNu2): raise Exception( "Error: U number not match between x and y.", "Hint: number of vertices in each x,y,z data should be the same." ) if (vNum != vNu2): raise Exception( "Error: V number not match between x and y.", "Hint: number of vertices in each x,y,z data should be the same." ) uNu3, vNu3, zValue = loadTextData(zFile) if (uNum != uNu3): raise Exception( "Error: U number not match between x and z.", "Hint: number of vertices in each x,y,z data should be the same." ) if (vNum != vNu3): raise Exception( "Error: V number not match between x and z.", "Hint: number of vertices in each x,y,z data should be the same." ) except: import traceback self.report({'ERROR'}, "Error combining coordinate data: " + traceback.format_exc(limit=1)) self.newError = True return {'CANCELLED'} itVertIdsPre = [] for itU in range(uNum): itVertIdsCur = [] for itV in range(vNum): itVertIdsCur.append(len(verts)) verts.append( (xValue[itV][itU], yValue[itV][itU], zValue[itV][itU])) if len(itVertIdsPre) > 0: faces.extend( makeFaces(itVertIdsPre, itVertIdsCur, loop, flip)) itVertIdsPre = itVertIdsCur if not verts: newError = True return {'CANCELLED'} the_object = create_mesh_and_object(context, verts, [], faces, "TextDataSurface") return {'FINISHED'} else: self.newError = False # self.report({'INFO'}, "Edit Over? Try it again.") return {'FINISHED'}
# The unpacked wheel is only loaded when actually used, not directly on import: os.path.join("io_blend_utils", "blender_bam-unpacked.whl"), } # Some modules need to add to the `sys.path`. MODULE_SYS_PATHS = { # Runs in a Python subprocess, so its expected its basedir can be imported. "io_blend_utils.blendfile_pack": ".", } if not bpy.app.build_options.freestyle: BLACKLIST.add("render_freestyle_svg") BLACKLIST_DIRS = ( os.path.join(bpy.utils.resource_path('USER'), "scripts"), ) + tuple(addon_utils.paths()[1:]) def module_names_recursive(mod_dir, *, parent=None): """ a version of bpy.path.module_names that includes non-packages """ is_package = os.path.exists(os.path.join(mod_dir, "__init__.py")) for n in os.listdir(mod_dir): if not n.startswith((".", "_")): submod_full = os.path.join(mod_dir, n) if os.path.isdir(submod_full): if not parent: subparent = n
def get_local_font_path(self): """getter: Returns the path where fonts used by Ephestos can be found""" import addon_utils result = addon_utils.paths()[0] + "/Ephestos/fonts" return result
import addon_utils import sys import os BLACKLIST = { "bl_i18n_utils", "bl_previews_utils", "cycles", "io_export_dxf", # TODO, check on why this fails 'io_import_dxf', # Because of cydxfentity.so dependency } BLACKLIST_DIRS = ( os.path.join(bpy.utils.resource_path('USER'), "scripts"), ) + tuple(addon_utils.paths()[1:]) def addon_modules_sorted(): modules = addon_utils.modules({}) modules[:] = [mod for mod in modules if not mod.__file__.startswith(BLACKLIST_DIRS)] modules.sort(key=lambda mod: mod.__name__) return modules def source_list(path, filename_check=None): from os.path import join for dirpath, dirnames, filenames in os.walk(path): # skip '.svn' if dirpath.startswith("."): continue
def execute(self, context): if (not self.newError): xFile = self.xFile yFile = self.yFile zFile = self.zFile loop = self.loop flip = self.flip verts = [] faces = [] uNum = 0 vNum = 0 if (self.firstCall): self.firstCall = False successFlag = False for it_path in addon_utils.paths(): if (successFlag): break; # successfully loaded, no need to continue xFile = it_path+"/add_mesh_DataSurface/Xdata.txt" yFile = it_path+"/add_mesh_DataSurface/Ydata.txt" zFile = it_path+"/add_mesh_DataSurface/Zdata.txt" self.xFile = xFile; self.yFile = yFile; self.zFile = zFile; try: uNum, vNum, xValue = loadTextData(xFile) uNu2, vNu2, yValue = loadTextData(yFile) if (uNum!=uNu2): raise Exception("Error: U number not match between x and y.", "Hint: number of vertices in each x,y,z data should be the same.") if (vNum!=vNu2): raise Exception("Error: V number not match between x and y.", "Hint: number of vertices in each x,y,z data should be the same.") uNu3, vNu3, zValue = loadTextData(zFile) if (uNum!=uNu3): raise Exception("Error: U number not match between x and z.", "Hint: number of vertices in each x,y,z data should be the same.") if (vNum!=vNu3): raise Exception("Error: V number not match between x and z.", "Hint: number of vertices in each x,y,z data should be the same.") successFlag = True except FileNotFoundError as e: successFlag = False except: import traceback self.report({'ERROR'}, "Error combining coordinate data: " + traceback.format_exc(limit=1)) self.newError = True return {'CANCELLED'} if (not successFlag): errStr = "Fail to find example data files: \nI have searched in following paths:\n" for it_path in addon_utils.paths(): errStr += " " + it_path+"/add_mesh_DataSurface/Xdata.txt\n" self.report({'ERROR'}, errStr) self.newError = True return {'CANCELLED'} else: try: uNum, vNum, xValue = loadTextData(xFile) uNu2, vNu2, yValue = loadTextData(yFile) if (uNum!=uNu2): raise Exception("Error: U number not match between x and y.", "Hint: number of vertices in each x,y,z data should be the same.") if (vNum!=vNu2): raise Exception("Error: V number not match between x and y.", "Hint: number of vertices in each x,y,z data should be the same.") uNu3, vNu3, zValue = loadTextData(zFile) if (uNum!=uNu3): raise Exception("Error: U number not match between x and z.", "Hint: number of vertices in each x,y,z data should be the same.") if (vNum!=vNu3): raise Exception("Error: V number not match between x and z.", "Hint: number of vertices in each x,y,z data should be the same.") except: import traceback self.report({'ERROR'}, "Error combining coordinate data: " + traceback.format_exc(limit=1)) self.newError = True return {'CANCELLED'} itVertIdsPre = [] for itU in range(uNum): itVertIdsCur = [] for itV in range(vNum): itVertIdsCur.append(len(verts)) verts.append( (xValue[itV][itU],yValue[itV][itU],zValue[itV][itU]) ) if len(itVertIdsPre)>0: faces.extend(makeFaces(itVertIdsPre,itVertIdsCur,loop,flip)) itVertIdsPre = itVertIdsCur if not verts: newError = True return {'CANCELLED'} the_object = create_mesh_and_object(context, verts, [], faces, "TextDataSurface") return {'FINISHED'} else: self.newError = False # self.report({'INFO'}, "Edit Over? Try it again.") return {'FINISHED'}
# knowledge of the CeCILL license and that you accept its terms. import bpy from bpy.props import * import os.path #Files functions of os lib import sys import addon_utils #utils to find addons path import shutil #Used to copy files from . import files from . import gui from . import interface from . import ressources from . import persistence for x in range(len(addon_utils.paths())): appending = sys.path.append(addon_utils.paths()[x] + '/addon/python3x') #Appending naming libs print(appending) '''<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< HELP OPERATOR >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>''' class Help(bpy.types.Operator): bl_idname = "scene.help" bl_label = "help" def execute(self, context):
def execute(self, context): import traceback import zipfile import shutil pyfile = self.filepath if self.target == 'DEFAULT': # dont use bpy.utils.script_paths("addons") because we may not be able to write to it. path_addons = bpy.utils.user_resource('SCRIPTS', "addons", create=True) else: path_addons = bpy.context.user_preferences.filepaths.script_directory if path_addons: path_addons = os.path.join(path_addons, "addons") if not path_addons: self.report({'ERROR'}, "Failed to get addons path") return {'CANCELLED'} # create dir is if missing. if not os.path.exists(path_addons): os.makedirs(path_addons) # Check if we are installing from a target path, # doing so causes 2+ addons of same name or when the same from/to # location is used, removal of the file! addon_path = "" pyfile_dir = os.path.dirname(pyfile) for addon_path in addon_utils.paths(): if os.path.samefile(pyfile_dir, addon_path): self.report({'ERROR'}, "Source file is in the addon search path: %r" % addon_path) return {'CANCELLED'} del addon_path del pyfile_dir # done checking for exceptional case addons_old = {mod.__name__ for mod in addon_utils.modules(USERPREF_PT_addons._addons_fake_modules)} #check to see if the file is in compressed format (.zip) if zipfile.is_zipfile(pyfile): try: file_to_extract = zipfile.ZipFile(pyfile, 'r') except: traceback.print_exc() return {'CANCELLED'} if self.overwrite: for f in file_to_extract.namelist(): WM_OT_addon_install._module_remove(path_addons, f) else: for f in file_to_extract.namelist(): path_dest = os.path.join(path_addons, os.path.basename(f)) if os.path.exists(path_dest): self.report({'WARNING'}, "File already installed to %r\n" % path_dest) return {'CANCELLED'} try: # extract the file to "addons" file_to_extract.extractall(path_addons) # zip files can create this dir with metadata, don't need it macosx_dir = os.path.join(path_addons, '__MACOSX') if os.path.isdir(macosx_dir): shutil.rmtree(macosx_dir) except: traceback.print_exc() return {'CANCELLED'} else: path_dest = os.path.join(path_addons, os.path.basename(pyfile)) if self.overwrite: WM_OT_addon_install._module_remove(path_addons, os.path.basename(pyfile)) elif os.path.exists(path_dest): self.report({'WARNING'}, "File already installed to %r\n" % path_dest) return {'CANCELLED'} #if not compressed file just copy into the addon path try: shutil.copyfile(pyfile, path_dest) except: traceback.print_exc() return {'CANCELLED'} addons_new = {mod.__name__ for mod in addon_utils.modules(USERPREF_PT_addons._addons_fake_modules)} - addons_old addons_new.discard("modules") # disable any addons we may have enabled previously and removed. # this is unlikely but do just incase. bug [#23978] for new_addon in addons_new: addon_utils.disable(new_addon) # possible the zip contains multiple addons, we could disallow this # but for now just use the first for mod in addon_utils.modules(USERPREF_PT_addons._addons_fake_modules): if mod.__name__ in addons_new: info = addon_utils.module_bl_info(mod) # show the newly installed addon. context.window_manager.addon_filter = 'All' context.window_manager.addon_search = info["name"] break # incase a new module path was created to install this addon. bpy.utils.refresh_script_paths() # TODO, should not be a warning. # self.report({'WARNING'}, "File installed to '%s'\n" % path_dest) return {'FINISHED'}
class PresetsMenu(bpy.types.Menu): bl_label = "Renderman Presets" bl_idname = "presets" preset_subdir = os.path.join("renderman", "render") preset_operator = "script.execute_preset" draw = bpy.types.Menu.draw_preset ################# # Sample scenes menu. ################# # Watch out for global list!! # Its name should be too long to be accedenty called but you never know. blenderAddonPaths = addon_utils.paths() rendermanExampleFilesList = [] names = [] for path in blenderAddonPaths: basePath = os.path.join(path, "PRMan-for-Blender", "examples") exists = os.path.exists(basePath) if exists: names = get_Files_in_Directory(basePath) for name in names: class examplesRenderman(bpy.types.Operator): bl_idname = ("rendermanexamples." + name.lower()) bl_label = name bl_description = name def invoke(self, context, event):
def execute(self, context): import traceback import zipfile import shutil pyfile = self.filepath if self.target == 'DEFAULT': # dont use bpy.utils.script_paths("addons") because we may not be able to write to it. path_addons = bpy.utils.user_resource('SCRIPTS', "addons", create=True) else: path_addons = bpy.context.user_preferences.filepaths.script_directory if path_addons: path_addons = os.path.join(path_addons, "addons") if not path_addons: self.report({'ERROR'}, "Failed to get addons path") return {'CANCELLED'} # create dir is if missing. if not os.path.exists(path_addons): os.makedirs(path_addons) # Check if we are installing from a target path, # doing so causes 2+ addons of same name or when the same from/to # location is used, removal of the file! addon_path = "" pyfile_dir = os.path.dirname(pyfile) for addon_path in addon_utils.paths(): if os.path.samefile(pyfile_dir, addon_path): self.report({'ERROR'}, "Source file is in the addon search path: %r" % addon_path) return {'CANCELLED'} del addon_path del pyfile_dir # done checking for exceptional case addons_old = { mod.__name__ for mod in addon_utils.modules( USERPREF_PT_addons._addons_fake_modules) } #check to see if the file is in compressed format (.zip) if zipfile.is_zipfile(pyfile): try: file_to_extract = zipfile.ZipFile(pyfile, 'r') except: traceback.print_exc() return {'CANCELLED'} if self.overwrite: for f in file_to_extract.namelist(): WM_OT_addon_install._module_remove(path_addons, f) else: for f in file_to_extract.namelist(): path_dest = os.path.join(path_addons, os.path.basename(f)) if os.path.exists(path_dest): self.report({'WARNING'}, "File already installed to %r\n" % path_dest) return {'CANCELLED'} try: # extract the file to "addons" file_to_extract.extractall(path_addons) # zip files can create this dir with metadata, don't need it macosx_dir = os.path.join(path_addons, '__MACOSX') if os.path.isdir(macosx_dir): shutil.rmtree(macosx_dir) except: traceback.print_exc() return {'CANCELLED'} else: path_dest = os.path.join(path_addons, os.path.basename(pyfile)) if self.overwrite: WM_OT_addon_install._module_remove(path_addons, os.path.basename(pyfile)) elif os.path.exists(path_dest): self.report({'WARNING'}, "File already installed to %r\n" % path_dest) return {'CANCELLED'} #if not compressed file just copy into the addon path try: shutil.copyfile(pyfile, path_dest) except: traceback.print_exc() return {'CANCELLED'} addons_new = { mod.__name__ for mod in addon_utils.modules( USERPREF_PT_addons._addons_fake_modules) } - addons_old addons_new.discard("modules") # disable any addons we may have enabled previously and removed. # this is unlikely but do just incase. bug [#23978] for new_addon in addons_new: addon_utils.disable(new_addon) # possible the zip contains multiple addons, we could disallow this # but for now just use the first for mod in addon_utils.modules( USERPREF_PT_addons._addons_fake_modules): if mod.__name__ in addons_new: info = addon_utils.module_bl_info(mod) # show the newly installed addon. context.window_manager.addon_filter = 'All' context.window_manager.addon_search = info["name"] break # incase a new module path was created to install this addon. bpy.utils.refresh_script_paths() # TODO, should not be a warning. # self.report({'WARNING'}, "File installed to '%s'\n" % path_dest) return {'FINISHED'}
## addon python management import bpy import addon_utils ## print all addons pathes for fp in addon_utils.paths(): print(fp) ## get list of enabled addon name on disk (stem of the .py file or the folder name for multifile addons) print(f'{len(bpy.context.preferences.addons.keys())} addons enabled') print(bpy.context.preferences.addons.keys()) ## print all addon names and version (from bl_info dic) for mod in addon_utils.modules(): print(mod.bl_info.get('name', ''), mod.bl_info.get('version', (-1, -1, -1))) ## enable / disable addon through python addon_name = 'Megaddon' if not addon_name in [m.bl_info.get('name') for m in addon_utils.modules()]: print(f'{addon_name} not found in addons') else: # Raise a silent error if not found and return None active = addon_utils.enable( addon_name) # default_set=False, persistent=False if active: print("enabled", active.bl_info['name']) else: print(addon_name, "not found !") ## Check loaded state of and addon