Skip to main content

voxel_framework/mobs/
mod.rs

1//! Simple mob (enemy entity) system for voxel worlds.
2//!
3//! Provides a complete AI loop — patrol → chase → attack — with voxel
4//! collision, gravity, player damage, and death events. Mobs are represented
5//! as capsule-shaped entities that collide with the chunk world using
6//! [`crate::world::resolve_capsule_collision`].
7//!
8//! # Quick start
9//!
10//! ```no_run
11//! use bevy::prelude::*;
12//! use voxel_framework::VoxelPlugin;
13//! use voxel_framework::mobs::{MobPlugin, MobConfig, spawn_mob};
14//! use voxel_framework::voxel::DefaultTerrainVoxel;
15//!
16//! App::new()
17//!     .add_plugins(DefaultPlugins)
18//!     .add_plugins(VoxelPlugin::<DefaultTerrainVoxel>::new())
19//!     .add_plugins(MobPlugin::<DefaultTerrainVoxel>::new())
20//!     .add_systems(Startup, |
21//!         mut commands: Commands,
22//!         mut meshes: ResMut<Assets<Mesh>>,
23//!         mut materials: ResMut<Assets<StandardMaterial>>,
24//!     | {
25//!         spawn_mob(
26//!             Vec3::new(8.0, 70.0, 8.0),
27//!             MobConfig::default(),
28//!             &mut commands, &mut meshes, &mut materials,
29//!         );
30//!     })
31//!     .run();
32//! ```
33
34use bevy::prelude::*;
35
36use crate::chunk::Chunk;
37use crate::player::{Player, PlayerHealth};
38use crate::voxel::VoxelType;
39use crate::world::ChunkManager;
40use crate::world::collision::resolve_capsule_collision;
41
42// ─── Constants ────────────────────────────────────────────────────────────────
43
44/// Half-height of the mob capsule along the Y axis (world units).
45pub const MOB_HALF_HEIGHT: f32 = 0.5;
46/// Radius of the mob capsule (world units).
47pub const MOB_RADIUS: f32 = 0.35;
48
49// ─── Components ───────────────────────────────────────────────────────────────
50
51/// AI behaviour state for a [`Mob`] entity.
52#[derive(Clone, Copy, Debug, PartialEq, Eq)]
53pub enum MobAiState {
54    /// Wanders randomly near the spawn point.
55    Patrol,
56    /// Has detected the player; moves toward them.
57    Chase,
58    /// Close enough to strike; swings at the player.
59    Attack,
60}
61
62/// Core mob component — attached to every mob entity.
63#[derive(Component)]
64pub struct Mob {
65    /// Current hit points. Mob is dead when `<= 0.0`.
66    pub health: f32,
67    /// Current AI mode.
68    pub ai_state: MobAiState,
69    /// Horizontal velocity accumulated this frame (m/s).
70    pub velocity: Vec3,
71    /// Vertical velocity for gravity/jumping (m/s, Y component only).
72    pub vertical_velocity: f32,
73    /// Whether the mob is resting on solid ground.
74    pub on_ground: bool,
75    /// Countdown until the next attack swing (seconds).
76    pub attack_cooldown: f32,
77    /// Accumulated time for patrol direction changes.
78    pub patrol_timer: f32,
79    /// Current patrol walk direction (horizontal, unnormalised may be zero).
80    pub patrol_dir: Vec3,
81    /// World-space position where this mob was spawned (patrol centre).
82    pub home_position: Vec3,
83}
84
85// ─── Config ───────────────────────────────────────────────────────────────────
86
87/// Per-mob-type configuration.
88///
89/// Insert as many [`MobConfig`] instances as you need — one per mob variety.
90/// Pass one to [`spawn_mob`] when spawning an entity.
91#[derive(Clone, Debug)]
92pub struct MobConfig {
93    /// Initial (and maximum) health points.
94    pub max_health: f32,
95    /// Horizontal movement speed while chasing (m/s).
96    pub chase_speed: f32,
97    /// Horizontal movement speed while patrolling (m/s).
98    pub patrol_speed: f32,
99    /// Distance at which the mob detects the player.
100    pub detection_radius: f32,
101    /// Distance at which melee attacks are triggered.
102    pub attack_range: f32,
103    /// Damage dealt per attack swing.
104    pub attack_damage: f32,
105    /// Minimum seconds between attacks.
106    pub attack_cooldown: f32,
107    /// How far the mob wanders from its spawn point while patrolling.
108    pub patrol_radius: f32,
109    /// Distance from the player at which the mob despawns (unloads).
110    pub despawn_distance: f32,
111    /// Gravity acceleration (m/s²). Positive = downward.
112    ///
113    /// `Some(g)` enables grounded behaviour: the mob accelerates downward each
114    /// frame and snaps to the ground via capsule collision (Minecraft-style).
115    /// `None` disables gravity and ground-snapping entirely so the mob floats
116    /// freely in 3D — useful for zero-g / space games where mobs should drift
117    /// alongside a [`crate::player::PlayerMode::FreeFlightSixDof`] player.
118    ///
119    /// In zero-g mode the mob's `vertical_velocity` field stays at `0.0`;
120    /// only horizontal AI velocity drives motion.
121    pub gravity: Option<f32>,
122    /// RGB color used for the default box mesh.
123    pub color: Color,
124}
125
126impl Default for MobConfig {
127    fn default() -> Self {
128        Self {
129            max_health: 20.0,
130            chase_speed: 3.5,
131            patrol_speed: 1.2,
132            detection_radius: 12.0,
133            attack_range: 1.5,
134            attack_damage: 4.0,
135            attack_cooldown: 1.2,
136            patrol_radius: 6.0,
137            despawn_distance: 64.0,
138            gravity: Some(20.0),
139            color: Color::srgb(0.6, 0.1, 0.1),
140        }
141    }
142}
143
144// ─── Events ───────────────────────────────────────────────────────────────────
145
146/// Emitted when a mob's health drops to zero or below.
147///
148/// Systems that handle loot drops or achievements should read this message.
149#[derive(bevy::ecs::message::Message, Debug, Clone)]
150pub struct MobDied {
151    /// World-space position of the mob at the moment of death.
152    pub position: Vec3,
153}
154
155// ─── Spawn ────────────────────────────────────────────────────────────────────
156
157/// Spawns a mob entity at `position` using the given [`MobConfig`].
158///
159/// The mob is rendered as a colored box mesh (1×1×1 voxel).  For custom
160/// visuals, spawn the mob yourself and attach the [`Mob`] component instead.
161pub fn spawn_mob(
162    position: Vec3,
163    config: MobConfig,
164    commands: &mut Commands,
165    meshes: &mut Assets<Mesh>,
166    materials: &mut Assets<StandardMaterial>,
167) -> Entity {
168    let mesh = meshes.add(Cuboid::new(
169        MOB_RADIUS * 2.0,
170        (MOB_HALF_HEIGHT + MOB_RADIUS) * 2.0,
171        MOB_RADIUS * 2.0,
172    ));
173    let material = materials.add(StandardMaterial {
174        base_color: config.color,
175        ..default()
176    });
177    commands
178        .spawn((
179            Mob {
180                health: config.max_health,
181                ai_state: MobAiState::Patrol,
182                velocity: Vec3::ZERO,
183                vertical_velocity: 0.0,
184                on_ground: false,
185                attack_cooldown: 0.0,
186                patrol_timer: 0.0,
187                patrol_dir: Vec3::ZERO,
188                home_position: position,
189            },
190            MobConfigComponent(config),
191            Transform::from_translation(position),
192            Visibility::default(),
193            Mesh3d(mesh),
194            MeshMaterial3d(material),
195        ))
196        .id()
197}
198
199/// Internal component that stores the [`MobConfig`] on the entity so systems
200/// can read it without a separate resource lookup.
201#[derive(Component)]
202pub struct MobConfigComponent(pub MobConfig);
203
204// ─── Systems ──────────────────────────────────────────────────────────────────
205
206fn mob_ai_system(
207    player_q: Query<&Transform, With<Player>>,
208    mut mob_q: Query<(&Transform, &mut Mob, &MobConfigComponent)>,
209    time: Res<Time>,
210) {
211    let Ok(player_tf) = player_q.single() else {
212        return;
213    };
214    let player_pos = player_tf.translation;
215    let dt = time.delta_secs();
216
217    for (mob_tf, mut mob, cfg) in mob_q.iter_mut() {
218        let mob_pos = mob_tf.translation;
219        let dist = mob_pos.distance(player_pos);
220        let config = &cfg.0;
221
222        mob.attack_cooldown = (mob.attack_cooldown - dt).max(0.0);
223        mob.patrol_timer += dt;
224
225        match mob.ai_state {
226            MobAiState::Patrol => {
227                if dist < config.detection_radius {
228                    mob.ai_state = MobAiState::Chase;
229                } else {
230                    // Change patrol direction every 3-5 s using timer.
231                    if mob.patrol_timer > 3.0 {
232                        mob.patrol_timer = 0.0;
233                        // Simple hash-based pseudo-random direction.
234                        let t = mob_pos.x * 13.7 + mob_pos.z * 7.3 + time.elapsed_secs() * 2.3;
235                        mob.patrol_dir = Vec3::new(t.sin(), 0.0, t.cos()).normalize_or_zero();
236                        // Stop walking if too far from home.
237                        if mob_pos.distance(mob.home_position) > config.patrol_radius {
238                            let home_dir = (mob.home_position - mob_pos).normalize_or_zero();
239                            mob.patrol_dir = Vec3::new(home_dir.x, 0.0, home_dir.z);
240                        }
241                    }
242                    mob.velocity = mob.patrol_dir * config.patrol_speed;
243                }
244            }
245            MobAiState::Chase => {
246                if dist > config.detection_radius * 1.5 {
247                    mob.ai_state = MobAiState::Patrol;
248                    mob.patrol_dir = Vec3::ZERO;
249                } else if dist < config.attack_range {
250                    mob.ai_state = MobAiState::Attack;
251                    mob.velocity = Vec3::ZERO;
252                } else {
253                    let dir = (player_pos - mob_pos).normalize_or_zero();
254                    mob.velocity = Vec3::new(dir.x, 0.0, dir.z) * config.chase_speed;
255                }
256            }
257            MobAiState::Attack => {
258                if dist > config.attack_range * 1.5 {
259                    mob.ai_state = MobAiState::Chase;
260                }
261                // Slow creep toward player even in attack state.
262                let dir = (player_pos - mob_pos).normalize_or_zero();
263                mob.velocity = Vec3::new(dir.x, 0.0, dir.z) * (config.chase_speed * 0.3);
264            }
265        }
266    }
267}
268
269fn mob_attack_system(
270    player_q: Query<&Transform, With<Player>>,
271    mut mob_q: Query<(&Transform, &mut Mob, &MobConfigComponent)>,
272    mut player_health: ResMut<PlayerHealth>,
273) {
274    let Ok(player_tf) = player_q.single() else {
275        return;
276    };
277    let player_pos = player_tf.translation;
278
279    for (mob_tf, mut mob, cfg) in mob_q.iter_mut() {
280        if mob.ai_state != MobAiState::Attack {
281            continue;
282        }
283        if mob.attack_cooldown > 0.0 {
284            continue;
285        }
286        let dist = mob_tf.translation.distance(player_pos);
287        if dist <= cfg.0.attack_range {
288            player_health.health = (player_health.health - cfg.0.attack_damage).max(0.0);
289            mob.attack_cooldown = cfg.0.attack_cooldown;
290        }
291    }
292}
293
294fn mob_physics_system<V: VoxelType>(
295    mut mob_q: Query<(&mut Transform, &mut Mob, &MobConfigComponent)>,
296    manager: Res<ChunkManager>,
297    chunks: Query<&Chunk<V>>,
298    time: Res<Time>,
299) {
300    let dt = time.delta_secs();
301    for (mut tf, mut mob, cfg) in mob_q.iter_mut() {
302        match cfg.0.gravity {
303            // ── Grounded mode (Minecraft-style) ───────────────────────────
304            Some(g) => {
305                // Gravity.
306                if !mob.on_ground {
307                    mob.vertical_velocity -= g * dt;
308                }
309
310                let move_delta = (mob.velocity + Vec3::Y * mob.vertical_velocity) * dt;
311                tf.translation += move_delta;
312
313                // Capsule collision.
314                let half = MOB_HALF_HEIGHT;
315                let bottom = tf.translation - Vec3::Y * half;
316                let top = tf.translation + Vec3::Y * half;
317                let push =
318                    resolve_capsule_collision::<V, ()>(bottom, top, MOB_RADIUS, &manager, &chunks);
319                tf.translation += push;
320
321                // Ground detection.
322                if push.y > 0.01 {
323                    mob.on_ground = true;
324                    mob.vertical_velocity = 0.0;
325                } else {
326                    mob.on_ground = false;
327                }
328            }
329            // ── Zero-gravity mode (space / FreeFlight) ────────────────────
330            None => {
331                // No gravity, no ground-snap. The AI's horizontal velocity
332                // drives motion in full 3D. `vertical_velocity` stays at 0
333                // and `on_ground` is meaningless here.
334                mob.vertical_velocity = 0.0;
335                mob.on_ground = false;
336
337                let move_delta = mob.velocity * dt;
338                tf.translation += move_delta;
339
340                // Still resolve capsule collision so mobs can't tunnel
341                // through chunks, but apply the push directly without
342                // ground inference.
343                let half = MOB_HALF_HEIGHT;
344                let bottom = tf.translation - Vec3::Y * half;
345                let top = tf.translation + Vec3::Y * half;
346                let push =
347                    resolve_capsule_collision::<V, ()>(bottom, top, MOB_RADIUS, &manager, &chunks);
348                tf.translation += push;
349            }
350        }
351    }
352}
353
354fn mob_death_system(
355    mob_q: Query<(Entity, &Transform, &Mob)>,
356    mut commands: Commands,
357    mut died_writer: bevy::ecs::message::MessageWriter<MobDied>,
358) {
359    for (entity, tf, mob) in mob_q.iter() {
360        if mob.health <= 0.0 {
361            died_writer.write(MobDied {
362                position: tf.translation,
363            });
364            commands.entity(entity).despawn();
365        }
366    }
367}
368
369fn mob_despawn_system(
370    mob_q: Query<(Entity, &Transform, &MobConfigComponent)>,
371    player_q: Query<&Transform, With<Player>>,
372    mut commands: Commands,
373) {
374    let Ok(player_tf) = player_q.single() else {
375        return;
376    };
377    let player_pos = player_tf.translation;
378    for (entity, tf, cfg) in mob_q.iter() {
379        if tf.translation.distance(player_pos) > cfg.0.despawn_distance {
380            commands.entity(entity).despawn();
381        }
382    }
383}
384
385// ─── Plugin ───────────────────────────────────────────────────────────────────
386
387/// Plugin that wires up all mob systems for voxel type `V`.
388///
389/// Add [`MobPlugin`] after your core voxel plugin. It relies on
390/// [`crate::world::ChunkManager`], [`crate::player::Player`], and
391/// [`crate::player::PlayerHealth`] being present.
392///
393/// # Example
394///
395/// ```no_run
396/// use bevy::prelude::*;
397/// use voxel_framework::VoxelPlugin;
398/// use voxel_framework::mobs::MobPlugin;
399/// use voxel_framework::voxel::DefaultTerrainVoxel;
400///
401/// App::new()
402///     .add_plugins(DefaultPlugins)
403///     .add_plugins(VoxelPlugin::<DefaultTerrainVoxel>::new())
404///     .add_plugins(MobPlugin::<DefaultTerrainVoxel>::new())
405///     .run();
406/// ```
407pub struct MobPlugin<V: VoxelType> {
408    _m: std::marker::PhantomData<V>,
409}
410
411impl<V: VoxelType> MobPlugin<V> {
412    /// Creates a new [`MobPlugin`] for voxel type `V`.
413    pub fn new() -> Self {
414        Self {
415            _m: std::marker::PhantomData,
416        }
417    }
418}
419
420impl<V: VoxelType> Default for MobPlugin<V> {
421    fn default() -> Self {
422        Self::new()
423    }
424}
425
426impl<V: VoxelType> Plugin for MobPlugin<V> {
427    fn build(&self, app: &mut App) {
428        app.add_message::<MobDied>();
429        app.add_systems(
430            Update,
431            (
432                mob_ai_system,
433                mob_attack_system,
434                mob_physics_system::<V>,
435                mob_death_system,
436                mob_despawn_system,
437            ),
438        );
439    }
440}
441
442// ─── Tests ────────────────────────────────────────────────────────────────────
443
444#[cfg(test)]
445mod tests {
446    use super::*;
447
448    /// Pure-Rust mirror of the per-mob branch in [`mob_physics_system`] with
449    /// no chunk collision (push = 0). This lets us unit-test the gravity
450    /// branching logic without spinning up a full Bevy app, matching the
451    /// `src/fragments/mod.rs` test convention of simulating the loop manually.
452    fn step(mob: &mut Mob, tf: &mut Transform, gravity: Option<f32>, dt: f32) {
453        match gravity {
454            Some(g) => {
455                if !mob.on_ground {
456                    mob.vertical_velocity -= g * dt;
457                }
458                let move_delta = (mob.velocity + Vec3::Y * mob.vertical_velocity) * dt;
459                tf.translation += move_delta;
460                // No chunks → push is zero → never grounded in this test.
461                mob.on_ground = false;
462            }
463            None => {
464                mob.vertical_velocity = 0.0;
465                mob.on_ground = false;
466                tf.translation += mob.velocity * dt;
467            }
468        }
469    }
470
471    fn make_mob(velocity: Vec3) -> Mob {
472        Mob {
473            health: 20.0,
474            ai_state: MobAiState::Patrol,
475            velocity,
476            vertical_velocity: 0.0,
477            on_ground: false,
478            attack_cooldown: 0.0,
479            patrol_timer: 0.0,
480            patrol_dir: Vec3::ZERO,
481            home_position: Vec3::ZERO,
482        }
483    }
484
485    #[test]
486    fn mob_default_has_gravity_enabled() {
487        // Grounded behaviour is preserved as the default — existing games
488        // built against MobConfig::default() keep falling under gravity.
489        assert_eq!(MobConfig::default().gravity, Some(20.0));
490    }
491
492    #[test]
493    fn mob_zero_gravity_does_not_fall() {
494        // A mob with `gravity: None` and zero velocity must stay put across
495        // many ticks — vertical_velocity is forced to 0 every step.
496        let mut mob = make_mob(Vec3::ZERO);
497        let mut tf = Transform::from_translation(Vec3::new(0.0, 100.0, 0.0));
498
499        for _ in 0..100 {
500            step(&mut mob, &mut tf, None, 0.1);
501        }
502
503        assert_eq!(tf.translation.y, 100.0, "zero-g mob must not fall");
504        assert_eq!(mob.vertical_velocity, 0.0);
505        assert!(!mob.on_ground);
506    }
507
508    #[test]
509    fn mob_zero_gravity_drifts_with_velocity() {
510        // Horizontal velocity carries through; Y is untouched.
511        let mut mob = make_mob(Vec3::new(2.0, 0.0, 0.0));
512        let mut tf = Transform::from_translation(Vec3::new(0.0, 100.0, 0.0));
513
514        // 10 ticks × 0.1 s × 2 m/s = 2.0 m drift.
515        for _ in 0..10 {
516            step(&mut mob, &mut tf, None, 0.1);
517        }
518
519        assert!(
520            (tf.translation.x - 2.0).abs() < 1e-4,
521            "x drift = {}",
522            tf.translation.x
523        );
524        assert_eq!(tf.translation.y, 100.0, "y must not change in zero-g");
525    }
526
527    #[test]
528    fn mob_with_gravity_falls() {
529        // Sanity check the Some(g) branch: gravity accumulates and the mob
530        // falls when no ground push is applied.
531        let mut mob = make_mob(Vec3::ZERO);
532        let mut tf = Transform::from_translation(Vec3::new(0.0, 100.0, 0.0));
533
534        for _ in 0..10 {
535            step(&mut mob, &mut tf, Some(20.0), 0.1);
536        }
537
538        assert!(
539            tf.translation.y < 100.0,
540            "grounded mob must fall (got y={})",
541            tf.translation.y
542        );
543        assert!(
544            mob.vertical_velocity < 0.0,
545            "vertical velocity must accumulate downward"
546        );
547    }
548}