Skip to content
Merged
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
1 change: 1 addition & 0 deletions docs/CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ You can add optional parameters to layers:
* `simplify_length` - how much to simplify features (in kilometers) on the zoom level `simplify_below-1`, preceding `simplify_level`
* `simplify_ratio` - (optional: the default value is 2.0) the actual simplify level will be `simplify_level * pow(simplify_ratio, (simplify_below-1) - <current zoom>)`
* `simplify_algorithm` - which simplification algorithm to use (defaults to Douglas-Peucker; you can also specify `"visvalingam"`, which can be better for landuse and similar polygons, or `"buildings"`, which preserves rectilinear shapes)
* `repair_polygons` - also repair invalid polygons that were not simplified (defaults to `false`). Polygons that simplification may have broken are always repaired; with `true`, polygons that were merely clipped and quantised onto the integer tile grid are repaired as well. Use it for layers built from large clipped polygons such as coastline/ocean shapefiles, whose tiles are otherwise written out invalid and can be mis-rendered by strict renderers. For those, a repair is only accepted if it preserves the polygon's area, so it can never fill a hole and make an island disappear.
* `filter_below` - filter areas by minimum size below this zoom level
* `filter_area` - minimum size (in square degrees of longitude) for the zoom level `filter_below-1`
* `feature_limit` - restrict the number of features written to each tile
Expand Down
10 changes: 9 additions & 1 deletion include/geom.h
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,15 @@ void make_valid(MultiPolygon &mp);
// best-effort input so callers never regress. If wholeValid is given, it is set
// to true only if mp as a whole is known to pass geom::is_valid afterwards (a true
// result alone can leave individually valid polygons that overlap each other).
bool repair_multi_polygon(MultiPolygon &mp, bool knownInvalid = false, bool *wholeValid = nullptr);
//
// AreaBound::Strict additionally rejects any repair that GROWS a polygon, i.e.
// that filled a hole. Use it for geometry that was not simplified: such geometry
// is only invalid because of the integer quantisation onto the tile grid, so a
// correct repair must not change its area. Simplified geometry legitimately
// changes area and must keep the lenient bound. A scoped enum rather than a bool,
// so that neither a bool nor a pointer argument can be passed for it by mistake.
enum class AreaBound { Lenient, Strict };
bool repair_multi_polygon(MultiPolygon &mp, bool knownInvalid = false, bool *wholeValid = nullptr, AreaBound areaBound = AreaBound::Lenient);

void union_many(std::vector<MultiPolygon> &mps);

Expand Down
7 changes: 7 additions & 0 deletions include/shared_data.h
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,13 @@ struct LayerDef {
uint declutterBelow = 0; // zoom below which point features are thinned out by Score()
double declutterDistance = 40; // how far apart (in 256px screen pixels) they should be kept
double declutterThreshold = 0; // score needed at the layer's minzoom (halves at each zoom)
// Geometry repair: also set after addLayer().
// Polygons that simplification may have broken are always repaired. With
// repairPolygons, polygons that were merely clipped and quantised onto the
// integer tile grid (e.g. ocean shapefiles) are repaired too. For those, a
// repair must not GROW the polygon, because growing means a hole was filled
// and an island would silently disappear.
bool repairPolygons = false;

const bool useColumn(std::string &col) {
return allSourceColumns || (std::find(sourceColumns.begin(), sourceColumns.end(), col) != sourceColumns.end());
Expand Down
4 changes: 2 additions & 2 deletions resources/config-openmaptiles.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@

"building": { "minzoom": 13, "maxzoom": 14 },

"water": { "minzoom": 6, "maxzoom": 14, "simplify_below": 12, "simplify_level": 0.0003, "simplify_algorithm": "visvalingam" },
"ocean": { "minzoom": 0, "maxzoom": 14, "source": "coastline/water_polygons.shp", "filter_below": 12, "filter_area": 0.5, "simplify_below": 13, "simplify_level": 0.0001, "simplify_algorithm": "visvalingam", "write_to": "water" },
"water": { "minzoom": 6, "maxzoom": 14, "simplify_below": 12, "simplify_level": 0.0003, "simplify_algorithm": "visvalingam", "repair_polygons": true },
"ocean": { "minzoom": 0, "maxzoom": 14, "source": "coastline/water_polygons.shp", "filter_below": 12, "filter_area": 0.5, "simplify_below": 13, "simplify_level": 0.0001, "simplify_algorithm": "visvalingam", "repair_polygons": true, "write_to": "water" },
"water_name": { "minzoom": 14, "maxzoom": 14 },
"water_name_detail": { "minzoom": 14, "maxzoom": 14, "write_to": "water_name" },

Expand Down
1 change: 1 addition & 0 deletions resources/config-schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@
"combine_polygons_below": { "type": "integer", "minimum": 0 },
"z_order_ascending": { "type": "boolean" },
"simplify_algorithm": { "type": "string" },
"repair_polygons": { "type": "boolean" },
"source": { "type": "string" },
"source_columns": {
"oneOf": [
Expand Down
47 changes: 34 additions & 13 deletions src/geom.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#include <boost/geometry/strategies/buffer.hpp>

#include "geometry/correct.hpp"
#include <limits>

#include <algorithm>
#include <cmath>
Expand Down Expand Up @@ -485,9 +486,22 @@ bool multiPolygonDefinitelyValid(const MultiPolygon &mp) {

// Repair a single (possibly invalid) polygon in an area-preserving way and
// append the resulting valid polygon(s) to `out`. Returns true on success.
// `minArea` is the lower bound on the repaired area we are willing to accept.
static bool repair_one_polygon(const Polygon &p, double minArea, MultiPolygon &out)
// A repair is only accepted if the resulting area stays within
// [minArea, maxArea]:
// - the LOWER bound catches a collapse (dissolve/buffer dropping most of the
// covered area on huge inputs);
// - the UPPER bound catches a FILLED HOLE, which is what used to make an ocean
// polygon swallow a whole island. Measured on real data, the separation is
// large: genuine repairs of quantised ocean polygons change the area by
// <=0.01 %, whereas filling one island hole grew it by 32 %.
static bool repair_one_polygon(const Polygon &p, double minArea, double maxArea, MultiPolygon &out)
{
auto acceptable = [&](const MultiPolygon &candidate) {
if (!geom::is_valid(candidate)) return false;
const double a = std::abs(geom::area(candidate));
return a >= minArea && a <= maxArea;
};

// 0) Fast path: a ring without holes whose only fault is its orientation
// (e.g. after the y-flip into tile coordinates). On such a simple ring the
// dissolve finds no intersections and just reverses it, so do that directly.
Expand All @@ -496,7 +510,7 @@ static bool repair_one_polygon(const Polygon &p, double minArea, MultiPolygon &o
std::reverse(rev.outer().begin(), rev.outer().end());
const double revArea = std::abs(geom::area(rev));
bool revValid = false;
if (revArea > 1E-12 && revArea >= minArea) {
if (revArea > 1E-12 && revArea >= minArea && revArea <= maxArea) {
const bool pre = polygonDefinitelyValid(rev);
revValid = pre || geom::is_valid(rev);
}
Expand All @@ -510,7 +524,7 @@ static bool repair_one_polygon(const Polygon &p, double minArea, MultiPolygon &o
try {
MultiPolygon fixed;
geometry::correct(p, fixed, 1E-12);
if (geom::is_valid(fixed) && std::abs(geom::area(fixed)) >= minArea) {
if (acceptable(fixed)) {
for (auto &fp : fixed) out.push_back(std::move(fp));
return true;
}
Expand All @@ -529,7 +543,7 @@ static bool repair_one_polygon(const Polygon &p, double minArea, MultiPolygon &o

geom::buffer(p, buffered, distanceStrategy, sideStrategy, joinStrategy, endStrategy, pointStrategy);
geom::correct(buffered);
if (geom::is_valid(buffered) && std::abs(geom::area(buffered)) >= minArea) {
if (acceptable(buffered)) {
for (auto &bp : buffered) out.push_back(std::move(bp));
return true;
}
Expand All @@ -540,7 +554,7 @@ static bool repair_one_polygon(const Polygon &p, double minArea, MultiPolygon &o
return false;
}

bool repair_multi_polygon(MultiPolygon &mp, bool knownInvalid, bool *wholeValid)
bool repair_multi_polygon(MultiPolygon &mp, bool knownInvalid, bool *wholeValid, AreaBound areaBound)
{
if (wholeValid) *wholeValid = false;
if (!knownInvalid) {
Expand Down Expand Up @@ -574,13 +588,20 @@ bool repair_multi_polygon(MultiPolygon &mp, bool knownInvalid, bool *wholeValid)
continue;
}
}
// Lenient threshold: resolving a self-intersection legitimately changes a
// single polygon's (shoelace) area, so anything down to half the original
// is accepted. Per-polygon repair cannot trigger the cross-polygon union
// that previously caused the catastrophic ~99% collapse, so this only
// rejects a genuine local collapse.
const double minArea = 0.5 * std::abs(geom::area(p));
if (!repair_one_polygon(p, minArea, out)) {
// Lenient lower bound: resolving a self-intersection legitimately changes
// a single polygon's (shoelace) area, so anything down to half the
// original is accepted. Per-polygon repair cannot trigger the
// cross-polygon union that previously caused the catastrophic ~99%
// collapse, so this only rejects a genuine local collapse.
// The upper bound is only applied with AreaBound::Strict, i.e. for geometry
// that was not simplified. Applying it to simplified geometry would be
// wrong: it rejects legitimate repairs there and measurably made things
// worse (5 -> 20 invalid features in one tile).
const double origArea = std::abs(geom::area(p));
const double maxArea = areaBound == AreaBound::Strict
? 1.01 * origArea
: std::numeric_limits<double>::infinity();
if (!repair_one_polygon(p, 0.5 * origArea, maxArea, out)) {
out.push_back(p);
allValid = false;
}
Expand Down
5 changes: 5 additions & 0 deletions src/shared_data.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,11 @@ void Config::readConfig(rapidjson::Document &jsonConfig, bool &hasClippingBox, B
source, sourceColumns, allSourceColumns, indexed, indexName,
writeTo);

// Also repair clipped-and-quantised geometry such as ocean shapefiles,
// which is otherwise written out invalid
if (it->value.HasMember("repair_polygons"))
layers.layers[layerNum].repairPolygons = it->value["repair_polygons"].GetBool();

// Decluttering (thinning out point features by the score their profile gives them)
if (it->value.HasMember("declutter_below")) {
LayerDef &layerDef = layers.layers[layerNum];
Expand Down
28 changes: 19 additions & 9 deletions src/tile_worker.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,7 @@ void writeMultiPolygon(
unsigned zoom,
double simplifyLevel,
unsigned simplifyAlgo,
bool repairPolygons,
const MultiPolygon& mp,
MvtAttributeMemo* attrMemo
) {
Expand Down Expand Up @@ -284,8 +285,18 @@ void writeMultiPolygon(
geom::correct(current);


// Simplification can turn a valid input into a self-intersecting/spiky one;
// such polygons are silently dropped by many renderers (missing features), so
// those are always repaired. Geometry that was NOT simplified is only invalid
// because of the integer quantisation onto the tile grid; repairing that as
// well is opt-in per layer ("repair_polygons": true), and uses
// the strict area guard so a repair can never fill a hole and hide an island.
// The validity check below is only worth its cost when a repair can follow,
// so it must include the opt-in - otherwise the option would never trigger.
const bool mayRepair = (simplifyLevel > 0 || repairPolygons);

geom::validity_failure_type failure;
if (!knownPolygonsValid && (simplifyLevel > 0 || verbose) && !geom::is_valid(current, failure)) {
if (!knownPolygonsValid && (mayRepair || verbose) && !geom::is_valid(current, failure)) {
if (verbose) {
cout << "output multipolygon has " << boost_validity_error(failure) << endl;

Expand All @@ -294,12 +305,10 @@ void writeMultiPolygon(
else
cout << "input multipolygon valid" << endl;
}

if (simplifyLevel > 0) {
// Simplification can turn a valid input into a self-intersecting/spiky
// one; such polygons are silently dropped by many renderers (missing
// features). Repair (dissolve, then zero-width buffer) before writing.
bool repaired = repair_multi_polygon(current, true); // already known invalid

if (mayRepair) {
bool repaired = repair_multi_polygon(current, /*knownInvalid=*/ true, /*wholeValid=*/ nullptr,
simplifyLevel == 0 ? AreaBound::Strict : AreaBound::Lenient);

if (geom::is_empty(current))
return;
Expand Down Expand Up @@ -350,6 +359,7 @@ void ProcessObjects(
class SharedData& sharedData,
double simplifyLevel,
unsigned simplifyAlgo,
bool repairPolygons,
double filterArea,
bool combinePoints,
bool combineLines,
Expand Down Expand Up @@ -455,7 +465,7 @@ void ProcessObjects(
if (oo.oo.geomType == LINESTRING_ || oo.oo.geomType == MULTILINESTRING_)
writeMultiLinestring<Backend>(attributeStore, sharedData, vtLayer, bbox, oo, zoom, simplifyLevel, simplifyAlgo, boost::get<MultiLinestring>(g), attrMemo);
else if (oo.oo.geomType == POLYGON_)
writeMultiPolygon<Backend>(attributeStore, sharedData, vtLayer, bbox, oo, zoom, simplifyLevel, simplifyAlgo, boost::get<MultiPolygon>(g), attrMemo);
writeMultiPolygon<Backend>(attributeStore, sharedData, vtLayer, bbox, oo, zoom, simplifyLevel, simplifyAlgo, repairPolygons, boost::get<MultiPolygon>(g), attrMemo);
}
}
}
Expand Down Expand Up @@ -543,7 +553,7 @@ void ProcessLayer(
if (ld.featureLimit>0 && end-ooListSameLayer.first>ld.featureLimit && zoom<ld.featureLimitBelow) end = ooListSameLayer.first+ld.featureLimit;
ProcessObjects<Backend>(sources[i], attributeStore,
ooListSameLayer.first, end, sharedData,
simplifyLevel, ld.simplifyAlgo,
simplifyLevel, ld.simplifyAlgo, ld.repairPolygons,
filterArea, ld.combinePoints, zoom < ld.combineLinesBelow, zoom < ld.combinePolygonsBelow, zoom, bbox, vtLayer, attrMemo);
}
}
Expand Down
Loading