• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python mathutils.Euler类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中mathutils.Euler的典型用法代码示例。如果您正苦于以下问题:Python Euler类的具体用法?Python Euler怎么用?Python Euler使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Euler类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: add_object_align_init

def add_object_align_init(context, operator):
    """
    Return a matrix using the operator settings and view context.

    :arg context: The context to use.
    :type context: :class:`bpy.types.Context`
    :arg operator: The operator, checked for location and rotation properties.
    :type operator: :class:`bpy.types.Operator`
    :return: the matrix from the context and settings.
    :rtype: :class:`mathutils.Matrix`
    """

    from mathutils import Matrix, Vector, Euler
    properties = operator.properties if operator is not None else None

    space_data = context.space_data
    if space_data and space_data.type != 'VIEW_3D':
        space_data = None

    # location
    if operator and properties.is_property_set("location"):
        location = Matrix.Translation(Vector(properties.location))
    else:
        location = Matrix.Translation(context.scene.cursor.location)

        if operator:
            properties.location = location.to_translation()

    # rotation
    view_align = (context.preferences.edit.object_align == 'VIEW')
    view_align_force = False
    if operator:
        if properties.is_property_set("view_align"):
            view_align = view_align_force = operator.view_align
        else:
            if properties.is_property_set("rotation"):
                # ugh, 'view_align' callback resets
                value = properties.rotation[:]
                properties.view_align = view_align
                properties.rotation = value
                del value
            else:
                properties.view_align = view_align

    if operator and (properties.is_property_set("rotation") and
                     not view_align_force):

        rotation = Euler(properties.rotation).to_matrix().to_4x4()
    else:
        if view_align and space_data:
            rotation = space_data.region_3d.view_matrix.to_3x3().inverted()
            rotation.resize_4x4()
        else:
            rotation = Matrix()

        # set the operator properties
        if operator:
            properties.rotation = rotation.to_euler()

    return location @ rotation
开发者ID:wangyxuan,项目名称:blender,代码行数:60,代码来源:object_utils.py


示例2: obj_orientation

def obj_orientation(obj, alpha, beta, gamma):
    '''Set obj orientation, angle in degrees'''
    alpha = alpha*pi/180
    beta = beta*pi/180
    gamma = gamma*pi/180
    rot_in_euler = Euler([alpha, beta, gamma])
    obj.worldOrientation = rot_in_euler.to_matrix()
开发者ID:Blender-Brussels,项目名称:bpy-bge-library,代码行数:7,代码来源:work_with_data.py


示例3: __getAxisAngleBasedRotation

    def __getAxisAngleBasedRotation(self, rotate, translate):

        euler = Euler(rotate)

        self.logger.debug("Injecting rotation: '%s'", str(euler))

        vector_translate = Vector((translate[0], translate[1], translate[2]))

        # actually the translation is also needed to be passed here
        rotate_mtx = Matrix.to_4x4(euler.to_matrix())
        translate_mtx = Matrix.Translation(vector_translate)

        cameraMatrix = translate_mtx * rotate_mtx

        # global matrix rotate (guess it is for world coordinate system rotating)

        mtx = Matrix.Rotation(-(math.pi / 2.0), 4, 'X')
        mtx = mtx * cameraMatrix

        (loc, quat, _) = mtx.decompose()

        # get the values the way that in x3d exporter does
        quat = quat.normalized()

        # some weird stuff
        axises = list(quat.axis.to_tuple())
        angle = quat.angle

        orientation = self.__getStringRepresentation(axises) + " " + str(angle)
        translation = self.__getStringRepresentation(loc)

        return translation, orientation
开发者ID:Dzess,项目名称:ALFIRT,代码行数:32,代码来源:SceneInjecterX3D.py


示例4: getTransformFromParent

    def getTransformFromParent(self):
        rot = Euler((radians(self.alpha.value), radians(self.beta.value),
                     radians(self.gamma.value)), 'XYZ').to_matrix()
        rot.resize_4x4()

        transl = Matrix.Translation((self.x.value, self.y.value, self.z.value))
        # print("here",transl * rot)
        return transl * rot
开发者ID:HBPNeurorobotics,项目名称:BlenderRobotDesigner,代码行数:8,代码来源:segments.py


示例5: mapping_node_order_flip

def mapping_node_order_flip(orientation):
    """
    Flip euler order of mapping shader node
    see: Blender #a1ffb49
    """
    rot = Euler(orientation)
    rot.order = 'ZYX'
    quat = rot.to_quaternion()
    return quat.to_euler('XYZ')
开发者ID:laocan,项目名称:Panorama-Tracker,代码行数:9,代码来源:core.py


示例6: process

    def process(self):
        if not self.outputs['Quaternions'].is_linked:
            return

        inputs = self.inputs

        quaternionList = []

        if self.mode == "WXYZ":
            I = [inputs[n].sv_get()[0] for n in "WXYZ"]
            params = match_long_repeat(I)
            for wxyz in zip(*params):
                q = Quaternion(wxyz)
                if self.normalize:
                    q.normalize()
                quaternionList.append(q)

        elif self.mode == "SCALARVECTOR":
            I = [inputs[n].sv_get()[0] for n in ["Scalar", "Vector"]]
            params = match_long_repeat(I)
            for scalar, vector in zip(*params):
                q = Quaternion([scalar, *vector])
                if self.normalize:
                    q.normalize()
                quaternionList.append(q)

        elif self.mode == "EULER":
            I = [inputs["Angle " + n].sv_get()[0] for n in "XYZ"]
            params = match_long_repeat(I)
            au = angleConversion[self.angleUnits]
            for angleX, angleY, angleZ in zip(*params):
                euler = Euler((angleX * au, angleY * au, angleZ * au), self.eulerOrder)
                q = euler.to_quaternion()
                if self.normalize:
                    q.normalize()
                quaternionList.append(q)

        elif self.mode == "AXISANGLE":
            I = [inputs[n].sv_get()[0] for n in ["Axis", "Angle"]]
            params = match_long_repeat(I)
            au = angleConversion[self.angleUnits]
            for axis, angle in zip(*params):
                q = Quaternion(axis, angle * au)
                if self.normalize:
                    q.normalize()
                quaternionList.append(q)

        elif self.mode == "MATRIX":
            input_M = inputs["Matrix"].sv_get(default=idMat)
            for m in input_M:
                q = Matrix(m).to_quaternion()
                if self.normalize:
                    q.normalize()
                quaternionList.append(q)

        self.outputs['Quaternions'].sv_set([quaternionList])
开发者ID:nortikin,项目名称:sverchok,代码行数:56,代码来源:quaternion_in.py


示例7: eval_planet_rotation

def eval_planet_rotation(scn_name, obj_name, index=None, time=None):
    """Evaluate the planets rotation, used by driver.

    scn_name = Name of a scene which contains the object
    obj_name = Name of the object to simulate
    index = index of the rotation channel,
            usually only z-axis (index=2) changes
    time = time when to calculate, if not given use current scene time
            time is in seconds of the simulation
    returns an Euler in mode ZYX or, if index given, an angle in radians
    """
    scn = bpy.data.scenes.get(scn_name)
    obj = bpy.data.objects.get(obj_name)
    if not obj or not scn:
        errmsg = "DRIVER ERROR: Invalid obj_name ({}) or scn_name ({})"
        print(errmsg.format(obj_name, scn_name))
        return 0

    simscn = scn.sssim_scn
    simrot = obj.sssim_rotation

    # time = time in seconds, if None use current scene time
    if time is None:
        time = simscn.time

    # rotation_period is also in seconds
    rotation_period = simrot.rotation_period
    if rotation_period != 0:
        rot_z = 2 * pi * time / rotation_period
    else:
        # invalid input -> no rotation
        rot_z = 0

    tilt = simrot.axis_tilt
    planet_rot = Euler((tilt, 0.0, 0.0), 'ZYX')  # note that mode is 'ZYX'

    # rotate around global (not local) z-axis
    direction = simrot.axis_direction
    planet_rot.rotate(Euler((0.0, 0.0, direction), 'XYZ'))

    # rotate around local z-axis
    # NOTE: we won't use planet_rot.rotate_axis('Z', rot_z) because then
    # all rotations are between -180 and 180 and for the rotation around
    # z we need a continous motion with increasing z values
    planet_rot.z += rot_z

    if simrot.relative_to_orbit and obj.sssim_obj.object_type == 'PLANET':
        planet_rot = orbit_rotate(planet_rot, obj.sssim_orbit)

    if index is None:
        return planet_rot
    else:
        return planet_rot[index]
开发者ID:IBaaNB,项目名称:blenderpython,代码行数:53,代码来源:calculation.py


示例8: main

			def main(_self, entity_object, plugin_data):               
				# Restore Euler structure
				new_orientation = [0, 0, 0]
				for value in plugin_data:
					new_orientation[value[1]] = value[0]
				euler_orientation = Euler(new_orientation)
				
				# Interpolate between data and use for extrapolation
				interpolator = setdefaultdict(entity_object, "interpolate_orientation", interpolate([entity_object.worldOrientation.to_quaternion(), 0.0]))     
				orientation = [euler_orientation.to_quaternion(), time.time()]
				interpolator.update(orientation)            
					
				entity_object.worldOrientation = euler_orientation.to_matrix()
开发者ID:nader92011,项目名称:zdotfiles,代码行数:13,代码来源:plugins.py


示例9: draw_cloud

def draw_cloud(bm, prefs, translation=(0, 0, 0)):
    mat = Matrix()
    mat.translation = translation
    smin = prefs.lp_Cloud_Scale_Min
    smax = prefs.lp_Cloud_Scale_Max
    sx = uniform(smin[0], smax[0])
    sy = uniform(smin[1], smax[1])
    sz = uniform(smin[2], smax[2])
    scale = (sx, sy, sz)
    mat[0][0], mat[1][1], mat[2][2] = scale[0], scale[1], scale[2]
    e = Euler((uniform(0, 3.14), uniform(0, 3.14), uniform(0, 3.14)), 'XYZ')
    mat = mat * e.to_matrix().to_4x4()
    bmesh.ops.create_icosphere(bm, subdivisions=prefs.lp_Cloud_Subdivisions,
                               diameter=1.0, matrix=mat)
    return scale
开发者ID:luboslenco,项目名称:lowpolyfactory,代码行数:15,代码来源:createCloudObject.py


示例10: draw_arc12

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()
开发者ID:BitByte01,项目名称:myblendercontrib,代码行数:19,代码来源:va_gl.py


示例11: rotation

	def rotation(self, xyz):
		if len(xyz) != 3: utils.debug("Rotation assignment failed on " + self.obj.name + " object. xyz size != 3.")
		if isinstance(xyz, (list, tuple)) or len(xyz) == 3:
			xyz = Euler(xyz, 'XYZ')
		srt = self.obj.localOrientation.copy()
		xyz = xyz.to_matrix()
			
		for obj in self.transformable:
			if obj.__class__.__name__ == "KX_GameObject":
				if obj == self.obj: obj.localOrientation = xyz
				else:
					srr = obj.worldOrientation.copy()
					srr.rotate(xyz)
					srr = srr.to_euler()
					obj.localOrientation = srr
			else:
				srr = obj.rotation.copy()
				srr.rotate(xyz)
				obj.localOrientation = srr
				obj.rotation = srr
		self._rotation = self.ProxyRotation()
开发者ID:Hubber116sx,项目名称:BGECore,代码行数:21,代码来源:widget.py


示例12: createSceneFromXML

def createSceneFromXML(scene_file):
    # parse xml
    sceneTree = ET.parse(scene_file)
    root = sceneTree.getroot()
    # traverse scene xml
    materialStack.append(createDefaultMaterial())
    transformStack.append(Matrix.Identity(4))
    rootObject = createObjectFromXML(root, root[0], './sceneRoot', None, True)
    # create coordinate conversion root
    sceneObject = bpy.data.objects.new('JReality Scene', None)
    jrealityToBlender = Euler((math.pi/2, 0.0, math.pi/2), 'XYZ')
    sceneObject.matrix_local = jrealityToBlender.to_matrix().to_4x4()
    bpy.context.scene.objects.link(sceneObject)
    rootObject.parent = sceneObject;
    # find active camera
    cameraPath = root.find("scenePaths/path[@name='cameraPath']")
    if cameraPath != None:
        cameraPathXpath = resolveReferencePath(root, cameraPath, "./scenePaths/path[@name='cameraPath']")
        cameraPath = resolveReference(root, cameraPath, "./scenePaths/path[@name='cameraPath']")
        node = cameraPath.find('node[last()]')
        camTag = resolveReference(root, node, cameraPathXpath + "/node[last()]")
        bpy.context.scene.camera = tagToObject[camTag]
    else:
        print('WARNING: no camera path set')
开发者ID:sechel,项目名称:jreality,代码行数:24,代码来源:renderer.py


示例13: __init__

 def __init__(self, name, root, length, chord, incidence, twist, taper, sweep, dihedral):
     
     # transform angles to rad
     sweep *= DEG2RAD
     twist *= DEG2RAD
     
     dihedral *= DEG2RAD
     incidence *=DEG2RAD
     
     # find out if it's a symetric element
     self.is_symetric = not name.startswith("YASim_vstab")
     
     # create the wing mesh object
     # the wing is first created at ORIGIN w/o incidence/dihedral
     
     base = ORIGIN
     basefore = ORIGIN + 0.5 * chord * X
     baseaft = ORIGIN - 0.5 * chord * X
     
     tip = ORIGIN + (math.cos(sweep) * length * Y) - (math.sin(sweep) * length * X)
     
     tipfore = tip + (0.5 * taper * chord * math.cos(twist) * X) + (0.5 * taper * chord * math.sin(twist) * Z)
     tipaft = tip + tip - tipfore
     #  <1--0--2
     #   \  |  /
     #    4-3-5
     wing_obj = mesh_create(name, ORIGIN, [base, basefore, baseaft, tip, tipfore, tipaft], [], 
                             [(0, 1, 4, 3), (2, 0, 3, 5)])
     
     # now transform the mesh
     # set the created object active !!!!!!!
     bpy.context.scene.objects.active = wing_obj
     # get the active mesh
     mesh = bpy.context.object.data
     
     # create a rotation matrix, for dihedral and incidence rotation
     e = Euler((dihedral, -incidence, 0))
     m1 = e.to_matrix()
     m = m1.to_4x4()
     
     # rotate it
     mesh.transform(m)
     
     mesh.update()
     
     # position the object
     #wing_obj.location = root
     # use the matrix to position it
     wing_obj.matrix_world = Matrix.Translation(root)
     
     # assign materials
     if self.is_symetric:
         Item.set_material('tgreen-1', (0.0,0.5,0.0), 0.5)
         
         Symetric.list_append(wing_obj)
     
     else:
         Item.set_material('tred-1', (0.5,0.0,0.0), 0.5)
     
     # write out the vars for the flaps
     self.baseaft = baseaft
     self.tipaft = tipaft
     self.base = base
     self.wing_obj = wing_obj
     self.mesh_matrix = m
开发者ID:alexeijd,项目名称:simple_yasim_import-git,代码行数:65,代码来源:simple_yasim_import.py


示例14: bvh_node_dict2armature


#.........这里部分代码省略.........

    # Create a shared time axis for all animation curves.
    time = [float(frame_start)] * num_frame
    dt = 0.0
    if use_fps_scale:
        dt = scene.render.fps * bvh_frame_time
        for frame_i in range(1, num_frame):
            time[frame_i] += float(frame_i) * dt
    else:
        sub_frame_step = 1
        for frame_i in range(1, num_frame):
            time[frame_i] += float(frame_i)

    frange = range(0, num_frame, sub_frame_step)
    print("bvh_frame_time = %f, dt = %f, num_frame = %d"
          % (bvh_frame_time, dt, num_frame))

    for i, bvh_node in enumerate(bvh_nodes_list):
        pose_bone, bone_rest_matrix, bone_rest_matrix_inv = bvh_node.temp

        #print("FRANGE:", frange)
        if bvh_node.has_loc:
            # Not sure if there is a way to query this or access it in the
            # PoseBone structure.
            if (pose_bone.parent is None and only_rootbone_location) or not only_rootbone_location:
                data_path = 'pose.bones["%s"].location' % pose_bone.name

                location = [(0.0, 0.0, 0.0)] * num_frame
                for frame_i in range(0, num_frame):
                    bvh_loc = bvh_node.anim_data[frame_i + skip_frame][:3]

                    bone_translate_matrix = Matrix.Translation(
                            Vector(bvh_loc) - bvh_node.rest_head_local)
                    location[frame_i] = (bone_rest_matrix_inv *
                                         bone_translate_matrix).to_translation()

                # For each location x, y, z.
                for axis_i in range(3):
                    curve = action.fcurves.new(data_path=data_path, index=axis_i)
                    keyframe_points = curve.keyframe_points
                    keyframe_points.add(len(frange))

                    for i, frame_i in enumerate(frange):
                        keyframe_points[i].co = \
                                (time[frame_i], location[frame_i][axis_i])

        if bvh_node.has_rot:
            data_path = None
            rotate = None

            if 'QUATERNION' == rotate_mode:
                rotate = [(1.0, 0.0, 0.0, 0.0)] * num_frame
                data_path = ('pose.bones["%s"].rotation_quaternion'
                             % pose_bone.name)
            else:
                rotate = [(0.0, 0.0, 0.0)] * num_frame
                data_path = ('pose.bones["%s"].rotation_euler' %
                             pose_bone.name)

            prev_euler = Euler((0.0, 0.0, 0.0))
            for frame_i in range(0, num_frame):
                bvh_rot = bvh_node.anim_data[frame_i + skip_frame][3:]

                # apply rotation order and convert to XYZ
                # note that the rot_order_str is reversed.
                euler = Euler(bvh_rot, bvh_node.rot_order_str[::-1])
                bone_rotation_matrix = euler.to_matrix().to_4x4()
                bone_rotation_matrix = (bone_rest_matrix_inv *
                                        bone_rotation_matrix *
                                        bone_rest_matrix)

                if 4 == len(rotate[frame_i]):
                    rotate[frame_i] = bone_rotation_matrix.to_quaternion()
                else:
                    rotate[frame_i] = bone_rotation_matrix.to_euler(
                            pose_bone.rotation_mode, prev_euler)
                    prev_euler = rotate[frame_i]

            # For each Euler angle x, y, z (or Quaternion w, x, y, z).
            for axis_i in range(len(rotate[0])):
                curve = action.fcurves.new(data_path=data_path, index=axis_i)
                keyframe_points = curve.keyframe_points
                keyframe_points.add(len(frange))

                for i, frame_i in enumerate(frange):
                    keyframe_points[i].co = \
                            (time[frame_i], rotate[frame_i][axis_i])

    for cu in action.fcurves:
        if IMPORT_LOOP:
            pass  # 2.5 doenst have cyclic now?

        for bez in cu.keyframe_points:
            bez.interpolation = 'LINEAR'

    # finally apply matrix
    arm_ob.matrix_world = global_matrix
    bpy.ops.object.transform_apply(rotation=True)

    return arm_ob
开发者ID:Italic-,项目名称:blenderpython,代码行数:101,代码来源:import_bvh.py


示例15: poll

import bge
import time
from rift import PyRift
from mathutils import Quaternion, Euler, Vector

# Functions
def poll():
    bge.logic.rift.pollSensor()
    bge.logic.rotation = Quaternion((bge.logic.rift.headPose[3], bge.logic.rift.headPose[4], bge.logic.rift.headPose[5], bge.logic.rift.headPose[6]))
    bge.logic.position = Vector((bge.logic.rift.headPose[0],bge.logic.rift.headPose[1],bge.logic.rift.headPose[2]))

# Main
try:
    eu = bge.logic.rotation.to_euler()
    fix = Euler((-1.57, 0, 0), 'XYZ')
    rot = Euler((-eu.z, eu.y, -eu.x), 'XYZ')
    rot.rotate(fix)
    
    bge.logic.prev_orientation = rot;
    poll()
    
except:
    bge.logic.rift = PyRift()
    bge.logic.rift.connect()
            
    scene_e = bge.logic.getCurrentScene()
    cam_e = scene_e.active_camera
    bge.logic.init_position = Vector((cam_e.localPosition[0],cam_e.localPosition[1],cam_e.localPosition[2]))
    bge.logic.init_orientation = cam_e.localOrientation.to_euler() 

    eu = Euler()
开发者ID:hjeldin,项目名称:OculusBlend,代码行数:31,代码来源:rift_controller.py


示例16: read_chan

def read_chan(context, filepath, z_up, rot_ord, sensor_width, sensor_height):

    # get the active object
    scene = context.scene
    obj = context.active_object
    camera = obj.data if obj.type == 'CAMERA' else None

    # prepare the correcting matrix
    rot_mat = Matrix.Rotation(radians(90.0), 4, 'X').to_4x4()

    # read the file
    filehandle = open(filepath, 'r')

    # iterate throug the files lines
    for line in filehandle:
        # reset the target objects matrix
        # (the one from whitch one we'll extract the final transforms)
        m_trans_mat = Matrix()

        # strip the line
        data = line.split()

        # test if the line is not commented out
        if data and not data[0].startswith("#"):

            # set the frame number basing on the chan file
            scene.frame_set(int(data[0]))

            # read the translation values from the first three columns of line
            v_transl = Vector((float(data[1]),
                               float(data[2]),
                               float(data[3])))
            translation_mat = Matrix.Translation(v_transl)
            translation_mat.to_4x4()

            # read the rotations, and set the rotation order basing on the
            # order set during the export (it's not being saved in the chan
            # file you have to keep it noted somewhere
            # the actual objects rotation order doesn't matter since the
            # rotations are being extracted from the matrix afterwards
            e_rot = Euler((radians(float(data[4])),
                           radians(float(data[5])),
                           radians(float(data[6]))))
            e_rot.order = rot_ord
            mrot_mat = e_rot.to_matrix()
            mrot_mat.resize_4x4()

            # merge the rotation and translation
            m_trans_mat = translation_mat * mrot_mat

            # correct the world space
            # (nuke's and blenders scene spaces are different)
            if z_up:
                m_trans_mat = rot_mat * m_trans_mat

            # break the matrix into a set of the coordinates
            trns = m_trans_mat.decompose()

            # set the location and the location's keyframe
            obj.location = trns[0]
            obj.keyframe_insert("location")

            # convert the rotation to euler angles (or not)
            # basing on the objects rotation mode
            if obj.rotation_mode == 'QUATERNION':
                obj.rotation_quaternion = trns[1]
                obj.keyframe_insert("rotation_quaternion")
            elif obj.rotation_mode == 'AXIS_ANGLE':
                tmp_rot = trns[1].to_axis_angle()
                obj.rotation_axis_angle = (tmp_rot[1], *tmp_rot[0])
                obj.keyframe_insert("rotation_axis_angle")
                del tmp_rot
            else:
                obj.rotation_euler = trns[1].to_euler(obj.rotation_mode)
                obj.keyframe_insert("rotation_euler")

            # check if the object is camera and fov data is present
            if camera and len(data) > 7:
                camera.sensor_fit = 'HORIZONTAL'
                camera.sensor_width = sensor_width
                camera.sensor_height = sensor_height
                camera.angle_y = radians(float(data[7]))
                camera.keyframe_insert("lens")
    filehandle.close()

    return {'FINISHED'}
开发者ID:Dancovich,项目名称:blender-addons-fork,代码行数:86,代码来源:import_nuke_chan.py


示例17: get_top_mesh

def get_top_mesh(context, prefs):
    me = context.blend_data.meshes.new("temp_mesh")
    bm = bmesh.new()
    bm.from_mesh(me)
    mat = Matrix()
    tt = prefs.lp_Tree_Type

    if tt == "lp_Tree_Oak":
        mat.translation = (0, 0, prefs.trunk_depth)
        tsmin = prefs.lp_Tree_Top_Scale_Min
        tsmax = prefs.lp_Tree_Top_Scale_Max
        mat[0][0], mat[1][1], mat[2][2] = (
            uniform(tsmin[0], tsmax[0]),
            uniform(tsmin[1], tsmax[1]),
            uniform(tsmin[2], tsmax[2]),
        )
        bmesh.ops.create_icosphere(bm, subdivisions=prefs.lp_Tree_Top_Subdivisions, diameter=1.0, matrix=mat)
    elif tt == "lp_Tree_Pine":
        segments = get_random(prefs.lp_Tree_Top_Stage_Segments_Min, prefs.lp_Tree_Top_Stage_Segments_Max)
        stages = get_random(prefs.lp_Tree_Top_Stages_Min, prefs.lp_Tree_Top_Stages_Max)
        td = prefs.trunk_depth - 0.7
        sstep = uniform(prefs.lp_Tree_Top_Stage_Step_Min, prefs.lp_Tree_Top_Stage_Step_Max)
        ssmin = prefs.lp_Tree_Top_Stage_Size_Min
        ssmax = prefs.lp_Tree_Top_Stage_Size_Max
        ssize = (uniform(ssmin[0], ssmax[0]), uniform(ssmin[1], ssmax[1]), uniform(ssmin[2], ssmax[2]))
        for i in range(0, stages):
            mult = prefs.lp_Tree_Top_Stage_Shrink_Multiplier * (i / 4)
            sc = (1 - i * prefs.lp_Tree_Top_Stage_Shrink * mult) * 0.9
            if sc < 0.01:
                sc = 0.01
            mat[0][0], mat[1][1], mat[2][2] = (sc * ssize[0], sc * ssize[1], sc * ssize[2])
            mat.translation = (0, 0, (td + ((ssize[2] - 1) / 2) + i * sstep) * 0.85)
            if prefs.lp_Tree_Top_Rotate_Stages:
                e = Euler((0, 0, uniform(0, 3.14)), "XYZ")
                mat = mat * e.to_matrix().to_4x4()
            bmesh.ops.create_cone(
                bm,
                cap_ends=True,
                cap_tris=True,
                segments=segments,
                diameter1=(prefs.lp_Tree_Top_Stage_Diameter),
                diameter2=0,
                depth=(0.85),
                matrix=mat,
            )
            mat = Matrix()
    elif tt == "lp_Tree_Palm":
        trunk_length = prefs.palm_stage_length * prefs.palm_stages
        leaf_length = get_random(prefs.lp_Tree_Palm_Top_Leaf_Length_Min, prefs.lp_Tree_Palm_Top_Leaf_Length_Max)
        leaf_size = uniform(prefs.lp_Tree_Palm_Top_Leaf_Size_Min, prefs.lp_Tree_Palm_Top_Leaf_Size_Max)

        mat.translation = (0, 0, trunk_length)
        leaves = get_random(prefs.lp_Tree_Palm_Top_Leaves_Min, prefs.lp_Tree_Palm_Top_Leaves_Max)
        bmesh.ops.create_cone(
            bm,
            cap_ends=True,
            cap_tris=True,
            segments=leaves,
            diameter1=leaf_size,
            diameter2=leaf_size,
            depth=0.1,
            matrix=mat,
        )
        faces = bm.faces[:]
        for face in faces:
            nor = face.normal  # Asume normalized normal
            dir = (nor.x * 0.3, nor.y * 0.3, -0.12)
            if nor.z == 0:
                for i in range(0, leaf_length):
                    r = bmesh.ops.extrude_discrete_faces(bm, faces=[face])
                    bmesh.ops.translate(bm, vec=dir, verts=r["faces"][0].verts)
                    face = r["faces"][0]
                    dir = (dir[0], dir[1], dir[2] - 0.08)
                # Align last face verts
                mid = [0, 0, 0]
                for v in face.verts:
                    mid[0] += v.co.x
                    mid[1] += v.co.y
                    mid[2] += v.co.z
                mid[0] /= len(face.verts)
                mid[1] /= len(face.verts)
                mid[2] /= len(face.verts)
                for v in face.verts:
                    v.co.x, v.co.y, v.co.z = mid[0], mid[1], mid[2]

    bm.to_mesh(me)
    return me
开发者ID:meta-androcto,项目名称:blenderpython,代码行数:87,代码来源:createTreeObject.py


示例18: _get_bone_channels

def _get_bone_channels(bone_list, action, export_scale):
    """Takes a bone list and action and returns bone channels.
    bone_channels structure example:
    [("Bone", [("_TIME", [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]), ("_MATRIX", [])])]"""
    bone_channels = []
    frame_start = action.frame_range[0]
    frame_end = action.frame_range[1]
    total_time = action.scs_props.action_length
    anim_export_step = action.scs_props.anim_export_step
    total_frames = (frame_end - frame_start) / anim_export_step
    # print(' -- action: %r' % str(action))
    for bone in bone_list:
        # print(' oo bone: %r' % str(bone))
        if bone:
            # print(' -- bone_name: %r' % bone.name)
            bone_name = bone.name
            bone_rest_mat = bone.matrix_local
            if bone.parent:
                parent_bone_rest_mat = Matrix.Scale(export_scale, 4) * _convert_utils.scs_to_blend_matrix().inverted() * bone.parent.matrix_local
            else:
                parent_bone_rest_mat = Matrix()
            for group in action.groups:
                if group.name == bone_name:
                    # print(' -- group: %r' % str(group))

                    # GET CHANELS' CURVES
                    loc_curves = {}
                    euler_rot_curves = {}
                    quat_rot_curves = {}
                    sca_curves = {}
                    rot_mode = ''
                    for channel in group.channels:
                        data_path = channel.data_path
                        array_index = channel.array_index
                        # channel_start = channel.range()[0]
                        # channel_end = channel.range()[1]
                        # print('      channel: %r (%s) [%s - %s]' % (data_path, array_index, channel_start, channel_end))
                        if data_path.endswith("location"):
                            loc_curves[array_index] = channel
                        elif data_path.endswith("rotation_euler"):
                            euler_rot_curves[array_index] = channel
                            rot_mode = 'euler'
                        elif data_path.endswith("rotation_quaternion"):
                            quat_rot_curves[array_index] = channel
                            rot_mode = 'quat'
                        elif data_path.endswith("scale"):
                            sca_curves[array_index] = channel

                    # GO THOUGH FRAMES
                    actual_frame = frame_start
                    timings_stream = []
                    matrices_stream = []
                    while actual_frame <= frame_end:
                        mat_loc = Matrix()
                        mat_rot = Matrix()
                        mat_sca = Matrix()

                        # LOCATION MATRIX
                        if len(loc_curves) > 0:
                            location = Vector()
                            for index in range(3):
                                if index in loc_curves:
                                    location[index] = loc_curves[index].evaluate(actual_frame)
                            mat_loc = Matrix.Translation(location)

                        # ROTATION MATRIX
                        if rot_mode == 'euler' and len(euler_rot_curves) > 0:
                            rotation = Euler()
                            for index in range(3):
                                if index in euler_rot_curves:
                                    rotation[index] = euler_rot_curves[index].evaluate(actual_frame)
                            mat_rot = Euler(rotation, 'XYZ').to_matrix().to_4x4()  # TODO: Solve the other rotation modes.
                        if rot_mode == 'quat' and len(quat_rot_curves) > 0:
                            rotation = Quaternion()
                            for index in range(4):
                                if index in quat_rot_curves:
                                    rotation[index] = quat_rot_curves[index].evaluate(actual_frame)
                            mat_rot = rotation.to_matrix().to_4x4()

                        # SCALE MATRIX
                        if len(sca_curves) > 0:
                            scale = Vector((1.0, 1.0, 1.0))
                            for index in range(3):
                                if index in sca_curves:
                                    scale[index] = sca_curves[index].evaluate(actual_frame)
                            mat_sca = Matrix()
                            mat_sca[0] = (scale[0], 0, 0, 0)
                            mat_sca[1] = (0, scale[2], 0, 0)
                            mat_sca[2] = (0, 0, scale[1], 0)
                            mat_sca[3] = (0, 0, 0, 1)

                        # BLENDER FRAME MATRIX
                        mat = mat_loc * mat_rot * mat_sca

                        # SCALE REMOVAL MATRIX
                        rest_location, rest_rotation, rest_scale = bone_rest_mat.decompose()
                        # print(' BONES rest_scale: %s' % str(rest_scale))
                        rest_scale = rest_scale * export_scale
                        scale_removal_matrix = Matrix()
                        scale_removal_matrix[0] = (1.0 / rest_scale[0], 0, 0, 0)
#.........这里部分代码省略.........
开发者ID:bbigii,项目名称:BlenderTools,代码行数:101,代码来源:pia.py


示例19: _get_bone_channels

def _get_bone_channels(scs_root_obj, armature, scs_animation, action, export_scale):
    """Takes armature and action and returns bone channels.
    bone_channels structure example:
    [("Bone", [("_TIME", [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]), ("_MATRIX", [])])]"""
    bone_channels = []
    frame_start = scs_animation.anim_start
    frame_end = scs_animation.anim_end
    anim_export_step = action.scs_props.anim_export_step
    total_frames = (frame_end - frame_start) / anim_export_step

    # armature matrix stores transformation of armature object against scs root
    # and has to be added to all bones as they only armature space transformations
    armature_mat = scs_root_obj.matrix_world.inverted() * armature.matrix_world

    invalid_data = False  # flag to indicate invalid data state
    curves_per_bone = {}  # store all the curves we are interested in per bone names

    for bone in armature.data.bones:
        for fcurve in action.fcurves:

            # check if curve belongs to bone
            if '["' + bone.name + '"]' in fcurve.data_path:

                data_path = fcurve.data_path
                array_index = fcurve.array_index

                if data_path.endswith("location"):
                    curve_type = "location"
                elif data_path.endswith("rotation_euler"):
                    curve_type = "euler_rotation"
                elif data_path.endswith("rotation_quaternion"):
                    curve_type = "quat_rotation"
                elif data_path.endswith("scale"):
                    curve_type = "scale"
                else:
                    curve_type = None

                # write only recognized curves
                if curve_type is not None:
                    if bone.name not in curves_per_bone:
                        curves_per_bone[bone.name] = {
                            "location": {},
                            "euler_rotation": {},
                            "quat_rotation": {},
                            "scale": {}
                        }

                    curves_per_bone[bone.name][curve_type][array_index] = fcurve

    for bone_name, bone_curves in curves_per_bone.items():

        bone = armature.data.bones[bone_name]
        pose_bone = armature.pose.bones[bone_name]
        loc_curves = bone_curves["location"]
        euler_rot_curves = bone_curves["euler_rotation"]
        quat_rot_curves = bone_curves["quat_rotation"]
        sca_curves = bone_curves["scale"]

        bone_rest_mat = armature_mat * bone.matrix_local
        if bone.parent:
            parent_bone_rest_mat = (Matrix.Scale(export_scale, 4) * _convert_utils.scs_to_blend_matrix().inverted() *
                                    armature_mat * bone.parent.matrix_local)
        else:
            parent_bone_rest_mat = Matrix()

        # GO THOUGH FRAMES
        actual_frame = frame_start
        timings_stream = []
        matrices_stream = []
        while actual_frame <= frame_end:
            mat_loc = Matrix()
            mat_rot = Matrix()
            mat_sca = Matrix()

            # LOCATION MATRIX
            if len(loc_curves) > 0:
                location = Vector()
                for index in range(3):
                    if index in loc_curves:
                        location[index] = loc_curves[index].evaluate(actual_frame)
                mat_loc = Matrix.Translation(location)

            # ROTATION MATRIX
            if len(euler_rot_curves) > 0:
                rotation = Euler()
                for index in range(3):
                    if index in euler_rot_curves:
                        rotation[index] = euler_rot_curves[index].evaluate(actual_frame)
                mat_rot = Euler(rotation, pose_bone.rotation_mode).to_matrix().to_4x4()  # calc rotation by pose rotation mode

            elif len(quat_rot_curves) > 0:
                rotation = Quaternion()
                for index in range(4):
                    if index in quat_rot_curves:
                        rotation[index] = quat_rot_curves[index].evaluate(actual_frame)
                mat_rot = rotation.to_matrix().to_4x4()

            # SCALE MATRIX
            if len(sca_curves) > 0:
                scale = Vector((1.0, 1.0, 1.0))
#.........这里部分代码省略.........
开发者ID:P-casper1,项目名称:BlenderTools,代码行数:101,代码来源:pia.py


示例20: bvh_node_dict2armature


#. 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python mathutils.Matrix类代码示例发布时间:2022-05-27
下一篇:
Python mathtools.norm函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap