Exemple #1
0
    def draw_points(self, points, layer=None, clear_layer=False, redraw=False):
        """Draw a collection of points.

        Parameters
        ----------
        points : list of dict
            The points to draw.
        layer : str, optional
            The layer to draw the points in.
            Default is ``None``.
        clear_layer : bool, optional
            Clear the specified layer.
            Default is ``False``.
        redraw : bool, optional
            Redraw the Rhino view.
            Default is ``False``.

        Returns
        -------
        list of guid
            The GUIDs of the points.

        """
        layer = layer or self.layer
        return compas_rhino.xdraw_points(points,
                                         layer=layer,
                                         clear=clear_layer,
                                         redraw=redraw)
Exemple #2
0
    def draw_vertices(self, keys=None, color=None):
        """Draw a selection of vertices.

        Parameters
        ----------
        keys : list
            A list of vertex keys identifying which vertices to draw.
            Default is ``None``, in which case all vertices are drawn.
        color : str, tuple, dict
            The color specififcation for the vertices.
            Colors should be specified in the form of a string (hex colors) or
            as a tuple of RGB components.
            To apply the same color to all vertices, provide a single color
            specification. Individual colors can be assigned using a dictionary
            of key-color pairs. Missing keys will be assigned the default vertex
            color (``self.defaults['color.vertex']``).
            The default is ``None``, in which case all vertices are assigned the
            default vertex color.

        Notes
        -----
        The vertices are named using the following template:
        ``"{}.vertex.{}".format(self.datastructure.name], key)``.
        This name is used afterwards to identify vertices in the Rhino model.

        """
        keys = keys or list(self.datastructure.vertices())
        colordict = color_to_colordict(
            color,
            keys,
            default=self.defaults.get('color.vertex'),
            colorformat='rgb',
            normalize=False)
        points = []
        for key in keys:
            points.append({
                'pos':
                self.datastructure.vertex_coordinates(key),
                'name':
                self.datastructure.vertex_name(key),
                'color':
                colordict[key],
                'layer':
                self.datastructure.get_vertex_attribute(key, 'layer', None)
            })
        return compas_rhino.xdraw_points(points,
                                         layer=self.layer,
                                         clear=False,
                                         redraw=False)
    def draw_striplabels(self):
        """Draw the strip labels.

        Parameters
        ----------

        """

        strips_to_edges = self.strips_to_edges_dict()

        strip_labels = []
        for strip, edges in strips_to_edges.items():
            strip_labels += [{
                'pos': self.datastructure.edge_midpoint(u, v),
                'name': strip,
                'color': [0, 0, 0],
                'text': strip,
                'layer': self.layer
            } for u, v in edges]

        return compas_rhino.xdraw_points(edge_midpoints,
                                         layer=self.layer,
                                         clear=False,
                                         redraw=False)
Exemple #4
0
            dx, dy, dz = subtract_vectors(point, xyz)
            mesh.vertex[key]['x'] += d * dx
            mesh.vertex[key]['y'] += d * dy
            mesh.vertex[key]['z'] += d * dz


# ==============================================================================
# Debugging
# ==============================================================================

if __name__ == '__main__':

    import compas_rhino

    guid = compas_rhino.select_surface()

    surface = RhinoSurface(guid)

    points = []
    for xyz in surface.heightfield():
        points.append({
            'pos': xyz,
            'name': 'heightfield',
            'color': (0, 255, 0),
        })

    compas_rhino.xdraw_points(points,
                              layer='Layer 01',
                              clear=True,
                              redraw=True)
Exemple #5
0
def draw_volmesh(volmesh,
                 name=None,
                 layer=None,
                 clear=True,
                 redraw=True,
                 show_faces=True,
                 show_vertices=True,
                 show_edges=True,
                 vertex_color=None,
                 edge_color=None,
                 face_color=None):
    """"""
    # set default options
    if not isinstance(vertex_color, dict):
        vertex_color = {}
    if not isinstance(edge_color, dict):
        edge_color = {}
    if not isinstance(face_color, dict):
        face_color = {}
    if name:
        volmesh.attributes['name'] = name
    name = volmesh.setdefault('name', name)
    if layer:
        volmesh.attributes['layer'] = layer
    layer = volmesh.setdefault('layer', layer)
    # delete all relevant objects by name
    objects = compas_rhino.get_objects(name='{0}.mesh'.format(name))
    objects += compas_rhino.get_objects(name='{0}.vertex.*'.format(name))
    objects += compas_rhino.get_objects(name='{0}.edge.*'.format(name))
    compas_rhino.delete_objects(objects)
    # clear the layer if requested
    if clear:
        compas_rhino.clear_layers([layer])
    # draw the requested components
    if show_faces:
        faces = []
        color = volmesh.attributes['color.face']
        for vertices in volmesh.faces():
            points = [
                volmesh.vertex_coordinates(vkey)
                for vkey in vertices + [vertices[0]]
            ]
            faces.append({
                'points': points,
                'name': '',
                'color': color,
            })
        compas_rhino.xdraw_faces(faces, layer=layer, clear=False, redraw=False)
    if show_edges:
        lines = []
        color = volmesh.attributes['color.edge']
        for u, v in volmesh.edges_iter():
            lines.append({
                'start': volmesh.vertex_coordinates(u),
                'end': volmesh.vertex_coordinates(v),
                'name': '{0}.edge.{1}-{2}'.format(name, u, v),
                'color': edge_color.get((u, v), color),
            })
        compas_rhino.xdraw_lines(lines, layer=layer, clear=False, redraw=False)
    if show_vertices:
        points = []
        color = volmesh.attributes['color.vertex']
        for key in volmesh.vertices_iter():
            points.append({
                'pos': volmesh.vertex_coordinates(key),
                'name': '{0}.vertex.{1}'.format(name, key),
                'color': vertex_color.get(key, color),
            })
        compas_rhino.xdraw_points(points,
                                  layer=layer,
                                  clear=False,
                                  redraw=False)
    # redraw if requested
    if redraw:
        rs.Redraw()
Exemple #6
0
def draw_mesh(
    mesh,
    layer=None,
    clear_layer=False,
    show_faces=True,
    show_vertices=False,
    show_edges=False,
    show_wireframe=False,
    vertexcolor=None,
    edgecolor=None,
    wireframecolor=None,
    facecolor=None,
):
    """
    Draw a mesh object in Rhino.

    Parameters:
        mesh (compas.datastructures.mesh.Mesh): The mesh object.
        layer (str): Optional. The layer to draw in. Default is ``None``.
        clear_layer (bool): Optional. Clear the drawing layer. Default is ``True``.
        show_faces (bool): Optional. Show the faces. Default is ``True``.
        show_vertices (bool): Optional. Show the vertices. Default is ``True``.
        show_edges (bool): Optional. Show the edges. Default is ``True``.
        vertexcolor (str, tuple, list, dict): Optional. The vertex color specification. Default is ``None``.
        edgecolor (str, tuple, list, dict): Optional. The edge color specification. Default is ``None``.
        facecolor (str, tuple, list, dict): Optional. The face color specification. Default is ``None``.
        redraw (bool): Optional. Redraw instructions. Default is ``True``.

    Note:
        Colors can be specifiedin different ways:

        * str: A hexadecimal color that will be applied to all elements subject to the specification.
        * tuple, list: RGB color that will be applied to all elements subject to the specification.
        * dict: RGB or hex color dict with a specification for some or all of the related elements.

    Important:
        RGB colors should specify color values between 0 and 255.

    """

    vertexcolor = color_to_colordict(vertexcolor,
                                     mesh.vertices(),
                                     default=mesh.attributes['color.vertex'],
                                     colorformat='rgb',
                                     normalize=False)

    edgecolor = color_to_colordict(edgecolor,
                                   mesh.edges(),
                                   default=mesh.attributes['color.edge'],
                                   colorformat='rgb',
                                   normalize=False)

    # facecolor = color_to_colordict(facecolor,
    #                                mesh.faces(),
    #                                default=mesh.attributes['color.face'],
    #                                colorformat='rgb',
    #                                normalize=False)

    guids = compas_rhino.get_objects(
        name='{0}.*'.format(mesh.attributes['name']))
    compas_rhino.delete_objects(guids)

    if clear_layer:
        if not layer:
            compas_rhino.clear_current_layer()
        else:
            compas_rhino.clear_layer(layer)

    if show_faces:
        key_index = {key: index for index, key in enumerate(mesh.vertices())}
        xyz = [mesh.vertex_coordinates(key) for key in mesh.vertices()]
        faces = []
        color = mesh.attributes['color.face']

        for fkey in mesh.face:
            face = mesh.face_vertices(fkey, ordered=True)
            v = len(face)

            if v < 3:
                print('Degenerate face: {0} => {1}'.format(fkey, face))
            elif v == 3:
                faces.append([key_index[k] for k in face + [face[-1]]])
            elif v == 4:
                faces.append([key_index[k] for k in face])
            else:
                c = len(xyz)
                xyz.append(mesh.face_center(fkey))
                for i in range(-1, len(face) - 1):
                    key = face[i]
                    nbr = face[i + 1]
                    vertices = [
                        c, key_index[key], key_index[nbr], key_index[nbr]
                    ]
                    faces.append(vertices)

        compas_rhino.xdraw_mesh(xyz,
                                faces,
                                color,
                                '{0}.mesh'.format(mesh.attributes['name']),
                                layer=layer,
                                clear=False,
                                redraw=False)

    if show_edges:
        lines = []
        color = mesh.attributes['color.edge']
        for u, v in mesh.edges():
            lines.append({
                'start':
                mesh.vertex_coordinates(u),
                'end':
                mesh.vertex_coordinates(v),
                'name':
                '{0}.edge.{1}-{2}'.format(mesh.attributes['name'], repr(u),
                                          repr(v)),
                'color':
                edgecolor.get((u, v), color),
            })
        compas_rhino.xdraw_lines(lines, layer=layer, clear=False, redraw=False)

    if show_wireframe:
        lines = []
        color = mesh.attributes['color.edge']
        for u, v in mesh.wireframe():
            lines.append({
                'start':
                mesh.vertex_coordinates(u),
                'end':
                mesh.vertex_coordinates(v),
                'name':
                '{0}.edge.{1}-{2}'.format(mesh.attributes['name'], repr(u),
                                          repr(v)),
                'color':
                edgecolor.get((u, v), color),
            })
        compas_rhino.xdraw_lines(lines, layer=layer, clear=False, redraw=False)

    if show_vertices:
        points = []
        color = mesh.attributes['color.vertex']
        for key in mesh.vertices():
            points.append({
                'pos':
                mesh.vertex_coordinates(key),
                'name':
                '{0}.vertex.{1}'.format(mesh.attributes['name'], repr(key)),
                'color':
                vertexcolor.get(key, color),
            })
        compas_rhino.xdraw_points(points,
                                  layer=layer,
                                  clear=False,
                                  redraw=False)

    rs.EnableRedraw()
    rs.Redraw()
def draw_network(network,
                 layer=None,
                 clear_layer=False,
                 vertexcolor=None,
                 edgecolor=None,
                 edgelabel=None):
    """Draw a network data structure in Rhino.

    Parameters:
        network (compas.datastructures.network.Network): The network object.
        layer (str): Optional. The layer to draw in. Default is ``None``. If
            ``None``, the currenlt layer is used.
        clear_layer (bool): Optional. Clear the layer if ``True``. Default is ``False``.
        vertexcolor (list, tuple, str, dict): Optional. The color specification
            for the vertices. Default is ``None``.

                * list, tuple: rgb color, with color specs between 0 and 255 (e.g. ``(255, 0, 0)``).
                * str: hex color (e.g. ``'#ff0000'``).
                * dict: dictionary of hex or rgb colors.

        edgecolor (list, tuple, str, dict): Optional. The color specification
            for the edges. Default is ``None``.

                * list, tuple: rgb color, with color specs between 0 and 255 (e.g. ``(255, 0, 0)``).
                * str: hex color (e.g. ``'#ff0000'``).
                * dict: dictionary of hex or rgb color.

    Note:
        * Any network objects with the same name that are already present in the
          model will be deleted by this function.
        * To also clear the entire layer the network will be drawn on, for
          example, if you have a dedicated network layer, use the ``clear_layer`` flag as well.

    See Also:
        * :class:`compas.datastructures.network.Network`
        * :func:`compas_compas_rhino.utilities.drawing.xdraw_lines`
        * :func:`compas_compas_rhino.utilities.drawing.xdraw_points`

    Example:

        .. code-block:: python
            :emphasize-lines: 7

            import compas
            from compas.datastructures.network import Network
            import compas_rhino as compas_rhino

            network = Network.from_obj(compas.get_data('lines.obj'))

            compas_compas_rhino.draw_network(network)

    """
    vertexcolor = color_to_colordict(vertexcolor,
                                     network.vertices(),
                                     default=network.attributes['color.vertex'],
                                     colorformat='rgb',
                                     normalize=False)

    edgecolor = color_to_colordict(edgecolor,
                                   network.edges(),
                                   default=network.attributes['color.edge'],
                                   colorformat='rgb',
                                   normalize=False)

    edgelabel = edgelabel or {}

    points = []
    for key, attr in network.vertices(True):
        points.append({
            'pos'  : network.vertex_coordinates(key),
            'name' : '{0}.vertex.{1}'.format(network.attributes['name'], repr(key)),
            'color': vertexcolor[key]
        })

    lines = []
    for u, v, attr in network.edges(True):
        lines.append({
            'start': network.vertex_coordinates(u),
            'end'  : network.vertex_coordinates(v),
            'name' : '{0}.edge.{1}-{2}'.format(network.attributes['name'], repr(u), repr(v)),
            'color': edgecolor[(u, v)]
        })

    labels = []
    for (u, v), text in edgelabel.items():
        labels.append({
            'pos'  : network.edge_midpoint(u, v),
            'text' : str(text),
            'name' : '{0}.edge.label.{1}-{2}'.format(network.attributes['name'], repr(u), repr(v)),
            'color': edgecolor[(u, v)],
        })

    guids = compas_rhino.get_objects(name='{0}.*'.format(network.attributes['name']))
    compas_rhino.delete_objects(guids)

    compas_rhino.xdraw_points(
        points,
        layer=layer,
        clear=clear_layer,
        redraw=False
    )
    compas_rhino.xdraw_lines(
        lines,
        layer=layer,
        clear=False,
        redraw=False
    )
    compas_rhino.xdraw_labels(
        labels,
        layer=layer,
        clear=False,
        redraw=True
    )