mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-16 16:22:20 +00:00
Merge main through #1495 into the renderer seam
Brings in radio country coverage (#1206), the restored format scope (#1527), the zoom-out guard (#1522), voice geometry and OSM places (#846) and paired traffic flow density (#1495). What main added that reached Cesium or the viewer now goes through the renderer: - The zoom-out guard reads the Cesium camera controller's own input, so it moves into the adapter (src/render/cesium/zoomOutGuard.js). The application installs it through the scene's viewer hooks, and a scene whose renderer gives no guard starts without one. - OSM places draws its points as a draw set, clamped to the ground. - The voice area actions read the view box and the view centre from the camera port. - The voice workflow harness is test support, named as such where the recent-imagery doubles are.
This commit is contained in:
commit
fd42fc0afd
136 files changed
+17399
-1120
No files matched your search
@@ -0,0 +1,190 @@
|
||||
import { fromDegrees } from '../../geo/ellipsoid.js';
|
||||
import { drawOf } from '../../render/rendererOf.js';
|
||||
import { msg } from '../../i18n/marker.js';
|
||||
import { OSM_PLACES_LAYER_ID } from './model.js';
|
||||
import { createNominatimStatus } from '../../sources/nominatimStatus.js';
|
||||
export * from './model.js';
|
||||
|
||||
const OVERLAY_SOURCE_ID = OSM_PLACES_LAYER_ID;
|
||||
/** Named results that get a map label; the rest are points. */
|
||||
const LABEL_LIMIT = 48;
|
||||
const COLOR = '#7fe3ff';
|
||||
const OUTLINE = [0, 0, 0, 0.8];
|
||||
|
||||
/** Each layer's draw set id is its own. */
|
||||
let instances = 0;
|
||||
|
||||
/**
|
||||
* OSM Places: the results of the last voice OpenStreetMap search ("hospitals
|
||||
* in Kathmandu"), drawn as points (a draw set on the viewer's renderer) with
|
||||
* name labels and queryable by
|
||||
* analyst_query. It fetches nothing itself; `setResults` replaces the set.
|
||||
* The search runs only on an operator-configured Overpass, so without one
|
||||
* the layer stays empty. Session-only: never in share links or stored layer
|
||||
* state.
|
||||
* @param {{overlayHost: object, overpassConfigured?: () => Promise<boolean|null>}} options
|
||||
*/
|
||||
export function createOsmPlacesLayer({
|
||||
overlayHost,
|
||||
// The same once-per-page capability probe as Nominatim's, on Overpass.
|
||||
overpassConfigured = createNominatimStatus({ url: '/api/overpass/status' }),
|
||||
} = {}) {
|
||||
if (!overlayHost) throw new TypeError('OSM Places requires an overlay host');
|
||||
let viewer = null;
|
||||
/** The places' points, or null before `init` and after `destroy`. */
|
||||
let points = null;
|
||||
let enabled = false;
|
||||
let records = [];
|
||||
let meta = null;
|
||||
let lastUpdate = null;
|
||||
/** true / false from the server's probe, null while unknown. */
|
||||
let configured = null;
|
||||
|
||||
function render() {
|
||||
if (!points) return;
|
||||
const items = [];
|
||||
const overlay = [];
|
||||
for (const record of records) {
|
||||
items.push({
|
||||
id: `osm-place:${record.id}`,
|
||||
pos: { lon: record.lon, lat: record.lat },
|
||||
height: 'clampGround',
|
||||
pixelSize: 9,
|
||||
color: COLOR,
|
||||
outlineColor: OUTLINE,
|
||||
outlineWidth: 2,
|
||||
// On top only up close (as bikeshare stations): beyond that the
|
||||
// depth test keeps far-side points from showing through the globe.
|
||||
disableDepthTest: 2500,
|
||||
});
|
||||
if (record.name && overlay.length < LABEL_LIMIT)
|
||||
overlay.push({
|
||||
id: record.id,
|
||||
position: fromDegrees(record.lon, record.lat),
|
||||
variant: 'label',
|
||||
title: record.name.slice(0, 40),
|
||||
accent: COLOR,
|
||||
priority: LABEL_LIMIT - overlay.length,
|
||||
collisionGroup: 'ambient-label',
|
||||
paintLane: 'ambient-label',
|
||||
interactive: false,
|
||||
edgeFade: 'keyhole',
|
||||
horizonCull: true,
|
||||
terrainOcclusion: false,
|
||||
gapPx: 12,
|
||||
verticalOnly: true,
|
||||
placement: 'above',
|
||||
});
|
||||
}
|
||||
points.set(items);
|
||||
if (enabled)
|
||||
overlayHost.setEntries(OVERLAY_SOURCE_ID, overlay, {
|
||||
cohortLimit: LABEL_LIMIT,
|
||||
collisionCapacity: LABEL_LIMIT,
|
||||
moving: false,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
id: OSM_PLACES_LAYER_ID,
|
||||
name: 'OSM Places',
|
||||
icon: '⌖',
|
||||
source: 'OpenStreetMap',
|
||||
updateInterval: 0,
|
||||
|
||||
/** Unavailable only once the server says no Overpass is configured. */
|
||||
getSourceAvailability() {
|
||||
return configured === false
|
||||
? {
|
||||
available: false,
|
||||
source: OSM_PLACES_LAYER_ID,
|
||||
reason: 'Needs an operator-configured Overpass server',
|
||||
}
|
||||
: { available: true, source: OSM_PLACES_LAYER_ID, reason: null };
|
||||
},
|
||||
|
||||
init(nextViewer) {
|
||||
viewer = nextViewer;
|
||||
Promise.resolve(overpassConfigured?.())
|
||||
.then((answer) => {
|
||||
if (typeof answer === 'boolean') configured = answer;
|
||||
})
|
||||
.catch(() => {});
|
||||
points?.dispose();
|
||||
points = drawOf(viewer).points({
|
||||
id: `${OSM_PLACES_LAYER_ID}:${++instances}:points`,
|
||||
show: false,
|
||||
});
|
||||
overlayHost.setVisible(OVERLAY_SOURCE_ID, false);
|
||||
},
|
||||
|
||||
enable() {
|
||||
enabled = true;
|
||||
if (points) points.show = true;
|
||||
overlayHost.setVisible(OVERLAY_SOURCE_ID, true);
|
||||
render();
|
||||
return true;
|
||||
},
|
||||
|
||||
disable() {
|
||||
enabled = false;
|
||||
if (points) points.show = false;
|
||||
overlayHost.clearSource(OVERLAY_SOURCE_ID);
|
||||
overlayHost.setVisible(OVERLAY_SOURCE_ID, false);
|
||||
return true;
|
||||
},
|
||||
|
||||
/** Nothing to poll: results change only through setResults. */
|
||||
async update() {
|
||||
return true;
|
||||
},
|
||||
|
||||
destroy() {
|
||||
enabled = false;
|
||||
overlayHost.clearSource(OVERLAY_SOURCE_ID);
|
||||
overlayHost.setVisible(OVERLAY_SOURCE_ID, false);
|
||||
points?.dispose();
|
||||
points = null;
|
||||
viewer = null;
|
||||
records = [];
|
||||
meta = null;
|
||||
lastUpdate = null;
|
||||
},
|
||||
|
||||
/**
|
||||
* Replace the result set.
|
||||
* @param {object[]} next Records from `mapOsmFeature`.
|
||||
* @param {{kind: string, label: string, area: string}} nextMeta
|
||||
*/
|
||||
setResults(next, nextMeta) {
|
||||
records = Array.isArray(next) ? next.slice() : [];
|
||||
meta = nextMeta ? { ...nextMeta } : null;
|
||||
lastUpdate = Date.now();
|
||||
render();
|
||||
},
|
||||
|
||||
/** The current search, for panels and voice. */
|
||||
getResultsMeta() {
|
||||
return meta ? { ...meta, count: records.length } : null;
|
||||
},
|
||||
|
||||
getAnalystRecords(maxCount = 2000) {
|
||||
if (!enabled) return [];
|
||||
const limit = Number.isFinite(maxCount)
|
||||
? Math.max(1, Math.floor(maxCount))
|
||||
: 2000;
|
||||
return records.slice(0, limit).map((record) => ({ ...record }));
|
||||
},
|
||||
|
||||
getStats() {
|
||||
return {
|
||||
count: records.length,
|
||||
lastUpdate,
|
||||
error: null,
|
||||
statusMessage: meta
|
||||
? `${meta.label} · ${meta.area}`
|
||||
: msg('Voice place search (needs an Overpass server)'),
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
// OSM Places holds the last voice search's results: queryable while shown,
|
||||
// labelled through the overlay host, and nothing when switched off.
|
||||
//
|
||||
// Run with: npm test
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createOsmPlacesLayer } from './index.js';
|
||||
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
|
||||
|
||||
function fakeOverlayHost() {
|
||||
const calls = [];
|
||||
return {
|
||||
calls,
|
||||
setEntries: (...args) => calls.push(['setEntries', ...args]),
|
||||
clearSource: (...args) => calls.push(['clearSource', ...args]),
|
||||
setVisible: (...args) => calls.push(['setVisible', ...args]),
|
||||
};
|
||||
}
|
||||
|
||||
const RECORDS = [
|
||||
{
|
||||
id: 'node/1',
|
||||
lat: 27.7,
|
||||
lon: 85.3,
|
||||
name: 'Bir Hospital',
|
||||
kind: 'hospital',
|
||||
},
|
||||
{ id: 'node/2', lat: 27.71, lon: 85.31, name: null, kind: 'hospital' },
|
||||
];
|
||||
|
||||
test('results are queryable only while the layer is on, and labels follow names', () => {
|
||||
const host = fakeOverlayHost();
|
||||
const layer = createOsmPlacesLayer({ overlayHost: host });
|
||||
layer.setResults(RECORDS, {
|
||||
kind: 'hospital',
|
||||
label: 'hospitals',
|
||||
area: 'Kathmandu',
|
||||
});
|
||||
assert.deepEqual(layer.getAnalystRecords(), [], 'off: nothing to count');
|
||||
assert.equal(layer.getStats().count, 2);
|
||||
assert.equal(layer.getStats().statusMessage, 'hospitals · Kathmandu');
|
||||
layer.enable();
|
||||
const records = layer.getAnalystRecords();
|
||||
assert.equal(records.length, 2);
|
||||
records[0].name = 'changed';
|
||||
assert.equal(
|
||||
layer.getAnalystRecords()[0].name,
|
||||
'Bir Hospital',
|
||||
'callers get copies',
|
||||
);
|
||||
assert.deepEqual(layer.getResultsMeta(), {
|
||||
kind: 'hospital',
|
||||
label: 'hospitals',
|
||||
area: 'Kathmandu',
|
||||
count: 2,
|
||||
});
|
||||
layer.disable();
|
||||
assert.ok(
|
||||
host.calls.some(
|
||||
([name, id]) => name === 'clearSource' && id === 'osm-places',
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
test('an empty layer tells the operator how to fill it', () => {
|
||||
const layer = createOsmPlacesLayer({ overlayHost: fakeOverlayHost() });
|
||||
assert.match(layer.getStats().statusMessage, /needs an Overpass server/);
|
||||
assert.throws(() => createOsmPlacesLayer(), TypeError);
|
||||
});
|
||||
|
||||
test('destroy and re-init expose a fresh empty session', () => {
|
||||
const host = fakeOverlayHost();
|
||||
const layer = createOsmPlacesLayer({ overlayHost: host });
|
||||
layer.setResults(RECORDS, {
|
||||
kind: 'hospital',
|
||||
label: 'hospitals',
|
||||
area: 'Kathmandu',
|
||||
});
|
||||
assert.ok(layer.getStats().lastUpdate);
|
||||
layer.destroy();
|
||||
const viewer = {};
|
||||
const { draw } = bindFakeDraw(viewer);
|
||||
layer.init(viewer);
|
||||
layer.enable();
|
||||
assert.equal(layer.getResultsMeta(), null);
|
||||
assert.deepEqual(layer.getAnalystRecords(), []);
|
||||
assert.deepEqual(layer.getStats(), {
|
||||
count: 0,
|
||||
lastUpdate: null,
|
||||
error: null,
|
||||
statusMessage: 'Voice place search (needs an Overpass server)',
|
||||
});
|
||||
const [points] = draw.sets.values();
|
||||
assert.equal(points.items.size, 0, 'a fresh session draws nothing');
|
||||
layer.setResults(RECORDS, {});
|
||||
assert.equal(points.items.size, 2);
|
||||
layer.destroy();
|
||||
assert.equal(points.disposed, true, 'destroy lets the points go');
|
||||
});
|
||||
|
||||
test('without an operator Overpass the layer shows as unavailable', async () => {
|
||||
const viewer = {};
|
||||
bindFakeDraw(viewer);
|
||||
const off = createOsmPlacesLayer({
|
||||
overlayHost: fakeOverlayHost(),
|
||||
overpassConfigured: async () => false,
|
||||
});
|
||||
assert.equal(
|
||||
off.getSourceAvailability().available,
|
||||
true,
|
||||
'unknown until asked',
|
||||
);
|
||||
off.init(viewer);
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
assert.equal(off.getSourceAvailability().available, false);
|
||||
const unknown = createOsmPlacesLayer({
|
||||
overlayHost: fakeOverlayHost(),
|
||||
overpassConfigured: async () => null,
|
||||
});
|
||||
unknown.init(viewer);
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
assert.equal(
|
||||
unknown.getSourceAvailability().available,
|
||||
true,
|
||||
'an unknown answer keeps it listed',
|
||||
);
|
||||
});
|
||||
|
||||
test('places are depth-tested past close range, so they never show through the globe', () => {
|
||||
const viewer = {};
|
||||
const { draw } = bindFakeDraw(viewer);
|
||||
const layer = createOsmPlacesLayer({
|
||||
overlayHost: fakeOverlayHost(),
|
||||
overpassConfigured: async () => true,
|
||||
});
|
||||
layer.init(viewer);
|
||||
layer.enable();
|
||||
layer.setResults(RECORDS, {
|
||||
kind: 'hospital',
|
||||
label: 'hospitals',
|
||||
area: 'Kathmandu',
|
||||
});
|
||||
const [points] = draw.sets.values();
|
||||
assert.equal(points.show, true, 'shown while the layer is on');
|
||||
const [point] = points.items.values();
|
||||
assert.equal(point.height, 'clampGround');
|
||||
const distance = point.disableDepthTest;
|
||||
assert.ok(
|
||||
Number.isFinite(distance) && distance <= 5000,
|
||||
`depth test off only within ${distance} m`,
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
/**
|
||||
* OSM Places records: OpenStreetMap features found by a voice search,
|
||||
* mapped to plain analyst records. Pure — no Cesium.
|
||||
* @module layers/osmPlaces/model
|
||||
*/
|
||||
|
||||
export const OSM_PLACES_LAYER_ID = 'osm-places';
|
||||
/** A node and a way/relation of the same name this close are one site mapped twice. */
|
||||
const SAME_SITE_M = 75;
|
||||
|
||||
/** Longest tag value kept; OSM names are open text that reaches the model. */
|
||||
const MAX_TEXT = 120;
|
||||
|
||||
/**
|
||||
* A tag value as plain bounded text: control characters (newlines, tabs)
|
||||
* become spaces; format characters (bidi overrides, zero-width spaces) are
|
||||
* dropped, except the zero-width (non-)joiners Persian and Indic names spell
|
||||
* with; runs of whitespace collapse, and long values are cut with an
|
||||
* ellipsis.
|
||||
*/
|
||||
function text(value) {
|
||||
if (typeof value !== 'string') return null;
|
||||
const clean = value
|
||||
.replace(/\p{Cc}+/gu, ' ')
|
||||
.replace(/(?![\u200c\u200d])\p{Cf}/gu, '')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
if (!clean) return null;
|
||||
// Cut on code points so an emoji's surrogate pair is never split.
|
||||
const chars = Array.from(clean);
|
||||
return chars.length <= MAX_TEXT
|
||||
? clean
|
||||
: `${chars
|
||||
.slice(0, MAX_TEXT - 1)
|
||||
.join('')
|
||||
.trimEnd()}…`;
|
||||
}
|
||||
|
||||
function distanceM(a, b) {
|
||||
const toRad = Math.PI / 180;
|
||||
const x = (b.lon - a.lon) * toRad * Math.cos(((a.lat + b.lat) / 2) * toRad);
|
||||
const y = (b.lat - a.lat) * toRad;
|
||||
return Math.hypot(x, y) * 6_371_000;
|
||||
}
|
||||
|
||||
/**
|
||||
* One feature from `/api/osm/features` → an analyst record.
|
||||
* @param {{id: string, lat: number, lon: number, tags?: object}} feature
|
||||
* @param {{id: string, label: string}} preset
|
||||
* @returns {object|null}
|
||||
*/
|
||||
export function mapOsmFeature(feature, preset) {
|
||||
if (!Number.isFinite(feature?.lat) || !Number.isFinite(feature?.lon))
|
||||
return null;
|
||||
const tags = feature.tags || {};
|
||||
const [osmType] = String(feature.id || '').split('/');
|
||||
return {
|
||||
id: String(feature.id),
|
||||
lat: feature.lat,
|
||||
lon: feature.lon,
|
||||
name: text(tags['name:en']) || text(tags.name),
|
||||
kind: preset.id,
|
||||
operator: text(tags.operator) || text(tags.brand),
|
||||
emergency: text(tags.emergency),
|
||||
wheelchair: text(tags.wheelchair),
|
||||
openingHours: text(tags.opening_hours),
|
||||
city: text(tags['addr:city']),
|
||||
osmType: ['node', 'way', 'relation'].includes(osmType) ? osmType : null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove double counting without merging distinct places:
|
||||
*
|
||||
* - the same OSM element (identical `type/id`) is counted once;
|
||||
* - a node and a way/relation with the same name within 75 m are one site
|
||||
* mapped twice (a point on the building and the building outline), and
|
||||
* merge;
|
||||
* - two nodes, or two ways, are always distinct places — two neighbouring
|
||||
* cafés of one chain are two cafés — and never merge, whatever their names.
|
||||
*
|
||||
* @param {object[]} records
|
||||
* @returns {{records: object[], merged: number}}
|
||||
*/
|
||||
export function dedupeOsmRecords(records) {
|
||||
const kept = [];
|
||||
const seen = new Set();
|
||||
let merged = 0;
|
||||
for (const record of records) {
|
||||
if (seen.has(record.id)) {
|
||||
merged += 1;
|
||||
continue;
|
||||
}
|
||||
seen.add(record.id);
|
||||
const name = record.name?.toLowerCase();
|
||||
const isNode = record.osmType === 'node';
|
||||
const sameSite =
|
||||
name &&
|
||||
record.osmType &&
|
||||
kept.some(
|
||||
(other) =>
|
||||
other.osmType &&
|
||||
(other.osmType === 'node') !== isNode &&
|
||||
other.name?.toLowerCase() === name &&
|
||||
distanceM(other, record) <= SAME_SITE_M,
|
||||
);
|
||||
if (sameSite) merged += 1;
|
||||
else kept.push(record);
|
||||
}
|
||||
return { records: kept, merged };
|
||||
}
|
||||
@@ -1208,6 +1208,16 @@ export function createRecentImageryLayer({
|
||||
notify('alpha');
|
||||
},
|
||||
|
||||
/** Stop catalog/preview work owned by a cancelled voice action. */
|
||||
cancelPendingSearch() {
|
||||
// Without a note the emptied strip would read as "no imagery".
|
||||
if (_searching) _notice = msg('Search cancelled');
|
||||
cancelSearch();
|
||||
clearPending();
|
||||
syncRender();
|
||||
notify();
|
||||
},
|
||||
|
||||
/**
|
||||
* Forget the box, the candidates, both pins, the preview and any pending
|
||||
* pick; reset opacity and split and cancel the box tool. Mode and
|
||||
|
||||
@@ -1430,3 +1430,13 @@ test('with SELECT BOX armed, Escape clears the preview first and the next Escape
|
||||
assert.equal(f.snap().toolActive, false);
|
||||
await tool.destroy();
|
||||
});
|
||||
|
||||
test('a voice search cancelled mid-flight says so instead of looking empty', async () => {
|
||||
const f = fixture();
|
||||
f.layer.enable();
|
||||
f.layer.setBox(BOX);
|
||||
assert.equal(f.snap().searching, true);
|
||||
f.layer.cancelPendingSearch();
|
||||
assert.equal(f.snap().searching, false);
|
||||
assert.equal(f.snap().notice, 'Search cancelled');
|
||||
});
|
||||
@@ -20,6 +20,19 @@ function tileFreshness(response) {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Clip a flow line to a box. Every piece keeps its uncut line as `line`, so
|
||||
* pieces of one line that doubles back are never paired with each other.
|
||||
*/
|
||||
function clipFlowSegment(segment, bbox) {
|
||||
const line = segment.line || segment;
|
||||
return clipTileLine(segment.coords, bbox).map((coords) => ({
|
||||
...segment,
|
||||
coords,
|
||||
line,
|
||||
}));
|
||||
}
|
||||
|
||||
/** Own one bounded decoded flow cache; every request still passes the server tile budget. */
|
||||
export function createFlowTileSource({
|
||||
fetchImpl = (...args) => globalThis.fetch(...args),
|
||||
@@ -41,12 +54,7 @@ export function createFlowTileSource({
|
||||
entry?.release();
|
||||
const segments = decodeFlowTile(bytes, z, x, y, { strict: true })
|
||||
.filter(isDrivableFlowSegment)
|
||||
.flatMap((segment) =>
|
||||
clipTileLine(segment.coords, tileToBBox(z, x, y)).map((coords) => ({
|
||||
...segment,
|
||||
coords,
|
||||
})),
|
||||
);
|
||||
.flatMap((segment) => clipFlowSegment(segment, tileToBBox(z, x, y)));
|
||||
if (mark) freshness.set(segments, mark);
|
||||
return segments;
|
||||
},
|
||||
@@ -87,12 +95,9 @@ export function createFlowTileSource({
|
||||
partial = result.partial;
|
||||
const segments = bounds.coverage
|
||||
? result.tiles.flat()
|
||||
: result.tiles.flat().flatMap((segment) =>
|
||||
clipTileLine(segment.coords, bounds).map((coords) => ({
|
||||
...segment,
|
||||
coords,
|
||||
})),
|
||||
);
|
||||
: result.tiles
|
||||
.flat()
|
||||
.flatMap((segment) => clipFlowSegment(segment, bounds));
|
||||
const marks = result.tiles.map((tile) => freshness.get(tile) || {});
|
||||
const times = marks
|
||||
.map((mark) => mark.fetchedAt)
|
||||
|
||||
@@ -35,6 +35,14 @@ const MIN_FILL_M = 40;
|
||||
* Same-class overlap keeps the full 35 m matcher radius.
|
||||
*/
|
||||
const CLASS_MISMATCH_RADIUS_M = 15;
|
||||
/**
|
||||
* Opposite-direction TomTom lines this close share one street: TomTom draws
|
||||
* both directions of a two-way street a metre or two apart, and a divided
|
||||
* carriageway's sides further apart.
|
||||
*/
|
||||
const PAIRED_SIDE_RADIUS_M = 5;
|
||||
/** Arc-length positions sampled along a `one_side` line for its partner. */
|
||||
const PAIRED_SIDE_SAMPLES = [0.25, 0.5, 0.75];
|
||||
const CONTROLLED_ACCESS_FLOW = new Set(['Motorway', 'International road']);
|
||||
const CONTROLLED_ACCESS_OSM = new Set(['motorway', 'trunk']);
|
||||
|
||||
@@ -85,20 +93,69 @@ export function isDrivableFlowSegment(segment) {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Share of a `one_side` line's sample points (PAIRED_SIDE_SAMPLES) with an
|
||||
* opposite-direction TomTom line beside them: TomTom draws a two-way street
|
||||
* whose directions differ as two `one_side` lines on one centreline, while a
|
||||
* divided carriageway's other side is further away than PAIRED_SIDE_RADIUS_M.
|
||||
* @returns {number} Paired share in [0, 1].
|
||||
*/
|
||||
function pairedSampleShare(segment, index) {
|
||||
const xs = [];
|
||||
const ys = [];
|
||||
const cum = [0];
|
||||
for (const [lon, lat] of segment.coords) {
|
||||
const [x, y] = index.project(lon, lat);
|
||||
const i = xs.push(x) - 1;
|
||||
ys.push(y);
|
||||
if (i) cum.push(cum[i - 1] + Math.hypot(x - xs[i - 1], y - ys[i - 1]));
|
||||
}
|
||||
const length = cum[cum.length - 1];
|
||||
if (!(length > 0)) return 0;
|
||||
const line = segment.line || segment;
|
||||
let paired = 0;
|
||||
let i = 1;
|
||||
for (const share of PAIRED_SIDE_SAMPLES) {
|
||||
const target = share * length;
|
||||
while (i < cum.length - 1 && cum[i] < target) i++;
|
||||
const dx = xs[i] - xs[i - 1];
|
||||
const dy = ys[i] - ys[i - 1];
|
||||
const t = (target - cum[i - 1]) / (cum[i] - cum[i - 1] || 1);
|
||||
const reverse = (Math.atan2(-dx, -dy) * 180) / Math.PI;
|
||||
if (
|
||||
index.nearest(
|
||||
xs[i - 1] + dx * t,
|
||||
ys[i - 1] + dy * t,
|
||||
reverse,
|
||||
// A line that doubles back beside itself, even clipped into pieces,
|
||||
// is not its own pair.
|
||||
(piece) =>
|
||||
(piece.flow.line || piece.flow) === line ? 0 : PAIRED_SIDE_RADIUS_M,
|
||||
).best
|
||||
)
|
||||
paired++;
|
||||
}
|
||||
return paired / PAIRED_SIDE_SAMPLES.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert decoded TomTom flow lines into road records that carry their own
|
||||
* flow. A line with `coverage: 'full'` describes both travel directions;
|
||||
* `one_side` lines describe the direction they are drawn in.
|
||||
* `one_side` lines describe the direction they are drawn in. A `one_side`
|
||||
* line paired with the opposite direction on the same street gets that
|
||||
* direction's half share of dots, as a two-way road's direction does.
|
||||
* @param {Array<{coords:number[][], trafficLevel:number, roadType:string, closure:boolean, coverage?:string}>} segments
|
||||
* @returns {Array<object>} Road records (`directFlow: true`).
|
||||
*/
|
||||
export function flowSegmentsToRoads(segments) {
|
||||
return (segments || [])
|
||||
.filter(
|
||||
(segment) =>
|
||||
segment?.coords?.length >= 2 && isDrivableFlowSegment(segment),
|
||||
)
|
||||
.map((segment) => ({
|
||||
const drivable = (segments || []).filter(
|
||||
(segment) => segment?.coords?.length >= 2 && isDrivableFlowSegment(segment),
|
||||
);
|
||||
const sides = createFlowSegmentIndex(
|
||||
drivable.filter((segment) => segment.coverage !== 'full'),
|
||||
);
|
||||
return drivable.map((segment) => {
|
||||
const road = {
|
||||
coordinates: segment.coords,
|
||||
type: FLOW_ROAD_TYPES[segment.roadType],
|
||||
drivable: true,
|
||||
@@ -110,7 +167,15 @@ export function flowSegmentsToRoads(segments) {
|
||||
oneway: segment.coverage === 'full' ? 0 : 1,
|
||||
flow: { level: segment.trafficLevel, closure: segment.closure === true },
|
||||
directFlow: true,
|
||||
}));
|
||||
};
|
||||
if (
|
||||
segment.coverage !== 'full' &&
|
||||
sides &&
|
||||
pairedSampleShare(segment, sides) >= 0.5
|
||||
)
|
||||
road.densityWeight = 0.5;
|
||||
return road;
|
||||
});
|
||||
}
|
||||
|
||||
/** Cut a projected polyline to the arc-length interval [from, to]. */
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { PbfWriter } from 'pbf';
|
||||
import {
|
||||
flowSegmentsToRoads,
|
||||
resolveRoadMode,
|
||||
selectTrafficRoads,
|
||||
} from './roadModes.js';
|
||||
import { createFlowTileSource } from './flowSource.js';
|
||||
import { createTrafficSource } from './source.js';
|
||||
import { createTrafficLayer } from './index.js';
|
||||
import {
|
||||
@@ -14,6 +16,7 @@ import {
|
||||
serializeStoredLayerState,
|
||||
parseStoredLayerState,
|
||||
} from '../../data/layerState.js';
|
||||
import { tileToBBox } from '../../data/tomtomTiles.js';
|
||||
|
||||
const coordinates = [
|
||||
[-97.744, 30.267],
|
||||
@@ -116,6 +119,133 @@ test('a full-coverage TomTom line is two-way and covers both OSM directions', ()
|
||||
assert.equal(roads.length, 1);
|
||||
assert.equal(roads[0].directFlow, true);
|
||||
});
|
||||
test("opposite TomTom sides of one street share a two-way street's dots", () => {
|
||||
// About 1 m and 20 m north of `coordinates`, drawn westbound.
|
||||
const back = (dLat) => ({
|
||||
...flow,
|
||||
coords: coordinates.map(([lon, lat]) => [lon, lat + dLat]).reverse(),
|
||||
});
|
||||
const weights = (segments) =>
|
||||
flowSegmentsToRoads(segments).map((road) => road.densityWeight ?? 1);
|
||||
assert.deepEqual(weights([flow, back(0.00001)]), [0.5, 0.5]);
|
||||
assert.deepEqual(weights([flow]), [1], 'a lone side keeps the one-way share');
|
||||
assert.deepEqual(
|
||||
weights([flow, back(0.00018)]),
|
||||
[1, 1],
|
||||
'a divided carriageway keeps one-way shares',
|
||||
);
|
||||
assert.deepEqual(
|
||||
weights([
|
||||
flow,
|
||||
{
|
||||
...flow,
|
||||
coords: coordinates.map(([lon, lat]) => [lon, lat + 0.00001]),
|
||||
},
|
||||
]),
|
||||
[1, 1],
|
||||
'same-direction lines are not a pair',
|
||||
);
|
||||
assert.deepEqual(
|
||||
weights([{ ...flow, coverage: 'full' }, back(0.00001)]),
|
||||
[1, 1],
|
||||
'a full-coverage line is not a side, and pairs with nothing',
|
||||
);
|
||||
});
|
||||
test('a TomTom side paired along only part of its length keeps its share', () => {
|
||||
// Westbound partners about 1 m north, from the start of `flow` to 30% and
|
||||
// to 60% of its length: one or two of its three sample points.
|
||||
const partner = (toLon) => ({
|
||||
...flow,
|
||||
coords: [
|
||||
[toLon, 30.26701],
|
||||
[-97.744, 30.26701],
|
||||
],
|
||||
});
|
||||
const weightOfFlow = (other) =>
|
||||
flowSegmentsToRoads([flow, other])[0].densityWeight ?? 1;
|
||||
assert.equal(weightOfFlow(partner(-97.7434)), 1);
|
||||
assert.equal(weightOfFlow(partner(-97.7428)), 0.5);
|
||||
});
|
||||
test('a TomTom side that doubles back beside itself is not its own pair', () => {
|
||||
// East along `coordinates`, then back west about 1 m north.
|
||||
const hairpin = {
|
||||
...flow,
|
||||
coords: [...coordinates, [-97.742, 30.26701], [-97.744, 30.26701]],
|
||||
};
|
||||
assert.equal(flowSegmentsToRoads([hairpin])[0].densityWeight ?? 1, 1);
|
||||
});
|
||||
/** A flow tile of one-way Major roads; each line is [x, y, x, y, ...]. */
|
||||
function flowTile(lines) {
|
||||
const writer = new PbfWriter();
|
||||
writer.writeMessage(3, writeFlowLayer, lines);
|
||||
return writer.finish();
|
||||
}
|
||||
function writeFlowLayer(lines, layer) {
|
||||
layer.writeVarintField(15, 2);
|
||||
layer.writeStringField(1, 'Traffic flow');
|
||||
layer.writeVarintField(5, 4096);
|
||||
layer.writeStringField(3, 'traffic_level');
|
||||
layer.writeMessage(4, (_, value) => value.writeDoubleField(3, 0.6), null);
|
||||
layer.writeStringField(3, 'road_type');
|
||||
layer.writeMessage(
|
||||
4,
|
||||
(_, value) => value.writeStringField(1, 'Major road'),
|
||||
null,
|
||||
);
|
||||
layer.writeStringField(3, 'traffic_road_coverage');
|
||||
layer.writeMessage(
|
||||
4,
|
||||
(_, value) => value.writeStringField(1, 'one_side'),
|
||||
null,
|
||||
);
|
||||
for (const xy of lines) {
|
||||
// MoveTo one point, LineTo the rest, as zigzag deltas.
|
||||
const geometry = [9];
|
||||
for (let i = 0; i < xy.length; i++) {
|
||||
if (i === 2) geometry.push(2 | ((xy.length / 2 - 1) << 3));
|
||||
const delta = xy[i] - (i < 2 ? 0 : xy[i - 2]);
|
||||
geometry.push((delta << 1) ^ (delta >> 31));
|
||||
}
|
||||
layer.writeMessage(
|
||||
2,
|
||||
(_, feature) => {
|
||||
feature.writeVarintField(3, 2);
|
||||
feature.writePackedVarint(2, [0, 0, 1, 1, 2, 2]);
|
||||
feature.writePackedVarint(4, geometry);
|
||||
},
|
||||
null,
|
||||
);
|
||||
}
|
||||
}
|
||||
test('TomTom sides clipped by their tile and the view pair only with other lines', async () => {
|
||||
// A one-way hairpin turning in the tile buffer, its arms one tile unit
|
||||
// (about 2 m) apart, and a separate opposite pair. The tile clip cuts the
|
||||
// hairpin into two arms; the view clip then cuts every line again.
|
||||
const lines = [
|
||||
[500, 1000, 4300, 1000, 4300, 1001, 500, 1001],
|
||||
[-200, 3000, 4300, 3000],
|
||||
[4300, 3001, -200, 3001],
|
||||
];
|
||||
const source = createFlowTileSource({
|
||||
fetchImpl: async () => new Response(flowTile(lines)),
|
||||
});
|
||||
const tile = tileToBBox(12, 935, 1686);
|
||||
const west = tile.west + (tile.east - tile.west) * 0.2;
|
||||
const { segments } = await source.fetchFlowDetail({
|
||||
...tile,
|
||||
west,
|
||||
east: tile.east - 1e-9,
|
||||
south: tile.south + 1e-9,
|
||||
});
|
||||
assert.equal(segments.length, 4);
|
||||
assert.ok(
|
||||
segments.every((s) => s.coords.every(([lon]) => lon >= west - 1e-10)),
|
||||
);
|
||||
assert.deepEqual(
|
||||
flowSegmentsToRoads(segments).map((road) => road.densityWeight ?? 1),
|
||||
[1, 1, 0.5, 0.5],
|
||||
);
|
||||
});
|
||||
test('bearing and distance reject nearby crossing and separate OSM roads', () => {
|
||||
const parallel = {
|
||||
...main,
|
||||
|
||||
@@ -67,7 +67,16 @@ function fixture(t) {
|
||||
const nodes = () => [
|
||||
...container.querySelectorAll('.gev-wind-inspection-marker'),
|
||||
];
|
||||
return { owner, viewer, store, frames, projected, requests, nodes, container };
|
||||
return {
|
||||
owner,
|
||||
viewer,
|
||||
store,
|
||||
frames,
|
||||
projected,
|
||||
requests,
|
||||
nodes,
|
||||
container,
|
||||
};
|
||||
}
|
||||
|
||||
test('the marker follows only its captured point, hides beyond the limb, and releases its listener', async (t) => {
|
||||
|
||||
Reference in new issue
Block a user