예제 #1
0
def export(width, height, filename, elements):
    surface = SVGSurface(filename, width, height)
    ctx = Context(width, height, surface)

    elements.draw(ctx)

    surface.finish()
예제 #2
0
def test_render_points():
    # Test for effectivenes of ticket #402 (borderline points get lost on reprojection)
    raise Todo("See: http://trac.mapnik2.org/ticket/402")

    if not mapnik2.has_pycairo():
        return

    # create and populate point datasource (WGS84 lat-lon coordinates)
    places_ds = mapnik2.PointDatasource()
    places_ds.add_point(142.48, -38.38, "Name", "Westernmost Point")  # westernmost
    places_ds.add_point(143.10, -38.60, "Name", "Southernmost Point")  # southernmost
    # create layer/rule/style
    s = mapnik2.Style()
    r = mapnik2.Rule()
    symb = mapnik2.PointSymbolizer()
    symb.allow_overlap = True
    r.symbols.append(symb)
    s.rules.append(r)
    lyr = mapnik2.Layer("Places", "+proj=latlon +datum=WGS84")
    lyr.datasource = places_ds
    lyr.styles.append("places_labels")
    # latlon bounding box corners
    ul_lonlat = mapnik2.Coord(142.30, -38.20)
    lr_lonlat = mapnik2.Coord(143.40, -38.80)
    # render for different projections
    projs = {
        "latlon": "+proj=latlon +datum=WGS84",
        "merc": "+proj=merc +datum=WGS84 +k=1.0 +units=m +over +no_defs",
        "google": "+proj=merc +ellps=sphere +R=6378137 +a=6378137 +units=m",
        "utm": "+proj=utm +zone=54 +datum=WGS84",
    }
    from cairo import SVGSurface

    for projdescr in projs.iterkeys():
        m = mapnik2.Map(1000, 500, projs[projdescr])
        m.append_style("places_labels", s)
        m.layers.append(lyr)
        p = mapnik2.Projection(projs[projdescr])
        m.zoom_to_box(p.forward(mapnik2.Box2d(ul_lonlat, lr_lonlat)))
        # Render to SVG so that it can be checked how many points are there with string comparison
        import StringIO

        svg_memory_file = StringIO.StringIO()
        surface = SVGSurface(svg_memory_file, m.width, m.height)
        mapnik2.render(m, surface)
        surface.flush()
        surface.finish()
        svg = svg_memory_file.getvalue()
        svg_memory_file.close()
        num_points_present = len(places_ds.all_features())
        num_points_rendered = svg.count("<image ")
        eq_(
            num_points_present,
            num_points_rendered,
            "Not all points were rendered (%d instead of %d) at projection %s"
            % (num_points_rendered, num_points_present, projdescr),
        )
예제 #3
0
def extract_polygon_data(romset_dir, cinematic):
    global polygon_data, pdata_offset
    global cinematic_entries
    global cinematic_counter
    global video2_entries
    global game_level

    if cinematic:
        try:
            polygon_data = open(f"{romset_dir}/cinematic.rom", "rb").read()
        except:
            print("FIXME! Did not find a cinematic.rom file...")
            return
        entries = cinematic_entries
        level_path = f"{output_dir}/level_{game_level}"
        dirpath = f"{level_path}/cinematic/"
        makedir(level_path)
    else:
        try:
            polygon_data = open(f"{romset_dir}/video2.rom", "rb").read()
        except:
            print("FIXME! Did not find a video2.rom file...")
            return

        entries = video2_entries
        dirpath = f"{output_dir}/common_video/"
        game_level = 0

    makedir(dirpath)

    for addr in entries.keys():
        entry = entries[addr]
        s = SVGSurface(f"{dirpath}/{entry['label']}.svg", 320, 200)
        c = Context(s)
        zoom = entry["zoom"]
        x = entry["x"]
        y = entry["y"]

        if not isinstance(zoom, int):
            zoom = 0x40  #HACK!

        if not isinstance(x, int):
            x = 160  #HACK!

        if not isinstance(y, int):
            y = 100  #HACK!

        #print ("\ndecoding polygons at {}: {}".format(hex(addr), entry))
        pdata_offset = addr
        readAndDrawPolygon(c, COLOR_BLACK, zoom, x, y)
        s.finish()

    # reset structures:
    cinematic_entries = {}
    cinematic_counter = 0
예제 #4
0
def test_render_points():
    # Test for effectivenes of ticket #402 (borderline points get lost on reprojection)
    raise Todo("See: http://trac.mapnik2.org/ticket/402")

    if not mapnik2.has_pycairo(): return

    # create and populate point datasource (WGS84 lat-lon coordinates)
    places_ds = mapnik2.PointDatasource()
    places_ds.add_point(142.48, -38.38, 'Name',
                        'Westernmost Point')  # westernmost
    places_ds.add_point(143.10, -38.60, 'Name',
                        'Southernmost Point')  # southernmost
    # create layer/rule/style
    s = mapnik2.Style()
    r = mapnik2.Rule()
    symb = mapnik2.PointSymbolizer()
    symb.allow_overlap = True
    r.symbols.append(symb)
    s.rules.append(r)
    lyr = mapnik2.Layer('Places', '+proj=latlon +datum=WGS84')
    lyr.datasource = places_ds
    lyr.styles.append('places_labels')
    # latlon bounding box corners
    ul_lonlat = mapnik2.Coord(142.30, -38.20)
    lr_lonlat = mapnik2.Coord(143.40, -38.80)
    # render for different projections
    projs = {
        'latlon': '+proj=latlon +datum=WGS84',
        'merc': '+proj=merc +datum=WGS84 +k=1.0 +units=m +over +no_defs',
        'google': '+proj=merc +ellps=sphere +R=6378137 +a=6378137 +units=m',
        'utm': '+proj=utm +zone=54 +datum=WGS84'
    }
    from cairo import SVGSurface
    for projdescr in projs.iterkeys():
        m = mapnik2.Map(1000, 500, projs[projdescr])
        m.append_style('places_labels', s)
        m.layers.append(lyr)
        p = mapnik2.Projection(projs[projdescr])
        m.zoom_to_box(p.forward(mapnik2.Box2d(ul_lonlat, lr_lonlat)))
        # Render to SVG so that it can be checked how many points are there with string comparison
        import StringIO
        svg_memory_file = StringIO.StringIO()
        surface = SVGSurface(svg_memory_file, m.width, m.height)
        mapnik2.render(m, surface)
        surface.flush()
        surface.finish()
        svg = svg_memory_file.getvalue()
        svg_memory_file.close()
        num_points_present = len(places_ds.all_features())
        num_points_rendered = svg.count('<image ')
        eq_(
            num_points_present, num_points_rendered,
            "Not all points were rendered (%d instead of %d) at projection %s"
            % (num_points_rendered, num_points_present, projdescr))
    def extract_polygon_data(self, game_level, entries, cinematic):
        if cinematic:
            self.game_level = game_level
        else:
            self.game_level = 0

        try:
            self.palette_data = open(f"{self.romset_dir}/palettes.rom", "rb").read()
        except:
            print("ERROR! Did not find a palettes.rom file...")
            return

        if cinematic:
            try:
                self.polygon_data = open(f"{self.romset_dir}/cinematic.rom", "rb").read()
            except:
                print("ERROR! Did not find a cinematic.rom file...")
                return
            level_path = f"{self.output_dir}/level_{game_level}"
            dirpath = f"{level_path}/cinematic/"
            makedir(level_path)
        else:
            try:
                self.polygon_data = open(f"{self.romset_dir}/video2.rom", "rb").read()
            except:
                print("ERROR! Did not find a video2.rom file...")
                return
    
            dirpath = f"{self.output_dir}/common_video/"

        makedir(dirpath)

        for addr in entries.keys():
            entry = entries[addr]
            s = SVGSurface(f"{dirpath}/{entry['label']}.svg", 320, 200)
            ctx = Context(s)
            zoom = entry["zoom"]
            x = entry["x"]
            y = entry["y"]
            palette_number = entry["palette_number"]

            if not isinstance(zoom, int):
                zoom = 0x40 #HACK!

            if not isinstance(x, int):
                x = 160 #HACK!

            if not isinstance(y, int):
                y = 100 #HACK!

            #print ("\ndecoding polygons at {}: {}".format(hex(addr), entry))
            self.readAndDrawPolygon(addr, ctx, palette_number, COLOR_BLACK, zoom, x, y)
            s.finish()
예제 #6
0
def draw_svg_asd(filename):
    
    surface = SVGSurface(filename, 320, 240)
    c = cairo.Context(surface)

    c.set_source_rgb(1, 1, 1)
    c.paint()

    c.arc(100, 80, 50, 0, 2*math.pi)
    c.set_source_rgba(1,0,0,1)
    c.fill()

    surface.finish()
예제 #7
0
class MapSurface(object):
    """wrapper to render the map to svg/png"""

    def __init__(self, hexmap=None, filename=None, width=None, height=None, size=None):
        self.hexmap = hexmap
        if self.hexmap is None:
            raise ValueError("No map was passed to {}".format(self.__class__.__name__))
        self.surface_name = filename or "test.svg"
        self.size = size or 32.0
        self.surface_width = width
        if self.surface_width is None:
            self.surface_width = (self.hexmap.map.cols + .5) * self.size * SQRT3
        self.surface_height = height
        if self.surface_height is None:
            self.surface_height = (self.hexmap.map.rows * 1.5 + .25) * self.size
        self.layer = []

        # build base map
        self.surface = SVGSurface(self.surface_name + ".svg", self.surface_width, self.surface_height)
        self.context = Context(self.surface)
        # background: magenta
        self.context.save()
        self.context.set_source_rgb(1.0, 0.0, 1.0)
        self.context.paint()
        self.context.restore()

    def add_layer(self, renderer_cls, position=None):
        if not position:
            self.layer.append(renderer_cls(self))
        else:
            self.layer.insert(position, renderer_cls(self))

    def render(self):
        print "Rendering {} ({}x{})".format(self.surface_name, self.surface_width, self.surface_height)
        for renderer in self.layer:
            renderer.render()

    def finalise(self, with_png=False):
        print "finalising:"
        if with_png is True:
            print "PNG"
            self.surface.write_to_png(self.surface_name + ".png")
        print "SVG"
        self.surface.finish()
        print "DONE!"
                VERTS[i + 1][0],
                VERTS[i + 1][1])
            i += 2
        elif (CODES[i] == CURVE4):
            ctx.curve_to(VERTS[i][0], VERTS[i][1], VERTS[i + 1][0],
                         VERTS[i + 1][1], VERTS[i + 2][0], VERTS[i + 2][1])
            i += 3
    ctx.fill_preserve()
    ctx.set_source_rgb(0, 0, 0)
    ctx.set_line_width(6)
    ctx.stroke()
    ctx.restore()

    scale2 = (height_s - 2.0 * MARGIN) / rows

    ctx.set_source_surface(Z, 0, 0)
    pattern = ctx.get_source()
    SurfacePattern.set_filter(pattern, FILTER_BEST)
    scalematrix = Matrix()
    scalematrix.scale(1.0 / scale2, 1.0 / scale2)
    scalematrix.translate(-(width_s / 2.0 - width * scale2 / 2.0), -MARGIN)
    pattern.set_matrix(scalematrix)
    ctx.set_source_rgba(0, 0, 0, 0.7)
    ctx.mask(pattern)
    ctx.fill()

    surface.flush()
    surface.write_to_png("glyph-vector-2-cairo.png")
    surface.finish()
    Image.open("glyph-vector-2-cairo.png").show()
예제 #9
0
            i += 2
        elif (CODES[i] == CURVE4):
            ctx.curve_to(VERTS[i][0],VERTS[i][1],
                         VERTS[i+1][0],VERTS[i+1][1],
                         VERTS[i+2][0],VERTS[i+2][1])
            i += 3
    ctx.fill_preserve()
    ctx.set_source_rgb(0,0,0)
    ctx.set_line_width(6)
    ctx.stroke()
    ctx.restore()

    scale2 = (height_s - 2.0 * MARGIN)/rows

    ctx.set_source_surface(Z, 0, 0)
    pattern = ctx.get_source()
    SurfacePattern.set_filter(pattern, FILTER_BEST)
    scalematrix = Matrix()
    scalematrix.scale(1.0/scale2, 1.0/scale2)
    scalematrix.translate(-( width_s/2.0  - width *scale2 /2.0 ), -MARGIN)
    pattern.set_matrix(scalematrix)
    ctx.set_source_rgba (0, 0, 0, 0.7)
    ctx.mask(pattern)
    ctx.fill()


    surface.flush()
    surface.write_to_png("glyph-vector-2-cairo.png")
    surface.finish()
    Image.open("glyph-vector-2-cairo.png").show()