diff --git a/.trellis/tasks/09-08-junction-reference-fidelity/artifacts/island-shape-four-arm.png b/.trellis/tasks/09-08-junction-reference-fidelity/artifacts/island-shape-four-arm.png
new file mode 100644
index 0000000..fbf6447
Binary files /dev/null and b/.trellis/tasks/09-08-junction-reference-fidelity/artifacts/island-shape-four-arm.png differ
diff --git a/.trellis/tasks/09-08-junction-reference-fidelity/artifacts/island-shape-four-arm.svg b/.trellis/tasks/09-08-junction-reference-fidelity/artifacts/island-shape-four-arm.svg
new file mode 100644
index 0000000..82b7d43
--- /dev/null
+++ b/.trellis/tasks/09-08-junction-reference-fidelity/artifacts/island-shape-four-arm.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/src/compile/complex-junction.js b/src/compile/complex-junction.js
index ff5f04c..b4c272a 100644
--- a/src/compile/complex-junction.js
+++ b/src/compile/complex-junction.js
@@ -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,
diff --git a/src/compile/direct-edit-solver.js b/src/compile/direct-edit-solver.js
index 14679a1..35c6cf9 100644
--- a/src/compile/direct-edit-solver.js
+++ b/src/compile/direct-edit-solver.js
@@ -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,
diff --git a/src/compile/junction-facility-composition.js b/src/compile/junction-facility-composition.js
index 63789c5..d510858 100644
--- a/src/compile/junction-facility-composition.js
+++ b/src/compile/junction-facility-composition.js
@@ -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,
diff --git a/src/compile/junction-island-offset.js b/src/compile/junction-island-offset.js
new file mode 100644
index 0000000..8fa1628
--- /dev/null
+++ b/src/compile/junction-island-offset.js
@@ -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 };
diff --git a/src/compile/junction-pavement-region.js b/src/compile/junction-pavement-region.js
index c167b38..f2c7032 100644
--- a/src/compile/junction-pavement-region.js
+++ b/src/compile/junction-pavement-region.js
@@ -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.
diff --git a/src/compile/native-road-edits.js b/src/compile/native-road-edits.js
index 01a0751..fd6d5f9 100644
--- a/src/compile/native-road-edits.js
+++ b/src/compile/native-road-edits.js
@@ -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.
diff --git a/src/compile/native-road.js b/src/compile/native-road.js
index 8c23217..2263842 100644
--- a/src/compile/native-road.js
+++ b/src/compile/native-road.js
@@ -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],
diff --git a/test/e2e/workbench.spec.ts b/test/e2e/workbench.spec.ts
index 6aca168..24e8c25 100644
--- a/test/e2e/workbench.spec.ts
+++ b/test/e2e/workbench.spec.ts
@@ -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,
diff --git a/test/junction-facility-composition.js b/test/junction-facility-composition.js
index bf34317..b62bc39 100644
--- a/test/junction-facility-composition.js
+++ b/test/junction-facility-composition.js
@@ -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.
{
diff --git a/test/junction-island-offset.js b/test/junction-island-offset.js
new file mode 100644
index 0000000..4b2df14
--- /dev/null
+++ b/test/junction-island-offset.js
@@ -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');
diff --git a/test/junction-pavement-region.js b/test/junction-pavement-region.js
index 648c5d2..439af65 100644
--- a/test/junction-pavement-region.js
+++ b/test/junction-pavement-region.js
@@ -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');
diff --git a/test/native-road-edits.js b/test/native-road-edits.js
index f360c01..e796c94 100644
--- a/test/native-road-edits.js
+++ b/test/native-road-edits.js
@@ -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',
diff --git a/test/workbench-edit-api.js b/test/workbench-edit-api.js
index bdd5b8e..b51243b 100644
--- a/test/workbench-edit-api.js
+++ b/test/workbench-edit-api.js
@@ -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),
diff --git a/workbench/client/src/App.tsx b/workbench/client/src/App.tsx
index 917e9f1..0ad6565 100644
--- a/workbench/client/src/App.tsx
+++ b/workbench/client/src/App.tsx
@@ -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 &&
diff --git a/workbench/client/src/edit/parameter.ts b/workbench/client/src/edit/parameter.ts
index b25b2c0..7f8bca9 100644
--- a/workbench/client/src/edit/parameter.ts
+++ b/workbench/client/src/edit/parameter.ts
@@ -120,6 +120,7 @@ const KIND_LABELS: Record = {
'cluster-carriageway-direction': '车行道接入方向',
'cluster-carriageway-edge-offset': '车行道左右边界',
'cluster-corner-radius': '角部圆角',
+ 'cluster-island-offset': '安全岛整体外移',
'cluster-crossing-inset': '斑马线退让',
'cluster-stop-line-offset': '停止线偏移',
'junction-cutback': '进口收口距离',
diff --git a/workbench/client/src/edit/projection.ts b/workbench/client/src/edit/projection.ts
index 3444474..d4eaa10 100644
--- a/workbench/client/src/edit/projection.ts
+++ b/workbench/client/src/edit/projection.ts
@@ -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':
diff --git a/workbench/client/src/edit/types.ts b/workbench/client/src/edit/types.ts
index 817b1a1..3d8abc8 100644
--- a/workbench/client/src/edit/types.ts
+++ b/workbench/client/src/edit/types.ts
@@ -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 };