src/tilemap.rs 10.6 K · 317 lines · raw · history

1 use bevy::{
2 asset::RenderAssetUsages,
3 prelude::*,
4 render::render_resource::{Extent3d, TextureDimension, TextureFormat},
5 sprite_render::{AlphaMode2d, TileData, TilemapChunk, TilemapChunkTileData},
6 };
7
8 use crate::{
9 world::{MAX_HEIGHT, Plant, TILE_SIZE, Terrain, WorldMap, hash2},
10 worldgen::WorldGenerated,
11 };
12
13 pub const CHUNK_SIZE: u32 = 64;
14 const TEXTURE_SIZE: u32 = 16;
15 const RELIEF: f32 = 0.35;
16 const LIGHT: Vec3 = Vec3::new(-1.0, 1.0, 1.5);
17
18 type Texture = Vec<[u8; 4]>;
19
20 pub struct TilemapPlugin;
21
22 impl Plugin for TilemapPlugin {
23 fn build(&self, app: &mut App) {
24 app.add_systems(Startup, spawn_chunks)
25 .add_systems(Update, refresh_chunks.run_if(on_message::<WorldGenerated>));
26 }
27 }
28
29 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
30 enum Layer {
31 Terrain,
32 Plants,
33 }
34
35 impl Layer {
36 fn z(self) -> f32 {
37 match self {
38 Layer::Terrain => 0.0,
39 Layer::Plants => 0.5,
40 }
41 }
42
43 fn tiles(self, map: &WorldMap, origin: UVec2) -> Vec<Option<TileData>> {
44 match self {
45 Layer::Terrain => chunk_tiles(map, origin),
46 Layer::Plants => plant_tiles(map, origin),
47 }
48 }
49 }
50
51 #[derive(Component)]
52 struct Chunk {
53 origin: UVec2,
54 layer: Layer,
55 }
56
57 fn spawn_chunks(mut commands: Commands, map: Res<WorldMap>, mut images: ResMut<Assets<Image>>) {
58 let terrain = images.add(stack_tileset(
59 Terrain::ALL.iter().map(|&t| terrain_texture(t)).collect(),
60 ));
61 let plants = images.add(stack_tileset(
62 Plant::ALL.iter().map(|&p| plant_texture(p)).collect(),
63 ));
64 let chunks = (map.size + CHUNK_SIZE - 1) / CHUNK_SIZE;
65 for (layer, tileset) in [(Layer::Terrain, terrain), (Layer::Plants, plants)] {
66 for cy in 0..chunks.y {
67 for cx in 0..chunks.x {
68 let origin = UVec2::new(cx, cy) * CHUNK_SIZE;
69 let center = (origin.as_vec2() + CHUNK_SIZE as f32 / 2.0) * TILE_SIZE;
70 commands.spawn((
71 Name::new(format!("{layer:?} chunk {cx},{cy}")),
72 Chunk { origin, layer },
73 TilemapChunk {
74 chunk_size: UVec2::splat(CHUNK_SIZE),
75 tile_display_size: UVec2::splat(TILE_SIZE as u32),
76 tileset: tileset.clone(),
77 alpha_mode: AlphaMode2d::Blend,
78 },
79 TilemapChunkTileData(layer.tiles(&map, origin)),
80 Transform::from_translation(center.extend(layer.z())),
81 ));
82 }
83 }
84 }
85 }
86
87 fn refresh_chunks(map: Res<WorldMap>, mut chunks: Query<(&Chunk, &mut TilemapChunkTileData)>) {
88 for (chunk, mut data) in &mut chunks {
89 data.0 = chunk.layer.tiles(&map, chunk.origin);
90 }
91 }
92
93 fn chunk_positions(origin: UVec2) -> impl Iterator<Item = UVec2> {
94 (0..CHUNK_SIZE).flat_map(move |y| (0..CHUNK_SIZE).map(move |x| origin + UVec2::new(x, y)))
95 }
96
97 pub fn chunk_tiles(map: &WorldMap, origin: UVec2) -> Vec<Option<TileData>> {
98 chunk_positions(origin)
99 .map(|pos| {
100 map.get(pos.as_ivec2()).map(|terrain| TileData {
101 tileset_index: terrain.index(),
102 color: tint(jitter(pos) * shade(map, pos)),
103 ..default()
104 })
105 })
106 .collect()
107 }
108
109 pub fn plant_tiles(map: &WorldMap, origin: UVec2) -> Vec<Option<TileData>> {
110 chunk_positions(origin)
111 .map(|pos| {
112 map.plant(pos.as_ivec2()).map(|plant| TileData {
113 tileset_index: plant.index(),
114 color: tint(jitter(pos) * hillshade(map, pos)),
115 ..default()
116 })
117 })
118 .collect()
119 }
120
121 fn tint(v: f32) -> Color {
122 Color::srgb(v, v, v)
123 }
124
125 fn jitter(pos: UVec2) -> f32 {
126 0.92 + (hash2(pos.x, pos.y) % 9) as f32 * 0.01
127 }
128
129 fn shade(map: &WorldMap, pos: UVec2) -> f32 {
130 match map.get(pos.as_ivec2()) {
131 Some(t) if t.is_water() => 1.0,
132 _ => hillshade(map, pos) * height_brightness(map, pos),
133 }
134 }
135
136 fn height_brightness(map: &WorldMap, pos: UVec2) -> f32 {
137 0.9 + 0.2 * map.height(pos.as_ivec2()).unwrap_or(0.0) / MAX_HEIGHT
138 }
139
140 pub fn hillshade(map: &WorldMap, pos: UVec2) -> f32 {
141 let p = pos.as_ivec2();
142 let center = map.height(p).unwrap_or(0.0);
143 let h = |d: IVec2| map.height(p + d).unwrap_or(center);
144 let dx = (h(IVec2::X) - h(IVec2::NEG_X)) / 2.0;
145 let dy = (h(IVec2::Y) - h(IVec2::NEG_Y)) / 2.0;
146 let normal = Vec3::new(-dx * RELIEF, -dy * RELIEF, 1.0).normalize();
147 let light = LIGHT.normalize();
148 (normal.dot(light) / light.z).clamp(0.6, 1.25)
149 }
150
151 fn terrain_texture(terrain: Terrain) -> Texture {
152 let base = terrain.color();
153 let layer = terrain.index() as u32;
154 (0..TEXTURE_SIZE * TEXTURE_SIZE)
155 .map(|i| {
156 let speck = terrain
157 .speck_color()
158 .filter(|_| hash2(i / 2 + i / 32, layer) % 5 == 0);
159 let jitter = (hash2(i, layer) % 16) as f32 / 255.0 - 8.0 / 255.0;
160 let c = speck.unwrap_or(base);
161 Srgba::new(c.red + jitter, c.green + jitter, c.blue + jitter, 1.0).to_u8_array()
162 })
163 .collect()
164 }
165
166 fn plant_texture(plant: Plant) -> Texture {
167 match plant {
168 Plant::Tree => tree_texture(),
169 }
170 }
171
172 fn tree_texture() -> Texture {
173 let leaves = Srgba::rgb_u8(38, 92, 42);
174 let highlight = Srgba::rgb_u8(66, 126, 58);
175 let trunk = Srgba::rgb_u8(92, 64, 40);
176 let canopy_center = Vec2::new(7.5, 6.5);
177 (0..TEXTURE_SIZE * TEXTURE_SIZE)
178 .map(|i| {
179 let (x, y) = (i % TEXTURE_SIZE, i / TEXTURE_SIZE);
180 let p = Vec2::new(x as f32, y as f32);
181 let from_center = p - canopy_center;
182 if from_center.length() <= 6.0 {
183 let lit = from_center.dot(Vec2::new(-1.0, -1.0)) > 3.0;
184 if lit { highlight } else { leaves }.to_u8_array()
185 } else if (7..=8).contains(&x) && y >= 12 && y <= 14 {
186 trunk.to_u8_array()
187 } else {
188 [0, 0, 0, 0]
189 }
190 })
191 .collect()
192 }
193
194 pub fn tileset_layer_count(textures: u32) -> u32 {
195 match textures {
196 0 | 1 => 2,
197 n if n % 6 == 0 => n + 1,
198 n => n,
199 }
200 }
201
202 fn stack_tileset(textures: Vec<Texture>) -> Image {
203 let layers = tileset_layer_count(textures.len() as u32);
204 let empty = vec![[0, 0, 0, 0]; (TEXTURE_SIZE * TEXTURE_SIZE) as usize];
205 let data = (0..layers as usize)
206 .flat_map(|i| textures.get(i).unwrap_or(&empty).clone())
207 .flatten()
208 .collect();
209 let mut image = Image::new(
210 Extent3d {
211 width: TEXTURE_SIZE,
212 height: TEXTURE_SIZE * layers,
213 depth_or_array_layers: 1,
214 },
215 TextureDimension::D2,
216 data,
217 TextureFormat::Rgba8UnormSrgb,
218 RenderAssetUsages::RENDER_WORLD,
219 );
220 image
221 .reinterpret_stacked_2d_as_array(layers)
222 .expect("tileset is a vertical stack of square layers");
223 image
224 }
225
226 #[cfg(test)]
227 mod tests {
228 use super::*;
229
230 #[test]
231 fn chunk_tiles_beyond_map_edge_are_empty() {
232 let map = WorldMap::filled(UVec2::new(CHUNK_SIZE + 2, 3), Terrain::Stone);
233 let tiles = chunk_tiles(&map, UVec2::new(CHUNK_SIZE, 0));
234 assert_eq!(tiles.len(), (CHUNK_SIZE * CHUNK_SIZE) as usize);
235 assert!(tiles[0].is_some());
236 assert!(tiles[1].is_some());
237 assert!(tiles[2].is_none());
238 assert!(tiles[CHUNK_SIZE as usize * 3].is_none());
239 }
240
241 // Chunk entities live for the whole session. World changes (regeneration now, digging and
242 // building later) rewrite their tile data in place; TilemapChunk re-uploads it through change
243 // detection, so no entities, meshes or materials are recreated.
244 #[test]
245 fn regeneration_rewrites_tile_data_of_existing_chunks() {
246 let mut app = App::new();
247 app.insert_resource(WorldMap::filled(UVec2::splat(CHUNK_SIZE), Terrain::Grass))
248 .add_message::<WorldGenerated>()
249 .add_systems(Update, refresh_chunks.run_if(on_message::<WorldGenerated>));
250 let map = app.world().resource::<WorldMap>().clone();
251 let chunk = app
252 .world_mut()
253 .spawn((
254 Chunk {
255 origin: UVec2::ZERO,
256 layer: Layer::Terrain,
257 },
258 TilemapChunkTileData(chunk_tiles(&map, UVec2::ZERO)),
259 ))
260 .id();
261
262 *app.world_mut().resource_mut::<WorldMap>() =
263 WorldMap::filled(UVec2::splat(CHUNK_SIZE), Terrain::Stone);
264 app.world_mut().write_message(WorldGenerated);
265 app.update();
266
267 let data = app.world().get::<TilemapChunkTileData>(chunk).unwrap();
268 assert!(
269 data.0
270 .iter()
271 .all(|t| t.unwrap().tileset_index == Terrain::Stone.index())
272 );
273 }
274
275 #[test]
276 fn tileset_has_a_layer_for_every_texture() {
277 let textures = Terrain::ALL.iter().map(|&t| terrain_texture(t)).collect();
278 let image = stack_tileset(textures);
279 assert!(image.texture_descriptor.size.depth_or_array_layers >= Terrain::ALL.len() as u32);
280 }
281
282 #[test]
283 fn plant_layer_only_has_tiles_where_plants_grow() {
284 let mut map = WorldMap::filled(UVec2::splat(4), Terrain::Grass);
285 map.set_plant(UVec2::new(1, 0), Some(Plant::Tree));
286 let tiles = plant_tiles(&map, UVec2::ZERO);
287 assert!(tiles[0].is_none());
288 assert_eq!(tiles[1].unwrap().tileset_index, Plant::Tree.index());
289 }
290
291 // Light comes from the north-west (LIGHT has -x, +y), the convention for hillshaded maps.
292 #[test]
293 fn slopes_facing_the_light_are_brighter_than_slopes_facing_away() {
294 let mut map = WorldMap::filled(UVec2::new(5, 1), Terrain::Grass);
295 for (x, h) in [0.0, 5.0, 10.0, 5.0, 0.0].into_iter().enumerate() {
296 map.set_height(UVec2::new(x as u32, 0), h);
297 }
298 let flat = WorldMap::filled(UVec2::new(3, 1), Terrain::Grass);
299 let facing_west = hillshade(&map, UVec2::new(1, 0));
300 let facing_east = hillshade(&map, UVec2::new(3, 0));
301 let level = hillshade(&flat, UVec2::new(1, 0));
302 assert!(facing_west > level);
303 assert!(facing_east < level);
304 }
305
306 // wgpu's GLES backend (WebGL2) guesses the texture view dimension from the layer count:
307 // 1 layer => D2, 6 => Cube, multiples of 6 => CubeArray. The tilemap shader needs D2Array,
308 // so the tileset is padded with an unused layer to dodge those counts.
309 #[test]
310 fn tileset_layer_count_avoids_webgl_view_dimension_heuristics() {
311 for n in 0..50 {
312 let layers = tileset_layer_count(n);
313 assert!(layers >= n.max(2));
314 assert!(layers % 6 != 0, "{n} terrains -> {layers} layers");
315 }
316 }
317 }