HighMap library (C++)
Loading...
Searching...
No Matches
hmap Namespace Reference

Namespaces

namespace  gpu
namespace  va
namespace  neighborhood
namespace  log
namespace  cte

Classes

struct  IVec2Hash
struct  IVec2Eq
struct  IVec4Hash
struct  IVec4Eq
struct  Mat
 Mat class for basic manipulation of 2D matrices. More...
class  Array
 Array class, helper to manipulate 2D float array with "(i, j)" indexing. More...
struct  DeformationConstraint
 Per-vertex penalty term used by sls_deformation. More...
struct  GaussianPush
 Truncated-Gaussian push operation, the elementary deformation used by sls_deformation. More...
struct  ColorAdjust
struct  TerrainTextureParams
struct  AffineTransform2D
 Lightweight 2D affine transformation mapping (x, y) -> (ax*x + bx*y + cx, ay*x + by*y + cy). More...
class  CoordFrame
class  ICommunicator
 Abstract communicator interface providing MPI-style collective directives for single-source SPMD Array algorithms. More...
class  SingleArrayComm
 Default standalone communicator for single-array computation. All collective calls are identity or no-ops, resulting in zero overhead. More...
struct  MiseParams
 Parameters for the MISE (Multiscale Implicit Stream-power Erosion) solver. More...
class  BigTiffWriter
struct  ImageWriterConfig
class  ImageWriter
class  OpenCVWriter
class  OpenEXRWriter
struct  PointOfInterest
 Represents a terrain-aware point of interest with physical descriptors. More...
struct  PoiGenerationOptions
 Configuration parameters for procedural point-of-interest generation. More...
class  ArrayFunction
 Array (x, y) function class. More...
class  BiquadFunction
 Biquad (x, y) function class. More...
class  BumpFunction
 Bump (x, y) function class. More...
class  CraterFunction
 Crater (x, y) function class. More...
class  DiskFunction
 DiskFunction (x, y) function class. More...
class  GaussianPulseFunction
 GaussianPulse (x, y) function class. More...
class  QuadSurfaceFunction
 Quadratic surface function defined by four corner values. More...
class  RectangleFunction
 RectangleFunction (x, y) function class. More...
class  RiftFunction
 Rift (x, y) function class. More...
class  SlopeFunction
 Slope (x, y) function class. More...
class  StepFunction
 Step (x, y) function class. More...
class  WaveDuneFunction
 Wave dune (x, y) function class. More...
class  WaveSineFunction
 Wave sine (x, y) function class. More...
class  WaveSquareFunction
 Wave square (x, y) function class. More...
class  WaveTriangularFunction
 Wave triangular (x, y) function class. More...
class  NoiseFunction
 A class for generating noise functions. More...
class  ParberryFunction
 Parberry (x, y) function class. More...
class  PerlinFunction
 Perlin (x, y) function class. More...
class  PerlinBillowFunction
 Perlin 'billow' (x, y) function class. More...
class  PerlinHalfFunction
 Perlin 'half' (x, y) function class. More...
class  PerlinMixFunction
 Perlin 'mix' (x, y) function class. More...
class  Simplex2Function
 OpenSimplex2 (x, y) function class. More...
class  Simplex2SFunction
 OpenSimplex2S (x, y) function class. More...
class  ValueNoiseFunction
 Value noise (x, y) function class. More...
class  ValueCubicNoiseFunction
 Value Cubic noise (x, y) function class. More...
class  ValueDelaunayNoiseFunction
 ValueDelaunayNoise (x, y) function class. More...
class  ValueLinearNoiseFunction
 ValueLinearNoiseFunction (x, y) function class. More...
class  WorleyFunction
 Worley (x, y) function class. More...
class  WorleyDoubleFunction
 Worley (x, y) function class. More...
class  GenericFractalFunction
 A class for generating fractal noise functions based on an underlying noise function. More...
class  FbmFunction
 Fractional Brownian Motion (FBM) function class. More...
class  FbmIqFunction
 IQ layering function class. More...
class  FbmJordanFunction
 Jordan layering function class. More...
class  FbmPingpongFunction
 Pingpong layering function class. More...
class  FbmRidgedFunction
 Ridged layering function class. More...
class  FbmSlopeFunction
 Slope-weighted FBM layering function class. More...
class  FbmSwissFunction
 Swiss layering function class. More...
class  FieldFunction
 Field function class. More...
struct  AABB2D
 2D Axis-Aligned Bounding Box (AABB). More...
struct  Segment2D
 2D Directed line segment with metadata. More...
class  BVH2D
 2D Linear Bounding Volume Hierarchy for line segments. More...
class  CellPath
 Ordered path of grid cell indices. More...
class  Cloud
 Represents a collection of unordered points in 2D space. More...
struct  Edge
 Graph edge connecting two node indices with an associated weight. More...
struct  Neighbor
 Graph neighbor information for adjacency representation. More...
class  Graph
 Graph class, to manipulate graphs in 2D. More...
class  InverseSampler2D
 Sequential 2D inverse transform point sampler based on a 2D density array. More...
class  KDTree
 2D KD-Tree for spatial point queries. More...
class  Path
 Represents an ordered set of points in 2D, forming a polyline (open or closed). More...
class  Point
 A class to represent and manipulate 2D points that can carry a value. More...
struct  FlowGraph
struct  AssertResults
struct  RadixHeap
struct  Recorder
 The Recorder class is responsible for recording timing information for individual events. More...
class  Timer
 The Timer class is a singleton that manages multiple Recorders and provides an interface for timing events. More...
struct  ScopedTimer
class  Interpolator1D
 A class for performing 1D interpolation using the GSL library. More...
class  NaturalNeighborInterpolator
class  InterpolatorCurve
 Class for performing curve interpolation on a set of points. More...
class  ChebyshevEvaluator
 Evaluates a Chebyshev polynomial series using Clenshaw recurrence. More...
class  ArrayControlFunction
class  XyControlFunction
class  PdfSampler
 Samples indices from a discrete probability distribution. More...
class  ScatterField
 Container and processor for spatial ScatterItem collections. More...
class  ScatterItem
 Represents a single spatial instance (tree, rock, prop) with position, class identifier, and radius. More...
struct  ScatterSeedingOptions
 Configuration parameters for scatter seeding algorithms. More...
struct  BBox2D
 Axis-aligned 2D bounding box in world coordinates. More...
struct  UvRect
 Axis-aligned rectangle in normalized [0, 1]^2 domain/UV space. More...
struct  TileKey
struct  UvTile
 Describes an Array tile's position within the normalized [0, 1]^2 UV domain and global index grid. More...
class  TerrainTriMesh
 Triangle mesh representation of a terrain surface. More...
class  Texture
 A class to represent a multi-channel texture using planar hmap::Array storage. More...
struct  TerrainAlignment
 Elevation offset and tilt parameters for aligning an upper terrain. More...
class  SequentialTileComm
 Communicator for single-threaded sequential tile traversal. Supports cooperative fiber suspension (Option A2) so iterative collective calls (sync_overlap_buffers, all_reduce, all_union, barrier) synchronize across all tiles using a disk-backed temporary VirtualArray (VA_DISK_LRU_STREAM). More...
class  ThreadedCollectiveState
 Shared synchronization state for multi-threaded tile communication. More...
class  ThreadedTileComm
 Thread-local communicator proxy connected to a ThreadedCollectiveState. More...
struct  TileKeyHash
class  TileStorage
class  RamTileStorage
struct  LruTileEntry
class  DiskLruTileStorage
struct  ComputeMode
struct  VirtualArray
class  VirtualTexture
struct  VirtualTextureStorage
 Storage manager for VirtualTexture. More...
class  Forest
 Container class representing a collection of Tree instances. More...
struct  InteractionMatrix
 Generic S x S matrix representing pair-wise interaction properties between species. More...
struct  ForestScaleSampler
 Helper for sampling spatial scaling maps over a 2D bounding box with blending. More...
struct  SpeciesLookup
 Helper for querying species traits and pairwise competition factors. More...
struct  ForestSeedingOptions
 Configuration parameters for forest seeding algorithms. More...
struct  Species
 Encapsulates biological and geometric traits of a tree species. More...
struct  RockDistribution
 Parameters defining the size, power-law scaling, and embedding traits of rocks. More...
class  RockField
 Container class representing a field of rocks/boulders (scree, talus, or boulder field). More...
struct  RockSeedingOptions
 Configuration parameters for rock field seeding algorithms. More...
struct  RockSimulationOptions
 Configuration parameters for GPU-based rock and debris trajectory simulation. More...

Typedefs

using UvTile = UvTile
using Tree = ScatterItem
 Represents a single tree instance.
using Rock = ScatterItem
 Represents a single rock or boulder instance.

Enumerations

enum  StampingBlendMethod : int {
  ADD , MAXIMUM , MAXIMUM_SMOOTH , MINIMUM ,
  MINIMUM_SMOOTH , MULTIPLY , SUBSTRACT
}
 Blending method for the stamping operator. More...
enum  DeformationConstraintType : int { MATCH , ABOVE , BELOW }
 Penalty type of a deformation constraint (see DeformationConstraint). More...
enum class  TerrainBlendMode : int {
  TBM_ADD , TBM_AVERAGE , TBM_DISTANCE , TBM_HEIGHT ,
  TBM_MAX , TBM_MAX_SMOOTH , TBM_MIN , TBM_MIN_SMOOTH ,
  TBM_MULTISCALE , TBM_POISSON , TBM_SEAMLESS , TBM_SLOPE ,
  TBM_SUBTRACT
}
 Blending modes for combining terrains with CoordFrame transforms. More...
enum  PeriodicityType : int { PERIODICITY_X , PERIODICITY_Y , PERIODICITY_XY }
 Describes the periodicity mode applied along map axes. More...
enum  DomainBoundary : int { BOUNDARY_LEFT , BOUNDARY_RIGHT , BOUNDARY_TOP , BOUNDARY_BOTTOM }
 Describes which domain boundary. More...
enum  ElevationLongitudinalProfile : int { ELP_UNCHANGED , ELP_FLAT , ELP_DECREASING , ELP_INCREASING }
enum  MixMethod : int { MM_LINEAR , MM_SQRT_AVG , MM_MIXBOX }
 Methods for mixing/blending texture colors. More...
enum  NormalMapBlendingMethod : int {
  NMAP_LINEAR , NMAP_DERIVATIVE , NMAP_UDN , NMAP_UNITY ,
  NMAP_WHITEOUT
}
enum  Cmap : int {
  BONE , GRAY , HOT , INFERNO ,
  JET , MAGMA , NIPY_SPECTRAL , RAINBOW_DEM ,
  SEISMIC , TERRAIN , TURBO , VIRIDIS ,
  WHITE_UNIFORM
}
 Enumeration for different colormap types. More...
enum class  ReduceOp : uint8_t { Min , Max , Sum }
enum class  SyncOperation {
  Average , CopyFirst , CopySecond , Min ,
  Max , Mean , SmoothBlend , Sum
}
enum  CurvatureType : int {
  CT_MIN , CT_MAX , CT_MEAN , CT_GAUSSIAN ,
  CT_PROFILE , CT_CONTOUR , CT_TANGENTIAL , CT_ACCUMULATION ,
  CT_SHAPE_INDEX , CT_UNSPHERICITY , CT_RING , CT_ROTOR
}
 Types of curvature measures. More...
enum  MeshType : int { TRI_OPTIMIZED , TRI }
 Enumeration for different mesh types. More...
enum  AssetExportFormat : int {
  _3DS , _3MF , ASSBIN , ASSXML ,
  FXBA , FBX , COLLADA , X3D ,
  GLTF , GLB , GTLF2 , GLB2 ,
  PLY , PLYB , STP , STL ,
  STLB , OBJ , OBJNOMTL
}
 Enumeration for asset export formats supported by Assimp. More...
enum class  ImageDataType : int { FLOAT32 , FLOAT16 , UINT16 , UINT8 }
enum class  PoiType : int {
  CUSTOM = 0 , APEX , SINK , SADDLE ,
  RIDGE , VALLEY , CLIFF , PLATEAU ,
  FLAT_LOWLAND , VIEWPOINT , SETTLEMENT_CANDIDATE
}
 Classification types for terrain-aware points of interest. More...
enum class  DistanceMode : int { ASTERISK = 0 , PYRAMID = 1 }
 Directional pattern mode for distance shaper. More...
enum class  DistanceMethod : int { RT = 0 , CLASSIC = 1 }
 Method used to calculate distance. More...
enum  NoiseType : int {
  PARBERRY , PERLIN , PERLIN_BILLOW , PERLIN_HALF ,
  SIMPLEX2 , SIMPLEX2S , VALUE , VALUE_CUBIC ,
  VALUE_DELAUNAY , VALUE_LINEAR , WORLEY , WORLEY_DOUBLE ,
  WORLEY_VALUE
}
 Enumeration of various noise types used for procedural generation. More...
enum class  ArraySampling : int { AS_POINT , AS_MIN , AS_MAX , AS_MEAN }
 Strategy used to extract a point value from an array. More...
enum  PointSamplingMethod : int { RND_RANDOM , RND_HALTON , RND_HAMMERSLEY , RND_LHS }
 Enumeration of point sampling methods. More...
enum  FlowGraphFlag : uint8_t { F_CLOSED = 1 , F_PIT = 2 , F_OUTLET = 4 }
enum  InterpolationMethod1D : int {
  AKIMA , AKIMA_PERIODIC , CUBIC , CUBIC_PERIODIC ,
  LINEAR , POLYNOMIAL , STEFFEN
}
 Enumeration of the available 1D interpolation methods. More...
enum  InterpolationMethod2D : int {
  ITP2D_DELAUNAY , ITP2D_NEAREST , ITP2D_IDW , ITP2D_GAUSSIAN ,
  ITP2D_NNI , ITP2D_DELAUNAY_GRADIENT
}
 Enumeration of 2D interpolation methods. More...
enum  InterpolationMethodCurve : int {
  BEZIER , BSPLINE , CATMULLROM , DECASTELJAU ,
  POINTS_LERP
}
 Enumeration for specifying the interpolation method for curves. More...
enum  KernelType : int {
  BIWEIGHT , CUBIC_PULSE , CONE , CONE_SMOOTH ,
  DISK , LORENTZIAN , SMOOTH_COSINE , SQUARE ,
  TRICUBE , CUPOLA
}
 Enumeration for different kernel functions used in various algorithms. More...
enum class  MinMaxKernel : int { DISK , OCTAGON , SQUARE }
 Kernel footprint geometry for local minimum / maximum operations. More...
enum  DistanceFunction : int { CHEBYSHEV , EUCLIDIAN , EUCLISHEV , MANHATTAN }
 Distance function type. More...
enum  DistanceFunctionAxis : int { DFA_X , DFA_Y , DFA_XY }
 Axis used for the distance function. More...
enum  ErosionProfile : int {
  EP_COSINE , EP_COSINE_BULK , EP_COSINE_PEAK , EP_PARABOL ,
  EP_SAW_SHARP , EP_SAW_SMOOTH , EP_SHARP_VALLEYS , EP_SQRT ,
  EP_TRIANGLE_GRENIER , EP_TRIANGLE_SHARP , EP_TRIANGLE_SMOOTH
}
 Procedural erosion angular profile type. More...
enum  PhasorProfile : int {
  PP_COSINE_BULKY , PP_COSINE_PEAKY , PP_COSINE_SQUARE , PP_COSINE_STD ,
  PP_TRIANGLE , PP_DUNE
}
 Phasor angular profile type. More...
enum  RadialProfile : int {
  RP_GAIN , RP_LINEAR , RP_POW , RP_SMOOTHSTEP ,
  RP_SMOOTHSTEP_UPPER , RP_FLAT_BOTTOM , RP_SQRT
}
 Radial profile type. More...
enum  DistanceTransformType : int { DT_EXACT , DT_APPROX , DT_MANHATTAN , DT_JFA }
 Enumeration for different types of distance transforms. More...
enum  MorphologyOperation : int {
  MO_BORDER , MO_CLOSING , MO_DILATION , MO_EROSION ,
  MO_OPENING , MO_BLACK_HAT , MO_TOP_HAT , MO_GRADIENT ,
  MO_LAPLACIAN , MO_CLOSING_BY_RECONSTRUCTION , MO_OPENING_BY_RECONSTRUCTION
}
 Types of base morphology operators. More...
enum  VoronoiReturnType : int {
  F1_SQUARED , F2_SQUARED , F1TF2_SQUARED , F1DF2_SQUARED ,
  F2MF1_SQUARED , EDGE_DISTANCE_EXP , EDGE_DISTANCE_SQUARED , CONSTANT ,
  CONSTANT_F2MF1_SQUARED
}
 Selects the value returned by the Voronoi evaluation. More...
enum  PrimitiveType : int {
  PRIM_BIQUAD_PULSE , PRIM_BUMP , PRIM_CONE , PRIM_CONE_SMOOTH ,
  PRIM_CUBIC_PULSE , PRIM_SMOOTH_COSINE
}
 Defines the primitive shape used for synthesis. More...
enum  ClampMode : int { POSITIVE_ONLY , NEGATIVE_ONLY , BOTH , NONE }
enum  ScatterShape : int {
  SCATTER_SHAPE_DISK , SCATTER_SHAPE_POLYGON , SCATTER_SHAPE_CONE , SCATTER_SHAPE_PYRAMID ,
  SCATTER_SHAPE_SMOOTH_DOME
}
 Defines the geometric shape used when converting a ScatterField to a heightmap. More...
enum class  GridRegistration { CellCenter , CellCorner , Node }
 Grid registration policy for mapping discrete indices to [0, 1]. More...
enum  NormalizationMethod : int { NM_MIN_MAX , NM_STANDARDIZE , NM_ROBUST }
 Normalization methods. More...
enum class  TerrainAlignMode : int { TAM_OFFSET , TAM_PLANE , TAM_ROBUST_OFFSET , TAM_ROBUST_PLANE }
 Alignment modes for fitting an upper terrain to a lower terrain. More...
enum  SymmetryType : int {
  SYMMETRY_LEFT_TO_RIGHT , SYMMETRY_RIGHT_TO_LEFT , SYMMETRY_TOP_TO_BOTTOM , SYMMETRY_BOTTOM_TO_TOP ,
  SYMMETRY_X , SYMMETRY_Y , SYMMETRY_XY , SYMMETRY_ROT180
}
 Describes the symmetry operation to apply to an array. More...
enum  StorageMode : int { VA_RAM = 0 , VA_DISK_LRU_STREAM = 1 , VA_DISK_LRU_FULL = 2 }
enum  ForEachMode : int { VA_SEQUENTIAL , VA_DISTRIBUTED , VA_SINGLE_ARRAY }

Functions

Array cv_mat_to_array (const cv::Mat &mat, bool remap_values=true, bool flip_j=false)
 Converts an OpenCV cv::Mat to a 2D Array with optional value scaling to [0, 1].
std::string get_opencv_build_information ()
 Returns OpenCV build information string.
cv::Mat to_cv_mat (Array &array)
 Converts a 2D Array to a non-owning OpenCV cv::Mat (CV_32FC1).
void to_csv (const std::vector< glm::vec3 > &xyz, const std::string &fname)
glm::vec4 adjust (const glm::vec4 &v, float dx, float dy, float dz, float dw)
glm::vec4 adjust (const glm::vec4 &v, float dr)
size_t count_non_zero (const Array &array)
 Count the number of non-zero elements in the array.
size_t count_zero (const Array &array)
 Count the number of zero elements in the array.
template<typename Fn>
void for_each_cell (Array &a, Fn &&fn)
 Apply a function to every cell (mutable).
template<typename Fn>
void for_each_cell (const Array &a, Fn &&fn)
 Apply a function to every cell (read-only).
void alter_elevation (Array &array, const Cloud &cloud, int ir, float footprint_ratio=1.f, glm::vec2 shift={0.f, 0.f}, glm::vec2 scale={1.f, 1.f})
 Point-wise alteration: locally enforce a new elevation value while maintaining the 'shape' of the heightmap.
void apply_gaussian_pushes (Array &array, const std::vector< GaussianPush > &pushes)
 Apply a sequence of truncated-Gaussian pushes to a heightmap.
Array base_elevation (glm::ivec2 shape, const std::vector< std::vector< float > > &values, float width_factor=1.f, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const Array *p_stretching=nullptr, const UvRect &uv_rect=UvRect::unit())
 Generate a heightmap from a coarse grid of control points with defined elevation values.
Array elevation_from_contours (glm::ivec2 shape, const std::vector< Path > &contours, const std::vector< float > &elevations, const Array *p_probability=nullptr, float randomness=1.f, std::uint32_t seed=0, float peak_ratio=0.5f, float outside_ratio=1.f, bool smoothstep=false, const UvRect &uv_rect=UvRect::unit())
 Synthesize a heightmap from sparse closed iso-contours with known elevations using stochastic front propagation (proof of concept).
Array elevation_from_contours (const Array &contours, const Array *p_probability=nullptr, float randomness=1.f, std::uint32_t seed=0, float peak_ratio=0.5f, float outside_ratio=1.f, bool smoothstep=false)
 Synthesize a heightmap from a raster of sparse iso-contours with known elevations using stochastic front propagation.
Array elevation_from_sparse_constraints (const Array &mountains, const Array *p_coastline=nullptr, const Array *p_boundary=nullptr, float mountain_elevation=1.0f, float coastline_elevation=0.0f, float boundary_elevation=-1.0f, int iterations_max=500, float tolerance=1e-5f, const Array *p_noise=nullptr, float noise_amplitude=0.0f)
 Synthesize a smooth heightmap from sparse elevation constraints using GPU harmonic interpolation (Laplacian PDE).
Array reverse_midpoint (const Array &array, std::uint32_t seed, float noise_scale=1.f, float threshold=0.f)
 Apply the reverse midpoint displacement algorithm to the input array.
Array ridgelines (glm::ivec2 shape, const std::vector< float > &xr, const std::vector< float > &yr, const std::vector< float > &zr, float slope, float k_smoothing=1.f, float width=0.1f, float vmin=0.f, const UvRect &uv_rect=UvRect::unit(), const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const Array *p_stretching=nullptr, const UvRect &uv_rect_array=UvRect::unit())
 Generate a heightmap based on a set of ridgelines and a specified slope.
Array ridgelines_bezier (glm::ivec2 shape, const std::vector< float > &xr, const std::vector< float > &yr, const std::vector< float > &zr, float slope, float k_smoothing=1.f, float width=0.1f, float vmin=0.f, const UvRect &uv_rect=UvRect::unit(), const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const Array *p_stretching=nullptr, const UvRect &uv_rect_array=UvRect::unit())
 Generate a heightmap based on a set of ridgelines with quadratic Bezier interpolation.
Array sls_deformation (const Array &z, const std::vector< DeformationConstraint > &constraints, std::uint32_t seed, int iterations=200, int ir_min=4, int ir_max=64, int n_radii=7, float talus_max=0.f, int n_candidates=512, float p_best=0.65f, float top_fraction=0.1f, float tolerance=1e-3f, std::vector< GaussianPush > *p_pushes=nullptr)
 Deform a heightmap to satisfy a set of constraints using stochastic local search over truncated-Gaussian push operations.
Array stamping (glm::ivec2 shape, const std::vector< float > &xr, const std::vector< float > &yr, const std::vector< float > &zr, Array kernel, int kernel_ir, bool kernel_scale_radius, bool kernel_scale_amplitude, StampingBlendMethod blend_method, std::uint32_t seed, float k_smoothing=0.1f, bool kernel_flip=true, bool kernel_rotate=false, const UvRect &uv_rect_array=UvRect::unit())
 Generate a heightmap by stamping a kernel at predefined locations.
Array blend_exclusion (const Array &array1, const Array &array2)
 Return the 'exclusion' blending of two arrays.
Array blend_gradients (const Array &array1, const Array &array2, int ir=4)
 Return the blending of two arrays based on their gradients.
Array blend_negate (const Array &array1, const Array &array2)
 Return the 'negate' blending of two arrays.
Array blend_overlay (const Array &array1, const Array &array2)
 Return the 'overlay' blending of two arrays.
Array blend_soft (const Array &array1, const Array &array2)
 Return the 'soft' blending of two arrays.
Array blend_power_law (const std::vector< const Array * > &arrays, float alpha=0.f)
 Return the power law blending of a set of arrays.
Array blend_power_law (const Array &array1, const Array &array2, float alpha=0.f)
 Return the power law blending of two arrays.
Array mixer (const Array &t, const std::vector< const Array * > &arrays, float gain_factor=1.f)
 Return the mixing of a set of arrays based on a parameter t.
Array transfer (const Array &source, const Array &target, int ir, float amplitude, bool target_prefiltering=false)
 Transfers spatial details from a source array onto a target array.
void blend_terrains (Array &lower, const CoordFrame &frame_lower, const Array &upper, const CoordFrame &frame_upper, TerrainBlendMode mode, float param=0.2f)
 Blend an upper terrain onto a lower terrain in-place, taking their CoordFrame transforms into account.
void blend_terrains (VirtualArray &lower, const CoordFrame &frame_lower, const VirtualArray &upper, const CoordFrame &frame_upper, TerrainBlendMode mode, float param=0.2f, const ComputeMode &cm=ComputeMode{})
 Blend an upper VirtualArray terrain onto a lower VirtualArray terrain in-place, taking their CoordFrame transforms into account.
void blend_terrains_height (Array &lower, const CoordFrame &frame_lower, const Array &upper, const CoordFrame &frame_upper, float feather_width=0.2f, float height_offset=0.f, float height_range=0.2f)
 Height-aware terrain blending for Array inputs.
void blend_terrains_height (VirtualArray &lower, const CoordFrame &frame_lower, const VirtualArray &upper, const CoordFrame &frame_upper, float feather_width=0.2f, float height_offset=0.f, float height_range=0.2f, const ComputeMode &cm=ComputeMode{})
 Height-aware terrain blending for VirtualArray inputs.
void blend_terrains_multiscale (Array &lower, const CoordFrame &frame_lower, const Array &upper, const CoordFrame &frame_upper, float feather_width=0.25f, int n_levels=3, int base_radius=16, float detail_gain=1.f)
 Multiscale (frequency-band) terrain blending for Array inputs.
void blend_terrains_multiscale (VirtualArray &lower, const CoordFrame &frame_lower, const VirtualArray &upper, const CoordFrame &frame_upper, float feather_width=0.25f, int n_levels=3, int base_radius=16, float detail_gain=1.f, int coarse_size=128, const ComputeMode &cm=ComputeMode{})
 Multiscale (frequency-band) terrain blending for VirtualArray inputs using a coarse global proxy for low-frequency bands and tile-local detail blending with halo synchronization.
void blend_terrains_poisson (Array &lower, const CoordFrame &frame_lower, const Array &upper, const CoordFrame &frame_upper, int iterations=400, float feather_width=0.15f, bool mixed_gradients=true)
 Poisson / gradient-domain terrain blending for Array inputs.
void blend_terrains_poisson (VirtualArray &lower, const CoordFrame &frame_lower, const VirtualArray &upper, const CoordFrame &frame_upper, int iterations=400, float feather_width=0.15f, bool mixed_gradients=true, int coarse_size=128, int sync_interval=25, const ComputeMode &cm=ComputeMode{})
 Poisson / gradient-domain terrain blending for VirtualArray inputs using a two-level coarse-proxy + tile-local Red-Black SOR solver with halo synchronization.
void blend_terrains_seamless (Array &lower, const CoordFrame &frame_lower, const Array &upper, const CoordFrame &frame_upper, float feather_width=0.2f, int boundary_samples=64)
 Seamless boundary blending (harmonic MVC membrane) for Array inputs.
void blend_terrains_seamless (VirtualArray &lower, const CoordFrame &frame_lower, const VirtualArray &upper, const CoordFrame &frame_upper, float feather_width=0.2f, int boundary_samples=64, const ComputeMode &cm=ComputeMode{})
 Seamless boundary blending (harmonic MVC membrane) for VirtualArray inputs.
void blend_terrains_slope (Array &lower, const CoordFrame &frame_lower, const Array &upper, const CoordFrame &frame_upper, float feather_width=0.2f, float slope_scale=0.1f, int ir_slope=2)
 Slope-aware terrain blending for Array inputs.
void blend_terrains_slope (VirtualArray &lower, const CoordFrame &frame_lower, const VirtualArray &upper, const CoordFrame &frame_upper, float feather_width=0.2f, float slope_scale=0.1f, int ir_slope=2, const ComputeMode &cm=ComputeMode{})
 Slope-aware terrain blending for VirtualArray inputs.
void extrapolate_borders (Array &array, int nbuffer=1, float sigma=0.f, float vmin=-FLT_MAX)
 Performs linear extrapolation of values at the borders of an array (e.g., i = 0, j = 0, etc.) based on the inner values of the array.
void falloff (Array &array, float strength=1.f, DistanceFunction dist_fct=DistanceFunction::EUCLIDIAN, const Array *p_noise=nullptr, const UvRect &uv_rect=UvRect::unit())
 Applies a falloff effect to the input array based on distance.
void fill_borders (Array &array)
 Fills the border values of an array (e.g., i = 0, j = 0, etc.) based on the values of the first neighboring cells.
void fill_borders (Array &array, int nbuffer)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
Array generate_buffered_array (const Array &array, glm::ivec4 buffers, bool zero_padding=false)
 Creates and returns a new array with additional buffer zones at the boundaries, where the buffer values are filled either by symmetry or by zero-padding.
void make_periodic (Array &array, int nbuffer, const PeriodicityType &periodicity_type=PeriodicityType::PERIODICITY_XY)
 Adjusts the input array to be periodic in both directions by transitioning smoothly at the boundaries.
Array make_periodic_stitching (const Array &array, float overlap)
 Creates a periodic array in both directions using a stitching operation that minimizes errors at the boundaries.
Array make_periodic_tiling (const Array &array, float overlap, glm::ivec2 tiling)
 Creates a tiled, periodic array by applying a transition with overlap in both directions.
glm::ivec2 pick_boundary_cell (const Array &z, DomainBoundary boundary, std::uint32_t seed, bool favor_boundary_center=true, bool favor_lower_elevation=true, bool favor_sinks=true)
 Picks a boundary cell using weighted random selection.
void set_borders (Array &array, glm::vec4 border_values, glm::ivec4 buffer_sizes)
 Enforces specific values at the boundaries of the array.
void set_borders (Array &array, glm::vec4 border_values, glm::vec4 buffer_sizes, const UvRect &uv_rect=UvRect::unit())
 Enforces specific values at the domain boundaries based on distance.
void set_borders (Array &array, float border_values, int buffer_sizes)
 Enforces a uniform value at all boundaries of the array.
void set_borders (Array &array, float border_values, float buffer_sizes, const UvRect &uv_rect=UvRect::unit())
 Enforces a uniform value at all domain boundaries based on distance.
void sym_borders (Array &array, glm::ivec4 buffer_sizes)
 Fills the values at the domain borders using symmetry over a specified buffer depth.
void zeroed_borders (Array &array)
 Fills the border values (e.g., i = 0, j = 0, etc.) of the array with zeros.
void zeroed_edges (Array &array, RadialProfile radial_profile=RadialProfile::RP_SMOOTHSTEP, float profile_param=0.f, float amount=1.f, DistanceFunction distance=DistanceFunction::EUCLIDIAN, DistanceFunctionAxis dfa=DistanceFunctionAxis::DFA_XY, glm::vec2 center={0.5f, 0.5f}, float radius=0.5f, const Array *p_noise_r=nullptr, const UvRect &uv_rect=UvRect::unit())
 Smoothly attenuates array values toward zero near the domain boundaries.
void carve_river (Array &z, const Graph &graph, float talus, float outlet_width, float headwater_width=0.f, float width_exponent=0.5f, float depth=0.05f, float depth_exponent=0.3f, std::uint32_t seed=0, float talus_noise_ratio=0.f, RadialProfile radial_profile=RadialProfile::RP_SMOOTHSTEP_UPPER, float radial_profile_parameter=2.f, Array *p_river_mask=nullptr, const UvRect &uv_rect=UvRect::unit())
 Carves a continuous river network into a heightmap along a directed flow Graph.
void dig_path (Array &z, Path &path, int width=1, int decay=2, int flattening_radius=16, bool force_downhill=false, const UvRect &uv_rect=UvRect::unit(), float depth=0.f)
 Dig a path on a heightmap.
void flatten_around_points (Array &z, const std::vector< float > &xp, const std::vector< float > &yp, const std::vector< float > &zp, const std::vector< float > &radius, float strength=1.0f, RadialProfile radial_profile=RadialProfile::RP_SMOOTHSTEP, float profile_param=1.0f, Array *p_mask=nullptr, const UvRect &uv_rect=UvRect::unit())
 Flattens a heightmap locally around a set of reference points.
void flatten_around_points (Array &z, const std::vector< float > &xp, const std::vector< float > &yp, const std::vector< float > &zp, float radius=0.2f, float strength=1.0f, RadialProfile radial_profile=RadialProfile::RP_SMOOTHSTEP, float profile_param=1.0f, Array *p_mask=nullptr, const UvRect &uv_rect=UvRect::unit())
 Overload of flatten_around_points with a single radius shared by all points.
void flatten_around_points_terrain_aware (Array &z, const std::vector< float > &xp, const std::vector< float > &yp, const std::vector< float > &zp, const std::vector< float > &radius, float slope_weight=1.f, float uphill_weight=2.f, float max_height_above=-1.f, float terrain_follow=0.5f, float strength=1.f, RadialProfile radial_profile=RadialProfile::RP_SMOOTHSTEP, float profile_param=1.f, Array *p_mask=nullptr, const UvRect &uv_rect=UvRect::unit())
 Terrain-aware flattening around a set of seed points.
void flatten_around_points_terrain_aware (Array &z, const std::vector< float > &xp, const std::vector< float > &yp, const std::vector< float > &zp, float radius, float slope_weight=1.f, float uphill_weight=2.f, float max_height_above=-1.f, float terrain_follow=0.5f, float strength=1.f, RadialProfile radial_profile=RadialProfile::RP_SMOOTHSTEP, float profile_param=1.f, Array *p_mask=nullptr, const UvRect &uv_rect=UvRect::unit())
 Overload with a single radius shared by all seeds.
void flatbed_carve (Array &z, const Path &path, float bottom_extent=32.f, float vmin=0.1f, float depth=0.05f, float falloff_distance=128.f, float outer_slope=0.1f, bool preserve_bedshape=true, RadialProfile radial_profile=RadialProfile::RP_GAIN, float radial_profile_parameter=2.f, Array *p_falloff_mask=nullptr, const Array *p_noise_r=nullptr, const UvRect &uv_rect=UvRect::unit())
 Blends a flatbed carve into an existing heightmap.
void trench (Array &z, const Path &path, float width, bool enable_width_depth_scaling=true, bool enable_width_distance_scaling=true, bool enable_width_curvature_scaling=false, float curvature_radius_min=1.f, float curv_width_ratio_min=0.5f, float curv_width_ratio_max=2.f, RadialProfile radial_profile=RadialProfile::RP_SMOOTHSTEP_UPPER, float radial_profile_parameter=2.f, ElevationLongitudinalProfile longitudinal_profile=ElevationLongitudinalProfile::ELP_DECREASING, float elevation_shift=-0.05f, float shift_ramp_start_ratio=0.f, float shift_ramp_end_ratio=0.f, float min_slope=0.001f, size_t k_neighbors=8, const Array *p_noise_r=nullptr, Array *p_bending_mask=nullptr, int tile_size=32, const UvRect &uv_rect=UvRect::unit())
 Carves a trench along a given path into a heightmap.
void trench (Array &z, const std::vector< Path > &paths, float width, bool enable_width_depth_scaling=true, bool enable_width_distance_scaling=true, bool enable_width_curvature_scaling=false, float curvature_radius_min=1.f, float curv_width_ratio_min=0.5f, float curv_width_ratio_max=2.f, RadialProfile radial_profile=RadialProfile::RP_SMOOTHSTEP_UPPER, float radial_profile_parameter=2.f, ElevationLongitudinalProfile longitudinal_profile=ElevationLongitudinalProfile::ELP_DECREASING, float elevation_shift=-0.05f, float shift_ramp_start_ratio=0.f, float shift_ramp_end_ratio=0.f, float min_slope=0.001f, size_t k_neighbors=8, const Array *p_noise_r=nullptr, Array *p_bending_mask=nullptr, int tile_size=32, const UvRect &uv_rect=UvRect::unit())
void trench (Array &z, const Graph &graph, const std::vector< float > &relative_widths, float width, bool enable_width_depth_scaling=true, RadialProfile radial_profile=RadialProfile::RP_SMOOTHSTEP_UPPER, float radial_profile_parameter=2.f, ElevationLongitudinalProfile longitudinal_profile=ElevationLongitudinalProfile::ELP_DECREASING, float elevation_shift=-0.05f, float min_slope=0.001f, const Array *p_noise_r=nullptr, Array *p_bending_mask=nullptr, int tile_size=32, const UvRect &uv_rect=UvRect::unit())
 Carves river channels for an entire flow network represented by a Graph with per-node relative widths.
void trench (Array &z, const Graph &graph, float width, float width_exponent=1.0f, bool enable_width_depth_scaling=true, RadialProfile radial_profile=RadialProfile::RP_SMOOTHSTEP_UPPER, float radial_profile_parameter=2.f, ElevationLongitudinalProfile longitudinal_profile=ElevationLongitudinalProfile::ELP_DECREASING, float elevation_shift=-0.05f, float min_slope=0.001f, const Array *p_noise_r=nullptr, Array *p_bending_mask=nullptr, int tile_size=32, const UvRect &uv_rect=UvRect::unit())
 Carves river channels for an entire flow network represented by a Graph, computing relative widths from distance to outlet.
void apply_hillshade (Texture &img, const Array &array, float vmin=0.f, float vmax=1.f, float exponent=1.f)
 Apply hillshading to a Tensor image.
void apply_hillshade (std::vector< uint8_t > &img, const Array &array, float vmin=0.f, float vmax=1.f, float exponent=1.f, bool is_img_rgba=false)
 Apply hillshading to an 8-bit image.
void color_adjust (Array &r, Array &g, Array &b, ColorAdjust param, glm::ivec2 dither_seed)
 Apply color correction and tonemapping to RGB arrays.
Array color_match_mask (const Array &r, const Array &g, const Array &b, const glm::vec3 &color, float tolerance=0.f)
 Create a mask of pixels matching a target color within a tolerance.
Texture colorize (const Array &array, float vmin, float vmax, int cmap, bool hillshading, bool reverse=false, const Array *p_noise=nullptr)
 Apply colorization to an array.
Texture colorize (const Array &array, float vmin, float vmax, const std::vector< float > &positions, const std::vector< glm::vec3 > &colormap_colors, bool reverse=false, const Array *p_noise=nullptr)
 Colorize a scalar field into a Texture using a custom colormap.
Texture colorize_bivariate (const Array &a1, const Array &a2, const glm::vec2 range1, const glm::vec2 range2, const std::vector< float > &positions1, const std::vector< float > &positions2, const std::vector< glm::vec3 > &colormap_colors1, const std::vector< glm::vec3 > &colormap_colors2, MixMethod method=MM_SQRT_AVG, bool reverse1=false, bool reverse2=false, const Array *p_noise1=nullptr, const Array *p_noise2=nullptr)
 Colorize two scalar fields into a Texture using two custom colormaps and a color mixing method.
Texture colorize_grayscale (const Array &array)
 Convert an array to a grayscale image.
Texture colorize_histogram (const Array &array)
 Convert an array to a histogram-based grayscale image.
Texture colorize_slope_height_heatmap (const Array &array, int cmap)
 Colorizes a slope height heatmap based on the gradient norms of a given array.
Texture colorize_vec2 (const Array &array1, const Array &array2)
 Combine two arrays into a colored image.
Array luminance (const Texture &tex)
 Compute luminance from a Texture.
Texture mix (const Texture &tex1, const Texture &tex2, MixMethod method=MM_SQRT_AVG)
 Mix two textures into an output texture.
Texture mix (const Texture &tex1, const Texture &tex2, const Array &mask, MixMethod method=MM_SQRT_AVG, float gain=1.f)
 Mix two textures based on a transparency mask.
Texture mix (const std::vector< const Texture * > &texs, MixMethod method=MM_SQRT_AVG)
 Mix a list of textures sequentially.
Texture mix_normal_map (const Texture &nmap_base, const Texture &nmap_detail, float detail_scaling, NormalMapBlendingMethod blending_method)
 Blend two normal maps into a single output normal map.
glm::vec3 shade_color (const glm::vec3 &color, float t)
 Adjust color by shading parameter t clamped to [0, 1].
void shade_color (Texture &tex, const Array &factor)
 Apply shade_color to each pixel of a Texture using values from an Array.
void shade_topographic_residual (Texture &tex, const Array &z, int ir, float strength=1.0f)
 Apply shade_color to a Texture based on topographic residuals of an elevation array.
Texture terrain_texture (const Array &z, const Array *p_deposition=nullptr, const Array *p_snow_depth=nullptr, const TerrainTextureParams &params=TerrainTextureParams(), const BBox2D &bbox=BBox2D::unit(), const Array *p_noise=nullptr, ICommunicator &comm=SingleArrayComm::instance())
 Generate a procedural terrain texture from elevation and surface analysis.
std::vector< glm::vec3 > get_colormap_data (int cmap)
std::string to_string (ReduceOp op)
Array level_set_curvature (const Array &array, int prefilter_ir)
 Computes a signed level-set curvature.
Array curvature_quadric (const Array &z, int ir, CurvatureType curvature_type)
 Compute curvature measures on a scalar field.
void aeolian_erosion (Array &z, int steps=300, std::uint32_t seed=1337u, glm::vec2 wind={3.f, 0.f}, const Array *p_bedrock=nullptr, const Array *p_vegetation=nullptr, const Array *p_abrasion_mask=nullptr, Array *p_sediment_map=nullptr, Array *p_bedrock_map=nullptr, float cell_size=-1.f, float matter_to_move=0.001f, int samples_per_step=0, float sand_repose_angle=33.f, float shadow_angle_min=5.f, float shadow_angle_max=15.f, float max_shadow_dist=12.f, float abrasion_rate=0.f, float repose_rate=0.35f, int sync_interval=0, const UvTile &region=UvTile::dummy(), ICommunicator &comm=SingleArrayComm::instance(), int shadow_map_interval=1, int repose_interval=2)
 Simulates wind-driven aeolian terrain erosion, sand transport, and dune dynamics on GPU.
void aeolian_erosion_multiscale (Array &z, int steps=300, std::uint32_t seed=1337u, glm::vec2 wind={3.f, 0.f}, const Array *p_bedrock=nullptr, const Array *p_vegetation=nullptr, const Array *p_abrasion_mask=nullptr, Array *p_sediment_map=nullptr, Array *p_bedrock_map=nullptr, float cell_size=-1.f, float matter_to_move=0.001f, float sand_repose_angle=33.f, float shadow_angle_min=5.f, float shadow_angle_max=15.f, float max_shadow_dist=12.f, float abrasion_rate=0.f, float repose_rate=0.35f, int levels=3, float coarse_fraction=0.7f, int min_level_size=64, int shadow_map_interval=1, int repose_interval=2)
 Multiscale (coarse-to-fine) variant of hmap::aeolian_erosion.
void coastal_erosion_diffusion (Array &z, Array &water_depth, float additional_depth, int iterations=10, const Array *p_mask=nullptr, Array *p_water_mask=nullptr)
 Simulates terrain diffusion due to coastal erosion.
void coastal_erosion_profile (Array &z, Array &water_depth, float shore_ground_extent, float shore_water_extent, float slope_shore=0.5f, float slope_shore_water=0.5f, float scarp_extent_ratio=0.5f, bool apply_post_filter=true, int post_filter_iterations=3, bool solid_shore_mask=true, float scarp_mask_transition_ratio=0.2f, const Array *p_noise=nullptr, Array *p_shore_mask=nullptr, Array *p_scarp_mask=nullptr)
 Applies a coastal erosion profile to a terrain elevation field.
void coastal_erosion_profile (Array &z, const Array *p_mask, Array &water_depth, float shore_ground_extent, float shore_water_extent, float slope_shore=0.5f, float slope_shore_water=0.5f, float scarp_extent_ratio=0.5f, bool apply_post_filter=true, int post_filter_iterations=3, bool solid_shore_mask=true, float scarp_mask_transition_ratio=0.2f, const Array *p_noise=nullptr, Array *p_shore_mask=nullptr, Array *p_scarp_mask=nullptr)
void hydraulic_algebric (Array &z, Array *p_mask, float talus_ref, int ir, Array *p_bedrock=nullptr, Array *p_erosion_map=nullptr, Array *p_deposition_map=nullptr, float c_erosion=0.05f, float c_deposition=0.05f, int iterations=1)
 Apply an algerbic formula based on the local gradient to perform erosion/deposition.
void hydraulic_algebric (Array &z, float talus_ref, int ir, Array *p_bedrock=nullptr, Array *p_erosion_map=nullptr, Array *p_deposition_map=nullptr, float c_erosion=0.05f, float c_deposition=0.05f, int iterations=1)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void hydraulic_benes (Array &z, Array *p_mask, int iterations=50, Array *p_bedrock=nullptr, Array *p_moisture_map=nullptr, Array *p_erosion_map=nullptr, Array *p_deposition_map=nullptr, float c_capacity=40.f, float c_erosion=0.2f, float c_deposition=0.8f, float water_level=0.005f, float evap_rate=0.01f, float rain_rate=0.5f)
 Apply cell-based hydraulic erosion/deposition based on Benes et al. procedure.
void hydraulic_benes (Array &z, int iterations=50, Array *p_bedrock=nullptr, Array *p_moisture_map=nullptr, Array *p_erosion_map=nullptr, Array *p_deposition_map=nullptr, float c_capacity=40.f, float c_erosion=0.2f, float c_deposition=0.8f, float water_level=0.005f, float evap_rate=0.01f, float rain_rate=0.5f)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void hydraulic_blur (Array &z, float radius, float vmax, float k_smoothing=0.1f)
 Apply cell-based hydraulic erosion using a nonlinear diffusion model.
void hydraulic_diffusion (Array &z, float c_diffusion, float talus, int iterations)
 Apply cell-based hydraulic erosion using a nonlinear diffusion model.
void hydraulic_musgrave (Array &z, Array &moisture_map, int iterations=100, float c_capacity=1.f, float c_erosion=0.1f, float c_deposition=0.1f, float water_level=0.01f, float evap_rate=0.01f)
 Apply cell-based hydraulic erosion/deposition of Musgrave et al. (1989).
void hydraulic_musgrave (Array &z, int iterations=100, float c_capacity=1.f, float c_erosion=0.1f, float c_deposition=0.1f, float water_level=0.01f, float evap_rate=0.01f)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void hydraulic_stream (Array &z, float c_erosion, float talus_ref, const Array *p_bedrock=nullptr, const Array *p_moisture_map=nullptr, Array *p_erosion_map=nullptr, int ir=1, float clipping_ratio=10.f)
 Apply hydraulic erosion based on a flow accumulation map.
void hydraulic_stream (Array &z, const Array *p_mask, float c_erosion, float talus_ref, const Array *p_bedrock=nullptr, const Array *p_moisture_map=nullptr, Array *p_erosion_map=nullptr, int ir=1, float clipping_ratio=10.f)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void hydraulic_stream_log (Array &z, float c_erosion, float talus_ref, int deposition_ir=32, float deposition_scale_ratio=1.f, float gradient_power=0.8f, float gradient_scaling_ratio=1.f, int gradient_prefilter_ir=16, float saturation_ratio=1.f, const Array *p_bedrock=nullptr, const Array *p_erodibility=nullptr, const Array *p_moisture_map=nullptr, Array *p_erosion_map=nullptr, Array *p_deposition_map=nullptr, Array *p_flow_map=nullptr)
 Apply hydraulic erosion based on a flow accumulation map, alternative formulation.
void hydraulic_stream_log (Array &z, float c_erosion, float talus_ref, const Array *p_mask, int deposition_ir=32, float deposition_scale_ratio=1.f, float gradient_power=0.8f, float gradient_scaling_ratio=1.f, int gradient_prefilter_ir=16, float saturation_ratio=1.f, const Array *p_bedrock=nullptr, const Array *p_erodibility=nullptr, const Array *p_moisture_map=nullptr, Array *p_erosion_map=nullptr, Array *p_deposition_map=nullptr, Array *p_flow_map=nullptr)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void hydraulic_stream_log_multiscale (Array &z, float c_erosion, float talus_ref, int levels=3, int deposition_ir=32, float deposition_scale_ratio=1.f, float gradient_power=0.8f, float gradient_scaling_ratio=1.f, int gradient_prefilter_ir=16, float saturation_ratio=1.f, const Array *p_bedrock=nullptr, const Array *p_erodibility=nullptr, const Array *p_moisture_map=nullptr, Array *p_erosion_map=nullptr, Array *p_deposition_map=nullptr, Array *p_flow_map=nullptr, float mix=1.f, float warp=0.35f, std::uint32_t seed=1)
 Multiscale stream-power hydraulic erosion cascade.
void hydraulic_stream_log_multiscale (Array &z, float c_erosion, float talus_ref, const Array *p_mask, int levels=3, int deposition_ir=32, float deposition_scale_ratio=1.f, float gradient_power=0.8f, float gradient_scaling_ratio=1.f, int gradient_prefilter_ir=16, float saturation_ratio=1.f, const Array *p_bedrock=nullptr, const Array *p_erodibility=nullptr, const Array *p_moisture_map=nullptr, Array *p_erosion_map=nullptr, Array *p_deposition_map=nullptr, Array *p_flow_map=nullptr, float mix=1.f, float warp=0.35f, std::uint32_t seed=1)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void hydraulic_saleve (TerrainTriMesh &mesh, const std::vector< float > &erodibility, const std::vector< float > &max_slope, float m_exp=0.8f, float uplift_rate=1.f, float tolerance=1e-3f, int max_iterations=200, float noise_strength=0.f, std::uint32_t seed=0, bool enable_post_slope_limiter=false, float post_slope_limit=0.f, bool enable_post_smoothing=false)
 Perform hydraulic erosion on a triangulated terrain mesh.
Array hydraulic_saleve (const Array &z, std::uint32_t seed, size_t control_points_count=10000, float m_exp=0.8f, float uplift_rate=1.f, float tolerance=1e-3f, int max_iterations=200, float smin=0.f, float smax=6.f, float strength=0.5f, bool scale_erodibility_with_z=true, float erodibility_distrib_exp=1.f, float noise_strength=0.f, bool enable_post_slope_limiter=false, float post_slope_limit=0.f, bool enable_post_smoothing=false, InterpolationMethod2D interpolation_method=InterpolationMethod2D::ITP2D_DELAUNAY_GRADIENT, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr)
 Apply hydraulic erosion to a heightmap using an adaptive mesh.
Array hydraulic_saleve (const Array &z, const Array *p_mask, std::uint32_t seed, size_t control_points_count=10000, float m_exp=0.8f, float uplift_rate=1.f, float tolerance=1e-3f, int max_iterations=200, float smin=0.f, float smax=6.f, float strength=0.5f, bool scale_erodibility_with_z=true, float erodibility_distrib_exp=1.f, float noise_strength=0.f, bool enable_post_slope_limiter=false, float post_slope_limit=0.f, bool enable_post_smoothing=false, InterpolationMethod2D interpolation_method=InterpolationMethod2D::ITP2D_DELAUNAY_GRADIENT, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void depression_filling (Array &z, int iterations=1000, float epsilon=1e-4f, bool outflow_left=true, bool outflow_right=true, bool outflow_bottom=true, bool outflow_top=true, const UvTile &region=UvTile::dummy(), ICommunicator &comm=SingleArrayComm::instance())
 Fill the depressions of the heightmap using the Planchon-Darboux algorithm.
void depression_filling_priority_flood (Array &z, bool apply_post_filter=false, bool outflow_left=true, bool outflow_right=true, bool outflow_bottom=true, bool outflow_top=true, const UvTile &region=UvTile::dummy(), ICommunicator &comm=SingleArrayComm::instance())
 Fill depressions in a heightmap using the Priority-Flood algorithm.
void erosion_maps (Array &z_before, Array &z_after, Array &erosion_map, Array &deposition_map, float tolerance=0.f)
 Computes erosion and deposition delta maps from terrain states before and after erosion.
Array generate_bedrock (const Array &z, float elevation_strength, float slope_strength, float slope_limit, float zmin=0.f, float zmax=-1.f)
 Generates a modified bedrock heightmap from an input elevation array.
void hydraulic_mise (Array &z, const MiseParams &params=MiseParams(), const Array *p_bedrock=nullptr, const Array *p_erodibility=nullptr, const Array *p_moisture_map=nullptr, const Array *p_outlet=nullptr, Array *p_sediment=nullptr, Array *p_flow=nullptr, Array *p_erosion_map=nullptr, Array *p_deposition_map=nullptr)
 Simulates multiscale implicit stream-power hydraulic erosion (MISE).
void hydraulic_mise (Array &z, const Array *p_mask, const MiseParams &params=MiseParams(), const Array *p_bedrock=nullptr, const Array *p_erodibility=nullptr, const Array *p_moisture_map=nullptr, const Array *p_outlet=nullptr, Array *p_sediment=nullptr, Array *p_flow=nullptr, Array *p_erosion_map=nullptr, Array *p_deposition_map=nullptr)
 Simulates multiscale implicit stream-power hydraulic erosion (MISE) with an intensity mask.
bool export_asset (const std::string &fname, const Array &array, MeshType mesh_type=MeshType::TRI, AssetExportFormat export_format=AssetExportFormat::GLB2, float elevation_scaling=0.2f, const std::string &texture_fname="", const std::string &normal_map_fname="", float max_error=5e-4f, bool fit_boundaries=false)
 Exports a heightmap to various 3D file formats.
bool export_asset (const std::string &fname, const Array &array, const Array &mask, AssetExportFormat export_format=AssetExportFormat::GLB2, float elevation_scaling=0.2f, const std::string &texture_fname="", const std::string &normal_map_fname="", bool fit_boundaries=false)
void export_points_to_ply (const std::string &fname, const std::vector< float > &x, const std::vector< float > &y, const std::vector< float > &z, const std::map< std::string, std::vector< float > > &custom_fields={})
 Exports 3D points with optional custom fields to an ASCII PLY file.
void write_raw_16bit (const std::string &fname, const Array &array)
 Exports an array to a 16-bit 'raw' file format, commonly used for Unity terrain imports.
std::string export_as_ascii (const Array &array, const glm::ivec2 &export_shape={64, 64}, const std::string chars_map=" .:-=+*#%@")
 Export a 2D array as an ASCII-art string representation.
void export_as_cubemap (const std::string &fname, const Array &z, int cubemap_resolution=128, float overlap=0.25f, int ir=16, Cmap cmap=static_cast< Cmap >(0), bool splitted=false, Array *p_cubemap=nullptr)
 Exports a 2D array as a cubemap texture with continuity enforcement and overlapping regions.
void export_banner_png (const std::string &fname, const std::vector< Array > &arrays, int cmap, bool hillshading=false, bool normalize_arrays=false)
 Exports a set of arrays as a banner PNG image file.
bool export_image (const Array &array, const std::string &fname, const ImageWriterConfig &config={})
 Exports an array using the generic ImageWriter pipeline.
bool export_image (const VirtualArray &va, const std::string &fname, const ImageWriterConfig &config={})
 Exports a VirtualArray incrementally using the generic ImageWriter pipeline.
bool export_image (const VirtualArray &va, const std::string &fname, const ImageWriterConfig &config, const ComputeMode &cm)
 Exports a VirtualArray incrementally with custom compute mode.
bool export_image (const VirtualTexture &vt, const std::string &fname, const ImageWriterConfig &config={})
 Exports a VirtualTexture incrementally using the generic ImageWriter pipeline.
bool export_image (const VirtualTexture &vt, const std::string &fname, const ImageWriterConfig &config, const ComputeMode &cm)
 Exports a VirtualTexture incrementally with custom compute mode.
bool export_virtual_array (const VirtualArray &va, ImageWriter &writer)
 Streams a VirtualArray tile-by-tile into an already opened ImageWriter.
bool export_virtual_array (const VirtualArray &va, ImageWriter &writer, const ComputeMode &cm)
 Streams a VirtualArray tile-by-tile into an already opened ImageWriter with custom compute mode.
bool export_virtual_array (const VirtualTexture &vt, ImageWriter &writer)
 Streams a VirtualTexture tile-by-tile into an already opened ImageWriter.
bool export_virtual_array (const VirtualTexture &vt, ImageWriter &writer, const ComputeMode &cm)
 Streams a VirtualTexture tile-by-tile into an already opened ImageWriter with custom compute mode.
void export_normal_map_png (const std::string &fname, const Array &array, int depth=CV_8U)
 Exports the heightmap normal map as an 8-bit PNG file.
void export_splatmap_png (const std::string &fname, const Array *p_r, const Array *p_g=nullptr, const Array *p_b=nullptr, const Array *p_a=nullptr, int depth=CV_8U)
 Exports four arrays as an RGBA PNG splatmap.
void export_tiled (const std::string &fname_radical, const std::string &fname_extension, const Array &array, const glm::ivec2 &tiling, int leading_zeros=0, int depth=CV_8U, bool overlapping_edges=false, bool reverse_tile_y_indexing=false)
 Exports a 2D array as a set of grayscale PNG image tiles.
Array read_to_array (const std::string &fname, bool flip_j=false, bool remap=true)
 Reads an image file and converts it to a 2D array.
bool export_usd (const std::string &fname, const Array &elevation={}, const std::vector< Forest > &forests={}, const std::vector< RockField > &rock_fields={}, const std::vector< Cloud > &clouds={}, const std::vector< Path > &paths={}, MeshType mesh_type=MeshType::TRI, float elevation_scaling=0.2f, const std::string &texture_fname="", const std::string &normal_map_fname="", float max_error=5e-4f, bool fit_boundaries=false)
 Exports a composite scene (terrain, forests, rock fields, clouds, and paths) to Universal Scene Description (USD).
Array compute_poi_suitability_field (const Array &heightmap, PoiType type, const PoiGenerationOptions &options)
 Computes a normalized suitability/score field in [0, 1] for a given terrain feature type.
Cloud generate_points_of_interest_cloud (const Array &heightmap, PoiType type, const PoiGenerationOptions &options)
 Generates a Cloud of points of interest from a heightmap.
std::vector< PointOfInterest > generate_points_of_interest (const Array &heightmap, PoiType type, const PoiGenerationOptions &options)
 Generates a list of PointOfInterest objects from a heightmap.
std::vector< glm::vec2 > generate_points_of_interest_positions (const Array &heightmap, PoiType type, const PoiGenerationOptions &options)
 Generates 2D positions of points of interest from a heightmap.
std::vector< PointOfInterest > generate_points_from_score_field (const Array &score_field, const Array &heightmap, const PoiGenerationOptions &options, PoiType type=PoiType::CUSTOM)
 Generates a list of PointOfInterest objects from a precomputed score field.
Array connected_components (const Array &array, float surface_threshold=0.f, float background_value=0.f, std::map< float, float > *p_surfaces=nullptr, std::map< float, std::array< float, 2 > > *p_centroids=nullptr)
 Identifies and labels connected components within a binary or labeled array, with optional filtering by size.
Array geomorphons (const Array &array, int irmin, int irmax, float epsilon)
 Classifies terrain into geomorphological features based on the geomorphons method.
Array kmeans_clustering2 (const Array &array1, const Array &array2, int nclusters, std::vector< Array > *p_scoring=nullptr, Array *p_aggregate_scoring=nullptr, glm::vec2 weights={1.f, 1.f}, std::uint32_t seed=1)
 Performs k-means clustering on two input arrays, grouping similar data points into clusters.
Array kmeans_clustering3 (const Array &array1, const Array &array2, const Array &array3, int nclusters, std::vector< Array > *p_scoring=nullptr, Array *p_aggregate_scoring=nullptr, glm::vec3 weights={1.f, 1.f, 1.f}, std::uint32_t seed=1)
 Performs k-means clustering on three input arrays.
Array bulkify (const Array &z, const PrimitiveType &primitive_type, float amp=1.f, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit())
 Applies a primitive-based displacement to an array.
void canyonize (Array &array, std::uint32_t seed=0, int nlevels=6, float convex_ratio=3.0f, float gamma_convex=3.0f, float gamma_concave=0.3f, float clamp_min_val=-std::numeric_limits< float >::infinity(), float k_smooth=0.1f, float noise_ratio=0.2f, const Array *p_noise=nullptr, float vmin=1.f, float vmax=0.f)
 Applies a canyonize filter to a heightmap.
void canyonize (Array &array, std::uint32_t seed, int nlevels, const Array *p_mask, float convex_ratio=3.0f, float gamma_convex=3.0f, float gamma_concave=0.3f, float clamp_min_val=-std::numeric_limits< float >::infinity(), float k_smooth=0.1f, float noise_ratio=0.2f, const Array *p_noise=nullptr, float vmin=1.f, float vmax=0.f)
 Applies a masked canyonize filter to a heightmap.
Array dequantize (const Array &array, std::uint32_t seed, float dither_amplitude=0.01f, int filtering_iterations=1)
 Reduce quantization artifacts using dithering and smoothing.
Array distance_shaper (const Array &array, float falloff=0.05f, int directions=8, float skew=0.f, float angle=0.f, DistanceMode mode=DistanceMode::PYRAMID, DistanceMethod method=DistanceMethod::RT, float angular_jitter=0.f, float falloff_jitter=0.f, float threshold=0.f, bool invert_input=false, bool invert_output=false, float mix_ratio=1.f, std::uint32_t seed=0, const Array *p_mask=nullptr, const Array *p_dx=nullptr, const Array *p_dy=nullptr)
 Generates sloped, stratified terrain profiles from shapes and masks using directional distance fields.
void equalize (Array &array)
 Apply histogram equalization to the array values.
void equalize (Array &array, const Array *p_mask)
 Apply histogram equalization to the array values with a mask.
void expand (Array &array, int ir, const Array *p_mask, int iterations=1)
 Apply expansion, or "inflation", to emphasize the bulk of the terrain.
void expand (Array &array, int ir, int iterations=1)
 Apply expansion to emphasize the bulk of the terrain using a filter radius.
void expand (Array &array, const Array &kernel, int iterations=1)
 Apply expansion using a custom kernel.
void expand (Array &array, const Array &kernel, const Array *p_mask, int iterations=1)
 Apply expansion using a custom kernel with an optional mask.
void expand_directional (Array &array, int ir, float angle, float aspect_ratio, float anisotropy=1.f, const Array *p_mask=nullptr)
 Apply expansion, or "inflation", to emphasize the bulk of the terrain, using a directional kernel.
void expand_talus (Array &z, const Array &mask, float talus, std::uint32_t seed, int ir=1, float noise_ratio=0.2f)
 Expand heights outward from a masked region with a talus slope limit.
void fill_talus (Array &z, float talus, std::uint32_t seed, int ir=1, float noise_ratio=0.2f, const Array *p_seed_mask=nullptr)
 Enforce a talus slope constraint on a height field.
void fill_talus (Array &z, const Array &talus, std::uint32_t seed, int ir=1, float noise_ratio=0.2f, const Array *p_seed_mask=nullptr)
void fold (Array &array, float vmin, float vmax, int iterations=3, float k=0.05f)
 Apply a "folding" filter (successive absolute values) to the array elements.
void fold (Array &array, int iterations=3, float k=0.05f)
 Apply a "folding" filter with default reference values and parameters.
void fold_periodic (Array &array, PhasorProfile phasor_profile, float vmin, float vmax, int iterations=3, float delta=0.f)
 Apply a periodic "folding" filter to the array elements using a periodic phasor profile.
void fold_periodic (Array &array, PhasorProfile phasor_profile=PhasorProfile::PP_COSINE_STD, int iterations=3, float delta=0.f)
 Apply a periodic "folding" filter with default reference values.
void gain (Array &array, float factor, const Array *p_mask)
 Apply a gain correction to the array elements.
void gain (Array &array, float factor)
 Apply a gain correction to the array elements without a mask.
void gamma_correction (Array &array, float gamma, const Array *p_mask)
 Apply gamma correction to the input array.
void gamma_correction (Array &array, float gamma)
 Apply gamma correction to the input array without a mask.
void gamma_correction_local (Array &array, float gamma, int ir, float k=0.1f)
 Apply a "local" gamma correction to the input array.
void gamma_correction_local (Array &array, float gamma, int ir, const Array *p_mask, float k=0.1f)
 Apply a "local" gamma correction with a mask to the input array.
void kuwahara (Array &array, int ir, float mix_ratio=1.f)
 Applies the Kuwahara filter to an array with optional per-pixel masking.
void kuwahara (Array &array, int ir, const Array *p_mask, float mix_ratio=1.f)
 Applies the Kuwahara filter to an array with optional per-pixel masking.
void laplace (Array &array, float sigma=0.125f, int iterations=3)
 Applies an iterative 8-neighbor Laplacian smoothing filter on an array.
void laplace (Array &array, const Array *p_mask, float sigma=0.125f, int iterations=3)
 Apply a low-pass Laplace filter with a mask.
void laplace1d (std::vector< float > &v, float sigma=0.5f, int iterations=1)
 Apply a low-pass Laplace filter to a vector.
void laplace_edge_preserving (Array &array, float talus, float sigma=0.2f, int iterations=3)
 Apply a low-pass anisotropic Laplace filter to the input array.
void laplace_edge_preserving (Array &array, float talus, const Array *p_mask, float sigma=0.2f, int iterations=3)
 Apply a low-pass anisotropic Laplace filter with a mask.
void low_pass_high_order (Array &array, int order=9, float sigma=1.f)
 Apply a low-pass high-order filter to the input array.
void make_binary (Array &array, float threshold=0.f)
 Convert array values to binary using a threshold.
void match_histogram (Array &array, const Array &array_reference)
 Transform the input array elevation to match the histogram of a reference array.
Array mean_shift (const Array &array, int ir, float talus, int iterations=1, bool talus_weighted=true)
 Applies the mean shift algorithm to the input array.
Array mean_shift (const Array &array, int ir, float talus, const Array *p_mask, int iterations=1, bool talus_weighted=true)
void median_3x3 (Array &array, const Array *p_mask)
 Apply a 3x3 median filter to the input array.
void median_3x3 (Array &array)
 Apply a 3x3 median filter to the input array without a mask.
Array median_pseudo (const Array &array, int ir)
 Computes a fast pseudo-median approximation of a local neighborhood in an array.
void normal_displacement (Array &array, float amount=0.1f, int ir=0, bool reverse=false)
 Apply a displacement to the terrain along the normal direction.
void normal_displacement (Array &array, const Array *p_mask, float amount=0.1f, int ir=0, bool reverse=false)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void plateau (Array &array, const Array *p_mask, int ir, float factor)
 Apply a plateau-shape filter to the input array.
void plateau (Array &array, int ir, float factor)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
Array quantize (const Array &array, int nlevels, float vmin, float vmax)
 Quantize array values into discrete levels.
Array quantize (const Array &array, int nlevels)
 Quantize array values using the array min/max range.
void recast_billow (Array &array, float vref, float k)
 Transform heightmap to give a "billow" like appearance.
void recast_canyon (Array &array, const Array &vcut, float gamma=4.f)
 Transform heightmap to give a "canyon" like appearance.
void recast_canyon (Array &array, const Array &vcut, const Array *p_mask, float gamma=4.f)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void recast_canyon (Array &array, float vcut, const Array *p_mask, float gamma=4.f, const Array *p_noise=nullptr)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void recast_canyon (Array &array, float vcut, float gamma=4.f, const Array *p_noise=nullptr)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void recast_cracks (Array &array, float cut_min=0.05f, float cut_max=0.5f, float k_smoothing=0.01f, float vmin=0.f, float vmax=-1.f)
void recast_escarpment (Array &array, int ir=16, float ratio=0.1f, float scale=1.f, bool reverse=false, bool transpose_effect=false, float global_scaling=0.f)
 Applies an escarpment effect to the given 2D array, modifying its values based on cumulative displacement with optional directional and transpositional transformations.
void recast_escarpment (Array &array, const Array *p_mask, int ir=16, float ratio=0.1f, float scale=1.f, bool reverse=false, bool transpose_effect=false, float global_scaling=0.f)
 Applies an escarpment effect to the given 2D array, with an optional mask to blend the effect.
void recast_peak (Array &array, int ir, float gamma=2.f, float k=0.1f)
 Transform heightmap to give a "peak" like appearance.
void recast_peak (Array &array, int ir, const Array *p_mask, float gamma=2.f, float k=0.1f)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void recast_rocky_slopes (Array &array, float talus, int ir, float amplitude, std::uint32_t seed, float kw, float gamma=0.5f, const Array *p_noise=nullptr, const UvRect &uv_rect=UvRect::unit())
 Transform heightmap by adding "rock-like" features at higher slopes.
void recast_rocky_slopes (Array &array, float talus, int ir, float amplitude, std::uint32_t seed, float kw, const Array *p_mask, float gamma=0.5f, const Array *p_noise=nullptr, const UvRect &uv_rect=UvRect::unit())
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void recast_sag (Array &array, float vref, float k)
 Transform heightmap to give a "cliff" like appearance.
void recast_sag (Array &array, float vref, float k, const Array *p_mask)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void recurve (Array &array, const std::vector< float > &t, const std::vector< float > &v)
 Apply a curve adjustment filter to the array.
void recurve (Array &array, const std::vector< float > &t, const std::vector< float > &v, const Array *p_mask)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void recurve_bexp (Array &array, float tau=0.5f)
 Apply a curve adjustment filter using a "bumpy exponential-shape" curve.
void recurve_bexp (Array &array, const Array *p_mask, float tau=0.5f)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void recurve_exp (Array &array, float tau=0.5f)
 Apply a curve adjustment filter using a "sharp exponential-shape" curve.
void recurve_exp (Array &array, const Array *p_mask, float tau=0.5f)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void recurve_kura (Array &array, float a, float b)
 Apply a curve adjustment filter using Kumaraswamy's cumulative distribution function (CDF).
void recurve_kura (Array &array, float a, float b, const Array *p_mask)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void recurve_s (Array &array)
 Apply a curve adjustment filter using a smooth "S-shape" curve.
void recurve_s (Array &array, const Array *p_mask)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void recurve_smoothstep_rational (Array &array, float n)
 Apply a curve adjustment filter using an nth-order smoothstep curve.
void recurve_smoothstep_rational (Array &array, float n, const Array *p_mask)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void reverse_above_theshold (Array &array, const Array &threshold, float scaling=1.f, float transition_extent=0.f)
 Applies a smooth reversal of values above a given threshold.
void reverse_above_theshold (Array &array, float threshold, float scaling=1.f, float transition_extent=0.f)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void reverse_above_theshold (Array &array, const Array &threshold, const Array *p_mask, float scaling=1.f, float transition_extent=0.f)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void reverse_above_theshold (Array &array, float threshold, const Array *p_mask, float scaling=1.f, float transition_extent=0.f)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void ridge_accentuate (Array &array, float strength=0.1f, int ir=0, bool reverse=false)
 Accentuate ridges by gradient-directed resampling along the normal direction.
void ridge_accentuate (Array &array, const Array *p_mask, float strength=0.1f, int ir=0, bool reverse=false)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void saturate (Array &array, float vmin, float vmax, float from_min, float from_max, float k=0.f)
 Saturate the array values based on the input interval [vmin, vmax] (the output amplitude is not modified).
void saturate (Array &array, float vmin, float vmax, float k=0.f)
void saturate_percentile (Array &array, float percentile_low, float percentile_high, float k=0.f)
 Saturate values based on percentile range.
void sharpen (Array &array, float ratio=1.f)
 Apply a sharpening filter based on the Laplace operator.
void sharpen (Array &array, const Array *p_mask, float ratio=1.f)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void sharpen_cone (Array &array, int ir, float intensity=0.5f)
 Apply a sharpening filter based on a smooth cone filter.
void sharpen_cone (Array &array, const Array *p_mask, int ir, float scale=0.5f)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void shrink (Array &array, int ir, int iterations=1)
 Apply shrinking, or "deflating", to emphasize the ridges in the heightmap.
void shrink (Array &array, int ir, const Array *p_mask, int iterations=1)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void shrink (Array &array, const Array &kernel, int iterations=1)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void shrink (Array &array, const Array &kernel, const Array *p_mask, int iterations=1)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void shrink_directional (Array &array, int ir, float angle, float aspect_ratio, float anisotropy=1.f, const Array *p_mask=nullptr)
 Apply directional shrinking, or "deflating", to emphasize the ridges in the terrain.
void smooth_cone (Array &array, int ir)
 Apply a convolution filter with a cone kernel to smooth the array.
void smooth_cone (Array &array, int ir, const Array *p_mask)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void smooth_cpulse (Array &array, int ir, const Array *p_mask=nullptr, const UvTile &region=UvTile::dummy(), ICommunicator &comm=SingleArrayComm::instance())
 Apply filtering to the array using convolution with a cubic pulse kernel.
void smooth_cpulse_edge_removing (Array &array, float talus, float talus_width, int ir)
 Smooths an array while attenuating edges using a gradient-based pulse.
void smooth_flat (Array &array, int ir)
 Applies a smoothing average filter to the given 2D array in both dimensions.
void smooth_gaussian (Array &array, int ir)
 Apply Gaussian filtering to the array.
void smooth_gaussian (Array &array, int ir, const Array *p_mask)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void smooth_fill (Array &array, int ir, float k=0.1f, Array *p_deposition_map=nullptr)
 Apply cubic pulse smoothing to fill lower flat regions while preserving some sharpness.
void smooth_fill (Array &array, int ir, const Array *p_mask, float k=0.1f, Array *p_deposition_map=nullptr)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void smooth_fill_holes (Array &array, int ir)
 Apply smoothing to fill holes (elliptic concave surfaces).
void smooth_fill_holes (Array &array, int ir, const Array *p_mask)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void smooth_fill_smear_peaks (Array &array, int ir)
 Apply smoothing to smear peaks (elliptic convex surfaces).
void smooth_fill_smear_peaks (Array &array, int ir, const Array *p_mask)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void smoothstep_local (Array &array, int ir)
 Applies a localized smoothstep operation to the provided array.
void smoothstep_local (Array &array, int ir, const Array *p_mask)
 Applies a localized smoothstep operation to the provided array with an optional mask.
void steepen (Array &array, float scale, int ir=8)
 Steepen (or flatten) the array map.
void steepen (Array &array, float scale, const Array *p_mask, int ir=8)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void steepen_convective (Array &array, float angle, int iterations=1, int ir=0, float dt=0.1f)
 Steepen array values by applying a nonlinear convection operator in a given direction.
void steepen_convective (Array &array, float angle, const Array *p_mask, int iterations=1, int ir=0, float dt=0.1f)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void terrace (Array &array, std::uint32_t seed, int nlevels, float gain=0.9f, float noise_ratio=0.f, const Array *p_noise=nullptr, float vmin=0.f, float vmax=-1.f)
 Applies a terrace effect to the values in an array.
void terrace (Array &array, std::uint32_t seed, int nlevels, const Array *p_mask, float gain=0.9f, float noise_ratio=0.f, const Array *p_noise=nullptr, float vmin=0.f, float vmax=-1.f)
 Applies a terrace effect to an array with optional masking.
std::function< float(float, float)> make_xy_function_from_array (const Array &array, const BBox2D &bbox=BBox2D::unit())
 Create a continuous 2D function from a sampled array.
template<typename Fn>
decltype(auto) with_noise_function (NoiseType noise_type, glm::vec2 kw, std::uint32_t seed, Fn &&fn)
 Dispatch a noise functor based on the specified noise type.
void add_line_bresenham (CellPath &out, glm::ivec2 a, glm::ivec2 b)
 Rasterizes a segment between two integer points using Bresenham's algorithm.
void add_noise (CellPath &path, std::uint32_t seed, float kw, float amp, const glm::ivec2 &shape, NoiseType noise_type=NoiseType::PERLIN, int octaves=8, float weight=0.7f, float persistence=0.5f, float lacunarity=2.f)
 Applies transverse noise displacement along an integer path.
void enforce_path_adjacency (CellPath &path)
 Ensures that an integer path is grid-adjacent and gap-free.
bool is_path_adjacent (const CellPath &path)
 Checks if a grid path has no gaps (8-connectivity).
Array cloud_sdf_to_array (const Cloud &cloud, glm::ivec2 shape, const BBox2D &bbox_array=BBox2D::unit(), const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr)
 Compute a distance field from a point cloud.
bool has_duplicates (const Cloud &cloud, float eps=1e-9f, bool xy_only=true)
 Checks whether the point cloud contains duplicate points.
std::vector< float > interpolate_values_from_array (const Cloud &cloud, const Array &array, const BBox2D &bbox)
 Interpolate values from an array at the points' (x, y) locations.
Cloud merge_cloud (const Cloud &cloud1, const Cloud &cloud2)
 Merges two point clouds into one.
Cloud merge_clouds (const std::vector< Cloud > &clouds)
 Merges multiple point clouds into a single cloud.
Cloud random_cloud (size_t count, std::uint32_t seed, const PointSamplingMethod &method=PointSamplingMethod::RND_LHS, const BBox2D &bbox=BBox2D{})
 Generates a random cloud of points within a bounding box.
Cloud random_cloud_density (size_t count, const Array &density, std::uint32_t seed, const BBox2D &bbox=BBox2D{})
 Generates a random cloud of points based on a spatial density map.
Cloud random_cloud_inverse_sampling (size_t count, const Array &density, std::uint32_t seed, const BBox2D &bbox=BBox2D{})
 Generates a random cloud of points using inverse transform sampling on a 2D density array.
Cloud random_cloud_distance (float min_dist, std::uint32_t seed, const BBox2D &bbox=BBox2D{})
 Generates a random cloud of points separated by at least a given minimum distance.
Cloud random_cloud_distance (float min_dist, float max_dist, const Array &density, std::uint32_t seed, const BBox2D &bbox=BBox2D{})
 Generates a random cloud of points separated by a distance range, influenced by a density map.
Cloud random_cloud_distance_power_law (float dist_min, float dist_max, float alpha, std::uint32_t seed, const BBox2D &bbox=BBox2D{})
 Generates a random cloud of points with distances drawn from a power-law distribution.
Cloud random_cloud_distance_weibull (float dist_min, float lambda, float k, std::uint32_t seed, const BBox2D &bbox=BBox2D{})
 Generates a random cloud of points with distances drawn from a Weibull distribution.
Cloud random_cloud_jittered (size_t count, const glm::vec2 &jitter_amount, const glm::vec2 &stagger_ratio, std::uint32_t seed, const BBox2D &bbox=BBox2D{})
 Generates a jittered grid cloud of points.
void rejection_filter_density (Cloud &cloud, const Array &density_mask, std::uint32_t seed, const BBox2D &bbox=BBox2D{})
 Filter a point cloud using rejection sampling based on a density mask.
Cloud scale (const Cloud &cloud, glm::vec2 scale, glm::vec2 center={0.5f, 0.5f})
 Scales the point coordinates in a cloud relative to a center point.
Cloud scale (const Cloud &cloud, float scale, glm::vec2 center={0.5f, 0.5f})
int convert_length_to_pixel (float x, int nx, bool lim_inf=true, bool lim_sup=false, float scale=1.f)
 Converts a length value to a pixel index in a discretized space.
void grid_xy_vector (std::vector< float > &x, std::vector< float > &y, glm::ivec2 shape, const UvRect &uv_rect=UvRect::unit(), bool endpoint=false)
 Return x and y coordinates of a regular grid, as two 1D vectors.
void rescale_grid_from_unit_square_to_bbox (std::vector< float > &x, std::vector< float > &y, const UvRect &uv_rect)
 Rescale 1D grid vectors from unit square [0, 1] to target UV rectangle.
Path bezier (const Path &path, float curvature_ratio=0.3f, int edge_divisions=10, Path::EdgeDivisionMode edm=Path::EdgeDivisionMode::EDM_PER_EDGE)
 Smooth the path using Bezier curves.
Path bezier_round (const Path &path, float curvature_ratio=0.3f, int edge_divisions=10, Path::EdgeDivisionMode edm=Path::EdgeDivisionMode::EDM_PER_EDGE)
 Smooth the path using Bezier curves (alternative method).
Path bspline (const Path &path, int edge_divisions=10, Path::EdgeDivisionMode edm=Path::EdgeDivisionMode::EDM_PER_EDGE)
 Smooth the path using B-Spline curves.
Path catmullrom (const Path &path, int edge_divisions=10, Path::EdgeDivisionMode edm=Path::EdgeDivisionMode::EDM_PER_EDGE)
 Smooth the path using Catmull-Rom curves.
Path decasteljau (const Path &path, int edge_divisions=10, Path::EdgeDivisionMode edm=Path::EdgeDivisionMode::EDM_PER_EDGE)
 Smooth the path using De Casteljau curves.
Path decimate_vw (const Path &path, int n_points_target=3)
 Simplifies the current path using the Visvalingam-Whyatt algorithm.
Path fractalize (const Path &path, int iterations, std::uint32_t seed, float sigma=0.2f, int orientation=0, float persistence=1.f, Array *p_control_field=nullptr, const BBox2D &bbox=BBox2D{}, bool bounded=false)
 Applies fractalization to the path by adding points and randomly displacing their positions.
Path inflate (const Path &path, float strength, bool resample=true)
 Inflate (offset) a path along its normals using curvature.
Path meanderize (const Path &path, float ratio, float noise_ratio=0.1f, std::uint32_t seed=1, int iterations=1, int edge_divisions=10, Path::EdgeDivisionMode edm=Path::EdgeDivisionMode::EDM_PER_EDGE)
 Add "meanders" to the path.
Array path_sdf_bezier_to_array (const Path &path, glm::ivec2 shape, const BBox2D &bbox_array=BBox2D::unit(), const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, bool use_bvh=true)
 Converts a 2D path treated as a piecewise quadratic Bezier curve to a signed distance field (SDF) array.
Array path_sdf_bezier_to_array_brute_force (const Path &path, glm::ivec2 shape, const BBox2D &bbox_array=BBox2D::unit(), const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr)
Array path_sdf_bezier_to_array_bvh (const Path &path, glm::ivec2 shape, const BBox2D &bbox_array=BBox2D::unit(), const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr)
Array path_sdf_to_array (const Path &path, glm::ivec2 shape, const BBox2D &bbox_array=BBox2D::unit(), const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, bool use_bvh=true)
 Compute a distance field from a point path.
Array path_sdf_to_array_brute_force (const Path &path, glm::ivec2 shape, const BBox2D &bbox_array=BBox2D::unit(), const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr)
Array path_sdf_to_array_bvh (const Path &path, glm::ivec2 shape, const BBox2D &bbox_array=BBox2D::unit(), const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr)
Path remove_geometric_loops (const Path &path)
 Removes geometric loops in a 2D path caused by self-intersections.
Path scale (const Path &path, glm::vec2 scale, glm::vec2 center={0.5f, 0.5f})
 Scales the point coordinates in a path relative to a center point.
Path scale (const Path &path, float scale, glm::vec2 center={0.5f, 0.5f})
Path smooth (const Path &path, int navg=1, float averaging_intensity=1.f, float inertia=0.f)
 Applies a smoothing operation to the path points using a moving average filter.
Path squiggle (const Path &path, int iterations=4, std::uint32_t seed=0, float height_ratio=0.5f, int orientation=0, const Array *p_weights=nullptr, const Array *p_mask=nullptr, const BBox2D &bbox=BBox2D{})
 Generates a continuous, non-self-intersecting squiggle curve by applying the squiggle recursive triangle subdivision algorithm to each edge of the input path.
std::vector< Path > squiggle_branches (const Path &path, int iterations=4, std::uint32_t seed=0, float branch_probability=0.3f, int max_branches=8, float height_ratio=0.5f, int orientation=0, const Array *p_weights=nullptr, const Array *p_mask=nullptr, const BBox2D &bbox=BBox2D{})
 Generates squiggle paths with secondary tributary branches along each edge.
Path truncate_at_first_intersection (const Path &path, const std::vector< Path > &existing_paths)
 Truncates a path at its first intersection with any path in a given set of existing paths. The intersection point is included as the new end point.
bool assert_start_end_points (const Path &path1, const Path &path2, float tol=1e-6f, bool verbose=false)
 Asserts that the start and end points of two paths are within a specified tolerance.
float chamfer_distance (const Path &a, const Path &b)
 Calculate the chamfer distance between two paths.
bool has_duplicates (const Path &path, float tol=1e-6f)
 Check if a path contains duplicate points within a given tolerance.
float angle (const Point &p1, const Point &p2)
 Computes the angle between two points relative to the x-axis.
float angle (const Point &p0, const Point &p1, const Point &p2)
 Computes the angle formed by three points with p0 as the origin.
float classify_point (const Point &p_prev, const Point &p, const Point &p_next, const Point &pq)
 Classify point convexity relative to neighboring curve vertices.
float cross_product (const Point &p0, const Point &p1, const Point &p2)
 Computes the 2D cross product of vectors (p1 - p0) and (p2 - p0).
float cross_product (const Point &p1, const Point &p2)
 Computes the 2D cross product of vectors p1 and p2.
float curvature (const Point &p1, const Point &p2, const Point &p3)
 Calculates the curvature formed by three points in 2D space.
float curvature_signed (const Point &p1, const Point &p2, const Point &p3)
 Calculates the signed curvature formed by three points in 2D space.
float distance (const Point &p1, const Point &p2)
 Calculates the Euclidean distance between two points.
float distance_squared (const Point &p1, const Point &p2)
 Calculates the squared Euclidean distance between two points.
Point interp_bezier (const Point &p_start, const Point &p_ctrl_start, const Point &p_ctrl_end, const Point &p_end, float t)
 Performs a cubic Bezier interpolation.
Point interp_bspline (const Point &p0, const Point &p1, const Point &p2, const Point &p3, float t)
 Performs a cubic B-spline interpolation.
Point interp_catmullrom (const Point &p0, const Point &p1, const Point &p2, const Point &p3, float t)
 Performs a Catmull-Rom spline interpolation.
Point interp_decasteljau (const std::vector< Point > &points, float t)
 Performs a De Casteljau algorithm-based interpolation for Bezier curves.
BBox2D intersect_bounding_boxes (const BBox2D &bbox1, const BBox2D &bbox2)
 Determines the intersection of two bounding boxes.
bool is_point_within_bounding_box (const Point &p, const BBox2D &bbox)
 Checks if a point is within a specified bounding box.
bool is_point_within_bounding_box (float x, float y, const BBox2D &bbox)
 Checks if a point with coordinates (x, y) is within a specified bounding box.
Point lerp (const Point &p1, const Point &p2, float t)
 Linearly interpolates between two points.
Point midpoint (const Point &p1, const Point &p2, int orientation, float distance_ratio, float t=0.5f)
 Computes the midpoint displacement with a perpendicular offset.
Point scale (const Point &p, glm::vec2 scale, glm::vec2 center={0.5f, 0.5f})
 Scales a point relative to a center point.
Point scale (const Point &p, float scale, glm::vec2 center={0.5f, 0.5f})
 Scales a point uniformly relative to a center point.
std::optional< Point > segment_intersection (const Point &p1, const Point &p2, const Point &q1, const Point &q2)
 Computes the intersection point of two 2D segments, if it exists.
float side (const Point &p1, const Point &p2, const Point &p3, const Point &p_query)
 Determines the relative side of a query point with respect to a curve segment.
void sort_points (std::vector< Point > &points)
 Sorts a vector of points in ascending order (x, then y, then v).
float triangle_area (const Point &p1, const Point &p2, const Point &p3)
 Calculates the unsigned area of a triangle formed by three points.
float triangle_area_signed (const Point &p1, const Point &p2, const Point &p3)
 Calculates the signed area of a triangle formed by three points.
BBox2D unit_square_bbox ()
 Constructs a 4D bounding box for a unit square {0, 1, 0, 1}.
std::array< std::pair< float, float >, 2 > bbox_to_ranges2d (const BBox2D &bbox)
 Converts a 2D bounding box into coordinate ranges.
void expand_points_domain (std::vector< float > &x, std::vector< float > &y, std::vector< float > &value, const BBox2D &bbox=BBox2D{})
 Expand grid by translating and copying the values of the current bounding box to the 8 first neighboring bounding boxes.
void expand_points_at_domain_boundaries (std::vector< float > &x, std::vector< float > &y, std::vector< float > &value, const BBox2D &bbox=BBox2D{}, float boundary_value=0.f)
 Expand the grid by adding points on the boundaries of the bounding box.
void expand_points_domain_corners (std::vector< float > &x, std::vector< float > &y, std::vector< float > &value, const BBox2D &bbox=BBox2D{}, float corner_value=0.f)
 Expand the grid by adding four points at the corner of the bounding box.
std::function< float(const ps::Point< float, 2 > &)> make_pointwise_function_from_array (const Array &array, const BBox2D &bbox)
 Create a continuous 2D function from a sampled array.
std::array< std::vector< float >, 2 > random_points (size_t count, std::uint32_t seed, const PointSamplingMethod &method=PointSamplingMethod::RND_RANDOM, const BBox2D &bbox=BBox2D{})
 Generates random 2D points within a bounding box using a sampling method.
std::array< std::vector< float >, 2 > random_points_density (size_t count, const Array &density, std::uint32_t seed, const BBox2D &bbox=BBox2D{})
 Generates random 2D points within a bounding box based on a density map.
std::array< std::vector< float >, 2 > random_points_inverse_sampling (size_t count, const Array &array, std::uint32_t seed, const BBox2D &bbox=BBox2D{})
 Generates random 2D points within a bounding box using inverse transform sampling on a 2D density array.
std::array< std::vector< float >, 2 > random_points_distance (float min_dist, std::uint32_t seed, const BBox2D &bbox=BBox2D{})
 Generates random 2D points with a minimum separation distance.
std::array< std::vector< float >, 2 > random_points_distance (float min_dist, float max_dist, const Array &density, std::uint32_t seed, const BBox2D &bbox=BBox2D{})
 Generates random 2D points with distance constraints and a density map.
std::array< std::vector< float >, 2 > random_points_distance_power_law (float dist_min, float dist_max, float alpha, std::uint32_t seed, const BBox2D &bbox=BBox2D{})
 Generates random 2D points with distances drawn from a power-law distribution.
std::array< std::vector< float >, 2 > random_points_distance_weibull (float dist_min, float lambda, float k, std::uint32_t seed, const BBox2D &bbox=BBox2D{})
 Generates random 2D points with distances drawn from a Weibull distribution.
std::array< std::vector< float >, 2 > random_points_jittered (size_t count, const glm::vec2 &jitter_amount, const glm::vec2 &stagger_ratio, std::uint32_t seed, const BBox2D &bbox=BBox2D{})
 Generates jittered grid-based 2D points.
void remove_points_outside_bbox (std::vector< float > &x, std::vector< float > &y, std::vector< float > &value, const BBox2D &bbox=BBox2D{})
 Remove grid points that are outside a given bounding box.
void rescale_points_to_unit_square (std::vector< float > &x, std::vector< float > &y, const BBox2D &bbox)
 Rescale coordinate (x, y) so that they fit in a unit-square box based on a given initial bounding box.
Array divergence_from_gradients (const Array &dx, const Array &dy)
 Compute the divergence of a 2D gradient field.
std::vector< float > gradient1d (const std::vector< float > &v)
 Compute the gradient of a 1D vector.
Array gradient_angle (const Array &array, bool downward=false)
 Compute the polar angle of the gradient of a 2D array.
Array gradient_angle_circular_smoothing (const Array &array, int ir, bool downward=false)
 Computes a smoothed gradient angle (aspect) field with circular unwrapping.
Array gradient_norm (const Array &array, Array *p_dx=nullptr, Array *p_dy=nullptr)
 Compute the gradient norm of a 2D array.
Array gradient_norm_filtered (const Array &array, int ir)
 Compute a smoothed gradient magnitude map.
Array gradient_norm_prewitt (const Array &array, Array *p_dx=nullptr, Array *p_dy=nullptr)
 Compute the gradient norm of a 2D array using the Prewitt filter.
Array gradient_norm_scharr (const Array &array, Array *p_dx=nullptr, Array *p_dy=nullptr)
 Compute the gradient norm of a 2D array using the Scharr filter.
Array gradient_norm_sobel (const Array &array, Array *p_dx=nullptr, Array *p_dy=nullptr)
 Compute the gradient norm of a 2D array using the Sobel filter.
Array gradient_talus (const Array &array)
 Compute the gradient talus slope of a 2D array.
void gradient_talus (const Array &array, Array &talus)
 Compute the gradient talus slope and store it in the provided array.
Array gradient_x (const Array &array)
 Compute the gradient in the x-direction of a 2D array.
void gradient_x (const Array &array, Array &dx)
 Compute the gradient in the x-direction of a 2D array and store it.
Array gradient_y (const Array &array)
 Compute the gradient in the y-direction of a 2D array.
void gradient_y (const Array &array, Array &dy)
 Compute the gradient in the y-direction of a 2D array and store it.
Array laplacian (const Array &array)
 Compute the Laplacian of a 2D array.
Texture normal_map (const Array &array)
 Generates a normal map from a given 2D array.
Array normal_map_to_heightmap (const Texture &nmap)
 Converts a normal map to a heightmap using direct summation of gradients.
Array normal_map_to_heightmap_poisson (const Texture &nmap, int iterations=500, float omega=1.5f)
void solve_poisson_gauss_seidel (const Array &rhs, Array &h, int iterations=500, float omega=1.0f)
 Solve the Poisson equation ∇²h = rhs using Gauss–Seidel iteration.
Array unwrap_phase (const Array &alpha)
 Unwraps a 2D phase array to correct discontinuities in phase data.
Array talus_jump_mask (const Array &z, float threshold, float sigma)
Array basin_id (const Array &z, bool fast_approx=false, bool remove_lakes=true)
 Label drainage basins using a priority-flood algorithm.
Array carve_riverbed (const Array &z, const Array &z_river, float talus_riverbank=0.01f, bool smooth_river_bottom=true, float merging_distance=8.f, std::uint32_t seed=0, float riverbank_noise_ratio=0.f, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr)
 Blends and carves smooth riverbanks around modified riverbed profiles.
Array d8_compute_ndip (const Array &d8)
 Computes the number of drainage paths for each cell based on the D8 flow direction model.
void find_flow_apex (const Array &z, std::vector< int > &is, std::vector< int > &js)
 Identifies flow apex (source) cells using D8 flow routing.
void find_flow_sinks (const Array &z, std::vector< int > &is, std::vector< int > &js)
 Identifies the indices of flow sinks within the heightmap.
std::vector< glm::ivec2 > find_flow_sinks (const Array &z)
 Find interior flow sinks in a height field.
std::vector< glm::ivec2 > find_flow_sinks_border (const Array &z)
 Find flow sinks located on the domain border.
Array flooding_uniform_level (const Array &z, float zref)
 Compute water depth for a uniform flooding level.
Array flooding_from_boundaries (const Array &z, float zref, bool from_east=true, bool from_west=true, bool from_north=true, bool from_south=true, const UvTile &region=UvTile::dummy(), ICommunicator &comm=SingleArrayComm::instance())
 Compute flooding starting from the lowest boundary points.
Array flooding_from_point (const Array &z, int i, int j, float depth_min=std::numeric_limits< float >::max(), const UvTile &region=UvTile::dummy(), ICommunicator &comm=SingleArrayComm::instance())
 Flood terrain starting from a single seed point.
Array flooding_from_point (const Array &z, const std::vector< int > &i, const std::vector< int > &j, float depth_min=std::numeric_limits< float >::max(), const UvTile &region=UvTile::dummy(), ICommunicator &comm=SingleArrayComm::instance())
 Flood terrain starting from multiple seed points.
Array flooding_lake_system (const Array &z, float surface_threshold=0.f, const UvTile &region=UvTile::dummy(), ICommunicator &comm=SingleArrayComm::instance())
 Estimate lake water depths on a terrain by filling depressions.
Array flow_accumulation_d8 (const Array &z)
 Computes the flow accumulation for each cell using the D8 flow direction model.
Array flow_accumulation_stochastic (const Array &z, int n_samples=1<< 19, std::uint32_t seed=0, const Array *p_source=nullptr, const Array *p_decay=nullptr)
 Computes flow accumulation using a stochastic (Monte-Carlo) transport estimator.
Array flow_accumulation_dinf (const Array &z, float talus_ref=0.1f, int iterations=0, const UvTile &region={}, ICommunicator &comm=SingleArrayComm::instance())
 Computes the flow accumulation for each cell using the Multiple Flow Direction (MFD) model.
Array flow_accumulation_dinf_perturbed (const Array &z, float talus_ref, int nsamples, glm::vec2 kw, std::uint32_t seed, float amp, const Array *p_perturb_scaling=nullptr, const UvRect &uv_rect=UvRect::unit(), int iterations=0, const UvTile &region={}, ICommunicator &comm=SingleArrayComm::instance())
 Computes averaged D-infinity flow accumulation with terrain perturbations.
Array flow_direction_d8 (const Array &z)
 Computes the flow direction from each cell to its downslope neighbor using the D8 model.
std::vector< Array > flow_direction_dinf (const Array &z, float talus_ref)
 Computes the flow direction and weights for each direction using the Multiple Flow Direction (MFD) model.
std::vector< float > flow_direction_dinf_flat (const Array &z, float talus_ref)
Array flow_direction_dinf_angle (const Array &z, float talus_ref)
 Computes the flow direction using the Multiple Flow Direction (MFD) model.
Array flow_fixing (const Array &z, float riverbed_talus=0.f, int iterations=5, int prefilter_ir=8, bool carve_riverbed=true, float merging_distance=8.f, const Array *p_noise_r=nullptr)
Array flow_fixing_drainage_basin (const Array &z, bool fast_approx=false, float riverbed_talus=1e-4f, int iterations=3, bool carve_riverbed=false, float talus_riverbank=0.01f, float merging_distance=8.f, std::uint32_t seed=0, float noise_strength=0.f, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr)
 Fixes flow paths and unwanted upslopes using a cell-based drainage basin tree network and elevation updates.
Array flow_fixing_mst (const Array &z, float riverbed_talus=0.f, float elevation_ratio=0.95f, float distance_exponent=2.f, float upward_penalization=0.1f, float valley_affinity=0.5f, int prefilter_ir=8, float minimum_depth=1e-4f, bool carve_riverbed=true, float merging_distance=8.f, RadialProfile radial_profile=RadialProfile::RP_SMOOTHSTEP_UPPER, float radial_profile_parameter=2.f, const Array *p_noise_r=nullptr, bool use_midpoint=false, float offset_ratio=0.2f)
 Resolves flow sinks and unwanted upslopes using Dijkstra pathfinding and a Minimum Spanning Tree (MST) over sinks and boundary outlets.
std::vector< Path > flow_fixing_mst_paths (const TerrainTriMesh &mesh, float riverbed_talus=0.f, float elevation_ratio=0.95f, float distance_exponent=2.f, float upward_penalization=0.1f, float minimum_depth=1e-4f)
 Computes river flow paths resolving depressions via Minimum Spanning Tree (MST) on a triangular terrain mesh.
std::vector< Path > flow_fixing_mst_paths (const Array &z, size_t control_points_count=2048, std::uint32_t seed=0, float riverbed_talus=0.f, float elevation_ratio=0.95f, float distance_exponent=2.f, float upward_penalization=0.1f, float minimum_depth=1e-4f)
 Computes river flow paths resolving depressions via Minimum Spanning Tree (MST) on a triangular mesh generated from a heightmap.
Array flow_fixing_mst_triangulated (const Array &z, size_t control_points_count=2048, std::uint32_t seed=0, float riverbed_talus=0.f, float elevation_ratio=0.95f, float distance_exponent=2.f, float upward_penalization=0.1f, float minimum_depth=1e-4f, float merging_distance=8.f, RadialProfile radial_profile=RadialProfile::RP_SMOOTHSTEP_UPPER, float radial_profile_parameter=2.f, const Array *p_noise_r=nullptr)
 Resolves flow sinks on a heightmap by computing an MST on a triangular mesh and carving the resulting river paths with trenching.
Path flow_stream (const Array &z, const glm::ivec2 ij_start, const float elevation_ratio=0.5f, const float distance_exponent=2.f, const float upward_penalization=100.f, const std::vector< Path > &existing_streams={}, const int valley_radius=2, const float valley_factor=0.35f, const bool truncate_at_intersection=false)
 Computes the optimal flow path from a starting point to the boundary of a given elevation array.
Path flow_stream (const TerrainTriMesh &mesh, size_t start_vertex_index, float elevation_ratio=0.5f, float distance_exponent=2.f, float upward_penalization=100.f, bool favor_domain_center=false, const std::vector< Path > &existing_streams={}, float valley_radius=0.02f, float valley_factor=0.35f, bool truncate_at_intersection=false)
 Computes the optimal flow path from a starting vertex to the boundary of a terrain triangular mesh.
Path flow_stream (const TerrainTriMesh &mesh, glm::vec2 xy_start, float elevation_ratio=0.5f, float distance_exponent=2.f, float upward_penalization=100.f, bool favor_domain_center=false, const std::vector< Path > &existing_streams={}, float valley_radius=0.02f, float valley_factor=0.35f, bool truncate_at_intersection=false)
 Computes the optimal flow path from starting 2D coordinates to the boundary of a terrain triangular mesh.
Array generate_riverbed (const Path &path, glm::ivec2 shape, const UvRect &uv_rect=UvRect::unit(), bool bezier_smoothing=false, float depth_start=0.01f, float depth_end=1.f, float slope_start=64.f, float slope_end=32.f, float shape_exponent_start=1.f, float shape_exponent_end=10.f, float k_smoothing=0.5f, int post_filter_ir=0, Array *p_noise_x=nullptr, Array *p_noise_y=nullptr, Array *p_noise_r=nullptr)
 Generates a 2D array representing a riverbed based on a specified path.
Graph hydrology_paths_to_graph (const std::vector< Path > &paths, float snap_tolerance=1e-4f)
 Convert a collection of hydrology flow paths into a connected Graph.
Array merge_water_depths (const Array &depth1, const Array &depth2, float k_smooth=0.f)
 Merge two water depth fields.
Array snow_melting_map (const Array &z, float melt_start_elevation=0.f, float melt_end_elevation=0.5f, float elevation_strength=1.f, float elevation_exp=1.f, float sun_azimuth=0.f, float sun_zenith=60.f, float aspect_strength=0.f, float slope_exp=1.f, float slope_strength=0.f)
 Generate a spatial snow melting map from terrain features.
Array water_depth_from_mask (const Array &z, const Array &mask, float mask_threshold=0.f, int iterations_max=10000, float tolerance=1e-2f)
 Compute water depth over a masked terrain using harmonic interpolation.
void water_depth_dry_out (Array &water_depth, float dry_out_ratio=0.5f, const Array *p_mask=nullptr, float depth_max=std::numeric_limits< float >::max())
 Apply a drying factor to a water depth field.
Array water_depth_increase (const Array &water_depth, const Array &z, float additional_depth)
 Simulates a local increase in water depth without global reflooding.
Array water_depth_increase_with_flooding (const Array &water_depth, const Array &z, float additional_depth)
 Simulates a physical rise in water level with full domain flooding.
Array water_frontier_curvature (const Array &water_depth, int prefilter_ir, bool extend_values_from_interface=false)
 Compute the curvature of the water interface from a signed distance field.
Array water_mask (const Array &water_depth)
 Generates a binary mask representing water presence.
Array water_mask (const Array &water_depth, const Array &z, float additional_depth)
 Computes a gradient-based water mask using an extended water depth model.
bool assert_almost_equal (const Array &a, const Array &b, float tolerance=1e-6f, const std::string &fname="", AssertResults *p_results=nullptr)
bool is_subset (const Array &a, const Array &b)
void print_array (const Array &arr, bool show_coords=false, int width=6, int precision=2)
void dump_visual_check (const Array &array, const std::string &fname="check.png")
uint32_t float_key (float f)
float key_float (uint32_t k)
float next_up (float f)
std::filesystem::path add_filename_suffix (const std::filesystem::path &file_path, const std::string &suffix)
 Adds a suffix to the filename of a given file path.
std::filesystem::path make_unique_temp_dir (const std::string &prefix)
 Create a unique temporary directory.
std::string zfill (const std::string &str, int n_zero)
 Pads the beginning of a string with zeros until it reaches a specified length.
bool validate_shape (glm::ivec2 shape, const std::source_location &loc=std::source_location::current())
 Validates that array dimensions are strictly positive.
bool validate_non_empty (const Array &array, const std::source_location &loc=std::source_location::current())
 Validates that an array is initialized, non-empty, and has a consistent buffer size.
template<typename T>
requires requires(const T &t) { { t.empty() } -> std::convertible_to<bool>; }
bool validate_non_empty (const T &container, std::string_view name="Container", const std::source_location &loc=std::source_location::current())
 Validates that a container or object with an empty() method is not empty.
template<typename T>
requires requires(const T &t) { { t.size() } -> std::convertible_to<size_t>; }
bool validate_min_size (const T &container, size_t min_size, std::string_view name="Container", const std::source_location &loc=std::source_location::current())
 Validates that a container has at least min_size elements.
bool validate_same_shape (const Array &a, const Array &b, const std::source_location &loc=std::source_location::current())
 Validates that two arrays have identical shapes and buffer sizes.
bool validate_same_shape (glm::ivec2 shape, const Array &b, const std::source_location &loc=std::source_location::current())
 Validates that an array has the expected 2D shape.
bool validate_non_empty (const Texture &tex, int min_channels=1, const std::source_location &loc=std::source_location::current())
 Validates that a Texture is initialized, non-empty, and has valid channel buffers.
bool validate_channels (const Texture &tex, int expected_channels, const std::source_location &loc=std::source_location::current())
 Validates exact channel count of a Texture.
bool validate_same_shape (const Texture &a, const Texture &b, const std::source_location &loc=std::source_location::current())
 Validates that two Textures have matching 2D shapes.
bool validate_same_shape (const Texture &tex, const Array &arr, const std::source_location &loc=std::source_location::current())
 Validates that a Texture and an Array have matching 2D shapes.
bool validate_slice (const Array &array, glm::ivec4 idx, const std::source_location &loc=std::source_location::current())
 Validates that a slice extent {i1, i2, j1, j2} is valid and within array boundaries.
bool validate_slice_for_array (const Array &dest, glm::ivec4 idx, const Array &src, const std::source_location &loc=std::source_location::current())
 Validates that a slice extent matches the dimensions of a source array.
bool validate_not_zero (float value, const std::source_location &loc=std::source_location::current())
 Validates that a divisor value is not zero.
bool validate_parameter_range (glm::vec2 range, float min_val, float max_val, std::string_view param_name="Range", const std::source_location &loc=std::source_location::current())
 Validates that a 2D range vector {low, high} lies within [min_val, max_val] with low <= high.
bool validate_finite (const Array &array, const std::source_location &loc=std::source_location::current())
 Validates that all elements of an array are finite (not NaN or Inf).
bool validate_cmap (int cmap, const std::source_location &loc=std::source_location::current())
 Validates that a colormap ID corresponds to a valid Cmap enum value.
constexpr float bilinear_interp (float f00, float f10, float f01, float f11, float u, float v) noexcept
 Compute the bilinear interpolated value from four input values.
void bspline_weights (float t, float w[4]) noexcept
 Compute uniform cubic B-spline weights for a fractional parameter in [0, 1).
constexpr float cubic_interpolate (const float p[4], float x) noexcept
Array harmonic_interpolation (const Array &array, const Array &mask_fixed_values, int iterations_max=500, float tolerance=1e-5f, float omega=0.f, int sync_interval=0, const UvTile &region=UvTile::unit(), ICommunicator &comm=SingleArrayComm::instance())
 Perform harmonic interpolation on a 2D array using the Successive Over-Relaxation (SOR) method.
Array harmonic_interpolation (const Array &array, const Array &mask_fixed_values, const Array &dx, const Array &dy, int iterations_max=500, float tolerance=1e-5f, float omega=0.f, int sync_interval=0, const UvTile &region=UvTile::unit(), ICommunicator &comm=SingleArrayComm::instance())
 Perform harmonic interpolation on a 2D array with 2D variable diffusion coefficients (Dx, Dy) using the Successive Over-Relaxation (SOR) method.
Array interpolate2d (glm::ivec2 shape, const std::vector< float > &x, const std::vector< float > &y, const std::vector< float > &values, InterpolationMethod2D interpolation_method, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit())
 Generic 2D interpolation function.
Array interpolate2d_delaunay (glm::ivec2 shape, const std::vector< float > &x, const std::vector< float > &y, const std::vector< float > &values, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit(), float fill_value=0.f)
 2D interpolation using the Delaunay triangulation method.
Array interpolate2d_delaunay_gradient (glm::ivec2 shape, const std::vector< float > &x, const std::vector< float > &y, const std::vector< float > &values, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit(), float fill_value=0.f, float gradient_scaling=1.f)
 2D interpolation using a smoother version of the Delaunay triangulation method.
Array interpolate2d_gaussian (glm::ivec2 shape, const std::vector< float > &x, const std::vector< float > &y, const std::vector< float > &values, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit(), float sigma=0.05f, float radius=0.f)
 2D interpolation using the Gaussian kernel method.
Array interpolate2d_idw (glm::ivec2 shape, const std::vector< float > &x, const std::vector< float > &y, const std::vector< float > &values, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit(), float distance_exp=2.f, float radius=0.f)
 2D interpolation using the IDW method.
Array interpolate2d_nearest (glm::ivec2 shape, const std::vector< float > &x, const std::vector< float > &y, const std::vector< float > &values, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit())
 2D interpolation using the nearest neighbor method.
Array interpolate2d_nni (glm::ivec2 shape, const std::vector< float > &x, const std::vector< float > &y, const std::vector< float > &values, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit())
 2D interpolation using the Natural Neighbor Interpolation method.
void interpolate_array_bicubic (const Array &source, Array &target, bool endpoint=false, bool pixel_centered=true)
 Resample an array to a target array using bicubic interpolation.
void interpolate_array_bicubic (const Array &source, Array &target, const UvRect &uv_rect_source, const UvRect &uv_rect_target, bool endpoint=false, bool pixel_centered=true)
 Resample a source array into a target array using bicubic interpolation between two local axis-aligned bounding boxes.
void interpolate_array_bilinear (const Array &source, Array &target, bool endpoint=false, bool pixel_centered=true)
 Resample an array to a target array using bilinear interpolation.
void interpolate_array_bilinear (const Array &source, Array &target, const UvRect &uv_rect_source, const UvRect &uv_rect_target, bool endpoint=false, bool pixel_centered=true)
 Resample a source array into a target array using bilinear interpolation between two local axis-aligned bounding boxes.
void interpolate_array_nearest (const Array &source, Array &target, bool endpoint=false)
 Resample an array to a target array using nearest-neighbor interpolation.
void interpolate_array_nearest (const Array &source, Array &target, const UvRect &uv_rect_source, const UvRect &uv_rect_target, bool endpoint=false)
 Resample a source array into a target array using nearest-neighbor interpolation between two local axis-aligned bounding boxes.
Array resample_bicubic_warp (const Array &src, glm::ivec2 dst_shape, float warp=0.f, std::uint32_t seed=0)
 Resample an array to a target shape using cubic B-spline interpolation with optional domain noise warping.
void flatten_terrain (Array &h_source1, const Array &h_source2, const CoordFrame &t_source1, const CoordFrame &t_source2, bool bilinear=true)
 Blend a second terrain array in-place onto a base terrain array using their world-space coordinate frames.
void flatten_terrain (const std::vector< const Array * > &h_sources, Array &h_target, const std::vector< const CoordFrame * > &t_sources, const CoordFrame &t_target, bool bilinear=true)
 Flatten multiple terrain arrays into a target array using their world-space coordinate frames.
void interpolate_terrain (const Array &h_source, Array &h_target, const CoordFrame &t_source, const CoordFrame &t_target, bool bilinear=true, float fill_value=0.f, Array *p_mask=nullptr)
 Project and interpolate a source terrain array onto a target terrain array using their world-space coordinate frames.
void flatten_terrain (VirtualArray &h_source1, const VirtualArray &h_source2, const CoordFrame &t_source1, const CoordFrame &t_source2, const ComputeMode &cm, bool bilinear=true)
 Blend a second terrain VirtualArray in-place onto a base terrain VirtualArray using their world-space coordinate frames.
void flatten_terrain (const std::vector< const VirtualArray * > &h_sources, VirtualArray &h_target, const std::vector< const CoordFrame * > &t_sources, const CoordFrame &t_target, const ComputeMode &cm, bool bilinear=true)
 Flatten multiple terrain VirtualArrays into a target VirtualArray using their world-space coordinate frames.
void interpolate_terrain (const VirtualArray &h_source, VirtualArray &h_target, const CoordFrame &t_source, const CoordFrame &t_target, const ComputeMode &cm, bool bilinear=true, float fill_value=0.f, VirtualArray *p_mask=nullptr)
 Project and interpolate a source terrain VirtualArray onto a target terrain VirtualArray using their world-space coordinate frames.
Array get_kernel (glm::ivec2 shape, KernelType kernel_type)
 Generate a kernel of the specified type.
Array biweight (glm::ivec2 shape)
 Generates a biweight kernel array.
Array blackman (glm::ivec2 shape)
 Generates a Blackman window array with the specified shape.
Array cone (glm::ivec2 shape)
 Generates a cone-shaped kernel array.
Array cone_talus (float height, float talus)
 Generates a cone-shaped kernel with specified height and talus.
Array cone_smooth (glm::ivec2 shape)
 Generates a cone-shaped kernel with a smooth landing.
Array cubic_pulse (glm::ivec2 shape)
 Generates a cubic pulse kernel array.
std::vector< float > cubic_pulse_1d (int nk)
 Generates a 1D cubic pulse kernel.
Array cubic_pulse_directional (glm::ivec2 shape, float angle, float aspect_ratio, float anisotropy)
 Generates a "directional" cubic pulse kernel.
Array cubic_pulse_truncated (glm::ivec2 shape, float slant_ratio, float angle)
 Generates a truncated cubic pulse kernel.
Array cupola (glm::ivec2 shape, float rc=0.5f)
 Generate a 2D radial cupola kernel.
Array disk (glm::ivec2 shape)
 Generates a disk-shaped kernel footprint.
Array disk_smooth (glm::ivec2 shape, float r_cutoff=0.9f)
 Generates a smooth, disk-shaped kernel footprint with soft edges.
Array gabor (glm::ivec2 shape, float kw, float angle, bool quad_phase_shift=false)
 Generates a Gabor kernel of the specified shape.
Array gabor_dune (glm::ivec2 shape, float kw, float angle, float xtop, float xbottom)
 Generates a modified dune-like Gabor kernel.
Array hann (glm::ivec2 shape)
 Generates a Hann window array with the specified shape.
Array lorentzian (glm::ivec2 shape, float footprint_threshold=0.1f)
 Generate a Lorentzian kernel.
Array lorentzian_compact (glm::ivec2 shape)
 Generate a modified Lorentzian kernel with compact support.
Array sinc_radial (glm::ivec2 shape, float kw)
 Generates a radial sinc function array with the specified shape and wave number.
Array sinc_separable (glm::ivec2 shape, float kw)
 Generates a separable sinc function array with the specified shape and wave number.
Array smooth_cosine (glm::ivec2 shape)
 Generate a smooth cosine kernel.
Array square (glm::ivec2 shape)
 Generate a square-shaped kernel.
Array tricube (glm::ivec2 shape)
 Generate a tricube kernel.
Array path_length_to_outlet (const Array &z)
 Computes the downstream path length to the domain outlet.
Array path_length_to_sink (const Array &z)
 Computes the downstream path length to the nearest sink.
Array local_max (const Array &array, int ir)
 Return the local maxima based on a maximum filter with a square kernel.
Array local_median_deviation (const Array &array, int ir)
 Computes the local median deviation of a 2D array.
Array local_min (const Array &array, int ir)
 Return the local minima based on a maximum filter with a square kernel.
Array local_mean (const Array &array, int ir)
 Return the local mean based on a mean filter with a square kernel.
Array relative_elevation (const Array &array, int ir)
 Calculates the relative elevation within a specified radius, helping to identify local highs and lows.
Array roughness (const Array &array, int ir)
 Measures the local surface roughness within a given radius.
Array ruggedness (const Array &array, int ir)
 Computes the ruggedness of each element in the input array.
Array rugosity (const Array &z, int ir, bool convex=true)
 Estimates the rugosity of a surface by analyzing the skewness of the elevation data, which reflects surface roughness.
Array topographic_wetness_index (const Array &z, float talus_ref=0.f, float min_slope=1e-4f)
 Computes the Topographic Wetness Index (TWI).
Array topographic_residual (const Array &z, int ir, bool normalize_output=false)
 Computes the topographic residual (relief) relative to a smoothed surface.
Array valley_width (const Array &z, int ir=0, bool ridge_select=false)
 Measures the valley width by calculating the distance from each point in a concave region to the frontier of that region.
Array abs (const Array &array)
 Absolute value.
Array abs_smooth (const Array &array, float mu, const Array &vshift)
 Smooth absolute value.
Array abs_smooth (const Array &array, float mu, float vshift)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
Array abs_smooth (const Array &array, float mu)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
Array almost_unit_identity (const Array &array)
 Almost unit identity function.
Array almost_unit_identity_c2 (const Array &array)
 Almost unit identity function (C2 variant).
Array atan (const Array &array)
 Arctangent.
Array atan2 (const Array &y, const Array &array)
 Element-wise arctangent with quadrant handling.
Array build_density_linear (const std::vector< const Array * > &layers, const std::vector< float > &weights={})
 Combine a list of layers in linear space.
Array build_density_log (const std::vector< const Array * > &layers, const std::vector< float > &weights={}, float eps=1e-6f)
 Combine a list of layers in log space.
Array cos (const Array &array)
 Cosine.
Array exp (const Array &array)
 Exponential.
Array gaussian_decay (const Array &array, float sigma)
 Gaussian decay.
Array hypot (const Array &array1, const Array &array2)
 Hypotenuse.
Array is_equal (const Array &array, float value)
 Binary mask of elements equal to a value.
Array is_non_zero (const Array &array)
 Binary mask of non-zero elements.
Array is_zero (const Array &array)
 Binary mask of zero elements.
Array lerp (const Array &array1, const Array &array2, const Array &t)
 Linear interpolation.
Array lerp (const Array &array1, const Array &array2, float t)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
Array log10 (const Array &array)
 Base-10 logarithm.
Array log_safe (const Array &array, float eps=1e-6f)
 Safe natural logarithm with lower clamp.
Array pow (const Array &array, float exp)
 Power function.
Array r_min (const Array &array1, const Array &array2, float alpha=0.f)
 Generalized Rvachev R-function for smooth minimum / intersection (exact zero-set).
Array r_max (const Array &array1, const Array &array2, float alpha=0.f)
 Generalized Rvachev R-function for smooth maximum / union (exact zero-set).
Array sigmoid (const Array &array, float width=1.f, float vmin=0.f, float vmax=1.f, float x0=0.f)
 Sigmoid function.
Array sin (const Array &array)
 Sine.
Array smoothstep3 (const Array &array, float vmin=0.f, float vmax=1.f)
 Cubic smoothstep.
Array smoothstep3_lower (const Array &array)
 Cubic smoothstep (zero derivative at 0 only).
Array smoothstep3_upper (const Array &array)
 Cubic smoothstep (zero derivative at 1 only).
Array smoothstep5 (const Array &array, float vmin=0.f, float vmax=1.f)
 Quintic smoothstep.
Array smoothstep5 (const Array &array, const Array &vmin, const Array &vmax)
Array smoothstep5_lower (const Array &array)
 Quintic smoothstep (zero derivative at 0 only).
Array smoothstep5_upper (const Array &array)
 Quintic smoothstep (zero derivative at 1 only).
Array smoothstep7 (const Array &array)
 Seventh-order smoothstep.
Array sqrt (const Array &array)
 Square root.
Array sqrt_safe (const Array &array)
 Safe square root.
Array threshold (const Array &array, float x0, float x1)
 Linear threshold.
Array threshold_smooth (const Array &array, float x0, float x1)
 Smooth threshold.
Array convolve1d_i (const Array &array, const std::vector< float > &kernel)
 Return the convolution product of the array with a 1D kernel along the 'i' direction.
Array convolve1d_j (const Array &array, const std::vector< float > &kernel)
 Return the convolution product of the array with a 1D kernel along the 'j' direction.
Array convolve2d (const Array &array, const Array &kernel)
 Return the convolution product of the array with a given 2D kernel.
Array convolve2d_truncated (const Array &array, const Array &kernel)
 Return the convolution product of the array with a given 2D kernel, with a truncated output size.
Array convolve2d_svd (const Array &z, const Array &kernel, int rank=3)
 Return the approximate convolution product of the array with a Singular Value Decomposition (SVD) of a kernel.
Array convolve2d_svd_rotated_kernel (const Array &z, const Array &kernel, int rank=3, int n_rotations=6, std::uint32_t seed=1)
 Return the approximate convolution product of the array with a Singular Value Decomposition (SVD) of a kernel combined with kernel rotations.
float abs_smooth (float a, float mu)
 Smooth absolute value.
float almost_unit_identity (float x)
 Almost unit identity function.
float almost_unit_identity_c2 (float x)
 Almost unit identity function (C2 variant).
float approx_hypot (float a, float b)
 Approximate hypotenuse.
float approx_rsqrt (float a)
 Fast inverse square root approximation.
int ceil_div (int a, int b)
 Integer ceiling division.
float fast_exp (float x)
 Fast exponential approximation.
float fast_log (float x)
 Fast natural logarithm approximation.
float gain (float x, float factor)
 Gain curve remapping in [0,1].
int highest_power_of_2 (int n)
 Highest power of 2 less than or equal to n.
float lerp (float a, float b, float t)
 Linear interpolation.
float log_safe (float x, float eps=1e-6f)
 Safe natural logarithm with lower clamp.
float power_curve (float x, float a, float b)
 Smooth asymmetric bell-shaped curve on [0,1].
float r_min (float f1, float f2, float alpha=0.f)
 Generalized Rvachev R-function for smooth minimum / intersection (exact zero-set).
float r_max (float f1, float f2, float alpha=0.f)
 Generalized Rvachev R-function for smooth maximum / union (exact zero-set).
float sigmoid (float x, float width=1.f, float vmin=0.f, float vmax=1.f, float x0=0.f)
 Sigmoid function.
float smoothstep3 (float x)
 Cubic smoothstep function.
float smoothstep3 (float x, float clamp_min, float clamp_max)
 Cubic smoothstep function with clamping.
float smoothstep3_lower (float x)
 Cubic smoothstep (zero derivative at 0 only).
float smoothstep3_upper (float x)
 Cubic smoothstep (zero derivative at 1 only).
float smoothstep5 (float x)
 Quintic smoothstep function.
float smoothstep5_lower (float x)
 Quintic smoothstep (zero derivative at 0 only).
float smoothstep5_upper (float x)
 Quintic smoothstep (zero derivative at 1 only).
float smoothstep7 (float x)
 Seventh-order smoothstep function.
float threshold (float x, float x0, float x1)
 Linear threshold.
float threshold_smooth (float x, float x0, float x1)
 Smooth threshold using smoothstep.
float trapeze (float x, float x0, float x1, float width)
 Computes a trapezoidal pulse function.
float trapeze_smooth (float x, float x0, float x1, float width)
 Smooth trapezoidal pulse using cubic smoothstep interpolation.
float triangle (float x, float vmin, float vmax)
 Triangle function between bounds.
std::function< float(float, float)> get_distance_function (DistanceFunction dist_fct, DistanceFunctionAxis dfa=DistanceFunctionAxis::DFA_XY)
 Return the requested distance function.
std::function< float(float)> get_erosion_profile_function (const ErosionProfile &erosion_profile, float delta, float &profile_avg)
 Generates a function representing an erosion profile based on the specified type and parameters.
std::function< float(float)> get_phasor_profile_function (PhasorProfile phasor_profile, float delta, float *p_profile_avg=nullptr)
 Generates a function representing a phasor profile based on the specified type and parameters.
std::function< float(float)> get_radial_profile_function (RadialProfile radial_profile, float delta)
 Returns a normalized radial profile function.
Array area_remove (const Array &array, float threshold_size, float background_value=0.f, float fill_value=0.f)
 Remove connected components smaller than a given size threshold.
Array border (const Array &array, int ir)
 Apply a border algorithm to the input array using a square structure.
Array closing (const Array &array, int ir)
 Apply a closing algorithm to the input array using a square structure.
Array closing_by_reconstruction (const Array &array, int ir, float k_smooth_max=0.f)
 Apply closing by reconstruction to the input array.
Array contour_smoothing (const Array &array, int ir, float transition_ratio=0.1f)
 Smooth contour boundaries of segmented regions.
Array dilation (const Array &array, int ir)
 Apply a dilation algorithm to the input array using a square structure.
Array dilation_expand_border_only (const Array &array, int ir)
 Expand non-zero regions of an array by morphological dilation, while preserving the original non-zero values.
Array dilation_expand_min_value_border_only (const Array &array)
Array distance_transform (const Array &array, bool return_squared_distance=false, const UvTile &region=UvTile::dummy(), ICommunicator &comm=SingleArrayComm::instance())
 Return the Euclidean distance transform.
Array distance_transform_approx (const Array &array, bool return_squared_distance=false)
 Calculates an approximate distance transform of the input array.
Array distance_transform_manhattan (const Array &array, bool return_squared_distance=false)
 Calculates the Manhattan distance transform of an array.
Array distance_transform_with_closest (const Array &array, Mat< glm::ivec2 > &closest, bool return_squared_distance=false)
 Return the Euclidean distance transform.
Array erosion (const Array &array, int ir)
 Apply an erosion algorithm to the input array using a square structure.
void flood_fill (Array &array, int i, int j, float fill_value=1.f, float background_value=0.f)
 Apply a flood fill algorithm to the input array.
Array morphological_black_hat (const Array &array, int ir)
 Apply a morphological black hat algorithm to the input array using a square structure.
Array morphological_gradient (const Array &array, int ir)
 Apply a morphological gradient algorithm to the input array using a square structure.
Array morphological_laplacian (const Array &array, int ir)
 Apply a morphological Laplacian operator to the input array using a square structure.
Array morphological_top_hat (const Array &array, int ir)
 Apply a morphological top hat algorithm to the input array using a square structure.
Array opening (const Array &array, int ir)
 Apply an opening algorithm to the input array using a square structure.
Array opening_by_reconstruction (const Array &array, int ir, float k_smooth_min=0.f)
 Apply opening by reconstruction to the input array.
Array reconstruction_by_dilation (const Array &marker, const Array &mask, int ir, float k_smooth_min=0.f)
 Perform morphological reconstruction by dilation.
Array reconstruction_by_erosion (const Array &marker, const Array &mask, int ir, float k_smooth_max=0.f)
 Perform morphological reconstruction by erosion.
Array relative_distance_from_skeleton (const Array &array, int ir_search, bool zero_at_borders=true, int ir_erosion=1)
 Computes the relative distance of each non-zero cell in a binary array from the skeleton and border.
Array relative_distance_from_skeleton (const Array &array, const Array &skeleton, int ir_search, int ir_erosion=1)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
Array skeleton (const Array &array, const Array &skeleton, bool zero_at_borders=true)
 Computes a skeletonized version of an array.
Array remove_endpoints (const Array &array, int iterations=1, float background_value=0.f)
 Removes endpoint-like pixels from a binary/weighted array.
Array signed_curvature_from_distance (const Array &array, int prefilter_ir=0)
 Computes the signed curvature of the distance transform.
Array signed_distance_transform (const Array &array, int prefilter_ir=0)
 Computes a signed distance transform using curvature sign.
Array skeleton (const Array &array, bool zero_at_borders=true)
 Computes the skeleton of a binary image using the Zhang-Suen skeletonization algorithm.
Array morphological_operators (const Array &array, int ir, hmap::MorphologyOperation operation, MinMaxKernel kernel_type=MinMaxKernel::DISK)
 Apply a morphological operation to the input array using a square kernel.
bool init_openmp (int num_threads=-1)
void log_openmp_info ()
void add_kernel (Array &array, const Array &kernel, int i, int j)
 Add a kernel to a specified position in an array.
void add_kernel_maximum_smooth (Array &array, const Array &kernel, float k_smooth, int i, int j)
 Adds a smoothed maximum value from a kernel to a specified position in a 2D array.
Array compare (const Array &a, const Array &b, float slice_x_pos, float slice_y_pos)
 Combines two arrays by selecting values from a or b based on a slice position.
Array hstack (const Array &array1, const Array &array2)
 Horizontally stack two arrays side by side.
Array inpainting_diffusion (const Array &array, const Array &mask, int iterations)
 Perform diffusion-based inpainting to fill a specified region of an array.
std::vector< float > linspace (float start, float stop, int num, bool endpoint=true)
 Generate a vector of evenly spaced numbers over a specified interval.
std::vector< float > linspace_jitted (float start, float stop, int num, float ratio, int seed, bool endpoint=true)
 Generate a vector of jittered (noised) numbers over a specified interval.
std::vector< float > logspace (float start, float stop, int num, bool endpoint=true)
 Generates a logarithmically spaced vector.
template<typename Fn>
void fill_array_using_xy_function (Array &array, const UvRect &uv_rect, const Array *p_ctrl_param, const Array *p_noise_x, const Array *p_noise_y, const Array *p_stretching, Fn &&fct_xy)
 Fill an array using a scalar function based on (x, y) coordinates.
template<typename Fn>
void fill_array_using_xy_function (Array &array, const UvRect &uv_rect, const Array *p_ctrl_param, const Array *p_noise_x, const Array *p_noise_y, const Array *p_stretching, Fn &&fct_xy, int subsampling)
 Fill an array using a scalar function based on (x, y) coordinates with subsampling.
void find_vertical_cut_path (const Array &error, std::vector< int > &path_i)
 Find the vertical cut path with the minimum cost using dynamic programming.
Array generate_mask (glm::ivec2 shape, std::vector< int > cut_path_i, int ir)
 Generate a smooth mask based on a cut path.
Array get_random_patch (const Array &array, glm::ivec2 patch_shape, std::mt19937 &gen, bool patch_flip=false, bool patch_rotate=false, bool patch_transpose=false, std::vector< Array * > *p_secondary_arrays=nullptr, std::vector< Array > *p_secondary_patches=nullptr)
 Extracts a random sub-array (patch) from the input array, with optional transformations.
std::vector< float > random_vector (float min, float max, int num, int seed)
 Generate a vector filled with random values within a specified range.
void rescale_vector (std::vector< float > &vec, float vmin, float vmax)
 Rescales the values of a vector to a specified range.
std::vector< float > rescaled_vector (const std::vector< float > &vec, float vmin, float vmax)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void swap (Array &a, Array &b)
 Swaps the contents of two Array objects.
Array vstack (const Array &array1, const Array &array2)
 Vertically stack two arrays.
template<typename Fn>
void apply_with_mask (Array &array, const Array *p_mask, Fn &&fn)
 Applies a transformation function with optional masked blending.
template<typename Fn>
Array transform_with_mask (const Array &array, const Array *p_mask, Fn &&fn)
 Applies a transformation function with optional masked blending.
Array dendry (glm::ivec2 shape, glm::vec2 kw, std::uint32_t seed, Array &control_function, float eps=0.05, int resolution=1, float displacement=0.075, int primitives_resolution_steps=3, float slope_power=2.f, float noise_amplitude_proportion=0.01, bool add_control_function=true, float control_function_overlap=0.5f, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit(), int subsampling=1)
 Dendry is a locally computable procedural function that generates branching patterns at various scales (see [Gaillard2019]).
Array dendry (glm::ivec2 shape, glm::vec2 kw, std::uint32_t seed, const std::function< float(float, float, float)> &noise_function, float noise_function_offset=0.f, float noise_function_scaling=1.f, float eps=0.05, int resolution=1, float displacement=0.075, int primitives_resolution_steps=3, float slope_power=2.f, float noise_amplitude_proportion=0.01, bool add_control_function=true, float control_function_overlap=0.5f, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit())
Array diffusion_limited_aggregation (glm::ivec2 shape, float scale, std::uint32_t seed, float seeding_radius=0.4f, float seeding_outer_radius_ratio=0.2f, float slope=8.f, float noise_ratio=0.2f)
 Generates a diffusion-limited aggregation (DLA) pattern.
Array diffusion_limited_aggregation_trimesh (glm::ivec2 shape, std::uint32_t seed, size_t control_points_count=5000, glm::vec2 seed_position={0.5f, 0.5f}, float ratio=0.98f, float stop_proba=1.f, float slope=16.f, InterpolationMethod2D interpolation_method=InterpolationMethod2D::ITP2D_DELAUNAY_GRADIENT, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr)
Array gabor_noise (glm::ivec2 shape, float kw, float angle, int width, float density, std::uint32_t seed)
 Return a sparse Gabor noise.
Array noise (NoiseType noise_type, glm::ivec2 shape, glm::vec2 kw, std::uint32_t seed, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit(), float angle=0.f, float stretch=1.f)
 Return an array filled with coherence noise.
Array noise_fbm (NoiseType noise_type, glm::ivec2 shape, glm::vec2 kw, std::uint32_t seed, int octaves=8, float weight=0.7f, float persistence=0.5f, float lacunarity=2.f, const Array *p_ctrl_param=nullptr, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit(), float angle=0.f, float stretch=1.f, float stretch_decay=0.f)
 Return an array filled with coherence fbm noise.
Array noise_iq (NoiseType noise_type, glm::ivec2 shape, glm::vec2 kw, std::uint32_t seed, int octaves=8, float weight=0.7f, float persistence=0.5f, float lacunarity=2.f, float gradient_scale=0.05f, const Array *p_ctrl_param=nullptr, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit(), float angle=0.f, float stretch=1.f, float stretch_decay=0.f)
 Return an array filled with coherence fbm noise.
Array noise_jordan (NoiseType noise_type, glm::ivec2 shape, glm::vec2 kw, std::uint32_t seed, int octaves=8, float weight=0.7f, float persistence=0.5f, float lacunarity=2.f, float warp0=0.4f, float damp0=1.f, float warp_scale=0.4f, float damp_scale=1.f, const Array *p_ctrl_param=nullptr, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit(), float angle=0.f, float stretch=1.f, float stretch_decay=0.f)
 Return an array filled with coherence fbm noise.
Array noise_parberry (glm::ivec2 shape, glm::vec2 kw, std::uint32_t seed, int octaves=8, float weight=0.7f, float persistence=0.5f, float lacunarity=2.f, float mu=1.02f, const Array *p_ctrl_param=nullptr, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit(), float angle=0.f, float stretch=1.f, float stretch_decay=0.f)
 Return an array filled with coherent fbm Parberry variant of Perlin noise.
Array noise_pingpong (NoiseType noise_type, glm::ivec2 shape, glm::vec2 kw, std::uint32_t seed, int octaves=8, float weight=0.7f, float persistence=0.5f, float lacunarity=2.f, const Array *p_ctrl_param=nullptr, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit(), float angle=0.f, float stretch=1.f, float stretch_decay=0.f)
 Return an array filled with coherence fbm pingpong noise.
Array noise_ridged (NoiseType noise_type, glm::ivec2 shape, glm::vec2 kw, std::uint32_t seed, int octaves=8, float weight=0.7f, float persistence=0.5f, float lacunarity=2.f, float k_smoothing=0.1f, const Array *p_ctrl_param=nullptr, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit(), float angle=0.f, float stretch=1.f, float stretch_decay=0.f)
 Return an array filled with coherence fbm ridged noise.
Array noise_slope (NoiseType noise_type, glm::ivec2 shape, glm::vec2 kw, std::uint32_t seed, int octaves=8, float weight=0.7f, float persistence=0.5f, float lacunarity=2.f, float gradient_scale=0.5f, float slope_power=2.f, float octave_blend=0.5f, float bias_angle=0.f, float bias_strength=0.f, const Array *p_ctrl_param=nullptr, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit(), float angle=0.f, float stretch=1.f, float stretch_decay=0.f)
 Return an array filled with slope-weighted coherence fbm noise.
Array noise_swiss (NoiseType noise_type, glm::ivec2 shape, glm::vec2 kw, std::uint32_t seed, int octaves=8, float weight=0.7f, float persistence=0.5f, float lacunarity=2.f, float warp_scale=0.1f, const Array *p_ctrl_param=nullptr, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit(), float angle=0.f, float stretch=1.f, float stretch_decay=0.f)
 Return an array filled with coherence fbm swiss noise.
Array worley_double (glm::ivec2 shape, glm::vec2 kw, std::uint32_t seed, float ratio=0.5f, float k=0.f, const Array *p_ctrl_param=nullptr, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit())
 Return an array filled with the maximum of two Worley (cellular) noises.
Array get_primitive_base (const PrimitiveType &primitive_type, const glm::ivec2 &shape, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit())
 Generates a primitive shape as a 2D array.
Array band (glm::ivec2 shape, float angle, float length=0.5f, float width=0.1f, RadialProfile profile=RadialProfile::RP_SMOOTHSTEP, float profile_param=0.f, const Array *p_noise_r=nullptr, const Array *p_noise_offset=nullptr, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit())
 Generate a bounded band (capsule) mask.
Array biquad_pulse (glm::ivec2 shape, float gain=1.f, const Array *p_ctrl_param=nullptr, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit())
 Return a 'biquadratic pulse'.
Array biquad_pulse_x (glm::ivec2 shape, const UvRect &uv_rect=UvRect::unit())
Array biquad_pulse_y (glm::ivec2 shape, const UvRect &uv_rect=UvRect::unit())
Array bump (glm::ivec2 shape, float gain=1.f, const Array *p_ctrl_param=nullptr, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit())
 Return a bump.
Array bump_lorentzian (glm::ivec2 shape, float shape_factor=0.5f, float radius=0.5f, const Array *p_ctrl_param=nullptr, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit())
 Generates a 2D Lorentzian bump pattern.
Array checkerboard (glm::ivec2 shape, glm::vec2 kw, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit())
 Return a checkerboard heightmap.
Array cone (glm::ivec2 shape, float slope, float apex_elevation=1.f, bool smooth_profile=false, glm::vec2 center={0.5f, 0.5f}, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit())
 Generates a synthetic conical mountain heightmap.
Array cone_complex (glm::ivec2 shape, float alpha, float radius=0.5f, bool smooth_profile=true, float valley_amp=0.2f, int valley_nb=5, float valley_decay_ratio=0.5f, float valley_angle0=15.f, const ErosionProfile &erosion_profile=ErosionProfile::EP_TRIANGLE_GRENIER, float erosion_delta=0.01f, float radial_waviness_amp=0.05f, float radial_waviness_kw=2.f, float bias_angle=30.f, float bias_amp=0.75f, float bias_exponent=1.f, glm::vec2 center={0.5f, 0.5f}, const Array *p_ctrl_param=nullptr, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit())
 Generates a complex conical heightfield with valleys, directional bias, and radial waviness.
Array cone_sigmoid (glm::ivec2 shape, float alpha, float radius=0.5f, glm::vec2 center={0.5f, 0.5f}, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit())
 Generates a smooth conical heightmap using a sigmoid-based profile.
Array constant (glm::ivec2 shape, float value=0.f)
 Return a constant value array.
Array cubic_pulse (glm::ivec2 shape, const Array *p_noise_x, const Array *p_noise_y, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit())
 Generates a cubic pulse array.
Array disk (glm::ivec2 shape, float radius, float slope=1.f, const Array *p_ctrl_param=nullptr, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit())
 Generates a disk-shaped heightmap with optional modifications.
Array gaussian_pulse (glm::ivec2 shape, float sigma, const Array *p_ctrl_param=nullptr, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit())
 Return a gaussian_decay pulse kernel.
Array multisteps (glm::ivec2 shape, float angle, float r=1.2f, int nsteps=8, float elevation_exponent=0.7f, float shape_gain=4.f, float scale=0.5f, float outer_slope=0.1f, const Array *p_ctrl_param=nullptr, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const glm::vec2 &center={0.5f, 0.5f}, const BBox2D &bbox=BBox2D::unit())
 Generate a multi-step height profile along a rotated axis.
Array paraboloid (glm::ivec2 shape, float angle, float a, float b, float v0=0.f, bool reverse_x=false, bool reverse_y=false, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit())
 Return a paraboloid.
Array polar_shape (glm::ivec2 shape, float rmin=0.1f, float rmax=0.3f, float aspect_ratio=1.f, float smoothing_width=0.1f, bool square_base=false, float angle=15.f, float sector_angle=90.f, float vmin=0.5f, float kt_value=0.f, float kr_border=0.f, float kr_border_ratio=0.1f, const Array *p_noise_r=nullptr, const Array *p_noise_theta=nullptr, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit())
 Generate a polar-based shape mask with optional angular and radial perturbations.
Array quad_surface (glm::ivec2 shape, float c00=0.f, float c10=0.f, float c01=0.f, float c11=0.f, const Array *p_ctrl_param=nullptr, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit())
 Generates a surface defined by the four corner values of the domain.
Array rectangle (glm::ivec2 shape, float rx, float ry, float angle, float slope=1.f, const Array *p_ctrl_param=nullptr, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit())
 Generates a rectangle-shaped heightmap with optional modifications.
Array slope (glm::ivec2 shape, float angle, float slope, const Array *p_ctrl_param=nullptr, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit())
 Return an array corresponding to a slope with a given overall.
Array smooth_cosine (glm::ivec2 shape, const Array *p_noise_x, const Array *p_noise_y, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit())
 Generates a smooth cosine array.
Array step (glm::ivec2 shape, float angle, float slope, const Array *p_ctrl_param=nullptr, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit())
 Return a step function (Heaviside with an optional talus slope at the transition).
void swirl (Array &dx, Array &dy, float amplitude=1.f, float exponent=1.f, const Array *p_noise=nullptr, const UvRect &uv_rect=UvRect::unit())
 Generate displacements dx and dy to apply a swirl effect to another primitve.
Array wave_dune (glm::ivec2 shape, float kw, float angle, float xtop, float xbottom, float phase_shift=0.f, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit())
 Return a dune shape wave.
Array wave_sine (glm::ivec2 shape, float kw, float angle, float phase_shift=0.f, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit())
 Return a sine wave.
Array wave_square (glm::ivec2 shape, float kw, float angle, float phase_shift=0.f, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit())
 Return a square wave.
Array wave_triangular (glm::ivec2 shape, float kw, float angle, float slant_ratio, float phase_shift=0.f, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit())
 Return a triangular wave.
Array caldera (glm::ivec2 shape, float radius, float sigma_inner, float sigma_outer, float z_bottom, const Array *p_noise, float noise_r_amp, float noise_ratio_z, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit())
 Return a caldera-shaped heightmap.
Array caldera (glm::ivec2 shape, float radius, float sigma_inner, float sigma_outer, float z_bottom, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit())
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
Array circus (glm::ivec2 shape, float radius=0.4f, float angle=0.f, float exit_width=0.35f, float exit_depth=0.f, float center_depth=0.1f, float ridge_height=1.f, float ridge_width=0.15f, float outer_falloff=2.f, const Array *p_noise_r=nullptr, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit(), Array *p_mask=nullptr)
 Generate a procedural circus (glacial cirque / amphitheatre basin) heightmap.
Array crater (glm::ivec2 shape, float radius, glm::vec2 center={0.5f, 0.5f}, float angle=30.f, float inner_depth=0.1f, float inner_exp=3.f, float lip_height=0.02f, float lip_extent=0.25f, float lip_exp=2.f, float asym_ratio=0.8f, float central_peak_height=0.01f, float central_peak_extent=0.4f, int n_terraces=0, float terrace_extent=0.1f, float terrace_exp=2.f, float terrace_persistence=0.5f, const Array *p_noise_r=nullptr, const UvRect &uv_rect=UvRect::unit(), Array *p_crater_mask=nullptr, Array *p_inner_crater_mask=nullptr)
 Generate a procedural impact crater heightmap.
Array crater_field (glm::ivec2 shape, const std::vector< glm::vec2 > &centers, const std::vector< float > &radii, float angle=30.f, float inner_depth=0.5f, float inner_exp=3.f, float lip_height=0.1f, float lip_extent=0.25f, float lip_exp=2.f, float asym_ratio=0.8f, float central_peak_height=0.05f, float central_peak_extent=0.4f, int n_terraces=0, float terrace_extent=0.1f, float terrace_exp=2.f, float terrace_persistence=0.5f, const Array *p_noise_r=nullptr, const UvRect &uv_rect=UvRect::unit(), Array *p_crater_mask=nullptr, Array *p_inner_crater_mask=nullptr, bool scale_elevation_with_radius=true)
 Generate a field of procedural impact craters from explicit centers and radii.
Array crater_field (glm::ivec2 shape, std::uint32_t seed, int n_craters, float r_min=0.02f, float r_max=0.2f, float angle=30.f, float inner_depth=0.5f, float inner_exp=3.f, float lip_height=0.1f, float lip_extent=0.25f, float lip_exp=2.f, float asym_ratio=0.8f, float central_peak_height=0.05f, float central_peak_extent=0.4f, int n_terraces=0, float terrace_extent=0.1f, float terrace_exp=2.f, float terrace_persistence=0.5f, const Array *p_noise_r=nullptr, const UvRect &uv_rect=UvRect::unit(), Array *p_crater_mask=nullptr, Array *p_inner_crater_mask=nullptr, bool scale_elevation_with_radius=true)
 Generate a field of randomly distributed procedural impact craters.
Array island_land_mask (glm::ivec2 shape, float radius, std::uint32_t seed, float displacement=0.2f, NoiseType noise_type=NoiseType::SIMPLEX2S, float kw=4.f, int octaves=8, float weight=0.f, float persistence=0.5f, float lacunarity=2.f, const glm::vec2 &center={0.5f, 0.5f}, const BBox2D &bbox=BBox2D::unit())
 Generates a 2D island mask by perturbing a radial boundary with noise.
Array island_chain_land_mask (glm::ivec2 shape, const Path &path, std::uint32_t seed, int island_count=5, float island_radius=0.1f, float size_falloff=0.5f, float size_jitter=0.3f, float scatter=0.f, float displacement=0.2f, NoiseType noise_type=NoiseType::SIMPLEX2S, float kw=4.f, int octaves=8, float weight=0.f, float persistence=0.5f, float lacunarity=2.f, const UvRect &uv_rect=UvRect::unit())
 Generates a land mask of an island chain scattered along a path.
Array rift (glm::ivec2 shape, float angle, float radius=0.1f, float axial_slope=0.2f, float depth=0.5f, bool scale_with_depth=true, RadialProfile profile=RadialProfile::RP_SMOOTHSTEP, float profile_param=0.f, float bottom_extent=0.1, float bottom_depth=0.05f, RadialProfile bottom_profile=RadialProfile::RP_SQRT, float bottom_profile_param=0.f, bool bottom_force_minimum_depth=true, float outer_slope=0.5f, const Array *p_noise_r=nullptr, const Array *p_noise_offset=nullptr, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit(), Array *p_rift_mask=nullptr, Array *p_bottom_mask=nullptr)
 Generate a rift-shaped primitive.
Array valley_head (glm::ivec2 shape, float angle=0.f, float min_depth=0.f, float max_depth=0.2f, float min_width=0.02f, float max_width=0.15f, float depth_length=0.5f, float width_length=0.5f, float development_power=2.f, float profile_power=1.3f, const Array *p_noise_offset=nullptr, const Array *p_noise_r=nullptr, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit(), Array *p_mask=nullptr)
 Generate a procedural natural valley head / valley incision deformation heightmap.
Array white (glm::ivec2 shape, float a, float b, std::uint32_t seed)
 Return an array filled with white noise.
Array white_density_map (const Array &density_map, std::uint32_t seed)
 Return an array filled 1 with a probability based on a density map.
Array white_sparse (glm::ivec2 shape, float a, float b, float density, std::uint32_t seed)
 Return an array sparsely filled with white noise.
Array white_sparse_binary (glm::ivec2 shape, float density, std::uint32_t seed)
 Return an array sparsely filled with random 0 and 1.
float fast_hash32_to_unit_float (unsigned int seed, size_t k)
 Generates a fast deterministic uniform float in [0,1) using a 32-bit hash.
float hash01 (uint32_t a, uint32_t b)
 Computes a pseudo-random float in [0, 1) by hashing two 32-bit integers.
uint32_t hash32 (uint32_t x)
 Integer hash function (Murmur3 / finalize style 32-bit mixer).
uint64_t splitmix64 (uint64_t x)
 Computes a deterministic 64-bit hash using the SplitMix64 algorithm.
float splitmix64_to_unit_float (unsigned int seed, size_t k)
 Generates a deterministic uniform float in [0,1) from a seed and sample index.
float uniform01 (uint64_t h)
 Converts a 64-bit hash value into a deterministic uniform float in [0, 1).
float vnoise (float x, float y, uint32_t seed=0)
 Computes 2D value noise in [-1, 1] using a hash-based lattice.
void chop (Array &array, float vmin)
 Set to zero any value lower than vmin.
void chop_max_smooth (Array &array, float vmax)
 Set to zero any value lower than vmax and apply a linear decrease slope between vmax / 2 and vmax.
void clamp (Array &array, float vmin=0.f, float vmax=1.f)
 Clamp array elements to a target range.
void clamp (Array &array, float vmax, ClampMode mode)
 Clamps the values of an array according to the specified mode.
void clamp_min (Array &array, float vmin)
 Clamp array values lower than a given bound.
void clamp_min (Array &array, const Array &vmin)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void clamp_min_smooth (Array &array, float vmin, float k=0.2f)
 Clamp array values lower than a given bound with a smooth transition.
void clamp_min_smooth (Array &array, const Array &vmin, float k=0.2f)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
float clamp_min_smooth (float x, float vmin, float k=0.2f)
 Clamp a single value lower than a given bound with a smooth transition.
void clamp_max (Array &array, float vmax)
 Clamp array values larger than a given bound.
void clamp_max (Array &array, const Array &vmax)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void clamp_max_smooth (Array &array, float vmax, float k=0.2f)
 Clamp array values larger than a given bound with a smooth transition.
void clamp_max_smooth (Array &array, const Array &vmax, float k=0.2f)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void clamp_oblique_plane (Array &array, float vmax, float angle, float slope, bool use_max_operator=true, float k=0.f, glm::vec2 center={0.5f, 0.5f}, const BBox2D &bbox=BBox2D::unit())
 Clamps an array against an oblique plane.
void clamp_smooth (Array &array, float vmin, float vmax, float k=0.2f)
 Clamp array values within a given interval with a smooth transition.
Array maximum (const Array &array1, const Array &array2)
 Return the element-wise maximum of two arrays.
Array maximum (const Array &array1, const float value)
 Return the element-wise maximum of an array and a scalar value.
Array maximum_smooth (const Array &array1, const Array &array2, float k=0.2)
 Return the polynomial cubic smooth element-wise maximum of two arrays.
float maximum_smooth (const float a, const float b, float k=0.2)
 Return the polynomial cubic smooth maximum of two scalar values.
Array minimum (const Array &array1, const Array &array2)
 Return the element-wise minimum of two arrays.
Array minimum (const Array &array1, const float value)
 Return the element-wise minimum of an array and a scalar value.
Array minimum_smooth (const Array &array1, const Array &array2, float k=0.2)
 Return the polynomial cubic smooth element-wise minimum of two arrays.
float minimum_smooth (const float a, const float b, float k)
 Return the polynomial cubic smooth minimum of two scalar values.
void remap (Array &array, float vmin, float vmax, float from_min, float from_max)
 Remap array elements from a starting range to a target range.
void remap (Array &array, float vmin=0, float vmax=1, ICommunicator &comm=SingleArrayComm::instance())
 Remap array elements from a starting range to a target range (default range).
void rescale (Array &array, float scaling, float vref=0.f)
 Remap array elements from a starting range to a target range.
void normalize_and_clip (Array &array, float multiplier=2.5f, bool smooth_transition=true, bool range_01=false, ICommunicator &comm=SingleArrayComm::instance())
 Normalize an array around its mean and clip values.
ScatterField merge_scatter_fields (const std::vector< ScatterField > &fields, bool merge_by_class=true)
 Merges multiple ScatterField instances into a single instance.
ScatterField merge_scatter_fields (const std::vector< ScatterField > &fields, const std::vector< BBox2D > &bboxs, bool merge_by_class=true)
 Merges multiple ScatterField instances with associated bounding boxes into a single instance, resolving overlaps by keeping items from earlier fields in the input order.
Array scatter_field_to_heightmap (const ScatterField &field, glm::ivec2 shape, ScatterShape shape_type=SCATTER_SHAPE_DISK, float height_radius_ratio=1.0f, std::optional< uint32_t > class_id=std::nullopt, Array *p_rock_map=nullptr, uint32_t seed=0, const UvRect &uv_rect=UvRect::unit())
 Converts a ScatterField into a heightmap by representing each scattered object as a local elevation increase on GPU.
ScatterField seed_scatter_clusters (size_t class_count, size_t item_count, const Array &density, const Array &exclusion, float cluster_spread=0.05f, size_t points_per_cluster=8, const ScatterSeedingOptions &options={})
 Generates a clustered scatter distribution using inverse transform sampling for cluster centers and local cluster regions.
ScatterField seed_scatter_kmeans (size_t class_count, size_t item_count, const Array &density, const Array &exclusion, float cluster_randomness=0.0f, size_t k_neighbors=4, const ScatterSeedingOptions &options={})
 Generates a multi-class scatter distribution using 2D inverse transform sampling for positions and PointSampler k-means clustering to tag classes.
Array sdf_2d_polyline (const Path &path, glm::ivec2 shape, const UvRect &uv_rect=UvRect::unit(), const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, bool use_bvh=true)
 Computes the signed distance field (SDF) of a 2D polyline.
Array sdf_2d_polyline_brute_force (const Path &path, glm::ivec2 shape, const UvRect &uv_rect=UvRect::unit(), const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr)
Array sdf_2d_polyline_bvh (const Path &path, glm::ivec2 shape, const UvRect &uv_rect=UvRect::unit(), const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr)
Array sdf_2d_polyline_bezier (const Path &path, glm::ivec2 shape, const UvRect &uv_rect=UvRect::unit(), const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, bool use_bvh=true)
 See hmap::sdf_2d_polyline, with a Bezier approximation of the path.
Array sdf_2d_polyline_bezier_brute_force (const Path &path, glm::ivec2 shape, const UvRect &uv_rect=UvRect::unit(), const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr)
Array sdf_2d_polyline_bezier_bvh (const Path &path, glm::ivec2 shape, const UvRect &uv_rect=UvRect::unit(), const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr)
Array sdf_2d_graph (const Graph &graph, glm::ivec2 shape, const UvRect &uv_rect=UvRect::unit(), const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, bool use_bvh=true)
 Computes the 2D unsigned distance field to a graph network.
Array sdf_2d_graph_brute_force (const Graph &graph, glm::ivec2 shape, const UvRect &uv_rect=UvRect::unit(), const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr)
Array sdf_2d_graph_bvh (const Graph &graph, glm::ivec2 shape, const UvRect &uv_rect=UvRect::unit(), const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr)
Array perturb_mask_contour (const Array &mask, const Array &noise, float max_displacement, int ir=1)
 Perturb the contour of a binary mask using a displacement field, while trying to preserve a single connected component without holes.
Array scan_mask (const Array &array, float contrast=0.5f, float brightness=0.5f)
 Mask adjustement using a 'scanning' method.
Array select_angle (const Array &array, float angle, float sigma)
 Return angle selection for a given angle and a tolerance half-width on this value.
Array select_blob_log (const Array &array, int ir, bool normalize=false, ICommunicator &comm=SingleArrayComm::instance())
 Return blob detection using the Laplacian of Gaussian (LoG) approach.
Array select_cavities (const Array &array, int ir, bool concave=true, bool normalize=false, ICommunicator &comm=SingleArrayComm::instance())
 Return holes or bumps detection based on the mean curvature of the heightmap.
Array select_eq (const Array &array, float value)
 Return an array with elements equal to 1 where input elements are equal to value.
Array select_gradient_angle (const Array &array, float angle)
 Return an array weighted by the gap between the gradient angle and a given angle.
Array select_gradient_binary (const Array &array, float talus_center)
 Return an array filled with 1 where the gradient is larger than a given value and 0 elsewhere.
Array select_gradient_exp (const Array &array, float talus_center, float talus_sigma)
 Return an array weighted (exponantial decay) by the gradient norm of the input array.
Array select_gradient_inv (const Array &array, float talus_center, float talus_sigma)
 Return an array weighted (square inverse) by the gradient norm of the input array.
Array select_gt (const Array &array, float value)
 Return an array with elements equal to 1 where input elements are larger than value.
Array select_interval (const Array &array, float value1, float value2)
 Return an array with elements equal to 1 where input elements are within the bounds provided.
Array select_inward_outward_slope (const Array &array, glm::vec2 center={0.5f, 0.5f}, const BBox2D &bbox=BBox2D::unit())
 Return an array with positive values if the slope is pointing to the center (slope is inward), and negative values otherwise (slope is outward).
Array select_lt (const Array &array, float value)
 Return an array with elements equal to 1 where input elements are smaller than value.
Array select_midrange (const Array &array, float gain, float vmin, float vmax)
 Selects the midrange values of the input array within a specified range.
Array select_midrange (const Array &array, float gain)
 Selects and scales the midrange values of the input array.
void select_multiband3 (const Array &array, Array &band_low, Array &band_mid, Array &band_high, float ratio1, float ratio2, float overlap, float vmin, float vmax)
 Splits the input array into three bands (low, mid, and high) based on given ratios and overlap.
void select_multiband3 (const Array &array, Array &band_low, Array &band_mid, Array &band_high, float ratio1, float ratio2, float overlap)
 Splits the input array into three bands (low, mid, and high) based on given ratios and overlap.
Array select_pulse (const Array &array, float value, float sigma)
 Return an array filled with non-zero values where the input is in the interval [value - sigma, value + sigma]. Output array values have a cubic pulse distribution within this interval.
Array select_range (const Array &array, float vmin, float vmax, float width)
 Return a selection mask for a value range [vmin, vmax] with smooth transitions of specified width at both ends.
Array select_rivers (const Array &array, float talus_ref, float clipping_ratio)
 Return an array filled with a criterion based on the occurence of a river bed.
Array select_transitions (const Array &array1, const Array &array2, const Array &array_blend)
 Return an array filled with 1 at the blending transition between two arrays, and 0 elsewhere.
Array select_valley (const Array &z, int ir, bool ridge_select=false, bool normalize=false, ICommunicator &comm=SingleArrayComm::instance())
Array smooth_mask_preserve_frontier (const Array &mask, float feather_width, const UvTile &region=UvTile::dummy(), ICommunicator &comm=SingleArrayComm::instance())
 Smooths a binary mask with an inward falloff while preserving its 0-boundary.
Array hillshade (const Array &z, float azimuth, float zenith, float talus_ref=1.f)
 Compute the shaded relief map (hillshading) from a heightmap.
Array shadow_grid (const Array &z, float shadow_talus)
 Compute the shadow intensity using a grid-based technique.
Array shadow_heightmap (const Array &z, float azimuth=180.f, float zenith=45.f, float distance=0.2f)
 Compute crude shadows from a heightmap.
Array topographic_shading (const Array &z, float azimuth, float zenith, float talus_ref=1.f)
 Compute the topographic shadow intensity in the range [-1, 1].
Path dijkstra (const Path &path, const Array &array, const UvRect &uv_rect, float elevation_ratio=0.f, float distance_exponent=0.5f, float upward_penalization=0.1f, Array *p_mask_nogo=nullptr)
 Divide the path by adding points based on the lowest elevation difference between each pair of edge endpoints.
Path find_cut_path_dijkstra (const Array &z, DomainBoundary start, DomainBoundary end, float dijk_elevation_ratio=0.9f, float dijk_distance_exponent=2.f, float dijk_upward_penalization=100.f, std::uint32_t seed=0, bool favor_boundary_center=true, bool favor_lower_elevation=true, bool favor_sinks=true, bool favor_domain_center=false)
 Find a Dijkstra-based cut path between two domain boundaries.
Path find_cut_path_dijkstra (const Array &z, DomainBoundary start, DomainBoundary end, std::uint32_t seed, size_t control_points_count=2048, bool favor_boundary_center=true, bool favor_lower_elevation=true, bool favor_sinks=true, bool favor_domain_center=false, const UvTile &region=UvTile::unit(), ICommunicator &comm=SingleArrayComm::instance())
 Generate a cut path across a heightmap using a random triangular mesh and Dijkstra shortest path search (tileable).
Path find_cut_path_midpoint (const Array &z, DomainBoundary start, DomainBoundary end, std::uint32_t seed, float offset_ratio=0.2f, int steps=16, bool favor_boundary_center=true, bool favor_lower_elevation=true, bool favor_sinks=true, const UvTile &region=UvTile::unit(), ICommunicator &comm=SingleArrayComm::instance())
 Generate a stochastic cut path using midpoint displacement.
Path find_cut_path_multiscale (const Array &z, DomainBoundary start, DomainBoundary end, int n_levels=3, int corridor_radius=4, float corridor_decay=1.f, float dijk_elevation_ratio=0.9f, float dijk_distance_exponent=2.f, float dijk_upward_penalization=100.f, std::uint32_t seed=0, bool favor_boundary_center=true, bool favor_lower_elevation=true, bool favor_sinks=true, bool use_astar=false, bool smooth_path=false)
 Find a fast coarse-to-fine multiscale cut path between two domain boundaries.
void find_path_dijkstra (const Array &z, glm::ivec2 ij_start, glm::ivec2 ij_end, std::vector< int > &i_path, std::vector< int > &j_path, float elevation_ratio=0.1f, float distance_exponent=2.f, float upward_penalization=0.1f, const Array *p_mask_nogo=nullptr, const Array *p_node_weights=nullptr)
 Finds the path with the lowest elevation and elevation difference between two points in a 2D array using Dijkstra's algorithm.
void find_path_dijkstra (const Array &z, glm::ivec2 ij_start, std::vector< glm::ivec2 > ij_end_list, std::vector< std::vector< int > > &i_path_list, std::vector< std::vector< int > > &j_path_list, float elevation_ratio=0.1f, float distance_exponent=2.f, float upward_penalization=0.1f, const Array *p_mask_nogo=nullptr, const Array *p_node_weights=nullptr)
Path find_path_dijkstra (const Array &z, glm::vec2 start, glm::vec2 end, std::uint32_t seed, size_t control_points_count=2048, bool favor_domain_center=false, const UvTile &region=UvTile::unit(), ICommunicator &comm=SingleArrayComm::instance())
 Generate a path between two points across a heightmap using a random triangular mesh and Dijkstra shortest path search (tileable).
std::vector< glm::ivec2 > find_path_dijkstra (const Array &z, glm::ivec2 ij_start, glm::ivec2 ij_end, float elevation_ratio=0.1f, float distance_exponent=2.f, float upward_penalization=0.1f, const Array *p_mask_nogo=nullptr, const Array *p_node_weights=nullptr)
 Overload of find_path_dijkstra returning a vector of grid indices.
Path find_path_dijkstra (const Array &z, glm::ivec2 ij_start, glm::ivec2 ij_end, const UvRect &uv_rect, float elevation_ratio=0.1f, float distance_exponent=2.f, float upward_penalization=0.1f, const Array *p_mask_nogo=nullptr, const Array *p_node_weights=nullptr)
 Overload of find_path_dijkstra returning a Path mapped to a bounding box with point values holding sampled terrain elevations.
std::vector< glm::ivec2 > find_path_midpoint (const Array &z, glm::ivec2 ij_start, glm::ivec2 ij_end, float offset_ratio=0.2f, int max_it=0, int steps=16)
 Compute a path between two points using iterative midpoint refinement.
void find_path_midpoint (const Array &z, glm::ivec2 ij_start, glm::ivec2 ij_end, std::vector< int > &i_path, std::vector< int > &j_path, float offset_ratio=0.2f, int max_it=0, int steps=16)
 Overload of find_path_midpoint returning path indices in i and j vectors.
Path find_path_midpoint (const Array &z, glm::ivec2 ij_start, glm::ivec2 ij_end, const UvRect &uv_rect, float offset_ratio=0.2f, int max_it=0, int steps=16)
 Overload of find_path_midpoint returning a Path mapped to a bounding box with point values holding sampled terrain elevations.
void find_path_multiscale (const Array &z, glm::ivec2 ij_start, glm::ivec2 ij_end, std::vector< int > &i_path, std::vector< int > &j_path, int n_levels=3, int corridor_radius=4, float corridor_decay=1.f, float elevation_ratio=0.1f, float distance_exponent=2.f, float upward_penalization=0.1f, const Array *p_mask_nogo=nullptr, bool use_astar=false, bool smooth_path=false)
 Finds a shortest path on a 2D grid using a fast coarse-to-fine multiscale approach.
std::vector< glm::ivec2 > find_path_multiscale (const Array &z, glm::ivec2 ij_start, glm::ivec2 ij_end, int n_levels=3, int corridor_radius=4, float corridor_decay=1.f, float elevation_ratio=0.1f, float distance_exponent=2.f, float upward_penalization=0.1f, const Array *p_mask_nogo=nullptr, bool use_astar=false, bool smooth_path=false)
 Overload of find_path_multiscale returning a vector of grid indices.
Path find_path_multiscale (const Array &z, glm::ivec2 ij_start, glm::ivec2 ij_end, const UvRect &uv_rect, int n_levels=3, int corridor_radius=4, float corridor_decay=1.f, float elevation_ratio=0.1f, float distance_exponent=2.f, float upward_penalization=0.1f, const Array *p_mask_nogo=nullptr, bool use_astar=false, bool smooth_path=false)
 Overload of find_path_multiscale returning a Path object mapped to a bounding box, with point values containing the elevation sampled from the heightmap.
float index_to_uv (int i, int n, GridRegistration reg=GridRegistration::CellCenter)
 Maps a discrete index i in [0, n) to a UV coordinate in [0, 1].
float uv_to_continuous_index (float u, int n, GridRegistration reg=GridRegistration::CellCenter)
 Maps a UV coordinate in [0, 1] to a continuous index in [0, n - 1].
UvRect tile_uv_rect (const glm::ivec2 &global_offset, const glm::ivec2 &tile_shape_with_halo, const glm::ivec2 &global_shape, const UvRect &domain_uv=UvRect::unit())
 Computes the exact UV rectangle of a tile (including halo) within a domain of global_shape.
float autocorr_length_scale (const Array &array, float max_lag_fraction=0.4f)
 Estimate the isotropic dominant length scale of a 2D heightmap.
glm::vec2 autocorr_length_scale_axial (const Array &array, float max_lag_fraction=0.4f)
 Estimate axis-aligned dominant length scales of a 2D heightmap.
Array detrend_reg (const Array &array)
 Apply linear regression for detrending of a 2D array.
void normalize (Array &array, NormalizationMethod method)
 In-place normalization of an array.
Array normalized (const Array &array, NormalizationMethod method)
 Returns a normalized copy of an array.
float variance (const Array &array, float *p_mean=nullptr)
 Compute the population variance of a 2D array.
Array loose_symmetry (const Array &array, SymmetryType symmetry_type=SymmetryType::SYMMETRY_LEFT_TO_RIGHT, float strength=1.f, int factor=4, int patch_size=16, int analysis_stride=2, int synthesis_stride=8, int sparsity=1, bool flatten_center=false, float flatten_radius=0.05f)
 Synthesize a heightmap with natural, approximate symmetry using exemplar-based super-resolution.
Array non_parametric_sampling (const Array &array, glm::ivec2 patch_shape, std::uint32_t seed, float error_threshold=0.1f)
 Synthesize a new heightmap based on an input array using a non-parametric sampling method.
Array quilting (const std::vector< const Array * > &p_arrays, glm::ivec2 patch_base_shape, glm::ivec2 tiling, float overlap, std::uint32_t seed, std::vector< Array * > secondary_arrays={}, bool patch_flip=true, bool patch_rotate=true, bool patch_transpose=true, float filter_width_ratio=0.25f)
 Synthesize a new heightmap by stitching together small patches from input heightmaps.
Array quilting_blend (const std::vector< const Array * > &p_arrays, glm::ivec2 patch_base_shape, float overlap, std::uint32_t seed, bool patch_flip=true, bool patch_rotate=true, bool patch_transpose=true, float filter_width_ratio=0.25f)
 Synthesize a new heightmap by stitching together small patches from a list of input heightmaps.
Array quilting_expand (const Array &array, float expansion_ratio, glm::ivec2 patch_base_shape, float overlap, std::uint32_t seed, std::vector< Array * > secondary_arrays={}, bool keep_input_shape=false, bool patch_flip=true, bool patch_rotate=true, bool patch_transpose=true, float filter_width_ratio=0.25f)
 Synthesize a new heightmap by expanding the input heightmap and stitching patches.
Array quilting_shuffle (const Array &array, glm::ivec2 patch_base_shape, float overlap, std::uint32_t seed, std::vector< Array * > secondary_arrays={}, bool patch_flip=true, bool patch_rotate=true, bool patch_transpose=true, float filter_width_ratio=0.25f)
 Synthesize a new heightmap by reshuffling patches of the input heightmap.
Array terrain_super_resolution (const Array &array, const Array &exemplar, int factor, int patch_size=16, int analysis_stride=8, int synthesis_stride=8, int sparsity=1)
 Synthesize a high-resolution heightmap from a low-resolution input using an exemplar-based sparse patch representation (terrain amplification).
std::vector< float > cubic_pulse (const TerrainTriMesh &mesh)
 Compute a cubic pulse value for each mesh vertex.
TerrainTriMesh generate_terrain_tri_mesh_from_heightmap (const Array &z, float max_error, int max_triangles=0, int max_points=0)
 Generate a terrain mesh from a heightmap.
TerrainTriMesh generate_terrain_tri_mesh_from_heightmap_random (const Array &z, int control_points_count, std::uint32_t seed, const UvTile &region=UvTile::unit(), ICommunicator *p_comm=nullptr)
 Generate a random terrain mesh from a heightmap tile.
TerrainAlignment compute_terrain_alignment (const Array &lower, const CoordFrame &frame_lower, const Array &upper, const CoordFrame &frame_upper, TerrainAlignMode mode, float huber_delta=0.1f, int max_iterations=10)
 Compute alignment parameters to fit upper to lower over their common valid area.
TerrainAlignment compute_terrain_alignment (const VirtualArray &lower, const CoordFrame &frame_lower, const VirtualArray &upper, const CoordFrame &frame_upper, TerrainAlignMode mode, float huber_delta=0.1f, int max_iterations=10, int coarse_size=128)
 Compute alignment parameters for VirtualArray inputs using a coarse Array representation.
void apply_terrain_alignment (Array &upper, const TerrainAlignment &alignment)
 Apply precomputed alignment parameters to an Array in-place.
void apply_terrain_alignment (VirtualArray &upper, const TerrainAlignment &alignment, const ComputeMode &cm=ComputeMode{})
 Apply precomputed alignment parameters to a VirtualArray in-place.
void align_terrains (const Array &lower, const CoordFrame &frame_lower, Array &upper, const CoordFrame &frame_upper, TerrainAlignMode mode, float huber_delta=0.1f, int max_iterations=10)
 Align upper to lower in-place over their common valid area.
void align_terrains (const VirtualArray &lower, const CoordFrame &frame_lower, VirtualArray &upper, const CoordFrame &frame_upper, TerrainAlignMode mode, float huber_delta=0.1f, int max_iterations=10, int coarse_size=128, const ComputeMode &cm=ComputeMode{})
 Align upper VirtualArray to lower VirtualArray in-place.
void flip_lr (Texture &texture)
 Flip the texture horizontally (left/right).
void flip_ud (Texture &texture)
 Flip the texture vertically (up/down).
void rot180 (Texture &texture)
 Rotate the texture by 180 degrees.
void rot270 (Texture &texture)
 Rotate the texture by 270 degrees counterclockwise.
void rot90 (Texture &texture)
 Rotate the texture by 90 degrees counterclockwise.
void scale_uv (Texture &texture, glm::vec2 uv_scale)
 Scale the texture in UV space with wrapping boundary.
Texture transpose (const Texture &texture)
 Return the transposed texture.
void flip_lr (Array &array)
 Flip the array horizontally (left/right).
void flip_ud (Array &array)
 Flip the array vertically (up/down).
void radial_displacement_to_xy (const Array &dr, Array &dx, Array &dy, float smoothing=1.f, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit())
 Interpret the input array dr as a radial displacement and convert it to a pair of displacements dx and dy in cartesian coordinates.
void rot180 (Array &array)
 Rotate the array by 180 degrees.
void rot270 (Array &array)
 Rotate the array by 270 degrees.
void rot90 (Array &array)
 Rotate the array by 90 degrees.
void rotate (Array &array, float angle, bool zoom_in=true, bool zero_padding=false)
 Rotate the array by a specified angle.
void rotate_displacement (const Array &delta, float angle, Array &dx, Array &dy)
 Rotates a scalar displacement field into directional X and Y components.
void scale_uv (Array &array, glm::vec2 uv_scale)
 Scale the array in UV space with wrapping boundary.
Array symmetrize (const Array &array, SymmetryType symmetry_type=SymmetryType::SYMMETRY_LEFT_TO_RIGHT, bool flatten_center=false, float flatten_radius=0.05f)
 Enforces geometric symmetry on an array.
Array translate (const Array &array, float dx, float dy, bool periodic=false, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit())
 Translates a 2D array by a specified amount along the x and y axes.
Array transpose (const Array &array)
 Return the transposed array.
Array zoom (const Array &array, float zoom_factor, bool periodic=false, glm::vec2 center={0.5f, 0.5f}, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit())
 Applies a zoom effect to a 2D array with an adjustable center.
void warp (Array &array, const Array *p_dx, const Array *p_dy)
 Apply a warping effect to the array.
void warp_directional (Array &array, float angle, float amount=0.02f, int ir=4, bool reverse=false)
 Apply a warping effect following the downward local gradient direction (deflate/inflate effect).
void warp_directional (Array &array, float angle, const Array *p_mask, float amount=0.02f, int ir=4, bool reverse=false)
 Apply a warping effect following the downward local gradient direction (deflate/inflate effect) with a mask.
void warp_downslope (Array &array, float amount=0.02f, int ir=4, bool reverse=false)
 Apply a warping effect following the downward local gradient direction (deflate/inflate effect).
void warp_downslope (Array &array, const Array *p_mask, float amount=0.02f, int ir=4, bool reverse=false)
 Apply a warping effect following the downward local gradient direction (deflate/inflate effect) with a mask.
std::vector< size_t > argsort (const std::vector< float > &v)
 Returns the indices that would sort the vector.
float compute_median (std::vector< float > values)
 Computes the median value of a set of floats.
std::vector< size_t > find_sign_changes (const std::vector< float > &data)
 Returns indices where a sign change occurs in the input vector.
std::vector< float > generate_random_vector (size_t size, float min_value, float max_value, uint32_t seed)
 Generate a vector of random floating-point values within a given range.
std::vector< int > generate_random_vector (size_t size, int min_value, int max_value, uint32_t seed)
 Generate a vector of random integers within a given range.
std::vector< int > generate_unique_random_vector (size_t size, int min_value, int max_value, uint32_t seed)
 Generate a vector of unique random integers within a given range.
std::string make_histogram (const std::vector< float > &values, int bin_count, int hist_height)
 Generates an ASCII histogram representation of values.
std::vector< float > moving_average (const std::vector< float > &input, int radius)
 Smooths a vector using a centered moving average.
template<typename T>
void reindex_vector (std::vector< T > &v, std::vector< size_t > &idx)
 Reorders a vector using a given index mapping.
std::vector< float > remap (const std::vector< float > &data, float new_min=0.f, float new_max=1.f)
 Remaps values of a vector to a given range [new_min, new_max].
template<typename T>
void shuffle_vector (std::vector< T > &values, std::uint32_t seed)
 Shuffles a vector in-place using a deterministic seed.
template<typename T>
std::vector< T > shuffled_vector (const std::vector< T > &values, std::uint32_t seed)
 Returns a shuffled copy of a vector.
size_t upperbound_right (const std::vector< float > &v, float value)
 Returns the index of the first element greater than a given value.
void vector_unique_values (std::vector< float > &v)
 Removes duplicate values from a vector.
std::string to_string (StorageMode m)
std::unique_ptr< TileStorage > make_storage (glm::ivec2 shape, glm::ivec2 tile_shape, StorageMode storage_mode)
std::string to_string (ForEachMode m)
void copy_data (const VirtualArray &src, VirtualArray &dst, const ComputeMode &cm)
void sum_per_tile (const VirtualArray &va, std::vector< float > &tile_sums, float *p_total_inner_sum=nullptr, const VirtualArray *p_exclusion_mask=nullptr, float exclusion_threshold=0.f, const ComputeMode &cm={})
template<std::size_t N, typename T, std::size_t... Is>
auto unpack_impl (const std::vector< T * > &v, std::index_sequence< Is... >)
template<std::size_t N, typename T>
auto unpack (const std::vector< T * > &v)
VirtualTexture convert_texture_channels (const VirtualTexture &src, int dst_channels, float fill_value, const ComputeMode &cm)
template<typename Func>
void for_each_tile (VirtualTexture &tex, Func &&func, const ComputeMode &cm)
template<typename Func>
void for_each_tile (const VirtualTexture &tex, Func &&func, const ComputeMode &cm)
template<typename Func>
void for_each_pixel (VirtualTexture &tex, Func &&func, const ComputeMode &cm)
Forest grow_forest_competition_nn (const Forest &forest, const std::vector< Species > &species={}, const InteractionMatrix &competition_matrix={}, const Array &max_radius_scale={}, float max_radius_scale_strength=1.0f, bool prune_unviable=true, const BBox2D &bbox=BBox2D{})
 Adjusts tree radii based on nearest-neighbor distances and species competition constraints.
Forest grow_forest_competition_voronoi (const Forest &forest, const std::vector< Species > &species={}, const InteractionMatrix &competition_matrix={}, const Array &max_radius_scale={}, float max_radius_scale_strength=1.0f, bool prune_unviable=true, const BBox2D &bbox=BBox2D{})
 Adjusts tree radii based on Voronoi cell areas and species competition constraints.
Forest grow_forest_iterative (const Forest &forest, const std::vector< Species > &species={}, size_t iterations=10, float growth_rate=0.1f, const InteractionMatrix &competition_matrix={}, const Array &max_radius_scale={}, float max_radius_scale_strength=1.0f, bool prune_unviable=true, const BBox2D &bbox=BBox2D{}, const UvTile &region=UvTile::unit())
 Simulates iterative plant growth with neighborhood competition and mortality.
Forest grow_forest_soft_core (const Forest &forest, const std::vector< Species > &species={}, const InteractionMatrix &repulsion_distances={}, const InteractionMatrix &repulsion_strengths={}, size_t target_count=0, const Array &max_radius_scale={}, float max_radius_scale_strength=1.0f, uint32_t seed=0, const BBox2D &bbox=BBox2D{})
 Performs multi-species Strauss soft-core growth and thinning on an input forest.
Array build_tree_density (const Array &heightmap, float min_elev=0.0f, float max_elev=0.9f, float elev_transition_width=0.1f, float min_talus=0.003f, float max_talus=0.005f, float angle=30.0f, float angle_width=90.0f, float weight_elev=1.0f, float weight_talus=1.0f, float weight_angle=0.8f, float weight_twi=0.5f, const Array &secondary_density={}, float weight_secondary=1.0f, const Array &exclusion_mask={}, float exclusion_threshold=0.f)
 Computes an environmental suitability criteria map in [0, 1] representing tree probability density based on elevation, slope talus, aspect angle, topographic wetness index (TWI), an optional secondary density map, and an optional exclusion mask.
Forest seed_forest_clusters (size_t species_count, size_t tree_count, const Array &density, const Array &exclusion, float cluster_spread=0.05f, size_t points_per_cluster=8, const ForestSeedingOptions &options={}, const UvTile &region=UvTile::unit(), ICommunicator &comm=SingleArrayComm::instance())
 Generates a clustered forest distribution using inverse transform sampling for cluster centers and local cluster regions.
Forest seed_forest_kmeans (size_t species_count, size_t tree_count, const Array &density, const Array &exclusion, float cluster_randomness=0.0f, size_t k_neighbors=4, const ForestSeedingOptions &options={}, const UvTile &region=UvTile::unit(), ICommunicator &comm=SingleArrayComm::instance())
 Generates a multi-species forest distribution using 2D inverse transform sampling for positions and PointSampler k-means clustering to tag species.
Graph generate_network_alpha_model (const std::vector< float > &xc, const std::vector< float > &yc, const std::vector< float > &size, const BBox2D &bbox, const Array &z, std::uint32_t seed, float alpha=0.7f, int n_dummy_nodes=2500, float dz_weight=1.f, const Array *p_weight=nullptr)
 Generate a large scale road network between "nodes" (or cities) using the alpha model.
Array build_rock_density (const Array &heightmap, float max_slope=0.05f, float bulkify_amp=0.01f, float weight_elev=1.0f, float weight_slope=1.0f, float weight_rivers=1.0f, float river_talus_ref=0.1f, float river_clipping_ratio=1000.0f, const Array &secondary_density={}, float weight_secondary=1.0f, const Array &exclusion_mask={}, float exclusion_threshold=0.f, const BBox2D &bbox=BBox2D{})
 Computes a probability density map in [0, 1] for rock placement based on elevation, talus/slope, river drainage paths, an optional secondary density map, and an optional exclusion mask.
RockField place_rocks_procedural (size_t rock_count, const Array &elevation, float min_elev=0.f, float max_elev=0.9f, float max_slope=1.f, const Array &density={}, const Array &exclusion={}, float size_slope_weight=0.f, float size_elevation_gain=1.f, float size_elevation_exponent=1.f, const RockSeedingOptions &options={}, const UvTile &region=UvTile::unit(), ICommunicator &comm=SingleArrayComm::instance())
 Places rocks procedurally on a terrain, without physical simulation.
RockField seed_rock_field (size_t rock_count, const Array &density, const Array &exclusion={}, const RockSeedingOptions &options={}, const UvTile &region=UvTile::unit(), ICommunicator &comm=SingleArrayComm::instance())
 Seeds a general rock/boulder field using inverse density transform sampling and applies power-law radius distribution and collision resolution.
RockField simulate_rock_emission (size_t rock_count, const Array &emission_density, const Array &elevation, const Array *p_friction_map=nullptr, const RockDistribution &dist={}, const RockSimulationOptions &options={})
 Emits rocks from a spatial emission density map and simulates their trajectories downhill across terrain on GPU.
RockField simulate_rock_trajectories (const RockField &rocks, const Array &elevation, const Array *p_friction_map=nullptr, const RockSimulationOptions &options={})
 Simulates physical movement (sliding, rolling, bouncing, and inter-rock collision avoidance) for an existing RockField across terrain on GPU.
Array operator* (const float value, const Array &array)
Array operator/ (const float value, const Array &array)
Array operator+ (const float value, const Array &array)
const Array operator- (const float value, const Array &array)
template<typename T>
void convert_mat_to_array (const cv::Mat &mat, Array &array, bool flip_j)
void square_fill_md (Array &array, Mat< int > &is_done, int i1, int i2, int j1, int j2, float noise_scale, std::mt19937 gen, std::uniform_real_distribution< float > dis)
void square_md (Array &array, Mat< int > &is_done, int step, float noise_scale, std::mt19937 gen, std::uniform_real_distribution< float > dis)
Array flatbed_carve (glm::ivec2 shape, const Path &path, float bottom_extent, float vmin, float depth, float falloff_distance, float outer_slope, bool preserve_bedshape, RadialProfile radial_profile, float radial_profile_parameter, Array *p_falloff_mask, const Array *p_noise_r, const UvRect &uv_rect)
uint32_t helper_hash_u32 (uint32_t x)
float helper_hash_01 (uint32_t x)
std::vector< glm::vec3 > helper_tov3 (const std::vector< std::vector< float > > &colors)
void thermal_schott (Array &z, const Array &talus, int iterations, float intensity)
void thermal_schott (Array &z, const Array &talus, Array *p_mask, int iterations, float intensity)
void thermal_schott (Array &z, const float talus, int iterations, float intensity)
void thermal_schott (Array &z, const float talus, Array *p_mask, int iterations, float intensity)
void helper_build_mesh_masked (aiMesh *p_mesh, const Array &array, const Array &mask, float elevation_scaling, bool fit_boundaries)
void helper_build_mesh (aiMesh *p_mesh, const Array &array, MeshType mesh_type, float elevation_scaling, float max_error, bool fit_boundaries)
Texture compute_splatmap (const Array *p_r, const Array *p_g, const Array *p_b, const Array *p_a)
glm::ivec4 helper_compute_tile_bounds (int tile_x, int tile_y, const glm::ivec2 &tile_count, const glm::ivec2 &array_shape, bool overlapping_edges, bool reverse_tile_y_indexing)
void recurve_bexp (Array &array, float tau, const Array *p_mask)
void recurve_exp (Array &array, float tau, const Array *p_mask)
Path helper_build_path (const std::vector< Point > &points, InterpolationMethodCurve method, Path::EdgeDivisionMode edm, int edge_divisions, int point_count)
size_t helper_estimate_count (const BBox2D &bbox, float distance)
void compute_gradient (const Array &array, Array &dx, Array &dy, float x_coeff[3], float y_coeff[3], float normalize_factor)
Array compute_gradient_norm (const Array &array, float x_coeff[3], float y_coeff[3], float normalize_factor, Array *p_dx=nullptr, Array *p_dy=nullptr)
bool is_monotonic (const std::vector< float > &data)
int find_last_index_smaller_than (const std::vector< float > &vec, float threshold)
float helper_wrap_phi (float phi)
template<typename F>
auto helper_make_wrapped (F f)
Array helper_reconstruction_impl (const Array &marker, const Array &mask, int ir, float k_smooth, std::function< Array(const Array &, int)> morph_op, std::function< Array(const Array &, const Array &, float)> clamp_op)
void helper_thinning (Array &in, int iter)
void helper_flip_rot_transpose (Array &array, bool do_flip, int rot_steps, bool do_transpose)
float helper_crater_radial_function (float r, float inner_depth, float inner_exp, float lip_height, float lip_extent, float lip_exp, int n_terraces, float terrace_extent, float terrace_exp, float terrace_persistence)
float helper_crater_profile (float r, float dx, float dy, float alpha, float ap, float am, float inner_depth, float inner_exp, float lip_height, float lip_extent, float lip_exp, float central_peak_height, float central_peak_extent, int n_terraces, float terrace_extent, float terrace_exp, float terrace_persistence)
Point helper_pick_lowest (const Point &pa, const Point &pb, const Array &z, float max_offset, int steps)
int count_neighbors_to_fill (int i, int j, Mat< int > &is_cell_done)
bool cmp_queue (std::pair< int, std::pair< int, int > > &a, std::pair< int, std::pair< int, int > > &b)
void reindex_vector (std::vector< int > &v, std::vector< size_t > &idx)
void reindex_vector (std::vector< float > &v, std::vector< size_t > &idx)
 TEST (NoiseStretch, CpuIsotropicPreserved)
 TEST (NoiseStretch, CpuDirectionalMatchesAxisScaling)
 TEST (NoiseStretch, CpuOctaveDecay)
 TEST (NoiseStretch, GpuIsotropicAndDirectional)
 TEST (NoiseStretch, AllNoiseTypesCpuAndGpu)

Typedef Documentation

◆ UvTile

using hmap::UvTile = UvTile

◆ Tree

Represents a single tree instance.

◆ Rock

Represents a single rock or boulder instance.

Enumeration Type Documentation

◆ StampingBlendMethod

Blending method for the stamping operator.

Enumerator
ADD 

add

MAXIMUM 

maximum

MAXIMUM_SMOOTH 

maximum smooth

MINIMUM 

minimum

MINIMUM_SMOOTH 

minimum smooth

MULTIPLY 

multiply

SUBSTRACT 

substract

◆ DeformationConstraintType

Penalty type of a deformation constraint (see DeformationConstraint).

Enumerator
MATCH 

penalize any deviation from the target height

ABOVE 

penalize only heights below the target (target acts as a floor)

BELOW 

penalize only heights above the target (target acts as a ceiling)

◆ TerrainBlendMode

enum class hmap::TerrainBlendMode : int
strong

Blending modes for combining terrains with CoordFrame transforms.

Enumerator
TBM_ADD 
TBM_AVERAGE 
TBM_DISTANCE 
TBM_HEIGHT 
TBM_MAX 
TBM_MAX_SMOOTH 
TBM_MIN 
TBM_MIN_SMOOTH 
TBM_MULTISCALE 
TBM_POISSON 
TBM_SEAMLESS 
TBM_SLOPE 
TBM_SUBTRACT 

◆ PeriodicityType

Describes the periodicity mode applied along map axes.

Enumerator
PERIODICITY_X 

Periodic only along the X axis.

PERIODICITY_Y 

Periodic only along the Y axis.

PERIODICITY_XY 

Periodic along both the X and Y axes.

◆ DomainBoundary

Describes which domain boundary.

Enumerator
BOUNDARY_LEFT 

i = 0

BOUNDARY_RIGHT 

i = nx - 1

BOUNDARY_TOP 

j = ny - 1

BOUNDARY_BOTTOM 

j = 0

◆ ElevationLongitudinalProfile

Enumerator
ELP_UNCHANGED 
ELP_FLAT 
ELP_DECREASING 
ELP_INCREASING 

◆ MixMethod

enum hmap::MixMethod : int

Methods for mixing/blending texture colors.

Enumerator
MM_LINEAR 

Linear RGB mixing.

MM_SQRT_AVG 

Square-root average mixing.

MM_MIXBOX 

Physical pigment-based mixing (Mixbox).

◆ NormalMapBlendingMethod

Enumerator
NMAP_LINEAR 
NMAP_DERIVATIVE 
NMAP_UDN 
NMAP_UNITY 
NMAP_WHITEOUT 

◆ Cmap

enum hmap::Cmap : int

Enumeration for different colormap types.

Enumeration of colormap types for image processing.

This enumeration is defined in the highmap/colormap.hpp file and is used for selecting the colormap to be applied during colorization.

This enumeration defines various colormap options that can be used for visualizing data in image processing. Each colormap provides a different color mapping scheme, which can be applied to grayscale images or data to enhance visual interpretation.

Enumerator
BONE 
GRAY 
HOT 
INFERNO 
JET 
MAGMA 
NIPY_SPECTRAL 
RAINBOW_DEM 
SEISMIC 
TERRAIN 
TURBO 
VIRIDIS 
WHITE_UNIFORM 

◆ ReduceOp

enum class hmap::ReduceOp : uint8_t
strong
Enumerator
Min 
Max 
Sum 

◆ SyncOperation

enum class hmap::SyncOperation
strong
Enumerator
Average 
CopyFirst 
CopySecond 
Min 
Max 
Mean 
SmoothBlend 
Sum 

◆ CurvatureType

enum hmap::CurvatureType : int

Types of curvature measures.

Defines the different curvature descriptors that can be computed on a scalar field (e.g. heightmap). They include classical differential curvatures as well as terrain-analysis specific measures.

Enumerator
CT_MIN 

Minimum curvature (principal).

CT_MAX 

Maximum curvature (principal).

CT_MEAN 

Mean curvature.

CT_GAUSSIAN 

Gaussian curvature.

CT_PROFILE 

Profile curvature (along slope direction).

CT_CONTOUR 

Contour curvature (across slope).

CT_TANGENTIAL 

Tangential curvature.

CT_ACCUMULATION 

Accumulation curvature (H² − K²).

CT_SHAPE_INDEX 

Shape index (normalized curvature classification).

CT_UNSPHERICITY 

Unsphericity (√(H² − K)).

CT_RING 

Ring curvature (planform torsion-like measure).

CT_ROTOR 

Rotor curvature (rotational component).

◆ MeshType

enum hmap::MeshType : int

Enumeration for different mesh types.

This enum defines the various types of mesh representations available. Each type corresponds to a different way of constructing and representing mesh data.

Enumerator
TRI_OPTIMIZED 

Triangles with optimized Delaunay triangulation.

TRI 

Triangle elements.

◆ AssetExportFormat

Enumeration for asset export formats supported by Assimp.

This enum lists the various file formats supported for asset export, as recognized by the Assimp library. Each format is associated with a specific file extension and usage.

Enumerator
_3DS 

Autodesk 3DS (legacy) - *.3ds.

_3MF 

The 3MF-File-Format - *.3mf.

ASSBIN 

Assimp Binary - *.assbin.

ASSXML 

Assxml Document - *.assxml.

FXBA 

Autodesk FBX (ascii) - *.fbx.

FBX 

Autodesk FBX (binary) - *.fbx.

COLLADA 

COLLADA - Digital Asset Exchange Schema - *.dae.

X3D 

Extensible 3D - *.x3d.

GLTF 

GL Transmission Format - *.gltf.

GLB 

GL Transmission Format (binary) - *.glb.

GTLF2 

GL Transmission Format v. 2 - *.gltf.

GLB2 

GL Transmission Format v. 2 (binary) - *.glb.

PLY 

Stanford Polygon Library - *.ply.

PLYB 

Stanford Polygon Library (binary) - *.ply.

STP 

Step Files - *.stp.

STL 

Stereolithography - *.stl.

STLB 

Stereolithography (binary) - *.stl.

OBJ 

Wavefront OBJ format - *.obj.

OBJNOMTL 

Wavefront OBJ format without material file - *.obj.

◆ ImageDataType

enum class hmap::ImageDataType : int
strong
Enumerator
FLOAT32 
FLOAT16 
UINT16 
UINT8 

◆ PoiType

enum class hmap::PoiType : int
strong

Classification types for terrain-aware points of interest.

Enumerator
CUSTOM 

Custom or unclassified score field.

APEX 

Local summits / peaks.

SINK 

Depressions / pits / sinkholes.

SADDLE 

Col / pass / saddle points.

RIDGE 

Elongated high terrain.

VALLEY 

Elongated low terrain.

CLIFF 

High slope / drop-offs.

PLATEAU 

Elevated flat areas.

FLAT_LOWLAND 

Low flat areas / plains.

VIEWPOINT 

High elevation + high prominence / openness.

SETTLEMENT_CANDIDATE 

Flat enough, accessible, good relief.

◆ DistanceMode

enum class hmap::DistanceMode : int
strong

Directional pattern mode for distance shaper.

Enumerator
ASTERISK 

Star-shaped pattern with cut-ins between directions.

PYRAMID 

Diamond/polyhedral pattern with flat planar facets.

◆ DistanceMethod

enum class hmap::DistanceMethod : int
strong

Method used to calculate distance.

Enumerator
RT 

Real-time directional slope projection.

CLASSIC 

Standard Euclidean distance transform.

◆ NoiseType

enum hmap::NoiseType : int

Enumeration of various noise types used for procedural generation.

This enumeration defines different types of noise algorithms that can be used for procedural generation tasks such as terrain generation, texture synthesis, and other applications where pseudo-random patterns are required.

Enumerator
PARBERRY 

Parberry (Perlin variant).

PERLIN 

Perlin.

PERLIN_BILLOW 

Perlin billow.

PERLIN_HALF 

Perlin half.

SIMPLEX2 

OpenSimplex2.

SIMPLEX2S 

OpenSimplex2S.

VALUE 

Value.

VALUE_CUBIC 

Value (cubic).

VALUE_DELAUNAY 

Value (delaunay).

VALUE_LINEAR 

Value (linear).

WORLEY 

Worley.

WORLEY_DOUBLE 

Worley double.

WORLEY_VALUE 

Worley (cell value return).

◆ ArraySampling

enum class hmap::ArraySampling : int
strong

Strategy used to extract a point value from an array.

Enumerator
AS_POINT 

Array value at the point (interpolated).

AS_MIN 

Minimum of the array values within a radius.

AS_MAX 

Maximum of the array values within a radius.

AS_MEAN 

Average of the array values within a radius.

◆ PointSamplingMethod

Enumeration of point sampling methods.

Enumerator
RND_RANDOM 

Purely random uniform sampling.

RND_HALTON 

Low-discrepancy Halton sequence sampling.

RND_HAMMERSLEY 

Low-discrepancy Hammersley sequence sampling.

RND_LHS 

Latin Hypercube Sampling.

◆ FlowGraphFlag

enum hmap::FlowGraphFlag : uint8_t
Enumerator
F_CLOSED 
F_PIT 
F_OUTLET 

◆ InterpolationMethod1D

Enumeration of the available 1D interpolation methods.

This enumeration defines the different types of interpolation methods that can be used with the Interpolator1D class.

Enumerator
AKIMA 

Akima interpolation.

AKIMA_PERIODIC 

Akima periodic interpolation.

CUBIC 

Cubic spline interpolation.

CUBIC_PERIODIC 

Cubic spline periodic interpolation.

LINEAR 

Linear interpolation.

POLYNOMIAL 

Polynomial interpolation.

STEFFEN 

Steffen interpolation (monotonic).

◆ InterpolationMethod2D

Enumeration of 2D interpolation methods.

This enum defines the available methods for 2D interpolation, such as Delaunay triangulation and nearest point interpolation.

Enumerator
ITP2D_DELAUNAY 

Delaunay triangulation method for 2D interpolation.

ITP2D_NEAREST 

Nearest point method for 2D interpolation.

ITP2D_IDW 

Inverse Distance Weighting.

ITP2D_GAUSSIAN 

Gaussian Distance Weighting.

ITP2D_NNI 

Natural Neighbor Interpolation.

ITP2D_DELAUNAY_GRADIENT 

Delaunay triangulation + linear gradient.

◆ InterpolationMethodCurve

Enumeration for specifying the interpolation method for curves.

Defines the available methods for curve interpolation:

  • BEZIER: Requires the number of points to be a multiple of 4 minus 1, like (4 * n - 1).
  • BSPLINE: B-spline interpolation method.
  • CATMULLROM: Catmull-Rom spline interpolation method.
  • DECASTELJAU: Uses De Casteljau's algorithm to compute Bézier curves at a given parameter. This is an alternative to the standard Bézier curve method.
  • POINTS_LERP: Linear interpolation between points.
Enumerator
BEZIER 

Bezier curve interpolation.

BSPLINE 

B-spline interpolation.

CATMULLROM 

Catmull-Rom spline interpolation.

DECASTELJAU 

De Casteljau algorithm for Bézier curve computation.

POINTS_LERP 

Linear interpolation between points.

◆ KernelType

enum hmap::KernelType : int

Enumeration for different kernel functions used in various algorithms.

This enumeration defines the types of kernel functions that can be used for smoothing, interpolation, and other operations requiring a kernel. Each kernel type represents a specific mathematical function used to weight data points based on their distance from a central point.

These kernels are used in algorithms that require weighting functions, such as kernel density estimation, interpolation, and data smoothing.

Enumerator
BIWEIGHT 

Biweight kernel function.

CUBIC_PULSE 

Cubic pulse kernel function.

CONE 

Cone kernel function.

CONE_SMOOTH 

Smooth cone kernel function.

DISK 

Disk kernel function.

LORENTZIAN 

Lorentzian (Cauchy) kernel function.

SMOOTH_COSINE 

Smooth cosine kernel function.

SQUARE 

Square kernel function.

TRICUBE 

Tricube kernel function.

CUPOLA 

Cupola (reverse) kernel function.

◆ MinMaxKernel

enum class hmap::MinMaxKernel : int
strong

Kernel footprint geometry for local minimum / maximum operations.

Enumerator
DISK 

Circular disk neighborhood.

OCTAGON 

Octagonal neighborhood (separable 4-pass approximation).

SQUARE 

Square neighborhood (separable 2-pass).

◆ DistanceFunction

Distance function type.

Enumerator
CHEBYSHEV 

Chebyshev.

EUCLIDIAN 

Euclidian.

EUCLISHEV 

Euclidian and Chebyshev mix.

MANHATTAN 

Manhattan.

◆ DistanceFunctionAxis

Axis used for the distance function.

Enumerator
DFA_X 

X-only.

DFA_Y 

Y-only.

DFA_XY 

X and Y.

◆ ErosionProfile

Procedural erosion angular profile type.

Enumerator
EP_COSINE 
EP_COSINE_BULK 
EP_COSINE_PEAK 
EP_PARABOL 
EP_SAW_SHARP 
EP_SAW_SMOOTH 
EP_SHARP_VALLEYS 
EP_SQRT 
EP_TRIANGLE_GRENIER 
EP_TRIANGLE_SHARP 
EP_TRIANGLE_SMOOTH 

◆ PhasorProfile

enum hmap::PhasorProfile : int

Phasor angular profile type.

Enumerator
PP_COSINE_BULKY 
PP_COSINE_PEAKY 
PP_COSINE_SQUARE 
PP_COSINE_STD 
PP_TRIANGLE 
PP_DUNE 

◆ RadialProfile

enum hmap::RadialProfile : int

Radial profile type.

Enumerator
RP_GAIN 
RP_LINEAR 
RP_POW 
RP_SMOOTHSTEP 
RP_SMOOTHSTEP_UPPER 
RP_FLAT_BOTTOM 
RP_SQRT 

◆ DistanceTransformType

Enumeration for different types of distance transforms.

Enumerator
DT_EXACT 

Exact distance transform.

DT_APPROX 

Approximate distance transform.

DT_MANHATTAN 

Manhattan distance transform.

DT_JFA 

Approximate (JFA) distance transform.

◆ MorphologyOperation

Types of base morphology operators.

Enumerator
MO_BORDER 

Extract border of structures.

MO_CLOSING 

Dilation followed by erosion (fills small holes).

MO_DILATION 

Expand structures (local maximum).

MO_EROSION 

Shrink structures (local minimum).

MO_OPENING 

Erosion followed by dilation (removes small objects).

MO_BLACK_HAT 

Difference between closing and input (dark features).

MO_TOP_HAT 

Difference between input and opening (bright features).

MO_GRADIENT 

Difference between dilation and erosion (edge magnitude).

MO_LAPLACIAN 

Second-order operator highlighting ridges and valleys.

MO_CLOSING_BY_RECONSTRUCTION 
MO_OPENING_BY_RECONSTRUCTION 

◆ VoronoiReturnType

Selects the value returned by the Voronoi evaluation.

F1 is the distance to the nearest site, F2 to the second nearest.

Enumerator
F1_SQUARED 

Returns F1^2.

F2_SQUARED 

Returns F2^2.

F1TF2_SQUARED 

Returns (F1 * F2)^2.

F1DF2_SQUARED 

Returns (F1 / F2)^2.

F2MF1_SQUARED 

Returns (F2 - F1)^2.

EDGE_DISTANCE_EXP 

Exponential edge distance.

EDGE_DISTANCE_SQUARED 

Squared edge distance.

CONSTANT 

Constant value.

CONSTANT_F2MF1_SQUARED 

Constant × (F2 - F1)^2.

◆ PrimitiveType

enum hmap::PrimitiveType : int

Defines the primitive shape used for synthesis.

Enumerator
PRIM_BIQUAD_PULSE 
PRIM_BUMP 
PRIM_CONE 
PRIM_CONE_SMOOTH 
PRIM_CUBIC_PULSE 
PRIM_SMOOTH_COSINE 

◆ ClampMode

enum hmap::ClampMode : int
Enumerator
POSITIVE_ONLY 
NEGATIVE_ONLY 
BOTH 
NONE 

◆ ScatterShape

enum hmap::ScatterShape : int

Defines the geometric shape used when converting a ScatterField to a heightmap.

Enumerator
SCATTER_SHAPE_DISK 

Circular dome / hemisphere profile.

SCATTER_SHAPE_POLYGON 

Irregular polygon profile.

SCATTER_SHAPE_CONE 

Linear cone profile.

SCATTER_SHAPE_PYRAMID 

Polygonal pyramid profile.

SCATTER_SHAPE_SMOOTH_DOME 

Smooth cosine dome profile.

◆ GridRegistration

enum class hmap::GridRegistration
strong

Grid registration policy for mapping discrete indices to [0, 1].

Enumerator
CellCenter 

Cell i covers [i/N, (i+1)/N], center at (i + 0.5)/N.

CellCorner 

Left corner of cell i at i/N.

Node 

Vertex-centered at i/(N-1), pinning endpoints 0 and 1.

◆ NormalizationMethod

Normalization methods.

Enumerator
NM_MIN_MAX 
NM_STANDARDIZE 
NM_ROBUST 

◆ TerrainAlignMode

enum class hmap::TerrainAlignMode : int
strong

Alignment modes for fitting an upper terrain to a lower terrain.

Enumerator
TAM_OFFSET 
TAM_PLANE 
TAM_ROBUST_OFFSET 
TAM_ROBUST_PLANE 

◆ SymmetryType

enum hmap::SymmetryType : int

Describes the symmetry operation to apply to an array.

Enumerator
SYMMETRY_LEFT_TO_RIGHT 

Mirror left half onto right half.

SYMMETRY_RIGHT_TO_LEFT 

Mirror right half onto left half.

SYMMETRY_TOP_TO_BOTTOM 

Mirror top half onto bottom half.

SYMMETRY_BOTTOM_TO_TOP 

Mirror bottom half onto top half.

SYMMETRY_X 

Symmetric average across vertical axis.

SYMMETRY_Y 

Symmetric average across horizontal axis.

SYMMETRY_XY 

4-quadrant symmetric average across both X and Y.

SYMMETRY_ROT180 

180-degree rotational symmetry around center.

◆ StorageMode

enum hmap::StorageMode : int
Enumerator
VA_RAM 
VA_DISK_LRU_STREAM 
VA_DISK_LRU_FULL 

◆ ForEachMode

enum hmap::ForEachMode : int
Enumerator
VA_SEQUENTIAL 
VA_DISTRIBUTED 
VA_SINGLE_ARRAY 

Function Documentation

◆ cv_mat_to_array()

Array hmap::cv_mat_to_array ( const cv::Mat & mat,
bool remap_values = true,
bool flip_j = false )

Converts an OpenCV cv::Mat to a 2D Array with optional value scaling to [0, 1].

◆ get_opencv_build_information()

std::string hmap::get_opencv_build_information ( )

Returns OpenCV build information string.

◆ to_cv_mat()

cv::Mat hmap::to_cv_mat ( Array & array)

Converts a 2D Array to a non-owning OpenCV cv::Mat (CV_32FC1).

◆ to_csv()

void hmap::to_csv ( const std::vector< glm::vec3 > & xyz,
const std::string & fname )

◆ adjust() [1/2]

glm::vec4 hmap::adjust ( const glm::vec4 & v,
float dx,
float dy,
float dz,
float dw )
inline

◆ adjust() [2/2]

glm::vec4 hmap::adjust ( const glm::vec4 & v,
float dr )
inline

◆ count_non_zero()

size_t hmap::count_non_zero ( const Array & array)

Count the number of non-zero elements in the array.

Parameters
arrayInput array.
Returns
Number of elements not equal to 0.

◆ count_zero()

size_t hmap::count_zero ( const Array & array)

Count the number of zero elements in the array.

Parameters
arrayInput array.
Returns
Number of elements equal to 0.

◆ for_each_cell() [1/2]

template<typename Fn>
void hmap::for_each_cell ( Array & a,
Fn && fn )
inline

Apply a function to every cell (mutable).

◆ for_each_cell() [2/2]

template<typename Fn>
void hmap::for_each_cell ( const Array & a,
Fn && fn )
inline

Apply a function to every cell (read-only).

◆ alter_elevation()

void hmap::alter_elevation ( Array & array,
const Cloud & cloud,
int ir,
float footprint_ratio = 1.f,
glm::vec2 shift = {0.f, 0.f},
glm::vec2 scale = {1.f, 1.f} )

Point-wise alteration: locally enforce a new elevation value while maintaining the 'shape' of the heightmap.

This function modifies the elevation values in the input array based on a cloud of points that specify the coordinates and variations for the alterations. The function ensures that the shape of the heightmap is preserved while applying these local changes.

The alteration is performed using a kernel with a minimal radius (ir) and the intensity of the alterations is scaled based on the footprint_ratio. The shift parameter allows for introducing noise or offset in the alteration process, and the scale parameter is used to adjust the domain of the alteration.

Parameters
arrayInput array representing the heightmap to be altered. The elevation values in this array will be adjusted according to the cloud data.
cloudCloud object that defines the coordinates and elevation variations for the alterations. This object provides the necessary data for applying the local changes.
irAlteration kernel minimal radius. This parameter defines the minimum size of the kernel used for local alterations.
footprint_ratioDefines how the radius of the alteration scales with the variation intensity. A higher ratio results in a larger footprint of the alterations.
shiftNoise shift specified as a vector {xs, ys} for each direction, relative to a unit domain. This allows for adding random offsets to the alteration process.
scaleDomain scaling in the range [0, 1]. This parameter adjusts the domain size over which the alteration is applied.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {2.f, 2.f};
int seed = 1;
// modification point (x, y) in [0, 1]x[0, 1] and a value
// corresponding to the relative elevation modification
cloud.push_back(hmap::Point(0.2f, 0.5f, -1.f));
cloud.push_back(hmap::Point(0.6f, 0.2f, 1.f));
hmap::Array z1 = z0;
hmap::alter_elevation(z1, cloud, 32, 2.f);
z1.to_png("out.png", hmap::Cmap::INFERNO);
z0.infos();
z1.infos();
hmap::export_banner_png("ex_alter_elevation.png",
{z0, z1},
}
Array class, helper to manipulate 2D float array with "(i, j)" indexing.
Definition array.hpp:31
void infos(const std::string &msg="") const
Display various information about the array.
Definition io.cpp:67
void to_png(const std::string &fname, int cmap, bool hillshading=false, int depth=0) const
Export the array as a PNG image file with a specified colormap and hillshading.
Definition io.cpp:132
Represents a collection of unordered points in 2D space.
Definition cloud.hpp:61
void push_back(const Point &p)
Appends a point.
Definition cloud.cpp:663
A class to represent and manipulate 2D points that can carry a value.
Definition point.hpp:26
int main(int argc, char **argv)
Definition main.cpp:12
Array noise_fbm(NoiseType noise_type, glm::ivec2 shape, glm::vec2 kw, std::uint32_t seed, int octaves=8, float weight=0.7f, float persistence=0.5f, float lacunarity=2.f, const Array *p_ctrl_param=nullptr, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit(), float angle=0.f, float stretch=1.f, float stretch_decay=0.f)
Return an array filled with coherence fbm noise.
Definition noise.cpp:78
void alter_elevation(Array &array, const Cloud &cloud, int ir, float footprint_ratio=1.f, glm::vec2 shift={0.f, 0.f}, glm::vec2 scale={1.f, 1.f})
Point-wise alteration: locally enforce a new elevation value while maintaining the 'shape' of the hei...
Definition alter_elevation.cpp:17
@ PERLIN
Perlin.
Definition functions.hpp:69
void export_banner_png(const std::string &fname, const std::vector< Array > &arrays, int cmap, bool hillshading=false, bool normalize_arrays=false)
Exports a set of arrays as a banner PNG image file.
Definition export_banner_png.cpp:18
@ INFERNO
Definition colormaps.hpp:87

Result

◆ apply_gaussian_pushes()

void hmap::apply_gaussian_pushes ( Array & array,
const std::vector< GaussianPush > & pushes )

Apply a sequence of truncated-Gaussian pushes to a heightmap.

Replays, in order, the deformations recorded by sls_deformation. Since the deformed terrain is fully described by the original terrain and the push sequence, this also provides a compact storage of the deformation.

Parameters
arrayHeightmap to deform (modified in place).
pushesPush operations to apply, in order.
See also
sls_deformation

◆ base_elevation()

Array hmap::base_elevation ( glm::ivec2 shape,
const std::vector< std::vector< float > > & values,
float width_factor = 1.f,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
const Array * p_stretching = nullptr,
const UvRect & uv_rect = UvRect::unit() )

Generate a heightmap from a coarse grid of control points with defined elevation values.

This function creates a heightmap by interpolating elevation values provided at specific control points on a coarse grid. The result is a finer resolution heightmap where the elevation values are smoothly distributed over the entire grid.

The interpolation is performed using a Gaussian function, with the width_factor parameter controlling the half-width of the base Gaussian function used for smoothing. Optionally, noise can be added using the provided p_noise_x and p_noise_y arrays, and the heightmap can be adjusted by a local wavenumber multiplier specified by p_stretching. The bbox parameter defines the domain bounding box for the heightmap.

Parameters
shapeDimensions of the output array (heightmap).
valuesElevation values at the control points specified on a coarse grid. This 2D vector holds the elevation data at each control point.
width_factorFactor applied to the half-width of the Gaussian function used for smoothing the elevations. A value of 1.0 represents the default smoothing width.
p_noise_xOptional pointer to an input noise array affecting the x-direction. If provided, it is used to add noise to the elevation values.
p_noise_yOptional pointer to an input noise array affecting the y-direction. If provided, it is used to add noise to the elevation values.
p_stretchingOptional pointer to an input array that acts as a local wavenumber multiplier. If provided, it adjusts the elevation values according to the local wavenumber.
bboxDomain bounding box specified as a vector {xmin, xmax, ymin, ymax}. This defines the extent of the heightmap in the coordinate space.
Returns
Array A new array representing the generated heightmap with interpolated elevation values.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
// 2x3 grid (column ordering, Fortran style)
std::vector<std::vector<float>> values = {{0.f, 0.5f, 0.f}, {1.f, 1.5f, 2.f}};
hmap::Array z1 = hmap::base_elevation(shape, values);
shape,
{2.f, 2.f},
1);
shape,
{2.f, 2.f},
2);
float width_factor = 1.f;
hmap::Array z2 = hmap::base_elevation(shape, values, width_factor, &nx, &ny);
hmap::export_banner_png("ex_base_elevation.png",
{z1, z2},
}
Array base_elevation(glm::ivec2 shape, const std::vector< std::vector< float > > &values, float width_factor=1.f, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const Array *p_stretching=nullptr, const UvRect &uv_rect=UvRect::unit())
Generate a heightmap from a coarse grid of control points with defined elevation values.
Definition base_elevation.cpp:16

Result

◆ elevation_from_contours() [1/2]

Array hmap::elevation_from_contours ( glm::ivec2 shape,
const std::vector< Path > & contours,
const std::vector< float > & elevations,
const Array * p_probability = nullptr,
float randomness = 1.f,
std::uint32_t seed = 0,
float peak_ratio = 0.5f,
float outside_ratio = 1.f,
bool smoothstep = false,
const UvRect & uv_rect = UvRect::unit() )

Synthesize a heightmap from sparse closed iso-contours with known elevations using stochastic front propagation (proof of concept).

Experimental raster adaptation of the contour-based terrain synthesis of Huftier et al. [Huftier2026]. Each input path is treated as a closed polygon at a constant elevation. Contour pixels are fixed to their elevation (Dirichlet constraints) and the innermost enclosing contour defines the "zone" of every other pixel. Within a zone, two fronts are propagated from the fixed pixels with an Eden growth process implemented as first-passage percolation (Dijkstra with random passage times): one front from the zone's own contour, one from its child contours. The time needed to enter a pixel is ((1 - randomness) + randomness * E) / rate with E an exponential random variable and rate given by the probability map for the rising front and by its complement for the descending front. The arrival times t_near and t_far define a progress t_near / (t_near + t_far) that is mapped linearly between the two contour elevations after spurious pits are removed by a priority flood.

With randomness = 0 the passage times equal their expectation and the method reduces to a deterministic, probability-weighted geodesic front propagation. With a uniform probability map the result is then close to an inverse-distance interpolation between consecutive contours.

Leaf contours (contours without children) rise to elevation + peak_ratio * spacing at their farthest interior point, or sink by the same amount when the contour is lower than its parent (basins). Outside all contours the terrain falls off to elevation - outside_ratio * spacing. spacing is the mean elevation gap between nested contours (falls back to the elevation range, then to 1).

Limitations of this proof of concept: contours must not cross each other; children of a contour with different elevations produce a discontinuity along the seam between their regions; pit removal is only applied to zones whose child contours are all higher than the enclosing contour.

Parameters
shapeOutput array shape.
contoursClosed contour polygons (at least 3 points each), in bbox coordinates. The closed flag of the paths is ignored, every path is closed.
elevationsElevation of each contour (same size as contours).
p_probabilityOptional probability map in [0, 1] with shape shape. Where it is high the rising front advances fast and the terrain stays low longer (gentle slopes); where it is low the terrain rises quickly (steep slopes). If null, a uniform map (0.5) is used.
randomnessAmount of randomness in the front propagation in [0, 1]: 0 is deterministic, 1 is the Eden growth model.
seedRandom seed.
peak_ratioElevation gain of leaf contour interiors, relative to the mean elevation gap between nested contours.
outside_ratioElevation drop outside all contours, relative to the mean elevation gap between nested contours.
smoothstepIf true, applies smoothstep (S-curve) interpolation between contours, yielding softer transitions near contour boundaries. If false (default), uses linear interpolation.
bboxDomain bounding box {xmin, xmax, ymin, ymax}.
Returns
Array Synthesized heightmap, or an empty array if the inputs are invalid.

Example

#include <cmath>
#include <iostream>
#include "highmap.hpp"
// closed star-shaped contour: radius r0 modulated by a fixed angular profile
// (all blobs share the profile so that nested blobs never cross)
hmap::Path blob(float cx, float cy, float r0, int npts = 96)
{
std::vector<float> x, y;
for (int k = 0; k < npts; ++k)
{
float t = 2.f * M_PI * k / npts;
float m = 1.f + 0.12f * std::sin(3.f * t + 0.7f) +
0.08f * std::sin(5.f * t + 2.1f);
x.push_back(cx + r0 * m * std::cos(t));
y.push_back(cy + r0 * m * std::sin(t));
}
hmap::Path p(x, y);
p.set_closed(true);
return p;
}
// extract n iso-level contours as a heightmap where contour pixels hold their
// elevation and other pixels are 0
hmap::Array extract_contours_from_heightmap(const hmap::Array &heightmap,
int n_levels)
{
if (heightmap.size() == 0 || n_levels <= 0) return hmap::Array();
const glm::ivec2 shape = heightmap.shape;
hmap::Array out(shape, 0.f);
const float h_min = heightmap.min();
const float h_max = heightmap.max();
if (std::abs(h_max - h_min) < 1e-6f) return out;
for (int l = 1; l <= n_levels; ++l)
{
const float isoval = h_min +
(float(l) / float(n_levels + 1)) * (h_max - h_min);
// a pixel is on the contour if it crosses the isovalue relative to any
// 4-neighbor
for (int j = 0; j < shape.y; ++j)
for (int i = 0; i < shape.x; ++i)
{
const float v = heightmap(i, j);
// check horizontal neighbor
if (i + 1 < shape.x)
{
const float vr = heightmap(i + 1, j);
if ((v <= isoval && vr >= isoval) || (v >= isoval && vr <= isoval))
{
if (std::abs(v - isoval) <= std::abs(vr - isoval))
out(i, j) = isoval;
else
out(i + 1, j) = isoval;
}
}
// check vertical neighbor
if (j + 1 < shape.y)
{
const float vt = heightmap(i, j + 1);
if ((v <= isoval && vt >= isoval) || (v >= isoval && vt <= isoval))
{
if (std::abs(v - isoval) <= std::abs(vt - isoval))
out(i, j) = isoval;
else
out(i, j + 1) = isoval;
}
}
}
}
return out;
}
int main(void)
{
glm::ivec2 shape = {1024, 1024};
hmap::BBox2D bbox = {0.f, 1.f, 0.f, 1.f};
int seed = 1;
// --- sparse contours: a main hill with 4 nested levels, a small basin in
// its lowest ring and a second, separate hill
std::vector<hmap::Path> contours = {blob(0.38f, 0.48f, 0.30f),
blob(0.38f, 0.48f, 0.21f),
blob(0.38f, 0.48f, 0.13f),
blob(0.38f, 0.48f, 0.06f),
blob(0.67f, 0.48f, 0.03f),
blob(0.82f, 0.82f, 0.11f),
blob(0.82f, 0.82f, 0.04f)};
std::vector<float> elevations = {0.1f, 0.3f, 0.5f, 0.7f, 0.f, 0.2f, 0.4f};
// input contours drawn at their elevation, for reference
hmap::Array z_contours(shape);
for (size_t k = 0; k < contours.size(); ++k)
{
hmap::Path p = contours[k];
p.set_values(elevations[k]);
p.to_array(z_contours, bbox);
}
// --- deterministic front propagation (weighted geodesic interpolation)
contours,
elevations,
nullptr,
0.f);
// --- stochastic Eden growth, uniform probability
contours,
elevations,
nullptr,
1.f,
seed);
// --- stochastic Eden growth biased by a noise probability map
shape,
{4.f, 4.f},
seed,
8);
hmap::remap(proba, 0.05f, 0.95f);
contours,
elevations,
&proba,
1.f,
seed);
// --- deterministic propagation with the same probability map
contours,
elevations,
&proba,
0.f);
// --- noise-based raster contours: extract iso-contours from Perlin fbm noise
shape,
{2.f, 2.f},
seed);
hmap::remap(noise_hmap, 0.1f, 0.9f);
hmap::Array raster_contours = extract_contours_from_heightmap(noise_hmap, 6);
// synthesize elevation directly from raster contours with smoothstep
hmap::Array z_noise_reconstructed = hmap::elevation_from_contours(
raster_contours,
&proba,
0.f,
seed,
1.f,
0.f,
false);
z_noise_reconstructed.dump();
// --- evaluation: elevation error along the input contours
for (const hmap::Array *pz : {&z1, &z2, &z3, &z4})
{
float err_max = 0.f;
float err_mean = 0.f;
int n = 0;
for (size_t k = 0; k < contours.size(); ++k)
{
std::vector<float> v = hmap::interpolate_values_from_array(contours[k],
*pz,
bbox);
for (float vi : v)
{
float e = std::abs(vi - elevations[k]);
err_max = std::max(err_max, e);
err_mean += e;
++n;
}
}
std::cout << "contour elevation error: max " << err_max << ", mean "
<< err_mean / n << "\n";
}
hmap::export_banner_png("ex_elevation_from_contours.png",
{z_contours,
z1,
z2,
z3,
z4,
noise_hmap,
raster_contours,
z_noise_reconstructed},
true);
}
void dump(const std::string &fname="out.png") const
Debug tool, dump some infos and generate an output file (16bits grayscale).
Definition methods.cpp:109
int size() const
Return the total number of elements in the array.
Definition methods.cpp:527
float min(ICommunicator &comm=SingleArrayComm::instance()) const
Return the value of the smallest element in the array.
Definition methods.cpp:321
glm::ivec2 shape
The shape of the array {ni, nj}.
Definition array.hpp:37
float max(ICommunicator &comm=SingleArrayComm::instance()) const
Return the value of the greatest element in the array.
Definition methods.cpp:293
void set_values(const std::vector< float > &new_values)
Set new values for the cloud points.
Definition cloud.cpp:363
Represents an ordered set of points in 2D, forming a polyline (open or closed).
Definition path.hpp:43
void to_array(Array &array, const BBox2D &bbox=BBox2D{}, bool filled=false) const
Project path points to an array.
Definition path.cpp:547
void remap(Array &array, float vmin, float vmax, float from_min, float from_max)
Remap array elements from a starting range to a target range.
Definition range.cpp:434
Array elevation_from_contours(glm::ivec2 shape, const std::vector< Path > &contours, const std::vector< float > &elevations, const Array *p_probability=nullptr, float randomness=1.f, std::uint32_t seed=0, float peak_ratio=0.5f, float outside_ratio=1.f, bool smoothstep=false, const UvRect &uv_rect=UvRect::unit())
Synthesize a heightmap from sparse closed iso-contours with known elevations using stochastic front p...
Definition elevation_from_contours.cpp:872
std::vector< float > interpolate_values_from_array(const Cloud &cloud, const Array &array, const BBox2D &bbox)
Interpolate values from an array at the points' (x, y) locations.
Definition cloud_functions.cpp:98
@ TERRAIN
Definition colormaps.hpp:93
Axis-aligned 2D bounding box in world coordinates.
Definition bbox2d.hpp:25

Result

◆ elevation_from_contours() [2/2]

Array hmap::elevation_from_contours ( const Array & contours,
const Array * p_probability = nullptr,
float randomness = 1.f,
std::uint32_t seed = 0,
float peak_ratio = 0.5f,
float outside_ratio = 1.f,
bool smoothstep = false )

Synthesize a heightmap from a raster of sparse iso-contours with known elevations using stochastic front propagation.

Overload of elevation_from_contours where contour elevations are provided directly on a raster grid (contours). Pixels with non-zero values (or distinct non-background elevation values) serve as the Dirichlet constraints.

Parameters
contoursRaster array containing contour elevations at contour pixels and zero elsewhere.
p_probabilityOptional probability map in [0, 1] with the same shape as contours.
randomnessAmount of randomness in the front propagation in [0, 1]: 0 is deterministic, 1 is the Eden growth model.
seedRandom seed.
peak_ratioElevation gain of leaf contour interiors, relative to the mean elevation gap between nested contours.
outside_ratioElevation drop outside all contours, relative to the mean elevation gap between nested contours.
smoothstepIf true, applies smoothstep (S-curve) interpolation between contours.
Returns
Array Synthesized heightmap.

◆ elevation_from_sparse_constraints()

Array hmap::elevation_from_sparse_constraints ( const Array & mountains,
const Array * p_coastline = nullptr,
const Array * p_boundary = nullptr,
float mountain_elevation = 1.0f,
float coastline_elevation = 0.0f,
float boundary_elevation = -1.0f,
int iterations_max = 500,
float tolerance = 1e-5f,
const Array * p_noise = nullptr,
float noise_amplitude = 0.0f )

Synthesize a smooth heightmap from sparse elevation constraints using GPU harmonic interpolation (Laplacian PDE).

This function allows generating a continuous terrain elevation model from sparse sketch data by treating the provided constraints as Dirichlet boundary conditions and solving the discrete Laplace equation ($\Delta z = 0$) using GPU-accelerated Red-Black SOR.

Parameters
mountainsArray specifying mountain peak/ridge elevations (> 0).
p_coastlineOptional pointer to coastline mask (fixed to coastline_elevation).
p_boundaryOptional pointer to outer boundary/ocean mask (fixed to boundary_elevation). If null, a 1-pixel boundary border around the domain perimeter is used.
mountain_elevationTarget elevation scaling for mountains (default: 1.0).
coastline_elevationElevation at coastline (default: 0.0).
boundary_elevationElevation at boundary/ocean (default: -1.0).
iterations_maxMax iterations for GPU solver (default: 500).
toleranceConvergence tolerance for early exit (default: 1e-5).
p_noiseOptional noise array to modulate the free terrain regions.
noise_amplitudeAmplitude of optional noise detail (default: 0.0).
Returns
Array The resulting smooth synthesized heightmap.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {512, 512};
// 1. Define mountain ridge lines (values > 0)
hmap::Path ridge1;
ridge1.push_back({0.150f, 0.250f, 1.0f});
ridge1.push_back({0.260f, 0.230f, 1.0f});
ridge1.push_back({0.360f, 0.220f, 1.0f});
ridge1 = hmap::catmullrom(ridge1);
hmap::Path ridge2;
ridge2.push_back({0.256f, 0.280f, 1.0f});
ridge2.push_back({0.280f, 0.380f, 1.0f});
ridge2 = hmap::catmullrom(ridge2);
hmap::Array mountains(shape, 0.0f);
ridge1.to_array(mountains);
ridge2.to_array(mountains);
// 2. Define closed coastline path (z = 0)
hmap::Path coast;
int n_coast_pts = 24;
for (int i = 0; i <= n_coast_pts; ++i)
{
float angle = 2.0f * M_PI * static_cast<float>(i) /
static_cast<float>(n_coast_pts);
float r = 0.22f + 0.03f * std::sin(3.0f * angle);
coast.push_back(
{0.256f + r * std::cos(angle), 0.256f + r * std::sin(angle), 1.0f});
}
coast = hmap::catmullrom(coast);
hmap::Array coastline(shape, 0.0f);
coast.to_array(coastline);
// 3. Generate smooth continuous heightmap using GPU harmonic interpolation
&coastline,
nullptr,
1.0f,
0.0f,
-1.0f);
// 4. Modulate with optional procedural noise
shape,
{6.0f, 6.0f},
42);
&coastline,
nullptr,
1.0f,
0.0f,
-1.0f,
500,
1e-5f,
&noise,
0.25f);
hmap::export_banner_png("ex_elevation_from_sparse_constraints.png",
{mountains, coastline, z_harmonic, z_detailed},
true);
return 0;
}
bool init_opencl()
Definition gpu_opencl.cpp:33
Array elevation_from_sparse_constraints(const Array &mountains, const Array *p_coastline=nullptr, const Array *p_boundary=nullptr, float mountain_elevation=1.0f, float coastline_elevation=0.0f, float boundary_elevation=-1.0f, int iterations_max=500, float tolerance=1e-5f, const Array *p_noise=nullptr, float noise_amplitude=0.0f)
Synthesize a smooth heightmap from sparse elevation constraints using GPU harmonic interpolation (Lap...
Definition elevation_from_sparse_constraints.cpp:12
Path catmullrom(const Path &path, int edge_divisions=10, Path::EdgeDivisionMode edm=Path::EdgeDivisionMode::EDM_PER_EDGE)
Smooth the path using Catmull-Rom curves.
Definition path_functions.cpp:162
float angle(const Point &p1, const Point &p2)
Computes the angle between two points relative to the x-axis.
Definition points.cpp:65
Array noise(NoiseType noise_type, glm::ivec2 shape, glm::vec2 kw, std::uint32_t seed, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit(), float angle=0.f, float stretch=1.f)
Return an array filled with coherence noise.
Definition noise.cpp:17

◆ reverse_midpoint()

Array hmap::reverse_midpoint ( const Array & array,
std::uint32_t seed,
float noise_scale = 1.f,
float threshold = 0.f )

Apply the reverse midpoint displacement algorithm to the input array.

This function implements the reverse midpoint displacement algorithm as described in Belhadj et al. (2005). The algorithm generates a terrain-like structure by applying displacement to the values in the input array based on random noise. The function can be tuned using the seed parameter for random number generation, noise_scale for controlling the amplitude of the noise, and threshold for setting a background value.

Parameters
arrayInput array to which the reverse midpoint displacement algorithm will be applied. The array's values are modified to produce the output terrain.
seedRandom seed number used to initialize the random number generator for reproducibility.
noise_scaleAmplitude of the noise applied during the displacement process. A higher value results in more pronounced terrain features.
thresholdThreshold 'background' value used to influence the displacement algorithm. Values below this threshold may be treated differently depending on the algorithm's design.
Returns
Array The output array after applying the reverse midpoint displacement algorithm. This array contains the modified values representing the generated terrain.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
int seed = 3;
hmap::Path path = hmap::Path(4, seed, bbox);
path.reorder_nns();
path = hmap::bezier(path);
// input array, scattered non-zero values
hmap::Array z0 = hmap::Array(shape);
path.to_array(z0, bbox);
hmap::Array z1 = reverse_midpoint(z0, seed++);
hmap::export_banner_png("ex_reverse_midpoint.png", {z0, z1}, hmap::Cmap::JET);
}
void reorder_nns(int start_index=0)
Reorder points using a nearest neighbor search.
Definition path.cpp:350
void median_3x3(Array &array, const Array *p_mask)
Apply a 3x3 median filter to the input array.
Definition filters.cpp:694
Path bezier(const Path &path, float curvature_ratio=0.3f, int edge_divisions=10, Path::EdgeDivisionMode edm=Path::EdgeDivisionMode::EDM_PER_EDGE)
Smooth the path using Bezier curves.
Definition path_functions.cpp:51
BBox2D unit_square_bbox()
Constructs a 4D bounding box for a unit square {0, 1, 0, 1}.
Definition points.cpp:379
@ JET
Definition colormaps.hpp:88

Result

◆ ridgelines()

Array hmap::ridgelines ( glm::ivec2 shape,
const std::vector< float > & xr,
const std::vector< float > & yr,
const std::vector< float > & zr,
float slope,
float k_smoothing = 1.f,
float width = 0.1f,
float vmin = 0.f,
const UvRect & uv_rect = UvRect::unit(),
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
const Array * p_stretching = nullptr,
const UvRect & uv_rect_array = UvRect::unit() )

Generate a heightmap based on a set of ridgelines and a specified slope.

This function creates a heightmap using a set of ridgelines defined by their x, y, and z coordinates, and applies a specified slope to the ridgelines. The function can optionally apply smoothing, adjust the ridge edge width, and clamp values below a minimum threshold. Additional noise and stretching parameters can be applied to modify the resulting heightmap.

Parameters
shapeThe dimensions of the output array (heightmap).
xrA vector of x-coordinates defining ridge segments.
yrA vector of y-coordinates defining ridge segments.
zrA vector of z-coordinates defining ridge segments.
slopeThe slope applied to the ridgelines. Can be negative to invert the slope.
k_smoothingSmoothing parameter to control the smoothness of the ridgelines.
widthWidth of the ridge edges. Determines how broad the ridges appear.
vminMinimum value for the heightmap. Values below this threshold will be clamped to vmin.
bboxBounding box for the entire domain, defining the area covered by the heightmap.
p_noise_xPointer to an optional array for x-direction noise to apply to the heightmap.
p_noise_yPointer to an optional array for y-direction noise to apply to the heightmap.
p_stretchingPointer to an optional array for local wavenumber multipliers to stretch the ridges.
bbox_arrayBounding box for the array domain, defining the spatial extent of the heightmap.
Returns
Array The generated heightmap with ridgelines and applied slope.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
// "segments", coordinates are given by pairs (xa_1, xa_2, xb_1,
// xb_2, ...)
std::vector<float> x = {0.1f, 0.5f, 0.7f, 0.2f, 0.2f, 0.1f};
std::vector<float> y = {0.2f, 0.2f, 0.8f, 0.9f, 0.9f, 0.6f};
std::vector<float> v = {1.0f, 0.5f, 0.8f, 0.4f, 0.4f, 0.9f};
float slope = 3.f;
auto z1 = hmap::ridgelines(shape, x, y, v, slope);
auto z2 = hmap::ridgelines(shape, x, y, v, -slope);
hmap::export_banner_png("ex_ridgelines.png", {z1, z2}, hmap::Cmap::INFERNO);
}
Array slope(glm::ivec2 shape, float angle, float slope, const Array *p_ctrl_param=nullptr, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit())
Return an array corresponding to a slope with a given overall.
Definition primitives.cpp:362
Array ridgelines(glm::ivec2 shape, const std::vector< float > &xr, const std::vector< float > &yr, const std::vector< float > &zr, float slope, float k_smoothing=1.f, float width=0.1f, float vmin=0.f, const UvRect &uv_rect=UvRect::unit(), const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const Array *p_stretching=nullptr, const UvRect &uv_rect_array=UvRect::unit())
Generate a heightmap based on a set of ridgelines and a specified slope.
Definition ridgelines.cpp:21

Result

◆ ridgelines_bezier()

Array hmap::ridgelines_bezier ( glm::ivec2 shape,
const std::vector< float > & xr,
const std::vector< float > & yr,
const std::vector< float > & zr,
float slope,
float k_smoothing = 1.f,
float width = 0.1f,
float vmin = 0.f,
const UvRect & uv_rect = UvRect::unit(),
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
const Array * p_stretching = nullptr,
const UvRect & uv_rect_array = UvRect::unit() )

Generate a heightmap based on a set of ridgelines with quadratic Bezier interpolation.

This function creates a heightmap using ridgelines defined by their x, y, and z coordinates. The ridgelines are interpolated using quadratic Bezier curves to smooth the transitions. The function applies a specified slope to the ridgelines and can optionally apply smoothing, adjust ridge edge width, and clamp values below a minimum threshold. Additional noise and stretching parameters can be used to modify the resulting heightmap.

Parameters
shapeThe dimensions of the output array (heightmap).
xrA vector of x-coordinates defining ridge segments, organized in groups of three (control points of the Bezier curves).
yrA vector of y-coordinates defining ridge segments, organized in groups of three (control points of the Bezier curves).
zrA vector of z-coordinates defining ridge segments, organized in groups of three (control points of the Bezier curves).
slopeThe slope applied to the ridgelines. Can be negative to invert the slope.
k_smoothingSmoothing parameter to control the smoothness of the ridgelines.
widthWidth of the ridge edges. Determines how broad the ridges appear.
vminMinimum value for the heightmap. Values below this threshold will be clamped to vmin.
bboxBounding box for the entire domain, defining the area covered by the heightmap.
p_noise_xPointer to an optional array for x-direction noise to apply to the heightmap.
p_noise_yPointer to an optional array for y-direction noise to apply to the heightmap.
p_stretchingPointer to an optional array for local wavenumber multipliers to stretch the ridges.
bbox_arrayBounding box for the array domain, defining the spatial extent of the heightmap.
Returns
Array The generated heightmap with ridgelines interpolated using quadratic Bezier curves and applied slope.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
// "segments", coordinates are given by groups of three points in
// order to define a quadratic bezier curve, start point, control
// point and end point (xa_1, xa_2, xa_3, xb_1, xb_2, xb_3...)
std::vector<float> x = {0.1f, 0.5f, 0.7f};
std::vector<float> y = {0.6f, 0.2f, 0.8f};
std::vector<float> v = {1.0f, 0.f, 0.5f}; // control pt (middle)
// value not used
float slope = 4.f;
auto z1 = hmap::ridgelines_bezier(shape, x, y, v, slope);
v = {-1.0f, 0.f, -0.5f};
auto z2 = hmap::ridgelines_bezier(shape, x, y, v, -slope);
hmap::export_banner_png("ex_ridgelines_bezier.png",
{z1, z2},
}
Array ridgelines_bezier(glm::ivec2 shape, const std::vector< float > &xr, const std::vector< float > &yr, const std::vector< float > &zr, float slope, float k_smoothing=1.f, float width=0.1f, float vmin=0.f, const UvRect &uv_rect=UvRect::unit(), const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const Array *p_stretching=nullptr, const UvRect &uv_rect_array=UvRect::unit())
Generate a heightmap based on a set of ridgelines with quadratic Bezier interpolation.
Definition ridgelines.cpp:111

Result

◆ sls_deformation()

Array hmap::sls_deformation ( const Array & z,
const std::vector< DeformationConstraint > & constraints,
std::uint32_t seed,
int iterations = 200,
int ir_min = 4,
int ir_max = 64,
int n_radii = 7,
float talus_max = 0.f,
int n_candidates = 512,
float p_best = 0.65f,
float top_fraction = 0.1f,
float tolerance = 1e-3f,
std::vector< GaussianPush > * p_pushes = nullptr )

Deform a heightmap to satisfy a set of constraints using stochastic local search over truncated-Gaussian push operations.

Implements the constraint-based terrain deformation of S. Stachniak and W. Stuerzlinger, "An Algorithm for Automated Fractal Terrain Deformation", WSCG

  1. The terrain T is deformed into T' by searching for a sequence of local push operations (location, amplitude, radius) (see GaussianPush) that minimize a fitness function F(T) = sum F(x, y), where the per-vertex penalty F(x, y) is the sum of the supplied constraint terms (see DeformationConstraint). Because the penalties are summed, several constraints (shape masks, fixed paths, edge matching, reference heights...) can be satisfied simultaneously.

At every iteration, a set of candidate vertices is drawn: half on a jittered uniform grid, half sampled proportionally to the current penalty map so that the search concentrates where constraints are violated. For each candidate and each radius, the push amplitude is the least-squares optimum of the (locally quadratic) penalty over the kernel footprint, clamped by the slope limit talus_max * radius which suppresses high-frequency spikes (frequency limitation of the paper). The best deformation is applied with probability p_best, otherwise one of the top_fraction best deformations is applied (the stochastic noise of the search, which prevents stalling in local minima). The search stops when the fitness drops below tolerance times its initial value, when no improving deformation can be found for a number of consecutive iterations, or after iterations pushes.

Parameters
zInput heightmap.
constraintsConstraint terms defining the fitness function. Every target and weight array must have the shape of z.
seedRandom seed number.
iterationsMaximum number of iterations (one push per iteration).
ir_minSmallest push radius, in pixels.
ir_maxLargest push radius, in pixels.
n_radiiNumber of radii, geometrically spaced in [ir_min, ir_max].
talus_maxMaximum push amplitude per pixel of radius (slope limit). If zero or negative, defaults to the elevation range of the inputs divided by ir_max.
n_candidatesNumber of candidate vertices evaluated per iteration.
p_bestProbability of applying the best deformation found (0.65 in the original paper).
top_fractionFraction of the best deformations a sub-optimal choice is drawn from.
toleranceRelative fitness tolerance for early termination.
p_pushesOptional pointer to a vector receiving the applied pushes, in order (see apply_gaussian_pushes).
Returns
Array Deformed heightmap.

Example

#include <chrono>
#include <iostream>
#include "highmap.hpp"
int main(void)
{
const glm::ivec2 shape = {256, 256};
const uint32_t seed = 1;
const float water_level = 0.5f;
const float coast_margin = 0.1f;
const float road_level = 0.65f;
shape,
{4.f, 4.f},
seed);
// 1. Shape constraint: a five-pointed star island. Vertices inside the
// mask must be above the water level, vertices outside must be below (with
// a small margin on each side to get a clear coastline).
hmap::Path star;
for (int k = 0; k < 10; ++k)
{
float angle = 0.5f * M_PI + 2.f * M_PI * static_cast<float>(k) / 10.f;
float r = (k % 2 == 0) ? 0.42f : 0.18f;
star.push_back(
{0.5f + r * std::cos(angle), 0.5f + r * std::sin(angle), 1.f});
}
star.set_closed(true);
hmap::Array mask(shape, 0.f);
star.to_array(mask, hmap::BBox2D::unit(), true);
hmap::Array sea(shape, 1.f);
sea -= mask;
land.target = hmap::Array(shape, water_level + coast_margin);
land.weight = mask;
ocean.target = hmap::Array(shape, water_level - coast_margin);
ocean.weight = sea;
// 2. Path constraint: a flat S-shaped road at a fixed elevation, the rest
// of the terrain being preserved as much as possible (to avoid a global
// flattening of the terrain)
hmap::Path road;
road.push_back({0.08f, 0.15f, 1.f});
road.push_back({0.35f, 0.25f, 1.f});
road.push_back({0.50f, 0.50f, 1.f});
road.push_back({0.65f, 0.75f, 1.f});
road.push_back({0.92f, 0.85f, 1.f});
road = hmap::catmullrom(road);
hmap::Array path(shape, 0.f);
road.to_array(path);
path = hmap::dilation(path, 4);
hmap::Array not_path(shape, 1.f);
not_path -= path;
flat_road.target = hmap::Array(shape, road_level);
flat_road.weight = path;
preserve.target = z;
preserve.weight = not_path;
// preserve original heights on the island so positive pushes do not inflate
// land amplitude
land_preserve.target = z;
land_preserve.weight = mask;
// 3. Run the search for each set of constraints, and for the combination
// (the road is allowed to cross the sea as a causeway: sea vertices under
// the road are released from the ocean constraint)
auto run = [&](const std::string &label,
const std::vector<hmap::DeformationConstraint> &constraints,
int iterations)
{
std::vector<hmap::GaussianPush> pushes;
auto t0 = std::chrono::steady_clock::now();
constraints,
seed,
iterations,
4,
64,
7,
0.f,
512,
0.65f,
0.1f,
1e-3f,
&pushes);
auto t1 = std::chrono::steady_clock::now();
std::cout << label << ": " << pushes.size() << " pushes in "
<< std::chrono::duration<float>(t1 - t0).count() << " s\n";
return out;
};
hmap::Array z_star = run("star island", {land, ocean, land_preserve}, 600);
hmap::Array z_road = run("flat road", {flat_road, preserve}, 800);
hmap::DeformationConstraint ocean_causeway = ocean;
ocean_causeway.weight *= not_path;
hmap::Array z_both = run("star island + road",
{land, ocean_causeway, flat_road},
1000);
// render with the sea flattened at the water level
for (hmap::Array *p : {&z_star, &z_road, &z_both})
hmap::clamp_min(*p, water_level);
hmap::export_banner_png("ex_sls_deformation.png",
{z, z_star, z_road, z_both},
true);
return 0;
}
void set_closed(bool new_value)
Set whether the path is closed.
Definition path.cpp:521
void clamp_min(Array &array, float vmin)
Clamp array values lower than a given bound.
Definition range.cpp:155
@ ABOVE
penalize only heights below the target (target acts as a floor)
Definition authoring.hpp:34
@ BELOW
Definition authoring.hpp:35
@ MATCH
penalize any deviation from the target height
Definition authoring.hpp:33
Array sls_deformation(const Array &z, const std::vector< DeformationConstraint > &constraints, std::uint32_t seed, int iterations=200, int ir_min=4, int ir_max=64, int n_radii=7, float talus_max=0.f, int n_candidates=512, float p_best=0.65f, float top_fraction=0.1f, float tolerance=1e-3f, std::vector< GaussianPush > *p_pushes=nullptr)
Deform a heightmap to satisfy a set of constraints using stochastic local search over truncated-Gauss...
Definition sls_deformation.cpp:231
Array dilation(const Array &array, int ir)
Apply a dilation algorithm to the input array using a square structure.
Definition morphology.cpp:93
static constexpr BBox2D unit()
Definition bbox2d.hpp:39
Per-vertex penalty term used by sls_deformation.
Definition authoring.hpp:59
DeformationConstraintType type
penalty type
Definition authoring.hpp:62
Array target
desired height field
Definition authoring.hpp:60
Array weight
per-vertex weight (0 = free)
Definition authoring.hpp:61

Result

See also
apply_gaussian_pushes, DeformationConstraint

◆ stamping()

Array hmap::stamping ( glm::ivec2 shape,
const std::vector< float > & xr,
const std::vector< float > & yr,
const std::vector< float > & zr,
Array kernel,
int kernel_ir,
bool kernel_scale_radius,
bool kernel_scale_amplitude,
StampingBlendMethod blend_method,
std::uint32_t seed,
float k_smoothing = 0.1f,
bool kernel_flip = true,
bool kernel_rotate = false,
const UvRect & uv_rect_array = UvRect::unit() )

Generate a heightmap by stamping a kernel at predefined locations.

This function creates a heightmap by stamping a specified kernel at given x, y, and z coordinates. The kernel can be scaled and manipulated based on the z-coordinates of the stamping points, and can be optionally flipped or rotated. The heightmap is generated by blending the results using the specified blending method. Randomization options are available for kernel manipulation.

Parameters
shapeThe dimensions of the output array (heightmap).
xrA vector of x-coordinates where the kernel is stamped.
yrA vector of y-coordinates where the kernel is stamped.
zrA vector of z-coordinates where the kernel is stamped. This affects the kernel radius and amplitude scaling.
kernelThe kernel to be stamped onto the heightmap.
kernel_irThe radius of the kernel in pixels.
kernel_scale_radiusBoolean flag to scale the kernel radius based on the z-coordinates.
kernel_scale_amplitudeBoolean flag to scale the kernel amplitude based on the z-coordinates.
blend_methodThe method used for blending multiple kernel stamps. Options may include additive, maximum, minimum, etc.
seedRandom seed number for kernel randomization.
k_smoothingSmoothing parameter for the heightmap (e.g., for smooth minimum or maximum blending).
kernel_flipBoolean flag to randomly flip the kernel before stamping. Flipping includes transposing.
kernel_rotateBoolean flag to randomly rotate the kernel before stamping. Rotation can be resource-intensive.
bbox_arrayBounding box for the array domain, defining the spatial extent of the heightmap.
Returns
Array The generated heightmap with kernel stamps applied at the specified locations.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
int seed = 1;
// kernel to be stamped
glm::ivec2 shape_kernel = {64, 64};
hmap::Array kernel = hmap::gabor(shape_kernel, 8.f, 15.f);
// generate stamping locations
size_t n = 50;
hmap::Cloud cloud = hmap::random_cloud(n, seed);
// eventually stamp...
cloud.get_x(),
cloud.get_y(),
cloud.get_values(),
kernel,
32, // kernel radius in pixels
true, // scale ampl
true, // scale radius
++seed,
true, // flip
true); // rotate
// export points to a cloud to generate a png file
cloud.to_array(c);
z.infos();
c.to_png("ex_stamping0.png", hmap::Cmap::INFERNO);
kernel.to_png("ex_stamping1.png", hmap::Cmap::INFERNO);
z.to_png("ex_stamping2.png", hmap::Cmap::INFERNO);
}
std::vector< float > get_values() const
Get the values assigned to the points in the cloud.
Definition cloud.cpp:219
void to_array(Array &array, const BBox2D &bbox=BBox2D{}) const
Project the cloud points onto an array.
Definition cloud.cpp:744
std::vector< float > get_x() const
Get the x coordinates of the points in the cloud.
Definition cloud.cpp:250
std::vector< float > get_y() const
Get the y coordinates of the points in the cloud.
Definition cloud.cpp:271
@ MAXIMUM
maximum
Definition authoring.hpp:19
Cloud random_cloud(size_t count, std::uint32_t seed, const PointSamplingMethod &method=PointSamplingMethod::RND_LHS, const BBox2D &bbox=BBox2D{})
Generates a random cloud of points within a bounding box.
Definition cloud.cpp:889
Array stamping(glm::ivec2 shape, const std::vector< float > &xr, const std::vector< float > &yr, const std::vector< float > &zr, Array kernel, int kernel_ir, bool kernel_scale_radius, bool kernel_scale_amplitude, StampingBlendMethod blend_method, std::uint32_t seed, float k_smoothing=0.1f, bool kernel_flip=true, bool kernel_rotate=false, const UvRect &uv_rect_array=UvRect::unit())
Generate a heightmap by stamping a kernel at predefined locations.
Definition stamping.cpp:22
Array gabor(glm::ivec2 shape, float kw, float angle, bool quad_phase_shift=false)
Generates a Gabor kernel of the specified shape.
Definition kernels.cpp:294

Result

See also
other_related_functions

◆ blend_exclusion()

Array hmap::blend_exclusion ( const Array & array1,
const Array & array2 )

Return the 'exclusion' blending of two arrays.

The exclusion blend mode creates a blend that is similar to the difference blend mode but with lower contrast. It produces an effect that is often used in image editing for special effects. For more details, see https://en.wikipedia.org/wiki/Blend_modes.

Warning
Array values are expected to be in the range [0, 1].
Parameters
array1First input array.
array2Second input array.
Returns
Array Resulting array after applying the exclusion blend mode.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {128, 128};
int seed = 1;
shape,
{2.f, 2.f},
seed);
shape,
{4.f, 4.f},
seed + 1);
auto z_exclusion = hmap::blend_exclusion(z1, z2);
auto z_negate = hmap::blend_negate(z1, z2);
auto z_overlay = hmap::blend_overlay(z1, z2);
auto z_soft = hmap::blend_soft(z1, z2);
auto z_gradients = hmap::blend_gradients(z1, z2);
hmap::export_banner_png("ex_blend0.png",
{z1, z2, z_exclusion},
hmap::export_banner_png("ex_blend1.png",
{z1, z2, z_negate},
hmap::export_banner_png("ex_blend2.png",
{z1, z2, z_overlay},
hmap::export_banner_png("ex_blend3.png",
{z1, z2, z_soft},
hmap::export_banner_png("ex_blend4.png",
{z1, z2, z_gradients},
}
Array blend_negate(const Array &array1, const Array &array2)
Return the 'negate' blending of two arrays.
Definition blending.cpp:50
Array blend_overlay(const Array &array1, const Array &array2)
Return the 'overlay' blending of two arrays.
Definition blending.cpp:68
Array blend_soft(const Array &array1, const Array &array2)
Return the 'soft' blending of two arrays.
Definition blending.cpp:86
Array blend_exclusion(const Array &array1, const Array &array2)
Return the 'exclusion' blending of two arrays.
Definition blending.cpp:23
@ VIRIDIS
Definition colormaps.hpp:95
Array blend_gradients(const Array &array1, const Array &array2, int ir=4)
Return the blending of two arrays based on their gradients.
Definition blending.cpp:33

Result

See also
blend_exclusion, blend_negate, blend_overlay, blend_soft

◆ blend_gradients()

Array hmap::blend_gradients ( const Array & array1,
const Array & array2,
int ir = 4 )

Return the blending of two arrays based on their gradients.

This function blends two arrays by considering their gradients, which can be useful for producing smooth transitions between the arrays based on their directional changes.

Parameters
array1First input array.
array2Second input array.
irFiltering radius in pixels.
Returns
Array Resulting array after blending based on gradients.

◆ blend_negate()

Array hmap::blend_negate ( const Array & array1,
const Array & array2 )

Return the 'negate' blending of two arrays.

The negate blend mode inverts the colors of one of the arrays relative to the other. It creates a high-contrast effect that can be useful for emphasizing differences between two arrays.

Parameters
array1First input array.
array2Second input array.
Returns
Array Resulting array after applying the negate blend mode.
See also
blend_exclusion, blend_negate, blend_overlay, blend_soft

◆ blend_overlay()

Array hmap::blend_overlay ( const Array & array1,
const Array & array2 )

Return the 'overlay' blending of two arrays.

The overlay blend mode combines the colors of two arrays in a way that enhances contrast and emphasizes details.

Warning
Array values are expected to be in the range [0, 1].
Parameters
array1First input array.
array2Second input array.
Returns
Array Resulting array after applying the overlay blend mode.
See also
blend_exclusion, blend_negate, blend_overlay, blend_soft

◆ blend_soft()

Array hmap::blend_soft ( const Array & array1,
const Array & array2 )

Return the 'soft' blending of two arrays.

The soft blend mode applies a soft light effect to the blending of two arrays, based on the soft light mode described in Pegtop soft light mode. It creates a subtle blend with reduced contrast.

Warning
Array values are expected to be in the range [0, 1].
Parameters
array1First input array.
array2Second input array.
Returns
Array Resulting array after applying the soft light blend mode.
See also
blend_exclusion, blend_negate, blend_overlay, blend_soft

◆ blend_power_law() [1/2]

Array hmap::blend_power_law ( const std::vector< const Array * > & arrays,
float alpha = 0.f )

Return the power law blending of a set of arrays.

Blends two (or more) arrays using power law averaging:

\[f_\text{blend} = \frac{\sum_i f_i^{\alpha+1}}{\sum_i f_i^\alpha} \]

The behavior varies with the bias \(\alpha\) from a simple average of the heights at each node when \(\alpha=0\), approaching \(\max(f_i)\) as \(\alpha \to \infty\).

Parameters
arraysArray references to blend.
alphaPower law exponent (default: 0.0).
Returns
Array Resulting array after power law blending.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {128, 128};
int seed = 1;
shape,
{2.f, 2.f},
seed);
shape,
{4.f, 4.f},
seed + 1);
auto z_alpha0 = hmap::blend_power_law(z1, z2, 0.f);
auto z_alpha1 = hmap::blend_power_law(z1, z2, 1.f);
auto z_alpha4 = hmap::blend_power_law(z1, z2, 4.f);
auto z_alpha16 = hmap::blend_power_law(z1, z2, 16.f);
hmap::export_banner_png("ex_blend_power_law0.png",
{z1, z2, z_alpha0},
hmap::export_banner_png("ex_blend_power_law1.png",
{z1, z2, z_alpha1},
hmap::export_banner_png("ex_blend_power_law2.png",
{z1, z2, z_alpha4},
hmap::export_banner_png("ex_blend_power_law3.png",
{z1, z2, z_alpha16},
}
Array blend_power_law(const std::vector< const Array * > &arrays, float alpha=0.f)
Return the power law blending of a set of arrays.
Definition blending.cpp:97

Result

◆ blend_power_law() [2/2]

Array hmap::blend_power_law ( const Array & array1,
const Array & array2,
float alpha = 0.f )

Return the power law blending of two arrays.

Parameters
array1First input array.
array2Second input array.
alphaPower law exponent (default: 0.0).
Returns
Array Resulting array after power law blending.

◆ mixer()

Array hmap::mixer ( const Array & t,
const std::vector< const Array * > & arrays,
float gain_factor = 1.f )

Return the mixing of a set of arrays based on a parameter t.

This function mixes a set of arrays based on a mixing coefficient t that determines the contribution of each array. The parameter t should be in the range [0, 1], where t represents the blending ratio.

Warning
Values of array t are expected to be in the range [0, 1].
Parameters
tMixing coefficient, in the range [0, 1].
arraysReferences to the input arrays to be mixed.
Returns
Array Resulting array after mixing.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {128, 128};
int seed = 1;
shape,
{8.f, 8.f},
seed);
shape,
{4.f, 4.f},
seed + 1);
hmap::Array z3 = hmap::white(shape, 0.f, 1.f, seed + 2);
shape,
{2.f, 2.f},
seed + 3); // mixer
auto zm = hmap::mixer(t, {&z1, &z2, &z3});
hmap::export_banner_png("ex_mixer.png",
{t, z1, z2, z3, zm},
}
Array white(glm::ivec2 shape, float a, float b, std::uint32_t seed)
Return an array filled with white noise.
Definition white.cpp:14
Array mixer(const Array &t, const std::vector< const Array * > &arrays, float gain_factor=1.f)
Return the mixing of a set of arrays based on a parameter t.
Definition blending.cpp:136

Result

◆ transfer()

Array hmap::transfer ( const Array & source,
const Array & target,
int ir,
float amplitude,
bool target_prefiltering = false )

Transfers spatial details from a source array onto a target array.

This function applies a high-pass spatial filter to the source array (using a smoothing pulse of radius ir) to extract its high-frequency content. That content is then scaled by amplitude and blended with the target array. Optionally, the target can be prefiltered before blending.

The result is a new array that combines the base structure of target with the high-frequency details from source.

Parameters
sourceThe input array providing high-frequency details.
targetThe input array providing the base structure.
irRadius (in pixels or samples) for the smoothing filter used to separate low/high frequencies.
amplitudeScaling factor applied to the high-frequency content extracted from source.
target_prefilteringIf true, target is smoothed before blending to better integrate with the transferred details.
Returns
A new Array containing the target data enhanced by the source's high-frequency information.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
shape,
res,
seed++);
hmap::Array target = hmap::noise(hmap::NoiseType::PERLIN, shape, res, seed);
// take details of source and transfer them to target
int ir = 16;
float amplitude = 2.f;
hmap::Array out1 = hmap::transfer(source, target, ir, amplitude);
hmap::Array out2 = hmap::gpu::transfer(source, target, ir, amplitude);
hmap::export_banner_png("ex_transfer.png",
{source, target, out1, out2},
true);
}
Array transfer(const Array &source, const Array &target, int ir, float amplitude, bool target_prefiltering=false)
See hmap::transfer.
Definition blending_gpu.cpp:123
Array transfer(const Array &source, const Array &target, int ir, float amplitude, bool target_prefiltering=false)
Transfers spatial details from a source array onto a target array.
Definition blending.cpp:188
@ MAGMA
Definition colormaps.hpp:89

Result

◆ blend_terrains() [1/2]

void hmap::blend_terrains ( Array & lower,
const CoordFrame & frame_lower,
const Array & upper,
const CoordFrame & frame_upper,
TerrainBlendMode mode,
float param = 0.2f )

Blend an upper terrain onto a lower terrain in-place, taking their CoordFrame transforms into account.

Parameters
lowerLower (base) terrain array, modified in-place.
frame_lowerCoordinate frame of the lower terrain.
upperUpper (overlay) terrain array.
frame_upperCoordinate frame of the upper terrain.
modeBlending mode.
paramMode-specific parameter (smoothness k for MIN_SMOOTH / MAX_SMOOTH, normalized feathering width in (0, 0.5] for DISTANCE).

◆ blend_terrains() [2/2]

void hmap::blend_terrains ( VirtualArray & lower,
const CoordFrame & frame_lower,
const VirtualArray & upper,
const CoordFrame & frame_upper,
TerrainBlendMode mode,
float param = 0.2f,
const ComputeMode & cm = ComputeMode{} )

Blend an upper VirtualArray terrain onto a lower VirtualArray terrain in-place, taking their CoordFrame transforms into account.

Parameters
lowerLower (base) VirtualArray, modified in-place.
frame_lowerCoordinate frame of the lower terrain.
upperUpper (overlay) VirtualArray.
frame_upperCoordinate frame of the upper terrain.
modeBlending mode.
paramMode-specific parameter (smoothness k for MIN_SMOOTH / MAX_SMOOTH, normalized feathering width in (0, 0.5] for DISTANCE).
cmCompute mode for tile execution.

◆ blend_terrains_height() [1/2]

void hmap::blend_terrains_height ( Array & lower,
const CoordFrame & frame_lower,
const Array & upper,
const CoordFrame & frame_upper,
float feather_width = 0.2f,
float height_offset = 0.f,
float height_range = 0.2f )

Height-aware terrain blending for Array inputs.

◆ blend_terrains_height() [2/2]

void hmap::blend_terrains_height ( VirtualArray & lower,
const CoordFrame & frame_lower,
const VirtualArray & upper,
const CoordFrame & frame_upper,
float feather_width = 0.2f,
float height_offset = 0.f,
float height_range = 0.2f,
const ComputeMode & cm = ComputeMode{} )

Height-aware terrain blending for VirtualArray inputs.

◆ blend_terrains_multiscale() [1/2]

void hmap::blend_terrains_multiscale ( Array & lower,
const CoordFrame & frame_lower,
const Array & upper,
const CoordFrame & frame_upper,
float feather_width = 0.25f,
int n_levels = 3,
int base_radius = 16,
float detail_gain = 1.f )

Multiscale (frequency-band) terrain blending for Array inputs.

◆ blend_terrains_multiscale() [2/2]

void hmap::blend_terrains_multiscale ( VirtualArray & lower,
const CoordFrame & frame_lower,
const VirtualArray & upper,
const CoordFrame & frame_upper,
float feather_width = 0.25f,
int n_levels = 3,
int base_radius = 16,
float detail_gain = 1.f,
int coarse_size = 128,
const ComputeMode & cm = ComputeMode{} )

Multiscale (frequency-band) terrain blending for VirtualArray inputs using a coarse global proxy for low-frequency bands and tile-local detail blending with halo synchronization.

◆ blend_terrains_poisson() [1/2]

void hmap::blend_terrains_poisson ( Array & lower,
const CoordFrame & frame_lower,
const Array & upper,
const CoordFrame & frame_upper,
int iterations = 400,
float feather_width = 0.15f,
bool mixed_gradients = true )

Poisson / gradient-domain terrain blending for Array inputs.

◆ blend_terrains_poisson() [2/2]

void hmap::blend_terrains_poisson ( VirtualArray & lower,
const CoordFrame & frame_lower,
const VirtualArray & upper,
const CoordFrame & frame_upper,
int iterations = 400,
float feather_width = 0.15f,
bool mixed_gradients = true,
int coarse_size = 128,
int sync_interval = 25,
const ComputeMode & cm = ComputeMode{} )

Poisson / gradient-domain terrain blending for VirtualArray inputs using a two-level coarse-proxy + tile-local Red-Black SOR solver with halo synchronization.

◆ blend_terrains_seamless() [1/2]

void hmap::blend_terrains_seamless ( Array & lower,
const CoordFrame & frame_lower,
const Array & upper,
const CoordFrame & frame_upper,
float feather_width = 0.2f,
int boundary_samples = 64 )

Seamless boundary blending (harmonic MVC membrane) for Array inputs.

◆ blend_terrains_seamless() [2/2]

void hmap::blend_terrains_seamless ( VirtualArray & lower,
const CoordFrame & frame_lower,
const VirtualArray & upper,
const CoordFrame & frame_upper,
float feather_width = 0.2f,
int boundary_samples = 64,
const ComputeMode & cm = ComputeMode{} )

Seamless boundary blending (harmonic MVC membrane) for VirtualArray inputs.

◆ blend_terrains_slope() [1/2]

void hmap::blend_terrains_slope ( Array & lower,
const CoordFrame & frame_lower,
const Array & upper,
const CoordFrame & frame_upper,
float feather_width = 0.2f,
float slope_scale = 0.1f,
int ir_slope = 2 )

Slope-aware terrain blending for Array inputs.

◆ blend_terrains_slope() [2/2]

void hmap::blend_terrains_slope ( VirtualArray & lower,
const CoordFrame & frame_lower,
const VirtualArray & upper,
const CoordFrame & frame_upper,
float feather_width = 0.2f,
float slope_scale = 0.1f,
int ir_slope = 2,
const ComputeMode & cm = ComputeMode{} )

Slope-aware terrain blending for VirtualArray inputs.

◆ extrapolate_borders()

void hmap::extrapolate_borders ( Array & array,
int nbuffer = 1,
float sigma = 0.f,
float vmin = -FLT_MAX )

Performs linear extrapolation of values at the borders of an array (e.g., i = 0, j = 0, etc.) based on the inner values of the array.

This function modifies the borders of the input array by applying a linear extrapolation method, which uses the values inside the array to estimate and fill in the border values. The extrapolation is influenced by a relaxation coefficient (sigma) and a buffer depth (nbuffer), which determines how many layers of the border are extrapolated.

Parameters
arrayReference to the input array whose borders need extrapolation.
nbufferOptional parameter specifying the buffer depth, i.e., the number of layers at the border to extrapolate. Default is 1.
sigmaOptional relaxation coefficient that adjusts the influence of inner values on the extrapolated border values. Default is 0.0.
See also
fill_borders()

◆ falloff()

void hmap::falloff ( Array & array,
float strength = 1.f,
DistanceFunction dist_fct = DistanceFunction::EUCLIDIAN,
const Array * p_noise = nullptr,
const UvRect & uv_rect = UvRect::unit() )

Applies a falloff effect to the input array based on distance.

This function modifies the elements of the input array by applying a falloff effect, which decreases the values based on their distance from a central point or area. The strength of the falloff, the type of distance function used, and optional noise can be specified.

Parameters
arrayReference to the array that will be modified by the falloff effect.
strengthThe strength of the falloff effect. A higher value results in a stronger falloff. Default is 1.0f.
dist_fctThe distance function to be used for calculating the falloff. Options include Euclidian and others, with DistanceFunction::EUCLIDIAN as the default.
p_noiseOptional pointer to an array that provides noise to be added to the falloff effect. If nullptr (default), no noise is added.
bboxA 4D vector representing the bounding box within which the falloff effect is applied. The default is {0.f, 1.f, 0.f, 1.f}.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
float sigma = 1.f;
auto z1 = z;
auto z2 = z;
auto z3 = z;
auto z4 = z;
hmap::export_banner_png("ex_falloff.png",
{z, z1, z2, z3, z4},
}
void falloff(Array &array, float strength=1.f, DistanceFunction dist_fct=DistanceFunction::EUCLIDIAN, const Array *p_noise=nullptr, const UvRect &uv_rect=UvRect::unit())
Applies a falloff effect to the input array based on distance.
Definition boundary.cpp:91
@ CHEBYSHEV
Chebyshev.
Definition distance_functions.hpp:21
@ EUCLISHEV
Euclidian and Chebyshev mix.
Definition distance_functions.hpp:23
@ EUCLIDIAN
Euclidian.
Definition distance_functions.hpp:22
@ MANHATTAN
Manhattan.
Definition distance_functions.hpp:24

Result

◆ fill_borders() [1/2]

void hmap::fill_borders ( Array & array)

Fills the border values of an array (e.g., i = 0, j = 0, etc.) based on the values of the first neighboring cells.

This function modifies the border values of the input array by copying values from their immediate neighbors. The operation ensures that border values are consistent with their adjacent cells, typically used to prepare the array for further processing.

Parameters
arrayReference to the input array whose borders need to be filled.
See also
extrapolate_borders()

◆ fill_borders() [2/2]

void hmap::fill_borders ( Array & array,
int nbuffer )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ generate_buffered_array()

Array hmap::generate_buffered_array ( const Array & array,
glm::ivec4 buffers,
bool zero_padding = false )

Creates and returns a new array with additional buffer zones at the boundaries, where the buffer values are filled either by symmetry or by zero-padding.

This function takes an input array and generates a new array with extra layers (buffers) added to its boundaries. The size of these buffer zones is specified by the buffers parameter, and the values within these buffers can be filled either by reflecting the values at the boundaries (symmetry) or by padding with zeros.

Parameters
arrayReference to the input array.
buffersA vector specifying the buffer sizes for the east, west, south, and north boundaries.
zero_paddingOptional boolean flag to use zero-padding instead of symmetry for filling the buffer values. Default is false.
Returns
Array A new array with buffers added at the boundaries.

◆ make_periodic()

void hmap::make_periodic ( Array & array,
int nbuffer,
const PeriodicityType & periodicity_type = PeriodicityType::PERIODICITY_XY )

Adjusts the input array to be periodic in both directions by transitioning smoothly at the boundaries.

This function modifies the input array so that the values at the boundaries transition smoothly, making the array periodic in both the horizontal and vertical directions. The width of the transition zone at the boundaries is controlled by the nbuffer parameter.

Parameters
arrayReference to the input array to be made periodic.
nbufferThe width of the transition zone at the boundaries.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
int nbuffer = 64;
auto zp = z;
hmap::make_periodic(zp, nbuffer);
auto zp_x = z;
auto zp_y = z;
// do some tiling to check periodicity
auto zt = zp;
zt = hstack(zt, zt);
zt = vstack(zt, zt);
hmap::export_banner_png("ex_make_periodic0.png",
{z, zp, zp_x, zp_y},
zt.to_png("ex_make_periodic1.png", hmap::Cmap::VIRIDIS);
}
void make_periodic(Array &array, int nbuffer, const PeriodicityType &periodicity_type=PeriodicityType::PERIODICITY_XY)
Adjusts the input array to be periodic in both directions by transitioning smoothly at the boundaries...
Definition boundary.cpp:227
@ PERIODICITY_X
Periodic only along the X axis.
Definition boundary.hpp:32
@ PERIODICITY_Y
Periodic only along the Y axis.
Definition boundary.hpp:33
Array vstack(const Array &array1, const Array &array2)
Vertically stack two arrays.
Definition operator.cpp:118
Array hstack(const Array &array1, const Array &array2)
Horizontally stack two arrays side by side.
Definition operator.cpp:79

Result

◆ make_periodic_stitching()

Array hmap::make_periodic_stitching ( const Array & array,
float overlap )

Creates a periodic array in both directions using a stitching operation that minimizes errors at the boundaries.

This function generates a new array that is periodic in both directions by applying a stitching operation at the boundaries. The stitching process aims to minimize discrepancies, creating a seamless transition between the edges of the array. The overlap parameter determines the extent of the overlap during the stitching, based on the half-size of the domain. If overlap is set to 1, the transition spans the entire domain.

Parameters
arrayReference to the input array to be made periodic.
overlapA float value representing the overlap based on the domain's half-size. An overlap of 1 means the transition spans the whole domain.
Returns
Array A new array that is periodic in both directions with minimized boundary errors.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
float overlap = 0.5f;
auto zp = hmap::make_periodic_stitching(z, overlap);
// do some tiling to check periodicity
auto zt = zp;
zt = hstack(zt, zt);
zt = vstack(zt, zt);
zt.infos();
hmap::export_banner_png("ex_make_periodic_stitching0.png",
{z, zp},
zt.to_png("ex_make_periodic_stitching1.png", hmap::Cmap::INFERNO);
auto zt_grad = hmap::gradient_norm(zt);
zt_grad.to_png("ex_make_periodic_stitching_grad.png", hmap::Cmap::INFERNO);
}
Array make_periodic_stitching(const Array &array, float overlap)
Creates a periodic array in both directions using a stitching operation that minimizes errors at the ...
Definition boundary.cpp:298
Array gradient_norm(const Array &array, Array *p_dx=nullptr, Array *p_dy=nullptr)
Compute the gradient norm of a 2D array.
Definition gradient.cpp:131

Result

◆ make_periodic_tiling()

Array hmap::make_periodic_tiling ( const Array & array,
float overlap,
glm::ivec2 tiling )

Creates a tiled, periodic array by applying a transition with overlap in both directions.

This function generates a new array that is periodic and tiled according to the specified tiling dimensions. The periodicity is achieved by applying a transition at the boundaries, where the extent of overlap is determined by the overlap parameter. The tiling parameter specifies the number of tiles in the horizontal and vertical directions.

Parameters
arrayReference to the input array to be tiled and made periodic.
overlapA float value representing the overlap based on the domain's half-size. If overlap is 1, the transition spans the entire domain on both sides.
tilingA 2D vector specifying the number of tiles in the horizontal and vertical directions.
Returns
Array A new tiled array that is periodic in both directions.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {2.f, 2.f};
int seed = 1;
float overlap = 0.5f;
glm::ivec2 tiling = {4, 3};
auto zp = hmap::make_periodic_tiling(z, overlap, tiling);
hmap::export_banner_png("ex_make_periodic_tiling.png",
{z, zp},
}
Array make_periodic_tiling(const Array &array, float overlap, glm::ivec2 tiling)
Creates a tiled, periodic array by applying a transition with overlap in both directions.
Definition boundary.cpp:389

Result

◆ pick_boundary_cell()

glm::ivec2 hmap::pick_boundary_cell ( const Array & z,
DomainBoundary boundary,
std::uint32_t seed,
bool favor_boundary_center = true,
bool favor_lower_elevation = true,
bool favor_sinks = true )

Picks a boundary cell using weighted random selection.

Selects a cell on the specified boundary, where each candidate is assigned a weight. Higher weights increase the probability of selection.

Optional weighting factors:

  • favor_boundary_center: favors cells near the boundary center.
  • favor_lower_elevation: favors lower values in z (normalized).
  • favor_sinks: favors local minima (cells <= neighbors).

Weights are combined multiplicatively. Selection is deterministic given seed.

Parameters
zInput 2D scalar field.
boundaryBoundary to sample from.
seedRandom seed.
favor_boundary_centerEnable center bias.
favor_lower_elevationEnable low-value bias.
favor_sinksEnable sink bias.
Returns
Selected boundary cell coordinates.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 0;
hmap::Array count(shape);
int nsamples = 1000;
for (int it = 0; it < nsamples; ++it)
{
for (const auto &b : {hmap::DomainBoundary::BOUNDARY_LEFT,
{
glm::ivec2 p = hmap::pick_boundary_cell(z, b, ++seed);
count(p) += 1;
}
}
count = hmap::dilation(count, 8); // to be able to see something
hmap::remap(count);
hmap::export_banner_png("ex_pick_boundary_cell.png",
{z, count},
}
@ BOUNDARY_TOP
j = ny - 1
Definition boundary.hpp:47
@ BOUNDARY_LEFT
i = 0
Definition boundary.hpp:45
@ BOUNDARY_BOTTOM
j = 0
Definition boundary.hpp:48
@ BOUNDARY_RIGHT
i = nx - 1
Definition boundary.hpp:46
glm::ivec2 pick_boundary_cell(const Array &z, DomainBoundary boundary, std::uint32_t seed, bool favor_boundary_center=true, bool favor_lower_elevation=true, bool favor_sinks=true)
Picks a boundary cell using weighted random selection.
Definition pick_boundary_cell.cpp:17

Result

◆ set_borders() [1/4]

void hmap::set_borders ( Array & array,
glm::vec4 border_values,
glm::ivec4 buffer_sizes )

Enforces specific values at the boundaries of the array.

This function sets the values at the borders of the input array to specified values for each side (east, west, south, and north). The size of the buffer zone at each border can also be defined, allowing precise control over how much of the boundary is modified.

Parameters
arrayReference to the input array whose borders are to be modified.
border_valuesA vector specifying the values to set at the east, west, south, and north borders.
buffer_sizesA vector specifying the size of the buffer zones at the east, west, south, and north borders.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
float value = 0.f;
int nbuffer = 100;
hmap::set_borders(z, value, nbuffer);
z.to_png("ex_set_borders.png", hmap::Cmap::TERRAIN, true);
}
void set_borders(Array &array, glm::vec4 border_values, glm::ivec4 buffer_sizes)
Enforces specific values at the boundaries of the array.
Definition set_borders.cpp:16

Result

◆ set_borders() [2/4]

void hmap::set_borders ( Array & array,
glm::vec4 border_values,
glm::vec4 buffer_sizes,
const UvRect & uv_rect = UvRect::unit() )

Enforces specific values at the domain boundaries based on distance.

This overloaded function sets values near the boundaries of the unit square domain [0, 1] x [0, 1] based on continuous distances. The array corresponds to the specified bounding box bbox.

Parameters
arrayReference to the input array whose borders are to be modified.
border_valuesA vector specifying the values to set at the west, east, south, and north borders.
buffer_sizesA vector specifying the buffer distance at the west, east, south, and north borders.
bboxDomain bounding box {xmin, xmax, ymin, ymax}. Default is {0.f, 1.f, 0.f, 1.f}.

◆ set_borders() [3/4]

void hmap::set_borders ( Array & array,
float border_values,
int buffer_sizes )

Enforces a uniform value at all boundaries of the array.

This overloaded function sets the same value at all borders of the input array. The size of the buffer zone at each border can be defined with a single value that applies uniformly to all sides.

Parameters
arrayReference to the input array whose borders are to be modified.
border_valuesThe value to set at all borders.
buffer_sizesThe size of the buffer zone to apply uniformly at all borders.

◆ set_borders() [4/4]

void hmap::set_borders ( Array & array,
float border_values,
float buffer_sizes,
const UvRect & uv_rect = UvRect::unit() )

Enforces a uniform value at all domain boundaries based on distance.

This overloaded function sets the same value at all borders of the unit square domain [0, 1] x [0, 1] based on a continuous buffer distance. The array corresponds to the specified bounding box bbox.

Parameters
arrayReference to the input array whose borders are to be modified.
border_valuesThe value to set at all borders.
buffer_sizesThe buffer distance to apply uniformly at all borders.
bboxDomain bounding box {xmin, xmax, ymin, ymax}. Default is {0.f, 1.f, 0.f, 1.f}.

◆ sym_borders()

void hmap::sym_borders ( Array & array,
glm::ivec4 buffer_sizes )

Fills the values at the domain borders using symmetry over a specified buffer depth.

This function fills the borders of the input array by reflecting the values inside the array symmetrically. The depth of the buffer at each border (east, west, south, north) is specified by the buffer_sizes parameter.

Parameters
arrayReference to the input array whose borders are to be filled using symmetry.
buffer_sizesA vector specifying the buffer sizes at the east, west, south, and north borders.

◆ zeroed_borders()

void hmap::zeroed_borders ( Array & array)

Fills the border values (e.g., i = 0, j = 0, etc.) of the array with zeros.

This function sets all the values at the borders of the input array to zero. It can be used to zero out boundary values, preparing the array for specific computations.

Parameters
arrayReference to the input array whose borders are to be zeroed.
See also
fill_borders()

◆ zeroed_edges()

void hmap::zeroed_edges ( Array & array,
RadialProfile radial_profile = RadialProfile::RP_SMOOTHSTEP,
float profile_param = 0.f,
float amount = 1.f,
DistanceFunction distance = DistanceFunction::EUCLIDIAN,
DistanceFunctionAxis dfa = DistanceFunctionAxis::DFA_XY,
glm::vec2 center = {0.5f, 0.5f},
float radius = 0.5f,
const Array * p_noise_r = nullptr,
const UvRect & uv_rect = UvRect::unit() )

Smoothly attenuates array values toward zero near the domain boundaries.

Applies a radial profile centered at center with the specified radius. The effect can be shaped using radial_profile, profile_param, and an optional noise modulation array.

Parameters
arrayInput/output array.
radial_profileRadial attenuation profile.
profile_paramProfile-specific parameter.
amountEffect strength in [0, 1].
distanceDistance function.
dfaDistance axes used for distance evaluation.
centerProfile center in normalized coordinates.
radiusProfile radius.
p_noise_rOptional modulation array.
bboxDomain bounding box.
#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {4.f, 4.f};
int seed = 0;
auto z1 = z0;
hmap::export_banner_png("ex_zeroed_edges.png",
{z0, z1},
true);
}
void zeroed_edges(Array &array, RadialProfile radial_profile=RadialProfile::RP_SMOOTHSTEP, float profile_param=0.f, float amount=1.f, DistanceFunction distance=DistanceFunction::EUCLIDIAN, DistanceFunctionAxis dfa=DistanceFunctionAxis::DFA_XY, glm::vec2 center={0.5f, 0.5f}, float radius=0.5f, const Array *p_noise_r=nullptr, const UvRect &uv_rect=UvRect::unit())
Smoothly attenuates array values toward zero near the domain boundaries.
Definition zeroed_edges.cpp:18
@ RP_SMOOTHSTEP
Definition profiles.hpp:55

◆ carve_river()

void hmap::carve_river ( Array & z,
const Graph & graph,
float talus,
float outlet_width,
float headwater_width = 0.f,
float width_exponent = 0.5f,
float depth = 0.05f,
float depth_exponent = 0.3f,
std::uint32_t seed = 0,
float talus_noise_ratio = 0.f,
RadialProfile radial_profile = RadialProfile::RP_SMOOTHSTEP_UPPER,
float radial_profile_parameter = 2.f,
Array * p_river_mask = nullptr,
const UvRect & uv_rect = UvRect::unit() )

Carves a continuous river network into a heightmap along a directed flow Graph.

A triangular riverbed with a given slope (talus) is generated from the channel bottom using expand_talus, and merged with the original heightmap using the network signed distance field (SDF), scaling channel width and depth with flow accumulation.

Parameters
[in,out]zTarget heightmap to carve in-place.
[in]graphInput flow network Graph.
[in]talusSlope of the triangular riverbed valley walls.
[in]outlet_widthMaximum channel influence width at downstream outlet(s).
[in]headwater_widthMinimum channel influence width at headwaters (default: 0).
[in]width_exponentScaling exponent for channel width with flow accumulation (default: 0.5).
[in]depthIncision depth below graph elevation for river bottom (default: 0.05).
[in]depth_exponentScaling exponent for depth scaling with flow accumulation (default: 0.3).
[in]seedRandom seed for expand_talus (default: 0).
[in]talus_noise_ratioRoughness / perturbation ratio for valley expansion (default: 0).
[in]radial_profileBlending profile for SDF transition (default: RP_SMOOTHSTEP_UPPER).
[in]radial_profile_parameterShaping parameter for the radial profile (default: 2.0).
[out]p_river_maskOptional output mask in [0, 1] of carved river channel.
[in]bboxDomain bounding box.

◆ dig_path()

void hmap::dig_path ( Array & z,
Path & path,
int width = 1,
int decay = 2,
int flattening_radius = 16,
bool force_downhill = false,
const UvRect & uv_rect = UvRect::unit(),
float depth = 0.f )

Dig a path on a heightmap.

This function modifies a heightmap array by "digging" a path into it based on the provided path. The path is represented by a Path object, and the function adjusts the height values in the z array to create the appearance of a dug path. The width, border decay, and flattening radius parameters control the characteristics of the dig. Optionally, the path can be forced to have a monotonically decreasing elevation.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
hmap::BBox2D bbox = {1.f, 2.f, -0.5f, 0.5f};
seed,
hmap::BBox2D({1.1f, 1.9f, -0.4f, 0.4f}));
path.set_closed(false);
path.reorder_nns();
path = hmap::dijkstra(path,
z,
hmap::UvRect(1.f, 2.f, -0.5f, 0.5f),
0,
0.9f,
1.f);
auto z1 = hmap::Array(shape);
path.to_array(z1, bbox);
auto z2 = z;
int width = 1; // pixels
int decay = 2;
int flattening_radius = 16;
bool force_downhill = false;
path,
width,
decay,
flattening_radius,
force_downhill,
hmap::UvRect(1.f, 2.f, -0.5f, 0.5f));
auto z3 = z;
force_downhill = true;
path,
width,
decay,
flattening_radius,
force_downhill,
hmap::UvRect(1.f, 2.f, -0.5f, 0.5f));
hmap::export_banner_png("ex_dig_path.png",
{z, z1, z2, z3},
true);
}
Path dijkstra(const Path &path, const Array &array, const UvRect &uv_rect, float elevation_ratio=0.f, float distance_exponent=0.5f, float upward_penalization=0.1f, Array *p_mask_nogo=nullptr)
Divide the path by adding points based on the lowest elevation difference between each pair of edge e...
Definition dijsktra_path.cpp:18
void dig_path(Array &z, Path &path, int width=1, int decay=2, int flattening_radius=16, bool force_downhill=false, const UvRect &uv_rect=UvRect::unit(), float depth=0.f)
Dig a path on a heightmap.
Definition dig_path.cpp:19
Axis-aligned rectangle in normalized [0, 1]^2 domain/UV space.
Definition uv_rect.hpp:30

Result

Parameters
zInput array representing the heightmap to be modified.
pathThe path to be dug into the heightmap, with coordinates with respect to a unit-square. The path will be processed to create the dig effect.
widthRadius of the path width in pixels. This determines how wide the dug path will be.
decayRadius of the path border decay in pixels. This controls how quickly the effect of the path fades out towards the edges.
flattening_radiusRadius used to flatten the elevation of the path, creating a smooth transition. This is measured in pixels.
force_downhillIf true, the path's elevation will be forced to decrease monotonically, creating a downhill effect.
bboxBounding box specifying the region of the heightmap to consider for the digging operation. It defines the area where the path is applied.
depthOptional depth parameter to specify the maximum depth of the dig. If not provided, the default depth of 0.f is used.

◆ flatten_around_points() [1/2]

void hmap::flatten_around_points ( Array & z,
const std::vector< float > & xp,
const std::vector< float > & yp,
const std::vector< float > & zp,
const std::vector< float > & radius,
float strength = 1.0f,
RadialProfile radial_profile = RadialProfile::RP_SMOOTHSTEP,
float profile_param = 1.0f,
Array * p_mask = nullptr,
const UvRect & uv_rect = UvRect::unit() )

Flattens a heightmap locally around a set of reference points.

Each point has its own influence radius. For a given cell, only the points whose radius covers the cell are kept, and the target elevation is the average of their elevations weighted by falloff * radius (larger radius, larger influence). The cell is blended toward this target using the sum of the falloffs (clamped to 1), which keeps the transition smooth.

Parameters
[in,out]zHeightmap array to modify in place.
[in]xpPoint x coordinates (in the bounding box).
[in]ypPoint y coordinates (in the bounding box).
[in]zpReference elevations of the points.
[in]radiusInfluence radius of each point.
[in]strengthFlattening strength in [0, 1].
[in]radial_profileRadial profile type used for distance falloff.
[in]profile_paramShape parameter for the radial profile.
[out]p_maskOptional output blending weights.
[in]bboxBounding box of the heightmap.

◆ flatten_around_points() [2/2]

void hmap::flatten_around_points ( Array & z,
const std::vector< float > & xp,
const std::vector< float > & yp,
const std::vector< float > & zp,
float radius = 0.2f,
float strength = 1.0f,
RadialProfile radial_profile = RadialProfile::RP_SMOOTHSTEP,
float profile_param = 1.0f,
Array * p_mask = nullptr,
const UvRect & uv_rect = UvRect::unit() )

Overload of flatten_around_points with a single radius shared by all points.

◆ flatten_around_points_terrain_aware() [1/2]

void hmap::flatten_around_points_terrain_aware ( Array & z,
const std::vector< float > & xp,
const std::vector< float > & yp,
const std::vector< float > & zp,
const std::vector< float > & radius,
float slope_weight = 1.f,
float uphill_weight = 2.f,
float max_height_above = -1.f,
float terrain_follow = 0.5f,
float strength = 1.f,
RadialProfile radial_profile = RadialProfile::RP_SMOOTHSTEP,
float profile_param = 1.f,
Array * p_mask = nullptr,
const UvRect & uv_rect = UvRect::unit() )

Terrain-aware flattening around a set of seed points.

From each seed, a Dijkstra propagation computes an accumulated cost distance over the heightmap. The step cost is the step length multiplied by 1 + slope_weight * slope + uphill_weight * climb / radius, so the flattened region follows valleys and spreads easily over flat areas but is reduced on steep or higher terrain. Cells are reached only while the cost is below the radius and the Euclidean distance is below the radius (the radius is thus a maximum geometric extent) and the elevation is not above the height limit.

The cost distance replaces the Euclidean distance in the radial profile. The target surface is the seed elevation plus a fraction (terrain_follow) of the smoothed terrain relief relative to the seed, so it is not an exact plateau. Contributions of several seeds are combined as in flatten_around_points.

Parameters
[in,out]zHeightmap array to modify in place.
[in]xpSeed x coordinates (in the bounding box).
[in]ypSeed y coordinates.
[in]zpSeed reference elevations.
[in]radiusMaximum geometric extent of each seed (bbox units).
[in]slope_weightPenalty on the local slope (0: ignored).
[in]uphill_weightPenalty on climbing above the seed elevation (0: ignored).
[in]max_height_aboveCells higher than seed elevation + max_height_above are never reached (negative: no limit).
[in]terrain_followAmount of smoothed relief kept in the target surface: 0 gives an exact plateau, 1 keeps the whole relief.
[in]strengthFlattening strength in [0, 1].
[in]radial_profileRadial profile used for the falloff.
[in]profile_paramShape parameter of the radial profile.
[out]p_maskOptional output blending weights.
[in]bboxBounding box of the heightmap.

◆ flatten_around_points_terrain_aware() [2/2]

void hmap::flatten_around_points_terrain_aware ( Array & z,
const std::vector< float > & xp,
const std::vector< float > & yp,
const std::vector< float > & zp,
float radius,
float slope_weight = 1.f,
float uphill_weight = 2.f,
float max_height_above = -1.f,
float terrain_follow = 0.5f,
float strength = 1.f,
RadialProfile radial_profile = RadialProfile::RP_SMOOTHSTEP,
float profile_param = 1.f,
Array * p_mask = nullptr,
const UvRect & uv_rect = UvRect::unit() )

Overload with a single radius shared by all seeds.

◆ flatbed_carve() [1/2]

void hmap::flatbed_carve ( Array & z,
const Path & path,
float bottom_extent = 32.f,
float vmin = 0.1f,
float depth = 0.05f,
float falloff_distance = 128.f,
float outer_slope = 0.1f,
bool preserve_bedshape = true,
RadialProfile radial_profile = RadialProfile::RP_GAIN,
float radial_profile_parameter = 2.f,
Array * p_falloff_mask = nullptr,
const Array * p_noise_r = nullptr,
const UvRect & uv_rect = UvRect::unit() )

Blends a flatbed carve into an existing heightmap.

Carves and blends a flatbed shape along a path into the provided array, using a smooth falloff mask.

Parameters
zHeightmap to modify in place.
pathPath defining the bed centerline.
bottom_extentRadius of the flatbed region.
vminBase height value.
depthBed depth.
falloff_distanceFalloff width outside the bed.
outer_slopeLinear slope beyond the bed.
preserve_bedshapePreserve relative bed shape under radial noise.
radial_profileRadial profile type.
radial_profile_parameterShape parameter for the profile.
p_falloff_maskOptional output falloff mask.
p_noise_rOptional radial noise.
bboxWorld-space bounding box.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {2.f, 2.f};
int seed = 0;
shape,
{16.f, 16.f},
++seed,
8,
0.1f);
hmap::remap(dr, -0.2f, 0.9f);
// --- generate path
z,
path = hmap::decimate_vw(path, 20);
path = hmap::bspline(path);
hmap::Array zp = hmap::Array(shape);
path.to_array(zp);
// --- carve
float bottom_extent = int(shape.x / 32);
float vmin = 0.1f;
float depth = 0.05f;
float falloff_distance = 4 * bottom_extent;
float outer_slope = 0.1f;
bool preserve_bedshape = true;
auto radial_profile = hmap::RadialProfile::RP_GAIN;
float radial_profile_parameter = 2.f;
hmap::Array zf = z;
path,
bottom_extent,
vmin,
depth,
falloff_distance,
outer_slope,
preserve_bedshape,
radial_profile,
radial_profile_parameter,
&mask,
&dr);
hmap::export_banner_png("ex_flatbed_carve.png",
{z, zp, mask, zf},
}
Path bspline(const Path &path, int edge_divisions=10, Path::EdgeDivisionMode edm=Path::EdgeDivisionMode::EDM_PER_EDGE)
Smooth the path using B-Spline curves.
Definition path_functions.cpp:142
@ RP_GAIN
Definition profiles.hpp:52
void flatbed_carve(Array &z, const Path &path, float bottom_extent=32.f, float vmin=0.1f, float depth=0.05f, float falloff_distance=128.f, float outer_slope=0.1f, bool preserve_bedshape=true, RadialProfile radial_profile=RadialProfile::RP_GAIN, float radial_profile_parameter=2.f, Array *p_falloff_mask=nullptr, const Array *p_noise_r=nullptr, const UvRect &uv_rect=UvRect::unit())
Blends a flatbed carve into an existing heightmap.
Definition flatbed_carve.cpp:120
Path decimate_vw(const Path &path, int n_points_target=3)
Simplifies the current path using the Visvalingam-Whyatt algorithm.
Definition path_functions.cpp:206
Path find_cut_path_dijkstra(const Array &z, DomainBoundary start, DomainBoundary end, float dijk_elevation_ratio=0.9f, float dijk_distance_exponent=2.f, float dijk_upward_penalization=100.f, std::uint32_t seed=0, bool favor_boundary_center=true, bool favor_lower_elevation=true, bool favor_sinks=true, bool favor_domain_center=false)
Find a Dijkstra-based cut path between two domain boundaries.
Definition find_cut_path.cpp:17

Result

◆ trench() [1/4]

void hmap::trench ( Array & z,
const Path & path,
float width,
bool enable_width_depth_scaling = true,
bool enable_width_distance_scaling = true,
bool enable_width_curvature_scaling = false,
float curvature_radius_min = 1.f,
float curv_width_ratio_min = 0.5f,
float curv_width_ratio_max = 2.f,
RadialProfile radial_profile = RadialProfile::RP_SMOOTHSTEP_UPPER,
float radial_profile_parameter = 2.f,
ElevationLongitudinalProfile longitudinal_profile = ElevationLongitudinalProfile::ELP_DECREASING,
float elevation_shift = -0.05f,
float shift_ramp_start_ratio = 0.f,
float shift_ramp_end_ratio = 0.f,
float min_slope = 0.001f,
size_t k_neighbors = 8,
const Array * p_noise_r = nullptr,
Array * p_bending_mask = nullptr,
int tile_size = 32,
const UvRect & uv_rect = UvRect::unit() )

Carves a trench along a given path into a heightmap.

This function modifies the input heightmap by carving a trench defined by a polyline path. The trench shape is controlled both longitudinally (along the path) and radially (across the path). Optional noise and scaling can be applied to introduce variations in width and depth.

Parameters
[in,out]zHeightmap to modify (2D array of elevations).
[in]pathPolyline defining the trench centerline.
[in]widthBase width of the trench.
[in]enable_width_depth_scalingIf true, modulates trench width based on local elevation difference.
[in]radial_profileType of radial profile used to shape the trench cross-section.
[in]radial_profile_parameterParameter controlling the radial profile shape.
[in]longitudinal_profileControls how elevation evolves along the path (e.g., flat, increasing, decreasing).
[in]elevation_shiftGlobal elevation offset applied along the path.
[in]shift_ramp_start_ratioRatio of the path length used to smoothly ramp the elevation shift at the beginning.
[in]shift_ramp_end_ratioRatio of the path length used to smoothly ramp the elevation shift at the end.
[in]min_slopeMinimum slope enforced between consecutive path points when monotonicity is required.
[in]k_neighborsNumber of nearest neighbors used for interpolation.
[in]p_noise_rOptional pointer to a noise array used to locally perturb trench width (can be nullptr).
[out]p_bending_maskOptional output mask representing blending weights (can be nullptr).
[in]tile_sizeTile size in pixels for spatial BVH partitioning (default: 32). A recommended rule of thumb is to choose tile_size on the order of the trench width in pixels: tile_size ~ clamp(width / dx, 16, 128).
[in]bboxBounding box of the domain as (xmin, xmax, ymin, ymax).
Warning
The function assumes that elevation_shift is non-zero when width-depth scaling is enabled, to avoid division by zero.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
shape = {1024, 1024};
glm::vec2 kw = {2.f, 2.f};
int seed = 0;
// --- create path
z1,
seed);
path = hmap::decimate_vw(path, 30);
path = hmap::bspline(path, 50);
hmap::Array z2 = hmap::Array(shape);
path.to_array(z2);
// path.smooth(10);
// hmap::Array z2 = hmap::Array(shape);
path.to_array(z2);
// --- trenchs
auto z3 = z1;
shape,
{8.f, 8.f},
++seed,
8,
0.f);
float width = 0.05f;
hmap::trench(z3, path, width, true, false);
z3.dump();
hmap::export_banner_png("ex_trench.png", {z1, z2, z3}, hmap::Cmap::JET, true);
}
bool init_openmp(int num_threads=-1)
Definition openmp.cpp:14
Path find_cut_path_midpoint(const Array &z, DomainBoundary start, DomainBoundary end, std::uint32_t seed, float offset_ratio=0.2f, int steps=16, bool favor_boundary_center=true, bool favor_lower_elevation=true, bool favor_sinks=true, const UvTile &region=UvTile::unit(), ICommunicator &comm=SingleArrayComm::instance())
Generate a stochastic cut path using midpoint displacement.
Definition find_cut_path.cpp:150
void trench(Array &z, const Path &path, float width, bool enable_width_depth_scaling=true, bool enable_width_distance_scaling=true, bool enable_width_curvature_scaling=false, float curvature_radius_min=1.f, float curv_width_ratio_min=0.5f, float curv_width_ratio_max=2.f, RadialProfile radial_profile=RadialProfile::RP_SMOOTHSTEP_UPPER, float radial_profile_parameter=2.f, ElevationLongitudinalProfile longitudinal_profile=ElevationLongitudinalProfile::ELP_DECREASING, float elevation_shift=-0.05f, float shift_ramp_start_ratio=0.f, float shift_ramp_end_ratio=0.f, float min_slope=0.001f, size_t k_neighbors=8, const Array *p_noise_r=nullptr, Array *p_bending_mask=nullptr, int tile_size=32, const UvRect &uv_rect=UvRect::unit())
Carves a trench along a given path into a heightmap.
Definition trench.cpp:538

Result

◆ trench() [2/4]

void hmap::trench ( Array & z,
const std::vector< Path > & paths,
float width,
bool enable_width_depth_scaling = true,
bool enable_width_distance_scaling = true,
bool enable_width_curvature_scaling = false,
float curvature_radius_min = 1.f,
float curv_width_ratio_min = 0.5f,
float curv_width_ratio_max = 2.f,
RadialProfile radial_profile = RadialProfile::RP_SMOOTHSTEP_UPPER,
float radial_profile_parameter = 2.f,
ElevationLongitudinalProfile longitudinal_profile = ElevationLongitudinalProfile::ELP_DECREASING,
float elevation_shift = -0.05f,
float shift_ramp_start_ratio = 0.f,
float shift_ramp_end_ratio = 0.f,
float min_slope = 0.001f,
size_t k_neighbors = 8,
const Array * p_noise_r = nullptr,
Array * p_bending_mask = nullptr,
int tile_size = 32,
const UvRect & uv_rect = UvRect::unit() )

◆ trench() [3/4]

void hmap::trench ( Array & z,
const Graph & graph,
const std::vector< float > & relative_widths,
float width,
bool enable_width_depth_scaling = true,
RadialProfile radial_profile = RadialProfile::RP_SMOOTHSTEP_UPPER,
float radial_profile_parameter = 2.f,
ElevationLongitudinalProfile longitudinal_profile = ElevationLongitudinalProfile::ELP_DECREASING,
float elevation_shift = -0.05f,
float min_slope = 0.001f,
const Array * p_noise_r = nullptr,
Array * p_bending_mask = nullptr,
int tile_size = 32,
const UvRect & uv_rect = UvRect::unit() )

Carves river channels for an entire flow network represented by a Graph with per-node relative widths.

Each node in the graph provides a relative width ratio in [0, 1] (scaled by width to obtain the node's channel width). Along each edge between node u and node v, width is linearly interpolated as a function of the projection parameter t:

w(t) = width * ((1 - t) * r_u + t * r_v)

Parameters
[in,out]zTarget heightmap to carve in-place.
[in]graphInput flow network Graph.
[in]relative_widthsRelative width ratio in [0, 1] per graph node.
[in]widthMaximum base width.
[in]enable_width_depth_scalingModulate width according to depth.
[in]radial_profileTransverse cross-section profile.
[in]radial_profile_parameterShaping parameter for radial profile.
[in]longitudinal_profileDownhill elevation monotonicity mode.
[in]elevation_shiftDepth of trench incision.
[in]min_slopeMinimum downstream slope.
[in]p_noise_rOptional noise array for radial perturbation.
[out]p_bending_maskOptional blending mask.
[in]tile_sizeSpatial tile partition size.
[in]bboxDomain bounding box.

◆ trench() [4/4]

void hmap::trench ( Array & z,
const Graph & graph,
float width,
float width_exponent = 1.0f,
bool enable_width_depth_scaling = true,
RadialProfile radial_profile = RadialProfile::RP_SMOOTHSTEP_UPPER,
float radial_profile_parameter = 2.f,
ElevationLongitudinalProfile longitudinal_profile = ElevationLongitudinalProfile::ELP_DECREASING,
float elevation_shift = -0.05f,
float min_slope = 0.001f,
const Array * p_noise_r = nullptr,
Array * p_bending_mask = nullptr,
int tile_size = 32,
const UvRect & uv_rect = UvRect::unit() )

Carves river channels for an entire flow network represented by a Graph, computing relative widths from distance to outlet.

Parameters
[in,out]zTarget heightmap to carve in-place.
[in]graphInput flow network Graph.
[in]widthTarget river width at the outlet(s).
[in]width_exponentScaling exponent for width with distance to outlet (default: 1.0).
[in]enable_width_depth_scalingModulate width according to depth.
[in]radial_profileTransverse cross-section profile.
[in]radial_profile_parameterShaping parameter for radial profile.
[in]longitudinal_profileDownhill elevation monotonicity mode.
[in]elevation_shiftDepth of trench incision.
[in]min_slopeMinimum downstream slope.
[in]p_noise_rOptional noise array for radial perturbation.
[out]p_bending_maskOptional blending mask.
[in]tile_sizeSpatial tile partition size.
[in]bboxDomain bounding box.

◆ apply_hillshade() [1/2]

void hmap::apply_hillshade ( Texture & img,
const Array & array,
float vmin = 0.f,
float vmax = 1.f,
float exponent = 1.f )

Apply hillshading to a Tensor image.

This function applies a hillshading effect to the provided tensor image using the elevation data in the input array. The effect is controlled by the power exponent and can be scaled by specifying the minimum and maximum values.

Parameters
imgInput image represented as a Tensor.
arrayElevation data used to generate the hillshading effect.
vminMinimum value for scaling the hillshading effect (default is 0.f).
vmaxMaximum value for scaling the hillshading effect (default is 1.f).
exponentPower exponent applied to the hillshade values (default is 1.f).

◆ apply_hillshade() [2/2]

void hmap::apply_hillshade ( std::vector< uint8_t > & img,
const Array & array,
float vmin = 0.f,
float vmax = 1.f,
float exponent = 1.f,
bool is_img_rgba = false )

Apply hillshading to an 8-bit image.

This function applies a hillshading effect to a vector of 8-bit image data. The effect is computed based on the elevation data in the input array. The image can be either RGB or RGBA format depending on the is_img_rgba flag.

Parameters
imgInput image represented as a vector of 8-bit data.
arrayElevation data used to generate the hillshading effect.
vminMinimum value for scaling the hillshading effect (default is 0.f).
vmaxMaximum value for scaling the hillshading effect (default is 1.f).
exponentPower exponent applied to the hillshade values (default is 1.f).
is_img_rgbaBoolean flag indicating if the input image has an alpha channel (default is false).

◆ color_adjust()

void hmap::color_adjust ( Array & r,
Array & g,
Array & b,
ColorAdjust param,
glm::ivec2 dither_seed )

Apply color correction and tonemapping to RGB arrays.

Performs per-pixel adjustments including levels, exposure, tonemapping (Reinhard, ACES, or AGX), contrast, saturation, temperature, gamma, and optional dithering.

Parameters
rRed channel array (modified in place).
gGreen channel array (modified in place).
bBlue channel array (modified in place).
paramColor adjustment parameters.
dither_seedSeed used for dithering noise.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {4.f, 4.f};
int seed = 1;
hmap::Texture tex = hmap::colorize(z, 0.f, 1.f, hmap::Cmap::VIRIDIS, false);
hmap::Array r = tex[0];
hmap::Array g = tex[1];
hmap::Array b = tex[2];
params.contrast = 1.5f;
params.saturation = 1.2f;
hmap::color_adjust(r, g, b, params, {0, 0});
hmap::Texture tex_adj(r, g, b);
tex_adj.to_png("ex_color_adjust.png");
}
A class to represent a multi-channel texture using planar hmap::Array storage.
Definition texture.hpp:37
void color_adjust(Array &r, Array &g, Array &b, ColorAdjust param, glm::ivec2 dither_seed)
Apply color correction and tonemapping to RGB arrays.
Definition color_adjust.cpp:43
Texture colorize(const Array &array, float vmin, float vmax, int cmap, bool hillshading, bool reverse=false, const Array *p_noise=nullptr)
Apply colorization to an array.
Definition colorize.cpp:115
Definition colorize.hpp:68
float saturation
Definition colorize.hpp:73
float contrast
Definition colorize.hpp:72

Result

◆ color_match_mask()

Array hmap::color_match_mask ( const Array & r,
const Array & g,
const Array & b,
const glm::vec3 & color,
float tolerance = 0.f )

Create a mask of pixels matching a target color within a tolerance.

Parameters
rRed channel array.
gGreen channel array.
bBlue channel array.
colorTarget RGB color.
toleranceAllowed color difference (0 = exact match).
Returns
Array Mask array (1 for match, 0 otherwise), same size as inputs.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 0;
glm::vec3 color = {1.f, 0.f, 0.f}; // red
float tolerance = 0.5f;
hmap::Array mask = hmap::color_match_mask(r, g, b, color, tolerance);
hmap::export_banner_png("ex_color_match_mask.png",
{r, g, b, mask},
}
Array color_match_mask(const Array &r, const Array &g, const Array &b, const glm::vec3 &color, float tolerance=0.f)
Create a mask of pixels matching a target color within a tolerance.
Definition color_match_mask.cpp:12

Result

See unit tests: test_color_match_mask.cpp

◆ colorize() [1/2]

Texture hmap::colorize ( const Array & array,
float vmin,
float vmax,
int cmap,
bool hillshading,
bool reverse = false,
const Array * p_noise = nullptr )

Apply colorization to an array.

This function applies a colormap to the input array and optionally applies hillshading and noise. The colorization can be reversed, and the function returns a Tensor representing the colorized image.

Parameters
arrayInput array to be colorized.
vminMinimum value for scaling the colormap.
vmaxMaximum value for scaling the colormap.
cmapColormap to be applied (using the Cmap enum).
hillshadingBoolean flag to apply hillshading.
reverseBoolean flag to reverse the colormap (default is false).
p_noiseOptional pointer to a noise array (default is nullptr).
Returns
Tensor Colorized Tensor image.

◆ colorize() [2/2]

Texture hmap::colorize ( const Array & array,
float vmin,
float vmax,
const std::vector< float > & positions,
const std::vector< glm::vec3 > & colormap_colors,
bool reverse = false,
const Array * p_noise = nullptr )

Colorize a scalar field into a Texture using a custom colormap.

Parameters
arrayInput scalar values.
vminLower bound for normalization.
vmaxUpper bound for normalization.
positionsNormalized color positions.
colormap_colorsRGB(A) colors per position.
reverseReverse colormap mapping.
p_noiseOptional noise for dithering.
Returns
Colorized Texture.

Example

#include "highmap.hpp"
int main(void)
{
const glm::ivec2 shape = {256, 256};
const glm::vec2 res = {4.f, 4.f};
int seed = 42;
// Generate some base noise layers
hmap::remap(base);
// Colorize with custom position and colormap colors
std::vector<float> positions = {0.0f, 0.5f, 1.0f};
std::vector<glm::vec3> colors = {
glm::vec3(0.1f, 0.05f, 0.05f), // dark brown
glm::vec3(0.8f, 0.7f, 0.5f), // sand
glm::vec3(0.9f, 0.95f, 1.0f) // snow-white
};
hmap::Texture tex1 = hmap::colorize(base, 0.0f, 1.0f, positions, colors);
// Create another texture (e.g. green terrain tint)
base,
0.0f,
1.0f,
{0.0f, 1.0f},
{glm::vec3(0.0f, 0.2f, 0.0f), glm::vec3(0.4f, 0.8f, 0.3f)});
// Convert to RGBA for blending (mix demands 4 channels)
hmap::Texture rgba1(tex1[0],
tex1[1],
tex1[2],
hmap::Array(shape, 0.7f)); // 70% opacity
hmap::Texture rgba2(tex2[0],
tex2[1],
tex2[2],
hmap::Array(shape, 0.3f)); // 30% opacity
// Mix the two textures together
// Save the mixed texture
blended.to_png("ex_texture_mixed.png");
// Compute luminance
hmap::Array lum = hmap::luminance(blended);
lum.to_png_grayscale("ex_texture_luminance.png");
}
void to_png_grayscale(const std::string &fname, int depth=0, float vmin=0.f, float vmax=0.f) const
Export the array as a grayscale PNG image file with specified bit depth.
Definition io.cpp:146
void to_png(const std::string &fname, int depth=CV_8U) const
Saves the Texture as an image file (e.g. PNG).
Definition texture.cpp:256
@ MM_LINEAR
Linear RGB mixing.
Definition colorize.hpp:45
Texture mix(const Texture &tex1, const Texture &tex2, MixMethod method=MM_SQRT_AVG)
Mix two textures into an output texture.
Definition colorize.cpp:561
Array luminance(const Texture &tex)
Compute luminance from a Texture.
Definition colorize.cpp:555
See also
tests/src/test_texture.cpp (TextureColorize.CustomColormapAndOperations)

◆ colorize_bivariate()

Texture hmap::colorize_bivariate ( const Array & a1,
const Array & a2,
const glm::vec2 range1,
const glm::vec2 range2,
const std::vector< float > & positions1,
const std::vector< float > & positions2,
const std::vector< glm::vec3 > & colormap_colors1,
const std::vector< glm::vec3 > & colormap_colors2,
MixMethod method = MM_SQRT_AVG,
bool reverse1 = false,
bool reverse2 = false,
const Array * p_noise1 = nullptr,
const Array * p_noise2 = nullptr )

Colorize two scalar fields into a Texture using two custom colormaps and a color mixing method.

Each scalar field is independently normalized using its corresponding range and mapped to a color using its custom colormap. The two resulting colors are then combined according to the specified mixing method.

Parameters
a1First input scalar field.
a2Second input scalar field.
range1Lower and upper bounds for normalization of the first field.
range2Lower and upper bounds for normalization of the second field.
positions1Normalized color positions for the first colormap.
positions2Normalized color positions for the second colormap.
colormap_colors1RGB colors for the first colormap.
colormap_colors2RGB colors for the second colormap.
methodMethod used to mix the two resulting colors.
reverse1Reverse the first colormap mapping.
reverse2Reverse the second colormap mapping.
p_noise1Optional noise added to the first scalar field before normalization.
p_noise2Optional noise added to the second scalar field before normalization.
Returns
Colorized Texture containing the mixed colors.

Example

Result

See also
tests/src/test_texture.cpp

◆ colorize_grayscale()

Texture hmap::colorize_grayscale ( const Array & array)

Convert an array to a grayscale image.

This function converts the input array to an 8-bit grayscale Texture image.

Parameters
arrayInput array.
Returns
Texture Grayscale Texture image.

◆ colorize_histogram()

Texture hmap::colorize_histogram ( const Array & array)

Convert an array to a histogram-based grayscale image.

This function converts the input array to an 8-bit grayscale Texture image using a histogram-based method for enhanced contrast.

Parameters
arrayInput array.
Returns
Texture Grayscale Texture image with histogram-based contrast.

◆ colorize_slope_height_heatmap()

Texture hmap::colorize_slope_height_heatmap ( const Array & array,
int cmap )

Colorizes a slope height heatmap based on the gradient norms of a given array.

This function computes a colorized heatmap using a two-dimensional histogram that considers the gradient norm of the input array. It normalizes both the input array values and their corresponding gradient norms, calculates a 2D histogram, and then applies a colormap to visualize the heatmap.

Parameters
arrayThe input array for which the slope height heatmap is computed. This should be a 2D array representing height values.
cmapAn integer representing the colormap to be used for colorization. Colormap options depend on the colorization function used internally.
Returns
Texture representing the colorized heatmap, which visualizes the distribution of height values and their corresponding gradient norms.
  • The function normalizes the height values and gradient norms independently using the minimum and maximum values.
  • A 2D histogram is constructed, where each bin corresponds to a pair of normalized height and gradient values.
  • The colormap is then applied to this histogram to produce a colorized output.
Note
If the input array has a constant value (i.e., min == max), no normalization is applied, and the function may not produce meaningful results.
Warning
Ensure that the input array is non-empty and has valid dimensions.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {2.f, 2.f};
int seed = 1;
col3.to_png("ex_colorize_slope_height_heatmap.png");
}
Texture colorize_slope_height_heatmap(const Array &array, int cmap)
Colorizes a slope height heatmap based on the gradient norms of a given array.
Definition colorize.cpp:461

Result

◆ colorize_vec2()

Texture hmap::colorize_vec2 ( const Array & array1,
const Array & array2 )

Combine two arrays into a colored image.

This function takes two input arrays and combines them into a single 8-bit colored Texture image. The resulting image uses the data from both arrays to create a composite color representation.

Parameters
array1First input array.
array2Second input array.
Returns
Texture Colorized Texture image.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
hmap::Array x = hmap::slope(shape, 0.f, 1.f);
hmap::Array y = hmap::slope(shape, 90.f, 1.f);
col3.to_png("ex_colorize_vec2.png");
}
Texture colorize_vec2(const Array &array1, const Array &array2)
Combine two arrays into a colored image.
Definition colorize.cpp:508

Result

◆ luminance()

Array hmap::luminance ( const Texture & tex)

Compute luminance from a Texture.

Computes a grayscale luminance array from the RGB channels of a texture.

Parameters
texInput texture (expects at least 3 channels).
Returns
Luminance Array.

Example

#include "highmap.hpp"
int main(void)
{
const glm::ivec2 shape = {256, 256};
const glm::vec2 res = {4.f, 4.f};
int seed = 42;
// Generate some base noise layers
hmap::remap(base);
// Colorize with custom position and colormap colors
std::vector<float> positions = {0.0f, 0.5f, 1.0f};
std::vector<glm::vec3> colors = {
glm::vec3(0.1f, 0.05f, 0.05f), // dark brown
glm::vec3(0.8f, 0.7f, 0.5f), // sand
glm::vec3(0.9f, 0.95f, 1.0f) // snow-white
};
hmap::Texture tex1 = hmap::colorize(base, 0.0f, 1.0f, positions, colors);
// Create another texture (e.g. green terrain tint)
base,
0.0f,
1.0f,
{0.0f, 1.0f},
{glm::vec3(0.0f, 0.2f, 0.0f), glm::vec3(0.4f, 0.8f, 0.3f)});
// Convert to RGBA for blending (mix demands 4 channels)
hmap::Texture rgba1(tex1[0],
tex1[1],
tex1[2],
hmap::Array(shape, 0.7f)); // 70% opacity
hmap::Texture rgba2(tex2[0],
tex2[1],
tex2[2],
hmap::Array(shape, 0.3f)); // 30% opacity
// Mix the two textures together
// Save the mixed texture
blended.to_png("ex_texture_mixed.png");
// Compute luminance
hmap::Array lum = hmap::luminance(blended);
lum.to_png_grayscale("ex_texture_luminance.png");
}
#include "highmap.hpp"
int main(void)
{
const glm::ivec2 shape = {512, 128};
// Define two classic pigment colors: Ultramarine Blue and Cadmium Yellow
// Ultramarine Blue: RGB (25, 0, 89) -> normalized: (0.098f, 0.0f, 0.349f)
// Cadmium Yellow: RGB (254, 236, 0) -> normalized: (0.996f, 0.925f, 0.0f)
const glm::vec3 blue(0.098f, 0.0f, 0.349f);
const glm::vec3 yellow(0.996f, 0.925f, 0.0f);
// Create base texture 1 (Blue) with 100% opacity
hmap::Texture tex1(shape, 4);
tex1[0] = hmap::Array(shape, blue.x);
tex1[1] = hmap::Array(shape, blue.y);
tex1[2] = hmap::Array(shape, blue.z);
tex1[3] = hmap::Array(shape, 1.0f);
// Create base texture 2 (Yellow) with a horizontal gradient in the alpha
// channel
hmap::Texture tex2(shape, 4);
tex2[0] = hmap::Array(shape, yellow.x);
tex2[1] = hmap::Array(shape, yellow.y);
tex2[2] = hmap::Array(shape, yellow.z);
hmap::Array alpha(shape);
for (int j = 0; j < shape.y; ++j)
{
for (int i = 0; i < shape.x; ++i)
{
alpha(i, j) = float(i) / float(shape.x - 1);
}
}
tex2[3] = alpha;
// Mix using the three different methods
hmap::Texture blended_linear = hmap::mix(tex1,
tex2,
hmap::Texture blended_sqrt = hmap::mix(tex1,
tex2,
hmap::Texture blended_mixbox = hmap::mix(tex1,
tex2,
// Save the blended gradients
blended_linear.to_png("ex_mixbox_linear.png");
blended_sqrt.to_png("ex_mixbox_sqrt.png");
blended_mixbox.to_png("ex_mixbox_mixbox.png");
return 0;
}
@ MM_MIXBOX
Physical pigment-based mixing (Mixbox).
Definition colorize.hpp:47
@ MM_SQRT_AVG
Square-root average mixing.
Definition colorize.hpp:46

Result

See also
tests/src/test_texture.cpp (TextureColorize.CustomColormapAndOperations)

◆ mix() [1/3]

Texture hmap::mix ( const Texture & tex1,
const Texture & tex2,
MixMethod method = MM_SQRT_AVG )

Mix two textures into an output texture.

Parameters
tex1First input texture.
tex2Second input texture.
methodMixing method to use.
Returns
Mixed Texture.

Example

#include "highmap.hpp"
int main(void)
{
const glm::ivec2 shape = {256, 256};
const glm::vec2 res = {4.f, 4.f};
int seed = 42;
// Generate some base noise layers
hmap::remap(base);
// Colorize with custom position and colormap colors
std::vector<float> positions = {0.0f, 0.5f, 1.0f};
std::vector<glm::vec3> colors = {
glm::vec3(0.1f, 0.05f, 0.05f), // dark brown
glm::vec3(0.8f, 0.7f, 0.5f), // sand
glm::vec3(0.9f, 0.95f, 1.0f) // snow-white
};
hmap::Texture tex1 = hmap::colorize(base, 0.0f, 1.0f, positions, colors);
// Create another texture (e.g. green terrain tint)
base,
0.0f,
1.0f,
{0.0f, 1.0f},
{glm::vec3(0.0f, 0.2f, 0.0f), glm::vec3(0.4f, 0.8f, 0.3f)});
// Convert to RGBA for blending (mix demands 4 channels)
hmap::Texture rgba1(tex1[0],
tex1[1],
tex1[2],
hmap::Array(shape, 0.7f)); // 70% opacity
hmap::Texture rgba2(tex2[0],
tex2[1],
tex2[2],
hmap::Array(shape, 0.3f)); // 30% opacity
// Mix the two textures together
// Save the mixed texture
blended.to_png("ex_texture_mixed.png");
// Compute luminance
hmap::Array lum = hmap::luminance(blended);
lum.to_png_grayscale("ex_texture_luminance.png");
}
#include "highmap.hpp"
int main(void)
{
const glm::ivec2 shape = {512, 128};
// Define two classic pigment colors: Ultramarine Blue and Cadmium Yellow
// Ultramarine Blue: RGB (25, 0, 89) -> normalized: (0.098f, 0.0f, 0.349f)
// Cadmium Yellow: RGB (254, 236, 0) -> normalized: (0.996f, 0.925f, 0.0f)
const glm::vec3 blue(0.098f, 0.0f, 0.349f);
const glm::vec3 yellow(0.996f, 0.925f, 0.0f);
// Create base texture 1 (Blue) with 100% opacity
hmap::Texture tex1(shape, 4);
tex1[0] = hmap::Array(shape, blue.x);
tex1[1] = hmap::Array(shape, blue.y);
tex1[2] = hmap::Array(shape, blue.z);
tex1[3] = hmap::Array(shape, 1.0f);
// Create base texture 2 (Yellow) with a horizontal gradient in the alpha
// channel
hmap::Texture tex2(shape, 4);
tex2[0] = hmap::Array(shape, yellow.x);
tex2[1] = hmap::Array(shape, yellow.y);
tex2[2] = hmap::Array(shape, yellow.z);
hmap::Array alpha(shape);
for (int j = 0; j < shape.y; ++j)
{
for (int i = 0; i < shape.x; ++i)
{
alpha(i, j) = float(i) / float(shape.x - 1);
}
}
tex2[3] = alpha;
// Mix using the three different methods
hmap::Texture blended_linear = hmap::mix(tex1,
tex2,
hmap::Texture blended_sqrt = hmap::mix(tex1,
tex2,
hmap::Texture blended_mixbox = hmap::mix(tex1,
tex2,
// Save the blended gradients
blended_linear.to_png("ex_mixbox_linear.png");
blended_sqrt.to_png("ex_mixbox_sqrt.png");
blended_mixbox.to_png("ex_mixbox_mixbox.png");
return 0;
}

Result

See also
tests/src/test_texture.cpp (TextureColorize.CustomColormapAndOperations)
Examples
ex_mixbox.cpp.

◆ mix() [2/3]

Texture hmap::mix ( const Texture & tex1,
const Texture & tex2,
const Array & mask,
MixMethod method = MM_SQRT_AVG,
float gain = 1.f )

Mix two textures based on a transparency mask.

Blends tex1 and tex2 according to the values in mask. When mask is 0, tex1 is selected; when mask is 1, tex2 is selected. If gain is different from 1.0, a gain curve is applied to the mask beforehand.

Parameters
tex1First input texture (background).
tex2Second input texture (foreground).
maskTransparency mask array with values in [0, 1].
methodMixing method to use (default: MM_SQRT_AVG).
gainGain factor applied to the mask when != 1.0 (default: 1.0).
Returns
Mixed Texture.

◆ mix() [3/3]

Texture hmap::mix ( const std::vector< const Texture * > & texs,
MixMethod method = MM_SQRT_AVG )

Mix a list of textures sequentially.

Parameters
texsInput list of textures.
methodMixing method to use.
Returns
Mixed Texture.

◆ mix_normal_map()

Texture hmap::mix_normal_map ( const Texture & nmap_base,
const Texture & nmap_detail,
float detail_scaling,
NormalMapBlendingMethod blending_method )

Blend two normal maps into a single output normal map.

Combines a base normal map with a detail normal map using the specified blending method and scaling factor.

Parameters
nmap_baseBase normal map texture.
nmap_detailDetail normal map texture.
detail_scalingStrength of the detail normal map.
blending_methodNormal map blending method.
Returns
Blended Texture normal map.
See also
tests/src/test_texture.cpp (TextureColorize.CustomColormapAndOperations)

◆ shade_color() [1/2]

glm::vec3 hmap::shade_color ( const glm::vec3 & color,
float t )

Adjust color by shading parameter t clamped to [0, 1].

Darker and richer for t approaching 0, lighter and duller for t approaching 1.

Parameters
colorInput RGB color.
tShading parameter (clamped to [0, 1]).
Returns
Adjusted RGB color.

◆ shade_color() [2/2]

void hmap::shade_color ( Texture & tex,
const Array & factor )

Apply shade_color to each pixel of a Texture using values from an Array.

For each pixel (i, j), adjusts RGB channels using factor(i, j) clamped to [0, 1]. Alpha channel (if present) is preserved.

Parameters
texTexture to be shaded in-place (must have at least 3 channels).
factorShading factor Array with same 2D shape as tex.

◆ shade_topographic_residual()

void hmap::shade_topographic_residual ( Texture & tex,
const Array & z,
int ir,
float strength = 1.0f )

Apply shade_color to a Texture based on topographic residuals of an elevation array.

Computes normalized topographic residual on the input elevation array z with smoothing radius ir, scales the normalized residual [-1, 1] by strength into shading factors in [0, 1], and applies shade_color to tex.

Parameters
texTexture to be shaded in-place (must have at least 3 channels).
zElevation array with same 2D shape as tex.
irRadius for topographic residual smoothing filter.
strengthStrength of residual shading (default is 1.f).

◆ terrain_texture()

Texture hmap::terrain_texture ( const Array & z,
const Array * p_deposition = nullptr,
const Array * p_snow_depth = nullptr,
const TerrainTextureParams & params = TerrainTextureParams(),
const BBox2D & bbox = BBox2D::unit(),
const Array * p_noise = nullptr,
ICommunicator & comm = SingleArrayComm::instance() )

Generate a procedural terrain texture from elevation and surface analysis.

Combines slopes, ridges, flow accumulation, deposition, and noise octaves into an RGBA color Texture.

Parameters
zElevation input array.
p_depositionOptional deposition array (may be nullptr).
p_snow_depthOptional snow depth array (may be nullptr).
paramsTerrain texturing parameters.
bboxBounding box for coherent noise coordinates.
p_noiseOptional custom noise array (bypasses procedural noise if provided).
commCommunicator for collective normalization across tiles.
Returns
4-channel RGBA Texture.

◆ get_colormap_data()

std::vector< glm::vec3 > hmap::get_colormap_data ( int cmap)

◆ to_string() [1/3]

std::string hmap::to_string ( ReduceOp op)

◆ level_set_curvature()

Array hmap::level_set_curvature ( const Array & array,
int prefilter_ir )

Computes a signed level-set curvature.

Parameters
arrayInput array.
prefilter_irOptional smoothing radius for curvature evaluation.
Returns
Signed curvature.

See unit tests: test_level_set_curvature.cpp

◆ curvature_quadric()

Array hmap::curvature_quadric ( const Array & z,
int ir,
CurvatureType curvature_type )

Compute curvature measures on a scalar field.

Computes various curvature descriptors from the input array z. If ir == 0, local derivatives (3×3 stencil) are used. Otherwise, a quadric surface is fitted over a (2·ir+1) window.

Parameters
zInput scalar field (e.g. heightmap)
irNeighborhood radius (0 for local, >0 for quadric fit)
curvature_typeType of curvature to compute.
Returns
Array of same size containing the selected curvature

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
int ir = 16;
std::vector<hmap::Array> arrays = {z};
std::vector<hmap::CurvatureType> types = {
};
for (const auto type : types)
{
{
arrays.push_back(out);
}
{
arrays.push_back(out);
}
}
hmap::export_banner_png("ex_curvature_quadric.png",
arrays,
false,
true);
}
Array curvature_quadric(const Array &z, int ir, CurvatureType curvature_type, bool approx_algo=false)
See hmap::curvature_quadric.
Definition curvature_quadric.cpp:302
Array curvature_quadric(const Array &z, int ir, CurvatureType curvature_type)
Compute curvature measures on a scalar field.
Definition curvature_quadric.cpp:22
@ CT_SHAPE_INDEX
Shape index (normalized curvature classification).
Definition curvature.hpp:48
@ CT_TANGENTIAL
Tangential curvature.
Definition curvature.hpp:46
@ CT_PROFILE
Profile curvature (along slope direction).
Definition curvature.hpp:44
@ CT_GAUSSIAN
Gaussian curvature.
Definition curvature.hpp:43
@ CT_MAX
Maximum curvature (principal).
Definition curvature.hpp:41
@ CT_ACCUMULATION
Accumulation curvature (H² − K²).
Definition curvature.hpp:47
@ CT_MIN
Minimum curvature (principal).
Definition curvature.hpp:40
@ CT_CONTOUR
Contour curvature (across slope).
Definition curvature.hpp:45
@ CT_RING
Ring curvature (planform torsion-like measure).
Definition curvature.hpp:50
@ CT_MEAN
Mean curvature.
Definition curvature.hpp:42
@ CT_ROTOR
Rotor curvature (rotational component).
Definition curvature.hpp:51
@ CT_UNSPHERICITY
Unsphericity (√(H² − K)).
Definition curvature.hpp:49

Result

◆ aeolian_erosion()

void hmap::aeolian_erosion ( Array & z,
int steps = 300,
std::uint32_t seed = 1337u,
glm::vec2 wind = {3.f, 0.f},
const Array * p_bedrock = nullptr,
const Array * p_vegetation = nullptr,
const Array * p_abrasion_mask = nullptr,
Array * p_sediment_map = nullptr,
Array * p_bedrock_map = nullptr,
float cell_size = -1.f,
float matter_to_move = 0.001f,
int samples_per_step = 0,
float sand_repose_angle = 33.f,
float shadow_angle_min = 5.f,
float shadow_angle_max = 15.f,
float max_shadow_dist = 12.f,
float abrasion_rate = 0.f,
float repose_rate = 0.35f,
int sync_interval = 0,
const UvTile & region = UvTile::dummy(),
ICommunicator & comm = SingleArrayComm::instance(),
int shadow_map_interval = 1,
int repose_interval = 2 )

Simulates wind-driven aeolian terrain erosion, sand transport, and dune dynamics on GPU.

This algorithm is adapted from the research by Axel Paris, Adrien Peytavie, Eric Guérin, Oscar Argudo, and Eric Galin (Pacific Graphics 2019 / Computer Graphics Forum), "Desertscapes Simulation".

It simulates:

  • Wind-directed sand saltation and reptation across the landscape.
  • Lee-side aerodynamic wind shadows triggering dune deposition.
  • Vegetation interaction, anchoring sand to form vegetated mounds (nabkhas).
  • Bedrock abrasion in high-energy, sediment-sparse regions, carving yardangs.
  • Angle-of-repose avalanching maintaining realistic slipfaces.
Parameters
zInput/output total elevation heightmap (modified in-place). On output, z equals bedrock + sediment.
stepsNumber of simulation iterations.
seedRandom seed for stochastic sampling.
windBase wind direction vector (in grid units).
p_bedrockOptional input bedrock elevation array. If null, bedrock is initialized to zero.
p_vegetationOptional vegetation density mask in [0, 1].
p_abrasion_maskOptional rock erodibility/susceptibility mask in [0, 1].
p_sediment_mapOptional output array receiving final sand thickness.
p_bedrock_mapOptional output array receiving final bedrock elevation.
cell_sizeHorizontal grid spacing in world units. If <= 0, defaults to 1.f / z.shape.x.
matter_to_moveVolume/height of sand grain packet displaced per hop.
samples_per_stepNumber of stochastic saltation samples evaluated per step. If <= 0, defaults to total cell count (nx * ny).
sand_repose_angleAngle of repose for loose sediment (in degrees, typically ~33°).
shadow_angle_minMinimum wind shadow angle threshold (in degrees, typically ~5°).
shadow_angle_maxMaximum wind shadow angle threshold (in degrees, typically ~15°).
max_shadow_distMaximum raymarch distance for wind shadow detection (in grid cells).
abrasion_rateAbrasion wear rate on exposed bedrock (0 to disable).
repose_rateRate of sediment redistribution during repose stabilization.
sync_intervalNumber of simulation steps between communicator tile syncs.
regionTile region geometry metadata.
commTiled communicator instance.
shadow_map_intervalIf > 0, wind shadows are precomputed on a grid every shadow_map_interval steps and looked up by the walkers, instead of ray-marching per walker hop. Much faster, at the cost of a slightly approximate (stale and interpolated) shadow. 0 keeps the exact per-walker ray-marching.
repose_intervalNumber of simulation steps between angle-of-repose stabilization passes.

Example

#include <iostream>
#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
// shape = {1024, 1024};
// shape = {512, 512};
std::uint32_t seed = 0;
constexpr int steps = 500;
constexpr float alpha = 0.f / 180.f * M_PI;
constexpr glm::vec2 wind_dir = {std::cos(alpha), std::sin(alpha)};
// --- 1. Transverse sand dunes (unimodal wind with abundant sand supply)
hmap::Array z_transverse(shape, 0.05f);
hmap::aeolian_erosion(z_transverse,
steps,
/* seed */ seed,
3.f * wind_dir,
/* p_bedrock */ nullptr,
/* p_vegetation */ nullptr,
/* p_abrasion_mask */ nullptr,
/* p_sediment_map */ nullptr,
/* p_bedrock_map */ nullptr,
/* cell_size */ -1.f,
/* matter_to_move */ 0.001f,
/* samples_per_step */ shape.x * shape.y,
/* sand_repose_angle */ 33.f,
/* shadow_angle_min */ 5.f,
/* shadow_angle_max */ 15.f,
/* max_shadow_dist */ 12.f,
/* abrasion_rate */ 0.f,
/* repose_rate */ 0.35f);
z_transverse.dump("zt.png");
// --- 2. Transverse dunes with bedrock bumps (sand flowing around and piling)
shape,
{3.f, 3.f},
seed + 10u,
8,
0.f);
hmap::remap(bed_bumps, 0.f, 0.5f);
hmap::clamp_min(bed_bumps, 0.5f * bed_bumps.max());
bed_bumps -= 0.5f * bed_bumps.max();
// Initial terrain: bedrock bumps + abundant sand layer (0.05 units)
const float smax = 0.01f;
hmap::Array z_bumps = bed_bumps + hmap::Array(shape, smax);
steps,
/* seed */ seed,
3.f * wind_dir,
/* p_bedrock */ &bed_bumps,
/* p_vegetation */ nullptr,
/* p_abrasion_mask */ nullptr,
/* p_sediment_map */ nullptr,
/* p_bedrock_map */ nullptr,
/* cell_size */ -1.f,
/* matter_to_move */ smax / 50.f,
/* samples_per_step */ shape.x * shape.y,
/* sand_repose_angle */ 33.f,
/* shadow_angle_min */ 5.f,
/* shadow_angle_max */ 15.f,
/* max_shadow_dist */ 12.f,
/* abrasion_rate */ 0.f,
/* repose_rate */ 0.35f);
bed_bumps.dump("z.png");
(z_bumps - bed_bumps).dump("s.png");
// --- 3. Barchan dunes (higher wind speed with lower sand supply)
hmap::Array z_barchan(shape, 0.0125f);
steps,
/* seed */ seed,
5.f * wind_dir,
/* p_bedrock */ nullptr,
/* p_vegetation */ nullptr,
/* p_abrasion_mask */ nullptr,
/* p_sediment_map */ nullptr,
/* p_bedrock_map */ nullptr,
/* cell_size */ -1.f,
/* matter_to_move */ 0.001f,
/* samples_per_step */ shape.x * shape.y,
/* sand_repose_angle */ 33.f,
/* shadow_angle_min */ 5.f,
/* shadow_angle_max */ 15.f,
/* max_shadow_dist */ 12.f,
/* abrasion_rate */ 0.f,
/* repose_rate */ 0.35f);
// --- 4. Yardangs (wind abrasion carving corrugated bedrock corridors)
hmap::Array bed_yardang(shape, 0.05f);
hmap::Array z_yardang = bed_yardang + hmap::Array(shape, 0.005f);
shape,
{4.f, 16.f},
seed);
hmap::remap(abrasion_mask, 0.2f, 1.f);
steps,
/* seed */ seed,
3.f * wind_dir,
/* p_bedrock */ &bed_yardang,
/* p_vegetation */ nullptr,
/* p_abrasion_mask */ &abrasion_mask,
/* p_sediment_map */ nullptr,
/* p_bedrock_map */ nullptr,
/* cell_size */ -1.f,
/* matter_to_move */ 0.001f,
/* samples_per_step */ shape.x * shape.y,
/* sand_repose_angle */ 33.f,
/* shadow_angle_min */ 5.f,
/* shadow_angle_max */ 15.f,
/* max_shadow_dist */ 12.f,
/* abrasion_rate */ 0.0005f,
/* repose_rate */ 0.35f);
// --- 5. Export banner
hmap::export_banner_png("ex_aeolian_erosion.png",
{z_transverse, z_bumps, z_barchan, z_yardang},
true,
true);
std::cout << "ex_aeolian_erosion successfully executed." << std::endl;
return 0;
}
void aeolian_erosion(Array &z, int steps=300, std::uint32_t seed=1337u, glm::vec2 wind={3.f, 0.f}, const Array *p_bedrock=nullptr, const Array *p_vegetation=nullptr, const Array *p_abrasion_mask=nullptr, Array *p_sediment_map=nullptr, Array *p_bedrock_map=nullptr, float cell_size=-1.f, float matter_to_move=0.001f, int samples_per_step=0, float sand_repose_angle=33.f, float shadow_angle_min=5.f, float shadow_angle_max=15.f, float max_shadow_dist=12.f, float abrasion_rate=0.f, float repose_rate=0.35f, int sync_interval=0, const UvTile &region=UvTile::dummy(), ICommunicator &comm=SingleArrayComm::instance(), int shadow_map_interval=1, int repose_interval=2)
Simulates wind-driven aeolian terrain erosion, sand transport, and dune dynamics on GPU.
Definition aeolian_erosion.cpp:24

Result

◆ aeolian_erosion_multiscale()

void hmap::aeolian_erosion_multiscale ( Array & z,
int steps = 300,
std::uint32_t seed = 1337u,
glm::vec2 wind = {3.f, 0.f},
const Array * p_bedrock = nullptr,
const Array * p_vegetation = nullptr,
const Array * p_abrasion_mask = nullptr,
Array * p_sediment_map = nullptr,
Array * p_bedrock_map = nullptr,
float cell_size = -1.f,
float matter_to_move = 0.001f,
float sand_repose_angle = 33.f,
float shadow_angle_min = 5.f,
float shadow_angle_max = 15.f,
float max_shadow_dist = 12.f,
float abrasion_rate = 0.f,
float repose_rate = 0.35f,
int levels = 3,
float coarse_fraction = 0.7f,
int min_level_size = 64,
int shadow_map_interval = 1,
int repose_interval = 2 )

Multiscale (coarse-to-fine) variant of hmap::aeolian_erosion.

The simulation is first run on downsampled copies of the terrain, where each step is much cheaper (fewer cells and shorter shadow rays in cells), to develop the large-scale dune pattern. At each level, only the change in sediment (and bedrock) is upsampled and added to the full-resolution layers so that fine details of the input are preserved. The last steps are run at full resolution to restore small-scale features.

Parameters
zInput/output total elevation (bedrock + sediment).
stepsTotal number of steps at full resolution (steps are distributed across the levels).
seedRandom seed.
windBase wind vector (reference grid of 256).
p_bedrockOptional bedrock elevation.
p_vegetationOptional vegetation density in [0, 1].
p_abrasion_maskOptional abrasion susceptibility in [0, 1].
p_sediment_mapOptional output sediment thickness.
p_bedrock_mapOptional output bedrock elevation.
cell_sizeFull-resolution cell size (<= 0 for 1 / z.shape.x).
matter_to_moveSand packet displaced per hop.
sand_repose_angleAngle of repose (degrees).
shadow_angle_minMinimum wind shadow angle (degrees).
shadow_angle_maxMaximum wind shadow angle (degrees).
max_shadow_distMaximum shadow raymarch distance (reference grid).
abrasion_rateBedrock abrasion rate (0 to disable).
repose_rateRepose stabilization rate.
levelsNumber of resolution levels (1 = single-scale). Each level halves the resolution.
coarse_fractionFraction in [0, 1) of the steps spent on coarse levels (shared equally); the remainder is run at full resolution.
min_level_sizeSmallest allowed size of a coarse level (levels that would be smaller are dropped).
shadow_map_intervalSee hmap::aeolian_erosion (0 = exact shadows).
repose_intervalSee hmap::aeolian_erosion.

◆ coastal_erosion_diffusion()

void hmap::coastal_erosion_diffusion ( Array & z,
Array & water_depth,
float additional_depth,
int iterations = 10,
const Array * p_mask = nullptr,
Array * p_water_mask = nullptr )

Simulates terrain diffusion due to coastal erosion.

This function applies an iterative coastal erosion diffusion process on a terrain elevation array (z), taking into account the presence and depth of water. The erosion model smooths the terrain near shorelines while maintaining constant water-surface height.

At each iteration:

  • A local water mask is computed using water_mask(water_depth, z, additional_depth).
  • The terrain elevations are smoothed (diffused) using a masked Laplacian filter, applied only near the water boundary.
  • The water depth is adjusted to preserve the total water surface height (i.e., z + water_depth remains constant).

This results in a realistic simulation of coastal erosion processes where the terrain near the waterline is progressively smoothed and redistributed.

Parameters
zReference to the terrain elevation array (modified in place).
water_depthReference to the array representing water depth values (modified to preserve water surface level).
additional_depthAdditional virtual water depth used to estimate the influence region of the shoreline during mask computation.
iterationsNumber of erosion–diffusion iterations to apply.
p_maskOptional intensity mask in [0, 1].
p_water_maskOptional output pointer. If non-null, it receives the last computed water mask used during the final iteration.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
auto z0 = z;
hmap::Array water_depth = hmap::flooding_uniform_level(z, 0.3f);
float additional_depth = 0.075f;
int iterations = 10;
hmap::coastal_erosion_diffusion(z, water_depth, additional_depth, iterations);
hmap::export_banner_png("ex_coastal_erosion_diffusion.png",
{z0, z, z + water_depth},
true);
}
void coastal_erosion_diffusion(Array &z, Array &water_depth, float additional_depth, int iterations=10, const Array *p_mask=nullptr, Array *p_water_mask=nullptr)
Simulates terrain diffusion due to coastal erosion.
Definition coastal_erosion.cpp:19
Array flooding_uniform_level(const Array &z, float zref)
Compute water depth for a uniform flooding level.
Definition flooding.cpp:24

Result

◆ coastal_erosion_profile() [1/2]

void hmap::coastal_erosion_profile ( Array & z,
Array & water_depth,
float shore_ground_extent,
float shore_water_extent,
float slope_shore = 0.5f,
float slope_shore_water = 0.5f,
float scarp_extent_ratio = 0.5f,
bool apply_post_filter = true,
int post_filter_iterations = 3,
bool solid_shore_mask = true,
float scarp_mask_transition_ratio = 0.2f,
const Array * p_noise = nullptr,
Array * p_shore_mask = nullptr,
Array * p_scarp_mask = nullptr )

Applies a coastal erosion profile to a terrain elevation field.

This function modifies the elevation array z by carving a coastal profile at the interface between ground and water. It uses distance transforms both from ground regions and from water regions to determine how far each point is from the shoreline. According to this distance, the function applies:

  • A ground-side shore slope with an optional scarp transition.
  • A water-side underwater slope ensuring continuity with the ground slope.
  • An optional post-filtering step (Laplace smoothing) restricted to the shoreline region.

Water depth is adjusted after filtering to preserve the original water surface height.

Optionally, a shoreline mask can be returned describing the region influenced by the coastal transformation.

Parameters
zArray of terrain elevations. Modified in-place.
water_depthArray of water depths. Modified to preserve water surface height after terrain changes.
shore_ground_extentHorizontal extent (in grid units) over which the ground-side shore profile is applied.
shore_water_extentHorizontal extent (in grid units) over which the underwater profile is applied.
slope_shoreGround-side slope magnitude of the coastal profile. Expressed in elevation units per domain width.
slope_shore_waterWater-side slope magnitude of the underwater profile. Expressed similarly to slope_shore.
scarp_extent_ratioRatio defining the relative extent of the scarp region. A value in [0,1]:
  • 0 → no scarp, only slope
  • 1 → all scarp
apply_post_filterIf true, applies Laplacian smoothing to z restricted to shoreline areas.
post_filter_iterationsIterations for post-smoothing filter.
solid_shore_maskWhether shore mask is solid.
scarp_mask_transition_ratioSmooth transition ratio for scarp mask.
p_noiseOptional noise array.
p_shore_maskOptional output pointer. If non-null, receives the shoreline mask (values in [0,1]) indicating where the coastal transformation was applied.
p_scarp_maskOptional output pointer for scarp mask.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {2.f, 2.f};
int seed = 1;
auto z1 = z0;
auto z2 = z0;
// --- without noise
hmap::Array water_depth1 = hmap::flooding_uniform_level(z1, 0.3f);
float shore_ground_extent = 32.f; // pixels
float shore_water_extent = 16.f;
water_depth1,
shore_ground_extent,
shore_water_extent);
// --- with noise
shape,
4.f * kw,
++seed,
8,
0.f);
hmap::Array water_depth2 = hmap::flooding_uniform_level(z2, 0.3f);
hmap::Array shore_mask;
hmap::Array scarp_mask;
water_depth2,
shore_ground_extent,
shore_water_extent,
0.5f,
0.5f,
0.5f,
true,
5,
true,
0.2f,
&dr,
&shore_mask,
&scarp_mask);
hmap::export_banner_png("ex_coastal_erosion_profile.png",
{z0,
z1,
z1 + water_depth1,
z2,
z2 + water_depth2,
shore_mask,
scarp_mask},
true);
}
void coastal_erosion_profile(Array &z, Array &water_depth, float shore_ground_extent, float shore_water_extent, float slope_shore=0.5f, float slope_shore_water=0.5f, float scarp_extent_ratio=0.5f, bool apply_post_filter=true, int post_filter_iterations=3, bool solid_shore_mask=true, float scarp_mask_transition_ratio=0.2f, const Array *p_noise=nullptr, Array *p_shore_mask=nullptr, Array *p_scarp_mask=nullptr)
Applies a coastal erosion profile to a terrain elevation field.
Definition coastal_erosion.cpp:57
@ SIMPLEX2S
OpenSimplex2S.
Definition functions.hpp:73

Result

◆ coastal_erosion_profile() [2/2]

void hmap::coastal_erosion_profile ( Array & z,
const Array * p_mask,
Array & water_depth,
float shore_ground_extent,
float shore_water_extent,
float slope_shore = 0.5f,
float slope_shore_water = 0.5f,
float scarp_extent_ratio = 0.5f,
bool apply_post_filter = true,
int post_filter_iterations = 3,
bool solid_shore_mask = true,
float scarp_mask_transition_ratio = 0.2f,
const Array * p_noise = nullptr,
Array * p_shore_mask = nullptr,
Array * p_scarp_mask = nullptr )

◆ hydraulic_algebric() [1/2]

void hmap::hydraulic_algebric ( Array & z,
Array * p_mask,
float talus_ref,
int ir,
Array * p_bedrock = nullptr,
Array * p_erosion_map = nullptr,
Array * p_deposition_map = nullptr,
float c_erosion = 0.05f,
float c_deposition = 0.05f,
int iterations = 1 )

Apply an algerbic formula based on the local gradient to perform erosion/deposition.

Parameters
zInput array.
p_maskIntensity mask, expected in [0, 1] (applied as a post-processing).
talus_refReference talus.
irSmoothing prefilter radius.
p_bedrockReference to the bedrock heightmap.
p_erosion_map[out]Reference to the erosion map, provided as an output field.
p_deposition_map[out] Reference to the deposition map, provided as an output field.
c_erosionErosion coefficient.
c_depositionDeposition coefficient.
iterationsNumber of iterations.

Example

#include "highmap.hpp"
int main(void)
{
"hydraulic_algebric is deprecated and will be removed at some point.");
glm::ivec2 shape = {256, 256};
glm::vec2 res = {2.f, 2.f};
int seed = 1;
auto z0 = z;
auto talus = gradient_talus(z);
float talus_ref = 0.2f * talus.max();
float c_erosion = 0.05f;
float c_deposition = 0.05f;
int iterations = 1;
int ir = 16;
talus_ref,
ir,
nullptr,
nullptr,
nullptr,
c_erosion,
c_deposition,
iterations);
hmap::export_banner_png("ex_hydraulic_algebric.png",
{z0, z},
true);
}
void warn(Args &&...args)
Definition logger.hpp:48
Array gradient_talus(const Array &array)
Compute the gradient talus slope of a 2D array.
Definition gradient.cpp:257
void hydraulic_algebric(Array &z, Array *p_mask, float talus_ref, int ir, Array *p_bedrock=nullptr, Array *p_erosion_map=nullptr, Array *p_deposition_map=nullptr, float c_erosion=0.05f, float c_deposition=0.05f, int iterations=1)
Apply an algerbic formula based on the local gradient to perform erosion/deposition.
Definition hydraulic_algebric.cpp:74

Result

◆ hydraulic_algebric() [2/2]

void hmap::hydraulic_algebric ( Array & z,
float talus_ref,
int ir,
Array * p_bedrock = nullptr,
Array * p_erosion_map = nullptr,
Array * p_deposition_map = nullptr,
float c_erosion = 0.05f,
float c_deposition = 0.05f,
int iterations = 1 )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ hydraulic_benes() [1/2]

void hmap::hydraulic_benes ( Array & z,
Array * p_mask,
int iterations = 50,
Array * p_bedrock = nullptr,
Array * p_moisture_map = nullptr,
Array * p_erosion_map = nullptr,
Array * p_deposition_map = nullptr,
float c_capacity = 40.f,
float c_erosion = 0.2f,
float c_deposition = 0.8f,
float water_level = 0.005f,
float evap_rate = 0.01f,
float rain_rate = 0.5f )

Apply cell-based hydraulic erosion/deposition based on Benes et al. procedure.

See [Benes2002] and [Olsen2004].

Parameters
zInput array.
p_maskIntensity mask, expected in [0, 1] (applied as a post-processing).
iterationsNumber of iterations.
p_bedrockReference to the bedrock heightmap.
p_moisture_mapReference to the moisture map (quantity of rain), expected to be in [0, 1].
p_erosion_map[out]Reference to the erosion map, provided as an output field.
p_deposition_map[out] Reference to the deposition map, provided as an output field.
c_capacitySediment capacity.
c_erosionErosion coefficient.
c_depositionDeposition coefficient.
water_levelWater level.
evap_rateWater evaporation rate.
rain_rateRain relaxation rate.

Example

#include "highmap.hpp"
int main(void)
{
"hydraulic_benes is deprecated and will be removed at some point.");
glm::ivec2 shape = {256, 256};
glm::vec2 res = {2.f, 2.f};
int seed = 1;
auto z0 = z;
hmap::export_banner_png("ex_hydraulic_benes.png",
{z0, z},
true);
}
void hydraulic_benes(Array &z, Array *p_mask, int iterations=50, Array *p_bedrock=nullptr, Array *p_moisture_map=nullptr, Array *p_erosion_map=nullptr, Array *p_deposition_map=nullptr, float c_capacity=40.f, float c_erosion=0.2f, float c_deposition=0.8f, float water_level=0.005f, float evap_rate=0.01f, float rain_rate=0.5f)
Apply cell-based hydraulic erosion/deposition based on Benes et al. procedure.
Definition hydraulic_benes.cpp:212

Result

◆ hydraulic_benes() [2/2]

void hmap::hydraulic_benes ( Array & z,
int iterations = 50,
Array * p_bedrock = nullptr,
Array * p_moisture_map = nullptr,
Array * p_erosion_map = nullptr,
Array * p_deposition_map = nullptr,
float c_capacity = 40.f,
float c_erosion = 0.2f,
float c_deposition = 0.8f,
float water_level = 0.005f,
float evap_rate = 0.01f,
float rain_rate = 0.5f )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ hydraulic_blur()

void hmap::hydraulic_blur ( Array & z,
float radius,
float vmax,
float k_smoothing = 0.1f )

Apply cell-based hydraulic erosion using a nonlinear diffusion model.

Parameters
zInput array.
radiusGaussian filter radius (with respect to a unit domain).
vmaxMaximum elevation for the details.
k_smoothingSmoothing factor, if any.

Example

#include "highmap.hpp"
int main(void)
{
"hydraulic_blur is deprecated and will be removed at some point.");
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
auto z0 = z;
float vmax = 0.8f;
float radius = 0.1f;
float k_smoothing = 0.5f;
hmap::hydraulic_blur(z, vmax, radius, k_smoothing);
hmap::export_banner_png("ex_hydraulic_blur.png",
{z0, z},
true);
}
void hydraulic_blur(Array &z, float radius, float vmax, float k_smoothing=0.1f)
Apply cell-based hydraulic erosion using a nonlinear diffusion model.
Definition hydraulic_blur.cpp:16

Result

◆ hydraulic_diffusion()

void hmap::hydraulic_diffusion ( Array & z,
float c_diffusion,
float talus,
int iterations )

Apply cell-based hydraulic erosion using a nonlinear diffusion model.

See [Roering2001].

Parameters
zInput array.
c_diffusionDiffusion coefficient.
talusReference talus (must be higher than the maximum talus of the map).
iterationsNumber of iterations.

Example

#include "highmap.hpp"
int main(void)
{
"hydraulic_diffusion is deprecated and will be removed at some point.");
glm::ivec2 shape = {256, 256};
glm::vec2 res = {2.f, 2.f};
int seed = 1;
auto z0 = z;
float c_diffusion = 0.1f;
int iterations = 100;
auto dn = gradient_norm(z);
float talus_ref = 1.1f * dn.max();
hmap::hydraulic_diffusion(z, c_diffusion, talus_ref, iterations);
hmap::export_banner_png("ex_hydraulic_diffusion.png",
{z0, z},
true);
}
void hydraulic_diffusion(Array &z, float c_diffusion, float talus, int iterations)
Apply cell-based hydraulic erosion using a nonlinear diffusion model.
Definition hydraulic_diffusion.cpp:13

Result

◆ hydraulic_musgrave() [1/2]

void hmap::hydraulic_musgrave ( Array & z,
Array & moisture_map,
int iterations = 100,
float c_capacity = 1.f,
float c_erosion = 0.1f,
float c_deposition = 0.1f,
float water_level = 0.01f,
float evap_rate = 0.01f )

Apply cell-based hydraulic erosion/deposition of Musgrave et al. (1989).

A simple grid-based erosion technique was published by Musgrave, Kolb, and Mace in 1989 [Musgrave1989].

Parameters
zInput array.
moisture_mapMoisture map (quantity of rain), expected to be in [0, 1].
iterationsNumber of iterations.
c_capacitySediment capacity.
c_depositionDeposition coefficient.
c_erosionErosion coefficient.
water_levelWater level.
evap_rateWater evaporation rate.

Example

#include "highmap.hpp"
int main(void)
{
"hydraulic_musgrave is deprecated and will be removed at some point.");
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
auto z0 = z;
hmap::export_banner_png("ex_hydraulic_musgrave.png",
{z0, z},
true);
}
void hydraulic_musgrave(Array &z, Array &moisture_map, int iterations=100, float c_capacity=1.f, float c_erosion=0.1f, float c_deposition=0.1f, float water_level=0.01f, float evap_rate=0.01f)
Apply cell-based hydraulic erosion/deposition of Musgrave et al. (1989).
Definition hydraulic_musgrave.cpp:21

Result

◆ hydraulic_musgrave() [2/2]

void hmap::hydraulic_musgrave ( Array & z,
int iterations = 100,
float c_capacity = 1.f,
float c_erosion = 0.1f,
float c_deposition = 0.1f,
float water_level = 0.01f,
float evap_rate = 0.01f )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ hydraulic_stream() [1/2]

void hmap::hydraulic_stream ( Array & z,
float c_erosion,
float talus_ref,
const Array * p_bedrock = nullptr,
const Array * p_moisture_map = nullptr,
Array * p_erosion_map = nullptr,
int ir = 1,
float clipping_ratio = 10.f )

Apply hydraulic erosion based on a flow accumulation map.

Parameters
zInput array.
c_erosionErosion coefficient.
talus_refReference talus used to localy define the flow-partition exponent (small values of talus_ref will lead to thinner flow streams, see flow_accumulation_dinf).
p_bedrockLower elevation limit.
p_moisture_mapReference to the moisture map (quantity of rain), expected to be in [0, 1].
p_erosion_map[out]Reference to the erosion map, provided as an output field.
irKernel radius. If ir > 1, a cone kernel is used to carv channel flow erosion.
clipping_ratioFlow accumulation clipping ratio.

Example

#include "highmap.hpp"
int main(void)
{
"hydraulic_stream is deprecated and will be removed at some point.");
glm::ivec2 shape = {256, 256};
shape = {1024, 1024};
glm::vec2 kw = {2.f, 2.f};
int seed = 1;
auto z0 = z;
float c_erosion = 0.1f;
float talus_ref = 5.f / (float)shape.x;
int iradius = 64;
hmap::Array z_bedrock = hmap::local_min(z, iradius);
auto z1 = z;
hmap::hydraulic_stream(z1, c_erosion, talus_ref);
auto z2 = z;
int ir = 5;
auto erosion_map = hmap::Array(shape);
auto moisture_map = z;
c_erosion,
talus_ref,
&z_bedrock,
&moisture_map,
&erosion_map,
ir);
// log scale
auto z3 = z;
int deposition_ir = 32;
c_erosion = 0.2f;
hmap::gpu::hydraulic_stream_log(z3, c_erosion, talus_ref, deposition_ir);
z3.dump();
// multiscale log scale
auto z4 = z;
c_erosion,
talus_ref,
/* levels */ 3,
deposition_ir);
z4.dump();
hmap::export_banner_png("ex_hydraulic_stream0.png",
{z0, z1, z2, z3, z4},
true);
erosion_map.to_png("ex_hydraulic_stream1.png", hmap::Cmap::INFERNO);
}
void hydraulic_stream_log_multiscale(Array &z, float c_erosion, float talus_ref, int levels=3, int deposition_ir=32, float deposition_scale_ratio=1.f, float gradient_power=0.8f, float gradient_scaling_ratio=1.f, int gradient_prefilter_ir=16, float saturation_ratio=1.f, const Array *p_bedrock=nullptr, const Array *p_erodibility=nullptr, const Array *p_moisture_map=nullptr, Array *p_erosion_map=nullptr, Array *p_deposition_map=nullptr, Array *p_flow_map=nullptr, float mix=1.f, float warp=0.35f, std::uint32_t seed=1)
See hmap::hydraulic_stream_log_multiscale.
Definition hydraulic_stream_gpu.cpp:168
void hydraulic_stream_log(Array &z, float c_erosion, float talus_ref, int deposition_ir=32, float deposition_scale_ratio=1.f, float gradient_power=0.8f, float gradient_scaling_ratio=1.f, int gradient_prefilter_ir=16, float saturation_ratio=1.f, const Array *p_bedrock=nullptr, const Array *p_erodibility=nullptr, const Array *p_moisture_map=nullptr, Array *p_erosion_map=nullptr, Array *p_deposition_map=nullptr, Array *p_flow_map=nullptr)
See hmap::hydraulic_stream_log.
Definition hydraulic_stream_gpu.cpp:23
void hydraulic_stream(Array &z, float c_erosion, float talus_ref, const Array *p_bedrock=nullptr, const Array *p_moisture_map=nullptr, Array *p_erosion_map=nullptr, int ir=1, float clipping_ratio=10.f)
Apply hydraulic erosion based on a flow accumulation map.
Definition hydraulic_stream.cpp:26
Array local_min(const Array &array, int ir)
Return the local minima based on a maximum filter with a square kernel.
Definition local_metrics.cpp:105

Result

◆ hydraulic_stream() [2/2]

void hmap::hydraulic_stream ( Array & z,
const Array * p_mask,
float c_erosion,
float talus_ref,
const Array * p_bedrock = nullptr,
const Array * p_moisture_map = nullptr,
Array * p_erosion_map = nullptr,
int ir = 1,
float clipping_ratio = 10.f )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ hydraulic_stream_log() [1/2]

void hmap::hydraulic_stream_log ( Array & z,
float c_erosion,
float talus_ref,
int deposition_ir = 32,
float deposition_scale_ratio = 1.f,
float gradient_power = 0.8f,
float gradient_scaling_ratio = 1.f,
int gradient_prefilter_ir = 16,
float saturation_ratio = 1.f,
const Array * p_bedrock = nullptr,
const Array * p_erodibility = nullptr,
const Array * p_moisture_map = nullptr,
Array * p_erosion_map = nullptr,
Array * p_deposition_map = nullptr,
Array * p_flow_map = nullptr )

Apply hydraulic erosion based on a flow accumulation map, alternative formulation.

Parameters
zInput array representing the terrain elevation.
c_erosionErosion coefficient controlling the intensity of erosion.
talus_refReference talus used to locally define the flow-partition exponent. Small values lead to thinner flow streams (see flow_accumulation_dinf).
deposition_irKernel radius for sediment deposition. If greater than 1, a smoothing effect is applied.
deposition_scale_ratioScaling factor for sediment deposition.
gradient_powerExponent applied to the terrain gradient to control erosion intensity.
gradient_scaling_ratioScaling factor for gradient-based erosion.
gradient_prefilter_irKernel radius for pre-filtering the terrain gradient.
saturation_ratioRatio controlling the water saturation threshold for erosion processes.
p_bedrockPointer to an optional lower elevation limit.
p_moisture_mapPointer to the moisture map (rainfall quantity), expected to be in [0, 1].
p_erosion_map[out]Pointer to the erosion map, provided as an output field.
p_flow_map[out]Pointer to the flow accumulation map, provided as an output field.
irKernel radius. If ir > 1, a cone kernel is used to carve channel flow erosion.

Example

#include "highmap.hpp"
int main(void)
{
"hydraulic_stream is deprecated and will be removed at some point.");
glm::ivec2 shape = {256, 256};
shape = {1024, 1024};
glm::vec2 kw = {2.f, 2.f};
int seed = 1;
auto z0 = z;
float c_erosion = 0.1f;
float talus_ref = 5.f / (float)shape.x;
int iradius = 64;
hmap::Array z_bedrock = hmap::local_min(z, iradius);
auto z1 = z;
hmap::hydraulic_stream(z1, c_erosion, talus_ref);
auto z2 = z;
int ir = 5;
auto erosion_map = hmap::Array(shape);
auto moisture_map = z;
c_erosion,
talus_ref,
&z_bedrock,
&moisture_map,
&erosion_map,
ir);
// log scale
auto z3 = z;
int deposition_ir = 32;
c_erosion = 0.2f;
hmap::gpu::hydraulic_stream_log(z3, c_erosion, talus_ref, deposition_ir);
z3.dump();
// multiscale log scale
auto z4 = z;
c_erosion,
talus_ref,
/* levels */ 3,
deposition_ir);
z4.dump();
hmap::export_banner_png("ex_hydraulic_stream0.png",
{z0, z1, z2, z3, z4},
true);
erosion_map.to_png("ex_hydraulic_stream1.png", hmap::Cmap::INFERNO);
}

Result

◆ hydraulic_stream_log() [2/2]

void hmap::hydraulic_stream_log ( Array & z,
float c_erosion,
float talus_ref,
const Array * p_mask,
int deposition_ir = 32,
float deposition_scale_ratio = 1.f,
float gradient_power = 0.8f,
float gradient_scaling_ratio = 1.f,
int gradient_prefilter_ir = 16,
float saturation_ratio = 1.f,
const Array * p_bedrock = nullptr,
const Array * p_erodibility = nullptr,
const Array * p_moisture_map = nullptr,
Array * p_erosion_map = nullptr,
Array * p_deposition_map = nullptr,
Array * p_flow_map = nullptr )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ hydraulic_stream_log_multiscale() [1/2]

void hmap::hydraulic_stream_log_multiscale ( Array & z,
float c_erosion,
float talus_ref,
int levels = 3,
int deposition_ir = 32,
float deposition_scale_ratio = 1.f,
float gradient_power = 0.8f,
float gradient_scaling_ratio = 1.f,
int gradient_prefilter_ir = 16,
float saturation_ratio = 1.f,
const Array * p_bedrock = nullptr,
const Array * p_erodibility = nullptr,
const Array * p_moisture_map = nullptr,
Array * p_erosion_map = nullptr,
Array * p_deposition_map = nullptr,
Array * p_flow_map = nullptr,
float mix = 1.f,
float warp = 0.35f,
std::uint32_t seed = 1 )

Multiscale stream-power hydraulic erosion cascade.

Runs stream-power erosion over a geometric resolution ladder (coarsest first, up to z.shape). Coarse levels carve broad valleys and major drainage networks, while fine levels carve detailed tributaries.

Parameters
zHeightmap array to modify.
c_erosionErosion coefficient.
talus_refReference talus.
levelsNumber of resolution levels.
deposition_irDeposition smoothing radius at full resolution.
deposition_scale_ratioDeposition blend factor (applied at last scale).
gradient_powerPower applied to normalized gradient.
gradient_scaling_ratioGradient scaling weight.
gradient_prefilter_irGradient prefilter smoothing radius at full resolution.
saturation_ratioFlow saturation ratio.
p_bedrockOptional bedrock array bounding maximum erosion depth.
p_erodibilityOptional spatial erodibility multiplier array.
p_moisture_mapOptional moisture map.
p_erosion_mapOptional output erosion map.
p_deposition_mapOptional output deposition map.
p_flow_mapOptional output flow accumulation map.
mixInterpolation blend factor between levels.
warpDomain warp amplitude during upsampling.
seedRandom seed for domain warping noise.

◆ hydraulic_stream_log_multiscale() [2/2]

void hmap::hydraulic_stream_log_multiscale ( Array & z,
float c_erosion,
float talus_ref,
const Array * p_mask,
int levels = 3,
int deposition_ir = 32,
float deposition_scale_ratio = 1.f,
float gradient_power = 0.8f,
float gradient_scaling_ratio = 1.f,
int gradient_prefilter_ir = 16,
float saturation_ratio = 1.f,
const Array * p_bedrock = nullptr,
const Array * p_erodibility = nullptr,
const Array * p_moisture_map = nullptr,
Array * p_erosion_map = nullptr,
Array * p_deposition_map = nullptr,
Array * p_flow_map = nullptr,
float mix = 1.f,
float warp = 0.35f,
std::uint32_t seed = 1 )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ hydraulic_saleve() [1/3]

void hmap::hydraulic_saleve ( TerrainTriMesh & mesh,
const std::vector< float > & erodibility,
const std::vector< float > & max_slope,
float m_exp = 0.8f,
float uplift_rate = 1.f,
float tolerance = 1e-3f,
int max_iterations = 200,
float noise_strength = 0.f,
std::uint32_t seed = 0,
bool enable_post_slope_limiter = false,
float post_slope_limit = 0.f,
bool enable_post_smoothing = false )

Perform hydraulic erosion on a triangulated terrain mesh.

Iteratively updates elevations using a drainage model with uplift, slope constraints, and spatially varying erodibility.

Parameters
meshInput/output terrain mesh.
erodibilityPer-vertex erodibility coefficients.
max_slopePer-vertex maximum slope constraint.
m_expExponent controlling flow response.
uplift_rateConstant uplift applied each iteration.
toleranceConvergence threshold on elevation updates.
max_iterationsMaximum number of erosion iterations.

Example

Result

◆ hydraulic_saleve() [2/3]

Array hmap::hydraulic_saleve ( const Array & z,
std::uint32_t seed,
size_t control_points_count = 10000,
float m_exp = 0.8f,
float uplift_rate = 1.f,
float tolerance = 1e-3f,
int max_iterations = 200,
float smin = 0.f,
float smax = 6.f,
float strength = 0.5f,
bool scale_erodibility_with_z = true,
float erodibility_distrib_exp = 1.f,
float noise_strength = 0.f,
bool enable_post_slope_limiter = false,
float post_slope_limit = 0.f,
bool enable_post_smoothing = false,
InterpolationMethod2D interpolation_method = InterpolationMethod2D::ITP2D_DELAUNAY_GRADIENT,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr )

Apply hydraulic erosion to a heightmap using an adaptive mesh.

Converts the input heightmap to a triangulated mesh, performs erosion, and interpolates the result back to a grid.

Parameters
zInput heightmap.
seedRandom seed for point sampling.
control_points_countNumber of mesh control points.
m_expFlow response exponent.
uplift_rateConstant uplift per iteration.
toleranceConvergence threshold.
max_iterationsMaximum number of iterations.
sminMinimum slope constraint.
smaxMaximum slope constraint.
strengthBlending factor between original and eroded terrain.
scale_erodibility_with_zModulate erodibility with elevation.
erodibility_distrib_expExponent for erodibility distribution.
p_noise_xOptional X displacement field.
p_noise_yOptional Y displacement field.
Returns
Eroded heightmap.

Example

Result

◆ hydraulic_saleve() [3/3]

Array hmap::hydraulic_saleve ( const Array & z,
const Array * p_mask,
std::uint32_t seed,
size_t control_points_count = 10000,
float m_exp = 0.8f,
float uplift_rate = 1.f,
float tolerance = 1e-3f,
int max_iterations = 200,
float smin = 0.f,
float smax = 6.f,
float strength = 0.5f,
bool scale_erodibility_with_z = true,
float erodibility_distrib_exp = 1.f,
float noise_strength = 0.f,
bool enable_post_slope_limiter = false,
float post_slope_limit = 0.f,
bool enable_post_smoothing = false,
InterpolationMethod2D interpolation_method = InterpolationMethod2D::ITP2D_DELAUNAY_GRADIENT,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ depression_filling()

void hmap::depression_filling ( Array & z,
int iterations = 1000,
float epsilon = 1e-4f,
bool outflow_left = true,
bool outflow_right = true,
bool outflow_bottom = true,
bool outflow_top = true,
const UvTile & region = UvTile::dummy(),
ICommunicator & comm = SingleArrayComm::instance() )

Fill the depressions of the heightmap using the Planchon-Darboux algorithm.

Fill heightmap depressions to ensure that every cell can be connected to the boundaries following a downward slope [Planchon2002].

Parameters
zInput array.
iterationsNumber of iterations.
epsilonEpsilon slope parameter.
outflow_leftAllow outflow on left boundary (i = 0).
outflow_rightAllow outflow on right boundary (i = nx - 1).
outflow_bottomAllow outflow on bottom boundary (j = 0).
outflow_topAllow outflow on top boundary (j = ny - 1).
regionTile region metadata (for tiled execution).
commCommunicator for multi-tile synchronization.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 0;
auto z1 = z0;
auto z2 = z0;
// with BC: left / right / bottom / top
auto z3 = z0;
hmap::depression_filling(z3, 1000, 1e-4f, false, true, true, true);
auto z4 = z0;
false /* filter */,
false,
true,
true,
true);
hmap::export_banner_png("ex_depression_filling.png",
{z0, z1, z2, z3, z4},
true);
}
void depression_filling(Array &z, int iterations=1000, float epsilon=1e-4f, bool outflow_left=true, bool outflow_right=true, bool outflow_bottom=true, bool outflow_top=true, const UvTile &region=UvTile::dummy(), ICommunicator &comm=SingleArrayComm::instance())
Fill the depressions of the heightmap using the Planchon-Darboux algorithm.
Definition depression_filling.cpp:19
void depression_filling_priority_flood(Array &z, bool apply_post_filter=false, bool outflow_left=true, bool outflow_right=true, bool outflow_bottom=true, bool outflow_top=true, const UvTile &region=UvTile::dummy(), ICommunicator &comm=SingleArrayComm::instance())
Fill depressions in a heightmap using the Priority-Flood algorithm.
Definition depression_filling_priority_flood.cpp:23

Result

◆ depression_filling_priority_flood()

void hmap::depression_filling_priority_flood ( Array & z,
bool apply_post_filter = false,
bool outflow_left = true,
bool outflow_right = true,
bool outflow_bottom = true,
bool outflow_top = true,
const UvTile & region = UvTile::dummy(),
ICommunicator & comm = SingleArrayComm::instance() )

Fill depressions in a heightmap using the Priority-Flood algorithm.

Parameters
zInput heightmap array.
apply_post_filterApply Laplacian smoothing to deposition.
outflow_leftAllow outflow on left boundary (i = 0).
outflow_rightAllow outflow on right boundary (i = nx - 1).
outflow_bottomAllow outflow on bottom boundary (j = 0).
outflow_topAllow outflow on top boundary (j = ny - 1).
regionTile region metadata (for tiled execution).
commCommunicator for multi-tile synchronization.

◆ erosion_maps()

void hmap::erosion_maps ( Array & z_before,
Array & z_after,
Array & erosion_map,
Array & deposition_map,
float tolerance = 0.f )

Computes erosion and deposition delta maps from terrain states before and after erosion.

Parameters
z_beforeInput array (before erosion).
z_afterInput array (after erosion).
erosion_mapErosion map.
deposition_mapDeposition map.
toleranceTolerance for erosion / deposition definition.

Example

Result

◆ generate_bedrock()

Array hmap::generate_bedrock ( const Array & z,
float elevation_strength,
float slope_strength,
float slope_limit,
float zmin = 0.f,
float zmax = -1.f )

Generates a modified bedrock heightmap from an input elevation array.

This function adjusts elevations based on overall height and local slope:

  • Reduces values relative to the elevation range using elevation_strength.
  • Reduces values in steep areas using slope_strength and slope_limit.
Parameters
zInput elevation array.
elevation_strengthStrength of elevation-based adjustment.
slope_strengthStrength of slope-based adjustment.
slope_limitSlope threshold for slope-based adjustment.
zminMinimum elevation to consider (computed from z if zmin > zmax).
zmaxMaximum elevation to consider (computed from z if zmin > zmax).
Returns
Array Modified bedrock heightmap.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
shape = {1024, 1024};
glm::vec2 kw = {4.f, 4.f};
int seed = 0;
shape,
kw,
seed,
8,
0.f);
int nparticles = int(0.5f * shape.x * shape.y);
auto z1 = z0;
nparticles,
seed,
/* p_bedrock */ nullptr,
/* p_erodibility */ nullptr,
/* p_moisture_map */ nullptr,
/* p_elevation_shift */ nullptr,
/* p_erosion_map */ nullptr,
/* p_deposition_map */ nullptr,
/* c_capacity */ 10.f,
/* c_erosion */ 0.1f,
/* c_deposition */ 0.1f,
/* c_gravity */ 1.f,
/* drag_rate */ 0.001f,
/* evap_rate */ 0.001f,
/* talus_slope */ 2.f,
/* collapse_rate */ 0.25f,
/* iterations */ 1);
z1.dump();
auto z2 = z0;
auto zb2 = hmap::generate_bedrock(z2,
/* elevation_strength */ 0.05f,
/* slope_strength */ 0.f,
/* slope_limit */ 0.f);
hmap::gpu::hydraulic_particle(z2, nparticles, seed, &zb2);
auto z3 = z0;
auto zb3 = hmap::generate_bedrock(z3,
/* elevation_strength */ 0.f,
/* slope_strength */ 0.1f,
/* slope_limit */ 2.f / shape.x);
hmap::gpu::hydraulic_particle(z3, nparticles, seed, &zb3);
auto z4 = z0;
z4,
seed,
/* steps_per_level */ {16, 8, 4, 2, 1},
/* p_bedrock */ nullptr,
/* p_erodibility */ nullptr,
/* p_moisture_map */ nullptr,
/* p_elevation_shift */ nullptr,
/* p_erosion_map */ nullptr,
/* p_deposition_map */ nullptr,
/* particles_ratio */ 0.5f,
/* c_capacity */ 10.f,
/* c_erosion */ 0.05f,
/* c_deposition */ 0.05f,
/* c_inertia */ 0.0f,
/* c_gravity */ 1.f,
/* drag_rate */ 0.001f,
/* evap_rate */ 0.001f,
/* talus_slope */ 2.f,
/* collapse_rate */ 0.25f,
/* mix */ 0.8f);
// --- output
z0.dump("out0.png");
z1.dump("out1.png");
z2.dump("out2.png");
z3.dump("out3.png");
z4.dump("out4.png");
hmap::export_banner_png("ex_hydraulic_particle.png",
{z0, z1, z2, z3, z4},
true);
}
void hydraulic_particle_multiscale(Array &z, std::uint32_t seed, const std::vector< int > &steps_per_level={4, 2, 1}, const Array *p_bedrock=nullptr, const Array *p_erodibility=nullptr, const Array *p_moisture_map=nullptr, const Array *p_elevation_shift=nullptr, Array *p_erosion_map=nullptr, Array *p_deposition_map=nullptr, float particles_ratio=0.5f, float c_capacity=10.f, float c_erosion=0.05f, float c_deposition=0.05f, float c_inertia=0.01f, float c_gravity=1.f, float drag_rate=0.001f, float evap_rate=0.001f, float talus_slope=2.f, float collapse_rate=0.1f, float mix=1.f, float warp=0.35f)
Multiscale particle-based hydraulic erosion cascade.
Definition hydraulic_particle.cpp:170
void hydraulic_particle(Array &z, int nparticles, std::uint32_t seed, const Array *p_bedrock=nullptr, const Array *p_erodibility=nullptr, const Array *p_moisture_map=nullptr, const Array *p_elevation_shift=nullptr, Array *p_erosion_map=nullptr, Array *p_deposition_map=nullptr, float c_capacity=10.f, float c_erosion=0.05f, float c_deposition=0.05f, float c_inertia=0.01f, float c_gravity=1.f, float drag_rate=0.001f, float evap_rate=0.001f, float talus_slope=2.f, float collapse_rate=0.1f, int iterations=1)
Simulates hydraulic erosion on a heightmap using particle-based flow.
Definition hydraulic_particle.cpp:23
Array bulkify(const Array &z, const PrimitiveType &primitive_type, float amp=1.f, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit())
Applies a primitive-based displacement to an array.
Definition bulkify.cpp:11
@ PRIM_CONE_SMOOTH
Definition functions.hpp:27
Array generate_bedrock(const Array &z, float elevation_strength, float slope_strength, float slope_limit, float zmin=0.f, float zmax=-1.f)
Generates a modified bedrock heightmap from an input elevation array.
Definition generate_bedrock.cpp:12

Result

◆ hydraulic_mise() [1/2]

void hmap::hydraulic_mise ( Array & z,
const MiseParams & params = MiseParams(),
const Array * p_bedrock = nullptr,
const Array * p_erodibility = nullptr,
const Array * p_moisture_map = nullptr,
const Array * p_outlet = nullptr,
Array * p_sediment = nullptr,
Array * p_flow = nullptr,
Array * p_erosion_map = nullptr,
Array * p_deposition_map = nullptr )

Simulates multiscale implicit stream-power hydraulic erosion (MISE).

Adapted from MISE by Leonhard (https://github.com/Leonhardmaster2).

Parameters
zHeightmap array to be eroded in-place.
paramsSolver parameters.
p_bedrockOptional bedrock array bounding maximum erosion depth.
p_erodibilityOptional spatial erodibility multiplier array.
p_moisture_mapOptional precipitation / moisture weight map.
p_outletOptional outlet mask (>0 flags fixed base-level cells).
p_sedimentOptional output array receiving loose sediment thickness.
p_flowOptional output array receiving normalized drainage flow area.
p_erosion_mapOptional output array receiving erosion delta (z_before - z, >= 0).
p_deposition_mapOptional output array receiving deposition delta (z - z_before, >= 0).

Example

#include <iostream>
#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {512, 512};
glm::vec2 kw = {3.f, 3.f};
int seed = 42;
// --- Initial heightmap generation
hmap::Array z0 = z;
// --- Mise erosion solver configuration
params.strength = 0.6f;
params.area_exp = 0.45f;
params.talus = 3.2f;
params.debris = 200.f;
params.deposition_rate = 1.f;
params.base_res = 128;
params.seed = seed;
hmap::Array sediment;
hmap::Array erosion_map;
hmap::Array deposition_map;
// run multiscale implicit stream-power erosion
params,
nullptr,
nullptr,
nullptr,
nullptr,
&sediment,
&flow,
&erosion_map,
&deposition_map);
// --- Output and visualization
std::cout << "original z range: [" << z0.min() << ", " << z0.max() << "]\n";
std::cout << "eroded z range: [" << z.min() << ", " << z.max() << "]\n";
std::cout << "sediment max: " << sediment.max() << "\n";
std::cout << "erosion max: " << erosion_map.max() << "\n";
std::cout << "deposition max: " << deposition_map.max() << "\n";
// export before/after comparison banner
hmap::export_banner_png("ex_hydraulic_mise.png",
{z0, z, sediment, flow},
true);
return 0;
}
void hydraulic_mise(Array &z, const MiseParams &params=MiseParams(), const Array *p_bedrock=nullptr, const Array *p_erodibility=nullptr, const Array *p_moisture_map=nullptr, const Array *p_outlet=nullptr, Array *p_sediment=nullptr, Array *p_flow=nullptr, Array *p_erosion_map=nullptr, Array *p_deposition_map=nullptr)
Simulates multiscale implicit stream-power hydraulic erosion (MISE).
Definition hydraulic_mise.cpp:415
Parameters for the MISE (Multiscale Implicit Stream-power Erosion) solver.
Definition erosion_parameters.hpp:19
float strength
Definition erosion_parameters.hpp:22
float area_exp
Definition erosion_parameters.hpp:23
std::uint32_t seed
Definition erosion_parameters.hpp:68
int base_res
Definition erosion_parameters.hpp:56
float talus
Definition erosion_parameters.hpp:30
float deposition_rate
Definition erosion_parameters.hpp:39
float debris
Definition erosion_parameters.hpp:29

Result

◆ hydraulic_mise() [2/2]

void hmap::hydraulic_mise ( Array & z,
const Array * p_mask,
const MiseParams & params = MiseParams(),
const Array * p_bedrock = nullptr,
const Array * p_erodibility = nullptr,
const Array * p_moisture_map = nullptr,
const Array * p_outlet = nullptr,
Array * p_sediment = nullptr,
Array * p_flow = nullptr,
Array * p_erosion_map = nullptr,
Array * p_deposition_map = nullptr )

Simulates multiscale implicit stream-power hydraulic erosion (MISE) with an intensity mask.

Parameters
zHeightmap array to be eroded in-place.
p_maskIntensity mask in [0, 1] used for blending post-erosion.
paramsSolver parameters.
p_bedrockOptional bedrock array bounding maximum erosion depth.
p_erodibilityOptional spatial erodibility multiplier array.
p_moisture_mapOptional precipitation / moisture weight map.
p_outletOptional outlet mask (>0 flags fixed base-level cells).
p_sedimentOptional output array receiving loose sediment thickness.
p_flowOptional output array receiving normalized drainage flow area.
p_erosion_mapOptional output array receiving erosion delta (z_before - z, >= 0).
p_deposition_mapOptional output array receiving deposition delta (z - z_before, >= 0).

◆ export_asset() [1/2]

bool hmap::export_asset ( const std::string & fname,
const Array & array,
MeshType mesh_type = MeshType::TRI,
AssetExportFormat export_format = AssetExportFormat::GLB2,
float elevation_scaling = 0.2f,
const std::string & texture_fname = "",
const std::string & normal_map_fname = "",
float max_error = 5e-4f,
bool fit_boundaries = false )

Exports a heightmap to various 3D file formats.

This function exports the input heightmap array as a 3D asset in the specified format. The export can include different mesh types, elevation scaling, and optional texture and normal maps. The function supports optimized Delaunay triangulation for mesh generation, with a configurable maximum error.

Parameters
fnameThe name of the file to which the 3D asset will be exported.
arrayThe input heightmap array to be converted into a 3D asset.
mesh_typeThe type of mesh to generate (see MeshType).
export_formatThe format in which to export the asset (see AssetExportFormat).
elevation_scalingA scaling factor applied to the elevation values of the heightmap. Default is 0.2f.
texture_fnameThe name of the texture file to be applied to the asset (optional).
normal_map_fnameThe name of the normal map file to be applied to the asset (optional).
max_errorThe maximum allowable error for optimized Delaunay triangulation. Default is 5e-4f.
fit_boundariesIf true, domain coordinates are scaled to [0, 1] x [0, 1]. Default is false (domain scaled to [0, 1 - 1/shape.x] x [0, 1 - 1/shape.y]).
Returns
true if the export is successful, false otherwise.

◆ export_asset() [2/2]

bool hmap::export_asset ( const std::string & fname,
const Array & array,
const Array & mask,
AssetExportFormat export_format = AssetExportFormat::GLB2,
float elevation_scaling = 0.2f,
const std::string & texture_fname = "",
const std::string & normal_map_fname = "",
bool fit_boundaries = false )

◆ export_points_to_ply()

void hmap::export_points_to_ply ( const std::string & fname,
const std::vector< float > & x,
const std::vector< float > & y,
const std::vector< float > & z,
const std::map< std::string, std::vector< float > > & custom_fields = {} )

Exports 3D points with optional custom fields to an ASCII PLY file.

This function writes vertex data (x, y, z) and optional additional per-point attributes to a PLY file in ASCII format. Each key in custom_fields defines a new property in the PLY header, and its associated vector provides per-point values for that property.

Parameters
fnameThe output file name.
xVector of x coordinates.
yVector of y coordinates.
zVector of z coordinates.
custom_fieldsA map of custom field names to their per-point float values.

Example

#include "highmap.hpp"
int main(void)
{
int npts = 8;
std::uint32_t seed = 0;
hmap::Cloud cloud = hmap::Cloud(npts, seed);
// create custom properties (optional)
std::map<std::string, std::vector<float>> custom_fields;
for (int k = 0; k < npts; ++k)
{
custom_fields["some_field"].push_back(float(k));
custom_fields["custom_prop"].push_back(float(k * k));
}
cloud.get_x(),
cloud.get_y(),
cloud.get_values(),
custom_fields);
}
void export_points_to_ply(const std::string &fname, const std::vector< float > &x, const std::vector< float > &y, const std::vector< float > &z, const std::map< std::string, std::vector< float > > &custom_fields={})
Exports 3D points with optional custom fields to an ASCII PLY file.
Definition export_points_to_ply.cpp:16

◆ write_raw_16bit()

void hmap::write_raw_16bit ( const std::string & fname,
const Array & array )

Exports an array to a 16-bit 'raw' file format, commonly used for Unity terrain imports.

This function saves the input array to a file in a 16-bit 'raw' format, which is suitable for importing heightmaps into Unity or other applications that support this format. The array values are converted and written to the file specified by fname.

Parameters
fnameThe name of the file to which the array will be exported.
arrayThe input array containing the data to be exported.

◆ export_as_ascii()

std::string hmap::export_as_ascii ( const Array & array,
const glm::ivec2 & export_shape = {64, 64},
const std::string chars_map = " .:-=+*#%@" )

Export a 2D array as an ASCII-art string representation.

This function rescales the input array to a given export resolution, remaps its values to the [0,1] range, and then converts each value to a character from a user-provided character map. The characters are arranged row by row to form a textual representation of the array, similar to rendering a heightmap in ASCII.

Parameters
arrayThe input 2D array to be exported.
export_shapeThe desired shape (width, height) of the ASCII output.
chars_mapA string containing characters ordered from "low" to "high" intensity. For example: " .:-=+*#%@"
Returns
A string containing the ASCII-art representation of the array.
Note
The function resamples the array using nearest-neighbor interpolation.
The y-axis is flipped so that higher indices appear lower in the text output.

◆ export_as_cubemap()

void hmap::export_as_cubemap ( const std::string & fname,
const Array & z,
int cubemap_resolution = 128,
float overlap = 0.25f,
int ir = 16,
Cmap cmap = static_cast<Cmap>(0),
bool splitted = false,
Array * p_cubemap = nullptr )

Exports a 2D array as a cubemap texture with continuity enforcement and overlapping regions.

This function generates a cubemap texture from the input array z, resamples the data to fit the cubemap resolution with optional overlapping regions, and ensures seamless transitions between the six faces of the cubemap. The cubemap can either be saved as a single texture or split into individual face textures.

Parameters
fnameOutput file name or base name for the cubemap files.
zInput 2D array representing the data to be converted into a cubemap.
cubemap_resolutionResolution (width and height) of each individual face of the cubemap.
overlapFraction (0 to 1) of overlap between adjacent faces to ensure smooth transitions.
irRadius parameter for smoothing at triple corners.
cmapColormap to be applied when exporting the textures.
splittedIf true, exports each face of the cubemap as a separate image; otherwise, exports the entire cubemap as a single texture.
p_cubemapPointer to an optional output array where the final cubemap data will be stored.

The generated cubemap maintains continuity between faces, adjusting values at overlapping regions and corners using smooth transitions. If the splitted flag is set, six individual PNG images are generated for the cubemap faces with appropriate suffixes appended to the base name. Otherwise, the entire cubemap is exported as a single texture file.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {1024, 1024};
glm::vec2 res = {4.f, 4.f};
int seed = 0;
int cubemap_resolution = shape.x / 4;
float overlap = 0.25f;
int ir = 16;
bool splitted = false;
hmap::export_as_cubemap("ex_export_as_cubemap.png",
z,
cubemap_resolution,
overlap,
ir,
cmap,
splitted);
}
Cmap
Enumeration for different colormap types.
Definition colormaps.hpp:83
void export_as_cubemap(const std::string &fname, const Array &z, int cubemap_resolution=128, float overlap=0.25f, int ir=16, Cmap cmap=static_cast< Cmap >(0), bool splitted=false, Array *p_cubemap=nullptr)
Exports a 2D array as a cubemap texture with continuity enforcement and overlapping regions.
Definition export_as_cubemap.cpp:71

Result

◆ export_banner_png()

void hmap::export_banner_png ( const std::string & fname,
const std::vector< Array > & arrays,
int cmap,
bool hillshading = false,
bool normalize_arrays = false )

Exports a set of arrays as a banner PNG image file.

This function takes a vector of arrays and exports them as a single banner PNG image. The arrays are displayed side by side in the image, using the specified colormap cmap. Optionally, hillshading can be applied to enhance the visual representation of the data.

Parameters
fnameThe name of the file to which the banner image will be exported.
arraysA vector of arrays to be included in the banner image.
cmapAn integer representing the colormap to be applied to the arrays.
hillshadingA boolean flag to activate hillshading for enhanced visual depth. Default is false.

◆ export_image() [1/5]

bool hmap::export_image ( const Array & array,
const std::string & fname,
const ImageWriterConfig & config = {} )

Exports an array using the generic ImageWriter pipeline.

Parameters
arrayInput 2D array.
fnameOutput file or directory path.
configOptional writer configuration.
Returns
True if successful, false otherwise.

◆ export_image() [2/5]

bool hmap::export_image ( const VirtualArray & va,
const std::string & fname,
const ImageWriterConfig & config = {} )

Exports a VirtualArray incrementally using the generic ImageWriter pipeline.

Parameters
vaInput VirtualArray.
fnameOutput file or directory path.
configOptional writer configuration.
Returns
True if successful, false otherwise.

◆ export_image() [3/5]

bool hmap::export_image ( const VirtualArray & va,
const std::string & fname,
const ImageWriterConfig & config,
const ComputeMode & cm )

Exports a VirtualArray incrementally with custom compute mode.

Parameters
vaInput VirtualArray.
fnameOutput file or directory path.
configWriter configuration.
cmCompute mode for tile processing.
Returns
True if successful, false otherwise.

◆ export_image() [4/5]

bool hmap::export_image ( const VirtualTexture & vt,
const std::string & fname,
const ImageWriterConfig & config = {} )

Exports a VirtualTexture incrementally using the generic ImageWriter pipeline.

Parameters
vtInput VirtualTexture.
fnameOutput file or directory path.
configOptional writer configuration.
Returns
True if successful, false otherwise.

◆ export_image() [5/5]

bool hmap::export_image ( const VirtualTexture & vt,
const std::string & fname,
const ImageWriterConfig & config,
const ComputeMode & cm )

Exports a VirtualTexture incrementally with custom compute mode.

Parameters
vtInput VirtualTexture.
fnameOutput file or directory path.
configWriter configuration.
cmCompute mode for tile processing.
Returns
True if successful, false otherwise.

◆ export_virtual_array() [1/4]

bool hmap::export_virtual_array ( const VirtualArray & va,
ImageWriter & writer )

Streams a VirtualArray tile-by-tile into an already opened ImageWriter.

Parameters
vaInput VirtualArray.
writerReference to target ImageWriter.
Returns
True if successful, false otherwise.

◆ export_virtual_array() [2/4]

bool hmap::export_virtual_array ( const VirtualArray & va,
ImageWriter & writer,
const ComputeMode & cm )

Streams a VirtualArray tile-by-tile into an already opened ImageWriter with custom compute mode.

Parameters
vaInput VirtualArray.
writerReference to target ImageWriter.
cmCompute mode for tile processing.
Returns
True if successful, false otherwise.

◆ export_virtual_array() [3/4]

bool hmap::export_virtual_array ( const VirtualTexture & vt,
ImageWriter & writer )

Streams a VirtualTexture tile-by-tile into an already opened ImageWriter.

Parameters
vtInput VirtualTexture.
writerReference to target ImageWriter.
Returns
True if successful, false otherwise.

◆ export_virtual_array() [4/4]

bool hmap::export_virtual_array ( const VirtualTexture & vt,
ImageWriter & writer,
const ComputeMode & cm )

Streams a VirtualTexture tile-by-tile into an already opened ImageWriter with custom compute mode.

Parameters
vtInput VirtualTexture.
writerReference to target ImageWriter.
cmCompute mode for tile processing.
Returns
True if successful, false otherwise.

◆ export_normal_map_png()

void hmap::export_normal_map_png ( const std::string & fname,
const Array & array,
int depth = CV_8U )

Exports the heightmap normal map as an 8-bit PNG file.

This function generates a normal map from the input heightmap array and exports it as an 8-bit PNG image. The normal map can be used in 3D rendering engines to create realistic lighting and shading effects.

Parameters
fnameThe name of the file to which the normal map will be exported.
arrayThe input heightmap array from which the normal map is derived.
depthThe depth of the PNG image, e.g., CV_8U for 8-bit or CV_16U for 16-bit. Default is CV_8U.

Example

#include "highmap.hpp"
int main(void)
{
const glm::ivec2 shape = {512, 512};
const glm::vec2 res = {1.f, 4.f};
int seed = 0;
// create Array from png
hmap::export_normal_map_png("ex_export_normal_map0.png", z1, CV_8U);
hmap::export_normal_map_png("ex_export_normal_map1.png", z1, CV_16U);
}
void export_normal_map_png(const std::string &fname, const Array &array, int depth=CV_8U)
Exports the heightmap normal map as an 8-bit PNG file.
Definition export_normal_map.cpp:15

◆ export_splatmap_png()

void hmap::export_splatmap_png ( const std::string & fname,
const Array * p_r,
const Array * p_g = nullptr,
const Array * p_b = nullptr,
const Array * p_a = nullptr,
int depth = CV_8U )

Exports four arrays as an RGBA PNG splatmap.

This function combines four input arrays, representing the red (R), green (G), blue (B), and alpha (A) channels, into a single RGBA PNG image. The resulting splatmap can be used in applications like terrain texturing. The PNG image is saved to the specified file name fname. Channels G, B, and A are optional; if not provided, they will default to zero.

Parameters
fnameThe name of the file to which the RGBA splatmap will be exported.
p_rPointer to the array representing the red (R) channel.
p_gPointer to the array representing the green (G) channel. Default is nullptr.
p_bPointer to the array representing the blue (B) channel. Default is nullptr.
p_aPointer to the array representing the alpha (A) channel. Default is nullptr.
depthThe depth of the PNG image, e.g., CV_8U for 8-bit or CV_16U for 16-bit. Default is CV_8U.

Example

#include "highmap.hpp"
int main(void)
{
const glm::ivec2 shape = {512, 512};
const glm::vec2 res = {4.f, 4.f};
int seed = 2;
hmap::Array zr = hmap::noise(hmap::NoiseType::PERLIN, shape, res, seed++);
hmap::Array zg = hmap::noise(hmap::NoiseType::PERLIN, shape, res, seed++);
hmap::Array zb = hmap::noise(hmap::NoiseType::PERLIN, shape, res, seed++);
hmap::Array za = hmap::noise(hmap::NoiseType::PERLIN, shape, res, seed++);
hmap::export_banner_png("ex_export_splatmap_png_16bit0.png",
{zr, zg, zb, za},
hmap::export_splatmap_png("ex_export_splatmap_png_16bit1.png",
&zr,
&zg,
&zb,
&za,
CV_16U);
}
void export_splatmap_png(const std::string &fname, const Array *p_r, const Array *p_g=nullptr, const Array *p_b=nullptr, const Array *p_a=nullptr, int depth=CV_8U)
Exports four arrays as an RGBA PNG splatmap.
Definition export_splatmap.cpp:34
@ GRAY
Definition colormaps.hpp:85

Result

◆ export_tiled()

void hmap::export_tiled ( const std::string & fname_radical,
const std::string & fname_extension,
const Array & array,
const glm::ivec2 & tiling,
int leading_zeros = 0,
int depth = CV_8U,
bool overlapping_edges = false,
bool reverse_tile_y_indexing = false )

Exports a 2D array as a set of grayscale PNG image tiles.

This function divides a given 2D array into smaller rectangular tiles and saves each tile as a grayscale PNG image file. Tiles are named using a combination of the provided file name radical, tile indices, and file extension.

Parameters
fname_radicalBase name (radical) for output image files.
fname_extensionFile extension to use for exported images (e.g., "png").
arrayThe input 2D array to be tiled and exported.
tilingA 2D vector specifying the number of tiles in the x and y directions.
leading_zerosNumber of digits used to pad the tile indices in the filename.
depthBit depth of the output PNG images (commonly 8 or 16).
overlapping_edgesIf true, each tile includes an extra row/column from neighboring tiles (for overlap).
reverse_tile_y_indexingIf true, Y tile indices are reversed (tile 0 is at the top).

Each tile is extracted using slicing, adjusted for overlap if specified, and then exported as an individual image file named with its tile indices. For example, an output file might be named radical_01_03.png.

Example

#include "highmap.hpp"
int main(void)
{
const glm::ivec2 shape = {763, 451};
const glm::vec2 res = {1.f, 4.f};
int seed = 0;
glm::ivec2 tiling = {4, 3};
std::string fname_radical = "ex_export_tiled";
std::string fname_extension = "png";
int leading_zeros = 2;
int depth = CV_16U;
bool overlapping_edges = false;
bool reverse_tile_y_indexing = false;
z.to_png("ex_export_tiled.png", hmap::Cmap::JET);
hmap::export_tiled(fname_radical,
fname_extension,
z,
tiling,
leading_zeros,
depth,
overlapping_edges,
reverse_tile_y_indexing);
}
void export_tiled(const std::string &fname_radical, const std::string &fname_extension, const Array &array, const glm::ivec2 &tiling, int leading_zeros=0, int depth=CV_8U, bool overlapping_edges=false, bool reverse_tile_y_indexing=false)
Exports a 2D array as a set of grayscale PNG image tiles.
Definition export_tiled.cpp:46

◆ read_to_array()

Array hmap::read_to_array ( const std::string & fname,
bool flip_j = false,
bool remap = true )

Reads an image file and converts it to a 2D array.

This function uses the OpenCV imread function to load an image from the specified file. The supported file formats are those recognized by OpenCV's imread function, such as JPEG, PNG, BMP, and others. If the image is in color, it is automatically converted to grayscale using the built-in OpenCV codec converter. This conversion process may introduce artifacts depending on the image's original format and content.

Parameters
fnameThe name of the image file to be read.
Returns
Array A 2D array containing the pixel values of the grayscale image.

◆ export_usd()

bool hmap::export_usd ( const std::string & fname,
const Array & elevation = {},
const std::vector< Forest > & forests = {},
const std::vector< RockField > & rock_fields = {},
const std::vector< Cloud > & clouds = {},
const std::vector< Path > & paths = {},
MeshType mesh_type = MeshType::TRI,
float elevation_scaling = 0.2f,
const std::string & texture_fname = "",
const std::string & normal_map_fname = "",
float max_error = 5e-4f,
bool fit_boundaries = false )

Exports a composite scene (terrain, forests, rock fields, clouds, and paths) to Universal Scene Description (USD).

Generates a USD stage (.usda, .usdc, or .usdz) containing:

  • Optional terrain mesh from elevation (with optional UV coordinates and elevation scaling)
  • Optional point collections from forests grouped by species as UsdGeomPoints with tree radii (widths)
  • Optional point collections from rock_fields grouped by class as UsdGeomPoints with rock radii (widths)
  • Optional point collections from clouds as UsdGeomPoints
  • Optional polylines/splines from paths as UsdGeomBasisCurves
Parameters
fnameOutput file name (.usda, .usdc, or .usdz).
elevationOptional heightmap array representing terrain elevation.
forestsOptional vector of Forest containers whose trees are exported as points.
rock_fieldsOptional vector of RockField containers whose rocks are exported as points.
cloudsOptional vector of Cloud objects to export as points primitives.
pathsOptional vector of Path objects to export as curve primitives.
mesh_typeThe type of mesh to generate for the terrain.
elevation_scalingElevation scaling factor applied to the terrain and 3D points.
texture_fnameOptional diffuse texture filename.
normal_map_fnameOptional normal map filename.
max_errorMaximum error for optimized Delaunay triangulation.
fit_boundariesScale domain coordinates to [0, 1].
Returns
true if export succeeded, false otherwise.

Example

#include <iostream>
#include <vector>
#include "highmap.hpp"
int main(void)
{
// --- Terrain heightmap
glm::ivec2 shape = {128, 128};
glm::vec2 kv = {2.f, 2.f};
int seed = 42;
hmap::Array terrain = hmap::noise(hmap::NoiseType::SIMPLEX2, shape, kv, seed);
hmap::remap(terrain);
// --- Clouds (scattered 3D point features)
hmap::Cloud trees(50, seed + 1);
hmap::Cloud rocks(30, seed + 2);
std::vector<hmap::Cloud> clouds = {trees, rocks};
// --- Paths (polylines / roads / rivers)
std::vector<hmap::Point> road_points = {hmap::Point(0.1f, 0.1f, 0.2f),
hmap::Point(0.3f, 0.4f, 0.35f),
hmap::Point(0.6f, 0.5f, 0.45f),
hmap::Point(0.9f, 0.85f, 0.25f)};
hmap::Path road(road_points);
std::vector<hmap::Point> river_points = {hmap::Point(0.05f, 0.85f, 0.15f),
hmap::Point(0.45f, 0.55f, 0.22f),
hmap::Point(0.85f, 0.15f, 0.1f)};
hmap::Path river(river_points);
std::vector<hmap::Path> paths = {road, river};
// --- Export composite scenes to USD formats
std::cout << "Exporting to scene.usda (ASCII USD)...\n";
hmap::export_usd("scene.usda",
terrain,
{},
{},
clouds,
paths,
0.25f);
std::cout << "Exporting to scene.usdc (Binary Crate USD)...\n";
hmap::export_usd("scene.usdc",
terrain,
{},
{},
clouds,
paths,
0.25f);
std::cout << "Exporting to scene_opt.usda (Delaunay optimized terrain)...\n";
hmap::export_usd("scene_opt.usda",
terrain,
{},
{},
clouds,
paths,
0.25f,
"",
"",
1e-2f);
std::cout << "USD export completed successfully.\n";
return 0;
}
bool export_usd(const std::string &fname, const Array &elevation={}, const std::vector< Forest > &forests={}, const std::vector< RockField > &rock_fields={}, const std::vector< Cloud > &clouds={}, const std::vector< Path > &paths={}, MeshType mesh_type=MeshType::TRI, float elevation_scaling=0.2f, const std::string &texture_fname="", const std::string &normal_map_fname="", float max_error=5e-4f, bool fit_boundaries=false)
Exports a composite scene (terrain, forests, rock fields, clouds, and paths) to Universal Scene Descr...
Definition export_usd.cpp:344
@ SIMPLEX2
OpenSimplex2.
Definition functions.hpp:72
@ TRI_OPTIMIZED
Triangles with optimized Delaunay triangulation.
Definition asset.hpp:36
@ TRI
Triangle elements.
Definition asset.hpp:37

◆ compute_poi_suitability_field()

Array hmap::compute_poi_suitability_field ( const Array & heightmap,
PoiType type,
const PoiGenerationOptions & options )

Computes a normalized suitability/score field in [0, 1] for a given terrain feature type.

Parameters
heightmapInput terrain heightmap array.
typeTarget point of interest type.
optionsGeneration options controlling neighborhood scale and parameters.
Returns
Array Suitability field in [0, 1].

◆ generate_points_of_interest_cloud()

Cloud hmap::generate_points_of_interest_cloud ( const Array & heightmap,
PoiType type,
const PoiGenerationOptions & options )

Generates a Cloud of points of interest from a heightmap.

Parameters
heightmapInput terrain heightmap array.
typeTarget point of interest type.
optionsGeneration options.
Returns
Cloud Point cloud carrying the score as the point value.

◆ generate_points_of_interest()

std::vector< PointOfInterest > hmap::generate_points_of_interest ( const Array & heightmap,
PoiType type,
const PoiGenerationOptions & options )

Generates a list of PointOfInterest objects from a heightmap.

Parameters
heightmapInput terrain heightmap array.
typeTarget point of interest type.
optionsGeneration options.
Returns
std::vector<PointOfInterest> List of extracted points of interest.

◆ generate_points_of_interest_positions()

std::vector< glm::vec2 > hmap::generate_points_of_interest_positions ( const Array & heightmap,
PoiType type,
const PoiGenerationOptions & options )

Generates 2D positions of points of interest from a heightmap.

Parameters
heightmapInput terrain heightmap array.
typeTarget point of interest type.
optionsGeneration options.
Returns
std::vector<glm::vec2> List of 2D positions.

◆ generate_points_from_score_field()

std::vector< PointOfInterest > hmap::generate_points_from_score_field ( const Array & score_field,
const Array & heightmap,
const PoiGenerationOptions & options,
PoiType type = PoiType::CUSTOM )

Generates a list of PointOfInterest objects from a precomputed score field.

Parameters
score_fieldPrecomputed suitability / score field in [0, 1].
heightmapInput terrain heightmap used to sample elevation, slope, and aspect.
optionsGeneration options.
typeOptional classification type to assign to the points.
Returns
std::vector<PointOfInterest> List of extracted points of interest.

◆ connected_components()

Array hmap::connected_components ( const Array & array,
float surface_threshold = 0.f,
float background_value = 0.f,
std::map< float, float > * p_surfaces = nullptr,
std::map< float, std::array< float, 2 > > * p_centroids = nullptr )

Identifies and labels connected components within a binary or labeled array, with optional filtering by size.

◆ geomorphons()

Array hmap::geomorphons ( const Array & array,
int irmin,
int irmax,
float epsilon )

Classifies terrain into geomorphological features based on the geomorphons method.

◆ kmeans_clustering2()

Array hmap::kmeans_clustering2 ( const Array & array1,
const Array & array2,
int nclusters,
std::vector< Array > * p_scoring = nullptr,
Array * p_aggregate_scoring = nullptr,
glm::vec2 weights = {1.f, 1.f},
std::uint32_t seed = 1 )

Performs k-means clustering on two input arrays, grouping similar data points into clusters.

◆ kmeans_clustering3()

Array hmap::kmeans_clustering3 ( const Array & array1,
const Array & array2,
const Array & array3,
int nclusters,
std::vector< Array > * p_scoring = nullptr,
Array * p_aggregate_scoring = nullptr,
glm::vec3 weights = {1.f, 1.f, 1.f},
std::uint32_t seed = 1 )

Performs k-means clustering on three input arrays.

◆ bulkify()

Array hmap::bulkify ( const Array & z,
const PrimitiveType & primitive_type,
float amp = 1.f,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
glm::vec2 center = {0.5f, 0.5f},
const UvRect & uv_rect = UvRect::unit() )

Applies a primitive-based displacement to an array.

Adds a scaled primitive pattern (optionally perturbed by noise) to the input array.

Parameters
zInput array.
primitive_typeType of primitive to generate.
ampAmplitude scaling factor.
p_noise_xOptional noise array for X perturbation (can be nullptr).
p_noise_yOptional noise array for Y perturbation (can be nullptr).
centerCenter of the primitive.
bboxBounding box of the primitive.
Returns
Resulting array after applying the displacement.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
hmap::export_banner_png("ex_bulkify.png", {z, zb}, hmap::Cmap::TERRAIN, true);
}
@ PRIM_CONE
Definition functions.hpp:26

Result

◆ canyonize() [1/2]

void hmap::canyonize ( Array & array,
std::uint32_t seed = 0,
int nlevels = 6,
float convex_ratio = 3.0f,
float gamma_convex = 3.0f,
float gamma_concave = 0.3f,
float clamp_min_val = -std::numeric_limits<float>::infinity(),
float k_smooth = 0.1f,
float noise_ratio = 0.2f,
const Array * p_noise = nullptr,
float vmin = 1.f,
float vmax = 0.f )

Applies a canyonize filter to a heightmap.

Flattens the bottom with smooth minimum clamping and applies stratification with alternating concave and convex power laws across elevation intervals, with optional strata elevation noise and lateral noise modulation.

Parameters
arrayThe array of values to modify.
seedRandom seed for strata level fluctuation.
nlevelsNumber of stratification levels.
convex_ratioHeight ratio of convex strata relative to concave strata (e.g., 3.0).
gamma_convexPower law exponent for convex levels (> 1, e.g., 3.0).
gamma_concavePower law exponent for concave levels (< 1, e.g., 0.3).
clamp_min_valElevation threshold for flattening the canyon bottom.
k_smoothSmoothing factor for clamp_min_smooth (0 for hard clamp).
noise_ratioRatio of random elevation variation on strata levels.
p_noiseOptional noise array for lateral modulation.
vminMinimum elevation bounds (auto if vmin >= vmax).
vmaxMaximum elevation bounds (auto if vmin >= vmax).

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {3.f, 3.f};
int seed = 42;
// Base terrain with ridges
hmap::remap(z, 0.f, 1.f);
// Optional high-frequency noise for lateral strata distortion
shape,
glm::vec2(2.f, 2.f),
seed++);
hmap::remap(noise, 0.f, 0.1f);
auto z_canyon = z;
hmap::canyonize(z_canyon,
seed++,
12, // 6 strata levels
2.f, // convex strata height ratio relative to concave
2.f, // convex exponent for base and alternate levels
0.5f, // concave exponent for alternate levels
0.15f, // clamp min to flatten valley / river floor
0.08f, // smooth clamp transition
0.7f, // strata height fluctuation
&noise);
z_canyon.dump();
hmap::export_banner_png("ex_canyonize.png",
{z, z_canyon},
true);
}
void canyonize(Array &array, std::uint32_t seed=0, int nlevels=6, float convex_ratio=3.0f, float gamma_convex=3.0f, float gamma_concave=0.3f, float clamp_min_val=-std::numeric_limits< float >::infinity(), float k_smooth=0.1f, float noise_ratio=0.2f, const Array *p_noise=nullptr, float vmin=1.f, float vmax=0.f)
Applies a canyonize filter to a heightmap.
Definition canyonize.cpp:23

Result

◆ canyonize() [2/2]

void hmap::canyonize ( Array & array,
std::uint32_t seed,
int nlevels,
const Array * p_mask,
float convex_ratio = 3.0f,
float gamma_convex = 3.0f,
float gamma_concave = 0.3f,
float clamp_min_val = -std::numeric_limits<float>::infinity(),
float k_smooth = 0.1f,
float noise_ratio = 0.2f,
const Array * p_noise = nullptr,
float vmin = 1.f,
float vmax = 0.f )

Applies a masked canyonize filter to a heightmap.

Parameters
arrayThe array of values to modify.
seedRandom seed for strata level fluctuation.
nlevelsNumber of stratification levels.
p_maskOptional mask controlling the effect blending.
convex_ratioHeight ratio of convex strata relative to concave strata (e.g., 3.0).
gamma_convexPower law exponent for convex levels (> 1, e.g., 3.0).
gamma_concavePower law exponent for concave levels (< 1, e.g., 0.3).
clamp_min_valElevation threshold for flattening the canyon bottom.
k_smoothSmoothing factor for clamp_min_smooth (0 for hard clamp).
noise_ratioRatio of random elevation variation on strata levels.
p_noiseOptional noise array for lateral modulation.
vminMinimum elevation bounds (auto if vmin >= vmax).
vmaxMaximum elevation bounds (auto if vmin >= vmax).

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ dequantize()

Array hmap::dequantize ( const Array & array,
std::uint32_t seed,
float dither_amplitude = 0.01f,
int filtering_iterations = 1 )

Reduce quantization artifacts using dithering and smoothing.

Adds white noise dithering to the input array and applies iterative Laplacian filtering to smooth quantization steps.

Parameters
arrayInput quantized array.
seedRandom seed used for dithering noise generation.
dither_amplitudeAmplitude of the added white noise.
filtering_iterationsNumber of Laplacian smoothing iterations.
Returns
Dequantized and smoothed array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {4.f, 4.f};
int seed = 0;
hmap::clamp_min(z, 0.f);
// mimic quantization
z = hmap::quantize(z, 64);
// try to improve
float dither_amplitude = 0.01f;
int iterations = 4;
auto zd = hmap::dequantize(z, ++seed, dither_amplitude, iterations);
hmap::export_banner_png("ex_dequantize.png",
{z, zd},
true);
}
Array dequantize(const Array &array, std::uint32_t seed, float dither_amplitude=0.01f, int filtering_iterations=1)
Reduce quantization artifacts using dithering and smoothing.
Definition dequantize.cpp:15
Array quantize(const Array &array, int nlevels, float vmin, float vmax)
Quantize array values into discrete levels.
Definition dequantize.cpp:33

Result

◆ distance_shaper()

Array hmap::distance_shaper ( const Array & array,
float falloff = 0.05f,
int directions = 8,
float skew = 0.f,
float angle = 0.f,
DistanceMode mode = DistanceMode::PYRAMID,
DistanceMethod method = DistanceMethod::RT,
float angular_jitter = 0.f,
float falloff_jitter = 0.f,
float threshold = 0.f,
bool invert_input = false,
bool invert_output = false,
float mix_ratio = 1.f,
std::uint32_t seed = 0,
const Array * p_mask = nullptr,
const Array * p_dx = nullptr,
const Array * p_dy = nullptr )

Generates sloped, stratified terrain profiles from shapes and masks using directional distance fields.

Reproduces the behavior of Gaea's Distance node. Can generate multi-directional slopes, terraced / folded rock formations, and anisotropic skewing.

Parameters
arrayInput heightmap or shape mask.
falloffSlope / distance gradient decay rate.
directionsNumber of projection directions.
skewAsymmetry / skew strength along orientation angle.
anglePrimary orientation angle in degrees.
modePattern mode (PYRAMID for flat faces, ASTERISK for star-shaped cuts).
methodDistance calculation method (RT or CLASSIC).
angular_jitterRandom jitter applied to directional angles in [0, 1].
falloff_jitterRandom variation applied to falloff in [0, 1].
thresholdCutoff elevation threshold for sources.
invert_inputIf true, inverts the input prior to distance calculation.
invert_outputIf true, inverts the output distance field.
mix_ratioBlending factor between original input and output in [0, 1].
seedRandom seed for stochastic jitter.
p_maskOptional blend mask pointer.
p_dxOptional X displacement array for domain warp.
p_dyOptional Y displacement array for domain warp.
Returns
Resulting shaped array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {3.f, 3.f};
int seed = 0;
// --- Base input: stepped / flat plateau shapes from quantized noise or
// Voronoi
const float slope = 2.f / shape.x;
// --- 1. Symmetrical slopes (Pyramid mode)
z0,
slope,
8,
/* skew */ 0.f,
/* angle */ 0.f,
// --- 2. Asterisk mode (cutting into faces)
z0,
slope,
8,
/* skew */ 0.f,
/* angle */ 0.f,
// --- 3. Skewed slopes (tilted stratified formations)
z0,
slope,
8,
/* skew */ 0.8f,
/* angle */ 35.f,
// --- 4. Folded / terraced rock formation with warp displacement
shape,
{4.f, 4.f},
seed + 10);
shape,
{4.f, 4.f},
seed + 20);
z0,
slope,
8,
/* skew */ 0.7f,
/* angle */ 45.f,
0.1f,
0.f,
0.f,
false,
false,
0.9f,
seed,
nullptr,
&dx,
&dy);
hmap::export_banner_png("ex_distance_shaper.png",
{z0, z_pyramid, z_asterisk, z_skewed, z_folded},
true);
return 0;
}
Array distance_shaper(const Array &array, float falloff=0.05f, int directions=8, float skew=0.f, float angle=0.f, DistanceMode mode=DistanceMode::PYRAMID, DistanceMethod method=DistanceMethod::RT, float angular_jitter=0.f, float falloff_jitter=0.f, float threshold=0.f, bool invert_input=false, bool invert_output=false, float mix_ratio=1.f, std::uint32_t seed=0, const Array *p_mask=nullptr, const Array *p_dx=nullptr, const Array *p_dy=nullptr)
See hmap::distance_shaper.
Definition distance_shaper.cpp:102
@ ASTERISK
Star-shaped pattern with cut-ins between directions.
Definition filters.hpp:38
@ PYRAMID
Diamond/polyhedral pattern with flat planar facets.
Definition filters.hpp:39
@ RT
Real-time directional slope projection.
Definition filters.hpp:47

Result

◆ equalize() [1/2]

void hmap::equalize ( Array & array)

Apply histogram equalization to the array values.

This function performs histogram equalization on the input array to enhance the contrast of the image or data by adjusting the intensity distribution.

Parameters
arrayInput array to be equalized.

◆ equalize() [2/2]

void hmap::equalize ( Array & array,
const Array * p_mask )

Apply histogram equalization to the array values with a mask.

This function performs histogram equalization on the input array while considering the specified mask. Only the elements of the array corresponding to non-zero values in the mask are equalized.

Parameters
arrayInput array to be equalized.
p_maskOptional mask array. Only the elements where the mask is non-zero are equalized.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ expand() [1/4]

void hmap::expand ( Array & array,
int ir,
const Array * p_mask,
int iterations = 1 )

Apply expansion, or "inflation", to emphasize the bulk of the terrain.

This function expands the features of the terrain represented by the input array. The expansion operation, often referred to as "inflation", increases the prominence of elevated regions, effectively making them more pronounced.

Parameters
arrayInput array representing the terrain or data to be expanded.
irFilter radius, which determines the extent of the expansion.
p_maskOptional filter mask, with values expected in the range [0, 1]. The mask controls which parts of the array are affected by the expansion.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
z.infos();
int ir = 64;
hmap::Array z1 = z;
hmap::expand(z1, ir);
hmap::Array z2 = z;
hmap::shrink(z2, ir);
hmap::Array z3 = z;
hmap::Array kernel = hmap::lorentzian(glm::ivec2(2 * ir + 1, 2 * ir + 1));
hmap::shrink(z3, kernel);
hmap::export_banner_png("ex_expand.png",
{z, z1, z2, z3},
}
Array lorentzian(glm::ivec2 shape, float footprint_threshold=0.1f)
Generate a Lorentzian kernel.
Definition kernels.cpp:372
void shrink(Array &array, int ir, int iterations=1)
Apply shrinking, or "deflating", to emphasize the ridges in the heightmap.
Definition filters.cpp:903
void expand(Array &array, int ir, const Array *p_mask, int iterations=1)
Apply expansion, or "inflation", to emphasize the bulk of the terrain.
Definition filters.cpp:87

Result

◆ expand() [2/4]

void hmap::expand ( Array & array,
int ir,
int iterations = 1 )

Apply expansion to emphasize the bulk of the terrain using a filter radius.

This overload applies expansion without the use of a mask, utilizing only the filter radius.

Parameters
arrayInput array representing the terrain or data to be expanded.
irFilter radius, which determines the extent of the expansion.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ expand() [3/4]

void hmap::expand ( Array & array,
const Array & kernel,
int iterations = 1 )

Apply expansion using a custom kernel.

This overload allows the use of a custom kernel for expansion, offering more control over the operation compared to the filter radius method.

Parameters
arrayInput array representing the terrain or data to be expanded.
kernelCustom kernel array used to perform the expansion.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ expand() [4/4]

void hmap::expand ( Array & array,
const Array & kernel,
const Array * p_mask,
int iterations = 1 )

Apply expansion using a custom kernel with an optional mask.

This overload allows the use of a custom kernel for expansion, along with an optional mask to control which parts of the array are affected.

Parameters
arrayInput array representing the terrain or data to be expanded.
kernelCustom kernel array used to perform the expansion.
p_maskOptional filter mask, with values expected in the range [0, 1]. The mask controls which parts of the array are affected by the expansion.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ expand_directional()

void hmap::expand_directional ( Array & array,
int ir,
float angle,
float aspect_ratio,
float anisotropy = 1.f,
const Array * p_mask = nullptr )

Apply expansion, or "inflation", to emphasize the bulk of the terrain, using a directional kernel.

This function expands features of the terrain represented by the input array, with emphasis applied directionally based on the specified angle. The directional kernel allows for anisotropic expansion, making the expansion more pronounced in a specified direction.

Parameters
arrayInput array representing the terrain or data to be expanded.
irFilter radius, determining the extent of the expansion.
angleAngle (in degrees) that sets the direction of the expansion.
aspect_ratioPulse aspect ratio, determining the shape of the expansion.
anisotropyPulse width ratio between upstream and downstream sides, default is 1.0 (isotropic expansion).
p_maskOptional filter mask with values expected in the range [0, 1]. The mask controls which parts of the array are affected by the expansion.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
int ir = 64;
float angle = 30.f;
float aspect_ratio = 0.2f;
hmap::Array z1 = z;
hmap::expand_directional(z1, ir, angle, aspect_ratio);
hmap::Array z2 = z;
hmap::shrink_directional(z2, ir, angle, aspect_ratio);
hmap::export_banner_png("ex_expand_directional.png",
{z, z1, z2},
}
void shrink_directional(Array &array, int ir, float angle, float aspect_ratio, float anisotropy=1.f, const Array *p_mask=nullptr)
Apply directional shrinking, or "deflating", to emphasize the ridges in the terrain.
Definition filters.cpp:946
void expand_directional(Array &array, int ir, float angle, float aspect_ratio, float anisotropy=1.f, const Array *p_mask=nullptr)
Apply expansion, or "inflation", to emphasize the bulk of the terrain, using a directional kernel.
Definition filters.cpp:146

Result

◆ expand_talus()

void hmap::expand_talus ( Array & z,
const Array & mask,
float talus,
std::uint32_t seed,
int ir = 1,
float noise_ratio = 0.2f )

Expand heights outward from a masked region with a talus slope limit.

Starting from the non-zero cells of mask, heights are propagated outward using a min-heap so lower cells are processed first. Neighbor heights are computed from the source height plus dist * talus, optionally perturbed with noise.

Intuition: grows terrain outward from seed cells, filling empty space while respecting a maximum slope.

Parameters
zHeight array modified in-place.
maskInitial region to expand from.
talusMaximum slope per unit distance.
seedRNG seed for noise.
irNeighborhood radius.
noise_ratioAmplitude of slope noise.

◆ fill_talus() [1/2]

void hmap::fill_talus ( Array & z,
float talus,
std::uint32_t seed,
int ir = 1,
float noise_ratio = 0.2f,
const Array * p_seed_mask = nullptr )

Enforce a talus slope constraint on a height field.

Cells are processed from highest to lowest using a max-heap. Each cell may raise neighboring cells so that the slope relative to the current cell does not exceed the local talus value.

Intuition: stabilizes an existing terrain by redistributing height so slopes do not exceed the talus limit (similar to talus erosion / relaxation but by adding material).

Parameters
zA reference to the 2D array representing the terrain heights. The function modifies this array in place to introduce talus slopes.
talusThe critical slope angle that determines where material will move from higher elevations to lower ones. Slopes steeper than this value will be flattened by material transport.
seedThe seed for the random number generator, ensuring reproducibility of the noise effects in the talus formation process. The same seed will produce the same terrain modifications.
noise_ratioA parameter that controls the amount of randomness or noise introduced in the talus formation process. The default value is 0.2.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {2.f, 2.f};
int seed = 1;
float talus = 2.f / shape.x;
hmap::Array z1 = z;
int ir = 6;
float noise_ratio = 0.01f;
hmap::fill_talus(z1, talus, seed, ir, noise_ratio);
// with seed mask
hmap::Array z2 = z;
hmap::saturate(mask, 0.01f, 1.f);
hmap::fill_talus(z2, talus, seed, ir, noise_ratio, &mask);
hmap::export_banner_png("ex_fill_talus.png",
{z, z1, z2},
true);
}
void saturate(Array &array, float vmin, float vmax, float from_min, float from_max, float k=0.f)
Saturate the array values based on the input interval [vmin, vmax] (the output amplitude is not modif...
Definition recurve.cpp:173
void fill_talus(Array &z, float talus, std::uint32_t seed, int ir=1, float noise_ratio=0.2f, const Array *p_seed_mask=nullptr)
Enforce a talus slope constraint on a height field.
Definition fill_talus.cpp:100
Array select_valley(const Array &z, int ir, bool ridge_select=false, bool normalize=false, ICommunicator &comm=SingleArrayComm::instance())
Definition selector.cpp:484

Result

See unit tests: test_fill_talus.cpp

◆ fill_talus() [2/2]

void hmap::fill_talus ( Array & z,
const Array & talus,
std::uint32_t seed,
int ir = 1,
float noise_ratio = 0.2f,
const Array * p_seed_mask = nullptr )

◆ fold() [1/2]

void hmap::fold ( Array & array,
float vmin,
float vmax,
int iterations = 3,
float k = 0.05f )

Apply a "folding" filter (successive absolute values) to the array elements.

This function applies a folding filter to the input array, where the values are successively folded (using absolute values) within a specified range, defined by vmin and vmax. The process can be repeated for a number of iterations, with an optional smoothing parameter k to control the intensity of the folding effect.

Parameters
arrayInput array to which the folding filter is applied.
vminMinimum reference value used as a lower bound for the folding operation.
vmaxMaximum reference value used as an upper bound for the folding operation.
iterationsNumber of iterations for applying the folding filter. The default is 3.
kSmoothing parameter for the absolute value operation, expected to be greater than 0. It controls the degree of smoothing applied during folding. The default value is 0.05.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
int iterations = 5;
float k_smooth;
auto z1 = z;
k_smooth = 0.f;
hmap::fold(z1, iterations, k_smooth);
auto z2 = z;
k_smooth = 0.05f;
hmap::fold(z2, iterations, k_smooth);
auto z3 = z;
hmap::export_banner_png("ex_fold.png", {z, z1, z2}, hmap::Cmap::INFERNO);
}
void fold(Array &array, float vmin, float vmax, int iterations=3, float k=0.05f)
Apply a "folding" filter (successive absolute values) to the array elements.
Definition filters.cpp:169
@ PP_COSINE_PEAKY
Definition profiles.hpp:40

Result

◆ fold() [2/2]

void hmap::fold ( Array & array,
int iterations = 3,
float k = 0.05f )

Apply a "folding" filter with default reference values and parameters.

This overload applies the folding filter to the input array with the default number of iterations and smoothing parameter k. The folding is done without explicit minimum and maximum reference values.

Parameters
arrayInput array to which the folding filter is applied.
iterationsNumber of iterations for applying the folding filter. The default is 3.
kSmoothing parameter for the absolute value operation, expected to be greater than 0. It controls the degree of smoothing applied during folding. The default value is 0.05.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ fold_periodic() [1/2]

void hmap::fold_periodic ( Array & array,
PhasorProfile phasor_profile,
float vmin,
float vmax,
int iterations = 3,
float delta = 0.f )

Apply a periodic "folding" filter to the array elements using a periodic phasor profile.

This function applies a folding filter based on a periodic profile function (PhasorProfile) rather than successive absolute-value operations. For each iteration, the function evaluates the periodic profile across the range defined by [vmin, vmax] with an increasing frequency (doubled per iteration).

Parameters
arrayInput array to which the periodic folding filter is applied.
phasor_profileType of phasor profile to use for folding.
deltaProfile shape parameter (defaults to 0.0).
vminMinimum reference value used as a lower bound for the folding operation.
vmaxMaximum reference value used as an upper bound for the folding operation.
iterationsNumber of iterations for applying the folding filter. The default is 3.

◆ fold_periodic() [2/2]

void hmap::fold_periodic ( Array & array,
PhasorProfile phasor_profile = PhasorProfile::PP_COSINE_STD,
int iterations = 3,
float delta = 0.f )

Apply a periodic "folding" filter with default reference values.

This overload applies the periodic folding filter using the array's minimum and maximum values as reference bounds.

Parameters
arrayInput array to which the periodic folding filter is applied.
phasor_profileType of phasor profile to use for folding.
iterationsNumber of iterations for applying the folding filter. The default is 3.
deltaProfile shape parameter (defaults to 0.0).

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ gain() [1/3]

void hmap::gain ( Array & array,
float factor,
const Array * p_mask )

Apply a gain correction to the array elements.

This function applies a gain correction to the input array using a power law. The correction enhances or reduces the intensity of the values based on the specified gain factor.

Parameters
arrayInput array to which the gain correction is applied.
factorGain factor, expected to be greater than 0. It determines the strength of the gain correction.
p_maskOptional filter mask, with values expected in the range [0, 1]. The mask controls which parts of the array are affected by the gain correction.
Warning
Array values are expected to be in the range [0, 1]. Applying the gain correction outside of this range may lead to unexpected results.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
hmap::gain(z, 2.f);
z.to_png("ex_gain.png", hmap::Cmap::VIRIDIS);
}
void gain(Array &array, float factor, const Array *p_mask)
Apply a gain correction to the array elements.
Definition filters.cpp:251

Result

◆ gain() [2/3]

void hmap::gain ( Array & array,
float factor )

Apply a gain correction to the array elements without a mask.

This overload applies the gain correction to the entire array without using a mask. The gain correction is performed using the specified gain factor.

Parameters
arrayInput array to which the gain correction is applied.
factorGain factor, expected to be greater than 0. It determines the strength of the gain correction.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ gamma_correction() [1/2]

void hmap::gamma_correction ( Array & array,
float gamma,
const Array * p_mask )

Apply gamma correction to the input array.

This function applies gamma correction to the input array, which adjusts the brightness and contrast based on a specified gamma factor. Gamma correction is used to correct or adjust the tonal range of an image or data to achieve a desired visual effect.

Parameters
arrayInput array to which the gamma correction is applied.
gammaGamma factor, expected to be greater than 0. It determines the level of correction applied. A gamma value less than 1 will lighten the image, while a value greater than 1 will darken it.
p_maskOptional filter mask, with values expected in the range [0, 1]. The mask controls which parts of the array are affected by the gamma correction.
Warning
Array values are expected to be in the range [0, 1]. Applying gamma correction outside of this range may result in incorrect or unintended modifications.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
z.to_png("ex_gamma_correction.png", hmap::Cmap::VIRIDIS);
}
void gamma_correction(Array &array, float gamma, const Array *p_mask)
Apply gamma correction to the input array.
Definition filters.cpp:271

Result

◆ gamma_correction() [2/2]

void hmap::gamma_correction ( Array & array,
float gamma )

Apply gamma correction to the input array without a mask.

This overload applies gamma correction to the entire array without using a mask. The gamma correction is performed using the specified gamma factor.

Parameters
arrayInput array to which the gamma correction is applied.
gammaGamma factor, expected to be greater than 0. It determines the level of correction applied. A gamma value less than 1 will lighten the image, while a value greater than 1 will darken it.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ gamma_correction_local() [1/2]

void hmap::gamma_correction_local ( Array & array,
float gamma,
int ir,
float k = 0.1f )

Apply a "local" gamma correction to the input array.

This function performs gamma correction by first normalizing the values locally within a specified neighborhood around each pixel. The normalization is achieved using minimum and maximum filters before applying the gamma correction based on the specified gamma factor. This method allows for localized adjustments of contrast and brightness in the input array.

Parameters
arrayInput array to which the local gamma correction is applied.
gammaGamma factor, expected to be greater than 0. It determines the level of correction applied after local normalization. A gamma value less than 1 will lighten the local regions, while a value greater than 1 will darken them.
irFilter radius that defines the size of the local neighborhood used for normalization.
kSmoothing factor used to control the degree of smoothing applied during normalization. The default value is 0.1.
p_maskOptional filter mask, with values expected in the range [0, 1]. The mask controls which parts of the array are affected by the local gamma correction.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
int ir = 8;
float k_smoothing = 0.1f;
hmap::gamma_correction_local(z, 0.5f, ir, k_smoothing);
z.to_png("ex_gamma_correction_local.png", hmap::Cmap::VIRIDIS);
}
void gamma_correction_local(Array &array, float gamma, int ir, float k=0.1f)
Apply a "local" gamma correction to the input array.
Definition filters.cpp:279

Result

◆ gamma_correction_local() [2/2]

void hmap::gamma_correction_local ( Array & array,
float gamma,
int ir,
const Array * p_mask,
float k = 0.1f )

Apply a "local" gamma correction with a mask to the input array.

This overload applies local gamma correction to the input array using a mask. The gamma correction is performed after normalizing values locally within the specified neighborhood defined by the filter radius. The optional mask allows for selective application of the correction.

Parameters
arrayInput array to which the local gamma correction is applied.
gammaGamma factor, expected to be greater than 0. It determines the level of correction applied after local normalization. A gamma value less than 1 will lighten the local regions, while a value greater than 1 will darken them.
irFilter radius that defines the size of the local neighborhood used for normalization.
p_maskFilter mask, with values expected in the range [0, 1]. The mask controls which parts of the array are affected by the local gamma correction.
kSmoothing factor used to control the degree of smoothing applied during normalization. The default value is 0.1.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ kuwahara() [1/2]

void hmap::kuwahara ( Array & array,
int ir,
float mix_ratio = 1.f )

Applies the Kuwahara filter to an array with optional per-pixel masking.

This overloaded version of the Kuwahara filter allows applying the filter with a per-pixel mask. The mask determines the blending ratio for each pixel, allowing selective smoothing.

Parameters
arrayThe input/output array to apply the filter on. The array is modified in place.
irThe radius of the region to analyze for each pixel. Larger values result in stronger smoothing.
mix_ratioA blending factor between the original and filtered arrays when p_mask is nullptr. Ignored if p_mask is provided.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
auto z1 = z;
int ir = 8;
hmap::kuwahara(z1, ir);
auto z2 = z;
float mix = 0.25f;
hmap::kuwahara(z2, ir, mix);
hmap::export_banner_png("ex_kuwahara.png", {z, z1, z2}, hmap::Cmap::INFERNO);
}
void kuwahara(Array &array, int ir, float mix_ratio=1.f)
Applies the Kuwahara filter to an array with optional per-pixel masking.
Definition filters.cpp:328

Result

◆ kuwahara() [2/2]

void hmap::kuwahara ( Array & array,
int ir,
const Array * p_mask,
float mix_ratio = 1.f )

Applies the Kuwahara filter to an array with optional per-pixel masking.

This overloaded version of the Kuwahara filter allows applying the filter with a per-pixel mask. The mask determines the blending ratio for each pixel, allowing selective smoothing.

Parameters
arrayThe input/output array to apply the filter on. The array is modified in place.
irThe radius of the region to analyze for each pixel. Larger values result in stronger smoothing.
p_maskA pointer to an array representing the mask. The values in the mask range from 0.0 to 1.0, specifying the blending ratio for each pixel. If nullptr, the filter is applied without masking.
mix_ratioA blending factor between the original and filtered arrays when p_mask is nullptr. Ignored if p_mask is provided.

If no mask is provided:

  • The function behaves like the single-argument version of kuwahara.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
auto z1 = z;
int ir = 8;
hmap::kuwahara(z1, ir);
auto z2 = z;
float mix = 0.25f;
hmap::kuwahara(z2, ir, mix);
hmap::export_banner_png("ex_kuwahara.png", {z, z1, z2}, hmap::Cmap::INFERNO);
}

Result

◆ laplace() [1/2]

void hmap::laplace ( Array & array,
float sigma = 0.125f,
int iterations = 3 )

Applies an iterative 8-neighbor Laplacian smoothing filter on an array.

This function performs isotropic Laplacian diffusion on a 2D array using an explicit finite-difference scheme. Each cell is updated according to the local Laplacian computed from its 8 surrounding neighbors:

\[A_{i,j}^{t+1} = A_{i,j}^{t} + \sigma \cdot \left( \sum_{(p,q)\in N_{8}(i,j)} A_{p,q}^{t} - 8A_{i,j}^{t} \right) \]

where ( N_{8}(i,j) ) denotes the 8 neighboring cells.

Boundary cells are handled by clamping neighbor indices to the valid range, effectively replicating edge values at the borders.

Parameters
arrayThe 2D array to be smoothed (modified in place).
sigmaDiffusion coefficient (small positive value, e.g. 0.05–0.25).
iterationsNumber of diffusion iterations to apply.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
float sigma = 0.2f;
int iterations = 10;
auto z1 = z;
hmap::laplace(z1, sigma, iterations);
auto z2 = z;
float talus = 1.f / (float)shape.x;
hmap::laplace_edge_preserving(z2, talus, sigma, iterations);
hmap::export_banner_png("ex_laplace.png",
{z, z1, z2},
true);
}
void laplace_edge_preserving(Array &array, float talus, float sigma=0.2f, int iterations=3)
Apply a low-pass anisotropic Laplace filter to the input array.
Definition filters.cpp:458
void laplace(Array &array, float sigma=0.125f, int iterations=3)
Applies an iterative 8-neighbor Laplacian smoothing filter on an array.
Definition filters.cpp:410

Result

◆ laplace() [2/2]

void hmap::laplace ( Array & array,
const Array * p_mask,
float sigma = 0.125f,
int iterations = 3 )

Apply a low-pass Laplace filter with a mask.

This overload applies the Laplace filter to the input array using an optional mask. The mask determines which parts of the array are affected by the filter. The filtering intensity and the number of iterations control the extent of the smoothing effect.

Parameters
arrayInput array to which the Laplace filter is applied.
p_maskOptional filter mask, with values expected in the range [0, 1]. The mask specifies which parts of the array are affected by the filter.
sigmaFiltering intensity, expected to be in the range [0, 1]. It controls the strength of the filtering effect. A value closer to 1 results in more smoothing. The default value is 0.2.
iterationsNumber of iterations to apply the filter. More iterations will increase the smoothing effect. The default value is 3.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ laplace1d()

void hmap::laplace1d ( std::vector< float > & v,
float sigma = 0.5f,
int iterations = 1 )

Apply a low-pass Laplace filter to a vector.

This function applies a low-pass Laplace filter to a 1D vector to smooth out high-frequency noise and detail. The filtering intensity and the number of iterations control the extent of the smoothing effect.

Parameters
vInput vector to which the Laplace filter is applied.
sigmaFiltering intensity, expected to be in the range [0, 1]. It determines the strength of the filtering effect. A value closer to 1 results in more smoothing.
iterationsNumber of iterations to apply the filter. More iterations will increase the smoothing effect. The default value is 1.

◆ laplace_edge_preserving() [1/2]

void hmap::laplace_edge_preserving ( Array & array,
float talus,
float sigma = 0.2f,
int iterations = 3 )

Apply a low-pass anisotropic Laplace filter to the input array.

This function applies an anisotropic Laplace filter to the input array. Anisotropic diffusion, also known as edge-preserving smoothing, helps to reduce noise while preserving edges. The effect of the filter is controlled by the talus limit, filtering intensity, and the number of iterations.

Parameters
arrayInput array to which the anisotropic Laplace filter is applied.
talusTalus limit for edge sensitivity. Gradients above this value are less affected by the filtering, preserving important edges in the data.
sigmaFiltering intensity, expected to be in the range [0, 1]. It controls the strength of the filtering effect. A value closer to 1 results in more smoothing. The default value is 0.2.
iterationsNumber of iterations to apply the filter. More iterations will increase the smoothing effect. The default value is 3.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
float sigma = 0.2f;
int iterations = 10;
auto z1 = z;
hmap::laplace(z1, sigma, iterations);
auto z2 = z;
float talus = 1.f / (float)shape.x;
hmap::laplace_edge_preserving(z2, talus, sigma, iterations);
hmap::export_banner_png("ex_laplace.png",
{z, z1, z2},
true);
}

Result

◆ laplace_edge_preserving() [2/2]

void hmap::laplace_edge_preserving ( Array & array,
float talus,
const Array * p_mask,
float sigma = 0.2f,
int iterations = 3 )

Apply a low-pass anisotropic Laplace filter with a mask.

This overload applies the anisotropic Laplace filter to the input array using an optional mask. The mask determines which parts of the array are affected by the filter. The effect of the filtering is controlled by the talus limit, filtering intensity, and the number of iterations.

Parameters
arrayInput array to which the anisotropic Laplace filter is applied.
talusTalus limit for edge sensitivity. Gradients above this value are less affected by the filtering, preserving important edges in the data.
p_maskOptional filter mask, with values expected in the range [0, 1]. The mask specifies which parts of the array are affected by the filter.
sigmaFiltering intensity, expected to be in the range [0, 1]. It controls the strength of the filtering effect. A value closer to 1 results in more smoothing. The default value is 0.2.
iterationsNumber of iterations to apply the filter. More iterations will increase the smoothing effect. The default value is 3.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ low_pass_high_order()

void hmap::low_pass_high_order ( Array & array,
int order = 9,
float sigma = 1.f )

Apply a low-pass high-order filter to the input array.

This function applies a high-order low-pass filter to the input array. The filter can be of 5th, 7th, or 9th order, providing increasingly sharp filtering effects. The filtering intensity is controlled by the sigma parameter, which determines the strength of the filtering.

Parameters
arrayInput array to which the high-order low-pass filter is applied.
orderFilter order, which can be 5, 7, or 9. Higher orders provide more refined filtering.
sigmaFiltering intensity, expected to be in the range [0, 1]. It controls the strength of the filtering effect. A value closer to 1 results in more smoothing. The default value is 1.0.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {2.f, 2.f};
int seed = 1;
auto zf = z;
int order = 7;
hmap::export_banner_png("ex_low_pass_high_order.png",
{z, zf},
}
void low_pass_high_order(Array &array, int order=9, float sigma=1.f)
Apply a low-pass high-order filter to the input array.
Definition filters.cpp:495

Result

See also
laplace

◆ make_binary()

void hmap::make_binary ( Array & array,
float threshold = 0.f )

Convert array values to binary using a threshold.

This function applies a binary filter to the input array, converting all values to either 0 or 1 based on a specified threshold. Values above the threshold are set to 1, while values equal to or below the threshold are set to 0.

Parameters
arrayInput array to be converted to binary.
thresholdThreshold value. Any array value greater than this threshold is set to 1, while values less than or equal to the threshold are set to 0. The default threshold is 0.0.

◆ match_histogram()

void hmap::match_histogram ( Array & array,
const Array & array_reference )

Transform the input array elevation to match the histogram of a reference array.

This function performs histogram matching on the input array to adjust its elevation values so that the resulting histogram closely matches the histogram of a reference array. This process is useful for aligning the statistical properties of the input data with those of the reference data. A single input sample maps to the reference median, interpolating between the two central reference values for an even sample count. Empty input or reference arrays leave the input unchanged.

Parameters
arrayInput array whose elevation values are to be transformed.
array_referenceReference array whose histogram is used as the target for matching.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
hmap::Array zref = hmap::noise(hmap::NoiseType::PERLIN, shape, res, ++seed);
hmap::remap(zref);
hmap::gain(zref, 4.f);
hmap::Array z1 = z0;
hmap::export_banner_png("ex_match_histogram.png",
{zref, z0, z1},
}
void match_histogram(Array &array, const Array &array_reference)
Transform the input array elevation to match the histogram of a reference array.
Definition filters.cpp:550

Result

◆ mean_shift() [1/2]

Array hmap::mean_shift ( const Array & array,
int ir,
float talus,
int iterations = 1,
bool talus_weighted = true )

Applies the mean shift algorithm to the input array.

The mean shift algorithm iteratively adjusts each value in the input array by averaging nearby values within a specified radius (ir), using either simple or weighted mean computation. The process stops after the specified number of iterations or if convergence criteria are met.

Parameters
arrayThe input array to process.
irThe radius of the neighborhood to consider for mean computation.
thresholdThe value threshold for considering neighboring elements. Only elements with differences below this threshold are included.
iterationsThe number of iterations to perform the mean shift process.
talus_weightedIf true, uses weighted mean based on differences between values and their neighbors. If false, uses unweighted mean.
Returns
A new array containing the result of the mean shift process.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {2.f, 2.f};
int seed = 1;
int ir = 32;
float talus = 16.f / (float)shape.x;
int iterations = 4;
hmap::Array zm = hmap::mean_shift(z, ir, talus, iterations);
zm.to_png_grayscale("out.png", CV_16U);
hmap::export_banner_png("ex_mean_shift.png", {z, zm}, hmap::Cmap::JET);
}
Array mean_shift(const Array &array, int ir, float talus, int iterations=1, bool talus_weighted=true)
Applies the mean shift algorithm to the input array.
Definition filters.cpp:578

Result

◆ mean_shift() [2/2]

Array hmap::mean_shift ( const Array & array,
int ir,
float talus,
const Array * p_mask,
int iterations = 1,
bool talus_weighted = true )

◆ median_3x3() [1/2]

void hmap::median_3x3 ( Array & array,
const Array * p_mask )

Apply a 3x3 median filter to the input array.

This function applies a 3x3 median filter to the input array to reduce noise while preserving edges. The median filter replaces each pixel with the median value of the 3x3 neighborhood surrounding it. An optional mask can be used to control which parts of the array are filtered.

Parameters
arrayInput array to which the median filter is applied.
p_maskOptional filter mask, with values expected in the range [0, 1]. The mask determines which parts of the array are affected by the median filter.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
z += 0.1f * hmap::white(shape, 0.f, 1.f, seed);
auto z0 = z;
hmap::export_banner_png("ex_median_3x3.png", {z0, z}, hmap::Cmap::VIRIDIS);
}

Result

◆ median_3x3() [2/2]

void hmap::median_3x3 ( Array & array)

Apply a 3x3 median filter to the input array without a mask.

This overload applies a 3x3 median filter to the input array, affecting all pixels. The median filter replaces each pixel with the median value of the 3x3 neighborhood surrounding it.

Parameters
arrayInput array to which the median filter is applied.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ median_pseudo()

Array hmap::median_pseudo ( const Array & array,
int ir )

Computes a fast pseudo-median approximation of a local neighborhood in an array.

This function approximates the effect of a median filter by computing the local minimum, maximum, and mean values within a square neighborhood of radius ir, and averaging the results:

\[\text{pseudo\_median}(x, y) = \frac{\text{min} + \text{max} + \text{mean}}{3} \]

This method is computationally cheaper than a true median filter and can approximate its noise-reduction and edge-preserving properties to some extent.

Parameters
arrayInput array (e.g., image or 2D signal).
irRadius of the square neighborhood (kernel size will be \(2 \cdot ir + 1\)).
Returns
An Array containing the pseudo-median filtered output.
Note
This method works best on images with impulsive noise (e.g., salt-and-pepper), but is only an approximation and may behave differently from a true median filter on complex structures or edges.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
z += 0.1f * hmap::white(shape, 0.f, 1.f, seed);
int ir = 16;
// gpu version
hmap::export_banner_png("ex_median_pseudo.png",
{z, z1, z2},
}
Array median_pseudo(const Array &array, int ir, MinMaxKernel kernel_type=MinMaxKernel::DISK)
See hmap::median_pseudo.
Definition filters_gpu.cpp:251
Array median_pseudo(const Array &array, int ir)
Computes a fast pseudo-median approximation of a local neighborhood in an array.
Definition filters.cpp:702

Result

See also
local_min, local_max, local_mean

◆ normal_displacement() [1/2]

void hmap::normal_displacement ( Array & array,
float amount = 0.1f,
int ir = 0,
bool reverse = false )

Apply a displacement to the terrain along the normal direction.

This function displaces the terrain along its normal direction, simulating effects like erosion or terrain modification. The amount of displacement and direction (normal or reversed) can be specified. Optionally, a mask can be used to control which parts of the terrain are affected.

Parameters
arrayInput array representing the terrain.
p_maskOptional filter mask, with values expected in the range [0, 1]. The mask specifies which parts of the array are affected by the displacement.
amountAmount of displacement to apply. The default value is 0.1.
irPre-filtering radius. The radius used to smooth the terrain before applying displacement. The default value is 0.
reverseIf true, the displacement direction is reversed. The default value is false.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
hmap::Array mask = z1;
hmap::remap(mask);
hmap::Array z2 = z1;
hmap::normal_displacement(z2, &mask, 5.f, 4, false);
hmap::export_banner_png("ex_normal_displacement.png",
{z1, z2},
}
void normal_displacement(Array &array, float amount=0.1f, int ir=0, bool reverse=false)
Apply a displacement to the terrain along the normal direction.
Definition filters.cpp:710

Result

◆ normal_displacement() [2/2]

void hmap::normal_displacement ( Array & array,
const Array * p_mask,
float amount = 0.1f,
int ir = 0,
bool reverse = false )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ plateau() [1/2]

void hmap::plateau ( Array & array,
const Array * p_mask,
int ir,
float factor )

Apply a plateau-shape filter to the input array.

This function applies a plateau-shape filter to the input array, modifying the terrain to create flat, plateau-like regions. The filter's radius and flatness can be adjusted to control the extent and shape of the plateaus. An optional mask can be used to control which parts of the array are affected.

Parameters
arrayInput array to which the plateau-shape filter is applied.
p_maskOptional filter mask, with values expected in the range [0, 1]. The mask specifies which parts of the array are affected by the filter.
irPlateau radius. The size of the area over which the plateau effect is applied.
factorGain factor that controls the flatness of the plateau. The higher the factor, the flatter the resulting plateau. The default value is 1.0.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
auto zp = z;
hmap::plateau(zp, 64, 4.f);
hmap::export_banner_png("ex_plateau.png", {z, zp}, hmap::Cmap::TERRAIN);
}
void plateau(Array &array, const Array *p_mask, int ir, float factor)
Apply a plateau-shape filter to the input array.
Definition filters.cpp:777

Result

◆ plateau() [2/2]

void hmap::plateau ( Array & array,
int ir,
float factor )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ quantize() [1/2]

Array hmap::quantize ( const Array & array,
int nlevels,
float vmin,
float vmax )

Quantize array values into discrete levels.

Values are clamped to the range [vmin, vmax] and remapped to nlevels uniformly distributed discrete values.

Parameters
arrayInput array.
nlevelsNumber of quantization levels.
vminMinimum clamp value.
vmaxMaximum clamp value.
Returns
Quantized array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {4.f, 4.f};
int seed = 0;
hmap::clamp_min(z, 0.f);
// mimic quantization
z = hmap::quantize(z, 64);
// try to improve
float dither_amplitude = 0.01f;
int iterations = 4;
auto zd = hmap::dequantize(z, ++seed, dither_amplitude, iterations);
hmap::export_banner_png("ex_dequantize.png",
{z, zd},
true);
}

Result

◆ quantize() [2/2]

Array hmap::quantize ( const Array & array,
int nlevels )

Quantize array values using the array min/max range.

Parameters
arrayInput array.
nlevelsNumber of quantization levels.
Returns
Quantized array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {4.f, 4.f};
int seed = 0;
hmap::clamp_min(z, 0.f);
// mimic quantization
z = hmap::quantize(z, 64);
// try to improve
float dither_amplitude = 0.01f;
int iterations = 4;
auto zd = hmap::dequantize(z, ++seed, dither_amplitude, iterations);
hmap::export_banner_png("ex_dequantize.png",
{z, zd},
true);
}

Result

◆ recast_billow()

void hmap::recast_billow ( Array & array,
float vref,
float k )

Transform heightmap to give a "billow" like appearance.

This function modifies the heightmap to produce a "billow" effect. The transformation is applied based on a reference elevation (vref) where the elevation is folded. The smoothing coefficient (k) controls the degree of smoothing applied during the transformation.

Parameters
arrayInput array representing the heightmap to be transformed.
vrefReference elevation where the heightmap values are folded. This value determines the baseline around which the billow effect is centered.
kSmoothing coefficient that influences the degree of smoothness in the billow transformation. Higher values result in more smoothing.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
shape = {512, 512};
glm::vec2 res = {2.f, 2.f};
int seed = 1;
auto z1 = z;
{
int ir = 16;
float gamma = 2.f;
hmap::recast_peak(z1, ir, gamma);
}
auto z2 = z;
{
shape,
res,
seed++);
hmap::remap(noise, -0.1f, 0.1f);
float zcut = 0.5f;
float gamma = 4.f;
hmap::recast_canyon(z2, zcut, gamma, &noise);
}
auto z3 = z;
{
float talus = 2.f / shape.x;
int ir = 4;
float amplitude = 0.2f;
float kw = 16.f;
float gamma = 0.5f;
hmap::recast_rocky_slopes(z3, talus, ir, amplitude, seed, kw, gamma);
}
auto z4 = z;
auto z5 = z;
{
float talus = 1.f / shape.x;
int ir = 32;
float amplitude = 0.05f;
float gain = 1.5f;
hmap::gpu::recast_cliff(z4, talus, ir, amplitude, gain);
float angle = 0.f;
hmap::gpu::recast_cliff_directional(z5, talus, ir, amplitude, angle, gain);
}
auto z6 = z;
auto z7 = z;
{
float k = 0.01f;
hmap::recast_billow(z6, 0.5f, k);
hmap::recast_sag(z7, 0.5f, k);
}
auto z8 = z;
{
z8.to_png("out0.png", hmap::Cmap::GRAY, false, CV_16U);
hmap::recast_escarpment(z8, 16, 0.1f, 1.f, false, true);
z8.to_png("out1.png", hmap::Cmap::GRAY, false, CV_16U);
}
hmap::export_banner_png("ex_recast.png",
{z, z1, z2, z3, z4, z5, z6, z7, z8},
true);
}
void recast_cliff(Array &array, float talus, int ir, float amplitude, float gain=2.f, int iterations=500, Array *p_cliff_mask=nullptr, int sync_interval=0, const UvTile &region=UvTile::dummy(), ICommunicator &comm=SingleArrayComm::instance())
Transform heightmap to add cliffs where gradients are steep enough using Poisson gradient amplificati...
Definition recast_cliff.cpp:27
void recast_cliff_directional(Array &array, float talus, int ir, float amplitude, float angle, float gain=2.f, int iterations=500, Array *p_cliff_mask=nullptr, int sync_interval=0, const UvTile &region=UvTile::dummy(), ICommunicator &comm=SingleArrayComm::instance())
Transform heightmap to add directional cliffs where gradients are steep enough using Poisson gradient...
Definition recast_cliff.cpp:166
void recast_rocky_slopes(Array &array, float talus, int ir, float amplitude, std::uint32_t seed, float kw, float gamma=0.5f, const Array *p_noise=nullptr, const UvRect &uv_rect=UvRect::unit())
Transform heightmap by adding "rock-like" features at higher slopes.
Definition recast.cpp:232
void recast_sag(Array &array, float vref, float k)
Transform heightmap to give a "cliff" like appearance.
Definition recast.cpp:305
void recast_peak(Array &array, int ir, float gamma=2.f, float k=0.1f)
Transform heightmap to give a "peak" like appearance.
Definition recast.cpp:207
void recast_billow(Array &array, float vref, float k)
Transform heightmap to give a "billow" like appearance.
Definition recast.cpp:24
void recast_escarpment(Array &array, int ir=16, float ratio=0.1f, float scale=1.f, bool reverse=false, bool transpose_effect=false, float global_scaling=0.f)
Applies an escarpment effect to the given 2D array, modifying its values based on cumulative displace...
Definition recast.cpp:133
void recast_canyon(Array &array, const Array &vcut, float gamma=4.f)
Transform heightmap to give a "canyon" like appearance.
Definition recast.cpp:30

Result

◆ recast_canyon() [1/4]

void hmap::recast_canyon ( Array & array,
const Array & vcut,
float gamma = 4.f )

Transform heightmap to give a "canyon" like appearance.

This function modifies the heightmap to create a "canyon" effect. The transformation is based on a canyon top elevation (vcut). The effect can be adjusted with a gamma factor to control the intensity of the canyon effect. Optional parameters include a filter mask for selective application and a noise array for additional variation.

Parameters
arrayInput array representing the heightmap to be transformed.
vcutCanyon top elevation. This value defines the threshold for canyon formation.
gammaGamma factor (> 0) that adjusts the intensity of the canyon effect. A higher value increases the effect. The default value is 4.0.
p_maskOptional filter mask, with values expected in the range [0, 1]. The mask specifies which parts of the heightmap are affected by the transformation.
p_noiseOptional noise array used to introduce variation in the canyon effect. If not provided, no additional noise is applied.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
shape = {512, 512};
glm::vec2 res = {2.f, 2.f};
int seed = 1;
auto z1 = z;
{
int ir = 16;
float gamma = 2.f;
hmap::recast_peak(z1, ir, gamma);
}
auto z2 = z;
{
shape,
res,
seed++);
hmap::remap(noise, -0.1f, 0.1f);
float zcut = 0.5f;
float gamma = 4.f;
hmap::recast_canyon(z2, zcut, gamma, &noise);
}
auto z3 = z;
{
float talus = 2.f / shape.x;
int ir = 4;
float amplitude = 0.2f;
float kw = 16.f;
float gamma = 0.5f;
hmap::recast_rocky_slopes(z3, talus, ir, amplitude, seed, kw, gamma);
}
auto z4 = z;
auto z5 = z;
{
float talus = 1.f / shape.x;
int ir = 32;
float amplitude = 0.05f;
float gain = 1.5f;
hmap::gpu::recast_cliff(z4, talus, ir, amplitude, gain);
float angle = 0.f;
hmap::gpu::recast_cliff_directional(z5, talus, ir, amplitude, angle, gain);
}
auto z6 = z;
auto z7 = z;
{
float k = 0.01f;
hmap::recast_billow(z6, 0.5f, k);
hmap::recast_sag(z7, 0.5f, k);
}
auto z8 = z;
{
z8.to_png("out0.png", hmap::Cmap::GRAY, false, CV_16U);
hmap::recast_escarpment(z8, 16, 0.1f, 1.f, false, true);
z8.to_png("out1.png", hmap::Cmap::GRAY, false, CV_16U);
}
hmap::export_banner_png("ex_recast.png",
{z, z1, z2, z3, z4, z5, z6, z7, z8},
true);
}

Result

◆ recast_canyon() [2/4]

void hmap::recast_canyon ( Array & array,
const Array & vcut,
const Array * p_mask,
float gamma = 4.f )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ recast_canyon() [3/4]

void hmap::recast_canyon ( Array & array,
float vcut,
const Array * p_mask,
float gamma = 4.f,
const Array * p_noise = nullptr )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ recast_canyon() [4/4]

void hmap::recast_canyon ( Array & array,
float vcut,
float gamma = 4.f,
const Array * p_noise = nullptr )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ recast_cracks()

void hmap::recast_cracks ( Array & array,
float cut_min = 0.05f,
float cut_max = 0.5f,
float k_smoothing = 0.01f,
float vmin = 0.f,
float vmax = -1.f )

◆ recast_escarpment() [1/2]

void hmap::recast_escarpment ( Array & array,
int ir = 16,
float ratio = 0.1f,
float scale = 1.f,
bool reverse = false,
bool transpose_effect = false,
float global_scaling = 0.f )

Applies an escarpment effect to the given 2D array, modifying its values based on cumulative displacement with optional directional and transpositional transformations.

This function calculates cumulative displacement along the x-axis based on relative elevation differences between adjacent cells. The displacement is scaled and optionally reversed, then used to apply a warping effect to the array, simulating an escarpment feature. An optional global scaling factor can further adjust the displacement effect intensity.

Parameters
arrayReference to the 2D array where the escarpment effect will be applied.
irRadius for the smoothing kernel used on the displacement, controlling the smoothness of the effect. Larger values result in smoother transitions.
ratioThe ratio influencing displacement; values > 1.0 increase displacement sensitivity to height differences.
scaleThe scaling factor for the cumulative displacement, affecting the intensity of the effect.
reverseIf true, reverses the direction of the displacement effect.
transpose_effectIf true, transposes the array before and after applying the effect.
global_scalingAn additional scaling factor for the displacement; if set to 0, a default value is computed based on the array's range and size. Higher values increase the overall effect.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
shape = {512, 512};
glm::vec2 res = {2.f, 2.f};
int seed = 1;
auto z1 = z;
{
int ir = 16;
float gamma = 2.f;
hmap::recast_peak(z1, ir, gamma);
}
auto z2 = z;
{
shape,
res,
seed++);
hmap::remap(noise, -0.1f, 0.1f);
float zcut = 0.5f;
float gamma = 4.f;
hmap::recast_canyon(z2, zcut, gamma, &noise);
}
auto z3 = z;
{
float talus = 2.f / shape.x;
int ir = 4;
float amplitude = 0.2f;
float kw = 16.f;
float gamma = 0.5f;
hmap::recast_rocky_slopes(z3, talus, ir, amplitude, seed, kw, gamma);
}
auto z4 = z;
auto z5 = z;
{
float talus = 1.f / shape.x;
int ir = 32;
float amplitude = 0.05f;
float gain = 1.5f;
hmap::gpu::recast_cliff(z4, talus, ir, amplitude, gain);
float angle = 0.f;
hmap::gpu::recast_cliff_directional(z5, talus, ir, amplitude, angle, gain);
}
auto z6 = z;
auto z7 = z;
{
float k = 0.01f;
hmap::recast_billow(z6, 0.5f, k);
hmap::recast_sag(z7, 0.5f, k);
}
auto z8 = z;
{
z8.to_png("out0.png", hmap::Cmap::GRAY, false, CV_16U);
hmap::recast_escarpment(z8, 16, 0.1f, 1.f, false, true);
z8.to_png("out1.png", hmap::Cmap::GRAY, false, CV_16U);
}
hmap::export_banner_png("ex_recast.png",
{z, z1, z2, z3, z4, z5, z6, z7, z8},
true);
}

Result

◆ recast_escarpment() [2/2]

void hmap::recast_escarpment ( Array & array,
const Array * p_mask,
int ir = 16,
float ratio = 0.1f,
float scale = 1.f,
bool reverse = false,
bool transpose_effect = false,
float global_scaling = 0.f )

Applies an escarpment effect to the given 2D array, with an optional mask to blend the effect.

This overload allows for a blending mask that controls the intensity of the escarpment effect at each point in the array. The mask values range between 0 and 1, where values closer to 1 fully apply the effect, and values closer to 0 reduce it. An optional global scaling factor can further adjust the displacement effect intensity.

Parameters
arrayReference to the 2D array where the escarpment effect will be applied.
p_maskPointer to an optional mask array for blending the effect, where values range from 0 to 1. A nullptr applies the effect fully without blending.
irRadius for the smoothing kernel used on the displacement, controlling the smoothness of the effect. Larger values result in smoother transitions.
ratioThe ratio influencing displacement; values > 1.0 increase displacement sensitivity to height differences.
scaleThe scaling factor for the cumulative displacement, affecting the intensity of the effect.
reverseIf true, reverses the direction of the displacement effect.
transpose_effectIf true, transposes the array before and after applying the effect.
global_scalingAn additional scaling factor for the displacement; if set to 0, a default value is computed based on the array's range and size. Higher values increase the overall effect.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
shape = {512, 512};
glm::vec2 res = {2.f, 2.f};
int seed = 1;
auto z1 = z;
{
int ir = 16;
float gamma = 2.f;
hmap::recast_peak(z1, ir, gamma);
}
auto z2 = z;
{
shape,
res,
seed++);
hmap::remap(noise, -0.1f, 0.1f);
float zcut = 0.5f;
float gamma = 4.f;
hmap::recast_canyon(z2, zcut, gamma, &noise);
}
auto z3 = z;
{
float talus = 2.f / shape.x;
int ir = 4;
float amplitude = 0.2f;
float kw = 16.f;
float gamma = 0.5f;
hmap::recast_rocky_slopes(z3, talus, ir, amplitude, seed, kw, gamma);
}
auto z4 = z;
auto z5 = z;
{
float talus = 1.f / shape.x;
int ir = 32;
float amplitude = 0.05f;
float gain = 1.5f;
hmap::gpu::recast_cliff(z4, talus, ir, amplitude, gain);
float angle = 0.f;
hmap::gpu::recast_cliff_directional(z5, talus, ir, amplitude, angle, gain);
}
auto z6 = z;
auto z7 = z;
{
float k = 0.01f;
hmap::recast_billow(z6, 0.5f, k);
hmap::recast_sag(z7, 0.5f, k);
}
auto z8 = z;
{
z8.to_png("out0.png", hmap::Cmap::GRAY, false, CV_16U);
hmap::recast_escarpment(z8, 16, 0.1f, 1.f, false, true);
z8.to_png("out1.png", hmap::Cmap::GRAY, false, CV_16U);
}
hmap::export_banner_png("ex_recast.png",
{z, z1, z2, z3, z4, z5, z6, z7, z8},
true);
}

Result

◆ recast_peak() [1/2]

void hmap::recast_peak ( Array & array,
int ir,
float gamma = 2.f,
float k = 0.1f )

Transform heightmap to give a "peak" like appearance.

This function modifies the heightmap to create a "peak" effect, where the elevations are adjusted to emphasize peak-like features. The transformation is applied based on a filter radius (ir) and involves gamma correction and smoothing parameters. The effect can be selectively applied using a filter mask.

Warning
Array values are expected to be in the range [0, 1].
Parameters
arrayInput array representing the heightmap to be transformed.
irFilter radius used to smooth the heightmap before applying the peak effect.
gammaGamma factor (> 0) that adjusts the intensity of the peak effect. A higher value increases the effect. The default value is 2.0. For details on gamma correction, see gamma_correction.
kSmoothing parameter (> 0) that controls the degree of smoothing applied during the transformation. Higher values result in more smoothing. The default value is 0.1.
p_maskOptional filter mask, with values expected in the range [0, 1]. The mask specifies which parts of the heightmap are affected by the peak transformation.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
shape = {512, 512};
glm::vec2 res = {2.f, 2.f};
int seed = 1;
auto z1 = z;
{
int ir = 16;
float gamma = 2.f;
hmap::recast_peak(z1, ir, gamma);
}
auto z2 = z;
{
shape,
res,
seed++);
hmap::remap(noise, -0.1f, 0.1f);
float zcut = 0.5f;
float gamma = 4.f;
hmap::recast_canyon(z2, zcut, gamma, &noise);
}
auto z3 = z;
{
float talus = 2.f / shape.x;
int ir = 4;
float amplitude = 0.2f;
float kw = 16.f;
float gamma = 0.5f;
hmap::recast_rocky_slopes(z3, talus, ir, amplitude, seed, kw, gamma);
}
auto z4 = z;
auto z5 = z;
{
float talus = 1.f / shape.x;
int ir = 32;
float amplitude = 0.05f;
float gain = 1.5f;
hmap::gpu::recast_cliff(z4, talus, ir, amplitude, gain);
float angle = 0.f;
hmap::gpu::recast_cliff_directional(z5, talus, ir, amplitude, angle, gain);
}
auto z6 = z;
auto z7 = z;
{
float k = 0.01f;
hmap::recast_billow(z6, 0.5f, k);
hmap::recast_sag(z7, 0.5f, k);
}
auto z8 = z;
{
z8.to_png("out0.png", hmap::Cmap::GRAY, false, CV_16U);
hmap::recast_escarpment(z8, 16, 0.1f, 1.f, false, true);
z8.to_png("out1.png", hmap::Cmap::GRAY, false, CV_16U);
}
hmap::export_banner_png("ex_recast.png",
{z, z1, z2, z3, z4, z5, z6, z7, z8},
true);
}

Result

◆ recast_peak() [2/2]

void hmap::recast_peak ( Array & array,
int ir,
const Array * p_mask,
float gamma = 2.f,
float k = 0.1f )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ recast_rocky_slopes() [1/2]

void hmap::recast_rocky_slopes ( Array & array,
float talus,
int ir,
float amplitude,
std::uint32_t seed,
float kw,
float gamma = 0.5f,
const Array * p_noise = nullptr,
const UvRect & uv_rect = UvRect::unit() )

Transform heightmap by adding "rock-like" features at higher slopes.

This function modifies the heightmap to introduce rock-like features, particularly at locations with higher slopes. The transformation is controlled by parameters defining talus limit, filter radius, amplitude, and noise characteristics. The rock features are generated using a specified random seed and can be customized with optional noise and gamma correction. A filter mask can be applied to control which parts of the heightmap are affected.

Parameters
arrayInput array representing the heightmap to be transformed.
talusTalus limit that determines the threshold above which rock-like features are introduced based on slope steepness.
irFilter radius used to smooth the heightmap and define the area of influence for adding rock features.
amplitudeAmplitude of the rock features. This value controls the intensity of the rock-like appearance.
seedRandom number seed used to generate noise patterns for the rock features. Different seeds produce different rock patterns.
kwNoise wavenumber with respect to a unit domain, influencing the frequency of rock features. Higher values result in more detailed rock textures.
gammaGamma correction coefficient applied to the rock features. This parameter adjusts the contrast of the rock features. The default value is 0.5.
p_noiseOptional reference to an input noise array used for generating rock features. If provided, it overrides the default noise generator.
p_maskOptional filter mask, with values expected in the range [0, 1]. The mask specifies which parts of the heightmap are affected by the rock feature transformation.
bboxBounding box defining the region of interest within the heightmap. This parameter specifies the coordinates of the bounding box in the format {xmin, xmax, ymin, ymax}. The default bounding box covers the entire domain.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
shape = {512, 512};
glm::vec2 res = {2.f, 2.f};
int seed = 1;
auto z1 = z;
{
int ir = 16;
float gamma = 2.f;
hmap::recast_peak(z1, ir, gamma);
}
auto z2 = z;
{
shape,
res,
seed++);
hmap::remap(noise, -0.1f, 0.1f);
float zcut = 0.5f;
float gamma = 4.f;
hmap::recast_canyon(z2, zcut, gamma, &noise);
}
auto z3 = z;
{
float talus = 2.f / shape.x;
int ir = 4;
float amplitude = 0.2f;
float kw = 16.f;
float gamma = 0.5f;
hmap::recast_rocky_slopes(z3, talus, ir, amplitude, seed, kw, gamma);
}
auto z4 = z;
auto z5 = z;
{
float talus = 1.f / shape.x;
int ir = 32;
float amplitude = 0.05f;
float gain = 1.5f;
hmap::gpu::recast_cliff(z4, talus, ir, amplitude, gain);
float angle = 0.f;
hmap::gpu::recast_cliff_directional(z5, talus, ir, amplitude, angle, gain);
}
auto z6 = z;
auto z7 = z;
{
float k = 0.01f;
hmap::recast_billow(z6, 0.5f, k);
hmap::recast_sag(z7, 0.5f, k);
}
auto z8 = z;
{
z8.to_png("out0.png", hmap::Cmap::GRAY, false, CV_16U);
hmap::recast_escarpment(z8, 16, 0.1f, 1.f, false, true);
z8.to_png("out1.png", hmap::Cmap::GRAY, false, CV_16U);
}
hmap::export_banner_png("ex_recast.png",
{z, z1, z2, z3, z4, z5, z6, z7, z8},
true);
}

Result

◆ recast_rocky_slopes() [2/2]

void hmap::recast_rocky_slopes ( Array & array,
float talus,
int ir,
float amplitude,
std::uint32_t seed,
float kw,
const Array * p_mask,
float gamma = 0.5f,
const Array * p_noise = nullptr,
const UvRect & uv_rect = UvRect::unit() )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ recast_sag() [1/2]

void hmap::recast_sag ( Array & array,
float vref,
float k )

Transform heightmap to give a "cliff" like appearance.

This function modifies the heightmap to create a "cliff" effect by folding the elevations around a reference height (vref). The transformation is influenced by a smoothing coefficient (k) and can be selectively applied using a filter mask.

Parameters
arrayInput array representing the heightmap to be transformed.
vrefReference elevation where the heightmap is folded to create the cliff-like appearance. Elevations near this value will be prominently altered.
kSmoothing coefficient that controls the degree of smoothing applied during the transformation. A higher value results in smoother cliffs. The default value is not specified in this function; it must be provided by the user.
p_maskOptional filter mask, with values expected in the range [0, 1]. The mask specifies which parts of the heightmap are affected by the cliff transformation. If not provided, the transformation is applied to the entire heightmap.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
shape = {512, 512};
glm::vec2 res = {2.f, 2.f};
int seed = 1;
auto z1 = z;
{
int ir = 16;
float gamma = 2.f;
hmap::recast_peak(z1, ir, gamma);
}
auto z2 = z;
{
shape,
res,
seed++);
hmap::remap(noise, -0.1f, 0.1f);
float zcut = 0.5f;
float gamma = 4.f;
hmap::recast_canyon(z2, zcut, gamma, &noise);
}
auto z3 = z;
{
float talus = 2.f / shape.x;
int ir = 4;
float amplitude = 0.2f;
float kw = 16.f;
float gamma = 0.5f;
hmap::recast_rocky_slopes(z3, talus, ir, amplitude, seed, kw, gamma);
}
auto z4 = z;
auto z5 = z;
{
float talus = 1.f / shape.x;
int ir = 32;
float amplitude = 0.05f;
float gain = 1.5f;
hmap::gpu::recast_cliff(z4, talus, ir, amplitude, gain);
float angle = 0.f;
hmap::gpu::recast_cliff_directional(z5, talus, ir, amplitude, angle, gain);
}
auto z6 = z;
auto z7 = z;
{
float k = 0.01f;
hmap::recast_billow(z6, 0.5f, k);
hmap::recast_sag(z7, 0.5f, k);
}
auto z8 = z;
{
z8.to_png("out0.png", hmap::Cmap::GRAY, false, CV_16U);
hmap::recast_escarpment(z8, 16, 0.1f, 1.f, false, true);
z8.to_png("out1.png", hmap::Cmap::GRAY, false, CV_16U);
}
hmap::export_banner_png("ex_recast.png",
{z, z1, z2, z3, z4, z5, z6, z7, z8},
true);
}

Result

◆ recast_sag() [2/2]

void hmap::recast_sag ( Array & array,
float vref,
float k,
const Array * p_mask )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ recurve() [1/2]

void hmap::recurve ( Array & array,
const std::vector< float > & t,
const std::vector< float > & v )

Apply a curve adjustment filter to the array.

This function applies a curve adjustment to the heightmap by mapping input values to output values according to a given correction curve. The curve is monotonically interpolated, and any values outside the defined input range are clipped. The filter can be selectively applied using a mask.

Parameters
arrayInput array representing the heightmap to be adjusted.
tVector of input values for the correction curve. These values define the x-coordinates (input values) of the curve.
vVector of output values for the correction curve. These values define the y-coordinates (output values) of the curve corresponding to the input values in t.
p_maskOptional filter mask, with values expected in the range [0, 1]. The mask specifies which parts of the heightmap are affected by the curve adjustment. If not provided, the curve adjustment is applied to the entire heightmap.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {2.f, 2.f};
int seed = 1;
auto z0 = z;
// curve definition (will be monotically interpolated and values
// outside the input range avec clipped)
std::vector<float> t = {0.f, 0.5f, 1.f};
std::vector<float> v = {0.f, 0.25f, 1.f};
hmap::recurve(z, t, v);
hmap::export_banner_png("ex_recurve.png", {z0, z}, hmap::Cmap::VIRIDIS);
}
void recurve(Array &array, const std::vector< float > &t, const std::vector< float > &v)
Apply a curve adjustment filter to the array.
Definition recurve.cpp:19

Result

◆ recurve() [2/2]

void hmap::recurve ( Array & array,
const std::vector< float > & t,
const std::vector< float > & v,
const Array * p_mask )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ recurve_bexp() [1/3]

void hmap::recurve_bexp ( Array & array,
float tau = 0.5f )

Apply a curve adjustment filter using a "bumpy exponential-shape" curve.

This function adjusts the heightmap using a "bumpy exponential-shape" curve, where the curve has an exponential decay defined by the parameter tau. The curve transformation is applied to the entire heightmap or selectively using a filter mask.

Warning
Array values are expected to be in the range [0, 1].
Parameters
arrayInput array representing the heightmap to be adjusted.
p_maskOptional filter mask, with values expected in the range [0, 1]. The mask specifies which parts of the heightmap are affected by the curve adjustment. If not provided, the adjustment is applied to the entire heightmap.
tauExponential decay parameter that defines the shape of the "bumpy" curve. Higher values of tau result in a sharper curve. The default value is 0.5.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {2.f, 2.f};
int seed = 1;
auto zs = z;
auto zb = z;
auto ze = z;
auto zk = z;
auto zr = z;
hmap::recurve_s(zs); // "gentle S"
hmap::recurve_bexp(zb, 0.5f); // bumpy exponential
hmap::recurve_exp(ze, 0.5f); // sharp exponential
hmap::recurve_kura(zk, 2.f, 0.5f); // Kumaraswamy
hmap::recurve_smoothstep_rational(zr, 0.5f); // general smoothstep
hmap::export_banner_png("ex_recurve_xxx.png",
{z, zs, zb, ze, zk, zr},
}
void recurve_exp(Array &array, float tau=0.5f)
Apply a curve adjustment filter using a "sharp exponential-shape" curve.
Definition recurve.cpp:85
void recurve_s(Array &array)
Apply a curve adjustment filter using a smooth "S-shape" curve.
Definition recurve.cpp:127
void recurve_kura(Array &array, float a, float b)
Apply a curve adjustment filter using Kumaraswamy's cumulative distribution function (CDF).
Definition recurve.cpp:106
void recurve_bexp(Array &array, float tau=0.5f)
Apply a curve adjustment filter using a "bumpy exponential-shape" curve.
Definition recurve.cpp:64
void recurve_smoothstep_rational(Array &array, float n)
Apply a curve adjustment filter using an nth-order smoothstep curve.
Definition recurve.cpp:147

Result

◆ recurve_bexp() [2/3]

void hmap::recurve_bexp ( Array & array,
const Array * p_mask,
float tau = 0.5f )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ recurve_exp() [1/3]

void hmap::recurve_exp ( Array & array,
float tau = 0.5f )

Apply a curve adjustment filter using a "sharp exponential-shape" curve.

This function adjusts the heightmap using a "sharp exponential-shape" curve, where the curve has an exponential decay defined by the parameter tau. The curve transformation can be applied to the entire heightmap or selectively using a filter mask.

Warning
Array values are expected to be in the range [0, 1].
Parameters
arrayInput array representing the heightmap to be adjusted.
p_maskOptional filter mask, with values expected in the range [0, 1]. The mask specifies which parts of the heightmap are affected by the curve adjustment. If not provided, the adjustment is applied to the entire heightmap.
tauExponential decay parameter that defines the shape of the "sharp" curve. Higher values of tau result in a steeper curve. The default value is 0.5.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {2.f, 2.f};
int seed = 1;
auto zs = z;
auto zb = z;
auto ze = z;
auto zk = z;
auto zr = z;
hmap::recurve_s(zs); // "gentle S"
hmap::recurve_bexp(zb, 0.5f); // bumpy exponential
hmap::recurve_exp(ze, 0.5f); // sharp exponential
hmap::recurve_kura(zk, 2.f, 0.5f); // Kumaraswamy
hmap::recurve_smoothstep_rational(zr, 0.5f); // general smoothstep
hmap::export_banner_png("ex_recurve_xxx.png",
{z, zs, zb, ze, zk, zr},
}

Result

◆ recurve_exp() [2/3]

void hmap::recurve_exp ( Array & array,
const Array * p_mask,
float tau = 0.5f )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ recurve_kura() [1/2]

void hmap::recurve_kura ( Array & array,
float a,
float b )

Apply a curve adjustment filter using Kumaraswamy's cumulative distribution function (CDF).

This function transforms the heightmap using Kumaraswamy's CDF, which is defined by two shape parameters, a and b. The transformation applies a curve adjustment that can shape the data closer to 0 or 1 depending on the values of a and b. The adjustment can be applied to the entire heightmap or selectively using a filter mask.

Parameters
arrayInput array representing the heightmap to be adjusted.
aParameter 'a' of Kumaraswamy's CDF, which drives the curve shape towards 0.
bParameter 'b' of Kumaraswamy's CDF, which drives the curve shape towards 1.
p_maskOptional filter mask, with values expected in the range [0, 1]. If provided, the adjustment is applied according to this mask. If not provided, the entire heightmap is adjusted.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {2.f, 2.f};
int seed = 1;
auto zs = z;
auto zb = z;
auto ze = z;
auto zk = z;
auto zr = z;
hmap::recurve_s(zs); // "gentle S"
hmap::recurve_bexp(zb, 0.5f); // bumpy exponential
hmap::recurve_exp(ze, 0.5f); // sharp exponential
hmap::recurve_kura(zk, 2.f, 0.5f); // Kumaraswamy
hmap::recurve_smoothstep_rational(zr, 0.5f); // general smoothstep
hmap::export_banner_png("ex_recurve_xxx.png",
{z, zs, zb, ze, zk, zr},
}

Result

◆ recurve_kura() [2/2]

void hmap::recurve_kura ( Array & array,
float a,
float b,
const Array * p_mask )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ recurve_s() [1/2]

void hmap::recurve_s ( Array & array)

Apply a curve adjustment filter using a smooth "S-shape" curve.

This function adjusts the heightmap using a smooth "S-shape" curve, which transforms the input values in a manner that creates an S-shaped distribution. The transformation can be applied to the entire heightmap or selectively using a filter mask.

Warning
Array values are expected to be in the range [0, 1].
Parameters
arrayInput array representing the heightmap to be adjusted.
p_maskOptional filter mask, with values expected in the range [0, 1]. If provided, the adjustment is applied according to this mask. If not provided, the entire heightmap is adjusted.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {2.f, 2.f};
int seed = 1;
auto zs = z;
auto zb = z;
auto ze = z;
auto zk = z;
auto zr = z;
hmap::recurve_s(zs); // "gentle S"
hmap::recurve_bexp(zb, 0.5f); // bumpy exponential
hmap::recurve_exp(ze, 0.5f); // sharp exponential
hmap::recurve_kura(zk, 2.f, 0.5f); // Kumaraswamy
hmap::recurve_smoothstep_rational(zr, 0.5f); // general smoothstep
hmap::export_banner_png("ex_recurve_xxx.png",
{z, zs, zb, ze, zk, zr},
}

Result

◆ recurve_s() [2/2]

void hmap::recurve_s ( Array & array,
const Array * p_mask )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ recurve_smoothstep_rational() [1/2]

void hmap::recurve_smoothstep_rational ( Array & array,
float n )

Apply a curve adjustment filter using an nth-order smoothstep curve.

This function applies a curve adjustment to the heightmap using a smoothstep function of order n. The smoothstep function provides a smooth transition between 0 and 1, where n determines the smoothness of the transition. The adjustment can be applied to the entire heightmap or selectively using a filter mask.

Warning
Array values are expected to be in the range [0, 1].
Parameters
arrayInput array representing the heightmap to be adjusted.
nSmoothstep order, which determines the degree of smoothness for the transition. n should be a non-negative value (in [0, ∞[).
p_maskOptional filter mask, with values expected in the range [0, 1]. If provided, the adjustment is applied according to this mask. If not provided, the entire heightmap is adjusted.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {2.f, 2.f};
int seed = 1;
auto zs = z;
auto zb = z;
auto ze = z;
auto zk = z;
auto zr = z;
hmap::recurve_s(zs); // "gentle S"
hmap::recurve_bexp(zb, 0.5f); // bumpy exponential
hmap::recurve_exp(ze, 0.5f); // sharp exponential
hmap::recurve_kura(zk, 2.f, 0.5f); // Kumaraswamy
hmap::recurve_smoothstep_rational(zr, 0.5f); // general smoothstep
hmap::export_banner_png("ex_recurve_xxx.png",
{z, zs, zb, ze, zk, zr},
}

Result

◆ recurve_smoothstep_rational() [2/2]

void hmap::recurve_smoothstep_rational ( Array & array,
float n,
const Array * p_mask )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ reverse_above_theshold() [1/4]

void hmap::reverse_above_theshold ( Array & array,
const Array & threshold,
float scaling = 1.f,
float transition_extent = 0.f )

Applies a smooth reversal of values above a given threshold.

This function modifies the elements of an array by "reversing" values that exceed a given threshold value, optionally blending the effect over a transition range.

For values above the threshold:

  • The difference between the value and the threshold is scaled down proportionally to scaling and modulated by a smooth transition (using smoothstep3) based on transition_extent.

For values below the threshold:

  • The values are linearly blended (lerp) with the threshold value using a smooth transition factor, gradually reducing the reversal effect.
Parameters
arrayArray to modify in place.
thresholdArray containing the per-element threshold values.
scalingMultiplier applied to the difference above the threshold.
transition_extentWidth of the smooth transition zone for blending.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
auto z1 = z;
float threshold = 0.7f;
float scaling = 0.5f;
float transition_extent = 0.2f;
hmap::reverse_above_theshold(z1, threshold, scaling, transition_extent);
// array input
auto z2 = z;
shape,
res,
++seed);
hmap::remap(threshold_array, 0.6f, 0.8f);
scaling = 0.2f;
hmap::reverse_above_theshold(z2, threshold_array, scaling, transition_extent);
z2.dump();
hmap::export_banner_png("ex_reverse_above_theshold.png",
{z, z1, z2},
true);
}
Array threshold(const Array &array, float x0, float x1)
Linear threshold.
Definition math.cpp:640
void reverse_above_theshold(Array &array, const Array &threshold, float scaling=1.f, float transition_extent=0.f)
Applies a smooth reversal of values above a given threshold.
Definition filters.cpp:785

Result

◆ reverse_above_theshold() [2/4]

void hmap::reverse_above_theshold ( Array & array,
float threshold,
float scaling = 1.f,
float transition_extent = 0.f )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ reverse_above_theshold() [3/4]

void hmap::reverse_above_theshold ( Array & array,
const Array & threshold,
const Array * p_mask,
float scaling = 1.f,
float transition_extent = 0.f )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ reverse_above_theshold() [4/4]

void hmap::reverse_above_theshold ( Array & array,
float threshold,
const Array * p_mask,
float scaling = 1.f,
float transition_extent = 0.f )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ ridge_accentuate() [1/2]

void hmap::ridge_accentuate ( Array & array,
float strength = 0.1f,
int ir = 0,
bool reverse = false )

Accentuate ridges by gradient-directed resampling along the normal direction.

This filter sharpens and accentuates ridgelines in a heightmap. For each pixel, the terrain surface normal is computed at a scale controlled by ir. The sampling position is displaced along the horizontal normal direction by an amount proportional to strength, and the original heightmap is resampled.

Parameters
arrayInput array representing the terrain (modified in place).
strengthDisplacement amount / ridge intensity (default is 0.1f).
irFilter radius used to smooth terrain before computing the normal (default is 0).
reverseIf true, inverts displacement direction to form valleys/channels (default is false).

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {512, 512};
glm::vec2 res = {4.f, 4.f};
int seed = 42;
// base terrain using fractional Brownian motion
// accentuate ridges using gradient-directed resampling
hmap::Array z2 = z1;
hmap::Array z3 = z1;
float strength = 0.01f;
int ir = 32;
hmap::ridge_accentuate(z2, strength, ir);
hmap::gpu::ridge_accentuate(z3, strength, ir);
z1.dump("z1.png");
z2.dump("z2.png");
z3.dump("z3.png");
// export before and after banner
hmap::export_banner_png("ex_ridge_accentuate.png",
{z1, z2, z3},
true);
}
void ridge_accentuate(Array &array, float strength=0.1f, int ir=0, bool reverse=false)
See hmap::ridge_accentuate.
Definition filters_gpu.cpp:405
void ridge_accentuate(Array &array, float strength=0.1f, int ir=0, bool reverse=false)
Accentuate ridges by gradient-directed resampling along the normal direction.
Definition ridge_accentuate.cpp:15

Result

◆ ridge_accentuate() [2/2]

void hmap::ridge_accentuate ( Array & array,
const Array * p_mask,
float strength = 0.1f,
int ir = 0,
bool reverse = false )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ saturate() [1/2]

void hmap::saturate ( Array & array,
float vmin,
float vmax,
float from_min,
float from_max,
float k = 0.f )

Saturate the array values based on the input interval [vmin, vmax] (the output amplitude is not modified).

This function adjusts the heightmap values to fit within the specified range [vmin, vmax]. Values outside the range [from_min, from_max] are clamped to [vmin, vmax]. The output amplitude of the heightmap remains unchanged.

Parameters
arrayInput array representing the heightmap to be saturated.
vminThe lower bound of the range to remap to.
vmaxThe upper bound of the range to remap to.
from_minThe lower bound of the range to remap from.
from_maxThe upper bound of the range to remap from.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
auto zs = z;
float vmin = -0.2f;
float vmax = 0.2f;
float k = 0.1f;
hmap::saturate(zs, vmin, vmax, k);
auto zp = z;
// remove 5% lowest and 5% highest
hmap::saturate_percentile(zp, 0.05f, 0.95f, k);
hmap::export_banner_png("ex_saturate.png", {z, zs, zp}, hmap::Cmap::MAGMA);
}
void saturate_percentile(Array &array, float percentile_low, float percentile_high, float k=0.f)
Saturate values based on percentile range.
Definition recurve.cpp:205

Result

See unit tests: test_saturate.cpp

◆ saturate() [2/2]

void hmap::saturate ( Array & array,
float vmin,
float vmax,
float k = 0.f )

◆ saturate_percentile()

void hmap::saturate_percentile ( Array & array,
float percentile_low,
float percentile_high,
float k = 0.f )

Saturate values based on percentile range.

Computes low/high bounds from percentiles and applies saturation scaling.

Parameters
arrayInput array (modified in place).
percentile_lowLower percentile [0–1].
percentile_highUpper percentile [0–1].
kSaturation strength.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
auto zs = z;
float vmin = -0.2f;
float vmax = 0.2f;
float k = 0.1f;
hmap::saturate(zs, vmin, vmax, k);
auto zp = z;
// remove 5% lowest and 5% highest
hmap::saturate_percentile(zp, 0.05f, 0.95f, k);
hmap::export_banner_png("ex_saturate.png", {z, zs, zp}, hmap::Cmap::MAGMA);
}

Result

See unit tests: test_saturate.cpp

◆ sharpen() [1/2]

void hmap::sharpen ( Array & array,
float ratio = 1.f )

Apply a sharpening filter based on the Laplace operator.

This function applies a sharpening filter to the input array using the Laplace operator. The sharpening effect can be controlled by adjusting the ratio parameter, which determines the balance between the sharpened and non-sharpened output. A ratio of 1 applies full sharpening, while a ratio of 0 applies no sharpening.

Parameters
arrayInput array representing the heightmap or image to be sharpened.
p_maskOptional filter mask, expected in the range [0, 1]. If provided, sharpening is applied according to this mask. If not provided, the entire array is sharpened.
ratioRatio of the sharpening effect. A value of 1 applies full sharpening, while a value of 0 applies no sharpening. Default is 1.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
auto z0 = z;
hstack(z0, z).to_png("ex_sharpen.png", hmap::Cmap::VIRIDIS);
}
void sharpen(Array &array, float ratio=1.f)
Apply a sharpening filter based on the Laplace operator.
Definition filters.cpp:862

Result

◆ sharpen() [2/2]

void hmap::sharpen ( Array & array,
const Array * p_mask,
float ratio = 1.f )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ sharpen_cone() [1/2]

void hmap::sharpen_cone ( Array & array,
int ir,
float intensity = 0.5f )

Apply a sharpening filter based on a smooth cone filter.

This function applies a sharpening filter to the input array using a smooth cone filter. The sharpening effect can be controlled by the scale parameter, and the size of the smoothing operation is determined by the ir parameter. The optional filter mask allows selective application of the sharpening effect.

Parameters
arrayInput array representing the heightmap or image to be sharpened.
p_maskOptional filter mask, expected in the range [0, 1]. If provided, sharpening is applied according to this mask. If not provided, the entire array is sharpened.
irFilter radius, which determines the size of the smoothing operation.
scaleSharpening scale. Adjusts the intensity of the sharpening effect. Default is 0.5.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
auto z1 = z0;
int ir = 16;
hmap::export_banner_png("ex_sharpen_clone.png", {z0, z1}, hmap::Cmap::JET);
}
void sharpen_cone(Array &array, int ir, float intensity=0.5f)
Apply a sharpening filter based on a smooth cone filter.
Definition filters.cpp:886

Result

◆ sharpen_cone() [2/2]

void hmap::sharpen_cone ( Array & array,
const Array * p_mask,
int ir,
float scale = 0.5f )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ shrink() [1/4]

void hmap::shrink ( Array & array,
int ir,
int iterations = 1 )

Apply shrinking, or "deflating", to emphasize the ridges in the heightmap.

This function applies a shrinking filter to the input array, which accentuates the ridges by shrinking or deflating the terrain features. The filter radius ir determines the extent of the deflation. You can also apply the shrinking effect selectively using an optional filter mask. Additionally, an alternative method using a custom kernel is available.

Parameters
arrayInput array representing the heightmap to be processed.
irFilter radius, which controls the extent of the shrinking effect.
p_maskOptional filter mask, expected in the range [0, 1]. If provided, shrinking is applied according to this mask. If not provided, the entire array is processed.
kernelOptional custom kernel to be used for the shrinking operation. If provided, this kernel will override the default filter radius.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
z.infos();
int ir = 64;
hmap::Array z1 = z;
hmap::expand(z1, ir);
hmap::Array z2 = z;
hmap::shrink(z2, ir);
hmap::Array z3 = z;
hmap::Array kernel = hmap::lorentzian(glm::ivec2(2 * ir + 1, 2 * ir + 1));
hmap::shrink(z3, kernel);
hmap::export_banner_png("ex_expand.png",
{z, z1, z2, z3},
}

Result

See also
ex_expand

◆ shrink() [2/4]

void hmap::shrink ( Array & array,
int ir,
const Array * p_mask,
int iterations = 1 )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ shrink() [3/4]

void hmap::shrink ( Array & array,
const Array & kernel,
int iterations = 1 )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ shrink() [4/4]

void hmap::shrink ( Array & array,
const Array & kernel,
const Array * p_mask,
int iterations = 1 )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ shrink_directional()

void hmap::shrink_directional ( Array & array,
int ir,
float angle,
float aspect_ratio,
float anisotropy = 1.f,
const Array * p_mask = nullptr )

Apply directional shrinking, or "deflating", to emphasize the ridges in the terrain.

This function applies a directional shrinking filter to the input array, enhancing the ridges by shrinking or deflating the terrain features with respect to a specified direction. Parameters include filter radius ir, direction angle, aspect ratio, and anisotropy to control the shape and orientation of the filter. An optional filter mask can be used for selective application.

Parameters
arrayInput array representing the heightmap to be processed.
irFilter radius, which controls the extent of the shrinking effect.
angleAngle (in degrees) of the directional filter.
aspect_ratioPulse aspect ratio, which influences the shape of the filter.
anisotropyPulse width ratio between upstream and downstream sides. Default is 1.
p_maskOptional filter mask, expected in the range [0, 1]. If provided, shrinking is applied according to this mask. If not provided, the entire array is processed.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
int ir = 64;
float angle = 30.f;
float aspect_ratio = 0.2f;
hmap::Array z1 = z;
hmap::expand_directional(z1, ir, angle, aspect_ratio);
hmap::Array z2 = z;
hmap::shrink_directional(z2, ir, angle, aspect_ratio);
hmap::export_banner_png("ex_expand_directional.png",
{z, z1, z2},
}

Result

◆ smooth_cone() [1/2]

void hmap::smooth_cone ( Array & array,
int ir )

Apply a convolution filter with a cone kernel to smooth the array.

This function performs convolution on the input array using a cone-shaped kernel. The cone radius ir determines the extent of the smoothing effect. An optional filter mask can be used for selective smoothing.

Parameters
arrayInput array representing the heightmap or image to be smoothed.
irCone radius, which controls the extent of the smoothing effect. The cone's half-width is half this radius.
p_maskOptional filter mask, expected in the range [0, 1]. If provided, smoothing is applied according to this mask. If not provided, the entire array is processed.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
int radius = 16;
hmap::Array z0 = z;
hmap::smooth_cone(z, radius);
hmap::export_banner_png("ex_smooth_cone.png", {z0, z}, hmap::Cmap::VIRIDIS);
}
void smooth_cone(Array &array, int ir)
Apply a convolution filter with a cone kernel to smooth the array.
Definition filters.cpp:963

Result

◆ smooth_cone() [2/2]

void hmap::smooth_cone ( Array & array,
int ir,
const Array * p_mask )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ smooth_cpulse()

void hmap::smooth_cpulse ( Array & array,
int ir,
const Array * p_mask = nullptr,
const UvTile & region = UvTile::dummy(),
ICommunicator & comm = SingleArrayComm::instance() )

Apply filtering to the array using convolution with a cubic pulse kernel.

This function performs convolution on the input array using a cubic pulse kernel. It serves as an alternative to Gaussian smoothing, offering a more compact support with potentially faster computations. For direct comparison with Gaussian smoothing, the pulse radius ir should be set to twice the desired Gaussian half-width.

Parameters
arrayInput array representing the heightmap or image to be smoothed.
irPulse radius, where the half-width of the cubic pulse kernel is half of this value.
p_maskOptional filter mask, expected in the range [0, 1]. If provided, filtering is applied according to this mask. If not provided, the entire array is processed.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {4.f, 4.f};
int seed = 1;
int ir = 64;
hmap::Array cpu = z0;
hmap::Array gpu = z0;
hmap::export_banner_png("ex_smooth_cpulse.png",
{z0, cpu, gpu},
false,
true);
}
void smooth_cpulse(Array &array, int ir, const Array *p_mask=nullptr, const UvTile &region=UvTile::dummy(), ICommunicator &comm=SingleArrayComm::instance())
See hmap::smooth_cpulse.
Definition filters_gpu.cpp:514
void smooth_cpulse(Array &array, int ir, const Array *p_mask=nullptr, const UvTile &region=UvTile::dummy(), ICommunicator &comm=SingleArrayComm::instance())
Apply filtering to the array using convolution with a cubic pulse kernel.
Definition filters.cpp:999

Result

See unit tests: test_smooth_cpulse.cpp

◆ smooth_cpulse_edge_removing()

void hmap::smooth_cpulse_edge_removing ( Array & array,
float talus,
float talus_width,
int ir )

Smooths an array while attenuating edges using a gradient-based pulse.

This function first computes the gradient norm of the input array, applies a sigmoid filter to highlight or attenuate regions based on the local gradient magnitude, and then performs a constrained pulse smoothing pass that respects those gradient-based weights. This is useful for smoothing heightmaps or scalar fields while preserving significant edges such as ridges or cliffs.

Parameters
arrayReference to the input array to be smoothed. The array is modified in-place.
talusThreshold value used in the sigmoid function to control where edge attenuation starts. Lower values affect more regions.
talus_widthWidth (steepness) of the sigmoid transition zone around the talus threshold.
irRadius of the smoothing kernel used in the constrained pulse smoothing step.

◆ smooth_flat()

void hmap::smooth_flat ( Array & array,
int ir )

Applies a smoothing average filter to the given 2D array in both dimensions.

This function creates a smoothing kernel of size (2 \times \text{ir} + 1) with uniform weights, then applies a 1D convolution along both the i (rows) and j (columns) dimensions of the array to achieve a 2D smoothing effect.

Parameters
arrayReference to the 2D array to be smoothed.
irRadius of the smoothing kernel, determining its size as (2 \times \text{ir} + 1). Larger values produce more smoothing.

◆ smooth_gaussian() [1/2]

void hmap::smooth_gaussian ( Array & array,
int ir )

Apply Gaussian filtering to the array.

This function performs convolution on the input array using a Gaussian kernel, which smooths the array by averaging values within a Gaussian-weighted neighborhood. The ir parameter specifies the Gaussian half-width, which influences the extent of the smoothing effect. An optional filter mask can be provided for selective filtering.

Parameters
arrayInput array representing the heightmap or image to be smoothed.
irGaussian half-width, which determines the extent of the smoothing effect.
p_maskOptional filter mask, expected in the range [0, 1]. If provided, filtering is applied according to this mask. If not provided, the entire array is processed.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
int radius = 10;
hmap::Array z0 = z;
hmap::export_banner_png("ex_smooth_gaussian.png",
{z0, z},
}
void smooth_gaussian(Array &array, int ir)
Apply Gaussian filtering to the array.
Definition filters.cpp:1080

Result

◆ smooth_gaussian() [2/2]

void hmap::smooth_gaussian ( Array & array,
int ir,
const Array * p_mask )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ smooth_fill() [1/2]

void hmap::smooth_fill ( Array & array,
int ir,
float k = 0.1f,
Array * p_deposition_map = nullptr )

Apply cubic pulse smoothing to fill lower flat regions while preserving some sharpness.

This function applies a cubic pulse smoothing technique to the input array, specifically designed to fill in lower flat regions without significantly impacting sharp features. It provides a more computationally efficient alternative to the thermal_auto_bedrock method. The p_deposition_map output field captures the amount of smoothing applied.

Parameters
arrayInput array representing the heightmap or image to be processed.
irPulse radius, which determines the extent of the smoothing effect.
kTransition smoothing parameter in the range [0, 1]. It controls the balance between smoothing and preserving sharpness.
p_maskOptional filter mask, expected in the range [0, 1]. If provided, smoothing is applied according to this mask. If not provided, the entire array is processed.
p_deposition_map[out] Optional reference to the deposition map. This output field records the amount of deposition or smoothing applied.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {2.f, 2.f};
int seed = 1;
int radius = 32;
hmap::Array z0 = z;
hmap::smooth_fill(z, radius);
hmap::export_banner_png("ex_smooth_fill.png",
{z0, z},
true);
z.to_file("out.bin");
}
void to_file(const std::string &fname) const
Export the array to a raw binary file.
Definition io.cpp:110
void smooth_fill(Array &array, int ir, float k=0.1f, Array *p_deposition_map=nullptr)
Apply cubic pulse smoothing to fill lower flat regions while preserving some sharpness.
Definition filters.cpp:1119

Result

See also
smooth_cpulse, thermal_auto_bedrock

◆ smooth_fill() [2/2]

void hmap::smooth_fill ( Array & array,
int ir,
const Array * p_mask,
float k = 0.1f,
Array * p_deposition_map = nullptr )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ smooth_fill_holes() [1/2]

void hmap::smooth_fill_holes ( Array & array,
int ir )

Apply smoothing to fill holes (elliptic concave surfaces).

This function applies a smoothing filter to the input array to fill in holes or concave surfaces. The goal is to smooth out regions that are concave, providing a more uniform appearance.

Parameters
arrayInput array representing the heightmap or image to be processed.
irFilter radius, which controls the extent of the smoothing effect.
p_maskOptional filter mask, expected in the range [0, 1]. If provided, smoothing is applied according to this mask. If not provided, the entire array is processed.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {2.f, 2.f};
int seed = 1;
int radius = 8;
auto z1 = z;
auto z2 = z;
hmap::export_banner_png("ex_smooth_fill_holes.png",
{z, z1, z2},
true);
z.to_file("out.bin");
}
void smooth_fill_holes(Array &array, int ir)
Apply smoothing to fill holes (elliptic concave surfaces).
Definition filters.cpp:1154
void smooth_fill_smear_peaks(Array &array, int ir)
Apply smoothing to smear peaks (elliptic convex surfaces).
Definition filters.cpp:1180

Result

See also
smooth_fill_smear_peaks

◆ smooth_fill_holes() [2/2]

void hmap::smooth_fill_holes ( Array & array,
int ir,
const Array * p_mask )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ smooth_fill_smear_peaks() [1/2]

void hmap::smooth_fill_smear_peaks ( Array & array,
int ir )

Apply smoothing to smear peaks (elliptic convex surfaces).

This function applies a smoothing filter designed to reduce the prominence of peaks or convex surfaces in the input array. It smooths out convex regions, creating a more level surface.

Parameters
arrayInput array representing the heightmap or image to be processed.
irFilter radius, which controls the extent of the smoothing effect.
p_maskOptional filter mask, expected in the range [0, 1]. If provided, smoothing is applied according to this mask. If not provided, the entire array is processed.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {2.f, 2.f};
int seed = 1;
int radius = 8;
auto z1 = z;
auto z2 = z;
hmap::export_banner_png("ex_smooth_fill_holes.png",
{z, z1, z2},
true);
z.to_file("out.bin");
}

Result

See also
smooth_fill_holes

◆ smooth_fill_smear_peaks() [2/2]

void hmap::smooth_fill_smear_peaks ( Array & array,
int ir,
const Array * p_mask )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ smoothstep_local() [1/2]

void hmap::smoothstep_local ( Array & array,
int ir )

Applies a localized smoothstep operation to the provided array.

This function modifies the input array using a localized smoothstep operation. It calculates the local minimum and maximum values within a radius (ir) and smooths the values in the array based on these bounds.

Parameters
arrayThe 2D array to be smoothed.
irThe radius used to compute the local minimum and maximum values.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
int ir = 8;
auto z1 = z;
hmap::export_banner_png("ex_smoothstep_local.png",
{z, z1},
}
void smoothstep_local(Array &array, int ir)
Applies a localized smoothstep operation to the provided array.
Definition filters.cpp:1208

Result

◆ smoothstep_local() [2/2]

void hmap::smoothstep_local ( Array & array,
int ir,
const Array * p_mask )

Applies a localized smoothstep operation to the provided array with an optional mask.

If a mask is provided, the function blends the smoothed values with the original array using the mask. Otherwise, it directly applies the localized smoothstep operation.

Parameters
arrayThe 2D array to be smoothed.
irThe radius used to compute the local minimum and maximum values.
p_maskA pointer to an optional mask array. If provided, the smoothed array is blended with the original using this mask.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
int ir = 8;
auto z1 = z;
hmap::export_banner_png("ex_smoothstep_local.png",
{z, z1},
}

Result

◆ steepen() [1/2]

void hmap::steepen ( Array & array,
float scale,
int ir = 8 )

Steepen (or flatten) the array map.

This function applies a steepening effect to the input array, enhancing the contrast of the gradients or flattening features based on the given filter amplitude. The effect is controlled by the scale parameter, and the ir parameter defines the filtering radius for computing the array gradients.

Parameters
arrayInput array representing the heightmap or image to be processed.
scaleFilter amplitude that determines the extent of steepening or flattening.
p_maskOptional filter mask, expected in the range [0, 1]. If provided, steepening is applied according to this mask. If not provided, the entire array is processed.
irFiltering radius of the array gradients, which influences the extent of the effect.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {2.f, 2.f};
int seed = 1;
auto z1 = z;
auto z2 = z;
float scale = 0.05f; // not in pixels
hmap::steepen(z1, scale);
// using a negative scale will "flatten" the map
hmap::steepen(z2, -scale);
hmap::export_banner_png("ex_steepen.png", {z, z1, z2}, hmap::Cmap::TERRAIN);
}
void steepen(Array &array, float scale, int ir=8)
Steepen (or flatten) the array map.
Definition filters.cpp:1234
Cloud scale(const Cloud &cloud, glm::vec2 scale, glm::vec2 center={0.5f, 0.5f})
Scales the point coordinates in a cloud relative to a center point.
Definition cloud_functions.cpp:163

Result

◆ steepen() [2/2]

void hmap::steepen ( Array & array,
float scale,
const Array * p_mask,
int ir = 8 )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ steepen_convective() [1/2]

void hmap::steepen_convective ( Array & array,
float angle,
int iterations = 1,
int ir = 0,
float dt = 0.1f )

Steepen array values by applying a nonlinear convection operator in a given direction.

This function applies a nonlinear convection operator to the input array, simulating the effect described by Burger's equation. The steepening effect is applied in the specified direction (angle) and is controlled by several parameters including the number of iterations, smoothing radius, and time step. The input array values are expected to be in the range [-1, 1].

Parameters
arrayInput array with elements expected to be in the range [-1, 1].
angleSteepening direction in degrees.
iterationsNumber of iterations to perform the convection process.
irSmoothing radius applied to the array values before differentiation.
dtTime step for the convection process, can be chosen smaller than 1 for finer tuning of the steepening effect.
p_maskOptional filter mask, expected in the range [0, 1]. If provided, steepening is applied according to this mask. If not provided, the entire array is processed.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {2.f, 2.f};
int seed = 1;
auto z1 = z;
auto z2 = z;
float angle = 30.f;
int iterations = 3;
int ir = 16;
hmap::steepen_convective(z1, angle, iterations, ir);
z1.infos();
hmap::export_banner_png("ex_steepen_convective.png",
{z, z1},
true);
}
void steepen_convective(Array &array, float angle, int iterations=1, int ir=0, float dt=0.1f)
Steepen array values by applying a nonlinear convection operator in a given direction.
Definition filters.cpp:1255

Result

◆ steepen_convective() [2/2]

void hmap::steepen_convective ( Array & array,
float angle,
const Array * p_mask,
int iterations = 1,
int ir = 0,
float dt = 0.1f )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ terrace() [1/2]

void hmap::terrace ( Array & array,
std::uint32_t seed,
int nlevels,
float gain = 0.9f,
float noise_ratio = 0.f,
const Array * p_noise = nullptr,
float vmin = 0.f,
float vmax = -1.f )

Applies a terrace effect to the values in an array.

This function adjusts the values in the array by applying a terrace or stepped effect, often used for terrain generation or other natural-looking height variations. The terrace effect is controlled by several parameters such as the number of levels, gain, noise ratio, and optional min/max range. The noise is applied to levels for added randomness, and a gain function is applied to smooth the transitions.

Parameters
arrayThe array of values to modify with the terrace effect.
seedSeed value for random number generation.
nlevelsNumber of terrace levels to apply.
gainGain factor for controlling the sharpness of the terrace levels, in [0, 1].
noise_ratioRatio of noise applied to each terrace level, except the first and last.
p_noiseOptional noise array to introduce additional variation per element.
vminMinimum value for terracing; if less than vmax, will be auto-determined.
vmaxMaximum value for terracing; if less than vmin, will be auto-determined.
Note
If p_noise is provided, each value in array is transformed using both the original value and the corresponding noise value from p_noise.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
int nlevels = 5;
float gain = 0.9f;
float noise_ratio = 0.5f;
auto zp = z;
hmap::terrace(zp, seed, nlevels, &z, gain, noise_ratio);
hmap::export_banner_png("ex_terrace.png", {z, zp}, hmap::Cmap::TERRAIN, true);
}
void terrace(Array &array, std::uint32_t seed, int nlevels, float gain=0.9f, float noise_ratio=0.f, const Array *p_noise=nullptr, float vmin=0.f, float vmax=-1.f)
Applies a terrace effect to the values in an array.
Definition filters.cpp:1306

Result

◆ terrace() [2/2]

void hmap::terrace ( Array & array,
std::uint32_t seed,
int nlevels,
const Array * p_mask,
float gain = 0.9f,
float noise_ratio = 0.f,
const Array * p_noise = nullptr,
float vmin = 0.f,
float vmax = -1.f )

Applies a terrace effect to an array with optional masking.

This overloaded version of the terrace function modifies array based on the terrace levels, gain, noise ratio, and an optional mask array. If a mask is provided, the terrace effect is applied conditionally based on the mask values.

Parameters
arrayThe array of values to modify with the terrace effect.
seedSeed value for random number generation.
nlevelsNumber of terrace levels to apply.
p_maskOptional mask array. If provided, blends the terrace effect with original values based on the mask.
gainGain factor for controlling the sharpness of the terrace levels, in [0, 1].
noise_ratioRatio of noise applied to each terrace level, except the first and last.
p_noiseOptional noise array to introduce additional variation per element.
vminMinimum value for terracing; if less than vmax, will be auto-determined.
vmaxMaximum value for terracing; if less than vmin, will be auto-determined.

This function:

  • If no mask is provided, directly applies the terrace effect using the first terrace overload.
  • If a mask is provided, creates a temporary copy of array, applies the terrace effect to it, and then interpolates between array and the modified copy based on mask values.
Note
The mask array allows for blending the terrace effect with the original array for more localized effects.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
int nlevels = 5;
float gain = 0.9f;
float noise_ratio = 0.5f;
auto zp = z;
hmap::terrace(zp, seed, nlevels, &z, gain, noise_ratio);
hmap::export_banner_png("ex_terrace.png", {z, zp}, hmap::Cmap::TERRAIN, true);
}

Result

◆ make_xy_function_from_array()

std::function< float(float, float)> hmap::make_xy_function_from_array ( const Array & array,
const BBox2D & bbox = BBox2D::unit() )

Create a continuous 2D function from a sampled array.

This adaptor takes a discrete 2D array (indexed by i, j) defined over a bounding box and returns a continuous function \(f(x, y)\) that interpolates values at arbitrary 2D positions inside the bounding box.

Parameters
arrayInput array containing sampled values on a regular grid.
bboxBounding box of the array in world coordinates, given as (xmin, xmax, ymin, ymax).
Returns
A function f(point) that returns the interpolated value at a 2D position.

◆ with_noise_function()

template<typename Fn>
decltype(auto) hmap::with_noise_function ( NoiseType noise_type,
glm::vec2 kw,
std::uint32_t seed,
Fn && fn )

Dispatch a noise functor based on the specified noise type.

Parameters
noise_typeThe type of noise function to create (e.g., PERLIN, SIMPLEX2, etc.).
kwThe frequency scaling vector to be used for the noise function.
seedThe random seed for noise generation.
fnCallable invoked with the concrete noise functor.

◆ add_line_bresenham()

void hmap::add_line_bresenham ( CellPath & out,
glm::ivec2 a,
glm::ivec2 b )

Rasterizes a segment between two integer points using Bresenham's algorithm.

Ensures full grid connectivity by filling all intermediate integer cells between points a and b.

Parameters
outOutput container receiving the rasterized points.
aStart point.
bEnd point.

◆ add_noise()

void hmap::add_noise ( CellPath & path,
std::uint32_t seed,
float kw,
float amp,
const glm::ivec2 & shape,
NoiseType noise_type = NoiseType::PERLIN,
int octaves = 8,
float weight = 0.7f,
float persistence = 0.5f,
float lacunarity = 2.f )

Applies transverse noise displacement along an integer path.

The function computes a global direction from first to last point, derives a perpendicular axis, and displaces each point using procedural noise.

Parameters
pathInput/output integer path to deform.
seedRandom seed for noise generation.
kwNoise spatial frequency (scale).
ampMaximum displacement amplitude.
shapeOptional domain scaling / bounds for noise sampling.
noise_typeType of procedural noise to use.
octavesNumber of noise octaves for fractal noise.
weightBlend factor between octaves.
persistenceAmplitude decay per octave.
lacunarityFrequency increase per octave.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
float kw = 4.f;
int seed = 0;
float amp = 128.f;
int i0 = 32;
int i1 = shape.x - i0;
int j0 = 32;
int j1 = 3 * j0;
for (int i = i0; i < i1; ++i)
{
int j = int(float(i - i0) / (i1 - i0) * (j1 - j0) + j0);
ipath.push_back({i, j});
}
hmap::Array a0(shape);
for (const auto &p : ipath)
a0(p) = 1.f;
hmap::add_noise(ipath, seed, kw, amp, shape);
hmap::Array a1(shape);
for (const auto &p : ipath)
a1(p) = 1.f;
hmap::export_banner_png("ex_add_noise_ipath.png", {a0, a1}, hmap::Cmap::GRAY);
}
Ordered path of grid cell indices.
Definition cell_path.hpp:28
void push_back(const glm::ivec2 &idx)
Add a cell index to the end of the path.
Definition cell_path.cpp:92
void add_noise(CellPath &path, std::uint32_t seed, float kw, float amp, const glm::ivec2 &shape, NoiseType noise_type=NoiseType::PERLIN, int octaves=8, float weight=0.7f, float persistence=0.5f, float lacunarity=2.f)
Applies transverse noise displacement along an integer path.
Definition add_noise.cpp:56

Result

◆ enforce_path_adjacency()

void hmap::enforce_path_adjacency ( CellPath & path)

Ensures that an integer path is grid-adjacent and gap-free.

Reconstructs the path so that every consecutive step moves to a neighboring grid cell (8-connected), filling missing cells if needed.

Parameters
pathInput/output path to repair and densify.

◆ is_path_adjacent()

bool hmap::is_path_adjacent ( const CellPath & path)

Checks if a grid path has no gaps (8-connectivity).

Verifies that each consecutive cell is adjacent using Moore neighborhood (max |dx| <= 1 and max |dy| <= 1).

Parameters
pathInput path of grid cells.
Returns
true if the path is fully 8-connected, false otherwise.

◆ cloud_sdf_to_array()

Array hmap::cloud_sdf_to_array ( const Cloud & cloud,
glm::ivec2 shape,
const BBox2D & bbox_array = BBox2D::unit(),
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr )

Compute a distance field from a point cloud.

Parameters
cloudInput point cloud.
shapeOutput array dimensions.
bbox_arrayBounding box of the output domain.
p_noise_xOptional x-direction noise (domain warp).
p_noise_yOptional y-direction noise (domain warp).
Returns
Array of distances to the nearest point.

◆ has_duplicates() [1/2]

bool hmap::has_duplicates ( const Cloud & cloud,
float eps = 1e-9f,
bool xy_only = true )

Checks whether the point cloud contains duplicate points.

Parameters
cloudInput point cloud.
epsDistance tolerance for considering two points identical.
xy_onlyIf true, compares only the X and Y coordinates.
Returns
True if duplicate points are found, false otherwise.

◆ interpolate_values_from_array()

std::vector< float > hmap::interpolate_values_from_array ( const Cloud & cloud,
const Array & array,
const BBox2D & bbox )

Interpolate values from an array at the points' (x, y) locations.

This method computes interpolated values for each point in the cloud based on its (x, y) coordinates and an underlying array, using bilinear interpolation within the specified bounding box.

Parameters
arrayThe input array from which to interpolate values.
bboxThe bounding box of the array.
Returns
std::vector<float> A vector containing the interpolated values for each point.

◆ merge_cloud()

Cloud hmap::merge_cloud ( const Cloud & cloud1,
const Cloud & cloud2 )

Merges two point clouds into one.

Parameters
cloud1The first point cloud to be merged. This cloud will be the base cloud to which the points from the second cloud are added.
cloud2The second point cloud whose points will be appended to the first cloud.
Returns
Cloud The resulting point cloud that includes all points from both cloud1 and cloud2.

◆ merge_clouds()

Cloud hmap::merge_clouds ( const std::vector< Cloud > & clouds)

Merges multiple point clouds into a single cloud.

Parameters
cloudsA vector of Cloud objects to be merged.

◆ random_cloud()

Cloud hmap::random_cloud ( size_t count,
std::uint32_t seed,
const PointSamplingMethod & method = PointSamplingMethod::RND_LHS,
const BBox2D & bbox = BBox2D{} )

Generates a random cloud of points within a bounding box.

Parameters
countNumber of points to generate.
seedRandom number generator seed.
methodSampling method to use. Defaults to PointSamplingMethod::RND_RANDOM.
bboxBounding box in which to generate the points (a,b,c,d = xmin, xmax, ymin, ymax). Defaults to the unit square {0.f, 1.f, 0.f, 1.f}.
Returns
A Cloud containing the generated points.

Example

#include <iostream>
#include "highmap.hpp"
int main(void)
{
// for render only
glm::ivec2 shape = {256, 256};
hmap::Array raster(shape);
std::vector<hmap::Array> zs = {};
std::uint32_t seed = 0;
// density field
glm::vec2 kw = {2.f, 2.f};
hmap::Array density = hmap::noise(hmap::NoiseType::PERLIN, shape, kw, seed);
hmap::remap(density); // /!\ NEEDS TO BE IN [0, 1]
hmap::gain(density, 2); // sharper transition
// base param
size_t count = 1000;
// --- random
{
hmap::Cloud cloud = hmap::random_cloud(count, seed, type);
cloud.to_array(raster);
zs.push_back(raster);
}
hmap::export_banner_png("ex_point_sampling0.png", zs, hmap::Cmap::BONE);
// --- density
{
zs.clear();
zs.push_back(density);
raster = 0.f;
// auto xy = hmap::random_points_density(count, density, seed);
// hmap::Cloud cloud(xy[0], xy[1], 1.f /* value */);
// rejection sampling
hmap::Cloud cloud = hmap::random_cloud_density(count, density, seed);
cloud.to_array(raster);
zs.push_back(raster);
std::cout << "cloud_density count: " << cloud.size() << "\n";
// inverse transform sampling (batch)
raster = 0.f;
density,
seed);
cloud_inv.to_array(raster);
zs.push_back(raster);
std::cout << "cloud_inv count: " << cloud_inv.size() << "\n";
// sequential inverse transform sampling with dynamic local updates (e.g.
// repelling radius)
raster = 0.f;
hmap::InverseSampler2D seq_sampler(density, seed);
hmap::Cloud cloud_seq;
int inhibit_r = 4; // grid radius to depress after each point
for (size_t k = 0; k < count; ++k)
{
glm::vec2 p = seq_sampler.sample();
cloud_seq.push_back(hmap::Point(p.x, p.y, 1.f));
// Depress density around the sampled point on the grid
int cx = static_cast<int>(p.x * (shape.x - 1));
int cy = static_cast<int>(p.y * (shape.y - 1));
seq_sampler.update_region(
[cx, cy, inhibit_r](int i, int j, float cur)
{
float d2 = static_cast<float>((i - cx) * (i - cx) +
(j - cy) * (j - cy));
float r2 = static_cast<float>(inhibit_r * inhibit_r);
if (d2 < r2)
{
float factor = d2 / r2;
return cur * factor;
}
return cur;
},
{cx - inhibit_r, cx + inhibit_r},
{cy - inhibit_r, cy + inhibit_r});
}
cloud_seq.to_array(raster);
zs.push_back(raster);
std::cout << "cloud_seq count: " << cloud_seq.size() << "\n";
// filter
cloud = hmap::random_cloud(count,
seed,
hmap::rejection_filter_density(cloud, density, seed);
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
std::cout << "cloud_rejection count: " << cloud.size() << "\n";
hmap::export_banner_png("ex_point_sampling1.png", zs, hmap::Cmap::BONE);
}
// --- distance based
{
zs.clear();
zs.push_back(density);
float min_dist = 0.02f;
float max_dist = 0.08f;
hmap::Cloud cloud = hmap::random_cloud_distance(min_dist, seed);
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
cloud = hmap::random_cloud_distance(min_dist, max_dist, density, seed);
std::cout << "count: " << cloud.size() << "\n";
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
cloud = hmap::random_cloud_distance_power_law(0.01f /* dist_min */,
0.2f /* dist_max */,
1.2f /* alpha */,
seed);
std::cout << "count: " << cloud.size() << "\n";
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
cloud = hmap::random_cloud_distance_weibull(0.01f /* dist_min */,
0.05f /* lambda */,
1.f /* k */,
seed);
std::cout << "count: " << cloud.size() << "\n";
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
hmap::export_banner_png("ex_point_sampling2.png", zs, hmap::Cmap::BONE);
}
// --- grid jittered
{
zs.clear();
glm::vec2 jitter_amount = {0.3f, 0.3f};
glm::vec2 stagger_ratio = {0.5f, 0.f};
jitter_amount,
stagger_ratio,
seed);
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
hmap::export_banner_png("ex_point_sampling3.png", zs, hmap::Cmap::BONE);
}
}
void set_values_from_min_distance()
Sets point values based on the distance to their nearest neighbor.
Definition cloud.cpp:504
size_t size() const
Get the number of points in the cloud.
Definition cloud.cpp:678
Sequential 2D inverse transform point sampler based on a 2D density array.
Definition inverse_sampler_2d.hpp:35
Cloud random_cloud_jittered(size_t count, const glm::vec2 &jitter_amount, const glm::vec2 &stagger_ratio, std::uint32_t seed, const BBox2D &bbox=BBox2D{})
Generates a jittered grid cloud of points.
Definition cloud.cpp:971
Cloud random_cloud_distance_weibull(float dist_min, float lambda, float k, std::uint32_t seed, const BBox2D &bbox=BBox2D{})
Generates a random cloud of points with distances drawn from a Weibull distribution.
Definition cloud.cpp:960
Cloud random_cloud_distance(float min_dist, std::uint32_t seed, const BBox2D &bbox=BBox2D{})
Generates a random cloud of points separated by at least a given minimum distance.
Definition cloud.cpp:923
Cloud random_cloud_inverse_sampling(size_t count, const Array &density, std::uint32_t seed, const BBox2D &bbox=BBox2D{})
Generates a random cloud of points using inverse transform sampling on a 2D density array.
Definition cloud.cpp:911
@ RND_LHS
Latin Hypercube Sampling.
Definition point_sampling.hpp:38
@ RND_HALTON
Low-discrepancy Halton sequence sampling.
Definition point_sampling.hpp:36
@ RND_RANDOM
Purely random uniform sampling.
Definition point_sampling.hpp:35
@ RND_HAMMERSLEY
Low-discrepancy Hammersley sequence sampling.
Definition point_sampling.hpp:37
@ BONE
Definition colormaps.hpp:84
void rejection_filter_density(Cloud &cloud, const Array &density_mask, std::uint32_t seed, const BBox2D &bbox=BBox2D{})
Filter a point cloud using rejection sampling based on a density mask.
Definition cloud_functions.cpp:141
Cloud random_cloud_distance_power_law(float dist_min, float dist_max, float alpha, std::uint32_t seed, const BBox2D &bbox=BBox2D{})
Generates a random cloud of points with distances drawn from a power-law distribution.
Definition cloud.cpp:945
Cloud random_cloud_density(size_t count, const Array &density, std::uint32_t seed, const BBox2D &bbox=BBox2D{})
Generates a random cloud of points based on a spatial density map.
Definition cloud.cpp:899

Result

◆ random_cloud_density()

Cloud hmap::random_cloud_density ( size_t count,
const Array & density,
std::uint32_t seed,
const BBox2D & bbox = BBox2D{} )

Generates a random cloud of points based on a spatial density map.

The probability of placing a point at a location is proportional to the density value at that location.

Parameters
countNumber of points to generate.
density2D array representing spatial density values.
seedRandom number generator seed.
bboxBounding box in which to generate the points (a,b,c,d = xmin, xmax, ymin, ymax). Defaults to the unit square {0.f, 1.f, 0.f, 1.f}.
Returns
A Cloud containing the generated points.

Example

#include <iostream>
#include "highmap.hpp"
int main(void)
{
// for render only
glm::ivec2 shape = {256, 256};
hmap::Array raster(shape);
std::vector<hmap::Array> zs = {};
std::uint32_t seed = 0;
// density field
glm::vec2 kw = {2.f, 2.f};
hmap::Array density = hmap::noise(hmap::NoiseType::PERLIN, shape, kw, seed);
hmap::remap(density); // /!\ NEEDS TO BE IN [0, 1]
hmap::gain(density, 2); // sharper transition
// base param
size_t count = 1000;
// --- random
{
hmap::Cloud cloud = hmap::random_cloud(count, seed, type);
cloud.to_array(raster);
zs.push_back(raster);
}
hmap::export_banner_png("ex_point_sampling0.png", zs, hmap::Cmap::BONE);
// --- density
{
zs.clear();
zs.push_back(density);
raster = 0.f;
// auto xy = hmap::random_points_density(count, density, seed);
// hmap::Cloud cloud(xy[0], xy[1], 1.f /* value */);
// rejection sampling
hmap::Cloud cloud = hmap::random_cloud_density(count, density, seed);
cloud.to_array(raster);
zs.push_back(raster);
std::cout << "cloud_density count: " << cloud.size() << "\n";
// inverse transform sampling (batch)
raster = 0.f;
density,
seed);
cloud_inv.to_array(raster);
zs.push_back(raster);
std::cout << "cloud_inv count: " << cloud_inv.size() << "\n";
// sequential inverse transform sampling with dynamic local updates (e.g.
// repelling radius)
raster = 0.f;
hmap::InverseSampler2D seq_sampler(density, seed);
hmap::Cloud cloud_seq;
int inhibit_r = 4; // grid radius to depress after each point
for (size_t k = 0; k < count; ++k)
{
glm::vec2 p = seq_sampler.sample();
cloud_seq.push_back(hmap::Point(p.x, p.y, 1.f));
// Depress density around the sampled point on the grid
int cx = static_cast<int>(p.x * (shape.x - 1));
int cy = static_cast<int>(p.y * (shape.y - 1));
seq_sampler.update_region(
[cx, cy, inhibit_r](int i, int j, float cur)
{
float d2 = static_cast<float>((i - cx) * (i - cx) +
(j - cy) * (j - cy));
float r2 = static_cast<float>(inhibit_r * inhibit_r);
if (d2 < r2)
{
float factor = d2 / r2;
return cur * factor;
}
return cur;
},
{cx - inhibit_r, cx + inhibit_r},
{cy - inhibit_r, cy + inhibit_r});
}
cloud_seq.to_array(raster);
zs.push_back(raster);
std::cout << "cloud_seq count: " << cloud_seq.size() << "\n";
// filter
cloud = hmap::random_cloud(count,
seed,
hmap::rejection_filter_density(cloud, density, seed);
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
std::cout << "cloud_rejection count: " << cloud.size() << "\n";
hmap::export_banner_png("ex_point_sampling1.png", zs, hmap::Cmap::BONE);
}
// --- distance based
{
zs.clear();
zs.push_back(density);
float min_dist = 0.02f;
float max_dist = 0.08f;
hmap::Cloud cloud = hmap::random_cloud_distance(min_dist, seed);
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
cloud = hmap::random_cloud_distance(min_dist, max_dist, density, seed);
std::cout << "count: " << cloud.size() << "\n";
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
cloud = hmap::random_cloud_distance_power_law(0.01f /* dist_min */,
0.2f /* dist_max */,
1.2f /* alpha */,
seed);
std::cout << "count: " << cloud.size() << "\n";
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
cloud = hmap::random_cloud_distance_weibull(0.01f /* dist_min */,
0.05f /* lambda */,
1.f /* k */,
seed);
std::cout << "count: " << cloud.size() << "\n";
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
hmap::export_banner_png("ex_point_sampling2.png", zs, hmap::Cmap::BONE);
}
// --- grid jittered
{
zs.clear();
glm::vec2 jitter_amount = {0.3f, 0.3f};
glm::vec2 stagger_ratio = {0.5f, 0.f};
jitter_amount,
stagger_ratio,
seed);
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
hmap::export_banner_png("ex_point_sampling3.png", zs, hmap::Cmap::BONE);
}
}

Result

◆ random_cloud_inverse_sampling()

Cloud hmap::random_cloud_inverse_sampling ( size_t count,
const Array & density,
std::uint32_t seed,
const BBox2D & bbox = BBox2D{} )

Generates a random cloud of points using inverse transform sampling on a 2D density array.

Parameters
countNumber of points to generate.
density2D array representing spatial density values.
seedRandom number generator seed.
bboxBounding box in which to generate the points (xmin, xmax, ymin, ymax). Defaults to the unit square {0.f, 1.f, 0.f, 1.f}.
Returns
A Cloud containing the generated points.

◆ random_cloud_distance() [1/2]

Cloud hmap::random_cloud_distance ( float min_dist,
std::uint32_t seed,
const BBox2D & bbox = BBox2D{} )

Generates a random cloud of points separated by at least a given minimum distance.

Points are distributed randomly but maintain a minimum separation, producing a blue-noise-like distribution.

Parameters
min_distMinimum allowed distance between any two points.
seedRandom number generator seed.
bboxBounding box in which to generate the points (a,b,c,d = xmin, xmax, ymin, ymax). Defaults to the unit square {0.f, 1.f, 0.f, 1.f}.
Returns
A Cloud containing the generated points.

Example

#include <iostream>
#include "highmap.hpp"
int main(void)
{
// for render only
glm::ivec2 shape = {256, 256};
hmap::Array raster(shape);
std::vector<hmap::Array> zs = {};
std::uint32_t seed = 0;
// density field
glm::vec2 kw = {2.f, 2.f};
hmap::Array density = hmap::noise(hmap::NoiseType::PERLIN, shape, kw, seed);
hmap::remap(density); // /!\ NEEDS TO BE IN [0, 1]
hmap::gain(density, 2); // sharper transition
// base param
size_t count = 1000;
// --- random
{
hmap::Cloud cloud = hmap::random_cloud(count, seed, type);
cloud.to_array(raster);
zs.push_back(raster);
}
hmap::export_banner_png("ex_point_sampling0.png", zs, hmap::Cmap::BONE);
// --- density
{
zs.clear();
zs.push_back(density);
raster = 0.f;
// auto xy = hmap::random_points_density(count, density, seed);
// hmap::Cloud cloud(xy[0], xy[1], 1.f /* value */);
// rejection sampling
hmap::Cloud cloud = hmap::random_cloud_density(count, density, seed);
cloud.to_array(raster);
zs.push_back(raster);
std::cout << "cloud_density count: " << cloud.size() << "\n";
// inverse transform sampling (batch)
raster = 0.f;
density,
seed);
cloud_inv.to_array(raster);
zs.push_back(raster);
std::cout << "cloud_inv count: " << cloud_inv.size() << "\n";
// sequential inverse transform sampling with dynamic local updates (e.g.
// repelling radius)
raster = 0.f;
hmap::InverseSampler2D seq_sampler(density, seed);
hmap::Cloud cloud_seq;
int inhibit_r = 4; // grid radius to depress after each point
for (size_t k = 0; k < count; ++k)
{
glm::vec2 p = seq_sampler.sample();
cloud_seq.push_back(hmap::Point(p.x, p.y, 1.f));
// Depress density around the sampled point on the grid
int cx = static_cast<int>(p.x * (shape.x - 1));
int cy = static_cast<int>(p.y * (shape.y - 1));
seq_sampler.update_region(
[cx, cy, inhibit_r](int i, int j, float cur)
{
float d2 = static_cast<float>((i - cx) * (i - cx) +
(j - cy) * (j - cy));
float r2 = static_cast<float>(inhibit_r * inhibit_r);
if (d2 < r2)
{
float factor = d2 / r2;
return cur * factor;
}
return cur;
},
{cx - inhibit_r, cx + inhibit_r},
{cy - inhibit_r, cy + inhibit_r});
}
cloud_seq.to_array(raster);
zs.push_back(raster);
std::cout << "cloud_seq count: " << cloud_seq.size() << "\n";
// filter
cloud = hmap::random_cloud(count,
seed,
hmap::rejection_filter_density(cloud, density, seed);
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
std::cout << "cloud_rejection count: " << cloud.size() << "\n";
hmap::export_banner_png("ex_point_sampling1.png", zs, hmap::Cmap::BONE);
}
// --- distance based
{
zs.clear();
zs.push_back(density);
float min_dist = 0.02f;
float max_dist = 0.08f;
hmap::Cloud cloud = hmap::random_cloud_distance(min_dist, seed);
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
cloud = hmap::random_cloud_distance(min_dist, max_dist, density, seed);
std::cout << "count: " << cloud.size() << "\n";
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
cloud = hmap::random_cloud_distance_power_law(0.01f /* dist_min */,
0.2f /* dist_max */,
1.2f /* alpha */,
seed);
std::cout << "count: " << cloud.size() << "\n";
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
cloud = hmap::random_cloud_distance_weibull(0.01f /* dist_min */,
0.05f /* lambda */,
1.f /* k */,
seed);
std::cout << "count: " << cloud.size() << "\n";
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
hmap::export_banner_png("ex_point_sampling2.png", zs, hmap::Cmap::BONE);
}
// --- grid jittered
{
zs.clear();
glm::vec2 jitter_amount = {0.3f, 0.3f};
glm::vec2 stagger_ratio = {0.5f, 0.f};
jitter_amount,
stagger_ratio,
seed);
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
hmap::export_banner_png("ex_point_sampling3.png", zs, hmap::Cmap::BONE);
}
}

Result

◆ random_cloud_distance() [2/2]

Cloud hmap::random_cloud_distance ( float min_dist,
float max_dist,
const Array & density,
std::uint32_t seed,
const BBox2D & bbox = BBox2D{} )

Generates a random cloud of points separated by a distance range, influenced by a density map.

Points maintain a separation between min_dist and max_dist, and are distributed according to the provided density map.

Parameters
min_distMinimum allowed distance between points.
max_distMaximum allowed distance between points.
density2D array representing spatial density values.
seedRandom number generator seed.
bboxBounding box in which to generate the points (a,b,c,d = xmin, xmax, ymin, ymax). Defaults to the unit square {0.f, 1.f, 0.f, 1.f}.
Returns
A Cloud containing the generated points.

Example

#include <iostream>
#include "highmap.hpp"
int main(void)
{
// for render only
glm::ivec2 shape = {256, 256};
hmap::Array raster(shape);
std::vector<hmap::Array> zs = {};
std::uint32_t seed = 0;
// density field
glm::vec2 kw = {2.f, 2.f};
hmap::Array density = hmap::noise(hmap::NoiseType::PERLIN, shape, kw, seed);
hmap::remap(density); // /!\ NEEDS TO BE IN [0, 1]
hmap::gain(density, 2); // sharper transition
// base param
size_t count = 1000;
// --- random
{
hmap::Cloud cloud = hmap::random_cloud(count, seed, type);
cloud.to_array(raster);
zs.push_back(raster);
}
hmap::export_banner_png("ex_point_sampling0.png", zs, hmap::Cmap::BONE);
// --- density
{
zs.clear();
zs.push_back(density);
raster = 0.f;
// auto xy = hmap::random_points_density(count, density, seed);
// hmap::Cloud cloud(xy[0], xy[1], 1.f /* value */);
// rejection sampling
hmap::Cloud cloud = hmap::random_cloud_density(count, density, seed);
cloud.to_array(raster);
zs.push_back(raster);
std::cout << "cloud_density count: " << cloud.size() << "\n";
// inverse transform sampling (batch)
raster = 0.f;
density,
seed);
cloud_inv.to_array(raster);
zs.push_back(raster);
std::cout << "cloud_inv count: " << cloud_inv.size() << "\n";
// sequential inverse transform sampling with dynamic local updates (e.g.
// repelling radius)
raster = 0.f;
hmap::InverseSampler2D seq_sampler(density, seed);
hmap::Cloud cloud_seq;
int inhibit_r = 4; // grid radius to depress after each point
for (size_t k = 0; k < count; ++k)
{
glm::vec2 p = seq_sampler.sample();
cloud_seq.push_back(hmap::Point(p.x, p.y, 1.f));
// Depress density around the sampled point on the grid
int cx = static_cast<int>(p.x * (shape.x - 1));
int cy = static_cast<int>(p.y * (shape.y - 1));
seq_sampler.update_region(
[cx, cy, inhibit_r](int i, int j, float cur)
{
float d2 = static_cast<float>((i - cx) * (i - cx) +
(j - cy) * (j - cy));
float r2 = static_cast<float>(inhibit_r * inhibit_r);
if (d2 < r2)
{
float factor = d2 / r2;
return cur * factor;
}
return cur;
},
{cx - inhibit_r, cx + inhibit_r},
{cy - inhibit_r, cy + inhibit_r});
}
cloud_seq.to_array(raster);
zs.push_back(raster);
std::cout << "cloud_seq count: " << cloud_seq.size() << "\n";
// filter
cloud = hmap::random_cloud(count,
seed,
hmap::rejection_filter_density(cloud, density, seed);
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
std::cout << "cloud_rejection count: " << cloud.size() << "\n";
hmap::export_banner_png("ex_point_sampling1.png", zs, hmap::Cmap::BONE);
}
// --- distance based
{
zs.clear();
zs.push_back(density);
float min_dist = 0.02f;
float max_dist = 0.08f;
hmap::Cloud cloud = hmap::random_cloud_distance(min_dist, seed);
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
cloud = hmap::random_cloud_distance(min_dist, max_dist, density, seed);
std::cout << "count: " << cloud.size() << "\n";
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
cloud = hmap::random_cloud_distance_power_law(0.01f /* dist_min */,
0.2f /* dist_max */,
1.2f /* alpha */,
seed);
std::cout << "count: " << cloud.size() << "\n";
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
cloud = hmap::random_cloud_distance_weibull(0.01f /* dist_min */,
0.05f /* lambda */,
1.f /* k */,
seed);
std::cout << "count: " << cloud.size() << "\n";
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
hmap::export_banner_png("ex_point_sampling2.png", zs, hmap::Cmap::BONE);
}
// --- grid jittered
{
zs.clear();
glm::vec2 jitter_amount = {0.3f, 0.3f};
glm::vec2 stagger_ratio = {0.5f, 0.f};
jitter_amount,
stagger_ratio,
seed);
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
hmap::export_banner_png("ex_point_sampling3.png", zs, hmap::Cmap::BONE);
}
}

Result

◆ random_cloud_distance_power_law()

Cloud hmap::random_cloud_distance_power_law ( float dist_min,
float dist_max,
float alpha,
std::uint32_t seed,
const BBox2D & bbox = BBox2D{} )

Generates a random cloud of points with distances drawn from a power-law distribution.

Distances between points follow a power-law distribution between dist_min and dist_max, with exponent alpha.

Parameters
dist_minMinimum possible distance between points.
dist_maxMaximum possible distance between points.
alphaPower-law exponent (larger alpha favors shorter distances).
seedRandom number generator seed.
bboxBounding box in which to generate the points (a,b,c,d = xmin, xmax, ymin, ymax). Defaults to the unit square {0.f, 1.f, 0.f, 1.f}.
Returns
A Cloud containing the generated points.

Example

#include <iostream>
#include "highmap.hpp"
int main(void)
{
// for render only
glm::ivec2 shape = {256, 256};
hmap::Array raster(shape);
std::vector<hmap::Array> zs = {};
std::uint32_t seed = 0;
// density field
glm::vec2 kw = {2.f, 2.f};
hmap::Array density = hmap::noise(hmap::NoiseType::PERLIN, shape, kw, seed);
hmap::remap(density); // /!\ NEEDS TO BE IN [0, 1]
hmap::gain(density, 2); // sharper transition
// base param
size_t count = 1000;
// --- random
{
hmap::Cloud cloud = hmap::random_cloud(count, seed, type);
cloud.to_array(raster);
zs.push_back(raster);
}
hmap::export_banner_png("ex_point_sampling0.png", zs, hmap::Cmap::BONE);
// --- density
{
zs.clear();
zs.push_back(density);
raster = 0.f;
// auto xy = hmap::random_points_density(count, density, seed);
// hmap::Cloud cloud(xy[0], xy[1], 1.f /* value */);
// rejection sampling
hmap::Cloud cloud = hmap::random_cloud_density(count, density, seed);
cloud.to_array(raster);
zs.push_back(raster);
std::cout << "cloud_density count: " << cloud.size() << "\n";
// inverse transform sampling (batch)
raster = 0.f;
density,
seed);
cloud_inv.to_array(raster);
zs.push_back(raster);
std::cout << "cloud_inv count: " << cloud_inv.size() << "\n";
// sequential inverse transform sampling with dynamic local updates (e.g.
// repelling radius)
raster = 0.f;
hmap::InverseSampler2D seq_sampler(density, seed);
hmap::Cloud cloud_seq;
int inhibit_r = 4; // grid radius to depress after each point
for (size_t k = 0; k < count; ++k)
{
glm::vec2 p = seq_sampler.sample();
cloud_seq.push_back(hmap::Point(p.x, p.y, 1.f));
// Depress density around the sampled point on the grid
int cx = static_cast<int>(p.x * (shape.x - 1));
int cy = static_cast<int>(p.y * (shape.y - 1));
seq_sampler.update_region(
[cx, cy, inhibit_r](int i, int j, float cur)
{
float d2 = static_cast<float>((i - cx) * (i - cx) +
(j - cy) * (j - cy));
float r2 = static_cast<float>(inhibit_r * inhibit_r);
if (d2 < r2)
{
float factor = d2 / r2;
return cur * factor;
}
return cur;
},
{cx - inhibit_r, cx + inhibit_r},
{cy - inhibit_r, cy + inhibit_r});
}
cloud_seq.to_array(raster);
zs.push_back(raster);
std::cout << "cloud_seq count: " << cloud_seq.size() << "\n";
// filter
cloud = hmap::random_cloud(count,
seed,
hmap::rejection_filter_density(cloud, density, seed);
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
std::cout << "cloud_rejection count: " << cloud.size() << "\n";
hmap::export_banner_png("ex_point_sampling1.png", zs, hmap::Cmap::BONE);
}
// --- distance based
{
zs.clear();
zs.push_back(density);
float min_dist = 0.02f;
float max_dist = 0.08f;
hmap::Cloud cloud = hmap::random_cloud_distance(min_dist, seed);
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
cloud = hmap::random_cloud_distance(min_dist, max_dist, density, seed);
std::cout << "count: " << cloud.size() << "\n";
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
cloud = hmap::random_cloud_distance_power_law(0.01f /* dist_min */,
0.2f /* dist_max */,
1.2f /* alpha */,
seed);
std::cout << "count: " << cloud.size() << "\n";
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
cloud = hmap::random_cloud_distance_weibull(0.01f /* dist_min */,
0.05f /* lambda */,
1.f /* k */,
seed);
std::cout << "count: " << cloud.size() << "\n";
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
hmap::export_banner_png("ex_point_sampling2.png", zs, hmap::Cmap::BONE);
}
// --- grid jittered
{
zs.clear();
glm::vec2 jitter_amount = {0.3f, 0.3f};
glm::vec2 stagger_ratio = {0.5f, 0.f};
jitter_amount,
stagger_ratio,
seed);
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
hmap::export_banner_png("ex_point_sampling3.png", zs, hmap::Cmap::BONE);
}
}

Result

◆ random_cloud_distance_weibull()

Cloud hmap::random_cloud_distance_weibull ( float dist_min,
float lambda,
float k,
std::uint32_t seed,
const BBox2D & bbox = BBox2D{} )

Generates a random cloud of points with distances drawn from a Weibull distribution.

Distances between points follow a Weibull distribution parameterized by lambda (scale) and k (shape).

Parameters
dist_minMinimum possible distance between points.
lambdaWeibull distribution scale parameter.
kWeibull distribution shape parameter.
seedRandom number generator seed.
bboxBounding box in which to generate the points (a,b,c,d = xmin, xmax, ymin, ymax). Defaults to the unit square {0.f, 1.f, 0.f, 1.f}.
Returns
A Cloud containing the generated points.

Example

#include <iostream>
#include "highmap.hpp"
int main(void)
{
// for render only
glm::ivec2 shape = {256, 256};
hmap::Array raster(shape);
std::vector<hmap::Array> zs = {};
std::uint32_t seed = 0;
// density field
glm::vec2 kw = {2.f, 2.f};
hmap::Array density = hmap::noise(hmap::NoiseType::PERLIN, shape, kw, seed);
hmap::remap(density); // /!\ NEEDS TO BE IN [0, 1]
hmap::gain(density, 2); // sharper transition
// base param
size_t count = 1000;
// --- random
{
hmap::Cloud cloud = hmap::random_cloud(count, seed, type);
cloud.to_array(raster);
zs.push_back(raster);
}
hmap::export_banner_png("ex_point_sampling0.png", zs, hmap::Cmap::BONE);
// --- density
{
zs.clear();
zs.push_back(density);
raster = 0.f;
// auto xy = hmap::random_points_density(count, density, seed);
// hmap::Cloud cloud(xy[0], xy[1], 1.f /* value */);
// rejection sampling
hmap::Cloud cloud = hmap::random_cloud_density(count, density, seed);
cloud.to_array(raster);
zs.push_back(raster);
std::cout << "cloud_density count: " << cloud.size() << "\n";
// inverse transform sampling (batch)
raster = 0.f;
density,
seed);
cloud_inv.to_array(raster);
zs.push_back(raster);
std::cout << "cloud_inv count: " << cloud_inv.size() << "\n";
// sequential inverse transform sampling with dynamic local updates (e.g.
// repelling radius)
raster = 0.f;
hmap::InverseSampler2D seq_sampler(density, seed);
hmap::Cloud cloud_seq;
int inhibit_r = 4; // grid radius to depress after each point
for (size_t k = 0; k < count; ++k)
{
glm::vec2 p = seq_sampler.sample();
cloud_seq.push_back(hmap::Point(p.x, p.y, 1.f));
// Depress density around the sampled point on the grid
int cx = static_cast<int>(p.x * (shape.x - 1));
int cy = static_cast<int>(p.y * (shape.y - 1));
seq_sampler.update_region(
[cx, cy, inhibit_r](int i, int j, float cur)
{
float d2 = static_cast<float>((i - cx) * (i - cx) +
(j - cy) * (j - cy));
float r2 = static_cast<float>(inhibit_r * inhibit_r);
if (d2 < r2)
{
float factor = d2 / r2;
return cur * factor;
}
return cur;
},
{cx - inhibit_r, cx + inhibit_r},
{cy - inhibit_r, cy + inhibit_r});
}
cloud_seq.to_array(raster);
zs.push_back(raster);
std::cout << "cloud_seq count: " << cloud_seq.size() << "\n";
// filter
cloud = hmap::random_cloud(count,
seed,
hmap::rejection_filter_density(cloud, density, seed);
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
std::cout << "cloud_rejection count: " << cloud.size() << "\n";
hmap::export_banner_png("ex_point_sampling1.png", zs, hmap::Cmap::BONE);
}
// --- distance based
{
zs.clear();
zs.push_back(density);
float min_dist = 0.02f;
float max_dist = 0.08f;
hmap::Cloud cloud = hmap::random_cloud_distance(min_dist, seed);
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
cloud = hmap::random_cloud_distance(min_dist, max_dist, density, seed);
std::cout << "count: " << cloud.size() << "\n";
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
cloud = hmap::random_cloud_distance_power_law(0.01f /* dist_min */,
0.2f /* dist_max */,
1.2f /* alpha */,
seed);
std::cout << "count: " << cloud.size() << "\n";
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
cloud = hmap::random_cloud_distance_weibull(0.01f /* dist_min */,
0.05f /* lambda */,
1.f /* k */,
seed);
std::cout << "count: " << cloud.size() << "\n";
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
hmap::export_banner_png("ex_point_sampling2.png", zs, hmap::Cmap::BONE);
}
// --- grid jittered
{
zs.clear();
glm::vec2 jitter_amount = {0.3f, 0.3f};
glm::vec2 stagger_ratio = {0.5f, 0.f};
jitter_amount,
stagger_ratio,
seed);
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
hmap::export_banner_png("ex_point_sampling3.png", zs, hmap::Cmap::BONE);
}
}

Result

◆ random_cloud_jittered()

Cloud hmap::random_cloud_jittered ( size_t count,
const glm::vec2 & jitter_amount,
const glm::vec2 & stagger_ratio,
std::uint32_t seed,
const BBox2D & bbox = BBox2D{} )

Generates a jittered grid cloud of points.

Points are placed on a grid and then offset by a jitter amount, optionally staggered for a more irregular pattern.

Parameters
countNumber of points to generate.
jitter_amountMaximum jitter to apply in each axis (x, y).
stagger_ratioRatio of staggering between consecutive rows or columns.
seedRandom number generator seed.
bboxBounding box in which to generate the points (a,b,c,d = xmin, xmax, ymin, ymax). Defaults to the unit square {0.f, 1.f, 0.f, 1.f}.
Returns
A Cloud containing the generated points.

Example

#include <iostream>
#include "highmap.hpp"
int main(void)
{
// for render only
glm::ivec2 shape = {256, 256};
hmap::Array raster(shape);
std::vector<hmap::Array> zs = {};
std::uint32_t seed = 0;
// density field
glm::vec2 kw = {2.f, 2.f};
hmap::Array density = hmap::noise(hmap::NoiseType::PERLIN, shape, kw, seed);
hmap::remap(density); // /!\ NEEDS TO BE IN [0, 1]
hmap::gain(density, 2); // sharper transition
// base param
size_t count = 1000;
// --- random
{
hmap::Cloud cloud = hmap::random_cloud(count, seed, type);
cloud.to_array(raster);
zs.push_back(raster);
}
hmap::export_banner_png("ex_point_sampling0.png", zs, hmap::Cmap::BONE);
// --- density
{
zs.clear();
zs.push_back(density);
raster = 0.f;
// auto xy = hmap::random_points_density(count, density, seed);
// hmap::Cloud cloud(xy[0], xy[1], 1.f /* value */);
// rejection sampling
hmap::Cloud cloud = hmap::random_cloud_density(count, density, seed);
cloud.to_array(raster);
zs.push_back(raster);
std::cout << "cloud_density count: " << cloud.size() << "\n";
// inverse transform sampling (batch)
raster = 0.f;
density,
seed);
cloud_inv.to_array(raster);
zs.push_back(raster);
std::cout << "cloud_inv count: " << cloud_inv.size() << "\n";
// sequential inverse transform sampling with dynamic local updates (e.g.
// repelling radius)
raster = 0.f;
hmap::InverseSampler2D seq_sampler(density, seed);
hmap::Cloud cloud_seq;
int inhibit_r = 4; // grid radius to depress after each point
for (size_t k = 0; k < count; ++k)
{
glm::vec2 p = seq_sampler.sample();
cloud_seq.push_back(hmap::Point(p.x, p.y, 1.f));
// Depress density around the sampled point on the grid
int cx = static_cast<int>(p.x * (shape.x - 1));
int cy = static_cast<int>(p.y * (shape.y - 1));
seq_sampler.update_region(
[cx, cy, inhibit_r](int i, int j, float cur)
{
float d2 = static_cast<float>((i - cx) * (i - cx) +
(j - cy) * (j - cy));
float r2 = static_cast<float>(inhibit_r * inhibit_r);
if (d2 < r2)
{
float factor = d2 / r2;
return cur * factor;
}
return cur;
},
{cx - inhibit_r, cx + inhibit_r},
{cy - inhibit_r, cy + inhibit_r});
}
cloud_seq.to_array(raster);
zs.push_back(raster);
std::cout << "cloud_seq count: " << cloud_seq.size() << "\n";
// filter
cloud = hmap::random_cloud(count,
seed,
hmap::rejection_filter_density(cloud, density, seed);
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
std::cout << "cloud_rejection count: " << cloud.size() << "\n";
hmap::export_banner_png("ex_point_sampling1.png", zs, hmap::Cmap::BONE);
}
// --- distance based
{
zs.clear();
zs.push_back(density);
float min_dist = 0.02f;
float max_dist = 0.08f;
hmap::Cloud cloud = hmap::random_cloud_distance(min_dist, seed);
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
cloud = hmap::random_cloud_distance(min_dist, max_dist, density, seed);
std::cout << "count: " << cloud.size() << "\n";
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
cloud = hmap::random_cloud_distance_power_law(0.01f /* dist_min */,
0.2f /* dist_max */,
1.2f /* alpha */,
seed);
std::cout << "count: " << cloud.size() << "\n";
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
cloud = hmap::random_cloud_distance_weibull(0.01f /* dist_min */,
0.05f /* lambda */,
1.f /* k */,
seed);
std::cout << "count: " << cloud.size() << "\n";
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
hmap::export_banner_png("ex_point_sampling2.png", zs, hmap::Cmap::BONE);
}
// --- grid jittered
{
zs.clear();
glm::vec2 jitter_amount = {0.3f, 0.3f};
glm::vec2 stagger_ratio = {0.5f, 0.f};
jitter_amount,
stagger_ratio,
seed);
raster = 0.f;
cloud.to_array(raster);
zs.push_back(raster);
hmap::export_banner_png("ex_point_sampling3.png", zs, hmap::Cmap::BONE);
}
}

Result

◆ rejection_filter_density()

void hmap::rejection_filter_density ( Cloud & cloud,
const Array & density_mask,
std::uint32_t seed,
const BBox2D & bbox = BBox2D{} )

Filter a point cloud using rejection sampling based on a density mask.

Each point in the input cloud is retained or discarded according to a spatially varying probability derived from the provided 2D density mask. The mask is mapped to the bounding box and evaluated as a continuous function over the domain.

Parameters
density_mask2D array defining the spatial density field over the bounding box. Values should lie in \([0,1]\).
seedRandom seed used for reproducible rejection sampling.
bboxBounding box (xmin, ymin, xmax, ymax) defining the spatial extent of the density mask in world coordinates.

◆ scale() [1/6]

Cloud hmap::scale ( const Cloud & cloud,
glm::vec2 scale,
glm::vec2 center = {0.5f, 0.5f} )

Scales the point coordinates in a cloud relative to a center point.

Scales the (x, y) coordinates of all points in the cloud relative to a specified center point while preserving each point's value (v). A scale factor smaller than 1 shrinks the point distribution toward the center (creating a margin from domain boundaries), while a scale factor greater than 1 expands it.

Parameters
cloudInput point cloud.
scaleScale factor(s) for x and y axes.
centerCenter of scaling (defaults to (0.5, 0.5)).
Returns
Cloud A new point cloud with scaled point coordinates.

◆ scale() [2/6]

Cloud hmap::scale ( const Cloud & cloud,
float scale,
glm::vec2 center = {0.5f, 0.5f} )

◆ convert_length_to_pixel()

int hmap::convert_length_to_pixel ( float x,
int nx,
bool lim_inf = true,
bool lim_sup = false,
float scale = 1.f )

Converts a length value to a pixel index in a discretized space.

This function maps a floating-point length x to an integer pixel index, considering the total number of pixels nx and a scaling factor scale. Optionally, it can enforce lower and upper limits on the output index.

Parameters
xThe length value to be converted.
nxThe number of pixels in the discretized space.
lim_infIf nonzero, enforces a minimum index of 1.
lim_supIf nonzero, enforces a maximum index of nx - 1.
scaleThe scaling factor relating the length to the pixel space.
Returns
The computed pixel index.

◆ grid_xy_vector()

void hmap::grid_xy_vector ( std::vector< float > & x,
std::vector< float > & y,
glm::ivec2 shape,
const UvRect & uv_rect = UvRect::unit(),
bool endpoint = false )

Return x and y coordinates of a regular grid, as two 1D vectors.

Parameters
x[out]Vector x.
y[out]Vector y.
shapeShape.
bboxBounding box.
endpointInclude or not the endpoint.

◆ rescale_grid_from_unit_square_to_bbox()

void hmap::rescale_grid_from_unit_square_to_bbox ( std::vector< float > & x,
std::vector< float > & y,
const UvRect & uv_rect )

Rescale 1D grid vectors from unit square [0, 1] to target UV rectangle.

Parameters
x[in,out]Vector x.
y[in,out]Vector y.
uv_rectTarget UV rectangle.

◆ bezier()

Path hmap::bezier ( const Path & path,
float curvature_ratio = 0.3f,
int edge_divisions = 10,
Path::EdgeDivisionMode edm = Path::EdgeDivisionMode::EDM_PER_EDGE )

Smooth the path using Bezier curves.

This method applies Bezier curve smoothing to the path. The curvature_ratio controls the amount of curvature applied, with typical values in the range of [-1, 1], where positive values generally result in more pronounced curvature. The edge_divisions parameter determines the number of subdivisions per edge to create a smoother curve.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
std::uint32_t seed = 1;
hmap::BBox2D bbox = {0.f, 1.f, 0.f, 1.f};
hmap::Path path = hmap::Path(5, seed, hmap::BBox2D(0.1f, 0.9f, 0.1f, 0.9f));
path.reorder_nns();
// --- Open path
path.set_closed(false);
auto z_sdf_open = hmap::path_sdf_to_array(path, shape, bbox);
auto z_bezier_open = hmap::sdf_2d_polyline_bezier(path,
shape,
// --- Closed path
path.set_closed(true);
auto z_sdf_closed = hmap::path_sdf_to_array(path, shape, bbox);
auto z_bezier_closed = hmap::sdf_2d_polyline_bezier(path,
shape,
"ex_path_bezier.png",
{z_sdf_open, z_bezier_open, z_sdf_closed, z_bezier_closed},
}
Array sdf_2d_polyline_bezier(const Path &path, glm::ivec2 shape, const UvRect &uv_rect=UvRect::unit(), const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, bool use_bvh=true)
See hmap::sdf_2d_polyline, with a Bezier approximation of the path.
Definition sdf_2d_polyline_bezier.cpp:367
Array path_sdf_to_array(const Path &path, glm::ivec2 shape, const BBox2D &bbox_array=BBox2D::unit(), const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, bool use_bvh=true)
Compute a distance field from a point path.
Definition path_functions.cpp:462
static constexpr UvRect unit()
Definition uv_rect.hpp:46

Result

Parameters
curvature_ratioAmount of curvature, usually in the range [-1, 1], with positive values resulting in more curvature.
edge_divisionsNumber of subdivisions per edge to achieve smooth curves.
edmThe mode for dividing edges. Default is Path::EdgeDivisionMode::EDM_PER_EDGE.

See unit tests: test_splines.cpp

◆ bezier_round()

Path hmap::bezier_round ( const Path & path,
float curvature_ratio = 0.3f,
int edge_divisions = 10,
Path::EdgeDivisionMode edm = Path::EdgeDivisionMode::EDM_PER_EDGE )

Smooth the path using Bezier curves (alternative method).

This alternative method applies Bezier curve smoothing to the path. The curvature_ratio parameter affects the curvature amount, similar to the bezier method. The edge_divisions parameter specifies how finely each edge is divided to create a smoother curve.

Example

#include "highmap.hpp"
int main(void)
{
hmap::Path path;
path.push_back({10.f, 10.f});
path.push_back({50.f, 100.f});
path.push_back({200.f, 50.f});
path.push_back({240.f, 240.f});
hmap::Path bpath = hmap::bezier_round(path, 0.3f, 10);
hmap::Array z({256, 256}, 0.f);
bpath.to_array(z);
z.to_png("ex_path_bezier_round.png", hmap::Cmap::VIRIDIS);
}
Path bezier_round(const Path &path, float curvature_ratio=0.3f, int edge_divisions=10, Path::EdgeDivisionMode edm=Path::EdgeDivisionMode::EDM_PER_EDGE)
Smooth the path using Bezier curves (alternative method).
Definition path_functions.cpp:95

Result

Parameters
curvature_ratioAmount of curvature, typically within [-1, 1], with positive values for increased curvature.
edge_divisionsNumber of edge subdivisions for smoothness.
edmThe mode for dividing edges. Default is Path::EdgeDivisionMode::EDM_PER_EDGE.

See unit tests: test_splines.cpp

◆ bspline()

Path hmap::bspline ( const Path & path,
int edge_divisions = 10,
Path::EdgeDivisionMode edm = Path::EdgeDivisionMode::EDM_PER_EDGE )

Smooth the path using B-Spline curves.

This method smooths the path using B-Spline curves, which provide a smooth curve that passes through the control points. The edge_divisions parameter defines the number of subdivisions per edge for achieving smooth curves.

Important: This function does not correctly handle closed polylines (circular contours). If the path is closed, the smoothing may not correctly close the loop, potentially leaving a gap between the start and end points.

Example

#include "highmap.hpp"
int main(void)
{
hmap::Path path;
path.push_back({10.f, 10.f});
path.push_back({50.f, 100.f});
path.push_back({200.f, 50.f});
path.push_back({240.f, 240.f});
hmap::Path bpath = hmap::bspline(path, 10);
hmap::Array z({256, 256}, 0.f);
bpath.to_array(z);
z.to_png("ex_path_bspline.png", hmap::Cmap::VIRIDIS);
}

Result

Parameters
edge_divisionsNumber of subdivisions per edge to achieve a smooth B-Spline curve.
Warning
This function does not correctly handle closed polylines.
Parameters
edmMode for dividing edges. Default is EDM_PER_EDGE.

See unit tests: test_splines.cpp

◆ catmullrom()

Path hmap::catmullrom ( const Path & path,
int edge_divisions = 10,
Path::EdgeDivisionMode edm = Path::EdgeDivisionMode::EDM_PER_EDGE )

Smooth the path using Catmull-Rom curves.

This method applies Catmull-Rom curve smoothing to the path. Catmull-Rom splines are interpolating splines that pass through each control point. The edge_divisions parameter determines the number of subdivisions per edge for smoothing.

Parameters
edge_divisionsNumber of edge subdivisions to create a smooth Catmull-Rom curve.
edmMode for dividing edges. Default is EDM_PER_EDGE.

Example

#include "highmap.hpp"
int main(void)
{
hmap::Path path;
path.push_back({10.f, 10.f});
path.push_back({50.f, 100.f});
path.push_back({200.f, 50.f});
path.push_back({240.f, 240.f});
hmap::Path bpath = hmap::catmullrom(path, 10);
hmap::Array z({256, 256}, 0.f);
bpath.to_array(z);
z.to_png("ex_path_catmullrom.png", hmap::Cmap::VIRIDIS);
}

Result

See unit tests: test_splines.cpp

◆ decasteljau()

Path hmap::decasteljau ( const Path & path,
int edge_divisions = 10,
Path::EdgeDivisionMode edm = Path::EdgeDivisionMode::EDM_PER_EDGE )

Smooth the path using De Casteljau curves.

This function smooths a path by applying De Casteljau's algorithm to generate intermediate points along the path, effectively creating a Bézier curve that approximates the original path. The path is divided into segments, and the De Casteljau algorithm is applied to each segment, resulting in a smooth curve.

The parameter edge_divisions controls the number of divisions (sub-segments) created along each segment of the path. A higher number of divisions will result in a smoother curve, but will also increase the computational cost.

Parameters
edge_divisionsThe number of divisions for each edge of the path. Default is 10, which provides a balanced level of smoothing.
edmMode for dividing edges (default is EDM_PER_EDGE).

Example

#include "highmap.hpp"
int main(void)
{
hmap::Path path;
path.push_back({10.f, 10.f});
path.push_back({50.f, 100.f});
path.push_back({200.f, 50.f});
path.push_back({240.f, 240.f});
hmap::Path bpath = hmap::decasteljau(path, 10);
hmap::Array z({256, 256}, 0.f);
bpath.to_array(z);
z.to_png("ex_path_decasteljau.png", hmap::Cmap::VIRIDIS);
}
Path decasteljau(const Path &path, int edge_divisions=10, Path::EdgeDivisionMode edm=Path::EdgeDivisionMode::EDM_PER_EDGE)
Smooth the path using De Casteljau curves.
Definition path_functions.cpp:184

Result

See unit tests: test_splines.cpp

◆ decimate_vw()

Path hmap::decimate_vw ( const Path & path,
int n_points_target = 3 )

Simplifies the current path using the Visvalingam-Whyatt algorithm.

This method reduces the number of points in the path to the specified target, n_points_target, while preserving the overall shape. It calculates the area of triangles formed by consecutive points and removes points corresponding to the smallest areas iteratively.

Parameters
pathThe input path to be decimated.
n_points_targetThe desired number of points to retain in the path. If the current number of points is less than n_points_target or the path contains fewer than 3 points, the method returns without modifying the path.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
int seed = 3;
int npoints = 30;
hmap::BBox2D bbox = {0.f, 1.f, 0.f, 1.f};
hmap::Path path = hmap::Path(npoints,
seed,
hmap::BBox2D(0.1f, 0.9f, 0.1f, 0.9f));
path.reorder_nns();
path = hmap::fractalize(path, 1, seed);
int ntarget = 15;
auto z1 = hmap::Array(shape);
path.to_array(z1, bbox);
// Visvalingam-Whyatt algo
auto path2 = hmap::decimate_vw(path, ntarget);
auto z2 = path2.to_array(shape, bbox);
path.set_closed(true);
auto path3 = hmap::decimate_vw(path, ntarget);
auto z3 = path3.to_array(shape, bbox);
hmap::export_banner_png("ex_path_decimate.png",
{z1, z2, z3},
}
bool assert_start_end_points(const Path &path1, const Path &path2, float tol=1e-6f, bool verbose=false)
Asserts that the start and end points of two paths are within a specified tolerance.
Definition path_verification.cpp:17
Path fractalize(const Path &path, int iterations, std::uint32_t seed, float sigma=0.2f, int orientation=0, float persistence=1.f, Array *p_control_field=nullptr, const BBox2D &bbox=BBox2D{}, bool bounded=false)
Applies fractalization to the path by adding points and randomly displacing their positions.
Definition path_functions.cpp:235

Result

See unit tests: test_decimate_vw.cpp

◆ fractalize()

Path hmap::fractalize ( const Path & path,
int iterations,
std::uint32_t seed,
float sigma = 0.2f,
int orientation = 0,
float persistence = 1.f,
Array * p_control_field = nullptr,
const BBox2D & bbox = BBox2D{},
bool bounded = false )

Applies fractalization to the path by adding points and randomly displacing their positions.

This method enhances the complexity of a path by iteratively adding new points between existing ones and displacing them using Gaussian noise. The process can simulate natural phenomena like terrain generation or random walk paths. The number of iterations determines the level of detail added to the path.

Parameters
pathThe input path to be fractalized.
iterationsNumber of iterations to apply the fractalization process.
seedSeed value for random number generation, ensuring reproducibility.
sigmaStandard deviation of the Gaussian displacement, relative to the distance between points.
orientationDetermines the displacement direction: 0 for random, 1 for inflation, -1 for deflation.
persistenceFactor that adjusts the noise intensity across iterations.
control_fieldOptional pointer to an array that locally modifies the displacement amplitude.
bboxBounding box that defines the valid area for the control field's influence.
boundedIf true, clamps each newly displaced midpoint to the bounding box defined by the initial edge it belongs to. Defaults to false.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
int seed = 2;
hmap::BBox2D bbox = {-1.f, 2.f, 0.f, 5.f};
// --- generate a path using a random set of points
int npoints = 8;
hmap::Path path = hmap::Path(npoints, seed, bbox);
path.reorder_nns(); // reorder points to get a better look
hmap::Array z1 = path.to_array(shape, bbox);
// --- control function (supposed to be in [0, 1])
hmap::Array z_control = hmap::slope(shape, 0.f, -1.f);
hmap::remap(z_control);
int iterations = 6;
float sigma = 0.3f;
path.resample_uniform(); // to ensure a "uniform" output
// --- fractalize, standard, bounded, and with control function
int orientation = 0;
float persistence = 1.f;
// 1. Standard unbounded fractalize
hmap::Path pn = path;
pn = hmap::fractalize(pn, iterations, seed, sigma);
hmap::Array z3 = hmap::Array(shape);
pn.to_array(z3, bbox);
// 2. Bounded fractalize
hmap::Path pb = path;
iterations,
seed,
2.f * sigma, // push amplitude
orientation,
persistence,
nullptr,
bbox,
true);
hmap::Array z5 = hmap::Array(shape);
pb.to_array(z5, bbox);
// 3. Control function modulated fractalize (closed path)
hmap::Path pc = path;
pc.set_closed(true);
iterations,
seed,
sigma,
orientation,
persistence,
&z_control,
bbox);
hmap::Array z4 = pc.to_array(shape, bbox);
hmap::export_banner_png("ex_path_fractalize.png",
{z1, z3, z5, z_control, z4},
}
void resample_uniform(InterpolationMethod1D itp_method=InterpolationMethod1D::LINEAR)
Resample the path to achieve fairly uniform distance between consecutive points.
Definition path.cpp:447

Result

◆ inflate()

Path hmap::inflate ( const Path & path,
float strength,
bool resample = true )

Inflate (offset) a path along its normals using curvature.

Each point is displaced along its normal direction by an amount proportional to local curvature and the given radius.

Parameters
pathInput path
radiusInflation radius (scales displacement)
resampleIf true, resample output to preserve spatial resolution
Returns
Inflated path

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
int seed = 6;
int npoints = 10;
hmap::BBox2D bbox = {0.f, 1.f, 0.f, 1.f};
hmap::Path path = hmap::Path(npoints,
seed,
hmap::BBox2D(0.1f, 0.9f, 0.1f, 0.9f));
path.reorder_nns();
path = hmap::fractalize(path, 2, seed, 0.2f);
path.resample_interp(200);
auto z1 = path.to_array(shape, bbox);
// --- open
hmap::Array z2(shape);
for (const auto &radius : {0.f, 0.1f, 0.2f, 0.3f})
{
hmap::Path p = hmap::inflate(path, radius);
p.set_values(radius + 0.7f);
p.to_array(z2, bbox);
}
// --- closed
path.set_closed(true);
hmap::Array z3(shape);
for (const auto &radius : {0.f, 0.1f, 0.2f, 0.3f})
{
hmap::Path p = hmap::inflate(path, radius);
p.set_values(radius + 0.7f);
p.to_array(z3, bbox);
}
hmap::export_banner_png("ex_path_inflate.png",
{z1, z2, z3},
}
void resample_interp(int npoints, InterpolationMethod1D itp_method=InterpolationMethod1D::CUBIC)
Resamples the path using cubic interpolation along arc length.
Definition path.cpp:408
Path inflate(const Path &path, float strength, bool resample=true)
Inflate (offset) a path along its normals using curvature.
Definition path_functions.cpp:326

Result

◆ meanderize()

Path hmap::meanderize ( const Path & path,
float ratio,
float noise_ratio = 0.1f,
std::uint32_t seed = 1,
int iterations = 1,
int edge_divisions = 10,
Path::EdgeDivisionMode edm = Path::EdgeDivisionMode::EDM_PER_EDGE )

Add "meanders" to the path.

This method introduces meandering effects to the path by adding random deviations. The amplitude of the meanders is controlled by the ratio parameter, while the noise_ratio controls the amount of randomness. The seed parameter is used to initialize the random number generator, ensuring reproducibility. The iterations parameter defines how many times the meandering process is applied, and edge_divisions controls how finely each edge is subdivided during the meandering.

Parameters
pathThe input path to be meanderized.
ratioAmplitude ratio of the meanders. Typically a positive value.
noise_ratioRatio of randomness introduced during meandering. Default is 0.1.
seedSeed for random number generation. Default is 1.
iterationsNumber of iterations to apply meandering. Default is 1.
edge_divisionsNumber of sub-divisions of each edge. Default is 10.
edmThe mode for dividing edges during the meandering process. Default is EDM_PER_EDGE.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
int seed = 6;
int npoints = 10;
hmap::BBox2D bbox = {0.f, 1.f, 0.f, 1.f};
hmap::Path path = hmap::Path(npoints,
seed,
hmap::BBox2D(0.1f, 0.9f, 0.1f, 0.9f));
path.reorder_nns();
auto z1 = path.to_array(shape, bbox);
hmap::Path path_c;
//
float ratio = 0.2f;
path_c = hmap::meanderize(path, ratio);
auto z2 = path_c.to_array(shape, bbox);
//
ratio = 0.3f;
float noise_ratio = 0.1f;
int iterations = 3;
path.set_closed(true);
path_c = hmap::meanderize(path, ratio, noise_ratio, seed, iterations);
auto z3 = path_c.to_array(shape, bbox);
hmap::export_banner_png("ex_path_meanderize.png",
{z1, z2, z3},
}
Path meanderize(const Path &path, float ratio, float noise_ratio=0.1f, std::uint32_t seed=1, int iterations=1, int edge_divisions=10, Path::EdgeDivisionMode edm=Path::EdgeDivisionMode::EDM_PER_EDGE)
Add "meanders" to the path.
Definition path_functions.cpp:356

Result

◆ path_sdf_bezier_to_array()

Array hmap::path_sdf_bezier_to_array ( const Path & path,
glm::ivec2 shape,
const BBox2D & bbox_array = BBox2D::unit(),
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
bool use_bvh = true )

Converts a 2D path treated as a piecewise quadratic Bezier curve to a signed distance field (SDF) array.

For each grid cell, computes the distance to the nearest point on the Bezier curves formed by consecutive point triplets, optionally applying domain warping using noise fields.

Parameters
pathInput point path.
shapeOutput array dimensions.
bbox_arrayBounding box of the output domain.
p_noise_xOptional x-direction noise (domain warp).
p_noise_yOptional y-direction noise (domain warp).
use_bvhWhether to use BVH acceleration (default: true).
Returns
Array of signed distances to the Bezier curve.

◆ path_sdf_bezier_to_array_brute_force()

Array hmap::path_sdf_bezier_to_array_brute_force ( const Path & path,
glm::ivec2 shape,
const BBox2D & bbox_array = BBox2D::unit(),
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr )

◆ path_sdf_bezier_to_array_bvh()

Array hmap::path_sdf_bezier_to_array_bvh ( const Path & path,
glm::ivec2 shape,
const BBox2D & bbox_array = BBox2D::unit(),
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr )

◆ path_sdf_to_array()

Array hmap::path_sdf_to_array ( const Path & path,
glm::ivec2 shape,
const BBox2D & bbox_array = BBox2D::unit(),
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
bool use_bvh = true )

Compute a distance field from a point path.

For each grid cell, computes the distance to the nearest point in the path, optionally applying domain warping using noise fields.

Parameters
pathInput point path.
shapeOutput array dimensions.
bbox_arrayBounding box of the output domain.
p_noise_xOptional x-direction noise (domain warp).
p_noise_yOptional y-direction noise (domain warp).
use_bvhWhether to use BVH acceleration (default: true).
Returns
Array of distances to the nearest point.

◆ path_sdf_to_array_brute_force()

Array hmap::path_sdf_to_array_brute_force ( const Path & path,
glm::ivec2 shape,
const BBox2D & bbox_array = BBox2D::unit(),
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr )

◆ path_sdf_to_array_bvh()

Array hmap::path_sdf_to_array_bvh ( const Path & path,
glm::ivec2 shape,
const BBox2D & bbox_array = BBox2D::unit(),
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr )

◆ remove_geometric_loops()

Path hmap::remove_geometric_loops ( const Path & path)

Removes geometric loops in a 2D path caused by self-intersections.

This function iteratively detects self-intersections in the path and removes the segments forming loops, optionally inserting the exact intersection points.

Parameters
pathThe input path as a vector of 2D points.
Returns
Path The simplified path with self-intersecting loops removed.

Example

#include "highmap.hpp"
int main(void)
{
hmap::Path path;
path.push_back({10.f, 10.f});
path.push_back({100.f, 10.f});
path.push_back({100.f, 100.f});
path.push_back({10.f, 100.f});
path.push_back({10.f, 10.f}); // loop
return 0;
}
Path remove_geometric_loops(const Path &path)
Removes geometric loops in a 2D path caused by self-intersections.
Definition path_functions.cpp:681

Result

◆ scale() [3/6]

Path hmap::scale ( const Path & path,
glm::vec2 scale,
glm::vec2 center = {0.5f, 0.5f} )

Scales the point coordinates in a path relative to a center point.

Scales the (x, y) coordinates of all points in the path relative to a specified center point while preserving each point's value (v) and the open/closed state of the path. A scale factor smaller than 1 shrinks the point distribution toward the center (creating a margin from domain boundaries), while a scale factor greater than 1 expands it.

Parameters
pathInput path.
scaleScale factor(s) for x and y axes.
centerCenter of scaling (defaults to (0.5, 0.5)).
Returns
Path A new path with scaled point coordinates.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
int seed = 6;
int npoints = 10;
hmap::BBox2D bbox = {0.f, 1.f, 0.f, 1.f};
hmap::Path path = hmap::Path(npoints,
seed,
hmap::BBox2D(0.05f, 0.95f, 0.05f, 0.95f));
path.reorder_nns();
path.set_closed(true);
path = hmap::fractalize(path, 2, seed, 0.2f);
path.resample_interp(200);
auto z1 = path.to_array(shape, bbox);
// --- Concentric uniform scale (shrinking creates margin from boundary)
hmap::Array z2(shape);
for (float s : {1.0f, 0.75f, 0.5f, 0.25f})
{
hmap::Path p = hmap::scale(path, s);
p.to_array(z2, bbox);
}
// --- Non-uniform scale (independent X and Y scaling)
hmap::Array z3(shape);
for (float s : {1.0f, 0.75f, 0.5f, 0.25f})
{
hmap::Path p = hmap::scale(path, glm::vec2(s, s * 0.5f));
p.to_array(z3, bbox);
}
hmap::export_banner_png("ex_path_scale.png",
{z1, z2, z3},
return 0;
}

Result

◆ scale() [4/6]

Path hmap::scale ( const Path & path,
float scale,
glm::vec2 center = {0.5f, 0.5f} )

◆ smooth()

Path hmap::smooth ( const Path & path,
int navg = 1,
float averaging_intensity = 1.f,
float inertia = 0.f )

Applies a smoothing operation to the path points using a moving average filter.

This method smooths the path points based on a specified number of neighboring points, an averaging intensity, and an inertia factor. The smoothing involves calculating the average of neighboring points within a range defined by navg, and then applying an intensity-based weighted average to blend the original and smoothed values. Additionally, an inertia effect can be applied to gradually adjust point positions based on previous points.

Parameters
pathThe input path to be smoothed.
navgNumber of neighboring points to consider on each side of the current point during the smoothing process. Higher values result in broader smoothing.
averaging_intensityThe weight given to the averaged points. A value of 1.0 applies full intensity, resulting in a complete averaging of the neighboring points. Lower values retain more of the original point's position.
inertiaThe factor by which each point is influenced by its previous point after the initial smoothing pass. A value of 0 has no inertia effect, while a higher value blends the current point's position with that of the preceding point, creating a trailing effect.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
int seed = 6;
int npoints = 10;
hmap::BBox2D bbox = {0.f, 1.f, 0.f, 1.f};
hmap::Path path = hmap::Path(npoints,
seed,
hmap::BBox2D(0.1f, 0.9f, 0.1f, 0.9f));
path.reorder_nns();
path = hmap::fractalize(path, 4, seed, 0.2f);
path.resample_by_spacing(0.05f);
auto z1 = path.to_array(shape, bbox);
int navg = 12;
hmap::Path path_c = hmap::smooth(path, navg);
auto z2 = path_c.to_array(shape, bbox);
path.set_closed(true);
path_c = hmap::smooth(path, navg);
auto z3 = path_c.to_array(shape, bbox);
hmap::export_banner_png("ex_path_smooth.png",
{z1, z2, z3},
}
void resample_by_spacing(float delta, InterpolationMethod1D itp_method=InterpolationMethod1D::LINEAR)
Resample the path to achieve an approximately constant distance between points.
Definition path.cpp:398
Path smooth(const Path &path, int navg=1, float averaging_intensity=1.f, float inertia=0.f)
Applies a smoothing operation to the path points using a moving average filter.
Definition path_functions.cpp:732

Result

◆ squiggle()

Path hmap::squiggle ( const Path & path,
int iterations = 4,
std::uint32_t seed = 0,
float height_ratio = 0.5f,
int orientation = 0,
const Array * p_weights = nullptr,
const Array * p_mask = nullptr,
const BBox2D & bbox = BBox2D{} )

Generates a continuous, non-self-intersecting squiggle curve by applying the squiggle recursive triangle subdivision algorithm to each edge of the input path.

Implements the squiggle curve construction from Prusinkiewicz et al., "Generating Mountainous Terrain". Constrained within domain triangles for each edge, ensuring continuity and absence of self-intersections.

Parameters
pathThe input path to apply the squiggle algorithm to.
iterationsNumber of recursive subdivision levels per edge (e.g., 2 to 6).
seedRandom seed number for deterministic edge selection.
height_ratioHeight of the bounding triangle relative to edge length (default 0.5).
orientationDisplacement direction: 0 to alternate sides, 1 for positive normal, -1 for negative normal.
p_weightsOptional pointer to an Array defining spatial weights to bias path progression.
p_maskOptional pointer to a binary/mask Array (1 = allowed, 0 = forbidden) preventing the path from entering forbidden areas.
bboxBounding box for spatial sampling.
Returns
Generated continuous Path.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
hmap::BBox2D bbox = {0.f, 1.f, 0.f, 1.f};
std::uint32_t seed = 42;
// 1. Initial base path (open polyline traversing domain)
hmap::Path base_path({hmap::Point(0.1f, 0.3f, 0.2f),
hmap::Point(0.4f, 0.55f, 0.5f),
hmap::Point(0.65f, 0.45f, 0.8f),
hmap::Point(0.9f, 0.8f, 1.0f)});
hmap::Array z_base = base_path.to_array(shape, bbox);
// 2. Standard procedural squiggle path (alternating orientation)
hmap::Path p_squiggle =
hmap::squiggle(base_path, 4, seed, 0.45f, 0, nullptr, nullptr, bbox);
hmap::Array z_squiggle = p_squiggle.to_array(shape, bbox);
// 3. Squiggle with spatial weighting (attracted towards top half)
hmap::Array weights(shape, 1.f);
for (int j = 0; j < shape.y; ++j)
for (int i = 0; i < shape.x; ++i)
{
float y_norm = (float)j / (float)shape.y;
weights(i, j) = std::exp(4.f * y_norm);
}
hmap::Path p_weighted =
hmap::squiggle(base_path, 4, seed, 0.45f, 0, &weights, nullptr, bbox);
hmap::Array z_weighted = p_weighted.to_array(shape, bbox);
// 4. Squiggle with branching tributaries
std::vector<hmap::Path> branched_paths = hmap::squiggle_branches(base_path,
4,
seed,
0.9f,
6,
0.4f,
0,
nullptr,
nullptr,
bbox);
hmap::Array z_branches(shape, 0.f);
for (const auto &p : branched_paths)
{
hmap::Array z_p = p.to_array(shape, bbox);
z_branches = hmap::maximum(z_branches, z_p);
}
// Export visual comparison banner
hmap::export_banner_png("ex_path_squiggle.png",
{z_base, z_squiggle, z_weighted, z_branches},
return 0;
}
Path squiggle(const Path &path, int iterations=4, std::uint32_t seed=0, float height_ratio=0.5f, int orientation=0, const Array *p_weights=nullptr, const Array *p_mask=nullptr, const BBox2D &bbox=BBox2D{})
Generates a continuous, non-self-intersecting squiggle curve by applying the squiggle recursive trian...
Definition path_squiggle.cpp:182
std::vector< Path > squiggle_branches(const Path &path, int iterations=4, std::uint32_t seed=0, float branch_probability=0.3f, int max_branches=8, float height_ratio=0.5f, int orientation=0, const Array *p_weights=nullptr, const Array *p_mask=nullptr, const BBox2D &bbox=BBox2D{})
Generates squiggle paths with secondary tributary branches along each edge.
Definition path_squiggle.cpp:296
Array maximum(const Array &array1, const Array &array2)
Return the element-wise maximum of two arrays.
Definition range.cpp:297

Result

Reference: Prusinkiewicz et al., Generating Mountainous Terrain (1993).

◆ squiggle_branches()

std::vector< Path > hmap::squiggle_branches ( const Path & path,
int iterations = 4,
std::uint32_t seed = 0,
float branch_probability = 0.3f,
int max_branches = 8,
float height_ratio = 0.5f,
int orientation = 0,
const Array * p_weights = nullptr,
const Array * p_mask = nullptr,
const BBox2D & bbox = BBox2D{} )

Generates squiggle paths with secondary tributary branches along each edge.

Parameters
pathThe input path.
iterationsNumber of recursive subdivision levels.
seedRandom seed number.
branch_probabilityProbability of initiating a tributary branch at subdivision steps.
max_branchesMaximum number of secondary branches.
height_ratioHeight of the bounding triangle relative to edge length.
orientationDisplacement direction: 0 to alternate sides, 1 for positive normal, -1 for negative normal.
p_weightsOptional spatial weights Array.
p_maskOptional mask Array.
bboxBounding box for array sampling.
Returns
Vector of Paths where the first Path is the main trunk and subsequent Paths are tributary branches.

◆ truncate_at_first_intersection()

Path hmap::truncate_at_first_intersection ( const Path & path,
const std::vector< Path > & existing_paths )

Truncates a path at its first intersection with any path in a given set of existing paths. The intersection point is included as the new end point.

Parameters
pathThe input path to be truncated.
existing_pathsCollection of already existing paths.
Returns
Truncated path, or copy of the original path if no intersection is found.

◆ assert_start_end_points()

bool hmap::assert_start_end_points ( const Path & path1,
const Path & path2,
float tol = 1e-6f,
bool verbose = false )

Asserts that the start and end points of two paths are within a specified tolerance.

Parameters
path1The first path to compare.
path2The second path to compare.
tolTolerance for comparing the start and end points. Default is 1e-6f.
verboseIf true, prints detailed information during comparison. Default is false.

◆ chamfer_distance()

float hmap::chamfer_distance ( const Path & a,
const Path & b )

Calculate the chamfer distance between two paths.

Parameters
aThe first path.
bThe second path.

◆ has_duplicates() [2/2]

bool hmap::has_duplicates ( const Path & path,
float tol = 1e-6f )

Check if a path contains duplicate points within a given tolerance.

Parameters
pathThe path to check for duplicates.
tolTolerance for considering two points as the same. Default is 1e-6.
Returns
true If there are duplicate points in the path.
false If there are no duplicate points in the path.

◆ angle() [1/2]

float hmap::angle ( const Point & p1,
const Point & p2 )

Computes the angle between two points relative to the x-axis.

Parameters
p1The starting point of the vector.
p2The ending point of the vector.
Returns
The angle in radians in the range [-π, π].

◆ angle() [2/2]

float hmap::angle ( const Point & p0,
const Point & p1,
const Point & p2 )

Computes the angle formed by three points with p0 as the origin.

Parameters
p0The reference point (origin).
p1The first point defining the angle.
p2The second point defining the angle.
Returns
The angle in radians in the range [-π, π].

◆ classify_point()

float hmap::classify_point ( const Point & p_prev,
const Point & p,
const Point & p_next,
const Point & pq )

Classify point convexity relative to neighboring curve vertices.

◆ cross_product() [1/2]

float hmap::cross_product ( const Point & p0,
const Point & p1,
const Point & p2 )

Computes the 2D cross product of vectors (p1 - p0) and (p2 - p0).

Parameters
p0Common origin point.
p1First destination point.
p2Second destination point.
Returns
Scalar cross product value.

◆ cross_product() [2/2]

float hmap::cross_product ( const Point & p1,
const Point & p2 )

Computes the 2D cross product of vectors p1 and p2.

Parameters
p1First vector.
p2Second vector.
Returns
Scalar cross product (p1.x * p2.y - p1.y * p2.x).

◆ curvature()

float hmap::curvature ( const Point & p1,
const Point & p2,
const Point & p3 )

Calculates the curvature formed by three points in 2D space.

Parameters
p1The first point.
p2The second point.
p3The third point.
Returns
The curvature. Returns 0 if the points are collinear.

◆ curvature_signed()

float hmap::curvature_signed ( const Point & p1,
const Point & p2,
const Point & p3 )

Calculates the signed curvature formed by three points in 2D space.

◆ distance()

float hmap::distance ( const Point & p1,
const Point & p2 )

Calculates the Euclidean distance between two points.

Parameters
p1The first point.
p2The second point.
Returns
The distance between the two points.

◆ distance_squared()

float hmap::distance_squared ( const Point & p1,
const Point & p2 )

Calculates the squared Euclidean distance between two points.

Parameters
p1The first point.
p2The second point.
Returns
The squared distance between the two points.

◆ interp_bezier()

Point hmap::interp_bezier ( const Point & p_start,
const Point & p_ctrl_start,
const Point & p_ctrl_end,
const Point & p_end,
float t )

Performs a cubic Bezier interpolation.

Parameters
p_startThe first control point (start point).
p_ctrl_startThe second control point.
p_ctrl_endThe third control point.
p_endThe fourth control point (end point).
tThe interpolation parameter, ranging from 0 to 1.
Returns
The interpolated point on the Bezier curve.

◆ interp_bspline()

Point hmap::interp_bspline ( const Point & p0,
const Point & p1,
const Point & p2,
const Point & p3,
float t )

Performs a cubic B-spline interpolation.

Parameters
p0The first control point.
p1The second control point (start of segment).
p2The third control point (end of segment).
p3The fourth control point.
tThe interpolation parameter, ranging from 0 to 1.
Returns
The interpolated point on the B-spline curve.

◆ interp_catmullrom()

Point hmap::interp_catmullrom ( const Point & p0,
const Point & p1,
const Point & p2,
const Point & p3,
float t )

Performs a Catmull-Rom spline interpolation.

Parameters
p0The first control point.
p1The second control point (start of segment).
p2The third control point (end of segment).
p3The fourth control point.
tThe interpolation parameter, ranging from 0 to 1.
Returns
The interpolated point on the Catmull-Rom spline.

◆ interp_decasteljau()

Point hmap::interp_decasteljau ( const std::vector< Point > & points,
float t )

Performs a De Casteljau algorithm-based interpolation for Bezier curves.

Parameters
pointsA vector of control points defining the Bezier curve.
tThe interpolation parameter, ranging from 0 to 1.
Returns
The interpolated point on the Bezier curve.

◆ intersect_bounding_boxes()

BBox2D hmap::intersect_bounding_boxes ( const BBox2D & bbox1,
const BBox2D & bbox2 )

Determines the intersection of two bounding boxes.

Parameters
bbox1The first bounding box defined as glm::vec4.
bbox2The second bounding box defined as glm::vec4.
Returns
The intersecting bounding box, or {1, -1, 1, -1} if disjoint.

◆ is_point_within_bounding_box() [1/2]

bool hmap::is_point_within_bounding_box ( const Point & p,
const BBox2D & bbox )

Checks if a point is within a specified bounding box.

Parameters
pThe point to check.
bboxBounding box {xmin, xmax, ymin, ymax}.
Returns
true if the point is within the bounding box, false otherwise.

◆ is_point_within_bounding_box() [2/2]

bool hmap::is_point_within_bounding_box ( float x,
float y,
const BBox2D & bbox )

Checks if a point with coordinates (x, y) is within a specified bounding box.

Parameters
xThe x-coordinate.
yThe y-coordinate.
bboxBounding box {xmin, xmax, ymin, ymax}.
Returns
true if the point is within the bounding box, false otherwise.

◆ lerp() [1/4]

Point hmap::lerp ( const Point & p1,
const Point & p2,
float t )

Linearly interpolates between two points.

Parameters
p1The starting point.
p2The ending point.
tThe interpolation factor (0 <= t <= 1).
Returns
The interpolated point between p1 and p2.

◆ midpoint()

Point hmap::midpoint ( const Point & p1,
const Point & p2,
int orientation,
float distance_ratio,
float t = 0.5f )

Computes the midpoint displacement with a perpendicular offset.

Parameters
p1The first point.
p2The second point.
orientationOrientation of the perpendicular displacement.
distance_ratioRatio of displacement relative to segment length.
tInterpolation factor along segment (default 0.5).
Returns
The displaced midpoint.

◆ scale() [5/6]

Point hmap::scale ( const Point & p,
glm::vec2 scale,
glm::vec2 center = {0.5f, 0.5f} )

Scales a point relative to a center point.

Parameters
pThe input point.
scaleScale factor(s) for x and y axes.
centerCenter of scaling (defaults to (0.5, 0.5)).
Returns
The scaled point.

◆ scale() [6/6]

Point hmap::scale ( const Point & p,
float scale,
glm::vec2 center = {0.5f, 0.5f} )

Scales a point uniformly relative to a center point.

◆ segment_intersection()

std::optional< Point > hmap::segment_intersection ( const Point & p1,
const Point & p2,
const Point & q1,
const Point & q2 )

Computes the intersection point of two 2D segments, if it exists.

Parameters
p1Start point of first segment.
p2End point of first segment.
q1Start point of second segment.
q2End point of second segment.
Returns
The intersection point if segments intersect; std::nullopt otherwise.

◆ side()

float hmap::side ( const Point & p1,
const Point & p2,
const Point & p3,
const Point & p_query )

Determines the relative side of a query point with respect to a curve segment.

Parameters
p1Preceding curve point.
p2Reference curve point.
p3Succeeding curve point.
p_queryQuery point to test.
Returns
+1.0f (left/CCW), -1.0f (right/CW), 0.0f (on tangent).

◆ sort_points()

void hmap::sort_points ( std::vector< Point > & points)

Sorts a vector of points in ascending order (x, then y, then v).

Parameters
pointsVector of points to sort in-place.

◆ triangle_area()

float hmap::triangle_area ( const Point & p1,
const Point & p2,
const Point & p3 )

Calculates the unsigned area of a triangle formed by three points.

Parameters
p1The first point.
p2The second point.
p3The third point.
Returns
The absolute area.

◆ triangle_area_signed()

float hmap::triangle_area_signed ( const Point & p1,
const Point & p2,
const Point & p3 )

Calculates the signed area of a triangle formed by three points.

Parameters
p1The first point.
p2The second point.
p3The third point.
Returns
The signed area (positive = CCW, negative = CW).

◆ unit_square_bbox()

BBox2D hmap::unit_square_bbox ( )

Constructs a 4D bounding box for a unit square {0, 1, 0, 1}.

Returns
glm::vec4 Unit square bounding box.

◆ bbox_to_ranges2d()

std::array< std::pair< float, float >, 2 > hmap::bbox_to_ranges2d ( const BBox2D & bbox)

Converts a 2D bounding box into coordinate ranges.

This function takes a bounding box defined by four values (xmin, xmax, ymin, ymax) stored in a glm::vec4 and returns an array of two ranges:

  • ranges[0] = {xmin, xmax}
  • ranges[1] = {ymin, ymax}
Parameters
bboxBounding box in the format {xmin, xmax, ymin, ymax}.
Returns
An array of two pairs:
  • First pair: x-axis range (min, max)
  • Second pair: y-axis range (min, max)

◆ expand_points_domain()

void hmap::expand_points_domain ( std::vector< float > & x,
std::vector< float > & y,
std::vector< float > & value,
const BBox2D & bbox = BBox2D{} )

Expand grid by translating and copying the values of the current bounding box to the 8 first neighboring bounding boxes.

Parameters
xx coordinates.
yy coordinates.
valuevalues.
bboxBounding box.

◆ expand_points_at_domain_boundaries()

void hmap::expand_points_at_domain_boundaries ( std::vector< float > & x,
std::vector< float > & y,
std::vector< float > & value,
const BBox2D & bbox = BBox2D{},
float boundary_value = 0.f )

Expand the grid by adding points on the boundaries of the bounding box.

Parameters
xx coordinates.
yy coordinates.
valuevalues.
bboxBounding box.
corner_valueValue at the boundary points.

◆ expand_points_domain_corners()

void hmap::expand_points_domain_corners ( std::vector< float > & x,
std::vector< float > & y,
std::vector< float > & value,
const BBox2D & bbox = BBox2D{},
float corner_value = 0.f )

Expand the grid by adding four points at the corner of the bounding box.

Parameters
xx coordinates.
yy coordinates.
valuevalues.
bboxBounding box.
corner_valueValue at the four corner points.

◆ make_pointwise_function_from_array()

std::function< float(const ps::Point< float, 2 > &)> hmap::make_pointwise_function_from_array ( const Array & array,
const BBox2D & bbox )

Create a continuous 2D function from a sampled array.

This adaptor takes a discrete 2D array (indexed by i, j) defined over a bounding box and returns a continuous function \(f(x, y)\) that interpolates values at arbitrary 2D positions inside the bounding box.

The function maps a point \(p = (x, y)\) in world coordinates to array indices \((i, j)\) and interpolates the array values.

Parameters
arrayInput array containing sampled values on a regular grid.
bboxBounding box of the array in world coordinates, given as (xmin, xmax, ymin, ymax).
Returns
A function f(point) that returns the interpolated value at a 2D position.
Example
Array heightmap = [...];
glm::vec4 bbox = {0.0f, 100.0f, 0.0f, 100.0f};
auto f = make_pointwise_function_from_array(heightmap, bbox);
ps::Point<float, 2> p{25.5f, 42.3f};
float value = f(p); // interpolated value at (25.5, 42.3)
float f(int i, float gi)
Definition distance_transform.cpp:14
std::function< float(const ps::Point< float, 2 > &)> make_pointwise_function_from_array(const Array &array, const BBox2D &bbox)
Create a continuous 2D function from a sampled array.
Definition point_sampling.cpp:50

◆ random_points()

std::array< std::vector< float >, 2 > hmap::random_points ( size_t count,
std::uint32_t seed,
const PointSamplingMethod & method = PointSamplingMethod::RND_RANDOM,
const BBox2D & bbox = BBox2D{} )

Generates random 2D points within a bounding box using a sampling method.

Parameters
countNumber of points to generate.
seedRandom number generator seed.
methodSampling method to use. Defaults to PointSamplingMethod::RND_RANDOM.
bboxBounding box in which to generate the points (a,b,c,d = xmin, xmax, ymin, ymax). Defaults to the unit square {0.f, 1.f, 0.f, 1.f}.
Returns
A pair of float vectors {x_coords, y_coords}.

◆ random_points_density()

std::array< std::vector< float >, 2 > hmap::random_points_density ( size_t count,
const Array & density,
std::uint32_t seed,
const BBox2D & bbox = BBox2D{} )

Generates random 2D points within a bounding box based on a density map.

Points are sampled with probability proportional to the density values.

Parameters
countNumber of points to generate.
density2D array representing spatial density values.
seedRandom number generator seed.
bboxBounding box in which to generate the points (a,b,c,d = xmin, xmax, ymin, ymax). Defaults to the unit square {0.f, 1.f, 0.f, 1.f}.
Returns
A pair of float vectors {x_coords, y_coords}.

◆ random_points_inverse_sampling()

std::array< std::vector< float >, 2 > hmap::random_points_inverse_sampling ( size_t count,
const Array & array,
std::uint32_t seed,
const BBox2D & bbox = BBox2D{} )

Generates random 2D points within a bounding box using inverse transform sampling on a 2D density array.

Points are sampled according to continuous row-marginal and conditional column cumulative distributions interpolated from the 2D array.

Parameters
countNumber of points to generate.
array2D array representing spatial density / probability field.
seedRandom number generator seed.
bboxBounding box in which to generate the points (xmin, xmax, ymin, ymax). Defaults to the unit square {0.f, 1.f, 0.f, 1.f}.
Returns
A pair of float vectors {x_coords, y_coords}.

◆ random_points_distance() [1/2]

std::array< std::vector< float >, 2 > hmap::random_points_distance ( float min_dist,
std::uint32_t seed,
const BBox2D & bbox = BBox2D{} )

Generates random 2D points with a minimum separation distance.

Produces a blue-noise-like distribution where no two points are closer than min_dist.

Parameters
min_distMinimum allowed distance between points.
seedRandom number generator seed.
bboxBounding box in which to generate the points (a,b,c,d = xmin, xmax, ymin, ymax). Defaults to the unit square {0.f, 1.f, 0.f, 1.f}.
Returns
A pair of float vectors {x_coords, y_coords}.

◆ random_points_distance() [2/2]

std::array< std::vector< float >, 2 > hmap::random_points_distance ( float min_dist,
float max_dist,
const Array & density,
std::uint32_t seed,
const BBox2D & bbox = BBox2D{} )

Generates random 2D points with distance constraints and a density map.

Points are separated by distances between min_dist and max_dist, and are sampled proportionally to the given density map.

Parameters
min_distMinimum allowed distance between points.
max_distMaximum allowed distance between points.
density2D array representing spatial density values.
seedRandom number generator seed.
bboxBounding box in which to generate the points (a,b,c,d = xmin, xmax, ymin, ymax). Defaults to the unit square {0.f, 1.f, 0.f, 1.f}.
Returns
A pair of float vectors {x_coords, y_coords}.

◆ random_points_distance_power_law()

std::array< std::vector< float >, 2 > hmap::random_points_distance_power_law ( float dist_min,
float dist_max,
float alpha,
std::uint32_t seed,
const BBox2D & bbox = BBox2D{} )

Generates random 2D points with distances drawn from a power-law distribution.

Distances between points follow a power-law distribution between dist_min and dist_max, with exponent alpha.

Parameters
dist_minMinimum possible distance between points.
dist_maxMaximum possible distance between points.
alphaPower-law exponent (larger alpha favors shorter distances).
seedRandom number generator seed.
bboxBounding box in which to generate the points (a,b,c,d = xmin, xmax, ymin, ymax). Defaults to the unit square {0.f, 1.f, 0.f, 1.f}.
Returns
A pair of float vectors {x_coords, y_coords}.

◆ random_points_distance_weibull()

std::array< std::vector< float >, 2 > hmap::random_points_distance_weibull ( float dist_min,
float lambda,
float k,
std::uint32_t seed,
const BBox2D & bbox = BBox2D{} )

Generates random 2D points with distances drawn from a Weibull distribution.

Distances between points follow a Weibull distribution parameterized by lambda (scale) and k (shape).

Parameters
dist_minMinimum possible distance between points.
lambdaWeibull distribution scale parameter.
kWeibull distribution shape parameter.
seedRandom number generator seed.
bboxBounding box in which to generate the points (a,b,c,d = xmin, xmax, ymin, ymax). Defaults to the unit square {0.f, 1.f, 0.f, 1.f}.
Returns
A pair of float vectors {x_coords, y_coords}.

◆ random_points_jittered()

std::array< std::vector< float >, 2 > hmap::random_points_jittered ( size_t count,
const glm::vec2 & jitter_amount,
const glm::vec2 & stagger_ratio,
std::uint32_t seed,
const BBox2D & bbox = BBox2D{} )

Generates jittered grid-based 2D points.

Points are placed on a regular grid, offset by jitter_amount, and optionally staggered according to stagger_ratio.

Parameters
countNumber of points to generate.
jitter_amountMaximum jitter to apply in each axis (x, y).
stagger_ratioRatio of staggering between consecutive rows or columns.
seedRandom number generator seed.
bboxBounding box in which to generate the points (a,b,c,d = xmin, xmax, ymin, ymax). Defaults to the unit square {0.f, 1.f, 0.f, 1.f}.
Returns
A pair of float vectors {x_coords, y_coords}.

◆ remove_points_outside_bbox()

void hmap::remove_points_outside_bbox ( std::vector< float > & x,
std::vector< float > & y,
std::vector< float > & value,
const BBox2D & bbox = BBox2D{} )

Remove grid points that are outside a given bounding box.

Parameters
xx coordinates.
yy coordinates.
valueValues at points.
bboxBounding box.

◆ rescale_points_to_unit_square()

void hmap::rescale_points_to_unit_square ( std::vector< float > & x,
std::vector< float > & y,
const BBox2D & bbox )

Rescale coordinate (x, y) so that they fit in a unit-square box based on a given initial bounding box.

Parameters
x[in,out]x coordinates (output).
y[in,out]y coordinates (output).
bboxInitial bounding box.

◆ divergence_from_gradients()

Array hmap::divergence_from_gradients ( const Array & dx,
const Array & dy )

Compute the divergence of a 2D gradient field.

Given two scalar fields representing the horizontal and vertical derivatives of a height map:

\[ p(x, y) = \frac{\partial h}{\partial x}, \qquad q(x, y) = \frac{\partial h}{\partial y} \]

this function returns the divergence:

\[ f(x, y) = \frac{\partial p}{\partial x}(x, y) + \frac{\partial q}{\partial y}(x, y) \]

The divergence is a key term for solving the Poisson equation \(\nabla^2 h = f\) when reconstructing a height field from gradients or from a normal map.

Parameters
dxArray of horizontal derivatives ( \(\partial h / \partial x\)). Must have the same dimensions as dy.
dyArray of vertical derivatives ( \(\partial h / \partial y\)). Must have the same dimensions as dx.
Returns
A new Array containing the divergence \(f(x, y)\) for each pixel. The returned array has the same size as the inputs.

See unit tests: test_gradient.cpp

◆ gradient1d()

std::vector< float > hmap::gradient1d ( const std::vector< float > & v)

Compute the gradient of a 1D vector.

This function calculates the gradient of a 1D vector by computing the difference between successive elements.

Parameters
vInput vector of floats.
Returns
std::vector<float> Vector of gradient values.

◆ gradient_angle()

Array hmap::gradient_angle ( const Array & array,
bool downward = false )

Compute the polar angle of the gradient of a 2D array.

This function calculates the gradient angle of a 2D array, which represents the direction of the steepest ascent. The angle is measured in radians and falls within the range [-π, π]. The direction can be inverted if the downward flag is set to true.

Parameters
arrayInput 2D array.
downwardIf true, invert the direction of the gradient.
Returns
Array Gradient angles in radians.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {4.f, 4.f};
int seed = 1;
// --- Angle compute
auto a0 = hmap::gradient_angle(z);
// --- Smoothing
int ir = 16;
auto a2 = a0;
float talus = M_PI;
float talus_width = 0.01f * talus;
ir = 16;
hmap::smooth_cpulse_edge_removing(a2, talus, talus_width, ir);
// --- Jump mask
auto mask = hmap::talus_jump_mask(a1, M_PI, 0.1f * M_PI);
hmap::export_banner_png("ex_gradient_angle.png",
{z, a0, a1, a2, mask},
false,
true);
}
Array talus_jump_mask(const Array &z, float threshold, float sigma)
Definition gradient.cpp:305
Array gradient_angle_circular_smoothing(const Array &array, int ir, bool downward=false)
Computes a smoothed gradient angle (aspect) field with circular unwrapping.
Definition gradient.cpp:96
void smooth_cpulse_edge_removing(Array &array, float talus, float talus_width, int ir)
Smooths an array while attenuating edges using a gradient-based pulse.
Definition filters.cpp:1052
Array gradient_angle(const Array &array, bool downward=false)
Compute the polar angle of the gradient of a 2D array.
Definition gradient.cpp:73

Result

See unit tests: test_gradient.cpp

◆ gradient_angle_circular_smoothing()

Array hmap::gradient_angle_circular_smoothing ( const Array & array,
int ir,
bool downward = false )

Computes a smoothed gradient angle (aspect) field with circular unwrapping.

This function computes the gradient angle (aspect) of the input scalar field and applies a circular smoothing to remove discontinuities caused by the ±π wrap of the arctangent. The angle field is smoothed by converting the angle to a unit vector representation on the circle, applying a local smoothing kernel, and converting it back to an angle. This results in a continuous aspect map that is ideal for visualization or further processing.

Parameters
arrayInput scalar field (e.g., a heightmap).
irRadius of the local smoothing kernel applied to the angle vectors.
downwardIf set to true, angles are adjusted to point in the downslope direction (useful for hydrology or flow simulations). If false, angles point in the upslope direction.
Returns
An Array containing the smoothed gradient angles in radians, in the range [-π, π].
Note
  • Regions with very low gradient magnitude may produce unstable angle values; these regions should typically be masked or treated separately.
  • This function is suited for preserving continuous angular fields when the direction (not the orientation) of the gradient matters.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {4.f, 4.f};
int seed = 1;
// --- Angle compute
auto a0 = hmap::gradient_angle(z);
// --- Smoothing
int ir = 16;
auto a2 = a0;
float talus = M_PI;
float talus_width = 0.01f * talus;
ir = 16;
hmap::smooth_cpulse_edge_removing(a2, talus, talus_width, ir);
// --- Jump mask
auto mask = hmap::talus_jump_mask(a1, M_PI, 0.1f * M_PI);
hmap::export_banner_png("ex_gradient_angle.png",
{z, a0, a1, a2, mask},
false,
true);
}

Result

◆ gradient_norm()

Array hmap::gradient_norm ( const Array & array,
Array * p_dx = nullptr,
Array * p_dy = nullptr )

Compute the gradient norm of a 2D array.

This function calculates the gradient norm (magnitude) of a 2D array. Optionally, the x and y gradients can be computed and stored in p_dx and p_dy respectively.

Parameters
arrayInput 2D array.
p_dxPointer to an Array where the x-gradient will be stored (optional).
p_dyPointer to an Array where the y-gradient will be stored (optional).
Returns
Array Gradient norm (magnitude).

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
auto dz = hmap::gradient_norm(z);
auto dz_s = hmap::gradient_norm_sobel(z);
int ir = 6;
auto dz_f = hmap::gradient_norm_filtered(z, ir);
hmap::export_banner_png("ex_gradient_norm.png",
{dz, dz_p, dz_c, dz_s, dz_f},
}
Array gradient_norm_scharr(const Array &array, Array *p_dx=nullptr, Array *p_dy=nullptr)
Compute the gradient norm of a 2D array using the Scharr filter.
Definition gradient.cpp:191
Array gradient_norm_filtered(const Array &array, int ir)
Compute a smoothed gradient magnitude map.
Definition gradient.cpp:146
Array gradient_norm_prewitt(const Array &array, Array *p_dx=nullptr, Array *p_dy=nullptr)
Compute the gradient norm of a 2D array using the Prewitt filter.
Definition gradient.cpp:161
Array gradient_norm_sobel(const Array &array, Array *p_dx=nullptr, Array *p_dy=nullptr)
Compute the gradient norm of a 2D array using the Sobel filter.
Definition gradient.cpp:176

Result

See unit tests: test_gradient.cpp

◆ gradient_norm_filtered()

Array hmap::gradient_norm_filtered ( const Array & array,
int ir )

Compute a smoothed gradient magnitude map.

The input array is downsampled by a factor of ir, the gradient norm is computed on the lower-resolution array, scaled back to the original units, and finally upsampled to the original resolution using bicubic interpolation.

Parameters
arrayInput array.
irDownsampling factor (> 0).
Returns
Gradient norm filtered at a larger spatial scale.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {4.f, 4.f};
int seed = 1;
hmap::export_banner_png("ex_gradient_norm_filtered.png",
{z, g},
}

Result

◆ gradient_norm_prewitt()

Array hmap::gradient_norm_prewitt ( const Array & array,
Array * p_dx = nullptr,
Array * p_dy = nullptr )

Compute the gradient norm of a 2D array using the Prewitt filter.

This function calculates the gradient norm (magnitude) using the Prewitt filter for gradient computation. Optionally, the x and y gradients can be computed and stored in p_dx and p_dy respectively.

Parameters
arrayInput 2D array.
p_dxPointer to an Array where the x-gradient will be stored (optional).
p_dyPointer to an Array where the y-gradient will be stored (optional).
Returns
Array Gradient norm (magnitude).

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
auto dz = hmap::gradient_norm(z);
auto dz_s = hmap::gradient_norm_sobel(z);
int ir = 6;
auto dz_f = hmap::gradient_norm_filtered(z, ir);
hmap::export_banner_png("ex_gradient_norm.png",
{dz, dz_p, dz_c, dz_s, dz_f},
}

Result

See unit tests: test_gradient.cpp

◆ gradient_norm_scharr()

Array hmap::gradient_norm_scharr ( const Array & array,
Array * p_dx = nullptr,
Array * p_dy = nullptr )

Compute the gradient norm of a 2D array using the Scharr filter.

This function calculates the gradient norm (magnitude) using the Scharr filter for gradient computation. Optionally, the x and y gradients can be computed and stored in p_dx and p_dy respectively.

Parameters
arrayInput 2D array.
p_dxPointer to an Array where the x-gradient will be stored (optional).
p_dyPointer to an Array where the y-gradient will be stored (optional).
Returns
Array Gradient norm (magnitude).

See unit tests: test_gradient.cpp

◆ gradient_norm_sobel()

Array hmap::gradient_norm_sobel ( const Array & array,
Array * p_dx = nullptr,
Array * p_dy = nullptr )

Compute the gradient norm of a 2D array using the Sobel filter.

This function calculates the gradient norm (magnitude) using the Sobel filter for gradient computation. Optionally, the x and y gradients can be computed and stored in p_dx and p_dy respectively.

Parameters
arrayInput 2D array.
p_dxPointer to an Array where the x-gradient will be stored (optional).
p_dyPointer to an Array where the y-gradient will be stored (optional).
Returns
Array Gradient norm (magnitude).

See unit tests: test_gradient.cpp

◆ gradient_talus() [1/2]

Array hmap::gradient_talus ( const Array & array)

Compute the gradient talus slope of a 2D array.

The talus slope is defined as the largest elevation difference between a cell and its immediate neighbors. This function computes the talus slope for the given 2D array.

Parameters
arrayInput 2D array.
Returns
Array Gradient talus slope.
See also
Thermal erosion: thermal.

See unit tests: test_gradient.cpp

◆ gradient_talus() [2/2]

void hmap::gradient_talus ( const Array & array,
Array & talus )

Compute the gradient talus slope and store it in the provided array.

This overload computes the gradient talus slope of a 2D array and stores the result in the given talus array.

Parameters
arrayInput 2D array.
talusOutput array where the gradient talus slope will be stored.

See unit tests: test_gradient.cpp This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ gradient_x() [1/2]

Array hmap::gradient_x ( const Array & array)

Compute the gradient in the x-direction of a 2D array.

This function calculates the gradient in the x-direction (i.e., horizontal gradient) for the given 2D array.

Parameters
arrayInput 2D array.
Returns
Array Gradient in the x-direction.

See unit tests: test_gradient.cpp

◆ gradient_x() [2/2]

void hmap::gradient_x ( const Array & array,
Array & dx )

Compute the gradient in the x-direction of a 2D array and store it.

This overload calculates the gradient in the x-direction and stores the result in the provided dx array.

Parameters
arrayInput 2D array.
dxOutput array where the gradient in the x-direction will be stored. This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ gradient_y() [1/2]

Array hmap::gradient_y ( const Array & array)

Compute the gradient in the y-direction of a 2D array.

This function calculates the gradient in the y-direction (i.e., vertical gradient) for the given 2D array.

Parameters
arrayInput 2D array.
Returns
Array Gradient in the y-direction.

See unit tests: test_gradient.cpp

◆ gradient_y() [2/2]

void hmap::gradient_y ( const Array & array,
Array & dy )

Compute the gradient in the y-direction of a 2D array and store it.

This overload calculates the gradient in the y-direction and stores the result in the provided dy array.

Parameters
arrayInput 2D array.
dyOutput array where the gradient in the y-direction will be stored. This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ laplacian()

Array hmap::laplacian ( const Array & array)

Compute the Laplacian of a 2D array.

The Laplacian is a measure of the second-order spatial derivative of the input array. This function computes the Laplacian for the given 2D array.

Parameters
arrayInput 2D array.
Returns
Array Laplacian of the input array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
auto d = hmap::laplacian(z);
// same as standard laplacian
auto df0 = hmap::gpu::laplacian_fract(z, /* s */ 1.f, /* ir */ 1);
int ir = 8;
float s = 0.2f; // fractional exponent
auto df1 = hmap::gpu::laplacian_fract(z, s, ir);
hmap::export_banner_png("ex_laplacian.png",
{z, d, df0, df1},
true);
}
Array laplacian_fract(const Array &array, float s, int ir)
Compute the fractional Laplacian of an array.
Definition gradient_gpu.cpp:54
Array laplacian(const Array &array)
Compute the Laplacian of a 2D array.
Definition gradient.cpp:290

Result

See unit tests: test_gradient.cpp

◆ normal_map()

Texture hmap::normal_map ( const Array & array)

Generates a normal map from a given 2D array.

This function calculates the normal vectors for each element in the 2D array and returns them as a tensor. The normal map is commonly used in image processing and 3D graphics to represent surface orientations based on height values.

Parameters
arrayA 2D array representing the height values from which normals are computed.
Returns
A tensor containing the normal vectors for each position in the input array.

◆ normal_map_to_heightmap()

Array hmap::normal_map_to_heightmap ( const Texture & nmap)

Converts a normal map to a heightmap using direct summation of gradients.

This function computes a heightmap from a given normal map (nmap) by integrating gradients derived from the normal map in two passes. The result is the average of two independent integrations to reduce artifacts from directional bias.

Parameters
nmapA 3D tensor representing the normal map. It should have three channels (X, Y, Z) and a shape of (width, height, 3). The values are assumed to be in the range [0, 1].
Returns
An Array object representing the computed heightmap with the same spatial dimensions as the input normal map (width, height).
Note

Result

◆ normal_map_to_heightmap_poisson()

Array hmap::normal_map_to_heightmap_poisson ( const Texture & nmap,
int iterations = 500,
float omega = 1.5f )

◆ solve_poisson_gauss_seidel()

void hmap::solve_poisson_gauss_seidel ( const Array & rhs,
Array & h,
int iterations = 500,
float omega = 1.0f )

Solve the Poisson equation ∇²h = rhs using Gauss–Seidel iteration.

This function assumes Dirichlet boundary conditions (height = 0 at the edges). The algorithm updates interior points according to:

\[ h(x, y) = (1 - \omega) h(x, y) + \omega \cdot 0.25 \big( h(x+1, y) + h(x-1, y) + h(x, y+1) + h(x, y-1) - rhs(x, y) \big) \]

Parameters
rhsRight-hand side (divergence of gradients).
hHeight field to update; initialized to 0 or an estimate.
iterationsNumber of Gauss–Seidel iterations to run.
omegaRelaxation parameter (1 = standard Gauss–Seidel, 1 < omega < 2 = over-relaxation).

◆ unwrap_phase()

Array hmap::unwrap_phase ( const Array & alpha)

Unwraps a 2D phase array to correct discontinuities in phase data.

This function unwraps phase values in the given array, ensuring that discontinuities exceeding \( \pi \) are adjusted to provide a continuous phase result.

Parameters
alphaA 2D array of wrapped phase values.
Returns
A 2D array of unwrapped phase values.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
// unwrapped reference
shape,
res,
seed);
hmap::remap(alpha0, 0.f, 4.f * M_PI);
// wrap it
hmap::Array alpha = alpha0;
for (auto &v : alpha.vector)
v = std::fmod(v, 2.f * M_PI);
// unwrap (and shift zero reference)
hmap::Array alpha_uw = hmap::unwrap_phase(alpha);
alpha_uw = alpha_uw - alpha_uw.min() + alpha0.min();
hmap::export_banner_png("ex_unwrap_phase.png",
{alpha0, alpha, alpha_uw},
}
std::vector< float > vector
The underlying data storage, a vector of size shape.x * shape.y.
Definition array.hpp:43
Array unwrap_phase(const Array &alpha)
Unwraps a 2D phase array to correct discontinuities in phase data.
Definition unwrap_phase.cpp:16

Result

◆ talus_jump_mask()

Array hmap::talus_jump_mask ( const Array & z,
float threshold,
float sigma )

◆ basin_id()

Array hmap::basin_id ( const Array & z,
bool fast_approx = false,
bool remove_lakes = true )

Label drainage basins using a priority-flood algorithm.

Starting from boundary cells, this function floods a 2D scalar field inward using a height-ordered priority queue and assigns each cell to a basin. Each boundary cell initializes a unique basin.

Connectivity is 8-neighbor. Spill elevations between basins are detected but not yet recorded.

Parameters
zInput 2D elevation array.
Returns
Array of basin identifiers with the same shape as z.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {8.f, 8.f};
int seed = 0;
hmap::Array id1 = hmap::basin_id(z, false);
hmap::Array id2 = hmap::basin_id(z, true);
hmap::export_banner_png("ex_basin_id.png", {z, id1, id2}, hmap::Cmap::JET);
}
Array basin_id(const Array &z, bool fast_approx=false, bool remove_lakes=true)
Label drainage basins using a priority-flood algorithm.
Definition basin_id.cpp:14

Result

◆ carve_riverbed()

Array hmap::carve_riverbed ( const Array & z,
const Array & z_river,
float talus_riverbank = 0.01f,
bool smooth_river_bottom = true,
float merging_distance = 8.f,
std::uint32_t seed = 0,
float riverbank_noise_ratio = 0.f,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr )

Blends and carves smooth riverbanks around modified riverbed profiles.

Compares an initial elevation terrain z with an updated/carved riverbed z_river, identifies modified cells, expands riverbanks using talus slopes, smooths the channel bottom, and blends the carved river with the original terrain using distance-transform based exponential falloff and optional domain warping.

Parameters
zOriginal terrain elevation array.
z_riverCarved riverbed elevation array (or stream bottom).
talus_riverbankTalus slope angle/ratio for riverbank expansion.
smooth_river_bottomWhether to apply Laplace smoothing along the river bottom.
merging_distanceTransition distance (in pixels) for blending riverbanks into terrain.
seedRandom seed for riverbank noise.
riverbank_noise_ratioNoise ratio for talus expansion roughness.
p_noise_xOptional noise array for domain warping in X.
p_noise_yOptional noise array for domain warping in Y.
Returns
Merged terrain array with smoothly carved river channels.

◆ d8_compute_ndip()

Array hmap::d8_compute_ndip ( const Array & d8)

Computes the number of drainage paths for each cell based on the D8 flow direction model.

This function calculates the number of neighboring cells that have flow directions pointing to the current cell according to the D8 model. The result is an array where each cell contains the count of its incoming flow directions.

Parameters
d8Input array representing the flow directions according to the D8 model. Each cell value indicates the direction of flow according to the D8 convention.
Returns
Array An array where each cell contains the number of incoming flow directions pointing to it.

◆ find_flow_apex()

void hmap::find_flow_apex ( const Array & z,
std::vector< int > & is,
std::vector< int > & js )

Identifies flow apex (source) cells using D8 flow routing.

A flow apex is defined as a cell with zero inflow neighbors (no upstream contributors) in the D8 flow graph. These cells correspond to drainage sources, ridge heads, or local flow origins.

Parameters
zInput elevation field.
isOutput x-coordinates of flow apex cells.
jsOutput y-coordinates of flow apex cells.

◆ find_flow_sinks() [1/2]

void hmap::find_flow_sinks ( const Array & z,
std::vector< int > & is,
std::vector< int > & js )

Identifies the indices of flow sinks within the heightmap.

This function locates the cells in the heightmap that are flow sinks (cells with no outflow) and returns their indices. Flow sinks are cells that do not direct flow to any other cell.

Parameters
zInput array representing the heightmap values.
isOutput vector containing the row indices i of the flow sinks.
jsOutput vector containing the column indices j of the flow sinks.

Example

#include <iostream>
#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
std::vector<int> is, js;
for (size_t k = 0; k < is.size(); k++)
std::cout << is[k] << " " << js[k] << "\n";
}
void find_flow_sinks(const Array &z, std::vector< int > &is, std::vector< int > &js)
Identifies the indices of flow sinks within the heightmap.
Definition find_flow_sinks.cpp:40

◆ find_flow_sinks() [2/2]

std::vector< glm::ivec2 > hmap::find_flow_sinks ( const Array & z)

Find interior flow sinks in a height field.

A sink is a cell whose 8 neighbors all have strictly higher elevation. Border cells are excluded.

Parameters
zInput elevation grid.
Returns
List of sink cell coordinates (i, j).

◆ find_flow_sinks_border()

std::vector< glm::ivec2 > hmap::find_flow_sinks_border ( const Array & z)

Find flow sinks located on the domain border.

A border cell is considered a sink if all its valid neighbors (within bounds) have strictly higher elevation.

Parameters
zInput elevation grid.
Returns
List of border sink cell coordinates (i, j).

◆ flooding_uniform_level()

Array hmap::flooding_uniform_level ( const Array & z,
float zref )

Compute water depth for a uniform flooding level.

Subtracts terrain elevation from a reference water level and clamps negative values to zero.

Parameters
zInput elevation array.
zrefReference water level.
Returns
Water depth array (0 where terrain is above zref).

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
int i, j;
i = 32;
j = 64;
hmap::Array water_depth1 = hmap::flooding_from_point(z, i, j);
i = 64;
j = 150;
float depth_min = 0.3f;
hmap::Array water_depth2 = hmap::flooding_from_point(z, i, j, depth_min);
hmap::Array water_depth3 = hmap::flooding_from_point(z, {32, 64}, {64, 150});
float water_zmax = 0.35f;
hmap::Array water_depth4 = flooding_from_boundaries(z, water_zmax);
hmap::Array water_depth5 = flooding_uniform_level(z, water_zmax);
hmap::export_banner_png("ex_flooding_from_point.png",
{z,
water_depth1,
z + water_depth1,
water_depth2,
z + water_depth2,
water_depth3,
z + water_depth3,
water_depth4,
z + water_depth4,
water_depth5,
z + water_depth5},
}
Array flooding_from_point(const Array &z, int i, int j, float depth_min=std::numeric_limits< float >::max(), const UvTile &region=UvTile::dummy(), ICommunicator &comm=SingleArrayComm::instance())
Flood terrain starting from a single seed point.
Definition flooding.cpp:394
Array flooding_from_boundaries(const Array &z, float zref, bool from_east=true, bool from_west=true, bool from_north=true, bool from_south=true, const UvTile &region=UvTile::dummy(), ICommunicator &comm=SingleArrayComm::instance())
Compute flooding starting from the lowest boundary points.
Definition flooding.cpp:36

Result

◆ flooding_from_boundaries()

Array hmap::flooding_from_boundaries ( const Array & z,
float zref,
bool from_east = true,
bool from_west = true,
bool from_north = true,
bool from_south = true,
const UvTile & region = UvTile::dummy(),
ICommunicator & comm = SingleArrayComm::instance() )

Compute flooding starting from the lowest boundary points.

Finds the lowest elevation on the selected boundaries and simulates flooding from those points up to a reference water level.

Parameters
zInput elevation array.
zrefReference water level.
from_eastInclude east boundary.
from_westInclude west boundary.
from_northInclude north boundary.
from_southInclude south boundary.
regionTile region metadata.
commCommunicator for tiled / distributed execution.
Returns
Water depth array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
int i, j;
i = 32;
j = 64;
hmap::Array water_depth1 = hmap::flooding_from_point(z, i, j);
i = 64;
j = 150;
float depth_min = 0.3f;
hmap::Array water_depth2 = hmap::flooding_from_point(z, i, j, depth_min);
hmap::Array water_depth3 = hmap::flooding_from_point(z, {32, 64}, {64, 150});
float water_zmax = 0.35f;
hmap::Array water_depth4 = flooding_from_boundaries(z, water_zmax);
hmap::Array water_depth5 = flooding_uniform_level(z, water_zmax);
hmap::export_banner_png("ex_flooding_from_point.png",
{z,
water_depth1,
z + water_depth1,
water_depth2,
z + water_depth2,
water_depth3,
z + water_depth3,
water_depth4,
z + water_depth4,
water_depth5,
z + water_depth5},
}

Result

◆ flooding_from_point() [1/2]

Array hmap::flooding_from_point ( const Array & z,
int i,
int j,
float depth_min = std::numeric_limits<float>::max(),
const UvTile & region = UvTile::dummy(),
ICommunicator & comm = SingleArrayComm::instance() )

Flood terrain starting from a single seed point.

Fills areas below a reference level by propagating from the given cell until higher ground is reached.

Parameters
zInput elevation array.
iSeed point X index.
jSeed point Y index.
depth_minWater depth at the source point (if max, uses 0).
Returns
Water depth array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
int i, j;
i = 32;
j = 64;
hmap::Array water_depth1 = hmap::flooding_from_point(z, i, j);
i = 64;
j = 150;
float depth_min = 0.3f;
hmap::Array water_depth2 = hmap::flooding_from_point(z, i, j, depth_min);
hmap::Array water_depth3 = hmap::flooding_from_point(z, {32, 64}, {64, 150});
float water_zmax = 0.35f;
hmap::Array water_depth4 = flooding_from_boundaries(z, water_zmax);
hmap::Array water_depth5 = flooding_uniform_level(z, water_zmax);
hmap::export_banner_png("ex_flooding_from_point.png",
{z,
water_depth1,
z + water_depth1,
water_depth2,
z + water_depth2,
water_depth3,
z + water_depth3,
water_depth4,
z + water_depth4,
water_depth5,
z + water_depth5},
}

Result

◆ flooding_from_point() [2/2]

Array hmap::flooding_from_point ( const Array & z,
const std::vector< int > & i,
const std::vector< int > & j,
float depth_min = std::numeric_limits<float>::max(),
const UvTile & region = UvTile::dummy(),
ICommunicator & comm = SingleArrayComm::instance() )

Flood terrain starting from multiple seed points.

Merges flooding results from each point below the reference level.

Parameters
zInput elevation array.
iList of X indices for seeds.
jList of Y indices for seeds.
depth_minWater depth at the source point (if max, uses 0).
regionTile region metadata.
commCommunicator for tiled / distributed execution.
Returns
Water depth array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
int i, j;
i = 32;
j = 64;
hmap::Array water_depth1 = hmap::flooding_from_point(z, i, j);
i = 64;
j = 150;
float depth_min = 0.3f;
hmap::Array water_depth2 = hmap::flooding_from_point(z, i, j, depth_min);
hmap::Array water_depth3 = hmap::flooding_from_point(z, {32, 64}, {64, 150});
float water_zmax = 0.35f;
hmap::Array water_depth4 = flooding_from_boundaries(z, water_zmax);
hmap::Array water_depth5 = flooding_uniform_level(z, water_zmax);
hmap::export_banner_png("ex_flooding_from_point.png",
{z,
water_depth1,
z + water_depth1,
water_depth2,
z + water_depth2,
water_depth3,
z + water_depth3,
water_depth4,
z + water_depth4,
water_depth5,
z + water_depth5},
}

Result

◆ flooding_lake_system()

Array hmap::flooding_lake_system ( const Array & z,
float surface_threshold = 0.f,
const UvTile & region = UvTile::dummy(),
ICommunicator & comm = SingleArrayComm::instance() )

Estimate lake water depths on a terrain by filling depressions.

This function identifies depressions in a terrain elevation model and simulates the flooding of these areas to produce a lake system. It uses a rough depression-filling algorithm to compute the water surface, then subtracts the original elevations to obtain the water depth at each cell.

Parameters
zInput 2D array representing terrain elevations (height field).
surface_thresholdThe minimum number of pixels a component must have to be retained. Components smaller than this threshold will be removed. The default value is 0 (no filtering).
regionTile region metadata (for tiled execution).
commCommunicator for multi-tile synchronization.
Returns
A 2D array representing the water depth for each cell. Values are zero where no lake is present and positive where water accumulates in depressions.
See also
depression_filling

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
hmap::export_banner_png("ex_flooding_lake_system.png",
{z, z + water_depth},
}
Array flooding_lake_system(const Array &z, float surface_threshold=0.f, const UvTile &region=UvTile::dummy(), ICommunicator &comm=SingleArrayComm::instance())
Estimate lake water depths on a terrain by filling depressions.
Definition flooding.cpp:573

Result

◆ flow_accumulation_d8()

Array hmap::flow_accumulation_d8 ( const Array & z)

Computes the flow accumulation for each cell using the D8 flow direction model.

This function calculates the flow accumulation for each cell in the heightmap based on the D8 flow direction model [Zhou2019]. Flow accumulation represents the total amount of flow that accumulates at each cell from upstream cells.

Parameters
zInput array representing the heightmap values.
Returns
Array An array where each cell contains the computed flow accumulation.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {2.f, 2.f};
int seed = 1;
z.to_png("ex_flow_accumulation_d80.png", hmap::Cmap::TERRAIN, true);
facc.to_png("ex_flow_accumulation_d81.png", hmap::Cmap::HOT);
}
Array flow_accumulation_d8(const Array &z)
Computes the flow accumulation for each cell using the D8 flow direction model.
Definition flow_accumulation_d8.cpp:50
@ HOT
Definition colormaps.hpp:86

Result

See also
flow_direction_d8

◆ flow_accumulation_stochastic()

Array hmap::flow_accumulation_stochastic ( const Array & z,
int n_samples = 1 << 19,
std::uint32_t seed = 0,
const Array * p_source = nullptr,
const Array * p_decay = nullptr )

Computes flow accumulation using a stochastic (Monte-Carlo) transport estimator.

Particles are spawned uniformly, advected along the downhill gradient field with exact voxel traversal, attenuated by an optional decay term, and deposit flux into every cell they exit. A final analytic normalization yields the steady-state flux, including for cells no particle visited. Compared to flow_accumulation_d8, the result is smooth and free of axis-aligned artifacts.

Port of the reference implementation of "Stochastic Geomorphological Transport for Terrain Erosion Simulation" (N. McDonald, G. Cordonnier), https://github.com/erosiv/geotransport (MIT).

Results are reproducible up to floating-point summation order (deposits accumulate via unordered atomic adds).

Parameters
zInput array representing the heightmap values.
n_samplesNumber of Monte-Carlo samples (particles).
seedRandom seed number (deterministic for fixed inputs).
p_sourceOptional per-cell source term (default: uniform 1).
p_decayOptional per-cell decay rate (default: 0, pure accumulation).
Returns
Array Per-cell steady-state flux.

Example

#include <cmath>
#include <iostream>
#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {2.f, 2.f};
int seed = 1;
// Dinf for visual reference
auto facc_d8 = hmap::flow_accumulation_d8(z);
auto facc_dinf = hmap::flow_accumulation_dinf(z, 1.f / shape.x);
auto facc_st = hmap::flow_accumulation_stochastic(z, 1 << 18, 1);
auto facc_gpu = hmap::gpu::flow_accumulation_stochastic(z, 1 << 18, 1);
// CPU/GPU agreement: Pearson correlation on log(1 + flux)
double sx = 0, sy = 0, sxx = 0, syy = 0, sxy = 0;
int ncells = shape.x * shape.y;
for (int k = 0; k < ncells; ++k)
{
double a = std::log1p((double)facc_st.vector[k]);
double b = std::log1p((double)facc_gpu.vector[k]);
sx += a;
sy += b;
sxx += a * a;
syy += b * b;
sxy += a * b;
}
double corr = (ncells * sxy - sx * sy) / (std::sqrt(ncells * sxx - sx * sx) *
std::sqrt(ncells * syy - sy * sy));
std::cout << "stochastic flow acc. min/max: " << facc_st.min() << " "
<< facc_st.max() << "\n";
std::cout << "CPU/GPU log-flux correlation: " << corr << "\n";
// flux spans many orders of magnitude, so log-scale before rendering to
// PNG (linear scaling makes the image mostly black with a few blown-out
// pixels); apply the same treatment to the D8 output so both images stay
// visually comparable
auto facc_d8_log = hmap::log10(1.f + facc_d8);
auto facc_st_log = hmap::log10(1.f + facc_st);
auto facc_dinf_log = hmap::log10(1.f + facc_dinf);
z.to_png("ex_flow_accumulation_stochastic0.png", hmap::Cmap::TERRAIN, true);
facc_d8_log.to_png("ex_flow_accumulation_stochastic1.png", hmap::Cmap::HOT);
facc_st_log.to_png("ex_flow_accumulation_stochastic2.png", hmap::Cmap::HOT);
facc_dinf_log.to_png("ex_flow_accumulation_stochastic3.png", hmap::Cmap::HOT);
}
Array flow_accumulation_stochastic(const Array &z, int n_samples=1<< 19, std::uint32_t seed=0, const Array *p_source=nullptr, const Array *p_decay=nullptr)
GPU (OpenCL) variant of hmap::flow_accumulation_stochastic — see the CPU declaration for the algorith...
Definition flow_accumulation_stochastic_gpu.cpp:19
Array log10(const Array &array)
Base-10 logarithm.
Definition math.cpp:378
Array flow_accumulation_dinf(const Array &z, float talus_ref=0.1f, int iterations=0, const UvTile &region={}, ICommunicator &comm=SingleArrayComm::instance())
Computes the flow accumulation for each cell using the Multiple Flow Direction (MFD) model.
Definition flow_accumulation_dinf.cpp:29
Array flow_accumulation_stochastic(const Array &z, int n_samples=1<< 19, std::uint32_t seed=0, const Array *p_source=nullptr, const Array *p_decay=nullptr)
Computes flow accumulation using a stochastic (Monte-Carlo) transport estimator.
Definition flow_accumulation_stochastic.cpp:43

Result

See also
flow_accumulation_d8

◆ flow_accumulation_dinf()

Array hmap::flow_accumulation_dinf ( const Array & z,
float talus_ref = 0.1f,
int iterations = 0,
const UvTile & region = {},
ICommunicator & comm = SingleArrayComm::instance() )

Computes the flow accumulation for each cell using the Multiple Flow Direction (MFD) model.

This function calculates the flow accumulation for each cell based on the MFD model [Qin2007]. Flow accumulation represents the total amount of flow that accumulates at each cell from upstream cells. The flow-partition exponent is locally defined using a reference talus value, where smaller values of talus_ref will lead to narrower flow streams. The maximum talus value of the heightmap can be used as a reference.

Parameters
zInput array representing the heightmap values.
talus_refReference talus used to locally define the flow-partition exponent. Small values will result in thinner flow streams.
iterationsMaximum number of boundary exchange iterations across tiles (0 defaults to auto: grid diameter).
regionUvTile descriptor for tiled domain positioning.
commCommunicator for multi-tile synchronization.
Returns
Array An array where each cell contains the computed flow accumulation.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {1.f, 1.f};
int seed = 1;
auto facc = hmap::flow_accumulation_dinf(z, talus.max());
// very high values are less relevant
hmap::clamp_max(facc, 200.f);
int nsamples = 20;
glm::vec2 kw = {4.f, 4.f};
float amp = 0.1f;
hmap::Array scaling = hmap::cubic_pulse(shape, nullptr, nullptr);
talus.max(),
nsamples,
kw,
seed,
amp,
&scaling);
hmap::clamp_max(facc_p, 200.f);
z.to_png("ex_flow_accumulation_dinf0.png", hmap::Cmap::TERRAIN, true);
facc.to_png("ex_flow_accumulation_dinf1.png", hmap::Cmap::HOT);
facc_p.to_png("ex_flow_accumulation_dinf2.png", hmap::Cmap::HOT);
}
Array flow_accumulation_dinf_perturbed(const Array &z, float talus_ref, int nsamples, glm::vec2 kw, std::uint32_t seed, float amp, const Array *p_perturb_scaling=nullptr, const UvRect &uv_rect=UvRect::unit(), int iterations=0, const UvTile &region={}, ICommunicator &comm=SingleArrayComm::instance())
Computes averaged D-infinity flow accumulation with terrain perturbations.
Definition flow_accumulation_dinf.cpp:261
Array cubic_pulse(glm::ivec2 shape)
Generates a cubic pulse kernel array.
Definition kernels.cpp:107
void clamp_max(Array &array, float vmax)
Clamp array values larger than a given bound.
Definition range.cpp:87

Result

See also
flow_direction_dinf, flow_accumulation_d8

◆ flow_accumulation_dinf_perturbed()

Array hmap::flow_accumulation_dinf_perturbed ( const Array & z,
float talus_ref,
int nsamples,
glm::vec2 kw,
std::uint32_t seed,
float amp,
const Array * p_perturb_scaling = nullptr,
const UvRect & uv_rect = UvRect::unit(),
int iterations = 0,
const UvTile & region = {},
ICommunicator & comm = SingleArrayComm::instance() )

Computes averaged D-infinity flow accumulation with terrain perturbations.

This function estimates flow accumulation using the D∞ (D-infinity) method by perturbing the input elevation map multiple times with Perlin noise. For each sample, a noise field is added to the terrain, the flow accumulation is computed, and results are accumulated and averaged.

The perturbation introduces stochastic variability, which can help reduce numerical artifacts and improve robustness in flat or ambiguous flow regions.

Parameters
zInput elevation array.
talus_refReference talus angle (or slope threshold) used by the D∞ algorithm.
nsamplesNumber of noise-perturbed samples to average.
kwNoise frequency scaling factor.
seedBase random seed (incremented for each sample).
ampAmplitude of the noise perturbation.
bboxBounding box used for noise generation.
iterationsMaximum number of boundary exchange iterations across tiles (0 defaults to auto).
regionUvTile descriptor for tiled domain positioning.
commCommunicator for multi-tile synchronization.
Returns
Averaged flow accumulation array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {1.f, 1.f};
int seed = 1;
auto facc = hmap::flow_accumulation_dinf(z, talus.max());
// very high values are less relevant
hmap::clamp_max(facc, 200.f);
int nsamples = 20;
glm::vec2 kw = {4.f, 4.f};
float amp = 0.1f;
hmap::Array scaling = hmap::cubic_pulse(shape, nullptr, nullptr);
talus.max(),
nsamples,
kw,
seed,
amp,
&scaling);
hmap::clamp_max(facc_p, 200.f);
z.to_png("ex_flow_accumulation_dinf0.png", hmap::Cmap::TERRAIN, true);
facc.to_png("ex_flow_accumulation_dinf1.png", hmap::Cmap::HOT);
facc_p.to_png("ex_flow_accumulation_dinf2.png", hmap::Cmap::HOT);
}

Result

◆ flow_direction_d8()

Array hmap::flow_direction_d8 ( const Array & z)

Computes the flow direction from each cell to its downslope neighbor using the D8 model.

This function calculates the direction of flow for each cell in the heightmap using the D8 flow direction model [Greenlee1987]. The D8 model defines eight possible flow directions as follows:

5 6 7 4 . 0 3 2 1
* 
Parameters
zInput array representing the heightmap values.
Returns
Array An array where each cell contains the flow direction according to the D8 nomenclature.
See also
flow_accumulation_d8

◆ flow_direction_dinf()

std::vector< Array > hmap::flow_direction_dinf ( const Array & z,
float talus_ref )

Computes the flow direction and weights for each direction using the Multiple Flow Direction (MFD) model.

This function calculates the flow direction for each cell and provides the weight for each possible flow direction using the MFD model [Qin2007]. The flow-partition exponent is determined using a reference talus value. Smaller values of talus_ref will lead to thinner flow streams. The maximum talus value of the heightmap can be used as a reference.

Parameters
zInput array representing the heightmap values.
talus_refReference talus used to locally define the flow-partition exponent. Smaller values will result in thinner flow streams.
Returns
std::vector<Array> A vector of arrays, each containing the weights for flow directions at every cell.

◆ flow_direction_dinf_flat()

std::vector< float > hmap::flow_direction_dinf_flat ( const Array & z,
float talus_ref )

◆ flow_direction_dinf_angle()

Array hmap::flow_direction_dinf_angle ( const Array & z,
float talus_ref )

Computes the flow direction using the Multiple Flow Direction (MFD) model.

◆ flow_fixing()

Array hmap::flow_fixing ( const Array & z,
float riverbed_talus = 0.f,
int iterations = 5,
int prefilter_ir = 8,
bool carve_riverbed = true,
float merging_distance = 8.f,
const Array * p_noise_r = nullptr )

◆ flow_fixing_drainage_basin()

Array hmap::flow_fixing_drainage_basin ( const Array & z,
bool fast_approx = false,
float riverbed_talus = 1e-4f,
int iterations = 3,
bool carve_riverbed = false,
float talus_riverbank = 0.01f,
float merging_distance = 8.f,
std::uint32_t seed = 0,
float noise_strength = 0.f,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr )

Fixes flow paths and unwanted upslopes using a cell-based drainage basin tree network and elevation updates.

This function constructs a stream tree network on the heightmap, resolves internal depressions/lakes towards boundary outlets, and iteratively adjusts terrain elevations along upstream-downstream paths to guarantee unbroken flow while preserving realistic terrain slope gradients.

Parameters
zInput elevation array.
iterationsNumber of iterative tree-building and elevation update passes.
min_slopeMinimum allowed downslope gradient along flow paths.
max_slopeMaximum allowed slope gradient.
uplift_rateRate of elevation adjustment / uplift per unit response time.
m_expDrainage area exponent for response time calculations.
seedRandom seed for stochastic receiver variations.
noise_strengthStrength of random perturbation during receiver computation.
carve_riverbedWhether to apply riverbank carving and smoothing along altered paths.
talus_riverbankTalus value used when expanding and carving the riverbed.
merging_distanceDistance (in pixels) for blending modified flow paths.
p_noise_xOptional noise array for riverbank domain warping in X.
p_noise_yOptional noise array for riverbank domain warping in Y.
Returns
Array with unbroken flow paths.

◆ flow_fixing_mst()

Array hmap::flow_fixing_mst ( const Array & z,
float riverbed_talus = 0.f,
float elevation_ratio = 0.95f,
float distance_exponent = 2.f,
float upward_penalization = 0.1f,
float valley_affinity = 0.5f,
int prefilter_ir = 8,
float minimum_depth = 1e-4f,
bool carve_riverbed = true,
float merging_distance = 8.f,
RadialProfile radial_profile = RadialProfile::RP_SMOOTHSTEP_UPPER,
float radial_profile_parameter = 2.f,
const Array * p_noise_r = nullptr,
bool use_midpoint = false,
float offset_ratio = 0.2f )

Resolves flow sinks and unwanted upslopes using Dijkstra pathfinding and a Minimum Spanning Tree (MST) over sinks and boundary outlets.

This function identifies all flow sinks and boundary outlets, computes candidate optimal path connections via multi-source Dijkstra search, constructs a Minimum Spanning Forest (Kruskal's algorithm) guaranteeing that each sink connects to an outlet through the lowest-effort saddle pass, and carves monotonic riverbeds along the MST paths using continuous trench profiles.

Parameters
zInput elevation array.
riverbed_talusMinimum talus (slope) along carved riverbeds.
elevation_ratioBalance factor between elevation level and slope in Dijkstra cost.
distance_exponentExponent applied to elevation differences in Dijkstra cost.
upward_penalizationPenalty factor for uphill moves in Dijkstra search.
valley_affinityWeight for valley/concavity affinity in cost.
prefilter_irRadius of Gaussian/cpulse prefilter applied before sink detection.
minimum_depthMinimum incision depth below initial terrain elevation.
carve_riverbedWhether to apply riverbank carving and smoothing along altered paths.
merging_distanceDistance (in pixels) for blending modified flow paths.
radial_profileRadial profile cross-section for trench carving.
use_midpointWhether to use midpoint displacement pathfinding instead of classical Dijkstra.
offset_ratioMidpoint displacement amplitude ratio.
Returns
Array with unbroken flow paths.

◆ flow_fixing_mst_paths() [1/2]

std::vector< Path > hmap::flow_fixing_mst_paths ( const TerrainTriMesh & mesh,
float riverbed_talus = 0.f,
float elevation_ratio = 0.95f,
float distance_exponent = 2.f,
float upward_penalization = 0.1f,
float minimum_depth = 1e-4f )

Computes river flow paths resolving depressions via Minimum Spanning Tree (MST) on a triangular terrain mesh.

Sinks are identified as local minima on the mesh (excluding boundary vertices). Multi-source Dijkstra expansion computes saddle passes between sinks and the boundary outlet, Kruskal's MST establishes optimal connectivity, and directed paths are reconstructed with monotonic downstream elevation profiles.

Parameters
meshInput triangular terrain mesh.
riverbed_talusMinimum talus (slope) along resolved paths.
elevation_ratioWeight for absolute elevation in Dijkstra step cost.
distance_exponentExponent applied to upward elevation changes.
upward_penalizationPenalty factor for uphill moves.
minimum_depthMinimum incision depth below mesh vertex elevations.
Returns
Vector of resolved flow paths (trenchable Path objects).

◆ flow_fixing_mst_paths() [2/2]

std::vector< Path > hmap::flow_fixing_mst_paths ( const Array & z,
size_t control_points_count = 2048,
std::uint32_t seed = 0,
float riverbed_talus = 0.f,
float elevation_ratio = 0.95f,
float distance_exponent = 2.f,
float upward_penalization = 0.1f,
float minimum_depth = 1e-4f )

Computes river flow paths resolving depressions via Minimum Spanning Tree (MST) on a triangular mesh generated from a heightmap.

Generates a jittered triangular mesh from the heightmap, solves the MST flow graph, and extracts a set of trenchable Path objects.

Parameters
zInput elevation array.
control_points_countNumber of mesh control vertices sampled.
seedRandom seed for vertex distribution.
riverbed_talusMinimum talus (slope) along resolved paths.
elevation_ratioWeight for absolute elevation in Dijkstra step cost.
distance_exponentExponent applied to upward elevation changes.
upward_penalizationPenalty factor for uphill moves.
minimum_depthMinimum incision depth below terrain elevation.
Returns
Vector of resolved flow paths (trenchable Path objects).

◆ flow_fixing_mst_triangulated()

Array hmap::flow_fixing_mst_triangulated ( const Array & z,
size_t control_points_count = 2048,
std::uint32_t seed = 0,
float riverbed_talus = 0.f,
float elevation_ratio = 0.95f,
float distance_exponent = 2.f,
float upward_penalization = 0.1f,
float minimum_depth = 1e-4f,
float merging_distance = 8.f,
RadialProfile radial_profile = RadialProfile::RP_SMOOTHSTEP_UPPER,
float radial_profile_parameter = 2.f,
const Array * p_noise_r = nullptr )

Resolves flow sinks on a heightmap by computing an MST on a triangular mesh and carving the resulting river paths with trenching.

Parameters
zInput elevation array.
control_points_countNumber of mesh control vertices sampled.
seedRandom seed for vertex distribution.
riverbed_talusMinimum talus (slope) along carved riverbeds.
elevation_ratioWeight for absolute elevation in Dijkstra step cost.
distance_exponentExponent applied to upward elevation changes.
upward_penalizationPenalty factor for uphill moves.
minimum_depthMinimum incision depth below terrain elevation.
merging_distanceTrench width in pixels.
radial_profileRadial profile cross-section for trench carving.
radial_profile_parameterParameter for radial profile shaping.
p_noise_rOptional noise array for radial trench perturbation.
Returns
Carved elevation array with unbroken flow paths.

◆ flow_stream() [1/3]

Path hmap::flow_stream ( const Array & z,
const glm::ivec2 ij_start,
const float elevation_ratio = 0.5f,
const float distance_exponent = 2.f,
const float upward_penalization = 100.f,
const std::vector< Path > & existing_streams = {},
const int valley_radius = 2,
const float valley_factor = 0.35f,
const bool truncate_at_intersection = false )

Computes the optimal flow path from a starting point to the boundary of a given elevation array.

This function finds the flow path on a grid represented by the input array z, starting from the given point ij_start. It identifies the best path to the boundary, minimizing upward elevation penalties while accounting for distance and elevation factors.

Parameters
zThe input 2D array representing elevation values.
ij_startThe starting point as a 2D vector of indices (i, j) within the array.
elevation_ratioWeight for elevation difference in the cost function (default: 0.5).
distance_exponentExponent for the distance term in the cost function (default: 2.0).
upward_penalizationPenalty factor for upward elevation changes (default: 100.0).
existing_streamsExisting flow streams to favor merging with (default: {}).
valley_radiusRadius around existing stream cells to apply depression (default: 2).
valley_factorAttenuation factor per distance unit in valley depression (default: 0.35).
truncate_at_intersectionTruncate path at first intersection with an existing stream (default: false).
Returns
A Path object representing the optimal flow path with normalized x and y coordinates and corresponding elevations.

The output path consists of:

  • Normalized x-coordinates along the path.
  • Normalized y-coordinates along the path.
  • Elevation values corresponding to each point on the path.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
// shape = {1024, 1024};
glm::vec2 kw = {4.f, 4.f};
int seed = 1;
// base terrain with Perlin noise
// z = hmap::bulkify(z, hmap::PrimitiveType::PRIM_SMOOTH_COSINE, 1.f);
z += hmap::circus(shape);
// generate triangular terrain mesh from heightmap
// multiple starting points across the slopes of the valley head
std::vector<glm::vec2> start_points = {
{0.39f, 0.78f},
{0.39f, 0.31f},
{0.31f, 0.39f},
{0.35f, 0.43f},
{0.27f, 0.49f},
{0.27f, 0.59f},
{0.24f, 0.67f},
{0.69f, 0.63f},
{0.61f, 0.82f},
{0.40f, 0.45f},
{0.50f, 0.70f},
};
std::vector<hmap::Path> streams;
for (const auto &start : start_points)
{
start,
0.95f,
2.f,
100.f,
true,
streams,
0.02f,
0.4f,
true);
if (!stream.empty()) streams.push_back(stream);
}
// convert merged streams into a connected Graph
hmap::Graph stream_graph = hmap::hydrology_paths_to_graph(streams, 1e-3f);
// enforce strict monotonic downflow along all stream branches
stream_graph.enforce_downhill_elevation(0.01f);
// visualize graph on an empty grid
glm::vec4 bbox(0.f, 1.f, 0.f, 1.f);
hmap::Array z_graph(shape, 0.f);
stream_graph.to_array(z_graph,
hmap::BBox2D(bbox.x, bbox.y, bbox.z, bbox.w),
false);
// carve river network into terrain with expand_talus and SDF blending
hmap::Array z_carved = z;
hmap::Array river_mask;
float talus = 0.5f / float(shape.x);
float outlet_width = 0.05f;
float headwater_width = 0.001f;
float depth = 0.1f;
stream_graph,
talus,
outlet_width,
headwater_width,
/* width_exponent */ 0.5f,
depth,
/* depth_exponent */ 0.3f,
seed,
/* talus_noise_ratio */ 0.05f,
2.0f,
&river_mask);
hmap::export_banner_png("ex_flow_stream.png",
{z, z_graph, z_carved},
true);
}
bool empty() const
Check whether the cloud has no points.
Definition cloud.cpp:606
Graph class, to manipulate graphs in 2D.
Definition graph.hpp:70
void to_array(Array &array, const BBox2D &bbox, bool color_by_edge_weight=true) const
Project the graph to an array and optionally color by edge weight.
Definition graph.cpp:902
void enforce_downhill_elevation(float min_slope=0.001f)
Enforce monotonic downhill elevations on all graph nodes.
Definition graph.cpp:520
Triangle mesh representation of a terrain surface.
Definition terrain_tri_mesh.hpp:32
Graph hydrology_paths_to_graph(const std::vector< Path > &paths, float snap_tolerance=1e-4f)
Convert a collection of hydrology flow paths into a connected Graph.
Definition hydrology_paths_to_graph.cpp:22
TerrainTriMesh generate_terrain_tri_mesh_from_heightmap_random(const Array &z, int control_points_count, std::uint32_t seed, const UvTile &region=UvTile::unit(), ICommunicator *p_comm=nullptr)
Generate a random terrain mesh from a heightmap tile.
Definition generate_terrain_tri_mesh_from_heightmap.cpp:51
@ RP_SMOOTHSTEP_UPPER
Definition profiles.hpp:56
Path flow_stream(const Array &z, const glm::ivec2 ij_start, const float elevation_ratio=0.5f, const float distance_exponent=2.f, const float upward_penalization=100.f, const std::vector< Path > &existing_streams={}, const int valley_radius=2, const float valley_factor=0.35f, const bool truncate_at_intersection=false)
Computes the optimal flow path from a starting point to the boundary of a given elevation array.
Definition flow_stream.cpp:26
void carve_river(Array &z, const Graph &graph, float talus, float outlet_width, float headwater_width=0.f, float width_exponent=0.5f, float depth=0.05f, float depth_exponent=0.3f, std::uint32_t seed=0, float talus_noise_ratio=0.f, RadialProfile radial_profile=RadialProfile::RP_SMOOTHSTEP_UPPER, float radial_profile_parameter=2.f, Array *p_river_mask=nullptr, const UvRect &uv_rect=UvRect::unit())
Carves a continuous river network into a heightmap along a directed flow Graph.
Definition carve_river.cpp:25
Array circus(glm::ivec2 shape, float radius=0.4f, float angle=0.f, float exit_width=0.35f, float exit_depth=0.f, float center_depth=0.1f, float ridge_height=1.f, float ridge_width=0.15f, float outer_falloff=2.f, const Array *p_noise_r=nullptr, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit(), Array *p_mask=nullptr)
Generate a procedural circus (glacial cirque / amphitheatre basin) heightmap.
Definition circus.cpp:17

Result

◆ flow_stream() [2/3]

Path hmap::flow_stream ( const TerrainTriMesh & mesh,
size_t start_vertex_index,
float elevation_ratio = 0.5f,
float distance_exponent = 2.f,
float upward_penalization = 100.f,
bool favor_domain_center = false,
const std::vector< Path > & existing_streams = {},
float valley_radius = 0.02f,
float valley_factor = 0.35f,
bool truncate_at_intersection = false )

Computes the optimal flow path from a starting vertex to the boundary of a terrain triangular mesh.

Parameters
meshInput triangular terrain mesh.
start_vertex_indexIndex of the starting vertex.
elevation_ratioWeight for elevation difference in the cost function (default: 0.5).
distance_exponentExponent for the distance/elevation term (default: 2.0).
upward_penalizationPenalty factor for upward elevation changes (default: 100.0).
favor_domain_centerFavor passing through the center of the domain (default: false).
existing_streamsExisting flow streams to favor merging with (default: {}).
valley_radiusRadius around existing stream cells to apply attraction (default: 0.02).
valley_factorAttenuation factor per distance unit in valley attraction (default: 0.35).
truncate_at_intersectionTruncate path at first intersection with an existing stream (default: false).
Returns
A Path object representing the optimal flow path.

◆ flow_stream() [3/3]

Path hmap::flow_stream ( const TerrainTriMesh & mesh,
glm::vec2 xy_start,
float elevation_ratio = 0.5f,
float distance_exponent = 2.f,
float upward_penalization = 100.f,
bool favor_domain_center = false,
const std::vector< Path > & existing_streams = {},
float valley_radius = 0.02f,
float valley_factor = 0.35f,
bool truncate_at_intersection = false )

Computes the optimal flow path from starting 2D coordinates to the boundary of a terrain triangular mesh.

Parameters
meshInput triangular terrain mesh.
xy_startStarting coordinates (x, y) in [0, 1].
elevation_ratioWeight for elevation difference in the cost function (default: 0.5).
distance_exponentExponent for the distance/elevation term (default: 2.0).
upward_penalizationPenalty factor for upward elevation changes (default: 100.0).
favor_domain_centerFavor passing through the center of the domain (default: false).
existing_streamsExisting flow streams to favor merging with (default: {}).
valley_radiusRadius around existing stream cells to apply attraction (default: 0.02).
valley_factorAttenuation factor per distance unit in valley attraction (default: 0.35).
truncate_at_intersectionTruncate path at first intersection with an existing stream (default: false).
Returns
A Path object representing the optimal flow path.

◆ generate_riverbed()

Array hmap::generate_riverbed ( const Path & path,
glm::ivec2 shape,
const UvRect & uv_rect = UvRect::unit(),
bool bezier_smoothing = false,
float depth_start = 0.01f,
float depth_end = 1.f,
float slope_start = 64.f,
float slope_end = 32.f,
float shape_exponent_start = 1.f,
float shape_exponent_end = 10.f,
float k_smoothing = 0.5f,
int post_filter_ir = 0,
Array * p_noise_x = nullptr,
Array * p_noise_y = nullptr,
Array * p_noise_r = nullptr )

Generates a 2D array representing a riverbed based on a specified path.

This function calculates a scalar depth field (dz) for a riverbed shape using a path, which can optionally be smoothed with Bezier curves. It supports noise perturbation and post-filtering to adjust the riverbed's features.

Parameters
pathThe input path defining the riverbed's trajectory.
shapeThe dimensions of the output array (width, height).
bboxThe bounding box for the output grid in world coordinates.
bezier_smoothingFlag to enable or disable Bezier smoothing of the path.
depth_startThe depth at the start of the riverbed.
depth_endThe depth at the end of the riverbed.
slope_startThe slope multiplier at the start of the riverbed.
slope_endThe slope multiplier at the end of the riverbed.
shape_exponent_startThe shape exponent at the start of the riverbed.
shape_exponent_endThe shape exponent at the end of the riverbed.
k_smoothingThe smoothing factor for the riverbed shape adjustments.
post_filter_irThe radius of the post-filtering operation for smoothing the output.
p_noise_xOptional pointer to a noise array for perturbing the x-coordinates.
p_noise_yOptional pointer to a noise array for perturbing the y-coordinates.
p_noise_rOptional pointer to a noise array for perturbing the radial function.
Returns
A 2D array representing the calculated riverbed depth field.
Note
The function requires the path to have at least two points. If the path has fewer points, an empty array is returned with the given shape.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {4.f, 4.f};
int seed = 1;
shape,
kw,
seed,
8,
0.f);
hmap::remap(noise);
// base path
hmap::BBox2D bbox = {1.f, 2.f, -0.5f, 0.5f};
hmap::Path path = hmap::Path(4, seed, hmap::BBox2D(1.2f, 1.8f, -0.3f, 0.3f));
path.reorder_nns();
path = hmap::fractalize(path, 8, seed);
path.set_values_from_array(noise, bbox);
auto zp = hmap::Array(shape);
path.to_array(zp, bbox);
shape,
hmap::UvRect(1.f, 2.f, -0.5f, 0.5f));
dz.to_png_grayscale("out.png", CV_16U);
dz.to_png("out1.png", hmap::Cmap::JET);
hmap::export_banner_png("ex_generate_riverbed.png",
{zp, dz},
}
void set_values_from_array(const Array &array, const BBox2D &bbox=BBox2D{})
Set the values of the cloud points using values from an underlying array.
Definition cloud.cpp:378
Array generate_riverbed(const Path &path, glm::ivec2 shape, const UvRect &uv_rect=UvRect::unit(), bool bezier_smoothing=false, float depth_start=0.01f, float depth_end=1.f, float slope_start=64.f, float slope_end=32.f, float shape_exponent_start=1.f, float shape_exponent_end=10.f, float k_smoothing=0.5f, int post_filter_ir=0, Array *p_noise_x=nullptr, Array *p_noise_y=nullptr, Array *p_noise_r=nullptr)
Generates a 2D array representing a riverbed based on a specified path.
Definition generate_riverbed.cpp:20

Result

◆ hydrology_paths_to_graph()

Graph hmap::hydrology_paths_to_graph ( const std::vector< Path > & paths,
float snap_tolerance = 1e-4f )

Convert a collection of hydrology flow paths into a connected Graph.

Path points within snap_tolerance Euclidean distance are welded into shared nodes, connecting tributaries and main river channels while preserving only the active river network (avoiding dense background meshes).

Parameters
pathsVector of flow paths.
snap_toleranceSpatial distance tolerance for snapping vertices.
Returns
Connected Graph containing only the river network.

◆ merge_water_depths()

Array hmap::merge_water_depths ( const Array & depth1,
const Array & depth2,
float k_smooth = 0.f )

Merge two water depth fields.

Computes the maximum (or smoothed maximum) of two depth arrays.

Parameters
depth1First water depth array.
depth2Second water depth array.
k_smoothSmoothing parameter (0 = sharp max).
Returns
Combined water depth array.

◆ snow_melting_map()

Array hmap::snow_melting_map ( const Array & z,
float melt_start_elevation = 0.f,
float melt_end_elevation = 0.5f,
float elevation_strength = 1.f,
float elevation_exp = 1.f,
float sun_azimuth = 0.f,
float sun_zenith = 60.f,
float aspect_strength = 0.f,
float slope_exp = 1.f,
float slope_strength = 0.f )

Generate a spatial snow melting map from terrain features.

Computes a melting factor in [0,1] from elevation, slope, and sun exposure. Low elevations, steep slopes, and sun-facing orientations increase melting.

Parameters
zInput terrain elevation.
melt_start_elevationElevation where melting starts (no melt below).
melt_end_elevationElevation where melting reaches full effect.
elevation_expExponent controlling elevation melt falloff.
sun_azimuthSun azimuth angle in degrees.
sun_zenithSun zenith angle in degrees.
aspect_strengthWeight of sun exposure contribution.
slope_expExponent controlling slope sensitivity.
slope_strengthWeight of slope contribution.
Returns
Melting map with values in [0,1], where higher values indicate stronger melting.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {4.f, 4.f};
int seed = 2;
// parameters
const float talus_repose = 2.5f / shape.x;
const int iterations = 500;
const float amount = 1e-1f;
const hmap::Array talus(shape, talus_repose);
// no-melting
z,
amount,
hmap::Array(shape, 1.f), // fall_map
hmap::Array(shape, 0.f), // melting_map
talus,
iterations);
// with melting
z,
amount,
hmap::Array(shape, 1.f), // fall_map
melt_map,
talus,
iterations);
z.dump("z0.png");
(z + snow_depth1).dump("z.png");
snow_depth1.dump("depth.png");
hmap::export_banner_png("ex_snow_simulation.png",
{z, z + snow_depth0, melt_map, z + snow_depth1},
}
Array snow_simulation(const Array &z, float snow_depth, const Array &fall_map, const Array &melting_map, const Array &talus, int iterations, float dt=0.5f, float fall_iterations_ratio=1.f, float k_snow=0.5f, float k_visc=0.1f, float k_melt_factor=0.8f, float k_depth_ratio=1.f, float k_depth_slope_ratio=1.f, float k_creep=0.1f, bool post_filter=true, float thermal_talus_ratio=0.2f, bool outflow_boundaries=true, float clamp_smin=0.f, bool rebase_snow_depth_to_zero=true, int sync_interval=0, const UvTile &region=UvTile::dummy(), ICommunicator &comm=SingleArrayComm::instance())
Simulate snow accumulation and redistribution over a terrain.
Definition snow_simulation.cpp:92
@ PRIM_CUBIC_PULSE
Definition functions.hpp:28
Array snow_melting_map(const Array &z, float melt_start_elevation=0.f, float melt_end_elevation=0.5f, float elevation_strength=1.f, float elevation_exp=1.f, float sun_azimuth=0.f, float sun_zenith=60.f, float aspect_strength=0.f, float slope_exp=1.f, float slope_strength=0.f)
Generate a spatial snow melting map from terrain features.
Definition snow_simulation.cpp:29

Result

◆ water_depth_from_mask()

Array hmap::water_depth_from_mask ( const Array & z,
const Array & mask,
float mask_threshold = 0.f,
int iterations_max = 10000,
float tolerance = 1e-2f )

Compute water depth over a masked terrain using harmonic interpolation.

This function estimates the water depth above a terrain surface by solving a Laplace equation on the domain defined by mask. The solution is obtained using the harmonic interpolation method with Successive Over-Relaxation (SOR). The resulting water depth is given by the difference between the interpolated surface and the original terrain elevation.

Parameters
zInput 2D array representing the terrain elevations (height field).
maskMask array of the same shape as z. Values greater than mask_threshold define regions where water can accumulate, while lower values represent boundaries or fixed terrain.
mask_thresholdThreshold used to convert mask into a binary field (0 or 1) for identifying water/terrain boundaries.
iterations_maxMaximum number of SOR iterations used in the harmonic interpolation.
toleranceConvergence criterion: the algorithm stops if the maximum absolute update between iterations is less than this value.
Returns
A 2D array containing the computed water depth at each grid cell. Depth values are non-negative where water is present and zero where the mask indicates no water.
See also
harmonic_interpolation

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
hmap::Array mask = hmap::select_rivers(z, 1.f / shape.x, 50.f);
hmap::remap(mask);
float mask_threshold = 0.1f; // higher values decrease water extent
mask,
mask_threshold);
hmap::export_banner_png("ex_water_depth_from_mask.png",
{z, mask, water_depth, z + water_depth},
}
Array select_rivers(const Array &array, float talus_ref, float clipping_ratio)
Return an array filled with a criterion based on the occurence of a river bed.
Definition selector.cpp:404
Array water_depth_from_mask(const Array &z, const Array &mask, float mask_threshold=0.f, int iterations_max=10000, float tolerance=1e-2f)
Compute water depth over a masked terrain using harmonic interpolation.
Definition water_depth.cpp:78

Result

◆ water_depth_dry_out()

void hmap::water_depth_dry_out ( Array & water_depth,
float dry_out_ratio = 0.5f,
const Array * p_mask = nullptr,
float depth_max = std::numeric_limits<float>::max() )

Apply a drying factor to a water depth field.

This function reduces the water depth values in-place by multiplying them by a given dry_out_ratio. If a mask is provided, the drying is applied only where the mask is non-zero, allowing selective drying of specific regions.

Parameters
water_depthReference to the 2D array containing water depth values. The array is modified in-place.
dry_out_ratioMultiplicative factor (typically between 0 and 1) used to scale down the water depth. A value of 1 leaves the depth unchanged, while 0 removes all water.
p_maskOptional pointer to a mask array of the same shape as water_depth. Drying is applied only where the mask has non-zero values. If nullptr, the factor is applied uniformly to all cells.
depth_maxMaximum water depth, computed automatically by default.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
hmap::Array water_depth = hmap::flooding_lake_system(z, 500);
float dry_out_ratio = 0.5f;
auto w1 = water_depth;
hmap::water_depth_dry_out(w1, dry_out_ratio);
// remove water at high elevations
dry_out_ratio = 1.f;
auto w2 = water_depth;
auto mask = 1.f - z;
hmap::water_depth_dry_out(w2, dry_out_ratio, &mask);
hmap::export_banner_png("ex_water_depth_dry_out.png",
{z, z + water_depth, z + w1, z + w2},
true);
}
void water_depth_dry_out(Array &water_depth, float dry_out_ratio=0.5f, const Array *p_mask=nullptr, float depth_max=std::numeric_limits< float >::max())
Apply a drying factor to a water depth field.
Definition water_depth.cpp:47

Result

◆ water_depth_increase()

Array hmap::water_depth_increase ( const Array & water_depth,
const Array & z,
float additional_depth )

Simulates a local increase in water depth without global reflooding.

This function propagates an additional water depth over a terrain elevation map (z), starting only from cells that already contain water in the input water_depth array. The propagation is restricted to neighboring cells of higher elevation (8-connectivity), preventing the formation of entirely new flooded basins disconnected from the original water region.

Unlike water_depth_increase_with_flooding(), this function does not perform a full flooding simulation of the domain. It is primarily intended for expanding or softening an existing water mask slightly beyond the current shoreline.

Parameters
water_depthInput array representing the initial water depth.
zElevation array corresponding to the same grid as water_depth.
additional_depthAdditional water depth to propagate from the existing water region.
Returns
An Array containing the updated water depth after local propagation.
Note
Water spreads only upward toward neighboring cells with higher elevation. Existing disconnected dry basins are not flooded.
This function is useful for generating extended shoreline masks, erosion influence regions, or visually expanding water boundaries without performing a physically complete flooding simulation.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {6.f, 6.f};
int seed = 1;
float additional_depth = 0.05f;
hmap::Array water_depth0 = hmap::flooding_uniform_level(z, 0.3f);
// hmap::Array water_depth0 = hmap::flooding_lake_system(z);
hmap::Array water_depth1 = hmap::water_depth_increase(water_depth0,
z,
additional_depth);
hmap::export_banner_png("ex_water_depth_increase.png",
{z, z + water_depth0, z + water_depth1},
true);
}
Array water_depth_increase(const Array &water_depth, const Array &z, float additional_depth)
Simulates a local increase in water depth without global reflooding.
Definition water_depth.cpp:100

Result

◆ water_depth_increase_with_flooding()

Array hmap::water_depth_increase_with_flooding ( const Array & water_depth,
const Array & z,
float additional_depth )

Simulates a physical rise in water level with full domain flooding.

This function increases the water level by additional_depth and recomputes flooding over the terrain elevation map (z). Unlike water_depth_increase(), the propagation is not restricted to the vicinity of the original water region: water may spread through connected terrain and flood previously dry areas if they become reachable under the new water level.

The simulation behaves more like a physical flooding process where rising water can overflow barriers, connect basins, and eventually inundate large portions of the domain depending on terrain topology.

Parameters
water_depthInput array representing the initial water depth.
zElevation array corresponding to the same grid as water_depth.
additional_depthAdditional water depth used to raise the global water level.
Returns
An Array containing the updated flooded state after recomputing water propagation.
Note
Flood propagation may extend far beyond the original water mask and can potentially inundate the entire connected terrain domain.
This function is more physically plausible than water_depth_increase(), and is suitable for terrain flooding simulations, overflow analysis, or hydrological studies.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {6.f, 6.f};
int seed = 1;
float additional_depth = 0.05f;
hmap::Array water_depth0 = hmap::flooding_uniform_level(z, 0.3f);
// hmap::Array water_depth0 = hmap::flooding_lake_system(z);
hmap::Array water_depth1 = hmap::water_depth_increase(water_depth0,
z,
additional_depth);
hmap::export_banner_png("ex_water_depth_increase.png",
{z, z + water_depth0, z + water_depth1},
true);
}

Result

◆ water_frontier_curvature()

Array hmap::water_frontier_curvature ( const Array & water_depth,
int prefilter_ir,
bool extend_values_from_interface = false )

Compute the curvature of the water interface from a signed distance field.

The interface curvature is evaluated from the level set built from the water depth mask. Optionally, curvature values can be extended away from the interface using closest-point propagation.

Parameters
water_depthWater depth field.
prefilter_irPrefilter radius used for curvature evaluation.
extend_values_from_interfaceExtend interface curvature values to the full domain using closest boundary points.
Returns
Curvature field.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {4.f, 4.f};
int seed = 1;
hmap::Array water_depth = hmap::flooding_uniform_level(z, 0.5f);
int prefilter_ir = 16;
hmap::Array wc0 = hmap::water_frontier_curvature(water_depth, prefilter_ir);
prefilter_ir);
hmap::export_banner_png("ex_water_frontier_curvature.png",
{z, water_depth, wc0, wc1},
false,
true);
}
Array water_frontier_curvature(const Array &water_depth, int prefilter_ir, bool extend_values_from_interface=false)
See hmap::water_frontier_curvature.
Definition water_depth.cpp:438
Array water_frontier_curvature(const Array &water_depth, int prefilter_ir, bool extend_values_from_interface=false)
Compute the curvature of the water interface from a signed distance field.
Definition water_depth.cpp:304

Result

◆ water_mask() [1/2]

Array hmap::water_mask ( const Array & water_depth)

Generates a binary mask representing water presence.

This version of the function converts the given water depth array into a binary mask where non-zero values indicate the presence of water.

Parameters
water_depthInput array representing water depth values.
Returns
A binary Array where each cell is 1 if water is present, 0 otherwise.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
hmap::Array water_depth = hmap::flooding_uniform_level(z, 0.3f);
// hmap::Array water_depth = hmap::flooding_lake_system(z, 500, 1e-4f);
hmap::Array mask0 = hmap::water_mask(water_depth);
hmap::Array mask1 = hmap::water_mask(water_depth, z, 0.075f);
hmap::export_banner_png("ex_water_mask.png",
{z, z + water_depth, mask0, mask1},
}
Array water_mask(const Array &water_depth)
Generates a binary mask representing water presence.
Definition water_depth.cpp:336

Result

◆ water_mask() [2/2]

Array hmap::water_mask ( const Array & water_depth,
const Array & z,
float additional_depth )

Computes a gradient-based water mask using an extended water depth model.

This function computes a smooth mask indicating regions that would be newly flooded when the water depth is artificially increased by a specified additional amount. It uses water_depth_increase() to simulate the spread of water over the terrain.

Parameters
water_depthInput array representing the current water depth.
zElevation array corresponding to the same grid as water_depth.
additional_depthThe amount of additional water depth to simulate.
Returns
An Array representing the normalized water extension mask, where values range from 0 to 1.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
hmap::Array water_depth = hmap::flooding_uniform_level(z, 0.3f);
// hmap::Array water_depth = hmap::flooding_lake_system(z, 500, 1e-4f);
hmap::Array mask0 = hmap::water_mask(water_depth);
hmap::Array mask1 = hmap::water_mask(water_depth, z, 0.075f);
hmap::export_banner_png("ex_water_mask.png",
{z, z + water_depth, mask0, mask1},
}

Result

◆ assert_almost_equal()

bool hmap::assert_almost_equal ( const Array & a,
const Array & b,
float tolerance = 1e-6f,
const std::string & fname = "",
AssertResults * p_results = nullptr )

◆ is_subset()

bool hmap::is_subset ( const Array & a,
const Array & b )

◆ print_array()

void hmap::print_array ( const Array & arr,
bool show_coords = false,
int width = 6,
int precision = 2 )

◆ dump_visual_check()

void hmap::dump_visual_check ( const Array & array,
const std::string & fname = "check.png" )

◆ float_key()

uint32_t hmap::float_key ( float f)
inline

◆ key_float()

float hmap::key_float ( uint32_t k)
inline

◆ next_up()

float hmap::next_up ( float f)
inline

◆ add_filename_suffix()

std::filesystem::path hmap::add_filename_suffix ( const std::filesystem::path & file_path,
const std::string & suffix )

Adds a suffix to the filename of a given file path.

This function appends a given suffix to the stem (base name without extension) of a file while preserving the original directory and file extension.

Parameters
file_pathThe original file path.
suffixThe suffix to append to the filename.
Returns
A new std::filesystem::path with the modified filename.
Note
If the input file has no extension, the suffix is added directly to the filename.

Example

std::filesystem::path path = "example.txt";
std::filesystem::path new_path = add_filename_suffix(path, "_backup");
std::cout << new_path; // Outputs "example_backup.txt"
std::filesystem::path add_filename_suffix(const std::filesystem::path &file_path, const std::string &suffix)
Adds a suffix to the filename of a given file path.
Definition string_utils.cpp:13

◆ make_unique_temp_dir()

std::filesystem::path hmap::make_unique_temp_dir ( const std::string & prefix)

Create a unique temporary directory.

Creates and returns a unique directory inside the system temporary directory using the given prefix.

Parameters
prefixDirectory name prefix.
Returns
Path to the created temporary directory.
Note
The caller is responsible for deleting the directory.

◆ zfill()

std::string hmap::zfill ( const std::string & str,
int n_zero )

Pads the beginning of a string with zeros until it reaches a specified length.

This function prepends '0' characters to the input string str so that the resulting string has at least n_zero characters. If str is already equal to or longer than n_zero, it is returned unchanged.

Parameters
strThe input string to pad.
n_zeroThe minimum total length of the resulting string after padding.
Returns
A new string padded with leading zeros to reach the specified length.

Example

zfill("42", 5); // returns "00042"
zfill("12345", 5); // returns "12345"
std::string zfill(const std::string &str, int n_zero)
Pads the beginning of a string with zeros until it reaches a specified length.
Definition string_utils.cpp:43

◆ validate_shape()

bool hmap::validate_shape ( glm::ivec2 shape,
const std::source_location & loc = std::source_location::current() )
inlinenodiscard

Validates that array dimensions are strictly positive.

Parameters
shapeDimensions {x, y} to check.
locSource location of the caller.
Returns
true if shape.x > 0 and shape.y > 0, false otherwise.

◆ validate_non_empty() [1/3]

bool hmap::validate_non_empty ( const Array & array,
const std::source_location & loc = std::source_location::current() )
inlinenodiscard

Validates that an array is initialized, non-empty, and has a consistent buffer size.

Parameters
arrayArray to check.
locSource location of the caller.
Returns
true if the array is non-empty and buffer size matches shape dimensions, false otherwise.

◆ validate_non_empty() [2/3]

template<typename T>
requires requires(const T &t) { { t.empty() } -> std::convertible_to<bool>; }
bool hmap::validate_non_empty ( const T & container,
std::string_view name = "Container",
const std::source_location & loc = std::source_location::current() )
inlinenodiscard

Validates that a container or object with an empty() method is not empty.

Parameters
containerContainer to check.
nameName or description of the container for logging.
locSource location of the caller.
Returns
true if container is not empty, false otherwise.

◆ validate_min_size()

template<typename T>
requires requires(const T &t) { { t.size() } -> std::convertible_to<size_t>; }
bool hmap::validate_min_size ( const T & container,
size_t min_size,
std::string_view name = "Container",
const std::source_location & loc = std::source_location::current() )
inlinenodiscard

Validates that a container has at least min_size elements.

Parameters
containerContainer to check.
min_sizeMinimum required number of elements.
nameName or description of the container for logging.
locSource location of the caller.
Returns
true if container has at least min_size elements, false otherwise.

◆ validate_same_shape() [1/4]

bool hmap::validate_same_shape ( const Array & a,
const Array & b,
const std::source_location & loc = std::source_location::current() )
inlinenodiscard

Validates that two arrays have identical shapes and buffer sizes.

Parameters
aFirst array.
bSecond array.
locSource location of the caller.
Returns
true if shapes and buffer sizes match, false otherwise.

◆ validate_same_shape() [2/4]

bool hmap::validate_same_shape ( glm::ivec2 shape,
const Array & b,
const std::source_location & loc = std::source_location::current() )
inlinenodiscard

Validates that an array has the expected 2D shape.

Parameters
shapeExpected shape {x, y}.
bArray to check.
locSource location of the caller.
Returns
true if b.shape matches shape and b is non-empty, false otherwise.

◆ validate_non_empty() [3/3]

bool hmap::validate_non_empty ( const Texture & tex,
int min_channels = 1,
const std::source_location & loc = std::source_location::current() )
inlinenodiscard

Validates that a Texture is initialized, non-empty, and has valid channel buffers.

Parameters
texTexture to check.
min_channelsMinimum required number of channels.
locSource location of the caller.
Returns
true if the Texture is non-empty and channels are valid, false otherwise.

◆ validate_channels()

bool hmap::validate_channels ( const Texture & tex,
int expected_channels,
const std::source_location & loc = std::source_location::current() )
inlinenodiscard

Validates exact channel count of a Texture.

Parameters
texTexture to check.
expected_channelsExact number of expected channels.
locSource location of the caller.
Returns
true if channel count matches, false otherwise.

◆ validate_same_shape() [3/4]

bool hmap::validate_same_shape ( const Texture & a,
const Texture & b,
const std::source_location & loc = std::source_location::current() )
inlinenodiscard

Validates that two Textures have matching 2D shapes.

Parameters
aFirst texture.
bSecond texture.
locSource location of the caller.
Returns
true if shapes match, false otherwise.

◆ validate_same_shape() [4/4]

bool hmap::validate_same_shape ( const Texture & tex,
const Array & arr,
const std::source_location & loc = std::source_location::current() )
inlinenodiscard

Validates that a Texture and an Array have matching 2D shapes.

Parameters
texTexture to check.
arrArray to check.
locSource location of the caller.
Returns
true if shapes match, false otherwise.

◆ validate_slice()

bool hmap::validate_slice ( const Array & array,
glm::ivec4 idx,
const std::source_location & loc = std::source_location::current() )
inlinenodiscard

Validates that a slice extent {i1, i2, j1, j2} is valid and within array boundaries.

Parameters
arrayTarget array.
idxSlice extents: {i1, i2, j1, j2}.
locSource location of the caller.
Returns
true if slice is valid and non-empty, false otherwise.

◆ validate_slice_for_array()

bool hmap::validate_slice_for_array ( const Array & dest,
glm::ivec4 idx,
const Array & src,
const std::source_location & loc = std::source_location::current() )
inlinenodiscard

Validates that a slice extent matches the dimensions of a source array.

Parameters
destDestination array.
idxSlice extents {i1, i2, j1, j2}.
srcSource array to assign into the slice.
locSource location of the caller.
Returns
true if slice is valid and matches src.shape, false otherwise.

◆ validate_not_zero()

bool hmap::validate_not_zero ( float value,
const std::source_location & loc = std::source_location::current() )
inlinenodiscard

Validates that a divisor value is not zero.

Parameters
valueDivisor value.
locSource location of the caller.
Returns
true if value != 0, false otherwise.

◆ validate_parameter_range()

bool hmap::validate_parameter_range ( glm::vec2 range,
float min_val,
float max_val,
std::string_view param_name = "Range",
const std::source_location & loc = std::source_location::current() )
inlinenodiscard

Validates that a 2D range vector {low, high} lies within [min_val, max_val] with low <= high.

Parameters
rangeRange vector {low, high}.
min_valMinimum allowed value.
max_valMaximum allowed value.
param_nameName or description of the range parameter for logging.
locSource location of the caller.
Returns
true if min_val <= range.x <= range.y <= max_val, false otherwise.

◆ validate_finite()

bool hmap::validate_finite ( const Array & array,
const std::source_location & loc = std::source_location::current() )
inlinenodiscard

Validates that all elements of an array are finite (not NaN or Inf).

Parameters
arrayArray to check.
locSource location of the caller.
Returns
true if all values are finite, false otherwise.

◆ validate_cmap()

bool hmap::validate_cmap ( int cmap,
const std::source_location & loc = std::source_location::current() )
inlinenodiscard

Validates that a colormap ID corresponds to a valid Cmap enum value.

Parameters
cmapColormap ID.
locSource location of the caller.
Returns
true if cmap is a valid Cmap enum value, false otherwise.

◆ bilinear_interp()

float hmap::bilinear_interp ( float f00,
float f10,
float f01,
float f11,
float u,
float v )
inlinenodiscardconstexprnoexcept

Compute the bilinear interpolated value from four input values.

This function calculates the interpolated value at a point within a grid using bilinear interpolation based on four surrounding values.

Parameters
f00Value at (u, v) = (0, 0).
f10Value at (u, v) = (1, 0).
f01Value at (u, v) = (0, 1).
f11Value at (u, v) = (1, 1).
uThe interpolation parameter in the x-direction, expected in [0, 1).
vThe interpolation parameter in the y-direction, expected in [0, 1).
Returns
float The bilinear interpolated value.

◆ bspline_weights()

void hmap::bspline_weights ( float t,
float w[4] )
inlinenoexcept

Compute uniform cubic B-spline weights for a fractional parameter in [0, 1).

Parameters
tFractional parameter in [0, 1).
wOutput array of 4 weights.

◆ cubic_interpolate()

float hmap::cubic_interpolate ( const float p[4],
float x )
inlinenodiscardconstexprnoexcept

◆ harmonic_interpolation() [1/2]

Array hmap::harmonic_interpolation ( const Array & array,
const Array & mask_fixed_values,
int iterations_max = 500,
float tolerance = 1e-5f,
float omega = 0.f,
int sync_interval = 0,
const UvTile & region = UvTile::unit(),
ICommunicator & comm = SingleArrayComm::instance() )

Perform harmonic interpolation on a 2D array using the Successive Over-Relaxation (SOR) method.

This function solves the discrete Laplace equation on a regular grid by iteratively updating the values of an input array. Values marked as fixed in the mask_fixed_values remain unchanged throughout the process. The algorithm stops when either the maximum number of iterations is reached or the change between successive iterations falls below the specified tolerance.

Parameters
arrayInput 2D array providing the initial guess for the solution.
mask_fixed_valuesMask of the same shape as array. Cells with a value greater than zero indicate fixed points that must remain unchanged during interpolation.
iterations_maxMaximum number of SOR iterations to perform.
toleranceConvergence criterion: the algorithm stops if the maximum absolute update between iterations is less than this value.
omegaRelaxation factor (1 < omega < 2 recommended). Values closer to 2 accelerate convergence, but overly large values may cause divergence.
Returns
A new 2D array containing the interpolated solution.
Note
  • The algorithm updates only the interior points (indices [1..nx-2, 1..ny-2]).
  • Cells where mask_fixed_values(i, j) > 0 remain unchanged.
  • A relaxation factor of 1 corresponds to the standard Jacobi/Gauss-Seidel update.

◆ harmonic_interpolation() [2/2]

Array hmap::harmonic_interpolation ( const Array & array,
const Array & mask_fixed_values,
const Array & dx,
const Array & dy,
int iterations_max = 500,
float tolerance = 1e-5f,
float omega = 0.f,
int sync_interval = 0,
const UvTile & region = UvTile::unit(),
ICommunicator & comm = SingleArrayComm::instance() )

Perform harmonic interpolation on a 2D array with 2D variable diffusion coefficients (Dx, Dy) using the Successive Over-Relaxation (SOR) method.

Solves the steady-state anisotropic diffusion equation:

\[\nabla \cdot (\mathbf{D} \nabla u) = \frac{\partial}{\partial x}\left(D_x \frac{\partial u}{\partial x}\right) + \frac{\partial}{\partial y}\left(D_y \frac{\partial u}{\partial y}\right) = 0 \]

Parameters
arrayInput 2D array providing the initial guess.
mask_fixed_valuesMask where values > 0 indicate fixed boundary constraints.
dxArray of diffusion coefficients in the x-direction.
dyArray of diffusion coefficients in the y-direction.
iterations_maxMaximum number of SOR iterations.
toleranceConvergence tolerance.
omegaRelaxation factor (0 = auto-computed optimal).
Returns
Interpolated array.

◆ interpolate2d()

Array hmap::interpolate2d ( glm::ivec2 shape,
const std::vector< float > & x,
const std::vector< float > & y,
const std::vector< float > & values,
InterpolationMethod2D interpolation_method,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
const UvRect & uv_rect = UvRect::unit() )

Generic 2D interpolation function.

This function performs interpolation on a 2D grid using the specified interpolation method. It can optionally apply noise and stretching to the input data before interpolation.

Parameters
shapeOutput array shape.
xx coordinates of the input values.
yy coordinates of the input values.
valuesInput values at (x, y).
interpolation_methodInterpolation method (see InterpolationMethod2D).
p_noise_xPointer to the input noise array in the x direction (optional).
p_noise_yPointer to the input noise array in the y direction (optional).
bboxDomain bounding box (default: {0.f, 1.f, 0.f, 1.f}).
Returns
Array Output array with interpolated values.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
// shape = {1024, 1024};
int seed = 0;
hmap::BBox2D bbox = {-1.f, 0.f, 0.5f, 1.5f};
hmap::UvRect uv_rect = {-1.f, 0.f, 0.5f, 1.5f};
hmap::Cloud cloud = hmap::Cloud(10, seed, bbox);
std::vector<float> x = cloud.get_x();
std::vector<float> y = cloud.get_y();
std::vector<float> values = cloud.get_values();
// reference, pointwise values
hmap::Array z0 = hmap::Array(shape);
cloud.to_array(z0, bbox);
// noise
shape,
{4.f, 4.f},
seed,
8,
0.f);
// nearest
hmap::Timer::Start("ITP2D_NEAREST");
shape,
x,
y,
values,
&dx,
&dx,
uv_rect);
hmap::Timer::Stop("ITP2D_NEAREST");
hmap::Timer::Start("ITP2D_DELAUNAY");
shape,
x,
y,
values,
&dx,
&dx,
uv_rect);
hmap::Timer::Stop("ITP2D_DELAUNAY");
hmap::Timer::Start("ITP2D_IDW");
x,
y,
values,
&dx,
&dx,
uv_rect);
hmap::Timer::Stop("ITP2D_IDW");
hmap::Timer::Start("ITP2D_GAUSSIAN");
shape,
x,
y,
values,
&dx,
&dx,
uv_rect);
hmap::Timer::Stop("ITP2D_GAUSSIAN");
hmap::Timer::Start("ITP2D_NNI");
x,
y,
values,
&dx,
&dx,
uv_rect);
hmap::Timer::Stop("ITP2D_NNI");
hmap::Timer::Start("ITP2D_CT");
shape,
x,
y,
values,
// hmap::InterpolationMethod2D::ITP2D_NNI,
nullptr,
nullptr,
uv_rect);
hmap::Timer::Stop("ITP2D_CT");
hmap::export_banner_png("ex_interpolate2d.png",
{z0, z1, z2, z3, z4, z5, z6},
}
void snap_points_to_bounding_box(const BBox2D &bbox=BBox2D{}, float tolerance_ratio=1.f)
Snap points to the bounding box edges and corners.
Definition cloud.cpp:683
static void Stop(const std::string &name)
Stops the timer for the specified event name.
Definition timer.cpp:59
static void Start(const std::string &name)
Starts a timer for the specified event name.
Definition timer.cpp:54
@ ITP2D_IDW
Inverse Distance Weighting.
Definition interpolate2d.hpp:46
@ ITP2D_DELAUNAY
Delaunay triangulation method for 2D interpolation.
Definition interpolate2d.hpp:44
@ ITP2D_NNI
Natural Neighbor Interpolation.
Definition interpolate2d.hpp:48
@ ITP2D_GAUSSIAN
Gaussian Distance Weighting.
Definition interpolate2d.hpp:47
@ ITP2D_NEAREST
Nearest point method for 2D interpolation.
Definition interpolate2d.hpp:45
Array interpolate2d(glm::ivec2 shape, const std::vector< float > &x, const std::vector< float > &y, const std::vector< float > &values, InterpolationMethod2D interpolation_method, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit())
Generic 2D interpolation function.
Definition interpolate2d.cpp:14
Array interpolate2d_delaunay_gradient(glm::ivec2 shape, const std::vector< float > &x, const std::vector< float > &y, const std::vector< float > &values, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit(), float fill_value=0.f, float gradient_scaling=1.f)
2D interpolation using a smoother version of the Delaunay triangulation method.
Definition interpolate2d_delaunay_gradient.cpp:14

Result

◆ interpolate2d_delaunay()

Array hmap::interpolate2d_delaunay ( glm::ivec2 shape,
const std::vector< float > & x,
const std::vector< float > & y,
const std::vector< float > & values,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
const UvRect & uv_rect = UvRect::unit(),
float fill_value = 0.f )

2D interpolation using the Delaunay triangulation method.

This function performs 2D interpolation by generating a Delaunay triangulation of the input points and interpolating the values within each triangle.

Parameters
shapeOutput array shape.
xx coordinates of the input values.
yy coordinates of the input values.
valuesInput values at (x, y).
p_noise_xPointer to the input noise array in the x direction (optional).
p_noise_yPointer to the input noise array in the y direction (optional).
bboxDomain bounding box (default: {0.f, 1.f, 0.f, 1.f}).
Returns
Array Output array with interpolated values.

◆ interpolate2d_delaunay_gradient()

Array hmap::interpolate2d_delaunay_gradient ( glm::ivec2 shape,
const std::vector< float > & x,
const std::vector< float > & y,
const std::vector< float > & values,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
const UvRect & uv_rect = UvRect::unit(),
float fill_value = 0.f,
float gradient_scaling = 1.f )

2D interpolation using a smoother version of the Delaunay triangulation method.

◆ interpolate2d_gaussian()

Array hmap::interpolate2d_gaussian ( glm::ivec2 shape,
const std::vector< float > & x,
const std::vector< float > & y,
const std::vector< float > & values,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
const UvRect & uv_rect = UvRect::unit(),
float sigma = 0.05f,
float radius = 0.f )

2D interpolation using the Gaussian kernel method.

◆ interpolate2d_idw()

Array hmap::interpolate2d_idw ( glm::ivec2 shape,
const std::vector< float > & x,
const std::vector< float > & y,
const std::vector< float > & values,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
const UvRect & uv_rect = UvRect::unit(),
float distance_exp = 2.f,
float radius = 0.f )

2D interpolation using the IDW method.

◆ interpolate2d_nearest()

Array hmap::interpolate2d_nearest ( glm::ivec2 shape,
const std::vector< float > & x,
const std::vector< float > & y,
const std::vector< float > & values,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
const UvRect & uv_rect = UvRect::unit() )

2D interpolation using the nearest neighbor method.

This function performs 2D interpolation by assigning the value of the nearest point to each point in the output grid.

Parameters
shapeOutput array shape.
xx coordinates of the input values.
yy coordinates of the input values.
valuesInput values at (x, y).
p_noise_xPointer to the input noise array in the x direction (optional).
p_noise_yPointer to the input noise array in the y direction (optional).
bboxDomain bounding box (default: {0.f, 1.f, 0.f, 1.f}).
Returns
Array Output array with interpolated values.

◆ interpolate2d_nni()

Array hmap::interpolate2d_nni ( glm::ivec2 shape,
const std::vector< float > & x,
const std::vector< float > & y,
const std::vector< float > & values,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
const UvRect & uv_rect = UvRect::unit() )

2D interpolation using the Natural Neighbor Interpolation method.

◆ interpolate_array_bicubic() [1/2]

void hmap::interpolate_array_bicubic ( const Array & source,
Array & target,
bool endpoint = false,
bool pixel_centered = true )

Resample an array to a target array using bicubic interpolation.

Parameters
sourceSource array.
targetTarget array.
endpointWhether the upper domain endpoint is included.
pixel_centeredWhether coordinates are pixel-centered.

◆ interpolate_array_bicubic() [2/2]

void hmap::interpolate_array_bicubic ( const Array & source,
Array & target,
const UvRect & uv_rect_source,
const UvRect & uv_rect_target,
bool endpoint = false,
bool pixel_centered = true )

Resample a source array into a target array using bicubic interpolation between two local axis-aligned bounding boxes.

Parameters
sourceSource array.
targetTarget array.
bbox_sourceSource local bounding box {xmin, xmax, ymin, ymax}.
bbox_targetTarget local bounding box {xmin, xmax, ymin, ymax}.
endpointWhether the upper domain endpoint is included.
pixel_centeredWhether coordinates are pixel-centered.

◆ interpolate_array_bilinear() [1/2]

void hmap::interpolate_array_bilinear ( const Array & source,
Array & target,
bool endpoint = false,
bool pixel_centered = true )

Resample an array to a target array using bilinear interpolation.

Parameters
sourceSource array.
targetTarget array.
endpointWhether the upper domain endpoint is included.
pixel_centeredWhether coordinates are pixel-centered.

◆ interpolate_array_bilinear() [2/2]

void hmap::interpolate_array_bilinear ( const Array & source,
Array & target,
const UvRect & uv_rect_source,
const UvRect & uv_rect_target,
bool endpoint = false,
bool pixel_centered = true )

Resample a source array into a target array using bilinear interpolation between two local axis-aligned bounding boxes.

Parameters
sourceSource array.
targetTarget array.
bbox_sourceSource local bounding box {xmin, xmax, ymin, ymax}.
bbox_targetTarget local bounding box {xmin, xmax, ymin, ymax}.
endpointWhether the upper domain endpoint is included.
pixel_centeredWhether coordinates are pixel-centered.

◆ interpolate_array_nearest() [1/2]

void hmap::interpolate_array_nearest ( const Array & source,
Array & target,
bool endpoint = false )

Resample an array to a target array using nearest-neighbor interpolation.

Parameters
sourceSource array.
targetTarget array.
endpointWhether the upper domain endpoint is included.

◆ interpolate_array_nearest() [2/2]

void hmap::interpolate_array_nearest ( const Array & source,
Array & target,
const UvRect & uv_rect_source,
const UvRect & uv_rect_target,
bool endpoint = false )

Resample a source array into a target array using nearest-neighbor interpolation between two local axis-aligned bounding boxes.

Parameters
sourceSource array.
targetTarget array.
bbox_sourceSource local bounding box {xmin, xmax, ymin, ymax}.
bbox_targetTarget local bounding box {xmin, xmax, ymin, ymax}.
endpointWhether the upper domain endpoint is included.

◆ resample_bicubic_warp()

Array hmap::resample_bicubic_warp ( const Array & src,
glm::ivec2 dst_shape,
float warp = 0.f,
std::uint32_t seed = 0 )

Resample an array to a target shape using cubic B-spline interpolation with optional domain noise warping.

Parameters
srcSource array to resample.
dst_shapeTarget output shape.
warpDomain warping amplitude (0 for no warping).
seedRandom seed for domain warping noise.
Returns
Array Resampled (and optionally warped) array.

◆ flatten_terrain() [1/4]

void hmap::flatten_terrain ( Array & h_source1,
const Array & h_source2,
const CoordFrame & t_source1,
const CoordFrame & t_source2,
bool bilinear = true )

Blend a second terrain array in-place onto a base terrain array using their world-space coordinate frames.

Parameters
h_source1Base terrain array (modified in-place).
h_source2Overlay terrain array.
t_source1World coordinate frame of h_source1.
t_source2World coordinate frame of h_source2.
bilinearUse bilinear interpolation if true, nearest-neighbor otherwise.

◆ flatten_terrain() [2/4]

void hmap::flatten_terrain ( const std::vector< const Array * > & h_sources,
Array & h_target,
const std::vector< const CoordFrame * > & t_sources,
const CoordFrame & t_target,
bool bilinear = true )

Flatten multiple terrain arrays into a target array using their world-space coordinate frames.

Parameters
h_sourcesOrdered list of source terrain arrays.
h_targetTarget terrain array.
t_sourcesWorld coordinate frames corresponding to h_sources.
t_targetWorld coordinate frame of h_target.
bilinearUse bilinear interpolation if true, nearest-neighbor otherwise.

◆ interpolate_terrain() [1/2]

void hmap::interpolate_terrain ( const Array & h_source,
Array & h_target,
const CoordFrame & t_source,
const CoordFrame & t_target,
bool bilinear = true,
float fill_value = 0.f,
Array * p_mask = nullptr )

Project and interpolate a source terrain array onto a target terrain array using their world-space coordinate frames.

Parameters
h_sourceSource terrain array.
h_targetTarget terrain array.
t_sourceWorld coordinate frame of h_source.
t_targetWorld coordinate frame of h_target.
bilinearUse bilinear interpolation if true, nearest-neighbor otherwise.
fill_valueValue assigned to target cells outside t_source.
p_maskOptional output mask (1.f where fill_value was used, 0.f where interpolated).

◆ flatten_terrain() [3/4]

void hmap::flatten_terrain ( VirtualArray & h_source1,
const VirtualArray & h_source2,
const CoordFrame & t_source1,
const CoordFrame & t_source2,
const ComputeMode & cm,
bool bilinear = true )

Blend a second terrain VirtualArray in-place onto a base terrain VirtualArray using their world-space coordinate frames.

Parameters
h_source1Base terrain VirtualArray (modified in-place).
h_source2Overlay terrain VirtualArray.
t_source1World coordinate frame of h_source1.
t_source2World coordinate frame of h_source2.
cmCompute mode controlling tiling and CPU distribution.
bilinearUse bilinear interpolation if true, nearest-neighbor otherwise.

◆ flatten_terrain() [4/4]

void hmap::flatten_terrain ( const std::vector< const VirtualArray * > & h_sources,
VirtualArray & h_target,
const std::vector< const CoordFrame * > & t_sources,
const CoordFrame & t_target,
const ComputeMode & cm,
bool bilinear = true )

Flatten multiple terrain VirtualArrays into a target VirtualArray using their world-space coordinate frames.

Parameters
h_sourcesOrdered list of source terrain VirtualArrays.
h_targetTarget terrain VirtualArray.
t_sourcesWorld coordinate frames corresponding to h_sources.
t_targetWorld coordinate frame of h_target.
cmCompute mode controlling tiling and CPU distribution.
bilinearUse bilinear interpolation if true, nearest-neighbor otherwise.

◆ interpolate_terrain() [2/2]

void hmap::interpolate_terrain ( const VirtualArray & h_source,
VirtualArray & h_target,
const CoordFrame & t_source,
const CoordFrame & t_target,
const ComputeMode & cm,
bool bilinear = true,
float fill_value = 0.f,
VirtualArray * p_mask = nullptr )

Project and interpolate a source terrain VirtualArray onto a target terrain VirtualArray using their world-space coordinate frames.

Parameters
h_sourceSource terrain VirtualArray.
h_targetTarget terrain VirtualArray.
t_sourceWorld coordinate frame of h_source.
t_targetWorld coordinate frame of h_target.
cmCompute mode controlling tiling and CPU distribution.
bilinearUse bilinear interpolation if true, nearest-neighbor otherwise.
fill_valueValue assigned to target cells outside t_source.
p_maskOptional output mask (1.f where fill_value was used, 0.f where interpolated).

◆ get_kernel()

Array hmap::get_kernel ( glm::ivec2 shape,
KernelType kernel_type )

Generate a kernel of the specified type.

This function creates a kernel based on the given shape and kernel type. It supports various types of kernels including biweight, cubic pulse, cone, and more. The resulting kernel is returned as an array.

Parameters
shapeThe dimensions of the kernel to be generated.
kernel_typeThe type of kernel to generate (e.g., BIWEIGHT, CUBIC_PULSE, etc.).
Returns
Array The generated kernel array.

◆ biweight()

Array hmap::biweight ( glm::ivec2 shape)

Generates a biweight kernel array.

This function creates a biweight kernel, which is a type of kernel function used in statistics for smoothing and interpolation.

For more details on the biweight kernel, refer to the Wikipedia page: https://en.wikipedia.org/wiki/Kernel_%28statistics%29.

Parameters
shapeArray shape specifying the dimensions of the kernel.
Returns
Array A new array containing the biweight kernel.

◆ blackman()

Array hmap::blackman ( glm::ivec2 shape)

Generates a Blackman window array with the specified shape.

The Blackman window is commonly used in signal processing for smoothing or tapering. This function creates a 2D array of values representing the Blackman window, calculated based on the given shape dimensions.

Parameters
shapeA 2D vector representing the dimensions of the array.
Returns
An Array object containing the Blackman window values of the specified shape.

◆ cone() [1/2]

Array hmap::cone ( glm::ivec2 shape)

Generates a cone-shaped kernel array.

This function creates a cone-shaped kernel. The maximum value of the kernel is 1, and the shape of the kernel is determined by the provided array dimensions.

Parameters
shapeArray shape specifying the dimensions of the kernel.
Returns
Array A new array containing the cone-shaped kernel.

◆ cone_talus()

Array hmap::cone_talus ( float height,
float talus )

Generates a cone-shaped kernel with specified height and talus.

This function creates a cone-shaped kernel with a given height and talus. The output array's shape is adjusted accordingly based on the specified height and talus.

Parameters
heightHeight of the cone. This determines the peak value of the kernel.
talusThe slope of the cone, which affects the rate at which the kernel value decreases.
Returns
Array A new array containing the cone-shaped kernel with the specified height and talus.

◆ cone_smooth()

Array hmap::cone_smooth ( glm::ivec2 shape)

Generates a cone-shaped kernel with a smooth landing.

This function creates a cone-shaped kernel where the kernel smoothly transitions to zero at the bottom, resulting in a smooth derivative at the cone base.

Parameters
shapeArray shape specifying the dimensions of the kernel.
Returns
Array A new array containing the smooth cone-shaped kernel.

◆ cubic_pulse() [1/3]

Array hmap::cubic_pulse ( glm::ivec2 shape)

Generates a cubic pulse kernel array.

This function creates a cubic pulse kernel, which is a type of kernel function characterized by its cubic shape.

Parameters
shapeArray shape specifying the dimensions of the kernel.
Returns
Array A new array containing the cubic pulse kernel.

◆ cubic_pulse_1d()

std::vector< float > hmap::cubic_pulse_1d ( int nk)

Generates a 1D cubic pulse kernel.

Parameters
nkThe number of samples in the 1D kernel.
Returns
std::vector<float> A vector containing the cubic pulse kernel values.

◆ cubic_pulse_directional()

Array hmap::cubic_pulse_directional ( glm::ivec2 shape,
float angle,
float aspect_ratio,
float anisotropy )

Generates a "directional" cubic pulse kernel.

This function creates a cubic pulse kernel with directional properties. The kernel's shape can be adjusted based on the provided angle, aspect ratio, and anisotropy. This allows for creating kernels that are elongated or compressed in specific directions, making them suitable for applications requiring directional smoothing or filtering.

Parameters
shapeArray shape specifying the dimensions of the kernel.
angleAngle (in degrees) defining the direction of the pulse elongation.
aspect_ratioPulse aspect ratio, which controls the kernel's elongation or compression.
anisotropyPulse width ratio between upstream and downstream sides of the pulse.
Returns
Array A new array containing the directional cubic pulse kernel.

◆ cubic_pulse_truncated()

Array hmap::cubic_pulse_truncated ( glm::ivec2 shape,
float slant_ratio,
float angle )

Generates a truncated cubic pulse kernel.

This function creates a cubic pulse kernel that is truncated based on the specified slant ratio and angle. The truncation slope determines how the kernel's values decrease as they approach the edge of the kernel, creating a "cut-off" effect.

Parameters
shapeArray shape specifying the dimensions of the kernel.
slant_ratioTruncation slope that affects the kernel's cut-off behavior.
angleAngle (in degrees) that defines the orientation of the truncation.
Returns
Array A new array containing the truncated cubic pulse kernel.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
float slant_ratio = 0.5f;
float angle = 30.f;
hmap::Array z = hmap::cubic_pulse_truncated(shape, slant_ratio, angle);
z.to_png("ex_cubic_pulse_truncated.png", hmap::Cmap::VIRIDIS);
}
Array cubic_pulse_truncated(glm::ivec2 shape, float slant_ratio, float angle)
Generates a truncated cubic pulse kernel.
Definition kernels.cpp:189

Result

◆ cupola()

Array hmap::cupola ( glm::ivec2 shape,
float rc = 0.5f )

Generate a 2D radial cupola kernel.

Values are computed from the normalized radial distance to the center: constant 1 inside radius rc, then smoothly decreasing to 0 at radius 1.

Parameters
shapeSize of the output array (width, height).
rcRadius of the inner flat region (normalized, < 1).
Returns
Generated cupola-shaped Array.

◆ disk() [1/2]

Array hmap::disk ( glm::ivec2 shape)

Generates a disk-shaped kernel footprint.

This function creates a disk-shaped kernel, which is a circular kernel where the values are radially symmetric around the center.

Parameters
shapeArray shape specifying the dimensions of the kernel.
Returns
Array A new array containing the disk-shaped kernel.

◆ disk_smooth()

Array hmap::disk_smooth ( glm::ivec2 shape,
float r_cutoff = 0.9f )

Generates a smooth, disk-shaped kernel footprint with soft edges.

This function creates a 2D, disk-shaped kernel with radially symmetric values centered in the array. Values inside the cutoff radius r_cutoff are set to 1.0. Between r_cutoff and the normalized radius 1.0, the values smoothly fall off to zero using a parabolic profile to ensure soft transitions at the disk boundary.

The generated array is useful for constructing smooth low-pass filters or spatial masks with circular support.

Parameters
shapeThe dimensions of the output array (width, height).
r_cutoffNormalized cutoff radius in the range [0.0, 1.0]. Inside this radius, the kernel has a flat value of 1.0; outside, it decays smoothly to 0.0.
Returns
A 2D array of size shape containing the smooth disk-shaped kernel.
Note
Coordinates are normalized such that the radius 1.0 corresponds to the maximum possible distance from the center in either dimension.
See also
disk()

◆ gabor()

Array hmap::gabor ( glm::ivec2 shape,
float kw,
float angle,
bool quad_phase_shift = false )

Generates a Gabor kernel of the specified shape.

This function creates a Gabor kernel, which is a type of sinusoidal kernel modulated by a Gaussian envelope. The Gabor kernel is useful for texture analysis and feature extraction. The kernel's frequency and orientation are defined by the wavenumber and angle parameters, respectively.

Parameters
shapeArray shape specifying the dimensions of the kernel.
kwKernel wavenumber, which determines the frequency of the sinusoidal component.
angleKernel angle (in degrees) that defines the orientation of the sinusoidal component.
Returns
Array A new array containing the Gabor kernel.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
float kw = 4.f;
float angle = 30.f;
hmap::Array z = hmap::gabor(shape, kw, angle);
z.to_png("ex_gabor.png", hmap::Cmap::VIRIDIS);
}

Result

◆ gabor_dune()

Array hmap::gabor_dune ( glm::ivec2 shape,
float kw,
float angle,
float xtop,
float xbottom )

Generates a modified dune-like Gabor kernel.

This function creates a modified Gabor kernel that has a dune-like profile. The dune profile modifies the standard Gabor kernel to include a top and foot for the dune, giving it a specific shape. The xtop and xbottom parameters control the relative locations of the top and foot of the dune profile, respectively.

Parameters
shapeArray shape specifying the dimensions of the kernel.
kwKernel wavenumber, which determines the frequency of the sinusoidal component.
angleKernel angle (in degrees) that defines the orientation of the sinusoidal component.
xtopRelative location of the top of the dune profile (in [0, 1]).
xbottomRelative location of the foot of the dune profile (in [0, 1]).
Returns
Array A new array containing the modified dune-like Gabor kernel.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
float kw = 8.f;
float angle = 30.f;
float xtop = 0.7f;
float xbottom = 1.f;
hmap::Array z = hmap::gabor_dune(shape, kw, angle, xtop, xbottom);
z.to_png("ex_gabor_dune.png", hmap::Cmap::VIRIDIS);
}
Array gabor_dune(glm::ivec2 shape, float kw, float angle, float xtop, float xbottom)
Generates a modified dune-like Gabor kernel.
Definition kernels.cpp:329

Result

◆ hann()

Array hmap::hann ( glm::ivec2 shape)

Generates a Hann window array with the specified shape.

The Hann window is commonly used in signal processing for smoothing or tapering. This function creates a 2D array of values representing the Hann window, calculated based on the given shape dimensions.

Parameters
shapeA 2D vector representing the dimensions of the array.
Returns
An Array object containing the Hann window values of the specified shape.

◆ lorentzian()

Array hmap::lorentzian ( glm::ivec2 shape,
float footprint_threshold = 0.1f )

Generate a Lorentzian kernel.

The Lorentzian kernel is characterized by its peak and tails that decay with the distance from the center. The width of the kernel is determined using the provided footprint threshold.

Parameters
shapeThe dimensions of the kernel.
footprint_thresholdDetermines the width of the Lorentzian kernel. Default is 0.1.
Returns
Array The Lorentzian kernel array.

◆ lorentzian_compact()

Array hmap::lorentzian_compact ( glm::ivec2 shape)

Generate a modified Lorentzian kernel with compact support.

This version of the Lorentzian kernel is modified to have compact support, meaning it is non-zero only within a certain range. This modification is useful for specific applications requiring compact kernels.

Parameters
shapeThe dimensions of the kernel.
Returns
Array The modified Lorentzian kernel with compact support.

◆ sinc_radial()

Array hmap::sinc_radial ( glm::ivec2 shape,
float kw )

Generates a radial sinc function array with the specified shape and wave number.

This function creates a 2D array of values representing the radial sinc function, calculated based on the given shape and wave number. The sinc function is defined as sin(x) / x and is useful in signal processing and analysis.

Parameters
shapeA 2D vector representing the dimensions of the array.
kwThe wave number used to scale the radial sinc function.
Returns
An Array object containing the radial sinc function values of the specified shape.

◆ sinc_separable()

Array hmap::sinc_separable ( glm::ivec2 shape,
float kw )

Generates a separable sinc function array with the specified shape and wave number.

This function creates a 2D array of values representing the separable sinc function, calculated as the product of 1D sinc functions along each dimension of the array. The sinc function is defined as sin(x) / x and is useful in signal processing and analysis.

Parameters
shapeA 2D vector representing the dimensions of the array.
kwThe wave number used to scale the separable sinc function.
Returns
An Array object containing the separable sinc function values of the specified shape.

◆ smooth_cosine() [1/2]

Array hmap::smooth_cosine ( glm::ivec2 shape)

Generate a smooth cosine kernel.

The smooth cosine kernel is a type of kernel function that smoothly transitions between values, based on a cosine function.

Parameters
shapeThe dimensions of the kernel.
Returns
Array The smooth cosine kernel array.

◆ square()

Array hmap::square ( glm::ivec2 shape)

Generate a square-shaped kernel.

The square kernel is a simple, isotropic kernel where the values are constant within the square region. The maximum value within the kernel is 1.

Parameters
shapeThe dimensions of the kernel.
Returns
Array The square-shaped kernel array.

◆ tricube()

Array hmap::tricube ( glm::ivec2 shape)

Generate a tricube kernel.

The tricube kernel is a type of kernel function that is often used in statistical applications. It has a specific shape defined by the tricube polynomial.

Parameters
shapeThe dimensions of the kernel.
Returns
Array The tricube kernel array.

Reference See https://en.wikipedia.org/wiki/Kernel_%28statistics%29 for details on the tricube kernel.

◆ path_length_to_outlet()

Array hmap::path_length_to_outlet ( const Array & z)

Computes the downstream path length to the domain outlet.

For each cell, follows the steepest-descending flow path and returns the number of downstream cells required to leave the domain. Cells whose flow terminates in an internal sink have a path length of 0.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {2.f, 2.f};
int seed = 0;
hmap::export_banner_png("ex_path_length_to_sink.png",
{z, k_sink, k_outlet},
false,
true);
}
Array path_length_to_outlet(const Array &z)
Computes the downstream path length to the domain outlet.
Definition path_length_to_sink.cpp:12
Array path_length_to_sink(const Array &z)
Computes the downstream path length to the nearest sink.
Definition path_length_to_sink.cpp:106

Result

◆ path_length_to_sink()

Array hmap::path_length_to_sink ( const Array & z)

Computes the downstream path length to the nearest sink.

For each cell, follows the steepest-descending flow path and returns the number of downstream cells required to reach a sink. Sink cells have a path length of 0.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {2.f, 2.f};
int seed = 0;
hmap::export_banner_png("ex_path_length_to_sink.png",
{z, k_sink, k_outlet},
false,
true);
}

Result

◆ local_max()

Array hmap::local_max ( const Array & array,
int ir )

Return the local maxima based on a maximum filter with a square kernel.

This function identifies the local maxima in the input array using a maximum filter with a square kernel. The local maxima are determined based on the footprint radius specified by ir. The result is an array where each value represents the local maximum within the defined kernel size.

Parameters
arrayInput array from which local maxima are to be extracted.
irSquare kernel footprint radius. The size of the kernel used to determine the local maxima.
Returns
Array Resulting array containing the local maxima.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {4.f, 4.f};
int seed = 1;
hmap::export_banner_png("ex_local_max.png",
{z, z_max, z_min},
}
Array local_max(const Array &array, int ir)
Return the local maxima based on a maximum filter with a square kernel.
Definition local_metrics.cpp:22

Result

See also
local_max_disk, local_min

◆ local_median_deviation()

Array hmap::local_median_deviation ( const Array & array,
int ir )

Computes the local median deviation of a 2D array.

This function calculates the absolute difference between the local mean and a pseudo-local median of each element in the input array. The local neighborhood is defined by a square window with radius ir.

Parameters
arrayThe input 2D array of values (e.g., a heightmap).
irThe radius of the square neighborhood window used for computing local statistics. The window size is (2*ir + 1) x (2*ir + 1).
Returns
A new array of the same size as array, where each element represents the absolute deviation between the local mean and pseudo-local median in its neighborhood.
Note
The function uses a pseudo-median approximation. For exact median computation, replace the median_pseudo() call with a proper median filter implementation.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
int ir = 16;
// gpu version
hmap::export_banner_png("ex_local_median_deviation.png",
{z, z1, z2},
}
Array local_median_deviation(const Array &array, int ir)
See hmap::local_median_deviation.
Definition local_metrics_gpu.cpp:306
Array local_median_deviation(const Array &array, int ir)
Computes the local median deviation of a 2D array.
Definition local_metrics.cpp:112

Result

See also
local_mean(), median_pseudo()

◆ local_min()

Array hmap::local_min ( const Array & array,
int ir )

Return the local minima based on a maximum filter with a square kernel.

This function identifies the local minima in the input array using a maximum filter with a square kernel. The local minima are determined based on the footprint radius specified by ir. The result is an array where each value represents the local minimum within the defined kernel size.

Parameters
arrayInput array from which local minima are to be extracted.
irSquare kernel footprint radius. The size of the kernel used to determine the local minima.
Returns
Array Resulting array containing the local minima.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {4.f, 4.f};
int seed = 1;
hmap::export_banner_png("ex_local_max.png",
{z, z_max, z_min},
}

Result

See also
local_min

◆ local_mean()

Array hmap::local_mean ( const Array & array,
int ir )

Return the local mean based on a mean filter with a square kernel.

This function calculates the local mean of the input array using a mean filter with a square kernel. The local mean is determined by averaging values within a square neighborhood defined by the footprint radius ir. The result is an array where each value represents the mean of the surrounding values within the kernel size.

Parameters
arrayInput array from which the local mean is to be calculated.
irSquare kernel footprint radius. The size of the kernel used to compute the local mean.
Returns
Array Resulting array containing the local means.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
int radius = 10;
hmap::Array zm = hmap::local_mean(z, radius);
z.to_png("ex_local_mean0.png", hmap::Cmap::VIRIDIS);
zm.to_png("ex_local_mean1.png", hmap::Cmap::VIRIDIS);
}
Array local_mean(const Array &array, int ir)
Return the local mean based on a mean filter with a square kernel.
Definition local_metrics.cpp:89

Result

See also
local_max, local_min

◆ relative_elevation()

Array hmap::relative_elevation ( const Array & array,
int ir )

Calculates the relative elevation within a specified radius, helping to identify local highs and lows.

Relative elevation analysis determines how high or low a point is relative to its surroundings, which can be critical in hydrological modeling and geomorphology.

Usage:

  • Use this function to detect local depressions or peaks in the terrain, which could indicate potential water collection points or hilltops.
  • Useful in flood risk assessment and landscape classification.
Parameters
arrayThe input array representing the terrain elevation data.
irThe radius (in pixels) within which to calculate the relative elevation for each point.
Returns
Array An output array containing the relative elevation values, normalized between 0 and 1.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
int ir = 32;
auto zr = hmap::relative_elevation(z, ir);
hmap::export_banner_png("ex_relative_elevation.png",
{z, zr},
}
Array relative_elevation(const Array &array, int ir)
Calculates the relative elevation within a specified radius, helping to identify local highs and lows...
Definition local_metrics.cpp:121

Result

◆ roughness()

Array hmap::roughness ( const Array & array,
int ir )

Measures the local surface roughness within a given radius.

Compares the original heightmap with a locally smoothed version (using a smooth cubic pulse filter) within the specified radius ir. The result is the magnitude of the local deviation.

Parameters
arrayThe input array representing the terrain elevation data.
irThe radius within which local roughness is computed.
Returns
Array An output array containing roughness values.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {2.f, 2.f};
int seed = 0;
const int ir = 16;
shape,
res,
seed,
8,
0.f);
// smooth lower elevations
auto mask = 1.f - z;
hmap::gpu::smooth_cpulse(z, ir, &mask);
std::vector<hmap::Array> arrays = {z};
std::vector<hmap::gpu::LocalMetrics> metrics = {
};
for (const auto metric : metrics)
{
hmap::Array out = hmap::gpu::local_metrics(z, ir, metric);
arrays.push_back(out);
}
hmap::export_banner_png("ex_local_metrics.png",
arrays,
false,
true);
}
Array local_metrics(const Array &array, int ir, LocalMetrics metric, MinMaxKernel kernel_type=MinMaxKernel::DISK)
Compute a local metric on the input array using a square neighborhood.
Definition local_metrics_wrapper.cpp:10
@ LM_LOCAL_MIN
Local minimum value.
Definition local_metrics.hpp:612
@ LM_RELATIVE_ELEVATION
Normalized elevation.
Definition local_metrics.hpp:620
@ LM_RUGGEDNESS
Measure of terrain roughness.
Definition local_metrics.hpp:622
@ LM_LOCAL_RELIEF
Diff. between local max & min.
Definition local_metrics.hpp:613
@ LM_LOCAL_ASPECT_VARIANCE
Variance of local slope directions.
Definition local_metrics.hpp:609
@ LM_LOCAL_Z_SCORE
Standardized value.
Definition local_metrics.hpp:617
@ LM_RUGOSITY_CONCAVE
Roughness of concave features.
Definition local_metrics.hpp:623
@ LM_TOPOGRAPHIC_POSITION_INDEX
Topographic index.
Definition local_metrics.hpp:618
@ LM_LOCAL_MAX
Local maximum value.
Definition local_metrics.hpp:610
@ LM_LOCAL_VARIANCE
Variance of local values.
Definition local_metrics.hpp:614
@ LM_ROUGHNESS
Local terrain roughness.
Definition local_metrics.hpp:621
@ LM_RUGOSITY_CONVEX
Roughness of convex features.
Definition local_metrics.hpp:624
@ LM_LOCAL_MEAN
Mean of local values.
Definition local_metrics.hpp:615
@ LM_TOPOGRAPHIC_WETNESS_INDEX
Topographic wetness index.
Definition local_metrics.hpp:619
@ LM_LOCAL_MEDIAN_DEVIATION
Deviation from local median.
Definition local_metrics.hpp:611
@ LM_LOCAL_SKEWNESS
Skewness.
Definition local_metrics.hpp:616

Result

◆ ruggedness()

Array hmap::ruggedness ( const Array & array,
int ir )

Computes the ruggedness of each element in the input array.

The ruggedness is calculated as the square root of the sum of squared differences between each element and its neighbors within a specified radius.

Parameters
arrayThe input array for which ruggedness is to be computed.
irThe radius within which neighbors are considered for ruggedness calculation.
Returns
An array containing the ruggedness values for each element in the input array.
Note
https://xdem.readthedocs.io/en/latest/terrain.html

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
int ir = 5;
z.to_png("ex_ruggedness0.png", hmap::Cmap::INFERNO);
c.to_png("ex_ruggedness1.png", hmap::Cmap::INFERNO);
}
Array ruggedness(const Array &array, int ir)
Computes the ruggedness of each element in the input array.
Definition local_metrics.cpp:147

Result

◆ rugosity()

Array hmap::rugosity ( const Array & z,
int ir,
bool convex = true )

Estimates the rugosity of a surface by analyzing the skewness of the elevation data, which reflects surface roughness.

Rugosity is a measure of terrain roughness, often used in ecological studies and habitat mapping. Higher rugosity values indicate more rugged terrain, which can affect species distribution and water flow.

Parameters
zThe input array representing the heightmap data (elevation values).
irThe radius of the square kernel used for calculations, determining the scale of the analysis.
convexReturn the convex rugosity if true, and the concave ones if not.
Returns
Array An output array containing the rugosity estimates, where higher values indicate rougher terrain.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
int ir = 5;
z.to_png("ex_rugosity0.png", hmap::Cmap::VIRIDIS);
c.to_png("ex_rugosity1.png", hmap::Cmap::VIRIDIS);
}
Array rugosity(const Array &z, int ir, bool convex=true)
Estimates the rugosity of a surface by analyzing the skewness of the elevation data,...
Definition local_metrics.cpp:176

Result

◆ topographic_wetness_index()

Array hmap::topographic_wetness_index ( const Array & z,
float talus_ref = 0.f,
float min_slope = 1e-4f )

Computes the Topographic Wetness Index (TWI).

TWI (compound topographic index) is a steady-state hydrological indicator estimating the tendency of terrain to accumulate water based on its topography:

\[ \text{TWI} = \ln\left(\frac{a}{\tan(\beta)}\right) \]

where \(a\) is the upslope contributing area computed via \(D_\infty\) flow accumulation, and \(\beta\) is the local slope.

Parameters
zInput elevation array.
talus_refReference talus slope for flow partitioning in D-infinity accumulation (if <= 0, automatically determined from max talus).
min_slopeMinimum slope threshold \(\tan(\beta)\) to prevent division by zero in flat areas (default: 1e-4f).
Returns
Array Resulting array containing the TWI values.

Example

Result

◆ topographic_residual()

Array hmap::topographic_residual ( const Array & z,
int ir,
bool normalize_output = false )

Computes the topographic residual (relief) relative to a smoothed surface.

Subtracts a smoothed version of the elevation (using smooth_cpulse with radius ir) from the input array. Optionally normalizes and clips the output to [-1, 1].

Parameters
zInput elevation array.
irRadius for smoothing filter.
normalize_outputIf true, normalizes and clips the residual to [-1, 1].
Returns
Array containing the topographic residual.

◆ valley_width()

Array hmap::valley_width ( const Array & z,
int ir = 0,
bool ridge_select = false )

Measures the valley width by calculating the distance from each point in a concave region to the frontier of that region.

Valley width is a geomorphological metric that represents the distance across valleys or concave regions in a terrain. This measurement is particularly useful in hydrological modeling and landscape analysis, where valley dimensions are important.

Usage

  • Use this function to assess the width of valleys within a terrain, which can be important for understanding water flow, sediment transport, and landform development.
  • Applicable in studies focusing on river valleys, canyon analysis, and erosion patterns.
Parameters
zThe input array representing the heightmap data (elevation values).
irThe radius used for pre-filtering, controlling the scale of analysis (in pixels). The default value is 0, meaning no pre-filtering is applied.
ridge_selectIf enabled, selects ridges instead of valleys.
Returns
Array An output array containing valley width values, representing the distance to the edge of the concave region for each point.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
int ir = 8;
bool ridge_select = true;
hmap::Array w2 = hmap::valley_width(z, ir, ridge_select);
z.to_png("ex_valley_width0.png", hmap::Cmap::TERRAIN);
w1.to_png("ex_valley_width1.png", hmap::Cmap::INFERNO);
w2.to_png("ex_valley_width2.png", hmap::Cmap::INFERNO);
}
Array valley_width(const Array &z, int ir=0, bool ridge_select=false)
Measures the valley width by calculating the distance from each point in a concave region to the fron...
Definition valley_width.cpp:13

Result

◆ abs()

Array hmap::abs ( const Array & array)

Absolute value.

Parameters
arrayInput array.
Returns
Output array.

◆ abs_smooth() [1/4]

Array hmap::abs_smooth ( const Array & array,
float mu,
const Array & vshift )

Smooth absolute value.

Parameters
arrayInput array.
muSmoothing coefficient.
vshiftReference value for the zero of the absolute value.
Returns
Output array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
hmap::remap(z, -1.f, 1.f);
float k = 0.1f;
auto z1 = hmap::abs_smooth(z, k);
auto z2 = hmap::abs_smooth(z, k, 0.5f);
auto vshift = hmap::noise(hmap::NoiseType::PERLIN, shape, res, ++seed);
auto z3 = hmap::abs_smooth(z, k, vshift);
hmap::export_banner_png("ex_abs_smooth.png",
{z, z1, z2, z3},
}
Array abs_smooth(const Array &array, float mu, const Array &vshift)
Smooth absolute value.
Definition math.cpp:61

Result

◆ abs_smooth() [2/4]

Array hmap::abs_smooth ( const Array & array,
float mu,
float vshift )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ abs_smooth() [3/4]

Array hmap::abs_smooth ( const Array & array,
float mu )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ almost_unit_identity() [1/2]

Array hmap::almost_unit_identity ( const Array & array)

Almost unit identity function.

Maps [0, 1] to itself with zero derivative at 0 and unit derivative at 1. See Inigo Quilez: https://iquilezles.org/articles/functions/

Parameters
arrayInput array.
Returns
Output array.

◆ almost_unit_identity_c2() [1/2]

Array hmap::almost_unit_identity_c2 ( const Array & array)

Almost unit identity function (C2 variant).

Ensures smoother behavior by also enforcing second-order continuity at x = 1.

Parameters
arrayInput array.
Returns
Output array.

◆ atan()

Array hmap::atan ( const Array & array)

Arctangent.

Parameters
arrayInput array.
Returns
Output array.

◆ atan2()

Array hmap::atan2 ( const Array & y,
const Array & array )

Element-wise arctangent with quadrant handling.

Computes atan2(y, x) element-wise.

Parameters
yNumerator array.
xDenominator array.
Returns
Output array.

◆ build_density_linear()

Array hmap::build_density_linear ( const std::vector< const Array * > & layers,
const std::vector< float > & weights = {} )

Combine a list of layers in linear space.

Multiplies layer values blended with weights:

\[\text{result} = \prod_{i=0}^{N-1} \text{lerp}(1, L_i, w_i) \]

Parameters
layersList of layer arrays (pointers).
weightsPer-layer weights (defaults to 1.0 for each layer).
Returns
Combined density array.

◆ build_density_log()

Array hmap::build_density_log ( const std::vector< const Array * > & layers,
const std::vector< float > & weights = {},
float eps = 1e-6f )

Combine a list of layers in log space.

Computes the weighted geometric combination in log space:

\[\text{result} = \exp\left(\sum_{i=0}^{N-1} w_i \log_{\text{safe}}(L_i, \epsilon)\right) \]

Parameters
layersList of layer arrays (pointers).
weightsPer-layer weights (defaults to 1.0 for each layer).
epsSmall epsilon value for numerical stability (default: 1e-6).
Returns
Combined density array.

◆ cos()

Array hmap::cos ( const Array & array)

Cosine.

Parameters
arrayInput array.
Returns
Output array.

◆ exp()

Array hmap::exp ( const Array & array)

Exponential.

Parameters
arrayInput array.
Returns
Output array.

◆ gaussian_decay()

Array hmap::gaussian_decay ( const Array & array,
float sigma )

Gaussian decay.

Parameters
arrayInput array.
sigmaGaussian half-width.
Returns
Output array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
hmap::remap(z, -1.f, 1.f);
float sigma = 0.5f;
hmap::export_banner_png("ex_gaussian_decay.png",
{z, zg},
}
Array gaussian_decay(const Array &array, float sigma)
Gaussian decay.
Definition math.cpp:282

Result

◆ hypot()

Array hmap::hypot ( const Array & array1,
const Array & array2 )

Hypotenuse.

Computes sqrt(array1² + array2²) element-wise.

Parameters
array1First array.
array2Second array.
Returns
Output array.

◆ is_equal()

Array hmap::is_equal ( const Array & array,
float value )

Binary mask of elements equal to a value.

Parameters
arrayInput array.
valueReference value.
Returns
Binary mask array.

◆ is_non_zero()

Array hmap::is_non_zero ( const Array & array)

Binary mask of non-zero elements.

Parameters
arrayInput array.
Returns
Binary mask array.

◆ is_zero()

Array hmap::is_zero ( const Array & array)

Binary mask of zero elements.

Parameters
arrayInput array.
Returns
Binary mask array.

◆ lerp() [2/4]

Array hmap::lerp ( const Array & array1,
const Array & array2,
const Array & t )

Linear interpolation.

Parameters
array1First array.
array2Second array.
tInterpolation factor in [0,1].
Returns
Interpolated array.

◆ lerp() [3/4]

Array hmap::lerp ( const Array & array1,
const Array & array2,
float t )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ log10()

Array hmap::log10 ( const Array & array)

Base-10 logarithm.

Parameters
arrayInput array.
Returns
Output array.

◆ log_safe() [1/2]

Array hmap::log_safe ( const Array & array,
float eps = 1e-6f )

Safe natural logarithm with lower clamp.

Computes std::log(std::max(v, eps)) element-wise.

Parameters
arrayInput array.
epsMinimum threshold (default: 1e-6).
Returns
Output array.

◆ pow()

Array hmap::pow ( const Array & array,
float exp )

Power function.

Parameters
arrayInput array.
expExponent.
Returns
Output array.

◆ r_min() [1/2]

Array hmap::r_min ( const Array & array1,
const Array & array2,
float alpha = 0.f )

Generalized Rvachev R-function for smooth minimum / intersection (exact zero-set).

Parameters
array1First array.
array2Second array.
alphaParameter in (-1, 1] controlling blending sharpness (default 0.0).
Returns
Output array.

◆ r_max() [1/2]

Array hmap::r_max ( const Array & array1,
const Array & array2,
float alpha = 0.f )

Generalized Rvachev R-function for smooth maximum / union (exact zero-set).

Parameters
array1First array.
array2Second array.
alphaParameter in (-1, 1] controlling blending sharpness (default 0.0).
Returns
Output array.

◆ sigmoid() [1/2]

Array hmap::sigmoid ( const Array & array,
float width = 1.f,
float vmin = 0.f,
float vmax = 1.f,
float x0 = 0.f )

Sigmoid function.

Applies the generalized sigmoid transformation element-wise:

\[y = v_{\min} + \frac{v_{\max} - v_{\min}} {1 + \exp\left(-\frac{x - x_0}{\text{width}}\right)} \]

Parameters
arrayInput array.
widthControls steepness.
vminMinimum output value.
vmaxMaximum output value.
x0Center offset.
Returns
Output array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
auto z1 = z;
hmap::remap(z1, -2.f, 2.f);
float width = 0.2f;
z1 = hmap::sigmoid(z1, width);
hmap::export_banner_png("ex_sigmoid.png", {z, z1}, hmap::Cmap::INFERNO);
}
Array sigmoid(const Array &array, float width=1.f, float vmin=0.f, float vmax=1.f, float x0=0.f)
Sigmoid function.
Definition math.cpp:450

Result

◆ sin()

Array hmap::sin ( const Array & array)

Sine.

Parameters
arrayInput array.
Returns
Output array.

◆ smoothstep3() [1/3]

Array hmap::smoothstep3 ( const Array & array,
float vmin = 0.f,
float vmax = 1.f )

Cubic smoothstep.

Parameters
arrayInput array.
vminLower bound.
vmaxUpper bound.
Returns
Output array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {2.f, 2.f};
int seed = 1;
float vmin = 0.25f;
float vmax = 0.75f;
hmap::Array z3 = hmap::smoothstep3(z, vmin, vmax);
hmap::Array z5 = hmap::smoothstep5(z, vmin, vmax);
hmap::export_banner_png("ex_smoothstep.png",
{z, z3, z5},
}
Array smoothstep3(const Array &array, float vmin=0.f, float vmax=1.f)
Cubic smoothstep.
Definition math.cpp:475
Array smoothstep5(const Array &array, float vmin=0.f, float vmax=1.f)
Quintic smoothstep.
Definition math.cpp:523

Result

◆ smoothstep3_lower() [1/2]

Array hmap::smoothstep3_lower ( const Array & array)

Cubic smoothstep (zero derivative at 0 only).

Parameters
arrayInput array.
Returns
Output array. This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ smoothstep3_upper() [1/2]

Array hmap::smoothstep3_upper ( const Array & array)

Cubic smoothstep (zero derivative at 1 only).

Parameters
arrayInput array.
Returns
Output array. This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ smoothstep5() [1/3]

Array hmap::smoothstep5 ( const Array & array,
float vmin = 0.f,
float vmax = 1.f )

Quintic smoothstep.

Parameters
arrayInput array.
vminLower bound.
vmaxUpper bound.
Returns
Output array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {2.f, 2.f};
int seed = 1;
float vmin = 0.25f;
float vmax = 0.75f;
hmap::Array z3 = hmap::smoothstep3(z, vmin, vmax);
hmap::Array z5 = hmap::smoothstep5(z, vmin, vmax);
hmap::export_banner_png("ex_smoothstep.png",
{z, z3, z5},
}

Result

◆ smoothstep5() [2/3]

Array hmap::smoothstep5 ( const Array & array,
const Array & vmin,
const Array & vmax )

◆ smoothstep5_lower() [1/2]

Array hmap::smoothstep5_lower ( const Array & array)

Quintic smoothstep (zero derivative at 0 only).

Parameters
arrayInput array.
Returns
Output array.

◆ smoothstep5_upper() [1/2]

Array hmap::smoothstep5_upper ( const Array & array)

Quintic smoothstep (zero derivative at 1 only).

Parameters
arrayInput array.
Returns
Output array.

◆ smoothstep7() [1/2]

Array hmap::smoothstep7 ( const Array & array)

Seventh-order smoothstep.

Parameters
arrayInput array.
Returns
Output array.

◆ sqrt()

Array hmap::sqrt ( const Array & array)

Square root.

Parameters
arrayInput array.
Returns
Output array.

◆ sqrt_safe()

Array hmap::sqrt_safe ( const Array & array)

Safe square root.

Returns sqrt(v) for positive values and 0 otherwise.

Parameters
arrayInput array.
Returns
Output array.

◆ threshold() [1/2]

Array hmap::threshold ( const Array & array,
float x0,
float x1 )

Linear threshold.

Parameters
arrayInput array.
x0Lower threshold.
x1Upper threshold.
Returns
Output array.

◆ threshold_smooth() [1/2]

Array hmap::threshold_smooth ( const Array & array,
float x0,
float x1 )

Smooth threshold.

Parameters
arrayInput array.
x0Lower threshold.
x1Upper threshold.
Returns
Output array.

◆ convolve1d_i()

Array hmap::convolve1d_i ( const Array & array,
const std::vector< float > & kernel )

Return the convolution product of the array with a 1D kernel along the 'i' direction.

This function applies a 1D convolution to the input array using the provided kernel, considering the convolution in the row direction ('i' direction).

Parameters
arrayInput array to be convolved.
kernel1D kernel to be used for the convolution.
Returns
Array Resulting array after applying the 1D convolution.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
std::vector<float> k(32);
std::fill(k.begin(), k.end(), 1.f / 32.f);
auto zc = hmap::convolve1d_i(z, k);
zc = hmap::convolve1d_j(zc, k);
hmap::export_banner_png("ex_convolve1d_ij.png", {z, zc}, hmap::Cmap::VIRIDIS);
}
Array convolve1d_j(const Array &array, const std::vector< float > &kernel)
Return the convolution product of the array with a 1D kernel along the 'j' direction.
Definition convolve.cpp:46
Array convolve1d_i(const Array &array, const std::vector< float > &kernel)
Return the convolution product of the array with a 1D kernel along the 'i' direction.
Definition convolve.cpp:22

Result

See also
convolve1d_j

◆ convolve1d_j()

Array hmap::convolve1d_j ( const Array & array,
const std::vector< float > & kernel )

Return the convolution product of the array with a 1D kernel along the 'j' direction.

This function applies a 1D convolution to the input array using the provided kernel, considering the convolution in the column direction ('j' direction).

Parameters
arrayInput array to be convolved.
kernel1D kernel to be used for the convolution.
Returns
Array Resulting array after applying the 1D convolution.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
std::vector<float> k(32);
std::fill(k.begin(), k.end(), 1.f / 32.f);
auto zc = hmap::convolve1d_i(z, k);
zc = hmap::convolve1d_j(zc, k);
hmap::export_banner_png("ex_convolve1d_ij.png", {z, zc}, hmap::Cmap::VIRIDIS);
}

Result

See also
convolve1d_i

◆ convolve2d()

Array hmap::convolve2d ( const Array & array,
const Array & kernel )

Return the convolution product of the array with a given 2D kernel.

This function performs a 2D convolution on the input array using the specified 2D kernel. The output array has the same shape as the input array, and symmetry boundary conditions are used.

Parameters
arrayInput array to be convolved.
kernel2D kernel to be used for the convolution.
Returns
Array Resulting array after applying the 2D convolution.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
int seed = 1;
hmap::Array z = hmap::white(shape, 0.f, 1.f, seed);
hmap::Array kernel = hmap::disk({32, 32});
kernel.normalize();
// SVD approximation
int rank = 4;
auto zs = hmap::convolve2d_svd(z, kernel, rank);
// exact convolution
auto zc = hmap::convolve2d(z, kernel);
remap(zs);
remap(zc);
hmap::export_banner_png("ex_convolve2d_svd.png",
{z, zs, zc},
}
void normalize(ICommunicator &comm=SingleArrayComm::instance())
Normalize array values so that the sum of all elements is equal to 1.
Definition methods.cpp:328
Array convolve2d_svd(const Array &z, const Array &kernel, int rank=3)
Return the approximate convolution product of the array with a Singular Value Decomposition (SVD) of ...
Definition convolve2d_svd.cpp:23
Array disk(glm::ivec2 shape)
Generates a disk-shaped kernel footprint.
Definition kernels.cpp:245
Array convolve2d(const Array &array, const Array &kernel)
Return the convolution product of the array with a given 2D kernel.
Definition convolve.cpp:68

◆ convolve2d_truncated()

Array hmap::convolve2d_truncated ( const Array & array,
const Array & kernel )

Return the convolution product of the array with a given 2D kernel, with a truncated output size.

This function performs a 2D convolution on the input array using the specified 2D kernel. The resulting output array is smaller than the input array by the dimensions of the kernel.

Parameters
arrayInput array to be convolved.
kernel2D kernel to be used for the convolution.
Returns
Array Resulting array after applying the truncated 2D convolution. Shape: {array.shape[0] - kernel.shape[0], array.shape[1] - kernel.shape[1]}.

◆ convolve2d_svd()

Array hmap::convolve2d_svd ( const Array & z,
const Array & kernel,
int rank = 3 )

Return the approximate convolution product of the array with a Singular Value Decomposition (SVD) of a kernel.

This function approximates the convolution of the input array with a 2D kernel by using its Singular Value Decomposition (SVD). The approximation is based on the first rank singular values and vectors.

Parameters
zInput array to be convolved.
kernel2D kernel to be used for the convolution.
rankApproximation rank: number of singular values/vectors used for the approximation.
Returns
Array Resulting array after applying the SVD-based convolution approximation.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
int seed = 1;
hmap::Array z = hmap::white(shape, 0.f, 1.f, seed);
hmap::Array kernel = hmap::disk({32, 32});
kernel.normalize();
// SVD approximation
int rank = 4;
auto zs = hmap::convolve2d_svd(z, kernel, rank);
// exact convolution
auto zc = hmap::convolve2d(z, kernel);
remap(zs);
remap(zc);
hmap::export_banner_png("ex_convolve2d_svd.png",
{z, zs, zc},
}

Result

◆ convolve2d_svd_rotated_kernel()

Array hmap::convolve2d_svd_rotated_kernel ( const Array & z,
const Array & kernel,
int rank = 3,
int n_rotations = 6,
std::uint32_t seed = 1 )

Return the approximate convolution product of the array with a Singular Value Decomposition (SVD) of a kernel combined with kernel rotations.

This function approximates the convolution of the input array with a 2D kernel using its SVD, combined with multiple rotations of the kernel. This can enhance the convolution approximation by considering different orientations of the kernel.

Parameters
zInput array to be convolved.
kernel2D kernel to be used for the convolution.
rankApproximation rank: number of singular values/vectors used for the approximation.
n_rotationsNumber of kernel rotations to be considered.
seedRandom seed number for kernel rotations.
Returns
Array Resulting array after applying the SVD-based convolution approximation with rotations.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
int seed = 1;
hmap::Array z = hmap::white(shape, 0.f, 1.f, seed);
hmap::Array kernel = hmap::disk({32, 32});
kernel.normalize();
// SVD approximation
int rank = 4;
auto zs = hmap::convolve2d_svd(z, kernel, rank);
// exact convolution
auto zc = hmap::convolve2d(z, kernel);
remap(zs);
remap(zc);
hmap::export_banner_png("ex_convolve2d_svd.png",
{z, zs, zc},
}

Result

◆ abs_smooth() [4/4]

float hmap::abs_smooth ( float a,
float mu )

Smooth absolute value.

Parameters
aInput value.
muSmoothing coefficient.

◆ almost_unit_identity() [2/2]

float hmap::almost_unit_identity ( float x)

Almost unit identity function.

Maps [0, 1] to itself with zero derivative at 0 and unit derivative at 1. See Inigo Quilez: https://iquilezles.org/articles/functions/

Parameters
xInput value.

◆ almost_unit_identity_c2() [2/2]

float hmap::almost_unit_identity_c2 ( float x)

Almost unit identity function (C2 variant).

Ensures smoother behavior by also enforcing second-order continuity at x = 1.

Parameters
xInput value.

◆ approx_hypot()

float hmap::approx_hypot ( float a,
float b )
inline

Approximate hypotenuse.

Parameters
aFirst value.
bSecond value.
Returns
Approximate sqrt(a² + b²).

◆ approx_rsqrt()

float hmap::approx_rsqrt ( float a)
inline

Fast inverse square root approximation.

Parameters
aInput value.
Returns
Approximate 1 / sqrt(a).

◆ ceil_div()

int hmap::ceil_div ( int a,
int b )

Integer ceiling division.

Parameters
aNumerator (>= 0).
bDenominator (> 0).
Returns
ceil(a / b).

◆ fast_exp()

float hmap::fast_exp ( float x)

Fast exponential approximation.

Parameters
xInput value.
Returns
Approximate exp(x).

◆ fast_log()

float hmap::fast_log ( float x)

Fast natural logarithm approximation.

Parameters
xInput value (must be > 0).
Returns
Approximate ln(x).

◆ gain() [3/3]

float hmap::gain ( float x,
float factor )

Gain curve remapping in [0,1].

Parameters
xInput value in [0,1].
factorContrast/gain factor.

◆ highest_power_of_2()

int hmap::highest_power_of_2 ( int n)

Highest power of 2 less than or equal to n.

Parameters
nInput value.
Returns
Power of 2.

◆ lerp() [4/4]

float hmap::lerp ( float a,
float b,
float t )

Linear interpolation.

Parameters
aFirst value.
bSecond value.
tInterpolation factor in [0,1].

◆ log_safe() [2/2]

float hmap::log_safe ( float x,
float eps = 1e-6f )

Safe natural logarithm with lower clamp.

Parameters
xInput value.
epsMinimum value threshold (default: 1e-6).
Returns
log(max(x, eps)).

◆ power_curve()

float hmap::power_curve ( float x,
float a,
float b )

Smooth asymmetric bell-shaped curve on [0,1].

Parameters a and b control left and right curvature. The function is normalized to a maximum of 1.

Parameters
xInput value.
aLeft curvature parameter.
bRight curvature parameter.

◆ r_min() [2/2]

float hmap::r_min ( float f1,
float f2,
float alpha = 0.f )

Generalized Rvachev R-function for smooth minimum / intersection (exact zero-set).

\[R_{\min}(f_1, f_2, \alpha) = \frac{f_1 + f_2 - \sqrt{f_1^2 + f_2^2 - 2\alpha f_1 f_2}}{1 + \alpha} \]

Parameters
f1First value.
f2Second value.
alphaParameter in (-1, 1] controlling blending sharpness (default 0.0). alpha = 0 gives standard Euclidean R-min, alpha = 1 gives exact min.
Returns
Smooth minimum value.

◆ r_max() [2/2]

float hmap::r_max ( float f1,
float f2,
float alpha = 0.f )

Generalized Rvachev R-function for smooth maximum / union (exact zero-set).

\[R_{\max}(f_1, f_2, \alpha) = \frac{f_1 + f_2 + \sqrt{f_1^2 + f_2^2 - 2\alpha f_1 f_2}}{1 + \alpha} \]

Parameters
f1First value.
f2Second value.
alphaParameter in (-1, 1] controlling blending sharpness (default 0.0). alpha = 0 gives standard Euclidean R-max, alpha = 1 gives exact max.
Returns
Smooth maximum value.

◆ sigmoid() [2/2]

float hmap::sigmoid ( float x,
float width = 1.f,
float vmin = 0.f,
float vmax = 1.f,
float x0 = 0.f )

Sigmoid function.

Generalized logistic function:

\[y = v_{\min} + \frac{v_{\max} - v_{\min}} {1 + \exp\left(-\frac{x - x_0}{\text{width}}\right)} \]

Parameters
xInput value.
widthControls steepness.
vminMinimum output value.
vmaxMaximum output value.
x0Center offset.
Returns
Sigmoid result in [vmin, vmax].

◆ smoothstep3() [2/3]

float hmap::smoothstep3 ( float x)

Cubic smoothstep function.

Parameters
xInput value.

◆ smoothstep3() [3/3]

float hmap::smoothstep3 ( float x,
float clamp_min,
float clamp_max )

Cubic smoothstep function with clamping.

Parameters
xInput value.
clamp_minLower clamp bound.
clamp_maxUpper clamp bound.

◆ smoothstep3_lower() [2/2]

float hmap::smoothstep3_lower ( float x)

Cubic smoothstep (zero derivative at 0 only).

Parameters
xInput value.

◆ smoothstep3_upper() [2/2]

float hmap::smoothstep3_upper ( float x)

Cubic smoothstep (zero derivative at 1 only).

Parameters
xInput value.

◆ smoothstep5() [3/3]

float hmap::smoothstep5 ( float x)

Quintic smoothstep function.

Parameters
xInput value.

◆ smoothstep5_lower() [2/2]

float hmap::smoothstep5_lower ( float x)

Quintic smoothstep (zero derivative at 0 only).

Parameters
xInput value.

◆ smoothstep5_upper() [2/2]

float hmap::smoothstep5_upper ( float x)

Quintic smoothstep (zero derivative at 1 only).

Parameters
xInput value.

◆ smoothstep7() [2/2]

float hmap::smoothstep7 ( float x)

Seventh-order smoothstep function.

Parameters
xInput value.

◆ threshold() [2/2]

float hmap::threshold ( float x,
float x0,
float x1 )

Linear threshold.

Parameters
xInput value.
x0Lower bound.
x1Upper bound.
Returns
0 if x < x0, 1 if x > x1, linear otherwise.

◆ threshold_smooth() [2/2]

float hmap::threshold_smooth ( float x,
float x0,
float x1 )

Smooth threshold using smoothstep.

Parameters
xInput value.
x0Lower bound.
x1Upper bound.

◆ trapeze()

float hmap::trapeze ( float x,
float x0,
float x1,
float width )

Computes a trapezoidal pulse function.

Returns a value in [0, 1] with linear ramps of size width around the interval [x0, x1].

Parameters
xInput value.
x0Start of the plateau.
x1End of the plateau.
widthWidth of the rising and falling ramps.

◆ trapeze_smooth()

float hmap::trapeze_smooth ( float x,
float x0,
float x1,
float width )

Smooth trapezoidal pulse using cubic smoothstep interpolation.

Parameters
xInput value.
x0Start of the plateau.
x1End of the plateau.
widthWidth of the rising and falling ramps.

◆ triangle()

float hmap::triangle ( float x,
float vmin,
float vmax )

Triangle function between bounds.

Parameters
xInput value.
vminLower bound.
vmaxUpper bound.
Returns
0 outside bounds, peak 1 at midpoint.

◆ get_distance_function()

std::function< float(float, float)> hmap::get_distance_function ( DistanceFunction dist_fct,
DistanceFunctionAxis dfa = DistanceFunctionAxis::DFA_XY )

Return the requested distance function.

Parameters
dist_fctDistance function type.
Returns
Distance function.

◆ get_erosion_profile_function()

std::function< float(float)> hmap::get_erosion_profile_function ( const ErosionProfile & erosion_profile,
float delta,
float & profile_avg )

Generates a function representing an erosion profile based on the specified type and parameters.

This function returns a callable object (std::function) that computes the value of the specified erosion profile for a given phase angle (phi). Optionally, it can compute the average value of the profile over the range [-π, π].

Parameters
erosion_profileThe type of erosion profile to generate.
deltaA parameter that can influence the profile (depending on the profile choice).
profile_avgReference to a float that will store the average value of the profile over the range [-π, π].
Returns
A std::function<float(float)> that computes the erosion profile for a given phase angle.
Exceptions
std::invalid_argument

erosion_profile is invalid.

Note
The average value is computed using numerical integration over 50 sample points within [-π, π].

◆ get_phasor_profile_function()

std::function< float(float)> hmap::get_phasor_profile_function ( PhasorProfile phasor_profile,
float delta,
float * p_profile_avg = nullptr )

Generates a function representing a phasor profile based on the specified type and parameters.

This function returns a callable object (std::function) that computes the value of the specified phasor profile for a given phase angle (phi). Optionally, it can compute the average value of the profile over the range [-π, π].

Parameters
phasor_profileThe type of phasor profile to generate.
deltaA parameter that can influence the profile (depending on the profile choice).
p_profile_avgOptional pointer to a float. If not nullptr, it will store the average value of the profile over the range [-π, π].
Returns
A std::function<float(float)> that computes the phasor profile for a given phase angle.
Exceptions
std::invalid_argumentIftheprovided`phasor_profile`isinvalid.
Note
The average value is computed using numerical integration over 50 sample points within [-π, π].

◆ get_radial_profile_function()

std::function< float(float)> hmap::get_radial_profile_function ( RadialProfile radial_profile,
float delta )

Returns a normalized radial profile function.

The returned function maps x ∈ [0,1] to a value in [0,1], with f(0) = 0 and f(1) = 1. It is typically used for radial or distance-based falloff in procedural heightmaps.

Parameters
radial_profileRadial profile type.
deltaShape parameter used by some profiles.
Returns
Radial profile evaluation function.
Exceptions
std::invalid_argumentIftheprofileisinvalid.

◆ area_remove()

Array hmap::area_remove ( const Array & array,
float threshold_size,
float background_value = 0.f,
float fill_value = 0.f )

Remove connected components smaller than a given size threshold.

Detects connected regions in the input array and removes those whose area is smaller than threshold_size.

Parameters
arrayInput array.
threshold_sizeMinimum component size to keep.
background_valueValue used to identify background.
fill_valueValue used to replace removed components.
Returns
Array with small components removed.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {2.f, 2.f};
int seed = 1;
hmap::clamp_min(z, 0.f);
float threshold_size = 64.f * 64.f; // pixels * pixels
hmap::Array zr = hmap::area_remove(z, threshold_size);
hmap::export_banner_png("ex_area_remove_fill.png",
{z, zr, labels},
false,
true);
}
Array connected_components(const Array &array, float surface_threshold=0.f, float background_value=0.f, std::map< float, float > *p_surfaces=nullptr, std::map< float, std::array< float, 2 > > *p_centroids=nullptr)
Identifies and labels connected components within a binary or labeled array, with optional filtering ...
Definition connected_components.cpp:20
Array area_remove(const Array &array, float threshold_size, float background_value=0.f, float fill_value=0.f)
Remove connected components smaller than a given size threshold.
Definition morphology.cpp:25

Result

See unit tests: test_area_remove.cpp

◆ border()

Array hmap::border ( const Array & array,
int ir )

Apply a border algorithm to the input array using a square structure.

Parameters
arrayInput array to which the border algorithm is applied.
irRadius of the square kernel used for the border algorithm.
Returns
Array Output array with the border applied.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
hmap::clamp_min(z, 0.f);
// radius = 1 ==> 3x3 square kernel
int ir = 8;
hmap::export_banner_png("ex_morphology_base.png",
{z, zr, zd, ze, zc, zo, zg, zt, zh, zl},
false,
true);
// --- Wrapper
std::vector<hmap::MorphologyOperation> ops = {
};
// CPU
std::vector<hmap::Array> arrays = {z};
for (const auto op : ops)
{
arrays.push_back(out);
}
hmap::export_banner_png("ex_morphology_base0.png",
arrays,
false,
true);
// GPU
arrays = {z};
for (const auto op : ops)
{
arrays.push_back(out);
}
hmap::export_banner_png("ex_morphology_base1.png",
arrays,
false,
true);
}
Array morphological_operators(const Array &array, int ir, hmap::MorphologyOperation operation, MinMaxKernel kernel_type=MinMaxKernel::DISK)
Apply a morphological operation to the input array using a square kernel.
Definition wrapper.cpp:65
Array morphological_gradient(const Array &array, int ir)
Apply a morphological gradient algorithm to the input array using a square structure.
Definition morphology.cpp:213
Array morphological_black_hat(const Array &array, int ir)
Apply a morphological black hat algorithm to the input array using a square structure.
Definition morphology.cpp:207
Array morphological_top_hat(const Array &array, int ir)
Apply a morphological top hat algorithm to the input array using a square structure.
Definition morphology.cpp:227
@ MO_EROSION
Shrink structures (local minimum).
Definition morphology.hpp:50
@ MO_LAPLACIAN
Second-order operator highlighting ridges and valleys.
Definition morphology.hpp:55
@ MO_GRADIENT
Difference between dilation and erosion (edge magnitude).
Definition morphology.hpp:54
@ MO_OPENING
Erosion followed by dilation (removes small objects).
Definition morphology.hpp:51
@ MO_CLOSING
Dilation followed by erosion (fills small holes).
Definition morphology.hpp:48
@ MO_BORDER
Extract border of structures.
Definition morphology.hpp:47
@ MO_BLACK_HAT
Difference between closing and input (dark features).
Definition morphology.hpp:52
@ MO_OPENING_BY_RECONSTRUCTION
Definition morphology.hpp:57
@ MO_TOP_HAT
Difference between input and opening (bright features).
Definition morphology.hpp:53
@ MO_DILATION
Expand structures (local maximum).
Definition morphology.hpp:49
@ MO_CLOSING_BY_RECONSTRUCTION
Definition morphology.hpp:56
Array closing(const Array &array, int ir)
Apply a closing algorithm to the input array using a square structure.
Definition morphology.cpp:65
Array erosion(const Array &array, int ir)
Apply an erosion algorithm to the input array using a square structure.
Definition morphology.cpp:158
Array morphological_operators(const Array &array, int ir, hmap::MorphologyOperation operation, MinMaxKernel kernel_type=MinMaxKernel::DISK)
Apply a morphological operation to the input array using a square kernel.
Definition wrapper.cpp:12
Array opening(const Array &array, int ir)
Apply an opening algorithm to the input array using a square structure.
Definition morphology.cpp:233
Array morphological_laplacian(const Array &array, int ir)
Apply a morphological Laplacian operator to the input array using a square structure.
Definition morphology.cpp:220
Array border(const Array &array, int ir)
Apply a border algorithm to the input array using a square structure.
Definition morphology.cpp:59

Result

◆ closing()

Array hmap::closing ( const Array & array,
int ir )

Apply a closing algorithm to the input array using a square structure.

Parameters
arrayInput array to which the closing algorithm is applied.
irRadius of the square kernel used for the closing algorithm.
Returns
Array Output array with the closing applied.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
hmap::clamp_min(z, 0.f);
// radius = 1 ==> 3x3 square kernel
int ir = 8;
hmap::export_banner_png("ex_morphology_base.png",
{z, zr, zd, ze, zc, zo, zg, zt, zh, zl},
false,
true);
// --- Wrapper
std::vector<hmap::MorphologyOperation> ops = {
};
// CPU
std::vector<hmap::Array> arrays = {z};
for (const auto op : ops)
{
arrays.push_back(out);
}
hmap::export_banner_png("ex_morphology_base0.png",
arrays,
false,
true);
// GPU
arrays = {z};
for (const auto op : ops)
{
arrays.push_back(out);
}
hmap::export_banner_png("ex_morphology_base1.png",
arrays,
false,
true);
}

Result

◆ closing_by_reconstruction()

Array hmap::closing_by_reconstruction ( const Array & array,
int ir,
float k_smooth_max = 0.f )

Apply closing by reconstruction to the input array.

Performs a dilation followed by a reconstruction by erosion, filling small dark regions while preserving the shape of larger structures.

Parameters
arrayInput array.
irRadius of the structuring element.
k_smooth_maxSmoothness factor (0 for hard max).
Returns
Array Result after closing by reconstruction.

◆ contour_smoothing()

Array hmap::contour_smoothing ( const Array & array,
int ir,
float transition_ratio = 0.1f )

Smooth contour boundaries of segmented regions.

Reduces staircase artifacts on component borders by smoothing the transition zone around edges.

Parameters
arrayInput labeled or binary array.
irRadius of the smoothing kernel.
transition_ratioControls edge blending width.
Returns
Array with smoothed contours.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {8.f, 8.f};
int seed = 1;
// generate a mask with "staircaise" borders
{32, 32},
res,
seed);
hmap::clamp_min(mask, 0.f);
mask = mask.resample_to_shape_nearest(shape);
// apply mask to field
z *= mask;
// smooth contour
int ir = 8;
float transition_ratio = 0.2f;
hmap::Array contour = hmap::contour_smoothing(z, ir, transition_ratio);
hmap::export_banner_png("ex_contour_smoothing.png",
{mask, z, contour, is_non_zero(contour), z * contour},
}
Array resample_to_shape_nearest(glm::ivec2 new_shape) const
Return a resampled array of shape new_shape using nearest neighbor interpolation.
Definition methods.cpp:490
Array contour_smoothing(const Array &array, int ir, float transition_ratio=0.1f)
Smooth contour boundaries of segmented regions.
Definition morphology.cpp:78
Array is_non_zero(const Array &array)
Binary mask of non-zero elements.
Definition math.cpp:322
void make_binary(Array &array, float threshold=0.f)
Convert array values to binary using a threshold.
Definition filters.cpp:538

Result

◆ dilation()

Array hmap::dilation ( const Array & array,
int ir )

Apply a dilation algorithm to the input array using a square structure.

Parameters
arrayInput array to which the dilation algorithm is applied.
irRadius of the square kernel used for the dilation algorithm.
Returns
Array Output array with the dilation applied.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
hmap::clamp_min(z, 0.f);
// radius = 1 ==> 3x3 square kernel
int ir = 8;
hmap::export_banner_png("ex_morphology_base.png",
{z, zr, zd, ze, zc, zo, zg, zt, zh, zl},
false,
true);
// --- Wrapper
std::vector<hmap::MorphologyOperation> ops = {
};
// CPU
std::vector<hmap::Array> arrays = {z};
for (const auto op : ops)
{
arrays.push_back(out);
}
hmap::export_banner_png("ex_morphology_base0.png",
arrays,
false,
true);
// GPU
arrays = {z};
for (const auto op : ops)
{
arrays.push_back(out);
}
hmap::export_banner_png("ex_morphology_base1.png",
arrays,
false,
true);
}

Result

◆ dilation_expand_border_only()

Array hmap::dilation_expand_border_only ( const Array & array,
int ir )

Expand non-zero regions of an array by morphological dilation, while preserving the original non-zero values.

This function performs a local-maximum (dilation) operation on the input array with a given radius ir, then copies back the original non-zero values so they remain unchanged. Only the surrounding background is filled with expanded values, effectively “growing” the borders of non-zero regions.

Parameters
arrayInput 2D array where non-zero cells represent regions of interest and zero cells represent background.
irRadius of the dilation (in grid cells). Defines how far the non-zero values can expand into the background.
Returns
A new 2D array where the borders of non-zero regions have been expanded outward by up to ir cells, while the original non-zero values are kept intact.

◆ dilation_expand_min_value_border_only()

Array hmap::dilation_expand_min_value_border_only ( const Array & array)

◆ distance_transform()

Array hmap::distance_transform ( const Array & array,
bool return_squared_distance = false,
const UvTile & region = UvTile::dummy(),
ICommunicator & comm = SingleArrayComm::instance() )

Return the Euclidean distance transform.

Exact transform based on Meijster et al. algorithm [Meijster2000].

Parameters
arrayInput array to be transformed, will be converted into binary: 1 wherever input is greater than 0, 0 elsewhere.
return_squared_distanceWhether the distance returned is squared or not.
Returns
Array Reference to the output array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
shape = {2048, 2048};
// shape = {4096, 4096};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
hmap::clamp_min(z, 0.f);
hmap::Timer::Start("approx.");
hmap::Timer::Stop("approx.");
hmap::Timer::Start("manhattan");
hmap::Timer::Stop("manhattan");
z.to_png("ex_distance_transform0.png", hmap::Cmap::VIRIDIS);
d0.to_png("ex_distance_transform1.png", hmap::Cmap::VIRIDIS);
d1.to_png("ex_distance_transform2.png", hmap::Cmap::VIRIDIS);
d2.to_png("ex_distance_transform3.png", hmap::Cmap::VIRIDIS);
d3.to_png("ex_distance_transform4.png", hmap::Cmap::VIRIDIS);
}
Array distance_transform_jfa(const Array &array, bool return_squared_distance=false)
Return the Euclidean distance transform.
Definition distance_transform_jfa.cpp:18
Array distance_transform_approx(const Array &array, bool return_squared_distance=false)
Calculates an approximate distance transform of the input array.
Definition distance_transform_approx.cpp:15
Array distance_transform(const Array &array, bool return_squared_distance=false, const UvTile &region=UvTile::dummy(), ICommunicator &comm=SingleArrayComm::instance())
Return the Euclidean distance transform.
Definition distance_transform.cpp:27
Array distance_transform_manhattan(const Array &array, bool return_squared_distance=false)
Calculates the Manhattan distance transform of an array.
Definition distance_transform_approx.cpp:59

Result

See unit tests: test_distance_transform.cpp

◆ distance_transform_approx()

Array hmap::distance_transform_approx ( const Array & array,
bool return_squared_distance = false )

Calculates an approximate distance transform of the input array.

Parameters
arrayInput array to calculate the distance transform for.
return_squared_distanceOptional parameter to return squared distances. Defaults to false.
Returns
Array containing the approximate distance transform of the input array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
shape = {2048, 2048};
// shape = {4096, 4096};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
hmap::clamp_min(z, 0.f);
hmap::Timer::Start("approx.");
hmap::Timer::Stop("approx.");
hmap::Timer::Start("manhattan");
hmap::Timer::Stop("manhattan");
z.to_png("ex_distance_transform0.png", hmap::Cmap::VIRIDIS);
d0.to_png("ex_distance_transform1.png", hmap::Cmap::VIRIDIS);
d1.to_png("ex_distance_transform2.png", hmap::Cmap::VIRIDIS);
d2.to_png("ex_distance_transform3.png", hmap::Cmap::VIRIDIS);
d3.to_png("ex_distance_transform4.png", hmap::Cmap::VIRIDIS);
}

Result

See unit tests: test_distance_transform.cpp

◆ distance_transform_manhattan()

Array hmap::distance_transform_manhattan ( const Array & array,
bool return_squared_distance = false )

Calculates the Manhattan distance transform of an array.

Parameters
arrayInput array.
return_squared_distanceIf true, returns the squared Manhattan distance instead of the actual distance.
Returns
Array containing the Manhattan distance transform of the input array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
shape = {2048, 2048};
// shape = {4096, 4096};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
hmap::clamp_min(z, 0.f);
hmap::Timer::Start("approx.");
hmap::Timer::Stop("approx.");
hmap::Timer::Start("manhattan");
hmap::Timer::Stop("manhattan");
z.to_png("ex_distance_transform0.png", hmap::Cmap::VIRIDIS);
d0.to_png("ex_distance_transform1.png", hmap::Cmap::VIRIDIS);
d1.to_png("ex_distance_transform2.png", hmap::Cmap::VIRIDIS);
d2.to_png("ex_distance_transform3.png", hmap::Cmap::VIRIDIS);
d3.to_png("ex_distance_transform4.png", hmap::Cmap::VIRIDIS);
}

Result

See unit tests: test_distance_transform.cpp

◆ distance_transform_with_closest()

Array hmap::distance_transform_with_closest ( const Array & array,
Mat< glm::ivec2 > & closest,
bool return_squared_distance = false )

Return the Euclidean distance transform.

Exact transform based on Meijster et al. algorithm [Meijster2000].

Parameters
arrayInput array to be transformed, will be converted into binary: 1 wherever input is greater than 0, 0 elsewhere.
return_squared_distanceWhether the distance returned is squared or not.
Returns
Array Reference to the output array.

See unit tests: test_distance_transform.cpp

◆ erosion()

Array hmap::erosion ( const Array & array,
int ir )

Apply an erosion algorithm to the input array using a square structure.

Parameters
arrayInput array to which the erosion algorithm is applied.
irRadius of the square kernel used for the erosion algorithm.
Returns
Array Output array with the erosion applied.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
hmap::clamp_min(z, 0.f);
// radius = 1 ==> 3x3 square kernel
int ir = 8;
hmap::export_banner_png("ex_morphology_base.png",
{z, zr, zd, ze, zc, zo, zg, zt, zh, zl},
false,
true);
// --- Wrapper
std::vector<hmap::MorphologyOperation> ops = {
};
// CPU
std::vector<hmap::Array> arrays = {z};
for (const auto op : ops)
{
arrays.push_back(out);
}
hmap::export_banner_png("ex_morphology_base0.png",
arrays,
false,
true);
// GPU
arrays = {z};
for (const auto op : ops)
{
arrays.push_back(out);
}
hmap::export_banner_png("ex_morphology_base1.png",
arrays,
false,
true);
}

Result

See unit tests: test_erosion.cpp

◆ flood_fill()

void hmap::flood_fill ( Array & array,
int i,
int j,
float fill_value = 1.f,
float background_value = 0.f )

Apply a flood fill algorithm to the input array.

Parameters
arrayInput array to be filled.
iSeed point row index.
jSeed point column index.
fill_valueFilling value.
background_valueBackground value.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
z = hmap::select_interval(z, 0.5f, 0.55f);
auto z1 = z;
hmap::flood_fill(z1, 128, 128);
auto z2 = z;
hmap::flood_fill(z2, 0, 0, 0.5f);
z2.infos();
hmap::export_banner_png("ex_flood_fill.png", {z, z1, z2}, hmap::Cmap::GRAY);
}
Array gaussian_pulse(glm::ivec2 shape, float sigma, const Array *p_ctrl_param=nullptr, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit())
Return a gaussian_decay pulse kernel.
Definition primitives.cpp:233
Array select_interval(const Array &array, float value1, float value2)
Return an array with elements equal to 1 where input elements are within the bounds provided.
Definition selector.cpp:193
void flood_fill(Array &array, int i, int j, float fill_value=1.f, float background_value=0.f)
Apply a flood fill algorithm to the input array.
Definition morphology.cpp:164

Result

◆ morphological_black_hat()

Array hmap::morphological_black_hat ( const Array & array,
int ir )

Apply a morphological black hat algorithm to the input array using a square structure.

Parameters
arrayInput array to which the black hat algorithm is applied.
irRadius of the square kernel used for the black hat algorithm.
Returns
Array Output array with the black hat applied.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
hmap::clamp_min(z, 0.f);
// radius = 1 ==> 3x3 square kernel
int ir = 8;
hmap::export_banner_png("ex_morphology_base.png",
{z, zr, zd, ze, zc, zo, zg, zt, zh, zl},
false,
true);
// --- Wrapper
std::vector<hmap::MorphologyOperation> ops = {
};
// CPU
std::vector<hmap::Array> arrays = {z};
for (const auto op : ops)
{
arrays.push_back(out);
}
hmap::export_banner_png("ex_morphology_base0.png",
arrays,
false,
true);
// GPU
arrays = {z};
for (const auto op : ops)
{
arrays.push_back(out);
}
hmap::export_banner_png("ex_morphology_base1.png",
arrays,
false,
true);
}

Result

◆ morphological_gradient()

Array hmap::morphological_gradient ( const Array & array,
int ir )

Apply a morphological gradient algorithm to the input array using a square structure.

Parameters
arrayInput array to which the gradient algorithm is applied.
irRadius of the square kernel used for the gradient algorithm.
Returns
Array Output array with the gradient applied.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
hmap::clamp_min(z, 0.f);
// radius = 1 ==> 3x3 square kernel
int ir = 8;
hmap::export_banner_png("ex_morphology_base.png",
{z, zr, zd, ze, zc, zo, zg, zt, zh, zl},
false,
true);
// --- Wrapper
std::vector<hmap::MorphologyOperation> ops = {
};
// CPU
std::vector<hmap::Array> arrays = {z};
for (const auto op : ops)
{
arrays.push_back(out);
}
hmap::export_banner_png("ex_morphology_base0.png",
arrays,
false,
true);
// GPU
arrays = {z};
for (const auto op : ops)
{
arrays.push_back(out);
}
hmap::export_banner_png("ex_morphology_base1.png",
arrays,
false,
true);
}

Result

◆ morphological_laplacian()

Array hmap::morphological_laplacian ( const Array & array,
int ir )

Apply a morphological Laplacian operator to the input array using a square structure.

Compared to the classical Laplacian, this operator is more robust to noise and better preserves sharp features, as it relies on morphological extrema rather than linear differences.

Parameters
arrayInput array to which the morphological Laplacian is applied.
irRadius of the square kernel used for the underlying dilation and erosion operations.
Returns
Array Output array containing the morphological Laplacian.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
hmap::clamp_min(z, 0.f);
// radius = 1 ==> 3x3 square kernel
int ir = 8;
hmap::export_banner_png("ex_morphology_base.png",
{z, zr, zd, ze, zc, zo, zg, zt, zh, zl},
false,
true);
// --- Wrapper
std::vector<hmap::MorphologyOperation> ops = {
};
// CPU
std::vector<hmap::Array> arrays = {z};
for (const auto op : ops)
{
arrays.push_back(out);
}
hmap::export_banner_png("ex_morphology_base0.png",
arrays,
false,
true);
// GPU
arrays = {z};
for (const auto op : ops)
{
arrays.push_back(out);
}
hmap::export_banner_png("ex_morphology_base1.png",
arrays,
false,
true);
}

Result

◆ morphological_top_hat()

Array hmap::morphological_top_hat ( const Array & array,
int ir )

Apply a morphological top hat algorithm to the input array using a square structure.

Parameters
arrayInput array to which the top hat algorithm is applied.
irRadius of the square kernel used for the top hat algorithm.
Returns
Array Output array with the top hat applied.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
hmap::clamp_min(z, 0.f);
// radius = 1 ==> 3x3 square kernel
int ir = 8;
hmap::export_banner_png("ex_morphology_base.png",
{z, zr, zd, ze, zc, zo, zg, zt, zh, zl},
false,
true);
// --- Wrapper
std::vector<hmap::MorphologyOperation> ops = {
};
// CPU
std::vector<hmap::Array> arrays = {z};
for (const auto op : ops)
{
arrays.push_back(out);
}
hmap::export_banner_png("ex_morphology_base0.png",
arrays,
false,
true);
// GPU
arrays = {z};
for (const auto op : ops)
{
arrays.push_back(out);
}
hmap::export_banner_png("ex_morphology_base1.png",
arrays,
false,
true);
}

Result

◆ opening()

Array hmap::opening ( const Array & array,
int ir )

Apply an opening algorithm to the input array using a square structure.

Parameters
arrayInput array to which the opening algorithm is applied.
irRadius of the square kernel used for the opening algorithm.
Returns
Array Output array with the opening applied.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
hmap::clamp_min(z, 0.f);
// radius = 1 ==> 3x3 square kernel
int ir = 8;
hmap::export_banner_png("ex_morphology_base.png",
{z, zr, zd, ze, zc, zo, zg, zt, zh, zl},
false,
true);
// --- Wrapper
std::vector<hmap::MorphologyOperation> ops = {
};
// CPU
std::vector<hmap::Array> arrays = {z};
for (const auto op : ops)
{
arrays.push_back(out);
}
hmap::export_banner_png("ex_morphology_base0.png",
arrays,
false,
true);
// GPU
arrays = {z};
for (const auto op : ops)
{
arrays.push_back(out);
}
hmap::export_banner_png("ex_morphology_base1.png",
arrays,
false,
true);
}

Result

◆ opening_by_reconstruction()

Array hmap::opening_by_reconstruction ( const Array & array,
int ir,
float k_smooth_min = 0.f )

Apply opening by reconstruction to the input array.

Performs an erosion followed by a reconstruction by dilation, removing small bright features while preserving the shape of larger structures.

Parameters
arrayInput array.
irRadius of the structuring element.
k_smooth_minSmoothness factor (0 for hard min).
Returns
Array Result after opening by reconstruction.

◆ reconstruction_by_dilation()

Array hmap::reconstruction_by_dilation ( const Array & marker,
const Array & mask,
int ir,
float k_smooth_min = 0.f )

Perform morphological reconstruction by dilation.

Iteratively dilates the marker image while constraining values to be less than or equal to the mask. The marker must be element-wise <= mask. Optionally uses a smooth minimum controlled by k_smooth_min.

Parameters
markerInitial image (seed), must satisfy marker <= mask.
maskConstraint image (upper bound).
irRadius of the structuring element.
k_smooth_minSmoothness factor (0 for hard min).
Returns
Array Reconstructed image.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
// hmap::clamp_min(z, 0.f);
int ir = 16;
hmap::Array marker_d = hmap::gpu::erosion(z, ir);
hmap::Array marker_e = hmap::gpu::dilation(z, ir);
hmap::export_banner_png("ex_reconstruction_by_dilation.png",
{z, zd, ze, zc, zo},
true);
}
Array opening_by_reconstruction(const Array &array, int ir, float k_smooth_min=0.f, MinMaxKernel kernel_type=MinMaxKernel::DISK)
See hmap::opening_by_reconstruction.
Definition morphology_gpu.cpp:139
Array erosion(const Array &array, int ir, MinMaxKernel kernel_type=MinMaxKernel::DISK)
See hmap::erosion.
Definition morphology_gpu.cpp:91
Array dilation(const Array &array, int ir, MinMaxKernel kernel_type=MinMaxKernel::DISK)
See hmap::dilation.
Definition morphology_gpu.cpp:65
Array reconstruction_by_erosion(const Array &marker, const Array &mask, int ir, float k_smooth_max=0.f, MinMaxKernel kernel_type=MinMaxKernel::DISK)
See hmap::reconstruction_by_erosion.
Definition morphology_gpu.cpp:182
Array closing_by_reconstruction(const Array &array, int ir, float k_smooth_max=0.f, MinMaxKernel kernel_type=MinMaxKernel::DISK)
See hmap::closing_by_reconstruction.
Definition morphology_gpu.cpp:36
Array reconstruction_by_dilation(const Array &marker, const Array &mask, int ir, float k_smooth_min=0.f, MinMaxKernel kernel_type=MinMaxKernel::DISK)
See hmap::reconstruction_by_dilation.
Definition morphology_gpu.cpp:153

Result

◆ reconstruction_by_erosion()

Array hmap::reconstruction_by_erosion ( const Array & marker,
const Array & mask,
int ir,
float k_smooth_max = 0.f )

Perform morphological reconstruction by erosion.

Iteratively erodes the marker image while constraining values to be greater than or equal to the mask. The marker must be element-wise >= mask. Optionally uses a smooth maximum controlled by k_smooth_max.

Parameters
markerInitial image (seed), must satisfy marker >= mask.
maskConstraint image (lower bound).
irRadius of the structuring element.
k_smooth_maxSmoothness factor (0 for hard max).
Returns
Array Reconstructed image.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
// hmap::clamp_min(z, 0.f);
int ir = 16;
hmap::Array marker_d = hmap::gpu::erosion(z, ir);
hmap::Array marker_e = hmap::gpu::dilation(z, ir);
hmap::export_banner_png("ex_reconstruction_by_dilation.png",
{z, zd, ze, zc, zo},
true);
}

Result

◆ relative_distance_from_skeleton() [1/2]

Array hmap::relative_distance_from_skeleton ( const Array & array,
int ir_search,
bool zero_at_borders = true,
int ir_erosion = 1 )

Computes the relative distance of each non-zero cell in a binary array from the skeleton and border.

This function calculates a relative distance measure for each non-zero cell in the input array. The measure is defined as the ratio of the cell's distance to the nearest border and the combined distances to the nearest skeleton and border cells. The skeleton is computed using the Zhang-Suen skeletonization algorithm.

Parameters
arrayThe input binary array for which the relative distance map is to be calculated. Non-zero values are considered for processing.
ir_searchThe search radius for finding the nearest skeleton and border cells.
zero_at_bordersIf true, the borders of the skeletonized image will be set to zero.
ir_erosionThe erosion radius applied to the skeleton.
Returns
An array representing the relative distance map, where each cell has a value between 0 and 1. A value closer to 1 indicates proximity to the skeleton, while a value closer to 0 indicates proximity to the border.
Note
The skeleton is computed using the Zhang-Suen skeletonization algorithm.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
hmap::clamp_min(z, 0.f);
int ir = 32; // can be 0
z.to_png("ex_signed_curvature_from_distance0.png", hmap::Cmap::JET);
d.to_png("ex_signed_curvature_from_distance1.png", hmap::Cmap::JET);
sc.to_png("ex_signed_curvature_from_distance2.png", hmap::Cmap::JET);
sd.to_png("ex_signed_curvature_from_distance3.png", hmap::Cmap::JET);
}
Array signed_curvature_from_distance(const Array &array, int prefilter_ir=0)
Computes the signed curvature of the distance transform.
Definition signed_curvature_from_distance.cpp:14
Array signed_distance_transform(const Array &array, int prefilter_ir=0)
Computes a signed distance transform using curvature sign.
Definition signed_curvature_from_distance.cpp:22

Result

◆ relative_distance_from_skeleton() [2/2]

Array hmap::relative_distance_from_skeleton ( const Array & array,
const Array & skeleton,
int ir_search,
int ir_erosion = 1 )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ skeleton() [1/2]

Array hmap::skeleton ( const Array & array,
const Array & skeleton,
bool zero_at_borders = true )

Computes a skeletonized version of an array.

Extracts or refines the skeleton structure of the input array using a reference skeleton mask. Optionally forces border values to zero to avoid edge artifacts.

Parameters
arrayInput array to skeletonize.
skeletonReference skeleton mask or initialization array.
zero_at_bordersIf true, clears skeleton values at borders.
Returns
Skeletonized array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {2.f, 8.f};
int seed = 2;
hmap::remap(z, -1.f, 0.4f);
auto sk = hmap::skeleton(z);
auto skg = hmap::gpu::skeleton(z);
int ir_search = 32;
auto rdist = hmap::relative_distance_from_skeleton(z, ir_search);
auto rdistg = hmap::gpu::relative_distance_from_skeleton(z, ir_search);
hmap::export_banner_png("ex_skeleton.png",
{z, sk, skg, 0.5f * (z + sk), rdist, rdistg},
}
Array skeleton(const Array &array, bool zero_at_borders=true)
See hmap::skeleton.
Definition morphology_gpu.cpp:250
Array relative_distance_from_skeleton(const Array &array, int ir_search, bool zero_at_borders=true, int ir_erosion=1)
See hmap::relative_distance_from_skeleton.
Definition morphology_gpu.cpp:239
Array skeleton(const Array &array, const Array &skeleton, bool zero_at_borders=true)
Computes a skeletonized version of an array.
Array relative_distance_from_skeleton(const Array &array, int ir_search, bool zero_at_borders=true, int ir_erosion=1)
Computes the relative distance of each non-zero cell in a binary array from the skeleton and border.
Definition morphology.cpp:416

Result

◆ remove_endpoints()

Array hmap::remove_endpoints ( const Array & array,
int iterations = 1,
float background_value = 0.f )

Removes endpoint-like pixels from a binary/weighted array.

Iteratively filters out isolated or weakly connected pixels based on their neighborhood connectivity. Pixels matching the background value or having fewer than 2 non-background neighbors are removed.

Parameters
arrayInput array to process.
iterationsNumber of erosion-like iterations to apply.
background_valueValue considered as background (removed).
Returns
Filtered array after endpoint removal.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {2.f, 8.f};
int seed = 2;
hmap::remap(z, -1.f, 0.4f);
int iterations = 16;
auto sk0 = hmap::skeleton(z);
auto sk1 = hmap::remove_endpoints(sk0, iterations);
auto overlay = hmap::maximum(0.2f * sk0, sk1);
hmap::export_banner_png("ex_remove_endpoints.png",
{sk0, sk1, overlay},
}
Array remove_endpoints(const Array &array, int iterations=1, float background_value=0.f)
Removes endpoint-like pixels from a binary/weighted array.
Definition morphology.cpp:427

Result

◆ signed_curvature_from_distance()

Array hmap::signed_curvature_from_distance ( const Array & array,
int prefilter_ir = 0 )

Computes the signed curvature of the distance transform.

Computes the Euclidean distance transform of a binary array, optionally smooths it, then returns the divergence of the normalized gradient: κ = div( ∇d / ||∇d|| ). Positive values indicate convex regions, negative values concave regions.

Parameters
arrayBinary input (non-zero = foreground).
prefilter_irOptional smoothing radius (0 = no smoothing).
Returns
Curvature field of the distance transform.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
hmap::clamp_min(z, 0.f);
int ir = 32; // can be 0
z.to_png("ex_signed_curvature_from_distance0.png", hmap::Cmap::JET);
d.to_png("ex_signed_curvature_from_distance1.png", hmap::Cmap::JET);
sc.to_png("ex_signed_curvature_from_distance2.png", hmap::Cmap::JET);
sd.to_png("ex_signed_curvature_from_distance3.png", hmap::Cmap::JET);
}

Result

◆ signed_distance_transform()

Array hmap::signed_distance_transform ( const Array & array,
int prefilter_ir = 0 )

Computes a signed distance transform using curvature sign.

First computes the unsigned Euclidean distance transform, then assigns its sign from the curvature of the smoothed distance field: sign = sign( div( ∇d / ||∇d|| ) ).

Parameters
arrayBinary input (non-zero = foreground).
prefilter_irOptional smoothing radius for curvature evaluation.
Returns
Signed distance transform.

◆ skeleton() [2/2]

Array hmap::skeleton ( const Array & array,
bool zero_at_borders = true )

Computes the skeleton of a binary image using the Zhang-Suen skeletonization algorithm.

This function processes a binary input array to extract its skeleton by iteratively thinning the image until no further changes occur. It optionally sets the borders of the resulting skeletonized image to zero.

Parameters
arrayThe input binary array to be skeletonized. Values should typically be 0 or 1.
zero_at_bordersIf true, the borders of the resulting array will be set to zero.
Returns
The skeletonized version of the input array.
Note
This implementation is based on the algorithm described at https://github.com/krishraghuram/Zhang-Suen-Skeletonization.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {2.f, 8.f};
int seed = 2;
hmap::remap(z, -1.f, 0.4f);
auto sk = hmap::skeleton(z);
auto skg = hmap::gpu::skeleton(z);
int ir_search = 32;
auto rdist = hmap::relative_distance_from_skeleton(z, ir_search);
auto rdistg = hmap::gpu::relative_distance_from_skeleton(z, ir_search);
hmap::export_banner_png("ex_skeleton.png",
{z, sk, skg, 0.5f * (z + sk), rdist, rdistg},
}

Result

See unit tests: test_skeleton.cpp

◆ morphological_operators()

Array hmap::morphological_operators ( const Array & array,
int ir,
hmap::MorphologyOperation operation,
MinMaxKernel kernel_type = MinMaxKernel::DISK )

Apply a morphological operation to the input array using a square kernel.

Dispatches to the selected morphological operator (e.g. erosion, dilation, opening, closing, gradient, etc.).

Parameters
arrayInput array to process.
irRadius of the square structuring element.
operationMorphological operation to apply.
Returns
Array Resulting array after applying the operation.

◆ init_openmp()

bool hmap::init_openmp ( int num_threads = -1)

◆ log_openmp_info()

void hmap::log_openmp_info ( )

◆ add_kernel()

void hmap::add_kernel ( Array & array,
const Array & kernel,
int i,
int j )

Add a kernel to a specified position in an array.

This function adds the values of a smaller kernel array to the input array, centered at the specified indices (i, j). The kernel is added element-wise.

Parameters
arrayThe input array to which the kernel is added.
kernelThe kernel array to be added.
iThe row index in the input array where the kernel is centered.
jThe column index in the input array where the kernel is centered.

◆ add_kernel_maximum_smooth()

void hmap::add_kernel_maximum_smooth ( Array & array,
const Array & kernel,
float k_smooth,
int i,
int j )

Adds a smoothed maximum value from a kernel to a specified position in a 2D array.

This function applies a truncated kernel to the given array at position (ic, jc), where the kernel is truncated to ensure it fits within the array's bounds. The maximum value between the current array value and the kernel value is computed using a smoothing factor, and the result is stored back in the array.

Parameters
arrayReference to the 2D array (heightmap) where the kernel is applied.
kernelThe kernel array containing values to be applied to the array.
k_smoothThe smoothing factor used in the maximum_smooth function.
icThe x-coordinate of the center in the array where the kernel is applied.
jcThe y-coordinate of the center in the array where the kernel is applied.

The kernel is truncated to ensure it fits within the bounds of the array. After applying the kernel, the values in the array are updated with the result of the maximum_smooth function.

◆ compare()

Array hmap::compare ( const Array & a,
const Array & b,
float slice_x_pos,
float slice_y_pos )

Combines two arrays by selecting values from a or b based on a slice position.

Parameters
aFirst input array.
bSecond input array.
slice_x_posHorizontal slice position in [0,1].
slice_y_posVertical slice position in [0,1].
Returns
Output array mixing a (top-left) and b (bottom-right).

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {4.f, 4.f};
int seed = 1;
shape,
0.5f * kw,
++seed);
float slice_x_pos = 0.5f;
float slice_y_pos = 0.2f;
hmap::Array out = hmap::compare(a, b, slice_x_pos, slice_y_pos);
hmap::export_banner_png("ex_compare.png", {a, b, out}, hmap::Cmap::INFERNO);
}
Array compare(const Array &a, const Array &b, float slice_x_pos, float slice_y_pos)
Combines two arrays by selecting values from a or b based on a slice position.
Definition compare.cpp:10

Result

◆ hstack()

Array hmap::hstack ( const Array & array1,
const Array & array2 )

Horizontally stack two arrays side by side.

This function concatenates two arrays along their columns, forming a new array with the columns of the first array followed by the columns of the second array.

Parameters
array1The first array to stack.
array2The second array to stack.
Returns
Array The resulting array obtained by horizontally stacking array1 and array2.

◆ inpainting_diffusion()

Array hmap::inpainting_diffusion ( const Array & array,
const Array & mask,
int iterations )

Perform diffusion-based inpainting to fill a specified region of an array.

This function fills the region defined by a mask in the input array using diffusion-based inpainting, which propagates known values to missing regions.

Parameters
arrayInput array with missing regions.
maskMask specifying the region to be inpainted.
iterationsNumber of diffusion iterations to perform.
Returns
Array The array with the inpainted region.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {2.f, 2.f};
int seed = 1;
hmap::Array mask = hmap::select_interval(z1, 0.5f, 0.6f);
// heightmap with "holes"
hmap::Array z2 = hmap::Array(shape);
for (int i = 0; i < shape.x; i++)
for (int j = 0; j < shape.y; j++)
if (mask(i, j) == 0.f) z2(i, j) = z1(i, j);
// holes filled with inpainting
int iterations = 200;
hmap::Array z3 = hmap::inpainting_diffusion(z2, mask, iterations);
hmap::export_banner_png("ex_inpainting_diffusion.png",
{z1, z2, z3},
}
Array inpainting_diffusion(const Array &array, const Array &mask, int iterations)
Perform diffusion-based inpainting to fill a specified region of an array.
Definition inpainting_gaussian.cpp:15

Result

◆ linspace()

std::vector< float > hmap::linspace ( float start,
float stop,
int num,
bool endpoint = true )

Generate a vector of evenly spaced numbers over a specified interval.

This function creates a vector containing evenly spaced values from start to stop. The number of values is specified by num, and endpoint determines whether to include the end value in the output.

See also
linspace_jitted
Parameters
startStarting value of the interval.
stopEnd value of the interval.
numNumber of values to generate.
endpointIf true, include the end value in the output vector.
Returns
std::vector<float> Vector of evenly spaced values.

◆ linspace_jitted()

std::vector< float > hmap::linspace_jitted ( float start,
float stop,
int num,
float ratio,
int seed,
bool endpoint = true )

Generate a vector of jittered (noised) numbers over a specified interval.

This function creates a vector with values spaced over an interval but with added noise, controlled by the ratio parameter. The noise is applied to an evenly spaced grid. The seed parameter controls the randomness.

See also
linspace
Parameters
startStarting value of the interval.
stopEnd value of the interval.
numNumber of values to generate.
ratioJittering ratio applied to the evenly spaced grid.
seedRandom seed for generating jittered values.
endpointIf true, include the end value in the output vector.
Returns
std::vector<float> Vector of jittered values.

◆ logspace()

std::vector< float > hmap::logspace ( float start,
float stop,
int num,
bool endpoint = true )

Generates a logarithmically spaced vector.

Values are distributed evenly in log-space between start and stop.

Parameters
startFirst value (must be > 0)
stopLast value (must be > 0)
numNumber of samples
endpointIf true, includes stop as last element
Returns
Vector of log-spaced values

◆ fill_array_using_xy_function() [1/2]

template<typename Fn>
void hmap::fill_array_using_xy_function ( Array & array,
const UvRect & uv_rect,
const Array * p_ctrl_param,
const Array * p_noise_x,
const Array * p_noise_y,
const Array * p_stretching,
Fn && fct_xy )

Fill an array using a scalar function based on (x, y) coordinates.

This function populates an array with values computed from a scalar function that depends on (x, y) coordinates. Additional input arrays can affect the function's computation, such as control parameters, noise, and stretching.

Parameters
arrayThe array to be filled with computed values.
bboxThe bounding box of the domain specified as {xmin, xmax, ymin, ymax}.
p_ctrl_paramPointer to an array of control parameters affecting the scalar function.
p_noise_xPointer to an array of noise values along the x-direction for domain warping.
p_noise_yPointer to an array of noise values along the y-direction for domain warping.
p_stretchingPointer to an array of local wavenumber multipliers for adjusting the function.
fct_xyThe scalar function to compute values at (x, y) with an initial value.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {4.f, 4.f};
int seed = 1;
auto n = 0.4f * hmap::noise(hmap::NoiseType::PERLIN, shape, kw, ++seed);
auto z1 = hmap::Array(shape);
auto z2 = hmap::Array(shape);
nullptr,
&n,
&n,
nullptr,
p);
int subsampling = 8;
nullptr, // ctrl_param
&n,
&n,
nullptr, // stretching
p,
subsampling);
hmap::export_banner_png("ex_fill_array_using_xy_function.png",
{z1, z2},
}
Perlin (x, y) function class.
Definition functions.hpp:865
void fill_array_using_xy_function(Array &array, const UvRect &uv_rect, const Array *p_ctrl_param, const Array *p_noise_x, const Array *p_noise_y, const Array *p_stretching, Fn &&fct_xy)
Fill an array using a scalar function based on (x, y) coordinates.
Definition operator.inl:14
constexpr glm::vec4 to_vec4() const
Definition bbox2d.hpp:64
static constexpr UvRect from_vec4(const glm::vec4 &v)
Definition uv_rect.hpp:51

Result

◆ fill_array_using_xy_function() [2/2]

template<typename Fn>
void hmap::fill_array_using_xy_function ( Array & array,
const UvRect & uv_rect,
const Array * p_ctrl_param,
const Array * p_noise_x,
const Array * p_noise_y,
const Array * p_stretching,
Fn && fct_xy,
int subsampling )

Fill an array using a scalar function based on (x, y) coordinates with subsampling.

This function is similar to the one above but includes a subsampling parameter to optimize performance. The array is subsampled during computation based on the subsampling factor, which determines how frequently the scalar function is applied.

Parameters
arrayThe array to be filled with computed values.
bboxThe bounding box of the domain specified as {xmin, xmax, ymin, ymax}.
p_ctrl_paramPointer to an array of control parameters affecting the scalar function.
p_noise_xPointer to an array of noise values along the x-direction for domain warping.
p_noise_yPointer to an array of noise values along the y-direction for domain warping.
p_stretchingPointer to an array of local wavenumber multipliers for adjusting the function.
fct_xyThe scalar function to compute values at (x, y) with an initial value.
subsamplingThe factor by which the array is subsampled during computation.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {4.f, 4.f};
int seed = 1;
auto n = 0.4f * hmap::noise(hmap::NoiseType::PERLIN, shape, kw, ++seed);
auto z1 = hmap::Array(shape);
auto z2 = hmap::Array(shape);
nullptr,
&n,
&n,
nullptr,
p);
int subsampling = 8;
nullptr, // ctrl_param
&n,
&n,
nullptr, // stretching
p,
subsampling);
hmap::export_banner_png("ex_fill_array_using_xy_function.png",
{z1, z2},
}

Result

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ find_vertical_cut_path()

void hmap::find_vertical_cut_path ( const Array & error,
std::vector< int > & path_i )

Find the vertical cut path with the minimum cost using dynamic programming.

This function identifies the vertical cut path in an array from the bottom to the top that has the minimum cumulative cost.

Parameters
errorInput array containing error or cost values.
path_iOutput vector of indices representing the cut path.

◆ generate_mask()

Array hmap::generate_mask ( glm::ivec2 shape,
std::vector< int > cut_path_i,
int ir )

Generate a smooth mask based on a cut path.

This function creates a mask based on the vertical cut path indices obtained from the find_vertical_cut_path function. The mask is smoothed using a specified filtering radius.

Parameters
shapeShape of the mask to be generated.
cut_path_iVector of vertical cut path indices.
irFiltering radius for smoothing the mask.
Returns
Array The generated smooth mask.

◆ get_random_patch()

Array hmap::get_random_patch ( const Array & array,
glm::ivec2 patch_shape,
std::mt19937 & gen,
bool patch_flip = false,
bool patch_rotate = false,
bool patch_transpose = false,
std::vector< Array * > * p_secondary_arrays = nullptr,
std::vector< Array > * p_secondary_patches = nullptr )

Extracts a random sub-array (patch) from the input array, with optional transformations.

This function selects a random patch from the specified input array and applies optional transformations such as flipping, rotation, and transposition. Additionally, if a list of secondary arrays is provided, corresponding patches are extracted and transformed in the same way.

Parameters
arrayThe main input array from which the patch is extracted.
patch_shapeThe shape (dimensions) of the patch to be extracted.
genRandom number generator for selecting patch location.
patch_flipIf true, allows the patch to be flipped vertically or horizontally.
patch_rotateIf true, allows the patch to be rotated by 90 degrees.
patch_transposeIf true, allows the patch to be transposed.
p_secondary_arraysOptional pointer to a list of secondary arrays. If provided, patches will be extracted and transformed from each array in the list, with the same transformations as the primary patch.
p_secondary_patchesOptional pointer to a list for storing the transformed patches from each secondary array.
Returns
The extracted and transformed patch from the main input array.

◆ random_vector()

std::vector< float > hmap::random_vector ( float min,
float max,
int num,
int seed )

Generate a vector filled with random values within a specified range.

This function creates a vector with random values uniformly distributed between min and max. The number of values and the randomness is controlled by the seed parameter.

Parameters
minLower bound of the random values.
maxUpper bound of the random values.
numNumber of random values to generate.
seedRandom seed for generating values.
Returns
std::vector<float> Vector of random values.

◆ rescale_vector()

void hmap::rescale_vector ( std::vector< float > & vec,
float vmin,
float vmax )

Rescales the values of a vector to a specified range.

This function linearly rescales all elements in vec so that their new values lie within the range [vmin, vmax]. The rescaling is based on the current minimum and maximum values found in the input vector.

Special cases:

  • If vec is empty, the function does nothing.
  • If vmin == vmax, all elements are set to vmax.
  • If all elements of vec are equal, they are replaced by that constant value.
Parameters
vecReference to the vector of float values to rescale (modified in place).
vminDesired minimum value after rescaling.
vmaxDesired maximum value after rescaling.

◆ rescaled_vector()

std::vector< float > hmap::rescaled_vector ( const std::vector< float > & vec,
float vmin,
float vmax )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ swap()

void hmap::swap ( Array & a,
Array & b )

Swaps the contents of two Array objects.

Parameters
aFirst Array to swap.
bSecond Array to swap.

◆ vstack()

Array hmap::vstack ( const Array & array1,
const Array & array2 )

Vertically stack two arrays.

This function concatenates two arrays along their rows, resulting in a new array where the rows of the second array are stacked below the rows of the first array.

Parameters
array1The first array to be stacked.
array2The second array to be stacked.
Returns
Array The resulting array with array1 stacked on top of array2.

◆ apply_with_mask()

template<typename Fn>
void hmap::apply_with_mask ( Array & array,
const Array * p_mask,
Fn && fn )

Applies a transformation function with optional masked blending.

If p_mask is null, the function operates directly on array in-place. Otherwise, the transformation is applied on a temporary copy and blended back into array using the mask values.

Parameters
arrayInput/output array to modify.
p_maskOptional mask controlling interpolation strength.
fnTransformation function operating in-place on an Array.

◆ transform_with_mask()

template<typename Fn>
Array hmap::transform_with_mask ( const Array & array,
const Array * p_mask,
Fn && fn )

Applies a transformation function with optional masked blending.

The function computes a transformed array using fn(array). If p_mask is provided, the result is blended with the original array using the mask values.

Parameters
arrayInput array.
p_maskOptional mask controlling interpolation strength.
fnTransformation function returning a new Array.
Returns
The transformed (and optionally blended) array.

◆ dendry() [1/2]

Array hmap::dendry ( glm::ivec2 shape,
glm::vec2 kw,
std::uint32_t seed,
Array & control_function,
float eps = 0.05,
int resolution = 1,
float displacement = 0.075,
int primitives_resolution_steps = 3,
float slope_power = 2.f,
float noise_amplitude_proportion = 0.01,
bool add_control_function = true,
float control_function_overlap = 0.5f,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
const UvRect & uv_rect = UvRect::unit(),
int subsampling = 1 )

Dendry is a locally computable procedural function that generates branching patterns at various scales (see [Gaillard2019]).

Parameters
shapeArray shape.
kwNoise wavenumber with respect to a unit domain.
seedRandom seed number.
control_arrayControl array (can be of any shape, different from shape).
epsEpsilon used to bias the area where points are generated in cells.
resolutionNumber of resolutions in the noise function.
displacementMaximum displacement of segments.
primitives_resolution_stepsAdditional resolution steps in the ComputeColorPrimitives function.
slope_powerAdditional parameter to control the variation of slope on terrains.
noise_amplitude_proportionProportion of the amplitude of the control function as noise.
add_control_functionAdd control function to the output.
control_function_overlapExtent of the extension added at the domain frontiers of the control array.
p_noise_x,p_noise_yReference to the input noise arrays.
p_stretchingLocal wavenumber multiplier.
bboxDomain bounding box.
Returns
Array New array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {2.f, 2.f};
int seed = 1;
// control function based on an array
auto control_hmap = hmap::noise(hmap::NoiseType::PERLIN, shape, kw, seed);
hmap::remap(control_hmap, 0.5f, 1.f);
glm::vec2 kd = {8.f, 8.f};
auto z1 = hmap::dendry(shape, kd, seed, control_hmap);
// array-based noise function can also be used
// hmap::ArrayFunction p = hmap::ArrayFunction(z, {1.f, 1.f}, true);
auto z2 = hmap::dendry(shape, kd, seed, p, 1.f, 0.5f);
hmap::export_banner_png("ex_dendry.png",
{control_hmap, z1, z2},
}
Array dendry(glm::ivec2 shape, glm::vec2 kw, std::uint32_t seed, Array &control_function, float eps=0.05, int resolution=1, float displacement=0.075, int primitives_resolution_steps=3, float slope_power=2.f, float noise_amplitude_proportion=0.01, bool add_control_function=true, float control_function_overlap=0.5f, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit(), int subsampling=1)
Dendry is a locally computable procedural function that generates branching patterns at various scale...
Definition dendry.cpp:31

Result

◆ dendry() [2/2]

Array hmap::dendry ( glm::ivec2 shape,
glm::vec2 kw,
std::uint32_t seed,
const std::function< float(float, float, float)> & noise_function,
float noise_function_offset = 0.f,
float noise_function_scaling = 1.f,
float eps = 0.05,
int resolution = 1,
float displacement = 0.075,
int primitives_resolution_steps = 3,
float slope_power = 2.f,
float noise_amplitude_proportion = 0.01,
bool add_control_function = true,
float control_function_overlap = 0.5f,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
const UvRect & uv_rect = UvRect::unit() )

◆ diffusion_limited_aggregation()

Array hmap::diffusion_limited_aggregation ( glm::ivec2 shape,
float scale,
std::uint32_t seed,
float seeding_radius = 0.4f,
float seeding_outer_radius_ratio = 0.2f,
float slope = 8.f,
float noise_ratio = 0.2f )

Generates a diffusion-limited aggregation (DLA) pattern.

This function simulates the diffusion-limited aggregation process to generate a pattern within a grid of specified dimensions. The DLA process models particles that undergo a random walk until they stick to a seed, gradually forming complex fractal structures.

Parameters
shapeThe dimensions of the grid where the DLA pattern will be generated. It is represented as a glm::ivec2 object, where the first element is the width and the second element is the height.
scaleA scaling factor that influences the density of the particles in the DLA pattern.
seeding_radiusThe radius within which initial seeding of particles occurs. This radius defines the area where the first particles are placed.
seeding_outer_radius_ratioThe ratio between the outer seeding radius and the initial seeding radius. It determines the outer boundary for particle seeding.
slopeSlope of the talus added to the DLA pattern.
noise_ratioA parameter that controls the amount of randomness or noise introduced in the talus formation process.
seedThe seed for the random number generator, ensuring reproducibility of the pattern. The same seed will generate the same pattern.
Returns
A 2D array representing the generated DLA pattern. The array is of the same size as specified by shape.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
shape = {1024, 1024};
int seed = 0;
float scale = 1.f / 128.f;
seed,
50000);
hmap::export_banner_png("ex_diffusion_limited_aggregation.png",
{z, zt},
true);
}
Array diffusion_limited_aggregation_trimesh(glm::ivec2 shape, std::uint32_t seed, size_t control_points_count=5000, glm::vec2 seed_position={0.5f, 0.5f}, float ratio=0.98f, float stop_proba=1.f, float slope=16.f, InterpolationMethod2D interpolation_method=InterpolationMethod2D::ITP2D_DELAUNAY_GRADIENT, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr)
Definition diffusion_limited_aggregation.cpp:117
Array diffusion_limited_aggregation(glm::ivec2 shape, float scale, std::uint32_t seed, float seeding_radius=0.4f, float seeding_outer_radius_ratio=0.2f, float slope=8.f, float noise_ratio=0.2f)
Generates a diffusion-limited aggregation (DLA) pattern.
Definition diffusion_limited_aggregation.cpp:28

Result

◆ diffusion_limited_aggregation_trimesh()

Array hmap::diffusion_limited_aggregation_trimesh ( glm::ivec2 shape,
std::uint32_t seed,
size_t control_points_count = 5000,
glm::vec2 seed_position = {0.5f, 0.5f},
float ratio = 0.98f,
float stop_proba = 1.f,
float slope = 16.f,
InterpolationMethod2D interpolation_method = InterpolationMethod2D::ITP2D_DELAUNAY_GRADIENT,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr )

◆ gabor_noise()

Array hmap::gabor_noise ( glm::ivec2 shape,
float kw,
float angle,
int width,
float density,
std::uint32_t seed )

Return a sparse Gabor noise.

Parameters
shapeArray shape.
kwKernel wavenumber, with respect to a unit domain.
angleKernel angle (in degree).
widthKernel width (in pixels).
densitySpot noise density.
seedRandom seed number.
Returns
Array New array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
float kw = 4.f;
float angle = 30.f;
int width = 32;
float density = 0.05f;
std::uint32_t seed = 1;
hmap::Array z = hmap::gabor_noise(shape, kw, angle, width, density, seed);
z.to_png("ex_gabor_noise.png", hmap::Cmap::VIRIDIS);
}
Array gabor_noise(glm::ivec2 shape, float kw, float angle, int width, float density, std::uint32_t seed)
Return a sparse Gabor noise.
Definition gabor.cpp:18

Result

◆ noise()

Array hmap::noise ( NoiseType noise_type,
glm::ivec2 shape,
glm::vec2 kw,
std::uint32_t seed,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
const UvRect & uv_rect = UvRect::unit(),
float angle = 0.f,
float stretch = 1.f )

Return an array filled with coherence noise.

Parameters
noise_typeNoise type.
shapeArray shape.
kwNoise wavenumbers {kx, ky} for each directions.
seedRandom seed number.
p_noise_x,p_noise_yReference to the input noise arrays.
p_stretchingLocal wavenumber multiplier.
bboxDomain bounding box.
Returns
Array Resulting array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {4.f, 4.f};
int seed = 1;
std::vector<hmap::NoiseType> noise_list = {hmap::NoiseType::PERLIN,
hmap::Array z = hmap::Array(glm::ivec2(0, shape.y));
for (auto &noise_type : noise_list)
{
auto n = hmap::noise(noise_type, shape, kw, seed);
z = hstack(z, n);
}
z.to_png("ex_noise.png", hmap::Cmap::TERRAIN, true);
}
@ WORLEY
Worley.
Definition functions.hpp:78
@ WORLEY_DOUBLE
Worley double.
Definition functions.hpp:79
@ VALUE_DELAUNAY
Value (delaunay).
Definition functions.hpp:76
@ PERLIN_BILLOW
Perlin billow.
Definition functions.hpp:70
@ WORLEY_VALUE
Worley (cell value return).
Definition functions.hpp:80
@ PERLIN_HALF
Perlin half.
Definition functions.hpp:71
@ VALUE_LINEAR
Value (linear).
Definition functions.hpp:77
@ VALUE_CUBIC
Value (cubic).
Definition functions.hpp:75
@ VALUE
Value.
Definition functions.hpp:74

Result

◆ noise_fbm()

Array hmap::noise_fbm ( NoiseType noise_type,
glm::ivec2 shape,
glm::vec2 kw,
std::uint32_t seed,
int octaves = 8,
float weight = 0.7f,
float persistence = 0.5f,
float lacunarity = 2.f,
const Array * p_ctrl_param = nullptr,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
const UvRect & uv_rect = UvRect::unit(),
float angle = 0.f,
float stretch = 1.f,
float stretch_decay = 0.f )

Return an array filled with coherence fbm noise.

Parameters
noise_typeNoise type.
shapeArray shape.
kwNoise wavenumbers {kx, ky} for each directions.
seedRandom seed number.
octavesNumber of octaves.
weigthOctave weighting.
persistenceOctave persistence.
lacunarityDefines the wavenumber ratio between each octaves.
p_ctrl_paramReference to the control parameter array (acts as a multiplier for the weight parameter).
p_noise_x,p_noise_yReference to the input noise arrays.
p_stretchingLocal wavenumber multiplier.
bboxDomain bounding box.
Returns
Array Fractal noise.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {4.f, 4.f};
int seed = 1;
std::vector<hmap::NoiseType> noise_list = {hmap::NoiseType::PERLIN,
auto ctrl_array = hmap::noise(hmap::NoiseType::PERLIN, shape, kw, seed);
hmap::remap(ctrl_array);
// fbm
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_fbm(noise_type,
shape,
kw,
seed,
8,
0.7f,
0.5f,
2.f,
&ctrl_array);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm0.png",
arrays,
true);
}
// iq
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_iq(noise_type, shape, kw, seed);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm1.png",
arrays,
true);
}
// jordan
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_jordan(noise_type, shape, kw, seed);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm2.png",
arrays,
true);
}
// pingpong
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_pingpong(noise_type, shape, kw, seed);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm3.png",
arrays,
true);
}
// ridged
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_ridged(noise_type, shape, kw, seed);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm4.png",
arrays,
true);
}
// swiss
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_swiss(noise_type, shape, kw, seed);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm5.png",
arrays,
true);
}
// Parberry
{
auto n = hmap::noise_parberry(shape, kw, seed);
n.to_png("ex_noise_fbm6.png", hmap::Cmap::TERRAIN, true);
}
// stretched fbm (isotropic, stretched, stretched with octave decay)
{
auto n0 = hmap::noise_fbm(hmap::NoiseType::PERLIN, shape, kw, seed);
shape,
kw,
seed,
8,
0.7f,
0.5f,
2.f,
nullptr,
nullptr,
nullptr,
{0.f, 1.f, 0.f, 1.f},
30.f,
4.f,
0.f);
shape,
kw,
seed,
8,
0.7f,
0.5f,
2.f,
nullptr,
nullptr,
nullptr,
{0.f, 1.f, 0.f, 1.f},
30.f,
4.f,
0.5f);
hmap::export_banner_png("ex_noise_fbm7.png",
{n0, n1, n2},
true);
}
}
Array noise_iq(NoiseType noise_type, glm::ivec2 shape, glm::vec2 kw, std::uint32_t seed, int octaves=8, float weight=0.7f, float persistence=0.5f, float lacunarity=2.f, float gradient_scale=0.05f, const Array *p_ctrl_param=nullptr, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit(), float angle=0.f, float stretch=1.f, float stretch_decay=0.f)
Return an array filled with coherence fbm noise.
Definition noise.cpp:124
Array noise_parberry(glm::ivec2 shape, glm::vec2 kw, std::uint32_t seed, int octaves=8, float weight=0.7f, float persistence=0.5f, float lacunarity=2.f, float mu=1.02f, const Array *p_ctrl_param=nullptr, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit(), float angle=0.f, float stretch=1.f, float stretch_decay=0.f)
Return an array filled with coherent fbm Parberry variant of Perlin noise.
Definition noise.cpp:228
Array noise_ridged(NoiseType noise_type, glm::ivec2 shape, glm::vec2 kw, std::uint32_t seed, int octaves=8, float weight=0.7f, float persistence=0.5f, float lacunarity=2.f, float k_smoothing=0.1f, const Array *p_ctrl_param=nullptr, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit(), float angle=0.f, float stretch=1.f, float stretch_decay=0.f)
Return an array filled with coherence fbm ridged noise.
Definition noise.cpp:319
Array noise_swiss(NoiseType noise_type, glm::ivec2 shape, glm::vec2 kw, std::uint32_t seed, int octaves=8, float weight=0.7f, float persistence=0.5f, float lacunarity=2.f, float warp_scale=0.1f, const Array *p_ctrl_param=nullptr, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit(), float angle=0.f, float stretch=1.f, float stretch_decay=0.f)
Return an array filled with coherence fbm swiss noise.
Definition noise.cpp:425
Array noise_pingpong(NoiseType noise_type, glm::ivec2 shape, glm::vec2 kw, std::uint32_t seed, int octaves=8, float weight=0.7f, float persistence=0.5f, float lacunarity=2.f, const Array *p_ctrl_param=nullptr, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit(), float angle=0.f, float stretch=1.f, float stretch_decay=0.f)
Return an array filled with coherence fbm pingpong noise.
Definition noise.cpp:272
Array noise_jordan(NoiseType noise_type, glm::ivec2 shape, glm::vec2 kw, std::uint32_t seed, int octaves=8, float weight=0.7f, float persistence=0.5f, float lacunarity=2.f, float warp0=0.4f, float damp0=1.f, float warp_scale=0.4f, float damp_scale=1.f, const Array *p_ctrl_param=nullptr, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit(), float angle=0.f, float stretch=1.f, float stretch_decay=0.f)
Return an array filled with coherence fbm noise.
Definition noise.cpp:173

Result

◆ noise_iq()

Array hmap::noise_iq ( NoiseType noise_type,
glm::ivec2 shape,
glm::vec2 kw,
std::uint32_t seed,
int octaves = 8,
float weight = 0.7f,
float persistence = 0.5f,
float lacunarity = 2.f,
float gradient_scale = 0.05f,
const Array * p_ctrl_param = nullptr,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
const UvRect & uv_rect = UvRect::unit(),
float angle = 0.f,
float stretch = 1.f,
float stretch_decay = 0.f )

Return an array filled with coherence fbm noise.

Parameters
noise_typeNoise type.
shapeArray shape.
kwNoise wavenumbers {kx, ky} for each directions.
seedRandom seed number.
octavesNumber of octaves.
weigthOctave weighting.
persistenceOctave persistence.
lacunarityDefines the wavenumber ratio between each octaves.
gradient_scaleGradient scale.
p_ctrl_paramReference to the control parameter array (acts as a multiplier for the weight parameter).
p_noise_x,p_noise_yReference to the input noise arrays.
p_stretchingLocal wavenumber multiplier.
bboxDomain bounding box.
Returns
Array Fractal noise.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {4.f, 4.f};
int seed = 1;
std::vector<hmap::NoiseType> noise_list = {hmap::NoiseType::PERLIN,
auto ctrl_array = hmap::noise(hmap::NoiseType::PERLIN, shape, kw, seed);
hmap::remap(ctrl_array);
// fbm
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_fbm(noise_type,
shape,
kw,
seed,
8,
0.7f,
0.5f,
2.f,
&ctrl_array);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm0.png",
arrays,
true);
}
// iq
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_iq(noise_type, shape, kw, seed);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm1.png",
arrays,
true);
}
// jordan
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_jordan(noise_type, shape, kw, seed);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm2.png",
arrays,
true);
}
// pingpong
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_pingpong(noise_type, shape, kw, seed);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm3.png",
arrays,
true);
}
// ridged
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_ridged(noise_type, shape, kw, seed);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm4.png",
arrays,
true);
}
// swiss
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_swiss(noise_type, shape, kw, seed);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm5.png",
arrays,
true);
}
// Parberry
{
auto n = hmap::noise_parberry(shape, kw, seed);
n.to_png("ex_noise_fbm6.png", hmap::Cmap::TERRAIN, true);
}
// stretched fbm (isotropic, stretched, stretched with octave decay)
{
auto n0 = hmap::noise_fbm(hmap::NoiseType::PERLIN, shape, kw, seed);
shape,
kw,
seed,
8,
0.7f,
0.5f,
2.f,
nullptr,
nullptr,
nullptr,
{0.f, 1.f, 0.f, 1.f},
30.f,
4.f,
0.f);
shape,
kw,
seed,
8,
0.7f,
0.5f,
2.f,
nullptr,
nullptr,
nullptr,
{0.f, 1.f, 0.f, 1.f},
30.f,
4.f,
0.5f);
hmap::export_banner_png("ex_noise_fbm7.png",
{n0, n1, n2},
true);
}
}

Result

◆ noise_jordan()

Array hmap::noise_jordan ( NoiseType noise_type,
glm::ivec2 shape,
glm::vec2 kw,
std::uint32_t seed,
int octaves = 8,
float weight = 0.7f,
float persistence = 0.5f,
float lacunarity = 2.f,
float warp0 = 0.4f,
float damp0 = 1.f,
float warp_scale = 0.4f,
float damp_scale = 1.f,
const Array * p_ctrl_param = nullptr,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
const UvRect & uv_rect = UvRect::unit(),
float angle = 0.f,
float stretch = 1.f,
float stretch_decay = 0.f )

Return an array filled with coherence fbm noise.

Parameters
noise_typeNoise type.
shapeArray shape.
kwNoise wavenumbers {kx, ky} for each directions.
seedRandom seed number.
octavesNumber of octaves.
weigthOctave weighting.
persistenceOctave persistence.
lacunarityDefines the wavenumber ratio between each octaves.
warp0Initial warp scale.
damp0Initial damp scale.
warp_scaleWarp scale.
damp_scaleDamp scale.
p_ctrl_paramReference to the control parameter array (acts as a multiplier for the weight parameter).
p_noise_x,p_noise_yReference to the input noise arrays.
p_stretchingLocal wavenumber multiplier.
bboxDomain bounding box.
Returns
Array Fractal noise.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {4.f, 4.f};
int seed = 1;
std::vector<hmap::NoiseType> noise_list = {hmap::NoiseType::PERLIN,
auto ctrl_array = hmap::noise(hmap::NoiseType::PERLIN, shape, kw, seed);
hmap::remap(ctrl_array);
// fbm
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_fbm(noise_type,
shape,
kw,
seed,
8,
0.7f,
0.5f,
2.f,
&ctrl_array);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm0.png",
arrays,
true);
}
// iq
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_iq(noise_type, shape, kw, seed);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm1.png",
arrays,
true);
}
// jordan
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_jordan(noise_type, shape, kw, seed);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm2.png",
arrays,
true);
}
// pingpong
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_pingpong(noise_type, shape, kw, seed);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm3.png",
arrays,
true);
}
// ridged
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_ridged(noise_type, shape, kw, seed);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm4.png",
arrays,
true);
}
// swiss
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_swiss(noise_type, shape, kw, seed);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm5.png",
arrays,
true);
}
// Parberry
{
auto n = hmap::noise_parberry(shape, kw, seed);
n.to_png("ex_noise_fbm6.png", hmap::Cmap::TERRAIN, true);
}
// stretched fbm (isotropic, stretched, stretched with octave decay)
{
auto n0 = hmap::noise_fbm(hmap::NoiseType::PERLIN, shape, kw, seed);
shape,
kw,
seed,
8,
0.7f,
0.5f,
2.f,
nullptr,
nullptr,
nullptr,
{0.f, 1.f, 0.f, 1.f},
30.f,
4.f,
0.f);
shape,
kw,
seed,
8,
0.7f,
0.5f,
2.f,
nullptr,
nullptr,
nullptr,
{0.f, 1.f, 0.f, 1.f},
30.f,
4.f,
0.5f);
hmap::export_banner_png("ex_noise_fbm7.png",
{n0, n1, n2},
true);
}
}

Result

◆ noise_parberry()

Array hmap::noise_parberry ( glm::ivec2 shape,
glm::vec2 kw,
std::uint32_t seed,
int octaves = 8,
float weight = 0.7f,
float persistence = 0.5f,
float lacunarity = 2.f,
float mu = 1.02f,
const Array * p_ctrl_param = nullptr,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
const UvRect & uv_rect = UvRect::unit(),
float angle = 0.f,
float stretch = 1.f,
float stretch_decay = 0.f )

Return an array filled with coherent fbm Parberry variant of Perlin noise.

Parameters
shapeArray shape.
kwNoise wavenumbers {kx, ky} for each directions.
seedRandom seed number.
octavesNumber of octaves.
weigthOctave weighting.
persistenceOctave persistence.
lacunarityDefines the wavenumber ratio between each octaves.
muGradient magnitude exponent.
p_ctrl_paramReference to the control parameter array (acts as a multiplier for the weight parameter).
p_noise_x,p_noise_yReference to the input noise arrays.
p_stretchingLocal wavenumber multiplier.
bboxDomain bounding box.
Returns
Array Fractal noise.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {4.f, 4.f};
int seed = 1;
std::vector<hmap::NoiseType> noise_list = {hmap::NoiseType::PERLIN,
auto ctrl_array = hmap::noise(hmap::NoiseType::PERLIN, shape, kw, seed);
hmap::remap(ctrl_array);
// fbm
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_fbm(noise_type,
shape,
kw,
seed,
8,
0.7f,
0.5f,
2.f,
&ctrl_array);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm0.png",
arrays,
true);
}
// iq
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_iq(noise_type, shape, kw, seed);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm1.png",
arrays,
true);
}
// jordan
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_jordan(noise_type, shape, kw, seed);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm2.png",
arrays,
true);
}
// pingpong
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_pingpong(noise_type, shape, kw, seed);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm3.png",
arrays,
true);
}
// ridged
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_ridged(noise_type, shape, kw, seed);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm4.png",
arrays,
true);
}
// swiss
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_swiss(noise_type, shape, kw, seed);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm5.png",
arrays,
true);
}
// Parberry
{
auto n = hmap::noise_parberry(shape, kw, seed);
n.to_png("ex_noise_fbm6.png", hmap::Cmap::TERRAIN, true);
}
// stretched fbm (isotropic, stretched, stretched with octave decay)
{
auto n0 = hmap::noise_fbm(hmap::NoiseType::PERLIN, shape, kw, seed);
shape,
kw,
seed,
8,
0.7f,
0.5f,
2.f,
nullptr,
nullptr,
nullptr,
{0.f, 1.f, 0.f, 1.f},
30.f,
4.f,
0.f);
shape,
kw,
seed,
8,
0.7f,
0.5f,
2.f,
nullptr,
nullptr,
nullptr,
{0.f, 1.f, 0.f, 1.f},
30.f,
4.f,
0.5f);
hmap::export_banner_png("ex_noise_fbm7.png",
{n0, n1, n2},
true);
}
}

Result

◆ noise_pingpong()

Array hmap::noise_pingpong ( NoiseType noise_type,
glm::ivec2 shape,
glm::vec2 kw,
std::uint32_t seed,
int octaves = 8,
float weight = 0.7f,
float persistence = 0.5f,
float lacunarity = 2.f,
const Array * p_ctrl_param = nullptr,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
const UvRect & uv_rect = UvRect::unit(),
float angle = 0.f,
float stretch = 1.f,
float stretch_decay = 0.f )

Return an array filled with coherence fbm pingpong noise.

Parameters
noise_typeNoise type.
shapeArray shape.
kwNoise wavenumbers {kx, ky} for each directions.
seedRandom seed number.
octavesNumber of octaves.
weigthOctave weighting.
persistenceOctave persistence.
lacunarityDefines the wavenumber ratio between each octaves.
p_ctrl_paramReference to the control parameter array (acts as a multiplier for the weight parameter).
p_noise_x,p_noise_yReference to the input noise arrays.
p_stretchingLocal wavenumber multiplier.
bboxDomain bounding box.
Returns
Array Fractal noise.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {4.f, 4.f};
int seed = 1;
std::vector<hmap::NoiseType> noise_list = {hmap::NoiseType::PERLIN,
auto ctrl_array = hmap::noise(hmap::NoiseType::PERLIN, shape, kw, seed);
hmap::remap(ctrl_array);
// fbm
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_fbm(noise_type,
shape,
kw,
seed,
8,
0.7f,
0.5f,
2.f,
&ctrl_array);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm0.png",
arrays,
true);
}
// iq
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_iq(noise_type, shape, kw, seed);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm1.png",
arrays,
true);
}
// jordan
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_jordan(noise_type, shape, kw, seed);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm2.png",
arrays,
true);
}
// pingpong
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_pingpong(noise_type, shape, kw, seed);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm3.png",
arrays,
true);
}
// ridged
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_ridged(noise_type, shape, kw, seed);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm4.png",
arrays,
true);
}
// swiss
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_swiss(noise_type, shape, kw, seed);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm5.png",
arrays,
true);
}
// Parberry
{
auto n = hmap::noise_parberry(shape, kw, seed);
n.to_png("ex_noise_fbm6.png", hmap::Cmap::TERRAIN, true);
}
// stretched fbm (isotropic, stretched, stretched with octave decay)
{
auto n0 = hmap::noise_fbm(hmap::NoiseType::PERLIN, shape, kw, seed);
shape,
kw,
seed,
8,
0.7f,
0.5f,
2.f,
nullptr,
nullptr,
nullptr,
{0.f, 1.f, 0.f, 1.f},
30.f,
4.f,
0.f);
shape,
kw,
seed,
8,
0.7f,
0.5f,
2.f,
nullptr,
nullptr,
nullptr,
{0.f, 1.f, 0.f, 1.f},
30.f,
4.f,
0.5f);
hmap::export_banner_png("ex_noise_fbm7.png",
{n0, n1, n2},
true);
}
}

Result

◆ noise_ridged()

Array hmap::noise_ridged ( NoiseType noise_type,
glm::ivec2 shape,
glm::vec2 kw,
std::uint32_t seed,
int octaves = 8,
float weight = 0.7f,
float persistence = 0.5f,
float lacunarity = 2.f,
float k_smoothing = 0.1f,
const Array * p_ctrl_param = nullptr,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
const UvRect & uv_rect = UvRect::unit(),
float angle = 0.f,
float stretch = 1.f,
float stretch_decay = 0.f )

Return an array filled with coherence fbm ridged noise.

Parameters
noise_typeNoise type.
shapeArray shape.
kwNoise wavenumbers {kx, ky} for each directions.
seedRandom seed number.
octavesNumber of octaves.
weigthOctave weighting.
persistenceOctave persistence.
lacunarityDefines the wavenumber ratio between each octaves.
k_smoothingSmoothing parameter.
p_ctrl_paramReference to the control parameter array (acts as a multiplier for the weight parameter).
p_noise_x,p_noise_yReference to the input noise arrays.
p_stretchingLocal wavenumber multiplier.
bboxDomain bounding box.
Returns
Array Fractal noise.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {4.f, 4.f};
int seed = 1;
std::vector<hmap::NoiseType> noise_list = {hmap::NoiseType::PERLIN,
auto ctrl_array = hmap::noise(hmap::NoiseType::PERLIN, shape, kw, seed);
hmap::remap(ctrl_array);
// fbm
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_fbm(noise_type,
shape,
kw,
seed,
8,
0.7f,
0.5f,
2.f,
&ctrl_array);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm0.png",
arrays,
true);
}
// iq
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_iq(noise_type, shape, kw, seed);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm1.png",
arrays,
true);
}
// jordan
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_jordan(noise_type, shape, kw, seed);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm2.png",
arrays,
true);
}
// pingpong
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_pingpong(noise_type, shape, kw, seed);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm3.png",
arrays,
true);
}
// ridged
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_ridged(noise_type, shape, kw, seed);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm4.png",
arrays,
true);
}
// swiss
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_swiss(noise_type, shape, kw, seed);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm5.png",
arrays,
true);
}
// Parberry
{
auto n = hmap::noise_parberry(shape, kw, seed);
n.to_png("ex_noise_fbm6.png", hmap::Cmap::TERRAIN, true);
}
// stretched fbm (isotropic, stretched, stretched with octave decay)
{
auto n0 = hmap::noise_fbm(hmap::NoiseType::PERLIN, shape, kw, seed);
shape,
kw,
seed,
8,
0.7f,
0.5f,
2.f,
nullptr,
nullptr,
nullptr,
{0.f, 1.f, 0.f, 1.f},
30.f,
4.f,
0.f);
shape,
kw,
seed,
8,
0.7f,
0.5f,
2.f,
nullptr,
nullptr,
nullptr,
{0.f, 1.f, 0.f, 1.f},
30.f,
4.f,
0.5f);
hmap::export_banner_png("ex_noise_fbm7.png",
{n0, n1, n2},
true);
}
}

Result

◆ noise_slope()

Array hmap::noise_slope ( NoiseType noise_type,
glm::ivec2 shape,
glm::vec2 kw,
std::uint32_t seed,
int octaves = 8,
float weight = 0.7f,
float persistence = 0.5f,
float lacunarity = 2.f,
float gradient_scale = 0.5f,
float slope_power = 2.f,
float octave_blend = 0.5f,
float bias_angle = 0.f,
float bias_strength = 0.f,
const Array * p_ctrl_param = nullptr,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
const UvRect & uv_rect = UvRect::unit(),
float angle = 0.f,
float stretch = 1.f,
float stretch_decay = 0.f )

Return an array filled with slope-weighted coherence fbm noise.

Modulates higher-octave amplitude by the accumulated low-frequency gradient norm so that flat areas remain smooth while steep slopes develop rugosity.

Parameters
noise_typeNoise type.
shapeArray shape.
kwNoise wavenumbers {kx, ky} for each directions.
seedRandom seed number.
octavesNumber of octaves.
weightOctave weighting.
persistenceOctave persistence.
lacunarityDefines the wavenumber ratio between each octaves.
gradient_scaleGradient scale influence.
slope_powerExponent controlling slope transition sharpness.
octave_blendRate at which higher octaves become slope-masked.
bias_anglePreferred slope direction angle in degrees.
bias_strengthDirectional bias strength in [0, 1].
p_ctrl_paramReference to the control parameter array (acts as a multiplier for the weight parameter).
p_noise_x,p_noise_yReference to the input noise arrays.
bboxDomain bounding box.
angleStretching direction angle in degrees.
stretchStretching factor along the direction.
stretch_decayProgressive decay of stretching across octaves.
Returns
Array Fractal noise.

◆ noise_swiss()

Array hmap::noise_swiss ( NoiseType noise_type,
glm::ivec2 shape,
glm::vec2 kw,
std::uint32_t seed,
int octaves = 8,
float weight = 0.7f,
float persistence = 0.5f,
float lacunarity = 2.f,
float warp_scale = 0.1f,
const Array * p_ctrl_param = nullptr,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
const UvRect & uv_rect = UvRect::unit(),
float angle = 0.f,
float stretch = 1.f,
float stretch_decay = 0.f )

Return an array filled with coherence fbm swiss noise.

Parameters
noise_typeNoise type.
shapeArray shape.
kwNoise wavenumbers {kx, ky} for each directions.
seedRandom seed number.
octavesNumber of octaves.
weigthOctave weighting.
persistenceOctave persistence.
lacunarityDefines the wavenumber ratio between each octaves.
warp_scaleWarp scale.
p_ctrl_paramReference to the control parameter array (acts as a multiplier for the weight parameter).
p_noise_x,p_noise_yReference to the input noise arrays.
p_stretchingLocal wavenumber multiplier.
bboxDomain bounding box.
Returns
Array Fractal noise.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {4.f, 4.f};
int seed = 1;
std::vector<hmap::NoiseType> noise_list = {hmap::NoiseType::PERLIN,
auto ctrl_array = hmap::noise(hmap::NoiseType::PERLIN, shape, kw, seed);
hmap::remap(ctrl_array);
// fbm
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_fbm(noise_type,
shape,
kw,
seed,
8,
0.7f,
0.5f,
2.f,
&ctrl_array);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm0.png",
arrays,
true);
}
// iq
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_iq(noise_type, shape, kw, seed);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm1.png",
arrays,
true);
}
// jordan
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_jordan(noise_type, shape, kw, seed);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm2.png",
arrays,
true);
}
// pingpong
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_pingpong(noise_type, shape, kw, seed);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm3.png",
arrays,
true);
}
// ridged
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_ridged(noise_type, shape, kw, seed);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm4.png",
arrays,
true);
}
// swiss
{
std::vector<hmap::Array> arrays;
for (auto &noise_type : noise_list)
{
auto n = hmap::noise_swiss(noise_type, shape, kw, seed);
arrays.push_back(n);
}
hmap::export_banner_png("ex_noise_fbm5.png",
arrays,
true);
}
// Parberry
{
auto n = hmap::noise_parberry(shape, kw, seed);
n.to_png("ex_noise_fbm6.png", hmap::Cmap::TERRAIN, true);
}
// stretched fbm (isotropic, stretched, stretched with octave decay)
{
auto n0 = hmap::noise_fbm(hmap::NoiseType::PERLIN, shape, kw, seed);
shape,
kw,
seed,
8,
0.7f,
0.5f,
2.f,
nullptr,
nullptr,
nullptr,
{0.f, 1.f, 0.f, 1.f},
30.f,
4.f,
0.f);
shape,
kw,
seed,
8,
0.7f,
0.5f,
2.f,
nullptr,
nullptr,
nullptr,
{0.f, 1.f, 0.f, 1.f},
30.f,
4.f,
0.5f);
hmap::export_banner_png("ex_noise_fbm7.png",
{n0, n1, n2},
true);
}
}

Result

◆ worley_double()

Array hmap::worley_double ( glm::ivec2 shape,
glm::vec2 kw,
std::uint32_t seed,
float ratio = 0.5f,
float k = 0.f,
const Array * p_ctrl_param = nullptr,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
const UvRect & uv_rect = UvRect::unit() )

Return an array filled with the maximum of two Worley (cellular) noises.

Parameters
shapeArray shape.
kwNoise wavenumbers {kx, ky} for each directions, with respect to a unit domain.
seedRandom seed number.
ratioAmplitude ratio between each Worley noise.
kTransition smoothing parameter.
p_ctrl_paramReference to the control parameter array (acts as a multiplier for the ratio parameter).
p_noise_x,p_noise_yReference to the input noise arrays.
p_stretchingLocal wavenumber multiplier.
bboxDomain bounding box.
Returns
Array Noise.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {4.f, 4.f};
int seed = 1;
float ratio = 0.5f;
float k = 0.1f;
// ratio multiplier
shape,
kw,
seed++);
hmap::remap(ctrl_array);
hmap::Array z = hmap::worley_double(shape, kw, seed, ratio, k, &ctrl_array);
z.to_png("ex_worley_double.png", hmap::Cmap::TERRAIN, true);
}
Array worley_double(glm::ivec2 shape, glm::vec2 kw, std::uint32_t seed, float ratio=0.5f, float k=0.f, const Array *p_ctrl_param=nullptr, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit())
Return an array filled with the maximum of two Worley (cellular) noises.
Definition worley.cpp:16

Result

◆ get_primitive_base()

Array hmap::get_primitive_base ( const PrimitiveType & primitive_type,
const glm::ivec2 & shape,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
glm::vec2 center = {0.5f, 0.5f},
const UvRect & uv_rect = UvRect::unit() )

Generates a primitive shape as a 2D array.

Parameters
primitive_typeType of primitive to generate.
shapeOutput array resolution.
p_noise_xOptional X-direction noise modulation.
p_noise_yOptional Y-direction noise modulation.
centerCenter position of the primitive (normalized).
bboxBounding box of the primitive (normalized).
Returns
The generated primitive as an Array.

◆ band()

Array hmap::band ( glm::ivec2 shape,
float angle,
float length = 0.5f,
float width = 0.1f,
RadialProfile profile = RadialProfile::RP_SMOOTHSTEP,
float profile_param = 0.f,
const Array * p_noise_r = nullptr,
const Array * p_noise_offset = nullptr,
glm::vec2 center = {0.5f, 0.5f},
const UvRect & uv_rect = UvRect::unit() )

Generate a bounded band (capsule) mask.

Creates a 0 to 1 mask shaped as a capsule: the value is 1 on a core segment defined by center, angle and length, and falls off to 0 at a distance width from the segment, following the requested radial profile. Typical uses: mountain-range envelopes, island-chain arc envelopes and, with a length larger than the domain, latitude bands / polar caps (place center on or beyond a domain edge).

Parameters
shapeOutput array shape.
angleBand orientation angle in degrees.
lengthCore segment length in normalized domain units. A zero length degenerates to a radial bump.
widthFalloff half-width in normalized domain units.
profileRadial profile used for the falloff.
profile_paramAdditional parameter for the profile.
p_noise_rOptional noise array used to locally perturb the falloff distance (edge displacement).
p_noise_offsetOptional noise array used to locally offset the band axis position (normalized by width).
centerBand center in normalized coordinates.
bboxDomain bounding box.
Returns
Generated band mask in [0, 1].

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
// --- Base noise for displacement
glm::vec2 kw = {8.f, 8.f};
std::uint32_t seed = 0;
auto dr = 0.2f * hmap::noise_fbm(hmap::NoiseType::PERLIN, shape, kw, ++seed);
// --- Band
// raw primitive
float angle = 30.f;
float length = 0.4f;
float width = 0.15f;
auto z1 = hmap::band(shape, angle, length, width);
// with edge displacement noise
auto z2 = hmap::band(shape,
angle,
length,
width,
0.f,
&dr);
// latitude band / polar cap: long band centered on the bottom edge
auto z3 = hmap::band(shape,
0.f,
4.f,
0.2f,
0.f,
&dr,
nullptr,
{0.5f, 0.f});
hmap::export_banner_png("ex_band.png",
{z1, z2, z3},
true);
}
Array band(glm::ivec2 shape, float angle, float length=0.5f, float width=0.1f, RadialProfile profile=RadialProfile::RP_SMOOTHSTEP, float profile_param=0.f, const Array *p_noise_r=nullptr, const Array *p_noise_offset=nullptr, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit())
Generate a bounded band (capsule) mask.
Definition band.cpp:17

Result

◆ biquad_pulse()

Array hmap::biquad_pulse ( glm::ivec2 shape,
float gain = 1.f,
const Array * p_ctrl_param = nullptr,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
glm::vec2 center = {0.5f, 0.5f},
const UvRect & uv_rect = UvRect::unit() )

Return a 'biquadratic pulse'.

Parameters
shapeArray shape.
gainGain (the higher, the steeper).
p_ctrl_paramReference to the control parameter array (acts as a multiplier for the gain parameter).
p_noise_x,p_noise_yReference to the input noise arrays.
p_stretchingLocal wavenumber multiplier.
bboxDomain bounding box.
Returns
Array Perlin billow noise.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
// with control array
glm::vec2 kw = {4.f, 4.f};
int seed = 1;
shape,
kw,
seed);
hmap::remap(ctrl_array, 0.8f, 1.2f);
hmap::Array z2 = hmap::biquad_pulse(shape, 1.f, &ctrl_array);
hmap::export_banner_png("ex_biquad_pulse.png",
{z1, z2},
false);
}
Array biquad_pulse(glm::ivec2 shape, float gain=1.f, const Array *p_ctrl_param=nullptr, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit())
Return a 'biquadratic pulse'.
Definition primitives.cpp:18

Result

◆ biquad_pulse_x()

Array hmap::biquad_pulse_x ( glm::ivec2 shape,
const UvRect & uv_rect = UvRect::unit() )

◆ biquad_pulse_y()

Array hmap::biquad_pulse_y ( glm::ivec2 shape,
const UvRect & uv_rect = UvRect::unit() )

◆ bump()

Array hmap::bump ( glm::ivec2 shape,
float gain = 1.f,
const Array * p_ctrl_param = nullptr,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
glm::vec2 center = {0.5f, 0.5f},
const UvRect & uv_rect = UvRect::unit() )

Return a bump.

Parameters
shapeArray shape.
gainGain (the higher, the steeper the bump).
p_ctrl_paramReference to the control parameter array (acts as a multiplier for the gain parameter).
p_noise_x,p_noise_yReference to the input noise arrays.
p_stretchingLocal wavenumber multiplier.
centerPrimitive reference center.
bboxDomain bounding box.
Returns
Array Perlin billow noise.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
hmap::Array z1 = hmap::bump(shape);
// with control array
glm::vec2 kw = {4.f, 4.f};
int seed = 1;
shape,
kw,
seed);
hmap::remap(ctrl_array, 0.8f, 1.2f);
hmap::Array z2 = hmap::bump(shape, 1.f, &ctrl_array);
hmap::Array z3 = hmap::bump_lorentzian(shape, 0.2f, 0.5f, &ctrl_array);
hmap::export_banner_png("ex_bump.png",
{z1, z2, z3},
false);
}
Array bump_lorentzian(glm::ivec2 shape, float shape_factor=0.5f, float radius=0.5f, const Array *p_ctrl_param=nullptr, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit())
Generates a 2D Lorentzian bump pattern.
Definition primitives.cpp:116
Array bump(glm::ivec2 shape, float gain=1.f, const Array *p_ctrl_param=nullptr, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit())
Return a bump.
Definition primitives.cpp:89

Result

◆ bump_lorentzian()

Array hmap::bump_lorentzian ( glm::ivec2 shape,
float shape_factor = 0.5f,
float radius = 0.5f,
const Array * p_ctrl_param = nullptr,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
glm::vec2 center = {0.5f, 0.5f},
const UvRect & uv_rect = UvRect::unit() )

Generates a 2D Lorentzian bump pattern.

This function fills an array with values computed from a normalized Lorentzian-shaped bump function. The bump is centered at a given position, has a specified radius, and can vary in width depending on a control parameter. Optional noise arrays can be applied to perturb the x and y coordinates before evaluation.

The Lorentzian function is normalized so that it returns 1.0 at the center and smoothly decays to 0.0 at the radius boundary. Outside the radius, the value is exactly 0.

Parameters
shapeDimensions of the output array (width, height).
width_factorScaling factor controlling the bump width relative to the control parameter.
radiusRadius of the bump in the coordinate space of bbox.
p_ctrl_paramOptional pointer to an array of per-pixel control parameters. If provided, it modulates the width of the Lorentzian bump.
p_noise_xOptional pointer to an array of x-offset noise values. Values are added to the x coordinate before evaluation.
p_noise_yOptional pointer to an array of y-offset noise values. Values are added to the y coordinate before evaluation.
centerCenter of the bump in the coordinate space of bbox.
bboxBounding box (xmin, ymin, xmax, ymax) defining the coordinate space for the array.
Returns
A new Array object of size shape containing the bump pattern.
Note
The function normalizes the Lorentzian curve so that the maximum value is 1 at the center and smoothly decays to 0 at the boundary defined by radius.
See also
fill_array_using_xy_function

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
hmap::Array z1 = hmap::bump(shape);
// with control array
glm::vec2 kw = {4.f, 4.f};
int seed = 1;
shape,
kw,
seed);
hmap::remap(ctrl_array, 0.8f, 1.2f);
hmap::Array z2 = hmap::bump(shape, 1.f, &ctrl_array);
hmap::Array z3 = hmap::bump_lorentzian(shape, 0.2f, 0.5f, &ctrl_array);
hmap::export_banner_png("ex_bump.png",
{z1, z2, z3},
false);
}

Result

◆ checkerboard()

Array hmap::checkerboard ( glm::ivec2 shape,
glm::vec2 kw,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
const UvRect & uv_rect = UvRect::unit() )

Return a checkerboard heightmap.

Parameters
shapeArray shape.
kwNoise wavenumber with respect to a unit domain.
p_noise_x,p_noise_yReference to the input noise arrays.
p_stretchingLocal wavenumber multiplier.
bboxDomain bounding box.
Returns
Array New array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {4.f, 3.f};
z.to_png("ex_checkerboard.png", hmap::Cmap::GRAY);
}
Array checkerboard(glm::ivec2 shape, glm::vec2 kw, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit())
Return a checkerboard heightmap.
Definition checkerboard.cpp:16

Result

◆ cone() [2/2]

Array hmap::cone ( glm::ivec2 shape,
float slope,
float apex_elevation = 1.f,
bool smooth_profile = false,
glm::vec2 center = {0.5f, 0.5f},
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
const UvRect & uv_rect = UvRect::unit() )

Generates a synthetic conical mountain heightmap.

This function creates a simple cone-shaped elevation field centered at a given position. The cone profile follows a linear slope until it reaches the talus angle, resembling volcanic cones or alluvial fans. Optional displacement noise fields can be applied to perturb the cone shape.

Parameters
shapeOutput array shape (resolution in x and y).
slopeSlope angle of the cone (controls steepness of the sides).
centerCenter of the cone in normalized coordinates (default = {0.5f, 0.5f}).
p_noise_xOptional pointer to external displacement noise field (X-axis).
p_noise_yOptional pointer to external displacement noise field (Y-axis).
bboxBounding box of the generation domain in normalized coordinates (default = {0.f, 1.f, 0.f, 1.f}).
Returns
Array containing the generated conical heightmap.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
hmap::Array z1 = hmap::cone(shape, 4.f);
hmap::Array z2 = hmap::cone_sigmoid(shape, 0.8f);
hmap::Array z3 = hmap::cone_complex(shape, 1.2f);
hmap::export_banner_png("ex_cone.png", {z1, z2, z3}, hmap::Cmap::MAGMA);
}
Array cone_sigmoid(glm::ivec2 shape, float alpha, float radius=0.5f, glm::vec2 center={0.5f, 0.5f}, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit())
Generates a smooth conical heightmap using a sigmoid-based profile.
Definition cone.cpp:162
Array cone_complex(glm::ivec2 shape, float alpha, float radius=0.5f, bool smooth_profile=true, float valley_amp=0.2f, int valley_nb=5, float valley_decay_ratio=0.5f, float valley_angle0=15.f, const ErosionProfile &erosion_profile=ErosionProfile::EP_TRIANGLE_GRENIER, float erosion_delta=0.01f, float radial_waviness_amp=0.05f, float radial_waviness_kw=2.f, float bias_angle=30.f, float bias_amp=0.75f, float bias_exponent=1.f, glm::vec2 center={0.5f, 0.5f}, const Array *p_ctrl_param=nullptr, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit())
Generates a complex conical heightfield with valleys, directional bias, and radial waviness.
Definition cone.cpp:75
Array cone(glm::ivec2 shape)
Generates a cone-shaped kernel array.
Definition kernels.cpp:62

Result

◆ cone_complex()

Array hmap::cone_complex ( glm::ivec2 shape,
float alpha,
float radius = 0.5f,
bool smooth_profile = true,
float valley_amp = 0.2f,
int valley_nb = 5,
float valley_decay_ratio = 0.5f,
float valley_angle0 = 15.f,
const ErosionProfile & erosion_profile = ErosionProfile::EP_TRIANGLE_GRENIER,
float erosion_delta = 0.01f,
float radial_waviness_amp = 0.05f,
float radial_waviness_kw = 2.f,
float bias_angle = 30.f,
float bias_amp = 0.75f,
float bias_exponent = 1.f,
glm::vec2 center = {0.5f, 0.5f},
const Array * p_ctrl_param = nullptr,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
const UvRect & uv_rect = UvRect::unit() )

Generates a complex conical heightfield with valleys, directional bias, and radial waviness.

This function procedurally constructs an island-like cone shape inside a 2D array. The height at each position is determined from the normalized radial distance to the center, with optional modulation by valleys, directional bias, and radial waviness. An erosion profile is applied to shape the valleys, and an optional control map can modulate the valley amplitude locally. The resulting height values are clamped to [0, 1].

Parameters
shapeOutput array dimensions (width, height).
alphaExponent controlling the steepness of the cone slope.
radiusEffective radius of the island (in coordinate space units).
valley_ampGlobal amplitude of valley depressions.
valley_nbNumber of valleys around the island.
valley_decay_ratioControls how valley amplitude decays toward the center.
valley_angle0Angular offset of the first valley (in degrees).
erosion_profileErosion profile type used for shaping valley cross-sections.
erosion_deltaSmoothing parameter for the erosion profile function.
radial_waviness_ampAmplitude of radial sinusoidal perturbations (coastal waviness).
radial_waviness_kwFrequency multiplier for radial waviness.
bias_angleDirection (in degrees) of the slope bias (e.g. wind or sun exposure).
bias_ampAmplitude of the directional bias effect.
bias_exponentControls how bias strength varies with radius.
centerCenter position of the cone in coordinate space.
p_ctrl_paramOptional control array; its values modulate the local valley amplitude. If nullptr, the valley amplitude is uniform.
p_noise_xOptional X-displacement noise field for coordinate perturbation.
p_noise_yOptional Y-displacement noise field for coordinate perturbation.
bboxBounding box defining the world coordinates covered by the array.
Returns
A 2D Array containing the generated heightfield values in the range [0, 1].

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
hmap::Array z1 = hmap::cone(shape, 4.f);
hmap::Array z2 = hmap::cone_sigmoid(shape, 0.8f);
hmap::Array z3 = hmap::cone_complex(shape, 1.2f);
hmap::export_banner_png("ex_cone.png", {z1, z2, z3}, hmap::Cmap::MAGMA);
}

Result

◆ cone_sigmoid()

Array hmap::cone_sigmoid ( glm::ivec2 shape,
float alpha,
float radius = 0.5f,
glm::vec2 center = {0.5f, 0.5f},
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
const UvRect & uv_rect = UvRect::unit() )

Generates a smooth conical heightmap using a sigmoid-based profile.

This function creates a 2D array representing a cone shape centered at a given position. The height decreases radially from the apex according to a sigmoid-shaped falloff, producing a smooth, rounded cone rather than a sharp linear one. Optionally, displacement noise can be applied along the X and Y axes to perturb the cone surface.

Parameters
shapeDimensions of the output array (width, height).
alphaPeak elevation value of the cone (controls maximum height).
radiusRadius of the cone base, expressed in normalized [0, 1] units relative to the bounding box.
centerNormalized coordinates of the cone’s center (default = {0.5, 0.5}).
p_noise_xOptional pointer to an array representing horizontal displacement noise (nullptr for none).
p_noise_yOptional pointer to an array representing vertical displacement noise (nullptr for none).
bboxBounding box of the generated region in (xmin, xmax, ymin, ymax) order.
Returns
A 2D Array object containing the generated conical heightmap.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
hmap::Array z1 = hmap::cone(shape, 4.f);
hmap::Array z2 = hmap::cone_sigmoid(shape, 0.8f);
hmap::Array z3 = hmap::cone_complex(shape, 1.2f);
hmap::export_banner_png("ex_cone.png", {z1, z2, z3}, hmap::Cmap::MAGMA);
}

Result

◆ constant()

Array hmap::constant ( glm::ivec2 shape,
float value = 0.f )

Return a constant value array.

Parameters
shapeArray shape.
valueFilling value.
Returns
Array New array.

◆ cubic_pulse() [2/3]

Array hmap::cubic_pulse ( glm::ivec2 shape,
const Array * p_noise_x,
const Array * p_noise_y,
glm::vec2 center = {0.5f, 0.5f},
const UvRect & uv_rect = UvRect::unit() )

Generates a cubic pulse array.

◆ disk() [2/2]

Array hmap::disk ( glm::ivec2 shape,
float radius,
float slope = 1.f,
const Array * p_ctrl_param = nullptr,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
glm::vec2 center = {0.5f, 0.5f},
const UvRect & uv_rect = UvRect::unit() )

Generates a disk-shaped heightmap with optional modifications.

This function creates a 2D array representing a disk shape with a specified radius, slope, and other optional parameters such as control parameters, noise, and stretching for additional customization.

Parameters
shapeDimensions of the output array (width, height).
radiusRadius of the disk, in normalized coordinates (0.0 to 1.0).
slopeSlope of the disk edge transition. A larger value makes the edge transition sharper. Defaults to 1.0.
p_ctrl_paramOptional pointer to an Array controlling custom parameters for the disk generation.
p_noise_xOptional pointer to an Array for adding noise in the x-direction.
p_noise_yOptional pointer to an Array for adding noise in the y-direction.
p_stretchingOptional pointer to an Array for stretching the disk horizontally or vertically.
centerCenter of the disk in normalized coordinates (0.0 to 1.0). Defaults to {0.5, 0.5}.
bboxBounding box for the disk in normalized coordinates {x_min, x_max, y_min, y_max}. Defaults to {0.0, 1.0, 0.0, 1.0}.
Returns
A 2D array representing the generated disk shape.

Result

◆ gaussian_pulse()

Array hmap::gaussian_pulse ( glm::ivec2 shape,
float sigma,
const Array * p_ctrl_param = nullptr,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
glm::vec2 center = {0.5f, 0.5f},
const UvRect & uv_rect = UvRect::unit() )

Return a gaussian_decay pulse kernel.

Parameters
shapeArray shape.
sigmaGaussian sigma (in pixels).
p_ctrl_paramReference to the control parameter array (acts as a multiplier for the half-width parameter).
p_noise_x,p_noise_yReference to the input noise arrays.
p_stretchingLocal wavenumber multiplier.
centerPrimitive reference center.
centerPrimitive reference center.
bboxDomain bounding box.
Returns
Array

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
float sigma = 0.2f;
hmap::Array z1 = hmap::gaussian_pulse(shape, sigma);
// with control array
glm::vec2 kw = {4.f, 4.f};
int seed = 1;
shape,
kw,
seed);
hmap::remap(ctrl_array, 0.5f, 1.5f);
hmap::Array z2 = hmap::gaussian_pulse(shape, sigma, &ctrl_array);
hmap::export_banner_png("ex_gaussian_pulse.png",
{z1, z2},
false);
}

Result

◆ multisteps()

Array hmap::multisteps ( glm::ivec2 shape,
float angle,
float r = 1.2f,
int nsteps = 8,
float elevation_exponent = 0.7f,
float shape_gain = 4.f,
float scale = 0.5f,
float outer_slope = 0.1f,
const Array * p_ctrl_param = nullptr,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
const glm::vec2 & center = {0.5f, 0.5f},
const BBox2D & bbox = BBox2D::unit() )

Generate a multi-step height profile along a rotated axis.

Constructs an Array where values follow a sequence of geometric steps blended with an optional linear transition. Steps are rotated by the given angle, can be shaped with an exponent, and may be modulated by optional control and noise fields.

Parameters
shapeOutput array resolution.
angleRotation angle in degrees.
rGeometric ratio between successive step widths.
nstepsNumber of steps.
elevation_exponentExponent shaping step heights.
shape_gainGain used to reshape intra-step transitions.
scaleScale of the step axis.
outer_slopeSlope outside the [0,1] axis interval.
p_ctrl_paramOptional control parameter array.
p_noise_xOptional x-axis noise array.
p_noise_yOptional y-axis noise array.
centerCenter of the step axis.
bboxBounding box of the domain.
Returns
Generated Array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
auto z1 = hmap::multisteps(shape, 10.f);
// with built-in default noise
std::uint32_t seed = 0;
auto z2 = hmap::gpu::multisteps(shape, 10.f, seed);
hmap::export_banner_png("ex_multisteps.png", {z1, z2}, hmap::Cmap::INFERNO);
}
Array multisteps(glm::ivec2 shape, float angle, std::uint32_t seed, glm::vec2 kw={2.f, 2.f}, float noise_amp=0.1f, float noise_rugosity=0.f, bool noise_inflate=true, float r=1.2f, int nsteps=8, float elevation_exponent=0.7f, float shape_gain=4.f, float scale=0.5f, float outer_slope=0.1f, const Array *p_ctrl_param=nullptr, const glm::vec2 &center={0.5f, 0.5f}, const BBox2D &bbox=BBox2D::unit())
GPU-accelerated multi-step height generation with procedural noise.
Definition multisteps.cpp:93
Array multisteps(glm::ivec2 shape, float angle, float r=1.2f, int nsteps=8, float elevation_exponent=0.7f, float shape_gain=4.f, float scale=0.5f, float outer_slope=0.1f, const Array *p_ctrl_param=nullptr, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const glm::vec2 &center={0.5f, 0.5f}, const BBox2D &bbox=BBox2D::unit())
Generate a multi-step height profile along a rotated axis.
Definition multisteps.cpp:18

Result

◆ paraboloid()

Array hmap::paraboloid ( glm::ivec2 shape,
float angle,
float a,
float b,
float v0 = 0.f,
bool reverse_x = false,
bool reverse_y = false,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
glm::vec2 center = {0.5f, 0.5f},
const UvRect & uv_rect = UvRect::unit() )

Return a paraboloid.

Parameters
shapeArray shape.
angleRotation angle.
aCurvature parameter, first principal axis.
bCurvature parameter, second principal axis.
v0Value at the paraboloid center.
reverse_xReverse coefficient of first principal axis.
reverse_yReverse coefficient of second principal axis.
p_base_elevationReference to the control parameter array (acts as a multiplier for the weight parameter).
p_noise_x,p_noise_yReference to the input noise arrays.
p_stretchingLocal wavenumber multiplier.
centerPrimitive reference center.
bboxDomain bounding box.
Returns
Output array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
float angle = 15.f;
auto z = hmap::paraboloid(shape, angle, 1.f, 0.5f);
z.to_png("ex_paraboloid.png", hmap::Cmap::INFERNO);
}
Array paraboloid(glm::ivec2 shape, float angle, float a, float b, float v0=0.f, bool reverse_x=false, bool reverse_y=false, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit())
Return a paraboloid.
Definition primitives.cpp:260

Result

◆ polar_shape()

Array hmap::polar_shape ( glm::ivec2 shape,
float rmin = 0.1f,
float rmax = 0.3f,
float aspect_ratio = 1.f,
float smoothing_width = 0.1f,
bool square_base = false,
float angle = 15.f,
float sector_angle = 90.f,
float vmin = 0.5f,
float kt_value = 0.f,
float kr_border = 0.f,
float kr_border_ratio = 0.1f,
const Array * p_noise_r = nullptr,
const Array * p_noise_theta = nullptr,
glm::vec2 center = {0.5f, 0.5f},
const UvRect & uv_rect = UvRect::unit() )

Generate a polar-based shape mask with optional angular and radial perturbations.

Creates a 2D scalar field defined in polar space using radial bounds, sector masking, aspect ratio deformation, and optional noise offsets on radius and angle.

Parameters
shapeOutput array shape.
rminInner radius.
rmaxOuter radius.
aspect_ratioElliptical aspect ratio applied on Y axis.
smoothing_widthSmoothing width for radial and angular transitions.
square_baseIf true, remaps the shape toward a square profile.
angleGlobal rotation angle in degrees.
sector_angleAngular opening removed from the shape in degrees.
vminMinimum angular modulation value.
kt_valueAngular modulation frequency.
kr_borderAngular modulation frequency for the outer border.
kr_border_ratioBlend factor for outer border modulation.
p_noise_rOptional radial noise offset field.
p_noise_thetaOptional angular noise offset field.
centerShape center.
bboxBounding box used for grid generation.
Returns
Generated scalar field.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
auto z1 = hmap::polar_shape(shape);
float rmin = 0.3f;
float rmax = 0.4f;
float aspect_ratio = 2.f;
float smoothing_width = 0.1f;
bool square_base = true;
auto z2 = hmap::polar_shape(shape,
rmin,
rmax,
aspect_ratio,
smoothing_width,
square_base);
hmap::export_banner_png("ex_polar_shape.png", {z1, z2}, hmap::Cmap::MAGMA);
}
Array polar_shape(glm::ivec2 shape, float rmin=0.1f, float rmax=0.3f, float aspect_ratio=1.f, float smoothing_width=0.1f, bool square_base=false, float angle=15.f, float sector_angle=90.f, float vmin=0.5f, float kt_value=0.f, float kr_border=0.f, float kr_border_ratio=0.1f, const Array *p_noise_r=nullptr, const Array *p_noise_theta=nullptr, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit())
Generate a polar-based shape mask with optional angular and radial perturbations.
Definition polar_shape.cpp:17

Result

◆ quad_surface()

Array hmap::quad_surface ( glm::ivec2 shape,
float c00 = 0.f,
float c10 = 0.f,
float c01 = 0.f,
float c11 = 0.f,
const Array * p_ctrl_param = nullptr,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
const UvRect & uv_rect = UvRect::unit() )

Generates a surface defined by the four corner values of the domain.

Interpolates values across the domain using a quadratic / bilinear surface function derived from the four corner elevations.

Parameters
shapeDimensions of the output array (width, height).
c00Elevation at bottom-left corner (xmin, ymin).
c10Elevation at bottom-right corner (xmax, ymin).
c01Elevation at top-left corner (xmin, ymax).
c11Elevation at top-right corner (xmax, ymax).
p_ctrl_paramOptional pointer to a control parameter array (multiplier).
p_noise_xOptional pointer to x-direction displacement noise array.
p_noise_yOptional pointer to y-direction displacement noise array.
bboxBounding box defining the domain coordinates (xmin, xmax, ymin, ymax).
Returns
Array containing the generated quadratic surface.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
// surface defined by 4 corner elevations: c00, c10, c01, c11
hmap::Array z1 = hmap::quad_surface(shape, 0.f, 1.f, 0.5f, 0.f);
// another surface configuration
hmap::Array z2 = hmap::quad_surface(shape, 1.f, 0.2f, 0.3f, 0.8f);
hmap::export_banner_png("ex_quad_surface.png",
{z1, z2},
false);
}
Array quad_surface(glm::ivec2 shape, float c00=0.f, float c10=0.f, float c01=0.f, float c11=0.f, const Array *p_ctrl_param=nullptr, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit())
Generates a surface defined by the four corner values of the domain.
Definition primitives.cpp:303

Result

◆ rectangle()

Array hmap::rectangle ( glm::ivec2 shape,
float rx,
float ry,
float angle,
float slope = 1.f,
const Array * p_ctrl_param = nullptr,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
glm::vec2 center = {0.5f, 0.5f},
const UvRect & uv_rect = UvRect::unit() )

Generates a rectangle-shaped heightmap with optional modifications.

This function creates a 2D array representing a rectangle with specified dimensions, rotation, and optional parameters for customization such as control parameters, noise, and stretching.

Parameters
shapeDimensions of the output array (width, height).
rxHalf-width of the rectangle, in normalized coordinates (0.0 to 1.0).
ryHalf-height of the rectangle, in normalized coordinates (0.0 to 1.0).
angleRotation angle of the rectangle in radians. Positive values rotate counterclockwise.
slopeSlope of the rectangle edge transition. A larger value makes the edge transition sharper. Defaults to 1.0.
p_ctrl_paramOptional pointer to an Array controlling custom parameters for the rectangle generation.
p_noise_xOptional pointer to an Array for adding noise in the x-direction.
p_noise_yOptional pointer to an Array for adding noise in the y-direction.
p_stretchingOptional pointer to an Array for stretching the rectangle horizontally or vertically.
centerCenter of the rectangle in normalized coordinates (0.0 to 1.0). Defaults to {0.5, 0.5}.
bboxBounding box for the rectangle in normalized coordinates {x_min, x_max, y_min, y_max}. Defaults to {0.0, 1.0, 0.0, 1.0}.
Returns
A 2D array representing the generated rectangle shape.

Result

◆ slope()

Array hmap::slope ( glm::ivec2 shape,
float angle,
float slope,
const Array * p_ctrl_param = nullptr,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
glm::vec2 center = {0.5f, 0.5f},
const UvRect & uv_rect = UvRect::unit() )

Return an array corresponding to a slope with a given overall.

Parameters
shapeArray shape.
angleOverall rotation angle (in degree).
slopeSlope (assuming a unit domain).
p_ctrl_paramReference to the control parameter array (acts as a multiplier for the slope parameter).
p_noise_x,p_noise_yReference to the input noise arrays.
p_stretchingLocal coordinate multiplier.
centerPrimitive reference center.
bboxDomain bounding box.
Returns
Array New array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {4.f, 4.f};
int seed = 1;
hmap::Array noise = 0.2f *
float slope = 1.f;
hmap::Array oblique = hmap::slope(shape, 30.f, slope, nullptr, &noise);
hmap::slope(shape, 0.f, slope, nullptr, &noise, &noise),
hmap::slope(shape, 90.f, slope, nullptr, &noise, &noise),
0.1f);
// with control array
shape,
kw,
seed);
hmap::remap(ctrl_array, 0.8f, 1.2f);
hmap::Array wctrl = hmap::slope(shape, 30.f, slope, &ctrl_array);
hmap::export_banner_png("ex_slope.png",
{oblique, valley, wctrl},
}
Array maximum_smooth(const Array &array1, const Array &array2, float k=0.2)
Return the polynomial cubic smooth element-wise maximum of two arrays.
Definition range.cpp:323

Result

◆ smooth_cosine() [2/2]

Array hmap::smooth_cosine ( glm::ivec2 shape,
const Array * p_noise_x,
const Array * p_noise_y,
glm::vec2 center = {0.5f, 0.5f},
const UvRect & uv_rect = UvRect::unit() )

Generates a smooth cosine array.

◆ step()

Array hmap::step ( glm::ivec2 shape,
float angle,
float slope,
const Array * p_ctrl_param = nullptr,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
glm::vec2 center = {0.5f, 0.5f},
const UvRect & uv_rect = UvRect::unit() )

Return a step function (Heaviside with an optional talus slope at the transition).

Parameters
shapeArray shape.
angleOverall rotation angle (in degree).
slopeStep slope (assuming a unit domain).
p_ctrl_paramReference to the control parameter array (acts as a multiplier for the slope parameter).
p_noise_x,p_noise_yReference to the input noise arrays.
p_stretchingLocal coordinate multiplier.
centerPrimitive reference center.
bboxDomain bounding box.
Returns
Array New array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
float angle = 30.f;
float talus = 4.f;
float kw = 4.f;
std::uint32_t seed = 1;
shape,
{kw, kw},
seed,
8,
0.f);
auto z1 = hmap::step(shape, angle, talus);
auto z2 = hmap::step(shape, angle, talus, nullptr, &noise);
// with control array
shape,
{kw, kw},
seed);
hmap::remap(ctrl_array, 0.8f, 1.2f);
hmap::Array z3 = hmap::step(shape, angle, talus, &ctrl_array);
hmap::export_banner_png("ex_step.png", {z1, z2, z3}, hmap::Cmap::INFERNO);
}
Array step(glm::ivec2 shape, float angle, float slope, const Array *p_ctrl_param=nullptr, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit())
Return a step function (Heaviside with an optional talus slope at the transition).
Definition primitives.cpp:424

Result

◆ swirl()

void hmap::swirl ( Array & dx,
Array & dy,
float amplitude = 1.f,
float exponent = 1.f,
const Array * p_noise = nullptr,
const UvRect & uv_rect = UvRect::unit() )

Generate displacements dx and dy to apply a swirl effect to another primitve.

Parameters
dx[out]'x' displacement (unit domain scale).
dy[out]'y' displacement (unit domain scale).
amplitudeDisplacement amplitude.
exponentDistance exponent.
p_noiseeference to the input noise array.
bboxDomain bounding box.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
shape,
res,
seed + 1);
hmap::Array dx = hmap::Array(shape);
hmap::Array dy = hmap::Array(shape);
hmap::swirl(dx, dy, 1.f, 1.f);
shape,
res,
seed,
&dx,
&dy);
hmap::swirl(dx, dy, 1.f, 1.f, &noise);
shape,
res,
seed,
&dx,
&dy);
hmap::export_banner_png("ex_swirl.png", {z0, z1, z2}, hmap::Cmap::INFERNO);
}
void swirl(Array &dx, Array &dy, float amplitude=1.f, float exponent=1.f, const Array *p_noise=nullptr, const UvRect &uv_rect=UvRect::unit())
Generate displacements dx and dy to apply a swirl effect to another primitve.
Definition swirl.cpp:12

Result

◆ wave_dune()

Array hmap::wave_dune ( glm::ivec2 shape,
float kw,
float angle,
float xtop,
float xbottom,
float phase_shift = 0.f,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
glm::vec2 center = {0.5f, 0.5f},
const UvRect & uv_rect = UvRect::unit() )

Return a dune shape wave.

Parameters
shapeArray shape.
kwWavenumber with respect to a unit domain.
angleOverall rotation angle (in degree).
xtopRelative location of the top of the dune profile (in [0, 1]).
xbottomRelative location of the foot of the dune profile (in [0, 1]).
phase_shiftPhase shift (in radians).
p_noise_x,p_noise_yReference to the input noise arrays.
p_stretchingLocal wavenumber multiplier.
centerPrimitive reference center.
bboxDomain bounding box.
Returns
Array New array.

◆ wave_sine()

Array hmap::wave_sine ( glm::ivec2 shape,
float kw,
float angle,
float phase_shift = 0.f,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
glm::vec2 center = {0.5f, 0.5f},
const UvRect & uv_rect = UvRect::unit() )

Return a sine wave.

Parameters
shapeArray shape.
kwWavenumber with respect to a unit domain.
angleOverall rotation angle (in degree).
phase_shiftPhase shift (in radians).
p_noise_x,p_noise_yReference to the input noise arrays.
p_stretchingLocal wavenumber multiplier.
centerPrimitive reference center.
bboxDomain bounding box.
Returns
Array New array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
float kw = 4.f;
float angle = 30.f;
std::uint32_t seed = 1;
shape,
{kw, kw},
seed,
8,
0.f);
auto zt = hmap::wave_triangular(shape, kw, angle, 0.8f);
auto zq = hmap::wave_square(shape, kw, angle);
auto zs = hmap::wave_sine(shape, kw, angle);
auto zd = hmap::wave_dune(shape, kw, angle, 0.5f, 0.7f, 0.f);
auto ztn = hmap::wave_triangular(shape, kw, angle, 0.8f, 0.f, &noise);
auto zqn = hmap::wave_square(shape, kw, angle, 0.f, &noise);
auto zsn = hmap::wave_sine(shape, kw, angle, 0.f, &noise);
auto zdn = hmap::wave_dune(shape, kw, angle, 0.5f, 0.7f, 0.f, &noise);
hmap::export_banner_png("ex_wave0.png",
{zt, zq, zs, zd},
hmap::export_banner_png("ex_wave1.png",
{ztn, zqn, zsn, zdn},
}
Array wave_square(glm::ivec2 shape, float kw, float angle, float phase_shift=0.f, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit())
Return a square wave.
Definition wave.cpp:75
Array wave_triangular(glm::ivec2 shape, float kw, float angle, float slant_ratio, float phase_shift=0.f, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit())
Return a triangular wave.
Definition wave.cpp:104
Array wave_dune(glm::ivec2 shape, float kw, float angle, float xtop, float xbottom, float phase_shift=0.f, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit())
Return a dune shape wave.
Definition wave.cpp:13
Array wave_sine(glm::ivec2 shape, float kw, float angle, float phase_shift=0.f, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit())
Return a sine wave.
Definition wave.cpp:46

Result

◆ wave_square()

Array hmap::wave_square ( glm::ivec2 shape,
float kw,
float angle,
float phase_shift = 0.f,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
glm::vec2 center = {0.5f, 0.5f},
const UvRect & uv_rect = UvRect::unit() )

Return a square wave.

Parameters
shapeArray shape.
kwWavenumber with respect to a unit domain.
angleOverall rotation angle (in degree).
phase_shiftPhase shift (in radians).
p_noise_x,p_noise_yReference to the input noise arrays.
p_stretchingLocal wavenumber multiplier.
centerPrimitive reference center.
bboxDomain bounding box.
Returns
Array New array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
float kw = 4.f;
float angle = 30.f;
std::uint32_t seed = 1;
shape,
{kw, kw},
seed,
8,
0.f);
auto zt = hmap::wave_triangular(shape, kw, angle, 0.8f);
auto zq = hmap::wave_square(shape, kw, angle);
auto zs = hmap::wave_sine(shape, kw, angle);
auto zd = hmap::wave_dune(shape, kw, angle, 0.5f, 0.7f, 0.f);
auto ztn = hmap::wave_triangular(shape, kw, angle, 0.8f, 0.f, &noise);
auto zqn = hmap::wave_square(shape, kw, angle, 0.f, &noise);
auto zsn = hmap::wave_sine(shape, kw, angle, 0.f, &noise);
auto zdn = hmap::wave_dune(shape, kw, angle, 0.5f, 0.7f, 0.f, &noise);
hmap::export_banner_png("ex_wave0.png",
{zt, zq, zs, zd},
hmap::export_banner_png("ex_wave1.png",
{ztn, zqn, zsn, zdn},
}

Result

◆ wave_triangular()

Array hmap::wave_triangular ( glm::ivec2 shape,
float kw,
float angle,
float slant_ratio,
float phase_shift = 0.f,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
glm::vec2 center = {0.5f, 0.5f},
const UvRect & uv_rect = UvRect::unit() )

Return a triangular wave.

Parameters
shapeArray shape.
kwWavenumber with respect to a unit domain.
angleOverall rotation angle (in degree).
slant_ratioRelative location of the triangle apex, in [0, 1].
phase_shiftPhase shift (in radians).
p_noise_x,p_noise_yReference to the input noise arrays.
p_stretchingLocal wavenumber multiplier.
centerPrimitive reference center.
bboxDomain bounding box.
Returns
Array New array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
float kw = 4.f;
float angle = 30.f;
std::uint32_t seed = 1;
shape,
{kw, kw},
seed,
8,
0.f);
auto zt = hmap::wave_triangular(shape, kw, angle, 0.8f);
auto zq = hmap::wave_square(shape, kw, angle);
auto zs = hmap::wave_sine(shape, kw, angle);
auto zd = hmap::wave_dune(shape, kw, angle, 0.5f, 0.7f, 0.f);
auto ztn = hmap::wave_triangular(shape, kw, angle, 0.8f, 0.f, &noise);
auto zqn = hmap::wave_square(shape, kw, angle, 0.f, &noise);
auto zsn = hmap::wave_sine(shape, kw, angle, 0.f, &noise);
auto zdn = hmap::wave_dune(shape, kw, angle, 0.5f, 0.7f, 0.f, &noise);
hmap::export_banner_png("ex_wave0.png",
{zt, zq, zs, zd},
hmap::export_banner_png("ex_wave1.png",
{ztn, zqn, zsn, zdn},
}

Result

◆ caldera() [1/2]

Array hmap::caldera ( glm::ivec2 shape,
float radius,
float sigma_inner,
float sigma_outer,
float z_bottom,
const Array * p_noise,
float noise_r_amp,
float noise_ratio_z,
glm::vec2 center = {0.5f, 0.5f},
const UvRect & uv_rect = UvRect::unit() )

Return a caldera-shaped heightmap.

Parameters
shapeArray shape.
radiusCrater radius at the ridge.
sigma_innerInner half-width.
sigma_outerOuter half-width.
z_bottomBottom elevation (ridge is at elevation 1).
p_noiseDisplacement noise.
noise_r_ampRadial noise amplitude.
noise_ratio_zVertical noise relative scale (in [0, 1]).
centerPrimitive reference center.
bboxDomain bounding box.
Returns
Array Resulting array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
float radius = 0.2f;
float sigma_inner = 0.03f;
float sigma_outer = 0.12f;
float z_bottom = 0.3f;
// without noise
radius,
sigma_inner,
sigma_outer,
z_bottom);
// with noise
glm::vec2 res = {4.f, 4.f};
int seed = 1;
shape,
res,
seed);
float noise_r_amp = 0.03f;
float noise_z_ratio = 0.4f; // in [0, 1]
hmap::remap(noise);
radius,
sigma_inner,
sigma_outer,
z_bottom,
&noise,
noise_r_amp,
noise_z_ratio);
hmap::export_banner_png("ex_caldera.png",
{z1, z2},
true);
}
Array caldera(glm::ivec2 shape, float radius, float sigma_inner, float sigma_outer, float z_bottom, const Array *p_noise, float noise_r_amp, float noise_ratio_z, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit())
Return a caldera-shaped heightmap.
Definition caldera.cpp:16

Result

◆ caldera() [2/2]

Array hmap::caldera ( glm::ivec2 shape,
float radius,
float sigma_inner,
float sigma_outer,
float z_bottom,
glm::vec2 center = {0.5f, 0.5f},
const UvRect & uv_rect = UvRect::unit() )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ circus()

Array hmap::circus ( glm::ivec2 shape,
float radius = 0.4f,
float angle = 0.f,
float exit_width = 0.35f,
float exit_depth = 0.f,
float center_depth = 0.1f,
float ridge_height = 1.f,
float ridge_width = 0.15f,
float outer_falloff = 2.f,
const Array * p_noise_r = nullptr,
glm::vec2 center = {0.5f, 0.5f},
const UvRect & uv_rect = UvRect::unit(),
Array * p_mask = nullptr )

Generate a procedural circus (glacial cirque / amphitheatre basin) heightmap.

Generates an elevation envelope representing a basin/depression with a defined low exit point, a central depression, and an elevated arc on the side opposite the exit point.

Parameters
shapeOutput array shape.
radiusCircus basin/ridge radius.
angleExit point direction angle in degrees.
exit_widthAngular opening/width factor of the low exit.
exit_depthElevation at the low exit point.
center_depthElevation in the central basin depression.
ridge_heightElevation of the opposite ridge arc.
ridge_widthRadial width of the ridge crest.
outer_falloffExponent controlling the outer slope falloff.
p_noise_rOptional radial noise distortion.
centerCenter position in normalized domain coordinates.
bboxBounding box coordinates.
p_maskOptional output mask of the circus envelope.
Returns
Generated circus elevation envelope.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {512, 512};
// --- 1. Default / baseline circus envelope (exit towards east)
float radius = 0.35f;
float angle = 0.f;
float exit_width = 0.35f;
float exit_depth = 0.0f;
float center_depth = 0.1f;
float ridge_height = 1.0f;
float ridge_width = 0.15f;
float outer_falloff = 2.0f;
radius,
angle,
exit_width,
exit_depth,
center_depth,
ridge_height,
ridge_width,
outer_falloff);
// --- 2. Wide exit angle, rotated orientation, deeper depression
float angle_var = 45.f;
float exit_width_var = 0.55f;
float center_depth_var = 0.02f;
float ridge_height_var = 0.85f;
float ridge_width_var = 0.25f;
radius,
angle_var,
exit_width_var,
exit_depth,
center_depth_var,
ridge_height_var,
ridge_width_var,
outer_falloff);
// --- 3. Circus modulatedwith procedural noise
glm::vec2 kw = {4.f, 4.f};
std::uint32_t seed = 42;
auto noise_r = 0.15f *
shape,
kw * 2.f,
seed + 1);
hmap::remap(terrain_noise, 0.f, 0.05f);
radius,
-30.f,
exit_width,
exit_depth,
center_depth,
ridge_height,
ridge_width,
outer_falloff,
&noise_r);
// --- Export comparison banner
hmap::export_banner_png("ex_circus.png",
{z1, z2, z3},
true);
return 0;
}

Result

◆ crater()

Array hmap::crater ( glm::ivec2 shape,
float radius,
glm::vec2 center = {0.5f, 0.5f},
float angle = 30.f,
float inner_depth = 0.1f,
float inner_exp = 3.f,
float lip_height = 0.02f,
float lip_extent = 0.25f,
float lip_exp = 2.f,
float asym_ratio = 0.8f,
float central_peak_height = 0.01f,
float central_peak_extent = 0.4f,
int n_terraces = 0,
float terrace_extent = 0.1f,
float terrace_exp = 2.f,
float terrace_persistence = 0.5f,
const Array * p_noise_r = nullptr,
const UvRect & uv_rect = UvRect::unit(),
Array * p_crater_mask = nullptr,
Array * p_inner_crater_mask = nullptr )

Generate a procedural impact crater heightmap.

Creates a crater-shaped terrain with configurable inner cavity, outer lip, asymmetry, terraces, and optional central peak. Optional masks for the crater region and inner crater region can also be generated.

Parameters
shapeOutput array shape.
radiusCrater radius.
centerCrater center position.
angleMain asymmetry orientation angle in degrees.
inner_depthDepth of the crater cavity.
inner_expExponent controlling the inner profile shape.
lip_heightHeight of the crater rim.
lip_extentExtent of the outer rim.
lip_expExponent controlling rim falloff.
asym_ratioAsymmetry factor applied along the main direction.
central_peak_heightHeight of the central peak.
central_peak_extentRadius of the central peak region.
n_terracesNumber of inner terraces.
terrace_extentTerrace spacing factor.
terrace_expTerrace profile exponent.
terrace_persistenceTerrace amplitude decay factor.
p_noise_rOptional radial noise distortion.
bboxBounding box coordinates.
p_crater_maskOptional output crater mask.
p_inner_crater_maskOptional output inner crater mask.
Returns
Generated crater heightmap.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
// --- Base
float radius = 0.3f;
hmap::Array z1 = hmap::crater(shape, radius);
// --- With noise
float noise_amp = 0.2f;
glm::vec2 kw = {4.f, 4.f};
int seed = 1;
auto noise = noise_amp *
hmap::Array crater_mask;
radius = 0.2f;
glm::vec2 center = {0.8f, 0.6f};
float angle = -15.f;
float inner_depth = 0.1f;
float inner_exp = 3.f;
float lip_height = 0.02f;
float lip_extent = 0.25f;
float lip_exp = 2.f;
float asym_ratio = 0.8f;
float central_peak_height = 0.01f;
float central_peak_extent = 0.4f;
int n_terraces = 0;
float terrace_extent = 0.1f;
float terrace_exp = 2.f;
float terrace_persistence = 0.5f;
glm::vec4 bbox = {0.f, 1.f, 0.f, 1.f};
radius,
center,
angle,
inner_depth,
inner_exp,
lip_height,
lip_extent,
lip_exp,
asym_ratio,
central_peak_height,
central_peak_extent,
n_terraces,
terrace_extent,
terrace_exp,
terrace_persistence,
&noise,
bbox,
&crater_mask,
/* p_inner_crater_mask */ nullptr);
// --- Crater merging - mask-based
// 2nd crater hits after the 1st one and replaces the ground
hmap::Array z3 = lerp(z1, z2, crater_mask);
hmap::export_banner_png("ex_crater.png",
{z1, z2, z3},
true);
}
Array crater(glm::ivec2 shape, float radius, glm::vec2 center={0.5f, 0.5f}, float angle=30.f, float inner_depth=0.1f, float inner_exp=3.f, float lip_height=0.02f, float lip_extent=0.25f, float lip_exp=2.f, float asym_ratio=0.8f, float central_peak_height=0.01f, float central_peak_extent=0.4f, int n_terraces=0, float terrace_extent=0.1f, float terrace_exp=2.f, float terrace_persistence=0.5f, const Array *p_noise_r=nullptr, const UvRect &uv_rect=UvRect::unit(), Array *p_crater_mask=nullptr, Array *p_inner_crater_mask=nullptr)
Generate a procedural impact crater heightmap.
Definition crater.cpp:126
Point lerp(const Point &p1, const Point &p2, float t)
Linearly interpolates between two points.
Definition points.cpp:265

Result

◆ crater_field() [1/2]

Array hmap::crater_field ( glm::ivec2 shape,
const std::vector< glm::vec2 > & centers,
const std::vector< float > & radii,
float angle = 30.f,
float inner_depth = 0.5f,
float inner_exp = 3.f,
float lip_height = 0.1f,
float lip_extent = 0.25f,
float lip_exp = 2.f,
float asym_ratio = 0.8f,
float central_peak_height = 0.05f,
float central_peak_extent = 0.4f,
int n_terraces = 0,
float terrace_extent = 0.1f,
float terrace_exp = 2.f,
float terrace_persistence = 0.5f,
const Array * p_noise_r = nullptr,
const UvRect & uv_rect = UvRect::unit(),
Array * p_crater_mask = nullptr,
Array * p_inner_crater_mask = nullptr,
bool scale_elevation_with_radius = true )

Generate a field of procedural impact craters from explicit centers and radii.

Uses a KD-tree over crater centers to evaluate only nearby craters per pixel, and scales cavity depth, lip height, and central peak height proportionally to each crater's radius.

Parameters
shapeOutput array shape.
centersCrater center positions in world coordinates.
radiiCrater radii corresponding to centers.
angleMain asymmetry orientation angle in degrees.
inner_depthDepth-to-radius ratio of the crater cavity.
inner_expExponent controlling the inner profile shape.
lip_heightRim height-to-radius ratio.
lip_extentExtent of the outer rim.
lip_expExponent controlling rim falloff.
asym_ratioAsymmetry factor applied along the main direction.
central_peak_heightCentral peak height-to-radius ratio.
central_peak_extentRadius of the central peak region.
n_terracesNumber of inner terraces.
terrace_extentTerrace spacing factor.
terrace_expTerrace profile exponent.
terrace_persistenceTerrace amplitude decay factor.
p_noise_rOptional radial noise distortion.
bboxBounding box coordinates.
p_crater_maskOptional output crater mask.
p_inner_crater_maskOptional output inner crater mask.
Returns
Generated crater field heightmap.

◆ crater_field() [2/2]

Array hmap::crater_field ( glm::ivec2 shape,
std::uint32_t seed,
int n_craters,
float r_min = 0.02f,
float r_max = 0.2f,
float angle = 30.f,
float inner_depth = 0.5f,
float inner_exp = 3.f,
float lip_height = 0.1f,
float lip_extent = 0.25f,
float lip_exp = 2.f,
float asym_ratio = 0.8f,
float central_peak_height = 0.05f,
float central_peak_extent = 0.4f,
int n_terraces = 0,
float terrace_extent = 0.1f,
float terrace_exp = 2.f,
float terrace_persistence = 0.5f,
const Array * p_noise_r = nullptr,
const UvRect & uv_rect = UvRect::unit(),
Array * p_crater_mask = nullptr,
Array * p_inner_crater_mask = nullptr,
bool scale_elevation_with_radius = true )

Generate a field of randomly distributed procedural impact craters.

Randomly samples crater centers within the unit square [0, 1] x [0, 1] and radii in [r_min, r_max] using seed, then delegates to the explicit-input crater_field overload.

Parameters
shapeOutput array shape.
seedRandom number generator seed.
n_cratersNumber of craters to generate.
r_minMinimum crater radius.
r_maxMaximum crater radius.
angleMain asymmetry orientation angle in degrees.
inner_depthDepth-to-radius ratio of the crater cavity.
inner_expExponent controlling the inner profile shape.
lip_heightRim height-to-radius ratio.
lip_extentExtent of the outer rim.
lip_expExponent controlling rim falloff.
asym_ratioAsymmetry factor applied along the main direction.
central_peak_heightCentral peak height-to-radius ratio.
central_peak_extentRadius of the central peak region.
n_terracesNumber of inner terraces.
terrace_extentTerrace spacing factor.
terrace_expTerrace profile exponent.
terrace_persistenceTerrace amplitude decay factor.
p_noise_rOptional radial noise distortion.
bboxBounding box coordinates.
p_crater_maskOptional output crater mask.
p_inner_crater_maskOptional output inner crater mask.
Returns
Generated crater field heightmap.

◆ island_land_mask()

Array hmap::island_land_mask ( glm::ivec2 shape,
float radius,
std::uint32_t seed,
float displacement = 0.2f,
NoiseType noise_type = NoiseType::SIMPLEX2S,
float kw = 4.f,
int octaves = 8,
float weight = 0.f,
float persistence = 0.5f,
float lacunarity = 2.f,
const glm::vec2 & center = {0.5f, 0.5f},
const BBox2D & bbox = BBox2D::unit() )

Generates a 2D island mask by perturbing a radial boundary with noise.

Creates a binary mask of a single connected island using radial distance from a center point and adding an FBM-based angular displacement.

Parameters
shapeOutput array size (width, height).
radiusBase island radius.
seedNoise seed.
displacementAmplitude of boundary perturbation.
noise_typeType of underlying noise function.
kwAngular frequency for sampling the noise.
octavesNumber of FBM octaves.
weightBase amplitude of the FBM.
persistenceAmplitude falloff per octave.
lacunarityFrequency multiplier per octave.
centerCenter of the island in normalized coordinates.
bboxBounding box for coordinate remapping.
Returns
Binary mask where 1.f indicates land and 0.f indicates water.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {4.f, 4.f};
std::uint32_t seed = 0;
shape,
kw,
seed++,
8,
0.f);
hmap::remap(noise);
// use dedicated mask generator
float radius = 0.3f;
float displacement = 0.2f;
radius,
seed,
displacement,
noise_type);
// default noise
hmap::Array za = hmap::gpu::island(land_mask, seed);
// custom noise (expected in [0, 1])
hmap::Array zb = hmap::gpu::island(land_mask, &noise);
// use "any" noise as land mask
auto land_mask2 = noise;
hmap::zeroed_edges(land_mask2);
hmap::make_binary(land_mask2, 0.15f);
hmap::Array zc = hmap::gpu::island(land_mask2, seed);
hmap::export_banner_png("ex_island.png",
{land_mask, za, zb, zc},
true);
}
Array island(const Array &land_mask, const Array *p_noise_r=nullptr, float apex_elevation=1.f, bool filter_distance=true, int filter_ir=32, float slope_min=0.1f, float slope_max=8.f, float slope_start=0.5f, float slope_end=1.f, float slope_noise_intensity=0.5f, float k_smooth=0.05f, float radial_noise_intensity=0.3f, float radial_profile_gain=2.f, float water_decay=0.05f, float water_depth=0.3f, float lee_angle=30.f, float lee_amp=0.f, float uplift_amp=0.f, Array *p_water_depth=nullptr, Array *p_inland_mask=nullptr)
Generates an island heightmap from a land mask using radial profiles, slope shaping,...
Definition island.cpp:116
Array island_land_mask(glm::ivec2 shape, float radius, std::uint32_t seed, float displacement=0.2f, NoiseType noise_type=NoiseType::SIMPLEX2S, float kw=4.f, int octaves=8, float weight=0.f, float persistence=0.5f, float lacunarity=2.f, const glm::vec2 &center={0.5f, 0.5f}, const BBox2D &bbox=BBox2D::unit())
Generates a 2D island mask by perturbing a radial boundary with noise.
Definition island.cpp:25
NoiseType
Enumeration of various noise types used for procedural generation.
Definition functions.hpp:67

Result

◆ island_chain_land_mask()

Array hmap::island_chain_land_mask ( glm::ivec2 shape,
const Path & path,
std::uint32_t seed,
int island_count = 5,
float island_radius = 0.1f,
float size_falloff = 0.5f,
float size_jitter = 0.3f,
float scatter = 0.f,
float displacement = 0.2f,
NoiseType noise_type = NoiseType::SIMPLEX2S,
float kw = 4.f,
int octaves = 8,
float weight = 0.f,
float persistence = 0.5f,
float lacunarity = 2.f,
const UvRect & uv_rect = UvRect::unit() )

Generates a land mask of an island chain scattered along a path.

Spawns island_count islands along the input path. Each island is an fbm-perturbed radial blob (same construction as island_land_mask). Island positions follow the path arc length, optionally jittered along and across the path by scatter. Island sizes follow a signed falloff: size_falloff = 0 gives uniform sizes, +1 shrinks the islands toward the path end (hotspot-chain look, largest island at the head), -1 shrinks them toward the start; size_jitter adds per-island random variation.

Parameters
shapeOutput array shape.
pathInput path (at least two points), in normalized domain coordinates.
seedRandom seed number.
island_countNumber of islands spawned along the path.
island_radiusBase island radius in normalized domain units.
size_falloffSigned size falloff along the path, in [-1, 1].
size_jitterPer-island random radius variation ratio.
scatterRandom island displacement along and across the path.
displacementAmplitude of the fbm boundary perturbation.
noise_typeNoise type used for the boundary perturbation.
kwNoise wavenumber.
octavesNumber of fbm octaves.
weightOctave weighting.
persistenceOctave persistence.
lacunarityDefines the wavenumber ratio between octaves.
bboxDomain bounding box.
Returns
Binary land mask (0 or 1).

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
std::uint32_t seed = 1;
hmap::Path path(std::vector<hmap::Point>{{0.2f, 0.3f, 0.f},
{0.5f, 0.6f, 0.f},
{0.8f, 0.7f, 0.f}});
// defaults
auto m1 = hmap::island_chain_land_mask(shape, path, seed);
// hotspot-style chain: strong size falloff, some scatter
path,
seed,
7, // island_count
0.09f, // island_radius
1.f, // size_falloff
0.3f, // size_jitter
0.04f, // scatter
0.15f);
hmap::export_banner_png("ex_island_chain.png", {m1, m2}, hmap::Cmap::GRAY);
}
Array island_chain_land_mask(glm::ivec2 shape, const Path &path, std::uint32_t seed, int island_count=5, float island_radius=0.1f, float size_falloff=0.5f, float size_jitter=0.3f, float scatter=0.f, float displacement=0.2f, NoiseType noise_type=NoiseType::SIMPLEX2S, float kw=4.f, int octaves=8, float weight=0.f, float persistence=0.5f, float lacunarity=2.f, const UvRect &uv_rect=UvRect::unit())
Generates a land mask of an island chain scattered along a path.
Definition island_chain.cpp:22

Result

◆ rift()

Array hmap::rift ( glm::ivec2 shape,
float angle,
float radius = 0.1f,
float axial_slope = 0.2f,
float depth = 0.5f,
bool scale_with_depth = true,
RadialProfile profile = RadialProfile::RP_SMOOTHSTEP,
float profile_param = 0.f,
float bottom_extent = 0.1,
float bottom_depth = 0.05f,
RadialProfile bottom_profile = RadialProfile::RP_SQRT,
float bottom_profile_param = 0.f,
bool bottom_force_minimum_depth = true,
float outer_slope = 0.5f,
const Array * p_noise_r = nullptr,
const Array * p_noise_offset = nullptr,
glm::vec2 center = {0.5f, 0.5f},
const UvRect & uv_rect = UvRect::unit(),
Array * p_rift_mask = nullptr,
Array * p_bottom_mask = nullptr )

Generate a rift-shaped primitive.

Creates a longitudinal depression centered around a rotated axis. The rift shape is defined by an outer radial profile, an optional bottom profile, and configurable inner/outer slopes. Noise fields can be used to locally perturb the radius and axial offset of the structure.

Parameters
shapeOutput array shape.
angleRift orientation angle in degrees.
radiusRift half-width in normalized domain units.
axial_slopeLongitudinal slope applied along the rift axis.
depthRift depth amplitude.
scale_with_depthIf true, scale radial features proportionally to the depth value.
profileRadial profile used for the outer rift shape.
profile_paramAdditional parameter for the outer profile.
bottom_extentRelative extent of the flat or inner bottom region inside the rift.
bottom_depthAdditional depth contribution applied to the bottom region.
bottom_profileRadial profile used for the bottom region.
bottom_profile_paramAdditional parameter for the bottom profile.
outer_slopeSlope factor controlling the outer falloff.
p_noise_rOptional noise array used to locally modulate the rift radius.
p_noise_offsetOptional noise array used to locally offset the rift axis position.
centerRift center in normalized coordinates.
bboxDomain bounding box.
Returns
Generated rift array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
// --- Base noise for displacement
glm::vec2 kw = {8.f, 8.f};
std::uint32_t seed = 0;
auto dr = 0.2f * hmap::noise_fbm(hmap::NoiseType::PERLIN, shape, kw, ++seed);
auto ds = 1.8f * hmap::noise_fbm(hmap::NoiseType::PERLIN, shape, kw, ++seed);
// --- Rift
// raw primitive
float angle = 15.f;
auto z1 = hmap::rift(shape, angle);
// with some noises
float radius = 0.1f;
float axial_slope = 0.2f;
float depth = 0.5f;
bool scale_with_depth = true;
float profile_param = 0.f;
float bottom_extent = 0.1;
float bottom_depth = 0.05f;
auto bottom_profile = hmap::RadialProfile::RP_SQRT;
float bottom_profile_param = 0.f;
bool bottom_force_minimum_depth = true;
float outer_slope = 0.5f;
auto z2 = hmap::rift(shape,
angle,
radius,
axial_slope,
depth,
scale_with_depth,
profile,
profile_param,
bottom_extent,
bottom_depth,
bottom_profile,
bottom_profile_param,
bottom_force_minimum_depth,
outer_slope,
&dr,
&ds);
hmap::export_banner_png("ex_rift.png", {z1, z2}, hmap::Cmap::TERRAIN, true);
}
Array rift(glm::ivec2 shape, float angle, float radius=0.1f, float axial_slope=0.2f, float depth=0.5f, bool scale_with_depth=true, RadialProfile profile=RadialProfile::RP_SMOOTHSTEP, float profile_param=0.f, float bottom_extent=0.1, float bottom_depth=0.05f, RadialProfile bottom_profile=RadialProfile::RP_SQRT, float bottom_profile_param=0.f, bool bottom_force_minimum_depth=true, float outer_slope=0.5f, const Array *p_noise_r=nullptr, const Array *p_noise_offset=nullptr, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit(), Array *p_rift_mask=nullptr, Array *p_bottom_mask=nullptr)
Generate a rift-shaped primitive.
Definition rift.cpp:18
@ RP_SQRT
Definition profiles.hpp:58

Result

◆ valley_head()

Array hmap::valley_head ( glm::ivec2 shape,
float angle = 0.f,
float min_depth = 0.f,
float max_depth = 0.2f,
float min_width = 0.02f,
float max_width = 0.15f,
float depth_length = 0.5f,
float width_length = 0.5f,
float development_power = 2.f,
float profile_power = 1.3f,
const Array * p_noise_offset = nullptr,
const Array * p_noise_r = nullptr,
glm::vec2 center = {0.5f, 0.5f},
const UvRect & uv_rect = UvRect::unit(),
Array * p_mask = nullptr )

Generate a procedural natural valley head / valley incision deformation heightmap.

Creates a valley head incision that smoothly emerges at the origin and progressively deepens and widens downstream following exponential saturation laws and smooth lateral falloff.

Parameters
shapeOutput array shape.
angleValley orientation angle in degrees.
min_depthValley depth at the head.
max_depthMaximum incision depth at maturity.
min_widthValley width at the head.
max_widthMature valley width.
depth_lengthDistance scale over which depth develops.
width_lengthDistance scale over which width develops.
development_powerExponent controlling how quickly the incision emerges.
profile_powerCross-section exponent (1 = sharp V, > 1 = rounded U-shape).
p_noise_offsetOptional cross-section centerline offset noise.
p_noise_rOptional width / radial noise.
centerValley head position.
bboxBounding box coordinates.
p_maskOptional output mask for incision intensity.
Returns
Generated valley head deformation array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {512, 512};
// --- Noise for cross-section and width modulation
glm::vec2 kw = {6.f, 6.f};
std::uint32_t seed = 42;
// displacement noise on local cross-section (meander)
auto noise_offset = 0.3f * hmap::noise_fbm(hmap::NoiseType::SIMPLEX2,
shape,
kw,
++seed);
// radial / width noise
shape,
kw * 2.f,
++seed);
// --- Clean valley head incision
float angle = 180.f; // along -y
float min_depth = 0.f;
float max_depth = 0.25f;
float min_width = 0.02f;
float max_width = 0.5f;
float depth_length = 0.45f;
float width_length = 0.45f;
float dev_power = 2.f;
float profile_power = 1.3f;
glm::vec2 center = {0.5f, 1.f};
auto delta_clean = hmap::valley_head(shape,
angle,
min_depth,
max_depth,
min_width,
max_width,
depth_length,
width_length,
dev_power,
profile_power,
nullptr,
nullptr,
center);
// --- Noisy valley head incision
auto delta_noisy = hmap::valley_head(shape,
angle,
min_depth,
max_depth,
min_width,
max_width,
depth_length,
width_length,
dev_power,
profile_power,
&noise_offset,
&noise_r,
center);
// --- Export
hmap::export_banner_png("ex_valley_head.png",
{delta_clean, delta_noisy},
true);
return 0;
}
Array valley_head(glm::ivec2 shape, float angle=0.f, float min_depth=0.f, float max_depth=0.2f, float min_width=0.02f, float max_width=0.15f, float depth_length=0.5f, float width_length=0.5f, float development_power=2.f, float profile_power=1.3f, const Array *p_noise_offset=nullptr, const Array *p_noise_r=nullptr, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit(), Array *p_mask=nullptr)
Generate a procedural natural valley head / valley incision deformation heightmap.
Definition valley_head.cpp:16

Result

◆ white()

Array hmap::white ( glm::ivec2 shape,
float a,
float b,
std::uint32_t seed )

Return an array filled with white noise.

Parameters
shapeArray shape.
aLower bound of random distribution.
bUpper bound of random distribution.
seedRandom number seed.
Returns
Array White noise.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
int seed = 1;
hmap::Array z = hmap::white(shape, 0.f, 1.f, seed);
z.to_png("ex_white.png", hmap::Cmap::VIRIDIS);
}

Result

See also
white_sparse

◆ white_density_map()

Array hmap::white_density_map ( const Array & density_map,
std::uint32_t seed )

Return an array filled 1 with a probability based on a density map.

Parameters
density_mapDensity map.
seedRandom number seed.
Returns
Array New array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
int seed = 1;
shape,
{2.f, 2.f},
seed);
hmap::remap(dmap);
hmap::Array w = hmap::white_density_map(0.5f * dmap, seed);
hmap::export_banner_png("ex_white_density_map.png",
{dmap, w},
}
Array white_density_map(const Array &density_map, std::uint32_t seed)
Return an array filled 1 with a probability based on a density map.
Definition white.cpp:28

Result

◆ white_sparse()

Array hmap::white_sparse ( glm::ivec2 shape,
float a,
float b,
float density,
std::uint32_t seed )

Return an array sparsely filled with white noise.

Parameters
shapeArray shape.
aLower bound of random distribution.
bUpper bound of random distribution.
densityArray filling density, in [0, 1]. If set to 1, the function is equivalent to white.
seedRandom number seed.
Returns
Array Sparse white noise.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
float density = 0.1f;
int seed = 1;
hmap::Array z = hmap::white_sparse(shape, 0.f, 1.f, density, seed);
z.to_png("ex_white_sparse.png", hmap::Cmap::VIRIDIS);
}
Array white_sparse(glm::ivec2 shape, float a, float b, float density, std::uint32_t seed)
Return an array sparsely filled with white noise.
Definition white.cpp:45

Result

See also
white

◆ white_sparse_binary()

Array hmap::white_sparse_binary ( glm::ivec2 shape,
float density,
std::uint32_t seed )

Return an array sparsely filled with random 0 and 1.

Parameters
shapeArray shape.
densityArray filling density, in [0, 1]. If set to 1, the function is equivalent to white.
seedRandom number seed.
Returns
Array Sparse white noise.

◆ fast_hash32_to_unit_float()

float hmap::fast_hash32_to_unit_float ( unsigned int seed,
size_t k )

Generates a fast deterministic uniform float in [0,1) using a 32-bit hash.

Parameters
seedBase seed value.
kSample index.
Returns
Pseudo-random float in [0,1).
Note
Faster but lower quality than splitmix64_to_unit_float().

◆ hash01()

float hmap::hash01 ( uint32_t a,
uint32_t b )

Computes a pseudo-random float in [0, 1) by hashing two 32-bit integers.

Parameters
aFirst 32-bit value.
bSecond 32-bit value.
Returns
Uniform float in [0, 1).

◆ hash32()

uint32_t hmap::hash32 ( uint32_t x)

Integer hash function (Murmur3 / finalize style 32-bit mixer).

Parameters
xInput 32-bit value.
Returns
Hashed 32-bit value.

◆ splitmix64()

uint64_t hmap::splitmix64 ( uint64_t x)

Computes a deterministic 64-bit hash using the SplitMix64 algorithm.

This function is used to generate reproducible pseudo-random values from integer inputs without maintaining any internal state. It is suitable for generating deterministic per-sample random seeds.

Parameters
xInput 64-bit value.
Returns
64-bit hashed value.

◆ splitmix64_to_unit_float()

float hmap::splitmix64_to_unit_float ( unsigned int seed,
size_t k )

Generates a deterministic uniform float in [0,1) from a seed and sample index.

The function combines the base seed and sample index, hashes the result using SplitMix64, and converts the generated bits into a floating-point value in the range [0,1). The output is deterministic and independent for each sample index.

Parameters
seedBase seed value.
kSample index.
Returns
Pseudo-random float in [0,1).

◆ uniform01()

float hmap::uniform01 ( uint64_t h)

Converts a 64-bit hash value into a deterministic uniform float in [0, 1).

Extracts the upper 24 bits of the input hash and scales them to produce a single-precision floating-point value. The 24-bit resolution matches the mantissa precision of a float, providing a deterministic pseudo-random uniform distribution.

Parameters
h64-bit hash value.
Returns
Uniform floating-point value in the range [0, 1).

◆ vnoise()

float hmap::vnoise ( float x,
float y,
uint32_t seed = 0 )

Computes 2D value noise in [-1, 1] using a hash-based lattice.

Parameters
xX coordinate.
yY coordinate.
seedRandom seed.
Returns
Value noise in [-1, 1].

◆ chop()

void hmap::chop ( Array & array,
float vmin )

Set to zero any value lower than vmin.

This function processes the input array and sets any value that is less than the specified lower bound vmin to zero. This operation effectively "chops off" values that fall below the threshold, which can be useful for filtering out unwanted low values in data processing tasks.

Parameters
arrayInput array to be processed. Values lower than vmin will be set to zero.
vminLower bound threshold. Values below this threshold will be set to zero.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {4.f, 4.f};
int seed = 1;
hmap::Array z1 = z;
hmap::chop(z1, 0.4f);
hmap::export_banner_png("ex_chop.png", {z, z1}, hmap::Cmap::VIRIDIS);
}
void chop(Array &array, float vmin)
Set to zero any value lower than vmin.
Definition range.cpp:17

Result

◆ chop_max_smooth()

void hmap::chop_max_smooth ( Array & array,
float vmax )

Set to zero any value lower than vmax and apply a linear decrease slope between vmax / 2 and vmax.

This function processes the input array and sets any value below the upper bound vmax to zero. Additionally, it applies a linear decrease slope to values that fall between vmax / 2 and vmax. This creates a smooth transition where values gradually approach zero as they get closer to vmax, providing a more nuanced adjustment compared to a sharp cutoff.

Parameters
arrayInput array to be processed. Values below vmax will be adjusted, with a linear decrease applied between vmax / 2 and vmax.
vmaxUpper bound threshold. Values below this threshold will be zeroed, with linear decrease applied in the specified range.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {4.f, 4.f};
int seed = 1;
hmap::Array z1 = z;
hmap::export_banner_png("ex_chop_max_smooth.png",
{z, z1},
}
void chop_max_smooth(Array &array, float vmax)
Set to zero any value lower than vmax and apply a linear decrease slope between vmax / 2 and vmax.
Definition range.cpp:29

Result

◆ clamp() [1/2]

void hmap::clamp ( Array & array,
float vmin = 0.f,
float vmax = 1.f )

Clamp array elements to a target range.

This function restricts the values in the input array to be within a specified range. Values below vmin are set to vmin, and values above vmax are set to vmax. This operation ensures that all elements of the array remain within the defined bounds.

Parameters
arrayInput array to be clamped.
vminLower bound of the clamping range (default is 0).
vmaxUpper bound of the clamping range (default is 1).

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {4.f, 4.f};
int seed = 1;
auto z1 = z;
hmap::clamp(z1, -0.1f, 0.1f);
auto z2 = z;
auto z3 = z;
auto z4 = z;
hmap::clamp_smooth(z4, -0.1f, 0.1f);
auto z5 = z;
hmap::clamp_oblique_plane(z5, 0.1f, 30.f, 0.3f);
hmap::export_banner_png("ex_clamp.png",
{z1, z2, z3, z4, z5},
}
void clamp_min_smooth(Array &array, float vmin, float k=0.2f)
Clamp array values lower than a given bound with a smooth transition.
Definition range.cpp:180
void clamp_smooth(Array &array, float vmin, float vmax, float k=0.2f)
Clamp array values within a given interval with a smooth transition.
Definition range.cpp:269
void clamp_max_smooth(Array &array, float vmax, float k=0.2f)
Clamp array values larger than a given bound with a smooth transition.
Definition range.cpp:112
void clamp(Array &array, float vmin=0.f, float vmax=1.f)
Clamp array elements to a target range.
Definition range.cpp:48
void clamp_oblique_plane(Array &array, float vmax, float angle, float slope, bool use_max_operator=true, float k=0.f, glm::vec2 center={0.5f, 0.5f}, const BBox2D &bbox=BBox2D::unit())
Clamps an array against an oblique plane.
Definition range.cpp:230

Result

See also
remap, clamp_min, clamp_max

◆ clamp() [2/2]

void hmap::clamp ( Array & array,
float vmax,
ClampMode mode )

Clamps the values of an array according to the specified mode.

This function modifies the input array in place based on one of three clamping modes:

  • ClampMode::POSITIVE_ONLY Keeps only positive values and clamps them to a maximum value vmax. All negative values are set to 0.
  • ClampMode::NEGATIVE_ONLY Keeps only negative values, reverses their sign (making them positive), and clamps them to a maximum value vmax. Positive values are set to 0.
  • ClampMode::BOTH Keeps both positive and negative values, clamping them symmetrically between -vmax and vmax.
Parameters
arrayReference to the array whose values will be clamped.
vmaxThe maximum absolute value used for clamping.
modeThe clamping mode to apply (see ::ClampMode).

◆ clamp_min() [1/2]

void hmap::clamp_min ( Array & array,
float vmin )

Clamp array values lower than a given bound.

This function clamps all values in the input array that are below the specified lower bound vmin to the value of vmin.

Parameters
arrayInput array to be clamped.
vminLower bound for clamping.
See also
clamp, clamp_max

◆ clamp_min() [2/2]

void hmap::clamp_min ( Array & array,
const Array & vmin )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ clamp_min_smooth() [1/3]

void hmap::clamp_min_smooth ( Array & array,
float vmin,
float k = 0.2f )

Clamp array values lower than a given bound with a smooth transition.

This function smoothly clamps values in the input array that are below the specified lower bound vmin. The smoothing parameter k controls the degree of smoothness applied during the clamping process.

Parameters
arrayInput array to be clamped.
vminLower bound for clamping.
kSmoothing parameter in the range [0, 1] (default is 0.2f).

◆ clamp_min_smooth() [2/3]

void hmap::clamp_min_smooth ( Array & array,
const Array & vmin,
float k = 0.2f )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ clamp_min_smooth() [3/3]

float hmap::clamp_min_smooth ( float x,
float vmin,
float k = 0.2f )

Clamp a single value lower than a given bound with a smooth transition.

This function smoothly clamps a single value that is below the specified lower bound vmin. The smoothing parameter k controls the degree of smoothness applied during the clamping process.

Parameters
xInput value to be clamped.
vminLower bound for clamping.
kSmoothing parameter in the range [0, 1] (default is 0.2f).
Returns
float The smoothly clamped value.

◆ clamp_max() [1/2]

void hmap::clamp_max ( Array & array,
float vmax )

Clamp array values larger than a given bound.

This function clamps all values in the input array that are above the specified upper bound vmax to the value of vmax.

Parameters
arrayInput array to be clamped.
vmaxUpper bound for clamping.
See also
clamp, clamp_min

◆ clamp_max() [2/2]

void hmap::clamp_max ( Array & array,
const Array & vmax )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ clamp_max_smooth() [1/2]

void hmap::clamp_max_smooth ( Array & array,
float vmax,
float k = 0.2f )

Clamp array values larger than a given bound with a smooth transition.

This function smoothly clamps values in the input array that are above the specified upper bound vmax. The smoothing parameter k controls the degree of smoothness applied during the clamping process.

Parameters
arrayInput array to be clamped.
vmaxUpper bound for clamping.
kSmoothing parameter in the range [0, 1] (default is 0.2f).

◆ clamp_max_smooth() [2/2]

void hmap::clamp_max_smooth ( Array & array,
const Array & vmax,
float k = 0.2f )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ clamp_oblique_plane()

void hmap::clamp_oblique_plane ( Array & array,
float vmax,
float angle,
float slope,
bool use_max_operator = true,
float k = 0.f,
glm::vec2 center = {0.5f, 0.5f},
const BBox2D & bbox = BBox2D::unit() )

Clamps an array against an oblique plane.

Generates a sloped plane and clamps the input array either with a min or max operator, optionally using a smooth transition controlled by k.

Parameters
arrayArray to be modified.
vmaxOffset applied to the generated plane.
anglePlane angle in radians.
slope_valueSlope intensity of the plane.
use_max_operatorIf true, apply a max-clamp; otherwise apply a min-clamp.
kSmoothness factor (0 for hard clamp).
centerCenter of the plane.
bboxBounding box used to generate the plane.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {4.f, 4.f};
int seed = 1;
auto z1 = z;
hmap::clamp(z1, -0.1f, 0.1f);
auto z2 = z;
auto z3 = z;
auto z4 = z;
hmap::clamp_smooth(z4, -0.1f, 0.1f);
auto z5 = z;
hmap::clamp_oblique_plane(z5, 0.1f, 30.f, 0.3f);
hmap::export_banner_png("ex_clamp.png",
{z1, z2, z3, z4, z5},
}

Result

◆ clamp_smooth()

void hmap::clamp_smooth ( Array & array,
float vmin,
float vmax,
float k = 0.2f )

Clamp array values within a given interval with a smooth transition.

This function smoothly clamps values in the input array to be within a specified range. Values below vmin are smoothly transitioned to vmin, and values above vmax are smoothly transitioned to vmax. The smoothing parameter k controls the degree of smoothness applied during the clamping process.

Parameters
arrayInput array to be clamped.
vminLower bound of the clamping range.
vmaxUpper bound of the clamping range.
kSmoothing parameter in the range [0, 1] (default is 0.2f).

◆ maximum() [1/2]

Array hmap::maximum ( const Array & array1,
const Array & array2 )

Return the element-wise maximum of two arrays.

This function computes the element-wise maximum between two input arrays. Each element in the resulting array is the maximum of the corresponding elements from array1 and array2.

Parameters
array1First input array.
array2Second input array.
Returns
Array The element-wise maximum between array1 and array2.

◆ maximum() [2/2]

Array hmap::maximum ( const Array & array1,
const float value )

Return the element-wise maximum of an array and a scalar value.

This overloaded function computes the element-wise maximum between an input array and a scalar value. Each element in the resulting array is the maximum of the corresponding element from the input array and the scalar value.

Parameters
array1Input array.
valueScalar value to compare with each element of the array.
Returns
Array The element-wise maximum between array1 and value. This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ maximum_smooth() [1/2]

Array hmap::maximum_smooth ( const Array & array1,
const Array & array2,
float k = 0.2 )

Return the polynomial cubic smooth element-wise maximum of two arrays.

This function computes the element-wise maximum of two input arrays with a smooth transition to avoid discontinuities that are present in the standard maximum function. The smoothness is controlled by the parameter k, which determines how smoothly the transition between the two arrays occurs.

The smooth transition is achieved using a polynomial cubic function, which provides a smooth blend between the two arrays. This approach helps in avoiding abrupt changes and can be useful in applications requiring smooth transitions.

Parameters
array1First array to be compared.
array2Second array to be compared.
kSmoothing parameter in the range [0, 1]. Higher values result in smoother transitions between the arrays (default is 0.2).
Returns
Array Element-wise smooth maximum between the two input arrays.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {4.f, 4.f};
hmap::Array z_smooth = hmap::maximum_smooth(z1, z2, 0.2f);
hmap::export_banner_png("ex_maximum_smooth.png",
{z1, z2, z_smooth},
}

Result

See also
minimum_smooth, minimum, maximum

◆ maximum_smooth() [2/2]

float hmap::maximum_smooth ( const float a,
const float b,
float k = 0.2 )

Return the polynomial cubic smooth maximum of two scalar values.

This function computes the smooth maximum of two scalar values with a polynomial cubic smooth transition. The parameter k controls the degree of smoothness applied to the maximum calculation, ensuring a continuous and smooth blend between the two values.

The smooth transition helps in avoiding abrupt changes, making this function suitable for applications that require smooth variations.

Parameters
aFirst scalar value.
bSecond scalar value.
kSmoothing parameter in the range [0, 1]. Higher values result in smoother transitions between the values (default is 0.2).
Returns
float Smooth maximum value between the two input values.

Example

#include <iostream>
#include "highmap.hpp"
int main(void)
{
float a = 0.5f;
float b = 0.7f;
float val = hmap::maximum_smooth(a, b, 0.2f);
// Also generate an image for Doxygen
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {4.f, 4.f};
hmap::Array z_smooth(shape);
for (int i = 0; i < shape.x; ++i)
{
for (int j = 0; j < shape.y; ++j)
{
z_smooth(i, j) = hmap::maximum_smooth(z(i, j), 0.5f, 0.2f);
}
}
hmap::export_banner_png("ex_maximum_smooth_scalar.png",
{z, z_smooth},
return 0;
}

Result

See also
minimum_smooth, minimum, maximum This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ minimum() [1/2]

Array hmap::minimum ( const Array & array1,
const Array & array2 )

Return the element-wise minimum of two arrays.

This function computes the element-wise minimum between two input arrays. Each element in the resulting array is the minimum of the corresponding elements from array1 and array2.

Parameters
array1First input array.
array2Second input array.
Returns
Array The element-wise minimum between array1 and array2.

◆ minimum() [2/2]

Array hmap::minimum ( const Array & array1,
const float value )

Return the element-wise minimum of an array and a scalar value.

This overloaded function computes the element-wise minimum between an input array and a scalar value. Each element in the resulting array is the minimum of the corresponding element from the input array and the scalar value.

Parameters
array1Input array.
valueScalar value to compare with each element of the array.
Returns
Array The element-wise minimum between array1 and value. This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ minimum_smooth() [1/2]

Array hmap::minimum_smooth ( const Array & array1,
const Array & array2,
float k = 0.2 )

Return the polynomial cubic smooth element-wise minimum of two arrays.

This function computes a smooth element-wise minimum between two input arrays using a polynomial cubic smoothing function. The smoothing parameter k controls the blending between the arrays, reducing the discontinuity found in a standard minimum operation. For details on the smoothing technique, refer to Inigo Quilez's articles.

Parameters
array1First input array.
array2Second input array.
kSmoothing parameter in the range [0, 1] that determines the degree of blending between the two arrays (default is 0.2).
Returns
Array The element-wise smooth minimum between array1 and array2.
See also
maximum_smooth, minimum, maximum

◆ minimum_smooth() [2/2]

float hmap::minimum_smooth ( const float a,
const float b,
float k )

Return the polynomial cubic smooth minimum of two scalar values.

This overloaded function computes a smooth minimum between two scalar values using a polynomial cubic smoothing function. The smoothing parameter k controls the blending between the values, reducing discontinuity compared to a standard minimum operation.

Parameters
aFirst scalar value.
bSecond scalar value.
kSmoothing parameter in the range [0, 1] that determines the degree of blending between the two values (default is 0.2).
Returns
float The smooth minimum between a and b. This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ remap() [1/3]

void hmap::remap ( Array & array,
float vmin,
float vmax,
float from_min,
float from_max )

Remap array elements from a starting range to a target range.

This function maps the values in the input array from one specified range to another. By default, the function uses the minimum and maximum values of the input array as the starting range. The target range is specified by vmin and vmax.

Parameters
arrayInput array to be remapped.
vminThe lower bound of the target range to remap to.
vmaxThe upper bound of the target range to remap to.
from_minThe lower bound of the starting range to remap from.
from_maxThe upper bound of the starting range to remap from.

Example

#include <iostream>
#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
std::cout << z.min() << " " << z.max() << std::endl;
hmap::remap(z, 0.f, 1.f);
std::cout << z.min() << " " << z.max() << std::endl;
}

See unit tests: test_remap.cpp

◆ remap() [2/3]

void hmap::remap ( Array & array,
float vmin = 0,
float vmax = 1,
ICommunicator & comm = SingleArrayComm::instance() )

Remap array elements from a starting range to a target range (default range).

This overloaded function remaps the values in the input array from the default starting range (the minimum and maximum values of the array) to a target range specified by vmin and vmax.

Parameters
arrayInput array to be remapped.
vminThe lower bound of the target range to remap to (default is 0).
vmaxThe upper bound of the target range to remap to (default is 1).
commOptional communicator for collective reduction across tiles.

See unit tests: test_remap.cpp This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ rescale()

void hmap::rescale ( Array & array,
float scaling,
float vref = 0.f )

Remap array elements from a starting range to a target range.

This function adjusts the values in the input array by scaling them and shifting them to fit within a new range. The scaling factor determines how much the values are stretched or compressed, and the reference value shifts the values to align with the target range.

Parameters
arrayInput array to be rescaled.
scalingAmplitude scaling factor to adjust the range of array elements.
vrefReference 'zero' value used to shift the values (default is 0.f).

◆ normalize_and_clip()

void hmap::normalize_and_clip ( Array & array,
float multiplier = 2.5f,
bool smooth_transition = true,
bool range_01 = false,
ICommunicator & comm = SingleArrayComm::instance() )

Normalize an array around its mean and clip values.

Centers the array by subtracting its mean, scales by (multiplier * std), and clamps the result to [-1, 1] (or [0, 1] if range_01 is true). When smooth_transition is enabled, applies smoothstep3 to soften transitions around the clipping boundaries.

Parameters
arrayInput array to be normalized and clipped.
multiplierStandard deviation multiplier (default is 2.5f).
smooth_transitionIf true, applies smoothstep3 to the clipped output.
range_01If true, maps output to [0, 1]; if false, [-1, 1].
commOptional communicator for collective reduction across tiles.

◆ merge_scatter_fields() [1/2]

ScatterField hmap::merge_scatter_fields ( const std::vector< ScatterField > & fields,
bool merge_by_class = true )

Merges multiple ScatterField instances into a single instance.

Parameters
fieldsList of ScatterField instances.
merge_by_classIf true, preserves existing class IDs. If false, assigns a new unique class ID for each input field corresponding to its index in fields.
Returns
ScatterField Merged scatter field.

◆ merge_scatter_fields() [2/2]

ScatterField hmap::merge_scatter_fields ( const std::vector< ScatterField > & fields,
const std::vector< BBox2D > & bboxs,
bool merge_by_class = true )

Merges multiple ScatterField instances with associated bounding boxes into a single instance, resolving overlaps by keeping items from earlier fields in the input order.

Parameters
fieldsList of ScatterField instances.
bboxsBounding box for each input field {xmin, xmax, ymin, ymax}.
merge_by_classIf true, preserves existing class IDs. If false, assigns a new unique class ID for each input field corresponding to its index in fields.
Returns
ScatterField Merged scatter field.

◆ scatter_field_to_heightmap()

Array hmap::scatter_field_to_heightmap ( const ScatterField & field,
glm::ivec2 shape,
ScatterShape shape_type = SCATTER_SHAPE_DISK,
float height_radius_ratio = 1.0f,
std::optional< uint32_t > class_id = std::nullopt,
Array * p_rock_map = nullptr,
uint32_t seed = 0,
const UvRect & uv_rect = UvRect::unit() )

Converts a ScatterField into a heightmap by representing each scattered object as a local elevation increase on GPU.

Parameters
fieldInput ScatterField.
shapeDimensions of the output heightmap {nx, ny}.
shape_typeObject geometry shape.
height_radius_ratioRatio of object maximum height relative to its radius.
class_idOptional class identifier to filter items.
p_rock_mapOptional output array for the rock map with normalized amplitude in [0, 1].
seedRandom seed for procedural shape variation.
bboxDomain bounding box {xmin, xmax, ymin, ymax}.
Returns
Array 2D heightmap array.

◆ seed_scatter_clusters()

ScatterField hmap::seed_scatter_clusters ( size_t class_count,
size_t item_count,
const Array & density,
const Array & exclusion,
float cluster_spread = 0.05f,
size_t points_per_cluster = 8,
const ScatterSeedingOptions & options = {} )

Generates a clustered scatter distribution using inverse transform sampling for cluster centers and local cluster regions.

Parameters
class_countNumber of distinct classes/categories.
item_countTarget total number of items.
densityGlobal density map array.
exclusionExclusion map array.
cluster_spreadHalf-extent of the bounding box surrounding each cluster center.
points_per_clusterNumber of child points sampled per parent cluster.
optionsSeeding options.
Returns
ScatterField Sampled scatter field container.

◆ seed_scatter_kmeans()

ScatterField hmap::seed_scatter_kmeans ( size_t class_count,
size_t item_count,
const Array & density,
const Array & exclusion,
float cluster_randomness = 0.0f,
size_t k_neighbors = 4,
const ScatterSeedingOptions & options = {} )

Generates a multi-class scatter distribution using 2D inverse transform sampling for positions and PointSampler k-means clustering to tag classes.

Parameters
class_countNumber of distinct item classes.
item_countTarget total number of items.
densityGlobal density map array.
exclusionExclusion map array.
cluster_randomnessRandomness factor in [0, 1] added to cluster features.
k_neighborsNumber of nearest spatial neighbors used to extract compactness features.
optionsSeeding options.
Returns
ScatterField Sampled scatter field container.

◆ sdf_2d_polyline()

Array hmap::sdf_2d_polyline ( const Path & path,
glm::ivec2 shape,
const UvRect & uv_rect = UvRect::unit(),
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
bool use_bvh = true )

Computes the signed distance field (SDF) of a 2D polyline.

This function calculates the distance of each grid cell in the specified 2D array to the closest segment of a polyline. The polyline is represented by a Path object, and optional noise fields can be added to perturb the array coordinates.

Parameters
pathThe polyline path represented as a Path object containing the nodes.
shapeThe dimensions (width, height) of the output array grid.
bboxThe bounding box of the array grid in the format (xmin, xmax, ymin, ymax).
p_noise_xPointer to an optional noise array for perturbing x-coordinates (can be nullptr).
p_noise_yPointer to an optional noise array for perturbing y-coordinates (can be nullptr).
Returns
Array The resulting signed distance field (SDF) as a 2D array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {4.f, 4.f};
int seed = 1;
shape,
kw,
seed,
8,
0.f);
hmap::remap(noise, 0.f, 1.f);
// base path
hmap::BBox2D bbox = {1.f, 2.f, -0.5f, 0.5f};
hmap::Path path = hmap::Path(9, seed, hmap::BBox2D(1.2f, 1.8f, -0.3f, 0.3f));
path.reorder_nns();
// path.fractalize(2, seed);
path.set_values_from_array(noise, bbox);
auto zp = hmap::Array(shape);
path.to_array(zp, bbox);
hmap::UvRect uv_rect = {1.f, 2.f, -0.5f, 0.5f};
hmap::Array sdf_2d = hmap::sdf_2d_polyline(path, shape, uv_rect);
hmap::remap(sdf_2d);
shape,
uv_rect);
hmap::remap(sdf_2d_bezier);
hmap::export_banner_png("ex_sdf_polyline.png",
{zp, sdf_2d, sdf_2d_bezier},
}
Array sdf_2d_polyline(const Path &path, glm::ivec2 shape, const UvRect &uv_rect=UvRect::unit(), const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, bool use_bvh=true)
Computes the signed distance field (SDF) of a 2D polyline.
Definition sdf_2d_polyline.cpp:95

Result

◆ sdf_2d_polyline_brute_force()

Array hmap::sdf_2d_polyline_brute_force ( const Path & path,
glm::ivec2 shape,
const UvRect & uv_rect = UvRect::unit(),
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr )

◆ sdf_2d_polyline_bvh()

Array hmap::sdf_2d_polyline_bvh ( const Path & path,
glm::ivec2 shape,
const UvRect & uv_rect = UvRect::unit(),
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr )

◆ sdf_2d_polyline_bezier()

Array hmap::sdf_2d_polyline_bezier ( const Path & path,
glm::ivec2 shape,
const UvRect & uv_rect = UvRect::unit(),
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
bool use_bvh = true )

See hmap::sdf_2d_polyline, with a Bezier approximation of the path.

◆ sdf_2d_polyline_bezier_brute_force()

Array hmap::sdf_2d_polyline_bezier_brute_force ( const Path & path,
glm::ivec2 shape,
const UvRect & uv_rect = UvRect::unit(),
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr )

◆ sdf_2d_polyline_bezier_bvh()

Array hmap::sdf_2d_polyline_bezier_bvh ( const Path & path,
glm::ivec2 shape,
const UvRect & uv_rect = UvRect::unit(),
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr )

◆ sdf_2d_graph()

Array hmap::sdf_2d_graph ( const Graph & graph,
glm::ivec2 shape,
const UvRect & uv_rect = UvRect::unit(),
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
bool use_bvh = true )

Computes the 2D unsigned distance field to a graph network.

Calculates the Euclidean distance from each cell to the closest edge of the graph. Supports accelerated BVH queries and coordinate perturbation.

Parameters
graphInput graph containing nodes and edges.
shapeDimensions (width, height) of the output array grid.
bboxBounding box of the array grid in the format (xmin, xmax, ymin, ymax).
p_noise_xPointer to an optional noise array for perturbing x-coordinates.
p_noise_yPointer to an optional noise array for perturbing y-coordinates.
use_bvhWhether to use BVH spatial acceleration (default: true).
Returns
Array containing Euclidean distance to the graph network.

◆ sdf_2d_graph_brute_force()

Array hmap::sdf_2d_graph_brute_force ( const Graph & graph,
glm::ivec2 shape,
const UvRect & uv_rect = UvRect::unit(),
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr )

◆ sdf_2d_graph_bvh()

Array hmap::sdf_2d_graph_bvh ( const Graph & graph,
glm::ivec2 shape,
const UvRect & uv_rect = UvRect::unit(),
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr )

◆ perturb_mask_contour()

Array hmap::perturb_mask_contour ( const Array & mask,
const Array & noise,
float max_displacement,
int ir = 1 )

Perturb the contour of a binary mask using a displacement field, while trying to preserve a single connected component without holes.

This function takes a binary mask and a noise map of the same size, computes the boundary of the mask, estimates a local outward normal for each boundary pixel, and displaces that pixel by an amount proportional to the noise value. The displacement is clamped to remain inside the image domain.

Parameters
maskInput binary mask as an Array (0 = background, >0 = foreground). Must be at least 3×3 in size.
noiseNoise field providing signed displacement factors, typically in [-1, 1]. Must have the same dimensions as mask.
max_displacementMaximum displacement magnitude in pixels applied along the estimated boundary normal for each pixel.
irNeighborhood radius used for normal estimation and contour reconnection.
Returns
A new Array representing the perturbed binary mask, with values 0 (background) and 1 (foreground), guaranteed to be a single connectedcomponent without holes.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {8.f, 8.f};
int seed = 1;
hmap::Array mask = hmap::cone(shape, 3.f);
hmap::make_binary(mask, 0.f);
shape,
res,
seed);
float max_displacement = 32.f; // pixels
auto mask_p = hmap::perturb_mask_contour(mask, noise, max_displacement);
hmap::export_banner_png("ex_perturb_mask_contour.png",
{mask, noise, mask_p},
}
Array perturb_mask_contour(const Array &mask, const Array &noise, float max_displacement, int ir=1)
Perturb the contour of a binary mask using a displacement field, while trying to preserve a single co...
Definition perturb_mask_contour.cpp:14

Result

◆ scan_mask()

Array hmap::scan_mask ( const Array & array,
float contrast = 0.5f,
float brightness = 0.5f )

Mask adjustement using a 'scanning' method.

See https://www.shadertoy.com/view/stjSRR

Parameters
arrayInput array.
contrastContrast.
brightnessBrightness.
Returns
Ouput array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
// contrast / brightness
auto z1 = hmap::scan_mask(z, 0.8f, 0.5f);
auto z2 = hmap::scan_mask(z, 0.5f, 0.2f);
hmap::export_banner_png("ex_scan_mask.png", {z, z1, z2}, hmap::Cmap::MAGMA);
}
Array scan_mask(const Array &array, float contrast=0.5f, float brightness=0.5f)
Mask adjustement using a 'scanning' method.
Definition selector.cpp:23

Result

◆ select_angle()

Array hmap::select_angle ( const Array & array,
float angle,
float sigma )

Return angle selection for a given angle and a tolerance half-width on this value.

Parameters
arrayInput array.
angleSelected angle (degree).
sigmaSelected angle tolerance (degree).
Returns
Output array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {2.f, 2.f};
int seed = 1;
// select angle 90° +- 30°
float angle = 90.f;
float sigma = 30.f;
hmap::Array c = hmap::select_angle(z, angle, sigma);
hmap::export_banner_png("ex_select_angle.png", {z, c}, hmap::Cmap::JET);
}
Array select_angle(const Array &array, float angle, float sigma)
Return angle selection for a given angle and a tolerance half-width on this value.
Definition selector.cpp:47

Result

◆ select_blob_log()

Array hmap::select_blob_log ( const Array & array,
int ir,
bool normalize = false,
ICommunicator & comm = SingleArrayComm::instance() )

Return blob detection using the Laplacian of Gaussian (LoG) approach.

Parameters
arrayInput array.
irKernel radius.
normalizeIf true, normalize and clip output to [0, 1] using standard deviation with a smooth transition.
commCommunicator for collective normalization.
Returns
Array Output array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
int ir = 32;
z.to_png("ex_select_blob0.png", hmap::Cmap::VIRIDIS);
c.to_png("ex_select_blob1.png", hmap::Cmap::VIRIDIS);
}
Array select_blob_log(const Array &array, int ir, bool normalize=false, ICommunicator &comm=SingleArrayComm::instance())
Return blob detection using the Laplacian of Gaussian (LoG) approach.
Definition selector.cpp:79

Result

◆ select_cavities()

Array hmap::select_cavities ( const Array & array,
int ir,
bool concave = true,
bool normalize = false,
ICommunicator & comm = SingleArrayComm::instance() )

Return holes or bumps detection based on the mean curvature of the heightmap.

Parameters
arrayInput array.
irKernel radius.
concaveSelect 'holes' if set to true, and select 'bumps' if set to false.
normalizeIf true, normalize and clip output to [0, 1] using standard deviation with a smooth transition.
commCommunicator for collective normalization.
Returns
Array Output array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
int ir = 32;
hmap::Array c1 = hmap::select_cavities(z, ir); // holes
hmap::Array c2 = hmap::select_cavities(z, ir, false); // bumps
hmap::export_banner_png("ex_select_cavities.png",
{z, c1, c2},
}
Array select_cavities(const Array &array, int ir, bool concave=true, bool normalize=false, ICommunicator &comm=SingleArrayComm::instance())
Return holes or bumps detection based on the mean curvature of the heightmap.
Definition selector.cpp:99

Result

◆ select_eq()

Array hmap::select_eq ( const Array & array,
float value )

Return an array with elements equal to 1 where input elements are equal to value.

Parameters
arrayInput array.
valueCriteria value.
Returns
Array Output array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
z.to_png("ex_select0.png", hmap::Cmap::VIRIDIS);
c1.to_png("ex_select1.png", hmap::Cmap::GRAY);
c2.to_png("ex_select2.png", hmap::Cmap::GRAY);
hmap::Array c3 = hmap::select_interval(z, 0.25f, 0.75f);
c3.to_png("ex_select3.png", hmap::Cmap::GRAY);
c4.to_png("ex_select4.png", hmap::Cmap::GRAY);
}
Array select_lt(const Array &array, float value)
Return an array with elements equal to 1 where input elements are smaller than value.
Definition selector.cpp:245
Array select_gt(const Array &array, float value)
Return an array with elements equal to 1 where input elements are larger than value.
Definition selector.cpp:134
Array select_eq(const Array &array, float value)
Return an array with elements equal to 1 where input elements are equal to value.
Definition selector.cpp:123

Result

◆ select_gradient_angle()

Array hmap::select_gradient_angle ( const Array & array,
float angle )

Return an array weighted by the gap between the gradient angle and a given angle.

Parameters
arrayInput array.
angleReference angle (degree).
Returns
Array Output array.

◆ select_gradient_binary()

Array hmap::select_gradient_binary ( const Array & array,
float talus_center )

Return an array filled with 1 where the gradient is larger than a given value and 0 elsewhere.

Parameters
arrayInput array.
talus_centerReference talus.
Returns
Array Output array.

◆ select_gradient_exp()

Array hmap::select_gradient_exp ( const Array & array,
float talus_center,
float talus_sigma )

Return an array weighted (exponantial decay) by the gradient norm of the input array.

Parameters
arrayInput array.
talus_centerReference talus.
talus_sigmaTalus half-width.
Returns
Array Output array.

◆ select_gradient_inv()

Array hmap::select_gradient_inv ( const Array & array,
float talus_center,
float talus_sigma )

Return an array weighted (square inverse) by the gradient norm of the input array.

Parameters
arrayInput array.
talus_centerReference talus.
talus_sigmaTalus half-width.
Returns
Array Output array.

◆ select_gt()

Array hmap::select_gt ( const Array & array,
float value )

Return an array with elements equal to 1 where input elements are larger than value.

Parameters
arrayInput array.
valueCriteria value.
Returns
Array Output array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
z.to_png("ex_select0.png", hmap::Cmap::VIRIDIS);
c1.to_png("ex_select1.png", hmap::Cmap::GRAY);
c2.to_png("ex_select2.png", hmap::Cmap::GRAY);
hmap::Array c3 = hmap::select_interval(z, 0.25f, 0.75f);
c3.to_png("ex_select3.png", hmap::Cmap::GRAY);
c4.to_png("ex_select4.png", hmap::Cmap::GRAY);
}

Result

◆ select_interval()

Array hmap::select_interval ( const Array & array,
float value1,
float value2 )

Return an array with elements equal to 1 where input elements are within the bounds provided.

Parameters
arrayInput array.
value1Lower bound.
value2Upper bound.
Returns
Array Output array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
z.to_png("ex_select0.png", hmap::Cmap::VIRIDIS);
c1.to_png("ex_select1.png", hmap::Cmap::GRAY);
c2.to_png("ex_select2.png", hmap::Cmap::GRAY);
hmap::Array c3 = hmap::select_interval(z, 0.25f, 0.75f);
c3.to_png("ex_select3.png", hmap::Cmap::GRAY);
c4.to_png("ex_select4.png", hmap::Cmap::GRAY);
}

Result

◆ select_inward_outward_slope()

Array hmap::select_inward_outward_slope ( const Array & array,
glm::vec2 center = {0.5f, 0.5f},
const BBox2D & bbox = BBox2D::unit() )

Return an array with positive values if the slope is pointing to the center (slope is inward), and negative values otherwise (slope is outward).

Parameters
arrayInput array.
centerReference center.
bboxDomain bounding box.
Returns
Output array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {2.f, 2.f};
int seed = 1;
hmap::export_banner_png("ex_select_inward_outward_slope.png",
{z, c},
}
Array select_inward_outward_slope(const Array &array, glm::vec2 center={0.5f, 0.5f}, const BBox2D &bbox=BBox2D::unit())
Return an array with positive values if the slope is pointing to the center (slope is inward),...
Definition selector.cpp:209

Result

◆ select_lt()

Array hmap::select_lt ( const Array & array,
float value )

Return an array with elements equal to 1 where input elements are smaller than value.

Parameters
arrayInput array.
valueCriteria value.
Returns
Array Output array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
z.to_png("ex_select0.png", hmap::Cmap::VIRIDIS);
c1.to_png("ex_select1.png", hmap::Cmap::GRAY);
c2.to_png("ex_select2.png", hmap::Cmap::GRAY);
hmap::Array c3 = hmap::select_interval(z, 0.25f, 0.75f);
c3.to_png("ex_select3.png", hmap::Cmap::GRAY);
c4.to_png("ex_select4.png", hmap::Cmap::GRAY);
}

Result

◆ select_midrange() [1/2]

Array hmap::select_midrange ( const Array & array,
float gain,
float vmin,
float vmax )

Selects the midrange values of the input array within a specified range.

Parameters
arrayThe input array from which the midrange values are selected.
gainThe gain factor to scale the selected midrange values.
vminThe minimum value for range.
vmaxThe maximum value for range.
Returns
An array containing the midrange values.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
float gain = 1.f;
hmap::export_banner_png("ex_select_midrange.png", {z, c}, hmap::Cmap::MAGMA);
}
Array select_midrange(const Array &array, float gain, float vmin, float vmax)
Selects the midrange values of the input array within a specified range.
Definition selector.cpp:256

Result

◆ select_midrange() [2/2]

Array hmap::select_midrange ( const Array & array,
float gain )

Selects and scales the midrange values of the input array.

This function extracts the midrange portion of the input array and scales it by the specified gain.

Parameters
arrayThe input array from which the midrange values are selected.
gainThe gain factor to scale the selected midrange values.
Returns
An array containing the midrange values scaled by the gain.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
float gain = 1.f;
hmap::export_banner_png("ex_select_midrange.png", {z, c}, hmap::Cmap::MAGMA);
}

Result

◆ select_multiband3() [1/2]

void hmap::select_multiband3 ( const Array & array,
Array & band_low,
Array & band_mid,
Array & band_high,
float ratio1,
float ratio2,
float overlap,
float vmin,
float vmax )

Splits the input array into three bands (low, mid, and high) based on given ratios and overlap.

This function processes the input array and divides it into three value bands: low, mid, and high. The bands are determined by the provided ratios and overlap. Optionally, a range (vmin, vmax) can be applied to the values in the array.

Parameters
arrayThe input array that contains the data to be split into bands.
band_lowThe output array for the low-value band.
band_midThe output array for the mid-value band.
band_highThe output array for the high-value band.
ratio1The ratio that defines the split between the low and mid bands.
ratio2The ratio that defines the split between the mid and high bands.
overlapThe amount of overlap between adjacent bands.
vminThe minimum value for range filtering. Values below vmin will be clamped. (Optional, only in the first function)
vmaxThe maximum value for range filtering. Values above vmax will be clamped. (Optional, only in the first function)

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
hmap::Array band_low;
hmap::Array band_mid;
hmap::Array band_high;
float ratio1 = 0.2f;
float ratio2 = 0.5f;
float overlap = 0.5f;
band_low,
band_mid,
band_high,
ratio1,
ratio2,
overlap);
hmap::export_banner_png("ex_select_multiband3.png",
{z, band_low, band_mid, band_high},
}
void select_multiband3(const Array &array, Array &band_low, Array &band_mid, Array &band_high, float ratio1, float ratio2, float overlap, float vmin, float vmax)
Splits the input array into three bands (low, mid, and high) based on given ratios and overlap.
Definition selector.cpp:284

Result

◆ select_multiband3() [2/2]

void hmap::select_multiband3 ( const Array & array,
Array & band_low,
Array & band_mid,
Array & band_high,
float ratio1,
float ratio2,
float overlap )

Splits the input array into three bands (low, mid, and high) based on given ratios and overlap.

This function processes the input array and divides it into three value bands: low, mid, and high. The bands are determined by the provided ratios and overlap.

Parameters
arrayThe input array that contains the data to be split into bands.
band_lowThe output array for the low-value band.
band_midThe output array for the mid-value band.
band_highThe output array for the high-value band.
ratio1The ratio that defines the split between the low and mid bands.
ratio2The ratio that defines the split between the mid and high bands.
overlapThe amount of overlap between adjacent bands.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
hmap::Array band_low;
hmap::Array band_mid;
hmap::Array band_high;
float ratio1 = 0.2f;
float ratio2 = 0.5f;
float overlap = 0.5f;
band_low,
band_mid,
band_high,
ratio1,
ratio2,
overlap);
hmap::export_banner_png("ex_select_multiband3.png",
{z, band_low, band_mid, band_high},
}

Result

◆ select_pulse()

Array hmap::select_pulse ( const Array & array,
float value,
float sigma )

Return an array filled with non-zero values where the input is in the interval [value - sigma, value + sigma]. Output array values have a cubic pulse distribution within this interval.

Parameters
arrayInput array.
valueCentral value.
sigmaPulse width.
Returns
Array Output array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
// select values in [0.3, 0.7] with a smooth transition
hmap::Array c = hmap::select_pulse(z, 0.5f, 0.2f);
hmap::export_banner_png("ex_select_pulse.png", {z, c}, hmap::Cmap::INFERNO);
}
Array select_pulse(const Array &array, float value, float sigma)
Return an array filled with non-zero values where the input is in the interval [value - sigma,...
Definition selector.cpp:354

Result

◆ select_range()

Array hmap::select_range ( const Array & array,
float vmin,
float vmax,
float width )

Return a selection mask for a value range [vmin, vmax] with smooth transitions of specified width at both ends.

The output value is 1.0 inside [vmin, vmax], 0.0 outside [vmin - width, vmax

  • width], and smoothly transitions using smoothstep (threshold_smooth) between 0 and 1.
Parameters
arrayInput array.
vminLower range bound.
vmaxUpper range bound.
widthTransition width at the boundaries.
Returns
Array Output mask with values in [0, 1].

◆ select_rivers()

Array hmap::select_rivers ( const Array & array,
float talus_ref,
float clipping_ratio )

Return an array filled with a criterion based on the occurence of a river bed.

Parameters
arrayInput array.
talus_refReference talus used to localy define the flow-partition.
clipping_ratioFlow accumulation clipping ratio.
Returns
Array Output array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {2.f, 2.f};
int seed = 1;
float talus_ref = 4.f;
float clipping_ratio = 50.f;
hmap::Array c = hmap::select_rivers(z, talus_ref, clipping_ratio);
hmap::export_banner_png("ex_select_rivers.png", {z, c}, hmap::Cmap::INFERNO);
}

Result

◆ select_transitions()

Array hmap::select_transitions ( const Array & array1,
const Array & array2,
const Array & array_blend )

Return an array filled with 1 at the blending transition between two arrays, and 0 elsewhere.

Parameters
array1Input array 1.
array2Input array 2.
array_blendBlending of array 1 and 2 to analyze.
Returns
Array Resulting array

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {128, 128};
int seed = 1;
shape,
{2.f, 2.f},
seed);
shape,
{4.f, 4.f},
++seed);
hmap::Array z_m = hmap::minimum(z1, z2); // sharp transition
hmap::Array z_s = hmap::minimum_smooth(z1, z2, 0.2f); // smooth transition
hmap::Array mask_m = hmap::select_transitions(z1, z2, z_m);
hmap::Array mask_s = hmap::select_transitions(z1, z2, z_s);
hmap::export_banner_png("ex_select_transitions0.png",
{z1, z2},
hmap::export_banner_png("ex_select_transitions1.png",
{z_m, z_s},
hmap::export_banner_png("ex_select_transitions2.png",
{mask_m, mask_s},
}
Array minimum_smooth(const Array &array1, const Array &array2, float k=0.2)
Return the polynomial cubic smooth element-wise minimum of two arrays.
Definition range.cpp:381
Array select_transitions(const Array &array1, const Array &array2, const Array &array_blend)
Return an array filled with 1 at the blending transition between two arrays, and 0 elsewhere.
Definition selector.cpp:419
Array minimum(const Array &array1, const Array &array2)
Return the element-wise minimum of two arrays.
Definition range.cpp:355

Result

◆ select_valley()

Array hmap::select_valley ( const Array & z,
int ir,
bool ridge_select = false,
bool normalize = false,
ICommunicator & comm = SingleArrayComm::instance() )

◆ smooth_mask_preserve_frontier()

Array hmap::smooth_mask_preserve_frontier ( const Array & mask,
float feather_width,
const UvTile & region = UvTile::dummy(),
ICommunicator & comm = SingleArrayComm::instance() )

Smooths a binary mask with an inward falloff while preserving its 0-boundary.

Computes a smooth falloff inside the non-zero region of the mask towards the 0/1 frontier using distance transform and smoothstep. The 0-set of the output remains identical to the input mask (no dilation beyond the boundary).

Parameters
maskInput binary mask ({0, 1}).
feather_widthWidth of the feathering falloff in grid units.
Returns
Array Smoothed mask with smooth falloff of the 1s.

◆ hillshade()

Array hmap::hillshade ( const Array & z,
float azimuth,
float zenith,
float talus_ref = 1.f )

Compute the shaded relief map (hillshading) from a heightmap.

This function calculates the shaded relief map of the input array based on the sun's azimuth (direction) and zenith (elevation) angles. The shading effect simulates the appearance of topographic features based on light direction.

Parameters
zInput array representing the heightmap.
azimuthSun azimuth (direction) in degrees.
zenithSun zenith (elevation) in degrees.
talus_refReference talus used to normalize gradient computations. It can be useful when working with true angles. Default is 1.f.
Returns
Array Resulting shaded relief map.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
float azimuth = 180.f; // exposure from the west
float zenith = 45.f; // "sun elevation angle"
hmap::Array ts = hmap::topographic_shading(z, azimuth, zenith);
hmap::Array hs = hmap::hillshade(z, azimuth, zenith);
float shadow_talus = 2.f / shape.x;
hmap::Array sg = hmap::shadow_grid(z, shadow_talus);
ts.to_png("ex_hillshade0.png", hmap::Cmap::BONE);
hs.to_png("ex_hillshade1.png", hmap::Cmap::BONE);
sg.to_png("ex_hillshade2.png", hmap::Cmap::BONE);
}
Array topographic_shading(const Array &z, float azimuth, float zenith, float talus_ref=1.f)
Compute the topographic shadow intensity in the range [-1, 1].
Definition shadows.cpp:33
Array shadow_grid(const Array &z, float shadow_talus)
Compute the shadow intensity using a grid-based technique.
Definition shadows.cpp:52
Array hillshade(const Array &z, float azimuth, float zenith, float talus_ref=1.f)
Compute the shaded relief map (hillshading) from a heightmap.
Definition shadows.cpp:16

Result

See also
topographic_shading

◆ shadow_grid()

Array hmap::shadow_grid ( const Array & z,
float shadow_talus )

Compute the shadow intensity using a grid-based technique.

This function calculates the shadow intensity from the input array using a grid-based approach. The shadow talus parameter influences the calculation of shadow intensity.

Parameters
zInput array representing the heightmap.
shadow_talusParameter affecting the shadow intensity computation.
Returns
Array Resulting shadow intensity map.

◆ shadow_heightmap()

Array hmap::shadow_heightmap ( const Array & z,
float azimuth = 180.f,
float zenith = 45.f,
float distance = 0.2f )

Compute crude shadows from a heightmap.

This function generates crude shadow effects from the input heightmap using the specified light azimuth, zenith, and distance. The method is based on the technique described in https://www.shadertoy.com/view/Xlsfzl.

Parameters
zInput array representing the heightmap.
azimuthLight azimuth (direction) in degrees. Default is 180.f.
zenithLight zenith (elevation) in degrees. Default is 45.f.
distanceLight distance. Default is 0.2f.
Returns
Array Resulting crude shadow map.

◆ topographic_shading()

Array hmap::topographic_shading ( const Array & z,
float azimuth,
float zenith,
float talus_ref = 1.f )

Compute the topographic shadow intensity in the range [-1, 1].

This function calculates the topographic shadow intensity of the input array based on the sun's azimuth and zenith. The shadow intensity is normalized to fall within the range [-1, 1].

Parameters
zInput array representing the heightmap.
azimuthSun azimuth (direction) in degrees.
zenithSun zenith (elevation) in degrees.
talus_refReference talus used to normalize gradient computations. It can be useful when working with true angles. Default is 1.f.
Returns
Array Resulting topographic shadow intensity map.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
float azimuth = 180.f; // exposure from the west
float zenith = 45.f; // "sun elevation angle"
hmap::Array ts = hmap::topographic_shading(z, azimuth, zenith);
hmap::Array hs = hmap::hillshade(z, azimuth, zenith);
float shadow_talus = 2.f / shape.x;
hmap::Array sg = hmap::shadow_grid(z, shadow_talus);
ts.to_png("ex_hillshade0.png", hmap::Cmap::BONE);
hs.to_png("ex_hillshade1.png", hmap::Cmap::BONE);
sg.to_png("ex_hillshade2.png", hmap::Cmap::BONE);
}

Result

See also
hillshade

◆ dijkstra()

Path hmap::dijkstra ( const Path & path,
const Array & array,
const UvRect & uv_rect,
float elevation_ratio = 0.f,
float distance_exponent = 0.5f,
float upward_penalization = 0.1f,
Array * p_mask_nogo = nullptr )

Divide the path by adding points based on the lowest elevation difference between each pair of edge endpoints.

This method uses the elevation map to subdivide the path by adding intermediate points where the elevation difference between edges is minimal. The elevation_ratio parameter balances the influence of absolute elevation versus elevation difference in the cost function used for path finding. The distance_exponent affects the weight function used in Dijkstra's algorithm. Areas defined by the p_mask_nogo mask are avoided.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 2;
int npoints = 10;
hmap::BBox2D bbox = {0.f, 1.f, 0.f, 1.f};
hmap::Path path = hmap::Path(npoints,
seed,
hmap::BBox2D(0.1f, 0.9f, 0.1f, 0.9f));
path.set_closed(false);
path.reorder_nns();
path.set_values_from_array(z, bbox);
// before
auto z1 = path.to_array(shape, bbox);
// after
int edge_divisions = 0;
path = hmap::dijkstra(path, z, hmap::UvRect::unit(), edge_divisions, 0.9f);
path.set_values_from_array(z, bbox);
auto z2 = path.to_array(shape, bbox);
hmap::export_banner_png("ex_path_dijkstra.png",
{z, z1, z2},
}

Result

Parameters
arrayElevation map used to determine elevation differences along the path.
bboxBounding box of the domain, defining the area where elevation data is valid.
edge_divisionsNumber of subdivisions per edge; set to 0 for automatic division based on array shape.
elevation_ratioRatio used to balance absolute elevation and elevation difference in the cost function.
distance_exponentExponent used in the Dijkstra weight function to adjust the influence of distance.
p_mask_nogoOptional mask array defining areas to avoid; points in these areas will not be considered.
See also
Array::find_path_dijkstra

◆ find_cut_path_dijkstra() [1/2]

Path hmap::find_cut_path_dijkstra ( const Array & z,
DomainBoundary start,
DomainBoundary end,
float dijk_elevation_ratio = 0.9f,
float dijk_distance_exponent = 2.f,
float dijk_upward_penalization = 100.f,
std::uint32_t seed = 0,
bool favor_boundary_center = true,
bool favor_lower_elevation = true,
bool favor_sinks = true,
bool favor_domain_center = false )

Find a Dijkstra-based cut path between two domain boundaries.

Selects the lowest point on the start and end boundaries of heightmap z, then computes a path between them using a weighted Dijkstra search. The path cost combines elevation, distance, and uphill penalization. The result is returned as normalized (x, y) coordinates and elevation samples.

Parameters
zHeightmap array.
startBoundary where the path begins.
endBoundary where the path ends.
dijk_elevation_ratioWeight of elevation in the cost.
dijk_distance_exponentExponent applied to distance cost.
dijk_upward_penalizationExtra penalty for uphill moves.
favor_domain_centerFavor passing through the center of the domain.
Returns
Path containing normalized (x, y) points and elevations.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {2.f, 2.f};
int seed = 0;
// Dijkstra
z,
hmap::Array zp = path.to_array(shape);
// greedy midpoint
z,
seed);
hmap::Array zp2 = path2.to_array(shape);
// multiscale
z,
hmap::Array zp3 = path3.to_array(shape);
hmap::export_banner_png("ex_find_cut_path.png",
{z, zp, zp2, zp3},
}
Path find_cut_path_multiscale(const Array &z, DomainBoundary start, DomainBoundary end, int n_levels=3, int corridor_radius=4, float corridor_decay=1.f, float dijk_elevation_ratio=0.9f, float dijk_distance_exponent=2.f, float dijk_upward_penalization=100.f, std::uint32_t seed=0, bool favor_boundary_center=true, bool favor_lower_elevation=true, bool favor_sinks=true, bool use_astar=false, bool smooth_path=false)
Find a fast coarse-to-fine multiscale cut path between two domain boundaries.
Definition find_cut_path.cpp:193

Result

◆ find_cut_path_dijkstra() [2/2]

Path hmap::find_cut_path_dijkstra ( const Array & z,
DomainBoundary start,
DomainBoundary end,
std::uint32_t seed,
size_t control_points_count = 2048,
bool favor_boundary_center = true,
bool favor_lower_elevation = true,
bool favor_sinks = true,
bool favor_domain_center = false,
const UvTile & region = UvTile::unit(),
ICommunicator & comm = SingleArrayComm::instance() )

Generate a cut path across a heightmap using a random triangular mesh and Dijkstra shortest path search (tileable).

Parameters
zHeightmap array (or tile).
startStart boundary.
endEnd boundary.
seedRandom seed for mesh point generation.
control_points_countNumber of control points sampled for the mesh.
favor_boundary_centerFavor points near the center of the boundary.
favor_lower_elevationFavor lower elevation points on the boundary.
favor_sinksFavor local depressions.
favor_domain_centerFavor passing through the center of the domain.
regionTile region metadata.
commTiled communicator instance.
Returns
Path containing normalized 3D coordinates and elevations (empty on non-root ranks).

◆ find_cut_path_midpoint()

Path hmap::find_cut_path_midpoint ( const Array & z,
DomainBoundary start,
DomainBoundary end,
std::uint32_t seed,
float offset_ratio = 0.2f,
int steps = 16,
bool favor_boundary_center = true,
bool favor_lower_elevation = true,
bool favor_sinks = true,
const UvTile & region = UvTile::unit(),
ICommunicator & comm = SingleArrayComm::instance() )

Generate a stochastic cut path using midpoint displacement.

Creates a path between the start and end boundaries of heightmap z by recursively subdividing and perturbing a segment. The result is a natural, irregular path defined by normalized (x, y) coordinates and elevations.

Parameters
zHeightmap array.
startStart boundary.
endEnd boundary.
seedRandom seed.
midp_iterationsNumber of subdivision steps.
midp_sigmaDisplacement amplitude.
favor_boundary_centerFavor points near the center of the boundary.
favor_lower_elevationFavor lower elevation points on the boundary.
favor_sinksFavor local depressions.
regionTile region metadata.
commTiled communicator instance.
Returns
Path with normalized coordinates and elevations.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 kw = {2.f, 2.f};
int seed = 0;
// Dijkstra
z,
hmap::Array zp = path.to_array(shape);
// greedy midpoint
z,
seed);
hmap::Array zp2 = path2.to_array(shape);
// multiscale
z,
hmap::Array zp3 = path3.to_array(shape);
hmap::export_banner_png("ex_find_cut_path.png",
{z, zp, zp2, zp3},
}

Result

◆ find_cut_path_multiscale()

Path hmap::find_cut_path_multiscale ( const Array & z,
DomainBoundary start,
DomainBoundary end,
int n_levels = 3,
int corridor_radius = 4,
float corridor_decay = 1.f,
float dijk_elevation_ratio = 0.9f,
float dijk_distance_exponent = 2.f,
float dijk_upward_penalization = 100.f,
std::uint32_t seed = 0,
bool favor_boundary_center = true,
bool favor_lower_elevation = true,
bool favor_sinks = true,
bool use_astar = false,
bool smooth_path = false )

Find a fast coarse-to-fine multiscale cut path between two domain boundaries.

Selects candidate boundary cells on the start and end boundaries, then computes a path using hierarchical multiscale search with corridor restriction.

Parameters
zHeightmap array.
startBoundary where the path begins.
endBoundary where the path ends.
n_levelsNumber of multiscale pyramid levels.
corridor_radiusCorridor radius in grid cells.
corridor_decayCorridor radius decay factor per level.
dijk_elevation_ratioWeight of elevation in the cost.
dijk_distance_exponentExponent applied to distance cost.
dijk_upward_penalizationExtra penalty for uphill moves.
seedSeed for boundary cell selection.
favor_boundary_centerBias boundary cell toward center.
favor_lower_elevationBias boundary cell toward lower elevation.
favor_sinksBias boundary cell toward local sinks.
use_astarUse A* heuristic.
smooth_pathSmooth the resulting path.
Returns
Path containing normalized coordinates and sampled elevations.

◆ find_path_dijkstra() [1/5]

void hmap::find_path_dijkstra ( const Array & z,
glm::ivec2 ij_start,
glm::ivec2 ij_end,
std::vector< int > & i_path,
std::vector< int > & j_path,
float elevation_ratio = 0.1f,
float distance_exponent = 2.f,
float upward_penalization = 0.1f,
const Array * p_mask_nogo = nullptr,
const Array * p_node_weights = nullptr )

Finds the path with the lowest elevation and elevation difference between two points in a 2D array using Dijkstra's algorithm.

This function calculates the shortest path considering both elevation and elevation differences. It uses a cost function that balances between absolute elevation and elevation change. The path is determined by minimizing the combined cost function.

See also
[Dijkstra1971] and https://math.stackexchange.com/questions/3088292
Warning
The elevation_ratio parameter must be less than 1 for the algorithm to converge properly.
Parameters
ij_startStarting coordinates (i, j) for the pathfinding.
ij_endEnding coordinates (i, j) for the pathfinding.
i_path[out]Vector to store the resulting shortest path indices in the i direction.
j_path[out]Vector to store the resulting shortest path indices in the j direction.
elevation_ratioBalance factor between absolute elevation and elevation difference in the cost function. Should be in the range [0, 1[.
distance_exponentExponent used in the distance calculation between points. A higher exponent increases the cost of elevation gaps, encouraging the path to minimize elevation changes and reduce overall cumulative elevation gain.
upward_penalizationPenalize upstream slopes.
p_mask_nogoOptional pointer to an array mask that defines areas to avoid during pathfinding.

Example

#include <vector>
#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {2.f, 2.f};
int seed = 1;
z.to_png("ex_find_path_dijkstra0.png", hmap::Cmap::TERRAIN, true);
glm::ivec2 ij_start = {40, 40};
glm::ivec2 ij_end = {230, 230};
glm::vec4 bbox = {0.f, 1.f, 0.f, 1.f};
// default parameters
hmap::Path path1 = hmap::find_path_dijkstra(z, ij_start, ij_end, bbox);
hmap::Array w1 = path1.to_array(shape);
// set "elevation_ratio" to 1.f to find the path with the lowest
// cumulative elevation
hmap::Path path2 = hmap::find_path_dijkstra(z, ij_start, ij_end, bbox, 1.f);
hmap::Array w2 = path2.to_array(shape);
hmap::export_banner_png("ex_find_path_dijkstra.png",
{z, w1, w2},
}
void find_path_dijkstra(const Array &z, glm::ivec2 ij_start, glm::ivec2 ij_end, std::vector< int > &i_path, std::vector< int > &j_path, float elevation_ratio=0.1f, float distance_exponent=2.f, float upward_penalization=0.1f, const Array *p_mask_nogo=nullptr, const Array *p_node_weights=nullptr)
Finds the path with the lowest elevation and elevation difference between two points in a 2D array us...
Definition dijsktra.cpp:159

Result

◆ find_path_dijkstra() [2/5]

void hmap::find_path_dijkstra ( const Array & z,
glm::ivec2 ij_start,
std::vector< glm::ivec2 > ij_end_list,
std::vector< std::vector< int > > & i_path_list,
std::vector< std::vector< int > > & j_path_list,
float elevation_ratio = 0.1f,
float distance_exponent = 2.f,
float upward_penalization = 0.1f,
const Array * p_mask_nogo = nullptr,
const Array * p_node_weights = nullptr )

◆ find_path_dijkstra() [3/5]

Path hmap::find_path_dijkstra ( const Array & z,
glm::vec2 start,
glm::vec2 end,
std::uint32_t seed,
size_t control_points_count = 2048,
bool favor_domain_center = false,
const UvTile & region = UvTile::unit(),
ICommunicator & comm = SingleArrayComm::instance() )

Generate a path between two points across a heightmap using a random triangular mesh and Dijkstra shortest path search (tileable).

Parameters
zHeightmap array (or tile).
startStart coordinates (x, y) in [0, 1].
endEnd coordinates (x, y) in [0, 1].
seedRandom seed for mesh point generation.
control_points_countNumber of control points sampled for the mesh.
favor_domain_centerFavor passing through the center of the domain.
regionTile region metadata.
commTiled communicator instance.
Returns
Path containing 3D coordinates and elevations (empty on non-root ranks).

◆ find_path_dijkstra() [4/5]

std::vector< glm::ivec2 > hmap::find_path_dijkstra ( const Array & z,
glm::ivec2 ij_start,
glm::ivec2 ij_end,
float elevation_ratio = 0.1f,
float distance_exponent = 2.f,
float upward_penalization = 0.1f,
const Array * p_mask_nogo = nullptr,
const Array * p_node_weights = nullptr )

Overload of find_path_dijkstra returning a vector of grid indices.

Parameters
zHeightmap array.
ij_startStart grid index (i, j).
ij_endEnd grid index (i, j).
elevation_ratioWeight of absolute elevation in cost.
distance_exponentExponent applied to distance cost.
upward_penalizationPenalty factor for uphill moves.
p_mask_nogoOptional obstacle mask.
p_node_weightsOptional node/cell cost multiplier weights.
Returns
Vector of 2D grid indices forming the path.

◆ find_path_dijkstra() [5/5]

Path hmap::find_path_dijkstra ( const Array & z,
glm::ivec2 ij_start,
glm::ivec2 ij_end,
const UvRect & uv_rect,
float elevation_ratio = 0.1f,
float distance_exponent = 2.f,
float upward_penalization = 0.1f,
const Array * p_mask_nogo = nullptr,
const Array * p_node_weights = nullptr )

Overload of find_path_dijkstra returning a Path mapped to a bounding box with point values holding sampled terrain elevations.

Parameters
zHeightmap array.
ij_startStart grid index (i, j).
ij_endEnd grid index (i, j).
bboxBounding box for coordinate remapping.
elevation_ratioWeight of absolute elevation in cost.
distance_exponentExponent applied to distance cost.
upward_penalizationPenalty factor for uphill moves.
p_mask_nogoOptional obstacle mask.
p_node_weightsOptional node/cell cost multiplier weights.
Returns
Path with coordinates and sampled elevation values.

◆ find_path_midpoint() [1/3]

std::vector< glm::ivec2 > hmap::find_path_midpoint ( const Array & z,
glm::ivec2 ij_start,
glm::ivec2 ij_end,
float offset_ratio = 0.2f,
int max_it = 0,
int steps = 16 )

Compute a path between two points using iterative midpoint refinement.

The algorithm subdivides segments and shifts midpoints along the perpendicular direction to locally minimize the scalar field z. This is a fast heuristic alternative to graph-based methods (not guaranteed optimal).

Parameters
z2D scalar field (weights).
ij_startStart index.
ij_endEnd index.
offset_ratioRelative transverse displacement (per segment length).
max_itMax iterations (0 = automatic based on distance).
stepsNumber of samples for transverse search.
Returns
Vector of grid indices forming the path.

Example

#include <vector>
#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {2.f, 2.f};
int seed = 1;
glm::ivec2 ij_start = {40, 40};
glm::ivec2 ij_end = {230, 230};
glm::vec4 bbox = {0.f, 1.f, 0.f, 1.f};
float offset_ratio = 0.3f; // in [0, 1]
// smallest resolution
ij_start,
ij_end,
bbox,
offset_ratio);
// limit iterations
int max_it = 4;
ij_start,
ij_end,
bbox,
offset_ratio,
max_it);
// spline interpolation
hmap::Path path3 = hmap::bspline(path2);
// --- export path to a png file
hmap::Array w1 = path1.to_array(shape);
hmap::Array w2 = path2.to_array(shape);
hmap::Array w3 = path3.to_array(shape);
hmap::export_banner_png("ex_find_path_midpoint.png",
{z, w1, w2, w3},
}
std::vector< glm::ivec2 > find_path_midpoint(const Array &z, glm::ivec2 ij_start, glm::ivec2 ij_end, float offset_ratio=0.2f, int max_it=0, int steps=16)
Compute a path between two points using iterative midpoint refinement.
Definition find_path_midpoint.cpp:79

Result

◆ find_path_midpoint() [2/3]

void hmap::find_path_midpoint ( const Array & z,
glm::ivec2 ij_start,
glm::ivec2 ij_end,
std::vector< int > & i_path,
std::vector< int > & j_path,
float offset_ratio = 0.2f,
int max_it = 0,
int steps = 16 )

Overload of find_path_midpoint returning path indices in i and j vectors.

Parameters
z2D scalar field (weights).
ij_startStart index.
ij_endEnd index.
i_path[out]Vector storing path i indices.
j_path[out]Vector storing path j indices.
offset_ratioRelative transverse displacement (per segment length).
max_itMax iterations (0 = automatic based on distance).
stepsNumber of samples for transverse search.

◆ find_path_midpoint() [3/3]

Path hmap::find_path_midpoint ( const Array & z,
glm::ivec2 ij_start,
glm::ivec2 ij_end,
const UvRect & uv_rect,
float offset_ratio = 0.2f,
int max_it = 0,
int steps = 16 )

Overload of find_path_midpoint returning a Path mapped to a bounding box with point values holding sampled terrain elevations.

Parameters
z2D scalar field (weights).
ij_startStart index.
ij_endEnd index.
bboxBounding box for coordinate remapping.
offset_ratioRelative transverse displacement (per segment length).
max_itMax iterations (0 = automatic based on distance).
stepsNumber of samples for transverse search.
Returns
Path with coordinates and sampled elevation values.

◆ find_path_multiscale() [1/3]

void hmap::find_path_multiscale ( const Array & z,
glm::ivec2 ij_start,
glm::ivec2 ij_end,
std::vector< int > & i_path,
std::vector< int > & j_path,
int n_levels = 3,
int corridor_radius = 4,
float corridor_decay = 1.f,
float elevation_ratio = 0.1f,
float distance_exponent = 2.f,
float upward_penalization = 0.1f,
const Array * p_mask_nogo = nullptr,
bool use_astar = false,
bool smooth_path = false )

Finds a shortest path on a 2D grid using a fast coarse-to-fine multiscale approach.

This function solves pathfinding across multiple grid resolutions to drastically reduce the number of explored cells on large grids while maintaining high path quality. A coarse path is found on downsampled cost maps, upsampled to the next finer resolution, and restricted to a narrow search corridor at each stage.

Parameters
zHeightmap or cost array.
ij_startStarting grid index (i, j).
ij_endTarget grid index (i, j).
i_path[out]Vector storing resulting path i indices.
j_path[out]Vector storing resulting path j indices.
n_levelsNumber of multiscale pyramid levels (>= 1).
corridor_radiusRadius of search corridor in grid cells.
corridor_decayDecay factor applied to corridor radius per level.
elevation_ratioWeight factor for absolute elevation vs gradient.
distance_exponentExponent applied to elevation differences.
upward_penalizationPenalty factor for moving uphill.
p_mask_nogoOptional pointer to mask of impassable regions.
use_astarUse A* heuristic instead of Dijkstra.
smooth_pathApply smoothing to the resulting path.

Example

#include <vector>
#include "highmap.hpp"
int main(void)
{
const glm::ivec2 shape = {512, 512};
const glm::vec2 res = {2.f, 2.f};
const int seed = 42;
// generate terrain cost map
const glm::ivec2 ij_start = {50, 50};
const glm::ivec2 ij_end = {460, 460};
const glm::vec4 bbox = {0.f, 1.f, 0.f, 1.f};
const float elevation_ratio = 0.1f;
const float distance_exponent = 2.f;
const float upward_penalization = 0.1f;
// --- 1. find_path_dijkstra (full-resolution Dijkstra)
hmap::Timer::Start("find_path_dijkstra");
ij_start,
ij_end,
bbox,
elevation_ratio,
distance_exponent,
upward_penalization);
hmap::Timer::Stop("find_path_dijkstra");
hmap::Array w_dijk = path_dijk.to_array(shape);
// --- 2. find_path_midpoint (midpoint displacement heuristic)
const float offset_ratio = 0.2f;
hmap::Timer::Start("find_path_midpoint");
ij_start,
ij_end,
bbox,
offset_ratio);
hmap::Timer::Stop("find_path_midpoint");
hmap::Array w_midp = path_midp.to_array(shape);
// --- 3. find_path_multiscale (coarse-to-fine shortest path)
const int n_levels = 4;
const int corridor_radius = 12;
const float corridor_decay = 1.f;
const bool use_astar = false;
const bool smooth_path = false;
hmap::Timer::Start("find_path_multiscale");
ij_start,
ij_end,
bbox,
n_levels,
corridor_radius,
corridor_decay,
elevation_ratio,
distance_exponent,
upward_penalization,
nullptr,
use_astar,
smooth_path);
hmap::Timer::Stop("find_path_multiscale");
hmap::Array w_multi = path_multi.to_array(shape);
// --- Export banner
hmap::export_banner_png("ex_find_path_multiscale.png",
{z, w_dijk, w_midp, w_multi},
return 0;
}
static void Dump()
Dumps the timing information for all recorded events to the console.
Definition timer.cpp:69
void find_path_multiscale(const Array &z, glm::ivec2 ij_start, glm::ivec2 ij_end, std::vector< int > &i_path, std::vector< int > &j_path, int n_levels=3, int corridor_radius=4, float corridor_decay=1.f, float elevation_ratio=0.1f, float distance_exponent=2.f, float upward_penalization=0.1f, const Array *p_mask_nogo=nullptr, bool use_astar=false, bool smooth_path=false)
Finds a shortest path on a 2D grid using a fast coarse-to-fine multiscale approach.
Definition find_path_multiscale.cpp:225

Result

◆ find_path_multiscale() [2/3]

std::vector< glm::ivec2 > hmap::find_path_multiscale ( const Array & z,
glm::ivec2 ij_start,
glm::ivec2 ij_end,
int n_levels = 3,
int corridor_radius = 4,
float corridor_decay = 1.f,
float elevation_ratio = 0.1f,
float distance_exponent = 2.f,
float upward_penalization = 0.1f,
const Array * p_mask_nogo = nullptr,
bool use_astar = false,
bool smooth_path = false )

Overload of find_path_multiscale returning a vector of grid indices.

Parameters
zHeightmap or cost array.
ij_startStarting grid index (i, j).
ij_endTarget grid index (i, j).
n_levelsNumber of multiscale pyramid levels (>= 1).
corridor_radiusRadius of search corridor in grid cells.
corridor_decayDecay factor applied to corridor radius per level.
elevation_ratioWeight factor for absolute elevation vs gradient.
distance_exponentExponent applied to elevation differences.
upward_penalizationPenalty factor for moving uphill.
p_mask_nogoOptional pointer to mask of impassable regions.
use_astarUse A* heuristic instead of Dijkstra.
smooth_pathApply smoothing to the resulting path.
Returns
Vector of 2D grid indices forming the path.

◆ find_path_multiscale() [3/3]

Path hmap::find_path_multiscale ( const Array & z,
glm::ivec2 ij_start,
glm::ivec2 ij_end,
const UvRect & uv_rect,
int n_levels = 3,
int corridor_radius = 4,
float corridor_decay = 1.f,
float elevation_ratio = 0.1f,
float distance_exponent = 2.f,
float upward_penalization = 0.1f,
const Array * p_mask_nogo = nullptr,
bool use_astar = false,
bool smooth_path = false )

Overload of find_path_multiscale returning a Path object mapped to a bounding box, with point values containing the elevation sampled from the heightmap.

Parameters
zHeightmap or cost array.
ij_startStarting grid index (i, j).
ij_endTarget grid index (i, j).
bboxBounding box domain for coordinate remapping.
n_levelsNumber of multiscale pyramid levels (>= 1).
corridor_radiusRadius of search corridor in grid cells.
corridor_decayDecay factor applied to corridor radius per level.
elevation_ratioWeight factor for absolute elevation vs gradient.
distance_exponentExponent applied to elevation differences.
upward_penalizationPenalty factor for moving uphill.
p_mask_nogoOptional pointer to mask of impassable regions.
use_astarUse A* heuristic instead of Dijkstra.
smooth_pathApply smoothing to the resulting path.
Returns
Path containing coordinates and sampled elevation values.

◆ index_to_uv()

float hmap::index_to_uv ( int i,
int n,
GridRegistration reg = GridRegistration::CellCenter )
inline

Maps a discrete index i in [0, n) to a UV coordinate in [0, 1].

◆ uv_to_continuous_index()

float hmap::uv_to_continuous_index ( float u,
int n,
GridRegistration reg = GridRegistration::CellCenter )
inline

Maps a UV coordinate in [0, 1] to a continuous index in [0, n - 1].

◆ tile_uv_rect()

UvRect hmap::tile_uv_rect ( const glm::ivec2 & global_offset,
const glm::ivec2 & tile_shape_with_halo,
const glm::ivec2 & global_shape,
const UvRect & domain_uv = UvRect::unit() )
inline

Computes the exact UV rectangle of a tile (including halo) within a domain of global_shape.

◆ autocorr_length_scale()

float hmap::autocorr_length_scale ( const Array & array,
float max_lag_fraction = 0.4f )

Estimate the isotropic dominant length scale of a 2D heightmap.

Computes the e-folding lag of the autocorrelation function (averaged over i and j directions) via binary search. Returns max(ni, nj) for flat arrays.

Parameters
arrayInput 2D heightmap, accessed via array(i, j).
max_lag_fractionSearch range as a fraction of the shorter dimension.
Returns
Length scale in grid cells.

Example

#include <iostream>
#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {1024, 1024};
int seed = 1;
// isotropic
{
glm::vec2 kw = {32.f, 32.f};
float scale_ref_x = 0.5f * shape.x / kw.x;
float scale_ref_y = 0.5f * shape.y / kw.y;
std::cout << "--- Scales ---\n";
std::cout << " scale: " << scale << "\n";
std::cout << " scale_ref_x: " << scale_ref_x << "\n";
std::cout << " scale_ref_y: " << scale_ref_y << "\n";
}
// per grid direction length-scales
{
glm::vec2 kw = {32.f, 8.f};
float scale_ref_x = 0.5f * shape.x / kw.x;
float scale_ref_y = 0.5f * shape.y / kw.y;
std::cout << "--- Scales ---\n";
std::cout << " scale.x: " << scale.x << "\n";
std::cout << " scale.y: " << scale.y << "\n";
std::cout << " scale_ref_x: " << scale_ref_x << "\n";
std::cout << " scale_ref_y: " << scale_ref_y << "\n";
}
}
float autocorr_length_scale(const Array &array, float max_lag_fraction=0.4f)
Estimate the isotropic dominant length scale of a 2D heightmap.
Definition autocorr_length_scale.cpp:13
glm::vec2 autocorr_length_scale_axial(const Array &array, float max_lag_fraction=0.4f)
Estimate axis-aligned dominant length scales of a 2D heightmap.
Definition autocorr_length_scale.cpp:67

See unit tests: test_autocorr_length_scale.cpp

◆ autocorr_length_scale_axial()

glm::vec2 hmap::autocorr_length_scale_axial ( const Array & array,
float max_lag_fraction = 0.4f )

Estimate axis-aligned dominant length scales of a 2D heightmap.

Independently computes the e-folding autocorrelation lag along the i and j grid axes. Use when the field is anisotropic but aligned with the grid. Returns {ni, nj} for flat arrays.

Parameters
arrayInput 2D heightmap, accessed via array(i, j).
max_lag_fractionSearch range as a fraction of each axis length.
Returns
{scale_i, scale_j} length scales in grid cells.

See unit tests: test_autocorr_length_scale.cpp

◆ detrend_reg()

Array hmap::detrend_reg ( const Array & array)

Apply linear regression for detrending of a 2D array.

This function performs detrending on the input array by applying linear regression separately to each row and column, removing trends from the data.

Parameters
arrayInput 2D array to be detrended.
Returns
Array The detrended output array.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {2.f, 2.f};
int seed = 1;
auto z1 = detrend_reg(z0);
hmap::export_banner_png("ex_detrend.png", {z0, z1}, hmap::Cmap::JET);
}
Array detrend_reg(const Array &array)
Apply linear regression for detrending of a 2D array.
Definition detrend.cpp:10

Result

◆ normalize()

void hmap::normalize ( Array & array,
NormalizationMethod method )

In-place normalization of an array.

Applies a normalization transform to the input array depending on the selected method. The operation modifies the array directly.

Supported methods:

  • NM_MIN_MAX: rescales values to the range [0, 1]
  • NM_STANDARDIZE: applies z-score normalization (zero mean, unit variance)
  • NM_ROBUST: applies robust scaling using median and interquartile range (IQR)
Parameters
arrayInput/output array to normalize in-place.
methodNormalization strategy to apply.
Warning
For NM_ROBUST, division by a near-zero interquartile range may lead to numerical instability if the input is nearly constant.

See unit tests: test_normalized.cpp

◆ normalized()

Array hmap::normalized ( const Array & array,
NormalizationMethod method )

Returns a normalized copy of an array.

This is a convenience wrapper around normalize().

Parameters
arrayInput array to normalize.
methodNormalization strategy to apply.
Returns
A new Array containing the normalized values.

See unit tests: test_normalized.cpp

◆ variance()

float hmap::variance ( const Array & array,
float * p_mean = nullptr )

Compute the population variance of a 2D array.

Parameters
arrayInput 2D array, accessed via array(i, j).
p_meanPointer to a precomputed mean (avoids recomputation); if null, the mean is computed internally.
Returns
Population variance.

See unit tests: test_variance.cpp

◆ loose_symmetry()

Array hmap::loose_symmetry ( const Array & array,
SymmetryType symmetry_type = SymmetryType::SYMMETRY_LEFT_TO_RIGHT,
float strength = 1.f,
int factor = 4,
int patch_size = 16,
int analysis_stride = 2,
int synthesis_stride = 8,
int sparsity = 1,
bool flatten_center = false,
float flatten_radius = 0.05f )

Synthesize a heightmap with natural, approximate symmetry using exemplar-based super-resolution.

This function creates a heightmap with recognizable symmetrical macro features while retaining natural variation and avoiding strict geometric pixel-mirroring. It extracts the macro shape of the input (with optional pre-filtering), applies geometric symmetry to construct a guide field, and transfers the un-mirrored high-resolution features and textures of the input exemplar onto the symmetrical guide using sparse patch coding.

Parameters
arrayInput heightmap providing the exemplar features.
symmetry_typeType of symmetry to apply to the guide field.
strengthSymmetry strength in [0, 1] controlling interpolation between the original macro base and the symmetrical guide. Default is 1.0.
factorSuper-resolution amplification factor (>= 1).
patch_sizeSide of square patches for sparse coding (>= 2).
analysis_stridePatch stride on the exemplar grid.
synthesis_stridePatch stride on the synthesis grid.
sparsityMaximum number of atoms used to code each patch.
flatten_centerIf true, flattens the elevation along the symmetry axis or center point towards minimum elevation.
flatten_radiusRadius (in normalized [0, 1] units) around the symmetry axis/center for the flattening transition.
Returns
Array Synthesized heightmap with loose symmetry.

Example

#include "highmap.hpp"
int main(void)
{
hmap::gpu::init_opencl(); // for hydraulic erosion
glm::ivec2 shape = {512, 512};
int seed = 42;
// input terrain with natural features and rich erosion details
shape,
{4.f, 4.f},
seed);
// loose symmetry parameters
int patch_size = 16;
int analysis_stride = patch_size / 8;
int synthesis_stride = patch_size / 2;
int factor = 4;
float strength = 0.8f;
// compute loose symmetry for all symmetry types
z,
strength,
factor,
patch_size,
analysis_stride,
synthesis_stride);
z,
strength,
factor,
patch_size,
analysis_stride,
synthesis_stride);
z,
strength,
factor,
patch_size,
analysis_stride,
synthesis_stride);
z,
strength,
factor,
patch_size,
analysis_stride,
synthesis_stride);
strength,
factor,
patch_size,
analysis_stride,
synthesis_stride);
strength,
factor,
patch_size,
analysis_stride,
synthesis_stride);
strength,
factor,
patch_size,
analysis_stride,
synthesis_stride);
z,
strength,
factor,
patch_size,
analysis_stride,
synthesis_stride);
// loose symmetry with flatten_center enabled
z,
strength,
factor,
patch_size,
analysis_stride,
synthesis_stride,
/* sparsity */ 1,
/* flatten_center */ true,
/* flatten_radius */ 0.08f);
"ex_loose_symmetry.png",
{z, z_lr, z_rl, z_tb, z_bt, z_x, z_y, z_xy, z_rot180, z_lr_flat},
true);
}
Array loose_symmetry(const Array &array, SymmetryType symmetry_type=SymmetryType::SYMMETRY_LEFT_TO_RIGHT, float strength=1.f, int factor=4, int patch_size=16, int analysis_stride=2, int synthesis_stride=8, int sparsity=1, bool flatten_center=false, float flatten_radius=0.05f)
Synthesize a heightmap with natural, approximate symmetry using exemplar-based super-resolution.
Definition loose_symmetry.cpp:39
@ SYMMETRY_TOP_TO_BOTTOM
Mirror top half onto bottom half.
Definition transform.hpp:30
@ SYMMETRY_LEFT_TO_RIGHT
Mirror left half onto right half.
Definition transform.hpp:28
@ SYMMETRY_RIGHT_TO_LEFT
Mirror right half onto left half.
Definition transform.hpp:29
@ SYMMETRY_Y
Symmetric average across horizontal axis.
Definition transform.hpp:33
@ SYMMETRY_ROT180
180-degree rotational symmetry around center.
Definition transform.hpp:35
@ SYMMETRY_X
Symmetric average across vertical axis.
Definition transform.hpp:32
@ SYMMETRY_BOTTOM_TO_TOP
Mirror bottom half onto top half.
Definition transform.hpp:31
@ SYMMETRY_XY
4-quadrant symmetric average across both X and Y.
Definition transform.hpp:34

Result

◆ non_parametric_sampling()

Array hmap::non_parametric_sampling ( const Array & array,
glm::ivec2 patch_shape,
std::uint32_t seed,
float error_threshold = 0.1f )

Synthesize a new heightmap based on an input array using a non-parametric sampling method.

This method generates a new heightmap by sampling patches from the input array non-parametrically. It is a slow process and is based on the technique described in [Efros1999].

Parameters
arrayInput array from which patches are sampled.
patch_shapeShape of the patches used for sampling.
seedRandom seed number for patch selection.
error_thresholdThreshold for patch selection based on error.
Returns
Array Resulting synthesized heightmap.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {64, 64};
glm::vec2 kw = {2.f, 2.f};
int seed = 1;
auto z = hmap::noise_fbm(hmap::NoiseType::PERLIN, shape, kw, seed);
glm::ivec2 patch_shape = {5, 5};
// base function
hmap::Array zq1 = hmap::non_parametric_sampling(z, patch_shape, ++seed, 0.5f);
hmap::Array zq2 = hmap::non_parametric_sampling(z, patch_shape, ++seed, 0.5f);
hmap::export_banner_png("ex_non_parametric_sampling.png",
{z, zq1, zq2},
true);
// // wrapper / shuffle
// hmap::Array zs0 = hmap::quilting_shuffle(z, patch_shape, overlap, ++seed);
// hmap::Array zs1 = hmap::quilting_shuffle(z, patch_shape, overlap, ++seed);
// hmap::export_banner_png("ex_quilting1.png",
// {z, zs0, zs1},
// hmap::cmap::terrain,
// true);
// // wrapper / expand
// // output array is 2-times larger in this case
// float expansion_ratio = 2.f;
// hmap::Array ze0 = hmap::quilting_expand(z,
// expansion_ratio,
// patch_shape,
// overlap,
// ++seed);
// ze0.to_png("ex_quilting2.png", hmap::cmap::terrain, true);
// // keep input shape for the output ('true' parameter)
// bool keep_input_shape = true;
// hmap::Array ze1 = hmap::quilting_expand(z,
// expansion_ratio,
// patch_shape,
// overlap,
// ++seed,
// keep_input_shape);
// hmap::Array ze2 = hmap::quilting_expand(z,
// 2.f * expansion_ratio,
// patch_shape,
// overlap,
// ++seed,
// keep_input_shape);
// hmap::export_banner_png("ex_quilting3.png",
// {z, ze1, ze2},
// hmap::cmap::terrain,
// true);
}
Array non_parametric_sampling(const Array &array, glm::ivec2 patch_shape, std::uint32_t seed, float error_threshold=0.1f)
Synthesize a new heightmap based on an input array using a non-parametric sampling method.
Definition non_parameteric_sampling.cpp:50

Result

◆ quilting()

Array hmap::quilting ( const std::vector< const Array * > & p_arrays,
glm::ivec2 patch_base_shape,
glm::ivec2 tiling,
float overlap,
std::uint32_t seed,
std::vector< Array * > secondary_arrays = {},
bool patch_flip = true,
bool patch_rotate = true,
bool patch_transpose = true,
float filter_width_ratio = 0.25f )

Synthesize a new heightmap by stitching together small patches from input heightmaps.

This function creates a new heightmap by stitching patches from a set of input heightmaps. The stitching process allows for flipping, rotating, and transposing patches, and includes options for smoothing based on the overlap between patches. This technique is based on [Efros2001].

Parameters
p_arraysVector of pointers to input heightmaps.
patch_base_shapeShape of the patches to be used.
tilingNumber of patches in each direction (x, y).
overlapOverlap between patches, in the range ]0, 1[.
seedRandom seed number for patch placement.
secondary_arraysOptional channels transformed using the guide's patches and seams. Each must match every guide's shape; otherwise an empty array is returned without modifying the channels. Pointers may repeat or alias a guide.
patch_flipAllow flipping of patches (up-down, left-right).
patch_rotateAllow 90-degree rotation of patches (for square patches).
patch_transposeAllow transposition of patches (for square patches).
filter_width_ratioRatio of filter width to overlap length for smoothing.
Returns
Array Resulting synthesized heightmap.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {512, 512};
glm::vec2 kw = {4.f, 4.f};
int seed = 1;
auto z = hmap::noise_fbm(hmap::NoiseType::PERLIN, shape, kw, seed);
auto zw = hmap::noise_fbm(hmap::NoiseType::WORLEY, shape, kw, ++seed);
float ratio = 0.5f;
glm::ivec2 patch_shape = {(int)(ratio * shape.x), (int)(ratio * shape.y)};
glm::ivec2 tiling = {4, 4};
float overlap = 0.9f;
// --- base function, a list of array can be provided as a source of
// --- patches. Secondary arrays can be provided, quilting will
// --- apply to them based on the input arrays.
std::vector<hmap::Array *> input_p_arrays = {&z};
auto zm = 1.f - z;
auto dz = hmap::gradient_norm(z);
std::vector<hmap::Array *> sec_arrays = {&zm, &dz}; // will be
// overriden
patch_shape,
tiling,
overlap,
++seed,
sec_arrays);
hmap::export_banner_png("ex_quilting0.png",
{zq, zm, dz},
true);
// --- wrapper / shuffle
hmap::Array zs0 = hmap::quilting_shuffle(z, patch_shape, overlap, ++seed);
// with secondary arrays
sec_arrays = {&dz};
patch_shape,
overlap,
++seed,
sec_arrays);
hmap::export_banner_png("ex_quilting1.png",
{z, zs0, zs1, dz},
true);
// --- wrapper / expand
// output array is 2-times larger in this case
float expansion_ratio = 2.f;
// with secondary arrays
sec_arrays = {&dz};
expansion_ratio,
patch_shape,
overlap,
++seed,
sec_arrays,
true);
hmap::export_banner_png("ex_quilting2.png",
{ze0, dz},
true);
// keep input shape for the output ('true' parameter)
bool keep_input_shape = true;
expansion_ratio,
patch_shape,
overlap,
++seed,
{}, // no secondary arrays
keep_input_shape);
2.f * expansion_ratio,
patch_shape,
overlap,
++seed,
{},
keep_input_shape);
hmap::export_banner_png("ex_quilting3.png",
{z, ze1, ze2},
true);
// wrapper / blend
patch_shape,
overlap,
++seed);
hmap::export_banner_png("ex_quilting4.png",
{z, zw, zb},
true);
}
Array quilting_blend(const std::vector< const Array * > &p_arrays, glm::ivec2 patch_base_shape, float overlap, std::uint32_t seed, bool patch_flip=true, bool patch_rotate=true, bool patch_transpose=true, float filter_width_ratio=0.25f)
Synthesize a new heightmap by stitching together small patches from a list of input heightmaps.
Definition quilting.cpp:233
Array quilting_expand(const Array &array, float expansion_ratio, glm::ivec2 patch_base_shape, float overlap, std::uint32_t seed, std::vector< Array * > secondary_arrays={}, bool keep_input_shape=false, bool patch_flip=true, bool patch_rotate=true, bool patch_transpose=true, float filter_width_ratio=0.25f)
Synthesize a new heightmap by expanding the input heightmap and stitching patches.
Definition quilting.cpp:268
Array quilting(const std::vector< const Array * > &p_arrays, glm::ivec2 patch_base_shape, glm::ivec2 tiling, float overlap, std::uint32_t seed, std::vector< Array * > secondary_arrays={}, bool patch_flip=true, bool patch_rotate=true, bool patch_transpose=true, float filter_width_ratio=0.25f)
Synthesize a new heightmap by stitching together small patches from input heightmaps.
Definition quilting.cpp:23
Array quilting_shuffle(const Array &array, glm::ivec2 patch_base_shape, float overlap, std::uint32_t seed, std::vector< Array * > secondary_arrays={}, bool patch_flip=true, bool patch_rotate=true, bool patch_transpose=true, float filter_width_ratio=0.25f)
Synthesize a new heightmap by reshuffling patches of the input heightmap.
Definition quilting.cpp:375

Result

◆ quilting_blend()

Array hmap::quilting_blend ( const std::vector< const Array * > & p_arrays,
glm::ivec2 patch_base_shape,
float overlap,
std::uint32_t seed,
bool patch_flip = true,
bool patch_rotate = true,
bool patch_transpose = true,
float filter_width_ratio = 0.25f )

Synthesize a new heightmap by stitching together small patches from a list of input heightmaps.

This function creates a new heightmap by stitching patches from a set of input heightmaps, similar to quilting, but the patches are blended together. The blending options include flipping, rotating, and transposing patches, with smoothing based on the overlap between patches.

Parameters
p_arraysVector of pointers to input heightmaps.
patch_base_shapeShape of the patches to be used.
overlapOverlap between patches, in the range ]0, 1[.
seedRandom seed number for patch placement.
patch_flipAllow flipping of patches (up-down, left-right).
patch_rotateAllow 90-degree rotation of patches (for square patches).
patch_transposeAllow transposition of patches (for square patches).
filter_width_ratioRatio of filter width to overlap length for smoothing.
Returns
Array Resulting synthesized heightmap.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {512, 512};
glm::vec2 kw = {4.f, 4.f};
int seed = 1;
auto z = hmap::noise_fbm(hmap::NoiseType::PERLIN, shape, kw, seed);
auto zw = hmap::noise_fbm(hmap::NoiseType::WORLEY, shape, kw, ++seed);
float ratio = 0.5f;
glm::ivec2 patch_shape = {(int)(ratio * shape.x), (int)(ratio * shape.y)};
glm::ivec2 tiling = {4, 4};
float overlap = 0.9f;
// --- base function, a list of array can be provided as a source of
// --- patches. Secondary arrays can be provided, quilting will
// --- apply to them based on the input arrays.
std::vector<hmap::Array *> input_p_arrays = {&z};
auto zm = 1.f - z;
auto dz = hmap::gradient_norm(z);
std::vector<hmap::Array *> sec_arrays = {&zm, &dz}; // will be
// overriden
patch_shape,
tiling,
overlap,
++seed,
sec_arrays);
hmap::export_banner_png("ex_quilting0.png",
{zq, zm, dz},
true);
// --- wrapper / shuffle
hmap::Array zs0 = hmap::quilting_shuffle(z, patch_shape, overlap, ++seed);
// with secondary arrays
sec_arrays = {&dz};
patch_shape,
overlap,
++seed,
sec_arrays);
hmap::export_banner_png("ex_quilting1.png",
{z, zs0, zs1, dz},
true);
// --- wrapper / expand
// output array is 2-times larger in this case
float expansion_ratio = 2.f;
// with secondary arrays
sec_arrays = {&dz};
expansion_ratio,
patch_shape,
overlap,
++seed,
sec_arrays,
true);
hmap::export_banner_png("ex_quilting2.png",
{ze0, dz},
true);
// keep input shape for the output ('true' parameter)
bool keep_input_shape = true;
expansion_ratio,
patch_shape,
overlap,
++seed,
{}, // no secondary arrays
keep_input_shape);
2.f * expansion_ratio,
patch_shape,
overlap,
++seed,
{},
keep_input_shape);
hmap::export_banner_png("ex_quilting3.png",
{z, ze1, ze2},
true);
// wrapper / blend
patch_shape,
overlap,
++seed);
hmap::export_banner_png("ex_quilting4.png",
{z, zw, zb},
true);
}

Result

◆ quilting_expand()

Array hmap::quilting_expand ( const Array & array,
float expansion_ratio,
glm::ivec2 patch_base_shape,
float overlap,
std::uint32_t seed,
std::vector< Array * > secondary_arrays = {},
bool keep_input_shape = false,
bool patch_flip = true,
bool patch_rotate = true,
bool patch_transpose = true,
float filter_width_ratio = 0.25f )

Synthesize a new heightmap by expanding the input heightmap and stitching patches.

This function generates a larger heightmap by expanding the input heightmap and stitching patches based on the given parameters. The expansion ratio determines the new size of the heightmap, and the function includes options for flipping, rotating, and transposing patches. The output can be either the same shape as the input or expanded based on the given ratio.

Parameters
arrayInput heightmap to be expanded.
expansion_ratioRatio by which to expand the heightmap (e.g., 2 for doubling the size).
patch_base_shapeShape of the patches to be used.
overlapOverlap between patches, in the range ]0, 1[.
seedRandom seed number for patch placement.
keep_input_shapeIf true, the output heightmap retains the input shape.
patch_flipAllow flipping of patches (up-down, left-right).
patch_rotateAllow 90-degree rotation of patches (for square patches).
patch_transposeAllow transposition of patches (for square patches).
filter_width_ratioRatio of filter width to overlap length for smoothing.
Returns
Array Resulting synthesized heightmap.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {512, 512};
glm::vec2 kw = {4.f, 4.f};
int seed = 1;
auto z = hmap::noise_fbm(hmap::NoiseType::PERLIN, shape, kw, seed);
auto zw = hmap::noise_fbm(hmap::NoiseType::WORLEY, shape, kw, ++seed);
float ratio = 0.5f;
glm::ivec2 patch_shape = {(int)(ratio * shape.x), (int)(ratio * shape.y)};
glm::ivec2 tiling = {4, 4};
float overlap = 0.9f;
// --- base function, a list of array can be provided as a source of
// --- patches. Secondary arrays can be provided, quilting will
// --- apply to them based on the input arrays.
std::vector<hmap::Array *> input_p_arrays = {&z};
auto zm = 1.f - z;
auto dz = hmap::gradient_norm(z);
std::vector<hmap::Array *> sec_arrays = {&zm, &dz}; // will be
// overriden
patch_shape,
tiling,
overlap,
++seed,
sec_arrays);
hmap::export_banner_png("ex_quilting0.png",
{zq, zm, dz},
true);
// --- wrapper / shuffle
hmap::Array zs0 = hmap::quilting_shuffle(z, patch_shape, overlap, ++seed);
// with secondary arrays
sec_arrays = {&dz};
patch_shape,
overlap,
++seed,
sec_arrays);
hmap::export_banner_png("ex_quilting1.png",
{z, zs0, zs1, dz},
true);
// --- wrapper / expand
// output array is 2-times larger in this case
float expansion_ratio = 2.f;
// with secondary arrays
sec_arrays = {&dz};
expansion_ratio,
patch_shape,
overlap,
++seed,
sec_arrays,
true);
hmap::export_banner_png("ex_quilting2.png",
{ze0, dz},
true);
// keep input shape for the output ('true' parameter)
bool keep_input_shape = true;
expansion_ratio,
patch_shape,
overlap,
++seed,
{}, // no secondary arrays
keep_input_shape);
2.f * expansion_ratio,
patch_shape,
overlap,
++seed,
{},
keep_input_shape);
hmap::export_banner_png("ex_quilting3.png",
{z, ze1, ze2},
true);
// wrapper / blend
patch_shape,
overlap,
++seed);
hmap::export_banner_png("ex_quilting4.png",
{z, zw, zb},
true);
}

Result

◆ quilting_shuffle()

Array hmap::quilting_shuffle ( const Array & array,
glm::ivec2 patch_base_shape,
float overlap,
std::uint32_t seed,
std::vector< Array * > secondary_arrays = {},
bool patch_flip = true,
bool patch_rotate = true,
bool patch_transpose = true,
float filter_width_ratio = 0.25f )

Synthesize a new heightmap by reshuffling patches of the input heightmap.

This function generates a new heightmap by reshuffling patches of the input heightmap, effectively creating a new pattern while keeping the same shape as the input heightmap. The function includes options for patch flipping, rotating, and transposing.

Parameters
arrayInput heightmap to be reshuffled.
patch_base_shapeShape of the patches to be used.
overlapOverlap between patches, in the range ]0, 1[.
seedRandom seed number for patch placement.
patch_flipAllow flipping of patches (up-down, left-right).
patch_rotateAllow 90-degree rotation of patches (for square patches).
patch_transposeAllow transposition of patches (for square patches).
filter_width_ratioRatio of filter width to overlap length for smoothing.
Returns
Array Resulting synthesized heightmap with reshuffled patches.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {512, 512};
glm::vec2 kw = {4.f, 4.f};
int seed = 1;
auto z = hmap::noise_fbm(hmap::NoiseType::PERLIN, shape, kw, seed);
auto zw = hmap::noise_fbm(hmap::NoiseType::WORLEY, shape, kw, ++seed);
float ratio = 0.5f;
glm::ivec2 patch_shape = {(int)(ratio * shape.x), (int)(ratio * shape.y)};
glm::ivec2 tiling = {4, 4};
float overlap = 0.9f;
// --- base function, a list of array can be provided as a source of
// --- patches. Secondary arrays can be provided, quilting will
// --- apply to them based on the input arrays.
std::vector<hmap::Array *> input_p_arrays = {&z};
auto zm = 1.f - z;
auto dz = hmap::gradient_norm(z);
std::vector<hmap::Array *> sec_arrays = {&zm, &dz}; // will be
// overriden
patch_shape,
tiling,
overlap,
++seed,
sec_arrays);
hmap::export_banner_png("ex_quilting0.png",
{zq, zm, dz},
true);
// --- wrapper / shuffle
hmap::Array zs0 = hmap::quilting_shuffle(z, patch_shape, overlap, ++seed);
// with secondary arrays
sec_arrays = {&dz};
patch_shape,
overlap,
++seed,
sec_arrays);
hmap::export_banner_png("ex_quilting1.png",
{z, zs0, zs1, dz},
true);
// --- wrapper / expand
// output array is 2-times larger in this case
float expansion_ratio = 2.f;
// with secondary arrays
sec_arrays = {&dz};
expansion_ratio,
patch_shape,
overlap,
++seed,
sec_arrays,
true);
hmap::export_banner_png("ex_quilting2.png",
{ze0, dz},
true);
// keep input shape for the output ('true' parameter)
bool keep_input_shape = true;
expansion_ratio,
patch_shape,
overlap,
++seed,
{}, // no secondary arrays
keep_input_shape);
2.f * expansion_ratio,
patch_shape,
overlap,
++seed,
{},
keep_input_shape);
hmap::export_banner_png("ex_quilting3.png",
{z, ze1, ze2},
true);
// wrapper / blend
patch_shape,
overlap,
++seed);
hmap::export_banner_png("ex_quilting4.png",
{z, zw, zb},
true);
}

Result

◆ terrain_super_resolution()

Array hmap::terrain_super_resolution ( const Array & array,
const Array & exemplar,
int factor,
int patch_size = 16,
int analysis_stride = 8,
int synthesis_stride = 8,
int sparsity = 1 )

Synthesize a high-resolution heightmap from a low-resolution input using an exemplar-based sparse patch representation (terrain amplification).

The exemplar is downsampled by factor and every patch_size x patch_size patch of the downsampled exemplar (mean removed, radial mask applied, unit norm) becomes an atom of a dictionary, paired with the corresponding patch_size * factor high-resolution patch. Each patch of the input is then sparse-coded against the low-resolution atoms with orthogonal matching pursuit, and the same coefficients are applied to the paired high-resolution atoms to synthesize the output, which is blended from the overlapping patches using the mask as weight. This technique is based on [Guerin2016].

With sparsity = 1 (the setting of the reference implementation), each input patch is replaced by the detail of its best-correlated exemplar patch. The strides control the density of the patch grids: smaller strides give more atoms and more overlap at a higher cost. The patch mask vanishes at the patch corners, so synthesis_stride should not exceed about 0.7 * patch_size to keep the output fully covered; uncovered pixels, if any, are filled with a bicubic upsampling of the input.

Memory usage scales with the number of atoms times (patch_size * factor)^2: large exemplars with small analysis_stride can require a lot of memory.

Parameters
arrayLow-resolution input heightmap.
exemplarHigh-resolution exemplar heightmap providing the detail.
factorAmplification factor (>= 1); the output shape is array.shape * factor.
patch_sizeSide of the square patches on the low-resolution grid (>= 2).
analysis_strideStride of the patch grid over the downsampled exemplar, in [1, patch_size].
synthesis_strideStride of the patch grid over the input, in [1, patch_size].
sparsityMaximum number of atoms used to code each patch (>= 1).
Returns
Array Synthesized heightmap of shape array.shape * factor, or an empty array if the inputs are invalid (e.g. the downsampled exemplar is smaller than a patch, or the exemplar is flat).

Example

#include "highmap.hpp"
int main(void)
{
hmap::gpu::init_opencl(); // for hydraulic erosion
glm::ivec2 shape_hr = {512, 512};
int factor = 4;
int seed = 1;
// high-resolution exemplar providing the fine details
shape_hr,
{2.f, 2.f},
seed + 1);
hmap::gpu::hydraulic_particle(exemplar, 500000, seed);
hmap::remap(exemplar);
// smooth, low-resolution input terrain to amplify
glm::ivec2 shape_lr = {shape_hr.x / factor, shape_hr.y / factor};
shape_lr,
{4.f, 4.f},
++seed,
2);
int patch_size = 16;
int analysis_stride = patch_size / 8;
int synthesis_stride = patch_size / 2;
exemplar,
factor,
patch_size,
analysis_stride,
synthesis_stride);
zsr.dump();
// plain upsampling of the input, for comparison
hmap::export_banner_png("ex_terrain_super_resolution.png",
{exemplar, zup, zsr},
true);
}
Array resample_to_shape_bicubic(glm::ivec2 new_shape) const
Return a resampled array of shape new_shape using bicubic interpolation.
Definition methods.cpp:468
Array terrain_super_resolution(const Array &array, const Array &exemplar, int factor, int patch_size=16, int analysis_stride=8, int synthesis_stride=8, int sparsity=1)
Synthesize a high-resolution heightmap from a low-resolution input using an exemplar-based sparse pat...
Definition terrain_super_resolution.cpp:328

Result

◆ cubic_pulse() [3/3]

std::vector< float > hmap::cubic_pulse ( const TerrainTriMesh & mesh)

Compute a cubic pulse value for each mesh vertex.

◆ generate_terrain_tri_mesh_from_heightmap()

TerrainTriMesh hmap::generate_terrain_tri_mesh_from_heightmap ( const Array & z,
float max_error,
int max_triangles = 0,
int max_points = 0 )

Generate a terrain mesh from a heightmap.

◆ generate_terrain_tri_mesh_from_heightmap_random()

TerrainTriMesh hmap::generate_terrain_tri_mesh_from_heightmap_random ( const Array & z,
int control_points_count,
std::uint32_t seed,
const UvTile & region = UvTile::unit(),
ICommunicator * p_comm = nullptr )

Generate a random terrain mesh from a heightmap tile.

◆ compute_terrain_alignment() [1/2]

TerrainAlignment hmap::compute_terrain_alignment ( const Array & lower,
const CoordFrame & frame_lower,
const Array & upper,
const CoordFrame & frame_upper,
TerrainAlignMode mode,
float huber_delta = 0.1f,
int max_iterations = 10 )

Compute alignment parameters to fit upper to lower over their common valid area.

◆ compute_terrain_alignment() [2/2]

TerrainAlignment hmap::compute_terrain_alignment ( const VirtualArray & lower,
const CoordFrame & frame_lower,
const VirtualArray & upper,
const CoordFrame & frame_upper,
TerrainAlignMode mode,
float huber_delta = 0.1f,
int max_iterations = 10,
int coarse_size = 128 )

Compute alignment parameters for VirtualArray inputs using a coarse Array representation.

◆ apply_terrain_alignment() [1/2]

void hmap::apply_terrain_alignment ( Array & upper,
const TerrainAlignment & alignment )

Apply precomputed alignment parameters to an Array in-place.

◆ apply_terrain_alignment() [2/2]

void hmap::apply_terrain_alignment ( VirtualArray & upper,
const TerrainAlignment & alignment,
const ComputeMode & cm = ComputeMode{} )

Apply precomputed alignment parameters to a VirtualArray in-place.

◆ align_terrains() [1/2]

void hmap::align_terrains ( const Array & lower,
const CoordFrame & frame_lower,
Array & upper,
const CoordFrame & frame_upper,
TerrainAlignMode mode,
float huber_delta = 0.1f,
int max_iterations = 10 )

Align upper to lower in-place over their common valid area.

◆ align_terrains() [2/2]

void hmap::align_terrains ( const VirtualArray & lower,
const CoordFrame & frame_lower,
VirtualArray & upper,
const CoordFrame & frame_upper,
TerrainAlignMode mode,
float huber_delta = 0.1f,
int max_iterations = 10,
int coarse_size = 128,
const ComputeMode & cm = ComputeMode{} )

Align upper VirtualArray to lower VirtualArray in-place.

◆ flip_lr() [1/2]

void hmap::flip_lr ( Texture & texture)

Flip the texture horizontally (left/right).

Parameters
textureInput texture to be flipped.

◆ flip_ud() [1/2]

void hmap::flip_ud ( Texture & texture)

Flip the texture vertically (up/down).

Parameters
textureInput texture to be flipped.

◆ rot180() [1/2]

void hmap::rot180 ( Texture & texture)

Rotate the texture by 180 degrees.

Parameters
textureInput texture to be rotated.

◆ rot270() [1/2]

void hmap::rot270 ( Texture & texture)

Rotate the texture by 270 degrees counterclockwise.

Parameters
textureInput texture to be rotated.

◆ rot90() [1/2]

void hmap::rot90 ( Texture & texture)

Rotate the texture by 90 degrees counterclockwise.

Parameters
textureInput texture to be rotated.

◆ scale_uv() [1/2]

void hmap::scale_uv ( Texture & texture,
glm::vec2 uv_scale )

Scale the texture in UV space with wrapping boundary.

Parameters
textureInput texture to be scaled.
uv_scaleScaling factors for U and V dimensions.

◆ transpose() [1/2]

Texture hmap::transpose ( const Texture & texture)

Return the transposed texture.

Parameters
textureInput texture to be transposed.
Returns
Texture The transposed texture.

◆ flip_lr() [2/2]

void hmap::flip_lr ( Array & array)

Flip the array horizontally (left/right).

This function flips the input array along the vertical axis, resulting in a left-to-right mirror image of the original array.

Parameters
arrayInput array to be flipped horizontally.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
auto z1 = z;
auto z2 = z;
hmap::export_banner_png("ex_flip_ud.png", {z, z1, z2}, hmap::Cmap::VIRIDIS);
}
void flip_ud(Texture &texture)
Flip the texture vertically (up/down).
Definition texture_transform.cpp:25
void flip_lr(Texture &texture)
Flip the texture horizontally (left/right).
Definition texture_transform.cpp:15

Result

◆ flip_ud() [2/2]

void hmap::flip_ud ( Array & array)

Flip the array vertically (up/down).

This function flips the input array along the horizontal axis, resulting in an up-to-down mirror image of the original array.

Parameters
arrayInput array to be flipped vertically.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
auto z1 = z;
auto z2 = z;
hmap::export_banner_png("ex_flip_ud.png", {z, z1, z2}, hmap::Cmap::VIRIDIS);
}

Result

◆ radial_displacement_to_xy()

void hmap::radial_displacement_to_xy ( const Array & dr,
Array & dx,
Array & dy,
float smoothing = 1.f,
glm::vec2 center = {0.5f, 0.5f},
const UvRect & uv_rect = UvRect::unit() )

Interpret the input array dr as a radial displacement and convert it to a pair of displacements dx and dy in cartesian coordinates.

Parameters
drRadial displacement.
dxDisplacent in x direction (output).
dyDisplacent in y direction (output).
smoothingSmoothing parameter to avoid discontinuity at the origin.
centerOrigin center.
bboxDomain bounding box.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
hmap::Array dx, dy;
hmap::export_banner_png("ex_radial_displacement_to_xy.png",
{dr, dx, dy},
}
void radial_displacement_to_xy(const Array &dr, Array &dx, Array &dy, float smoothing=1.f, glm::vec2 center={0.5f, 0.5f}, const UvRect &uv_rect=UvRect::unit())
Interpret the input array dr as a radial displacement and convert it to a pair of displacements dx an...
Definition transform.cpp:41

Result

◆ rot180() [2/2]

void hmap::rot180 ( Array & array)

Rotate the array by 180 degrees.

This function rotates the input array by 180 degrees in the counterclockwise direction. The dimensions of the array will be adjusted accordingly.

Parameters
arrayInput array to be rotated by 180 degrees.

◆ rot270() [2/2]

void hmap::rot270 ( Array & array)

Rotate the array by 270 degrees.

This function rotates the input array by 270 degrees in the counterclockwise direction. The dimensions of the array will be adjusted accordingly.

Parameters
arrayInput array to be rotated by 270 degrees.

◆ rot90() [2/2]

void hmap::rot90 ( Array & array)

Rotate the array by 90 degrees.

This function rotates the input array by 90 degrees in the counterclockwise direction. The dimensions of the array will be adjusted accordingly.

Parameters
arrayInput array to be rotated by 90 degrees.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
auto z1 = z;
hmap::export_banner_png("ex_rot90.png", {z, z1}, hmap::Cmap::INFERNO);
}
void rot90(Texture &texture)
Rotate the texture by 90 degrees counterclockwise.
Definition texture_transform.cpp:35

Result

◆ rotate()

void hmap::rotate ( Array & array,
float angle,
bool zoom_in = true,
bool zero_padding = false )

Rotate the array by a specified angle.

This function rotates the input array by a given angle in degrees. The rotation can be performed with optional zero-padding, which fills in the borders with zeros instead of using symmetric padding. This is particularly useful when the array contains zero values at its borders.

Parameters
arrayInput array to be rotated.
angleRotation angle in degrees.
zoom_inIf true, zoom in after rotation (default is true).
zero_paddingIf true, use zero-padding to fill the borders; otherwise, use symmetry (default is false).

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
auto z1 = z;
hmap::rotate(z1, 30.f);
// gpu version
auto z2 = z;
hmap::gpu::rotate(z2, 30.f);
auto z3 = z;
hmap::gpu::rotate(z3, 30.f, false); // no zoom
hmap::export_banner_png("ex_rotate.png", {z, z1, z2, z3}, hmap::Cmap::JET);
}
void rotate(Array &array, float angle, bool zoom_in=true)
See hmap::rotate.
Definition transform_gpu.cpp:16
void rotate(Array &array, float angle, bool zoom_in=true, bool zero_padding=false)
Rotate the array by a specified angle.
Definition transform.cpp:94

Result

◆ rotate_displacement()

void hmap::rotate_displacement ( const Array & delta,
float angle,
Array & dx,
Array & dy )

Rotates a scalar displacement field into directional X and Y components.

This function converts a scalar displacement map into two directional components (dx and dy) according to a given rotation angle. It is typically used to orient procedural displacements, such as those applied to terrain heightmaps or noise-based distortion fields.

Parameters
deltaInput scalar displacement field.
angleRotation angle in degrees (counterclockwise).
dxOutput array receiving the X-axis displacement component.
dyOutput array receiving the Y-axis displacement component.

◆ scale_uv() [2/2]

void hmap::scale_uv ( Array & array,
glm::vec2 uv_scale )

Scale the array in UV space with wrapping boundary.

Parameters
arrayInput array to be scaled.
uv_scaleScaling factors for U and V dimensions.

◆ symmetrize()

Array hmap::symmetrize ( const Array & array,
SymmetryType symmetry_type = SymmetryType::SYMMETRY_LEFT_TO_RIGHT,
bool flatten_center = false,
float flatten_radius = 0.05f )

Enforces geometric symmetry on an array.

This function reflects or averages portions of the input array across the specified symmetry axis or plane according to symmetry_type.

Parameters
arrayInput array to symmetrize.
symmetry_typeType of symmetry operation to apply.
flatten_centerIf true, flattens the elevation along the symmetry axis or center point towards minimum elevation.
flatten_radiusRadius (in normalized [0, 1] units) around the symmetry axis/center for the flattening transition.
Returns
Symmetrized array.

◆ translate()

Array hmap::translate ( const Array & array,
float dx,
float dy,
bool periodic = false,
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
const UvRect & uv_rect = UvRect::unit() )

Translates a 2D array by a specified amount along the x and y axes.

This function shifts the contents of the input array by dx and dy units along the x and y axes, respectively. It supports both periodic boundary conditions, where the array wraps around, and non-periodic conditions, where the shifted areas are filled with zeros.

Parameters
arrayThe input 2D array to be translated. This array remains unmodified.
dxThe translation distance along the x-axis. Positive values shift the array to the right.
dyThe translation distance along the y-axis. Positive values shift the array downward.
periodicIf set to true, the translation is periodic, meaning that elements that move out of one side of the array reappear on the opposite side. If false, the areas exposed by the translation are filled with zeros. The default is false.
p_noise_xOptional pointer to a 2D array that contains x-direction noise to be added to the translation. If provided, the noise values are added to dx on a per-element basis.
p_noise_yOptional pointer to a 2D array that contains y-direction noise to be added to the translation. If provided, the noise values are added to dy on a per-element basis.
bboxDomain bounding box.
Returns
A new 2D array that is the result of translating the input array by the specified dx and dy values.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
auto zt = hmap::translate(z, 0.25f, -0.1f, false);
hmap::export_banner_png("ex_translate.png", {z, zt}, hmap::Cmap::JET);
}
Array translate(const Array &array, float dx, float dy, bool periodic=false, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit())
Translates a 2D array by a specified amount along the x and y axes.
Definition transform.cpp:299

Result

◆ transpose() [2/2]

Array hmap::transpose ( const Array & array)

Return the transposed array.

This function returns a new array that is the transpose of the input array. The transpose operation swaps the rows and columns of the array, effectively flipping the array over its diagonal.

Parameters
arrayInput array to be transposed.
Returns
Array The transposed array.

◆ zoom()

Array hmap::zoom ( const Array & array,
float zoom_factor,
bool periodic = false,
glm::vec2 center = {0.5f, 0.5f},
const Array * p_noise_x = nullptr,
const Array * p_noise_y = nullptr,
const UvRect & uv_rect = UvRect::unit() )

Applies a zoom effect to a 2D array with an adjustable center.

This function scales the input 2D array by a specified zoom factor, effectively resizing the array's contents. The zoom operation is centered around a specified point within the array, allowing for flexible zooming behavior. The function supports both periodic boundary conditions, where the array wraps around, and non-periodic conditions, where areas outside the original array bounds are filled with zeros.

Parameters
arrayThe input 2D array to be zoomed. This array remains unmodified.
zoom_factorThe factor by which to zoom the array. A value greater than 1 enlarges the contents, while a value between 0 and 1 reduces them.
periodicIf set to true, the zoom is periodic, meaning that elements moving out of the array bounds due to the zoom reappear on the opposite side. If false, areas outside the original array bounds are filled with zeros. The default is false.
centerThe center of the zoom operation, specified as a glm::vec2 with coordinates in the range [0, 1], where {0.5f, 0.5f} represents the center of the array. The default center is {0.5f, 0.5f}.
p_noise_xOptional pointer to a 2D array that contains x-direction noise to be added during the zoom operation. If provided, the noise values are applied to the x-coordinates of the zoomed array on a per-element basis.
p_noise_yOptional pointer to a 2D array that contains y-direction noise to be added during the zoom operation. If provided, the noise values are applied to the y-coordinates of the zoomed array on a per-element basis.
bboxDomain bounding box.
Returns
A new 2D array that is the result of applying the zoom effect to the input array by the specified zoom_factor and centered at the specified center.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
float zoom = 2.f;
glm::vec2 center = {0.25f, 0.f};
auto z1 = hmap::zoom(z, zoom);
auto z2 = hmap::zoom(z, zoom, false, center); // false for not periodic
// to avoid: zoom < 1.f, w/ periodic boundaries
auto z3 = hmap::zoom(z, 0.5f, true);
hmap::export_banner_png("ex_zoom.png", {z, z1, z2, z3}, hmap::Cmap::MAGMA);
}
Array zoom(const Array &array, float zoom_factor, bool periodic=false, glm::vec2 center={0.5f, 0.5f}, const Array *p_noise_x=nullptr, const Array *p_noise_y=nullptr, const UvRect &uv_rect=UvRect::unit())
Applies a zoom effect to a 2D array with an adjustable center.
Definition transform.cpp:350

Result

◆ warp()

void hmap::warp ( Array & array,
const Array * p_dx,
const Array * p_dy )

Apply a warping effect to the array.

This function applies a warping effect to the input array by translating its elements according to the specified x and y translation arrays. The warp effect distorts the array based on the displacement values provided by p_dx and p_dy.

Parameters
arrayInput array to be warped.
p_dxPointer to the array containing x-axis translation values.
p_dyPointer to the array containing y-axis translation values.

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {2.f, 2.f};
int seed = 1;
hmap::Array z0 = z;
shape,
{4.f, 4.f},
seed + 1);
shape,
{4.f, 4.f},
seed + 2);
// warping scale assuming a unit square domain
float scale = 0.25f;
remap(dx, -scale, scale);
remap(dy, -scale, scale);
hmap::warp(z, &dx, &dy);
hmap::export_banner_png("ex_warp.png", {z0, z}, hmap::Cmap::VIRIDIS);
}
void warp(Array &array, const Array *p_dx, const Array *p_dy)
Apply a warping effect to the array.
Definition warp.cpp:17

Result

◆ warp_directional() [1/2]

void hmap::warp_directional ( Array & array,
float angle,
float amount = 0.02f,
int ir = 4,
bool reverse = false )

Apply a warping effect following the downward local gradient direction (deflate/inflate effect).

This function applies a warping effect to the input array based on the downward local gradient direction, creating a deflate or inflate effect. The warp amount, pre-filtering radius, and displacement direction can be customized.

Parameters
arrayInput array to be warped.
angleThe angle to determine the gradient direction.
amountAmount of displacement (default is 0.02f).
irPre-filtering radius to smooth the input data (default is 4).
reverseReverse the displacement direction if set to true (default is false).

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
shape = {512, 512};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
hmap::Array mask = z1;
hmap::remap(mask);
hmap::Array z2 = z1;
hmap::warp_directional(z2, 30.f, 0.02f, 0, true);
hmap::export_banner_png("ex_warp_directional.png",
{z1, z2},
}
void warp_directional(Array &array, float angle, float amount=0.02f, int ir=4, bool reverse=false)
Apply a warping effect following the downward local gradient direction (deflate/inflate effect).
Definition warp.cpp:34

Result

◆ warp_directional() [2/2]

void hmap::warp_directional ( Array & array,
float angle,
const Array * p_mask,
float amount = 0.02f,
int ir = 4,
bool reverse = false )

Apply a warping effect following the downward local gradient direction (deflate/inflate effect) with a mask.

This overloaded function applies a warping effect to the input array using a specified mask. The mask controls the regions where the warp effect is applied, with values expected in the range [0, 1]. The warp is based on the downward local gradient direction.

Parameters
arrayInput array to be warped.
angleThe angle to determine the gradient direction.
p_maskPointer to the mask array that filters the effect, expected in [0, 1].
amountAmount of displacement (default is 0.02f).
irPre-filtering radius to smooth the input data (default is 4).
reverseReverse the displacement direction if set to true (default is false).

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
shape = {512, 512};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
hmap::Array mask = z1;
hmap::remap(mask);
hmap::Array z2 = z1;
hmap::warp_directional(z2, 30.f, 0.02f, 0, true);
hmap::export_banner_png("ex_warp_directional.png",
{z1, z2},
}

Result

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ warp_downslope() [1/2]

void hmap::warp_downslope ( Array & array,
float amount = 0.02f,
int ir = 4,
bool reverse = false )

Apply a warping effect following the downward local gradient direction (deflate/inflate effect).

This function applies a warping effect to the input array based on the downward local gradient direction, simulating a deflate or inflate effect. The effect can be customized by adjusting the displacement amount, pre-filtering radius, and whether the displacement direction is reversed.

Parameters
arrayInput array to be warped.
amountAmount of displacement (default is 0.02f).
irPre-filtering radius to smooth the input data (default is 4).
reverseReverse the displacement direction if set to true (default is false).

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
hmap::Array mask = z1;
hmap::remap(mask);
hmap::Array z2 = z1;
hmap::warp_downslope(z2, &mask, 0.02f, 4, false);
hmap::export_banner_png("ex_warp_downslope.png",
{z1, z2},
}
void warp_downslope(Array &array, float amount=0.02f, int ir=4, bool reverse=false)
Apply a warping effect following the downward local gradient direction (deflate/inflate effect).
Definition warp.cpp:84

Result

◆ warp_downslope() [2/2]

void hmap::warp_downslope ( Array & array,
const Array * p_mask,
float amount = 0.02f,
int ir = 4,
bool reverse = false )

Apply a warping effect following the downward local gradient direction (deflate/inflate effect) with a mask.

This overloaded function applies a warping effect to the input array based on the downward local gradient direction using a specified mask. The mask controls where the warp effect is applied, with values expected in the range [0, 1]. This function allows for additional customization of the warp effect.

Parameters
arrayInput array to be warped.
p_maskPointer to the mask array that filters the effect, expected in [0, 1].
amountAmount of displacement (default is 0.02f).
irPre-filtering radius to smooth the input data (default is 4).
reverseReverse the displacement direction if set to true (default is false).

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {256, 256};
glm::vec2 res = {4.f, 4.f};
int seed = 1;
hmap::Array mask = z1;
hmap::remap(mask);
hmap::Array z2 = z1;
hmap::warp_downslope(z2, &mask, 0.02f, 4, false);
hmap::export_banner_png("ex_warp_downslope.png",
{z1, z2},
}

Result

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ argsort()

std::vector< size_t > hmap::argsort ( const std::vector< float > & v)

Returns the indices that would sort the vector.

Parameters
vInput vector.
Returns
Indices representing the sorted order of v.
Note
The original vector is not modified.

◆ compute_median()

float hmap::compute_median ( std::vector< float > values)

Computes the median value of a set of floats.

Parameters
valuesInput values (copied and partially reordered).
Returns
Median of the input values.

◆ find_sign_changes()

std::vector< size_t > hmap::find_sign_changes ( const std::vector< float > & data)

Returns indices where a sign change occurs in the input vector.

A sign change is detected between i-1 and i when values have opposite signs.

Parameters
dataInput vector.
Returns
Indices i where a sign change occurs between data[i-1] and data[i].

◆ generate_random_vector() [1/2]

std::vector< float > hmap::generate_random_vector ( size_t size,
float min_value,
float max_value,
uint32_t seed )

Generate a vector of random floating-point values within a given range.

Uses a deterministic random number generator initialized with the provided seed. The same seed will always produce the same sequence of values.

Parameters
sizeNumber of elements in the vector.
min_valueLower bound of the range (inclusive).
max_valueUpper bound of the range (inclusive).
seedSeed used to initialize the random number generator.
Returns
std::vector<float> Vector filled with random values in [min_value, max_value].

◆ generate_random_vector() [2/2]

std::vector< int > hmap::generate_random_vector ( size_t size,
int min_value,
int max_value,
uint32_t seed )

Generate a vector of random integers within a given range.

Uses a deterministic random number generator initialized with the provided seed. The same seed will always produce the same sequence of values.

Parameters
sizeNumber of elements in the vector.
min_valueLower bound of the range (inclusive).
max_valueUpper bound of the range (inclusive).
seedSeed used to initialize the random number generator.
Returns
std::vector<int> Vector filled with random integers in [min_value, max_value].

◆ generate_unique_random_vector()

std::vector< int > hmap::generate_unique_random_vector ( size_t size,
int min_value,
int max_value,
uint32_t seed )

Generate a vector of unique random integers within a given range.

Values are sampled without replacement using a deterministic shuffle based on the provided seed.

Parameters
sizeNumber of elements to generate.
min_valueLower bound (inclusive).
max_valueUpper bound (inclusive).
seedSeed for reproducible randomness.
Returns
std::vector<int> Vector of unique integers in [min_value, max_value].
Exceptions
std::invalid_argumentIfsizeexceedsavailableuniquevalues.

◆ make_histogram()

std::string hmap::make_histogram ( const std::vector< float > & values,
int bin_count,
int hist_height )

Generates an ASCII histogram representation of values.

Parameters
valuesInput data.
bin_countNumber of bins.
hist_heightHeight of the histogram in characters.
Returns
String representing the histogram.

◆ moving_average()

std::vector< float > hmap::moving_average ( const std::vector< float > & input,
int radius )

Smooths a vector using a centered moving average.

Each value is replaced by the average of its neighbors within a given radius.

Parameters
inputInput vector.
radiusNumber of elements on each side to include in the average.
Returns
Smoothed vector of the same size.
Note
Borders are handled by clamping (no wrapping).

◆ reindex_vector() [1/3]

template<typename T>
void hmap::reindex_vector ( std::vector< T > & v,
std::vector< size_t > & idx )

Reorders a vector using a given index mapping.

Template Parameters
TType of the vector elements.
Parameters
vVector to reorder.
idxIndex mapping (typically from argsort).
Note
idx[k] indicates the source index of the k-th element in the result.

◆ remap() [3/3]

std::vector< float > hmap::remap ( const std::vector< float > & data,
float new_min = 0.f,
float new_max = 1.f )

Remaps values of a vector to a given range [new_min, new_max].

Parameters
dataInput vector.
new_minTarget minimum value.
new_maxTarget maximum value.
Returns
Remapped vector.
Note
If input values are constant, all outputs are set to new_min.

◆ shuffle_vector()

template<typename T>
void hmap::shuffle_vector ( std::vector< T > & values,
std::uint32_t seed )

Shuffles a vector in-place using a deterministic seed.

Template Parameters
TType of the vector elements.
Parameters
valuesVector to shuffle.
seedSeed for the random generator.

◆ shuffled_vector()

template<typename T>
std::vector< T > hmap::shuffled_vector ( const std::vector< T > & values,
std::uint32_t seed )

Returns a shuffled copy of a vector.

Template Parameters
TType of the vector elements.
Parameters
valuesInput vector.
seedSeed for the random generator.
Returns
Shuffled copy of the input vector.

◆ upperbound_right()

size_t hmap::upperbound_right ( const std::vector< float > & v,
float value )

Returns the index of the first element greater than a given value.

Equivalent to std::upper_bound but returns the index instead of an iterator.

Parameters
vSorted input vector.
valueValue to compare.
Returns
Index of the first element greater than value.

◆ vector_unique_values()

void hmap::vector_unique_values ( std::vector< float > & v)

Removes duplicate values from a vector.

Parameters
vInput vector.
Note
The vector is modified in-place.
The resulting order is not guaranteed to be preserved.

◆ to_string() [2/3]

std::string hmap::to_string ( StorageMode m)

◆ make_storage()

std::unique_ptr< TileStorage > hmap::make_storage ( glm::ivec2 shape,
glm::ivec2 tile_shape,
StorageMode storage_mode )

◆ to_string() [3/3]

std::string hmap::to_string ( ForEachMode m)
inline

◆ copy_data()

void hmap::copy_data ( const VirtualArray & src,
VirtualArray & dst,
const ComputeMode & cm )

◆ sum_per_tile()

void hmap::sum_per_tile ( const VirtualArray & va,
std::vector< float > & tile_sums,
float * p_total_inner_sum = nullptr,
const VirtualArray * p_exclusion_mask = nullptr,
float exclusion_threshold = 0.f,
const ComputeMode & cm = {} )

◆ unpack_impl()

template<std::size_t N, typename T, std::size_t... Is>
auto hmap::unpack_impl ( const std::vector< T * > & v,
std::index_sequence< Is... >  )

◆ unpack()

template<std::size_t N, typename T>
auto hmap::unpack ( const std::vector< T * > & v)

◆ convert_texture_channels()

VirtualTexture hmap::convert_texture_channels ( const VirtualTexture & src,
int dst_channels,
float fill_value,
const ComputeMode & cm )

◆ for_each_tile() [1/2]

template<typename Func>
void hmap::for_each_tile ( VirtualTexture & tex,
Func && func,
const ComputeMode & cm )

◆ for_each_tile() [2/2]

template<typename Func>
void hmap::for_each_tile ( const VirtualTexture & tex,
Func && func,
const ComputeMode & cm )

◆ for_each_pixel()

template<typename Func>
void hmap::for_each_pixel ( VirtualTexture & tex,
Func && func,
const ComputeMode & cm )

◆ grow_forest_competition_nn()

Forest hmap::grow_forest_competition_nn ( const Forest & forest,
const std::vector< Species > & species = {},
const InteractionMatrix & competition_matrix = {},
const Array & max_radius_scale = {},
float max_radius_scale_strength = 1.0f,
bool prune_unviable = true,
const BBox2D & bbox = BBox2D{} )

Adjusts tree radii based on nearest-neighbor distances and species competition constraints.

For each tree $i$ with nearest neighbor $j$ at Euclidean distance $d_i = |p_i - p_j|$:

  • Looks up competition factor $\alpha = \text{competition_matrix.get}(s_i, s_j)$ (or species $[s_i].\text{competition_factor}$).
  • Calculates estimated radius $r_i = \alpha \cdot d_i$.
  • Linearly scales effective maximum radius: $r_{\max,\text{eff}} = r_{\min}(s_i) + s \cdot (r_{\max}(s_i) - r_{\min}(s_i))$, where $s \in [0, 1]$ is sampled from max_radius_scale (if provided, default $s = 1.0$).
  • Clamps $r_i \in [\text{radius_min}(s_i), r_{\max,\text{eff}}]$.
  • If prune_unviable is true and raw calculated radius $r_i < \text{radius_min}(s_i)$, the tree is removed.
Parameters
forestInput forest container.
speciesVector of Species definitions.
competition_matrixOptional pairwise S x S competition factors (alpha).
max_radius_scaleOptional 2D array in [0, 1] scaling maximum radius locally (0 -> rmax = rmin, 1 -> rmax = rmax).
max_radius_scale_strengthBlend strength for max_radius_scale in [0, 1] (0 -> no scaling/full rmax, 1 -> full scale array modulation).
prune_unviableWhether to remove trees unable to reach radius_min.
bboxBounding box {xmin, xmax, ymin, ymax} for sampling max_radius_scale.
Returns
Forest Grown forest with updated tree radii.

◆ grow_forest_competition_voronoi()

Forest hmap::grow_forest_competition_voronoi ( const Forest & forest,
const std::vector< Species > & species = {},
const InteractionMatrix & competition_matrix = {},
const Array & max_radius_scale = {},
float max_radius_scale_strength = 1.0f,
bool prune_unviable = true,
const BBox2D & bbox = BBox2D{} )

Adjusts tree radii based on Voronoi cell areas and species competition constraints.

Builds a Delaunay triangulation (TerrainTriMesh) on the tree positions in the XY plane to compute the local Voronoi/dual cell territory area $A_i$ of each tree:

  • Computes equivalent circular territory radius $r_i = \sqrt{A_i / \pi}$.
  • Multiplies by competition factor $\alpha = \text{species}[s_i].\text{competition_factor}$ (or pairwise $\alpha = \text{competition_matrix.get}(s_i, s_i)$): $r_{\text{est}} = \alpha \cdot r_i$.
  • Linearly scales effective maximum radius: $r_{\max,\text{eff}} = r_{\min}(s_i) + s \cdot (r_{\max}(s_i) - r_{\min}(s_i))$, where $s \in [0, 1]$ is sampled from max_radius_scale (if provided, default $s = 1.0$).
  • Clamps $r_i \in [\text{radius_min}(s_i), r_{\max,\text{eff}}]$.
  • If prune_unviable is true and raw calculated radius $r_{\text{est}} < \text{radius_min}(s_i)$, the tree is removed.
Parameters
forestInput forest container.
speciesVector of Species definitions.
competition_matrixOptional pairwise S x S competition factors (alpha).
max_radius_scaleOptional 2D array in [0, 1] scaling maximum radius locally (0 -> rmax = rmin, 1 -> rmax = rmax).
max_radius_scale_strengthBlend strength for max_radius_scale in [0, 1] (0 -> no scaling/full rmax, 1 -> full scale array modulation).
prune_unviableWhether to remove trees unable to reach radius_min.
bboxBounding box {xmin, xmax, ymin, ymax} for sampling max_radius_scale.
Returns
Forest Grown forest with updated tree radii.

◆ grow_forest_iterative()

Forest hmap::grow_forest_iterative ( const Forest & forest,
const std::vector< Species > & species = {},
size_t iterations = 10,
float growth_rate = 0.1f,
const InteractionMatrix & competition_matrix = {},
const Array & max_radius_scale = {},
float max_radius_scale_strength = 1.0f,
bool prune_unviable = true,
const BBox2D & bbox = BBox2D{},
const UvTile & region = UvTile::unit() )

Simulates iterative plant growth with neighborhood competition and mortality.

Progressively expands plant crowns over multiple time steps according to: r_i^{t+1} = min(r_max_eff, r_i^t + G_i * max(0, 1 - C_i)) where G_i is the growth increment and C_i is the neighborhood competition factor. Suppressed plants falling below species viability or suffocated by larger crowns are pruned.

Parameters
forestInput forest container.
speciesVector of Species definitions.
iterationsMaximum number of growth iterations.
growth_rateBase growth fraction per iteration in [0, 1].
competition_matrixOptional pairwise competition matrix.
max_radius_scaleOptional 2D heightmap array to modulate max radius locally.
max_radius_scale_strengthStrength factor for max_radius_scale in [0, 1].
prune_unviableWhether to remove suppressed/non-viable plants.
bboxSpatial bounding box for sampling max_radius_scale.
regionUvTile descriptor for tiled domain positioning.
Returns
Forest Grown and thinned forest container.

◆ grow_forest_soft_core()

Forest hmap::grow_forest_soft_core ( const Forest & forest,
const std::vector< Species > & species = {},
const InteractionMatrix & repulsion_distances = {},
const InteractionMatrix & repulsion_strengths = {},
size_t target_count = 0,
const Array & max_radius_scale = {},
float max_radius_scale_strength = 1.0f,
uint32_t seed = 0,
const BBox2D & bbox = BBox2D{} )

Performs multi-species Strauss soft-core growth and thinning on an input forest.

Repels and thins neighboring trees probabilistically based on species pairwise interaction distances and strengths, and clamps resulting crown radii according to species traits and local spatial scale.

Parameters
forestInput candidate forest.
speciesVector of Species definitions.
repulsion_distancesInteraction distance matrix between species.
repulsion_strengthsRepulsion strength matrix between species in [0, 1].
target_countOptional target number of trees (0 means keep all accepted).
max_radius_scaleOptional 2D array scaling maximum radius locally.
max_radius_scale_strengthBlend strength for max_radius_scale in [0, 1].
seedRandom number generator seed.
bboxBounding box {xmin, xmax, ymin, ymax}.
Returns
Forest Grown and thinned forest.

◆ build_tree_density()

Array hmap::build_tree_density ( const Array & heightmap,
float min_elev = 0.0f,
float max_elev = 0.9f,
float elev_transition_width = 0.1f,
float min_talus = 0.003f,
float max_talus = 0.005f,
float angle = 30.0f,
float angle_width = 90.0f,
float weight_elev = 1.0f,
float weight_talus = 1.0f,
float weight_angle = 0.8f,
float weight_twi = 0.5f,
const Array & secondary_density = {},
float weight_secondary = 1.0f,
const Array & exclusion_mask = {},
float exclusion_threshold = 0.f )

Computes an environmental suitability criteria map in [0, 1] representing tree probability density based on elevation, slope talus, aspect angle, topographic wetness index (TWI), an optional secondary density map, and an optional exclusion mask.

Parameters
heightmapInput terrain heightmap.
min_elevMinimum elevation threshold.
max_elevMaximum elevation threshold.
elev_transition_widthElevation transition smoothing width.
min_talusSlope/talus threshold for full suitability (1.0).
max_talusSlope/talus threshold for zero suitability (0.0).
anglePreferred slope aspect angle in degrees.
angle_widthSlope aspect angle tolerance half-width in degrees.
weight_elevWeight for elevation criterion in [0, 1].
weight_talusWeight for talus/slope criterion in [0, 1].
weight_angleWeight for aspect angle criterion in [0, 1].
weight_twiWeight for topographic wetness index criterion in [0, 1].
secondary_densityOptional secondary density or noise modulation map.
weight_secondaryWeight for optional secondary density map in [0, 1].
exclusion_maskOptional exclusion mask (where > exclusion_threshold, density is set to 0).
exclusion_thresholdThreshold above which exclusion mask excludes trees (default 0.f).
Returns
Array Computed density array in [0, 1].

◆ seed_forest_clusters()

Forest hmap::seed_forest_clusters ( size_t species_count,
size_t tree_count,
const Array & density,
const Array & exclusion,
float cluster_spread = 0.05f,
size_t points_per_cluster = 8,
const ForestSeedingOptions & options = {},
const UvTile & region = UvTile::unit(),
ICommunicator & comm = SingleArrayComm::instance() )

Generates a clustered forest distribution using inverse transform sampling for cluster centers and local cluster regions.

Parameters
species_countNumber of distinct tree species.
tree_countTarget total number of trees.
densityGlobal density map array.
exclusionExclusion map array.
cluster_spreadHalf-extent of the bounding box surrounding each cluster center.
points_per_clusterNumber of child points sampled per parent cluster.
optionsSeeding options.
regionUvTile descriptor for tiled domain positioning.
commCommunicator for collective density reduction.
Returns
Forest Sampled forest container.

◆ seed_forest_kmeans()

Forest hmap::seed_forest_kmeans ( size_t species_count,
size_t tree_count,
const Array & density,
const Array & exclusion,
float cluster_randomness = 0.0f,
size_t k_neighbors = 4,
const ForestSeedingOptions & options = {},
const UvTile & region = UvTile::unit(),
ICommunicator & comm = SingleArrayComm::instance() )

Generates a multi-species forest distribution using 2D inverse transform sampling for positions and PointSampler k-means clustering to tag species.

Note
Species abundance is governed by spatial cluster partitioning in the compactness feature space; species weights in options.species are not taken into account by this function.
Parameters
species_countNumber of distinct tree species.
tree_countTarget total number of trees.
densityGlobal density map array.
exclusionExclusion map array.
cluster_randomnessRandomness factor in [0, 1] added to cluster features.
k_neighborsNumber of nearest spatial neighbors used to extract compactness features.
optionsSeeding options.
regionUvTile descriptor for tiled domain positioning.
commCommunicator for collective density reduction.
Returns
Forest Sampled forest container.

◆ generate_network_alpha_model()

Graph hmap::generate_network_alpha_model ( const std::vector< float > & xc,
const std::vector< float > & yc,
const std::vector< float > & size,
const BBox2D & bbox,
const Array & z,
std::uint32_t seed,
float alpha = 0.7f,
int n_dummy_nodes = 2500,
float dz_weight = 1.f,
const Array * p_weight = nullptr )

Generate a large scale road network between "nodes" (or cities) using the alpha model.

Based on the paper of Molinero et al. [Molinero2020].

Parameters
xcx locations of the cities.
ycy locations of the cities.
sizeCity sizes (arbitrary unit).
bboxBounding box.
zHeightmap.
seedRandom seed number.
alpha"Alpha coefficient" of the model (cost difference between creating a new and using an old one).
n_dummy_nodesNumber of dummy nodes added for the tesselation.
dz_weightWeight of the elevation difference in the cost function.
p_weightMap defining the local value added to the cost function (can be used to add large penalizations to create "no go" zones).
Returns
Graph Road network, edge weights correspond to the road "size".

Example

#include "highmap.hpp"
int main(void)
{
glm::ivec2 shape = {512, 512};
int seed = 0;
shape,
{4.f, 4.f},
seed);
z.to_png("ex_generate_network_alpha_model0.png", hmap::Cmap::TERRAIN, true);
// "cities"
int npoints = 4;
int ndummy = 50 * 50;
float alpha = 0.8f;
hmap::BBox2D bbox = {1.f, 2.f, -0.5f, 0.5f};
hmap::Cloud cloud = hmap::Cloud(npoints,
seed,
hmap::BBox2D({1.2f, 1.8f, -0.4f, 0.4f}));
cloud.get_y(),
cloud.get_values(),
bbox,
z,
seed,
alpha,
ndummy);
network.to_csv("nodes.csv", "adj.csv");
// network.set_values(1.f);
// graph view, no bounding box, color by edge weight
network.to_png("ex_generate_network_alpha_model1.png");
// graph project onto an array, with bounding box, color by point
// values
network.to_array(g, bbox);
g.to_png("ex_generate_network_alpha_model2.png", hmap::Cmap::JET);
}
Graph generate_network_alpha_model(const std::vector< float > &xc, const std::vector< float > &yc, const std::vector< float > &size, const BBox2D &bbox, const Array &z, std::uint32_t seed, float alpha=0.7f, int n_dummy_nodes=2500, float dz_weight=1.f, const Array *p_weight=nullptr)
Generate a large scale road network between "nodes" (or cities) using the alpha model.
Definition alpha_model.cpp:24

Result

◆ build_rock_density()

Array hmap::build_rock_density ( const Array & heightmap,
float max_slope = 0.05f,
float bulkify_amp = 0.01f,
float weight_elev = 1.0f,
float weight_slope = 1.0f,
float weight_rivers = 1.0f,
float river_talus_ref = 0.1f,
float river_clipping_ratio = 1000.0f,
const Array & secondary_density = {},
float weight_secondary = 1.0f,
const Array & exclusion_mask = {},
float exclusion_threshold = 0.f,
const BBox2D & bbox = BBox2D{} )

Computes a probability density map in [0, 1] for rock placement based on elevation, talus/slope, river drainage paths, an optional secondary density map, and an optional exclusion mask.

A subtle bulkify filter can be applied to the heightmap prior to computing talus and river beds, eliminating micro-depressions and guiding flow lines.

Parameters
heightmapInput terrain heightmap.
max_slopeTalus value above which density smoothly falls to zero.
bulkify_ampAmplitude of bulkify pulse filter applied to the terrain (0.f disables).
weight_elevWeight for inverted elevation criterion.
weight_slopeWeight for talus/slope criterion.
weight_riversWeight for river accumulation criterion.
river_talus_refReference talus for river flow partitioning.
river_clipping_ratioFlow accumulation clipping ratio.
secondary_densityOptional secondary density modulation map.
weight_secondaryWeight for optional secondary density map.
exclusion_maskOptional exclusion mask (density set to 0 where exclusion > exclusion_threshold).
exclusion_thresholdThreshold above which exclusion mask excludes rocks.
bboxDomain bounding box for tiled bulkify synthesis.
Returns
Array Computed density array in [0, 1].

◆ place_rocks_procedural()

RockField hmap::place_rocks_procedural ( size_t rock_count,
const Array & elevation,
float min_elev = 0.f,
float max_elev = 0.9f,
float max_slope = 1.f,
const Array & density = {},
const Array & exclusion = {},
float size_slope_weight = 0.f,
float size_elevation_gain = 1.f,
float size_elevation_exponent = 1.f,
const RockSeedingOptions & options = {},
const UvTile & region = UvTile::unit(),
ICommunicator & comm = SingleArrayComm::instance() )

Places rocks procedurally on a terrain, without physical simulation.

Positions are sampled from a density map (defaults to a flat density equal to 1 if none is provided). Rock radii are drawn from a bounded power-law (Pareto) distribution between radius_min and a local maximum radius that grows toward radius_max as the elevation decreases: high areas only hold small rocks, whereas low areas hold both small and large rocks (the size distribution broadens when lowering altitude). Steep slopes further reduce the maximum rock size.

Parameters
rock_countTarget number of rocks.
elevationTerrain elevation heightmap.
min_elevElevation mapped to 0 in the normalized elevation.
max_elevElevation mapped to 1 in the normalized elevation.
max_slopeTalus threshold above which rock size is attenuated.
densityOptional user density map (if empty, defaults to uniform flat density of 1).
exclusionOptional exclusion map (same shape as elevation).
size_slope_weightIn [0, 1], reduces the maximum rock size on steep slopes (0 = no effect).
size_elevation_gainLow-elevation influence on the maximum rock size (0 = none).
size_elevation_exponentPower-law exponent of the maximum size / (1 - elevation) relation.
optionsSeeding options (bbox, seed, exclusion threshold, rock distribution).
regionUvTile descriptor for tiled domain positioning.
commCommunicator for collective density reduction.
Returns
RockField Placed rocks.

◆ seed_rock_field()

RockField hmap::seed_rock_field ( size_t rock_count,
const Array & density,
const Array & exclusion = {},
const RockSeedingOptions & options = {},
const UvTile & region = UvTile::unit(),
ICommunicator & comm = SingleArrayComm::instance() )

Seeds a general rock/boulder field using inverse density transform sampling and applies power-law radius distribution and collision resolution.

Parameters
rock_countTarget number of rocks.
densitySpatial probability density map array.
exclusionOptional exclusion map array.
optionsSeeding options.
regionUvTile descriptor for tiled domain positioning.
commCommunicator for collective density reduction.
Returns
RockField Sampled rock field.

◆ simulate_rock_emission()

RockField hmap::simulate_rock_emission ( size_t rock_count,
const Array & emission_density,
const Array & elevation,
const Array * p_friction_map = nullptr,
const RockDistribution & dist = {},
const RockSimulationOptions & options = {} )

Emits rocks from a spatial emission density map and simulates their trajectories downhill across terrain on GPU.

Parameters
rock_countTarget number of rocks to emit and simulate.
emission_densitySpatial probability density map where rocks originate.
elevationTerrain elevation heightmap.
p_friction_mapOptional soil friction map (same dimensions as elevation).
distRock distribution specifying radii and classes.
optionsSimulation options.
Returns
RockField Field containing the resting rocks.

◆ simulate_rock_trajectories()

RockField hmap::simulate_rock_trajectories ( const RockField & rocks,
const Array & elevation,
const Array * p_friction_map = nullptr,
const RockSimulationOptions & options = {} )

Simulates physical movement (sliding, rolling, bouncing, and inter-rock collision avoidance) for an existing RockField across terrain on GPU.

Parameters
rocksInput rock field with initial positions.
elevationTerrain elevation heightmap.
p_friction_mapOptional soil friction map.
optionsSimulation options.
Returns
RockField Updated rock field with resting positions.

◆ operator*()

Array hmap::operator* ( const float value,
const Array & array )
Parameters
valueThe scalar value to multiply.
arrayThe Array to multiply with.
Returns
Array The resulting Array after multiplication.

◆ operator/()

Array hmap::operator/ ( const float value,
const Array & array )
Parameters
valueThe scalar value to divide by.
arrayThe Array to divide by.
Returns
Array The resulting Array after division.

◆ operator+()

Array hmap::operator+ ( const float value,
const Array & array )
Parameters
valueThe scalar value to add.
arrayThe Array to add.
Returns
Array The resulting Array after addition.

◆ operator-()

const Array hmap::operator- ( const float value,
const Array & array )
Parameters
valueThe scalar value to subtract.
arrayThe Array to subtract from.
Returns
Array The resulting Array after subtraction.

◆ convert_mat_to_array()

template<typename T>
void hmap::convert_mat_to_array ( const cv::Mat & mat,
Array & array,
bool flip_j )

◆ square_fill_md()

void hmap::square_fill_md ( Array & array,
Mat< int > & is_done,
int i1,
int i2,
int j1,
int j2,
float noise_scale,
std::mt19937 gen,
std::uniform_real_distribution< float > dis )

◆ square_md()

void hmap::square_md ( Array & array,
Mat< int > & is_done,
int step,
float noise_scale,
std::mt19937 gen,
std::uniform_real_distribution< float > dis )

◆ flatbed_carve() [2/2]

Array hmap::flatbed_carve ( glm::ivec2 shape,
const Path & path,
float bottom_extent,
float vmin,
float depth,
float falloff_distance,
float outer_slope,
bool preserve_bedshape,
RadialProfile radial_profile,
float radial_profile_parameter,
Array * p_falloff_mask,
const Array * p_noise_r,
const UvRect & uv_rect )

◆ helper_hash_u32()

uint32_t hmap::helper_hash_u32 ( uint32_t x)
inline

◆ helper_hash_01()

float hmap::helper_hash_01 ( uint32_t x)
inline

◆ helper_tov3()

std::vector< glm::vec3 > hmap::helper_tov3 ( const std::vector< std::vector< float > > & colors)

◆ thermal_schott() [1/4]

void hmap::thermal_schott ( Array & z,
const Array & talus,
int iterations,
float intensity )

◆ thermal_schott() [2/4]

void hmap::thermal_schott ( Array & z,
const Array & talus,
Array * p_mask,
int iterations,
float intensity )

◆ thermal_schott() [3/4]

void hmap::thermal_schott ( Array & z,
const float talus,
int iterations,
float intensity )

◆ thermal_schott() [4/4]

void hmap::thermal_schott ( Array & z,
const float talus,
Array * p_mask,
int iterations,
float intensity )

◆ helper_build_mesh_masked()

void hmap::helper_build_mesh_masked ( aiMesh * p_mesh,
const Array & array,
const Array & mask,
float elevation_scaling,
bool fit_boundaries )

◆ helper_build_mesh()

void hmap::helper_build_mesh ( aiMesh * p_mesh,
const Array & array,
MeshType mesh_type,
float elevation_scaling,
float max_error,
bool fit_boundaries )

◆ compute_splatmap()

Texture hmap::compute_splatmap ( const Array * p_r,
const Array * p_g,
const Array * p_b,
const Array * p_a )

◆ helper_compute_tile_bounds()

glm::ivec4 hmap::helper_compute_tile_bounds ( int tile_x,
int tile_y,
const glm::ivec2 & tile_count,
const glm::ivec2 & array_shape,
bool overlapping_edges,
bool reverse_tile_y_indexing )

◆ recurve_bexp() [3/3]

void hmap::recurve_bexp ( Array & array,
float tau,
const Array * p_mask )

◆ recurve_exp() [3/3]

void hmap::recurve_exp ( Array & array,
float tau,
const Array * p_mask )

◆ helper_build_path()

Path hmap::helper_build_path ( const std::vector< Point > & points,
InterpolationMethodCurve method,
Path::EdgeDivisionMode edm,
int edge_divisions,
int point_count )

◆ helper_estimate_count()

size_t hmap::helper_estimate_count ( const BBox2D & bbox,
float distance )

◆ compute_gradient()

void hmap::compute_gradient ( const Array & array,
Array & dx,
Array & dy,
float x_coeff[3],
float y_coeff[3],
float normalize_factor )

◆ compute_gradient_norm()

Array hmap::compute_gradient_norm ( const Array & array,
float x_coeff[3],
float y_coeff[3],
float normalize_factor,
Array * p_dx = nullptr,
Array * p_dy = nullptr )

◆ is_monotonic()

bool hmap::is_monotonic ( const std::vector< float > & data)

◆ find_last_index_smaller_than()

int hmap::find_last_index_smaller_than ( const std::vector< float > & vec,
float threshold )

◆ helper_wrap_phi()

float hmap::helper_wrap_phi ( float phi)

◆ helper_make_wrapped()

template<typename F>
auto hmap::helper_make_wrapped ( F f)

◆ helper_reconstruction_impl()

Array hmap::helper_reconstruction_impl ( const Array & marker,
const Array & mask,
int ir,
float k_smooth,
std::function< Array(const Array &, int)> morph_op,
std::function< Array(const Array &, const Array &, float)> clamp_op )

◆ helper_thinning()

void hmap::helper_thinning ( Array & in,
int iter )

◆ helper_flip_rot_transpose()

void hmap::helper_flip_rot_transpose ( Array & array,
bool do_flip,
int rot_steps,
bool do_transpose )

◆ helper_crater_radial_function()

float hmap::helper_crater_radial_function ( float r,
float inner_depth,
float inner_exp,
float lip_height,
float lip_extent,
float lip_exp,
int n_terraces,
float terrace_extent,
float terrace_exp,
float terrace_persistence )

◆ helper_crater_profile()

float hmap::helper_crater_profile ( float r,
float dx,
float dy,
float alpha,
float ap,
float am,
float inner_depth,
float inner_exp,
float lip_height,
float lip_extent,
float lip_exp,
float central_peak_height,
float central_peak_extent,
int n_terraces,
float terrace_extent,
float terrace_exp,
float terrace_persistence )

◆ helper_pick_lowest()

Point hmap::helper_pick_lowest ( const Point & pa,
const Point & pb,
const Array & z,
float max_offset,
int steps )

◆ count_neighbors_to_fill()

int hmap::count_neighbors_to_fill ( int i,
int j,
Mat< int > & is_cell_done )

◆ cmp_queue()

bool hmap::cmp_queue ( std::pair< int, std::pair< int, int > > & a,
std::pair< int, std::pair< int, int > > & b )

◆ reindex_vector() [2/3]

void hmap::reindex_vector ( std::vector< int > & v,
std::vector< size_t > & idx )

◆ reindex_vector() [3/3]

void hmap::reindex_vector ( std::vector< float > & v,
std::vector< size_t > & idx )

◆ TEST() [1/5]

hmap::TEST ( NoiseStretch ,
CpuIsotropicPreserved  )

◆ TEST() [2/5]

hmap::TEST ( NoiseStretch ,
CpuDirectionalMatchesAxisScaling  )

◆ TEST() [3/5]

hmap::TEST ( NoiseStretch ,
CpuOctaveDecay  )

◆ TEST() [4/5]

hmap::TEST ( NoiseStretch ,
GpuIsotropicAndDirectional  )

◆ TEST() [5/5]

hmap::TEST ( NoiseStretch ,
AllNoiseTypesCpuAndGpu  )