我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用bpy.context()。
def check_name(self,context): sprite_object = get_sprite_object(context.active_object) if self.name_old != "" and self.name_change_to != self.name: name_array = [] for item in sprite_object.coa_anim_collections: name_array.append(item.name_old) self.name_change_to = check_name(name_array,self.name) self.name = self.name_change_to for child in get_children(context,sprite_object,ob_list=[]): action_name = self.name_old + "_" + child.name action_name_new = self.name + "_" + child.name if action_name in bpy.data.actions: action = bpy.data.actions[action_name] action.name = action_name_new self.name_old = self.name
def draw(self, context): layout = self.layout row = layout.row() row.alignment = "CENTER" pcoll = preview_collections["main"] donate_icon = pcoll["donate_icon"] twitter_icon = pcoll["twitter_icon"] row.operator("coa_operator.coa_donate",text="Show Your Love",icon_value=donate_icon.icon_id,emboss=True) row = layout.row() row.alignment = "CENTER" row.scale_x = 1.75 op = row.operator("coa_operator.coa_tweet",text="Tweet",icon_value=twitter_icon.icon_id,emboss=True) op.link = "https://www.youtube.com/ndee85" op.text = "Check out CutoutAnimation Tools Addon for Blender by Andreas Esau." op.hashtags = "b3d,coatools" op.via = "ndee85"
def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index): ob = data slot = item col = layout.row(align=True) if item.name not in ["NO ACTION","Restpose"]: col.label(icon="ACTION") col.prop(item,"name",emboss=False,text="") elif item.name == "NO ACTION": col.label(icon="RESTRICT_SELECT_ON") col.label(text=item.name) elif item.name == "Restpose": col.label(icon="ARMATURE_DATA") col.label(text=item.name) if context.scene.coa_nla_mode == "NLA" and item.name not in ["NO ACTION","Restpose"]: col = layout.row(align=False) op = col.operator("coa_operator.create_nla_track",icon="NLA",text="") op.anim_collection_name = item.name ### Custom template_list look for event lists
def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index): ob = data slot = item col = layout.column(align=False) row = col.row(align=True) row.label(text="",icon="TIME") row.prop(item,"frame",emboss=False,text="Frame") op = row.operator("coa_tools.remove_timeline_event",text="",icon="PANEL_CLOSE",emboss=False) op.index = index row = col.row(align=True) row.prop(item,"event",emboss=True,text="Event") row.prop(item,"action",emboss=True,text="Action") row.prop(item,"sound",emboss=True,text="Sound") ######################################################################################################################################### Select Child Operator
def select_child(self,context): if self.mode == "object": ob = bpy.data.objects[self.ob_name] ob.coa_hide_select = False ob.coa_hide = False ob.select = not(ob.select) context.scene.objects.active = ob elif self.mode == "bone": armature_ob = bpy.data.objects[self.ob_name] armature = bpy.data.armatures[armature_ob.data.name] bone = armature.bones[self.bone_name] bone.select = not bone.select bone.select_tail = not bone.select_tail bone.select_head = not bone.select_head if bone.select == True: armature.bones.active = bone else: armature.bones.active = None
def modal(self, context, event): wm = context.window_manager context.area.tag_redraw() for region in context.area.regions: if region.type == "TOOLS": self.region_offset = region.width if region.type == "WINDOW": self.region_height = region.height self.scale = self.region_height/920 self.scale = min(1.0,max(.7,self.scale)) if context.user_preferences.system.use_region_overlap: pass else: self.region_offset = 0 if not wm.coa_show_help: self.alpha = 0.0 if not wm.coa_show_help and round(self.alpha_current,1) == 0:#event.type in {"RIGHTMOUSE", "ESC"}: return self.finish() if self.alpha != round(self.alpha_current,1): self.fade() return {"PASS_THROUGH"}
def project_cursor(self, event): coord = mathutils.Vector((event.mouse_region_x, event.mouse_region_y)) transform = bpy_extras.view3d_utils.region_2d_to_location_3d region = bpy.context.region rv3d = bpy.context.space_data.region_3d #### cursor used for the depth location of the mouse #depth_location = bpy.context.scene.cursor_location depth_location = bpy.context.active_object.location ### creating 3d vector from the cursor end = transform(region, rv3d, coord, depth_location) #end = transform(region, rv3d, coord, bpy.context.space_data.region_3d.view_location) ### Viewport origin start = bpy_extras.view3d_utils.region_2d_to_origin_3d(region, rv3d, coord) ### Cast ray from view to mouselocation if b_version_bigger_than((2,76,0)): ray = bpy.context.scene.ray_cast(start, (start+(end-start)*2000)-start ) else: ray = bpy.context.scene.ray_cast(start, start+(end-start)*2000) ### ray_cast return values have changed after blender 2.67.0 if b_version_bigger_than((2,76,0)): ray = [ray[0],ray[4],ray[5],ray[1],ray[2]] return start, end, ray
def limit_cursor_by_bounds(self,context,location): obj = context.active_object bounds = self.bounds#get_bounds_and_center(obj)[1] if len(bounds) > 0: e1 = [bounds[0],bounds[2]] ### top edge e2 = [bounds[2],bounds[3]] ### right edge e3 = [bounds[3],bounds[1]] ### bottom edge e4 = [bounds[1],bounds[0]] ### left edge p1 = self.get_projected_point(e1,custom_pos=None,disable_edge_threshold=True) + Vector((0,0,-.1)) p2 = self.get_projected_point(e2,custom_pos=None,disable_edge_threshold=True) + Vector((-.1,0,0)) p3 = self.get_projected_point(e3,custom_pos=None,disable_edge_threshold=True) + Vector((0,0,.1)) p4 = self.get_projected_point(e4,custom_pos=None,disable_edge_threshold=True) + Vector((.1,0,0)) edges = [e1,e2,e3,e4] points_on_edge = [p1,p2,p3,p4] mouse_vec = [self.mesh_center,location] for j,edge in enumerate(edges): #mouse_vec = [points_on_edge[j] , location] i = geometry.intersect_line_line_2d(edge[0].xz,edge[1].xz,mouse_vec[0].xz,mouse_vec[1].xz) if i != None: location = Vector((i[0],location[1],i[1])) return location
def get_projected_point(self,edge,custom_pos=None,disable_edge_threshold=False): context = bpy.context obj = context.active_object mouse_pos = custom_pos if custom_pos != None else self.mouse_pos_3d if type(edge) == bmesh.types.BMEdge: v1 = obj.matrix_world * edge.verts[0].co v2 = obj.matrix_world * edge.verts[1].co elif type(edge) == list: v1 = obj.matrix_world * edge[0] v2 = obj.matrix_world * edge[1] dist = context.scene.coa_snap_distance * context.space_data.region_3d.view_distance if disable_edge_threshold: dist = 0 p1 = (v1 - v2).normalized() p2 = mouse_pos - v2 l = max(min(p2.dot(p1), (v1 - v2).magnitude - dist),0 + dist) c = (v2 + l * p1) return c
def get_visible_verts(self,context,bm): obj = context.active_object visible_verts = [] self.selected_verts_count = 0 delete_search = self.ctrl and not self.type in ["MIDDLEMOUSE"] active_vert = None if len(bm.select_history)>0 and type(bm.select_history[0]) == bmesh.types.BMVert: active_vert = bm.select_history[0] for vert in bm.verts: if not vert.hide and vert.select: self.selected_verts_count += 1 if not vert.hide:# and (vert.is_boundary or vert.is_wire or len(vert.link_edges)==0 or delete_search): visible_verts.append([obj.matrix_world * vert.co , vert]) return visible_verts
def get_intersecting_lines(self,coord,bm): scene = bpy.context.scene vertex_vec_new = self.limit_cursor_by_bounds(bpy.context,coord) if scene.coa_surface_snap: coord, point_type, bm_ob = self.snap_to_edge_or_vert(vertex_vec_new) else: coord, point_type, bm_ob = [None,None,None] intersection_points = [] if self.selected_vert_coord != None and coord != None: obj = bpy.context.active_object e1 = [self.selected_vert_coord.xz,coord.xz] for edge in bm.edges: if not edge.hide:# and (edge.is_wire or edge.is_boundary): e2 = [(obj.matrix_world * edge.verts[0].co).xz , (obj.matrix_world * edge.verts[1].co).xz ] ip = geometry.intersect_line_line_2d(e1[0],e1[1],e2[0],e2[1]) if ip != None: ip = Vector((ip[0],self.selected_vert_coord[1],ip[1])) if (ip - self.selected_vert_coord).magnitude > 0.001 and (ip - coord).magnitude > 0.001: #ip, point_type, bm_ob = self.snap_to_edge_or_vert(ip) ### snap intersection points intersection_points.append(ip) intersection_points.sort(key=lambda x: (self.selected_vert_coord - x).magnitude) return intersection_points
def exit_edit_weights(self,context): tool_settings = context.scene.tool_settings tool_settings.unified_paint_settings.use_unified_strength = self.use_unified_strength set_local_view(False) armature = get_armature(get_sprite_object(context.active_object)) bpy.ops.object.mode_set(mode="OBJECT") for i,bone_layer in enumerate(bone_layers): armature.data.layers[i] = bone_layer for obj in context.scene.objects: obj.select = False for name in self.selected_objects: obj = bpy.data.objects[name] obj.select = True context.scene.objects.active = bpy.data.objects[self.active_object] self.unhide_non_deform_bones(context) self.hide_deform_bones(context)
def remove_base_mesh(obj): bpy.ops.object.mode_set(mode="EDIT") bm = bmesh.from_edit_mesh(obj.data) bm.verts.ensure_lookup_table() verts = [] if "coa_base_sprite" in obj.vertex_groups: v_group_idx = obj.vertex_groups["coa_base_sprite"].index for i,vert in enumerate(obj.data.vertices): for g in vert.groups: if g.group == v_group_idx: verts.append(bm.verts[i]) break bmesh.ops.delete(bm,geom=verts,context=1) bm = bmesh.update_edit_mesh(obj.data) bpy.ops.object.mode_set(mode="OBJECT")
def check_region(context,event): in_view_3d = False if context.area != None: if context.area.type == "VIEW_3D": t_panel = context.area.regions[1] n_panel = context.area.regions[3] view_3d_region_x = Vector((context.area.x + t_panel.width, context.area.x + context.area.width - n_panel.width)) view_3d_region_y = Vector((context.region.y, context.region.y+context.region.height)) if event.mouse_x > view_3d_region_x[0] and event.mouse_x < view_3d_region_x[1] and event.mouse_y > view_3d_region_y[0] and event.mouse_y < view_3d_region_y[1]: in_view_3d = True else: in_view_3d = False else: in_view_3d = False return in_view_3d
def create_action(context,item=None,obj=None): sprite_object = get_sprite_object(context.active_object) if len(sprite_object.coa_anim_collections) < 3: bpy.ops.my_operator.add_animation_collection() if item == None: item = sprite_object.coa_anim_collections[sprite_object.coa_anim_collections_index] if obj == None: obj = context.active_object action_name = item.name + "_" + obj.name if action_name not in bpy.data.actions: action = bpy.data.actions.new(action_name) else: action = bpy.data.actions[action_name] action.use_fake_user = True if obj.animation_data == None: obj.animation_data_create() obj.animation_data.action = action context.scene.update()
def create_armature(context): obj = bpy.context.active_object sprite_object = get_sprite_object(obj) armature = get_armature(sprite_object) if armature != None: context.scene.objects.active = armature armature.select = True return armature else: amt = bpy.data.armatures.new("Armature") armature = bpy.data.objects.new("Armature",amt) armature.parent = sprite_object context.scene.objects.link(armature) context.scene.objects.active = armature armature.select = True amt.draw_type = "BBONE" return armature
def set_view(screen,mode): if mode == "2D": active_space_data = bpy.context.space_data if active_space_data != None: if hasattr(active_space_data,"region_3d"): region_3d = active_space_data.region_3d bpy.ops.view3d.viewnumpad(type='FRONT') if region_3d.view_perspective != "ORTHO": bpy.ops.view3d.view_persportho() elif mode == "3D": active_space_data = bpy.context.space_data if active_space_data != None: if hasattr(active_space_data,"region_3d"): region_3d = active_space_data.region_3d if region_3d.view_perspective == "ORTHO": bpy.ops.view3d.view_persportho()
def ray_cast(start,end,list=[]): if b_version_bigger_than((2,76,0)): end = end - start result = bpy.context.scene.ray_cast(start,end) if b_version_bigger_than((2,76,0)): result = [result[0],result[4],result[5],result[1],result[2]] if result[0]: if result not in list: list.append(result) else: return list dir_vec = (end - start).normalized() new_start = result[3] + (dir_vec*0.000001) return ray_cast(new_start,end,list) else: return list
def set_uv_default_coords(context,obj): uv_coords = obj.data.uv_layers[obj.data.uv_layers.active.name].data ### add uv items for i in range(len(uv_coords)-len(obj.coa_uv_default_state)): item = obj.coa_uv_default_state.add() ### remove unneeded uv items if len(uv_coords) < len(obj.coa_uv_default_state): for i in range(len(obj.coa_uv_default_state) - len(uv_coords)): obj.coa_uv_default_state.remove(0) ### set default uv coords frame_size = Vector((1 / obj.coa_tiles_x,1 / obj.coa_tiles_y)) pos_x = frame_size.x * (obj.coa_sprite_frame % obj.coa_tiles_x) pos_y = frame_size.y * -int(int(obj.coa_sprite_frame) / int(obj.coa_tiles_x)) frame = Vector((pos_x,pos_y)) offset = Vector((0,1-(1/obj.coa_tiles_y))) for i,coord in enumerate(uv_coords): uv_vec_x = (coord.uv[0] - frame[0]) * obj.coa_tiles_x uv_vec_y = (coord.uv[1] - offset[1] - frame[1]) * obj.coa_tiles_y uv_vec = Vector((uv_vec_x,uv_vec_y)) obj.coa_uv_default_state[i].uv = uv_vec
def change_slot_mesh_data(context,obj): if len(obj.coa_slot) > 0: slot_len = len(obj.coa_slot)-1 obj["coa_slot_index"] = min(obj.coa_slot_index,max(0,len(obj.coa_slot)-1)) idx = max(min(obj.coa_slot_index,len(obj.coa_slot)-1),0) slot = obj.coa_slot[idx] obj = slot.id_data obj.data = slot.mesh set_alpha(obj,context,obj.coa_alpha) for slot2 in obj.coa_slot: if slot != slot2: slot2["active"] = False else: slot2["active"] = True if "coa_base_sprite" in obj.modifiers: if slot.mesh.coa_hide_base_sprite: obj.modifiers["coa_base_sprite"].show_render = True obj.modifiers["coa_base_sprite"].show_viewport = True else: obj.modifiers["coa_base_sprite"].show_render = False obj.modifiers["coa_base_sprite"].show_viewport = False
def unregister(): for pcoll in preview_collections.values(): bpy.utils.previews.remove(pcoll) preview_collections.clear() try: bpy.utils.unregister_module(__name__) except: traceback.print_exc() print("Unregistered {}".format(bl_info["name"])) bpy.context.window_manager.coa_running_modal = False bpy.app.handlers.frame_change_post.remove(update_sprites) bpy.app.handlers.scene_update_pre.remove(scene_update) bpy.app.handlers.load_post.remove(coa_startup) unregister_keymaps()
def coa_startup(dummy): print("startup coa modal operator") bpy.app.handlers.scene_update_pre.append(scene_update_callback) hide_base_sprite_version_fix() ### version fix coa_fix_slots() ### fix coa_slots to point to mesh data for obj in bpy.data.objects: if obj.type == "MESH": if "sprite" in obj: obj["coa_sprite"] = True del obj["sprite"] if "coa_sprite" in obj: obj.coa_sprite_updated = False obj.coa_tiles_changed = True set_uv_default_coords(bpy.context,obj)
def import_audio(self, project_directory, audio_files, import_channel): """ Imports audio files as sound strips from absolute file paths Returns the list of newly imported audio files """ import_frame = bpy.context.scene.frame_current new_sequences = [] for f in audio_files: audio_abs_path = os.path.join(project_directory, f) bpy.ops.sequencer.sound_strip_add( self.SEQUENCER_AREA, filepath=audio_abs_path, frame_start=import_frame, channel=import_channel) new_sequences.extend(bpy.context.selected_sequences) import_frame = bpy.context.selected_sequences[0].frame_final_end return new_sequences
def import_img(self, project_directory, img_files, import_channel): import_frame = bpy.context.scene.frame_current new_sequences = [] for f in img_files: head, tail = os.path.split(f) img_directory = os.path.join(project_directory, head) img_file_dict = [{'name': tail}] bpy.ops.sequencer.image_strip_add( self.SEQUENCER_AREA, directory=img_directory, files=img_file_dict, frame_start=import_frame, frame_end=import_frame + self.img_length, channel=import_channel) import_frame += self.img_length + self.img_padding new_sequences.extend(bpy.context.selected_sequences) return new_sequences
def create_block(x, y, hw, h, verts: list, faces: list): if bpy.context.scene.cubester_block_style == "size": z = 0.0 else: z = h h = 2 * hw p = len(verts) verts += [(x - hw, y - hw, z), (x + hw, y - hw, z), (x + hw, y + hw, z), (x - hw, y + hw, z)] verts += [(x - hw, y - hw, z + h), (x + hw, y - hw, z + h), (x + hw, y + hw, z + h), (x - hw, y + hw, z + h)] faces += [(p, p+1, p+5, p+4), (p+1, p+2, p+6, p+5), (p+2, p+3, p+7, p+6), (p, p+4, p+7, p+3), (p+4, p+5, p+6, p+7), (p, p+3, p+2, p+1)] # go through all frames in len(frames), adjusting values at frames[x][y]
def draw(self , context): layout = self.layout row = layout.row() split = row.split(percentage=0.5) col_left = split.column() col_right = split.column(align=True) cam = context.scene.camera col_left.separator() col_left.scale_y = 3 col_left.operator("cropper.set", text="Crop using borders") col_right.label(text="Split Camera over time :") col_right.prop_menu_enum(cam, "my_tiles") col_right.prop_menu_enum(cam, "tiling_order") col_right.operator("splitter.set") # ? Split operator ?
def SetRestPosePosition(context, armatureObj): if not armatureObj: return None # Force the armature in the rest position (warning: https://developer.blender.org/T24674) # This should reset bones matrices ok, but for sure it is not resetting the mesh tessfaces # positions savedPosePositionAndVisibility = [armatureObj.data.pose_position, armatureObj.hide] armatureObj.data.pose_position = 'REST' armatureObj.hide = False # This should help to recalculate all the mesh vertices, it is needed by decomposeMesh # and maybe it helps decomposeArmature (but no problem was seen there) # TODO: find the correct way, for sure it is not this objects = context.scene.objects savedObjectActive = objects.active objects.active = armatureObj if bpy.ops.object.mode_set.poll(): bpy.ops.object.mode_set(mode='EDIT', toggle=False) if bpy.ops.object.mode_set.poll(): bpy.ops.object.mode_set(mode='OBJECT', toggle=False) objects.active = savedObjectActive return savedPosePositionAndVisibility
def draw(self, context): layout = self.layout layout.prop(self, "outputPath") layout.prop(self, "modelsPath") layout.prop(self, "animationsPath") layout.prop(self, "materialsPath") layout.prop(self, "techniquesPath") layout.prop(self, "texturesPath") layout.prop(self, "objectsPath") layout.prop(self, "scenesPath") row = layout.row() row.label("Max number of bones:") row.prop(self, "bonesPerGeometry") row.prop(self, "bonesPerVertex") row = layout.row() row.label("Report window:") row.prop(self, "reportWidth") row.prop(self, "maxMessagesCount") # Here we define all the UI objects to be added in the export panel
def reset_paths(self, context, forced): addonPrefs = context.user_preferences.addons[__name__].preferences if forced or (not self.outputPath and addonPrefs.outputPath): self.outputPath = addonPrefs.outputPath if forced or (not self.modelsPath and addonPrefs.modelsPath): self.modelsPath = addonPrefs.modelsPath self.animationsPath = addonPrefs.animationsPath self.materialsPath = addonPrefs.materialsPath self.techniquesPath = addonPrefs.techniquesPath self.texturesPath = addonPrefs.texturesPath self.objectsPath = addonPrefs.objectsPath self.scenesPath = addonPrefs.scenesPath # --- Accessory ---
def draw(self, context): layout = self.layout scene = context.scene for line in logList: lines = line.split(":", 1) if lines[0] == 'CRITICAL': lineicon = 'RADIO' elif lines[0] == 'ERROR': lineicon = 'CANCEL' elif lines[0] == 'WARNING': lineicon = 'ERROR' elif lines[0] == 'INFO': lineicon = 'INFO' else: lineicon = 'TEXT' layout.label(text = lines[1], icon = lineicon) logList[:] = [] # Clear log list for next call (otherwise list is not updated when 'OK' button is not clicked) # Export button
def selectErrors(context, errorsMem, errorName): names = errorsMem.Names() if errorName != 'ALL': names = [errorName] for i, name in enumerate(names): errors = errorsMem.Get(name) if not errors: continue indices = defaultdict(set) for mi, vi in errors: objectName = errorsMem.Second(mi) if objectName: indices[objectName].add(vi) for objectName, indicesSet in indices.items(): count = len(indicesSet) if count: log.info( "Selecting {:d} vertices on {:s} with '{:s}' errors".format(count, objectName, name) ) selectVertices(context, objectName, indicesSet, i == 0) #------------------------------------------------------------------------- # Export main #-------------------------------------------------------------------------
def get_key_coords(ob=None, key='Basis', proxy=False): '''Creates an N x 3 numpy array of vertex coords. from shape keys''' if key is None: return get_coords(ob) if proxy: mesh = proxy.to_mesh(bpy.context.scene, True, 'PREVIEW') verts = mesh.data.shape_keys.key_blocks[key].data else: verts = ob.data.shape_keys.key_blocks[key].data v_count = len(verts) coords = np.zeros(v_count * 3, dtype=np.float32) verts.foreach_get("co", coords) if proxy: bpy.data.meshes.remove(mesh) return coords.reshape(v_count, 3)
def get_coords(ob=None, proxy=False): '''Creates an N x 3 numpy array of vertex coords. If proxy is used the coords are taken from the object specified with modifiers evaluated. For the proxy argument put in the object: get_coords(ob, proxy_ob)''' if ob is None: ob = bpy.context.object if proxy: mesh = proxy.to_mesh(bpy.context.scene, True, 'PREVIEW') verts = mesh.vertices else: verts = ob.data.vertices v_count = len(verts) coords = np.zeros(v_count * 3, dtype=np.float32) verts.foreach_get("co", coords) if proxy: bpy.data.meshes.remove(mesh) return coords.reshape(v_count, 3)
def get_bmesh(ob=None): '''Returns a bmesh. Works either in edit or object mode. ob can be either an object or a mesh.''' obm = bmesh.new() if ob is None: mesh = bpy.context.object.data if 'data' in dir(ob): mesh = ob.data if ob.mode == 'OBJECT': obm.from_mesh(mesh) elif ob.mode == 'EDIT': obm = bmesh.from_edit_mesh(mesh) else: mesh = ob obm.from_mesh(mesh) return obm
def reassign_mats(ob=None, type=None): '''Resets materials based on stored face indices''' if ob is None: ob = bpy.context.object if type == 'off': ob.data.polygons.foreach_set('material_index', data[ob.name]['mat_index']) ob.data.update() idx = ob.data.materials.find(data[ob.name]['material'].name) if idx != -1: ob.data.materials.pop(idx, update_data=True) bpy.data.materials.remove(data[ob.name]['material']) del(data[ob.name]) if type == 'on': idx = ob.data.materials.find(data[ob.name]['material'].name) mat_idx = np.zeros(len(ob.data.polygons), dtype=np.int32) + idx ob.data.polygons.foreach_set('material_index', mat_idx) ob.data.update()
def dynamic_tension_handler(scene): stretch = bpy.context.scene.dynamic_tension_map_max_stretch / 100 items = data.items() if len(items) == 0: for i in bpy.data.objects: i.dynamic_tension_map_on = False for i in bpy.app.handlers.scene_update_post: if i.__name__ == 'dynamic_tension_handler': bpy.app.handlers.scene_update_post.remove(i) for i, value in items: if i in bpy.data.objects: update(ob=bpy.data.objects[i], max_stretch=stretch, bleed=0.2) else: del(data[i]) break
def get_masked_vertices(context): ob = context.active_object scn = context.scene vertex_color = scn.ne_vertex_color selected = [False]*len(ob.data.vertices) if not scn.ne_mask_name in ob.vertex_groups: return selected vg_index = ob.vertex_groups[scn.ne_mask_name].index for v in ob.data.vertices: for vg in v.groups: if vg.group == vg_index: selected[v.index] = True return selected
def update_active_normal(context, ob): scn = context.scene normal = get_active_normal(context, ob) if normal==None: return if scn.ne_split_mode: loop_index = normal[2] if loop_index!=-1: normal = ob.data.loops[loop_index].normal else: normal = normal[0] else: normal = normal[0] scn.ne_type_normal = normal
def view_normal_callback(self, context): scn = context.scene #update from view if scn.ne_update_by_global_callback: scn.ne_update_by_global_callback = False return real_normal = scn.ne_view_normal if scn.ne_view_sync_mode: mView = get_view_rotational_matrix() mObject = get_object_rotational_matrix() mObject.transpose() real_normal = mObject * mView * real_normal else: real_normal = rot_vector(real_normal) scn.ne_type_normal = real_normal
def type_direction_callback(self, context): scn = context.scene v = mathutils.Vector(scn.ne_type_normal) nv = copy.deepcopy(v) nv.normalize() rotated = nv if scn.ne_view_sync_mode: mView = get_view_rotational_matrix(True) mObject = get_object_rotational_matrix() rotated = mView * mObject * nv else: rotated = rot_vector(nv, reverse=True) if not is_same_vector(scn.ne_type_normal, scn.ne_type_normal_old): if not scn.ne_update_by_global_callback: set_normal_to_selected(context, nv) scn.ne_type_normal_old = scn.ne_type_normal # update direction sphere # avoid recursive call scn.ne_update_by_global_callback = True scn.ne_view_normal = rotated
def index_callback(self, context): scn = context.scene if scn.ne_split_mode: o = context.active_object bm = bmesh.from_edit_mesh(o.data) ensure_lookup_table(bm) index = bm.select_history.active.index masked_vertices = get_masked_vertices(context) loop_index = scn.ne_view_normal_index to_loops = create_loop_table(o.data) if loop_index < len(to_loops[index]): o.data.calc_normals_split() loop_index = to_loops[index][face_index] rotated = o.data.loops[loop_index].normal if scn.ne_view_sync_mode: mView = get_view_rotational_matrix(True) mObject = get_object_rotational_matrix() rotated = mView * mObject * rotated else: rotated = rot_vector(rotated, reverse=True) scn.ne_view_normal = rotated
def execute(self, context): o = context.active_object scn = context.scene bpy.ops.object.mode_set(mode='OBJECT') if not scn.ne_mask_name in o.vertex_groups: bpy.ops.object.mode_set(mode='EDIT') return {'FINISHED'} vg = o.vertex_groups[scn.ne_mask_name] #update vertex group selected = [v.index for v in o.data.vertices if v.select] vg.remove(selected) bpy.ops.object.mode_set(mode='EDIT') return {'FINISHED'}
def global_callback_handler(context): ob = bpy.context.active_object scn = bpy.context.scene if is_normal_active(ob): new_orientation = get_view_quaternion() if new_orientation==None: return if not is_same_vector(new_orientation, scn.ne_view_orientation): #update view orientation scn.ne_update_by_global_callback = True scn.ne_view_orientation = new_orientation #active vertex changed bm = bmesh.from_edit_mesh(ob.data) ensure_lookup_table(bm) active = bm.select_history.active if active!=None: index = active.index if index != scn.ne_last_selected_vert_index: scn.ne_last_selected_vert_index = index scn.ne_update_by_global_callback = True scn.ne_type_normal = get_active_normal(bpy.context, ob)[0]
def _call_recursive(context, base, py_node): # prop = base.bl_rna.properties.get(py_node[TAG]) if py_node[TAG] in base.bl_rna.properties: value = py_node[ARGS].get("expr") if value: value = eval(value, {"context": _bpy.context}) setattr(base, py_node[TAG], value) else: value = py_node[ARGS]["value"] # have to have this setattr(base, py_node[TAG], value) else: args = _parse_rna_args(base, py_node) func_new = getattr(base, py_node[TAG]) base_new = func_new(**args) # call blender func if base_new is not None: for py_node_child in py_node[CHILDREN]: _call_recursive(context, base_new, py_node_child)
def draw_preset(self, context): """ Define these on the subclass: - preset_operator (string) - preset_subdir (string) Optionally: - preset_extensions (set of strings) - preset_operator_defaults (dict of keyword args) """ import bpy ext_valid = getattr(self, "preset_extensions", {".py", ".xml"}) props_default = getattr(self, "preset_operator_defaults", None) self.path_menu(bpy.utils.preset_paths(self.preset_subdir), self.preset_operator, props_default=props_default, filter_ext=lambda ext: ext.lower() in ext_valid)
def _parse_args(args): C_dict = None C_exec = 'EXEC_DEFAULT' C_undo = False is_dict = is_exec = is_undo = False for i, arg in enumerate(args): if is_dict is False and isinstance(arg, dict): if is_exec is True or is_undo is True: raise ValueError("dict arg must come first") C_dict = arg is_dict = True elif is_exec is False and isinstance(arg, str): if is_undo is True: raise ValueError("string arg must come before the boolean") C_exec = arg is_exec = True elif is_undo is False and isinstance(arg, int): C_undo = arg is_undo = True else: raise ValueError("1-3 args execution context is supported") return C_dict, C_exec, C_undo
def poll(cls, context): return True
def execute(self, context): bpy.context.space_data.viewport_shade = 'MATERIAL' return {"FINISHED"}
def change_slot_mesh(self,context): obj = self.id_data self["active"] = True if self.active: obj.coa_slot_index = self.index hide_base_sprite(obj) for slot in obj.coa_slot: if slot != self: slot["active"] = False
def change_event_order(self,context): events = self.id_data.coa_anim_collections[self.id_data.coa_anim_collections_index].event for i,event in enumerate(events): if i+1 < len(events): if events[i].frame == events[i+1].frame: events.remove(i+1) if events[i].frame > events[i+1].frame: events.move(i,i+1)