src/colonist.rs 5.9 K · 189 lines · raw · history

1 use std::collections::VecDeque;
2
3 use bevy::prelude::*;
4
5 use crate::{
6 food::Hunger,
7 items::{Carrying, ItemAssets},
8 jobs::{CurrentJob, IdleTimer},
9 needs::{Rest, sleep_marker},
10 pathfinding::find_path,
11 sim::{SimPos, SimSystems, sim_pos},
12 world::{TILE_SIZE, TilePos, WorldMap},
13 worldgen::{WorldGenerated, spawn_tiles},
14 };
15
16 pub struct ColonistPlugin;
17
18 impl Plugin for ColonistPlugin {
19 fn build(&self, app: &mut App) {
20 app.add_systems(Update, spawn_colonists.run_if(on_message::<WorldGenerated>))
21 .add_systems(FixedUpdate, follow_path.in_set(SimSystems::Move));
22 }
23 }
24
25 const TILES_PER_SECOND: f32 = 4.0;
26
27 const STARTING_COLONISTS: [(&str, Color); 3] = [
28 ("Ada", Color::srgb(0.9, 0.3, 0.3)),
29 ("Bram", Color::srgb(0.3, 0.5, 0.95)),
30 ("Cleo", Color::srgb(0.95, 0.75, 0.3)),
31 ];
32
33 #[derive(Component, Debug)]
34 #[require(
35 Transform, SimPos, TilePos, Path, CurrentJob, IdleTimer, Carrying, Rest, Hunger
36 )]
37 pub struct Colonist {
38 pub name: String,
39 }
40
41 #[derive(Component, Default, Debug)]
42 pub struct Path(pub VecDeque<UVec2>);
43
44 fn spawn_colonists(
45 mut commands: Commands,
46 map: Res<WorldMap>,
47 existing: Query<Entity, With<Colonist>>,
48 item_assets: Res<ItemAssets>,
49 mut meshes: ResMut<Assets<Mesh>>,
50 mut materials: ResMut<Assets<ColorMaterial>>,
51 ) {
52 for entity in &existing {
53 commands.entity(entity).despawn();
54 }
55 let mesh = meshes.add(Circle::new(TILE_SIZE * 0.35));
56 let tiles = spawn_tiles(&map, STARTING_COLONISTS.len());
57 for ((name, color), tile) in STARTING_COLONISTS.into_iter().zip(tiles) {
58 commands.spawn((
59 Name::new(name),
60 Colonist { name: name.into() },
61 TilePos(tile),
62 Mesh2d(mesh.clone()),
63 MeshMaterial2d(materials.add(color)),
64 sim_pos(WorldMap::tile_center(tile)),
65 Transform::from_translation(WorldMap::tile_center(tile).extend(1.0)),
66 children![item_assets.carried_visual(), sleep_marker()],
67 ));
68 }
69 }
70
71 pub fn repath(
72 map: &WorldMap,
73 tile: UVec2,
74 current: &VecDeque<UVec2>,
75 goal: UVec2,
76 ) -> Option<VecDeque<UVec2>> {
77 match current.front() {
78 Some(&next) => {
79 let mut path: VecDeque<_> = find_path(map, next, goal)?.into();
80 path.push_front(next);
81 Some(path)
82 }
83 None => find_path(map, tile, goal).map(VecDeque::from),
84 }
85 }
86
87 pub fn follow_path(
88 time: Res<Time>,
89 map: Res<WorldMap>,
90 mut colonists: Query<(&mut TilePos, &mut Path, &mut SimPos)>,
91 ) {
92 for (mut tile, mut path, mut pos) in &mut colonists {
93 let Some(&next) = path.0.front() else {
94 continue;
95 };
96 let cost = map
97 .step_cost(tile.0.as_ivec2(), next.as_ivec2())
98 .unwrap_or(100) as f32
99 / 100.0;
100 let max_distance = TILES_PER_SECOND * TILE_SIZE / cost * time.delta_secs();
101 let target = WorldMap::tile_center(next);
102 let arrived;
103 (pos.0, arrived) = step_towards(pos.0, target, max_distance);
104 if arrived {
105 tile.0 = next;
106 path.0.pop_front();
107 }
108 }
109 }
110
111 pub fn step_towards(pos: Vec2, target: Vec2, max_distance: f32) -> (Vec2, bool) {
112 let delta = target - pos;
113 if delta.length() <= max_distance {
114 (target, true)
115 } else {
116 (pos + delta.normalize() * max_distance, false)
117 }
118 }
119
120 #[cfg(test)]
121 mod tests {
122 use super::*;
123 use crate::world::Terrain;
124 use std::time::Duration;
125
126 #[test]
127 fn step_towards_stops_exactly_on_target() {
128 assert_eq!(
129 step_towards(Vec2::ZERO, Vec2::new(3.0, 4.0), 10.0),
130 (Vec2::new(3.0, 4.0), true)
131 );
132 let (pos, arrived) = step_towards(Vec2::ZERO, Vec2::new(3.0, 4.0), 2.5);
133 assert!(!arrived);
134 assert!(pos.abs_diff_eq(Vec2::new(1.5, 2.0), 1e-5));
135 }
136
137 // A colonist halfway between two tiles keeps heading to the tile it is entering; repathing
138 // from its last reached tile would make it turn around mid-step or walk diagonally past walls.
139 #[test]
140 fn repath_while_moving_keeps_the_tile_being_entered() {
141 let map = WorldMap::filled(UVec2::new(10, 10), Terrain::Grass);
142 let current = VecDeque::from([UVec2::new(3, 2), UVec2::new(4, 2)]);
143 let path = repath(&map, UVec2::new(2, 2), &current, UVec2::new(3, 5)).unwrap();
144 assert_eq!(path.front(), Some(&UVec2::new(3, 2)));
145 assert_eq!(path.back(), Some(&UVec2::new(3, 5)));
146 }
147
148 #[test]
149 fn repath_when_idle_starts_from_current_tile() {
150 let map = WorldMap::filled(UVec2::new(10, 10), Terrain::Grass);
151 let path = repath(&map, UVec2::new(2, 2), &VecDeque::new(), UVec2::new(4, 2)).unwrap();
152 assert_eq!(path, VecDeque::from([UVec2::new(3, 2), UVec2::new(4, 2)]));
153 }
154
155 #[test]
156 fn colonists_walk_their_path_and_update_tile_pos() {
157 let mut app = App::new();
158 app.insert_resource(WorldMap::filled(UVec2::new(10, 10), Terrain::Grass))
159 .init_resource::<Time>()
160 .add_systems(Update, follow_path);
161 let colonist = app
162 .world_mut()
163 .spawn((
164 Colonist {
165 name: "Test".into(),
166 },
167 TilePos(UVec2::new(1, 1)),
168 Path(VecDeque::from([UVec2::new(2, 1), UVec2::new(3, 1)])),
169 sim_pos(WorldMap::tile_center(UVec2::new(1, 1))),
170 ))
171 .id();
172 for _ in 0..100 {
173 app.world_mut()
174 .resource_mut::<Time>()
175 .advance_by(Duration::from_millis(50));
176 app.update();
177 }
178 let world = app.world();
179 assert_eq!(
180 world.get::<TilePos>(colonist),
181 Some(&TilePos(UVec2::new(3, 1)))
182 );
183 assert!(world.get::<Path>(colonist).unwrap().0.is_empty());
184 assert_eq!(
185 world.get::<SimPos>(colonist),
186 Some(&SimPos(WorldMap::tile_center(UVec2::new(3, 1))))
187 );
188 }
189 }