src/animals.rs 10.9 K · 362 lines · raw · history

1 use std::{ops::Range, time::Duration};
2
3 use bevy::prelude::*;
4
5 use crate::{
6 colonist::{Colonist, MoveSpeed, Path},
7 pathfinding::find_path,
8 rng::SimRng,
9 sim::{SimPos, SimSystems, SimTick, TICKS_PER_HOUR, sim_pos},
10 world::{TILE_SIZE, TilePos, WorldMap},
11 worldgen::{WorldGenerated, spawn_tiles},
12 };
13
14 pub struct AnimalsPlugin;
15
16 impl Plugin for AnimalsPlugin {
17 fn build(&self, app: &mut App) {
18 app.add_systems(Startup, create_animal_assets)
19 .add_systems(Update, populate.run_if(on_message::<WorldGenerated>))
20 .add_systems(
21 FixedUpdate,
22 (
23 wander.in_set(SimSystems::Decide),
24 migrate.in_set(SimSystems::Act),
25 ),
26 );
27 }
28 }
29
30 const WANDER_RADIUS: i32 = 10;
31 pub const FLEE_RANGE: i32 = 4;
32 const FLEE_DISTANCE: f32 = 7.0;
33 const IDLE_SECS: Range<f32> = 2.0..8.0;
34 const MIN_DISTANCE_FROM_COLONY: f32 = 25.0;
35 const MIGRATION_INTERVAL_TICKS: u64 = 2 * TICKS_PER_HOUR;
36 const PLACEMENT_ATTEMPTS: usize = 200;
37
38 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
39 pub enum AnimalKind {
40 Deer,
41 Rabbit,
42 }
43
44 impl AnimalKind {
45 pub const ALL: [AnimalKind; 2] = [AnimalKind::Deer, AnimalKind::Rabbit];
46
47 pub fn meat(self) -> u32 {
48 match self {
49 AnimalKind::Deer => 30,
50 AnimalKind::Rabbit => 8,
51 }
52 }
53
54 pub fn population(self) -> usize {
55 match self {
56 AnimalKind::Deer => 10,
57 AnimalKind::Rabbit => 16,
58 }
59 }
60
61 pub fn hunt_work(self) -> u32 {
62 match self {
63 AnimalKind::Deer => 360,
64 AnimalKind::Rabbit => 160,
65 }
66 }
67
68 fn speed(self) -> f32 {
69 match self {
70 AnimalKind::Deer => 3.0,
71 AnimalKind::Rabbit => 2.5,
72 }
73 }
74
75 pub fn name(self) -> &'static str {
76 match self {
77 AnimalKind::Deer => "deer",
78 AnimalKind::Rabbit => "rabbit",
79 }
80 }
81 }
82
83 #[derive(Component, Debug, Clone, Copy, PartialEq)]
84 #[require(Transform, Visibility, TilePos, Path, SimPos, AnimalIdle)]
85 pub struct Animal {
86 pub kind: AnimalKind,
87 }
88
89 #[derive(Component, Debug)]
90 pub struct AnimalIdle(Timer);
91
92 impl Default for AnimalIdle {
93 fn default() -> Self {
94 Self(Timer::from_seconds(IDLE_SECS.start, TimerMode::Once))
95 }
96 }
97
98 type Part = (Handle<Mesh>, Handle<ColorMaterial>);
99
100 #[derive(Resource, Default)]
101 pub struct AnimalAssets {
102 deer_body: Part,
103 deer_head: Part,
104 rabbit_body: Part,
105 rabbit_ear: Part,
106 }
107
108 fn create_animal_assets(
109 mut commands: Commands,
110 mut meshes: ResMut<Assets<Mesh>>,
111 mut materials: ResMut<Assets<ColorMaterial>>,
112 ) {
113 let mut part = |mesh: Mesh, color: Color| (meshes.add(mesh), materials.add(color));
114 let deer = Color::srgb_u8(150, 100, 60);
115 let rabbit = Color::srgb_u8(185, 175, 160);
116 commands.insert_resource(AnimalAssets {
117 deer_body: part(
118 Ellipse::new(TILE_SIZE * 0.42, TILE_SIZE * 0.22).into(),
119 deer,
120 ),
121 deer_head: part(
122 Rectangle::new(TILE_SIZE * 0.2, TILE_SIZE * 0.3).into(),
123 Color::srgb_u8(120, 80, 48),
124 ),
125 rabbit_body: part(
126 Ellipse::new(TILE_SIZE * 0.22, TILE_SIZE * 0.15).into(),
127 rabbit,
128 ),
129 rabbit_ear: part(
130 Rectangle::new(TILE_SIZE * 0.06, TILE_SIZE * 0.2).into(),
131 rabbit,
132 ),
133 });
134 }
135
136 fn part_bundle((mesh, material): &Part, transform: Transform) -> impl Bundle {
137 (
138 Mesh2d(mesh.clone()),
139 MeshMaterial2d(material.clone()),
140 transform,
141 )
142 }
143
144 pub fn spawn_animal(commands: &mut Commands, assets: &AnimalAssets, kind: AnimalKind, tile: UVec2) {
145 let at = |x: f32, y: f32| Transform::from_xyz(x * TILE_SIZE, y * TILE_SIZE, 0.01);
146 let mut entity = commands.spawn((
147 Name::new(kind.name()),
148 Animal { kind },
149 MoveSpeed(kind.speed()),
150 TilePos(tile),
151 sim_pos(WorldMap::tile_center(tile)),
152 Transform::from_translation(WorldMap::tile_center(tile).extend(0.9)),
153 ));
154 entity.with_children(|c| match kind {
155 AnimalKind::Deer => {
156 c.spawn(part_bundle(&assets.deer_body, at(0.0, 0.0)));
157 c.spawn(part_bundle(&assets.deer_head, at(0.38, 0.15)));
158 }
159 AnimalKind::Rabbit => {
160 c.spawn(part_bundle(&assets.rabbit_body, at(0.0, 0.0)));
161 c.spawn(part_bundle(&assets.rabbit_ear, at(0.1, 0.2)));
162 c.spawn(part_bundle(&assets.rabbit_ear, at(0.18, 0.2)));
163 }
164 });
165 }
166
167 pub fn wild_tile(map: &WorldMap, rng: &mut SimRng, away_from: UVec2) -> Option<UVec2> {
168 (0..PLACEMENT_ATTEMPTS).find_map(|_| {
169 let tile = IVec2::new(
170 rng.range_i32(0..map.size.x as i32),
171 rng.range_i32(0..map.size.y as i32),
172 );
173 let far = tile.as_vec2().distance(away_from.as_vec2()) >= MIN_DISTANCE_FROM_COLONY;
174 let open = map.move_cost(tile).is_some() && map.plant(tile).is_none();
175 (far && open && !map.get(tile).is_some_and(|t| t.is_water())).then(|| tile.as_uvec2())
176 })
177 }
178
179 fn populate(
180 mut commands: Commands,
181 map: Res<WorldMap>,
182 assets: Res<AnimalAssets>,
183 mut rng: ResMut<SimRng>,
184 existing: Query<Entity, With<Animal>>,
185 ) {
186 for entity in &existing {
187 commands.entity(entity).despawn();
188 }
189 let colony = spawn_tiles(&map, 1)
190 .first()
191 .copied()
192 .unwrap_or(map.size / 2);
193 for kind in AnimalKind::ALL {
194 for _ in 0..kind.population() {
195 if let Some(tile) = wild_tile(&map, &mut rng, colony) {
196 spawn_animal(&mut commands, &assets, kind, tile);
197 }
198 }
199 }
200 }
201
202 pub fn missing_animals(kind: AnimalKind, alive: usize) -> bool {
203 alive < kind.population()
204 }
205
206 fn migrate(
207 mut commands: Commands,
208 tick: Res<SimTick>,
209 map: Res<WorldMap>,
210 assets: Res<AnimalAssets>,
211 mut rng: ResMut<SimRng>,
212 animals: Query<&Animal>,
213 ) {
214 if !tick.0.is_multiple_of(MIGRATION_INTERVAL_TICKS) || tick.0 == 0 {
215 return;
216 }
217 let colony = spawn_tiles(&map, 1)
218 .first()
219 .copied()
220 .unwrap_or(map.size / 2);
221 for kind in AnimalKind::ALL {
222 let alive = animals.iter().filter(|a| a.kind == kind).count();
223 if missing_animals(kind, alive)
224 && let Some(tile) = wild_tile(&map, &mut rng, colony)
225 {
226 spawn_animal(&mut commands, &assets, kind, tile);
227 }
228 }
229 }
230
231 pub fn flee_goal(tile: UVec2, threats: &[UVec2]) -> Option<IVec2> {
232 let near: Vec<IVec2> = threats
233 .iter()
234 .map(|t| t.as_ivec2())
235 .filter(|t| (*t - tile.as_ivec2()).abs().max_element() <= FLEE_RANGE)
236 .collect();
237 if near.is_empty() {
238 return None;
239 }
240 let away: Vec2 = near
241 .iter()
242 .map(|t| (tile.as_ivec2() - *t).as_vec2())
243 .sum::<Vec2>()
244 .normalize_or(Vec2::X);
245 Some(tile.as_ivec2() + (away * FLEE_DISTANCE).round().as_ivec2())
246 }
247
248 pub fn wander(
249 time: Res<Time>,
250 map: Res<WorldMap>,
251 mut rng: ResMut<SimRng>,
252 colonists: Query<&TilePos, (With<Colonist>, Without<Animal>)>,
253 mut animals: Query<(&TilePos, &mut Path, &mut AnimalIdle), With<Animal>>,
254 ) {
255 let threats: Vec<UVec2> = colonists.iter().map(|t| t.0).collect();
256 for (tile, mut path, mut idle) in &mut animals {
257 let heading_into_danger = path
258 .0
259 .back()
260 .is_none_or(|end| flee_goal(*end, &threats).is_some());
261 if heading_into_danger && let Some(goal) = flee_goal(tile.0, &threats) {
262 let goal = goal.clamp(IVec2::ZERO, map.size.as_ivec2() - 1).as_uvec2();
263 if let Some(route) = find_path(&map, tile.0, goal) {
264 path.0 = route.into();
265 continue;
266 }
267 }
268 if !path.0.is_empty() || !idle.0.tick(time.delta()).is_finished() {
269 continue;
270 }
271 let goal = tile.0.as_ivec2()
272 + IVec2::new(
273 rng.range_i32(-WANDER_RADIUS..WANDER_RADIUS + 1),
274 rng.range_i32(-WANDER_RADIUS..WANDER_RADIUS + 1),
275 );
276 if map.in_bounds(goal)
277 && let Some(route) = find_path(&map, tile.0, goal.as_uvec2())
278 {
279 path.0 = route.into();
280 let secs = rng.range_f32(IDLE_SECS);
281 idle.0.set_duration(Duration::from_secs_f32(secs));
282 idle.0.reset();
283 }
284 }
285 }
286
287 #[cfg(test)]
288 mod tests {
289 use super::*;
290 use crate::world::Terrain;
291
292 #[test]
293 fn animals_run_away_from_nearby_colonists() {
294 let tile = UVec2::new(10, 10);
295 let goal = flee_goal(tile, &[UVec2::new(8, 10), UVec2::new(30, 30)]).unwrap();
296 assert!(goal.x > 10 + FLEE_RANGE);
297 assert_eq!(
298 flee_goal(tile, &[UVec2::new(10, 10 + FLEE_RANGE as u32 + 1)]),
299 None
300 );
301 }
302
303 #[test]
304 fn wild_animals_appear_away_from_the_colony_on_open_ground() {
305 let mut map = WorldMap::filled(UVec2::splat(80), Terrain::Grass);
306 map.set_plant(UVec2::new(70, 70), Some(crate::world::Plant::Tree));
307 let mut rng = SimRng::new(3);
308 for _ in 0..50 {
309 let tile = wild_tile(&map, &mut rng, UVec2::new(40, 40)).unwrap();
310 assert!(tile.as_vec2().distance(Vec2::splat(40.0)) >= MIN_DISTANCE_FROM_COLONY);
311 assert!(map.plant(tile.as_ivec2()).is_none());
312 }
313 }
314
315 #[test]
316 fn herds_regrow_up_to_their_population() {
317 assert!(missing_animals(AnimalKind::Deer, 3));
318 assert!(!missing_animals(
319 AnimalKind::Deer,
320 AnimalKind::Deer.population()
321 ));
322 }
323
324 // Hunted animals used to stand still for the hunter; now everything wild bolts from people
325 // nearby, which is why hunters shoot from beyond FLEE_RANGE.
326 #[test]
327 fn idle_animals_wander_and_startled_ones_bolt() {
328 let mut app = App::new();
329 app.insert_resource(WorldMap::filled(UVec2::splat(30), Terrain::Grass))
330 .insert_resource(SimRng::new(1))
331 .init_resource::<Time>()
332 .add_systems(Update, wander);
333 let spawn = |app: &mut App, tile: UVec2| {
334 app.world_mut()
335 .spawn((
336 Animal {
337 kind: AnimalKind::Deer,
338 },
339 TilePos(tile),
340 ))
341 .id()
342 };
343 let idle = spawn(&mut app, UVec2::splat(25));
344 let startled = spawn(&mut app, UVec2::splat(10));
345 app.world_mut()
346 .spawn((Colonist { name: "Ada".into() }, TilePos(UVec2::new(9, 10))));
347 app.update();
348 let route = &app.world().get::<Path>(startled).unwrap().0;
349 assert!(
350 route
351 .back()
352 .is_some_and(|end| end.x > 10 + FLEE_RANGE as u32)
353 );
354 for _ in 0..10 {
355 app.world_mut()
356 .resource_mut::<Time>()
357 .advance_by(Duration::from_secs(1));
358 app.update();
359 }
360 assert!(!app.world().get::<Path>(idle).unwrap().0.is_empty());
361 }
362 }