Raster, GeoTIFF and WebGL · Angular, React and OpenLayers

Contours from interpolated elevation data

Generate adaptive terrain contour lines from WebGL-interpolated float EU-DEM tiles in OpenLayers and compare rendered and source pixel heights.

Adaptive terrain contours around Kraków Main Square, with rendered elevation, source-data elevation and a 10 metre contour interval.
A screenshot of the example. Produced using Copernicus data and information funded by the European Union - EU-DEM layers. Terrain Tiles on AWS; Tilezen attribution.

What this example shows

Centred on Kraków’s Main Market Square and fenced to the 25-tile core of a local 49-tile EU-DEM elevation fixture, crisp adaptive contour lines trace terrain relief while readouts below compare bilinearly interpolated Rendered elevation, raw Source-data elevation and the active zoom-dependent contour interval (for example 10 m).

When you need it

Drawing contours directly on un-interpolated integer DEM pixels past their native zoom produces staircase “terracing” artifacts and broken lines along tile seams.

Decoding Terrarium RGB heights into floating-point metres with a 1-pixel neighbour gutter—and letting WebGL bilinearly interpolate float heights before a Raster worker traces contours—produces smooth cartographic isolines even when overzoomed.

The code

The example uses cc-openlayers, my Angular component library for OpenLayers: each aol-… element creates the OpenLayers object it names, updates it from its inputs and disposes of it with the component.

contour-interpolation.html
<section class="example">
  <h2>{{ label }}</h2>
  <p>Local EU-DEM tiles around central Kraków; the map is limited to the saved area.</p>

  <aol-map height="480px" [ariaLabel]="label" (pointerMove)="updatePointer($event)">
    <aol-interaction-default />
    <aol-control-defaults />
    <aol-view [zoom]="17" [minZoom]="13" [maxZoom]="21" [extent]="coreExtent" [constrainOnlyCenter]="true">
      <aol-coordinate [x]="19.9368" [y]="50.0614" srid="EPSG:4326" />
    </aol-view>

    <aol-layer-webgltile
      #sourceDataLayer
      [extent]="coreExtent"
      [sources]="terrain.dataSources"
      [style]="transparentDataStyle"
      [postrender]="checkLinearInterpolation"
    />

    <aol-layer-image [extent]="coreExtent" [opacity]="0.5">
      <aol-source-raster
        [sources]="terrain.contourSources"
        operationType="image"
        [operation]="operation"
        [lib]="operationLib"
        [resolutions]="null"
        (beforeOperations)="beforeOperations($event)"
      />
    </aol-layer-image>

    <aol-layer-image #renderedElevationLayer [extent]="coreExtent" [opacity]="0">
      <aol-source-raster
        [sources]="terrain.elevationSources"
        [operation]="renderedElevationOperation"
        [resolutions]="null"
      />
    </aol-layer-image>
  </aol-map>

  <div class="example-controls" aria-live="polite">
    <dl>
      <div>
        <dt>Rendered elevation</dt>
        <dd>
          <output>{{ formatHeight(pointer().rendered) }}</output>
        </dd>
      </div>
      <div>
        <dt>Source data</dt>
        <dd>
          <output>{{ formatHeight(pointer().source) }}</output>
        </dd>
      </div>
      <div>
        <dt>Contour interval</dt>
        <dd>
          <output>{{ formatInterval(interval()) }}</output>
        </dd>
      </div>
    </dl>
  </div>

  <p class="terrain-attribution">
    {{ attributionNotice }}
    <a [href]="attributionUrl" target="_blank" rel="noreferrer">Tilezen attribution</a>
  </p>

  @if (linearInterpolationUnavailable()) {
    <p class="terrain-error" role="alert">
      Linear interpolation of floating-point textures is unavailable on this device.
    </p>
  }

  @if (loadFailed()) {
    <p class="terrain-error" role="alert">Elevation tiles could not be loaded.</p>
    <button type="button" (click)="retryElevationTiles()">Retry elevation tiles</button>
  }
</section>
contour-interpolation.shared.ts
import DataTile, { type Options as DataTileOptions } from 'ol/source/DataTile.js';
import type { ExpressionValue } from 'ol/expr/expression.js';
import type WebGLTileLayer from 'ol/layer/WebGLTile.js';
import type { Style as WebGLStyle } from 'ol/layer/WebGLTile.js';
import type { Extent } from 'ol/extent.js';
import { get as getProjection } from 'ol/proj.js';
import type { Operation, Options as RasterOptions } from 'ol/source/Raster.js';
import TileGrid from 'ol/tilegrid/TileGrid.js';
import { createWebGLTileLayer } from 'cc-openlayers/core/webgl';

export const TERRAIN_TILE_SIZE = 256;
export const TERRAIN_GUTTER = 1;
export const TERRAIN_ASSET_PREFIX = 'assets/krakow/contour-terrarium/tiles/';
export const TERRAIN_ATTRIBUTION_NOTICE =
  'Produced using Copernicus data and information funded by the European Union - EU-DEM layers.';
export const TERRAIN_ATTRIBUTION_URL = 'https://github.com/tilezen/joerd/blob/master/docs/attribution.md';
export const TERRAIN_ATTRIBUTION = `${TERRAIN_ATTRIBUTION_NOTICE} <a href="${TERRAIN_ATTRIBUTION_URL}" target="_blank" rel="noreferrer">Tilezen attribution</a>`;

/** The only z15 terrain cells shown. The source grid keeps these global XYZ indices. */
export const CONTOUR_CORE = { z: 15, xMin: 18196, xMax: 18200, yMin: 11102, yMax: 11106 } as const;
/** The one-tile halo is loaded only to fill the real neighbouring pixel gutter. */
export const CONTOUR_HALO = { xMin: 18195, xMax: 18201, yMin: 11101, yMax: 11107 } as const;

const WEB_MERCATOR_EXTENT = getProjection('EPSG:3857')?.getExtent();
if (!WEB_MERCATOR_EXTENT) throw new Error('EPSG:3857 must be registered before the terrain grid is created.');
const [worldMinX, , worldMaxX, worldMaxY] = WEB_MERCATOR_EXTENT;
const worldWidth = worldMaxX - worldMinX;
const tileWidthAtCoreZoom = worldWidth / 2 ** CONTOUR_CORE.z;

function tileAlignedExtent(xMin: number, xMax: number, yMin: number, yMax: number): Extent {
  return [
    worldMinX + xMin * tileWidthAtCoreZoom,
    worldMaxY - (yMax + 1) * tileWidthAtCoreZoom,
    worldMinX + (xMax + 1) * tileWidthAtCoreZoom,
    worldMaxY - yMin * tileWidthAtCoreZoom,
  ];
}

export const CONTOUR_CORE_EXTENT = tileAlignedExtent(
  CONTOUR_CORE.xMin,
  CONTOUR_CORE.xMax,
  CONTOUR_CORE.yMin,
  CONTOUR_CORE.yMax
);

/** Bounded cache for the original local PNGs; failed and late results never remain reusable. */
export class TerrariumImageCache<T> {
  private readonly entries = new Map<string, Promise<T>>();
  private readonly controller = new AbortController();
  private disposed = false;

  constructor(private readonly maximumEntries: number) {
    if (!Number.isInteger(maximumEntries) || maximumEntries < 1) {
      throw new RangeError('The image cache limit must be a positive integer.');
    }
  }

  get size(): number {
    return this.entries.size;
  }

  load(key: string, load: (signal: AbortSignal) => Promise<T>): Promise<T> {
    if (this.disposed) return Promise.reject(new Error('Terrain image cache has been released.'));
    const current = this.entries.get(key);
    if (current) return current;
    if (this.entries.size >= this.maximumEntries) {
      return Promise.reject(new RangeError(`Terrain image cache exceeds ${this.maximumEntries} assets.`));
    }

    const request = Promise.resolve()
      .then(() => {
        if (this.disposed) throw new Error('Terrain image cache has been released.');
        return load(this.controller.signal);
      })
      .then((value) => {
        if (this.disposed || this.entries.get(key) !== request) {
          throw new Error('Terrain image load completed after its owner was released.');
        }
        return value;
      })
      .catch((error: unknown) => {
        if (this.entries.get(key) === request) this.entries.delete(key);
        throw error;
      });
    this.entries.set(key, request);
    return request;
  }

  dispose(): void {
    if (this.disposed) return;
    this.disposed = true;
    this.controller.abort(new Error('Terrain image cache has been released.'));
    this.entries.clear();
  }
}

/** Decode the source's RGB Terrarium bytes. Alpha zero means no rendered sample, not a DEM NoData code. */
export function decodeTerrariumPixel(pixel: ArrayLike<number>): number | undefined {
  if (!pixel[3]) return undefined;
  return pixel[0] * 256 + pixel[1] + pixel[2] / 256 - 32768;
}

/**
 * Assemble a Float32 DataTile from row-major 3×3 PNG ImageData. The outer row and column come from
 * the real eight neighbouring tiles; the center contributes its full 256×256 pixels.
 */
export function buildGutteredElevationTile(tiles: readonly ImageData[]): Float32Array {
  const expectedPixels = TERRAIN_TILE_SIZE * TERRAIN_TILE_SIZE;
  if (
    tiles.length !== 9 ||
    tiles.some((tile) => tile.width !== TERRAIN_TILE_SIZE || tile.height !== TERRAIN_TILE_SIZE)
  ) {
    throw new RangeError('A Terrarium tile requires nine decoded 256×256 neighbours.');
  }
  if (tiles.some((tile) => tile.data.length !== expectedPixels * 4)) {
    throw new RangeError('Each Terrarium image must contain four RGBA bytes per pixel.');
  }

  const outputSize = TERRAIN_TILE_SIZE + 2 * TERRAIN_GUTTER;
  const output = new Float32Array(outputSize * outputSize);
  for (let outputY = 0; outputY < outputSize; outputY++) {
    const tileY = outputY === 0 ? 0 : outputY === outputSize - 1 ? 2 : 1;
    const pixelY = outputY === 0 ? TERRAIN_TILE_SIZE - 1 : outputY === outputSize - 1 ? 0 : outputY - 1;
    for (let outputX = 0; outputX < outputSize; outputX++) {
      const tileX = outputX === 0 ? 0 : outputX === outputSize - 1 ? 2 : 1;
      const pixelX = outputX === 0 ? TERRAIN_TILE_SIZE - 1 : outputX === outputSize - 1 ? 0 : outputX - 1;
      const imageData = tiles[tileY * 3 + tileX].data;
      const pixelOffset = (pixelY * TERRAIN_TILE_SIZE + pixelX) * 4;
      const red = imageData[pixelOffset];
      const green = imageData[pixelOffset + 1];
      const blue = imageData[pixelOffset + 2];
      if (!imageData[pixelOffset + 3]) {
        throw new Error(`Terrarium tile ${tileX},${tileY} contains a transparent elevation pixel.`);
      }
      const elevation = red * 256 + green + blue / 256 - 32768;
      output[outputY * outputSize + outputX] = elevation;
    }
  }
  return output;
}

/** The finite global XYZ grid always reads the saved z15 core, including at zooms 13–21. */
export function createContourTileGrid(): TileGrid {
  return new TileGrid({
    extent: CONTOUR_CORE_EXTENT,
    minZoom: CONTOUR_CORE.z,
    origin: [worldMinX, worldMaxY],
    resolutions: Array.from({ length: CONTOUR_CORE.z + 1 }, (_, zoom) => worldWidth / (TERRAIN_TILE_SIZE * 2 ** zoom)),
    tileSize: TERRAIN_TILE_SIZE,
  });
}

/** The adaptive bands used in the pinned OpenLayers example. */
export function contourInterval(resolution: number): number {
  if (resolution < 5) return 10;
  if (resolution < 25) return 50;
  if (resolution < 50) return 100;
  if (resolution < 250) return 500;
  return 1000;
}

// Raster serializes its operation and lib into a worker; this function is injected by lib there.
declare const calculateElevation: (pixel: number[]) => number | undefined;

/** Image operation adapted from OpenLayers 10.11.0's contour-interpolation example. */
export function contourOperation(inputs: (number[] | ImageData)[], data: object): ImageData {
  const elevationImage = inputs[0] as ImageData | undefined;
  if (!elevationImage) throw new Error('The contour operation requires one elevation image.');
  const interval = (data as { interval?: number }).interval;
  if (!interval || !Number.isFinite(interval)) throw new Error('The contour interval must be finite and positive.');

  const { width, height, data: elevationData } = elevationImage;
  const contourData = new Uint8ClampedArray(elevationData.length);
  const pixel = [0, 0, 0, 0];
  for (let pixelY = 0; pixelY < height; pixelY++) {
    for (let pixelX = 0; pixelX < width; pixelX++) {
      const offset = (pixelY * width + pixelX) * 4;
      const sample = (x: number, y: number): number | undefined => {
        const pixelOffset = (y * width + x) * 4;
        pixel[0] = elevationData[pixelOffset];
        pixel[1] = elevationData[pixelOffset + 1];
        pixel[2] = elevationData[pixelOffset + 2];
        pixel[3] = elevationData[pixelOffset + 3];
        return calculateElevation(pixel);
      };

      const left = sample(Math.max(pixelX - 1, 0), pixelY);
      const right = sample(Math.min(pixelX + 1, width - 1), pixelY);
      const top = sample(pixelX, Math.max(pixelY - 1, 0));
      const bottom = sample(pixelX, Math.min(pixelY + 1, height - 1));
      const center = sample(pixelX, pixelY);
      if (
        left === undefined ||
        right === undefined ||
        top === undefined ||
        bottom === undefined ||
        center === undefined
      ) {
        continue;
      }

      const band = Math.floor(center / interval);
      if (
        band === Math.floor(left / interval) &&
        band === Math.floor(right / interval) &&
        band === Math.floor(top / interval) &&
        band === Math.floor(bottom / interval)
      ) {
        continue;
      }

      const positive = center > 0 && left > 0 && right > 0 && top > 0 && bottom > 0;
      contourData[offset] = positive ? 0xe0 : 0x00;
      contourData[offset + 1] = positive ? 0x94 : 0xa9;
      contourData[offset + 2] = positive ? 0x5e : 0xca;
      contourData[offset + 3] = 255;
    }
  }
  return { data: contourData, width, height, colorSpace: 'srgb' } as ImageData;
}

export const CONTOUR_OPERATION_LIB: RasterOptions['lib'] = { calculateElevation: decodeTerrariumPixel };

/** Identity image operation retained for the pointer's rendered-elevation readout. */
export const elevationOperation: Operation = (pixels) => pixels[0];

/** The shader maps a float elevation back to normalized Terrarium RGBA for Raster's CPU image operation. */
function createTerrariumRgbaStyle(): WebGLStyle {
  const encoded = ['*', ['+', ['band', 1], 32768], 256] as ExpressionValue;
  const color: ExpressionValue = [
    'array',
    ['/', ['floor', ['/', encoded, 65536]], 255],
    ['/', ['floor', ['/', ['%', encoded, 65536], 256]], 255],
    ['/', ['%', encoded, 256], 255],
    1,
  ];
  return { color: color as WebGLStyle['color'] };
}

export const TRANSPARENT_DATA_STYLE: WebGLStyle = { color: ['array', 0, 0, 0, 0] };

export interface ContourTerrainInputs {
  readonly source: DataTile;
  readonly contourLayer: WebGLTileLayer;
  readonly elevationLayer: WebGLTileLayer;
  readonly dataSources: DataTile[];
  readonly contourSources: WebGLTileLayer[];
  readonly elevationSources: WebGLTileLayer[];
  dispose(): void;
}

/** Fetch and decode a local RGB PNG without retaining an ImageBitmap beyond pixel extraction. */
export async function loadTerrariumImage(url: string, signal?: AbortSignal): Promise<ImageData> {
  const response = await fetch(new URL(url, document.baseURI), { signal });
  const mimeType = response.headers.get('content-type')?.split(';', 1)[0].trim().toLowerCase();
  if (!response.ok || mimeType !== 'image/png') {
    throw new Error(`Could not load ${url}: HTTP ${response.status}, ${mimeType ?? 'unknown MIME type'}.`);
  }
  const bitmap = await createImageBitmap(await response.blob());
  try {
    if (bitmap.width !== TERRAIN_TILE_SIZE || bitmap.height !== TERRAIN_TILE_SIZE) {
      throw new Error(`Could not load ${url}: expected a 256×256 PNG.`);
    }
    const canvas = document.createElement('canvas');
    canvas.width = TERRAIN_TILE_SIZE;
    canvas.height = TERRAIN_TILE_SIZE;
    const context = canvas.getContext('2d', { willReadFrequently: true });
    if (!context) throw new Error('The browser cannot decode the local elevation tiles.');
    context.drawImage(bitmap, 0, 0);
    const imageData = context.getImageData(0, 0, TERRAIN_TILE_SIZE, TERRAIN_TILE_SIZE);
    for (let offset = 3; offset < imageData.data.length; offset += 4) {
      if (imageData.data[offset] !== 255) {
        throw new Error(`Could not load ${url}: the Terrarium RGB tile unexpectedly contains transparency.`);
      }
    }
    return imageData;
  } finally {
    bitmap.close();
  }
}

/** A loader that admits only the 5×5 core and reads real neighbours from its one-tile saved halo. */
export function createTerrariumTileLoader(
  cache: TerrariumImageCache<ImageData>,
  loadImage: (url: string, signal?: AbortSignal) => Promise<ImageData>
): (
  z: number,
  x: number,
  y: number,
  loaderOptions?: Parameters<NonNullable<DataTileOptions['loader']>>[3]
) => Promise<Float32Array> {
  return async (z, x, y) => {
    if (
      z !== CONTOUR_CORE.z ||
      x < CONTOUR_CORE.xMin ||
      x > CONTOUR_CORE.xMax ||
      y < CONTOUR_CORE.yMin ||
      y > CONTOUR_CORE.yMax
    ) {
      throw new RangeError(`Terrain tile ${z}/${x}/${y} is outside the saved contour core.`);
    }
    const urls: string[] = [];
    for (let yOffset = -1; yOffset <= 1; yOffset++) {
      for (let xOffset = -1; xOffset <= 1; xOffset++) {
        const neighborX = x + xOffset;
        const neighborY = y + yOffset;
        if (
          neighborX < CONTOUR_HALO.xMin ||
          neighborX > CONTOUR_HALO.xMax ||
          neighborY < CONTOUR_HALO.yMin ||
          neighborY > CONTOUR_HALO.yMax
        ) {
          throw new RangeError(`Terrain tile ${z}/${x}/${y} has no saved 3×3 pixel neighbourhood.`);
        }
        urls.push(`${TERRAIN_ASSET_PREFIX}${z}/${neighborX}/${neighborY}.png`);
      }
    }
    const images = await Promise.all(urls.map((url) => cache.load(url, (signal) => loadImage(url, signal))));
    return buildGutteredElevationTile(images);
  };
}

/** Owns one float source and two distinct input renderers used by the Raster image operations. */
export function createContourTerrainInputs(): ContourTerrainInputs {
  const cache = new TerrariumImageCache<ImageData>(49);
  const source = new DataTile({
    attributions: TERRAIN_ATTRIBUTION,
    bandCount: 1,
    gutter: TERRAIN_GUTTER,
    interpolate: true,
    loader: createTerrariumTileLoader(cache, loadTerrariumImage),
    maxZoom: CONTOUR_CORE.z,
    minZoom: CONTOUR_CORE.z,
    tileGrid: createContourTileGrid(),
    tileSize: TERRAIN_TILE_SIZE,
    wrapX: false,
  });
  const contourLayer = createWebGLTileLayer({ source, style: createTerrariumRgbaStyle(), cacheSize: 49 });
  const elevationLayer = createWebGLTileLayer({ source, style: createTerrariumRgbaStyle(), cacheSize: 49 });
  const dataSources = [source];
  const contourSources = [contourLayer];
  const elevationSources = [elevationLayer];
  let disposed = false;
  return {
    source,
    contourLayer,
    elevationLayer,
    dataSources,
    contourSources,
    elevationSources,
    dispose(): void {
      if (disposed) return;
      disposed = true;
      contourLayer.dispose();
      elevationLayer.dispose();
      source.dispose();
      cache.dispose();
    },
  };
}
contour-interpolation.ts
import { AfterViewInit, ChangeDetectionStrategy, Component, OnDestroy, signal, viewChild } from '@angular/core';
import type MapBrowserEvent from 'ol/MapBrowserEvent.js';
import type RenderEvent from 'ol/render/Event.js';
import type { EventsKey } from 'ol/events.js';
import { unByKey } from 'ol/Observable.js';
import {
  CoordinateComponent,
  DefaultControlComponent,
  DefaultInteractionComponent,
  LayerImageComponent,
  MapComponent,
  SourceRasterComponent,
  ViewComponent,
} from 'cc-openlayers';
import { LayerWebGLTileComponent } from 'cc-openlayers/webgl';
import {
  CONTOUR_CORE_EXTENT,
  CONTOUR_OPERATION_LIB,
  TERRAIN_ATTRIBUTION_NOTICE,
  TERRAIN_ATTRIBUTION_URL,
  TRANSPARENT_DATA_STYLE,
  contourInterval,
  contourOperation,
  createContourTerrainInputs,
  decodeTerrariumPixel,
  elevationOperation,
} from './contour-interpolation.shared';

interface ElevationReadout {
  readonly rendered: number | undefined;
  readonly source: number | undefined;
}

function firstBandValue(sample: Uint8ClampedArray | Uint8Array | Float32Array | DataView | null): number | undefined {
  if (!sample || sample instanceof DataView) return undefined;
  const value = sample[0];
  return Number.isFinite(value) ? value : undefined;
}

@Component({
  selector: 'app-contour-interpolation',
  imports: [
    CoordinateComponent,
    DefaultControlComponent,
    DefaultInteractionComponent,
    LayerImageComponent,
    LayerWebGLTileComponent,
    MapComponent,
    SourceRasterComponent,
    ViewComponent,
  ],
  templateUrl: './contour-interpolation.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ContourInterpolation implements AfterViewInit, OnDestroy {
  protected readonly label = 'Interpolated terrain contours around Kraków';
  protected readonly coreExtent = CONTOUR_CORE_EXTENT;
  protected readonly terrain = createContourTerrainInputs();
  protected readonly operation = contourOperation;
  protected readonly operationLib = CONTOUR_OPERATION_LIB;
  protected readonly renderedElevationOperation = elevationOperation;
  protected readonly transparentDataStyle = TRANSPARENT_DATA_STYLE;
  protected readonly attributionNotice = TERRAIN_ATTRIBUTION_NOTICE;
  protected readonly attributionUrl = TERRAIN_ATTRIBUTION_URL;
  protected readonly interval = signal<number | undefined>(undefined);
  protected readonly pointer = signal<ElevationReadout>({ rendered: undefined, source: undefined });
  protected readonly loadFailed = signal(false);
  protected readonly linearInterpolationUnavailable = signal(false);

  private readonly renderedLayer = viewChild.required<LayerImageComponent>('renderedElevationLayer');
  private readonly sourceDataLayer = viewChild.required<LayerWebGLTileComponent>('sourceDataLayer');
  private readonly sourceEvents: EventsKey[] = [];
  private capabilityChecked = false;

  protected readonly checkLinearInterpolation = (event: RenderEvent): void => {
    if (this.capabilityChecked) return;
    this.capabilityChecked = true;
    const context = event.context;
    const extensions = 'getSupportedExtensions' in context ? context.getSupportedExtensions() : null;
    if (!extensions?.includes('OES_texture_float_linear')) this.linearInterpolationUnavailable.set(true);
  };

  ngAfterViewInit(): void {
    this.sourceEvents.push(this.terrain.source.on('tileloaderror', () => this.loadFailed.set(true)));
  }

  protected beforeOperations(event: { data: Record<string, unknown>; resolution: number }): void {
    const next = contourInterval(event.resolution);
    event.data['interval'] = next;
    this.interval.set(next);
  }

  protected updatePointer(event: MapBrowserEvent): void {
    const rendered = this.renderedLayer().instance.getData(event.pixel);
    const source = this.sourceDataLayer().instance.getData(event.pixel);
    this.pointer.set({
      rendered: rendered instanceof DataView ? undefined : decodeTerrariumPixel(rendered ?? []),
      source: firstBandValue(source),
    });
  }

  protected formatHeight(value: number | undefined): string {
    return value === undefined || !Number.isFinite(value) ? '—' : `${value.toFixed(1)} m`;
  }

  protected formatInterval(value: number | undefined): string {
    return value === undefined ? '—' : `${value} m`;
  }

  protected retryElevationTiles(): void {
    this.loadFailed.set(false);
    this.terrain.source.refresh();
  }

  ngOnDestroy(): void {
    unByKey(this.sourceEvents);
    this.terrain.dispose();
  }
}

Architecture and OpenLayers mechanics

Each floating-point DataTile stitches a 1-pixel border gutter from surrounding zoom-15 Terrarium PNGs so tile edges interpolate seamlessly without discontinuities. Two WebGL tile layers share that float source: one feeds a SourceRasterComponent running contourOperation (whose contour interval adapts to event.resolution inside beforeOperations), and the second provides interpolated height readback alongside a raw sourceDataLayer getData readout.

A one-time checkLinearInterpolation check inspects WebGL context extensions for OES_texture_float_linear so devices lacking hardware float-linear filtering surface an explicit notice, and ngOnDestroy detaches listeners and disposes of the terrain source cleanly.

How it works

  • Forty-nine local zoom-15 tiles assemble 1-pixel halo gutters from decoded Terrarium PNGs into floating-point elevation DataTiles.
  • Shared WebGL layers feed native Raster contour generation and separate interpolated versus raw getData elevation readouts.
  • beforeOperations adjusts the contour interval dynamically from event.resolution while formatting unavailable readings with an em dash (—).
  • Hardware support for OES_texture_float_linear and tile-load errors are checked explicitly with clean ngOnDestroy disposal.

Pitfalls

  • Never let WebGL bilinearly interpolate raw Terrarium RGB bytes before decoding height: blending [128, 255, 255] (255.996 m) with [129, 0, 0] (256.000 m) produces [128.5, 127.5, 127.5], creating artificial cliff spikes along every 256-metre contour! Always decode to float metres first.
  • When feeding a WebGLTileLayer as an input into OpenLayers’ RasterSource, configure the WebGL layer with singular source (not plural sources) because RasterSource checks readiness via layer.getSource().

The same feature in the OpenLayers examples .

Background: state and lifecycle of maps in Angular with OpenLayers, which the components of cc-openlayers take care of.