'use strict'; // Independent measurements of published geometry. Do not call the boundary or // marking builders here: a shared bug must not manufacture its own expectation. const TOLERANCE_METERS = 0.01; const LAYERS = [ 'roadSurface', 'coreApproach', 'edgeLines', 'centerLines', 'laneCenterlines', 'laneSeparators', 'sidewalkSurface', ]; const mix = (a, b, t = 0.5) => a.map((v, i) => v + (b[i] - v) * t); const ids = (value) => String(value || '') .split(',') .filter(Boolean); const id = (feature) => feature?.properties?.native_id; const xy = (point, origin) => [ (point[0] - origin[0]) * 111320 * Math.cos((origin[1] * Math.PI) / 180), (point[1] - origin[1]) * 111320, ]; const distance = (a, b) => Math.hypot(...xy(a, b)); const dot = (a, b) => a[0] * b[0] + a[1] * b[1]; const cross = (a, b) => a[0] * b[1] - a[1] * b[0]; const subtract = (a, b) => a.map((v, i) => v - b[i]); function pointSegmentDistance(point, a, b) { const p = xy(a, point), q = xy(b, point), v = subtract(q, p); const t = Math.max(0, Math.min(1, -dot(p, v) / (dot(v, v) || 1))); return Math.hypot(...mix(p, q, t)); } function lineDistance(point, line) { return Math.min(...line.slice(1).map((q, i) => pointSegmentDistance(point, line[i], q))); } function ringsOf(feature) { if (feature?.geometry?.type === 'Polygon') return feature.geometry.coordinates; if (feature?.geometry?.type === 'MultiPolygon') return feature.geometry.coordinates.flat(); return []; } function inside(point, ring) { let result = false; for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) { const a = ring[i], b = ring[j]; if (a[1] > point[1] !== b[1] > point[1] && point[0] < ((b[0] - a[0]) * (point[1] - a[1])) / (b[1] - a[1]) + a[0]) result = !result; } return result; } // Partition at every edge crossing. A narrow interior notch cannot hide // between probes, unlike endpoint-only or fixed quarter-point measurements. function measureSegment(a, b, feature, boundaryOnly = true) { const rings = ringsOf(feature).map((ring) => ring.map((p) => xy(p, a))); const end = xy(b, a), length = Math.hypot(...end), length2 = dot(end, end); if (!rings.length || !length) return { errorMeters: null, uncoveredMeters: length, missing: true }; const partitions = [0, 1], intervals = []; for (const ring of rings) for (let i = 1; i < ring.length; i++) { const p = ring[i - 1], q = ring[i], v = subtract(q, p), denominator = cross(end, v); if (Math.abs(denominator) > 1e-12) { const t = cross(p, v) / denominator, u = cross(p, end) / denominator; if (t > 0 && t < 1 && u >= 0 && u <= 1) partitions.push(t); } // Project only edges parallel and numerically coincident with the seam. // Tolerance is a permitted geometric error, not permission to bridge gaps. if ( Math.abs(cross(end, p)) / length <= TOLERANCE_METERS && Math.abs(cross(end, q)) / length <= TOLERANCE_METERS ) { const first = Math.max(0, Math.min(dot(p, end), dot(q, end)) / length2); const last = Math.min(1, Math.max(dot(p, end), dot(q, end)) / length2); if (last > first) { intervals.push([first, last]); partitions.push(first, last); } } } partitions.sort((x, y) => x - y); let uncoveredMeters = 0; const polygons = feature.geometry.type === 'Polygon' ? [feature.geometry.coordinates] : feature.geometry.coordinates; const inPolygon = (p) => polygons.some((polygon) => inside(p, polygon[0]) && !polygon.slice(1).some((hole) => inside(p, hole))); for (let i = 1; i < partitions.length; i++) { const first = partitions[i - 1], last = partitions[i], t = (first + last) / 2; if (!intervals.some(([lo, hi]) => t >= lo && t <= hi) && (boundaryOnly || !inPolygon(mix(a, b, t)))) uncoveredMeters += (last - first) * length; } const endpointError = Math.max( ...[a, b].map((p) => !boundaryOnly && inPolygon(p) ? 0 : Math.min(...ringsOf(feature).map((ring) => lineDistance(p, ring))), ), ); return { errorMeters: endpointError, uncoveredMeters }; } function caps(feature) { const ring = ringsOf(feature)[0] || [], half = (ring.length - 1) / 2; if (!Number.isInteger(half) || half < 2) return []; return [ [ring[0], ring[ring.length - 2]], [ring[half - 1], ring[half]], ]; } function auditJunctionSeams(model, geometry, structures) { const report = Object.fromEntries( LAYERS.map((layer) => [layer, { checked: 0, failed: 0, notApplicable: 0, records: [] }]), ); const features = (layer) => geometry[layer]?.features || []; function record(layer, identity, measurement, featureIds = []) { const missing = Boolean(measurement.missing); const failed = missing || !Number.isFinite(measurement.errorMeters) || measurement.errorMeters > TOLERANCE_METERS || (measurement.uncoveredMeters || 0) > TOLERANCE_METERS; report[layer].checked++; if (failed) report[layer].failed++; report[layer].records.push({ ...identity, featureIds: featureIds.filter(Boolean), ...measurement, status: failed ? 'failed' : 'passed', }); } function na(layer, identity, reason) { report[layer].notApplicable++; report[layer].records.push({ ...identity, status: 'not-applicable', reason }); } function point(layer, identity, expected, candidates, points) { const actual = candidates.flatMap(points); record( layer, identity, { errorMeters: actual.length ? Math.min(...actual.map((p) => distance(expected, p))) : null, missing: !actual.length, }, candidates.map(id), ); } for (const structure of structures) { const clusterId = structure.junctionRef.id; const core = features('roadSurface').find( (f) => f.properties.cluster_id === clusterId && f.properties.kind === 'complex-core', ); for (const arm of structure.arms) for (const carriageway of arm.carriageways) { const roadIds = carriageway.provenance.roadIds; const identity = { clusterId, carriagewayKey: carriageway.key, roadIds }; const approach = features('roadSurface').find((f) => f.properties.carriageway_key === carriageway.key); if (!approach) { for (const layer of LAYERS.filter((name) => name !== 'sidewalkSurface')) record(layer, identity, { missing: true, errorMeters: null, reason: 'Required approach is missing.' }); continue; } const ring = approach.geometry.coordinates[0], seam = [ring[0], ring[3]]; const exterior = features('roadSurface').filter( (f) => roadIds.length === ids(f.properties.directional_road_ids).length && roadIds.every((roadId) => ids(f.properties.directional_road_ids).includes(roadId)), ); record('roadSurface', { ...identity, join: 'exterior-approach' }, measureSegment(...seam, exterior[0]), [ id(approach), id(exterior[0]), ]); record('coreApproach', { ...identity, join: 'approach-core' }, measureSegment(ring[1], ring[2], core, false), [ id(approach), id(core), ]); const pavement = features('roadSurface').find( (f) => f.properties.cluster_id === clusterId && f.properties.kind === 'complex-pavement-region', ); record( 'roadSurface', { ...identity, join: 'exterior-published-pavement' }, measureSegment(...seam, pavement, false), [id(pavement)], ); const road = model.roads.find((r) => r.id === roadIds[0]); // Preview indices run right-to-left in the outward arm frame; native // lanes run left-to-right in each road's travel frame. Derive the mapping // from source direction, never from whichever geometry happens to be near. const incoming = (r) => carriageway.provenance.nodeIds.includes(String(r.sourceNodeIds.at(-1))); const sourceRoads = roadIds.map((roadId) => model.roads.find((r) => r.id === roadId)); const bindings = [...sourceRoads.filter((r) => !incoming(r)), ...sourceRoads.filter(incoming)].flatMap((r) => Array.from({ length: r.laneCount }, (_, i) => ({ roadId: r.id, laneIndex: incoming(r) ? i + 1 : r.laneCount - i, })), ); const previews = features('laneCenterlines').filter( (f) => f.properties.carriageway_key === carriageway.key && f.properties.cluster_preview && roadIds.includes(f.properties.road_id), ); for (let index = 1; index <= carriageway.laneCount; index++) { const laneIdentity = { ...identity, laneIndex: index }; const preview = previews.find((f) => f.properties.lane_index === index); const binding = bindings[index - 1]; const external = features('laneCenterlines').filter( (f) => !f.properties.cluster_preview && f.properties.road_id === binding.roadId && f.properties.lane_index === binding.laneIndex, ); const expected = mix(...seam, (index - 0.5) / carriageway.laneCount); point( 'laneCenterlines', { ...laneIdentity, join: 'transition-seam' }, expected, preview ? [preview] : [], (f) => [f.geometry.coordinates[0]], ); point('laneCenterlines', { ...laneIdentity, join: 'external-transition' }, expected, external, (f) => [ f.geometry.coordinates[0], f.geometry.coordinates.at(-1), ]); } // Edges terminate at the outer pavement edge; there is no separately // published internal edge continuation. Match the same source road only. const directions = model.roads.filter((r) => r.segmentId === road.segmentId); for (const sourceRoad of sourceRoads) for (const side of directions.length > 1 ? ['right'] : ['left', 'right']) { const edges = features('edgeLines').filter( (f) => f.properties.road_id === sourceRoad.id && f.properties.side === side, ); const expected = seam[(side === 'right') === incoming(sourceRoad) ? 1 : 0]; if (edges.some((f) => f.properties.pattern !== 'solid')) { const surfaceRing = ringsOf(exterior[0])[0] || []; const half = (surfaceRing.length - 1) / 2; const supports = [surfaceRing.slice(0, half), surfaceRing.slice(half, -1)]; const support = supports.sort((a, b) => lineDistance(expected, a) - lineDistance(expected, b))[0]; const nearest = edges .map((f) => ({ f, ends: caps(f).map((cap) => mix(...cap)) })) .sort( (a, b) => Math.min(...a.ends.map((p) => distance(p, expected))) - Math.min(...b.ends.map((p) => distance(p, expected))), )[0]; const gap = Math.min(...nearest.ends.map((p) => distance(p, expected))); record( 'edgeLines', { ...identity, roadId: sourceRoad.id, side, join: 'dash-support' }, { errorMeters: Math.max(...nearest.ends.map((p) => lineDistance(p, support))), gapMeters: gap, uncoveredMeters: Math.max(0, gap - (incoming(sourceRoad) ? 4 : 0)), }, [id(nearest.f)], ); na( 'edgeLines', { ...identity, side }, 'Two-metre dashes with two-metre spacing need not end at the seam.', ); continue; } const actual = edges.flatMap((f) => caps(f).map((cap) => mix(...cap))); record( 'edgeLines', { ...identity, roadId: sourceRoad.id, side }, { missing: !actual.length, errorMeters: actual.length ? Math.min(...actual.map((p) => distance(p, expected))) : null, }, edges.map(id), ); } for (let index = 1; index < carriageway.laneCount; index++) { const separatorIdentity = { ...identity, leftLaneIndex: index, rightLaneIndex: index + 1 }; const expected = mix(...seam, index / carriageway.laneCount); const separators = features('laneSeparators').filter( (f) => f.properties.cluster_id === clusterId && roadIds.includes(f.properties.road_id) && f.properties.left_lane_index === index && f.properties.provenance === 'native-road-complex-lane-separator/v1', ); point('laneSeparators', { ...separatorIdentity, join: 'transition-seam' }, expected, separators, (f) => caps(f).map((cap) => mix(...cap)), ); const firstBinding = bindings[index - 1], secondBinding = bindings[index]; if (firstBinding.roadId !== secondBinding.roadId) { na( 'laneSeparators', separatorIdentity, 'Opposite directions meet at the road centre marking, not an exterior lane separator.', ); continue; } const exteriorIndex = Math.min(firstBinding.laneIndex, secondBinding.laneIndex); const exteriorSeparators = features('laneSeparators').filter( (f) => f.properties.road_id === firstBinding.roadId && f.properties.left_lane_index === exteriorIndex && f.properties.provenance === 'native-road-lane-separator/v1', ); if (!exteriorSeparators.length) record('laneSeparators', separatorIdentity, { missing: true, errorMeters: null }); else { // The final dash need not end at the seam. Its centre must lie on the // same lane pair's support, near this interface rather than another arm. const lanes = [exteriorIndex, exteriorIndex + 1].map((laneIndex) => features('laneCenterlines').find( (f) => !f.properties.cluster_preview && f.properties.road_id === firstBinding.roadId && f.properties.lane_index === laneIndex, ), ); const nearest = exteriorSeparators .map((f) => ({ f, point: mix(...caps(f).map((cap) => mix(...cap))) })) .sort((a, b) => distance(a.point, expected) - distance(b.point, expected))[0]; const first = lanes[0]?.geometry.coordinates, second = lanes[1]?.geometry.coordinates; const support = first && first.length === second?.length ? first.map((p, i) => mix(p, second[i])) : []; const gap = Math.min(...caps(nearest.f).map((cap) => distance(mix(...cap), expected))); record( 'laneSeparators', { ...separatorIdentity, join: 'external-dash-support' }, { missing: !support.length, errorMeters: support.length ? Math.max(...caps(nearest.f).map((cap) => lineDistance(mix(...cap), support))) : null, gapMeters: gap, uncoveredMeters: Math.max( 0, gap - (nearest.f.properties.pattern === 'solid' || !incoming(sourceRoads.find((r) => r.id === firstBinding.roadId)) ? 0 : 4), ), }, [id(nearest.f), ...lanes.map(id)], ); na( 'laneSeparators', separatorIdentity, 'Dash spacing and stop-line clipping do not require white paint across the seam.', ); } } if (carriageway.laneCount < 2) na('laneSeparators', identity, 'Single lane has no lane separator.'); if (directions.length < 2 || road.highway === 'service') na('centerLines', identity, 'No bidirectional road centre marking is published.'); else { const markings = features('centerLines').filter( (f) => roadIds.includes(f.properties.road_id) && roadIds.length === ids(f.properties.directional_road_ids).length && roadIds.every((roadId) => ids(f.properties.directional_road_ids).includes(roadId)), ); const nearest = markings .map((f) => ({ f, point: mix(...caps(f).map((cap) => mix(...cap))) })) .sort((a, b) => distance(a.point, mix(...seam)) - distance(b.point, mix(...seam)))[0]; const supportPoints = nearest ? caps(nearest.f).map((cap) => mix(...cap)) : []; const gap = supportPoints.length ? Math.min(...supportPoints.map((p) => distance(p, mix(...seam)))) : null; record( 'centerLines', identity, { missing: !nearest, errorMeters: nearest ? Math.max( ...supportPoints.map((p) => Math.abs(lineDistance(p, road.centerline) - (nearest.f.properties.double ? 0.16 : 0)), ), ) : null, gapMeters: gap, uncoveredMeters: gap === null ? 0 : Math.max( 0, gap - (incoming(sourceRoads.find((r) => r.id === nearest.f.properties.road_id)) ? nearest.f.properties.dash_length_m + nearest.f.properties.dash_gap_m : 0), ), }, [id(nearest?.f)], ); na( 'centerLines', identity, 'Road centre dashes terminate outside the cluster; no interior centre marking is published.', ); } } for (const corner of structure.corners) { const arms = [corner.fromArmKey, corner.toArmKey].map((key) => structure.arms.find((arm) => arm.key === key)); const roadGroups = arms.map((arm) => arm.carriageways.flatMap((c) => c.provenance.roadIds)); const strips = roadGroups.map((roadIds) => features('sidewalkSurface').filter( (f) => f.properties.provenance === 'native-road-sidewalk/v1' && ids(f.properties.directional_road_ids).some((roadId) => roadIds.includes(roadId)), ), ); const identity = { clusterId, cornerKey: corner.key, roadIds: roadGroups.flat() }; if (strips.some((group) => !group.length)) { const enabled = roadGroups.every((group) => group.some((roadId) => { const road = model.roads.find((r) => r.id === roadId); return road?.sidewalkLeft || road?.sidewalkRight; }), ); if (enabled) record('sidewalkSurface', identity, { missing: true, errorMeters: null }); else na('sidewalkSurface', identity, 'Source arms do not both carry sidewalks.'); continue; } const join = features('sidewalkSurface').find( (f) => f.properties.kind === 'complex-sidewalk-corner' && f.properties.corner_key === corner.key, ); if (!join) { const omitted = (geometry.diagnostics || []).find( (d) => d.subjectId === `corner:${corner.key}` && [ 'complex-junction-sidewalk-corner-fallback', 'complex-junction-island-infeasible', 'complex-junction-corner-exclusion-overlap', ].includes(d.rule), ); if (omitted) na('sidewalkSurface', identity, `Explicitly rejected corner: ${omitted.rule}. ${omitted.message}`); else record('sidewalkSurface', identity, { missing: true, errorMeters: null }); continue; } if (caps(join).length !== 2) { record('sidewalkSurface', identity, { missing: true, errorMeters: null, reason: 'Invalid corner end edges.' }); continue; } for (const [index, cap] of caps(join).entries()) { const candidates = strips[index] .map((f) => ({ f, measurement: measureSegment(...cap, f) })) .sort( (a, b) => a.measurement.errorMeters + a.measurement.uncoveredMeters - (b.measurement.errorMeters + b.measurement.uncoveredMeters), ); record('sidewalkSurface', { ...identity, end: index }, candidates[0].measurement, [ id(join), id(candidates[0].f), ]); } } } return report; } module.exports = { TOLERANCE_METERS, LAYERS, auditJunctionSeams, measureSegment, distance };