Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

apply negative potion effects when holding filled containers #2316

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/main/java/gregtech/api/GregTechAPI.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import gregtech.api.cover.CoverDefinition;
import gregtech.api.event.HighTierEvent;
import gregtech.api.gui.UIFactory;
import gregtech.api.items.effect.IHeldItemEffectManager;
import gregtech.api.metatileentity.MetaTileEntity;
import gregtech.api.metatileentity.multiblock.IBatteryData;
import gregtech.api.modules.IModuleManager;
Expand Down Expand Up @@ -60,6 +61,8 @@ public class GregTechAPI {
public static IMaterialRegistryManager materialManager;
/** Will be available at the Pre-Initialization stage */
public static MarkerMaterialRegistry markerMaterialRegistry;
/** Will be available at the Initialization stage */
public static IHeldItemEffectManager heldItemEffectManager;

/** Will be available at the Pre-Initialization stage */
private static boolean highTier;
Expand Down
10 changes: 10 additions & 0 deletions src/main/java/gregtech/api/block/machines/MachineItemBlock.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import net.minecraft.client.resources.I18n;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
Expand Down Expand Up @@ -202,4 +203,13 @@ public int getItemStackLimit(@NotNull ItemStack stack) {
MetaTileEntity metaTileEntity = GTUtility.getMetaTileEntity(stack);
return metaTileEntity != null ? metaTileEntity.getItemStackLimit(stack) : super.getItemStackLimit(stack);
}

@Override
public void onUpdate(@NotNull ItemStack stack, @NotNull World worldIn, @NotNull Entity entityIn, int itemSlot,
boolean isSelected) {
MetaTileEntity metaTileEntity = GTUtility.getMetaTileEntity(stack);
if (metaTileEntity != null) {
metaTileEntity.onItemHeldUpdate(stack, worldIn, entityIn, itemSlot, isSelected);
}
}
}
55 changes: 55 additions & 0 deletions src/main/java/gregtech/api/config/ConfigUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package gregtech.api.config;

import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.common.registry.ForgeRegistries;

import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.NotNull;

import java.util.regex.Pattern;

public final class ConfigUtil {

private static final Pattern COLON_REGEX = Pattern.compile(":");

private ConfigUtil() {}

/**
* Parse an ItemStack from a string in format {@code modid:registry_name} or {@code modid:registry_name:metadata}.
*
* @param string the string to parse
* @param logger the logger used to log errors
* @return the parsed ItemStack, or {@link ItemStack#EMPTY} if parsing failed
*/
public static @NotNull ItemStack parseItemStack(@NotNull String string, @NotNull Logger logger) {
String[] split = COLON_REGEX.split(string);
if (split.length < 2) {
logger.error("Invalid string '{}', must be in format 'modid:registry_name:metadata'", string);
return ItemStack.EMPTY;
}

String modid = split[0];
String registryName = split[1];

Item item = ForgeRegistries.ITEMS.getValue(new ResourceLocation(modid, registryName));
if (item == null) {
logger.error("Could not find item with name '{}:{}' for string {}", modid, registryName, string);
return ItemStack.EMPTY;
}

int meta = 0;

if (split.length > 2) {
try {
meta = Integer.parseInt(split[2]);
} catch (NumberFormatException e) {
logger.error("Failed to parse ItemStack metadata for string '{}'", string, e);
return ItemStack.EMPTY;
}
}

return new ItemStack(item, 1, meta);
}
}
109 changes: 109 additions & 0 deletions src/main/java/gregtech/api/items/effect/HeldItemEffectManager.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
package gregtech.api.items.effect;

import gregtech.api.config.ConfigUtil;
import gregtech.api.util.GTLog;
import gregtech.common.ConfigHolder;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.MobEffects;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.PotionEffect;

import com.google.common.base.Preconditions;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class HeldItemEffectManager implements IHeldItemEffectManager {

private static final PotionEffect HUNGER = new PotionEffect(MobEffects.HUNGER, 20, 0, true, false);
private static final PotionEffect SLOWNESS = new PotionEffect(MobEffects.SLOWNESS, 20, 1, true, false);
private static final PotionEffect MINING_FATIGUE = new PotionEffect(MobEffects.MINING_FATIGUE, 20, 1, true, false);
private static final PotionEffect WEAKNESS = new PotionEffect(MobEffects.WEAKNESS, 20, 0, true, false);

private final Collection<ItemStack> protectiveBoots = new ArrayList<>();
private final Collection<ItemStack> protectiveLegs = new ArrayList<>();
private final Collection<ItemStack> protectiveChests = new ArrayList<>();
private final Collection<ItemStack> protectiveHelmets = new ArrayList<>();

@ApiStatus.Internal
public @NotNull HeldItemEffectManager init() {
for (String string : ConfigHolder.misc.protectiveArmor) {
ItemStack stack = ConfigUtil.parseItemStack(string.trim(), GTLog.logger);
if (stack.isEmpty()) continue;
EntityEquipmentSlot slot = stack.getItem().getEquipmentSlot(stack);
if (slot == null || slot.getSlotType() != EntityEquipmentSlot.Type.ARMOR) {
GTLog.logger.error("Item {} cannot be equipped in an armor slot", string);
continue;
}
addProtectiveItem(slot, stack);
}

return this;
}

@Override
public void addProtectiveItem(@NotNull EntityEquipmentSlot slot, @NotNull ItemStack stack) {
Preconditions.checkArgument(slot.getSlotType() == EntityEquipmentSlot.Type.ARMOR,
"type must be ARMOR");
Preconditions.checkArgument(!stack.isEmpty(), "stack cannot be empty");
switch (slot) {
case FEET -> protectiveBoots.add(stack);
case LEGS -> protectiveLegs.add(stack);
case CHEST -> protectiveChests.add(stack);
case HEAD -> protectiveHelmets.add(stack);
}
}

@Override
@SuppressWarnings("DataFlowIssue")
public void tryApplyEffects(@NotNull EntityPlayer player) {
if (!shouldApplyEffects(player)) return;

if (!player.isPotionActive(MobEffects.HUNGER)) {
player.addPotionEffect(new PotionEffect(HUNGER));
}
if (!player.isPotionActive(MobEffects.SLOWNESS)) {
player.addPotionEffect(new PotionEffect(SLOWNESS));
}
if (!player.isPotionActive(MobEffects.MINING_FATIGUE)) {
player.addPotionEffect(new PotionEffect(MINING_FATIGUE));
}
if (!player.isPotionActive(MobEffects.WEAKNESS)) {
player.addPotionEffect(new PotionEffect(WEAKNESS));
}
}

private boolean shouldApplyEffects(@NotNull EntityPlayer player) {
if (player.capabilities.isCreativeMode) return false;

List<ItemStack> armorInventory = player.inventory.armorInventory;
if (armorInventory.size() < 4) return false;

if (!isProtection(protectiveBoots, armorInventory.get(EntityEquipmentSlot.FEET.getIndex()))) {
return true;
}
if (!isProtection(protectiveLegs, armorInventory.get(EntityEquipmentSlot.LEGS.getIndex()))) {
return true;
}
if (!isProtection(protectiveChests, armorInventory.get(EntityEquipmentSlot.CHEST.getIndex()))) {
return true;
}

return !isProtection(protectiveHelmets, armorInventory.get(EntityEquipmentSlot.HEAD.getIndex()));
}

private static boolean isProtection(@NotNull Iterable<@NotNull ItemStack> candidates, @NotNull ItemStack stack) {
if (stack.isEmpty()) return false;
for (ItemStack s : candidates) {
if (s.isItemEqual(stack)) {
return true;
}
}
return false;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package gregtech.api.items.effect;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.item.ItemStack;

import org.jetbrains.annotations.NotNull;

/**
* Applies negative effects to players when holding items, such as filled Super Chests and Tanks
*/
public interface IHeldItemEffectManager {

/**
* Add a protective armor item to contribute to negating negative effects
*
* @param slot the slot type the item can be stored in
* @param stack the item to consider protective
*
* @throws IllegalArgumentException if {@code slot.getSlotType()} is {@link EntityEquipmentSlot.Type#HAND} or
* if {@code stack.isEmpty()} is {@code true}.
*/
void addProtectiveItem(@NotNull EntityEquipmentSlot slot, @NotNull ItemStack stack);

/**
* @param player the player to apply negative held item effects to
*/
void tryApplyEffects(@NotNull EntityPlayer player);
}
38 changes: 34 additions & 4 deletions src/main/java/gregtech/api/metatileentity/MetaTileEntity.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,16 @@
import gregtech.api.capability.GregtechTileCapabilities;
import gregtech.api.capability.IControllable;
import gregtech.api.capability.IEnergyContainer;
import gregtech.api.capability.impl.*;
import gregtech.api.cover.*;
import gregtech.api.capability.impl.AbstractRecipeLogic;
import gregtech.api.capability.impl.FluidHandlerProxy;
import gregtech.api.capability.impl.FluidTankList;
import gregtech.api.capability.impl.ItemHandlerProxy;
import gregtech.api.capability.impl.NotifiableFluidTank;
import gregtech.api.cover.Cover;
import gregtech.api.cover.CoverHolder;
import gregtech.api.cover.CoverRayTracer;
import gregtech.api.cover.CoverSaveHandler;
import gregtech.api.cover.CoverUtil;
import gregtech.api.gui.ModularUI;
import gregtech.api.items.itemhandlers.GTItemStackHandler;
import gregtech.api.items.toolitem.ToolClasses;
Expand All @@ -32,6 +40,7 @@
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.resources.I18n;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.Blocks;
Expand All @@ -40,7 +49,13 @@
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.PacketBuffer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.*;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.NonNullList;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.SoundEvent;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.world.World;
Expand Down Expand Up @@ -84,7 +99,11 @@
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.*;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;

Expand Down Expand Up @@ -1526,6 +1545,17 @@ public boolean canVoidRecipeFluidOutputs() {
return false;
}

/**
* @param stack the ItemStack being updated
* @param world the world containing the ItemStack. Called on client and server
* @param entity the entity holding the stack in its inventory
* @param slot the index of the slot containing the stack
* @param isSelected if the ItemStack is currently selected in the hotbar
* @see net.minecraft.item.Item#onUpdate(ItemStack, World, Entity, int, boolean)
*/
public void onItemHeldUpdate(@NotNull ItemStack stack, @NotNull World world, @NotNull Entity entity, int slot,
boolean isSelected) {}

@NotNull
@Method(modid = GTValues.MODID_APPENG)
public AECableType getCableConnectionType(@NotNull AEPartLocation part) {
Expand Down
16 changes: 16 additions & 0 deletions src/main/java/gregtech/common/ConfigHolder.java
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,22 @@ public static class MiscOptions {

@Config.Comment({ "Whether to give the terminal to new players on login", "Default: true" })
public boolean spawnTerminal = true;

@Config.Comment({ "Additional armors which count as protection from effects.",
"For example, protection from effects caused by carrying filled tanks.",
"Defaults: GregTech NanoMuscle and QuarkTech armors."
})
public String[] protectiveArmor = {
"gregtech:gt_armor:20",
"gregtech:gt_armor:21",
"gregtech:gt_armor:22",
"gregtech:gt_armor:30",
"gregtech:gt_armor:40",
"gregtech:gt_armor:41",
"gregtech:gt_armor:42",
"gregtech:gt_armor:43",
"gregtech:gt_armor:50"
};
}

public static class ClientOptions {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package gregtech.common.metatileentities.storage;

import gregtech.api.GregTechAPI;
import gregtech.api.items.itemhandlers.GTItemStackHandler;
import gregtech.api.items.toolitem.ToolClasses;
import gregtech.api.metatileentity.MetaTileEntity;
Expand All @@ -13,6 +14,7 @@

import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.resources.I18n;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
Expand Down Expand Up @@ -40,13 +42,13 @@
import com.cleanroommc.modularui.widgets.ItemSlot;
import com.cleanroommc.modularui.widgets.layout.Grid;
import org.apache.commons.lang3.tuple.Pair;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.List;

import static gregtech.api.capability.GregtechDataCodes.IS_TAPED;
import static gregtech.api.capability.GregtechDataCodes.TAG_KEY_PAINTING_COLOR;

public class MetaTileEntityCrate extends MetaTileEntity {

Expand Down Expand Up @@ -274,4 +276,21 @@ public void addToolUsages(ItemStack stack, @Nullable World world, List<String> t
tooltip.add(I18n.format("gregtech.tool_action.screwdriver.access_covers"));
super.addToolUsages(stack, world, tooltip, advanced);
}

@Override
public void onItemHeldUpdate(@NotNull ItemStack stack, @NotNull World world, @NotNull Entity entity, int slot,
boolean isSelected) {
if (world.isRemote) return;

NBTTagCompound tag = stack.getTagCompound();
if (tag == null) return;

if (entity instanceof EntityPlayer player) {
if (player.isCreative()) return;

if (tag.getBoolean(TAPED_NBT)) {
GregTechAPI.heldItemEffectManager.tryApplyEffects(player);
}
}
}
}
Loading
Loading