Files
road-compiler/src/compile/junction-boundary-graph.js
T

325 lines
14 KiB
JavaScript

'use strict';
const { stationAtDistanceFrom } = require('./junction-build-plan');
function pointAtStation(line, station, helpers) {
let remaining = Math.max(0, station);
for (let index = 1; index < line.length; index += 1) {
const length = helpers.distanceMeters(line[index - 1], line[index]);
if (remaining <= length) {
const ratio = length ? remaining / length : 0;
return [
line[index - 1][0] + (line[index][0] - line[index - 1][0]) * ratio,
line[index - 1][1] + (line[index][1] - line[index - 1][1]) * ratio,
];
}
remaining -= length;
}
return line.at(-1) || null;
}
function tangentAtStation(line, station, helpers) {
let walked = 0;
for (let index = 1; index < line.length; index += 1) {
const length = helpers.distanceMeters(line[index - 1], line[index]);
if (station <= walked + length || index === line.length - 1)
return helpers.headingAtEndpoint([line[index - 1], line[index]]);
walked += length;
}
return null;
}
function offsetCoordinate(point, heading, meters) {
if (!point || !Number.isFinite(heading)) return null;
const radians = (heading * Math.PI) / 180;
const lonMeters = 111320 * Math.cos((point[1] * Math.PI) / 180);
return [
point[0] + (Math.sin(radians) * meters) / Math.max(lonMeters, 1e-9),
point[1] + (Math.cos(radians) * meters) / 111320,
];
}
function sectionAt(item, radius, center, widthMeters, helpers, explicitStation, edgeOffsets = null) {
const station = Math.max(
0,
Math.min(item.length, explicitStation ?? stationAtDistanceFrom(item.approach.line, center, radius, helpers)),
);
const point = pointAtStation(item.approach.line, station, helpers);
const tangent = tangentAtStation(item.approach.line, station, helpers) + (Number(edgeOffsets?.direction) || 0);
const halfWidth = Math.max(0, Number(widthMeters) || 0) / 2;
const leftOffset = Number(edgeOffsets?.left) || 0;
const rightOffset = Number(edgeOffsets?.right) || 0;
return {
stationMeters: station,
point,
tangent,
left: offsetCoordinate(point, tangent - 90, halfWidth + leftOffset),
right: offsetCoordinate(point, tangent + 90, halfWidth + rightOffset),
};
}
// The graph currently owns only source-derived entry edges. Core closure is
// deliberately unresolved until a later stage can distinguish paved links,
// medians, and exclusion regions from topology alone.
function buildJunctionBoundaryGraph(topology, center, radii, helpers, exclusionRegions = []) {
const sections = topology.carriageways.map((item) => {
const outerRadius = radii.outerRadiusFor(item);
const innerRadius = radii.innerRadiusFor(item);
const outerWidthMeters = Number(item.approach.sourceWidthMeters) || item.approach.widthMeters;
const innerWidthMeters = item.approach.widthMeters;
const positionOffset = Number(item.approach.positionOffsetMeters) || 0;
const outer = sectionAt(item, outerRadius, center, outerWidthMeters, helpers, undefined);
const requestedTransition = Number.isFinite(item.approach.transitionLengthMeters)
? Math.max(0, item.approach.transitionLengthMeters)
: null;
const edgeOffsets = {
left: item.approach.leftEdgeOffsetMeters,
right: item.approach.rightEdgeOffsetMeters,
direction: item.approach.directionOffsetDegrees,
};
const baseInnerStation =
requestedTransition === null
? stationAtDistanceFrom(item.approach.line, center, innerRadius, helpers)
: outer.stationMeters - requestedTransition;
const inner = sectionAt(
item,
innerRadius,
center,
innerWidthMeters,
helpers,
baseInnerStation + positionOffset,
edgeOffsets,
);
const key = `boundary:${item.key}`;
const sectionRing = [outer.right, inner.right, inner.left, outer.left, outer.right];
const exclusion = exclusionRegions.find((region) => ringsOverlap(region.ring, sectionRing));
const ringFinite = sectionRing.every((coordinate) => coordinate?.every(Number.isFinite));
const ringArea = ringFinite ? Math.abs(signedArea(sectionRing)) : 0;
const ringStatus = !ringFinite || ringArea < 1e-14 || ringSelfIntersects(sectionRing) ? 'invalid' : 'supported';
return {
key,
carriagewayKey: item.key,
exclusionStatus: exclusion ? 'overlaps-known-region' : 'clear',
...(exclusion ? { exclusionRegionId: String(exclusion.id ?? '') } : {}),
armKey: item.armKey,
outerWidthMeters,
innerWidthMeters,
transitionMeters: Math.max(0, outer.stationMeters - inner.stationMeters),
transitionStatus:
Math.abs(baseInnerStation + positionOffset - inner.stationMeters) > 1e-6
? 'insufficient-source-length'
: outer.stationMeters - inner.stationMeters > 1e-6
? 'supported'
: 'insufficient-source-length',
outer,
inner,
ring: sectionRing,
ringStatus,
edgeRefs: {
left: `${key}:left`,
right: `${key}:right`,
outer: `${key}:outer`,
inner: `${key}:inner`,
},
};
});
const edges = sections.flatMap((section) => [
{ key: section.edgeRefs.left, from: section.outer.left, to: section.inner.left, owner: section.carriagewayKey },
{ key: section.edgeRefs.right, from: section.inner.right, to: section.outer.right, owner: section.carriagewayKey },
{ key: section.edgeRefs.outer, from: section.outer.right, to: section.outer.left, owner: section.carriagewayKey },
{ key: section.edgeRefs.inner, from: section.inner.left, to: section.inner.right, owner: section.carriagewayKey },
]);
return {
schema: 'junction-boundary-graph/v1',
status: 'entry-sections-only',
sections,
edges,
exclusionRegions: exclusionRegions.filter((region) => Array.isArray(region.ring) && region.ring.length >= 4),
unresolvedClosures: topology.arms.map((arm) => arm.cornerKey),
};
}
function ringSelfIntersects(ring) {
const cross = (a, b, c) => (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
const straddles = (p1, p2, p3, p4) => {
const d1 = cross(p3, p4, p1);
const d2 = cross(p3, p4, p2);
const d3 = cross(p1, p2, p3);
const d4 = cross(p1, p2, p4);
return ((d1 > 0 && d2 < 0) || (d1 < 0 && d2 > 0)) && ((d3 > 0 && d4 < 0) || (d3 < 0 && d4 > 0));
};
for (let first = 0; first < ring.length - 1; first += 1) {
for (let second = first + 2; second < ring.length - 1; second += 1) {
if (first === 0 && second === ring.length - 2) continue;
if (straddles(ring[first], ring[first + 1], ring[second], ring[second + 1])) return true;
}
}
return false;
}
function signedArea(ring) {
return ring.slice(1).reduce((area, point, index) => area + ring[index][0] * point[1] - point[0] * ring[index][1], 0);
}
function pointInRing(point, ring) {
return ring.slice(1).reduce((inside, candidate, index) => {
const previous = ring[index];
const crosses = previous[1] > point[1] !== candidate[1] > point[1];
return crosses &&
point[0] < ((candidate[0] - previous[0]) * (point[1] - previous[1])) / (candidate[1] - previous[1]) + previous[0]
? !inside
: inside;
}, false);
}
function segmentsIntersect(first, second, third, fourth) {
// Orientation alone treats all collinear segments as intersecting, even
// when their finite extents are disjoint.
if (
Math.max(first[0], second[0]) < Math.min(third[0], fourth[0]) ||
Math.max(third[0], fourth[0]) < Math.min(first[0], second[0]) ||
Math.max(first[1], second[1]) < Math.min(third[1], fourth[1]) ||
Math.max(third[1], fourth[1]) < Math.min(first[1], second[1])
)
return false;
const cross = (a, b, c) => (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
const firstSide = cross(first, second, third);
const secondSide = cross(first, second, fourth);
const thirdSide = cross(third, fourth, first);
const fourthSide = cross(third, fourth, second);
return (
((firstSide >= 0 && secondSide <= 0) || (firstSide <= 0 && secondSide >= 0)) &&
((thirdSide >= 0 && fourthSide <= 0) || (thirdSide <= 0 && fourthSide >= 0))
);
}
function ringsOverlap(first, second) {
return (
first.slice(0, -1).some((point) => pointInRing(point, second)) ||
second.slice(0, -1).some((point) => pointInRing(point, first)) ||
first
.slice(1)
.some((point, index) =>
second.slice(1).some((other, otherIndex) => segmentsIntersect(first[index], point, second[otherIndex], other)),
)
);
}
function coordinateDistanceMeters(first, second) {
if (!first?.every(Number.isFinite) || !second?.every(Number.isFinite)) return Infinity;
const radians = Math.PI / 180;
const latitude = ((first[1] + second[1]) / 2) * radians;
const east = (second[0] - first[0]) * 111320 * Math.cos(latitude);
const north = (second[1] - first[1]) * 111320;
return Math.hypot(east, north);
}
// A central paved region is safe to infer only when every arm has exactly one
// source carriageway. Its shared entry seams are the sections' `inner` edges;
// every remaining edge is an explicit closure between adjacent arms.
function buildCoreClosure(topology, graph, center) {
let coreSections = graph.sections;
if (topology.arms.some((arm) => arm.members.length !== 1)) {
if (topology.arms.length < 4 || topology.arms.length > 6)
return { status: 'unsupported', reason: 'parallel-carriageway-closure-unresolved' };
coreSections = topology.arms.map(
(arm) =>
graph.sections
.filter((section) => section.armKey === arm.key && section.ringStatus === 'supported')
.sort((a, b) => {
const distance = (section) => {
const x = (section.inner.left[0] + section.inner.right[0]) / 2 - center[0];
const y = (section.inner.left[1] + section.inner.right[1]) / 2 - center[1];
return x * x + y * y;
};
return distance(a) - distance(b) || a.carriagewayKey.localeCompare(b.carriagewayKey);
})[0],
);
if (coreSections.some((section) => !section))
return { status: 'unsupported', reason: 'parallel-carriageway-closure-unresolved' };
}
if (coreSections.length < 3 || coreSections.length > 6)
return { status: 'unsupported', reason: 'unsupported-arm-count' };
const points = coreSections
.flatMap((section) => [
{ point: section.inner.left, edgeRef: section.edgeRefs.inner },
{ point: section.inner.right, edgeRef: section.edgeRefs.inner },
])
.filter((item) => item.point?.every(Number.isFinite))
.sort(
(first, second) =>
Math.atan2(first.point[1] - center[1], first.point[0] - center[0]) -
Math.atan2(second.point[1] - center[1], second.point[0] - center[0]),
);
const ring = [...points.map((item) => item.point), points[0]?.point].filter(Boolean);
const hasZeroLengthEdge = ring.slice(1).some((point, index) => {
const previous = ring[index];
const dx = point[0] - previous[0];
const dy = point[1] - previous[1];
return dx * dx + dy * dy <= 1e-24;
});
const pairedEdges = new Map();
points.forEach((item, index) => {
if (!pairedEdges.has(item.edgeRef)) pairedEdges.set(item.edgeRef, []);
pairedEdges.get(item.edgeRef).push(index);
});
const paired = [...pairedEdges.values()].every((indexes) => {
if (indexes.length !== 2) return false;
return Math.abs(indexes[0] - indexes[1]) === 1 || (indexes[0] === 0 && indexes[1] === points.length - 1);
});
if (ring.length < 7 || hasZeroLengthEdge || !paired || Math.abs(signedArea(ring)) < 1e-14 || ringSelfIntersects(ring))
return { status: 'unsupported', reason: 'core-closure-invalid' };
const holes = graph.exclusionRegions
.filter((region) => {
const boundaryIntersects = ringSelfIntersects([...region.ring]);
const contained = region.ring.slice(0, -1).every((point) => pointInRing(point, ring));
const clearOfEntries = graph.sections.every((section) => !ringsOverlap(region.ring, section.ring));
return region.isHole === true && !boundaryIntersects && contained && clearOfEntries;
})
.map((region) => region.ring);
if (graph.exclusionRegions.some((region) => ringsOverlap(region.ring, ring) && !holes.includes(region.ring)))
return { status: 'unsupported', reason: 'known-exclusion-region' };
const seamErrors = graph.sections.map((section) => {
const leftIndex = ring.findIndex(
(point) => point[0] === section.inner.left[0] && point[1] === section.inner.left[1],
);
const rightIndex = ring.findIndex(
(point) => point[0] === section.inner.right[0] && point[1] === section.inner.right[1],
);
const contiguous =
leftIndex >= 0 &&
rightIndex >= 0 &&
(Math.abs(leftIndex - rightIndex) === 1 || Math.abs(leftIndex - rightIndex) === ring.length - 2);
const edge = graph.edges.find((candidate) => candidate.key === section.edgeRefs.inner);
if (!contiguous || !edge) return { carriagewayKey: section.carriagewayKey, errorMeters: Infinity };
const ringLeft = ring[leftIndex];
const ringRight = ring[rightIndex];
const forward = Math.max(
coordinateDistanceMeters(ringLeft, edge.from),
coordinateDistanceMeters(ringRight, edge.to),
);
const reverse = Math.max(
coordinateDistanceMeters(ringLeft, edge.to),
coordinateDistanceMeters(ringRight, edge.from),
);
return { carriagewayKey: section.carriagewayKey, errorMeters: Math.min(forward, reverse) };
});
const seamErrorMeters = seamErrors.reduce((maximum, item) => Math.max(maximum, item.errorMeters), 0);
const connectedEntryCount = seamErrors.filter((item) => Number.isFinite(item.errorMeters)).length;
return {
status: 'supported',
ring,
holes,
ringArea: Math.abs(signedArea(ring)) / 2,
ringSelfIntersects: false,
sharedEdgeRefs: [...pairedEdges.keys()].sort(),
closureCount: graph.sections.length,
connectedEntryCount,
requiredPavementConnected: connectedEntryCount === graph.sections.length,
maxSharedSeamErrorMeters: seamErrorMeters,
sharedSeamErrors: seamErrors,
};
}
module.exports = { buildJunctionBoundaryGraph, buildCoreClosure, ringsOverlap };