Volver al índice

src/main/java/ar/com/companeros/world/CraftChainTask.java

package ar.com.companeros.world;

import ar.com.companeros.action.ToolResult;
import java.util.*;
import net.minecraft.core.*;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.item.*;
import net.minecraft.world.item.crafting.*;
import net.minecraftforge.registries.ForgeRegistries;

/** Fabrica ingredientes intermedios y despliega una mesa real, sin consultas por cada receta. */
public final class CraftChainTask implements PlayerOperations.Operation {
    private final ServerPlayer player;
    private final UUID id;
    private final Item target;
    private final int additional;
    private final Map<String, Integer> before;
    private final long began = System.currentTimeMillis();
    private ProductionPlanner.Plan plan;
    private int cursor;
    private PlaceTask placement;
    private ToolResult terminal;
    private long first = -1;
    public CraftChainTask(ServerPlayer player, UUID id, Item target, int additional) {
        this.player = player; this.id = id; this.target = target; this.additional = additional;
        before = PlayerCrafting.counts(player);
    }

    // Catálogo construido una vez por tarea; usa recetas del servidor y etiquetas de los mods.
    private ProductionPlanner.Plan prepare() {
        return preview(player, target, additional);
    }
    public static ProductionPlanner.Plan preview(ServerPlayer player, Item target, int additional) {
        Map<String, List<ProductionPlanner.Recipe>> index = new HashMap<>();
        var inventory = player.getInventory().items;
        for (CraftingRecipe recipe : player.serverLevel().getRecipeManager().getAllRecipesFor(RecipeType.CRAFTING)) {
            ItemStack output = recipe.getResultItem(player.level().registryAccess());
            if (output.isEmpty() || recipe.getIngredients().isEmpty() || !recipe.canCraftInDimensions(3, 3)) continue;
            List<List<String>> ingredients = new ArrayList<>();
            for (Ingredient ingredient : recipe.getIngredients()) {
                if (ingredient.isEmpty()) continue;
                LinkedHashSet<String> choices = new LinkedHashSet<>();
                inventory.stream().filter(stack -> !stack.isEmpty() && ingredient.test(stack))
                    .forEach(stack -> choices.add(key(stack.getItem())));
                Arrays.stream(ingredient.getItems()).limit(32).forEach(stack -> choices.add(key(stack.getItem())));
                ingredients.add(List.copyOf(choices));
            }
            index.computeIfAbsent(key(output.getItem()), ignored -> new ArrayList<>()).add(new ProductionPlanner.Recipe(
                recipe.getId().toString(), key(output.getItem()), output.getCount(), !recipe.canCraftInDimensions(2, 2), ingredients));
        }
        index.values().forEach(options -> options.sort(Comparator.comparing(ProductionPlanner.Recipe::id)));
        return new ProductionPlanner(item -> index.getOrDefault(item, List.of()))
            .plan(PlayerCrafting.counts(player), PlayerCrafting.workbench(player), key(target), additional);
    }
    @Override public ToolResult tick(long tick) {
        if (terminal != null) return terminal;
        if (first < 0) first = tick;
        if (!player.isAlive() || player.isRemoved()) return finish(ToolResult.Status.CANCELLED, ToolResult.Reason.CONDITIONS_CHANGED, "body_unavailable");
        if (tick - first >= 2380) return finish(ToolResult.Status.BLOCKED, ToolResult.Reason.TIMEOUT, "craft_chain_timeout");
        if (plan == null) {
            plan = prepare();
            if (!plan.complete()) return finish(ToolResult.Status.BLOCKED, ToolResult.Reason.RESOURCE_EXHAUSTED,
                "craft_chain_first_missing=" + plan.missing() + "; no_materials_consumed; machine_recipes_use_smelt_or_research_recipe");
        }
        if (cursor >= plan.steps().size()) {
            int gained = PlayerCrafting.counts(player).getOrDefault(key(target), 0) - before.getOrDefault(key(target), 0);
            return finish(gained >= additional ? ToolResult.Status.SUCCEEDED : ToolResult.Status.BLOCKED,
                gained >= additional ? ToolResult.Reason.NONE : ToolResult.Reason.CONDITIONS_CHANGED, "crafted_target=" + key(target) + " gained=" + gained);
        }
        var step = plan.steps().get(cursor);
        if (step.deployTable()) {
            if (!PlayerCrafting.workbench(player)) {
                if (placement == null) {
                    BlockPos site = stationSite();
                    if (site == null) return finish(ToolResult.Status.BLOCKED, ToolResult.Reason.PATH_BLOCKED,
                        "crafting_table_owned_but_no_free_supported_site; choose_a_site_and_place_block");
                    placement = new PlaceTask(player, id, site, Items.CRAFTING_TABLE);
                }
                ToolResult placed = placement.tick(tick);
                if (!placed.finished()) return report(ToolResult.Status.RUNNING, ToolResult.Reason.NONE, "placing_crafting_table");
                if (!placed.succeeded()) return finish(placed.status(), placed.reason(), "table_placement=" + placed.actualEffects());
                placement = null;
            }
        } else {
            ToolResult crafted = PlayerCrafting.craftRecipe(player, id, ForgeRegistries.ITEMS.getValue(new ResourceLocation(step.output())),
                new ResourceLocation(step.recipe()));
            if (!crafted.succeeded()) return finish(crafted.status(), crafted.reason(), "dependency=" + step.output() + " " + crafted.actualEffects());
        }
        cursor++;
        return report(ToolResult.Status.RUNNING, ToolResult.Reason.NONE, "craft_chain_step=" + cursor + "/" + plan.steps().size());
    }
    private BlockPos stationSite() {
        return BlockPos.betweenClosedStream(player.blockPosition().offset(-2, 0, -2), player.blockPosition().offset(2, 0, 2))
            .map(BlockPos::immutable).filter(pos -> PlayerOperations.editable(player, pos) && PlayerOperations.reach(player, pos)
                && player.level().getBlockState(pos).isAir() && player.level().getBlockState(pos.below()).isFaceSturdy(player.level(), pos.below(), Direction.UP)
                && !player.getBoundingBox().intersects(new net.minecraft.world.phys.AABB(pos)))
            .sorted(Comparator.comparingDouble(pos -> player.position().distanceToSqr(net.minecraft.world.phys.Vec3.atCenterOf(pos))))
            .findFirst().orElse(null);
    }
    private static String key(Item item) { return ForgeRegistries.ITEMS.getKey(item).toString(); }
    private ToolResult report(ToolResult.Status status, ToolResult.Reason reason, String text) {
        return new ToolResult(id, status, reason, PlayerCrafting.delta(before, PlayerCrafting.counts(player)), List.of(text), List.of(),
            GlobalPos.of(player.level().dimension(), player.blockPosition()), began, System.currentTimeMillis());
    }
    private ToolResult finish(ToolResult.Status status, ToolResult.Reason reason, String text) {
        if (terminal == null) { if (placement != null) placement.cancel(); terminal = report(status, reason, text); }
        return terminal;
    }
    public void cancel() { finish(ToolResult.Status.CANCELLED, ToolResult.Reason.CANCELLED, "craft_chain_interrupted; crafted_materials_preserved"); }
}