mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-20 10:12:18 +00:00
Bin Navara ground corridors set-wide and give corridors glow, pulse and dash
Navara's ground pass cut each corridor into chunks and tested them per screen cell, so dense corridor sets were slow (10,000 cost about 150 ms a frame). A corridor set is now cut into pieces along its great circles, sorted into lon/lat tiles, each with a pyramid of bins listing the segment runs within its margin; a pixel takes its tile and the finest bin that covers its reach and tests only those runs. At 10,000 corridors a frame now takes 11.8 ms still (Cesium 23 ms), at 15,000 17.9 ms. A pixel corridor's width is measured across the line, so diagonal lines no longer draw up to 1.4 times wider. Pixel corridors take three looks, evaluated on the GPU from a time uniform: Cesium's PolylineGlow falloff (glow), an alpha pulse and the annotation route's flowing dash. While a shown set pulses or flows the engine draws continuously, as Cesium did. Traffic's jam lines take the glow and pulse again and the Directions route its flowing dash and render hold, so on Cesium both match the drawing before they moved to the contract pixel for pixel. The contract suite passes on both engines (Cesium 69/69, Navara 72/72).
This commit is contained in:
1 parent
48885d9e61
commit
47d63128ff
30 files changed
+2501
-391
No files matched your search
@@ -0,0 +1,630 @@
|
||||
// A corridor set as Navara's ground pass draws it (pack.js), without three:
|
||||
// the set's lines, cut into pieces of at most MAX_PIECE_DEG along their
|
||||
// great circles, fall into a tree of longitude/latitude tiles of at most
|
||||
// TILE_PIECES pieces each. A tile is one pass item: a gnomonic plane of its
|
||||
// own, the pieces that come near it as segments in that plane, and a
|
||||
// pyramid of square bins over it. Each bin of level z (2^z times the finest
|
||||
// bin) lists the runs of segments, item by item in draw order, that reach
|
||||
// within a margin of it: MARGIN_RATIO bins for the set's thinnest corridor,
|
||||
// more for a wider one, plus its width in metres. A pixel takes the tile
|
||||
// whose longitude/latitude cell holds its ground (tested once per pixel in
|
||||
// world space, so neighbouring tiles never both draw it), the finest level
|
||||
// whose margin covers its widest reach, and tests only its bin's runs.
|
||||
|
||||
import * as geo from '../../../geo/index.js';
|
||||
|
||||
const { cartesian3, ellipsoid } = geo;
|
||||
|
||||
const DEG = Math.PI / 180;
|
||||
/** Pieces a tile holds before it splits. */
|
||||
export const TILE_PIECES = 20000;
|
||||
/** A piece's longest arc, degrees. */
|
||||
export const MAX_PIECE_DEG = 0.5;
|
||||
// A tile's longest side, degrees: its plane stays precise in float32 and
|
||||
// its meridians less than 180° apart.
|
||||
const MAX_TILE_DEG = 20;
|
||||
// A tile this small (metres) never splits: its pieces share a few metres.
|
||||
const MIN_TILE_M = 50;
|
||||
/** A bin's margin, in bins at its level, for the set's thinnest corridor. */
|
||||
export const MARGIN_RATIO = 0.5;
|
||||
// Runs the finest level holds per piece of the tile, about: it sets the
|
||||
// finest bin (smaller bins test fewer segments a pixel and hold more runs).
|
||||
const RUN_BUDGET = 2;
|
||||
// The coarsest level has at most this many bins across; its margin bounds
|
||||
// how far a tile reaches into its neighbours.
|
||||
const TOP_ACROSS = 8;
|
||||
// The finest level has at most this many.
|
||||
const MAX_ACROSS = 128;
|
||||
/** Slack for the pixel's world position, metres. */
|
||||
export const EPSILON_M = 4;
|
||||
// Segments of one line a run spans over: fewer, longer runs.
|
||||
const RUN_GAP = 2;
|
||||
const METRES_PER_DEG = ellipsoid.WGS84.maximumRadius * DEG;
|
||||
const E2 =
|
||||
1 - (ellipsoid.WGS84.minimumRadius / ellipsoid.WGS84.maximumRadius) ** 2;
|
||||
|
||||
/** Item looks as the shader reads them: glow, pulse and dash bits. */
|
||||
export const LOOK = Object.freeze({ glow: 1, pulse: 2, dash: 4 });
|
||||
/** RGBA32F texels per corridor item. */
|
||||
export const ITEM_TEXELS = 5;
|
||||
|
||||
const wrap180 = (degrees) => degrees - 360 * Math.round(degrees / 360);
|
||||
const geodetic = (latcDeg) =>
|
||||
Math.abs(latcDeg) >= 90
|
||||
? latcDeg
|
||||
: Math.atan(Math.tan(latcDeg * DEG) / (1 - E2)) / DEG;
|
||||
|
||||
/** One item's look: five texels (colour, widths, glow/pulse, dash). */
|
||||
function itemTexels(item, lengthM) {
|
||||
const { glow, pulse, dash } = item.animation ?? {};
|
||||
const flags =
|
||||
(glow ? LOOK.glow : 0) | (pulse ? LOOK.pulse : 0) | (dash ? LOOK.dash : 0);
|
||||
return [
|
||||
...item.fill,
|
||||
item.widthPx ?? 0,
|
||||
item.widthM ?? 0,
|
||||
lengthM,
|
||||
flags,
|
||||
glow?.power ?? 0,
|
||||
glow?.taper ?? 1,
|
||||
pulse ? pulse.periodMs / 1000 : 1,
|
||||
pulse?.min ?? 1,
|
||||
pulse?.max ?? 1,
|
||||
dash?.cells ?? 0,
|
||||
dash?.duty ?? 0.5,
|
||||
dash?.speed ?? 0,
|
||||
dash?.gapAlpha ?? 0,
|
||||
dash?.emission ?? 0,
|
||||
0,
|
||||
0,
|
||||
];
|
||||
}
|
||||
|
||||
// Every item's line as pieces: unit directions from the Earth's centre
|
||||
// (a plane through the centre holds each piece), their ends in longitude
|
||||
// and geocentric latitude, and their place along the line in metres.
|
||||
function piecesOf(items) {
|
||||
const item = [];
|
||||
const index = [];
|
||||
const ends = [];
|
||||
const lonLat = [];
|
||||
const along = [];
|
||||
const lengths = [];
|
||||
const lineLengths = [];
|
||||
const point = cartesian3.create();
|
||||
items.forEach((entry, itemIndex) => {
|
||||
const flat = entry.path;
|
||||
const count = flat.length / 2;
|
||||
const directions = [];
|
||||
const surface = [];
|
||||
for (let k = 0; k < count; k++) {
|
||||
cartesian3.fromDegrees(flat[k * 2], flat[k * 2 + 1], 0, undefined, point);
|
||||
surface.push([point.x, point.y, point.z]);
|
||||
const length = Math.hypot(point.x, point.y, point.z);
|
||||
directions.push([point.x / length, point.y / length, point.z / length]);
|
||||
}
|
||||
let total = 0;
|
||||
let piece = 0;
|
||||
for (let k = 0; k + 1 < count; k++) {
|
||||
const a = directions[k];
|
||||
const b = directions[k + 1];
|
||||
const angle = Math.acos(
|
||||
Math.min(1, Math.max(-1, a[0] * b[0] + a[1] * b[1] + a[2] * b[2])),
|
||||
);
|
||||
const steps = Math.max(
|
||||
1,
|
||||
Math.ceil(angle / (MAX_PIECE_DEG * DEG) - 1e-9),
|
||||
);
|
||||
const chord = Math.hypot(
|
||||
surface[k + 1][0] - surface[k][0],
|
||||
surface[k + 1][1] - surface[k][1],
|
||||
surface[k + 1][2] - surface[k][2],
|
||||
);
|
||||
// Along the great circle from a to b (the plane through both and
|
||||
// the centre), in equal steps.
|
||||
const sin = Math.sin(angle);
|
||||
const between = (t) => {
|
||||
if (sin < 1e-12) return a;
|
||||
const wa = Math.sin((1 - t) * angle) / sin;
|
||||
const wb = Math.sin(t * angle) / sin;
|
||||
return [
|
||||
wa * a[0] + wb * b[0],
|
||||
wa * a[1] + wb * b[1],
|
||||
wa * a[2] + wb * b[2],
|
||||
];
|
||||
};
|
||||
let from = a;
|
||||
for (let step = 1; step <= steps; step++) {
|
||||
const to = step === steps ? b : between(step / steps);
|
||||
item.push(itemIndex);
|
||||
index.push(piece++);
|
||||
ends.push(...from, ...to);
|
||||
const lonA = Math.atan2(from[1], from[0]) / DEG;
|
||||
const lonB = Math.atan2(to[1], to[0]) / DEG;
|
||||
lonLat.push(
|
||||
lonA,
|
||||
Math.asin(Math.max(-1, Math.min(1, from[2]))) / DEG,
|
||||
lonA + wrap180(lonB - lonA),
|
||||
Math.asin(Math.max(-1, Math.min(1, to[2]))) / DEG,
|
||||
);
|
||||
along.push(total + (chord * (step - 1)) / steps);
|
||||
lengths.push(chord / steps);
|
||||
from = to;
|
||||
}
|
||||
total += chord;
|
||||
}
|
||||
lineLengths.push(total);
|
||||
});
|
||||
return {
|
||||
count: item.length,
|
||||
item: Int32Array.from(item),
|
||||
index: Int32Array.from(index),
|
||||
ends: Float64Array.from(ends),
|
||||
lonLat: Float64Array.from(lonLat),
|
||||
along: Float64Array.from(along),
|
||||
lengths: Float64Array.from(lengths),
|
||||
lineLengths,
|
||||
};
|
||||
}
|
||||
|
||||
// The middle of the widest gap between the pieces' longitudes: the set's
|
||||
// longitudes run from there round to there.
|
||||
function seamOf(lonLat, count) {
|
||||
const lons = new Float64Array(count * 2);
|
||||
for (let piece = 0; piece < count; piece++) {
|
||||
lons[piece * 2] = wrap180(lonLat[piece * 4]);
|
||||
lons[piece * 2 + 1] = wrap180(lonLat[piece * 4 + 2]);
|
||||
}
|
||||
lons.sort();
|
||||
let seam = lons[0] - 180;
|
||||
let widest = -1;
|
||||
for (let k = 0; k < lons.length; k++) {
|
||||
const next = k + 1 < lons.length ? lons[k + 1] : lons[0] + 360;
|
||||
if (next - lons[k] > widest) {
|
||||
widest = next - lons[k];
|
||||
seam = (lons[k] + next) / 2;
|
||||
}
|
||||
}
|
||||
return seam;
|
||||
}
|
||||
|
||||
// The longest east-west and north-south sides of a rectangle, metres.
|
||||
function sidesM(rect) {
|
||||
const nearest = Math.min(
|
||||
89.9,
|
||||
rect.south <= 0 && rect.north >= 0
|
||||
? 0
|
||||
: Math.min(Math.abs(rect.south), Math.abs(rect.north)),
|
||||
);
|
||||
return [
|
||||
(rect.east - rect.west) * METRES_PER_DEG * Math.cos(nearest * DEG),
|
||||
(rect.north - rect.south) * METRES_PER_DEG,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a piece's padded bounds come within `metres` of `rect`, the
|
||||
* metres as degrees of longitude by `lonPerLat` (rect's coldest latitude
|
||||
* and the farthest margin from it).
|
||||
*/
|
||||
function near(boxes, piece, rect, metres, lonPerLat) {
|
||||
const b = piece * 4;
|
||||
const dLat = metres / METRES_PER_DEG;
|
||||
if (boxes[b + 1] > rect.north + dLat || boxes[b + 3] < rect.south - dLat)
|
||||
return false;
|
||||
const dLon = dLat * lonPerLat;
|
||||
const west = rect.west - dLon;
|
||||
const east = rect.east + dLon;
|
||||
return (
|
||||
(boxes[b] <= east && boxes[b + 2] >= west) ||
|
||||
(boxes[b] + 360 <= east && boxes[b + 2] + 360 >= west) ||
|
||||
(boxes[b] - 360 <= east && boxes[b + 2] - 360 >= west)
|
||||
);
|
||||
}
|
||||
|
||||
// Degrees of longitude per degree of latitude near `rect`, `metres` from it.
|
||||
function lonPerLatNear(rect, metres) {
|
||||
const coldest = Math.min(
|
||||
89.9,
|
||||
Math.max(Math.abs(rect.south), Math.abs(rect.north)) +
|
||||
metres / METRES_PER_DEG,
|
||||
);
|
||||
return 1 / Math.max(1e-3, Math.cos(coldest * DEG));
|
||||
}
|
||||
|
||||
/**
|
||||
* The tiles of a corridor set: { pieces (piecesOf, with each piece's
|
||||
* padded bounds in `boxes`: west, south, east, north), tiles }. A tile is
|
||||
* { west, south, east, north } (longitude, geocentric latitude, degrees;
|
||||
* the tiles split the set's bounds and a border round them), `own` (the
|
||||
* pieces in it) and `near` (those that may come within their margin of
|
||||
* it). `reachOf(item)` is [half width in pixels + 0.5, half width in
|
||||
* metres]; `reference` the set's least pixel reach; `tilePieces` (a test
|
||||
* seam) the pieces a tile holds before it splits.
|
||||
*/
|
||||
export function tileCorridors(
|
||||
items,
|
||||
reachOf,
|
||||
reference,
|
||||
tilePieces = TILE_PIECES,
|
||||
) {
|
||||
const pieces = piecesOf(items);
|
||||
const { count, lonLat } = pieces;
|
||||
if (!count) return { pieces, tiles: [] };
|
||||
const seam = seamOf(lonLat, count);
|
||||
const boxes = new Float64Array(count * 4);
|
||||
// A piece's margin per metre of a tile's side, and its fixed metres.
|
||||
const perSide = new Float64Array(count);
|
||||
const fixed = new Float64Array(count);
|
||||
// Its pixel reach over the reference's, and its half width in metres.
|
||||
const ratio = new Float64Array(count);
|
||||
const metres = new Float64Array(count);
|
||||
let west = Infinity;
|
||||
let east = -Infinity;
|
||||
let south = Infinity;
|
||||
let north = -Infinity;
|
||||
for (let piece = 0; piece < count; piece++) {
|
||||
const lonA = seam + ((((lonLat[piece * 4] - seam) % 360) + 360) % 360);
|
||||
const lonB = lonA + (lonLat[piece * 4 + 2] - lonLat[piece * 4]);
|
||||
const latA = lonLat[piece * 4 + 1];
|
||||
const latB = lonLat[piece * 4 + 3];
|
||||
// A great circle bows off the straight line between its ends in
|
||||
// longitude and latitude; pad by a bound of that.
|
||||
const span = Math.hypot(
|
||||
(lonB - lonA) * Math.cos(((latA + latB) / 2) * DEG),
|
||||
latB - latA,
|
||||
);
|
||||
const steepest = Math.min(89, Math.max(Math.abs(latA), Math.abs(latB)));
|
||||
const bow =
|
||||
(((span * DEG) ** 2 / 8 / DEG) * (1 + Math.tan(steepest * DEG)) * 2) /
|
||||
Math.max(0.02, Math.cos(steepest * DEG)) +
|
||||
1e-7;
|
||||
const box = [
|
||||
Math.min(lonA, lonB) - bow,
|
||||
Math.max(-90, Math.min(latA, latB) - bow),
|
||||
Math.max(lonA, lonB) + bow,
|
||||
Math.min(90, Math.max(latA, latB) + bow),
|
||||
];
|
||||
boxes.set(box, piece * 4);
|
||||
const [px, m] = reachOf(items[pieces.item[piece]]);
|
||||
ratio[piece] = px / reference;
|
||||
metres[piece] = m;
|
||||
perSide[piece] = 1.1 * MARGIN_RATIO * ratio[piece];
|
||||
fixed[piece] = m + 2 * EPSILON_M;
|
||||
west = Math.min(west, box[0]);
|
||||
south = Math.min(south, box[1]);
|
||||
east = Math.max(east, box[2]);
|
||||
north = Math.max(north, box[3]);
|
||||
}
|
||||
Object.assign(pieces, { boxes, ratio, metres });
|
||||
// The tiles split the set's bounds; a tile on an edge of them also takes
|
||||
// every pixel beyond that edge (its side is open), as if the pixel were
|
||||
// moved onto the bounds.
|
||||
const root = {
|
||||
west,
|
||||
south,
|
||||
east: Math.max(east, west + 1e-9),
|
||||
north: Math.max(north, south + 1e-9),
|
||||
open: { west: true, south: true, east: true, north: true },
|
||||
};
|
||||
let widestFixed = 0;
|
||||
let widestPerSide = 0;
|
||||
for (let piece = 0; piece < count; piece++) {
|
||||
widestFixed = Math.max(widestFixed, fixed[piece]);
|
||||
widestPerSide = Math.max(widestPerSide, perSide[piece]);
|
||||
}
|
||||
const tiles = [];
|
||||
const split = (rect, own, nearby) => {
|
||||
const lonSpan = rect.east - rect.west;
|
||||
const latSpan = rect.north - rect.south;
|
||||
const [widthM, heightM] = sidesM(rect);
|
||||
const tooWide = lonSpan > MAX_TILE_DEG || latSpan > MAX_TILE_DEG;
|
||||
if (
|
||||
!tooWide &&
|
||||
(own.length <= tilePieces || Math.max(widthM, heightM) < 2 * MIN_TILE_M)
|
||||
) {
|
||||
// A tile no line reaches draws nothing.
|
||||
if (nearby.length) tiles.push({ ...rect, own, near: nearby });
|
||||
return;
|
||||
}
|
||||
const alongLon = tooWide ? lonSpan >= latSpan : widthM >= heightM;
|
||||
const mid = alongLon
|
||||
? (rect.west + rect.east) / 2
|
||||
: (rect.south + rect.north) / 2;
|
||||
const halves = alongLon
|
||||
? [
|
||||
{ ...rect, east: mid, open: { ...rect.open, east: false } },
|
||||
{ ...rect, west: mid, open: { ...rect.open, west: false } },
|
||||
]
|
||||
: [
|
||||
{ ...rect, north: mid, open: { ...rect.open, north: false } },
|
||||
{ ...rect, south: mid, open: { ...rect.open, south: false } },
|
||||
];
|
||||
for (const half of halves) {
|
||||
const side = Math.max(...sidesM(half));
|
||||
const lonPerLat = lonPerLatNear(half, widestFixed + widestPerSide * side);
|
||||
split(
|
||||
half,
|
||||
own.filter((piece) => near(boxes, piece, half, 0, 1)),
|
||||
nearby.filter((piece) =>
|
||||
near(
|
||||
boxes,
|
||||
piece,
|
||||
half,
|
||||
fixed[piece] + perSide[piece] * side,
|
||||
lonPerLat,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
};
|
||||
const all = Array.from({ length: count }, (_, piece) => piece);
|
||||
split(root, all, all);
|
||||
return { pieces, tiles };
|
||||
}
|
||||
|
||||
/**
|
||||
* One tile packed for the pass, in `frame`'s gnomonic plane (pack.js
|
||||
* frameAt): its region's bounds in the plane, its segments (the pieces
|
||||
* near it, item by item), its bins' runs and its levels.
|
||||
* `reachOf(item)` is the item's [half width in pixels + 0.5, half width in
|
||||
* metres]; `reference` the set's least pixel reach.
|
||||
*/
|
||||
export function packTile(tile, pieces, items, frame, reachOf, reference) {
|
||||
const { project } = frame;
|
||||
// Its region in the plane, from its edges.
|
||||
let x0 = Infinity;
|
||||
let y0 = Infinity;
|
||||
let x1 = -Infinity;
|
||||
let y1 = -Infinity;
|
||||
const STEPS = 8;
|
||||
for (let k = 0; k <= STEPS; k++) {
|
||||
const f = k / STEPS;
|
||||
for (const [lon, latc] of [
|
||||
[tile.west + f * (tile.east - tile.west), tile.south],
|
||||
[tile.west + f * (tile.east - tile.west), tile.north],
|
||||
[tile.west, tile.south + f * (tile.north - tile.south)],
|
||||
[tile.east, tile.south + f * (tile.north - tile.south)],
|
||||
]) {
|
||||
const [x, y] = project(direction(lon, latc));
|
||||
x0 = Math.min(x0, x);
|
||||
y0 = Math.min(y0, y);
|
||||
x1 = Math.max(x1, x);
|
||||
y1 = Math.max(y1, y);
|
||||
}
|
||||
}
|
||||
const pad = 0.01 * Math.max(x1 - x0, y1 - y0) + EPSILON_M;
|
||||
x0 -= pad;
|
||||
y0 -= pad;
|
||||
x1 += pad;
|
||||
y1 += pad;
|
||||
const width = x1 - x0;
|
||||
const height = y1 - y0;
|
||||
// A line crosses about (1 + 2 MARGIN_RATIO) bins of the finest level a
|
||||
// bin's length along it.
|
||||
const counted = tile.own.length ? tile.own : tile.near;
|
||||
let countedLength = 0;
|
||||
for (const piece of counted) countedLength += pieces.lengths[piece];
|
||||
const size = Math.max(
|
||||
Math.max(width, height) / MAX_ACROSS,
|
||||
((1 + 2 * MARGIN_RATIO) * countedLength) / (RUN_BUDGET * counted.length),
|
||||
1e-3,
|
||||
);
|
||||
const columns = Math.max(1, Math.ceil(width / size));
|
||||
const rows = Math.max(1, Math.ceil(height / size));
|
||||
const levels = [];
|
||||
for (let c = columns, r = rows; ; c = (c + 1) >> 1, r = (r + 1) >> 1) {
|
||||
levels.push([c, r]);
|
||||
if (Math.max(c, r) <= TOP_ACROSS || (c === 1 && r === 1)) break;
|
||||
}
|
||||
const top = levels.length - 1;
|
||||
// A piece's margin at level z: its metres, its pixel reach scaled to the
|
||||
// reference's margin, and the slack.
|
||||
const marginOf = (piece, z) => {
|
||||
return (
|
||||
pieces.metres[piece] +
|
||||
MARGIN_RATIO * size * 2 ** z * pieces.ratio[piece] +
|
||||
EPSILON_M
|
||||
);
|
||||
};
|
||||
// Every piece that comes within its coarsest margin of the tile, by item
|
||||
// and along each line.
|
||||
const rect = {
|
||||
west: tile.west,
|
||||
south: tile.south,
|
||||
east: tile.east,
|
||||
north: tile.north,
|
||||
};
|
||||
let widest = 0;
|
||||
for (const piece of tile.near)
|
||||
widest = Math.max(widest, marginOf(piece, top));
|
||||
const lonPerLat = lonPerLatNear(rect, widest);
|
||||
const { boxes } = pieces;
|
||||
const nearby = tile.near.filter((piece) =>
|
||||
near(boxes, piece, rect, marginOf(piece, top), lonPerLat),
|
||||
);
|
||||
const segments = new Float64Array(nearby.length * 4);
|
||||
nearby.forEach((piece, at) => {
|
||||
const e = piece * 6;
|
||||
const a = project([pieces.ends[e], pieces.ends[e + 1], pieces.ends[e + 2]]);
|
||||
const b = project([
|
||||
pieces.ends[e + 3],
|
||||
pieces.ends[e + 4],
|
||||
pieces.ends[e + 5],
|
||||
]);
|
||||
segments.set([a[0] - x0, a[1] - y0, b[0] - x0, b[1] - y0], at * 4);
|
||||
});
|
||||
// Lines: consecutive segments of one item, next to each other along it.
|
||||
const line = new Int32Array(nearby.length);
|
||||
nearby.forEach((piece, at) => {
|
||||
const previous = nearby[at - 1];
|
||||
line[at] =
|
||||
at > 0 &&
|
||||
pieces.item[previous] === pieces.item[piece] &&
|
||||
pieces.index[previous] + 1 === pieces.index[piece]
|
||||
? line[at - 1]
|
||||
: at;
|
||||
});
|
||||
const bins = [];
|
||||
const runs = [];
|
||||
const clampTo = (value, max) => Math.min(max - 1, Math.max(0, value));
|
||||
levels.forEach(([c, r], z) => {
|
||||
const binSize = size * 2 ** z;
|
||||
const counts = new Uint32Array(c * r);
|
||||
const ranges = new Int32Array(nearby.length * 4);
|
||||
const reach = new Float64Array(nearby.length);
|
||||
nearby.forEach((piece, at) => {
|
||||
const s = at * 4;
|
||||
const margin = marginOf(piece, z);
|
||||
reach[at] = margin;
|
||||
const ax = segments[s];
|
||||
const ay = segments[s + 1];
|
||||
const bx = segments[s + 2];
|
||||
const by = segments[s + 3];
|
||||
ranges[s] = clampTo(Math.floor((Math.min(ax, bx) - margin) / binSize), c);
|
||||
ranges[s + 1] = clampTo(
|
||||
Math.floor((Math.min(ay, by) - margin) / binSize),
|
||||
r,
|
||||
);
|
||||
ranges[s + 2] = clampTo(
|
||||
Math.floor((Math.max(ax, bx) + margin) / binSize),
|
||||
c,
|
||||
);
|
||||
ranges[s + 3] = clampTo(
|
||||
Math.floor((Math.max(ay, by) + margin) / binSize),
|
||||
r,
|
||||
);
|
||||
});
|
||||
// A long diagonal segment skips the bins of its box it never nears.
|
||||
const nears = (at, column, row) => {
|
||||
const s = at * 4;
|
||||
const ax = segments[s];
|
||||
const ay = segments[s + 1];
|
||||
const dx = segments[s + 2] - ax;
|
||||
const dy = segments[s + 3] - ay;
|
||||
const cx = (column + 0.5) * binSize - ax;
|
||||
const cy = (row + 0.5) * binSize - ay;
|
||||
const lengthSq = dx * dx + dy * dy;
|
||||
const t =
|
||||
lengthSq > 0
|
||||
? Math.max(0, Math.min(1, (cx * dx + cy * dy) / lengthSq))
|
||||
: 0;
|
||||
return (
|
||||
Math.hypot(cx - t * dx, cy - t * dy) <=
|
||||
reach[at] + binSize * Math.SQRT1_2
|
||||
);
|
||||
};
|
||||
const each = (visit) => {
|
||||
for (let at = 0; at < nearby.length; at++) {
|
||||
const s = at * 4;
|
||||
const sparse =
|
||||
ranges[s + 2] - ranges[s] > 1 && ranges[s + 3] - ranges[s + 1] > 1;
|
||||
for (let row = ranges[s + 1]; row <= ranges[s + 3]; row++)
|
||||
for (let column = ranges[s]; column <= ranges[s + 2]; column++)
|
||||
if (!sparse || nears(at, column, row)) visit(row * c + column, at);
|
||||
}
|
||||
};
|
||||
each((bin) => counts[bin]++);
|
||||
const offsets = new Uint32Array(c * r + 1);
|
||||
for (let bin = 0; bin < c * r; bin++)
|
||||
offsets[bin + 1] = offsets[bin] + counts[bin];
|
||||
const entries = new Int32Array(offsets[c * r]);
|
||||
const cursor = offsets.slice(0, c * r);
|
||||
each((bin, at) => {
|
||||
entries[cursor[bin]++] = at;
|
||||
});
|
||||
for (let bin = 0; bin < c * r; bin++) {
|
||||
const start = runs.length / 4;
|
||||
let first = -1;
|
||||
let last = -1;
|
||||
const flush = () => {
|
||||
if (first < 0) return;
|
||||
const piece = nearby[first];
|
||||
runs.push(
|
||||
pieces.item[piece],
|
||||
first,
|
||||
last - first + 1,
|
||||
pieces.along[piece],
|
||||
);
|
||||
};
|
||||
for (let k = offsets[bin]; k < offsets[bin + 1]; k++) {
|
||||
const at = entries[k];
|
||||
if (first >= 0 && line[at] === line[first] && at - last <= RUN_GAP + 1)
|
||||
last = at;
|
||||
else {
|
||||
flush();
|
||||
first = last = at;
|
||||
}
|
||||
}
|
||||
flush();
|
||||
bins.push(start, runs.length / 4 - start, 0, 0);
|
||||
}
|
||||
});
|
||||
// The segments in the frame's plane, as the shader reads them.
|
||||
for (let at = 0; at < segments.length; at += 2) {
|
||||
segments[at] += x0;
|
||||
segments[at + 1] += y0;
|
||||
}
|
||||
// The widest reach of its corridors: in pixels and in metres.
|
||||
let pixels = 0;
|
||||
let metres = 0;
|
||||
for (const piece of nearby) {
|
||||
pixels = Math.max(pixels, pieces.ratio[piece] * reference);
|
||||
metres = Math.max(metres, pieces.metres[piece]);
|
||||
}
|
||||
return {
|
||||
origin: [x0, y0],
|
||||
size,
|
||||
columns,
|
||||
rows,
|
||||
top,
|
||||
pixels,
|
||||
metres,
|
||||
segments,
|
||||
runs,
|
||||
bins,
|
||||
// The plane radius the region reaches from the frame's origin.
|
||||
extent: Math.max(
|
||||
Math.hypot(x0, y0),
|
||||
Math.hypot(x1, y0),
|
||||
Math.hypot(x0, y1),
|
||||
Math.hypot(x1, y1),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
/** The unit direction at a longitude and geocentric latitude (degrees). */
|
||||
export function direction(lon, latc) {
|
||||
const cosLat = Math.cos(latc * DEG);
|
||||
return [
|
||||
cosLat * Math.cos(lon * DEG),
|
||||
cosLat * Math.sin(lon * DEG),
|
||||
Math.sin(latc * DEG),
|
||||
];
|
||||
}
|
||||
|
||||
/** Terrain sample positions for a tile: [lon, lat geodetic, …] degrees. */
|
||||
export function tileSamples(tile, pieces, limit = 48) {
|
||||
const flat = [];
|
||||
for (let k = 0; k < 9; k++) {
|
||||
const lon = tile.west + ((k % 3) / 2) * (tile.east - tile.west);
|
||||
const latc =
|
||||
tile.south + (Math.floor(k / 3) / 2) * (tile.north - tile.south);
|
||||
flat.push(wrap180(lon), geodetic(latc));
|
||||
}
|
||||
const own = tile.own.length ? tile.own : tile.near;
|
||||
const step = Math.max(1, Math.ceil(own.length / (limit - 9)));
|
||||
for (let k = 0; k < own.length; k += step) {
|
||||
const e = own[k] * 6;
|
||||
const x = pieces.ends[e];
|
||||
const y = pieces.ends[e + 1];
|
||||
const z = pieces.ends[e + 2];
|
||||
flat.push(
|
||||
Math.atan2(y, x) / DEG,
|
||||
geodetic(Math.asin(Math.max(-1, Math.min(1, z))) / DEG),
|
||||
);
|
||||
}
|
||||
return Float64Array.from(flat);
|
||||
}
|
||||
|
||||
export { itemTexels, geodetic };
|
||||
@@ -3,13 +3,15 @@
|
||||
// alike. A commit packs the set's items once (pack.js), with the terrain
|
||||
// heights under them that bound each item's screen box; a set packed before
|
||||
// its terrain loaded is packed again a few times, further apart each time,
|
||||
// until it has them. A show, hide or commit composes the shown sets in draw
|
||||
// order (set order, then creation) and asks for one frame. Nothing animates
|
||||
// on its own. Picks are CPU picks at the globe under the pointer
|
||||
// (src/globe/ground.js), wired by the engine.
|
||||
// until it has them (only the heights are sampled again). A show, hide or
|
||||
// commit composes the shown sets in draw order (set order, then creation)
|
||||
// and asks for one frame; while a shown set has a pulse or a dash, every
|
||||
// frame asks for the next, the continuous render Cesium drew them with (the
|
||||
// pass reads the time each frame). Picks are CPU picks at the globe under
|
||||
// the pointer (src/globe/ground.js), wired by the engine.
|
||||
|
||||
import { createGroundRegistry } from '../../ground.js';
|
||||
import { composeGround, packSet } from './pack.js';
|
||||
import { composeGround, packHeights, packSet } from './pack.js';
|
||||
|
||||
// Frames before the first new try at a set's missing terrain heights; each
|
||||
// later try waits twice as long, up to RETRIES tries.
|
||||
@@ -18,14 +20,38 @@ const RETRIES = 6;
|
||||
|
||||
/**
|
||||
* @param {object} view an initialised Navara ThreeView
|
||||
* @param {{ createPass: (view: object) => ReturnType<typeof import('./pass.js').createGroundPass> }} options
|
||||
* @param {{ createPass: (view: object) => ReturnType<typeof import('./pass.js').createGroundPass>,
|
||||
* nextFrame?: (run: () => void) => void }} options
|
||||
* `createPass` makes the pass (pass.js createGroundPass; the view's three
|
||||
* runtime, which Node tests replace).
|
||||
* runtime, which Node tests replace); `nextFrame` runs a callback before
|
||||
* the next display frame (requestAnimationFrame).
|
||||
* Navara clears its update request once a frame is drawn, so one made
|
||||
* while the frame is drawn (in postRender) is asked again from the next
|
||||
* display frame.
|
||||
* @returns {{ ground: import('../../contract.js').GlobeGround,
|
||||
* pickables: () => object[], diagnostics: () => object, destroy: () => void }}
|
||||
*/
|
||||
export function createNavaraGround(view, { createPass }) {
|
||||
export function createNavaraGround(
|
||||
view,
|
||||
{
|
||||
createPass,
|
||||
nextFrame = (run) =>
|
||||
globalThis.requestAnimationFrame
|
||||
? globalThis.requestAnimationFrame(run)
|
||||
: setTimeout(run, 16),
|
||||
},
|
||||
) {
|
||||
const pass = createPass(view);
|
||||
let destroyed = false;
|
||||
let asked = false;
|
||||
const askNextFrame = () => {
|
||||
if (asked) return;
|
||||
asked = true;
|
||||
nextFrame(() => {
|
||||
asked = false;
|
||||
if (!destroyed) view.forceUpdate();
|
||||
});
|
||||
};
|
||||
const entries = new Set();
|
||||
const terrainHeight = (lon, lat) => {
|
||||
const height = view.sampleTerrainHeight?.({ lat, lng: lon });
|
||||
@@ -35,6 +61,10 @@ export function createNavaraGround(view, { createPass }) {
|
||||
entry.pack = packSet(entry.options.kind, entry.items, { terrainHeight });
|
||||
entry.wait = entry.pack.heights.some(Number.isNaN) ? RETRY_FRAMES : 0;
|
||||
};
|
||||
const sampleAgain = (entry) => {
|
||||
entry.pack.heights = packHeights(entry.pack, { terrainHeight });
|
||||
entry.wait = entry.pack.heights.some(Number.isNaN) ? RETRY_FRAMES : 0;
|
||||
};
|
||||
const compose = () => {
|
||||
const drawn = [...entries]
|
||||
.filter((entry) => entry.shown && entry.pack?.count)
|
||||
@@ -49,13 +79,14 @@ export function createNavaraGround(view, { createPass }) {
|
||||
for (const entry of entries) {
|
||||
if (!entry.wait || !entry.shown || --entry.wait > 0) continue;
|
||||
const tries = entry.tries + 1;
|
||||
pack(entry);
|
||||
sampleAgain(entry);
|
||||
entry.tries = tries;
|
||||
if (entry.wait)
|
||||
entry.wait = tries < RETRIES ? RETRY_FRAMES * 2 ** tries : 0;
|
||||
changed = true;
|
||||
}
|
||||
if (changed) compose();
|
||||
if (changed || registry.animating()) askNextFrame();
|
||||
};
|
||||
view.on('postRender', retry);
|
||||
const registry = createGroundRegistry((options) => {
|
||||
@@ -99,6 +130,7 @@ export function createNavaraGround(view, { createPass }) {
|
||||
textureBytes: pass.textureBytes(),
|
||||
}),
|
||||
destroy() {
|
||||
destroyed = true;
|
||||
view.off('postRender', retry);
|
||||
registry.destroyAll();
|
||||
pass.destroy();
|
||||
|
||||
@@ -87,3 +87,41 @@ test('a set packed before its terrain loaded is packed again later', () => {
|
||||
assert.equal(pass.states.length, before + 1, 'no more once it has them');
|
||||
ground.destroy();
|
||||
});
|
||||
|
||||
test('while a shown set pulses or dashes, every frame asks for the next', () => {
|
||||
const view = fakeView();
|
||||
const pass = fakePass();
|
||||
const queued = [];
|
||||
const ground = createNavaraGround(view, {
|
||||
createPass: () => pass,
|
||||
nextFrame: (run) => queued.push(run),
|
||||
});
|
||||
const set = ground.ground.createSet({ id: 'route', kind: 'corridor' });
|
||||
set.replace([
|
||||
{
|
||||
positions: [
|
||||
[0, 0],
|
||||
[0.1, 0],
|
||||
],
|
||||
color: [0, 1, 1, 1],
|
||||
widthPx: 9,
|
||||
dash: { cells: 8, duty: 0.5, speed: 1 },
|
||||
},
|
||||
]);
|
||||
set.commit();
|
||||
const before = view.frames;
|
||||
view.postRender();
|
||||
view.postRender();
|
||||
assert.equal(queued.length, 1, 'one request a display frame');
|
||||
queued.shift()();
|
||||
assert.equal(view.frames, before + 1);
|
||||
set.show(false);
|
||||
view.postRender();
|
||||
assert.equal(queued.length, 0, 'none while hidden');
|
||||
set.show(true);
|
||||
view.postRender();
|
||||
ground.destroy();
|
||||
const destroyed = view.frames;
|
||||
queued.shift()();
|
||||
assert.equal(view.frames, destroyed, 'none after destroy');
|
||||
});
|
||||
+228
-138
@@ -2,21 +2,29 @@
|
||||
// gnomonic frame of its own (the tangent plane at its centre, reached along
|
||||
// rays from the Earth's centre, where great-circle edges are straight
|
||||
// lines), its boundary as segments in that plane, in float64 until the
|
||||
// numbers are small; per camera change the frames in view space, each
|
||||
// numbers are small; a corridor set as tiles of binned segments
|
||||
// (corridors.js); per camera change the frames in view space, each pass
|
||||
// item's conservative screen box and a screen grid of candidate items,
|
||||
// kept in draw order.
|
||||
|
||||
import * as geo from '../../../geo/index.js';
|
||||
import { cellRing } from '../../ground.js';
|
||||
import {
|
||||
ITEM_TEXELS,
|
||||
itemTexels,
|
||||
packTile,
|
||||
tileCorridors,
|
||||
tileSamples,
|
||||
} from './corridors.js';
|
||||
|
||||
const { cartesian3 } = geo;
|
||||
const DEG = Math.PI / 180;
|
||||
|
||||
/** Item kinds as the shader reads them. */
|
||||
export const KIND = Object.freeze({
|
||||
area: 0,
|
||||
disc: 1,
|
||||
corridorPx: 2,
|
||||
corridorM: 3,
|
||||
corridorTile: 4,
|
||||
});
|
||||
export const GRID_COLS = 64;
|
||||
export const GRID_ROWS = 40;
|
||||
@@ -27,9 +35,7 @@ export const STYLE_TEXELS = 6;
|
||||
/** An area of more segments than this gets a grid of bins (binArea). */
|
||||
export const BIN_THRESHOLD = 32;
|
||||
const MAX_BINS = 32;
|
||||
/** Segments of a corridor drawn as one pass item. */
|
||||
export const CORRIDOR_CHUNK = 4;
|
||||
/** Texture rows hold this many texels. */
|
||||
/** Texture rows hold this many texels (a power of two: the shader masks). */
|
||||
export const ROW = 1024;
|
||||
|
||||
// Highest ground above the ellipsoid a fill reaches (the item's volume).
|
||||
@@ -51,7 +57,7 @@ const nearFloor = (distance) => -Math.min(-FLOOR_M, 1000 + 0.05 * distance);
|
||||
const SAMPLE_STEP_DEG = 0.005;
|
||||
const lodMargin = (distance) => 450 + 0.02 * distance;
|
||||
const TILE_HEADROOM_M = 900;
|
||||
/** Terrain samples per pass item. */
|
||||
/** Terrain samples per area; a corridor tile takes more (corridors.js). */
|
||||
const SAMPLES = 9;
|
||||
const CELL_STEP_DEG = 0.25;
|
||||
|
||||
@@ -66,8 +72,18 @@ function frameAt(lon, lat) {
|
||||
if (!Number.isFinite(east.x)) Object.assign(east, { x: 1, y: 0, z: 0 });
|
||||
const north = cartesian3.cross(up, east, cartesian3.create());
|
||||
const scratch = cartesian3.create();
|
||||
// A ground position in the frame's gnomonic plane, metres.
|
||||
// A ground position in the frame's gnomonic plane, metres; or, given a
|
||||
// unit direction [x, y, z] from the Earth's centre, where its ray meets
|
||||
// the plane.
|
||||
const project = (lonDeg, latDeg) => {
|
||||
if (Array.isArray(lonDeg)) {
|
||||
const [x, y, z] = lonDeg;
|
||||
const scale = radius / (x * up.x + y * up.y + z * up.z);
|
||||
return [
|
||||
(x * east.x + y * east.y + z * east.z) * scale,
|
||||
(x * north.x + y * north.y + z * north.z) * scale,
|
||||
];
|
||||
}
|
||||
cartesian3.fromDegrees(lonDeg, latDeg, 0, undefined, scratch);
|
||||
const dx = scratch.x - center.x;
|
||||
const dy = scratch.y - center.y;
|
||||
@@ -172,56 +188,44 @@ export function binArea(list) {
|
||||
};
|
||||
}
|
||||
|
||||
// An open side of a corridor tile's cell: its meridian test always holds.
|
||||
const OPEN = 1e30;
|
||||
|
||||
// A pixel corridor reaches half its width and the half pixel of its
|
||||
// anti-aliasing in pixels; a metre one its half width in metres and the
|
||||
// half pixel.
|
||||
const reachOf = (item) => [
|
||||
(item.widthPx ?? 0) / 2 + 0.5,
|
||||
(item.widthM ?? 0) / 2,
|
||||
];
|
||||
|
||||
/**
|
||||
* One set's items packed for the pass as pass items: float64 frames, the
|
||||
* terrain heights under each (`terrainHeight(lon, lat)`, undefined where
|
||||
* not loaded: that item keeps the deep default box), the
|
||||
* style texels (segment starts relative to the set's own segments) and the
|
||||
* segments. A corridor longer than CORRIDOR_CHUNK segments becomes one pass
|
||||
* item per chunk, each in its own plane with its own screen box; a chunk
|
||||
* also holds its neighbours' end segments and draws only where its own
|
||||
* segments are the nearest, so joints blend once.
|
||||
* not loaded: that item keeps the deep default box; packHeights samples
|
||||
* them again), the style texels (segment starts relative to the set's own
|
||||
* segments) and the segments. A corridor set becomes tiles (corridors.js):
|
||||
* each a pass item with its segments, the runs of its bins and the set's
|
||||
* item looks (`items`, ITEM_TEXELS each).
|
||||
*/
|
||||
export function packSet(kind, items, { terrainHeight = null } = {}) {
|
||||
export function packSet(
|
||||
kind,
|
||||
items,
|
||||
{ terrainHeight = null, tilePieces = undefined } = {},
|
||||
) {
|
||||
const frames = [];
|
||||
const styles = [];
|
||||
const volumes = [];
|
||||
const heights = [];
|
||||
const segments = [];
|
||||
const bins = [];
|
||||
// Terrain heights on a grid of SAMPLE_STEP_DEG, each sampled once.
|
||||
const sampled = new Map();
|
||||
const heightAt = (lon, lat) => {
|
||||
const x = Math.round(lon / SAMPLE_STEP_DEG);
|
||||
const y = Math.round(lat / SAMPLE_STEP_DEG);
|
||||
const key = x * 1e6 + y;
|
||||
if (!sampled.has(key))
|
||||
sampled.set(
|
||||
key,
|
||||
terrainHeight?.(x * SAMPLE_STEP_DEG, y * SAMPLE_STEP_DEG),
|
||||
);
|
||||
return sampled.get(key);
|
||||
};
|
||||
// The lowest and highest terrain under a pass item's sample positions
|
||||
// (flat [lon, lat, …], at most SAMPLES of them), NaN when unknown.
|
||||
const sampleHeights = (flat) => {
|
||||
if (!terrainHeight) return [Number.NaN, Number.NaN];
|
||||
let low = Infinity;
|
||||
let high = -Infinity;
|
||||
const count = flat.length / 2;
|
||||
const step = Math.max(1, Math.ceil(count / SAMPLES));
|
||||
for (let index = 0; index < count; index += step) {
|
||||
const height = heightAt(flat[index * 2], flat[index * 2 + 1]);
|
||||
if (!Number.isFinite(height)) return [Number.NaN, Number.NaN];
|
||||
low = Math.min(low, height);
|
||||
high = Math.max(high, height);
|
||||
}
|
||||
return [low, high];
|
||||
};
|
||||
const emit = (frame, style, extent, padPx, list, samples, extra = null) => {
|
||||
heights.push(...sampleHeights(samples));
|
||||
const runs = [];
|
||||
const looks = [];
|
||||
const samples = [];
|
||||
const emit = (frame, style, extent, padPx, list, sampled, extra = null) => {
|
||||
samples.push(sampled);
|
||||
const start = segments.length / 4;
|
||||
segments.push(...list);
|
||||
for (let index = 0; index < list.length; index++)
|
||||
segments.push(list[index]);
|
||||
if (extra) {
|
||||
// The bins' own segment lists follow the item's, relative to its start.
|
||||
style.bins[3] = bins.length / 4;
|
||||
@@ -255,7 +259,7 @@ export function packSet(kind, items, { terrainHeight = null } = {}) {
|
||||
floor,
|
||||
CEILING_M,
|
||||
start,
|
||||
list.length / 4,
|
||||
style.count ?? list.length / 4,
|
||||
...style.bins,
|
||||
...style.origin,
|
||||
);
|
||||
@@ -272,114 +276,180 @@ export function packSet(kind, items, { terrainHeight = null } = {}) {
|
||||
};
|
||||
const reach = (points) =>
|
||||
points.reduce((most, [x, y]) => Math.max(most, Math.hypot(x, y)), 0);
|
||||
for (const item of items) {
|
||||
const none = [0, 0, 0, 0];
|
||||
if (kind === 'corridor') {
|
||||
const code = item.widthM ? KIND.corridorM : KIND.corridorPx;
|
||||
const segmentCount = item.path.length / 2 - 1;
|
||||
for (let first = 0; first < segmentCount; first += CORRIDOR_CHUNK) {
|
||||
const own = Math.min(CORRIDOR_CHUNK, segmentCount - first);
|
||||
const from = Math.max(0, first - 1);
|
||||
const to = Math.min(segmentCount, first + own + 1);
|
||||
const part = item.path.subarray(from * 2, (to + 1) * 2);
|
||||
let west = Infinity;
|
||||
let east = -Infinity;
|
||||
let south = Infinity;
|
||||
let north = -Infinity;
|
||||
for (let at = 0; at < part.length; at += 2) {
|
||||
west = Math.min(west, part[at]);
|
||||
east = Math.max(east, part[at]);
|
||||
south = Math.min(south, part[at + 1]);
|
||||
north = Math.max(north, part[at + 1]);
|
||||
}
|
||||
const frame = frameAt((west + east) / 2, (south + north) / 2);
|
||||
const points = planePoints(part, frame.project);
|
||||
if (kind === 'corridor' && items.length) {
|
||||
const reference = Math.min(...items.map((item) => reachOf(item)[0]));
|
||||
const { pieces, tiles } = tileCorridors(
|
||||
items,
|
||||
reachOf,
|
||||
reference,
|
||||
tilePieces,
|
||||
);
|
||||
items.forEach((item, index) =>
|
||||
looks.push(...itemTexels(item, pieces.lineLengths[index])),
|
||||
);
|
||||
for (const tile of tiles) {
|
||||
const frame = frameAt(
|
||||
(tile.west + tile.east) / 2,
|
||||
(tile.south + tile.north) / 2,
|
||||
);
|
||||
const packed = packTile(tile, pieces, items, frame, reachOf, reference);
|
||||
// Runs and bins relative to the tile's own: its style holds where
|
||||
// they start in the set's.
|
||||
const runStart = runs.length / 4;
|
||||
for (const value of packed.runs) runs.push(value);
|
||||
const binStart = bins.length / 4;
|
||||
for (const value of packed.bins) bins.push(value);
|
||||
// The tile's cell: east of its west meridian (a normal pointing
|
||||
// east), west of its east one (one pointing west), between its
|
||||
// parallels' sines; an open side takes everything beyond it.
|
||||
const meridian = (lon, sign) => [
|
||||
-sign * Math.sin(lon * DEG),
|
||||
sign * Math.cos(lon * DEG),
|
||||
];
|
||||
const { open } = tile;
|
||||
const parallel = (latc, side) =>
|
||||
open[side] ? (side === 'south' ? -2 : 2) : Math.sin(latc * DEG);
|
||||
emit(
|
||||
frame,
|
||||
{
|
||||
fill: [...meridian(tile.west, 1), ...meridian(tile.east, -1)],
|
||||
line: [
|
||||
parallel(tile.south, 'south'),
|
||||
parallel(tile.north, 'north'),
|
||||
reference,
|
||||
packed.top,
|
||||
],
|
||||
shape: [KIND.corridorTile, packed.size, packed.columns, packed.rows],
|
||||
count: runStart,
|
||||
bins: [...packed.origin, binStart, 0],
|
||||
// Its open meridians, and the far corner of its bins.
|
||||
origin: [
|
||||
open.west ? OPEN : 0,
|
||||
open.east ? OPEN : 0,
|
||||
packed.origin[0] + packed.columns * packed.size,
|
||||
packed.origin[1] + packed.rows * packed.size,
|
||||
],
|
||||
},
|
||||
packed.extent * 1.01 + 1 + packed.metres,
|
||||
packed.pixels,
|
||||
packed.segments,
|
||||
tileSamples(tile, pieces),
|
||||
);
|
||||
}
|
||||
} else
|
||||
for (const item of items) {
|
||||
const none = [0, 0, 0, 0];
|
||||
const style = {
|
||||
fill: item.fill ?? none,
|
||||
line: item.outline?.color ?? none,
|
||||
shape: [KIND.area, item.outline?.widthPx ?? 0, 0, 0],
|
||||
bins: [0, 0, 0, 0],
|
||||
origin: [0, 0, 0, 0],
|
||||
};
|
||||
const padPx = (item.outline?.widthPx ?? 0) / 2;
|
||||
if (kind === 'disc') {
|
||||
const frame = frameAt(item.center[0], item.center[1]);
|
||||
const radius = frame.radius * Math.tan(item.radiusM / frame.radius);
|
||||
style.shape = [KIND.disc, item.outline?.widthPx ?? 0, 0, radius];
|
||||
emit(
|
||||
frame,
|
||||
{
|
||||
fill: item.fill,
|
||||
line: none,
|
||||
shape: [code, 0, item.widthPx ?? 0, item.widthM ?? 0],
|
||||
bins: [first - from, own, 0, 0],
|
||||
origin: [0, 0, 0, 0],
|
||||
},
|
||||
reach(points) + (item.widthM ?? 0) / 2,
|
||||
(item.widthPx ?? 0) / 2,
|
||||
segmentsOf(points, false),
|
||||
part,
|
||||
style,
|
||||
radius,
|
||||
padPx,
|
||||
[],
|
||||
Float64Array.of(
|
||||
...item.center,
|
||||
item.bounds.west,
|
||||
item.center[1],
|
||||
item.bounds.east,
|
||||
item.center[1],
|
||||
item.center[0],
|
||||
item.bounds.south,
|
||||
item.center[0],
|
||||
item.bounds.north,
|
||||
),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const { bounds } = item;
|
||||
const frame = frameAt(
|
||||
(bounds.west + bounds.east) / 2,
|
||||
(bounds.south + bounds.north) / 2,
|
||||
);
|
||||
const rings = (
|
||||
kind === 'cell' ? [cellRing(item, CELL_STEP_DEG)] : item.rings
|
||||
).map((ring) => planePoints(ring, frame.project));
|
||||
const list = rings.flatMap((ring) => segmentsOf(ring, true));
|
||||
const binned = binArea(list);
|
||||
if (binned) {
|
||||
style.bins = [binned.columns, binned.rows, binned.size, 0];
|
||||
style.origin = [binned.x, binned.y, 0, 0];
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const style = {
|
||||
fill: item.fill ?? none,
|
||||
line: item.outline?.color ?? none,
|
||||
shape: [KIND.area, item.outline?.widthPx ?? 0, 0, 0],
|
||||
bins: [0, 0, 0, 0],
|
||||
origin: [0, 0, 0, 0],
|
||||
};
|
||||
const padPx = (item.outline?.widthPx ?? 0) / 2;
|
||||
if (kind === 'disc') {
|
||||
const frame = frameAt(item.center[0], item.center[1]);
|
||||
const radius = frame.radius * Math.tan(item.radiusM / frame.radius);
|
||||
style.shape = [KIND.disc, item.outline?.widthPx ?? 0, 0, radius];
|
||||
emit(
|
||||
frame,
|
||||
style,
|
||||
radius,
|
||||
Math.max(...rings.map(reach)),
|
||||
padPx,
|
||||
[],
|
||||
list,
|
||||
Float64Array.of(
|
||||
...item.center,
|
||||
item.bounds.west,
|
||||
item.center[1],
|
||||
item.bounds.east,
|
||||
item.center[1],
|
||||
item.center[0],
|
||||
item.bounds.south,
|
||||
item.center[0],
|
||||
item.bounds.north,
|
||||
(bounds.west + bounds.east) / 2,
|
||||
(bounds.south + bounds.north) / 2,
|
||||
...(kind === 'cell' ? cellRing(item, CELL_STEP_DEG) : item.rings[0]),
|
||||
),
|
||||
binned,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const { bounds } = item;
|
||||
const frame = frameAt(
|
||||
(bounds.west + bounds.east) / 2,
|
||||
(bounds.south + bounds.north) / 2,
|
||||
);
|
||||
const rings = (
|
||||
kind === 'cell' ? [cellRing(item, CELL_STEP_DEG)] : item.rings
|
||||
).map((ring) => planePoints(ring, frame.project));
|
||||
const list = rings.flatMap((ring) => segmentsOf(ring, true));
|
||||
const binned = binArea(list);
|
||||
if (binned) {
|
||||
style.bins = [binned.columns, binned.rows, binned.size, 0];
|
||||
style.origin = [binned.x, binned.y, 0, 0];
|
||||
}
|
||||
emit(
|
||||
frame,
|
||||
style,
|
||||
Math.max(...rings.map(reach)),
|
||||
padPx,
|
||||
list,
|
||||
Float64Array.of(
|
||||
(bounds.west + bounds.east) / 2,
|
||||
(bounds.south + bounds.north) / 2,
|
||||
...(kind === 'cell' ? cellRing(item, CELL_STEP_DEG) : item.rings[0]),
|
||||
),
|
||||
binned,
|
||||
);
|
||||
}
|
||||
return {
|
||||
const pack = {
|
||||
count: volumes.length / 4,
|
||||
bins: Float32Array.from(bins),
|
||||
heights: Float64Array.from(heights),
|
||||
frames: Float64Array.from(frames),
|
||||
styles: Float32Array.from(styles),
|
||||
volumes: Float64Array.from(volumes),
|
||||
segments: Float32Array.from(segments),
|
||||
runs: Float32Array.from(runs),
|
||||
items: Float32Array.from(looks),
|
||||
samples,
|
||||
};
|
||||
pack.heights = packHeights(pack, { terrainHeight });
|
||||
return pack;
|
||||
}
|
||||
|
||||
/**
|
||||
* The lowest and highest terrain under each pass item of a pack, NaN where
|
||||
* any of its samples is not loaded: [low, high, …].
|
||||
*/
|
||||
export function packHeights(pack, { terrainHeight = null } = {}) {
|
||||
const heights = new Float64Array(pack.count * 2).fill(Number.NaN);
|
||||
if (!terrainHeight) return heights;
|
||||
// Terrain heights on a grid of SAMPLE_STEP_DEG, each sampled once.
|
||||
const sampled = new Map();
|
||||
const heightAt = (lon, lat) => {
|
||||
const x = Math.round(lon / SAMPLE_STEP_DEG);
|
||||
const y = Math.round(lat / SAMPLE_STEP_DEG);
|
||||
const key = x * 1e6 + y;
|
||||
if (!sampled.has(key))
|
||||
sampled.set(key, terrainHeight(x * SAMPLE_STEP_DEG, y * SAMPLE_STEP_DEG));
|
||||
return sampled.get(key);
|
||||
};
|
||||
pack.samples.forEach((flat, item) => {
|
||||
let low = Infinity;
|
||||
let high = -Infinity;
|
||||
const count = flat.length / 2;
|
||||
const limit =
|
||||
pack.styles[item * STYLE_TEXELS * 4 + 8] === KIND.corridorTile
|
||||
? count
|
||||
: SAMPLES;
|
||||
const step = Math.max(1, Math.ceil(count / limit));
|
||||
for (let index = 0; index < count; index += step) {
|
||||
const height = heightAt(flat[index * 2], flat[index * 2 + 1]);
|
||||
if (!Number.isFinite(height)) return;
|
||||
low = Math.min(low, height);
|
||||
high = Math.max(high, height);
|
||||
}
|
||||
heights[item * 2] = low;
|
||||
heights[item * 2 + 1] = high;
|
||||
});
|
||||
return heights;
|
||||
}
|
||||
|
||||
/** Storage for `texels` RGBA texels in rows of ROW. */
|
||||
@@ -454,9 +524,17 @@ export function composeGround(packs) {
|
||||
const bins = texelStorage(
|
||||
packs.reduce((total, pack) => total + pack.bins.length / 4, 0),
|
||||
);
|
||||
const runs = texelStorage(
|
||||
packs.reduce((total, pack) => total + pack.runs.length / 4, 0),
|
||||
);
|
||||
const looks = texelStorage(
|
||||
packs.reduce((total, pack) => total + pack.items.length / 4, 0),
|
||||
);
|
||||
let item = 0;
|
||||
let segment = 0;
|
||||
let bin = 0;
|
||||
let run = 0;
|
||||
let look = 0;
|
||||
for (const pack of packs) {
|
||||
frames64.set(pack.frames, item * 13);
|
||||
volumes.set(pack.volumes, item * 4);
|
||||
@@ -468,12 +546,22 @@ export function composeGround(packs) {
|
||||
// A binned area's first bin.
|
||||
if (styles.data[at + 8] === KIND.area && styles.data[at + 16] > 0)
|
||||
styles.data[at + 19] += bin;
|
||||
// A corridor tile's first run, first bin and its set's first item.
|
||||
if (styles.data[at + 8] === KIND.corridorTile) {
|
||||
styles.data[at + 15] += run;
|
||||
styles.data[at + 18] += bin;
|
||||
styles.data[at + 19] += look / ITEM_TEXELS;
|
||||
}
|
||||
}
|
||||
segments.data.set(pack.segments, segment * 4);
|
||||
bins.data.set(pack.bins, bin * 4);
|
||||
runs.data.set(pack.runs, run * 4);
|
||||
looks.data.set(pack.items, look * 4);
|
||||
item += pack.count;
|
||||
segment += pack.segments.length / 4;
|
||||
bin += pack.bins.length / 4;
|
||||
run += pack.runs.length / 4;
|
||||
look += pack.items.length / 4;
|
||||
}
|
||||
const frames = texelStorage(count * TEXELS);
|
||||
const grid = {
|
||||
@@ -499,6 +587,8 @@ export function composeGround(packs) {
|
||||
styles,
|
||||
segments,
|
||||
bins,
|
||||
runs,
|
||||
items: looks,
|
||||
frames,
|
||||
grid,
|
||||
get candidates() {
|
||||
|
||||
@@ -2,13 +2,20 @@ import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as geo from '../../../geo/index.js';
|
||||
import { normalizeGroundItem } from '../../ground.js';
|
||||
import {
|
||||
EPSILON_M,
|
||||
ITEM_TEXELS,
|
||||
LOOK,
|
||||
MARGIN_RATIO,
|
||||
MAX_PIECE_DEG,
|
||||
} from './corridors.js';
|
||||
import {
|
||||
BIN_THRESHOLD,
|
||||
binArea,
|
||||
composeGround,
|
||||
CORRIDOR_CHUNK,
|
||||
GRID_COLS,
|
||||
KIND,
|
||||
packHeights,
|
||||
packSet,
|
||||
STYLE_TEXELS,
|
||||
} from './pack.js';
|
||||
@@ -74,11 +81,21 @@ test('gnomonic segments keep a great-circle edge straight and distances right',
|
||||
},
|
||||
]),
|
||||
);
|
||||
const [ax, ay, bx, by] = corridor.segments;
|
||||
assert.ok(Math.abs(ay) < 1e-6 && Math.abs(by) < 1e-6, 'on the equator');
|
||||
assert.ok(Math.abs(ax + bx) < 1e-6);
|
||||
assert.equal(corridor.styles[8], KIND.corridorPx);
|
||||
assert.equal(corridor.styles[10], 4);
|
||||
// Cut into pieces of at most MAX_PIECE_DEG, each straight in the plane.
|
||||
const pieces = corridor.segments.length / 4;
|
||||
assert.equal(pieces, Math.ceil(2 / MAX_PIECE_DEG));
|
||||
for (let at = 0; at < corridor.segments.length; at += 4) {
|
||||
const [ax, ay, bx, by] = corridor.segments.slice(at, at + 4);
|
||||
assert.ok(Math.abs(ay) < 1e-3 && Math.abs(by) < 1e-3, 'on the equator');
|
||||
if (at) assert.equal(ax, corridor.segments[at - 2], 'joined');
|
||||
assert.ok(bx > ax);
|
||||
}
|
||||
assert.ok(
|
||||
Math.abs(corridor.segments[0] + corridor.segments.at(-2)) < 1e-3,
|
||||
'centred',
|
||||
);
|
||||
assert.equal(corridor.styles[8], KIND.corridorTile);
|
||||
assert.equal(corridor.items[4], 4, 'the item keeps its width');
|
||||
});
|
||||
|
||||
test('composed sets keep draw order and offset their segments', () => {
|
||||
@@ -171,31 +188,203 @@ test('composed sets keep draw order and offset their segments', () => {
|
||||
assert.ok(state.frames.data[2] < -1.9e6);
|
||||
});
|
||||
|
||||
test('a long corridor packs as chunks that own their own segments', () => {
|
||||
const positions = Array.from({ length: 41 }, (_, index) => [index * 0.01, 0]);
|
||||
const pack = packSet(
|
||||
'corridor',
|
||||
items('corridor', [{ positions, color: [1, 1, 1, 1], widthM: 10 }]),
|
||||
// Random lines over a region, as the ground bench draws them.
|
||||
function lines(count, { lon = 55, lat = 25, spread = 0.4, step = 0.004 } = {}) {
|
||||
let seed = 7;
|
||||
const next = () => {
|
||||
seed = (seed * 1664525 + 1013904223) >>> 0;
|
||||
return seed / 2 ** 32;
|
||||
};
|
||||
return Array.from({ length: count }, (_, index) => {
|
||||
let x = lon + next() * spread;
|
||||
let y = lat + next() * spread;
|
||||
const heading = next() * 2 * Math.PI;
|
||||
const positions = [];
|
||||
for (let k = 0; k < 12; k++) {
|
||||
positions.push([x, y]);
|
||||
const turn = heading + (next() - 0.5) * 1.2;
|
||||
x += step * Math.cos(turn);
|
||||
y += step * Math.sin(turn);
|
||||
}
|
||||
return {
|
||||
positions,
|
||||
color: [1, 1, 1, 1],
|
||||
...(index % 5 ? { widthPx: 2 + (index % 3) } : { widthM: 30 }),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// A tile's levels as the shader walks them: [directory start, columns, rows].
|
||||
function levelsOf(style) {
|
||||
const out = [];
|
||||
let columns = style[10];
|
||||
let rows = style[11];
|
||||
let dir = style[18];
|
||||
for (let z = 0; z <= style[7]; z++) {
|
||||
out.push([dir, columns, rows]);
|
||||
dir += columns * rows;
|
||||
columns = (columns + 1) >> 1;
|
||||
rows = (rows + 1) >> 1;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
test('a corridor set packs as tiles whose bins list every segment near them', () => {
|
||||
const checked = items('corridor', lines(80));
|
||||
const pack = packSet('corridor', checked, { tilePieces: 300 });
|
||||
assert.ok(pack.count > 1, `${pack.count} tiles`);
|
||||
assert.ok(pack.count >= 1);
|
||||
assert.equal(pack.items.length, checked.length * ITEM_TEXELS * 4);
|
||||
for (let tile = 0; tile < pack.count; tile++) {
|
||||
const style = pack.styles.slice(
|
||||
tile * STYLE_TEXELS * 4,
|
||||
(tile + 1) * STYLE_TEXELS * 4,
|
||||
);
|
||||
assert.equal(style[8], KIND.corridorTile);
|
||||
const size = style[9];
|
||||
const [x0, y0] = [style[16], style[17]];
|
||||
const segmentStart = style[14];
|
||||
const runStart = style[15];
|
||||
const reference = style[6];
|
||||
for (const [z, [dir, columns, rows]] of levelsOf(style).entries()) {
|
||||
const bin = size * 2 ** z;
|
||||
// Brute force: every segment of the tile within its margin of a bin
|
||||
// is in one of the bin's runs.
|
||||
for (let row = 0; row < rows; row++)
|
||||
for (let column = 0; column < columns; column++) {
|
||||
const at = (dir + row * columns + column) * 4;
|
||||
const listed = new Set();
|
||||
for (let r = 0; r < pack.bins[at + 1]; r++) {
|
||||
const run = (runStart + pack.bins[at] + r) * 4;
|
||||
for (let k = 0; k < pack.runs[run + 2]; k++)
|
||||
listed.add(pack.runs[run + 1] + k);
|
||||
}
|
||||
const left = x0 + column * bin;
|
||||
const bottom = y0 + row * bin;
|
||||
for (
|
||||
let s = 0;
|
||||
s <
|
||||
(tile + 1 < pack.count
|
||||
? pack.styles[(tile + 1) * STYLE_TEXELS * 4 + 14]
|
||||
: pack.segments.length / 4) -
|
||||
segmentStart;
|
||||
s++
|
||||
) {
|
||||
const g = (segmentStart + s) * 4;
|
||||
const [ax, ay, bx, by] = pack.segments.slice(g, g + 4);
|
||||
// The segment's distance to the bin's square.
|
||||
let near = Infinity;
|
||||
for (let t = 0; t <= 16; t++) {
|
||||
const px = ax + ((bx - ax) * t) / 16;
|
||||
const py = ay + ((by - ay) * t) / 16;
|
||||
const dx = Math.max(left - px, 0, px - left - bin);
|
||||
const dy = Math.max(bottom - py, 0, py - bottom - bin);
|
||||
near = Math.min(near, Math.hypot(dx, dy));
|
||||
}
|
||||
// The least margin of any item: a 2 px one (1.5 px of reach)
|
||||
// or a 30 m one (0.5 px, the reference, and 15 m).
|
||||
const margin =
|
||||
Math.min(
|
||||
(MARGIN_RATIO * bin * 1.5) / reference,
|
||||
MARGIN_RATIO * bin + 15,
|
||||
) +
|
||||
EPSILON_M * 0.5;
|
||||
if (near < margin)
|
||||
assert.ok(
|
||||
listed.has(s),
|
||||
`tile ${tile} level ${z} bin ${column},${row} misses segment ${s}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("tiles' cells split the set's region: one tile holds each point", () => {
|
||||
const checked = items('corridor', [
|
||||
...lines(400, { lon: -179.9, lat: 60, spread: 0.3, step: 0.02 }),
|
||||
...lines(400, { lon: 179.7, lat: 60.1, spread: 0.2, step: 0.02 }),
|
||||
]);
|
||||
// Few pieces a tile: many tiles.
|
||||
const pack = packSet('corridor', checked, { tilePieces: 300 });
|
||||
assert.ok(pack.count > 8, `${pack.count} tiles`);
|
||||
const cells = [];
|
||||
for (let tile = 0; tile < pack.count; tile++) {
|
||||
const at = tile * STYLE_TEXELS * 4;
|
||||
cells.push([
|
||||
...pack.styles.slice(at, at + 8),
|
||||
...pack.styles.slice(at + 20, at + 22),
|
||||
]);
|
||||
}
|
||||
let seed = 3;
|
||||
const next = () => {
|
||||
seed = (seed * 1664525 + 1013904223) >>> 0;
|
||||
return seed / 2 ** 32;
|
||||
};
|
||||
for (let k = 0; k < 2000; k++) {
|
||||
// Inside the set's bounds and beyond them (open sides).
|
||||
const lon = 179.4 + next() * 1.3;
|
||||
const lat = 59.8 + next() * 0.7;
|
||||
const world = geo.cartesian3.fromDegrees(lon, lat, next() * 500);
|
||||
const sinLat = world.z / Math.hypot(world.x, world.y, world.z);
|
||||
const holders = cells.filter(
|
||||
(c) =>
|
||||
world.x * c[0] + world.y * c[1] + c[8] >= 0 &&
|
||||
world.x * c[2] + world.y * c[3] + c[9] > 0 &&
|
||||
sinLat >= c[4] &&
|
||||
sinLat < c[5],
|
||||
);
|
||||
assert.equal(holders.length, 1, `${lon}, ${lat}: ${holders.length} tiles`);
|
||||
}
|
||||
});
|
||||
|
||||
test("a corridor item's look packs for the shader", () => {
|
||||
const [item] = items('corridor', [
|
||||
{
|
||||
positions: [
|
||||
[0, 0],
|
||||
[0.01, 0],
|
||||
],
|
||||
color: [1, 0, 0, 1],
|
||||
widthPx: 9,
|
||||
glow: { power: 0.25 },
|
||||
pulse: { periodMs: 1600, min: 0.35, max: 0.75 },
|
||||
dash: {
|
||||
cells: 64,
|
||||
duty: 0.46,
|
||||
speed: 0.55,
|
||||
gapAlpha: 0.18,
|
||||
emission: 0.9,
|
||||
},
|
||||
},
|
||||
]);
|
||||
const pack = packSet('corridor', [item]);
|
||||
const look = [...pack.items];
|
||||
assert.deepEqual(look.slice(0, 4), [1, 0, 0, 1]);
|
||||
assert.equal(look[4], 9);
|
||||
assert.ok(Math.abs(look[6] - 1113) < 5, `length ${look[6]}`);
|
||||
assert.equal(look[7], LOOK.glow | LOOK.pulse | LOOK.dash);
|
||||
assert.ok(Math.abs(look[8] - 0.25) < 1e-6);
|
||||
assert.equal(look[9], 1, 'no taper');
|
||||
assert.ok(Math.abs(look[10] - 1.6) < 1e-6);
|
||||
assert.ok(Math.abs(look[11] - 0.35) < 1e-6);
|
||||
assert.ok(Math.abs(look[12] - 0.75) < 1e-6);
|
||||
assert.deepEqual(
|
||||
look.slice(13, 16).map((v) => +v.toFixed(2)),
|
||||
[64, 0.46, 0.55],
|
||||
);
|
||||
assert.equal(pack.count, Math.ceil(40 / CORRIDOR_CHUNK));
|
||||
const owned = (index) => [
|
||||
...pack.styles.slice(
|
||||
index * STYLE_TEXELS * 4 + 16,
|
||||
index * STYLE_TEXELS * 4 + 18,
|
||||
),
|
||||
];
|
||||
const counts = (index) => pack.styles[index * STYLE_TEXELS * 4 + 15];
|
||||
// The first chunk has no segment before it, the others one each side.
|
||||
assert.deepEqual(owned(0), [0, CORRIDOR_CHUNK]);
|
||||
assert.equal(counts(0), CORRIDOR_CHUNK + 1);
|
||||
assert.deepEqual(owned(1), [1, CORRIDOR_CHUNK]);
|
||||
assert.equal(counts(1), CORRIDOR_CHUNK + 2);
|
||||
const last = pack.count - 1;
|
||||
const rest = 40 - last * CORRIDOR_CHUNK;
|
||||
assert.deepEqual(owned(last), [1, rest]);
|
||||
assert.equal(counts(last), rest + 1);
|
||||
assert.equal(pack.styles[8], KIND.corridorM);
|
||||
assert.equal(pack.styles[11], 10);
|
||||
assert.deepEqual(
|
||||
look.slice(16, 18).map((v) => +v.toFixed(2)),
|
||||
[0.18, 0.9],
|
||||
);
|
||||
});
|
||||
|
||||
test('heights are sampled again without packing the set again', () => {
|
||||
const checked = items('corridor', lines(20));
|
||||
const pack = packSet('corridor', checked);
|
||||
assert.ok(pack.heights.every(Number.isNaN));
|
||||
const heights = packHeights(pack, { terrainHeight: () => 25 });
|
||||
assert.deepEqual([...heights], Array(pack.count * 2).fill(25));
|
||||
});
|
||||
|
||||
test('sampled terrain heights bound the screen box; unknown ones keep it deep', () => {
|
||||
|
||||
+176
-36
@@ -4,11 +4,14 @@
|
||||
// 3D tiles); where that is the ground (not a mesh in front of it), the
|
||||
// candidates of its screen cell (pack.js) are tested in their own gnomonic
|
||||
// planes: a disc against its radius, an area against its segments (even-odd
|
||||
// inside, distance to the nearest edge), a corridor against its distance to
|
||||
// the line. Fills and outlines are anti-aliased over one pixel across the
|
||||
// boundary and blended in display space, in draw order, as Cesium blends
|
||||
// translucent ground primitives. Costs nothing while no item is drawn
|
||||
// (the effect is hidden).
|
||||
// inside, distance to the nearest edge), a corridor tile (corridors.js),
|
||||
// when the pixel's ground is in its cell, against the runs of the pixel's
|
||||
// bin: each item's distance to its nearest segment there. Fills, outlines
|
||||
// and corridors are anti-aliased over one pixel across the boundary and
|
||||
// blended in display space, in draw order, as Cesium blends translucent
|
||||
// ground primitives; a corridor's glow, pulse and dash follow Cesium's
|
||||
// materials, from the time uniform (src/globe/ground.js groundSeconds).
|
||||
// Costs nothing while no item is drawn (the effect is hidden).
|
||||
|
||||
import { EffectDesc, Effect as NavaraEffect } from '@navaramap/three';
|
||||
import { Effect, EffectAttribute } from 'postprocessing';
|
||||
@@ -21,11 +24,22 @@ import {
|
||||
RGBAFormat,
|
||||
Uniform,
|
||||
} from 'three';
|
||||
import { DASH_EDGE, groundSeconds } from '../../ground.js';
|
||||
import { withFrameUpdates, withPassDisposal } from '../frameDescriptor.js';
|
||||
import { GRID_COLS, GRID_ROWS, KIND, STYLE_TEXELS, TEXELS } from './pack.js';
|
||||
import { ITEM_TEXELS, LOOK, MARGIN_RATIO } from './corridors.js';
|
||||
import {
|
||||
GRID_COLS,
|
||||
GRID_ROWS,
|
||||
KIND,
|
||||
ROW,
|
||||
STYLE_TEXELS,
|
||||
TEXELS,
|
||||
} from './pack.js';
|
||||
|
||||
export const GROUND_EFFECT_KEY = 'gevGround';
|
||||
|
||||
const float = (value) => (Number.isInteger(value) ? `${value}.0` : `${value}`);
|
||||
|
||||
const fragmentShader = /* glsl */ `
|
||||
uniform sampler2D tAllDepth;
|
||||
uniform sampler2D tSurfaceDepth;
|
||||
@@ -33,13 +47,17 @@ uniform highp sampler2D tFrames;
|
||||
uniform highp sampler2D tStyles;
|
||||
uniform highp sampler2D tSegments;
|
||||
uniform highp sampler2D tBins;
|
||||
uniform highp sampler2D tRuns;
|
||||
uniform highp sampler2D tItems;
|
||||
uniform highp sampler2D tGrid;
|
||||
uniform highp sampler2D tCandidates;
|
||||
uniform mat4 uInverseProjection;
|
||||
uniform mat4 uViewToWorld;
|
||||
uniform float uLogDepthFC;
|
||||
uniform float uTime;
|
||||
// Rows of ${ROW} texels (pack.js texelStorage).
|
||||
vec4 atSlot(highp sampler2D image, int slot) {
|
||||
int width = textureSize(image, 0).x;
|
||||
return texelFetch(image, ivec2(slot % width, slot / width), 0);
|
||||
return texelFetch(image, ivec2(slot & ${ROW - 1}, slot >> ${Math.log2(ROW)}), 0);
|
||||
}
|
||||
vec3 toDisplay(vec3 c) {
|
||||
return mix(12.92*c,1.055*pow(max(c,vec3(0.0)),vec3(1.0/2.4))-0.055,step(vec3(0.0031308),c));
|
||||
@@ -47,6 +65,45 @@ vec3 toDisplay(vec3 c) {
|
||||
vec3 toLinear(vec3 c) {
|
||||
return mix(c/12.92,pow(max((c+0.055)/1.055,vec3(0.0)),vec3(2.4)),step(vec3(0.04045),c));
|
||||
}
|
||||
// A corridor item over the colour, nearest metres from its line and along
|
||||
// metres from its start: its width, glow, pulse and dash, in LDR and
|
||||
// premultiplied, as Cesium writes ground polylines.
|
||||
vec3 blendCorridor(vec3 color, int item, float nearest, vec2 normal, float along, vec2 localDx, vec2 localDy) {
|
||||
int at = item * ${ITEM_TEXELS};
|
||||
vec4 shape = atSlot(tItems, at + 1);
|
||||
// Metres a pixel spans across the line (the screen gradient of the
|
||||
// distance to it): its width in pixels the same at any angle, as Cesium's.
|
||||
float pixel = max(length(vec2(dot(normal, localDx), dot(normal, localDy))), 1e-4);
|
||||
float halfWidth = shape.x > 0.0 ? shape.x * 0.5 * pixel : shape.y * 0.5;
|
||||
float cover = clamp((halfWidth - nearest) / pixel + 0.5, 0.0, 1.0);
|
||||
if (cover <= 0.0) return color;
|
||||
vec4 fill = atSlot(tItems, at);
|
||||
vec3 rgb = fill.rgb;
|
||||
float alpha = fill.a * cover;
|
||||
int look = int(shape.w + 0.5);
|
||||
if (look != 0) {
|
||||
vec4 glowPulse = atSlot(tItems, at + 2);
|
||||
vec4 pulseDash = atSlot(tItems, at + 3);
|
||||
vec4 dash = atSlot(tItems, at + 4);
|
||||
float s = clamp(along / max(shape.z, 1e-6), 0.0, 1.0);
|
||||
if ((look & ${LOOK.pulse}) != 0)
|
||||
alpha *= mix(glowPulse.w, pulseDash.x, 0.5 + 0.5 * sin(6.283185307179586 * uTime / glowPulse.z));
|
||||
if ((look & ${LOOK.glow}) != 0) {
|
||||
float glow = glowPulse.x / max(nearest / (2.0 * halfWidth), 1e-6) - glowPulse.x / 0.5;
|
||||
if (glowPulse.y <= 0.99999)
|
||||
glow *= min(1.0, glowPulse.y / (0.5 - s * 0.5) - glowPulse.y / 0.5);
|
||||
rgb = max(vec3(glow - 1.0) + rgb, rgb);
|
||||
alpha *= clamp(glow, 0.0, 1.0);
|
||||
}
|
||||
if ((look & ${LOOK.dash}) != 0) {
|
||||
float flow = fract(s * pulseDash.y - uTime * pulseDash.w);
|
||||
float on = 1.0 - smoothstep(pulseDash.z - ${float(DASH_EDGE)}, pulseDash.z + ${float(DASH_EDGE)}, flow);
|
||||
rgb *= 1.0 + dash.y * on;
|
||||
alpha *= max(on, dash.x);
|
||||
}
|
||||
}
|
||||
return min(color * (1.0 - alpha) + min(rgb * alpha, vec3(1.0)), vec3(1.0));
|
||||
}
|
||||
void mainImage(const in vec4 inputColor, const in vec2 uv, out vec4 outputColor) {
|
||||
outputColor = inputColor;
|
||||
float depth = unpackRGBAToDepth(texture2D(tAllDepth, uv));
|
||||
@@ -69,6 +126,11 @@ void mainImage(const in vec4 inputColor, const in vec2 uv, out vec4 outputColor)
|
||||
// The packed depth also holds forward meshes, which are not ground.
|
||||
if (depth < surface - 2e-7) return;
|
||||
vec3 color = toDisplay(inputColor.rgb);
|
||||
// The pixel's ground in world space, once: every corridor tile tests the
|
||||
// same value, so exactly one tile of a set holds it.
|
||||
bool placed = false;
|
||||
vec3 world = vec3(0.0);
|
||||
float sinLatitude = 0.0;
|
||||
int first = int(range.x);
|
||||
int candidates = int(range.y);
|
||||
for (int k = 0; k < candidates; k++) {
|
||||
@@ -84,6 +146,20 @@ void mainImage(const in vec4 inputColor, const in vec2 uv, out vec4 outputColor)
|
||||
vec4 fillColor = atSlot(tStyles, id * ${STYLE_TEXELS});
|
||||
vec4 lineColor = atSlot(tStyles, id * ${STYLE_TEXELS} + 1);
|
||||
vec4 shape = atSlot(tStyles, id * ${STYLE_TEXELS} + 2);
|
||||
int kind = int(shape.x + 0.5);
|
||||
if (kind == ${KIND.corridorTile}) {
|
||||
if (!placed) {
|
||||
world = (uViewToWorld * vec4(point, 1.0)).xyz;
|
||||
sinLatitude = world.z / length(world);
|
||||
placed = true;
|
||||
}
|
||||
// The tile's cell: east of its west meridian, west of its east one,
|
||||
// between its parallels (fillColor and lineColor hold them); an open
|
||||
// side takes everything beyond it.
|
||||
vec4 open = atSlot(tStyles, id * ${STYLE_TEXELS} + 5);
|
||||
if (dot(world.xy, fillColor.xy) + open.x < 0.0 || dot(world.xy, fillColor.zw) + open.y <= 0.0 ||
|
||||
sinLatitude < lineColor.x || sinLatitude >= lineColor.y) continue;
|
||||
}
|
||||
// Along the ray from the Earth's centre onto the item's plane.
|
||||
float scale = origin.w / (origin.w + height);
|
||||
vec2 local = vec2(dot(delta, east.xyz), dot(delta, north.xyz)) * scale;
|
||||
@@ -92,9 +168,72 @@ void mainImage(const in vec4 inputColor, const in vec2 uv, out vec4 outputColor)
|
||||
// Beyond the item's extent and its padding in pixels: not this item.
|
||||
float reach = east.w + north.w * (length(localDx) + length(localDy));
|
||||
if (dot(local, local) > reach * reach) continue;
|
||||
int kind = int(shape.x + 0.5);
|
||||
if (kind == ${KIND.corridorTile}) {
|
||||
// The finest level whose margin covers the set's thinnest reach in
|
||||
// the pixel's widest metres per pixel (a wider corridor's runs are
|
||||
// listed with a wider margin).
|
||||
vec4 place = atSlot(tStyles, id * ${STYLE_TEXELS} + 4);
|
||||
vec4 open = atSlot(tStyles, id * ${STYLE_TEXELS} + 5);
|
||||
float pixelMax = max(length(localDx + localDy), length(localDx - localDy));
|
||||
// A pixel past the bins (beyond an open side) takes the bin nearest
|
||||
// it, with a margin that reaches it too.
|
||||
float past = length(max(vec2(0.0), max(place.xy - local, local - open.zw)));
|
||||
float need = (lineColor.z * pixelMax + past) / (${float(MARGIN_RATIO)} * shape.y);
|
||||
int level = need <= 1.0 ? 0 : min(int(lineColor.w + 0.5), int(ceil(log2(need))));
|
||||
int columns = int(shape.z + 0.5);
|
||||
int rows = int(shape.w + 0.5);
|
||||
int dir = int(place.z + 0.5);
|
||||
for (int z = 0; z < level; z++) {
|
||||
dir += columns * rows;
|
||||
columns = (columns + 1) >> 1;
|
||||
rows = (rows + 1) >> 1;
|
||||
}
|
||||
float size = shape.y * exp2(float(level));
|
||||
ivec2 cell = clamp(ivec2(floor((local - place.xy) / size)), ivec2(0), ivec2(columns - 1, rows - 1));
|
||||
vec4 bin = atSlot(tBins, dir + cell.y * columns + cell.x);
|
||||
int runStart = int(span.w + 0.5) + int(bin.x + 0.5);
|
||||
int runCount = int(bin.y + 0.5);
|
||||
int segmentBase = int(span.z + 0.5);
|
||||
int itemBase = int(place.w + 0.5);
|
||||
int item = -1;
|
||||
float best = 1e30;
|
||||
vec2 bestNormal = vec2(1.0, 0.0);
|
||||
float bestAlong = 0.0;
|
||||
for (int r = 0; r < runCount; r++) {
|
||||
vec4 run = atSlot(tRuns, runStart + r);
|
||||
int runItem = itemBase + int(run.x + 0.5);
|
||||
if (runItem != item) {
|
||||
if (item >= 0)
|
||||
color = blendCorridor(color, item, best, bestNormal, bestAlong, localDx, localDy);
|
||||
item = runItem;
|
||||
best = 1e30;
|
||||
}
|
||||
float along = run.w;
|
||||
int start = segmentBase + int(run.y + 0.5);
|
||||
int count = int(run.z + 0.5);
|
||||
for (int s = 0; s < count; s++) {
|
||||
vec4 segment = atSlot(tSegments, start + s);
|
||||
vec2 a = segment.xy;
|
||||
vec2 ab = segment.zw - a;
|
||||
vec2 ap = local - a;
|
||||
float lengthSq = dot(ab, ab);
|
||||
float t = clamp(dot(ap, ab) / max(lengthSq, 1e-12), 0.0, 1.0);
|
||||
vec2 off = ap - ab * t;
|
||||
float d = length(off);
|
||||
float segmentLength = sqrt(lengthSq);
|
||||
if (d < best) {
|
||||
best = d;
|
||||
if (d > 0.0) bestNormal = off / d;
|
||||
bestAlong = along + t * segmentLength;
|
||||
}
|
||||
along += segmentLength;
|
||||
}
|
||||
}
|
||||
if (item >= 0)
|
||||
color = blendCorridor(color, item, best, bestNormal, bestAlong, localDx, localDy);
|
||||
continue;
|
||||
}
|
||||
float nearest = 1e30;
|
||||
int nearestSegment = 0;
|
||||
vec2 normal = vec2(1.0, 0.0);
|
||||
bool inside = false;
|
||||
if (kind == ${KIND.disc}) {
|
||||
@@ -111,21 +250,19 @@ void mainImage(const in vec4 inputColor, const in vec2 uv, out vec4 outputColor)
|
||||
bool binned = false;
|
||||
bool centreInside = false;
|
||||
vec2 centre = vec2(0.0);
|
||||
if (kind == ${KIND.area}) {
|
||||
vec4 grid = atSlot(tStyles, id * ${STYLE_TEXELS} + 4);
|
||||
if (grid.x > 0.5 &&
|
||||
(length(localDx) + length(localDy)) * (shape.y * 0.5 + 1.5) <= grid.z * 0.5) {
|
||||
vec2 origin = atSlot(tStyles, id * ${STYLE_TEXELS} + 5).xy;
|
||||
ivec2 cell = ivec2(floor((local - origin) / grid.z));
|
||||
// Off the grid: outside the area, beyond any edge's reach.
|
||||
if (cell.x < 0 || cell.y < 0 || cell.x >= int(grid.x) || cell.y >= int(grid.y)) continue;
|
||||
vec4 bin = atSlot(tBins, int(grid.w) + cell.y * int(grid.x) + cell.x);
|
||||
start += int(bin.x);
|
||||
count = int(bin.y);
|
||||
centreInside = bin.z > 0.5;
|
||||
centre = origin + (vec2(cell) + 0.5) * grid.z;
|
||||
binned = true;
|
||||
}
|
||||
vec4 grid = atSlot(tStyles, id * ${STYLE_TEXELS} + 4);
|
||||
if (grid.x > 0.5 &&
|
||||
(length(localDx) + length(localDy)) * (shape.y * 0.5 + 1.5) <= grid.z * 0.5) {
|
||||
vec2 origin = atSlot(tStyles, id * ${STYLE_TEXELS} + 5).xy;
|
||||
ivec2 cell = ivec2(floor((local - origin) / grid.z));
|
||||
// Off the grid: outside the area, beyond any edge's reach.
|
||||
if (cell.x < 0 || cell.y < 0 || cell.x >= int(grid.x) || cell.y >= int(grid.y)) continue;
|
||||
vec4 bin = atSlot(tBins, int(grid.w) + cell.y * int(grid.x) + cell.x);
|
||||
start += int(bin.x);
|
||||
count = int(bin.y);
|
||||
centreInside = bin.z > 0.5;
|
||||
centre = origin + (vec2(cell) + 0.5) * grid.z;
|
||||
binned = true;
|
||||
}
|
||||
for (int s = 0; s < count; s++) {
|
||||
vec4 segment = atSlot(tSegments, start + s);
|
||||
@@ -137,7 +274,6 @@ void mainImage(const in vec4 inputColor, const in vec2 uv, out vec4 outputColor)
|
||||
float d = length(off);
|
||||
if (d < nearest) {
|
||||
nearest = d;
|
||||
nearestSegment = s;
|
||||
if (d > 0.0) normal = off / d;
|
||||
}
|
||||
if (binned) {
|
||||
@@ -156,16 +292,6 @@ void mainImage(const in vec4 inputColor, const in vec2 uv, out vec4 outputColor)
|
||||
}
|
||||
// Metres one pixel spans across the boundary.
|
||||
float pixel = max(abs(dot(normal, localDx)) + abs(dot(normal, localDy)), 1e-4);
|
||||
if (kind == ${KIND.corridorPx} || kind == ${KIND.corridorM}) {
|
||||
// A chunk of a long corridor draws where its own segments are nearest.
|
||||
vec2 owned = atSlot(tStyles, id * ${STYLE_TEXELS} + 4).xy;
|
||||
if (float(nearestSegment) < owned.x - 0.5 ||
|
||||
float(nearestSegment) > owned.x + owned.y - 0.5) continue;
|
||||
float halfWidth = kind == ${KIND.corridorPx} ? shape.z * 0.5 * pixel : shape.w * 0.5;
|
||||
float cover = clamp((halfWidth - nearest) / pixel + 0.5, 0.0, 1.0);
|
||||
color = mix(color, fillColor.rgb, fillColor.a * cover);
|
||||
continue;
|
||||
}
|
||||
float inward = inside ? nearest : -nearest;
|
||||
if (fillColor.a > 0.0)
|
||||
color = mix(color, fillColor.rgb, fillColor.a * clamp(inward / pixel + 0.5, 0.0, 1.0));
|
||||
@@ -190,6 +316,8 @@ function texturesFor(state) {
|
||||
styles: dataTexture(state.styles),
|
||||
segments: dataTexture(state.segments),
|
||||
bins: dataTexture(state.bins),
|
||||
runs: dataTexture(state.runs),
|
||||
items: dataTexture(state.items),
|
||||
frames: dataTexture(state.frames),
|
||||
grid: dataTexture(state.grid),
|
||||
candidates: dataTexture(state.candidates),
|
||||
@@ -199,6 +327,8 @@ function texturesFor(state) {
|
||||
'styles',
|
||||
'segments',
|
||||
'bins',
|
||||
'runs',
|
||||
'items',
|
||||
'frames',
|
||||
'grid',
|
||||
'candidates',
|
||||
@@ -216,6 +346,8 @@ export const textureBytes = (state) =>
|
||||
state.styles,
|
||||
state.segments,
|
||||
state.bins,
|
||||
state.runs,
|
||||
state.items,
|
||||
state.frames,
|
||||
state.grid,
|
||||
state.candidates,
|
||||
@@ -260,10 +392,14 @@ class GroundEffectDesc extends withPassDisposal(withFrameUpdates(EffectDesc)) {
|
||||
['tStyles', new Uniform(null)],
|
||||
['tSegments', new Uniform(null)],
|
||||
['tBins', new Uniform(null)],
|
||||
['tRuns', new Uniform(null)],
|
||||
['tItems', new Uniform(null)],
|
||||
['tGrid', new Uniform(null)],
|
||||
['tCandidates', new Uniform(null)],
|
||||
['uInverseProjection', new Uniform(new Matrix4())],
|
||||
['uViewToWorld', new Uniform(new Matrix4())],
|
||||
['uLogDepthFC', new Uniform(1)],
|
||||
['uTime', new Uniform(0)],
|
||||
]),
|
||||
});
|
||||
return new NavaraEffect(camera, this.effect);
|
||||
@@ -300,11 +436,15 @@ class GroundEffectDesc extends withPassDisposal(withFrameUpdates(EffectDesc)) {
|
||||
u.get('tAllDepth').value = mrt.depthBuffer;
|
||||
u.get('tSurfaceDepth').value = this.ctx.getRenderTarget().depthTexture;
|
||||
u.get('uInverseProjection').value.copy(camera.projectionMatrixInverse);
|
||||
u.get('uViewToWorld').value.copy(camera.matrixWorld);
|
||||
u.get('uLogDepthFC').value = 2 / Math.log2(camera.far + 1);
|
||||
u.get('uTime').value = groundSeconds();
|
||||
u.get('tFrames').value = owner.textures.frames;
|
||||
u.get('tStyles').value = owner.textures.styles;
|
||||
u.get('tSegments').value = owner.textures.segments;
|
||||
u.get('tBins').value = owner.textures.bins;
|
||||
u.get('tRuns').value = owner.textures.runs;
|
||||
u.get('tItems').value = owner.textures.items;
|
||||
u.get('tGrid').value = owner.textures.grid;
|
||||
u.get('tCandidates').value = owner.textures.candidates;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user