我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用bpy.ops()。
def updater_run_success_popup_handler(scene): global ran_update_sucess_popup ran_update_sucess_popup = True # in case of error importing updater if updater.invalidupdater == True: return try: bpy.app.handlers.scene_update_post.remove( updater_run_success_popup_handler) except: pass atr = addon_updater_updated_successful.bl_idname.split(".") getattr(getattr(bpy.ops, atr[0]),atr[1])('INVOKE_DEFAULT')
def post_update_callback(): # in case of error importing updater if updater.invalidupdater == True: return # this is the same code as in conditional at the end of the register function # ie if "auto_reload_post_update" == True, comment out this code if updater.verbose: print("{} updater: Running post update callback".format(updater.addon)) #bpy.app.handlers.scene_update_post.append(updater_run_success_popup_handler) atr = addon_updater_updated_successful.bl_idname.split(".") getattr(getattr(bpy.ops, atr[0]),atr[1])('INVOKE_DEFAULT') global ran_update_sucess_popup ran_update_sucess_popup = True return # function for asynchronous background check, which *could* be called on register
def __repr__(self): # useful display, repr(op) # import bpy idname = self.idname() as_string = op_as_string(idname) # XXX You never quite know what you get from bpy.types, # with operators... Operator and OperatorProperties # are shadowing each other, and not in the same way for # native ops and py ones! See T39158. # op_class = getattr(bpy.types, idname) op_class = op_get_rna(idname) descr = op_class.bl_rna.description # XXX, workaround for not registering # every __doc__ to save time on load. if not descr: descr = op_class.__doc__ if not descr: descr = "" return "# %s\n%s" % (descr, as_string)
def importMesh_PointSet(geom, ancestry, _): # VRML not x3d coord = geom.getChildBySpec('Coordinate') # works for x3d and vrml if coord: points = coord.getFieldAsArray('point', 3, ancestry) else: points = [] # vcolor = geom.getChildByName('color') # blender dosnt have per vertex color bpymesh = bpy.data.meshes.new("PointSet") bpymesh.vertices.add(len(points)) bpymesh.vertices.foreach_set("co", [a for v in points for a in v]) # No need to validate bpymesh.update() return bpymesh # ----------------------------------------------------------------------------------- # Primitives # SA: they used to use bpy.ops for primitive creation. That was # unbelievably slow on complex scenes. I rewrote to generate meshes # by hand.
def get_ops(): allops = [] opsdir = dir(bpy.ops) for opmodname in opsdir: opmod = getattr(bpy.ops, opmodname) opmoddir = dir(opmod) for o in opmoddir: name = opmodname + "." + o clazz = getclazz(name) if (clazz.__module__ != 'bpy.types'): allops.append(name) del opmoddir # add own operator name too, since its not loaded yet when this is called allops.append("text.edit_operator") l = sorted(allops) del allops del opsdir return [(y, y, "", x) for x, y in enumerate(l)]
def execute(self, context): found = False path, line, addon = getmodule(self.op) if addon: for t in bpy.data.texts: if t.filepath == path: ctx = context.copy() ctx['edit_text'] = t bpy.ops.text.jump(ctx, line=line) found = True break if (found is False): self.report({'INFO'}, "Opened file: " + path) bpy.ops.text.open(filepath=path) bpy.ops.text.jump(line=line) return {'FINISHED'} else: self.report({'WARNING'}, "Found no source file for " + self.op) return {'CANCELLED'}
def execute(self, context): from os.path import basename, splitext filepath = self.filepath # change the menu title to the most recently chosen option preset_class = getattr(bpy.types, self.menu_idname) preset_class.bl_label = bpy.path.display_name(basename(filepath)) ext = splitext(filepath)[1].lower() # execute the preset using script.python_file_run if ext == ".py": bpy.ops.script.python_file_run(filepath=filepath) elif ext == ".xml": import rna_xml rna_xml.xml_file_run(context, filepath, preset_class.preset_xml_map) else: self.report({'ERROR'}, "unknown filetype: %r" % ext) return {'CANCELLED'} return {'FINISHED'}
def invoke(self, context, event): wm = context.window_manager data_path = self.data_path prop_string = self.prop_string # same as eval("bpy.ops." + data_path) op_mod_str, ob_id_str = data_path.split(".", 1) op = getattr(getattr(bpy.ops, op_mod_str), ob_id_str) del op_mod_str, ob_id_str try: op_rna = op.get_rna() except KeyError: self.report({'ERROR'}, "Operator not found: bpy.ops.%s" % data_path) return {'CANCELLED'} def draw_cb(self, context): layout = self.layout pie = layout.menu_pie() pie.operator_enum(data_path, prop_string) wm.popup_menu_pie(draw_func=draw_cb, title=op_rna.bl_rna.name, event=event) return {'FINISHED'}
def execute(self, context): op_strings = [] tot = 0 for op_module_name in dir(bpy.ops): op_module = getattr(bpy.ops, op_module_name) for op_submodule_name in dir(op_module): op = getattr(op_module, op_submodule_name) text = repr(op) if text.split("\n")[-1].startswith("bpy.ops."): op_strings.append(text) tot += 1 op_strings.append('') textblock = bpy.data.texts.new("OperatorList.txt") textblock.write('# %d Operators\n\n' % tot) textblock.write('\n'.join(op_strings)) self.report({'INFO'}, "See OperatorList.txt textblock") return {'FINISHED'} # ----------------------------------------------------------------------------- # Add-on Operators
def execute(self, context): import addon_utils module_name = self.module modules = addon_utils.modules(refresh=False) mod = addon_utils.addons_fake_modules.get(module_name) if mod is not None: info = addon_utils.module_bl_info(mod) info["show_expanded"] = True bpy.context.user_preferences.active_section = 'ADDONS' context.window_manager.addon_filter = 'All' context.window_manager.addon_search = info["name"] bpy.ops.screen.userpref_show('INVOKE_DEFAULT') return {'FINISHED'} # Note: shares some logic with WM_OT_addon_install # but not enough to de-duplicate. Fixes here may apply to both.
def execute(self,context): if updater.update_ready == True: res = updater.run_update(force=False, callback=post_update_callback) # should return 0, if not something happened if updater.verbose: if res==0: print("Updater returned successful") else: print("Updater returned "+str(res)+", error occured") elif updater.update_ready == None: (update_ready, version, link) = updater.check_for_update(now=True) # re-launch this dialog atr = addon_updater_install_popup.bl_idname.split(".") getattr(getattr(bpy.ops, atr[0]),atr[1])('INVOKE_DEFAULT') #bpy.ops.retopoflow.updater_install_popup('INVOKE_DEFAULT') else: if updater.verbose:print("Doing nothing, not ready for update") return {'FINISHED'} # User preference check-now operator
def updater_run_install_popup_handler(scene): global ran_autocheck_install_popup ran_autocheck_install_popup = True try: bpy.app.handlers.scene_update_post.remove( updater_run_install_popup_handler) except: pass if "ignore" in updater.json and updater.json["ignore"] == True: return # don't do popup if ignore pressed atr = addon_updater_install_popup.bl_idname.split(".") getattr(getattr(bpy.ops, atr[0]),atr[1])('INVOKE_DEFAULT') # passed into the updater, background thread updater
def iter_exporters(): #categories = dir(bpy.ops) categories = ["export_anim", "export_mesh", "export_scene"] for category_name in categories: op_category = getattr(bpy.ops, category_name) for name in dir(op_category): total_name = category_name + "." + name if total_name == ExportSelected.bl_idname: continue if "export" in total_name: op = getattr(op_category, name) yield total_name, op
def execute(self, context): with ToggleObjectMode(undo=None): self.clear_world(context) if self.format: props = {} for key in CurrentFormatProperties._keys(): props[key] = getattr(self.format_props, key) props["filepath"] = self.filepath op = get_op(self.format) op(**props) else: bpy.ops.wm.save_as_mainfile( filepath=self.filepath, copy=True, ) bpy.ops.ed.undo() bpy.ops.ed.undo_push(message="Export Selected") return {'FINISHED'}
def execute(self, context): selected_rock = active() try: is_rock = selected_rock.get('ROCK_GENERATOR') except KeyError: self.report({'ERROR'}, "No active rock object!") return {'CANCELLED'} if not is_rock: self.report({'ERROR'}, "No active rock object!") return {'CANCELLED'} for s in context.selected_objects: s.select = False selected_rock.select = True bpy.ops.object.delete(use_global=False) build_rock(context) return {'FINISHED'}
def updater_run_success_popup_handler(scene): global ran_update_sucess_popup ran_update_sucess_popup = True # in case of error importing updater if updater.invalidupdater == True: return try: bpy.app.handlers.scene_update_post.remove( updater_run_success_popup_handler) except: pass atr = ARCHIPACK_OT_updater_updated_successful.bl_idname.split(".") getattr(getattr(bpy.ops, atr[0]),atr[1])('INVOKE_DEFAULT')
def post_update_callback(): # in case of error importing updater if updater.invalidupdater == True: return # this is the same code as in conditional at the end of the register function # ie if "auto_reload_post_update" == True, comment out this code if updater.verbose: print("{} updater: Running post update callback".format(updater.addon)) #bpy.app.handlers.scene_update_post.append(updater_run_success_popup_handler) atr = ARCHIPACK_OT_updater_updated_successful.bl_idname.split(".") getattr(getattr(bpy.ops, atr[0]),atr[1])('INVOKE_DEFAULT') global ran_update_sucess_popup ran_update_sucess_popup = True return # function for asynchronous background check, which *could* be called on register
def get_obj_mesh_pair(obj, context): log.debug('Transforming object into mesh: %s', obj.name) mesh = obj.to_mesh(context.scene, apply_modifiers=True, settings='RENDER') mesh.name = obj.name mesh.transform(Matrix.Rotation(-math.pi / 2, 4, 'X') * obj.matrix_world) bm = bmesh.new() bm.from_mesh(mesh) bmesh.ops.triangulate(bm, faces=bm.faces) bm.to_mesh(mesh) bm.free() del bm mesh.calc_normals() mesh.calc_tessface() return (obj, mesh)
def post_update_callback(res=None): # in case of error importing updater if updater.invalidupdater == True: return if res==None: # this is the same code as in conditional at the end of the register function # ie if "auto_reload_post_update" == True, comment out this code if updater.verbose: print("{} updater: Running post update callback".format(updater.addon)) #bpy.app.handlers.scene_update_post.append(updater_run_success_popup_handler) atr = addon_updater_updated_successful.bl_idname.split(".") getattr(getattr(bpy.ops, atr[0]),atr[1])('INVOKE_DEFAULT') global ran_update_sucess_popup ran_update_sucess_popup = True else: # some kind of error occured and it was unable to install, # offer manual download instead atr = addon_updater_updated_successful.bl_idname.split(".") getattr(getattr(bpy.ops, atr[0]),atr[1])('INVOKE_DEFAULT',error=res) return # function for asynchronous background check, which *could* be called on register
def execute(self, context): activeObj = context.active_object for SelectedObject in bpy.context.selected_objects : bpy.context.scene.objects.active = SelectedObject oldMode = SelectedObject.mode bpy.ops.object.mode_set(mode='OBJECT') for md in SelectedObject.modifiers : # apply the modifier try: bpy.ops.object.modifier_apply(apply_as='DATA', modifier=md.name) except: pass bpy.ops.object.mode_set(mode=oldMode) bpy.context.scene.objects.active = activeObj return {'FINISHED'}
def boolean_optimized(mode): context = bpy.context obj = context.active_object object_prepare() obj.select = False obs = context.selected_objects ob = obs[0] if len(obs) != 1: context.scene.objects.active = ob bpy.ops.object.join() context.scene.objects.active = obj mesh_selection(obj, 'DESELECT') mesh_selection(ob, 'SELECT') modifier_boolean(obj, ob, mode) obj.select = True
def union(): context = bpy.context mode = 'UNION' def separate(): ops = bpy.ops ops_ob = ops.object ops_ob.mode_set(mode="EDIT") ops.mesh.separate(type="LOOSE") ops_ob.mode_set(mode="OBJECT") boolean_optimized(mode) separate() if len(context.selected_objects) != 1: boolean_each(mode)
def updater_run_install_popup_handler(scene): global ran_autocheck_install_popup ran_autocheck_install_popup = True try: bpy.app.handlers.scene_update_post.remove( updater_run_install_popup_handler) except: pass if "ignore" in updater.json and updater.json["ignore"] == True: return # don't do popup if ignore pressed atr = addon_updater_install_popup.bl_idname.split(".") getattr(getattr(bpy.ops, atr[0]), atr[1])('INVOKE_DEFAULT') # passed into the updater, background thread updater
def __init__(self): bpy.ops.object.mode_set(mode='OBJECT') object_ = bpy.context.active_object self.node_name = object_.name self.node_type = 'cgf' if object_.type not in ('MESH', 'EMPTY'): self.report( {'ERROR'}, "Selected object is not a mesh! Please select a mesh object.") return {'FINISHED'} if object_.parent and object_.parent.type == 'ARMATURE': if len(object_.data.vertices) <= 4: self.node_type = 'chr' self.node_name = object_.parent.name else: self.node_type = 'skin' elif object_.animation_data: self.node_type = 'cga'
def execute(self, context): if bpy.context.selected_objects: scene = bpy.context.scene node_name = "{}.{}".format(self.node_name, self.node_type) group = bpy.data.groups.get(node_name) if group is None: bpy.ops.group.create(name=node_name) else: for object in bpy.context.selected_objects: if object.name not in group.objects: group.objects.link(object) message = "Adding Export Node" else: message = "No Objects Selected" self.report({"INFO"}, message) return {"FINISHED"}
def execute(self, context): old_cursor = context.scene.cursor_location.copy() for obj in context.selected_objects: ctx = utils.override(obj, active=True, selected=True) bpy.ops.object.origin_set( ctx, type="ORIGIN_GEOMETRY", center="BOUNDS") bpy.ops.view3d.snap_cursor_to_selected(ctx) x, y, z = bpy.context.scene.cursor_location z = obj.location.z - obj.dimensions.z / 2 - self.z_offset bpy.context.scene.cursor_location = Vector((x, y, z)) bpy.ops.object.origin_set(ctx, type="ORIGIN_CURSOR") bpy.context.scene.cursor_location = Vector((0, 0, 0)) bpy.ops.view3d.snap_selected_to_cursor(ctx) bpy.context.scene.cursor_location = old_cursor return {'FINISHED'}
def execute(self, context): active_object = bpy.context.active_object bpy.ops.object.mode_set(mode='OBJECT') selected_vert_coordinates = get_vertex_data() if (selected_vert_coordinates): selected_vert = selected_vert_coordinates[0] bpy.ops.object.add( type='EMPTY', view_align=False, enter_editmode=False, location=( selected_vert[0], selected_vert[1], selected_vert[2])) empty_object = bpy.context.active_object empty_object.name = name_branch(True) utils.set_active(active_object) bpy.ops.object.mode_set(mode='EDIT') message = "Adding Branch" self.report({'INFO'}, message) bcPrint(message) return {'FINISHED'}
def execute(self, context): mesh = bpy.context.active_object.data vert_list = [vert for vert in mesh.vertices] context.tool_settings.mesh_select_mode = (True, False, False) bpy.ops.object.mode_set(mode='OBJECT') bcPrint("Locating degenerate faces.") for i in mesh.edges: counter = 0 for polygon in mesh.polygons: if (i.vertices[0] in polygon.vertices and i.vertices[1] in polygon.vertices): counter += 1 if counter > 2: bcPrint('Found a multi-face line') for v in i.vertices: bcPrint('Selecting line vertices.') vert_list[v].select = True bpy.ops.object.mode_set(mode='EDIT') return {'FINISHED'}
def __init__(self): armature = bpy.context.active_object if not armature or armature.type != 'ARMATURE': self.report({'ERROR'}, "Please select a armature object!") return {'FINISHED'} elif armature.pose.bones.find('Root') != -1: message = "{} armature already has a Root bone!".format( armature.name) self.report({'INFO'}, message) return {'FINISHED'} bpy.ops.object.mode_set(mode='EDIT') root_bone = utils.get_root_bone(armature) loc = root_bone.head if loc.x == 0 and loc.y == 0 and loc.z == 0: message = "Armature already has a root/center bone!" self.report({'INFO'}, message) return {'FINISHED'} else: self.hips_bone = root_bone.name
def __set_primitive_mesh_material(self, armature, materials): object_ = utils.get_chr_object_from_skeleton(armature) object_.select = True bpy.context.scene.objects.active = object_ mat = None if self.use_single_material: mat = materials['single'] else: mat = materials['primitive'] if object_.material_slots: object_.material_slots[0].material = mat else: bpy.ops.object.material_slot_add() if object_.material_slots: object_.material_slots[0].material = mat object_.select = False
def execute(self, context): bcPrint(Configuration.rc_path, 'debug', True) try: config = Export.Config(config=self) if self.run_in_profiler: import cProfile cProfile.runctx('export.save(config)', {}, {'export': export, 'config': config}) else: export.save(config) self.filepath = '//' except exceptions.BCryException as exception: bcPrint(exception.what(), 'error') bpy.ops.screen.display_error( 'INVOKE_DEFAULT', message=exception.what()) return {'FINISHED'}
def execute(self, context): bcPrint(Configuration.rc_path, 'debug') try: config = ExportAnimations.Config(config=self) if self.run_in_profiler: import cProfile cProfile.runctx( 'export_animations.save(config)', {}, { 'export_animations': export_animations, 'config': config}) else: export_animations.save(config) self.filepath = '//' except exceptions.BCryException as exception: bcPrint(exception.what(), 'error') bpy.ops.screen.display_error( 'INVOKE_DEFAULT', message=exception.what()) return {'FINISHED'}
def execute(self,context): # in case of error importing updater if updater.invalidupdater == True: return {'CANCELLED'} if updater.manual_only==True: row.operator("wm.url_open",text="Open website").url=\ updater.website elif updater.update_ready == True: res = updater.run_update(force=False, callback=post_update_callback) # should return 0, if not something happened if updater.verbose: if res==0: print("Updater returned successful") else: print("Updater returned "+str(res)+", error occurred") elif updater.update_ready is None: (update_ready, version, link) = updater.check_for_update(now=True) # re-launch this dialog atr = addon_updater_install_popup.bl_idname.split(".") getattr(getattr(bpy.ops, atr[0]),atr[1])('INVOKE_DEFAULT') else: if updater.verbose:print("Doing nothing, not ready for update") return {'FINISHED'} # User preference check-now operator
def execute(self,context): # in case of error importing updater if updater.invalidupdater == True: return {'CANCELLED'} if updater.manual_only == True: row.operator("wm.url_open",text="Open website").url=\ updater.website if updater.update_ready == True: # if it fails, offer to open the website instead try: res = updater.run_update( force=False, callback=post_update_callback) # should return 0, if not something happened if updater.verbose: if res==0: print("Updater returned successful") else: print("Updater returned "+str(res)+", error occurred") except: atr = addon_updater_install_manually.bl_idname.split(".") getattr(getattr(bpy.ops, atr[0]),atr[1])('INVOKE_DEFAULT') elif updater.update_ready is None: (update_ready, version, link) = updater.check_for_update(now=True) # re-launch this dialog atr = addon_updater_install_popup.bl_idname.split(".") getattr(getattr(bpy.ops, atr[0]),atr[1])('INVOKE_DEFAULT') elif updater.update_ready == False: self.report({'INFO'}, "Nothing to update") else: self.report({'ERROR'}, "Encountered problem while trying to update") return {'FINISHED'}
def updater_run_install_popup_handler(scene): global ran_autocheck_install_popup ran_autocheck_install_popup = True # in case of error importing updater if updater.invalidupdater == True: return try: bpy.app.handlers.scene_update_post.remove( updater_run_install_popup_handler) except: pass if "ignore" in updater.json and updater.json["ignore"] == True: return # don't do popup if ignore pressed elif type(updater.update_version) != type((0,0,0)): # likely was from master or another branch, shouldn't trigger popup updater.json_reset_restore() return elif "version_text" in updater.json and "version" in updater.json["version_text"]: version = updater.json["version_text"]["version"] ver_tuple = updater.version_tuple_from_text(version) if ver_tuple < updater.current_version: # user probably manually installed to get the up to date addon # in here. Clear out the update flag using this function if updater.verbose: print("{} updater: appears user updated, clearing flag".format(\ updater.addon)) updater.json_reset_restore() return atr = addon_updater_install_popup.bl_idname.split(".") getattr(getattr(bpy.ops, atr[0]),atr[1])('INVOKE_DEFAULT') # passed into the updater, background thread updater
def add_scrollback(text, text_type): for l in text.split("\n"): bpy.ops.console.scrollback_append(text=l.replace("\t", " "), type=text_type)