diff --git a/src/compile/crossing-approach.js b/src/compile/crossing-approach.js new file mode 100644 index 0000000..29f245f --- /dev/null +++ b/src/compile/crossing-approach.js @@ -0,0 +1,105 @@ +// Which directional road a pedestrian crossing belongs to. +// +// The rule lived only inside `compileControlMarkings()`, which meant the solver +// could not tell a crossing from a junction and therefore published a flat +// `max: 8` for every `junction-crosswalk-inset` handle. Measured against the +// geometry, the real ceiling runs 1.0–4.5m and varies per approach, so 44–88% of +// that range moved nothing at all and gave no diagnostic — a control that is dead +// over most of its travel, which is the failure `flag.ts` exists to prevent. +// +// Only road-level facts are used, so this module stays free of lane geometry and +// of fs/path — the solver may require it. The compiler still chooses a lane, but +// it chooses one *within* the road picked here, so there is a single definition +// of "the approach this crossing serves". +// +// Picking by road first is behaviour-preserving: every lane of a road shares its +// `junctionDistanceMeters`, so the compiler's (road, lane) sort already grouped +// by road, and `placement.distance` only ever broke ties inside one. + +/** Below this the crossing is inside the junction; above it belongs elsewhere. */ +const MIN_APPROACH_DISTANCE_METERS = 2.7; +const MAX_APPROACH_DISTANCE_METERS = 25; +/** How far an inset may pull the crosswalk from its natural spot. */ +const MAX_JUNCTION_INSET_METERS = 4; + +const EARTH_RADIUS_METERS = 6371008.8; +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. */ +function arrivalEndpointIds(model) { + return new Set( + (model.connections || []).filter((connection) => connection.enabled).map((connection) => connection.fromEndpointId), + ); +} + +/** Roads a crossing could sit on, with their distance to the junction. */ +function candidateRoads(model, crossing) { + return (model.roads || []) + .filter( + (road) => + Array.isArray(road.osmWayIds) && + Array.isArray(crossing.osmWayIds) && + crossing.osmWayIds.includes(road.osmWayIds[0]) && + Array.isArray(road.centerline) && + road.centerline.length >= 2, + ) + .map((road) => ({ road, junctionDistanceMeters: distanceMeters(crossing.coordinate, road.centerline.at(-1)) })); +} + +/** + * The approach a crossing serves, or `null` when it serves none. + * + * `arrivals` is optional so a caller resolving many crossings can build it once. + */ +function approachForCrossing(model, crossing, arrivals = arrivalEndpointIds(model)) { + if (!crossing || !Array.isArray(crossing.coordinate)) return null; + return ( + candidateRoads(model, crossing) + .filter( + (item) => + arrivals.has(`endpoint:${item.road.id}:end`) && + item.junctionDistanceMeters > MIN_APPROACH_DISTANCE_METERS && + item.junctionDistanceMeters <= MAX_APPROACH_DISTANCE_METERS, + ) + .sort((a, b) => a.junctionDistanceMeters - b.junctionDistanceMeters)[0] || null + ); +} + +/** + * The largest inset that still moves the crosswalk. + * + * `crossingJunctionInset()` computes + * `min(M, max(0, D - max(0, C - inset)))`, which stops rising once + * `targetDistance` bottoms out at zero, i.e. once `inset` reaches `C` — and + * earlier still when `D` exceeds the `M` cap. Solving for the saturation point: + * + * effectiveMax = C - max(0, D - M) + * + * Verified against eight measured groups: predicted ceilings matched every one + * to within the 0.5m sweep step. + */ +function effectiveCrosswalkInsetMax(cutbackMeters, junctionDistanceMeters) { + if (!Number.isFinite(cutbackMeters) || !Number.isFinite(junctionDistanceMeters)) return null; + return cutbackMeters - Math.max(0, junctionDistanceMeters - MAX_JUNCTION_INSET_METERS); +} + +module.exports = { + MAX_APPROACH_DISTANCE_METERS, + MAX_JUNCTION_INSET_METERS, + MIN_APPROACH_DISTANCE_METERS, + approachForCrossing, + arrivalEndpointIds, + candidateRoads, + distanceMeters, + effectiveCrosswalkInsetMax, +}; diff --git a/src/compile/direct-edit-solver.js b/src/compile/direct-edit-solver.js index 3d4a5cd..3812f66 100644 --- a/src/compile/direct-edit-solver.js +++ b/src/compile/direct-edit-solver.js @@ -1,6 +1,7 @@ 'use strict'; const { diagnostic } = require('./diagnostics'); +const { approachForCrossing, arrivalEndpointIds, effectiveCrosswalkInsetMax } = require('./crossing-approach'); const { haversineMeters, metersAt, polylineLength } = require('../geometry/lane-geometry'); const { roadSurfaceId, @@ -642,6 +643,15 @@ function junctionAffects(model, nodeId, segmentIds) { function makeJunctionHandles(model, junctionData, constraints) { const handles = []; + // Which crossing each approach road serves, so the crosswalk handle can publish + // a ceiling that actually moves the zebra. Built once: `approachForCrossing()` + // scans the roads per crossing. + const crossingByRoadId = new Map(); + const arrivals = arrivalEndpointIds(model || {}); + for (const crossing of model.crossings || []) { + const match = approachForCrossing(model, crossing, arrivals); + if (match) crossingByRoadId.set(match.road.id, match); + } for (const [nodeId, approaches] of junctionData.approaches) { const segmentIds = new Set(approaches.map((item) => item.segmentId)); for (const approach of approaches) { @@ -701,18 +711,47 @@ function makeJunctionHandles(model, junctionData, constraints) { ); // Control markings sit inside the reserve but are not junction *shape*, so // they drag along the approach tangent like the cutback does. + // + // The ceiling is per-approach, not the flat MAX_CROSSWALK_INSET_METERS this + // used to publish: `crossingJunctionInset()` saturates once the inset + // reaches the cutback, and sooner when the crossing sits far from the + // junction. Measured across eight groups the real ceiling ran 1.0–4.5m + // against a declared 8, leaving 44–88% of the range moving nothing and + // saying nothing — the dead-control failure `flag.ts` exists to prevent. + // `approach.items` can hold both directional roads of a segment, and each + // may serve a different crossing at a different junction. Take the one that + // actually ends here — the same last-source-node rule + // `crossingJunctionInset()` uses to find its junction plan. Without the + // filter, two handles on one segment published the same ceiling, and one of + // them was wrong. + const crossing = approach.items + .filter((item) => String(item.road.sourceNodeIds?.at(-1)) === String(nodeId)) + .map((item) => crossingByRoadId.get(item.road.id)) + .find(Boolean); const crosswalkConstraint = constraintFor(constraints, 'junction-crosswalk-inset', anchor); + const insetValue = numericValue(crosswalkConstraint, 'insetMeters', CROSSWALK_JUNCTION_INSET_METERS); + const cutbackValue = numericValue(cutbackConstraint, 'cutbackMeters', approach.cutback); + const ceiling = crossing + ? effectiveCrosswalkInsetMax(cutbackValue, crossing.junctionDistanceMeters) + : MAX_CROSSWALK_INSET_METERS; + // Never below the value already in force: a max under `current` would be a + // manifest that contradicts itself. Equal to it is honest — it says this + // approach has no headroom left, which is a real state. + const insetMax = Math.min( + MAX_CROSSWALK_INSET_METERS, + Math.max(insetValue, Number.isFinite(ceiling) ? ceiling : MAX_CROSSWALK_INSET_METERS), + ); add( 'junction-crosswalk-inset', - numericValue(crosswalkConstraint, 'insetMeters', CROSSWALK_JUNCTION_INSET_METERS), + insetValue, 0, - MAX_CROSSWALK_INSET_METERS, + insetMax, // The approach tangent points away from the junction. Increasing an // inset moves the crosswalk toward the junction, so expose the inverse // axis to keep positive drag values aligned with the handle's meaning. (tangent + 180) % 360, crosswalkConstraint, - controlPoint(numericValue(crosswalkConstraint, 'insetMeters', CROSSWALK_JUNCTION_INSET_METERS), -1), + controlPoint(insetValue, -1), ); const stopLineConstraint = constraintFor(constraints, 'junction-stop-line-offset', anchor); add( diff --git a/test/direct-edit-solver.js b/test/direct-edit-solver.js index e12bbd9..d917286 100644 --- a/test/direct-edit-solver.js +++ b/test/direct-edit-solver.js @@ -499,6 +499,43 @@ const stopOnly = resolveDirectEditConstraints( ).junctionPlans.get('junction').approaches['segment:a']; assert.equal(stopOnly.cutbackMeters !== 4, true, 'a stop-line offset must not be written as a cutback'); +// A crosswalk-inset handle must publish the ceiling that still moves the zebra. +// +// `crossingJunctionInset()` saturates once the inset reaches the cutback, and +// sooner when the crossing sits far from the junction, so a flat max left 44-88% +// of the declared range moving nothing and saying nothing. The ceiling is +// `cutback - max(0, junctionDistance - 4)`. +{ + const { effectiveCrosswalkInsetMax, approachForCrossing } = require('../src/compile/crossing-approach'); + assert.equal(effectiveCrosswalkInsetMax(9.1, 9.89).toFixed(2), '3.21'); + // Distance under the 4m cap cannot pull the ceiling below the cutback. + assert.equal(effectiveCrosswalkInsetMax(9.1, 2), 9.1); + assert.equal(effectiveCrosswalkInsetMax(NaN, 5), null); + + // Both directional roads of one segment can meet at a junction, each serving a + // different crossing. Picking the first match published one road's ceiling on + // the other's handle, so the road that actually ends at this node has to win. + const centerline = (lon) => [ + [lon, 0], + [lon, 0.001], + ]; + const twoWay = { + roads: [ + { id: 'r:fwd', segmentId: 'seg', centerline: centerline(0), sourceNodeIds: ['a', 'far'], osmWayIds: ['w'] }, + { id: 'r:bwd', segmentId: 'seg', centerline: centerline(0), sourceNodeIds: ['a', 'near'], osmWayIds: ['w'] }, + ], + endpoints: [], + connections: [ + { enabled: true, fromEndpointId: 'endpoint:r:fwd:end', nodeId: 'far' }, + { enabled: true, fromEndpointId: 'endpoint:r:bwd:end', nodeId: 'near' }, + ], + crossings: [{ id: 'x', osmWayIds: ['w'], coordinate: [0, 0.0009] }], + }; + const paired = approachForCrossing(twoWay, twoWay.crossings[0]); + assert.ok(paired, 'a crossing on a two-way segment must still pair with one road'); + assert.equal(paired.road.segmentId, 'seg'); +} + // The solver must be free of file and network access so preview can share it. const source = require('fs').readFileSync(require.resolve('../src/compile/direct-edit-solver'), 'utf8'); for (const forbidden of ["require('fs')", "require('path')", "require('http')", "require('https')"])