Example #1
0
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]
Example #2
0
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]
    def getOculusOri(self):
        self.pyrift.poll()

        oculus_ori = Quaternion(
            (self.pyrift.rotation[0], self.pyrift.rotation[1],
             self.pyrift.rotation[2], self.pyrift.rotation[3]))

        eu = oculus_ori.to_euler()
        eu = oculus_ori.to_euler()

        fix = Euler((-math.pi / 2, 0., math.pi / 2), 'XYZ')
        ori = Euler((-eu.z, eu.y, -eu.x), 'XYZ')
        ori.rotate(fix)

        return ori
Example #4
0
    def execute(self, context):
        with open(self.filepath, 'r') as f:
            lines = f.readlines()

        if 'Sockets' not in bpy.data.collections:
            sockets = bpy.data.collections.new('Sockets')
        else:
            sockets = bpy.data.collections['Sockets']

        if 'Sockets' not in context.scene.collection.children:
            context.scene.collection.children.link(sockets)

        set_active_collection('Sockets')

        for i, line in enumerate(lines):
            match = socket_regex.match(line.strip())
            if match:
                rotator_match = rotator_regex.match(lines[i + 1])

                mesh_name = match.group('mesh')
                bone_name = match.group('bone')
                tag = match.group('tag')
                x = float(match.group('x'))
                y = float(match.group('y'))
                z = float(match.group('z'))

                mesh = context.scene.objects[mesh_name + '.ao']
                bone = mesh.data.bones[bone_name]
                socket_location = mesh.location + bone.head_local + Vector(
                    (x, -y, z))

                pitch = rotator_to_deg(float(rotator_match.group('pitch')))
                yaw = rotator_to_deg(float(rotator_match.group('yaw')))
                roll = rotator_to_deg(float(rotator_match.group('roll')))
                rotation = Euler((roll, -pitch, yaw), 'XYZ')

                rotation.rotate(mesh.rotation_euler)
                rotation.rotate(bone.matrix)

                bpy.ops.object.empty_add(type='CUBE',
                                         location=socket_location[:],
                                         rotation=rotation[:])
                bpy.context.active_object.name = tag

        return {'FINISHED'}
Example #5
0
def passive_rotation(data):
    rotation = Euler((radians(90.0), 0.0, 0.0))
    rotation.rotate(data.rotation)
    return rotation
Example #6
0
def import_animations(mdl: MdlV44, armature, scale):
    bpy.ops.object.select_all(action="DESELECT")
    armature.select_set(True)
    bpy.context.view_layer.objects.active = armature
    bpy.ops.object.mode_set(mode='POSE')
    if not armature.animation_data:
        armature.animation_data_create()
    # for var_pos in ['XYZ', 'YXZ', ]:
    #     for var_rot in ['XYZ', 'XZY', 'YZX', 'ZYX', 'YXZ', 'ZXY', ]:
    for var_pos in ['XYZ']:
        for var_rot in ['XYZ']:
            for anim_desc in mdl.anim_descs:
                anim_name = f'pos_{var_pos}_rot_{var_rot}_{anim_desc.name}'
                action = bpy.data.actions.new(anim_name)
                armature.animation_data.action = action
                curve_per_bone = {}
                for bone in anim_desc.anim_bones:
                    if bone.bone_id == -1:
                        continue
                    bone_name = mdl.bones[bone.bone_id].name

                    bone_string = f'pose.bones["{bone_name}"].'
                    group = action.groups.new(name=bone_name)
                    pos_curves = []
                    rot_curves = []
                    for i in range(3):
                        pos_curve = action.fcurves.new(data_path=bone_string +
                                                       "location",
                                                       index=i)
                        pos_curve.keyframe_points.add(anim_desc.frame_count)
                        pos_curves.append(pos_curve)
                        pos_curve.group = group
                    for i in range(3):
                        # rot_curve = action.fcurves.new(data_path=bone_string + "rotation_quaternion", index=i)
                        rot_curve = action.fcurves.new(data_path=bone_string +
                                                       "rotation_euler",
                                                       index=i)
                        rot_curve.keyframe_points.add(anim_desc.frame_count)
                        rot_curves.append(rot_curve)
                        rot_curve.group = group
                    curve_per_bone[bone_name] = pos_curves, rot_curves

                for bone in anim_desc.anim_bones:
                    if bone.bone_id == -1:
                        continue
                    mdl_bone = mdl.bones[bone.bone_id]

                    bl_bone = armature.pose.bones.get(mdl_bone.name)
                    bl_bone.rotation_mode = 'XYZ'

                    pos_scale = mdl_bone.position_scale
                    rot_scale = mdl_bone.rotation_scale
                    if bone.is_raw_pos:
                        pos_frames = [
                            Vector(
                                np.multiply(np.multiply(bone.pos, pos_scale),
                                            scale))
                        ]
                    elif bone.is_anim_pos:
                        pos_frames = [
                            Vector(
                                np.multiply(np.multiply(pos, pos_scale),
                                            scale)) for pos in bone.pos_anim
                        ]
                    else:
                        pos_frames = []

                    if bone.is_raw_rot:
                        rot_frames = [
                            Euler(
                                np.multiply(
                                    Quaternion(bone.quat).to_euler('XYZ'),
                                    rot_scale))
                        ]
                    elif bone.is_anim_rot:
                        rot_frames = [
                            Euler(np.multiply(rot, rot_scale))
                            for rot in bone.vec_rot_anim
                        ]
                    else:
                        rot_frames = []

                    pos_curves, rot_curves = curve_per_bone[mdl_bone.name]
                    for n, pos_frame in enumerate(pos_frames):
                        pos = __swap_components(pos_frame, var_pos)

                        for i in range(3):
                            pos_curves[i].keyframe_points.add(1)
                            pos_curves[i].keyframe_points[-1].co = (n, pos[i])

                    for n, rot_frame in enumerate(rot_frames):
                        fixed_rot = rot_frame
                        if mdl_bone.parent_bone_index == -1:
                            fixed_rot.x += math.radians(-90)
                            fixed_rot.y += math.radians(180)
                            fixed_rot.z += math.radians(-90)
                        fixed_rot = Euler(__swap_components(
                            fixed_rot, var_rot))
                        # qx = Quaternion([1, 0, 0], fixed_rot[0])
                        # qy = Quaternion([0, 1, 0], -fixed_rot[1])
                        # qz = Quaternion([0, 0, 1], -fixed_rot[2])
                        # fixed_rot: Euler = (qx @ qy @ qz).to_euler()
                        # fixed_rot.x += mdl_bone.rotation[0]
                        # fixed_rot.y += mdl_bone.rotation[1]
                        # fixed_rot.z += mdl_bone.rotation[2]
                        fixed_rot.rotate(
                            Euler([
                                math.radians(90),
                                math.radians(0),
                                math.radians(0)
                            ]))
                        fixed_rot.rotate(
                            Euler([
                                math.radians(0),
                                math.radians(0),
                                math.radians(90)
                            ]))
                        fixed_rot = (
                            fixed_rot.to_matrix().to_4x4()
                            @ bl_bone.rotation_euler.to_matrix().to_4x4()
                        ).to_euler()
                        for i in range(3):
                            rot_curves[i].keyframe_points.add(1)
                            rot_curves[i].keyframe_points[-1].co = (
                                n, fixed_rot[i])

                        bpy.ops.object.mode_set(mode='OBJECT')
Example #7
0
    def _core(self, context, ob, verts, to_del=[]):
        if len(verts) < 2:
            self.report({'ERROR_INVALID_INPUT'}, "Select at least 2 vertices")
            return

        mat_wrld = np.array(ob.matrix_world)
        in_editmode = context.mode == 'EDIT_MESH'

        if self.align_to_axes:
            # If we align sources to world axes, we are interested in
            # the bounds in world coordinates.
            verts = sbt.transf_vecs(mat_wrld, verts)
            # If we align sources to axes, we ignore ob's rotation.
            rotation = Euler()

        bounds, center = sbio.get_bounds_and_center(verts)

        if not self.align_to_axes:
            # Even though we want the ob bounds in object space if align
            # to axes is false, we still are interested in world scale
            # and center.
            bounds *= np.array(ob.matrix_world.to_scale())
            center = sbt.transf_point(mat_wrld, center)
            rotation = ob.matrix_world.to_euler()

        if self.delete_original and in_editmode:
            mode = context.tool_settings.mesh_select_mode
            if mode[0]:
                del_type = 'VERTS'
            elif mode[1]:
                del_type = 'EDGES'
            else:
                del_type = 'FACES'
            for o in to_del:
                sbmm.remove_selection(o.data, type=del_type)

        if self.replace_by == 'CYLINDER_Z':
            bpy.ops.mesh.primitive_cylinder_add(
                {'active_object': ob},
                vertices=self.resolution,
                radius=self.metric(bounds[:2]) * 0.5,
                depth=bounds[2],
                end_fill_type='TRIFAN',
                location=center,
                rotation=rotation)
        elif self.replace_by == 'CYLINDER_Y':
            rotation.rotate(Euler((1.57, 0.0, 0.0)))
            bpy.ops.mesh.primitive_cylinder_add(
                {'active_object': ob},
                vertices=self.resolution,
                radius=self.metric(bounds[::2]) * 0.5,
                depth=bounds[1],
                end_fill_type='TRIFAN',
                location=center,
                rotation=rotation)
        elif self.replace_by == 'CYLINDER_X':
            rotation.rotate(Euler((0.0, 1.57, 0.0)))
            bpy.ops.mesh.primitive_cylinder_add(
                {'active_object': ob},
                vertices=self.resolution,
                radius=self.metric(bounds[1:]) * 0.5,
                depth=bounds[0],
                end_fill_type='TRIFAN',
                location=center,
                rotation=rotation)
        elif self.replace_by == 'CUBOID':
            if in_editmode:
                sbmm.add_box_to_obj(ob=ob,
                                    location=center,
                                    rotation=rotation,
                                    size=bounds)
            else:
                sbmm.add_box_to_scene(context, center, rotation, bounds)
        elif self.replace_by == 'SPHERE':
            bpy.ops.mesh.primitive_uv_sphere_add({'active_object': ob},
                                                 segments=self.resolution * 2,
                                                 ring_count=self.resolution,
                                                 radius=self.metric(bounds) *
                                                 0.5,
                                                 location=center,
                                                 rotation=rotation)

        if not in_editmode:
            # apply material if existent in original
            try:
                mat = ob.data.materials[0]
            except IndexError:
                pass
            else:
                context.object.data.materials.append(mat)

            if self.delete_original:
                for o in to_del:
                    bpy.data.objects.remove(o)
    def BlockDrawTypeLineType(self,
                              block: Block,
                              component: Component,
                              vanilla_skins=False) -> 'Object':
        '''
		This is the draw type intended for line type blocks. These blocks have a position, scale, rotation, start position,
		end position, start rotation and end rotation. These values are used to draw a block that connects 2 points.
		Parameters
			block : Block : Block to import
			component : Component : Component to import
			vanilla_skins : Bool : Import vanilla skins
		Returns : Object
		Exceptions : None
		'''

        # Import the connector, start and end objects
        connector = self.ImportCustomModel(component.line_type_middle)
        start = self.ImportCustomModel(component.line_type_end)
        end = self.ImportCustomModel(component.line_type_start)

        # Set the material for models
        if self.setting_GenerateMaterial:
            material = self.GenerateMaterial(
                block, component, component.skin_name
            )  #if not self.setting_use_vanilla_skin else self.GenerateMaterial(block, component, "TemplateB")
            start.active_material = material
            end.active_material = material
            connector.active_material = material

        # Create the empty object. We'll be using it as
        # a parent
        parent = bpy.data.objects.new("empty", None)
        parent.empty_display_size = 0.25
        parent.empty_display_type = 'CUBE'
        bpy.data.collections[bpy.context.view_layer.active_layer_collection.
                             name].objects.link(parent)

        # Set the location of the blocks
        start.location = Vector(block.GetLineStartPosition())
        end.location = Vector(block.GetLineEndPosition())
        connector.location = Vector(block.GetLineStartPosition())
        parent.location = Vector((block.getVectorPosition()))

        # Set parents of the start, end
        # and connector block to the empty object
        start.parent = parent
        end.parent = parent

        # Set the rotation of the parent, So it'll
        # transforming the other child blocks as well
        parent.rotation_mode = 'QUATERNION'
        parent.rotation_quaternion = Quaternion(
            block.getQuarternion()).inverted()
        parent.rotation_mode = 'XYZ'

        # Set the name of the blocks. We'll be
        # using the GUID in the name so it'll be
        # easier to debug
        parent.name = "LineType_" + block.guid
        start.name = "StartPoint_" + block.guid
        end.name = "EndPoint_" + block.guid
        connector.name = "Connector_" + block.guid

        # Reset the parent transformation data so that
        # the rotation is (0,0,0). Basically doing
        # parenting an object while keeping the transformation
        self.ResetParentTransformRotation(end, parent)
        self.ResetParentTransformRotation(start, parent)

        # Set the rotation of the start block
        start_rot = Euler(block.GetLineStartRotation())
        start_rot.rotate(block.GetGlobalMachineRotation().inverted())
        start.rotation_euler = start_rot
        start.rotation_mode = 'ZXY'
        self.InvertRotation(start)

        # Set the rotation of the end block
        end_rot = Euler(block.GetLineEndRotation())
        end_rot.rotate(block.GetGlobalMachineRotation().inverted())
        end.rotation_euler = end_rot
        end.rotation_mode = 'ZXY'
        self.InvertRotation(end)

        # Set the scale of the parent object,
        # which will deform the blocks
        parent.scale = block.getScale()

        # We'll be using a Track-To contraint to point the start block at the end block.
        # So here we'll be creating the contraint and configuring it to point at the end
        # block
        connector.parent = parent
        self.ResetParentTransformRotation(connector, parent)
        constraint = connector.constraints.new('TRACK_TO')
        constraint.track_axis = "TRACK_Y"
        constraint.up_axis = "UP_X"
        constraint.target = end
        distance = self.GetDistance([start, end])
        connector.dimensions[1] = distance

        # If the length between the starting and end block is less than a specific value
        # the end and the connector block will be deleted. This specific value... we dont
        # know

        if distance < self.setting_brace_threshhold:
            bpy.data.objects.remove(connector)
            bpy.data.objects.remove(end)

        if self.setting_join_line_components:
            for obj in list(bpy.context.selected_objects):
                obj.select_set(False)
            bpy.context.view_layer.objects.active = start

            start.select_set(True)
            if not distance < self.setting_brace_threshhold:
                connector.select_set(True)
                end.select_set(True)
                bpy.ops.object.join()
            current_obj = bpy.context.selected_objects[0]

            if self.setting_clean_up_action == 'DELETE_EMPTIES':
                self.UnparentKeepTransform(current_obj)
                bpy.data.objects.remove(parent)
            elif self.setting_clean_up_action == 'HIDE_EMPTIES':
                parent.hide_set(True)
            return current_obj
        return parent
Example #9
0
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()
    fix = Euler((1.57, 0, 0), 'XYZ')
Example #10
0
def hitbox_rotation(data):
    rotation = Euler((radians(90.0), 0.0, 0.0))
    rotation.rotate(data.rotation)
    return rotation