CanvasHeatLayer.ts 30 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
/**
 * 百度侧自绘热力层 —— 不再用 BMapGL.Heatmap(黑盒,max/weight 被 WebGL worker 忽略)。
 *
 * 为什么换掉内置层(2026-11-24 四轮截图后定案):
 *   内置 Heatmap 的 max/size/weightField 在 911KB 主脚本里只是构造时存进 _style,
 *   真正的归一化发生在 WebGL worker,读的是另一套参数 —— 主脚本改 max 完全不生效。
 *   现场就是「调 max 从 1 到 P82×4,截图纹丝不动,依旧一片饱和红」。
 *
 * 自绘走 heatmap.js 的标准两遍法,一切参数都在我们手里:
 *   1) 离屏低分辨率灰度画布:每个点画一个黑色径向渐变圆,alpha 记录密度;
 *   2) 读 alpha,按 gradient 查表着色到主画布(主画布由 @hm/map-overlay 管出帧/投影)。
 *
 * ⚠️ 合成模式必须是 source-over(默认),不能图快改成 lighter:
 *   lighter 让 alpha 线性相加,几笔就冲到 255 → 偶发整片封顶成红(2026-11-24 实测);
 *   source-over 的 alpha 是渐近逼近 1(a = as + ad*(1-as)),叠加层数再多也留得住层次。
 *   笔刷因此画黑色(RGB=0),密度只存在 alpha 通道里,查表时再把颜色换回去。
 *
 * 笔刷与映射(2026-11-25 第三十一轮:第三十轮的「浓场」回调):
 * 第三十轮把场推到 1.6×/0.44、核放大到 0.9×,截图结果是**整片饱和红糊在一起** ——
 * 场贡献太浓,密集区每个像素都被邻桶推到色带末端,红心反而被淹进红片,边界也糊。
 * 回看高德同视角图:它确实是连片红橙 blob,但**每颗数字底下仍能辨出一枚圆润红心**,
 * 且红→橙→黄→青的带宽窄、层次清楚。所以第三十一轮回到「淡场 + 可见小核」:
 *   1) 密度场:半径 1.8×格距、峰值 0.30×权重,线性软边。单桶只到黄绿,邻桶叠加
 *      在密集区铺出橙红连续场,但不会让整片烧到饱和红 —— 负责连片与层次;
 *   2) 头部补峰:半径 0.58×格距、内 8% 软平台、强度 = 权重^2.4。头部桶在自身
 *      圆心垫出可见红心,中段桶退到黄绿,核半径小于半格不互相连 —— 数字仍同圆。
 * 两笔起点都是 weight = count/max,都走 source-over;着色仍是 heatmap.js 口径:
 * 灰度字节直接索引 palette、输出 alpha = clamp(a, minOpacity, maxOpacity),无 gamma。
 *
 * 第二十八轮的桶心扰动保留:核半径 ±12%(圆心不偏移,同圆不变)、场半径 ±18% +
 * 场心偏移 ±10% 半径,叠在 grid.ts 的低频流场错落上,避免新场又排成规则同心圆。
 * 散列输入是桶心坐标,跨帧/缩放/筛选重算同值,不闪烁。
 *
 * ⚠️ 半径按**实际屏幕格距** cellPx 缩放,不能写死像素:Worker 用整数 zoom + 256 瓦片,
 * 百度按小数 zoom + 等效 152.874 瓦片渲染,同一 dLng 在屏上可能是 30px 也可能是 60px。
 * MapStage 用 agg.dLng × frame.pxPerDegLng 把真实格距传进来,两笔同比缩放。
 *
 * 和聚合数字层共用同一套 frameScale(百度等效 tileSize + 椭圆斜率),点位不会错位。
 * 出帧也走 defineAppOverlay(百度 runtime perFrameRender=false → schedule 自己排 rAF),
 * 滚轮停下后一样有帧兑现。
 */

import { APP_SCALE, defineAppOverlay } from '../../appOverlay';
import { HEAT_GRADIENT } from '../../palette';
import {
  DEFAULT_HEAT_STYLE,
  HEAT_MIN_OPACITY,
  reference,
  type HeatLayerStyle,
} from '../../heatReference';
import { Frame, mercY, type PaintEnv } from '@hm/map-overlay';
import type { Overlay } from '@hm/map-overlay';
import type { Basemap, HeatLayerLike } from '../types';
import { unregisterDebugLayer } from '../../../debug/debugBus';

/**
 * 灰度图相对主画布的分辨率。1/3 时一个灰度像素铺 3×3 主画布像素,红核边缘发毛、
 * 数字压上去显糊;第三十一轮起改 1/2(像素量 1/4,仍是降采样),核边界更利落,
 * 配合下面的有机笔刷才能做出高德那种「清晰明确」的小斑块。
 */
const GRAY_SCALE = 1 / 2;

/**
 * 头部补峰笔刷(heatmap.js 2.0.5 `_getPointTemplate` 的逐点等价):
 * 内 BLUR_FACTOR 半径 alpha=1 实心平台,平台边缘→R 线性淡出到 0。
 *
 * 平台是「一数字一红心」的来源。第三十轮 0.12 平台 + 0.9×格距半径 + γ4 想让红心
 * 融进浓场,结果整片饱和红糊成一片、红心反而看不清。第三十一轮回到 0.08 平台 +
 * 0.58×格距半径 + γ2.4:平台够小不留大块深玫红,半径够小邻格中心落在核外,
 * γ2.4 让头部桶显出可见红心、中段桶退到黄绿。第三十二轮再把核从正圆改成有机
 * 斑块(椭圆化 + 偏瓣),见 brushVariation。
 *
 * ⚠️ 这里的 alpha 是**笔刷自己的透明度**(模板里 rgba(0,0,0,a)),
 * 每桶再乘 coreWeightToAlpha(weight) = weight^2.4(见 paint),两级不要混在一起。
 */
export const BLUR_FACTOR = 0.08;
const CORE_PROFILE: ReadonlyArray<readonly [number, number]> = [
  [0, 1],
  [BLUR_FACTOR, 1],
  [1, 0],
];

/**
 * 密度场笔刷:从中心 1 线性淡到边缘 0,没有实心平台。
 * 峰值另乘 FIELD_PEAK —— 单桶只到青绿,靠邻桶重叠才在密集区烧成连续红橙场。
 *
 * 第二十六、二十七轮为压「红海」把半径 1.5→2.0、峰值 0.45→0.30;第三十轮抬到
 * 1.6×/0.44 想复刻高德的连片红橙,但贡献太浓 → 整片饱和红、边界糊、红心被淹没。
 * 第三十一轮回调到 1.8×/0.30:宽一点更柔、单桶淡一点留层次,靠邻桶叠加在密集区
 * 自然进橙红,稀疏区仍停在冷色。
 */
export const FIELD_PEAK = 0.30;
const FIELD_PROFILE: ReadonlyArray<readonly [number, number]> = [
  [0, 1],
  [1, 0],
];

/** 剖面插值,和建笔刷时加的 gradient stop 同源,测试直接锁这两条曲线。 */
function profileAt(profile: ReadonlyArray<readonly [number, number]>, t: number): number {
  const x = Math.min(1, Math.max(0, t));
  for (let i = 1; i < profile.length; i += 1) {
    const [t1, a1] = profile[i];
    if (x <= t1) {
      const [t0, a0] = profile[i - 1];
      const k = t1 === t0 ? 0 : (x - t0) / (t1 - t0);
      return a0 + (a1 - a0) * k;
    }
  }
  return 0;
}

/** 头部补峰剖面在 t 处的系数(0.12R 软平台 + 线性软边) */
export function brushAlphaAt(t: number): number {
  return profileAt(CORE_PROFILE, t);
}

/** 密度场剖面在 t 处的系数(线性 1-t) */
export function fieldAlphaAt(t: number): number {
  return profileAt(FIELD_PROFILE, t);
}

/**
 * 半径相对实际屏幕格距的倍率。heatmap.js 默认 radius 是绝对像素,
 * 但我们的桶是屏幕网格聚合的结果,半径必须跟着格距走才不会在缩放时漂移。
 * 场 1.8×格距负责连片(邻格中心 t=0.56 仍在软边里),补峰 0.58×格距负责
 * 点睛红心(邻格中心 t=3.1 落在核外,数百桶也不会把红心连成一块)。
 */
export const FIELD_RADIUS_SCALE = 1.8;
export const CORE_RADIUS_SCALE = 0.58;

/**
 * 笔刷个性扰动(第二十八轮起,第三十二轮加有机形状):
 * 桶心错落(grid.ts 的低频流场,抖动份额 20% 格宽)只挪位置,盘仍是「半径一模一样的圆按行列排」——
 * 超人原话「一格一格像蜂窝,没有热力图那种随意飘逸、不确定性」。给每桶再叠一层确定性
 * 散列:核半径 ±12%、场半径 ±18%、场心相对核偏移 ±10% 半径。于是盘有大有小、场形不再
 * 同心圆,热力场显出有机密度感;数字圆心仍是同一个桶心(核不偏移),同圆与点击不变。
 *
 * 第三十二轮(超人:「高德的圆点不是规则圆,百度就是直观看一个个圆,很分明」):
 * 上面几项只改变位置和半径,画出来的仍是**完美正圆**。现在核本体再做椭圆化
 * (sx/sy ±28%) + 旋转 + 单侧偏瓣,画成不规则斑块;场也轻微椭圆化跟着转。
 * 主核圆心仍钉在桶心,数字与热峰严格同圆;偏瓣只是额外密度,不移动峰值。
 *
 * 为什么用散列而不是 Math.random:同一桶跨帧/跨缩放/筛选重算必须拿到同一个值,否则
 * 热力会在重绘时「呼吸」闪烁。散列输入用桶心 ×1e6 存储刻度,和点坐标同一口径。
 */
export const CORE_JITTER = 0.12;
export const FIELD_JITTER = 0.18;
export const FIELD_SHIFT = 0.1;

/**
 * 第三十二轮:核形状本身也要「不规则」。上面几项只挪位置/缩放半径,画出来的仍是
 * 完美正圆 —— 高德的核是原始点密度堆出的斑块,带偏瓣、椭圆、毛边,所以这里给每桶:
 *   - 椭圆长短轴各 ±28% 独立扰动(aspectX/aspectY),再整体旋转 angle;
 *   - 一侧再叠一个小偏瓣(lobeDist/lobeScale/lobeAngle),让轮廓鼓出一块而不是对称圆。
 * 主核圆心固定在桶心(数字仍同圆),偏瓣只是额外叠的密度,不会把峰值挪走;
 * 全部由桶心散列决定,跨帧同值不闪烁。偏瓣对小案量桶不画(ca<LOBE_MIN_ALPHA),
 * 免得满屏小点都长出尾巴。
 */
export const CORE_ASPECT_JITTER = 0.28;
export const FIELD_ASPECT_JITTER = 0.14;
export const CORE_LOBE_MIN_ALPHA = 0.12;
export const CORE_LOBE_ALPHA = 0.45;

/** 确定性散列 → [0,1),输入是桶心的存储刻度 + 盐 */
function cellHash(lngE6: number, latE6: number, salt: number): number {
  let h =
    (Math.imul(lngE6 | 0, 0x27d4eb2d) ^ Math.imul(latE6 | 0, 0x165667b1) ^ salt) | 0;
  h = Math.imul(h ^ (h >>> 15), 0x2c1b3c6d);
  h = Math.imul(h ^ (h >>> 12), 0x297a2d39);
  return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
}

/** 每桶的核/场半径倍率、场心偏移、偏瓣与椭圆化参数(跨帧同值,不闪烁) */
export interface BrushVariation {
  /** 核半径倍率(圆心不偏移) */
  core: number;
  /** 场半径倍率 */
  field: number;
  /** 场心相对核心的偏移,单位是场半径 */
  fx: number;
  fy: number;
  /** 核的长短轴倍率(各向异性拉伸,圆→椭圆) */
  sx: number;
  sy: number;
  /** 核整体旋转角(弧度) */
  rot: number;
  /** 偏瓣:相对核半径的距离、半径倍率、方位角 */
  lobeDist: number;
  lobeScale: number;
  lobeAngle: number;
  /** 场的椭圆化(比核轻,避免连续场被切碎) */
  fsx: number;
  fsy: number;
}

export function brushVariation(lngE6: number, latE6: number): BrushVariation {
  return {
    core: 1 + (cellHash(lngE6, latE6, 0x51ed270b) * 2 - 1) * CORE_JITTER,
    field: 1 + (cellHash(lngE6, latE6, 0x85ebca6b) * 2 - 1) * FIELD_JITTER,
    fx: (cellHash(lngE6, latE6, 0x27d4eb2d) * 2 - 1) * FIELD_SHIFT,
    fy: (cellHash(lngE6, latE6, 0x165667b1) * 2 - 1) * FIELD_SHIFT,
    sx: 1 + (cellHash(lngE6, latE6, 0x7f4a7c15) * 2 - 1) * CORE_ASPECT_JITTER,
    sy: 1 + (cellHash(lngE6, latE6, 0x9e3779b1) * 2 - 1) * CORE_ASPECT_JITTER,
    rot: cellHash(lngE6, latE6, 0x243f6a88) * Math.PI,
    lobeDist: 0.55 + cellHash(lngE6, latE6, 0xb7e15162) * 0.45,
    lobeScale: 0.5 + cellHash(lngE6, latE6, 0xbf58476d) * 0.3,
    lobeAngle: cellHash(lngE6, latE6, 0x94d049bb) * Math.PI * 2,
    fsx: 1 + (cellHash(lngE6, latE6, 0x94d049bc) * 2 - 1) * FIELD_ASPECT_JITTER,
    fsy: 1 + (cellHash(lngE6, latE6, 0x94d049bd) * 2 - 1) * FIELD_ASPECT_JITTER,
  };
}

/**
 * 两笔笔刷的实际半径。style.radius 默认 80 只作为档位倍率的基准:
 * 高德侧它仍是绝对像素,百度侧改成「相对默认档」的缩放,滑杆拖到 40 就是半档。
 */
export function heatBrushRadii(
  cellPx: number,
  styleRadius: number = DEFAULT_HEAT_STYLE.radius,
): { core: number; field: number } {
  const cell = Math.max(1, cellPx);
  const scale = Math.max(0.1, styleRadius / DEFAULT_HEAT_STYLE.radius);
  return {
    core: cell * CORE_RADIUS_SCALE * scale,
    field: cell * FIELD_RADIUS_SCALE * scale,
  };
}

/**
 * 案量→笔刷强度 = heatmap.js 的 `globalAlpha = (value-min)/(max-min)`。
 *
 * 这里 min=0、max=视野内 reference(),所以就是 `count/max`,**不再乘任何系数**、不做 gamma。
 * 那个曾反复调的 0.5 峰值是错的:heatmap.js 的 0.5 是笔刷模板中心吗?不是——
 * 官方 2.0.5 `_getPointTemplate` 的中心是 `rgba(0,0,0,1)`,0.5 从来不在链路里。
 * 单点满案量时 globalAlpha=1,配上实心平台,盘心灰度直接到 255 → 红心。
 */
export function weightToAlpha(weight: number): number {
  return Math.min(1, Math.max(0, weight));
}

/**
 * 头部补峰的主次压缩指数(第三十一轮 4.0→2.4)。
 *
 * 4.0 太狠:0.8 案量只剩 0.41,红心几乎全灭,画面只剩一团糊红场。
 * 2.4 下:0.6→0.29、0.8→0.59、0.9→0.77、1.0→1.0 —— 头部桶红心清楚,
 * 中段桶停在橙绿不抢戏,配合 0.58×格距小半径,红心独立又不排成棋盘。
 * 场笔刷不经过这个指数,连续过渡完全由 FIELD_PEAK 那条线负责。
 */
export const CORE_GAMMA = 2.4;

/** 补峰笔刷的案量→强度:恒等权重再做主次压缩,场笔刷不要调这个函数 */
export function coreWeightToAlpha(weight: number): number {
  return weightToAlpha(weight) ** CORE_GAMMA;
}

/**
 * 灰度 alpha → 色带位置:heatmap.js 是 `palette[alpha*4]`,即灰度字节**直接索引**调色板,
 * 没有任何 gamma / pow。这里保持恒等,纯粹为了测试能钉住这条契约。
 */
export function densityToStop(alphaByte: number): number {
  return Math.min(1, Math.max(0, alphaByte / 255));
}

/**
 * 归一化上限单帧逼近率:每帧把 max 向 target 拉近这个比例(0~1)。
 *
 * 为什么不用「每次 setDataset 推一步的固定倍率」:滚轮时回包来得疏密不定,
 * 停下时 max 可能停在任何中间态,下一次滚动又从那个不确定值起步 ——
 * 同一片数据有时追到了(偏红)、有时没追到(偏淡),正是「忽红忽淡」的根因。
 * 改成渲染帧里持续逼近,停下后还会自己追到收敛,颜色只由数据决定、与滚动节奏无关。
 * 0.18 约 20 帧(1/3 秒)才走完 98%,超人实测"光晕散开太慢、拖沓";0.35 约
 * 6~8 帧(0.1 秒出头)到位,仍逐帧渐变但不再拖尾。
 */
const MAX_EASE = 0.35;
/** max 与 target 差到这个比例以内就吸附,避免无限逼近、每帧都重画 */
const MAX_EASE_EPS = 0.005;

type RGB = [number, number, number];

/** 把 HEAT_GRADIENT 的 {stop:'rgb(...)'} 烘成 256 级查表,省掉逐像素解析字符串 */
export function buildLut(): Uint8ClampedArray {
  const stops = Object.keys(HEAT_GRADIENT)
    .map(Number)
    .sort((a, b) => a - b);
  const colors: RGB[] = stops.map((s) => {
    const m = /rgb\((\d+)\s*,\s*(\d+)\s*,\s*(\d+)\)/.exec(HEAT_GRADIENT[s]);
    return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : [0, 0, 0];
  });
  const lut = new Uint8ClampedArray(256 * 3);
  for (let i = 0; i < 256; i += 1) {
    const t = i / 255;
    let k = 0;
    while (k < stops.length - 2 && stops[k + 1] < t) k += 1;
    const t0 = stops[k];
    const t1 = stops[k + 1] ?? 1;
    const u = t1 === t0 ? 0 : Math.min(1, Math.max(0, (t - t0) / (t1 - t0)));
    const c0 = colors[k];
    const c1 = colors[k + 1] ?? c0;
    lut[i * 3] = c0[0] + (c1[0] - c0[0]) * u;
    lut[i * 3 + 1] = c0[1] + (c1[1] - c0[1]) * u;
    lut[i * 3 + 2] = c0[2] + (c1[2] - c0[2]) * u;
  }
  return lut;
}

const LUT = buildLut();

/**
 * 归一化上限逐帧逼近:把 current 朝 target 拉近固定比例,靠近到 EPS 内直接吸附。
 * 返回 { value, settled },settled=false 表示还要再来一帧。
 */
export function smoothMax(current: number, target: number): { value: number; settled: boolean } {
  const t = Math.max(1, target);
  const c = Math.max(1, current);
  // 差值已经在 EPS 内,或步进取整后挪不动(差额只有一两位、18% 不够 1 个整数),
  // 都直接吸附到目标 —— 否则 round 会把 max 卡在原地永远不到账,每帧空转重画。
  if (Math.abs(t - c) / t <= MAX_EASE_EPS) return { value: t, settled: true };
  const next = Math.max(1, Math.round(c + (t - c) * MAX_EASE));
  if (next === c) return { value: t, settled: true };
  return { value: next, settled: next === t };
}

export class CanvasHeatLayer implements HeatLayerLike {
  private readonly overlay: Overlay;
  private style: HeatLayerStyle = { ...DEFAULT_HEAT_STYLE };
  private visible = true;
  private lng = new Float64Array(0);
  private lat = new Float64Array(0);
  private counts = new Int32Array(0);
  /** 视野内 P82,决定灰度→颜色的映射上限(平滑后的实际值) */
  private max = 1;
  /** P82 本次算出的目标值,max 逐帧向它靠拢 */
  private targetMax = 0;
  private maxReady = false;
  /** max 是否已追平 target;true 时不逐帧排帧 */
  private maxSettled = true;
  private lastMax = 0;
  /**
   * 当前投影下的真实屏幕格距。MapStage 每次喂数据时按 agg.dLng × frame.pxPerDegLng 传入;
   * 缺省时用 style.radius 兜底,保证单独构造这一层的调用方也有合理尺寸。
   */
  private cellPx = DEFAULT_HEAT_STYLE.radius;

  /** 离屏灰度画布与着色结果,尺寸随主画布变 */
  private gray = document.createElement('canvas');
  private grayCtx: CanvasRenderingContext2D | null = null;
  private grayW = 0;
  private grayH = 0;
  /** 复用的实心核笔刷:半径变了才重建 */
  private coreBrush: HTMLCanvasElement | null = null;
  private coreBrushR = -1;
  /** 复用的密度场笔刷:半径变了才重建 */
  private fieldBrush: HTMLCanvasElement | null = null;
  private fieldBrushR = -1;

  constructor(private readonly map: Basemap) {
    this.overlay = defineAppOverlay(map, {
      id: 'heat',
      name: '自绘热力层 · 灰度累积 + 渐变着色',
      zIndex: 110,
      zooms: [3, 20],
      // 百度 runtime 必须透传:不传则内核回退到全局 AMap.CustomLayer,
      // 百度页面没有 AMap,第一次 invalidate 建层就抛"运行时没有 AMap.CustomLayer"。
      runtime: this.map.overlayRuntime,
      canPaint: () => this.visible && this.counts.length > 0,
      paint: (env) => this.paint(env),
      extras: () => {
        const r = heatBrushRadii(this.cellPx, this.style.radius);
        return {
          built: this.overlay.mounted,
          visible: this.visible,
          note: `归一化上限 ${Math.round(this.lastMax)} · 格距 ${this.cellPx.toFixed(1)}px · 场 ${r.field.toFixed(0)}/核 ${r.core.toFixed(0)}px · 灰度 ${this.grayW}×${this.grayH}`,
        };
      },
    });
    // 开发期把实例挂到 window,现场排查可直接看 __hmHeat.snapshot()
    if (import.meta.env.DEV) {
      (window as unknown as { __hmHeat?: CanvasHeatLayer }).__hmHeat = this;
    }
  }

  /** 给现场排查用的一屏快照:不用打开调试面板也能确认数据/归一化/建层状态 */
  snapshot() {
    const r = heatBrushRadii(this.cellPx, this.style.radius);
    return {
      visible: this.visible,
      points: this.counts.length,
      max: this.lastMax,
      targetMax: this.targetMax,
      gray: `${this.grayW}×${this.grayH}`,
      cellPx: this.cellPx,
      coreRadius: r.core,
      fieldRadius: r.field,
      radius: this.style.radius,
      opacity: this.style.opacity,
      mounted: this.overlay.mounted,
      sample: Array.from(this.counts.slice(0, 12)),
    };
  }

  /** 视野判定复用 Frame:只把屏幕内的点算进 P82,缓冲区里的不算 */
  private recomputeMax(): void {
    const size = this.map.getSize();
    const center = this.map.getCenter();
    const frame = new Frame();
    const scale = this.map.frameScale ?? APP_SCALE;
    frame.set(this.map, this.map.getZoom(), center.getLng(), center.getLat(), scale);
    const inView = new Int32Array(this.counts.length);
    let v = 0;
    for (let i = 0; i < this.counts.length; i += 1) {
      const x = frame.x(this.lng[i]);
      if (x < 0 || x > size.width) continue;
      const y = frame.y(mercY(this.lat[i]));
      if (y >= 0 && y <= size.height) inView[v++] = this.counts[i];
    }
    const next = reference(v > 0 ? inView.subarray(0, v) : this.counts);
    this.targetMax = next;
    // 只更新目标;真正的 max 在 paint 里逐帧逼近。首次没有旧画面,直接落位,
    // 否则从 1 起步会先淡后浓地"渐变"出一个并不存在的过渡。
    if (!this.maxReady) {
      this.max = next;
      this.lastMax = next;
      this.maxReady = true;
      this.maxSettled = true;
    } else {
      // 目标变了(滚轮/筛选导致视野 P82 变化)→ 唤醒逐帧逼近
      this.maxSettled = false;
    }
  }

  /** 双尺度那套笔刷按格距标定(1.8× 铺面、0.58× 点睛),圆心必须保持格距:要格心,不要重心 */
  readonly wantsLatticeCenters = true;

  setDataset(
    lng: Int32Array,
    lat: Int32Array,
    count: Int32Array,
    keep?: Uint8Array | null,
    cellPx?: number,
  ): void {
    if (cellPx !== undefined && Number.isFinite(cellPx) && cellPx > 0) this.cellPx = cellPx;
    const n = lng.length;
    const pts: number[] = [];
    for (let i = 0; i < n; i += 1) {
      if (keep && keep[i] !== 1) continue;
      pts.push(i);
    }
    this.lng = new Float64Array(pts.length);
    this.lat = new Float64Array(pts.length);
    this.counts = new Int32Array(pts.length);
    for (let j = 0; j < pts.length; j += 1) {
      const i = pts[j];
      this.lng[j] = lng[i] / 1e6;
      this.lat[j] = lat[i] / 1e6;
      this.counts[j] = count[i];
    }
    this.recomputeMax();
    if (this.counts.length > 0) {
      this.overlay.invalidate();
      this.overlay.setTotal(this.counts.length);
    } else {
      this.overlay.release();
    }
  }

  clear(): void {
    this.lng = new Float64Array(0);
    this.lat = new Float64Array(0);
    this.counts = new Int32Array(0);
    this.grayW = 0;
    this.grayH = 0;
    this.overlay.release();
  }

  setStyle(style: Partial<HeatLayerStyle>): void {
    const next = { ...this.style, ...style };
    const radiusChanged = next.radius !== this.style.radius;
    this.style = next;
    if (radiusChanged) {
      this.coreBrushR = -1;
      this.fieldBrushR = -1;
    }
    this.overlay.invalidate();
  }

  setVisible(visible: boolean): void {
    this.visible = visible;
    if (visible) this.overlay.show();
    else this.overlay.hide();
  }

  get countPoints(): number {
    return this.counts.length;
  }

  get count(): number {
    return this.counts.length;
  }

  get maxWeight(): number {
    return this.lastMax;
  }

  /**
   * 建径向渐变笔刷:中心黑不透明、边缘透明,半径按灰度图分辨率缩放。
   * 密度存在 alpha 通道(RGB 全 0),查表时再换成渐变色。
   */
  private buildBrush(
    radiusPx: number,
    profile: ReadonlyArray<readonly [number, number]>,
  ): HTMLCanvasElement {
    const r = Math.max(2, Math.round(radiusPx * GRAY_SCALE));
    const b = document.createElement('canvas');
    b.width = b.height = r * 2;
    const c = b.getContext('2d');
    if (c) {
      const g = c.createRadialGradient(r, r, 0, r, r, r);
      for (const [stop, alpha] of profile) {
        g.addColorStop(stop, `rgba(0,0,0,${alpha})`);
      }
      c.fillStyle = g;
      c.fillRect(0, 0, r * 2, r * 2);
    }
    return b;
  }

  /** 建/取小实心核笔刷 */
  private ensureCoreBrush(radiusPx: number): HTMLCanvasElement {
    const r = Math.max(2, Math.round(radiusPx * GRAY_SCALE));
    if (this.coreBrush && this.coreBrushR === r) return this.coreBrush;
    this.coreBrush = this.buildBrush(radiusPx, CORE_PROFILE);
    this.coreBrushR = r;
    return this.coreBrush;
  }

  /** 建/取密度场笔刷 */
  private ensureFieldBrush(radiusPx: number): HTMLCanvasElement {
    const r = Math.max(2, Math.round(radiusPx * GRAY_SCALE));
    if (this.fieldBrush && this.fieldBrushR === r) return this.fieldBrush;
    this.fieldBrush = this.buildBrush(radiusPx, FIELD_PROFILE);
    this.fieldBrushR = r;
    return this.fieldBrush;
  }

  private paint(env: PaintEnv): number {
    const main = env.ctx;
    const w = env.width;
    const h = env.height;
    if (w <= 0 || h <= 0) return 0;

    // 归一化上限在渲染帧里持续逼近目标(不是在 setDataset 里推一步就停)。
    // 未收敛就再排一帧,滚轮停下后颜色仍会自己走到终值 —— 同一片数据无论
    // 滚动节奏如何,最终颜色一致,不再"忽红忽淡"。
    if (!this.maxSettled) {
      const next = smoothMax(this.max, this.targetMax);
      this.max = next.value;
      this.lastMax = next.value;
      this.maxSettled = next.settled;
      if (!next.settled) this.overlay.invalidate();
    }

    const gw = Math.max(1, Math.round(w * GRAY_SCALE));
    const gh = Math.max(1, Math.round(h * GRAY_SCALE));
    if (this.grayW !== gw || this.grayH !== gh) {
      this.gray.width = gw;
      this.gray.height = gh;
      this.grayW = gw;
      this.grayH = gh;
      this.grayCtx = this.gray.getContext('2d', { willReadFrequently: true });
    }
    const gc = this.grayCtx;
    if (!gc) return 0;

    // 1) 灰度累积:source-over 渐近叠加(绝不是 lighter,见文件头注释)
    gc.setTransform(1, 0, 0, 1, 0, 0);
    gc.clearRect(0, 0, gw, gh);
    gc.globalCompositeOperation = 'source-over';
    // 每个桶画两笔,起点都是 weight = count/max(min=0,heatmap.js `_renderData` 口径):
    //   1) 密度场(半径 1.8×格距、峰值 0.30×weight):单桶只到黄绿,邻桶互相
    //      source-over 在密集区铺出橙红连续场 —— 恒等不压缩,层次不被饱和吃掉;
    //   2) 头部补峰(半径 0.58×格距、内 8% 软平台):强度 = weight^2.4,头部桶在
    //      自身圆心垫出可见红心,中段桶退到橙绿,数字仍同圆。
    // 小值兜底 .01 沿用 heatmap.js(globalAlpha 太小读不出 imageData)。
    const radii = heatBrushRadii(this.cellPx, this.style.radius);
    const core = this.ensureCoreBrush(radii.core);
    const field = this.ensureFieldBrush(radii.field);
    const cr = core.width / 2;
    const fr = field.width / 2;
    const inv = this.max > 0 ? 1 / this.max : 1;
    // 视野裁剪留量要覆盖扰动后的最大场:半径 (1+FIELD_JITTER)×(1+FIELD_ASPECT_JITTER)
    // + 场心偏移 FIELD_SHIFT×。核偏瓣最远 (1+FIELD_JITTER+CORE_JITTER+1)*cr 仍远小于场。
    const pad =
      fr * (1 + FIELD_JITTER + FIELD_SHIFT) * (1 + FIELD_ASPECT_JITTER) + 2;

    /** 有机核笔刷:以 (cx,cy) 为中心,椭圆化 (sx,sy) + 旋转 rot 后落笔 */
    const drawCore = (
      cx: number,
      cy: number,
      alpha: number,
      radius: number,
      sx: number,
      sy: number,
      rot: number,
    ): void => {
      gc.globalAlpha = alpha < 0.01 ? 0.01 : alpha;
      gc.save();
      gc.translate(cx, cy);
      gc.rotate(rot);
      gc.scale(sx, sy);
      gc.drawImage(core, -radius, -radius, radius * 2, radius * 2);
      gc.restore();
    };
    for (let i = 0; i < this.counts.length; i += 1) {
      const x = env.frame.x(this.lng[i]) * GRAY_SCALE;
      const y = env.frame.y(mercY(this.lat[i])) * GRAY_SCALE;
      if (x < -pad || y < -pad || x > gw + pad || y > gh + pad) continue;
      const a = weightToAlpha(this.counts[i] * inv);
      // 每桶一套扰动:核只在半径上变(圆心不动,保住同圆),场连半径带圆心一起抖,
      // 让场形不再是一排同心圆 —— 这是「飘逸/不确定性」的直接来源。
      const v = brushVariation(this.lng[i] * 1e6, this.lat[i] * 1e6);
      const vr = fr * v.field;
      const vc = cr * v.core;
      const fx = x + v.fx * fr;
      const fy = y + v.fy * fr;
      const fa = a * FIELD_PEAK;
      // 密度场也轻微椭圆化并跟着桶的旋转角转,连片场不再是同心圆的叠加。
      gc.globalAlpha = fa < 0.01 ? 0.01 : fa;
      gc.save();
      gc.translate(fx, fy);
      gc.rotate(v.rot);
      gc.scale(v.fsx, v.fsy);
      gc.drawImage(field, -vr, -vr, vr * 2, vr * 2);
      gc.restore();
      // 补峰单独走主次压缩:场照旧恒等铺面,只有头部桶才在圆心垫出可见热峰。
      // 主核椭圆化 + 旋转 → 不再是正圆;圆心仍钉在桶心,数字同圆不破。
      const ca = coreWeightToAlpha(a);
      drawCore(x, y, ca, vc, v.sx, v.sy, v.rot);
      // 一侧的偏瓣:把轮廓鼓成有机斑块,高德那种「不规则热核」的直接来源。
      // 只对够强的核画(小案量不画尾巴),强度减半免得盖过主峰。
      if (ca >= CORE_LOBE_MIN_ALPHA) {
        const lx = x + Math.cos(v.lobeAngle) * v.lobeDist * vc;
        const ly = y + Math.sin(v.lobeAngle) * v.lobeDist * vc;
        drawCore(lx, ly, ca * CORE_LOBE_ALPHA, vc * v.lobeScale, v.sy, v.sx, v.rot);
      }
    }
    gc.globalAlpha = 1;

    // 2) 查表着色:heatmap.js `_colorize` 逐点等价
    //   alpha = imgData[i]        (灰度字节,0~255,直接当色带位置)
    //   finalAlpha = clamp(alpha, minOpacity, maxOpacity)
    //   imgData[i-3..i-1] = palette[alpha*4 .. +2]
    // 没有 gamma、没有 floor + span 重算 —— 那两层自创加工正是颜色失真的来源。
    const img = gc.getImageData(0, 0, gw, gh);
    const data = img.data;
    const minA = Math.round(255 * HEAT_MIN_OPACITY);
    const maxA = Math.round(255 * this.style.opacity);
    for (let p = 0; p < data.length; p += 4) {
      const a = data[p + 3];
      if (a === 0) continue;
      const t = densityToStop(a);
      const k = Math.round(t * 255) * 3;
      data[p] = LUT[k];
      data[p + 1] = LUT[k + 1];
      data[p + 2] = LUT[k + 2];
      // 灰度值本身即密度即透明度,clamp 到 [minOpacity, maxOpacity]
      data[p + 3] = a < minA ? minA : a > maxA ? maxA : a;
    }
    gc.putImageData(img, 0, 0);

    // 3) 放大到主画布(热力是模糊色块,双线性放大足够)
    main.save();
    main.imageSmoothingEnabled = true;
    main.drawImage(this.gray, 0, 0, gw, gh, 0, 0, w, h);
    main.restore();
    return this.counts.length;
  }

  destroy(): void {
    unregisterDebugLayer('heat');
    if (import.meta.env.DEV) {
      const w = window as unknown as { __hmHeat?: CanvasHeatLayer };
      if (w.__hmHeat === this) delete w.__hmHeat;
    }
    this.overlay.destroy();
    this.gray.width = 0;
    this.gray.height = 0;
  }
}