fix complex junction island geometry

This commit is contained in:
que01 committed 2026-09-16 13:24:34 +08:00
1 parent c3579074fd
commit 0c42eb46cd
19 files changed
+424 -44

No files matched your search

Binary file not shown.

After

Width:  |  Height:  |  Size: 192 KiB

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1000" height="1000" viewBox="-52.78889359712193 -40.86147050800531 71.14669386644465 70.76835623217826"><rect x="-52.78889359712193" y="-40.86147050800531" width="71.14669386644465" height="70.76835623217826" fill="#454950"/><path d="M-200.13011320235026,96.97316481090922L-50.40949800958033,14.550274196968616L-45.7075152497884,23.09155309989208L-195.42813044255834,105.51444371383269L-200.13011320235026,96.97316481090922Z" fill="#62666c" stroke="none" stroke-width="0"/><path d="M-793.7916770658974,-387.7839318791216L-845.1650567582058,-487.13703187901854L-839.3910080114139,-490.1224555961643L-788.0176283191055,-390.76935559626736L-793.7916770658974,-387.7839318791216Z" fill="#62666c" stroke="none" stroke-width="0"/><path d="M-2212.489088585786,-179.16371676032455L-2140.8373837257627,-212.76908247573147L-2055.3546438878975,-257.7298604933583L-1946.504942587327,-317.49844706818476L-1920.2967912232373,-331.66965274156485L-1909.267437792862,-337.1847523911823L-1906.360681520644,-331.370885985413L-1917.2587011279645,-325.9233227337445L-1943.3834621352125,-311.79698440706477L-2052.2709166003433,-252.00789098238346L-2137.93042558401,-206.9553169993128L-2209.728856397725,-173.27887471468827L-2212.489088585786,-179.16371676032455Z" fill="#62666c" stroke="none" stroke-width="0"/><path d="M-1901.3832252060452,-341.1116816775457L-1893.2847693869107,-346.1210816775538L-1889.8652200042864,-340.5932057979503L-1897.9636758234208,-335.5838057979422L-1901.3832252060452,-341.1116816775457Z" fill="#62666c" stroke="none" stroke-width="0"/><path d="M-1885.5446540386663,-350.90762542444725L-1871.3336073778248,-359.69567637035624L-1867.9004329088675,-361.592089505735L-1865.3636714937468,-362.96850950667204L-1661.6452375512724,-473.3089209311598L-1559.2054575963696,-528.7900258071686L-1488.0931582262856,-565.8036376884446L-1468.1927540956744,-576.4637935848872L-1465.1233484809766,-570.7341030074538L-1485.0769145942518,-560.045785786982L-1556.1481677590236,-523.0538616679592L-1658.5494243487235,-467.59345454390456L-1862.2677570264448,-357.2530979688686L-1864.7781375089362,-355.89104596944264L-1867.9657385322353,-354.13616310486475L-1882.125719951502,-345.3793670833436L-1885.5446540386663,-350.90762542444725Z" fill="#62666c" stroke="none" stroke-width="0"/><path d="M-1452.1469867840974,-585.0594846582919L-1432.104456652289,-595.7962435514792L-1218.1918007211652,-715.7288498478376L-1079.6540729108235,-790.43451194658L-1040.3070028720547,-810.8356521885094L-1036.7982547964043,-812.6787966482818L-1034.9293077213947,-813.3780107231175L-1032.694005761087,-807.2744083702975L-1034.0080950149177,-806.8080348272504L-1037.312028967057,-805.0666752870558L-1076.5890667358456,-784.7024315287647L-1215.0492330132888,-710.0389176276485L-1428.9346271731526,-590.1214519235243L-1449.0771977421884,-579.3299639841225L-1452.1469867840974,-585.0594846582919Z" fill="#62666c" stroke="none" stroke-width="0"/><path d="M-845.1547466225953,-487.1172091076758L-991.4358727260025,-765.306591104199L-1010.3303829813176,-801.425404366697L-1014.8573823615368,-809.2944049210076L-1009.2222786408443,-812.5345388472233L-1004.5927835431219,-804.4803871083212L-985.6817062029568,-768.3302563710397L-839.4013181470243,-490.14227836750706L-845.1547466225953,-487.1172091076758Z" fill="#62666c" stroke="none" stroke-width="0"/><path d="M-1019.3748880334443,-817.1506845179565L-1021.636937053879,-820.9759595915772L-1022.7230343166299,-822.7935558234957L-1024.4987487264195,-825.8113064161093L-1028.258392942898,-832.1536348496203L-1022.6664397364649,-835.4679646260355L-1018.9033477431357,-829.1198130591567L-1017.1287912346535,-826.1040196516587L-1016.0463446409709,-824.2925838838808L-1013.7793994102785,-820.4590429573801L-1019.3748880334443,-817.1506845179565Z" fill="#62666c" stroke="none" stroke-width="0"/><path d="M-476.8493517975444,185.05069806548647L-592.2916845241798,-18.86100573671456L-601.6200539462159,-33.298132793636626L-793.7597756470255,-387.7240606086096L-788.0455703603151,-390.8219232925737L-595.9156037179849,-36.41392268205806L-586.6482297994067,-22.085961738993376L-471.1930466514354,181.84833493475026L-476.8493517975444,185.05069806548647Z" fill="#62666c" stroke="none" stroke-width="0"/><path d="M-2200.3163351069234,-874.7506753824654L-2195.2308119016593,-867.4814793825467L-2197.8941022197573,-865.6185440926313L-2202.9796254250214,-872.88774009255L-2200.3163351069234,-874.7506753824654Z" fill="#62666c" stroke="none" stroke-width="0"/><path d="M-2190.6066283641294,-859.4800486845243L-2171.2290628963233,-825.8985000095679L-1988.6461687232077,-504.8129046352983L-1927.0761413734326,-393.358987669808L-1912.2793798232574,-366.9302321034586L-1910.2267214089243,-362.8642615497772L-1913.128617930232,-361.4004206149873L-1915.1242567726058,-365.35846337230555L-1929.9194830758202,-391.7844438058693L-1991.4766892366433,-503.21543084034914L-2174.0535517972303,-824.2903874656485L-2193.421878582618,-857.8558191919022L-2190.6066283641294,-8Line truncated

After

Width:  |  Height:  |  Size: 236 KiB

+114 -6
View File
@@ -14,6 +14,7 @@ const {
solveIslandContacts,
} = require('./junction-facility-composition');
const { complexJunctionMetrics: calculateComplexJunctionMetrics } = require('./junction-metrics');
const { radialShift } = require('./junction-island-offset');
const { convertGeoJson, boundsOf } = require('../reference/gaode');
const metricsCache = new WeakMap();
const CORNER_FILLET_SEGMENTS = 12;
@@ -88,6 +89,11 @@ function buildComplexJunctionGeometry(model, cluster, helpers) {
const crossingRegions = [];
const stopLines = [];
const islands = [];
// Each arm crossing is shared by two corner islands. Corner generation
// records its two endpoint displacements here; the stripes are rebuilt once
// after every corner has contributed, rather than being mutated per corner.
const armEndpointOffsets = new Map();
const islandOffsetMeters = Number(helpers.clusterIslandOffsetMeters) || 0;
const crossingControls = helpers.clusterCrossingControls || new Map();
const crossingPlans = new Map(
arms.map((arm) => {
@@ -341,6 +347,7 @@ function buildComplexJunctionGeometry(model, cluster, helpers) {
arm.crosswalkFrame.center = midpoint(...endpoints);
arm.crosswalkFrame.endpoints = endpoints;
arm.crosswalkFrame.spanMeters = usableSpan;
arm.crosswalkFrame.contactEndpointRatio = (layout.centers[0] - layout.width / 2) / usableSpan;
arm.crosswalkFrame.roadEdgeInsetMeters = roadEdgeInset;
crossingRegions.push(rectangle(arm.crosswalkFrame.center, crossingHeading, groupDepth, usableSpan));
for (let stripe = 0; stripe < stripeCount; stripe += 1) {
@@ -510,8 +517,14 @@ function buildComplexJunctionGeometry(model, cluster, helpers) {
geometry: { type: 'Polygon', coordinates: [ring] },
});
if (!first.crosswalkFrame?.endpoints || !second.crosswalkFrame?.endpoints) continue;
const endpointPairs = first.crosswalkFrame.endpoints.flatMap((a) =>
second.crosswalkFrame.endpoints.map((b) => ({ a, b, distance: helpers.distanceMeters(a, b) })),
const endpointPairs = first.crosswalkFrame.endpoints.flatMap((a, firstEndpointIndex) =>
second.crosswalkFrame.endpoints.map((b, secondEndpointIndex) => ({
a,
b,
firstEndpointIndex,
secondEndpointIndex,
distance: helpers.distanceMeters(a, b),
})),
);
const pair = endpointPairs.sort((a, b) => a.distance - b.distance)[0];
const crossingCorner = rayIntersection(
@@ -543,11 +556,11 @@ function buildComplexJunctionGeometry(model, cluster, helpers) {
toLocal(helpers.offsetCoordinate(edgeCenter, frame.heading, (sign * frame.groupDepth) / 2)),
);
};
const contactSolution = solveIslandContacts(
let contactSolution = solveIslandContacts(
landing(first, pair.a),
landing(second, pair.b),
COMPLEX_CROSSWALK_DEPTH_METERS,
{ maxLegLength: outerRadius, minLegLength: Math.max(outerRadius - coreRadius, COMPLEX_CROSSWALK_DEPTH_METERS) },
{ maxLegLength: outerRadius },
);
if (contactSolution.status !== 'solved') {
cornerDiagnostics.push(
@@ -562,6 +575,49 @@ function buildComplexJunctionGeometry(model, cluster, helpers) {
);
continue;
}
// Dragging moves the whole pedestrian composition away from the cluster
// centre. Re-solve from the translated landing segments so the island,
// its green contact hexagon and all three complete contacts retain the same
// source coordinates instead of merely translating a detached island.
let islandShift = [0, 0];
if (islandOffsetMeters > 0) {
const provisionalRing = contactSolution.ring.map(fromLocal);
const provisionalCenter = polygonCenter(provisionalRing);
islandShift = radialShift(center, provisionalCenter, islandOffsetMeters);
const localShift = toLocal([crossingCorner[0] + islandShift[0], crossingCorner[1] + islandShift[1]]);
const translateSegment = (segment) =>
segment.map((point) => [point[0] + localShift[0], point[1] + localShift[1]]);
const shifted = solveIslandContacts(
translateSegment(landing(first, pair.a)),
translateSegment(landing(second, pair.b)),
COMPLEX_CROSSWALK_DEPTH_METERS,
{ maxLegLength: outerRadius },
);
if (shifted.status !== 'solved') {
cornerDiagnostics.push(
helpers.diagnostic(
'warning',
`corner:${first.cornerKey}`,
[...nodeIds],
'complex-junction-island-offset-infeasible',
shifted.reason,
crossingCorner,
),
);
continue;
}
contactSolution = shifted;
const rememberOffset = (arm, endpointIndex) => {
const offsets = armEndpointOffsets.get(arm.key) || [
[0, 0],
[0, 0],
];
offsets[endpointIndex] = islandShift;
armEndpointOffsets.set(arm.key, offsets);
};
rememberOffset(first, pair.firstEndpointIndex);
rememberOffset(second, pair.secondEndpointIndex);
}
const publishedIslandRing = contactSolution.ring.map(fromLocal);
const greenRing = contactSolution.greenRing.map(fromLocal);
if (!cornerOverlapsExclusion(publishedIslandRing, first.cornerKey, '安全岛'))
@@ -722,6 +778,40 @@ function buildComplexJunctionGeometry(model, cluster, helpers) {
geometry: { type: 'Polygon', coordinates: [sidewalkRing] },
});
}
// Rebuild each shared arm crossing from its two endpoint displacement values.
// Interpolation occurs along its declared support axis, preserving every
// stripe's width and spacing while allowing the two neighbouring islands to
// move in different radial directions.
if (armEndpointOffsets.size) {
for (const arm of arms) {
const offsets = armEndpointOffsets.get(arm.key);
if (!offsets || !arm.crosswalkFrame?.endpoints) continue;
const [start, end] = arm.crosswalkFrame.endpoints;
const movedRing = (ring) =>
ring.map((point) => {
const rawRatio = projectionRatio(point, start, end);
const contactRatio = arm.crosswalkFrame.contactEndpointRatio || 0;
const ratio = Math.max(0, Math.min(1, (rawRatio - contactRatio) / (1 - contactRatio * 2)));
const shift = [
offsets[0][0] * (1 - ratio) + offsets[1][0] * ratio,
offsets[0][1] * (1 - ratio) + offsets[1][1] * ratio,
];
return [point[0] + shift[0], point[1] + shift[1]];
});
for (const crossing of crosswalks) {
if (crossing.properties.arm_key === arm.key)
crossing.geometry.coordinates[0] = movedRing(crossing.geometry.coordinates[0]);
}
const averageShift = [(offsets[0][0] + offsets[1][0]) / 2, (offsets[0][1] + offsets[1][1]) / 2];
for (const stopLine of stopLines) {
if (stopLine.properties.arm_key !== arm.key) continue;
stopLine.geometry.coordinates[0] = stopLine.geometry.coordinates[0].map((point) => [
point[0] + averageShift[0],
point[1] + averageShift[1],
]);
}
}
}
const features = [];
let coreFeature = null;
if (coreRing)
@@ -842,8 +932,12 @@ function buildComplexJunctionGeometry(model, cluster, helpers) {
'warning',
`junction-cluster:${cluster.id}`,
[...nodeIds],
'complex-junction-pavement-region-disconnected',
'过街与入口无法组成连续铺装区域,保留结构输入面并拒绝发布统一铺装面。',
pavementRegion.status === 'unsupported'
? 'complex-junction-pavement-region-assembly-failed'
: 'complex-junction-pavement-region-disconnected',
pavementRegion.status === 'unsupported'
? '统一铺装区域无法可靠装配,保留结构输入面并拒绝发布统一铺装面。'
: '过街与入口无法组成连续铺装区域,保留结构输入面并拒绝发布统一铺装面。',
center,
),
);
@@ -1221,6 +1315,20 @@ function directionalProjectionMeters(origin, point, heading) {
const radians = (heading * Math.PI) / 180;
return east * Math.sin(radians) + north * Math.cos(radians);
}
function polygonCenter(ring) {
const points = ring.slice(0, -1);
return points.reduce((sum, point) => [sum[0] + point[0] / points.length, sum[1] + point[1] / points.length], [0, 0]);
}
function projectionRatio(point, start, end) {
const lonScale = 111320 * Math.cos((start[1] * Math.PI) / 180);
const vector = [(end[0] - start[0]) * lonScale, (end[1] - start[1]) * 111320];
const relative = [(point[0] - start[0]) * lonScale, (point[1] - start[1]) * 111320];
const lengthSquared = vector[0] * vector[0] + vector[1] * vector[1];
if (lengthSquared < 1e-12) return 0;
return Math.max(0, Math.min(1, (relative[0] * vector[0] + relative[1] * vector[1]) / lengthSquared));
}
module.exports = {
resolveComplexJunctionTopology,
buildComplexJunctionGeometry,
+79 -1
View File
@@ -35,6 +35,7 @@ const SOLVED_KINDS = new Set([
'cluster-carriageway-direction',
'cluster-carriageway-edge-offset',
'cluster-corner-radius',
'cluster-island-offset',
'cluster-crossing-inset',
'cluster-stop-line-offset',
'junction-cutback',
@@ -56,6 +57,7 @@ const KINDS = [
'cluster-carriageway-direction',
'cluster-carriageway-edge-offset',
'cluster-corner-radius',
'cluster-island-offset',
'cluster-crossing-inset',
'cluster-stop-line-offset',
'junction-cutback',
@@ -285,6 +287,12 @@ function clusterCenter(model, cluster) {
return points.reduce((sum, point) => [sum[0] + point[0] / points.length, sum[1] + point[1] / points.length], [0, 0]);
}
function azimuthBetween(from, to) {
const east = (to[0] - from[0]) * 111320 * Math.cos((from[1] * Math.PI) / 180);
const north = (to[1] - from[1]) * 111320;
return ((Math.atan2(east, north) * 180) / Math.PI + 360) % 360;
}
function clusterRadiusPoint(line, center, radius) {
if (!center || !line.length) return null;
const length = polylineLength(line);
@@ -532,7 +540,7 @@ function reconcileConstraints(model, constraints, base, junctionData, context) {
if (versionChanged) return { ...constraint, status: 'recheck' };
return constraint;
}
if (constraint.kind === 'cluster-corner-radius') {
if (constraint.kind === 'cluster-corner-radius' || constraint.kind === 'cluster-island-offset') {
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))
@@ -903,6 +911,7 @@ function solveConstraints(model, constraints, junctionData, diagnostics, cluster
const clusterDirections = new Map();
const clusterEdgeOffsets = new Map();
const clusterCorners = new Map();
const clusterIslandOffsets = new Map();
const clusterCrossings = new Map();
const clusterItems = clusterCarriageways(model, junctionData, clusters);
const states = [];
@@ -941,6 +950,7 @@ function solveConstraints(model, constraints, junctionData, diagnostics, cluster
const directionSnapshot = new Map([...clusterDirections].map(([key, value]) => [key, new Map(value)]));
const edgeSnapshot = new Map([...clusterEdgeOffsets].map(([key, value]) => [key, new Map(value)]));
const cornerSnapshot = new Map([...clusterCorners].map(([key, value]) => [key, new Map(value)]));
const islandOffsetSnapshot = new Map(clusterIslandOffsets);
const crossingClusterSnapshot = new Map([...clusterCrossings].map(([key, value]) => [key, new Map(value)]));
const junctionSnapshot = new Map(
[...junctionPlans].map(([key, plan]) => [
@@ -1053,6 +1063,24 @@ function solveConstraints(model, constraints, junctionData, diagnostics, cluster
clusterCorners.get(String(cluster.id)).set(String(constraint.anchor.cornerKey), radius);
applied = true;
}
} else if (constraint.kind === 'cluster-island-offset') {
const cluster = clusters.find((item) => String(item.id) === String(constraint.anchor?.clusterId));
const offset = Number(constraint.value?.offsetMeters);
const keys = constraint.anchor?.carriagewayKeys || [];
if (!cluster || !Number.isFinite(offset) || offset < 0 || offset > 8 || keys.length !== 2) {
blocking(
diagnostics,
constraint,
'direct-edit-cluster-island-offset-invalid',
'安全岛整体外移必须在 0 到 8 米之间。',
);
applied = false;
} else {
// A corner grip is only the gesture anchor. The stored value belongs to
// the cluster so any one of the four grips moves the complete island set.
clusterIslandOffsets.set(String(cluster.id), offset);
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(
@@ -1146,6 +1174,8 @@ function solveConstraints(model, constraints, junctionData, diagnostics, cluster
for (const [key, value] of edgeSnapshot) clusterEdgeOffsets.set(key, value);
clusterCorners.clear();
for (const [key, value] of cornerSnapshot) clusterCorners.set(key, value);
clusterIslandOffsets.clear();
for (const [key, value] of islandOffsetSnapshot) clusterIslandOffsets.set(key, value);
clusterCrossings.clear();
for (const [key, value] of crossingClusterSnapshot) clusterCrossings.set(key, value);
}
@@ -1163,6 +1193,7 @@ function solveConstraints(model, constraints, junctionData, diagnostics, cluster
clusterDirections,
clusterEdgeOffsets,
clusterCorners,
clusterIslandOffsets,
clusterCrossings,
states,
};
@@ -1795,6 +1826,51 @@ function makeClusterCornerHandles(model, junctionData, constraints, clusters) {
return handles;
}
function makeClusterIslandOffsetHandles(model, junctionData, constraints, clusters) {
const handles = [];
for (const [clusterId, items] of clusterCarriageways(model, junctionData, clusters)) {
const cluster = clusters.find((item) => String(item.id) === clusterId);
const center = clusterCenter(model, cluster);
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}`;
// There may be four visible grips, but this remains one cluster value.
// Reusing its id makes all grips display and edit the same draft.
const constraint = constraints
.filter(
(item) =>
item.enabled !== false &&
item.kind === 'cluster-island-offset' &&
item.anchor?.type === 'cluster-corner' &&
item.anchor.clusterId === clusterId,
)
.at(-1);
const firstPoint = clusterApproachLine(first.representative)[0];
const secondPoint = clusterApproachLine(second.representative)[0];
const position = [(firstPoint[0] + secondPoint[0]) / 2, (firstPoint[1] + secondPoint[1]) / 2];
handles.push({
handleId: `handle:cluster-island-offset:${cornerKey}`,
kind: 'cluster-island-offset',
anchor: {
type: 'cluster-corner',
clusterId,
cornerKey,
carriagewayKeys: [first.representative.key, second.representative.key],
},
position,
axisAzimuth: azimuthBetween(center, position),
value: { current: numericValue(constraint, 'offsetMeters', 0), min: 0, max: 8, unit: 'meter' },
...(constraint ? { constraintId: constraint.id } : {}),
affects: [`complex-junction:${clusterId}:islands`],
editable: true,
});
}
}
return handles;
}
function makeClusterCrossingHandles(model, junctionData, constraints, clusters) {
const handles = [];
const itemsByCluster = clusterCarriageways(model, junctionData, clusters);
@@ -1937,6 +2013,7 @@ function resolveDirectEditConstraints(model, editDocument = null, context = {})
...(clusterSelection ? [] : makeJunctionHandles(model || {}, junctionData, reconciled)),
...makeClusterCarriagewayHandles(model || {}, junctionData, reconciled, clusters),
...makeClusterCornerHandles(model || {}, junctionData, reconciled, clusters),
...makeClusterIslandOffsetHandles(model || {}, junctionData, reconciled, clusters),
...makeClusterCrossingHandles(model || {}, junctionData, reconciled, clusters),
...(clusterSelection ? [] : makeLaneManeuverHandles(model || {}, reconciled)),
],
@@ -1956,6 +2033,7 @@ function resolveDirectEditConstraints(model, editDocument = null, context = {})
clusterDirections: solved.clusterDirections,
clusterEdgeOffsets: solved.clusterEdgeOffsets,
clusterCorners: solved.clusterCorners,
clusterIslandOffsets: solved.clusterIslandOffsets,
clusterCrossings: solved.clusterCrossings,
laneManeuvers: solved.laneManeuvers,
handles,
+34 -32
View File
@@ -1,7 +1,5 @@
'use strict';
const { union } = require('./junction-polygon-ops');
function buildPedestrianIsland({ key, ring, crossingKeys, provenance = 'inferred' }) {
if (!key || !Array.isArray(ring) || ring.length < 4) return null;
const adjacentCrossings = [...new Set(crossingKeys || [])];
@@ -108,7 +106,7 @@ function crossingArcSupport(ring, halfWidth) {
module.exports.crossingArcSupport = crossingArcSupport;
// Solve three complete landings together. All coordinates are local metres.
// Quadratic connectors round the supporting triangle outside the green hexagon;
// Rounded supporting-triangle tips remain outside the green contact hexagon;
// the three contact segments themselves are never shortened by rounding.
function solveIslandContacts(firstSegment, secondSegment, thirdWidth, options = {}) {
const fail = (reason) => ({ status: 'infeasible', reason });
@@ -156,7 +154,11 @@ function solveIslandContacts(firstSegment, secondSegment, thirdWidth, options =
return fail('leg-length-exceeds-space');
const firstTip = add(corner, u, legLengths[0]),
secondTip = add(corner, v, legLengths[1]);
const thirdCenter = firstTip.map((value, i) => (value + secondTip[i]) / 2);
const tipCenter = firstTip.map((value, i) => (value + secondTip[i]) / 2);
// Move the landing toward the corner, leaving the tips on the supporting
// triangle. Bound the inset by the spare leg length so contacts remain inside.
const inset = Math.min(0.12, 0.35 * Math.min(1 - a / legLengths[0], 1 - b / legLengths[1]));
const thirdCenter = add(tipCenter, sub(corner, tipCenter), inset);
const thirdContact = [add(thirdCenter, tangent, -thirdWidth / 2), add(thirdCenter, tangent, thirdWidth / 2)];
let outward = [tangent[1], -tangent[0]];
if (dot(outward, sub(thirdCenter, corner)) < 0) outward = outward.map((value) => -value);
@@ -172,36 +174,36 @@ function solveIslandContacts(firstSegment, secondSegment, thirdWidth, options =
}, 0),
) / 2;
if (hexArea <= 1e-8) return fail('degenerate-contact-hexagon');
const ring = [];
const midpoint = (a, b) => a.map((value, axis) => (value + b[axis]) / 2);
// The hypotenuse must bow toward the right-angle vertex. The final inner
// roundover is pushed away from that vertex so the island does not intrude
// into the vehicle swept area behind the two perpendicular crossings.
const hypotenuseMidpoint = midpoint(contacts[1][1], contacts[2][0]);
const hypotenuseControl = hypotenuseMidpoint.map((value, axis) => value * 1.45 - corner[axis] * 0.45);
const innerMidpoint = midpoint(contacts[2][1], contacts[0][0]);
// Keep the right-angle roundover outside the crossing intersection. Its
// control point is deliberately beyond the contact chord, leaving the
// vehicle-side edge at least one crossing half-depth from the corner.
const innerControl = innerMidpoint.map((value, axis) => value * 4 - corner[axis] * 3);
const controls = [firstTip, hypotenuseControl, innerControl];
const steps = 16;
contacts.forEach((contact, index) => {
ring.push(...contact);
const start = contact[1],
end = contacts[(index + 1) % 3][0],
control = controls[index];
for (let step = 1; step < steps; step++) {
const t = step / steps;
ring.push(
start.map((value, axis) => (1 - t) ** 2 * value + 2 * t * (1 - t) * control[axis] + t ** 2 * end[axis]),
);
// Keep the two complete straight legs. Only their unused ends are rounded;
// the former six-endpoint outline discarded all three triangle vertices.
const radius = Math.min(0.45, length(sub(first[0], corner)) / 3, length(sub(second[0], corner)) / 3);
const firstTrim = Math.min(radius, (legLengths[0] - a) / 3);
const secondTrim = Math.min(radius, (legLengths[1] - b) / 3);
const nearFirst = add(corner, u, radius);
const nearSecond = add(corner, v, radius);
const tipFirst = add(firstTip, u, -firstTrim);
const tipSecond = add(secondTip, v, -secondTrim);
const ring = [nearFirst, ...first, tipFirst];
const cubic = (start, control1, control2, end) => {
for (let step = 1; step <= 16; step++) {
const t = step / 16, q = 1 - t;
ring.push(start.map((value, axis) =>
q ** 3 * value + 3 * q * q * t * control1[axis] +
3 * q * t * t * control2[axis] + t ** 3 * end[axis]));
}
});
ring.push(ring[0]);
};
// Tangents follow the leg at each tip and the full straight landing at the
// middle. Thus the long side bows inward without a kink at the third crossing.
const firstRun = length(sub(thirdContact[0], firstTip)) / 3;
const secondRun = length(sub(secondTip, thirdContact[1])) / 3;
cubic(tipFirst, firstTip, add(thirdContact[0], tangent, -firstRun), thirdContact[0]);
ring.push(thirdContact[1]);
cubic(thirdContact[1], add(thirdContact[1], tangent, secondRun), secondTip, tipSecond);
ring.push(second[1], second[0], nearSecond);
// A small right-angle roundover, independent of the contact-to-corner distance.
cubic(nearSecond, add(nearSecond, v, -radius * 0.55228475),
add(nearFirst, u, -radius * 0.55228475), nearFirst);
const greenRing = [...vertices, vertices[0]];
const merged = union(ring, greenRing);
if (merged.length === 1 && merged[0].length === 1) ring.splice(0, ring.length, ...merged[0][0]);
return {
status: 'solved',
reason: null,
+15
View File
@@ -0,0 +1,15 @@
'use strict';
// Pure geometry helpers for the cluster-level island drag. This module does
// not mutate compiler features; callers can validate the returned rings before
// publishing a preview.
function radialShift(center, islandCenter, distanceMeters) {
const scale = 111320 * Math.cos((center[1] * Math.PI) / 180);
const east = (islandCenter[0] - center[0]) * scale;
const north = (islandCenter[1] - center[1]) * 111320;
const length = Math.hypot(east, north);
if (!Number.isFinite(length) || length < 1e-9 || !Number.isFinite(distanceMeters)) return [0, 0];
return [(distanceMeters * east) / length / scale, (distanceMeters * north) / length / 111320];
}
module.exports = { radialShift };
+10 -1
View File
@@ -11,7 +11,16 @@ function solveComplexPavementRegion(parts, crossingRegions = []) {
const inputs = [...parts, ...crossingRegions].filter(
(ring) => Array.isArray(ring) && ring.length >= 4 && ring.every((point) => point?.every(Number.isFinite)),
);
const regions = union(...inputs.map((ring) => [ring]));
let regions;
try {
regions = union(...inputs.map((ring) => [ring]));
} catch (error) {
// A valid local edit must not make the whole preview endpoint fail merely
// because the third-party polygon assembler cannot order this irregular
// multi-arm input. The caller retains the structural pavement features and
// publishes an object-level diagnostic instead of a false unified surface.
return { status: 'unsupported', regions: [], inputCount: inputs.length, reason: error.message };
}
// Construction polygons can enclose unpaved pockets where approach,
// core and corner edges meet. Those pockets are the visible "holes" in a
// complex junction; they are not exclusion regions and must be paved.
+4
View File
@@ -20,6 +20,7 @@ const CONSTRAINT_ANCHORS = {
'cluster-carriageway-direction': 'cluster-carriageway',
'cluster-carriageway-edge-offset': 'cluster-carriageway',
'cluster-corner-radius': 'cluster-corner',
'cluster-island-offset': 'cluster-corner',
'cluster-crossing-inset': 'cluster-crossing',
'cluster-stop-line-offset': 'cluster-crossing',
'junction-cutback': 'junction-approach',
@@ -196,6 +197,9 @@ function validateValue(scope, kind, value) {
} else if (kind === 'junction-corner-radius' || kind === 'cluster-corner-radius') {
if (!isFiniteNumber(value.radiusMeters) || value.radiusMeters < 0)
fail(scope, 'value.radiusMeters', 'must be a non-negative number of meters');
} else if (kind === 'cluster-island-offset') {
if (!isFiniteNumber(value.offsetMeters) || value.offsetMeters < 0 || value.offsetMeters > 8)
fail(scope, 'value.offsetMeters', 'must be between 0 and 8 meters');
} else if (kind === 'junction-crosswalk-inset' || kind === 'cluster-crossing-inset') {
// How far the zebra sits back from the junction boundary. Negative would put
// it inside the intersection surface.
+24 -3
View File
@@ -809,6 +809,7 @@ function compileGeometry(model, overrides = { overrides: [] }, options = {}) {
boundaryGraph: complexApproachBoundaries.get(cluster.id)?.boundaryGraph,
exteriorSidewalks: sidewalks,
clusterCornerRadii: options.directEdit?.clusterCorners?.get(String(cluster.id)),
clusterIslandOffsetMeters: options.directEdit?.clusterIslandOffsets?.get(String(cluster.id)),
clusterCrossingControls: options.directEdit?.clusterCrossings?.get(String(cluster.id)),
});
features.push(...generated.features);
@@ -2666,9 +2667,29 @@ function compileConnectors(model, lanes, diagnostics, overrides, junctionPlans,
};
const replacements = [],
replacementMovements = [];
const pavement = unionPolygons(
...pavementFeatures.filter((f) => f.properties.cluster_id === cluster.id).map((f) => f.geometry.coordinates),
);
const clusterPavement = pavementFeatures
.filter((feature) => feature.properties.cluster_id === cluster.id)
.map((feature) => feature.geometry.coordinates);
let pavement;
try {
pavement = unionPolygons(...clusterPavement);
} catch (error) {
// Keep the edit preview available when a non-convex multi-arm pavement
// input defeats polygon-clipping's ring assembler. Individual structural
// regions are still a conservative connector bound: a route crossing an
// unjoined seam is deferred rather than emitted outside the road surface.
pavement = clusterPavement;
diagnostics.push(
diagnostic(
'warning',
`junction-cluster:${cluster.id}`,
[...nodes],
'complex-junction-connector-pavement-assembly-failed',
'车行轨迹铺装区域无法统一装配,已按结构区域逐段校验并延后无法验证的轨迹。',
null,
),
);
}
for (const route of routes.values()) {
const first = route[0],
+1
View File
@@ -257,6 +257,7 @@ test.describe('workbench editing shell', () => {
'cluster-carriageway-direction',
'cluster-carriageway-edge-offset',
'cluster-corner-radius',
'cluster-island-offset',
'cluster-crossing-inset',
'cluster-stop-line-offset',
].includes(handle.kind) && handle.editable,
+2 -1
View File
@@ -1,6 +1,7 @@
'use strict';
const assert = require('assert/strict');
const clipping = require('polygon-clipping');
const { buildPedestrianIsland, validateFacilityComposition } = require('../src/compile/junction-facility-composition');
const ring = [
@@ -24,7 +25,6 @@ console.log('junction facility composition tests passed');
// User's sketch: a horizontal crossing to the right, a vertical crossing down,
// and the island in the upper-left quadrant, bounded by doubled short edges.
const { buildIslandFromCrossingEdges } = require('../src/compile/junction-facility-composition');
const clipping = require('polygon-clipping');
const sketchIsland = buildIslandFromCrossingEdges([0, 0], [0, 6.8], [-6.8, 0]);
assert.deepEqual(sketchIsland[0], sketchIsland.at(-1));
assert.ok(sketchIsland.every(([x, y]) => x <= 0 && y >= 0));
@@ -167,6 +167,7 @@ assert.equal(extendedContacts.status, 'solved');
assert.ok(extendedContacts.legLengths.every((value) => value >= 9));
assert.equal(new Set(solvedContacts.greenRing.slice(0, -1).map((p) => p.join(','))).size, 6);
assert.equal(clipping.difference([solvedContacts.greenRing], [solvedContacts.ring]).length, 0);
// Regression: the saved four-node, 21m cluster previously lost two islands.
{
+104
View File
@@ -0,0 +1,104 @@
'use strict';
const assert = require('assert/strict');
const { radialShift } = require('../src/compile/junction-island-offset');
const center = [114, 30];
const islandCenter = [114.0001, 30.0001];
const shift = radialShift(center, islandCenter, 2);
assert.ok(Math.hypot(shift[0] * 111320 * Math.cos((center[1] * Math.PI) / 180), shift[1] * 111320) > 1.99);
// Real four-arm integration: the compiler receives one cluster value but moves
// all four islands and their linked arm crossings in the same compilation pass.
{
const fs = require('fs');
const path = require('path');
const { compileRoadModel, compileGeometry } = require('../src/compile/native-road');
const cluster = {
id: 'offset-four-arm',
template: 'complex-junction-v1',
coreRadiusMeters: 21,
nodeIds: ['8005332807', '8024512135', '8024512145', '8024512147'],
};
const model = compileRoadModel(fs.readFileSync(path.join(__dirname, '../inputs/osm/枫树二路.osm'), 'utf8'), {
overrides: [],
});
const options = { edgeLines: false, junctionTemplates: { enabled: true, clusters: [cluster] } };
const base = compileGeometry(model, { overrides: [] }, options);
const shifted = compileGeometry(
model,
{ overrides: [] },
{
...options,
directEdit: { clusterIslandOffsets: new Map([[cluster.id, 2]]) },
},
);
const byKind = (geometry, kind) =>
geometry.sidewalkSurface.features.filter((feature) => feature.properties.kind === kind);
const baseIslands = byKind(base, 'island');
const shiftedIslands = byKind(shifted, 'island');
assert.equal(baseIslands.length, 4);
assert.equal(shiftedIslands.length, 4);
for (const island of shiftedIslands) {
const original = baseIslands.find((feature) => feature.properties.corner_key === island.properties.corner_key);
assert.notDeepEqual(island.geometry.coordinates, original.geometry.coordinates, 'each island must move');
}
const baseCrosswalks = base.crosswalks.features.filter((feature) => feature.properties.kind === 'complex-crosswalk');
const shiftedCrosswalks = shifted.crosswalks.features.filter(
(feature) => feature.properties.kind === 'complex-crosswalk',
);
assert.equal(shiftedCrosswalks.length, baseCrosswalks.length);
assert.ok(
shiftedCrosswalks.some(
(feature, index) =>
JSON.stringify(feature.geometry.coordinates) !== JSON.stringify(baseCrosswalks[index].geometry.coordinates),
),
'linked arm crossings must be rebuilt with the islands',
);
const baseStops = base.vehicleStopLines.features.filter((feature) => feature.properties.kind === 'complex-stop-line');
const shiftedStops = shifted.vehicleStopLines.features.filter(
(feature) => feature.properties.kind === 'complex-stop-line',
);
assert.ok(
shiftedStops.some(
(feature, index) =>
JSON.stringify(feature.geometry.coordinates) !== JSON.stringify(baseStops[index].geometry.coordinates),
),
'stop lines must retain their spacing from moved arm crossings',
);
const allStripeVertices = shifted.crosswalks.features.flatMap((feature) => feature.geometry.coordinates[0]);
const metersBetween = (a, b) =>
Math.hypot((a[0] - b[0]) * 111320 * Math.cos((a[1] * Math.PI) / 180), (a[1] - b[1]) * 111320);
for (const green of byKind(shifted, 'island-green')) {
for (const contactPoint of green.geometry.coordinates[0].slice(0, -1))
assert.ok(
Math.min(...allStripeVertices.map((vertex) => metersBetween(contactPoint, vertex))) < 0.01,
'each green contact endpoint must remain on a linked crossing after the offset',
);
}
const local = (point) => [
(point[0] - 114.1229) * 111320 * Math.cos((point[1] * Math.PI) / 180),
(point[1] - 30.4629) * 111320,
];
const cross = (a, b, c) => (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
const properIntersection = (a, b, c, d) => {
const ab = cross(a, b, c) * cross(a, b, d);
const cd = cross(c, d, a) * cross(c, d, b);
return ab < -1e-8 && cd < -1e-8;
};
const islandEdges = shiftedIslands.flatMap((island) =>
island.geometry.coordinates[0]
.slice(1)
.map((point, index) => [local(island.geometry.coordinates[0][index]), local(point)]),
);
const laneSegments = shifted.laneCenterlines.features.flatMap((feature) => {
const coordinates = feature.geometry.type === 'LineString' ? feature.geometry.coordinates : [];
return coordinates.slice(1).map((point, index) => [local(coordinates[index]), local(point)]);
});
assert.equal(
laneSegments.some(([a, b]) => islandEdges.some(([c, d]) => properIntersection(a, b, c, d))),
false,
'the shifted island boundary must stay outside vehicle lane centre lines',
);
}
console.log('junction island offset tests passed');
+26
View File
@@ -64,4 +64,30 @@ for (const [name, nodeIds] of Object.entries({
`${name} ${stripe.properties.native_id} must lie on the unified pavement`,
);
}
// A valid five-arm corner-radius edit used to let polygon-clipping throw while
// assembling connector pavement, aborting the entire preview. It must instead
// retain the changed structural pavement and defer only unverifiable routes.
{
const cluster = {
id: 'five-arm-pavement-assembly',
template: 'complex-junction-v1',
coreRadiusMeters: 32,
nodeIds: ['8005332807', '8024512135', '8024512145', '8024512147', '8613058676'],
};
const options = { edgeLines: false, junctionTemplates: { enabled: true, clusters: [cluster] } };
const baseline = compileGeometry(model, { overrides: [] }, options);
const cornerKeys = baseline.roadSurface.features
.filter((feature) => feature.properties.kind === 'complex-corner-fillet')
.map((feature) => feature.properties.corner_key);
const edited = compileGeometry(
model,
{ overrides: [] },
{
...options,
directEdit: { clusterCorners: new Map([[cluster.id, new Map(cornerKeys.map((key) => [key, 14]))]]) },
},
);
assert.ok(edited.roadSurface.features.some((feature) => feature.properties.kind === 'complex-corner-fillet'));
}
console.log('junction pavement region tests passed');
+3
View File
@@ -78,6 +78,8 @@ function valueFor(kind) {
return { leftOffsetMeters: 0.5, rightOffsetMeters: 0 };
case 'cluster-corner-radius':
return { radiusMeters: 6 };
case 'cluster-island-offset':
return { offsetMeters: 2 };
case 'cluster-crossing-inset':
return { insetMeters: 1.5 };
case 'cluster-stop-line-offset':
@@ -149,6 +151,7 @@ assert.deepEqual(CONSTRAINT_KINDS, [
'cluster-carriageway-direction',
'cluster-carriageway-edge-offset',
'cluster-corner-radius',
'cluster-island-offset',
'cluster-crossing-inset',
'cluster-stop-line-offset',
'junction-cutback',
+1
View File
@@ -342,6 +342,7 @@ assert.ok(
'cluster-carriageway-direction',
'cluster-carriageway-edge-offset',
'cluster-corner-radius',
'cluster-island-offset',
'cluster-crossing-inset',
'cluster-stop-line-offset',
].includes(handle.kind),
+1
View File
@@ -274,6 +274,7 @@ function App() {
handle.kind === 'cluster-carriageway-direction' ||
handle.kind === 'cluster-carriageway-edge-offset' ||
handle.kind === 'cluster-corner-radius' ||
handle.kind === 'cluster-island-offset' ||
handle.kind === 'cluster-crossing-inset' ||
handle.kind === 'cluster-stop-line-offset') &&
'clusterId' in handle.anchor &&
+1
View File
@@ -120,6 +120,7 @@ const KIND_LABELS: Record<ConstraintKind, string> = {
'cluster-carriageway-direction': '车行道接入方向',
'cluster-carriageway-edge-offset': '车行道左右边界',
'cluster-corner-radius': '角部圆角',
'cluster-island-offset': '安全岛整体外移',
'cluster-crossing-inset': '斑马线退让',
'cluster-stop-line-offset': '停止线偏移',
'junction-cutback': '进口收口距离',
+2
View File
@@ -131,6 +131,8 @@ export function constraintValueFor(
: { leftOffsetMeters: scalar, rightOffsetMeters: 0 };
case 'cluster-corner-radius':
return { radiusMeters: Math.max(0, scalar) };
case 'cluster-island-offset':
return { offsetMeters: Math.max(0, scalar) };
case 'junction-cutback':
return { cutbackMeters: Math.max(0, scalar) };
case 'junction-corner-radius':
+2
View File
@@ -38,6 +38,7 @@ export const JUNCTION_KINDS = [
'cluster-carriageway-direction',
'cluster-carriageway-edge-offset',
'cluster-corner-radius',
'cluster-island-offset',
'junction-cutback',
'junction-corner-radius',
...CONTROL_KINDS,
@@ -135,6 +136,7 @@ export type ConstraintValue =
| { cutbackMeters: number }
| { transitionLengthMeters: number }
| { radiusMeters: number }
| { offsetMeters: number }
| { insetMeters: number }
| { offsetDegrees: number }
| { leftOffsetMeters: number; rightOffsetMeters: number };