Example #1
0
def show(*cad_objs, render_mates=None, mate_scale=None, **kwargs):
    """Show CAD objects in Jupyter

    Valid keywords:
    - height:            Height of the CAD view (default=600)
    - tree_width:        Width of navigation tree part of the view (default=250)
    - cad_width:         Width of CAD view part of the view (default=800)
    - bb_factor:         Scale bounding box to ensure compete rendering (default=1.5)
    - default_color:     Default mesh color (default=(232, 176, 36))
    - default_edgecolor: Default mesh color (default=(128, 128, 128))
    - render_edges:      Render edges  (default=True)
    - render_normals:    Render normals (default=False)
    - render_mates:      Render mates (for MAssemblies)
    - mate_scale:        Scale of rendered mates (for MAssemblies)
    - quality:           Linear deflection for tessellation (default=None)
                         If None, uses bounding box as in (xlen + ylen + zlen) / 300 * deviation)
    - deviation:         Deviation from default for linear deflection value ((default=0.1)
    - angular_tolerance: Angular deflection in radians for tessellation (default=0.2)
    - edge_accuracy:     Presicion of edge discretizaion (default=None)
                         If None, uses: quality / 100
    - optimal_bb:        Use optimal bounding box (default=False)
    - axes:              Show axes (default=False)
    - axes0:             Show axes at (0,0,0) (default=False)
    - grid:              Show grid (default=False)
    - ticks:             Hint for the number of ticks in both directions (default=10)
    - ortho:             Use orthographic projections (default=True)
    - transparent:       Show objects transparent (default=False)
    - ambient_intensity  Intensity of ambient ligth (default=1.0)
    - direct_intensity   Intensity of direct lights (default=0.12)
    - position:          Relative camera position that will be scaled (default=(1, 1, 1))
    - rotation:          z, y and y rotation angles to apply to position vector (default=(0, 0, 0))
    - zoom:              Zoom factor of view (default=2.5)
    - reset_camera:      Reset camera position, rotation and zoom to default (default=True)
    - mac_scrollbar:     Prettify scrollbars (default=True)
    - display:           Select display: "sidecar", "cell", "html"
    - tools:             Show the viewer tools like the object tree
    - timeit:            Show rendering times, levels = False, 0,1,2,3,4,5 (default=False)

    For example isometric projection can be achieved in two ways:
    - position = (1, 1, 1)
    - position = (0, 0, 1) and rotation = (45, 35.264389682, 0)
    """
    render_mates = render_mates or get_default("render_mates")
    mate_scale = mate_scale or get_default("mate_scale")
    default_color = kwargs.get("default_color") or get_default("default_color")

    assembly = to_assembly(*cad_objs, render_mates=render_mates, mate_scale=mate_scale, default_color=default_color)

    if assembly is None:
        raise ValueError("%s cannot be viewed" % cad_objs)

    if len(assembly.objects) == 1 and isinstance(assembly.objects[0], PartGroup):
        # omit leading "PartGroup" group
        return _show(assembly.objects[0], **kwargs)
    else:
        return _show(assembly, **kwargs)
Example #2
0
def show(*cad_objs, render_mates=None, mate_scale=None, **kwargs):
    """Show CAD objects in Jupyter

    Valid keywords:
    - height:            Height of the CAD view (default=600)
    - tree_width:        Width of navigation tree part of the view (default=250)
    - cad_width:         Width of CAD view part of the view (default=800)
    - bb_factor:         Scale bounding box to ensure compete rendering (default=1.0)
    - render_shapes:     Render shapes  (default=True)
    - render_edges:      Render edges  (default=True)
    - render_mates:      For MAssemblies, whether to rander the mates (default=True)
    - mate_scale:        For MAssemblies, scale of rendered mates (default=1)
    - quality:           Tolerance for tessellation (default=0.1)
    - angular_tolerance: Angular tolerance for building the mesh for tessellation (default=0.1)
    - edge_accuracy:     Presicion of edge discretizaion (default=0.01)
    - optimal_bb:        Use optimal bounding box (default=True)
    - axes:              Show axes (default=False)
    - axes0:             Show axes at (0,0,0) (default=False)
    - grid:              Show grid (default=False)
    - ortho:             Use orthographic projections (default=True)
    - transparent:       Show objects transparent (default=False)
    - position:          Relative camera position that will be scaled (default=(1, 1, 1))
    - rotation:          z, y and y rotation angles to apply to position vector (default=(0, 0, 0))
    - zoom:              Zoom factor of view (default=2.5)
    - mac_scrollbar:     Prettify scrollbasrs on Macs (default=True)
    - display:           Select display: "sidecar", "cell", "html"
    - tools:             Show the viewer tools like the object tree
    - timeit:            Show rendering times (default=False)

    For example isometric projection can be achieved in two ways:
    - position = (1, 1, 1)
    - position = (0, 0, 1) and rotation = (45, 35.264389682, 0)
    """
    render_mates = render_mates or get_default("render_mates")
    mate_scale = mate_scale or get_default("mate_scale")

    assembly = to_assembly(*cad_objs,
                           render_mates=render_mates,
                           mate_scale=mate_scale)

    if assembly is None:
        raise ValueError("%s cannot be viewed" % cad_objs)

    if len(assembly.objects) == 1 and isinstance(assembly.objects[0],
                                                 PartGroup):
        # omit leading "PartGroup" group
        return _show(assembly.objects[0], **kwargs)
    else:
        return _show(assembly, **kwargs)
Example #3
0
    def __init__(self,
                 shape,
                 name="Part",
                 color=None,
                 show_faces=True,
                 show_edges=True):
        super().__init__()
        self.name = name
        self.id = self.next_id()
        self.color = Color(
            get_default("default_color") if color is None else color)

        self.shape = shape
        self.set_states(show_faces, show_edges)
Example #4
0
def _show(assembly, **kwargs):
    for k in kwargs:
        if get_default(k) is None:
            raise KeyError("Paramater %s is not a valid argument for show()" % k)

    mapping = assembly.to_state()
    shapes = assembly.collect_mapped_shapes(mapping)
    tree = tree = assembly.to_nav_dict()

    d = CadqueryDisplay()
    widget = d.create(**kwargs)
    d.display(widget)
    d.add_shapes(shapes=shapes, mapping=mapping, tree=tree)

    d.info.ready_msg(d.cq_view.grid.step)

    return d
Example #5
0
def from_assembly(cad_obj, top, loc=None, render_mates=False, mate_scale=1, default_color=None):
    loc = Location()
    render_loc = cad_obj.loc

    if cad_obj.color is None:
        if default_color is None:
            color = Color(get_default("default_color"))
        else:
            color = Color(default_color)
    else:
        color = Color(get_rgb(cad_obj.color))

    parent = [
        Part(
            Workplane(shape),
            "%s_%d" % (cad_obj.name, i),
            color=color,
        )
        for i, shape in enumerate(cad_obj.shapes)
    ]

    if render_mates and cad_obj.mates is not None:
        RGB = (Color((255, 0, 0)), Color((0, 128, 0)), Color((0, 0, 255)))
        parent.append(
            PartGroup(
                [
                    Edges(to_edge(mate_def.mate, scale=mate_scale), name=name, color=RGB)
                    for name, mate_def in top.mates.items()
                    if mate_def.assembly == cad_obj
                ],
                name="mates",
                loc=Location(),  # mates inherit the parent location, so actually add a no-op
            )
        )

    children = [from_assembly(c, top, loc, render_mates, mate_scale) for c in cad_obj.children]
    return PartGroup(parent + children, cad_obj.name, loc=render_loc)
Example #6
0
 def __init__(self, shape, name="Part", color=None, show_faces=True, show_edges=True):
     if color is None:
         color = get_default("default_color")
     super().__init__(_to_occ(shape), name, color, show_faces, show_edges)
Example #7
0
def to_assembly(*cad_objs, render_mates=None, mate_scale=1, default_color=None):
    default_color = get_default("default_color") if default_color is None else default_color
    assembly = PartGroup([], "Group")
    obj_id = 0
    for cad_obj in cad_objs:
        if isinstance(cad_obj, (PartGroup, Part, Faces, Edges, Vertices)):
            assembly.add(cad_obj)

        elif HAS_MASSEMBLY and isinstance(cad_obj, MAssembly):
            assembly.add(
                from_assembly(
                    cad_obj, cad_obj, render_mates=render_mates, mate_scale=mate_scale, default_color=default_color
                )
            )

        elif isinstance(cad_obj, CqAssembly):
            assembly.add(from_assembly(cad_obj, cad_obj, default_color=default_color))

        elif isinstance(cad_obj, Edge):
            assembly.add_list(_from_edgelist(Workplane(cad_obj), obj_id))

        elif isinstance(cad_obj, Face):
            assembly.add_list(_from_facelist(Workplane(cad_obj), obj_id))

        elif isinstance(cad_obj, Wire):
            assembly.add(_from_wirelist(Workplane(cad_obj), obj_id))

        elif isinstance(cad_obj, Vertex):
            assembly.add_list(_from_vertexlist(Workplane(cad_obj), obj_id))

        elif is_cqparts(cad_obj):
            assembly = convert_cqparts(cad_obj)

        elif _is_facelist(cad_obj):
            assembly.add_list(_from_facelist(cad_obj, obj_id))

        elif _is_edgelist(cad_obj):
            assembly.add_list(_from_edgelist(cad_obj, obj_id))

        elif _is_wirelist(cad_obj):
            assembly.add(_from_wirelist(cad_obj, obj_id))

        elif _is_vertexlist(cad_obj):
            assembly.add_list(_from_vertexlist(cad_obj, obj_id))

        elif isinstance(cad_obj, Vector):
            assembly.add_list(_from_vector(cad_obj, obj_id))

        elif isinstance(cad_obj, (Shape, Compound)):
            assembly.add(_from_workplane(Workplane(cad_obj), obj_id, default_color=default_color))

        elif isinstance(cad_obj.val(), Vector):
            assembly.add_list(_from_vectorlist(cad_obj, obj_id))

        elif isinstance(cad_obj, Workplane):
            assembly.add(_from_workplane(cad_obj, obj_id, default_color=default_color))

        else:
            raise NotImplementedError("Type:", cad_obj)

        obj_id += 1
    return assembly
Example #8
0
def _show(part_group, **kwargs):
    for k in kwargs:
        if get_default(k, "n/a") == "n/a":
            raise KeyError(f"Paramater {k} is not a valid argument for show()")

    if kwargs.get("cad_width") is not None and kwargs.get("cad_width") < 640:
        warn("cad_width has to be >= 640, setting to 640")
        kwargs["cad_width"] = 640

    if kwargs.get("height") is not None and kwargs.get("height") < 400:
        warn("height has to be >= 400, setting to 400")
        kwargs["height"] = 400

    if kwargs.get("tree_width") is not None and kwargs.get("tree_width") < 250:
        warn("tree_width has to be >= 250, setting to 250")
        kwargs["tree_width"] = 250

    # remove all tessellation and view parameters
    create_args, add_shape_args = split_args(kwargs)

    preset = lambda key, value: get_default(key) if value is None else value

    timeit = preset("timeit", kwargs.get("timeit"))

    with Timer(timeit, "", "overall"):

        with Timer(timeit, "", "setup display", 1):
            num_shapes = part_group.count_shapes()
            d = get_or_create_display(**create_args)
            d.init_progress(2 * num_shapes)

        with Timer(timeit, "", "tessellate", 1):

            mapping = part_group.to_state()
            shapes = part_group.collect_mapped_shapes(
                mapping,
                quality=preset("quality", kwargs.get("quality")),
                deviation=preset("deviation", kwargs.get("deviation")),
                angular_tolerance=preset("angular_tolerance",
                                         kwargs.get("angular_tolerance")),
                edge_accuracy=preset("edge_accuracy",
                                     kwargs.get("edge_accuracy")),
                render_edges=preset("render_edges",
                                    kwargs.get("render_edges")),
                render_normals=preset("render_normals",
                                      kwargs.get("render_normals")),
                progress=d.progress,
                timeit=timeit,
            )
            tree = part_group.to_nav_dict()

        with Timer(timeit, "", "show shapes", 1):
            d.add_shapes(shapes=shapes,
                         mapping=mapping,
                         tree=tree,
                         bb=_combined_bb(shapes),
                         **add_shape_args)

    d.info.version_msg(__version__)
    d.info.ready_msg(d.cq_view.grid.step)

    sidecar = has_sidecar()
    if sidecar is not None:
        print(f"Done, using side car '{sidecar.title()}'")

    return d
Example #9
0
 def __init__(self):
     self.color = Color(get_default("default_color"))