代码
// ======================= 赛事参数(时间单位:鸣枪后秒数) =======================
const RACE = 42195;
const RUNNERS = 30000;
const GUN = 7.5 * 3600; // 07:30 鸣枪
const T_MIN = -600;
const T_MAX = 6 * 3600 + 600;
const CUTOFF = 6 * 3600; // 关门时间
const SWEEP_START = 1800; // 收容车出发时间
const SWEEP_V = RACE / (CUTOFF - SWEEP_START); // 收容车匀速,关门时到达终点
const WALL = 30000; // 30 km 后开始掉速
const BIN = 50; // 热力按 50 m 分段聚合

const $ = (id) => document.getElementById(id);
const pad = (n) => String(n).padStart(2, '0');
const km = (d) => (d / 1000).toFixed(1);
const fc = (features) => ({type: 'FeatureCollection', features});
const pointFeature = (coord, properties = {}) => ({
  type: 'Feature',
  geometry: {type: 'Point', coordinates: coord},
  properties,
});

function clockText(t, withSec) {
  const s = Math.round(GUN + t);
  return (
    pad(Math.floor(s / 3600)) +
    ':' +
    pad(Math.floor((s % 3600) / 60)) +
    (withSec ? ':' + pad(s % 60) : '')
  );
}
function durationText(sec) {
  sec = Math.max(0, Math.round(sec));
  return Math.floor(sec / 3600) + ':' + pad(Math.floor((sec % 3600) / 60)) + ':' + pad(sec % 60);
}
function upperBound(arr, x) {
  let lo = 0;
  let hi = arr.length;
  while (lo < hi) {
    const mid = (lo + hi) >> 1;
    if (arr[mid] <= x) {
      lo = mid + 1;
    } else {
      hi = mid;
    }
  }
  return lo;
}
function mulberry32(seed) {
  return function () {
    seed |= 0;
    seed = (seed + 0x6d2b79f5) | 0;
    let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}
const rnd = mulberry32(20261023);
const gauss = () => Math.sqrt(-2 * Math.log(1 - rnd())) * Math.cos(2 * Math.PI * rnd());

// ======================= 赛道:里程 → 坐标 =======================
const ROUTE = window.MARATHON_ROUTE;
const cumLen = [0];
for (let i = 1; i < ROUTE.length; i++) {
  const [a, b] = [ROUTE[i - 1], ROUTE[i]];
  const dx = (b[0] - a[0]) * 111320 * Math.cos((a[1] * Math.PI) / 180);
  const dy = (b[1] - a[1]) * 111320;
  cumLen.push(cumLen[i - 1] + Math.hypot(dx, dy));
}
const routeLen = cumLen[cumLen.length - 1];

function pointAt(d) {
  const g = Math.max(0, Math.min(1, d / RACE)) * routeLen;
  let lo = 0;
  let hi = cumLen.length - 1;
  while (hi - lo > 1) {
    const mid = (lo + hi) >> 1;
    if (cumLen[mid] <= g) {
      lo = mid;
    } else {
      hi = mid;
    }
  }
  const f = (g - cumLen[lo]) / (cumLen[hi] - cumLen[lo] || 1);
  return [
    ROUTE[lo][0] + (ROUTE[hi][0] - ROUTE[lo][0]) * f,
    ROUTE[lo][1] + (ROUTE[hi][1] - ROUTE[lo][1]) * f,
  ];
}

// ======================= 跑者 =======================
// 每名跑者的位置都是时间的解析函数,时间轴可以任意拖动
const startDelay = new Float32Array(RUNNERS); // 出发区排队时间
const pace1 = new Float32Array(RUNNERS); // 30 km 前配速(秒/米)
const pace2 = new Float32Array(RUNNERS); // 30 km 后配速
const wallTime = new Float32Array(RUNNERS);
const finishTime = new Float32Array(RUNNERS);
const quitTime = new Float32Array(RUNNERS);
const quitDist = new Float32Array(RUNNERS);
const sweptTime = new Float32Array(RUNNERS);

const sweepAt = (t) => Math.max(0, Math.min(RACE, (t - SWEEP_START) * SWEEP_V));
function distAt(i, t) {
  if (t <= startDelay[i]) {
    return 0;
  }
  if (t <= wallTime[i]) {
    return (t - startDelay[i]) / pace1[i];
  }
  return Math.min(RACE, WALL + (t - wallTime[i]) / pace2[i]);
}
function timeAt(i, d) {
  return d <= WALL ? startDelay[i] + d * pace1[i] : wallTime[i] + (d - WALL) * pace2[i];
}
// 跑者两段匀速、收容车匀速,逐段求被追上的最早时刻
function catchTime(i) {
  const segs = [
    [startDelay[i], wallTime[i], 0, 1 / pace1[i]],
    [wallTime[i], wallTime[i] + (RACE - WALL) * pace2[i], WALL, 1 / pace2[i]],
  ];
  for (const [t0, t1, d0, v] of segs) {
    const lo = Math.max(t0, SWEEP_START);
    if (lo >= t1) {
      continue;
    }
    const gap = d0 + (lo - t0) * v - sweepAt(lo);
    if (gap <= 0) {
      return lo;
    }
    if (v < SWEEP_V) {
      const tc = lo + gap / (SWEEP_V - v);
      if (tc < t1) {
        return tc;
      }
    }
  }
  return Infinity;
}

const targetTime = new Float32Array(RUNNERS);
(function initRunners() {
  const order = [];
  for (let i = 0; i < RUNNERS; i++) {
    let T =
      rnd() < 0.005
        ? (2.1 + rnd() * 0.55) * 3600
        : Math.exp(Math.log(4.42 * 3600) + 0.17 * gauss());
    T = Math.max(2.1 * 3600, Math.min(7 * 3600, T));
    const slow = Math.min(1, Math.max(0, (T - 2.1 * 3600) / (4.5 * 3600)));
    const fade = 0.02 + (0.06 + 0.22 * slow) * rnd();
    targetTime[i] = T;
    pace1[i] = T / (WALL + (RACE - WALL) * (1 + fade));
    pace2[i] = pace1[i] * (1 + fade);
    order.push(i);
  }
  // 按报名成绩分出发区,最后一个出发区约 25 分钟后过起点
  order.sort((a, b) => targetTime[a] - targetTime[b]);
  order.forEach((runner, rank) => {
    startDelay[runner] = (rank / RUNNERS) * 1500 + rnd() * 40;
  });
  for (let i = 0; i < RUNNERS; i++) {
    wallTime[i] = startDelay[i] + WALL * pace1[i];
    finishTime[i] = wallTime[i] + (RACE - WALL) * pace2[i];
    quitDist[i] = rnd() < 0.012 ? 5000 + 37000 * Math.sqrt(rnd()) : Infinity;
    quitTime[i] = quitDist[i] === Infinity ? Infinity : timeAt(i, quitDist[i]);
    const tc = catchTime(i);
    if (tc < quitTime[i]) {
      quitTime[i] = quitDist[i] = Infinity;
      sweptTime[i] = tc;
    } else {
      sweptTime[i] = Infinity;
    }
    if (quitTime[i] !== Infinity || sweptTime[i] !== Infinity) {
      finishTime[i] = Infinity;
    }
  }
})();
const sortedTarget = Float32Array.from(targetTime).sort();
let winner = 0;
for (let i = 1; i < RUNNERS; i++) {
  if (finishTime[i] < finishTime[winner]) {
    winner = i;
  }
}

// ======================= 补给站 =======================
// 每站保存跑者到站时刻的有序表,任意时刻的通过人数用一次二分得到
const STATION_KM = [7.5, 12.5, 17.5, 22.5, 27.5, 32.5, 37.5, 40.5];
const STOCK_FACTOR = [1.3, 1.25, 1.18, 0.93, 1.12, 0.9, 1.08, 1.2];
const STATIONS = STATION_KM.map((k, j) => {
  const d = k * 1000;
  const arrivals = [];
  for (let i = 0; i < RUNNERS; i++) {
    const t = timeAt(i, d);
    if (t < quitTime[i] && t < sweptTime[i]) {
      arrivals.push(t);
    }
  }
  arrivals.sort((a, b) => a - b);
  const rate = k >= 25 ? 1.35 : 1; // 后半程每人取水量上升
  const stock = Math.round((arrivals.length * rate * STOCK_FACTOR[j]) / 100) * 100;
  const s = {
    name: k + 'K',
    d,
    coord: pointAt(d),
    arrivals: Float32Array.from(arrivals),
    rate,
    stock,
    refill: 0,
    alertTime: Infinity,
    refillTime: Infinity,
    emptyTime: Infinity,
  };
  // 消耗过 85% 告警,12 分钟后补给车到站补 25%
  const alertIdx = Math.ceil((stock * 0.85) / rate);
  if (alertIdx < arrivals.length) {
    s.alertTime = arrivals[alertIdx];
    s.refillTime = s.alertTime + 720;
    s.refill = Math.round((arrivals.length * rate * 0.25) / 100) * 100;
    const emptyIdx = Math.ceil(stock / rate);
    if (emptyIdx < arrivals.length && arrivals[emptyIdx] < s.refillTime) {
      s.emptyTime = arrivals[emptyIdx];
    }
  }
  return s;
});
function stationState(s, t) {
  const passed = upperBound(s.arrivals, t);
  const stock = s.stock + (t >= s.refillTime ? s.refill : 0);
  const used = Math.min(stock, Math.round(passed * s.rate));
  return {passed, stock, used, left: stock - used, ratio: (stock - used) / stock};
}
const levelColor = (r) =>
  r > 0.35 ? 'rgba(54, 211, 153, 1)' : r > 0.15 ? 'rgba(255, 184, 77, 1)' : 'rgba(255, 77, 79, 1)';

// ======================= 配速员 =======================
const PACERS = [
  [3, 'rgba(255, 90, 138, 1)'],
  [3.5, 'rgba(255, 184, 77, 1)'],
  [4, 'rgba(255, 225, 77, 1)'],
  [4.5, 'rgba(123, 227, 107, 1)'],
  [5, 'rgba(79, 195, 255, 1)'],
  [5.5, 'rgba(179, 140, 255, 1)'],
].map(([h, color]) => {
  const T = h * 3600;
  const delay = (upperBound(sortedTarget, T) / RUNNERS) * 1500;
  return {
    label: Math.floor(h) + ':' + (h % 1 ? '30' : '00'),
    color,
    pace: T / RACE,
    delay,
    finish: delay + T,
  };
});
const pacerDist = (p, t) => Math.max(0, Math.min(RACE, (t - p.delay) / p.pace));

// ======================= 医疗求助 =======================
const INCIDENT_TYPES = ['抽筋', '抽筋', '脱水', '体力不支', '崴脚', '低血糖', '心率异常', '摔倒'];
const nearestStation = (d) =>
  STATIONS.reduce((a, b) => (Math.abs(b.d - d) < Math.abs(a.d - d) ? b : a));
const INCIDENTS = [];
for (let i = 0; i < RUNNERS; i++) {
  if (quitTime[i] !== Infinity && rnd() < 0.06) {
    const d = quitDist[i];
    INCIDENTS.push({
      id: 'M' + (101 + INCIDENTS.length),
      time: quitTime[i],
      d,
      coord: pointAt(d),
      type: INCIDENT_TYPES[Math.floor(rnd() * INCIDENT_TYPES.length)],
      station: nearestStation(d).name,
      doneTime: quitTime[i] + (15 + rnd() * 20) * 60,
    });
  }
}

// ======================= 事件流 =======================
const EVENT_COLOR = {
  race: '#ff8a3d',
  open: '#36d399',
  warn: '#ff4d4f',
  supply: '#ffb84d',
  info: '#4fc3ff',
};
const EVENTS = [];
const addEvent = (time, kind, text, coord) => EVENTS.push({time, kind, text, coord});

addEvent(0, 'race', '鸣枪起跑', pointAt(0));
addEvent(Math.max(...startDelay), 'info', '最后一个出发区通过起点', pointAt(0));
[
  [10000, '10K'],
  [RACE / 2, '半程'],
  [30000, '30K'],
  [40000, '40K'],
].forEach(([d, name]) => {
  const t = timeAt(winner, d);
  addEvent(
    t,
    'race',
    '领跑者通过' + name + ',用时 ' + durationText(t - startDelay[winner]),
    pointAt(d),
  );
});
addEvent(
  finishTime[winner],
  'race',
  '冠军冲线,净成绩 ' + durationText(finishTime[winner] - startDelay[winner]),
  pointAt(RACE),
);
PACERS.forEach((p) => addEvent(p.finish, 'info', p.label + ' 配速员到达终点', pointAt(RACE)));
STATIONS.forEach((s) => {
  if (s.alertTime === Infinity) {
    return;
  }
  addEvent(s.alertTime, 'supply', s.name + ' 饮水低于 15%,补给车出发', s.coord);
  if (s.emptyTime !== Infinity) {
    addEvent(s.emptyTime, 'warn', s.name + ' 饮水断供', s.coord);
  }
  addEvent(
    s.refillTime,
    'open',
    s.name + ' 补给到站 +' + s.refill.toLocaleString() + ' 杯',
    s.coord,
  );
});
INCIDENTS.forEach((m) =>
  addEvent(
    m.time,
    'warn',
    km(m.d) + ' km 跑者' + m.type + ',' + m.station + ' 医疗点出动',
    m.coord,
  ),
);
for (let k = 5; k <= 40; k += 5) {
  addEvent(SWEEP_START + (k * 1000) / SWEEP_V, 'open', '0–' + k + 'K 恢复通车', pointAt(k * 1000));
}
const finishPerMin = {};
for (let i = 0; i < RUNNERS; i++) {
  if (finishTime[i] !== Infinity) {
    const m = Math.floor(finishTime[i] / 60);
    finishPerMin[m] = (finishPerMin[m] || 0) + 1;
  }
}
const peakMinute = Number(
  Object.keys(finishPerMin).reduce((a, b) => (finishPerMin[b] > finishPerMin[a] ? b : a)),
);
addEvent(
  peakMinute * 60,
  'race',
  '冲线高峰 ' + finishPerMin[peakMinute] + ' 人/分钟',
  pointAt(RACE),
);
addEvent(CUTOFF, 'warn', '比赛关门', pointAt(RACE));
EVENTS.sort((a, b) => a.time - b.time);
const EVENT_TIMES = EVENTS.map((e) => e.time);

// ======================= 地图与图层 =======================
const DARK_STYLE = [
  {featureType: 'land', elementType: 'geometry', stylers: {color: '#0d1724ff'}},
  {featureType: 'water', elementType: 'geometry', stylers: {color: '#0a2033ff'}},
  {featureType: 'green', elementType: 'geometry', stylers: {color: '#0f2129ff'}},
  {featureType: 'manmade', elementType: 'geometry', stylers: {color: '#111e2eff'}},
  {featureType: 'education', elementType: 'geometry', stylers: {color: '#111e2eff'}},
  {featureType: 'medical', elementType: 'geometry', stylers: {color: '#111e2eff'}},
  {featureType: 'scenicspots', elementType: 'geometry', stylers: {color: '#0f2129ff'}},
  {featureType: 'building', elementType: 'geometry.fill', stylers: {color: '#15253aff'}},
  {featureType: 'building', elementType: 'geometry.stroke', stylers: {color: '#1b2e47ff'}},
  ...[
    'highway',
    'provincialway',
    'arterial',
    'tertiaryway',
    'fourlevelway',
    'local',
    'road',
  ].flatMap((type, i) => [
    {
      featureType: type,
      elementType: 'geometry.fill',
      stylers: {
        color:
          [
            'rgba(36, 56, 79, 1)',
            'rgba(31, 50, 71, 1)',
            'rgba(28, 45, 66, 1)',
            'rgba(24, 40, 59, 1)',
            'rgba(22, 37, 54, 1)',
            'rgba(21, 35, 52, 1)',
            'rgba(21, 35, 52, 1)',
          ][i] + 'ff',
      },
    },
    {featureType: type, elementType: 'geometry.stroke', stylers: {color: '#0d172400'}},
  ]),
  {featureType: 'railway', elementType: 'geometry', stylers: {visibility: 'off'}},
  {featureType: 'subway', elementType: 'geometry', stylers: {visibility: 'off'}},
  {featureType: 'all', elementType: 'labels.icon', stylers: {visibility: 'off'}},
  {featureType: 'all', elementType: 'labels.text.fill', stylers: {color: '#4f6580ff'}},
  {featureType: 'all', elementType: 'labels.text.stroke', stylers: {color: '#0d1724ff'}},
];

const map = new BMap.Map('map', {enableAdaptiveMinZoom: false});
map.centerAndZoom(new BMap.Point(116.345, 39.952), 13);
map.enableScrollWheelZoom(true);
map.setMapStyleV2({styleJson: DARK_STYLE});
map.setViewport(
  ROUTE.map((c) => new BMap.Point(c[0], c[1])),
  {margins: [40, 320, 40, 360], enableAnimation: false},
);
map.setTilt(40);

const REF = new BMap.Point(116.345, 39.952);
const ROUTE_FEATURE = {
  type: 'Feature',
  geometry: {type: 'LineString', coordinates: ROUTE},
  properties: {},
};

const routeLayer = new BMap.PolylineLayer({
  strokeColor: 'rgba(90, 108, 134, 0.8)',
  strokeWeight: 7,
  referCenter: REF,
  zIndex: 1,
});
routeLayer.setData(ROUTE_FEATURE);

// 两条 TrackLine 共用赛道,进度由时钟驱动:未走过的部分隐藏,线随进度生长
const trackOptions = (color, zIndex) => ({
  strokeColor: color,
  strokeWeight: 7,
  passedColor: null,
  upcomingColor: 'none',
  speedMode: 0,
  duration: 100,
  movePoint: false,
  referCenter: REF,
  zIndex,
});
const raceTrack = new BMap.TrackLine(trackOptions('rgba(255, 138, 61, 1)', 2));
const openTrack = new BMap.TrackLine(trackOptions('rgba(54, 211, 153, 1)', 3));
raceTrack.setData(ROUTE_FEATURE);
openTrack.setData(ROUTE_FEATURE);

// 热力半径是屏幕像素,同一段人群在不同级别下重叠的分段数不同,max 随级别同比调整
const heatMax = () => Math.max(80, 1100 * Math.pow(2, 13 - map.getZoom()));
const heatLayer = new BMap.Heatmap({
  size: 12,
  max: heatMax(),
  maxOpacity: 0.9,
  weightField: 'count',
  referCenter: REF,
  zIndex: 5,
  gradient: {
    0.2: 'rgba(47, 107, 255, 1)',
    0.45: 'rgba(47, 224, 255, 1)',
    0.7: 'rgba(255, 225, 77, 1)',
    1.0: 'rgba(255, 90, 54, 1)',
  },
});
map.addEventListener('zoomend', () => heatLayer.setOptions({max: heatMax()}));

const maxStock = Math.max(...STATIONS.map((s) => s.stock + s.refill));
const barLayer = new BMap.BarLayer({
  unit: 'm',
  size: 160,
  edgeCount: 24,
  referCenter: REF,
  zIndex: 6,
});

const pointOptions = (extra) =>
  Object.assign(
    {
      shape: 'circle',
      strokeColor: 'rgba(255, 255, 255, 1)',
      strokeWeight: 2,
      enablePicked: true,
      renderStage: 'poi',
    },
    extra,
  );
const stationLayer = new BMap.PointLayer(
  pointOptions({size: 12, fillColor: (p) => levelColor(p.ratio)}),
);
const medicalLayer = new BMap.PointLayer(
  pointOptions({
    shape: 'cross',
    size: 15,
    strokeWeight: 1.5,
    fillColor: (p) => (p.active ? 'rgba(255, 77, 79, 1)' : 'rgba(120, 132, 148, 1)'),
  }),
);
const pacerLayer = new BMap.PointLayer(
  pointOptions({size: 11, strokeColor: 'rgba(13, 23, 36, 1)', fillColor: (p) => p.color}),
);
const pacerText = new BMap.TextLayer({
  text: (p) => p.label,
  fontSize: 11,
  fontWeight: 'bold',
  color: (p) => p.color,
  strokeColor: 'rgba(13, 23, 36, 1)',
  strokeWeight: 3,
  anchor: 'leftCenter',
  offset: [9, 0],
  collides: false,
  renderStage: 'poi',
});
const hotspotLayer = new BMap.PointLayer({
  size: 34,
  fillColor: 'rgba(255, 77, 79, 1)',
  fillOpacity: 0.18,
  strokeColor: 'rgba(255, 77, 79, 1)',
  strokeWeight: 2,
  renderStage: 'poi',
});
const hotspotText = new BMap.TextLayer({
  text: (p) => p.per100 + ' 人/百米',
  fontSize: 11,
  fontWeight: 'bold',
  color: 'rgba(255, 140, 140, 1)',
  strokeColor: 'rgba(13, 23, 36, 1)',
  strokeWeight: 3,
  anchor: 'bottomCenter',
  offset: [0, 20],
  collides: false,
  renderStage: 'poi',
});

const KM_MARKS = [5, 10, 15, 20, 25, 30, 35, 40].map((k) =>
  pointFeature(pointAt(k * 1000), {text: k + 'K'}),
);
const ENDS = [
  pointFeature(pointAt(0), {text: '起点 天安门东'}),
  pointFeature(pointAt(RACE), {text: '终点 国家体育场'}),
];
const markLayer = new BMap.PointLayer({
  shape: 'square',
  size: 6,
  fillColor: 'rgba(207, 227, 255, 1)',
  renderStage: 'poi',
});
const markText = new BMap.TextLayer({
  text: (p) => p.text,
  fontSize: 11,
  color: 'rgba(207, 227, 255, 1)',
  strokeColor: 'rgba(13, 23, 36, 1)',
  strokeWeight: 3,
  anchor: 'rightCenter',
  offset: [-8, 0],
  renderStage: 'poi',
});
const endText = new BMap.TextLayer({
  text: (p) => p.text,
  fontSize: 13,
  fontWeight: 'bold',
  color: 'rgba(255, 255, 255, 1)',
  strokeColor: 'rgba(255, 138, 61, 1)',
  strokeWeight: 3,
  anchor: 'bottomCenter',
  offset: [0, 10],
  collides: false,
  renderStage: 'poi',
});
markLayer.setData(fc(KM_MARKS.concat(ENDS)));
markText.setData(fc(KM_MARKS));
endText.setData(fc(ENDS));

[
  routeLayer,
  raceTrack,
  openTrack,
  heatLayer,
  barLayer,
  hotspotLayer,
  hotspotText,
  markLayer,
  markText,
  endText,
  stationLayer,
  medicalLayer,
  pacerLayer,
  pacerText,
].forEach((layer) => map.addLayer(layer));

// ======================= 按时刻重算 =======================
const BIN_COUNT = Math.ceil(RACE / BIN);
const BIN_COORDS = Array.from({length: BIN_COUNT}, (_, b) => pointAt((b + 0.5) * BIN));
const bins = new Float32Array(BIN_COUNT);
const kmHist = new Int32Array(43);
let snap = null;

// 拥堵预警:取人数最多的 500 m 窗口;新窗口须多出 15% 才切换,避免标记来回跳
const HOT_WINDOW = 10;
const HOT_LIMIT = 220;
let hotStart = -1;
function windowSum(b0) {
  let sum = 0;
  for (let k = b0; k < b0 + HOT_WINDOW; k++) {
    sum += bins[k];
  }
  return sum;
}
function updateHotspot() {
  let best = -1;
  let bestSum = 0;
  for (let b = 4; b + HOT_WINDOW < BIN_COUNT - HOT_WINDOW; b++) {
    const v = windowSum(b);
    if (v > bestSum) {
      bestSum = v;
      best = b;
    }
  }
  let cur = hotStart >= 0 ? windowSum(hotStart) : 0;
  if (best >= 0 && bestSum > cur * 1.15) {
    hotStart = best;
    cur = bestSum;
  }
  const per100 = Math.round(cur / ((HOT_WINDOW * BIN) / 100));
  if (hotStart < 0 || per100 < HOT_LIMIT) {
    hotStart = -1;
    hotspotLayer.setData(fc([]));
    hotspotText.setData(fc([]));
    return;
  }
  const f = pointFeature(pointAt((hotStart + HOT_WINDOW / 2) * BIN), {per100});
  hotspotLayer.setData(fc([f]));
  hotspotText.setData(fc([f]));
}

function update(t) {
  bins.fill(0);
  kmHist.fill(0);
  let running = 0;
  let waiting = 0;
  let finished = 0;
  let out = 0;
  let lead = 0;
  for (let i = 0; i < RUNNERS; i++) {
    if (t >= quitTime[i] || t >= sweptTime[i]) {
      out++;
      continue;
    }
    if (t >= finishTime[i]) {
      finished++;
      lead = RACE;
      continue;
    }
    if (t <= startDelay[i]) {
      waiting++;
      continue;
    }
    const d = distAt(i, t);
    running++;
    lead = Math.max(lead, d);
    bins[Math.min(BIN_COUNT - 1, Math.floor(d / BIN))]++;
    kmHist[Math.min(42, Math.floor(d / 1000))]++;
  }
  bins[0] += waiting;

  const heatPoints = [];
  for (let b = 0; b < BIN_COUNT; b++) {
    if (bins[b]) {
      heatPoints.push(pointFeature(BIN_COORDS[b], {count: bins[b]}));
    }
  }
  heatLayer.setData(fc(heatPoints));
  updateHotspot();

  const sweep = sweepAt(t);
  raceTrack.setProcess(lead / RACE);
  openTrack.setProcess(sweep / RACE);

  const stations = STATIONS.map((s) => Object.assign({station: s}, stationState(s, t)));
  barLayer.setData(
    fc(
      stations.map((x) =>
        pointFeature(x.station.coord, {
          value: [x.left, x.used],
          height: (x.stock / maxStock) * 5200,
          color: [levelColor(x.ratio), 'rgba(170, 195, 230, 0.35)'],
        }),
      ),
    ),
  );
  stationLayer.setData(
    fc(
      stations.map((x) =>
        pointFeature(x.station.coord, {
          name: x.station.name,
          ratio: x.ratio,
          left: x.left,
          stock: x.stock,
          passed: x.passed,
          refilling: t >= x.station.alertTime && t < x.station.refillTime,
        }),
      ),
    ),
  );
  medicalLayer.setData(
    fc(
      INCIDENTS.filter((m) => m.time <= t && t < m.doneTime + 1200).map((m) =>
        pointFeature(m.coord, {incident: m, active: t < m.doneTime}),
      ),
    ),
  );
  const pacers = PACERS.map((p) => ({p, d: pacerDist(p, t)}))
    .filter((x) => x.d > 0 && x.d < RACE)
    .map((x) =>
      pointFeature(pointAt(x.d), {label: x.p.label, color: x.p.color, d: x.d, pacer: x.p}),
    );
  pacerLayer.setData(fc(pacers));
  pacerText.setData(fc(pacers));

  const per100 = hotStart >= 0 ? Math.round(windowSum(hotStart) / ((HOT_WINDOW * BIN) / 100)) : 0;
  snap = {
    t,
    running: running + waiting,
    finished,
    out,
    lead,
    sweep,
    per100,
    hotAt: hotStart >= 0 ? (hotStart + HOT_WINDOW / 2) * BIN : 0,
    stations,
  };
  renderPanel();
}

// ======================= 面板 =======================
const HEAT_STOPS = [
  [0, [47, 107, 255]],
  [0.33, [47, 224, 255]],
  [0.66, [255, 225, 77]],
  [1, [255, 90, 54]],
];
function heatColor(v) {
  v = Math.max(0, Math.min(1, v));
  let i = 1;
  while (i < HEAT_STOPS.length - 1 && v > HEAT_STOPS[i][0]) {
    i++;
  }
  const [p0, c0] = HEAT_STOPS[i - 1];
  const [p1, c1] = HEAT_STOPS[i];
  const f = (v - p0) / (p1 - p0);
  return 'rgb(' + c0.map((c, k) => Math.round(c + (c1[k] - c) * f)).join(',') + ')';
}

function drawHistogram() {
  const canvas = $('hist');
  const W = 288;
  const H = 96;
  const dpr = window.devicePixelRatio || 1;
  if (canvas.width !== W * dpr) {
    canvas.width = W * dpr;
    canvas.height = H * dpr;
  }
  const ctx = canvas.getContext('2d');
  ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  ctx.clearRect(0, 0, W, H);
  const top = 12;
  const base = H - 14;
  const bw = W / 43;
  const peak = Math.max(...kmHist);
  const scale = Math.max(peak, 600);
  kmHist.forEach((n, i) => {
    if (!n) {
      return;
    }
    const h = (n / scale) * (base - top);
    ctx.fillStyle = heatColor(n / 2400);
    ctx.fillRect(i * bw + 0.5, base - h, bw - 1, h);
  });
  ctx.fillStyle = 'rgba(255, 255, 255, 0.12)';
  ctx.fillRect(0, base, W, 1);
  ctx.fillStyle = '#7f93ab';
  ctx.font = '10px sans-serif';
  ctx.textAlign = 'center';
  [0, 10, 20, 30, 40].forEach((k) =>
    ctx.fillText(k + (k === 40 ? ' km' : ''), Math.min(W - 16, Math.max(6, k * bw)), H - 2),
  );
  const marker = (d, color) => {
    ctx.fillStyle = color;
    ctx.fillRect((d / 1000) * bw - 1, top - 4, 2, base - top + 4);
  };
  if (snap.sweep > 0) {
    marker(snap.sweep, '#36d399');
  }
  if (snap.lead > 0 && snap.lead < RACE) {
    marker(snap.lead, '#ff8a3d');
  }
  PACERS.forEach((p) => {
    const d = pacerDist(p, snap.t);
    if (d <= 0 || d >= RACE) {
      return;
    }
    const x = (d / 1000) * bw;
    ctx.fillStyle = p.color;
    ctx.beginPath();
    ctx.moveTo(x - 4, 1);
    ctx.lineTo(x + 4, 1);
    ctx.lineTo(x, 8);
    ctx.fill();
  });
  $('histPeak').textContent = peak ? '峰值 ' + peak.toLocaleString() + ' 人/km' : '';
}

function buildStationRows() {
  STATIONS.forEach((s) => {
    const row = document.createElement('div');
    row.className = 'stn';
    row.innerHTML =
      '<span class="nm"></span><span class="bar"><i></i></span><span class="v"></span>';
    row.firstChild.textContent = s.name;
    row.addEventListener('click', () => map.panTo(new BMap.Point(s.coord[0], s.coord[1])));
    $('stations').appendChild(row);
  });
}

let shownEvents = -1;
function renderEvents(highlight) {
  const n = upperBound(EVENT_TIMES, snap.t);
  if (n === shownEvents) {
    return;
  }
  const prev = shownEvents;
  shownEvents = n;
  $('eventCount').textContent = n ? n + ' 条' : '';
  const list = $('eventList');
  list.textContent = '';
  for (let i = n - 1; i >= Math.max(0, n - 60); i--) {
    const e = EVENTS[i];
    const li = document.createElement('li');
    if (highlight && prev >= 0 && i >= prev) {
      li.className = 'new';
    }
    const time = document.createElement('time');
    time.textContent = clockText(e.time);
    const dot = document.createElement('i');
    dot.style.background = EVENT_COLOR[e.kind];
    const text = document.createElement('span');
    text.textContent = e.text;
    li.append(time, dot, text);
    li.addEventListener('click', () => map.panTo(new BMap.Point(e.coord[0], e.coord[1])));
    list.appendChild(li);
  }
}

const withUnit = (v, unit) => v + '<em>' + unit + '</em>';
function renderPanel() {
  const t = snap.t;
  $('clock').textContent = clockText(t, true);
  $('elapsed').textContent =
    t < 0 ? '距鸣枪 ' + durationText(-t) : t > CUTOFF ? '已关门' : '+' + durationText(t);
  $('time').value = t;
  $('kRunning').textContent = snap.running.toLocaleString();
  $('kFinished').textContent = snap.finished.toLocaleString();
  $('kOut').textContent = snap.out.toLocaleString();
  $('kLead').innerHTML = withUnit(km(snap.lead), 'km');
  $('kOpen').innerHTML = withUnit(km(snap.sweep), 'km');
  $('kDense').innerHTML = snap.per100 ? withUnit(snap.per100, '人/百米') : '—';
  $('kDenseAt').textContent = snap.per100 ? '拥堵 ' + km(snap.hotAt) + ' km' : '最密路段';
  drawHistogram();
  snap.stations.forEach((x, j) => {
    const row = $('stations').children[j];
    const bar = row.children[1].firstChild;
    bar.style.width = (x.ratio * 100).toFixed(1) + '%';
    bar.style.background = levelColor(x.ratio);
    row.children[2].textContent = x.left.toLocaleString() + ' / ' + x.stock.toLocaleString();
  });
  renderEvents(playing);
}

// ======================= 悬停信息 =======================
const tooltip = $('tooltip');
function showTip(e, html) {
  tooltip.innerHTML = html;
  tooltip.style.left = e.pixel.x + 14 + 'px';
  tooltip.style.top = e.pixel.y + 14 + 'px';
  tooltip.style.display = 'block';
}
const hideTip = () => {
  tooltip.style.display = 'none';
};

stationLayer.addEventListener('mouseover', (e) => {
  const p = e.value.properties;
  showTip(
    e,
    '<b>' +
      p.name +
      ' 补给站</b>' +
      (p.refilling ? ' 补给在途' : '') +
      '<br>饮水 ' +
      p.left.toLocaleString() +
      ' / ' +
      p.stock.toLocaleString() +
      ' 杯' +
      '<br>已通过 ' +
      p.passed.toLocaleString() +
      ' 人',
  );
});
medicalLayer.addEventListener('mouseover', (e) => {
  const m = e.value.properties.incident;
  showTip(
    e,
    '<b>' +
      m.id +
      ' ' +
      m.type +
      '</b><br>' +
      clockText(m.time) +
      ' · ' +
      km(m.d) +
      ' km' +
      '<br>' +
      m.station +
      ' 医疗点 · ' +
      (e.value.properties.active ? '处置中' : '已处置'),
  );
});
pacerLayer.addEventListener('mouseover', (e) => {
  const p = e.value.properties;
  const pace = p.pacer.pace * 1000;
  showTip(
    e,
    '<b>' +
      p.label +
      ' 配速员</b><br>' +
      Math.floor(pace / 60) +
      "'" +
      pad(Math.round(pace % 60)) +
      '" /km · ' +
      km(p.d) +
      ' km<br>预计 ' +
      clockText(p.pacer.finish) +
      ' 到达',
  );
});
[stationLayer, medicalLayer, pacerLayer].forEach((layer) =>
  layer.addEventListener('mouseout', hideTip),
);
map.addEventListener('movestart', hideTip);

// ======================= 播放控制 =======================
let simTime = 70 * 60;
let playing = true;
let speed = 120;
let dirty = true;

const slider = $('time');
slider.min = T_MIN;
slider.max = T_MAX;

function setPlaying(value) {
  playing = value;
  $('play').textContent = value ? '暂停' : '播放';
}
function seek(t) {
  simTime = Math.max(T_MIN, Math.min(T_MAX, t));
  shownEvents = -1;
  hotStart = -1;
  dirty = true;
}
$('play').addEventListener('click', () => {
  if (!playing && simTime >= T_MAX) {
    seek(T_MIN);
  }
  setPlaying(!playing);
});
$('speed').addEventListener('change', (e) => {
  speed = Number(e.target.value);
});
slider.addEventListener('input', () => seek(Number(slider.value)));
[
  ['鸣枪', 0],
  ['冠军冲线', finishTime[winner]],
  ['冲线高峰', peakMinute * 60],
  ['关门', CUTOFF],
].forEach(([label, t]) => {
  const button = document.createElement('button');
  button.type = 'button';
  button.textContent = label;
  button.addEventListener('click', () => seek(t));
  $('jumps').appendChild(button);
});

buildStationRows();

let lastFrame = 0;
let lastUpdate = 0;
function frame(now) {
  requestAnimationFrame(frame);
  const dt = lastFrame ? Math.min(0.25, (now - lastFrame) / 1000) : 0;
  lastFrame = now;
  if (playing) {
    simTime += dt * speed;
    if (simTime >= T_MAX) {
      simTime = T_MAX;
      setPlaying(false);
    }
    dirty = true;
  }
  // 全场重算约 8 次/秒
  if (dirty && now - lastUpdate > 120) {
    lastUpdate = now;
    dirty = false;
    update(simTime);
  }
}
requestAnimationFrame(frame);
// 图层实现是异步加载的,首屏瓦片就绪后再刷新一次,保证暂停状态下也能看到当前进度
map.addEventListener('tilesloaded', () => {
  dirty = true;
});
预览