Jump to content

[1.14.4][SOLVED] add item to empty inventory


andGarrett

Recommended Posts

I'm trying to add an item to an empty inventory, but what I've tried hasn't worked. I tried:

this.container.getInventory().set(0, item);

and

this.container.getInventory().set(0, item).setCount(1);

"item" in this context is an item stack containing 1 coal. I'm able to change the count if there is already an item in the container, so I know I'm accessing the correct container.

 

[SOLUTION]

use your handler's "insertItem" method.

Edited by andGarrett
found solution
Link to comment
Share on other sites

5 minutes ago, andGarrett said:

I'm trying to add an item to an empty inventory, but what I've tried hasn't worked. I tried:

this.container.getInventory().set(0, item);

and

this.container.getInventory().set(0, item).setCount(1);

"item" in this context is an item stack containing 1 coal. I'm able to change the count if there is already an item in the container, so I know I'm accessing the correct container.

Post all of your code.

VANILLA MINECRAFT CLASSES ARE THE BEST RESOURCES WHEN MODDING

I will be posting 1.15.2 modding tutorials on this channel. If you want to be notified of it do the normal YouTube stuff like subscribing, ect.

Forge and vanilla BlockState generator.

Link to comment
Share on other sites

2 hours ago, Animefan8888 said:

Post all of your code.

The class is incomplete. I'm in the process of setting up the mineBlock method. currently it only really does something if the AutoMiner block is facing up and has a block above it. the important part is on line 123 in the mineBlock method.

 

package com.Garrett.backtobasics.blocks;

import net.minecraft.block.Block;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.container.Container;
import net.minecraft.inventory.container.INamedContainerProvider;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.tileentity.ITickableTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.Direction;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.world.server.ServerWorld;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.util.INBTSerializable;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.ItemStackHandler;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import static net.minecraft.util.Direction.*;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import java.util.List;

import static com.Garrett.backtobasics.blocks.ModBlocks.AUTO_MINER_TILE_ENTITY;

public class AutoMinerTileEntity extends TileEntity implements ITickableTileEntity, INamedContainerProvider {

    private static final Logger LOGGER = LogManager.getLogger();
    private LazyOptional<IItemHandler> handler = LazyOptional.of(this::createHandler);
    private int tickCounter = 0;
    private AutoMinerContainer container;

    public AutoMinerTileEntity() {

        super(AUTO_MINER_TILE_ENTITY);

    }


    // 20 ticks per second
    @Override
    public void tick() {

        tickCounter++;

        if (tickCounter >= 60) {
            tickCounter = 0;

            mineBlock();
        }
    }

    // the lazy handler postpones execution of code until it is needed for the first time and cashes it
    // so it won't be recreated every time it is used.
    private ItemStackHandler createHandler () {
        return new ItemStackHandler(1);
    }

    // reads inventory from world file on load
    @Override
    public void read(CompoundNBT tag) {
        CompoundNBT invTag = tag.getCompound("inv");
        handler.ifPresent(h -> ((INBTSerializable<CompoundNBT>) h).deserializeNBT(invTag));
        createHandler().deserializeNBT(invTag);
        super.read(tag);
    }

    // writes inventory to world file whenever world is saved
    @Override
    public CompoundNBT write(CompoundNBT tag) {
        handler.ifPresent(h -> {
            CompoundNBT compound = ((INBTSerializable<CompoundNBT>) h).serializeNBT();
            tag.put("inv", compound);
        });
        return super.write(tag);
    }


    // Capabilities add funcionality to blocks and items.
    @Nonnull
    @Override
    public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction side) {
        if (cap == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) {
            return handler.cast();
        }
        return super.getCapability(cap, side);
    }

    @Override
    public ITextComponent getDisplayName() {
        return new StringTextComponent(getType().getRegistryName().getPath());
    }

    @Nullable
    @Override
    public Container createMenu(int i, PlayerInventory playerInventory, PlayerEntity playerEntity) {
        this.container = new AutoMinerContainer(i, world, pos, playerInventory, playerEntity);
        return container;
    }

    private void mineBlock() {

        if (getBlockState().getValues().containsValue(UP)
                && !world.getBlockState(getPos().up()).getMaterial().isToolNotRequired()
                && world.getServer() != null
                && this.container != null) {
            if (this.container.getInventory().get(0).getCount() < this.container.getInventory().get(0).getItem().getMaxStackSize()) {
                Block block = world.getBlockState(getPos().up()).getBlock();
                ServerWorld serverWorld = world.getServer().getWorld(world.dimension.getType());
                List<ItemStack> drops = Block.getDrops(block.getDefaultState(), serverWorld, getPos().up(), super.getTileEntity());
                for (ItemStack item: drops) {
                    if (item.getItem() == this.container.getInventory().get(0).getItem()) {
                        this.container.getInventory().get(0).grow(1);
                    } else if (this.container.getInventory().get(0).isEmpty()) {
                        LOGGER.info(item);
                        this.container.getInventory().set(0, item).setCount(1); // Here's where I want to add items to the inventory
                    }

                    //LOGGER.info(drops.get(0).getItem().getRegistryName());
                    //LOGGER.info(drops.get(0).getCount());
                }
            }

        } else if (getBlockState().getValues().containsValue(DOWN)) {
            if (!world.getBlockState(getPos().down()).getMaterial().isToolNotRequired()) {
                LOGGER.info(world.getBlockState(getPos().down()).getBlock().getLootTable().toString());
            }
        } else if (getBlockState().getValues().containsValue(NORTH)) {
            if (!world.getBlockState(getPos().north()).getMaterial().isToolNotRequired()) {
                LOGGER.info(world.getBlockState(getPos().north()).getBlock().getLootTable().toString());
            }
        } else if (getBlockState().getValues().containsValue(SOUTH)) {
            if (!world.getBlockState(getPos().south()).getMaterial().isToolNotRequired()) {
                LOGGER.info(world.getBlockState(getPos().south()).getBlock().getLootTable().toString());
            }
        } else if (getBlockState().getValues().containsValue(EAST)) {
            if (!world.getBlockState(getPos().east()).getMaterial().isToolNotRequired()) {
                LOGGER.info(world.getBlockState(getPos().east()).getBlock().getLootTable().toString());
            }
        } else if (getBlockState().getValues().containsValue(WEST)) {
            if (!world.getBlockState(getPos().west()).getMaterial().isToolNotRequired()) {
                LOGGER.info(world.getBlockState(getPos().west()).getBlock().getLootTable().toString());
            }
        }
    }
}

 

Link to comment
Share on other sites

3 hours ago, andGarrett said:

this.container

Why is this a thing? What if two players open the TE at the same time....

3 hours ago, andGarrett said:

(this.container.getInventory().get(0).getCount()

Why not just use the IItemHandler you have directly?...

VANILLA MINECRAFT CLASSES ARE THE BEST RESOURCES WHEN MODDING

I will be posting 1.15.2 modding tutorials on this channel. If you want to be notified of it do the normal YouTube stuff like subscribing, ect.

Forge and vanilla BlockState generator.

Link to comment
Share on other sites

17 minutes ago, Animefan8888 said:

Why is this a thing? What if two players open the TE at the same time....

 

Why not just use the IItemHandler you have directly?...

I stored the container in an instance field because I couldn't figure out how to get access to it any other way. for your second question, I don't know how to interact with IItemHandler. I don't know if this is relevant, but the container is a different class. I figured working with the container associated with the block was the best way to effect the inventory.

Link to comment
Share on other sites

13 minutes ago, andGarrett said:

for your second question, I don't know how to interact with IItemHandler

Look at the methods inside it there are two I can think of insertItem and extractItem. 

 

16 minutes ago, andGarrett said:

I figured working with the container associated with the block was the best way to effect the inventory.

It isn't. The contents are synced from the IItemHandler when they change if you call detectAndSendChanges(I believe that is what it is called).

VANILLA MINECRAFT CLASSES ARE THE BEST RESOURCES WHEN MODDING

I will be posting 1.15.2 modding tutorials on this channel. If you want to be notified of it do the normal YouTube stuff like subscribing, ect.

Forge and vanilla BlockState generator.

Link to comment
Share on other sites

18 hours ago, Animefan8888 said:

Look at the methods inside it there are two I can think of insertItem and extractItem. 

 

It isn't. The contents are synced from the IItemHandler when they change if you call detectAndSendChanges(I believe that is what it is called).

I think I got it... again.

 

package com.Garrett.backtobasics.blocks;

import net.minecraft.block.Block;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.container.Container;
import net.minecraft.inventory.container.INamedContainerProvider;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.tileentity.ITickableTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.Direction;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.world.server.ServerWorld;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.util.INBTSerializable;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.ItemStackHandler;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import static net.minecraft.util.Direction.*;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

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

import static com.Garrett.backtobasics.blocks.ModBlocks.AUTO_MINER_TILE_ENTITY;

public class AutoMinerTileEntity extends TileEntity implements ITickableTileEntity, INamedContainerProvider {

    private static final Logger LOGGER = LogManager.getLogger();
    private LazyOptional<IItemHandler> handler = LazyOptional.of(this::createHandler);
    private int tickCounter = 0;
    private ArrayList<String> veinBlockList = new ArrayList<>();

    public AutoMinerTileEntity() {

        super(AUTO_MINER_TILE_ENTITY);
        veinBlockList.add("backtobasics:diamond_vein");
        veinBlockList.add("backtobasics:gold_vein");
        veinBlockList.add("backtobasics:iron_vein");
        veinBlockList.add("backtobasics:redstone_vein");
    }


    // 20 ticks per second
    @Override
    public void tick() {

        tickCounter++;

        if (tickCounter >= 60) {
            tickCounter = 0;

            mineBlock();
        }
    }

    // the lazy handler postpones execution of code until it is needed for the first time and cashes it
    // so it won't be recreated every time it is used.
    private ItemStackHandler createHandler () {
        return new ItemStackHandler(1);
    }

    // reads inventory from world file on load
    @Override
    public void read(CompoundNBT tag) {
        CompoundNBT invTag = tag.getCompound("inv");
        handler.ifPresent(h -> ((INBTSerializable<CompoundNBT>) h).deserializeNBT(invTag));
        createHandler().deserializeNBT(invTag);
        super.read(tag);
    }

    // writes inventory to world file whenever world is saved
    @Override
    public CompoundNBT write(CompoundNBT tag) {
        handler.ifPresent(h -> {
            CompoundNBT compound = ((INBTSerializable<CompoundNBT>) h).serializeNBT();
            tag.put("inv", compound);
        });
        return super.write(tag);
    }


    // Capabilities add funcionality to blocks and items.
    @Nonnull
    @Override
    public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction side) {
        if (cap == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) {
            return handler.cast();
        }
        return super.getCapability(cap, side);
    }

    @Override
    public ITextComponent getDisplayName() {
        return new StringTextComponent(getType().getRegistryName().getPath());
    }

    @Nullable
    @Override
    public Container createMenu(int i, PlayerInventory playerInventory, PlayerEntity playerEntity) {
        return new AutoMinerContainer(i, world, pos, playerInventory, playerEntity);
    }

    private void mineBlock() {

        if (world != null) {
            if (world.getServer() != null) {
                Block block = getBlockToMine();
                BlockPos blockPos = getBlockToMinePosition();
                handler.ifPresent(h -> {
                    ItemStack stack = h.getStackInSlot(0);
                    int stackSize = stack.getCount();
                    int stackLimit = h.getSlotLimit(0);
                    ServerWorld serverWorld = world.getServer().getWorld(world.dimension.getType());
                    List<ItemStack> drops = Block.getDrops(block.getDefaultState(), serverWorld, blockPos, super.getTileEntity());
                    for (ItemStack item: drops) {
                        if ((stackSize < stackLimit && item.getItem() == stack.getItem()) || stack.isEmpty()) {
                            h.insertItem(0, item, false);
                            if (!veinBlockList.contains(block.getRegistryName().toString())) {
                                world.destroyBlock(blockPos, false);
                            }
                        }
                    }
                });
            }
        }
    }

    // gets block connected to the "drill face"
    private Block getBlockToMine() {

        if (getBlockState().getValues().containsValue(UP)) {
            return world.getBlockState(getPos().up()).getBlock();

        } else if (getBlockState().getValues().containsValue(DOWN)) {
            return world.getBlockState(getPos().down()).getBlock();

        } else if (getBlockState().getValues().containsValue(NORTH)) {
            return world.getBlockState(getPos().north()).getBlock();

        } else if (getBlockState().getValues().containsValue(SOUTH)) {
            return world.getBlockState(getPos().south()).getBlock();

        } else if (getBlockState().getValues().containsValue(EAST)) {
            return world.getBlockState(getPos().east()).getBlock();

        } else {
            return world.getBlockState(getPos().west()).getBlock();
        }
    }
    // gets block connected to the "drill face"
    private BlockPos getBlockToMinePosition() {

        if (getBlockState().getValues().containsValue(UP)) {
            return getPos().up();

        } else if (getBlockState().getValues().containsValue(DOWN)) {
            return getPos().down();

        } else if (getBlockState().getValues().containsValue(NORTH)) {
            return getPos().north();

        } else if (getBlockState().getValues().containsValue(SOUTH)) {
            return getPos().south();

        } else if (getBlockState().getValues().containsValue(EAST)) {
            return getPos().east();

        } else {
            return getPos().west();
        }
    }
}

 

Edited by andGarrett
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • I am not using hardcoded recipes, I'm using Vanilla's already existing code for leather armor dying. (via extending and implementing DyeableArmorItem / DyeableLeatherItem respectively) I have actually figured out that it's something to do with registering item colors to the ItemColors instance, but I'm trying to figure out where exactly in my mod's code I would be placing a call to the required event handler. Unfortunately the tutorial is criminally undescriptive. The most I've found is that it has to be done during client initialization. I'm currently trying to do the necessary setup via hijacking the item registry since trying to modify the item classes directly (via using SubscribeEvent in the item's constructor didn't work. Class so far: // mrrp mrow - mcmod item painter v1.0 - catzrule ch package catzadvitems.init; import net.minecraft.client.color.item.ItemColors; import net.minecraft.world.item.Item; import net.minecraftforge.registries.ObjectHolder; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.client.event.ColorHandlerEvent; import catzadvitems.item.DyeableWoolArmorItem; @Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD) public class Painter { @ObjectHolder("cai:dyeable_wool_chestplate") public static final Item W_CHEST = null; @ObjectHolder("cai:dyeable_wool_leggings") public static final Item W_LEGS = null; @ObjectHolder("cai:dyeable_wool_boots") public static final Item W_SOCKS = null; public Painter() { // left blank, idk if forge throws a fit if constructors are missing, not taking the chance of it happening. } @SubscribeEvent public static void init(FMLClientSetupEvent event) { new Painter(); } @Mod.EventBusSubscriber private static class ForgeBusEvents { @SubscribeEvent public static void registerItemColors(ColorHandlerEvent.Item event) { ItemColors col = event.getItemColors(); col.register(DyeableUnderArmorItem::getItemDyedColor, W_CHEST, W_LEGS, W_SOCKS); //placeholder for other dye-able items here later.. } } } (for those wondering, i couldn't think of a creative wool helmet name)
    • nvm found out it was because i had create h and not f
    • Maybe there's something happening in the 'leather armor + dye' recipe itself that would be updating the held item texture?
    • @SubscribeEvent public static void onRenderPlayer(RenderPlayerEvent.Pre e) { e.setCanceled(true); model.renderToBuffer(e.getPoseStack(), pBuffer, e.getPackedLight(), 0f, 0f, 0f, 0f, 0f); //ToaPlayerRenderer.render(); } Since getting the render method from a separate class is proving to be bit of a brick wall for me (but seems to be the solution in older versions of minecraft/forge) I've decided to try and pursue using the renderToBuffer method directly from the model itself. I've tried this route before but can't figure out what variables to feed it for the vertexConsumer and still can't seem to figure it out; if this is even a path to pursue.  The vanilla model files do not include any form of render methods, and seem to be fully constructed from their layer definitions? Their renderer files seem to take their layers which are used by the render method in the vanilla MobRenderer class. But for modded entities we @Override this function and don't have to feed the method variables because of that? I assume that the render method in the extended renderer takes the layer definitions from the renderer classes which take those from the model files. Or maybe instead of trying to use a render method I should be calling the super from the renderer like   new ToaPlayerRenderer(context, false); Except I'm not sure what I would provide for context? There's a context method in the vanilla EntityRendererProvider class which doesn't look especially helpful. I've been trying something like <e.getEntity(), model<e.getEntity()>> since that generally seems to be what is provided to the renderers for context, but I don't know if it's THE context I'm looking for? Especially since the method being called doesn't want to take this or variations of this.   In short; I feel like I'm super super close but I have to be missing something obvious? Maybe this insane inane ramble post will provide some insight into this puzzle?
  • Topics

×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.