BaiduNativeHeatLayer.ts 18.1 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
/**
 * 百度内置热力层 —— BMapGL.Heatmap(JSAPI 4.0 官方 WebGL 图层)。
 *
 * 2026-11-25 从 git 历史(commit 2e69c4b)恢复为**可切换的第二实现**:
 * 用 `?heat=official` 启用,默认仍是自绘层(CanvasHeatLayer)。目的是拿官方 WebGL
 * 热力做 A/B 对照 —— 用户给的调研要点是「官方内置 + 动态半径/归一化调整可能更好」。
 *
 * 历史沿革(决定这里为什么这样写,别轻易改):
 *   1) 曾用内置层,但默认 max=100 且改 max 不重建 GPU 缓冲 → 一片饱和红。
 *      2e69c4b 修好:构造时传真实 max,后续换 max 时先 setOptions 再 setData;
 *   2) 49a724b 又整体切到自绘,根因是**百度投影口径**:GL 用等效 152.874px 瓦片 +
 *      椭圆纬度斜率,而内置层按自己的口径画,与自绘的数字层(已按 BAIDU_TILE_SIZE
 *      对齐)会错位。这里只做视觉 A/B,不承诺与数字严丝合缝。
 *
 * 2026-11-25 官方层调参(同视野截图实证):
 *   官方层是**单笔固定半径** source-over,没有自绘层的双尺度分工。原 size=80(半径)
 *   在约 35px 的屏幕格距下每像素被十几笔叠加 → alpha 饱和到色带末端 → 整片红海
 *   (数值模拟 .tmp_official_grid 的 CURRENT 精确复现了用户截图)。唯一有效杠杆是
 *   **缩小 size**:size=32 + opacity=0.85 + max=P82 时红核退回独立、青绿黄过渡仍在。
 *   三个值都做成 URL 可调(heatSize / heatOpacity / heatMax),滑杆仍按相对档位生效:
 *   默认档 80/0.95 = 1× → 32/0.85;拖到半档 40 → 16px。
 *
 * 2026-11-25 原始点 A/B(?heat=official&heatData=raw):
 *   官方 demo(lbs.baidu.com/jsapi/demo/layer/heatmap/unit.html)的配置是
 *   `unit:'m', size:800, max:60` + 35058 个**原始点**。此前蜂窝的根因不是 API,而是
 *   我们喂了 350 个聚合桶 + 32px 绝对半径:桶距 30~60px,半径盖不住 → 一个桶一个圆盘。
 *   `setRawDataset()` 走 demo 口径:unit='m'、size=800 米、每点权重 1。
 *   原始点由 Worker 抽样后零拷贝回传(见 aggregate.worker 的 handleRawPoints)。
 *
 * 2026-11-25 阈值修正(同视野截图实证:蜂窝没了但整片玫红、无过渡无主次):
 *   上一版把 raw 模式的 max 设成 1 —— 逐条权重 1 直接就是满强度,3.5 万点叠加
 *   在任何密度下灰度都饱和到色带末端 → 纯玫红地毯。百度官方文档 `max` 是
 *   **权重归一化上界**(默认 100),demo 的 max=60 正是靠它把每点贡献压到 1/60,
 *   让灰度按真实密度爬升,只有最密的头部才到红端。现在 raw 默认 max=60(同 demo),
 *   并以 `heatRawMax` URL 旋钮开放 1~500:调高 → 红更稀有更突出;调低 → 整体更暖。
 *   ⚠️ max 必须和 size 成对看:半径放大后每像素被更多点覆盖,max 也要同步抬高,
 *   否则又烧成红海。
 *
 * 2026-11-25 尺度再标定(超人:「点跟热度对不上、点太多很杂乱」):
 *   demo 的 800 米半径在 z12 ≈ 13.5px,但我们默认 z11 只有 **6.8px** —— 比
 *   数字白盘半径 8~12px 还小,红心被白盘盖住或错开,看起来就是「点对不上热度」。
 *   默认改为 **2000 米**(z11 ≈ 17px,刚好盖过白盘),并按覆盖面积守恒把
 *   max 从 60 抬到 375(面积比 (2000/800)² = 6.25,60×6.25 = 375),维持同样的
 *   红核稀有度与青绿黄过渡。这是**按视野缩放标定**,不再是照抄 demo 的绝对值;
 *   z12 下 2000 米会偏大,可用 `heatSize=800&heatRawMax=60` 切回 demo 口径。
 *
 * 数据格式:setData 吃 GeoJSON FeatureCollection,权重取 properties[weightField]
 * (这里用 count),坐标按全局 GCJ-02 口径直接传(load.ts 已声明 BMAP_COORD_GCJ02)。
 */

import { Frame, mercY } from '@hm/map-overlay';
import { HEAT_GRADIENT } from '../../palette';
import {
  DEFAULT_HEAT_STYLE,
  HEAT_MIN_OPACITY,
  reference,
  type HeatLayerStyle,
} from '../../heatReference';
import type { BaiduLayerLike } from './load';
import type { BaiduBasemap } from './BaiduBasemap';
import type { HeatLayerLike } from '../types';
import { registerDebugLayer, unregisterDebugLayer } from '../../../debug/debugBus';

import { expandBucketsToDots } from './bucketDots';

type HeatPoint = { lng: number; lat: number; count: number };

/**
 * 官方层的数据口径:
 *   - raw        Worker 抽样的原始点(demo 口径)—— 热力峰在原始点密度最高处,与数字不同源;
 *   - bucketDots **把数字用的那批桶按案量展开成点阵**再喂 —— 峰落在桶心,与数字严格同圆;
 *   - bucket     直接喂聚合桶(旧回退)—— 单笔固定半径在桶距下蜂窝/红海两难。
 */
export type OfficialHeatMode = 'raw' | 'bucketDots' | 'bucket';

/** 官方层 URL 调参。size/opacity 是 80/0.95 默认档对应的实际生效值;maxScale 乘在 P82 上 */
export interface OfficialHeatConfig {
  size: number;
  opacity: number;
  maxScale: number;
  /** true = 走原始点喂数路径(raw / bucketDots);false = 直接喂桶(bucket) */
  raw: boolean;
  mode: OfficialHeatMode;
  /** 原始点模式下的半径单位与米数:官方 demo 用 unit:'m' + size=800 */
  unit: 'm' | 'px';
  /** 原始点抽样上限(raw 模式,官方 demo 35058 点)/ 点阵总预算(bucketDots 模式) */
  limit: number;
  /** 原始点的权重归一化上界(百度 max,官方 demo=60);越大红心越稀有 */
  rawMax: number;
  /** bucketDots 模式:点阵相对桶宽的单侧散布半径(0.45 = 45% 格宽) */
  spread: number;
}

/**
 * 官方层默认配置 = 按 z11 视野标定的 demo 口径:
 * unit='m' + size=2000 米(红核盖过数字白盘)+ max=375(面积守恒后的归一化上界)。
 * demo 原值是 size=800/max=60(z12 视野);zip 到 z12 可用 URL 切回。
 * bucketDots 模式与 raw 共用同一套标定(size=2000/max=375):两者都是每点权重 1,
 * 唯一差别是点从哪来;4000/140 曾在错误模拟下试用,真实数据直接烧成红海(见 index.ts)。
 * 注意 size 在 raw 模式下是**米**,不是像素;heatData=bucket 回退模式才用像素。
 * max 不能是 1:逐条权重 1 时 max=1 等于不归一化,整片饱和红海。
 */
export const DEFAULT_OFFICIAL_CONFIG: OfficialHeatConfig = {
  size: 2000,
  opacity: 0.85,
  maxScale: 1,
  raw: true,
  mode: 'raw',
  unit: 'm',
  limit: 35000,
  rawMax: 375,
  spread: 0.45,
};

export class BaiduNativeHeatLayer implements HeatLayerLike {
  private heat: BaiduLayerLike | null = null;
  private style: HeatLayerStyle = { ...DEFAULT_HEAT_STYLE };
  private visible = true;
  private data: HeatPoint[] = [];
  /** 原始点模式:Worker 抽样回传的经纬度(存储刻度 ×1e6),一条点权重=1 */
  private rawLng: Int32Array = new Int32Array(0);
  private rawLat: Int32Array = new Int32Array(0);
  private rawKey = '';
  /** raw 模式下数字层的浓淡仍按桶 P82,与热力 WebGL 的归一化上界分开记 */
  private bucketRefMax = 1;
  private max = 1;
  private lastMax = 0;
  private feedKey = '';
  private readonly frame = new Frame();
  private inViewBuf = new Int32Array(0);
  private allBuf = new Int32Array(0);
  private readonly geo: { type: 'FeatureCollection'; features: unknown[] } = {
    type: 'FeatureCollection',
    features: [],
  };

  constructor(
    private readonly basemap: BaiduBasemap,
    private readonly cfg: OfficialHeatConfig = DEFAULT_OFFICIAL_CONFIG,
  ) {
    registerDebugLayer({
      id: 'heat',
      name: 'BMapGL.Heatmap · 百度官方热力底色层(?heat=official)',
      zIndex: 110,
      kind: 'webgl',
      canvas: null,
      read: () => ({
        built: this.heat !== null,
        visible: this.visible,
        released: this.heat === null,
        cssW: 0,
        cssH: 0,
        dpr: 0,
        total: this.count,
        painted: this.heat && this.visible ? this.count : 0,
        drawn: 0,
        skipped: 0,
        lastMs: 0,
        light: false,
        note: `官方 WebGL · ${this.cfg.mode === 'bucketDots' ? `桶展点阵 ${this.rawLng.length}(桶心同源,spread ${this.cfg.spread})` : this.cfg.raw ? `原始点 ${this.rawLng.length}(demo 口径 ${this.cfg.unit}=${this.cfg.size})` : '聚合桶'} · max=${Math.round(this.lastMax)} · opacity ${this.effectiveOpacity().toFixed(2)}`,
      }),
    });
  }

  /** 滑杆档位 → 实际半径:raw 模式是米(demo 800),桶模式是像素(旧 32) */
  private effectiveSize(): number {
    const gear = Math.max(0.1, this.style.radius / DEFAULT_HEAT_STYLE.radius);
    return Math.max(1, this.cfg.size * gear);
  }

  /** 半径单位:raw 模式按 demo 用米(半径随真实距离固定,不随缩放漂移) */
  private effectiveUnit(): 'm' | 'px' {
    return this.cfg.raw ? this.cfg.unit : 'px';
  }

  /** 滑杆档位 → 实际不透明度:与 size 同比,默认档 0.95 = 1× → cfg.opacity */
  private effectiveOpacity(): number {
    const gear = Math.max(0.1, this.style.opacity / DEFAULT_HEAT_STYLE.opacity);
    return Math.min(1, Math.max(HEAT_MIN_OPACITY, this.cfg.opacity * gear));
  }

  /**
   * max 必须在构造时就传对:百度 4.0 脚本里 Heatmap 的 max 默认 100,
   * setData 触发 _rebuild 生成 GPU 缓冲时按当时的 max 归一化,而改 max 不重建。
   * 所以后续换 max 必须先 setOptions 再 setData(见 setDataset)。
   */
  private ensure(max: number): BaiduLayerLike {
    if (!this.heat) {
      const Ctor = this.basemap.gl.Heatmap;
      if (!Ctor) {
        throw new Error('当前百度 JSAPI 未提供内置 BMapGL.Heatmap(需 JSAPI 4.0 入口)');
      }
      this.heat = new Ctor({
        size: this.effectiveSize(),
        unit: this.effectiveUnit(),
        max,
        min: 0,
        minOpacity: HEAT_MIN_OPACITY,
        maxOpacity: this.effectiveOpacity(),
        gradient: HEAT_GRADIENT,
        maxZoom: 20,
        zIndex: 110,
        visible: this.visible,
        weightField: 'count',
        // 官方强烈建议给 referCenter,规避大坐标 float32 抖动
        referCenter: { lng: 114.06, lat: 22.62 },
      });
      this.basemap.raw.addLayer(this.heat);
    }
    return this.heat;
  }

  /**
   * 桶点阵喂数(?heat=official&heatMode=bucketDots):把数字层那批桶按案量展开成点阵。
   *
   * 与 raw 模式的本质差别:raw 吃 Worker 抽样的原始点,峰在密度最高处、与数字不同源;
   * 这里吃的是**数字层同一批桶**,点围绕桶心(=数字圆心)散布,所以严格同圆。
   * 展开在主线程完成(桶数据本就在那儿),不额外开 Worker 请求。
   *
   * @param keep 过滤掩码,与数字层共用同一张表 —— 被过滤的桶不产生热力点
   * @param budget 点阵总预算(URL heatLimit),高案量桶按比例多分、低案量桶保底 1 点
   */
  setBucketDotsDataset(
    lng: Int32Array,
    lat: Int32Array,
    count: Int32Array,
    keep: Uint8Array | null | undefined,
    dLng: number,
    dLat: number,
    budget: number,
    sourceKey = '',
  ): void {
    if (!this.cfg.raw || this.cfg.mode !== 'bucketDots') return;
    const dots = expandBucketsToDots(lng, lat, count, keep, budget, this.cfg.spread, dLng, dLat);
    this.setRawDataset(dots.lng, dots.lat, sourceKey);
  }

  /** raw 模式才需要 Worker 的原始点抽样;bucketDots 的点阵从桶就地展开 */
  get needsWorkerRawPoints(): boolean {
    return this.cfg.mode === 'raw';
  }

  /**
   * 原始点喂数(demo 口径):经纬度是存储刻度 ×1e6,逐条权重 = 1。
   *
   * 关键差异(与 setDataset 的聚合桶口径):
   *   - max 用 `rawMax`(默认 60 = demo 值),不走视野 P82:原始点 P82 恒为 1,
   *     拿它当分母就等于关掉归一化,红海正是这么来的;
   *   - unit='m' + size=800:半径代表真实 800 米,缩放时按投影自动换算像素,
   *     这正是官方 demo 能出连续场、而绝对像素 32px 出蜂窝的原因。
   *   - max 必须在构造时就传对:百度 4.0 的 max 改动不重建 GPU 缓冲(见 ensure)。
   */
  setRawDataset(lng: Int32Array, lat: Int32Array, sourceKey = ''): void {
    if (!this.cfg.raw) return; // 桶模式忽略,避免两路数据互相踩
    const n = Math.min(lng.length, lat.length);
    // sourceKey 让 bucketDots 能带上「桶批次」的指纹:点阵总数恰好相同时,
    // 只比首尾点会误判为同一批,换了筛选却看不到热力变化。
    const key = `${sourceKey}|${n}:${lng[0] ?? 0}:${lat[0] ?? 0}:${lng[n - 1] ?? 0}`;
    if (key === this.rawKey && this.rawLng.length === n) return;
    this.rawLng = lng;
    this.rawLat = lat;
    this.rawKey = key;
    // rawMax 是归一化上界(demo=60):每点贡献 1/60,靠叠加密度爬色阶。
    // maxScale 仍是倍率旋钮:0.5 → 30(更暖),2 → 120(红更稀有)。
    const max = Math.max(1, Math.round(this.cfg.rawMax * this.cfg.maxScale));
    this.lastMax = max;
    const heat = this.ensure(max);
    // 三条点直接铺 GeoJSON:constructor 里已定好 unit/size,setOptions 不再动它们,
    // 免得百度 4.0 的 setOptions 改 unit 不重建缓冲的坑(注释见 ensure)。
    this.geo.features = new Array(n);
    for (let i = 0; i < n; i += 1) {
      this.geo.features[i] = {
        type: 'Feature',
        geometry: { type: 'Point', coordinates: [lng[i] / 1e6, lat[i] / 1e6] },
        properties: { count: 1 },
      };
    }
    heat.setOptions?.({
      max,
      minOpacity: HEAT_MIN_OPACITY,
      maxOpacity: this.visible ? this.effectiveOpacity() : 0,
    });
    heat.setData(this.geo);
    heat.setVisible?.(this.visible);
  }

  setDataset(
    lng: Int32Array,
    lat: Int32Array,
    count: Int32Array,
    keep?: Uint8Array | null,
    cellPx?: number,
  ): void {
    // cellPx 是自绘层按缩放缩放笔刷用的;官方层 radius 是绝对像素,不用这个口径。
    void cellPx;
    const n = lng.length;
    const size = this.basemap.getSize();
    const center = this.basemap.getCenter();
    // 视野内 P82 只用于归一化上限,用百度门面的真实投影口径取点比 APP_SCALE 更准。
    this.frame.set(
      this.basemap,
      this.basemap.getZoom(),
      center.getLng(),
      center.getLat(),
      this.basemap.frameScale,
    );

    const key = `${n}:${lng.length}:${lat.length}:${count.length}:${keep ? 'k' : ''}`;
    const sameSource = key === this.feedKey && this.data.length > 0;
    const data: HeatPoint[] = sameSource ? this.data : [];

    if (this.inViewBuf.length < n) {
      this.inViewBuf = new Int32Array(n);
      this.allBuf = new Int32Array(n);
    }
    const inView = this.inViewBuf;
    const all = this.allBuf;
    let v = 0;
    let a = 0;
    for (let i = 0; i < n; i += 1) {
      if (keep && keep[i] !== 1) continue;
      const lng6 = lng[i] / 1e6;
      const lat6 = lat[i] / 1e6;
      const c = count[i];
      if (!sameSource) data.push({ lng: lng6, lat: lat6, count: c });
      all[a++] = c;
      const x = this.frame.x(lng6);
      if (x < 0 || x > size.width) continue;
      const y = this.frame.y(mercY(lat6));
      if (y >= 0 && y <= size.height) inView[v++] = c;
    }
    this.feedKey = key;
    this.data = data;
    // maxScale >1 抬高上限 → 红核更少更集中在头部;<1 让更多桶烧到暖端。
    const ref = Math.max(
      1,
      Math.round(reference(v > 0 ? inView.subarray(0, v) : all.subarray(0, a)) * this.cfg.maxScale),
    );
    // raw 模式下热力 WebGL 吃原始点(max=rawMax×maxScale),桶 P82 只供数字层分浓淡。
    // ⚠️ 这里不写 this.max:ensure 首次建层若被 setVisible 抢先触发,必须拿 raw 的阈值,
    // 而百度 4.0 改 max 不重建 GPU 缓冲(见 ensure 注释),建错就再也纠不回来。
    if (this.cfg.raw) {
      this.bucketRefMax = ref;
      // setVisible 可能早于 setRawDataset 触发,ensure 会拿 this.max 建 WebGL 层;
      // 这里同步成 raw 阈值,避免先用 1 建错缓冲(百度改 max 不重建,见 ensure)。
      this.max = Math.max(1, Math.round(this.cfg.rawMax * this.cfg.maxScale));
      this.data = data;
      this.feedKey = key;
      return;
    }
    this.max = ref;

    // 数据与归一化上限都没变 → 只管显隐,不重传 GPU 数据
    if (sameSource && this.lastMax === this.max) {
      this.heat?.setVisible?.(this.visible);
      return;
    }
    this.lastMax = this.max;
    const heat = this.ensure(this.max);
    this.geo.features = data.map((p) => ({
      type: 'Feature',
      geometry: { type: 'Point', coordinates: [p.lng, p.lat] },
      properties: { count: p.count },
    }));
    // 顺序要紧:先把新 max 写进 _style,再 setData 重建缓冲。
    heat.setOptions?.({
      max: this.max,
      size: this.effectiveSize(),
      minOpacity: HEAT_MIN_OPACITY,
      maxOpacity: this.visible ? this.effectiveOpacity() : 0,
    });
    heat.setData(this.geo);
    heat.setVisible?.(this.visible);
  }

  clear(): void {
    this.data = [];
    this.feedKey = '';
    this.rawLng = new Int32Array(0);
    this.rawLat = new Int32Array(0);
    this.rawKey = '';
    this.geo.features = [];
    this.heat?.clearData?.();
  }

  setStyle(style: Partial<HeatLayerStyle>): void {
    this.style = { ...this.style, ...style };
    this.heat?.setOptions?.({
      size: this.effectiveSize(),
      maxOpacity: this.effectiveOpacity(),
    });
  }

  setVisible(visible: boolean): void {
    this.visible = visible;
    if (visible) this.ensure(Math.max(this.max, 1)).setVisible?.(true);
    else this.heat?.setVisible?.(false);
  }

  get count(): number {
    return this.cfg.raw ? Math.min(this.rawLng.length, this.rawLat.length) : this.data.length;
  }

  get rawPointLimit(): number {
    return this.cfg.limit;
  }

  get maxWeight(): number {
    return this.cfg.raw ? this.bucketRefMax : this.lastMax;
  }

  destroy(): void {
    unregisterDebugLayer('heat');
    if (this.heat) {
      this.basemap.raw.removeLayer(this.heat);
      this.heat = null;
    }
    this.data = [];
    this.geo.features = [];
  }
}