Compare commits

..
Author SHA1 Message Date
Claude 9ff3f92e6e Spread shared node marking across all CPUs regardless of readers
Marking used one thread per reader, so input that was read serially,
which all goes to the first reader, was marked by a single thread.
Instead, use the readers' indexes to divide all the geometry into
ranges of about the same size at feature boundaries, and have each
thread take the next unmarked range until there are none left.

With 4 CPUs and input read by one reader, this makes marking about
3x faster.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01P2nBqZisxNQfmEmon3vE9v
2026-09-23 20:02:49 +00:00
Claude 58ad6e3008 Use the faster bit interleave for encode_quadkey itself
encode_vertex() computed exactly the same thing as encode_quadkey(),
so there is no reason to have both. Give encode_quadkey() the branch-free
implementation, which also speeds up the default encode_index, and have
the shared node code call it directly. The unit test now compares it
against the old bit-at-a-time loop and checks that decode_quadkey()
reverses it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01P2nBqZisxNQfmEmon3vE9v
2026-09-23 20:02:49 +00:00
Claude e1795ebe32 Make the remaining shared node lookups faster
Encode the shared nodes as quadkeys, as the comment on struct node
already said they were, with a branch-free bit interleave, so that
vertices that are near each other are near each other in the sorted list
too. Search the list with an inlined std::lower_bound instead of bsearch.

Size the Bloom filter by the number of nodes, at about 16 bits each and
at most 32MB, instead of always using 34MB, so that it can usually stay
in the cache, and set three bits for each node, chosen by a mixing hash,
within a single 64-bit word, so that each check still touches only one
cache line but has far fewer false positives than a single bit.

In the pass that marks the vertices with whether they are shared nodes,
this is about 1.7x faster with 70 thousand nodes and 1.9x faster with
3 million.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01P2nBqZisxNQfmEmon3vE9v
2026-09-23 19:46:09 +00:00
Claude 175036930d Test --no-simplification-of-shared-nodes with --clip-bounding-box
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01P2nBqZisxNQfmEmon3vE9v
2026-09-23 18:28:32 +00:00
Claude f03cc8ce0e Treat points created by clipping and tiny polygon placeholders as not shared
Points that clipping creates along a feature's edges, other than at the
existing vertices, and the vertices of tiny polygon placeholders, are
not vertices of the original geometry, so they are now marked as not
being shared nodes instead of being looked up in the global list of
shared nodes when they are simplified. This could only change the output
where a vertex of some other feature happens to fall exactly on one of
these new points, and in practice none of them ever turned out to be
shared nodes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01P2nBqZisxNQfmEmon3vE9v
2026-09-23 18:28:04 +00:00
Claude 1dee1890e7 Mask the node state out of the operation when marking shared nodes
Geometry that was clipped to --clip-bounding-box while it was being
serialized can already have node states in its operation bytes, so the
unmasked comparison against VT_MOVETO and VT_LINETO failed to recognize
those vertices and lost track of where the following vertices began.
Also stop with an error instead of continuing if the operation is not
one that can appear in serialized geometry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01P2nBqZisxNQfmEmon3vE9v
2026-09-23 18:28:04 +00:00
Claude ee5debc4f2 Don't look up shared nodes that are already necessary
Vertices that are already going to be kept, because they begin a ring
or are on the tile boundary, can't be affected by whether they are also
global shared nodes, so skip looking them up. These are most of the
vertices that clipping creates, which don't know their node state.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01P2nBqZisxNQfmEmon3vE9v
2026-09-23 18:09:52 +00:00
Claude d3a98170bf Look up shared nodes once per vertex instead of once per tile
With --no-simplification-of-shared-nodes, simplify_lines() used to offset
every vertex of every feature to world coordinates and check it against
the Bloom filter and the global sorted list of shared nodes, in every
tile at every zoom level.

Whether a vertex is a shared node depends only on its world coordinates,
so now it is found once, after the list of shared nodes has been made
and before the geometry is sorted, by a parallel pass over each reader's
geometry that marks each vertex in place, in the upper bits of its
serialized operation byte. Decoding puts that state into a new field of
draw (which still fits in 16 bytes), and it is carried through clipping,
the copies across the antimeridian at z0, and the geometry written for
the next zoom level. Polygon cleaning of coalesced features restores the
state of any output vertex with the same coordinates as an input vertex.

Vertices whose state is still unknown, because they were created by
clipping or polygon cleaning or came back from a prefilter, are still
looked up in the global list when they are simplified, so the output is
unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01P2nBqZisxNQfmEmon3vE9v
2026-09-23 17:39:48 +00:00
17 changed files with 2598 additions and 85 deletions
+27
View File
@@ -1,3 +1,30 @@
# 2.83.0
* Speed up `--no-simplification-of-shared-nodes` by checking each vertex
against the global list of shared nodes only once, before tiling begins,
instead of again in every tile at every zoom level. Each vertex now carries
whether it is a shared node, in the upper bits of its serialized operation
byte and in a new field of `draw`, through clipping and into the geometry
for the next zoom level. Vertices that are already being kept, because they
begin a ring or are on the tile boundary, are not looked up at all.
* Points that clipping creates along a feature's edges, and the vertices
of tiny polygon placeholders, are no longer considered to be shared nodes,
since they are not vertices of the original geometry. This could only
change the output where a vertex of some other feature happens to fall
exactly on one of these new points, and means that only
vertices that come back from a prefilter, or that are created by polygon
cleaning, still need to be looked up in the list of shared nodes during tiling.
* Make the remaining lookups of shared nodes faster: sort the list of nodes
by quadkey, as its comment always said, so that nearby vertices are near
each other in the list; search it with `std::lower_bound` instead of `bsearch`;
and size the Bloom filter in front of it by the number of nodes, with three
bits for each node within one 64-bit word, so that it usually fits in the cache.
* Spread the marking of shared nodes across all the CPUs even when all
the features were read by one reader, by dividing the geometry into
ranges at feature boundaries instead of giving each reader's geometry
to its own thread.
* Speed up `encode_quadkey` with a branch-free bit interleave.
# 2.82.0
* Fix corruption of a JSON array when a non-final element was removed from it.
+78 -31
View File
@@ -16,10 +16,29 @@
#include "projection.hpp"
#include "read_json.hpp"
static std::vector<std::pair<double, double>> clip_poly1(std::vector<std::pair<double, double>> &geom,
long long minx, long long miny, long long maxx, long long maxy,
long long ax, long long ay, long long bx, long long by, drawvec &edge_nodes,
bool prevent_simplify_shared_nodes);
// A vertex being clipped, which remembers whether it is a shared node.
struct clip_point_d {
double first;
double second;
signed char node = NODE_UNKNOWN;
clip_point_d()
: first(0), second(0) {
}
clip_point_d(double x, double y)
: first(x), second(y) {
}
clip_point_d(double x, double y, signed char n)
: first(x), second(y), node(n) {
}
};
static std::vector<clip_point_d> clip_poly1(std::vector<clip_point_d> &geom,
long long minx, long long miny, long long maxx, long long maxy,
long long ax, long long ay, long long bx, long long by, drawvec &edge_nodes,
bool prevent_simplify_shared_nodes);
drawvec simple_clip_poly(drawvec &geom, long long minx, long long miny, long long maxx, long long maxy,
long long ax, long long ay, long long bx, long long by, drawvec &edge_nodes, bool prevent_simplify_shared_nodes) {
@@ -37,11 +56,11 @@ drawvec simple_clip_poly(drawvec &geom, long long minx, long long miny, long lon
}
}
std::vector<std::pair<double, double>> tmp;
std::vector<clip_point_d> tmp;
for (size_t k = i; k < j; k++) {
double x = geom[k].x;
double y = geom[k].y;
tmp.emplace_back(x, y);
tmp.emplace_back(x, y, geom[k].node);
}
tmp = clip_poly1(tmp, minx, miny, maxx, maxy, ax, ay, bx, by, edge_nodes, prevent_simplify_shared_nodes);
if (tmp.size() > 0) {
@@ -52,9 +71,9 @@ drawvec simple_clip_poly(drawvec &geom, long long minx, long long miny, long lon
}
for (size_t k = 0; k < tmp.size(); k++) {
if (k == 0) {
out.push_back(draw(VT_MOVETO, std::round(tmp[k].first), std::round(tmp[k].second)));
out.push_back(draw(VT_MOVETO, std::round(tmp[k].first), std::round(tmp[k].second), tmp[k].node));
} else {
out.push_back(draw(VT_LINETO, std::round(tmp[k].first), std::round(tmp[k].second)));
out.push_back(draw(VT_LINETO, std::round(tmp[k].first), std::round(tmp[k].second), tmp[k].node));
}
}
@@ -126,13 +145,15 @@ drawvec clip_lines(drawvec &geom, long long minx, long long miny, long long maxx
int c = clip(&x1, &y1, &x2, &y2, minx, miny, maxx, maxy);
if (c > 1) { // clipped
out.push_back(draw(VT_MOVETO, x1, y1));
out.push_back(draw(VT_LINETO, x2, y2));
out.push_back(draw(VT_MOVETO, geom[i].x, geom[i].y));
// endpoints that weren't moved by clipping keep their node state;
// new endpoints along the segment aren't original vertices, so aren't shared nodes
out.push_back(draw(VT_MOVETO, x1, y1, (x1 == geom[i - 1].x && y1 == geom[i - 1].y) ? geom[i - 1].node : NODE_NOT_SHARED));
out.push_back(draw(VT_LINETO, x2, y2, (x2 == geom[i].x && y2 == geom[i].y) ? geom[i].node : NODE_NOT_SHARED));
out.push_back(draw(VT_MOVETO, geom[i].x, geom[i].y, geom[i].node));
} else if (c == 1) { // unchanged
out.push_back(geom[i]);
} else { // clipped away entirely
out.push_back(draw(VT_MOVETO, geom[i].x, geom[i].y));
out.push_back(draw(VT_MOVETO, geom[i].x, geom[i].y, geom[i].node));
}
} else {
out.push_back(geom[i]);
@@ -739,7 +760,7 @@ drawvec close_poly(drawvec &geom) {
return out;
}
static bool inside(std::pair<double, double> d, int edge, long long minx, long long miny, long long maxx, long long maxy) {
static bool inside(clip_point_d const &d, int edge, long long minx, long long miny, long long maxx, long long maxy) {
switch (edge) {
case 0: // top
return d.second > miny;
@@ -758,41 +779,64 @@ static bool inside(std::pair<double, double> d, int edge, long long minx, long l
exit(EXIT_FAILURE);
}
static std::pair<double, double> intersect(std::pair<double, double> a, std::pair<double, double> b, int edge, long long minx, long long miny, long long maxx, long long maxy) {
static clip_point_d intersect1(clip_point_d const &a, clip_point_d const &b, int edge, long long minx, long long miny, long long maxx, long long maxy) {
switch (edge) {
case 0: // top
return std::pair<double, double>((a.first + (double) (b.first - a.first) * (miny - a.second) / (b.second - a.second)), miny);
return clip_point_d((a.first + (double) (b.first - a.first) * (miny - a.second) / (b.second - a.second)), miny);
case 1: // right
return std::pair<double, double>(maxx, (a.second + (double) (b.second - a.second) * (maxx - a.first) / (b.first - a.first)));
return clip_point_d(maxx, (a.second + (double) (b.second - a.second) * (maxx - a.first) / (b.first - a.first)));
case 2: // bottom
return std::pair<double, double>((a.first + (double) (b.first - a.first) * (maxy - a.second) / (b.second - a.second)), maxy);
return clip_point_d((a.first + (double) (b.first - a.first) * (maxy - a.second) / (b.second - a.second)), maxy);
case 3: // left
return std::pair<double, double>(minx, (a.second + (double) (b.second - a.second) * (minx - a.first) / (b.first - a.first)));
return clip_point_d(minx, (a.second + (double) (b.second - a.second) * (minx - a.first) / (b.first - a.first)));
}
fprintf(stderr, "internal error intersecting\n");
exit(EXIT_FAILURE);
}
// If the intersection is at one of the endpoints of the segment,
// it is the same vertex, and has the same node state.
//
// Otherwise it is a new point along the segment, which is not a vertex
// of the original geometry, so it is treated as not being a shared node.
// (It could only be one if some other feature had a vertex exactly where
// this feature's edge crosses the clipping line, without this feature
// having a vertex there too.)
static clip_point_d intersect(clip_point_d const &a, clip_point_d const &b, int edge, long long minx, long long miny, long long maxx, long long maxy) {
clip_point_d p = intersect1(a, b, edge, minx, miny, maxx, maxy);
double x = std::round(p.first), y = std::round(p.second);
if (x == a.first && y == a.second) {
p.node = a.node;
} else if (x == b.first && y == b.second) {
p.node = b.node;
} else {
p.node = NODE_NOT_SHARED;
}
return p;
}
// http://en.wikipedia.org/wiki/Sutherland%E2%80%93Hodgman_algorithm
static std::vector<std::pair<double, double>> clip_poly1(std::vector<std::pair<double, double>> &geom,
long long minx, long long miny, long long maxx, long long maxy,
long long ax, long long ay, long long bx, long long by, drawvec &edge_nodes,
bool prevent_simplify_shared_nodes) {
std::vector<std::pair<double, double>> out = geom;
static std::vector<clip_point_d> clip_poly1(std::vector<clip_point_d> &geom,
long long minx, long long miny, long long maxx, long long maxy,
long long ax, long long ay, long long bx, long long by, drawvec &edge_nodes,
bool prevent_simplify_shared_nodes) {
std::vector<clip_point_d> out = geom;
for (int edge = 0; edge < 4; edge++) {
if (out.size() > 0) {
std::vector<std::pair<double, double>> in = out;
std::vector<clip_point_d> in = out;
out.resize(0);
std::pair<double, double> S = in[in.size() - 1];
clip_point_d S = in[in.size() - 1];
for (size_t e = 0; e < in.size(); e++) {
std::pair<double, double> E = in[e];
clip_point_d E = in[e];
if (!inside(S, edge, minx, miny, maxx, maxy)) {
// was outside the buffer
@@ -1087,11 +1131,14 @@ drawvec reduce_tiny_poly(drawvec const &geom, int z, int detail, bool *still_nee
if (area > 0 && *accum_area > pixel * pixel) {
// XXX use centroid;
out.emplace_back(VT_MOVETO, geom[i].x - pixel / 2, geom[i].y - pixel / 2);
out.emplace_back(VT_LINETO, geom[i].x - pixel / 2 + pixel, geom[i].y - pixel / 2);
out.emplace_back(VT_LINETO, geom[i].x - pixel / 2 + pixel, geom[i].y - pixel / 2 + pixel);
out.emplace_back(VT_LINETO, geom[i].x - pixel / 2, geom[i].y - pixel / 2 + pixel);
out.emplace_back(VT_LINETO, geom[i].x - pixel / 2, geom[i].y - pixel / 2);
// This placeholder is synthetic, so none of its vertices
// can be shared nodes from the original geometry.
out.emplace_back(VT_MOVETO, geom[i].x - pixel / 2, geom[i].y - pixel / 2, NODE_NOT_SHARED);
out.emplace_back(VT_LINETO, geom[i].x - pixel / 2 + pixel, geom[i].y - pixel / 2, NODE_NOT_SHARED);
out.emplace_back(VT_LINETO, geom[i].x - pixel / 2 + pixel, geom[i].y - pixel / 2 + pixel, NODE_NOT_SHARED);
out.emplace_back(VT_LINETO, geom[i].x - pixel / 2, geom[i].y - pixel / 2 + pixel, NODE_NOT_SHARED);
out.emplace_back(VT_LINETO, geom[i].x - pixel / 2, geom[i].y - pixel / 2, NODE_NOT_SHARED);
*accum_area -= pixel * pixel;
}
+1 -2
View File
@@ -12,7 +12,6 @@
#include <errno.h>
#include "geojson-loop.hpp"
#include "jsonpull/jsonpull.h"
#include "text.hpp"
// XXX duplicated
#define GEOM_TYPES 6
@@ -30,7 +29,7 @@ static void json_context(json_object *j) {
std::string s = json_stringify(j);
if (s.size() >= 500) {
s = truncate_string(s, 497);
s.resize(497);
s.append("...");
}
+105 -19
View File
@@ -7,6 +7,7 @@
#include <cstdio>
#include <unistd.h>
#include <cmath>
#include <cstring>
#include <limits.h>
#include <sqlite3.h>
#include <mapbox/geometry/point.hpp>
@@ -37,6 +38,9 @@ drawvec decode_geometry(const char **meta, int z, unsigned tx, unsigned ty, long
break;
}
d.node = (d.op >> NODE_SHIFT) & NODE_MASK;
d.op &= OP_MASK;
if (d.op == VT_MOVETO || d.op == VT_LINETO) {
long long dx, dy;
@@ -216,6 +220,81 @@ drawvec impose_tile_boundaries(const drawvec &geom, long long extent) {
return out;
}
// Where a shared node goes in the Bloom filter: three bits, all within the same
// 64-bit word, so that checking for a node only touches one cache line.
static void shared_node_bloom_bits(unsigned long long index, size_t bloom_size, size_t *word, unsigned long long *mask) {
// splitmix64 finalizer, to spread out the index, whose low bits are
// mostly zero because of the geometry scale
unsigned long long h = index;
h ^= h >> 30;
h *= 0xBF58476D1CE4E5B9ULL;
h ^= h >> 27;
h *= 0x94D049BB133111EBULL;
h ^= h >> 31;
*word = ((h >> 32) * (unsigned long long) (bloom_size / sizeof(unsigned long long))) >> 32;
*mask = (1ULL << (h & 63)) | (1ULL << ((h >> 6) & 63)) | (1ULL << ((h >> 12) & 63));
}
void add_shared_node_to_bloom(std::string &shared_nodes_bloom, unsigned long long index) {
size_t word;
unsigned long long mask, bits;
shared_node_bloom_bits(index, shared_nodes_bloom.size(), &word, &mask);
memcpy(&bits, shared_nodes_bloom.data() + word * sizeof(bits), sizeof(bits));
bits |= mask;
memcpy(&shared_nodes_bloom[0] + word * sizeof(bits), &bits, sizeof(bits));
}
// Is the vertex at world coordinates wx, wy one of the nodes in the global list of shared nodes?
bool is_shared_node(long long wx, long long wy, struct node const *shared_nodes_map, size_t nodepos, std::string const &shared_nodes_bloom) {
struct node n;
n.index = encode_quadkey((unsigned) wx, (unsigned) wy);
size_t word;
unsigned long long mask, bits;
shared_node_bloom_bits(n.index, shared_nodes_bloom.size(), &word, &mask);
memcpy(&bits, shared_nodes_bloom.data() + word * sizeof(bits), sizeof(bits));
if ((bits & mask) == mask) {
struct node const *end = shared_nodes_map + nodepos / sizeof(node);
struct node const *found = std::lower_bound(shared_nodes_map, end, n.index, [](struct node const &a, unsigned long long b) {
return a.index < b;
});
if (found != end && found->index == n.index) {
return true;
}
}
return false;
}
// Operations like polygon cleaning that construct new geometries don't know about
// the node states of the vertices. But since the node state is a function only
// of the vertex's coordinates, any vertex in the output that has the same coordinates
// as a vertex in the input must have the same node state as that vertex did.
void restore_node_states(drawvec const &from, drawvec &to) {
drawvec known;
for (auto const &d : from) {
if ((d.op == VT_MOVETO || d.op == VT_LINETO) && d.node != NODE_UNKNOWN) {
known.push_back(d);
}
}
if (known.size() == 0) {
return;
}
std::sort(known.begin(), known.end());
for (auto &d : to) {
if ((d.op == VT_MOVETO || d.op == VT_LINETO) && d.node == NODE_UNKNOWN) {
auto pt = std::lower_bound(known.begin(), known.end(), d);
if (pt != known.end() && *pt == d) {
d.node = pt->node;
}
}
}
}
drawvec simplify_lines(drawvec &geom, int z, int tx, int ty, int detail, bool mark_tile_bounds, double simplification, size_t retain, drawvec const &shared_nodes, struct node *shared_nodes_map, size_t nodepos, std::string const &shared_nodes_bloom) {
int res = 1 << (32 - detail - z);
long long area = 1LL << (32 - z);
@@ -236,33 +315,40 @@ drawvec simplify_lines(drawvec &geom, int z, int tx, int ty, int detail, bool ma
// * the drawvec, which is nodes that were introduced during clipping to the tile edge,
// and which are in local tile coordinates
// * the shared_nodes_map, which was made globally before tiling began, and which
// is in global quadkey coordinates.
// To look through the latter, we need to offset and encode the coordinates
// of the feature we are simplifying.
// is in global coordinates.
//
// The vertices from the original geometry were already checked against the
// shared_nodes_map before tiling began, and carry the result of that check
// in their node state, so it is only vertices that have been created since then,
// by clipping or polygon cleaning, that need to be looked up in it here.
// To look through it, we need to offset the coordinates to global.
//
// If the shared_nodes_map is NULL, the caller doesn't want the global
// shared nodes to be preserved, so the node states are ignored too.
auto pt = std::lower_bound(shared_nodes.begin(), shared_nodes.end(), geom[i]);
if (pt != shared_nodes.end() && *pt == geom[i]) {
geom[i].necessary = true;
}
if (nodepos > 0) {
// offset to global
draw d = geom[i];
if (z != 0) {
d.x += tx * (1LL << (32 - z));
d.y += ty * (1LL << (32 - z));
// A vertex that is already necessary, because it is the start of a ring
// or on the tile boundary, doesn't need to be looked up, since the answer
// could only make it necessary again.
if (shared_nodes_map != NULL && nodepos > 0 && !geom[i].necessary) {
if (geom[i].node == NODE_UNKNOWN) {
// offset to global
long long wx = geom[i].x;
long long wy = geom[i].y;
if (z != 0) {
wx += tx * (1LL << (32 - z));
wy += ty * (1LL << (32 - z));
}
geom[i].node = is_shared_node(wx, wy, shared_nodes_map, nodepos, shared_nodes_bloom) ? NODE_SHARED : NODE_NOT_SHARED;
}
struct node n;
n.index = encode_vertex((unsigned) d.x, (unsigned) d.y);
size_t bloom_ix = n.index % (shared_nodes_bloom.size() * 8);
unsigned char bloom_mask = 1 << (bloom_ix & 7);
bloom_ix >>= 3;
if (shared_nodes_bloom[bloom_ix] & bloom_mask) {
if (bsearch(&n, shared_nodes_map, nodepos / sizeof(node), sizeof(node), nodecmp) != NULL) {
geom[i].necessary = true;
}
if (geom[i].node == NODE_SHARED) {
geom[i].necessary = true;
}
}
}
+34 -2
View File
@@ -20,6 +20,22 @@
#define VT_LINETO 2
#define VT_CLOSEPATH 7
// Whether a vertex is one of the shared nodes that --no-simplification-of-shared-nodes
// must not simplify away. This is a function only of the vertex's world coordinates,
// so it is found once, before tiling, from the global list of shared nodes, and then
// carried along with the vertex, instead of being looked up again for each tile.
// Vertices that are created during tiling, by clipping or polygon cleaning,
// start out NODE_UNKNOWN and are looked up in the global list if they are simplified.
#define NODE_UNKNOWN 0
#define NODE_NOT_SHARED 1
#define NODE_SHARED 2
// In serialized geometry, the node state is stored in the upper bits
// of the byte that holds each vertex's operation.
#define NODE_SHIFT 4
#define NODE_MASK 3
#define OP_MASK 0x0F
// The bitfield is to make sizeof(draw) be 16 instead of 24
// at the cost, apparently, of a 0.7% increase in running time
// for packing and unpacking.
@@ -28,19 +44,30 @@ struct draw {
signed char op;
long long y : 40;
signed char necessary;
signed char node;
draw(int nop, long long nx, long long ny)
: x(nx),
op(nop),
y(ny),
necessary(0) {
necessary(0),
node(NODE_UNKNOWN) {
}
draw(int nop, long long nx, long long ny, signed char nnode)
: x(nx),
op(nop),
y(ny),
necessary(0),
node(nnode) {
}
draw()
: x(0),
op(0),
y(0),
necessary(0) {
necessary(0),
node(NODE_UNKNOWN) {
}
bool operator<(draw const &s) const {
@@ -64,6 +91,8 @@ struct draw {
}
};
static_assert(sizeof(draw) == 16, "draw should still fit in 16 bytes");
typedef std::vector<draw> drawvec;
struct serial_feature;
@@ -81,6 +110,9 @@ drawvec stairstep(drawvec &geom, int z, int detail);
bool point_within_tile(long long x, long long y, int z);
int quick_check(const long long *bbox, int z, long long buffer);
void douglas_peucker(drawvec &geom, int start, int n, double e, size_t kept, size_t retain, bool prevent_simplify_shared_nodes);
void add_shared_node_to_bloom(std::string &shared_nodes_bloom, unsigned long long index);
bool is_shared_node(long long wx, long long wy, struct node const *shared_nodes_map, size_t nodepos, std::string const &shared_nodes_bloom);
void restore_node_states(drawvec const &from, drawvec &to);
drawvec simplify_lines(drawvec &geom, int z, int tx, int ty, int detail, bool mark_tile_bounds, double simplification, size_t retain, drawvec const &shared_nodes, struct node *shared_nodes_map, size_t nodepos, std::string const &shared_nodes_bloom);
drawvec reorder_lines(const drawvec &geom);
drawvec fix_polygon(const drawvec &geom, bool use_winding, bool reverse_winding);
+186 -7
View File
@@ -1233,6 +1233,140 @@ int vertexcmp(const void *void1, const void *void2) {
return 0;
}
// A range of one reader's geometry, beginning and ending at feature boundaries
struct mark_shared_nodes_range {
int geomfd;
long long start;
long long end;
};
struct mark_shared_nodes_arg {
std::vector<mark_shared_nodes_range> const *ranges;
std::atomic<size_t> *next_range;
unsigned *initial_x;
unsigned *initial_y;
node const *shared_nodes_map;
size_t nodepos;
std::string const *shared_nodes_bloom;
};
// Go through a range of the geometry that a reader serialized, marking each vertex
// with whether it is one of the shared nodes. The features are read in
// chunks and written back in place, since marking doesn't change their size.
static void mark_shared_nodes_in_range(mark_shared_nodes_arg *a, mark_shared_nodes_range const &r, std::string &buf) {
long long pos = r.start;
while (pos < r.end) {
long long want = std::min((long long) buf.size(), r.end - pos);
if (pread(r.geomfd, &buf[0], want, pos) != want) {
fprintf(stderr, "pread(geom): %s\n", strerror(errno));
exit(EXIT_READ);
}
// Mark each feature that is entirely within this chunk
long long used = 0;
while (used < want) {
// a feature length is at most 10 bytes of varint
if (want - used < 10 && pos + want < r.end) {
break;
}
const char *cp = buf.c_str() + used;
long long len;
deserialize_long_long(&cp, &len);
long long flen = (cp - buf.c_str()) - used;
if (used + flen + len > want) {
break;
}
mark_shared_nodes(&buf[0] + used + flen, len, a->initial_x, a->initial_y, a->shared_nodes_map, a->nodepos, *a->shared_nodes_bloom);
used += flen + len;
}
if (used == 0) {
// a single feature is bigger than the buffer
buf.resize(buf.size() * 2);
continue;
}
if (pwrite(r.geomfd, buf.c_str(), used, pos) != used) {
fprintf(stderr, "pwrite(geom): %s\n", strerror(errno));
exit(EXIT_WRITE);
}
pos += used;
}
}
// Each thread takes the next range that hasn't been marked yet, until there are none left
static void *run_mark_shared_nodes(void *v) {
mark_shared_nodes_arg *a = (mark_shared_nodes_arg *) v;
std::string buf;
buf.resize(4 * 1024 * 1024);
while (true) {
size_t which = (*a->next_range)++;
if (which >= a->ranges->size()) {
break;
}
mark_shared_nodes_in_range(a, (*a->ranges)[which], buf);
}
return NULL;
}
// Divide the geometry of all the readers into ranges of about the same size,
// at feature boundaries, which are found from the readers' indexes, so that
// the marking can be spread across all the CPUs even if all the features
// were read by one reader.
static std::vector<mark_shared_nodes_range> mark_shared_nodes_ranges(std::vector<struct reader> &readers) {
long long total = 0;
for (auto &r : readers) {
total += r.geompos;
}
long long target = std::max(total / (long long) (CPUS * 8), 1024LL * 1024);
std::vector<mark_shared_nodes_range> ranges;
for (auto &r : readers) {
long long indexsize = r.indexpos;
if (indexsize == 0) {
continue;
}
struct index *indexmap = (struct index *) mmap(NULL, indexsize, PROT_READ, MAP_PRIVATE, r.indexfd, 0);
if (indexmap == MAP_FAILED) {
perror("mmap index for marking nodes");
exit(EXIT_MEMORY);
}
madvise(indexmap, indexsize, MADV_SEQUENTIAL);
size_t n = indexsize / sizeof(struct index);
long long start = indexmap[0].start;
for (size_t i = 0; i < n; i++) {
if (i + 1 == n || indexmap[i].end - start >= target) {
ranges.push_back(mark_shared_nodes_range{r.geomfd, start, indexmap[i].end});
start = indexmap[i].end;
}
}
if (indexmap[0].start != 0 || indexmap[n - 1].end != r.geompos) {
fprintf(stderr, "Internal error: index covers geometry %lld to %lld, not 0 to %lld\n", indexmap[0].start, indexmap[n - 1].end, (long long) r.geompos);
exit(EXIT_IMPOSSIBLE);
}
if (munmap(indexmap, indexsize) != 0) {
perror("munmap index for marking nodes");
exit(EXIT_MEMORY);
}
}
return ranges;
}
double round_droprate(double r) {
return std::round(r * 100000.0) / 100000.0;
}
@@ -2057,7 +2191,7 @@ std::pair<int, metadata> read_input(std::vector<source> &sources, char *fname, i
#endif
struct node n;
n.index = encode_vertex((unsigned) x, (unsigned) y);
n.index = encode_quadkey((unsigned) x, (unsigned) y);
fwrite_check((char *) &n, sizeof(struct node), 1, readers[0].nodefile, &readers[0].nodepos, "vertices");
}
@@ -2071,8 +2205,8 @@ std::pair<int, metadata> read_input(std::vector<source> &sources, char *fname, i
fprintf(stderr, "Merging nodes \r");
}
// This is sized once the number of nodes is known, below
std::string shared_nodes_bloom;
shared_nodes_bloom.resize(34567891); // circa 34MB, size nowhere near a power of 2
// Sort nodes that can't be simplified away; scan the list to remove duplicates
@@ -2139,11 +2273,6 @@ std::pair<int, metadata> read_input(std::vector<source> &sources, char *fname, i
fwrite_check((void *) &here, sizeof(here), 1, shared_nodes, &nodepos, "shared nodes");
written = here;
size_t bloom_ix = here.index % (shared_nodes_bloom.size() * 8);
unsigned char bloom_mask = 1 << (bloom_ix & 7);
bloom_ix >>= 3;
shared_nodes_bloom[bloom_ix] |= bloom_mask;
#if 0
unsigned wx, wy;
decode_quadkey(here.index, &wx, &wy);
@@ -2162,11 +2291,61 @@ std::pair<int, metadata> read_input(std::vector<source> &sources, char *fname, i
perror("mmap nodes");
exit(EXIT_MEMORY);
}
// Size the Bloom filter at about 16 bits per node, so that for a moderate
// number of nodes it can stay in the cache while it is being checked,
// but no more than 32MB.
size_t nnodes = nodepos / sizeof(node);
size_t bloom_size = std::min(nnodes * 2, (size_t) 32 * 1024 * 1024);
bloom_size = std::max((bloom_size + 7) / 8 * 8, (size_t) 64);
shared_nodes_bloom.resize(bloom_size);
for (size_t i = 0; i < nnodes; i++) {
add_shared_node_to_bloom(shared_nodes_bloom, shared_nodes_map[i].index);
}
}
fclose(node_out);
}
// Mark the vertices of each feature with whether they are shared nodes,
// so that tiling doesn't need to look them up again for every tile.
if (nodepos > 0) {
if (!quiet) {
fprintf(stderr, "Marking nodes \r");
}
std::vector<mark_shared_nodes_range> ranges = mark_shared_nodes_ranges(readers);
std::atomic<size_t> next_range(0);
std::vector<pthread_t> pthreads(CPUS);
std::vector<mark_shared_nodes_arg> args(CPUS);
for (size_t i = 0; i < CPUS; i++) {
args[i].ranges = &ranges;
args[i].next_range = &next_range;
args[i].initial_x = initial_x.data();
args[i].initial_y = initial_y.data();
args[i].shared_nodes_map = shared_nodes_map;
args[i].nodepos = nodepos;
args[i].shared_nodes_bloom = &shared_nodes_bloom;
if (thread_create(&pthreads[i], NULL, run_mark_shared_nodes, &args[i]) != 0) {
perror("pthread_create");
exit(EXIT_PTHREAD);
}
}
for (size_t i = 0; i < CPUS; i++) {
void *retval;
if (pthread_join(pthreads[i], &retval) != 0) {
perror("pthread_join mark nodes");
}
}
}
if (!quiet) {
fprintf(stderr, "Merging index \r");
}
+13 -16
View File
@@ -156,19 +156,20 @@ void decode_hilbert(unsigned long long index, unsigned *wx, unsigned *wy) {
hilbert_d2xy(1LL << 32, index, wx, wy);
}
// Spread the 32 bits of v out into the even bits of a 64-bit value
static inline unsigned long long spread_bits(unsigned int v) {
unsigned long long x = v;
x = (x | (x << 16)) & 0x0000FFFF0000FFFFULL;
x = (x | (x << 8)) & 0x00FF00FF00FF00FFULL;
x = (x | (x << 4)) & 0x0F0F0F0F0F0F0F0FULL;
x = (x | (x << 2)) & 0x3333333333333333ULL;
x = (x | (x << 1)) & 0x5555555555555555ULL;
return x;
}
// Interleave the bits of wx and wy, with each bit of wx above the same bit of wy
unsigned long long encode_quadkey(unsigned int wx, unsigned int wy) {
unsigned long long out = 0;
int i;
for (i = 0; i < 32; i++) {
unsigned long long v = ((wx >> (32 - (i + 1))) & 1) << 1;
v |= (wy >> (32 - (i + 1))) & 1;
v = v << (64 - 2 * (i + 1));
out |= v;
}
return out;
return (spread_bits(wx) << 1) | spread_bits(wy);
}
static std::atomic<unsigned char> decodex[256];
@@ -217,7 +218,3 @@ void set_projection_or_exit(const char *optarg) {
exit(EXIT_ARGS);
}
}
unsigned long long encode_vertex(unsigned int wx, unsigned int wy) {
return (((unsigned long long) wx) << 32) | wy;
}
-1
View File
@@ -26,6 +26,5 @@ void decode_quadkey(unsigned long long index, unsigned *wx, unsigned *wy);
unsigned long long encode_hilbert(unsigned int wx, unsigned int wy);
void decode_hilbert(unsigned long long index, unsigned *wx, unsigned *wy);
unsigned long long encode_vertex(unsigned int wx, unsigned int wy);
#endif
+1 -1
View File
@@ -46,7 +46,7 @@ void json_context(json_object *j) {
std::string s = json_stringify(j);
if (s.size() >= 500) {
s = truncate_string(s, 497);
s.resize(497);
s.append("...");
}
+70 -2
View File
@@ -157,7 +157,7 @@ void deserialize_byte(const char **f, signed char *n) {
static void write_geometry(drawvec const &dv, std::string &out, long long wx, long long wy) {
for (size_t i = 0; i < dv.size(); i++) {
if (dv[i].op == VT_MOVETO || dv[i].op == VT_LINETO) {
serialize_byte(out, dv[i].op);
serialize_byte(out, dv[i].op | (dv[i].node << NODE_SHIFT));
serialize_long_long(out, dv[i].x - wx);
serialize_long_long(out, dv[i].y - wy);
wx = dv[i].x;
@@ -301,6 +301,74 @@ serial_feature deserialize_feature(std::string const &geoms, unsigned z, unsigne
return sf;
}
// Before tiling, mark each vertex of a serialized feature with whether
// it is one of the global shared nodes. This is done in place, by setting
// the node state in the upper bits of the byte that holds each vertex's operation,
// so the feature's length and position don't change.
void mark_shared_nodes(char *feature, size_t len, unsigned *initial_x, unsigned *initial_y, struct node const *shared_nodes_map, size_t nodepos, std::string const &shared_nodes_bloom) {
const char *cp = feature;
signed char t;
deserialize_byte(&cp, &t);
if (t != VT_LINE && t != VT_POLYGON) {
return;
}
long long layer, seq;
deserialize_long_long(&cp, &layer);
deserialize_long_long(&cp, &seq);
if (layer & (1 << FLAG_MINZOOM)) {
int minzoom;
deserialize_int(&cp, &minzoom);
}
if (layer & (1 << FLAG_MAXZOOM)) {
int maxzoom;
deserialize_int(&cp, &maxzoom);
}
if (layer & (1 << FLAG_ID)) {
unsigned long long id;
deserialize_ulong_long(&cp, &id);
}
int segment;
deserialize_int(&cp, &segment);
// the same accumulation as in decode_geometry()
long long wx = initial_x[segment], wy = initial_y[segment];
while (cp < feature + len) {
char *opp = feature + (cp - feature);
signed char op;
deserialize_byte(&cp, &op);
if (op == VT_END) {
return;
}
// the vertex may already have a node state, from clipping to --clip-bounding-box
op &= OP_MASK;
if (op == VT_MOVETO || op == VT_LINETO) {
long long dx, dy;
deserialize_long_long(&cp, &dx);
deserialize_long_long(&cp, &dy);
wx += dx * (1 << geometry_scale);
wy += dy * (1 << geometry_scale);
signed char node = is_shared_node(wx, wy, shared_nodes_map, nodepos, shared_nodes_bloom) ? NODE_SHARED : NODE_NOT_SHARED;
*opp = op | (node << NODE_SHIFT);
} else if (op != VT_CLOSEPATH) {
fprintf(stderr, "Internal error: unexpected geometry operation %d marking shared nodes\n", op);
exit(EXIT_IMPOSSIBLE);
}
}
fprintf(stderr, "Internal error: no end of geometry marking shared nodes\n");
exit(EXIT_IMPOSSIBLE);
}
static long long scale_geometry(struct serialization_state *sst, long long *bbox, drawvec &geom) {
long long offset = 0;
long long prev = 0;
@@ -407,7 +475,7 @@ static void add_scaled_node(struct reader *r, serialization_state *sst, draw g)
long long y = SHIFT_LEFT(g.y);
struct node n;
n.index = encode_vertex((unsigned) x, (unsigned) y);
n.index = encode_quadkey((unsigned) x, (unsigned) y);
fwrite_check((char *) &n, sizeof(struct node), 1, r->nodefile, &r->nodepos, sst->fname);
}
+1
View File
@@ -321,6 +321,7 @@ struct node {
};
int nodecmp(const void *void1, const void *void2);
void mark_shared_nodes(char *feature, size_t len, unsigned *initial_x, unsigned *initial_y, struct node const *shared_nodes_map, size_t nodepos, std::string const &shared_nodes_bloom);
int serialize_feature(struct serialization_state *sst, serial_feature &sf, std::string const &layername);
void coerce_value(std::string const &key, int &vt, std::string &val, std::unordered_map<std::string, int> const *attribute_types);
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+6 -3
View File
@@ -476,7 +476,7 @@ static void rewrite(serial_feature const &osf, int z, int nextzoom, int maxzoom,
drawvec geom2;
for (auto const &g : osf.geometry) {
geom2.emplace_back(g.op, SHIFT_RIGHT(g.x + sx), SHIFT_RIGHT(g.y + sy));
geom2.emplace_back(g.op, SHIFT_RIGHT(g.x + sx), SHIFT_RIGHT(g.y + sy), g.node);
}
for (xo = bbox2[0]; xo <= bbox2[2]; xo++) {
@@ -631,7 +631,9 @@ static double simplify_feature(serial_feature *p, drawvec const &shared_nodes, n
// unioned exactly
//
// don't try to scale up because these are still world coordinates
drawvec before = geom;
coalesce_polygon(geom, false);
restore_node_states(before, geom);
}
// continues to simplify to line_detail even if we have extra detail
@@ -979,13 +981,13 @@ static bool clip_to_tile(serial_feature &sf, int z, long long buffer) {
if (sf.bbox[0] <= (1LL << 32) * buffer / 256) {
for (size_t i = 0; i < n; i++) {
sf.geometry.push_back(draw(sf.geometry[i].op, sf.geometry[i].x + (1LL << 32), sf.geometry[i].y));
sf.geometry.push_back(draw(sf.geometry[i].op, sf.geometry[i].x + (1LL << 32), sf.geometry[i].y, sf.geometry[i].node));
}
}
if (sf.bbox[2] >= (1LL << 32) - ((1LL << 32) * buffer / 256)) {
for (size_t i = 0; i < n; i++) {
sf.geometry.push_back(draw(sf.geometry[i].op, sf.geometry[i].x - (1LL << 32), sf.geometry[i].y));
sf.geometry.push_back(draw(sf.geometry[i].op, sf.geometry[i].x - (1LL << 32), sf.geometry[i].y, sf.geometry[i].node));
}
}
@@ -2295,6 +2297,7 @@ long long write_tile(decompressor *geoms, std::atomic<long long> *geompos_in, ch
// don't scale up because this is still world coordinates
coalesce_polygon(to_clean, false);
restore_node_states(features[simplified_geometry_through]->geometry, to_clean);
features[simplified_geometry_through]->geometry = std::move(to_clean);
}
}
+37
View File
@@ -129,6 +129,43 @@ TEST_CASE("Bit reversal", "bit reversal") {
REQUIRE(bit_reverse(0xF3D912481E6A2C48) == 0x1234567812489BCF);
}
// The bit-at-a-time quadkey encoding that encode_quadkey() used to use
static unsigned long long reference_quadkey(unsigned int wx, unsigned int wy) {
unsigned long long out = 0;
for (int i = 0; i < 32; i++) {
unsigned long long v = ((wx >> (32 - (i + 1))) & 1) << 1;
v |= (wy >> (32 - (i + 1))) & 1;
v = v << (64 - 2 * (i + 1));
out |= v;
}
return out;
}
TEST_CASE("Quadkey encoding", "[projection]") {
unsigned int values[] = {0, 1, 2, 0x7FFFFFFF, 0x80000000, 0xFFFFFFFF, 0x12345678, 0xDEADBEEF};
for (unsigned int x : values) {
for (unsigned int y : values) {
REQUIRE(encode_quadkey(x, y) == reference_quadkey(x, y));
unsigned wx, wy;
decode_quadkey(encode_quadkey(x, y), &wx, &wy);
REQUIRE(wx == x);
REQUIRE(wy == y);
}
}
unsigned long long seed = 1;
for (size_t i = 0; i < 10000; i++) {
seed = seed * 6364136223846793005ULL + 1442695040888963407ULL;
unsigned int x = seed >> 32;
unsigned int y = seed;
REQUIRE(encode_quadkey(x, y) == reference_quadkey(x, y));
}
}
TEST_CASE("line_is_too_small") {
drawvec dv;
dv.emplace_back(VT_MOVETO, 4243099709, 2683872952);
+1 -1
View File
@@ -1,6 +1,6 @@
#ifndef VERSION_HPP
#define VERSION_HPP
#define VERSION "v2.82.0"
#define VERSION "v2.83.0"
#endif