Search in sources :

Example 6 with IAIState

use of com.minecolonies.api.entity.ai.statemachine.states.IAIState in project minecolonies by Minecolonies.

the class AbstractEntityAIStructure method structureStep.

/**
 * The Structure step to execute the actual placement actions etc.
 *
 * @return the next step to go to.
 */
protected IAIState structureStep() {
    if (structurePlacer.getB().getStage() == null) {
        return PICK_UP_RESIDUALS;
    }
    if (InventoryUtils.isItemHandlerFull(worker.getInventoryCitizen())) {
        return INVENTORY_FULL;
    }
    worker.getCitizenStatusHandler().setLatestStatus(new TranslationTextComponent("com.minecolonies.coremod.status.building"));
    checkForExtraBuildingActions();
    // some things to do first! then we go to the actual phase!
    // Fill workFrom with the position from where the builder should build.
    // also ensure we are at that position.
    final BlockPos progress = getProgressPos() == null ? NULL_POS : getProgressPos().getA();
    final BlockPos worldPos = structurePlacer.getB().getProgressPosInWorld(progress);
    if (getProgressPos() != null) {
        structurePlacer.getB().setStage(getProgressPos().getB());
    }
    if (!progress.equals(NULL_POS) && !limitReached && (blockToMine == null ? !walkToConstructionSite(worldPos) : !walkToConstructionSite(blockToMine))) {
        return getState();
    }
    limitReached = false;
    final StructurePhasePlacementResult result;
    final StructurePlacer placer = structurePlacer.getA();
    switch(structurePlacer.getB().getStage()) {
        case BUILD_SOLID:
            // structure
            result = placer.executeStructureStep(world, null, progress, StructurePlacer.Operation.BLOCK_PLACEMENT, () -> placer.getIterator().increment(DONT_TOUCH_PREDICATE.or((info, pos, handler) -> !info.getBlockInfo().getState().getMaterial().isSolid() || isDecoItem(info.getBlockInfo().getState().getBlock()))), false);
            break;
        case CLEAR_WATER:
            // water
            result = placer.executeStructureStep(world, null, progress, StructurePlacer.Operation.WATER_REMOVAL, () -> placer.getIterator().decrement((info, pos, handler) -> handler.getWorld().getBlockState(pos).getFluidState().isEmpty()), false);
            break;
        case CLEAR_NON_SOLIDS:
            // clear air
            result = placer.executeStructureStep(world, null, progress, StructurePlacer.Operation.BLOCK_PLACEMENT, () -> placer.getIterator().decrement(DONT_TOUCH_PREDICATE.or((info, pos, handler) -> !(info.getBlockInfo().getState().getBlock() instanceof AirBlock) || (handler.getWorld().isEmptyBlock(pos)))), false);
            break;
        case DECORATE:
            // not solid
            result = placer.executeStructureStep(world, null, progress, StructurePlacer.Operation.BLOCK_PLACEMENT, () -> placer.getIterator().increment(DONT_TOUCH_PREDICATE.or((info, pos, handler) -> info.getBlockInfo().getState().getMaterial().isSolid() && !isDecoItem(info.getBlockInfo().getState().getBlock()))), false);
            break;
        case SPAWN:
            // entities
            result = placer.executeStructureStep(world, null, progress, StructurePlacer.Operation.BLOCK_PLACEMENT, () -> placer.getIterator().increment(DONT_TOUCH_PREDICATE.or((info, pos, handler) -> info.getEntities().length == 0)), true);
            break;
        case REMOVE_WATER:
            // water
            placer.getIterator().setRemoving();
            result = placer.executeStructureStep(world, null, progress, StructurePlacer.Operation.WATER_REMOVAL, () -> placer.getIterator().decrement((info, pos, handler) -> info.getBlockInfo().getState().getFluidState().isEmpty()), false);
            break;
        case REMOVE:
            placer.getIterator().setRemoving();
            result = placer.executeStructureStep(world, null, progress, StructurePlacer.Operation.BLOCK_REMOVAL, () -> placer.getIterator().decrement((info, pos, handler) -> handler.getWorld().getBlockState(pos).getBlock() instanceof AirBlock || info.getBlockInfo().getState().getBlock() instanceof AirBlock || !handler.getWorld().getBlockState(pos).getFluidState().isEmpty() || info.getBlockInfo().getState().getBlock() == com.ldtteam.structurize.blocks.ModBlocks.blockSolidSubstitution.get() || info.getBlockInfo().getState().getBlock() == com.ldtteam.structurize.blocks.ModBlocks.blockSubstitution.get() || info.getBlockInfo().getState().getBlock() == com.ldtteam.structurize.blocks.ModBlocks.blockSubstitution.get() || handler.getWorld().getBlockState(pos).getBlock() instanceof IBuilderUndestroyable), true);
            break;
        case CLEAR:
        default:
            result = placer.executeStructureStep(world, null, progress, StructurePlacer.Operation.BLOCK_REMOVAL, () -> placer.getIterator().decrement((info, pos, handler) -> handler.getWorld().getBlockState(pos).getBlock() instanceof IBuilderUndestroyable || handler.getWorld().getBlockState(pos).getBlock() == Blocks.BEDROCK || handler.getWorld().getBlockState(pos).getBlock() instanceof AirBlock || info.getBlockInfo().getState().getBlock() == com.ldtteam.structurize.blocks.ModBlocks.blockFluidSubstitution.get() || !handler.getWorld().getBlockState(pos).getFluidState().isEmpty()), false);
            if (result.getBlockResult().getResult() == BlockPlacementResult.Result.FINISHED) {
                getOwnBuilding().checkOrRequestBucket(getOwnBuilding().getRequiredResources(), worker.getCitizenData(), true);
            }
            break;
    }
    if (result.getBlockResult().getResult() == BlockPlacementResult.Result.FINISHED) {
        getOwnBuilding().nextStage();
        if (!structurePlacer.getB().nextStage()) {
            getOwnBuilding().setProgressPos(null, null);
            return COMPLETE_BUILD;
        }
    } else if (result.getBlockResult().getResult() == BlockPlacementResult.Result.LIMIT_REACHED) {
        this.limitReached = true;
    }
    this.storeProgressPos(result.getIteratorPos(), structurePlacer.getB().getStage());
    if (result.getBlockResult().getResult() == BlockPlacementResult.Result.MISSING_ITEMS) {
        if (hasListOfResInInvOrRequest(this, result.getBlockResult().getRequiredItems(), result.getBlockResult().getRequiredItems().size() > 1) == RECALC) {
            job.getWorkOrder().setRequested(false);
            return LOAD_STRUCTURE;
        }
        return NEEDS_ITEM;
    }
    if (result.getBlockResult().getResult() == BlockPlacementResult.Result.BREAK_BLOCK) {
        blockToMine = result.getBlockResult().getWorldPos();
        return MINE_BLOCK;
    } else {
        blockToMine = null;
    }
    if (MineColonies.getConfig().getServer().builderBuildBlockDelay.get() > 0) {
        final double decrease = 1 - worker.getCitizenColonyHandler().getColony().getResearchManager().getResearchEffects().getEffectStrength(BLOCK_PLACE_SPEED);
        setDelay((int) ((MineColonies.getConfig().getServer().builderBuildBlockDelay.get() * PROGRESS_MULTIPLIER / (getPlaceSpeedLevel() / 2 + PROGRESS_MULTIPLIER)) * decrease));
    }
    return getState();
}
Also used : IRequest(com.minecolonies.api.colony.requestsystem.request.IRequest) BLOCK_PLACE_SPEED(com.minecolonies.api.research.util.ResearchConstants.BLOCK_PLACE_SPEED) AirBlock(net.minecraft.block.AirBlock) IBuilderUndestroyable(com.minecolonies.api.entity.ai.citizen.builder.IBuilderUndestroyable) TileEntityDecorationController(com.minecolonies.coremod.tileentities.TileEntityDecorationController) TranslationTextComponent(net.minecraft.util.text.TranslationTextComponent) TriPredicate(net.minecraftforge.common.util.TriPredicate) Blueprint(com.ldtteam.structures.blueprints.v1.Blueprint) BuildingBuilderResource(com.minecolonies.coremod.colony.buildings.utils.BuildingBuilderResource) Block(net.minecraft.block.Block) IAIState(com.minecolonies.api.entity.ai.statemachine.states.IAIState) BlockTags(net.minecraft.tags.BlockTags) AITarget(com.minecolonies.api.entity.ai.statemachine.AITarget) BlockState(net.minecraft.block.BlockState) CitizenConstants(com.minecolonies.api.util.constant.CitizenConstants) TICKS_SECOND(com.minecolonies.api.util.constant.Constants.TICKS_SECOND) AIEventTarget(com.minecolonies.api.entity.ai.statemachine.AIEventTarget) Predicate(java.util.function.Predicate) BlueprintPositionInfo(com.ldtteam.structurize.util.BlueprintPositionInfo) PlacementSettings(com.ldtteam.structurize.util.PlacementSettings) Nullable(org.jetbrains.annotations.Nullable) AbstractEntityCitizen(com.minecolonies.api.entity.citizen.AbstractEntityCitizen) BlockItem(net.minecraft.item.BlockItem) MineColonies(com.minecolonies.coremod.MineColonies) AbstractJobStructure(com.minecolonies.coremod.colony.jobs.AbstractJobStructure) IStructureHandler(com.ldtteam.structurize.placement.structure.IStructureHandler) ItemStorage(com.minecolonies.api.crafting.ItemStorage) NotNull(org.jetbrains.annotations.NotNull) StructurePlacer(com.ldtteam.structurize.placement.StructurePlacer) BuilderBucket(com.minecolonies.coremod.colony.buildings.utils.BuilderBucket) java.util(java.util) AxisAlignedBB(net.minecraft.util.math.AxisAlignedBB) ModBlocks(com.minecolonies.api.blocks.ModBlocks) Mirror(net.minecraft.util.Mirror) ItemStack(net.minecraft.item.ItemStack) BuildingResourcesModule(com.minecolonies.coremod.colony.buildings.modules.BuildingResourcesModule) ImmutableList(com.google.common.collect.ImmutableList) AbstractBuildingStructureBuilder(com.minecolonies.coremod.colony.buildings.AbstractBuildingStructureBuilder) Hand(net.minecraft.util.Hand) com.minecolonies.api.util(com.minecolonies.api.util) StructurePhasePlacementResult(com.ldtteam.structurize.placement.StructurePhasePlacementResult) Stack(com.minecolonies.api.colony.requestsystem.requestable.Stack) IDeliverable(com.minecolonies.api.colony.requestsystem.requestable.IDeliverable) BuildingStructureHandler(com.minecolonies.coremod.entity.ai.util.BuildingStructureHandler) ModTags(com.minecolonies.api.items.ModTags) AIBlockingEventType(com.minecolonies.api.entity.ai.statemachine.states.AIBlockingEventType) BlockPos(net.minecraft.util.math.BlockPos) NULL_POS(com.ldtteam.structurize.placement.AbstractBlueprintIterator.NULL_POS) AIWorkerState(com.minecolonies.api.entity.ai.statemachine.states.AIWorkerState) AbstractBlockHut(com.minecolonies.api.blocks.AbstractBlockHut) Blocks(net.minecraft.block.Blocks) Stage(com.minecolonies.coremod.entity.ai.util.BuildingStructureHandler.Stage) TypeConstants(com.minecolonies.api.util.constant.TypeConstants) BlockPlacementResult(com.ldtteam.structurize.placement.BlockPlacementResult) BlockUtils(com.ldtteam.structurize.util.BlockUtils) IBuilding(com.minecolonies.api.colony.buildings.IBuilding) BlockFluidSubstitution(com.ldtteam.structurize.blocks.schematic.BlockFluidSubstitution) TileEntity(net.minecraft.tileentity.TileEntity) ItemCheckResult(com.minecolonies.coremod.entity.ai.basic.AbstractEntityAIStructure.ItemCheckResult) AirBlock(net.minecraft.block.AirBlock) StructurePhasePlacementResult(com.ldtteam.structurize.placement.StructurePhasePlacementResult) StructurePlacer(com.ldtteam.structurize.placement.StructurePlacer) TranslationTextComponent(net.minecraft.util.text.TranslationTextComponent) BlockPos(net.minecraft.util.math.BlockPos) IBuilderUndestroyable(com.minecolonies.api.entity.ai.citizen.builder.IBuilderUndestroyable)

Example 7 with IAIState

use of com.minecolonies.api.entity.ai.statemachine.states.IAIState in project minecolonies by Minecolonies.

the class AbstractEntityAIStructure method pickUpMaterial.

/**
 * State to pick up material before going back to work.
 *
 * @return the next state to go to.
 */
public IAIState pickUpMaterial() {
    if (structurePlacer == null || !structurePlacer.getB().hasBluePrint()) {
        return IDLE;
    }
    if (structurePlacer.getB().getStage() == null || structurePlacer.getB().getStage() == BuildingStructureHandler.Stage.CLEAR) {
        pickUpCount = 0;
        return START_WORKING;
    }
    final List<Tuple<Predicate<ItemStack>, Integer>> neededItemsList = new ArrayList<>();
    final BuilderBucket neededRessourcesMap = getOwnBuilding().getRequiredResources();
    final BuildingResourcesModule module = getOwnBuilding().getFirstModuleOccurance(BuildingResourcesModule.class);
    if (neededRessourcesMap != null) {
        for (final Map.Entry<String, Integer> entry : neededRessourcesMap.getResourceMap().entrySet()) {
            final BuildingBuilderResource res = module.getResourceFromIdentifier(entry.getKey());
            if (res != null) {
                int amount = entry.getValue();
                neededItemsList.add(new Tuple<>(itemstack -> ItemStackUtils.compareItemStacksIgnoreStackSize(res.getItemStack(), itemstack, true, true), amount));
            }
        }
    }
    if (neededItemsList.size() <= pickUpCount || InventoryUtils.openSlotCount(worker.getInventoryCitizen()) <= MIN_OPEN_SLOTS) {
        getOwnBuilding().checkOrRequestBucket(getOwnBuilding().getRequiredResources(), worker.getCitizenData(), true);
        getOwnBuilding().checkOrRequestBucket(getOwnBuilding().getNextBucket(), worker.getCitizenData(), false);
        pickUpCount = 0;
        return START_WORKING;
    }
    needsCurrently = neededItemsList.get(pickUpCount);
    pickUpCount++;
    if (InventoryUtils.hasItemInProvider(getOwnBuilding().getTileEntity(), needsCurrently.getA())) {
        return GATHERING_REQUIRED_MATERIALS;
    }
    return pickUpMaterial();
}
Also used : IRequest(com.minecolonies.api.colony.requestsystem.request.IRequest) BLOCK_PLACE_SPEED(com.minecolonies.api.research.util.ResearchConstants.BLOCK_PLACE_SPEED) AirBlock(net.minecraft.block.AirBlock) IBuilderUndestroyable(com.minecolonies.api.entity.ai.citizen.builder.IBuilderUndestroyable) TileEntityDecorationController(com.minecolonies.coremod.tileentities.TileEntityDecorationController) TranslationTextComponent(net.minecraft.util.text.TranslationTextComponent) TriPredicate(net.minecraftforge.common.util.TriPredicate) Blueprint(com.ldtteam.structures.blueprints.v1.Blueprint) BuildingBuilderResource(com.minecolonies.coremod.colony.buildings.utils.BuildingBuilderResource) Block(net.minecraft.block.Block) IAIState(com.minecolonies.api.entity.ai.statemachine.states.IAIState) BlockTags(net.minecraft.tags.BlockTags) AITarget(com.minecolonies.api.entity.ai.statemachine.AITarget) BlockState(net.minecraft.block.BlockState) CitizenConstants(com.minecolonies.api.util.constant.CitizenConstants) TICKS_SECOND(com.minecolonies.api.util.constant.Constants.TICKS_SECOND) AIEventTarget(com.minecolonies.api.entity.ai.statemachine.AIEventTarget) Predicate(java.util.function.Predicate) BlueprintPositionInfo(com.ldtteam.structurize.util.BlueprintPositionInfo) PlacementSettings(com.ldtteam.structurize.util.PlacementSettings) Nullable(org.jetbrains.annotations.Nullable) AbstractEntityCitizen(com.minecolonies.api.entity.citizen.AbstractEntityCitizen) BlockItem(net.minecraft.item.BlockItem) MineColonies(com.minecolonies.coremod.MineColonies) AbstractJobStructure(com.minecolonies.coremod.colony.jobs.AbstractJobStructure) IStructureHandler(com.ldtteam.structurize.placement.structure.IStructureHandler) ItemStorage(com.minecolonies.api.crafting.ItemStorage) NotNull(org.jetbrains.annotations.NotNull) StructurePlacer(com.ldtteam.structurize.placement.StructurePlacer) BuilderBucket(com.minecolonies.coremod.colony.buildings.utils.BuilderBucket) java.util(java.util) AxisAlignedBB(net.minecraft.util.math.AxisAlignedBB) ModBlocks(com.minecolonies.api.blocks.ModBlocks) Mirror(net.minecraft.util.Mirror) ItemStack(net.minecraft.item.ItemStack) BuildingResourcesModule(com.minecolonies.coremod.colony.buildings.modules.BuildingResourcesModule) ImmutableList(com.google.common.collect.ImmutableList) AbstractBuildingStructureBuilder(com.minecolonies.coremod.colony.buildings.AbstractBuildingStructureBuilder) Hand(net.minecraft.util.Hand) com.minecolonies.api.util(com.minecolonies.api.util) StructurePhasePlacementResult(com.ldtteam.structurize.placement.StructurePhasePlacementResult) Stack(com.minecolonies.api.colony.requestsystem.requestable.Stack) IDeliverable(com.minecolonies.api.colony.requestsystem.requestable.IDeliverable) BuildingStructureHandler(com.minecolonies.coremod.entity.ai.util.BuildingStructureHandler) ModTags(com.minecolonies.api.items.ModTags) AIBlockingEventType(com.minecolonies.api.entity.ai.statemachine.states.AIBlockingEventType) BlockPos(net.minecraft.util.math.BlockPos) NULL_POS(com.ldtteam.structurize.placement.AbstractBlueprintIterator.NULL_POS) AIWorkerState(com.minecolonies.api.entity.ai.statemachine.states.AIWorkerState) AbstractBlockHut(com.minecolonies.api.blocks.AbstractBlockHut) Blocks(net.minecraft.block.Blocks) Stage(com.minecolonies.coremod.entity.ai.util.BuildingStructureHandler.Stage) TypeConstants(com.minecolonies.api.util.constant.TypeConstants) BlockPlacementResult(com.ldtteam.structurize.placement.BlockPlacementResult) BlockUtils(com.ldtteam.structurize.util.BlockUtils) IBuilding(com.minecolonies.api.colony.buildings.IBuilding) BlockFluidSubstitution(com.ldtteam.structurize.blocks.schematic.BlockFluidSubstitution) TileEntity(net.minecraft.tileentity.TileEntity) ItemCheckResult(com.minecolonies.coremod.entity.ai.basic.AbstractEntityAIStructure.ItemCheckResult) Blueprint(com.ldtteam.structures.blueprints.v1.Blueprint) BuildingResourcesModule(com.minecolonies.coremod.colony.buildings.modules.BuildingResourcesModule) ItemStack(net.minecraft.item.ItemStack) BuildingBuilderResource(com.minecolonies.coremod.colony.buildings.utils.BuildingBuilderResource) BuilderBucket(com.minecolonies.coremod.colony.buildings.utils.BuilderBucket)

Example 8 with IAIState

use of com.minecolonies.api.entity.ai.statemachine.states.IAIState in project minecolonies by Minecolonies.

the class EntityAIWorkCook method serveFoodToCitizen.

/**
 * Serve food to customer
 * <p>
 * If no customer, transition to START_WORKING. If we need to walk to the customer, repeat this state with tiny delay. If the customer has a full inventory, report and remove
 * customer, delay and repeat this state. If we have food, then COOK_SERVE. If no food in the building, transition to START_WORKING. If we were able to get the stored food,
 * then COOK_SERVE. If food is no longer available, delay and transition to START_WORKING. Otherwise, give the customer some food, then delay and repeat this state.
 *
 * @return next IAIState
 */
private IAIState serveFoodToCitizen() {
    worker.getCitizenStatusHandler().setLatestStatus(new TranslationTextComponent(TranslationConstants.COM_MINECOLONIES_COREMOD_STATUS_SERVING));
    if (citizenToServe.isEmpty() && playerToServe.isEmpty()) {
        return START_WORKING;
    }
    worker.getCitizenData().setVisibleStatus(COOK);
    final Entity living = citizenToServe.isEmpty() ? playerToServe.get(0) : citizenToServe.get(0);
    if (!getOwnBuilding().isInBuilding(living.blockPosition())) {
        worker.getNavigation().stop();
        removeFromQueue();
        return START_WORKING;
    }
    if (walkToBlock(new BlockPos(living.position()))) {
        return getState();
    }
    final IItemHandler handler = citizenToServe.isEmpty() ? new InvWrapper(playerToServe.get(0).inventory) : citizenToServe.get(0).getInventoryCitizen();
    if (InventoryUtils.isItemHandlerFull(handler)) {
        if (!citizenToServe.isEmpty()) {
            final int foodSlot = InventoryUtils.findFirstSlotInItemHandlerWith(worker.getInventoryCitizen(), stack -> ItemStackUtils.CAN_EAT.test(stack) && canEat(stack));
            if (foodSlot != -1) {
                final ItemStack stack = worker.getInventoryCitizen().extractItem(foodSlot, 1, false);
                if (stack.getItem().isEdible()) {
                    citizenToServe.get(0).getCitizenData().increaseSaturation(stack.getItem().getFoodProperties().getNutrition() / 2.0);
                }
            }
        }
        removeFromQueue();
        return getState();
    } else if (InventoryUtils.hasItemInItemHandler(handler, stack -> CAN_EAT.test(stack) && canEat(stack))) {
        removeFromQueue();
        return getState();
    }
    if (!InventoryUtils.transferFoodUpToSaturation(worker, handler, getOwnBuilding().getBuildingLevel() * SATURATION_TO_SERVE, stack -> CAN_EAT.test(stack) && canEat(stack))) {
        removeFromQueue();
        return getState();
    }
    if (!citizenToServe.isEmpty() && citizenToServe.get(0).getCitizenData() != null) {
        citizenToServe.get(0).getCitizenData().setJustAte(true);
    }
    if (citizenToServe.isEmpty() && living instanceof PlayerEntity) {
        LanguageHandler.sendPlayerMessage((PlayerEntity) living, "com.minecolonies.coremod.cook.serve.player", worker.getName().getString());
    }
    removeFromQueue();
    worker.getCitizenExperienceHandler().addExperience(BASE_XP_GAIN);
    this.incrementActionsDoneAndDecSaturation();
    return START_WORKING;
}
Also used : IItemHandler(net.minecraftforge.items.IItemHandler) java.util(java.util) LanguageHandler(com.ldtteam.structurize.util.LanguageHandler) ItemStackUtils(com.minecolonies.api.util.ItemStackUtils) BuildingCook(com.minecolonies.coremod.colony.buildings.workerbuildings.BuildingCook) JobCook(com.minecolonies.coremod.colony.jobs.JobCook) TypeToken(com.google.common.reflect.TypeToken) Action(com.minecolonies.api.colony.permissions.Action) TranslationTextComponent(net.minecraft.util.text.TranslationTextComponent) FOOD_EXCLUSION_LIST(com.minecolonies.coremod.colony.buildings.workerbuildings.BuildingCook.FOOD_EXCLUSION_LIST) MinecoloniesAPIProxy(com.minecolonies.api.MinecoloniesAPIProxy) ItemStack(net.minecraft.item.ItemStack) InvWrapper(net.minecraftforge.items.wrapper.InvWrapper) Tuple(com.minecolonies.api.util.Tuple) IAIState(com.minecolonies.api.entity.ai.statemachine.states.IAIState) CAN_EAT(com.minecolonies.api.util.ItemStackUtils.CAN_EAT) AITarget(com.minecolonies.api.entity.ai.statemachine.AITarget) Constants(com.minecolonies.api.util.constant.Constants) ItemListModule(com.minecolonies.coremod.colony.buildings.modules.ItemListModule) TranslationConstants(com.minecolonies.api.util.constant.TranslationConstants) Entity(net.minecraft.entity.Entity) Food(com.minecolonies.api.colony.requestsystem.requestable.Food) PlayerEntity(net.minecraft.entity.player.PlayerEntity) IColonyManager(com.minecolonies.api.colony.IColonyManager) VisibleCitizenStatus(com.minecolonies.api.entity.citizen.VisibleCitizenStatus) ChatPriority(com.minecolonies.api.colony.interactionhandling.ChatPriority) StandardInteraction(com.minecolonies.coremod.colony.interactionhandling.StandardInteraction) BlockPos(net.minecraft.util.math.BlockPos) FurnaceTileEntity(net.minecraft.tileentity.FurnaceTileEntity) IRequestable(com.minecolonies.api.colony.requestsystem.requestable.IRequestable) AIWorkerState(com.minecolonies.api.entity.ai.statemachine.states.AIWorkerState) Collectors(java.util.stream.Collectors) AbstractEntityCitizen(com.minecolonies.api.entity.citizen.AbstractEntityCitizen) IBuilding(com.minecolonies.api.colony.buildings.IBuilding) InventoryUtils(com.minecolonies.api.util.InventoryUtils) ResourceLocation(net.minecraft.util.ResourceLocation) ItemStorage(com.minecolonies.api.crafting.ItemStorage) WorldUtil(com.minecolonies.api.util.WorldUtil) AbstractEntityAIUsesFurnace(com.minecolonies.coremod.entity.ai.basic.AbstractEntityAIUsesFurnace) NotNull(org.jetbrains.annotations.NotNull) Entity(net.minecraft.entity.Entity) PlayerEntity(net.minecraft.entity.player.PlayerEntity) FurnaceTileEntity(net.minecraft.tileentity.FurnaceTileEntity) IItemHandler(net.minecraftforge.items.IItemHandler) InvWrapper(net.minecraftforge.items.wrapper.InvWrapper) TranslationTextComponent(net.minecraft.util.text.TranslationTextComponent) BlockPos(net.minecraft.util.math.BlockPos) ItemStack(net.minecraft.item.ItemStack) PlayerEntity(net.minecraft.entity.player.PlayerEntity)

Example 9 with IAIState

use of com.minecolonies.api.entity.ai.statemachine.states.IAIState in project minecolonies by Minecolonies.

the class AbstractEntityAICrafting method checkForItems.

/**
 * Check for all items of the required recipe.
 *
 * @param storage the recipe storage.
 * @return the next state to go to.
 */
protected IAIState checkForItems(@NotNull final IRecipeStorage storage) {
    final int inProgressCount = getExtendedCount(currentRecipeStorage.getPrimaryOutput());
    final int countPerIteration = currentRecipeStorage.getPrimaryOutput().getCount();
    final int progressOpsCount = inProgressCount / countPerIteration;
    final List<ItemStorage> input = storage.getCleanedInput();
    for (final ItemStorage inputStorage : input) {
        final Predicate<ItemStack> predicate = stack -> !ItemStackUtils.isEmpty(stack) && new Stack(stack, false).matches(inputStorage.getItemStack());
        final int invCount = InventoryUtils.getItemCountInItemHandler(worker.getInventoryCitizen(), predicate);
        final ItemStack container = inputStorage.getItem().getContainerItem(inputStorage.getItemStack());
        final int remaining;
        if (!currentRecipeStorage.getCraftingToolsAndSecondaryOutputs().isEmpty() && ItemStackUtils.compareItemStackListIgnoreStackSize(currentRecipeStorage.getCraftingToolsAndSecondaryOutputs(), inputStorage.getItemStack(), false, true)) {
            remaining = inputStorage.getAmount();
        } else if (!ItemStackUtils.isEmpty(container) && ItemStackUtils.compareItemStacksIgnoreStackSize(inputStorage.getItemStack(), container, false, true)) {
            remaining = inputStorage.getAmount();
        } else {
            remaining = inputStorage.getAmount() * job.getMaxCraftingCount();
        }
        if (invCount <= 0 || invCount + ((job.getCraftCounter() + progressOpsCount) * inputStorage.getAmount()) < remaining) {
            if (InventoryUtils.hasItemInProvider(getOwnBuilding(), predicate)) {
                needsCurrently = new Tuple<>(predicate, remaining);
                return GATHERING_REQUIRED_MATERIALS;
            }
            currentRecipeStorage = null;
            currentRequest = null;
            return GET_RECIPE;
        }
    }
    return CRAFT;
}
Also used : ServerWorld(net.minecraft.world.server.ServerWorld) IRequest(com.minecolonies.api.colony.requestsystem.request.IRequest) ItemStackUtils(com.minecolonies.api.util.ItemStackUtils) IRecipeStorage(com.minecolonies.api.crafting.IRecipeStorage) AbstractJobCrafter(com.minecolonies.coremod.colony.jobs.AbstractJobCrafter) ItemStack(net.minecraft.item.ItemStack) AbstractAdvancedPathNavigate(com.minecolonies.api.entity.pathfinding.AbstractAdvancedPathNavigate) LootContext(net.minecraft.loot.LootContext) Tuple(com.minecolonies.api.util.Tuple) ImmutableList(com.google.common.collect.ImmutableList) IAIState(com.minecolonies.api.entity.ai.statemachine.states.IAIState) CraftingWorkerBuildingModule(com.minecolonies.coremod.colony.buildings.modules.CraftingWorkerBuildingModule) Hand(net.minecraft.util.Hand) AITarget(com.minecolonies.api.entity.ai.statemachine.AITarget) Stack(com.minecolonies.api.colony.requestsystem.requestable.Stack) RecipeStorage(com.minecolonies.api.crafting.RecipeStorage) Predicate(java.util.function.Predicate) ICraftingBuildingModule(com.minecolonies.api.colony.buildings.modules.ICraftingBuildingModule) RequestState(com.minecolonies.api.colony.requestsystem.request.RequestState) VisibleCitizenStatus(com.minecolonies.api.entity.citizen.VisibleCitizenStatus) LootParameters(net.minecraft.loot.LootParameters) AbstractBuilding(com.minecolonies.coremod.colony.buildings.AbstractBuilding) AIWorkerState(com.minecolonies.api.entity.ai.statemachine.states.AIWorkerState) DamageSource(net.minecraft.util.DamageSource) FakePlayerFactory(net.minecraftforge.common.util.FakePlayerFactory) DEFAULT_SPEED(com.minecolonies.api.util.constant.Constants.DEFAULT_SPEED) List(java.util.List) PublicCrafting(com.minecolonies.api.colony.requestsystem.requestable.crafting.PublicCrafting) InventoryUtils(com.minecolonies.api.util.InventoryUtils) ItemStorage(com.minecolonies.api.crafting.ItemStorage) NotNull(org.jetbrains.annotations.NotNull) FakePlayer(net.minecraftforge.common.util.FakePlayer) ItemStack(net.minecraft.item.ItemStack) ItemStorage(com.minecolonies.api.crafting.ItemStorage) ItemStack(net.minecraft.item.ItemStack) Stack(com.minecolonies.api.colony.requestsystem.requestable.Stack)

Example 10 with IAIState

use of com.minecolonies.api.entity.ai.statemachine.states.IAIState in project minecolonies by Minecolonies.

the class AbstractEntityAICrafting method craft.

/**
 * The actual crafting logic.
 *
 * @return the next state to go to.
 */
protected IAIState craft() {
    if (currentRecipeStorage == null || job.getCurrentTask() == null) {
        return START_WORKING;
    }
    if (currentRequest == null && job.getCurrentTask() != null) {
        return GET_RECIPE;
    }
    if (walkToBuilding()) {
        return getState();
    }
    job.setProgress(job.getProgress() + 1);
    worker.setItemInHand(Hand.MAIN_HAND, currentRecipeStorage.getCleanedInput().get(worker.getRandom().nextInt(currentRecipeStorage.getCleanedInput().size())).getItemStack().copy());
    worker.setItemInHand(Hand.OFF_HAND, currentRecipeStorage.getPrimaryOutput().copy());
    worker.getCitizenItemHandler().hitBlockWithToolInHand(getOwnBuilding().getPosition());
    currentRequest = job.getCurrentTask();
    if (currentRequest != null && (currentRequest.getState() == RequestState.CANCELLED || currentRequest.getState() == RequestState.FAILED)) {
        currentRequest = null;
        incrementActionsDone(getActionRewardForCraftingSuccess());
        currentRecipeStorage = null;
        return START_WORKING;
    }
    if (job.getProgress() >= getRequiredProgressForMakingRawMaterial()) {
        final IAIState check = checkForItems(currentRecipeStorage);
        if (check == CRAFT) {
            if (!currentRecipeStorage.fullfillRecipe(getLootContext(), ImmutableList.of(worker.getItemHandlerCitizen()))) {
                currentRequest = null;
                incrementActionsDone(getActionRewardForCraftingSuccess());
                job.finishRequest(false);
                resetValues();
                return START_WORKING;
            }
            currentRequest.addDelivery(currentRecipeStorage.getPrimaryOutput());
            job.setCraftCounter(job.getCraftCounter() + 1);
            if (job.getCraftCounter() >= job.getMaxCraftingCount()) {
                incrementActionsDone(getActionRewardForCraftingSuccess());
                final ICraftingBuildingModule module = getOwnBuilding().getCraftingModuleForRecipe(currentRecipeStorage.getToken());
                if (module != null) {
                    module.improveRecipe(currentRecipeStorage, job.getCraftCounter(), worker.getCitizenData());
                }
                currentRecipeStorage = null;
                resetValues();
                if (inventoryNeedsDump()) {
                    if (job.getMaxCraftingCount() == 0 && job.getProgress() == 0 && job.getCraftCounter() == 0 && currentRequest != null) {
                        job.finishRequest(true);
                        worker.getCitizenExperienceHandler().addExperience(currentRequest.getRequest().getCount() / 2.0);
                    }
                }
            } else {
                job.setProgress(0);
                return GET_RECIPE;
            }
        } else {
            currentRequest = null;
            job.finishRequest(false);
            incrementActionsDoneAndDecSaturation();
            resetValues();
        }
        return START_WORKING;
    }
    return getState();
}
Also used : IAIState(com.minecolonies.api.entity.ai.statemachine.states.IAIState) ICraftingBuildingModule(com.minecolonies.api.colony.buildings.modules.ICraftingBuildingModule)

Aggregations

IAIState (com.minecolonies.api.entity.ai.statemachine.states.IAIState)67 ItemStack (net.minecraft.item.ItemStack)52 BlockPos (net.minecraft.util.math.BlockPos)45 AIWorkerState (com.minecolonies.api.entity.ai.statemachine.states.AIWorkerState)44 NotNull (org.jetbrains.annotations.NotNull)44 AITarget (com.minecolonies.api.entity.ai.statemachine.AITarget)42 TranslationTextComponent (net.minecraft.util.text.TranslationTextComponent)42 ItemStorage (com.minecolonies.api.crafting.ItemStorage)35 InventoryUtils (com.minecolonies.api.util.InventoryUtils)32 StandardInteraction (com.minecolonies.coremod.colony.interactionhandling.StandardInteraction)32 Hand (net.minecraft.util.Hand)32 ItemStackUtils (com.minecolonies.api.util.ItemStackUtils)30 ChatPriority (com.minecolonies.api.colony.interactionhandling.ChatPriority)28 TranslationConstants (com.minecolonies.api.util.constant.TranslationConstants)24 ItemListModule (com.minecolonies.coremod.colony.buildings.modules.ItemListModule)24 TileEntity (net.minecraft.tileentity.TileEntity)24 Tuple (com.minecolonies.api.util.Tuple)22 List (java.util.List)22 TypeToken (com.google.common.reflect.TypeToken)20 IRequest (com.minecolonies.api.colony.requestsystem.request.IRequest)20