src/colonist.rs 9.9 K · 331 lines · raw · history

1 use std::collections::VecDeque;
2
3 use bevy::prelude::*;
4
5 use crate::{
6 climate::Warmth,
7 food::Hunger,
8 items::{Carrying, ItemAssets},
9 jobs::{CurrentJob, IdleTimer, WorkPriorities},
10 needs::{Rest, sleep_marker},
11 pathfinding::find_path,
12 population::Starvation,
13 sim::{SimPos, SimSystems, sim_pos},
14 skills::{Skills, WorkCarry},
15 world::{TILE_SIZE, TilePos, WorldMap},
16 worldgen::{WorldGenerated, spawn_tiles},
17 };
18
19 pub struct ColonistPlugin;
20
21 impl Plugin for ColonistPlugin {
22 fn build(&self, app: &mut App) {
23 app.add_systems(Startup, create_colonist_assets)
24 .add_systems(Update, spawn_colonists.run_if(on_message::<WorldGenerated>))
25 .add_systems(FixedUpdate, follow_path.in_set(SimSystems::Move));
26 }
27 }
28
29 const TILES_PER_SECOND: f32 = 4.0;
30
31 pub const NAMES: [&str; 26] = [
32 "Ada", "Bram", "Cleo", "Dana", "Emil", "Fenna", "Gijs", "Hanna", "Ivo", "Juul", "Kees",
33 "Lotte", "Milan", "Noor", "Otto", "Pien", "Quinn", "Roos", "Sem", "Tess", "Ugo", "Vera",
34 "Wout", "Xem", "Yara", "Zeno",
35 ];
36
37 const COLORS: [Color; 8] = [
38 Color::srgb(0.9, 0.3, 0.3),
39 Color::srgb(0.3, 0.5, 0.95),
40 Color::srgb(0.95, 0.75, 0.3),
41 Color::srgb(0.6, 0.35, 0.85),
42 Color::srgb(0.3, 0.8, 0.75),
43 Color::srgb(0.95, 0.5, 0.75),
44 Color::srgb(0.55, 0.8, 0.3),
45 Color::srgb(0.95, 0.95, 0.95),
46 ];
47
48 const STARTING_COLONISTS: usize = 3;
49
50 #[derive(Resource, Default)]
51 pub struct ColonistAssets {
52 mesh: Handle<Mesh>,
53 }
54
55 fn create_colonist_assets(mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>) {
56 commands.insert_resource(ColonistAssets {
57 mesh: meshes.add(Circle::new(TILE_SIZE * 0.35)),
58 });
59 }
60
61 pub fn spawn_colonist(
62 commands: &mut Commands,
63 assets: &ColonistAssets,
64 item_assets: &ItemAssets,
65 materials: &mut Assets<ColorMaterial>,
66 index: usize,
67 tile: UVec2,
68 ) -> Entity {
69 let name = NAMES[index % NAMES.len()];
70 commands
71 .spawn((
72 Name::new(name),
73 Colonist { name: name.into() },
74 TilePos(tile),
75 Mesh2d(assets.mesh.clone()),
76 MeshMaterial2d(materials.add(COLORS[index % COLORS.len()])),
77 sim_pos(WorldMap::tile_center(tile)),
78 Transform::from_translation(WorldMap::tile_center(tile).extend(1.0)),
79 children![item_assets.carried_visual(), sleep_marker()],
80 ))
81 .id()
82 }
83
84 #[derive(Component, Debug)]
85 #[require(
86 Transform,
87 SimPos,
88 TilePos,
89 Path,
90 CurrentJob,
91 IdleTimer,
92 Carrying,
93 Rest,
94 Hunger,
95 Starvation,
96 WorkPriorities,
97 Warmth,
98 Skills,
99 WorkCarry
100 )]
101 pub struct Colonist {
102 pub name: String,
103 }
104
105 #[derive(Component, Default, Debug)]
106 pub struct Path(pub VecDeque<UVec2>);
107
108 fn spawn_colonists(
109 mut commands: Commands,
110 map: Res<WorldMap>,
111 existing: Query<Entity, With<Colonist>>,
112 assets: Res<ColonistAssets>,
113 item_assets: Res<ItemAssets>,
114 mut materials: ResMut<Assets<ColorMaterial>>,
115 ) {
116 for entity in &existing {
117 commands.entity(entity).despawn();
118 }
119 let tiles = spawn_tiles(&map, STARTING_COLONISTS);
120 for (index, tile) in tiles.into_iter().enumerate() {
121 spawn_colonist(
122 &mut commands,
123 &assets,
124 &item_assets,
125 &mut materials,
126 index,
127 tile,
128 );
129 }
130 }
131
132 pub fn repath(
133 map: &WorldMap,
134 tile: UVec2,
135 current: &VecDeque<UVec2>,
136 goal: UVec2,
137 ) -> Option<VecDeque<UVec2>> {
138 match current.front() {
139 Some(&next) => {
140 let mut path: VecDeque<_> = find_path(map, next, goal)?.into();
141 path.push_front(next);
142 Some(path)
143 }
144 None => find_path(map, tile, goal).map(VecDeque::from),
145 }
146 }
147
148 #[derive(Component, Debug, Clone, Copy, PartialEq)]
149 pub struct MoveSpeed(pub f32);
150
151 pub fn follow_path(
152 time: Res<Time>,
153 mut map: ResMut<WorldMap>,
154 mut movers: Query<(
155 &mut TilePos,
156 &mut Path,
157 &mut SimPos,
158 Option<&MoveSpeed>,
159 Has<Colonist>,
160 )>,
161 ) {
162 for (mut tile, mut path, mut pos, speed, is_colonist) in &mut movers {
163 let Some(&next) = path.0.front() else {
164 continue;
165 };
166 if map.move_cost(next.as_ivec2()).is_none() {
167 path.0.clear();
168 continue;
169 }
170 let cost = map
171 .step_cost(tile.0.as_ivec2(), next.as_ivec2())
172 .unwrap_or(100) as f32
173 / 100.0;
174 let tiles_per_second = speed.map_or(TILES_PER_SECOND, |s| s.0);
175 let max_distance = tiles_per_second * TILE_SIZE / cost * time.delta_secs();
176 let target = WorldMap::tile_center(next);
177 let arrived;
178 (pos.0, arrived) = step_towards(pos.0, target, max_distance);
179 if arrived {
180 tile.0 = next;
181 path.0.pop_front();
182 if is_colonist {
183 let wear = map.wear(next.as_ivec2());
184 map.set_wear(next, wear + 1.0);
185 }
186 }
187 }
188 }
189
190 pub fn step_towards(pos: Vec2, target: Vec2, max_distance: f32) -> (Vec2, bool) {
191 let delta = target - pos;
192 if delta.length() <= max_distance {
193 (target, true)
194 } else {
195 (pos + delta.normalize() * max_distance, false)
196 }
197 }
198
199 #[cfg(test)]
200 mod tests {
201 use super::*;
202 use crate::world::Terrain;
203 use std::time::Duration;
204
205 #[test]
206 fn step_towards_stops_exactly_on_target() {
207 assert_eq!(
208 step_towards(Vec2::ZERO, Vec2::new(3.0, 4.0), 10.0),
209 (Vec2::new(3.0, 4.0), true)
210 );
211 let (pos, arrived) = step_towards(Vec2::ZERO, Vec2::new(3.0, 4.0), 2.5);
212 assert!(!arrived);
213 assert!(pos.abs_diff_eq(Vec2::new(1.5, 2.0), 1e-5));
214 }
215
216 // A colonist halfway between two tiles keeps heading to the tile it is entering; repathing
217 // from its last reached tile would make it turn around mid-step or walk diagonally past walls.
218 #[test]
219 fn repath_while_moving_keeps_the_tile_being_entered() {
220 let map = WorldMap::filled(UVec2::new(10, 10), Terrain::Grass);
221 let current = VecDeque::from([UVec2::new(3, 2), UVec2::new(4, 2)]);
222 let path = repath(&map, UVec2::new(2, 2), &current, UVec2::new(3, 5)).unwrap();
223 assert_eq!(path.front(), Some(&UVec2::new(3, 2)));
224 assert_eq!(path.back(), Some(&UVec2::new(3, 5)));
225 }
226
227 #[test]
228 fn repath_when_idle_starts_from_current_tile() {
229 let map = WorldMap::filled(UVec2::new(10, 10), Terrain::Grass);
230 let path = repath(&map, UVec2::new(2, 2), &VecDeque::new(), UVec2::new(4, 2)).unwrap();
231 assert_eq!(path, VecDeque::from([UVec2::new(3, 2), UVec2::new(4, 2)]));
232 }
233
234 #[test]
235 fn movers_stop_instead_of_walking_into_a_new_wall() {
236 let mut map = WorldMap::filled(UVec2::new(10, 10), Terrain::Grass);
237 map.set_wall(UVec2::new(3, 1), true);
238 let mut app = App::new();
239 app.insert_resource(map)
240 .init_resource::<Time>()
241 .add_systems(Update, follow_path);
242 let mover = app
243 .world_mut()
244 .spawn((
245 TilePos(UVec2::new(1, 1)),
246 Path(VecDeque::from([
247 UVec2::new(2, 1),
248 UVec2::new(3, 1),
249 UVec2::new(4, 1),
250 ])),
251 sim_pos(WorldMap::tile_center(UVec2::new(1, 1))),
252 ))
253 .id();
254 for _ in 0..40 {
255 app.world_mut()
256 .resource_mut::<Time>()
257 .advance_by(Duration::from_millis(50));
258 app.update();
259 }
260 assert_eq!(
261 app.world().get::<TilePos>(mover),
262 Some(&TilePos(UVec2::new(2, 1)))
263 );
264 assert!(app.world().get::<Path>(mover).unwrap().0.is_empty());
265 }
266
267 #[test]
268 fn colonists_wear_down_the_ground_they_walk_on() {
269 let mut app = App::new();
270 app.insert_resource(WorldMap::filled(UVec2::new(10, 10), Terrain::Grass))
271 .init_resource::<Time>()
272 .add_systems(Update, follow_path);
273 app.world_mut().spawn((
274 Colonist {
275 name: "Test".into(),
276 },
277 TilePos(UVec2::new(1, 1)),
278 Path(VecDeque::from([UVec2::new(2, 1)])),
279 sim_pos(WorldMap::tile_center(UVec2::new(1, 1))),
280 ));
281 app.world_mut().spawn((
282 TilePos(UVec2::new(1, 3)),
283 Path(VecDeque::from([UVec2::new(2, 3)])),
284 sim_pos(WorldMap::tile_center(UVec2::new(1, 3))),
285 ));
286 for _ in 0..20 {
287 app.world_mut()
288 .resource_mut::<Time>()
289 .advance_by(Duration::from_millis(50));
290 app.update();
291 }
292 let map = app.world().resource::<WorldMap>();
293 assert_eq!(map.wear(IVec2::new(2, 1)), 1.0);
294 assert_eq!(map.wear(IVec2::new(2, 3)), 0.0);
295 }
296
297 #[test]
298 fn colonists_walk_their_path_and_update_tile_pos() {
299 let mut app = App::new();
300 app.insert_resource(WorldMap::filled(UVec2::new(10, 10), Terrain::Grass))
301 .init_resource::<Time>()
302 .add_systems(Update, follow_path);
303 let colonist = app
304 .world_mut()
305 .spawn((
306 Colonist {
307 name: "Test".into(),
308 },
309 TilePos(UVec2::new(1, 1)),
310 Path(VecDeque::from([UVec2::new(2, 1), UVec2::new(3, 1)])),
311 sim_pos(WorldMap::tile_center(UVec2::new(1, 1))),
312 ))
313 .id();
314 for _ in 0..100 {
315 app.world_mut()
316 .resource_mut::<Time>()
317 .advance_by(Duration::from_millis(50));
318 app.update();
319 }
320 let world = app.world();
321 assert_eq!(
322 world.get::<TilePos>(colonist),
323 Some(&TilePos(UVec2::new(3, 1)))
324 );
325 assert!(world.get::<Path>(colonist).unwrap().0.is_empty());
326 assert_eq!(
327 world.get::<SimPos>(colonist),
328 Some(&SimPos(WorldMap::tile_center(UVec2::new(3, 1))))
329 );
330 }
331 }