DebugCanvas.test.ts 7.54 KB
/**
 * 调试覆盖画布的几何守卫。
 *
 * 这一层是给开发者看的"证据",而证据最怕的是假:它画的格子必须与 Worker 真正分桶用的
 * 那一套边界是同一支公式(aggregate/grid.ts 的 toGrid:按经纬度等分,y 方向再过墨卡托),
 * 它报的均值落点必须真的落在自己画的那一格里面。一旦这里为了"看着顺眼"改用屏幕像素等分,
 * 屏幕上就是调试线跟着走、真格子不跟 —— 用户会据此判定图层画错了,而错的是调试视图。
 *
 * 观察手法与 frameBudget.test.ts 一致:jsdom 没有 canvas 实现,把 getContext 换成一份
 * 记账的假上下文,落笔坐标即为断言对象;出帧由测试推进 rAF(高德就是这么驱动的)。
 */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { GRID, gridDegAtZoom, toGrid } from '../aggregate/grid';
import {
  setAggregateDebug,
  setDebugEnabled,
  pushDebugEvent,
  registerDebugLayer,
  unregisterDebugLayer,
} from './debugBus';
import { DebugCanvas } from './DebugCanvas';

interface Op {
  name: string;
  args: number[];
}

function fakeCtx() {
  const ops: Op[] = [];
  const rec =
    (name: string) =>
    (...args: number[]) => {
      ops.push({ name, args });
    };
  const ctx: Record<string, unknown> = { ops };
  for (const name of [
    'setTransform',
    'clearRect',
    'beginPath',
    'moveTo',
    'lineTo',
    'arc',
    'fill',
    'stroke',
    'fillRect',
    'strokeRect',
    'save',
    'restore',
    'setLineDash',
  ]) {
    ctx[name] = rec(name);
  }
  ctx.strokeText = () => undefined;
  ctx.fillText = () => undefined;
  return ctx as unknown as CanvasRenderingContext2D & { ops: Op[] };
}

const ZOOM = 12;
const LNG = 114.05;
const LAT = 22.54;
const W = 800;
const H = 600;

function fakeMap() {
  return {
    getSize: () => ({ width: W, height: H }),
    getCenter: () => ({ getLng: () => LNG, getLat: () => LAT }),
    getZoom: () => ZOOM,
    // 原点交给"地图本身":这里给画布正中,与真地图一致
    lngLatToContainer: () => ({ x: W / 2, y: H / 2 }),
  } as unknown as AMap.Map;
}

const cell = gridDegAtZoom(ZOOM, GRID.gridPx, LAT);
/** 与 Frame 同一支换算:经度线性,纬度先过墨卡托 */
function expectedX(lng: number): number {
  return W / 2 + (lng - LNG) * ((GRID.tileSize * Math.pow(2, ZOOM)) / 360);
}

const alive: DebugCanvas[] = [];
let ctx!: CanvasRenderingContext2D & { ops: Op[] };
let restoreCanvas: (() => void) | null = null;

beforeEach(() => {
  vi.useFakeTimers();
  ctx = fakeCtx();
  const proto = window.HTMLCanvasElement.prototype as unknown as {
    getContext: (id: string) => unknown;
  };
  const original = proto.getContext;
  proto.getContext = () => ctx;
  restoreCanvas = () => {
    proto.getContext = original;
  };
  setDebugEnabled(true);
});

afterEach(() => {
  while (alive.length) alive.pop()?.destroy();
  restoreCanvas?.();
  setDebugEnabled(false);
  vi.useRealTimers();
  vi.restoreAllMocks();
});

function flush(frames = 3): void {
  for (let i = 0; i < frames; i += 1) vi.advanceTimersByTime(17);
}

function makeCanvas(): DebugCanvas {
  const host = document.createElement('div');
  document.body.appendChild(host);
  const dc = new DebugCanvas(
    fakeMap() as unknown as import('../map/provider/types').Basemap,
    host,
  );
  alive.push(dc);
  dc.start();
  return dc;
}

describe('调试画布画的格子就是聚合用的那一套网格', () => {
  it('格子的左右边界由 gx 与 dLng 还原,且均值落点落在自己那一格内', () => {
    const lng = LNG + 0.0004;
    const lat = LAT + 0.0002;
    const g = toGrid(lng, lat, cell);
    setAggregateDebug({
      zoom: ZOOM,
      bbox: { minLng: LNG - 0.02, maxLng: LNG + 0.02, minLat: LAT - 0.02, maxLat: LAT + 0.02 },
      view: { minLng: LNG - 0.01, maxLng: LNG + 0.01, minLat: LAT - 0.01, maxLat: LAT + 0.01 },
      bucketCount: 1,
      matched: 9,
      used: 9,
      ms: 4,
      gridPx: GRID.gridPx,
      dLng: cell.dLng,
      dLat: cell.dLat,
      maxCount: 9,
      lng: Int32Array.from([Math.round(lng * 1e6)]),
      lat: Int32Array.from([Math.round(lat * 1e6)]),
      gx: Int32Array.from([g.gx]),
      gy: Int32Array.from([g.gy]),
      count: Int32Array.from([9]),
    });

    const dc = makeCanvas();
    flush();

    // 一帧里 strokeRect 有三笔:视口框、请求框、这一格的框。取宽度最接近 GRID.gridPx 的那一笔
    const rects = ctx.ops.filter((o) => o.name === 'strokeRect').map((o) => o.args);
    const cellRect = rects.find((a) => Math.abs(a[2] - GRID.gridPx) < 4);
    expect(cellRect).toBeTruthy();
    const [x, , w, h] = cellRect!;
    expect(x).toBeCloseTo(expectedX(g.gx * cell.dLng - 180), 1);
    expect(x + w).toBeCloseTo(expectedX((g.gx + 1) * cell.dLng - 180), 1);
    expect(w).toBeGreaterThan(1);
    expect(h).toBeGreaterThan(1);

    // 均值点(数字真正落笔的地方)必须落在这一格里,否则画出来的格子和报出来的数各说各话
    const meanX = expectedX(lng);
    expect(meanX).toBeGreaterThan(x);
    expect(meanX).toBeLessThan(x + w);
    expect(dc.readout()).not.toBeNull();
  });

  it('网格线与格子边界重合:同一个 gx 只有一支尺子', () => {
    const g = toGrid(LNG + 0.0004, LAT + 0.0002, cell);
    setAggregateDebug({
      zoom: ZOOM,
      bbox: { minLng: LNG - 0.02, maxLng: LNG + 0.02, minLat: LAT - 0.02, maxLat: LAT + 0.02 },
      view: { minLng: LNG - 0.01, maxLng: LNG + 0.01, minLat: LAT - 0.01, maxLat: LAT + 0.01 },
      bucketCount: 0,
      matched: 0,
      used: 0,
      ms: 0,
      gridPx: GRID.gridPx,
      dLng: cell.dLng,
      dLat: cell.dLat,
      maxCount: 0,
      lng: null,
      lat: null,
      gx: null,
      gy: null,
      count: null,
    });
    makeCanvas();
    flush();

    const lineXs = ctx.ops.filter((o) => o.name === 'moveTo').map((o) => o.args[0]);
    const boundary = expectedX(g.gx * cell.dLng - 180);
    // 画线时对齐到半像素,所以差值只会来自取整
    expect(lineXs.some((x) => Math.abs(x - (Math.round(boundary) + 0.5)) < 0.01)).toBe(true);
  });
});

describe('调试画布自己也要省帧', () => {
  it('视图与调试内容都没变就整帧跳过', () => {
    makeCanvas();
    flush(1);
    const first = ctx.ops.length;
    expect(first).toBeGreaterThan(0);
    ctx.ops.length = 0;
    flush(3);
    expect(ctx.ops).toHaveLength(0);
  });

  it('总线一变(事件、聚合、开关项)就补一帧,不然读数看着像卡住', () => {
    const dc = makeCanvas();
    flush(1);
    ctx.ops.length = 0;
    pushDebugEvent('event', 'mapmove');
    flush(2);
    expect(ctx.ops.length).toBeGreaterThan(0);
    expect(dc.stats().painted).toBeGreaterThan(1);
  });
});

describe('图层高亮描的是那块画布本身', () => {
  it('点名某一行 → 给它的 canvas 上描边;关掉调试必须收掉', () => {
    const target = document.createElement('canvas');
    registerDebugLayer({
      id: 'cluster',
      name: 'ClusterLayer · 聚合方格层',
      zIndex: 130,
      kind: 'canvas',
      canvas: target,
      read: () => ({
        built: true,
        visible: true,
        released: false,
        cssW: W,
        cssH: H,
        dpr: 1,
        total: 1,
        painted: 1,
        drawn: 1,
        skipped: 0,
        lastMs: 1,
        light: false,
      }),
    });
    const dc = makeCanvas();
    dc.setOptions({ highlight: 'cluster' });
    flush(2);
    expect(target.style.outline).not.toBe('');

    setDebugEnabled(false);
    expect(target.style.outline).toBe('');
    unregisterDebugLayer('cluster');
  });
});