@trackunit/geo-json-utils 1.21.43-alpha-b8d3d323d1a.0 → 1.21.43

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
@@ -14,6 +14,7 @@ The package entry (`src/index.ts`) exports these module surfaces:
14
14
  - **Runtime validation** (`GeoJsonRuntimeValidation`) — These helpers validate unknown input against GeoJSON schemas and log warnings for invalid values so callers can fail safely without throwing.
15
15
  - **Geometry helpers** (`GeoJsonGeometryUtils`)
16
16
  - **General GeoJSON utilities** (`GeoJsonUtils`)
17
+ - **Overlap predicate** (`PolygonOverlap`) — `polygonalGeometriesOverlap`, a yes/no overlap test that avoids the boolean operation for all but degenerate pairs
17
18
  - **Zod schemas** — GeoJSON (`GeoJsonSchemas`) and Trackunit-oriented variants (`TuGeoJsonSchemas`)
18
19
  - **Meridian / longitude helpers** (`MeridianUtils`)
19
20
  - **Bridge utilities** — Trackunit GeoJSON bridging (`TuGeoJsonBridgeUtils`)
package/index.cjs.js CHANGED
@@ -1444,6 +1444,9 @@ const isFullyContainedInGeoJsonPolygon = (polygon1, polygon2) => {
1444
1444
  * catch and treat the throw as no intersection; callers that turn `null` into "no spatial
1445
1445
  * filter" (e.g. `mapUtils` viewport/area merges) must instead fall back to a conservative
1446
1446
  * geometry rather than assume disjointness.
1447
+ *
1448
+ * Callers that only need to know *whether* two geometries overlap should use
1449
+ * `polygonalGeometriesOverlap` instead, which answers without building the intersection.
1447
1450
  */
1448
1451
  const getGeoJsonPolygonIntersection = (polygon1, polygon2) => {
1449
1452
  const geom1 = polygon1.type === "MultiPolygon" ? toClipMultiPolygon(polygon1.coordinates) : [toClipPolygon(polygon1.coordinates)];
@@ -1595,7 +1598,7 @@ const ensureMinimumGeoJsonBboxSpan = (bbox, minSpanDegrees) => {
1595
1598
  * Returns Polygon for a single-ring result, MultiPolygon otherwise.
1596
1599
  * When clips is empty the subject is returned unchanged.
1597
1600
  */
1598
- const geoJsonPolygonDifference = (subject, clips) => {
1601
+ const geoJsonPolygonDifference = (subject, clips, onFallback) => {
1599
1602
  if (clips.length === 0) {
1600
1603
  return subject;
1601
1604
  }
@@ -1605,10 +1608,12 @@ const geoJsonPolygonDifference = (subject, clips) => {
1605
1608
  try {
1606
1609
  differenceResult = polygonClipping.difference(subjectClip, ...clipsConverted);
1607
1610
  }
1608
- catch {
1611
+ catch (error) {
1609
1612
  // polygon-clipping can throw "Unable to complete output ring" for degenerate or
1610
1613
  // near-self-intersecting polygons. Fall back to returning the subject unclipped
1611
- // so the shape still renders rather than crashing the caller.
1614
+ // so the shape still renders rather than crashing the caller; `onFallback` lets
1615
+ // callers surface that the clip was skipped (SAGA-743).
1616
+ onFallback?.(error);
1612
1617
  return subject;
1613
1618
  }
1614
1619
  if (differenceResult.length === 0) {
@@ -1760,6 +1765,269 @@ const distanceToGeoJsonPolygonBoundary = (position, geometry) => {
1760
1765
  return minDist === Infinity ? null : minDist;
1761
1766
  };
1762
1767
 
1768
+ const OUTSIDE = 0;
1769
+ const INSIDE = 1;
1770
+ const ON_BOUNDARY = 2;
1771
+ const DISJOINT = 0;
1772
+ const PROPER_CROSSING = 1;
1773
+ const TOUCHING = 2;
1774
+ /**
1775
+ * A point closer than this to a segment's line, as a fraction of the coordinate magnitude, counts as
1776
+ * collinear (about 0.1 mm for lon/lat). Anything inside the band is routed to the exact fallback.
1777
+ *
1778
+ * `polygon-clipping` 0.15.7 snaps coordinates that are within `Number.EPSILON` of each other
1779
+ * (relative, per axis) before sweeping, so a vertex within rounding noise of the other polygon's
1780
+ * edge is "touching" for it; a raw determinant here would call the same configuration a clean
1781
+ * crossing or a clean inside/outside and disagree. The band is deliberately much wider than that
1782
+ * snapping so that vertices produced by interpolation onto an edge land in it too; its edges are
1783
+ * pinned by the spec.
1784
+ */
1785
+ const COLLINEAR_TOLERANCE = 1e-11;
1786
+ const ringBbox = (ring) => {
1787
+ let minX = Infinity;
1788
+ let minY = Infinity;
1789
+ let maxX = -Infinity;
1790
+ let maxY = -Infinity;
1791
+ for (let i = 0; i < ring.length; i++) {
1792
+ const position = ring[i];
1793
+ if (position === undefined)
1794
+ continue;
1795
+ const x = position[0];
1796
+ const y = position[1];
1797
+ if (x < minX)
1798
+ minX = x;
1799
+ if (x > maxX)
1800
+ maxX = x;
1801
+ if (y < minY)
1802
+ minY = y;
1803
+ if (y > maxY)
1804
+ maxY = y;
1805
+ }
1806
+ return [minX, minY, maxX, maxY];
1807
+ };
1808
+ /** Planar interval test; longitudes are never wrapped here (fill tiling densifies and splits first). */
1809
+ const bboxesIntersect = (a, b) => a[0] <= b[2] && b[0] <= a[2] && a[1] <= b[3] && b[1] <= a[3];
1810
+ /**
1811
+ * Sign of the turn a→b→c (positive = counter-clockwise), with `0` when c lies within
1812
+ * {@link COLLINEAR_TOLERANCE} × coordinate magnitude of the line through a and b. Compared in
1813
+ * squared form so no square root or division runs per call.
1814
+ */
1815
+ const orientation = (a, b, c) => {
1816
+ const abx = b[0] - a[0];
1817
+ const aby = b[1] - a[1];
1818
+ const determinant = abx * (c[1] - a[1]) - aby * (c[0] - a[0]);
1819
+ const lengthSquared = abx * abx + aby * aby;
1820
+ if (lengthSquared === 0)
1821
+ return 0;
1822
+ const magnitude = Math.max(1, Math.abs(a[0]), Math.abs(a[1]), Math.abs(b[0]), Math.abs(b[1]), Math.abs(c[0]), Math.abs(c[1]));
1823
+ const band = COLLINEAR_TOLERANCE * magnitude;
1824
+ return determinant * determinant <= band * band * lengthSquared ? 0 : determinant;
1825
+ };
1826
+ /**
1827
+ * Ray casting (crossing number) with an explicit on-segment check so boundary points are not
1828
+ * misclassified. The on-segment test uses the same tolerant `orientation` as the edge tests, so a
1829
+ * vertex the edge sweep would call touching is never silently classified inside or outside here.
1830
+ */
1831
+ const classifyPositionAgainstRing = (point, ring) => {
1832
+ const [px, py] = point;
1833
+ let inside = false;
1834
+ for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
1835
+ const current = ring[i];
1836
+ const previous = ring[j];
1837
+ if (current === undefined || previous === undefined)
1838
+ continue;
1839
+ const [xi, yi] = current;
1840
+ const [xj, yj] = previous;
1841
+ if (px >= Math.min(xi, xj) &&
1842
+ px <= Math.max(xi, xj) &&
1843
+ py >= Math.min(yi, yj) &&
1844
+ py <= Math.max(yi, yj) &&
1845
+ orientation(current, previous, point) === 0) {
1846
+ return ON_BOUNDARY;
1847
+ }
1848
+ if (yi > py !== yj > py && px < ((xj - xi) * (py - yi)) / (yj - yi) + xi) {
1849
+ inside = !inside;
1850
+ }
1851
+ }
1852
+ return inside ? INSIDE : OUTSIDE;
1853
+ };
1854
+ /** Hole-aware classification: inside the exterior ring and outside every hole. */
1855
+ const classifyPositionAgainstPolygon = (point, rings) => {
1856
+ const exterior = rings[0];
1857
+ if (exterior === undefined)
1858
+ return OUTSIDE;
1859
+ const againstExterior = classifyPositionAgainstRing(point, exterior);
1860
+ if (againstExterior !== INSIDE)
1861
+ return againstExterior;
1862
+ for (let h = 1; h < rings.length; h++) {
1863
+ const hole = rings[h];
1864
+ if (hole === undefined)
1865
+ continue;
1866
+ const againstHole = classifyPositionAgainstRing(point, hole);
1867
+ if (againstHole === INSIDE)
1868
+ return OUTSIDE;
1869
+ if (againstHole === ON_BOUNDARY)
1870
+ return ON_BOUNDARY;
1871
+ }
1872
+ return INSIDE;
1873
+ };
1874
+ /**
1875
+ * An exterior vertex only proves interior area next to it when no hole of its own polygon touches
1876
+ * it; a hole meeting the exterior at a vertex is valid GeoJSON, and there the polygon has no area
1877
+ * on the hole's side.
1878
+ */
1879
+ const vertexBordersInterior = (vertex, rings) => {
1880
+ for (let h = 1; h < rings.length; h++) {
1881
+ const hole = rings[h];
1882
+ if (hole !== undefined && classifyPositionAgainstRing(vertex, hole) === ON_BOUNDARY)
1883
+ return false;
1884
+ }
1885
+ return true;
1886
+ };
1887
+ /**
1888
+ * Relation of segments a–b and c–d whose bounding boxes already overlap (the caller filters on that).
1889
+ * A collinear endpoint is reported as TOUCHING even when the segments do not meet; that only costs a
1890
+ * fallback to the exact operation, never a wrong answer.
1891
+ */
1892
+ const relateSegments = (a, b, c, d) => {
1893
+ const o1 = orientation(a, b, c);
1894
+ const o2 = orientation(a, b, d);
1895
+ const o3 = orientation(c, d, a);
1896
+ const o4 = orientation(c, d, b);
1897
+ if (o1 * o2 < 0 && o3 * o4 < 0)
1898
+ return PROPER_CROSSING;
1899
+ if (o1 === 0 || o2 === 0 || o3 === 0 || o4 === 0)
1900
+ return TOUCHING;
1901
+ return DISJOINT;
1902
+ };
1903
+ /**
1904
+ * Whether any edge of `ringA` properly crosses an edge of `ringB`, or whether the rings touch
1905
+ * (shared vertex, collinear overlap, vertex on edge). Touching is reported separately because it
1906
+ * cannot be resolved without an exact boolean operation. Rings are closed (schema-valid input), so
1907
+ * consecutive vertex pairs cover every edge.
1908
+ */
1909
+ const relateRings = (ringA, ringB, bboxB) => {
1910
+ let touching = false;
1911
+ for (let i = 0; i + 1 < ringA.length; i++) {
1912
+ const a = ringA[i];
1913
+ const b = ringA[i + 1];
1914
+ if (a === undefined || b === undefined)
1915
+ continue;
1916
+ const edgeMinX = Math.min(a[0], b[0]);
1917
+ const edgeMaxX = Math.max(a[0], b[0]);
1918
+ const edgeMinY = Math.min(a[1], b[1]);
1919
+ const edgeMaxY = Math.max(a[1], b[1]);
1920
+ if (edgeMaxX < bboxB[0] || edgeMinX > bboxB[2] || edgeMaxY < bboxB[1] || edgeMinY > bboxB[3])
1921
+ continue;
1922
+ for (let j = 0; j + 1 < ringB.length; j++) {
1923
+ const c = ringB[j];
1924
+ const d = ringB[j + 1];
1925
+ if (c === undefined || d === undefined)
1926
+ continue;
1927
+ if (Math.max(c[0], d[0]) < edgeMinX || Math.min(c[0], d[0]) > edgeMaxX)
1928
+ continue;
1929
+ if (Math.max(c[1], d[1]) < edgeMinY || Math.min(c[1], d[1]) > edgeMaxY)
1930
+ continue;
1931
+ const relation = relateSegments(a, b, c, d);
1932
+ if (relation === PROPER_CROSSING)
1933
+ return PROPER_CROSSING;
1934
+ if (relation === TOUCHING)
1935
+ touching = true;
1936
+ }
1937
+ }
1938
+ return touching ? TOUCHING : DISJOINT;
1939
+ };
1940
+ /**
1941
+ * Exact overlap test for two simple polygons (exterior ring + holes) without a boolean operation.
1942
+ *
1943
+ * One exterior vertex of each polygon is classified against the other first: strictly inside (hole
1944
+ * aware) proves shared interior in O(|A| + |B|), which is the common containment case, provided the
1945
+ * vertex borders its own polygon's interior (a hole touching the exterior there makes the probe
1946
+ * `"undecided"`); on the boundary is `"undecided"`. Only when both probes are outside does the
1947
+ * O(|A|·|B|) edge sweep run.
1948
+ *
1949
+ * A proper edge crossing between two hole-free polygons means their interiors overlap. With holes it
1950
+ * does not: a hole flush with the exterior (or two holes sharing an edge) leaves a boundary segment
1951
+ * that borders no interior, so a crossing there is `"undecided"` and left to the exact fallback, as
1952
+ * is any touching or collinear edge.
1953
+ *
1954
+ * If no edge crosses or touches and both probes were outside, each exterior ring lies entirely
1955
+ * outside the other polygon's area, so the polygons are disjoint.
1956
+ */
1957
+ const polygonsOverlap = (polygonA, polygonB) => {
1958
+ const exteriorA = polygonA[0];
1959
+ const exteriorB = polygonB[0];
1960
+ if (exteriorA === undefined || exteriorB === undefined)
1961
+ return false;
1962
+ const bboxesB = polygonB.map(ringBbox);
1963
+ const exteriorBboxB = bboxesB[0];
1964
+ if (exteriorBboxB === undefined || !bboxesIntersect(ringBbox(exteriorA), exteriorBboxB))
1965
+ return false;
1966
+ const vertexA = exteriorA[0];
1967
+ const vertexB = exteriorB[0];
1968
+ if (vertexA === undefined || vertexB === undefined)
1969
+ return false;
1970
+ const aInB = classifyPositionAgainstPolygon(vertexA, polygonB);
1971
+ if (aInB === ON_BOUNDARY)
1972
+ return "undecided";
1973
+ if (aInB === INSIDE)
1974
+ return vertexBordersInterior(vertexA, polygonA) ? true : "undecided";
1975
+ const bInA = classifyPositionAgainstPolygon(vertexB, polygonA);
1976
+ if (bInA === ON_BOUNDARY)
1977
+ return "undecided";
1978
+ if (bInA === INSIDE)
1979
+ return vertexBordersInterior(vertexB, polygonB) ? true : "undecided";
1980
+ const crossingIsDecisive = polygonA.length === 1 && polygonB.length === 1;
1981
+ for (const ringA of polygonA) {
1982
+ for (let b = 0; b < polygonB.length; b++) {
1983
+ const ringB = polygonB[b];
1984
+ const bboxB = bboxesB[b];
1985
+ if (ringB === undefined || bboxB === undefined)
1986
+ continue;
1987
+ const relation = relateRings(ringA, ringB, bboxB);
1988
+ if (relation === PROPER_CROSSING)
1989
+ return crossingIsDecisive ? true : "undecided";
1990
+ if (relation === TOUCHING)
1991
+ return "undecided";
1992
+ }
1993
+ }
1994
+ return false;
1995
+ };
1996
+ const polygonsOf = (geometry) => geometry.type === "Polygon" ? [geometry.coordinates] : geometry.coordinates;
1997
+ const asPolygon = (rings) => ({ type: "Polygon", coordinates: rings });
1998
+ /**
1999
+ * Whether two polygonal geometries share interior area.
2000
+ *
2001
+ * Equivalent to `getGeoJsonPolygonIntersection(a, b) !== null` for simple polygons, but without
2002
+ * computing the intersection geometry: a bbox reject, one point-in-polygon probe per side, then an
2003
+ * edge-crossing test. Degenerate configurations (shared vertices, collinear or near-collinear edges
2004
+ * within {@link COLLINEAR_TOLERANCE}, a vertex on the other boundary, a probe vertex that touches a
2005
+ * hole) and crossings that involve a polygon with holes fall back to the boolean operation,
2006
+ * evaluated only for the undecided pairs of parts of a MultiPolygon, so the result is exact and the
2007
+ * fallback's failure modes (it can throw for degenerate input) are preserved for callers to handle
2008
+ * without a far-away part poisoning the answer.
2009
+ *
2010
+ * Known divergence: a ring with a zero-area part (a spike that doubles back on itself, a
2011
+ * self-touching lobe) is invalid GeoJSON that the schema does not reject. When such a zero-area edge
2012
+ * crosses the other polygon, this predicate reports overlap while the boolean operation, which
2013
+ * ignores zero-area geometry, does not.
2014
+ *
2015
+ * Inputs are assumed schema-valid (closed rings); this is a hot-path helper for rendering code.
2016
+ */
2017
+ const polygonalGeometriesOverlap = (a, b) => {
2018
+ const undecided = [];
2019
+ for (const polygonA of polygonsOf(a)) {
2020
+ for (const polygonB of polygonsOf(b)) {
2021
+ const verdict = polygonsOverlap(polygonA, polygonB);
2022
+ if (verdict === true)
2023
+ return true;
2024
+ if (verdict === "undecided")
2025
+ undecided.push([polygonA, polygonB]);
2026
+ }
2027
+ }
2028
+ return undecided.some(([polygonA, polygonB]) => getGeoJsonPolygonIntersection(asPolygon(polygonA), asPolygon(polygonB)) !== null);
2029
+ };
2030
+
1763
2031
  //! These tools are used to bridge the gap with out poorly typed graphql types
1764
2032
  // Should be ideally be avoided but are needed until we fix the graphql types
1765
2033
  const isDoubleNestedCoords = (coords) => Array.isArray(coords) &&
@@ -2100,6 +2368,7 @@ const edgePixelLength = (x0, y0, x1, y1, zoom, midLatDeg, tileSize = 256) => {
2100
2368
  return Math.sqrt(dxPx * dxPx + dyPx * dyPx);
2101
2369
  };
2102
2370
 
2371
+ exports.COLLINEAR_TOLERANCE = COLLINEAR_TOLERANCE;
2103
2372
  exports.EARTH_RADIUS = EARTH_RADIUS;
2104
2373
  exports.EMPTY_FEATURE_COLLECTION = EMPTY_FEATURE_COLLECTION;
2105
2374
  exports.boundingBoxCrossesMeridian = boundingBoxCrossesMeridian;
@@ -2154,6 +2423,7 @@ exports.mercatorPxToLngLatWS = mercatorPxToLngLatWS;
2154
2423
  exports.normalizeLongitudes = normalizeLongitudes;
2155
2424
  exports.padGeoJsonBbox = padGeoJsonBbox;
2156
2425
  exports.pixelsToLatDegrees = pixelsToLatDegrees;
2426
+ exports.polygonalGeometriesOverlap = polygonalGeometriesOverlap;
2157
2427
  exports.projectLngLatToWebMercator = projectLngLatToWebMercator;
2158
2428
  exports.projectPolygonalToWebMercator = projectPolygonalToWebMercator;
2159
2429
  exports.scaleGeoJsonBbox = scaleGeoJsonBbox;
package/index.esm.js CHANGED
@@ -1442,6 +1442,9 @@ const isFullyContainedInGeoJsonPolygon = (polygon1, polygon2) => {
1442
1442
  * catch and treat the throw as no intersection; callers that turn `null` into "no spatial
1443
1443
  * filter" (e.g. `mapUtils` viewport/area merges) must instead fall back to a conservative
1444
1444
  * geometry rather than assume disjointness.
1445
+ *
1446
+ * Callers that only need to know *whether* two geometries overlap should use
1447
+ * `polygonalGeometriesOverlap` instead, which answers without building the intersection.
1445
1448
  */
1446
1449
  const getGeoJsonPolygonIntersection = (polygon1, polygon2) => {
1447
1450
  const geom1 = polygon1.type === "MultiPolygon" ? toClipMultiPolygon(polygon1.coordinates) : [toClipPolygon(polygon1.coordinates)];
@@ -1593,7 +1596,7 @@ const ensureMinimumGeoJsonBboxSpan = (bbox, minSpanDegrees) => {
1593
1596
  * Returns Polygon for a single-ring result, MultiPolygon otherwise.
1594
1597
  * When clips is empty the subject is returned unchanged.
1595
1598
  */
1596
- const geoJsonPolygonDifference = (subject, clips) => {
1599
+ const geoJsonPolygonDifference = (subject, clips, onFallback) => {
1597
1600
  if (clips.length === 0) {
1598
1601
  return subject;
1599
1602
  }
@@ -1603,10 +1606,12 @@ const geoJsonPolygonDifference = (subject, clips) => {
1603
1606
  try {
1604
1607
  differenceResult = polygonClipping.difference(subjectClip, ...clipsConverted);
1605
1608
  }
1606
- catch {
1609
+ catch (error) {
1607
1610
  // polygon-clipping can throw "Unable to complete output ring" for degenerate or
1608
1611
  // near-self-intersecting polygons. Fall back to returning the subject unclipped
1609
- // so the shape still renders rather than crashing the caller.
1612
+ // so the shape still renders rather than crashing the caller; `onFallback` lets
1613
+ // callers surface that the clip was skipped (SAGA-743).
1614
+ onFallback?.(error);
1610
1615
  return subject;
1611
1616
  }
1612
1617
  if (differenceResult.length === 0) {
@@ -1758,6 +1763,269 @@ const distanceToGeoJsonPolygonBoundary = (position, geometry) => {
1758
1763
  return minDist === Infinity ? null : minDist;
1759
1764
  };
1760
1765
 
1766
+ const OUTSIDE = 0;
1767
+ const INSIDE = 1;
1768
+ const ON_BOUNDARY = 2;
1769
+ const DISJOINT = 0;
1770
+ const PROPER_CROSSING = 1;
1771
+ const TOUCHING = 2;
1772
+ /**
1773
+ * A point closer than this to a segment's line, as a fraction of the coordinate magnitude, counts as
1774
+ * collinear (about 0.1 mm for lon/lat). Anything inside the band is routed to the exact fallback.
1775
+ *
1776
+ * `polygon-clipping` 0.15.7 snaps coordinates that are within `Number.EPSILON` of each other
1777
+ * (relative, per axis) before sweeping, so a vertex within rounding noise of the other polygon's
1778
+ * edge is "touching" for it; a raw determinant here would call the same configuration a clean
1779
+ * crossing or a clean inside/outside and disagree. The band is deliberately much wider than that
1780
+ * snapping so that vertices produced by interpolation onto an edge land in it too; its edges are
1781
+ * pinned by the spec.
1782
+ */
1783
+ const COLLINEAR_TOLERANCE = 1e-11;
1784
+ const ringBbox = (ring) => {
1785
+ let minX = Infinity;
1786
+ let minY = Infinity;
1787
+ let maxX = -Infinity;
1788
+ let maxY = -Infinity;
1789
+ for (let i = 0; i < ring.length; i++) {
1790
+ const position = ring[i];
1791
+ if (position === undefined)
1792
+ continue;
1793
+ const x = position[0];
1794
+ const y = position[1];
1795
+ if (x < minX)
1796
+ minX = x;
1797
+ if (x > maxX)
1798
+ maxX = x;
1799
+ if (y < minY)
1800
+ minY = y;
1801
+ if (y > maxY)
1802
+ maxY = y;
1803
+ }
1804
+ return [minX, minY, maxX, maxY];
1805
+ };
1806
+ /** Planar interval test; longitudes are never wrapped here (fill tiling densifies and splits first). */
1807
+ const bboxesIntersect = (a, b) => a[0] <= b[2] && b[0] <= a[2] && a[1] <= b[3] && b[1] <= a[3];
1808
+ /**
1809
+ * Sign of the turn a→b→c (positive = counter-clockwise), with `0` when c lies within
1810
+ * {@link COLLINEAR_TOLERANCE} × coordinate magnitude of the line through a and b. Compared in
1811
+ * squared form so no square root or division runs per call.
1812
+ */
1813
+ const orientation = (a, b, c) => {
1814
+ const abx = b[0] - a[0];
1815
+ const aby = b[1] - a[1];
1816
+ const determinant = abx * (c[1] - a[1]) - aby * (c[0] - a[0]);
1817
+ const lengthSquared = abx * abx + aby * aby;
1818
+ if (lengthSquared === 0)
1819
+ return 0;
1820
+ const magnitude = Math.max(1, Math.abs(a[0]), Math.abs(a[1]), Math.abs(b[0]), Math.abs(b[1]), Math.abs(c[0]), Math.abs(c[1]));
1821
+ const band = COLLINEAR_TOLERANCE * magnitude;
1822
+ return determinant * determinant <= band * band * lengthSquared ? 0 : determinant;
1823
+ };
1824
+ /**
1825
+ * Ray casting (crossing number) with an explicit on-segment check so boundary points are not
1826
+ * misclassified. The on-segment test uses the same tolerant `orientation` as the edge tests, so a
1827
+ * vertex the edge sweep would call touching is never silently classified inside or outside here.
1828
+ */
1829
+ const classifyPositionAgainstRing = (point, ring) => {
1830
+ const [px, py] = point;
1831
+ let inside = false;
1832
+ for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
1833
+ const current = ring[i];
1834
+ const previous = ring[j];
1835
+ if (current === undefined || previous === undefined)
1836
+ continue;
1837
+ const [xi, yi] = current;
1838
+ const [xj, yj] = previous;
1839
+ if (px >= Math.min(xi, xj) &&
1840
+ px <= Math.max(xi, xj) &&
1841
+ py >= Math.min(yi, yj) &&
1842
+ py <= Math.max(yi, yj) &&
1843
+ orientation(current, previous, point) === 0) {
1844
+ return ON_BOUNDARY;
1845
+ }
1846
+ if (yi > py !== yj > py && px < ((xj - xi) * (py - yi)) / (yj - yi) + xi) {
1847
+ inside = !inside;
1848
+ }
1849
+ }
1850
+ return inside ? INSIDE : OUTSIDE;
1851
+ };
1852
+ /** Hole-aware classification: inside the exterior ring and outside every hole. */
1853
+ const classifyPositionAgainstPolygon = (point, rings) => {
1854
+ const exterior = rings[0];
1855
+ if (exterior === undefined)
1856
+ return OUTSIDE;
1857
+ const againstExterior = classifyPositionAgainstRing(point, exterior);
1858
+ if (againstExterior !== INSIDE)
1859
+ return againstExterior;
1860
+ for (let h = 1; h < rings.length; h++) {
1861
+ const hole = rings[h];
1862
+ if (hole === undefined)
1863
+ continue;
1864
+ const againstHole = classifyPositionAgainstRing(point, hole);
1865
+ if (againstHole === INSIDE)
1866
+ return OUTSIDE;
1867
+ if (againstHole === ON_BOUNDARY)
1868
+ return ON_BOUNDARY;
1869
+ }
1870
+ return INSIDE;
1871
+ };
1872
+ /**
1873
+ * An exterior vertex only proves interior area next to it when no hole of its own polygon touches
1874
+ * it; a hole meeting the exterior at a vertex is valid GeoJSON, and there the polygon has no area
1875
+ * on the hole's side.
1876
+ */
1877
+ const vertexBordersInterior = (vertex, rings) => {
1878
+ for (let h = 1; h < rings.length; h++) {
1879
+ const hole = rings[h];
1880
+ if (hole !== undefined && classifyPositionAgainstRing(vertex, hole) === ON_BOUNDARY)
1881
+ return false;
1882
+ }
1883
+ return true;
1884
+ };
1885
+ /**
1886
+ * Relation of segments a–b and c–d whose bounding boxes already overlap (the caller filters on that).
1887
+ * A collinear endpoint is reported as TOUCHING even when the segments do not meet; that only costs a
1888
+ * fallback to the exact operation, never a wrong answer.
1889
+ */
1890
+ const relateSegments = (a, b, c, d) => {
1891
+ const o1 = orientation(a, b, c);
1892
+ const o2 = orientation(a, b, d);
1893
+ const o3 = orientation(c, d, a);
1894
+ const o4 = orientation(c, d, b);
1895
+ if (o1 * o2 < 0 && o3 * o4 < 0)
1896
+ return PROPER_CROSSING;
1897
+ if (o1 === 0 || o2 === 0 || o3 === 0 || o4 === 0)
1898
+ return TOUCHING;
1899
+ return DISJOINT;
1900
+ };
1901
+ /**
1902
+ * Whether any edge of `ringA` properly crosses an edge of `ringB`, or whether the rings touch
1903
+ * (shared vertex, collinear overlap, vertex on edge). Touching is reported separately because it
1904
+ * cannot be resolved without an exact boolean operation. Rings are closed (schema-valid input), so
1905
+ * consecutive vertex pairs cover every edge.
1906
+ */
1907
+ const relateRings = (ringA, ringB, bboxB) => {
1908
+ let touching = false;
1909
+ for (let i = 0; i + 1 < ringA.length; i++) {
1910
+ const a = ringA[i];
1911
+ const b = ringA[i + 1];
1912
+ if (a === undefined || b === undefined)
1913
+ continue;
1914
+ const edgeMinX = Math.min(a[0], b[0]);
1915
+ const edgeMaxX = Math.max(a[0], b[0]);
1916
+ const edgeMinY = Math.min(a[1], b[1]);
1917
+ const edgeMaxY = Math.max(a[1], b[1]);
1918
+ if (edgeMaxX < bboxB[0] || edgeMinX > bboxB[2] || edgeMaxY < bboxB[1] || edgeMinY > bboxB[3])
1919
+ continue;
1920
+ for (let j = 0; j + 1 < ringB.length; j++) {
1921
+ const c = ringB[j];
1922
+ const d = ringB[j + 1];
1923
+ if (c === undefined || d === undefined)
1924
+ continue;
1925
+ if (Math.max(c[0], d[0]) < edgeMinX || Math.min(c[0], d[0]) > edgeMaxX)
1926
+ continue;
1927
+ if (Math.max(c[1], d[1]) < edgeMinY || Math.min(c[1], d[1]) > edgeMaxY)
1928
+ continue;
1929
+ const relation = relateSegments(a, b, c, d);
1930
+ if (relation === PROPER_CROSSING)
1931
+ return PROPER_CROSSING;
1932
+ if (relation === TOUCHING)
1933
+ touching = true;
1934
+ }
1935
+ }
1936
+ return touching ? TOUCHING : DISJOINT;
1937
+ };
1938
+ /**
1939
+ * Exact overlap test for two simple polygons (exterior ring + holes) without a boolean operation.
1940
+ *
1941
+ * One exterior vertex of each polygon is classified against the other first: strictly inside (hole
1942
+ * aware) proves shared interior in O(|A| + |B|), which is the common containment case, provided the
1943
+ * vertex borders its own polygon's interior (a hole touching the exterior there makes the probe
1944
+ * `"undecided"`); on the boundary is `"undecided"`. Only when both probes are outside does the
1945
+ * O(|A|·|B|) edge sweep run.
1946
+ *
1947
+ * A proper edge crossing between two hole-free polygons means their interiors overlap. With holes it
1948
+ * does not: a hole flush with the exterior (or two holes sharing an edge) leaves a boundary segment
1949
+ * that borders no interior, so a crossing there is `"undecided"` and left to the exact fallback, as
1950
+ * is any touching or collinear edge.
1951
+ *
1952
+ * If no edge crosses or touches and both probes were outside, each exterior ring lies entirely
1953
+ * outside the other polygon's area, so the polygons are disjoint.
1954
+ */
1955
+ const polygonsOverlap = (polygonA, polygonB) => {
1956
+ const exteriorA = polygonA[0];
1957
+ const exteriorB = polygonB[0];
1958
+ if (exteriorA === undefined || exteriorB === undefined)
1959
+ return false;
1960
+ const bboxesB = polygonB.map(ringBbox);
1961
+ const exteriorBboxB = bboxesB[0];
1962
+ if (exteriorBboxB === undefined || !bboxesIntersect(ringBbox(exteriorA), exteriorBboxB))
1963
+ return false;
1964
+ const vertexA = exteriorA[0];
1965
+ const vertexB = exteriorB[0];
1966
+ if (vertexA === undefined || vertexB === undefined)
1967
+ return false;
1968
+ const aInB = classifyPositionAgainstPolygon(vertexA, polygonB);
1969
+ if (aInB === ON_BOUNDARY)
1970
+ return "undecided";
1971
+ if (aInB === INSIDE)
1972
+ return vertexBordersInterior(vertexA, polygonA) ? true : "undecided";
1973
+ const bInA = classifyPositionAgainstPolygon(vertexB, polygonA);
1974
+ if (bInA === ON_BOUNDARY)
1975
+ return "undecided";
1976
+ if (bInA === INSIDE)
1977
+ return vertexBordersInterior(vertexB, polygonB) ? true : "undecided";
1978
+ const crossingIsDecisive = polygonA.length === 1 && polygonB.length === 1;
1979
+ for (const ringA of polygonA) {
1980
+ for (let b = 0; b < polygonB.length; b++) {
1981
+ const ringB = polygonB[b];
1982
+ const bboxB = bboxesB[b];
1983
+ if (ringB === undefined || bboxB === undefined)
1984
+ continue;
1985
+ const relation = relateRings(ringA, ringB, bboxB);
1986
+ if (relation === PROPER_CROSSING)
1987
+ return crossingIsDecisive ? true : "undecided";
1988
+ if (relation === TOUCHING)
1989
+ return "undecided";
1990
+ }
1991
+ }
1992
+ return false;
1993
+ };
1994
+ const polygonsOf = (geometry) => geometry.type === "Polygon" ? [geometry.coordinates] : geometry.coordinates;
1995
+ const asPolygon = (rings) => ({ type: "Polygon", coordinates: rings });
1996
+ /**
1997
+ * Whether two polygonal geometries share interior area.
1998
+ *
1999
+ * Equivalent to `getGeoJsonPolygonIntersection(a, b) !== null` for simple polygons, but without
2000
+ * computing the intersection geometry: a bbox reject, one point-in-polygon probe per side, then an
2001
+ * edge-crossing test. Degenerate configurations (shared vertices, collinear or near-collinear edges
2002
+ * within {@link COLLINEAR_TOLERANCE}, a vertex on the other boundary, a probe vertex that touches a
2003
+ * hole) and crossings that involve a polygon with holes fall back to the boolean operation,
2004
+ * evaluated only for the undecided pairs of parts of a MultiPolygon, so the result is exact and the
2005
+ * fallback's failure modes (it can throw for degenerate input) are preserved for callers to handle
2006
+ * without a far-away part poisoning the answer.
2007
+ *
2008
+ * Known divergence: a ring with a zero-area part (a spike that doubles back on itself, a
2009
+ * self-touching lobe) is invalid GeoJSON that the schema does not reject. When such a zero-area edge
2010
+ * crosses the other polygon, this predicate reports overlap while the boolean operation, which
2011
+ * ignores zero-area geometry, does not.
2012
+ *
2013
+ * Inputs are assumed schema-valid (closed rings); this is a hot-path helper for rendering code.
2014
+ */
2015
+ const polygonalGeometriesOverlap = (a, b) => {
2016
+ const undecided = [];
2017
+ for (const polygonA of polygonsOf(a)) {
2018
+ for (const polygonB of polygonsOf(b)) {
2019
+ const verdict = polygonsOverlap(polygonA, polygonB);
2020
+ if (verdict === true)
2021
+ return true;
2022
+ if (verdict === "undecided")
2023
+ undecided.push([polygonA, polygonB]);
2024
+ }
2025
+ }
2026
+ return undecided.some(([polygonA, polygonB]) => getGeoJsonPolygonIntersection(asPolygon(polygonA), asPolygon(polygonB)) !== null);
2027
+ };
2028
+
1761
2029
  //! These tools are used to bridge the gap with out poorly typed graphql types
1762
2030
  // Should be ideally be avoided but are needed until we fix the graphql types
1763
2031
  const isDoubleNestedCoords = (coords) => Array.isArray(coords) &&
@@ -2098,4 +2366,4 @@ const edgePixelLength = (x0, y0, x1, y1, zoom, midLatDeg, tileSize = 256) => {
2098
2366
  return Math.sqrt(dxPx * dxPx + dyPx * dyPx);
2099
2367
  };
2100
2368
 
2101
- export { EARTH_RADIUS, EMPTY_FEATURE_COLLECTION, boundingBoxCrossesMeridian, checkCrossesMeridian, computeGeometryCentroid, coordinatesToStandardFormat, denormalizeLongitude, distanceToGeoJsonPolygonBoundary, edgePixelLength, ensureMinimumGeoJsonBboxSpan, extractEdges, extractFirstPointCoordinate, extractPositionsFromGeometry, geoJsonBboxSchema, geoJsonFeatureCollectionSchema, geoJsonFeatureSchema, geoJsonGeometryCollectionSchema, geoJsonGeometrySchema, geoJsonLineStringSchema, geoJsonLinearRingSchema, geoJsonMultiLineStringSchema, geoJsonMultiPointSchema, geoJsonMultiPolygonSchema, geoJsonPointSchema, geoJsonPolygonDifference, geoJsonPolygonSchema, geoJsonPosition2dSchema, geoJsonPositionSchema, getBboxFromGeoJsonPolygon, getBoundingBoxFromGeoJsonBbox, getBoundingBoxFromGeoJsonPolygon, getExtremeGeoJsonPointFromPolygon, getGeoJsonPolygonFromBoundingBox, getGeoJsonPolygonIntersection, getMinMaxLongitudes, getMultipleCoordinatesFromGeoJsonObject, getPointCoordinateFromGeoJsonObject, getPointCoordinateFromGeoJsonPoint, getPolygonFromBbox, getPolygonFromPointAndRadius, isBboxInsideFeatureCollection, isFullyContainedInGeoJsonGeometry, isFullyContainedInGeoJsonPolygon, isFullyContainedInGeometry, isGeoJsonPointInPolygon, isGeoJsonPositionInLinearRing, isPointInPolygon, isPositionInsideRing, lngLatToMercatorPxWS, lngLatToWebMercatorPx, mercatorPxToLngLatWS, normalizeLongitudes, padGeoJsonBbox, pixelsToLatDegrees, projectLngLatToWebMercator, projectPolygonalToWebMercator, scaleGeoJsonBbox, splitAntimeridianCrossingFeatures, splitAntimeridianCrossingGeometry, splitPolygonAtAntimeridian, splitPolygonWithHolesAtAntimeridian, toFeatureCollection, toPosition2d, tuGeoJsonPointRadiusSchema, tuGeoJsonPolygonNoHolesSchema, tuGeoJsonRectangularBoxPolygonSchema, unprojectPolygonalFromWebMercator, unprojectWebMercatorToLngLat, validateBbox, validateBboxWithFallback, validateFeatureCollection, validatePosition, webMercatorPxToLngLat };
2369
+ export { COLLINEAR_TOLERANCE, EARTH_RADIUS, EMPTY_FEATURE_COLLECTION, boundingBoxCrossesMeridian, checkCrossesMeridian, computeGeometryCentroid, coordinatesToStandardFormat, denormalizeLongitude, distanceToGeoJsonPolygonBoundary, edgePixelLength, ensureMinimumGeoJsonBboxSpan, extractEdges, extractFirstPointCoordinate, extractPositionsFromGeometry, geoJsonBboxSchema, geoJsonFeatureCollectionSchema, geoJsonFeatureSchema, geoJsonGeometryCollectionSchema, geoJsonGeometrySchema, geoJsonLineStringSchema, geoJsonLinearRingSchema, geoJsonMultiLineStringSchema, geoJsonMultiPointSchema, geoJsonMultiPolygonSchema, geoJsonPointSchema, geoJsonPolygonDifference, geoJsonPolygonSchema, geoJsonPosition2dSchema, geoJsonPositionSchema, getBboxFromGeoJsonPolygon, getBoundingBoxFromGeoJsonBbox, getBoundingBoxFromGeoJsonPolygon, getExtremeGeoJsonPointFromPolygon, getGeoJsonPolygonFromBoundingBox, getGeoJsonPolygonIntersection, getMinMaxLongitudes, getMultipleCoordinatesFromGeoJsonObject, getPointCoordinateFromGeoJsonObject, getPointCoordinateFromGeoJsonPoint, getPolygonFromBbox, getPolygonFromPointAndRadius, isBboxInsideFeatureCollection, isFullyContainedInGeoJsonGeometry, isFullyContainedInGeoJsonPolygon, isFullyContainedInGeometry, isGeoJsonPointInPolygon, isGeoJsonPositionInLinearRing, isPointInPolygon, isPositionInsideRing, lngLatToMercatorPxWS, lngLatToWebMercatorPx, mercatorPxToLngLatWS, normalizeLongitudes, padGeoJsonBbox, pixelsToLatDegrees, polygonalGeometriesOverlap, projectLngLatToWebMercator, projectPolygonalToWebMercator, scaleGeoJsonBbox, splitAntimeridianCrossingFeatures, splitAntimeridianCrossingGeometry, splitPolygonAtAntimeridian, splitPolygonWithHolesAtAntimeridian, toFeatureCollection, toPosition2d, tuGeoJsonPointRadiusSchema, tuGeoJsonPolygonNoHolesSchema, tuGeoJsonRectangularBoxPolygonSchema, unprojectPolygonalFromWebMercator, unprojectWebMercatorToLngLat, validateBbox, validateBboxWithFallback, validateFeatureCollection, validatePosition, webMercatorPxToLngLat };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trackunit/geo-json-utils",
3
- "version": "1.21.43-alpha-b8d3d323d1a.0",
3
+ "version": "1.21.43",
4
4
  "repository": "https://github.com/Trackunit/manager",
5
5
  "license": "SEE LICENSE IN LICENSE.txt",
6
6
  "engines": {
@@ -124,6 +124,9 @@ export declare const isFullyContainedInGeoJsonPolygon: (polygon1: GeoJsonPolygon
124
124
  * catch and treat the throw as no intersection; callers that turn `null` into "no spatial
125
125
  * filter" (e.g. `mapUtils` viewport/area merges) must instead fall back to a conservative
126
126
  * geometry rather than assume disjointness.
127
+ *
128
+ * Callers that only need to know *whether* two geometries overlap should use
129
+ * `polygonalGeometriesOverlap` instead, which answers without building the intersection.
127
130
  */
128
131
  export declare const getGeoJsonPolygonIntersection: (polygon1: GeoJsonPolygon | GeoJsonMultiPolygon, polygon2: GeoJsonPolygon | GeoJsonMultiPolygon) => GeoJsonMultiPolygon | GeoJsonPolygon | null;
129
132
  /**
@@ -179,7 +182,7 @@ export declare const ensureMinimumGeoJsonBboxSpan: (bbox: GeoJsonBbox, minSpanDe
179
182
  * Returns Polygon for a single-ring result, MultiPolygon otherwise.
180
183
  * When clips is empty the subject is returned unchanged.
181
184
  */
182
- export declare const geoJsonPolygonDifference: (subject: GeoJsonPolygon | GeoJsonMultiPolygon, clips: ReadonlyArray<GeoJsonPolygon | GeoJsonMultiPolygon>) => GeoJsonPolygon | GeoJsonMultiPolygon | null;
185
+ export declare const geoJsonPolygonDifference: (subject: GeoJsonPolygon | GeoJsonMultiPolygon, clips: ReadonlyArray<GeoJsonPolygon | GeoJsonMultiPolygon>, onFallback?: (error: unknown) => void) => GeoJsonPolygon | GeoJsonMultiPolygon | null;
183
186
  /**
184
187
  * Project a `[lng, lat]` position to Web Mercator metres (EPSG:3857).
185
188
  *
@@ -0,0 +1,33 @@
1
+ import type { GeoJsonMultiPolygon, GeoJsonPolygon } from "./GeoJsonSchemas";
2
+ /**
3
+ * A point closer than this to a segment's line, as a fraction of the coordinate magnitude, counts as
4
+ * collinear (about 0.1 mm for lon/lat). Anything inside the band is routed to the exact fallback.
5
+ *
6
+ * `polygon-clipping` 0.15.7 snaps coordinates that are within `Number.EPSILON` of each other
7
+ * (relative, per axis) before sweeping, so a vertex within rounding noise of the other polygon's
8
+ * edge is "touching" for it; a raw determinant here would call the same configuration a clean
9
+ * crossing or a clean inside/outside and disagree. The band is deliberately much wider than that
10
+ * snapping so that vertices produced by interpolation onto an edge land in it too; its edges are
11
+ * pinned by the spec.
12
+ */
13
+ export declare const COLLINEAR_TOLERANCE = 1e-11;
14
+ /**
15
+ * Whether two polygonal geometries share interior area.
16
+ *
17
+ * Equivalent to `getGeoJsonPolygonIntersection(a, b) !== null` for simple polygons, but without
18
+ * computing the intersection geometry: a bbox reject, one point-in-polygon probe per side, then an
19
+ * edge-crossing test. Degenerate configurations (shared vertices, collinear or near-collinear edges
20
+ * within {@link COLLINEAR_TOLERANCE}, a vertex on the other boundary, a probe vertex that touches a
21
+ * hole) and crossings that involve a polygon with holes fall back to the boolean operation,
22
+ * evaluated only for the undecided pairs of parts of a MultiPolygon, so the result is exact and the
23
+ * fallback's failure modes (it can throw for degenerate input) are preserved for callers to handle
24
+ * without a far-away part poisoning the answer.
25
+ *
26
+ * Known divergence: a ring with a zero-area part (a spike that doubles back on itself, a
27
+ * self-touching lobe) is invalid GeoJSON that the schema does not reject. When such a zero-area edge
28
+ * crosses the other polygon, this predicate reports overlap while the boolean operation, which
29
+ * ignores zero-area geometry, does not.
30
+ *
31
+ * Inputs are assumed schema-valid (closed rings); this is a hot-path helper for rendering code.
32
+ */
33
+ export declare const polygonalGeometriesOverlap: (a: GeoJsonPolygon | GeoJsonMultiPolygon, b: GeoJsonPolygon | GeoJsonMultiPolygon) => boolean;
package/src/index.d.ts CHANGED
@@ -3,6 +3,7 @@ export * from "./GeoJsonRuntimeValidation";
3
3
  export * from "./GeoJsonSchemas";
4
4
  export * from "./GeoJsonUtils";
5
5
  export * from "./MeridianUtils";
6
+ export * from "./PolygonOverlap";
6
7
  export * from "./TuGeoJsonBridgeUtils";
7
8
  export * from "./TuGeoJsonConversions";
8
9
  export * from "./TuGeoJsonSchemas";