Shifts a heightmap under spatial geometries by a constant or per-feature amount. This is useful when terrain needs to be lowered below water or raised beneath structures.

Positive amount values raise the surface and negative values lower it.

shift_terrain(
  heightmap,
  geometry,
  amount = 1,
  transition = 0,
  transition_units = c("map", "cells"),
  extent = NULL,
  crs = NULL,
  touches = TRUE,
  fun = "max"
)

Arguments

heightmap

Height matrix or spatial raster DEM. Matrix inputs require extent or cached or attribute extent metadata. Spatial raster inputs return a spatial raster; matrix inputs return a matrix.

geometry

Spatial geometry used to select the affected cells. Supports sf, sfc, sfg, terra::SpatVector, and sp vector objects.

amount

Default 1. Constant amount to apply, numeric vector with one value per feature, or a single character string naming a numeric column in geometry. Positive values raise terrain, negative values lower terrain, and NA values skip their features.

transition

Default 0. Distance over which amount transitions from the polygon edge to the full shift. 0 applies the full amount abruptly to all selected cells.

transition_units

Default c("map", "cells"). Units for transition. "map" uses meters for longitude and latitude rasters, the CRS linear units for projected rasters, and coordinate units for CRS-less rasters. "cells" measures distance in unit-width and unit-height raster cells, independent of CRS and spatial resolution.

extent

Default NULL. Spatial extent for matrix heightmap inputs. Ignored for spatial raster inputs.

crs

Default NULL. CRS describing the input heightmap. For spatial raster inputs, an explicit value overrides embedded metadata on a copy of the raster before geometry is transformed into that CRS.

touches

Default TRUE. Passed to terra::rasterize(). If TRUE, cells touched by polygons or lines are modified.

fun

Default "max". Rasterization reducer passed to terra::rasterize() for cells intersected by multiple features.

Value

A shifted height matrix or terra::SpatRaster. Legacy Raster* inputs are returned as terra::SpatRaster objects.

Details

In map mode, transition distance is measured by terra::distance(). The center-to-boundary inset is one-half of the smaller raster resolution. In cell mode, distance is calculated on a temporary unit-resolution raster and uses a half-cell inset of 0.5. A polygon that fills the raster has no internal polygon edge, so the raster boundary does not reduce its shift.

Examples

water_poly = sf::st_sfc(
  sf::st_polygon(list(rbind(
    c(0.2, 0.2), c(0.8, 0.2), c(0.8, 0.8), c(0.2, 0.8), c(0.2, 0.2)
  ))),
  crs = 4326
)
lowered = shift_terrain(
  matrix(10, 10, 10),
  water_poly,
  amount = -2,
  extent = c(0, 1, 0, 1)
)