feat: add participant runtime simulation with traffic signal scheduling

- Implement deterministic participant simulation in cesium-preview.js with
  fixed-seed arrival, IDM car-following, stop-line constraints, and
  geometric conflict occupancy detection
- Build native traffic simulation participants from road package data
  including signal phase mapping, crosswalk centerlines, and lane routing
- Add participant runtime regression test covering 600 s simulation,
  green-only releases, and 2D bounding box overlap checks
- Update model URI prefix to _preview/ so simulation JSON resolves assets
  relative to area output directory
- Sync Trellis spec and task docs for participant scheduling contract
This commit is contained in:
que01 committed 2026-10-10 16:07:00 +08:00
1 parent c1277af16a
commit 7ce412e52e
10 files changed
+1587 -43

No files matched your search

+568 -32
View File
@@ -39,7 +39,7 @@
// from a control the user just touched. Keep the summary so the transient
// note can be replaced instead of destroying it.
let baseStatus = "";
const PREVIEW_BACKGROUND = "#d9e0e2";
const PREVIEW_BACKGROUND = "#02050A";
Cesium.Ion.defaultAccessToken = "";
@@ -55,14 +55,16 @@
setLoadingMessage("Loading model", config.glbName || "");
const assets = await loadSceneAssets(viewer, metadata, placement);
const trafficStart = Cesium.JulianDate.now();
const trafficEpochMs = performance.now();
const useLiveV2x = Boolean(config.v2xPreview?.enabled);
const trafficSignals = useLiveV2x
? createLiveTrafficSignals(signalData, assets)
: addTrafficSignals(viewer, signalData, trafficStart, assets);
if (useLiveV2x) hideUnconfirmedSignalAssets(assets);
const cruise = useLiveV2x
? createLiveVehicleState()
: addVehicleCruises(viewer, routeData, signalData, trafficStart, config.vehicleModelNames, config.vehicleModelName);
// The native signal cycle is the local fallback and must remain visible
// when the optional V2X overlay has no websocket connection.
const trafficSignals = addTrafficSignals(viewer, signalData, trafficStart, assets, routeData?.signalPlan, trafficEpochMs);
// Keep the deterministic native intersection simulation visible even when
// the optional V2X overlay is enabled. The overlay may add live entities,
// but an unavailable websocket must not replace the local traffic layer
// with an empty state.
const cruise = addVehicleCruises(viewer, routeData, signalData, trafficStart, config.vehicleModelNames, config.vehicleModelName, trafficEpochMs);
const cameras = createCameraPresets(viewer, metadata, placement, cruise);
const v2xOverlay = typeof window.createV2xCesiumOverlay === "function"
? window.createV2xCesiumOverlay({
@@ -81,6 +83,7 @@
bindVehicleInfoCard(viewer, cruise);
startDiagnostics(viewer, metadata, assets, cruise, placement, trafficSignals, v2xOverlay);
cameras.overview();
cameras.startAutoOrbit();
baseStatus = summaryText(metadata, assets, cruise);
setStatus(baseStatus);
setLoadingMessage("Preparing view", "finalizing materials");
@@ -121,8 +124,8 @@
geocoder: false,
navigationHelpButton: false,
sceneModePicker: false,
homeButton: true,
fullscreenButton: true,
homeButton: false,
fullscreenButton: false,
infoBox: false,
selectionIndicator: false,
baseLayer: false
@@ -135,6 +138,12 @@
viewer.scene.sun.show = false;
viewer.scene.moon.show = false;
viewer.scene.globe.baseColor = Cesium.Color.fromCssColorString(PREVIEW_BACKGROUND);
viewer.scene.screenSpaceCameraController.enableTranslate = false;
viewer.scene.screenSpaceCameraController.maximumTranslateFactor = 0.0;
viewer.canvas.addEventListener("mousedown", (event) => {
if (event.button === 1 || event.shiftKey) event.preventDefault();
});
viewer.canvas.addEventListener("contextmenu", (event) => event.preventDefault());
return viewer;
}
@@ -436,6 +445,10 @@
!semanticAssets(assets).some((asset) => asset.id === "vegetation")) {
toggleBuildingGhost.disabled = true;
}
// Keep the intersection readable by default: the building shell is
// translucent while roads, signals and participants remain visible.
toggleBuildingGhost.checked = !toggleBuildingGhost.disabled;
if (toggleBuildingGhost.checked) void setBuildingGhost(true);
async function setViewMode(nextMode) {
if (nextMode === viewMode) return;
@@ -565,7 +578,10 @@
return stopFollow;
}
function addVehicleCruises(viewer, routeData, signalData, trafficStart, vehicleModelNames, fallbackVehicleModelName) {
function addVehicleCruises(viewer, routeData, signalData, trafficStart, vehicleModelNames, fallbackVehicleModelName, trafficEpochMs) {
if (routeData && Array.isArray(routeData.participants) && routeData.participants.length) {
return addParticipantCruises(viewer, routeData, signalData, trafficStart, trafficEpochMs);
}
const segments = ((routeData && (routeData.routes || routeData.segments)) || [])
.filter((segment) => segment.coordinates && segment.coordinates.length >= 2)
.slice(0, 5);
@@ -615,6 +631,492 @@
}
}
// ---------------------------------------------------------------------------
// Intersection participants (descriptor v2)
//
// Open routes: agents enter at the approach end, cross the junction, and
// despawn past the exit end, then respawn after a short delay. Vehicles stop
// at their own approach's red signal and follow the leader on the same
// template; pedestrians cross while their paired approach phase is red.
// ---------------------------------------------------------------------------
function addParticipantCruises(viewer, routeData, signalData, trafficStart, trafficEpochMs) {
const templates = routeData.participants.filter((template) => template.coordinates && template.coordinates.length >= 2);
const speed = Number(routeData.speedMetersPerSecond) || 8;
const start = trafficStart;
const simulation = createParticipantSimulation(viewer, templates, start, speed, routeData.settings || {}, routeData.signalPlan, trafficEpochMs);
viewer.clock.startTime = start.clone();
viewer.clock.currentTime = start.clone();
viewer.clock.clockRange = Cesium.ClockRange.UNBOUNDED;
viewer.clock.multiplier = 1;
viewer.clock.shouldAnimate = templates.length > 0;
const vehicles = simulation.agents.map((agent, index) => {
const template = agent.template;
const routeEntity = viewer.entities.add({
name: "Participant route " + (index + 1),
polyline: {
positions: Cesium.Cartesian3.fromDegreesArrayHeights(
template.coordinates.flatMap((coord) => [coord[0], coord[1], ROUTE_LINE_HEIGHT_METERS])
),
width: 2,
material: participantRouteColor(index),
arcType: Cesium.ArcType.NONE,
clampToGround: false
}
});
routeEntity.show = false;
const entity = viewer.entities.add({
name: "Participant " + (index + 1),
position: agent.positions,
orientation: openRouteOrientationFromState(agent.route, agent.state, agent.speed, template.headingOffsetDegrees || 0),
model: {
uri: template.modelName,
scale: Number(template.modelScale) || 1.0,
minimumPixelSize: 0
},
show: false
});
agent.entity = entity;
const record = {
id: "participant-" + (index + 1),
entity,
routeEntity,
positions: agent.positions,
route: agent.route,
segment: { lengthMeters: template.lengthMeters, maneuvers: template.turn ? [template.turn] : [] },
label: participantLabel(template, index),
modelName: template.modelName.split("/").pop(),
status: "normal",
incidentNote: "",
motion: agent,
routeColor: participantRouteColor(index),
markerEntity: null,
};
entity.properties = new Cesium.PropertyBag({ vehicleId: record.id });
record.markerEntity = viewer.entities.add({
name: "Participant incident marker " + (index + 1),
position: agent.positions,
billboard: {
image: "",
show: false,
width: 36,
height: 44,
pixelOffset: new Cesium.Cartesian2(0, -40),
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
});
const option = document.createElement("option");
option.value = String(index);
option.textContent = record.label;
vehicleSelect.appendChild(option);
return record;
});
const cruise = {
vehicles,
baseSpeed: speed,
state: { selectedIndex: 0 },
simulation,
usingLiveData: false,
};
syncSelectedRouteVisibility(cruise);
return cruise;
}
function participantRouteColor(index) {
return [
Cesium.Color.CYAN,
Cesium.Color.LIME,
Cesium.Color.YELLOW,
Cesium.Color.ORANGE,
Cesium.Color.DEEPSKYBLUE
][index % 5];
}
function participantLabel(template, index) {
const kindLabel = { vehicle: "", motorcycle: "摩托 · ", bicycle: "骑行 · ", pedestrian: "行人 · " }[template.kind] || "";
const turn = { left: "左转", right: "右转", through: "直行" }[template.turn];
return "#" + (index + 1) + " · " + kindLabel + (turn ? turn + " · " : "") + Math.round(template.lengthMeters || 0) + " m";
}
function participantRoute(template, reversed) {
const coordinates = reversed ? [...template.coordinates].reverse() : template.coordinates;
const distances = [0.0];
for (let i = 1; i < coordinates.length; i += 1) {
distances.push(distances[i - 1] + distanceMeters(coordinates[i - 1], coordinates[i]));
}
return {
coordinates,
distances,
length: Math.max(1.0, distances[distances.length - 1]),
// Stops are pre-attached to the template by the generator; reversing a
// route is only used for pedestrians, which carry none.
stops: reversed ? [] : (template.stops || []).map((stop) => ({
distance: stop.distance,
stopReason: stop.stopReason || "traffic-signal",
signal: { id: stop.signalId, phaseGroup: stop.phaseGroup },
})),
};
}
function createParticipantSimulation(viewer, templates, start, baseSpeed, settings = {}, signalPlan, trafficEpochMs) {
const isCrossing = (agent) => agent.template.kind === "pedestrian" || agent.template.kind === "bicycle";
const entryDistance = (agent) => isCrossing(agent) ? -agent.length - minimumGapMeters : -120 - agent.length;
const exitDistance = (agent) => agent.route.length + (isCrossing(agent) ? agent.length : 120 + agent.length);
let randomState = 27092026;
function random() {
randomState = (Math.imul(randomState, 1664525) + 1013904223) >>> 0;
return (randomState + 0.5) / 4294967296;
}
function arrivalDelay(agent) {
return (isCrossing(agent) ? 12 : 4) - Math.log(1 - random()) * (isCrossing(agent) ? 18 : 7);
}
const reactionTimeSeconds = Number(settings.reactionTimeSeconds) || 0.8;
const minimumGapMeters = Number(settings.minimumGapMeters) || 6;
const agents = templates.flatMap((template, templateIndex) => {
const count = Math.max(1, Math.round(Number(template.fleet) || 1)) * (template.kind === "vehicle" ? 3 : 1);
return Array.from({ length: count }, (_, index) => {
// Crossing users share the same ordered crosswalk queue. Keeping one
// travel direction avoids head-on overlap between pedestrians and bikes.
const reversed = false;
const route = participantRoute(template, reversed);
const jitter = 0.9 + 0.2 * random();
const speed = Math.max(0.8, Math.min(14, (Number(template.speedMetersPerSecond) || baseSpeed) * jitter));
const length = Number(template.vehicleLengthMeters) || (template.kind === "pedestrian" ? 0.8 : 4.6);
const height = Number(template.heightMeters) || 0.4;
const state = {
distance: (template.kind === "pedestrian" || template.kind === "bicycle") ? -length - minimumGapMeters : -120 - length,
// Vehicles must enter the simulation from rest. Starting them at
// cruising speed made the first rendered frame look like a red-light
// violation before the controller had a chance to brake.
speed: 0,
targetSpeed: speed,
stopReason: null,
active: true,
// Stagger entries by a realistic headway so the whole fleet does
// not appear at the stop line in the same simulation second.
spawnDelay: 1 + templateIndex * 0.7 + index * (6 + random() * 5),
committed: false,
respawnDelay: 0,
lastTime: start.clone(),
};
return {
template,
route,
speed,
length,
height,
headway: 1.2 + random() * 0.6,
state,
positions: new Cesium.CallbackProperty((time, result) =>
openRoutePositionAtDistance(route, state.distance, height, result), false),
};
});
});
agents.forEach((agent, index) => { agent.agentIndex = index; });
const byTemplate = new Map();
const crossingUsersById = new Map();
agents.forEach((agent) => {
const queueKey = (agent.template.kind === "pedestrian" || agent.template.kind === "bicycle")
? (agent.template.crossingId || agent.template)
: (agent.template.approachLaneId || agent.template.id);
if (!byTemplate.has(queueKey)) byTemplate.set(queueKey, []);
byTemplate.get(queueKey).push(agent);
if (agent.template.kind === "pedestrian" || agent.template.kind === "bicycle") {
const crossingId = agent.template.crossingId;
if (!crossingUsersById.has(crossingId)) crossingUsersById.set(crossingId, []);
crossingUsersById.get(crossingId).push(agent);
}
});
// Queue outside the scene; no participant starts inside a crossing.
for (const [queueKey, peers] of byTemplate) {
if (typeof queueKey !== "string" || peers.length < 2) continue;
peers.sort((a, b) => a.agentIndex - b.agentIndex);
// Crossing users enter from the near edge. Seeding them at the far end
// would mark the whole zebra crossing occupied before the first signal
// phase and make every approach yield indefinitely.
let occupied = 0;
for (const agent of peers) {
agent.state.distance = entryDistance(agent) - occupied;
occupied += agent.length + minimumGapMeters;
}
}
// Cache geometric conflicts once. Reservations cover only the junction,
// not distant approach lanes. A released movement retains priority until
// its rear clears the shared trajectory.
const movementConflicts = new Map();
for (const agent of agents.filter((candidate) => !isCrossing(candidate))) {
const entries = [];
for (const other of agents.filter((candidate) => !isCrossing(candidate))) {
if (agent === other || agent.template.approachLaneId === other.template.approachLaneId) continue;
let conflict = null;
for (let i = 0; i < agent.route.coordinates.length; i += 1) {
if (agent.route.distances[i] < (agent.route.stops[0]?.distance || 0) + agent.length + 3) continue;
for (let j = 0; j < other.route.coordinates.length; j += 1) {
if (other.route.distances[j] < (other.route.stops[0]?.distance || 0) + other.length + 3) continue;
if (distanceMeters(agent.route.coordinates[i], other.route.coordinates[j]) < 3.5) {
conflict = { other, distance: agent.route.distances[i], otherDistance: other.route.distances[j] };
}
}
}
if (conflict) entries.push(conflict);
}
movementConflicts.set(agent, entries);
}
const update = (clock) => {
const elapsed = Cesium.JulianDate.secondsDifference(clock.currentTime, agents[0]?.state.lastTime || start);
if (!(elapsed > 0) || elapsed > 2) {
for (const agent of agents) Cesium.JulianDate.clone(clock.currentTime, agent.state.lastTime);
return;
}
for (const peers of byTemplate.values()) {
peers.sort((a, b) => a.state.distance - b.state.distance);
}
const trafficElapsed = Math.max(0, (performance.now() - trafficEpochMs) / 1000);
const elapsedFromStart = Cesium.JulianDate.secondsDifference(clock.currentTime, start);
const present = (agent) => agent.state.active && elapsedFromStart >= agent.state.spawnDelay;
const ordered = [...agents].sort((a, b) => b.state.distance - a.state.distance);
for (const agent of ordered) {
const state = agent.state;
Cesium.JulianDate.clone(clock.currentTime, state.lastTime);
const ready = elapsedFromStart >= state.spawnDelay;
if (agent.entity) agent.entity.show = state.active && ready && toggleVehicles.checked;
if (!ready) continue;
if (state.isMoving && !state.isMoving()) {
state.speed = 0;
state.stopReason = "incident";
continue;
}
if (!state.active) {
state.respawnDelay -= elapsed;
if (state.respawnDelay <= 0) {
const entryBlocked = agents.some((other) => other !== agent && present(other)
&& (other.template.approachLaneId || other.template.crossingId) === (agent.template.approachLaneId || agent.template.crossingId)
&& other.state.distance < entryDistance(agent) + agent.length + other.length + minimumGapMeters);
if (entryBlocked) continue;
state.active = true;
state.committed = false;
state.distance = entryDistance(agent);
state.speed = 0;
}
continue;
}
const route = agent.route;
const controlStop = route.stops[0] || null;
let target = agent.speed;
let stopReason = null;
let crossingOccupied = false;
let crossingYieldDistance = null;
let boundary = Infinity;
if (agent.template.kind === "pedestrian" || agent.template.kind === "bicycle") {
// Walk only while the paired approach phase is red; once started,
// finish the crossing regardless of the phase clock.
const group = Number(agent.template.phaseGroup);
const phaseState = Number.isFinite(group) ? signalPhaseAtElapsed(group, trafficElapsed, signalPlan) : null;
const clearanceSeconds = agent.route.length / agent.speed + agent.speed / 1.4 + 3;
const occupiedByVehicle = agents.some((other) => !isCrossing(other) && present(other)
&& other.state.committed && (other.template.crossingConflicts || []).some((conflict) =>
conflict.crossingId === agent.template.crossingId
// Permission to enter is a reservation until the vehicle's rear
// clears this crossing, including the whole turning movement.
&& other.state.distance < conflict.distance + other.length + 3));
if (!state.committed && (!phaseState || phaseState.active !== "red" || phaseState.initialClearance
|| phaseState.remaining < clearanceSeconds || occupiedByVehicle)) {
boundary = -0.5;
stopReason = "pedestrian-signal";
}
} else {
const conflicts = agent.template.crossingConflicts || [];
for (const conflict of conflicts) {
// A crossing that is already behind the vehicle cannot make it
// stop again. This matters for left turns: after clearing the
// first zebra, a phase change must not freeze the vehicle on the
// downstream approach.
if (!(Number.isFinite(conflict.distance) && conflict.distance > state.distance + 0.25)) continue;
const crossingUsers = crossingUsersById.get(conflict.crossingId) || [];
const occupied = crossingUsers.some((candidate) => present(candidate) && candidate.state.committed
&& candidate.state.distance >= 0
&& candidate.state.distance < candidate.route.length + candidate.length);
if (occupied && (crossingYieldDistance === null || conflict.distance < crossingYieldDistance)) {
crossingYieldDistance = conflict.distance;
}
}
crossingOccupied = crossingYieldDistance !== null;
if (crossingOccupied) {
boundary = Math.min(boundary, crossingYieldDistance - agent.length / 2 - 2);
const remaining = crossingYieldDistance - state.distance - 1.0;
const decel = Number(agent.template.decelerationMetersPerSecondSquared) || 3.5;
target = Math.min(target, Math.sqrt(Math.max(0, 2 * decel * Math.max(0, remaining))));
stopReason = "pedestrian-crossing";
// Even a vehicle already committed to the junction must yield to
// an occupied zebra crossing; it stops in place, never teleports.
}
if (controlStop && !state.committed) {
const phase = signalPhaseAtElapsed(controlStop.signal.phaseGroup, trafficElapsed, signalPlan).active;
const junctionBlocked = (movementConflicts.get(agent) || []).some((conflict) => present(conflict.other)
&& conflict.other.state.committed
&& conflict.other.state.distance < conflict.otherDistance + conflict.other.length + 3);
const exitBlocked = agents.some((other) => other !== agent && !isCrossing(other) && present(other)
&& other.state.committed && agent.template.exitRoadId && other.template.exitRoadId === agent.template.exitRoadId
&& other.state.speed < 0.5 && other.state.distance < other.route.length + other.length + minimumGapMeters);
if (phase !== "green" || crossingOccupied || junctionBlocked || exitBlocked) {
boundary = Math.min(boundary, controlStop.distance);
// Keep the same controlling stop active at and before the line.
// Do not search only for a stop ahead: that made it disappear
// exactly when the vehicle reached it, allowing red-light runs.
const remaining = Math.max(0, controlStop.distance - state.distance);
const decel = Number(agent.template.decelerationMetersPerSecondSquared) || 3.5;
const stoppingSpeed = Math.sqrt(Math.max(0, 2 * decel * Math.max(0, remaining - 0.8)));
target = Math.min(target, stoppingSpeed);
stopReason = junctionBlocked || exitBlocked ? "junction-clearance" : crossingOccupied ? "pedestrian-crossing" : "traffic-signal";
}
}
if (agent.template.turn && agent.template.turn !== "through"
&& state.distance > (controlStop?.distance || 0) && state.distance < route.length * 0.85) {
target = Math.min(target, agent.template.turn === "left" ? 4.5 : 3.5);
}
}
const queueKey = (agent.template.kind === "pedestrian" || agent.template.kind === "bicycle")
? (agent.template.crossingId || agent.template)
: (agent.template.approachLaneId || agent.template.id);
const peers = byTemplate.get(queueKey) || [];
let leaderAgent = null;
const leader = peers.filter((candidate) => candidate !== agent && present(candidate)
&& candidate.state.distance > state.distance).sort((a, b) => a.state.distance - b.state.distance)[0];
if (leader) {
leaderAgent = leader;
const centerGap = leader.state.distance - state.distance;
const crossingAgent = agent.template.kind === "pedestrian" || agent.template.kind === "bicycle";
const gapBuffer = crossingAgent ? 1.5 : minimumGapMeters;
const requiredGap = (leader.length + agent.length) / 2 + gapBuffer + state.speed * reactionTimeSeconds;
if (centerGap < requiredGap + 10) {
target = Math.min(target, Math.max(0, (centerGap - (leader.length + agent.length) / 2 - gapBuffer) / Math.max(reactionTimeSeconds, 0.1)));
if (target < 0.2) stopReason = stopReason || "leader-gap";
}
}
state.targetSpeed = target;
const accel = Number(agent.template.accelerationMetersPerSecondSquared) || 1.8;
const decel = Number(agent.template.decelerationMetersPerSecondSquared) || 3.5;
// Intelligent Driver Model: free acceleration plus a speed-dependent
// desired gap. Treat a waiting boundary as a stationary virtual leader.
let gap = boundary - state.distance;
let leaderSpeed = 0;
if (leaderAgent && leaderAgent.state.distance - state.distance - (leaderAgent.length + agent.length) / 2 < gap) {
gap = leaderAgent.state.distance - state.distance - (leaderAgent.length + agent.length) / 2;
leaderSpeed = leaderAgent.state.speed;
}
const desiredGap = (isCrossing(agent) ? 0.5 : 2.5) + Math.max(0,
state.speed * agent.headway + state.speed * (state.speed - leaderSpeed) / (2 * Math.sqrt(accel * decel)));
const acceleration = accel * (1 - (state.speed / Math.max(0.1, target)) ** 4
- (Number.isFinite(gap) ? (desiredGap / Math.max(0.1, gap)) ** 2 : 0));
state.speed = Math.max(0, state.speed + Math.max(-decel, Math.min(accel, acceleration)) * elapsed);
let nextDistance = state.distance + Math.max(0, state.speed) * elapsed;
if (leaderAgent) {
const crossingAgent = agent.template.kind === "pedestrian" || agent.template.kind === "bicycle";
const physicalGap = (leaderAgent.length + agent.length) / 2 + (crossingAgent ? 1.5 : minimumGapMeters);
nextDistance = Math.min(nextDistance, Math.max(state.distance, leaderAgent.state.distance - physicalGap));
}
if (Number.isFinite(boundary)) {
nextDistance = Math.min(nextDistance, Math.max(state.distance, boundary));
if (nextDistance >= boundary - 0.05) state.speed = 0;
}
state.distance = nextDistance;
if (controlStop && !state.committed) {
const phase = signalPhaseAtElapsed(controlStop.signal.phaseGroup, trafficElapsed, signalPlan).active;
if (phase === "green" && nextDistance > controlStop.distance) {
state.committed = true;
}
}
if (isCrossing(agent) && state.distance >= 0) state.committed = true;
state.stopReason = state.speed < 0.25 ? stopReason : null;
if (state.distance >= exitDistance(agent)) {
state.active = false;
state.speed = 0;
// Crossing users are occasional arrivals, not a continuous stream.
// Keep the route reusable while leaving a realistic gap between
// successive pedestrians/cyclists.
state.respawnDelay = arrivalDelay(agent);
}
}
};
viewer.clock.onTick.addEventListener(update);
return {
agents,
settings: { reactionTimeSeconds, minimumGapMeters },
diagnostics() {
const live = agents.filter((agent) => agent.state.active);
return {
stoppedVehicles: live.filter((agent) => agent.state.stopReason).length,
queueLength: live.filter((agent) => agent.state.stopReason === "leader-gap").length,
activeVehicles: live.length,
pedestrians: live.filter((agent) => agent.template.kind === "pedestrian").length,
};
},
};
}
// Open-route variant of routePositionAtDistance: no wraparound; distances
// outside [0, length] extrapolate along the first/last segment, and the
// model height comes from the participant template.
function openRoutePositionAtDistance(route, distance, heightMeters, result) {
let index = 1;
while (index < route.distances.length - 1 && route.distances[index] < distance) {
index += 1;
}
const prevDist = route.distances[index - 1];
const nextDist = route.distances[index];
const t = nextDist > prevDist ? (distance - prevDist) / (nextDist - prevDist) : 0;
const a = route.coordinates[index - 1];
const b = route.coordinates[index];
const lon = a[0] + (b[0] - a[0]) * t;
const lat = a[1] + (b[1] - a[1]) * t;
return Cesium.Cartesian3.fromDegrees(lon, lat, heightMeters, Cesium.Ellipsoid.WGS84, result);
}
function openRouteOrientationFromState(route, state, speed, yawDegrees) {
const correction = Cesium.Quaternion.fromAxisAngle(
Cesium.Cartesian3.UNIT_Z,
Cesium.Math.toRadians(yawDegrees)
);
const current = new Cesium.Cartesian3();
const ahead = new Cesium.Cartesian3();
const direction = new Cesium.Cartesian3();
const up = new Cesium.Cartesian3();
const east = new Cesium.Cartesian3();
const north = new Cesium.Cartesian3();
const hpr = new Cesium.HeadingPitchRoll(0.0, 0.0, 0.0);
const base = new Cesium.Quaternion();
return new Cesium.CallbackProperty((time, result) => {
openRoutePositionAtDistance(route, state.distance, 0, current);
const lookAhead = Math.max(0.8, speed * 0.8);
// Position and heading share the open route's endpoint extrapolation.
// Clamping only the forward sample points behind an exiting vehicle.
openRoutePositionAtDistance(route, state.distance + lookAhead, 0, ahead);
Cesium.Cartesian3.subtract(ahead, current, direction);
if (Cesium.Cartesian3.magnitudeSquared(direction) < 1e-9) return result;
Cesium.Cartesian3.normalize(direction, direction);
Cesium.Cartesian3.normalize(current, up);
Cesium.Cartesian3.cross(Cesium.Cartesian3.UNIT_Z, up, east);
if (Cesium.Cartesian3.magnitudeSquared(east) < 1e-9) {
Cesium.Cartesian3.clone(Cesium.Cartesian3.UNIT_X, east);
} else {
Cesium.Cartesian3.normalize(east, east);
}
Cesium.Cartesian3.cross(up, east, north);
Cesium.Cartesian3.normalize(north, north);
hpr.heading = Math.atan2(Cesium.Cartesian3.dot(direction, east), Cesium.Cartesian3.dot(direction, north));
Cesium.Transforms.headingPitchRollQuaternion(current, hpr, undefined, undefined, base);
return Cesium.Quaternion.multiply(base, correction, result || new Cesium.Quaternion());
}, false);
}
function createLiveVehicleState() {
return {
vehicles: [],
@@ -697,7 +1199,7 @@
return { count: signals.length, state, update, set show(value) { if (dynamic?.model) dynamic.model.show = Boolean(value && state.live); } };
}
function addTrafficSignals(viewer, signalData, start, assets) {
function addTrafficSignals(viewer, signalData, start, assets, signalPlan, trafficEpochMs) {
const dynamic = assets.find((asset) => asset.category === "dynamic" && asset.model);
const countdownModels = new Map(assets
.filter((asset) => asset.category === "countdown" && asset.model)
@@ -705,7 +1207,6 @@
if (dynamic && countdownModels.size === 2) {
const signals = (signalData?.signals || []).filter((signal) => signal && signal.id);
if (signals.length && !viewer.clock.shouldAnimate) viewer.clock.shouldAnimate = true;
const visualStart = performance.now();
const phaseTime = new Cesium.JulianDate();
const state = { elapsedSeconds: 0, phase: "" };
const entities = [];
@@ -743,7 +1244,7 @@
const groupPhases = new Map();
for (const signal of signals) {
const nodeKey = signal.nodeKey || signal.id;
const phase = signalPhase(signal.phaseGroup, phaseTime, start);
const phase = signalPhaseAtElapsed(signal.phaseGroup, elapsedSeconds, signalPlan);
groupPhases.set(signal.phaseGroup, phase.active);
if (signal === signals[0]) state.phase = `${phase.active} ${String(phase.remaining).padStart(2, "0")}`;
for (const state of ["red", "yellow", "green"]) {
@@ -775,7 +1276,7 @@
};
let lastSecond = -1;
const render = () => {
const elapsedSeconds = Math.floor((performance.now() - visualStart) / 1000);
const elapsedSeconds = Math.floor(Math.max(0, performance.now() - trafficEpochMs) / 1000);
if (elapsedSeconds === lastSecond) return;
lastSecond = elapsedSeconds;
state.elapsedSeconds = elapsedSeconds;
@@ -823,16 +1324,25 @@
return signalPhaseAtElapsed(group, Cesium.JulianDate.secondsDifference(time, start));
}
function signalPhaseAtElapsed(group, elapsed) {
const second = ((elapsed % 20) + 20) % 20;
if (group === 0) {
if (second < 8) return { active: "green", remaining: Math.ceil(8 - second) };
if (second < 10) return { active: "yellow", remaining: Math.ceil(10 - second) };
return { active: "red", remaining: Math.ceil(20 - second) };
}
if (second < 10) return { active: "red", remaining: Math.ceil(10 - second) };
if (second < 18) return { active: "green", remaining: Math.ceil(18 - second) };
return { active: "yellow", remaining: Math.ceil(20 - second) };
function signalPhaseAtElapsed(group, elapsed, signalPlan) {
const plan = signalPlan || {
cycleSeconds: 60,
initialAllRedSeconds: 5,
groups: {
0: [{ from: 0, to: 25, state: "green" }, { from: 25, to: 28, state: "yellow" }, { from: 28, to: 60, state: "red" }],
1: [{ from: 0, to: 32, state: "red" }, { from: 32, to: 57, state: "green" }, { from: 57, to: 60, state: "yellow" }],
},
};
const initialAllRedSeconds = Math.max(0, Number(plan.initialAllRedSeconds) || 0);
if (elapsed < initialAllRedSeconds) return { active: "red", remaining: Math.ceil(initialAllRedSeconds - elapsed), initialClearance: true };
const cycleSeconds = Number(plan.cycleSeconds) || 20;
const intervals = plan.groups?.[String(Number(group))] || plan.groups?.[Number(group)];
if (!Array.isArray(intervals) || !intervals.length) return { active: "red", remaining: 0 };
const cycleElapsed = elapsed - initialAllRedSeconds;
const second = ((cycleElapsed % cycleSeconds) + cycleSeconds) % cycleSeconds;
const interval = intervals.find((candidate) => second >= candidate.from && second < candidate.to);
if (!interval) return { active: "red", remaining: 0 };
return { active: interval.state, remaining: Math.ceil(interval.to - second) };
}
function selectedVehicleModelName(modelNames, fallbackModelName) {
@@ -1374,8 +1884,14 @@
}
function createCameraPresets(viewer, metadata, placement, cruise) {
const radius = Math.max(220.0, boundsRadiusMeters(metadata.bounds) || 900.0);
const center = placement.position;
const configuredCenter = Array.isArray(config.simulationCenter) && config.simulationCenter.length >= 2
? config.simulationCenter.map(Number)
: null;
const center = configuredCenter && configuredCenter.every(Number.isFinite)
? Cesium.Cartesian3.fromDegrees(configuredCenter[0], configuredCenter[1], placement.height)
: placement.position;
const radius = Math.max(40.0, Number(config.cameraRadiusMeters) || 105.0);
let autoOrbit = null;
function lookAt(range, headingDegrees, pitchDegrees) {
viewer.camera.lookAt(
center,
@@ -1385,15 +1901,13 @@
range
)
);
// lookAt locks the camera into the target's reference frame; release it
// so orbit and pan keep working from the new vantage point.
// Release the temporary target frame after positioning the camera so
// Cesium's normal orbit and zoom controls remain available.
viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
}
return {
overview() {
viewer.camera.flyToBoundingSphere(new Cesium.BoundingSphere(center, radius), {
duration: 0.0
});
lookAt(radius, 135.0, -32.0);
},
oblique() {
lookAt(radius * 0.92, 135.0, -28.0);
@@ -1414,6 +1928,28 @@
},
duration: 0.0
});
},
startAutoOrbit() {
if (autoOrbit) return;
let headingDegrees = 135.0;
let lastTime = performance.now();
const onPointerDown = () => {
if (!autoOrbit) return;
viewer.scene.preRender.removeEventListener(autoOrbit);
viewer.canvas.removeEventListener("pointerdown", onPointerDown);
autoOrbit = null;
viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
};
autoOrbit = () => {
const now = performance.now();
const elapsed = Math.min(0.1, Math.max(0, (now - lastTime) / 1000));
lastTime = now;
headingDegrees = (headingDegrees + elapsed * 4.0) % 360.0;
lookAt(radius, headingDegrees, -32.0);
};
viewer.scene.preRender.addEventListener(autoOrbit);
viewer.canvas.addEventListener("pointerdown", onPointerDown, { once: true });
autoOrbit();
}
};
}