Example #1
0
    def apply_blade_offset(self, path, job):
        """ Apply blade offset to the given path.

        """
        params = []
        e = None
        cmd = None
        qf = getattr(job.config, 'quality_factor', 1)

        # Holds the blade path
        blade_path = QPainterPath()
        offset_path = QPainterPath()

        for i in range(path.elementCount()):
            e = path.elementAt(i)

            # Finish the previous curve (if there was one)
            if cmd == CurveToElement and e.type != CurveToDataElement:
                n = len(params)
                if n == 2:
                    self.process_quad(offset_path, blade_path, params, qf)
                elif n == 3:
                    self.process_cubic(offset_path, blade_path, params, qf)
                else:
                    raise ValueError("Unexpected curve data length %s" % n)
                params = []

            # Reconstruct the path
            if e.type == MoveToElement:
                cmd = MoveToElement
                self.process_move(offset_path, blade_path, [QPointF(e.x, e.y)])
            elif e.type == LineToElement:
                cmd = LineToElement
                self.process_line(offset_path, blade_path, [QPointF(e.x, e.y)])
            elif e.type == CurveToElement:
                cmd = CurveToElement
                params = [QPointF(e.x, e.y)]
            elif e.type == CurveToDataElement:
                params.append(QPointF(e.x, e.y))

        # Finish the previous curve (if there was one)
        if params and e.type != CurveToDataElement:
            n = len(params)
            if n == 2:
                self.process_quad(offset_path, blade_path, params, qf)
            elif n == 3:
                self.process_cubic(offset_path, blade_path, params, qf)
        return offset_path
Example #2
0
def split_painter_path(path):
    """ Split a QPainterPath into subpaths. """
    if not isinstance(path, QPainterPath):
        raise TypeError("path must be a QPainterPath, got: {}".format(path))

    # Element types
    MoveToElement = QPainterPath.MoveToElement
    LineToElement = QPainterPath.LineToElement
    CurveToElement = QPainterPath.CurveToElement
    CurveToDataElement = QPainterPath.CurveToDataElement

    subpaths = []
    params = []
    e = None

    def finish_curve(p, params):
        if len(params) == 2:
            p.quadTo(*params)
        elif len(params) == 3:
            p.cubicTo(*params)
        else:
            raise ValueError("Invalid curve parameters: {}".format(params))

    for i in range(path.elementCount()):
        e = path.elementAt(i)

        # Finish the previous curve (if there was one)
        if params and e.type != CurveToDataElement:
            finish_curve(p, params)
            params = []

        # Reconstruct the path 
        if e.type == MoveToElement:
            p = QPainterPath()
            p.moveTo(e.x, e.y)
            subpaths.append(p)
        elif e.type == LineToElement:
            p.lineTo(e.x, e.y)
        elif e.type == CurveToElement:
            params = [QPointF(e.x, e.y)]
        elif e.type == CurveToDataElement:
            params.append(QPointF(e.x, e.y))

    # Finish the previous curve (if there was one)
    if params and e and e.type != CurveToDataElement:
        finish_curve(p, params)
    return subpaths
Example #3
0
    def add_continuity_correction(self, offset_path, blade_path, point):
        """ Adds if the upcoming angle and previous angle are not the same
        we need to correct for that difference by "arcing back" about the
        current blade point with a radius equal to the offset.

        """
        # Current blade position
        cur = blade_path.currentPosition()

        # Determine direction of next move
        sp = QPainterPath()
        sp.moveTo(cur)
        sp.lineTo(point)
        next_angle = sp.angleAtPercent(1)

        # Direction of last move
        angle = blade_path.angleAtPercent(1)

        # If not continuous it needs corrected with an arc
        if isnan(angle) or isnan(next_angle):
            return
        if abs(angle - next_angle) > self.config.cutoff:
            r = self.config.offset
            a = radians(next_angle)
            dx, dy = r*cos(a), -r*sin(a)
            po = QPointF(cur.x()+dx, cur.y()+dy)

            c = offset_path.currentPosition()
            dx, dy = po.x()-cur.x()+c.x()-cur.x(), po.y()-cur.y()+c.y()-cur.y()
            c1 = QPointF(cur.x()+dx, cur.y()+dy)
            offset_path.quadTo(c1, po)
Example #4
0
 def splitAtPercent(self, t):
     paths = []
     path = QPainterPath()
     i = 0
     while i < self.elementCount():
         e = self.elementAt(i)
         if e.type == ElementType.MoveToElement:
             if not path.isEmpty():
                 paths.append(path)
             path = QPainterPath(QPointF(e.x, e.y))
         elif e.type == ElementType.LineToElement:
             path.lineTo(QPointF(e.x, e.y))
         elif e.type == ElementType.CurveToElement:
             e1, e2 = self.elementAt(i + 1), self.elementAt(i + 2)
             path.cubicTo(QPointF(e.x, e.y), QPointF(e1.x, e1.y),
                          QPointF(e2.x, e2.y))
             i += 2
         else:
             raise ValueError("Invalid element type %s" % (e.type, ))
         i += 1
     if not path.isEmpty():
         paths.append(path)
     return paths
Example #5
0
    def move_path(self):
        """ Returns the path the head moves when not cutting

        """
        # Compute the negative
        path = QPainterPath()
        for i in range(self.model.elementCount()):
            e = self.model.elementAt(i)
            if e.isMoveTo():
                path.lineTo(e.x, e.y)
            else:
                path.moveTo(e.x, e.y)
        return path
Example #6
0
def split_painter_path(path):
    """ Split a QPainterPath into subpaths. """
    if not isinstance(path, QPainterPath):
        raise TypeError("path must be a QPainterPath, got: {}".format(path))

    # Element types
    MoveToElement = QPainterPath.MoveToElement
    LineToElement = QPainterPath.LineToElement
    CurveToElement = QPainterPath.CurveToElement
    CurveToDataElement = QPainterPath.CurveToDataElement

    subpaths = []
    params = []
    e = None

    def finish_curve(p, params):
        if len(params) == 2:
            p.quadTo(*params)
        elif len(params) == 3:
            p.cubicTo(*params)
        else:
            raise ValueError("Invalid curve parameters: {}".format(params))

    for i in range(path.elementCount()):
        e = path.elementAt(i)

        # Finish the previous curve (if there was one)
        if params and e.type != CurveToDataElement:
            finish_curve(p, params)
            params = []

        # Reconstruct the path
        if e.type == MoveToElement:
            p = QPainterPath()
            p.moveTo(e.x, e.y)
            subpaths.append(p)
        elif e.type == LineToElement:
            p.lineTo(e.x, e.y)
        elif e.type == CurveToElement:
            params = [QPointF(e.x, e.y)]
        elif e.type == CurveToDataElement:
            params.append(QPointF(e.x, e.y))

    # Finish the previous curve (if there was one)
    if params and e and e.type != CurveToDataElement:
        finish_curve(p, params)
    return subpaths
Example #7
0
def join_painter_paths(paths):
    """ Join a list of QPainterPath into a single path """
    result = QPainterPath()
    for p in paths:
        result.addPath(p)
    return result
Example #8
0
    def create(self, swap_xy=False, scale=None):
        """ Create a path model that is rotated and scaled

        """
        model = QPainterPath()

        if not self.path:
            return

        path = self._create_copy()

        # Update size
        bbox = path.boundingRect()
        self.size = [bbox.width(), bbox.height()]

        # Create copies
        c = 0
        points = self._copy_positions_iter(path)

        if self.auto_copies:
            self.stack_size = self._compute_stack_sizes(path)
            if self.stack_size[0]:
                copies_left = self.copies % self.stack_size[0]
                if copies_left:  # not a full stack
                    with self.events_suppressed():
                        self.copies = self._desired_copies
                        self.add_stack()

        while c < self.copies:
            x, y = next(points)
            model.addPath(path * QTransform.fromTranslate(x, -y))
            c += 1

        # Create weedline
        if self.plot_weedline:
            self._add_weedline(model, self.plot_weedline_padding)

        # Determine padding
        bbox = model.boundingRect()
        if self.align_center[0]:
            px = (self.material.width() - bbox.width()) / 2.0
        else:
            px = self.material.padding_left

        if self.align_center[1]:
            py = -(self.material.height() - bbox.height()) / 2.0
        else:
            py = -self.material.padding_bottom

        # Scale and rotate
        if scale:
            model *= QTransform.fromScale(*scale)
            px, py = px * abs(scale[0]), py * abs(scale[1])

        if swap_xy:
            t = QTransform()
            t.rotate(90)
            model *= t

        # Move to 0,0
        bbox = model.boundingRect()
        p = bbox.bottomLeft()
        tx, ty = -p.x(), -p.y()

        # If swapped, make sure padding is still correct
        if swap_xy:
            px, py = -py, -px
        tx += px
        ty += py

        model = model * QTransform.fromTranslate(tx, ty)

        end_point = (QPointF(0, -self.feed_after + model.boundingRect().top())
                     if self.feed_to_end else QPointF(0, 0))
        model.moveTo(end_point)

        return model
Example #9
0
    def arc(self, x1, y1, rx, ry, phi, large_arc_flag, sweep_flag, x2o, y2o):

        # handle rotated arcs as normal arcs that are transformed as a rotation
        if phi != 0:
            x2 = x1 + (x2o - x1) * cos(radians(phi)) + (y2o - y1) * sin(
                radians(phi))
            y2 = y1 - (x2o - x1) * sin(radians(phi)) + (y2o - y1) * cos(
                radians(phi))
        else:
            x2, y2 = x2o, y2o

        # https://www.w3.org/TR/SVG/implnote.html F.6.6
        rx = abs(rx)
        ry = abs(ry)

        # https://www.w3.org/TR/SVG/implnote.html F.6.5
        x1prime = (x1 - x2) / 2
        y1prime = (y1 - y2) / 2

        # https://www.w3.org/TR/SVG/implnote.html F.6.6
        lamb = (x1prime * x1prime) / (rx * rx) + (y1prime * y1prime) / (ry *
                                                                        ry)
        if lamb >= 1:
            ry = sqrt(lamb) * ry
            rx = sqrt(lamb) * rx

        # Back to https://www.w3.org/TR/SVG/implnote.html F.6.5
        radicand = (rx * rx * ry * ry - rx * rx * y1prime * y1prime -
                    ry * ry * x1prime * x1prime)
        radicand /= (rx * rx * y1prime * y1prime + ry * ry * x1prime * x1prime)

        if radicand < 0:
            radicand = 0

        factor = (-1 if large_arc_flag == sweep_flag else 1) * sqrt(radicand)

        cxprime = factor * rx * y1prime / ry
        cyprime = -factor * ry * x1prime / rx

        cx = cxprime + (x1 + x2) / 2
        cy = cyprime + (y1 + y2) / 2

        start_theta = -atan2((y1 - cy) * rx, (x1 - cx) * ry)

        start_phi = -atan2((y1 - cy) / ry, (x1 - cx) / rx)
        end_phi = -atan2((y2 - cy) / ry, (x2 - cx) / rx)

        sweep_length = end_phi - start_phi

        if sweep_length < 0 and not sweep_flag:
            sweep_length += 2 * pi
        elif sweep_length > 0 and sweep_flag:
            sweep_length -= 2 * pi

        if phi != 0:
            rotarc = QPainterPath()
            rotarc.moveTo(x1, y1)
            rotarc.arcTo(cx - rx, cy - ry, rx * 2, ry * 2,
                         start_theta * 360 / 2 / pi,
                         sweep_length * 360 / 2 / pi)

            t = QTransform()
            t.translate(x1, y1)
            t.rotate(phi)
            t.translate(-x1, -y1)
            tmp = rotarc * t
            rotarc -= rotarc
            rotarc += tmp
            self.addPath(rotarc)

        else:
            self.arcTo(cx - rx, cy - ry, rx * 2, ry * 2,
                       start_theta * 360 / 2 / pi, sweep_length * 360 / 2 / pi)
Example #10
0
    def process_cubic(self, offset_path, blade_path, params, quality):
        """ Add offset correction to a cubic bezier.
        """
        r = self.config.offset
        p0 = blade_path.currentPosition()
        p1, p2, p3 = params
        self.add_continuity_correction(offset_path, blade_path, p1)

        curve = QPainterPath()
        curve.moveTo(p0)
        curve.cubicTo(*params)
        p = QPainterPath()
        p.moveTo(p0)

        if quality == 1:
            polygon = curve.toSubpathPolygons(IDENITY_MATRIX)[0]
        else:
            m = QTransform.fromScale(quality, quality)
            m_inv = QTransform.fromScale(1/quality, 1/quality)
            polygon = m_inv.map(curve.toSubpathPolygons(m)[0])

        for point in polygon:
            p.lineTo(point)
            t = curve.percentAtLength(p.length())
            angle = curve.angleAtPercent(t)
            a = radians(angle)
            dx, dy = r*cos(a), -r*sin(a)
            offset_path.lineTo(point.x()+dx, point.y()+dy)

        blade_path.cubicTo(*params)
Example #11
0
    def request_relayout(self):
        # y = 0.0

        # for child in self.children():
        #     if not isinstance(child, QtContainer):
        #         continue
        #     scene_proxy = self._proxies[child]
        #     width, height = child._layout_manager.best_size()
        #     scene_proxy.setPos(0.0, y)
        #     y += height + 25.0

        for p in self._edge_paths:
            self.scene.removeItem(p)
        self._edge_paths = []

        g = pygraphviz.AGraph(directed=True)
        g.graph_attr['nodesep'] = 100
        g.graph_attr['ranksep'] = 50
        g.node_attr['shape'] = 'rect'

        children_names = {child.declaration.name for child in self.children() if isinstance(child, QtContainer)}

        if any(from_ not in children_names or to not in children_names for (from_, to) in self.declaration.edges):
            # hasn't finished being set up yet
            return

        for child in self.children():
            if not isinstance(child, QtContainer):
                continue
            scene_proxy = self._proxy(child)
            width, height = child._layout_manager.best_size()
            scene_proxy.setGeometry(QRectF(0.0, 0.0, width, height))
            g.add_node(child.declaration.name, width=width, height=height)

        for from_, to in self.declaration.edges:
            g.add_edge(from_, to)

        g.layout(prog='dot')

        for child in self.children():
            if not isinstance(child, QtContainer):
                continue
            scene_proxy = self._proxies[child]
            node = g.get_node(child.declaration.name)
            center_x, center_y = (-float(v)/72.0 for v in node.attr['pos'].split(','))
            width, height = child._layout_manager.best_size()
            x = center_x - (width / 2.0)
            y = center_y - (height / 2.0)
            scene_proxy.setPos(x, y)

        for from_, to in self.declaration.edges:
            if from_ not in children_names or to not in children_names:
                continue
            edge = g.get_edge(from_, to)
            # TODO: look at below code
            all_points = [tuple(-float(v)/72.0 for v in t.strip('e,').split(',')) for t in edge.attr['pos'].split(' ')]
            arrow = all_points[0]
            start_point = all_points[1]

            painter = QPainterPath(QPointF(*start_point))
            for c1, c2, end in grouper(all_points[2:], 3):
                painter.cubicTo(QPointF(*c1), QPointF(*c2), QPointF(*end))

            self._edge_paths.append(self.scene.addPath(painter))

        rect = self.scene.itemsBoundingRect()
        # Enlarge the rect so there is enough room at right and bottom
        rect.setX(rect.x() - self.LEFT_PADDING)
        rect.setY(rect.y() - self.TOP_PADDING)
        rect.setWidth(rect.width() + 2 * self.LEFT_PADDING)
        rect.setHeight(rect.height() + 2 * self.TOP_PADDING)

        self.scene.setSceneRect(rect)
        self.widget.viewport().update()

        self.show_selected()
Example #12
0
    def request_relayout(self):
        # y = 0.0

        # for child in self.children():
        #     if not isinstance(child, QtContainer):
        #         continue
        #     scene_proxy = self._proxies[child]
        #     width, height = child._layout_manager.best_size()
        #     scene_proxy.setPos(0.0, y)
        #     y += height + 25.0

        for p in self._edge_paths:
            self.scene.removeItem(p)
        self._edge_paths = []

        g = pygraphviz.AGraph(directed=True)
        g.graph_attr['nodesep'] = 100
        g.graph_attr['ranksep'] = 50
        g.node_attr['shape'] = 'rect'

        children_names = {child.declaration.name for child in self.children() if isinstance(child, QtContainer)}

        if any(from_ not in children_names or to not in children_names for (from_, to) in self.declaration.edges):
            # hasn't finished being set up yet
            return

        for child in self.children():
            if not isinstance(child, QtContainer):
                continue
            scene_proxy = self._proxy(child)
            width, height = child._layout_manager.best_size()
            scene_proxy.setGeometry(QRectF(0.0, 0.0, width, height))
            g.add_node(child.declaration.name, width=width, height=height)

        for from_, to in self.declaration.edges:
            g.add_edge(from_, to)

        before = time.time()
        g.layout(prog='dot')
        after = time.time()

        for child in self.children():
            if not isinstance(child, QtContainer):
                continue
            scene_proxy = self._proxies[child]
            node = g.get_node(child.declaration.name)
            center_x, center_y = (-float(v)/72.0 for v in node.attr['pos'].split(','))
            width, height = child._layout_manager.best_size()
            x = center_x - (width / 2.0)
            y = center_y - (height / 2.0)
            scene_proxy.setPos(x, y)

        for from_, to in self.declaration.edges:
            if from_ not in children_names or to not in children_names:
                continue
            edge = g.get_edge(from_, to)
            # TODO: look at below code
            all_points = [tuple(-float(v)/72.0 for v in t.strip('e,').split(',')) for t in edge.attr['pos'].split(' ')]
            arrow = all_points[0]
            start_point = all_points[1]

            painter = QPainterPath(QPointF(*start_point))
            for c1, c2, end in grouper(all_points[2:], 3):
                painter.cubicTo(QPointF(*c1), QPointF(*c2), QPointF(*end))

            self._edge_paths.append(self.scene.addPath(painter))

        self.show_selected()
Example #13
0
    def request_relayout(self):
        # y = 0.0

        # for child in self.children():
        #     if not isinstance(child, QtContainer):
        #         continue
        #     scene_proxy = self._proxies[child]
        #     width, height = child._layout_manager.best_size()
        #     scene_proxy.setPos(0.0, y)
        #     y += height + 25.0

        # Remove all paths
        for p in self._edge_paths:
            self.scene.removeItem(p)
        self._edge_paths = []

        children_names = {child.declaration.name for child in self.children() if isinstance(child, QtContainer)}

        if self.declaration.edges and \
                any(from_ not in children_names or to not in children_names for (from_, to) in self.declaration.edges):
            # hasn't finished being set up yet
            return

        for child in self.children():
            if not isinstance(child, QtContainer):
                continue
            scene_proxy = self._proxy(child)
            width, height = child._layout_manager.best_size()
            scene_proxy.setGeometry(QRectF(0.0, 0.0, width, height))

        node_coords, edge_coords = self._layout_nodes_and_edges(self.declaration.func_addr)

        if not node_coords:
            return

        for child in self.children():
            if not isinstance(child, QtContainer):
                continue
            scene_proxy = self._proxies[child]
            # width, height = child._layout_manager.best_size()
            x, y = node_coords[child.declaration.addr]
            scene_proxy.setPos(x, y)

        for edges in edge_coords:
            for from_, to_ in zip(edges, edges[1:]):
                painter = QPainterPath(QPointF(*from_))
                painter.lineTo(QPointF(*to_))
                p = self.scene.addPath(painter)
                self._edge_paths.append(p)

        rect = self.scene.itemsBoundingRect()
        # Enlarge the rect so there is enough room at right and bottom
        rect.setX(rect.x() - self.LEFT_PADDING)
        rect.setY(rect.y() - self.TOP_PADDING)
        rect.setWidth(rect.width() + 2 * self.LEFT_PADDING)
        rect.setHeight(rect.height() + 2 * self.TOP_PADDING)

        self.scene.setSceneRect(rect)
        self.widget.viewport().update()

        self.show_selected()
Example #14
0
 def apply_blade_offset(self, poly, offset):
     """ Apply blade offset to the given polygon by appending a quadratic
     bezier to each point .
     
     """
     # Use a QPainterPath to track the distance in c++
     path = QPainterPath()
     cutoff = cos(radians(self.config.cutoff)) # Forget 
     last = None
     n = len(poly)
     for i, p in enumerate(poly):
         if i == 0:
             path.moveTo(p)
             last_path = QPainterPath()
             last_path.moveTo(p)
             last = p
             continue
         
         # Move to the point
         path.lineTo(p)
         
         if i+1 == n:
             # Done
             break
         
         # Get next point
         next = poly.at(i+1)
         
         # Make our paths
         last_path.lineTo(p)
         next_path = QPainterPath()
         next_path.moveTo(p)
         next_path.lineTo(next)
         
         # Get angle between the two components
         u, v = QVector2D(last-p), QVector2D(next-p)
         cos_theta = QVector2D.dotProduct(u.normalized(), v.normalized())
         
         # If the angle is large enough to need compensation
         if (cos_theta < cutoff and
                 last_path.length() > offset and
                 next_path.length() > offset):
             # Calculate the extended point
             t = last_path.percentAtLength(offset)
             c1 = p+(last_path.pointAtPercent(t)-last)
             c2 = p
             t = next_path.percentAtLength(offset)
             ep = next_path.pointAtPercent(t)
             if offset > 2:
                 # Can smooth it for larger offsets
                 path.cubicTo(c1, c2, ep)
             else:
                 # This works for small offsets < 0.5 mm 
                 path.lineTo(c1)
                 path.lineTo(ep)
         
         # Update last
         last_path = next_path
         last = p
     return path.toSubpathPolygons(IDENITY_MATRIX)
Example #15
0
def join_painter_paths(paths):
    """ Join a list of QPainterPath into a single path """
    result = QPainterPath()
    for p in paths:
        result.addPath(p)
    return result