1use std::marker::PhantomData;
43
44use bevy::prelude::*;
45
46use crate::items::ItemType;
47use crate::items::inventory::{Container, ContainerComponent, PrimaryContainer};
48
49#[derive(Debug, Clone)]
53pub struct CraftingIngredient<I> {
54 pub item: I,
56 pub count: u32,
58}
59
60#[derive(Debug, Clone)]
66pub struct CraftingRecipe<I> {
67 pub name: &'static str,
69 pub ingredients: Vec<CraftingIngredient<I>>,
71 pub outputs: Vec<CraftingIngredient<I>>,
73}
74
75#[derive(Resource, Debug, Clone, Default)]
80pub struct CraftingRegistry<I: ItemType> {
81 pub recipes: Vec<CraftingRecipe<I>>,
83}
84
85impl<I: ItemType> CraftingRegistry<I> {
86 pub fn add(&mut self, recipe: CraftingRecipe<I>) {
88 self.recipes.push(recipe);
89 }
90}
91
92#[derive(Debug, Clone, PartialEq, Eq)]
96pub enum CraftingError {
97 InvalidRecipe,
99 InsufficientIngredients,
101 InventoryFull,
103}
104
105pub 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
122pub 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 for ing in &recipe.ingredients {
147 if inventory.count_of(ing.item) < ing.count {
148 return Err(CraftingError::InsufficientIngredients);
149 }
150 }
151
152 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 for ing in &recipe.ingredients {
165 inventory.remove(ing.item, ing.count);
166 }
167
168 for out in &recipe.outputs {
170 inventory.add(out.item, out.count);
171 }
172
173 Ok(())
174}
175
176#[derive(Resource, Default)]
180pub struct CraftingMenuState {
181 pub visible: bool,
183 rebuild: bool,
185}
186
187#[derive(Component)]
191struct CraftingMenuRoot;
192
193#[derive(Component)]
198struct CraftingRecipeRow {
199 recipe_index: usize,
200}
201
202fn 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 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 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 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 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 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(®istry, &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(®istry, &mut container.0, row.recipe_index);
429 }
430 }
431}
432
433pub 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
464pub 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#[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(®istry, &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); assert!(!can_craft(®istry, &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(®istry, &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(®istry, &mut inv, 0);
594 assert_eq!(result, Ok(()));
595 assert_eq!(inv.count_of(DefaultItem::IronOre), 1); 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(®istry, &mut inv, 0);
606 assert_eq!(result, Err(CraftingError::InsufficientIngredients));
607 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(®istry, &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(®istry, &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 let mut inv = Inventory::new(1);
640 inv.add(DefaultItem::IronOre, 4); let result = try_craft(®istry, &mut inv, 0);
645 assert_eq!(result, Err(CraftingError::InventoryFull));
646 assert_eq!(inv.count_of(DefaultItem::IronOre), 4);
648 }
649}