Python mathutils.Matrix() Examples

The following are 30 code examples of mathutils.Matrix(). 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 , or try the search function .
Example #1
Source File: structures.py    From godot-blender-exporter with GNU General Public License v2.0 6 votes vote down vote up
def fix_matrix(mtx):
    """ Shuffles a matrix to change from y-up to z-up"""
    # TODO: can this be replaced my a matrix multiplcation?
    trans = mathutils.Matrix(mtx)
    up_axis = 2

    for i in range(3):
        trans[1][i], trans[up_axis][i] = trans[up_axis][i], trans[1][i]
    for i in range(3):
        trans[i][1], trans[i][up_axis] = trans[i][up_axis], trans[i][1]

    trans[1][3], trans[up_axis][3] = trans[up_axis][3], trans[1][3]

    trans[up_axis][0] = -trans[up_axis][0]
    trans[up_axis][1] = -trans[up_axis][1]
    trans[0][up_axis] = -trans[0][up_axis]
    trans[1][up_axis] = -trans[1][up_axis]
    trans[up_axis][3] = -trans[up_axis][3]

    return trans 
Example #2
Source File: nodes.py    From Arnold-For-Blender with GNU General Public License v3.0 6 votes vote down vote up
def draw_buttons(self, context, layout):
        col = layout.column()
        col.prop(self, "geometry_type")
        col.prop(self, "axis")
        col.prop(self, "ramp")
        col.prop(self, "height_edge")
        col.prop(self, "width_edge")
        col.prop(self, "roundness")
        col.label(text="Matrix:")
        sub = col.box().column()
        sub.prop_search(self, "geometry_matrix_object", context.scene, "objects", text="")
        sub = sub.column()
        sub.enabled = not self.geometry_matrix_object
        sub.template_component_menu(self, "geometry_matrix_scale", name="Weight:")
        sub.template_component_menu(self, "geometry_matrix_rotation", name="Rotation:")
        sub.template_component_menu(self, "geometry_matrix_translation", name="Translation:") 
Example #3
Source File: camera-calibration-pvr.py    From camera-calibration-pvr with GNU General Public License v2.0 6 votes vote down vote up
def get_vertical_mode_matrix(is_vertical, camera_rotation):
    if is_vertical:
    # Get the up direction of the camera
        up_vec = mathutils.Vector((0.0, 1.0, 0.0))
        up_vec.rotate(camera_rotation)
        # Decide around which axis to rotate
        vert_mode_rotate_x = abs(up_vec[0]) < abs(up_vec[1])
        # Create rotation matrix
        if vert_mode_rotate_x:
            vert_angle = pi / 2 if up_vec[1] > 0 else -pi / 2
            return mathutils.Matrix().Rotation(vert_angle, 3, "X")
        else:
            vert_angle = pi / 2 if up_vec[0] < 0 else -pi / 2
            return mathutils.Matrix().Rotation(vert_angle, 3, "Y")
    else:
        return mathutils.Matrix().Identity(3) 
Example #4
Source File: nodes.py    From Arnold-For-Blender with GNU General Public License v3.0 6 votes vote down vote up
def ai_properties(self):
        scale = self.geometry_matrix_scale
        matrix = Matrix([
            [scale.x, 0, 0],
            [0, scale.y, 0],
            [0, 0, scale.z]
        ])
        matrix.rotate(Euler(self.geometry_matrix_rotation))
        matrix = matrix.to_4x4()
        matrix.translation = (self.geometry_matrix_translation)
        return {
            "format": ('STRING', self.format),
            "resolution": ('STRING', self.resolution),
            "portal_mode": ('STRING', self.portal_mode),
            "matrix": ('MATRIX', matrix),
            "camera": ('BOOL', self.camera),
            "diffuse": ('BOOL', self.diffuse),
            "specular": ('BOOL', self.specular),
            "sss": ('BOOL', self.sss),
            "volume": ('BOOL', self.volume),
            "transmission": ('BOOL', self.transmission)
        } 
Example #5
Source File: render_random_pose.py    From ObjectPoseEstimationSummary with MIT License 6 votes vote down vote up
def setup_camera(scene, fx=572, fy=574, cx=325, cy=242):
    cam = scene.objects['Camera']
    width = scene.render.resolution_x
    height = scene.render.resolution_y
    cam.data.sensor_height = cam.data.sensor_width * height / width
    cam.data.lens = (fx + fy) / 2 * cam.data.sensor_width / width
    cam.data.shift_x = (width / 2 - cx) / width
    cam.data.shift_y = (cy - height / 2) / width
    # change to OpenCV camera coordinate system
    cam.matrix_world = Matrix(((1.0, 0.0, 0.0, 0.0),
                               (0.0, -1.0, 0.0, 0.0),
                               (0.0, 0.0, -1.0, 0.0),
                               (0.0, 0.0, 0.0, 1.0)))
    return cam


# Add material to object 
Example #6
Source File: utils.py    From verge3d-blender-addon with GNU General Public License v3.0 6 votes vote down vote up
def get_lookat_aligned_up_matrix(eye, target):

    """
    This method uses camera axes for building the matrix.
    """

    axis_z = (eye - target).normalized()

    if axis_z.length == 0:
        axis_z = mathutils.Vector((0, -1, 0))

    axis_x = mathutils.Vector((0, 0, 1)).cross(axis_z)

    if axis_x.length == 0:
        axis_x = mathutils.Vector((1, 0, 0))

    axis_y = axis_z.cross(axis_x)

    return mathutils.Matrix([
        axis_x,
        axis_y,
        axis_z,
    ]).transposed() 
Example #7
Source File: utils.py    From verge3d-blender-addon with GNU General Public License v3.0 6 votes vote down vote up
def mat4_svd_decompose_to_mats(mat4):
    """
    Decompose the given matrix into a couple of TRS-decomposable matrices or
    Returns None in case of an error.
    """

    try:
        u, s, vh = np.linalg.svd(mat4.to_3x3())
        mat_u = mathutils.Matrix(u)
        mat_s = mathutils.Matrix([[s[0], 0, 0], [0, s[1], 0], [0, 0, s[2]]])
        mat_vh = mathutils.Matrix(vh)

        # NOTE: a potential reflection part in U and VH matrices isn't considered
        mat_trans = mathutils.Matrix.Translation(mat4.to_translation())
        mat_left = mat_trans @ (mat_u @ mat_s).to_4x4()

        return (mat_left, mat_vh.to_4x4())

    except np.linalg.LinAlgError:
        # numpy failed to decompose the matrix
        return None 
Example #8
Source File: archipack_2d.py    From archipack with GNU General Public License v3.0 6 votes vote down vote up
def scale_rot_matrix(self, u, v):
        """
            given vector u and v (from and to p0 p1)
            apply scale factor to radius and
            return a matrix to rotate and scale
            the center around u origin so
            arc fit v
        """
        # signed angle old new vectors (rotation)
        a = self.signed_angle(u, v)
        # scale factor
        scale = v.length / u.length
        ca = scale * cos(a)
        sa = scale * sin(a)
        return scale, Matrix([
            [ca, -sa],
            [sa, ca]
            ]) 
Example #9
Source File: export_dxf.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def get_view_projection_matrix(context, settings):
	"""
	Returns view projection matrix.
	Projection matrix is either identity if 3d export is selected or
	camera projection if a camera or view is selected.
	Currently only orthographic projection is used. (Subject to discussion).
	"""	
	cam = settings['projectionThrough']
	if cam == None:
		mw = mathutils.Matrix()
		mw.identity()
	elif cam in projectionMapping.keys():
		projection = mathutils.Matrix.OrthoProjection(projectionMapping[cam], 4)
		mw = projection
	else: # get camera with given name
		c = context.scene.objects[cam]
		mw = getCameraMatrix(c)
	return mw 
Example #10
Source File: archipack_2d.py    From archipack with GNU General Public License v3.0 6 votes vote down vote up
def rotate(self, a):
        """
            Rotate center so we rotate ccw arround p0
        """
        ca = cos(a)
        sa = sin(a)
        rM = Matrix([
            [ca, -sa],
            [sa, ca]
            ])
        p0 = self.p0
        self.c = p0 + rM * (self.c - p0)
        dp = p0 - self.c
        self.a0 = atan2(dp.y, dp.x)
        return self

    # make offset for line / arc, arc / arc 
Example #11
Source File: serializer.py    From godot-blender-exporter with GNU General Public License v2.0 6 votes vote down vote up
def add_obj_xform_track(self, node_type, track_path,
                            xform_frames_list, frame_range,
                            parent_mat_inverse=mathutils.Matrix.Identity(4)):
        """Add a object transform track to AnimationResource"""
        track = TransformTrack(
            track_path,
            frames_iter=range(frame_range[0], frame_range[1]),
            values_iter=xform_frames_list,
        )
        track.set_parent_inverse(parent_mat_inverse)
        if node_type in ("SpotLight", "DirectionalLight",
                         "Camera", "CollisionShape"):
            track.is_directional = True

        self.add_track(track)

    # pylint: disable-msg=too-many-arguments 
Example #12
Source File: offscreen.py    From jewelcraft with GNU General Public License v3.0 6 votes vote down vote up
def offscreen_refresh(self, context):
        if self.offscreen is not None:
            self.offscreen.free()

        width = self.region.width
        height = self.region.height
        self.offscreen = gpu.types.GPUOffScreen(width, height)

        mat_offscreen = Matrix()
        mat_offscreen[0][0] = 2 / width
        mat_offscreen[0][3] = -1
        mat_offscreen[1][1] = 2 / height
        mat_offscreen[1][3] = -1

        with self.offscreen.bind():
            bgl.glClear(bgl.GL_COLOR_BUFFER_BIT)

            with gpu.matrix.push_pop():
                gpu.matrix.load_matrix(mat_offscreen)
                gpu.matrix.load_projection_matrix(Matrix())

                self.draw_gems(context) 
Example #13
Source File: muv_uvbb_ops.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def to_matrix(self):
        """
        mat = M(to original transform)^-1 * Mt(to origin) * Ms *
              Mt(to origin)^-1 * M(to original transform)
        """
        m = self.__mat
        mi = self.__mat.inverted()
        mtoi = mathutils.Matrix.Translation((-self.__iox, -self.__ioy, 0.0))
        mto = mathutils.Matrix.Translation((self.__iox, self.__ioy, 0.0))
        # every point must be transformed to origin
        t = m * mathutils.Vector((self.__ix, self.__iy, 0.0))
        tix, tiy = t.x, t.y
        t = m * mathutils.Vector((self.__ox, self.__oy, 0.0))
        tox, toy = t.x, t.y
        t = m * mathutils.Vector((self.__x, self.__y, 0.0))
        tx, ty = t.x, t.y
        ms = mathutils.Matrix()
        ms.identity()
        if self.__dir_x == 1:
            ms[0][0] = (tx - tox) * self.__dir_x / (tix - tox)
        if self.__dir_y == 1:
            ms[1][1] = (ty - toy) * self.__dir_y / (tiy - toy)
        return mi * mto * ms * mtoi * m 
Example #14
Source File: drawing.py    From addon_common with GNU General Public License v3.0 6 votes vote down vote up
def get_mvp_matrix(self, view3D=True):
        '''
        if view3D == True: returns MVP for 3D view
        else: returns MVP for pixel view
        TODO: compute separate M,V,P matrices
        '''
        if not self.r3d: return None
        if view3D:
            # 3D view
            return self.r3d.perspective_matrix
        else:
            # pixel view
            return self.get_pixel_matrix()

        mat_model = Matrix()
        mat_view = Matrix()
        mat_proj = Matrix()

        view_loc = self.r3d.view_location # vec
        view_rot = self.r3d.view_rotation # quat
        view_per = self.r3d.view_perspective # 'PERSP' or 'ORTHO'

        return mat_model,mat_view,mat_proj 
Example #15
Source File: io_export_paper_model.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def finalize_islands(self, title_height=0):
        for island in self.islands:
            if title_height:
                island.title = "[{}] {}".format(island.abbreviation, island.label)
            points = list(vertex.co for vertex in island.verts) + island.fake_verts
            angle = M.geometry.box_fit_2d(points)
            rot = M.Matrix.Rotation(angle, 2)
            for point in points:
                # note: we need an in-place operation, and Vector.rotate() seems to work for 3d vectors only
                point[:] = rot * point
            for marker in island.markers:
                marker.rot = rot * marker.rot
            bottom_left = M.Vector((min(v.x for v in points), min(v.y for v in points) - title_height))
            for point in points:
                point -= bottom_left
            island.bounding_box = M.Vector((max(v.x for v in points), max(v.y for v in points))) 
Example #16
Source File: blender_utils.py    From pvnet-rendering with Apache License 2.0 6 votes vote down vote up
def get_3x4_RT_matrix_from_blender(camera):
    # bcam stands for blender camera
    R_bcam2cv = Matrix(
        ((1, 0,  0),
         (0, -1, 0),
         (0, 0, -1)))

    # Use matrix_world instead to account for all constraints
    location, rotation = camera.matrix_world.decompose()[0:2]
    R_world2bcam = rotation.to_matrix().transposed()

    # Convert camera location to translation vector used in coordinate changes
    # Use location from matrix_world to account for constraints:
    T_world2bcam = -1 * R_world2bcam * location

    # Build the coordinate transform matrix from world to computer vision camera
    R_world2cv = R_bcam2cv * R_world2bcam
    T_world2cv = R_bcam2cv * T_world2bcam

    # put into 3x4 matrix
    RT = Matrix((R_world2cv[0][:] + (T_world2cv[0],),
                 R_world2cv[1][:] + (T_world2cv[1],),
                 R_world2cv[2][:] + (T_world2cv[2],)))
    return RT 
Example #17
Source File: car_rig.py    From rigacar with GNU General Public License v3.0 6 votes vote down vote up
def _create_bone(self, rig, name, delta_pos):
        b = rig.data.edit_bones.new('DEF-' + name)

        b.head = self.bones_position[name] + delta_pos
        b.tail = b.head
        if name == 'Body':
            b.tail.y += b.tail.z * 4
        else:
            b.tail.y += b.tail.z

        target_obj_name = self.target_objects_name.get(name)
        if target_obj_name is not None and target_obj_name in bpy.context.scene.objects:
            target_obj = bpy.context.scene.objects[target_obj_name]
            if name == 'Body':
                b.tail = b.head
                b.tail.y += target_obj.dimensions[1] / 2 if target_obj.dimensions and target_obj.dimensions[0] != 0 else 1
            target_obj.parent = rig
            target_obj.parent_bone = b.name
            target_obj.parent_type = 'BONE'
            target_obj.location += rig.matrix_world.to_translation()
            target_obj.matrix_parent_inverse = (rig.matrix_world @ mathutils.Matrix.Translation(b.tail)).inverted()

        return b 
Example #18
Source File: utils.py    From addon_common with GNU General Public License v3.0 5 votes vote down vote up
def shorten_floats(s):
    # reduces number of digits (for float) found in a string
    # useful for reducing noise of printing out a Vector, Buffer, Matrix, etc.
    s = re.sub(r'(?P<neg>-?)(?P<d0>\d)\.(?P<d1>\d)\d\d+e-02', r'\g<neg>0.0\g<d0>\g<d1>', s)
    s = re.sub(r'(?P<neg>-?)(?P<d0>\d)\.\d\d\d+e-03', r'\g<neg>0.00\g<d0>', s)
    s = re.sub(r'-?\d\.\d\d\d+e-0[4-9]', r'0.000', s)
    s = re.sub(r'-?\d\.\d\d\d+e-[1-9]\d', r'0.000', s)
    s = re.sub(r'(?P<digs>\d\.\d\d\d)\d+', r'\g<digs>', s)
    return s 
Example #19
Source File: archipack_blind.py    From archipack with GNU General Public License v3.0 5 votes vote down vote up
def cylinder(self, radius, size, x, y, z, axis, verts, faces, matids):
        seg = 12
        deg = 2 * pi / seg
        nv = len(verts)

        if axis == 'X':
            tM = Matrix([
                [0, 0, size, x],
                [0, radius, 0, y],
                [radius, 0, 0, z],
                [0, 0, 0, 1]
            ])

        elif axis == 'Y':
            tM = Matrix([
                [radius, 0, 0, x],
                [0, 0, size, y],
                [0, radius, 0, z],
                [0, 0, 0, 1]
            ])

        else:
            tM = Matrix([
                [radius, 0, 0, x],
                [0, radius, 0, y],
                [0, 0, size, z],
                [0, 0, 0, 1]
            ])

        verts.extend([tM * Vector((sin(deg * a), cos(deg * a), 0)) for a in range(seg)])
        verts.extend([tM * Vector((sin(deg * a), cos(deg * a), 1)) for a in range(seg)])

        faces.extend([tuple([nv + i + f for f in (0, 1, seg + 1, seg)]) for i in range(seg - 1)])
        faces.append((nv + seg - 1, nv, nv + seg, nv + 2 * seg - 1))
        matids.extend([2 for i in range(seg)]) 
Example #20
Source File: Object3D.py    From three.py with MIT License 5 votes vote down vote up
def __init__(self):
        self.transform = Matrix()
        self.parent = None
        self.children = []
        self.name = "" 
Example #21
Source File: import_usdz.py    From BlenderUSDZ with GNU General Public License v3.0 5 votes vote down vote up
def addBone(arm, joint, pose):
    stack = joint.split('/')
    bone = arm.data.edit_bones.new(stack[-1])
    bone.head = (0.0, 0.0, 0.0)
    bone.tail = (0.0, 1.0, 0.0)
    matrix = mathutils.Matrix(pose)
    matrix.transpose()
    bone.transform(matrix)
    if len(stack) > 1:
        bone.parent = arm.data.edit_bones[stack[-2]] 
Example #22
Source File: car_rig.py    From rigacar with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, armature, bone_name):
        objs = [o for o in armature.children if o.parent_bone == bone_name]
        bone = armature.data.bones[bone_name]
        self.__center = bone.head.copy()
        if not objs:
            self.__xyz = [bone.head.x - bone.length / 2, bone.head.x + bone.length / 2, bone.head.y - bone.length, bone.head.y + bone.length, .0, bone.head.z * 2]
        else:
            self.__xyz = [inf, -inf, inf, -inf, inf, -inf]
            self.__compute(mathutils.Matrix(), *objs) 
Example #23
Source File: drawing.py    From addon_common with GNU General Public License v3.0 5 votes vote down vote up
def get_pixel_matrix(self):
        '''
        returns MVP for pixel view
        TODO: compute separate M,V,P matrices
        '''
        return Matrix(self.get_pixel_matrix_list()) if self.r3d else None 
Example #24
Source File: node_converters.py    From godot-blender-exporter with GNU General Public License v2.0 5 votes vote down vote up
def blender_value_to_string(blender_value):
    """convert blender socket.default_value to shader script"""
    if isinstance(blender_value,
                  (bpy.types.bpy_prop_array, mathutils.Vector)):
        tmp = list()
        for val in blender_value:
            tmp.append(str(val))

        return "vec%d(%s)" % (len(tmp), ", ".join(tmp))

    if isinstance(blender_value, mathutils.Euler):
        return "vec3(%s)" % ', '.join([str(d) for d in blender_value])

    if isinstance(blender_value, mathutils.Matrix):
        # godot mat is column major order
        mat = blender_value.transposed()
        column_vec_list = list()
        for vec in mat:
            column_vec_list.append(blender_value_to_string(vec))

        return "mat%d(%s)" % (
            len(column_vec_list),
            ", ".join(column_vec_list)
        )

    return "float(%s)" % blender_value 
Example #25
Source File: armature.py    From godot-blender-exporter with GNU General Public License v2.0 5 votes vote down vote up
def find_bone_rest(self, bl_bone_name):
        """Given a blender bone name , return its rest matrix"""
        bone_id = self.find_bone_id(bl_bone_name)
        bone_rest_key = 'bones/%d/rest' % bone_id
        return self.get(bone_rest_key, mathutils.Matrix.Identity(4)) 
Example #26
Source File: serializer.py    From godot-blender-exporter with GNU General Public License v2.0 5 votes vote down vote up
def set_parent_inverse(self, parent_inverse):
        """Blender interpolate is matrix_basis, it needs to left multiply
        its parent's object.matrix_parent_inverse to get
        matrix_local(parent space transform)"""
        self.parent_trans_inverse = mathutils.Matrix(parent_inverse) 
Example #27
Source File: serializer.py    From godot-blender-exporter with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, track_path, frames_iter=(), values_iter=()):
        super().__init__("transform", track_path, frames_iter, values_iter)
        self.parent_trans_inverse = mathutils.Matrix.Identity(4)

        # Fix of object's rotation, directional object like
        # camera, spotLight has different initial orientation
        self.is_directional = False

        self.interp = LINEAR_INTERPOLATION 
Example #28
Source File: structures.py    From godot-blender-exporter with GNU General Public License v2.0 5 votes vote down vote up
def fix_bone_attachment_transform(attachment_obj, blender_transform):
    """Godot and blender bone children nodes' transform relative to
    different bone joints, so there is a difference of bone_length
    along bone direction axis"""
    armature_obj = attachment_obj.parent
    bone_length = armature_obj.data.bones[attachment_obj.parent_bone].length
    mtx = mathutils.Matrix(blender_transform)
    mtx[1][3] += bone_length
    return mtx 
Example #29
Source File: views.py    From import_3dm with MIT License 5 votes vote down vote up
def handle_view(context, view, name, scale):
        vp = view.Viewport

        # Construct transformation matrix
        mat = Matrix([
            [vp.CameraX.X, vp.CameraX.Y, vp.CameraX.Z, 0],
            [vp.CameraY.X, vp.CameraY.Y, vp.CameraY.Z, 0],
            [vp.CameraZ.X, vp.CameraZ.Y, vp.CameraZ.Z, 0],
            [0,0,0,1]])

        mat.invert()
        
        mat[0][3] = vp.CameraLocation.X * scale
        mat[1][3] = vp.CameraLocation.Y * scale
        mat[2][3] = vp.CameraLocation.Z * scale
        
        lens = vp.Camera35mmLensLength
        
        blcam = utils.get_iddata(context.blend_data.cameras, None, name, None)   
            
        # Set camera to perspective or parallel
        if vp.IsPerspectiveProjection:
            blcam.type = "PERSP"
            blcam.lens = lens
            blcam.sensor_width = 36.0
        elif vp.IsParallelProjection:
            blcam.type = "ORTHO"
            frustum = vp.GetFrustum()
            blcam.ortho_scale = (frustum['right'] - frustum['left']) * scale
            
        # Link camera data to new object
        blobj = utils.get_iddata(context.blend_data.objects, None, name, blcam)
        blobj.matrix_world = mat
            
        # Return new camera
        return blobj 
Example #30
Source File: simulator.py    From BlenderAndMBDyn with GNU General Public License v3.0 5 votes vote down vote up
def insert_keyframe(self, label, fields):
        database.node[label].location = fields[:3]
        if self.orientation == "orientation matrix":
            euler = Matrix([fields[3:6], fields[6:9], fields[9:12]]).to_euler()
            database.node[label].rotation_euler = euler[0], euler[1], euler[2]
        elif self.orientation == "euler321":
            database.node[label].rotation_euler = Euler((math.radians(fields[5]), math.radians(fields[4]), math.radians(fields[3])), 'XYZ')
        elif self.orientation == "euler123":
            database.node[label].rotation_euler = Euler((math.radians(fields[3]), math.radians(fields[4]), math.radians(fields[5])), 'ZYX').to_quaternion().to_euler('XYZ')
            #database.node[label].rotation_mode = 'ZYX'
        elif self.orientation == "orientation vector":
            #database.node[label].rotation_axis_angle = [math.sqrt(sum([x*x for x in fields[3:6]]))] + fields[3:6]
            database.node[label].rotation_euler = Quaternion(fields[3:6], math.sqrt(sum([x*x for x in fields[3:6]]))).to_euler('XYZ')
        for data_path in "location rotation_euler".split():
            database.node[label].keyframe_insert(data_path)