Skip to main content

wde_terrain_editor/
lib.rs

1//! Terrain editor for WaterDropEngine.
2//!
3//! Gives each spawned terrain (see `wde-terrain`) a paint brush, and edits it on the GPU:
4//! the brush turns mouse strokes on the terrain into paint commands, run by a compute pass on the
5//! chunk maps. Painting modes edit the splat maps (paint, erase), the others the heightmaps (raise,
6//! lower, smooth, flatten). Edited chunks are read back to update the terrain heights and
7//! colliders.
8//!
9//! The editor windows are in the `Terrain` menu:
10//! - `Terrain/Paint`: brush mode, radius, strength and color.
11//! - `Terrain/Settings`: tiling and height blending of the ground materials.
12//! - `Terrain/Save`: writes the edited maps back to the PNG files of the terrain in `res/`.
13//!
14//! The `Debug/Terrain` window tints the terrain with its masks (buildable, slope), and reads them
15//! under the cursor.
16use wde_logger::prelude::*;
17
18use bevy::prelude::*;
19use wde_terrain::prelude::*;
20
21use crate::{
22    paint::{brush::PaintBrush, paint_manager::PaintManagerPlugin},
23    processor::PaintProcessorPlugin,
24    ui_painter::TerrainEditorUIPlugin
25};
26
27mod paint;
28mod processor;
29mod ui_painter;
30
31pub struct TerrainEditorPlugin;
32impl Plugin for TerrainEditorPlugin {
33    fn build(&self, app: &mut App) {
34        app.add_plugins((
35            PaintManagerPlugin,
36            PaintProcessorPlugin,
37            TerrainEditorUIPlugin
38        ))
39        .init_resource::<SaveManager>()
40        .add_systems(Update, add_brush)
41        .add_systems(Update, handle_extracted_tiles)
42        .add_message::<ExtractedTileMessage>();
43    }
44}
45
46fn add_brush(mut commands: Commands, terrains: Query<Entity, Added<Terrain>>) {
47    for terrain in &terrains {
48        commands.spawn((
49            Name::new("Terrain Default Brush"),
50            PaintBrush::default(),
51            ChildOf(terrain)
52        ));
53    }
54}
55
56#[derive(Resource, Default)]
57struct SaveManager {
58    saving: bool,
59    tiles_to_save: Vec<(ChunkPos, u32, u32)>
60}
61
62/// Handle all tile readbacks from the GPU:
63/// - Always update physics and the CPU heights when a heightmap arrives.
64/// - When in save mode, also write the tile to disk (without its border, as loaded).
65fn handle_extracted_tiles(
66    mut terrain: Query<&mut Terrain>,
67    mut save_manager: ResMut<SaveManager>,
68    mut extracted_tiles: MessageReader<ExtractedTileMessage>
69) {
70    let mut terrain = match terrain.single_mut() {
71        Ok(t) => t,
72        Err(_) => return
73    };
74
75    for message in extracted_tiles.read() {
76        let ExtractedTileMessage {
77            pos,
78            map_type,
79            splat_map_index,
80            data
81        } = message;
82
83        if *map_type == 0 {
84            terrain.dirty_physics.push((*pos, 0, 0, data.clone()));
85            terrain.set_chunk_heights(*pos, data);
86        }
87
88        // Optionally save to disk.
89        if save_manager.saving {
90            let folder = Terrain::folder(&terrain.path);
91            let result = match map_type {
92                0 => save_heightmap(
93                    &format!("{folder}/{}", terrain.config.heightmap_file(*pos)),
94                    data
95                ),
96                1 => save_splatmap(
97                    &format!(
98                        "{folder}/{}",
99                        terrain.config.splatmap_file(*pos, *splat_map_index)
100                    ),
101                    data
102                ),
103                _ => continue
104            };
105            if let Err(e) = result {
106                error!("Failed to save terrain tile ({}, {}): {}", pos.x, pos.y, e);
107            }
108            save_manager
109                .tiles_to_save
110                .retain(|(p, t, s)| !(p == pos && t == map_type && s == splat_map_index));
111        }
112    }
113
114    if save_manager.saving && save_manager.tiles_to_save.is_empty() {
115        info!("Finished saving terrain.");
116        save_manager.saving = false;
117    }
118}
119
120/// Saves the chunk samples of a GPU heightmap as a 16-bit grayscale PNG.
121fn save_heightmap(path: &str, map: &[u8]) -> Result<(), String> {
122    let data: Vec<u8> = chunk_samples(map)
123        .iter()
124        .flat_map(|h| ((h.clamp(0.0, 1.0) * u16::MAX as f32).round() as u16).to_be_bytes())
125        .collect();
126    write_png(
127        path,
128        &data,
129        png::ColorType::Grayscale,
130        png::BitDepth::Sixteen
131    )
132}
133
134/// Saves the chunk samples of a GPU splat map as an RGBA PNG.
135fn save_splatmap(path: &str, map: &[u8]) -> Result<(), String> {
136    let size = CHUNK_MAP_SIZE as usize;
137    let data: Vec<u8> = (1..size - 1)
138        .flat_map(|z| (1..size - 1).map(move |x| (z * size + x) * 4))
139        .flat_map(|i| map[i..i + 4].to_vec())
140        .collect();
141    write_png(path, &data, png::ColorType::Rgba, png::BitDepth::Eight)
142}
143
144fn write_png(
145    path: &str,
146    data: &[u8],
147    color: png::ColorType,
148    depth: png::BitDepth
149) -> Result<(), String> {
150    let file =
151        std::fs::File::create(path).map_err(|e| format!("Failed to create file {path}: {e}"))?;
152    let mut encoder =
153        png::Encoder::new(std::io::BufWriter::new(file), CHUNK_SAMPLES, CHUNK_SAMPLES);
154    encoder.set_color(color);
155    encoder.set_depth(depth);
156    let mut writer = encoder
157        .write_header()
158        .map_err(|e| format!("Failed to write PNG header: {e}"))?;
159    writer
160        .write_image_data(data)
161        .map_err(|e| format!("Failed to write PNG data: {e}"))
162}