src/colonist.rs 7.6 K · 243 lines · raw · history

1 use std::{collections::VecDeque, time::Duration};
2
3 use bevy::prelude::*;
4
5 use crate::{
6 pathfinding::find_path,
7 rng::SimRng,
8 world::{TILE_SIZE, WorldMap},
9 };
10
11 pub struct ColonistPlugin;
12
13 impl Plugin for ColonistPlugin {
14 fn build(&self, app: &mut App) {
15 app.insert_resource(SimRng::new(0x5EED))
16 .add_message::<MoveOrder>()
17 .add_systems(Startup, spawn_colonists)
18 .add_systems(Update, (toggle_pause, (handle_move_orders, wander, follow_path).chain()));
19 }
20 }
21
22 const TILES_PER_SECOND: f32 = 4.0;
23 const WANDER_RADIUS: i32 = 8;
24 const WANDER_PAUSE_SECS: std::ops::Range<f32> = 1.0..4.0;
25
26 pub const SPAWNS: [(&str, UVec2, Color); 3] = [
27 ("Ada", UVec2::new(96, 64), Color::srgb(0.9, 0.3, 0.3)),
28 ("Bram", UVec2::new(99, 62), Color::srgb(0.3, 0.5, 0.95)),
29 ("Cleo", UVec2::new(94, 60), Color::srgb(0.95, 0.75, 0.3)),
30 ];
31
32 #[derive(Component, Debug)]
33 #[require(Transform, TilePos, Path, Wander)]
34 pub struct Colonist {
35 pub name: String,
36 }
37
38 #[derive(Component, Default, Debug, Clone, Copy, PartialEq)]
39 pub struct TilePos(pub UVec2);
40
41 #[derive(Component, Default, Debug)]
42 pub struct Path(pub VecDeque<UVec2>);
43
44 #[derive(Component, Debug)]
45 pub struct Wander(Timer);
46
47 impl Default for Wander {
48 fn default() -> Self {
49 Self(Timer::from_seconds(WANDER_PAUSE_SECS.start, TimerMode::Once))
50 }
51 }
52
53 #[derive(Message, Debug, Clone, Copy)]
54 pub struct MoveOrder {
55 pub colonist: Entity,
56 pub goal: UVec2,
57 }
58
59 fn spawn_colonists(
60 mut commands: Commands,
61 mut meshes: ResMut<Assets<Mesh>>,
62 mut materials: ResMut<Assets<ColorMaterial>>,
63 ) {
64 let mesh = meshes.add(Circle::new(TILE_SIZE * 0.35));
65 for (name, tile, color) in SPAWNS {
66 commands.spawn((
67 Name::new(name),
68 Colonist { name: name.into() },
69 TilePos(tile),
70 Mesh2d(mesh.clone()),
71 MeshMaterial2d(materials.add(color)),
72 Transform::from_translation(WorldMap::tile_center(tile).extend(1.0)),
73 ));
74 }
75 }
76
77 fn toggle_pause(keys: Res<ButtonInput<KeyCode>>, mut time: ResMut<Time<Virtual>>) {
78 if keys.just_pressed(KeyCode::Space) {
79 if time.is_paused() {
80 time.unpause();
81 } else {
82 time.pause();
83 }
84 }
85 }
86
87 fn handle_move_orders(
88 mut orders: MessageReader<MoveOrder>,
89 map: Res<WorldMap>,
90 mut colonists: Query<(&TilePos, &mut Path)>,
91 ) {
92 for order in orders.read() {
93 let Ok((tile, mut path)) = colonists.get_mut(order.colonist) else {
94 continue;
95 };
96 if let Some(new_path) = repath(&map, tile.0, &path.0, order.goal) {
97 path.0 = new_path;
98 }
99 }
100 }
101
102 pub fn repath(
103 map: &WorldMap,
104 tile: UVec2,
105 current: &VecDeque<UVec2>,
106 goal: UVec2,
107 ) -> Option<VecDeque<UVec2>> {
108 match current.front() {
109 Some(&next) => {
110 let mut path: VecDeque<_> = find_path(map, next, goal)?.into();
111 path.push_front(next);
112 Some(path)
113 }
114 None => find_path(map, tile, goal).map(VecDeque::from),
115 }
116 }
117
118 fn wander(
119 time: Res<Time>,
120 map: Res<WorldMap>,
121 mut rng: ResMut<SimRng>,
122 mut colonists: Query<(&TilePos, &mut Path, &mut Wander)>,
123 ) {
124 for (tile, mut path, mut wander) in &mut colonists {
125 if !path.0.is_empty() || !wander.0.tick(time.delta()).is_finished() {
126 continue;
127 }
128 let offset = IVec2::new(
129 rng.range_i32(-WANDER_RADIUS..WANDER_RADIUS + 1),
130 rng.range_i32(-WANDER_RADIUS..WANDER_RADIUS + 1),
131 );
132 let goal = tile.0.as_ivec2() + offset;
133 if !map.in_bounds(goal) {
134 continue;
135 }
136 if let Some(new_path) = find_path(&map, tile.0, goal.as_uvec2()) {
137 path.0 = new_path.into();
138 let pause = rng.range_f32(WANDER_PAUSE_SECS);
139 wander.0.set_duration(Duration::from_secs_f32(pause));
140 wander.0.reset();
141 }
142 }
143 }
144
145 fn follow_path(
146 time: Res<Time>,
147 map: Res<WorldMap>,
148 mut colonists: Query<(&mut TilePos, &mut Path, &mut Transform)>,
149 ) {
150 for (mut tile, mut path, mut transform) in &mut colonists {
151 let Some(&next) = path.0.front() else {
152 continue;
153 };
154 let cost = map.move_cost(next.as_ivec2()).unwrap_or(100) as f32 / 100.0;
155 let max_distance = TILES_PER_SECOND * TILE_SIZE / cost * time.delta_secs();
156 let target = WorldMap::tile_center(next);
157 let (pos, arrived) = step_towards(transform.translation.truncate(), target, max_distance);
158 transform.translation = pos.extend(transform.translation.z);
159 if arrived {
160 tile.0 = next;
161 path.0.pop_front();
162 }
163 }
164 }
165
166 pub fn step_towards(pos: Vec2, target: Vec2, max_distance: f32) -> (Vec2, bool) {
167 let delta = target - pos;
168 if delta.length() <= max_distance {
169 (target, true)
170 } else {
171 (pos + delta.normalize() * max_distance, false)
172 }
173 }
174
175 #[cfg(test)]
176 mod tests {
177 use super::*;
178 use crate::world::{Terrain, static_world};
179
180 #[test]
181 fn spawn_tiles_are_walkable() {
182 let map = static_world();
183 for (name, tile, _) in SPAWNS {
184 assert!(map.move_cost(tile.as_ivec2()).is_some(), "{name}");
185 }
186 }
187
188 #[test]
189 fn step_towards_stops_exactly_on_target() {
190 assert_eq!(step_towards(Vec2::ZERO, Vec2::new(3.0, 4.0), 10.0), (Vec2::new(3.0, 4.0), true));
191 let (pos, arrived) = step_towards(Vec2::ZERO, Vec2::new(3.0, 4.0), 2.5);
192 assert!(!arrived);
193 assert!(pos.abs_diff_eq(Vec2::new(1.5, 2.0), 1e-5));
194 }
195
196 // A colonist halfway between two tiles keeps heading to the tile it is entering; repathing
197 // from its last reached tile would make it turn around mid-step or walk diagonally past walls.
198 #[test]
199 fn repath_while_moving_keeps_the_tile_being_entered() {
200 let map = WorldMap::filled(UVec2::new(10, 10), Terrain::Grass);
201 let current = VecDeque::from([UVec2::new(3, 2), UVec2::new(4, 2)]);
202 let path = repath(&map, UVec2::new(2, 2), &current, UVec2::new(3, 5)).unwrap();
203 assert_eq!(path.front(), Some(&UVec2::new(3, 2)));
204 assert_eq!(path.back(), Some(&UVec2::new(3, 5)));
205 }
206
207 #[test]
208 fn repath_when_idle_starts_from_current_tile() {
209 let map = WorldMap::filled(UVec2::new(10, 10), Terrain::Grass);
210 let path = repath(&map, UVec2::new(2, 2), &VecDeque::new(), UVec2::new(4, 2)).unwrap();
211 assert_eq!(path, VecDeque::from([UVec2::new(3, 2), UVec2::new(4, 2)]));
212 }
213
214 #[test]
215 fn colonists_walk_their_path_and_update_tile_pos() {
216 let mut app = App::new();
217 app.insert_resource(WorldMap::filled(UVec2::new(10, 10), Terrain::Grass))
218 .init_resource::<Time>()
219 .add_systems(Update, follow_path);
220 let colonist = app
221 .world_mut()
222 .spawn((
223 Colonist { name: "Test".into() },
224 TilePos(UVec2::new(1, 1)),
225 Path(VecDeque::from([UVec2::new(2, 1), UVec2::new(3, 1)])),
226 Transform::from_translation(WorldMap::tile_center(UVec2::new(1, 1)).extend(0.0)),
227 ))
228 .id();
229 for _ in 0..100 {
230 app.world_mut()
231 .resource_mut::<Time>()
232 .advance_by(Duration::from_millis(50));
233 app.update();
234 }
235 let world = app.world();
236 assert_eq!(world.get::<TilePos>(colonist), Some(&TilePos(UVec2::new(3, 1))));
237 assert!(world.get::<Path>(colonist).unwrap().0.is_empty());
238 assert_eq!(
239 world.get::<Transform>(colonist).unwrap().translation.truncate(),
240 WorldMap::tile_center(UVec2::new(3, 1))
241 );
242 }
243 }