Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion builder/web/src/lib/trailview/kinds/kind.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { BRIDGE, metresPerUnit, PROFILES, RAIL, ROAD, TUNNEL, type Line, type Sh
import { RIGHT } from '../terrain/town';

/** The shapes of a tile with these lines and buildings alone. */
const tileOf = (lines: Line[], buildings: unknown[] = []) => ({ lines, lakes: [], seas: [], pads: [], areas: [], buildings }) as unknown as Shapes;
const tileOf = (lines: Line[], buildings: unknown[] = []) => ({ zoom: 13, lines, lakes: [], seas: [], pads: [], areas: [], buildings }) as unknown as Shapes;

describe('kinds', () => {
it('draws only kinds of the table', () => {
Expand Down
6 changes: 3 additions & 3 deletions builder/web/src/lib/trailview/roads/cores.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ describe('the cores of the ways', () => {
const y = 2 ** 29, m = 1 / metresPerUnit(y);
// A residential road east, 2.5 m each side; a sidewalk on its right (south) from its middle vertex on.
const line = { kind: ROAD, xy: [-50 * m, y, 0, y, 50 * m, y], z: [0, 0, 0], h: 2.5, code: 2, ford: false, profile: Object.keys(PROFILES).indexOf('residential'), sidewalks: [0, RIGHT] } as Line;
const cores = coresOf({ lines: [line], lakes: [], seas: [], pads: [], areas: [], buildings: [] } as unknown as Shapes), across = 2.5 + walkOf(line) - 0.2;
const cores = coresOf({ zoom: 13, lines: [line], lakes: [], seas: [], pads: [], areas: [], buildings: [] } as unknown as Shapes), across = 2.5 + walkOf(line) - 0.2;
expect(across).toBeGreaterThan(2.9);
expect(coreAt(cores, 0.5 * m, y + across * m)?.side).toBe(-1);
expect(coreAt(cores, -1 * m, y + across * m)).toBeUndefined();
Expand All @@ -22,7 +22,7 @@ describe('the cores of the ways', () => {
expect(coreAt(cores, -1 * m, y + across * m, 1)).toBeDefined();
// A sidewalk that ends at the middle vertex: the step after it lies on the next segment.
const ends = { ...line, sidewalks: [RIGHT, 0] };
const ended = coresOf({ lines: [ends], lakes: [], seas: [], pads: [], areas: [], buildings: [] } as unknown as Shapes);
const ended = coresOf({ zoom: 13, lines: [ends], lakes: [], seas: [], pads: [], areas: [], buildings: [] } as unknown as Shapes);
expect(coreAt(ended, -0.5 * m, y + across * m)?.side).toBe(-1);
expect(coreAt(ended, 0.5 * m, y + across * m)).toBeUndefined();
});
Expand All @@ -32,7 +32,7 @@ describe('the cores of the ways', () => {
// A road of two vertices 400 m apart that leaves north and comes in heading south: its curve passes 100 m, a quarter of
// the segment, north of its middle. The most that a curve can leave its segment.
const line = { kind: ROAD, xy: [-200 * m, y, 200 * m, y], z: flat, h: 2.5, code: 2, ford: false, profile: Object.keys(PROFILES).indexOf('residential'), plan: { tangent: [-turn, turn], grade: flat, bank: flat, widen: flat } } as Line;
const cores = coresOf({ lines: [line], lakes: [], seas: [], pads: [], areas: [], buildings: [] } as unknown as Shapes);
const cores = coresOf({ zoom: 13, lines: [line], lakes: [], seas: [], pads: [], areas: [], buildings: [] } as unknown as Shapes);
expect(coreAt(cores, 0, y - 100 * m)).toBeDefined();
expect(coreAt(cores, 0, y)).toBeUndefined();
});
Expand Down
47 changes: 40 additions & 7 deletions builder/web/src/lib/trailview/terrain/bins.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { functionOf, shaderFunctions } from '../gpu/shader-functions';
import { decodeFeatures, EXTENT, SIDE_BACK, SIDE_ON, unitScale, type Feature } from '../stream/features';
import { PAGE } from '../stream/heights';
import { auditSamples, IN_WATER, roadHeight, SAMPLE } from './audit-samples';
import { BRIDGE, CELL, cellAt, CORNER, crosses, crossSlope, DRIVEWAY, EDGE, features, fronts, gateTexel, GRID, halfWidth, INSIDE, insideRings, isPath, JUNCTION, junctions, junctionWays, LAKE, linesNear, metresPerUnit, NEAR, nodeStamps, PATH, ringsDistance, smoothed, PROFILE_FLOATS, PROFILE_ROWS, PROFILES, profileTable, RAIL_CODE, RECORD, RIVER, ROAD, RULES, SEA, seaShows, SHOULDER_M, shows, SLEEPER_M, STREAM, surfaceOf, SURFACE_CODES, SURFACES, AREA, trackSurface, TUNNEL, WARP_M, waterAt, type Line, type Profile, type Shapes } from './bins';
import { BRIDGE, CELL, cellAt, CORNER, crosses, crossSlope, DRIVEWAY, EDGE, features, fronts, gateTexel, GRID, halfWidth, INSIDE, insideRings, isPath, JUNCTION, junctions, junctionWays, LAKE, linesNear, linesShow, metresPerUnit, NEAR, nodeStamps, PATH, ringsDistance, smoothed, PROFILE_FLOATS, PROFILE_ROWS, PROFILES, profileTable, RAIL_CODE, RECORD, RIVER, ROAD, RULES, SEA, seaShows, SHOULDER_M, shows, SLEEPER_M, STREAM, surfaceOf, SURFACE_CODES, SURFACES, AREA, trackSurface, TUNNEL, WARP_M, waterAt, type Line, type Profile, type Shapes } from './bins';
import { SPILL_M } from '../roads/section';
import { cornersOf, halfAt, partnersOf } from './corners';
import { FOOT_HALF_M, GIVE_WAY_M } from './culverts';
Expand Down Expand Up @@ -186,6 +186,39 @@ describe('the stamp data of a node', { timeout: 30_000 }, () => {
expect(seen.size).toBe(2);
});

it('shows no line at a level where linesShow says that none shows', () => {
const levels = Array.from({ length: 23 }, (_, level) => level).filter(level => !linesShow(level));
// Level 13 reads zoom 12 tiles, which keep their roads: a motorway of 6.75 to 7 m half-width shows there.
expect(levels).toEqual(Array.from({ length: 13 }, (_, level) => level));
expect(shows({ kind: ROAD, h: 7, profile: Object.keys(PROFILES).indexOf('motorway') } as Line, gateTexel(13))).toBe(true);
for (const level of levels) for (const profile of Object.keys(PROFILES).keys()) for (const kind of [ROAD, PATH]) for (const h of [0, 0.5, 2, 6, 20, 100]) {
expect(shows({ kind, h, profile } as Line, gateTexel(level)), `kind ${kind}, profile ${profile}, h ${h}, level ${level}`).toBe(false);
}
});

it('keeps only the lines of the water mesh where no line shows, and writes no junction or corner there', () => {
const coarse = { level: 10, x: 535, y: 360 };
expect(linesShow(coarse.level + 1)).toBe(false);
const kinds = new Set(features(fixture(coarse.level, coarse.x, coarse.y), coarse).lines.map(({ kind }) => kind));
expect(kinds.size).toBeGreaterThan(0);
expect([...kinds].filter(kind => ![RIVER, STREAM, BRIDGE, TUNNEL].includes(kind))).toEqual([]);
// A zoom 12 tile serves level 13, where lines show: it keeps its roads.
const finer = { level: 12, x: 2143, y: 1444 };
expect(features(fixture(finer.level, finer.x, finer.y), finer).lines.some(({ kind }) => kind === ROAD)).toBe(true);
// The junctions and corners of the fixture tile in its four level 14 nodes, and in the level 12 node over it.
const list = fixture(TILE.level, TILE.x, TILE.y);
const joints = (node: { level: number; x: number; y: number }) => {
const { data } = nodeStamps(list, TILE, node);
if (!data) return 0;
const records = 2 + GRID * GRID + 1 + data[1];
return Array.from({ length: data[0] }, (_, r) => data[records + RECORD * r + 4]).filter(kind => kind === JUNCTION || kind === CORNER).length;
};
const fine = [0, 1, 2, 3].map(k => joints({ level: 14, x: 2 * TILE.x + (k % 2), y: 2 * TILE.y + (k >> 1) }));
expect(fine.reduce((a, b) => a + b)).toBeGreaterThan(0);
expect(linesShow(12)).toBe(false);
expect(joints({ level: 12, x: TILE.x >> 1, y: TILE.y >> 1 })).toBe(0);
});

it('lists in each cell every segment and edge within the buffer of the feature tiles, and the lakes over its centre, in the order of the shader', () => {
const NODE = lakeNode(), list = fixture(TILE.level, TILE.x, TILE.y), { data } = nodeStamps(list, TILE, NODE);
const records = 2 + GRID * GRID + 1 + data![1], word = (r: number, i: number) => data![records + RECORD * r + i] | 0;
Expand Down Expand Up @@ -776,7 +809,7 @@ describe('the cross-section table of the ground plan', () => {
describe('the lines near a point', () => {
/** A steady value in [0, 1) for each call. */
const random = (seed => () => (seed = (seed * 1103515245 + 12345) % 2 ** 31) / 2 ** 31)(7);
const tileOf = (lines: Line[]) => ({ lines, lakes: [], seas: [], pads: [], areas: [], buildings: [] }) as unknown as Shapes;
const tileOf = (lines: Line[], zoom = 13) => ({ zoom, lines, lakes: [], seas: [], pads: [], areas: [], buildings: [] }) as unknown as Shapes;
const way = (xy: number[]) => ({ kind: ROAD, xy, z: xy.filter((_, i) => i % 2 === 0).map(() => 0), h: 2.5, code: 2, ford: false, profile: 0 }) as Line;
/** The world units from a point to the nearest segment of a line. */
const distance = ({ xy }: Line, x: number, y: number) => {
Expand All @@ -788,17 +821,17 @@ describe('the lines near a point', () => {
return best;
};

it('hold every line that a scan of all lines finds within reach, in the tile\'s order', () => {
// The index has cells of 2^13 units: a square of 20 cells, with its corner on a cell line.
const cell = 2 ** 13, x0 = 2 ** 29, y0 = 2 ** 29, side = 20 * cell, lines: Line[] = [];
it.each([13, 8])('hold every line that a scan of all lines finds within reach, in the tile\'s order, on a zoom %i tile', zoom => {
// The index has cells of 2^13 units on a zoom 13 tile and 16 × 16 cells on a coarser one: a square of 20 cells, with its corner on a cell line.
const cell = Math.max(2 ** 13, 2 ** (30 - zoom) / 16), x0 = 2 ** 29, y0 = 2 ** 29, side = 20 * cell, lines: Line[] = [];
for (let k = 0; k < 400; k++) {
const xy = [x0 + random() * side, y0 + random() * side];
for (let v = 1 + Math.floor(random() * 5); v > 0; v--) xy.push(xy[xy.length - 2] + (random() - 0.5) * 3 * cell, xy[xy.length - 2 + 1] + (random() - 0.5) * 3 * cell);
lines.push(way(xy));
}
// A segment without length, ways on a cell line and across every cell, and a way that ends on a corner of cells.
lines.push(way([x0 + 5.5 * cell, y0 + 5.5 * cell, x0 + 5.5 * cell, y0 + 5.5 * cell]), way([x0 + 3 * cell, y0, x0 + 3 * cell, y0 + side]), way([x0, y0 + 7 * cell, x0 + side, y0 + 7 * cell]), way([x0 + 2 * cell, y0 + 2 * cell, x0 + 2.5 * cell, y0 + 2.2 * cell]));
const shapes = tileOf(lines);
const shapes = tileOf(lines, zoom);
const points = Array.from({ length: 300 }, () => [x0 + (random() * 1.4 - 0.2) * side, y0 + (random() * 1.4 - 0.2) * side]);
// On a cell line, on a corner of cells, on the segment without length, and far outside the tile.
points.push([x0 + 3 * cell, y0 + 4.5 * cell], [x0 + 2 * cell, y0 + 2 * cell], [x0 + 5.5 * cell, y0 + 5.5 * cell], [x0 - 50 * cell, y0 + 300 * cell], [0, 0]);
Expand All @@ -811,6 +844,6 @@ describe('the lines near a point', () => {
found += scanned.length;
}
expect(found).toBeGreaterThan(1000);
expect(linesNear(tileOf([]), x0, y0, 600)).toEqual([]);
expect(linesNear(tileOf([], zoom), x0, y0, 600)).toEqual([]);
});
});
48 changes: 36 additions & 12 deletions builder/web/src/lib/trailview/terrain/bins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,8 @@ export interface Building { rings: number[][]; outer: boolean[] }
* surface, the pads under the platforms and the buildings.
*/
export interface Shapes {
/** The zoom of the tile. */
zoom: number;
lines: Line[]; mouths: CulvertMouth[]; lakes: Lake[]; seas: Lake[]; areas: Omit<Lake, 'level'>[]; pads: Lake[]; buildings: Building[]; barriers: Barrier[];
crossings: { x: number; y: number }[];
/** Each part of a bridge whole, missing heights included, in world units, and the half-width of its deck in metres. */
Expand All @@ -259,8 +261,13 @@ export const gateTexel = (level: number) => 2 * Math.PI * EARTH_RADIUS * RULES.G
/** As sea_shows of stamp-core.wgsl: whether a level cuts the sea. */
export const seaShows = (level: number) => RULES.LIFT_M + RULES.LIFT * RULES.MESH_TEXELS * gateTexel(level) < RULES.BED_DEPTH;

/** As reach_limit of stamp-core.wgsl: the metres that a line's half-width and its reach may take at a texel. */
const reachLimit = (texel: number) => RULES.BUFFER_M - 2 * texel - 1;
/** Whether any line can show at a level: below 0 of the reach limit, none does, as neither a half-width nor a reach is below 0. */
export const linesShow = (level: number) => reachLimit(gateTexel(level)) >= 0;

export function shows({ kind, h, profile }: Line, texel: number): boolean {
const limit = RULES.BUFFER_M - 2 * texel - 1, { reach, least } = Object.values(PROFILES)[profile];
const limit = reachLimit(texel), { reach, least } = Object.values(PROFILES)[profile];
if (kind === STREAM) return false;
if (kind === PATH) return 2 * h >= texel && h + reach <= limit;
return 2 * h >= texel && h + least <= limit;
Expand All @@ -275,11 +282,25 @@ export function zebraTagged(tags: Record<string, string>): boolean {
/** The shapes of each decoded tile, made once: the stamps and the water of each of its nodes read them. */
const shapes = new WeakMap<Feature[], Shapes & { tile: string }>();

/** The roads, paths, rivers, lakes and sea of a tile that have heights, its river areas and its buildings, in world units. */
/**
* The lines that a node reads at a level where no line shows: the water mesh draws the rivers and streams, and lifts
* them under a bridge (`underDeck`); `portalBoxes` cuts the terrain at a tunnel's portals.
*/
const COARSE_KINDS = [RIVER, STREAM, BRIDGE, TUNNEL];

/**
* The roads, paths, rivers, lakes and sea of a tile that have heights, its river areas and its buildings, in world units.
* A tile under DEEPEST serves the nodes of one level (featureTile); where no line shows there, it keeps only the lines that
* its nodes read (COARSE_KINDS), as its other lines take most of its bytes in a worker.
*/
export function features(list: Feature[], tile: Node): Shapes {
const name = `${tile.level}/${tile.x}/${tile.y}`;
let known = shapes.get(list);
if (known?.tile !== name) shapes.set(list, (known = { tile: name, ...shapesOf(list, tile) }));
if (known?.tile !== name) {
const made = shapesOf(list, tile);
if (tile.level < DEEPEST && !linesShow(tile.level + 1)) made.lines = made.lines.filter(({ kind }) => COARSE_KINDS.includes(kind));
shapes.set(list, (known = { tile: name, ...made }));
}
return known;
}

Expand All @@ -293,11 +314,13 @@ export function features(list: Feature[], tile: Node): Shapes {
export interface TileIndex { lines: Grid; reach: number; waterHalf: number; outlines: Grid & { seasFrom: number; padsFrom: number; areasFrom: number; buildingsFrom: number } }
const indexes = new WeakMap<Shapes, TileIndex>();
/**
* The cells of a tile's index, 2^13 world units (about 200 m in the Alps): a level-18 node asks a few, and a lake's box
* The cells of a zoom 13 tile's index, 2^13 world units (about 200 m in the Alps): a level-18 node asks a few, and a lake's box
* takes few. Most structures ask about a point with a reach of some tens of metres: one cell, or two to four at a cell's
* edge. `coreAt` asks with a quarter of the tile's longest way segment, which can be hundreds of metres and many cells.
* A coarser tile has at most 16 × 16 cells: a box takes a cell of each 2^13 that it covers, and a long river's box on a
* zoom 8 tile covers thousands of them.
*/
const INDEX_SHIFT = 13;
const indexShift = ({ zoom }: Shapes) => Math.max(13, 30 - zoom - 4);

/** The box of rings, west, north, east, south. */
function ringsBox(rings: number[][]): number[] {
Expand All @@ -317,10 +340,10 @@ export function tileIndex(shapes: Shapes): TileIndex {
if (index) return index;
const { lines, lakes, seas, pads, areas, buildings } = shapes, seasAt = lakes.length, padsAt = seasAt + seas.length, areasAt = padsAt + pads.length;
index = {
lines: gridOf(lines.map(({ xy }) => ringsBox([xy])), INDEX_SHIFT),
lines: gridOf(lines.map(({ xy }) => ringsBox([xy])), indexShift(shapes)),
reach: lines.reduce((most, line) => Math.max(most, reachOf(line, NEAR), reachOf(line, NEAR - 1)), REACH_M),
waterHalf: lines.reduce((most, { kind, h }) => (kind === RIVER || kind === STREAM ? Math.max(most, h) : most), 0),
outlines: { ...gridOf([...lakes, ...seas, ...pads, ...areas, ...buildings].map(({ rings }) => ringsBox(rings)), INDEX_SHIFT), seasFrom: seasAt, padsFrom: padsAt, areasFrom: areasAt, buildingsFrom: areasAt + areas.length },
outlines: { ...gridOf([...lakes, ...seas, ...pads, ...areas, ...buildings].map(({ rings }) => ringsBox(rings)), indexShift(shapes)), seasFrom: seasAt, padsFrom: padsAt, areasFrom: areasAt, buildingsFrom: areasAt + areas.length },
};
indexes.set(shapes, index);
return index;
Expand Down Expand Up @@ -388,7 +411,7 @@ function deckIndex(shapes: Shapes): DeckIndex {
let index = deckIndexes.get(shapes);
if (!index) {
const rings = shapes.bridges.map(({ xy, half }) => ({ rings: [deckRing(xy, half)], outer: [true] })).filter(({ rings }) => rings[0].length);
deckIndexes.set(shapes, (index = { grid: gridOf(rings.map(({ rings }) => ringsBox(rings)), INDEX_SHIFT), rings }));
deckIndexes.set(shapes, (index = { grid: gridOf(rings.map(({ rings }) => ringsBox(rings)), indexShift(shapes)), rings }));
}
return index;
}
Expand Down Expand Up @@ -581,7 +604,7 @@ function shapesOf(list: Feature[], tile: Node): Shapes {
const buried = joinCulverts(list, lines, world);
junctionPlanes(lines);
abutments(lines);
return { lines, lakes, seas, areas, pads, buildings, barriers, crossings, bridges, mouths: standMouths(lines, buried) };
return { zoom: tile.level, lines, lakes, seas, areas, pads, buildings, barriers, crossings, bridges, mouths: standMouths(lines, buried) };
}

/**
Expand Down Expand Up @@ -1180,15 +1203,16 @@ export function nodeStamps(list: Feature[], tile: Node, node: Node, plan = false
/** Two numbers within ±1 as unpack2x16snorm reads them. */
const pair = (a: number, b: number) => (Math.round(a * 32767) & 0xffff) | (Math.round(b * 32767) << 16);

// With `plan` the records hold the junctions.
for (const [point, { x, y, h }] of plan ? [] : runsOnOf(lines)) {
// With `plan` the records hold the junctions. Where no line shows, the shader draws neither a junction nor a corner.
const junctionsShow = !plan && linesShow(node.level);
for (const [point, { x, y, h }] of junctionsShow ? runsOnOf(lines) : []) {
if (!joinsOf(lines).has(point) && !kerbedOf(lines).has(point)) continue;
const touched = within([x, y, x, y], REACH_M);
if (!touched.length) continue;
const at = record([x, y, 0, 0, JUNCTION, 0, f(h)]);
for (const c of touched) cells[0][c].push(at);
}
for (const corner of plan ? [] : cornersOf(lines)) {
for (const corner of junctionsShow ? cornersOf(lines) : []) {
const { o, a, b, z, grad, walk, code, profile, h } = corner, touched = within(boxOf(corner), 1);
if (!touched.length) continue;
// The sidewalks' widths in decimetres share a word; the slopes fill the words about the second end.
Expand Down
Loading