Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ else ifeq ($(TM_GIT_TAG)$(TM_GIT_DIRTY),$(TM_BASE_VERSION))
else
TM_VERSION ?= $(TM_BASE_VERSION)+g$(TM_GIT_SHA)$(TM_GIT_DIRTY)
endif
CXXFLAGS ?= -O3 -Wall -Wno-unknown-pragmas -Wno-sign-compare -std=c++14 -pthread -fPIE -DTM_VERSION=$(TM_VERSION) $(CONFIG)
CXXFLAGS ?= -O3 -Wall -Wno-unknown-pragmas -Wno-sign-compare -std=c++17 -pthread -fPIE -DTM_VERSION=$(TM_VERSION) $(CONFIG)
CFLAGS ?= -O3 -Wall -Wno-unknown-pragmas -Wno-sign-compare -std=c99 -fPIE -DTM_VERSION=$(TM_VERSION) $(CONFIG)
DEPFLAGS := -MD -MP
DEPS := $(wildcard src/*.d src/external/*.d src/external/libdeflate/lib/*.d src/external/libdeflate/lib/*/*.d server/*.d test/*.d)
Expand Down Expand Up @@ -197,6 +197,7 @@ src/config_schema.h: resources/config-schema.json
src/config_validator.o: src/config_schema.h

test_correct: \
src/geom.o \
test/correct.test.o
$(CXX) $(CXXFLAGS) -o test.correct $^ $(INC) $(LIB) $(LDFLAGS) && ./test.correct

Expand Down
15 changes: 15 additions & 0 deletions docs/CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,8 @@ To do that, you use these methods:
* `MinZoom(zoom)`: set the minimum zoom level (0-15) at which this object will be written. Note that the JSON layer configuration minimum still applies (so `:MinZoom(5)` will have no effect if your layer only starts at z6).
* `Score(number)`: set how important this point feature is (a whole number; anything else is rounded down), so that tilemaker can decide which zoom level to show it from. Only meaningful for points (i.e. features written with `Layer` for a node, or `LayerAsCentroid`) in a layer with `declutter_below` set - see 'Decluttering point features' below.
* `Length()` and `Area()`: return the length (metres)/area (square metres) of the current object. Requires Boost 1.67+.
* `MercatorArea()`: return the area of the current object on the Web Mercator plane, in square metres at the scale of the equator (so it grows towards the poles, as the map does). It is cheap to compute and tells how much of a tile the object covers, which makes it the right measure for minimum zoom rules.
* `MinZoomByArea(limit, thresholds)`: set the minimum zoom of the current object from its `MercatorArea()`: the first zoom z from `limit` on whose threshold the area exceeds, where `thresholds` lists the thresholds for zoom 1, 2, 3...; if there is none, one more than the number of thresholds. Unlike the same rule written in Lua with `MercatorArea()`, this keeps `way_function` replayable (see `way_memo` above).
* `Centroid()`: return the lat/lon of the centre of the current object as a two-element Lua table (element 1 is lat, 2 is lon).

The simplest possible function, to include roads/paths and nothing else, might look like this:
Expand Down Expand Up @@ -238,6 +240,19 @@ If your Lua file causes an error due to mistaken syntax, you can test it at the

`way_keys` is similar, but for ways. For ways, you may also wish to express the filter in terms of the tag value, or as an inversion. For example, to exclude buildings: `way_keys = {"~building"}`. To build a map only of major roads: `way_keys = {"highway=motorway", "highway=trunk", "highway=primary", "highway=secondary"}`

`way_memo = true` lets tilemaker replay `way_function` instead of running it, for ways that read the same as an earlier way. This is only allowed if `way_function` is a function of what it reads with `Find`, `Holds`, `IsClosed` and `NextRelation` (no other state, such as global counters), and what it does is call tilemaker's functions (`Layer`, `Attribute`... `MinZoom`): tilemaker records which reads lead to which calls, and replays the calls for a way whose reads give the same results. Anything else (geometry queries such as `Area`, relation tags, `Id`...) makes ways with those reads run through Lua. A tag whose value is only tested for being empty and copied unchanged into some attributes can be declared in `way_memo_values`, e.g. `way_memo_values = { name = { "name:latin" } }`: ways are then replayed with their own value of the tag, instead of being told apart by it. A tag whose value is compared with another tag's value (e.g. `name` with `name:de`) must not be declared, as the memo only tells its values apart by being empty or not. An attribute that is set to the length of the value (in bytes, as Lua's `#value` or `value:len()`) is declared as `attribute = "length"`, e.g. `way_memo_values = { ref = { "ref", ref_length = "length" } }`.

Two more declarations let the memo replay ways that use some of the other functions:

* `way_memo_area = { 1000, 5000 }`: `way_function` uses `MercatorArea()` only to compare it (`<`, `<=`, `>`, `>=`, `==`, `~=`) with these numbers. The memo then tells ways apart by the results of these comparisons, not by the area (e.g. `if MercatorArea() < 1000 then MinZoom(8) else MinZoomByArea(0, thresholds) end`; `MinZoomByArea` needs no declaration, it is worked out for each way).
* `way_memo_relations = true`: `way_function` uses the relation id `NextRelation()` returns only to test whether there is one (`if not rel then break end`), and reads the relations' tags only with `FindInRelation` (no `RestartRelations`). The memo then tells ways apart by the roles and the relation tags read.

As with `way_memo_values`, tilemaker can't check these promises: if `way_function` does more with the area or the relations, ways are replayed with the wrong calls.

Multipolygon relations, which also run `way_function`, are replayed the same way (with a record of their own, apart from that of the ways): the promises above are about `way_function`, so they hold for them too. For a multipolygon, `NextRelation` and `FindInRelation` are about the relations it is a member of.

`node_memo = true` and `node_memo_values`, `node_memo_area`, `node_memo_relations` do the same for `node_function` (with its own record).

`init_function(name, is_first)` and `exit_function` are called at the start and end of processing (once per thread). You can use this to output statistics or even to read a small amount of external data. `is_first` will be true only the first time `init_function` is called.

Other functions are described below and in RELATIONS.md.
Expand Down
17 changes: 17 additions & 0 deletions include/append_vector.h
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#define _APPEND_VECTOR_H

#include "mmap_allocator.h"
#include <algorithm>
#include <vector>
#include <queue>
#include <cstdint>
Expand Down Expand Up @@ -188,6 +189,22 @@ namespace AppendVectorNS {
count++;
}

// The same as push_back of each of p[0, n)
void append(const T* p, size_t n) {
while (n > 0) {
auto& vec = vecs.back();
if (vec.capacity() == 0)
vec.reserve(APPEND_VECTOR_SIZE);
const size_t take = std::min(n, vec.capacity() - vec.size());
vec.insert(vec.end(), p, p + take);
p += take; n -= take; count += take;
if (vec.size() == vec.capacity()) {
vecs.push_back(std::vector<T, mmap_allocator<T>>());
vecs.back().reserve(APPEND_VECTOR_SIZE);
}
}
}

size_t count;
std::deque<std::vector<T, mmap_allocator<T>>> vecs;
};
Expand Down
31 changes: 29 additions & 2 deletions include/attribute_store.h
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
#include <boost/container/flat_map.hpp>
#include <boost/container/small_vector.hpp>
#include <algorithm>
#include <cstring>
#include <vector>
#include <protozero/data_view.hpp>
#include "pooled_string.h"
Expand Down Expand Up @@ -159,14 +160,29 @@ struct AttributePair {
return true;
}

// Hashes the string 8 bytes at a time (the hash only picks shards and hash table slots)
static uint64_t hashBytes(uint64_t h, const char* p, size_t n) {
h ^= n * 0x9E3779B97F4A7C15ULL;
while (n >= 8) {
uint64_t w; memcpy(&w, p, 8);
h = (h ^ w) * 0xff51afd7ed558ccdULL; h ^= h >> 32;
p += 8; n -= 8;
}
if (n > 0) {
uint64_t w = 0; memcpy(&w, p, n);
h = (h ^ w) * 0xc4ceb9fe1a85ec53ULL; h ^= h >> 29;
}
h *= 0x94d049bb133111ebULL; h ^= h >> 31;
return h;
}

size_t hash() const {
std::size_t rv = minzoom;
boost::hash_combine(rv, keyIndex);
boost::hash_combine(rv, valueType);

if(hasStringValue()) {
const char* data = pooledString().data();
boost::hash_range(rv, data, data + pooledString().size());
rv = hashBytes(rv, pooledString().data(), pooledString().size());
} else if(hasFloatValue())
boost::hash_combine(rv, doubleValue_);
else if(hasIntValue())
Expand Down Expand Up @@ -223,6 +239,9 @@ class AttributePairStore {
friend class AttributeStore;
std::vector<DequeMap<AttributePair>> pairs;
bool finalized;
// Set (under its lock) once the hot shard is full: from then on it never changes, so it is
// looked up without the lock
std::atomic<bool> hotFull{false};
// We refer to all attribute pairs by index.
//
// Each shard is responsible for a portion of the key space.
Expand Down Expand Up @@ -478,6 +497,14 @@ struct AttributeStore {
void addAttributeWithKeyIndex(AttributeSet& attributeSet, uint16_t keyIndex, double v, char minzoom);
void addAttributeWithKeyIndex(AttributeSet& attributeSet, uint16_t keyIndex, int v, char minzoom);
void addAttributeWithKeyIndex(AttributeSet& attributeSet, uint16_t keyIndex, bool v, char minzoom);
// The pair index that addAttributeWithKeyIndex adds to the set. It is the same for the same
// arguments for as long as the store lives, so callers may keep it.
uint32_t pairIndexWithKeyIndex(uint16_t keyIndex, std::string const &key, const protozero::data_view v, char minzoom);
uint32_t pairIndexWithKeyIndex(uint16_t keyIndex, double v, char minzoom);
uint32_t pairIndexWithKeyIndex(uint16_t keyIndex, int v, char minzoom);
uint32_t pairIndexWithKeyIndex(uint16_t keyIndex, bool v, char minzoom);
// Counts an object whose AttributeIndex the caller knew without add() (for reportSize)
void noteLookup();

AttributeStore():
finalized(false),
Expand Down
164 changes: 164 additions & 0 deletions include/clip_line.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
/*! \file */
#ifndef _CLIP_LINE_H
#define _CLIP_LINE_H

#include <cmath>
#include <cstdint>
#include "geom.h"
#ifdef __SSE2__
#include <emmintrin.h>
#endif

// buildWayGeometry for a linestring: splits `ls` into the runs of segments that intersect
// clippingBox (appended to `out`), and returns whether any point lies outside extBox (then the
// caller intersects the result with extBox).
//
// Reference version: a segment with both ends within the closed clippingBox always intersects
// it (Boost's cartesian segment/box disjoint test then sees t ranges that contain the whole
// segment in both dimensions: every ti_min <= 0 <= ti_max, diff >= 0), so Boost isn't called for
// those. Every other segment is tested with boost::geometry::intersects.
template<class LS>
bool split_linestring_for_tile_reference(const LS &ls, Box const &clippingBox, Box const &extBox, MultiLinestring &out) {
const double minX = extBox.min_corner().x(), maxX = extBox.max_corner().x();
const double minY = extBox.min_corner().y(), maxY = extBox.max_corner().y();
auto pointInsideExtBox = [minX, maxX, minY, maxY](const Point& p) {
return p.x() >= minX && p.x() <= maxX && p.y() >= minY && p.y() <= maxY;
};
const double cx0 = clippingBox.min_corner().x(), cx1 = clippingBox.max_corner().x();
const double cy0 = clippingBox.min_corner().y(), cy1 = clippingBox.max_corner().y();
auto coveredByClip = [cx0, cx1, cy0, cy1](const Point& p) {
return p.x() >= cx0 && p.x() <= cx1 && p.y() >= cy0 && p.y() <= cy1;
};
bool needsIntersection = !pointInsideExtBox(ls[0]);

Linestring current_ls;
current_ls.push_back(ls[0]);

bool prevCovered = coveredByClip(ls[0]);
for (size_t i = 1; i < ls.size(); ++i) {
const bool covered = coveredByClip(ls[i]);
if (!(prevCovered && covered)) {
boost::geometry::model::segment<Point> segment(ls[i-1], ls[i]);
if (!boost::geometry::intersects(segment, clippingBox)) {
if (current_ls.size() > 1)
out.push_back(std::move(current_ls));
current_ls.clear();
}
}
prevCovered = covered;
current_ls.push_back(ls[i]);
if (!needsIntersection)
needsIntersection = !pointInsideExtBox(ls[i]);
}

if (current_ls.size() > 1)
out.push_back(std::move(current_ls));
return needsIntersection;
}

// Fast version, same result. Per point, one SSE2 pass computes whether it is within the closed
// clippingBox / extBox and on which sides it lies more than M outside clippingBox. A segment
// then
// - continues the run if both ends are within clippingBox (as in the reference);
// - ends it if both ends are more than M left (right) of the box: Boost's x step returns
// disjoint. With the ends left, either p1 >= p0 and fl(x0 - p0) > fl(p1 - p0) (the exact
// values differ by x0 - p1 > M, far more than their rounding errors), or p1 < p0 and
// fl(p0 - x0) < 0. Neither value is near enough to 0 for the diff ~ 0 branch to replace it.
// Right: symmetric;
// - ends it if both ends are more than M below (above) the box, and the x extent s = |p1x - p0x|
// (as Boost computes it) is either exactly 0 or at least D: if the x step passes
// (t_min.first <= s, t_max.first >= 0), the y step either returns disjoint at once or updates
// t_min to (ti_min, dy) with ti_min > dy (below, p1y >= p0y: the products ti_min*s and
// t_min.first*dy differ by at least M*s, more than their relative rounding errors), resp.
// t_max to (ti_max, dy) with ti_max < 0 (below, p1y < p0y: ti_max*s < 0 <= t_max.first*dy,
// no underflow as s >= D), and then returns disjoint. With s exactly 0, the x step leaves
// t_min.first < 0 < t_max.first (it replaces values ~0 by -1/1), and the same updates
// happen. Above: symmetric;
// - is tested with boost::geometry::intersects otherwise, as in the reference.
// The margins need bounded coordinates (|c| <= BOUND); if the box or any point (NaN included)
// isn't, the reference version runs instead. Each run is copied into its part in one go (only
// the capacity of the parts differs from appending point by point).
namespace clip_line_detail {
constexpr double M = 1e-9, D = 1e-12, BOUND = 1000.0;
}

template<class LS>
bool split_linestring_for_tile(const LS &ls, Box const &clippingBox, Box const &extBox, MultiLinestring &out) {
#ifdef __SSE2__
using namespace clip_line_detail;
const size_t n = ls.size();
const double cx0 = clippingBox.min_corner().x(), cx1 = clippingBox.max_corner().x();
const double cy0 = clippingBox.min_corner().y(), cy1 = clippingBox.max_corner().y();
if (!(std::fabs(cx0) <= BOUND && std::fabs(cx1) <= BOUND && std::fabs(cy0) <= BOUND && std::fabs(cy1) <= BOUND))
return split_linestring_for_tile_reference(ls, clippingBox, extBox, out);
const size_t outSize = out.size();

const __m128d cmin = _mm_set_pd(cy0, cx0), cmax = _mm_set_pd(cy1, cx1);
const __m128d emin = _mm_set_pd(extBox.min_corner().y(), extBox.min_corner().x());
const __m128d emax = _mm_set_pd(extBox.max_corner().y(), extBox.max_corner().x());
const __m128d smin = _mm_set_pd(cy0 - M, cx0 - M), smax = _mm_set_pd(cy1 + M, cx1 + M);
const __m128d absMask = _mm_castsi128_pd(_mm_set1_epi64x(0x7fffffffffffffffLL)), bound = _mm_set1_pd(BOUND);
__m128d bounded = _mm_castsi128_pd(_mm_set1_epi32(-1));
// code bits (two per compare): 0-3 within clippingBox (x, y), 4-7 within extBox, 8-9 left,
// 10-11 below, 12-13 right, 14-15 above
auto code = [&](const Point &p) -> unsigned {
const __m128d v = _mm_loadu_pd(reinterpret_cast<const double*>(&p));
bounded = _mm_and_pd(bounded, _mm_cmple_pd(_mm_and_pd(v, absMask), bound));
const __m128i in = _mm_castpd_si128(_mm_and_pd(_mm_cmpge_pd(v, cmin), _mm_cmple_pd(v, cmax)));
const __m128i inExt = _mm_castpd_si128(_mm_and_pd(_mm_cmpge_pd(v, emin), _mm_cmple_pd(v, emax)));
const __m128i lo = _mm_castpd_si128(_mm_cmplt_pd(v, smin)), hi = _mm_castpd_si128(_mm_cmpgt_pd(v, smax));
return unsigned(_mm_movemask_epi8(_mm_packs_epi16(_mm_packs_epi32(in, inExt), _mm_packs_epi32(lo, hi))));
};
constexpr unsigned C_COV = 0xf, C_EXT = 0xf0, C_LR = 0x100 | 0x1000, C_BT = 0x400 | 0x4000;

unsigned prev = code(ls[0]);
unsigned all = prev;
size_t start = 0;
for (size_t i = 1; i < n; ++i) {
const unsigned cur = code(ls[i]);
all &= cur;
const unsigned both = prev & cur;
prev = cur;
if ((both & C_COV) == C_COV) continue;
if (!(both & C_LR)) {
bool sure = false;
if (both & C_BT) {
const double x0 = ls[i-1].x(), x1 = ls[i].x();
const double s = x1 >= x0 ? x1 - x0 : x0 - x1;
sure = s == 0 || s >= D;
}
if (!sure && boost::geometry::intersects(boost::geometry::model::segment<Point>(ls[i-1], ls[i]), clippingBox))
continue;
}
// segment (i-1, i) doesn't intersect the box: the run so far ends at i-1
if (i - 1 > start)
out.emplace_back(ls.begin() + start, ls.begin() + i);
start = i;
}
if (_mm_movemask_pd(bounded) != 3) {
// a point out of range (or NaN): the shortcuts may not match Boost
out.resize(outSize);
return split_linestring_for_tile_reference(ls, clippingBox, extBox, out);
}
if (n - 1 > start)
out.emplace_back(ls.begin() + start, ls.end());
return (all & C_EXT) != C_EXT;
#else
return split_linestring_for_tile_reference(ls, clippingBox, extBox, out);
#endif
}

// buildWayGeometry LINESTRING_: the parts of `ls` for the tile
template<class LS>
MultiLinestring clip_linestring_for_tile(const LS &ls, Box const &clippingBox, Box const &extBox) {
MultiLinestring out;
if (ls.empty())
return out;
if (!split_linestring_for_tile(ls, clippingBox, extBox, out))
return out;
MultiLinestring result;
boost::geometry::intersection(out, extBox, result);
return result;
}

#endif //_CLIP_LINE_H
3 changes: 3 additions & 0 deletions include/coordinates.h
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,9 @@ constexpr double MinLatp = -MaxLatp;
// (if calling with raw coords, remember to divide/multiply by 10000000.0)
double lat2latp(double lat);
double latp2lat(double latp);
// int(lat2latp(lat / 1e7) * 1e7) for a latitude in 1e-7 degrees (as read from .osm.pbf), exactly
// the same value, fast (see coordinates.cpp)
int32_t lat2latpE7(int32_t lat);

// Tile conversions
double lon2tilexf(double lon, uint8_t z);
Expand Down
2 changes: 2 additions & 0 deletions include/coordinates_geom.h
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ class TileBbox {
TileBbox(TileCoordinates i, uint z, bool h, bool e);

std::pair<int,int> scaleLatpLon(double latp, double lon) const;
// scaleLatpLon() of every point of a line, without points repeating their predecessor
void scaleLine(std::vector<std::pair<int,int>> &dst, Linestring const &src) const;
void scaleRing(Ring &dst, Ring const &src) const;
Ring scaleRing(Ring const &src) const;
void scaleRingNoBacktrack(Ring &dst, Ring const &src) const;
Expand Down
Loading
Loading