Пример #1
0
    def generate_paths(self):
        """Generates the planar slicing paths."""
        z = [
            self.mesh.vertex_attribute(key, 'z')
            for key in self.mesh.vertices()
        ]
        min_z, max_z = min(z), max(z)
        d = abs(min_z - max_z)
        no_of_layers = int(d / self.layer_height) + 1
        normal = Vector(0, 0, 1)
        planes = [
            Plane(Point(0, 0, min_z + i * self.layer_height), normal)
            for i in range(no_of_layers)
        ]
        # planes.pop(0)  # remove planes that are on the print platform

        if self.slicer_type == "default":
            logger.info('')
            logger.info("Planar slicing using default function ...")
            self.layers = compas_slicer.slicers.create_planar_paths(
                self.mesh, planes)

        elif self.slicer_type == "cgal":
            logger.info('')
            logger.info("Planar slicing using CGAL ...")
            self.layers = compas_slicer.slicers.create_planar_paths_cgal(
                self.mesh, planes)

        else:
            raise NameError("Invalid slicing type : " + self.slicer_type)
Пример #2
0
    def from_planes(cls, planes):
        """Construct a polyhedron from intersecting planes.

        Parameters
        ----------
        planes : list of :class:`compas.geometry.Plane` or list of (point, normal)

        Returns
        -------
        :class:`compas.geometry.Polyhedron`

        Examples
        --------
        >>> from compas.geometry import Plane
        >>> left = Plane([-1, 0, 0], [-1, 0, 0])
        >>> right = Plane([+1, 0, 0], [+1, 0, 0])
        >>> top = Plane([0, 0, +1], [0, 0, +1])
        >>> bottom = Plane([0, 0, -1], [0, 0, -1])
        >>> front = Plane([0, -1, 0], [0, -1, 0])
        >>> back = Plane([0, +1, 0], [0, +1, 0])
        >>> p = Polyhedron.from_planes([left, right, top, bottom, front, back])

        """
        from compas.geometry import Plane
        from compas.geometry import centroid_points
        planes = [Plane(point, normal) for point, normal in planes]
        interior = centroid_points([plane.point for plane in planes])
        return cls.from_halfspaces([plane.abcd for plane in planes], interior)
Пример #3
0
    def to_circle(self) -> compas.geometry.Circle:
        """Convert the edge geometry to a circle.

        Returns
        -------
        :class:`~compas.geometry.Circle`
            A COMPAS circle.

        Raises
        ------
        ValueError
            If the underlying geometry is not a circle.

        """
        if not self.is_circle:
            raise ValueError(
                f'The underlying geometry is not a circle: {self.type}')

        curve = self.adaptor.Curve()
        circle = curve.Circle()
        location = circle.Location()
        direction = circle.Axis().Direction()
        radius = circle.Radius()
        point = location.X(), location.Y(), location.Z()
        normal = direction.X(), direction.Y(), direction.Z()
        return Circle(Plane(point, normal), radius)
Пример #4
0
    def plot(self):
        """Visualize the current map with the plotter.

        Returns
        -------
        None

        """
        from compas_plotters.plotter import Plotter
        from compas.geometry import Pointcloud
        from compas.geometry import Plane, Circle, Polygon
        plotter = Plotter(figsize=(16, 12))
        w = 16
        h = 10
        n = len(self.colors)
        d = w / n
        cloud = Pointcloud.from_bounds(w, h, 0, n)
        white = Color.white()
        for i, color in enumerate(self.colors):
            c = Circle(Plane(cloud[i], [0, 0, 1]), 0.1)
            p = Polygon([[i * d, -2, 0], [(i + 1) * d, -2, 0],
                         [(i + 1) * d, -1, 0], [i * d, -1, 0]])
            plotter.add(c, facecolor=color, edgecolor=white, linewidth=0.5)
            plotter.add(p, facecolor=color, edgecolor=color)
        plotter.zoom_extents()
        plotter.show()
Пример #5
0
    def to_ellipse(self) -> compas.geometry.Ellipse:
        """Convert the edge geometry to an ellipse.

        Returns
        -------
        :class:`~compas.geometry.Ellipse`
            A COMPAS ellipse.

        Raises
        ------
        ValueError
            If the underlying geometry is not an ellipse.

        """
        if not self.is_ellipse:
            raise ValueError(
                f'The underlying geometry is not an ellipse: {self.type}')

        curve = self.adaptor.Curve()
        ellipse = curve.Ellipse()
        location = ellipse.Location()
        direction = ellipse.Axis().Direction()
        major = ellipse.MajorRadius()
        minor = ellipse.MinorRadius()
        point = location.X(), location.Y(), location.Z()
        normal = direction.X(), direction.Y(), direction.Z()
        return Ellipse(Plane(point, normal), major, minor)
Пример #6
0
def cutting_plane(mesh, ry=10, rz=-50):
    plane = Plane(mesh.centroid(), Vector(1, 0, 0))
    Ry = Rotation.from_axis_and_angle(Vector(0, 1, 0), radians(ry),
                                      plane.point)
    Rz = Rotation.from_axis_and_angle(Vector(0, 0, 1), radians(rz),
                                      plane.point)
    plane.transform(Rz * Ry)
    return plane
Пример #7
0
    def get_Beam_interecting_Planes(self, BeamsRef, flag=0, face_id=None):
        """Computes the interecting planes of a given Beam
        ----------

        """
        if flag == 0:
            intersecting_planes = []
            frame = BeamsRef.get_face_frame(4)
            intersecting_planes.append(Plane(frame.point, frame.normal))
            frame = BeamsRef.get_face_frame(3)
            intersecting_planes.append(Plane(frame.point, frame.normal))
            return intersecting_planes
        elif flag == 1:
            frame = BeamsRef.get_face_frame(self.get_start_face(face_id))
            start_frame = Plane(frame.point, frame.normal)
            return start_frame
        else:
            pass
Пример #8
0
 def get_distance(self, point):
     """
     single point distance function
     """
     plane = Plane(self.frame.point, self.frame.normal)
     plndst = distance_point_plane_signed(point, plane)
     pr = rotate_points([point], plndst / 10, self.frame.normal,
                        self.frame.point)
     d = self.obj.get_distance(pr[0])
     return d
Пример #9
0
def plane_to_compas(plane):
    """Convert a Rhino plane to a COMPAS plane.

    Parameters
    ----------
    plane : :class:`Rhino.Geometry.Plane`

    Returns
    -------
    :class:`compas.geometry.Plane`
    """
    return Plane(point_to_compas(plane.Origin), vector_to_compas(plane.Normal))
Пример #10
0
 def __iter__(self):
     if self.start_vector:
         # correct start_vector
         self.start_vector = (self.axis.cross(
             self.start_vector.unitized())).cross(self.axis)
         for alpha in arange(0, 2 * math.pi, self.angle_step):
             R = Rotation.from_axis_and_angle(self.axis, alpha)
             yield self.start_vector.transformed(R)
     else:
         f = Frame.from_plane(Plane((0, 0, 0), self.axis))
         for alpha in arange(0, 2 * math.pi, self.angle_step):
             x = math.cos(alpha)
             y = math.sin(alpha)
             yield f.to_world_coordinates(Vector(x, y, 0))
def points_on_sphere_generator(sphere):
    for theta_deg in range(0, 360, 20):
        for phi_deg in range(0, 90, 10):
            theta = math.radians(theta_deg)
            phi = math.radians(phi_deg)
            x = sphere.point.x + sphere.radius * math.cos(theta) * math.sin(phi)
            y = sphere.point.y + sphere.radius * math.sin(theta) * math.sin(phi)
            z = sphere.point.z + sphere.radius * math.cos(phi)
            point = Point(x, y, z)
            axis = sphere.point - point
            plane = Plane((x, y, z), axis)
            f = Frame.from_plane(plane)
            # for UR5 is zaxis the xaxis
            yield Frame(f.point, f.zaxis, f.yaxis)
Пример #12
0
def cone_to_compas(cone):
    """Convert a Rhino cone to a COMPAS cone.

    Parameters
    ----------
    cone: :class:`Rhino.Geometry.Cone`

    Returns
    -------
    :class:`compas.geometry.Cone`
    """
    plane = Plane(cone.BasePoint,
                  vector_to_compas(cone.Plane.Normal).inverted())
    return Cone(Circle(plane, cone.Radius), cone.Height)
Пример #13
0
    def __init__(self, scene, arrow, **kwargs):
        super(ArrowObject, self).__init__(scene, arrow, **kwargs)

        length = np.linalg.norm(arrow.direction)

        plane = Plane(arrow.point + arrow.direction * 0.7, arrow.direction)
        circle = Circle(plane, length * 0.15)
        cone = Cone(circle, length * 0.3)

        line = Line(Point(*arrow.point),
                    Point(*(arrow.point + arrow.direction * 0.7)))

        self.view = ArrowView(arrow, ConeObject(None, cone, 3),
                              LineObject(None, line))
Пример #14
0
 def __iter__(self):
     yield self.axis
     alphas = arange(self.max_alpha / self.step,
                     self.max_alpha + self.max_alpha / self.step,
                     self.max_alpha / self.step)
     radii = [math.sin(alpha) for alpha in alphas]
     x, y = math.cos(alphas[0]), math.sin(alphas[0])
     d = math.sqrt((1 - x)**2 + y**2)
     # get any vector normal to axis
     axis2 = Frame.from_plane(Plane((0, 0, 0), self.axis)).xaxis
     for alpha, r in zip(alphas, radii):
         R1 = Rotation.from_axis_and_angle(axis2, alpha)
         amount = int(round(2 * math.pi * r / d))
         betas = arange(0, 2 * math.pi, 2 * math.pi / amount)
         for beta in betas:
             R2 = Rotation.from_axis_and_angle(self.axis, beta)
             yield self.axis.transformed(R2 * R1)
Пример #15
0
def test_slicer():

    FILE = os.path.join(HERE, '../..', 'data', '3DBenchy.stl')

    # ==============================================================================
    # Get benchy and construct a mesh
    # ==============================================================================

    benchy = Mesh.from_stl(FILE)

    # ==============================================================================
    # Create planes
    # ==============================================================================

    # replace by planes along a curve

    bbox = benchy.bounding_box()

    x, y, z = zip(*bbox)
    zmin, zmax = min(z), max(z)

    normal = Vector(0, 0, 1)
    planes = []
    for i in np.linspace(zmin, zmax, 50):
        plane = Plane(Point(0, 0, i), normal)
        planes.append(plane)

    # ==============================================================================
    # Slice
    # ==============================================================================

    M = benchy.to_vertices_and_faces()

    pointsets = slice_mesh(M, planes)

    # ==============================================================================
    # Process output
    # ==============================================================================

    polylines = []
    for points in pointsets:
        points = [Point(*point) for point in points]
        polyline = Polyline(points)
        polylines.append(polyline)
Пример #16
0
def _get_geometry_and_origin(primitive):
    shape = None
    origin = None
    if isinstance(primitive, compas.geometry.Box):
        shape = Box.from_geometry(primitive)
        origin = Origin(*primitive.frame)
    if isinstance(primitive, compas.geometry.Capsule):
        shape = Capsule.from_geometry(primitive)
        point = primitive.line.midpoint
        normal = primitive.line.vector
        plane = Plane(point, normal)
        origin = Origin.from_plane(plane)
    if isinstance(primitive, compas.geometry.Cylinder):
        shape = Cylinder.from_geometry(primitive)
        origin = Origin.from_plane(primitive.circle.plane)
    if isinstance(primitive, compas.geometry.Sphere):
        shape = Sphere.from_geometry(primitive)
        origin = Origin(primitive.point, [1, 0, 0], [0, 1, 0])
    if not shape:
        raise Exception('Unrecognized primitive type {}'.format(
            primitive.__class__))
    geometry = Geometry(shape)
    return geometry, origin
Пример #17
0
    def face_plane(self,plane_id):
        """Computes the plane of each face of a beam
        ----------
        plane_id: (int) ID of plane

        Return:
        ------
        compas plane 
        """

        origin_frame = self.frame.copy()
        if plane_id == 0:
            plane = Plane(origin_frame.point, origin_frame.xaxis) 

        elif plane_id == 1:
            face_1 = self.face_frame(1).copy()
            plane = Plane(face_1.point, face_1.yaxis)

        elif plane_id == 2:
            face_2 = self.face_frame(2).copy()
            plane = Plane(face_2.point, face_2.yaxis)

        elif plane_id == 3:
            face_3 = self.face_frame(3).copy()
            plane = Plane(face_3.point, face_3.yaxis)

        elif plane_id == 4:
            face_4 = self.face_frame(4).copy()
            plane = Plane(face_4.point, face_4.yaxis)

        elif plane_id == 5: #horizontal plane that at the center of the beam 
            center_point = self.center_point_at_beam_start()
            plane = Plane(center_point, self.frame.normal)

        elif plane_id == 6: #vertical plane that at the center of the beam 
            center_point = self.center_point_at_beam_start()
            plane = Plane(center_point, self.frame.yaxis)
            
        return plane
from compas.geometry import Frame
from compas.geometry import Plane
from compas.geometry import Vector

a = Vector(1, 0, 0)
b = Vector.from_start_end([1, 0, 0], [2, 0, 0])
assert a == b

a = Plane([0, 0, 0], [0, 0, 1])
b = Plane.from_three_points([0, 0, 0], [1, 0, 0], [0, 1, 0])
assert a == b

a = Frame([0, 0, 0], [3, 0, 0], [0, 2, 0])
b = Frame.from_points([0, 0, 0], [5, 0, 0], [1, 2, 0])
assert a == b
Пример #19
0
 def plane(self, plane):
     self._plane = Plane(plane[0], plane[1])
Пример #20
0
        xt, yt, zt, _ = np.dot(self.inversetransform, p)

        # d = np.sqrt((xt - self.torus.center.x)**2 +
        #             (yt - self.torus.center.y)**2) - self.torus.radius_axis
        # d2 = np.sqrt(d**2 + (zt - self.torus.center.z)**2)
        d = np.sqrt(xt**2 + yt**2) - self.torus.radius_axis
        d2 = np.sqrt(d**2 + zt**2)
        return d2 - self.torus.radius_pipe


if __name__ == "__main__":
    from compas.geometry import Plane
    import matplotlib.pyplot as plt
    import numpy as np

    o = VolTorus(Torus(Plane((2, 3, 0), (0.3, 0.2, 1)), 7.0, 4.0))
    print(o)

    x, y, z = np.ogrid[-13:13:60j, -13:13:60j, -13:13:60j]
    d = o.get_distance_numpy(x, y, z)
    plt.imshow(d[:, :, 30], cmap='RdBu')
    plt.show()

    for y in range(-15, 15):
        s = ''
        for x in range(-30, 30):
            d = o.get_distance(Point(x * 0.5, -y, 0))
            if d < 0:
                s += 'x'
            else:
                s += '.'
Пример #21
0
    def to_vertices_and_faces(self, u=10, v=10):
        """Returns a list of vertices and faces.

        Parameters
        ----------
        u : int, optional
            Number of faces in the "u" direction.
            Default is ``10``.
        v : int, optional
            Number of faces in the "v" direction.
            Default is ``10``.

        Returns
        -------
        (vertices, faces)
            A list of vertex locations and a list of faces,
            with each face defined as a list of indices into the list of vertices.
        """
        if u < 3:
            raise ValueError('The value for u should be u > 3.')
        if v < 3:
            raise ValueError('The value for v should be v > 3.')
        if v % 2 == 1:
            v += 1

        theta = pi / v
        phi = pi * 2 / u
        hpi = pi * 0.5
        halfheight = self.line.length / 2
        sidemult = -1
        capswitch = 0

        vertices = []
        for i in range(1, v + 1):
            for j in range(u):
                a = i + capswitch
                tx = self.radius * cos(a * theta - hpi) * cos(j * phi)
                ty = self.radius * cos(a * theta - hpi) * sin(j * phi)
                tz = self.radius * sin(a * theta - hpi) + sidemult * halfheight
                vertices.append([tx, ty, tz])
            # switch from lower pole cap to upper pole cap
            if i == v / 2 and sidemult == -1:
                capswitch = -1
                sidemult *= -1

        vertices.append([0, 0, halfheight + self.radius])
        vertices.append([0, 0, -halfheight - self.radius])

        # move points to correct location in space
        plane = Plane(self.line.midpoint, self.line.direction)
        frame = Frame.from_plane(plane)
        M = matrix_from_frame(frame)
        vertices = transform_points(vertices, M)

        faces = []

        # south pole triangle fan
        sp = len(vertices) - 1
        for j in range(u):
            faces.append([sp, (j + 1) % u, j])

        for i in range(v - 1):
            for j in range(u):
                jj = (j + 1) % u
                a = i * u + j
                b = i * u + jj
                c = (i + 1) * u + jj
                d = (i + 1) * u + j
                faces.append([a, b, c, d])

        # north pole triangle fan
        np = len(vertices) - 2
        for j in range(u):
            nc = len(vertices) - 3 - j
            nn = len(vertices) - 3 - (j + 1) % u
            faces.append([np, nn, nc])

        return vertices, faces
# Rhino
from compas.datastructures import Mesh
from compas.geometry import Circle
from compas.geometry import Cylinder
from compas.geometry import Frame
from compas.geometry import Plane
from compas.geometry import Translation
from compas.robots import Joint
from compas.robots import RobotModel
from compas_fab.rhino import RobotArtist
from compas_fab.robots import Configuration

# create cylinder in yz plane
radius, length = 0.3, 5
cylinder = Cylinder(Circle(Plane([0, 0, 0], [1, 0, 0]), radius), length)
cylinder.transform(Translation([length / 2., 0, 0]))

# create robot
robot = RobotModel("robot", links=[], joints=[])

# add first link to robot
link0 = robot.add_link("world")

# add second link to robot
mesh = Mesh.from_shape(cylinder)
link1 = robot.add_link("link1", visual_mesh=mesh, visual_color=(0.2, 0.5, 0.6))

# add the joint between the links
axis = (0, 0, 1)
origin = Frame.worldXY()
robot.add_joint("joint1", Joint.CONTINUOUS, link0, link1, origin, axis)
Пример #23
0
# ==============================================================================
# Main
# ==============================================================================

if __name__ == '__main__':

    from compas.geometry import Ellipse
    from compas.geometry import Point
    from compas.geometry import Plane
    from compas.geometry import Vector
    from compas.geometry import Translation
    from compas_plotters import GeometryPlotter

    plotter = GeometryPlotter()

    plane = Plane(Point(0, 0, 0), Vector(0, 0, 1))

    a = Ellipse(plane, 5.0, 3.0)
    b = Ellipse(plane, 2.0, 1.0)
    c = Ellipse(plane, 3.0, 1.0)

    T = Translation.from_vector([0.1, 0.0, 0.0])

    plotter.add(a, edgecolor='#ff0000', fill=False)
    plotter.add(b, edgecolor='#00ff00', fill=False)
    plotter.add(c, edgecolor='#0000ff', fill=False)

    plotter.pause(1.0)

    for i in range(100):
        a.transform(T)
Пример #24
0
from compas.datastructures import Mesh
from compas.datastructures import mesh_quads_to_triangles
from compas.datastructures import mesh_subdivide_quad

from compas_viewers.multimeshviewer import MultiMeshViewer
from compas_viewers.multimeshviewer.model import MeshObject

import compas_libigl as igl


origin = Point(0.0, 0.0, 0.0)

cube = Box.from_width_height_depth(1.0, 1.0, 1.0)
sphere = Sphere(origin, 0.95 * sqrt(0.5 ** 2 + 0.5 ** 2))

xcyl = Cylinder(Circle(Plane(origin, Vector(1.0, 0.0, 0.0)), 0.35), 2.0)
ycyl = Cylinder(Circle(Plane(origin, Vector(0.0, 1.0, 0.0)), 0.35), 2.0)
zcyl = Cylinder(Circle(Plane(origin, Vector(0.0, 0.0, 1.0)), 0.35), 2.0)

a = Mesh.from_vertices_and_faces(cube.vertices, cube.faces)
a = mesh_subdivide_quad(a, k=3)
b = Mesh.from_vertices_and_faces(* sphere.to_vertices_and_faces(u=30, v=30))
c = Mesh.from_vertices_and_faces(* xcyl.to_vertices_and_faces(u=30))
d = Mesh.from_vertices_and_faces(* ycyl.to_vertices_and_faces(u=30))
e = Mesh.from_vertices_and_faces(* zcyl.to_vertices_and_faces(u=30))

mesh_quads_to_triangles(a)
mesh_quads_to_triangles(b)
mesh_quads_to_triangles(c)
mesh_quads_to_triangles(d)
mesh_quads_to_triangles(e)
def RunCommand(is_interactive):

    #load Derivation and model
    derivation = Derivation.from_json(
        rhino_UI_utilities.get_json_file_location())
    model = derivation.get_next_step()

    #select beams
    selection_reference = []
    selection_reference.append(
        rs.GetObject(message="select start Beam", filter=32, preselect=True))
    selection_reference.extend(
        rs.GetObjects(message="select Beams to connect",
                      filter=32,
                      preselect=True))

    #load helpers
    helper = UI_helpers()

    #name search
    selected_beams = helper.extract_BeambyName(model, selection_reference)

    #check for parallel planes, uses the function above
    start_beam = selected_beams[0]
    beams_to_connect = selected_beams[1:]
    parallel_check = check_for_parallel_vectors(start_beam, beams_to_connect)
    if parallel_check != True:
        raise IndexError('beams are not parallel')
    else:
        print("beams are parallel")

    #check for coplanarity, uses the function above
    coplanar_planes = {}
    face_ids_coplanar_planes = {}
    for i in range(1, 5):
        start_beam_plane = start_beam.face_plane(i).copy()
        start_beam_origin = start_beam_plane.point
        a = get_coplanar_planes(start_beam_plane, start_beam_origin,
                                beams_to_connect)
        if a != False:
            coplanar_planes['' + str(i)] = a[0]
            face_ids_coplanar_planes['' + str(i)] = a[1]
        else:
            pass
    print("face_dictionary here", face_ids_coplanar_planes)
    if len(coplanar_planes.keys()) == 2:
        print("'success", coplanar_planes)
    else:
        raise IndexError('beams are not coplanar')

    #user inputs
    face_id = rs.GetInteger(("possible face connections " + "face_id " +
                             coplanar_planes.keys()[0] + " or face_id " +
                             coplanar_planes.keys()[1]), None, None, None)
    start_point = (helper.Get_SelectPointOnMeshEdge("Select mesh edge",
                                                    "Pick point on edge"))
    ext_start = rs.GetReal("extension length start", 200, None, None)
    ext_end = rs.GetReal("extension length end", 200, None, None)

    #list of coplanar planes extracted from coplanar_planes dict using face_id as key
    coplanar_planes_along_selected_face = []
    coplanar_planes_along_selected_face.append(
        start_beam.face_plane(face_id).copy())
    for key, value in coplanar_planes.items():
        if key == "" + str(face_id):
            coplanar_planes_along_selected_face.extend(value)

    #list of face_ids of coplanar planes
    coplanar_face_ids = []
    coplanar_face_ids.append(face_id)
    for key, value in face_ids_coplanar_planes.items():
        if key == "" + str(face_id):
            coplanar_face_ids.extend(value)

    #intersection points by passing a line from the origin of start beam to the adjacent planes of the coplanar planes of all beams
    points_to_compare = []
    for i in range(len(selected_beams)):
        beam = selected_beams[i]
        start_beam_selected_face_frame = selected_beams[0].face_frame(face_id)
        line_pt_a = start_beam_selected_face_frame.point
        normal = start_beam_selected_face_frame.normal
        line_pt_b = add_vectors(line_pt_a, scale_vector(normal, 0.3))
        line_to_intersect = Line(line_pt_a, line_pt_b)

        face_index = coplanar_face_ids[i]
        adjacent_planes = beam.neighbour_face_plane(face_index)
        for p in adjacent_planes:
            intersection_point = intersection_line_plane(line_to_intersect, p)
            points_to_compare.append(intersection_point)

    viz_pts = []
    #project distance from  points_to_compare to the plane of the start Beam
    distances = []
    start_beam_face_frame = start_beam.face_frame(face_id).copy()
    start_beam_Plane_perpendicular_to_face_id_Plane = Plane(
        start_beam_face_frame.point, start_beam_face_frame.normal)
    viz_pts.append(start_beam_Plane_perpendicular_to_face_id_Plane.point)
    for point in points_to_compare:
        viz_pts.append(point)
        vector = subtract_vectors(
            point, start_beam_Plane_perpendicular_to_face_id_Plane.point)
        distances.append(
            dot_vectors(
                vector,
                start_beam_Plane_perpendicular_to_face_id_Plane.normal))

    #search to find max point
    maximum_distance = max(distances)
    minimum_distance = min(distances)
    beam_length = (maximum_distance - minimum_distance) + ext_start + ext_end
    ext_len = maximum_distance + ext_start

    #project selected point to perpendicular planes of the beams to connect
    if coplanar_planes.keys()[0] == "1" or coplanar_planes.keys()[0] == "3":
        start_beam_perpendicular_plane = start_beam.face_plane(5).copy()

    elif coplanar_planes.keys()[0] == "2" or coplanar_planes.keys()[0] == "4":
        start_beam_perpendicular_plane = start_beam.face_plane(6).copy()

    tol = 1.0e-5
    # tol = 5.0
    perpendicular_plane = []
    for beam in beams_to_connect:
        for i in range(5, 7):
            beam_plane = beam.face_plane(i).copy()
            print("beam_plane", beam_plane)
            angle_check = start_beam_perpendicular_plane.normal.angle(
                beam_plane.normal)
            print("angle", angle_check)
            if (abs(angle_check) - 0) < tol or (abs(angle_check) - 180) < tol:
                perpendicular_plane.append(beam_plane)

    print(perpendicular_plane)
    print(len(perpendicular_plane))
    #project points
    projected_point_list = []
    new_start_point = project_points_plane([start_point],
                                           start_beam_perpendicular_plane)
    projected_point_list.extend(new_start_point)
    for plane in perpendicular_plane:
        new_point = project_points_plane(new_start_point, plane)
        projected_point_list.extend(new_point)

    #list of distance to move joints on match beam
    model.rule_Connect_90lap(selected_beams, projected_point_list,
                             coplanar_face_ids, beam_length, ext_len,
                             create_id())
    print(len(projected_point_list))
    print(projected_point_list)

    #Save Derivation (Model is also saved)
    derivation.to_json(rhino_UI_utilities.get_json_file_location(),
                       pretty=True)

    # Visualization
    viz_point = []
    for pt in projected_point_list:
        a = (pt[0], pt[1], pt[2])
        viz_point.append({'pos': a, 'color': (0, 255, 0)})

    artist = MeshArtist(None, layer='BEAM::Beams_out')
    artist.clear_layer()
    artist.draw_points(viz_point)
    for beam in model.beams:
        artist = MeshArtist(
            beam.mesh, layer='BEAM::Beams_out'
        )  #.mesh is not ideal fix in beam and assemble class
        artist.draw_faces(join_faces=True)
Пример #26
0
from numpy import array
from scipy.spatial import HalfspaceIntersection
from scipy.spatial import ConvexHull

from itertools import combinations

from compas.geometry import Plane, Vector
from compas.datastructures import Mesh

from compas_view2.app import App

left = Plane([-1, 0, 0], [-1, 0, 0])
right = Plane([+1, 0, 0], [+1, 0, 0])
top = Plane([0, 0, +1], [0, 0, +1])
bottom = Plane([0, 0, -1], [0, 0, -1])
front = Plane([0, -1, 0], [0, -1, 0])
back = Plane([0, +1, 0], [0, +1, 0])

halfspaces = array(
    [left.abcd, right.abcd, top.abcd, bottom.abcd, front.abcd, back.abcd],
    dtype=float)

interior = array([0, 0, 0], dtype=float)

hsi = HalfspaceIntersection(halfspaces, interior)
hull = ConvexHull(hsi.intersections)

mesh = Mesh.from_vertices_and_faces(
    [hsi.intersections[i] for i in hull.vertices], hull.simplices)
mesh.unify_cycles()
Пример #27
0
    descdent_tree[u][v] = {'jp': None, 'lp': None}
    descdent_tree[v][u] = {'jp': None, 'lp': None}

current_key = convex_hull_mesh.number_of_vertices()

for fkey in convex_hull_mesh.faces():
    f_centroid = convex_hull_mesh.face_centroid(fkey)
    vec = Vector.from_start_end(pt_center, f_centroid)

    # if the branches has a 'convex' corner,
    # flip the vec to the corresponding face.
    f_normal = convex_hull_mesh.face_normal(fkey)
    angle = angle_vectors(f_normal, vec, False)
    if angle > math.pi * 0.5:
        # vec.scale(-1)
        pln = Plane(pt_center, f_normal)
        pt_mirror = mirror_point_plane(f_centroid, pln)
        vec = Vector.from_start_end(pt_center, pt_mirror)

        # angle = math.pi - angle

    vec.unitize()
    # dist = joint_width / math.cos(angle)
    # vec.scale(dist)
    vec.scale(joint_width)

    pt = add_vectors(pt_center, vec)

    face = convex_hull_mesh.face[fkey]
    v_keys = face + [face[0]]
    for u, v in pairwise(v_keys):
OFFSET_1 = 0.03

# ==============================================================================
# Build blocks
# ==============================================================================
blocks = []

for face_key in cablenet.faces():
    vertices = cablenet.face_vertices(face_key)
    points = cablenet.get_vertices_attributes('xyz', keys=vertices)
    normals = [cablenet.vertex_normal(key) for key in vertices]

    face_normal = cablenet.face_normal(face_key)
    face_normal = scale_vector(face_normal, THICKNESS)
    point = add_vectors(points[0], face_normal)
    top_plane = Frame.from_plane(Plane(point, face_normal))

    bottom = points[:]
    top = []
    for point, normal in zip(points, normals):
        pt = point_on_plane(point, top_plane, normal)
        top.append(pt)

    bottom = offset_polygon_xy(bottom, OFFSET_0)
    top = offset_polygon_xy(top, OFFSET_1, True)

    vertices = bottom + top

    faces = [[0, 3, 2, 1], [4, 5, 6, 7], [3, 0, 4, 7], [2, 3, 7, 6],
             [1, 2, 6, 5], [0, 1, 5, 4]]
    block = Mesh.from_vertices_and_faces(vertices, faces)
Пример #29
0
from compas.geometry import Vector, Point, Plane
from compas.geometry import Polyline
from compas.geometry import Circle
from compas_occ.geometry import OCCNurbsCurve
from compas_view2.app import App

circle = Circle(Plane(Point(0, 0, 0), Vector(0, 0, 1)), 1.0)
curve = OCCNurbsCurve.from_circle(circle)

# ==============================================================================
# Visualisation
# ==============================================================================

view = App()

view.add(Polyline(curve.locus()), linewidth=3)
view.add(Polyline(curve.points),
         show_points=True,
         pointsize=20,
         pointcolor=(1, 0, 0),
         linewidth=1,
         linecolor=(0.3, 0.3, 0.3))

view.run()
Пример #30
0
from compas.geometry import Plane
from compas_rhino.artists import BoxArtist
from compas_rhino.artists import MeshArtist
from compas.datastructures import Mesh

# Define a Frame, which is not in the origin and a bit tilted to the world frame
frame = Frame([4, 4, 4], [.5, 1, 2], [0, 1, 2])

# Create a Box with that frame
width, length, height = 1, 1, 1
box = Box(frame, width, length, height)

# Create a Projection (can be orthogonal, parallel or perspective)
point = [0, 0, 0]
normal = [0, 0, 1]
plane = Plane(point, normal)
direction = [1, 1, 1]
P = Projection.from_plane_and_direction(plane, direction)

# Create a Mesh from the Box
mesh = Mesh.from_shape(box)

# Apply the Projection onto the mesh
mesh_projected = mesh.transformed(P)

# Create artists
artist1 = BoxArtist(box)
artist2 = MeshArtist(mesh_projected)

# Draw
artist1.draw()