Java Code Examples for net.minecraft.item.ItemStack#isEmpty()

The following examples show how to use net.minecraft.item.ItemStack#isEmpty() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RenderAltar.java    From CommunityMod with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void render(TileEntityAltar te, double x, double y, double z, float partialTicks, int destroyStage, float alpha) {
	ItemStack stack = te.getStack();
	if (!stack.isEmpty()) {
		GlStateManager.enableRescaleNormal();
		GlStateManager.pushMatrix();
		GlStateManager.translate(x + 0.5, y + 0.85, z + 0.5);
		GlStateManager.rotate(te.getWorld().getTotalWorldTime() * 4, 0, 1, 0);
		
		Minecraft.getMinecraft().getRenderItem().renderItem(stack, ItemCameraTransforms.TransformType.GROUND);
		
		GlStateManager.popMatrix();
		GlStateManager.disableRescaleNormal();
		
		if (te.altarAnimation != null) {
			switch (te.altarAnimation) {
				case SHOCKWAVE:
					this.renderShockwave(te.animationProgress, te.altarAnimation.animationLength(), x, y, z);
					break;
				default: break;
			}
		}
	}
}
 
Example 2
Source File: HeldItemFeature.java    From MineLittlePony with MIT License 6 votes vote down vote up
private void renderHeldItem(T entity, ItemStack drop, ModelTransformation.Mode transform, Arm arm, MatrixStack stack, VertexConsumerProvider renderContext, int lightUv) {
    if (!drop.isEmpty()) {
        stack.push();
        renderArm(arm, stack);

        if (getContextModel().getAttributes().isCrouching) {
            stack.translate(0, 0.2F, 0);
        }

        float left = arm == Arm.LEFT ? 1 : -1;

        if (entity.hasVehicle()) {
            stack.translate(left / 10, -0.2F, -0.5F);
        }

        stack.multiply(Vector3f.POSITIVE_X.getDegreesQuaternion(-90));
        stack.multiply(Vector3f.POSITIVE_Y.getDegreesQuaternion(left * 180));
        stack.translate(left * -0.2F, 0, 0);

        preItemRender(entity, drop, transform, arm, stack);
        MinecraftClient.getInstance().getItemRenderer().renderItem(entity, drop, transform, arm == Arm.LEFT, stack, renderContext, entity.world, lightUv, OverlayTexture.DEFAULT_UV);
        postItemRender(entity, drop, transform, arm, stack, renderContext);

        stack.pop();
    }
}
 
Example 3
Source File: HallowedLogBlock.java    From the-hallow with MIT License 6 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) {
	ItemStack stack = player.getStackInHand(hand);
	if (stack.isEmpty() || !(stack.getItem() instanceof MiningToolItem)) {
		return ActionResult.PASS;
	}
	
	MiningToolItem tool = (MiningToolItem) stack.getItem();
	if (stripped != null && (tool.isEffectiveOn(state) || tool.getMiningSpeed(stack, state) > 1.0F)) {
		world.playSound(player, pos, SoundEvents.ITEM_AXE_STRIP, SoundCategory.BLOCKS, 1.0F, 1.0F);
		if (!world.isClient) {
			BlockState target = stripped.getDefaultState().with(LogBlock.AXIS, state.get(LogBlock.AXIS));
			world.setBlockState(pos, target);
			stack.damage(1, player, consumedPlayer -> consumedPlayer.sendToolBreakStatus(hand));
		}
		return ActionResult.SUCCESS;
	}
	return ActionResult.PASS;
}
 
Example 4
Source File: ContainerCustomSlotClick.java    From enderutilities with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Toggles the locked state for the given slot and sets the template stack
 * to the one in the cursor.<br>
 * If <b>requireStorageKey</b> is true, then a "storage key"
 * item needs to be held in the cursor for this to do anything.<br>
 * If <b>requireStorageKey</b> is false, then the template stack is set to
 * whatever is currently in the cursor, and the locked status is toggled.
 * @param slotNum
 * @param inv
 * @return true if the slot locked status was toggled, false if the conditions weren't met
 */
protected boolean toggleSlotLocked(int slotNum, ItemStackHandlerLockable inv)
{
    Slot slot = this.getSlot(slotNum);
    int slotIndex = slot != null ? slot.getSlotIndex() : -1;
    ItemStack stackCursor = this.player.inventory.getItemStack();

    if (slotIndex != -1)
    {
        if (stackCursor.isEmpty() == false)
        {
            inv.setTemplateStackInSlot(slotIndex, stackCursor);
        }
        else
        {
            inv.setTemplateStackInSlot(slotIndex, slot.getStack());
        }

        inv.toggleSlotLocked(slotIndex);
        return true;
    }

    return false;
}
 
Example 5
Source File: TileGenericPipe.java    From Logistics-Pipes-2 with MIT License 6 votes vote down vote up
public ArrayList<ItemStack> getItemsInInventory(EnumFacing face){
	ArrayList<ItemStack> result = new ArrayList<ItemStack>();
	
	if (!hasInventoryOnSide(face.getIndex())) {
		return result;
	}
	TileEntity te = world.getTileEntity(getPos().offset(face));
	if (!te.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, face.getOpposite())) {
		return result;
	}
	IItemHandler itemHandler = te.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, face.getOpposite());
	for(int i=0; i < itemHandler.getSlots(); i++) {
		ItemStack slotStack = itemHandler.getStackInSlot(i);
		if(!slotStack.isEmpty()) {
			result.add(slotStack);
		}
	}
	return result;
}
 
Example 6
Source File: ItemKotachi.java    From Sakura_mod with MIT License 6 votes vote down vote up
@Override
public void onUpdate(ItemStack stack, World worldIn, Entity entityIn, int itemSlot, boolean isSelected) {
	super.onUpdate(stack, worldIn, entityIn, itemSlot, isSelected);
	if(worldIn.isRemote) return;
	if(entityIn instanceof EntityPlayer){
		EntityPlayer player = (EntityPlayer) entityIn;
		ItemStack mainhand =player.getHeldItem(EnumHand.MAIN_HAND);
		ItemStack offhand =player.getHeldItem(EnumHand.OFF_HAND);
		boolean flag1 =!(mainhand.isEmpty())&&!(offhand.isEmpty()),
				flag2 = mainhand.getItem() instanceof ItemKotachi && offhand.getItem() instanceof ItemKotachi;
		if(flag1&&flag2) {
            player.setItemStackToSlot(EntityEquipmentSlot.OFFHAND, ItemStack.EMPTY);
            player.dropItem(offhand, false);
            player.sendStatusMessage(new TextComponentTranslation("sakura.katana.wrong_duel", new Object()), false);
		}
	}
}
 
Example 7
Source File: CmdReport.java    From I18nUpdateMod with MIT License 6 votes vote down vote up
@Override
public void execute(MinecraftServer server, ICommandSender sender, String[] args) {
    ItemStack stack = Minecraft.getMinecraft().player.inventory.getCurrentItem();
    if (!stack.isEmpty()) {
        String text = String.format("模组ID:%s\n非本地化名称:%s\n显示名称:%s", stack.getItem().getCreatorModId(stack), stack.getItem().getUnlocalizedName(), stack.getDisplayName());
        String url = I18nConfig.key.reportURL;
        try {
            GuiScreen.setClipboardString(text);
            Desktop.getDesktop().browse(new URI(url));
        } catch (Exception urlException) {
            urlException.printStackTrace();
        }
    } else {
        Minecraft.getMinecraft().player.sendMessage(new TextComponentTranslation("message.i18nmod.cmd_report.empty"));
    }
}
 
Example 8
Source File: ItemBreakingTracker.java    From Survivalist with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@SubscribeEvent
public void onPlayerDestroyItem(PlayerDestroyItemEvent ev)
{
    if (!ConfigManager.SERVER.enableScraping.get())
        return;
    if (ev.getPlayer().world.isRemote)
        return;

    ItemStack stack = ev.getOriginal();
    if (stack.isEmpty())
        return;

    Item item = stack.getItem();

    if (!(item instanceof TieredItem))
        return;

    onItemBroken(ev.getPlayer(), stack);
}
 
Example 9
Source File: MetaTileEntityCokeOven.java    From GregTech with GNU Lesser General Public License v3.0 6 votes vote down vote up
private boolean tryPickNewRecipe() {
    ItemStack inputStack = importItems.getStackInSlot(0);
    if (inputStack.isEmpty()) {
        return false;
    }
    CokeOvenRecipe currentRecipe = getOrRefreshRecipe(inputStack);
    if (currentRecipe != null && setupRecipe(inputStack, currentRecipe)) {
        inputStack.shrink(currentRecipe.getInput().getCount());
        this.maxProgressDuration = currentRecipe.getDuration();
        this.currentProgress = 0;
        this.outputStack = currentRecipe.getOutput().copy();
        this.outputFluid = currentRecipe.getFluidOutput().copy();
        markDirty();
        return true;
    }
    return false;
}
 
Example 10
Source File: TileSatelliteBuilder.java    From AdvancedRocketry with MIT License 6 votes vote down vote up
@Override
public ItemStack decrStackSize(int slot, int amt) {
	if(slot < outputSlot) {
		ItemStack chassis = getStackInSlot(chassisSlot);

		if(!chassis.isEmpty() && chassis.getItem() instanceof ItemSatellite) {
			EmbeddedInventory inv = ((ItemSatellite)chassis.getItem()).readInvFromNBT(chassis);
			ItemStack stack = inv.decrStackSize(slot, amt);
			((ItemSatellite)chassis.getItem()).writeInvToNBT(chassis, inv);
			return stack;
		}

		return ItemStack.EMPTY;
	}

	return inventory.decrStackSize(slot - 7, amt);
}
 
Example 11
Source File: ProxiedItemStackHandler.java    From Wizardry with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
@Nonnull
public ItemStack extractItem(int slot, int amount, boolean simulate) {
	if (amount == 0)
		return ItemStack.EMPTY;

	validateSlotIndex(slot);

	ItemStack existing = readStack(slot);

	if (existing.isEmpty())
		return ItemStack.EMPTY;

	int toExtract = Math.min(amount, existing.getMaxStackSize());

	if (existing.getCount() <= toExtract) {
		if (!simulate)
			writeStack(slot, ItemStack.EMPTY);

		return existing;
	} else {
		if (!simulate)
			writeStack(slot, ItemHandlerHelper.copyStackWithSize(existing, existing.getCount() - toExtract));

		return ItemHandlerHelper.copyStackWithSize(existing, toExtract);
	}
}
 
Example 12
Source File: UtilItemModular.java    From enderutilities with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Returns the ItemStack of the (currently selected, if multiple) installed module of type moduleType.
 * @param containerStack
 * @param moduleType
 * @return
 */
public static ItemStack getSelectedModuleStack(ItemStack containerStack, ModuleType moduleType)
{
    NBTTagList nbtTagList = NBTUtils.getStoredItemsList(containerStack, false);

    if (nbtTagList == null)
    {
        return ItemStack.EMPTY;
    }

    int listNumStacks = nbtTagList.tagCount();
    int selected = getClampedModuleSelection(containerStack, moduleType);

    // Get the selected-th TAG_Compound of the given module type
    for (int i = 0, count = -1; i < listNumStacks && count < selected; ++i)
    {
        ItemStack moduleStack = NBTUtils.loadItemStackFromTag(nbtTagList.getCompoundTagAt(i));

        if (moduleStack.isEmpty() == false && moduleTypeEquals(moduleStack, moduleType))
        {
            if (++count >= selected)
            {
                return moduleStack;
            }
        }
    }

    return ItemStack.EMPTY;
}
 
Example 13
Source File: CraftJukebox.java    From Kettle with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Material getPlaying() {
    ItemStack record = this.getSnapshot().getRecord();
    if (record.isEmpty()) {
        return Material.AIR;
    }
    return CraftMagicNumbers.getMaterial(record.getItem());
}
 
Example 14
Source File: LootTableHelper.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * shuffles items by changing their order and splitting stacks
 */
private static void shuffleItems(List<ItemStack> stacks, int slotCount, Random rand) {
    List<ItemStack> list = Lists.<ItemStack>newArrayList();
    Iterator<ItemStack> iterator = stacks.iterator();

    while (iterator.hasNext()) {
        ItemStack itemstack = iterator.next();

        if (itemstack.isEmpty()) {
            iterator.remove();
        } else if (itemstack.getCount() > 4) {
            list.add(itemstack);
            iterator.remove();
        }
    }

    slotCount = slotCount - stacks.size();

    while (slotCount > 0 && !list.isEmpty()) {
        ItemStack itemstack2 = list.remove(MathHelper.getInt(rand, 0, list.size() - 1));
        int i = MathHelper.getInt(rand, itemstack2.getCount() / 3, itemstack2.getCount() / 2);
        ItemStack itemstack1 = itemstack2.splitStack(i);

        if (itemstack2.getCount() > 1 && rand.nextBoolean()) {
            list.add(itemstack2);
        } else {
            stacks.add(itemstack2);
        }

        if (itemstack1.getCount() > 1 && rand.nextBoolean()) {
            list.add(itemstack1);
        } else {
            stacks.add(itemstack1);
        }
    }

    stacks.addAll(list);
    Collections.shuffle(stacks, rand);
}
 
Example 15
Source File: RecipeMapFurnace.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
@Nullable
public Recipe findRecipe(long voltage, List<ItemStack> inputs, List<FluidStack> fluidInputs, int outputFluidTankCapacity) {
    Recipe normalRecipe = super.findRecipe(voltage, inputs, fluidInputs, outputFluidTankCapacity);
    if (normalRecipe != null || inputs.size() == 0 || inputs.get(0).isEmpty())
        return normalRecipe;
    ItemStack output = ModHandler.getSmeltingOutput(inputs.get(0));
    return output.isEmpty() ? null : this.recipeBuilder()
        .inputs(GTUtility.copyAmount(1, inputs.get(0)))
        .outputs(output)
        .duration(128).EUt(4)
        .build().getResult();
}
 
Example 16
Source File: ContainerHelper.java    From AgriCraft with MIT License 5 votes vote down vote up
public static final boolean isSlotValidFor(@Nonnull Slot slot, @Nonnull ItemStack stack) {
    // Validate the input parameters.
    Preconditions.checkNotNull(slot);
    Preconditions.checkNotNull(stack);

    // Fetch the slot stack.
    final ItemStack slotStack = slot.getStack();

    // Return
    return slot.isItemValid(stack)
            && (slotStack.isEmpty() || StackHelper.areCompatible(stack, slotStack));
}
 
Example 17
Source File: NBTUtils.java    From enderutilities with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Writes the ItemStacks in <b>items</b> to a new NBTTagList and returns that list.
 * @param items
 */
@Nonnull
public static NBTTagList createTagListForItems(NonNullList<ItemStack> items)
{
    NBTTagList nbtTagList = new NBTTagList();
    final int invSlots = items.size();

    // Write all the ItemStacks into a TAG_List
    for (int slotNum = 0; slotNum < invSlots; slotNum++)
    {
        ItemStack stack = items.get(slotNum);

        if (stack.isEmpty() == false)
        {
            NBTTagCompound tag = storeItemStackInTag(stack, new NBTTagCompound());

            if (invSlots <= 127)
            {
                tag.setByte("Slot", (byte) slotNum);
            }
            else
            {
                tag.setShort("Slot", (short) slotNum);
            }

            nbtTagList.appendTag(tag);
        }
    }

    return nbtTagList;
}
 
Example 18
Source File: ImplementedInventory.java    From LibGui with MIT License 5 votes vote down vote up
/**
 * @return true if this inventory has only empty stacks, false otherwise
 */
@Override
default boolean isEmpty() {
    for (int i = 0; i < size(); i++) {
        ItemStack stack = getStack(i);
        if (!stack.isEmpty()) {
            return false;
        }
    }

    return true;
}
 
Example 19
Source File: OreDictUnifier.java    From GregTech with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static void registerOre(ItemStack itemStack, ItemMaterialInfo materialInfo) {
    if (itemStack.isEmpty()) return;
    materialUnificationInfo.put(new ItemAndMetadata(itemStack), materialInfo);
}
 
Example 20
Source File: TickHandler.java    From enderutilities with GNU Lesser General Public License v3.0 4 votes vote down vote up
@SubscribeEvent
public void onPlayerTick(PlayerTickEvent event)
{
    EntityPlayer player = event.player;

    if (event.side == Side.CLIENT || player.getEntityWorld().isRemote)
    {
        return;
    }

    // Once every 2 seconds
    if (this.playerTickCounter % 40 == 0)
    {
        if (player.isRiding() && player.inventory.hasItemStack(new ItemStack(EnderUtilitiesItems.MOB_HARNESS)))
        {
            ItemMobHarness.addAITask(player.getRidingEntity(), false);
        }

        ItemStack stack = EntityUtils.getHeldItemOfType(player, IChunkLoadingItem.class);

        if (stack.isEmpty() == false)
        {
            NBTTagCompound nbt = stack.getTagCompound();

            // If the player is holding an item that requires a chunk to stay loaded, refresh the timeout value
            if (nbt != null && nbt.getBoolean("ChunkLoadingRequired"))
            {
                TargetData target;

                // Note: There is the possibility that the target or the selected link crystal
                // has been changed since the chunk loading first started, but it just means
                // that the refreshing will not happen, or will happen to the new target chunk,
                // (the one currently active in the item) if that also happens to be chunk loaded by us.

                // In case of modular items, we get the target info from the selected module (= Link Crystal)
                if (stack.getItem() instanceof IModular)
                {
                    target = TargetData.getTargetFromSelectedModule(stack, ModuleType.TYPE_LINKCRYSTAL);
                }
                else
                {
                    target = TargetData.getTargetFromItem(stack);
                }

                if (target != null)
                {
                    ChunkLoading.getInstance().refreshChunkTimeout(target.dimension, target.pos.getX() >> 4, target.pos.getZ() >> 4);
                }
            }
        }
    }

    PlayerTaskScheduler.getInstance().runTasks(player.getEntityWorld(), player);
}