class PolygonCurve(OWCurve): """ A plot item that shows a filled or empty polygon. :param pen: The pen used to draw the polygon's outline :type pen: :obj:`.QPen` :param brush: The brush used to paint the polygon's inside :type brush: :obj:`.QBrush` :param xData: The list of x coordinates :type xData: list of float :param yData: The list of y coordinates :type yData: list of float :param tooltip: The tool tip shown when hovering over this curve :type tooltip: str """ def __init__(self, pen=QPen(Qt.black), brush=QBrush(Qt.white), xData=[], yData=[], tooltip=None): OWCurve.__init__(self, xData, yData, tooltip=tooltip) self._data_polygon = self.polygon_from_data(xData, yData) self._polygon_item = QGraphicsPolygonItem(self) self.set_pen(pen) self.set_brush(brush) def update_properties(self): self._polygon_item.setPolygon(self.graph_transform().map( self._data_polygon)) self._polygon_item.setPen(self.pen()) self._polygon_item.setBrush(self.brush()) @staticmethod def polygon_from_data(xData, yData): """ Creates a polygon from a list of x and y coordinates. :returns: A polygon with point corresponding to ``xData`` and ``yData``. :rtype: QPolygonF """ if xData and yData: n = min(len(xData), len(yData)) p = QPolygonF(n + 1) for i in range(n): p[i] = QPointF(xData[i], yData[i]) p[n] = QPointF(xData[0], yData[0]) return p else: return QPolygonF() def set_data(self, xData, yData): self._data_polygon = self.polygon_from_data(xData, yData) OWCurve.set_data(self, xData, yData)
class PolygonCurve(OWCurve): """ A plot item that shows a filled or empty polygon. :param pen: The pen used to draw the polygon's outline :type pen: :obj:`.QPen` :param brush: The brush used to paint the polygon's inside :type brush: :obj:`.QBrush` :param xData: The list of x coordinates :type xData: list of float :param yData: The list of y coordinates :type yData: list of float :param tooltip: The tool tip shown when hovering over this curve :type tooltip: str """ def __init__(self, pen=QPen(Qt.black), brush=QBrush(Qt.white), xData=[], yData=[], tooltip=None): OWCurve.__init__(self, xData, yData, tooltip=tooltip) self._data_polygon = self.polygon_from_data(xData, yData) self._polygon_item = QGraphicsPolygonItem(self) self.set_pen(pen) self.set_brush(brush) def update_properties(self): self._polygon_item.setPolygon(self.graph_transform().map(self._data_polygon)) self._polygon_item.setPen(self.pen()) self._polygon_item.setBrush(self.brush()) @staticmethod def polygon_from_data(xData, yData): """ Creates a polygon from a list of x and y coordinates. :returns: A polygon with point corresponding to ``xData`` and ``yData``. :rtype: QPolygonF """ if xData and yData: n = min(len(xData), len(yData)) p = QPolygonF(n + 1) for i in range(n): p[i] = QPointF(xData[i], yData[i]) p[n] = QPointF(xData[0], yData[0]) return p else: return QPolygonF() def set_data(self, xData, yData): self._data_polygon = self.polygon_from_data(xData, yData) OWCurve.set_data(self, xData, yData)
class ParallelCoordinatePolygon(OWPlotItem): def __init__(self, i, mu1, mu2, sigma1, sigma2, phi, color): OWPlotItem.__init__(self) self.outer_box = QGraphicsPolygonItem(self) self.inner_box = QGraphicsPolygonItem(self) self.i = i self.mu1 = mu1 self.mu2 = mu2 self.sigma1 = sigma1 self.sigma2 = sigma2 self.phi = phi self.twosigmapolygon = QPolygonF([ QPointF(i, mu1 - sigma1), QPointF(i, mu1 + sigma1), QPointF(i + 1, mu2 + sigma2), QPointF(i + 1, mu2 - sigma2), QPointF(i, mu1 - sigma1) ]) self.sigmapolygon = QPolygonF([ QPointF(i, mu1 - .5 * sigma1), QPointF(i, mu1 + .5 * sigma1), QPointF(i + 1, mu2 + .5 * sigma2), QPointF(i + 1, mu2 - .5 * sigma2), QPointF(i, mu1 - .5 * sigma1) ]) if isinstance(color, tuple): color = QColor(*color) color.setAlphaF(.3) self.outer_box.setBrush(color) self.outer_box.setPen(QColor(0, 0, 0, 0)) self.inner_box.setBrush(color) self.inner_box.setPen(color) def update_properties(self): self.outer_box.setPolygon(self.graph_transform().map( self.twosigmapolygon)) self.inner_box.setPolygon(self.graph_transform().map( self.sigmapolygon))
class ParallelCoordinatePolygon(OWPlotItem): def __init__(self, i, mu1, mu2, sigma1, sigma2, phi, color): OWPlotItem.__init__(self) self.outer_box = QGraphicsPolygonItem(self) self.inner_box = QGraphicsPolygonItem(self) self.i = i self.mu1 = mu1 self.mu2 = mu2 self.sigma1 = sigma1 self.sigma2 = sigma2 self.phi = phi self.twosigmapolygon = QPolygonF([ QPointF(i, mu1 - sigma1), QPointF(i, mu1 + sigma1), QPointF(i + 1, mu2 + sigma2), QPointF(i + 1, mu2 - sigma2), QPointF(i, mu1 - sigma1) ]) self.sigmapolygon = QPolygonF([ QPointF(i, mu1 - .5 * sigma1), QPointF(i, mu1 + .5 * sigma1), QPointF(i + 1, mu2 + .5 * sigma2), QPointF(i + 1, mu2 - .5 * sigma2), QPointF(i, mu1 - .5 * sigma1) ]) if isinstance(color, tuple): color = QColor(*color) color.setAlphaF(.3) self.outer_box.setBrush(color) self.outer_box.setPen(QColor(0, 0, 0, 0)) self.inner_box.setBrush(color) self.inner_box.setPen(color) def update_properties(self): self.outer_box.setPolygon(self.graph_transform().map(self.twosigmapolygon)) self.inner_box.setPolygon(self.graph_transform().map(self.sigmapolygon))
def polygon_name_face(node, *args, **kwargs): """create a wedge shaped face in the style of ARB Args: width (int): size in pixels for the width of the wedge height (int): size in pixels for the height of the wedge width_percent (float): change the angle of the point of the wedge. This must be a number between 0 and 1 Returns: QGraphicsRectItem: The Qt graphics item of the polygon """ n_leaves = len(node.get_leaves()) closest_leaf_dist = node.get_closest_leaf()[1] farthest_leaf_dist = node.get_farthest_leaf()[1] base_height = 30 width = 60 height = math.log(n_leaves, 2) + base_height width_percent = closest_leaf_dist / farthest_leaf_dist #print(width, height, width_percent) points = [ (0.0, 0.0), # top left point (width, 0.0), # top right point (width * width_percent, height), # bottom right point (0.0, height), # bottom left point (0.0, 0.0) # back to the beginning ] shape = QPolygonF() for i in points: shape << QtCore.QPointF(*i) ## Creates a main master Item that will contain all other elements ## Items can be standard QGraphicsItem masterItem = QGraphicsRectItem(0, 0, width, height) # Keep a link within the item to access node info masterItem.node = node # I dont want a border around the masterItem masterItem.setPen(QPen(QtCore.Qt.NoPen)) polygon = QGraphicsPolygonItem(shape, masterItem) # Make the wedge grey in color polygon.setBrush(QBrush(QColor( '#D3D3D3'))) # Print the name of the node # Center text according to masterItem size center = masterItem.boundingRect().center() text = QGraphicsSimpleTextItem(node.name) text.setParentItem(polygon) tw = text.boundingRect().width() th = text.boundingRect().height() text.setPos(center.x() + tw/2, center.y() - th/2) # this is a hack to prevent the name being printed twice # we set the node name to blank after we write it with the QGraphicsSimpleTextItem # it must be set to a blank string for it not to be printed later node.name = '' # print the number of collapsed leaves in the polygon leaves_count_text = QGraphicsSimpleTextItem('('+str(n_leaves)+')') leaves_count_text.setParentItem(polygon) leaves_count_text.setFont(QFont('Veranda', 6)) leaves_count_text.setPos(masterItem.boundingRect().x() + 5, center.y() - leaves_count_text.boundingRect().height()/2) polygon.setPos(0, masterItem.boundingRect().y()/1.5) return masterItem
class auto(QGraphicsPixmapItem): def __init__(self, *args): self.seleccionado = False self.velocity = random.randint(1, 10) QGraphicsPixmapItem.__init__(self, *args) self.setPixmap( QPixmap("sprites/" + str(random.randint(1, 45)) + ".png")) self.setTransformOriginPoint(self.boundingRect().width() / 2.0, self.boundingRect().height() / 2.0) self.setZValue(10) ##menu contextual self.menu = QMenu() self.Actions = [] #arreglo de acciones self.Actions.append(self.menu.addAction("Seguir")) self.Actions.append(self.menu.addAction("Editar")) self.Actions.append(self.menu.addAction("girar clockwise")) self.Actions.append(self.menu.addAction("girar anti-clockwise")) self.Actions.append(self.menu.addAction("Colisiones")) self.Actions.append(self.menu.addAction("Duplicar")) self.Actions.append(self.menu.addAction("Eliminar")) self.menu.triggered[QAction].connect(self.test) ##offset para el arrastre self.offset = QPointF(0, 0) ##poligono de vision poligono = QPolygonF() poligono.append(QPointF(-1, 10)) poligono.append(QPointF(-1, 20)) poligono.append(QPointF(-30, 40)) poligono.append(QPointF(-40, 15)) poligono.append(QPointF(-30, -10)) self.vision = QGraphicsPolygonItem(poligono, self, self.scene()) self.vision.setBrush(QColor(255, 255, 0, 100)) self.vision.setPen(QColor(255, 255, 0)) def info(self): return "Velocidad " + str(self.velocity) + " posicion " + str( self.pos())[20:] + "\n" def test(self, act): print act.text() if act.text() == "girar clockwise": self.setRotation(self.rotation() - 45) if act.text() == "girar anti-clockwise": self.setRotation(self.rotation() + 45) if act.text() == "Colisiones": print "colisiones con", self.collidingItems( 1), self.vision.collidingItems(1) if act.text() == "Duplicar": self.scene().addItem(auto()) if act.text() == "Eliminar": self.scene().removeItem(self) def contextMenuEvent(self, event): self.menu.popup(event.screenPos()) def mousePressEvent(self, event): p = event.pos() self.offset = QPointF(p.x() * 1.0, p.y() * 1.0) self.seleccionado = not self.seleccionado def mouseMoveEvent(self, event): self.setPos(event.scenePos() - self.offset) def avanza(self): if self.velocity != 0: """print velocity print "current pos (%f,%f)"%(self.pos().x(),self.pos().y()) print "angle %f "%(self.rotation())""" radians = self.rotation() * 0.0174532925 """ print "angle rad %f "%(radians)""" nx = 1.0 * self.velocity * cos(radians) ny = 1.0 * self.velocity * sin(radians) """ print "avanzara a (%f,%f)"%(nx,ny) """ self.setPos(self.pos().x() - nx, self.pos().y() - ny) """for i in self.collidingItems():
def __init__(self, world): QGraphicsPolygonItem.__init__(self) ############################# ### Build graph ############################# graph = pydot.Dot() graph.set_node_defaults(color = 'red', fontcolor = 'red', label = '\<orphan\>') graph.set('overlap', 'prism') # build adjacency graph from world for area in world.areas: # create node for each room node = pydot.Node(area.id) node.set( 'label', area.name ) if area == world.player.currentArea: node.set( 'color', 'blue' ) node.set( 'fontcolor', 'blue' ) else: node.set( 'color', 'black' ) node.set( 'fontcolor', 'black' ) graph.add_node(node) # link to adjacent rooms for feature in area.features: for action in feature.actions: finalEvent = None for event in action.events: if type(event) == events.PlayerMoveEvent: finalEvent = pydot.Edge( src=area.id, dst=event.properties['destination'] ) if finalEvent is not None: graph.add_edge( finalEvent ) ################################ ### Generate SVG from graph ################################ ps = graph.create_svg(prog='neato') ######################################### ### Build graphics items from SVG ######################################### # build xml tree ns = {'svg': 'http://www.w3.org/2000/svg'} doc = ET.fromstring(ps) # grab the root node properties rootNode = doc.xpath('/svg:svg/svg:g[1]', namespaces=ns)[0] polygon = rootNode.xpath('./svg:polygon', namespaces=ns)[0] pointStr = polygon.xpath('./@points', namespaces=ns)[0] penColor = QString(polygon.xpath('./@stroke', namespaces=ns)[0]) fillColor = QString(polygon.xpath('./@fill', namespaces=ns)[0]) # parse root polygon path path = QPolygonF() for pair in pointStr.split(' '): dims = pair.split(',') point = QPointF( float(dims[0]), float(dims[1]) ) path.append(point) self.setPolygon(path) # fill in root node colors if QColor.isValidColor(penColor): self.setPen( QColor(penColor) ) if QColor.isValidColor(fillColor): self.setBrush( QColor(fillColor) ) # build each graph node for xmlNode in rootNode.xpath('./svg:g', namespaces=ns): group = QGraphicsRectItem(self) group.setPen( Qt.transparent ) group.setBrush( Qt.transparent ) if xmlNode.attrib['class'] == 'node': # find the area object name = xmlNode.xpath('./svg:title', namespaces=ns)[0].text group.setData( 0, QString(world.areas[world.areaLookup[name]].id) ) # get the ellipse info ellipseNode = xmlNode.xpath('./svg:ellipse', namespaces=ns)[0] elProps = { k: float(ellipseNode.attrib[k]) for k in ['cx', 'cy', 'rx', 'ry']} rect = QRectF( elProps['cx']-elProps['rx'], elProps['cy']-elProps['ry'], 2*elProps['rx'], 2*elProps['ry']) penColor = QString(ellipseNode.attrib['stroke']) ellipseItem = QGraphicsEllipseItem(rect, group) if QColor.isValidColor(penColor): ellipseItem.setPen( QColor(penColor) ) # get the text info textNode = xmlNode.xpath('./svg:text', namespaces=ns)[0] text = textNode.text textItem = QGraphicsTextItem(text, group) penColor = textNode.attrib.get('fill', 'black') nodePoint = QPointF(float(textNode.attrib['x']), float(textNode.attrib['y'])) textItem.setPos( nodePoint - textItem.boundingRect().center() + QPointF(0.0,-4.0)) if QColor.isValidColor(penColor): textItem.setDefaultTextColor( QColor(penColor) ) group.setRect( ellipseItem.boundingRect() ) group.setFlags( QGraphicsRectItem.ItemIsSelectable ) elif xmlNode.attrib['class'] == 'edge': # parse the line portion of the arrow line = xmlNode.xpath('./svg:path', namespaces=ns)[0] path = QPainterPath() # pull info from xml file linePath = line.attrib['d'] lineColor = line.attrib['stroke'] # parse path coords points = re.findall( '(-?\d+\.\d+),(-?\d+\.\d+)', linePath ) if len(points) != 4: continue startPoint = QPointF( float(points[0][0]), float(points[0][1]) ) path.moveTo(startPoint) curvePoints = [] for pointCoord in points[1:]: curvePoints.append( QPointF(float(pointCoord[0]), float(pointCoord[1])) ) path.cubicTo( curvePoints[0], curvePoints[1], curvePoints[2] ) # construct path item pathItem = QGraphicsPathItem(path, group) if QColor.isValidColor(lineColor): pathItem.setPen( QColor(lineColor) ) polyNode = xmlNode.xpath('./svg:polygon', namespaces=ns)[0] # pull info from xml file pointStr = polyNode.xpath('./@points', namespaces=ns)[0] penColor = QString(polyNode.xpath('./@stroke', namespaces=ns)[0]) fillColor = QString(polyNode.xpath('./@fill', namespaces=ns)[0]) # parse polygon path path = QPolygonF() for pair in pointStr.split(' '): dims = pair.split(',') point = QPointF( float(dims[0]), float(dims[1]) ) path.append(point) # construct polygon item polygonItem = QGraphicsPolygonItem(path, group) if QColor.isValidColor(penColor): polygonItem.setPen( QColor(penColor) ) if QColor.isValidColor(fillColor): polygonItem.setBrush( QColor(fillColor) ) group.setRect( pathItem.boundingRect() and polygonItem.boundingRect() )
class auto(QGraphicsPixmapItem): def __init__(self, *args): self.seleccionado = False self.velocity = random.randint(1,10) QGraphicsPixmapItem.__init__(self, *args) self.setPixmap(QPixmap("sprites/"+str(random.randint(1,45))+".png")) self.setTransformOriginPoint(self.boundingRect().width()/2.0,self.boundingRect().height()/2.0) self.setZValue(10) ##menu contextual self.menu = QMenu() self.Actions =[] #arreglo de acciones self.Actions.append( self.menu.addAction("Seguir") ) self.Actions.append( self.menu.addAction("Editar") ) self.Actions.append( self.menu.addAction("girar clockwise") ) self.Actions.append( self.menu.addAction("girar anti-clockwise") ) self.Actions.append( self.menu.addAction("Colisiones") ) self.Actions.append( self.menu.addAction("Duplicar") ) self.Actions.append( self.menu.addAction("Eliminar") ) self.menu.triggered[QAction].connect(self.test) ##offset para el arrastre self.offset= QPointF(0,0) ##poligono de vision poligono = QPolygonF() poligono.append(QPointF(-1,10)) poligono.append(QPointF(-1,20)) poligono.append(QPointF(-30,40)) poligono.append(QPointF(-40,15)) poligono.append(QPointF(-30,-10)) self.vision = QGraphicsPolygonItem(poligono,self,self.scene()) self.vision.setBrush(QColor(255, 255, 0,100)) self.vision.setPen(QColor(255, 255, 0)) def info(self): return "Velocidad "+ str(self.velocity)+" posicion "+ str(self.pos())[20:]+"\n" def test(self,act): print act.text() if act.text()=="girar clockwise": self.setRotation(self.rotation()-45) if act.text()=="girar anti-clockwise": self.setRotation(self.rotation()+45) if act.text()=="Colisiones": print "colisiones con",self.collidingItems(1),self.vision.collidingItems(1) if act.text()=="Duplicar": self.scene().addItem(auto()) if act.text()=="Eliminar": self.scene().removeItem(self) def contextMenuEvent(self,event): self.menu.popup(event.screenPos()) def mousePressEvent(self, event): p = event.pos() self.offset= QPointF(p.x()*1.0,p.y()*1.0) self.seleccionado = not self.seleccionado def mouseMoveEvent(self, event): self.setPos(event.scenePos()-self.offset) def avanza(self): if self.velocity !=0: """print velocity print "current pos (%f,%f)"%(self.pos().x(),self.pos().y()) print "angle %f "%(self.rotation())""" radians = self.rotation()*0.0174532925 """ print "angle rad %f "%(radians)""" nx = 1.0*self.velocity*cos(radians) ny = 1.0*self.velocity*sin(radians) """ print "avanzara a (%f,%f)"%(nx,ny) """ self.setPos(self.pos().x()-nx,self.pos().y()-ny) """for i in self.collidingItems():