Illustrated C/C++ source sheets, symbol index, API relationship graph, compiler console and debug trace

LIVE AI / FLEXIBLE SENSING / FLIGHT CONTEXT

Sensoraia API

Live AI and sensing, connected to the flight.
See, listen, inspect and return supported results while airborne.

Loading...
Searching...
No Matches
xyz_tiles.h
Go to the documentation of this file.
1/*
2 * Copyright 2026 OpenUAS
3 * SPDX-License-Identifier: Apache-2.0
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18/**
19 * @file xyz_tiles.h
20 * @brief Plan interoperable XYZ tile ranges in Web Mercator.
21 * @details XYZ uses a north-origin tile grid and the Web-Mercator latitude
22 * limit. Planning snaps only floating-point noise at exact tile boundaries so
23 * a request does not gain or lose an entire row of tiles from rounding error.
24 */
25#ifndef PANGEA_XYZ_TILES_H
26#define PANGEA_XYZ_TILES_H
27
28#include "map_config.h"
29#include "map_projection.h"
30#include <cstdint>
31#include <iomanip>
32#include <sstream>
33
34namespace pangea_survey {
35/** @brief Inclusive rectangular tile range at one zoom level. */
36struct XyzRange {
37 int zoom = 19;
38 std::uint32_t firstX = 0, firstY = 0, lastX = 0, lastY = 0;
39 /** @brief Count columns in the ordered inclusive X range.
40 * @return One column when both X endpoints are the same. */
41 std::size_t columns() const { return static_cast<std::size_t>(lastX) - firstX + 1; }
42 /** @brief Count rows in the ordered inclusive Y range.
43 * @return One row when both Y endpoints are the same. */
44 std::size_t rows() const { return static_cast<std::size_t>(lastY) - firstY + 1; }
45 /** @brief Count tiles in the validated rectangular range.
46 * @return Number of tiles at this zoom; both edges are included. */
47 std::size_t size() const { return columns() * rows(); }
48};
49
50/**
51 * @brief Convert Web-Mercator geographic coordinates to canonical XYZ addresses.
52 * @details Tile pixels use a 256-pixel extent and paths are `zoom/x/y.jpeg`;
53 * the output is an ordinary interoperable XYZ tile pyramid.
54 */
55class XyzTiles {
56public:
57 static constexpr int tileSize = 256;
58 static constexpr double radius = 6378137;
59 static constexpr double radians = 0.01745329251994329577;
60 static constexpr double latitudeLimit = 85.0511287798066;
61 /** @brief Number of tiles across one axis at this zoom level. */
62 static double dimension(int zoom) {
63 if (zoom < 0 || zoom > 22) throw std::runtime_error("XYZ zoom must be an integer from 0 to 22");
64 return std::ldexp(1.0, zoom);
65 }
66 /** @brief Equatorial Web-Mercator metres per pixel at this zoom. */
67 static double metresPerPixel(int zoom) {
68 return 2 * 3.14159265358979323846 * radius / (tileSize * dimension(zoom));
69 }
70 /** @brief Ground metres per pixel at a latitude after Mercator scale correction. */
71 static double groundPixel(int zoom, double latitude) {
72 if (!std::isfinite(latitude) || std::abs(latitude) > latitudeLimit)
73 throw std::runtime_error("Latitude is outside the Web-Mercator tile grid");
74 return metresPerPixel(zoom) * std::cos(latitude * radians);
75 }
76 /**
77 * @brief Convert WGS-84 latitude/longitude to fractional tile coordinates.
78 * @param[in] latitude Latitude in degrees within Web-Mercator limits.
79 * @param[in] longitude Longitude in degrees.
80 * @param[in] zoom XYZ zoom level from 0 through 22.
81 * @return Fractional tile x and y, with y increasing southward.
82 */
83 static std::pair<double, double> tileCoordinate(double latitude, double longitude, int zoom) {
84 if (!std::isfinite(latitude) || !std::isfinite(longitude) || std::abs(latitude) > latitudeLimit ||
86 throw std::runtime_error("Invalid Web-Mercator latitude/longitude");
87 const double n = dimension(zoom);
88 return {(longitude + 180) / 360 * n,
89 (1 - std::asinh(std::tan(latitude * radians)) / 3.14159265358979323846) / 2 * n};
90 }
91 /** @brief Convert fractional tile coordinates back to latitude/longitude. */
92 static std::pair<double, double> geographic(double x, double y, int zoom) {
93 const double n = dimension(zoom);
94 if (!std::isfinite(x) || !std::isfinite(y) || x < 0 || y < 0 || x > n || y > n)
95 throw std::runtime_error("Invalid Web-Mercator tile coordinates");
96 return {std::atan(std::sinh(3.14159265358979323846 * (1 - 2 * y / n))) / radians,
97 x / n * 360 - 180};
98 }
99 /** @brief Return the geographic centre of one global pixel address. */
100 static std::pair<double, double> pixel(std::uint64_t x, std::uint64_t y, int zoom) {
101 return geographic((static_cast<double>(x) + .5) / tileSize,
102 (static_cast<double>(y) + .5) / tileSize, zoom);
103 }
104 /** @brief Build the canonical `zoom/x/y.jpeg` path after range validation. */
105 static std::filesystem::path path(const std::filesystem::path& root, int zoom,
106 std::uint32_t x, std::uint32_t y) {
107 const double n = dimension(zoom);
108 if (x >= n || y >= n) throw std::runtime_error("XYZ tile address is outside its zoom level");
109 return root / std::to_string(zoom) / std::to_string(x) / (std::to_string(y) + ".jpeg");
110 }
111};
112
113/**
114 * @brief Derive requested XYZ bounds, map grid, and per-zoom tile ranges.
115 * @details The tile rectangle is aligned in Web Mercator while the source
116 * mapper renders in UTM; a small working-grid pad contains the resampling taps.
117 * It is not a claim that imagery exists over every requested output pixel.
118 */
119struct XyzPlan {
121 int minZoom = 19;
122 double north = 0, south = 0, west = 0, east = 0;
123 /**
124 * @brief Construct a bounded tile pyramid from the configured geographic bounds.
125 * @param[in] config Validated XYZ settings and requested WGS-84 bounds.
126 * @throws std::runtime_error If zooms, bounds, or requested tile count are invalid.
127 */
128 explicit XyzPlan(const MapConfig& config) : minZoom(config.xyzMinZoom) {
129 if (minZoom < 0 || minZoom > config.xyzZoom || config.xyzZoom - minZoom > 2)
130 throw std::runtime_error("XYZ min_zoom must be within two levels below zoom");
131 const auto nw = XyzTiles::tileCoordinate(std::max(config.start.lat, config.end.lat),
132 std::min(config.start.lon, config.end.lon), minZoom);
133 const auto se = XyzTiles::tileCoordinate(std::min(config.start.lat, config.end.lat),
134 std::max(config.start.lon, config.end.lon), minZoom);
135 const auto n = static_cast<std::uint32_t>(XyzTiles::dimension(minZoom));
136 const auto snap = [](double value) {
137 const double integer = std::round(value);
138 return std::abs(value - integer) <= 8 * std::numeric_limits<double>::epsilon() *
139 std::max(1.0, std::abs(value)) ? integer : value;
140 };
141 const auto first = [n, &snap](double value) {
142 value = snap(value);
143 return static_cast<std::uint32_t>(std::clamp(std::floor(value), 0.0, double(n - 1)));
144 };
145 const auto last = [n, &snap](double value) {
146 value = snap(value);
147 return static_cast<std::uint32_t>(std::clamp(std::ceil(value) - 1, 0.0, double(n - 1)));
148 };
149 const auto factor = std::uint32_t{1} << (config.xyzZoom - minZoom);
150 base = {config.xyzZoom, first(nw.first) * factor, first(nw.second) * factor,
151 (last(se.first) + 1) * factor - 1, (last(se.second) + 1) * factor - 1};
152 if (base.firstX > base.lastX || base.firstY > base.lastY || size() > 100000)
153 throw std::runtime_error("Invalid XYZ bounds or more than 100000 requested tiles");
154 const auto corner = XyzTiles::geographic(base.firstX, base.firstY, base.zoom);
155 const auto opposite = XyzTiles::geographic(double(base.lastX) + 1, double(base.lastY) + 1, base.zoom);
156 north = corner.first; west = corner.second; south = opposite.first; east = opposite.second;
157 }
158 /** @brief Return the aligned tile rectangle at a zoom within this plan. */
159 XyzRange range(int zoom) const {
160 if (zoom < minZoom || zoom > base.zoom) throw std::runtime_error("Zoom outside the XYZ export plan");
161 const auto shift = base.zoom - zoom;
162 return {zoom, base.firstX >> shift, base.firstY >> shift, base.lastX >> shift, base.lastY >> shift};
163 }
164 /** @brief Count all requested tiles across the configured zoom pyramid. */
165 std::size_t size() const {
166 std::size_t count = 0;
167 for (int zoom = minZoom; zoom <= base.zoom; ++zoom) count += range(zoom).size();
168 return count;
169 }
170 /** @brief Derive the padded UTM working-grid settings needed for resampling. */
171 MapConfig workingConfig(const MapConfig& original) const {
172 auto result = original;
173 const double latitude = (north + south) / 2, longitude = (west + east) / 2;
174 const MapProjection projection(latitude, longitude);
175 result.mapPixelSize = std::clamp(XyzTiles::groundPixel(base.zoom, latitude) *
176 projection.scale(latitude, longitude), .05, 2.0);
177 const double pad = 4 * result.mapPixelSize / XyzTiles::radius / XyzTiles::radians;
178 result.start.lat = north + pad; result.end.lat = south - pad;
179 result.start.lon = west - pad / std::cos(latitude * XyzTiles::radians);
180 result.end.lon = east + pad / std::cos(latitude * XyzTiles::radians);
181 result.jpegWidth = result.jpegHeight = 512;
182 return result;
183 }
184 /**
185 * @brief Reject any existing tile or partial file in the output plan.
186 * @param[in] root XYZ output directory.
187 * @throws std::runtime_error If any planned destination already exists.
188 */
189 void checkOutput(const std::filesystem::path& root) const {
190 for (int zoom = minZoom; zoom <= base.zoom; ++zoom) {
191 const auto r = range(zoom);
192 for (auto x = r.firstX; x <= r.lastX; ++x) for (auto y = r.firstY; y <= r.lastY; ++y) {
193 const auto tile = XyzTiles::path(root, zoom, x, y);
194 if (std::filesystem::exists(tile) || std::filesystem::exists(tile.string() + ".partial"))
195 throw std::runtime_error("Refusing to overwrite XYZ tile: " + tile.u8string());
196 }
197 }
198 }
199};
200}
201#endif
static double latitude
static double longitude
Forward and inverse WGS-84 Transverse Mercator conversion for one UTM zone.
double scale(double latitude, double longitude) const
Estimate local UTM point scale at a geographic position.
Convert Web-Mercator geographic coordinates to canonical XYZ addresses.
Definition xyz_tiles.h:55
static std::pair< double, double > geographic(double x, double y, int zoom)
Convert fractional tile coordinates back to latitude/longitude.
Definition xyz_tiles.h:92
static double groundPixel(int zoom, double latitude)
Ground metres per pixel at a latitude after Mercator scale correction.
Definition xyz_tiles.h:71
static std::filesystem::path path(const std::filesystem::path &root, int zoom, std::uint32_t x, std::uint32_t y)
Build the canonical zoom/x/y.jpeg path after range validation.
Definition xyz_tiles.h:105
static constexpr double radians
Definition xyz_tiles.h:59
static constexpr double radius
Definition xyz_tiles.h:58
static std::pair< double, double > pixel(std::uint64_t x, std::uint64_t y, int zoom)
Return the geographic centre of one global pixel address.
Definition xyz_tiles.h:100
static constexpr double latitudeLimit
Definition xyz_tiles.h:60
static constexpr int tileSize
Definition xyz_tiles.h:57
static std::pair< double, double > tileCoordinate(double latitude, double longitude, int zoom)
Convert WGS-84 latitude/longitude to fractional tile coordinates.
Definition xyz_tiles.h:83
static double dimension(int zoom)
Number of tiles across one axis at this zoom level.
Definition xyz_tiles.h:62
static double metresPerPixel(int zoom)
Equatorial Web-Mercator metres per pixel at this zoom.
Definition xyz_tiles.h:67
Own the survey mapper's validated configuration and mode defaults.
Convert between WGS-84 coordinates and one local UTM grid.
static size_t count
Definition pose_log.c:79
Fully parsed settings shared by orthomap and XYZ export.
Definition map_config.h:41
std::size_t size() const
Count all requested tiles across the configured zoom pyramid.
Definition xyz_tiles.h:165
XyzPlan(const MapConfig &config)
Construct a bounded tile pyramid from the configured geographic bounds.
Definition xyz_tiles.h:128
void checkOutput(const std::filesystem::path &root) const
Reject any existing tile or partial file in the output plan.
Definition xyz_tiles.h:189
MapConfig workingConfig(const MapConfig &original) const
Derive the padded UTM working-grid settings needed for resampling.
Definition xyz_tiles.h:171
XyzRange range(int zoom) const
Return the aligned tile rectangle at a zoom within this plan.
Definition xyz_tiles.h:159
Inclusive rectangular tile range at one zoom level.
Definition xyz_tiles.h:36
std::uint32_t firstX
Definition xyz_tiles.h:38
std::size_t rows() const
Count rows in the ordered inclusive Y range.
Definition xyz_tiles.h:44
std::size_t size() const
Count tiles in the validated rectangular range.
Definition xyz_tiles.h:47
std::size_t columns() const
Count columns in the ordered inclusive X range.
Definition xyz_tiles.h:41
std::uint32_t firstY
Definition xyz_tiles.h:38
std::uint32_t lastX
Definition xyz_tiles.h:38
std::uint32_t lastY
Definition xyz_tiles.h:38
struct usher_control_result result
Definition usher.c:377