HeatLayer.ts
10.7 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
import { HEAT_GRADIENT } from '../../palette';
import { resolveHeatMapCtor } from './load';
import { Frame, mercY } from '@hm/map-overlay';
import { APP_SCALE } from '../../appOverlay';
import { registerDebugLayer, unregisterDebugLayer } from '../../../debug/debugBus';
export type { HeatLayerStyle } from '../../heatReference';
export { DEFAULT_HEAT_STYLE, MAX_REF_PERCENTILE, reference } from '../../heatReference';
import {
DEFAULT_HEAT_STYLE,
HEAT_MIN_OPACITY,
reference,
type HeatLayerStyle,
} from '../../heatReference';
/** 喂给热力后端的一个权重点:桶中心 + 起数 */
type HeatPoint = { lng: number; lat: number; count: number };
export class HeatLayer {
private heat: AMap.HeatMap | null = null;
private style: HeatLayerStyle = { ...DEFAULT_HEAT_STYLE };
private visible = true;
private dataset: AMap.HeatMapDataSet | null = null;
/**
* 上一次喂进去的那批桶,连同一遍换算好的点表。
*
* 只按引用判同(数组换了就重建),所以聚合一换结果、显著性掩码一重算(它是新建的表),
* 这份缓存立刻作废 —— 不存在「拿旧坐标画新数」的口子。
*/
private feed: {
lng: Int32Array;
lat: Int32Array;
count: Int32Array;
keep: Uint8Array | null;
data: HeatPoint[];
} | null = null;
/**
* 视野判定的投影基准,每次喂数据时按当前缩放与中心重设一次。
*
* 高德自己不带「这批桶哪些在屏幕里」的接口,setDataSet 收到什么就画什么,
* 所以分位数只能我们自己按视野内那批算 —— 这件事原本靠逐个调 lngLatToContainer,
* 几万个桶就是几万次内部投影加同样多个临时对象(喂数据发生在每次聚合之后,
* 拖动时也会走,这笔钱正是「拖一下卡一下」的一部分)。换成一次换算 + 每桶两次乘加。
*/
private readonly frame = new Frame();
/**
* 两批发给分位数的权重缓冲(视野内那批 / 整批),按桶数增长后反复复用。
*
* 原先每次喂数据都新建两份 `new Int32Array(n)`:n 是聚合桶数,缓冲视口下能到一两万,
* 一次就是十几万字节,而这件事每 moveend、每开一次抽屉都要来一遍。
* 复用之后唯一的区别是里面得按 `v`/`a` 取前段(下面用 subarray 表达),内容算法一个字没改。
*/
private inViewBuf = new Int32Array(0);
private allBuf = new Int32Array(0);
constructor(private readonly map: AMap.Map) {
// 调试视图里这一层报的是"喂进去多少个权重点"。帧计数留空是诚实的:
// 底色由高德自己的 WebGL 场景逐帧重绘,没有我们这一侧的开帧判定可数。
registerDebugLayer({
id: 'heat',
name: 'AMap.HeatMap · 热力底色层',
zIndex: 110,
kind: 'webgl',
canvas: null,
read: () => ({
built: this.heat !== null,
visible: this.visible,
released: false,
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: `归一化上限 ${Math.round(this.maxWeight)} · 半径 ${this.style.radius}px · 逐帧由 WebGL 重绘`,
}),
});
}
private ensure(): AMap.HeatMap {
if (!this.heat) {
const Ctor = resolveHeatMapCtor();
this.heat = new Ctor(this.map, {
radius: this.style.radius,
// ⚠️ 必须是 [min, max] 数组,传 number 会在 uniform2fv 处崩溃 —— 见类注释
opacity: [HEAT_MIN_OPACITY, this.style.opacity],
gradient: HEAT_GRADIENT,
zooms: [3, 20],
visible: this.visible,
zIndex: 110,
});
}
return this.heat;
}
/**
* 归一化上限为什么用 P82 而不是最大值:
*
* heatmap.js 的权重是 count / max。用全局最大桶当 max 时,只要存在一个
* 极端桶(比如某园区集中报了 300 起),其余几百个桶的比值就被压到 0.05 以下,
* 颜色全落在渐变最左端的靛蓝 —— 实测观感就是「热力几乎看不见,只剩聚合圆圈」。
*
* 取 P82 后,头部约 18% 的桶饱和显示为最高色,其余桶的色阶被整体拉开。
* 这是热力图的常规做法:热点区「封顶」在最高色,本来也不需要再区分 300 和 800。
*
* 上限的具体算法在 reference():分位只是基准,视野内分布越「彼此接近」越会向实际峰值
* 补一段头空。理由与实测数字写在那里,调这两个旋钮之前请先读它。
*
* ⚠️ 分位数按**实际进图、且落在当前视野内**的那批桶算。
* 按全量算的话,被保留的本来就全是热点,几乎个个顶到上限,
* 「黑点之间谁更危险」又分不清了 —— 而这一层正是为了区分它们才留下来的。
* 代价是开关降噪时同一片热点的深浅会有变化;这是刻意的,比较的样本换了。
*
* 视野内这一半同样关键:聚合请求带缓冲区,缓冲区里的桶在屏幕外却仍在数组里。
* 把它们算进参考,就会出现「放大到街区,颜色深浅由屏幕外的园区决定」——
* 实测表现是放大后整片热点退成黄绿,看着像没有热力。
*
* @param keep 逐桶过滤器,1 才进热力。降噪开启时由 MapStage 从聚合层取现成的表
* (两处必须同一张表,否则会出现「数字淡出、热力还亮着」的半截状态)。
*/
setDataset(
lng: Int32Array,
lat: Int32Array,
count: Int32Array,
keep?: Uint8Array | null,
// 高德内置 HeatMap 的半径就是绝对像素(style.radius),不接百度的实际格距口径;
// 这里保留可选参数只为与 HeatLayerLike 契约一致。
_cellPx?: number,
) {
const heat = this.ensure();
const n = lng.length;
const size = this.map.getSize();
const center = this.map.getCenter();
// 一次换算代替每桶一次 lngLatToContainer:判断「这一桶在不在视野里」原先要为每个桶
// 在高德内部新建一个 LngLat 再投影一次(两万桶就是两万次)。投影是纯几何,
// 缩放与中心定了就定死,所以取一次基准,剩下按桶做两次乘加(投影口径见 APP_SCALE)。
this.frame.set(this.map, this.map.getZoom(), center.getLng(), center.getLat(), APP_SCALE);
// 这批桶的「同一份底数」是否还指着同一批数:数据集来自 Worker 的全量降采样,与视野无关,
// 换的只是当前视野里挑出来的那一份权重。
const prev = this.feed;
const sameSource =
prev !== null &&
prev.lng === lng &&
prev.lat === lat &&
prev.count === count &&
prev.keep === (keep ?? null);
const data: HeatPoint[] = sameSource && prev ? prev.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];
// 只有换了底数才建对象:一桶一个对象,两万桶就是两万多次分配,
// 而它每次 moveend 都要重来一遍 —— 堆压力正是「拖一阵子越来越沉」的来源之一。
// 深浅口径不受影响:max 每帧照当前视野重算,进图的还是同一批点。
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.feed = { lng, lat, count, keep: keep ?? null, data };
const max = reference(v > 0 ? inView.subarray(0, v) : all.subarray(0, a));
// 点表的对象与归一化上限都和上一份一模一样 → 高德那边换了也是同一张图。
// 而 setDataSet 会把整批点重新塞进 WebGL(几万个顶点 + 一次纹理上传),
// 这件事在「开抽屉、切图层、点黑点」这类不会改变视野的调用里发生得莫名其妙地频繁。
// visible 仍然要设:那条路只管显隐,不重传数据。
if (prev !== null && prev.data === data && this.dataset !== null && this.dataset.max === max) {
heat.setOptions({ visible: this.visible });
return;
}
this.dataset = { data, max };
heat.setDataSet(this.dataset);
heat.setOptions({ visible: this.visible });
}
/** 数据被筛选清空时要把旧数据集显式清掉,否则地图上会残留上一次的热力色块 */
clear() {
this.dataset = null;
// 缓存的那一份点表跟着作废:下次喂的是另一批桶,不能拿旧的坐标去画新的数
this.feed = null;
this.heat?.setDataSet({ data: [], max: 1 });
}
setStyle(style: Partial<HeatLayerStyle>) {
this.style = { ...this.style, ...style };
// opacity 整体是 [min, max],界面上拖的只是上限,下限恒为 HEAT_MIN_OPACITY
this.heat?.setOptions({
radius: this.style.radius,
opacity: [HEAT_MIN_OPACITY, this.style.opacity],
});
}
setVisible(visible: boolean) {
this.visible = visible;
if (!this.heat) return;
// 首次显示时才创建实例:如果用户一进来就关掉热力层,不必为它初始化 WebGL 上下文
if (visible) this.ensure().show();
else this.heat.hide();
}
get count(): number {
return this.dataset?.data.length ?? 0;
}
/**
* 这份数据集实际用的归一化上限(视野内、过滤后的分位 + 紧凑度补偿)。
*
* 聚合层的数字浓淡读它,而不是自己再算一遍:两处若要「淡字压在淡底色、浓字压在亮底色」,
* 就必须是同一个分母。没喂过数据时返回 0,调用方据此退回自己的兜底值。
*/
get maxWeight(): number {
return this.dataset?.max ?? 0;
}
destroy() {
unregisterDebugLayer('heat');
// AMap JS API 2.0 的 HeatMap 运行时没有 destroy() 方法(d.ts 误声明了),
// 调用会抛 "destroy is not a function"。官方移除方式就是 setMap(null)。
this.heat?.setMap(null);
this.heat = null;
this.dataset = null;
this.feed = null;
}
}