Files
road-compiler/src/compile/direct-edit-solver.js
T

1841 lines
80 KiB
JavaScript

'use strict';
const { diagnostic } = require('./diagnostics');
const { approachForCrossing, arrivalEndpointIds, effectiveCrosswalkInsetMax } = require('./crossing-approach');
const { haversineMeters, metersAt, polylineLength } = require('../geometry/lane-geometry');
const {
roadSurfaceId,
sidewalkId,
laneId,
laneSeparatorId,
edgeLineId,
centerLineId,
junctionSurfaceId,
connectionConnectorId,
} = require('./native-ids');
const { complexJunctionMetrics } = require('./junction-metrics');
const { resolveJunctionBuildPlan, stationAtDistanceFrom } = require('./junction-build-plan');
const RESOLUTION_SCHEMA = 'road-edit-resolution/v1';
const HANDLE_MANIFEST_SCHEMA = 'road-edit-handles/v1';
const ACTIVE_STATUSES = new Set(['exact', 'recheck']);
const SOLVED_KINDS = new Set([
'road-edge-offset',
'road-sidewalk-width',
'road-lane-divider',
'junction-approach-width',
'cluster-carriageway-width',
'cluster-carriageway-cutback',
'cluster-carriageway-transition-length',
'cluster-carriageway-position',
'cluster-corner-radius',
'cluster-crossing-inset',
'cluster-stop-line-offset',
'junction-cutback',
'junction-corner-radius',
'junction-crosswalk-inset',
'junction-crosswalk-size',
'junction-stop-line-offset',
'lane-maneuver',
]);
const KINDS = [
'road-edge-offset',
'road-sidewalk-width',
'road-lane-divider',
'junction-approach-width',
'cluster-carriageway-width',
'cluster-carriageway-cutback',
'cluster-carriageway-transition-length',
'cluster-carriageway-position',
'cluster-corner-radius',
'cluster-crossing-inset',
'cluster-stop-line-offset',
'junction-cutback',
'junction-corner-radius',
'junction-crosswalk-inset',
'junction-crosswalk-size',
'junction-stop-line-offset',
'lane-maneuver',
];
const SUPPORTED_MANEUVERS = new Set([
'',
'through',
'left',
'right',
'through;left',
'through;right',
'through;left;right',
]);
const MIN_LANE_WIDTH_METERS = 2.4;
// Bounds for the control-marking offsets. The crosswalk may sit anywhere from the
// junction boundary out to a few metres; the stop line must stay clear of the
// crossing it protects.
const MAX_CROSSWALK_INSET_METERS = 8;
const MIN_STOP_LINE_OFFSET_METERS = 0.5;
// Default placement, and therefore a handle's value when no constraint exists yet.
// These live here rather than in native-road.js because the solver must stay free
// of fs/path — a test asserts that — so the dependency can only point this way.
const CROSSWALK_JUNCTION_INSET_METERS = 1.5;
// Zebra geometry. Depth runs along the approach; the span across the road is
// `stripeCount * pitch`, not a stored number, because stripe and gap widths are
// standardised while the road they cross is not. Pitch is not editable this phase.
const CROSSWALK_DEPTH_METERS = 3;
const CROSSWALK_STRIPE_WIDTH_METERS = 0.45;
const CROSSWALK_STRIPE_PITCH_METERS = 0.9;
const MIN_CROSSWALK_DEPTH_METERS = 1;
const MAX_CROSSWALK_DEPTH_METERS = 12;
const MIN_CROSSWALK_STRIPE_COUNT = 2;
const MAX_CROSSWALK_STRIPE_COUNT = 40;
const STOP_LINE_OFFSET_METERS = 2.7;
/** Junction-anchored but owned by the main map, unlike the junction shape kinds. */
const CONTROL_KINDS = new Set(['junction-crosswalk-inset', 'junction-crosswalk-size', 'junction-stop-line-offset']);
const GEOMETRY_VERSION = 'native-road-package/v1.1';
function emptyHandleManifest(context) {
return {
schema: HANDLE_MANIFEST_SCHEMA,
revisionId: typeof context.revisionId === 'string' ? context.revisionId : null,
previewSeq: Number.isInteger(context.previewSeq) ? context.previewSeq : 0,
handles: [],
reserves: [],
};
}
function constraintState(constraint, applied, reason) {
return {
constraintId: constraint.id,
kind: constraint.kind,
status: constraint.status,
applied,
reason: constraint.status === 'stale' && constraint.replayReason ? constraint.replayReason : reason,
};
}
function coordinateAt(line, station) {
if (!Array.isArray(line) || line.length === 0) return null;
if (line.length === 1) return [...line[0]];
const total = polylineLength(line);
if (!Number.isFinite(total) || total <= 0) return [...line[0]];
let remaining = Math.max(0, Math.min(1, station)) * total;
for (let index = 1; index < line.length; index += 1) {
const length = haversineMeters(line[index - 1], line[index]);
if (length >= remaining) {
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)];
}
function tangentAzimuth(line, station) {
const point = coordinateAt(line, station);
if (!point || line.length < 2) return 0;
const distance = Math.max(0.01, polylineLength(line) * 0.005);
const before = coordinateAt(line, Math.max(0, station - distance / Math.max(polylineLength(line), 1)));
const after = coordinateAt(line, Math.min(1, station + distance / Math.max(polylineLength(line), 1)));
const dx = (after[0] - before[0]) * Math.cos((point[1] * Math.PI) / 180);
const dy = after[1] - before[1];
if (Math.abs(dx) + Math.abs(dy) < 1e-12) return 0;
return ((Math.atan2(dx, dy) * 180) / Math.PI + 360) % 360;
}
function offsetCoordinate(point, azimuth, meters) {
const radians = (azimuth * Math.PI) / 180;
const latitudeScale = metersAt(point[1]).lon;
return [
point[0] + (Math.sin(radians) * meters) / Math.max(latitudeScale, 1e-9),
point[1] + (Math.cos(radians) * meters) / 111320,
];
}
function constraintFor(constraints, kind, anchor) {
return constraints.find((item) => {
if (item.kind !== kind || !item.anchor || item.enabled === false) return false;
if (kind.startsWith('road-')) {
return (
item.anchor.type === 'road-interval' &&
item.anchor.roadId === anchor.roadId &&
(item.anchor.side || null) === (anchor.side || null) &&
(kind !== 'road-lane-divider' || item.value?.boundaryIndex === anchor.boundaryIndex)
);
}
if (kind === 'junction-corner-radius')
return (
item.anchor.type === 'junction-corner' &&
item.anchor.nodeId === anchor.nodeId &&
item.anchor.incomingRoadId === anchor.incomingRoadId &&
item.anchor.outgoingRoadId === anchor.outgoingRoadId
);
if (kind === 'cluster-carriageway-width')
return (
item.anchor.type === 'cluster-carriageway' &&
item.anchor.clusterId === anchor.clusterId &&
item.anchor.carriagewayKey === anchor.carriagewayKey
);
if (kind === 'cluster-carriageway-transition-length' || kind === 'cluster-carriageway-cutback')
return (
item.anchor.type === 'cluster-carriageway' &&
item.anchor.clusterId === anchor.clusterId &&
item.anchor.carriagewayKey === anchor.carriagewayKey
);
if (kind === 'cluster-corner-radius')
return (
item.anchor.type === 'cluster-corner' &&
item.anchor.clusterId === anchor.clusterId &&
item.anchor.cornerKey === anchor.cornerKey
);
if (kind === 'cluster-crossing-inset' || kind === 'cluster-stop-line-offset')
return (
item.anchor.type === 'cluster-crossing' &&
item.anchor.clusterId === anchor.clusterId &&
item.anchor.crossingKey === anchor.crossingKey
);
if (kind === 'junction-crosswalk-inset' || kind === 'junction-stop-line-offset')
return (
item.anchor.type === 'junction-crossing' &&
item.anchor.crossingId === anchor.crossingId &&
item.anchor.nodeId === anchor.nodeId &&
item.anchor.segmentId === anchor.segmentId &&
item.anchor.roadId === anchor.roadId
);
return (
item.anchor.type === 'junction-approach' &&
item.anchor.nodeId === anchor.nodeId &&
item.anchor.segmentId === anchor.segmentId &&
(item.anchor.side || null) === (anchor.side || null)
);
});
}
function clusterCarriageways(model, junctionData, clusters) {
const result = new Map();
for (const cluster of Array.isArray(clusters) ? clusters : []) {
if (!cluster?.id || !Array.isArray(cluster.nodeIds)) continue;
const plans = new Map();
for (const nodeId of cluster.nodeIds.map(String)) {
const approaches = (junctionData.approaches.get(nodeId) || []).map((source) => {
const roads = source.items.map((item) => item.road);
const first = source.items[0];
const line = first?.endpoint.side === 'end' ? [...roads[0].centerline].reverse() : roads[0]?.centerline || [];
return {
...source,
roadIds: roads.map((road) => road.id),
widthMeters: source.items.reduce((sum, item) => sum + item.road.widthMeters, 0),
line,
};
});
const node = approaches[0]?.line?.[0] || [0, 0];
plans.set(nodeId, { node, approaches });
}
const topology = resolveJunctionBuildPlan(model, cluster, {
junctionPlans: plans,
distanceMeters: haversineMeters,
lineLengthMeters: polylineLength,
headingAtEndpoint: (line) => tangentAzimuth(line, 0),
});
const armByKey = new Map(topology.arms.flatMap((arm) => arm.members.map((member) => [member.key, arm])));
result.set(
String(cluster.id),
topology.carriageways.map((item) => ({
...item,
clusterId: String(cluster.id),
identity: item.key.split(':carriageway:').at(-1),
sourceNodeIds: [...new Set(item.roads.flatMap((road) => (road.sourceNodeIds || []).map(String)))].sort(),
sourceRoadIds: item.roads.map((road) => String(road.id)).sort(),
widthMeters: item.approach.widthMeters,
laneCount: item.roads.reduce((sum, road) => sum + (Number(road.laneCount) || 0), 0),
arm: armByKey.get(item.key),
})),
);
}
return result;
}
function clusterApproachLine(item) {
return item.approach.line || [];
}
function clusterCenter(model, cluster) {
const endpointsByNode = new Map();
for (const endpoint of model.endpoints || []) {
const nodeId = String(endpoint.nodeId);
if (!endpointsByNode.has(nodeId) && Array.isArray(endpoint.coordinate))
endpointsByNode.set(nodeId, endpoint.coordinate);
}
const points = (cluster.nodeIds || []).map((nodeId) => endpointsByNode.get(String(nodeId))).filter(Boolean);
if (!points.length) return null;
return points.reduce((sum, point) => [sum[0] + point[0] / points.length, sum[1] + point[1] / points.length], [0, 0]);
}
function clusterRadiusPoint(line, center, radius) {
if (!center || !line.length) return null;
const length = polylineLength(line);
if (!Number.isFinite(length) || length <= 0) return line[0] || null;
const station = stationAtDistanceFrom(line, center, radius, { distanceMeters: haversineMeters });
return coordinateAt(line, Math.max(0, Math.min(1, station / length)));
}
function signedLateralMeters(origin, point, heading) {
const east = (point[0] - origin[0]) * 111320 * Math.cos((origin[1] * Math.PI) / 180);
const north = (point[1] - origin[1]) * 111320;
const radians = ((heading + 90) * Math.PI) / 180;
return east * Math.sin(radians) + north * Math.cos(radians);
}
function clusterArmRadiusPoint(arm, center, radius) {
const points = arm.members
.map((member) => ({ member, point: clusterRadiusPoint(clusterApproachLine(member), center, radius) }))
.filter((item) => item.point);
if (!points.length) return null;
const reference = points[0].point;
let minimum = Infinity;
let maximum = -Infinity;
for (const { member, point } of points) {
const lateral = signedLateralMeters(reference, point, arm.heading);
const halfWidth = (Number(member.approach.widthMeters) || 0) / 2;
minimum = Math.min(minimum, lateral - halfWidth);
maximum = Math.max(maximum, lateral + halfWidth);
}
return Number.isFinite(minimum) && Number.isFinite(maximum)
? offsetCoordinate(reference, arm.heading + 90, (minimum + maximum) / 2)
: reference;
}
function clusterCrossingBaseRadius(model, arm, center, inferredRadius) {
const inferredCenter = clusterArmRadiusPoint(arm, center, inferredRadius);
if (!inferredCenter) return inferredRadius;
const osmWayIds = new Set(
arm.members.flatMap((member) => member.roads.flatMap((road) => (road.osmWayIds || []).map(String))),
);
const maximumDistance = Math.max(
8,
arm.members.reduce((width, member) => width + (Number(member.approach.widthMeters) || 0), 0) / 2 + 3,
);
const crossing = (model.crossings || [])
.filter(
(item) =>
(item.osmWayIds || []).some((wayId) => osmWayIds.has(String(wayId))) &&
haversineMeters(item.coordinate, inferredCenter) <= maximumDistance,
)
.sort(
(first, second) =>
haversineMeters(first.coordinate, inferredCenter) - haversineMeters(second.coordinate, inferredCenter) ||
String(first.id).localeCompare(String(second.id)),
)[0];
return crossing ? haversineMeters(center, crossing.coordinate) : inferredRadius;
}
function clusterArms(clusterId, items) {
const byArm = new Map();
for (const item of items) {
if (!item.arm || byArm.has(item.arm.key)) continue;
byArm.set(item.arm.key, {
...item.arm,
members: item.arm.members.map((member) => items.find((candidate) => candidate.key === member.key) || member),
});
}
return [...byArm.values()];
}
function numericValue(constraint, key, fallback) {
const value = constraint?.value?.[key];
return Number.isFinite(value) ? value : fallback;
}
function transitionBounds(model, cluster, item, constraints) {
const metrics = complexJunctionMetrics(cluster);
const cutback = constraintFor(constraints, 'cluster-carriageway-cutback', {
clusterId: String(cluster.id),
carriagewayKey: item.key,
});
const cutbackValue = numericValue(cutback, 'cutbackMeters', item.approach.cutback);
const effectiveCutback =
cutback &&
ACTIVE_STATUSES.has(cutback.status) &&
cutbackValue >= 1 &&
cutbackValue <= clusterCutbackMaximum(cluster, item.approach.length)
? cutbackValue
: item.approach.cutback;
const radius = Math.max(metrics.coreRadius + 4, metrics.approachOuterRadius - effectiveCutback);
const center = clusterCenter(model, cluster) || item.approach.line[0];
const outer = stationAtDistanceFrom(item.approach.line, center, radius, { distanceMeters: haversineMeters });
const inner = stationAtDistanceFrom(item.approach.line, center, metrics.approachInnerRadius, {
distanceMeters: haversineMeters,
});
const current = Math.max(0, outer - inner);
return { min: Math.min(metrics.minimumTransitionMeters, current), max: outer, current, outer };
}
function clusterCutbackMaximum(cluster, approachLength) {
const metrics = complexJunctionMetrics(cluster);
// Keep a measurable local taper between the source-road outer section and
// the inner core section. The other cap preserves a usable source approach.
return Math.min(
approachLength * 0.45,
Math.max(1, metrics.approachOuterRadius - (metrics.approachInnerRadius + metrics.minimumTransitionMeters)),
);
}
function roadGroups(model) {
const groups = new Map();
for (const road of Array.isArray(model?.roads) ? model.roads : []) {
if (!road || !Array.isArray(road.centerline) || road.centerline.length < 2) continue;
if (!groups.has(road.segmentId)) groups.set(road.segmentId, []);
groups.get(road.segmentId).push(road);
}
return groups;
}
function junctionReserves(model) {
const endpointGroups = new Map();
for (const endpoint of Array.isArray(model?.endpoints) ? model.endpoints : []) {
const road = (model.roads || []).find((item) => item.id === endpoint.roadId);
if (!road) continue;
if (!endpointGroups.has(endpoint.nodeId)) endpointGroups.set(endpoint.nodeId, new Map());
const bySegment = endpointGroups.get(endpoint.nodeId);
if (!bySegment.has(road.segmentId)) bySegment.set(road.segmentId, []);
bySegment.get(road.segmentId).push({ endpoint, road });
}
const reserves = [];
const approaches = new Map();
for (const [nodeId, bySegment] of endpointGroups) {
if (bySegment.size < 3 || bySegment.size > 4) continue;
const widths = [...bySegment.values()].map((items) => items.reduce((sum, item) => sum + item.road.widthMeters, 0));
const cutback = Math.max(...widths) * 1.4;
for (const [segmentId, items] of bySegment) {
const representative = items[0].road;
const length = polylineLength(representative.centerline);
if (!Number.isFinite(length) || length <= 0) continue;
const fraction = Math.min(0.45, cutback / length);
const endpoint = items[0].endpoint;
const range = endpoint.side === 'start' ? [0, fraction] : [1 - fraction, 1];
const reserve = { nodeId: String(nodeId), roadId: segmentId, fromStation: range[0], toStation: range[1] };
reserves.push(reserve);
if (!approaches.has(nodeId)) approaches.set(nodeId, []);
approaches.get(nodeId).push({ nodeId: String(nodeId), segmentId, items, cutback, length, endpoint, range });
}
}
return { reserves, approaches };
}
function snapshotCandidates(model, constraint) {
const snapshot = constraint.anchorSnapshot;
if (!snapshot || !Array.isArray(snapshot.coordinate)) return [];
const roads = (model.roads || []).filter((road) => {
if (!road.centerline?.length) return false;
const nodeMatch = snapshot.osmNodeIds?.some((id) => road.sourceNodeIds?.includes(String(id)));
const nearest = road.centerline.reduce(
(best, point) => Math.min(best, haversineMeters(snapshot.coordinate, point)),
Infinity,
);
return nodeMatch && nearest <= 50;
});
return roads;
}
function roadForLaneAnchor(model, laneAnchorId) {
if (typeof laneAnchorId !== 'string') return null;
for (const road of model.roads || []) {
const count = Number(road.laneCount) || 0;
for (let index = 1; index <= count; index += 1) if (laneId(road.id, index) === laneAnchorId) return road;
}
return null;
}
function reconcileConstraints(model, constraints, base, junctionData, context) {
const clusterItems = clusterCarriageways(
model,
junctionData,
context.junctionTemplates?.clusters || context.junctionClusters || [],
);
const clusterCorners = new Map(
[...clusterItems].map(([clusterId, items]) => [
clusterId,
new Map(
clusterArms(clusterId, items).map((arm, index, arms) => [
`corner:${arm.key}>${arms[(index + 1) % arms.length].key}`,
[arm.representative.key, arms[(index + 1) % arms.length].representative.key],
]),
),
]),
);
const versionChanged = Boolean(
context.compilerGeometryVersion &&
base?.compilerGeometryVersion &&
context.compilerGeometryVersion !== base.compilerGeometryVersion,
);
return constraints.map((constraint) => {
if (!constraint.enabled || !constraint.anchor || !['exact', 'recheck'].includes(constraint.status))
return constraint;
let matched = false;
if (constraint.kind === 'lane-maneuver') {
if (!roadForLaneAnchor(model, constraint.anchor.laneId))
return { ...constraint, status: 'stale', replayReason: 'anchor-missing' };
if (versionChanged) return { ...constraint, status: 'recheck' };
return constraint;
}
if (
constraint.kind === 'cluster-carriageway-width' ||
constraint.kind === 'cluster-carriageway-transition-length'
) {
const item = clusterItems
.get(String(constraint.anchor.clusterId))
?.find((candidate) => candidate.key === constraint.anchor.carriagewayKey);
const sourcesMatch =
item &&
JSON.stringify(item.sourceNodeIds) ===
JSON.stringify([...constraint.anchor.sourceNodeIds].map(String).sort()) &&
JSON.stringify(item.sourceRoadIds) === JSON.stringify([...constraint.anchor.sourceRoadIds].map(String).sort());
if (!sourcesMatch) return { ...constraint, status: 'stale', replayReason: 'anchor-missing' };
if (versionChanged) return { ...constraint, status: 'recheck' };
return constraint;
}
if (constraint.kind === 'cluster-carriageway-cutback') {
const item = clusterItems
.get(String(constraint.anchor.clusterId))
?.find((candidate) => candidate.key === constraint.anchor.carriagewayKey);
if (!item) return { ...constraint, status: 'stale', replayReason: 'anchor-missing' };
if (versionChanged) return { ...constraint, status: 'recheck' };
return constraint;
}
if (constraint.kind === 'cluster-corner-radius') {
const expected = clusterCorners.get(String(constraint.anchor.clusterId))?.get(constraint.anchor.cornerKey);
const supplied = [...constraint.anchor.carriagewayKeys].sort();
if (!expected || JSON.stringify([...expected].sort()) !== JSON.stringify(supplied))
return { ...constraint, status: 'stale', replayReason: 'anchor-missing' };
if (versionChanged) return { ...constraint, status: 'recheck' };
return constraint;
}
if (constraint.kind === 'cluster-crossing-inset' || constraint.kind === 'cluster-stop-line-offset') {
const arm = clusterArms(
String(constraint.anchor.clusterId),
clusterItems.get(String(constraint.anchor.clusterId)) || [],
).find((candidate) => `crossing:${candidate.key}` === constraint.anchor.crossingKey);
if (!arm) return { ...constraint, status: 'stale', replayReason: 'anchor-missing' };
if (versionChanged) return { ...constraint, status: 'recheck' };
return constraint;
}
if (constraint.kind.startsWith('road-')) {
const road = roadForAnchor(model, constraint.anchor.roadId);
matched = Boolean(road);
const roadExists = matched;
if (matched && constraint.kind === 'road-lane-divider')
matched = Number.isInteger(constraint.value?.boundaryIndex) && constraint.value.boundaryIndex < road.laneCount;
if (!matched) {
const candidates = snapshotCandidates(model, constraint);
if (candidates.length === 1) return { ...constraint, status: 'pending' };
return {
...constraint,
status: candidates.length > 1 ? 'conflicted' : 'stale',
...(candidates.length || !roadExists
? { replayReason: candidates.length ? undefined : 'anchor-missing' }
: {}),
};
}
} else if (constraint.kind === 'junction-corner-radius') {
const approaches = junctionData.approaches.get(String(constraint.anchor.nodeId));
matched = Boolean(
approaches?.some((item) => item.segmentId === constraint.anchor.incomingRoadId) &&
approaches?.some((item) => item.segmentId === constraint.anchor.outgoingRoadId),
);
} else {
matched = Boolean(
junctionData.approaches
.get(String(constraint.anchor.nodeId))
?.some((item) => item.segmentId === constraint.anchor.segmentId),
);
}
if (!matched) return { ...constraint, status: 'stale', replayReason: 'anchor-missing' };
if ((versionChanged || context.replay) && constraint.kind === 'road-edge-offset') {
const value = Number(constraint.value?.offsetMeters);
const sides = constraint.anchor.side ? [constraint.anchor.side] : ['left', 'right'];
if (sides.some((side) => !inRange(value, roadEdgeOffsetRange(model, { ...constraint.anchor, side }, null))))
return { ...constraint, status: 'stale', replayReason: 'range-out-of-bounds' };
}
if (versionChanged) return { ...constraint, status: 'recheck' };
return constraint;
});
}
function roadForAnchor(model, roadId) {
return (model.roads || []).find(
(road) => road.id === roadId || road.sourceRoadId === roadId || road.segmentId === roadId,
);
}
function inRange(value, range) {
return Boolean(range && Number.isFinite(value) && value >= range.min && value <= range.max);
}
// This is the authoritative range for both the published edge handle and the
// solver. A segment can contain two directional roads, but an edge constraint
// applies to exactly one `roadId`; using the segment total here was the source
// of the previously advertised-but-invalid drag range.
function roadEdgeOffsetRange(model, anchor, profile) {
const road = roadForAnchor(model, anchor?.roadId);
const side = anchor?.side;
if (!road || !['left', 'right'].includes(side)) return null;
const otherSide = side === 'left' ? 'right' : 'left';
const otherOffset = Number(profile?.edgeOffsets?.[otherSide]) || 0;
const width = Number(road.widthMeters);
const minimumWidth = Number(road.laneCount) * MIN_LANE_WIDTH_METERS;
if (!Number.isFinite(width) || !Number.isFinite(minimumWidth)) return null;
return {
min: Math.max(-width / 2, minimumWidth - width - otherOffset),
max: width / 2,
};
}
function blocking(diagnostics, constraint, rule, message, coordinate = null) {
diagnostics.push(diagnostic('error', `constraint:${constraint.id}`, [], rule, message, coordinate));
}
function profileFor(profiles, road) {
if (!profiles.has(road.id))
profiles.set(road.id, {
roadId: road.id,
segmentId: road.segmentId,
interval: null,
edgeOffsets: { left: 0, right: 0 },
sidewalkWidths: {
left: road.sidewalkLeft ? 2 : 0,
right: road.sidewalkRight ? 2 : 0,
},
laneDividerOffsets: {},
transitions: {},
widthMeters: road.widthMeters,
});
return profiles.get(road.id);
}
function applyRoadConstraint(model, constraint, profiles, diagnostics) {
const road = roadForAnchor(model, constraint.anchor?.roadId);
if (!road) {
blocking(diagnostics, constraint, 'direct-edit-road-anchor-missing', '直接编辑约束的道路锚点不存在。');
return false;
}
const anchor = constraint.anchor;
if (
anchor.type !== 'road-interval' ||
!Number.isFinite(anchor.startStation) ||
!Number.isFinite(anchor.endStation) ||
anchor.startStation < 0 ||
anchor.endStation > 1 ||
anchor.startStation >= anchor.endStation
) {
blocking(
diagnostics,
constraint,
'direct-edit-invalid-interval',
'道路编辑区间必须按 0..1 的归一化 station 严格递增。',
road.centerline?.[0],
);
return false;
}
const profile = profileFor(profiles, road);
profile.interval = profile.interval
? {
startStation: Math.min(profile.interval.startStation, anchor.startStation),
endStation: Math.max(profile.interval.endStation, anchor.endStation),
}
: { startStation: anchor.startStation, endStation: anchor.endStation };
const sides = anchor.side ? [anchor.side] : ['left', 'right'];
if (sides.some((side) => !['left', 'right'].includes(side))) {
blocking(diagnostics, constraint, 'direct-edit-invalid-side', '道路约束 side 必须是 left 或 right。');
return false;
}
if (constraint.kind === 'road-edge-offset') {
const offset = Number(constraint.value?.offsetMeters);
const ranges = sides.map((side) => roadEdgeOffsetRange(model, { ...anchor, side }, profile));
if (ranges.some((range) => !inRange(offset, range))) {
const range = ranges.find((item) => item && !inRange(offset, item)) || ranges[0];
blocking(
diagnostics,
constraint,
'direct-edit-edge-offset-out-of-range',
`外缘偏移必须在 ${range ? `${range.min} 到 ${range.max}` : '当前道路可用范围'} 米之间。`,
);
return false;
}
for (const side of sides) {
profile.edgeOffsets[side] = offset;
profile.transitions[`road-edge-offset:${side}`] = constraint.value?.transition || 'smoothstep';
}
} else if (constraint.kind === 'road-sidewalk-width') {
const width = Number(constraint.value?.widthMeters);
if (!Number.isFinite(width) || width < 0) {
blocking(diagnostics, constraint, 'direct-edit-invalid-value', '步行带宽度必须是非负米数。');
return false;
}
for (const side of sides) {
profile.sidewalkWidths[side] = width;
profile.transitions[`road-sidewalk-width:${side}`] = constraint.value?.transition || 'smoothstep';
}
} else if (constraint.kind === 'road-lane-divider') {
const boundaryIndex = constraint.value?.boundaryIndex;
const offset = Number(constraint.value?.offsetMeters);
if (!Number.isInteger(boundaryIndex) || boundaryIndex < 1 || boundaryIndex >= road.laneCount) {
blocking(diagnostics, constraint, 'direct-edit-lane-boundary-stale', '车道分隔 boundaryIndex 已超出当前车道数。');
return false;
}
if (!Number.isFinite(offset)) {
blocking(diagnostics, constraint, 'direct-edit-invalid-value', '车道分隔偏移必须是有限米数。');
return false;
}
const laneWidth = road.widthMeters / road.laneCount;
if (laneWidth - Math.abs(offset) < 2.4) {
blocking(diagnostics, constraint, 'direct-edit-min-lane-width', '车道分隔调整会使相邻车道小于 2.4 米。');
return false;
}
profile.laneDividerOffsets[boundaryIndex] = offset;
profile.transitions[`road-lane-divider:${boundaryIndex}`] = constraint.value?.transition || 'smoothstep';
}
profile.widthMeters = road.widthMeters + profile.edgeOffsets.left + profile.edgeOffsets.right;
if (
Math.abs(profile.edgeOffsets.left) > road.widthMeters / 2 ||
Math.abs(profile.edgeOffsets.right) > road.widthMeters / 2 ||
profile.widthMeters < road.laneCount * 2.4
) {
blocking(diagnostics, constraint, 'direct-edit-outer-edges-cross', '左右外缘调整后无法容纳最小车道宽度。');
return false;
}
return true;
}
function applyJunctionConstraint(model, constraint, junctionPlans, junctionData, diagnostics, crossingControls) {
const anchor = constraint.anchor || {};
if (anchor.type === 'junction-crossing') {
const crossing = (model.crossings || []).find((item) => String(item.id) === String(anchor.crossingId));
const road = (model.roads || []).find((item) => item.id === anchor.roadId);
const approach = crossing && road ? approachForCrossing(model, crossing) : null;
if (
!crossing ||
!road ||
!approach ||
approach.road.id !== road.id ||
String(road.segmentId) !== String(anchor.segmentId)
) {
blocking(diagnostics, constraint, 'direct-edit-crossing-anchor-missing', '直接编辑约束的控制元素锚点不存在。');
return false;
}
const value = Number(constraint.value?.insetMeters ?? constraint.value?.offsetMeters);
const valid =
constraint.kind === 'junction-crosswalk-inset'
? Number.isFinite(value) && value >= 0 && value <= MAX_CROSSWALK_INSET_METERS
: Number.isFinite(value) && value >= MIN_STOP_LINE_OFFSET_METERS && value <= approach.junctionDistanceMeters;
if (!valid) {
blocking(diagnostics, constraint, 'direct-edit-crossing-value-invalid', '控制线位置超出当前元素可用范围。');
return false;
}
// Keep the geometry value in a separate per-crossing map. Multiple crossings
// may share one approach, so storing this on the approach would couple them.
const crossingKey = String(anchor.crossingId);
const control = crossingControls.get(crossingKey) || {};
crossingControls.set(crossingKey, control);
if (constraint.kind === 'junction-crosswalk-inset') control.crosswalkInsetMeters = value;
else control.stopLineOffsetMeters = value;
return true;
}
const approaches = junctionData.approaches.get(String(anchor.nodeId));
const approach = approaches?.find((item) => item.segmentId === anchor.segmentId);
if (constraint.kind !== 'junction-corner-radius' && !approach) {
blocking(diagnostics, constraint, 'direct-edit-junction-anchor-missing', '直接编辑约束的路口进口锚点不存在。');
return false;
}
if (constraint.kind === 'junction-corner-radius') {
const incoming = approaches?.find((item) => item.segmentId === anchor.incomingRoadId);
const outgoing = approaches?.find((item) => item.segmentId === anchor.outgoingRoadId);
const radius = Number(constraint.value?.radiusMeters);
if (!incoming || !outgoing) {
blocking(diagnostics, constraint, 'direct-edit-junction-corner-missing', '直接编辑约束的路口角部锚点不存在。');
return false;
}
if (!Number.isFinite(radius) || radius < 0.5 || radius > 30) {
blocking(diagnostics, constraint, 'direct-edit-corner-radius-invalid', '路口角部半径必须在 0.5 到 30 米之间。');
return false;
}
if (!junctionPlans.has(String(anchor.nodeId)))
junctionPlans.set(String(anchor.nodeId), { nodeId: String(anchor.nodeId), approaches: {}, corners: {} });
const plan = junctionPlans.get(String(anchor.nodeId));
plan.corners[`${anchor.incomingRoadId}->${anchor.outgoingRoadId}`] = radius;
return true;
}
if (!junctionPlans.has(String(anchor.nodeId)))
junctionPlans.set(String(anchor.nodeId), { nodeId: String(anchor.nodeId), approaches: {}, corners: {} });
const plan = junctionPlans.get(String(anchor.nodeId));
const entry = (plan.approaches[anchor.segmentId] ||= {
widthMeters: approach.items.reduce((sum, item) => sum + item.road.widthMeters, 0),
cutbackMeters: approach.cutback,
});
// An explicit branch per kind: the previous `else` meant every kind that was not
// approach-width fell through to the cutback validator, so a new kind would have
// been silently validated as, and written as, a cutback.
switch (constraint.kind) {
case 'junction-approach-width': {
const width = Number(constraint.value?.widthMeters);
if (!Number.isFinite(width) || width < MIN_LANE_WIDTH_METERS) {
blocking(diagnostics, constraint, 'direct-edit-min-approach-width', '路口进口宽度不能小于 2.4 米。');
return false;
}
entry.widthMeters = width;
return true;
}
case 'junction-cutback': {
const cutback = Number(constraint.value?.cutbackMeters);
if (!Number.isFinite(cutback) || cutback < 1 || cutback > approach.length * 0.45) {
blocking(
diagnostics,
constraint,
'direct-edit-cutback-invalid',
'路口 cutback 必须落在进口可用长度的 45% 以内。',
);
return false;
}
entry.cutbackMeters = cutback;
return true;
}
case 'junction-crosswalk-inset': {
const inset = Number(constraint.value?.insetMeters);
if (!Number.isFinite(inset) || inset < 0 || inset > MAX_CROSSWALK_INSET_METERS) {
blocking(
diagnostics,
constraint,
'direct-edit-crosswalk-inset-invalid',
`斑马线内缩必须在 0 到 ${MAX_CROSSWALK_INSET_METERS} 米之间。`,
);
return false;
}
entry.crosswalkInsetMeters = inset;
return true;
}
case 'junction-crosswalk-size': {
const depth = Number(constraint.value?.depthMeters);
const stripeCount = constraint.value?.stripeCount;
if (!Number.isFinite(depth) || depth < MIN_CROSSWALK_DEPTH_METERS || depth > MAX_CROSSWALK_DEPTH_METERS) {
blocking(
diagnostics,
constraint,
'direct-edit-crosswalk-depth-invalid',
`斑马线进深必须在 ${MIN_CROSSWALK_DEPTH_METERS} 到 ${MAX_CROSSWALK_DEPTH_METERS} 米之间。`,
);
return false;
}
if (
!Number.isInteger(stripeCount) ||
stripeCount < MIN_CROSSWALK_STRIPE_COUNT ||
stripeCount > MAX_CROSSWALK_STRIPE_COUNT
) {
blocking(
diagnostics,
constraint,
'direct-edit-crosswalk-stripes-invalid',
`斑马线条带数必须是 ${MIN_CROSSWALK_STRIPE_COUNT} 到 ${MAX_CROSSWALK_STRIPE_COUNT} 之间的整数。`,
);
return false;
}
entry.crosswalkDepthMeters = depth;
entry.crosswalkStripeCount = stripeCount;
return true;
}
case 'junction-stop-line-offset': {
const offset = Number(constraint.value?.offsetMeters);
if (!Number.isFinite(offset) || offset < MIN_STOP_LINE_OFFSET_METERS || offset > approach.length * 0.45) {
blocking(
diagnostics,
constraint,
'direct-edit-stop-line-offset-invalid',
`停止线退距必须在 ${MIN_STOP_LINE_OFFSET_METERS} 米到进口可用长度的 45% 之间。`,
);
return false;
}
entry.stopLineOffsetMeters = offset;
return true;
}
default:
blocking(diagnostics, constraint, 'direct-edit-unknown-junction-kind', '未知的路口约束类型。');
return false;
}
}
function solveConstraints(model, constraints, junctionData, diagnostics, clusters = []) {
const roadProfiles = new Map();
const junctionPlans = new Map();
const laneManeuvers = new Map();
const crossingControls = new Map();
const clusterPlans = new Map();
const clusterCutbacks = new Map();
const clusterTransitions = new Map();
const clusterPositions = new Map();
const clusterCorners = new Map();
const clusterCrossings = new Map();
const clusterItems = clusterCarriageways(model, junctionData, clusters);
const states = [];
for (const constraint of constraints) {
if (!constraint.enabled) {
states.push(constraintState(constraint, false, 'disabled'));
continue;
}
if (!ACTIVE_STATUSES.has(constraint.status)) {
states.push(constraintState(constraint, false, `status-${constraint.status}`));
continue;
}
if (!SOLVED_KINDS.has(constraint.kind)) {
states.push(constraintState(constraint, false, 'kind-not-solved'));
continue;
}
const roadSnapshot = new Map(
[...roadProfiles].map(([key, profile]) => [
key,
{
...profile,
edgeOffsets: { ...profile.edgeOffsets },
sidewalkWidths: { ...profile.sidewalkWidths },
laneDividerOffsets: { ...profile.laneDividerOffsets },
transitions: { ...profile.transitions },
interval: profile.interval && { ...profile.interval },
},
]),
);
const laneSnapshot = new Map(laneManeuvers);
const crossingSnapshot = new Map([...crossingControls].map(([key, value]) => [key, { ...value }]));
const clusterSnapshot = new Map([...clusterPlans].map(([key, value]) => [key, new Map(value)]));
const cutbackSnapshot = new Map([...clusterCutbacks].map(([key, value]) => [key, new Map(value)]));
const transitionSnapshot = new Map([...clusterTransitions].map(([key, value]) => [key, new Map(value)]));
const positionSnapshot = new Map([...clusterPositions].map(([key, value]) => [key, new Map(value)]));
const cornerSnapshot = new Map([...clusterCorners].map(([key, value]) => [key, new Map(value)]));
const crossingClusterSnapshot = new Map([...clusterCrossings].map(([key, value]) => [key, new Map(value)]));
const junctionSnapshot = new Map(
[...junctionPlans].map(([key, plan]) => [
key,
{
...plan,
approaches: Object.fromEntries(Object.entries(plan.approaches).map(([id, entry]) => [id, { ...entry }])),
corners: { ...plan.corners },
},
]),
);
let applied;
if (
constraint.kind === 'cluster-carriageway-width' ||
constraint.kind === 'cluster-carriageway-cutback' ||
constraint.kind === 'cluster-carriageway-transition-length' ||
constraint.kind === 'cluster-carriageway-position'
) {
const item = clusterItems
.get(String(constraint.anchor?.clusterId))
?.find((candidate) => candidate.key === constraint.anchor?.carriagewayKey);
const value = Number(
constraint.kind === 'cluster-carriageway-width'
? constraint.value?.widthMeters
: constraint.kind === 'cluster-carriageway-transition-length'
? constraint.value?.transitionLengthMeters
: constraint.kind === 'cluster-carriageway-position'
? constraint.value?.offsetMeters
: constraint.value?.cutbackMeters,
);
const cluster = clusters.find((candidate) => String(candidate.id) === String(item?.clusterId));
const cutbackMax = cluster ? clusterCutbackMaximum(cluster, item?.approach.length || 0) : 0;
const transitionMax = item && cluster ? transitionBounds(model, cluster, item, constraints).max : 0;
if (!item) {
blocking(diagnostics, constraint, 'direct-edit-cluster-carriageway-missing', '复杂路口车行道锚点不存在。');
applied = false;
} else if (
!Number.isFinite(value) ||
(constraint.kind === 'cluster-carriageway-width' &&
(value < Math.max(MIN_LANE_WIDTH_METERS, item.laneCount * MIN_LANE_WIDTH_METERS) ||
value > item.widthMeters * 2)) ||
(constraint.kind === 'cluster-carriageway-cutback' && (value < 1 || value > cutbackMax)) ||
(constraint.kind === 'cluster-carriageway-transition-length' &&
(value < transitionBounds(model, cluster, item, constraints).min || value > transitionMax)) ||
(constraint.kind === 'cluster-carriageway-position' && (value < -20 || value > 20))
) {
blocking(
diagnostics,
constraint,
'direct-edit-cluster-carriageway-geometry-invalid',
'复杂路口车行道参数超出当前可用范围。',
);
applied = false;
} else {
const target =
constraint.kind === 'cluster-carriageway-width'
? clusterPlans
: constraint.kind === 'cluster-carriageway-transition-length'
? clusterTransitions
: constraint.kind === 'cluster-carriageway-position'
? clusterPositions
: clusterCutbacks;
if (!target.has(item.clusterId)) target.set(item.clusterId, new Map());
target.get(item.clusterId).set(item.key, value);
applied = true;
}
} else if (constraint.kind === 'cluster-corner-radius') {
const cluster = clusters.find((item) => String(item.id) === String(constraint.anchor?.clusterId));
const radius = Number(constraint.value?.radiusMeters);
const keys = constraint.anchor?.carriagewayKeys || [];
if (!cluster || !Number.isFinite(radius) || radius < 1 || radius > 25 || keys.length !== 2) {
blocking(diagnostics, constraint, 'direct-edit-cluster-corner-invalid', '复杂路口角部圆角超出当前可用范围。');
applied = false;
} else {
if (!clusterCorners.has(String(cluster.id))) clusterCorners.set(String(cluster.id), new Map());
clusterCorners.get(String(cluster.id)).set(String(constraint.anchor.cornerKey), radius);
applied = true;
}
} else if (constraint.kind === 'cluster-crossing-inset' || constraint.kind === 'cluster-stop-line-offset') {
const clusterId = String(constraint.anchor?.clusterId);
const arm = clusterArms(clusterId, clusterItems.get(clusterId) || []).find(
(candidate) => `crossing:${candidate.key}` === constraint.anchor?.crossingKey,
);
const value = Number(constraint.value?.insetMeters ?? constraint.value?.offsetMeters);
const min = constraint.kind === 'cluster-crossing-inset' ? 0 : MIN_STOP_LINE_OFFSET_METERS;
const max = constraint.kind === 'cluster-crossing-inset' ? MAX_CROSSWALK_INSET_METERS : 12;
if (!arm || !Number.isFinite(value) || value < min || value > max) {
blocking(
diagnostics,
constraint,
'direct-edit-cluster-crossing-invalid',
'复杂路口过街控制元素超出当前可用范围。',
);
applied = false;
} else {
if (!clusterCrossings.has(clusterId)) clusterCrossings.set(clusterId, new Map());
const control = clusterCrossings.get(clusterId).get(constraint.anchor.crossingKey) || {};
if (constraint.kind === 'cluster-crossing-inset') control.crosswalkInsetMeters = value;
else control.stopLineOffsetMeters = value;
clusterCrossings.get(clusterId).set(constraint.anchor.crossingKey, control);
applied = true;
}
} else if (constraint.kind === 'lane-maneuver') {
const laneId = constraint.anchor?.laneId;
const laneExists = Boolean(roadForLaneAnchor(model, laneId));
const maneuver = constraint.value?.maneuver;
const placement = constraint.value?.placementDistanceMeters;
if (!laneExists) {
blocking(diagnostics, constraint, 'direct-edit-lane-anchor-missing', '导向箭头车道锚点不存在。');
applied = false;
} else if (!SUPPORTED_MANEUVERS.has(maneuver)) {
blocking(diagnostics, constraint, 'direct-edit-lane-maneuver-invalid', '导向箭头 maneuver 不受支持。');
applied = false;
} else if (placement !== undefined && (!Number.isFinite(placement) || placement < 0)) {
blocking(diagnostics, constraint, 'direct-edit-lane-placement-invalid', '导向箭头位置必须是非负米数。');
applied = false;
} else {
laneManeuvers.set(laneId, {
maneuver,
...(placement === undefined ? {} : { placementDistanceMeters: placement }),
});
applied = true;
}
} else {
applied = constraint.kind.startsWith('road-')
? applyRoadConstraint(model, constraint, roadProfiles, diagnostics)
: applyJunctionConstraint(model, constraint, junctionPlans, junctionData, diagnostics, crossingControls);
}
if (!applied) {
roadProfiles.clear();
for (const [key, profile] of roadSnapshot) roadProfiles.set(key, profile);
junctionPlans.clear();
for (const [key, plan] of junctionSnapshot) junctionPlans.set(key, plan);
laneManeuvers.clear();
for (const [key, value] of laneSnapshot) laneManeuvers.set(key, value);
crossingControls.clear();
for (const [key, value] of crossingSnapshot) crossingControls.set(key, value);
clusterPlans.clear();
for (const [key, value] of clusterSnapshot) clusterPlans.set(key, value);
clusterCutbacks.clear();
for (const [key, value] of cutbackSnapshot) clusterCutbacks.set(key, value);
clusterTransitions.clear();
for (const [key, value] of transitionSnapshot) clusterTransitions.set(key, value);
clusterPositions.clear();
for (const [key, value] of positionSnapshot) clusterPositions.set(key, value);
clusterCorners.clear();
for (const [key, value] of cornerSnapshot) clusterCorners.set(key, value);
clusterCrossings.clear();
for (const [key, value] of crossingClusterSnapshot) clusterCrossings.set(key, value);
}
states.push(constraintState(constraint, applied, applied ? null : 'invalid'));
}
return {
roadProfiles,
junctionPlans,
laneManeuvers,
crossingControls,
clusterPlans,
clusterCutbacks,
clusterTransitions,
clusterPositions,
clusterCorners,
clusterCrossings,
states,
};
}
function roadAffects(roads, model, side, boundaryIndex) {
const ids = [];
for (const road of roads) {
ids.push(roadSurfaceId(road), centerLineId(road.segmentId));
ids.push(edgeLineId(road.id, side || 'left'), edgeLineId(road.id, side || 'right'));
if (side) ids.push(sidewalkId(road, side));
for (let index = 1; index <= road.laneCount; index += 1) ids.push(laneId(road.id, index));
if (boundaryIndex) ids.push(laneSeparatorId(road.id, boundaryIndex));
}
const roadIds = new Set(roads.map((road) => road.id));
const endpointRoads = new Map((model.endpoints || []).map((endpoint) => [endpoint.id, endpoint.roadId]));
for (const connection of model.connections || []) {
const from = endpointRoads.get(connection.fromEndpointId);
const to = endpointRoads.get(connection.toEndpointId);
if (!roadIds.has(from) && !roadIds.has(to)) continue;
const fromRoad = (model.roads || []).find((road) => road.id === from);
const toRoad = (model.roads || []).find((road) => road.id === to);
for (let fromIndex = 1; fromIndex <= (fromRoad?.laneCount || 0); fromIndex += 1)
for (let toIndex = 1; toIndex <= (toRoad?.laneCount || 0); toIndex += 1)
ids.push(`${connectionConnectorId(connection.id)}:${laneId(from, fromIndex)}->${laneId(to, toIndex)}`);
}
return [...new Set(ids)];
}
function makeRoadHandles(model, groups, reserves, constraints, roadProfiles) {
const handles = [];
for (const [segmentId, roads] of groups) {
const road = roads.find((item) => item.direction === 'forward') || roads[0];
const length = polylineLength(road.centerline);
if (!Number.isFinite(length) || length <= 0) continue;
const segmentReserves = reserves.filter((item) => item.roadId === segmentId);
const startReserve = Math.max(0, ...segmentReserves.map((item) => item.toStation * (item.fromStation === 0)));
const endReserve = Math.max(0, ...segmentReserves.map((item) => (item.fromStation > 0 ? 1 - item.fromStation : 0)));
const start = Math.min(1, startReserve);
const end = Math.max(0, 1 - endReserve);
const station = start < end ? (start + end) / 2 : 0.5;
const unavailable = start >= end;
const width = roads.reduce((sum, item) => sum + (Number(item.widthMeters) || 0), 0);
const laneCount = roads.reduce((sum, item) => sum + (Number(item.laneCount) || 0), 0);
// `junctionReserves()` caps each end's reserve at 0.45, so `unavailable`
// alone can never fire — it would need start >= end, i.e. 0.45 >= 0.55. On a
// road the junctions geometrically fill, that cap invents an editable band in
// the middle (1.5 m on a 14.5 m road) with no room for the smoothstep
// transitions a road-interval constraint needs at both ends.
//
// Compare in meters rather than stations: a transition needs real distance,
// and a band shorter than the road is wide cannot carry a cross-section
// change. This only marks handles read-only; existing constraints on such a
// road keep being solved, so a compiler upgrade never silently drops a saved
// edit and the geometry output is unchanged.
const bandMeters = Math.max(0, end - start) * length;
const junctionDominated = bandMeters < width;
const point = coordinateAt(road.centerline, station);
const tangent = tangentAzimuth(road.centerline, station);
const normal = (tangent + 90) % 360;
const interval = { type: 'road-interval', roadId: road.id, startStation: start, endStation: end };
const baseDisabled =
unavailable || junctionDominated ? '该道路全部位于路口保留区,请进入 JunctionTools 编辑。' : undefined;
const add = (kind, anchor, value, min, max, axis, position, affects, constraint) => {
const disabledReason = baseDisabled;
handles.push({
handleId: `handle:${kind}:${segmentId}:${anchor.side || anchor.boundaryIndex || 'main'}`,
kind,
anchor,
position,
axisAzimuth: ((axis % 360) + 360) % 360,
value: { current: value, min, max, unit: 'meter' },
...(constraint ? { constraintId: constraint.id } : {}),
affects,
editable: !disabledReason,
...(disabledReason ? { disabledReason } : {}),
});
};
for (const side of ['left', 'right']) {
// Left is `tangent - 90`, matching the geometry compiler: `offsetLine()`
// shifts a positive offset counter-clockwise from the direction of travel,
// and sidewalks use `heading + (side === 'left' ? -90 : 90)`. Placing the
// left handle at `tangent + 90` drew it over the right kerb, so dragging the
// visually-left handle moved the right edge.
const sideSign = side === 'left' ? -1 : 1;
const edgeAnchor = { ...interval, side };
const edgeConstraint = constraintFor(constraints, 'road-edge-offset', edgeAnchor);
const edgeRange = roadEdgeOffsetRange(model, edgeAnchor, roadProfiles.get(road.id));
add(
'road-edge-offset',
edgeAnchor,
numericValue(edgeConstraint, 'offsetMeters', 0),
edgeRange.min,
edgeRange.max,
normal,
offsetCoordinate(point, tangent + sideSign * 90, width / 2),
roadAffects(roads, model, side),
edgeConstraint,
);
const sidewalkConstraint = constraintFor(constraints, 'road-sidewalk-width', edgeAnchor);
const enabled = side === 'left' ? Boolean(road.sidewalkLeft) : Boolean(road.sidewalkRight);
add(
'road-sidewalk-width',
edgeAnchor,
numericValue(sidewalkConstraint, 'widthMeters', enabled ? 2 : 0),
0,
8,
normal,
offsetCoordinate(point, tangent + sideSign * 90, width / 2 + (enabled ? 1 : 0)),
roadAffects(roads, model, side),
sidewalkConstraint,
);
}
for (let boundaryIndex = 1; boundaryIndex < laneCount; boundaryIndex += 1) {
const anchor = { ...interval };
const constraint = constraintFor(constraints, 'road-lane-divider', { ...anchor, boundaryIndex });
const laneWidth = laneCount ? width / laneCount : MIN_LANE_WIDTH_METERS;
const lateral = -width / 2 + laneWidth * boundaryIndex;
add(
'road-lane-divider',
{ ...anchor, boundaryIndex },
numericValue(constraint, 'offsetMeters', 0),
-Math.max(0.1, laneWidth - MIN_LANE_WIDTH_METERS),
Math.max(0.1, laneWidth - MIN_LANE_WIDTH_METERS),
normal,
offsetCoordinate(point, tangent + 90, lateral),
roadAffects(roads, model, null, boundaryIndex),
constraint,
);
}
}
return handles;
}
function makeLaneManeuverHandles(model, constraints) {
const handles = [];
for (const road of model.roads || []) {
const laneCount = Number(road.laneCount) || 0;
const length = polylineLength(road.centerline);
if (!(length > 0) || road.centerline.length < 2) continue;
for (let index = 1; index <= laneCount; index += 1) {
const laneAnchorId = laneId(road.id, index);
const constraint = constraints.find(
(item) => item.kind === 'lane-maneuver' && item.anchor?.type === 'lane' && item.anchor.laneId === laneAnchorId,
);
const value = constraint?.value || {};
const placement = Number.isFinite(value.placementDistanceMeters) ? value.placementDistanceMeters : 6;
const station = Math.max(0, Math.min(1, 1 - placement / length));
const position = coordinateAt(road.centerline, station);
const axis = tangentAzimuth(road.centerline, station);
handles.push({
handleId: `handle:lane-maneuver:${laneAnchorId}`,
kind: 'lane-maneuver',
anchor: { type: 'lane', laneId: laneAnchorId, roadId: road.id },
position,
axisAzimuth: axis,
value: { current: placement, min: 0, max: length, unit: 'meter' },
...(constraint ? { constraintId: constraint.id } : {}),
affects: [`turn-arrow:${laneAnchorId}`],
editable: true,
});
}
}
return handles;
}
function junctionAffects(model, nodeId, segmentIds) {
const roads = (model.roads || []).filter((road) => segmentIds.has(road.segmentId));
const ids = [junctionSurfaceId(nodeId), ...roadAffects(roads, model)];
const endpointRoads = new Map((model.endpoints || []).map((endpoint) => [endpoint.id, endpoint.roadId]));
for (const connection of model.connections || []) {
if (String(connection.nodeId) !== String(nodeId)) continue;
const from = (model.roads || []).find((road) => road.id === endpointRoads.get(connection.fromEndpointId));
const to = (model.roads || []).find((road) => road.id === endpointRoads.get(connection.toEndpointId));
for (let fromIndex = 1; fromIndex <= (from?.laneCount || 0); fromIndex += 1)
for (let toIndex = 1; toIndex <= (to?.laneCount || 0); toIndex += 1)
ids.push(`${connectionConnectorId(connection.id)}:${laneId(from.id, fromIndex)}->${laneId(to.id, toIndex)}`);
}
return [...new Set(ids)];
}
function makeJunctionHandles(model, junctionData, constraints) {
const handles = [];
const arrivals = arrivalEndpointIds(model || {});
for (const [nodeId, approaches] of junctionData.approaches) {
const segmentIds = new Set(approaches.map((item) => item.segmentId));
for (const approach of approaches) {
const road = approach.items[0].road;
const line = approach.endpoint.side === 'start' ? road.centerline : [...road.centerline].reverse();
const station = Math.min(0.95, Math.max(0.05, approach.cutback / approach.length));
const point = coordinateAt(line, station);
const tangent = tangentAzimuth(line, station);
const normal = (tangent + 90) % 360;
const anchor = { type: 'junction-approach', nodeId: String(nodeId), segmentId: approach.segmentId };
const affects = junctionAffects(model, nodeId, segmentIds);
// Control markings are positioned by their distance back from the junction,
// rather than at the approach cutback point shared by shape handles. Keeping
// these positions distinct is important: otherwise the later stop-line
// feature covers the crosswalk handle and neither target is discoverable.
const controlPoint = (offsetMeters, lateralMeters = 0) => {
const coordinate = coordinateAt(
line,
Math.min(0.98, Math.max(0.02, offsetMeters / Math.max(approach.length, 1))),
);
return lateralMeters ? offsetCoordinate(coordinate, normal, lateralMeters) : coordinate;
};
const add = (kind, value, min, max, axis, constraint, position = point) => {
handles.push({
handleId: `handle:${kind}:node/${nodeId}:${approach.segmentId}`,
kind,
anchor,
position,
axisAzimuth: ((axis % 360) + 360) % 360,
value: { current: value, min, max, unit: 'meter' },
...(constraint ? { constraintId: constraint.id } : {}),
affects,
editable: true,
});
};
const widthConstraint = constraintFor(constraints, 'junction-approach-width', anchor);
add(
'junction-approach-width',
numericValue(
widthConstraint,
'widthMeters',
approach.items.reduce((sum, item) => sum + item.road.widthMeters, 0),
),
MIN_LANE_WIDTH_METERS,
Math.max(8, approach.items.reduce((sum, item) => sum + item.road.widthMeters, 0) * 2),
normal,
widthConstraint,
);
const cutbackConstraint = constraintFor(constraints, 'junction-cutback', anchor);
add(
'junction-cutback',
numericValue(cutbackConstraint, 'cutbackMeters', approach.cutback),
1,
Math.max(1, approach.length * 0.45),
tangent,
cutbackConstraint,
);
// Synthetic models used by older resolver consumers may not carry crossing
// features. Keep their approach-level controls for compatibility; real
// models below always publish element-owned crossing handles.
if (!(model.crossings || []).length) {
const insetConstraint = constraintFor(constraints, 'junction-crosswalk-inset', anchor);
const insetValue = numericValue(insetConstraint, 'insetMeters', CROSSWALK_JUNCTION_INSET_METERS);
add(
'junction-crosswalk-inset',
insetValue,
0,
MAX_CROSSWALK_INSET_METERS,
(tangent + 180) % 360,
insetConstraint,
controlPoint(insetValue, -1),
);
const stopConstraint = constraintFor(constraints, 'junction-stop-line-offset', anchor);
const stopValue = numericValue(stopConstraint, 'offsetMeters', STOP_LINE_OFFSET_METERS);
add(
'junction-stop-line-offset',
stopValue,
MIN_STOP_LINE_OFFSET_METERS,
Math.max(MIN_STOP_LINE_OFFSET_METERS, approach.length * 0.45),
tangent,
stopConstraint,
controlPoint(stopValue, 1),
);
}
}
// Control-marking handles are element-owned. A single approach may serve
// multiple crossings, so each handle carries the crossing id as well as the
// road context needed to resolve its geometry.
for (const crossing of model.crossings || []) {
const match = approachForCrossing(model, crossing, arrivals);
if (!match || String(match.road.sourceNodeIds?.at(-1)) !== String(nodeId)) continue;
const approach = approaches.find((item) => item.segmentId === match.road.segmentId);
if (!approach) continue;
const road = match.road;
const line = approach.endpoint.side === 'start' ? road.centerline : [...road.centerline].reverse();
const tangent = tangentAzimuth(line, Math.min(0.95, approach.cutback / approach.length));
// `line` is oriented from the junction outward. Native control geometry
// follows the road centerline orientation, which is outward for a `start`
// endpoint and inward for an `end` endpoint. Derive this per approach;
// assuming every arm has the same endpoint side reverses half the handles.
const approachAzimuth = approach.endpoint.side === 'start' ? tangent : (tangent + 180) % 360;
const placementAzimuth = approachAzimuth;
const anchorBase = {
type: 'junction-crossing',
crossingId: String(crossing.id),
nodeId: String(nodeId),
segmentId: approach.segmentId,
roadId: road.id,
};
const controlPoint = (offsetMeters, lateralMeters = 0) => {
const point = coordinateAt(line, Math.min(0.98, Math.max(0.02, offsetMeters / Math.max(approach.length, 1))));
return lateralMeters ? offsetCoordinate(point, (tangent + 90) % 360, lateralMeters) : point;
};
const insetConstraint = constraintFor(constraints, 'junction-crosswalk-inset', anchorBase);
const insetValue = numericValue(insetConstraint, 'insetMeters', CROSSWALK_JUNCTION_INSET_METERS);
// The solver may saturate the inset at the junction boundary; the
// configured value is still the closest stable client-side knob position.
const insetApplied = insetValue;
const insetMax = Math.min(
MAX_CROSSWALK_INSET_METERS,
Math.max(insetValue, effectiveCrosswalkInsetMax(approach.cutback, match.junctionDistanceMeters) || insetValue),
);
handles.push({
handleId: `handle:junction-crosswalk-inset:crossing/${crossing.id}`,
kind: 'junction-crosswalk-inset',
anchor: anchorBase,
// Anchor the knob to the actual crossing feature. The inset is a value
// along the approach, not a reliable screen station from the junction;
// deriving the point from junction distance put the knob off the zebra.
position: offsetCoordinate(crossing.coordinate, placementAzimuth, insetApplied),
// Increasing inset moves the crossing toward the junction.
axisAzimuth: approachAzimuth,
value: { current: insetValue, min: 0, max: insetMax, unit: 'meter' },
...(insetConstraint ? { constraintId: insetConstraint.id } : {}),
affects: [`crosswalk:node/${crossing.id}`],
editable: true,
});
const stopConstraint = constraintFor(constraints, 'junction-stop-line-offset', anchorBase);
const stopValue = numericValue(stopConstraint, 'offsetMeters', STOP_LINE_OFFSET_METERS);
handles.push({
handleId: `handle:junction-stop-line-offset:crossing/${crossing.id}`,
kind: 'junction-stop-line-offset',
anchor: anchorBase,
// The stop line is measured back from the crossing, so its knob follows
// the rendered line while remaining independent of the road cutback.
position: offsetCoordinate(
offsetCoordinate(crossing.coordinate, placementAzimuth, insetApplied),
placementAzimuth,
-stopValue,
),
// The compiled stop line applies `-offset` along the approach axis, so
// Increasing the offset moves away from the junction, opposite to the
// approach axis used by the compiled stop-line geometry.
axisAzimuth: (approachAzimuth + 180) % 360,
value: {
current: stopValue,
min: MIN_STOP_LINE_OFFSET_METERS,
max: Math.max(MIN_STOP_LINE_OFFSET_METERS, approach.length * 0.45),
unit: 'meter',
},
...(stopConstraint ? { constraintId: stopConstraint.id } : {}),
affects: [`stop-line:node/${crossing.id}:1`],
editable: true,
});
}
const ordered = [...approaches].sort((a, b) => a.segmentId.localeCompare(b.segmentId));
for (let index = 0; index < ordered.length; index += 1) {
const incoming = ordered[index];
const outgoing = ordered[(index + 1) % ordered.length];
const anchor = {
type: 'junction-corner',
nodeId: String(nodeId),
incomingRoadId: incoming.segmentId,
outgoingRoadId: outgoing.segmentId,
};
const constraint = constraintFor(constraints, 'junction-corner-radius', anchor);
const first = coordinateAt(
incoming.endpoint.side === 'start'
? incoming.items[0].road.centerline
: [...incoming.items[0].road.centerline].reverse(),
Math.min(0.95, incoming.cutback / incoming.length),
);
const second = coordinateAt(
outgoing.endpoint.side === 'start'
? outgoing.items[0].road.centerline
: [...outgoing.items[0].road.centerline].reverse(),
Math.min(0.95, outgoing.cutback / outgoing.length),
);
const position = [((first?.[0] || 0) + (second?.[0] || 0)) / 2, ((first?.[1] || 0) + (second?.[1] || 0)) / 2];
handles.push({
handleId: `handle:junction-corner-radius:node/${nodeId}:${incoming.segmentId}->${outgoing.segmentId}`,
kind: 'junction-corner-radius',
anchor,
position,
axisAzimuth: tangentAzimuth(incoming.items[0].road.centerline, 0.05),
value: {
current: numericValue(
constraint,
'radiusMeters',
Math.max(1, Math.min(12, incoming.items[0].road.widthMeters)),
),
min: 0.5,
max: 30,
unit: 'meter',
},
...(constraint ? { constraintId: constraint.id } : {}),
affects: junctionAffects(model, nodeId, segmentIds),
editable: true,
});
}
}
return handles;
}
function makeClusterCarriagewayHandles(model, junctionData, constraints, clusters) {
const handles = [];
for (const [clusterId, items] of clusterCarriageways(model, junctionData, clusters)) {
const cluster = clusters.find((item) => String(item.id) === String(clusterId));
if (!cluster) continue;
for (const item of items) {
const road = item.roads[0];
const line = item.approach.endpoint.side === 'start' ? road.centerline : [...road.centerline].reverse();
const station = Math.min(0.95, Math.max(0.05, item.approach.cutback / Math.max(item.approach.length, 1)));
const point = coordinateAt(line, station);
const constraint = constraintFor(constraints, 'cluster-carriageway-width', {
clusterId,
carriagewayKey: item.key,
});
handles.push({
handleId: `handle:cluster-carriageway-width:${item.key}`,
kind: 'cluster-carriageway-width',
anchor: {
type: 'cluster-carriageway',
clusterId,
carriagewayKey: item.key,
sourceNodeIds: item.sourceNodeIds,
sourceRoadIds: item.sourceRoadIds,
},
position: point,
axisAzimuth: (tangentAzimuth(line, station) + 90) % 360,
value: {
current: numericValue(constraint, 'widthMeters', item.widthMeters),
min: Math.max(MIN_LANE_WIDTH_METERS, item.laneCount * MIN_LANE_WIDTH_METERS),
max: Math.max(item.widthMeters * 2, item.laneCount * MIN_LANE_WIDTH_METERS),
unit: 'meter',
},
...(constraint ? { constraintId: constraint.id } : {}),
affects: [`complex-junction:${clusterId}:carriageway:${item.approach.segmentId}`],
editable: true,
});
const transitionConstraint = constraintFor(constraints, 'cluster-carriageway-transition-length', {
clusterId,
carriagewayKey: item.key,
});
const bounds = transitionBounds(model, cluster, item, constraints);
const transitionValue = numericValue(transitionConstraint, 'transitionLengthMeters', bounds.current);
const transitionStation = Math.max(0, bounds.outer - transitionValue) / Math.max(item.length, 1);
if (bounds.max > 0 && bounds.max >= bounds.min)
handles.push({
handleId: `handle:cluster-carriageway-transition-length:${item.key}`,
kind: 'cluster-carriageway-transition-length',
anchor: {
type: 'cluster-carriageway',
clusterId,
carriagewayKey: item.key,
sourceNodeIds: item.sourceNodeIds,
sourceRoadIds: item.sourceRoadIds,
},
position: coordinateAt(line, transitionStation),
axisAzimuth: (tangentAzimuth(line, transitionStation) + 180) % 360,
value: { current: transitionValue, min: bounds.min, max: bounds.max, unit: 'meter' },
...(transitionConstraint ? { constraintId: transitionConstraint.id } : {}),
affects: [`complex-junction:${clusterId}:carriageway:${item.approach.segmentId}`],
editable: true,
});
const cutbackConstraint = constraintFor(constraints, 'cluster-carriageway-cutback', {
clusterId,
carriagewayKey: item.key,
});
handles.push({
handleId: `handle:cluster-carriageway-cutback:${item.key}`,
kind: 'cluster-carriageway-cutback',
anchor: {
type: 'cluster-carriageway',
clusterId,
carriagewayKey: item.key,
sourceNodeIds: item.sourceNodeIds,
sourceRoadIds: item.sourceRoadIds,
},
position: coordinateAt(
line,
Math.min(0.95, Math.max(0.05, item.approach.cutback / Math.max(item.approach.length, 1))),
),
axisAzimuth: tangentAzimuth(line, 0.1),
value: {
current: numericValue(cutbackConstraint, 'cutbackMeters', item.approach.cutback),
min: 1,
max: clusterCutbackMaximum(cluster, item.approach.length),
unit: 'meter',
},
...(cutbackConstraint ? { constraintId: cutbackConstraint.id } : {}),
affects: [`complex-junction:${clusterId}:carriageway:${item.approach.segmentId}`],
editable: true,
});
}
}
return handles;
}
function makeClusterCornerHandles(model, junctionData, constraints, clusters) {
const handles = [];
for (const [clusterId, items] of clusterCarriageways(model, junctionData, clusters)) {
const arms = clusterArms(clusterId, items);
for (let index = 0; index < arms.length; index += 1) {
const first = arms[index];
const second = arms[(index + 1) % arms.length];
const cornerKey = `corner:${first.key}>${second.key}`;
const constraint = constraintFor(constraints, 'cluster-corner-radius', { clusterId, cornerKey });
const firstLine = clusterApproachLine(first.representative);
const secondLine = clusterApproachLine(second.representative);
const firstPoint = firstLine[0];
const secondPoint = secondLine[0];
handles.push({
handleId: `handle:cluster-corner-radius:${cornerKey}`,
kind: 'cluster-corner-radius',
anchor: {
type: 'cluster-corner',
clusterId,
cornerKey,
carriagewayKeys: [first.representative.key, second.representative.key],
},
position: [(firstPoint[0] + secondPoint[0]) / 2, (firstPoint[1] + secondPoint[1]) / 2],
axisAzimuth: first.heading,
value: { current: numericValue(constraint, 'radiusMeters', 12), min: 1, max: 25, unit: 'meter' },
...(constraint ? { constraintId: constraint.id } : {}),
affects: [`complex-junction:${clusterId}:corner:${cornerKey}`],
editable: true,
});
}
}
return handles;
}
function makeClusterCrossingHandles(model, junctionData, constraints, clusters) {
const handles = [];
const itemsByCluster = clusterCarriageways(model, junctionData, clusters);
for (const cluster of clusters) {
if (cluster.template !== 'complex-junction-v1') continue;
const clusterId = String(cluster.id);
const center = clusterCenter(model, cluster);
for (const arm of clusterArms(clusterId, itemsByCluster.get(clusterId) || [])) {
const item = arm.representative;
const line = clusterApproachLine(item);
const length = polylineLength(line);
if (length <= 0) continue;
const crossingKey = `crossing:${arm.key}`;
const anchor = {
type: 'cluster-crossing',
clusterId,
crossingKey,
carriagewayKeys: arm.members.map((member) => member.key).sort(),
};
// Complex crossing geometry is anchored to the core radius. Using the
// carriageway cutback here put the editor knob on a different station
// from the zebra it controls, especially for multi-node clusters.
const pointAt = (distance) =>
clusterArmRadiusPoint(arm, center, distance) ||
coordinateAt(line, Math.min(0.9, Math.max(0.05, distance / length)));
const baseCrosswalkDistance = clusterCrossingBaseRadius(
model,
arm,
center,
Math.max(2, complexJunctionMetrics(cluster).coreRadius * 0.68),
);
const insetConstraint = constraintFor(constraints, 'cluster-crossing-inset', anchor);
const inset = numericValue(insetConstraint, 'insetMeters', 0);
handles.push({
handleId: `handle:cluster-crossing-inset:${crossingKey}`,
kind: 'cluster-crossing-inset',
anchor,
position: pointAt(baseCrosswalkDistance + inset),
axisAzimuth: arm.heading,
value: { current: inset, min: 0, max: MAX_CROSSWALK_INSET_METERS, unit: 'meter' },
...(insetConstraint ? { constraintId: insetConstraint.id } : {}),
affects: [`complex-crosswalk:${clusterId}`],
editable: true,
});
const stopConstraint = constraintFor(constraints, 'cluster-stop-line-offset', anchor);
const offset = numericValue(stopConstraint, 'offsetMeters', 3);
handles.push({
handleId: `handle:cluster-stop-line-offset:${crossingKey}`,
kind: 'cluster-stop-line-offset',
anchor,
position: pointAt(baseCrosswalkDistance + inset + offset),
axisAzimuth: arm.heading,
value: { current: offset, min: MIN_STOP_LINE_OFFSET_METERS, max: 12, unit: 'meter' },
...(stopConstraint ? { constraintId: stopConstraint.id } : {}),
affects: [`complex-stop-line:${clusterId}`],
editable: true,
});
}
}
return handles;
}
/**
* Which handles a selection wants.
*
* Whole-manifest responses are expensive: on a 41-road area the handles are
* 844 KB, 89% of it the `affects` id lists (46 ids per junction handle), and the
* map renders about six of them. `selection` therefore scopes the manifest to the
* object being edited. Omitting it keeps the full manifest, which the compiler
* and the existing callers rely on.
*
* The two selection types match the two editors: the main map owns a road
* segment's cross-section, JunctionTools owns a node.
*/
function selectHandles(handles, model, selection) {
if (!selection || !selection.type) return handles;
if (selection.type === 'cluster')
return handles.filter(
(handle) => handle.anchor?.clusterId === String(selection.id) && handle.kind.startsWith('cluster-'),
);
if (selection.type === 'segment') {
const segmentOf = new Map((model.roads || []).map((road) => [road.id, road.segmentId]));
const wanted = String(selection.id);
return handles.filter((handle) => {
if (!handle.anchor) return false;
// Control markings are junction-anchored but edited from the main map, and
// they name their segment directly. Junction *shape* kinds stay out: those
// are JunctionTools', and the main map must not offer a second way in.
if (CONTROL_KINDS.has(handle.kind)) return handle.anchor.segmentId === wanted;
if (handle.kind === 'lane-maneuver') {
return handle.anchor?.type === 'lane' && segmentOf.get(handle.anchor.roadId) === wanted;
}
return handle.kind.startsWith('road-') && segmentOf.get(handle.anchor.roadId) === wanted;
});
}
if (selection.type === 'junction')
return handles.filter(
(handle) => handle.kind.startsWith('junction-') && handle.anchor?.nodeId === String(selection.id),
);
return handles;
}
function resolveDirectEditConstraints(model, editDocument = null, context = {}) {
const diagnostics = [];
const constraints = Array.isArray(editDocument && editDocument.constraints) ? editDocument.constraints : [];
const handles = emptyHandleManifest(context);
const groups = roadGroups(model || {});
const junctionData = junctionReserves(model || {});
const reconciled = reconcileConstraints(model || {}, constraints, editDocument?.base, junctionData, context);
const clusters = context.junctionTemplates?.clusters || context.junctionClusters || [];
const solved = solveConstraints(model || {}, reconciled, junctionData, diagnostics, clusters);
const effectiveJunctionPlans = buildEffectiveJunctionPlans(
model || {},
solved.junctionPlans,
junctionData,
clusters,
solved.clusterPlans,
);
handles.reserves = junctionData.reserves;
handles.handles = selectHandles(
[
...makeRoadHandles(model || {}, groups, handles.reserves, reconciled, solved.roadProfiles),
...makeJunctionHandles(model || {}, junctionData, reconciled),
...makeClusterCarriagewayHandles(model || {}, junctionData, reconciled, clusters),
...makeClusterCornerHandles(model || {}, junctionData, reconciled, clusters),
...makeClusterCrossingHandles(model || {}, junctionData, reconciled, clusters),
...makeLaneManeuverHandles(model || {}, reconciled),
],
model || {},
context.selection,
);
return {
schema: RESOLUTION_SCHEMA,
roadProfiles: solved.roadProfiles,
junctionPlans: solved.junctionPlans,
effectiveJunctionPlans,
crossingControls: solved.crossingControls,
clusterPlans: solved.clusterPlans,
clusterCutbacks: solved.clusterCutbacks,
clusterTransitions: solved.clusterTransitions,
clusterCorners: solved.clusterCorners,
clusterCrossings: solved.clusterCrossings,
laneManeuvers: solved.laneManeuvers,
handles,
constraintStates: solved.states,
diagnostics,
};
}
// Normalize node plans and configured clusters into the read model consumed by
// JunctionTools. Clusters deliberately remain read-only in this phase: their
// effective plan is assembled from member nodes without rewriting constraints or
// silently splitting the cluster into independent editors.
function buildEffectiveJunctionPlans(model, solvedPlans, junctionData, clusters = [], clusterPlans = new Map()) {
const nodePlan = (nodeId) => {
const id = String(nodeId);
const solved = solvedPlans.get(id);
const approaches = junctionData.approaches.get(id) || [];
if (solved)
return {
schema: 'junction-effective-plan/v1',
junctionRef: { type: 'node', id },
...solved,
nodeId: id,
readOnly: false,
};
if (!approaches.length) return null;
return {
schema: 'junction-effective-plan/v1',
junctionRef: { type: 'node', id },
nodeId: id,
approaches: Object.fromEntries(
approaches.map((item) => [
item.segmentId,
{
widthMeters: item.items.reduce((sum, entry) => sum + entry.road.widthMeters, 0),
cutbackMeters: item.cutback,
},
]),
),
corners: {},
readOnly: false,
};
};
const result = new Map();
for (const [nodeId] of junctionData.approaches) {
const plan = nodePlan(nodeId);
if (plan) result.set(`node:${nodeId}`, plan);
}
for (const cluster of Array.isArray(clusters) ? clusters : []) {
if (!cluster || !cluster.id || !Array.isArray(cluster.nodeIds)) continue;
const members = cluster.nodeIds.map((id) => nodePlan(id)).filter(Boolean);
if (!members.length) continue;
const approaches = members.flatMap((member) =>
Object.entries(member.approaches || {}).map(([segmentId, value]) => ({
nodeId: member.nodeId,
segmentId,
...value,
})),
);
const corners = Object.assign({}, ...members.map((member) => member.corners || {}));
const carriageways = clusterCarriageways(model, junctionData, [cluster]).get(String(cluster.id)) || [];
const widths = clusterPlans.get(String(cluster.id)) || new Map();
result.set(`cluster:${cluster.id}`, {
schema: 'junction-effective-plan/v1',
junctionRef: { type: 'cluster', id: String(cluster.id) },
nodeIds: cluster.nodeIds.map(String),
approaches,
carriageways: carriageways.map((item) => ({
key: item.key,
nodeId: item.nodeId,
segmentId: item.approach.segmentId,
widthMeters: widths.get(item.key) ?? item.widthMeters,
sourceNodeIds: item.sourceNodeIds,
sourceRoadIds: item.sourceRoadIds,
})),
corners,
readOnly: false,
});
}
return result;
}
module.exports = {
CROSSWALK_DEPTH_METERS,
CROSSWALK_STRIPE_PITCH_METERS,
CROSSWALK_STRIPE_WIDTH_METERS,
MAX_CROSSWALK_STRIPE_COUNT,
MIN_CROSSWALK_STRIPE_COUNT,
CROSSWALK_JUNCTION_INSET_METERS,
STOP_LINE_OFFSET_METERS,
RESOLUTION_SCHEMA,
HANDLE_MANIFEST_SCHEMA,
ACTIVE_STATUSES,
SOLVED_KINDS,
KINDS,
GEOMETRY_VERSION,
roadEdgeOffsetRange,
SUPPORTED_MANEUVERS,
resolveDirectEditConstraints,
buildEffectiveJunctionPlans,
};