use std::collections::BTreeMap; use std::path::PathBuf; use std::sync::Arc; use project_cold_water::audio::bvh::AcousticBvh; use project_cold_water::core::materials::MaterialId; use project_cold_water::modding::blueprint::{ AssetBlueprint, BlueprintPayload, MapStampBlueprint, SCHEMA_VERSION, }; use project_cold_water::modding::csg::{evaluate_csg_tree, CsgNode, CsgOp, PrimitiveKind}; use project_cold_water::modding::registry::ModRegistry; use project_cold_water::sim::Simulation; use project_cold_water::world::generator::{ CustomGridSpec, DynamicMapGenerator, GridCellScope, GridTemplateKind, MapGenConfig, }; use project_cold_water::world::palette::{ export_builtin_preset_to_map_stamp, MapGenPalette, MapGenSlot, WeightedAssetEntry, }; use project_cold_water::world::terrain::ZoneType; use project_cold_water::world::{HeightQuery, MapScenario}; fn make_temp_project_dir(tag: &str) -> PathBuf { let ts = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map_or(0, |d| d.as_nanos()); let dir = std::env::temp_dir().join(format!("cw_sculpt_test_{tag}_{ts}")); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).expect("create temp dir"); dir } #[test] fn test_mapgen_palette_custom_stamp_placement_and_builtin_export() { let dir = make_temp_project_dir("palette_stamp"); // 1. Author a custom CSG MapStamp in temp project let stamp_bp = AssetBlueprint { schema_version: SCHEMA_VERSION, id: "test_custom_bastion".into(), name: "Test Custom Bastion".into(), author: "UnitTest".into(), payload: BlueprintPayload::MapStamp(MapStampBlueprint { nodes: vec![ CsgNode::new_primitive( 1, "Bastion Block", CsgOp::Union, PrimitiveKind::Box, [0.0, 2.0, 0.0], [0.0, 0.0, 0.0], [7.0, 4.0, 7.0], MaterialId::Concrete, ), CsgNode::new_primitive( 2, "Room Cutout", CsgOp::Subtract, PrimitiveKind::Box, [0.0, 1.8, 0.0], [0.0, 0.0, 0.0], [5.0, 3.0, 5.0], MaterialId::Concrete, ), ], description: "Custom bastion stamp for generator palette test.".into(), blocks_navigation: true, }), }; let mut mods = ModRegistry::load_project_dir(&dir, false); mods.save_blueprint(&dir, stamp_bp).expect("save custom stamp"); // 2. Bind the custom stamp across slots in a custom MapGenPalette let mut zone_slots = BTreeMap::new(); for &z in &ZoneType::ALL { let mut slots = BTreeMap::new(); slots.insert( MapGenSlot::MediumBuilding, vec![WeightedAssetEntry::stamp("test_custom_bastion", 5.0, 6.0, true)], ); slots.insert( MapGenSlot::LargeBuilding, vec![WeightedAssetEntry::stamp("test_custom_bastion", 5.0, 6.0, true)], ); slots.insert( MapGenSlot::SmallBuilding, vec![WeightedAssetEntry::stamp("test_custom_bastion", 5.0, 6.0, true)], ); slots.insert( MapGenSlot::Landmark, vec![WeightedAssetEntry::stamp("test_custom_bastion", 5.0, 6.0, true)], ); slots.insert( MapGenSlot::Bridge, vec![WeightedAssetEntry::builtin("engine:bridge", 1.0, 14.0, false)], ); zone_slots.insert(z, slots); } let palette = MapGenPalette { id: "custom_bastion_palette".into(), name: "Custom Bastion Palette".into(), zone_slots, }; mods.save_palette(&dir, palette).expect("save custom palette"); // 3. Reload from disk and generate a CustomGrid map using our palette let reloaded = ModRegistry::load_project_dir(&dir, false); assert!(reloaded.find_stamp("test_custom_bastion").is_some()); assert!(reloaded.find_palette("custom_bastion_palette").is_some()); let mut grid = CustomGridSpec::new(4, 4, GridCellScope::Block32m, ZoneType::SovietCityCore); grid.auto_roads = false; let mut cfg = MapGenConfig::custom_grid(grid, 777); cfg.palette_id = Some("custom_bastion_palette".into()); let world = DynamicMapGenerator::new(cfg).build_with_mods(Some(&reloaded)); assert!( !world.destructible.structures.is_empty(), "expected custom destructible stamps to be placed on the generated world" ); assert!( world.static_indices.len() > 300, "expected static geometry from terrain + stamped CSG structures" ); // 4. Convert a built-in generator preset -> editable CSG MapStamp let converted = export_builtin_preset_to_map_stamp("engine:block_medium"); let BlueprintPayload::MapStamp(sb) = &converted.payload else { panic!("expected MapStamp payload from export_builtin_preset_to_map_stamp"); }; let polys = evaluate_csg_tree(&sb.nodes); assert!(!polys.is_empty(), "exported CSG stamp must evaluate to valid polygons"); let _ = std::fs::remove_dir_all(&dir); } #[test] fn test_custom_grid_3x3_small_and_128x128_large_scaling() { // 1. Minimum 3x3 grid @ 32m scope -> 96m x 96m playable + scenic skirt -> 120m half_extent let mut small_grid = CustomGridSpec::new(3, 3, GridCellScope::Block32m, ZoneType::SuburbanTown); small_grid.set(1, 0, ZoneType::RiverCrossing); small_grid.set(1, 1, ZoneType::RiverCrossing); small_grid.set(1, 2, ZoneType::RiverCrossing); let small_world = DynamicMapGenerator::new(MapGenConfig::custom_grid(small_grid, 101)).build(); assert!((small_world.world_half_extent - 120.0).abs() < 1.0); let small_play = small_world.height_grid.playable_half_extents(); assert!((small_play.x - 48.0).abs() < 0.1 && (small_play.y - 48.0).abs() < 0.1); assert!(small_world.nav_grid.cells_per_side >= 16); assert!(!small_world.squad_spawns.is_empty()); // 2. Maximum 128x128 grid @ 128m scope -> 16,384m playable + 25% skirt = 20,480m total (half_extent = 10,240m) let mut large_grid = CustomGridSpec::new(128, 128, GridCellScope::Sector128m, ZoneType::OpenField); large_grid.apply_template(GridTemplateKind::ValleyRiver, 404); let large_world = DynamicMapGenerator::new(MapGenConfig::custom_grid(large_grid, 404)).build(); assert!( (large_world.world_half_extent - 10240.0).abs() < 1.0, "expected 20480m theater with +25% skirt (half_extent = 10240.0), got {}", large_world.world_half_extent ); let large_play = large_world.height_grid.playable_half_extents(); assert!((large_play.x - 8192.0).abs() < 1.0 && (large_play.y - 8192.0).abs() < 1.0); let chunks = large_world .terrain_chunks .as_ref() .expect("128x128 large grid must build 3-LOD chunked terrain"); assert_eq!(chunks.chunks.len(), 256, "expected 16x16 = 256 LOD terrain chunks"); let min_cx = chunks.chunks.iter().map(|c| c.bounds_min.x).fold(f32::MAX, f32::min); let max_cx = chunks.chunks.iter().map(|c| c.bounds_max.x).fold(f32::MIN, f32::max); let min_cz = chunks.chunks.iter().map(|c| c.bounds_min.z).fold(f32::MAX, f32::min); let max_cz = chunks.chunks.iter().map(|c| c.bounds_max.z).fold(f32::MIN, f32::max); assert!((min_cx + large_world.world_half_extent).abs() < 1.0); assert!((max_cx - large_world.world_half_extent).abs() < 1.0); assert!((min_cz + large_world.world_half_extent).abs() < 1.0); assert!((max_cz - large_world.world_half_extent).abs() < 1.0); assert!( large_world.nav_grid.cells_per_side <= 256, "NavGrid must remain bounded <= 256x256, got {}", large_world.nav_grid.cells_per_side ); assert!( large_world.destructible.structures.len() <= 12_000, "destructible budget exceeded: {}", large_world.destructible.structures.len() ); assert!( large_world.destructible.buildings.len() >= 20, "expected >= 20 destructible building clusters on 128x128 map, got {}", large_world.destructible.buildings.len() ); assert!( large_world.squad_spawns.len() >= 2, "expected Federal & Militia spawns on 128x128 map" ); } #[test] fn test_custom_grid_terrain_bounds_and_no_objects_outside_terrain() { let cases = [ ("medium_16x16_64m", 16u16, 16u16, GridCellScope::District64m, GridTemplateKind::ValleyRiver), ("rect_24x8_64m", 24, 8, GridCellScope::District64m, GridTemplateKind::TwinCities), ("large_64x64_128m", 64, 64, GridCellScope::Sector128m, GridTemplateKind::RandomBiomes), ("island_12x12_64m", 12, 12, GridCellScope::District64m, GridTemplateKind::ArchipelagoLake), ]; for (label, w, h, scope, tmpl) in cases { let mut spec = CustomGridSpec::new(w, h, scope, ZoneType::OpenField); spec.apply_template(tmpl, 5150); if label == "island_12x12_64m" { // Paint solid WaterLake border ring so skirt must continue into open water for x in 0..w { spec.set(x, 0, ZoneType::WaterLake); spec.set(x, h - 1, ZoneType::WaterLake); } for z in 0..h { spec.set(0, z, ZoneType::WaterLake); spec.set(w - 1, z, ZoneType::WaterLake); } } let world = DynamicMapGenerator::new(MapGenConfig::custom_grid(spec, 5150)).build(); let play = world.height_grid.playable_half_extents(); let he = world.world_half_extent; assert!(he >= play.x.max(play.y) + 48.0, "{label}: terrain must include scenic skirt"); let chunks = world .terrain_chunks .as_ref() .unwrap_or_else(|| panic!("{label}: expected chunked terrain")); let min_cx = chunks.chunks.iter().map(|c| c.bounds_min.x).fold(f32::MAX, f32::min); let max_cx = chunks.chunks.iter().map(|c| c.bounds_max.x).fold(f32::MIN, f32::max); let min_cz = chunks.chunks.iter().map(|c| c.bounds_min.z).fold(f32::MAX, f32::min); let max_cz = chunks.chunks.iter().map(|c| c.bounds_max.z).fold(f32::MIN, f32::max); assert!( (min_cx + he).abs() < 1.0 && (max_cx - he).abs() < 1.0, "{label}: X chunk span [{min_cx}, {max_cx}] does not match [-{he}, +{he}]" ); assert!( (min_cz + he).abs() < 1.0 && (max_cz - he).abs() < 1.0, "{label}: Z chunk span [{min_cz}, {max_cz}] does not match [-{he}, +{he}]" ); // On chunked maps, static_vertices holds placed trees/buildings/props/bridges (not terrain). // Every single vertex must sit well inside the painted playable grid and never outside terrain! for v in &world.static_vertices { let px = v.position[0]; let pz = v.position[2]; assert!( px.abs() <= play.x + 18.0 && pz.abs() <= play.y + 18.0, "{label}: placed mesh vertex ({px}, {pz}) outside playable bounds ({}, {})", play.x, play.y ); assert!( px.abs() <= he && pz.abs() <= he, "{label}: placed mesh vertex ({px}, {pz}) outside terrain half_extent {he}" ); } // Biome-aware skirt height check + NavGrid clamping check let skirt_x = play.x + (he - play.x) * 0.75; let skirt_h = world.height_grid.height_at(skirt_x, 0.0); if label == "island_12x12_64m" { assert!(skirt_h < 0.0, "{label}: WaterLake border skirt should remain underwater, got {skirt_h}"); } else { assert!(skirt_h > 4.0, "{label}: land border skirt should rise cleanly above sea level, got {skirt_h}"); } let nav = &world.nav_grid; for iz in 0..nav.cells_per_side { let z = -nav.half_extent + (iz as f32 + 0.5) * nav.cell_size; for ix in 0..nav.cells_per_side { let x = -nav.half_extent + (ix as f32 + 0.5) * nav.cell_size; if nav.cells[iz * nav.cells_per_side + ix].is_walkable() { assert!( x.abs() <= play.x + nav.cell_size && z.abs() <= play.y + nav.cell_size, "{label}: walkable nav cell ({x}, {z}) leaked outside playable bounds" ); } } } } } #[test] fn test_sculpt_empty_project_registry_has_no_cold_water_starters() { let dir = make_temp_project_dir("empty_sculpt_proj"); let mods = ModRegistry::load_project_dir(&dir, false); assert!(mods.weapons.is_empty(), "Sculpt project must not seed Cold Water weapons"); assert!(mods.vehicles.is_empty(), "Sculpt project must not seed Cold Water vehicles"); assert!(mods.maps.is_empty(), "Sculpt project must not seed Cold Water maps"); assert!(mods.stamps.is_empty(), "Sculpt project must not seed Cold Water stamps"); assert!( !mods.mapgen_palettes.is_empty(), "Sculpt project should still have an engine default MapGenPalette" ); let _ = std::fs::remove_dir_all(&dir); } #[test] fn test_custom_grid_painting_tools_and_json_roundtrip() { let dir = make_temp_project_dir("grid_roundtrip"); let mut g = CustomGridSpec::new(12, 10, GridCellScope::District64m, ZoneType::OpenField); g.paint_line(0, 5, 11, 5, 1, ZoneType::RiverCrossing); assert_eq!(g.get(6, 5), ZoneType::RiverCrossing); g.paint_circle(2, 2, 2, ZoneType::SovietCityCore); assert_eq!(g.get(2, 2), ZoneType::SovietCityCore); g.flood_fill(9, 1, ZoneType::Forest); assert_eq!(g.get(9, 1), ZoneType::Forest); // Flood fill must not cross the RiverCrossing barrier at z=5 assert_eq!(g.get(9, 8), ZoneType::OpenField); g.resize(16, 12, ZoneType::FoothillRidge); assert_eq!(g.width, 16); assert_eq!(g.height, 12); assert_eq!(g.get(15, 11), ZoneType::FoothillRidge); assert_eq!(g.get(6, 5), ZoneType::RiverCrossing); let path = dir.join("grids").join("roundtrip_test.cwgrid.json"); g.save(&path).expect("save .cwgrid.json"); let loaded = CustomGridSpec::load(&path).expect("load .cwgrid.json"); assert_eq!(g, loaded); let _ = std::fs::remove_dir_all(&dir); } #[test] fn test_custom_grid_buildings_are_csg_destructible() { let mut spec = CustomGridSpec::new(16, 16, GridCellScope::District64m, ZoneType::OpenField); spec.apply_template(GridTemplateKind::ValleyRiver, 909); let world = DynamicMapGenerator::new(MapGenConfig::custom_grid(spec, 909)).build(); assert!( world.destructible.buildings.len() >= 10, "expected >= 10 destructible buildings on 16x16 grid, got {}", world.destructible.buildings.len() ); let first_aabb = world .destructible .structures .iter() .find(|s| s.building_id.is_some() && !s.polys.is_empty()) .expect("first building panel") .aabb; let first_panel = (first_aabb.min + first_aabb.max) * 0.5; let last_aabb = world .destructible .structures .iter() .rev() .find(|s| s.building_id.is_some() && !s.polys.is_empty()) .expect("last building panel") .aabb; let last_panel = (last_aabb.min + last_aabb.max) * 0.5; assert_ne!(first_panel, last_panel); let mut sim = Simulation::new(&world); let base_end = world .destructible .base_acoustic_tri_count .min(world.acoustic_triangles.len()); sim.set_initial_bvh(Arc::new(AcousticBvh::build_split( world.acoustic_triangles[..base_end].to_vec(), &world.destructible, ))); assert!( sim.apply_destruction_crater_batched(first_panel, 2.2, 42), "expected first grid building panel to carve" ); assert!( sim.apply_destruction_crater_batched(last_panel, 2.2, 43), "expected last grid building panel to carve (not capped out)" ); let new_bvh = sim.flush_destruction_updates(); assert!(new_bvh.is_some(), "expected updated DynamicBvh after CSG craters"); assert!(sim.destructible.revision >= 2); assert!(sim.take_world_geometry_dirty()); } #[test] fn test_custom_grid_wide_and_oriented_rivers_have_no_mud_ridges_and_bank_to_bank_bridges() { // 1. Wide multi-cell river flanked by lakes (reproducing parallel mud ridge & fragmented bridge bug) let mut wide_spec = CustomGridSpec::new(9, 7, GridCellScope::District64m, ZoneType::OpenField); for gz in 0..7 { for gx in 2..=6 { let zt = if (2..=4).contains(&gz) { ZoneType::RiverCrossing } else { ZoneType::WaterLake }; wide_spec.set(gx, gz, zt); } } let wide_world = DynamicMapGenerator::new(MapGenConfig::custom_grid(wide_spec, 4242)).build(); let wl = wide_world.height_grid.water_level; assert!(wl > -10.0, "expected water level enabled"); // Sample straight across the 5-cell-wide river interior (-128m..+128m at z=0) -> ZERO mud ridges! for step in 0..=32 { let x = -128.0 + (step as f32 / 32.0) * 256.0; let h = wide_world.height_grid.height_at(x, 0.0); assert!( h < wl - 0.5, "expected continuous submerged riverbed across 5-cell wide river at x={x:.1}, got h={h:.2} vs wl={wl:.2}" ); } // All water mesh vertices must sit strictly flat at water_level (no climbing bank ramps) assert!(!wide_world.water_vertices.is_empty(), "expected water vertices on wide river"); for wv in &wide_world.water_vertices { assert!( (wv.position[1] - wl).abs() < 1e-4, "water vertex sloped above/below water_level: y={} vs wl={}", wv.position[1], wl ); } // Bank-to-bank bridge(s) must span East-West (!span_along_z) onto both dry banks and support A* crossing assert!( !wide_world.nav_grid.bridges.is_empty() && wide_world.nav_grid.bridges.len() <= 2, "expected 1-2 clean crossing bridges across wide river, got {}", wide_world.nav_grid.bridges.len() ); let b = wide_world.nav_grid.bridges[0]; assert!(!b.span_along_z, "expected East-West bridge spanning North-South river"); assert!( b.half_span_x * 2.0 > 260.0, "expected full bank-to-bank bridge span > 260m across 5-cell (320m) channel, got {}", b.half_span_x * 2.0 ); let left_h = wide_world.height_grid.height_at(b.center_x - b.half_span_x, b.center_z); let right_h = wide_world.height_grid.height_at(b.center_x + b.half_span_x, b.center_z); assert!(left_h > wl + 0.4, "bridge west abutment should land on dry bank, got {left_h:.2}"); assert!(right_h > wl + 0.4, "bridge east abutment should land on dry bank, got {right_h:.2}"); let start = wide_world.nav_grid.nearest_walkable(glam::Vec3::new(-240.0, 0.0, -90.0)); let goal = wide_world.nav_grid.nearest_walkable(glam::Vec3::new(240.0, 0.0, 90.0)); let path = wide_world.nav_grid.find_path(start, goal); assert!( path.len() >= 2 && path.last().map_or(false, |p| p.distance(goal) < 8.0) && path.iter().any(|p| { p.x.abs() < 40.0 && wide_world .nav_grid .bridges .iter() .any(|br| (p.z - br.center_z).abs() < 12.0) }), "expected A* route to reach East bank across bridge, got {:?}", path ); // 2. Horizontal (East-West) river across the middle -> continuous submerged channel & North-South bridge let mut ew_spec = CustomGridSpec::new(7, 7, GridCellScope::Block32m, ZoneType::OpenField); for gx in 0..7 { ew_spec.set(gx, 3, ZoneType::RiverCrossing); } let ew_world = DynamicMapGenerator::new(MapGenConfig::custom_grid(ew_spec, 5151)).build(); let ew_wl = ew_world.height_grid.water_level; for step in 0..=24 { let x = -96.0 + (step as f32 / 24.0) * 192.0; let h = ew_world.height_grid.height_at(x, 0.0); assert!( h < ew_wl - 0.5, "expected continuous East-West river channel at x={x:.1}, got h={h:.2}" ); } assert!( ew_world.nav_grid.bridges.iter().any(|br| br.span_along_z), "expected North-South bridge (span_along_z=true) across East-West river" ); let n_bridge = ew_world.nav_grid.bridges.iter().find(|br| br.span_along_z).unwrap(); let north_p = ew_world.nav_grid.nearest_walkable(glam::Vec3::new(-64.0, 0.0, -80.0)); let south_p = ew_world.nav_grid.nearest_walkable(glam::Vec3::new(64.0, 0.0, 80.0)); let ew_path = ew_world.nav_grid.find_path(north_p, south_p); let crossed_ns_bridge = ew_path .windows(2) .any(|seg| { let a = seg[0]; let b = seg[1]; (a.z <= 0.0 && b.z >= 0.0) && ew_world .nav_grid .bridges .iter() .any(|br| br.span_along_z && (a.x - br.center_x).abs() < 16.0 && (b.x - br.center_x).abs() < 16.0) }); assert!( ew_path.len() >= 2 && ew_path.last().map_or(false, |p| p.distance(south_p) < 8.0) && crossed_ns_bridge, "expected A* route across North-South bridge (x={:.1}) over East-West river, got {:?}", n_bridge.center_x, ew_path ); }