Skip to main content

HeightField

Struct HeightField 

Source
pub struct HeightField {
    pub heights: Vec<Real>,
    pub rows: usize,
    pub cols: usize,
    pub scale_x: Real,
    pub scale_z: Real,
}
Expand description

A grid-based height field for terrain representation.

Heights are stored in row-major order. The field spans from (0,0) to (scale_x * (cols-1), scale_z * (rows-1)) in the XZ plane.

Fields§

§heights: Vec<Real>

Height values in row-major order.

§rows: usize

Number of rows (Z direction).

§cols: usize

Number of columns (X direction).

§scale_x: Real

Spacing in the X direction.

§scale_z: Real

Spacing in the Z direction.

Implementations§

Source§

impl HeightField

Source

pub fn new( heights: Vec<Real>, rows: usize, cols: usize, scale_x: Real, scale_z: Real, ) -> Self

Create a new height field.

Source

pub fn height_at(&self, row: usize, col: usize) -> Real

Get the height at grid position (row, col).

Source

pub fn from_fn( cols: usize, rows: usize, cell_size: Real, f: impl Fn(usize, usize) -> Real, ) -> Self

Create a height field from a function.

The function f(col, row) returns the height at each grid point.

Source

pub fn height_at_uv(&self, u: Real, v: Real) -> Real

Bilinear interpolation of height at normalized coordinates (u, v).

u and v are in [0, 1], mapping to the full extent of the grid.

Source

pub fn normal_at_grid(&self, col: usize, row: usize) -> [Real; 3]

Compute the surface normal at grid point (col, row) via finite differences.

Source

pub fn to_triangle_mesh(&self) -> (Vec<[Real; 3]>, Vec<[usize; 3]>)

Tessellate the height field into a triangle mesh.

Returns (vertices, triangles) where each vertex is [x, y, z] and each triangle is 3 vertex indices.

Source

pub fn min_height(&self) -> Real

Return the minimum height in the field.

Source

pub fn max_height(&self) -> Real

Return the maximum height in the field.

Source

pub fn surface_area(&self) -> Real

Compute the total surface area by summing triangle areas from tessellation.

Source

pub fn smooth(&mut self, iterations: usize)

Apply Laplacian smoothing to the height field.

Each interior height is replaced by the average of its 4-connected neighbors. Boundary heights are unchanged.

Source

pub fn ray_cast_grid( &self, origin: [Real; 3], dir: [Real; 3], max_toi: Real, ) -> Option<(Real, [Real; 3])>

Ray cast using grid DDA traversal and per-cell triangle intersection.

Returns Some((toi, [nx, ny, nz])) for the closest hit within max_toi, or None if no intersection.

Source§

impl HeightField

Source

pub fn lod_downsample(&self, factor: usize) -> HeightField

Generate a downsampled (LOD) version of the height field.

factor must be ≥ 1. A factor of 2 halves the resolution by averaging 2×2 blocks of cells. If the grid is too small the original is returned.

Source

pub fn lod_pyramid(&self, levels: usize) -> Vec<HeightField>

Generate multiple LOD levels.

Returns a Vec where index 0 is the original, index 1 is 2× downsampled, index 2 is 4× downsampled, etc., until the grid is too small.

Source

pub fn normal_at_world(&self, x: Real, z: Real) -> [Real; 3]

Compute the normal at an arbitrary world-space XZ position via bilinear interpolation of the four surrounding grid normals.

Source

pub fn serialize(&self) -> Vec<Real>

Serialize the height field to a flat Vecf64` prefixed by metadata.

Format: \[rows, cols, scale_x, scale_z, h0, h1, ...\]

Source

pub fn deserialize(data: &[Real]) -> Option<HeightField>

Deserialize a height field from a flat Vecf64(inverse ofserialize`).

Source

pub fn compute_all_normals(&self) -> Vec<[Real; 3]>

Compute per-vertex normals for all grid vertices.

Returns a flat Vec<[Real; 3]> in row-major order.

Source

pub fn height_at_world(&self, x: Real, z: Real) -> Real

Height at arbitrary world-space XZ position (bilinear interpolation).

Clamps to grid extents.

Source

pub fn ray_cast_bounded( &self, origin: [Real; 3], dir: [Real; 3], max_toi: Real, max_steps: usize, ) -> Option<(Real, [Real; 3])>

Ray cast with DDA and a maximum number of steps (bounded version).

Avoids unbounded loops on very large grids.

Source§

impl HeightField

Source

pub fn aabb(&self) -> ([f64; 3], [f64; 3])

Axis-aligned bounding box of this height field in world space.

Returns (min, max) where each is [x, y, z].

Source

pub fn height_at_xz(&self, x: f64, z: f64) -> f64

Bilinear height interpolation at world-space position (x, z).

Unlike height_at(row, col) (grid indices) and height_at_world, this method accepts (x, z) world coordinates and returns the interpolated height, clamping to the grid extents.

Source

pub fn normals(&self) -> Vec<[f64; 3]>

Per-vertex normals for the entire grid in row-major order.

Each normal is computed via finite differences over the 4-connected neighborhood and returned as a unit vector [nx, ny, nz].

Source

pub fn tessellate(&self) -> (Vec<[f64; 3]>, Vec<[usize; 3]>)

Tessellate the height field into a triangle mesh.

Returns (vertices, indices) where:

  • vertices is a list of world-space [x, y, z] positions, one per grid point, in row-major order.
  • indices is a list of [i0, i1, i2] triangles (two per quad cell).
Source

pub fn ray_intersect( &self, origin: [f64; 3], dir: [f64; 3], ) -> Option<(f64, [f64; 3])>

DDA ray intersection returning (t, normal) for the first hit.

Uses grid-cell DDA traversal in the XZ plane, testing the two triangles of each cell with Möller–Trumbore intersection. Returns None if the ray misses the terrain or is going away from it.

The search is limited to a reasonable distance (diagonal of the AABB).

Source§

impl HeightField

Source

pub fn slope_at(&self, col: usize, row: usize) -> f64

Compute the slope magnitude at grid point (col, row).

Slope is defined as sqrt((dh/dx)² + (dh/dz)²) using the same finite-difference stencil as normal_at_grid.

Source

pub fn curvature_at(&self, col: usize, row: usize) -> f64

Compute the mean curvature at grid point (col, row).

Uses a second-order central difference approximation: κ ≈ (d²h/dx² + d²h/dz²) / 2.

Source

pub fn slope_map(&self) -> Vec<f64>

Return a flat Vecf64` of slope magnitudes in row-major order.

Source

pub fn curvature_map(&self) -> Vec<f64>

Return a flat Vecf64` of mean curvatures in row-major order.

Source

pub fn closest_vertex(&self, q: [f64; 3]) -> ([f64; 3], usize, usize)

Find the closest surface point to query point q by brute-force search over all grid vertices.

Returns (closest_world_point, row, col).

Source

pub fn resample(&self, new_cols: usize, new_rows: usize) -> HeightField

Resample the height field to new grid dimensions by bilinear interpolation.

new_cols and new_rows must be ≥ 2. Returns a new HeightField with the same world extents but a different resolution.

Source

pub fn hydraulic_erode(&mut self, sediment_rate: f64, iterations: usize)

Simple hydraulic erosion step: for each cell, water flows to the steepest-descent neighbor and carries a fraction sediment_rate of height difference.

iterations controls how many passes are performed. For correctness the caller should keep sediment_rate ≤ 0.5.

Source

pub fn flow_accumulation(&self) -> Vec<f64>

Compute a simple flow-accumulation map (watershed proxy).

Each cell accumulates 1 unit plus the total of all upstream cells that drain into it following steepest descent. Returns a flat Vecf64` in row-major order; larger values indicate valleys/channels.

Source

pub fn clamp_heights(&mut self, min_h: f64, max_h: f64)

Clamp all height values to the range \[min_h, max_h\].

Source

pub fn scale_heights(&mut self, factor: f64)

Scale all heights by a uniform factor.

Source

pub fn offset_heights(&mut self, offset: f64)

Offset all heights by a constant value.

Source

pub fn normalize_heights(&mut self)

Normalize heights to the range \[0, 1\]. If all heights are equal, all become 0.

Source

pub fn invert_heights(&mut self)

Invert heights: each height h becomes max_height - (h - min_height).

Source

pub fn mean_height(&self) -> f64

Compute the average height over the entire grid.

Source

pub fn height_variance(&self) -> f64

Compute the variance of heights.

Source

pub fn count_peaks(&self) -> usize

Count the number of local maxima (peaks) in the grid.

A cell is a peak if it is strictly higher than all 4-connected neighbors.

Source

pub fn volume(&self) -> f64

Approximate volume under the height field (above y=0) using the trapezoidal rule.

Each grid cell contributes (average_height) * cell_area.

Source

pub fn ray_cast( &self, ray_origin: &Vec3, ray_direction: &Vec3, max_toi: f64, ) -> Option<HeightfieldRayHit>

Cast a ray against the height field. Returns hit information if intersection found.

Uses the tessellated triangle mesh for accurate intersection.

Trait Implementations§

Source§

impl Clone for HeightField

Source§

fn clone(&self) -> HeightField

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for HeightField

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Shape for HeightField

Source§

fn bounding_box(&self) -> Aabb

Compute the axis-aligned bounding box of this shape (in local space).
Source§

fn support_point(&self, direction: &Vec3) -> Vec3

Compute the support point in the given direction (for GJK).
Source§

fn volume(&self) -> Real

Compute the volume of this shape.
Source§

fn center_of_mass(&self) -> Vec3

Compute the center of mass in local space.
Source§

fn inertia_tensor(&self, _mass: Real) -> Mat3

Compute the inertia tensor for the given mass.
Source§

fn ray_cast( &self, ray_origin: &Vec3, ray_direction: &Vec3, max_toi: Real, ) -> Option<RayHit>

Cast a ray against this shape (in local space). Returns the first intersection within max_toi.
Source§

fn mass_properties(&self, density: Real) -> MassProperties

Compute full mass properties for a given density.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> Conv for T

Source§

fn conv<T>(self) -> T
where Self: Into<T>,

Converts self into T using Into<T>. Read more
Source§

impl<T> FmtForward for T

Source§

fn fmt_binary(self) -> FmtBinary<Self>
where Self: Binary,

Causes self to use its Binary implementation when Debug-formatted.
Source§

fn fmt_display(self) -> FmtDisplay<Self>
where Self: Display,

Causes self to use its Display implementation when Debug-formatted.
Source§

fn fmt_lower_exp(self) -> FmtLowerExp<Self>
where Self: LowerExp,

Causes self to use its LowerExp implementation when Debug-formatted.
Source§

fn fmt_lower_hex(self) -> FmtLowerHex<Self>
where Self: LowerHex,

Causes self to use its LowerHex implementation when Debug-formatted.
Source§

fn fmt_octal(self) -> FmtOctal<Self>
where Self: Octal,

Causes self to use its Octal implementation when Debug-formatted.
Source§

fn fmt_pointer(self) -> FmtPointer<Self>
where Self: Pointer,

Causes self to use its Pointer implementation when Debug-formatted.
Source§

fn fmt_upper_exp(self) -> FmtUpperExp<Self>
where Self: UpperExp,

Causes self to use its UpperExp implementation when Debug-formatted.
Source§

fn fmt_upper_hex(self) -> FmtUpperHex<Self>
where Self: UpperHex,

Causes self to use its UpperHex implementation when Debug-formatted.
Source§

fn fmt_list(self) -> FmtList<Self>
where &'a Self: for<'a> IntoIterator,

Formats each item in a sequence. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pipe for T
where T: ?Sized,

Source§

fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R
where Self: Sized,

Pipes by value. This is generally the method you want to use. Read more
Source§

fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> R
where R: 'a,

Borrows self and passes that borrow into the pipe function. Read more
Source§

fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> R
where R: 'a,

Mutably borrows self and passes that borrow into the pipe function. Read more
Source§

fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
where Self: Borrow<B>, B: 'a + ?Sized, R: 'a,

Borrows self, then passes self.borrow() into the pipe function. Read more
Source§

fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R, ) -> R
where Self: BorrowMut<B>, B: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.borrow_mut() into the pipe function. Read more
Source§

fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
where Self: AsRef<U>, U: 'a + ?Sized, R: 'a,

Borrows self, then passes self.as_ref() into the pipe function.
Source§

fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
where Self: AsMut<U>, U: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.as_mut() into the pipe function.
Source§

fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
where Self: Deref<Target = T>, T: 'a + ?Sized, R: 'a,

Borrows self, then passes self.deref() into the pipe function.
Source§

fn pipe_deref_mut<'a, T, R>( &'a mut self, func: impl FnOnce(&'a mut T) -> R, ) -> R
where Self: DerefMut<Target = T> + Deref, T: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.deref_mut() into the pipe function.
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

Source§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
Source§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
Source§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
Source§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
Source§

impl<T> Tap for T

Source§

fn tap(self, func: impl FnOnce(&Self)) -> Self

Immutable access to a value. Read more
Source§

fn tap_mut(self, func: impl FnOnce(&mut Self)) -> Self

Mutable access to a value. Read more
Source§

fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Immutable access to the Borrow<B> of a value. Read more
Source§

fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
where Self: BorrowMut<B>, B: ?Sized,

Mutable access to the BorrowMut<B> of a value. Read more
Source§

fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
where Self: AsRef<R>, R: ?Sized,

Immutable access to the AsRef<R> view of a value. Read more
Source§

fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
where Self: AsMut<R>, R: ?Sized,

Mutable access to the AsMut<R> view of a value. Read more
Source§

fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
where Self: Deref<Target = T>, T: ?Sized,

Immutable access to the Deref::Target of a value. Read more
Source§

fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Mutable access to the Deref::Target of a value. Read more
Source§

fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self

Calls .tap() only in debug builds, and is erased in release builds.
Source§

fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self

Calls .tap_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Calls .tap_borrow() only in debug builds, and is erased in release builds.
Source§

fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
where Self: BorrowMut<B>, B: ?Sized,

Calls .tap_borrow_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
where Self: AsRef<R>, R: ?Sized,

Calls .tap_ref() only in debug builds, and is erased in release builds.
Source§

fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
where Self: AsMut<R>, R: ?Sized,

Calls .tap_ref_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
where Self: Deref<Target = T>, T: ?Sized,

Calls .tap_deref() only in debug builds, and is erased in release builds.
Source§

fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Calls .tap_deref_mut() only in debug builds, and is erased in release builds.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> TryConv for T

Source§

fn try_conv<T>(self) -> Result<T, Self::Error>
where Self: TryInto<T>,

Attempts to convert self into T using TryInto<T>. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.