From 707840e7f78b2bf707f36f77fffd9b8741858091 Mon Sep 17 00:00:00 2001 From: Elenterius Date: Fri, 4 Oct 2024 23:32:47 +0200 Subject: [PATCH] chore: add utility method for matching recipes with the last know recipe id first before doing a lookup --- .../crafting/recipe/SimpleRecipeType.java | 32 +++++++++++++++---- 1 file changed, 26 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/github/elenterius/biomancy/crafting/recipe/SimpleRecipeType.java b/src/main/java/com/github/elenterius/biomancy/crafting/recipe/SimpleRecipeType.java index 33d9ab52c..660ef6be0 100644 --- a/src/main/java/com/github/elenterius/biomancy/crafting/recipe/SimpleRecipeType.java +++ b/src/main/java/com/github/elenterius/biomancy/crafting/recipe/SimpleRecipeType.java @@ -1,5 +1,6 @@ package com.github.elenterius.biomancy.crafting.recipe; +import com.mojang.datafixers.util.Pair; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.Container; import net.minecraft.world.item.ItemStack; @@ -10,6 +11,7 @@ import net.minecraft.world.level.Level; import org.jetbrains.annotations.Nullable; +import java.util.Map; import java.util.Optional; public class SimpleRecipeType> implements RecipeType { @@ -50,18 +52,36 @@ public Optional getRecipeFromContainer(Level level, Container inputInventory) return (R) recipe; } + private boolean matches(R recipe, ItemStack stack) { + for (Ingredient ingredient : recipe.getIngredients()) { + if (ingredient.test(stack)) return true; + } + return false; + } + public Optional getRecipeForIngredient(Level level, ItemStack stack) { RecipeManager recipeManager = level.getRecipeManager(); return recipeManager.byType(this).values().stream() - .filter(recipe -> { - for (Ingredient ingredient : recipe.getIngredients()) { - if (ingredient.test(stack)) return true; - } - return false; - }) + .filter(recipe -> matches(recipe, stack)) .findFirst().map(this::castRecipe); } + public Optional> getRecipeForIngredient(Level level, ItemStack stack, @Nullable ResourceLocation lastRecipeId) { + RecipeManager recipeManager = level.getRecipeManager(); + + Map map = recipeManager.byType(this); + if (lastRecipeId != null) { + R recipe = map.get(lastRecipeId); + if (recipe != null && matches(recipe, stack)) { + return Optional.of(Pair.of(lastRecipeId, recipe)); + } + } + + return map.entrySet().stream() + .filter(entry -> matches(entry.getValue(), stack)) + .findFirst() + .map(entry -> Pair.of(entry.getKey(), entry.getValue())); + } } }