grid.test.ts 8.41 KB
/**
 * 分格几何的守卫。
 *
 * 这一组盯的是「分格与投影是不是同一套换算」。这件事失效的方式很安静:
 * 两边各按各的比例尺算,点照样落在屏幕上、数字照样写得出,只是格子集体偏一角 ——
 * 于是「点压在线边上」「圆圈不在重心」这类现象没人能一眼看出根因,也没有构建期检查会报。
 * 所以这里全部拿**真实球形墨卡托投影**去比,而不是比一个手算的常数。
 */
import { describe, expect, it } from 'vitest';
import { Frame, mercY, pxPerDegLng } from '../src/frame';
import {
  BUCKET_OFFSET_MAX,
  bucketize,
  latticeCenter,
  cellAt,
  cellAtZoom,
  cellKey,
  cellWidthPx,
  KEY_SHIFT,
  pxPerDegLat,
  type GridCell,
} from '../src/grid';
import { fakeMap, worldPxOf } from './fakes';

/** 用底图自己的投影算两点的屏幕竖直距离 */
function pixelHeight(lng: number, lat: number, dLat: number, zoom: number): number {
  const a = worldPxOf(lng, lat, zoom).y;
  const b = worldPxOf(lng, lat + dLat, zoom).y;
  return Math.abs(a - b);
}

describe('分格几何 · 格子在屏幕上就是那个像素边长', () => {
  for (const zoom of [8, 12, 16, 18]) {
    for (const lat of [0, 22.5, 45]) {
      it(`z${zoom} · 纬度 ${lat}°:横向与纵向都回到 48 像素`, () => {
        const cell = cellAtZoom(zoom, 48, lat);
        expect(cellWidthPx(zoom, cell)).toBeCloseTo(48, 6);
        // 纵向按墨卡托换算:一阶近似,跨的度数极小,与真实投影比到 1% 以内
        const exact = pixelHeight(114.05, lat, cell.dLat, zoom);
        expect(Math.abs(exact - 48) / 48).toBeLessThan(0.01);
      });
    }
  }

  it('缩放翻一级,经度边长减半 —— 屏幕疏密因此不随缩放突变', () => {
    const at = (zoom: number) => cellAtZoom(zoom, 48, 22.5).dLng;
    expect(at(13)).toBeCloseTo(at(12) / 2, 12);
    expect(at(16)).toBeCloseTo(at(12) / 16, 12);
  });

  it('纬度方向比经度方向宽 1/cos(纬度):这就是纬度越高格子越"扁"的那一条换算', () => {
    const ratio = pxPerDegLat(12, 60) / pxPerDegLng(12);
    expect(ratio).toBeCloseTo(2, 8);
  });
});

describe('分格几何 · 与生产投影同源', () => {
  it('用 Frame 走一遍:一格的横向像素数与 cellWidthPx 分毫不差,纵向回到 48', () => {
    const view = { zoom: 12, lng: 114.05, lat: 22.54, w: 800, h: 600 };
    const { map } = fakeMap(view);
    const frame = new Frame();
    frame.set(map, view.zoom, view.lng, view.lat, { tileSize: 256, referenceLat: 22.5 });
    const cell = cellAtZoom(view.zoom, 48, view.lat);
    // 横轴是线性的:这一条应当完全相等,不是"近似相等"
    expect(frame.x(114 + cell.dLng) - frame.x(114)).toBeCloseTo(cellWidthPx(view.zoom, cell), 9);
    // 纵轴走同一支墨卡托纬度:这一格在视图中心那一带的真实高度就是 48
    const mid = view.lat;
    const top = frame.y(mercY(mid + cell.dLat / 2));
    const bottom = frame.y(mercY(mid - cell.dLat / 2));
    expect(Math.abs(bottom - top)).toBeCloseTo(48, 1);
  });

  it('米制口径也同源:参考纬度上,frame.pxPerMeter × 一度经度的米数 = pxPerDegLng', () => {
    const view = { zoom: 12, lng: 114.05, lat: 22.54, w: 800, h: 600 };
    const { map } = fakeMap(view);
    const frame = new Frame();
    const referenceLat = 22.5;
    frame.set(map, view.zoom, view.lng, view.lat, { tileSize: 256, referenceLat });
    // 赤道 1° 经线 × cos(参考纬度) = 这一纬度上 1° 经线实际多少米
    const metersPerDegLng = 111_195 * Math.cos((referenceLat * Math.PI) / 180);
    expect(frame.pxPerMeter * metersPerDegLng).toBeCloseTo(pxPerDegLng(view.zoom), 6);
  });
});

describe('分格 · 格子编号与归属', () => {
  const cell: GridCell = { dLng: 0.25, dLat: 0.2 };

  it('边界上的点归右/上那一格:半开区间,相邻两格不重复计', () => {
    expect(cellAt({ lng: -180, lat: -90 }, cell)).toEqual({ gx: 0, gy: 0 });
    expect(cellAt({ lng: -179.999, lat: -89.999 }, cell)).toEqual({ gx: 0, gy: 0 });
    expect(cellAt({ lng: -179.75, lat: -89.9 }, cell)).toEqual({ gx: 1, gy: 0 });
    expect(cellAt({ lng: -179.7500001, lat: -89.9 }, cell)).toEqual({ gx: 0, gy: 0 });
  });

  it('格子编号拼成单值 key 不串位,且能按 KEY_SHIFT 反解回来', () => {
    const seen = new Set<number>();
    for (let gx = 0; gx < 2000; gx += 37) {
      for (let gy = 0; gy < 2000; gy += 53) {
        const key = cellKey(gx, gy);
        expect(seen.has(key)).toBe(false);
        seen.add(key);
        expect(key % KEY_SHIFT).toBe(gy);
      }
    }
  });
});

describe('分桶', () => {
  const cell: GridCell = { dLng: 0.1, dLat: 0.1 };

  it('每个点归到的格子,与它所在桶的格子编号是同一个 —— 圆圈里的数才等于清单里的行数', () => {
    const pts = [
      { lng: 114.02, lat: 22.51 },
      { lng: 114.021, lat: 22.512 },
      { lng: 114.029, lat: 22.519 },
      { lng: 114.13, lat: 22.51 },
      { lng: 113.91, lat: 22.62 },
    ];
    const out = bucketize({ lng: pts.map((p) => p.lng), lat: pts.map((p) => p.lat) }, cell);
    expect(out.count.length).toBe(3);
    for (const p of pts) {
      const at = cellAt(p, cell);
      const idx = out.gx.findIndex((gx, i) => gx === at.gx && out.gy[i] === at.gy);
      expect(idx).toBeGreaterThanOrEqual(0);
      expect(out.gx[idx]).toBe(at.gx);
      expect(out.gy[idx]).toBe(at.gy);
    }
  });

  it('桶心 = 本格成员均值(第四十五轮):数字站在自己那几起案子上', () => {
    const pts = [114.01, 114.01, 114.012];
    const lats = [22.51, 22.511, 22.513];
    const out = bucketize({ lng: pts, lat: lats }, cell);
    expect(out.count.length).toBe(1);
    expect(out.lng[0]).toBeCloseTo((114.01 + 114.01 + 114.012) / 3, 12);
    expect(out.lat[0]).toBeCloseTo((22.51 + 22.511 + 22.513) / 3, 12);
    expect(out.maxCount).toBe(3);
  });

  it('只有 1 起的那一格,落点就是那一起的坐标:不再有与数据无关的位移', () => {
    // 旧口径在这里最露馅:格心 + 26% 重心 + 20% 流场抖动,数字离案发点中位 20~29px、最远半格
    const out = bucketize({ lng: [114.031], lat: [22.577] }, cell);
    expect(out.lng[0]).toBeCloseTo(114.031, 12);
    expect(out.lat[0]).toBeCloseTo(22.577, 12);
  });

  it('落点只认成员,不认格号:同一份成员换一格平移,偏移完全相同(抖动已删)', () => {
    const a = bucketize({ lng: [114.011, 114.019], lat: [22.511, 22.519] }, cell);
    // 平移一整格(0.1 度)后成员相对格心的位置不变,落点相对格心的位置也不该变
    const b = bucketize({ lng: [114.111, 114.119], lat: [22.511, 22.519] }, cell);
    const ga = cellAt({ lng: 114.011, lat: 22.511 }, cell);
    const gb = cellAt({ lng: 114.111, lat: 22.511 }, cell);
    const ca = latticeCenter(ga.gx, ga.gy, cell);
    const cb = latticeCenter(gb.gx, gb.gy, cell);
    expect(a.lng[0] - ca.lng).toBeCloseTo(b.lng[0] - cb.lng, 12);
    expect(a.lat[0] - ca.lat).toBeCloseTo(b.lat[0] - cb.lat, 12);
  });

  it('重心天然在格内:偏移上界 = 半格,写成常量给断言用', () => {
    expect(BUCKET_OFFSET_MAX).toBe(0.5);
    // 成员贴着格边,均值仍在这一格里
    const out = bucketize({ lng: [114.0001, 114.0002], lat: [22.5001, 22.5002] }, cell);
    const at = cellAt({ lng: 114.0001, lat: 22.5001 }, cell);
    const center = latticeCenter(at.gx, at.gy, cell);
    expect(Math.abs(out.lng[0] - center.lng)).toBeLessThan(cell.dLng / 2);
    expect(Math.abs(out.lat[0] - center.lat)).toBeLessThan(cell.dLat / 2);
  });

  it('latticeCenter 给出格心:逐桶回退层靠它保住「间距 = 格距」', () => {
    const c = latticeCenter(2940, 1125, cell);
    expect(c.lng).toBeCloseTo(-180 + 2940.5 * cell.dLng, 12);
    expect(c.lat).toBeCloseTo(-90 + 1125.5 * cell.dLat, 12);
    const next = latticeCenter(2941, 1125, cell);
    expect(next.lng - c.lng).toBeCloseTo(cell.dLng, 12);
  });

  it('跨半球、跨赤道的点不会并到同一桶(floor 前先 +180/+90 挪到非负)', () => {
    const out = bucketize({ lng: [-0.05], lat: [-0.05] }, cell);
    const at = cellAt({ lng: -0.05, lat: -0.05 }, cell);
    expect(out.gx[0]).toBe(at.gx);
    expect(out.gy[0]).toBe(at.gy);
    expect(at.gx).toBe(1799);
    expect(at.gy).toBe(899);
  });

  it('空输入给空桶,不炸', () => {
    const out = bucketize({ lng: [], lat: [] }, cell);
    expect(out.count.length).toBe(0);
    expect(out.maxCount).toBe(0);
  });
});