Search in sources :

Example 1 with IAgriGrowthResponse

use of com.infinityraider.agricraft.api.v1.requirement.IAgriGrowthResponse in project AgriCraft by AgriCraft.

the class BotanyPotsHandler method onCropGrowth.

// Fertility checks and weeds
@SuppressWarnings("unused")
@SubscribeEvent(priority = EventPriority.LOWEST)
public void onCropGrowth(PotGrowCropEvent.Pre event) {
    if (event.getBotanyPot().getCrop() instanceof AgriCropInfo) {
        event.getBotanyPot().getCapability(CropCapability.getCapability()).ifPresent(crop -> {
            boolean cancel;
            if (AgriCraft.instance.getConfig().allowBotanyPotsWeeds() && CropHelper.rollForWeedAction(crop)) {
                // Weed tick, run weed logic
                cancel = true;
                if (!crop.hasWeeds()) {
                    CropHelper.spawnWeeds(crop);
                } else {
                    if (crop instanceof BotanyPotAgriCropInstance.Impl) {
                        BotanyPotAgriCropInstance.Impl cropImpl = (BotanyPotAgriCropInstance.Impl) crop;
                        if (cropImpl.incrementWeedCounter(event.getCurrentAmount())) {
                            if (AgriCraft.instance.getConfig().allowLethalWeeds()) {
                                event.setAmount(-1);
                                if (event.getBotanyPot().getCurrentGrowthTicks() <= 0) {
                                    event.getBotanyPot().setCrop(null, ItemStack.EMPTY);
                                }
                            }
                        }
                    }
                }
            } else {
                // Plant tick, run fertility checks
                cancel = false;
                IAgriGrowthResponse response = crop.getFertilityResponse();
                if (response.killInstantly()) {
                    event.getBotanyPot().setCrop(null, ItemStack.EMPTY);
                    response.onPlantKilled(crop);
                    cancel = true;
                } else if (response.isLethal()) {
                    event.setAmount(-1);
                    if (event.getBotanyPot().getCurrentGrowthTicks() <= 0) {
                        event.getBotanyPot().setCrop(null, ItemStack.EMPTY);
                        cancel = true;
                    }
                } else {
                    cancel = !response.isFertile();
                }
            }
            if (cancel) {
                event.setAmount(0);
                event.setCanceled(true);
                event.setResult(Event.Result.DENY);
            }
        });
    }
}
Also used : IAgriGrowthResponse(com.infinityraider.agricraft.api.v1.requirement.IAgriGrowthResponse) SubscribeEvent(net.minecraftforge.eventbus.api.SubscribeEvent)

Example 2 with IAgriGrowthResponse

use of com.infinityraider.agricraft.api.v1.requirement.IAgriGrowthResponse in project AgriCraft by AgriCraft.

the class JsonPlant method initGrowthRequirement.

public static IAgriGrowthRequirement initGrowthRequirement(AgriPlant plant) {
    // Run checks
    if (plant == null) {
        return AgriGrowthRequirement.getNone();
    }
    // Initialize utility objects
    IAgriGrowthRequirement.Builder builder = AgriApi.getGrowthRequirementBuilder();
    // Define requirement for humidity
    String humidityString = plant.getRequirement().getHumiditySoilCondition().getCondition();
    IAgriSoil.Humidity humidity = IAgriSoil.Humidity.fromString(humidityString).orElse(IAgriSoil.Humidity.INVALID);
    handleSoilCriterion(humidity, builder::defineHumidity, plant.getRequirement().getHumiditySoilCondition().getType(), plant.getRequirement().getHumiditySoilCondition().getToleranceFactor(), () -> AgriCore.getLogger("agricraft").warn("Plant: \"{0}\" has an invalid humidity criterion (\"{1}\")!", plant.getId(), humidityString));
    // Define requirement for acidity
    String acidityString = plant.getRequirement().getAciditySoilCondition().getCondition();
    IAgriSoil.Acidity acidity = IAgriSoil.Acidity.fromString(acidityString).orElse(IAgriSoil.Acidity.INVALID);
    handleSoilCriterion(acidity, builder::defineAcidity, plant.getRequirement().getAciditySoilCondition().getType(), plant.getRequirement().getAciditySoilCondition().getToleranceFactor(), () -> AgriCore.getLogger("agricraft").warn("Plant: \"{0}\" has an invalid acidity criterion (\"{1}\")!", plant.getId(), acidityString));
    // Define requirement for nutrients
    String nutrientString = plant.getRequirement().getNutrientSoilCondition().getCondition();
    IAgriSoil.Nutrients nutrients = IAgriSoil.Nutrients.fromString(nutrientString).orElse(IAgriSoil.Nutrients.INVALID);
    handleSoilCriterion(nutrients, builder::defineNutrients, plant.getRequirement().getNutrientSoilCondition().getType(), plant.getRequirement().getNutrientSoilCondition().getToleranceFactor(), () -> AgriCore.getLogger("agricraft").warn("Plant: \"{0}\" has an invalid nutrients criterion (\"{1}\")!", plant.getId(), nutrientString));
    // Define requirement for light
    final double f = plant.getRequirement().getLightToleranceFactor();
    final int minLight = plant.getRequirement().getMinLight();
    final int maxLight = plant.getRequirement().getMaxLight();
    builder.defineLightLevel((strength, light) -> {
        int lower = minLight - (int) (f * strength);
        int upper = maxLight + (int) (f * strength);
        return light >= lower && light <= upper ? IAgriGrowthResponse.FERTILE : IAgriGrowthResponse.INFERTILE;
    });
    // Define requirement for nearby blocks
    plant.getRequirement().getConditions().forEach(obj -> {
        BlockPos min = new BlockPos(obj.getMinX(), obj.getMinY(), obj.getMinZ());
        BlockPos max = new BlockPos(obj.getMaxX(), obj.getMaxY(), obj.getMaxZ());
        builder.addCondition(builder.blockStatesNearby(obj.convertAll(BlockState.class), obj.getAmount(), min, max));
    });
    // Define requirement for seasons
    List<AgriSeason> seasons = plant.getRequirement().getSeasons().stream().map(AgriSeason::fromString).filter(Optional::isPresent).map(Optional::get).distinct().collect(Collectors.toList());
    if (seasons.size() > 0) {
        builder.defineSeasonality((str, season) -> {
            if (str >= AgriApi.getStatRegistry().strengthStat().getMax() || seasons.stream().anyMatch(season::matches)) {
                return IAgriGrowthResponse.FERTILE;
            } else {
                return IAgriGrowthResponse.INFERTILE;
            }
        });
    }
    // Define requirement for fluids
    List<Fluid> fluids = plant.getRequirement().getFluid().convertAll(FluidState.class).stream().map(FluidState::getFluid).distinct().collect(Collectors.toList());
    BiFunction<Integer, Fluid, IAgriGrowthResponse> response = (strength, fluid) -> {
        if (fluids.size() > 0) {
            if (fluids.contains(fluid)) {
                return IAgriGrowthResponse.FERTILE;
            }
            return fluid.equals(Fluids.LAVA) ? IAgriGrowthResponse.KILL_IT_WITH_FIRE : IAgriGrowthResponse.LETHAL;
        } else {
            if (fluid.equals(Fluids.LAVA)) {
                return IAgriGrowthResponse.KILL_IT_WITH_FIRE;
            }
            return fluid.equals(Fluids.EMPTY) ? IAgriGrowthResponse.FERTILE : IAgriGrowthResponse.LETHAL;
        }
    };
    builder.defineFluid(response);
    // Build the growth requirement
    IAgriGrowthRequirement req = builder.build();
    // Log warning if no soils exist for this requirement combination
    if (noSoilsMatch(req)) {
        AgriCore.getLogger("agricraft").warn("Plant: \"{0}\" has no valid soils to plant on for any strength level!", plant.getId());
    }
    // Return the growth requirements
    return req;
}
Also used : FluidState(net.minecraft.fluid.FluidState) java.util(java.util) IAgriCrop(com.infinityraider.agricraft.api.v1.crop.IAgriCrop) OnlyIn(net.minecraftforge.api.distmarker.OnlyIn) BiFunction(java.util.function.BiFunction) AgriSoilCondition(com.agricraft.agricore.plant.AgriSoilCondition) IAgriGrowthStage(com.infinityraider.agricraft.api.v1.crop.IAgriGrowthStage) Direction(net.minecraft.util.Direction) ITextComponent(net.minecraft.util.text.ITextComponent) TranslationTextComponent(net.minecraft.util.text.TranslationTextComponent) Dist(net.minecraftforge.api.distmarker.Dist) AgriCore(com.agricraft.agricore.core.AgriCore) ItemStack(net.minecraft.item.ItemStack) ImmutableList(com.google.common.collect.ImmutableList) AgriGrowthRequirement(com.infinityraider.agricraft.impl.v1.requirement.AgriGrowthRequirement) IAgriFertilizer(com.infinityraider.agricraft.api.v1.fertilizer.IAgriFertilizer) com.infinityraider.agricraft.api.v1.requirement(com.infinityraider.agricraft.api.v1.requirement) BlockState(net.minecraft.block.BlockState) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) Fluids(net.minecraft.fluid.Fluids) AgriCraft(com.infinityraider.agricraft.AgriCraft) Entity(net.minecraft.entity.Entity) IAgriPlant(com.infinityraider.agricraft.api.v1.plant.IAgriPlant) IJsonPlantCallback(com.infinityraider.agricraft.api.v1.plant.IJsonPlantCallback) IncrementalGrowthLogic(com.infinityraider.agricraft.impl.v1.crop.IncrementalGrowthLogic) AgriApi(com.infinityraider.agricraft.api.v1.AgriApi) VanillaSeedConversionHandler(com.infinityraider.agricraft.handler.VanillaSeedConversionHandler) LivingEntity(net.minecraft.entity.LivingEntity) World(net.minecraft.world.World) BlockPos(net.minecraft.util.math.BlockPos) Collectors(java.util.stream.Collectors) AgriPlantQuadGenerator(com.infinityraider.agricraft.render.plant.AgriPlantQuadGenerator) BakedQuad(net.minecraft.client.renderer.model.BakedQuad) Consumer(java.util.function.Consumer) IParticleData(net.minecraft.particles.IParticleData) IAgriStatsMap(com.infinityraider.agricraft.api.v1.stat.IAgriStatsMap) AgriPlant(com.agricraft.agricore.plant.AgriPlant) ResourceLocation(net.minecraft.util.ResourceLocation) ParticleType(net.minecraft.particles.ParticleType) Fluid(net.minecraft.fluid.Fluid) ActionResultType(net.minecraft.util.ActionResultType) ForgeRegistries(net.minecraftforge.registries.ForgeRegistries) ModelResourceLocation(net.minecraft.client.renderer.model.ModelResourceLocation) Fluid(net.minecraft.fluid.Fluid) BlockPos(net.minecraft.util.math.BlockPos) FluidState(net.minecraft.fluid.FluidState)

Example 3 with IAgriGrowthResponse

use of com.infinityraider.agricraft.api.v1.requirement.IAgriGrowthResponse in project AgriCraft by AgriCraft.

the class BlockCropSticks method onFluidChanged.

@Override
protected boolean onFluidChanged(World world, BlockPos pos, BlockState state, Fluid oldFluid, Fluid newFluid) {
    Optional<IAgriCrop> optCrop = this.getCrop(world, pos);
    boolean noMorePlant = optCrop.map(crop -> {
        if (!crop.hasPlant()) {
            return true;
        }
        IAgriGrowthResponse response = crop.getPlant().getGrowthRequirement(crop.getGrowthStage()).getFluidResponse(newFluid, crop.getStats().getStrength());
        if (response.killInstantly()) {
            response.onPlantKilled(crop);
            crop.removeGenome();
            return true;
        }
        return false;
    }).orElse(true);
    if (this.getVariant().canExistInFluid(newFluid)) {
        // the crop sticks remain, regardless of what happened to the plant
        return false;
    } else {
        if (noMorePlant) {
            // no more crop sticks, no more plant, only fluid
            world.setBlockState(pos, newFluid.getDefaultState().getBlockState());
            if (world instanceof ServerWorld) {
                double x = pos.getX() + 0.5;
                double y = pos.getY() + 0.5;
                double z = pos.getZ() + 0.5;
                for (int i = 0; i < 2; i++) {
                    ((ServerWorld) world).spawnParticle(ParticleTypes.SMOKE, x + 0.25 * world.getRandom().nextDouble(), y, z + 0.25 * world.getRandom().nextDouble(), 1, 0, 1, 0, 0.25);
                }
                world.playSound(null, x, y, z, SoundEvents.BLOCK_LAVA_EXTINGUISH, SoundCategory.BLOCKS, 0.2F + world.getRandom().nextFloat() * 0.2F, 0.9F + world.getRandom().nextFloat() * 0.05F);
            }
        } else {
            // no more crop sticks, but still plant, and fluid
            BlockState newState = AgriCraft.instance.getModBlockRegistry().crop_plant.getDefaultState();
            newState = BlockCropBase.PLANT.mimic(state, newState);
            newState = BlockCropBase.LIGHT.mimic(state, newState);
            newState = InfProperty.Defaults.fluidlogged().mimic(state, newState);
            world.setBlockState(pos, newState);
            // If there was trouble, reset and abort.
            TileEntity tile = world.getTileEntity(pos);
            if (!(tile instanceof TileEntityCropPlant)) {
                world.setBlockState(pos, state);
                return false;
            }
            // Mimic plant and weed
            ((TileEntityCropPlant) tile).mimicFrom(optCrop.get());
        }
        return true;
    }
}
Also used : net.minecraft.util(net.minecraft.util) ServerWorld(net.minecraft.world.server.ServerWorld) TypeHelper(com.agricraft.agricore.util.TypeHelper) Arrays(java.util.Arrays) IAgriCrop(com.infinityraider.agricraft.api.v1.crop.IAgriCrop) BiFunction(java.util.function.BiFunction) IAgriGrowthResponse(com.infinityraider.agricraft.api.v1.requirement.IAgriGrowthResponse) IAgriGenome(com.infinityraider.agricraft.api.v1.genetics.IAgriGenome) ParametersAreNonnullByDefault(javax.annotation.ParametersAreNonnullByDefault) IAgriClipperItem(com.infinityraider.agricraft.api.v1.content.items.IAgriClipperItem) ItemStack(net.minecraft.item.ItemStack) LootContext(net.minecraft.loot.LootContext) Lists(com.google.common.collect.Lists) IBlockReader(net.minecraft.world.IBlockReader) net.minecraft.block(net.minecraft.block) Map(java.util.Map) IAgriTrowelItem(com.infinityraider.agricraft.api.v1.content.items.IAgriTrowelItem) ISelectionContext(net.minecraft.util.math.shapes.ISelectionContext) VoxelShape(net.minecraft.util.math.shapes.VoxelShape) InfProperty(com.infinityraider.infinitylib.block.property.InfProperty) AgriCraft(com.infinityraider.agricraft.AgriCraft) MethodsReturnNonnullByDefault(mcp.MethodsReturnNonnullByDefault) AgriApi(com.infinityraider.agricraft.api.v1.AgriApi) PlayerEntity(net.minecraft.entity.player.PlayerEntity) World(net.minecraft.world.World) IBooleanFunction(net.minecraft.util.math.shapes.IBooleanFunction) LootParameters(net.minecraft.loot.LootParameters) BlockPos(net.minecraft.util.math.BlockPos) Maps(com.google.common.collect.Maps) BlockRayTraceResult(net.minecraft.util.math.BlockRayTraceResult) ParticleTypes(net.minecraft.particles.ParticleTypes) List(java.util.List) Stream(java.util.stream.Stream) IAgriRakeItem(com.infinityraider.agricraft.api.v1.content.items.IAgriRakeItem) InfPropertyConfiguration(com.infinityraider.infinitylib.block.property.InfPropertyConfiguration) Optional(java.util.Optional) TileEntity(net.minecraft.tileentity.TileEntity) ItemSeedBag(com.infinityraider.agricraft.content.tools.ItemSeedBag) Fluid(net.minecraft.fluid.Fluid) VoxelShapes(net.minecraft.util.math.shapes.VoxelShapes) ServerWorld(net.minecraft.world.server.ServerWorld) TileEntity(net.minecraft.tileentity.TileEntity) IAgriCrop(com.infinityraider.agricraft.api.v1.crop.IAgriCrop) IAgriGrowthResponse(com.infinityraider.agricraft.api.v1.requirement.IAgriGrowthResponse)

Aggregations

AgriCraft (com.infinityraider.agricraft.AgriCraft)2 AgriApi (com.infinityraider.agricraft.api.v1.AgriApi)2 IAgriCrop (com.infinityraider.agricraft.api.v1.crop.IAgriCrop)2 IAgriGrowthResponse (com.infinityraider.agricraft.api.v1.requirement.IAgriGrowthResponse)2 BiFunction (java.util.function.BiFunction)2 Fluid (net.minecraft.fluid.Fluid)2 ItemStack (net.minecraft.item.ItemStack)2 BlockPos (net.minecraft.util.math.BlockPos)2 AgriCore (com.agricraft.agricore.core.AgriCore)1 AgriPlant (com.agricraft.agricore.plant.AgriPlant)1 AgriSoilCondition (com.agricraft.agricore.plant.AgriSoilCondition)1 TypeHelper (com.agricraft.agricore.util.TypeHelper)1 ImmutableList (com.google.common.collect.ImmutableList)1 Lists (com.google.common.collect.Lists)1 Maps (com.google.common.collect.Maps)1 IAgriClipperItem (com.infinityraider.agricraft.api.v1.content.items.IAgriClipperItem)1 IAgriRakeItem (com.infinityraider.agricraft.api.v1.content.items.IAgriRakeItem)1 IAgriTrowelItem (com.infinityraider.agricraft.api.v1.content.items.IAgriTrowelItem)1 IAgriGrowthStage (com.infinityraider.agricraft.api.v1.crop.IAgriGrowthStage)1 IAgriFertilizer (com.infinityraider.agricraft.api.v1.fertilizer.IAgriFertilizer)1