@duoquote/polytini 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +119 -2
- package/dist/deckgl.cjs +250 -0
- package/dist/flexible.cjs +229 -0
- package/dist/google.cjs +232 -0
- package/dist/leaflet-auto.cjs +209 -0
- package/dist/leaflet.cjs +231 -0
- package/dist/mapbox.cjs +185 -0
- package/dist/maplibre.cjs +185 -0
- package/dist/node.cjs +322 -0
- package/dist/presets.cjs +65 -0
- package/dist/turf.cjs +267 -0
- package/dist/types/cli.d.cts +2 -0
- package/dist/types/deckgl.d.cts +72 -0
- package/dist/types/flexible.d.cts +92 -0
- package/dist/types/geojson.jsr.d.cts +111 -0
- package/dist/types/google.d.cts +48 -0
- package/dist/types/google.jsr.d.cts +72 -0
- package/dist/types/index.d.cts +109 -0
- package/dist/types/leaflet-auto.d.cts +4 -0
- package/dist/types/leaflet-auto.jsr.d.cts +2 -0
- package/dist/types/leaflet.d.cts +39 -0
- package/dist/types/leaflet.jsr.d.cts +15 -0
- package/dist/types/mapbox.d.cts +50 -0
- package/dist/types/mapbox.jsr.d.cts +5 -0
- package/dist/types/maplibre.d.cts +54 -0
- package/dist/types/maplibre.jsr.d.cts +92 -0
- package/dist/types/openlayers.d.cts +23 -0
- package/dist/types/openlayers.jsr.d.cts +42 -0
- package/dist/types/presets.d.cts +70 -0
- package/dist/types/turf.d.cts +33 -0
- package/dist/types/turf.jsr.d.cts +46 -0
- package/dist/types/wasm.d.cts +42 -0
- package/dist/web.cjs +231 -0
- package/package.json +198 -4
- package/src/browser.js +15 -0
- package/src/bun.js +4 -0
- package/src/cli-lib.js +160 -0
- package/src/cli.js +7 -0
- package/src/core.js +268 -0
- package/src/deckgl.js +176 -0
- package/src/deno.js +12 -0
- package/src/error.js +15 -0
- package/src/fast.js +179 -0
- package/src/flexible.js +283 -0
- package/src/google.js +70 -0
- package/src/leaflet-auto.js +11 -0
- package/src/leaflet.js +44 -0
- package/src/mapbox.js +10 -0
- package/src/maplibre.js +57 -0
- package/src/node.js +17 -0
- package/src/openlayers.js +172 -0
- package/src/presets.js +242 -0
- package/src/text.js +111 -0
- package/src/turf.js +80 -0
- package/src/wasm-bytes.js +2 -0
- package/src/wasm.js +235 -0
- package/src/web.js +9 -0
- package/types/cli.d.ts +2 -0
- package/types/deckgl.d.ts +72 -0
- package/types/flexible.d.ts +92 -0
- package/types/geojson.jsr.d.ts +111 -0
- package/types/google.d.ts +48 -0
- package/types/google.jsr.d.ts +72 -0
- package/types/index.d.ts +109 -0
- package/types/leaflet-auto.d.ts +4 -0
- package/types/leaflet-auto.jsr.d.ts +2 -0
- package/types/leaflet.d.ts +39 -0
- package/types/leaflet.jsr.d.ts +15 -0
- package/types/mapbox.d.ts +50 -0
- package/types/mapbox.jsr.d.ts +5 -0
- package/types/maplibre.d.ts +54 -0
- package/types/maplibre.jsr.d.ts +92 -0
- package/types/openlayers.d.ts +23 -0
- package/types/openlayers.jsr.d.ts +42 -0
- package/types/presets.d.ts +70 -0
- package/types/turf.d.ts +33 -0
- package/types/turf.jsr.d.ts +46 -0
- package/types/wasm.d.ts +42 -0
- package/wasm/polytini.wasm +0 -0
package/src/cli-lib.js
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
// The polytini command line, minus the part that runs it (src/cli.js).
|
|
2
|
+
// No dependencies, and only node: built-ins that Node, Bun and Deno all
|
|
3
|
+
// have, so the same code runs under each.
|
|
4
|
+
import { readFileSync } from 'node:fs';
|
|
5
|
+
import process from 'node:process';
|
|
6
|
+
import { encode, decode, PolylineError } from './web.js';
|
|
7
|
+
|
|
8
|
+
// Kept in sync with package.json and jsr.json by test/cli.test.js.
|
|
9
|
+
export const VERSION = '0.1.1';
|
|
10
|
+
|
|
11
|
+
const HELP = `polytini ${VERSION}: encode and decode Google encoded polylines
|
|
12
|
+
|
|
13
|
+
Usage:
|
|
14
|
+
polytini encode [input] [options]
|
|
15
|
+
polytini decode [input] [options]
|
|
16
|
+
|
|
17
|
+
Input is the argument, --file <path>, or stdin. Quote polylines on the
|
|
18
|
+
command line: they can contain \\ \` | and other shell characters.
|
|
19
|
+
|
|
20
|
+
encode reads JSON ([[lat, lng], ...], or GeoJSON), CSV with a header, or
|
|
21
|
+
"lat,lng" lines, and prints one polyline per line.
|
|
22
|
+
decode reads one polyline per line and prints coordinates.
|
|
23
|
+
|
|
24
|
+
Options:
|
|
25
|
+
-p, --precision <n> decimal places, 0 to 15 (default 5; OSRM polyline6
|
|
26
|
+
and Valhalla use 6)
|
|
27
|
+
--lnglat coordinates are [lng, lat], like GeoJSON (GeoJSON
|
|
28
|
+
input is always read that way)
|
|
29
|
+
--no-strict accept malformed input instead of failing
|
|
30
|
+
-f, --format <fmt> decode output: json (default), geojson, csv or lines
|
|
31
|
+
--file <path> read input from a file
|
|
32
|
+
-h, --help show this help
|
|
33
|
+
-v, --version show the version
|
|
34
|
+
|
|
35
|
+
Examples:
|
|
36
|
+
polytini decode '_p~iF~ps|U_ulLnnqC_mqNvxq\`@'
|
|
37
|
+
polytini decode -p 6 -f geojson --file route.txt
|
|
38
|
+
echo '[[38.5,-120.2],[40.7,-120.95]]' | polytini encode
|
|
39
|
+
polytini encode --file points.csv
|
|
40
|
+
`;
|
|
41
|
+
|
|
42
|
+
export function parseArgs(argv) {
|
|
43
|
+
const a = { precision: 5, order: 'latlng', strict: true, format: 'json', rest: [] };
|
|
44
|
+
for (let i = 0; i < argv.length; i++) {
|
|
45
|
+
const x = argv[i], value = () => argv[++i] ?? die(`${x} needs a value`);
|
|
46
|
+
if (x == '-h' || x == '--help') a.help = true;
|
|
47
|
+
else if (x == '-v' || x == '--version') a.version = true;
|
|
48
|
+
else if (x == '-p' || x == '--precision') a.precision = Number(value());
|
|
49
|
+
else if (x.startsWith('--precision=')) a.precision = Number(x.slice(12));
|
|
50
|
+
else if (x == '--lnglat') a.order = 'lnglat';
|
|
51
|
+
else if (x == '--no-strict') a.strict = false;
|
|
52
|
+
else if (x == '-f' || x == '--format') a.format = value();
|
|
53
|
+
else if (x.startsWith('--format=')) a.format = x.slice(9);
|
|
54
|
+
else if (x == '--file') a.file = value();
|
|
55
|
+
else if (x.startsWith('-') && x.length > 1) die(`unknown option ${x}`);
|
|
56
|
+
else a.rest.push(x);
|
|
57
|
+
}
|
|
58
|
+
return a;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
class Usage extends Error {}
|
|
62
|
+
const die = (m) => {
|
|
63
|
+
throw new Usage(m);
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
// Numbers from one CSV or "lat,lng" line: commas, semicolons, tabs or spaces.
|
|
67
|
+
const cells = (line) => line.trim().split(/\s*[,;\t]\s*|\s+/);
|
|
68
|
+
|
|
69
|
+
/** Parses encode input into lines of [a, b] tuples in the given order. */
|
|
70
|
+
export function readPoints(text, order) {
|
|
71
|
+
const t = text.trim();
|
|
72
|
+
if (!t) return [[]];
|
|
73
|
+
if (t[0] == '[' || t[0] == '{') {
|
|
74
|
+
const j = JSON.parse(t);
|
|
75
|
+
if (Array.isArray(j)) return Array.isArray(j[0]?.[0]) ? j : [j];
|
|
76
|
+
// GeoJSON: every LineString, MultiLineString part and polygon ring.
|
|
77
|
+
const out = [], flip = (c) => (order == 'lnglat' ? c : c.map(([x, y]) => [y, x]));
|
|
78
|
+
const walk = (g) => {
|
|
79
|
+
if (!g) return;
|
|
80
|
+
if (g.type == 'Feature') walk(g.geometry);
|
|
81
|
+
else if (g.type == 'FeatureCollection') g.features.forEach(walk);
|
|
82
|
+
else if (g.type == 'GeometryCollection') g.geometries.forEach(walk);
|
|
83
|
+
else if (g.type == 'LineString') out.push(flip(g.coordinates));
|
|
84
|
+
else if (g.type == 'MultiLineString' || g.type == 'Polygon') g.coordinates.forEach((c) => out.push(flip(c)));
|
|
85
|
+
else if (g.type == 'MultiPolygon') g.coordinates.forEach((p) => p.forEach((c) => out.push(flip(c))));
|
|
86
|
+
};
|
|
87
|
+
walk(j);
|
|
88
|
+
if (!out.length) die('no LineString in the GeoJSON input');
|
|
89
|
+
return out;
|
|
90
|
+
}
|
|
91
|
+
// CSV or lines. A header row picks the columns by name; otherwise the
|
|
92
|
+
// first two columns are lat, lng (or lng, lat with --lnglat).
|
|
93
|
+
const rows = t.split(/\r?\n/).filter((l) => l.trim());
|
|
94
|
+
let ia = 0, ib = 1;
|
|
95
|
+
const head = cells(rows[0]).map((c) => c.toLowerCase().replace(/^"|"$/g, ''));
|
|
96
|
+
if (head.some((c) => c && isNaN(c))) {
|
|
97
|
+
rows.shift();
|
|
98
|
+
const find = (...names) => head.findIndex((c) => names.includes(c));
|
|
99
|
+
const lat = find('lat', 'latitude', 'y'), lng = find('lng', 'lon', 'long', 'longitude', 'x');
|
|
100
|
+
if (lat < 0 || lng < 0) die('CSV header needs lat and lng (or lon, longitude) columns');
|
|
101
|
+
[ia, ib] = order == 'lnglat' ? [lng, lat] : [lat, lng];
|
|
102
|
+
}
|
|
103
|
+
return [
|
|
104
|
+
rows.map((r, i) => {
|
|
105
|
+
const c = cells(r);
|
|
106
|
+
if (c.length < 2) die(`line ${i + 1}: expected two numbers, got ${JSON.stringify(r.trim())}`);
|
|
107
|
+
return [Number(c[ia]), Number(c[ib])];
|
|
108
|
+
}),
|
|
109
|
+
];
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Formats decoded lines. */
|
|
113
|
+
export function format(lines, fmt, order) {
|
|
114
|
+
const [a, b] = order == 'lnglat' ? ['lng', 'lat'] : ['lat', 'lng'];
|
|
115
|
+
const many = lines.length > 1;
|
|
116
|
+
switch (fmt) {
|
|
117
|
+
case 'json':
|
|
118
|
+
return JSON.stringify(many ? lines : lines[0]);
|
|
119
|
+
case 'geojson': {
|
|
120
|
+
const geo = (l) => ({ type: 'LineString', coordinates: order == 'lnglat' ? l : l.map(([x, y]) => [y, x]) });
|
|
121
|
+
return JSON.stringify(many ? { type: 'FeatureCollection', features: lines.map((l) => ({ type: 'Feature', properties: {}, geometry: geo(l) })) } : geo(lines[0]));
|
|
122
|
+
}
|
|
123
|
+
case 'csv':
|
|
124
|
+
return [many ? `line,${a},${b}` : `${a},${b}`, ...lines.flatMap((l, i) => l.map((p) => (many ? `${i},` : '') + p.join(',')))].join('\n');
|
|
125
|
+
case 'lines':
|
|
126
|
+
return lines.map((l) => l.map((p) => p.join(',')).join('\n')).join('\n\n');
|
|
127
|
+
default:
|
|
128
|
+
die(`unknown format ${fmt}: use json, geojson, csv or lines`);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Runs one command and returns the output text (no trailing newline). */
|
|
133
|
+
export function run(argv, stdin = () => '') {
|
|
134
|
+
const a = parseArgs(argv);
|
|
135
|
+
if (a.help) return HELP.trimEnd();
|
|
136
|
+
if (a.version) return VERSION;
|
|
137
|
+
const [cmd, arg, extra] = a.rest;
|
|
138
|
+
if (cmd != 'encode' && cmd != 'decode') die(cmd ? `unknown command ${cmd}` : 'expected a command: encode or decode');
|
|
139
|
+
if (extra != null) die('expected one input argument; quote it');
|
|
140
|
+
if (arg != null && a.file) die('give an argument or --file, not both');
|
|
141
|
+
const input = arg ?? (a.file ? readFileSync(a.file, 'utf8') : stdin());
|
|
142
|
+
const o = { precision: a.precision, order: a.order, strict: a.strict };
|
|
143
|
+
if (cmd == 'encode') return readPoints(input, a.order).map((l) => encode(l, o)).join('\n');
|
|
144
|
+
// Polylines never contain whitespace, so one per line, blank lines skipped.
|
|
145
|
+
const strs = input.split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
|
|
146
|
+
return format(strs.length ? strs.map((s) => decode(s, o)) : [[]], a.format, a.order);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Runs the CLI with process.argv and stdin, and sets the exit code. */
|
|
150
|
+
export function main() {
|
|
151
|
+
try {
|
|
152
|
+
const out = run(process.argv.slice(2), () => readFileSync(0, 'utf8'));
|
|
153
|
+
process.stdout.write(out + '\n');
|
|
154
|
+
} catch (e) {
|
|
155
|
+
const usage = e instanceof Usage;
|
|
156
|
+
process.stderr.write(`polytini: ${e instanceof PolylineError || usage || e instanceof SyntaxError ? e.message : e?.stack ?? e}\n`);
|
|
157
|
+
if (usage) process.stderr.write('Run polytini --help for usage.\n');
|
|
158
|
+
process.exitCode = usage ? 2 : 1;
|
|
159
|
+
}
|
|
160
|
+
}
|
package/src/cli.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The polytini command. npx/bunx/pnpm dlx/yarn dlx run this through the
|
|
3
|
+
// package's bin, and `deno run jsr:@duoquote/polytini/cli` runs it directly.
|
|
4
|
+
/* @ts-self-types="../types/cli.d.ts" */
|
|
5
|
+
import { main } from './cli-lib.js';
|
|
6
|
+
|
|
7
|
+
main();
|
package/src/core.js
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
// The portable codec. Every entry point builds on this file, and the web
|
|
2
|
+
// entry is only this file. It uses no Node, Bun or Deno globals.
|
|
3
|
+
//
|
|
4
|
+
// Each public function has a fast loop for the common case (2D points,
|
|
5
|
+
// precision up to 6, valid input) and falls back to the exact `slow*`
|
|
6
|
+
// functions for anything else: other dimensions, huge values, objects,
|
|
7
|
+
// and every kind of bad input. The slow functions do the same Number math
|
|
8
|
+
// as Google's algorithm description, so both paths give identical output.
|
|
9
|
+
|
|
10
|
+
import { PolylineError, fail } from './error.js';
|
|
11
|
+
|
|
12
|
+
export { PolylineError, fail };
|
|
13
|
+
|
|
14
|
+
// Options of the current call, set by opts() and read right after it, so the
|
|
15
|
+
// hot paths never allocate. A plain object on purpose: writing exported
|
|
16
|
+
// module-level `let` bindings cost about 30 ns per call on V8, this costs
|
|
17
|
+
// nothing measurable.
|
|
18
|
+
export const st = { swap: false, strict: true, dims: 2, zf: 1e5 };
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Parses options, fills `st` and returns the factor. Kept tiny so V8 inlines
|
|
22
|
+
* it into every caller; with the object branch in the same function it
|
|
23
|
+
* wasn't inlined, and decoding 10 points got about 25% slower.
|
|
24
|
+
*/
|
|
25
|
+
export function opts(o) {
|
|
26
|
+
st.swap = false;
|
|
27
|
+
st.strict = true;
|
|
28
|
+
st.dims = 2;
|
|
29
|
+
return o && typeof o == 'object' ? objOpts(o) : (st.zf = o == null ? 1e5 : pow(o));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function objOpts(o) {
|
|
33
|
+
const { order, dimensions: d } = o;
|
|
34
|
+
if (order == 'lnglat') st.swap = true;
|
|
35
|
+
else if (order != null && order != 'latlng') bad('order');
|
|
36
|
+
if (o.strict === false) st.strict = false;
|
|
37
|
+
if (d != null) st.dims = d >= 1 && d <= 16 && d % 1 == 0 ? d : bad('dimensions');
|
|
38
|
+
const f = o.factor != null ? num(o.factor) : pow(o.precision ?? 5);
|
|
39
|
+
st.zf = o.zFactor != null ? num(o.zFactor) : f;
|
|
40
|
+
return f;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const bad = (name) => fail('option', 'Invalid ' + name);
|
|
44
|
+
const num = (f) => (f > 0 && f < 1 / 0 ? f : bad('factor'));
|
|
45
|
+
const pow = (p) => (typeof p == 'number' && p >= 0 && p <= 15 && p % 1 == 0 ? 10 ** p : bad('precision'));
|
|
46
|
+
|
|
47
|
+
// Scaled values below this fit the 32-bit math of the fast loops, deltas and
|
|
48
|
+
// zigzag included. It covers every valid coordinate up to precision 6.
|
|
49
|
+
export const LIMIT = 2 ** 29;
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Exact decoder for any input. Returns points, or a flat Float64Array.
|
|
53
|
+
* Strict mode throws on invalid characters, on a string that ends inside a
|
|
54
|
+
* value or a point, and on values past 2^53. Otherwise it skips invalid
|
|
55
|
+
* characters and drops an incomplete last point.
|
|
56
|
+
*/
|
|
57
|
+
export function slowDecode(str, f, flat) {
|
|
58
|
+
if (typeof str != 'string') fail('input', 'Expected a string');
|
|
59
|
+
const { dims: d, strict, zf } = st, sw = st.swap && d > 1, values = [];
|
|
60
|
+
let v = 0, scale = 1, i = 0, c;
|
|
61
|
+
for (; i < str.length; i++) {
|
|
62
|
+
c = str.charCodeAt(i) - 63;
|
|
63
|
+
if (c < 0 || c > 63) {
|
|
64
|
+
if (strict) fail('char', 'Invalid character', i);
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
v += (c & 31) * scale;
|
|
68
|
+
scale *= 32;
|
|
69
|
+
if (v > 2 ** 53 && strict) fail('overflow', 'Value too large', i);
|
|
70
|
+
if (c < 32) {
|
|
71
|
+
values.push(v % 2 ? -(v + 1) / 2 : v / 2);
|
|
72
|
+
v = 0;
|
|
73
|
+
scale = 1;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
if (strict && (scale > 1 || values.length % d)) fail('truncated', 'Truncated', i);
|
|
77
|
+
const n = (values.length / d) | 0, sum = Array(d).fill(0), out = flat ? new Float64Array(n * d) : Array(n);
|
|
78
|
+
for (let j = 0, k = 0; j < n; j++) {
|
|
79
|
+
const p = flat ? out : Array(d);
|
|
80
|
+
for (let a = 0; a < d; a++, k++) {
|
|
81
|
+
sum[a] += values[k];
|
|
82
|
+
p[(flat ? k - a : 0) + (sw && a < 2 ? 1 - a : a)] = sum[a] / (a < 2 ? f : zf);
|
|
83
|
+
}
|
|
84
|
+
if (!flat) out[j] = p;
|
|
85
|
+
}
|
|
86
|
+
return out;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Exact encoder for any input: [a, b] tuples (or any array-like), objects
|
|
91
|
+
* with lat/latitude and lng/lon/longitude, or a flat array of numbers.
|
|
92
|
+
* Rounds half away from zero, like Google's reference implementation.
|
|
93
|
+
*/
|
|
94
|
+
export function slowEncode(points, f, flat) {
|
|
95
|
+
if (points == null || !(points.length >= 0)) fail('input', 'Expected an array');
|
|
96
|
+
const { dims: d, strict, zf } = st, sw = st.swap && d > 1, last = Array(d).fill(0), n = flat ? points.length / d : points.length;
|
|
97
|
+
if (n % 1 && strict) fail('input', 'Length not a multiple of ' + d);
|
|
98
|
+
let s = '';
|
|
99
|
+
for (let i = 0; i < (n | 0); i++) {
|
|
100
|
+
const p = flat ? 0 : points[i];
|
|
101
|
+
for (let a = 0; a < d; a++) {
|
|
102
|
+
const b = sw && a < 2 ? 1 - a : a;
|
|
103
|
+
let x = flat ? points[i * d + b] : p == null ? p : p.length >= 0 ? p[b] : a ? (a > 1 ? p.alt ?? p.altitude : p.lng ?? p.lon ?? p.longitude) : p.lat ?? p.latitude;
|
|
104
|
+
// null and undefined are missing, not 0. Numeric strings are numbers.
|
|
105
|
+
x = x == null ? NaN : +x * (a < 2 ? f : zf);
|
|
106
|
+
if (!(x - x == 0)) {
|
|
107
|
+
if (strict) fail('coordinate', 'Invalid coordinate', i);
|
|
108
|
+
x = 0;
|
|
109
|
+
}
|
|
110
|
+
x = Math.sign(x) * Math.round(Math.abs(x));
|
|
111
|
+
let z = x - last[a];
|
|
112
|
+
last[a] = x;
|
|
113
|
+
z = z < 0 ? -z * 2 - 1 : z * 2;
|
|
114
|
+
if (z > 2 ** 53 && strict) fail('overflow', 'Value too large', i);
|
|
115
|
+
for (; z >= 32; z = Math.floor(z / 32)) s += String.fromCharCode((z % 32) + 95);
|
|
116
|
+
s += String.fromCharCode(z + 63);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return s;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const decodeWith = (str, o, flat) => {
|
|
123
|
+
const f = opts(o), out = st.dims == 2 && typeof str == 'string' && decodeLoop(str, f, st.swap, flat);
|
|
124
|
+
return out ? (st.swap && !flat ? flip(out) : out) : slowDecode(str, f, flat);
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
// The fast loops always build [lat, lng]; lnglat output is flipped in place
|
|
128
|
+
// afterwards. A per-point `swap ? [b, a] : [a, b]` cost the default order
|
|
129
|
+
// about 5%, and the extra pass is small next to allocating the points.
|
|
130
|
+
export const flip = (out) => {
|
|
131
|
+
for (const p of out) {
|
|
132
|
+
const t = p[0];
|
|
133
|
+
p[0] = p[1];
|
|
134
|
+
p[1] = t;
|
|
135
|
+
}
|
|
136
|
+
return out;
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
/** Decodes to [lat, lng] tuples. */
|
|
140
|
+
export const decode = (str, o) => decodeWith(str, o, 0);
|
|
141
|
+
|
|
142
|
+
/** Decodes to a flat Float64Array: [lat0, lng0, lat1, lng1, ...]. */
|
|
143
|
+
export const decodeFlat = (str, o) => decodeWith(str, o, 1);
|
|
144
|
+
|
|
145
|
+
// The 2D fast loop, or null when the input needs slowDecode. A separate,
|
|
146
|
+
// self-contained function because V8 optimized it better that way: with the
|
|
147
|
+
// option and type checks in the same function, 10 point lines decoded about
|
|
148
|
+
// 15% slower.
|
|
149
|
+
export function decodeLoop(str, f, sw, flat) {
|
|
150
|
+
const len = str.length, a = +sw;
|
|
151
|
+
let i = 0, n = 0, lat = 0, lng = 0, bad = 0, c, v, s, out;
|
|
152
|
+
if (flat) {
|
|
153
|
+
// Every value ends with exactly one character below code 95.
|
|
154
|
+
for (; i < len; i++) n += (str.charCodeAt(i) - 95) >>> 31;
|
|
155
|
+
out = new Float64Array(n & ~1);
|
|
156
|
+
i = n = 0;
|
|
157
|
+
} else out = len < 64 ? [] : Array(len >> 1);
|
|
158
|
+
// One value is one or more 5-bit chunks. `bad` collects every character
|
|
159
|
+
// code: anything outside 0..63 after the -63 shift sets a high bit, and
|
|
160
|
+
// so does a 7th chunk in one value (25 - s < 0). NaN past the end of
|
|
161
|
+
// a truncated string ends the value and leaves i past len.
|
|
162
|
+
while (i < len) {
|
|
163
|
+
c = str.charCodeAt(i++) - 63;
|
|
164
|
+
bad |= c;
|
|
165
|
+
v = c & 31;
|
|
166
|
+
for (s = 5; c >= 32; s += 5) {
|
|
167
|
+
c = str.charCodeAt(i++) - 63;
|
|
168
|
+
bad |= c | (25 - s);
|
|
169
|
+
v |= (c & 31) << s;
|
|
170
|
+
}
|
|
171
|
+
lat += (v >>> 1) ^ -(v & 1);
|
|
172
|
+
c = str.charCodeAt(i++) - 63;
|
|
173
|
+
bad |= c;
|
|
174
|
+
v = c & 31;
|
|
175
|
+
for (s = 5; c >= 32; s += 5) {
|
|
176
|
+
c = str.charCodeAt(i++) - 63;
|
|
177
|
+
bad |= c | (25 - s);
|
|
178
|
+
v |= (c & 31) << s;
|
|
179
|
+
}
|
|
180
|
+
lng += (v >>> 1) ^ -(v & 1);
|
|
181
|
+
if (flat) {
|
|
182
|
+
out[n + a] = lat / f;
|
|
183
|
+
out[n + 1 - a] = lng / f;
|
|
184
|
+
n += 2;
|
|
185
|
+
} else out[n++] = [lat / f, lng / f];
|
|
186
|
+
}
|
|
187
|
+
if (bad & ~63 || i != len) return null;
|
|
188
|
+
if (out.length != n) out.length = n;
|
|
189
|
+
return out;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// Encoded characters for every zigzag value below 1024, so one or two
|
|
193
|
+
// characters cost one string concatenation instead of a loop. Built by a
|
|
194
|
+
// pure call, so bundles that never encode can drop it.
|
|
195
|
+
const CHARS = /* @__PURE__ */ Array.from({ length: 1024 }, (_, z) => chars(z));
|
|
196
|
+
|
|
197
|
+
export function chars(z) {
|
|
198
|
+
let s = '';
|
|
199
|
+
for (; z >= 32; z >>>= 5) s += String.fromCharCode((z & 31) + 95);
|
|
200
|
+
return s + String.fromCharCode(z + 63);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const encodeWith = (src, o, flat) => {
|
|
204
|
+
const f = opts(o);
|
|
205
|
+
return (st.dims == 2 && f <= 1e6 && (flat ? src != null && !(src.length % 2) : Array.isArray(src)) ? encodeLoop(src, f, +st.swap, flat) : null) ?? slowEncode(src, f, flat);
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
/** Encodes [lat, lng] tuples, or objects with lat and lng. */
|
|
209
|
+
export const encode = (points, o) => encodeWith(points, o, 0);
|
|
210
|
+
|
|
211
|
+
/** Encodes a flat array of numbers: [lat0, lng0, lat1, lng1, ...]. */
|
|
212
|
+
export const encodeFlat = (values, o) => encodeWith(values, o, 1);
|
|
213
|
+
|
|
214
|
+
// The 2D fast loop, or null when the input needs slowEncode.
|
|
215
|
+
function encodeLoop(src, f, a, flat) {
|
|
216
|
+
const n = flat ? src.length >> 1 : src.length;
|
|
217
|
+
let s = '', i = 0, la = 0, lb = 0, x, y, p, q, z, pt;
|
|
218
|
+
try {
|
|
219
|
+
for (; i < n; i++) {
|
|
220
|
+
if (flat) {
|
|
221
|
+
x = src[i * 2 + a];
|
|
222
|
+
y = src[i * 2 + 1 - a];
|
|
223
|
+
} else {
|
|
224
|
+
pt = src[i];
|
|
225
|
+
x = pt[a];
|
|
226
|
+
y = pt[1 - a];
|
|
227
|
+
}
|
|
228
|
+
// Anything but numbers goes the slow way, which coerces numeric
|
|
229
|
+
// strings and rejects null. The range check is also false for NaN.
|
|
230
|
+
if (typeof x != 'number' || typeof y != 'number' || !((x *= f) < LIMIT && x > -LIMIT && (y *= f) < LIMIT && y > -LIMIT)) return null;
|
|
231
|
+
// Round half away from zero. floor(|x| + 0.5) is exact here except for
|
|
232
|
+
// |x| = 0.49999999999999994, where the addition rounds up to 1, so any
|
|
233
|
+
// |x| < 0.5 is set to 0 afterwards. Math.round would be exact on its own,
|
|
234
|
+
// but it measured 40% slower on JavaScriptCore.
|
|
235
|
+
p = x < 0 ? -((0.5 - x) | 0) : (x + 0.5) | 0;
|
|
236
|
+
q = y < 0 ? -((0.5 - y) | 0) : (y + 0.5) | 0;
|
|
237
|
+
if (x < 0.5 && x > -0.5) p = 0;
|
|
238
|
+
if (y < 0.5 && y > -0.5) q = 0;
|
|
239
|
+
z = p - la;
|
|
240
|
+
z = (z << 1) ^ (z >> 31);
|
|
241
|
+
s += z < 1024 ? CHARS[z] : chars(z);
|
|
242
|
+
z = q - lb;
|
|
243
|
+
z = (z << 1) ^ (z >> 31);
|
|
244
|
+
s += z < 1024 ? CHARS[z] : chars(z);
|
|
245
|
+
la = p;
|
|
246
|
+
lb = q;
|
|
247
|
+
}
|
|
248
|
+
} catch {
|
|
249
|
+
// A null point: let slowEncode report it.
|
|
250
|
+
return null;
|
|
251
|
+
}
|
|
252
|
+
return s;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
// Helpers built on top of an entry point's own decode and encode, so every
|
|
256
|
+
// entry uses its fastest paths. Entries call these with /* @__PURE__ */, so
|
|
257
|
+
// bundlers drop the ones nobody imports.
|
|
258
|
+
const lngLat = (o) => ({ ...(typeof o == 'number' ? { precision: o } : o), order: 'lnglat' });
|
|
259
|
+
|
|
260
|
+
/** {lat, lng} objects, the shape Google Maps and Leaflet take. */
|
|
261
|
+
export const latLngs = (decode) => (str, o) => decode(str, o).map(([lat, lng]) => ({ lat, lng }));
|
|
262
|
+
|
|
263
|
+
export const toGeo = (decode) => (str, o) => ({ type: 'LineString', coordinates: decode(str, lngLat(o)) });
|
|
264
|
+
|
|
265
|
+
export const fromGeo = (encode) => (g, o) => {
|
|
266
|
+
if (g?.type == 'Feature') g = g.geometry;
|
|
267
|
+
return g?.type == 'LineString' ? encode(g.coordinates, lngLat(o)) : fail('input', 'Expected a LineString');
|
|
268
|
+
};
|
package/src/deckgl.js
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
// deck.gl: encoded polylines straight into deck.gl's binary data format, one
|
|
2
|
+
// typed array for all lines and no array per point.
|
|
3
|
+
//
|
|
4
|
+
// import { PathLayer } from '@deck.gl/layers';
|
|
5
|
+
// import { binaryPaths } from '@duoquote/polytini/deckgl';
|
|
6
|
+
// const data = binaryPaths(routes.map((r) => r.geometry), { precision: 6 });
|
|
7
|
+
// new PathLayer({ id: 'routes', data, _pathType: 'open', getWidth: 3 });
|
|
8
|
+
//
|
|
9
|
+
// The result has the shape deck.gl 9 documents for PathLayer, TripsLayer and
|
|
10
|
+
// SolidPolygonLayer:
|
|
11
|
+
// { length, startIndices, attributes: { getPath: { value, size } } }
|
|
12
|
+
// where startIndices has length + 1 entries, the last one the vertex count,
|
|
13
|
+
// and value holds [lng, lat] or [lng, lat, z] per vertex. Positions always
|
|
14
|
+
// come out as [lng, lat], whatever `order` the options or a preset say,
|
|
15
|
+
// because that is what deck.gl reads.
|
|
16
|
+
//
|
|
17
|
+
// Each string is decoded twice over its characters: a first pass over all
|
|
18
|
+
// strings counts the values (every value ends with exactly one character
|
|
19
|
+
// below code 95), so one buffer of the right size is allocated, and a second
|
|
20
|
+
// pass decodes into it. Strings the fast loop does not take (bad characters,
|
|
21
|
+
// a cut-off value, values of more than 30 bits) go through polytini's exact
|
|
22
|
+
// decoder, which throws a PolylineError in strict mode, the default.
|
|
23
|
+
//
|
|
24
|
+
// PolygonLayer, the composite layer, does not take binary data in deck.gl
|
|
25
|
+
// 9.4: it calls getPolygon on every row to build its outlines, and binary
|
|
26
|
+
// data has no rows (it fails with "Cannot read properties of undefined").
|
|
27
|
+
// For filled polygons with outlines, use a SolidPolygonLayer with
|
|
28
|
+
// binaryPolygons data plus a PathLayer with the same buffer as getPath:
|
|
29
|
+
// new PathLayer({ data: { ...polys, attributes: { getPath: polys.attributes.getPolygon } }, _pathType: 'open' })
|
|
30
|
+
//
|
|
31
|
+
// No deck.gl code is imported.
|
|
32
|
+
/* @ts-self-types="../types/deckgl.d.ts" */
|
|
33
|
+
import { decodeFlat } from './web.js';
|
|
34
|
+
import { opts, st, fail } from './core.js';
|
|
35
|
+
|
|
36
|
+
// Decodes a 2D string into out[2k], out[2k + 1] as [lng, lat] from vertex k.
|
|
37
|
+
// Returns the number of vertices, or -1 when the string needs the exact
|
|
38
|
+
// decoder. Writes past the end of a typed array are dropped, and anything
|
|
39
|
+
// written for a bad string is overwritten afterwards.
|
|
40
|
+
function fill2(str, out, k, f) {
|
|
41
|
+
const len = str.length, start = k;
|
|
42
|
+
let i = 0, lat = 0, lng = 0, bad = 0, c, v, s;
|
|
43
|
+
k *= 2;
|
|
44
|
+
while (i < len) {
|
|
45
|
+
c = str.charCodeAt(i++) - 63;
|
|
46
|
+
bad |= c;
|
|
47
|
+
v = c & 31;
|
|
48
|
+
for (s = 5; c >= 32; s += 5) {
|
|
49
|
+
c = str.charCodeAt(i++) - 63;
|
|
50
|
+
bad |= c;
|
|
51
|
+
v |= (c & 31) << s;
|
|
52
|
+
}
|
|
53
|
+
bad |= 30 - s;
|
|
54
|
+
lat += (v >>> 1) ^ -(v & 1);
|
|
55
|
+
c = str.charCodeAt(i++) - 63;
|
|
56
|
+
bad |= c;
|
|
57
|
+
v = c & 31;
|
|
58
|
+
for (s = 5; c >= 32; s += 5) {
|
|
59
|
+
c = str.charCodeAt(i++) - 63;
|
|
60
|
+
bad |= c;
|
|
61
|
+
v |= (c & 31) << s;
|
|
62
|
+
}
|
|
63
|
+
bad |= 30 - s;
|
|
64
|
+
lng += (v >>> 1) ^ -(v & 1);
|
|
65
|
+
out[k++] = lng / f;
|
|
66
|
+
out[k++] = lat / f;
|
|
67
|
+
}
|
|
68
|
+
return bad & ~63 || i != len ? -1 : k / 2 - start;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// The same for d values per point (3 or 4): [lng, lat] plus z when size is
|
|
72
|
+
// 3, and the last value into ts when ts is given.
|
|
73
|
+
function fillN(str, out, ts, k, d, size, f, zf) {
|
|
74
|
+
const len = str.length, start = k, sum = [0, 0, 0, 0];
|
|
75
|
+
let i = 0, bad = 0, a, c, v, s, j;
|
|
76
|
+
while (i < len) {
|
|
77
|
+
for (a = 0; a < d; a++) {
|
|
78
|
+
c = str.charCodeAt(i++) - 63;
|
|
79
|
+
bad |= c;
|
|
80
|
+
v = c & 31;
|
|
81
|
+
for (s = 5; c >= 32; s += 5) {
|
|
82
|
+
c = str.charCodeAt(i++) - 63;
|
|
83
|
+
bad |= c;
|
|
84
|
+
v |= (c & 31) << s;
|
|
85
|
+
}
|
|
86
|
+
bad |= 30 - s;
|
|
87
|
+
sum[a] += (v >>> 1) ^ -(v & 1);
|
|
88
|
+
}
|
|
89
|
+
j = k * size;
|
|
90
|
+
out[j] = sum[1] / f;
|
|
91
|
+
out[j + 1] = sum[0] / f;
|
|
92
|
+
if (size == 3) out[j + 2] = sum[2] / zf;
|
|
93
|
+
if (ts) ts[k] = sum[d - 1] / zf;
|
|
94
|
+
k++;
|
|
95
|
+
}
|
|
96
|
+
return bad & ~63 || i != len ? -1 : k - start;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// The exact decoder, for strings the fast loops gave up on. It returns at
|
|
100
|
+
// most as many points as the first pass counted, so they fit.
|
|
101
|
+
function slow(str, o, out, ts, k, d, size) {
|
|
102
|
+
const flat = decodeFlat(str, o), n = flat.length / d;
|
|
103
|
+
for (let p = 0; p < n; p++, k++) {
|
|
104
|
+
for (let a = 0; a < size; a++) out[k * size + a] = flat[p * d + a];
|
|
105
|
+
if (ts) ts[k] = flat[p * d + d - 1];
|
|
106
|
+
}
|
|
107
|
+
return n;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function build(encoded, o, polygons) {
|
|
111
|
+
const list = typeof encoded == 'string' ? [encoded] : encoded;
|
|
112
|
+
if (!Array.isArray(list)) fail('input', 'Expected a string or an array of strings');
|
|
113
|
+
const f = opts(o), { dims: d, zf } = st, time = !polygons && o != null && typeof o == 'object' && !!o.timestamps;
|
|
114
|
+
const size = time ? d - 1 : d;
|
|
115
|
+
if (size < 2 || size > 3) fail('option', time ? 'timestamps need dimensions 3 or 4' : 'Invalid dimensions for deck.gl: use 2 or 3, or 4 with timestamps');
|
|
116
|
+
const Type = o?.float32 ? Float32Array : Float64Array;
|
|
117
|
+
const n = list.length;
|
|
118
|
+
// Pass 1: an upper bound of the vertex count, exact for valid strings.
|
|
119
|
+
// Polygons get room for one more vertex per ring to close it.
|
|
120
|
+
let max = 0;
|
|
121
|
+
for (let i = 0; i < n; i++) {
|
|
122
|
+
const s = list[i];
|
|
123
|
+
if (typeof s != 'string') fail('input', 'Expected a string', i);
|
|
124
|
+
let values = 0;
|
|
125
|
+
for (let j = 0; j < s.length; j++) values += (s.charCodeAt(j) - 95) >>> 31;
|
|
126
|
+
max += ((values / d) | 0) + (polygons ? 1 : 0);
|
|
127
|
+
}
|
|
128
|
+
const out = new Type(max * size), ts = time ? new Float32Array(max) : null, starts = new Uint32Array(n + 1);
|
|
129
|
+
const exact = { ...(typeof o == 'number' ? { precision: o } : o), order: 'lnglat' };
|
|
130
|
+
// Pass 2: decode each string at the running vertex offset.
|
|
131
|
+
let k = 0;
|
|
132
|
+
for (let i = 0; i < n; i++) {
|
|
133
|
+
const s = list[i];
|
|
134
|
+
starts[i] = k;
|
|
135
|
+
let m = d == 2 ? fill2(s, out, k, f) : fillN(s, out, ts, k, d, size, f, zf);
|
|
136
|
+
if (m < 0) m = slow(s, exact, out, ts, k, d, size);
|
|
137
|
+
if (polygons && m > 0) {
|
|
138
|
+
// Close the ring if the last vertex is not the first.
|
|
139
|
+
const a = k * size, b = (k + m - 1) * size;
|
|
140
|
+
let open = false;
|
|
141
|
+
for (let c = 0; c < size; c++) open ||= out[a + c] !== out[b + c];
|
|
142
|
+
if (open) {
|
|
143
|
+
for (let c = 0; c < size; c++) out[b + size + c] = out[a + c];
|
|
144
|
+
m++;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
k += m;
|
|
148
|
+
}
|
|
149
|
+
starts[n] = k;
|
|
150
|
+
const value = k * size < out.length ? out.subarray(0, k * size) : out;
|
|
151
|
+
const attributes = polygons ? { getPolygon: { value, size } } : { getPath: { value, size } };
|
|
152
|
+
if (ts) attributes.getTimestamps = { value: k < ts.length ? ts.subarray(0, k) : ts, size: 1 };
|
|
153
|
+
return { length: n, startIndices: starts, attributes };
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Binary data for PathLayer and TripsLayer: one path per string. Options:
|
|
158
|
+
* polytini options or a preset, plus `float32` (Float32Array instead of
|
|
159
|
+
* Float64Array) and, for TripsLayer, `timestamps`: the last value of each
|
|
160
|
+
* point (dimensions 3 or 4) goes to attributes.getTimestamps instead of the
|
|
161
|
+
* positions. Timestamps are always a Float32Array: TripsLayer's timestamp
|
|
162
|
+
* attribute is 32-bit, and deck.gl 9.4 drew nothing for a TripsLayer given
|
|
163
|
+
* Float64Array timestamps (checked in test/deckgl.test.js). Keep them small,
|
|
164
|
+
* for example seconds since the start of the trip.
|
|
165
|
+
*/
|
|
166
|
+
export const binaryPaths = (encoded, options) => build(encoded, options, false);
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Binary data for SolidPolygonLayer: one ring per string, closed (the first
|
|
170
|
+
* vertex is repeated at the end when it is not there already). The binary
|
|
171
|
+
* format has no holes. With _normalize: false deck.gl uses the rings as
|
|
172
|
+
* they are, so for extruded polygons they must also be in the layer's
|
|
173
|
+
* _windingOrder; leave _normalize on when the winding is unknown.
|
|
174
|
+
* Options: polytini options or a preset, plus float32.
|
|
175
|
+
*/
|
|
176
|
+
export const binaryPolygons = (encoded, options) => build(encoded, options, true);
|
package/src/deno.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// Deno entry: the core plus the TextEncoder/TextDecoder byte paths in
|
|
2
|
+
// text.js. Deno has no global Buffer, and node:buffer measured slower than
|
|
3
|
+
// the portable core there (see the README), so this doesn't use it.
|
|
4
|
+
/* @ts-self-types="../types/index.d.ts" */
|
|
5
|
+
import { decode, encode } from './text.js';
|
|
6
|
+
import { latLngs, toGeo, fromGeo } from './core.js';
|
|
7
|
+
|
|
8
|
+
export { PolylineError } from './core.js';
|
|
9
|
+
export { decode, decodeFlat, encode, encodeFlat } from './text.js';
|
|
10
|
+
export const decodeLatLng = /* @__PURE__ */ latLngs(decode);
|
|
11
|
+
export const toGeoJSON = /* @__PURE__ */ toGeo(decode);
|
|
12
|
+
export const fromGeoJSON = /* @__PURE__ */ fromGeo(encode);
|
package/src/error.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// The error type every entry point and subpath throws. Its own module, so
|
|
2
|
+
// subpaths that only need the error (like /flexible) don't pull in the
|
|
3
|
+
// Google-format code.
|
|
4
|
+
export class PolylineError extends Error {
|
|
5
|
+
constructor(code, message, index) {
|
|
6
|
+
super(index == null ? message : message + ' at ' + index);
|
|
7
|
+
this.name = 'PolylineError';
|
|
8
|
+
this.code = code;
|
|
9
|
+
this.index = index;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export const fail = (code, message, index) => {
|
|
14
|
+
throw new PolylineError(code, message, index);
|
|
15
|
+
};
|