Skip to main content

voxel_framework/crafting/
mod.rs

1//! Crafting system — shapeless recipes, registry, and in-game crafting menu.
2//!
3//! # Data model
4//!
5//! [`CraftingRegistry<I>`] is a Bevy resource that holds a list of
6//! [`CraftingRecipe<I>`] values. Each recipe describes a set of input
7//! ingredients and output items. Recipes are *shapeless* — only item types and
8//! counts matter, not arrangement in a grid.
9//!
10//! # Crafting logic
11//!
12//! [`try_craft`] is a pure function: it verifies that the inventory holds
13//! enough of every ingredient, consumes them atomically, and produces the
14//! outputs. [`can_craft`] performs the read-only check without side effects.
15//!
16//! # UI
17//!
18//! [`CraftingPlugin<I>`] adds a crafting menu toggled by the `C` key.
19//! The menu lists every registered recipe and highlights those the player can
20//! currently craft. Clicking a highlighted row invokes [`try_craft`].
21//!
22//! # Integration
23//!
24//! ```no_run
25//! use bevy::prelude::*;
26//! use voxel_framework::crafting::{CraftingPlugin, CraftingRecipe, CraftingIngredient, CraftingRegistry};
27//! use voxel_framework::items::DefaultItem;
28//!
29//! App::new()
30//!     .add_plugins(CraftingPlugin::<DefaultItem>::new())
31//!     .add_systems(Startup, register_recipes);
32//!
33//! fn register_recipes(mut registry: ResMut<CraftingRegistry<DefaultItem>>) {
34//!     registry.add(CraftingRecipe {
35//!         name: "Crystal from Ore",
36//!         ingredients: vec![CraftingIngredient { item: DefaultItem::IronOre, count: 4 }],
37//!         outputs:     vec![CraftingIngredient { item: DefaultItem::Crystal,  count: 1 }],
38//!     });
39//! }
40//! ```
41
42use std::marker::PhantomData;
43
44use bevy::prelude::*;
45
46use crate::items::ItemType;
47use crate::items::inventory::{Container, ContainerComponent, PrimaryContainer};
48
49// ─── Data layer ───────────────────────────────────────────────────────────────
50
51/// A single ingredient entry: the item type and the required or produced quantity.
52#[derive(Debug, Clone)]
53pub struct CraftingIngredient<I> {
54    /// The item type consumed or produced.
55    pub item: I,
56    /// How many items are consumed or produced.
57    pub count: u32,
58}
59
60/// A shapeless crafting recipe: consume [`ingredients`](CraftingRecipe::ingredients),
61/// produce [`outputs`](CraftingRecipe::outputs).
62///
63/// "Shapeless" means arrangement in a crafting grid is not modelled — only item
64/// types and counts matter.
65#[derive(Debug, Clone)]
66pub struct CraftingRecipe<I> {
67    /// Short human-readable name shown in the crafting menu.
68    pub name: &'static str,
69    /// Items consumed from the player's inventory when this recipe is crafted.
70    pub ingredients: Vec<CraftingIngredient<I>>,
71    /// Items added to the player's inventory when this recipe is crafted.
72    pub outputs: Vec<CraftingIngredient<I>>,
73}
74
75/// Registry of all crafting recipes available in the game.
76///
77/// Inserted automatically by [`CraftingPlugin`] as an empty resource.
78/// Populate it from a startup system before the crafting menu is first opened.
79#[derive(Resource, Debug, Clone, Default)]
80pub struct CraftingRegistry<I: ItemType> {
81    /// Ordered list of registered recipes. Indices are stable for the session.
82    pub recipes: Vec<CraftingRecipe<I>>,
83}
84
85impl<I: ItemType> CraftingRegistry<I> {
86    /// Appends a recipe to the registry.
87    pub fn add(&mut self, recipe: CraftingRecipe<I>) {
88        self.recipes.push(recipe);
89    }
90}
91
92// ─── Pure crafting functions ──────────────────────────────────────────────────
93
94/// Reason a craft attempt failed.
95#[derive(Debug, Clone, PartialEq, Eq)]
96pub enum CraftingError {
97    /// No recipe exists at the given index.
98    InvalidRecipe,
99    /// The inventory does not hold enough of one or more ingredients.
100    InsufficientIngredients,
101    /// The inventory does not have room for the produced outputs.
102    InventoryFull,
103}
104
105/// Returns `true` if the container satisfies all ingredients of `recipe_index`.
106///
107/// Does **not** mutate the container.
108pub fn can_craft<I: ItemType>(
109    registry: &CraftingRegistry<I>,
110    inventory: &impl Container<I>,
111    recipe_index: usize,
112) -> bool {
113    let Some(recipe) = registry.recipes.get(recipe_index) else {
114        return false;
115    };
116    recipe
117        .ingredients
118        .iter()
119        .all(|ing| inventory.count_of(ing.item) >= ing.count)
120}
121
122/// Attempts to craft recipe `recipe_index`, consuming ingredients and producing
123/// outputs.
124///
125/// # Atomicity
126///
127/// All preconditions are checked before any mutation:
128/// - The recipe must exist.
129/// - The container must hold enough of every ingredient.
130/// - The container must have enough free slots for output item types not yet
131///   present.
132///
133/// Returns `Ok(())` on success and a [`CraftingError`] without modifying the
134/// container on failure.
135pub fn try_craft<I: ItemType>(
136    registry: &CraftingRegistry<I>,
137    inventory: &mut impl Container<I>,
138    recipe_index: usize,
139) -> Result<(), CraftingError> {
140    let recipe = registry
141        .recipes
142        .get(recipe_index)
143        .ok_or(CraftingError::InvalidRecipe)?;
144
145    // Pre-check: enough ingredients?
146    for ing in &recipe.ingredients {
147        if inventory.count_of(ing.item) < ing.count {
148            return Err(CraftingError::InsufficientIngredients);
149        }
150    }
151
152    // Pre-check: free slots for new output types.
153    let free_slots = inventory.capacity() - inventory.iter_slots().filter(|s| s.is_some()).count();
154    let new_types = recipe
155        .outputs
156        .iter()
157        .filter(|out| inventory.count_of(out.item) == 0)
158        .count();
159    if new_types > free_slots {
160        return Err(CraftingError::InventoryFull);
161    }
162
163    // Consume ingredients.
164    for ing in &recipe.ingredients {
165        inventory.remove(ing.item, ing.count);
166    }
167
168    // Produce outputs.
169    for out in &recipe.outputs {
170        inventory.add(out.item, out.count);
171    }
172
173    Ok(())
174}
175
176// ─── UI state ────────────────────────────────────────────────────────────────
177
178/// Runtime state of the crafting menu.
179#[derive(Resource, Default)]
180pub struct CraftingMenuState {
181    /// Whether the crafting menu is currently visible.
182    pub visible: bool,
183    /// Dirty flag: set to `true` to trigger a full UI rebuild on next frame.
184    rebuild: bool,
185}
186
187// ─── UI markers ───────────────────────────────────────────────────────────────
188
189/// Marker component on the root crafting menu panel.
190#[derive(Component)]
191struct CraftingMenuRoot;
192
193/// Marker component on each recipe row in the crafting menu.
194///
195/// `usize::MAX` is used as a sentinel for header/footer rows that are not
196/// interactive recipes.
197#[derive(Component)]
198struct CraftingRecipeRow {
199    recipe_index: usize,
200}
201
202// ─── Systems ──────────────────────────────────────────────────────────────────
203
204fn spawn_crafting_menu(mut commands: Commands) {
205    commands.spawn((
206        CraftingMenuRoot,
207        Node {
208            position_type: PositionType::Absolute,
209            right: Val::Px(10.0),
210            top: Val::Px(60.0),
211            width: Val::Px(340.0),
212            max_height: Val::Vh(75.0),
213            flex_direction: FlexDirection::Column,
214            padding: UiRect::all(Val::Px(10.0)),
215            row_gap: Val::Px(4.0),
216            overflow: Overflow::clip_y(),
217            ..default()
218        },
219        BackgroundColor(Color::srgba(0.04, 0.04, 0.04, 0.88)),
220        Visibility::Hidden,
221    ));
222}
223
224fn toggle_crafting_menu(keys: Res<ButtonInput<KeyCode>>, mut state: ResMut<CraftingMenuState>) {
225    if keys.just_pressed(KeyCode::KeyC) {
226        state.visible = !state.visible;
227        if state.visible {
228            state.rebuild = true;
229        }
230    }
231    // ESC closes crafting menu if open (without consuming the event — pause menu
232    // handles its own ESC separately).
233    if keys.just_pressed(KeyCode::Escape) && state.visible {
234        state.visible = false;
235    }
236}
237
238fn sync_crafting_visibility(
239    state: Res<CraftingMenuState>,
240    mut root_q: Query<&mut Visibility, With<CraftingMenuRoot>>,
241) {
242    if !state.is_changed() {
243        return;
244    }
245    let Ok(mut vis) = root_q.single_mut() else {
246        return;
247    };
248    *vis = if state.visible {
249        Visibility::Visible
250    } else {
251        Visibility::Hidden
252    };
253}
254
255fn rebuild_crafting_menu<I: ItemType>(
256    mut commands: Commands,
257    mut state: ResMut<CraftingMenuState>,
258    registry: Res<CraftingRegistry<I>>,
259    root_q: Query<Entity, With<CraftingMenuRoot>>,
260    row_q: Query<Entity, With<CraftingRecipeRow>>,
261) {
262    if !state.rebuild {
263        return;
264    }
265    state.rebuild = false;
266
267    // Despawn stale rows.
268    for e in row_q.iter() {
269        commands.entity(e).despawn();
270    }
271
272    let Ok(root) = root_q.single() else {
273        return;
274    };
275
276    // Header.
277    let header = commands
278        .spawn((
279            CraftingRecipeRow {
280                recipe_index: usize::MAX,
281            },
282            Node {
283                padding: UiRect::bottom(Val::Px(6.0)),
284                ..default()
285            },
286            Text::new("-- Crafting (C to close) --"),
287            TextFont {
288                font_size: 15.0,
289                ..default()
290            },
291            TextColor(Color::WHITE),
292        ))
293        .id();
294    commands.entity(root).add_child(header);
295
296    if registry.recipes.is_empty() {
297        let empty = commands
298            .spawn((
299                CraftingRecipeRow {
300                    recipe_index: usize::MAX,
301                },
302                Text::new("No recipes registered."),
303                TextFont {
304                    font_size: 13.0,
305                    ..default()
306                },
307                TextColor(Color::srgb(0.55, 0.55, 0.55)),
308            ))
309            .id();
310        commands.entity(root).add_child(empty);
311        return;
312    }
313
314    // One row per recipe.
315    for (i, recipe) in registry.recipes.iter().enumerate() {
316        let ing_str = recipe
317            .ingredients
318            .iter()
319            .map(|ing| format!("{} ×{}", ing.item.name(), ing.count))
320            .collect::<Vec<_>>()
321            .join(", ");
322        let out_str = recipe
323            .outputs
324            .iter()
325            .map(|out| format!("{} ×{}", out.item.name(), out.count))
326            .collect::<Vec<_>>()
327            .join(", ");
328
329        let label = format!("[{}]  {} > {}", recipe.name, ing_str, out_str);
330
331        let row = commands
332            .spawn((
333                CraftingRecipeRow { recipe_index: i },
334                Button,
335                Node {
336                    padding: UiRect::all(Val::Px(6.0)),
337                    width: Val::Percent(100.0),
338                    ..default()
339                },
340                BackgroundColor(Color::srgba(0.15, 0.15, 0.15, 0.90)),
341                Text::new(label),
342                TextFont {
343                    font_size: 12.0,
344                    ..default()
345                },
346                TextColor(Color::srgb(0.70, 0.70, 0.70)),
347            ))
348            .id();
349        commands.entity(root).add_child(row);
350    }
351
352    // Footer hint.
353    let footer = commands
354        .spawn((
355            CraftingRecipeRow {
356                recipe_index: usize::MAX,
357            },
358            Node {
359                padding: UiRect::top(Val::Px(6.0)),
360                ..default()
361            },
362            Text::new("Green = craftable  |  click to craft"),
363            TextFont {
364                font_size: 11.0,
365                ..default()
366            },
367            TextColor(Color::srgb(0.45, 0.45, 0.45)),
368        ))
369        .id();
370    commands.entity(root).add_child(footer);
371}
372
373fn update_crafting_row_colors<I: ItemType>(
374    mut row_q: Query<(
375        &CraftingRecipeRow,
376        &mut BackgroundColor,
377        &mut TextColor,
378        &Interaction,
379    )>,
380    registry: Res<CraftingRegistry<I>>,
381    container_query: Query<&ContainerComponent<I>, With<PrimaryContainer>>,
382    state: Res<CraftingMenuState>,
383) {
384    if !state.visible {
385        return;
386    }
387    let Ok(container) = container_query.single() else {
388        return;
389    };
390    for (row, mut bg, mut tc, interaction) in row_q.iter_mut() {
391        if row.recipe_index == usize::MAX {
392            continue;
393        }
394        let craftable = can_craft(&registry, &container.0, row.recipe_index);
395        let hovered = matches!(interaction, Interaction::Hovered | Interaction::Pressed);
396
397        *bg = match (craftable, hovered) {
398            (true, true) => BackgroundColor(Color::srgba(0.18, 0.50, 0.18, 0.95)),
399            (true, false) => BackgroundColor(Color::srgba(0.10, 0.28, 0.10, 0.90)),
400            (false, true) => BackgroundColor(Color::srgba(0.25, 0.25, 0.25, 0.90)),
401            (false, false) => BackgroundColor(Color::srgba(0.15, 0.15, 0.15, 0.90)),
402        };
403        *tc = if craftable {
404            TextColor(Color::srgb(0.82, 1.0, 0.82))
405        } else {
406            TextColor(Color::srgb(0.45, 0.45, 0.45))
407        };
408    }
409}
410
411fn handle_craft_click<I: ItemType>(
412    row_q: Query<(&CraftingRecipeRow, &Interaction), Changed<Interaction>>,
413    registry: Res<CraftingRegistry<I>>,
414    mut container_query: Query<&mut ContainerComponent<I>, With<PrimaryContainer>>,
415    state: Res<CraftingMenuState>,
416) {
417    if !state.visible {
418        return;
419    }
420    let Ok(mut container) = container_query.single_mut() else {
421        return;
422    };
423    for (row, interaction) in row_q.iter() {
424        if row.recipe_index == usize::MAX {
425            continue;
426        }
427        if matches!(interaction, Interaction::Pressed) {
428            let _ = try_craft(&registry, &mut container.0, row.recipe_index);
429        }
430    }
431}
432
433// ─── Plugins ──────────────────────────────────────────────────────────────────
434
435/// Core crafting plugin — registers [`CraftingRegistry<I>`] only.
436///
437/// No UI, no input, no systems. Use alongside [`CraftingUiPlugin<I>`] when you
438/// want the built-in `C`-key crafting menu, or provide your own UI by reading
439/// [`CraftingRegistry<I>`] and calling [`can_craft`] / [`try_craft`] directly.
440///
441/// Mirrors the [`crate::world::MiningPlugin`] / [`crate::world::MiningInputPlugin`] split pattern.
442pub struct CraftingPlugin<I: ItemType> {
443    _m: PhantomData<I>,
444}
445
446impl<I: ItemType> CraftingPlugin<I> {
447    pub fn new() -> Self {
448        Self { _m: PhantomData }
449    }
450}
451
452impl<I: ItemType> Default for CraftingPlugin<I> {
453    fn default() -> Self {
454        Self::new()
455    }
456}
457
458impl<I: ItemType> Plugin for CraftingPlugin<I> {
459    fn build(&self, app: &mut App) {
460        app.init_resource::<CraftingRegistry<I>>();
461    }
462}
463
464/// Batteries-included crafting UI plugin.
465///
466/// Adds [`CraftingMenuState`], spawns the in-game crafting panel, and wires the
467/// `C`-key toggle, recipe highlighting, and click-to-craft. Requires
468/// [`CraftingPlugin<I>`] to have been added first (for the registry).
469///
470/// # Example
471///
472/// ```no_run
473/// use bevy::prelude::*;
474/// use voxel_framework::crafting::{CraftingPlugin, CraftingUiPlugin, CraftingRecipe, CraftingIngredient};
475/// use voxel_framework::items::DefaultItem;
476///
477/// App::new()
478///     .add_plugins(CraftingPlugin::<DefaultItem>::new())
479///     .add_plugins(CraftingUiPlugin::<DefaultItem>::new())
480///     .add_systems(Startup, register_recipes);
481///
482/// fn register_recipes(mut registry: ResMut<voxel_framework::crafting::CraftingRegistry<DefaultItem>>) {
483///     registry.add(CraftingRecipe {
484///         name: "Iron Block",
485///         ingredients: vec![CraftingIngredient { item: DefaultItem::IronOre, count: 9 }],
486///         outputs:     vec![CraftingIngredient { item: DefaultItem::Crystal,  count: 1 }],
487///     });
488/// }
489/// ```
490pub struct CraftingUiPlugin<I: ItemType> {
491    _m: PhantomData<I>,
492}
493
494impl<I: ItemType> CraftingUiPlugin<I> {
495    pub fn new() -> Self {
496        Self { _m: PhantomData }
497    }
498}
499
500impl<I: ItemType> Default for CraftingUiPlugin<I> {
501    fn default() -> Self {
502        Self::new()
503    }
504}
505
506impl<I: ItemType> Plugin for CraftingUiPlugin<I> {
507    fn build(&self, app: &mut App) {
508        app.init_resource::<CraftingMenuState>();
509        app.add_systems(Startup, spawn_crafting_menu);
510        app.add_systems(
511            Update,
512            (
513                toggle_crafting_menu,
514                sync_crafting_visibility,
515                rebuild_crafting_menu::<I>,
516                update_crafting_row_colors::<I>,
517                handle_craft_click::<I>,
518            )
519                .chain(),
520        );
521    }
522}
523
524// ─── Tests ────────────────────────────────────────────────────────────────────
525
526#[cfg(test)]
527mod tests {
528    use super::*;
529    use crate::items::{DefaultItem, Inventory};
530
531    fn make_registry() -> CraftingRegistry<DefaultItem> {
532        let mut r = CraftingRegistry::default();
533        r.add(CraftingRecipe {
534            name: "Crystal from Ore",
535            ingredients: vec![CraftingIngredient {
536                item: DefaultItem::IronOre,
537                count: 4,
538            }],
539            outputs: vec![CraftingIngredient {
540                item: DefaultItem::Crystal,
541                count: 1,
542            }],
543        });
544        r.add(CraftingRecipe {
545            name: "Rare from Ore+Crystal",
546            ingredients: vec![
547                CraftingIngredient {
548                    item: DefaultItem::IronOre,
549                    count: 2,
550                },
551                CraftingIngredient {
552                    item: DefaultItem::Crystal,
553                    count: 1,
554                },
555            ],
556            outputs: vec![CraftingIngredient {
557                item: DefaultItem::RareMineral,
558                count: 1,
559            }],
560        });
561        r
562    }
563
564    #[test]
565    fn can_craft_true_when_enough_items() {
566        let registry = make_registry();
567        let mut inv = Inventory::new(9);
568        inv.add(DefaultItem::IronOre, 4);
569        assert!(can_craft(&registry, &inv, 0));
570    }
571
572    #[test]
573    fn can_craft_false_when_insufficient() {
574        let registry = make_registry();
575        let mut inv = Inventory::new(9);
576        inv.add(DefaultItem::IronOre, 3); // need 4
577        assert!(!can_craft(&registry, &inv, 0));
578    }
579
580    #[test]
581    fn can_craft_false_for_invalid_index() {
582        let registry = make_registry();
583        let inv = Inventory::<DefaultItem>::new(9);
584        assert!(!can_craft(&registry, &inv, 99));
585    }
586
587    #[test]
588    fn try_craft_consumes_ingredients_and_produces_outputs() {
589        let registry = make_registry();
590        let mut inv = Inventory::new(9);
591        inv.add(DefaultItem::IronOre, 5);
592
593        let result = try_craft(&registry, &mut inv, 0);
594        assert_eq!(result, Ok(()));
595        assert_eq!(inv.count_of(DefaultItem::IronOre), 1); // 5 - 4
596        assert_eq!(inv.count_of(DefaultItem::Crystal), 1);
597    }
598
599    #[test]
600    fn try_craft_fails_with_insufficient_ingredients() {
601        let registry = make_registry();
602        let mut inv = Inventory::new(9);
603        inv.add(DefaultItem::IronOre, 2);
604
605        let result = try_craft(&registry, &mut inv, 0);
606        assert_eq!(result, Err(CraftingError::InsufficientIngredients));
607        // Inventory unchanged.
608        assert_eq!(inv.count_of(DefaultItem::IronOre), 2);
609    }
610
611    #[test]
612    fn try_craft_fails_with_invalid_recipe() {
613        let registry = make_registry();
614        let mut inv = Inventory::new(9);
615        assert_eq!(
616            try_craft(&registry, &mut inv, 99),
617            Err(CraftingError::InvalidRecipe)
618        );
619    }
620
621    #[test]
622    fn try_craft_multi_ingredient_recipe() {
623        let registry = make_registry();
624        let mut inv = Inventory::new(9);
625        inv.add(DefaultItem::IronOre, 2);
626        inv.add(DefaultItem::Crystal, 1);
627
628        let result = try_craft(&registry, &mut inv, 1);
629        assert_eq!(result, Ok(()));
630        assert_eq!(inv.count_of(DefaultItem::IronOre), 0);
631        assert_eq!(inv.count_of(DefaultItem::Crystal), 0);
632        assert_eq!(inv.count_of(DefaultItem::RareMineral), 1);
633    }
634
635    #[test]
636    fn try_craft_inventory_full_returns_error() {
637        let registry = make_registry();
638        // Fill all slots with RockFragment so no room for Crystal output.
639        let mut inv = Inventory::new(1);
640        inv.add(DefaultItem::IronOre, 4); // occupies the 1 slot
641
642        // Now inventory is full (1 slot used).
643        // Crystal is a new type — needs a free slot, but none available.
644        let result = try_craft(&registry, &mut inv, 0);
645        assert_eq!(result, Err(CraftingError::InventoryFull));
646        // Ingredients not consumed.
647        assert_eq!(inv.count_of(DefaultItem::IronOre), 4);
648    }
649}