Raster, GeoTIFF and WebGL · Angular, React and OpenLayers

Shaded relief computed on the GPU

Compute interactive GPU hillshade relief in OpenLayers WebGLTileLayer by sampling neighbouring Terrarium elevation pixels inside shaders.

OpenStreetMap west of Kraków with the shaded relief over it, exaggerated five times under a sun 30° high: the hills of Las Wolski and Kopiec Piłsudskiego above the Vistula, 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

West of Kraków over the wooded hills of Las Wolski, Kopiec Piłsudskiego and the Vistula river bend at zoom 13, analytical shaded relief ([opacity]="0.3") renders directly on the GPU over OpenStreetMap—responding instantaneously without worker delay as you drag sliders for vertical exaggeration, sun elevation and sun azimuth (starting at 1×, 45° and 45°).

When you need it

GPU fragment-shader hillshading delivers zero-latency interactive terrain lighting during fast pans, continuous pinch-zooms and live sun-angle scrubbing where CPU ImageData workers lag on high-DPI screens.

OpenLayers’ 4-argument band operator lets WebGL expressions sample neighbouring pixels directly inside declarative style JSON without writing raw GLSL.

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.

webgl-shaded-relief.shared.ts
import type { ExpressionValue } from 'ol/expr/expression.js';
import type { Style } from 'ol/layer/WebGLTile.js';

export type Setting = 'vert' | 'sunEl' | 'sunAz';

// 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
//
export function elevation(xOffset: number, yOffset: number): ExpressionValue {
  const red = ['band', 1, xOffset, yOffset];
  const green = ['band', 2, xOffset, yOffset];
  const blue = ['band', 3, xOffset, yOffset];
  // band math operates on normalized values from 0-1
  // so we scale by 255
  return ['+', ['*', 255 * 256, red], ['*', 255, green], ['*', 255 / 256, blue], -32768];
}

// Generates a shaded relief image given elevation data.  Uses a 3x3
// neighborhood for determining slope and aspect.
export const dp = ['*', 2, ['resolution']];
export const z0x = ['*', ['var', 'vert'], elevation(-1, 0)];
export const z1x = ['*', ['var', 'vert'], elevation(1, 0)];
export const dzdx = ['/', ['-', z1x, z0x], dp];
export const z0y = ['*', ['var', 'vert'], elevation(0, -1)];
export const z1y = ['*', ['var', 'vert'], elevation(0, 1)];
export const dzdy = ['/', ['-', z1y, z0y], dp];
export const slope = ['atan', ['sqrt', ['+', ['^', dzdx, 2], ['^', dzdy, 2]]]];
export const aspect = ['clamp', ['atan', ['-', 0, dzdx], dzdy], -Math.PI, Math.PI];
export const sunEl = ['*', Math.PI / 180, ['var', 'sunEl']];
export const sunAz = ['*', Math.PI / 180, ['var', 'sunAz']];

export const cosIncidence = [
  '+',
  ['*', ['sin', sunEl], ['cos', slope]],
  ['*', ['cos', sunEl], ['sin', slope], ['cos', ['-', sunAz, aspect]]],
];
export const scaled = ['*', 255, cosIncidence];

export const STYLE: Style = { color: ['color', scaled] };

export const CONTROLS: { id: Setting; label: string; min: number; max: number; unit: string }[] = [
  { id: 'vert', label: 'vertical exaggeration:', min: 1, max: 5, unit: 'x' },
  { id: 'sunEl', label: 'sun elevation:', min: 0, max: 90, unit: '°' },
  { id: 'sunAz', label: 'sun azimuth:', min: 0, max: 360, unit: '°' },
];
webgl-shaded-relief.ts
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import {
  CoordinateComponent,
  DefaultControlComponent,
  DefaultInteractionComponent,
  LayerTileComponent,
  MapComponent,
  SourceImageTileComponent,
  SourceOsmComponent,
  ViewComponent,
} from 'cc-openlayers';
import { LayerWebGLTileComponent } from 'cc-openlayers/webgl';
import { CONTROLS, type Setting, STYLE } from './webgl-shaded-relief.shared';

/**
 * A shaded relief of the hills of Las Wolski west of Kraków, computed on the GPU from Terrarium elevation tiles over
 * OpenStreetMap: the layer's `color` expression samples each pixel's neighbours for slope and aspect, and the sliders
 * update the style variables for the vertical exaggeration and the sun's elevation and azimuth.
 */
@Component({
  selector: 'app-webgl-shaded-relief',
  imports: [
    CoordinateComponent,
    DefaultControlComponent,
    DefaultInteractionComponent,
    LayerTileComponent,
    LayerWebGLTileComponent,
    MapComponent,
    SourceImageTileComponent,
    SourceOsmComponent,
    ViewComponent,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <aol-map height="480px">
      <aol-interaction-default />
      <aol-control-defaults />
      <aol-view [zoom]="13">
        <aol-coordinate [x]="19.86" [y]="50.055" srid="EPSG:4326" />
      </aol-view>
      <aol-layer-tile><aol-source-osm /></aol-layer-tile>
      <aol-layer-webgltile [opacity]="0.3" [style]="style" [variables]="variables()">
        <aol-source-imagetile
          url="https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png"
          [maxZoom]="15"
          attributions='<a href="https://github.com/tilezen/joerd/blob/master/docs/attribution.md" target="_blank">Data sources and attribution</a>'
        />
      </aol-layer-webgltile>
    </aol-map>
    <div class="example-controls">
      @for (control of controls; track control.id) {
        <label>
          {{ control.label }}
          <input
            type="range"
            [name]="control.id"
            [min]="control.min"
            [max]="control.max"
            [value]="variables()[control.id]"
            (input)="set(control.id, $event)"
          />
          <output>{{ variables()[control.id] }} {{ control.unit }}</output>
        </label>
      }
    </div>
  `,
})
export class WebglShadedRelief {
  readonly variables = signal<Record<Setting, number>>({ vert: 1, sunEl: 45, sunAz: 45 });
  protected readonly style = STYLE;
  protected readonly controls = CONTROLS;

  protected set(setting: Setting, event: Event): void {
    const value = Number((event.target as HTMLInputElement).value);
    this.variables.update((variables) => ({ ...variables, [setting]: value }));
  }
}

Architecture and OpenLayers mechanics

Helper elevation(xOffset, yOffset) decodes Terrarium heights at integer pixel offsets (-1, 0), (+1, 0), (0, -1) and (0, +1) using ['band', 1, xOffset, yOffset] (and bands 2 and 3). Finite-difference gradients dzdx and dzdy multiply height differences by ['var', 'vert'] divided by dp (twice the built-in resolution), deriving slope, aspect and solar incidence scaled (0..255) inside { color: ['color', scaled] }.

[variables]="variables()" streams vert, sunEl and sunAz directly to shader uniforms.

How it works

  • The WebGL style outputs { color: ['color', scaled] } where scaled scales the cosine of solar incidence onto 0..255.
  • elevation samples neighbouring pixels via ['band', 1, xOffset, yOffset] (and bands 2–3) to decode local heights on the GPU.
  • dzdx and dzdy divide ['var', 'vert']-scaled height differences by dp (twice the built-in resolution) to compute terrain slope and aspect.
  • [variables]="variables()" updates vert, sunEl and sunAz (initialised to 1, 45, 45) at [opacity]="0.3" over OpenStreetMap.

Pitfalls

  • Built-in ['resolution'] reports Web Mercator projection units per pixel, making raw gradients ~0.64× as steep as true ground metres at Kraków’s 50° N latitude unless compensated in vert.
  • Always keep the complex hillshade expression static in [style] and pass slider values via [variables] so dragging sun sliders never triggers expensive shader recompilation.

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.