import {
cameraOf,
canvasOf,
drawOf,
findCamera,
findFrame,
findGlobe,
findQuery,
} from '../render/rendererOf.js';
import { cssColor } from '../render/color.js';
import { fromDegrees, fromDegreesInto, toLonLatH } from '../geo/ellipsoid.js';
import { sphereFromPoints } from '../geo/sphere.js';
import { densifyRhumb } from '../geo/rhumb.js';
import { heightsOf } from '../queries/heights.js';
import {
layerTitle,
mapAnalystRecord,
parseGeojsonLines,
} from '../sources/infrastructureData.js';
import { createInfrastructureOverlayEntry } from './infrastructureOverlayEntry.js';
import { inputFor as defaultInputFor } from '../input/dispatcher.js';
import {
selectInfraLod,
applyInfraEvictionGrace,
shouldRecomputeInfraLod,
} from './localGeojsonLod.js';
const DEFAULT_LABEL_MAX = 900;
const DEFAULT_LABEL_GRID_PX = 132;
const VISIBILITY_UPDATE_MS = 450;
// Each source keeps its own bounded cohort; the host sums their ambient-card
// paint budgets only up to its 192-card shared-lane ceiling.
export const LOCAL_OVERLAY_COHORT_LIMIT = 160;
const LOCAL_OVERLAY_COLLISION_CAPACITY = 96;
const LOCAL_OVERLAY_CELL_SURPLUS = 2;
// Stems are anchored at ellipsoid height 0, but high-elevation features
// (e.g. dams in river canyons) sit hundreds of meters above the ellipsoid,
// burying the short close-in stem inside the photoreal mesh. Once the
// camera is near enough for tiles to be loaded, sample the real surface
// height once per feature and lift the stem onto it.
const GROUND_SAMPLE_MAX_DISTANCE_M = 75000;
const GROUND_SAMPLE_RETRY_MS = 2000;
const GROUND_SAMPLE_MAX_ABS_HEIGHT_M = 9000;
/**
* Bounded give-up for the self-armed retry. Sampling can be SUPPORTED and still
* never succeed (no sampleable surface under the feature), in which case each
* requested frame would arm the next 2 s timer forever — an idle-governor leak
* dressed up as a retry. After this many consecutive armed retries with no
* record newly grounded, stop arming; camera motion (a frame we get for free)
* still retries through the normal preRender walk and re-opens the budget.
* 30 × 2 s ≈ 60 s, far longer than a tile stream-in.
*/
export const GROUND_SAMPLE_MAX_ARMED_RETRIES = 30;
/** Ignore sub-metre camera-derived stem-tip noise at camera settle. */
export const LOCAL_STEM_TIP_EPSILON_M = 0.5;
const LOCAL_STEM_TIP_EPSILON_SQ = LOCAL_STEM_TIP_EPSILON_M ** 2;
/**
* Build the owner-approved local-infrastructure card copy.
* @param {object} properties Unwrapped GeoJSON feature properties.
* @param {string} layerId Local layer id.
* @returns {{title:string,details:string[]}}
*/
export function localInfrastructureOverlayCopy(properties, layerId) {
const props = unwrapProperties(properties) || {};
const tags = props.tags || {};
const title = featureLabelFromProperties(props, layerId);
const details = [];
if (layerId === 'local-datacenters') {
const operator = firstClean([
tags.operator,
props.operator,
tags['operator:short'],
]);
const capacity = firstClean([
tags['capacity:it_load'],
tags.it_load,
tags.capacity,
props.capacity,
]);
const line = [operator, capacity]
.filter(
(value, index, values) => value && values.indexOf(value) === index,
)
.filter(
(value) => value.toLocaleLowerCase() !== title.toLocaleLowerCase(),
)
.join(' · ');
if (line) details.push(clampCardLine(line));
} else if (layerId === 'local-dams') {
const river = firstClean([
tags.associated_river,
props.associated_river,
tags.river,
props.river,
tags['river:name'],
]);
if (river && river.toLocaleLowerCase() !== title.toLocaleLowerCase()) {
details.push(clampCardLine(river));
}
}
return { title, details };
}
/**
* Produce one normalized-contract input owned by a local infrastructure layer.
* The host revalidates the authoritative `source` value while normalizing it.
* @param {object} options
* @param {string} options.id Stable id within the source.
* @param {string} options.layerId Local layer id.
* @param {{x: number, y: number, z: number}} options.position Current stem-tip
* position, ECEF metres.
* @param {object} options.properties Unwrapped feature properties.
* @param {number} options.priority Source-owned importance score.
* @param {string} options.accent Source accent color.
* @returns {object}
*/
export function createLocalInfrastructureOverlayEntry({
id,
layerId,
position,
properties,
priority,
accent,
}) {
const copy = localInfrastructureOverlayCopy(properties, layerId);
return createInfrastructureOverlayEntry({
id,
source: layerId,
position,
title: copy.title,
details: copy.details,
accent,
priority,
});
}
/**
* Retain a bounded screen-grid surplus for the host's final rectangle arbiter.
* Two deterministic contenders per legacy grid cell preserve the old density
* while giving the shared solver an alternative when the first card collides.
* @param {object[]} records Local stem/entry records.
* @param {object} options
* @param {number} options.maxEntries Legacy source cap.
* @param {number} options.gridPx Legacy screen grid size.
* @param {number} options.width Viewport width in CSS pixels.
* @param {number} options.height Viewport height in CSS pixels.
* @param {function(object):({x:number,y:number}|null)} options.project Projection callback.
* @param {number} [options.cohortLimit=Infinity] Host-safe materialization cap.
* @returns {object[]} Bounded overlay entries for shared-host arbitration.
*/
export function selectLocalInfrastructureOverlayCohort(
records,
{
maxEntries,
gridPx,
width,
height,
project,
cohortLimit = Number.POSITIVE_INFINITY,
},
) {
const sourceCap = Math.max(0, Math.floor(Number(maxEntries) || 0));
const materializationCap = Number.isFinite(Number(cohortLimit))
? Math.max(0, Math.floor(Number(cohortLimit)))
: Number.POSITIVE_INFINITY;
const cap = Math.min(sourceCap, materializationCap);
const cellSize = Math.max(1, Number(gridPx) || 1);
if (
!Array.isArray(records) ||
records.length === 0 ||
cap === 0 ||
typeof project !== 'function'
) {
return [];
}
const cells = new Map();
const padding = cellSize;
for (const record of records) {
const screen = project(record);
if (!Number.isFinite(screen?.x) || !Number.isFinite(screen?.y)) continue;
if (
screen.x < -padding ||
screen.x > width + padding ||
screen.y < -padding ||
screen.y > height + padding
)
continue;
const key = `${Math.floor(screen.x / cellSize)}:${Math.floor(screen.y / cellSize)}`;
let contenders = cells.get(key);
if (!contenders) {
contenders = [];
cells.set(key, contenders);
}
insertLocalCellContender(contenders, record);
}
const primary = [];
const surplus = [];
for (const contenders of cells.values()) {
if (contenders[0]) primary.push(contenders[0]);
if (contenders[1]) surplus.push(contenders[1]);
}
primary.sort(compareLocalOverlayRecords);
surplus.sort(compareLocalOverlayRecords);
if (primary.length >= cap)
return primary.slice(0, cap).map((record) => record.entry);
const candidates = primary.concat(surplus.slice(0, cap - primary.length));
return candidates.map((record) => record.entry);
}
/**
* Bind a local layer's visibility and entry lifecycle to the shared host.
* @param {object} options
* @param {string} options.sourceId Local layer id.
* @param {object} [options.host] Test seam for the three host lifecycle calls.
* @returns {{show:function():void,publish:function(object[]):void,hide:function():void,destroy:function():void}}
*/
export function createLocalInfrastructureOverlayPublisher({ sourceId, host }) {
let visible = false;
let published = false;
let destroyed = false;
// Local entries have immutable metadata and a mutable Cartesian position.
// Snapshot coordinates: retaining only the entry reference would miss a
// stem tip moving in place. Republishing an unchanged cohort invalidates
// the host and can sustain a render loop when frames exceed the 450 ms walk.
let lastPublication = null;
const sourceOptions = {
cohortLimit: LOCAL_OVERLAY_COHORT_LIMIT,
collisionCapacity: LOCAL_OVERLAY_COLLISION_CAPACITY,
moving: false,
};
return {
show() {
if (destroyed || visible) return;
visible = true;
host.setVisible(sourceId, true);
},
publish(entries) {
if (destroyed || !visible) return;
if (
lastPublication &&
entries.length === lastPublication.length &&
entries.every((entry, index) => {
const previous = lastPublication[index];
return (
entry === previous.entry &&
entry.position?.x === previous.x &&
entry.position?.y === previous.y &&
entry.position?.z === previous.z
);
})
)
return;
host.setEntries(sourceId, entries, sourceOptions);
lastPublication = entries.map((entry) => ({
entry,
x: entry.position?.x,
y: entry.position?.y,
z: entry.position?.z,
}));
published = entries.length > 0;
},
hide() {
if (destroyed) return;
if (published) host.clearSource(sourceId);
if (visible) host.setVisible(sourceId, false);
visible = false;
published = false;
lastPublication = null;
},
destroy() {
if (destroyed) return;
if (published) host.clearSource(sourceId);
if (visible) host.setVisible(sourceId, false);
visible = false;
published = false;
lastPublication = null;
destroyed = true;
},
};
}
/**
* Reduce a bundled-dataset load failure to one short, honest stats string.
*
* These layers ship their data with the build, so a failure means the asset
* is missing (404 / bad path) or corrupt — never "the network is slow". Both
* must reach the user's chip; the raw parser message is console-only because
* a truncated JSON blob is not a status line.
*
* @param {Error|{name?:string, message?:string}|null|undefined} error - The thrown load failure.
* @returns {string} Short reason for getStats().error.
*/
export function localDatasetError(error) {
if (error?.name === 'SyntaxError') return 'dataset is malformed';
const message = String(error?.message || '').trim();
return message ? `dataset unavailable (${message})` : 'dataset unavailable';
}
/** Layer instances made so far, so each draws under set ids of its own. */
let layerInstances = 0;
/** The stem's starting height above the ellipsoid, until the first walk sizes it. */
const INITIAL_TIP_HEIGHT_M = 2000;
/** A polygon's fill alpha, and the line widths, as the GeoJSON loader drew them. */
const FILL_ALPHA = 0.3;
const FEATURE_LINE_WIDTH_PX = 2;
const STEM_WIDTH_PX = 3.5;
const PIN_SIZE_PX = 8;
const BLACK = Object.freeze([0, 0, 0, 1]);
/** A colour channel as a CSS byte, as the default renderer writes one. */
const cssByte = (value) => (value === 1 ? 255 : (value * 256) | 0);
const cssRgba = ([r, g, b, a]) =>
`rgba(${cssByte(r)},${cssByte(g)},${cssByte(b)},${a})`;
/**
* The pin a Point feature stands on: the GeoJSON loader's default marker,
* its pin path at `size` pixels, filled in `rgba` and outlined in that
* colour brightened by 0.6.
* @param {number[]} rgba
* @param {number} [size]
* @returns {{svg: string}}
*/
function pinImage(rgba, size = PIN_SIZE_PX) {
const brighter = [
1 - (1 - rgba[0]) * 0.4,
1 - (1 - rgba[1]) * 0.4,
1 - (1 - rgba[2]) * 0.4,
rgba[3],
];
return {
svg:
``,
};
}
/** The GeoJSON loader's `marker-size` names, in pixels. */
const MARKER_SIZES = Object.freeze({ small: 24, medium: 48, large: 64 });
/**
* Ground edges are drawn along rhumb lines, split this finely (metres), as
* the default renderer splits a draped rhumb line.
*/
const RHUMB_GRANULARITY_M = 9999;
/** `rgba` with alpha `alpha`. */
const withAlpha = (rgba, alpha) => [rgba[0], rgba[1], rgba[2], alpha];
/** Whether the loader took a property: present and not null. */
const given = (value) => value !== undefined && value !== null;
/**
* A feature's own stroke as the GeoJSON loader read it from its
* properties (`stroke`, `stroke-opacity`, `stroke-width`), over the
* layer's colour and width.
*/
function strokeOf(properties, rgba) {
let color = null;
let widthPx = FEATURE_LINE_WIDTH_PX;
if (properties) {
if (given(properties['stroke-width']))
widthPx = Number(properties['stroke-width']);
if (given(properties.stroke)) color = cssColor(properties.stroke);
const opacity = properties['stroke-opacity'];
if (given(opacity) && opacity !== 1)
color = withAlpha(color ?? rgba, Number(opacity));
}
return { color: color ?? rgba, widthPx };
}
/**
* A polygon's own fill as the GeoJSON loader read it (`fill` keeps the
* layer's fill alpha; `fill-opacity` sets the alpha).
*/
function fillOf(properties, fillColor) {
let fill = null;
if (properties) {
if (given(properties.fill)) {
const css = cssColor(properties.fill);
if (css) fill = withAlpha(css, fillColor[3]);
}
const opacity = properties['fill-opacity'];
if (given(opacity) && opacity !== fillColor[3])
fill = withAlpha(fill ?? fillColor, Number(opacity));
}
return fill ?? fillColor;
}
/**
* A point's own marker colour and size as the GeoJSON loader read them
* (`marker-color`, `marker-size`), over the layer's.
*/
function markerOf(properties, rgba) {
const color = given(properties?.['marker-color'])
? cssColor(properties['marker-color'])
: null;
const size = MARKER_SIZES[properties?.['marker-size']] ?? PIN_SIZE_PX;
return { color: color ?? rgba, size };
}
/**
* Ground `coordinates` as `{lon, lat}` degrees along the rhumb lines
* between them, as the GeoJSON loader drew its draped edges.
*/
function rhumbPositions(coordinates) {
return densifyRhumb(
coordinates.map((c) => ({ lon: c[0] * RADIANS, lat: c[1] * RADIANS })),
RHUMB_GRANULARITY_M,
).map(({ lon, lat }) => ({ lon: lon / RADIANS, lat: lat / RADIANS }));
}
const RADIANS = Math.PI / 180;
/**
* The drawn parts of a feature collection, one per thing the GeoJSON loader
* made an entity of, in its order and under its ids: a polygon, line or
* point per part of a multi-geometry, the feature's id taking `_2`, `_3`…
* when repeated, and an empty part for a null geometry. A feature without
* an id gets one of its own. Throws as the loader does on a missing or
* unknown geometry.
* @param {object[]} features
* @returns {Array<{id: string, kind: 'polygon'|'line'|'point'|'empty',
* feature: object, coordinates?: any}>}
*/
export function localGeojsonParts(features) {
const parts = [];
const taken = new Set();
const idOf = (feature) => {
const base =
feature.id === undefined || feature.id === null
? `local-part:${parts.length}`
: String(feature.id);
let id = base;
for (let i = 2; taken.has(id); i++) id = `${base}_${i}`;
return id;
};
const add = (feature, kind, coordinates) => {
const id = idOf(feature);
taken.add(id);
parts.push({ id, kind, feature, coordinates });
};
const polygon = (feature, rings) => {
if (rings.length === 0 || rings[0].length === 0) return;
add(feature, 'polygon', rings);
};
const geometry = (feature, shape) => {
switch (shape.type) {
case 'Point':
return add(feature, 'point', shape.coordinates);
case 'MultiPoint':
for (const point of shape.coordinates) add(feature, 'point', point);
return;
case 'LineString':
return add(feature, 'line', shape.coordinates);
case 'MultiLineString':
for (const line of shape.coordinates) add(feature, 'line', line);
return;
case 'Polygon':
return polygon(feature, shape.coordinates);
case 'MultiPolygon':
for (const rings of shape.coordinates) polygon(feature, rings);
return;
case 'GeometryCollection':
for (const inner of shape.geometries) geometry(feature, inner);
return;
default:
throw new Error(`Unknown geometry type: ${shape.type}`);
}
};
for (const feature of features) {
if (feature.geometry === null) {
add(feature, 'empty');
continue;
}
if (!feature.geometry) throw new Error('feature.geometry is required.');
geometry(feature, feature.geometry);
}
return parts;
}
const lonLatOf = (coordinates) => ({
lon: coordinates[0],
lat: coordinates[1],
});
const distance = (a, b) => Math.sqrt(distanceSquared(a, b));
function distanceSquared(a, b) {
const dx = a.x - b.x;
const dy = a.y - b.y;
const dz = a.z - b.z;
return dx * dx + dy * dy + dz * dz;
}
const copy = (p) => ({ x: p.x, y: p.y, z: p.z });
/**
* The horizontal field of view the stems are sized by: the wider of the
* two angles, as the default renderer's frustum states its field of view.
*/
function wideFov(pose) {
const fovy = Number.isFinite(pose?.fovy) ? pose.fovy : Math.PI / 3;
const aspect = pose?.aspectRatio;
return Number.isFinite(aspect) && aspect > 1
? 2 * Math.atan(Math.tan(fovy / 2) * aspect)
: fovy;
}
/**
* A layer drawing a bundled GeoJSON dataset through the renderer's draw
* port: polygons and lines on the ground, and on each polygon or point a
* 3D stem with a dot on its tip, sized to the camera and lifted onto the
* sampled surface. Clicking any of it selects the feature and flies there.
* @param {object} options Dataset URL, identity, appearance and optional adapters.
* @param {object} services Caller-owned operations; see docs/INFRASTRUCTURE-LAYERS.md.
* @returns {object} A fresh layer implementing init/enable/disable/update/destroy/getStats/getAnalystRecords.
* One live instance per layer id is allowed in a given viewer/context/overlay host.
* Destroy the previous instance before replacing it. Importing creates no layers.
*/
export function createLocalGeoJsonLayer(
{
id,
url,
name,
color,
icon = '📍',
source = 'Local JSONL',
osmDerived = false,
labels = true,
labelMax = DEFAULT_LABEL_MAX,
labelGridPx = DEFAULT_LABEL_GRID_PX,
inputFor = defaultInputFor,
projectToWindow = (viewer, position) =>
findQuery(viewer)?.project(position) ?? null,
},
{
overlayHost,
registerEntityContext,
selectEntityContext,
clearSelectedEntityContextForLayer,
removeEntityContextsForLayer,
governorRequestRender,
showOsmCredit,
hideOsmCredit,
},
) {
const setPrefix = `${id}:${++layerInstances}`;
/** What this layer draws while built: its sets and parts, or null. */
let _drawn = null;
let _enabled = false;
let _clickSubscription = null;
let _count = 0;
/** @type {number|null} Timestamp of the last successful dataset load. */
let _lastUpdate = null;
/** @type {string|null} Short reason the bundled dataset failed to load. */
let _error = null;
let _preRenderRemover = null;
let _cameraMoveEndRemover = null;
let _stemRecords = [];
let _stemGeometryDirty = true;
let _lastVisibilityUpdate = 0;
let _destroyed = false;
let _loadPromise = null;
let _loadController = null;
/**
* The parsed bundled dataset, kept across disable/enable so a re-enable
* rebuilds its sets without refetching. The sets themselves are NOT kept:
* a hidden set still holds its primitives, and the ~11k features of the
* three bundled layers hold hundreds of MB, so leaving them parked after a
* toggle-off made the whole scene render ~2× slower for the rest of the
* session (owner field test 2026-09-13).
* @type {Array