@vim3d/geojson 0.3.0 → 0.5.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.md CHANGED
@@ -38,7 +38,28 @@ comes out of `maxPositions: 5000` with all 41 polygons kept.
38
38
  in coordinate units (degrees for WGS84). `maxPositions` finds the smallest
39
39
  tolerance that fits the budget. Points are kept; polygons, holes and
40
40
  features that collapse below four positions are dropped.
41
+ - `resampleGeoJSON(input, { topology: true })` (also on `loadGeoJSON`): cuts
42
+ lines and rings into arcs where they meet and simplifies each arc once, so
43
+ a border two neighborhoods share stays identical in both. Only positions
44
+ that match exactly count as shared.
45
+ - `borders(input)`: every line and ring edge once, as a `MultiLineString`, so
46
+ shared borders draw once:
47
+ `toSceneCurves(borders(neighborhoods), origin)`.
41
48
  - `toSceneCurves(input, origin, { elevation })`: lines and polygon rings as
42
49
  `curve` geometries in the Vim3D `world` frame around `origin` (x east, y up,
43
50
  -z north), with each feature's `properties` and `id`.
51
+ - `toScenePoints(input, origin, { elevation })`: every `Point` and
52
+ `MultiPoint` position in the same frame, with its feature's `properties`
53
+ and `id`, for labels, trees and other markers.
54
+ - `toSceneFills(input, origin, { elevation })`: each polygon (each
55
+ `MultiPolygon` part on its own) as a flat, upward-facing `mesh` geometry
56
+ with its holes cut out, triangulated with
57
+ [earcut](https://www.npmjs.com/package/earcut). It has the same
58
+ `positions`/`indices` shape the `geo:mesh` node outputs.
59
+ - `toSceneRibbons(input, origin, { width, widthProperty, elevation })`: each
60
+ line as a flat, upward-facing strip around its centerline, for streets.
61
+ The width is in metres: `properties[widthProperty]` when it is a positive
62
+ number, else `width` (default 1). Corners are mitered up to twice the half
63
+ width and beveled past that, or when a short segment would make the strip
64
+ fold. A line that ends where it starts joins up.
44
65
  - `simplifyLine`, `simplifyRing`, `countPositions`, `bbox`, `eachPosition`.
package/esm/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  export const name = '@vim3d/geojson';
2
2
  export { loadGeoJSON } from './fetch.js';
3
3
  export { bbox, countPositions, eachPosition, resampleGeoJSON } from './resample.js';
4
- export { toSceneCurves } from './scene.js';
4
+ export { toSceneCurves, toSceneFills, toScenePoints, toSceneRibbons } from './scene.js';
5
5
  export { simplifyLine, simplifyRing } from './simplify.js';
6
+ export { borders } from './topology.js';
package/esm/resample.js CHANGED
@@ -1,4 +1,25 @@
1
1
  import { simplifyLine, simplifyRing } from './simplify.js';
2
+ import { buildTopology, simplifyTopology } from './topology.js';
3
+ function area(ring) {
4
+ const [x0, y0] = ring[0];
5
+ let sum = 0;
6
+ for (let i = 2; i < ring.length - 1; i++) {
7
+ sum += (ring[i - 1][0] - x0) * (ring[i][1] - y0) - (ring[i][0] - x0) * (ring[i - 1][1] - y0);
8
+ }
9
+ return sum;
10
+ }
11
+ function simplifier(tolerance, topology) {
12
+ if (!topology)
13
+ return { line: points => simplifyLine(points, tolerance), ring: ring => simplifyRing(ring, tolerance) };
14
+ const rebuild = simplifyTopology(topology, tolerance);
15
+ return {
16
+ line: points => rebuild(points) ?? points.slice(),
17
+ ring: ring => {
18
+ const out = rebuild(ring);
19
+ return out && out.length >= 4 && area(out) !== 0 ? out : null;
20
+ },
21
+ };
22
+ }
2
23
  function walkGeometry(geometry, visit) {
3
24
  if (!geometry)
4
25
  return;
@@ -51,14 +72,14 @@ export function bbox(input) {
51
72
  });
52
73
  return box;
53
74
  }
54
- function simplifyPolygon(rings, tolerance) {
55
- const outer = simplifyRing(rings[0] ?? [], tolerance);
75
+ function simplifyPolygon(rings, s) {
76
+ const outer = s.ring(rings[0] ?? []);
56
77
  if (!outer)
57
78
  return null;
58
- const holes = rings.slice(1).map(ring => simplifyRing(ring, tolerance)).filter((ring) => !!ring);
79
+ const holes = rings.slice(1).map(ring => s.ring(ring)).filter((ring) => !!ring);
59
80
  return [outer, ...holes];
60
81
  }
61
- function simplifyGeometry(geometry, tolerance) {
82
+ function simplifyGeometry(geometry, s) {
62
83
  if (!geometry)
63
84
  return null;
64
85
  switch (geometry.type) {
@@ -66,51 +87,54 @@ function simplifyGeometry(geometry, tolerance) {
66
87
  case 'MultiPoint':
67
88
  return geometry;
68
89
  case 'LineString':
69
- return { type: 'LineString', coordinates: simplifyLine(geometry.coordinates, tolerance) };
90
+ return { type: 'LineString', coordinates: s.line(geometry.coordinates) };
70
91
  case 'MultiLineString':
71
- return { type: 'MultiLineString', coordinates: geometry.coordinates.map(line => simplifyLine(line, tolerance)) };
92
+ return { type: 'MultiLineString', coordinates: geometry.coordinates.map(line => s.line(line)) };
72
93
  case 'Polygon': {
73
- const coordinates = simplifyPolygon(geometry.coordinates, tolerance);
94
+ const coordinates = simplifyPolygon(geometry.coordinates, s);
74
95
  return coordinates && { type: 'Polygon', coordinates };
75
96
  }
76
97
  case 'MultiPolygon': {
77
- const coordinates = geometry.coordinates.map(polygon => simplifyPolygon(polygon, tolerance))
98
+ const coordinates = geometry.coordinates.map(polygon => simplifyPolygon(polygon, s))
78
99
  .filter((polygon) => !!polygon);
79
100
  return coordinates.length ? { type: 'MultiPolygon', coordinates } : null;
80
101
  }
81
102
  case 'GeometryCollection': {
82
- const geometries = geometry.geometries.map(child => simplifyGeometry(child, tolerance))
103
+ const geometries = geometry.geometries.map(child => simplifyGeometry(child, s))
83
104
  .filter((child) => !!child);
84
105
  return geometries.length ? { type: 'GeometryCollection', geometries } : null;
85
106
  }
86
107
  }
87
108
  }
88
- function simplifyFeature(feature, tolerance) {
109
+ function simplifyFeature(feature, s) {
89
110
  if (!feature.geometry)
90
111
  return feature;
91
- const geometry = simplifyGeometry(feature.geometry, tolerance);
112
+ const geometry = simplifyGeometry(feature.geometry, s);
92
113
  return geometry && { ...feature, geometry };
93
114
  }
94
- function simplifyAll(input, tolerance) {
115
+ function simplifyAll(input, s) {
95
116
  if (input.type === 'FeatureCollection') {
96
- const features = input.features.map(feature => simplifyFeature(feature, tolerance))
117
+ const features = input.features.map(feature => simplifyFeature(feature, s))
97
118
  .filter((feature) => !!feature);
98
119
  return { ...input, features };
99
120
  }
100
121
  if (input.type === 'Feature')
101
- return simplifyFeature(input, tolerance);
102
- return simplifyGeometry(input, tolerance);
122
+ return simplifyFeature(input, s);
123
+ return simplifyGeometry(input, s);
103
124
  }
104
125
  /**
105
126
  * Simplifies every line and ring with Douglas-Peucker. Points are kept as is.
106
127
  * Polygons and holes that collapse below four positions are dropped, and so
107
128
  * are features whose geometry disappears; a lone geometry that collapses
108
- * returns null.
129
+ * returns null. With `topology`, shared borders are simplified once and stay
130
+ * identical in every polygon that uses them.
109
131
  */
110
132
  export function resampleGeoJSON(input, options = {}) {
111
133
  const minimum = Math.max(0, options.tolerance ?? 0);
112
134
  const { maxPositions } = options;
113
- const first = simplifyAll(input, minimum);
135
+ const topology = options.topology ? buildTopology(input) : undefined;
136
+ const at = (tolerance) => simplifyAll(input, simplifier(tolerance, topology));
137
+ const first = at(minimum);
114
138
  if (maxPositions === undefined || !first || countPositions(first) <= maxPositions)
115
139
  return first;
116
140
  const box = bbox(input);
@@ -118,10 +142,10 @@ export function resampleGeoJSON(input, options = {}) {
118
142
  return first;
119
143
  let lo = minimum;
120
144
  let hi = Math.max(Math.hypot(box[2] - box[0], box[3] - box[1]), minimum);
121
- let best = simplifyAll(input, hi);
145
+ let best = at(hi);
122
146
  for (let i = 0; i < 40 && hi - lo > hi * 1e-6; i++) {
123
147
  const mid = (lo + hi) / 2;
124
- const candidate = simplifyAll(input, mid);
148
+ const candidate = at(mid);
125
149
  if (!candidate)
126
150
  hi = mid;
127
151
  else if (countPositions(candidate) <= maxPositions) {
package/esm/scene.js CHANGED
@@ -1,25 +1,45 @@
1
1
  import { geodeticToScene } from '@vim3d/core';
2
- function lines(geometry, emit) {
2
+ import earcut from 'earcut';
3
+ function eachFeature(input, emit) {
4
+ if (input.type === 'FeatureCollection')
5
+ input.features.forEach(feature => emit(feature.geometry, feature.properties, feature.id));
6
+ else if (input.type === 'Feature')
7
+ emit(input.geometry, input.properties, input.id);
8
+ else
9
+ emit(input, null);
10
+ }
11
+ function eachGeometry(geometry, visit) {
3
12
  if (!geometry)
4
13
  return;
5
- switch (geometry.type) {
6
- case 'LineString':
7
- emit(geometry.coordinates, false);
8
- break;
9
- case 'MultiLineString':
10
- geometry.coordinates.forEach(line => emit(line, false));
11
- break;
12
- case 'Polygon':
13
- geometry.coordinates.forEach(ring => emit(ring, true));
14
- break;
15
- case 'MultiPolygon':
16
- geometry.coordinates.forEach(polygon => polygon.forEach(ring => emit(ring, true)));
17
- break;
18
- case 'GeometryCollection':
19
- geometry.geometries.forEach(child => lines(child, emit));
20
- break;
21
- default: break;
22
- }
14
+ if (geometry.type === 'GeometryCollection')
15
+ geometry.geometries.forEach(child => eachGeometry(child, visit));
16
+ else
17
+ visit(geometry);
18
+ }
19
+ const finite = ([lon, lat]) => Number.isFinite(lon) && Number.isFinite(lat);
20
+ function projector(origin, options) {
21
+ const elevation = options.elevation ?? origin.elevation;
22
+ return (positions) => positions.filter(finite)
23
+ .map(([lon, lat, height]) => geodeticToScene(origin, lat, lon, Number.isFinite(height) ? height : elevation));
24
+ }
25
+ function lines(geometry, emit) {
26
+ eachGeometry(geometry, child => {
27
+ switch (child.type) {
28
+ case 'LineString':
29
+ emit(child.coordinates, false);
30
+ break;
31
+ case 'MultiLineString':
32
+ child.coordinates.forEach(line => emit(line, false));
33
+ break;
34
+ case 'Polygon':
35
+ child.coordinates.forEach(ring => emit(ring, true));
36
+ break;
37
+ case 'MultiPolygon':
38
+ child.coordinates.forEach(polygon => polygon.forEach(ring => emit(ring, true)));
39
+ break;
40
+ default: break;
41
+ }
42
+ });
23
43
  }
24
44
  /**
25
45
  * Turns every line and polygon ring into a scene-space curve around `origin`,
@@ -28,22 +48,155 @@ function lines(geometry, emit) {
28
48
  */
29
49
  export function toSceneCurves(input, origin, options = {}) {
30
50
  const curves = [];
31
- const elevation = options.elevation ?? origin.elevation;
32
- const add = (geometry, properties, id) => lines(geometry, (line, closed) => {
33
- const vertices = line.filter(([lon, lat]) => Number.isFinite(lon) && Number.isFinite(lat))
34
- .map(([lon, lat, height]) => geodeticToScene(origin, lat, lon, Number.isFinite(height) ? height : elevation));
51
+ const project = projector(origin, options);
52
+ eachFeature(input, (geometry, properties, id) => lines(geometry, (line, closed) => {
53
+ const vertices = project(line);
35
54
  if (vertices.length < 2)
36
55
  return;
37
56
  const [first, last] = [vertices[0], vertices[vertices.length - 1]];
38
57
  if (closed && first.some((v, i) => v !== last[i]))
39
58
  vertices.push(first);
40
59
  curves.push({ geometry: { primitive: 'curve', args: [], vertices }, properties, id, closed });
41
- });
42
- if (input.type === 'FeatureCollection')
43
- input.features.forEach(feature => add(feature.geometry, feature.properties, feature.id));
44
- else if (input.type === 'Feature')
45
- add(input.geometry, input.properties, input.id);
46
- else
47
- add(input, null);
60
+ }));
48
61
  return curves;
49
62
  }
63
+ /**
64
+ * Every `Point` and `MultiPoint` position as a scene-space point with its
65
+ * feature's `properties` and `id`, for labels, trees and other markers.
66
+ */
67
+ export function toScenePoints(input, origin, options = {}) {
68
+ const points = [];
69
+ const project = projector(origin, options);
70
+ eachFeature(input, (geometry, properties, id) => eachGeometry(geometry, child => {
71
+ const positions = child.type === 'Point' ? [child.coordinates] : child.type === 'MultiPoint' ? child.coordinates : [];
72
+ for (const position of project(positions))
73
+ points.push({ position, properties, id });
74
+ }));
75
+ return points;
76
+ }
77
+ function mesh(positions, indices) {
78
+ for (let i = 0; i < indices.length; i += 3) {
79
+ const [a, b, c] = [indices[i] * 3, indices[i + 1] * 3, indices[i + 2] * 3];
80
+ const up = (positions[b + 2] - positions[a + 2]) * (positions[c] - positions[a])
81
+ - (positions[b] - positions[a]) * (positions[c + 2] - positions[a + 2]);
82
+ if (up < 0)
83
+ [indices[i + 1], indices[i + 2]] = [indices[i + 2], indices[i + 1]];
84
+ }
85
+ return { primitive: 'mesh', args: [], positions, indices };
86
+ }
87
+ function openRing(ring) {
88
+ const [first, last] = [ring[0], ring[ring.length - 1]];
89
+ return ring.length > 1 && first[0] === last[0] && first[2] === last[2] ? ring.slice(0, -1) : ring;
90
+ }
91
+ /**
92
+ * Every polygon (each part of a `MultiPolygon` on its own) as a flat,
93
+ * upward-facing triangle mesh with its holes cut out.
94
+ */
95
+ export function toSceneFills(input, origin, options = {}) {
96
+ const meshes = [];
97
+ const project = projector(origin, options);
98
+ const fill = (rings, properties, id) => {
99
+ const [outer, ...holes] = rings.map(ring => openRing(project(ring)));
100
+ if (!outer || outer.length < 3)
101
+ return;
102
+ const kept = [outer, ...holes.filter(hole => hole.length >= 3)];
103
+ const positions = [];
104
+ const flat = [];
105
+ const starts = [];
106
+ for (const ring of kept) {
107
+ if (ring !== outer)
108
+ starts.push(positions.length / 3);
109
+ for (const [x, y, z] of ring) {
110
+ positions.push(x, y, z);
111
+ flat.push(x, z);
112
+ }
113
+ }
114
+ const indices = earcut(flat, starts.length ? starts : undefined, 2);
115
+ if (indices.length)
116
+ meshes.push({ geometry: mesh(positions, indices), properties, id });
117
+ };
118
+ eachFeature(input, (geometry, properties, id) => eachGeometry(geometry, child => {
119
+ if (child.type === 'Polygon')
120
+ fill(child.coordinates, properties, id);
121
+ else if (child.type === 'MultiPolygon')
122
+ child.coordinates.forEach(polygon => fill(polygon, properties, id));
123
+ }));
124
+ return meshes;
125
+ }
126
+ const MITER_LIMIT = 2;
127
+ function ribbon(line, width) {
128
+ let points = line.filter((p, i) => i === 0 || p[0] !== line[i - 1][0] || p[2] !== line[i - 1][2]);
129
+ const [first, last] = [points[0], points[points.length - 1]];
130
+ const closed = points.length > 3 && first[0] === last[0] && first[2] === last[2];
131
+ if (closed)
132
+ points = points.slice(0, -1);
133
+ if (points.length < 2)
134
+ return null;
135
+ const count = points.length;
136
+ const half = width / 2;
137
+ const segments = closed ? count : count - 1;
138
+ const normals = [];
139
+ const lengths = [];
140
+ for (let i = 0; i < segments; i++) {
141
+ const [p, q] = [points[i], points[(i + 1) % count]];
142
+ const [dx, dz] = [q[0] - p[0], q[2] - p[2]];
143
+ const length = Math.hypot(dx, dz);
144
+ normals.push([-dz / length, dx / length]);
145
+ lengths.push(length);
146
+ }
147
+ const sections = [];
148
+ const section = ([x, y, z], [nx, nz], scale) => sections.push([x, y, z, nx * scale, nz * scale]);
149
+ points.forEach((point, i) => {
150
+ const before = closed ? (i + count - 1) % count : i - 1;
151
+ const after = i < segments ? i : -1;
152
+ if (before < 0 || after < 0)
153
+ return section(point, normals[Math.max(before, after)], half);
154
+ const [a, b] = [normals[before], normals[after]];
155
+ const [mx, mz] = [a[0] + b[0], a[1] + b[1]];
156
+ const length = Math.hypot(mx, mz);
157
+ const cos = length / 2;
158
+ const reach = cos > 0 ? half * Math.sqrt(Math.max(0, 1 - cos * cos)) / cos : Infinity;
159
+ if (cos >= 1 / MITER_LIMIT && reach <= Math.min(lengths[before], lengths[after])) {
160
+ section(point, [mx / length, mz / length], half / cos);
161
+ }
162
+ else {
163
+ section(point, a, half);
164
+ section(point, b, half);
165
+ }
166
+ });
167
+ if (closed)
168
+ sections.push(sections[0]);
169
+ const positions = [];
170
+ const indices = [];
171
+ sections.forEach(([x, y, z, ox, oz], i) => {
172
+ positions.push(x + ox, y, z + oz, x - ox, y, z - oz);
173
+ if (i > 0) {
174
+ const k = 2 * (i - 1);
175
+ indices.push(k, k + 1, k + 2, k + 1, k + 3, k + 2);
176
+ }
177
+ });
178
+ return mesh(positions, indices);
179
+ }
180
+ /**
181
+ * Every line (not polygon rings) as a flat, upward-facing strip of the given
182
+ * width around its centerline, for streets and paths. Corners are mitered;
183
+ * corners sharper than the miter limit, or whose miter would reach past the
184
+ * next vertex, are beveled. A line that ends where it starts joins up.
185
+ */
186
+ export function toSceneRibbons(input, origin, options = {}) {
187
+ const meshes = [];
188
+ const project = projector(origin, options);
189
+ eachFeature(input, (geometry, properties, id) => {
190
+ const value = options.widthProperty ? properties?.[options.widthProperty] : undefined;
191
+ const width = typeof value === 'number' && value > 0 && Number.isFinite(value) ? value : options.width ?? 1;
192
+ eachGeometry(geometry, child => {
193
+ const parts = child.type === 'LineString' ? [child.coordinates] : child.type === 'MultiLineString' ? child.coordinates : [];
194
+ for (const part of parts) {
195
+ const strip = ribbon(project(part), width);
196
+ if (strip)
197
+ meshes.push({ geometry: strip, properties, id });
198
+ }
199
+ });
200
+ });
201
+ return meshes;
202
+ }
@@ -0,0 +1,154 @@
1
+ import { simplifyLine } from './simplify.js';
2
+ const keyOf = (p) => `${p[0]},${p[1]}`;
3
+ function eachLine(input, visit) {
4
+ const walk = (geometry) => {
5
+ if (!geometry)
6
+ return;
7
+ switch (geometry.type) {
8
+ case 'LineString':
9
+ visit(geometry.coordinates, false);
10
+ break;
11
+ case 'MultiLineString':
12
+ geometry.coordinates.forEach(line => visit(line, false));
13
+ break;
14
+ case 'Polygon':
15
+ geometry.coordinates.forEach(ring => visit(ring, true));
16
+ break;
17
+ case 'MultiPolygon':
18
+ geometry.coordinates.forEach(polygon => polygon.forEach(ring => visit(ring, true)));
19
+ break;
20
+ case 'GeometryCollection':
21
+ geometry.geometries.forEach(walk);
22
+ break;
23
+ }
24
+ };
25
+ if (input.type === 'FeatureCollection')
26
+ input.features.forEach(feature => walk(feature.geometry));
27
+ else if (input.type === 'Feature')
28
+ walk(input.geometry);
29
+ else
30
+ walk(input);
31
+ }
32
+ /** Drops repeated positions and, for rings, the closing position. */
33
+ function dedupe(line, closed) {
34
+ const out = [];
35
+ for (const p of line)
36
+ if (!out.length || keyOf(out[out.length - 1]) !== keyOf(p))
37
+ out.push(p);
38
+ if (closed && out.length > 1 && keyOf(out[0]) === keyOf(out[out.length - 1]))
39
+ out.pop();
40
+ return out;
41
+ }
42
+ function lowest(points) {
43
+ let best = 0;
44
+ points.forEach((p, i) => {
45
+ const q = points[best];
46
+ if (p[0] < q[0] || (p[0] === q[0] && p[1] < q[1]))
47
+ best = i;
48
+ });
49
+ return best;
50
+ }
51
+ /**
52
+ * Finds where lines and rings meet (a position whose neighbors differ between
53
+ * two of its uses, or a line end) and cuts them there into shared arcs.
54
+ */
55
+ export function buildTopology(input) {
56
+ const entries = [];
57
+ eachLine(input, (line, closed) => entries.push([line, dedupe(line, closed), closed]));
58
+ const neighbors = new Map();
59
+ const junctions = new Set();
60
+ const visit = (p, a, b) => {
61
+ const [ka, kb] = [keyOf(a), keyOf(b)];
62
+ const pair = ka < kb ? `${ka}|${kb}` : `${kb}|${ka}`;
63
+ const key = keyOf(p);
64
+ const seen = neighbors.get(key);
65
+ if (seen === undefined)
66
+ neighbors.set(key, pair);
67
+ else if (seen !== pair)
68
+ junctions.add(key);
69
+ };
70
+ for (const [, points, closed] of entries) {
71
+ const n = points.length;
72
+ if (closed) {
73
+ if (n >= 3)
74
+ points.forEach((p, i) => visit(p, points[(i + n - 1) % n], points[(i + 1) % n]));
75
+ }
76
+ else if (n) {
77
+ junctions.add(keyOf(points[0]));
78
+ junctions.add(keyOf(points[n - 1]));
79
+ for (let i = 1; i < n - 1; i++)
80
+ visit(points[i], points[i - 1], points[i + 1]);
81
+ }
82
+ }
83
+ const arcs = [];
84
+ const index = new Map();
85
+ const add = (arc) => {
86
+ const keys = arc.map(keyOf);
87
+ const forward = keys.join(';');
88
+ const backward = keys.reverse().join(';');
89
+ const reversed = backward < forward;
90
+ const key = reversed ? backward : forward;
91
+ let i = index.get(key);
92
+ if (i === undefined) {
93
+ i = arcs.length;
94
+ index.set(key, i);
95
+ arcs.push(reversed ? arc.slice().reverse() : arc);
96
+ }
97
+ return { index: i, reversed };
98
+ };
99
+ const lines = new WeakMap();
100
+ for (const [line, points, closed] of entries) {
101
+ if (points.length < (closed ? 3 : 2))
102
+ continue;
103
+ let sequence = points;
104
+ if (closed) {
105
+ let start = points.findIndex(p => junctions.has(keyOf(p)));
106
+ if (start === -1)
107
+ start = lowest(points);
108
+ sequence = [...points.slice(start), ...points.slice(0, start), points[start]];
109
+ }
110
+ const refs = [];
111
+ let from = 0;
112
+ for (let i = 1; i < sequence.length; i++) {
113
+ if (i === sequence.length - 1 || junctions.has(keyOf(sequence[i]))) {
114
+ refs.push(add(sequence.slice(from, i + 1)));
115
+ from = i;
116
+ }
117
+ }
118
+ lines.set(line, refs);
119
+ }
120
+ return { arcs, lines };
121
+ }
122
+ /**
123
+ * Returns a function that rebuilds a line or ring of the topology's input from
124
+ * its arcs, each simplified once, so shared borders stay identical. Lines the
125
+ * topology skipped (too short to draw) return undefined.
126
+ */
127
+ export function simplifyTopology(topology, tolerance) {
128
+ const simplified = new Map();
129
+ const arc = ({ index, reversed }) => {
130
+ let points = simplified.get(index);
131
+ if (!points)
132
+ simplified.set(index, points = simplifyLine(topology.arcs[index], tolerance));
133
+ return reversed ? points.slice().reverse() : points;
134
+ };
135
+ return line => {
136
+ const refs = topology.lines.get(line);
137
+ if (!refs)
138
+ return undefined;
139
+ const out = [];
140
+ for (const ref of refs) {
141
+ const points = arc(ref);
142
+ for (let i = out.length ? 1 : 0; i < points.length; i++)
143
+ out.push(points[i]);
144
+ }
145
+ return out;
146
+ };
147
+ }
148
+ /**
149
+ * Every line and ring edge once, as a MultiLineString: a border two polygons
150
+ * share comes out as one line instead of two.
151
+ */
152
+ export function borders(input) {
153
+ return { type: 'MultiLineString', coordinates: buildTopology(input).arcs.map(arc => arc.slice()) };
154
+ }
package/index.d.ts CHANGED
@@ -3,7 +3,8 @@ export type { LoadGeoJSONOptions } from './fetch.js';
3
3
  export { loadGeoJSON } from './fetch.js';
4
4
  export type { ResampleOptions } from './resample.js';
5
5
  export { bbox, countPositions, eachPosition, resampleGeoJSON } from './resample.js';
6
- export type { SceneCurve, SceneCurveOptions } from './scene.js';
7
- export { toSceneCurves } from './scene.js';
6
+ export type { MeshGeometry, SceneCurve, SceneCurveOptions, SceneMesh, ScenePoint, SceneRibbonOptions } from './scene.js';
7
+ export { toSceneCurves, toSceneFills, toScenePoints, toSceneRibbons } from './scene.js';
8
8
  export { simplifyLine, simplifyRing } from './simplify.js';
9
+ export { borders } from './topology.js';
9
10
  export type * from './types.js';
package/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.simplifyRing = exports.simplifyLine = exports.toSceneCurves = exports.resampleGeoJSON = exports.eachPosition = exports.countPositions = exports.bbox = exports.loadGeoJSON = exports.name = void 0;
3
+ exports.borders = exports.simplifyRing = exports.simplifyLine = exports.toSceneRibbons = exports.toScenePoints = exports.toSceneFills = exports.toSceneCurves = exports.resampleGeoJSON = exports.eachPosition = exports.countPositions = exports.bbox = exports.loadGeoJSON = exports.name = void 0;
4
4
  exports.name = '@vim3d/geojson';
5
5
  var fetch_js_1 = require("./fetch.js");
6
6
  Object.defineProperty(exports, "loadGeoJSON", { enumerable: true, get: function () { return fetch_js_1.loadGeoJSON; } });
@@ -11,6 +11,11 @@ Object.defineProperty(exports, "eachPosition", { enumerable: true, get: function
11
11
  Object.defineProperty(exports, "resampleGeoJSON", { enumerable: true, get: function () { return resample_js_1.resampleGeoJSON; } });
12
12
  var scene_js_1 = require("./scene.js");
13
13
  Object.defineProperty(exports, "toSceneCurves", { enumerable: true, get: function () { return scene_js_1.toSceneCurves; } });
14
+ Object.defineProperty(exports, "toSceneFills", { enumerable: true, get: function () { return scene_js_1.toSceneFills; } });
15
+ Object.defineProperty(exports, "toScenePoints", { enumerable: true, get: function () { return scene_js_1.toScenePoints; } });
16
+ Object.defineProperty(exports, "toSceneRibbons", { enumerable: true, get: function () { return scene_js_1.toSceneRibbons; } });
14
17
  var simplify_js_1 = require("./simplify.js");
15
18
  Object.defineProperty(exports, "simplifyLine", { enumerable: true, get: function () { return simplify_js_1.simplifyLine; } });
16
19
  Object.defineProperty(exports, "simplifyRing", { enumerable: true, get: function () { return simplify_js_1.simplifyRing; } });
20
+ var topology_js_1 = require("./topology.js");
21
+ Object.defineProperty(exports, "borders", { enumerable: true, get: function () { return topology_js_1.borders; } });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vim3d/geojson",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "description": "Fetch GeoJSON at load time and resample it for Vim3D scenes.",
5
5
  "author": "Dan Lynch <pyramation@gmail.com>",
6
6
  "homepage": "https://github.com/pyramation/vim3d/tree/master/js/packages/geojson",
@@ -22,9 +22,11 @@
22
22
  },
23
23
  "dependencies": {
24
24
  "@constructive-io/fetch": "^1.2.2",
25
+ "earcut": "^2.2.4",
25
26
  "@vim3d/core": "^0.6.0"
26
27
  },
27
28
  "devDependencies": {
29
+ "@types/earcut": "^2.1.4",
28
30
  "makage": "^0.8.0"
29
31
  },
30
32
  "scripts": {
package/resample.d.ts CHANGED
@@ -9,6 +9,11 @@ export interface ResampleOptions {
9
9
  * smallest reachable, which can still be over it.
10
10
  */
11
11
  maxPositions?: number;
12
+ /**
13
+ * Cut lines and rings into arcs where they meet and simplify each arc once,
14
+ * so borders that polygons share stay identical after resampling.
15
+ */
16
+ topology?: boolean;
12
17
  }
13
18
  type Collect = (position: Position) => void;
14
19
  /** Calls `visit` for every position in a geometry, feature or collection. */
@@ -20,7 +25,8 @@ export declare function bbox(input: GeoJSON): [number, number, number, number] |
20
25
  * Simplifies every line and ring with Douglas-Peucker. Points are kept as is.
21
26
  * Polygons and holes that collapse below four positions are dropped, and so
22
27
  * are features whose geometry disappears; a lone geometry that collapses
23
- * returns null.
28
+ * returns null. With `topology`, shared borders are simplified once and stay
29
+ * identical in every polygon that uses them.
24
30
  */
25
31
  export declare function resampleGeoJSON<T extends GeoJSON>(input: T, options?: ResampleOptions): T | null;
26
32
  export {};
package/resample.js CHANGED
@@ -5,6 +5,27 @@ exports.countPositions = countPositions;
5
5
  exports.bbox = bbox;
6
6
  exports.resampleGeoJSON = resampleGeoJSON;
7
7
  const simplify_js_1 = require("./simplify.js");
8
+ const topology_js_1 = require("./topology.js");
9
+ function area(ring) {
10
+ const [x0, y0] = ring[0];
11
+ let sum = 0;
12
+ for (let i = 2; i < ring.length - 1; i++) {
13
+ sum += (ring[i - 1][0] - x0) * (ring[i][1] - y0) - (ring[i][0] - x0) * (ring[i - 1][1] - y0);
14
+ }
15
+ return sum;
16
+ }
17
+ function simplifier(tolerance, topology) {
18
+ if (!topology)
19
+ return { line: points => (0, simplify_js_1.simplifyLine)(points, tolerance), ring: ring => (0, simplify_js_1.simplifyRing)(ring, tolerance) };
20
+ const rebuild = (0, topology_js_1.simplifyTopology)(topology, tolerance);
21
+ return {
22
+ line: points => rebuild(points) ?? points.slice(),
23
+ ring: ring => {
24
+ const out = rebuild(ring);
25
+ return out && out.length >= 4 && area(out) !== 0 ? out : null;
26
+ },
27
+ };
28
+ }
8
29
  function walkGeometry(geometry, visit) {
9
30
  if (!geometry)
10
31
  return;
@@ -57,14 +78,14 @@ function bbox(input) {
57
78
  });
58
79
  return box;
59
80
  }
60
- function simplifyPolygon(rings, tolerance) {
61
- const outer = (0, simplify_js_1.simplifyRing)(rings[0] ?? [], tolerance);
81
+ function simplifyPolygon(rings, s) {
82
+ const outer = s.ring(rings[0] ?? []);
62
83
  if (!outer)
63
84
  return null;
64
- const holes = rings.slice(1).map(ring => (0, simplify_js_1.simplifyRing)(ring, tolerance)).filter((ring) => !!ring);
85
+ const holes = rings.slice(1).map(ring => s.ring(ring)).filter((ring) => !!ring);
65
86
  return [outer, ...holes];
66
87
  }
67
- function simplifyGeometry(geometry, tolerance) {
88
+ function simplifyGeometry(geometry, s) {
68
89
  if (!geometry)
69
90
  return null;
70
91
  switch (geometry.type) {
@@ -72,51 +93,54 @@ function simplifyGeometry(geometry, tolerance) {
72
93
  case 'MultiPoint':
73
94
  return geometry;
74
95
  case 'LineString':
75
- return { type: 'LineString', coordinates: (0, simplify_js_1.simplifyLine)(geometry.coordinates, tolerance) };
96
+ return { type: 'LineString', coordinates: s.line(geometry.coordinates) };
76
97
  case 'MultiLineString':
77
- return { type: 'MultiLineString', coordinates: geometry.coordinates.map(line => (0, simplify_js_1.simplifyLine)(line, tolerance)) };
98
+ return { type: 'MultiLineString', coordinates: geometry.coordinates.map(line => s.line(line)) };
78
99
  case 'Polygon': {
79
- const coordinates = simplifyPolygon(geometry.coordinates, tolerance);
100
+ const coordinates = simplifyPolygon(geometry.coordinates, s);
80
101
  return coordinates && { type: 'Polygon', coordinates };
81
102
  }
82
103
  case 'MultiPolygon': {
83
- const coordinates = geometry.coordinates.map(polygon => simplifyPolygon(polygon, tolerance))
104
+ const coordinates = geometry.coordinates.map(polygon => simplifyPolygon(polygon, s))
84
105
  .filter((polygon) => !!polygon);
85
106
  return coordinates.length ? { type: 'MultiPolygon', coordinates } : null;
86
107
  }
87
108
  case 'GeometryCollection': {
88
- const geometries = geometry.geometries.map(child => simplifyGeometry(child, tolerance))
109
+ const geometries = geometry.geometries.map(child => simplifyGeometry(child, s))
89
110
  .filter((child) => !!child);
90
111
  return geometries.length ? { type: 'GeometryCollection', geometries } : null;
91
112
  }
92
113
  }
93
114
  }
94
- function simplifyFeature(feature, tolerance) {
115
+ function simplifyFeature(feature, s) {
95
116
  if (!feature.geometry)
96
117
  return feature;
97
- const geometry = simplifyGeometry(feature.geometry, tolerance);
118
+ const geometry = simplifyGeometry(feature.geometry, s);
98
119
  return geometry && { ...feature, geometry };
99
120
  }
100
- function simplifyAll(input, tolerance) {
121
+ function simplifyAll(input, s) {
101
122
  if (input.type === 'FeatureCollection') {
102
- const features = input.features.map(feature => simplifyFeature(feature, tolerance))
123
+ const features = input.features.map(feature => simplifyFeature(feature, s))
103
124
  .filter((feature) => !!feature);
104
125
  return { ...input, features };
105
126
  }
106
127
  if (input.type === 'Feature')
107
- return simplifyFeature(input, tolerance);
108
- return simplifyGeometry(input, tolerance);
128
+ return simplifyFeature(input, s);
129
+ return simplifyGeometry(input, s);
109
130
  }
110
131
  /**
111
132
  * Simplifies every line and ring with Douglas-Peucker. Points are kept as is.
112
133
  * Polygons and holes that collapse below four positions are dropped, and so
113
134
  * are features whose geometry disappears; a lone geometry that collapses
114
- * returns null.
135
+ * returns null. With `topology`, shared borders are simplified once and stay
136
+ * identical in every polygon that uses them.
115
137
  */
116
138
  function resampleGeoJSON(input, options = {}) {
117
139
  const minimum = Math.max(0, options.tolerance ?? 0);
118
140
  const { maxPositions } = options;
119
- const first = simplifyAll(input, minimum);
141
+ const topology = options.topology ? (0, topology_js_1.buildTopology)(input) : undefined;
142
+ const at = (tolerance) => simplifyAll(input, simplifier(tolerance, topology));
143
+ const first = at(minimum);
120
144
  if (maxPositions === undefined || !first || countPositions(first) <= maxPositions)
121
145
  return first;
122
146
  const box = bbox(input);
@@ -124,10 +148,10 @@ function resampleGeoJSON(input, options = {}) {
124
148
  return first;
125
149
  let lo = minimum;
126
150
  let hi = Math.max(Math.hypot(box[2] - box[0], box[3] - box[1]), minimum);
127
- let best = simplifyAll(input, hi);
151
+ let best = at(hi);
128
152
  for (let i = 0; i < 40 && hi - lo > hi * 1e-6; i++) {
129
153
  const mid = (lo + hi) / 2;
130
- const candidate = simplifyAll(input, mid);
154
+ const candidate = at(mid);
131
155
  if (!candidate)
132
156
  hi = mid;
133
157
  else if (countPositions(candidate) <= maxPositions) {
package/scene.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { type GeometrySnapshot, type GeoOrigin } from '@vim3d/core';
1
+ import { type GeometrySnapshot, type GeoOrigin, type Vec3 } from '@vim3d/core';
2
2
  import type { GeoJSON, Properties } from './types.js';
3
3
  export interface SceneCurve {
4
- /** A curve geometry @vim3d/threejs `createGeometry` draws as a line. */
4
+ /** A curve geometry @vim3d/threejs draws as a line. */
5
5
  readonly geometry: GeometrySnapshot;
6
6
  readonly properties: Properties;
7
7
  readonly id?: string | number;
@@ -11,9 +11,51 @@ export interface SceneCurveOptions {
11
11
  /** Elevation in metres for positions without one; defaults to the origin's. */
12
12
  elevation?: number;
13
13
  }
14
+ export interface ScenePoint {
15
+ readonly position: Vec3;
16
+ readonly properties: Properties;
17
+ readonly id?: string | number;
18
+ }
19
+ export interface MeshGeometry {
20
+ readonly primitive: 'mesh';
21
+ readonly args: readonly number[];
22
+ /** Flat x, y, z vertices. */
23
+ readonly positions: number[];
24
+ /** Vertex triples, wound counter-clockwise seen from above (+y). */
25
+ readonly indices: number[];
26
+ }
27
+ export interface SceneMesh {
28
+ /** A `mesh` geometry, the same shape the `geo:mesh` node outputs. */
29
+ readonly geometry: MeshGeometry;
30
+ readonly properties: Properties;
31
+ readonly id?: string | number;
32
+ }
33
+ export interface SceneRibbonOptions extends SceneCurveOptions {
34
+ /** Ribbon width in metres; defaults to 1. */
35
+ width?: number;
36
+ /** Feature property holding a width in metres, used when it is a positive number. */
37
+ widthProperty?: string;
38
+ }
14
39
  /**
15
40
  * Turns every line and polygon ring into a scene-space curve around `origin`,
16
41
  * using the same local frame as Vim3D `world` (x east, y up, -z north).
17
42
  * Positions without a finite longitude and latitude are skipped.
18
43
  */
19
44
  export declare function toSceneCurves(input: GeoJSON, origin: GeoOrigin, options?: SceneCurveOptions): SceneCurve[];
45
+ /**
46
+ * Every `Point` and `MultiPoint` position as a scene-space point with its
47
+ * feature's `properties` and `id`, for labels, trees and other markers.
48
+ */
49
+ export declare function toScenePoints(input: GeoJSON, origin: GeoOrigin, options?: SceneCurveOptions): ScenePoint[];
50
+ /**
51
+ * Every polygon (each part of a `MultiPolygon` on its own) as a flat,
52
+ * upward-facing triangle mesh with its holes cut out.
53
+ */
54
+ export declare function toSceneFills(input: GeoJSON, origin: GeoOrigin, options?: SceneCurveOptions): SceneMesh[];
55
+ /**
56
+ * Every line (not polygon rings) as a flat, upward-facing strip of the given
57
+ * width around its centerline, for streets and paths. Corners are mitered;
58
+ * corners sharper than the miter limit, or whose miter would reach past the
59
+ * next vertex, are beveled. A line that ends where it starts joins up.
60
+ */
61
+ export declare function toSceneRibbons(input: GeoJSON, origin: GeoOrigin, options?: SceneRibbonOptions): SceneMesh[];
package/scene.js CHANGED
@@ -1,28 +1,54 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.toSceneCurves = toSceneCurves;
7
+ exports.toScenePoints = toScenePoints;
8
+ exports.toSceneFills = toSceneFills;
9
+ exports.toSceneRibbons = toSceneRibbons;
4
10
  const core_1 = require("@vim3d/core");
5
- function lines(geometry, emit) {
11
+ const earcut_1 = __importDefault(require("earcut"));
12
+ function eachFeature(input, emit) {
13
+ if (input.type === 'FeatureCollection')
14
+ input.features.forEach(feature => emit(feature.geometry, feature.properties, feature.id));
15
+ else if (input.type === 'Feature')
16
+ emit(input.geometry, input.properties, input.id);
17
+ else
18
+ emit(input, null);
19
+ }
20
+ function eachGeometry(geometry, visit) {
6
21
  if (!geometry)
7
22
  return;
8
- switch (geometry.type) {
9
- case 'LineString':
10
- emit(geometry.coordinates, false);
11
- break;
12
- case 'MultiLineString':
13
- geometry.coordinates.forEach(line => emit(line, false));
14
- break;
15
- case 'Polygon':
16
- geometry.coordinates.forEach(ring => emit(ring, true));
17
- break;
18
- case 'MultiPolygon':
19
- geometry.coordinates.forEach(polygon => polygon.forEach(ring => emit(ring, true)));
20
- break;
21
- case 'GeometryCollection':
22
- geometry.geometries.forEach(child => lines(child, emit));
23
- break;
24
- default: break;
25
- }
23
+ if (geometry.type === 'GeometryCollection')
24
+ geometry.geometries.forEach(child => eachGeometry(child, visit));
25
+ else
26
+ visit(geometry);
27
+ }
28
+ const finite = ([lon, lat]) => Number.isFinite(lon) && Number.isFinite(lat);
29
+ function projector(origin, options) {
30
+ const elevation = options.elevation ?? origin.elevation;
31
+ return (positions) => positions.filter(finite)
32
+ .map(([lon, lat, height]) => (0, core_1.geodeticToScene)(origin, lat, lon, Number.isFinite(height) ? height : elevation));
33
+ }
34
+ function lines(geometry, emit) {
35
+ eachGeometry(geometry, child => {
36
+ switch (child.type) {
37
+ case 'LineString':
38
+ emit(child.coordinates, false);
39
+ break;
40
+ case 'MultiLineString':
41
+ child.coordinates.forEach(line => emit(line, false));
42
+ break;
43
+ case 'Polygon':
44
+ child.coordinates.forEach(ring => emit(ring, true));
45
+ break;
46
+ case 'MultiPolygon':
47
+ child.coordinates.forEach(polygon => polygon.forEach(ring => emit(ring, true)));
48
+ break;
49
+ default: break;
50
+ }
51
+ });
26
52
  }
27
53
  /**
28
54
  * Turns every line and polygon ring into a scene-space curve around `origin`,
@@ -31,22 +57,155 @@ function lines(geometry, emit) {
31
57
  */
32
58
  function toSceneCurves(input, origin, options = {}) {
33
59
  const curves = [];
34
- const elevation = options.elevation ?? origin.elevation;
35
- const add = (geometry, properties, id) => lines(geometry, (line, closed) => {
36
- const vertices = line.filter(([lon, lat]) => Number.isFinite(lon) && Number.isFinite(lat))
37
- .map(([lon, lat, height]) => (0, core_1.geodeticToScene)(origin, lat, lon, Number.isFinite(height) ? height : elevation));
60
+ const project = projector(origin, options);
61
+ eachFeature(input, (geometry, properties, id) => lines(geometry, (line, closed) => {
62
+ const vertices = project(line);
38
63
  if (vertices.length < 2)
39
64
  return;
40
65
  const [first, last] = [vertices[0], vertices[vertices.length - 1]];
41
66
  if (closed && first.some((v, i) => v !== last[i]))
42
67
  vertices.push(first);
43
68
  curves.push({ geometry: { primitive: 'curve', args: [], vertices }, properties, id, closed });
44
- });
45
- if (input.type === 'FeatureCollection')
46
- input.features.forEach(feature => add(feature.geometry, feature.properties, feature.id));
47
- else if (input.type === 'Feature')
48
- add(input.geometry, input.properties, input.id);
49
- else
50
- add(input, null);
69
+ }));
51
70
  return curves;
52
71
  }
72
+ /**
73
+ * Every `Point` and `MultiPoint` position as a scene-space point with its
74
+ * feature's `properties` and `id`, for labels, trees and other markers.
75
+ */
76
+ function toScenePoints(input, origin, options = {}) {
77
+ const points = [];
78
+ const project = projector(origin, options);
79
+ eachFeature(input, (geometry, properties, id) => eachGeometry(geometry, child => {
80
+ const positions = child.type === 'Point' ? [child.coordinates] : child.type === 'MultiPoint' ? child.coordinates : [];
81
+ for (const position of project(positions))
82
+ points.push({ position, properties, id });
83
+ }));
84
+ return points;
85
+ }
86
+ function mesh(positions, indices) {
87
+ for (let i = 0; i < indices.length; i += 3) {
88
+ const [a, b, c] = [indices[i] * 3, indices[i + 1] * 3, indices[i + 2] * 3];
89
+ const up = (positions[b + 2] - positions[a + 2]) * (positions[c] - positions[a])
90
+ - (positions[b] - positions[a]) * (positions[c + 2] - positions[a + 2]);
91
+ if (up < 0)
92
+ [indices[i + 1], indices[i + 2]] = [indices[i + 2], indices[i + 1]];
93
+ }
94
+ return { primitive: 'mesh', args: [], positions, indices };
95
+ }
96
+ function openRing(ring) {
97
+ const [first, last] = [ring[0], ring[ring.length - 1]];
98
+ return ring.length > 1 && first[0] === last[0] && first[2] === last[2] ? ring.slice(0, -1) : ring;
99
+ }
100
+ /**
101
+ * Every polygon (each part of a `MultiPolygon` on its own) as a flat,
102
+ * upward-facing triangle mesh with its holes cut out.
103
+ */
104
+ function toSceneFills(input, origin, options = {}) {
105
+ const meshes = [];
106
+ const project = projector(origin, options);
107
+ const fill = (rings, properties, id) => {
108
+ const [outer, ...holes] = rings.map(ring => openRing(project(ring)));
109
+ if (!outer || outer.length < 3)
110
+ return;
111
+ const kept = [outer, ...holes.filter(hole => hole.length >= 3)];
112
+ const positions = [];
113
+ const flat = [];
114
+ const starts = [];
115
+ for (const ring of kept) {
116
+ if (ring !== outer)
117
+ starts.push(positions.length / 3);
118
+ for (const [x, y, z] of ring) {
119
+ positions.push(x, y, z);
120
+ flat.push(x, z);
121
+ }
122
+ }
123
+ const indices = (0, earcut_1.default)(flat, starts.length ? starts : undefined, 2);
124
+ if (indices.length)
125
+ meshes.push({ geometry: mesh(positions, indices), properties, id });
126
+ };
127
+ eachFeature(input, (geometry, properties, id) => eachGeometry(geometry, child => {
128
+ if (child.type === 'Polygon')
129
+ fill(child.coordinates, properties, id);
130
+ else if (child.type === 'MultiPolygon')
131
+ child.coordinates.forEach(polygon => fill(polygon, properties, id));
132
+ }));
133
+ return meshes;
134
+ }
135
+ const MITER_LIMIT = 2;
136
+ function ribbon(line, width) {
137
+ let points = line.filter((p, i) => i === 0 || p[0] !== line[i - 1][0] || p[2] !== line[i - 1][2]);
138
+ const [first, last] = [points[0], points[points.length - 1]];
139
+ const closed = points.length > 3 && first[0] === last[0] && first[2] === last[2];
140
+ if (closed)
141
+ points = points.slice(0, -1);
142
+ if (points.length < 2)
143
+ return null;
144
+ const count = points.length;
145
+ const half = width / 2;
146
+ const segments = closed ? count : count - 1;
147
+ const normals = [];
148
+ const lengths = [];
149
+ for (let i = 0; i < segments; i++) {
150
+ const [p, q] = [points[i], points[(i + 1) % count]];
151
+ const [dx, dz] = [q[0] - p[0], q[2] - p[2]];
152
+ const length = Math.hypot(dx, dz);
153
+ normals.push([-dz / length, dx / length]);
154
+ lengths.push(length);
155
+ }
156
+ const sections = [];
157
+ const section = ([x, y, z], [nx, nz], scale) => sections.push([x, y, z, nx * scale, nz * scale]);
158
+ points.forEach((point, i) => {
159
+ const before = closed ? (i + count - 1) % count : i - 1;
160
+ const after = i < segments ? i : -1;
161
+ if (before < 0 || after < 0)
162
+ return section(point, normals[Math.max(before, after)], half);
163
+ const [a, b] = [normals[before], normals[after]];
164
+ const [mx, mz] = [a[0] + b[0], a[1] + b[1]];
165
+ const length = Math.hypot(mx, mz);
166
+ const cos = length / 2;
167
+ const reach = cos > 0 ? half * Math.sqrt(Math.max(0, 1 - cos * cos)) / cos : Infinity;
168
+ if (cos >= 1 / MITER_LIMIT && reach <= Math.min(lengths[before], lengths[after])) {
169
+ section(point, [mx / length, mz / length], half / cos);
170
+ }
171
+ else {
172
+ section(point, a, half);
173
+ section(point, b, half);
174
+ }
175
+ });
176
+ if (closed)
177
+ sections.push(sections[0]);
178
+ const positions = [];
179
+ const indices = [];
180
+ sections.forEach(([x, y, z, ox, oz], i) => {
181
+ positions.push(x + ox, y, z + oz, x - ox, y, z - oz);
182
+ if (i > 0) {
183
+ const k = 2 * (i - 1);
184
+ indices.push(k, k + 1, k + 2, k + 1, k + 3, k + 2);
185
+ }
186
+ });
187
+ return mesh(positions, indices);
188
+ }
189
+ /**
190
+ * Every line (not polygon rings) as a flat, upward-facing strip of the given
191
+ * width around its centerline, for streets and paths. Corners are mitered;
192
+ * corners sharper than the miter limit, or whose miter would reach past the
193
+ * next vertex, are beveled. A line that ends where it starts joins up.
194
+ */
195
+ function toSceneRibbons(input, origin, options = {}) {
196
+ const meshes = [];
197
+ const project = projector(origin, options);
198
+ eachFeature(input, (geometry, properties, id) => {
199
+ const value = options.widthProperty ? properties?.[options.widthProperty] : undefined;
200
+ const width = typeof value === 'number' && value > 0 && Number.isFinite(value) ? value : options.width ?? 1;
201
+ eachGeometry(geometry, child => {
202
+ const parts = child.type === 'LineString' ? [child.coordinates] : child.type === 'MultiLineString' ? child.coordinates : [];
203
+ for (const part of parts) {
204
+ const strip = ribbon(project(part), width);
205
+ if (strip)
206
+ meshes.push({ geometry: strip, properties, id });
207
+ }
208
+ });
209
+ });
210
+ return meshes;
211
+ }
package/topology.d.ts ADDED
@@ -0,0 +1,29 @@
1
+ import type { GeoJSON, MultiLineString, Position } from './types.js';
2
+ export interface ArcRef {
3
+ index: number;
4
+ reversed: boolean;
5
+ }
6
+ /**
7
+ * Lines and rings cut into arcs at the positions where they meet, so a border
8
+ * two polygons share is one arc.
9
+ */
10
+ export interface Topology {
11
+ arcs: Position[][];
12
+ lines: WeakMap<readonly Position[], ArcRef[]>;
13
+ }
14
+ /**
15
+ * Finds where lines and rings meet (a position whose neighbors differ between
16
+ * two of its uses, or a line end) and cuts them there into shared arcs.
17
+ */
18
+ export declare function buildTopology(input: GeoJSON): Topology;
19
+ /**
20
+ * Returns a function that rebuilds a line or ring of the topology's input from
21
+ * its arcs, each simplified once, so shared borders stay identical. Lines the
22
+ * topology skipped (too short to draw) return undefined.
23
+ */
24
+ export declare function simplifyTopology(topology: Topology, tolerance: number): (line: readonly Position[]) => Position[] | undefined;
25
+ /**
26
+ * Every line and ring edge once, as a MultiLineString: a border two polygons
27
+ * share comes out as one line instead of two.
28
+ */
29
+ export declare function borders(input: GeoJSON): MultiLineString;
package/topology.js ADDED
@@ -0,0 +1,159 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildTopology = buildTopology;
4
+ exports.simplifyTopology = simplifyTopology;
5
+ exports.borders = borders;
6
+ const simplify_js_1 = require("./simplify.js");
7
+ const keyOf = (p) => `${p[0]},${p[1]}`;
8
+ function eachLine(input, visit) {
9
+ const walk = (geometry) => {
10
+ if (!geometry)
11
+ return;
12
+ switch (geometry.type) {
13
+ case 'LineString':
14
+ visit(geometry.coordinates, false);
15
+ break;
16
+ case 'MultiLineString':
17
+ geometry.coordinates.forEach(line => visit(line, false));
18
+ break;
19
+ case 'Polygon':
20
+ geometry.coordinates.forEach(ring => visit(ring, true));
21
+ break;
22
+ case 'MultiPolygon':
23
+ geometry.coordinates.forEach(polygon => polygon.forEach(ring => visit(ring, true)));
24
+ break;
25
+ case 'GeometryCollection':
26
+ geometry.geometries.forEach(walk);
27
+ break;
28
+ }
29
+ };
30
+ if (input.type === 'FeatureCollection')
31
+ input.features.forEach(feature => walk(feature.geometry));
32
+ else if (input.type === 'Feature')
33
+ walk(input.geometry);
34
+ else
35
+ walk(input);
36
+ }
37
+ /** Drops repeated positions and, for rings, the closing position. */
38
+ function dedupe(line, closed) {
39
+ const out = [];
40
+ for (const p of line)
41
+ if (!out.length || keyOf(out[out.length - 1]) !== keyOf(p))
42
+ out.push(p);
43
+ if (closed && out.length > 1 && keyOf(out[0]) === keyOf(out[out.length - 1]))
44
+ out.pop();
45
+ return out;
46
+ }
47
+ function lowest(points) {
48
+ let best = 0;
49
+ points.forEach((p, i) => {
50
+ const q = points[best];
51
+ if (p[0] < q[0] || (p[0] === q[0] && p[1] < q[1]))
52
+ best = i;
53
+ });
54
+ return best;
55
+ }
56
+ /**
57
+ * Finds where lines and rings meet (a position whose neighbors differ between
58
+ * two of its uses, or a line end) and cuts them there into shared arcs.
59
+ */
60
+ function buildTopology(input) {
61
+ const entries = [];
62
+ eachLine(input, (line, closed) => entries.push([line, dedupe(line, closed), closed]));
63
+ const neighbors = new Map();
64
+ const junctions = new Set();
65
+ const visit = (p, a, b) => {
66
+ const [ka, kb] = [keyOf(a), keyOf(b)];
67
+ const pair = ka < kb ? `${ka}|${kb}` : `${kb}|${ka}`;
68
+ const key = keyOf(p);
69
+ const seen = neighbors.get(key);
70
+ if (seen === undefined)
71
+ neighbors.set(key, pair);
72
+ else if (seen !== pair)
73
+ junctions.add(key);
74
+ };
75
+ for (const [, points, closed] of entries) {
76
+ const n = points.length;
77
+ if (closed) {
78
+ if (n >= 3)
79
+ points.forEach((p, i) => visit(p, points[(i + n - 1) % n], points[(i + 1) % n]));
80
+ }
81
+ else if (n) {
82
+ junctions.add(keyOf(points[0]));
83
+ junctions.add(keyOf(points[n - 1]));
84
+ for (let i = 1; i < n - 1; i++)
85
+ visit(points[i], points[i - 1], points[i + 1]);
86
+ }
87
+ }
88
+ const arcs = [];
89
+ const index = new Map();
90
+ const add = (arc) => {
91
+ const keys = arc.map(keyOf);
92
+ const forward = keys.join(';');
93
+ const backward = keys.reverse().join(';');
94
+ const reversed = backward < forward;
95
+ const key = reversed ? backward : forward;
96
+ let i = index.get(key);
97
+ if (i === undefined) {
98
+ i = arcs.length;
99
+ index.set(key, i);
100
+ arcs.push(reversed ? arc.slice().reverse() : arc);
101
+ }
102
+ return { index: i, reversed };
103
+ };
104
+ const lines = new WeakMap();
105
+ for (const [line, points, closed] of entries) {
106
+ if (points.length < (closed ? 3 : 2))
107
+ continue;
108
+ let sequence = points;
109
+ if (closed) {
110
+ let start = points.findIndex(p => junctions.has(keyOf(p)));
111
+ if (start === -1)
112
+ start = lowest(points);
113
+ sequence = [...points.slice(start), ...points.slice(0, start), points[start]];
114
+ }
115
+ const refs = [];
116
+ let from = 0;
117
+ for (let i = 1; i < sequence.length; i++) {
118
+ if (i === sequence.length - 1 || junctions.has(keyOf(sequence[i]))) {
119
+ refs.push(add(sequence.slice(from, i + 1)));
120
+ from = i;
121
+ }
122
+ }
123
+ lines.set(line, refs);
124
+ }
125
+ return { arcs, lines };
126
+ }
127
+ /**
128
+ * Returns a function that rebuilds a line or ring of the topology's input from
129
+ * its arcs, each simplified once, so shared borders stay identical. Lines the
130
+ * topology skipped (too short to draw) return undefined.
131
+ */
132
+ function simplifyTopology(topology, tolerance) {
133
+ const simplified = new Map();
134
+ const arc = ({ index, reversed }) => {
135
+ let points = simplified.get(index);
136
+ if (!points)
137
+ simplified.set(index, points = (0, simplify_js_1.simplifyLine)(topology.arcs[index], tolerance));
138
+ return reversed ? points.slice().reverse() : points;
139
+ };
140
+ return line => {
141
+ const refs = topology.lines.get(line);
142
+ if (!refs)
143
+ return undefined;
144
+ const out = [];
145
+ for (const ref of refs) {
146
+ const points = arc(ref);
147
+ for (let i = out.length ? 1 : 0; i < points.length; i++)
148
+ out.push(points[i]);
149
+ }
150
+ return out;
151
+ };
152
+ }
153
+ /**
154
+ * Every line and ring edge once, as a MultiLineString: a border two polygons
155
+ * share comes out as one line instead of two.
156
+ */
157
+ function borders(input) {
158
+ return { type: 'MultiLineString', coordinates: buildTopology(input).arcs.map(arc => arc.slice()) };
159
+ }