Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
// SPDX-License-Identifier: MIT
// Copyright contributors to the kepler.gl project
import test from 'tape';
import sinon from 'sinon';
import {LayerManager, WebMercatorViewport} from '@deck.gl/core';
import {device} from '@deck.gl/test-utils';
import {KeplerGlLayers} from '@kepler.gl/layers';
import {
getEOBands,
findAssetWithName,
getUsableAssets,
getRasterStatisticsMinMax,
filterAvailablePresets,
getDataSourceParams,
computeDerivedValue,
computeRasterZonalStats,
formatRasterIdentifyRows,
lngLatToTileUV,
mercatorPixelSizeForBbox,
parseTitilerPointResponse,
polygonToBboxRectangle,
isDownloadableImageBlob,
rasterZonalStatsToSidecar,
sampleRasterTileAtLngLat
} from '@kepler.gl/layers';
import {RasterWebGL} from '@kepler.gl/deckgl-layers';
import {parseRasterMetadata} from '@kepler.gl/table';
import {testCreateCases} from 'test/helpers/layer-utils';
import {getModules, loadNpyArray} from '../../../src/layers/src/raster-tile/gpu-utils';
import * as rasterGpuUtils from '../../../src/layers/src/raster-tile/gpu-utils';
import * as rasterImages from '../../../src/layers/src/raster-tile/image';
import * as rasterExtract from '../../../src/layers/src/raster-tile/raster-tile-extract';
const {RasterTileLayer} = KeplerGlLayers;
// Mock data for raster tests
const MOCK_STAC_METADATA = {
type: 'Feature',
stac_version: '1.0.0',
stac_extensions: ['https://stac-extensions.github.io/eo/v1.0.0/schema.json'],
assets: {
red: {
href: 'https://example.com/red.tif',
type: 'image/tiff',
'eo:bands': [{name: 'red', common_name: 'red'}]
},
green: {
href: 'https://example.com/green.tif',
type: 'image/tiff',
'eo:bands': [{name: 'green', common_name: 'green'}]
},
blue: {
href: 'https://example.com/blue.tif',
type: 'image/tiff',
'eo:bands': [{name: 'blue', common_name: 'blue'}]
}
},
bounds: [-122.5, 37.5, -122.0, 38.0],
properties: {
datetime: '2023-01-01T00:00:00Z'
}
};
const MOCK_PMTILES_METADATA = {
metadataUrl: 'https://example.com/raster.pmtiles',
pmtilesType: 'raster',
minZoom: 0,
maxZoom: 18,
bounds: [-122.5, 37.5, -122.0, 38.0]
};
const MOCK_STAC_DATASET = {
type: 'raster-tile',
metadata: MOCK_STAC_METADATA,
label: 'Test STAC Dataset'
};
const MOCK_PMTILES_DATASET = {
type: 'raster-tile',
metadata: MOCK_PMTILES_METADATA,
label: 'Test PMTiles Dataset'
};
// Shared render options for tests
const createRenderOpts = (dataset, mapState = {dragRotate: false, bearing: 0, pitch: 0}) => ({
data: {
dataset,
tileSource: dataset.metadata.pmtilesType ? {getTileData: () => Promise.resolve(null)} : null
},
mapState,
interactionConfig: {tooltip: {enabled: true}}
});
test('#RasterTileLayer -> tile requests carry the abort signal', async t => {
// deck.gl aborts a tile that scrolls out of view by firing the AbortSignal it
// puts in the request. The signal has to reach the fetch, or the browser keeps
// downloading tiles nobody will draw and they queue ahead of the ones in view.
const controller = new AbortController();
const requests = [];
const originalFetch = globalThis.fetch;
globalThis.fetch = (url, init) => {
requests.push(init);
return Promise.resolve({
ok: true,
status: 200,
url: String(url),
headers: new Map(),
arrayBuffer: async () => new ArrayBuffer(8)
});
};
try {
await loadNpyArray(
{
url: 'https://example.com/tile.npy',
rasterServerUrl: 'https://example.com',
options: {signal: controller.signal},
rasterServerMaxRetries: 0
},
true
);
} finally {
globalThis.fetch = originalFetch;
}
t.equal(requests.length, 1, 'should issue one tile request');
t.equal(
requests[0]?.signal,
controller.signal,
'the tile request should carry the abort signal deck.gl provided'
);
t.end();
});
test('#RasterTileLayer -> required raster assets load together', async t => {
const bands = [10, 20, 30].map(value => ({data: new Uint8Array([value]), width: 1, height: 1}));
const mask = {data: new Uint8Array([255]), width: 1, height: 1};
const requests = ['red', 'green', 'blue'].map((url, index) => ({
url,
rasterServerUrl: '',
options: {},
useMask: index === 0
}));
let results = [[bands[0], mask], [bands[1]], [bands[2]]];
const loadStub = sinon.stub(rasterGpuUtils, 'loadNpyArray').callsFake(async request => {
const result = results[requests.indexOf(request)];
return result && [...result];
});
const requestsStub = sinon.stub(rasterImages, 'getSTACImageRequests').resolves(requests);
const layer = new RasterTileLayer({id: 'required-assets', dataId: 'stac-data'});
const tileProps = {
stac: MOCK_STAC_METADATA,
index: {x: 0, y: 0, z: 0},
bbox: {west: -180, south: -85, east: 180, north: 85},
shouldLoadTerrain: false,
colormapId: ''
};
try {
const complete = await rasterImages.loadSTACImageData(requests);
t.deepEqual(complete.imageBands, bands, 'complete RGB keeps every channel in request order');
t.equal(complete.imageMask, mask, 'only the first asset supplies the validity mask');
const completeTile = await layer.getTileData(tileProps);
t.deepEqual(completeTile.images.imageBands, bands, 'complete RGB yields a usable tile');
for (const failedIndex of [0, 1, 2]) {
for (const missing of [null, []]) {
results = [[bands[0], mask], [bands[1]], [bands[2]]];
results[failedIndex] = missing;
const label = `${requests[failedIndex].url} returns ${
missing === null ? 'null' : 'no bands'
}`;
const incomplete = await rasterImages.loadSTACImageData(requests);
t.deepEqual(incomplete, {imageBands: null}, `${label}: no partial channels or mask`);
t.equal(await layer.getTileData(tileProps), null, `${label}: no successful tile to cache`);
}
}
results = [[mask], [bands[1]], [bands[2]]];
t.deepEqual(
await rasterImages.loadSTACImageData(requests),
{imageBands: null},
'a first asset containing only a mask is also incomplete'
);
results = [[bands[0], mask], [bands[1]], [bands[2]]];
t.deepEqual(
(await layer.getTileData(tileProps)).images.imageBands,
bands,
'a later complete load recovers all channels'
);
t.deepEqual(
await rasterImages.loadSTACImageData(requests.slice(0, 2)),
{imageBands: bands.slice(0, 2), imageMask: mask},
'two-asset presets retain their bands and mask'
);
results = [[bands[0], bands[1], bands[2], mask]];
requests[0].responseRequiredBandIndices = [2, 0];
t.deepEqual(
await rasterImages.loadSTACImageData([requests[0]]),
{imageBands: [bands[2], bands[0]], imageMask: mask},
'single-asset band selection and mask handling are unchanged'
);
results = [null];
requestsStub.resolves([requests[0]]);
t.deepEqual(
await rasterImages.loadSTACImageData([requests[0]]),
{imageBands: null},
'a failed single asset keeps the same failure sentinel'
);
t.equal(await layer.getTileData(tileProps), null, 'a failed single asset yields no tile');
requestsStub.resolves(requests);
for (const error of [
new Error('asset failed'),
Object.assign(new Error('aborted'), {name: 'AbortError'})
]) {
loadStub.callsFake(() => Promise.reject(error));
try {
await rasterImages.loadSTACImageData(requests);
t.fail('a rejected asset must reject the image load');
} catch (caught) {
t.equal(caught, error, 'image loading preserves the original rejection');
}
try {
const tile = await layer.getTileData(tileProps);
t.equal(error.name, 'AbortError', 'only cancellation resolves instead of throwing');
t.equal(tile, null, 'cancellation yields no tile');
} catch (caught) {
t.notEqual(error.name, 'AbortError', 'tile cancellation must resolve without throwing');
t.equal(caught, error, 'tile loading preserves a genuine error');
}
}
} finally {
loadStub.restore();
requestsStub.restore();
}
t.end();
});
test('#RasterTileLayer -> constructor and basic properties', t => {
const TEST_CASES = {
CREATE: [
{
props: {
dataId: 'raster-test-data',
isVisible: true,
label: 'test raster layer'
},
test: layer => {
t.equal(layer.config.dataId, 'raster-test-data', 'dataId should be correct');
t.equal(layer.type, 'rasterTile', 'type should be rasterTile');
t.equal(layer.isAggregated, false, 'should not be aggregated');
t.equal(layer.config.label, 'test raster layer', 'label should be correct');
t.equal(layer.config.isVisible, true, 'should be visible');
t.equal(layer.config.visConfig.opacity, 1, 'should have default opacity');
t.equal(
layer.config.visConfig.allowHover,
false,
'should disable hover tooltips by default'
);
t.equal(
layer.config.visConfig.enableTerrain,
true,
'should have terrain enabled by default'
);
t.equal(
layer.config.visConfig.enableTerrainTopView,
false,
'should have terrain top view disabled'
);
t.equal(layer.requireData, true, 'should require data');
t.deepEqual(
layer.supportedDatasetTypes,
['raster-tile'],
'should support raster-tile dataset type'
);
t.equal(layer.name, 'Raster Tile', 'should have correct layer name');
t.ok(typeof layer.layerIcon === 'function', 'should have layerIcon function');
t.ok(layer.isValidToSave(), 'should be valid to save');
}
}
]
};
testCreateCases(t, RasterTileLayer, TEST_CASES.CREATE);
t.end();
});
test('#RasterTileLayer -> data formatting and rendering', t => {
const stacLayer = new RasterTileLayer({id: 'stac-layer', dataId: 'stac-data'});
const pmtilesLayer = new RasterTileLayer({id: 'pmtiles-layer', dataId: 'pmtiles-data'});
// Test STAC data formatting
const stacLayerData = stacLayer.formatLayerData({'stac-data': MOCK_STAC_DATASET});
t.ok(stacLayerData, 'should return STAC layer data');
t.equal(stacLayerData.dataset, MOCK_STAC_DATASET, 'should have correct STAC dataset');
t.equal(stacLayerData.tileSource, null, 'should have null tileSource for STAC');
// Test PMTiles data formatting
const pmtilesLayerData = pmtilesLayer.formatLayerData({'pmtiles-data': MOCK_PMTILES_DATASET});
t.ok(pmtilesLayerData, 'should return PMTiles layer data');
t.equal(pmtilesLayerData.dataset, MOCK_PMTILES_DATASET, 'should have correct PMTiles dataset');
t.ok(pmtilesLayerData.tileSource, 'should create tileSource for PMTiles');
// Test rendering
const stacLayers = stacLayer.renderLayer(createRenderOpts(MOCK_STAC_DATASET));
const pmtilesLayers = pmtilesLayer.renderLayer(createRenderOpts(MOCK_PMTILES_DATASET));
t.ok(Array.isArray(stacLayers), 'should return array for STAC');
t.ok(Array.isArray(pmtilesLayers), 'should return array for PMTiles');
t.equal(pmtilesLayers.length, 1, 'should render one deck layer for PMTiles');
t.end();
});
test('#RasterTileLayer -> configuration and visual settings', t => {
const layer = new RasterTileLayer({id: 'test-layer', dataId: 'stac-data'});
// Test layer config updates
layer.updateLayerConfig({isVisible: false, label: 'Updated Layer'});
t.equal(layer.config.isVisible, false, 'should update visibility');
t.equal(layer.config.label, 'Updated Layer', 'should update label');
// Test visual config updates
layer.updateLayerVisConfig({
opacity: 0.7,
enableTerrain: false,
enableTerrainTopView: true,
allowHover: true
});
t.equal(layer.config.visConfig.opacity, 0.7, 'should update opacity');
t.equal(layer.config.visConfig.enableTerrain, false, 'should update terrain');
t.equal(layer.config.visConfig.enableTerrainTopView, true, 'should update terrain top view');
t.equal(layer.config.visConfig.allowHover, true, 'should update allowHover');
// Test shouldRenderLayer
t.notOk(layer.shouldRenderLayer(), 'should not render when not visible');
layer.updateLayerConfig({isVisible: true});
t.ok(layer.shouldRenderLayer(), 'should render when visible');
t.end();
});
test('#RasterTileLayer -> metadata handling', t => {
const layer = new RasterTileLayer({id: 'test-layer', dataId: 'stac-data'});
// Test with non-raster dataset (should not throw)
t.doesNotThrow(() => {
layer.updateLayerMeta({type: 'csv'});
}, 'should handle non-raster dataset');
// Test with STAC and PMTiles datasets (should not throw)
t.doesNotThrow(() => {
layer.updateLayerMeta(MOCK_STAC_DATASET);
layer.updateLayerMeta(MOCK_PMTILES_DATASET);
}, 'should handle STAC and PMTiles datasets');
t.end();
});
test('#RasterTileLayer -> pixel value tracking', t => {
const layer = new RasterTileLayer({id: 'test-layer', dataId: 'stac-data'});
// Test initial state
t.equal(layer.minViewportPixelValue, Infinity, 'should have Infinity as initial min');
t.equal(layer.maxViewportPixelValue, -Infinity, 'should have -Infinity as initial max');
// Test with valid tiles
const mockTiles = [
{data: {minPixelValue: 25, maxPixelValue: 100}},
{data: {minPixelValue: 10, maxPixelValue: 150}}
];
layer.updateMinMaxPixelValue(mockTiles);
t.equal(layer.minViewportPixelValue, 10, 'should set correct min pixel value');
t.equal(layer.maxViewportPixelValue, 150, 'should set correct max pixel value');
// Test with empty tiles
layer.updateMinMaxPixelValue([]);
t.equal(layer.minViewportPixelValue, Infinity, 'should reset to Infinity for empty tiles');
t.equal(layer.maxViewportPixelValue, -Infinity, 'should reset to -Infinity for empty tiles');
// Test with null data
layer.updateMinMaxPixelValue([
{data: null},
{data: {minPixelValue: 30, maxPixelValue: 120}},
null
]);
t.equal(layer.minViewportPixelValue, 30, 'should handle null data gracefully');
t.equal(layer.maxViewportPixelValue, 120, 'should handle null data gracefully');
t.end();
});
test('#RasterTileLayer -> dynamic coloring keeps finite zero endpoints', t => {
const layer = new RasterTileLayer({id: 'dynamic-raster', dataId: 'stac-data'});
layer.updateLayerVisConfig({dynamicColor: true, preset: 'singleBand', singleBandName: 'red'});
const dataset = {
...MOCK_STAC_DATASET,
metadata: {
...MOCK_STAC_METADATA,
assets: Object.fromEntries(
Object.entries(MOCK_STAC_METADATA.assets).map(([id, asset]) => [
id,
{
...asset,
'raster:bands': [{data_type: 'float32', statistics: {minimum: -100, maximum: 100}}]
}
])
)
}
};
const tile = (minPixelValue, maxPixelValue) => ({data: {minPixelValue, maxPixelValue}});
const cases = [
{name: 'zero minimum', tiles: [tile(0, 10), tile(5, 20)], range: [0, 20]},
{name: 'zero maximum', tiles: [tile(-10, 0), tile(-5, -2)], range: [-10, 0]},
{name: 'negative endpoints', tiles: [tile(-20, -10), tile(-15, -5)], range: [-20, -5]},
{name: 'all-zero tiles', tiles: [tile(0, 0), tile(0, 0)], range: [0, 0]},
{name: 'normal nonzero endpoints', tiles: [tile(5, 10), tile(8, 20)], range: [5, 20]},
{
name: 'missing and nonfinite endpoints',
tiles: [
null,
{},
{data: null},
{data: {}},
tile(null, undefined),
tile(NaN, NaN),
tile(-Infinity, Infinity),
tile(0, 10)
],
range: [0, 10]
},
{
name: 'independent valid endpoints',
tiles: [tile(0, null), tile(undefined, 0)],
range: [0, 0]
},
{name: 'zero tile removed from viewport', tiles: [tile(5, 20)], range: [5, 20]},
{name: 'zero tile enters viewport again', tiles: [tile(0, 10), tile(5, 20)], range: [0, 20]},
{name: 'all tiles removed', tiles: [], range: [Infinity, -Infinity]},
{
name: 'only invalid statistics',
tiles: [null, {}, {data: {}}, tile(NaN, Infinity), tile(-Infinity, null)],
range: [Infinity, -Infinity]
}
];
for (const {name, tiles, range} of cases) {
layer.onViewportLoad(tiles);
t.deepEqual(
[layer.minViewportPixelValue, layer.maxViewportPixelValue],
range,
`${name}: tracks the current viewport range`
);
const [rendered] = layer.renderLayer(createRenderOpts(dataset));
t.ok(rendered, `${name}: creates the raster TileLayer`);
t.deepEqual(
[rendered?.props.minPixelValue, rendered?.props.maxPixelValue],
range,
`${name}: forwards the range for dynamic rendering`
);
}
t.end();
});
test('#RasterTileLayer -> findDefaultLayerProps', t => {
// Test with raster dataset
const result = RasterTileLayer.findDefaultLayerProps(MOCK_STAC_DATASET);
t.ok(result.props, 'should return props object');
t.equal(result.props.length, 1, 'should return one layer prop');
t.equal(result.props[0].label, 'Test STAC Dataset', 'should use dataset label');
t.equal(result.props[0].isVisible, true, 'should be visible by default');
// Test with non-raster dataset
const nonRasterResult = RasterTileLayer.findDefaultLayerProps({type: 'csv'});
t.deepEqual(nonRasterResult.props, [], 'should return empty props for non-raster dataset');
t.end();
});
test('#RasterTileLayer -> edge cases and error handling', t => {
const layer = new RasterTileLayer({id: 'test-layer', dataId: 'stac-data'});
// Test formatLayerData with missing dataset
t.throws(() => {
layer.formatLayerData({});
}, 'should throw error when dataset missing');
// Test layer without dataId
const layerWithoutDataId = new RasterTileLayer({id: 'test-layer'});
layerWithoutDataId.config.dataId = undefined;
const layerData = layerWithoutDataId.formatLayerData({});
t.deepEqual(layerData, {}, 'should return empty object when no dataId');
// Test rendering with invalid/missing data
const invalidLayers = layer.renderLayer(createRenderOpts({metadata: {type: 'Feature'}}));
t.deepEqual(invalidLayers, [], 'should return empty array for invalid STAC data');
const noDataLayers = layer.renderLayer({...createRenderOpts(MOCK_STAC_DATASET), data: null});
t.deepEqual(noDataLayers, [], 'should return empty array when no data');
// Test malformed metadata (should not throw)
t.doesNotThrow(() => {
layer.updateLayerMeta({type: 'raster-tile', metadata: {type: 'Feature'}});
layer.updateLayerMeta({type: 'raster-tile', metadata: {pmtilesType: 'raster'}});
}, 'should handle malformed metadata gracefully');
t.end();
});
test('#RasterTileLayer -> data type variations', t => {
const layer = new RasterTileLayer({id: 'test-layer', dataId: 'stac-data'});
// Test multi-asset STAC
const multiAssetStac = {
type: 'raster-tile',
metadata: {
...MOCK_STAC_METADATA,
assets: {
...MOCK_STAC_METADATA.assets,
nir: {
href: 'https://example.com/nir.tif',
type: 'image/tiff',
'eo:bands': [{name: 'nir', common_name: 'nir'}]
}
}
}
};
const multiAssetData = layer.formatLayerData({'stac-data': multiAssetStac});
t.ok(multiAssetData, 'should handle multi-asset STAC data');
// Test single asset STAC
const singleAssetStac = {
type: 'raster-tile',
metadata: {
type: 'Feature',
stac_version: '1.0.0',
assets: {
visual: {href: 'https://example.com/visual.tif', type: 'image/tiff'}
},
bounds: [-122.5, 37.5, -122.0, 38.0]
}
};
const singleAssetData = layer.formatLayerData({'stac-data': singleAssetStac});
t.ok(singleAssetData, 'should handle single-asset STAC data');
t.end();
});
test('#RasterTileLayer -> layer serialization', t => {
const layer = new RasterTileLayer({
id: 'test-layer',
dataId: 'stac-data',
label: 'Test Raster Layer'
});
// Configure layer
layer.updateLayerVisConfig({
opacity: 0.8,
enableTerrain: false,
colorRange: {
colors: ['#FF0000', '#00FF00'],
colorLegends: {water: [0, 0, 255]}
}
});
// Test layer properties
const config = layer.config;
t.ok(layer.id, 'should have id on layer');
t.ok(config.dataId, 'should have dataId in config');
t.ok(config.label, 'should have label in config');
t.equal(config.visConfig.opacity, 0.8, 'should preserve opacity');
t.equal(config.visConfig.enableTerrain, false, 'should preserve terrain setting');
t.ok(layer.isValidToSave(), 'should be valid to save');
t.end();
});
// ---- STAC 1.1.0 Core Bands Support Tests ----
const MOCK_STAC_110_METADATA = {
type: 'Feature',
stac_version: '1.1.0',
stac_extensions: ['https://stac-extensions.github.io/projection/v1.1.0/schema.json'],
id: 'test-cog',
geometry: {type: 'Point', coordinates: [0, 0]},
bbox: [-122.5, 37.5, -122.0, 38.0],
links: [],
properties: {datetime: '2023-01-01T00:00:00Z'},
assets: {
data: {
href: 'https://example.com/cog.tif',
type: 'image/tiff; application=geotiff',
bands: [
{
name: 'b1',
'eo:common_name': 'red',
data_type: 'uint8',
statistics: {minimum: 0, maximum: 255, mean: 128}
},
{
name: 'b2',
'eo:common_name': 'green',
data_type: 'uint8',
statistics: {minimum: 0, maximum: 255, mean: 120}
},
{
name: 'b3',
'eo:common_name': 'blue',
data_type: 'uint8',
statistics: {minimum: 0, maximum: 255, mean: 110}
}
]
}
}
};
const MOCK_STAC_110_LEGACY_MIX = {
type: 'Feature',
stac_version: '1.1.0',
stac_extensions: [
'https://stac-extensions.github.io/eo/v1.0.0/schema.json',
'https://stac-extensions.github.io/raster/v1.0.0/schema.json'
],
id: 'test-mix',
geometry: {type: 'Point', coordinates: [0, 0]},
bbox: [-122.5, 37.5, -122.0, 38.0],
links: [],
properties: {datetime: '2023-01-01T00:00:00Z'},
assets: {
visual: {
href: 'https://example.com/visual.tif',
type: 'image/tiff; application=geotiff',
'eo:bands': [
{name: 'red', common_name: 'red'},
{name: 'green', common_name: 'green'},
{name: 'blue', common_name: 'blue'}
],
'raster:bands': [
{data_type: 'uint8', statistics: {minimum: 0, maximum: 255}},
{data_type: 'uint8', statistics: {minimum: 0, maximum: 255}},
{data_type: 'uint8', statistics: {minimum: 0, maximum: 255}}
]
},
nir_core: {
href: 'https://example.com/nir.tif',
type: 'image/tiff; application=geotiff',
bands: [
{
name: 'nir',
'eo:common_name': 'nir',
data_type: 'uint16',
statistics: {minimum: 0, maximum: 10000}
}
]
}
}
};
test('#STAC 1.1.0 -> parseRasterMetadata accepts core bands', t => {
const result = parseRasterMetadata(MOCK_STAC_110_METADATA, {allowCollections: false});
t.ok(result, 'should return a result');
t.notOk(result instanceof Error, 'should not return an error for STAC 1.1.0 with core bands');
t.equal(result.stac_version, '1.1.0', 'should preserve stac_version');
t.end();
});
test('#STAC 1.1.0 -> parseRasterMetadata rejects items without bands', t => {
const noBands = {
type: 'Feature',
stac_version: '1.1.0',
stac_extensions: [],
id: 'no-bands',
geometry: {type: 'Point', coordinates: [0, 0]},
bbox: [-1, -1, 1, 1],
links: [],
properties: {datetime: '2023-01-01T00:00:00Z'},
assets: {
data: {
href: 'https://example.com/cog.tif',
type: 'image/tiff'
}
}
};
const result = parseRasterMetadata(noBands, {allowCollections: false});
t.ok(
result instanceof Error,
'should return an error for STAC 1.1.0 without core bands or extensions'
);
t.end();
});
test('#STAC 1.1.0 -> parseRasterMetadata still accepts legacy 1.0.0', t => {
const legacy = {
type: 'Feature',
stac_version: '1.0.0',
stac_extensions: [
'https://stac-extensions.github.io/eo/v1.0.0/schema.json',
'https://stac-extensions.github.io/raster/v1.0.0/schema.json'
],
id: 'legacy',
geometry: {type: 'Point', coordinates: [0, 0]},
bbox: [-1, -1, 1, 1],
links: [],
properties: {datetime: '2023-01-01T00:00:00Z'},
assets: {
red: {
href: 'https://example.com/red.tif',
'eo:bands': [{name: 'red', common_name: 'red'}],
'raster:bands': [{data_type: 'uint8'}]
}
}
};
const result = parseRasterMetadata(legacy, {allowCollections: false});
t.ok(result, 'should return a result');
t.notOk(result instanceof Error, 'should not return an error for legacy STAC 1.0.0');
t.end();
});
test('#STAC 1.1.0 -> getUsableAssets with core bands', t => {
const usable = getUsableAssets(MOCK_STAC_110_METADATA);
t.ok(usable.data, 'should include asset with core bands containing data_type');
t.equal(Object.keys(usable).length, 1, 'should return one usable asset');
t.end();
});
test('#STAC 1.1.0 -> getUsableAssets mixed legacy + core', t => {
const usable = getUsableAssets(MOCK_STAC_110_LEGACY_MIX);
t.ok(usable.visual, 'should include legacy asset with raster:bands');
t.ok(usable.nir_core, 'should include core bands asset');
t.equal(Object.keys(usable).length, 2, 'should return two usable assets');
t.end();
});
test('#STAC 1.1.0 -> getEOBands normalizes core bands', t => {
const bands = getEOBands(MOCK_STAC_110_METADATA);
t.ok(bands, 'should return bands');
t.equal(bands.length, 3, 'should return 3 bands');
t.equal(bands[0].common_name, 'red', 'should map eo:common_name to common_name for red');
t.equal(bands[1].common_name, 'green', 'should map eo:common_name to common_name for green');
t.equal(bands[2].common_name, 'blue', 'should map eo:common_name to common_name for blue');
t.equal(bands[0].name, 'b1', 'should preserve name');
t.end();
});
test('#STAC 1.1.0 -> getEOBands mixed legacy + core', t => {
const bands = getEOBands(MOCK_STAC_110_LEGACY_MIX);
t.ok(bands, 'should return bands');
t.equal(bands.length, 4, 'should return 4 bands (3 legacy + 1 core)');
const nir = bands.find(b => b.common_name === 'nir');
t.ok(nir, 'should include the NIR band from core bands');
t.end();
});
test('#STAC 1.1.0 -> findAssetWithName with core bands', t => {
const usable = getUsableAssets(MOCK_STAC_110_METADATA);
const result = findAssetWithName(usable, 'red', 'common_name');
t.ok(result, 'should find asset with common_name=red');
t.equal(result[0], 'data', 'should return asset name "data"');
t.equal(result[1], 0, 'should return band index 0');
const greenResult = findAssetWithName(usable, 'green', 'common_name');
t.ok(greenResult, 'should find asset with common_name=green');
t.equal(greenResult[1], 1, 'should return band index 1');
const nameResult = findAssetWithName(usable, 'b1', 'name');
t.ok(nameResult, 'should find asset by name=b1');
t.equal(nameResult[0], 'data', 'should return asset name "data"');
t.equal(nameResult[1], 0, 'should return band index 0');
const noResult = findAssetWithName(usable, 'nir', 'common_name');
t.notOk(noResult, 'should return null for missing band');
t.end();
});
test('#STAC 1.1.0 -> getRasterStatisticsMinMax with core bands', t => {
const [min, max] = getRasterStatisticsMinMax(MOCK_STAC_110_METADATA, 'singleBand', {
assetId: 'data'
});
t.equal(min, 0, 'should get minimum from core bands statistics');
t.equal(max, 255, 'should get maximum from core bands statistics');
t.end();
});
test('#STAC 1.1.0 -> filterAvailablePresets with core bands', t => {
const presetData = {
trueColor: {
id: 'trueColor',
commonNames: ['red', 'green', 'blue'],
bandCombination: 'rgb'
},
ndvi: {
id: 'ndvi',
commonNames: ['red', 'nir'],
bandCombination: 'normalizedDifference'
},
singleBand: {
id: 'singleBand',
commonNames: null,
bandCombination: 'single'
}
};
const available = filterAvailablePresets(MOCK_STAC_110_METADATA, presetData);
t.ok(available, 'should return available presets');
t.ok(available.includes('trueColor'), 'should include trueColor preset');
t.ok(available.includes('singleBand'), 'should include singleBand preset');
t.notOk(available.includes('ndvi'), 'should not include ndvi (missing nir)');
t.end();
});
test('#STAC 1.1.0 -> RasterTileLayer with core bands metadata handling', t => {
const layer = new RasterTileLayer({id: 'test-110', dataId: 'stac-110'});
const dataset = {
type: 'raster-tile',
metadata: MOCK_STAC_110_METADATA,
label: 'STAC 1.1.0 COG'
};
t.doesNotThrow(() => {
layer.updateLayerMeta(dataset);
}, 'should handle STAC 1.1.0 metadata without throwing');
const layerData = layer.formatLayerData({'stac-110': dataset});
t.ok(layerData, 'should return layer data for STAC 1.1.0');
t.equal(layerData.dataset, dataset, 'should have correct dataset');
t.end();
});
// ---- Description fallback tests ----
const MOCK_STAC_DESCRIPTION_FALLBACK = {
type: 'Feature',
stac_version: '1.0.0',
stac_extensions: [
'https://stac-extensions.github.io/eo/v1.0.0/schema.json',
'https://stac-extensions.github.io/raster/v1.0.0/schema.json'
],
id: 'description-fallback-test',
geometry: {type: 'Point', coordinates: [0, 0]},
bbox: [-1, -1, 1, 1],
links: [],
properties: {datetime: '2023-01-01T00:00:00Z'},
assets: {
data: {
href: 'https://example.com/cog.tif',
type: 'image/tiff; application=geotiff',
'eo:bands': [
{name: 'b1', description: 'red'},
{name: 'b2', description: 'green'},
{name: 'b3', description: 'blue'}
],
'raster:bands': [
{data_type: 'uint8', statistics: {minimum: 0, maximum: 255}},
{data_type: 'uint8', statistics: {minimum: 0, maximum: 255}},
{data_type: 'uint8', statistics: {minimum: 0, maximum: 255}}
]
}
}
};
const MOCK_STAC_110_DESCRIPTION_FALLBACK = {
type: 'Feature',
stac_version: '1.1.0',
stac_extensions: [],
id: 'description-fallback-110',
geometry: {type: 'Point', coordinates: [0, 0]},
bbox: [-1, -1, 1, 1],
links: [],
properties: {datetime: '2023-01-01T00:00:00Z'},
assets: {
data: {
href: 'https://example.com/cog.tif',
type: 'image/tiff; application=geotiff',
bands: [
{name: 'b1', description: 'red', data_type: 'uint8'},
{name: 'b2', description: 'green', data_type: 'uint8'},
{name: 'b3', description: 'blue', data_type: 'uint8'}
]
}
}
};
test('#Description fallback -> getEOBands infers common_name from description (legacy eo:bands)', t => {
const bands = getEOBands(MOCK_STAC_DESCRIPTION_FALLBACK);
t.ok(bands, 'should return bands');
t.equal(bands.length, 3, 'should return 3 bands');
t.equal(bands[0].common_name, 'red', 'should infer red from description');
t.equal(bands[1].common_name, 'green', 'should infer green from description');
t.equal(bands[2].common_name, 'blue', 'should infer blue from description');
t.end();
});
test('#Description fallback -> getEOBands infers common_name from description (core bands)', t => {
const bands = getEOBands(MOCK_STAC_110_DESCRIPTION_FALLBACK);
t.ok(bands, 'should return bands');
t.equal(bands.length, 3, 'should return 3 bands');
t.equal(bands[0].common_name, 'red', 'should infer red from core band description');
t.equal(bands[1].common_name, 'green', 'should infer green from core band description');
t.equal(bands[2].common_name, 'blue', 'should infer blue from core band description');
t.end();
});
test('#Description fallback -> findAssetWithName uses description fallback', t => {
const usable = getUsableAssets(MOCK_STAC_DESCRIPTION_FALLBACK);
const result = findAssetWithName(usable, 'red', 'common_name');
t.ok(result, 'should find asset with common_name=red via description');
t.equal(result[0], 'data', 'should return correct asset name');
t.equal(result[1], 0, 'should return correct band index');
const blueResult = findAssetWithName(usable, 'blue', 'common_name');
t.ok(blueResult, 'should find asset with common_name=blue via description');
t.equal(blueResult[1], 2, 'should return band index 2 for blue');
t.end();
});
test('#Description fallback -> filterAvailablePresets works with description fallback', t => {
const presetData = {
trueColor: {
id: 'trueColor',
commonNames: ['red', 'green', 'blue'],
bandCombination: 'rgb'
},
singleBand: {
id: 'singleBand',
commonNames: null,
bandCombination: 'single'
}
};
const available = filterAvailablePresets(MOCK_STAC_DESCRIPTION_FALLBACK, presetData);
t.ok(available, 'should return available presets');
t.ok(available.includes('trueColor'), 'should include trueColor via description fallback');
t.ok(available.includes('singleBand'), 'should include singleBand');
t.end();
});
test('#Description fallback -> ignores non-matching descriptions', t => {
const stac = {
type: 'Feature',
stac_version: '1.0.0',
stac_extensions: [
'https://stac-extensions.github.io/eo/v1.0.0/schema.json',
'https://stac-extensions.github.io/raster/v1.0.0/schema.json'
],
id: 'unknown-desc-test',
geometry: {type: 'Point', coordinates: [0, 0]},
bbox: [-1, -1, 1, 1],
links: [],
properties: {datetime: '2023-01-01T00:00:00Z'},
assets: {
data: {
href: 'https://example.com/cog.tif',
'eo:bands': [
{name: 'b1', description: 'custom band'},
{name: 'b2', description: 'another band'}
],
'raster:bands': [{data_type: 'uint8'}, {data_type: 'uint8'}]
}
}
};
const bands = getEOBands(stac);
t.ok(bands, 'should return bands');
t.notOk(bands[0].common_name, 'should not infer common_name from non-standard description');
t.notOk(bands[1].common_name, 'should not infer common_name from non-standard description');
t.end();
});
// ---- Debug mode tests ----
test('#RasterTileLayer -> showTileBorders default config', t => {
const layer = new RasterTileLayer({id: 'test-debug', dataId: 'test'});
t.equal(layer.config.visConfig.showTileBorders, false, 'showTileBorders should default to false');
layer.updateLayerVisConfig({showTileBorders: true});
t.equal(
layer.config.visConfig.showTileBorders,
true,
'showTileBorders should be updatable to true'
);
t.end();
});
const MOCK_STAC_FLOAT32_METADATA = {
type: 'Feature',
stac_version: '1.0.0',
stac_extensions: ['https://stac-extensions.github.io/raster/v1.1.0/schema.json'],
id: 'test-float32-cog',
geometry: {type: 'Point', coordinates: [0, 0]},
bbox: [-122.5, 37.5, -122.0, 38.0],
links: [],
properties: {datetime: '2023-01-01T00:00:00Z'},
assets: {
ndvi: {
href: 'https://example.com/ndvi.tif',
type: 'image/tiff; application=geotiff',
'raster:bands': [
{
data_type: 'float32',
statistics: {minimum: -0.2, maximum: 0.92}
}
]
}
}
};
test('#RasterTileLayer -> getDataSourceParams float32 band with statistics', t => {
const params = getDataSourceParams(MOCK_STAC_FLOAT32_METADATA, 'singleBand', {
singleBand: {assetId: 'ndvi'}
});
t.ok(params, 'should return data source params for a float32 band');
t.equal(params?.dataType, 'float32', 'should keep the float32 data type');
t.equal(params?.minPixelValue, -0.2, 'should take the minimum from the band statistics');
t.equal(params?.maxPixelValue, 0.92, 'should take the maximum from the band statistics');
t.end();
});
test('#RasterTileLayer -> getDataSourceParams float32 band without statistics', t => {
const noStatsStac = {
...MOCK_STAC_FLOAT32_METADATA,
assets: {
ndvi: {
...MOCK_STAC_FLOAT32_METADATA.assets.ndvi,
'raster:bands': [{data_type: 'float32'}]
}
}
};
const params = getDataSourceParams(noStatsStac, 'singleBand', {singleBand: {assetId: 'ndvi'}});
t.equal(params, null, 'should return null when there is no range to rescale against');
t.end();
});
test('#RasterTileLayer -> getDataSourceParams integer band uses the data type range', t => {
const params = getDataSourceParams(MOCK_STAC_110_METADATA, 'singleBand', {
singleBand: {assetId: 'data'}
});
t.ok(params, 'should return data source params for a uint8 band');
t.equal(params?.minPixelValue, 0, 'should keep the data type minimum');
t.equal(params?.maxPixelValue, 255, 'should keep the data type maximum');
t.end();
});
test('#RasterTileLayer -> linear stretch normalizes the selected pixel interval', t => {
for (const [minPixelValue, maxPixelValue] of [
[100, 200],
[-100, 100],
[0, 200]
]) {
for (const linearRescalingFactor of [
[0, 1],
[0.25, 0.75],
[0.1, 0.8]
]) {
for (const bandCombination of ['rgb', 'single']) {
const {modules, moduleProps} = getModules({
images: {},
props: {minPixelValue, maxPixelValue, linearRescalingFactor, bandCombination}
});
t.ok(modules.includes(RasterWebGL.linearRescale), 'uses the linear rescale shader');
const {scaler, offset} = RasterWebGL.linearRescale.getUniforms(moduleProps);
const range = maxPixelValue - minPixelValue;
const low = minPixelValue + linearRescalingFactor[0] * range;
const high = minPixelValue + linearRescalingFactor[1] * range;
// The shader applies arr * scaler + offset to every RGB channel.
const rgb = [low, (low + high) / 2, high].map(value => value * scaler + offset);
rgb.forEach((value, channel) => {
t.ok(
Math.abs(value - [0, 0.5, 1][channel]) < 1e-12,
`${bandCombination} ${minPixelValue}:${maxPixelValue} stretch ${linearRescalingFactor}, channel ${channel}`
);
});
}
}
}
t.end();
});
test('#RasterTileLayer -> linear stretch preserves fallback and other rescaling modes', t => {
const props = {
minPixelValue: 100,
maxPixelValue: 200,
linearRescalingFactor: [0.25, 0.75],
bandCombination: 'rgb'
};
const getRescale = overrides => {
const result = getModules({images: {}, props: {...props, ...overrides}});
return {...result, uniforms: RasterWebGL.linearRescale.getUniforms(result.moduleProps)};
};
for (const overrides of [
{maxPixelValue: 100},
{linearRescalingFactor: [0.25, 0.25]},
{minPixelValue: undefined, maxPixelValue: undefined}
]) {
t.deepEqual(
getRescale(overrides).uniforms,
{scaler: 1, offset: -0.25},
'keeps the degenerate-range fallback'
);
}
t.deepEqual(
getRescale({minPixelValue: Infinity, maxPixelValue: -Infinity}).uniforms,
{scaler: -0, offset: -0.25},
'keeps the empty viewport fallback'
);
const nonlinear = getRescale({nonLinearRescaling: true, gammaContrastFactor: 2});
t.deepEqual(nonlinear.uniforms, {scaler: 1 / 200, offset: 0}, 'keeps nonlinear normalization');
t.ok(nonlinear.modules.includes(RasterWebGL.gammaContrast), 'keeps gamma contrast');
t.equal(nonlinear.moduleProps.gammaContrastValue, 2, 'keeps the gamma factor');
t.deepEqual(
getRescale({hasCategoricalColorMap: true}).uniforms,
{scaler: 1 / 200, offset: 0},
'keeps categorical normalization'
);
t.notOk(
getRescale({bandCombination: 'normalizedDifference'}).modules.includes(
RasterWebGL.linearRescale
),
'does not rescale spectral indices'
);
t.deepEqual(
getModules({images: {}}),
{modules: [], moduleProps: {}},
'keeps missing-props behavior'
);
t.deepEqual(
getModules({images: {imageRgba: {}}, props}),
{modules: [RasterWebGL.rgbaImage], moduleProps: {}},
'keeps direct RGBA behavior'
);
t.end();
});
test('#RasterTileLayer -> float mask keeps the pixels a float32 mask marks as valid', t => {
// A tile server writes the mask in the band's own data type, marking valid pixels with that
// type's maximum: 255 for uint8, 65535 for uint16, and FLT_MAX for float32. The default upper
// bound therefore has to sit at or above FLT_MAX, or every valid pixel of a float raster is
// discarded and the layer draws nothing.
const FLOAT32_MAX = 3.4028234663852886e38;
const uniforms = RasterWebGL.maskFloat.getUniforms({imageMask: {}, maskKeepMin: 1});
t.ok(uniforms, 'should return uniforms for a mask texture');
t.equal(uniforms.keepMin, 1, 'should keep the given lower bound');
t.ok(
uniforms.keepMax >= FLOAT32_MAX,
`should not discard valid float pixels: keepMax ${uniforms.keepMax} < ${FLOAT32_MAX}`
);
t.end();
});
test('#RasterTileLayer -> identify samples band values at lng/lat', t => {
const [u, v] = lngLatToTileUV(0, 0, {x: 0, y: 0, z: 0});
t.ok(Math.abs(u - 0.5) < 1e-6, 'lng 0 is the center of tile 0/0/0 in x');
t.ok(Math.abs(v - 0.5) < 1e-6, 'lat 0 is the center of tile 0/0/0 in y');
const data = new Float32Array([1, 2, 3, 4]);
const tile = {
index: {x: 0, y: 0, z: 0},
bbox: {west: -180, south: -85, east: 180, north: 85},
data: {
images: {
imageBands: [{data, width: 2, height: 2}]
}
}
};
const sample = sampleRasterTileAtLngLat([tile], 0, 0, {
isPMTiles: false,
bandCombination: 'single',
loadAssetIds: ['ndvi']
});
t.ok(sample, 'should sample a loaded tile');
t.equal(sample.col, 1, 'center of a 2x2 tile is column 1');
t.equal(sample.row, 1, 'center of a 2x2 tile is row 1');
t.equal(sample.bandValues[0], 4, 'should read the bottom-right pixel');
const rows = formatRasterIdentifyRows(sample, {
isPMTiles: false,
bandCombination: 'single',
loadAssetIds: ['ndvi']
});
t.ok(
rows.some(row => row.name === 'ndvi' && row.value === '4'),
'tooltip rows include the band value'
);
const ndvi = computeDerivedValue([0.8, 0.2], 'normalizedDifference');
t.ok(ndvi, 'should compute NDVI');
t.equal(ndvi.name, 'NDVI');
t.ok(Math.abs(ndvi.value - 0.6) < 1e-6, 'NDVI (0.8-0.2)/(0.8+0.2) = 0.6');
const ndmi = computeDerivedValue([0.8, 0.2], 'normalizedDifference', 'NDMI');
t.equal(ndmi.name, 'NDMI', 'normalized-difference presets should use the active index label');
const parsed = parseTitilerPointResponse({
coordinates: [-122.4, 37.8],
values: [12.5, 8],
band_names: ['red', 'nir']
});
t.equal(parsed.length, 4, 'should format lon/lat plus two bands');
t.equal(parsed[2].name, 'red');
t.end();
});
test('#RasterTileLayer -> PMTiles hover reads decoded browser image pixels', async t => {
const layer = new RasterTileLayer({id: 'pmtiles-image-hover', dataId: 'pmtiles'});
const image = document.createElement('img');
image.width = 2;
image.height = 2;
const pixels = new Uint8ClampedArray([
10, 20, 30, 255, 40, 50, 60, 255, 70, 80, 90, 255, 100, 110, 120, 255
]);
const drawImage = sinon.spy();
const getImageData = sinon.stub().returns({data: pixels});
const canvas = sinon.stub(window.HTMLCanvasElement.prototype, 'getContext').returns({
drawImage,
getImageData
});
const opts = createRenderOpts(MOCK_PMTILES_DATASET);
opts.data.tileSource.getTileData = async () => image;
const index = {x: 0, y: 0, z: 0};
const bbox = {west: -180, south: -85, east: 180, north: 85};
try {
const [tileLayer] = layer.renderLayer(opts);
const data = await tileLayer.props.getTileData({index, bbox});
t.equal(data.image, image, 'the loader keeps the browser image used for rendering');
tileLayer.props.onViewportLoad([{index, bbox, data}]);
const hover = coordinate => layer.getHoverData(null, null, [], null, {coordinate});
t.equal(hover([0, 0]), null, 'hover remains opt-in');
t.equal(getImageData.callCount, 0, 'loading does not read pixels');
layer.config.visConfig.allowHover = true;
t.ok(
hover([0, 0]).rasterFeatureData.some(
row => row.name === 'RGBA' && row.value === '100, 110, 120, 255'
),
'hover reads the bottom-right pixel of a decoded image'
);
t.ok(
hover([-90, 45]).rasterFeatureData.some(
row => row.name === 'RGBA' && row.value === '10, 20, 30, 255'
),
'another coordinate reads the correct pixel'
);
t.equal(drawImage.firstCall?.args[0], image, 'readback draws the loaded image');
t.equal(getImageData.callCount, 1, 'repeated hover reuses the decoded pixels');
const replacement = document.createElement('img');
replacement.width = replacement.height = 2;
getImageData.returns({data: new Uint8ClampedArray(16)});
tileLayer.props.onViewportLoad([{index, bbox, data: {image: replacement}}]);
t.ok(
hover([0, 0]).rasterFeatureData.some(row => row.value === 'NoData'),
'transparent pixels remain NoData'
);
t.equal(getImageData.callCount, 2, 'replacement images get fresh pixels');
const blocked = document.createElement('img');
blocked.width = blocked.height = 2;
getImageData.throws(Object.assign(new Error('tainted canvas'), {name: 'SecurityError'}));
tileLayer.props.onViewportLoad([{index, bbox, data: {image: blocked}}]);
t.equal(
sampleRasterTileAtLngLat(layer._loadedTiles, 0, 0, layer._identifyContext),
null,
'security failures do not expose pixels or throw'
);
t.equal(
sampleRasterTileAtLngLat(layer._loadedTiles, 0, 0, layer._identifyContext),
null,
'unreadable tiles remain unavailable'
);
t.equal(getImageData.callCount, 3, 'unreadable images are not retried on every hover');
tileLayer.props.onViewportLoad([
{index, bbox, data: {image: {data: pixels, width: 2, height: 2}}}
]);
t.deepEqual(
sampleRasterTileAtLngLat(layer._loadedTiles, 0, 0, layer._identifyContext).rgba,
[100, 110, 120, 255],
'raw buffers still sample without a canvas'
);
t.equal(getImageData.callCount, 3, 'raw buffers bypass readback');
t.equal(
sampleRasterTileAtLngLat([], 0, 0, layer._identifyContext),
null,
'missing tiles remain unavailable'
);
} finally {
canvas.restore();
}
t.end();
});
test('#RasterTileLayer -> hover, picking, and extract from loaded tiles', t => {
const layer = new RasterTileLayer({id: 'raster-id', dataId: 'stac-data', label: 'Rivers'});
layer.config.visConfig.allowHover = true;
layer._loadedTiles = [
{
index: {x: 0, y: 0, z: 0},
bbox: {west: -180, south: -85, east: 180, north: 85},
data: {
images: {
imageBands: [{data: new Uint8Array([40]), width: 1, height: 1}]
}
}
}
];
layer._identifyContext = {
isPMTiles: false,
bandCombination: 'single',
loadAssetIds: ['red']
};
const hover = layer.getHoverData(null, null, [], null, {index: 0, coordinate: [0, 0]});
t.ok(hover.rasterFeatureData, 'hover should return raster feature rows');
t.ok(
hover.rasterFeatureData.some(row => row.name === 'red'),
'hover includes the sampled band'
);
const hovered = layer.hasHoveredObject({
picked: true,
layer: {props: {id: `raster-2d-layer-${layer.id}`}}
});
t.ok(hovered, 'child RasterLayer ids should count as hovered');
const pmtilesLayer = new RasterTileLayer({id: 'pmtiles-id', dataId: 'pmtiles-data'});
const pmtilesLayersDefault = pmtilesLayer.renderLayer({
...createRenderOpts(MOCK_PMTILES_DATASET),
idx: 2
});
t.equal(
pmtilesLayersDefault[0]?.props.pickable,
false,
'PMTiles should not be pickable by default'
);
t.equal(pmtilesLayersDefault[0]?.props.idx, 2, 'idx should be forwarded onto the TileLayer');
pmtilesLayer.config.visConfig.allowHover = true;
const pmtilesLayersHoverOn = pmtilesLayer.renderLayer({
...createRenderOpts(MOCK_PMTILES_DATASET),
idx: 2
});
t.equal(
pmtilesLayersHoverOn[0]?.props.pickable,
true,
'PMTiles should be pickable when allowHover and tooltips are on'
);
pmtilesLayer.config.visConfig.allowHover = false;
const pmtilesLayersHoverOff = pmtilesLayer.renderLayer({
...createRenderOpts(MOCK_PMTILES_DATASET),
idx: 2
});
t.equal(
pmtilesLayersHoverOff[0]?.props.pickable,
false,
'PMTiles should not be pickable when allowHover is off'
);
layer.config.visConfig.allowHover = false;
t.equal(
layer.hasHoveredObject({
picked: true,
layer: {props: {id: `raster-2d-layer-${layer.id}`}}
}),
null,
'should not report hover when allowHover is off'
);
t.equal(
layer.getHoverData(null, null, [], null, {index: 0, coordinate: [0, 0]}),
null,
'should not build tooltip rows when allowHover is off'
);
const extracted = layer.extractInsideFeature({
type: 'Feature',
properties: {shape: 'Rectangle'},
geometry: {
type: 'Polygon',
coordinates: [
[
[-10, -10],
[10, -10],
[10, 10],
[-10, 10],
[-10, -10]
]
]
}
});
t.equal(extracted.kind, 'geojson', 'extract should return geojson stats');
t.equal(extracted.rowCount, 1, 'extract should keep the polygon as one feature');
t.ok(extracted.features[0].properties.pixel_count > 0, 'extract should count pixels');
t.end();
});
test('#RasterTileLayer -> scan limit never returns partial statistics', async t => {
const polygon = {
type: 'Feature',
properties: {shape: 'Rectangle'},
geometry: {
type: 'Polygon',
coordinates: [
[
[-180, -86],
[180, -86],
[180, 86],
[-180, 86],
[-180, -86]
]
]
}
};
const context = {isPMTiles: false, bandCombination: 'single', loadAssetIds: ['value']};
const band = {width: 2000, height: 1000, data: new Uint8Array(2_000_000).fill(1)};
band.data[band.data.length - 1] = 100;
const tile = {index: {x: 0, y: 0, z: 0}, data: {images: {imageBands: [band]}}};
const exact = computeRasterZonalStats([tile], polygon, context);
t.equal(exact.pixelCount, 2_000_000, 'exactly the scan limit is supported');
t.equal(exact.bands.value.max, 100, 'the final pixel is included');
const extra = {
...tile,
data: {images: {imageBands: [{width: 1, height: 1, data: new Uint8Array([200])}]}}
};
const scanLimit = /2,000,000-pixel scan limit/;
t.throws(
() => computeRasterZonalStats([tile, extra], polygon, context),
scanLimit,
'one more pixel in a later tile fails instead of returning truncated totals'
);
const tinyPolygon = {
...polygon,
geometry: {
type: 'Polygon',
coordinates: [
[
[0, 0],
[0.01, 0],
[0.01, 0.01],
[0, 0.01],
[0, 0]
]
]
}
};
t.throws(
() => computeRasterZonalStats([tile, extra], tinyPolygon, context),
scanLimit,
'the work limit counts scanned pixels, including those outside the selection'
);
const layer = new RasterTileLayer({id: 'raster-scan-limit', dataId: 'raster'});
layer._identifyContext = context;
layer._loadedTiles = [
{
...tile,
data: {
images: {imageBands: [{...band, height: 1001, data: new Uint8Array(2_002_000).fill(1)}]}
}
}
];
t.throws(
() => layer.extractInsideFeature(polygon),
scanLimit,
'extraction also fails when additional pixels are in the same tile'
);
const download = sinon.stub(rasterExtract, 'downloadBlob');
const mosaic = sinon.stub(rasterExtract, 'mosaicTilesToPng').resolves(null);
try {
await layer.downloadClip(polygon);
t.fail('oversized clip statistics must reject');
} catch (error) {
t.ok(scanLimit.test(error.message), 'clip download propagates the actionable limit error');
} finally {
t.equal(download.callCount, 0, 'no partial statistics file is downloaded');
t.equal(mosaic.callCount, 0, 'no clip image work starts after a statistics failure');
download.restore();
mosaic.restore();
}
layer._loadedTiles = [extra];
const ordinary = layer.extractInsideFeature(polygon);
t.equal(ordinary.rowCount, 1, 'ordinary selections still extract after a failed attempt');
t.equal(ordinary.features[0].properties.pixel_count, 1, 'ordinary counts are unchanged');
t.equal(ordinary.features[0].properties.value_max, 200, 'ordinary extrema are unchanged');
t.deepEqual(
computeRasterZonalStats([], polygon, context),
{pixelCount: 0, bands: {}},
'empty tiles are unchanged'
);
t.end();
});
test('#RasterTileLayer -> raster stats sidecar is GeoJSON with bbox rectangle', t => {
const geometry = {
type: 'Polygon',
coordinates: [
[
[0, 0],
[10, 0],
[10, 5],
[0, 5],
[0, 0]
]
]
};
const sidecar = rasterZonalStatsToSidecar(
{
pixelCount: 12,
bands: {red: {count: 12, min: 1, max: 9, mean: 4, sum: 48}},
derived: {count: 12, min: 0.1, max: 0.8, mean: 0.4, sum: 4.8},
derivedName: 'NDVI'
},
{layer: 'Rivers', preset: 'ndvi', geometry}
);
t.equal(sidecar.type, 'FeatureCollection');
t.equal(sidecar.features.length, 1);
t.equal(sidecar.features[0].type, 'Feature');
t.deepEqual(sidecar.features[0].geometry, geometry);
t.equal(sidecar.features[0].properties.layer, 'Rivers');
t.equal(sidecar.features[0].properties.pixel_count, 12);
t.equal(sidecar.features[0].properties.red_mean, 4);
t.equal(sidecar.features[0].properties.ndvi_mean, 0.4);
t.equal(sidecar.features[0].properties.shape, 'Rectangle');
t.end();
});
test('#RasterTileLayer -> extract PNG size follows rectangle aspect ratio', t => {
const wide = mercatorPixelSizeForBbox([-20, 10, 20, 12], 1000);
t.ok(wide.width > wide.height, 'a wide geographic rectangle should export a wide image');
t.equal(wide.width, 1000, 'the long side should use the max size');
const tall = mercatorPixelSizeForBbox([0, 0, 1, 20], 1000);
t.ok(tall.height > tall.width, 'a tall geographic rectangle should export a tall image');
t.equal(tall.height, 1000, 'the long side should use the max size');
const square = mercatorPixelSizeForBbox([-1, -1, 1, 1], 512);
t.ok(
Math.abs(square.width / square.height - 1) < 0.15,
'a square geographic bbox should stay roughly square in mercator near the equator'
);
t.end();
});
test('#RasterTileLayer -> non-rectangular polygon export uses lon/lat bbox rectangle', t => {
const triangle = {
type: 'Feature',
properties: {shape: 'Polygon'},
geometry: {
type: 'Polygon',
coordinates: [
[
[0, 0],
[10, 0],
[0, 5],
[0, 0]
]
]
}
};
const rect = polygonToBboxRectangle(triangle);
t.ok(rect, 'should build a bbox rectangle');
t.equal(rect.properties.shape, 'Rectangle');
t.deepEqual(rect.geometry.coordinates[0], [
[0, 0],
[10, 0],
[10, 5],
[0, 5],
[0, 0]
]);
const layer = new RasterTileLayer({id: 'raster-bbox-id', dataId: 'stac-data', label: 'Rivers'});
layer._loadedTiles = [
{
index: {x: 0, y: 0, z: 0},
bbox: {west: -180, south: -85, east: 180, north: 85},
data: {
images: {
imageBands: [{data: new Uint8Array([40]), width: 1, height: 1}]
}
}
}
];
layer._identifyContext = {
isPMTiles: false,
bandCombination: 'single',
loadAssetIds: ['red']
};
const extracted = layer.extractInsideFeature(triangle);
t.deepEqual(
extracted.features[0].geometry.coordinates[0],
[
[0, 0],
[10, 0],
[10, 5],
[0, 5],
[0, 0]
],
'extract should use the lon/lat bbox rectangle, not the triangle'
);
t.end();
});
test('#RasterTileLayer -> only image blobs are treated as downloadable PNGs', t => {
t.ok(
isDownloadableImageBlob({type: 'image/png', size: 12}),
'a non-empty PNG blob should download'
);
t.notOk(
isDownloadableImageBlob({type: 'application/json', size: 80}),
'a JSON error body should not be saved as a PNG'
);
t.notOk(
isDownloadableImageBlob({type: 'image/png', size: 0}),
'an empty image blob should not download'
);
t.end();
});
test('#RasterTileLayer -> replacing a PMTiles URL reloads cached tile content', async t => {
const layer = new RasterTileLayer({id: 'pmtiles-cache', dataId: 'raster'});
layer.updateLayerVisConfig({enableTerrain: false});
const manager = new LayerManager(device, {
viewport: new WebMercatorViewport({width: 64, height: 64, longitude: 0, latitude: 0, zoom: 2})
});
const requests = [];
const imageA = new Uint8Array([10, 20, 30, 255]);
const imageB = new Uint8Array([40, 50, 60, 255]);
const format = (url, oldData) => {
const data = layer.formatLayerData(
{raster: {...MOCK_PMTILES_DATASET, metadata: {...MOCK_PMTILES_METADATA, metadataUrl: url}}},
oldData
);
// Keep the production PMTiles source and cache lifecycle, replacing only archive I/O.
data.tileSource.getTileData = async () => {
requests.push(url);
return url.endsWith('a.pmtiles') ? imageA : imageB;
};
return data;
};
const render = async data => {
const deckLayer = layer.renderLayer({
...createRenderOpts(data.dataset),
data,
visible: true
})[0];
// Exercise TileLayer/Tileset2D on the test device without drawing bitmap sublayers.
const rendered = deckLayer.clone({renderSubLayers: () => null});
manager.setLayers([rendered]);
await Promise.all(rendered.state.tileset.selectedTiles.map(tile => tile.data));
return rendered;
};
try {
const firstData = format('https://example.com/a.pmtiles');
const first = await render(firstData);
const tileset = first.state.tileset;
const reload = sinon.spy(tileset, 'reloadAll');
t.ok(requests.length > 0, 'initial source loads visible tiles');
t.equal(tileset.selectedTiles[0].content.image, imageA, 'cache contains the original image');
const initialRequests = requests.length;
const sameSource = await render(firstData);
t.equal(sameSource.state.tileset, tileset, 'the same layer keeps its tile cache');
t.equal(requests.length, initialRequests, 'an ordinary rerender does not reload tiles');
layer.updateLayerVisConfig({opacity: 0.4, showTileBorders: true});
await render(firstData);
t.equal(requests.length, initialRequests, 'style changes do not reload tiles');
const equivalentData = format('https://example.com/a.pmtiles', firstData);
t.notEqual(
equivalentData.tileSource,
firstData.tileSource,
'metadata replacement makes a new source'
);
await render(equivalentData);
t.equal(
requests.length,
initialRequests,
'a replacement source with the same URL keeps cached data'
);
t.equal(reload.callCount, 0, 'no cache reload was needed for unchanged content');
const changedData = format('https://example.com/b.pmtiles', equivalentData);
const changed = await render(changedData);
t.equal(
changed.props.tileSource,
changedData.tileSource,
'render receives the replacement source'
);
t.equal(changed.state.tileset, tileset, 'replacement reuses the existing tileset');
t.equal(reload.callCount, 1, 'changing the source URL reloads the existing cache');
t.ok(
requests.includes('https://example.com/b.pmtiles'),
'visible tiles are requested from the new source'
);
t.equal(
tileset.selectedTiles[0].content.image,
imageB,
'cached content is replaced by the new image'
);
} finally {
manager.finalize();
}
t.end();
});
test('#RasterTileLayer -> identify preserves the picking coordinate for selection ownership', async t => {
const layer = new RasterTileLayer({id: 'identify-coordinate', dataId: 'raster'});
const rows = [{name: 'BAND', value: '20'}];
layer._fetchTitilerPoint = async () => rows;
const results = [];
const coordinate = [1, 2];
await layer._onClickIdentify({onWMSFeatureInfo: result => results.push(result)}, {coordinate});
t.equal(results[0].coordinate, coordinate, 'keeps the exact picking coordinate identity');
t.deepEqual(results[0].featureInfo, rows, 'publishes the sampled values');
t.end();
});
test('#RasterTileLayer -> TiTiler identification distinguishes masked values from zero', async t => {
const layer = new RasterTileLayer({id: 'identify-nodata', dataId: 'raster'});
layer._stac = {
...MOCK_STAC_METADATA,
rasterTileServerUrls: ['https://example.com']
};
layer._identifyContext = {isPMTiles: false, loadAssetIds: ['red']};
const results = [];
const originalFetch = globalThis.fetch;
globalThis.fetch = async () => ({
ok: true,
json: async () => ({
values: [null, 42, 0, -3.5, '12.5'],
band_names: ['masked', 'valid', 'zero', 'negative', 'numeric string']
})
});
try {
await layer._onClickIdentify(
{onWMSFeatureInfo: result => results.push(result)},
{coordinate: [1, 2]}
);
t.deepEqual(
results[0]?.featureInfo,
[
{name: 'masked', value: 'NoData'},
{name: 'valid', value: '42'},
{name: 'zero', value: '0'},
{name: 'negative', value: '-3.5000'},
{name: 'numeric string', value: '12.5000'}
],
'the identification callback keeps masked bands distinct from valid measurements'
);
t.deepEqual(
parseTitilerPointResponse({value: [null, 0]}),
[
{name: 'Band 1', value: 'NoData'},
{name: 'Band 2', value: '0'}
],
'legacy value payloads and fallback band names also preserve NoData'
);
t.equal(parseTitilerPointResponse({values: []}), null, 'empty responses remain unavailable');
} finally {
globalThis.fetch = originalFetch;
}
t.end();
});
test('#RasterTileLayer -> SAVI uses the soil adjustment multiplier in CPU and shader arithmetic', t => {
// Evaluate this scalar GLSL function as JavaScript to check the shipped expression.
// This is an arithmetic parity test, not a WebGL rendering test.
const body = RasterWebGL.soilAdjustedVegetationIndex.fs.match(/\{([\s\S]*)\}/)[1];
const shaderSavi = new Function('image', body.replace(/\bfloat\b/g, 'const'));
for (const [nir, red, expected] of [
[0.8, 0.2, 0.6],
[0.2, 0.8, -0.6],
[0.2, 0.2, 0],
[0, 0, 0],
[0.5, 0, 0.75]
]) {
const cpu = computeDerivedValue([nir, red], 'soilAdjustedVegetationIndex');
t.equal(cpu.name, 'SAVI', 'derived value retains its label');
t.ok(Math.abs(cpu.value - expected) < 1e-10, `CPU SAVI for ${nir}, ${red} is ${expected}`);
t.ok(
Math.abs(shaderSavi({r: nir, g: red}) - expected) < 1e-10,
'GLSL arithmetic matches the reference'
);
}
for (const values of [[NaN, 0.2], [0.8, Infinity], [0.8], [-0.5, 0]]) {
t.equal(
computeDerivedValue(values, 'soilAdjustedVegetationIndex'),
null,
'invalid inputs or zero denominator stay unavailable'
);
}
const context = {isPMTiles: false, bandCombination: 'soilAdjustedVegetationIndex'};
const sample = {
lng: 0,
lat: 0,
tileIndex: {x: 0, y: 0, z: 0},
col: 0,
row: 0,
bandValues: [0.8, 0.2],
bandLabels: ['nir', 'red'],
nodata: false
};
t.ok(
formatRasterIdentifyRows(sample, context).some(
row => row.name === 'SAVI' && row.value === '0.600000'
),
'identify displays the corrected derived value'
);
const nodataRows = formatRasterIdentifyRows({...sample, nodata: true}, context);
t.ok(
nodataRows.some(row => row.value === 'NoData'),
'masked samples remain NoData'
);
t.notOk(
nodataRows.some(row => row.name === 'SAVI'),
'masked samples do not emit a derived value'
);
t.end();
});
test('#RasterTileLayer -> switching STAC datasets with matching bands reloads cached imagery', async t => {
const layer = new RasterTileLayer({id: 'stac-cache', dataId: 'raster'});
layer.updateLayerVisConfig({enableTerrain: false, preset: 'trueColor'});
const manager = new LayerManager(device, {
viewport: new WebMercatorViewport({width: 64, height: 64, longitude: 0, latitude: 0, zoom: 2})
});
const requests = [];
const metadata = suffix => ({
...MOCK_STAC_METADATA,
id: suffix,
assets: Object.fromEntries(
Object.entries(MOCK_STAC_METADATA.assets).map(([name, asset]) => [
name,
{
...asset,
href: `https://example.com/${suffix}/${name}.tif`,
'raster:bands': [{data_type: 'uint8'}]
}
])
)
});
const firstMetadata = metadata('a');
const secondMetadata = metadata('b');
const imageA = {images: {imageBands: [{data: new Float32Array([0.2]), width: 1, height: 1}]}};
const imageB = {images: {imageBands: [{data: new Float32Array([0.8]), width: 1, height: 1}]}};
const getTileData = sinon.stub(layer, 'getTileData').callsFake(async ({stac}) => {
requests.push(stac);
return stac === firstMetadata ? imageA : imageB;
});
const render = async stac => {
const deckLayer = layer.renderLayer(
createRenderOpts({...MOCK_STAC_DATASET, metadata: stac})
)[0];
const rendered = deckLayer.clone({renderSubLayers: () => null});
manager.setLayers([rendered]);
await Promise.all(rendered.state.tileset.selectedTiles.map(tile => tile.data));
return rendered;
};
try {
const first = await render(firstMetadata);
const tileset = first.state.tileset;
const reload = sinon.spy(tileset, 'reloadAll');
t.ok(requests.length > 0, 'initial source requests tiles');
t.equal(tileset.selectedTiles[0].content, imageA, 'first source image is cached');
const initialRequests = requests.length;
await render(firstMetadata);
layer.updateLayerVisConfig({opacity: 0.4, showTileBorders: true});
await render(firstMetadata);
t.equal(requests.length, initialRequests, 'same-source rerenders and style edits reuse tiles');
t.equal(reload.callCount, 0, 'same-source cache is not invalidated');
const changed = await render(secondMetadata);
t.equal(changed.state.tileset, tileset, 'source replacement retains the tileset');
t.equal(reload.callCount, 1, 'source replacement invalidates cached tiles');
t.ok(requests.includes(secondMetadata), 'new requests use the replacement STAC source');
t.equal(tileset.selectedTiles[0].content, imageB, 'new imagery replaces cached imagery');
} finally {
getTileData.restore();
manager.finalize();
}
t.end();
});