Jump to content

[1.15] Help getting container and gui to work properly


TheMysteryStache

Recommended Posts

I'm attempting to add some form of crafting screen to an entity I'm creating, but the slots are not working properly and while items  can be put in, they cannot be taken out. This is a link to a gif of the issue in game. I'm also putting in my container code and my entity class. I'm not entirely sure what the issue could be, but I'm thinking there's something wrong with my container code. The container code is mostly from my tileentity which actually works,  so I'm not entirely sure why it doesn't work with the entity itself.


import net.minecraft.entity.Entity;

import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.container.*;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.util.IWorldPosCallable;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.SlotItemHandler;
import net.minecraftforge.items.wrapper.InvWrapper;

import javax.annotation.Nullable;


import static com.minecraft2.ModBlocks.CLAIRO_CONTAINER;

public class ClairoContainer extends Container {


    public static Entity entity;
    private PlayerEntity playerEntity;
    private IItemHandler playerInventory;
    public IItemHandler handler;
    public ClairoContainer(int windowId, World world, BlockPos pos, PlayerInventory playerInventory, PlayerEntity player, Entity entity) {
        super(CLAIRO_CONTAINER, windowId);
        this.entity = entity;

        this.playerEntity = player;
        this.playerInventory = new InvWrapper(playerInventory);

        entity.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY).ifPresent(h -> {
            addSlot(new SlotItemHandler(h, 0, 64, 24));
            this.handler = h;
            //minecraft2mod.logger.info("ENTITY HAS CAPABILITY");
        });
        layoutPlayerInventorySlots(10, 70);
    }

    @Override
    public boolean canInteractWith(PlayerEntity playerEntity) {
        return true;

    }

    private int addSlotRange(IItemHandler handler, int index, int x, int y, int amount, int dx) {
        for (int i = 0 ; i < amount ; i++) {
            addSlot(new SlotItemHandler(handler, index, x, y));
            x += dx;
            index++;
        }
        return index;
    }

    private int addSlotBox(IItemHandler handler, int index, int x, int y, int horAmount, int dx, int verAmount, int dy) {
        for (int j = 0 ; j < verAmount ; j++) {
            index = addSlotRange(handler, index, x, y, horAmount, dx);
            y += dy;
        }
        return index;
    }

    private void layoutPlayerInventorySlots(int leftCol, int topRow) {
        // Player inventory
        addSlotBox(playerInventory, 9, leftCol, topRow, 9, 18, 3, 18);

        // Hotbar
        topRow += 58;
        addSlotRange(playerInventory, 0, leftCol, topRow, 9, 18);
    }

    @Override
    public ItemStack transferStackInSlot(PlayerEntity playerIn, int index) {
        ItemStack itemstack = ItemStack.EMPTY;
        Slot slot = this.inventorySlots.get(index);
        if (slot != null && slot.getHasStack()) {
            ItemStack stack = slot.getStack();
            itemstack = stack.copy();
            if (index == 0) {
                if (!this.mergeItemStack(stack, 1, 37, true)) {
                    return ItemStack.EMPTY;
                }
                slot.onSlotChange(stack, itemstack);
            } else {
                if (stack.getItem() == Items.DIAMOND) {
                    if (!this.mergeItemStack(stack, 0, 1, false)) {
                        return ItemStack.EMPTY;
                    }
                } else if (index < 28) {
                    if (!this.mergeItemStack(stack, 28, 37, false)) {
                        return ItemStack.EMPTY;
                    }
                } else if (index < 37 && !this.mergeItemStack(stack, 1, 28, false)) {
                    return ItemStack.EMPTY;
                }
            }

            if (stack.isEmpty()) {
                slot.putStack(ItemStack.EMPTY);
            } else {
                slot.onSlotChanged();
            }

            if (stack.getCount() == itemstack.getCount()) {
                return ItemStack.EMPTY;
            }

            slot.onTake(playerIn, stack);
        }

        return itemstack;
    }


}

Entity Code:

import net.minecraft.entity.AgeableEntity;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.goal.*;
import net.minecraft.entity.effect.LightningBoltEntity;
import net.minecraft.entity.passive.AnimalEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.inventory.container.Container;
import net.minecraft.inventory.container.INamedContainerProvider;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.tileentity.ITickableTileEntity;
import net.minecraft.util.Direction;
import net.minecraft.util.Hand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.world.World;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
import net.minecraftforge.common.util.INBTSerializable;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.fml.network.NetworkHooks;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.ItemStackHandler;

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

public class Clairo extends AnimalEntity implements ITickableTileEntity, INamedContainerProvider {

    private LazyOptional<IItemHandler> handler = LazyOptional.of(this::createHandler);

    public ClairoContainer container;

    public Clairo(EntityType<? extends AnimalEntity> p_i48568_1_, World p_i48568_2_) {

        super(p_i48568_1_, p_i48568_2_);
    }

    @Nullable
    @Override
    public AgeableEntity createChild(AgeableEntity ageableEntity) {
        return null;
    }


    @Override
    public boolean processInteract(PlayerEntity p_184645_1_, Hand p_184645_2_) {

        if(!world.isRemote)
        {
            if(this instanceof INamedContainerProvider)
            {
                NetworkHooks.openGui((ServerPlayerEntity) p_184645_1_, (INamedContainerProvider) this.getEntity(), this.getPosition());
            }
            else {
                throw new IllegalStateException("Our named container provider is missing!");
            }

            return true;
        }


        return super.processInteract(p_184645_1_, p_184645_2_);
    }



    @Override
    public void onStruckByLightning(LightningBoltEntity p_70077_1_) {
        this.setGlowing(true);
    }

    @Override
    protected void registerGoals() {
        this.goalSelector.addGoal(0, new SwimGoal(this));
        this.goalSelector.addGoal(1, new PanicGoal(this, 0.4));
        this.goalSelector.addGoal(2, new OpenDoorGoal(this, true));
        this.goalSelector.addGoal(3, new LookAtGoal(this, PlayerEntity.class, 6.0f));
        this.goalSelector.addGoal(4, new WaterAvoidingRandomWalkingGoal(this, 1.0));

        super.registerGoals();
    }

    @Override
    protected void updateAITasks() {
        super.updateAITasks();
    }

    public Entity entitygetter()
    {
        return this;
    }

    @Override
    public void livingTick() {
        if(this.world.isRemote)
        {
            handler.ifPresent(h ->
            {
                if(h.getStackInSlot(0) != null )
                {
                }

            });

        }
        super.livingTick();
    }

    @Override
    protected void registerAttributes() {
        super.registerAttributes();
        this.getAttribute(SharedMonsterAttributes.MAX_HEALTH).setBaseValue(20.0);
        this.getAttribute(SharedMonsterAttributes.MOVEMENT_SPEED).setBaseValue(0.2);
        this.getAttribute(SharedMonsterAttributes.FOLLOW_RANGE).setBaseValue(20.0);
        this.getAttribute(SharedMonsterAttributes.ARMOR).setBaseValue(10.0);
    }

    @Nullable
    @Override
    public Container createMenu(int i, PlayerInventory playerInventory, PlayerEntity playerEntity) {

        container = new ClairoContainer(i, playerEntity.world, playerEntity.getPosition(), playerInventory, playerEntity, this.getEntity());
        

        return container;
    }

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


    private IItemHandler createHandler() {

        return new ItemStackHandler(9)
        {
            @Override
            protected void onContentsChanged(int slot) {
                handler.ifPresent(h ->
                {
                    //h.insertItem(0, h.getStackInSlot(0), false);
                });
            }

        };

    }
    @Nonnull
    @Override
    public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction side) {
        if (cap == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) {
            return this.handler.cast();
        }
        return super.getCapability(cap, side);
    }

    @Override
    public void read(CompoundNBT tag) {
        CompoundNBT invTag = tag.getCompound("inv");
        handler.ifPresent(h -> ((INBTSerializable<CompoundNBT>)h).deserializeNBT(invTag));
        super.read(tag);
    }

    @Override
    public void writeAdditional(CompoundNBT tag) {
        handler.ifPresent(h -> {
            CompoundNBT compound = ((INBTSerializable<CompoundNBT>)h).serializeNBT();
            tag.put("inv", compound);
        });
        super.writeAdditional(tag);
    }
}

Please keep  in mind that I've been throwing hail mary's at  this code for a long time now so a lot of the code in here might not make sense and could even possibly be working against me. 

Any help is appreciated, thank you.

Link to comment
Share on other sites

The ITickableTileEntity I copied from my TileEntity code, only now do I actually read the name and realize it's for tile entities ?‍♂️. The position for the openGui was for a the container constructor but now I realize that the position isn't even used and so I've removed it. The getEntity I was using for some earlier debugging and has now been removed. I'm not entirely sure what a ScreenFactory is so I've added my Gui code and my client proxy.

Proxy:

public class ClientProxy implements IProxy {

    @Override
    public World getClientWorld()
    {
        return Minecraft.getInstance().world;
    }

    @Override
    public PlayerEntity getClientPlayer()
    {
        return Minecraft.getInstance().player;
    }
    @Override
    public void init() {
        ScreenManager.registerFactory(ModBlocks.FURNACEBLOCK_CONTAINER, furnaceBlockScreen::new);
        RenderingRegistry.registerEntityRenderingHandler(ModEntityTypes.clairo_entity.get(), ClairoEntityRender::new);
        ScreenManager.registerFactory(ModBlocks.CLAIRO_CONTAINER, ClairoScreen::new);
    }
}

Screen:


public class ClairoScreen extends ContainerScreen<ClairoContainer> {

    private ResourceLocation GUI = new ResourceLocation(minecraft2mod.MOD_ID, "textures/gui/clairo_gui.png");

    public ClairoScreen(ClairoContainer p_i51105_1_, PlayerInventory p_i51105_2_, ITextComponent p_i51105_3_) {
        super(p_i51105_1_, p_i51105_2_, p_i51105_3_);
    }

    @Override
    protected void drawGuiContainerBackgroundLayer(float v, int i, int i1) {
        GlStateManager.color4f(1.0F, 1.0F, 1.0F, 1.0F);
        this.minecraft.getTextureManager().bindTexture(GUI);
        int relX = (this.width - this.xSize) / 2;
        int relY = (this.height - this.ySize) / 2;
        this.blit(relX, relY, 0, 0, this.xSize, this.ySize);
    }

    @Override
    public void render(int mouseX, int mouseY, float partialTicks) {
        this.renderBackground();
        super.render(mouseX, mouseY, partialTicks);
        this.renderHoveredToolTip(mouseX, mouseY);
    }

    @Override
    protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) {

    }

Thank you for the help.

Link to comment
Share on other sites

@SubscribeEvent
        public static void onContainerRegistry(final RegistryEvent.Register<ContainerType<?>> event) {
            event.getRegistry().register(IForgeContainerType.create((windowId, inv, data) -> {
                BlockPos pos = data.readBlockPos();
                return new furnaceBlockContainer(windowId, minecraft2mod.proxy.getClientWorld(), pos, inv, minecraft2mod.proxy.getClientPlayer());
            }).setRegistryName("furnaceblock"));

            event.getRegistry().register(IForgeContainerType.create((windowId, inv, data) ->
            {

                return new ClairoContainer(windowId, minecraft2mod.proxy.getClientWorld(),  inv, minecraft2mod.proxy.getClientPlayer(), ClairoContainer.entity);
            }).setRegistryName("clairo_entity"));
        }

I think this would be where I'm creating the ContainerType, it's in my main mod file and is being registered with my TileEntity Container.

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



×
×
  • Create New...

Important Information

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