hmz2riv

package module
v0.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: 4 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

hmz2riv

hmz2riv extracts rivers from a dem2hm heightmap (format 1.1) at full resolution and snaps them to the edges of the flat-top hex grid used by hmz2ele. It writes the river edges as JSON, with optional full-resolution river lines and a PNG preview.

Usage

go run ./cmd/hmz2riv [flags] <input.hmz>

Flags:

  • -apothem <px> sets the hex apothem in raster pixels. The default is 48.
  • -threshold <km²> sets the drainage area, in km² of source ground, that makes a river. The default is 50.
  • -barrier <lon1,lat1,lon2,lat2,height> adds a wall that water cannot cross. Repeatable. See Barriers.
  • -output <file> is the JSON file for the river edges. Required.
  • -lines <file> is a JSON file for the full-resolution river lines. Optional.
  • -preview <file> is a PNG preview to write: the hmz2ele hex preview with rivers drawn along hex edges. Optional.
  • -preview-scale <n> sets how many raster pixels, in each direction, one preview pixel covers. The default is 8.
  • -preview-lines also draws the full-resolution river lines, in light blue, under the snapped rivers.
  • -trace <lon,lat> prints where water starting at that point leaves the map. Repeatable. Useful for checking barriers.
  • -version prints the version.

The command prints the time taken by each phase and a summary. A full run on the Panama heightmap (189 million pixels) takes about 14 seconds and 4.3 GB of memory.

Method

  1. Barriers. Each barrier raises the valid pixels within 1.5 pixels of its line to at least its height.
  2. Depression filling. A priority flood, seeded from every valid pixel on the raster edge or next to a no-data pixel, raises each closed basin to its lowest spill point. Elevations are whole meters, so the priority queue is one FIFO bucket per meter.
  3. Flow directions. Pixels on the raster edge or next to no-data drain off the map. Every other pixel drains to its steepest downhill neighbor among its 8 neighbors, allowing for diagonal neighbors being √2 times farther away.
  4. Flats. Pixels with no downhill neighbor are routed with the method of Barnes, Lehman, and Mulla (2014), "An efficient assignment of drainage direction over flat surfaces in raster digital elevation models": within each flat, water flows toward the flat's outlets and away from the higher ground around it.
  5. Drainage area. Each pixel's drainage area is the number of pixels that drain through it, itself included, times the heightmap's pixel area (pixel_size_m squared).
  6. River links. Pixels whose drainage area meets the threshold are river pixels. They are split into links, each running from a source or a confluence down to the next confluence or to where the river leaves the map.
  7. Snapping. Links are snapped in decreasing order of drainage area at their downstream end, so each river is placed before its tributaries. Each pixel moves to its nearest hex vertex; gaps between consecutive vertices are filled with the shortest path along hex edges, and loops are cut out. A link stops at the first vertex already in the network, which is where it joins the river it flows into.

The result is a network in which every vertex has at most one outflow and every path leads to a river mouth.

Barriers

A barrier undoes earthworks that would otherwise shape the drainage. For the Panama heightmap, this barrier dams the Culebra Cut of the Panama Canal at its highest point, restoring the continental divide:

-barrier=-79.6323,9.0652,-79.6599,9.0412,100

The line is about 4 km long and ends on ground above 120 m on both banks; 100 m is well above the lake levels on either side (about 26 m). Without it, the divide still exists, but falls wherever flat resolution happens to split the canal's water surface, about 2 km south of the saddle.

Output

drainage_km2 is in km² of source (real-world) ground.

{
  "hmz2riv_version": "0.1.0",
  "heightmap": { "file_name": "pandemokh.hmz", "metadata": { ... } },
  "grid": { "apothem_px": 48, "side_px": 55.43, "columns": 106, "rows": 222 },
  "hydrology": { "threshold_km2": 50, "pixel_area_m2": 943.8, "threshold_pixels": 52977, "barriers": [ "..." ], "method": "..." },
  "stats": { "barrier_pixels": 291, "filled_pixels": 1728, "flat_pixels": 12506022, "links": 758, "mouths": 132, "river_edges": 4667 },
  "edges": [
    { "col": 91, "row": 9, "side": "ne", "from": { "col": 92, "row": 8, "corner": "west" }, "to": { "col": 91, "row": 9, "corner": "east" }, "drainage_km2": 252.5 },
    ...
  ]
}

Each edge is identified by the hex that owns it and the side (n, ne, or se), following the hmz2ele ownership rules; water flows from from to to. Vertices are identified by the hex that owns them and the corner (west or east). Edges are ordered by owner row, column, and side.

The optional lines file lists each link as raster pixel coordinates, upstream to downstream, with its drainage area at the downstream end and whether it ends at a river mouth.

License

MIT. See LICENSE.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DrawEdges

func DrawEdges(img *image.RGBA, g hmz2ele.Grid, edges []RiverEdge, pixelAreaM2 float64, scale int)

DrawEdges draws the snapped river edges onto a preview, wider for larger drainage areas.

func DrawLinks(img *image.RGBA, h *Hydrology, links []Link, scale int)

DrawLinks draws the full-resolution links onto a preview, one preview pixel per covered cell.

func PixelFromLonLat

func PixelFromLonLat(hm *dem2hm.HeightMap16, lon, lat float64) (x, y float64, err error)

PixelFromLonLat returns the continuous raster coordinates of a longitude and latitude in the heightmap: the inverse of HeightMap16.LonLat.

func Version

func Version() semver.Version

Types

type Barrier

type Barrier struct {
	Lon1, Lat1, Lon2, Lat2 float64
	Height                 int16
}

Barrier is a wall along a line between two points, used to undo earthworks such as a canal cut. Valid pixels within barrierRadius of the line are raised to at least Height meters.

func ParseBarrier

func ParseBarrier(s string) (Barrier, error)

ParseBarrier parses "lon1,lat1,lon2,lat2,height".

func (Barrier) Apply

func (b Barrier) Apply(hm *dem2hm.HeightMap16) (int, error)

Apply raises the heightmap's valid pixels near the barrier's line and returns how many pixels it raised.

func (Barrier) String

func (b Barrier) String() string

type EdgeJSON

type EdgeJSON struct {
	Col         int          `json:"col"`
	Row         int          `json:"row"`
	Side        hmz2ele.Side `json:"side"`
	From        VertexJSON   `json:"from"`
	To          VertexJSON   `json:"to"`
	DrainageKm2 float64      `json:"drainage_km2"`
}

EdgeJSON is one hex edge carrying a river. The edge is identified by the hex that owns it and the side; water flows from From to To. DrainageKm2 is the area of source ground draining through the edge.

func EdgesJSON

func EdgesJSON(edges []RiverEdge, pixelAreaM2 float64) []EdgeJSON

EdgesJSON converts snapped edges for output.

type GridInfo

type GridInfo struct {
	ApothemPx int     `json:"apothem_px"`
	SidePx    float64 `json:"side_px"`
	Columns   int     `json:"columns"`
	Rows      int     `json:"rows"`
}

GridInfo identifies the hex grid the rivers were snapped to.

type HeightmapInfo

type HeightmapInfo struct {
	FileName string          `json:"file_name"`
	Metadata dem2hm.Metadata `json:"metadata"`
}

HeightmapInfo identifies the heightmap the rivers were extracted from.

type Hydrology

type Hydrology struct {
	Width, Height int
	// Elev holds the depression-filled elevations in meters.
	Elev []int16
	// Dir holds each pixel's flow direction code.
	Dir []uint8
	// Acc holds each pixel's drainage area in pixels, counting itself.
	Acc []uint32

	// FilledPixels is the number of pixels raised by depression filling.
	FilledPixels int
	// FlatPixels is the number of pixels that had no downhill neighbor
	// after filling and were routed by flat resolution.
	FlatPixels int
}

Hydrology is the drainage of a heightmap: filled elevations, a flow direction for every valid pixel, and the number of pixels that drain through each pixel.

func Compute

func Compute(width, height int, elev []int16) (*Hydrology, error)

Compute fills depressions in elev, in place, and computes flow directions and drainage area. Valid pixels on the raster edge or next to a no-data pixel drain off the map.

func (*Hydrology) Downstream

func (h *Hydrology) Downstream(i int) int

Downstream returns the pixel that pixel i drains into, or -1 if it drains off the map or is no-data.

func (*Hydrology) Rivers

func (h *Hydrology) Rivers(threshold uint32) []Link

Rivers returns the links of every river: pixels whose drainage area is at least threshold pixels.

func (*Hydrology) Trace

func (h *Hydrology) Trace(i int) (last, steps int)

Trace follows the flow from pixel i to where it leaves the map and returns the last pixel and the number of steps.

type HydrologyInfo

type HydrologyInfo struct {
	ThresholdKm2    float64  `json:"threshold_km2"`
	PixelAreaM2     float64  `json:"pixel_area_m2"`
	ThresholdPixels uint32   `json:"threshold_pixels"`
	Barriers        []string `json:"barriers"`
	Method          string   `json:"method"`
}

HydrologyInfo records the settings used to extract the rivers.

type Lines

type Lines struct {
	Hmz2rivVersion string     `json:"hmz2riv_version"`
	Links          []LinkJSON `json:"links"`
}

Lines holds the full-resolution river links, as written to JSON.

func LinesJSON

func LinesJSON(h *Hydrology, links []Link, pixelAreaM2 float64) Lines

LinesJSON converts links for output.

type Link struct {
	// Pixels lists raster pixel indexes from upstream to downstream.
	Pixels []int32
	// Mouth reports whether the link ends where the river leaves the map.
	Mouth bool
}

Link is one stretch of river: from a source or a confluence down to the next confluence, or to where the river leaves the map. Consecutive links share the confluence pixel.

type LinkJSON

type LinkJSON struct {
	Mouth       bool     `json:"mouth"`
	DrainageKm2 float64  `json:"drainage_km2"`
	Points      [][2]int `json:"points"`
}

LinkJSON is one link as raster pixel coordinates, upstream to downstream.

type RiverEdge

type RiverEdge struct {
	Edge     hmz2ele.EdgeKey
	From, To hmz2ele.VertexKey
	Acc      uint32
}

RiverEdge is one hex edge carrying a river, with the direction of flow and the drainage area, in pixels, where the river leaves the edge.

func Snap

func Snap(h *Hydrology, g hmz2ele.Grid, links []Link) []RiverEdge

Snap moves each link onto a chain of hex edges and returns the edges of the resulting river network, ordered by owner row, column, and side.

Links are snapped in decreasing order of drainage area at their downstream end, so every river is placed before its tributaries. Each river pixel moves to its nearest vertex; gaps between consecutive vertices are filled with the shortest path along hex edges, and loops are cut out. A link stops at the first vertex already in the network, which is where it joins the river it flows into.

type Rivers

type Rivers struct {
	Hmz2rivVersion string        `json:"hmz2riv_version"`
	Heightmap      HeightmapInfo `json:"heightmap"`
	Grid           GridInfo      `json:"grid"`
	Hydrology      HydrologyInfo `json:"hydrology"`
	Stats          Stats         `json:"stats"`
	Edges          []EdgeJSON    `json:"edges"`
}

Rivers is the river network snapped to hex edges, as written to JSON.

type Stats

type Stats struct {
	BarrierPixels int `json:"barrier_pixels"`
	FilledPixels  int `json:"filled_pixels"`
	FlatPixels    int `json:"flat_pixels"`
	Links         int `json:"links"`
	Mouths        int `json:"mouths"`
	RiverEdges    int `json:"river_edges"`
}

Stats summarizes the extraction.

type VertexJSON

type VertexJSON struct {
	Col    int            `json:"col"`
	Row    int            `json:"row"`
	Corner hmz2ele.Corner `json:"corner"`
}

VertexJSON identifies a vertex by its owning hex and corner.

Directories

Path Synopsis
cmd
hmz2riv command
Command hmz2riv extracts rivers from a dem2hm heightmap (format 1.1) at full resolution and snaps them to the edges of a flat-top hex grid, writing the river edges as JSON, with optional full-resolution river lines and a PNG preview.
Command hmz2riv extracts rivers from a dem2hm heightmap (format 1.1) at full resolution and snaps them to the edges of a flat-top hex grid, writing the river edges as JSON, with optional full-resolution river lines and a PNG preview.

Jump to

Keyboard shortcuts

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