195 lines
9.3 KiB
JavaScript
195 lines
9.3 KiB
JavaScript
#!/usr/bin/env node
|
|
'use strict';
|
|
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const {
|
|
compileRoadModel,
|
|
compileGeometry,
|
|
loadOverrides,
|
|
validateOverrides,
|
|
writeJsonAtomic,
|
|
} = require('./native-road');
|
|
const { LAYER_REGISTRY, manifestForArea, validatePublishedLayers } = require('./layer-manifest');
|
|
const { loadOrGenerate, runtime } = require('../native-traffic-signals');
|
|
const { readAreaConfigSnapshot } = require('./road-revisions');
|
|
const { loadEditDocument } = require('./native-road-edits');
|
|
const { GEOMETRY_VERSION, resolveDirectEditConstraints } = require('./direct-edit-solver');
|
|
|
|
function compileInput(input) {
|
|
validateInput(input);
|
|
const options = input.areaConfigSnapshotFile ? readAreaConfigSnapshot(input.areaConfigSnapshotFile) : input.options;
|
|
validateOptions(options);
|
|
const area = {
|
|
id: input.areaId,
|
|
input: input.osmFile,
|
|
nativeRoad: options,
|
|
outputs: {
|
|
nativeRoadOverrides: input.overridesFile,
|
|
nativeTrafficSignals: input.trafficSignalsFile,
|
|
nativeRoadDir: input.outDir,
|
|
pipelineDir: input.stagingDir,
|
|
geojsonDir: input.comparisonDir || null,
|
|
},
|
|
};
|
|
const overrides = loadOverrides(area.outputs.nativeRoadOverrides);
|
|
const model = compileRoadModel(fs.readFileSync(area.input, 'utf8'), overrides);
|
|
// Editing the source OSM retires the ids some overrides point at. Those
|
|
// entries can no longer match anything, so drop them with a diagnostic rather
|
|
// than aborting the whole compile — otherwise every OSM edit blocks the
|
|
// pipeline until the file is hand-pruned, one error message at a time.
|
|
const validated = validateOverrides(overrides, model, { skipStaleTargets: true });
|
|
for (const item of validated.stale)
|
|
console.warn(`[warning] 忽略失效的 override(目标已不存在):${item.id} -> ${item.target}`);
|
|
fs.mkdirSync(area.outputs.pipelineDir, { recursive: true });
|
|
// Direct edits resolve against the model *after* v1 overrides, then feed
|
|
// compileGeometry. An area with no v2 document resolves to an empty result,
|
|
// which leaves the geometry byte-identical to a compile without this stage.
|
|
const directEdits = input.editsFile ? loadEditDocument(input.editsFile) : null;
|
|
const directEdit = resolveDirectEditConstraints(model, directEdits, {
|
|
compilerGeometryVersion: GEOMETRY_VERSION,
|
|
});
|
|
const compiled = compileGeometry(model, overrides, {
|
|
edgeLines: area.nativeRoad.edgeLines,
|
|
junctionTemplates: area.nativeRoad.junctionTemplates,
|
|
directEdit,
|
|
});
|
|
compiled.diagnostics.push(...directEdit.diagnostics);
|
|
compiled.diagnostics.push(
|
|
...validated.stale.map((item) => ({
|
|
id: `diagnostic:stale-override:${item.id}`,
|
|
severity: 'warning',
|
|
subjectId: item.id,
|
|
sourceIds: [],
|
|
rule: 'stale-override-target',
|
|
message: `该设置指向的 ${item.kind} 目标 ${item.target} 已不存在(OSM 改动后 id 失效),本次编译已忽略。可在工作台重新设置,或从 native-road-overrides.json 中删除。`,
|
|
geometry: null,
|
|
})),
|
|
);
|
|
const signalDocument = loadOrGenerate(
|
|
area.outputs.nativeTrafficSignals,
|
|
fs.readFileSync(area.input, 'utf8'),
|
|
compiled.vehicleStopLines,
|
|
compiled.intersectionSurface,
|
|
);
|
|
const signalRuntime = runtime(signalDocument);
|
|
// Persist validation normalization, including one-time legacy heading migration.
|
|
writeJsonAtomic(area.outputs.nativeTrafficSignals, signalDocument);
|
|
const staging = fs.mkdtempSync(path.join(area.outputs.pipelineDir, 'native-road-'));
|
|
try {
|
|
const result = {
|
|
schema: 'native-road-compiled/v1',
|
|
areaId: area.id,
|
|
source: {
|
|
osm: area.input,
|
|
overrides: area.outputs.nativeRoadOverrides,
|
|
trafficSignals: area.outputs.nativeTrafficSignals,
|
|
},
|
|
model: { roads: model.roads, endpoints: model.endpoints, connections: model.connections },
|
|
movements: compiled.movements,
|
|
trafficSignals: {
|
|
assemblies: 'traffic-signal-assemblies.json',
|
|
runtime: 'traffic-signals.json',
|
|
count: signalRuntime.signals.length,
|
|
},
|
|
diagnostics: compiled.diagnostics,
|
|
layers: Object.fromEntries(LAYER_REGISTRY.map((layer) => [layer.key, `layers/${layer.source}.geojson`])),
|
|
};
|
|
const comparison = compareOsm2Streets(area, result.model, compiled);
|
|
writeJsonAtomic(path.join(staging, 'compiled.json'), result);
|
|
writeJsonAtomic(path.join(staging, 'diagnostics.json'), {
|
|
schema: 'native-road-diagnostics/v1',
|
|
diagnostics: compiled.diagnostics,
|
|
});
|
|
writeJsonAtomic(path.join(staging, 'comparison.json'), comparison);
|
|
writeJsonAtomic(path.join(staging, 'traffic-signal-assemblies.json'), signalDocument.assemblies);
|
|
writeJsonAtomic(path.join(staging, 'traffic-signals.json'), signalRuntime);
|
|
for (const layer of LAYER_REGISTRY)
|
|
writeJsonAtomic(path.join(staging, 'layers', `${layer.source}.geojson`), compiled[layer.key]);
|
|
const manifest = manifestForArea(area.id);
|
|
validatePublishedLayers(staging, manifest);
|
|
writeJsonAtomic(path.join(staging, 'manifest.json'), manifest);
|
|
fs.rmSync(area.outputs.nativeRoadDir, { recursive: true, force: true });
|
|
fs.renameSync(staging, area.outputs.nativeRoadDir);
|
|
return { area, result, comparison };
|
|
} catch (error) {
|
|
fs.rmSync(staging, { recursive: true, force: true });
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
function compareOsm2Streets(area, model, compiled) {
|
|
const source = area.outputs.geojsonDir ? path.join(area.outputs.geojsonDir, 'road_surface.geojson') : null;
|
|
let featureCount = null;
|
|
if (source && fs.existsSync(source)) {
|
|
const collection = JSON.parse(fs.readFileSync(source, 'utf8'));
|
|
featureCount = Array.isArray(collection.features) ? collection.features.length : null;
|
|
}
|
|
const diagnosticsBySeverity = {};
|
|
const diagnosticsByRule = {};
|
|
for (const item of compiled.diagnostics) {
|
|
diagnosticsBySeverity[item.severity] = (diagnosticsBySeverity[item.severity] || 0) + 1;
|
|
diagnosticsByRule[item.rule] = (diagnosticsByRule[item.rule] || 0) + 1;
|
|
}
|
|
const dangling = compiled.diagnostics.filter((item) => item.rule === 'unconnected-interior-road-end');
|
|
const junctions = compiled.intersectionSurface.features;
|
|
const fallbackJunctions = junctions.filter(
|
|
(feature) => feature.properties.boundary_mode === 'connector-convex-fallback',
|
|
);
|
|
return {
|
|
schema: 'native-road-comparison/v2',
|
|
nativeRoadCount: model.roads.length,
|
|
nativeRoadSurfaceFeatures: compiled.roadSurface.features.length,
|
|
nativeSidewalkSurfaceFeatures: compiled.sidewalkSurface.features.length,
|
|
nativeJunctionSurfaceFeatures: compiled.intersectionSurface.features.length,
|
|
nativeApproachEnvelopeJunctions: junctions.length - fallbackJunctions.length,
|
|
nativeFallbackJunctions: fallbackJunctions.length,
|
|
nativeMaxJunctionExpansionRatio: junctions.reduce(
|
|
(maximum, feature) => Math.max(maximum, Number(feature.properties.expansion_ratio) || 0),
|
|
0,
|
|
),
|
|
nativeLaneCenterlineFeatures: compiled.laneCenterlines.features.length,
|
|
nativeLaneSeparatorFeatures: compiled.laneSeparators.features.length,
|
|
nativeCenterLineFeatures: compiled.centerLines.features.length,
|
|
nativeDirectionArrowFeatures: compiled.directionArrows.features.length,
|
|
nativeTurnArrowFeatures: compiled.turnArrows.features.length,
|
|
nativeCrosswalkFeatures: compiled.crosswalks.features.length,
|
|
nativeVehicleStopLineFeatures: compiled.vehicleStopLines.features.length,
|
|
nativeConnectorFeatures: compiled.connectors.features.length,
|
|
nativeMovementCount: compiled.movements.length,
|
|
nativePublishedMovementCount: compiled.movements.filter((movement) => movement.geometryPublished).length,
|
|
nativeConnectionCount: model.connections.length,
|
|
unconnectedInteriorRoadEnds: dangling.length,
|
|
unconnectedEndsWithManualCandidates: dangling.filter((item) => item.manualCandidates?.length).length,
|
|
diagnosticsBySeverity,
|
|
diagnosticsByRule,
|
|
osm2streetsRoadSurfaceFeatures: featureCount,
|
|
osm2streetsAvailable: featureCount !== null,
|
|
note: 'Counts are coverage evidence only; geometry quality requires diagnostic and visual review.',
|
|
};
|
|
}
|
|
|
|
function validateInput(input) {
|
|
if (!input || typeof input !== 'object') throw new Error('RoadCompilerInput must be an object');
|
|
for (const key of ['areaId', 'osmFile', 'outDir', 'stagingDir', 'overridesFile', 'trafficSignalsFile']) {
|
|
if (typeof input[key] !== 'string' || input[key].trim() === '')
|
|
throw new Error(`RoadCompilerInput.${key} must be a non-empty string`);
|
|
}
|
|
if (
|
|
input.areaConfigSnapshotFile !== undefined &&
|
|
(typeof input.areaConfigSnapshotFile !== 'string' || !input.areaConfigSnapshotFile)
|
|
)
|
|
throw new Error('RoadCompilerInput.areaConfigSnapshotFile must be a non-empty string when present');
|
|
if (input.editsFile !== undefined && (typeof input.editsFile !== 'string' || !input.editsFile))
|
|
throw new Error('RoadCompilerInput.editsFile must be a non-empty string when present');
|
|
}
|
|
|
|
function validateOptions(options) {
|
|
if (!options || typeof options !== 'object') throw new Error('RoadCompilerInput.options must be an object');
|
|
if (typeof options.edgeLines !== 'boolean') throw new Error('RoadCompilerInput.options.edgeLines must be a boolean');
|
|
if (!options.junctionTemplates || typeof options.junctionTemplates !== 'object')
|
|
throw new Error('RoadCompilerInput.options.junctionTemplates must be an object');
|
|
}
|
|
|
|
module.exports = { compileInput, validateInput, validateOptions };
|