tileset.py 1.76 KB
Newer Older
1
from math import floor
Jgiannelos's avatar
Jgiannelos committed
2
3
4
5
6
7
8
9
10
from dataclasses import dataclass


@dataclass(eq=True, frozen=True)
class Tile:
    z: int
    x: int
    y: int

11
    @property
Jgiannelos's avatar
Jgiannelos committed
12
13
14
15
16
17
18
19
20
    def children(self):
        """Calculate the children tiles of a tile"""
        return [
            Tile(self.z + 1, self.x * 2, self.y * 2),
            Tile(self.z + 1, self.x * 2 + 1, self.y * 2),
            Tile(self.z + 1, self.x * 2, self.y * 2 + 1),
            Tile(self.z + 1, self.x * 2 + 1, self.y * 2 + 1),
        ]

21
22
23
24
25
    @property
    def parent(self):
        """Calculate the parent tile of a tile"""
        return Tile(self.z - 1, floor(self.x / 2), floor(self.y / 2))

Jgiannelos's avatar
Jgiannelos committed
26
27
28
29
30
31
32
33
34
35
36
37
38
39

class TileSet:
    def __init__(self, tilelistPath, maxzoom):
        self.tilelistPath = tilelistPath
        self.tileset = set()
        self.maxzoom = maxzoom

    @staticmethod
    def parse(entry):
        """Parse tile list entries"""
        entry = entry.rstrip()
        (z, x, y) = map(int, entry.split("/"))
        return Tile(z, x, y)

40
41
42
    def addParent(self, tile):
        """Add parent tile in the tileset"""
        if tile.z < 0 or tile in self.tileset:
Jgiannelos's avatar
Jgiannelos committed
43
44
            return

Jgiannelos's avatar
Jgiannelos committed
45
        self.tileset.add(tile)
46
47
48
49
50
51
52
        self.addParent(tile.parent)

    def addChildren(self, tiles):
        """Add children tiles in the tileset"""
        for tile in tiles:
            if tile.z > self.maxzoom or tile in self.tileset:
                return
Jgiannelos's avatar
Jgiannelos committed
53

54
55
            self.tileset.add(tile)
            self.addChildren(tile.children)
Jgiannelos's avatar
Jgiannelos committed
56
57
58
59
60
61

    def read(self):
        """Read tilelist as input"""
        with open(self.tilelistPath, "r") as f:
            for line in f.readlines():
                tile = self.parse(line)
62
63
64
                self.addParent(tile.parent)
                self.addChildren(tile.children)
                self.tileset.add(tile)