Raster, GeoTIFF and WebGL · Angular, React and OpenLayers

Shaded relief computed on the CPU

Compute interactive hillshade relief over Ojców’s Prądnik gorge on the CPU from Terrarium DEM tiles using an OpenLayers image RasterSource UI.

OpenStreetMap of Ojców with the shaded relief over it, exaggerated five times under a sun 30° high: the deep Prądnik gorge and its side valleys among the woods, and the three sliders below.
A screenshot of the example. Elevation: Terrain Tiles on AWS (Mapzen); Europe terrain data produced using Copernicus data and information funded by the European Union - EU-DEM layers; global GMTED2010 and SRTM terrain data courtesy of the U.S. Geological Survey. Map data © OpenStreetMap contributors.

What this example shows

Zoomed to level 14 over Ojców National Park north of Kraków, dynamic shaded relief draped at 30% opacity ([opacity]="0.3") over OpenStreetMap brings the steep limestone cliffs of the Prądnik gorge and tributary ravines into crisp 3D focus, controlled live by sliders for vertical exaggeration, sun elevation and sun azimuth.

When you need it

Geomorphologists, trail designers, archaeologists and forestry planners adjust virtual sun azimuth and elevation interactively to reveal subtle ridges, quarries or fault scarps that fixed north-west hillshades hide.

Computing analytical hillshade from raw elevation tiles in the browser replaces static pre-rendered hillshade WMS layers with a fully steerable light source.

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.

shaded-relief.shared.ts
/**
 * Generates a shaded relief image given elevation data.  Uses a 3x3
 * neighborhood for determining slope and aspect.
 * @param inputs Array of input images.
 * @param data Data added in the "beforeoperations" event.
 * @return Output image.
 */
export function shade(inputs: (number[] | ImageData)[], data: object): ImageData {
  const { resolution, vert, sunEl: elevation, sunAz: azimuth } = data as Record<string, number>;
  const elevationImage = inputs[0] as ImageData;
  const width = elevationImage.width;
  const height = elevationImage.height;
  const elevationData = elevationImage.data;
  const shadeData = new Uint8ClampedArray(elevationData.length);
  const dp = resolution * 2;
  const maxX = width - 1;
  const maxY = height - 1;
  const pixel = [0, 0, 0, 0];
  const twoPi = 2 * Math.PI;
  const halfPi = Math.PI / 2;
  const sunEl = (Math.PI * elevation) / 180;
  const sunAz = (Math.PI * azimuth) / 180;
  const cosSunEl = Math.cos(sunEl);
  const sinSunEl = Math.sin(sunEl);
  let pixelX, pixelY, x0, x1, y0, y1, offset, z0, z1, dzdx, dzdy, slope, aspect, cosIncidence, scaled;
  function calculateElevation(pixel: number[]) {
    // The method used to extract elevations from the DEM.
    // In this case the format used is Terrarium
    // red * 256 + green + blue / 256 - 32768
    //
    // Other frequently used methods include the Mapbox format
    // (red * 256 * 256 + green * 256 + blue) * 0.1 - 10000
    //
    return pixel[0] * 256 + pixel[1] + pixel[2] / 256 - 32768;
  }
  for (pixelY = 0; pixelY <= maxY; ++pixelY) {
    y0 = pixelY === 0 ? 0 : pixelY - 1;
    y1 = pixelY === maxY ? maxY : pixelY + 1;
    for (pixelX = 0; pixelX <= maxX; ++pixelX) {
      x0 = pixelX === 0 ? 0 : pixelX - 1;
      x1 = pixelX === maxX ? maxX : pixelX + 1;

      // determine elevation for (x0, pixelY)
      offset = (pixelY * width + x0) * 4;
      pixel[0] = elevationData[offset];
      pixel[1] = elevationData[offset + 1];
      pixel[2] = elevationData[offset + 2];
      pixel[3] = elevationData[offset + 3];
      z0 = vert * calculateElevation(pixel);

      // determine elevation for (x1, pixelY)
      offset = (pixelY * width + x1) * 4;
      pixel[0] = elevationData[offset];
      pixel[1] = elevationData[offset + 1];
      pixel[2] = elevationData[offset + 2];
      pixel[3] = elevationData[offset + 3];
      z1 = vert * calculateElevation(pixel);

      dzdx = (z1 - z0) / dp;

      // determine elevation for (pixelX, y0)
      offset = (y0 * width + pixelX) * 4;
      pixel[0] = elevationData[offset];
      pixel[1] = elevationData[offset + 1];
      pixel[2] = elevationData[offset + 2];
      pixel[3] = elevationData[offset + 3];
      z0 = vert * calculateElevation(pixel);

      // determine elevation for (pixelX, y1)
      offset = (y1 * width + pixelX) * 4;
      pixel[0] = elevationData[offset];
      pixel[1] = elevationData[offset + 1];
      pixel[2] = elevationData[offset + 2];
      pixel[3] = elevationData[offset + 3];
      z1 = vert * calculateElevation(pixel);

      dzdy = (z1 - z0) / dp;

      slope = Math.atan(Math.sqrt(dzdx * dzdx + dzdy * dzdy));

      aspect = Math.atan2(dzdy, -dzdx);
      if (aspect < 0) {
        aspect = halfPi - aspect;
      } else if (aspect > halfPi) {
        aspect = twoPi - aspect + halfPi;
      } else {
        aspect = halfPi - aspect;
      }

      cosIncidence = sinSunEl * Math.cos(slope) + cosSunEl * Math.sin(slope) * Math.cos(sunAz - aspect);

      offset = (pixelY * width + pixelX) * 4;
      scaled = 255 * cosIncidence;
      shadeData[offset] = scaled;
      shadeData[offset + 1] = scaled;
      shadeData[offset + 2] = scaled;
      shadeData[offset + 3] = elevationData[offset + 3];
    }
  }

  return {
    data: shadeData,
    width,
    height,
    colorSpace: 'srgb',
  } as ImageData;
}

/** A range control: its name, label, range and start, and the unit its value is shown in. */
export interface Control {
  name: 'vert' | 'sunEl' | 'sunAz';
  label: string;
  min: number;
  max: number;
  start: number;
  unit: string;
}

export const CONTROLS: Control[] = [
  { name: 'vert', label: 'vertical exaggeration:', min: 1, max: 5, start: 1, unit: 'x' },
  { name: 'sunEl', label: 'sun elevation:', min: 0, max: 90, start: 45, unit: '°' },
  { name: 'sunAz', label: 'sun azimuth:', min: 0, max: 360, start: 45, unit: '°' },
];

export const ATTRIBUTIONS =
  'Elevation: <a href="https://github.com/tilezen/joerd/blob/master/docs/attribution.md" target="_blank">Terrain Tiles</a>';
shaded-relief.ts
import { ChangeDetectionStrategy, Component, signal, viewChild } from '@angular/core';
import type { RasterSourceEvent } from 'ol/source/Raster';
import {
  CoordinateComponent,
  DefaultControlComponent,
  DefaultInteractionComponent,
  LayerImageComponent,
  LayerTileComponent,
  MapComponent,
  SourceImageTileComponent,
  SourceOsmComponent,
  SourceRasterComponent,
  ViewComponent,
} from 'cc-openlayers';
import { ATTRIBUTIONS, CONTROLS, type Control, shade } from './shaded-relief.shared';

/**
 * A shaded relief computed on the CPU by a raster source from Terrarium elevation tiles: the gorge of the Prądnik at
 * Ojców, north of Kraków, with its limestone rocks, laid over OpenStreetMap. The sliders set the vertical
 * exaggeration and the sun's elevation and azimuth, which the source passes to its operation before each frame.
 */
@Component({
  selector: 'app-shaded-relief',
  imports: [
    CoordinateComponent,
    DefaultControlComponent,
    DefaultInteractionComponent,
    LayerImageComponent,
    LayerTileComponent,
    MapComponent,
    SourceImageTileComponent,
    SourceOsmComponent,
    SourceRasterComponent,
    ViewComponent,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <aol-map height="480px">
      <aol-interaction-default />
      <aol-control-defaults />
      <aol-view [zoom]="14">
        <aol-coordinate [x]="19.8291" [y]="50.2097" srid="EPSG:4326" />
      </aol-view>
      <aol-layer-tile><aol-source-osm /></aol-layer-tile>
      <aol-layer-image [opacity]="0.3">
        <aol-source-raster operationType="image" [operation]="operation" (beforeOperations)="beforeOperations($event)">
          <aol-source-imagetile
            url="https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png"
            [maxZoom]="15"
            [attributions]="attributions"
          />
        </aol-source-raster>
      </aol-layer-image>
    </aol-map>
    <div class="example-controls">
      @for (control of controls; track control.name) {
        <label>
          {{ control.label }}
          <input
            type="range"
            [name]="control.name"
            [min]="control.min"
            [max]="control.max"
            [value]="values()[control.name]"
            (input)="set(control.name, $event)"
          />
          <output>{{ values()[control.name] }}</output>
          {{ control.unit }}
        </label>
      }
    </div>
  `,
})
export class ShadedRelief {
  protected readonly attributions = ATTRIBUTIONS;
  protected readonly operation = shade;
  protected readonly controls = CONTROLS;
  protected readonly values = signal(Object.fromEntries(CONTROLS.map((control) => [control.name, control.start])));
  private readonly raster = viewChild.required(SourceRasterComponent);

  protected set(name: Control['name'], event: Event): void {
    const value = Number((event.target as HTMLInputElement).value);
    this.values.update((values) => ({ ...values, [name]: value }));
    this.raster().instance.changed();
  }

  /** The event's data object is passed to the operation. */
  protected beforeOperations(event: RasterSourceEvent): void {
    const data = event.data;
    data.resolution = event.resolution;
    for (const [name, value] of Object.entries(this.values())) {
      data[name] = value;
    }
  }
}

Architecture and OpenLayers mechanics

aol-source-raster runs in whole-frame operationType="image" mode over aol-source-imagetile (which fetches Terrarium PNGs up to [maxZoom]="15" with CORS enabled by default). Before each pass, (beforeOperations) injects event.resolution alongside the three slider settings into event.data.

Worker function shade decodes heights scaled by vert, estimates east-west and north-south slope and aspect across the four cardinal neighbour pixels (2 * resolution span), and writes the Lambertian cosine of solar incidence as greyscale shading.

How it works

  • aol-source-raster with operationType="image" passes full ImageData frames from Terrarium tiles to shade.
  • shade decodes neighbour heights scaled by vert, derives slope and aspect across 2 × resolution, and computes solar incidence shading.
  • (beforeOperations) forwards event.resolution and the three illumination slider values, rendered at [opacity]="0.3" over OpenStreetMap.
  • aol-source-imagetile enables anonymous CORS by default so the raster worker can read decoded tile pixels.

Pitfalls

  • event.resolution is reported in Web Mercator units—roughly 1.56× true ground metres at 50° N latitude—which makes uncompensated slopes appear ~0.64× flatter unless compensated or boosted via vertical exaggeration.
  • If you swap aol-source-imagetile for aol-source-xyz, remember to add crossOrigin="anonymous" explicitly so pixel reads are not blocked by CORS.

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.