Ejemplo n.º 1
0
def discretise_mesh(mesh, layer, target, min_angle=15, factor=1):
    """ Discretise a mesh from an input triangulated coarse mesh into small denser meshes.

    Parameters
    ----------
    mesh : guid
        The guid of the Rhino input mesh.
    layer : str
        Layer name to draw results.
    target : float
        Target length of each triangle.
    min_angle : float
        Minimum internal angle of triangles.
    factor : float
        Factor on the maximum area of each triangle.

    Returns
    -------
    None

    """

    rhinomesh = RhinoMesh(mesh)
    vertices = rhinomesh.get_vertex_coordinates()
    faces = [face[:3] for face in rhinomesh.get_face_vertices()]

    try:

        points, tris = meshing.discretise_faces(vertices=vertices,
                                                faces=faces,
                                                target=target,
                                                min_angle=min_angle,
                                                factor=factor)

        rs.CurrentLayer(rs.AddLayer(layer))
        rs.DeleteObjects(rs.ObjectsByLayer(layer))
        rs.EnableRedraw(False)

        for pts, tri in zip(points, tris):
            mesh_faces = []

            for i in tri:
                face_ = i + [i[-1]]
                mesh_faces.append(face_)
            rs.AddMesh(pts, mesh_faces)

        rs.EnableRedraw(True)

    except:

        print('***** Error using MeshPy (Triangle) or drawing faces *****')
Ejemplo n.º 2
0
    def _get_building_member_info(self, gripping_config):
        start = timer() if self.debug else None
        self.simulator.set_robot_config(self.robot, gripping_config)
        mesh = RhinoMesh.from_guid(self.building_member).to_compas()
        handle = self.simulator.add_attached_collision_mesh(
            mesh, options={'robot_name': self.robot.name})
        matrix = self.simulator.get_object_matrices([handle])[handle]

        parent_handle = self.simulator.get_object_handle('customGripper' +
                                                         self.robot.name)
        _, _, mesh_matrix, _, _ = self.simulator.run_child_script(
            'getShapeMatrixRelative', [handle, parent_handle], [], [])

        relative_transform = _to_xform(mesh_matrix)

        transform = _to_xform(matrix)
        mesh_at_origin = _transform_to_origin(
            rs.coercemesh(self.building_member), transform)

        if self.debug:
            LOG.debug('Execution time: building member=%.2f', timer() - start)

        return {
            'mesh': mesh_at_origin,
            'parent_handle': parent_handle,
            'relative_transform': relative_transform
        }
Ejemplo n.º 3
0
    def from_rhinomesh(cls, guid, **kwargs):
        """Construct a FormDiagram from a Rhino mesh represented by a guid.

        Parameters
        ----------
        guid : str
            A globally unique identifier.

        Returns
        -------
        FormDiagram
            A FormDiagram object.

        Examples
        --------
        .. code-block:: python

            import compas_rhino
            from compas_tna.diagrams import FormDiagram

            guid = compas_rhino.select_mesh()
            form = FormDiagram.from_rhinomesh(guid)

        """
        from compas_rhino.geometry import RhinoMesh
        mesh = RhinoMesh.from_guid(guid).to_compas(cls)
        if 'name' in kwargs:
            mesh.name = kwargs['name']
        return mesh
Ejemplo n.º 4
0
 def RunScript(self, scene, M, name, add, remove):
     ok = False
     if scene and M and name:
         mesh = RhinoMesh.from_geometry(M).to_compas()
         collision_mesh = CollisionMesh(mesh, name)
         if add:
             scene.add_collision_mesh(collision_mesh)
             ok = True
         if remove:
             scene.remove_collision_mesh(name)
             ok = True
     return ok
Ejemplo n.º 5
0
 def RunScript(self, scene, mesh, identifier, link_name, touch_links, add, remove):
     attached_collision_mesh = None
     if scene and mesh and identifier and link_name:
         compas_mesh = RhinoMesh.from_geometry(mesh).to_compas()
         collision_mesh = CollisionMesh(compas_mesh, identifier)
         attached_collision_mesh = AttachedCollisionMesh(collision_mesh, link_name, touch_links)
         if add:
             scene.add_attached_collision_mesh(attached_collision_mesh)
         if remove:
             scene.remove_attached_collision_mesh(identifier)
             scene.remove_collision_mesh(identifier)
     return attached_collision_mesh
Ejemplo n.º 6
0
def gh_from_rhino_mesh(mesh_guid, pole_guids):
	rhino_mesh = RhinoMesh.from_guid(mesh_guid)
	vertices, faces = rhino_mesh.vertices, rhino_mesh.faces
	face_no_dup = []
	for face in faces:
		fv = []
		for vertex in face:
			if vertex not in fv:
				fv.append(vertex)
		face_no_dup.append(fv)
	poles = [rs.PointCoordinates(point) for point in pole_guids]
	# warning if ambiguous selection of poles
	return CoarsePseudoQuadMesh.from_vertices_and_faces_with_poles(vertices, face_no_dup, poles)
    def from_rhinomesh(cls, guid, frame):
        """Class method for constructing a block from a Rhino mesh.

        Parameters
        ----------
        guid : str
            The GUID of the mesh.
        frame : :class:`Frame`
            Origin frame of the element.
        """
        from compas_rhino.geometry import RhinoMesh
        element = cls(frame)
        element._source = RhinoMesh.from_guid(guid)
        element._mesh = element._source.mesh.to_compas()
        return element
Ejemplo n.º 8
0
def get_dense_mesh():
    guid = rs.GetObject('get dense mesh', filter=32)
    vertices, faces = RhinoMesh.from_guid(guid).get_vertices_and_faces()
    clean_faces(faces)
    poles = []
    for face in faces:
        if len(face) != 4:
            poles = [
                rs.PointCoordinates(point)
                for point in rs.GetObjects('get pole points', filter=1)
            ]
            break
    singularity_mesh = CoarsePseudoQuadMesh.from_quad_mesh(
        PseudoQuadMesh.from_vertices_and_faces_with_poles(
            vertices, faces, poles))
    return singularity_mesh
Ejemplo n.º 9
0
    def from_rhinomesh(cls, guid):
        """Class method for constructing a block from a Rhino mesh.

        Parameters
        ----------
        guid : str
            The GUID of the mesh.

        Returns
        -------
        Block
            The block corresponding to the Rhino mesh.
        """
        from compas_rhino.geometry import RhinoMesh
        mesh = RhinoMesh.from_guid(guid)
        return mesh.to_compas(cls)
Ejemplo n.º 10
0
    def from_rhinomesh(cls, guid):
        """Make a cable net from a Rhino mesh.

        Parameters
        ----------
        guid : str
            The GUID of the Rhino mesh.

        Returns
        -------
        :class:`Cablenet`
            An instance of a cable net.

        """
        from compas_rhino.geometry import RhinoMesh
        return RhinoMesh.from_guid(guid).to_compas(cls=cls)
Ejemplo n.º 11
0
def RunCommand(is_interactive):

    scene = get_scene()
    if not scene:
        return

    guid = compas_rhino.select_mesh()
    if not guid:
        return

    pattern = RhinoMesh.from_guid(guid).to_compas(cls=Pattern)

    compas_rhino.rs.HideObject(guid)

    scene.clear()
    scene.add(pattern, name='pattern')
    scene.update()

    print("Pattern object successfully created. Input mesh has been hidden.")
Ejemplo n.º 12
0
    def from_guid(guid):
        """Create a ``RhinoGeometry`` instance of the correct type based on a given guid.

        Parameters
        ----------
        guid : str or System.Guid
            The *guid* of the Rhino object.

        Returns
        -------
        RhinoPoint
            If the type of the Rhino object is ``rs.filter.point``.
        RhinoCurve
            If the type of the Rhino object is ``rs.filter.curve``.
        RhinoMesh
            If the type of the Rhino object is ``rs.filter.mesh``.
        RhinoSurface
            If the type of the Rhino object is ``rs.filter.surface``.

        Examples
        --------
        >>>

        """
        from compas_rhino.geometry import RhinoPoint
        from compas_rhino.geometry import RhinoCurve
        from compas_rhino.geometry import RhinoMesh
        from compas_rhino.geometry import RhinoSurface

        otype = rs.ObjectType(guid)

        if otype == rs.filter.point:
            return RhinoPoint(guid)

        if otype == rs.filter.curve:
            return RhinoCurve(guid)

        if otype == rs.filter.mesh:
            return RhinoMesh(guid)

        if otype == rs.filter.surface:
            return RhinoSurface(guid)
Ejemplo n.º 13
0
    def callback(k, args):

        mesh, constraints = args

        for vkey, constraint in constraints.items():
            if rs.ObjectType(constraint) == 1:
                x, y, z = RhinoPoint.from_guid(constraint).xyz
            elif rs.ObjectType(constraint) == 4:
                x, y, z = RhinoCurve.from_guid(constraint).closest_point(
                    mesh.vertex_coordinates(vkey))
            elif rs.ObjectType(constraint) == 8:
                x, y, z = RhinoSurface.from_guid(constraint).closest_point(
                    mesh.vertex_coordinates(vkey))
            elif rs.ObjectType(constraint) == 32:
                x, y, z = RhinoMesh.from_guid(constraint).closest_point(
                    mesh.vertex_coordinates(vkey))
            else:
                continue

            mesh.vertex[vkey]['x'] = x
            mesh.vertex[vkey]['y'] = y
            mesh.vertex[vkey]['z'] = z
Ejemplo n.º 14
0
import rhinoscriptsyntax as rs
from compas_rhino.geometry import RhinoMesh
from compas_pattern.datastructures.mesh_quad_pseudo.mesh_quad_pseudo import PseudoQuadMesh
from compas_pattern.cad.rhino.draw import draw_graph

guids = rs.GetObjects('get quad meshes', filter=32)
poles = rs.GetObjects('get pole points', filter=1)
if poles is None:
    poles = []
else:
    poles = [rs.PointCoordinates(pole) for pole in poles]
rs.EnableRedraw(False)
for guid in guids:
    vertices, faces = RhinoMesh.from_guid(guid).get_vertices_and_faces()
    mesh = PseudoQuadMesh.from_vertices_and_faces_with_poles(
        vertices, faces, poles)
    #mesh = QuadMesh.from_vertices_and_faces(*RhinoMesh.from_guid(guid).get_vertices_and_faces())
    #print('euler', mesh.euler())
    #print('nb_boundaries', len(mesh.boundaries()))
    #mesh.collect_strips()
    #mesh.collect_polyedges()
    #polylines = [rs.AddPolyline(mesh.strip_edge_midpoint_polyline(skey)) for skey in mesh.strips()]
    #for i, polyline in enumerate(polylines):
    #
    #polylines = [rs.AddPolyline(polyline) for polyline in mesh.singularity_polylines()]
    #polylines = [rs.AddPolyline(polyline) for polyline in mesh.polylines()]
    #for polyline in polylines:
    #    rs.CurveArrows(polyline, 3)
    #for i, vkey in enumerate(mesh.vertices()):
    #    rs.AddCircle(mesh.vertex_coordinates(vkey), 2)
    #    rs.AddText(str(i), mesh.vertex_coordinates(vkey), 2)
Ejemplo n.º 15
0
from compas.utilities import XFunc

from math import sin
from math import cos

import rhinoscriptsyntax as rs

__author__ = ['Andrew Liew <*****@*****.**>']
__copyright__ = 'Copyright 2017, BLOCK Research Group - ETH Zurich'
__license__ = 'MIT License'
__email__ = '*****@*****.**'

# Input

guid = rs.ObjectsByLayer('Plane')[0]
rhinomesh = RhinoMesh(guid)
vertices, faces = rhinomesh.get_vertices_and_faces()
points = [[x, y, sin(x) * cos(y)] for x, y, z in vertices]

# Set-up XFunc

basedir = 'D:/compas-dev/examples/'
tmpdir = 'C:/Temp/'
xfunc = XFunc(basedir=basedir, tmpdir=tmpdir)

# Python

xfunc.funcname = 'hpc_normals_func.python_normals'
normals, toc1 = xfunc(points, offset=0.5)['data']
print('Python : {0:.6f} ms'.format(toc1 * 1000))
Ejemplo n.º 16
0
def add_tets_from_mesh(structure,
                       name,
                       mesh,
                       draw_tets=False,
                       volume=None,
                       layer='Default',
                       acoustic=False,
                       thermal=False):
    """ Adds tetrahedron elements from a Rhino mesh to the Structure object.

    Parameters
    ----------
    structure : obj
        Structure object to update.
    name : str
        Name for the element set of tetrahedrons.
    mesh : obj
        The Rhino mesh representing the outer surface.
    draw_tets : bool
        Draw the generated tetrahedrons.
    volume : float
        Maximum volume for each tet.
    layer : str
        Layer to draw tetrahedrons if draw_tets=True.
    acoustic : bool
        Acoustic properties on or off.
    thermal : bool
        Thermal properties on or off.

    Returns
    -------
    None
        Nodes and elements are updated in the Structure object.

    """

    rhinomesh = RhinoMesh(mesh)
    vertices = rhinomesh.get_vertex_coordinates()
    faces = [face[:3] for face in rhinomesh.get_face_vertices()]

    basedir = utilities.__file__.split('__init__.py')[0]
    xfunc = XFunc('tets', basedir=basedir, tmpdir=structure.path)
    xfunc.funcname = 'functions.tets_from_vertices_faces'

    try:
        tets_points, tets_elements = xfunc(vertices=vertices,
                                           faces=faces,
                                           volume=volume)

        for point in tets_points:
            structure.add_node(point)

        ekeys = []
        for element in tets_elements:
            nodes = [
                structure.check_node_exists(tets_points[i]) for i in element
            ]
            ekey = structure.add_element(nodes=nodes,
                                         type='TetrahedronElement',
                                         acoustic=acoustic,
                                         thermal=thermal)
            ekeys.append(ekey)
        structure.add_set(name=name, type='element', selection=ekeys)

        if draw_tets:
            rs.EnableRedraw(False)
            rs.DeleteObjects(rs.ObjectsByLayer(layer))
            rs.CurrentLayer(layer)
            tet_faces = [[0, 2, 1, 1], [1, 2, 3, 3], [1, 3, 0, 0],
                         [0, 3, 2, 2]]
            for i, points in enumerate(tets_elements):
                xyz = [tets_points[j] for j in points]
                rs.AddMesh(vertices=xyz, face_vertices=tet_faces)
        rs.EnableRedraw(True)

    except:
        print('***** Error using MeshPy or drawing Tets *****')
Ejemplo n.º 17
0
def mesh_extrude(structure, guid, layers, thickness, mesh_name='', links_name='', blocks_name='', points_name='',
                 plot_mesh=False, plot_links=False, plot_blocks=False, plot_points=False):
    """
    Extrudes a Rhino mesh and adds/creates elements.

    Parameters
    ----------
    structure : obj
        Structure object to update.
    guid : guid
        Rhino mesh guid.
    layers : int
        Number of layers.
    thickness : float
        Layer thickness.
    mesh_name : str
        Name of set for mesh on final surface.
    links_name : str
        Name of set for adding links along extrusion.
    blocks_name : str
        Name of set for solid elements.
    points_name : str
        Name of aded points.
    plot_mesh : bool
        Plot outer mesh.
    plot_links : bool
        Plot links.
    plot_blocks : bool
        Plot blocks.
    plot_points : bool
        Plot end points.

    Returns
    -------
    None

    Notes
    -----
    - Extrusion is along the mesh vertex normals.

    """

    mesh = RhinoMesh.from_guid(guid).to_compas(cls=Mesh)
    extrude_mesh(structure=structure, mesh=mesh, layers=layers, thickness=thickness, mesh_name=mesh_name,
                 links_name=links_name, blocks_name=blocks_name)

    block_faces = [[0, 1, 2, 3], [4, 5, 6, 7], [0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [3, 0, 4, 7]]
    xyz = structure.nodes_xyz()

    rs.EnableRedraw(False)

    if plot_blocks:

        rs.CurrentLayer(rs.AddLayer(blocks_name))
        rs.DeleteObjects(rs.ObjectsByLayer(blocks_name))

        for i in structure.sets[blocks_name]['selection']:
            nodes = structure.elements[i].nodes
            xyz   = structure.nodes_xyz(nodes)
            rs.AddMesh(xyz, block_faces)

    if plot_mesh:

        rs.CurrentLayer(rs.AddLayer(mesh_name))
        rs.DeleteObjects(rs.ObjectsByLayer(mesh_name))

        faces = []
        for i in structure.sets[mesh_name]['selection']:
            enodes = structure.elements[i].nodes
            if len(enodes) == 3:
                enodes.append(enodes[-1])
            faces.append(enodes)
        rs.AddMesh(xyz, faces)

    if plot_links:

        rs.CurrentLayer(rs.AddLayer(links_name))
        rs.DeleteObjects(rs.ObjectsByLayer(links_name))

        if plot_points:
            rs.CurrentLayer(rs.AddLayer(points_name))
            rs.DeleteObjects(rs.ObjectsByLayer(points_name))

        for i in structure.sets[links_name]['selection']:

            nodes = structure.elements[i].nodes
            xyz = structure.nodes_xyz(nodes)
            rs.CurrentLayer(links_name)
            rs.AddLine(xyz[0], xyz[1])

            if plot_points:
                rs.CurrentLayer(points_name)
                rs.AddPoint(xyz[1])

    rs.EnableRedraw(True)
    rs.CurrentLayer(rs.AddLayer('Default'))
import rhinoscriptsyntax as rs
from compas_rhino.geometry import RhinoMesh
from compas_pattern.datastructures.mesh_quad.mesh_quad import QuadMesh

guids = rs.GetObjects('get quad meshes', filter = 32)
rs.EnableRedraw(False)
for guid in guids:
    mesh = QuadMesh.from_vertices_and_faces(*RhinoMesh.from_guid(guid).get_vertices_and_faces())
    mesh.collect_strips()
    polylines = [rs.AddPolyline(mesh.strip_edge_polyline(skey)) for skey in mesh.strips()]
    for polyline in polylines:
        rs.CurveArrows(polyline, 3)
Ejemplo n.º 19
0
def add_tets_from_mesh(structure,
                       name,
                       mesh,
                       draw_tets=False,
                       volume=None,
                       thermal=False):
    """ Adds tetrahedron elements from a mesh in Rhino to the Structure object.

    Parameters
    ----------
    structure : obj
        Structure object to update.
    name : str
        Name for the element set of tetrahedrons.
    mesh : guid
        The mesh in Rhino representing the outer surface.
    draw_tets : str
        Layer to draw tetrahedrons on.
    volume : float
        Maximum volume for each tet.
    thermal : bool
        Thermal properties on or off.

    Returns
    -------
    None

    """

    rhinomesh = RhinoMesh(mesh)
    vertices = rhinomesh.get_vertex_coordinates()
    faces = [face[:3] for face in rhinomesh.get_face_vertices()]

    try:
        tets_points, tets_elements = meshing.tets_from_vertices_faces(
            vertices=vertices, faces=faces, volume=volume)

        for point in tets_points:
            structure.add_node(point)

        ekeys = []

        for element in tets_elements:

            nodes = [
                structure.check_node_exists(tets_points[i]) for i in element
            ]
            ekey = structure.add_element(nodes=nodes,
                                         type='TetrahedronElement',
                                         thermal=thermal)
            ekeys.append(ekey)

        structure.add_set(name=name, type='element', selection=ekeys)

        if draw_tets:

            rs.EnableRedraw(False)
            rs.DeleteObjects(rs.ObjectsByLayer(draw_tets))
            rs.CurrentLayer(draw_tets)

            tet_faces = [[0, 2, 1, 1], [1, 2, 3, 3], [1, 3, 0, 0],
                         [0, 3, 2, 2]]

            for i, points in enumerate(tets_elements):

                xyz = [tets_points[j] for j in points]
                rs.AddMesh(vertices=xyz, face_vertices=tet_faces)

            rs.EnableRedraw(True)

        print('***** MeshPy (TetGen) successfull *****')

    except:

        print('***** Error using MeshPy (TetGen) or drawing Tets *****')
Ejemplo n.º 20
0
import rhinoscriptsyntax as rs
from compas_rhino.geometry import RhinoMesh
from compas_pattern.datastructures.mesh_quad_pseudo_coarse.mesh_quad_pseudo_coarse import CoarsePseudoQuadMesh
#from compas_pattern.cad.rhino.artist import select_quad_mesh_strip
from compas_rhino.artists import MeshArtist

guid = rs.GetObject('get (coarse) quad mesh', filter=32)
poles = rs.GetObjects('get pole points', filter=1)
if poles is None:
    poles = []
else:
    poles = [rs.PointCoordinates(pole) for pole in poles]

mesh = RhinoMesh.from_guid(guid)
vertices, faces = mesh.vertices, mesh.faces
mesh = CoarsePseudoQuadMesh.from_vertices_and_faces_with_poles(
    vertices, faces, poles)

print(mesh.boundaries())

#mesh.collect_strips()
#mesh.set_strips_density(1)
#mesh.densification()
#
#
#count = 100
#while count:
#    count -= 1
#
#    artist = MeshArtist(mesh.get_quad_mesh())
#    guid = artist.draw_mesh()
Ejemplo n.º 21
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 = RhinoMesh.from_guid(guid).to_compas()

                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':
                    node_iterator=0
                    for node in nodes:
                        ekey = structure.add_element(nodes=[node], type=mesh_type, thermal=thermal, mass=masses[node_iterator]) #structure.nodes[node].mass
                        node_iterator += 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)
Ejemplo n.º 22
0
def singular():
    """Explore a pattern, its topology (singularities, densities and symmetries) and its geoemtry (via smoothing).

    """

    layer = rs.CurrentLayer()

    pattern_from = rs.GetString('start pattern from?',
                                strings=[
                                    'coarse_pseudo_quad_mesh',
                                    'pseudo_quad_mesh', 'surface_and_features'
                                ])

    if pattern_from == 'coarse_pseudo_quad_mesh':
        guid = rs.GetObject('get coarse quad mesh', filter=32)
        vertices, faces = RhinoMesh.from_guid(guid).get_vertices_and_faces()
        clean_faces(faces)
        poles = []
        #print(faces)
        for face in faces:
            if len(face) != 4:
                poles = [
                    rs.PointCoordinates(point)
                    for point in rs.GetObjects('get pole points', filter=1)
                ]
                break
        coarse_pseudo_quad_mesh = CoarsePseudoQuadMesh.from_vertices_and_faces_with_poles(
            vertices, faces, poles)
        coarse_pseudo_quad_mesh.collect_strips()
        print(coarse_pseudo_quad_mesh.data['attributes']['strips'])
        coarse_pseudo_quad_mesh.set_strips_density(1)
        coarse_pseudo_quad_mesh.set_quad_mesh(coarse_pseudo_quad_mesh.copy())
        coarse_pseudo_quad_mesh.set_polygonal_mesh(
            coarse_pseudo_quad_mesh.copy())
        print(coarse_pseudo_quad_mesh.data['attributes']['strips'])
    elif pattern_from == 'pseudo_quad_mesh':
        guid = rs.GetObject('get quad mesh', filter=32)
        vertices, faces = RhinoMesh.from_guid(guid).get_vertices_and_faces()
        clean_faces(faces)
        poles = []
        for face in faces:
            if len(face) != 4:
                poles = [
                    rs.PointCoordinates(point)
                    for point in rs.GetObjects('get pole points', filter=1)
                ]
                break
        coarse_pseudo_quad_mesh = CoarsePseudoQuadMesh.from_quad_mesh(
            PseudoQuadMesh.from_vertices_and_faces_with_poles(
                vertices, faces, poles))
    elif pattern_from == 'surface_and_features':
        srf_guid = rs.GetObject('get surface', filter=8)
        crv_guids = rs.GetObjects('get optional curve features', filter=4)
        if crv_guids is None:
            crv_guids = []
        pt_guids = rs.GetObjects('get optional point features', filter=1)
        if pt_guids is None:
            pt_guids = []
        coarse_pseudo_quad_mesh = surface_decomposition(
            srf_guid,
            rs.GetReal('precision', number=1.),
            crv_guids=crv_guids,
            pt_guids=pt_guids,
            output_skeleton=False)[0]
        coarse_pseudo_quad_mesh.collect_strips()
        coarse_pseudo_quad_mesh.set_strips_density(1)
        coarse_pseudo_quad_mesh.set_quad_mesh(coarse_pseudo_quad_mesh.copy())
        coarse_pseudo_quad_mesh.set_polygonal_mesh(
            coarse_pseudo_quad_mesh.copy())
        artist = rhino_artist.MeshArtist(coarse_pseudo_quad_mesh)
        guid = artist.draw_mesh()
    else:
        return 0

    while True:

        #edit = rs.GetString('edit pattern?', strings = ['topology', 'density', 'symmetry', 'geometry', 'evaluate', 'exit'])
        edit = rs.GetString('edit pattern?',
                            strings=[
                                'topology', 'density', 'symmetry', 'geometry',
                                'save', 'exit'
                            ])

        if type(guid) == list:
            rs.DeleteObjects(guid)
        else:
            rs.DeleteObject(guid)

        if edit is None or edit == 'exit':
            rs.EnableRedraw(False)
            artist = rhino_artist.MeshArtist(
                coarse_pseudo_quad_mesh.get_polygonal_mesh())
            return artist.draw_mesh()

        if edit == 'topology':
            editing_topology(coarse_pseudo_quad_mesh)
            coarse_pseudo_quad_mesh.densification()
            coarse_pseudo_quad_mesh.set_polygonal_mesh(
                coarse_pseudo_quad_mesh.get_quad_mesh().copy())

        elif edit == 'density':
            editing_density(coarse_pseudo_quad_mesh)
            coarse_pseudo_quad_mesh.set_polygonal_mesh(
                coarse_pseudo_quad_mesh.get_quad_mesh().copy())

        elif edit == 'symmetry':
            editing_symmetry(coarse_pseudo_quad_mesh)

        elif edit == 'geometry':
            editing_geometry(coarse_pseudo_quad_mesh)

        rs.EnableRedraw(False)
        artist = rhino_artist.MeshArtist(
            coarse_pseudo_quad_mesh.get_polygonal_mesh())
        guid = artist.draw_mesh()
        rs.EnableRedraw(True)

        if edit == 'save':
            save_design(coarse_pseudo_quad_mesh, layer)

        if edit == 'evaluate':
            evaluate_pattern(coarse_pseudo_quad_mesh.get_polygonal_mesh())
Ejemplo n.º 23
0
length = 0.25
kmax = 300

# select the original mesh
# select the border
# select the fixed points

guid_target = compas_rhino.select_mesh()
guid_border = compas_rhino.select_polyline()
guid_points = compas_rhino.select_points()

# wrap the Rhino mesh object for convenience
# wrap the Rhino curve object for convenience
# get the point coordinates

target = RhinoMesh(guid_target)
border = RhinoCurve(guid_border)
points = compas_rhino.get_point_coordinates(guid_points)

# make a mesh datastructure from the Rhino mesh
# triangulate the mesh

mesh = mesh_from_guid(Mesh, guid_target)
mesh_quads_to_triangles(mesh)

# identify the fixed vertices
# by matching the coordinates of the selected points
# up to a precision

keys = mesh_identify_vertices(mesh, points, '1f')
fixed = set(keys)
def rgmesh_to_cgmesh(mesh, cls=None):
    return RhinoMesh.from_geometry(mesh).to_compas(cls=cls)