use std::sync::Arc;
use crate::textures::{Texture, TextureFormat, TextureWrap};
pub struct MapBuffer {
pub width: u32,
pub height: u32,
pub data: Vec<u8>,
}
impl MapBuffer {
fn new(width: u32, height: u32) -> Self {
Self {
width,
height,
data: vec![0; (width as usize) * (height as usize) * 4],
}
}
pub fn into_texture(self, format: TextureFormat) -> Texture {
let mut t = Texture::new(self.width, self.height, format, self.data);
t.wrap_s = TextureWrap::Repeat;
t.wrap_t = TextureWrap::ClampToEdge;
t
}
}
fn hash3(x: i32, y: i32, z: i32, seed: i32) -> f32 {
let mut h = (x as u32).wrapping_mul(374_761_393)
^ (y as u32).wrapping_mul(668_265_263)
^ (z as u32).wrapping_mul(2_246_822_519)
^ (seed as u32).wrapping_mul(1_274_126_177);
h ^= h >> 13;
h = h.wrapping_mul(1_274_126_177);
h ^= h >> 16;
h as f32 / u32::MAX as f32
}
fn smooth(t: f32) -> f32 {
t * t * (3.0 - 2.0 * t)
}
pub fn value_noise(p: [f32; 3], seed: i32) -> f32 {
let i = [p[0].floor(), p[1].floor(), p[2].floor()];
let f = [
smooth(p[0] - i[0]),
smooth(p[1] - i[1]),
smooth(p[2] - i[2]),
];
let (xi, yi, zi) = (i[0] as i32, i[1] as i32, i[2] as i32);
let corner = |dx, dy, dz| hash3(xi + dx, yi + dy, zi + dz, seed);
let lerp = |a: f32, b: f32, t: f32| a + (b - a) * t;
let x00 = lerp(corner(0, 0, 0), corner(1, 0, 0), f[0]);
let x10 = lerp(corner(0, 1, 0), corner(1, 1, 0), f[0]);
let x01 = lerp(corner(0, 0, 1), corner(1, 0, 1), f[0]);
let x11 = lerp(corner(0, 1, 1), corner(1, 1, 1), f[0]);
lerp(lerp(x00, x10, f[1]), lerp(x01, x11, f[1]), f[2])
}
fn scaled(p: [f32; 3], k: f32) -> [f32; 3] {
[p[0] * k, p[1] * k, p[2] * k]
}
pub fn fbm(p: [f32; 3], frequency: f32, octaves: u32, seed: i32) -> f32 {
let (mut sum, mut amp, mut norm, mut freq) = (0.0, 0.5, 0.0, frequency);
for o in 0..octaves {
sum += value_noise(scaled(p, freq), seed + o as i32 * 977) * amp;
norm += amp;
amp *= 0.5;
freq *= 2.0;
}
sum / norm.max(1e-6)
}
pub fn ridged(p: [f32; 3], frequency: f32, octaves: u32, seed: i32) -> f32 {
let (mut sum, mut amp, mut norm, mut freq) = (0.0, 0.5, 0.0, frequency);
for o in 0..octaves {
let n = value_noise(scaled(p, freq), seed + o as i32 * 313) * 2.0 - 1.0;
sum += (1.0 - n.abs()) * amp;
norm += amp;
amp *= 0.5;
freq *= 2.0;
}
sum / norm.max(1e-6)
}
pub fn direction(u: f32, v: f32) -> [f32; 3] {
let lon = std::f32::consts::PI - u * std::f32::consts::TAU;
let lat = (0.5 - v) * std::f32::consts::PI;
let (cl, sl) = (lat.cos(), lat.sin());
[cl * lon.cos(), sl, cl * lon.sin()]
}
fn fill_rows<T: Send>(
#[cfg_attr(target_arch = "wasm32", allow(unused_variables))] height: u32,
stride: usize,
out: &mut [T],
f: impl Fn(u32, &mut [T]) + Sync,
) {
#[cfg(not(target_arch = "wasm32"))]
{
let threads = std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(1)
.min(height.max(1) as usize)
.max(1);
let rows_per = (height as usize).div_ceil(threads);
let f = &f;
std::thread::scope(|scope| {
for (band, chunk) in out.chunks_mut(rows_per * stride).enumerate() {
scope.spawn(move || {
for (i, row) in chunk.chunks_mut(stride).enumerate() {
f((band * rows_per + i) as u32, row);
}
});
}
});
}
#[cfg(target_arch = "wasm32")]
for (y, row) in out.chunks_mut(stride).enumerate() {
f(y as u32, row);
}
}
pub struct HeightField {
pub width: u32,
pub height: u32,
pub values: Vec<f32>,
}
impl HeightField {
pub fn from_texture(texture: &Texture) -> Self {
let (w, h) = (texture.width.max(1), texture.height.max(1));
let bpp = texture.bytes_per_pixel().max(1);
let mut values = vec![0.0f32; (w as usize) * (h as usize)];
for (i, v) in values.iter_mut().enumerate() {
let o = i * bpp;
*v = texture.data.get(o).copied().unwrap_or(0) as f32 / 255.0;
}
Self {
width: w,
height: h,
values,
}
}
fn at(&self, x: isize, y: isize) -> f32 {
let w = self.width as isize;
let h = self.height as isize;
let xi = x.rem_euclid(w) as usize;
let yi = y.clamp(0, h - 1) as usize;
self.values[yi * self.width as usize + xi]
}
pub fn to_normal_map(&self, strength: f32) -> Texture {
let (w, h) = (self.width, self.height);
let mut buf = MapBuffer::new(w, h);
let hf = self;
fill_rows(h, w as usize * 4, &mut buf.data, |y, row| {
let v = (y as f32 + 0.5) / h as f32;
let scale = 1.0 / ((v - 0.5) * std::f32::consts::PI).cos().max(0.2);
for x in 0..w as usize {
let (xi, yi) = (x as isize, y as isize);
let dx = (hf.at(xi + 1, yi) - hf.at(xi - 1, yi)) * 0.5 * scale * strength;
let dy = (hf.at(xi, yi + 1) - hf.at(xi, yi - 1)) * 0.5 * strength;
let len = (dx * dx + dy * dy + 1.0).sqrt();
let o = x * 4;
row[o] = ((-dx / len * 0.5 + 0.5) * 255.0).clamp(0.0, 255.0) as u8;
row[o + 1] = ((-dy / len * 0.5 + 0.5) * 255.0).clamp(0.0, 255.0) as u8;
row[o + 2] = ((1.0 / len * 0.5 + 0.5) * 255.0).clamp(0.0, 255.0) as u8;
row[o + 3] = 255;
}
});
buf.into_texture(TextureFormat::Rgba8Unorm)
}
pub fn to_height_map(&self, sea_level: f32) -> Texture {
let (w, h) = (self.width, self.height);
let mut buf = MapBuffer::new(w, h);
let hf = self;
let span = (1.0 - sea_level).max(1e-4);
fill_rows(h, w as usize * 4, &mut buf.data, |y, row| {
for x in 0..w as usize {
let e = hf.values[y as usize * w as usize + x];
let v = (((e - sea_level) / span).clamp(0.0, 1.0) * 255.0) as u8;
let o = x * 4;
row[o] = v;
row[o + 1] = v;
row[o + 2] = v;
row[o + 3] = 255;
}
});
buf.into_texture(TextureFormat::Rgba8Unorm)
}
pub fn range(&self) -> (f32, f32) {
self.values
.iter()
.fold((f32::MAX, f32::MIN), |(lo, hi), &v| (lo.min(v), hi.max(v)))
}
pub fn to_height_map_normalized(&self) -> Texture {
let (lo, hi) = self.range();
let span = (hi - lo).max(1e-6);
let (w, h) = (self.width, self.height);
let mut buf = MapBuffer::new(w, h);
let hf = self;
fill_rows(h, w as usize * 4, &mut buf.data, |y, row| {
for x in 0..w as usize {
let e = hf.values[y as usize * w as usize + x];
let v = (((e - lo) / span).clamp(0.0, 1.0) * 255.0) as u8;
let o = x * 4;
row[o] = v;
row[o + 1] = v;
row[o + 2] = v;
row[o + 3] = 255;
}
});
buf.into_texture(TextureFormat::Rgba8Unorm)
}
pub fn to_roughness_map(&self, sea_level: f32, water: f32, land: f32) -> Texture {
let (w, h) = (self.width, self.height);
let mut buf = MapBuffer::new(w, h);
let hf = self;
fill_rows(h, w as usize * 4, &mut buf.data, |y, row| {
for x in 0..w as usize {
let e = hf.values[y as usize * w as usize + x];
let r = if e <= sea_level { water } else { land };
let v = (r.clamp(0.0, 1.0) * 255.0) as u8;
let o = x * 4;
row[o] = v;
row[o + 1] = v;
row[o + 2] = v;
row[o + 3] = 255;
}
});
buf.into_texture(TextureFormat::Rgba8Unorm)
}
pub fn to_roughness_map_with_ice(
&self,
albedo: &Texture,
sea_level: f32,
water: f32,
land: f32,
ice: f32,
) -> Texture {
let (w, h) = (self.width, self.height);
let (aw, ah) = (albedo.width.max(1), albedo.height.max(1));
let abpp = albedo.bytes_per_pixel().max(1);
if albedo.data.len() < (aw as usize) * (ah as usize) * abpp {
return self.to_roughness_map(sea_level, water, land);
}
let mut buf = MapBuffer::new(w, h);
let hf = self;
fill_rows(h, w as usize * 4, &mut buf.data, |y, row| {
let ay = ((y as usize) * ah as usize / h.max(1) as usize).min(ah as usize - 1);
for x in 0..w as usize {
let ax = (x * aw as usize / w.max(1) as usize).min(aw as usize - 1);
let ao = (ay * aw as usize + ax) * abpp;
let (r, g, b) = (
albedo.data[ao] as f32 / 255.0,
albedo.data[ao + 1] as f32 / 255.0,
albedo.data[ao + 2] as f32 / 255.0,
);
let luma = 0.2126 * r + 0.7152 * g + 0.0722 * b;
let chroma = (r - b).abs().max((g - b).abs()).max((r - g).abs());
let e = hf.values[y as usize * w as usize + x];
let rough = if e <= sea_level {
water
} else if luma > 0.62 && chroma < 0.10 {
ice
} else {
land
};
let v = (rough.clamp(0.0, 1.0) * 255.0) as u8;
let o = x * 4;
row[o] = v;
row[o + 1] = v;
row[o + 2] = v;
row[o + 3] = 255;
}
});
buf.into_texture(TextureFormat::Rgba8Unorm)
}
}
fn elevation(p: [f32; 3]) -> f32 {
let continents = fbm(p, 1.5, 8, 11);
let warp = fbm(p, 4.3, 4, 71) - 0.5;
let mass = continents + warp * 0.22;
let land = mass - 0.545;
if land <= 0.0 {
let floor = fbm(p, 6.0, 4, 401);
return (land * 2.4 - floor * 0.10).max(-1.0);
}
let mountains = ridged(p, 7.5, 5, 907);
let relief = fbm(p, 18.0, 4, 55);
((land * 3.0) + mountains * mountains * 0.6 * (land * 7.0).min(1.0) + relief * 0.07).min(1.0)
}
pub fn blend_polar_cap(base: &mut Texture, cap: &Texture, from_lat: f32, to_lat: f32) {
blend_polar_cap_in(base, (-180.0, 180.0, -90.0, 90.0), cap, from_lat, to_lat)
}
pub fn blend_polar_cap_in(
base: &mut Texture,
bounds: (f32, f32, f32, f32),
cap: &Texture,
from_lat: f32,
to_lat: f32,
) {
let (bw_deg, be_deg, bs_deg, bn_deg) = bounds;
let (w, h) = (base.width as usize, base.height as usize);
let (cw, ch) = (cap.width as usize, cap.height as usize);
let bpp = base.bytes_per_pixel();
let cbpp = cap.bytes_per_pixel();
if w < 2 || h < 2 || cw < 2 || ch < 2 || bpp < 3 || cbpp < 3 {
return;
}
if base.data.len() != w * h * bpp || cap.data.len() != cw * ch * cbpp {
return;
}
let to_linear = |b: u8| {
let v = b as f32 / 255.0;
if v <= 0.04045 {
v / 12.92
} else {
((v + 0.055) / 1.055).powf(2.4)
}
};
let to_srgb = |v: f32| {
let v = v.clamp(0.0, 1.0);
let e = if v <= 0.0031308 {
v * 12.92
} else {
1.055 * v.powf(1.0 / 2.4) - 0.055
};
(e * 255.0).round() as u8
};
if (to_lat - from_lat).abs() < 1e-6 {
return;
}
let data = Arc::make_mut(&mut base.data);
for y in 0..h {
let lat = bn_deg - (y as f32 + 0.5) / h as f32 * (bn_deg - bs_deg);
let t = ((lat - from_lat) / (to_lat - from_lat)).clamp(0.0, 1.0);
let mix = t * t * (3.0 - 2.0 * t);
if mix <= 0.0 {
continue;
}
let cy = (((90.0 - lat) / 180.0) * ch as f32 - 0.5).clamp(0.0, ch as f32 - 1.0);
let (y0, fy) = (cy.floor() as usize, cy - cy.floor());
let y1 = (y0 + 1).min(ch - 1);
for x in 0..w {
let lon = bw_deg + (x as f32 + 0.5) / w as f32 * (be_deg - bw_deg);
let cx = (((lon + 180.0) / 360.0) * cw as f32 - 0.5).rem_euclid(cw as f32);
let (x0, fx) = (cx.floor() as usize % cw, cx - cx.floor());
let x1 = (x0 + 1) % cw;
let o = (y * w + x) * bpp;
for c in 0..3 {
let s = |xi: usize, yi: usize| to_linear(cap.data[(yi * cw + xi) * cbpp + c]);
let top = s(x0, y0) * (1.0 - fx) + s(x1, y0) * fx;
let bot = s(x0, y1) * (1.0 - fx) + s(x1, y1) * fx;
let capv = top * (1.0 - fy) + bot * fy;
let basev = to_linear(data[o + c]);
data[o + c] = to_srgb(basev + (capv - basev) * mix);
}
}
}
}
pub fn ease_poles(texture: &mut Texture) {
let (w, h) = (texture.width as usize, texture.height as usize);
let bpp = texture.bytes_per_pixel();
if w < 4 || h < 4 || texture.data.len() != w * h * bpp {
return;
}
let data = Arc::make_mut(&mut texture.data);
for y in 0..h {
let lat = (0.5 - (y as f32 + 0.5) / h as f32) * std::f32::consts::PI;
let cos = lat.cos().abs().max(1e-6);
let over = 1.0 / cos;
let t = ((over - 30.0) / 60.0).clamp(0.0, 1.0);
let flat = t * t * (3.0 - 2.0 * t);
if flat <= 0.001 {
continue;
}
let base = y * w * bpp;
for c in 0..bpp {
let mean: u32 = (0..w).map(|x| data[base + x * bpp + c] as u32).sum::<u32>() / w as u32;
for x in 0..w {
let v = data[base + x * bpp + c] as f32;
data[base + x * bpp + c] = (v + (mean as f32 - v) * flat) as u8;
}
}
}
}
#[derive(Clone, Default)]
pub struct PlanetMaps {
pub albedo: Option<Arc<Texture>>,
pub normal: Option<Arc<Texture>>,
pub roughness: Option<Arc<Texture>>,
pub night: Option<Arc<Texture>>,
pub clouds: Option<Arc<Texture>>,
pub displacement: Option<Arc<Texture>>,
}
impl std::fmt::Debug for PlanetMaps {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let size = |t: &Option<Arc<Texture>>| {
t.as_ref()
.map(|t| format!("{}x{}", t.width, t.height))
.unwrap_or_else(|| "-".into())
};
f.debug_struct("PlanetMaps")
.field("albedo", &size(&self.albedo))
.field("normal", &size(&self.normal))
.field("roughness", &size(&self.roughness))
.field("night", &size(&self.night))
.field("clouds", &size(&self.clouds))
.field("displacement", &size(&self.displacement))
.finish()
}
}
impl PlanetMaps {
pub fn new() -> Self {
Self::default()
}
pub fn albedo(mut self, texture: Texture) -> Self {
self.albedo = Some(Arc::new(texture));
self
}
pub fn normal(mut self, texture: Texture) -> Self {
self.normal = Some(Arc::new(texture));
self
}
pub fn roughness(mut self, texture: Texture) -> Self {
self.roughness = Some(Arc::new(texture));
self
}
pub fn night(mut self, texture: Texture) -> Self {
self.night = Some(Arc::new(texture));
self
}
pub fn clouds(mut self, texture: Texture) -> Self {
self.clouds = Some(Arc::new(texture));
self
}
pub fn displacement(mut self, texture: Texture) -> Self {
self.displacement = Some(Arc::new(texture));
self
}
pub fn is_empty(&self) -> bool {
self.slots().iter().all(|s| s.is_none())
}
pub fn is_complete(&self) -> bool {
self.slots().iter().all(|s| s.is_some())
}
fn slots(&self) -> [&Option<Arc<Texture>>; 5] {
[
&self.albedo,
&self.normal,
&self.roughness,
&self.night,
&self.clouds,
]
}
}
pub fn generate_earth_maps(width: u32) -> PlanetMaps {
use std::f32::consts::PI;
let width = width.clamp(16, 8192);
let height = (width / 2).max(8);
let (w, h) = (width as usize, height as usize);
let mut field = vec![0f32; w * h];
fill_rows(height, w, &mut field, |y, row| {
let v = (y as f32 + 0.5) / h as f32;
for (x, cell) in row.iter_mut().enumerate() {
*cell = elevation(direction((x as f32 + 0.5) / w as f32, v));
}
});
let hf = HeightField {
width,
height,
values: field.iter().map(|e| e * 0.5 + 0.5).collect(),
};
let mut albedo = MapBuffer::new(width, height);
fill_rows(height, w * 4, &mut albedo.data, |y, row| {
let v = (y as f32 + 0.5) / h as f32;
let lat = (v - 0.5) * PI;
let polar_base = (lat.abs() - 1.02) / 0.34;
for x in 0..w {
let u = (x as f32 + 0.5) / w as f32;
let d = direction(u, 1.0 - v);
let e = field[y as usize * w + x];
let polar = (polar_base + (fbm(d, 14.0, 3, 4242) - 0.5) * 0.55).clamp(0.0, 1.0);
let mut rgb = if e <= 0.0 {
let depth = (-e / 0.6).clamp(0.0, 1.0);
[
0.05 + (0.008 - 0.05) * depth,
0.30 + (0.035 - 0.30) * depth,
0.36 + (0.13 - 0.36) * depth,
]
} else {
let jitter = fbm(d, 9.0, 3, 1234);
let warmth = (1.0 - lat.abs() / 1.4).clamp(0.0, 1.0) + (jitter - 0.5) * 0.28;
let belt = (1.0 - (lat.abs() - 0.46).abs() / 0.30).clamp(0.0, 1.0);
let dryness = fbm(d, 5.5, 4, 6060);
let desert = (belt * 1.25 * (dryness - 0.34) * 3.0).clamp(0.0, 1.0);
let base = [
0.34 + (0.06 - 0.34) * warmth,
0.33 + (0.24 - 0.33) * warmth,
0.28 + (0.07 - 0.28) * warmth,
];
let green = [
base[0] * 0.5 + 0.045,
base[1] * 0.5 + 0.100,
base[2] * 0.5 + 0.040,
];
let land = [
green[0] + (0.62 - green[0]) * desert,
green[1] + (0.51 - green[1]) * desert,
green[2] + (0.31 - green[2]) * desert,
];
let snow_line = 0.78 - 0.62 * (lat.abs() / 1.5).powi(2);
let alpine = ((e - snow_line) / 0.14).clamp(0.0, 1.0);
let snow = polar.max(alpine);
[
land[0] + (0.92 - land[0]) * snow,
land[1] + (0.94 - land[1]) * snow,
land[2] + (0.97 - land[2]) * snow,
]
};
if e <= 0.0 && polar > 0.35 {
let t = ((polar - 0.35) / 0.4).clamp(0.0, 1.0);
rgb = [
rgb[0] + (0.88 - rgb[0]) * t,
rgb[1] + (0.91 - rgb[1]) * t,
rgb[2] + (0.95 - rgb[2]) * t,
];
}
let o = x * 4;
row[o] = (rgb[0].clamp(0.0, 1.0) * 255.0) as u8;
row[o + 1] = (rgb[1].clamp(0.0, 1.0) * 255.0) as u8;
row[o + 2] = (rgb[2].clamp(0.0, 1.0) * 255.0) as u8;
row[o + 3] = 255;
}
});
let mut night = MapBuffer::new(width, height);
fill_rows(height, w * 4, &mut night.data, |y, row| {
let v = (y as f32 + 0.5) / h as f32;
let lat = (v - 0.5) * PI;
let habitable = (1.0 - ((lat.abs() - 0.30) / 0.95).clamp(0.0, 1.0)).clamp(0.0, 1.0);
for x in 0..w {
let e = field[y as usize * w + x];
let o = x * 4;
if e <= 0.005 {
row[o..o + 4].copy_from_slice(&[0, 0, 0, 255]);
continue;
}
let d = direction((x as f32 + 0.5) / w as f32, v);
let region = fbm(d, 7.0, 4, 5150);
let towns = fbm(d, 44.0, 3, 8191);
let lowland = 1.0 - (e / 0.8).clamp(0.0, 1.0);
let mut lit = ((region - 0.55) / 0.15).clamp(0.0, 1.0) * lowland * habitable;
lit *= ((towns - 0.42) / 0.20).clamp(0.0, 1.0);
let lit = lit.powf(1.1);
let core = (lit - 0.55).max(0.0) / 0.45;
row[o] = (lit * 255.0) as u8;
row[o + 1] = (lit * (0.78 + 0.22 * core) * 255.0) as u8;
row[o + 2] = (lit * (0.43 + 0.57 * core) * 255.0) as u8;
row[o + 3] = 255;
}
});
let mut clouds = MapBuffer::new(width, height);
fill_rows(height, w * 4, &mut clouds.data, |y, row| {
let v = (y as f32 + 0.5) / h as f32;
let lat = (v - 0.5) * PI;
let band = 0.55 + 0.45 * (lat * 6.0).cos() * (1.0 - lat.abs() / 1.7).max(0.0);
for x in 0..w {
let d = direction((x as f32 + 0.5) / w as f32, v);
let n = fbm([d[0], d[1] * 2.6, d[2]], 6.0, 6, 31337);
let a = ((n * band - 0.42) * 3.4).clamp(0.0, 1.0);
let o = x * 4;
row[o] = 255;
row[o + 1] = 255;
row[o + 2] = 255;
row[o + 3] = (a * 255.0) as u8;
}
});
let ease = |mut t: Texture| {
ease_poles(&mut t);
Arc::new(t)
};
PlanetMaps {
albedo: Some(ease(albedo.into_texture(TextureFormat::Rgba8UnormSrgb))),
normal: Some(ease(hf.to_normal_map(3.2))),
roughness: Some(ease(hf.to_roughness_map(0.5, 0.14, 0.86))),
night: Some(ease(night.into_texture(TextureFormat::Rgba8UnormSrgb))),
clouds: Some(ease(clouds.into_texture(TextureFormat::Rgba8UnormSrgb))),
displacement: Some(Arc::new(hf.to_height_map(0.5))),
}
}
pub fn equirect_to_cube_faces(src: &Texture, face_size: u32) -> Vec<Texture> {
let n = face_size.clamp(4, 8192);
let (sw, sh) = (src.width.max(1) as usize, src.height.max(1) as usize);
let bpp = src.bytes_per_pixel();
let half = matches!(src.format, TextureFormat::Rgba16Float);
let flip = src.flip_y;
if src.data.len() < sw * sh * bpp || bpp < 3 {
return Vec::new();
}
let texel = |x: usize, y: usize, c: usize| -> f32 {
let o = (y * sw + x) * bpp;
if half {
crate::math::float::f16_to_f32(u16::from_le_bytes([
src.data[o + c * 2],
src.data[o + c * 2 + 1],
]))
} else {
src.data[o + c] as f32 / 255.0
}
};
let sample = |d: [f32; 3]| -> [f32; 4] {
let lat = d[1].clamp(-1.0, 1.0).asin();
let u = (std::f32::consts::PI - d[2].atan2(d[0])) / std::f32::consts::TAU;
let u = u - u.floor();
let v = if flip {
0.5 - lat / std::f32::consts::PI
} else {
0.5 + lat / std::f32::consts::PI
};
let fx = (u * sw as f32 - 0.5).rem_euclid(sw as f32);
let fy = (v * sh as f32 - 0.5).clamp(0.0, sh as f32 - 1.0);
let (x0, y0) = (fx.floor(), fy.floor());
let (tx, ty) = (fx - x0, fy - y0);
let (x0, y0) = (x0 as usize % sw, y0 as usize);
let x1 = (x0 + 1) % sw;
let y1 = (y0 + 1).min(sh - 1);
let mut out = [0.0f32; 4];
for (c, o) in out.iter_mut().enumerate().take(bpp.min(4)) {
let top = texel(x0, y0, c) * (1.0 - tx) + texel(x1, y0, c) * tx;
let bot = texel(x0, y1, c) * (1.0 - tx) + texel(x1, y1, c) * tx;
*o = top * (1.0 - ty) + bot * ty;
}
if bpp < 4 {
out[3] = 1.0;
}
out
};
CUBE_FACES
.iter()
.map(|(f, r, up)| {
let mut data = vec![0u8; (n as usize) * (n as usize) * bpp];
fill_rows(n, n as usize * bpp, &mut data, |j, row| {
let _y = 2.0 * (j as f32 + 0.5) / n as f32 - 1.0;
for i in 0..n as usize {
const SS: usize = 2;
let mut acc = [0.0f32; 4];
for sy in 0..SS {
for sx in 0..SS {
let ox = (sx as f32 + 0.5) / SS as f32 - 0.5;
let oy = (sy as f32 + 0.5) / SS as f32 - 0.5;
let x = 2.0 * (i as f32 + 0.5 + ox) / n as f32 - 1.0;
let yy = 2.0 * (j as f32 + 0.5 + oy) / n as f32 - 1.0;
let d = [
f[0] + x * r[0] + yy * up[0],
f[1] + x * r[1] + yy * up[1],
f[2] + x * r[2] + yy * up[2],
];
let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt().max(1e-8);
let t = sample([d[0] / len, d[1] / len, d[2] / len]);
for c in 0..4 {
acc[c] += t[c];
}
}
}
let inv = 1.0 / (SS * SS) as f32;
let s = [acc[0] * inv, acc[1] * inv, acc[2] * inv, acc[3] * inv];
let o = i * bpp;
for c in 0..bpp.min(4) {
if half {
let h = crate::math::float::f32_to_f16(s[c]);
row[o + c * 2..o + c * 2 + 2].copy_from_slice(&h.to_le_bytes());
} else {
row[o + c] = (s[c].clamp(0.0, 1.0) * 255.0).round() as u8;
}
}
}
});
let mut t = Texture::new(n, n, src.format, data);
t.wrap_s = TextureWrap::ClampToEdge;
t.wrap_t = TextureWrap::ClampToEdge;
t.flip_y = false;
t
})
.collect()
}
pub const CUBE_FACES: [([f32; 3], [f32; 3], [f32; 3]); 6] = [
([1.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]),
([-1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 0.0]),
([0.0, 1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, -1.0]),
([0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]),
([0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]),
([0.0, 0.0, -1.0], [-1.0, 0.0, 0.0], [0.0, 1.0, 0.0]),
];
#[allow(clippy::excessive_precision)]
pub fn blackbody_rgb(kelvin: f32) -> [f32; 3] {
let t = kelvin.clamp(1667.0, 25000.0);
let (t1, t2, t3) = (1.0 / t, 1.0 / (t * t), 1.0 / (t * t * t));
let x = if t <= 4000.0 {
-0.2661239e9 * t3 - 0.2343589e6 * t2 + 0.8776956e3 * t1 + 0.179910
} else {
-3.0258469e9 * t3 + 2.1070379e6 * t2 + 0.2226347e3 * t1 + 0.240390
};
let (x2, x3) = (x * x, x * x * x);
let y = if t <= 2222.0 {
-1.1063814 * x3 - 1.34811020 * x2 + 2.18555832 * x - 0.20219683
} else if t <= 4000.0 {
-0.9549476 * x3 - 1.37418593 * x2 + 2.09137015 * x - 0.16748867
} else {
3.0817580 * x3 - 5.87338670 * x2 + 3.75112997 * x - 0.37001483
};
let y = y.max(1e-4);
let (xx, zz) = (x / y, (1.0 - x - y) / y);
let rgb = [
3.2404542 * xx - 1.5371385 - 0.4985314 * zz,
-0.9692660 * xx + 1.8760108 + 0.0415560 * zz,
0.0556434 * xx - 0.2040259 + 1.0572252 * zz,
];
let rgb = [rgb[0].max(0.0), rgb[1].max(0.0), rgb[2].max(0.0)];
let luma = 0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2];
if luma <= 1e-6 {
return [1.0, 1.0, 1.0];
}
[rgb[0] / luma, rgb[1] / luma, rgb[2] / luma]
}
pub fn generate_starfield(width: u32, count: u32) -> Texture {
let width = width.clamp(64, 16384);
let height = (width / 2).max(32);
let (w, h) = (width as usize, height as usize);
let mut buf = vec![0f32; w * h * 4];
galactic_band(w, h, &mut buf);
scatter_stars(w, h, count, &mut buf);
let data = buf
.iter()
.flat_map(|&v| crate::math::float::f32_to_f16(v).to_le_bytes())
.collect::<Vec<u8>>();
let mut t = Texture::new(width, height, TextureFormat::Rgba16Float, data);
t.wrap_s = TextureWrap::Repeat;
t.wrap_t = TextureWrap::ClampToEdge;
t
}
fn galactic_band(w: usize, h: usize, buf: &mut [f32]) {
let pole = [-0.868, 0.198, 0.456];
let centre = [-0.055, -0.874, -0.483];
fill_rows(h as u32, w * 4, buf, |y, row| {
let v = (y as f32 + 0.5) / h as f32;
for x in 0..w {
let d = direction((x as f32 + 0.5) / w as f32, v);
let sin_b = d[0] * pole[0] + d[1] * pole[1] + d[2] * pole[2];
let toward = d[0] * centre[0] + d[1] * centre[1] + d[2] * centre[2];
let bulge = (((toward + 1.0) * 0.5).clamp(0.0, 1.0)).powi(3);
let thickness = 0.055 + 0.16 * bulge;
let glow = (-(sin_b / thickness).powi(2)).exp() * (0.05 + 0.95 * bulge.sqrt());
row[x * 4 + 3] = 1.0;
if glow <= 1e-4 {
continue;
}
let clumps = 0.45 + 0.40 * fbm(d, 14.0, 5, 771) + 0.15 * fbm(d, 58.0, 3, 1097);
let lane = (-(sin_b / (thickness * 0.55)).powi(2)).exp();
let coarse = fbm(d, 26.0, 4, 313);
let fine = fbm(d, 88.0, 3, 641);
let dust = ((coarse * 0.72 + fine * 0.28) * 1.7 - 0.45).clamp(0.0, 1.0) * lane;
let m = glow * clumps * (1.0 - 0.85 * dust) * 0.018;
let warmth = 1.0 + 0.18 * bulge + 0.25 * dust;
let o = x * 4;
row[o] = m * (0.74 * warmth).min(1.15);
row[o + 1] = m * 0.82;
row[o + 2] = m * (1.02 / warmth.max(1.0)).max(0.78);
row[o + 3] = 1.0;
}
});
}
fn scatter_stars(w: usize, h: usize, count: u32, buf: &mut [f32]) {
let mut seed = 12_345u32;
let mut rnd = || {
seed = seed.wrapping_mul(747_796_405).wrapping_add(2_891_336_453);
let mut x = seed;
x ^= x >> 16;
x = x.wrapping_mul(2_246_822_519);
x ^= x >> 13;
x = x.wrapping_mul(3_266_489_917);
x ^= x >> 16;
(x >> 8) as f32 / 16_777_216.0
};
const CLASSES: [(f32, f32, f32); 6] = [
(0.08, 12000.0, 18000.0), (0.22, 7800.0, 10000.0), (0.20, 6200.0, 7500.0), (0.18, 5300.0, 6000.0), (0.22, 4000.0, 5200.0), (0.10, 2900.0, 3900.0), ];
const M_LIM: f32 = 8.0;
const M_MIN: f32 = -1.5;
let flux = |m: f32| 10f32.powf(-0.4 * (m - 6.0)) * 0.55;
for _ in 0..count {
let z = rnd() * 2.0 - 1.0;
let lon = rnd() * std::f32::consts::TAU;
let u = rnd().max(1e-6);
let m = (M_LIM + u.log10() / 0.6).max(M_MIN);
let pick = rnd();
let mut acc = 0.0;
let mut temp = 5800.0;
for (share, lo, hi) in CLASSES {
acc += share;
if pick <= acc {
temp = lo + (hi - lo) * rnd();
break;
}
}
let tint = blackbody_rgb(temp);
let f = flux(m);
let lat = z.asin();
let sx = lon / std::f32::consts::TAU * w as f32;
let sy = (0.5 - lat / std::f32::consts::PI) * h as f32;
splat(
w,
h,
buf,
sx,
sy,
lat,
[f * tint[0], f * tint[1], f * tint[2]],
);
}
}
fn splat(w: usize, h: usize, buf: &mut [f32], sx: f32, sy: f32, lat: f32, rgb: [f32; 3]) {
const SIGMA: f32 = 0.65;
let stretch = (1.0 / lat.cos().abs().max(1e-3)).min(w as f32 / 2.0);
const VAR_GRID: f32 = 1.0 / 12.0;
let var_v = SIGMA * SIGMA + VAR_GRID;
let sigma_u = (stretch * stretch * var_v - VAR_GRID)
.max(SIGMA * SIGMA)
.sqrt();
let (rx, ry) = (((sigma_u * 2.5).ceil() as i32).max(1), 2i32);
let mut total = 0.0;
for dy in -ry..=ry {
let y = sy.floor() as i32 + dy;
if y < 0 || y >= h as i32 {
continue;
}
let fy = (y as f32 + 0.5 - sy) / SIGMA;
for dx in -rx..=rx {
let fx = (sx.floor() as i32 + dx) as f32 + 0.5 - sx;
let fx = fx / sigma_u;
total += (-0.5 * (fx * fx + fy * fy)).exp();
}
}
if total <= 1e-9 {
return;
}
for dy in -ry..=ry {
let y = sy.floor() as i32 + dy;
if y < 0 || y >= h as i32 {
continue;
}
let fy = (y as f32 + 0.5 - sy) / SIGMA;
for dx in -rx..=rx {
let xi = sx.floor() as i32 + dx;
let fx = (xi as f32 + 0.5 - sx) / sigma_u;
let weight = (-0.5 * (fx * fx + fy * fy)).exp() / total;
let x = xi.rem_euclid(w as i32) as usize;
let o = (y as usize * w + x) * 4;
for c in 0..3 {
buf[o + c] += rgb[c] * weight;
}
buf[o + 3] = 1.0;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn flat(w: u32, h: u32, rgb: [u8; 3]) -> Texture {
let mut data = vec![255u8; (w * h * 4) as usize];
for px in data.as_chunks_mut::<4>().0 {
px[..3].copy_from_slice(&rgb);
}
Texture::new(w, h, TextureFormat::Rgba8UnormSrgb, data)
}
fn row_red(t: &Texture, y: u32) -> u8 {
t.data[(y * t.width * 4) as usize]
}
#[test]
fn the_polar_cap_replaces_the_pole_and_leaves_the_tropics_alone() {
let mut base = flat(16, 180, [0, 0, 0]);
let cap = flat(8, 90, [255, 255, 255]);
blend_polar_cap(&mut base, &cap, 72.0, 82.0);
assert_eq!(row_red(&base, 4), 255, "the pole should be all cap");
assert_eq!(
row_red(&base, 20),
0,
"below the band the base must survive"
);
assert_eq!(row_red(&base, 90), 0);
assert_eq!(
row_red(&base, 176),
0,
"a north band must not touch the south"
);
}
#[test]
fn the_polar_cap_joins_without_a_step() {
let mut base = flat(16, 180, [0, 0, 0]);
let cap = flat(8, 90, [255, 255, 255]);
blend_polar_cap(&mut base, &cap, 72.0, 82.0);
let mut prev = 0u8;
for y in (0..20).rev() {
let v = row_red(&base, y);
assert!(v >= prev, "row {y} went backwards: {v} after {prev}");
assert!(v - prev < 60, "step of {} at row {y}", v - prev);
prev = v;
}
assert_eq!(prev, 255);
}
#[test]
fn a_southward_band_addresses_the_south_cap() {
let mut base = flat(16, 180, [0, 0, 0]);
let cap = flat(8, 90, [255, 255, 255]);
blend_polar_cap(&mut base, &cap, -72.0, -82.0);
assert_eq!(row_red(&base, 176), 255, "the south pole should be all cap");
assert_eq!(
row_red(&base, 4),
0,
"a south band must not touch the north"
);
}
#[test]
fn the_polar_cap_mixes_in_linear_light() {
let mut base = flat(16, 180, [0, 0, 0]);
let cap = flat(8, 90, [255, 255, 255]);
blend_polar_cap(&mut base, &cap, 72.0, 82.0);
let mut checked = 0;
for y in 0..20u32 {
let lat = 90.0 - (y as f32 + 0.5);
let t = ((lat - 72.0) / 10.0).clamp(0.0, 1.0);
let mix = t * t * (3.0 - 2.0 * t);
if !(0.1..=0.9).contains(&mix) {
continue;
}
let want = (1.055 * mix.powf(1.0 / 2.4) - 0.055) * 255.0;
let got = row_red(&base, y) as f32;
assert!(
(got - want).abs() <= 2.0,
"row {y} (mix {mix:.2}) came out at {got}, wanted {want:.0} \
(a byte-space lerp would give {:.0})",
mix * 255.0
);
checked += 1;
}
assert!(checked >= 3, "only {checked} rows fell inside the band");
}
#[test]
fn direction_inverts_how_the_sphere_lays_a_map_out() {
use crate::geometries::SphereGeometry;
let g = SphereGeometry::new(1.0, 64, 32);
let pos = g.get_attribute("position").expect("position");
let uv = g.get_attribute("uv").expect("uv");
let mut checked = 0;
for i in 0..pos.count() {
let (x, y, z) = (pos.array[i * 3], pos.array[i * 3 + 1], pos.array[i * 3 + 2]);
let (u, v) = (uv.array[i * 2], uv.array[i * 2 + 1]);
if y.abs() > 0.995 {
continue;
}
let d = direction(u, 1.0 - v);
let dot = d[0] * x + d[1] * y + d[2] * z;
assert!(
dot > 0.999,
"uv ({u:.3}, {v:.3}) is at ({x:.3}, {y:.3}, {z:.3}) on the sphere \
but `direction` puts it at ({:.3}, {:.3}, {:.3})",
d[0],
d[1],
d[2]
);
checked += 1;
}
assert!(checked > 1000, "only {checked} vertices compared");
}
#[test]
fn cube_faces_sample_the_directions_they_are_placed_at() {
let (w, h) = (64u32, 32u32);
let mut data = vec![255u8; (w * h * 4) as usize];
for y in 0..h {
for x in 0..w {
let o = ((y * w + x) * 4) as usize;
let v = (x * 255 / (w - 1)) as u8;
data[o..o + 3].copy_from_slice(&[v, v, v]);
}
}
let src = Texture::new(w, h, TextureFormat::Rgba8Unorm, data);
let faces = equirect_to_cube_faces(&src, 16);
assert_eq!(faces.len(), 6);
for (face, (f, _, _)) in faces.iter().zip(CUBE_FACES.iter()) {
let mid = (8 * 16 + 8) * 4;
let got = face.data[mid] as f32 / 255.0;
let want = if f[1].abs() > 0.9 {
continue;
} else {
let u = (std::f32::consts::PI - f[2].atan2(f[0])) / std::f32::consts::TAU;
u - u.floor()
};
if !(0.02..=0.98).contains(&want) {
continue;
}
assert!(
(got - want).abs() < 0.05,
"face {f:?} centre carries {got:.3}, the sphere shows {want:.3} there"
);
}
}
#[test]
fn cube_faces_follow_the_sources_flip() {
let (w, h) = (32u32, 16u32);
let mut data = vec![255u8; (w * h * 4) as usize];
for y in 0..h {
for x in 0..w {
let o = ((y * w + x) * 4) as usize;
let v = if y < h / 2 { 255 } else { 0 };
data[o..o + 3].copy_from_slice(&[v, v, v]);
}
}
let mut north_first = Texture::new(w, h, TextureFormat::Rgba8Unorm, data.clone());
north_first.flip_y = true;
let up = &equirect_to_cube_faces(&north_first, 8)[2]; assert!(
up.data[0] > 200,
"+Y face should be the white half, got {}",
up.data[0]
);
let mut south_first = Texture::new(w, h, TextureFormat::Rgba8Unorm, data);
south_first.flip_y = false;
let up = &equirect_to_cube_faces(&south_first, 8)[2];
assert!(
up.data[0] < 55,
"+Y face should be the black half, got {}",
up.data[0]
);
}
#[test]
fn cube_faces_keep_the_maps_range() {
let sky = generate_starfield(256, 3000);
assert!(matches!(sky.format, TextureFormat::Rgba16Float));
let faces = equirect_to_cube_faces(&sky, 64);
assert_eq!(faces.len(), 6);
let peak = faces
.iter()
.flat_map(|f| f.data.as_chunks::<2>().0)
.map(|b| crate::math::float::f16_to_f32(u16::from_le_bytes([b[0], b[1]])))
.fold(0.0f32, f32::max);
assert!(
peak > 1.0,
"cube faces clipped the sky's range: peak {peak}"
);
for f in &faces {
assert!(matches!(f.format, TextureFormat::Rgba16Float));
assert!(
!f.flip_y,
"face rows are written in face order, not flipped"
);
}
}
#[test]
fn ice_is_told_from_desert_by_its_colour_not_its_brightness() {
let (w, h) = (8u32, 4u32);
let mut field = HeightField {
width: w,
height: h,
values: vec![1.0; (w * h) as usize],
};
for x in 0..w as usize {
field.values[x] = 0.0;
}
let mut albedo = vec![0u8; (w * h * 4) as usize];
for i in 0..(w * h) as usize {
let px = if i % (w as usize) < 4 {
[240, 242, 238]
} else {
[235, 200, 130]
};
albedo[i * 4..i * 4 + 3].copy_from_slice(&px);
albedo[i * 4 + 3] = 255;
}
let albedo = Texture::new(w, h, TextureFormat::Rgba8UnormSrgb, albedo);
let rough = field.to_roughness_map_with_ice(&albedo, 0.5, 0.45, 0.85, 0.30);
let at = |x: u32, y: u32| rough.data[((y * w + x) * 4) as usize] as f32 / 255.0;
assert!(
(at(1, 1) - 0.30).abs() < 0.01,
"snow should be ice: {}",
at(1, 1)
);
assert!(
(at(6, 1) - 0.85).abs() < 0.01,
"desert should be land: {}",
at(6, 1)
);
assert!(
(at(1, 0) - 0.45).abs() < 0.01,
"ocean should stay water: {}",
at(1, 0)
);
}
#[test]
fn the_hash_covers_the_whole_range() {
let mut lo = f32::MAX;
let mut hi = f32::MIN;
for i in 0..4000 {
let v = hash3(i % 60, i / 60, i % 7, 11);
lo = lo.min(v);
hi = hi.max(v);
}
assert!(lo < 0.05, "hash never gets near 0: {lo}");
assert!(hi > 0.95, "hash never gets near 1: {hi}");
}
#[test]
fn elevation_lands_near_earths_land_fraction() {
let mut land = 0;
let total = 40 * 80;
for y in 0..40 {
for x in 0..80 {
let d = direction((x as f32 + 0.5) / 80.0, (y as f32 + 0.5) / 40.0);
if elevation(d) > 0.0 {
land += 1;
}
}
}
let fraction = land as f32 / total as f32;
assert!(
(0.15..0.45).contains(&fraction),
"land fraction {fraction} is nowhere near Earth's 0.29"
);
}
#[test]
fn generated_maps_are_the_right_size_and_all_present() {
let maps = generate_earth_maps(128);
for t in [
&maps.albedo,
&maps.normal,
&maps.roughness,
&maps.night,
&maps.clouds,
] {
let t = t.as_ref().expect("every map is generated");
assert_eq!((t.width, t.height), (128, 64));
assert_eq!(t.data.len(), 128 * 64 * 4);
assert_eq!(t.wrap_s, TextureWrap::Repeat);
}
assert_eq!(maps.albedo.unwrap().format, TextureFormat::Rgba8UnormSrgb);
assert_eq!(maps.normal.unwrap().format, TextureFormat::Rgba8Unorm);
}
#[test]
fn the_night_side_is_lit_about_as_much_as_earths() {
let night = generate_earth_maps(512).night.unwrap();
let total = night.data.len() / 4;
let bright = night
.data
.as_chunks::<4>()
.0
.iter()
.filter(|p| p[0] >= 40)
.count();
let fraction = bright as f32 / total as f32;
assert!(
(0.003..0.04).contains(&fraction),
"{:.2}% of the map is lit; Earth's is around 1%",
fraction * 100.0
);
let peak = night
.data
.as_chunks::<4>()
.0
.iter()
.map(|p| p[0])
.max()
.unwrap();
assert!(peak > 150, "the brightest city is only {peak}/255");
for y in 0..night.height {
for x in 0..night.width {
let o = ((y * night.width + x) * 4) as usize;
if night.data[o] > 20 {
let d = direction(
(x as f32 + 0.5) / night.width as f32,
(y as f32 + 0.5) / night.height as f32,
);
assert!(elevation(d) > 0.0, "a lit texel out at sea at ({x}, {y})");
}
}
}
}
#[test]
fn normalising_a_height_map_recovers_the_wasted_range() {
let (w, h) = (16u32, 8u32);
let mut data = vec![255u8; (w * h * 4) as usize];
for y in 0..h {
for x in 0..w {
let o = ((y * w + x) * 4) as usize;
let v = 40 + ((x * 80) / (w - 1)) as u8;
data[o..o + 3].copy_from_slice(&[v, v, v]);
}
}
let hf = HeightField::from_texture(&Texture::new(w, h, TextureFormat::Rgba8Unorm, data));
let (lo, hi) = hf.range();
assert!((lo - 40.0 / 255.0).abs() < 1e-3 && (hi - 120.0 / 255.0).abs() < 1e-3);
let plain = hf.to_height_map(0.0);
let stretched = hf.to_height_map_normalized();
let red = |t: &Texture, x: u32| t.data[((h / 2 * w + x) * 4) as usize];
assert_eq!(red(&plain, 0), 40);
assert_eq!(red(&plain, w - 1), 120);
assert_eq!(red(&stretched, 0), 0);
assert_eq!(red(&stretched, w - 1), 255);
}
#[test]
fn easing_the_poles_flattens_only_the_rows_that_feed_the_pole_vertices() {
let (w, h) = (512u32, 256u32);
let mut data = vec![255u8; (w * h * 4) as usize];
for y in 0..h {
for x in 0..w {
let o = ((y * w + x) * 4) as usize;
let v = if x % 2 == 0 { 0 } else { 255 };
data[o..o + 3].copy_from_slice(&[v, v, v]);
}
}
let mut t = Texture::new(w, h, TextureFormat::Rgba8Unorm, data);
ease_poles(&mut t);
let spread = |y: u32| {
let base = (y * w * 4) as usize;
let vals: Vec<u8> = (0..w).map(|x| t.data[base + (x * 4) as usize]).collect();
vals.iter().copied().max().unwrap() - vals.iter().copied().min().unwrap()
};
assert!(spread(0) < 20, "the top row still varies by {}", spread(0));
assert!(
spread(h - 1) < 20,
"the bottom row still varies by {}",
spread(h - 1)
);
assert_eq!(spread(5), 255, "86 degrees north was flattened");
assert_eq!(spread(h / 2), 255, "the equator should keep its full range");
assert_eq!(spread(h / 2 - 1), 255);
}
#[test]
fn a_displaced_pole_reads_one_height_all_the_way_round() {
let (w, h) = (512u32, 256u32);
let mut data = vec![255u8; (w * h * 4) as usize];
for y in 0..h {
for x in 0..w {
let o = ((y * w + x) * 4) as usize;
let v = if x == 3 { 255 } else { 0 };
data[o..o + 3].copy_from_slice(&[v, v, v]);
}
}
let mut t = Texture::new(w, h, TextureFormat::Rgba8Unorm, data);
ease_poles(&mut t);
for row in [0u32, h - 1] {
let base = (row * w * 4) as usize;
let vals: Vec<u8> = (0..w).map(|x| t.data[base + (x * 4) as usize]).collect();
let spread = vals.iter().copied().max().unwrap() - vals.iter().copied().min().unwrap();
assert!(
spread <= 1,
"row {row} varies by {spread}; a displaced pole would tear"
);
}
}
#[test]
fn clouds_carry_their_shape_in_the_alpha_channel() {
let maps = generate_earth_maps(256);
let clouds = maps.clouds.unwrap();
let alphas: Vec<u8> = clouds
.data
.as_chunks::<4>()
.0
.iter()
.map(|p| p[3])
.collect();
assert!(alphas.iter().any(|&a| a > 200), "no thick cloud anywhere");
assert!(alphas.iter().any(|&a| a < 20), "no clear sky anywhere");
assert!(clouds.data.as_chunks::<4>().0.iter().all(|p| p[0] == 255));
}
#[test]
fn a_height_field_derives_relief_and_water() {
let (w, h) = (32u32, 16u32);
let mut data = vec![0u8; (w * h * 4) as usize];
for y in 0..h {
for x in 0..w {
let o = ((y * w + x) * 4) as usize;
let v = if x < w / 2 { 40 } else { 200 };
data[o..o + 4].copy_from_slice(&[v, v, v, 255]);
}
}
let hf = HeightField::from_texture(&Texture::new(w, h, TextureFormat::Rgba8Unorm, data));
assert_eq!(hf.values.len(), (w * h) as usize);
let rough = hf.to_roughness_map(0.5, 0.1, 0.9);
let sample = |x: u32| rough.data[((h / 2 * w + x) * 4) as usize];
assert!(sample(4) < 40, "water should be smooth");
assert!(sample(28) > 200, "land should be rough");
let normal = hf.to_normal_map(3.0);
let flat = normal.data[((h / 2 * w + 4) * 4) as usize];
let edge = normal.data[((h / 2 * w + w / 2) * 4) as usize];
assert!((flat as i32 - 128).abs() < 6, "open water should be flat");
assert_ne!(flat, edge, "the shoreline should register as a slope");
}
fn sky_pixels(t: &Texture) -> Vec<[f32; 3]> {
use crate::math::float::f16_to_f32 as f16_bits_to_f32;
t.data
.as_chunks::<8>()
.0
.iter()
.map(|p| {
let h = |i: usize| f16_bits_to_f32(u16::from_le_bytes([p[i * 2], p[i * 2 + 1]]));
[h(0), h(1), h(2)]
})
.collect()
}
fn luma(p: [f32; 3]) -> f32 {
0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2]
}
#[test]
fn starfield_density_follows_the_star_count() {
let lit = |count| {
let sky = generate_starfield(256, count);
sky_pixels(&sky).iter().filter(|&&p| luma(p) > 0.1).count()
};
let sparse = lit(200);
let dense = lit(2000);
assert!(sparse > 0, "no stars at all");
assert!(
dense > sparse * 3,
"ten times the stars barely changed the sky: {sparse} → {dense}"
);
assert!(
sparse * 20 < 256 * 128,
"sparse sky is too crowded: {sparse}"
);
}
#[test]
fn the_galactic_band_is_dim_but_present() {
let sky = sky_pixels(&generate_starfield(256, 0));
let brightest = sky.iter().map(|&p| luma(p)).fold(0.0, f32::max);
assert!(brightest > 0.002, "no galactic band at all: {brightest}");
assert!(
brightest < 0.2,
"the band is as bright as a star: {brightest}"
);
let in_band = sky.iter().filter(|&&p| luma(p) > 0.002).count();
assert!(in_band * 2 < sky.len(), "the band covers half the sky");
}
#[test]
fn stars_span_the_magnitude_range_they_claim_to() {
let sky = sky_pixels(&generate_starfield(1024, 20_000));
let mut lumas: Vec<f32> = sky.iter().map(|&p| luma(p)).filter(|&l| l > 0.05).collect();
lumas.sort_by(|a, b| a.partial_cmp(b).unwrap());
assert!(lumas.len() > 500, "too few stars to judge: {}", lumas.len());
let faint = lumas[lumas.len() / 20];
let bright = lumas[lumas.len() - 1];
assert!(
bright / faint > 50.0,
"the brightest star is only {:.1}x the faintest; the magnitude \
distribution has been flattened",
bright / faint
);
assert!(bright > 1.0, "nothing exceeds display white: {bright}");
}
#[test]
fn a_star_keeps_its_flux_wherever_it_lands() {
let total = |count| -> f32 {
let sky = sky_pixels(&generate_starfield(256, count));
sky.iter().map(|&p| luma(p)).sum()
};
let band = total(0);
let with_stars = total(4000);
let flux = with_stars - band;
assert!(flux > 0.0, "stars added no light at all");
let hi = {
let sky = sky_pixels(&generate_starfield(512, 4000));
sky.iter().map(|&p| luma(p)).sum::<f32>()
} - {
let sky = sky_pixels(&generate_starfield(512, 0));
sky.iter().map(|&p| luma(p)).sum::<f32>()
};
let ratio = hi / flux;
assert!(
(0.8..1.25).contains(&ratio),
"doubling the map's edge changed the stars' total flux by {ratio:.2}x"
);
}
#[test]
fn star_colour_is_temperature_and_not_brightness() {
for t in [3000.0, 5800.0, 15000.0] {
let rgb = blackbody_rgb(t);
let l = 0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2];
assert!((l - 1.0).abs() < 0.02, "{t}K has luminance {l}");
}
let cool = blackbody_rgb(3000.0);
let hot = blackbody_rgb(15000.0);
assert!(cool[0] > cool[2], "3000K should be red-leaning: {cool:?}");
assert!(hot[2] > hot[0], "15000K should be blue-leaning: {hot:?}");
let sun = blackbody_rgb(5800.0);
assert!(
(sun[0] - sun[2]).abs() < 0.25,
"5800K should be near neutral: {sun:?}"
);
}
}