Python bmesh.update_edit_mesh() Examples

The following are 30 code examples of bmesh.update_edit_mesh(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module bmesh , or try the search function .
Example #1
Source File: functions.py    From coa_tools with GNU General Public License v3.0 6 votes vote down vote up
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") 
Example #2
Source File: operator_mesh_uv.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def main(context):
    obj = context.active_object
    me = obj.data
    bm = bmesh.from_edit_mesh(me)

    uv_layer = bm.loops.layers.uv.verify()
    bm.faces.layers.tex.verify()  # currently blender needs both layers.

    # adjust UVs
    for f in bm.faces:
        for l in f.loops:
            luv = l[uv_layer]
            if luv.select:
                # apply the location of the vertex as a UV
                luv.uv = l.vert.co.xy

    bmesh.update_edit_mesh(me) 
Example #3
Source File: floor.py    From building_tools with MIT License 6 votes vote down vote up
def build(cls, context, prop):
        verify_facemaps_for_object(context.object)

        me = get_edit_mesh()
        bm = bmesh.from_edit_mesh(me)

        if cls.validate(bm):
            cls.add_floor_facemaps(context, prop)
            selected_faces = [f for f in bm.faces if f.select]
            if selected_faces:
                create_floors(bm, selected_faces, prop)
                select(bm.faces, False)
            else:
                all_faces = [f for f in bm.faces]
                create_floors(bm, all_faces, prop)
            bmesh.update_edit_mesh(me, True)
            return {"FINISHED"}
        return {"CANCELLED"} 
Example #4
Source File: operator_mesh_uv.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def main(context):
    obj = context.active_object
    me = obj.data
    bm = bmesh.from_edit_mesh(me)

    uv_layer = bm.loops.layers.uv.verify()
    bm.faces.layers.tex.verify()  # currently blender needs both layers.

    # adjust UVs
    for f in bm.faces:
        for l in f.loops:
            luv = l[uv_layer]
            if luv.select:
                # apply the location of the vertex as a UV
                luv.uv = l.vert.co.xy

    bmesh.update_edit_mesh(me) 
Example #5
Source File: edit_mesh.py    From coa_tools with GNU General Public License v3.0 6 votes vote down vote up
def clean_mesh(self,obj):
        bm = bmesh.from_edit_mesh(obj.data)
        
        faces = []
        for face in bm.faces:
            if not face.hide:
                face_ok = False
                invalid_edges = 0
                for edge in face.edges:
                    if not edge.is_manifold and not edge.is_wire and not edge.is_boundary:
                        invalid_edges += 1
                        
                if invalid_edges == len(face.edges):
                    faces.append(face)
        bmesh.ops.delete(bm,geom=faces,context=3)
        bmesh.update_edit_mesh(obj.data) 
Example #6
Source File: mi_noise.py    From mifthtools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def noise_obj(obj, context, self):
    bm = bmesh.from_edit_mesh(obj.data)
    verts = [v for v in bm.verts if v.select]
    if not verts:
        verts = [v for v in bm.verts if v.hide is False]

    for vert in verts:
        noise_pos = self.frequency * vert.co.copy()
        noise_pos.x += self.offset_x
        noise_pos.z += self.offset_y
        noise_pos.z += self.offset_z

        noise_val = None
        if self.noise_type == 'Turbulence':
            noise_val = mathu.noise.turbulence(noise_pos, self.octaves, self.hard, mathu.noise.types.STDPERLIN, self.amplitude_scale, self.frequency_scale)
        elif self.noise_type == 'Fractal':
            noise_val = mathu.noise.fractal(noise_pos, self.amplitude_scale, self.frequency_scale, self.octaves, mathu.noise.types.STDPERLIN)
        else:
            noise_val = mathu.noise.hetero_terrain(noise_pos, self.amplitude_scale, self.frequency_scale, self.octaves, 0, mathu.noise.types.STDPERLIN)

        vert_offset = vert.normal.copy().normalized() * noise_val
        vert.co += vert_offset * self.intensity

    bm.normal_update()
    bmesh.update_edit_mesh(obj.data) 
Example #7
Source File: mi_noise.py    From mifthtools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def noise_obj(obj, context, self):
    bm = bmesh.from_edit_mesh(obj.data)
    verts = [v for v in bm.verts if v.select]
    if not verts:
        verts = [v for v in bm.verts if v.hide is False]

    for vert in verts:
        noise_pos = self.frequency * vert.co.copy()
        noise_pos.x += self.offset_x
        noise_pos.z += self.offset_y
        noise_pos.z += self.offset_z

        noise_val = None
        if self.noise_type == 'Turbulence':
            noise_val = mathu.noise.turbulence(noise_pos, self.octaves, self.hard, noise_basis="PERLIN_ORIGINAL", amplitude_scale=self.amplitude_scale, frequency_scale=self.frequency_scale)
        elif self.noise_type == 'Fractal':
            noise_val = mathu.noise.fractal(noise_pos, self.amplitude_scale, self.frequency_scale, self.octaves, noise_basis="PERLIN_ORIGINAL")
        else:
            noise_val = mathu.noise.hetero_terrain(noise_pos, self.amplitude_scale, self.frequency_scale, self.octaves, 0, noise_basis="PERLIN_ORIGINAL")

        vert_offset = vert.normal.copy().normalized() * noise_val
        vert.co += vert_offset * self.intensity

    bm.normal_update()
    bmesh.update_edit_mesh(obj.data) 
Example #8
Source File: edit_mesh.py    From coa_tools with GNU General Public License v3.0 6 votes vote down vote up
def collapse_short_edges(bm,obj,threshold=1.0):
    ### collapse short edges
    edges_len_average = 0
    edges_count = 0
    shortest_edge = 10000
    for edge in bm.edges:
        if True:
            edges_count += 1
            length = edge.calc_length()
            edges_len_average += length
            if length < shortest_edge:
                shortest_edge = length
    edges_len_average = edges_len_average/edges_count

    verts = []
    for vert in bm.verts:
        if not vert.is_boundary:
            verts.append(vert)
    bmesh.update_edit_mesh(obj.data)
    
    bmesh.ops.remove_doubles(bm,verts=verts,dist=edges_len_average*threshold)

    bmesh.update_edit_mesh(obj.data) 
Example #9
Source File: functions.py    From coa_tools with GNU General Public License v3.0 6 votes vote down vote up
def unwrap_with_bounds(obj,uv_idx):
    bpy.ops.object.mode_set(mode="EDIT")
    me = obj.data
    bm = bmesh.from_edit_mesh(me)
    bm.verts.ensure_lookup_table()
    uv_layer = bm.loops.layers.uv[uv_idx]
    scale_x = 1.0 / get_local_dimension(obj)[0] * obj.coa_tiles_x
    scale_z = 1.0 / get_local_dimension(obj)[1] * obj.coa_tiles_y
    offset = [get_local_dimension(obj)[2][0] * scale_x , get_local_dimension(obj)[2][1] * scale_z]
    for i,v in enumerate(bm.verts):
        for l in v.link_loops:
            uv_data = l[uv_layer]
            uv_data.uv[0] = (bm.verts[i].co[0] * scale_x) - offset[0]
            uv_data.uv[1] = (bm.verts[i].co[2] * scale_z)+1 - offset[1]
   
    bmesh.update_edit_mesh(me)
    bm.free()
    bpy.ops.object.mode_set(mode="OBJECT") 
Example #10
Source File: object_fastorigin.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def modal(self, context, event):

		if event.type in {'LEFTMOUSE', 'MIDDLEMOUSE', 'RIGHTMOUSE', 'WHEELDOWNMOUSE', 'WHEELUPMOUSE', 'G', 'X', 'Y', 'Z', 'MOUSEMOVE'}:
			return {'PASS_THROUGH'}
			
		elif event.type in {'RET', 'NUMPAD_ENTER'}:
			del bpy.types.Scene.PreSelOff
			# Consolidate changes.
			for v in self.vsellist:
				v.select = True
			for e in self.esellist:
				e.select = True
			for f in self.fsellist:
				f.select = True
			self.bm.verts.remove(self.originvert)
			bmesh.update_edit_mesh(self.mesh, destructive=True)
			self.mesh.update()
			self.bm.free()
			self.snapelem = context.tool_settings.snap_element
			self.snapstate = context.tool_settings.use_snap
			context.tool_settings.snap_element = self.snapelsave
			context.tool_settings.use_snap = self.snapstsave
			bpy.ops.object.editmode_toggle()
			bpy.ops.object.origin_set(type='ORIGIN_CURSOR')
			self.space3d.cursor_location = self.cursorsave			
			if self.mode == 'EDIT':
				bpy.ops.object.editmode_toggle()
			bpy.types.SpaceView3D.draw_handler_remove(self._handle, 'WINDOW')
			return {'FINISHED'}
		
		return {'RUNNING_MODAL'} 
Example #11
Source File: mi_linear_deformer.py    From mifthtools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def undo_history(bm, h_undo, h_redo, active_obj):
    if h_undo:
        pre_history = h_undo[-1]
        if len(h_undo) > 1:  # 0 index is always original verts
            h_undo.remove(pre_history)
            h_redo.append(pre_history)

        history = h_undo[-1]
        for h_vert in history:
            bm.verts[h_vert[0]].co = h_vert[1].copy()

        bm.normal_update()
        bmesh.update_edit_mesh(active_obj.data) 
Example #12
Source File: curve_ops.py    From jewelcraft with GNU General Public License v3.0 5 votes vote down vote up
def execute(self, context):

        if context.mode == "EDIT_MESH":

            for ob in context.objects_in_mode:
                me = ob.data
                bbox, curve = asset.mod_curve_off(ob)

                if curve:
                    length = mesh.curve_length(curve)
                    length_halved = length / 2 / ob.matrix_world.to_scale()[0]

                    bm = bmesh.from_edit_mesh(me)

                    for v in bm.verts:
                        if v.select:
                            if v.co[0] > 0.0:
                                v.co[0] = length_halved
                            else:
                                v.co[0] = -length_halved

                    bm.normal_update()
                    bmesh.update_edit_mesh(me)

        else:

            for ob in context.selected_objects:
                bbox, curve = asset.mod_curve_off(ob)

                if curve:
                    length = mesh.curve_length(curve)

                    bbox = [ob.matrix_world @ Vector(x) for x in bbox]
                    dim = max(x[0] for x in bbox) - min(x[0] for x in bbox)

                    scaling = ob.matrix_local @ ob.scale
                    scaling[0] = length / dim * scaling[0]

                    ob.scale = ob.matrix_local.inverted() @ scaling

        return {"FINISHED"} 
Example #13
Source File: stairs.py    From building_tools with MIT License 5 votes vote down vote up
def build(cls, context, prop):
        verify_facemaps_for_object(context.object)
        me = get_edit_mesh()
        bm = bmesh.from_edit_mesh(me)
        faces = [f for f in bm.faces if f.select]

        if cls.validate(faces):
            cls.add_stairs_facemaps()
            if create_stairs(bm, faces, prop):
                bmesh.update_edit_mesh(me, True)
                return {"FINISHED"}
        return {"CANCELLED"} 
Example #14
Source File: archipack_polylines.py    From archipack with GNU General Public License v3.0 5 votes vote down vote up
def wall_uv(self, me, bm):

        for face in bm.faces:
            face.select = face.material_index > 0

        bmesh.update_edit_mesh(me, True)
        if bpy.ops.uv.cube_project.poll():
            bpy.ops.uv.cube_project(scale_to_bounds=False, correct_aspect=True)

        for face in bm.faces:
            face.select = face.material_index < 1

        bmesh.update_edit_mesh(me, True)
        if bpy.ops.uv.smart_project.poll():
            bpy.ops.uv.smart_project(use_aspect=True, stretch_to_bounds=False) 
Example #15
Source File: archipack_polylines.py    From archipack with GNU General Public License v3.0 5 votes vote down vote up
def assign_matindex_to_wall(obj):
        """
            Use vertex groups to assign materials
        """
        inside_mat = 0
        outside_mat = 1
        cut_mat = 2
        me = obj.data

        vgroup_names = {vgroup.name: vgroup.index for vgroup in obj.vertex_groups}
        if obj.vertex_groups.get('Interior') is not None:
            mat_index = outside_mat
        else:
            mat_index = inside_mat

        bpy.ops.object.mode_set(mode='EDIT')
        bpy.ops.mesh.select_mode(type="FACE")
        bpy.ops.mesh.select_all(action='DESELECT')
        obj.vertex_groups.active_index = vgroup_names['Exterior']
        bpy.ops.object.vertex_group_select()
        Io.assign_matindex_to_selected(me, mat_index, True)
        Io.assign_matindex_to_selected(me, inside_mat, False)

        bm = bmesh.from_edit_mesh(me)
        bm.verts.ensure_lookup_table()
        bm.faces.ensure_lookup_table()
        for poly in bm.faces:
            if abs(poly.normal.z) > 0.5:
                poly.material_index = cut_mat
        bmesh.update_edit_mesh(me, True)
        bpy.ops.object.mode_set(mode='OBJECT') 
Example #16
Source File: archipack_polylines.py    From archipack with GNU General Public License v3.0 5 votes vote down vote up
def assign_matindex_to_selected(me, index, selected):
        bm = bmesh.from_edit_mesh(me)
        bm.verts.ensure_lookup_table()
        bm.faces.ensure_lookup_table()
        for poly in bm.faces:
            if poly.select == selected:
                poly.material_index = index
        bmesh.update_edit_mesh(me, True) 
Example #17
Source File: uv_squares.py    From UvSquares with GNU General Public License v2.0 5 votes vote down vote up
def SuccessFinished(me, startTime):
    #use for backtrack of steps 
    #bpy.ops.ed.undo_push()
    bmesh.update_edit_mesh(me)
    elapsed = round(timer()-startTime, 2)
    #if (elapsed >= 0.05): operator.report({'INFO'}, "UvSquares finished, elapsed:", elapsed, "s.")
    if (elapsed >= 0.05): print("UvSquares finished, elapsed:", elapsed, "s.")
    return 
Example #18
Source File: blender_convert.py    From GEOMetrics with MIT License 5 votes vote down vote up
def triangulate_edit_object(obj):
	me = obj.data
	bm = bmesh.from_edit_mesh(me)
	bmesh.ops.triangulate(bm, faces=bm.faces[:], quad_method=0, ngon_method=0)
	bmesh.update_edit_mesh(me, True)



# import arguements 
Example #19
Source File: blender_convert.py    From GEOMetrics with MIT License 5 votes vote down vote up
def triangulate_edit_object(obj):
	me = obj.data
	bm = bmesh.from_edit_mesh(me)
	bmesh.ops.triangulate(bm, faces=bm.faces[:], quad_method=0, ngon_method=0)
	bmesh.update_edit_mesh(me, True)



# import arguements 
Example #20
Source File: bmesh_utils.py    From archipack with GNU General Public License v3.0 5 votes vote down vote up
def _end(bm, o):
        """
            private, end bmesh editing of active object
        """
        bm.normal_update()
        bmesh.update_edit_mesh(o.data, True)
        bpy.ops.object.mode_set(mode='OBJECT')
        bm.free() 
Example #21
Source File: roof.py    From building_tools with MIT License 5 votes vote down vote up
def build(cls, context, props):
        verify_facemaps_for_object(context.object)
        me = get_edit_mesh()
        bm = bmesh.from_edit_mesh(me)
        faces = [f for f in bm.faces if f.select]

        if cls.validate(bm):
            cls.add_roof_facemaps()
            create_roof(bm, faces, props)
            bmesh.update_edit_mesh(me, True)
            return {"FINISHED"}
        return {"CANCELLED"} 
Example #22
Source File: pdt_tangent.py    From Precision-Drawing-Tools with GNU General Public License v3.0 5 votes vote down vote up
def draw_tangents(tangent_vectors, obj_data):
    """Add Edges Representing the Tangents.

    Note:
        The length of the tanget_vectors determins whcih tangents will be
        drawn, 3 gives Point Tangents, 4 gives Inner/Outer tangents

    Args:
        tangent_vectors: A list of vectores representing the tangents
        obj_data: A list giving Object, Object Location and Object Bmesh

    Returns:
        Nothing.
    """
    obj = obj_data[0]
    obj_loc = obj_data[1]
    bm = obj_data[2]
    if len(tangent_vectors) == 3:
        point_vertex_outer = bm.verts.new(tangent_vectors[0] - obj_loc)
        tangent_vertex_o1 = bm.verts.new(tangent_vectors[1] - obj_loc)
        tangent_vertex_o2 = bm.verts.new(tangent_vectors[2] - obj_loc)
        bm.edges.new([tangent_vertex_o1, point_vertex_outer])
        bm.edges.new([tangent_vertex_o2, point_vertex_outer])
    else:
        tangent_vertex_o1 = bm.verts.new(tangent_vectors[0] - obj_loc)
        tangent_vertex_o2 = bm.verts.new(tangent_vectors[2] - obj_loc)
        tangent_vertex_o3 = bm.verts.new(tangent_vectors[1] - obj_loc)
        tangent_vertex_o4 = bm.verts.new(tangent_vectors[3] - obj_loc)
        bm.edges.new([tangent_vertex_o1, tangent_vertex_o2])
        bm.edges.new([tangent_vertex_o3, tangent_vertex_o4])
    bmesh.update_edit_mesh(obj.data) 
Example #23
Source File: window.py    From building_tools with MIT License 5 votes vote down vote up
def build(cls, context, prop):
        verify_facemaps_for_object(context.object)
        me = get_edit_mesh()
        bm = bmesh.from_edit_mesh(me)
        faces = [face for face in bm.faces if face.select]

        if cls.validate(faces):
            cls.add_window_facemaps()
            if create_window(bm, faces, prop):
                bmesh.update_edit_mesh(me, True)
                return {"FINISHED"}
        return {"CANCELLED"} 
Example #24
Source File: functions.py    From coa_tools with GNU General Public License v3.0 5 votes vote down vote up
def hide_base_sprite(obj):
    context = bpy.context
    selected_object = bpy.data.objects[context.active_object.name]
    if "coa_sprite" in obj and obj.type == "MESH":
        orig_mode = obj.mode
        context.scene.objects.active = obj
        bpy.ops.object.mode_set(mode="OBJECT")
        bpy.ops.object.mode_set(mode="EDIT")
        me = obj.data
        bm = bmesh.from_edit_mesh(me)
        bm.verts.ensure_lookup_table()
        
        vertex_idxs = []
        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:
                        vertex_idxs.append(i)
                    
        for idx in vertex_idxs:
            vert = bm.verts[idx]
            vert.hide = True
            vert.select = False
            for edge in vert.link_edges:
                edge.hide = True
                edge.select = False
            for face in vert.link_faces:
                face.hide = obj.data.coa_hide_base_sprite
                face.select = False
                
        if "coa_base_sprite" in obj.modifiers:
            mod = obj.modifiers["coa_base_sprite"]
            mod.show_viewport = obj.data.coa_hide_base_sprite
            mod.show_render = obj.data.coa_hide_base_sprite
            
        bmesh.update_edit_mesh(me)               
        bpy.ops.object.mode_set(mode=orig_mode)                      
    context.scene.objects.active = selected_object 
Example #25
Source File: muv_unwrapconst_ops.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def execute(self, context):
        obj = bpy.context.active_object
        bm = bmesh.from_edit_mesh(obj.data)
        if muv_common.check_version(2, 73, 0) >= 0:
            bm.faces.ensure_lookup_table()

        if not bm.loops.layers.uv:
            self.report(
                {'WARNING'}, "Object must have more than one UV map")
            return {'CANCELLED'}
        uv_layer = bm.loops.layers.uv.verify()

        # get original UV coordinate
        faces = [f for f in bm.faces if f.select]
        uv_list = []
        for f in faces:
            uvs = [l[uv_layer].uv.copy() for l in f.loops]
            uv_list.append(uvs)

        # unwrap
        bpy.ops.uv.unwrap(
            method=self.method,
            fill_holes=self.fill_holes,
            correct_aspect=self.correct_aspect,
            use_subsurf_data=self.use_subsurf_data,
            margin=self.margin)

        # when U/V-Constraint is checked, revert original coordinate
        for f, uvs in zip(faces, uv_list):
            for l, uv in zip(f.loops, uvs):
                if self.u_const:
                    l[uv_layer].uv.x = uv.x
                if self.v_const:
                    l[uv_layer].uv.y = uv.y

        # update mesh
        bmesh.update_edit_mesh(obj.data)

        return {'FINISHED'} 
Example #26
Source File: util_material.py    From building_tools with MIT License 5 votes vote down vote up
def verify_facemaps_for_object(obj):
    """ Ensure object has a facemap layer """
    me = get_edit_mesh()
    bm = bmesh.from_edit_mesh(me)
    bm.faces.layers.face_map.verify()
    bmesh.update_edit_mesh(me, True) 
Example #27
Source File: pdt_pivot_point.py    From Precision-Drawing-Tools with GNU General Public License v3.0 5 votes vote down vote up
def execute(self, context):
        """Rotate Selected Vertices about Pivot Point.

        Note:
            Rotates any selected vertices about the Pivot Point
            in View Oriented coordinates, works in any view orientation.

        Args:
            context: Blender bpy.context instance.

        Note:
            Uses pg.pivot_loc, pg.pivot_ang scene variables

        Returns:
            Status Set.
        """

        scene = context.scene
        pg = scene.pdt_pg
        obj = bpy.context.view_layer.objects.active
        if obj is None:
            self.report({"ERROR"}, PDT_ERR_NO_ACT_OBJ)
            return {"FINISHED"}
        if obj.mode != "EDIT":
            error_message = f"{PDT_ERR_EDIT_MODE} {obj.mode})"
            self.report({"ERROR"}, error_message)
            return {"FINISHED"}
        bm = bmesh.from_edit_mesh(obj.data)
        v1 = Vector((0, 0, 0))
        v2 = view_coords(0, 0, 1)
        axis = (v2 - v1).normalized()
        rot = Matrix.Rotation((pg.pivot_ang * pi / 180), 4, axis)
        verts = verts = [v for v in bm.verts if v.select]
        bmesh.ops.rotate(
            bm, cent=pg.pivot_loc - obj.matrix_world.decompose()[0], matrix=rot, verts=verts
        )
        bmesh.update_edit_mesh(obj.data)
        return {"FINISHED"} 
Example #28
Source File: util_object.py    From building_tools with MIT License 5 votes vote down vote up
def bmesh_from_active_object(context=None):
    context = context or bpy.context

    if context.mode == "EDIT_MESH":
        me = get_edit_mesh()
        bm = bmesh.from_edit_mesh(me)
    elif context.mode == "OBJECT":
        bm = bm_from_obj(context.object)

    yield bm

    if context.mode == "EDIT_MESH":
        bmesh.update_edit_mesh(me, True)
    elif context.mode == "OBJECT":
        bm_to_obj(bm, context.object) 
Example #29
Source File: pdt_command_functions.py    From Precision-Drawing-Tools with GNU General Public License v3.0 5 votes vote down vote up
def origin_to_cursor(context):
    """Sets Object Origin in Edit Mode to Cursor Location.

    Note:
        Keeps geometry static in World Space whilst moving Object Origin
        Requires cursor location
        Works in Edit and Object Modes.

    Args:
        context: Blender bpy.context instance.

    Returns:
        Status Set.
    """

    scene = context.scene
    pg = context.scene.pdt_pg
    obj = context.view_layer.objects.active
    if obj is None:
        pg.error = PDT_ERR_NO_ACT_OBJ
        context.window_manager.popup_menu(oops, title="Error", icon="ERROR")
        return
    obj_loc = obj.matrix_world.decompose()[0]
    cur_loc = scene.cursor.location
    diff_v = obj_loc - cur_loc
    if obj.mode == "EDIT":
        bm = bmesh.from_edit_mesh(obj.data)
        for v in bm.verts:
            v.co = v.co + diff_v
        obj.location = cur_loc
        bmesh.update_edit_mesh(obj.data)
        bm.select_history.clear()
    elif obj.mode == "OBJECT":
        for v in obj.data.vertices:
            v.co = v.co + diff_v
        obj.location = cur_loc
    else:
        pg.error = f"{PDT_ERR_EDOB_MODE} {obj.mode})"
        context.window_manager.popup_menu(oops, title="Error", icon="ERROR")
        raise PDT_ObjectModeError 
Example #30
Source File: pdt_command_functions.py    From Precision-Drawing-Tools with GNU General Public License v3.0 5 votes vote down vote up
def join_two_vertices(context):
    """Joins 2 Free Vertices that do not form part of a Face.

    Note:
        Joins two vertices that do not form part of a single face
        It is designed to close open Edge Loops, where a face is not required
        or to join two disconnected Edges.

    Args:
        context: Blender bpy.context instance.

    Returns:
        Status Set.
    """

    scene = context.scene
    pg = scene.pdt_pg
    obj = context.view_layer.objects.active
    if all([bool(obj), obj.type == "MESH", obj.mode == "EDIT"]):
        bm = bmesh.from_edit_mesh(obj.data)
        verts = [v for v in bm.verts if v.select]
        if len(verts) == 2:
            try:
                bm.edges.new([verts[-1], verts[-2]])
                bmesh.update_edit_mesh(obj.data)
                bm.select_history.clear()
                return
            except ValueError:
                pg.error = PDT_ERR_CONNECTED
                context.window_manager.popup_menu(oops, title="Error", icon="ERROR")
                raise PDT_VerticesConnected
        else:
            pg.error = f"{PDT_ERR_SEL_2_VERTS} {len(verts)})"
            context.window_manager.popup_menu(oops, title="Error", icon="ERROR")
            raise PDT_SelectionError
    else:
        pg.error = f"{PDT_ERR_EDOB_MODE},{obj.mode})"
        context.window_manager.popup_menu(oops, title="Error", icon="ERROR")
        raise PDT_ObjectModeError