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