Python mathutils 模块,Vector() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用mathutils.Vector()

项目:coa_tools    作者:ndee85    | 项目源码 | 文件源码
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
项目:coa_tools    作者:ndee85    | 项目源码 | 文件源码
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
项目:coa_tools    作者:ndee85    | 项目源码 | 文件源码
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")
项目:coa_tools    作者:ndee85    | 项目源码 | 文件源码
def limit_cursor_by_bounds(self,context,location):
        obj = context.active_object
        bounds = self.bounds#get_bounds_and_center(obj)[1]

        if len(bounds) > 0:
            e1 = [bounds[0],bounds[2]] ### top edge
            e2 = [bounds[2],bounds[3]] ### right edge
            e3 = [bounds[3],bounds[1]] ### bottom edge
            e4 = [bounds[1],bounds[0]] ### left edge

            p1 = self.get_projected_point(e1,custom_pos=None,disable_edge_threshold=True) + Vector((0,0,-.1))
            p2 = self.get_projected_point(e2,custom_pos=None,disable_edge_threshold=True) + Vector((-.1,0,0))
            p3 = self.get_projected_point(e3,custom_pos=None,disable_edge_threshold=True) + Vector((0,0,.1))
            p4 = self.get_projected_point(e4,custom_pos=None,disable_edge_threshold=True) + Vector((.1,0,0))

            edges = [e1,e2,e3,e4]
            points_on_edge = [p1,p2,p3,p4]

            mouse_vec = [self.mesh_center,location]
            for j,edge in enumerate(edges):
                #mouse_vec = [points_on_edge[j] , location]
                i = geometry.intersect_line_line_2d(edge[0].xz,edge[1].xz,mouse_vec[0].xz,mouse_vec[1].xz)
                if i != None:
                    location = Vector((i[0],location[1],i[1]))
        return location
项目:coa_tools    作者:ndee85    | 项目源码 | 文件源码
def get_intersecting_lines(self,coord,bm):
        scene = bpy.context.scene
        vertex_vec_new = self.limit_cursor_by_bounds(bpy.context,coord)

        if scene.coa_surface_snap:
            coord, point_type, bm_ob = self.snap_to_edge_or_vert(vertex_vec_new)
        else:    
            coord, point_type, bm_ob = [None,None,None]
        intersection_points = []
        if self.selected_vert_coord != None and coord != None:
            obj = bpy.context.active_object
            e1 = [self.selected_vert_coord.xz,coord.xz]

            for edge in bm.edges:
                if not edge.hide:# and (edge.is_wire or edge.is_boundary):
                    e2 = [(obj.matrix_world * edge.verts[0].co).xz , (obj.matrix_world * edge.verts[1].co).xz ]
                    ip = geometry.intersect_line_line_2d(e1[0],e1[1],e2[0],e2[1])
                    if ip != None:
                        ip = Vector((ip[0],self.selected_vert_coord[1],ip[1]))
                        if (ip - self.selected_vert_coord).magnitude > 0.001 and (ip - coord).magnitude > 0.001:
                            #ip, point_type, bm_ob = self.snap_to_edge_or_vert(ip) ### snap intersection points
                            intersection_points.append(ip)
        intersection_points.sort(key=lambda x: (self.selected_vert_coord - x).magnitude)
        return intersection_points
项目:coa_tools    作者:ndee85    | 项目源码 | 文件源码
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
项目:coa_tools    作者:ndee85    | 项目源码 | 文件源码
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
项目:blender-scripting    作者:njanakiev    | 项目源码 | 文件源码
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
项目:Blender-WMO-import-export-scripts    作者:WowDevTools    | 项目源码 | 文件源码
def get_min_max(vertList):
    min = Vector(vertList[0])
    max = Vector(vertList[0])
    for v in vertList:
        if v.x < min.x:
            min.x = v.x
        elif v.x > max.x:
            max.x = v.x
        if v.y < min.y:
            min.y = v.y
        elif v.y > max.y:
            max.y = v.y
        if v.z < min.z:
            min.z = v.z
        elif v.z > max.z:
            max.z = v.z
    return min, max
项目:Blender-WMO-import-export-scripts    作者:WowDevTools    | 项目源码 | 文件源码
def project_point(pt, v):
    """ Return projection of point with given direction vector """
    proj = Vector()
    # project on X
    if v.y == 0:
        l = 0
    else:
        l = - pt.y / v.y
    proj.z = pt.x + l * v.x
    # project on Y
    if v.z == 0:
        l = 0
    else:
        l = - pt.z / v.z
    proj.y = pt.x + l * v.x
    # project on Z
    proj.x = pt.y + l * v.y
    return proj
项目:io_scene_kcl    作者:Syroot    | 项目源码 | 文件源码
def __init__(self, base, width, bm, indices, max_triangles, min_width):
            self.half_width = width / 2.0
            self.c = base + Vector((self.half_width, self.half_width, self.half_width))
            self.is_leaf = True
            self.indices = []
            for i in indices:
                # TODO: Maybe solving it with a Wiimm KCL_BLOW approach is faster.
                if self.tricube_overlap(bm.faces[i], self):
                    self.indices.append(i)
            # Split this node's cube when it contains too many triangles and the minimum size is not underrun yet.
            if len(self.indices) > max_triangles and self.half_width >= min_width:
                self.is_leaf = False
                self.branches = [KclModel.OctreeNode(base + (Vector((x, y, z)) * self.half_width), self.half_width,
                     bm, self.indices,
                     max_triangles, min_width)
                     for z in range(0, 2) for y in range(0, 2) for x in range(0, 2)]
                self.indices = []
项目:blender-tools    作者:vvoovv    | 项目源码 | 文件源码
def execute(self, context):
        wm = context.window_manager
        scene = context.scene
        o = scene.objects.active
        # calculationg the new position of the active object center
        v = -Vector((wm["_x"], wm["_y"], o.location.z))
        p = o.matrix_world * v
        projection = TransverseMercator(lat=scene["lat"], lon=scene["lon"])
        (lat, lon) = projection.toGeographic(p[0], p[1])
        scene["lat"] = lat
        scene["lon"] = lon
        scene["heading"] = (o.rotation_euler[2]-wm["_h"])*180/math.pi

        # restoring original objects location and orientation
        bpy.ops.transform.rotate(value=-(o.rotation_euler[2]-wm["_h"]), axis=(0,0,1))
        bpy.ops.transform.translate(value=-(o.location+v))
        # cleaning up
        del wm["_x"], wm["_y"], wm["_h"]
        return {"FINISHED"}
项目:UPBGE-CommunityAddon    作者:elmeunick9    | 项目源码 | 文件源码
def getNearestVertexToPoly(object, poly, point):
    """ Returns the nearest vertext to a poligon.

    :param poly: The poligon if wich vertex you want to check.
    :type poly: |KX_PolyProxy|
    :param point: The point to check, in world coordinates.
    :type point: |Vector|
    """

    if not type(point) is Vector: point = Vector(point)
    mesh = poly.getMesh()

    min = None
    f = None
    for i in range(poly.getNumVertex()):
        v = mesh.getVertex(0, poly.getVertexIndex(i))
        r = vectorFrom2Points(v.XYZ, point - object.worldPosition).length
        if not min or r < min:
            min = r
            f = v

    return f
项目:UPBGE-CommunityAddon    作者:elmeunick9    | 项目源码 | 文件源码
def vectorFrom2Points(origin, dest, module = None):
    """ Returns a |Vector|  form 2 points in the space.

    :param origin: Point A
    :type origin: |Vector|
    :param dest: Point B
    :type dest: |Vector|
    :param float module: If setted, the returned vector will have this maxium lenght. The new lenght will never be greater than the original.
    """
    vec = Vector((dest.x - origin.x, dest.y - origin.y, dest.z - origin.z))
    if not module: return vec

    l = vec.length

    if l < 0.0125: return vec.zero()
    if l < module: return vec

    vec = vec / l
    if module == 1: return vec
    else: return vec * module
项目:UPBGE-CommunityAddon    作者:elmeunick9    | 项目源码 | 文件源码
def moveObjectToPosition(origin, dest, speed = 1):
    """ Moves *origin* to *dest* at a speed of *speed*. Must by called every frame for a complete movement.

    :param origin: Object to move.
    :type origin: |KX_GameObject|
    :param dest: Destination object.
    :type dest: |Vector|
    :param float speed: The amount of movment to do in one frame.
    :return: True if the object has been moved, false otherwise.
    """
    fr = logic.getAverageFrameRate()
    if fr < 20: fr = 20
    vel = speed / fr
    vec = vectorFrom2Points(origin.position, dest, vel)
    if vec:
        origin.position += vec
        return True
    else: return False
项目:UPBGE-CommunityAddon    作者:elmeunick9    | 项目源码 | 文件源码
def test_bge():
    import traceback
    sys.path.append(build_path)

    try:
        import mathutils, bge
        v=mathutils.Vector()
        m=mathutils.Matrix()
        scn = bge.logic.getCurrentScene()
        o = scn.objects["some"]
        a=o.isPlayingAction()
        b=o.parent.addDebugProperty("LOL")
        o.endObject()

        print("Test BGE: OK")
    except Exception: traceback.print_exc()
项目:UPBGE-CommunityAddon    作者:elmeunick9    | 项目源码 | 文件源码
def __init__(self):
        self.diffuseIntensity = float()
        self.diffuseFactor = float()
        self.alpha = float()
        self.specularIntensity = float()
        self.specularFactor = float()
        self.hardness = float()
        self.emit = float()
        self.mirror = float()
        self.normal = float()
        self.parallaxBump = float()
        self.parallaxStep = float()
        self.lodBias = float()
        self.bindCode = int()
        self.cubeMap = KX_CubeMap()
        self.ior = float()
        self.refractionRatio = float()
        self.uvOffset = mathutils.Vector()
        self.uvSize = mathutils.Vector()
        self.uvRotation = float()
项目:UPBGE-CommunityAddon    作者:elmeunick9    | 项目源码 | 文件源码
def __init__(self):
        self.XYZ = mathutils.Vector()
        self.UV = mathutils.Vector()
        self.uvs = CListValue(mathutils.Vector)
        self.normal = mathutils.Vector()
        self.color = mathutils.Vector()
        self.colors = CListValue(mathutils.Vector)
        self.x = float()
        self.y = float()
        self.z = float()
        self.u = float()
        self.v = float()
        self.u2 = float()
        self.v2 = float()
        self.r = float()
        self.g = float()
        self.b = float()
        self.a = float()
项目:UPBGE-CommunityAddon    作者:elmeunick9    | 项目源码 | 文件源码
def __init__(self):
        self.name = str()
        self.objects = CListValue(KX_GameObject)
        self.objectsInactive = CListValue(KX_GameObject)
        self.lights = CListValue(KX_LightObject)
        self.cameras = CListValue(KX_Camera)
        self.texts = CListValue(KX_FontObject)
        self.active_camera = KX_Camera()
        self.world = KX_WorldInfo()
        self.filterManager = KX_2DFilterManager()
        self.suspended = bool()
        self.activity_culling = bool()
        self.activity_culling_radius = float()
        self.dbvt_culling = bool()
        self.pre_draw = list()
        self.post_draw = list()
        self.pre_draw_setup = list()
        self.gravity = mathutils.Vector()
项目:blemd    作者:niacdoial    | 项目源码 | 文件源码
def _FixBoneLength(self):

        for childBone in self.children:
            if (self._bone is not None) and (self._bone.parent.fget() is not None):
                mt = mathutils.Matrix.Translation(mathutils.Vector((self.f.t.x, self.f.t.y, self.f.t.z)))
                mx = mathutils.Matrix.Rotation(self.f.rx, 4, 'X')
                my = mathutils.Matrix.Rotation(self.f.ry, 4, 'Y')
                mz = mathutils.Matrix.Rotation(self.f.rz, 4, 'Z')

                parentVec = vect_normalize((self._bone.position)*self._bone.transform.inverted() -
                                           (self._bone.parent.fget().position)*self._bone.parent.fget().transform.inverted())

                mTransform = (mx * my * mz * mt)

                boneVec2 = vect_normalize((vect_normalize(self._bone.dir)) * mTransform)

                print(str(parentVec) + ":" + str(boneVec2))

            childBone._FixBoneLength()
项目:blemd    作者:niacdoial    | 项目源码 | 文件源码
def ResetControllers(self):
        if self._bone is not None:
            if self._bone.parent.fget() is not None:
                m = mathutils.Euler((), 'XYZ')
                #                   m.x_rotation = self.f.rx
                #                   m.y_rotation = self.f.ry
                #                   m.z_rotation = self.f.rz
                #
                self._bone.scale = mathutils.Vector((0,0,0))                 # -- resets animations

                self._eulerController = m
                self._bone.rotation = m

                pos = mathutils.Vector((0,0,0))
                                    #pos.x_position = self.f.t.x
                #                   pos.y_position = self.f.t.y
                #                   pos.z_position = self.f.t.z

                self._bone.position.controller = pos
        for child in self.children:
            child.ResetControllers()
项目:blemd    作者:niacdoial    | 项目源码 | 文件源码
def RotateAroundWorld(self, obj, rotation):  # XCX used?
        print(rotation, type(rotation))
        origParent = obj.parent
        d = bpy.data.new('UTEMP_PL', None)
        d.location = Vector((0,0,0))
        obj.parent = d
        d.rotation_euler = Euler(rotation, 'XYZ')
        act_bk = bpy.ops.active
        bpy.ops.active = d
        bpy.ops.object.transform_apply(rotation=True)
        bpy.ops.active = obj
        bpy.ops.object.transform_apply(rotation=True)
        bpy.ops.active = act_bk
        obj.parent = None
        bpy.data.objects.remove(d)
        # --delete d
        # --if (origParent != undefined) then
        # --    obj.parent = origParent
项目:Urho3D-Blender-Mod    作者:Mike3D    | 项目源码 | 文件源码
def __init__(self):
        # Index of the vertex in the Blender buffer
        self.blenderIndex = None
        # Position of the vertex: Vector((0.0, 0.0, 0.0))
        self.pos = None
        # Normal of the vertex: Vector((0.0, 0.0, 0.0))
        self.normal = None
        # Color of the vertex: (0, 0, 0, 0)...(255, 255, 255, 255)
        self.color = None
        # UV coordinates of the vertex: Vector((0.0, 0.0))..Vector((1.0, 1.0))
        self.uv = None
        # UV2 coordinates of the vertex: Vector((0.0, 0.0))..Vector((1.0, 1.0))
        self.uv2 = None
        # Tangent of the vertex: Vector((0.0, 0.0, 0.0, 0.0))
        self.tangent = None
        # Bitangent of the vertex: Vector((0.0, 0.0, 0.0))
        self.bitangent = None
        # Bones weights: list of tuple(boneIndex, weight)
        self.weights = None

    # returns True is this vertex is a changed morph of vertex 'other'
项目:Urho3D-Blender-Mod    作者:Mike3D    | 项目源码 | 文件源码
def __init__(self):
        # Bone name
        self.name = None
        # Index of the parent bone in the model bones list
        self.parentIndex = None
        # Bone position in parent space
        self.position = None
        # Bone rotation in parent space
        self.rotation = None
        # Bone scale
        self.scale = Vector((1.0, 1.0, 1.0))
        # Bone transformation in skeleton space
        self.matrix = None
        # Inverse of the above
        self.inverseMatrix = None
        # Position in skeleton space
        self.derivedPosition = None
        # Collision sphere and/or box
        self.collisionMask = 0
        self.radius = None
        self.boundingBox = BoundingBox()
        self.length = 0
项目:Nier2Blender    作者:C4nf3ng    | 项目源码 | 文件源码
def construct_armature(name, bone_data_array):          # bone_data =[boneIndex, boneName, parentIndex, parentName, bone_pos, optional ]
    print('[+] importing armature')
    bpy.ops.object.add(
        type='ARMATURE', 
        enter_editmode=True,
        location=(0,0,0))
    ob = bpy.context.object
    ob.show_x_ray = False
    ob.name = name
    amt = ob.data
    amt.name = name +'Amt'
    for bone_data in bone_data_array:   
        bone = amt.edit_bones.new(bone_data[1])
        bone.head = Vector(bone_data[4]) 
        bone.tail = Vector(bone_data[4]) + Vector((0 , 0.01, 0))
    bones = amt.edit_bones
    for bone_data in bone_data_array:
        if bone_data[2] < 0xffff:                       #this value need to edit in different games
            bone = bones[bone_data[1]]
            bone.parent = bones[bone_data[3]]
            bones[bone_data[3]].tail = bone.head
    bpy.ops.object.mode_set(mode='OBJECT')
    ob.rotation_euler = (math.tan(1),0,0)
    #split_armature(amt.name)                           #current not used
    return ob
项目:Nier2Blender    作者:C4nf3ng    | 项目源码 | 文件源码
def add_material_to_mesh(mesh, materials , uvs):
    for material in materials:
        print('linking material %s to mesh object %s' % (material.name, mesh.name))
        mesh.data.materials.append(material)
    bpy.context.scene.objects.active = mesh
    bpy.ops.object.mode_set(mode="EDIT")
    bm = bmesh.from_edit_mesh(mesh.data)
    uv_layer = bm.loops.layers.uv.verify()
    bm.faces.layers.tex.verify()
    for face in bm.faces:
        face.material_index = 0
        for l in face.loops:
            luv = l[uv_layer]
            ind = l.vert.index
            luv.uv = Vector(uvs[ind])
    bpy.ops.object.mode_set(mode='OBJECT')
    mesh.select = True
    bpy.ops.object.shade_smooth()
    #mesh.hide = True
    mesh.select = False
项目:Smooth-Normal    作者:dskjal    | 项目源码 | 文件源码
def type_direction_callback(self, context):
    scn = context.scene
    v = mathutils.Vector(scn.ne_type_normal)

    nv = copy.deepcopy(v)
    nv.normalize()
    rotated = nv

    if scn.ne_view_sync_mode:
        mView = get_view_rotational_matrix(True)
        mObject = get_object_rotational_matrix()
        rotated = mView * mObject * nv
    else:
        rotated = rot_vector(nv, reverse=True)

    if not is_same_vector(scn.ne_type_normal, scn.ne_type_normal_old):
        if not scn.ne_update_by_global_callback:
            set_normal_to_selected(context, nv)
        scn.ne_type_normal_old = scn.ne_type_normal

    # update direction sphere
    # avoid recursive call
    scn.ne_update_by_global_callback = True
    scn.ne_view_normal = rotated
项目:bpy_lambda    作者:bcongdon    | 项目源码 | 文件源码
def poly_to_doom(me, p, radius):
    """
    Convert a face into Doom3 representation (infinite plane defined by its normal
    and distance from origin along that normal).
    """
    # Compute the distance to the mesh from the origin to the plane.
    # Line from origin in the direction of the face normal.
    origin = Vector((0, 0, 0))
    target = Vector(p.normal) * radius
    # Find the target point.
    intersect = mathutils.geometry.intersect_line_plane(origin, target, Vector(p.center), Vector(p.normal))
    # We have to handle cases where intersection with face happens on the "negative" part of the vector!
    length = intersect.length
    nor = p.normal.copy()
    if (nor.dot(intersect.normalized()) > 0):
        length *= -1
    nor.resize_4d()
    nor.w = length
    return nor
项目:bpy_lambda    作者:bcongdon    | 项目源码 | 文件源码
def mouse_to_plane(self, context, event, origin=Vector((0, 0, 0)), normal=Vector((0, 0, 1))):
        """
            convert mouse pos to 3d point over plane defined by origin and normal
        """
        region = context.region
        rv3d = context.region_data
        co2d = (event.mouse_region_x, event.mouse_region_y)
        view_vector_mouse = region_2d_to_vector_3d(region, rv3d, co2d)
        ray_origin_mouse = region_2d_to_origin_3d(region, rv3d, co2d)
        pt = intersect_line_plane(ray_origin_mouse, ray_origin_mouse + view_vector_mouse,
           origin, normal, False)
        # fix issue with parallel plane
        if pt is None:
            pt = intersect_line_plane(ray_origin_mouse, ray_origin_mouse + view_vector_mouse,
                origin, view_vector_mouse, False)
        return pt
项目:bpy_lambda    作者:bcongdon    | 项目源码 | 文件源码
def mouse_hover_wall(self, context, event):
        """
            convert mouse pos to matrix at bottom of surrounded wall, y oriented outside wall
        """
        res, pt, y, i, o, tM = self.mouse_to_scene_raycast(context, event)
        if res and o.data is not None and 'archipack_wall2' in o.data:
            z = Vector((0, 0, 1))
            d = o.data.archipack_wall2[0]
            y = -y
            pt += (0.5 * d.width) * y.normalized()
            x = y.cross(z)
            return True, Matrix([
                [x.x, y.x, z.x, pt.x],
                [x.y, y.y, z.y, pt.y],
                [x.z, y.z, z.z, o.matrix_world.translation.z],
                [0, 0, 0, 1]
                ]), o, y
        return False, Matrix(), None, Vector()
项目:bpy_lambda    作者:bcongdon    | 项目源码 | 文件源码
def __init__(self, sensor_size, size, draggable=False, selectable=False, d=3):
        """
            sensor_size : 2d size in pixels of sensor area
            size : 3d size of handle
        """
        GlPolygon.__init__(self, d=d)
        self.colour_active = (1.0, 0.0, 0.0, 1.0)
        self.colour_hover = (1.0, 1.0, 0.0, 1.0)
        self.colour_normal = (1.0, 1.0, 1.0, 1.0)
        self.colour_selected = (0.0, 0.0, 0.7, 1.0)
        self.size = size
        self.sensor_width = sensor_size
        self.sensor_height = sensor_size
        self.pos_3d = Vector((0, 0, 0))
        self.up_axis = Vector((0, 0, 0))
        self.c_axis = Vector((0, 0, 0))
        self.hover = False
        self.active = False
        self.draggable = draggable
        self.selectable = selectable
        self.selected = False
项目:bpy_lambda    作者:bcongdon    | 项目源码 | 文件源码
def set_location(self, context, p0, p1):
        x0, y0 = p0
        x1, y1 = p1
        if x0 > x1:
            x1, x0 = x0, x1
        if y0 > y1:
            y1, y0 = y0, y1
        self.min = Vector((x0, y0))
        self.max = Vector((x1, y1))
        pos = [
            Vector((x0, y0)),
            Vector((x0, y1)),
            Vector((x1, y1)),
            Vector((x1, y0))]
        self.area.set_pos(pos)
        self.border.set_pos(pos)
项目:bpy_lambda    作者:bcongdon    | 项目源码 | 文件源码
def setup_user_defined_post(self, o, post_x, post_y, post_z):
        self.user_defined_post = o
        x = o.bound_box[6][0] - o.bound_box[0][0]
        y = o.bound_box[6][1] - o.bound_box[0][1]
        z = o.bound_box[6][2] - o.bound_box[0][2]
        self.user_defined_post_scale = Vector((post_x / x, post_y / -y, post_z / z))
        m = o.data
        # create vertex group lookup dictionary for names
        vgroup_names = {vgroup.index: vgroup.name for vgroup in o.vertex_groups}
        # create dictionary of vertex group assignments per vertex
        self.vertex_groups = [[vgroup_names[g.group] for g in v.groups] for v in m.vertices]
        # uvs
        uv_act = m.uv_layers.active
        if uv_act is not None:
            uv_layer = uv_act.data
            self.user_defined_uvs = [[uv_layer[li].uv for li in p.loop_indices] for p in m.polygons]
        else:
            self.user_defined_uvs = [[(0, 0) for i in p.vertices] for p in m.polygons]
        # material ids
        self.user_defined_mat = [p.material_index for p in m.polygons]
项目:bpy_lambda    作者:bcongdon    | 项目源码 | 文件源码
def setup_manipulators(self):

        if len(self.manipulators) == 0:
            s = self.manipulators.add()
            s.prop1_name = "width"
            s = self.manipulators.add()
            s.prop1_name = "height"
            s.normal = Vector((0, 1, 0))

        for i in range(self.n_parts):
            p = self.parts[i]
            n_manips = len(p.manipulators)
            if n_manips == 0:
                s = p.manipulators.add()
                s.type_key = "ANGLE"
                s.prop1_name = "a0"
                s = p.manipulators.add()
                s.type_key = "SIZE"
                s.prop1_name = "length"
                s = p.manipulators.add()
                # s.type_key = 'SNAP_POINT'
                s.type_key = 'WALL_SNAP'
                s.prop1_name = str(i)
                s.prop2_name = 'post_z'
项目:bpy_lambda    作者:bcongdon    | 项目源码 | 文件源码
def docylinder(self, faces, verts, radius, segs, tMt, tMb, tM, add=False):
        segs_step = 2 * pi / segs
        tmpverts = [0 for i in range(segs)]
        if add:
            cv = len(verts) - segs
        else:
            cv = len(verts)
        for seg in range(segs):
            seg_angle = pi / 4 + seg * segs_step
            tmpverts[seg] = radius * Vector((sin(seg_angle), -cos(seg_angle), 0))

        if not add:
            for seg in range(segs):
                verts.append(tM * tMb * tmpverts[seg])

        for seg in range(segs):
            verts.append(tM * tMt * tmpverts[seg])

        for seg in range(segs - 1):
            f = cv + seg
            faces.append((f + 1, f, f + segs, f + segs + 1))
        f = cv
        faces.append((f, f + segs - 1, f + 2 * segs - 1, f + segs))
项目:bpy_lambda    作者:bcongdon    | 项目源码 | 文件源码
def create(self, context):
        curve = context.active_object
        bpy.ops.archipack.slab(auto_manipulate=self.auto_manipulate)
        o = context.scene.objects.active
        d = archipack_slab.datablock(o)
        spline = curve.data.splines[0]
        d.from_spline(curve.matrix_world, 12, spline)
        if spline.type == 'POLY':
            pt = spline.points[0].co
        elif spline.type == 'BEZIER':
            pt = spline.bezier_points[0].co
        else:
            pt = Vector((0, 0, 0))
        # pretranslate
        o.matrix_world = curve.matrix_world * Matrix([
            [1, 0, 0, pt.x],
            [0, 1, 0, pt.y],
            [0, 0, 1, pt.z],
            [0, 0, 0, 1]
            ])
        return o

    # -----------------------------------------------------
    # Execute
    # -----------------------------------------------------
项目:bpy_lambda    作者:bcongdon    | 项目源码 | 文件源码
def sp_draw(self, sp, context):
        z = 2.7
        if self.state == 'CREATE':
            p0 = self.takeloc
        else:
            p0 = sp.takeloc

        p1 = sp.placeloc
        delta = p1 - p0
        # print("sp_draw state:%s delta:%s p0:%s p1:%s" % (self.state, delta.length, p0, p1))
        if delta.length == 0:
            return
        self.wall_part1.set_pos([p0, p1, Vector((p1.x, p1.y, p1.z + z)), Vector((p0.x, p0.y, p0.z + z))])
        self.wall_line1.set_pos([p0, p1, Vector((p1.x, p1.y, p1.z + z)), Vector((p0.x, p0.y, p0.z + z))])
        self.wall_part1.draw(context)
        self.wall_line1.draw(context)
        self.line.p = p0
        self.line.v = delta
        self.label.set_pos(context, self.line.length, self.line.lerp(0.5), self.line.v, normal=Vector((0, 0, 1)))
        self.label.draw(context)
        self.line.draw(context)
项目:bpy_lambda    作者:bcongdon    | 项目源码 | 文件源码
def set_pos(self, pos_2d):
        self.pos_2d = pos_2d
        o = pos_2d
        w = 0.5 * self.sensor_width
        d = self.depth
        c = d / 1.4242
        s = w - c
        p0 = o + Vector((s, w))
        p1 = o + Vector((w, s))
        p2 = o + Vector((c, 0))
        p3 = o + Vector((w, -s))
        p4 = o + Vector((s, -w))
        p5 = o + Vector((0, -c))
        p6 = o + Vector((-s, -w))
        p7 = o + Vector((-w, -s))
        p8 = o + Vector((-c, 0))
        p9 = o + Vector((-w, s))
        p10 = o + Vector((-s, w))
        p11 = o + Vector((0, c))
        self.branch_0.set_pos([p11, p0, p1, p2, o])
        self.branch_1.set_pos([p2, p3, p4, p5, o])
        self.branch_2.set_pos([p5, p6, p7, p8, o])
        self.branch_3.set_pos([p8, p9, p10, p11, o])
项目:bpy_lambda    作者:bcongdon    | 项目源码 | 文件源码
def set_pos(self, context, pos_2d):
        x, ty = self.text_size(context)
        w = self.sensor_width
        y = 12
        pos_2d.y += y
        pos_2d.x -= 0.5 * w
        self.pos_2d = pos_2d.copy()
        self.pos_3d = pos_2d.copy()
        self.pos_3d.x += 6
        self.sensor_height = y
        p0 = pos_2d + Vector((w, -0.5 * y))
        p1 = pos_2d + Vector((w, 1.5 * y))
        p2 = pos_2d + Vector((0, 1.5 * y))
        p3 = pos_2d + Vector((0, -0.5 * y))
        self.bg.set_pos([p0, p2])
        self.frame.set_pos([p0, p1, p2, p3])
        self.cancel.set_pos(pos_2d + Vector((w + 15, 0.5 * y)))
项目:bpy_lambda    作者:bcongdon    | 项目源码 | 文件源码
def execute(self, context):
        if context.mode == "OBJECT":
            o = context.active_object
            props = archipack_reference_point.datablock(o)
            if props is None:
                return {'CANCELLED'}
            sel = [obj for obj in context.selected_objects if obj != o and obj.parent != o]
            itM = o.matrix_world.inverted()
            # print("parent_to_reference parenting:%s objects" % (len(sel)))
            for child in sel:
                rs = child.matrix_world.to_3x3().to_4x4()
                loc = itM * child.matrix_world.translation
                child.parent = None
                child.matrix_parent_inverse.identity()
                child.location = Vector((0, 0, 0))
                child.parent = o
                child.matrix_world = rs
                child.location = loc
            return {'FINISHED'}
        else:
            self.report({'WARNING'}, "Archipack: Option only valid in Object mode")
            return {'CANCELLED'}
项目:bpy_lambda    作者:bcongdon    | 项目源码 | 文件源码
def interactive_hole(self, context, o):
        hole_obj = self.find_hole(o)
        if hole_obj is None:
            m = bpy.data.meshes.new("hole")
            hole_obj = bpy.data.objects.new("hole", m)
            context.scene.objects.link(hole_obj)
            hole_obj['archipack_hole'] = True
            hole_obj.parent = o
            hole_obj.matrix_world = o.matrix_world.copy()
            MaterialUtils.add_wall2_materials(hole_obj)
        hole = self.hole
        v = Vector((0, 0, 0))
        offset = Vector((0, -0.001, 0))
        size = Vector((self.x + 2 * self.frame_x, self.z + self.frame_x + 0.001, self.y))
        verts = hole.vertices(16, offset, v, v, size, v, 0, 0, shape_z=None, path_type='RECTANGLE')
        faces = hole.faces(16, path_type='RECTANGLE')
        matids = hole.mat(16, 0, 1, path_type='RECTANGLE')
        uvs = hole.uv(16, v, v, size, v, 0, 0, 0, 0, path_type='RECTANGLE')
        bmed.buildmesh(context, hole_obj, verts, faces, matids=matids, uvs=uvs)
        return hole_obj
项目:bpy_lambda    作者:bcongdon    | 项目源码 | 文件源码
def robust_hole(self, context, tM):
        hole = self.hole
        m = bpy.data.meshes.new("hole")
        o = bpy.data.objects.new("hole", m)
        o['archipack_robusthole'] = True
        context.scene.objects.link(o)
        v = Vector((0, 0, 0))
        offset = Vector((0, -0.001, 0))
        size = Vector((self.x + 2 * self.frame_x, self.z + self.frame_x + 0.001, self.y))
        verts = hole.vertices(16, offset, v, v, size, v, 0, 0, shape_z=None, path_type='RECTANGLE')
        verts = [tM * Vector(v) for v in verts]
        faces = hole.faces(16, path_type='RECTANGLE')
        matids = hole.mat(16, 0, 1, path_type='RECTANGLE')
        uvs = hole.uv(16, v, v, size, v, 0, 0, 0, 0, path_type='RECTANGLE')
        bmed.buildmesh(context, o, verts, faces, matids=matids, uvs=uvs)
        MaterialUtils.add_wall2_materials(o)
        o.select = True
        context.scene.objects.active = o
        return o
项目:bpy_lambda    作者:bcongdon    | 项目源码 | 文件源码
def setup_user_defined_post(self, o, post_x, post_y, post_z):
        self.user_defined_post = o
        x = o.bound_box[6][0] - o.bound_box[0][0]
        y = o.bound_box[6][1] - o.bound_box[0][1]
        z = o.bound_box[6][2] - o.bound_box[0][2]
        self.user_defined_post_scale = Vector((post_x / x, post_y / -y, post_z / z))
        m = o.data
        # create vertex group lookup dictionary for names
        vgroup_names = {vgroup.index: vgroup.name for vgroup in o.vertex_groups}
        # create dictionary of vertex group assignments per vertex
        self.vertex_groups = [[vgroup_names[g.group] for g in v.groups] for v in m.vertices]
        # uvs
        uv_act = m.uv_layers.active
        if uv_act is not None:
            uv_layer = uv_act.data
            self.user_defined_uvs = [[uv_layer[li].uv for li in p.loop_indices] for p in m.polygons]
        else:
            self.user_defined_uvs = [[(0, 0) for i in p.vertices] for p in m.polygons]
        # material ids
        self.user_defined_mat = [p.material_index for p in m.polygons]
项目:bpy_lambda    作者:bcongdon    | 项目源码 | 文件源码
def setup_manipulators(self):

        if len(self.manipulators) == 0:
            s = self.manipulators.add()
            s.prop1_name = "width"
            s = self.manipulators.add()
            s.prop1_name = "height"
            s.normal = Vector((0, 1, 0))

        for i in range(self.n_parts):
            p = self.parts[i]
            n_manips = len(p.manipulators)
            if n_manips < 1:
                m = p.manipulators.add()
                m.type_key = 'SIZE'
                m.prop1_name = 'length'
项目:bpy_lambda    作者:bcongdon    | 项目源码 | 文件源码
def verts(self):
        center, origin, size, radius = self.get_radius()
        is_not_circle = self.shape != 'CIRCLE'
        offset = Vector((0, self.altitude, 0))
        verts = self.window.vertices(self.curve_steps, offset, center, origin,
            size, radius, self.angle_y, 0, shape_z=None, path_type=self.shape)
        if self.out_frame:
            verts += self.frame.vertices(self.curve_steps, offset, center, origin,
                size, radius, self.angle_y, 0, shape_z=None, path_type=self.shape)
        if is_not_circle and self.out_tablet_enable:
            verts += self.out_tablet.vertices(self.curve_steps, offset, center, origin,
                Vector((size.x + 2 * self.out_tablet_x, size.y, size.z)),
                radius, self.angle_y, 0, shape_z=None, path_type='HORIZONTAL')
        if is_not_circle and self.in_tablet_enable:
            verts += self.in_tablet.vertices(self.curve_steps, offset, center, origin,
                Vector((size.x + 2 * (self.frame_x + self.in_tablet_x), size.y, size.z)),
                radius, self.angle_y, 0, shape_z=None, path_type='HORIZONTAL')
        if is_not_circle and self.blind_enable:
            verts += self.blind.vertices(self.curve_steps, offset, center, origin,
                Vector((-size.x, 0, 0)), radius, 0, 0, shape_z=None, path_type='HORIZONTAL')
        return verts
项目:bpy_lambda    作者:bcongdon    | 项目源码 | 文件源码
def setup_manipulators(self):
        if len(self.manipulators) == 4:
            return
        s = self.manipulators.add()
        s.prop1_name = "x"
        s.prop2_name = "x"
        s.type_key = "SNAP_SIZE_LOC"
        s = self.manipulators.add()
        s.prop1_name = "y"
        s.prop2_name = "y"
        s.type_key = "SNAP_SIZE_LOC"
        s = self.manipulators.add()
        s.prop1_name = "z"
        s.normal = Vector((0, 1, 0))
        s = self.manipulators.add()
        s.prop1_name = "altitude"
        s.normal = Vector((0, 1, 0))
项目:bpy_lambda    作者:bcongdon    | 项目源码 | 文件源码
def get_radius(self):
        """
            return center, origin, size, radius
        """
        if self.shape == 'ROUND':
            return self._get_round_radius()
        elif self.shape == 'ELLIPSIS':
            return self._get_ellipsis_radius()
        elif self.shape == 'CIRCLE':
            return self._get_circle_radius()
        elif self.shape == 'QUADRI':
            return self._get_quad_radius()
        elif self.shape in ['TRIANGLE', 'PENTAGON']:
            return self._get_tri_radius()
        else:
            return Vector((0, 0, 0)), Vector((0, 0, 0)), \
                Vector((self.x, self.z, 0)), Vector((0, 0, 0))
项目:bpy_lambda    作者:bcongdon    | 项目源码 | 文件源码
def __init__(self, p=None, v=None, p0=None, p1=None):
        """
            Init by either
            p: Vector or tuple origin
            v: Vector or tuple size and direction
            or
            p0: Vector or tuple 1 point location
            p1: Vector or tuple 2 point location
            Will convert any into Vector 2d
            both optionnals
        """
        Projection.__init__(self)
        if p is not None and v is not None:
            self.p = Vector(p).to_2d()
            self.v = Vector(v).to_2d()
        elif p0 is not None and p1 is not None:
            self.p = Vector(p0).to_2d()
            self.v = Vector(p1).to_2d() - self.p
        else:
            self.p = Vector((0, 0))
            self.v = Vector((0, 0))
项目:bpy_lambda    作者:bcongdon    | 项目源码 | 文件源码
def __init__(self, c, radius, a0, da):
        """
            a0 and da arguments are in radians
            c Vector 2d center
            radius float radius
            a0 radians start angle
            da radians delta angle from start to end
            a0 = 0   on the right side
            a0 = pi on the left side
            da > 0 CCW contrary-clockwise
            da < 0 CW  clockwise
            stored internally as radians
        """
        Circle.__init__(self, Vector(c).to_2d(), radius)
        self.a0 = a0
        self.da = da
项目:bpy_lambda    作者:bcongdon    | 项目源码 | 文件源码
def __init__(self, p=None, v=None, p0=None, p1=None, z_axis=None):
        """
            Init by either
            p: Vector or tuple origin
            v: Vector or tuple size and direction
            or
            p0: Vector or tuple 1 point location
            p1: Vector or tuple 2 point location
            Will convert any into Vector 3d
            both optionnals
        """
        if p is not None and v is not None:
            self.p = Vector(p).to_3d()
            self.v = Vector(v).to_3d()
        elif p0 is not None and p1 is not None:
            self.p = Vector(p0).to_3d()
            self.v = Vector(p1).to_3d() - self.p
        else:
            self.p = Vector((0, 0, 0))
            self.v = Vector((0, 0, 0))
        if z_axis is not None:
            self.z_axis = z_axis
        else:
            self.z_axis = Vector((0, 0, 1))