HotspotLayer.ts 40.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
import { fmtCompact } from '@/utils/format';
import { mercY, roundRectPath, textWidth, type Overlay, type PaintEnv } from '@hm/map-overlay';
import type { HotspotRow } from '../aggregate/types';
import { labelDomains } from '../aggregate/hotspotAnalysis';
import { defineAppOverlay } from './appOverlay';
import { domainOutline } from './footprintOutline';
import { traceRoundedRings } from './roundedPath';
import { CLUSTER_LABEL, PALETTE, labelFont } from './palette';
import { LABEL_MIN_R } from './ClusterLayer';
import { HOTSPOT_MAX_DRAW_PX, HOTSPOT_MIN_DRAW_PX } from './hotspotGeometry';

/** 黑点栅格几何(与 analyze / Worker 的 handleScope 同一口径) */
export interface HotspotGrid {
  originLng: number;
  originLat: number;
  dLng: number;
  dLat: number;
  w: number;
  h: number;
}

export interface HotspotLayerOptions {
  /** 当前选中的黑点下标(清单与地图双向联动) */
  active: number | null;
}

/**
 * 排名牌字号。11px 而不是 10px:牌子靠实色底衬就够醒目了,字号大一点
 * 换来的是「一眼能认出是第几名」,而不用担心再叠描边。
 */
const CHIP_FONT = labelFont(11);
/** 盘心案量的字号区间:小盘时与聚合数字同尺寸,盘放大后再涨,别涨过盘本身的边界感 */
const COUNT_FONT_MIN = 11;
const COUNT_FONT_MAX = 18;
/**
 * 盘心案量那八档字号的 font 串,模块加载时一次生成。
 *
 * 字号被上面两个常量夹死,能出现的取值就是这八个整数,所以没有理由在帧里现插字符串 ——
 * 原先每个盘每帧插一支,几十个盘就是每帧几十支新字符串,全记在拖动的账单上。
 * 这张表同时是底衬半径缓存的键(见 plateRadius):字号定下来,那一档的字宽就定下来了,
 * 与缩放、与盘在屏幕哪儿都无关。
 */
const COUNT_FONTS: string[] = Array.from({ length: COUNT_FONT_MAX - COUNT_FONT_MIN + 1 }, (_, k) =>
  labelFont(COUNT_FONT_MIN + k),
);
/** 盘心多少像素内算「点在那个黑点上」。小盘时靠它保证盘心仍然可点 */
const DISC_CENTER_HIT_R = 20;
/** 命中判定的外扩量:脚印是格子块,点进一格哪怕压在格边也该算命中这一片 */
const CELL_HIT_PAD = 4;
/** 视口裁剪的外扩量:描边、虚线外环与排名牌都在轮廓外一点 */
const CULL_PAD = 40;
/**
 * 外光雾的宽度系数,与 glow 的档位一一对应(第 0 档贴边、最后一档最外)。
 *
 * 0.42 → 2.0 是「近五倍的跨度」:三层旧版只到 1.0,光到轮廓外一倍宽就断了,
 * 看着只是描了一圈粗边;跨到两倍才有向外散开的体量感。
 *
 * ⚠️ 只有三档,不是五档。原来的第 4、5 档 alpha 是 0.055 / 0.028 —— 肉眼几乎不可见,
 * 却仍要付两次「整条轮廓再描一遍」的钱(一片几百个顶点 × 几十片,还是一帧一付)。
 * 把跨度交给三档(中间档相位错开)视觉上读不出差别,笔数直接少了四成。
 */
const GLOW_FACTORS = [0.42, 0.95, 2.0];
/** 精简档只用前两档。宽度收在旧版的量级,避免几十片同时在场时糊成一片 */
const GLOW_FACTORS_LITE = [0.5, 1.15];
/**
 * 走「满配」的屏幕等效半径门槛(像素)。
 *
 * 低于这个值的片通常成片出现(全市视图),逐片多画几笔会把拖动拖慢;
 * 高于它的片一般只有三五片在屏幕里,正好把暗底与细高光都上满。
 */
const HOTSPOT_RICH_R = 28;
/**
 * 选中某一片时,其余各片的不透明度。
 *
 * 0.62 是折中:退得够远,焦点明确落在点开的那一片;又没退到「看不见」——
 * 用户仍然能看清旁边还有几处、排在哪儿,只是不再抢注意力。
 */
const DIMMED_ALPHA = 0.62;
/** 拿不到画布时的一字兜底宽度(粗体数字约 6.2px)。只影响底衬大小,不参与任何数字口径 */
const FALLBACK_CHAR_W = 6.2;

/**
 * 排名分档配色。前三红、4~8 橙、其余品牌靛 —— 用色相而不是深浅分档,
 * 因为这一层本来就叠在高饱和的热力底色上,深浅差在暖色区根本分不出来。
 */
function tierColor(id: number): string {
  if (id < 3) return PALETTE.error;
  if (id < 8) return PALETTE.warn;
  return PALETTE.primary;
}

function rgba(hex: string, alpha: number): string {
  const v = hex.replace('#', '');
  return `rgba(${parseInt(v.slice(0, 2), 16)},${parseInt(v.slice(2, 4), 16)},${parseInt(v.slice(4, 6), 16)},${alpha})`;
}

/**
 * 把分档色朝某个方向(0 = 黑、255 = 白)拉 t,再按 alpha 输出 rgba。
 *
 * 只服务轮廓那三层描边:暗底要真的更暗、高光要真的更亮,三者才是「有厚度的边」。
 * 全部同色只是深浅不同的话,屏幕上看到的是「一条粗边」,不是「一条边在发光」。
 */
function shade(hex: string, toward: number, t: number, alpha = 1): string {
  const v = hex.replace('#', '');
  const mix = (c: number) => Math.round(c + (toward - c) * t);
  return `rgba(${mix(parseInt(v.slice(0, 2), 16))},${mix(parseInt(v.slice(2, 4), 16))},${mix(parseInt(v.slice(4, 6), 16))},${alpha})`;
}
const lighten = (hex: string, t: number, alpha = 1): string => shade(hex, 255, t, alpha);
const darken = (hex: string, t: number, alpha = 1): string => shade(hex, 0, t, alpha);

/**
 * 量一段落在盘上的文字。量不到画布时(无 canvas 的环境)按字数估,
 * 只影响底衬与牌子大小,不参与任何数字口径。
 */
function measureWidth(font: string, label: string): number {
  return textWidth(font, label) ?? label.length * FALLBACK_CHAR_W;
}

/**
 * 这一环境有没有 Path2D。单测里的假画布没有(jsdom 不实现它),
 * 那种环境退回「逐格矩形判命中」,与改造前的行为一致。
 */
const HAS_PATH2D = typeof Path2D !== 'undefined';

/**
 * 把投影好的轮廓环建成一条 Path2D。
 *
 * 为什么值得多这一步:同一条轮廓一帧要描 4~6 遍(光雾 2~3 档、暗底、主边、高光)。
 * 若每遍都是「往 ctx 当前路径里再 trace 一次」,浏览器就得把这几十上百段 arcTo
 * 重新展开、重新扁平化 —— 一遍一份钱。建成 Path2D 之后,展开一次、描边多次,
 * 省下的正是「同一形状被反复解析」的那部分。命中判定(isPointInPath)也白拿。
 */
function buildRoundedPath(rings: Float32Array[] | null, radius: number): Path2D | null {
  if (!HAS_PATH2D || !rings || rings.length === 0) return null;
  const path = new Path2D();
  traceRoundedRings(path, rings, radius);
  return path;
}

/**
 * 两层薄封装:有 Path2D 时把路径交给它,没有时用 ctx 当前路径。
 *
 * 写成模块级函数而不是闭包:这两句每片每帧各调几次,闭包本身也是要分配的。
 */
function strokePath(ctx: CanvasRenderingContext2D, path: Path2D | null): void {
  if (path) ctx.stroke(path);
  else ctx.stroke();
}

function fillPath(ctx: CanvasRenderingContext2D, path: Path2D | null): void {
  if (path) ctx.fill(path);
  else ctx.fill();
}

/**
 * 一个黑点在一帧里要用到的、与缩放无关的东西。
 *
 * 全部在 setData 那一次算好:原先每帧每行都要拼 rgba 字符串、跑一次 fmtCompact、
 * 做一次投影,几十个标记摊到每帧也是几百次调用加几百个临时字符串(颜色串每次都是新对象,
 * 浏览器还得重新解析)。缩放一帧只算一次,这些数在整帧里都是同一个。
 */
interface Prepared {
  /** 墨卡托纬度:与缩放无关,画时只剩减法和乘法 */
  my: number;
  lng: number;
  lat: number;
  /** 盘心的案量数字,与清单那一行同一个 fmtCompact */
  countLabel: string;
  /** 排名牌上的序号 */
  rankLabel: string;
  /**
   * 排名牌的宽度(序号那一行量好,左右各 5 像素内边距)。
   *
   * 序号与字号都不随缩放变,所以牌宽在喂数据那一次量一次定死;
   * 原先它是每帧每个盘量一遍 —— 一帧几十次量字换一串从来没变过的数字。
   * 牌子的高度是常量(CH 那一档),只有宽要现算。
   */
  chipW: number;
  /** 分档色,以及它在「常态 / 选中」两档下的底面与环色 */
  tier: string;
  fill: string;
  fillActive: string;
  ring: string;
  ringActive: string;
  /** 轮廓的暗底(压在下面的宽边,让轮廓从浅色底图上「立」起来) */
  edgeDark: string;
  /** 轮廓的内侧高光(提亮的分档色,贴着主边描一条细亮线) */
  edgeHi: string;
  /**
   * 外发光的分档色(由内到外、由浓到淡),常态与选中各一套。
   *
   * 预存在这里而不是每帧拼:轮廓一天要重画几十上百次,rgba 解析是纯浪费;
   * 发光本身是「同一路径叠几层不同宽度」,颜色定了就没有帧内计算。
   */
  glow: string[];
  glowActive: string[];
  /** 这一片包含的栅格下标(连通域成员),仅在拿到 grid+mask 时有值 */
  cells: number[];
  /**
   * 上一帧的屏幕路径,命中检测直接判「点落不落在这一片里」。
   *
   * 有了它就不必每帧为每片算一遍逐格屏幕矩形(一片两百来格、几十片,
   * 那是每帧上万次投影与数组写,只为了一次可能永远不发生的点击)。
   * 路径本身每帧都要建(要画),顺手存下来是最便宜的做法。
   */
  path: Path2D | null;
  /** 逐格屏幕矩形。**只在没有 Path2D 的环境(单测的假画布)里维护**,见 paint */
  rects: Float32Array;
  /**
   * 这一片的闭合轮廓环(格角坐标,去共线后)。与缩放无关,喂数据时算一次。
   *
   * 画法从「逐格四边」换成「闭合环」正是为了解决线条断开:一条边一段子路径时,
   * 每段都是 butt 端点,台阶拐角外侧缺一个三角,满屏小缺口看起来就是碎线。
   */
  outline: Int32Array[] | null;
  /** 轮廓环投影后的屏幕坐标,与 outline 一一对应(每帧重写,不重新分配) */
  screen: Float32Array[] | null;
}

/**
 * 黑点标记层 —— 画的是「分析结论」,不是原始数据。
 *
 * 与聚合圆圈层的分工要说清楚,否则两层看起来功能重复:
 *   - 聚合层:视口像素网格的实时计数,回答「屏幕这一格有多少起」,随缩放变化;
 *   - 黑点层:地理连通域,回答「哪儿值得派人去看」,范围按地面上的米算,
 *     并且带排名和域内案量 —— 这两个数就是清单上的那两个数。
 *
 * 盘心刻意写 count:以前这里只有排名牌,案件数只能从底下的聚合数字读,
 * 而那个数字是「屏幕格子的计数」,跟清单那行「域内 N 起」本来就不是一个口径,
 * 于是同一个位置并排出现两个对不上的数(实测被质疑「列表 51 起、圈里 30 起」)。
 * 现在盘内的数字直接由黑点层报,聚合层在该让位的地方整块收掉自己的数字,
 * 一个位置只剩一个数,剩下的区别只是「谁的口径」。
 *
 * ⚠️ 范围不再画等效圆,改画黑点**真实的格子脚印轮廓**:
 * 之前画的是 √(面积/π) 的等效圆,周长是规整了,但它只是「示意覆盖范围」——
 * 真实脚印(连通的显著方格)是不规则块,等效圆罩不住伸出去的格子、又圈进圆内的邻格,
 * 于是清单里列出来的点在地图上落在圈外,读起来像 bug。现在直接画那一整片格子
 * (填充并集 + 逐格边界描边),清单、盘心数字、这一片图形就是同一个地面区域,
 * 「列表里的点都在范围内」才成立。grid/mask 没拿到时(如旧单元测试)退回画等效圆。
 *
 * 与 ClusterLayer 同样的实现方式(CustomLayer + canvas 自绘 + 自己算命中),
 * 理由也一致:几十个标记不值得为它们建 AMap.Marker 覆盖物。
 *
 * ⚠️ 帧预算(2026-10-15 调优):与缩放无关的那批数(投影纬度、盘心数字、排名与牌宽、
 * 底面 / 环那几支颜色)在喂数据时一次算完;视图与本层都没变时整帧跳过、快拖那几帧整层
 * 不落笔、收起期间连重画请求都不发 —— 这三条由内核的出帧骨架守着
 * (`@hm/map-overlay` 的 `defineOverlay`:`canPaint` 管能不能落笔,`paint` 里的 light
 * 分支管减载),本层只管「这一帧画什么、画了几笔」。画出来的还是同一批盘、同一个数、同一种颜色。
 */
export class HotspotLayer {
  private readonly overlay: Overlay;
  private opts: HotspotLayerOptions = { active: null };

  private rows: HotspotRow[] = [];
  private prepared: Prepared[] = [];
  private grid: HotspotGrid | null = null;
  private mask: Uint8Array | null = null;
  /** 连通域编号 → 格子下标,由 grid+mask 一次算好(按 mask 引用缓存,避免每次分析重算) */
  private cellsByDomain: Map<number, number[]> | null = null;
  private cachedMask: Uint8Array | null = null;
  private cachedGrid: HotspotGrid | null = null;
  /** 逐格连通域编号(labelDomains 的结果,与 cellsByDomain 同一份缓存) */
  private label: Int32Array | null = null;

  /**
   * 盘心案量的底衬半径,按「屏上那一串数字」存一排(一排八档,与 COUNT_FONTS 同序)。
   *
   * 字宽只由「字号 + 内容」决定,与缩放无关:所以这张表既不按帧清空,也不按缩放换代
   * (原先那套「缩放一变就整表重量」把每个盘每帧两遍量字留到了慢速拖动里,
   * 而量字比画盘本身还贵)。一屏的数字串来来回回就几十种,行里的 0 表示那一档还没量过。
   */
  private plateRs = new Map<string, Float32Array>();

  /** 屏幕缓存,供命中检测复用(点一次不必重投影) */
  private sx = new Float32Array(0);
  private sy = new Float32Array(0);
  /** 等效圆退回模式下的命中半径(拿到脚印后由格子判定,这一项不再用) */
  private sr = new Float32Array(0);
  private visible = true;
  /**
   * 每一行格界的墨卡托纬度(长度 = 栅格高 + 1)。
   *
   * 格角坐标在轮廓里是整数行号,投影时只是查一次表 —— 这就把每帧上万次
   * `tan/log` 换成了上万次数组读。纬度只随数据变,与缩放、中心都无关。
   */
  private rowMerc: Float64Array | null = null;
  /** 上一帧用的绘制上下文:命中判定(isPointInPath)要借它,没有 Path2D 的环境为 null */
  private hitCtx: CanvasRenderingContext2D | null = null;

  constructor(map: AMap.Map) {
    this.overlay = defineAppOverlay(map, {
      id: 'hotspot',
      name: 'HotspotLayer · 黑点范围脚印层',
      // 高于聚合层(130):黑点是结论,压住数字是合理的层级关系
      zIndex: 140,
      zooms: [3, 20],
      canPaint: () => this.visible && this.prepared.length > 0,
      paint: (env) => this.paint(env),
      extras: () => ({
        built: this.overlay.mounted,
        visible: this.visible,
        note: this.opts.active === null ? '未选中任何一片' : `选中第 ${this.opts.active + 1} 片`,
      }),
    });
  }

  setOptions(opts: Partial<HotspotLayerOptions>) {
    this.opts = { ...this.opts, ...opts };
    this.overlay.invalidate();
  }

  /** 每行格界的墨卡托纬度。格角行号是 0..h 的整数,直接按行号索引 */
  private buildRowMerc(): Float64Array | null {
    const g = this.grid;
    if (!g || g.h <= 0 || !(g.dLat > 0)) return null;
    const out = new Float64Array(g.h + 1);
    for (let y = 0; y <= g.h; y += 1) out[y] = mercY(g.originLat + y * g.dLat);
    return out;
  }

  /**
   * 喂数据。grid+mask 用来还原每个黑点的真实脚印;不传则退回画等效圆(兼容旧测试)。
   *
   * 连通域 → 格子下标只依赖 mask 与 grid,与遍历顺序无关;按 mask 引用缓存,
   * 这样聚焦切来切去、参数微调触发的重复 setData 不必每次都重跑一遍 labelDomains。
   */
  setData(rows: HotspotRow[], grid?: HotspotGrid | null, mask?: Uint8Array | null) {
    const g = grid ?? null;
    const mk = mask ?? null;
    // 同一批结果重复喂就什么都不做:点一个黑点(activeHotspot 变)、切换视图、
    // 拖一下抽屉,都会让 MapStage 的 applyAnalysis 重跑一遍。而这一遍要重新
    // 合并连通域、为每个域拼一次轮廓环 —— 输入没换就不该再付这份钱。
    // 空清单用「双方都为空」判等:调用处传的是 `res?.hotspots ?? []`,每次都是新数组。
    const sameRows = this.rows === rows || (rows.length === 0 && this.rows.length === 0);
    if (sameRows && this.grid === g && this.mask === mk) return;

    this.rows = rows;
    this.grid = g;
    this.mask = mk;

    if (this.grid && this.mask) {
      if (this.cachedMask !== this.mask || this.cachedGrid !== this.grid) {
        const { label } = labelDomains(this.mask, this.grid.w, this.grid.h);
        const byDomain = new Map<number, number[]>();
        for (let i = 0; i < label.length; i += 1) {
          const d = label[i];
          if (d === 0) continue;
          let arr = byDomain.get(d);
          if (!arr) {
            arr = [];
            byDomain.set(d, arr);
          }
          arr.push(i);
        }
        this.cellsByDomain = byDomain;
        this.label = label;
        this.cachedMask = this.mask;
        this.cachedGrid = this.grid;
      }
    } else {
      this.cellsByDomain = null;
      this.label = null;
      this.cachedMask = null;
      this.cachedGrid = null;
    }

    // 每一行格界的墨卡托纬度:格角坐标是整数行号,投影时直接查表。
    // 原先每帧对每个轮廓顶点、每个格子都现算一次 mercY(tan + log)——
    // 一片两百来个顶点、几十片就是每帧上万次三角函数,只因为纬度是逐帧不变的量。
    this.rowMerc = this.buildRowMerc();

    this.prepared = rows.map((r, i) => {
      const tier = tierColor(i);
      const rankLabel = String(i + 1);
      const cells = this.cellsByDomain?.get(r.domainId) ?? [];
      const outline =
        this.label && this.grid
          ? domainOutline(this.label, this.grid.w, this.grid.h, r.domainId, cells)
          : null;
      return {
        my: mercY(r.lat),
        lng: r.lng,
        lat: r.lat,
        countLabel: fmtCompact(r.count),
        rankLabel,
        chipW: Math.ceil(measureWidth(CHIP_FONT, rankLabel)) + 10,
        tier,
        // 圈内那层蒙层:热力只剩一层(整体淡化),「这一片更值得看」由轮廓自己的填充表达。
        // 它同时压住圈内淡掉的热力,让黑点的色相仍然说得出「前三红、4~8 橙、其余靛」。
        // 内侧发光取消后,圈内只剩这一层 —— 淡一点,让热力透得过气。
        fill: rgba(tier, 0.14),
        fillActive: rgba(tier, 0.22),
        ring: rgba(tier, 0.9),
        ringActive: rgba(tier, 1),
        // 暗底朝黑拉 45%:轮廓压在暖色热力上时靠它把边「切」出来,也让主边显得更亮
        edgeDark: darken(tier, 0.45, 0.55),
        // 高光朝白提亮 58%:同色系但明显更亮,读起来是「这条边在反光」而不是「这条边是红的」
        edgeHi: lighten(tier, 0.58, 0.9),
        // 由内到外三档:贴着轮廓的那层最浓最窄,往外逐层加宽、变淡,最外一层是光雾。
        // 三档而非五档的理由见 GLOW_FACTORS —— 后两档肉眼不可见,却要各付一次整圈描边。
        glow: [rgba(tier, 0.34), rgba(tier, 0.15), rgba(tier, 0.07)],
        glowActive: [rgba(tier, 0.46), rgba(tier, 0.22), rgba(tier, 0.1)],
        cells,
        path: null,
        rects: new Float32Array(cells.length * 4),
        outline,
        screen: outline ? outline.map((ring) => new Float32Array(ring.length)) : null,
      };
    });

    this.sx = new Float32Array(rows.length);
    this.sy = new Float32Array(rows.length);
    this.sr = new Float32Array(rows.length);

    // 先点名(第一次有数据就在这一步把层建起来),再报数据量:读数要写在建好的那块画布上
    this.overlay.invalidate();
    this.overlay.setTotal(rows.length);
  }

  setVisible(v: boolean) {
    // 幂等:聚合每次回包都会叫一次,而 show/hide 会重分配或交还整块画布
    if (this.visible === v) return;
    this.visible = v;
    // 黑点层是「偶尔出现」的层:收起时内核把画布像素交还(DPR 2 下三十来兆),
    // 重新展开时那一屏欠的变化由同一句 show 补画
    if (v) this.overlay.show();
    else this.overlay.hide();
  }

  /** 强制下一帧重画本层(为什么必须点名,见 ClusterLayer.invalidate) */
  invalidate() {
    this.overlay.invalidate();
  }

  /**
   * 盘心案量的底衬半径:与聚合数字同一套算法(字号 + 文字宽度)。
   *
   * 按「那一串数字 + 第几档字号」存住,两个都不随缩放变,所以一帧之内的重复取用是纯查表,
   * 缩放来回穿过同一档字号也不再重量(账见 plateRs 那一段)。
   */
  private plateRadius(label: string, fontIdx: number): number {
    let row = this.plateRs.get(label);
    if (!row) {
      row = new Float32Array(COUNT_FONTS.length);
      this.plateRs.set(label, row);
    }
    const cached = row[fontIdx];
    if (cached > 0) return cached;
    const r = Math.max(LABEL_MIN_R, measureWidth(COUNT_FONTS[fontIdx], label) / 2 + 3);
    row[fontIdx] = r;
    return r;
  }

  private paint(env: PaintEnv): number {
    const { ctx, frame, width: w, height: h } = env;
    // 命中判定借这一块上下文问 isPointInPath(路径是屏幕坐标,两者同一坐标系)
    this.hitCtx = ctx;
    // 米 → 像素每帧一次(原来是每行一次 cos 与乘法)
    const pxPerMeter = frame.pxPerMeter;
    // 快拖这一拍:这一层整块不落笔(判据见 gesture.ts 的 light() —— 在动 **且**
    // 这一帧真的挪得够快,见内核 viewPos 的 FAST_MOVE_PX;聚合层用的是同一条)。
    // 盘的填充、描边、盘心案量、排名牌一起收掉。
    // ⚠️ 只收「画」,不收「算」:格子屏幕坐标与命中矩形照旧写进缓存,
    //    松手后紧接着的那一次点击仍按脚印的真实范围命中,不会出现「看不见就点不动」。
    const light = env.light;
    // 调试视图的读数:这一帧真的落了几笔(与聚合层同一口径 —— 出屏与减载的那些都不算)
    let painted = 0;

    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';

    for (let i = 0; i < this.prepared.length; i += 1) {
      const p = this.prepared[i];
      const x = frame.x(p.lng);
      const y = frame.y(p.my);
      const active = this.opts.active === i;
      this.sx[i] = x;
      this.sy[i] = y;

      const hasFootprint = p.cells.length > 0 && this.grid !== null && p.outline !== null;

      // ---- 计算这一片的屏幕几何(命中矩形 + 包围盒),命中检测与裁剪都要用 ----
      let minX = Infinity;
      let minY = Infinity;
      let maxX = -Infinity;
      let maxY = -Infinity;
      let effR = 0; // 用于盘心字号与排名牌定位的「等效半径」
      /** 最小可见尺寸兜底的放大系数:格子矩形与轮廓环必须用同一个,否则两者会错位 */
      let scale = 1;
      /** 轮廓圆角半径(像素):台阶靠它化成圆弧 */
      let cornerR = 0;

      if (hasFootprint) {
        const g = this.grid as HotspotGrid;
        const rowMerc = this.rowMerc;
        const outline = p.outline as Int32Array[];
        const screen = p.screen as Float32Array[];
        // 轮廓投影:顶点数是「边界拐角」的量级,逐格矩形是「格数 × 4」——差一个数量级。
        // 包围盒与等效半径都从轮廓顶点推出来,于是每帧不必再把每个格子投一遍。
        // (逐格矩形只在没有 Path2D 的环境里补算,那是命中判定的兜底路径,见 hitAt。)
        for (let r = 0; r < outline.length; r += 1) {
          const src = outline[r];
          const dst = screen[r];
          for (let k = 0; k < src.length; k += 2) {
            const px = frame.x(g.originLng + src[k] * g.dLng);
            // 行号是整数,纬度查表 —— 每帧上万次 tan/log 在这里被换成数组读
            const py = frame.y(
              rowMerc ? rowMerc[src[k + 1]] : mercY(g.originLat + src[k + 1] * g.dLat),
            );
            dst[k] = px;
            dst[k + 1] = py;
            if (px < minX) minX = px;
            if (py < minY) minY = py;
            if (px > maxX) maxX = px;
            if (py > maxY) maxY = py;
            const rr = Math.hypot(px - x, py - y);
            if (rr > effR) effR = rr;
          }
        }

        // 全市视图下 100 米格子不足 1 像素,真实尺寸的脚印会直接看不见
        // (老实现的圆有 HOTSPOT_MIN_DRAW_PX 兜底,这里不能丢)。按质心等比放大到
        // 最小可见尺寸:形状还是这片脚印,只是整体放大 —— 放大后读不出形状细节,
        // 但「这儿有一个黑点、多大一片」的读数保住了,命中区域也跟着放大。
        if (effR > 0 && effR < HOTSPOT_MIN_DRAW_PX) {
          const s = HOTSPOT_MIN_DRAW_PX / effR;
          scale = s;
          for (let r = 0; r < screen.length; r += 1) {
            const dst = screen[r];
            for (let k = 0; k < dst.length; k += 2) {
              dst[k] = x + (dst[k] - x) * s;
              dst[k + 1] = y + (dst[k + 1] - y) * s;
            }
          }
          minX = x + (minX - x) * s;
          minY = y + (minY - y) * s;
          maxX = x + (maxX - x) * s;
          maxY = y + (maxY - y) * s;
          effR = HOTSPOT_MIN_DRAW_PX;
        }

        // 逐格屏幕矩形:只为没有 Path2D 的环境(单测的假画布)保留。
        // 生产环境走 isPointInPath,这条路一年也不会走一次。
        if (!HAS_PATH2D && rowMerc) {
          const rects = p.rects;
          for (let k = 0; k < p.cells.length; k += 1) {
            const cell = p.cells[k];
            const cx = cell % g.w;
            const cy = (cell / g.w) | 0;
            const X0 = frame.x(g.originLng + cx * g.dLng);
            const X1 = frame.x(g.originLng + (cx + 1) * g.dLng);
            const Y0 = frame.y(rowMerc[cy + 1]);
            const Y1 = frame.y(rowMerc[cy]);
            rects[k * 4] = X0;
            rects[k * 4 + 1] = Y0;
            rects[k * 4 + 2] = X1;
            rects[k * 4 + 3] = Y1;
          }
          if (scale !== 1) {
            for (let k = 0; k < p.cells.length; k += 1) {
              rects[k * 4] = x + (rects[k * 4] - x) * scale;
              rects[k * 4 + 1] = y + (rects[k * 4 + 1] - y) * scale;
              rects[k * 4 + 2] = x + (rects[k * 4 + 2] - x) * scale;
              rects[k * 4 + 3] = y + (rects[k * 4 + 3] - y) * scale;
            }
          }
        }

        // 圆角半径跟着格子的屏幕边长走:格子越大,圆角可以越大而不会把形状糊掉;
        // 上限 9px 是给大域留的(不然一圈 200px 的轮廓会被圆成近似椭圆,读不出范围)。
        const cellPx = Math.abs(frame.x(g.originLng + g.dLng) - frame.x(g.originLng)) * scale;
        cornerR = Math.min(9, Math.max(1.5, cellPx * 0.45));

        // 命中路径:快拖减载的那几帧也重建 —— 只描边不建路径的话,
        // 松手那一下的点击会按上一帧的旧坐标判定。
        p.path = buildRoundedPath(screen, cornerR);
      } else {
        // 等效圆退回模式:按面积等效半径画(旧单元测试走这里)
        const rad = Math.min(
          HOTSPOT_MAX_DRAW_PX,
          Math.max(HOTSPOT_MIN_DRAW_PX, (this.rows[i].radiusM ?? 0) * pxPerMeter),
        );
        this.sr[i] = rad;
        effR = rad;
        minX = x - rad;
        minY = y - rad;
        maxX = x + rad;
        maxY = y + rad;
      }

      // 整片(或圆)都在视口外:跳过这一片(含盘心数字与排名牌)
      const bleed = (hasFootprint ? effR : this.sr[i]) + CULL_PAD;
      if (x < -bleed || y < -bleed || x > w + bleed || y > h + bleed) continue;
      if (maxX < 0 || minX > w || maxY < 0 || minY > h) continue;

      if (light) {
        // 快拖减载:只画轮廓本身(填充 + 主边),让黑点线圈不再整片消失 / 重绘,
        // 省掉外光雾、案量数字与排名牌这几笔重活。松手那一下由 repaintLayers 立刻补满。
        if (hasFootprint) this.paintFootprint(ctx, p, active, cornerR, effR, true);
        else this.paintDisc(ctx, p, x, y, this.sr[i], active);
        ctx.globalAlpha = 1;
        painted += 1;
        continue;
      }

      // 有选中时其余各片整体压淡一档:焦点落在你点的那一片上,别处退成背景。
      // 用 globalAlpha 而不是逐片改颜色:一次赋值换来整组(轮廓 + 数字 + 排名牌)一起退,
      // 而且不必为「淡的那一版」再预算一堆 rgba 字符串。
      ctx.globalAlpha = this.opts.active !== null && !active ? DIMMED_ALPHA : 1;

      if (hasFootprint) {
        this.paintFootprint(ctx, p, active, cornerR, effR, false);
      } else {
        this.paintDisc(ctx, p, x, y, this.sr[i], active);
      }

      // 盘心案量。数字直接用 fmtCompact(清单那一行用的是同一个函数),字色、白描边、
      // 极淡底衬全部照聚合数字 —— 这一层要顶掉的正是那个数字,同一种长相,
      // 用户才不会问「这两个数哪个算数」,也不会怀疑清单和地图各算了一遍。
      const fontIdx =
        Math.round(Math.min(COUNT_FONT_MAX, Math.max(COUNT_FONT_MIN, effR * 0.16))) - COUNT_FONT_MIN;
      ctx.font = COUNT_FONTS[fontIdx];
      const plateR = this.plateRadius(p.countLabel, fontIdx);
      ctx.beginPath();
      ctx.arc(x, y, plateR, 0, Math.PI * 2);
      ctx.fillStyle = CLUSTER_LABEL.plate;
      ctx.fill();
      ctx.lineWidth = CLUSTER_LABEL.haloWidth;
      ctx.strokeStyle = CLUSTER_LABEL.halo;
      ctx.strokeText(p.countLabel, x, y + 0.5);
      ctx.fillStyle = CLUSTER_LABEL.color;
      ctx.fillText(p.countLabel, x, y + 0.5);

      // 排名牌放在右上 45°,并且落在轮廓外一点点。
      //
      // 位置比原先外移,是因为小范围时(全市视图下脚印只有几十像素)牌子正好压在
      // 圆心上 —— 而圆心现在是案量数字,编号和数字叠成一坨,两个都读不出来。
      //
      // 画法也换了:原先是「实心小圆 + 白字 + 2.5px 白色 strokeText」,10px 字号上
      // 叠 2.5px 描边,描边比笔画还宽,字形边缘全被糊掉,看着就是一团发光的光斑。
      // 牌面本身是不透明的分档色,白字靠底色就有足够对比,所以描边整个去掉,
      // 只留一层很淡的投影把牌子从热力暖色上抬起来 —— 阴影给层次,不给虚边。
      ctx.font = CHIP_FONT;
      const cw = p.chipW;
      const ch = 15;
      const off = (effR + 11) * 0.7071;
      const cx = x + off - cw / 2;
      const cy = y - off - ch / 2;
      roundRectPath(ctx, cx, cy, cw, ch, 5);
      // 投影只在近看(或选中)时开:canvas 的 shadowBlur 是一次真的高斯模糊,
      // 全市视图下几十片各来一次并不便宜,而 15px 的小牌子上那层投影根本读不出来。
      // 牌面本身是不透明的分档色,白字靠底色就有足够对比 —— 阴影给层次,不给虚边。
      const withShadow = active || effR >= HOTSPOT_RICH_R;
      if (withShadow) {
        ctx.shadowColor = 'rgba(16,24,40,.32)';
        ctx.shadowBlur = 4;
        ctx.shadowOffsetY = 1;
      }
      ctx.fillStyle = p.tier;
      ctx.fill();
      if (withShadow) {
        ctx.shadowColor = 'transparent';
        ctx.shadowBlur = 0;
        ctx.shadowOffsetY = 0;
      }
      ctx.lineWidth = 1.2;
      ctx.strokeStyle = 'rgba(255,255,255,.9)';
      ctx.stroke();

      ctx.fillStyle = '#ffffff';
      ctx.fillText(p.rankLabel, cx + cw / 2, cy + ch / 2 + 0.5);
      // 复位:下一片可能是「选中那一片」,不能继承上一片的淡
      ctx.globalAlpha = 1;
      painted += 1;
    }
    return painted;
  }


  /**
   * 画一片脚印:外光雾 + 填充 + 三明治描边。
   *
   * 画的是**多边形**,不是一堆格子边:边界在喂数据时已由 domainOutline 拼成闭合环,
   * 每帧只做「格角 → 屏幕」的投影,然后把所有环描进同一条 path,之后反复复用它。
   *
   * 层次(由外到内):
   *   1. 外光雾:同一条路径叠 2~3 层描边,由内到外逐层加宽、变淡 —— 冲击力主要来自这一层;
   *   2. 擦内半:destination-out 把光雾落在轮廓里的那一半擦掉,光只留在外面;
   *   3. 底面填充:圈内那层蒙层,压住已经淡掉的热力;
   *   4. 三明治描边:暗底(宽)→ 主边(分档色)→ 亮线(细高光),边界因此有厚度。
   *
   * ⚠️ 第 2 步不能省。光雾是「描宽线」,线宽必然一半在内、一半在外;只拿一层 0.14 的
   * 填充去压,0.34 的光隔着一层 14% 的膜照样看得见 —— 屏上就是轮廓里还套着一圈亮边
   * (用户连着反馈了两次)。擦掉才是真的只在外面。
   *
   * ⚠️ 分档:屏幕上的片越大(用户看得越近),笔数越多。全市视图下几十片同时在场、
   * 每片才十几像素,把满配的笔全画上会把拖动拖慢;近看时一屏通常只有几片,正好上满。
   * 选中的那一片永远满配 —— 特效要花在用户正在看的地方。
   */
  private paintFootprint(
    ctx: CanvasRenderingContext2D,
    p: Prepared,
    active: boolean,
    cornerR: number,
    effR: number,
    light: boolean,
  ): void {
    const rings = p.screen;
    if (!rings || rings.length === 0) return;

    // 满配门槛:等效半径够大,或者就是选中这一片
    const rich = active || effR >= HOTSPOT_RICH_R;

    // 有 Path2D 就走「展开一次、描多次」;没有(单测的假画布)就先 trace 进当前路径
    const path = p.path;
    if (!path) {
      ctx.beginPath();
      traceRoundedRings(ctx, rings, cornerR);
    }

    ctx.save();
    ctx.lineJoin = 'round';
    ctx.lineCap = 'round';

    if (light) {
      // 快拖减载:只保填充 + 主边,圈不消失也不多花光雾 / 擦除那几笔。
      // 没有外光雾就不需要 destination-out 擦内半 —— 直接填 + 描边即可。
      ctx.fillStyle = active ? p.fillActive : p.fill;
      fillPath(ctx, path);
      ctx.lineWidth = active ? 3 : 2.2;
      ctx.strokeStyle = active ? p.ringActive : p.ring;
      strokePath(ctx, path);
      ctx.restore();
      return;
    }

    // ---- 1. 外光雾 ----
    // 光雾本来是「内外各一半」的:轮廓内侧那一半由下一步擦掉,只留外面这一圈。
    const glow = active ? p.glowActive : p.glow;
    const w0 = Math.max(9, Math.min(active ? 34 : 24, effR * 0.55));
    if (rich) {
      for (let i = 0; i < GLOW_FACTORS.length; i += 1) {
        ctx.strokeStyle = glow[i];
        ctx.lineWidth = w0 * GLOW_FACTORS[i];
        strokePath(ctx, path);
      }
    } else {
      // 精简档:两档就够读出「这儿有一片」,宽度回到与旧版持平的量级
      for (let i = 0; i < GLOW_FACTORS_LITE.length; i += 1) {
        ctx.strokeStyle = glow[i];
        ctx.lineWidth = w0 * GLOW_FACTORS_LITE[i];
        strokePath(ctx, path);
      }
    }

    // ---- 2. 擦掉光雾朝内的那一半 ----
    // 光雾是「同一条轮廓描几遍宽线」,线宽有一半落在轮廓内侧。只靠后面那层 fill 压不住:
    // fill 只有 0.14 透明度,0.34 的光雾隔着一层 14% 的膜照样看得见 ——
    // 屏上就是「轮廓里面还套着一圈亮边」。
    // destination-out 把本层画布上轮廓内部的像素直接擦成透明,底下的热力与地图一点不受影响
    // (本层自己有独立画布)。擦出来的硬边随后由暗底(4px)与主边(2.2px)盖住。
    // 用默认的 nonzero 填充:带洞的脚印洞里那圈光本来就该留着 —— 洞是轮廓外。
    //
    // ⚠️ 擦的时候必须临时把 globalAlpha 拉满:选中某一片时,其余各片是按 0.62 画的
    // (见 DIMMED_ALPHA),而 destination-out 也吃 globalAlpha —— 0.62 只能擦掉 62%,
    // 剩下 38% 的内圈光正好留在屏上,问题会「只在选中时复发」。
    const alpha = ctx.globalAlpha;
    ctx.globalAlpha = 1;
    ctx.globalCompositeOperation = 'destination-out';
    fillPath(ctx, path);
    ctx.globalCompositeOperation = 'source-over';
    ctx.globalAlpha = alpha;

    // ---- 3. 底面填充 ----
    ctx.fillStyle = active ? p.fillActive : p.fill;
    fillPath(ctx, path);

    // ---- 4. 暗底 ----
    // 宽而深的一圈,把轮廓从暖色热力底图里「切」出来。
    // 只在满配档做:它靠「宽」起作用,片太小时压到轮廓上只会糊成脏边。
    if (rich) {
      ctx.lineWidth = active ? 5 : 4;
      ctx.strokeStyle = p.edgeDark;
      strokePath(ctx, path);
    }

    // ---- 5. 主边 + 边上的高光 ----
    // 边界要「实」,光才托得住。选中再粗一档。
    ctx.lineWidth = active ? 3 : 2.2;
    ctx.strokeStyle = active ? p.ringActive : p.ring;
    strokePath(ctx, path);

    if (rich) {
      // 1px 的亮线压在主边上:同色系但明显更亮,读起来是「这条边在反光」。
      // 不做整圈加粗 —— 那只会把边糊成一条带子,反而失去锐度。
      ctx.lineWidth = 1;
      ctx.strokeStyle = p.edgeHi;
      strokePath(ctx, path);
    }

    ctx.restore();
  }

  /** 等效圆退回模式下的绘制(无 grid/mask 时,如旧单元测试) */
  private paintDisc(
    ctx: CanvasRenderingContext2D,
    p: Prepared,
    x: number,
    y: number,
    rad: number,
    active: boolean,
  ): void {
    // 范围盘
    ctx.beginPath();
    ctx.arc(x, y, rad, 0, Math.PI * 2);
    ctx.fillStyle = active ? p.fillActive : p.fill;
    ctx.fill();

    // 环
    ctx.lineWidth = active ? 2.6 : 1.6;
    ctx.strokeStyle = active ? p.ringActive : p.ring;
    ctx.stroke();
  }

  /** 命中行的下标,未命中返回 -1。缓存的屏幕坐标由 paint 维护,与 ClusterLayer 同一套做法 */
  hitAt(x: number, y: number): number {
    if (!this.visible) return -1;
    let best = -1;
    let bestDist = Infinity;
    for (let i = 0; i < this.prepared.length; i += 1) {
      const p = this.prepared[i];
      const cx = this.sx[i];
      const cy = this.sy[i];
      let hit = false;

      if (p.cells.length > 0 && this.grid) {
        // 脚印模式:点在轮廓内即命中。
        // 有 Path2D 时直接问路径 —— 连「环里的洞」都自动判对,而且不必维护
        // 「每格一个屏幕矩形」那张表(那表每帧都得为几十片各重写几百个 float,
        // 只为了一次可能永远不发生的点击)。贴近边线也算,用描边判定补一手。
        const path = p.path;
        const hctx = this.hitCtx;
        if (path && hctx) {
          hit = hctx.isPointInPath(path, x, y);
          if (!hit) {
            hctx.save();
            hctx.lineWidth = CELL_HIT_PAD * 2;
            hit = hctx.isPointInStroke(path, x, y);
            hctx.restore();
          }
        } else {
          // 没有 Path2D 的环境(单测的假画布):退回逐格矩形
          const rects = p.rects;
          for (let k = 0; k < p.cells.length; k += 1) {
            const X0 = rects[k * 4] - CELL_HIT_PAD;
            const Y0 = rects[k * 4 + 1] - CELL_HIT_PAD;
            const X1 = rects[k * 4 + 2] + CELL_HIT_PAD;
            const Y1 = rects[k * 4 + 3] + CELL_HIT_PAD;
            if (x >= X0 && x <= X1 && y >= Y0 && y <= Y1) {
              hit = true;
              break;
            }
          }
        }
      } else {
        // 等效圆退回模式
        const r = this.sr[i];
        if (r <= 0) continue;
        const dx = x - cx;
        const dy = y - cy;
        const d2 = dx * dx + dy * dy;
        const reach = r + 22;
        if (d2 > reach * reach) continue;
        // 小盘只认环带和盘心;大盘整盘都认(判据同旧逻辑)
        hit =
          r >= 48 || d2 >= (r - 12) * (r - 12) || d2 < DISC_CENTER_HIT_R * DISC_CENTER_HIT_R;
      }

      if (!hit) continue;
      const d2 = (x - cx) * (x - cx) + (y - cy) * (y - cy);
      if (d2 < bestDist) {
        bestDist = d2;
        best = i;
      }
    }
    return best;
  }

  destroy() {
    this.overlay.destroy();
  }
}