dem2hm

package module
v1.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 28, 2026 License: MIT Imports: 11 Imported by: 3 modules, 6 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

dem2hm

dem2hm converts a digital elevation model (DEM) into a compact integer heightmap designed for direct use by Go programs. By default it writes format version 1.1: elevations in meters with the source georeference and provenance. The frozen version 1 format of normalized pixels remains available.

Usage

Run the application through Cargo from the repository root:

cargo run --release -- [OPTIONS] <INPUT> <OUTPUT>

After installing it with cargo install --path ., invoke the executable directly:

dem2hm [OPTIONS] <INPUT> <OUTPUT>

The input must be a single-image, single-band GeoTIFF with signed 8-, 16-, 32-, or 64-bit integer samples. If the GeoTIFF declares a GDAL_NODATA value, those pixels are encoded with the heightmap no-data sentinel and excluded when finding the elevation range.

Format 1.1 also requires:

  • a geographic (longitude and latitude in degrees) GeoTIFF georeference, given by one ModelTiepoint plus ModelPixelScale, or by an unrotated ModelTransformation. Projected rasters, rotated rasters and world files are not supported.
  • every valid elevation to fit in -32767..=32767 meters. -32768 is reserved for no-data, so a source value that doesn't fit, including a valid -32768, is rejected rather than clamped. A declared no-data value may be any integer.

Arguments:

  • <INPUT> is the source GeoTIFF DEM.
  • <OUTPUT> is the gzip-compressed heightmap file to create. Use the .hmz extension; its parent directory must already exist.

Options:

  • --format <1|1.1> selects the heightmap format. The default is 1.1.
  • --rotate <0|90|180|270> rotates clockwise. The default is 0.
  • --flip-horizontal flips the rotated raster left-to-right.
  • --flip-vertical flips the rotated raster top-to-bottom.
  • --vertical-datum <NAME> records the vertical datum, for example EGM96, when the GeoTIFF keys do not declare one. A datum declared in the GeoTIFF takes precedence. Format 1.1 only.
  • -h, --help prints command-line help.
  • -V, --version prints the application version.

Rotation is applied first. Flips are then applied in output coordinates, so they always describe the final image's horizontal and vertical axes.

Panama DEM

From the repository root, this exact command reads ../dem/Pma_DEM_30m.tif, rotates it 90 degrees clockwise and writes ../var/pandemokh.hmz. The ALOS AW3D30 source measures heights above the EGM96 geoid but does not declare it in its GeoTIFF keys, so the command records it explicitly:

cargo run --release -- --rotate 90 --vertical-datum EGM96 ../dem/Pma_DEM_30m.tif ../var/pandemokh.hmz

The ../var directory must exist before running the command.

The converter scans the TIFF once to find valid minimum and maximum elevations, hashes the input file, then decodes and transforms one TIFF strip or tile at a time into a temporary payload. It finally streams that payload through gzip into the output file. It does not load the complete raster into memory.

Heightmap format, version 1.1

Version 1.1 stores elevations in meters with the metadata needed to place them on the Earth. It is a separate format with its own magic value; it does not change how version 1 files are read.

The output is an 8-byte raw header, a UTF-8 JSON metadata block, and one gzip member containing an int16 for every output pixel:

Byte offset Type Meaning
0 int32 Magic value 0x0108AAFE
4 int32 Metadata length n in bytes, 1..=1048576
8 UTF-8 JSON Metadata object, exactly n bytes
8 + n gzip stream height * width int16 elevations in meters

Every integer in the raw header and decompressed payload uses little-endian two's-complement byte order, so the file starts with bytes FE AA 08 01. The gzip stream starts immediately after the metadata with bytes 1F 8B. Pixel data is row-major, as in version 1: pixel (x, y) is sample y * width + x. The decompressed payload is exactly height * width * 2 bytes.

Elevations are the source values, unscaled. Sea level is 0, so a pixel is above sea level when its value is > 0. The reserved value -32768 marks a no-data pixel: one outside the source data. It does not mean sea. A DEM cut to a political border uses no-data for neighboring land too, so each application decides whether no-data is sea, off-map land or something else.

The metadata is one JSON object. The converter writes keys in the order shown, in compact form, making output deterministic. Readers must ignore unknown keys, so later writers can add metadata.

{
  "height": 21307,
  "width": 8868,
  "elevation": {"minimum": -37, "maximum": 3431, "vertical_datum": "EGM96"},
  "pixel_size_m": 30.72168914643369,
  "source": {
    "file_name": "Pma_DEM_30m.tif",
    "sha256": "e00cccc404d88c1f5bd2a57b5e4d78959c9c789173193c475a9e3152a091f42c",
    "width": 21307,
    "height": 8868,
    "no_data": 32767,
    "geotransform": [-83.05972222222222, 0.00027777777777777745, 0.0, 9.650555555555552, 0.0, -0.00027777777777777745]
  },
  "transform": {"rotate": 90, "flip_horizontal": false, "flip_vertical": false},
  "dem2hm_version": "1.1.0"
}
Key Meaning
height, width Output raster dimensions; positive int32 values.
elevation.minimum, elevation.maximum Range of valid elevations in meters.
elevation.vertical_datum The GeoTIFF's vertical coordinate system as EPSG:<code> or its citation, else the --vertical-datum value, else null.
pixel_size_m Nominal ground size of one pixel in meters: the north–south size at the source's center latitude on the WGS 84 ellipsoid. East–west size is smaller by the cosine of the latitude.
source.file_name, source.sha256 Base name and lowercase hex SHA-256 of the source file.
source.width, source.height Source raster dimensions.
source.no_data Source GDAL_NODATA value, or null if none was declared.
source.geotransform GDAL-style affine transform from the top-left corner of source pixel (column, row) to degrees: lon = g[0] + column * g[1] + row * g[2], lat = g[3] + column * g[4] + row * g[5]. A PixelIsPoint GeoTIFF is shifted by half a pixel to this convention.
transform.rotate Clockwise rotation in degrees: 0, 90, 180 or 270.
transform.flip_horizontal, transform.flip_vertical Flips applied after rotation, in output coordinates.
dem2hm_version Version of the converter that wrote the file.

To map output pixel (x, y) to the source, undo the flips (x = width - 1 - x, y = height - 1 - y), then the rotation, with W and H the source width and height:

rotate Source column Source row
0 x y
90 y H - 1 - x
180 W - 1 - x H - 1 - y
270 W - 1 - y x

Apply the geotransform to column + 0.5, row + 0.5 for the pixel's center.

Heightmap format, version 1 (frozen)

The version 1 wire format is frozen. Existing version 1 files will not be reinterpreted if the format evolves; an incompatible future format will use a new version and magic value.

The output is a raw 12-byte header followed immediately by one gzip member containing an int32 for every output pixel:

Byte offset Type Meaning
0 int32 Magic value 0x0108AAFF
4 int32 Height in rows
8 int32 Width in columns
12 gzip stream height * width normalized int32 pixels

Every integer in both the raw header and decompressed payload uses little-endian byte order. Thus, the first four bytes are FF AA 08 01. The gzip stream starts at byte 12 with bytes 1F 8B. Go can decode the payload with its standard compress/gzip package and decode the integers portably with encoding/binary.LittleEndian.

Pixel data is row-major, with each row written left-to-right from the top of the raster. Pixel (x, y) is stored at sample index:

y * width + x

Valid elevations are linearly normalized to 0..2147483647:

round((elevation - min) * 2147483647 / (max - min))

The reserved value -2147483648 marks a no-data pixel. The decompressed gzip payload has no padding or trailer, so its exact size is:

height * width * 4 bytes

The complete file size depends on the gzip compression ratio. The gzip header uses a zero modification time, making repeated conversions of identical input deterministic.

If every valid pixel has the same elevation, all valid pixels are written as 0 because the normalization span is zero.

Go module

This repository includes the Go module github.com/maloquacious/dem2hm, which provides the canonical heightmap reader so applications do not need to implement and test their own decoder.

  • ReadHeightMap16 reads a version 1.1 stream and returns a *HeightMap16: elevations in a flat row-major []int16 and the decoded Metadata.
  • ReadHeightMap reads a version 1 stream and returns a *HeightMap of normalized pixels in a flat row-major []int32. Read forwards to it.

Each reader validates the complete stream and rejects the other version's magic value. Both types provide the same accessors: Pixel gives bounds-checked access with an error, At is a fast path that panics on out-of-bounds coordinates, and Row returns a bounds-checked view into the heightmap's backing data. HeightMap16 also provides SourcePixel, which maps an output pixel to its source column and row, and LonLat, which returns the longitude and latitude of its center.

Reading a heightmap in Go

heightmap, err := dem2hm.ReadHeightMap16(r)
if err != nil {
	return err
}
elevation, err := heightmap.Pixel(x, y)
if err != nil {
	return err
}
switch {
case elevation == dem2hm.NoDataPixel16:
	// Outside the source data: the application decides what this means.
case elevation > 0:
	// Above sea level.
}
lon, lat, err := heightmap.LonLat(x, y)

Malformed-input and bounds errors wrap exported constant errors, allowing callers to use errors.Is while retaining a detailed error message.

Malicious inputs

compress/gzip validates stream structure, CRC, and decompressed size, but it does not impose decompressed-size, compression-ratio, CPU-time, or elapsed-time limits. The readers validate dimensions and read exactly the declared payload, but their unrestricted APIs assume the input is trusted because declared dimensions determine the final pixel allocation. A version 1.1 metadata block is limited to 1 MiB (MaxMetadataSize).

Applications accepting untrusted files should call ReadHeightMap16WithOptions or ReadHeightMapWithOptions, set MaxPixels to an application-appropriate allocation ceiling, and pass the request or operation context:

heightmap, err := dem2hm.ReadHeightMap16WithOptions(r, dem2hm.Options{
	Context:   req.Context(),
	MaxPixels: 100_000_000,
})

The context is checked during header, metadata and compressed-stream reads. As with all APIs built on io.Reader, cancellation cannot interrupt a reader already blocked inside its Read method unless that source also supports cancellation, deadlines, or closure. HTTP handlers should use the request context, wrap the request body with http.MaxBytesReader to cap compressed input, and retain the server's normal timeout limits. Non-HTTP callers should apply an equivalent input-byte limit when the source is untrusted.

Input trust

The Rust converter is intended only for trusted TIFF inputs. It validates the TIFF structure and supported sample format, but it is not a sandbox and does not impose security-oriented file-size, memory, CPU, or elapsed-time limits. Do not expose the converter directly to untrusted uploads without enforcing those limits outside the process.

The intended upstream repository is https://github.com/maloquacious/dem2hm.

Authors

  • Michael D. Henderson
  • Amp

Documentation

Overview

Package dem2hm reads heightmaps produced by the dem2hm converter.

Index

Examples

Constants

View Source
const (

	// MaxMetadataSize is the largest version 1.1 JSON metadata block in bytes.
	MaxMetadataSize = 1 << 20

	// NoDataPixel16 marks a version 1.1 pixel outside the source data. It
	// does not imply sea; the application decides what such a pixel means.
	NoDataPixel16 int16 = -32768
)
View Source
const (

	// NoDataPixel is the value reserved for a pixel with no elevation data.
	NoDataPixel int32 = -2147483648

	// ErrInvalidByteOrder indicates that the file does not start with the
	// expected magic value in little-endian byte order.
	ErrInvalidByteOrder = Error("invalid heightmap byte order or format")
	// ErrInvalidHeader indicates that the heightmap header is incomplete or,
	// for version 1.1, declares an invalid metadata length.
	ErrInvalidHeader = Error("invalid heightmap header")
	// ErrInvalidMetadata indicates that the version 1.1 JSON metadata block is
	// not valid UTF-8 JSON or does not describe a consistent heightmap.
	ErrInvalidMetadata = Error("invalid heightmap metadata")
	// ErrInvalidDimensions indicates that the height or width is not positive,
	// or that the resulting payload size cannot be represented safely.
	ErrInvalidDimensions = Error("invalid heightmap dimensions")
	// ErrInvalidGzip indicates that the payload is not a valid gzip stream.
	ErrInvalidGzip = Error("invalid heightmap gzip stream")
	// ErrInvalidPayload indicates that the decompressed pixel payload does not
	// conform to the heightmap format.
	ErrInvalidPayload = Error("invalid heightmap payload")
	// ErrMultipleGzipMembers indicates that a second gzip member follows the
	// required payload member.
	ErrMultipleGzipMembers = Error("multiple gzip members")
	// ErrTrailingData indicates that data follows the single gzip member.
	ErrTrailingData = Error("trailing heightmap data")
	// ErrOutOfBounds indicates that a requested pixel or row is outside the map.
	ErrOutOfBounds = Error("heightmap coordinates out of bounds")
	// ErrLimitExceeded indicates that the heightmap exceeds a configured limit.
	ErrLimitExceeded = Error("heightmap resource limit exceeded")
	// ErrCanceled indicates that reading was canceled or its deadline expired.
	ErrCanceled = Error("heightmap read canceled")
)

Variables

This section is empty.

Functions

func Version

func Version() semver.Version

Types

type ElevationMetadata added in v1.1.0

type ElevationMetadata struct {
	Minimum int16 `json:"minimum"`
	Maximum int16 `json:"maximum"`
	// VerticalDatum is the datum elevations are measured from, such as
	// "EGM96" or "EPSG:5773", or nil when unknown.
	VerticalDatum *string `json:"vertical_datum"`
}

ElevationMetadata summarizes the valid elevations in meters.

type Error

type Error string

Error defines a constant error

func (Error) Error

func (e Error) Error() string

Error implements the Errors interface

type HeightMap

type HeightMap struct {
	Height int
	Width  int
	Data   []int32
}

HeightMap is a normalized raster stored in top-to-bottom row-major order.

func Read

func Read(r io.Reader) (*HeightMap, error)

Read reads a version 1 heightmap from r. It forwards to ReadHeightMap.

Example
package main

import (
	"bytes"
	"fmt"

	_ "embed"
	"github.com/maloquacious/dem2hm"
)

//go:embed testdata/example.hmz
var exampleHMZ []byte

func main() {
	heightmap, err := dem2hm.Read(bytes.NewReader(exampleHMZ))
	if err != nil {
		fmt.Println("error:", err)
		return
	}

	emptyPixels := 0
	for _, pixel := range heightmap.Data {
		if pixel == dem2hm.NoDataPixel {
			emptyPixels++
		}
	}

	fmt.Println("height:", heightmap.Height)
	fmt.Println("width:", heightmap.Width)
	fmt.Println("empty pixels:", emptyPixels)

}
Output:
height: 2
width: 3
empty pixels: 2

func ReadHeightMap added in v1.1.0

func ReadHeightMap(r io.Reader) (*HeightMap, error)

ReadHeightMap reads a version 1 heightmap from r without an application-defined resource limit or cancellation context.

func ReadHeightMapWithOptions added in v1.1.0

func ReadHeightMapWithOptions(r io.Reader, options Options) (*HeightMap, error)

ReadHeightMapWithOptions reads a version 1 heightmap from r using options.

func ReadWithOptions

func ReadWithOptions(r io.Reader, options Options) (*HeightMap, error)

ReadWithOptions reads a version 1 heightmap from r using options. It forwards to ReadHeightMapWithOptions.

func (*HeightMap) At

func (hm *HeightMap) At(x, y int) int32

At returns the pixel at column x and row y. It panics if the coordinates are outside the heightmap.

func (*HeightMap) Pixel

func (hm *HeightMap) Pixel(x, y int) (int32, error)

Pixel returns the pixel at column x and row y.

func (*HeightMap) Row

func (hm *HeightMap) Row(y int) ([]int32, error)

Row returns row y as a view into the heightmap's backing data. Changes to the returned slice change the heightmap.

type HeightMap16 added in v1.1.0

type HeightMap16 struct {
	Height   int
	Width    int
	Metadata Metadata
	Data     []int16
}

HeightMap16 is a raster of elevations in meters, stored in top-to-bottom row-major order, with the metadata recorded by the converter.

func ReadHeightMap16 added in v1.1.0

func ReadHeightMap16(r io.Reader) (*HeightMap16, error)

ReadHeightMap16 reads a version 1.1 heightmap from r without an application-defined resource limit or cancellation context.

Example
package main

import (
	"bytes"
	"fmt"

	_ "embed"
	"github.com/maloquacious/dem2hm"
)

//go:embed testdata/example16.hmz
var example16HMZ []byte

func main() {
	heightmap, err := dem2hm.ReadHeightMap16(bytes.NewReader(example16HMZ))
	if err != nil {
		fmt.Println("error:", err)
		return
	}

	aboveSeaLevel, outsideSource := 0, 0
	for _, elevation := range heightmap.Data {
		switch {
		case elevation == dem2hm.NoDataPixel16:
			outsideSource++
		case elevation > 0:
			aboveSeaLevel++
		}
	}
	lon, lat, err := heightmap.LonLat(1, 1)
	if err != nil {
		fmt.Println("error:", err)
		return
	}

	fmt.Println("height:", heightmap.Height)
	fmt.Println("width:", heightmap.Width)
	fmt.Println("elevation (1, 1):", heightmap.At(1, 1), "m")
	fmt.Println("above sea level:", aboveSeaLevel)
	fmt.Println("outside source:", outsideSource)
	fmt.Println("vertical datum:", *heightmap.Metadata.Elevation.VerticalDatum)
	fmt.Printf("center of (1, 1): %.3f, %.3f\n", lon, lat)

}
Output:
height: 2
width: 3
elevation (1, 1): 1830 m
above sea level: 2
outside source: 2
vertical datum: EGM96
center of (1, 1): -79.625, 8.625

func ReadHeightMap16WithOptions added in v1.1.0

func ReadHeightMap16WithOptions(r io.Reader, options Options) (*HeightMap16, error)

ReadHeightMap16WithOptions reads a version 1.1 heightmap from r using options.

func (*HeightMap16) At added in v1.1.0

func (hm *HeightMap16) At(x, y int) int16

At returns the elevation at column x and row y. It panics if the coordinates are outside the heightmap.

func (*HeightMap16) LonLat added in v1.1.0

func (hm *HeightMap16) LonLat(x, y int) (float64, float64, error)

LonLat returns the longitude and latitude in degrees of the center of output pixel (x, y).

func (*HeightMap16) Pixel added in v1.1.0

func (hm *HeightMap16) Pixel(x, y int) (int16, error)

Pixel returns the elevation at column x and row y.

func (*HeightMap16) Row added in v1.1.0

func (hm *HeightMap16) Row(y int) ([]int16, error)

Row returns row y as a view into the heightmap's backing data. Changes to the returned slice change the heightmap.

func (*HeightMap16) SourcePixel added in v1.1.0

func (hm *HeightMap16) SourcePixel(x, y int) (int, int, error)

SourcePixel returns the source GeoTIFF column and row of output pixel (x, y).

type Metadata added in v1.1.0

type Metadata struct {
	// Height and Width are the output raster dimensions.
	Height int32 `json:"height"`
	Width  int32 `json:"width"`
	// Elevation summarizes the valid elevations.
	Elevation ElevationMetadata `json:"elevation"`
	// PixelSizeMeters is the nominal north–south ground size of one pixel at
	// the source raster's center latitude on the WGS 84 ellipsoid.
	PixelSizeMeters float64 `json:"pixel_size_m"`
	// Source describes the GeoTIFF the heightmap was converted from.
	Source SourceMetadata `json:"source"`
	// Transform is the rotation and flips applied to the source raster.
	Transform TransformMetadata `json:"transform"`
	// Dem2hmVersion is the version of the converter that wrote the file.
	Dem2hmVersion string `json:"dem2hm_version"`
}

Metadata is the version 1.1 JSON metadata block.

type Options

type Options struct {
	// Context is checked while reading and decoding. A nil Context is treated
	// as context.Background(). Cancellation cannot interrupt an underlying
	// io.Reader blocked in Read unless that reader also honors cancellation,
	// deadlines, or closure.
	Context context.Context
	// MaxPixels is the largest decoded heightmap to accept. Zero disables the
	// additional limit; format and address-space limits still apply.
	MaxPixels uint64
}

Options controls resource use while reading a heightmap.

type SourceMetadata added in v1.1.0

type SourceMetadata struct {
	FileName string `json:"file_name"`
	SHA256   string `json:"sha256"`
	Width    int32  `json:"width"`
	Height   int32  `json:"height"`
	// NoData is the source's declared no-data value, or nil if it had none.
	NoData *int64 `json:"no_data"`
	// GeoTransform maps the top-left corner of source pixel (column, row) to
	// degrees: longitude = g[0] + column*g[1] + row*g[2] and
	// latitude = g[3] + column*g[4] + row*g[5].
	GeoTransform [6]float64 `json:"geotransform"`
}

SourceMetadata describes the source GeoTIFF.

type TransformMetadata added in v1.1.0

type TransformMetadata struct {
	Rotate         int  `json:"rotate"`
	FlipHorizontal bool `json:"flip_horizontal"`
	FlipVertical   bool `json:"flip_vertical"`
}

TransformMetadata is the transformation from source to output pixels: a clockwise rotation, followed by flips in output coordinates.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL