Exemple #1
0
    def __init__(self, starCount=1, maxStarCount=5):
        self.starCount = starCount
        self.maxStarCount = maxStarCount

        # Create the star shape we'll be drawing.
        self.starPolygon = QPolygonF()
        self.starPolygon.append(QPointF(1.0, 0.5))
        for i in range(1, 5):
            self.starPolygon.append(QPointF(0.5 + 0.5 * cos(0.8 * i * pi),
                                    0.5 + 0.5 * sin(0.8 * i * pi)))

        # Create the diamond shape we'll show in the editor
        self.diamondPolygon = QPolygonF()
        diamondPoints = [QPointF(0.4, 0.5), QPointF(0.5, 0.4),
                         QPointF(0.6, 0.5), QPointF(0.5, 0.6),
                         QPointF(0.4, 0.5)]
        for point in diamondPoints:
            self.diamondPolygon.append(point)
Exemple #2
0
class StarRating(object):
    """ Handle the actual painting of the stars themselves. """

    def __init__(self, starCount=1, maxStarCount=5):
        self.starCount = starCount
        self.maxStarCount = maxStarCount

        # Create the star shape we'll be drawing.
        self.starPolygon = QPolygonF()
        self.starPolygon.append(QPointF(1.0, 0.5))
        for i in range(1, 5):
            self.starPolygon.append(QPointF(0.5 + 0.5 * cos(0.8 * i * pi),
                                    0.5 + 0.5 * sin(0.8 * i * pi)))

        # Create the diamond shape we'll show in the editor
        self.diamondPolygon = QPolygonF()
        diamondPoints = [QPointF(0.4, 0.5), QPointF(0.5, 0.4),
                         QPointF(0.6, 0.5), QPointF(0.5, 0.6),
                         QPointF(0.4, 0.5)]
        for point in diamondPoints:
            self.diamondPolygon.append(point)

    def sizeHint(self):
        """ Tell the caller how big we are. """
        return PAINTING_SCALE_FACTOR * QSize(self.maxStarCount, 1)

    def paint(self, painter, rect, palette, isEditable=False):
        """ Paint the stars (and/or diamonds if we're in editing mode). """
        painter.save()

        painter.setRenderHint(QPainter.Antialiasing, True)
        painter.setPen(Qt.NoPen)

        if isEditable:
            painter.setBrush(palette.highlight())
        else:
            painter.setBrush(palette.windowText())

        yOffset = (rect.height() - PAINTING_SCALE_FACTOR) / 2
        painter.translate(rect.x(), rect.y() + yOffset)
        painter.scale(PAINTING_SCALE_FACTOR, PAINTING_SCALE_FACTOR)

        for i in range(self.maxStarCount):
            if i < self.starCount:
                painter.drawPolygon(self.starPolygon, Qt.WindingFill)
            elif isEditable:
                painter.drawPolygon(self.diamondPolygon, Qt.WindingFill)
            painter.translate(1.0, 0.0)

        painter.restore()
Exemple #3
0
    def SocialNavigationGaussian_getObjectInteraction(self, persons, objects, interaction, d):

        # print("getObjectInteration")
        plt.close('all')

        polylines_object = []
        polylines_interacting = []

        for o in objects:
            obj = Object(o.x, o.z, o.angle, o.space)
            # print("OBJETO")
            ##para dibujarlo
            if d:
                plt.figure('ObjectSpace')
                rect = plt.Rectangle((obj.x - 0.25, obj.y - 0.25), 0.5, 0.5, fill=False)

                plt.gca().add_patch(rect)
                x_aux = obj.x + 0.25 * cos(pi / 2 - obj.th)
                y_aux = obj.y + 0.25 * sin(pi / 2 - obj.th)
                heading = plt.Line2D((obj.x, x_aux), (obj.y, y_aux), lw=1, color='k')
                plt.gca().add_line(heading)

            w = 1.0
            # print (obj.x,obj.y)
            ##para calcular el rectangulo
            s = QRectF(QPointF(0, 0), QSizeF(w, obj.sp))

            # if (d):
            #     plt.plot (s.bottomLeft().x(),s.bottomLeft().y(),"go")
            #     plt.plot(s.bottomRight().x(), s.bottomRight().y(), "ro")
            #     plt.plot(s.topRight().x(), s.topRight().y(), "yo")
            #     plt.plot(s.topLeft().x(), s.topLeft().y(), "bo")

            space = QPolygonF()
            space.append(s.topLeft())
            space.append(s.topRight())
            space.append(QPointF(s.bottomRight().x() + obj.sp / 4, s.bottomRight().y()))
            space.append(QPointF(s.bottomLeft().x() - obj.sp / 4, s.bottomLeft().y()))

            t = QTransform()
            t.translate(-w / 2, 0)
            space = t.map(space)
            t = QTransform()
            t.rotateRadians(-obj.th)
            space = t.map(space)

            t = QTransform()
            t.translate(obj.x, obj.y)
            space = t.map(space)

            # points = []
            # for x in xrange(space.count()-1):
            #     point = space.value(x)
            #     print ("valor", point)
            #     points.append([point.x(),point.y()])
            #     plt.plot(point.x(),point.y(),"go")

            polyline = []

            for x in xrange(space.count()):
                point = space.value(x)
                if (d):
                    plt.plot(point.x(), point.y(), "go")

                p = SNGPoint2D()
                p.x = point.x()
                p.z = point.y()
                polyline.append(p)

            polylines_object.append(polyline)

            for p in persons:
                pn = Person(p.x, p.z, p.angle)
                # print("PERSONA", persons.index(p)+1)
                if d:
                    body = plt.Circle((pn.x, pn.y), radius=0.3, fill=False)
                    plt.gca().add_patch(body)

                    x_aux = pn.x + 0.30 * cos(pi / 2 - pn.th)
                    y_aux = pn.y + 0.30 * sin(pi / 2 - pn.th)
                    heading = plt.Line2D((pn.x, x_aux), (pn.y, y_aux), lw=1, color='k')
                    plt.gca().add_line(heading)
                    plt.axis('equal')

                ##CHECKING THE ORIENTATION
                a = abs(obj.th - abs(pn.th - math.pi))
                if a < math.radians(45):
                    checkangle = True
                else:
                    checkangle = False

                ##CHECKING IF THE PERSON IS INSIDE THE POLYGON
                if space.containsPoint(QPointF(pn.x, pn.y), Qt.OddEvenFill) and checkangle:
                    # print("DENTROOOOO Y MIRANDO")
                    if not polyline in polylines_interacting:
                        polylines_interacting.append(polyline)

        if d:
            for ps in polylines_interacting:
                #  plt.figure()
                for p in ps:
                    plt.plot(p.x, p.z, "ro")
                    plt.axis('equal')
                    plt.xlabel('X')
                    plt.ylabel('Y')
            plt.show()
        plt.show()

        if (interaction):
            return polylines_interacting
        else:
            return polylines_object
Exemple #4
0
 def _pointsToPath(self, points: List[QtCore.QPointF]) -> QPainterPath:
     """Converts list of `QtCore.QPointF` objects to a `QPainterPath`."""
     path = QPainterPath()
     path.addPolygon(QPolygonF(points))
     return path
Exemple #5
0
 def add_Polygon(self, arr, xoffset=0, yoffset=0):
     polygon = QPolygonF()
     for p in arr:
         x,y=p[0]
         polygon.append(QPointF(x+xoffset,y+yoffset))
     self.imgArea.scene.addPolygon(polygon, pen=QPen(Qt.blue, 3))
Exemple #6
0
    def testquadToQuad(self):
        q1 = QPolygonF()
        q1.append(QPointF(10.0, 10.0))
        q1.append(QPointF(20.0, 10.0))
        q1.append(QPointF(10.0, -10.0))
        q1.append(QPointF(20.0, -10.0))

        q2 = QPolygonF()
        q2.append(QPointF(20.0, 20.0))
        q2.append(QPointF(30.0, 20.0))
        q2.append(QPointF(20.0, -20.0))
        q2.append(QPointF(30.0, -20.0))

        t1 = QTransform()
        r1 = QTransform.quadToQuad(q1, q2, t1)
        r2 = QTransform.quadToQuad(q1, q2)

        self.assertTrue(r1)
        self.assertTrue(r2)

        self.assertEqual(t1, r2)
class activeMarker(QGraphicsPolygonItem):

    size = 10
    triangle = QPolygonF()
    triangle.append(QPointF(-size, size))
    triangle.append(QPointF(0, 0))
    triangle.append(QPointF(size, size))

    cross = QPolygonF()
    cross.append(QPointF(-size/2, -size/2))
    cross.append(QPointF(0, 0))
    cross.append(QPointF(size / 2, size / 2))
    cross.append(QPointF(0, 0))
    cross.append(QPointF(-size / 2, size / 2))
    cross.append(QPointF(0, 0))
    cross.append(QPointF(size / 2, -size / 2))
    cross.append(QPointF(0, 0))

    @classmethod
    def fromTriangle(cls, parent=None):
        color = QColor(255, 255, 255)
        item = activeMarker(parent=parent)
        item.setPolygon(cls.triangle)
        item.setPen(QPen(color))
        item.setBrush(QBrush(color))
        # set move range to parent bounding rect
        item.moveRange = item.parentItem().boundingRect().bottomRight()
        return item

    @classmethod
    def fromCross(cls, parent=None):
        color = QColor(0, 0, 0)
        item = activeMarker(parent=parent)
        item.setPolygon(cls.cross)
        item.setPen(QPen(color))
        item.setBrush(QBrush(color))
        # set move range to parent bounding rect
        item.moveRange = item.parentItem().boundingRect().bottomRight()
        return item

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.onMouseMove, self.onMouseRelease = lambda e, x, y: 0, lambda e, x, y: 0
        self.moveRange = QRectF(0.0, 0.0, 0.0, 0.0)

    def setMoveRange(self, rect):
        self.moveRange = rect

    def mousePressEvent(self, e):
        pass

    def mouseMoveEvent(self, e):
        # position relative to parent
        pos = e.scenePos() - self.parentItem().scenePos()
        x, y = pos.x(), pos.y()
        # limit move to moveRange
        xmin, ymin = self.moveRange.left(), self.moveRange.top()
        xmax, ymax = self.moveRange.right(), self.moveRange.bottom()
        x, y = xmin if x < xmin else xmax if x > xmax else x, ymin if y < ymin else ymax if y > ymax else y
        self.setPos(x, y)
        self.onMouseMove(e, x, y)

    def mouseReleaseEvent(self, e):
        # position relative to parent
        pos = e.scenePos() - self.parentItem().scenePos()
        x, y = pos.x(), pos.y()
        # limit move to (0,0) and moveRange
        xmin, ymin = self.moveRange.left(), self.moveRange.top()
        xmax, ymax = self.moveRange.right(), self.moveRange.bottom()
        x, y = xmin if x < xmin else xmax if x > xmax else x, ymin if y < ymin else ymax if y > ymax else y
        self.onMouseRelease(e, x, y)
Exemple #8
0
def polygonf_to_array(polygon: QtGui.QPolygonF) -> np.ndarray:
    """Converts a Qt polygon to a numpy array of shape (n, 2)."""
    buf = (ctypes.c_double * 2 * polygon.length()).from_address(
        shiboken2.getCppPointer(polygon.data())[0]  # type: ignore
    )
    return np.frombuffer(buf, dtype=np.float64).reshape(-1, 2)
Exemple #9
0
    def _create_line_indicator(self, addr, item_map, color=Qt.yellow, show_frontier=False, z=None, z_frontier=None):
        """
        Generate a cursor at a given address.
        """
        pos_x = self._get_pos_from_addr(addr)
        if pos_x is None:
            return

        pen = QPen(color)
        brush = QBrush(color)
        height = self.height

        tri_width = 7
        tri_height = 4

        pos_x = int(pos_x - tri_width / 2)  # Center drawing
        center = pos_x + int(tri_width / 2)
        pos_y = 0
        frontier_width = int(0.15 * max(self.width, self.height))

        if show_frontier:
            # Draw frontier gradients
            r = QRectF(center - frontier_width, pos_y, frontier_width, height)
            bg = QLinearGradient(r.topLeft(), r.topRight())
            color = Qt.red
            top_color = QColor(color)
            top_color.setAlpha(0)
            bg.setColorAt(0, top_color)
            bottom_color = QColor(color)
            bottom_color.setAlpha(180)
            bg.setColorAt(1, bottom_color)

            i = QGraphicsRectItem(r, parent=self)
            i.setPen(Qt.NoPen)
            i.setBrush(bg)
            if z_frontier is not None:
                i.setZValue(z_frontier)
            item_map.append(i)

            r = QRectF(center, pos_y, frontier_width, height)
            bg = QLinearGradient(r.topLeft(), r.topRight())
            color = Qt.blue
            top_color = QColor(color)
            bg.setColorAt(0, top_color)
            bottom_color = QColor(color)
            bottom_color.setAlpha(0)
            bg.setColorAt(1, bottom_color)

            i = QGraphicsRectItem(r, parent=self)
            i.setPen(Qt.NoPen)
            i.setBrush(bg)
            if z_frontier is not None:
                i.setZValue(z_frontier)
            item_map.append(i)

        # Draw line
        i = QGraphicsLineItem(center, 0, center, height, parent=self)
        i.setPen(pen)
        if z is not None:
            i.setZValue(z)
        item_map.append(i)

        # Draw top and bottom triangles
        t = QPolygonF()
        t.append(QPointF(pos_x, pos_y))
        t.append(QPointF(pos_x + tri_width - 1, pos_y))
        t.append(QPointF(center, pos_y + tri_height - 1))
        t.append(QPointF(pos_x, pos_y))

        pos_y += height - 1
        b = QPolygonF()
        b.append(QPointF(pos_x, pos_y))
        b.append(QPointF(center, pos_y - tri_height + 1))
        b.append(QPointF(pos_x + tri_width - 1, pos_y))
        b.append(QPointF(pos_x, pos_y))

        for i in [QGraphicsPolygonItem(t, parent=self),
                  QGraphicsPolygonItem(b, parent=self)]:
            i.setPen(pen)
            i.setBrush(brush)
            if z is not None:
                i.setZValue(z)
            item_map.append(i)
Exemple #10
0
 def testPolygon(self):
     #QGraphicsScene.addPolygon
     points = [QPointF(0, 0), QPointF(100, 100), QPointF(0, 100)]
     item = self.scene.addPolygon(QPolygonF(points))
     self.assertTrue(isinstance(item, QGraphicsPolygonItem))
class AutoScrollDrawer:
    def __init__(self, auto_scroll_row: int, level: Level):
        self.auto_scroll_row = auto_scroll_row
        self.level = level

        self.current_pos = QPointF()
        self.horizontal_speed = 0
        self.vertical_speed = 0

        self.rom = ROM()

        self.pixel_length = 1

        self.acceleration_pen = Qt.NoPen
        self.acceleration_brush = Qt.NoBrush
        self.scroll_pen = Qt.NoPen
        self.scroll_brush = Qt.NoBrush

        self.screen_polygon = QPolygonF()

    def draw(self, painter: QPainter, block_length: int):
        self.pixel_length = block_length / Block.WIDTH

        self.scroll_brush = QBrush(Qt.blue)
        self.scroll_pen = QPen(self.scroll_brush, 2 * self.pixel_length)

        self.acceleration_brush = QBrush(Qt.red)
        self.acceleration_pen = QPen(self.acceleration_brush,
                                     2 * self.pixel_length)

        painter.setPen(self.scroll_pen)
        painter.setBrush(self.scroll_brush)

        auto_scroll_type_index = self.auto_scroll_row >> 4
        auto_scroll_routine_index = self.auto_scroll_row & 0b0001_1111

        if auto_scroll_type_index in [
                SPIKE_CEILING_SCROLL,
                UP_TIL_DOOR_SCROLL,
                WATER_LEVEL_SCROLL,
                UP_RIGHT_DIAG_SCROLL,
        ]:
            # not visualized
            return
        elif auto_scroll_type_index not in [
                HORIZONTAL_SCROLL_0, HORIZONTAL_SCROLL_1
        ]:
            # illegal value, those appear in the vanilla ROM, though; so error out
            return

        first_movement_command_index = (self.rom.int(
            AScroll_HorizontalInitMove + auto_scroll_routine_index) + 1) % 256
        last_movement_command_index = (self.rom.int(
            AScroll_HorizontalInitMove + auto_scroll_routine_index + 1)) % 256

        self.horizontal_speed = 0
        self.vertical_speed = 0

        self.current_pos = self._determine_auto_scroll_start(block_length)

        for movement_command_index in range(first_movement_command_index,
                                            last_movement_command_index + 1):

            movement_command = self.rom.int(AScroll_Movement +
                                            movement_command_index)
            movement_repeat = self.rom.int(AScroll_MovementRepeat +
                                           movement_command_index)

            self._execute_movement_command(painter, movement_command,
                                           movement_repeat)

        stop_marker = QRectF(QPoint(0, 0), QSizeF(10, 10) * self.pixel_length)
        stop_marker.moveCenter(self.current_pos)

        painter.setPen(Qt.NoPen)
        painter.drawRect(stop_marker)

        painter.setPen(self.scroll_pen)
        painter.setBrush(self.scroll_brush)

        painter.setOpacity(0.2)
        painter.drawPolygon(self.screen_polygon)

    def _execute_movement_command(self, painter: QPainter, command: int,
                                  repeat: int):
        h_updates_per_tick = 4  # got those by reading the auto scroll routine
        v_updates_per_tick = 2

        is_acceleration_command = (command >> 4) == 0

        if is_acceleration_command:
            # set speed
            h_acceleration_index = (command & 0b00001100) >> 2
            v_acceleration_index = command & 0b00000011

            assert h_acceleration_index != 3
            assert v_acceleration_index != 3

            h_acceleration = self.rom.int(AScroll_VelAccel +
                                          h_acceleration_index)
            v_acceleration = self.rom.int(AScroll_VelAccel +
                                          v_acceleration_index)

            if h_acceleration == 0xFF:
                h_acceleration = -0x01

            if v_acceleration == 0xFF:
                v_acceleration = -0x01

            h_acceleration <<= 4
            v_acceleration <<= 4

            movement_ticks = repeat
            repeat = 1
        else:
            auto_scroll_loop_selector = command >> 4

            loop_start_offset = AScroll_MovementLoopStart - 2 + auto_scroll_loop_selector

            if auto_scroll_loop_selector in [0, 1]:
                # normal movement command
                movement_ticks = self.rom.int(loop_start_offset)

                h_acceleration = 0
                v_acceleration = 0
            else:
                # loop command
                movement_loop_start_index = self.rom.int(loop_start_offset)
                movement_loop_end_index = self.rom.int(loop_start_offset + 1)

                number_of_commands = movement_loop_end_index - movement_loop_start_index

                movement_loop_commands = self.rom.read(
                    AScroll_MovementLoop + movement_loop_start_index,
                    number_of_commands)
                movement_loop_repeats = self.rom.read(
                    AScroll_MovementLoopTicks + movement_loop_start_index,
                    number_of_commands)

                for _ in range(repeat):
                    for sub_command, sub_repeat in zip(movement_loop_commands,
                                                       movement_loop_repeats):
                        self._execute_movement_command(painter, sub_command,
                                                       sub_repeat)

                return

        if is_acceleration_command and (h_acceleration or v_acceleration):
            painter.setPen(self.acceleration_pen)
            painter.setBrush(self.acceleration_brush)
        else:
            painter.setPen(self.scroll_pen)
            painter.setBrush(self.scroll_brush)

        # circle at start of new command
        painter.drawEllipse(self.current_pos, 4 * self.pixel_length,
                            4 * self.pixel_length)

        self._add_points_for_position(self.current_pos)

        if is_acceleration_command and (h_acceleration or v_acceleration):
            for _ in range(movement_ticks):
                self.horizontal_speed += h_acceleration
                self.vertical_speed += v_acceleration

                old_pos = self.current_pos

                self.current_pos += (
                    QPointF(h_updates_per_tick * self.horizontal_speed / 256,
                            v_updates_per_tick * self.vertical_speed / 256) *
                    self.pixel_length)

                painter.drawLine(old_pos, self.current_pos)
                self._add_points_for_position(self.current_pos)
        else:
            old_pos = QPointF(self.current_pos)

            h_movement = h_updates_per_tick * self.horizontal_speed / 256 * movement_ticks * repeat
            v_movement = v_updates_per_tick * self.vertical_speed / 256 * movement_ticks * repeat

            self.current_pos += QPointF(h_movement,
                                        v_movement) * self.pixel_length

            painter.drawLine(old_pos, self.current_pos)

            self._add_points_for_line(old_pos, self.current_pos)

    def _add_points_for_position(self, pos: QPointF):
        self.screen_polygon = self.screen_polygon.united(
            QPolygonF.fromList(self._rect_for_point(pos)))

    def _add_points_for_line(self, start: QPointF, stop: QPointF):
        start_points = self._rect_for_point(start)
        stop_points = self._rect_for_point(stop)

        point_list = []

        if start.y() == stop.y():
            point_list.extend([
                start_points[0], stop_points[1], stop_points[2],
                start_points[3]
            ])
        elif start.y() < stop.y():
            point_list.extend(start_points[0:2])
            point_list.extend(stop_points[1:4])
            point_list.append(start_points[3])
        else:
            point_list.append(start_points[0])
            point_list.extend(stop_points[0:3])
            point_list.extend(start_points[2:4])

        self.screen_polygon = self.screen_polygon.united(
            QPolygonF.fromList(point_list))

    def _rect_for_point(self, pos: QPointF):
        top_right = pos + QPointF(SCREEN_WIDTH // 2, -_ASCROLL_SCREEN_HEIGHT //
                                  2) * self.pixel_length * Block.WIDTH
        bottom_right = pos + QPoint(SCREEN_WIDTH // 2, _ASCROLL_SCREEN_HEIGHT
                                    // 2) * self.pixel_length * Block.WIDTH

        top_left = top_right - QPointF(SCREEN_WIDTH,
                                       0) * self.pixel_length * Block.WIDTH
        bottom_left = bottom_right - QPointF(
            SCREEN_WIDTH, 0) * self.pixel_length * Block.WIDTH

        return top_left, top_right, bottom_right, bottom_left

    def _determine_auto_scroll_start(self, block_length: int) -> QPointF:
        # only support horizontal levels for now
        _, mario_y = self.level.header.mario_position()

        scroll_x, scroll_y = SCREEN_WIDTH // 2, min(
            mario_y + 2, GROUND - _ASCROLL_SCREEN_HEIGHT // 2)

        return QPointF(scroll_x, scroll_y) * block_length
 def _add_points_for_position(self, pos: QPointF):
     self.screen_polygon = self.screen_polygon.united(
         QPolygonF.fromList(self._rect_for_point(pos)))
Exemple #13
0
            if new_corridor_location not in dict_corridors_per_side['top']:
                dict_corridors_per_side['top'].append(new_corridor_location)

    else:

        print('Not modifying last corridor')

# --------------------------------------------------------------------------------------------------------
# -------------------- Cambiamos la dimensión de la habitación de forma aleatoria ----------------------
# ----------------------------------------y añadimos puertas -------------------------------------------
# --------------------------------------------------------------------------------------------------------

print('posicion pasillo parte superior', dict_corridors_per_side['top'])
print('posicion pasillo parte inferior', dict_corridors_per_side['bottom'])

union_polygon = QPolygonF()
result_polygon_list = []

for side, rooms_list in dict_rooms_per_side.items():

    for i, room in enumerate(rooms_list):

        # #Cambio el ancho de la habitación de forma aleatoria (para no quedarme sin pasillo como maximo la muevo un tercio de este)
        # random_sign = [1,-1]
        # random_mov = list(np.arange(0, corridor_height/3, 0.05))
        # room.setTopLeft(QPointF(room.topLeft().x(),room.topLeft().y() + random.choice(random_sign)*random.choice(random_mov)))

        # Selecciono dónde va a estar la puerta
        possibles_door_locations = ['center']
        if i in dict_corridors_per_side[side]:  # Pasillo a la izquierda
            possibles_door_locations.append('left')
class activeMarker(QGraphicsPolygonItem):
    """
    Movable marker
    """

    size = 10
    triangle = QPolygonF()
    triangle.append(QPointF(-size, size))
    triangle.append(QPointF(0, 0))
    triangle.append(QPointF(size, size))

    cross = QPolygonF()
    cross.append(QPointF(-size / 2, -size / 2))
    cross.append(QPointF(0, 0))
    cross.append(QPointF(size / 2, size / 2))
    cross.append(QPointF(0, 0))
    cross.append(QPointF(-size / 2, size / 2))
    cross.append(QPointF(0, 0))
    cross.append(QPointF(size / 2, -size / 2))
    cross.append(QPointF(0, 0))

    @classmethod
    def fromTriangle(cls, *args, **kwargs):
        color = QColor(255, 255, 255)
        item = cls(*args, **kwargs)
        item.setPolygon(cls.triangle)
        item.setPen(QPen(color))
        item.setBrush(QBrush(color))
        # set move range to parent bounding rect
        item.moveRange = item.parentItem().boundingRect()
        return item

    @classmethod
    def fromCross(cls, *args, **kwargs):
        color = QColor(0, 0, 0)
        item = cls(*args, **kwargs)
        item.setPolygon(cls.cross)
        item.setPen(QPen(color))
        item.setBrush(QBrush(color))
        # set move range to parent bounding rect
        item.moveRange = item.parentItem().boundingRect()
        return item

    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.onMouseMove, self.onMouseRelease = lambda e, x, y: 0, lambda e, x, y: 0
        self.moveRange = QRectF(0.0, 0.0, 0.0, 0.0)

    @property  # read only
    def currentColor(self):
        return self.scene().slider2D.QImg.pixelColor(
            (self.pos() - self.parentItem().offset()).toPoint())

    def setMoveRange(self, rect):
        self.moveRange = rect

    def mousePressEvent(self, e):
        pass

    def mouseMoveEvent(self, e):
        # event position relative to parent
        pos = e.pos() + self.pos(
        )  #  e.scenePos() - self.parentItem().scenePos()  # TODO modified 16/02/20 validate
        x, y = pos.x(), pos.y()
        # limit move to moveRange
        xmin, ymin = self.moveRange.left(), self.moveRange.top()
        xmax, ymax = self.moveRange.right(), self.moveRange.bottom()
        x, y = xmin if x < xmin else xmax if x > xmax else x, ymin if y < ymin else ymax if y > ymax else y
        self.setPos(x, y)
        self.onMouseMove(e, x, y)

    def mouseReleaseEvent(self, e):
        # event position relative to parent
        pos = e.pos() + self.pos(
        )  #  e.scenePos() - self.parentItem().scenePos()
        x, y = pos.x(), pos.y()
        # limit move to (0,0) and moveRange
        xmin, ymin = self.moveRange.left(), self.moveRange.top()
        xmax, ymax = self.moveRange.right(), self.moveRange.bottom()
        x, y = xmin if x < xmin else xmax if x > xmax else x, ymin if y < ymin else ymax if y > ymax else y
        self.onMouseRelease(e, x, y)
def _test_pipedimagerpq():
    # vertices of a pentagon (roughly) centered in a 1000 x 1000 square
    pentagonpts = (
        (504.5, 100.0),
        (100.0, 393.9),
        (254.5, 869.4),
        (754.5, 869.4),
        (909.0, 393.9),
    )
    linepts = ((350, 50), (200, 150), (400, 250), (300, 350), (150, 250),
               (100, 450))
    # start PyQt
    testapp = QApplication(["PipedImagerPQ"])
    # create the list of commands to submit
    drawcmnds = []
    drawcmnds.append({"action": "setTitle", "title": "Tester"})
    drawcmnds.append({"action": "show"})
    drawcmnds.append({"action": "clear", "color": "black"})
    drawcmnds.append({"action": "screenInfo"})
    # create the image to be displayed
    testimage = QImage(500, 500, QImage.Format_ARGB32_Premultiplied)
    # initialize a black background
    testimage.fill(0xFF000000)
    # draw some things in the image
    testpainter = QPainter(testimage)
    testpainter.setBrush(QBrush(QColor(0, 255, 0, 128), Qt.SolidPattern))
    testpainter.setPen(
        QPen(QBrush(QColor(255, 0, 0, 255), Qt.SolidPattern), 5.0,
             Qt.SolidLine, Qt.SquareCap, Qt.MiterJoin))
    testpainter.drawRect(QRectF(5.0, 255.0, 240.0, 240.0))
    testpainter.setBrush(QBrush(QColor(0, 0, 255, 255), Qt.SolidPattern))
    testpainter.setPen(
        QPen(QBrush(QColor(0, 0, 0, 255), Qt.SolidPattern), 5.0, Qt.DashLine,
             Qt.RoundCap, Qt.RoundJoin))
    testpainter.drawPolygon(
        QPolygonF([
            QPointF(.25 * ptx, .25 * pty + 250) for (ptx, pty) in pentagonpts
        ]))
    testpainter.setBrush(Qt.NoBrush)
    testpainter.setPen(
        QPen(QBrush(QColor(255, 255, 255, 255), Qt.SolidPattern), 3.0,
             Qt.DashLine, Qt.RoundCap, Qt.RoundJoin))
    testpainter.drawPolyline(
        QPolygonF([QPointF(pts, pty) for (pts, pty) in linepts]))
    testpainter.end()
    # add the image command
    testimgwidth = testimage.width()
    testimgheight = testimage.height()
    testimgstride = testimage.bytesPerLine()
    # not a good way to get the pixel data
    testimgdata = bytearray(testimgheight * testimgstride)
    k = 0
    for pty in range(testimgheight):
        for ptx in range(testimgwidth):
            pixval = testimage.pixel(ptx, pty)
            (aval, rgbval) = divmod(pixval, 256 * 256 * 256)
            (rval, gbval) = divmod(rgbval, 256 * 256)
            (gval, bval) = divmod(gbval, 256)
            testimgdata[k] = bval
            k += 1
            testimgdata[k] = gval
            k += 1
            testimgdata[k] = rval
            k += 1
            testimgdata[k] = aval
            k += 1
    testblocksize = 4000
    testnumblocks = (testimgheight * testimgstride + testblocksize -
                     1) // testblocksize
    drawcmnds.append({
        "action": "newImage",
        "width": testimgwidth,
        "height": testimgheight,
        "stride": testimgstride
    })
    for k in range(testnumblocks):
        if k < (testnumblocks - 1):
            blkdata = testimgdata[k * testblocksize:(k + 1) * testblocksize]
        else:
            blkdata = testimgdata[k * testblocksize:]
        drawcmnds.append({
            "action": "newImage",
            "blocknum": k + 1,
            "numblocks": testnumblocks,
            "startindex": k * testblocksize,
            "blockdata": blkdata
        })
    # finish the command list
    drawcmnds.append({"action": "show"})
    drawcmnds.append({"action": "exit"})
    # create a PipedImagerPQ in this process
    (cmndrecvpipe, cmndsendpipe) = multiprocessing.Pipe(False)
    (rspdrecvpipe, rspdsendpipe) = multiprocessing.Pipe(False)
    testviewer = PipedImagerPQ(cmndrecvpipe, rspdsendpipe)
    # create a command submitter dialog
    tester = _CommandSubmitterPQ(testviewer, cmndsendpipe, rspdrecvpipe,
                                 drawcmnds)
    tester.show()
    # let it all run
    testresult = testapp.exec_()
    if testresult != 0:
        sys.exit(testresult)
Exemple #16
0
 def __init__(self, *args, **kwargs):
     super(PolyLineItem, self).__init__()
     self.points = [get_point(p) for p in args]
     self.closed = kwargs.pop('closed')
     self._polygon = QPolygonF(QPolygonF.fromList(self.points))
Exemple #17
0
    def addBackground(self):
        scene = self.scene()

        if not DisplayOptions.map_poly:
            bg = QPixmap("./resources/" + self.game.theater.overview_image)
            scene.addPixmap(bg)

            # Apply graphical effects to simulate current daytime
            if self.game.current_turn_time_of_day == TimeOfDay.Day:
                pass
            elif self.game.current_turn_time_of_day == TimeOfDay.Night:
                ov = QPixmap(bg.width(), bg.height())
                ov.fill(CONST.COLORS["night_overlay"])
                overlay = scene.addPixmap(ov)
                effect = QGraphicsOpacityEffect()
                effect.setOpacity(0.7)
                overlay.setGraphicsEffect(effect)
            else:
                ov = QPixmap(bg.width(), bg.height())
                ov.fill(CONST.COLORS["dawn_dust_overlay"])
                overlay = scene.addPixmap(ov)
                effect = QGraphicsOpacityEffect()
                effect.setOpacity(0.3)
                overlay.setGraphicsEffect(effect)

        if DisplayOptions.map_poly or self.reference_point_setup_mode:
            # Polygon display mode
            if self.game.theater.landmap is not None:

                for sea_zone in self.game.theater.landmap.sea_zones:
                    print(sea_zone)
                    poly = QPolygonF(
                        [
                            QPointF(*self._transform_point(Point(point[0], point[1])))
                            for point in sea_zone.exterior.coords
                        ]
                    )
                    if self.reference_point_setup_mode:
                        color = "sea_blue_transparent"
                    else:
                        color = "sea_blue"
                    scene.addPolygon(poly, CONST.COLORS[color], CONST.COLORS[color])

                for inclusion_zone in self.game.theater.landmap.inclusion_zones:
                    poly = QPolygonF(
                        [
                            QPointF(*self._transform_point(Point(point[0], point[1])))
                            for point in inclusion_zone.exterior.coords
                        ]
                    )
                    if self.reference_point_setup_mode:
                        scene.addPolygon(
                            poly,
                            CONST.COLORS["grey_transparent"],
                            CONST.COLORS["dark_grey_transparent"],
                        )
                    else:
                        scene.addPolygon(
                            poly, CONST.COLORS["grey"], CONST.COLORS["dark_grey"]
                        )

                for exclusion_zone in self.game.theater.landmap.exclusion_zones:
                    poly = QPolygonF(
                        [
                            QPointF(*self._transform_point(Point(point[0], point[1])))
                            for point in exclusion_zone.exterior.coords
                        ]
                    )
                    if self.reference_point_setup_mode:
                        scene.addPolygon(
                            poly,
                            CONST.COLORS["grey_transparent"],
                            CONST.COLORS["dark_dark_grey_transparent"],
                        )
                    else:
                        scene.addPolygon(
                            poly, CONST.COLORS["grey"], CONST.COLORS["dark_dark_grey"]
                        )

        # Uncomment to display plan projection test
        # self.projection_test()
        self.draw_scale()

        if self.reference_point_setup_mode:
            for i, point in enumerate(self.game.theater.reference_points):
                self.scene().addRect(
                    QRectF(
                        point.image_coordinates.x, point.image_coordinates.y, 25, 25
                    ),
                    pen=CONST.COLORS["red"],
                    brush=CONST.COLORS["red"],
                )
                text = self.scene().addText(
                    f"P{i} = {point.image_coordinates}",
                    font=QFont("Trebuchet MS", 14, weight=8, italic=False),
                )
                text.setDefaultTextColor(CONST.COLORS["red"])
                text.setPos(point.image_coordinates.x + 26, point.image_coordinates.y)

                # Set to True to visually debug _transform_point.
                draw_transformed = False
                if draw_transformed:
                    x, y = self._transform_point(point.world_coordinates)
                    self.scene().addRect(
                        QRectF(x, y, 25, 25),
                        pen=CONST.COLORS["red"],
                        brush=CONST.COLORS["red"],
                    )
                    text = self.scene().addText(
                        f"P{i}' = {x}, {y}",
                        font=QFont("Trebuchet MS", 14, weight=8, italic=False),
                    )
                    text.setDefaultTextColor(CONST.COLORS["red"])
                    text.setPos(x + 26, y)
Exemple #18
0
    def drawOneStep(self, step):
        """
        :type step: tuple
        """
        if step[0] == ACTION_RECT:
            self.graphics_scene.addRect(
                QRectF(QPointF(step[1], step[2]), QPointF(step[3], step[4])),
                step[5])
        elif step[0] == ACTION_ELLIPSE:
            self.graphics_scene.addEllipse(
                QRectF(QPointF(step[1], step[2]), QPointF(step[3], step[4])),
                step[5])
        elif step[0] == ACTION_ARROW:
            arrow = QPolygonF()

            linex = float(step[1] - step[3])
            liney = float(step[2] - step[4])
            line = sqrt(pow(linex, 2) + pow(liney, 2))

            # in case to divided by 0
            if line == 0:
                return

            sinAngel = liney / line
            cosAngel = linex / line

            # sideLength is the length of bottom side of the body of an arrow
            # arrowSize is the size of the head of an arrow, left and right
            # sides' size is arrowSize, and the bottom side's size is arrowSize / 2
            sideLength = step[5].width()
            arrowSize = 8
            bottomSize = arrowSize / 2

            tmpPoint = QPointF(step[3] + arrowSize * sideLength * cosAngel,
                               step[4] + arrowSize * sideLength * sinAngel)

            point1 = QPointF(step[1] + sideLength * sinAngel,
                             step[2] - sideLength * cosAngel)
            point2 = QPointF(step[1] - sideLength * sinAngel,
                             step[2] + sideLength * cosAngel)
            point3 = QPointF(tmpPoint.x() - sideLength * sinAngel,
                             tmpPoint.y() + sideLength * cosAngel)
            point4 = QPointF(tmpPoint.x() - bottomSize * sideLength * sinAngel,
                             tmpPoint.y() + bottomSize * sideLength * cosAngel)
            point5 = QPointF(step[3], step[4])
            point6 = QPointF(tmpPoint.x() + bottomSize * sideLength * sinAngel,
                             tmpPoint.y() - bottomSize * sideLength * cosAngel)
            point7 = QPointF(tmpPoint.x() + sideLength * sinAngel,
                             tmpPoint.y() - sideLength * cosAngel)

            arrow.append(point1)
            arrow.append(point2)
            arrow.append(point3)
            arrow.append(point4)
            arrow.append(point5)
            arrow.append(point6)
            arrow.append(point7)
            arrow.append(point1)

            self.graphics_scene.addPolygon(arrow, step[5], step[6])
        elif step[0] == ACTION_LINE:
            self.graphics_scene.addLine(
                QLineF(QPointF(step[1], step[2]), QPointF(step[3], step[4])),
                step[5])
        elif step[0] == ACTION_FREEPEN:
            self.graphics_scene.addPath(step[1], step[2])
        elif step[0] == ACTION_TEXT:
            textAdd = self.graphics_scene.addSimpleText(step[1], step[2])
            textAdd.setPos(step[3])
            textAdd.setBrush(QBrush(step[4]))
            self.textRect = textAdd.boundingRect()