Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
feat(terrain): one streamer, integer saved ground, drop dormant stacks
ColumnStream is the demo keep/evict set. Scene saves and the Aravath
checkpoint store the integer column record, with an erosion banner that
the preview is not the ground. PCG dungeons collapse through SeedRng.
Voxel materials bind through ModelSurfaceMaps. --frame-times writes a
CSV beside the exe. The unused heightmap loader, clipmap, GPU erosion,
voxel modifier, and second terrain save format are removed.

Co-authored-by: Andrew Brown <lazyxeon@users.noreply.github.com>
  • Loading branch information
cursoragent and lazyxeon committed Oct 16, 2026
commit f977a9071c1f142f7f46ffdbe16e4d58cd1c954d
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions aravath_runtime/src/figure.rs
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,7 @@ impl Figure {
indices: primitive.indices.clone(),
albedo_image: None,
texture_source_hint: None,
..Default::default()
},
color: primitive.color,
});
Expand Down
1 change: 1 addition & 0 deletions aravath_runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ pub mod hud;
pub mod ik;
pub mod island;
pub mod locomotion;
pub mod materials;
pub mod motor;
pub mod play_input;
pub mod player;
Expand Down
127 changes: 127 additions & 0 deletions aravath_runtime/src/materials.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
//! Voxel materials 1–5 sample the pine-forest Poly Haven set.
//!
//! `diff` / `nor_gl` / `arm` are converted with `astraweave_render::pbr_maps`
//! into [`astraweave_render::ModelSurfaceMaps`]. KayKit props stay on the
//! greybox colored-mesh path.

use std::path::{Path, PathBuf};

use anyhow::{bail, Context, Result};

use crate::assets;

/// One material after the Poly Haven ARM split.
pub struct VoxelSurface {
pub width: u32,
pub height: u32,
pub albedo: Vec<u8>,
pub normal: Vec<u8>,
pub metallic_roughness: Vec<u8>,
pub occlusion: Vec<u8>,
}

/// Stone, dirt (road), grass, sand, wood.
pub fn material_slug(material: u16) -> &'static str {
match material {
2 => "rocky_trail",
3 => "forest_ground_04",
4 => "coast_land_rocks_01",
5 => "pine_bark",
_ => "aerial_rocks_01",
}
}

/// Build engine maps from already-decoded RGBA8 images of the same size.
pub fn maps_from_polyhaven(
diff: &[u8],
nor_gl: &[u8],
arm: &[u8],
width: u32,
height: u32,
) -> VoxelSurface {
let (metallic_roughness, occlusion) = astraweave_render::pbr_maps::split_polyhaven_arm(arm);
let normal = astraweave_render::pbr_maps::nor_gl_unchanged(nor_gl);
VoxelSurface {
width,
height,
albedo: diff.to_vec(),
normal,
metallic_roughness,
occlusion,
}
}

pub fn pine_forest_dir() -> PathBuf {
let beside = assets::exe_dir().join("assets/terrain/polyhaven/pine_forest");
if beside.is_dir() {
return beside;
}
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../assets/terrain/polyhaven/pine_forest")
}

pub fn load_slug(slug: &str) -> Result<VoxelSurface> {
let dir = pine_forest_dir();
let diff = read_rgba(&dir.join(format!("{slug}_diff_2k.jpg")))?;
let nor = read_rgba(&dir.join(format!("{slug}_nor_gl_2k.jpg")))?;
let arm = read_rgba(&dir.join(format!("{slug}_arm_2k.jpg")))?;
if diff.0 != nor.0 || diff.1 != nor.1 || diff.0 != arm.0 || diff.1 != arm.1 {
bail!("{slug} maps are not the same size");
}
Ok(maps_from_polyhaven(&diff.2, &nor.2, &arm.2, diff.0, diff.1))
}

fn read_rgba(path: &Path) -> Result<(u32, u32, Vec<u8>)> {
let meta = std::fs::metadata(path).with_context(|| format!("open {}", path.display()))?;
if !meta.is_file() || meta.len() == 0 || meta.len() > assets::MAX_TEXTURE_BYTES {
bail!("texture {} is missing or too large", path.display());
}
let image = image::ImageReader::open(path)
.with_context(|| format!("open {}", path.display()))?
.with_guessed_format()
.context("guess texture format")?
.decode()
.with_context(|| format!("decode {}", path.display()))?
.into_rgba8();
let width = image.width();
let height = image.height();
if width == 0
|| height == 0
|| width > assets::MAX_TEXTURE_EDGE
|| height > assets::MAX_TEXTURE_EDGE
{
bail!("texture {} has an invalid size", path.display());
}
Ok((width, height, image.into_raw()))
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn polyhaven_arm_feeds_the_engine_layout() {
let surface =
maps_from_polyhaven(&[1, 2, 3, 255], &[9, 8, 7, 255], &[10, 80, 250, 255], 1, 1);
assert_eq!(surface.albedo, vec![1, 2, 3, 255]);
assert_eq!(surface.normal, vec![9, 8, 7, 255]);
assert_eq!(surface.metallic_roughness, vec![250, 80, 0, 255]);
assert_eq!(surface.occlusion, vec![10, 10, 10, 255]);
assert_eq!(material_slug(1), "aerial_rocks_01");
assert_eq!(material_slug(2), "rocky_trail");
assert_eq!(material_slug(3), "forest_ground_04");
assert_eq!(material_slug(4), "coast_land_rocks_01");
assert_eq!(material_slug(5), "pine_bark");
}

#[test]
fn pine_forest_2k_maps_are_vendored() {
let dir = pine_forest_dir();
for material in 1..=5 {
let slug = material_slug(material);
for role in ["diff", "nor_gl", "arm"] {
let path = dir.join(format!("{slug}_{role}_2k.jpg"));
assert!(path.is_file(), "missing {}", path.display());
}
}
}
}
3 changes: 3 additions & 0 deletions aravath_runtime/src/props.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,7 @@ impl NodeActor {
indices,
albedo_image: None,
texture_source_hint: None,
..Default::default()
})
}

Expand Down Expand Up @@ -241,6 +242,7 @@ pub fn load_colored(path: &Path) -> Result<Vec<ColoredMesh>> {
indices: prim_indices,
albedo_image: None,
texture_source_hint: None,
..Default::default()
},
color: primitive
.material()
Expand Down Expand Up @@ -302,6 +304,7 @@ pub fn load_rigid(path: &Path) -> Result<TexturedMesh> {
indices,
albedo_image: None,
texture_source_hint: None,
..Default::default()
},
albedo: rgba_from_images(&images),
})
Expand Down
82 changes: 82 additions & 0 deletions aravath_runtime/src/save.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ pub fn save_checkpoint(root: &Path, checkpoint: &Checkpoint) -> Result<()> {
let mut meta = std::collections::HashMap::new();
meta.insert("edits".into(), encode_edits(&checkpoint.edits));
insert_into_meta(&mut meta, &checkpoint.scars).context("encode veil scars")?;
meta.insert(
"ground".into(),
encode_hex(&astraweave_terrain::column_gen::worldgen_record()),
);
meta.insert(
"player".into(),
format!(
Expand Down Expand Up @@ -88,6 +92,7 @@ pub fn load_checkpoint(root: &Path) -> Result<Checkpoint> {
Some(text) => finite_limited(text, "player hp", 10_000.0)?,
None => 100.0,
};
require_saved_ground(&bundle.meta)?;
let scars = read_from_meta(&bundle.meta).context("decode veil scars")?;
Ok(Checkpoint {
edits,
Expand Down Expand Up @@ -129,6 +134,54 @@ fn finite_limited(text: &str, name: &str, limit: f32) -> Result<f32> {
Ok(value)
}

fn encode_hex(bytes: &[u8]) -> String {
const HEX: &[u8; 16] = b"0123456789abcdef";
let mut out = String::with_capacity(bytes.len() * 2);
for byte in bytes {
out.push(HEX[(byte >> 4) as usize] as char);
out.push(HEX[(byte & 0x0f) as usize] as char);
}
out
}

fn decode_hex(text: &str) -> Result<Vec<u8>> {
if text.len() % 2 != 0 {
bail!("ground record is not hex");
}
let raw = text.as_bytes();
let mut out = Vec::with_capacity(text.len() / 2);
let mut index = 0;
while index < raw.len() {
let hi = hex_nibble(raw[index])?;
let lo = hex_nibble(raw[index + 1])?;
out.push((hi << 4) | lo);
index += 2;
}
Ok(out)
}

fn hex_nibble(byte: u8) -> Result<u8> {
match byte {
b'0'..=b'9' => Ok(byte - b'0'),
b'a'..=b'f' => Ok(byte - b'a' + 10),
b'A'..=b'F' => Ok(byte - b'A' + 10),
_ => bail!("ground record is not hex"),
}
}

/// Old saves omit `ground`. A present key must be the integer columns.
fn require_saved_ground(meta: &std::collections::HashMap<String, String>) -> Result<()> {
let Some(text) = meta.get("ground") else {
return Ok(());
};
let stored = decode_hex(text).context("ground record")?;
let fresh = astraweave_terrain::column_gen::worldgen_record();
if stored != fresh {
bail!("saved ground does not match the integer columns");
}
Ok(())
}

fn encode_edits(edits: &[VoxelEdit]) -> String {
edits
.iter()
Expand Down Expand Up @@ -300,6 +353,35 @@ mod tests {
0.5f32.to_bits()
);
}

#[test]
fn saved_ground_is_the_integer_record() {
let dir = tempfile::tempdir().unwrap();
save_checkpoint(
dir.path(),
&Checkpoint {
edits: Vec::new(),
position: Vec3::ZERO,
yaw: 0.0,
stamina: 1.0,
player_hp: 1.0,
scars: astraweave_veil::ScarField::new(),
},
)
.unwrap();
let loaded = load_checkpoint(dir.path()).unwrap();
assert!(loaded.edits.is_empty());
let (bundle, _) = aw_save::SaveManager::new(dir.path())
.load_latest_slot("aravath", 0)
.unwrap();
let mut mismatched = bundle.meta.clone();
mismatched.insert("ground".into(), "00".into());
let err = require_saved_ground(&mismatched).unwrap_err();
assert!(err.to_string().contains("integer columns"), "{err}");
let mut legacy = bundle.meta.clone();
legacy.remove("ground");
require_saved_ground(&legacy).unwrap();
}
}

#[cfg(test)]
Expand Down
2 changes: 1 addition & 1 deletion astraweave-pcg/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,4 @@ pub mod wfc;
pub use encounters::{Encounter, EncounterConstraints, EncounterGenerator, EncounterKind};
pub use layout::{LayoutGenerator, Room};
pub use seed_rng::SeedRng;
pub use wfc::{Direction, TileId, TileSet, WfcError, WfcGrid};
pub use wfc::{seeded_dungeon_tile_count, Direction, TileId, TileSet, WfcError, WfcGrid};
16 changes: 15 additions & 1 deletion astraweave-pcg/src/seed_rng.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

use rand::distr::uniform::{SampleRange, SampleUniform};
use rand::rngs::StdRng;
use rand::{Rng, SeedableRng};
use rand::{Rng, RngCore, SeedableRng};

/// Deterministic random number generator with layer tracking
pub struct SeedRng {
Expand Down Expand Up @@ -86,6 +86,20 @@ impl SeedRng {
}
}

impl RngCore for SeedRng {
fn next_u32(&mut self) -> u32 {
self.inner.next_u32()
}

fn next_u64(&mut self) -> u64 {
self.inner.next_u64()
}

fn fill_bytes(&mut self, dest: &mut [u8]) {
self.inner.fill_bytes(dest)
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
29 changes: 29 additions & 0 deletions astraweave-pcg/src/wfc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,12 @@ impl WfcGrid {
}

/// Run the full WFC algorithm until all cells are collapsed.
/// Collapse with [`crate::SeedRng`] so the same seed is the same dungeon.
pub fn collapse_seeded(&mut self, seed: u64) -> Result<(), WfcError> {
let mut rng = crate::SeedRng::new(seed, "wfc");
self.collapse_all(&mut rng)
}

pub fn collapse_all<R: Rng>(&mut self, rng: &mut R) -> Result<(), WfcError> {
if self.tileset.tile_count() == 0 {
return Err(WfcError::EmptyTileSet);
Expand Down Expand Up @@ -539,6 +545,18 @@ pub fn rooms_and_corridors_tileset() -> TileSet {
ts
}

/// Collapse a 6×6 rooms-and-corridors dungeon and count placed tiles.
///
/// The editor dungeon button calls this. The same seed returns the same count.
pub fn seeded_dungeon_tile_count(seed: u64) -> usize {
let tileset = rooms_and_corridors_tileset();
let mut grid = WfcGrid::new(6, 6, &tileset);
match grid.collapse_seeded(seed) {
Ok(()) => grid.to_grid().into_iter().flatten().flatten().count(),
Err(_) => 0,
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -690,6 +708,17 @@ mod tests {
}

#[test]
fn wfc_seeded_collapse_is_stable() {
let ts = rooms_and_corridors_tileset();
let mut a = WfcGrid::new(6, 6, &ts);
let mut b = WfcGrid::new(6, 6, &ts);
a.collapse_seeded(7).expect("seed 7");
b.collapse_seeded(7).expect("seed 7");
assert_eq!(a.to_grid(), b.to_grid());
assert_eq!(seeded_dungeon_tile_count(7), seeded_dungeon_tile_count(7));
assert!(seeded_dungeon_tile_count(7) > 0);
}

fn wfc_rooms_tileset() {
let ts = rooms_and_corridors_tileset();
assert_eq!(ts.tile_count(), 10);
Expand Down
1 change: 1 addition & 0 deletions astraweave-render/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ approx = "0.5"
naga = { version = "25.0.1", features = ["wgsl-in"] }
glob = "0.3"
image = "0.25"
sha2 = { workspace = true }

[[bench]]
name = "alloc_measure"
Expand Down
Loading