Skip to main content

voxel_framework/world/
mining.rs

1//! Voxel mining (block-breaking) API.
2//!
3//! # Design — pure functions, no implicit systems
4//!
5//! All logic lives in free functions ([`tick_mining`], [`stop_mining`]) so
6//! that game code retains full control over when and how mining occurs.
7//! [`MiningPlugin`] only registers the required resources and message types;
8//! it adds **no** systems of its own.
9//!
10//! # Integration pattern
11//!
12//! ```no_run
13//! # use bevy::prelude::*;
14//! # use voxel_framework::world::mining::{MiningPlugin, MiningConfig, MiningState,
15//! #     MiningProgress, VoxelBroken, tick_mining, stop_mining};
16//! # use voxel_framework::world::{ChunkManager, ChunkModified};
17//! # use voxel_framework::chunk::Chunk;
18//! # use voxel_framework::voxel::DefaultVoxel;
19//! // 1. Add the plugin once when building the App.
20//! //    App::new().add_plugins(MiningPlugin);
21//!
22//! // 2. In your input system, call tick_mining every frame while the
23//! //    mine button is held, or stop_mining when it is released.
24//! fn my_mining_system(
25//!     mut state:    ResMut<MiningState>,
26//!     config:       Res<MiningConfig>,
27//!     manager:      Res<ChunkManager>,
28//!     mut chunks:   Query<&mut Chunk<DefaultVoxel>>,
29//!     mut broken:   MessageWriter<VoxelBroken>,
30//!     mut progress: MessageWriter<MiningProgress>,
31//!     mut modified: MessageWriter<ChunkModified>,
32//!     time:         Res<Time>,
33//! ) {
34//!     let mining = true; // replace with real input check
35//!     if mining {
36//!         tick_mining(
37//!             IVec3::ZERO, (8, 8, 8),
38//!             time.delta_secs(),
39//!             &mut state, &config, &manager,
40//!             &mut chunks, &mut broken, &mut progress, &mut modified,
41//!         );
42//!     } else {
43//!         stop_mining(&mut state);
44//!     }
45//! }
46//! ```
47
48use bevy::prelude::*;
49
50use crate::chunk::Chunk;
51#[cfg(feature = "items")]
52use crate::items::inventory::{ContainerComponent, PrimaryContainer};
53#[cfg(feature = "items")]
54use crate::items::{HotbarState, ItemType};
55#[cfg(feature = "items")]
56use crate::player::effects::AppliedEffectModifiers;
57use crate::voxel::VoxelType;
58
59use super::{ChunkManager, ChunkModified};
60
61// ─── Resources ───────────────────────────────────────────────────────────────
62
63/// Configuration for the mining system.
64///
65/// Insert this resource before adding [`MiningPlugin`], or mutate it at
66/// runtime to adjust difficulty.
67#[derive(Resource, Debug, Clone)]
68pub struct MiningConfig {
69    /// Time in seconds required to break a single voxel.
70    ///
71    /// Must be greater than zero.  **Default: `1.5` seconds.**
72    pub break_time: f32,
73}
74
75impl Default for MiningConfig {
76    fn default() -> Self {
77        Self { break_time: 1.5 }
78    }
79}
80
81/// Runtime state for the mining system.
82///
83/// Tracks which voxel is currently being mined and how much time has
84/// accumulated toward breaking it.  There is at most one active target at a
85/// time; switching targets resets elapsed time automatically inside
86/// [`tick_mining`].
87///
88/// Call [`stop_mining`] whenever the mine button is released — failing to do
89/// so leaves stale progress that will carry over to the next target.
90#[derive(Resource, Debug)]
91pub struct MiningState {
92    /// The chunk coordinate and local voxel index `(x, y, z)` currently being
93    /// mined, or `None` when no mining is in progress.
94    pub target: Option<(IVec3, (usize, usize, usize))>,
95    /// Accumulated break time in seconds, in the range `[0.0, effective_break_time]`.
96    pub elapsed: f32,
97    /// Normalised break progress in the range `[0.0, 1.0]`.
98    ///
99    /// Equals `elapsed / effective_break_time`.  Reaches `1.0` when the voxel breaks.
100    pub progress: f32,
101    /// Cached effective break time for the current target, in seconds.
102    ///
103    /// Computed once per target as `config.break_time * voxel.hardness()`.
104    /// Initialised to `1.0` until the first mining target is set.
105    pub(crate) effective_break_time: f32,
106}
107
108impl Default for MiningState {
109    fn default() -> Self {
110        Self {
111            target: None,
112            elapsed: 0.0,
113            progress: 0.0,
114            effective_break_time: 1.0,
115        }
116    }
117}
118
119/// Active-tool statistics derived from the hotbar selection each frame.
120///
121/// [`MiningInputPlugin`] keeps this resource up to date via
122/// `hotbar_to_tool_system`. Game code that calls [`tick_mining`] directly
123/// can read or override it as needed.
124#[derive(Resource, Debug, Clone)]
125pub struct ToolStats {
126    /// Minimum tool level required to mine a voxel.
127    ///
128    /// Matched against [`crate::voxel::VoxelType::mining_level`]:
129    /// if `tool_level < voxel.mining_level()`, mining makes no progress.
130    pub tool_level: u8,
131    /// Mining speed multiplier for the active tool.
132    ///
133    /// The effective break time is divided by this value (`2.0` = twice as fast).
134    pub tool_speed: f32,
135}
136
137impl ToolStats {
138    /// Resets stats to bare-hands defaults (level 0, speed 1.0).
139    pub fn reset(&mut self) {
140        self.tool_level = 0;
141        self.tool_speed = 1.0;
142    }
143}
144
145impl Default for ToolStats {
146    fn default() -> Self {
147        Self {
148            tool_level: 0,
149            tool_speed: 1.0,
150        }
151    }
152}
153
154// ─── Messages ────────────────────────────────────────────────────────────────
155
156/// Message fired once when a voxel's break time is fully elapsed.
157///
158/// Emitted by [`tick_mining`] in the same frame the voxel is destroyed.
159/// Systems that react to block destruction (e.g. particle effects, inventory
160/// updates) should read this message.
161#[derive(Message, Debug, Clone)]
162pub struct VoxelBroken {
163    /// Chunk-grid coordinate of the chunk that contained the broken voxel.
164    pub chunk_coord: IVec3,
165    /// Local voxel index `(x, y, z)` within the chunk.  Each component is in
166    /// `[0, CHUNK_SIZE)`.
167    pub local: (usize, usize, usize),
168    /// World-space center of the broken voxel.
169    pub world_pos: Vec3,
170}
171
172/// Message sent every frame while a voxel is being mined.
173///
174/// Useful for driving crack-overlay animations, progress bars, or audio
175/// feedback.  Emitted by [`tick_mining`] on every frame where mining is
176/// active, including the frame the voxel breaks (where `progress` is `1.0`).
177#[derive(Message, Debug, Clone)]
178pub struct MiningProgress {
179    /// Normalised break progress in `[0.0, 1.0]`.
180    ///
181    /// `0.0` on the first frame, `1.0` on the frame the voxel breaks.
182    pub progress: f32,
183    /// World-space center of the voxel being mined.
184    pub world_pos: Vec3,
185}
186
187// ─── Free functions ───────────────────────────────────────────────────────────
188
189/// Breaks a single voxel at world-voxel coordinates `world_voxel` if it is
190/// solid and its chunk is loaded.  Emits [`VoxelBroken`], [`ChunkModified`],
191/// and border-neighbor notifications.
192fn break_voxel<V: VoxelType>(
193    world_voxel: IVec3,
194    manager: &ChunkManager,
195    chunks: &mut Query<&mut Chunk<V>>,
196    broken: &mut MessageWriter<VoxelBroken>,
197    modified: &mut MessageWriter<ChunkModified>,
198) {
199    use crate::chunk::CHUNK_SIZE;
200    let cs = CHUNK_SIZE as i32;
201    let chunk_coord = IVec3::new(
202        world_voxel.x.div_euclid(cs),
203        world_voxel.y.div_euclid(cs),
204        world_voxel.z.div_euclid(cs),
205    );
206    let local = (
207        world_voxel.x.rem_euclid(cs) as usize,
208        world_voxel.y.rem_euclid(cs) as usize,
209        world_voxel.z.rem_euclid(cs) as usize,
210    );
211
212    let Some(entity) = manager.get_entity(chunk_coord) else {
213        return;
214    };
215    let Ok(mut chunk) = chunks.get_mut(entity) else {
216        return;
217    };
218    if !chunk.is_solid_at(local.0, local.1, local.2) {
219        return;
220    }
221    chunk.set(local.0, local.1, local.2, V::air());
222    drop(chunk);
223
224    let wp = voxel_world_pos(chunk_coord, local);
225    broken.write(VoxelBroken {
226        chunk_coord,
227        local,
228        world_pos: wp,
229    });
230    modified.write(ChunkModified(chunk_coord));
231    notify_border_neighbors(chunk_coord, local, modified);
232}
233
234/// Returns the three extra world-voxel offsets that form a 2×2 square on the
235/// hit face together with the primary voxel.
236///
237/// The two tangent axes are determined by `face_normal`.  For each axis the
238/// sign of the offset is chosen so that the 2×2 quad lies in the quadrant
239/// where the ray actually entered the face (using `hit_point` vs
240/// `voxel_center`).
241fn quad_offsets(face_normal: Vec3, hit_point: Vec3, voxel_center: Vec3) -> [IVec3; 3] {
242    let sign = |coord: f32, center: f32| -> i32 { if coord >= center { 1 } else { -1 } };
243    let (du, dv) = if face_normal.x.abs() > 0.5 {
244        // X face → perpendicular plane is YZ
245        (
246            IVec3::new(0, sign(hit_point.y, voxel_center.y), 0),
247            IVec3::new(0, 0, sign(hit_point.z, voxel_center.z)),
248        )
249    } else if face_normal.y.abs() > 0.5 {
250        // Y face → perpendicular plane is XZ
251        (
252            IVec3::new(sign(hit_point.x, voxel_center.x), 0, 0),
253            IVec3::new(0, 0, sign(hit_point.z, voxel_center.z)),
254        )
255    } else {
256        // Z face (or zero normal) → perpendicular plane is XY
257        (
258            IVec3::new(sign(hit_point.x, voxel_center.x), 0, 0),
259            IVec3::new(0, sign(hit_point.y, voxel_center.y), 0),
260        )
261    };
262    [du, dv, du + dv]
263}
264
265/// Sends [`ChunkModified`] for any neighboring chunks whose border shares the
266/// face of the voxel at `local` within `chunk_coord`.
267///
268/// When a voxel on the edge of a chunk is added or removed, the adjacent
269/// chunk's mesh must also be regenerated — its border faces were previously
270/// culled by this voxel and are now exposed (or vice versa for placement).
271fn notify_border_neighbors(
272    chunk_coord: IVec3,
273    local: (usize, usize, usize),
274    modified: &mut MessageWriter<ChunkModified>,
275) {
276    use crate::chunk::CHUNK_SIZE;
277    let (x, y, z) = local;
278    let offsets: [(usize, IVec3); 6] = [
279        (x, IVec3::NEG_X),
280        (CHUNK_SIZE - 1 - x, IVec3::X),
281        (y, IVec3::NEG_Y),
282        (CHUNK_SIZE - 1 - y, IVec3::Y),
283        (z, IVec3::NEG_Z),
284        (CHUNK_SIZE - 1 - z, IVec3::Z),
285    ];
286    for (dist, dir) in offsets {
287        if dist == 0 {
288            modified.write(ChunkModified(chunk_coord + dir));
289        }
290    }
291}
292
293/// Compute the world-space center of a voxel given its chunk coord and local index.
294fn voxel_world_pos(chunk_coord: IVec3, local: (usize, usize, usize)) -> Vec3 {
295    let chunk_origin = chunk_coord.as_vec3() * crate::chunk::CHUNK_SIZE as f32;
296    chunk_origin
297        + Vec3::new(
298            local.0 as f32 + 0.5,
299            local.1 as f32 + 0.5,
300            local.2 as f32 + 0.5,
301        )
302}
303
304/// Advance mining by one frame toward breaking the target voxel.
305///
306/// Call this **every frame** while the mine button is held.  When the
307/// accumulated time reaches `config.break_time` the function:
308///
309/// 1. Sets the target voxel to air (if the chunk is loaded).
310/// 2. Writes a [`VoxelBroken`] message.
311/// 3. Writes a [`ChunkModified`] message to trigger remeshing.
312/// 4. Resets `state` so a new target can start fresh.
313///
314/// A [`MiningProgress`] message is written on **every** call, including the
315/// break frame.
316///
317/// If `target_chunk` / `target_local` differs from the previous frame, elapsed
318/// time is reset to zero automatically — no need to call [`stop_mining`] when
319/// switching targets mid-frame.
320///
321/// # Parameters
322///
323/// - `target_chunk` — Chunk-grid coordinate of the chunk containing the target
324///   voxel.
325/// - `target_local` — Local `(x, y, z)` voxel index within the chunk.
326/// - `delta_secs` — Frame delta time in seconds (typically `time.delta_secs()`).
327/// - `state` — Mutable reference to the shared [`MiningState`] resource.
328/// - `config` — Read-only mining configuration (break time).
329/// - `manager` — Chunk registry used to look up the chunk entity.
330/// - `chunks` — Mutable query used to set voxels to air on break.
331/// - `broken` — Message writer for [`VoxelBroken`].
332/// - `progress_writer` — Message writer for [`MiningProgress`].
333/// - `modified` — Message writer for [`crate::world::ChunkModified`].
334///
335/// # Examples
336///
337/// ```no_run
338/// # use bevy::prelude::*;
339/// # use voxel_framework::world::mining::{MiningConfig, MiningState, MiningProgress, VoxelBroken, tick_mining};
340/// # use voxel_framework::world::{ChunkManager, ChunkModified};
341/// # use voxel_framework::chunk::Chunk;
342/// # use voxel_framework::voxel::DefaultVoxel;
343/// fn my_system(
344///     mut state:    ResMut<MiningState>,
345///     config:       Res<MiningConfig>,
346///     manager:      Res<ChunkManager>,
347///     mut chunks:   Query<&mut Chunk<DefaultVoxel>>,
348///     mut broken:   MessageWriter<VoxelBroken>,
349///     mut progress: MessageWriter<MiningProgress>,
350///     mut modified: MessageWriter<ChunkModified>,
351///     time:         Res<Time>,
352/// ) {
353///     tick_mining(
354///         IVec3::ZERO, (4, 0, 4),
355///         time.delta_secs(),
356///         &mut state, &config, &manager,
357///         &mut chunks, &mut broken, &mut progress, &mut modified,
358///     );
359/// }
360/// ```
361#[allow(clippy::too_many_arguments)]
362pub fn tick_mining<V: VoxelType>(
363    target_chunk: IVec3,
364    target_local: (usize, usize, usize),
365    delta_secs: f32,
366    state: &mut MiningState,
367    config: &MiningConfig,
368    manager: &ChunkManager,
369    chunks: &mut Query<&mut Chunk<V>>,
370    broken: &mut MessageWriter<VoxelBroken>,
371    progress_writer: &mut MessageWriter<MiningProgress>,
372    modified: &mut MessageWriter<ChunkModified>,
373) {
374    // Reset elapsed when target changes and sample the new voxel's hardness.
375    if state.target != Some((target_chunk, target_local)) {
376        let hardness = manager
377            .get_entity(target_chunk)
378            .and_then(|e| chunks.get(e).ok())
379            .map(|chunk| {
380                let (x, y, z) = target_local;
381                chunk.get(x, y, z).hardness()
382            })
383            .unwrap_or(1.0);
384
385        // Hardness 0.0 means unbreakable — use a very large break time.
386        state.effective_break_time = if hardness > 0.0 {
387            config.break_time * hardness
388        } else {
389            f32::MAX
390        };
391        state.elapsed = 0.0;
392        state.progress = 0.0;
393        state.target = Some((target_chunk, target_local));
394    }
395
396    state.elapsed += delta_secs;
397    state.progress = (state.elapsed / state.effective_break_time).min(1.0);
398
399    let world_pos = voxel_world_pos(target_chunk, target_local);
400
401    progress_writer.write(MiningProgress {
402        progress: state.progress,
403        world_pos,
404    });
405
406    if state.progress >= 1.0 && state.effective_break_time < f32::MAX {
407        // Destroy the voxel if the chunk is loaded.
408        if let Some(entity) = manager.get_entity(target_chunk) {
409            if let Ok(mut chunk) = chunks.get_mut(entity) {
410                let (x, y, z) = target_local;
411                chunk.set(x, y, z, V::air());
412            }
413        }
414
415        broken.write(VoxelBroken {
416            chunk_coord: target_chunk,
417            local: target_local,
418            world_pos,
419        });
420
421        modified.write(ChunkModified(target_chunk));
422        notify_border_neighbors(target_chunk, target_local, modified);
423
424        // Reset state.
425        state.target = None;
426        state.elapsed = 0.0;
427        state.progress = 0.0;
428    }
429}
430
431/// Stop mining and reset all accumulated progress.
432///
433/// Call this whenever the mine button is released.  Failing to call
434/// `stop_mining` means any partial progress persists, and the next target
435/// will appear to start partially broken.
436///
437/// # Examples
438///
439/// ```no_run
440/// # use voxel_framework::world::mining::{MiningState, stop_mining};
441/// fn on_button_release(mut state: bevy::prelude::ResMut<MiningState>) {
442///     stop_mining(&mut state);
443/// }
444/// ```
445pub fn stop_mining(state: &mut MiningState) {
446    state.target = None;
447    state.elapsed = 0.0;
448    state.progress = 0.0;
449}
450
451// ─── Plugin ───────────────────────────────────────────────────────────────────
452
453/// Bevy plugin that registers the mining subsystem.
454///
455/// Adds the following to the [`bevy::prelude::App`]:
456///
457/// - [`MiningConfig`] resource (initialised with defaults — `break_time: 1.5 s`)
458/// - [`MiningState`] resource (initialised at default / idle)
459/// - [`VoxelBroken`] message type
460/// - [`MiningProgress`] message type
461///
462/// Does **not** add any systems.  Game code is responsible for calling
463/// [`tick_mining`] and [`stop_mining`] from its own update systems.
464pub struct MiningPlugin;
465
466impl Plugin for MiningPlugin {
467    fn build(&self, app: &mut App) {
468        app.init_resource::<MiningConfig>();
469        app.init_resource::<MiningState>();
470        app.add_message::<VoxelBroken>();
471        app.add_message::<MiningProgress>();
472    }
473}
474
475// ─── MiningInputPlugin ────────────────────────────────────────────────────────
476//
477// `MiningInputPlugin` and its companion `hotbar_to_tool_system` are gated on the
478// `items` feature because they require `ItemType`, `HotbarState`,
479// `ContainerComponent`, and `PrimaryContainer` — all of which live in
480// `crate::items`. Disabling the feature compiles them out cleanly.
481
482/// Convenience plugin that wires mouse input to the mining API automatically.
483///
484/// `MiningInputPlugin<V, I>` adds two [`Update`] systems:
485///
486/// 1. `hotbar_to_tool_system` — reads the active hotbar slot from [`Inventory<I>`](crate::items::Inventory)
487///    and updates [`ToolStats`] with the slot's tool level and speed each frame.
488/// 2. `mining_input_system` — raycasts from the active [`Camera3d`] (max
489///    `6.0` world units). While the **left mouse button** is held and the ray
490///    hits a solid voxel whose [`crate::voxel::VoxelType::mining_level`] is
491///    satisfied by the current [`ToolStats::tool_level`], calls [`tick_mining`]
492///    to accumulate break progress. When the button is released (or no voxel is
493///    hit, or the tool level is too low), calls [`stop_mining`].
494///
495/// # Prerequisites
496///
497/// [`MiningPlugin`] must be added **before** this plugin so that the required
498/// resources ([`MiningState`], [`MiningConfig`]) and message channels
499/// ([`VoxelBroken`], [`MiningProgress`]) are already registered.
500///
501/// A player entity with [`crate::items::inventory::ContainerComponent<I>`] and
502/// [`crate::items::inventory::PrimaryContainer`] must be present (typically spawned
503/// in a `Startup` system).
504///
505/// # Example
506///
507/// ```no_run
508/// use bevy::prelude::*;
509/// use voxel_framework::{VoxelPlugin, generator::{GeneratorPlugin, GeneratorResource}};
510/// use voxel_framework::world::mining::MiningInputPlugin;
511/// use voxel_framework::voxel::DefaultTerrainVoxel;
512/// use voxel_framework::items::DefaultItem;
513///
514/// App::new()
515///     .add_plugins(DefaultPlugins)
516///     .add_plugins(VoxelPlugin::<DefaultTerrainVoxel>::new())
517///     .add_plugins(MiningInputPlugin::<DefaultTerrainVoxel, DefaultItem>::new())
518///     .run();
519/// ```
520#[cfg(feature = "items")]
521pub struct MiningInputPlugin<V: VoxelType, I: ItemType> {
522    _m: std::marker::PhantomData<(V, I)>,
523}
524
525#[cfg(feature = "items")]
526impl<V: VoxelType, I: ItemType> MiningInputPlugin<V, I> {
527    /// Creates a new [`MiningInputPlugin`] for voxel type `V` and item type `I`.
528    pub fn new() -> Self {
529        Self {
530            _m: std::marker::PhantomData,
531        }
532    }
533}
534
535#[cfg(feature = "items")]
536impl<V: VoxelType, I: ItemType> Default for MiningInputPlugin<V, I> {
537    fn default() -> Self {
538        Self::new()
539    }
540}
541
542#[cfg(feature = "items")]
543impl<V: VoxelType, I: ItemType> Plugin for MiningInputPlugin<V, I> {
544    fn build(&self, app: &mut App) {
545        app.init_resource::<ToolStats>();
546        app.add_systems(
547            Update,
548            (hotbar_to_tool_system::<I>, mining_input_system::<V>).chain(),
549        );
550    }
551}
552
553/// Updates [`ToolStats`] from the active hotbar slot each frame.
554///
555/// Reads the [`ContainerComponent`] on the [`PrimaryContainer`] entity.
556/// If no such entity exists, resets to bare-hands stats silently.
557///
558/// Added automatically by [`MiningInputPlugin`] — do not add manually.
559#[cfg(feature = "items")]
560pub fn hotbar_to_tool_system<I: ItemType>(
561    hotbar: Res<HotbarState>,
562    container_query: Query<&ContainerComponent<I>, With<PrimaryContainer>>,
563    mut tool_stats: ResMut<ToolStats>,
564    applied: Option<Res<AppliedEffectModifiers>>,
565) {
566    let Ok(container) = container_query.single() else {
567        tool_stats.reset();
568        return;
569    };
570    let active_slot = hotbar.selected;
571    if let Some(slot) = container.0.slots.get(active_slot).and_then(|s| s.as_ref()) {
572        tool_stats.tool_level = slot.item.tool_level();
573        tool_stats.tool_speed = slot.item.tool_speed()
574            * applied
575                .as_deref()
576                .map(|a| a.0.mining_speed_mult)
577                .unwrap_or(1.0);
578    } else {
579        tool_stats.reset();
580    }
581}
582
583/// System added by [`MiningInputPlugin`].
584///
585/// Raycasts from the camera and drives [`tick_mining`] / [`stop_mining`] based
586/// on left-mouse-button state and [`ToolStats`]. Added automatically — do not
587/// add this system manually when using [`MiningInputPlugin`].
588pub fn mining_input_system<V: VoxelType>(
589    buttons: Res<ButtonInput<MouseButton>>,
590    camera_q: Query<&GlobalTransform, With<Camera3d>>,
591    manager: Res<ChunkManager>,
592    mut chunks: Query<&mut crate::chunk::Chunk<V>>,
593    mut state: ResMut<MiningState>,
594    config: Res<MiningConfig>,
595    tool_stats: Res<ToolStats>,
596    mut broken: MessageWriter<VoxelBroken>,
597    mut progress: MessageWriter<MiningProgress>,
598    mut modified: MessageWriter<ChunkModified>,
599    time: Res<Time>,
600) {
601    if !buttons.pressed(MouseButton::Left) {
602        stop_mining(&mut state);
603        return;
604    }
605
606    let Ok(cam_tf) = camera_q.single() else {
607        return;
608    };
609
610    let origin = cam_tf.translation();
611    let direction = cam_tf.forward().as_vec3();
612
613    // `transmute_lens` gives a read-only view without a second conflicting query.
614    let mut lens = chunks.transmute_lens::<&crate::chunk::Chunk<V>>();
615    let Some(hit) = super::raycast::raycast(origin, direction, 6.0, &manager, &lens.query()) else {
616        stop_mining(&mut state);
617        return;
618    };
619
620    // Check that the active tool can mine this voxel type.
621    let voxel_mining_level = lens
622        .query()
623        .get(
624            manager
625                .get_entity(hit.chunk_coord)
626                .unwrap_or(Entity::PLACEHOLDER),
627        )
628        .map(|chunk| {
629            let (x, y, z) = hit.local;
630            chunk.get(x, y, z).mining_level()
631        })
632        .unwrap_or(0);
633
634    if tool_stats.tool_level < voxel_mining_level {
635        stop_mining(&mut state);
636        return;
637    }
638
639    // Apply tool speed to the effective delta — faster tools reduce break time.
640    let effective_delta = time.delta_secs() * tool_stats.tool_speed;
641
642    // Snapshot before tick so we can detect the break event below.
643    let was_mining = state.target.is_some();
644
645    tick_mining(
646        hit.chunk_coord,
647        hit.local,
648        effective_delta,
649        &mut state,
650        &config,
651        &manager,
652        &mut chunks,
653        &mut broken,
654        &mut progress,
655        &mut modified,
656    );
657
658    // If the primary block just broke, also break the 3 adjacent blocks that
659    // form a 2×2 square on the struck face.
660    if was_mining && state.target.is_none() {
661        use crate::chunk::CHUNK_SIZE;
662        let cs = CHUNK_SIZE as i32;
663        let vx = hit.chunk_coord.x * cs + hit.local.0 as i32;
664        let vy = hit.chunk_coord.y * cs + hit.local.1 as i32;
665        let vz = hit.chunk_coord.z * cs + hit.local.2 as i32;
666        let primary = IVec3::new(vx, vy, vz);
667        let center = Vec3::new(vx as f32 + 0.5, vy as f32 + 0.5, vz as f32 + 0.5);
668        let hit_pt = origin + hit.distance * direction.normalize();
669
670        for offset in quad_offsets(hit.face_normal, hit_pt, center) {
671            break_voxel(
672                primary + offset,
673                &manager,
674                &mut chunks,
675                &mut broken,
676                &mut modified,
677            );
678        }
679    }
680}
681
682// ─── Tests ────────────────────────────────────────────────────────────────────
683
684#[cfg(test)]
685mod tests {
686    use super::*;
687
688    fn default_config() -> MiningConfig {
689        MiningConfig { break_time: 1.5 }
690    }
691
692    // ── stop_mining ──────────────────────────────────────────────────────────
693
694    #[test]
695    fn stop_mining_resets_state() {
696        let mut state = MiningState {
697            target: Some((IVec3::ZERO, (1, 2, 3))),
698            elapsed: 0.8,
699            progress: 0.5,
700            effective_break_time: 1.0,
701        };
702        stop_mining(&mut state);
703        assert!(state.target.is_none());
704        assert_eq!(state.elapsed, 0.0);
705        assert_eq!(state.progress, 0.0);
706    }
707
708    // ── progress calculation ──────────────────────────────────────────────────
709
710    #[test]
711    fn test_mining_progress_accumulates() {
712        let config = default_config();
713        let mut state = MiningState::default();
714
715        // Manually simulate two ticks without Bevy context.
716        let target = (IVec3::ZERO, (0usize, 0usize, 0usize));
717
718        // First tick: set target and advance elapsed.
719        if state.target != Some(target) {
720            state.elapsed = 0.0;
721            state.progress = 0.0;
722            state.target = Some(target);
723        }
724        state.elapsed += 0.3;
725        state.progress = (state.elapsed / config.break_time).min(1.0);
726
727        assert!((state.elapsed - 0.3).abs() < f32::EPSILON);
728
729        // Second tick: same target, keep accumulating.
730        state.elapsed += 0.4;
731        state.progress = (state.elapsed / config.break_time).min(1.0);
732
733        assert!((state.elapsed - 0.7).abs() < f32::EPSILON);
734        assert!(state.progress > 0.0 && state.progress < 1.0);
735    }
736
737    #[test]
738    fn test_mining_resets_on_target_change() {
739        let config = default_config();
740        let mut state = MiningState::default();
741
742        let target_a = (IVec3::ZERO, (0usize, 0usize, 0usize));
743        let target_b = (IVec3::ONE, (1usize, 1usize, 1usize));
744
745        // Mine target A for a bit.
746        state.target = Some(target_a);
747        state.elapsed += 0.5;
748        state.progress = (state.elapsed / config.break_time).min(1.0);
749
750        assert!(state.elapsed > 0.0);
751
752        // Switch to target B — should reset.
753        if state.target != Some(target_b) {
754            state.elapsed = 0.0;
755            state.progress = 0.0;
756            state.target = Some(target_b);
757        }
758
759        assert_eq!(state.elapsed, 0.0);
760        assert_eq!(state.progress, 0.0);
761        assert_eq!(state.target, Some(target_b));
762    }
763
764    #[test]
765    fn test_mining_completes_at_break_time() {
766        let config = default_config();
767        let mut state = MiningState::default();
768
769        // Simulate ticks until elapsed >= break_time.
770        let target = (IVec3::ZERO, (0usize, 0usize, 0usize));
771        state.target = Some(target);
772
773        let mut completed = false;
774        let tick = 0.5_f32;
775        for _ in 0..10 {
776            state.elapsed += tick;
777            state.progress = (state.elapsed / config.break_time).min(1.0);
778            if state.progress >= 1.0 {
779                completed = true;
780                break;
781            }
782        }
783
784        assert!(completed, "mining should complete within 10 ticks of 0.5s");
785        assert_eq!(state.progress, 1.0);
786    }
787
788    #[test]
789    fn progress_is_clamped_to_one() {
790        let config = default_config();
791        let mut state = MiningState::default();
792
793        // Way more elapsed than break_time.
794        state.elapsed = 99.0;
795        state.progress = (state.elapsed / config.break_time).min(1.0);
796
797        assert_eq!(state.progress, 1.0);
798    }
799
800    // Mirrors the production formula at `tick_mining` (mining.rs:376-388).
801    fn compute_effective_break_time(break_time: f32, hardness: f32) -> f32 {
802        if hardness > 0.0 {
803            break_time * hardness
804        } else {
805            f32::MAX
806        }
807    }
808
809    // Mirrors the gating + tool-speed multiplier at `mining_input_system`
810    // (mining.rs:615-621). Returns the per-call delta passed into `tick_mining`,
811    // or `None` if the tool level gate blocks progress.
812    fn gated_effective_delta(
813        delta: f32,
814        tool_level: u8,
815        tool_speed: f32,
816        voxel_mining_level: u8,
817    ) -> Option<f32> {
818        if tool_level < voxel_mining_level {
819            None
820        } else {
821            Some(delta * tool_speed)
822        }
823    }
824
825    #[test]
826    fn hardness_zero_is_unbreakable() {
827        let config = default_config();
828        let hardness = 0.0;
829        let effective = compute_effective_break_time(config.break_time, hardness);
830
831        assert_eq!(effective, f32::MAX);
832
833        let mut state = MiningState {
834            target: Some((IVec3::ZERO, (0, 0, 0))),
835            elapsed: 0.0,
836            progress: 0.0,
837            effective_break_time: effective,
838        };
839
840        // Simulate a long delta — progress must remain effectively zero.
841        for _ in 0..1_000 {
842            state.elapsed += 10.0;
843            state.progress = (state.elapsed / state.effective_break_time).min(1.0);
844        }
845
846        assert!(state.progress < 1.0);
847        assert!(state.progress < f32::EPSILON * 1_000.0);
848        // Production code at mining.rs:397 only emits VoxelBroken when
849        // `effective_break_time < f32::MAX`, so the unbreakable branch
850        // never reaches the break message.
851        assert_eq!(state.effective_break_time, f32::MAX);
852    }
853
854    #[test]
855    fn hardness_scales_break_time() {
856        let break_time = 1.5_f32;
857        let hardness = 3.0_f32;
858        let effective = compute_effective_break_time(break_time, hardness);
859        assert!((effective - 4.5).abs() < f32::EPSILON);
860    }
861
862    #[test]
863    fn tool_level_below_mining_level_blocks_progress() {
864        let delta = gated_effective_delta(0.1, 1, 1.0, 2);
865        assert!(
866            delta.is_none(),
867            "tool_level=1 must not mine voxel with mining_level=2"
868        );
869
870        // Confirm `stop_mining` semantics — state resets when gate trips.
871        let mut state = MiningState {
872            target: Some((IVec3::ZERO, (0, 0, 0))),
873            elapsed: 0.4,
874            progress: 0.2,
875            effective_break_time: 1.5,
876        };
877        stop_mining(&mut state);
878        assert!(state.target.is_none());
879        assert_eq!(state.elapsed, 0.0);
880        assert_eq!(state.progress, 0.0);
881    }
882
883    #[test]
884    fn tool_level_meets_requirement_progresses() {
885        let config = default_config();
886        let delta = gated_effective_delta(0.1, 1, 1.0, 1)
887            .expect("tool_level=1 must satisfy mining_level=1 gate");
888        assert!((delta - 0.1).abs() < f32::EPSILON);
889
890        let hardness = 1.0_f32;
891        let effective = compute_effective_break_time(config.break_time, hardness);
892        let mut state = MiningState {
893            target: Some((IVec3::ZERO, (0, 0, 0))),
894            elapsed: 0.0,
895            progress: 0.0,
896            effective_break_time: effective,
897        };
898
899        for _ in 0..3 {
900            state.elapsed += delta;
901            state.progress = (state.elapsed / state.effective_break_time).min(1.0);
902        }
903
904        assert!(state.progress > 0.0);
905        assert!(state.progress < 1.0);
906    }
907
908    #[test]
909    fn tool_speed_scales_delta() {
910        let break_time = 1.5_f32;
911        let hardness = 1.0_f32;
912        let tool_speed = 2.0_f32;
913        let frame_delta = 0.1_f32;
914
915        let effective_delta = gated_effective_delta(frame_delta, 0, tool_speed, 0)
916            .expect("level-0 voxel is breakable by bare hands");
917        assert!(
918            (effective_delta - 0.2).abs() < f32::EPSILON,
919            "tool_speed=2.0 must double the per-call delta"
920        );
921
922        let effective_break_time = compute_effective_break_time(break_time, hardness);
923        let mut state = MiningState {
924            target: Some((IVec3::ZERO, (0, 0, 0))),
925            elapsed: 0.0,
926            progress: 0.0,
927            effective_break_time,
928        };
929
930        // Simulate ~0.75 s of real time at frame_delta = 0.1.
931        let frames_for_half_time = (0.75 / frame_delta).ceil() as usize;
932        for _ in 0..frames_for_half_time {
933            state.elapsed += effective_delta;
934            state.progress = (state.elapsed / state.effective_break_time).min(1.0);
935        }
936
937        assert!(
938            state.progress >= 1.0,
939            "tool_speed=2.0 must reach progress=1.0 at ~half the nominal break time \
940             (expected >=1.0, got {})",
941            state.progress
942        );
943    }
944}