use super::*;
impl Default for TerrainConfig {
fn default() -> Self {
Self::alpine(42)
}
}
impl TerrainConfig {
#[must_use]
pub fn alpine(seed: u64) -> Self {
Self {
grid_x: 65,
grid_z: 65,
world_size_x: 120.0,
world_size_z: 120.0,
height_scale: 28.0,
seed,
fbm_octaves: 5,
fbm_frequency: 2.2,
fbm_lacunarity: 2.05,
fbm_persistence: 0.5,
ridged_weight: 0.55,
canyon_weight: 0.1,
terrace_steps: 0,
terrace_strength: 0.0,
hydraulic_droplets: 1500,
thermal_iterations: 8,
talus_angle: 0.65,
biome: TerrainBiome::Alpine,
}
}
#[must_use]
pub fn canyon(seed: u64) -> Self {
Self {
grid_x: 65,
grid_z: 65,
world_size_x: 120.0,
world_size_z: 120.0,
height_scale: 24.0,
seed,
fbm_octaves: 4,
fbm_frequency: 2.6,
fbm_lacunarity: 2.0,
fbm_persistence: 0.48,
ridged_weight: 0.2,
canyon_weight: 0.72,
terrace_steps: 6,
terrace_strength: 0.65,
hydraulic_droplets: 1200,
thermal_iterations: 10,
talus_angle: 0.72,
biome: TerrainBiome::Canyon,
}
}
#[must_use]
pub fn archipelago(seed: u64) -> Self {
Self {
grid_x: 65,
grid_z: 65,
world_size_x: 140.0,
world_size_z: 140.0,
height_scale: 18.0,
seed,
fbm_octaves: 5,
fbm_frequency: 2.4,
fbm_lacunarity: 2.0,
fbm_persistence: 0.52,
ridged_weight: 0.3,
canyon_weight: 0.05,
terrace_steps: 0,
terrace_strength: 0.0,
hydraulic_droplets: 1000,
thermal_iterations: 6,
talus_angle: 0.55,
biome: TerrainBiome::Archipelago,
}
}
#[must_use]
pub fn terraced(seed: u64) -> Self {
Self {
grid_x: 65,
grid_z: 65,
world_size_x: 120.0,
world_size_z: 120.0,
height_scale: 22.0,
seed,
fbm_octaves: 5,
fbm_frequency: 2.0,
fbm_lacunarity: 2.0,
fbm_persistence: 0.5,
ridged_weight: 0.25,
canyon_weight: 0.15,
terrace_steps: 8,
terrace_strength: 0.85,
hydraulic_droplets: 800,
thermal_iterations: 6,
talus_angle: 0.62,
biome: TerrainBiome::TerracedHighlands,
}
}
}
impl HeightfieldTerrain {
#[must_use]
pub fn generate(config: &TerrainConfig) -> Self {
let gx: u32 = config
.get_grid_x()
.clamp(TERRAIN_MIN_GRID, TERRAIN_MAX_GRID);
let gz: u32 = config
.get_grid_z()
.clamp(TERRAIN_MIN_GRID, TERRAIN_MAX_GRID);
let size_x: f32 = sanitize_scalar(config.get_world_size_x(), 100.0)
.abs()
.max(1.0);
let size_z: f32 = sanitize_scalar(config.get_world_size_z(), 100.0)
.abs()
.max(1.0);
let h_scale: f32 = sanitize_scalar(config.get_height_scale(), 20.0)
.abs()
.max(0.1);
let freq: f32 = sanitize_scalar(config.get_fbm_frequency(), 2.0)
.abs()
.max(0.05);
let lac: f32 = sanitize_scalar(config.get_fbm_lacunarity(), 2.0).clamp(1.1, 4.0);
let pers: f32 = sanitize_scalar(config.get_fbm_persistence(), 0.5).clamp(0.1, 0.9);
let ridge_w: f32 = sanitize_scalar(config.get_ridged_weight(), 0.4).clamp(0.0, 1.0);
let canyon_w: f32 = sanitize_scalar(config.get_canyon_weight(), 0.1).clamp(0.0, 1.0);
let octaves: u32 = config.get_fbm_octaves().clamp(1, TERRAIN_MAX_OCTAVES);
let seed: u64 = config.get_seed();
let total_cells: usize = (gx as usize) * (gz as usize);
let mut heights: Vec<f32> = Vec::with_capacity(total_cells);
for iz in 0..gz {
let v: f32 = (iz as f32) / ((gz - 1) as f32);
for ix in 0..gx {
let u: f32 = (ix as f32) / ((gx - 1) as f32);
let nx: f32 = u * freq;
let nz: f32 = v * freq;
let fbm_val: f32 = fbm_2d(nx, nz, octaves, lac, pers, seed) * 0.5 + 0.5;
let ridge_val: f32 =
ridged_multifractal_2d(nx * 0.85, nz * 0.85, octaves, lac, pers, seed);
let base_h: f32 = fbm_val * (1.0 - ridge_w) + ridge_val * ridge_w;
let canyon_mask: f32 =
worley_canyon_2d(nx * 1.15, nz * 1.15, seed.wrapping_add(7919));
let carved_h: f32 = base_h * (1.0 - canyon_w * (1.0 - canyon_mask));
let biome_shaped: f32 = match config.get_biome() {
TerrainBiome::Archipelago => {
let dx: f32 = (u - 0.5) * 2.0;
let dz: f32 = (v - 0.5) * 2.0;
let radial: f32 = (dx * dx + dz * dz).sqrt();
let falloff: f32 = (1.0 - (radial * 0.95).powi(2)).clamp(0.0, 1.0);
carved_h * falloff
}
TerrainBiome::Canyon => (carved_h * 1.15).clamp(0.0, 1.0),
TerrainBiome::Alpine => carved_h.powf(1.25),
TerrainBiome::TerracedHighlands => carved_h,
};
let terraced: f32 = apply_terracing(
biome_shaped,
config.get_terrace_steps(),
config.get_terrace_strength(),
);
let elev: f32 = sanitize_scalar(terraced * h_scale, 0.0);
heights.push(elev);
}
}
let mut terrain: Self = Self {
grid_x: gx,
grid_z: gz,
world_size_x: size_x,
world_size_z: size_z,
heights,
splat_weights: vec![[1.0, 0.0, 0.0, 0.0]; total_cells],
vertex_colors: vec![[128, 160, 100, 255]; total_cells],
normal_map: vec![[128, 255, 128, 255]; total_cells],
min_height: 0.0,
max_height: h_scale,
};
if config.get_hydraulic_droplets() > 0 {
terrain
.apply_hydraulic_erosion(config.get_hydraulic_droplets(), seed.wrapping_add(31337));
}
if config.get_thermal_iterations() > 0 {
terrain
.apply_thermal_erosion(config.get_thermal_iterations(), config.get_talus_angle());
}
terrain.recompute_surface_maps(config.get_biome());
terrain
}
pub fn apply_hydraulic_erosion(&mut self, droplets: u32, seed: u64) {
let gx: usize = self.get_grid_x() as usize;
let gz: usize = self.get_grid_z() as usize;
if gx.min(gz) < 4 || droplets == 0 {
return;
}
let brush: [(i32, i32, f32); 9] = [
(-1, -1, 0.0625),
(0, -1, 0.125),
(1, -1, 0.0625),
(-1, 0, 0.125),
(0, 0, 0.25),
(1, 0, 0.125),
(-1, 1, 0.0625),
(0, 1, 0.125),
(1, 1, 0.0625),
];
let mut rng: u64 = seed ^ 0xA5A5_5A5A_1234_5678;
let max_x: f32 = (gx - 2) as f32;
let max_z: f32 = (gz - 2) as f32;
let heights: &mut Vec<f32> = self.get_mut_heights();
for _ in 0..droplets {
let mut px: f32 = 1.0 + terrain_next_f32(&mut rng) * (max_x - 1.0);
let mut pz: f32 = 1.0 + terrain_next_f32(&mut rng) * (max_z - 1.0);
let mut dir_x: f32 = 0.0;
let mut dir_z: f32 = 0.0;
let mut speed: f32 = 1.0;
let mut water: f32 = 1.0;
let mut sediment: f32 = 0.0;
for _ in 0..TERRAIN_DROPLET_MAX_STEPS {
let ix: usize = (px.floor() as usize).clamp(0, gx - 2);
let iz: usize = (pz.floor() as usize).clamp(0, gz - 2);
let tx: f32 = (px - (ix as f32)).clamp(0.0, 1.0);
let tz: f32 = (pz - (iz as f32)).clamp(0.0, 1.0);
let idx00: usize = iz * gx + ix;
let h00: f32 = heights[idx00];
let h10: f32 = heights[idx00 + 1];
let h01: f32 = heights[idx00 + gx];
let h11: f32 = heights[idx00 + gx + 1];
let grad_x: f32 = (h10 - h00) * (1.0 - tz) + (h11 - h01) * tz;
let grad_z: f32 = (h01 - h00) * (1.0 - tx) + (h11 - h10) * tx;
let old_h: f32 =
(h00 * (1.0 - tx) + h10 * tx) * (1.0 - tz) + (h01 * (1.0 - tx) + h11 * tx) * tz;
dir_x = dir_x * TERRAIN_INERTIA - grad_x * (1.0 - TERRAIN_INERTIA);
dir_z = dir_z * TERRAIN_INERTIA - grad_z * (1.0 - TERRAIN_INERTIA);
let dlen: f32 = (dir_x * dir_x + dir_z * dir_z).sqrt();
if dlen <= 1e-6 || !dlen.is_finite() {
break;
}
dir_x /= dlen;
dir_z /= dlen;
let next_x: f32 = px + dir_x;
let next_z: f32 = pz + dir_z;
let out_x: bool = next_x < 1.0 || next_x >= max_x;
let out_z: bool = next_z < 1.0 || next_z >= max_z;
if out_x || out_z {
break;
}
let nix: usize = (next_x.floor() as usize).clamp(0, gx - 2);
let niz: usize = (next_z.floor() as usize).clamp(0, gz - 2);
let ntx: f32 = (next_x - (nix as f32)).clamp(0.0, 1.0);
let ntz: f32 = (next_z - (niz as f32)).clamp(0.0, 1.0);
let nidx: usize = niz * gx + nix;
let new_h: f32 = (heights[nidx] * (1.0 - ntx) + heights[nidx + 1] * ntx)
* (1.0 - ntz)
+ (heights[nidx + gx] * (1.0 - ntx) + heights[nidx + gx + 1] * ntx) * ntz;
let dh: f32 = new_h - old_h;
let capacity: f32 =
((-dh).max(TERRAIN_MIN_SLOPE) * speed * water * TERRAIN_CAPACITY_FACTOR)
.clamp(0.0, 20.0);
if sediment > capacity || dh > 0.0 {
let deposit: f32 = if dh > 0.0 {
dh.min(sediment)
} else {
(sediment - capacity) * TERRAIN_DEPOSITION_RATE
};
let clean_dep: f32 = sanitize_scalar(deposit, 0.0).max(0.0);
sediment = (sediment - clean_dep).max(0.0);
heights[idx00] = sanitize_scalar(
heights[idx00] + clean_dep * (1.0 - tx) * (1.0 - tz),
old_h,
);
heights[idx00 + 1] =
sanitize_scalar(heights[idx00 + 1] + clean_dep * tx * (1.0 - tz), old_h);
heights[idx00 + gx] =
sanitize_scalar(heights[idx00 + gx] + clean_dep * (1.0 - tx) * tz, old_h);
heights[idx00 + gx + 1] =
sanitize_scalar(heights[idx00 + gx + 1] + clean_dep * tx * tz, old_h);
} else {
let erode: f32 =
((capacity - sediment) * TERRAIN_EROSION_RATE).min((-dh).max(0.0));
let clean_erode: f32 = sanitize_scalar(erode, 0.0).clamp(0.0, 2.0);
let mut actual_eroded: f32 = 0.0;
for &(ox, oz, w) in brush.iter() {
let bx: i32 = (ix as i32) + ox;
let bz: i32 = (iz as i32) + oz;
if bx >= 0 && bx < (gx as i32) && bz >= 0 && bz < (gz as i32) {
let bidx: usize = (bz as usize) * gx + (bx as usize);
let delta: f32 = clean_erode * w;
heights[bidx] = sanitize_scalar(heights[bidx] - delta, 0.0);
actual_eroded += delta;
}
}
sediment += actual_eroded;
}
let speed_sq: f32 = (speed * speed + (-dh) * TERRAIN_GRAVITY).clamp(0.0025, 64.0);
speed = speed_sq.sqrt();
water *= 1.0 - TERRAIN_EVAPORATION_RATE;
px = next_x;
pz = next_z;
if water < 0.02 {
break;
}
}
}
}
pub fn apply_thermal_erosion(&mut self, iterations: u32, talus_angle: f32) {
let gx: usize = self.get_grid_x() as usize;
let gz: usize = self.get_grid_z() as usize;
if gx.min(gz) < 3 || iterations == 0 {
return;
}
let step_x: f32 = self.get_world_size_x() / ((gx - 1) as f32);
let step_z: f32 = self.get_world_size_z() / ((gz - 1) as f32);
let avg_step: f32 = (step_x + step_z) * 0.5;
let angle: f32 = sanitize_scalar(talus_angle, 0.6).clamp(0.1, 1.45);
let talus_h: f32 = avg_step * angle.tan();
let neighbors: [(i32, i32, f32); 8] = [
(-1, 0, 1.0),
(1, 0, 1.0),
(0, -1, 1.0),
(0, 1, 1.0),
(-1, -1, SQRT_2),
(1, -1, SQRT_2),
(-1, 1, SQRT_2),
(1, 1, SQRT_2),
];
let mut deltas: Vec<f32> = vec![0.0; gx * gz];
let heights: &mut Vec<f32> = self.get_mut_heights();
for _ in 0..iterations {
deltas.fill(0.0);
for iz in 0..gz {
for ix in 0..gx {
let idx: usize = iz * gx + ix;
let h: f32 = heights[idx];
let mut excess_sum: f32 = 0.0;
let mut max_diff: f32 = 0.0;
let mut local_excess: [f32; 8] = [0.0; 8];
for (k, &(ox, oz, dist_mul)) in neighbors.iter().enumerate() {
let nx: i32 = (ix as i32) + ox;
let nz: i32 = (iz as i32) + oz;
if nx >= 0 && nx < (gx as i32) && nz >= 0 && nz < (gz as i32) {
let nidx: usize = (nz as usize) * gx + (nx as usize);
let diff: f32 = h - heights[nidx];
let thresh: f32 = talus_h * dist_mul;
if diff > thresh {
let exc: f32 = diff - thresh;
local_excess[k] = exc;
excess_sum += exc;
if exc > max_diff {
max_diff = exc;
}
}
}
}
if excess_sum > 1e-6 {
let transfer: f32 = 0.45 * max_diff;
deltas[idx] -= transfer;
for (k, &(ox, oz, _)) in neighbors.iter().enumerate() {
if local_excess[k] > 0.0 {
let nx: usize = ((ix as i32) + ox) as usize;
let nz: usize = ((iz as i32) + oz) as usize;
deltas[nz * gx + nx] += transfer * (local_excess[k] / excess_sum);
}
}
}
}
}
for (h_slot, &d) in heights.iter_mut().zip(deltas.iter()) {
*h_slot = sanitize_scalar(*h_slot + d, 0.0);
}
}
}
pub fn recompute_surface_maps(&mut self, biome: TerrainBiome) {
let gx: usize = self.get_grid_x() as usize;
let gz: usize = self.get_grid_z() as usize;
let step_x: f32 = self.get_world_size_x() / ((gx.max(2) - 1) as f32);
let step_z: f32 = self.get_world_size_z() / ((gz.max(2) - 1) as f32);
let mut min_h: f32 = f32::INFINITY;
let mut max_h: f32 = f32::NEG_INFINITY;
for &h in self.get_heights().iter() {
let clean: f32 = sanitize_scalar(h, 0.0);
min_h = min_h.min(clean);
max_h = max_h.max(clean);
}
if !min_h.is_finite() || !max_h.is_finite() {
min_h = 0.0;
max_h = 1.0;
}
let span: f32 = (max_h - min_h).max(1e-4);
let total: usize = gx * gz;
let mut splats: Vec<[f32; 4]> = Vec::with_capacity(total);
let mut colors: Vec<[u8; 4]> = Vec::with_capacity(total);
let mut nmap: Vec<[u8; 4]> = Vec::with_capacity(total);
let heights_ref: &[f32] = self.get_heights();
for iz in 0..gz {
let z_prev: usize = iz.saturating_sub(1);
let z_next: usize = (iz + 1).min(gz - 1);
let dz: f32 = ((z_next - z_prev).max(1) as f32) * step_z;
for ix in 0..gx {
let x_prev: usize = ix.saturating_sub(1);
let x_next: usize = (ix + 1).min(gx - 1);
let dx: f32 = ((x_next - x_prev).max(1) as f32) * step_x;
let h: f32 = heights_ref[iz * gx + ix];
let hx0: f32 = heights_ref[iz * gx + x_prev];
let hx1: f32 = heights_ref[iz * gx + x_next];
let hz0: f32 = heights_ref[z_prev * gx + ix];
let hz1: f32 = heights_ref[z_next * gx + ix];
let n: Vec3 =
safe_unit_normal(Vec3::new(-(hx1 - hx0) / dx, 1.0, -(hz1 - hz0) / dz));
nmap.push([
((n.get_x() * 0.5 + 0.5) * 255.0).round().clamp(0.0, 255.0) as u8,
((n.get_y() * 0.5 + 0.5) * 255.0).round().clamp(0.0, 255.0) as u8,
((n.get_z() * 0.5 + 0.5) * 255.0).round().clamp(0.0, 255.0) as u8,
255,
]);
let alt: f32 = ((h - min_h) / span).clamp(0.0, 1.0);
let slope: f32 = (1.0 - n.get_y()).clamp(0.0, 1.0);
let mut w_sand: f32 = ((0.22 - alt) * 4.5).clamp(0.0, 1.0);
let mut w_snow: f32 = ((alt - 0.72) * 3.8 * (1.0 - slope * 1.4)).clamp(0.0, 1.0);
let mut w_rock: f32 = ((slope - 0.14) * 3.5).clamp(0.0, 1.0);
let mut w_grass: f32 = (1.0 - w_rock - w_snow - w_sand).clamp(0.0, 1.0);
if matches!(biome, TerrainBiome::Canyon) {
w_sand = (w_sand + 0.45 * (1.0 - slope)).clamp(0.0, 1.0);
w_rock = (w_rock + 0.45 * slope).clamp(0.0, 1.0);
w_snow *= 0.05;
w_grass *= 0.15;
}
let w_sum: f32 = (w_grass + w_rock + w_snow + w_sand).max(1e-5);
let sw: [f32; 4] = [
w_grass / w_sum,
w_rock / w_sum,
w_snow / w_sum,
w_sand / w_sum,
];
splats.push(sw);
let (c_grass, c_rock, c_snow, c_sand): ([f32; 3], [f32; 3], [f32; 3], [f32; 3]) =
match biome {
TerrainBiome::Canyon => (
[138.0, 122.0, 74.0],
[168.0, 92.0, 56.0],
[228.0, 198.0, 162.0],
[208.0, 146.0, 88.0],
),
TerrainBiome::Archipelago => (
[74.0, 148.0, 72.0],
[112.0, 114.0, 118.0],
[235.0, 240.0, 244.0],
[226.0, 206.0, 152.0],
),
TerrainBiome::TerracedHighlands => (
[86.0, 138.0, 68.0],
[124.0, 116.0, 108.0],
[226.0, 232.0, 236.0],
[174.0, 152.0, 112.0],
),
TerrainBiome::Alpine => (
[76.0, 132.0, 66.0],
[118.0, 116.0, 114.0],
[242.0, 246.0, 250.0],
[184.0, 164.0, 122.0],
),
};
let rgb_r: f32 =
c_grass[0] * sw[0] + c_rock[0] * sw[1] + c_snow[0] * sw[2] + c_sand[0] * sw[3];
let rgb_g: f32 =
c_grass[1] * sw[0] + c_rock[1] * sw[1] + c_snow[1] * sw[2] + c_sand[1] * sw[3];
let rgb_b: f32 =
c_grass[2] * sw[0] + c_rock[2] * sw[1] + c_snow[2] * sw[2] + c_sand[2] * sw[3];
colors.push([
rgb_r.round().clamp(0.0, 255.0) as u8,
rgb_g.round().clamp(0.0, 255.0) as u8,
rgb_b.round().clamp(0.0, 255.0) as u8,
255,
]);
}
}
self.set_min_height(min_h);
self.set_max_height(max_h);
self.set_splat_weights(splats);
self.set_vertex_colors(colors);
self.set_normal_map(nmap);
}
#[must_use]
pub fn sample_height(&self, world_x: f32, world_z: f32) -> f32 {
let gx: usize = self.get_grid_x() as usize;
let gz: usize = self.get_grid_z() as usize;
let heights: &[f32] = self.get_heights();
if gx.min(gz) < 2 || heights.len() < gx * gz {
return 0.0;
}
let u: f32 =
(sanitize_scalar(world_x, 0.0) / self.get_world_size_x() + 0.5).clamp(0.0, 1.0);
let v: f32 =
(sanitize_scalar(world_z, 0.0) / self.get_world_size_z() + 0.5).clamp(0.0, 1.0);
let fx: f32 = u * ((gx - 1) as f32);
let fz: f32 = v * ((gz - 1) as f32);
let ix: usize = (fx.floor() as usize).min(gx - 2);
let iz: usize = (fz.floor() as usize).min(gz - 2);
let tx: f32 = (fx - (ix as f32)).clamp(0.0, 1.0);
let tz: f32 = (fz - (iz as f32)).clamp(0.0, 1.0);
let base: usize = iz * gx + ix;
let h00: f32 = heights[base];
let h10: f32 = heights[base + 1];
let h01: f32 = heights[base + gx];
let h11: f32 = heights[base + gx + 1];
let hx0: f32 = h00 + (h10 - h00) * tx;
let hx1: f32 = h01 + (h11 - h01) * tx;
sanitize_scalar(hx0 + (hx1 - hx0) * tz, 0.0)
}
#[must_use]
pub fn sample_normal(&self, world_x: f32, world_z: f32) -> Vec3 {
let gx: usize = self.get_grid_x() as usize;
let gz: usize = self.get_grid_z() as usize;
let heights: &[f32] = self.get_heights();
if gx.min(gz) < 2 || heights.len() < gx * gz {
return Vec3::new(0.0, 1.0, 0.0);
}
let step_x: f32 = self.get_world_size_x() / ((gx - 1) as f32);
let step_z: f32 = self.get_world_size_z() / ((gz - 1) as f32);
let u: f32 =
(sanitize_scalar(world_x, 0.0) / self.get_world_size_x() + 0.5).clamp(0.0, 1.0);
let v: f32 =
(sanitize_scalar(world_z, 0.0) / self.get_world_size_z() + 0.5).clamp(0.0, 1.0);
let fx: f32 = u * ((gx - 1) as f32);
let fz: f32 = v * ((gz - 1) as f32);
let ix: usize = (fx.floor() as usize).min(gx - 2);
let iz: usize = (fz.floor() as usize).min(gz - 2);
let tx: f32 = (fx - (ix as f32)).clamp(0.0, 1.0);
let tz: f32 = (fz - (iz as f32)).clamp(0.0, 1.0);
let base: usize = iz * gx + ix;
let h00: f32 = heights[base];
let h10: f32 = heights[base + 1];
let h01: f32 = heights[base + gx];
let h11: f32 = heights[base + gx + 1];
let dh_dx: f32 = ((h10 - h00) * (1.0 - tz) + (h11 - h01) * tz) / step_x.max(1e-4);
let dh_dz: f32 = ((h01 - h00) * (1.0 - tx) + (h11 - h10) * tx) / step_z.max(1e-4);
safe_unit_normal(Vec3::new(-dh_dx, 1.0, -dh_dz))
}
#[must_use]
pub fn sample_splat_weights(&self, world_x: f32, world_z: f32) -> [f32; 4] {
let gx: usize = self.get_grid_x() as usize;
let gz: usize = self.get_grid_z() as usize;
let splats: &[[f32; 4]] = self.get_splat_weights();
if gx.min(gz) < 2 || splats.len() < gx * gz {
return [1.0, 0.0, 0.0, 0.0];
}
let u: f32 =
(sanitize_scalar(world_x, 0.0) / self.get_world_size_x() + 0.5).clamp(0.0, 1.0);
let v: f32 =
(sanitize_scalar(world_z, 0.0) / self.get_world_size_z() + 0.5).clamp(0.0, 1.0);
let fx: f32 = u * ((gx - 1) as f32);
let fz: f32 = v * ((gz - 1) as f32);
let ix: usize = (fx.floor() as usize).min(gx - 2);
let iz: usize = (fz.floor() as usize).min(gz - 2);
let tx: f32 = (fx - (ix as f32)).clamp(0.0, 1.0);
let tz: f32 = (fz - (iz as f32)).clamp(0.0, 1.0);
let base: usize = iz * gx + ix;
let s00: [f32; 4] = splats[base];
let s10: [f32; 4] = splats[base + 1];
let s01: [f32; 4] = splats[base + gx];
let s11: [f32; 4] = splats[base + gx + 1];
let mut out: [f32; 4] = [0.0; 4];
let mut sum: f32 = 0.0;
for c in 0..4 {
let v0: f32 = s00[c] + (s10[c] - s00[c]) * tx;
let v1: f32 = s01[c] + (s11[c] - s01[c]) * tx;
out[c] = (v0 + (v1 - v0) * tz).max(0.0);
sum += out[c];
}
if sum > 1e-6 {
[out[0] / sum, out[1] / sum, out[2] / sum, out[3] / sum]
} else {
[1.0, 0.0, 0.0, 0.0]
}
}
#[must_use]
pub fn to_mesh3d(&self, name: &str, material: PbrMaterial) -> Mesh3D {
let gx: usize = self.get_grid_x() as usize;
let gz: usize = self.get_grid_z() as usize;
let mesh_name: String = if name.is_empty() {
TERRAIN_DEFAULT_NAME.to_string()
} else {
name.to_string()
};
if gx < 2 || gz < 2 {
return Mesh3D::from_parts(mesh_name, Vec::new(), Vec::new(), material);
}
let size_x: f32 = self.get_world_size_x();
let size_z: f32 = self.get_world_size_z();
let heights: &[f32] = self.get_heights();
let colors: &[[u8; 4]] = self.get_vertex_colors();
let nmap: &[[u8; 4]] = self.get_normal_map();
let mut vertices: Vec<Vertex3D> = Vec::with_capacity(gx * gz);
let mut indices: Vec<[u32; 3]> = Vec::with_capacity((gx - 1) * (gz - 1) * 2);
let uv_flags: u32 = VERTEX_FLAG_UV0 | VERTEX_FLAG_UV1;
let flags: u32 = uv_flags | VERTEX_FLAG_COLOR0;
for iz in 0..gz {
let v: f32 = (iz as f32) / ((gz - 1) as f32);
let wz: f32 = (v - 0.5) * size_z;
for ix in 0..gx {
let u: f32 = (ix as f32) / ((gx - 1) as f32);
let wx: f32 = (u - 0.5) * size_x;
let idx: usize = iz * gx + ix;
let wy: f32 = heights.get(idx).copied().unwrap_or(0.0);
let nc: [u8; 4] = nmap.get(idx).copied().unwrap_or([128, 255, 128, 255]);
let normal: Vec3 = safe_unit_normal(Vec3::new(
(nc[0] as f32) / 127.5 - 1.0,
(nc[1] as f32) / 127.5 - 1.0,
(nc[2] as f32) / 127.5 - 1.0,
));
let col: [u8; 4] = colors.get(idx).copied().unwrap_or([128, 160, 100, 255]);
vertices.push(Vertex3D::from_full(
Vec3::new(wx, wy, wz),
normal,
[1.0, 0.0, 0.0, 1.0],
[u, v],
[u * 8.0, v * 8.0],
col,
flags,
));
}
}
for iz in 0..(gz - 1) {
let row0: u32 = (iz * gx) as u32;
let row1: u32 = ((iz + 1) * gx) as u32;
for ix in 0..(gx - 1) {
let jx: u32 = ix as u32;
let i00: u32 = row0 + jx;
let i10: u32 = row0 + jx + 1;
let i01: u32 = row1 + jx;
let i11: u32 = row1 + jx + 1;
indices.push([i00, i01, i10]);
indices.push([i01, i11, i10]);
}
}
let mesh: Mesh3D = Mesh3D::from_parts(mesh_name, vertices, indices, material);
compute_tangents(&mesh)
}
}