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