src/tilemap.rs 23.5 K · 721 lines · raw · history

1 use std::time::Duration;
2
3 use bevy::{
4 asset::RenderAssetUsages,
5 image::ImageSampler,
6 prelude::*,
7 render::render_resource::{Extent3d, TextureDimension, TextureFormat},
8 sprite_render::{AlphaMode2d, TileData, TilemapChunk, TilemapChunkTileData},
9 };
10
11 use crate::{
12 light::LightMap,
13 world::{MAX_HEIGHT, Plant, TILE_SIZE, Terrain, TileChanged, WorldMap, hash2},
14 worldgen::WorldGenerated,
15 zones::Zones,
16 };
17
18 pub const CHUNK_SIZE: u32 = 64;
19 const TEXTURE_SIZE: u32 = 16;
20 const RELIEF: f32 = 0.35;
21 const LIGHT: Vec3 = Vec3::new(-1.0, 1.0, 1.5);
22 const SHADE_FLAT: f32 = 1.1;
23 const MAX_SHADOW: f32 = 0.5;
24 const HILL_SHADE_Z: f32 = 0.1;
25 const LIGHT_REFRESH_INTERVAL: Duration = Duration::from_millis(100);
26
27 type Texture = Vec<[u8; 4]>;
28
29 pub struct TilemapPlugin;
30
31 impl Plugin for TilemapPlugin {
32 fn build(&self, app: &mut App) {
33 app.add_systems(Startup, spawn_chunks).add_systems(
34 Update,
35 (
36 refresh_chunks.run_if(world_or_light_changed),
37 refresh_changed_chunks,
38 refresh_zone_chunks.run_if(resource_changed::<Zones>),
39 refresh_hill_shade.run_if(on_message::<WorldGenerated>),
40 ),
41 );
42 }
43 }
44
45 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
46 enum Layer {
47 Terrain,
48 Snow,
49 Zones,
50 Roofs,
51 Plants,
52 }
53
54 impl Layer {
55 fn z(self) -> f32 {
56 match self {
57 Layer::Terrain => 0.0,
58 Layer::Snow => 0.2,
59 Layer::Zones => 0.3,
60 Layer::Roofs => 0.85,
61 Layer::Plants => 0.5,
62 }
63 }
64
65 fn tiles(
66 self,
67 map: &WorldMap,
68 zones: &Zones,
69 light: &LightMap,
70 origin: UVec2,
71 ) -> Vec<Option<TileData>> {
72 match self {
73 Layer::Terrain => chunk_tiles(map, light, origin),
74 Layer::Snow => snow_tiles(map, light, origin),
75 Layer::Zones => zone_tiles(zones, origin),
76 Layer::Roofs => roof_tiles(map, origin),
77 Layer::Plants => plant_tiles(map, light, origin),
78 }
79 }
80 }
81
82 #[derive(Component)]
83 struct Chunk {
84 origin: UVec2,
85 layer: Layer,
86 }
87
88 #[derive(Component)]
89 struct HillShade;
90
91 pub fn shadow_alpha(shade: f32) -> u8 {
92 ((SHADE_FLAT - shade).clamp(0.0, MAX_SHADOW) * 255.0) as u8
93 }
94
95 fn hill_shade_image(map: &WorldMap) -> Image {
96 let mut data = Vec::with_capacity((map.size.element_product() * 4) as usize);
97 for row in 0..map.size.y {
98 let y = map.size.y - 1 - row;
99 for x in 0..map.size.x {
100 let pos = UVec2::new(x, y);
101 let water = map.get(pos.as_ivec2()).is_some_and(|t| t.is_water());
102 let alpha = if water {
103 0
104 } else {
105 shadow_alpha(hillshade(map, pos))
106 };
107 data.extend_from_slice(&[0, 0, 0, alpha]);
108 }
109 }
110 let mut image = Image::new(
111 Extent3d {
112 width: map.size.x,
113 height: map.size.y,
114 depth_or_array_layers: 1,
115 },
116 TextureDimension::D2,
117 data,
118 TextureFormat::Rgba8UnormSrgb,
119 RenderAssetUsages::default(),
120 );
121 image.sampler = ImageSampler::linear();
122 image
123 }
124
125 fn refresh_hill_shade(
126 map: Res<WorldMap>,
127 shade: Single<&MeshMaterial2d<ColorMaterial>, With<HillShade>>,
128 materials: Res<Assets<ColorMaterial>>,
129 mut images: ResMut<Assets<Image>>,
130 ) {
131 if let Some(texture) = materials.get(&shade.0).and_then(|m| m.texture.clone()) {
132 let _ = images.insert(&texture, hill_shade_image(&map));
133 }
134 }
135
136 #[allow(clippy::too_many_arguments)]
137 fn spawn_chunks(
138 mut commands: Commands,
139 map: Res<WorldMap>,
140 zones: Res<Zones>,
141 light: Res<LightMap>,
142 mut images: ResMut<Assets<Image>>,
143 mut meshes: ResMut<Assets<Mesh>>,
144 mut materials: ResMut<Assets<ColorMaterial>>,
145 ) {
146 let shade = images.add(hill_shade_image(&map));
147 commands.spawn((
148 HillShade,
149 Name::new("Hill shade"),
150 Mesh2d(meshes.add(Rectangle::from_size(map.world_size()))),
151 MeshMaterial2d(materials.add(ColorMaterial {
152 texture: Some(shade),
153 ..default()
154 })),
155 Transform::from_translation((map.world_size() / 2.0).extend(HILL_SHADE_Z)),
156 ));
157 let terrain = images.add(stack_tileset(
158 Terrain::ALL.iter().map(|&t| terrain_texture(t)).collect(),
159 ));
160 let plants = images.add(stack_tileset(
161 PlantLook::ALL
162 .iter()
163 .map(|&look| plant_texture(look))
164 .collect(),
165 ));
166 let zone = images.add(stack_tileset(vec![zone_texture(), farm_texture()]));
167 let roof = images.add(stack_tileset(vec![roof_texture()]));
168 let snow = images.add(stack_tileset(vec![snow_texture()]));
169 let chunks = (map.size + CHUNK_SIZE - 1) / CHUNK_SIZE;
170 for (layer, tileset) in [
171 (Layer::Terrain, terrain),
172 (Layer::Snow, snow),
173 (Layer::Zones, zone),
174 (Layer::Plants, plants),
175 (Layer::Roofs, roof),
176 ] {
177 for cy in 0..chunks.y {
178 for cx in 0..chunks.x {
179 let origin = UVec2::new(cx, cy) * CHUNK_SIZE;
180 let center = (origin.as_vec2() + CHUNK_SIZE as f32 / 2.0) * TILE_SIZE;
181 commands.spawn((
182 Name::new(format!("{layer:?} chunk {cx},{cy}")),
183 Chunk { origin, layer },
184 TilemapChunk {
185 chunk_size: UVec2::splat(CHUNK_SIZE),
186 tile_display_size: UVec2::splat(TILE_SIZE as u32),
187 tileset: tileset.clone(),
188 alpha_mode: AlphaMode2d::Blend,
189 },
190 TilemapChunkTileData(layer.tiles(&map, &zones, &light, origin)),
191 Transform::from_translation(center.extend(layer.z())),
192 ));
193 }
194 }
195 }
196 }
197
198 fn refresh_chunks(
199 map: Res<WorldMap>,
200 zones: Res<Zones>,
201 light: Res<LightMap>,
202 mut chunks: Query<(&Chunk, &mut TilemapChunkTileData)>,
203 ) {
204 for (chunk, mut data) in &mut chunks {
205 data.0 = chunk.layer.tiles(&map, &zones, &light, chunk.origin);
206 }
207 }
208
209 pub fn light_refresh_due(pending: bool, since_last: Duration) -> bool {
210 pending && since_last >= LIGHT_REFRESH_INTERVAL
211 }
212
213 fn world_or_light_changed(
214 mut generated: MessageReader<WorldGenerated>,
215 light: Res<LightMap>,
216 real: Res<Time<Real>>,
217 mut pending: Local<bool>,
218 mut last: Local<Duration>,
219 ) -> bool {
220 *pending |= light.is_changed();
221 let now = real.elapsed();
222 let due = generated.read().count() > 0 || light_refresh_due(*pending, now - *last);
223 if due {
224 *pending = false;
225 *last = now;
226 }
227 due
228 }
229
230 fn refresh_zone_chunks(
231 map: Res<WorldMap>,
232 zones: Res<Zones>,
233 light: Res<LightMap>,
234 mut chunks: Query<(&Chunk, &mut TilemapChunkTileData)>,
235 ) {
236 for (chunk, mut data) in &mut chunks {
237 if chunk.layer == Layer::Zones {
238 data.0 = chunk.layer.tiles(&map, &zones, &light, chunk.origin);
239 }
240 }
241 }
242
243 fn refresh_changed_chunks(
244 map: Res<WorldMap>,
245 zones: Res<Zones>,
246 light: Res<LightMap>,
247 mut changes: MessageReader<TileChanged>,
248 mut chunks: Query<(&Chunk, &mut TilemapChunkTileData)>,
249 ) {
250 let origins: Vec<UVec2> = changes
251 .read()
252 .map(|TileChanged(tile)| chunk_origin(*tile))
253 .collect();
254 for (chunk, mut data) in &mut chunks {
255 if origins.contains(&chunk.origin) {
256 data.0 = chunk.layer.tiles(&map, &zones, &light, chunk.origin);
257 }
258 }
259 }
260
261 pub fn chunk_origin(tile: UVec2) -> UVec2 {
262 tile / CHUNK_SIZE * CHUNK_SIZE
263 }
264
265 fn chunk_positions(origin: UVec2) -> impl Iterator<Item = UVec2> {
266 (0..CHUNK_SIZE).flat_map(move |y| (0..CHUNK_SIZE).map(move |x| origin + UVec2::new(x, y)))
267 }
268
269 pub fn chunk_tiles(map: &WorldMap, light: &LightMap, origin: UVec2) -> Vec<Option<TileData>> {
270 chunk_positions(origin)
271 .map(|pos| {
272 map.get(pos.as_ivec2()).map(|terrain| TileData {
273 tileset_index: terrain.index(),
274 color: tint(jitter(pos) * shade(map, pos), light.color(pos)),
275 ..default()
276 })
277 })
278 .collect()
279 }
280
281 pub fn snow_tiles(map: &WorldMap, light: &LightMap, origin: UVec2) -> Vec<Option<TileData>> {
282 let cover = light.snow();
283 chunk_positions(origin)
284 .map(|pos| {
285 let p = pos.as_ivec2();
286 let land = map.get(p).is_some_and(|t| !t.is_water());
287 (cover > 0.0 && land && !map.is_roofed(p)).then(|| {
288 let l = light.color(pos);
289 TileData {
290 tileset_index: 0,
291 color: Color::srgba(l.x, l.y, l.z, cover * jitter(pos)),
292 ..default()
293 }
294 })
295 })
296 .collect()
297 }
298
299 pub fn zone_tiles(zones: &Zones, origin: UVec2) -> Vec<Option<TileData>> {
300 chunk_positions(origin)
301 .map(|pos| {
302 zones
303 .is_stockpile(pos)
304 .then(|| TileData::from_tileset_index(0))
305 })
306 .collect()
307 }
308
309 pub fn roof_tiles(map: &WorldMap, origin: UVec2) -> Vec<Option<TileData>> {
310 chunk_positions(origin)
311 .map(|pos| {
312 map.is_roofed(pos.as_ivec2())
313 .then(|| TileData::from_tileset_index(0))
314 })
315 .collect()
316 }
317
318 pub fn plant_tiles(map: &WorldMap, light: &LightMap, origin: UVec2) -> Vec<Option<TileData>> {
319 chunk_positions(origin)
320 .map(|pos| {
321 map.plant(pos.as_ivec2()).map(|plant| TileData {
322 tileset_index: PlantLook::of(plant, map.growth(pos.as_ivec2())) as u16,
323 color: tint(jitter(pos), light.color(pos)),
324 ..default()
325 })
326 })
327 .collect()
328 }
329
330 fn tint(v: f32, light: Vec3) -> Color {
331 Color::srgb(v * light.x, v * light.y, v * light.z)
332 }
333
334 fn jitter(pos: UVec2) -> f32 {
335 0.92 + (hash2(pos.x, pos.y) % 9) as f32 * 0.01
336 }
337
338 fn shade(map: &WorldMap, pos: UVec2) -> f32 {
339 match map.get(pos.as_ivec2()) {
340 Some(t) if t.is_water() => 1.0,
341 _ => SHADE_FLAT * height_brightness(map, pos),
342 }
343 }
344
345 fn height_brightness(map: &WorldMap, pos: UVec2) -> f32 {
346 0.9 + 0.2 * map.height(pos.as_ivec2()).unwrap_or(0.0) / MAX_HEIGHT
347 }
348
349 pub fn hillshade(map: &WorldMap, pos: UVec2) -> f32 {
350 let p = pos.as_ivec2();
351 let center = map.height(p).unwrap_or(0.0);
352 let h = |d: IVec2| map.height(p + d).unwrap_or(center);
353 let dx = (h(IVec2::X) - h(IVec2::NEG_X)) / 2.0;
354 let dy = (h(IVec2::Y) - h(IVec2::NEG_Y)) / 2.0;
355 let normal = Vec3::new(-dx * RELIEF, -dy * RELIEF, 1.0).normalize();
356 let light = LIGHT.normalize();
357 (normal.dot(light) / light.z).clamp(0.6, 1.25)
358 }
359
360 fn terrain_texture(terrain: Terrain) -> Texture {
361 let base = terrain.color();
362 let layer = terrain.index() as u32;
363 (0..TEXTURE_SIZE * TEXTURE_SIZE)
364 .map(|i| {
365 let speck = terrain
366 .speck_color()
367 .filter(|_| hash2(i / 2 + i / 32, layer) % 5 == 0);
368 let jitter = (hash2(i, layer) % 16) as f32 / 255.0 - 8.0 / 255.0;
369 let (x, y) = (i % TEXTURE_SIZE, i / TEXTURE_SIZE);
370 let mortar = terrain == Terrain::Paved
371 && (y % 5 == 0 || (x + if (y / 5) % 2 == 0 { 0 } else { 4 }) % 8 == 0);
372 let c = if mortar {
373 Srgba::rgb_u8(110, 106, 100)
374 } else {
375 speck.unwrap_or(base)
376 };
377 Srgba::new(c.red + jitter, c.green + jitter, c.blue + jitter, 1.0).to_u8_array()
378 })
379 .collect()
380 }
381
382 fn zone_texture() -> Texture {
383 (0..TEXTURE_SIZE * TEXTURE_SIZE)
384 .map(|i| {
385 let (x, y) = (i % TEXTURE_SIZE, i / TEXTURE_SIZE);
386 let edge = x == 0 || y == 0 || x == TEXTURE_SIZE - 1 || y == TEXTURE_SIZE - 1;
387 [90, 160, 230, if edge { 150 } else { 55 }]
388 })
389 .collect()
390 }
391
392 fn snow_texture() -> Texture {
393 (0..TEXTURE_SIZE * TEXTURE_SIZE)
394 .map(|i| {
395 let (x, y) = (i % TEXTURE_SIZE, i / TEXTURE_SIZE);
396 let speck = hash2(x, y + 7) % 7 == 0;
397 if speck {
398 [215, 225, 240, 255]
399 } else {
400 [245, 248, 255, 255]
401 }
402 })
403 .collect()
404 }
405
406 fn roof_texture() -> Texture {
407 (0..TEXTURE_SIZE * TEXTURE_SIZE)
408 .map(|i| {
409 let (x, y) = (i % TEXTURE_SIZE, i / TEXTURE_SIZE);
410 let stripe = (x + y) % 4 == 0;
411 [110, 80, 50, if stripe { 90 } else { 45 }]
412 })
413 .collect()
414 }
415
416 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
417 pub enum PlantLook {
418 Tree,
419 Bush,
420 RipeBush,
421 Sprout,
422 YoungCrop,
423 RipeCrop,
424 }
425
426 impl PlantLook {
427 const ALL: [PlantLook; 6] = [
428 PlantLook::Tree,
429 PlantLook::Bush,
430 PlantLook::RipeBush,
431 PlantLook::Sprout,
432 PlantLook::YoungCrop,
433 PlantLook::RipeCrop,
434 ];
435
436 pub fn of(plant: Plant, growth: f32) -> Self {
437 match plant {
438 Plant::Tree => PlantLook::Tree,
439 Plant::BerryBush if plant.is_ripe(growth) => PlantLook::RipeBush,
440 Plant::BerryBush => PlantLook::Bush,
441 Plant::Crop if plant.is_ripe(growth) => PlantLook::RipeCrop,
442 Plant::Crop if growth >= SPROUT_UNTIL => PlantLook::YoungCrop,
443 Plant::Crop => PlantLook::Sprout,
444 }
445 }
446 }
447
448 pub const SPROUT_UNTIL: f32 = 0.4;
449
450 fn farm_texture() -> Texture {
451 (0..TEXTURE_SIZE * TEXTURE_SIZE)
452 .map(|i| {
453 let (x, y) = (i % TEXTURE_SIZE, i / TEXTURE_SIZE);
454 let edge = x == 0 || y == 0 || x == TEXTURE_SIZE - 1 || y == TEXTURE_SIZE - 1;
455 let furrow = x % 4 == 0;
456 match (edge, furrow) {
457 (true, _) => [150, 190, 90, 140],
458 (_, true) => [80, 56, 34, 150],
459 _ => [110, 78, 48, 110],
460 }
461 })
462 .collect()
463 }
464
465 fn plant_texture(look: PlantLook) -> Texture {
466 let leaves = Srgba::rgb_u8(52, 110, 50);
467 let berry = Srgba::rgb_u8(190, 40, 90);
468 let stalk = Srgba::rgb_u8(110, 160, 60);
469 let grain = Srgba::rgb_u8(220, 190, 80);
470 match look {
471 PlantLook::Tree => tree_texture(),
472 PlantLook::Bush => blob_texture(5.0, leaves, None),
473 PlantLook::RipeBush => blob_texture(5.0, leaves, Some(berry)),
474 PlantLook::Sprout => rows_texture(3, stalk, None),
475 PlantLook::YoungCrop => rows_texture(7, stalk, None),
476 PlantLook::RipeCrop => rows_texture(10, stalk, Some(grain)),
477 }
478 }
479
480 fn blob_texture(radius: f32, color: Srgba, dots: Option<Srgba>) -> Texture {
481 (0..TEXTURE_SIZE * TEXTURE_SIZE)
482 .map(|i| {
483 let (x, y) = (i % TEXTURE_SIZE, i / TEXTURE_SIZE);
484 let d = Vec2::new(x as f32, y as f32).distance(Vec2::new(7.5, 8.5));
485 if d > radius {
486 return [0, 0, 0, 0];
487 }
488 match dots {
489 Some(dot) if hash2(x, y) % 5 == 0 => dot.to_u8_array(),
490 _ => color.to_u8_array(),
491 }
492 })
493 .collect()
494 }
495
496 fn rows_texture(height: u32, stalk: Srgba, head: Option<Srgba>) -> Texture {
497 (0..TEXTURE_SIZE * TEXTURE_SIZE)
498 .map(|i| {
499 let (x, y) = (i % TEXTURE_SIZE, i / TEXTURE_SIZE);
500 let in_row = x % 4 == 1 || x % 4 == 2;
501 let top = TEXTURE_SIZE - 2 - height;
502 if !in_row || y < top || y >= TEXTURE_SIZE - 2 {
503 return [0, 0, 0, 0];
504 }
505 match head {
506 Some(head) if y < top + 3 => head.to_u8_array(),
507 _ => stalk.to_u8_array(),
508 }
509 })
510 .collect()
511 }
512
513 fn tree_texture() -> Texture {
514 let leaves = Srgba::rgb_u8(38, 92, 42);
515 let highlight = Srgba::rgb_u8(66, 126, 58);
516 let trunk = Srgba::rgb_u8(92, 64, 40);
517 let canopy_center = Vec2::new(7.5, 6.5);
518 (0..TEXTURE_SIZE * TEXTURE_SIZE)
519 .map(|i| {
520 let (x, y) = (i % TEXTURE_SIZE, i / TEXTURE_SIZE);
521 let p = Vec2::new(x as f32, y as f32);
522 let from_center = p - canopy_center;
523 if from_center.length() <= 6.0 {
524 let lit = from_center.dot(Vec2::new(-1.0, -1.0)) > 3.0;
525 if lit { highlight } else { leaves }.to_u8_array()
526 } else if (7..=8).contains(&x) && y >= 12 && y <= 14 {
527 trunk.to_u8_array()
528 } else {
529 [0, 0, 0, 0]
530 }
531 })
532 .collect()
533 }
534
535 pub fn tileset_layer_count(textures: u32) -> u32 {
536 match textures {
537 0 | 1 => 2,
538 n if n % 6 == 0 => n + 1,
539 n => n,
540 }
541 }
542
543 fn stack_tileset(textures: Vec<Texture>) -> Image {
544 let layers = tileset_layer_count(textures.len() as u32);
545 let empty = vec![[0, 0, 0, 0]; (TEXTURE_SIZE * TEXTURE_SIZE) as usize];
546 let data = (0..layers as usize)
547 .flat_map(|i| textures.get(i).unwrap_or(&empty).clone())
548 .flatten()
549 .collect();
550 let mut image = Image::new(
551 Extent3d {
552 width: TEXTURE_SIZE,
553 height: TEXTURE_SIZE * layers,
554 depth_or_array_layers: 1,
555 },
556 TextureDimension::D2,
557 data,
558 TextureFormat::Rgba8UnormSrgb,
559 RenderAssetUsages::RENDER_WORLD,
560 );
561 image
562 .reinterpret_stacked_2d_as_array(layers)
563 .expect("tileset is a vertical stack of square layers");
564 image
565 }
566
567 #[cfg(test)]
568 mod tests {
569 use super::*;
570
571 #[test]
572 fn chunk_tiles_beyond_map_edge_are_empty() {
573 let map = WorldMap::filled(UVec2::new(CHUNK_SIZE + 2, 3), Terrain::Stone);
574 let tiles = chunk_tiles(&map, &LightMap::default(), UVec2::new(CHUNK_SIZE, 0));
575 assert_eq!(tiles.len(), (CHUNK_SIZE * CHUNK_SIZE) as usize);
576 assert!(tiles[0].is_some());
577 assert!(tiles[1].is_some());
578 assert!(tiles[2].is_none());
579 assert!(tiles[CHUNK_SIZE as usize * 3].is_none());
580 }
581
582 // Chunk entities live for the whole session. World changes (regeneration now, digging and
583 // building later) rewrite their tile data in place; TilemapChunk re-uploads it through change
584 // detection, so no entities, meshes or materials are recreated.
585 #[test]
586 fn regeneration_rewrites_tile_data_of_existing_chunks() {
587 let mut app = App::new();
588 app.insert_resource(WorldMap::filled(UVec2::splat(CHUNK_SIZE), Terrain::Grass))
589 .init_resource::<Zones>()
590 .init_resource::<LightMap>()
591 .add_message::<WorldGenerated>()
592 .add_systems(Update, refresh_chunks.run_if(on_message::<WorldGenerated>));
593 let map = app.world().resource::<WorldMap>().clone();
594 let chunk = app
595 .world_mut()
596 .spawn((
597 Chunk {
598 origin: UVec2::ZERO,
599 layer: Layer::Terrain,
600 },
601 TilemapChunkTileData(chunk_tiles(&map, &LightMap::default(), UVec2::ZERO)),
602 ))
603 .id();
604
605 *app.world_mut().resource_mut::<WorldMap>() =
606 WorldMap::filled(UVec2::splat(CHUNK_SIZE), Terrain::Stone);
607 app.world_mut().write_message(WorldGenerated);
608 app.update();
609
610 let data = app.world().get::<TilemapChunkTileData>(chunk).unwrap();
611 assert!(
612 data.0
613 .iter()
614 .all(|t| t.unwrap().tileset_index == Terrain::Stone.index())
615 );
616 }
617
618 #[test]
619 fn darkness_tints_tiles_and_fires_warm_them() {
620 let map = WorldMap::filled(UVec2::splat(CHUNK_SIZE), Terrain::Grass);
621 let fire = (
622 UVec2::new(10, 10),
623 crate::structures::StructureKind::Campfire,
624 );
625 let night = LightMap::compute(&map, 0.0, [fire]);
626 let tiles = chunk_tiles(&map, &night, UVec2::ZERO);
627 let lum = |pos: UVec2| {
628 let c = tiles[(pos.y * CHUNK_SIZE + pos.x) as usize]
629 .unwrap()
630 .color
631 .to_srgba();
632 c.red + c.green + c.blue
633 };
634 assert!(lum(UVec2::new(10, 11)) > lum(UVec2::new(40, 40)) * 2.0);
635 }
636
637 #[test]
638 fn roof_layer_covers_roofed_tiles_only() {
639 let mut map = WorldMap::filled(UVec2::splat(4), Terrain::Grass);
640 map.set_roof(UVec2::new(2, 1), true);
641 let tiles = roof_tiles(&map, UVec2::ZERO);
642 assert!(tiles[(CHUNK_SIZE + 2) as usize].is_some());
643 assert_eq!(tiles.iter().filter(|t| t.is_some()).count(), 1);
644 }
645
646 #[test]
647 fn chunk_origin_rounds_down_to_chunk_grid() {
648 assert_eq!(chunk_origin(UVec2::new(0, 63)), UVec2::new(0, 0));
649 assert_eq!(chunk_origin(UVec2::new(64, 130)), UVec2::new(64, 128));
650 }
651
652 #[test]
653 fn tileset_has_a_layer_for_every_texture() {
654 let textures = Terrain::ALL.iter().map(|&t| terrain_texture(t)).collect();
655 let image = stack_tileset(textures);
656 assert!(image.texture_descriptor.size.depth_or_array_layers >= Terrain::ALL.len() as u32);
657 }
658
659 #[test]
660 fn plants_look_different_as_they_grow() {
661 assert_eq!(PlantLook::of(Plant::Crop, 0.1), PlantLook::Sprout);
662 assert_eq!(PlantLook::of(Plant::Crop, 0.7), PlantLook::YoungCrop);
663 assert_eq!(PlantLook::of(Plant::Crop, 1.0), PlantLook::RipeCrop);
664 assert_eq!(PlantLook::of(Plant::BerryBush, 0.5), PlantLook::Bush);
665 assert_eq!(PlantLook::of(Plant::BerryBush, 1.0), PlantLook::RipeBush);
666 }
667
668 #[test]
669 fn plant_layer_only_has_tiles_where_plants_grow() {
670 let mut map = WorldMap::filled(UVec2::splat(4), Terrain::Grass);
671 map.set_plant(UVec2::new(1, 0), Some(Plant::Tree));
672 let tiles = plant_tiles(&map, &LightMap::default(), UVec2::ZERO);
673 assert!(tiles[0].is_none());
674 assert_eq!(tiles[1].unwrap().tileset_index, PlantLook::Tree as u16);
675 }
676
677 // Light comes from the north-west (LIGHT has -x, +y), the convention for hillshaded maps.
678 #[test]
679 fn slopes_facing_the_light_are_brighter_than_slopes_facing_away() {
680 let mut map = WorldMap::filled(UVec2::new(5, 1), Terrain::Grass);
681 for (x, h) in [0.0, 5.0, 10.0, 5.0, 0.0].into_iter().enumerate() {
682 map.set_height(UVec2::new(x as u32, 0), h);
683 }
684 let flat = WorldMap::filled(UVec2::new(3, 1), Terrain::Grass);
685 let facing_west = hillshade(&map, UVec2::new(1, 0));
686 let facing_east = hillshade(&map, UVec2::new(3, 0));
687 let level = hillshade(&flat, UVec2::new(1, 0));
688 assert!(facing_west > level);
689 assert!(facing_east < level);
690 }
691
692 // wgpu's GLES backend (WebGL2) guesses the texture view dimension from the layer count:
693 // 1 layer => D2, 6 => Cube, multiples of 6 => CubeArray. The tilemap shader needs D2Array,
694 // so the tileset is padded with an unused layer to dodge those counts.
695 // Shading is drawn as a smooth, linearly filtered overlay instead of per-tile tints, which
696 // looked blocky up close; slopes facing away from the light get the darkest shadow.
697 #[test]
698 fn shadows_darken_slopes_facing_away_from_the_light() {
699 assert_eq!(shadow_alpha(1.25), 0);
700 assert!(shadow_alpha(0.7) > shadow_alpha(1.0));
701 assert_eq!(shadow_alpha(0.0), (MAX_SHADOW * 255.0) as u8);
702 }
703
704 // Every ambient light step re-tints all chunks; at high sim speeds dusk produced one per
705 // frame and dragged the frame rate down, so light-driven refreshes are rate limited.
706 #[test]
707 fn light_refreshes_are_rate_limited() {
708 assert!(!light_refresh_due(true, Duration::from_millis(20)));
709 assert!(light_refresh_due(true, LIGHT_REFRESH_INTERVAL));
710 assert!(!light_refresh_due(false, Duration::from_secs(5)));
711 }
712
713 #[test]
714 fn tileset_layer_count_avoids_webgl_view_dimension_heuristics() {
715 for n in 0..50 {
716 let layers = tileset_layer_count(n);
717 assert!(layers >= n.max(2));
718 assert!(layers % 6 != 0, "{n} terrains -> {layers} layers");
719 }
720 }
721 }