Files
planet/frontend/public/earth/js/boundary-tile-decode.js
T
linkong e1cc27f13d
ci / backend (push) Canceled after 0s
ci / frontend (push) Canceled after 0s
ci / delivery (push) Canceled after 0s
release: bump version to 0.84.0
2026-12-04 07:07:19 +08:00

403 lines
14 KiB
JavaScript

// Pure JS (no Three.js import) MVT decoder -> indexed Float32Array / Uint32Array buffers.
// Coordinates use the exact same piecewise-linear SphereGeometry triangle grid as earth-surface.js.
const RAD_TO_DEG = 180 / Math.PI;
const DEG_TO_RAD = Math.PI / 180;
const _surfaceGridCache = new Map();
function getSurfaceGrid(radius, width, height) {
const key = `${radius}:${width}:${height}`;
let grid = _surfaceGridCache.get(key);
if (grid) return grid;
const vertices = new Float64Array((width + 1) * (height + 1) * 3);
for (let row = 0; row <= height; row += 1) {
const lat = 90 - (row / height) * 180;
const phi = (90 - lat) * DEG_TO_RAD;
const sinPhi = Math.sin(phi);
const cosPhi = Math.cos(phi);
for (let col = 0; col <= width; col += 1) {
const lon = (col / width) * 360 - 180;
const theta = (lon + 180) * DEG_TO_RAD;
const idx = (row * (width + 1) + col) * 3;
vertices[idx] = -(radius * sinPhi * Math.cos(theta));
vertices[idx + 1] = radius * cosPhi;
vertices[idx + 2] = radius * sinPhi * Math.sin(theta);
}
}
if (_surfaceGridCache.size >= 8) {
_surfaceGridCache.delete(_surfaceGridCache.keys().next().value);
}
_surfaceGridCache.set(key, vertices);
return vertices;
}
function projectSurfacePoint(lat, lon, grid, width, height, outPos, outIdx) {
const wrappedLon = (((lon + 180) % 360) + 360) % 360;
const u = (wrappedLon / 360) * width;
const v = Math.max(0, Math.min(height, ((90 - lat) / 180) * height));
const x = Math.min(width - 1, Math.floor(u));
const y = Math.min(height - 1, Math.floor(v));
const du = u - x;
const dv = v - y;
const b = (y * (width + 1) + x) * 3;
const d = b + (width + 2) * 3;
const middle = du >= dv ? b + 3 : b + (width + 1) * 3;
const w0 = 1 - Math.max(du, dv);
const w2 = Math.min(du, dv);
const w1 = Math.abs(du - dv);
outPos[outIdx] = grid[b] * w0 + grid[middle] * w1 + grid[d] * w2;
outPos[outIdx + 1] = grid[b + 1] * w0 + grid[middle + 1] * w1 + grid[d + 1] * w2;
outPos[outIdx + 2] = grid[b + 2] * w0 + grid[middle + 2] * w1 + grid[d + 2] * w2;
}
class IndexedLineBuilder {
constructor(initialVerts = 256, initialIndices = 512) {
this.positions = new Float32Array(initialVerts * 3);
this.indices = new Uint32Array(initialIndices);
this.vertexCount = 0;
this.indexCount = 0;
}
ensurePositions(extraVerts) {
const needed = (this.vertexCount + extraVerts) * 3;
if (needed <= this.positions.length) return;
let nextLen = this.positions.length || 768;
while (nextLen < needed) nextLen *= 2;
const next = new Float32Array(nextLen);
next.set(this.positions.subarray(0, this.vertexCount * 3));
this.positions = next;
}
ensureIndices(extraIndices) {
const needed = this.indexCount + extraIndices;
if (needed <= this.indices.length) return;
let nextLen = this.indices.length || 512;
while (nextLen < needed) nextLen *= 2;
const next = new Uint32Array(nextLen);
next.set(this.indices.subarray(0, this.indexCount));
this.indices = next;
}
appendTileRing(ring, tileX, tileY, tileZ, extent, grid, wSeg, hSeg) {
if (!ring || ring.length < 2) return;
const scale = 360 / (extent * Math.pow(2, tileZ));
const xOffset = extent * tileX;
const yOffset = extent * tileY;
const stepDeg = 180 / hSeg / 2;
const firstPt = ring[0];
let prevLon = (firstPt.x + xOffset) * scale - 180;
let prevLat =
(360 / Math.PI) *
Math.atan(Math.exp(((180 - (firstPt.y + yOffset) * scale) * Math.PI) / 180)) -
90;
this.ensurePositions(1);
let prevVertIdx = this.vertexCount;
projectSurfacePoint(prevLat, prevLon, grid, wSeg, hSeg, this.positions, prevVertIdx * 3);
this.vertexCount += 1;
for (let i = 1; i < ring.length; i += 1) {
const pt = ring[i];
const nextLon = (pt.x + xOffset) * scale - 180;
const nextLat =
(360 / Math.PI) *
Math.atan(Math.exp(((180 - (pt.y + yOffset) * scale) * Math.PI) / 180)) -
90;
const deltaLon = ((nextLon - prevLon + 540) % 360) - 180;
const subCount = Math.max(
1,
Math.ceil(Math.max(Math.abs(deltaLon), Math.abs(nextLat - prevLat)) / stepDeg),
);
this.ensurePositions(subCount);
this.ensureIndices(subCount * 2);
for (let step = 1; step <= subCount; step += 1) {
const t = step / subCount;
const interpLat = prevLat + (nextLat - prevLat) * t;
const interpLon = prevLon + deltaLon * t;
const vertIdx = this.vertexCount;
projectSurfacePoint(interpLat, interpLon, grid, wSeg, hSeg, this.positions, vertIdx * 3);
this.vertexCount += 1;
this.indices[this.indexCount++] = prevVertIdx;
this.indices[this.indexCount++] = vertIdx;
prevVertIdx = vertIdx;
}
prevLon = nextLon;
prevLat = nextLat;
}
}
finish() {
if (this.indexCount === 0) return null;
return {
positions: this.positions.slice(0, this.vertexCount * 3),
indices: this.indices.slice(0, this.indexCount),
};
}
}
class DashedLineBuilder {
constructor(initialPairs = 64) {
this.positions = new Float32Array(initialPairs * 6);
this.lineDistances = new Float32Array(initialPairs * 2);
this.vertexCount = 0;
}
ensureVertices(extra) {
const neededPos = (this.vertexCount + extra) * 3;
if (neededPos <= this.positions.length) return;
let nextVertCap = (this.positions.length / 3) || 128;
while (nextVertCap * 3 < neededPos) nextVertCap *= 2;
const nextPos = new Float32Array(nextVertCap * 3);
nextPos.set(this.positions.subarray(0, this.vertexCount * 3));
this.positions = nextPos;
const nextDist = new Float32Array(nextVertCap);
nextDist.set(this.lineDistances.subarray(0, this.vertexCount));
this.lineDistances = nextDist;
}
appendTileRing(ring, tileX, tileY, tileZ, extent, grid, wSeg, hSeg) {
if (!ring || ring.length < 2) return;
const scale = 360 / (extent * Math.pow(2, tileZ));
const xOffset = extent * tileX;
const yOffset = extent * tileY;
const stepDeg = 180 / hSeg / 2;
const firstPt = ring[0];
let prevLon = (firstPt.x + xOffset) * scale - 180;
let prevLat =
(360 / Math.PI) *
Math.atan(Math.exp(((180 - (firstPt.y + yOffset) * scale) * Math.PI) / 180)) -
90;
const scratch = new Float64Array(6);
projectSurfacePoint(prevLat, prevLon, grid, wSeg, hSeg, scratch, 0);
let cumDist = 0;
for (let i = 1; i < ring.length; i += 1) {
const pt = ring[i];
const nextLon = (pt.x + xOffset) * scale - 180;
const nextLat =
(360 / Math.PI) *
Math.atan(Math.exp(((180 - (pt.y + yOffset) * scale) * Math.PI) / 180)) -
90;
const deltaLon = ((nextLon - prevLon + 540) % 360) - 180;
const subCount = Math.max(
1,
Math.ceil(Math.max(Math.abs(deltaLon), Math.abs(nextLat - prevLat)) / stepDeg),
);
this.ensureVertices(subCount * 2);
for (let step = 1; step <= subCount; step += 1) {
const t = step / subCount;
const interpLat = prevLat + (nextLat - prevLat) * t;
const interpLon = prevLon + deltaLon * t;
projectSurfacePoint(interpLat, interpLon, grid, wSeg, hSeg, scratch, 3);
const dx = scratch[3] - scratch[0];
const dy = scratch[4] - scratch[1];
const dz = scratch[5] - scratch[2];
const segLen = Math.hypot(dx, dy, dz);
const base = this.vertexCount * 3;
this.positions[base] = scratch[0];
this.positions[base + 1] = scratch[1];
this.positions[base + 2] = scratch[2];
this.positions[base + 3] = scratch[3];
this.positions[base + 4] = scratch[4];
this.positions[base + 5] = scratch[5];
this.lineDistances[this.vertexCount] = cumDist;
cumDist += segLen;
this.lineDistances[this.vertexCount + 1] = cumDist;
this.vertexCount += 2;
scratch[0] = scratch[3];
scratch[1] = scratch[4];
scratch[2] = scratch[5];
}
prevLon = nextLon;
prevLat = nextLat;
}
}
finish() {
if (this.vertexCount === 0) return null;
return {
positions: this.positions.slice(0, this.vertexCount * 3),
lineDistances: this.lineDistances.slice(0, this.vertexCount),
};
}
}
export function decodeBoundaryTile({
buffer,
z,
x,
y,
VectorTile,
Pbf,
earthRadius = 100,
lineAltitudeOffset = 0.48,
claimLineAltitudeOffset = 0,
textureWidthSegments = 192,
textureHeightSegments = 96,
includeCoast = true,
includeBorders = true,
includeAdmin1 = true,
includeClaim = true,
coastLayers = ["coastline"],
borderLayers = ["boundary_admin0", "boundary_disputed_internal"],
admin1Layers = ["boundary_admin1"],
claimLayers = ["claim_line"],
}) {
if (!buffer || buffer.byteLength === 0) {
return { coast: null, border: null, admin1: null, claim: null };
}
const vectorTile = new VectorTile(new Pbf(new Uint8Array(buffer)));
const mainRadius = earthRadius + lineAltitudeOffset;
const claimRadius = mainRadius + claimLineAltitudeOffset;
const mainGrid = getSurfaceGrid(mainRadius, textureWidthSegments, textureHeightSegments);
const claimGrid =
claimRadius === mainRadius
? mainGrid
: getSurfaceGrid(claimRadius, textureWidthSegments, textureHeightSegments);
let coast = null;
if (includeCoast) {
const grouped = new Map();
for (const layerName of coastLayers) {
const layer = vectorTile.layers[layerName];
if (!layer) continue;
const extent = layer.extent || 4096;
for (let i = 0; i < layer.length; i += 1) {
const feat = layer.feature(i);
const geom = feat.loadGeometry();
if (!geom || !geom.length) continue;
const code = String(feat.properties?.ADM0_A3 || "").trim().toUpperCase();
let list = grouped.get(code);
if (!list) {
list = [];
grouped.set(code, list);
}
list.push({ extent, rings: geom });
}
}
if (grouped.size > 0) {
const builder = new IndexedLineBuilder(512, 1024);
const countryRuns = {};
const sortedCodes = [...grouped.keys()].sort();
for (const code of sortedCodes) {
const startIdx = builder.indexCount;
for (const item of grouped.get(code)) {
for (const ring of item.rings) {
builder.appendTileRing(ring, x, y, z, item.extent, mainGrid, textureWidthSegments, textureHeightSegments);
}
}
const count = builder.indexCount - startIdx;
if (code && count > 0) {
countryRuns[code] = new Uint32Array([startIdx, count]);
}
}
const built = builder.finish();
if (built) {
coast = { ...built, countryRuns };
}
}
}
let border = null;
if (includeBorders) {
const builder = new IndexedLineBuilder(256, 512);
const runsByCode = new Map();
const recordRun = (rawCode, start, count) => {
const code = String(rawCode || "").trim().toUpperCase();
if (!code || code === "-99" || count <= 0) return;
let list = runsByCode.get(code);
if (!list) {
list = [];
runsByCode.set(code, list);
}
list.push(start, count);
};
for (const layerName of borderLayers) {
const layer = vectorTile.layers[layerName];
if (!layer) continue;
const extent = layer.extent || 4096;
for (let i = 0; i < layer.length; i += 1) {
const feat = layer.feature(i);
const geom = feat.loadGeometry();
if (!geom || !geom.length) continue;
const startIdx = builder.indexCount;
for (const ring of geom) {
builder.appendTileRing(ring, x, y, z, extent, mainGrid, textureWidthSegments, textureHeightSegments);
}
const count = builder.indexCount - startIdx;
if (count > 0) {
const props = feat.properties || {};
recordRun(props.ADM0_L, startIdx, count);
if (props.ADM0_R && props.ADM0_R !== props.ADM0_L) {
recordRun(props.ADM0_R, startIdx, count);
}
if (!props.ADM0_L && !props.ADM0_R && props.ADM0_A3) {
recordRun(props.ADM0_A3, startIdx, count);
}
}
}
}
const built = builder.finish();
if (built) {
const countryRuns = {};
for (const [code, arr] of runsByCode.entries()) {
countryRuns[code] = new Uint32Array(arr);
}
border = { ...built, countryRuns };
}
}
let admin1 = null;
if (includeAdmin1) {
const builder = new IndexedLineBuilder(256, 512);
for (const layerName of admin1Layers) {
const layer = vectorTile.layers[layerName];
if (!layer) continue;
const extent = layer.extent || 4096;
for (let i = 0; i < layer.length; i += 1) {
const geom = layer.feature(i).loadGeometry();
if (!geom || !geom.length) continue;
for (const ring of geom) {
builder.appendTileRing(ring, x, y, z, extent, mainGrid, textureWidthSegments, textureHeightSegments);
}
}
}
admin1 = builder.finish();
}
let claim = null;
if (includeClaim) {
const builder = new DashedLineBuilder(32);
for (const layerName of claimLayers) {
const layer = vectorTile.layers[layerName];
if (!layer) continue;
const extent = layer.extent || 4096;
for (let i = 0; i < layer.length; i += 1) {
const geom = layer.feature(i).loadGeometry();
if (!geom || !geom.length) continue;
for (const ring of geom) {
builder.appendTileRing(ring, x, y, z, extent, claimGrid, textureWidthSegments, textureHeightSegments);
}
}
}
claim = builder.finish();
}
return { coast, border, admin1, claim };
}