@celljs/ta-geo 0.0.0-stage → 4.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.en.md ADDED
@@ -0,0 +1,13 @@
1
+ # Cell - Ta Geo
2
+
3
+ Real places for Ta's extensions (a plain library, not a pi package), for any extension, not only games: nearby, trips, meeting in person, questions of geography.
4
+
5
+ - **A grid of plots over the earth** (`GeoGrid`): a tile of zoom 16 of Web Mercator is a plot of 256 × 256 columns, a column a pixel of zoom 24, so that every device names a place by the same numbers and what each makes fits beside the others' with nothing to agree on.
6
+ - **Vector tiles decoded** (`GeoMvt`): Mapbox Vector Tile v2, read without a library.
7
+ - **A source of tiles** (`OpenFreeMapTiles`): OpenStreetMap, free and without a key, under versions whose URLs never change.
8
+ - **Places** (`GeoPlaces`): a search of Nominatim, the name of a place, the location of the browser.
9
+ - **The ground of a plot** (`GeoRaster`): a kind of ground for each column and the buildings with their heights.
10
+ - **How high the ground is** (`GeoElevation`): heights at the points of one lattice over the earth (5 × 5 a plot, one request), the lowest of the nine round each to take away buildings and trees, less the low ground of the region; plots side by side read the same points on their edge and fit. Open-Meteo (Copernicus DEM) by default, free and without a key.
11
+ - **The weather of a place** (`GeoWeather`): clear, cloudy, overcast, fog, rain, snow or a storm, how warm, the clouds, the wind, sunrise, sunset and the place's clock; kept a quarter of an hour for a square of about a kilometre, only the place sent.
12
+
13
+ Map data © OpenStreetMap contributors: say so where it is shown (ODbL). The design is `docs/design/ta-earth.md`.
package/README.md CHANGED
@@ -1,3 +1,13 @@
1
- # Temporary Holding Version
1
+ # Cell - Ta Geo
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 给 Ta 的扩展用的真实地点库(普通的库,不是 pi 包)。和游戏无关的扩展也能用:附近、出行、线下见面、地理题。
4
+
5
+ - **全球地块网格**(`GeoGrid`):Web Mercator 第 16 级瓦片是一个地块,256 × 256 列;一列是第 24 级的一个像素。任何设备按同样的数字指同一个地方,拼起来不用协调。经纬度与列互换、地块号、所在的低级瓦片、每列多少米、把位置粗化到约 10 公里。
6
+ - **矢量瓦片解码**(`GeoMvt`):自带的 Mapbox Vector Tile v2 读取,不依赖第三方库。
7
+ - **瓦片来源**(`OpenFreeMapTiles`):OpenStreetMap 数据,免费、无需密钥;瓦片地址带版本,永不变,所以同一版本在每台设备上一样。版本下架时退回最新版。
8
+ - **地名搜索与定位**(`GeoPlaces`):Nominatim 搜索、反查地名,浏览器定位。
9
+ - **地面栅格化**(`GeoRaster`):把一个地块上的地物画成每列一种地面(草、公园、树林、水、道路……)和建筑(轮廓、高度、颜色)。
10
+ - **地形高度**(`GeoElevation`):在全球统一的格点上读高度(每地块 5 × 5 个点,一次请求),每点取周围九点最低去掉楼和树,再减去区域低地基准,相邻地块边上读的是同一批点,拼起来不断。默认 Open-Meteo(Copernicus DEM),免费无密钥。
11
+ - **当地天气**(`GeoWeather`):晴、多云、阴、雾、雨、雪、雷雨,气温、云量、风、日出日落和当地时差;按约 1 公里的格子缓存 15 分钟,只发出位置。
12
+
13
+ 地图数据 © OpenStreetMap 贡献者,使用时界面上要写出来(ODbL)。设计见 `docs/design/ta-earth.md`。
@@ -0,0 +1,42 @@
1
+ import { type LonLat, type Plot } from './geo-grid.js';
2
+ import type { Fetcher } from './geo-tiles.js';
3
+ /** Columns between two points of the lattice: a quarter of a plot. */
4
+ export declare const RELIEF_STEP = 128;
5
+ export interface ElevationSource {
6
+ /** The height above the sea of each place, in metres. */
7
+ read(places: LonLat[]): Promise<number[]>;
8
+ }
9
+ export declare class OpenMeteoElevation implements ElevationSource {
10
+ protected readonly fetcher: Fetcher;
11
+ protected readonly base: string;
12
+ constructor(fetcher?: Fetcher, base?: string);
13
+ read(places: LonLat[]): Promise<number[]>;
14
+ }
15
+ /** The ground of a plot: metres above the low ground of its region. */
16
+ export interface PlotRelief {
17
+ /** At the points of the lattice on and in the plot, (PER_PLOT + 1)² of them, row by row from the north-west. */
18
+ readonly lattice: Float32Array;
19
+ /** At a column of the plot (0 to 511 each way), between the points round it. */
20
+ at(x: number, z: number): number;
21
+ }
22
+ interface Waiting {
23
+ ix: number;
24
+ iz: number;
25
+ resolve(metres: number): void;
26
+ reject(error: unknown): void;
27
+ }
28
+ export declare class GeoElevation {
29
+ protected readonly source: ElevationSource;
30
+ protected readonly points: Map<string, Promise<number>>;
31
+ protected waiting: Waiting[];
32
+ protected timer?: ReturnType<typeof setTimeout>;
33
+ constructor(source?: ElevationSource);
34
+ /** The ground of a plot; it fails when the heights cannot be read (the next time asks again). */
35
+ plot({ px, pz }: Plot): Promise<PlotRelief>;
36
+ /** The ground between the points of a lattice of a plot. */
37
+ static relief(lattice: Float32Array): PlotRelief;
38
+ /** The height of a point of the lattice, read with others asked at the same time. */
39
+ protected point(ix: number, iz: number): Promise<number>;
40
+ protected flush(): void;
41
+ }
42
+ export {};
@@ -0,0 +1,165 @@
1
+ import { GeoGrid, PLOT_SIZE } from './geo-grid.js';
2
+ // How high the ground is (GeoElevation): heights read at the points of one lattice over the whole earth, a point
3
+ // every RELIEF_STEP columns, so that two plots side by side read the same points on their edge and fit; of each
4
+ // point the lowest of it and the eight round it, which takes away the buildings and trees the model of the
5
+ // surface has in it and leaves the hills; then less a datum, the low ground of the region (the lowest of nine
6
+ // points round each corner of a much coarser lattice, between them in a straight line), so that a city by the sea
7
+ // and one on a plateau both stand on their own ground. The same points give the same heights on every device: what
8
+ // each makes of a place, the others make too. Open-Meteo by default (Copernicus DEM, 90 m), free and without a key.
9
+ /** Columns between two points of the lattice: a quarter of a plot. */
10
+ export const RELIEF_STEP = 128;
11
+ /** Points of the lattice between two corners of the datum's (about 30 km at the equator). */
12
+ const DATUM_STEPS = 256;
13
+ const PER_PLOT = PLOT_SIZE / RELIEF_STEP;
14
+ /** Points asked in one request at most. */
15
+ const BATCH = 100;
16
+ /** Points kept, the latest read. */
17
+ const KEPT = 20000;
18
+ export class OpenMeteoElevation {
19
+ constructor(fetcher = (url, init) => fetch(url, init), base = 'https://api.open-meteo.com/v1/elevation') {
20
+ this.fetcher = fetcher;
21
+ this.base = base;
22
+ }
23
+ async read(places) {
24
+ const latitude = places.map(each => each.lat.toFixed(5)).join(',');
25
+ const longitude = places.map(each => each.lon.toFixed(5)).join(',');
26
+ const response = await this.fetcher(`${this.base}?latitude=${latitude}&longitude=${longitude}`);
27
+ if (!response.ok) {
28
+ throw new Error(`Elevation: HTTP ${response.status}`);
29
+ }
30
+ const json = (await response.json());
31
+ if (!Array.isArray(json.elevation) || json.elevation.length !== places.length) {
32
+ throw new Error('Elevation: no heights');
33
+ }
34
+ return json.elevation.map(value => (typeof value === 'number' && Number.isFinite(value) ? value : 0));
35
+ }
36
+ }
37
+ export class GeoElevation {
38
+ constructor(source = new OpenMeteoElevation()) {
39
+ this.source = source;
40
+ this.points = new Map();
41
+ this.waiting = [];
42
+ }
43
+ /** The ground of a plot; it fails when the heights cannot be read (the next time asks again). */
44
+ async plot({ px, pz }) {
45
+ const ix0 = px * PER_PLOT;
46
+ const iz0 = pz * PER_PLOT;
47
+ const side = PER_PLOT + 1;
48
+ // Every point asked at once, so that they go in one request.
49
+ const raw = new Map();
50
+ const ask = (ix, iz) => {
51
+ const key = `${ix},${iz}`;
52
+ let known = raw.get(key);
53
+ if (!known) {
54
+ known = this.point(ix, iz);
55
+ raw.set(key, known);
56
+ }
57
+ return known;
58
+ };
59
+ for (let iz = iz0 - 1; iz <= iz0 + side; iz++) {
60
+ for (let ix = ix0 - 1; ix <= ix0 + side; ix++) {
61
+ ask(ix, iz);
62
+ }
63
+ }
64
+ const corners = new Map();
65
+ const corner = (jx, jz) => {
66
+ const key = `${jx},${jz}`;
67
+ let known = corners.get(key);
68
+ if (!known) {
69
+ const half = DATUM_STEPS / 2;
70
+ const nine = [];
71
+ for (let b = -1; b <= 1; b++) {
72
+ for (let a = -1; a <= 1; a++) {
73
+ nine.push(ask(jx * DATUM_STEPS + a * half, jz * DATUM_STEPS + b * half));
74
+ }
75
+ }
76
+ known = Promise.all(nine).then(values => Math.min(...values));
77
+ corners.set(key, known);
78
+ }
79
+ return known;
80
+ };
81
+ const lattice = new Float32Array(side * side);
82
+ const datums = [];
83
+ for (let iz = iz0; iz < iz0 + side; iz++) {
84
+ for (let ix = ix0; ix < ix0 + side; ix++) {
85
+ const jx = Math.floor(ix / DATUM_STEPS);
86
+ const jz = Math.floor(iz / DATUM_STEPS);
87
+ const tx = ix / DATUM_STEPS - jx;
88
+ const tz = iz / DATUM_STEPS - jz;
89
+ datums.push(Promise.all([corner(jx, jz), corner(jx + 1, jz), corner(jx, jz + 1), corner(jx + 1, jz + 1)]).then(([a, b, c, d]) => (a * (1 - tx) + b * tx) * (1 - tz) + (c * (1 - tx) + d * tx) * tz));
90
+ }
91
+ }
92
+ const [heights, datum] = await Promise.all([Promise.all([...raw.values()]), Promise.all(datums)]);
93
+ const keys = [...raw.keys()];
94
+ const metres = new Map(keys.map((key, k) => [key, heights[k]]));
95
+ const height = (ix, iz) => { var _a; return (_a = metres.get(`${ix},${iz}`)) !== null && _a !== void 0 ? _a : 0; };
96
+ for (let row = 0; row < side; row++) {
97
+ for (let col = 0; col < side; col++) {
98
+ let low = Number.POSITIVE_INFINITY;
99
+ for (let b = -1; b <= 1; b++) {
100
+ for (let a = -1; a <= 1; a++) {
101
+ low = Math.min(low, height(ix0 + col + a, iz0 + row + b));
102
+ }
103
+ }
104
+ lattice[row * side + col] = Math.max(0, low - datum[row * side + col]);
105
+ }
106
+ }
107
+ return GeoElevation.relief(lattice);
108
+ }
109
+ /** The ground between the points of a lattice of a plot. */
110
+ static relief(lattice) {
111
+ const side = PER_PLOT + 1;
112
+ return {
113
+ lattice,
114
+ at(x, z) {
115
+ const fx = Math.min(PER_PLOT - 1e-6, Math.max(0, (x + 0.5) / RELIEF_STEP));
116
+ const fz = Math.min(PER_PLOT - 1e-6, Math.max(0, (z + 0.5) / RELIEF_STEP));
117
+ const ix = Math.floor(fx);
118
+ const iz = Math.floor(fz);
119
+ const tx = fx - ix;
120
+ const tz = fz - iz;
121
+ const v = (c, r) => lattice[(iz + r) * side + ix + c];
122
+ return (v(0, 0) * (1 - tx) + v(1, 0) * tx) * (1 - tz) + (v(0, 1) * (1 - tx) + v(1, 1) * tx) * tz;
123
+ },
124
+ };
125
+ }
126
+ /** The height of a point of the lattice, read with others asked at the same time. */
127
+ point(ix, iz) {
128
+ const key = `${ix},${iz}`;
129
+ const known = this.points.get(key);
130
+ if (known) {
131
+ return known;
132
+ }
133
+ const made = new Promise((resolve, reject) => {
134
+ var _a;
135
+ this.waiting.push({ ix, iz, resolve, reject });
136
+ (_a = this.timer) !== null && _a !== void 0 ? _a : (this.timer = setTimeout(() => this.flush(), 0));
137
+ });
138
+ made.catch(() => this.points.delete(key));
139
+ this.points.set(key, made);
140
+ while (this.points.size > KEPT) {
141
+ this.points.delete(this.points.keys().next().value);
142
+ }
143
+ return made;
144
+ }
145
+ flush() {
146
+ this.timer = undefined;
147
+ const all = this.waiting;
148
+ this.waiting = [];
149
+ for (let start = 0; start < all.length; start += BATCH) {
150
+ const batch = all.slice(start, start + BATCH);
151
+ const places = batch.map(each => GeoGrid.toLonLat({ x: each.ix * RELIEF_STEP, z: each.iz * RELIEF_STEP }));
152
+ const read = (tries) => this.source.read(places).catch(error => (tries > 0 ? read(tries - 1) : Promise.reject(error)));
153
+ read(1).then(values => {
154
+ for (const [k, each] of batch.entries()) {
155
+ each.resolve(values[k]);
156
+ }
157
+ }, error => {
158
+ for (const each of batch) {
159
+ each.reject(error);
160
+ }
161
+ });
162
+ }
163
+ }
164
+ }
165
+ //# sourceMappingURL=geo-elevation.js.map
@@ -0,0 +1,50 @@
1
+ /** The zoom of a plot. */
2
+ export declare const PLOT_ZOOM = 16;
3
+ /** Columns across a plot. */
4
+ export declare const PLOT_SIZE = 512;
5
+ /** The zoom of a column: a pixel of a plot. */
6
+ export declare const COLUMN_ZOOM: number;
7
+ export interface LonLat {
8
+ lon: number;
9
+ lat: number;
10
+ }
11
+ /** A point of the grid, in columns: x east, z south, from the north-west corner of the earth. */
12
+ export interface GridPoint {
13
+ x: number;
14
+ z: number;
15
+ }
16
+ /** A plot: a tile of zoom 16. */
17
+ export interface Plot {
18
+ px: number;
19
+ pz: number;
20
+ }
21
+ /** A tile of a zoom of the maps of the web. */
22
+ export interface MapTile {
23
+ z: number;
24
+ x: number;
25
+ y: number;
26
+ }
27
+ export declare namespace GeoGrid {
28
+ /** Where a place is on the grid, in columns (not whole). */
29
+ function toGrid({ lon, lat }: LonLat): GridPoint;
30
+ /** The place at a point of the grid. */
31
+ function toLonLat({ x, z }: GridPoint): LonLat;
32
+ /** The plot a point is in. */
33
+ function plotOf({ x, z }: GridPoint): Plot;
34
+ /** A plot by its name, `16/x/y` as the maps of the web name its tile. */
35
+ function key({ px, pz }: Plot): string;
36
+ function parse(key: string): Plot | undefined;
37
+ /** The tile of a lower zoom the plot is in, and where in it, as a fraction of the tile (0 to 1). */
38
+ function tileOf({ px, pz }: Plot, zoom: number): {
39
+ tile: MapTile;
40
+ left: number;
41
+ top: number;
42
+ size: number;
43
+ };
44
+ /** The metres a column is across at a latitude. */
45
+ function metresPerColumn(lat: number): number;
46
+ /** The plots around one, `ring` away at most, nearest first. */
47
+ function around(plot: Plot, ring: number): Plot[];
48
+ /** A place made coarse: the middle of its tile of `zoom` (12: about ten kilometres), to tell others roughly where. */
49
+ function coarse(place: LonLat, zoom: number): LonLat;
50
+ }
@@ -0,0 +1,90 @@
1
+ // The earth as one grid (GeoGrid): Web Mercator, as the maps of the web draw it, cut into plots, the tiles of
2
+ // zoom 16, each of 512 × 512 columns. A column is a pixel of zoom 25 (about a metre: 1.19 m at the equator, 1.1 m
3
+ // at 22°), so that every device names the same place by the same numbers and what each makes of it fits beside what
4
+ // the others make, with nothing to agree on.
5
+ /** The zoom of a plot. */
6
+ export const PLOT_ZOOM = 16;
7
+ /** Columns across a plot. */
8
+ export const PLOT_SIZE = 512;
9
+ /** The zoom of a column: a pixel of a plot. */
10
+ export const COLUMN_ZOOM = PLOT_ZOOM + 9;
11
+ const COLUMNS = 2 ** COLUMN_ZOOM;
12
+ /** The earth's circumference at the equator, in metres (WGS 84). */
13
+ const EQUATOR = 40075016.686;
14
+ /** How far north and south Web Mercator goes. */
15
+ const MAX_LAT = 85.05112878;
16
+ export var GeoGrid;
17
+ (function (GeoGrid) {
18
+ /** Where a place is on the grid, in columns (not whole). */
19
+ function toGrid({ lon, lat }) {
20
+ const clamped = Math.max(-MAX_LAT, Math.min(MAX_LAT, lat));
21
+ const rad = (clamped * Math.PI) / 180;
22
+ const x = ((lon + 180) / 360) * COLUMNS;
23
+ const z = ((1 - Math.log(Math.tan(rad) + 1 / Math.cos(rad)) / Math.PI) / 2) * COLUMNS;
24
+ return { x, z };
25
+ }
26
+ GeoGrid.toGrid = toGrid;
27
+ /** The place at a point of the grid. */
28
+ function toLonLat({ x, z }) {
29
+ const lon = (x / COLUMNS) * 360 - 180;
30
+ const n = Math.PI - (2 * Math.PI * z) / COLUMNS;
31
+ const lat = (180 / Math.PI) * Math.atan(Math.sinh(n));
32
+ return { lon, lat };
33
+ }
34
+ GeoGrid.toLonLat = toLonLat;
35
+ /** The plot a point is in. */
36
+ function plotOf({ x, z }) {
37
+ return { px: Math.floor(x / PLOT_SIZE), pz: Math.floor(z / PLOT_SIZE) };
38
+ }
39
+ GeoGrid.plotOf = plotOf;
40
+ /** A plot by its name, `16/x/y` as the maps of the web name its tile. */
41
+ function key({ px, pz }) {
42
+ return `${PLOT_ZOOM}/${px}/${pz}`;
43
+ }
44
+ GeoGrid.key = key;
45
+ function parse(key) {
46
+ const match = /^16\/(\d+)\/(\d+)$/.exec(key);
47
+ if (!match) {
48
+ return undefined;
49
+ }
50
+ const plot = { px: Number(match[1]), pz: Number(match[2]) };
51
+ return plot.px < 2 ** PLOT_ZOOM && plot.pz < 2 ** PLOT_ZOOM ? plot : undefined;
52
+ }
53
+ GeoGrid.parse = parse;
54
+ /** The tile of a lower zoom the plot is in, and where in it, as a fraction of the tile (0 to 1). */
55
+ function tileOf({ px, pz }, zoom) {
56
+ const shift = PLOT_ZOOM - zoom;
57
+ const per = 2 ** shift;
58
+ return {
59
+ tile: { z: zoom, x: Math.floor(px / per), y: Math.floor(pz / per) },
60
+ left: (px % per) / per,
61
+ top: (pz % per) / per,
62
+ size: 1 / per,
63
+ };
64
+ }
65
+ GeoGrid.tileOf = tileOf;
66
+ /** The metres a column is across at a latitude. */
67
+ function metresPerColumn(lat) {
68
+ return (EQUATOR * Math.cos((lat * Math.PI) / 180)) / COLUMNS;
69
+ }
70
+ GeoGrid.metresPerColumn = metresPerColumn;
71
+ /** The plots around one, `ring` away at most, nearest first. */
72
+ function around(plot, ring) {
73
+ const out = [];
74
+ for (let dz = -ring; dz <= ring; dz++) {
75
+ for (let dx = -ring; dx <= ring; dx++) {
76
+ out.push({ px: plot.px + dx, pz: plot.pz + dz });
77
+ }
78
+ }
79
+ return out.sort((a, b) => Math.hypot(a.px - plot.px, a.pz - plot.pz) - Math.hypot(b.px - plot.px, b.pz - plot.pz));
80
+ }
81
+ GeoGrid.around = around;
82
+ /** A place made coarse: the middle of its tile of `zoom` (12: about ten kilometres), to tell others roughly where. */
83
+ function coarse(place, zoom) {
84
+ const per = 2 ** (COLUMN_ZOOM - zoom);
85
+ const { x, z } = toGrid(place);
86
+ return toLonLat({ x: (Math.floor(x / per) + 0.5) * per, z: (Math.floor(z / per) + 0.5) * per });
87
+ }
88
+ GeoGrid.coarse = coarse;
89
+ })(GeoGrid || (GeoGrid = {}));
90
+ //# sourceMappingURL=geo-grid.js.map
@@ -0,0 +1,17 @@
1
+ export type MvtValue = string | number | boolean;
2
+ export interface MvtFeature {
3
+ /** 1 a point, 2 a line, 3 a polygon. */
4
+ type: 1 | 2 | 3;
5
+ properties: Record<string, MvtValue>;
6
+ /** Points: one part of points; lines: a part each; polygons: rings, each outer one before its holes. */
7
+ geometry: [number, number][][];
8
+ }
9
+ export interface MvtLayer {
10
+ name: string;
11
+ extent: number;
12
+ features: MvtFeature[];
13
+ }
14
+ export declare namespace GeoMvt {
15
+ /** The layers of a tile, by name. */
16
+ function decode(bytes: Uint8Array): Map<string, MvtLayer>;
17
+ }
package/esm/geo-mvt.js ADDED
@@ -0,0 +1,213 @@
1
+ // Vector tiles (GeoMvt): the Mapbox Vector Tile format, version 2, that the maps of the web serve, read without a
2
+ // library: the protobuf of its layers, the keys and values of their features, the commands of their geometry made
3
+ // points, lines and rings in the units of the tile (0 to its extent).
4
+ /** Reads the protobuf of a tile: varints, fixed numbers and lengths of bytes. */
5
+ class Pbf {
6
+ constructor(buf, end = buf.length) {
7
+ this.buf = buf;
8
+ this.end = end;
9
+ this.pos = 0;
10
+ }
11
+ varint() {
12
+ let value = 0;
13
+ let shift = 0;
14
+ let byte;
15
+ do {
16
+ byte = this.buf[this.pos++];
17
+ value += (byte & 0x7f) * 2 ** shift;
18
+ shift += 7;
19
+ } while (byte & 0x80 && shift < 70);
20
+ return value;
21
+ }
22
+ svarint() {
23
+ const n = this.varint();
24
+ return n % 2 === 1 ? (n + 1) / -2 : n / 2;
25
+ }
26
+ bytes() {
27
+ const length = this.varint();
28
+ const start = this.pos;
29
+ this.pos += length;
30
+ return this.buf.subarray(start, start + length);
31
+ }
32
+ /** Skips a field of the wire type. */
33
+ skip(wire) {
34
+ if (wire === 0) {
35
+ this.varint();
36
+ }
37
+ else if (wire === 1) {
38
+ this.pos += 8;
39
+ }
40
+ else if (wire === 2) {
41
+ this.pos += this.varint();
42
+ }
43
+ else if (wire === 5) {
44
+ this.pos += 4;
45
+ }
46
+ else {
47
+ throw new Error(`Unknown wire type ${wire}`);
48
+ }
49
+ }
50
+ packed() {
51
+ const inner = new Pbf(this.bytes());
52
+ const out = [];
53
+ while (inner.pos < inner.end) {
54
+ out.push(inner.varint());
55
+ }
56
+ return out;
57
+ }
58
+ }
59
+ const decoder = new TextDecoder();
60
+ function value(bytes) {
61
+ const pbf = new Pbf(bytes);
62
+ let out = '';
63
+ while (pbf.pos < pbf.end) {
64
+ const tag = pbf.varint();
65
+ const field = Math.floor(tag / 8);
66
+ const view = new DataView(bytes.buffer, bytes.byteOffset + pbf.pos);
67
+ switch (field) {
68
+ case 1:
69
+ out = decoder.decode(pbf.bytes());
70
+ break;
71
+ case 2:
72
+ out = view.getFloat32(0, true);
73
+ pbf.pos += 4;
74
+ break;
75
+ case 3:
76
+ out = view.getFloat64(0, true);
77
+ pbf.pos += 8;
78
+ break;
79
+ case 4:
80
+ case 5:
81
+ out = pbf.varint();
82
+ break;
83
+ case 6:
84
+ out = pbf.svarint();
85
+ break;
86
+ case 7:
87
+ out = pbf.varint() !== 0;
88
+ break;
89
+ default:
90
+ pbf.skip(tag & 7);
91
+ }
92
+ }
93
+ return out;
94
+ }
95
+ /** The parts of a geometry from its commands: MoveTo starts a part, LineTo goes on, ClosePath closes a ring. */
96
+ function geometry(commands, type) {
97
+ const parts = [];
98
+ let part = [];
99
+ let x = 0;
100
+ let y = 0;
101
+ let i = 0;
102
+ const zigzag = (n) => (n % 2 === 1 ? (n + 1) / -2 : n / 2);
103
+ while (i < commands.length) {
104
+ const command = commands[i] & 7;
105
+ const count = commands[i] >>> 3;
106
+ i++;
107
+ if (command === 7) {
108
+ if (part.length > 0) {
109
+ part.push([part[0][0], part[0][1]]);
110
+ }
111
+ continue;
112
+ }
113
+ for (let k = 0; k < count && i + 1 < commands.length; k++) {
114
+ x += zigzag(commands[i++]);
115
+ y += zigzag(commands[i++]);
116
+ if (command === 1 && type !== 1) {
117
+ if (part.length > 0) {
118
+ parts.push(part);
119
+ }
120
+ part = [];
121
+ }
122
+ part.push([x, y]);
123
+ }
124
+ }
125
+ if (part.length > 0) {
126
+ parts.push(part);
127
+ }
128
+ return parts;
129
+ }
130
+ function layer(bytes) {
131
+ const pbf = new Pbf(bytes);
132
+ let name = '';
133
+ let extent = 4096;
134
+ const keys = [];
135
+ const values = [];
136
+ const raw = [];
137
+ while (pbf.pos < pbf.end) {
138
+ const tag = pbf.varint();
139
+ const field = Math.floor(tag / 8);
140
+ if (field === 1) {
141
+ name = decoder.decode(pbf.bytes());
142
+ }
143
+ else if (field === 2) {
144
+ const inner = new Pbf(pbf.bytes());
145
+ const feature = { tags: [], type: 0, geometry: [] };
146
+ while (inner.pos < inner.end) {
147
+ const t = inner.varint();
148
+ const f = Math.floor(t / 8);
149
+ if (f === 2) {
150
+ feature.tags = inner.packed();
151
+ }
152
+ else if (f === 3) {
153
+ feature.type = inner.varint();
154
+ }
155
+ else if (f === 4) {
156
+ feature.geometry = inner.packed();
157
+ }
158
+ else {
159
+ inner.skip(t & 7);
160
+ }
161
+ }
162
+ raw.push(feature);
163
+ }
164
+ else if (field === 3) {
165
+ keys.push(decoder.decode(pbf.bytes()));
166
+ }
167
+ else if (field === 4) {
168
+ values.push(value(pbf.bytes()));
169
+ }
170
+ else if (field === 5) {
171
+ extent = pbf.varint();
172
+ }
173
+ else {
174
+ pbf.skip(tag & 7);
175
+ }
176
+ }
177
+ const features = [];
178
+ for (const each of raw) {
179
+ if (each.type < 1 || each.type > 3) {
180
+ continue;
181
+ }
182
+ const properties = {};
183
+ for (let i = 0; i + 1 < each.tags.length; i += 2) {
184
+ const key = keys[each.tags[i]];
185
+ if (key !== undefined) {
186
+ properties[key] = values[each.tags[i + 1]];
187
+ }
188
+ }
189
+ features.push({ type: each.type, properties, geometry: geometry(each.geometry, each.type) });
190
+ }
191
+ return { name, extent, features };
192
+ }
193
+ export var GeoMvt;
194
+ (function (GeoMvt) {
195
+ /** The layers of a tile, by name. */
196
+ function decode(bytes) {
197
+ const pbf = new Pbf(bytes);
198
+ const layers = new Map();
199
+ while (pbf.pos < pbf.end) {
200
+ const tag = pbf.varint();
201
+ if (Math.floor(tag / 8) === 3) {
202
+ const made = layer(pbf.bytes());
203
+ layers.set(made.name, made);
204
+ }
205
+ else {
206
+ pbf.skip(tag & 7);
207
+ }
208
+ }
209
+ return layers;
210
+ }
211
+ GeoMvt.decode = decode;
212
+ })(GeoMvt || (GeoMvt = {}));
213
+ //# sourceMappingURL=geo-mvt.js.map
@@ -0,0 +1,27 @@
1
+ import type { MvtLayer } from './geo-mvt.js';
2
+ export declare const MapPixel: {
3
+ readonly LAND: 0;
4
+ readonly WATER: 1;
5
+ readonly WOOD: 2;
6
+ readonly GRASS: 3;
7
+ readonly SAND: 4;
8
+ readonly ICE: 5;
9
+ readonly TOWN: 6;
10
+ readonly ROAD: 7;
11
+ readonly MAJOR: 8;
12
+ };
13
+ export type MapPixelKind = (typeof MapPixel)[keyof typeof MapPixel];
14
+ /** A name on a tile: where (fractions of the tile), and how much it matters (`rank`, lower the more; a capital 0). */
15
+ export interface MapName {
16
+ name: string;
17
+ x: number;
18
+ y: number;
19
+ rank: number;
20
+ kind: string;
21
+ }
22
+ export declare namespace GeoPixels {
23
+ /** The pixels of a tile: `zoom` the zoom it is of (towns from 9, motorways from 9, the smaller roads from 11). */
24
+ function tile(layers: ReadonlyMap<string, MvtLayer> | undefined, zoom: number, size?: number): Uint8Array;
25
+ /** The names of the places on a tile, in `language` where the map has it (`name:zh`), the most important first. */
26
+ function names(layers: ReadonlyMap<string, MvtLayer> | undefined, language: string): MapName[];
27
+ }