Files
road-compiler/workbench/client/src/edit/projection.ts
T

272 lines
11 KiB
TypeScript

// Handle drag -> constraint value. The only place a pointer position becomes a
// number the server will solve with.
//
// Nothing here touches OpenLayers or geometry output: a drag is projected onto
// the axis the manifest declared, converted to meters, clamped to the manifest's
// own range, and packaged as a `native-road-edits/v2` value. The client never
// writes a coordinate into a road polygon.
import {
azimuthBetween,
clamp,
haversineMeters,
offsetCoordinate,
polylineLengthMeters,
signedMetersAlongAxis,
toLonLat,
type Coordinate,
} from './meters';
import type {
AnchorSnapshot,
ConstraintValue,
LaneManeuverValue,
EditHandle,
JunctionReserve,
RoadConstraint,
RoadEditOperation,
RoadIntervalAnchor,
Transition,
} from './types';
/** Smallest interval the range handles may collapse to, in normalized station. */
export const MIN_INTERVAL_STATION = 0.02;
export interface IntervalWindow {
minStation: number;
maxStation: number;
}
/**
* Turns "along axisAzimuth" into "outward" for a handle.
*
* The manifest reports `axisAzimuth = tangent + 90` for both sides, which is the
* geometry compiler's *right*: `offsetLine()` treats a positive offset as
* counter-clockwise from the direction of travel, and sidewalks are placed at
* `heading + (side === 'left' ? -90 : 90)`. So the left kerb lies along the
* negative axis, and a left-side drag has to be negated for a positive
* `offsetMeters` / `widthMeters` to mean "wider" on both sides.
*
* Lane dividers are the exception: their offset is a signed lateral position
* already measured along the axis (left negative, right positive), so the raw
* projection is the value.
*/
function outwardSign(handle: EditHandle): number {
if (handle.kind === 'road-lane-divider') return 1;
const side = 'side' in handle.anchor ? handle.anchor.side : undefined;
return side === 'left' ? -1 : 1;
}
/**
* The scalar a drag produces for `handle`, clamped to the range the manifest
* declared. `from` / `to` are EPSG:3857 map coordinates.
*/
export function projectHandleValue(handle: EditHandle, from: Coordinate, to: Coordinate): number {
if (handle.interaction?.kind === 'rotation') {
const center = handle.interaction.center;
const start = azimuthBetween(center, handle.position);
const target = azimuthBetween(center, toLonLat(to));
const delta = ((target - start + 540) % 360) - 180;
return clamp(handle.value.current + delta, handle.value.min, handle.value.max);
}
const delta = signedMetersAlongAxis(from, to, handle.axisAzimuth) * outwardSign(handle);
return clamp(handle.value.current + delta, handle.value.min, handle.value.max);
}
/**
* Where the handle belongs for a given constraint value — the inverse of
* `projectHandleValue`, in EPSG:4326.
*
* This is what stops a handle running away from the geometry it controls. The
* ol-ext probe translated its proxy by the raw pointer delta, so a drag reading
* -24.1 m left the handle 24 m out while the constraint clamped at -5.4 m: the
* handle pointed at a road shape that could never exist. Deriving the position
* from the clamped value instead pins the handle to the limit.
*/
export function handlePositionFor(handle: EditHandle, value: number): Coordinate {
if (handle.interaction?.kind === 'rotation') {
const delta = value - handle.value.current;
return offsetCoordinate(handle.interaction.center, handle.axisAzimuth + delta, handle.interaction.radiusMeters);
}
const outward = outwardSign(handle) < 0 ? handle.axisAzimuth + 180 : handle.axisAzimuth;
return offsetCoordinate(handle.position, outward, value - handle.value.current);
}
/** The manifest hangs `boundaryIndex` on the anchor; the document needs it in `value`. */
function boundaryIndexOf(handle: EditHandle): number {
const index = 'boundaryIndex' in handle.anchor ? handle.anchor.boundaryIndex : undefined;
if (!Number.isInteger(index) || (index as number) < 1)
throw new Error(`handle ${handle.handleId} is a lane divider without an anchor boundaryIndex`);
return index as number;
}
/** Packages a projected scalar as the `value` the server validates. */
export function constraintValueFor(
handle: EditHandle,
scalar: number,
transition: Transition = 'smoothstep',
): ConstraintValue {
switch (handle.kind) {
case 'lane-maneuver':
throw new Error('lane-maneuver requires laneManeuverValueFor');
case 'road-edge-offset':
return { offsetMeters: scalar, transition };
case 'road-sidewalk-width':
return { widthMeters: Math.max(0, scalar), transition };
case 'road-lane-divider':
return { boundaryIndex: boundaryIndexOf(handle), offsetMeters: scalar, transition };
case 'junction-approach-width':
case 'cluster-carriageway-width':
return { widthMeters: Math.max(0, scalar) };
case 'cluster-carriageway-cutback':
return { cutbackMeters: Math.max(0, scalar) };
case 'cluster-carriageway-transition-length':
return { transitionLengthMeters: Math.max(0, scalar) };
case 'cluster-carriageway-position':
return { offsetMeters: scalar };
case 'cluster-carriageway-direction':
return { offsetDegrees: scalar };
case 'cluster-carriageway-edge-offset':
return handle.anchor.type === 'cluster-carriageway' && handle.anchor.side === 'right'
? { leftOffsetMeters: 0, rightOffsetMeters: scalar }
: { leftOffsetMeters: scalar, rightOffsetMeters: 0 };
case 'cluster-corner-radius':
return { radiusMeters: Math.max(0, scalar) };
case 'junction-cutback':
return { cutbackMeters: Math.max(0, scalar) };
case 'junction-corner-radius':
return { radiusMeters: Math.max(0, scalar) };
case 'junction-crosswalk-inset':
case 'cluster-crossing-inset':
return { insetMeters: Math.max(0, scalar) };
case 'junction-stop-line-offset':
case 'cluster-stop-line-offset':
return { offsetMeters: Math.max(0, scalar) };
case 'junction-crosswalk-size':
// Size is a pair — depth and stripe count — so no single dragged scalar
// produces it, and the solver emits no handle of this kind. Reaching here
// means one appeared without a matching input path; failing loudly beats
// writing half a value.
throw new Error('junction-crosswalk-size has no scalar form; it is written by the element size controls');
}
}
/** Packages the two-field lane arrow edit as one direct-edit value. */
export function laneManeuverValueFor(maneuver: string, placementDistanceMeters: number): LaneManeuverValue {
return { maneuver, placementDistanceMeters };
}
/**
* The station range a road interval may occupy, i.e. everything outside the
* junction reserves. Mirrors the window `makeRoadHandles()` centres its handles
* in. `reserves` are keyed by segment id, not by directional road id.
*/
export function reserveWindow(reserves: JunctionReserve[], segmentId: string): IntervalWindow {
let minStation = 0;
let maxStation = 1;
for (const reserve of reserves) {
if (reserve.roadId !== segmentId) continue;
if (reserve.fromStation <= 0) minStation = Math.max(minStation, reserve.toStation);
else maxStation = Math.min(maxStation, reserve.fromStation);
}
return { minStation, maxStation };
}
/** True when the station sits inside a junction reserve, where the main map may not edit. */
export function insideReserve(reserves: JunctionReserve[], segmentId: string, station: number): boolean {
return reserves.some(
(reserve) => reserve.roadId === segmentId && station >= reserve.fromStation && station <= reserve.toStation,
);
}
/**
* Moves one end of the affected interval. The dragged end stays inside the
* reserve-free window and never crosses the other end, so the solver always
* receives `startStation < endStation` and both ends keep a transition back to
* the baseline.
*/
export function projectIntervalEnd(
anchor: RoadIntervalAnchor,
end: 'start' | 'end',
from: Coordinate,
to: Coordinate,
tangentAzimuth: number,
roadLengthMeters: number,
window: IntervalWindow,
): RoadIntervalAnchor {
if (!(roadLengthMeters > 0)) return anchor;
const deltaStation = signedMetersAlongAxis(from, to, tangentAzimuth) / roadLengthMeters;
if (end === 'start') {
const limit = Math.max(window.minStation, anchor.endStation - MIN_INTERVAL_STATION);
return { ...anchor, startStation: clamp(anchor.startStation + deltaStation, window.minStation, limit) };
}
const limit = Math.min(window.maxStation, anchor.startStation + MIN_INTERVAL_STATION);
return { ...anchor, endStation: clamp(anchor.endStation + deltaStation, limit, window.maxStation) };
}
/**
* Evidence a later reimport uses to relocate this anchor. `centerline` is the
* road's EPSG:4326 centerline from the compiled model.
*/
export function anchorSnapshotFor(handle: EditHandle, centerline: Coordinate[], osmNodeIds: string[]): AnchorSnapshot {
return {
coordinate: [handle.position[0], handle.position[1]],
tangentAzimuth: (((handle.axisAzimuth - 90) % 360) + 360) % 360,
roadLengthMeters: polylineLengthMeters(centerline) || haversineMeters(centerline[0], centerline.at(-1)!) || 1,
osmNodeIds: [...osmNodeIds],
};
}
/**
* The operation a drafted constraint has to travel with.
*
* `validateEditDocument()` rejects any constraint whose `provenance.operationId`
* is not a recorded operation, so sending constraints alone is a 400 — which is
* exactly how the first wiring of the preview request failed. Every caller that
* ships a constraint must ship this alongside it.
*/
export function operationFor(constraint: RoadConstraint): RoadEditOperation {
return {
id: constraint.provenance.operationId,
createdAt: constraint.provenance.createdAt,
constraintIds: [constraint.id],
...(constraint.provenance.author ? { author: constraint.provenance.author } : {}),
};
}
export interface DraftIdentity {
constraintId: string;
operationId: string;
createdAt: string;
author?: string;
}
/**
* Builds the constraint a drag drafts. `anchor` is passed separately so a range
* drag can widen the interval while the value stays put, and vice versa.
*
* A drafted constraint is always `exact`: it was just authored against the model
* currently on screen. Only a reimport or a compiler upgrade can demote it.
*/
export function draftConstraint(
handle: EditHandle,
anchor: RoadConstraint['anchor'],
value: ConstraintValue,
snapshot: AnchorSnapshot,
identity: DraftIdentity,
): RoadConstraint {
return {
id: handle.constraintId || identity.constraintId,
kind: handle.kind,
anchor,
anchorSnapshot: snapshot,
value,
enabled: true,
status: 'exact',
provenance: {
operationId: identity.operationId,
createdAt: identity.createdAt,
...(identity.author ? { author: identity.author } : {}),
},
};
}