Python mathutils.Euler() Examples

The following are 30 code examples of mathutils.Euler(). 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: 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 #2
Source File: functions.py    From coa_tools with GNU General Public License v3.0 6 votes vote down vote up
def clear_pose(obj):
    if obj.type == "ARMATURE":
        for bone in obj.pose.bones:
            bone.scale = Vector((1,1,1))
            bone.location = Vector((0,0,0))
            bone.rotation_euler = Euler((0,0,0),"XYZ")
            bone.rotation_quaternion = Euler((0,0,0),"XYZ").to_quaternion()
    elif obj.type == "MESH":
        obj.coa_sprite_frame = 0
        obj.coa_alpha = 1.0
        obj.coa_modulate_color = (1.0,1.0,1.0)
        #obj["coa_slot_index"] = max(0,len(obj.coa_slot)-1)
        #obj["coa_slot_index"] = obj.coa_slot_reset_index
        obj.coa_slot_index = 0 
Example #3
Source File: gltf2_blender_math.py    From glTF-Blender-IO with Apache License 2.0 6 votes vote down vote up
def list_to_mathutils(values: typing.List[float], data_path: str) -> typing.Union[Vector, Quaternion, Euler]:
    """Transform a list to blender py object."""
    target = get_target_property_name(data_path)

    if target == 'delta_location':
        return Vector(values)  # TODO Should be Vector(values) - Vector(something)?
    elif target == 'delta_rotation_euler':
        return Euler(values).to_quaternion()  # TODO Should be multiply(Euler(values).to_quaternion(), something)?
    elif target == 'location':
        return Vector(values)
    elif target == 'rotation_axis_angle':
        angle = values[0]
        axis = values[1:]
        return Quaternion(axis, math.radians(angle))
    elif target == 'rotation_euler':
        return Euler(values).to_quaternion()
    elif target == 'rotation_quaternion':
        return Quaternion(values)
    elif target == 'scale':
        return Vector(values)
    elif target == 'value':
        return Vector(values)

    return values 
Example #4
Source File: camera-calibration-pvr.py    From camera-calibration-pvr with GNU General Public License v2.0 6 votes vote down vote up
def reconstruct_rectangle(pa, pb, pc, pd, scale, focal):
    # Calculate the coordinates of the rectangle in 3d
    coords = get_lambda_d(pa, pb, pc, pd, scale, focal)
    # Calculate the transformation of the rectangle
    trafo = get_transformation(coords[0], coords[1], coords[2], coords[3])
    # Reconstruct the rotation angles of the transformation
    angles = get_rot_angles(trafo[0], trafo[1], trafo[2])
    xyz_matrix = mathutils.Euler((angles[0], angles[1], angles[2]), "XYZ")
    # Reconstruct the camera position and the corners of the rectangle in 3d such that it lies on the xy-plane
    tr = trafo[-1]
    cam_pos = apply_transformation([mathutils.Vector((0.0, 0.0, 0.0))], tr, xyz_matrix)[0]
    corners = apply_transformation(coords, tr, xyz_matrix)
    # Printout for debugging
    print("Focal length:", focal)
    print("Camera rotation:", degrees(angles[0]), degrees(angles[1]), degrees(angles[2]))
    print("Camera position:", cam_pos)
    length = (coords[0] - coords[1]).length
    width = (coords[0] - coords[3]).length
    size = max(length, width)
    print("Rectangle length:", length)
    print("Rectangle width:", width)
    print("Rectangle corners:", corners)
    return (cam_pos, xyz_matrix, corners, size) 
Example #5
Source File: show_hide_panel.py    From mmvt with GNU General Public License v3.0 6 votes vote down vote up
def rotate_brain(dx=None, dy=None, dz=None, keep_rotating=False, save_image=False, render_image=False):
    dx = bpy.context.scene.rotate_dx if dx is None else dx
    dy = bpy.context.scene.rotate_dy if dy is None else dy
    dz = bpy.context.scene.rotate_dz if dz is None else dz
    ShowHideObjectsPanel.rotate_dxyz += np.array([dx, dy, dz])
    bpy.context.scene.rotate_dx, bpy.context.scene.rotate_dy, bpy.context.scene.rotate_dz = dx, dy, dz
    rv3d = mu.get_view3d_region()
    rv3d.view_rotation.rotate(mathutils.Euler((math.radians(d) for d in (dx, dy, dz))))
    if bpy.context.scene.rotate_and_save or save_image:
        _addon().save_image('rotation', view_selected=bpy.context.scene.save_selected_view)
    # if bpy.context.scene.rotate_and_render or render_image:
    #     _addon().render_image('rotation')
    if bpy.context.scene.rotate_360 and any([ShowHideObjectsPanel.rotate_dxyz[k] >= 360 for k in range(3)]):
        stop_rotating()
    elif keep_rotating:
        start_rotating() 
Example #6
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 #7
Source File: materials.py    From Blender-Metaverse-Addon with GNU General Public License v3.0 6 votes vote down vote up
def fix_env_rotations():
    try:
        for world in bpy.data.worlds:
            nodes = world.node_tree.nodes
            links = world.node_tree.links
            mapping = find_existing_mapping(nodes)
            env = find_env_texture(nodes)

            if mapping == False and env != False:

                texture_coordinates = nodes.new("ShaderNodeTexCoord")
                texture_coordinates.location = (-800, 145)
                mapper = nodes.new("ShaderNodeMapping")
                mapper.location = (-625, 145)

                mapper.rotation = Euler((0.0, 0.0, 1.5707963705062866), 'XYZ')

                links.new(mapper.inputs[0],
                          texture_coordinates.outputs["Object"])
                links.new(env.inputs[0], mapper.outputs[0])

    except Exception as e:
        print(e) 
Example #8
Source File: do.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def text(self, en, scene, name):
        """
        en: dxf entity
        name: ignored; exists to make separate and merged objects methods universally callable from _call_types()
        Returns a new single line text object.
        """
        if self.import_text:
            name = en.text[:8]
            d = bpy.data.curves.new(name, "FONT")
            d.body = en.plain_text()
            d.size = en.height
            o = bpy.data.objects.new(name, d)
            o.rotation_euler = Euler((0, 0, radians(en.rotation)), 'XYZ')
            basepoint = self.proj(en.basepoint) if hasattr(en, "basepoint") else self.proj((0, 0, 0))
            o.location = self.proj((en.insert)) + basepoint
            if hasattr(en, "thickness"):
                et = en.thickness / 2
                d.extrude = abs(et)
                if et > 0:
                    o.location.z += et
                elif et < 0:
                    o.location.z -= et
            return o 
Example #9
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 #10
Source File: cm_templates.py    From CrowdMaster with GNU General Public License v3.0 6 votes vote down vote up
def build(self, buildRequest):
        t = time.time()
        rotDiff = random.uniform(self.settings["minRandRot"],
                                 self.settings["maxRandRot"])
        eul = mathutils.Euler(buildRequest.rot, 'XYZ')
        eul.rotate_axis('Z', math.radians(rotDiff))

        scaleDiff = random.uniform(self.settings["minRandSz"],
                                   self.settings["maxRandSz"])
        newScale = buildRequest.scale * scaleDiff

        buildRequest.rot = Vector(eul)
        buildRequest.scale = newScale
        cm_timings.placement["TemplateRANDOM"] += time.time() - t
        cm_timings.placementNum["TemplateRANDOM"] += 1
        self.inputs["Template"].build(buildRequest) 
Example #11
Source File: gl.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def draw_arc12(x, y, radius, start_angle, end_angle, subdivide):  # いずれ削除
    # 十二時から時計回りに描画
    v = Vector([0, 1, 0])
    e = Euler((0, 0, -start_angle))
    m = e.to_matrix()
    v = v * m
    if end_angle >= start_angle:
        a = (end_angle - start_angle) / (subdivide + 1)
    else:
        a = (end_angle + math.pi * 2 - start_angle) / (subdivide + 1)
    e = Euler((0, 0, -a))
    m = e.to_matrix()

    bgl.glBegin(bgl.GL_LINE_STRIP)
    for i in range(subdivide + 2):
        v1 = v * radius
        bgl.glVertex2f(x + v1[0], y + v1[1])
        v = v * m
    bgl.glEnd() 
Example #12
Source File: viewport.py    From BlendLuxCore with GNU General Public License v3.0 5 votes vote down vote up
def draw_bbox(location, rotation, bbox_min, bbox_max, progress=None, color=(0, 1, 0, 1)):
    rotation = mathutils.Euler(rotation)

    smin = Vector(bbox_min)
    smax = Vector(bbox_max)
    v0 = Vector(smin)
    v1 = Vector((smax.x, smin.y, smin.z))
    v2 = Vector((smax.x, smax.y, smin.z))
    v3 = Vector((smin.x, smax.y, smin.z))
    v4 = Vector((smin.x, smin.y, smax.z))
    v5 = Vector((smax.x, smin.y, smax.z))
    v6 = Vector((smax.x, smax.y, smax.z))
    v7 = Vector((smin.x, smax.y, smax.z))

    arrowx = smin.x + (smax.x - smin.x) / 2
    arrowy = smin.y - (smax.x - smin.x) / 2
    v8 = Vector((arrowx, arrowy, smin.z))

    vertices = [v0, v1, v2, v3, v4, v5, v6, v7, v8]
    for v in vertices:
        v.rotate(rotation)
        v += Vector(location)

    lines = [[0, 1], [1, 2], [2, 3], [3, 0], [4, 5], [5, 6], [6, 7], [7, 4], [0, 4], [1, 5],
             [2, 6], [3, 7], [0, 8], [1, 8]]
    draw_lines(vertices, lines, color)
    if progress != None:
        color = (color[0], color[1], color[2], .2)
        progress = progress * .01
        vz0 = (v4 - v0) * progress + v0
        vz1 = (v5 - v1) * progress + v1
        vz2 = (v6 - v2) * progress + v2
        vz3 = (v7 - v3) * progress + v3
        rects = (
            (v0, v1, vz1, vz0),
            (v1, v2, vz2, vz1),
            (v2, v3, vz3, vz2),
            (v3, v0, vz0, vz3))
        for r in rects:
            draw_rect_3d(r, color) 
Example #13
Source File: utils.py    From blendercam with GNU General Public License v2.0 5 votes vote down vote up
def Helix(r, np, zstart, pend, rev):
    c = []
    pi = math.pi
    v = mathutils.Vector((r, 0, zstart))
    e = mathutils.Euler((0, 0, 2.0 * pi / np))
    zstep = (zstart - pend[2]) / (np * rev)
    for a in range(0, int(np * rev)):
        c.append((v.x + pend[0], v.y + pend[1], zstart - (a * zstep)))
        v.rotate(e)
    c.append((v.x + pend[0], v.y + pend[1], pend[2]))

    return c 
Example #14
Source File: ItemWriter.py    From BlenderProc with GNU General Public License v3.0 5 votes vote down vote up
def _write_items_to_file_for_current_frame(self, path_prefix, items, attributes, frame=None):
        """ Writes the state of the given items to one numpy file for the given frame.

        :param path_prefix: The prefix path to write the files to.
        :param items: A list of items.
        :param attributes: A list of attributes to write per item.
        :param frame: The frame number.
        """
        value_list = []
        # Go over all items
        for item in items:
            value_list_per_item = {}
            # Go through all attributes
            for attribute in attributes:
                # Get the attribute value
                value = self.get_item_attribute_func(item, attribute)

                # If its a list of numbers, just add to the array, else just add one value
                if isinstance(value, Vector) or isinstance(value, Euler):
                    value = list(value)

                value_list_per_item[attribute] = value

            value_list.append(value_list_per_item)

        # Write to a numpy file
        np.save(path_prefix + "%04d" % frame + ".npy", np.string_(json.dumps(value_list))) 
Example #15
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 #16
Source File: CameraModule.py    From BlenderProc with GNU General Public License v3.0 5 votes vote down vote up
def _cam2world_matrix_from_cam_extrinsics(self, config):
        """ Determines camera extrinsics by using the given config and returns them in form of a cam to world frame transformation matrix.

        :param config: The configuration object.
        :return: The cam to world transformation matrix.
        """
        if not config.has_param("cam2world_matrix"):
            position = Utility.transform_point_to_blender_coord_frame(config.get_vector3d("location", [0, 0, 0]), self.source_frame)

            # Rotation
            rotation_format = config.get_string("rotation/format", "euler")
            value = config.get_vector3d("rotation/value", [0, 0, 0])
            if rotation_format == "euler":
                # Rotation, specified as euler angles
                rotation_euler = Utility.transform_point_to_blender_coord_frame(value, self.source_frame)
            elif rotation_format == "forward_vec":
                # Rotation, specified as forward vector
                forward_vec = Vector(Utility.transform_point_to_blender_coord_frame(value, self.source_frame))
                # Convert forward vector to euler angle (Assume Up = Z)
                rotation_euler = forward_vec.to_track_quat('-Z', 'Y').to_euler()
            elif rotation_format == "look_at":
                # Compute forward vector
                forward_vec = value - position
                forward_vec.normalize()
                # Convert forward vector to euler angle (Assume Up = Z)
                rotation_euler = forward_vec.to_track_quat('-Z', 'Y').to_euler()
            else:
                raise Exception("No such rotation format:" + str(rotation_format))

            rotation_matrix = Euler(rotation_euler, 'XYZ').to_matrix()

            if rotation_format == "look_at" or rotation_format == "forward_vec":
                inplane_rot = config.get_float("rotation/inplane_rot", 0.0)
                rotation_matrix = rotation_matrix @ Euler((0.0, 0.0, inplane_rot)).to_matrix()

            cam2world_matrix = Matrix.Translation(Vector(position)) @ rotation_matrix.to_4x4()
        else:
            cam2world_matrix = Matrix(np.array(config.get_list("cam2world_matrix")).reshape(4, 4).astype(np.float32))
        return cam2world_matrix 
Example #17
Source File: links.py    From phobos with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setLinkTransformations(model, parent):
    """Assigns the transformations recursively for a model parent link according to the model.
    
    This needs access to the **object** key of a link entry in the specified model.
    The transformations for each link object are extracted from the specified model and applied to
    the Blender object.

    Args:
      parent(dict): parent link you want to set the children for.
      model(dict): model dictionary containing the **object** key for each link

    Returns:

    """
    bpy.context.scene.layers = bUtils.defLayers(defs.layerTypes['link'])
    for chi in parent['children']:
        child = model['links'][chi]

        # apply transform as saved in model
        location = mathutils.Matrix.Translation(child['pose']['translation'])
        rotation = (
            mathutils.Euler(tuple(child['pose']['rotation_euler']), 'XYZ').to_matrix().to_4x4()
        )

        log("Transforming link {0}.".format(child['name']), 'DEBUG')
        transform_matrix = location * rotation
        child['object'].matrix_local = transform_matrix

        # traverse the tree
        setLinkTransformations(model, child) 
Example #18
Source File: exporter.py    From cats-blender-plugin with MIT License 5 votes vote down vote up
def __xyzw_from_rotation_mode(mode):
        if mode == 'QUATERNION':
            return lambda xyzw: xyzw

        if mode == 'AXIS_ANGLE':
            def __xyzw_from_axis_angle(xyzw):
                q = mathutils.Quaternion(xyzw[:3], xyzw[3])
                return [q.x, q.y, q.z, q.w]
            return __xyzw_from_axis_angle

        def __xyzw_from_euler(xyzw):
            q = mathutils.Euler(xyzw[:3], xyzw[3]).to_quaternion()
            return [q.x, q.y, q.z, q.w]
        return __xyzw_from_euler 
Example #19
Source File: io_export_babylon.py    From BlenderExporter with Apache License 2.0 5 votes vote down vote up
def post_rotate_quaternion(quat, angle):
    post = mathutils.Euler((angle, 0.0, 0.0)).to_matrix()
    mqtn = quat.to_matrix()
    quat = (mqtn*post).to_quaternion()
    return quat 
Example #20
Source File: package_level.py    From BlenderExporter with Apache License 2.0 5 votes vote down vote up
def post_rotate_quaternion(quat, angle):
    post = Euler((angle, 0.0, 0.0)).to_matrix()
    mqtn = quat.to_matrix()
    quat = (mqtn*post).to_quaternion()
    return quat
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
Example #21
Source File: util_common.py    From building_tools with MIT License 5 votes vote down vote up
def local_xyz(face):
    """ Get local xyz directions
    """
    z = face.normal.copy()
    x = face.normal.copy()
    x.rotate(Euler((0.0, 0.0, radians(90)), "XYZ"))
    y = z.cross(x)
    return x, y, z 
Example #22
Source File: polygon_utils_cam.py    From blendercam with GNU General Public License v2.0 5 votes vote down vote up
def Circle(r, np):
    c = []
    pi = math.pi
    v = mathutils.Vector((r, 0, 0))
    e = mathutils.Euler((0, 0, 2.0 * pi / np))
    for a in range(0, np):
        c.append((v.x, v.y))
        v.rotate(e)

    p = spolygon.Polygon(c)
    return p 
Example #23
Source File: pack.py    From blendercam with GNU General Public License v2.0 5 votes vote down vote up
def srotate(s, r, x, y):
    ncoords = []
    e = mathutils.Euler((0, 0, r))
    for p in s.exterior.coords:
        v1 = Vector((p[0], p[1], 0))
        v2 = Vector((x, y, 0))
        v = v1 - v2
        v.rotate(e)
        ncoords.append((v[0], v[1]))

    return sgeometry.Polygon(ncoords) 
Example #24
Source File: cm_templates.py    From CrowdMaster with GNU General Public License v3.0 5 votes vote down vote up
def build(self, buildRequest):
        t = time.time()

        placePos = Vector(buildRequest.pos)
        diffRow = Vector((self.settings["ArrayRowMargin"], 0, 0))
        diffCol = Vector((0, self.settings["ArrayColumnMargin"], 0))
        diffRow.rotate(mathutils.Euler(buildRequest.rot))
        diffCol.rotate(mathutils.Euler(buildRequest.rot))
        diffRow *= buildRequest.scale
        diffCol *= buildRequest.scale
        number = self.settings["noToPlace"]
        rows = self.settings["ArrayRows"]

        cm_timings.placement["TemplateFORMATION"] += time.time() - t
        cm_timings.placementNum["TemplateFORMATION"] += 1

        for fullcols in range(number // rows):
            for row in range(rows):
                newBuildRequest = buildRequest.copy()
                newBuildRequest.pos = placePos + fullcols * diffCol + row * diffRow
                self.inputs["Template"].build(newBuildRequest)

        for leftOver in range(number % rows):
            newBuild = buildRequest.copy()
            newBuild.pos = placePos + \
                (number // rows) * diffCol + leftOver * diffRow
            self.inputs["Template"].build(newBuild) 
Example #25
Source File: render.py    From g-tensorflow-models with Apache License 2.0 5 votes vote down vote up
def roll_camera(obj_camera):
  roll_rotate = mathutils.Euler(
      (0, 0, random.random() * math.pi - math.pi * 0.5), 'XYZ')
  obj_camera.rotation_euler = (obj_camera.rotation_euler.to_matrix() *
      roll_rotate.to_matrix()).to_euler() 
Example #26
Source File: cm_pathChannels.py    From CrowdMaster with GNU General Public License v3.0 5 votes vote down vote up
def calcRelativeTarget(self, pathEntry, lookahead):
        context = bpy.context

        pathObject = pathEntry.objectName
        radius = pathEntry.radius
        laneSep = pathEntry.laneSeparation
        isDirectional = pathEntry.mode == "directional"
        revDirec = pathEntry.revDirec if isDirectional else None

        kd, bm, pathMatrixInverse, rotation = self.calcPathData(pathObject,
                                                                revDirec)

        vel = self.sim.agents[self.userid].globalVelocity * lookahead
        if vel.x == 0 and vel.y == 0 and vel.z == 0:
            vel = Vector((0, lookahead, 0))
            vel.rotate(bpy.context.scene.objects[self.userid].rotation_euler)
        vel = vel * rotation
        co_find = pathMatrixInverse * \
            context.scene.objects[self.userid].location
        co, index, dist = kd.find(co_find)
        offset = self.followPath(bm, co, index, vel, co_find, radius, laneSep,
                                 isDirectional, pathEntry)

        offset = offset * pathMatrixInverse

        eul = Euler(
            [-x for x in context.scene.objects[self.userid].rotation_euler], 'ZYX')
        offset.rotate(eul)

        return offset 
Example #27
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) 
Example #28
Source File: render.py    From models with Apache License 2.0 5 votes vote down vote up
def roll_camera(obj_camera):
  roll_rotate = mathutils.Euler(
      (0, 0, random.random() * math.pi - math.pi * 0.5), 'XYZ')
  obj_camera.rotation_euler = (obj_camera.rotation_euler.to_matrix() *
      roll_rotate.to_matrix()).to_euler() 
Example #29
Source File: bake_operators.py    From rigacar with GNU General Public License v3.0 5 votes vote down vote up
def evaluate(self, f):
        return mathutils.Euler(self.fcurves_evaluator.evaluate(f)).to_quaternion() 
Example #30
Source File: gltf2_animate.py    From verge3d-blender-addon with GNU General Public License v3.0 5 votes vote down vote up
def animate_convert_rotation_euler(euler, rotation_mode):
    """
    Converts an euler angle to a quaternion rotation.
    """
    rotation = mathutils.Euler((euler[0], euler[1], euler[2]), rotation_mode).to_quaternion()

    return [rotation.x, rotation.y, rotation.z, rotation.w]