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

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