Python mathutils.Vector() Examples

The following are 30 code examples of mathutils.Vector(). 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: edit_mesh.py    From coa_tools with GNU General Public License v3.0 6 votes vote down vote up
def project_cursor(self, event):
        coord = mathutils.Vector((event.mouse_region_x, event.mouse_region_y))
        transform = bpy_extras.view3d_utils.region_2d_to_location_3d
        region = bpy.context.region
        rv3d = bpy.context.space_data.region_3d
        #### cursor used for the depth location of the mouse
        #depth_location = bpy.context.scene.cursor_location
        depth_location = bpy.context.active_object.location
        ### creating 3d vector from the cursor
        end = transform(region, rv3d, coord, depth_location)
        #end = transform(region, rv3d, coord, bpy.context.space_data.region_3d.view_location)
        ### Viewport origin
        start = bpy_extras.view3d_utils.region_2d_to_origin_3d(region, rv3d, coord)
        
        ### Cast ray from view to mouselocation
        if b_version_bigger_than((2,76,0)):
            ray = bpy.context.scene.ray_cast(start, (start+(end-start)*2000)-start )
        else:    
            ray = bpy.context.scene.ray_cast(start, start+(end-start)*2000)
        
        ### ray_cast return values have changed after blender 2.67.0 
        if b_version_bigger_than((2,76,0)):
            ray = [ray[0],ray[4],ray[5],ray[1],ray[2]]
        return start, end, ray 
Example #2
Source File: vnode.py    From gltf-blender-importer with MIT License 6 votes vote down vote up
def get_node_trs(op, node):
    """Gets the TRS proerties from a glTF node JSON object."""
    if 'matrix' in node:
        m = node['matrix']
        # column-major to row-major
        m = Matrix([m[0:4], m[4:8], m[8:12], m[12:16]])
        m.transpose()
        loc, rot, sca = m.decompose()
        # wxyz -> xyzw
        # convert_rotation will switch back
        rot = [rot[1], rot[2], rot[3], rot[0]]

    else:
        sca = node.get('scale', [1.0, 1.0, 1.0])
        rot = node.get('rotation', [0.0, 0.0, 0.0, 1.0])
        loc = node.get('translation', [0.0, 0.0, 0.0])

    # Switch glTF coordinates to Blender coordinates
    sca = op.convert_scale(sca)
    rot = op.convert_rotation(rot)
    loc = op.convert_translation(loc)

    return [Vector(loc), Quaternion(rot), Vector(sca)] 
Example #3
Source File: DtsTypes.py    From io_scene_dts with MIT License 6 votes vote down vote up
def __init__(self, mtype):
                self.bounds = Box(Vector(), Vector())
                self.center = Vector()
                self.radius = 0
                self.numFrames = 1
                self.numMatFrames = 1
                self.vertsPerFrame = 1
                self.parent = -1
                self.type = mtype
                self.verts = []
                self.tverts = []
                self.normals = []
                self.enormals = []
                self.primitives = []
                self.indices = []
                self.mindices = []

                self.bones = []
                self.influences = [] 
Example #4
Source File: fbx2joints3d.py    From 2D-Motion-Retargeting with MIT License 6 votes vote down vote up
def get_joint3d_positions(joint_names, frame_idx):
    """
    Get joint3d positions for current armature and given frame index.

    :param frame_idx: frame index
    :param joint_names: list of joint names
    :return: dict, {'pose_keypoints_3d': [x1, y1, z1, x2, y2, z2, ...]}
    """
    bpy.context.scene.frame_set(frame_idx)

    posebones = bpy.data.objects['Armature'].pose.bones
    armature = bpy.data.objects['Armature']

    out_dict = {'pose_keypoints_3d': []}
    for name in joint_names:
        global_location = armature.matrix_world * posebones[name].matrix * Vector((0, 0, 0))
        l = [global_location[0], global_location[1], global_location[2]]
        out_dict['pose_keypoints_3d'].extend(l)
    return out_dict 
Example #5
Source File: __init__.py    From retopology-polystrips with GNU General Public License v2.0 6 votes vote down vote up
def scale_tool_gvert(self, command, eventd):
        if command == 'init':
            self.footer = 'Scaling GVerts'
            sgv = self.sel_gvert
            lgv = [ge.gvert1 if ge.gvert0==sgv else ge.gvert2 for ge in sgv.get_gedges() if ge]
            self.tool_data = [(gv,Vector(gv.position)) for gv in lgv]
        elif command == 'commit':
            pass
        elif command == 'undo':
            for gv,p in self.tool_data:
                gv.position = p
                gv.update()
            self.sel_gvert.update()
            self.sel_gvert.update_visibility(eventd['r3d'], update_gedges=True)
        else:
            m = command
            sgv = self.sel_gvert
            p = sgv.position
            for ge in sgv.get_gedges():
                if not ge: continue
                gv = ge.gvert1 if ge.gvert0 == self.sel_gvert else ge.gvert2
                gv.position = p + (gv.position-p) * m
                gv.update()
            sgv.update()
            self.sel_gvert.update_visibility(eventd['r3d'], update_gedges=True) 
Example #6
Source File: block.py    From gltf-blender-importer with MIT License 6 votes vote down vote up
def add(self, child):
        self.children.append(child)
        if len(self.children) == 1:
            self.top_left = top_left(child)
            self.bottom_right = bottom_right(child)
        else:
            tl = top_left(child)
            br = bottom_right(child)
            self.top_left = Vector((
                min(self.top_left[0], tl[0]),
                max(self.top_left[1], tl[1]),
            ))
            self.bottom_right = Vector((
                max(self.bottom_right[0], br[0]),
                min(self.bottom_right[1], br[1]),
            )) 
Example #7
Source File: node.py    From gltf-blender-importer with MIT License 6 votes vote down vote up
def realize_bone(op, vnode):
    """Create a real EditBone for a BONE vnode."""
    armature = vnode.armature_vnode.blender_armature
    editbone = armature.edit_bones.new(vnode.name)

    editbone.use_connect = False

    # Bones transforms are given, not by giving their local-to-parent transform,
    # but by giving their head, tail, and roll in armature space. So we need the
    # local-to-armature transform.
    m = vnode.editbone_local_to_armature
    editbone.head = mul(m, Vector((0, 0, 0)))
    editbone.tail = mul(m, Vector((0, vnode.bone_length, 0)))
    editbone.align_roll(mul(m, Vector((0, 0, 1))) - editbone.head)

    vnode.blender_name = editbone.name
    # NOTE: can't access this after we leave edit mode
    vnode.blender_editbone = editbone

    # Set parent
    if vnode.parent:
        if getattr(vnode.parent, 'blender_editbone', None):
            editbone.parent = vnode.parent.blender_editbone 
Example #8
Source File: __init__.py    From retopology-polystrips with GNU General Public License v2.0 6 votes vote down vote up
def modal_rotate_tool(self, eventd):
        cx,cy = self.action_center
        mx,my = eventd['mouse']
        px,py = self.prev_pos #mode_pos

        if eventd['press'] in {'RET', 'NUMPAD_ENTER', 'LEFTMOUSE'}:
            self.tool_fn('commit', eventd)
            return 'main'

        if eventd['press'] in {'ESC', 'RIGHTMOUSE'}:
            self.tool_fn('undo', eventd)
            return 'main'

        if eventd['type'] == 'MOUSEMOVE':
            vp = Vector((px-cx,py-cy,0))
            vm = Vector((mx-cx,my-cy,0))
            ang = vp.angle(vm) * (-1 if vp.cross(vm).z<0 else 1)
            self.tool_rot += ang
            self.tool_fn(self.tool_rot, eventd)
            self.prev_pos = (mx,my)
            return ''

        return '' 
Example #9
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 #10
Source File: functions.py    From coa_tools with GNU General Public License v3.0 6 votes vote down vote up
def check_region(context,event):
    in_view_3d = False
    if context.area != None:
        if context.area.type == "VIEW_3D":
            t_panel = context.area.regions[1]
            n_panel = context.area.regions[3]
            
            view_3d_region_x = Vector((context.area.x + t_panel.width, context.area.x + context.area.width - n_panel.width))
            view_3d_region_y = Vector((context.region.y, context.region.y+context.region.height))
            
            if event.mouse_x > view_3d_region_x[0] and event.mouse_x < view_3d_region_x[1] and event.mouse_y > view_3d_region_y[0] and event.mouse_y < view_3d_region_y[1]:
                in_view_3d = True
            else:
                in_view_3d = False
        else:
            in_view_3d = False
    return in_view_3d 
Example #11
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 #12
Source File: functions.py    From coa_tools with GNU General Public License v3.0 6 votes vote down vote up
def set_uv_default_coords(context,obj):
    uv_coords = obj.data.uv_layers[obj.data.uv_layers.active.name].data
    ### add uv items
    for i in range(len(uv_coords)-len(obj.coa_uv_default_state)):
        item = obj.coa_uv_default_state.add()
    ### remove unneeded uv items    
    if len(uv_coords) < len(obj.coa_uv_default_state):
        for i in range(len(obj.coa_uv_default_state) - len(uv_coords)):
            obj.coa_uv_default_state.remove(0)

    ### set default uv coords
    frame_size = Vector((1 / obj.coa_tiles_x,1 / obj.coa_tiles_y))
    pos_x = frame_size.x * (obj.coa_sprite_frame % obj.coa_tiles_x)
    pos_y = frame_size.y *  -int(int(obj.coa_sprite_frame) / int(obj.coa_tiles_x))
    frame = Vector((pos_x,pos_y))
    offset = Vector((0,1-(1/obj.coa_tiles_y)))
    
    
    for i,coord in enumerate(uv_coords):    
        uv_vec_x = (coord.uv[0] - frame[0]) * obj.coa_tiles_x 
        uv_vec_y = (coord.uv[1] - offset[1] - frame[1]) * obj.coa_tiles_y
        uv_vec = Vector((uv_vec_x,uv_vec_y)) 
        obj.coa_uv_default_state[i].uv = uv_vec 
Example #13
Source File: col_exporter.py    From DragonFF with GNU General Public License v3.0 6 votes vote down vote up
def _convert_bounds():
        self = col_exporter

        radius = 0.0
        center = [0, 0, 0]
        rect_min = [0, 0, 0]
        rect_max  = [0, 0, 0]

        if self.coll.bounds is not None:
            rect_min = self.coll.bounds[0]
            rect_max  = self.coll.bounds[1]
            center = [(x + y) / 2 for x, y in zip(*self.coll.bounds)]
            radius = (
                mathutils.Vector(rect_min) - mathutils.Vector(rect_max)
            ).magnitude / 2

        self.coll.bounds = col.TBounds(max = col.TVector(*rect_min),
                                       min = col.TVector(*rect_max),
                                       center = col.TVector(*center),
                                       radius = radius
        )   
        
        pass
        
    ####################################################### 
Example #14
Source File: export_creature.py    From coa_tools with GNU General Public License v3.0 6 votes vote down vote up
def check_and_store_bone_scaling(self, context):
        anim_collections = self.sprite_object.coa_anim_collections
        bone_scaled = {}
        for anim_index, anim in enumerate(anim_collections):
            if anim.name not in ["NO ACTION"]:
                if anim.name == "Restpose":
                    if "default" in anim_collections:
                        continue
                anim_name = anim.name if anim.name != "Restpose" else "default"
                self.sprite_object.coa_anim_collections_index = anim_index  ### set animation

                for frame in range(anim.frame_end+1):
                    context.scene.frame_set(frame)
                    for bone in self.armature.pose.bones:
                        bone_scale = bone.matrix.to_scale()
                        bone_scale = Vector((round(bone_scale.x,1), round(bone_scale.y,1), round(bone_scale.z,1)))
                        if bone_scale != Vector((1, 1, 1)):
                            if anim_name not in bone_scaled:
                                bone_scaled[anim_name] = []
                            bone_scaled[anim_name].append(bone.name)
        return bone_scaled 
Example #15
Source File: __init__.py    From blender-terrain with GNU General Public License v3.0 6 votes vote down vote up
def getSelectionBoundingBox(context):
    # perform context.scene.update(), otherwise o.matrix_world or o.bound_box are incorrect
    context.scene.update()
    if len(context.selected_objects)==0:
        return None
    xmin = float("inf")
    ymin = float("inf")
    xmax = float("-inf")
    ymax = float("-inf")
    for o in context.selected_objects:
        for v in o.bound_box:
            (x,y,z) = o.matrix_world * mathutils.Vector(v)
            if x<xmin: xmin = x
            elif x>xmax: xmax = x
            if y<ymin: ymin = y
            elif y>ymax: ymax = y
    return {"xmin": xmin, "ymin": ymin, "xmax": xmax, "ymax": ymax} 
Example #16
Source File: import_sprites.py    From coa_tools with GNU General Public License v3.0 6 votes vote down vote up
def move_verts(self,obj,ratio_x,ratio_y):
        bpy.ops.object.mode_set(mode="EDIT")
        bpy.ops.mesh.reveal()
        bpy.ops.object.mode_set(mode="OBJECT")
        
        shapekeys = [obj.data.vertices]
        if obj.data.shape_keys != None:
            shapekeys = []
            for shapekey in obj.data.shape_keys.key_blocks:
                shapekeys.append(shapekey.data)
        
        for shapekey in shapekeys:
            for vert in shapekey:
                co_x = vert.co[0] * ratio_x
                co_y = vert.co[2] * ratio_y
                vert.co = Vector((co_x,0,co_y))
            
            
        obj.coa_sprite_dimension = Vector((get_local_dimension(obj)[0],0,get_local_dimension(obj)[1]))
        obj.coa_tiles_x = self.tiles_x
        obj.coa_tiles_y = self.tiles_y 
Example #17
Source File: import_sprites.py    From coa_tools with GNU General Public License v3.0 6 votes vote down vote up
def create_verts(self,width,height,pos,me,tag_hide=False):
        bpy.ops.object.mode_set(mode="EDIT")
        bm = bmesh.from_edit_mesh(me)
        vert1 = bm.verts.new(Vector((0,0,-height))*self.scale)
        vert2 = bm.verts.new(Vector((width,0,-height))*self.scale)
        vert3 = bm.verts.new(Vector((width,0,0))*self.scale)
        vert4 = bm.verts.new(Vector((0,0,0))*self.scale)
        
        bm.faces.new([vert1,vert2,vert3,vert4])
                
        bmesh.update_edit_mesh(me)
        
        if tag_hide:
            for vert in bm.verts:
                vert.hide = True    
                
            for edge in bm.edges:
                edge.hide = True    
        
        bmesh.update_edit_mesh(me)
        bpy.ops.object.mode_set(mode="OBJECT") 
Example #18
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 #19
Source File: edit_armature.py    From coa_tools with GNU General Public License v3.0 6 votes vote down vote up
def execute(self,context):
        armature = context.active_object
        p_bone = armature.pose.bones[context.active_pose_bone.name]
        bpy.ops.object.mode_set(mode="EDIT")
        
        bone_name = "Stretch_"+p_bone.name
        stretch_to_bone = armature.data.edit_bones.new(bone_name)
        stretch_to_bone.use_deform = False
        if p_bone.parent != None:
            stretch_to_bone.parent = context.active_object.data.edit_bones[p_bone.name].parent
        length = Vector(p_bone.tail - p_bone.head).length
        stretch_to_bone.head =  p_bone.tail
        stretch_to_bone.tail = Vector((p_bone.tail[0],0, p_bone.tail[2] + length * .5))
        bpy.ops.object.mode_set(mode="POSE")
        
        stretch_to_constraint = p_bone.constraints.new("STRETCH_TO")
        stretch_to_constraint.target = context.active_object
        stretch_to_constraint.subtarget = bone_name
        stretch_to_constraint.keep_axis = "PLANE_Z" 
        stretch_to_constraint.volume = "VOLUME_X"
        set_bone_group(self, context.active_object, context.active_object.pose.bones[bone_name],group="stretch_to",theme = "THEME07")
        return{'FINISHED'}

######################################################################################################################################### Set IK Constraint 
Example #20
Source File: metaballs.py    From blender-scripting with MIT License 6 votes vote down vote up
def createMetaball(origin=(0, 0, 0), n=30, r0=4, r1=2.5):
    metaball = bpy.data.metaballs.new('MetaBall')
    obj = bpy.data.objects.new('MetaBallObject', metaball)
    bpy.context.scene.objects.link(obj)

    metaball.resolution = 0.2
    metaball.render_resolution = 0.05

    for i in range(n):
        location = Vector(origin) + Vector(random.uniform(-r0, r0) for i in range(3))

        element = metaball.elements.new()
        element.co = location
        element.radius = r1

    return metaball 
Example #21
Source File: edit_armature.py    From coa_tools with GNU General Public License v3.0 6 votes vote down vote up
def project_cursor(self, event):
        coord = mathutils.Vector((event.mouse_region_x, event.mouse_region_y))
        transform = bpy_extras.view3d_utils.region_2d_to_location_3d
        region = bpy.context.region
        rv3d = bpy.context.space_data.region_3d
        #### cursor used for the depth location of the mouse
        depth_location = bpy.context.scene.cursor_location
        #depth_location = bpy.context.active_object.location
        ### creating 3d vector from the cursor
        end = transform(region, rv3d, coord, depth_location)
        #end = transform(region, rv3d, coord, bpy.context.space_data.region_3d.view_location)
        ### Viewport origin
        start = bpy_extras.view3d_utils.region_2d_to_origin_3d(region, rv3d, coord)
        
        ### Cast ray from view to mouselocation
        if b_version_bigger_than((2,76,0)):
            ray = bpy.context.scene.ray_cast(start, (start+(end-start)*2000)-start )
        else:    
            ray = bpy.context.scene.ray_cast(start, start+(end-start)*2000)
            
        ### ray_cast return values have changed after blender 2.67.0 
        if b_version_bigger_than((2,76,0)):
            ray = [ray[0],ray[4],ray[5],ray[1],ray[2]]
        
        return start, end, ray 
Example #22
Source File: dff_exporter.py    From DragonFF with GNU General Public License v3.0 6 votes vote down vote up
def edit_bone_matrix(edit_bone):

    """ A helper function to return correct matrix from any
        bone setup there might. 
        
        Basically resets the Tail to +0.05 in Y Axis to make a correct
        prediction
    """

    return edit_bone.matrix
    
    # What I wrote above is rubbish, by the way. This is a hack-ish solution
    original_tail = list(edit_bone.tail)
    edit_bone.tail = edit_bone.head + mathutils.Vector([0, 0.05, 0])
    matrix = edit_bone.matrix

    edit_bone.tail = original_tail
    return matrix
            
####################################################### 
Example #23
Source File: export_creature.py    From coa_tools with GNU General Public License v3.0 6 votes vote down vote up
def get_bone_head_tail(self, pbone, local=True):
        parent_x_axis = Vector((1, 0))
        parent_y_axis = Vector((0, 1))
        space_origin = Vector((0, 0))
        if pbone.parent != None and local:
            parent_x_axis = (pbone.parent.tail.xz - pbone.parent.head.xz).normalized()
            parent_y_axis = parent_x_axis.orthogonal().normalized()
            space_origin = pbone.parent.tail.xz

        head = pbone.head.xz - space_origin
        tail = pbone.tail.xz - space_origin

        local_tail_x = round(tail.dot(parent_x_axis), 3) * self.armature_export_scale
        local_tail_y = round(tail.dot(parent_y_axis), 3) * self.armature_export_scale

        local_head_x = round(head.dot(parent_x_axis), 3) * self.armature_export_scale
        local_head_y = round(head.dot(parent_y_axis), 3) * self.armature_export_scale

        local_tail_vec = Vector((local_tail_x, 0, local_tail_y))
        local_head_vec = Vector((local_head_x, 0, local_head_y))

        return {"head": local_head_vec.xz, "tail": local_tail_vec.xz} 
Example #24
Source File: export_creature.py    From coa_tools with GNU General Public License v3.0 6 votes vote down vote up
def scale_verts_by_bone(self, pbone, armature, mesh_object, vert_co, weight=1.0):
        # verts = mesh_object.data.vertices
        bone = armature.data.bones[pbone.name]
        bone_head = self.init_bone_positions[bone.name]["head"]
        bone_tail = self.init_bone_positions[bone.name]["tail"]
        bone_axis_x = (bone_tail - bone_head).normalized().xz
        bone_axis_y = bone_axis_x.orthogonal().normalized()

        world_axis_x = Vector((bone_axis_x.dot(Vector((1, 0))), bone_axis_y.dot(Vector((1, 0)))))
        world_axis_y = Vector((bone_axis_x.dot(Vector((0, 1))), bone_axis_y.dot(Vector((0, 1)))))

        bone_system_origin = (mesh_object.matrix_world.inverted() * (armature.matrix_world * bone_head)).xz

        bone_scale = pbone.matrix.to_scale()
        bone_scale_2d = Vector(( self.lerp( 1.0, bone_scale.y, weight), self.lerp(1.0, bone_scale.x, weight) ))

        vert_delta_co = vert_co.xz
        vert_delta_co -= bone_system_origin
        vert_delta_co = Vector((bone_axis_x.dot(vert_delta_co), bone_axis_y.dot(vert_delta_co)))
        vert_delta_co = Vector((vert_delta_co.x * bone_scale_2d.x, vert_delta_co.y * bone_scale_2d.y))
        vert_delta_co = Vector((world_axis_x.dot(vert_delta_co), world_axis_y.dot(vert_delta_co)))
        vert_delta_co += bone_system_origin

        scaled_vert_co = Vector((vert_delta_co.x, 0, vert_delta_co.y))
        return scaled_vert_co 
Example #25
Source File: export_creature.py    From coa_tools with GNU General Public License v3.0 6 votes vote down vote up
def create_cleaned_armature_copy(self, context, armature_orig):
        armature = armature_orig

        selected_objects = bpy.context.selected_objects[:]
        active_object = bpy.context.active_object
        for ob in selected_objects:
            ob.select = False
        context.scene.objects.active = armature
        bpy.ops.object.mode_set(mode="EDIT")
        for bone in armature.data.edit_bones:
            self.init_bone_positions[bone.name] = {"head": Vector(bone.head), "tail": Vector(bone.tail)}

        bpy.ops.object.mode_set(mode="OBJECT")
        for ob in context.selected_objects:
            ob.select = False
        for ob in selected_objects:
            ob.select = True
        context.scene.objects.active = active_object
        return armature 
Example #26
Source File: camera-calibration-pvr.py    From camera-calibration-pvr with GNU General Public License v2.0 5 votes vote down vote up
def get_camera_plane_vector(p, scale, focal_length = 1.0):
    """Convert a 2d point in the camera plane into a 3d vector from the camera onto the camera plane"""
    # field_of_view = 2 * atan(sensor_size / 2 * focal_length), assume sensor_size = 32
    s = (16.0 / focal_length) / (scale / 2.0)
    return mathutils.Vector((p[0] * s, p[1] * s, -1.0))

### Algorithms for intrinsic camera parameters ###################################

# The algorithm solves the following intrinsic parameters of the camera:
# - (F) focal length
# - (X) lens shift in x
# - (Y) lens shift in y
# - (A) pixel aspect ratio
# There are the following solutions for the extrinsic parameters:
# - (P) camera position
# - (R) camera rotation
# The following inputs are accepted:
# - (S) single rectangle
# - (V) single rectangle with dangling vertex
# - (D) dual rectangle
# Naming convention for the different solvers (examples):
# - solve_F_S(): solves for the focal length using a single rectangle as input
# - solve_FY_V(): solves for the focal length and y-shift from a single rectangle with dangling vertex
# - solve_FXY_VV(): solves for the focal length and x- and y- shift from a single rectangle with two dangling vertices
# - calibrate_camera_F_PR_S(): calibrates focal length, position and rotation from a single rectangle
# - calibrate_camera_FX_PR_V(): calibrates focal length, x-shift, position and rotation from a single rectangle with dangling vertex
# - calibrate_camera_FXY_PR_VV(): calibrates focal length, x- and y-shift, position and rotation from a single rectangle with two dangling vertices 
Example #27
Source File: camera-calibration-pvr.py    From camera-calibration-pvr with GNU General Public License v2.0 5 votes vote down vote up
def is_to_the_right(a, b, c):
    """Checks whether the rotation angle from vector AB to vector BC is between 0 and 180 degrees when rotating to the right. Returns a number."""
    # Vector from a to b
    ab = b - a
    # Vector from b to c
    bc = c - b
    # This is a simple dot product with bc and the vector perpendicular to ab (rotated clockwise)
    return - ab[0] * bc[1] + ab[1] * bc[0] 
Example #28
Source File: import_sprites.py    From coa_tools with GNU General Public License v3.0 5 votes vote down vote up
def execute(self,context):
        if os.path.exists(self.path):
            data = bpy.data
            sprite_name = os.path.basename(self.path)
            
            sprite_found = False
            for image in bpy.data.images:
                if os.path.exists(bpy.path.abspath(image.filepath)) and os.path.exists(self.path):
                    if os.path.samefile(bpy.path.abspath(image.filepath),self.path):
                        sprite_found = True
                        img = image
                        img.reload()
                        break
            if not sprite_found:
                img = data.images.load(self.path)
                
            obj = self.create_mesh(context,name=img.name,width=img.size[0],height=img.size[1],pos=self.pos)
            mat = self.create_material(context,obj,name=img.name)
            tex = self.create_texture(context,mat,img,name=img.name)
            msg = sprite_name + " Sprite created."
            assign_tex_to_uv(img,obj.data.uv_textures.active)
            
            obj.coa_sprite_dimension = Vector((get_local_dimension(obj)[0],0,get_local_dimension(obj)[1]))
            
            obj.coa_tiles_x = self.tilesize[0]
            obj.coa_tiles_y = self.tilesize[1]
            
            selected_objects = []
            for obj2 in context.selected_objects:
                selected_objects.append(obj2)
                if obj2 != context.active_object:
                    obj2.select = False
            obj.coa_z_value = -self.pos[1]
            for obj2 in selected_objects:
                obj2.select = True
            
            self.report({'INFO'},msg)
            return{'FINISHED'}
        else:
            self.report({'WARNING'},'File does not exist.')
            return{'CANCELLED'} 
Example #29
Source File: __init__.py    From retopology-polystrips with GNU General Public License v2.0 5 votes vote down vote up
def create_polystrips_from_bezier(self, ob_bezier):
        data  = ob_bezier.data
        mx    = ob_bezier.matrix_world

        def create_gvert(self, mx, co, radius):
            p0  = mx * co
            r0  = radius
            n0  = Vector((0,0,1))
            tx0 = Vector((1,0,0))
            ty0 = Vector((0,1,0))
            return GVert(self.obj,p0,r0,n0,tx0,ty0)

        for spline in data.splines:
            pregv = None
            for bp0,bp1 in zip(spline.bezier_points[:-1],spline.bezier_points[1:]):
                gv0 = pregv if pregv else self.create_gvert(mx, bp0.co, 0.2)
                gv1 = self.create_gvert(mx, bp0.handle_right, 0.2)
                gv2 = self.create_gvert(mx, bp1.handle_left, 0.2)
                gv3 = self.create_gvert(mx, bp1.co, 0.2)

                ge0 = GEdge(self.obj, gv0, gv1, gv2, gv3)
                ge0.recalc_igverts_approx()
                ge0.snap_igverts_to_object()

                if pregv:
                    self.polystrips.gverts += [gv1,gv2,gv3]
                else:
                    self.polystrips.gverts += [gv0,gv1,gv2,gv3]
                self.polystrips.gedges += [ge0]
                pregv = gv3 
Example #30
Source File: camera-calibration-pvr.py    From camera-calibration-pvr with GNU General Public License v2.0 5 votes vote down vote up
def solve_FXY_VV(vertices, attached_vertices, dangling_vertices, scale):
    # Get the 3 vanishing points
    v1 = get_vanishing_point(vertices[0], vertices[3], vertices[1], vertices[2])
    v2 = get_vanishing_point(attached_vertices[0], dangling_vertices[0], attached_vertices[1], dangling_vertices[1])
    v3 = get_vanishing_point(vertices[0], vertices[1], vertices[3], vertices[2])
    print("Vanishing points:", v1, v2, v3)
    # Use that v1, v2, and v3 are all perpendicular to each other to solve for the lens shift
    # x*(v2x - v3x) + y*(v2y - v3y) = v1y*v2y - v1y*v3y + v1x*v2x - v1x*v3x
    # x*(v1x - v3x) + y*(v1y - v3y) = v1y*v2y - v2y*v3y + v1x*v2x - v2x*v3x
    A1 = v2[0] - v3[0]
    B1 = v2[1] - v3[1]
    C1 = v1[1] * v2[1] - v1[1] * v3[1] + v1[0] * v2[0] - v1[0] * v3[0]
    A2 = v1[0] - v3[0]
    B2 = v1[1] - v3[1]
    C2 = v1[1] * v2[1] - v2[1] * v3[1] + v1[0] * v2[0] - v2[0] * v3[0]
    # Solve A1 * x + B1 * y = C1, A2 * x + B2 * y = C2
    shift_x, shift_y = solve_linear_system_2d(A1, B1, C1, A2, B2, C2)
    optical_centre = mathutils.Vector((shift_x, shift_y))
    shift_x /= -scale
    shift_y /= -scale
    print("Shift:", shift_x, shift_y)
    # Get the focal length
    vm = get_camera_plane_vector(v1 - optical_centre, scale)
    vn = get_camera_plane_vector(v3 - optical_centre, scale)
    # Calculate the focal length
    focal = sqrt(abs(vm.dot(vn)))
    print("Focal:", focal)
    return focal, shift_x, shift_y, optical_centre

### Helper functions for extrinsic camera parameter algorithms ###################