Exemplo n.º 1
0
    def setPlanarBaseSurface(self):
        '''
        set surface that is planar surface
        this surface will be made from additiveObj
        this surface will be used in offsetNonPlanarSurface()
        '''

        explodedSurfaces = rs.ExplodePolysurfaces(self.additiveObj)
        editPoint = []

        if len(explodedSurfaces) is 0:

            meshed = rhino.Geometry.Mesh.CreateFromBrep(
                rs.coercebrep(self.additiveObj))
            editPoint = rs.MeshVertices(meshed[0])
        else:

            for i in explodedSurfaces:
                meshed = rhino.Geometry.Mesh.CreateFromBrep(rs.coercebrep(i))
                vertices = rs.MeshVertices(meshed[0])
                editPoint.extend(vertices)

        rs.DeleteObjects(explodedSurfaces)

        xValues = [i[0] for i in editPoint]
        yValues = [i[1] for i in editPoint]

        xValues.sort()
        yValues.sort()

        xMin = xValues[0]
        xMax = xValues[-1]
        yMin = yValues[0]
        yMax = yValues[-1]

        lineForSur = []
        lineForSur.append(rs.AddLine((xMin, yMin, 0), (xMax, yMin, 0)))
        lineForSur.append(rs.AddLine((xMax, yMin, 0), (xMax, yMax, 0)))
        lineForSur.append(rs.AddLine((xMax, yMax, 0), (xMin, yMax, 0)))
        lineForSur.append(rs.AddLine((xMin, yMax, 0), (xMin, yMin, 0)))

        joinedCurve = rs.JoinCurves(lineForSur)
        rs.DeleteObjects(lineForSur)

        curveForSur = rs.OffsetCurve(joinedCurve, (0, 0, 1), 20)

        if len(curveForSur) > 1:
            curveForSur = rs.OffsetCurve(joinedCurve, (0, 0, 1), -20)

        self.basePlanarSurface = rs.AddPlanarSrf(curveForSur)
        rs.DeleteObjects(curveForSur)

        if self.basePlanarSurface is None:
            return False

        return True
Exemplo n.º 2
0
def getMeshSharedNormals(mesh):
    omesh=rs.MeshOffset(mesh,1)
    pts=rs.MeshVertices(mesh)
    ptso=rs.MeshVertices(omesh)
    vects=[]
    for p0,p1 in zip(pts,ptso):
        v=p1-p0
        vects.append(v)

    rs.DeleteObject(omesh)
    return vects
Exemplo n.º 3
0
def adjacent_faces(mesh_id):
    """Constructs a set of adjacent faces for each vertex.
    Returns a list of form
        [
          [0]: [face_index_1, face_index_2, ...]
          [1]: [face_index_1, ...]
               ...
        ]
    """
    vertices = rs.MeshVertices(mesh_id)
    face_vertices = rs.MeshFaceVertices(mesh_id)
    adjacency_list = [[] for _ in xrange(len(vertices))]
    face_planes = [
        rs.PlaneFitFromPoints(mu.get_face_points(mesh_id, face))
        for face in xrange(len(face_vertices))
    ]
    for next_face in xrange(len(face_vertices)):
        for vertex_index in face_vertices[next_face]:
            for face in adjacency_list[vertex_index]:
                # NOTE(mikhaildubov): we have to check the face planes as well because
                #                     of the way Rhinoceros works.
                if (face == next_face or rs.PlanePlaneIntersection(
                        face_planes[face], face_planes[next_face]) is None):
                    break
            else:
                adjacency_list[vertex_index].append(next_face)
    return adjacency_list
Exemplo n.º 4
0
def flow(mesh_id=None, step=1):
    """Performs one step of the face flow of the given mesh,
    replacing that mesh with a new one.
    """
    # If mesh_id is None, then get the mesh from the user.
    # Check that all its faces are correctly set up.
    mesh_id = mu.get_and_check_mesh(mesh_id)

    # Various precomputations (including motion vectors for each face)
    normals = get_motion_vectors(mesh_id, step)
    adj_faces = adjacent_faces(mesh_id)
    n = len(rs.MeshVertices(mesh_id))
    face_planes = mu.get_face_planes(mesh_id)

    # Shift all the planes by their normal vectors.
    # NOTE(mikhaildubov): This computation relies on the fact that normals are
    #                     listed in the same order as the corresponding faces.
    face_planes_translated = [
        translate_plane(face_planes[i], normals[i])
        for i in xrange(len(face_planes))
    ]

    # Calculate the intersections of the shifted planes.
    # Those are going to be the vertices of the updated mesh.
    new_vertices = []
    for i in xrange(n):
        adj_planes = [face_planes_translated[j] for j in adj_faces[i]]
        adj_planes_eq = [rs.PlaneEquation(plane) for plane in adj_planes]
        intersection_point = planes_intersection(adj_planes_eq)
        new_vertices.append(intersection_point)

    # Update the mesh
    new_mesh_id = rs.AddMesh(new_vertices, rs.MeshFaceVertices(mesh_id))
    rs.DeleteObject(mesh_id)
    return new_mesh_id
def get_face_points(mesh_id, face_index):
    """Returns a list of vertices that define the given face. The face_index argument
    should correspond to the order of faces as returned from rs.MeshFaceVertices().
    """
    vertices = rs.MeshVertices(mesh_id)
    face_vertices = rs.MeshFaceVertices(mesh_id)
    return [vertices[i] for i in face_vertices[face_index]]
Exemplo n.º 6
0
def mesh_from_rhino_mesh(guid):
    """ Create a mola mesh from rhino mesh

    Parameters
    ----------
    guid: guid of Rhino Mesh

    Returns
    -------
    mesh: mola.Mesh

    Example
    -------
    >>>import rhinoscriptsyntax as rs
    >>>import mola
    >>>from mola import module_rhino
    >>>
    >>>guid = rs.GetObject()
    >>>new_mesh = module_rhino.mesh_from_rhino_mesh(guid)
    """
    mesh=Mesh()
    vertices = rs.MeshVertices(guid)
    for v in vertices:
        mesh.vertices.append(Vertex(v[0],v[1],v[2]))
    faceVerts = rs.MeshFaceVertices(guid)
    for face in faceVerts:
        if face[2]==face[3]:
            mesh.faces.append(Face([mesh.vertices[face[0]],mesh.vertices[face[1]],mesh.vertices[face[2]]]))
        else:
            mesh.faces.append(Face([mesh.vertices[face[0]],mesh.vertices[face[1]],mesh.vertices[face[2]],mesh.vertices[face[3]]]))
    return mesh
Exemplo n.º 7
0
def create_targets(mesh, targets, resolution_mult, path, folder_name,
                   json_name):
    """ Creation of targets for curved slicing. """

    avg_face_area = max(rs.MeshArea([mesh])) / rs.MeshFaceCount(mesh)
    div_num = max(20, int(resolution_mult * avg_face_area))

    pts = []
    for target in targets:
        print(div_num)
        pts.extend(rs.DivideCurve(target, div_num))

    vs = rs.MeshVertices(mesh)
    vertices = []
    vertex_indices = []
    for p in pts:
        closest_vi = get_closest_point_index(p, vs)
        if closest_vi not in vertex_indices:
            ds_from_targets = [
                distance_of_pt_from_crv(vs[closest_vi], target)
                for target in targets
            ]
            if min(ds_from_targets) < 0.5:  # hardcoded threshold value
                vertices.append(vs[closest_vi])
                vertex_indices.append(closest_vi)

    save_json_file(vertex_indices, path, folder_name, json_name)
    return pts, vertices, vertex_indices
def flow(mesh_id=None, step=1):
    """Performs one step of the harmonic flow of the given mesh,
    replacing that mesh with a new one.
    """
    # TODO(mikhaildubov): This flow results in a degenerate case at the poles of sphere134.3dm.
    #                     Fix this by making it a true MCF (i.e. by using the angles).

    # If mesh_id is None, then get the mesh from the user.
    # Check that all its faces are correctly set up.
    mesh_id = mu.get_and_check_mesh(mesh_id)

    # Various precomputations (including motion vectors for each vertex)
    v = rs.MeshVertices(mesh_id)
    n = len(v)
    harmonic_vectors = get_motion_vectors(mesh_id, step)

    # Move each vertex by its motion vector
    new_vertices = []
    for i in xrange(n):
        new_vertices.append(rs.PointAdd(v[i], harmonic_vectors[i]))

    # Update the mesh
    new_mesh_id = rs.AddMesh(new_vertices, rs.MeshFaceVertices(mesh_id))
    rs.DeleteObject(mesh_id)
    return new_mesh_id
def exportODMesh():

    file = tempfile.gettempdir() + os.sep + "ODVertexData.txt"

    obj = rs.GetObject("Select mesh", rs.filter.mesh, True)
    vertices = rs.MeshVertices(obj)
    faces = rs.MeshFaceVertices(obj)

    f = open(file, "w")

    f.write("VERTICES:" + str(len(vertices)) + "\n")
    for vert in vertices:
        f.write(
            str(vert[0]) + " " + str(vert[2]) + " " + str(vert[1] * -1) + "\n")

    f.write("POLYGONS:" + str(len(faces)) + "\n")
    for face in faces:
        fpt = []
        for p in face:
            if str(
                    p
            ) not in fpt:  #need this check as when there's 3pt polys somehow, it gives 4 points
                fpt.append(str(p))
        line = ",".join(fpt)
        line += ";;" + "Default" + ";;" + "FACE" + "\n"
        f.write(line)
    f.close()
Exemplo n.º 10
0
def crackpolygon(meshes, count):
    tempMeshes = meshes
    newMeshes = []
    if count == 0:
        return 1
    else:
        for mesh in tempMeshes:

            if rs.MeshVertexCount(mesh) != 3 and rs.MeshVertexCount(mesh) != 4:
                countV = rs.MeshVertexCount(mesh)
                print "mesh has too many vertices"
            else:
                #print "Cool"
                centroid = rs.MeshAreaCentroid(mesh)
                normals = rs.MeshFaceNormals(mesh)
                centroid = rs.PointAdd(centroid, normals[0] * (count / 5))
                vertices = rs.MeshVertices(mesh)
                for i in range(1, len(vertices)):
                    newVertices = []
                    newVertices.append(vertices[i])
                    newVertices.append(centroid)
                    newVertices.append(vertices[i - 1])
                    newFaces = [[0, 1, 2]]
                    newMesh = rs.AddMesh(newVertices, newFaces)
                    newMeshes.append(newMesh)

                newVertices = []
                newVertices.append(vertices[0])
                newVertices.append(centroid)
                newVertices.append(vertices[len(vertices) - 1])
                newFaces = [[0, 1, 2]]
                newMesh = rs.AddMesh(newVertices, newFaces)
                newMeshes.append(newMesh)

        return crackpolygon(newMeshes, count - 1)
def draw_motion_vectors(mesh_id=None, step=1):
    """Draws the motion vectors for the harmonic flow of the given mesh."""
    mesh_id = mu.get_and_check_mesh(mesh_id)
    harmonic_vectors = get_motion_vectors(mesh_id, step)
    v = rs.MeshVertices(mesh_id)
    n = len(v)
    for i in xrange(n):
        vu.VectorDraw(harmonic_vectors[i], v[i])
Exemplo n.º 12
0
def RenderAgentsOnMesh(strMesh, arrIndexes):
    arrVertices     = rs.MeshVertices(strMesh)
    arrVertexColors = []
    for i in range(len(arrVertices)):
        arrVertexColors.append( [255,255,255] )
    for index in arrIndexes:
        arrVertexColors[index] = [0,0,0]
    rs.MeshVertexColors (strMesh , arrVertexColors)
Exemplo n.º 13
0
def add_element_set(structure, guids, name):
    """ Adds element set information from Rhino curve and mesh guids.

    Parameters
    ----------
    structure : obj
        Structure object to update.
    guids : list
        Rhino curve and Rhino mesh guids.
    name : str
        Name of the new element set.

    Returns
    -------
    None

    Notes
    -----
    - Meshes representing solids must have 'solid' in their name.

    """

    elements = []

    for guid in guids:

        if rs.IsCurve(guid):

            sp = structure.check_node_exists(rs.CurveStartPoint(guid))
            ep = structure.check_node_exists(rs.CurveEndPoint(guid))
            element = structure.check_element_exists([sp, ep])
            if element is not None:
                elements.append(element)

        if rs.IsMesh(guid):

            vertices = rs.MeshVertices(guid)
            faces = rs.MeshFaceVertices(guid)

            if 'solid' in rs.ObjectName(guid):
                nodes = [structure.check_node_exists(i) for i in vertices]
                element = structure.check_element_exists(nodes)
                if element is not None:
                    elements.append(element)

            else:
                for face in faces:
                    nodes = [
                        structure.check_node_exists(vertices[i]) for i in face
                    ]
                    if nodes[2] == nodes[3]:
                        nodes = nodes[:-1]
                    element = structure.check_element_exists(nodes)
                    if element is not None:
                        elements.append(element)

    structure.add_set(name=name, type='element', selection=elements)
Exemplo n.º 14
0
def mesh_to_mesh(rhino_mesh,trg_len,vis):
    
    print rhino_mesh
    crvs = rs.DuplicateMeshBorder(rhino_mesh)
    
    
    
    vertices = [map(float, vertex) for vertex in rs.MeshVertices(rhino_mesh)]
    faces = map(list, rs.MeshFaceVertices(rhino_mesh))
    
    mesh  = Mesh.from_vertices_and_faces(vertices, faces)
    
    
    pts_objs = rs.GetObjects("Fixed Points",1)
    rs.EnableRedraw(False)
    if pts_objs:
        pts_fixed = [rs.PointCoordinates(obj) for obj in pts_objs]
        
        pts = []
        index_key = {}
        count = 0
        for k, a in mesh.vertices_iter(True):
            pts.append((a['x'], a['y'], a['z'])) 
            index_key[count] = k
            count += 1
        
        fixed = [] 
        for pt_fix in pts_fixed:
            index = rs.PointArrayClosestPoint(pts,pt_fix)
            fixed.append(index_key[index])
    
    

      
    edge_lengths = []
    for u, v in mesh.edges():
        edge_lengths.append(mesh.edge_length(u, v))
    target_start = max(edge_lengths)/2  
     
    id = rs.coerceguid(rhino_mesh, True)
    mesh_rhino_obj = rs.coercemesh(id, False)
    
    boundary = set(mesh.vertices_on_boundary())
    user_func = wrapper_2(crvs,mesh_rhino_obj,fixed,boundary,vis)
        
    rs.HideObject(rhino_mesh)
        
    remesh(mesh,trg_len,
       tol=0.1, divergence=0.01, kmax=400,
       target_start=target_start, kmax_approach=200,
       verbose=False, allow_boundary=True,
       ufunc=user_func)  
        
    rs.DeleteObject(rhino_mesh)
    return draw_light(mesh,temp = False) 
def randommeshcolors():
    mesh_id = rs.GetObject("Mesh to randomize", 32, True, True)
    if not mesh_id: return

    verts = rs.MeshVertices(mesh_id)
    faces = rs.MeshFaceVertices(mesh_id)
    colors = []
    for vert in verts:
        rgb = random() * 255, random() * 255, random() * 255
        colors.append(rgb)
    rs.AddMesh(verts, faces, vertex_colors=colors)
    rs.DeleteObject(mesh_id)
Exemplo n.º 16
0
def mesh_from_rhino_mesh(obj):
    mesh=Mesh()
    vertices = rs.MeshVertices(obj)
    for v in vertices:
        mesh.vertices.append(Vertex(v[0],v[1],v[2]))
    faceVerts = rs.MeshFaceVertices(obj)
    for face in faceVerts:
        if face[2]==face[3]:
            mesh.faces.append(Face(mesh.vertices[face[0]],mesh.vertices[face[1]],mesh.vertices[face[2]]))
        else:
            mesh.faces.append(Face(mesh.vertices[face[0]],mesh.vertices[face[1]],mesh.vertices[face[2]],mesh.vertices[face[3]]))
    return mesh
Exemplo n.º 17
0
def mesh_from_guid(guid, **kwargs):
    """Creates an instance of a compAS mesh class from an identifier
    in Rhino/Grasshopper.

    This function is almost identical to ``mesh_from_guid`` in the core
    framework, but there were some import issues when used from within
    Grasshopper, but eventually, it should be migrated into the core.
    """
    trimesh = ghcomp.Triangulate(rs.coercemesh(guid))[0]
    vertices = [map(float, vertex) for vertex in rs.MeshVertices(trimesh)]
    faces = map(list, rs.MeshFaceVertices(trimesh))
    faces = [face[:-1] if face[-2] == face[-1] else face for face in faces]
    mesh = Mesh.from_vertices_and_faces(vertices, faces)
    mesh.attributes.update(kwargs)
    return mesh
Exemplo n.º 18
0
    def ProximityAnalysis():
        mesh_id = rs.GetObject("Mesh for proximity analysis", 32, True, True)
        if not mesh_id: return
        brep_id = rs.GetObject("Surface for proximity test", 8+16, False, True)
        if not brep_id: return

        vertices = rs.MeshVertices(mesh_id)
        faces = rs.MeshFaceVertices(mesh_id)
        arrD = VertexValueArray(vertices, brep_id)
        minD = min(arrD)
        maxD = max(arrD)
        colors = []
        for i in range(len(vertices)):
            proxFactor = (arrD[i]-minD)/(maxD-minD)
            colors.append( (255, 255*proxFactor, 255*proxFactor) )
        rs.AddMesh(vertices, faces, vertex_colors=colors)
        rs.DeleteObject(mesh_id)
Exemplo n.º 19
0
def mesh_dict(mesh_list):
    '''
     A separate function for gathering the chosen meshes vertices and
     face vertices. Then storing them in a dictionary. Needed steps for
     generating them later.
    '''

    mesh_dict = {}
    len_mesh_list = len(mesh_list)
    for n in range(len_mesh_list):
        vertlist = []
        verts = rs.MeshVertices(mesh_list[n])
        vertlist.append(verts)
        face_verts = rs.MeshFaceVertices(mesh_list[n])
        vertlist.append(face_verts)
        mesh = mesh_list[n]
        mesh_dict[mesh] = vertlist
    return mesh_dict
Exemplo n.º 20
0
def checkConcaveConvex(curve):
    CH = ConvexHull2d()
    curve_pts = rs.CurvePoints(curve)
    curve_pts.pop(-1)
    chull_pts = CH.convex_hull(curve_pts)

    if len(chull_pts) == len(curve_pts):  # no need to mesh
        meshcurves = curve
        ##print 'is convex' ## for testing
    else:
        meshParam = Rhino.Geometry.MeshingParameters.Coarse
        mesh = Rhino.Geometry.Mesh.CreateFromPlanarBoundary(curve, meshParam)
        mesh = sc.doc.Objects.AddMesh(mesh)
        vertice_lst = rs.MeshVertices(mesh)
        face_lst = rs.MeshFaceVertices(mesh)
        meshcurves = mesh2curve(face_lst, vertice_lst)
        ## print 'is concave' ## for testing
    return meshcurves
def get_motion_vectors(mesh_id, step):
    """Returns a list of motion vectors in the same order as the vertices in the
    Rhino representation of the input mesh. Uses adjacency list instead of adjacency
    matrix, thus improving the running time from O(|V|^2) to O(|V|+|E|).
    """
    adj_list = adjacency_list(mesh_id)
    vertex_face_ind = vertex_face_index(mesh_id)
    v = rs.MeshVertices(mesh_id)
    n = len(v)
    harmonic_vectors = []
    for i in xrange(n):
        p = v[i]
        # Initialize the harmonic vector as a zero vector
        harmonic_vector = rs.VectorCreate([0, 0, 0], [0, 0, 0])
        # Sum up all the vectors pointing to adjacent vertices
        adj = get_adjacent_vertices_in_order(mesh_id, adj_list,
                                             vertex_face_ind, i)
        for j in xrange(len(adj)):
            # q_j vertices
            q_prev = v[adj[(j - 1) % len(adj)]]
            q_curr = v[adj[j]]
            q_next = v[adj[(j + 1) % len(adj)]]
            # pq vectors
            pq_prev = rs.VectorCreate(q_prev, p)
            pq = rs.VectorCreate(q_curr, p)
            pq_next = rs.VectorCreate(q_next, p)
            # vectors between q vertices
            q_prev_q_curr = rs.VectorCreate(q_curr, q_prev)
            q_next_q_curr = rs.VectorCreate(q_curr, q_next)
            # Angles needed for MCF
            alpha = vu.VectorAngleRadians(rs.VectorReverse(pq), q_prev_q_curr)
            beta = vu.VectorAngleRadians(rs.VectorReverse(pq), q_next_q_curr)
            # Continue computing the sum for the harmonic vector
            # TODO(mikhaildubov): The formula with cotangents fails on sphere134.3dm.
            #                     Check it and also ensure that the input mesh is triangulated.
            harmonic_coeff = 1  #(cotan(alpha) + cotan(beta)) / 2
            harmonic_vector = rs.VectorScale(rs.VectorAdd(harmonic_vector, pq),
                                             harmonic_coeff)
        # Rescale
        # TODO(mikhaildubov): use this for true MCF:
        #harmonic_vector = rs.VectorScale(harmonic_vector, step)
        harmonic_vector = vu.VectorResize(harmonic_vector, step)
        harmonic_vectors.append(harmonic_vector)
    return harmonic_vectors
Exemplo n.º 22
0
def obj_export(mesh, file_path):

    if not file_path.endswith('.obj'):
        file_path = file_path + '.obj'

    with open(file_path, 'w') as file_obj:
        file_obj.write('# Livestock OBJ exporter\n')
        for vert in rs.MeshVertices(mesh):
            file_obj.write('v ' + str(vert.X) + ' ' + str(vert.Y) + ' ' +
                           str(vert.Z) + '\n')
        for fvert in rs.MeshFaceVertices(mesh):
            if len(fvert) == 3:
                file_obj.write('f ' + str(fvert[0] + 1) + ' ' +
                               str(fvert[1] + 1) + ' ' + str(fvert[2] + 1) +
                               '\n')
            elif len(fvert) == 4:
                file_obj.write('f ' + str(fvert[0] + 1) + ' ' +
                               str(fvert[1] + 1) + ' ' + str(fvert[2] + 1) +
                               ' ' + str(fvert[3] + 1) + '\n')
Exemplo n.º 23
0
def add_element_set(structure, guids, name):
    added_ele = set()

    for guid in guids:
        if rs.IsMesh(guid):
            vertices = rs.MeshVertices(guid)
            faces = rs.MeshFaceVertices(guid)
            nodes = [structure.add_node(vertex) for vertex in vertices]

            for f in rs.MeshFaceVertices(guid):
                nodes = [structure.check_node_exists(vertices[i]) for i in f]

                if nodes[-1] == nodes[-2]:
                    del nodes[-1]

                ekey = structure.add_element(nodes=nodes, type='ShellElement')
                if ekey is not None:
                    added_ele.add(ekey)

    structure.add_set(name=name, type='element', selection=list(added_ele))
Exemplo n.º 24
0
    def setSurfaceForSlicing(self):

        explodedSurfaces = rs.ExplodePolysurfaces(self.addtiveObj)
        editPoint = []

        #get editPoint from polysurfaces
        if len(explodedSurfaces) == 0:
            #use obj
            meshed = rhino.Geometry.Mesh.CreateFromBrep(
                rs.coercebrep(self.addtiveObj))
            editPoint = rs.MeshVertices(meshed[0])

        else:
            for i in explodedSurfaces:
                meshed = rhino.Geometry.Mesh.CreateFromBrep(rs.coercebrep(i))
                vertices = rs.MeshVertices(meshed[0])
                editPoint.extend(vertices)

        rs.DeleteObjects(explodedSurfaces)

        minValue = []
        maxValue = []
        basePointForPlane = None
        basePointForDistance = None

        for i in range(len(editPoint)):
            if i == 0:
                basePointForPlane = editPoint[0]
                basePointForDistance = editPoint[0]

                for j in range(3):
                    minValue.append(editPoint[0][j])
                    maxValue.append(editPoint[0][j])
                continue

            else:
                if basePointForPlane[2] > editPoint[i][2]:
                    basePointForPlane = editPoint[i]
                if basePointForDistance[2] < editPoint[i][2]:
                    basePointForDistance = editPoint[i]

                for j in range(3):
                    if minValue[j] > editPoint[i][j]:
                        minValue[j] = editPoint[i][j]
                    elif maxValue[j] < editPoint[i][j]:
                        maxValue[j] = editPoint[i][j]

        #why?
        self.basePointForPlane = basePointForPlane

        plane = rs.PlaneFromNormal(basePointForPlane, self.normalVec)

        #calculating distance printing
        self.calcDistance(plane, editPoint)

        #make base surface
        pntForSur = []
        line = (minValue[0], minValue[1],
                minValue[2]), (minValue[0], minValue[1], maxValue[2])
        pntForSur.append(rs.LinePlaneIntersection(line, plane))
        line = (minValue[0], maxValue[1],
                minValue[2]), (minValue[0], maxValue[1], maxValue[2])
        pntForSur.append(rs.LinePlaneIntersection(line, plane))
        line = (maxValue[0], maxValue[1],
                minValue[2]), (maxValue[0], maxValue[1], maxValue[2])
        pntForSur.append(rs.LinePlaneIntersection(line, plane))
        line = (maxValue[0], minValue[1],
                minValue[2]), (maxValue[0], minValue[1], maxValue[2])
        pntForSur.append(rs.LinePlaneIntersection(line, plane))

        lineForSur = []

        for i in range(4):
            lineForSur.append(rs.AddLine(pntForSur[i], pntForSur[(i + 1) % 4]))

        joinedCurve = rs.JoinCurves(lineForSur)
        rs.DeleteObjects(lineForSur)

        curveForSur = rs.OffsetCurve(joinedCurve, rs.CurveNormal(joinedCurve),
                                     30)

        self.sliceSurface = rs.AddPlanarSrf(curveForSur)

        if len(curveForSur) > 1 or rs.IsPointOnSurface(
                self.sliceSurface, rs.CurveStartPoint(joinedCurve)) is False:

            rs.DeleteObjects(curveForSur)
            if self.sliceSurface is not None:
                rs.DeleteObject(self.sliceSurface)

            curveForSur = rs.OffsetCurve(joinedCurve,
                                         rs.CurveNormal(joinedCurve), -30)
            self.sliceSurface = rs.AddPlanarSrf(curveForSur)
        rs.DeleteObjects(joinedCurve)
        rs.DeleteObjects(curveForSur)

        self.fixedLayerHeight = float(
            self.gcoder.getLayerHeight() *
            (1.0 / math.cos(math.radians(self.angleOfSurface))))

        self.addtiveObj = rs.CopyObject(self.addtiveObj,
                                        (0, 0, self.fixedLayerHeight * 0.9))
        self.sliceSurface = rs.MoveObject(self.sliceSurface,
                                          (0, 0, self.fixedLayerHeight * 0.9))
Exemplo n.º 25
0
def get_mesh_vertices_and_faces(guid):
    if not guid:
        return
    vertices = [map(float, vertex) for vertex in rs.MeshVertices(guid)]
    faces = map(list, rs.MeshFaceVertices(guid))
    return vertices, faces
Exemplo n.º 26
0
def get_mesh_vertex_coordinates(guid):
    vertices = []
    if guid:
        vertices = [map(float, vertex) for vertex in rs.MeshVertices(guid)]
    return vertices
Exemplo n.º 27
0
 def get_vertices_and_faces(self):
     vertices = [map(float, vertex) for vertex in rs.MeshVertices(self.guid)]
     faces = map(list, rs.MeshFaceVertices(self.guid))
     return vertices, faces
Exemplo n.º 28
0
 def get_vertex_coordinates(self):
     return [map(float, vertex) for vertex in rs.MeshVertices(self.guid)]
Exemplo n.º 29
0
def add_nodes_elements_from_layers(structure,
                                   layers,
                                   line_type=None,
                                   mesh_type=None,
                                   acoustic=False,
                                   thermal=False):
    """ Adds node and element data from Rhino layers to Structure object.

    Parameters
    ----------
    structure : obj
        Structure object to update.
    layers : list
        Layers to extract nodes and elements.
    line_type : str
        Element type for lines.
    mesh_type : str
        Element type for meshes.
    acoustic : bool
        Acoustic properties on or off.
    thermal : bool
        Thermal properties on or off.

    Returns
    -------
    list
        Node keys that were added to the Structure.
    list
        Element keys that were added to the Structure.

    """

    if isinstance(layers, str):
        layers = [layers]

    created_nodes = set()
    created_elements = set()

    for layer in layers:
        elset = set()
        for guid in rs.ObjectsByLayer(layer):

            if line_type and rs.IsCurve(guid):

                sp_xyz = rs.CurveStartPoint(guid)
                ep_xyz = rs.CurveEndPoint(guid)
                sp = structure.add_node(sp_xyz)
                ep = structure.add_node(ep_xyz)
                sp_ep = [sp, ep]
                created_nodes.add(sp)
                created_nodes.add(ep)
                ez = subtract_vectors(ep_xyz, sp_xyz)

                try:
                    dic = json.loads(rs.ObjectName(guid).replace("'", '"'))
                    ex = dic.get('ex', None)
                    ey = dic.get('ey', None)
                    if ex and not ey:
                        ey = cross_vectors(ex, ez)
                except:
                    ex = None
                    ey = None
                axes = {'ex': ex, 'ey': ey, 'ez': ez}

                e = structure.add_element(nodes=sp_ep,
                                          type=line_type,
                                          acoustic=acoustic,
                                          thermal=thermal,
                                          axes=axes)
                if e is not None:
                    created_elements.add(e)
                    elset.add(e)

            elif mesh_type and rs.IsMesh(guid):

                vertices = rs.MeshVertices(guid)
                nodes = [structure.add_node(vertex) for vertex in vertices]
                created_nodes.update(nodes)

                if mesh_type in [
                        'HexahedronElement', 'TetrahedronElement',
                        'SolidElement', 'PentahedronElement'
                ]:
                    e = structure.add_element(nodes=nodes,
                                              type=mesh_type,
                                              acoustic=acoustic,
                                              thermal=thermal)
                    if e is not None:
                        created_elements.add(e)
                        elset.add(e)

                else:
                    try:
                        dic = json.loads(rs.ObjectName(guid).replace("'", '"'))
                        ex = dic.get('ex', None)
                        ey = dic.get('ey', None)
                        if ex and ey:
                            ez = cross_vectors(ex, ey)
                        else:
                            ez = None
                    except:
                        ex = None
                        ey = None
                        ez = None
                    axes = {'ex': ex, 'ey': ey, 'ez': ez}

                    for face in rs.MeshFaceVertices(guid):
                        nodes = [
                            structure.check_node_exists(vertices[i])
                            for i in face
                        ]
                        if nodes[-1] == nodes[-2]:
                            del nodes[-1]
                        e = structure.add_element(nodes=nodes,
                                                  type=mesh_type,
                                                  acoustic=acoustic,
                                                  thermal=thermal,
                                                  axes=axes)
                        if e is not None:
                            created_elements.add(e)
                            elset.add(e)

        structure.add_set(name=layer, type='element', selection=list(elset))

    return list(created_nodes), list(created_elements)
Exemplo n.º 30
0
 def findAxis(self, point):
     norms = rs.MeshVertexNormals(self.mesh)
     verts = rs.MeshVertices(self.mesh)
     param = rs.PointArrayClosestPoint(verts, point)
     axis = norms[param]
     return axis