| 1 |
use std::{collections::HashMap, ops::Range, time::Duration}; |
| 2 |
|
| 3 |
use bevy::prelude::*; |
| 4 |
|
| 5 |
use crate::{ |
| 6 |
colonist::{Colonist, Path, repath}, |
| 7 |
items::{Item, ItemAssets, ItemKind, drop_items, stock}, |
| 8 |
pathfinding::{find_path, find_path_adjacent, is_adjacent, nearest_tile}, |
| 9 |
rng::SimRng, |
| 10 |
sim::SimSystems, |
| 11 |
world::{Plant, TileChanged, TilePos, WorldMap}, |
| 12 |
worldgen::WorldGenerated, |
| 13 |
}; |
| 14 |
|
| 15 |
pub struct JobsPlugin; |
| 16 |
|
| 17 |
impl Plugin for JobsPlugin { |
| 18 |
fn build(&self, app: &mut App) { |
| 19 |
app.insert_resource(SimRng::new(0x5EED)) |
| 20 |
.init_resource::<Reservations>() |
| 21 |
.init_resource::<ColonyGoals>() |
| 22 |
.add_message::<Order>() |
| 23 |
.add_message::<TileChanged>() |
| 24 |
.add_systems( |
| 25 |
Update, |
| 26 |
( |
| 27 |
clear_reservations.run_if(on_message::<WorldGenerated>), |
| 28 |
handle_orders, |
| 29 |
), |
| 30 |
) |
| 31 |
.add_systems(FixedUpdate, choose_jobs.in_set(SimSystems::Decide)) |
| 32 |
.add_systems(FixedUpdate, run_jobs.in_set(SimSystems::Act)); |
| 33 |
} |
| 34 |
} |
| 35 |
|
| 36 |
pub const CHOP_TICKS: u32 = 240; |
| 37 |
pub const WOOD_PER_TREE: u32 = 10; |
| 38 |
const TREE_SEARCH_TILES: usize = 6000; |
| 39 |
const WANDER_RADIUS: i32 = 8; |
| 40 |
const IDLE_SECS: Range<f32> = 1.0..4.0; |
| 41 |
const IDLE_AFTER_ORDER_SECS: f32 = 10.0; |
| 42 |
|
| 43 |
#[derive(Component, Default, Debug, Clone, PartialEq)] |
| 44 |
pub struct CurrentJob(pub Option<Job>); |
| 45 |
|
| 46 |
#[derive(Debug, Clone, Copy, PartialEq)] |
| 47 |
pub struct Job { |
| 48 |
pub task: Task, |
| 49 |
pub ordered: bool, |
| 50 |
} |
| 51 |
|
| 52 |
#[derive(Debug, Clone, Copy, PartialEq)] |
| 53 |
pub enum Task { |
| 54 |
MoveTo(UVec2), |
| 55 |
Chop { tree: UVec2, progress: u32 }, |
| 56 |
} |
| 57 |
|
| 58 |
#[derive(Component, Debug)] |
| 59 |
pub struct IdleTimer(Timer); |
| 60 |
|
| 61 |
impl Default for IdleTimer { |
| 62 |
fn default() -> Self { |
| 63 |
Self(Timer::from_seconds(IDLE_SECS.start, TimerMode::Once)) |
| 64 |
} |
| 65 |
} |
| 66 |
|
| 67 |
impl IdleTimer { |
| 68 |
fn restart(&mut self, secs: f32) { |
| 69 |
self.0.set_duration(Duration::from_secs_f32(secs)); |
| 70 |
self.0.reset(); |
| 71 |
} |
| 72 |
} |
| 73 |
|
| 74 |
#[derive(Resource, Default, Debug)] |
| 75 |
pub struct Reservations(HashMap<UVec2, Entity>); |
| 76 |
|
| 77 |
impl Reservations { |
| 78 |
pub fn reserve(&mut self, tile: UVec2, by: Entity) { |
| 79 |
self.0.insert(tile, by); |
| 80 |
} |
| 81 |
|
| 82 |
pub fn holder(&self, tile: UVec2) -> Option<Entity> { |
| 83 |
self.0.get(&tile).copied() |
| 84 |
} |
| 85 |
|
| 86 |
pub fn release_all(&mut self, by: Entity) { |
| 87 |
self.0.retain(|_, holder| *holder != by); |
| 88 |
} |
| 89 |
} |
| 90 |
|
| 91 |
#[derive(Resource, Debug)] |
| 92 |
pub struct ColonyGoals { |
| 93 |
pub wood: u32, |
| 94 |
} |
| 95 |
|
| 96 |
impl Default for ColonyGoals { |
| 97 |
fn default() -> Self { |
| 98 |
Self { wood: 50 } |
| 99 |
} |
| 100 |
} |
| 101 |
|
| 102 |
#[derive(Message, Debug, Clone, Copy)] |
| 103 |
pub struct Order { |
| 104 |
pub colonist: Entity, |
| 105 |
pub tile: UVec2, |
| 106 |
} |
| 107 |
|
| 108 |
fn clear_reservations(mut reservations: ResMut<Reservations>) { |
| 109 |
reservations.0.clear(); |
| 110 |
} |
| 111 |
|
| 112 |
fn handle_orders( |
| 113 |
mut orders: MessageReader<Order>, |
| 114 |
map: Res<WorldMap>, |
| 115 |
mut reservations: ResMut<Reservations>, |
| 116 |
mut colonists: Query<(&TilePos, &mut Path, &mut CurrentJob)>, |
| 117 |
) { |
| 118 |
for order in orders.read() { |
| 119 |
let Ok((tile, mut path, mut job)) = colonists.get_mut(order.colonist) else { |
| 120 |
continue; |
| 121 |
}; |
| 122 |
if map.plant(order.tile.as_ivec2()) == Some(Plant::Tree) { |
| 123 |
reservations.release_all(order.colonist); |
| 124 |
reservations.reserve(order.tile, order.colonist); |
| 125 |
path.0.truncate(1); |
| 126 |
job.0 = Some(Job { |
| 127 |
task: Task::Chop { |
| 128 |
tree: order.tile, |
| 129 |
progress: 0, |
| 130 |
}, |
| 131 |
ordered: true, |
| 132 |
}); |
| 133 |
} else if let Some(new_path) = repath(&map, tile.0, &path.0, order.tile) { |
| 134 |
reservations.release_all(order.colonist); |
| 135 |
path.0 = new_path; |
| 136 |
job.0 = Some(Job { |
| 137 |
task: Task::MoveTo(order.tile), |
| 138 |
ordered: true, |
| 139 |
}); |
| 140 |
} |
| 141 |
} |
| 142 |
} |
| 143 |
|
| 144 |
pub fn wood_wanted(goals: &ColonyGoals, in_stock: u32, trees_being_chopped: u32) -> bool { |
| 145 |
in_stock + trees_being_chopped * WOOD_PER_TREE < goals.wood |
| 146 |
} |
| 147 |
|
| 148 |
pub fn find_tree( |
| 149 |
map: &WorldMap, |
| 150 |
reservations: &Reservations, |
| 151 |
from: UVec2, |
| 152 |
) -> Option<(UVec2, Vec<UVec2>)> { |
| 153 |
let tree = nearest_tile(map, from, TREE_SEARCH_TILES, |p| { |
| 154 |
map.plant(p.as_ivec2()) == Some(Plant::Tree) && reservations.holder(p).is_none() |
| 155 |
})?; |
| 156 |
let path = find_path_adjacent(map, from, tree)?; |
| 157 |
Some((tree, path)) |
| 158 |
} |
| 159 |
|
| 160 |
#[allow(clippy::too_many_arguments)] |
| 161 |
fn choose_jobs( |
| 162 |
time: Res<Time>, |
| 163 |
map: Res<WorldMap>, |
| 164 |
goals: Res<ColonyGoals>, |
| 165 |
mut rng: ResMut<SimRng>, |
| 166 |
mut reservations: ResMut<Reservations>, |
| 167 |
items: Query<&Item>, |
| 168 |
mut colonists: Query< |
| 169 |
(Entity, &TilePos, &mut Path, &mut CurrentJob, &mut IdleTimer), |
| 170 |
With<Colonist>, |
| 171 |
>, |
| 172 |
) { |
| 173 |
let wood = stock(items.iter(), ItemKind::Wood); |
| 174 |
let mut chopping = colonists |
| 175 |
.iter() |
| 176 |
.filter(|(.., job, _)| { |
| 177 |
matches!( |
| 178 |
job.0, |
| 179 |
Some(Job { |
| 180 |
task: Task::Chop { .. }, |
| 181 |
.. |
| 182 |
}) |
| 183 |
) |
| 184 |
}) |
| 185 |
.count() as u32; |
| 186 |
for (entity, tile, mut path, mut job, mut idle) in &mut colonists { |
| 187 |
if job.0.is_some() || !path.0.is_empty() || !idle.0.tick(time.delta()).is_finished() { |
| 188 |
continue; |
| 189 |
} |
| 190 |
if wood_wanted(&goals, wood, chopping) |
| 191 |
&& let Some((tree, tree_path)) = find_tree(&map, &reservations, tile.0) |
| 192 |
{ |
| 193 |
reservations.reserve(tree, entity); |
| 194 |
path.0 = tree_path.into(); |
| 195 |
job.0 = Some(Job { |
| 196 |
task: Task::Chop { tree, progress: 0 }, |
| 197 |
ordered: false, |
| 198 |
}); |
| 199 |
chopping += 1; |
| 200 |
continue; |
| 201 |
} |
| 202 |
let goal = tile.0.as_ivec2() |
| 203 |
+ IVec2::new( |
| 204 |
rng.range_i32(-WANDER_RADIUS..WANDER_RADIUS + 1), |
| 205 |
rng.range_i32(-WANDER_RADIUS..WANDER_RADIUS + 1), |
| 206 |
); |
| 207 |
if map.in_bounds(goal) |
| 208 |
&& let Some(wander_path) = find_path(&map, tile.0, goal.as_uvec2()) |
| 209 |
{ |
| 210 |
path.0 = wander_path.into(); |
| 211 |
idle.restart(rng.range_f32(IDLE_SECS)); |
| 212 |
} |
| 213 |
} |
| 214 |
} |
| 215 |
|
| 216 |
#[allow(clippy::too_many_arguments)] |
| 217 |
fn run_jobs( |
| 218 |
mut commands: Commands, |
| 219 |
mut map: ResMut<WorldMap>, |
| 220 |
mut reservations: ResMut<Reservations>, |
| 221 |
mut rng: ResMut<SimRng>, |
| 222 |
item_assets: Res<ItemAssets>, |
| 223 |
mut items: Query<(&mut Item, &TilePos)>, |
| 224 |
mut changed: MessageWriter<TileChanged>, |
| 225 |
mut colonists: Query<(Entity, &TilePos, &mut Path, &mut CurrentJob, &mut IdleTimer)>, |
| 226 |
) { |
| 227 |
for (entity, tile, mut path, mut current, mut idle) in &mut colonists { |
| 228 |
let Some(mut job) = current.0 else { |
| 229 |
continue; |
| 230 |
}; |
| 231 |
if !path.0.is_empty() { |
| 232 |
continue; |
| 233 |
} |
| 234 |
let done = match &mut job.task { |
| 235 |
Task::MoveTo(_) => true, |
| 236 |
Task::Chop { tree, progress } => { |
| 237 |
let tree = *tree; |
| 238 |
let still_ours = map.plant(tree.as_ivec2()) == Some(Plant::Tree) |
| 239 |
&& reservations.holder(tree) == Some(entity); |
| 240 |
if !still_ours { |
| 241 |
true |
| 242 |
} else if !is_adjacent(tile.0.as_ivec2(), tree.as_ivec2()) { |
| 243 |
match find_path_adjacent(&map, tile.0, tree) { |
| 244 |
Some(p) if !p.is_empty() => { |
| 245 |
path.0 = p.into(); |
| 246 |
false |
| 247 |
} |
| 248 |
_ => true, |
| 249 |
} |
| 250 |
} else { |
| 251 |
*progress += 1; |
| 252 |
if *progress >= CHOP_TICKS { |
| 253 |
map.set_plant(tree, None); |
| 254 |
changed.write(TileChanged(tree)); |
| 255 |
drop_items( |
| 256 |
&mut commands, |
| 257 |
&mut items, |
| 258 |
&item_assets, |
| 259 |
tree, |
| 260 |
ItemKind::Wood, |
| 261 |
WOOD_PER_TREE, |
| 262 |
); |
| 263 |
} |
| 264 |
*progress >= CHOP_TICKS |
| 265 |
} |
| 266 |
} |
| 267 |
}; |
| 268 |
if done { |
| 269 |
reservations.release_all(entity); |
| 270 |
current.0 = None; |
| 271 |
let ordered_move = matches!( |
| 272 |
job, |
| 273 |
Job { |
| 274 |
task: Task::MoveTo(_), |
| 275 |
ordered: true |
| 276 |
} |
| 277 |
); |
| 278 |
idle.restart(if ordered_move { |
| 279 |
IDLE_AFTER_ORDER_SECS |
| 280 |
} else { |
| 281 |
rng.range_f32(IDLE_SECS) |
| 282 |
}); |
| 283 |
} else { |
| 284 |
current.0 = Some(job); |
| 285 |
} |
| 286 |
} |
| 287 |
} |
| 288 |
|
| 289 |
#[cfg(test)] |
| 290 |
mod tests { |
| 291 |
use super::*; |
| 292 |
use crate::{ |
| 293 |
colonist::follow_path, |
| 294 |
sim::{SimPos, sim_pos}, |
| 295 |
world::Terrain, |
| 296 |
}; |
| 297 |
|
| 298 |
const TICK: Duration = Duration::from_nanos(1_000_000_000 / 60); |
| 299 |
|
| 300 |
fn test_app(map: WorldMap) -> App { |
| 301 |
let mut app = App::new(); |
| 302 |
app.insert_resource(map) |
| 303 |
.insert_resource(SimRng::new(1)) |
| 304 |
.init_resource::<Time>() |
| 305 |
.init_resource::<Reservations>() |
| 306 |
.init_resource::<ColonyGoals>() |
| 307 |
.init_resource::<ItemAssets>() |
| 308 |
.add_message::<Order>() |
| 309 |
.add_message::<TileChanged>() |
| 310 |
.add_systems( |
| 311 |
Update, |
| 312 |
(handle_orders, choose_jobs, run_jobs, follow_path).chain(), |
| 313 |
); |
| 314 |
app |
| 315 |
} |
| 316 |
|
| 317 |
fn spawn_colonist(app: &mut App, tile: UVec2) -> Entity { |
| 318 |
app.world_mut() |
| 319 |
.spawn(( |
| 320 |
Colonist { |
| 321 |
name: "Test".into(), |
| 322 |
}, |
| 323 |
TilePos(tile), |
| 324 |
sim_pos(WorldMap::tile_center(tile)), |
| 325 |
)) |
| 326 |
.id() |
| 327 |
} |
| 328 |
|
| 329 |
fn run_ticks(app: &mut App, ticks: u32) { |
| 330 |
for _ in 0..ticks { |
| 331 |
app.world_mut().resource_mut::<Time>().advance_by(TICK); |
| 332 |
app.update(); |
| 333 |
} |
| 334 |
} |
| 335 |
|
| 336 |
fn map_with_trees(trees: &[UVec2]) -> WorldMap { |
| 337 |
let mut map = WorldMap::filled(UVec2::new(20, 20), Terrain::Grass); |
| 338 |
for &t in trees { |
| 339 |
map.set_plant(t, Some(Plant::Tree)); |
| 340 |
} |
| 341 |
map |
| 342 |
} |
| 343 |
|
| 344 |
fn wood_on_map(app: &mut App) -> u32 { |
| 345 |
let world = app.world_mut(); |
| 346 |
let items: Vec<Item> = world.query::<&Item>().iter(world).copied().collect(); |
| 347 |
stock(items.iter(), ItemKind::Wood) |
| 348 |
} |
| 349 |
|
| 350 |
fn job(app: &App, colonist: Entity) -> Option<Job> { |
| 351 |
app.world().get::<CurrentJob>(colonist).unwrap().0 |
| 352 |
} |
| 353 |
|
| 354 |
#[test] |
| 355 |
fn idle_colonists_cut_trees_when_the_colony_needs_wood() { |
| 356 |
let tree = UVec2::new(8, 5); |
| 357 |
let mut app = test_app(map_with_trees(&[tree])); |
| 358 |
spawn_colonist(&mut app, UVec2::new(2, 5)); |
| 359 |
run_ticks(&mut app, 60 * 15); |
| 360 |
assert_eq!( |
| 361 |
app.world().resource::<WorldMap>().plant(tree.as_ivec2()), |
| 362 |
None |
| 363 |
); |
| 364 |
assert_eq!(wood_on_map(&mut app), WOOD_PER_TREE); |
| 365 |
assert!(app.world().resource::<Reservations>().0.is_empty()); |
| 366 |
} |
| 367 |
|
| 368 |
#[test] |
| 369 |
fn colonists_leave_trees_alone_when_there_is_enough_wood() { |
| 370 |
let tree = UVec2::new(8, 5); |
| 371 |
let mut app = test_app(map_with_trees(&[tree])); |
| 372 |
app.world_mut().resource_mut::<ColonyGoals>().wood = 0; |
| 373 |
spawn_colonist(&mut app, UVec2::new(2, 5)); |
| 374 |
run_ticks(&mut app, 60 * 15); |
| 375 |
assert_eq!( |
| 376 |
app.world().resource::<WorldMap>().plant(tree.as_ivec2()), |
| 377 |
Some(Plant::Tree) |
| 378 |
); |
| 379 |
} |
| 380 |
|
| 381 |
#[test] |
| 382 |
fn colonists_never_pick_the_same_tree() { |
| 383 |
let trees = [UVec2::new(10, 10), UVec2::new(10, 11)]; |
| 384 |
let mut app = test_app(map_with_trees(&trees)); |
| 385 |
let a = spawn_colonist(&mut app, UVec2::new(5, 10)); |
| 386 |
let b = spawn_colonist(&mut app, UVec2::new(5, 11)); |
| 387 |
run_ticks(&mut app, 61); |
| 388 |
let target = |c| match job(&app, c) { |
| 389 |
Some(Job { |
| 390 |
task: Task::Chop { tree, .. }, |
| 391 |
.. |
| 392 |
}) => tree, |
| 393 |
other => panic!("expected chop job, got {other:?}"), |
| 394 |
}; |
| 395 |
assert_ne!(target(a), target(b)); |
| 396 |
} |
| 397 |
|
| 398 |
|
| 399 |
|
| 400 |
#[test] |
| 401 |
fn trees_already_being_cut_count_towards_the_wood_goal() { |
| 402 |
let goals = ColonyGoals { wood: 25 }; |
| 403 |
assert!(wood_wanted(&goals, 10, 1)); |
| 404 |
assert!(!wood_wanted(&goals, 10, 2)); |
| 405 |
assert!(!wood_wanted(&goals, 30, 0)); |
| 406 |
} |
| 407 |
|
| 408 |
#[test] |
| 409 |
fn ordered_chop_ignores_the_wood_goal() { |
| 410 |
let tree = UVec2::new(8, 5); |
| 411 |
let mut app = test_app(map_with_trees(&[tree])); |
| 412 |
app.world_mut().resource_mut::<ColonyGoals>().wood = 0; |
| 413 |
let colonist = spawn_colonist(&mut app, UVec2::new(2, 5)); |
| 414 |
app.world_mut().write_message(Order { |
| 415 |
colonist, |
| 416 |
tile: tree, |
| 417 |
}); |
| 418 |
run_ticks(&mut app, 60 * 15); |
| 419 |
assert_eq!( |
| 420 |
app.world().resource::<WorldMap>().plant(tree.as_ivec2()), |
| 421 |
None |
| 422 |
); |
| 423 |
} |
| 424 |
|
| 425 |
#[test] |
| 426 |
fn ordering_a_move_cancels_the_current_job_and_frees_its_tree() { |
| 427 |
let tree = UVec2::new(15, 5); |
| 428 |
let mut app = test_app(map_with_trees(&[tree])); |
| 429 |
let colonist = spawn_colonist(&mut app, UVec2::new(2, 5)); |
| 430 |
run_ticks(&mut app, 61); |
| 431 |
assert!(matches!( |
| 432 |
job(&app, colonist), |
| 433 |
Some(Job { |
| 434 |
task: Task::Chop { .. }, |
| 435 |
.. |
| 436 |
}) |
| 437 |
)); |
| 438 |
app.world_mut().write_message(Order { |
| 439 |
colonist, |
| 440 |
tile: UVec2::new(2, 15), |
| 441 |
}); |
| 442 |
run_ticks(&mut app, 1); |
| 443 |
assert_eq!( |
| 444 |
job(&app, colonist).map(|j| j.task), |
| 445 |
Some(Task::MoveTo(UVec2::new(2, 15))) |
| 446 |
); |
| 447 |
assert_eq!(app.world().resource::<Reservations>().holder(tree), None); |
| 448 |
} |
| 449 |
|
| 450 |
#[test] |
| 451 |
fn colonists_chop_from_a_neighbouring_tile() { |
| 452 |
let tree = UVec2::new(8, 5); |
| 453 |
let mut app = test_app(map_with_trees(&[tree])); |
| 454 |
let colonist = spawn_colonist(&mut app, UVec2::new(2, 5)); |
| 455 |
run_ticks(&mut app, 60 * 5); |
| 456 |
let tile = app.world().get::<TilePos>(colonist).unwrap().0; |
| 457 |
assert!(is_adjacent(tile.as_ivec2(), tree.as_ivec2())); |
| 458 |
assert_eq!( |
| 459 |
app.world().get::<SimPos>(colonist).unwrap().0, |
| 460 |
WorldMap::tile_center(tile) |
| 461 |
); |
| 462 |
} |
| 463 |
} |