Python mathutils.Matrix.Rotation() Examples

The following are 30 code examples of mathutils.Matrix.Rotation(). 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 mathutils.Matrix , or try the search function .
Example #1
Source File: BopLoader.py    From BlenderProc with GNU General Public License v3.0 6 votes vote down vote up
def _compute_camera_to_world_trafo(self, cam_H_m2w_ref, cam_H_m2c_ref):
        """ Returns camera to world transformation in blender coords.

        :param cam_H_m2c_ref: (4x4) Homog trafo from object to camera coords. Type: ndarray.
        :param cam_H_m2w_ref: (4x4) Homog trafo from object to world coords. Type: ndarray.
        :return: cam_H_c2w: (4x4) Homog trafo from camera to world coords. Type: mathutils.Matrix.
        """

        cam_H_c2w = np.dot(cam_H_m2w_ref, np.linalg.inv(cam_H_m2c_ref))

        print('-----------------------------')
        print("Cam: {}".format(cam_H_c2w))
        print('-----------------------------')

        # transform from OpenCV to blender coords
        cam_H_c2w = cam_H_c2w @ Matrix.Rotation(math.radians(180), 4, "X")

        return cam_H_c2w 
Example #2
Source File: archipack_section.py    From archipack with GNU General Public License v3.0 6 votes vote down vote up
def update_section(self, context):
        o = self.find_in_selection(context, self.auto_update)

        if o is None:
            return
        src_name = o.name
        loc = o.matrix_world.translation
        clip_x = 0.5 * self.size
        sel = []
        tM = self.get_objects(context, o, sel)

        # rotate section plane normal 90 deg on x axis
        pM = tM * Matrix.Rotation(pi / 2, 4, Vector((1, 0, 0)))
        s = self.generate_section(context, sel, pM, clip_x, 0)

        # get points in plane matrix coordsys so they are in 2d
        itM = pM.inverted()
        c = self.as_curves(context, s, itM, loc, src_name, self.section_name)
        if c is None:
            self.delete_object(context, s)
        else:
            self.section_name = c.name

        self.restore_context(context)
        return c 
Example #3
Source File: curve_ops.py    From jewelcraft with GNU General Public License v3.0 6 votes vote down vote up
def execute(self, context):
        obs = context.selected_objects

        bpy.ops.curve.primitive_bezier_circle_add(radius=self.diameter / 2, rotation=(pi / 2, 0.0, 0.0))

        curve = context.object
        curve.name = "Size"
        curve.data.name = "Size"
        curve.data.resolution_u = 512
        curve.data.use_radius = False

        if self.up:
            mat = Matrix.Rotation(pi, 4, "Z")
            curve.data.transform(mat)

        if obs:
            for ob in obs:
                try:
                    md = ob.modifiers.new("Curve", "CURVE")
                    md.object = curve
                except AttributeError:
                    continue

        return {"FINISHED"} 
Example #4
Source File: transform.py    From object_alignment with GNU General Public License v3.0 6 votes vote down vote up
def transformToWorld(vec:Vector, mat:Matrix, junk_bme:bmesh=None):
    """ transfrom vector to world space from 'mat' matrix local space """
    # decompose matrix
    loc = mat.to_translation()
    rot = mat.to_euler()
    scale = mat.to_scale()[0]
    # apply rotation
    if rot != Euler((0, 0, 0), "XYZ"):
        junk_bme = bmesh.new() if junk_bme is None else junk_bme
        v1 = junk_bme.verts.new(vec)
        bmesh.ops.rotate(junk_bme, verts=[v1], cent=-loc, matrix=Matrix.Rotation(rot.x, 3, 'X'))
        bmesh.ops.rotate(junk_bme, verts=[v1], cent=-loc, matrix=Matrix.Rotation(rot.y, 3, 'Y'))
        bmesh.ops.rotate(junk_bme, verts=[v1], cent=-loc, matrix=Matrix.Rotation(rot.z, 3, 'Z'))
        vec = v1.co
    # apply scale
    vec = vec * scale
    # apply translation
    vec += loc
    return vec 
Example #5
Source File: transform.py    From object_alignment with GNU General Public License v3.0 6 votes vote down vote up
def transformToLocal(vec:Vector, mat:Matrix, junk_bme:bmesh=None):
    """ transfrom vector to local space of 'mat' matrix """
    # decompose matrix
    loc = mat.to_translation()
    rot = mat.to_euler()
    scale = mat.to_scale()[0]
    # apply scale
    vec = vec / scale
    # apply rotation
    if rot != Euler((0, 0, 0), "XYZ"):
        junk_bme = bmesh.new() if junk_bme is None else junk_bme
        v1 = junk_bme.verts.new(vec)
        bmesh.ops.rotate(junk_bme, verts=[v1], cent=loc, matrix=Matrix.Rotation(-rot.z, 3, 'Z'))
        bmesh.ops.rotate(junk_bme, verts=[v1], cent=loc, matrix=Matrix.Rotation(-rot.y, 3, 'Y'))
        bmesh.ops.rotate(junk_bme, verts=[v1], cent=loc, matrix=Matrix.Rotation(-rot.x, 3, 'X'))
        vec = v1.co
    return vec 
Example #6
Source File: internal.py    From curve_cad with GNU General Public License v3.0 6 votes vote down vote up
def bezierArcAt(tangent, normal, center, radius, angle, tollerance=0.99999):
    transform = Matrix.Identity(4)
    transform.col[0].xyz = tangent.cross(normal)*radius
    transform.col[1].xyz = tangent*radius
    transform.col[2].xyz = normal*radius
    transform.col[3].xyz = center
    segments = []
    segment_count = math.ceil(abs(angle)/(math.pi*0.5)*tollerance)
    angle /= segment_count
    x0 = math.cos(angle*0.5)
    y0 = math.sin(angle*0.5)
    x1 = (4.0-x0)/3.0
    y1 = (1.0-x0)*(3.0-x0)/(3.0*y0)
    points = [
        Vector((x0, -y0, 0)),
        Vector((x1, -y1, 0)),
        Vector((x1, y1, 0)),
        Vector((x0, y0, 0))
    ]
    for i in range(0, segment_count):
        rotation = Matrix.Rotation((i+0.5)*angle, 4, 'Z')
        segments.append(list(map(lambda v: transform@(rotation@v), points)))
    return segments 
Example #7
Source File: convert.py    From BlenderTools with GNU General Public License v2.0 6 votes vote down vote up
def mat3_to_vec_roll(mat):
    """Computes rotation axis and its roll from a Matrix.

    :param mat: Matrix
    :type mat: Matrix
    :return: Rotation axis and roll
    :rtype: Vector and float
    """
    mat_3x3 = mat.to_3x3()
    # print('  mat_3x3:\n%s' % str(mat_3x3))
    axis = Vector(mat_3x3.col[1]).normalized()
    # print('  axis:\n%s' % str(axis))
    # print('  mat_3x3[2]:\n%s' % str(mat_3x3.col[2]))

    zero_angle_matrix = vec_roll_to_mat3(axis, 0)
    delta_matrix = zero_angle_matrix.inverted() @ mat_3x3
    angle = math.atan2(delta_matrix.col[2][0], delta_matrix.col[2][2])
    return axis, angle 
Example #8
Source File: import_svg.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def SVGTransformRotate(params):
    """
    skewX SVG transform command
    """

    ang = float(params[0]) * pi / 180.0
    cx = cy = 0.0

    if len(params) >= 3:
        cx = float(params[1])
        cy = float(params[2])

    tm = Matrix.Translation(Vector((cx, cy, 0.0)))
    rm = Matrix.Rotation(ang, 4, Vector((0.0, 0.0, 1.0)))

    return tm * rm * tm.inverted() 
Example #9
Source File: clip.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def _findOrCreateCamera(context):
        scene = context.scene

        if scene.camera:
            return scene.camera

        cam = bpy.data.cameras.new(name="Camera")
        camob = bpy.data.objects.new(name="Camera", object_data=cam)
        scene.objects.link(camob)

        scene.camera = camob

        camob.matrix_local = (Matrix.Translation((7.481, -6.508, 5.344)) *
                              Matrix.Rotation(0.815, 4, 'Z') *
                              Matrix.Rotation(0.011, 4, 'Y') *
                              Matrix.Rotation(1.109, 4, 'X'))

        return camob 
Example #10
Source File: uvcalc_smart_project.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def main_consts():
    from math import radians

    global ROTMAT_2D_POS_90D
    global ROTMAT_2D_POS_45D
    global RotMatStepRotation

    ROTMAT_2D_POS_90D = Matrix.Rotation(radians(90.0), 2)
    ROTMAT_2D_POS_45D = Matrix.Rotation(radians(45.0), 2)

    RotMatStepRotation = []
    rot_angle = 22.5 #45.0/2
    while rot_angle > 0.1:
        RotMatStepRotation.append([
            Matrix.Rotation(radians(+rot_angle), 2),
            Matrix.Rotation(radians(-rot_angle), 2),
            ])

        rot_angle = rot_angle/2.0 
Example #11
Source File: armature.py    From leadwerks-blender-exporter with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, blender_data=None):
        self.index = 0
        self.name = ''
        self.parent = None
        self.children = []
        self.animations = []
        self.matrix_basis = Matrix((
            (1.0, 0.0, 0.0, 0.0),
            (0.0, 0.0, 1.0, 0.0),
            (0.0, -1.0, 0.0, 0.0),
            (0.0, 0.0, 0.0, 1.0),
        )) * Matrix.Rotation(1.5707963267948966*2, 4, 'Z')

        self.matrix_basis = utils.magick_convert(self.matrix_basis)

        if blender_data:
            self.blender_data = blender_data
            self.name = blender_data.name 
Example #12
Source File: mapping3d.py    From BlendLuxCore with GNU General Public License v3.0 5 votes vote down vote up
def export(self, exporter, depsgraph, props, luxcore_name=None, output_socket=None):
        mapping_type, uvindex, input_mapping = self.inputs["3D Mapping (optional)"].export(exporter, depsgraph, props)
        # Use the mapping type of this node only when mapping type is not
        # already set by previous mapping node
        if not self.inputs["3D Mapping (optional)"].is_linked:
            mapping_type = self.mapping_type
            uvindex = self.uvindex

        # create a location matrix
        tex_loc = Matrix.Translation(self.translate)

        # create an identity matrix
        tex_sca = Matrix()
        tex_sca[0][0] = self.uniform_scale if self.use_uniform_scale else self.scale[0]  # X
        tex_sca[1][1] = self.uniform_scale if self.use_uniform_scale else self.scale[1]  # Y
        tex_sca[2][2] = self.uniform_scale if self.use_uniform_scale else self.scale[2]  # Z

        # Prevent "singular matrix in matrixinvert" error (happens if a scale axis equals 0)
        for i in range(3):
            if tex_sca[i][i] == 0:
                tex_sca[i][i] = 0.0000000001

        # create a rotation matrix
        tex_rot0 = Matrix.Rotation(self.rotate[0], 4, "X")
        tex_rot1 = Matrix.Rotation(self.rotate[1], 4, "Y")
        tex_rot2 = Matrix.Rotation(self.rotate[2], 4, "Z")
        tex_rot = tex_rot0 @ tex_rot1 @ tex_rot2

        # combine transformations
        transformation = tex_loc @ tex_rot @ tex_sca

        # Transform input matrix
        output_mapping = input_mapping @ transformation

        return mapping_type, uvindex, output_mapping 
Example #13
Source File: skull_panel.py    From mmvt with GNU General Public License v3.0 5 votes vote down vote up
def rotate_skull_plane(d_ang):
    from mathutils import Matrix
    plane = bpy.data.objects.get('skull_plane', None)
    if plane is not None and SkullPanel.plane_dir_vec is not None:
        plane.rotation_mode = 'XYZ'
        vec = SkullPanel.plane_dir_vec
        ang = math.radians(d_ang)
        plane.rotation_euler = (Matrix.Rotation(ang, 3, vec) * plane.rotation_euler.to_matrix()).to_euler() 
Example #14
Source File: BopWriter.py    From BlenderProc with GNU General Public License v3.0 5 votes vote down vote up
def _get_frame_gt(self):
        """ Returns GT annotations for the active camera.

        :return: A list of GT annotations.
        """
        camera_rotation = self._get_camera_attribute(self.cam_pose, 'rotation_euler')
        camera_translation = self._get_camera_attribute(self.cam_pose, 'location')
        H_c2w = Matrix.Translation(Vector(camera_translation)) @ Euler(
            camera_rotation, 'XYZ').to_matrix().to_4x4()

        # Blender to opencv coordinates.
        H_c2w_opencv = H_c2w @ Matrix.Rotation(math.radians(-180), 4, "X")

        frame_gt = []
        for idx, obj in enumerate(self.dataset_objects):
            object_rotation = self._get_object_attribute(obj, 'rotation_euler')
            object_translation = self._get_object_attribute(obj, 'location')
            H_m2w = Matrix.Translation(Vector(object_translation)) @ Euler(
                object_rotation, 'XYZ').to_matrix().to_4x4()

            cam_H_m2c = (H_m2w.inverted() @ H_c2w_opencv).inverted()

            cam_R_m2c = cam_H_m2c.to_quaternion().to_matrix()
            cam_R_m2c = list(cam_R_m2c[0]) + list(cam_R_m2c[1]) + list(cam_R_m2c[2])
            cam_t_m2c = list(cam_H_m2c.to_translation() * 1000.)

            # ignore examples that fell through the plane
            if not np.linalg.norm(cam_t_m2c) > self._ignore_dist_thres * 1000.:
                frame_gt.append({
                    'cam_R_m2c': cam_R_m2c,
                    'cam_t_m2c': cam_t_m2c,
                    'obj_id': self._get_object_attribute(obj, 'id')
                })
            else:
                print('ignored obj, ', self._get_object_attribute(obj, 'id'))

        return frame_gt 
Example #15
Source File: utils.py    From se-blender with GNU General Public License v2.0 5 votes vote down vote up
def rotX(rad):
    return Matrix.Rotation(rad, 4, 'X') 
Example #16
Source File: object_drop.py    From BlenderGIS with GNU General Public License v3.0 5 votes vote down vote up
def get_align_matrix(location, normal):
    up = Vector((0, 0, 1))
    angle = normal.angle(up)
    axis = up.cross(normal)
    mat_rot = Matrix.Rotation(angle, 4, axis)
    mat_loc = Matrix.Translation(location)
    mat_align = mat_rot @ mat_loc
    return mat_align 
Example #17
Source File: SuncgLoader.py    From BlenderProc with GNU General Public License v3.0 5 votes vote down vote up
def _load_box(self, node, material_adjustments, transform, parent):
        """ Creates a cube inside blender which follows the specifications of the given node.

        :param node: The node dict which contains information from house.json..
        :param material_adjustments: Adjustments to the materials which were specified inside house.json.
        :param transform: The transformation that should be applied to the loaded objects.
        :param parent: The parent object to which the ground should be linked
        """
        bpy.ops.mesh.primitive_cube_add(location=(0, 0, 0))
        box = bpy.context.object
        box.name = "Box#" + node["id"]
        box.matrix_world = Matrix.Identity(4)
        # Scale the cube to the required dimensions
        box.matrix_world @= Matrix.Scale(node["dimensions"][0] / 2, 4, (1.0, 0.0, 0.0)) @ Matrix.Scale(node["dimensions"][1] / 2, 4, (0.0, 1.0, 0.0)) @ Matrix.Scale(node["dimensions"][2] / 2, 4, (0.0, 0.0, 1.0))

        # Create UV mapping (beforehand we apply the scaling from the previous step, such that the resulting uv mapping has the correct aspect)
        bpy.ops.object.transform_apply(scale=True)
        bpy.ops.object.editmode_toggle()
        bpy.ops.uv.cube_project()
        bpy.ops.object.editmode_toggle()

        # Create an empty material which is filled in the next step
        mat = bpy.data.materials.new(name="material_0")
        mat.use_nodes = True
        box.data.materials.append(mat)

        self._transform_and_colorize_object(box, material_adjustments, transform, parent)
        # set class to void
        box["category_id"] = LabelIdMapping.label_id_map["void"]
        # Rotate cube to match objects loaded from .obj, has to be done after transformations have been applied
        box.matrix_world = Matrix.Rotation(math.radians(90), 4, "X") @ box.matrix_world

        # Set the physics property of all imported boxes
        self._set_properties(bpy.context.selected_objects) 
Example #18
Source File: convert.py    From BlenderTools with GNU General Public License v2.0 5 votes vote down vote up
def vec_roll_to_mat3(axis, roll):
    """Computes 3x3 Matrix from rotation axis and its roll.

    :param axis: Rotation
    :type axis: Vector
    :param roll: Roll
    :type roll: float
    :return: 3x3 Matrix
    :rtype: Matrix
    """
    nor = axis.normalized()
    target = Vector((0, 1, 0))
    axis = target.cross(nor)

    if axis.dot(axis) > 1.0e-9:
        axis.normalize()
        theta = _math_utils.angle_normalized_v3v3(target, nor)
        b_matrix = Matrix.Rotation(theta, 4, axis)
    else:
        if target.dot(nor) > 0:
            up_or_down = 1.0
        else:
            up_or_down = -1.0

        b_matrix = Matrix()
        b_matrix[0] = (up_or_down, 0, 0, 0)
        b_matrix[1] = (0, up_or_down, 0, 0)
        b_matrix[2] = (0, 0, 1, 0)
        b_matrix[3] = (0, 0, 0, 1)

    roll_matrix = Matrix.Rotation(roll, 4, nor)
    return (roll_matrix @ b_matrix).to_3x3() 
Example #19
Source File: utils.py    From se-blender with GNU General Public License v2.0 5 votes vote down vote up
def rotY(rad):
    return Matrix.Rotation(rad, 4, 'Y') 
Example #20
Source File: convert.py    From BlenderTools with GNU General Public License v2.0 5 votes vote down vote up
def scs_to_blend_matrix():
    """Transformation matrix for space conversion from SCS coordinate system to Blender's.

    :return: Transformation matrix
    :rtype: Matrix
    """
    return Matrix.Rotation(math.pi / 2, 4, 'X') 
Example #21
Source File: utils.py    From se-blender with GNU General Public License v2.0 5 votes vote down vote up
def rotZ(rad):
    return Matrix.Rotation(rad, 4, 'Z')


# ----------------------------------- predefined transformations ------------------------------------ # 
Example #22
Source File: armature.py    From BlenderExporter with Apache License 2.0 5 votes vote down vote up
def get_matrix(bpyBone, matrix_world):
        if bpy.context.scene.world.preserveZUpRight == True :
            SystemMatrix = Matrix.Scale(1, 4, Vector((0, 0, 1)))
        else :
            SystemMatrix = Matrix.Scale(-1, 4, Vector((0, 0, 1))) @ Matrix.Rotation(radians(-90), 4, 'X')

        if bpyBone.parent:
            return (SystemMatrix @ matrix_world @ bpyBone.parent.matrix).inverted() @ (SystemMatrix @ matrix_world @ bpyBone.matrix)
        else:
            return SystemMatrix @ matrix_world @ bpyBone.matrix
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
Example #23
Source File: phyllotaxis_flower.py    From blender-scripting with MIT License 5 votes vote down vote up
def geometry(self, frame=0):
        t = frame / self.frames
        Rot = Matrix.Rotation(0.5*pi, 4, 'Y')
        bm = bmesh.new()

        for i in range(self.n):
            t0 = i / self.n
            r0, theta = t0*self.r0, i*goldenAngle - frame*goldenAngle + t*self.offset

            x = r0*cos(theta)
            y = r0*sin(theta)
            z = self.h0/2 - (self.h0 / (self.r0*self.r0))*r0*r0
            p0 = Vector((x, y, z))

            T0, N0, B0 = getTNBfromVector(p0)
            M0 = Matrix([T0, B0, N0]).to_4x4().transposed()

            for j in range(self.m):
                t1 = j / self.m
                t2 = 0.4 + 0.6*t0
                r1, theta = t2*t1*self.r1, j*goldenAngle #- frame*goldenAngle + t*self.offset

                x = r1*cos(theta)
                y = r1*sin(theta)
                z = self.h1 - (self.h1 / (self.r1*self.r1))*r1*r1
                p1 = Vector((x, y, z))
                T1, N1, B1 = getTNBfromVector(p1)
                M1 = Matrix([T1, B1, N1]).to_4x4().transposed()

                p = p0 + M0*p1
                r2 = t2*t1*self.r2

                T = Matrix.Translation(p)
                bmesh.ops.create_cone(bm,
                                cap_ends=True, segments=6,
                                diameter1=r2, diameter2=r2,
                                depth=0.1*r2, matrix=T*M0*M1*Rot)
        return bm 
Example #24
Source File: archipack_custom.py    From archipack with GNU General Public License v3.0 5 votes vote down vote up
def add_vertex_groups(self, o, d, center):
        vgroups = {vgroup.name: vgroup.index for vgroup in o.vertex_groups}

        # matrix to retrieve vertex distance from center
        tM = Matrix.Translation(center)
        rM_top = Matrix.Rotation(-pi / 2, 4, Vector((0, 1, 0)))
        rM_front = Matrix.Rotation(pi / 2, 4, Vector((0, 0, 1)))
        rM_back = Matrix.Rotation(-pi / 2, 4, Vector((0, 0, 1)))
        rM_left = Matrix.Rotation(pi, 4, Vector((0, 0, 1)))
        rM_right = Matrix.Rotation(0, 4, Vector((0, 0, 1)))
        itM = [(tM * rM).inverted() * o.matrix_world for rM in [rM_left, rM_right, rM_back, rM_front, rM_top]]

        limit = [
            self.x_min, self.x_max,
            self.y_min, self.y_max,
            self.z_max,
            ]
        soft = [
            self.x_soft, self.x_soft,
            self.y_soft, self.y_soft,
            self.z_soft,
            ]

        for i, group_name in enumerate(['left', 'right', 'back', 'front', 'top']):
            if group_name not in vgroups:
                g = o.vertex_groups.new()
                g.name = group_name
            else:
                g = o.vertex_groups[group_name]
            self.weight(o, g, itM[i], soft[i], limit[i]) 
Example #25
Source File: mi_draw_extrude.py    From mifthtools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def rotate_verts(verts, rot_angle, axis, rot_origin):
    for vert in verts:
        rot_mat = Matrix.Rotation(rot_angle, 3, axis)
        vert.co = rot_mat @ (vert.co - rot_origin) + rot_origin 
Example #26
Source File: mi_draw_extrude.py    From mifthtools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def rotate_verts(verts, rot_angle, axis, rot_origin):
    for vert in verts:
        rot_mat = Matrix.Rotation(rot_angle, 3, axis)
        vert.co = rot_mat * (vert.co - rot_origin) + rot_origin 
Example #27
Source File: railing.py    From building_tools with MIT License 5 votes vote down vote up
def rotate_sloped_rail_bounds(bm, cylinder_verts, dir):
    """ Rotate the end faces of sloping cylinder rail to be vertically aligned
    """
    mid = len(cylinder_verts) // 2
    vts = sort_verts(cylinder_verts, dir)
    angle = math.atan(dir.z / dir.xy.length)
    for bunch in [vts[:mid], vts[-mid:]]:
        bmesh.ops.rotate(
            bm, verts=bunch, cent=calc_verts_median(bunch),
            matrix=Matrix.Rotation(angle, 4, dir.cross(Vector((0, 0, -1))))
        ) 
Example #28
Source File: railing.py    From building_tools with MIT License 5 votes vote down vote up
def rotate_top_faces(bm, cylinder, dir, left):
    """ Rotate the upper faces (align posts to slanted railing)
    """
    mid = len(cylinder) // 2
    vts = sort_verts(cylinder, dir)
    angle = math.atan(left.z / left.xy.length)
    bmesh.ops.rotate(
            bm, verts=vts[-mid:], cent=calc_verts_median(vts[-mid:]),
            matrix=Matrix.Rotation(angle, 4, dir.cross(-left))
        ) 
Example #29
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 #30
Source File: uvcalc_smart_project.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def rotate_uvs(uv_points, angle):

    if angle != 0.0:
        mat = Matrix.Rotation(angle, 2)
        for uv in uv_points:
            uv[:] = mat * uv