def readObstacles(fileName, yFlip=False): print "READ OBSTACLES: ", fileName if (fileName[-3:] == 'xml'): parser = make_parser() obstHandler = ObstXMLParser() parser.setContentHandler(obstHandler) parser.parse(fileName) if (yFlip): for o in obstHandler.obstacles: o.flipY() obstHandler.bb.flipY() elif (fileName[-3:] == 'txt'): f = open(fileName, 'r') try: oCount = int(f.readline()) except ValueError: raise Exception, "Tried to parse Stephen's file format, but the first line was not edge count" bb = AABB() obstacles = ObstacleSet() for o in xrange(oCount): try: x0, y0, x1, y1 = map(lambda x: float(x), f.readline().split()) except: raise Exception, "Error trying to parse the sjguy obstacle file -- didn't find the specified number of edges" obst = GLPoly() obst.closed = False obst.vertices.append(Vector3(x0, y0, 0)) obst.vertices.append(Vector3(x1, y1, 0)) bb.expand(obst.vertices) obstacles.append(obst) f.close() return obstacles, bb else: raise Exception, "Invalid obstacle extension: %s" % (fileName) return obstHandler.obstacles, obstHandler.bb
class ObstXMLParser(handler.ContentHandler): def __init__(self): self.bb = AABB() self.obstacles = ObstacleSet() self.currObst = None def startElement(self, name, attrs): if (name == 'Obstacle'): # assume all obstacles have a closed attribute self.currObst = GLPoly() if (int(attrs['closed']) != 0): self.currObst.closed = True elif (name == 'Vertex' and self.currObst != None): x = float(attrs['p_x']) y = float(attrs['p_y']) self.currObst.vertices.append(Vector3(x, y, 0)) def endElement(self, name): if (name == "Obstacle"): self.currObst.close() self.obstacles.append(self.currObst) self.bb.expand(self.currObst.vertices) self.currObst = None def endDocument(self): print "Found %d obstacles" % (len(self.obstacles)) print "Overal BB:", self.bb print