diff --git a/.trellis/tasks/09-02-junction-detection-hotspot/implement.md b/.trellis/tasks/09-02-junction-detection-hotspot/implement.md new file mode 100644 index 0000000..29f31d2 --- /dev/null +++ b/.trellis/tasks/09-02-junction-detection-hotspot/implement.md @@ -0,0 +1,21 @@ +# Implementation + +先为 node/cluster/candidate 派生逻辑加单测,再接 MapCanvas 热区渲染和点击路由;验证与现有道路/设施命中隔离。 +# Implementation + +1. Add a pure descriptor model deriving editable node, readonly configured cluster, + and candidate cluster hotspots from the compiled state. +2. Add a dedicated OpenLayers hotspot layer with visibility control and isolated + click handling that returns a stable `JunctionRef`. +3. Add unit coverage for descriptor stability and node/cluster/candidate status. + +## Progress + +- [x] Pure descriptor model and stable `JunctionRef` +- [x] Dedicated hotspot layer and map click adapter +- [x] Client type-check, unit tests, format check, and production build + +## Deferred + +- Independent JunctionTools route and session lifecycle belong to the workspace + child task and are intentionally not implemented here. diff --git a/workbench/client/src/App.tsx b/workbench/client/src/App.tsx index 180e88d..e538c7f 100644 --- a/workbench/client/src/App.tsx +++ b/workbench/client/src/App.tsx @@ -53,6 +53,7 @@ import type { import { Button } from './ui/button'; import type { GeoFeature, GeoJson, Road, WorkbenchState } from './types/state'; import type { LayerName } from './map/layers'; +import type { JunctionRef } from './junction/hotspots'; const layerLabels: Array<[LayerName, string]> = [ ['osm', '方向道路参考线'], @@ -65,6 +66,7 @@ const layerLabels: Array<[LayerName, string]> = [ ['edgeLines', '道路外缘线'], ['controls', '斑马线与停止线'], ['signals', '红绿灯设施'], + ['junctionHotspots', '路口编辑热区'], ]; const defaultLayers = Object.fromEntries(layerLabels.map(([key]) => [key, key !== 'edgeLines'])) as Record< LayerName, @@ -78,6 +80,7 @@ function App() { const [selected, setSelected] = useState(null); const [layers, setLayers] = useState(defaultLayers); const [scene, setScene] = useState(false); + const [junctionHotspots, setJunctionHotspots] = useState(true); const [status, setStatus] = useState('正在加载工作台...'); const [filter, setFilter] = useState<'all' | 'candidates' | 'other'>('all'); const [marking, setMarking] = useState | null>(null); @@ -802,6 +805,10 @@ function App() { selected={selected} visible={layers} scene={scene} + junctionHotspots={junctionHotspots} + onJunctionHotspot={(ref: JunctionRef) => { + setStatus(ref.type === 'node' ? `已定位路口节点 ${ref.id}(可编辑)` : `已定位路口 ${ref.id}(只读)`); + }} onSelectRoad={setSelected} onFeature={handleFeature} signalSelectionUid={typeof marking?.signal_uid === 'string' ? marking.signal_uid : null} diff --git a/workbench/client/src/components/MapCanvas.tsx b/workbench/client/src/components/MapCanvas.tsx index f2e3129..1126246 100644 --- a/workbench/client/src/components/MapCanvas.tsx +++ b/workbench/client/src/components/MapCanvas.tsx @@ -15,7 +15,8 @@ import Stroke from 'ol/style/Stroke'; import Style from 'ol/style/Style'; import { click } from 'ol/events/condition'; import type { GeoJson, Road, WorkbenchState } from '../types/state'; -import { createLayers, updateLayers, updateSelectedRoad, type LayerName } from '../map/layers'; +import { createLayers, updateJunctionHotspots, updateLayers, updateSelectedRoad, type LayerName } from '../map/layers'; +import { junctionDescriptors, type JunctionDescriptor, type JunctionRef } from '../junction/hotspots'; import { createHandleDragInteraction } from '../edit/drag-interaction'; import { EditGhostLayer } from '../edit/ghost-layer'; import { EditHandleLayer, type ElementOutline } from '../edit/handle-layer'; @@ -70,6 +71,8 @@ interface Props { /** Last solve came back degraded; hold the ghost instead of clearing it. */ ghostPending?: boolean; editMode?: boolean; + junctionHotspots?: boolean; + onJunctionHotspot?: (ref: JunctionRef, coordinate: Coordinate, descriptor: JunctionDescriptor) => void; } export function MapCanvas({ state, @@ -102,6 +105,8 @@ export function MapCanvas({ onRangeEnd, ghostPending, editMode = false, + junctionHotspots = true, + onJunctionHotspot, }: Props) { const target = useRef(null); const mapRef = useRef(null); @@ -155,8 +160,8 @@ export function MapCanvas({ laneSelectionAxisAzimuth, ghostPending, }; - const selectRef = useRef({ onSelectRoad, onFeature, onBackground }); - selectRef.current = { onSelectRoad, onFeature, onBackground }; + const selectRef = useRef({ onSelectRoad, onFeature, onBackground, onJunctionHotspot }); + selectRef.current = { onSelectRoad, onFeature, onBackground, onJunctionHotspot }; const selectedRef = useRef(selected); const stateRef = useRef(state); const sceneRef = useRef(scene); @@ -249,11 +254,22 @@ export function MapCanvas({ layer !== layers.selectedRoad && layer !== handleLayer?.layer && layer !== laneSelectionLayer && - layer !== signalTransformLayer, + layer !== signalTransformLayer && + layer !== layers.junctionHotspots, hitTolerance: 12, style: null, }); map.addInteraction(select); + map.on('singleclick', (event) => { + const hit = map.forEachFeatureAtPixel(event.pixel, (feature) => feature, { + layerFilter: (layer) => layer === layers.junctionHotspots, + hitTolerance: 12, + }); + const ref = hit?.get('junction_ref'); + const descriptor = hit?.get('junction_descriptor'); + if (!ref || !descriptor) return; + selectRef.current.onJunctionHotspot?.(ref, toLonLat(event.coordinate as Coordinate), descriptor); + }); let signalUid: string | null = null; let rotatePivot: Coordinate | null = null; map.addInteraction( @@ -409,12 +425,13 @@ export function MapCanvas({ const map = mapRef.current; if (!layers || !map) return; updateLayers(layers, state, selected); + updateJunctionHotspots(layers, junctionDescriptors(state), junctionHotspots); const extent = layers.osm.getSource()!.getExtent(); if (fittedAreaIdRef.current !== state.areaId && extent && Number.isFinite(extent[0])) { map.getView().fit(extent, { padding: [48, 48, 48, 48], maxZoom: 19 }); fittedAreaIdRef.current = state.areaId; } - }, [state]); + }, [state, junctionHotspots]); useEffect(() => { const layers = layersRef.current; if (!layers) return; diff --git a/workbench/client/src/junction/hotspots.test.ts b/workbench/client/src/junction/hotspots.test.ts new file mode 100644 index 0000000..5619e98 --- /dev/null +++ b/workbench/client/src/junction/hotspots.test.ts @@ -0,0 +1,86 @@ +import { describe, expect, it } from 'vitest'; +import { junctionDescriptors, hotspotAt } from './hotspots'; +import type { WorkbenchState } from '../types/state'; + +const state = (overrides: Partial = {}): WorkbenchState => ({ + areaId: 'a', + compiled: { + model: { + roads: [], + endpoints: [ + { id: 'e2', roadId: 'r2', side: 'start', nodeId: 'n1', coordinate: [2, 2] }, + { id: 'e1', roadId: 'r1', side: 'end', nodeId: 'n1', coordinate: [0, 0] }, + ], + connections: [], + }, + diagnostics: [], + }, + overrides: { schema: 'x', overrides: [] }, + trafficSignals: { provenance: 'x', assemblies: { type: 'FeatureCollection', features: [] } }, + trafficRuntime: { signals: [] }, + comparison: {}, + layers: {}, + ...overrides, +}); + +describe('junction hotspots', () => { + it('derives stable editable node descriptor', () => { + const first = junctionDescriptors(state()); + const second = junctionDescriptors(state()); + expect(first).toEqual(second); + expect(first[0]).toMatchObject({ ref: { type: 'node', id: 'n1' }, status: 'editable', coordinate: [1, 1] }); + }); + it('marks configured clusters readonly and candidates as candidate', () => { + const value = state({ + layers: { + nativeIntersectionSurface: { + type: 'FeatureCollection', + features: [ + { + type: 'Feature', + geometry: { + type: 'Polygon', + coordinates: [ + [ + [0, 0], + [1, 0], + [1, 1], + [0, 0], + ], + ], + }, + properties: { cluster_id: 'c1' }, + }, + ], + }, + }, + debug: { + junctionCandidates: [ + { + index: 1, + id: 'd1', + nodeIds: ['n1', 'n2'], + nodeCount: 2, + diameterMeters: 10, + template: 'complex-junction-v1', + coreRadiusMeters: 8, + }, + ], + }, + compiled: { + ...state().compiled, + diagnostics: [ + { + id: 'd1', + rule: 'complex-junction-candidate', + message: 'candidate', + geometry: { type: 'Point', coordinates: [3, 3] }, + }, + ], + }, + }); + const descriptors = junctionDescriptors(value); + expect(hotspotAt(descriptors, { type: 'cluster', id: 'c1' })?.status).toBe('readonly'); + expect(hotspotAt(descriptors, { type: 'cluster', id: 'd1' })?.status).toBe('candidate'); + }); +}); diff --git a/workbench/client/src/junction/hotspots.ts b/workbench/client/src/junction/hotspots.ts new file mode 100644 index 0000000..93f741c --- /dev/null +++ b/workbench/client/src/junction/hotspots.ts @@ -0,0 +1,112 @@ +import type { Diagnostic, JunctionCandidate, Position, WorkbenchState } from '../types/state'; + +export type JunctionRef = { type: 'node' | 'cluster'; id: string }; +export type JunctionHotspotStatus = 'editable' | 'readonly' | 'candidate'; +export interface JunctionDescriptor { + ref: JunctionRef; + status: JunctionHotspotStatus; + coordinate: Position; + radiusMeters: number; + nodeIds: string[]; + approachRoadIds: string[]; + diagnosticIds: string[]; + source: 'junction-plan' | 'cluster-config' | 'candidate'; +} + +function average(points: Position[]): Position | null { + if (!points.length) return null; + return [ + points.reduce((sum, point) => sum + point[0], 0) / points.length, + points.reduce((sum, point) => sum + point[1], 0) / points.length, + ]; +} + +function candidateDescriptor(candidate: JunctionCandidate, diagnostics: Diagnostic): JunctionDescriptor | null { + const coordinate = + diagnostics.geometry?.type === 'Point' && Array.isArray(diagnostics.geometry.coordinates) + ? (diagnostics.geometry.coordinates as Position) + : null; + if (!coordinate || coordinate.length < 2) return null; + return { + ref: { type: 'cluster', id: candidate.id }, + status: 'candidate', + coordinate, + radiusMeters: Math.max(8, Number(candidate.coreRadiusMeters) || 12), + nodeIds: candidate.nodeIds.map(String).sort(), + approachRoadIds: [], + diagnosticIds: [diagnostics.id], + source: 'candidate', + }; +} + +/** Derive stable, read-only hotspots from the compiled state. */ +export function junctionDescriptors(state: WorkbenchState): JunctionDescriptor[] { + const diagnostics = state.compiled.diagnostics || []; + const result: JunctionDescriptor[] = []; + const endpointsByNode = new Map(); + for (const endpoint of state.compiled.model.endpoints || []) { + const list = endpointsByNode.get(String(endpoint.nodeId)) || []; + list.push(endpoint); + endpointsByNode.set(String(endpoint.nodeId), list); + } + for (const [nodeId, endpoints] of endpointsByNode) { + if (endpoints.length < 2) continue; + const coordinate = average(endpoints.map((endpoint) => endpoint.coordinate)); + if (!coordinate) continue; + const related = diagnostics.filter( + (item) => + item.subjectId === nodeId || (item.endpointId && endpoints.some((endpoint) => endpoint.id === item.endpointId)), + ); + result.push({ + ref: { type: 'node', id: nodeId }, + status: 'editable', + coordinate, + radiusMeters: 10, + nodeIds: [nodeId], + approachRoadIds: [...new Set(endpoints.map((endpoint) => endpoint.roadId))].sort(), + diagnosticIds: related.map((item) => item.id).sort(), + source: 'junction-plan', + }); + } + const configured = new Map(); + for (const feature of state.layers.nativeIntersectionSurface?.features || []) { + const clusterId = feature.properties?.cluster_id; + if (typeof clusterId !== 'string' || !clusterId) continue; + const geometry = feature.geometry; + const coordinates = + geometry && geometry.type === 'Polygon' && Array.isArray(geometry.coordinates) + ? (geometry.coordinates as Position[][])[0] + : []; + const center = average(coordinates || []); + if (!center) continue; + const current = configured.get(clusterId) || { nodeIds: [], coordinate: center, approachRoadIds: [] }; + current.coordinate = center; + const nodeId = feature.properties?.node_id; + if (typeof nodeId === 'string') current.nodeIds.push(nodeId); + configured.set(clusterId, current); + } + for (const [clusterId, value] of configured) { + const nodeIds = [...new Set(value.nodeIds)].sort(); + result.push({ + ref: { type: 'cluster', id: clusterId }, + status: 'readonly', + coordinate: value.coordinate, + radiusMeters: 16, + nodeIds, + approachRoadIds: value.approachRoadIds, + diagnosticIds: [], + source: 'cluster-config', + }); + } + for (const candidate of state.debug?.junctionCandidates || []) { + const diagnostic = diagnostics.find((item) => item.id === candidate.id); + if (!diagnostic) continue; + const descriptor = candidateDescriptor(candidate, diagnostic); + if (descriptor) result.push(descriptor); + } + return result.sort((a, b) => `${a.ref.type}:${a.ref.id}`.localeCompare(`${b.ref.type}:${b.ref.id}`)); +} + +export function hotspotAt(descriptors: JunctionDescriptor[], ref: JunctionRef): JunctionDescriptor | null { + return descriptors.find((item) => item.ref.type === ref.type && item.ref.id === ref.id) || null; +} diff --git a/workbench/client/src/map/layers.ts b/workbench/client/src/map/layers.ts index cbf9080..6dd501c 100644 --- a/workbench/client/src/map/layers.ts +++ b/workbench/client/src/map/layers.ts @@ -11,6 +11,7 @@ import Stroke from 'ol/style/Stroke'; import Style from 'ol/style/Style'; import { offsetCoordinate, type Coordinate } from '../edit/meters'; import type { Road, WorkbenchState } from '../types/state'; +import type { JunctionDescriptor } from '../junction/hotspots'; const geojson = new GeoJSON(); const source = () => new VectorSource(); @@ -27,7 +28,8 @@ export type LayerName = | 'signals' | 'connectors' | 'diagnostics' - | 'selectedRoad'; + | 'selectedRoad' + | 'junctionHotspots'; export function createLayers( onRoad: () => Road | null, scene: () => boolean, @@ -137,9 +139,46 @@ export function createLayers( source: source(), style: new Style({ stroke: new Stroke({ color: '#00a5cf', width: 8 }) }), }), + junctionHotspots: new VectorLayer({ + source: source(), + zIndex: 80, + style: (feature) => { + const status = feature.get('junction_status'); + const color = status === 'editable' ? '#0e7490' : status === 'candidate' ? '#d49318' : '#64748b'; + return new Style({ + image: new CircleStyle({ + radius: status === 'candidate' ? 9 : 8, + fill: new Fill({ color: `${color}33` }), + stroke: new Stroke({ color, width: 2 }), + }), + }); + }, + }), }; return layers; } + +export function updateJunctionHotspots( + layers: ReturnType, + descriptors: JunctionDescriptor[], + visible = true, +) { + const target = layers.junctionHotspots; + target.setVisible(visible); + const source = target.getSource()!; + source.clear(); + source.addFeatures( + descriptors.map( + (descriptor) => + new Feature({ + geometry: new Point([descriptor.coordinate[0], descriptor.coordinate[1]]).transform('EPSG:4326', 'EPSG:3857'), + junction_ref: descriptor.ref, + junction_status: descriptor.status, + junction_descriptor: descriptor, + }), + ), + ); +} function features(value: unknown) { return geojson.readFeatures((value || { type: 'FeatureCollection', features: [] }) as object, { dataProjection: 'EPSG:4326',