summaryrefslogtreecommitdiff
path: root/src/map/tile.cpp
blob: 1d4a660ac5f133ca00aa6f773a395333d1d1851f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
#include <llmr/map/tile.hpp>

#include <stdint.h>
#include <cassert>
// #include <iostream>
#include <thread>

#include <llmr/util/pbf.hpp>
#include <llmr/util/string.hpp>
#include <llmr/geometry/geometry.hpp>
#include <cmath>

using namespace llmr;

Tile::ID Tile::parent(const ID& id, int32_t z) {
    assert(z < id.z);
    ID pos(id);
    while (pos.z > z) {
        pos.z--;
        pos.x = floor(pos.x / 2);
        pos.y = floor(pos.y / 2);
    }
    return pos;
}


std::forward_list<Tile::ID> Tile::children(const ID& id, int32_t z) {
    assert(z > id.z);
    int32_t factor = pow(2, z - id.z);

    std::forward_list<ID> children;
    for (int32_t y = id.y * factor, y_max = (id.y + 1) * factor; y < y_max; y++) {
        for (int32_t x = id.x * factor, x_max = (id.x + 1) * factor; x < x_max; x++) {
            children.emplace_front(x, y, z);
        }
    }
    return children;
}


Tile::Tile(ID id)
    : id(id),
      state(initial),
      data(0),
      bytes(0) {

    // Initialize tile debug coordinates
    char coord[32];
    snprintf(coord, sizeof(coord), "%d/%d/%d", id.z, id.x, id.y);
    debugFontVertex.addText(coord, 50, 200, 5);
}

Tile::~Tile() {
    // fprintf(stderr, "[%p] deleting tile %d/%d/%d\n", this, id.z, id.x, id.y);
    if (this->data) {
        free(this->data);
    }
}

const std::string Tile::toString() const {
    return util::sprintf("[tile %d/%d/%d]", id.z, id.x, id.y);
}


void Tile::setData(uint8_t *data, uint32_t bytes) {
    this->data = (uint8_t *)malloc(bytes);
    this->bytes = bytes;
    memcpy(this->data, data, bytes);
}

void Tile::cancel() {
    // TODO: thread safety
    if (state != obsolete) {
        state = obsolete;
    } else {
        assert((!"logic error? multiple cancelleations"));
    }
}

bool Tile::parse() {
    std::lock_guard<std::mutex> lock(mtx);

    if (state == obsolete) {
        return false;
    }

    // fprintf(stderr, "[%p] parsing tile [%d/%d/%d]...\n", this, z, x, y);

    pbf tile(data, bytes);
    try {
        while (tile.next()) {
            if (tile.tag == 3) { // layer
                uint32_t bytes = (uint32_t)tile.varint();
                parseLayer(tile.data, bytes);
                tile.skipBytes(bytes);
            } else {
                tile.skip();
            }
        }
    } catch (const pbf::exception& ex) {
        fprintf(stderr, "[%p] parsing tile [%d/%d/%d]... failed: %s\n", this, id.z, id.x, id.y, ex.what());
        cancel();
        return false;
    } catch (const Tile::exception& ex) {
        fprintf(stderr, "[%p] parsing tile [%d/%d/%d]... failed: %s\n", this, id.z, id.x, id.y, ex.what());
        cancel();
        return false;
    } catch (const std::exception& ex) {
        fprintf(stderr, "[%p] general exception [%d/%d/%d]... failed: %s\n", this, id.z, id.x, id.y, ex.what());
        cancel();
        return false;
    }

    if (state == obsolete) {
        return false;
    } else {
        state = ready;
    }

    // int i = 0;
    // for (const fill_index& index : fillIndices) {
    //     fprintf(stderr, "[%p] %d: vertex   % 8d / % 8d\n", this, i, index.vertex_start, index.vertex_length);
    //     fprintf(stderr, "[%p] %d: elements % 8d / % 8d\n", this, i, index.elements_start, index.elements_length);
    //     i++;
    // }

    return true;
}

void Tile::parseLayer(const uint8_t *data, uint32_t bytes) {
    pbf layer(data, bytes);
    std::string name;

    uint32_t vertex_start = fillBuffer.vertex_length();
    uint32_t elements_start = fillBuffer.elements_length();
    fillIndices.emplace_back(vertex_start, elements_start);

    while (layer.next()) {
        if (layer.tag == 1) {
            name = layer.string();
            fillIndices.back().name = name;
        } else if (layer.tag == 2) {
            uint32_t bytes = (uint32_t)layer.varint();
            parseFeature(layer.data, bytes);
            layer.skipBytes(bytes);
        } else {
            layer.skip();
        }
    }
}


enum geom_type {
    Unknown = 0,
    Point = 1,
    LineString = 2,
    Polygon = 3
};


void Tile::parseFeature(const uint8_t *data, uint32_t bytes) {
    pbf feature(data, bytes);

    geom_type type = Unknown;
    pbf geom;

    while (feature.next()) {
        if (feature.tag == 1) {
            /*uint32_t id =*/ feature.varint();
        } else if (feature.tag == 2) {
            const uint8_t *tag_end = feature.data + feature.varint();
            while (feature.data < tag_end) {
                /*uint32_t key =*/ feature.varint();
                /*uint32_t value =*/ feature.varint();
            }
        } else if (feature.tag == 3) {
            type = (geom_type)feature.varint();
        } else if (feature.tag == 4) {
            geom = feature.message();
        } else {
            feature.skip();
        }
    }

    if (geom) {
        if (type == LineString) {
            addLineGeometry(geom);
        } else if (type == Polygon) {
            addFillGeometry(geom);
        }
    }
}

void Tile::addFillGeometry(pbf& geom) {

    std::vector<std::vector<std::pair<int16_t, int16_t>>> lines;

    {
        std::vector<std::pair<int16_t, int16_t>> line;
        Geometry::command cmd;
        int32_t x, y;
        Geometry geometry(geom);
        while ((cmd = geometry.next(x, y)) != Geometry::end) {
            if (cmd == Geometry::move_to) {
                if (line.size()) {
                    lines.push_back(line);
                    line.clear();
                }
            }
            line.emplace_back(x, y);
        }
        if (line.size()) {
            lines.push_back(line);
        }
    }

    for (const std::vector<std::pair<int16_t, int16_t>>& line : lines) {
        uint32_t vertex_start = fillBuffer.vertex_length();

        fillBuffer.addDegenerate();
        for (const std::pair<int16_t, int16_t>& coord : line) {
            fillBuffer.addCoordinate(coord.first, coord.second);
        }

        uint32_t vertex_end = fillBuffer.vertex_length();

        if (vertex_end - vertex_start > 65535) {
            throw geometry_too_long_exception();
        }

        if (!fillIndices.size()) {
            // Create a new index because there is none yet.
            throw std::runtime_error("no index yet");
        }

        fill_index& index = fillIndices.back();
        if (!index.groups.size()) {
            throw std::runtime_error("no group yet");
        }

        uint32_t vertex_count = vertex_end - vertex_start;
        index.length += vertex_count;

        if (index.groups.back().vertex_length + vertex_count > 65535) {
            // Move to a new group because the old one can't hold the geometry.
            index.groups.emplace_back();
        }

        fill_index::group& group = index.groups.back();

        // We're generating triangle fans, so we always start with the first
        // coordinate in this polygon.
        // The first valid index that is not a degenerate.
        uint16_t firstIndex = group.vertex_length + 1;

        assert(firstIndex + vertex_count - 1 < 65536);

        uint32_t elements_start = fillBuffer.elements_length();

        for (uint32_t i = 2; i < vertex_count; i++) {
            fillBuffer.addElements(firstIndex, firstIndex + i - 1, firstIndex + i);
        }

        uint32_t elements_end = fillBuffer.elements_length();
        uint32_t elements_count = elements_end - elements_start;
        group.vertex_length += vertex_count;
        group.elements_length += elements_count;
    }
}

void Tile::addLineGeometry(pbf& geom) {
    Geometry geometry(geom);

    Geometry::command cmd;
    int32_t x, y;
    while ((cmd = geometry.next(x, y)) != Geometry::end) {
        if (cmd == Geometry::move_to) {
            lineVertex.addDegenerate();
        }
        lineVertex.addCoordinate(x, y);
    }
}