feat: refine complex junction geometry and workbench

This commit is contained in:
que01 committed 2026-09-23 17:55:55 +08:00
1 parent 7c04d086db
commit 05614d1a69
20 files changed
+315 -267

No files matched your search

+3 -1
View File
@@ -11,4 +11,6 @@ const inputFile = index >= 0 && args[index + 1] ? path.resolve(args[index + 1])
const input = inputFile ? JSON.parse(fs.readFileSync(inputFile, 'utf8')) : null; const input = inputFile ? JSON.parse(fs.readFileSync(inputFile, 'utf8')) : null;
const portIndex = args.indexOf('--port'); const portIndex = args.indexOf('--port');
const port = portIndex >= 0 ? Number(args[portIndex + 1]) : 8787; const port = portIndex >= 0 ? Number(args[portIndex + 1]) : 8787;
startWorkbench({ input, inputFile, repoRoot: path.resolve(__dirname, '..'), port, debug: args.includes('--debug') }); // Keep the diagnostic read model enabled by default. Use --no-debug only when
// running a minimal production-like session.
startWorkbench({ input, inputFile, repoRoot: path.resolve(__dirname, '..'), port, debug: !args.includes('--no-debug') });
+1 -1
View File
@@ -10,7 +10,7 @@
"scripts": { "scripts": {
"test": "node test/index.js && node test/junction-structure.js && node test/connector-trajectories.js && node test/junction-projection.js && node test/junction-build-plan-counterexamples.js && node test/junction-polygon-ops.js && node test/junction-region-solver.js && node test/junction-facility-composition.js && node test/junction-pavement-region.js && node test/junction-marking-containment.js && node test/junction-corridor-markings.js && node test/junction-layer-seams.js && node test/native-road-edits.js && node test/road-revisions.js && node test/direct-edit-solver.js && node test/workbench-edit-api.js && node test/workbench-import-compile.js && node test/fixtures.js", "test": "node test/index.js && node test/junction-structure.js && node test/connector-trajectories.js && node test/junction-projection.js && node test/junction-build-plan-counterexamples.js && node test/junction-polygon-ops.js && node test/junction-region-solver.js && node test/junction-facility-composition.js && node test/junction-pavement-region.js && node test/junction-marking-containment.js && node test/junction-corridor-markings.js && node test/junction-layer-seams.js && node test/native-road-edits.js && node test/road-revisions.js && node test/direct-edit-solver.js && node test/workbench-edit-api.js && node test/workbench-import-compile.js && node test/fixtures.js",
"test:fixtures:update-baseline": "node test/update-fixture-baselines.js", "test:fixtures:update-baseline": "node test/update-fixture-baselines.js",
"road:workbench": "node bin/road-workbench.js", "road:workbench": "npm run build && node bin/road-workbench.js",
"road:export": "node bin/road-compiler.js", "road:export": "node bin/road-compiler.js",
"build": "vite build --config workbench/client/vite.config.ts", "build": "vite build --config workbench/client/vite.config.ts",
"dev": "vite --config workbench/client/vite.config.ts", "dev": "vite --config workbench/client/vite.config.ts",
+4 -3
View File
@@ -5,6 +5,7 @@ const { ringsOverlap } = require('./junction-boundary-graph');
const { rectangle } = require('./junction-pavement-region'); const { rectangle } = require('./junction-pavement-region');
const { orthogonalCrossingHeadings, stripeLayout, solveIslandContacts } = require('./junction-facility-composition'); const { orthogonalCrossingHeadings, stripeLayout, solveIslandContacts } = require('./junction-facility-composition');
const { radialShift } = require('./junction-island-offset'); const { radialShift } = require('./junction-island-offset');
const { METERS_PER_DEGREE, metersAt } = require('../geometry/metric');
const { const {
armCarriesSidewalk, armCarriesSidewalk,
armEnvelopeAtRadius, armEnvelopeAtRadius,
@@ -625,9 +626,9 @@ function solveCornerContacts({
center, center,
); );
if (!crossingCorner) return null; if (!crossingCorner) return null;
const lonScale = 111320 * Math.cos((crossingCorner[1] * Math.PI) / 180); const { lon } = metersAt(crossingCorner[1]);
const toLocal = (point) => [(point[0] - crossingCorner[0]) * lonScale, (point[1] - crossingCorner[1]) * 111320]; const toLocal = (point) => [(point[0] - crossingCorner[0]) * lon, (point[1] - crossingCorner[1]) * METERS_PER_DEGREE];
const fromLocal = (point) => [crossingCorner[0] + point[0] / lonScale, crossingCorner[1] + point[1] / 111320]; const fromLocal = (point) => [crossingCorner[0] + point[0] / lon, crossingCorner[1] + point[1] / METERS_PER_DEGREE];
const landing = (arm, endpoint) => { const landing = (arm, endpoint) => {
const frame = arm.crosswalkFrame; const frame = arm.crosswalkFrame;
const layout = stripeLayout(frame.spanMeters); const layout = stripeLayout(frame.spanMeters);
+16 -32
View File
@@ -1,6 +1,13 @@
'use strict'; 'use strict';
const { stationAtDistanceFrom } = require('./junction-build-plan'); const { stationAtDistanceFrom } = require('./junction-build-plan');
const {
METERS_PER_DEGREE,
averageHeading,
headingDegrees: bearing,
metersAt,
signedLateralMeters,
} = require('../geometry/metric');
function normalizeHeading(value) { function normalizeHeading(value) {
return ((((value + 180) % 360) + 360) % 360) - 180; return ((((value + 180) % 360) + 360) % 360) - 180;
@@ -78,34 +85,10 @@ function angleAround(center, point) {
return Math.atan2(point[1] - center[1], point[0] - center[0]); return Math.atan2(point[1] - center[1], point[0] - center[0]);
} }
function signedLateralMeters(origin, point, heading) {
const east = (point[0] - origin[0]) * 111320 * Math.cos((origin[1] * Math.PI) / 180);
const north = (point[1] - origin[1]) * 111320;
const radians = ((heading + 90) * Math.PI) / 180;
return east * Math.sin(radians) + north * Math.cos(radians);
}
function bearing(first, second) {
const east = (second[0] - first[0]) * Math.cos((first[1] * Math.PI) / 180);
const north = second[1] - first[1];
return (Math.atan2(east, north) * 180) / Math.PI;
}
function midpoint(first, second) { function midpoint(first, second) {
return [(first[0] + second[0]) / 2, (first[1] + second[1]) / 2]; return [(first[0] + second[0]) / 2, (first[1] + second[1]) / 2];
} }
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;
}
function positiveHeadingDelta(first, second) { function positiveHeadingDelta(first, second) {
return (((second - first) % 360) + 360) % 360; return (((second - first) % 360) + 360) % 360;
} }
@@ -183,8 +166,8 @@ function cornerEdgeAt(arm, radius, bisector, center, helpers) {
} }
function rayIntersection(first, second, origin) { function rayIntersection(first, second, origin) {
const lonScale = 111320 * Math.cos((origin[1] * Math.PI) / 180); const { lon } = metersAt(origin[1]);
const toLocal = (point) => [(point[0] - origin[0]) * lonScale, (point[1] - origin[1]) * 111320]; const toLocal = (point) => [(point[0] - origin[0]) * lon, (point[1] - origin[1]) * METERS_PER_DEGREE];
const direction = (heading) => { const direction = (heading) => {
const radians = (heading * Math.PI) / 180; const radians = (heading * Math.PI) / 180;
return [Math.sin(radians), Math.cos(radians)]; return [Math.sin(radians), Math.cos(radians)];
@@ -202,7 +185,7 @@ function rayIntersection(first, second, origin) {
firstPoint[1] + firstDirection[1] * distanceAlongFirst, firstPoint[1] + firstDirection[1] * distanceAlongFirst,
]; ];
if (!local.every(Number.isFinite)) return null; if (!local.every(Number.isFinite)) return null;
return [origin[0] + local[0] / lonScale, origin[1] + local[1] / 111320]; return [origin[0] + local[0] / lon, origin[1] + local[1] / METERS_PER_DEGREE];
} }
function quadraticCurve(start, control, end, segments) { function quadraticCurve(start, control, end, segments) {
@@ -219,8 +202,9 @@ function quadraticCurve(start, control, end, segments) {
} }
function directionalProjectionMeters(origin, point, heading) { function directionalProjectionMeters(origin, point, heading) {
const east = (point[0] - origin[0]) * 111320 * Math.cos((origin[1] * Math.PI) / 180); const { lon, lat } = metersAt(origin[1]);
const north = (point[1] - origin[1]) * 111320; const east = (point[0] - origin[0]) * lon;
const north = (point[1] - origin[1]) * lat;
const radians = (heading * Math.PI) / 180; const radians = (heading * Math.PI) / 180;
return east * Math.sin(radians) + north * Math.cos(radians); return east * Math.sin(radians) + north * Math.cos(radians);
} }
@@ -231,9 +215,9 @@ function polygonCenter(ring) {
} }
function projectionRatio(point, start, end) { function projectionRatio(point, start, end) {
const lonScale = 111320 * Math.cos((start[1] * Math.PI) / 180); const { lon, lat } = metersAt(start[1]);
const vector = [(end[0] - start[0]) * lonScale, (end[1] - start[1]) * 111320]; const vector = [(end[0] - start[0]) * lon, (end[1] - start[1]) * lat];
const relative = [(point[0] - start[0]) * lonScale, (point[1] - start[1]) * 111320]; const relative = [(point[0] - start[0]) * lon, (point[1] - start[1]) * lat];
const lengthSquared = vector[0] * vector[0] + vector[1] * vector[1]; const lengthSquared = vector[0] * vector[0] + vector[1] * vector[1];
if (lengthSquared < 1e-12) return 0; if (lengthSquared < 1e-12) return 0;
return Math.max(0, Math.min(1, (relative[0] * vector[0] + relative[1] * vector[1]) / lengthSquared)); return Math.max(0, Math.min(1, (relative[0] * vector[0] + relative[1] * vector[1]) / lengthSquared));
+4 -3
View File
@@ -8,6 +8,7 @@ const { rectangle } = require('./junction-pavement-region');
const { assemblePavementSurfaces } = require('./complex-junction-surfaces'); const { assemblePavementSurfaces } = require('./complex-junction-surfaces');
const { complexJunctionMetrics: calculateComplexJunctionMetrics } = require('./junction-metrics'); const { complexJunctionMetrics: calculateComplexJunctionMetrics } = require('./junction-metrics');
const { convertGeoJson, boundsOf } = require('../reference/gaode'); const { convertGeoJson, boundsOf } = require('../reference/gaode');
const { metersAt } = require('../geometry/metric');
const { normalizeHeading, positiveHeadingDelta } = require('./complex-junction-geometry'); const { normalizeHeading, positiveHeadingDelta } = require('./complex-junction-geometry');
const { const {
applyCrossingDisplacements, applyCrossingDisplacements,
@@ -341,10 +342,10 @@ function readReferenceCalibration(cluster) {
const bounds = boundsOf({ const bounds = boundsOf({
features: converted.features.filter((feature) => [1, 2, 3, 4].includes(Number(feature.properties?.type))), features: converted.features.filter((feature) => [1, 2, 3, 4].includes(Number(feature.properties?.type))),
}); });
const lonScale = 111320 * Math.cos((((bounds.minLat + bounds.maxLat) / 2) * Math.PI) / 180); const { lon, lat } = metersAt((bounds.minLat + bounds.maxLat) / 2);
return { return {
longSpanMeters: (bounds.maxLon - bounds.minLon) * lonScale, longSpanMeters: (bounds.maxLon - bounds.minLon) * lon,
shortSpanMeters: (bounds.maxLat - bounds.minLat) * 111320, shortSpanMeters: (bounds.maxLat - bounds.minLat) * lat,
}; };
} catch (_) { } catch (_) {
return null; return null;
+1 -12
View File
@@ -22,18 +22,7 @@ const MAX_APPROACH_DISTANCE_METERS = 25;
/** How far an inset may pull the crosswalk from its natural spot. */ /** How far an inset may pull the crosswalk from its natural spot. */
const MAX_JUNCTION_INSET_METERS = 4; const MAX_JUNCTION_INSET_METERS = 4;
const EARTH_RADIUS_METERS = 6371008.8; const { distanceMeters } = require('../geometry/metric');
const toRadians = (degrees) => (degrees * Math.PI) / 180;
function distanceMeters(a, b) {
if (!Array.isArray(a) || !Array.isArray(b)) return Infinity;
const lat1 = toRadians(a[1]);
const lat2 = toRadians(b[1]);
const h =
Math.sin(toRadians(b[1] - a[1]) / 2) ** 2 +
Math.cos(lat1) * Math.cos(lat2) * Math.sin(toRadians(b[0] - a[0]) / 2) ** 2;
return 2 * EARTH_RADIUS_METERS * Math.asin(Math.min(1, Math.sqrt(h)));
}
/** Endpoints that a connection arrives at, i.e. roads that end in a junction. */ /** Endpoints that a connection arrives at, i.e. roads that end in a junction. */
function arrivalEndpointIds(model) { function arrivalEndpointIds(model) {
+6 -40
View File
@@ -7,6 +7,7 @@ const { COMPLEX_CROSSWALK_DEPTH_METERS } = require('./junction-metrics');
const { diagnostic } = require('./diagnostics'); const { diagnostic } = require('./diagnostics');
const { approachForCrossing, arrivalEndpointIds, effectiveCrosswalkInsetMax } = require('./crossing-approach'); const { approachForCrossing, arrivalEndpointIds, effectiveCrosswalkInsetMax } = require('./crossing-approach');
const { haversineMeters, metersAt, polylineLength } = require('../geometry/lane-geometry'); const { haversineMeters, metersAt, polylineLength } = require('../geometry/lane-geometry');
const { offsetCoordinate, signedLateralMeters } = require('../geometry/metric');
const { const {
roadSurfaceId, roadSurfaceId,
sidewalkId, sidewalkId,
@@ -45,28 +46,9 @@ const SOLVED_KINDS = new Set([
'junction-stop-line-offset', 'junction-stop-line-offset',
'lane-maneuver', 'lane-maneuver',
]); ]);
const KINDS = [ // Set iteration order is insertion order, so this is the same list as the
'road-edge-offset', // literal above — one source of truth instead of two copies that can drift.
'road-sidewalk-width', const KINDS = [...SOLVED_KINDS];
'road-lane-divider',
'junction-approach-width',
'cluster-carriageway-width',
'cluster-carriageway-cutback',
'cluster-carriageway-transition-length',
'cluster-carriageway-position',
'cluster-carriageway-direction',
'cluster-carriageway-edge-offset',
'cluster-corner-radius',
'cluster-island-offset',
'cluster-crossing-inset',
'cluster-stop-line-offset',
'junction-cutback',
'junction-corner-radius',
'junction-crosswalk-inset',
'junction-crosswalk-size',
'junction-stop-line-offset',
'lane-maneuver',
];
const SUPPORTED_MANEUVERS = new Set([ const SUPPORTED_MANEUVERS = new Set([
'', '',
'through', 'through',
@@ -153,15 +135,6 @@ function tangentAzimuth(line, station) {
return ((Math.atan2(dx, dy) * 180) / Math.PI + 360) % 360; return ((Math.atan2(dx, dy) * 180) / Math.PI + 360) % 360;
} }
function offsetCoordinate(point, azimuth, meters) {
const radians = (azimuth * Math.PI) / 180;
const latitudeScale = metersAt(point[1]).lon;
return [
point[0] + (Math.sin(radians) * meters) / Math.max(latitudeScale, 1e-9),
point[1] + (Math.cos(radians) * meters) / 111320,
];
}
function constraintFor(constraints, kind, anchor) { function constraintFor(constraints, kind, anchor) {
return constraints.find((item) => { return constraints.find((item) => {
if (item.kind !== kind || !item.anchor || item.enabled === false) return false; if (item.kind !== kind || !item.anchor || item.enabled === false) return false;
@@ -288,8 +261,8 @@ function clusterCenter(model, cluster) {
} }
function azimuthBetween(from, to) { function azimuthBetween(from, to) {
const east = (to[0] - from[0]) * 111320 * Math.cos((from[1] * Math.PI) / 180); const east = (to[0] - from[0]) * metersAt(from[1]).lon;
const north = (to[1] - from[1]) * 111320; const north = (to[1] - from[1]) * metersAt(from[1]).lat;
return ((Math.atan2(east, north) * 180) / Math.PI + 360) % 360; return ((Math.atan2(east, north) * 180) / Math.PI + 360) % 360;
} }
@@ -301,13 +274,6 @@ function clusterRadiusPoint(line, center, radius) {
return coordinateAt(line, Math.max(0, Math.min(1, station / length))); return coordinateAt(line, Math.max(0, Math.min(1, station / length)));
} }
function signedLateralMeters(origin, point, heading) {
const east = (point[0] - origin[0]) * 111320 * Math.cos((origin[1] * Math.PI) / 180);
const north = (point[1] - origin[1]) * 111320;
const radians = ((heading + 90) * Math.PI) / 180;
return east * Math.sin(radians) + north * Math.cos(radians);
}
function clusterArmRadiusPoint(arm, center, radius) { function clusterArmRadiusPoint(arm, center, radius) {
const points = arm.members const points = arm.members
.map((member) => ({ member, point: clusterRadiusPoint(clusterApproachLine(member), center, radius) })) .map((member) => ({ member, point: clusterRadiusPoint(clusterApproachLine(member), center, radius) }))
+7 -16
View File
@@ -6,6 +6,8 @@ const { solvePavedRegion } = require('./junction-region-solver');
const { stationAtDistanceFrom } = require('./junction-build-plan'); const { stationAtDistanceFrom } = require('./junction-build-plan');
const { offsetCoordinate, metersAt } = require('../geometry/metric');
function pointAtStation(line, station, helpers) { function pointAtStation(line, station, helpers) {
let remaining = Math.max(0, station); let remaining = Math.max(0, station);
for (let index = 1; index < line.length; index += 1) { for (let index = 1; index < line.length; index += 1) {
@@ -33,16 +35,6 @@ function tangentAtStation(line, station, helpers) {
return null; return null;
} }
function offsetCoordinate(point, heading, meters) {
if (!point || !Number.isFinite(heading)) return null;
const radians = (heading * Math.PI) / 180;
const lonMeters = 111320 * Math.cos((point[1] * Math.PI) / 180);
return [
point[0] + (Math.sin(radians) * meters) / Math.max(lonMeters, 1e-9),
point[1] + (Math.cos(radians) * meters) / 111320,
];
}
function sectionAt(item, radius, center, widthMeters, helpers, explicitStation, edgeOffsets = null) { function sectionAt(item, radius, center, widthMeters, helpers, explicitStation, edgeOffsets = null) {
const station = Math.max( const station = Math.max(
0, 0,
@@ -211,10 +203,9 @@ function ringsOverlap(first, second) {
function coordinateDistanceMeters(first, second) { function coordinateDistanceMeters(first, second) {
if (!first?.every(Number.isFinite) || !second?.every(Number.isFinite)) return Infinity; if (!first?.every(Number.isFinite) || !second?.every(Number.isFinite)) return Infinity;
const radians = Math.PI / 180; const { lon, lat } = metersAt((first[1] + second[1]) / 2);
const latitude = ((first[1] + second[1]) / 2) * radians; const east = (second[0] - first[0]) * lon;
const east = (second[0] - first[0]) * 111320 * Math.cos(latitude); const north = (second[1] - first[1]) * lat;
const north = (second[1] - first[1]) * 111320;
return Math.hypot(east, north); return Math.hypot(east, north);
} }
@@ -223,8 +214,8 @@ function coordinateDistanceMeters(first, second) {
// every remaining edge is an explicit closure between adjacent arms. // every remaining edge is an explicit closure between adjacent arms.
// Split at boundary crossings to check complete seam intervals, not samples. // Split at boundary crossings to check complete seam intervals, not samples.
function segmentCoveredByRing(start, end, ring) { function segmentCoveredByRing(start, end, ring) {
const scale = Math.cos((start[1] * Math.PI) / 180); const { lon, lat } = metersAt(start[1]);
const xy = (p) => [(p[0] - start[0]) * 111320 * scale, (p[1] - start[1]) * 111320]; const xy = (p) => [(p[0] - start[0]) * lon, (p[1] - start[1]) * lat];
const d = xy(end), const d = xy(end),
boundary = ring.map(xy); boundary = ring.map(xy);
const cross = (a, b) => a[0] * b[1] - a[1] * b[0]; const cross = (a, b) => a[0] * b[1] - a[1] * b[0];
+1 -14
View File
@@ -1,13 +1,10 @@
'use strict'; 'use strict';
const { topologyIdentity } = require('./junction-topology'); const { topologyIdentity } = require('./junction-topology');
const { normalizeHeading, offsetCoordinate } = require('../geometry/metric');
const MIN_ENTRY_SECTION_METERS = 12; const MIN_ENTRY_SECTION_METERS = 12;
function normalizeHeading(value) {
return ((((value + 180) % 360) + 360) % 360) - 180;
}
function averageHeading(headings) { function averageHeading(headings) {
const vector = headings.reduce( const vector = headings.reduce(
(sum, heading) => { (sum, heading) => {
@@ -31,16 +28,6 @@ function tangentAt(line, station, length, helpers) {
return null; 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) { function boundaryAt(point, tangent, widthMeters) {
const halfWidth = Math.max(0, Number(widthMeters) || 0) / 2; const halfWidth = Math.max(0, Number(widthMeters) || 0) / 2;
return { return {
+6 -4
View File
@@ -1,15 +1,17 @@
'use strict'; 'use strict';
const { metersAt } = require('../geometry/metric');
// Pure geometry helpers for the cluster-level island drag. This module does // Pure geometry helpers for the cluster-level island drag. This module does
// not mutate compiler features; callers can validate the returned rings before // not mutate compiler features; callers can validate the returned rings before
// publishing a preview. // publishing a preview.
function radialShift(center, islandCenter, distanceMeters) { function radialShift(center, islandCenter, distanceMeters) {
const scale = 111320 * Math.cos((center[1] * Math.PI) / 180); const { lon, lat } = metersAt(center[1]);
const east = (islandCenter[0] - center[0]) * scale; const east = (islandCenter[0] - center[0]) * lon;
const north = (islandCenter[1] - center[1]) * 111320; const north = (islandCenter[1] - center[1]) * lat;
const length = Math.hypot(east, north); const length = Math.hypot(east, north);
if (!Number.isFinite(length) || length < 1e-9 || !Number.isFinite(distanceMeters)) return [0, 0]; if (!Number.isFinite(length) || length < 1e-9 || !Number.isFinite(distanceMeters)) return [0, 0];
return [(distanceMeters * east) / length / scale, (distanceMeters * north) / length / 111320]; return [(distanceMeters * east) / length / lon, (distanceMeters * north) / length / lat];
} }
module.exports = { radialShift }; module.exports = { radialShift };
+4 -5
View File
@@ -2,6 +2,7 @@
const { union, difference } = require('./junction-polygon-ops'); const { union, difference } = require('./junction-polygon-ops');
const { segmentCoveredByRing } = require('./junction-boundary-graph'); const { segmentCoveredByRing } = require('./junction-boundary-graph');
const { metersAt, offsetCoordinate } = require('../geometry/metric');
/** /**
* The road layer has one authoritative complex-junction region. Construction * The road layer has one authoritative complex-junction region. Construction
@@ -37,8 +38,8 @@ function solveComplexPavementRegion(parts, crossingRegions = [], exclusionRegion
// crossing instead of checking fixed samples that can miss a narrow obstacle. // crossing instead of checking fixed samples that can miss a narrow obstacle.
function segmentCoveredByPolygon(start, end, polygon) { function segmentCoveredByPolygon(start, end, polygon) {
if (!segmentCoveredByRing(start, end, polygon[0])) return false; if (!segmentCoveredByRing(start, end, polygon[0])) return false;
const scale = 111320 * Math.cos((start[1] * Math.PI) / 180); const { lon, lat } = metersAt(start[1]);
const xy = (p) => [(p[0] - start[0]) * scale, (p[1] - start[1]) * 111320]; const xy = (p) => [(p[0] - start[0]) * lon, (p[1] - start[1]) * lat];
const d = xy(end); const d = xy(end);
const cross = (a, b) => a[0] * b[1] - a[1] * b[0]; const cross = (a, b) => a[0] * b[1] - a[1] * b[0];
return polygon.slice(1).every((hole) => { return polygon.slice(1).every((hole) => {
@@ -80,9 +81,7 @@ function segmentCoveredByPolygon(start, end, polygon) {
} }
function offset(point, heading, meters) { function offset(point, heading, meters) {
const radians = (heading * Math.PI) / 180; return offsetCoordinate(point, heading, meters);
const scale = 111320 * Math.cos((point[1] * Math.PI) / 180);
return [point[0] + (Math.sin(radians) * meters) / scale, point[1] + (Math.cos(radians) * meters) / 111320];
} }
function rectangle(center, heading, depth, span) { function rectangle(center, heading, depth, span) {
+19 -68
View File
@@ -34,6 +34,19 @@ const {
junctionSurfaceId, junctionSurfaceId,
connectionConnectorId, connectionConnectorId,
} = require('./native-ids'); } = require('./native-ids');
const {
METERS_PER_DEGREE,
distanceMeters,
headingDegrees,
headingVector,
interpolate,
metersAt,
offsetCoordinate,
project,
unproject,
} = require('../geometry/metric');
const headingAtEndpoint = (line) => headingDegrees(line[0], line[1]);
const OVERRIDE_SCHEMA = 'native-road-overrides/v1'; const OVERRIDE_SCHEMA = 'native-road-overrides/v1';
const MOTOR_HIGHWAYS = new Set([ const MOTOR_HIGHWAYS = new Set([
@@ -233,12 +246,12 @@ function roadExtent(roads) {
} }
function distanceToExtentEdgeMeters(point, extent) { function distanceToExtentEdgeMeters(point, extent) {
const lonScale = 111320 * Math.cos((point[1] * Math.PI) / 180); const lonScale = metersAt(point[1]).lon;
return Math.min( return Math.min(
(point[0] - extent.minLon) * lonScale, (point[0] - extent.minLon) * lonScale,
(extent.maxLon - point[0]) * lonScale, (extent.maxLon - point[0]) * lonScale,
(point[1] - extent.minLat) * 111320, (point[1] - extent.minLat) * METERS_PER_DEGREE,
(extent.maxLat - point[1]) * 111320, (extent.maxLat - point[1]) * METERS_PER_DEGREE,
); );
} }
@@ -515,8 +528,8 @@ function connectionEndpointsCompatible(model, fromId, toId) {
) )
return false; return false;
if (from.nodeId === to.nodeId) return true; if (from.nodeId === to.nodeId) return true;
const dx = (from.coordinate[0] - to.coordinate[0]) * 111320 * Math.cos((from.coordinate[1] * Math.PI) / 180); const dx = (from.coordinate[0] - to.coordinate[0]) * metersAt(from.coordinate[1]).lon;
const dy = (from.coordinate[1] - to.coordinate[1]) * 111320; const dy = (from.coordinate[1] - to.coordinate[1]) * METERS_PER_DEGREE;
return Math.hypot(dx, dy) <= 35; return Math.hypot(dx, dy) <= 35;
} }
@@ -1783,7 +1796,6 @@ function compileLaneMarkings(model, overrides, lanes, diagnostics, junctionPlans
} }
const previous = lane.coordinates.at(-2); const previous = lane.coordinates.at(-2);
const end = lane.coordinates.at(-1); const end = lane.coordinates.at(-1);
const meters = project(end, end);
const vector = project(previous, end); const vector = project(previous, end);
const length = Math.hypot(-vector[0], -vector[1]); const length = Math.hypot(-vector[0], -vector[1]);
const axis = length ? [-vector[0] / length, -vector[1] / length] : null; const axis = length ? [-vector[0] / length, -vector[1] / length] : null;
@@ -1864,10 +1876,6 @@ function clusterCenter(cluster, junctionPlans) {
: null; : null;
} }
function angularDistance(first, second) {
return Math.abs(((first - second + 180) % 360) - 180);
}
function laneSeparatorStyle(overrides, roadId, leftLaneIndex, rightLaneIndex) { function laneSeparatorStyle(overrides, roadId, leftLaneIndex, rightLaneIndex) {
const value = overrides.overrides.find( const value = overrides.overrides.find(
(item) => (item) =>
@@ -2475,22 +2483,6 @@ function compileLaneCenterlines(
return { features, byRoadId, markingByRoadId }; return { features, byRoadId, markingByRoadId };
} }
function cubicTurnCurve(start, end, startHeading, endHeading, radius, turn, center) {
const reach = turn === 'right' ? Math.max(5, radius * 0.75) : Math.max(9, radius * 1.35);
const first = offsetCoordinate(start, startHeading, reach);
const second = offsetCoordinate(end, endHeading, reach);
const points = [];
for (let index = 0; index <= 18; index += 1) {
const t = index / 18;
const inverse = 1 - t;
points.push([
inverse ** 3 * start[0] + 3 * inverse ** 2 * t * first[0] + 3 * inverse * t ** 2 * second[0] + t ** 3 * end[0],
inverse ** 3 * start[1] + 3 * inverse ** 2 * t * first[1] + 3 * inverse * t ** 2 * second[1] + t ** 3 * end[1],
]);
}
return points.every((point) => point.every(Number.isFinite)) ? points : [start, center, end];
}
function compileConnectors(model, lanes, diagnostics, overrides, junctionPlans, options, islands, pavementFeatures) { function compileConnectors(model, lanes, diagnostics, overrides, junctionPlans, options, islands, pavementFeatures) {
const features = []; const features = [];
const movements = []; const movements = [];
@@ -2968,9 +2960,7 @@ function offsetLine(line, offsetMeters) {
function lineLengthMeters(line) { function lineLengthMeters(line) {
return line.slice(1).reduce((sum, point, index) => { return line.slice(1).reduce((sum, point, index) => {
const previous = line[index]; const previous = line[index];
const dx = (point[0] - previous[0]) * 111320 * Math.cos((point[1] * Math.PI) / 180); return sum + distanceMeters(previous, point);
const dy = (point[1] - previous[1]) * 111320;
return sum + Math.hypot(dx, dy);
}, 0); }, 0);
} }
function polygonAreaMeters(ring) { function polygonAreaMeters(ring) {
@@ -3545,11 +3535,6 @@ function junctionTemplateFor(nodeId, segmentIds, configured, diagnostics, node)
}; };
} }
function headingVector(degrees) {
const radians = (degrees * Math.PI) / 180;
return [Math.sin(radians), Math.cos(radians)];
}
function lineIntersection(firstPoint, firstDirection, secondPoint, secondDirection) { function lineIntersection(firstPoint, firstDirection, secondPoint, secondDirection) {
const cross = firstDirection[0] * secondDirection[1] - firstDirection[1] * secondDirection[0]; const cross = firstDirection[0] * secondDirection[1] - firstDirection[1] * secondDirection[0];
if (Math.abs(cross) < 1e-4) return null; if (Math.abs(cross) < 1e-4) return null;
@@ -3671,27 +3656,9 @@ function trimLineRange(line, startCutback, endCutback) {
return result; return result;
} }
function headingAtEndpoint(line) {
return headingDegrees(line[0], line[1]);
}
function headingDegrees(a, b) {
return (Math.atan2((b[0] - a[0]) * Math.cos((a[1] * Math.PI) / 180), b[1] - a[1]) * 180) / Math.PI;
}
function offsetCoordinate(point, degrees, meters) {
const radians = (degrees * Math.PI) / 180;
return [
point[0] + (Math.sin(radians) * meters) / (111320 * Math.cos((point[1] * Math.PI) / 180)),
point[1] + (Math.cos(radians) * meters) / 111320,
];
}
function angleAround(center, point) { function angleAround(center, point) {
return Math.atan2(point[1] - center[1], point[0] - center[0]); return Math.atan2(point[1] - center[1], point[0] - center[0]);
} }
function sortAround(center, points) {
return points.sort(
(a, b) => Math.atan2(a[1] - center[1], a[0] - center[0]) - Math.atan2(b[1] - center[1], b[0] - center[0]),
);
}
function convexHull(points) { function convexHull(points) {
const unique = [...new Map(points.map((point) => [`${point[0]},${point[1]}`, point])).values()].sort( const unique = [...new Map(points.map((point) => [`${point[0]},${point[1]}`, point])).values()].sort(
(a, b) => a[0] - b[0] || a[1] - b[1], (a, b) => a[0] - b[0] || a[1] - b[1],
@@ -3710,14 +3677,6 @@ function convexHull(points) {
} }
return [...lower.slice(0, -1), ...upper.slice(0, -1)]; return [...lower.slice(0, -1), ...upper.slice(0, -1)];
} }
function interpolate(a, b, ratio) {
return [a[0] + (b[0] - a[0]) * ratio, a[1] + (b[1] - a[1]) * ratio];
}
function distanceMeters(a, b) {
const dx = (b[0] - a[0]) * 111320 * Math.cos((a[1] * Math.PI) / 180);
const dy = (b[1] - a[1]) * 111320;
return Math.hypot(dx, dy);
}
function hasSelfIntersection(ring, closed = true) { function hasSelfIntersection(ring, closed = true) {
for (let first = 0; first < ring.length - 1; first += 1) for (let first = 0; first < ring.length - 1; first += 1)
for (let second = first + 1; second < ring.length - 1; second += 1) { for (let second = first + 1; second < ring.length - 1; second += 1) {
@@ -3808,14 +3767,6 @@ function sidewalkRing(line, innerOffset, outerOffset, side) {
return ring.every((point) => point.every(Number.isFinite)) ? ring : null; return ring.every((point) => point.every(Number.isFinite)) ? ring : null;
} }
function project(point, origin) {
const scale = 111320;
return [(point[0] - origin[0]) * scale * Math.cos((origin[1] * Math.PI) / 180), (point[1] - origin[1]) * scale];
}
function unproject(point, origin) {
const scale = 111320;
return [point[0] / (scale * Math.cos((origin[1] * Math.PI) / 180)) + origin[0], point[1] / scale + origin[1]];
}
function xmlAttrs(text) { function xmlAttrs(text) {
const attrs = {}; const attrs = {};
for (const match of text.matchAll(/([:\w-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)) attrs[match[1]] = match[2] ?? match[3]; for (const match of text.matchAll(/([:\w-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)) attrs[match[1]] = match[2] ?? match[3];
+1 -4
View File
@@ -3,6 +3,7 @@
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');
const { laneCenterline } = require('../geometry/lane-geometry'); const { laneCenterline } = require('../geometry/lane-geometry');
const { metersAt: metersForLat } = require('../geometry/metric');
const ASSET_MANIFEST = path.resolve(__dirname, '..', '..', 'assets', 'lane-icons', 'manifest.json'); const ASSET_MANIFEST = path.resolve(__dirname, '..', '..', 'assets', 'lane-icons', 'manifest.json');
let defaultManifestCache = null; let defaultManifestCache = null;
@@ -457,10 +458,6 @@ function isOneway(way) {
return ['yes', 'true', '1'].includes(String(way.tags.oneway || '').toLowerCase()); return ['yes', 'true', '1'].includes(String(way.tags.oneway || '').toLowerCase());
} }
function metersForLat(lat) {
return { lon: 111320 * Math.cos((lat * Math.PI) / 180), lat: 110540 };
}
function normalizeMetersVector([dxLon, dyLat], meters) { function normalizeMetersVector([dxLon, dyLat], meters) {
const x = dxLon * meters.lon; const x = dxLon * meters.lon;
const y = dyLat * meters.lat; const y = dyLat * meters.lat;
+5 -1
View File
@@ -5,6 +5,10 @@ const path = require('path');
const { zipSync } = require('fflate'); const { zipSync } = require('fflate');
const { LAYER_REGISTRY, validatePublishedLayers } = require('../compile/layer-manifest'); const { LAYER_REGISTRY, validatePublishedLayers } = require('../compile/layer-manifest');
// Single source of truth for the version: package.json. The generator string is
// embedded byte-for-byte into every export, so it must never drift from the
// release version.
const ROOT_FILES = [ const ROOT_FILES = [
'manifest.json', 'manifest.json',
'compiled.json', 'compiled.json',
@@ -14,7 +18,7 @@ const ROOT_FILES = [
'traffic-signals.json', 'traffic-signals.json',
]; ];
const GENERATOR = Object.freeze({ name: 'road-compiler', version: '0.3.0' }); const GENERATOR = Object.freeze({ name: 'road-compiler', version: require('../../package.json').version });
function packageEntries(directory) { function packageEntries(directory) {
const manifestPath = path.join(directory, 'manifest.json'); const manifestPath = path.join(directory, 'manifest.json');
+6 -14
View File
@@ -1,6 +1,9 @@
'use strict'; 'use strict';
const EARTH_RADIUS_METERS = 6371008.8; // The single equirectangular metric source is `./metric`; `haversineMeters` is
// re-exported for constraint-station bookkeeping only — never for seam-critical
// distances, which must stay equirectangular to keep the 1 cm seam contract.
const { METERS_PER_DEGREE, averageHeading, haversineMeters, metersAt } = require('./metric');
function laneCenterline(lane) { function laneCenterline(lane) {
const ring = lane?.geometry?.type === 'Polygon' ? lane.geometry.coordinates?.[0] : null; const ring = lane?.geometry?.type === 'Polygon' ? lane.geometry.coordinates?.[0] : null;
@@ -115,15 +118,6 @@ function polylineLength(polyline) {
return total; return total;
} }
function haversineMeters(a, b) {
const lat1 = degreesToRadians(a[1]);
const lat2 = degreesToRadians(b[1]);
const dLat = degreesToRadians(b[1] - a[1]);
const dLon = degreesToRadians(b[0] - a[0]);
const h = Math.sin(dLat / 2) ** 2 + Math.cos(lat1) * Math.cos(lat2) * Math.sin(dLon / 2) ** 2;
return 2 * EARTH_RADIUS_METERS * Math.asin(Math.min(1, Math.sqrt(h)));
}
function appendCoordinates(target, coordinates) { function appendCoordinates(target, coordinates) {
for (const coordinate of coordinates) { for (const coordinate of coordinates) {
if (!sameCoordinate(target.at(-1), coordinate)) target.push(copyCoordinate(coordinate)); if (!sameCoordinate(target.at(-1), coordinate)) target.push(copyCoordinate(coordinate));
@@ -142,10 +136,6 @@ function copyCoordinate(coordinate) {
return [coordinate[0], coordinate[1]]; return [coordinate[0], coordinate[1]];
} }
function metersAt(latitude) {
return { lon: 111320 * Math.cos(degreesToRadians(latitude)), lat: 111320 };
}
function degreesToRadians(value) { function degreesToRadians(value) {
return (value * Math.PI) / 180; return (value * Math.PI) / 180;
} }
@@ -161,4 +151,6 @@ module.exports = {
projectedDistanceAlong, projectedDistanceAlong,
stitchPolylines, stitchPolylines,
metersAt, metersAt,
averageHeading,
METERS_PER_DEGREE,
}; };
+131
View File
@@ -0,0 +1,131 @@
'use strict';
// The single local-metre approximation shared by the whole compiler.
//
// One degree of latitude is METERS_PER_DEGREE metres everywhere; one degree of
// longitude is scaled by cos(latitude) taken at the first point of a
// measurement. Every distance, offset, heading, and planar projection in src/
// must come from here: the junction seam contract is 1 cm, which two
// independent copies of this family cannot be trusted to keep — one copy had
// already drifted to 110540 on the latitude axis.
//
// Two deliberate exceptions remain:
// - `haversineMeters()` in lane-geometry is great-circle distance. The direct
// edit solver uses it for persisted constraint stations; switching it to the
// equirectangular value would silently reinterpret every saved edit.
// - `test/helpers/junction-seams.js` re-derives its own copy on purpose: the
// seam audit must not call the geometry it audits.
//
// This module must stay free of fs/path so the solver can require it.
const METERS_PER_DEGREE = 111320;
const EARTH_RADIUS_METERS = 6371008.8;
function metersAt(latitude) {
return { lon: METERS_PER_DEGREE * Math.cos((latitude * Math.PI) / 180), lat: METERS_PER_DEGREE };
}
function distanceMeters(a, b) {
const dx = (b[0] - a[0]) * metersAt(a[1]).lon;
const dy = (b[1] - a[1]) * METERS_PER_DEGREE;
return Math.hypot(dx, dy);
}
function offsetCoordinate(point, degrees, meters) {
if (!point || !Number.isFinite(degrees)) return null;
const radians = (degrees * Math.PI) / 180;
const lonMeters = metersAt(point[1]).lon;
return [
point[0] + (Math.sin(radians) * meters) / Math.max(lonMeters, 1e-9),
point[1] + (Math.cos(radians) * meters) / METERS_PER_DEGREE,
];
}
// Azimuth from `a` to `b` in degrees, unnormalized: west of north is negative.
// Callers that need [0, 360) wrap with `normalizeDegrees()`.
function headingDegrees(a, b) {
return (Math.atan2((b[0] - a[0]) * Math.cos((a[1] * Math.PI) / 180), b[1] - a[1]) * 180) / Math.PI;
}
function headingVector(degrees) {
const radians = (degrees * Math.PI) / 180;
return [Math.sin(radians), Math.cos(radians)];
}
function normalizeDegrees(value) {
return ((value % 360) + 360) % 360;
}
function angularDistance(a, b) {
return Math.abs(((a - b + 540) % 360) - 180);
}
function normalizeHeading(value) {
return ((((value + 180) % 360) + 360) % 360) - 180;
}
// Signed projection of `point` onto the axis `heading + 90` (driver's right of
// `heading`) in local metres.
function signedLateralMeters(origin, point, heading) {
const east = (point[0] - origin[0]) * metersAt(origin[1]).lon;
const north = (point[1] - origin[1]) * METERS_PER_DEGREE;
const radians = ((heading + 90) * Math.PI) / 180;
return east * Math.sin(radians) + north * Math.cos(radians);
}
// Great-circle distance in metres, for persisted constraint stations only —
// equirectangular must not silently reinterpret saved edits.
// Mean Earth radius follows IUGG: 6371008.8 m.
function haversineMeters(a, b) {
const radians = Math.PI / 180;
const dLat = (b[1] - a[1]) * radians;
const dLon = (b[0] - a[0]) * radians;
const sinLat = Math.sin(dLat / 2);
const sinLon = Math.sin(dLon / 2);
const h = sinLat * sinLat + Math.cos(a[1] * radians) * Math.cos(b[1] * radians) * sinLon * sinLon;
return 2 * EARTH_RADIUS_METERS * Math.asin(Math.min(1, Math.sqrt(h)));
}
function interpolate(a, b, ratio) {
return [a[0] + (b[0] - a[0]) * ratio, a[1] + (b[1] - a[1]) * ratio];
}
// Local planar frame relative to `origin`, in metres. `project`/`unproject`
// are inverse; everything between them runs in flat space.
function project(point, origin) {
return [(point[0] - origin[0]) * metersAt(origin[1]).lon, (point[1] - origin[1]) * METERS_PER_DEGREE];
}
function unproject(point, origin) {
return [point[0] / metersAt(origin[1]).lon + origin[0], point[1] / METERS_PER_DEGREE + origin[1]];
}
// Circular mean of headings (handles the -180/180 wrap).
function averageHeading(values) {
let sinSum = 0;
let cosSum = 0;
for (const value of values) {
const radians = (value * Math.PI) / 180;
sinSum += Math.sin(radians);
cosSum += Math.cos(radians);
}
return (Math.atan2(sinSum, cosSum) * 180) / Math.PI;
}
module.exports = {
METERS_PER_DEGREE,
angularDistance,
averageHeading,
distanceMeters,
headingDegrees,
headingVector,
haversineMeters,
interpolate,
metersAt,
normalizeDegrees,
normalizeHeading,
offsetCoordinate,
project,
signedLateralMeters,
unproject,
};
+6 -7
View File
@@ -3,6 +3,10 @@
const fs = require('fs'); const fs = require('fs');
const PI = Math.PI; const PI = Math.PI;
// GCJ-02 conversion is deliberately self-contained, but the local-metre scale
// is the compiler-wide equirectangular metric — one copy keeps reference
// matching and SVG projection consistent with native road geometry.
const { METERS_PER_DEGREE, distanceMeters } = require('../geometry/metric');
const EARTH_A = 6378245.0; const EARTH_A = 6378245.0;
const EARTH_EE = 0.00669342162296594323; const EARTH_EE = 0.00669342162296594323;
@@ -92,11 +96,6 @@ function centerOf(bounds) {
return [(bounds.minLon + bounds.maxLon) / 2, (bounds.minLat + bounds.maxLat) / 2]; return [(bounds.minLon + bounds.maxLon) / 2, (bounds.minLat + bounds.maxLat) / 2];
} }
function distanceMeters(first, second) {
const lonScale = 111320 * Math.cos((first[1] * PI) / 180);
return Math.hypot((second[0] - first[0]) * lonScale, (second[1] - first[1]) * 111320);
}
function parseOsmNodes(xml) { function parseOsmNodes(xml) {
const nodes = []; const nodes = [];
for (const match of xml.matchAll(/<node\b([^>]*?)(?:\/>|>([\s\S]*?)<\/node>)/g)) { for (const match of xml.matchAll(/<node\b([^>]*?)(?:\/>|>([\s\S]*?)<\/node>)/g)) {
@@ -218,10 +217,10 @@ function inspectReference({
function localReferenceSvg({ converted, nativeIntersection, center, radiusMeters = 180 }) { function localReferenceSvg({ converted, nativeIntersection, center, radiusMeters = 180 }) {
const width = 1000; const width = 1000;
const height = 1000; const height = 1000;
const lonScale = 111320 * Math.cos((center[1] * PI) / 180); const lonScale = METERS_PER_DEGREE * Math.cos((center[1] * PI) / 180);
const project = (point) => [ const project = (point) => [
width / 2 + ((point[0] - center[0]) * lonScale * width) / (radiusMeters * 2), width / 2 + ((point[0] - center[0]) * lonScale * width) / (radiusMeters * 2),
height / 2 - ((point[1] - center[1]) * 111320 * height) / (radiusMeters * 2), height / 2 - ((point[1] - center[1]) * METERS_PER_DEGREE * height) / (radiusMeters * 2),
]; ];
const pathFor = (coordinates) => { const pathFor = (coordinates) => {
const parts = []; const parts = [];
+10 -22
View File
@@ -3,8 +3,15 @@
const fs = require('fs'); const fs = require('fs');
const crypto = require('crypto'); const crypto = require('crypto');
const { parseOsm } = require('./osm'); const { parseOsm } = require('./osm');
const {
angularDistance,
distanceMeters,
headingDegrees,
headingVector,
normalizeDegrees,
unproject,
} = require('./geometry/metric');
const EARTH_RADIUS = 6371008.8;
const CURB_OFFSET_METERS = 5.2; const CURB_OFFSET_METERS = 5.2;
const MAX_SIGNAL_POLE_DISTANCE_FROM_STOP_METERS = 40; const MAX_SIGNAL_POLE_DISTANCE_FROM_STOP_METERS = 40;
const MAST_REACH_METERS = 4.5; const MAST_REACH_METERS = 4.5;
@@ -491,29 +498,10 @@ function nearestCenter(point, centers) {
); );
} }
function metersBetween(a, b) { function metersBetween(a, b) {
const lat = (((a[1] + b[1]) / 2) * Math.PI) / 180; return distanceMeters(a, b);
return ((Math.hypot((a[0] - b[0]) * Math.cos(lat), a[1] - b[1]) * Math.PI) / 180) * EARTH_RADIUS;
} }
function moveMeters(point, vector, meters) { function moveMeters(point, vector, meters) {
const scale = 180 / Math.PI / EARTH_RADIUS; return unproject([vector[0] * meters, vector[1] * meters], point);
return [
point[0] + (vector[0] * meters * scale) / Math.cos((point[1] * Math.PI) / 180),
point[1] + vector[1] * meters * scale,
];
}
function headingBetween(from, to) {
const latitude = (((from[1] + to[1]) / 2) * Math.PI) / 180;
return (Math.atan2((to[0] - from[0]) * Math.cos(latitude), to[1] - from[1]) * 180) / Math.PI;
}
function headingVector(degrees) {
const radians = (degrees * Math.PI) / 180;
return [Math.sin(radians), Math.cos(radians)];
}
function normalizeDegrees(value) {
return ((value % 360) + 360) % 360;
}
function angularDistance(a, b) {
return Math.abs(((a - b + 540) % 360) - 180);
} }
module.exports = { module.exports = {
+70 -15
View File
@@ -463,6 +463,11 @@ function App() {
* same id in the document, which `validateEditDocument()` rejects outright. * same id in the document, which `validateEditDocument()` rejects outright.
*/ */
const gesture = useRef<{ operationId: string; createdAt: string } | null>(null); const gesture = useRef<{ operationId: string; createdAt: string } | null>(null);
const pendingDraft = useRef<PreviewDraft | null>(null);
const debugIslandDraft = (stage: string, draft: PreviewDraft | null) => {
const item = draft?.constraints?.find((constraint) => constraint.kind === 'cluster-island-offset');
if (item) console.log('[direct-edit:island]', stage, item.value, item.id, item.provenance?.operationId);
};
const gestureIdentity = () => { const gestureIdentity = () => {
if (!gesture.current) if (!gesture.current)
gesture.current = { gesture.current = {
@@ -576,6 +581,16 @@ function App() {
for (const constraint of draft.constraints ?? []) constraints.set(constraint.id, constraint); for (const constraint of draft.constraints ?? []) constraints.set(constraint.id, constraint);
for (const operation of draft.operations ?? []) operations.set(operation.id, operation); for (const operation of draft.operations ?? []) operations.set(operation.id, operation);
} }
// Every member draft is built from the same gesture operation. Merge its
// constraint ids instead of letting the last member overwrite the earlier
// operation; otherwise validation sees operation ids that are absent from
// the final constraint set.
for (const operation of operations.values()) {
if (!gesture.current || operation.id !== gesture.current.operationId) continue;
operation.constraintIds = [...constraints.values()]
.filter((constraint) => constraint.provenance.operationId === operation.id)
.map((constraint) => constraint.id);
}
return { constraints: [...constraints.values()], operations: [...operations.values()] }; return { constraints: [...constraints.values()], operations: [...operations.values()] };
}; };
const settleGroup = (handles: EditHandle[], value: number) => { const settleGroup = (handles: EditHandle[], value: number) => {
@@ -590,19 +605,26 @@ function App() {
const defaultKey = [...frequencies.entries()].sort((a, b) => b[1] - a[1])[0]?.[0]; const defaultKey = [...frequencies.entries()].sort((a, b) => b[1] - a[1])[0]?.[0];
const changed = handles.filter( const changed = handles.filter(
(handle) => (handle) =>
formatParameterValue(handle.value.current) === defaultKey && !rendersSame(value, handle.value.current), formatParameterValue(handle.value.current) === defaultKey &&
(Boolean(gesture.current) || !rendersSame(value, handle.value.current)),
); );
if (!changed.length) { // Once typing has produced a draft, the group value is authoritative. The
// preview may already have rewritten every manifest value before blur or
// Enter; using that refreshed manifest to filter members would discard the
// pending edit and restore the old document.
const targetHandles = gesture.current ? handles : changed;
if (!targetHandles.length) {
abandonGesture(); abandonGesture();
return; return;
} }
const draft = draftForGroup(changed, value); const draft = draftForGroup(targetHandles, value);
if (draft) if (draft) {
commitGesture( pendingDraft.current = draft;
draft, const ids = targetHandles
changed.map((handle) => `constraint:${handle.handleId}`), .map((handle) => `constraint:${handle.handleId}`)
); .filter((id) => (draft.constraints ?? []).some((constraint) => constraint.id === id));
else abandonGesture(); commitGesture(draft, ids);
} else abandonGesture();
}; };
const draftLane = (laneId: string, maneuver: string, placementDistanceMeters: number): PreviewDraft | null => { const draftLane = (laneId: string, maneuver: string, placementDistanceMeters: number): PreviewDraft | null => {
const handle = manifest?.handles.find( const handle = manifest?.handles.find(
@@ -654,6 +676,8 @@ function App() {
*/ */
const commitGesture = (draft: PreviewDraft | null, constraintIds: string[]) => { const commitGesture = (draft: PreviewDraft | null, constraintIds: string[]) => {
if (!draft || !session) return; if (!draft || !session) return;
debugIslandDraft('session.commit', draft);
pendingDraft.current = null;
requester?.flush(draft); requester?.flush(draft);
session.commit(draft.constraints ?? [], constraintIds, gestureIdentity()); session.commit(draft.constraints ?? [], constraintIds, gestureIdentity());
recordEdit(editHistoryRef.current, 'session'); recordEdit(editHistoryRef.current, 'session');
@@ -681,10 +705,15 @@ function App() {
*/ */
const draftValue = (handle: EditHandle, value: number) => { const draftValue = (handle: EditHandle, value: number) => {
const draft = draftFor(handle, value); const draft = draftFor(handle, value);
if (draft) requester?.schedule(draft); if (draft) {
pendingDraft.current = draft;
debugIslandDraft('preview.schedule', draft);
requester?.schedule(draft);
}
}; };
/** Neither channel committed: release the id and put the settled state back. */ /** Neither channel committed: release the id and put the settled state back. */
const abandonGesture = () => { const abandonGesture = () => {
pendingDraft.current = null;
gesture.current = null; gesture.current = null;
panelRef.current?.clearLive(); panelRef.current?.clearLive();
previewSession(); previewSession();
@@ -719,7 +748,11 @@ function App() {
// captured at pointerdown, so this compares against the pre-drag value. The // captured at pointerdown, so this compares against the pre-drag value. The
// element box is a large hit target, which makes a click-without-drag common // element box is a large hit target, which makes a click-without-drag common
// rather than an edge case — but the same applies to a tapped handle dot. // rather than an edge case — but the same applies to a tapped handle dot.
if (rendersSame(value, handle.value.current)) { // A focused field can already match the refreshed manifest after its
// preview response. The live gesture identity is the source of truth for
// whether this blur has an edit to commit; comparing against the manifest
// here would abandon that edit and restore the old preview.
if (!gesture.current && rendersSame(value, handle.value.current)) {
abandonGesture(); abandonGesture();
return; return;
} }
@@ -843,12 +876,22 @@ function App() {
setStatus('已放弃未保存的直接编辑'); setStatus('已放弃未保存的直接编辑');
}; };
const saveDirectEdits = async (recompile = true) => { const saveDirectEdits = async (recompile = true) => {
if (!session || !session.dirty) return true;
// A field still being typed in holds an uncommitted value. Blur fires before // A field still being typed in holds an uncommitted value. Blur fires before
// click so the button press would settle it anyway, but that ordering is not // click so the button press would settle it anyway, but that ordering is not
// something to depend on for whether an edit is persisted. // something to depend on for whether an edit is persisted.
panelRef.current?.settleOpenEdit(); panelRef.current?.commitPending();
// A preview draft is authoritative user intent even if the input event
// that normally commits it was interrupted by a manifest refresh.
if (session && pendingDraft.current) {
const draft = pendingDraft.current;
debugIslandDraft('save.fallback-commit', draft);
const ids = (draft.constraints ?? []).map((constraint) => constraint.id);
session.commit(draft.constraints ?? [], ids, gestureIdentity());
pendingDraft.current = null;
}
if (!session || !session.dirty) return true;
const fragment = session.fragment(); const fragment = session.fragment();
debugIslandDraft('save.payload', fragment);
let version: number; let version: number;
try { try {
const result = await api.saveEdits({ const result = await api.saveEdits({
@@ -1324,7 +1367,10 @@ function App() {
.catch((error: Error) => setStatus(`更新失败:${error.message}`)); .catch((error: Error) => setStatus(`更新失败:${error.message}`));
}} }}
onCandidateMarkersChange={setJunctionNodeMarkers} onCandidateMarkersChange={setJunctionNodeMarkers}
onApply={() => setJunctionSession((current) => (current ? applyJunctionDraft(current) : current))} onApply={() => {
panelRef.current?.commitPending();
setJunctionSession((current) => (current ? applyJunctionDraft(current) : current));
}}
onDiscard={discardJunctionDraft} onDiscard={discardJunctionDraft}
onSave={() => onSave={() =>
void compile().then((ok) => { void compile().then((ok) => {
@@ -1346,8 +1392,17 @@ function App() {
setJunctionSession((current) => (current ? { ...current, status: 'draft', dirty: true } : current)); setJunctionSession((current) => (current ? { ...current, status: 'draft', dirty: true } : current));
}} }}
onDraftGroup={(handles, value) => { onDraftGroup={(handles, value) => {
console.log(
'[direct-edit:island:group-input]',
value,
handles.map((handle) => ({ id: handle.handleId, kind: handle.kind, current: handle.value.current })),
);
const draft = draftForGroup(handles, value); const draft = draftForGroup(handles, value);
if (draft) requester?.schedule(draft); if (draft) {
pendingDraft.current = draft;
debugIslandDraft('preview.schedule.group', draft);
requester?.schedule(draft);
}
setJunctionSession((current) => (current ? { ...current, status: 'draft', dirty: true } : current)); setJunctionSession((current) => (current ? { ...current, status: 'draft', dirty: true } : current));
}} }}
onSettle={(handle, value) => { onSettle={(handle, value) => {
@@ -49,7 +49,7 @@ export interface ParameterPanelHandle {
* in time on its own — but only just, and nothing states that ordering. Saving * in time on its own — but only just, and nothing states that ordering. Saving
* calls this first so the guarantee does not rest on event order. * calls this first so the guarantee does not rest on event order.
*/ */
settleOpenEdit(): void; commitPending(): void;
} }
/** Baseline text is kept on the node so a restore cannot go stale with a closure. */ /** Baseline text is kept on the node so a restore cannot go stale with a closure. */
@@ -124,8 +124,11 @@ function ParameterRow({
// Committing a value that renders the same as the stored one would turn a // Committing a value that renders the same as the stored one would turn a
// focus/blur with no typing into an edit, because the field shows a rounded // focus/blur with no typing into an edit, because the field shows a rounded
// form of what the manifest holds. // form of what the manifest holds.
if (value !== null && rangeVerdictOf(value, min, max) === 'ok' && !rendersSame(value, current)) // The manifest may already contain this value because an authoritative
onSettle(handle, value); // preview arrived while the field was focused. Compare with the value at
// focus, not the freshly replaced manifest, or blur would abandon a valid
// edit and clear the preview.
if (value !== null && rangeVerdictOf(value, min, max) === 'ok') onSettle(handle, value);
// Typed, then left unusable: a previously previewed keystroke may still be // Typed, then left unusable: a previously previewed keystroke may still be
// pending, so the settled state has to be put back. // pending, so the settled state has to be put back.
else onAbandon(); else onAbandon();
@@ -192,7 +195,13 @@ function ParameterRow({
const next = Math.min(max, Math.max(min, (parsed ?? current) + direction * step)); const next = Math.min(max, Math.max(min, (parsed ?? current) + direction * step));
draft(formatParameterValue(next)); draft(formatParameterValue(next));
} }
if (event.key === 'Enter') event.currentTarget.blur(); if (event.key === 'Enter') {
event.preventDefault();
// Commit from the row's current text first. Calling blur here
// made Enter depend on React's rerender and the refreshed
// manifest, which could turn a valid preview back into 0.
settle();
}
if (event.key === 'Escape') { if (event.key === 'Escape') {
setText(null); setText(null);
onAbandon(); onAbandon();
@@ -271,7 +280,7 @@ export function ParameterPanel({
} }
live.current.clear(); live.current.clear();
}, },
settleOpenEdit() { commitPending() {
// `blur()` runs the row's onBlur synchronously, so the command is on the // `blur()` runs the row's onBlur synchronously, so the command is on the
// stack by the time this returns. // stack by the time this returns.
for (const node of nodes.current.values()) if (node === document.activeElement) node.blur(); for (const node of nodes.current.values()) if (node === document.activeElement) node.blur();