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
Example #2
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
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]]
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()
Example #5
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
Example #6
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 vertex_face_index(mesh_id):
    """Returns an auxiliary index containing sets of adjacent faces for each vertex."""
    n = rs.MeshVertexCount(mesh_id)
    adj = [set() for _ in xrange(n)]
    for face_index, face_vertices in enumerate(rs.MeshFaceVertices(mesh_id)):
        for vertex_index in face_vertices:
            adj[vertex_index].add(face_index)
    return adj
Example #8
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)
Example #9
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) 
Example #10
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))
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)
Example #12
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
def adjacency_list(mesh_id):
    """Builds an adjacency list of the mesh, taking O(|V|+|E|) space."""
    n = rs.MeshVertexCount(mesh_id)
    adj = [set() for _ in xrange(n)]
    for face in rs.MeshFaceVertices(mesh_id):
        for i in xrange(len(face)):
            a = face[i]
            b = face[(i + 1) % len(face)]
            # NOTE: Rhinoceros occasionally has duplicate vertices in face representations,
            #       so we should prevent vertices from being adjacent to themselves in the list.
            if a != b:
                adj[a].add(b)
                adj[b].add(a)
    return adj
Example #14
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
Example #15
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)
Example #16
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
Example #17
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
Example #18
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')
def get_adjacent_vertices_in_order(mesh_id, adj_list, vertex_face_ind, i):
    adj_vertices = adj_list[i].copy()
    adj_vertices_in_order = [adj_vertices.pop()]
    face_vertices = rs.MeshFaceVertices(mesh_id)

    def get_next_vertex(last_vertex):
        for adj_face in vertex_face_ind[last_vertex]:
            for vertex in face_vertices[adj_face]:
                if vertex in adj_vertices:
                    return vertex
        # NOTE(mikhaildubov): Depending on the mesh, we may need to get the last one manually
        #                     (e.g. this is the case for a dipyramid).
        return list(adj_vertices)[0]

    while adj_vertices:
        last_vertex = adj_vertices_in_order[-1]
        next_vertex = get_next_vertex(last_vertex)
        adj_vertices.remove(next_vertex)
        adj_vertices_in_order.append(next_vertex)
        last_vertex = next_vertex

    return adj_vertices_in_order
Example #20
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
Example #21
0
 def get_face_vertices(self):
     return map(list, rs.MeshFaceVertices(self.guid))
Example #22
0
def add_nodes_elements_from_layers(structure,
                                   layers,
                                   line_type=None,
                                   mesh_type=None,
                                   thermal=False,
                                   pA=None,
                                   pL=None):
    """ Adds node and element data from Rhino layers to the Structure object.

    Parameters
    ----------
    structure : obj
        Structure object to update.
    layers : list
        Layer string names to extract nodes and elements.
    line_type : str
        Element type for line objects.
    mesh_type : str
        Element type for mesh objects.
    thermal : bool
        Thermal properties on or off.
    pA : float
        Mass area density [kg/m2].
    pL : float
        Mass length density [kg/m].

    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]

    added_nodes = set()
    added_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)
                ez = subtract_vectors(ep_xyz, sp_xyz)
                L = length_vector(ez)
                m = 0.5 * L * pL if pL else None

                sp = structure.add_node(xyz=sp_xyz, mass=m)
                ep = structure.add_node(xyz=ep_xyz, mass=m)
                added_nodes.add(sp)
                added_nodes.add(ep)

                try:
                    name = rs.ObjectName(guid).replace("'", '"')

                    if name[0] in ['_', '^']:
                        name = name[1:]

                    dic = json.loads(name)
                    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}

                ekey = structure.add_element(nodes=[sp, ep],
                                             type=line_type,
                                             thermal=thermal,
                                             axes=axes)

                if (line_type == 'BeamElement') and (ex is None):

                    if (ez[0] == 0) and (ez[1] == 0):

                        print(
                            '***** WARNING: vertical BeamElement with no ex axis, element {0} *****'
                            .format(ekey))

                if ekey is not None:
                    added_elements.add(ekey)
                    elset.add(ekey)

            elif mesh_type and rs.IsMesh(guid):

                mesh = mesh_from_guid(Mesh(), guid)

                vertices = rs.MeshVertices(guid)
                nodes = []
                masses = []

                for c, vertex in enumerate(vertices):
                    m = mesh.vertex_area(c) * pA if pA else None
                    masses.append(m)
                    nodes.append(structure.add_node(xyz=vertex, mass=m))

                added_nodes.update(nodes)

                if mesh_type in [
                        'HexahedronElement', 'TetrahedronElement',
                        'SolidElement', 'PentahedronElement'
                ]:
                    ekey = structure.add_element(nodes=nodes,
                                                 type=mesh_type,
                                                 thermal=thermal)

                    if ekey is not None:
                        added_elements.add(ekey)
                        elset.add(ekey)

                elif mesh_type == 'MassElement':

                    nodei = 0

                    for node in nodes:

                        ekey = structure.add_element(nodes=[node],
                                                     type=mesh_type,
                                                     thermal=thermal,
                                                     mass=masses[nodei])
                        nodei += 1

                        if ekey is not None:
                            added_elements.add(ekey)
                            elset.add(ekey)

                else:

                    try:
                        name = rs.ObjectName(guid).replace("'", '"')

                        if name[0] in ['_', '^']:
                            name = name[1:]

                        dic = json.loads(name)
                        ex = dic.get('ex', None)
                        ey = dic.get('ey', None)
                        ez = dic.get('ez', None)

                        if (ex and ey) and (not ez):
                            ez = cross_vectors(ex, ey)

                    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]

                        ekey = structure.add_element(nodes=nodes,
                                                     type=mesh_type,
                                                     thermal=thermal,
                                                     axes=axes)
                        if ekey is not None:
                            added_elements.add(ekey)
                            elset.add(ekey)

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

    return list(added_nodes), list(added_elements)
Example #23
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)
Example #24
0
import rhinoscriptsyntax as rs
from compas_pattern.cad.rhino.objects.surface import RhinoSurface
from compas_pattern.datastructures.mesh.mesh import Mesh
from compas_pattern.algorithms.relaxation.constraints import automated_smoothing_constraints
from compas_pattern.algorithms.relaxation.constraints import automated_smoothing_surface_constraints
from compas_pattern.algorithms.relaxation.relaxation import constrained_smoothing
from compas_rhino.artists import MeshArtist

guid = rs.GetObject('get mesh', filter=32)
srf_guid = rs.GetObject('get surface', filter=8)
crv_guids = rs.GetObjects('get curves', filter=4)
pt_guids = rs.GetObjects('get points', filter=1)
rs.EnableRedraw(False)
vertices = rs.MeshVertices(guid)
faces = [list(face) for face in rs.MeshFaceVertices(guid)]

mesh = Mesh.from_vertices_and_faces(vertices, faces)

if srf_guid is not None:
    constraints = automated_smoothing_surface_constraints(
        mesh, RhinoSurface(srf_guid))
else:
    constraints = {}
if crv_guids is not None:
    for vkey in mesh.vertices():
        if not mesh.is_vertex_on_boundary(vkey):
            for crv_guid in crv_guids:
                if rs.IsPointOnCurve(crv_guid, mesh.vertex_coordinates(vkey)):
                    constraints[vkey] = crv_guid
                    break
Example #25
0
import compas
import rhinoscriptsyntax as rs

from compas.datastructures import Mesh

rmesh = rs.ObjectsByLayer('mesh')
vertices = rs.MeshVertices(rmesh)
faces = rs.MeshFaceVertices(rmesh)

mesh = Mesh.from_vertices_and_faces(vertices, faces)
mesh.to_json('flat_10x10.json')
Example #26
0
    v = 0.5
if z is None:
    z = 0
if ratio1 is None:
    ratio1 = 0.5
if ratio2 is None:
    ratio2 = 0.5

print(u, v, z)

# vertices
vertices = rs.MeshVertices(quad_mesh)
num_vertices = len(vertices)

# faces
faces = rs.MeshFaceVertices(quad_mesh)
num_faces = len(faces)
vpface = [len(f) for f in faces]

# edges
half_edges = {(faces[i][j], faces[i][(j + 1) % vpface[i]]): i
              for i in range(num_faces) for j in range(vpface[i])}
edges = [(i, j) for i, j in list(half_edges.keys()) if i < j]
num_edges = len(edges)

# neighbors
vs_nbe = [[] for _ in range(num_vertices)]
for i in range(num_edges):
    v1, v2 = edges[i]
    vs_nbe[v1].append(i)
    vs_nbe[v2].append(i)
Example #27
0
def get_mesh_face_vertices(guid):
    faces = []
    if guid:
        temp = rs.MeshFaceVertices(guid)
        faces = map(list, temp)
    return faces
Example #28
0
def mesh_from_guid(guid):
    vertices = rs.MeshVertices(guid)
    faces = [list(face) for face in rs.MeshFaceVertices(guid)]
    mesh = Mesh.from_vertices_and_faces(vertices, faces)
    return mesh
Example #29
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
Example #30
0
def MeshVtxAdjacentVtxs (strMesh, index, blnAbsolutConnections=False, blnCreate=False): 
    """---------------------------------------------------------------------------------------------------------------------------------------
    MeshVtxAdjacentVtxs
    finds the adjecent vertices on a mesh for a given index of a vertex.
    written by Ezio Blasetti. Last Revision 062411.
    
    Syntax
    MeshVtxAdjacentVtxs (strMesh, index, blnAbsolutConnections, blnCreate)
    
    Parameters
    strMesh                       Required. String.  The identifier of a mesh object.
    index                         Required. Integer. The index of a vertex object inside the array returned from rs.MeshVertices method.
                                                     Use rs.MeshVertexCount for the length of that array.
    blnAbsolutConnections         Optional. Boolean. If True only the end points of the adjacent edges will be returned.
                                                     Note, if false, all the vertices of the adjacent faces will be returned.
    blnCreate                     Optional. Boolean. Create the adjacent points. If false, points are not created.
    
    Returns
    Array                         If blnCreate is equal to True , an array containing 3D adjacent points if successful.
    Array                         If blnCreate is equal to False, an array containing the indexes of the adjacent vetrices if successful.
    None                          If not successful, or on error.
    
    
    Example
    import rhinoscriptsyntax as rs
    strObject        = rs.GetObject("Select the mesh", 32)
    intRndVtxIndex   = 0
    arr              = MeshVtxAdjacentVtxs (strObject, intRndVtxIndex, True, True)
    ---------------------------------------------------------------------------------------------------------------------------------------"""
    """custom function"""
    #-----------------------------------------------------------------------------------------------------------------------------------------
    def CullDuplicates(seq, idfun=None):  
        # order preserving 
        if idfun is None: 
            def idfun(x): return x 
        seen = {} 
        result = [] 
        for item in seq: 
            marker = idfun(item) 
            if marker in seen: continue 
            seen[marker] = 1 
            result.append(item) 
        return result
    #-----------------------------------------------------------------------------------------------------------------------------------------
    MeshVtxAdjacentVtxs = []
    if rs.IsMesh(strMesh)==False : 
        print "strMesh is not an mesh"
        return None
    if type(index)==type("string"):
        print "index is not an integer"
        return None
    if type(index)==type(0.1): index = int(index)

    arrVertices     = rs.MeshVertices    (strMesh)
    arrFaceVertices = rs.MeshFaceVertices(strMesh)

    intCount = 0
    arrAdjacentVtxs = []
    for arrFace in arrFaceVertices:
        blnIsAdjacent = False
        for arrVtxIndex in arrFace:
            if arrVtxIndex == index :
                blnIsAdjacent = True
        if blnIsAdjacent :
            if blnAbsolutConnections :
                if arrFace[2]==arrFace[3] :
                    for arrVtxIndex in arrFace :
                        if arrVtxIndex != index :
                            arrAdjacentVtxs.append( arrVtxIndex)
                else :
                    if index == arrFace[0] :
                        arrAdjacentVtxs.append( arrFace[3] )
                        arrAdjacentVtxs.append( arrFace[1] )
                    elif index == arrFace[1] :
                        arrAdjacentVtxs.append( arrFace[0] )
                        arrAdjacentVtxs.append( arrFace[2] )
                    elif index == arrFace[2] :
                        arrAdjacentVtxs.append( arrFace[1] )
                        arrAdjacentVtxs.append( arrFace[3] )
                    elif index == arrFace(3) :
                        arrAdjacentVtxs.append( arrFace[2] )
                        arrAdjacentVtxs.append( arrFace[0] )
            else :
                for arrVtxIndex in arrFace :
                    if arrVtxIndex != index :
                        arrAdjacentVtxs.append( arrVtxIndex )
    if type(arrAdjacentVtxs) != type([]) : return None
    arrOrderAdjacentVtxs = CullDuplicates(arrAdjacentVtxs)
    if blnCreate :
        arrStrPts = []
        for arrVtxIndex in arrOrderAdjacentVtxs:
            rs.AddPoint ( arrVertices[arrVtxIndex] )
            arrStrPts.append( arrVertices[arrVtxIndex] )
        return arrStrPts
    else :
        return arrOrderAdjacentVtxs