feat(junction): share complex topology build plan

This commit is contained in:
que01 committed 2026-09-08 17:47:35 +08:00
1 parent 855400fba2
commit a12e2ac823
20 files changed
+712 -147

No files matched your search

+5 -76
View File
@@ -1,7 +1,8 @@
'use strict';
const fs = require('fs');
const { topologyIdentity, structureFromTopology } = require('./junction-topology');
const { structureFromTopology } = require('./junction-topology');
const { resolveJunctionBuildPlan } = require('./junction-build-plan');
const { convertGeoJson, boundsOf } = require('../reference/gaode');
const metricsCache = new WeakMap();
const CORNER_FILLET_SEGMENTS = 12;
@@ -13,81 +14,9 @@ const SIDEWALK_WIDTH_METERS = 2;
// past that end and let the two overlap rather than chase an exact seam.
const SIDEWALK_CORNER_OVERRUN_METERS = 6;
// Geometry and the durable structure use this single external topology.
function resolveComplexJunctionTopology(model, cluster, helpers) {
const nodeIds = new Set(cluster.nodeIds.map(String));
const nodes = [...nodeIds]
.sort()
.map((id) => helpers.junctionPlans.get(id)?.node)
.filter(Boolean);
const carriageways = [];
for (const [nodeId, plan] of helpers.junctionPlans) {
if (!nodeIds.has(String(nodeId))) continue;
for (const approach of plan.approaches) {
const roads = approach.roadIds.map((id) => model.roads.find((road) => road.id === id)).filter(Boolean);
// Source topology is authoritative; geometric proximity is only a fallback
// for legacy plans with no source-node metadata.
const sourced = roads.filter((road) => road.sourceNodeIds?.length >= 2);
const internal = sourced.length
? sourced.every(
(road) => nodeIds.has(String(road.sourceNodeIds[0])) && nodeIds.has(String(road.sourceNodeIds.at(-1))),
)
: nodes.some((node) => node !== plan.node && helpers.distanceMeters(approach.line.at(-1), node) < 4);
if (internal) continue;
carriageways.push({
nodeId: String(nodeId),
approach,
plan,
roads,
heading: helpers.headingAtEndpoint(approach.line),
length: helpers.lineLengthMeters(approach.line),
});
}
}
// Stable source ordering makes heading grouping independent of plan/road order.
carriageways.sort((a, b) => topologyIdentity(a).localeCompare(topologyIdentity(b)));
const duplicateSources = new Set();
const seenSources = new Set();
for (const item of carriageways) {
const identity = topologyIdentity(item);
if (seenSources.has(identity)) duplicateSources.add(identity);
seenSources.add(identity);
}
for (let index = carriageways.length - 1; index > 0; index -= 1)
if (topologyIdentity(carriageways[index]) === topologyIdentity(carriageways[index - 1]))
carriageways.splice(index, 1);
const arms = [];
for (const item of carriageways) {
item.ambiguousSource = duplicateSources.has(topologyIdentity(item));
let arm = arms.find(
(candidate) => Math.abs(normalizeHeading(candidate.representative.heading - item.heading)) < 20,
);
if (!arm) {
arm = { representative: item, members: [] };
arms.push(arm);
}
arm.members.push(item);
}
for (const arm of arms) arm.heading = averageHeading(arm.members.map((item) => item.heading));
for (const item of carriageways)
if (arms.filter((arm) => Math.abs(normalizeHeading(arm.representative.heading - item.heading)) < 20).length > 1)
item.ambiguousSource = true;
arms.sort(
(a, b) =>
a.heading - b.heading || topologyIdentity(a.representative).localeCompare(topologyIdentity(b.representative)),
);
const scope = `cluster:${encodeURIComponent(cluster.id)}`;
for (const arm of arms) {
arm.key = `${scope}:arm:${arm.members.map(topologyIdentity).sort().join('|')}`;
for (const item of arm.members) {
item.key = `${scope}:carriageway:${topologyIdentity(item)}`;
item.armKey = arm.key;
}
}
for (let index = 0; index < arms.length; index += 1)
arms[index].cornerKey = `corner:${arms[index].key}>${arms[(index + 1) % arms.length].key}`;
return { cluster, nodeIds: [...nodeIds].sort(), carriageways, arms };
}
// Compatibility export for current compiler consumers. The build-plan module is
// pure and is the shared authority for geometry and direct-edit identity.
const resolveComplexJunctionTopology = resolveJunctionBuildPlan;
function buildComplexJunctionGeometry(model, cluster, helpers) {
const nodeIds = new Set(cluster.nodeIds.map(String));
+41 -70
View File
@@ -13,8 +13,8 @@ const {
junctionSurfaceId,
connectionConnectorId,
} = require('./native-ids');
const { topologyIdentity } = require('./junction-topology');
const { complexJunctionMetrics } = require('./complex-junction');
const { resolveJunctionBuildPlan } = require('./junction-build-plan');
const RESOLUTION_SCHEMA = 'road-edit-resolution/v1';
const HANDLE_MANIFEST_SCHEMA = 'road-edit-handles/v1';
@@ -211,89 +211,60 @@ 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 nodeIds = new Set(cluster.nodeIds.map(String));
const items = [];
for (const nodeId of nodeIds) {
for (const approach of junctionData.approaches.get(nodeId) || []) {
const roads = approach.items.map((item) => item.road);
const sourced = roads.filter((road) => road.sourceNodeIds?.length >= 2);
const internal =
sourced.length &&
sourced.every(
(road) => nodeIds.has(String(road.sourceNodeIds[0])) && nodeIds.has(String(road.sourceNodeIds.at(-1))),
);
if (internal || !roads.length) continue;
const source = {
nodeId: String(nodeId),
approach: { segmentId: approach.segmentId, roadIds: roads.map((road) => road.id) },
roads,
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,
};
items.push({
clusterId: String(cluster.id),
nodeId: String(nodeId),
approach,
roads,
identity: topologyIdentity(source),
key: `cluster:${encodeURIComponent(cluster.id)}:carriageway:${topologyIdentity(source)}`,
sourceNodeIds: [...new Set(roads.flatMap((road) => (road.sourceNodeIds || []).map(String)))].sort(),
sourceRoadIds: roads.map((road) => String(road.id)).sort(),
widthMeters: approach.items.reduce((sum, item) => sum + item.road.widthMeters, 0),
laneCount: roads.reduce((sum, road) => sum + (Number(road.laneCount) || 0), 0),
});
}
});
const node = approaches[0]?.line?.[0] || [0, 0];
plans.set(nodeId, { node, approaches });
}
const seen = new Set();
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),
items.filter((item) => !seen.has(item.key) && seen.add(item.key)),
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) {
const road = item.approach.items[0]?.road;
if (!road) return [];
return item.approach.endpoint.side === 'end' ? [...road.centerline].reverse() : road.centerline;
return item.approach.line || [];
}
function headingDifference(first, second) {
return Math.abs(((first - second + 540) % 360) - 180);
}
function averageHeading(headings) {
const vector = headings.reduce(
(sum, heading) => {
const radians = (heading * Math.PI) / 180;
return [sum[0] + Math.sin(radians), sum[1] + Math.cos(radians)];
},
[0, 0],
);
return ((Math.atan2(vector[0], vector[1]) * 180) / Math.PI + 360) % 360;
}
// Mirrors resolveComplexJunctionTopology(): corner identity belongs to adjacent
// external arms, not whichever individual carriageways happened to be listed.
function clusterArms(clusterId, items) {
const arms = [];
for (const item of [...items].sort((a, b) => a.identity.localeCompare(b.identity))) {
item.heading = tangentAzimuth(clusterApproachLine(item), 0.05);
let arm = arms.find((candidate) => headingDifference(candidate.representative.heading, item.heading) < 20);
if (!arm) {
arm = { representative: item, members: [] };
arms.push(arm);
}
arm.members.push(item);
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),
});
}
for (const arm of arms) {
arm.heading = averageHeading(arm.members.map((member) => member.heading));
arm.key = `cluster:${encodeURIComponent(clusterId)}:arm:${arm.members
.map((member) => member.identity)
.sort()
.join('|')}`;
}
arms.sort((a, b) => a.heading - b.heading || a.representative.identity.localeCompare(b.representative.identity));
return arms;
return [...byArm.values()];
}
function numericValue(constraint, key, fallback) {
+151
View File
@@ -0,0 +1,151 @@
'use strict';
const { topologyIdentity } = require('./junction-topology');
const MIN_ENTRY_SECTION_METERS = 12;
function normalizeHeading(value) {
return ((((value + 180) % 360) + 360) % 360) - 180;
}
function averageHeading(headings) {
const vector = headings.reduce(
(sum, heading) => {
const radians = (heading * Math.PI) / 180;
return [sum[0] + Math.sin(radians), sum[1] + Math.cos(radians)];
},
[0, 0],
);
return ((Math.atan2(vector[0], vector[1]) * 180) / Math.PI + 360) % 360;
}
function tangentAt(line, station, length, helpers) {
if (!Array.isArray(line) || line.length < 2 || !Number.isFinite(length) || length <= 0) return null;
let walked = 0;
for (let index = 1; index < line.length; index += 1) {
const segmentLength = helpers.distanceMeters(line[index - 1], line[index]);
if (station <= walked + segmentLength || index === line.length - 1)
return helpers.headingAtEndpoint([line[index - 1], line[index]]);
walked += segmentLength;
}
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 boundaryAt(point, tangent, widthMeters) {
const halfWidth = Math.max(0, Number(widthMeters) || 0) / 2;
return {
left: offsetCoordinate(point, tangent - 90, halfWidth),
right: offsetCoordinate(point, tangent + 90, halfWidth),
};
}
function entrySectionFor(item, helpers) {
const length = item.length;
const line = item.approach.line;
const nearTangent = tangentAt(line, 0, length, helpers);
const farTangent = tangentAt(line, length, length, helpers);
const feasible = Number.isFinite(length) && length >= MIN_ENTRY_SECTION_METERS;
return {
carriagewayKey: item.key,
sourceLine: line,
nearStationMeters: 0,
farStationMeters: length,
entryStationMeters: 0,
nearTangent,
farTangent,
boundaryEndpoints: {
near: boundaryAt(line?.[0] || null, nearTangent, item.approach.widthMeters),
far: boundaryAt(line?.at(-1) || null, farTangent, item.approach.widthMeters),
},
feasibility: feasible ? 'supported' : 'short-approach',
...(feasible ? {} : { reason: 'entry-section-too-short' }),
};
}
// This plan is deliberately limited to source topology and source-polyline
// sections. It is shared by geometry and edit identity, while later work can
// add computed shared boundaries without making either layer guess arm order.
function resolveJunctionBuildPlan(model, cluster, helpers) {
const nodeIds = new Set(cluster.nodeIds.map(String));
const nodes = [...nodeIds]
.sort()
.map((id) => helpers.junctionPlans.get(id)?.node)
.filter(Boolean);
const carriageways = [];
for (const [nodeId, plan] of helpers.junctionPlans) {
if (!nodeIds.has(String(nodeId))) continue;
for (const approach of plan.approaches || []) {
const roads = approach.roadIds.map((id) => model.roads.find((road) => road.id === id)).filter(Boolean);
const sourced = roads.filter((road) => road.sourceNodeIds?.length >= 2);
const internal = sourced.length
? sourced.every(
(road) => nodeIds.has(String(road.sourceNodeIds[0])) && nodeIds.has(String(road.sourceNodeIds.at(-1))),
)
: nodes.some((node) => node !== plan.node && helpers.distanceMeters(approach.line.at(-1), node) < 4);
if (internal) continue;
carriageways.push({
nodeId: String(nodeId),
approach,
plan,
roads,
heading: helpers.headingAtEndpoint(approach.line),
length: helpers.lineLengthMeters(approach.line),
});
}
}
carriageways.sort((a, b) => topologyIdentity(a).localeCompare(topologyIdentity(b)));
const duplicateSources = new Set();
const seenSources = new Set();
for (const item of carriageways) {
const identity = topologyIdentity(item);
if (seenSources.has(identity)) duplicateSources.add(identity);
seenSources.add(identity);
}
for (let index = carriageways.length - 1; index > 0; index -= 1)
if (topologyIdentity(carriageways[index]) === topologyIdentity(carriageways[index - 1]))
carriageways.splice(index, 1);
const arms = [];
for (const item of carriageways) {
item.ambiguousSource = duplicateSources.has(topologyIdentity(item));
let arm = arms.find(
(candidate) => Math.abs(normalizeHeading(candidate.representative.heading - item.heading)) < 20,
);
if (!arm) {
arm = { representative: item, members: [] };
arms.push(arm);
}
arm.members.push(item);
}
for (const arm of arms) arm.heading = averageHeading(arm.members.map((item) => item.heading));
for (const item of carriageways)
if (arms.filter((arm) => Math.abs(normalizeHeading(arm.representative.heading - item.heading)) < 20).length > 1)
item.ambiguousSource = true;
arms.sort(
(a, b) =>
a.heading - b.heading || topologyIdentity(a.representative).localeCompare(topologyIdentity(b.representative)),
);
const scope = `cluster:${encodeURIComponent(cluster.id)}`;
for (const arm of arms) {
arm.key = `${scope}:arm:${arm.members.map(topologyIdentity).sort().join('|')}`;
for (const item of arm.members) {
item.key = `${scope}:carriageway:${topologyIdentity(item)}`;
item.armKey = arm.key;
item.entrySection = entrySectionFor(item, helpers);
}
}
for (let index = 0; index < arms.length; index += 1)
arms[index].cornerKey = `corner:${arms[index].key}>${arms[(index + 1) % arms.length].key}`;
return { schema: 'junction-build-plan/v1', cluster, nodeIds: [...nodeIds].sort(), carriageways, arms };
}
module.exports = { MIN_ENTRY_SECTION_METERS, resolveJunctionBuildPlan };