Jump to content

Recommended Posts

Posted

I created my custom IInventory, Container, GUIContainer and GUIHandler.

Without any problems I can drag an item inside the custom inventory slot and without any problems I can remove it double clicking it.

(I overwrote transferStackInSlot)

But somehow it isn't possible to remove the item in the slot dragging it.

 

package com.minecolonies.colony;

import com.minecolonies.inventory.InventoryField;
import com.minecolonies.util.BlockPosUtil;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemSeeds;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.BlockPos;
import org.jetbrains.annotations.NotNull;

public class Field extends Container
{
    /**
     * Tag to store the location.
     */
    private static final String TAG_LOCATION = "location";

    /**
     * Tag to store if the field has been taken.
     */
    private static final String TAG_TAKEN = "taken";

    /**
     * Tag to store the fields length.
     */
    private static final String TAG_LENGTH = "length";

    /**
     * Tag to store the fields width.
     */
    private static final String TAG_WIDTH = "width";

    /**
     * The max width/length of a field.
     */
    private static final int MAX_RANGE = 10;

    /**
     * The fields location.
     */
    private BlockPos location;

    /**
     * The colony of the field.
     */
    private final Colony colony;

    /**
     * Has the field be taken by any worker?
     */
    private boolean taken = false;

    /**
     * Checks if the field needsWork (Hoeig, Seedings, Farming etc)
     */
    private boolean needsWork = false;

    /**
     * Has the field been planted?
     */
    private boolean planted = false;

    /**
     * The set seed type for the field.
     */
    private ItemSeeds seed;

    /**
     * The length of the field.
     */
    private int length;

    /**
     * The width of the seed;
     */
    private int width;

    /**
     * The inventorySlot of the field.
     */
    private InventoryField inventory;

     /**
     * Private constructor to create field from NBT.
     * @param colony the colony the field belongs to.
     */
    private Field(Colony colony)
    {
       this.colony = colony;
    }

    /**
     * Creates a new field object.
     * @param colony The colony the field is a part of.
     * @param location The location the field has been placed.
     * @param width The fields width.
     * @param length The fields length.
     */
    public Field(Colony colony, BlockPos location, int width, int length, InventoryField inventory)
    {
        this.location = location;
        this.colony   = colony;
        this.length = length;
        this.width = width;
        this.inventory = inventory;
    }

    public Field(InventoryField inventory, final InventoryPlayer playerInventory)
    {
        colony = this.getColony();
        location = new BlockPos(0,1,2);

        this.inventory = inventory;

        addSlotToContainer(new Slot(inventory, 0, 80, 34));

        //Ddd player inventory slots
        // Note: The slot numbers are within the player inventory and may be the same as the field inventory.
        int i;
        for (i = 0; i < 3; ++i)
        {
            for (int j = 0; j < 9; ++j)
            {
                addSlotToContainer(new Slot(playerInventory, j+i*9+9,
                                            8+j*18, 84+i*18));
            }
        }

        for (i = 0; i < 9; ++i)
        {
            addSlotToContainer(new Slot(playerInventory, i, 8 + i * 18,
                                        142));
        }
    }

    /**
     * Returns the {@link BlockPos} of the current object, also used as ID
     *
     * @return          {@link BlockPos} of the current object
     */
    public BlockPos getID()
    {
        return this.location; //  Location doubles as ID
    }

    /**
     * Returns the colony of the field
     *
     * @return          {@link com.minecolonies.colony.Colony} of the current object
     */
    public Colony getColony()
    {
        return this.colony;
    }

    /**
     * Create and load a Field given it's saved NBTTagCompound
     *
     * @param colony    The owning colony
     * @param compound  The saved data
     * @return          {@link com.minecolonies.colony.Field} created from the compound.
     */
    public static Field createFromNBT(Colony colony, NBTTagCompound compound)
    {
        Field field = new Field(colony);
        field.readFromNBT(compound);
        return field;
    }

    /**
     * Save data to NBT compound.
     * Writes the {@link #location} value.
     *
     * @param compound      {@link net.minecraft.nbt.NBTTagCompound} to write data to
     */
    public void writeToNBT(NBTTagCompound compound)
    {
        BlockPosUtil.writeToNBT(compound, TAG_LOCATION, this.location);
        compound.setBoolean(TAG_TAKEN, taken);
        compound.setInteger(TAG_LENGTH, length);
        compound.setInteger(TAG_WIDTH, width);
        inventory.writeToNBT(compound);
    }

    /**
     * Save data to NBT compound.
     * Writes the {@link #location} value.
     *
     * @param compound      {@link net.minecraft.nbt.NBTTagCompound} to write data to
     */
    public void readFromNBT(NBTTagCompound compound)
    {
        location = BlockPosUtil.readFromNBT(compound, TAG_LOCATION);
        taken = compound.getBoolean(TAG_TAKEN);
        length = compound.getInteger(TAG_LENGTH);
        width = compound.getInteger(TAG_WIDTH);
        inventory = new InventoryField("Scarecrow", true);
        inventory.readFromNBT(compound);
    }

    /**
     * Has the field been taken?
     * @return true if the field is not free to use, false after releasing it.
     */
    public boolean isTaken() {
        return this.taken;
    }

    /**
     * Sets the field taken.
     * @param taken is field free or not
     */
    public void setTaken(boolean taken) {
        this.taken = taken;
    }

    /**
     * Checks if the field has been planted.
     * @return true if there are crops planted.
     */
    public boolean isPlanted()
    {
        return this.planted;
    }

    /**
     * Sets if there are any crops planted.
     * @param planted true after planting, false after harvesting.
     */
    public void setPlanted(boolean planted)
    {
        this.planted = planted;
    }

    /**
     * Checks if the field needs work (planting, hoeing)
     * @return true if so.
     */
    public boolean needsWork()
    {
        return this.needsWork;
    }

    /**
     * Sets that the field needs work
     * @param needsWork true if work needed, false after completing the job.
     */
    public void setNeedsWork(boolean needsWork)
    {
        this.needsWork = needsWork;
    }

    /**
     * Getter for the length.
     * @return the fields length.
     */
    public int getLength()
    {
        return this.length;
    }

    /**
     * Getter for the width.
     * @return the fields with.
     */
    public int getWidth()
    {
        return this.width;
    }

    /**
     * Getter for MAX_RANGE.
     * @return the max range.
     */
    public int getMaxRange()
    {
        return MAX_RANGE;
    }

    /**
     * Return this citizens inventory.
     *
     * @return the inventory this citizen has.
     */
    @NotNull
    public InventoryField getInventoryField()
    {
        return inventory;
    }

    @Override
    public boolean canInteractWith(final EntityPlayer playerIn)
    {
        return true;
    }

    @Override
    public ItemStack transferStackInSlot(EntityPlayer playerIn, int slotIndex)
    {
        if (slotIndex == 0)
        {
            playerIn.inventory.addItemStackToInventory(inventory.getStackInSlot(0));
            inventory.setInventorySlotContents(0, null);
        }
        else if(inventory.getStackInSlot(0) == null)
        {
            int playerIndex = slotIndex < 28 ? slotIndex + 8 : slotIndex - 28;
            if(playerIn.inventory.getStackInSlot(playerIndex) != null)
            {
                inventory.setInventorySlotContents(0, playerIn.inventory.getStackInSlot(playerIndex).splitStack(1));
            }
        }

        return null;
    }

    @Override
    public ItemStack slotClick(final int slotId, final int clickedButton, final int mode, final EntityPlayer playerIn)
    {
        return super.slotClick(slotId, clickedButton, mode, playerIn);
    }
}

 

package com.minecolonies.inventory;
import com.minecolonies.colony.materials.MaterialSystem;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraftforge.common.util.Constants;

/**
* The custom chest of the field.
*/
public class InventoryField extends InventoryCitizen
{
    /**
     * NBTTag to store the slot.
     */
    private static final String TAG_SLOT = "slot";

    /**
     * NBTTag to store the items.
     */
    private static final String TAG_ITEMS = "items";

    /**
     * NBTTag to store the custom name.
     */
    private static final String TAG_CUSTOM_NAME = "name";

    /**
     * NBTTag to store the inventory.
     */
    private static final String TAG_INVENTORY = "inventory";

    /**
     * Returned slot if no slat has been found.
     */
    private static final int NO_SLOT = -1;

    /**
     * The inventory stack.
     */
    private ItemStack[] stackResult   = new ItemStack[1];

    /**
     * The custom name of the inventory.
     */
    private String customName         = "";

    /**
     * Creates the inventory of the citizen.
     *
     * @param title         Title of the inventory.
     * @param localeEnabled Boolean whether the inventory has a custom name.
     */
    public InventoryField(final String title, final boolean localeEnabled)
    {
        super(title, localeEnabled);
        customName = title;
    }

    @Override
    public int getSizeInventory()
    {
        return 1;
    }

    @Override
    public int getInventoryStackLimit()
    {
        return 1;
    }

    @Override
    public int getHotbarSize()
    {
        return 0;
    }

    public ItemStack getStackInSlot(int index)
    {
        return this.stackResult[0];
    }

    @Override
    public boolean hasCustomName()
    {
        return true;
    }

    /**
     * Sets the given item stack to the specified slot in the inventory (can be crafting or armor sections).
     * @param index the slot to set the itemStack.
     * @param stack the itemStack to set.
     */
    @Override
    public void setInventorySlotContents(int index, ItemStack stack)
    {
        this.stackResult[index] = stack;

        if (stack != null && stack.stackSize > this.getInventoryStackLimit())
        {
            stack.stackSize = this.getInventoryStackLimit();
        }

        this.markDirty();
    }

    /**
     *  Get the name of this object. For citizens this returns their name.
     * @return the name of the inventory.
     */
    @Override
    public String getName()
    {
        return this.hasCustomName() ? this.customName : "field.inventory";
    }

    /**
     * Used to retrieve variables.
     * @param compound with the give tag.
     */
    @Override
    public void readFromNBT(NBTTagCompound compound)
    {
        NBTTagList nbttaglist = compound.getTagList(TAG_ITEMS, Constants.NBT.TAG_COMPOUND);
        this.stackResult = new ItemStack[this.getSizeInventory()];

        for (int i = 0; i < nbttaglist.tagCount(); ++i)
        {
            NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i);
            int            j              = nbttagcompound.getByte(TAG_SLOT) & Byte.MAX_VALUE;

            if (j != NO_SLOT && j < this.stackResult.length)
            {
                this.stackResult[j] = ItemStack.loadItemStackFromNBT(nbttagcompound);
            }
        }

        if (compound.hasKey(TAG_CUSTOM_NAME, Constants.NBT.TAG_STRING))
        {
            this.customName = compound.getString(TAG_CUSTOM_NAME);
        }
    }

    /**
     * Used to store variables.
     * @param compound with the given tag.
     */
    @Override
    public void writeToNBT(NBTTagCompound compound)
    {
        NBTTagList nbttaglist = new NBTTagList();

        for (int i = 0; i < this.stackResult.length; ++i)
        {
            if (this.stackResult[i] != null)
            {
                NBTTagCompound nbttagcompound = new NBTTagCompound();
                nbttagcompound.setByte(TAG_SLOT, (byte) i);
                this.stackResult[i].writeToNBT(nbttagcompound);
                nbttaglist.appendTag(nbttagcompound);
            }
        }

        compound.setTag(TAG_ITEMS, nbttaglist);

        if (this.hasCustomName())
        {
            compound.setString(TAG_CUSTOM_NAME, this.customName);
        }

        compound.setTag(TAG_INVENTORY, nbttaglist);
    }
}

Posted

public ItemStack transferStackInSlot(EntityPlayer playerIn, int slotIndex) isn't called  when I try to drag it out of the custom inventory, it gets called the other way around.

public ItemStack slotClick(final int slotId, final int clickedButton, final int mode, final EntityPlayer playerIn) always gets called but I do not overwrite it.

 

 

Posted

Look at the log, I am pretty sure there is somewhere an exception, also wich constructor do you use and how looks you guiHandler ?

catch(Exception e)

{

 

}

Yay, Pokémon exception handling, gotta catch 'em all (and then do nothing with 'em).

Posted

The InventoryField extends InventoryCitizen which extends IInventory.

I do not get any feedback at all when I try to drag out an object not even a log or exception.

 

The GuiHandler.

@SideOnly(Side.CLIENT)
public class GuiHandler implements IGuiHandler
{
    @Override
    public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z)
    {
        BlockPos            pos        = new BlockPos(x,y,z);
        ScarecrowTileEntity tileEntity = (ScarecrowTileEntity) world.getTileEntity(pos);
        return new Field(tileEntity.inventoryField, player.inventory, world, pos);
    }

    @Override
    public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z)
    {
        BlockPos            pos        = new BlockPos(x,y,z);
        ScarecrowTileEntity tileEntity = (ScarecrowTileEntity) world.getTileEntity(pos);
        return new GuiField(player.inventory, tileEntity.inventoryField, world, pos);

    }
}

 

Posted

[16:23:15] [Realms Notification Availability checker #1/INFO]: Could not authorize you against Realms server: Invalid session id
[16:26:01] [server thread/INFO]: Starting integrated minecraft server version 1.8.9
[16:26:01] [server thread/INFO]: Generating keypair
[16:26:01] [server thread/INFO] [FML]: Injecting existing block and item data into this server instance
[16:26:01] [server thread/INFO] [FML]: Applying holder lookups
[16:26:01] [server thread/INFO] [FML]: Holder lookups applied
[16:26:02] [Realms Notification Availability checker #1/INFO]: Could not authorize you against Realms server: Invalid session id
[16:26:02] [server thread/INFO] [FML]: Loading dimension 0 (New World) (net.minecraft.server.integrated.IntegratedServer@24062a4b)
[16:26:02] [server thread/INFO] [FML]: Loading dimension 1 (New World) (net.minecraft.server.integrated.IntegratedServer@24062a4b)
[16:26:02] [server thread/INFO] [minecolonies]: Loaded 1 colonies
[16:26:02] [server thread/INFO] [FML]: Loading dimension -1 (New World) (net.minecraft.server.integrated.IntegratedServer@24062a4b)
[16:26:02] [server thread/INFO]: Preparing start region for level 0
[16:26:03] [server thread/INFO]: Preparing spawn area: 47%
[16:26:04] [server thread/INFO] [minecolonies]: Starting AI job com.minecolonies.job.Lumberjack
[16:26:04] [Realms Notification Availability checker #1/INFO]: Could not authorize you against Realms server: Invalid session id
[16:26:04] [server thread/INFO] [minecolonies]: Starting AI job com.minecolonies.job.Builder
[16:26:04] [server thread/INFO]: Changing view distance to 6, from 10
[16:26:06] [Netty Local Client IO #0/INFO] [FML]: Server protocol version 2
[16:26:06] [Netty Server IO #1/INFO] [FML]: Client protocol version 2
[16:26:06] [Netty Server IO #1/INFO] [FML]: Client attempting to join with 4 mods : [email protected],[email protected],minecolonies@@VERSION@,[email protected]
[16:26:06] [Netty Local Client IO #0/INFO] [FML]: [Netty Local Client IO #0] Client side modded connection established
[16:26:06] [server thread/INFO] [FML]: [server thread] Server side modded connection established
[16:26:06] [server thread/INFO]: Raycoms[local:E:fb690bcb] logged in with entity id 557 at (-180.58073028560275, 64.88756546798191, 268.0009106214668)
[16:26:06] [server thread/INFO]: Raycoms joined the game
[16:26:08] [pool-2-thread-1/WARN]: Couldn't look up profile properties for com.mojang.authlib.GameProfile@3ec8890[id=7a8d2f7a-e6ca-3651-b109-06fdcd7aa8cb,name=Raycoms,properties={},legacy=false]
com.mojang.authlib.exceptions.AuthenticationException: The client has sent too many requests within a certain amount of time
at com.mojang.authlib.yggdrasil.YggdrasilAuthenticationService.makeRequest(YggdrasilAuthenticationService.java:65) ~[YggdrasilAuthenticationService.class:?]
at com.mojang.authlib.yggdrasil.YggdrasilMinecraftSessionService.fillGameProfile(YggdrasilMinecraftSessionService.java:175) [YggdrasilMinecraftSessionService.class:?]
at com.mojang.authlib.yggdrasil.YggdrasilMinecraftSessionService$1.load(YggdrasilMinecraftSessionService.java:59) [YggdrasilMinecraftSessionService$1.class:?]
at com.mojang.authlib.yggdrasil.YggdrasilMinecraftSessionService$1.load(YggdrasilMinecraftSessionService.java:56) [YggdrasilMinecraftSessionService$1.class:?]
at com.google.common.cache.LocalCache$LoadingValueReference.loadFuture(LocalCache.java:3524) [guava-17.0.jar:?]
at com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2317) [guava-17.0.jar:?]
at com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2280) [guava-17.0.jar:?]
at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2195) [guava-17.0.jar:?]
at com.google.common.cache.LocalCache.get(LocalCache.java:3934) [guava-17.0.jar:?]
at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:3938) [guava-17.0.jar:?]
at com.google.common.cache.LocalCache$LocalLoadingCache.get(LocalCache.java:4821) [guava-17.0.jar:?]
at com.google.common.cache.LocalCache$LocalLoadingCache.getUnchecked(LocalCache.java:4827) [guava-17.0.jar:?]
at com.mojang.authlib.yggdrasil.YggdrasilMinecraftSessionService.fillProfileProperties(YggdrasilMinecraftSessionService.java:165) [YggdrasilMinecraftSessionService.class:?]
at net.minecraft.client.Minecraft.getProfileProperties(Minecraft.java:2951) [Minecraft.class:?]
at net.minecraft.client.resources.SkinManager$3.run(SkinManager.java:130) [skinManager$3.class:?]
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [?:1.8.0_102]
at java.util.concurrent.FutureTask.run(FutureTask.java:266) [?:1.8.0_102]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [?:1.8.0_102]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [?:1.8.0_102]
at java.lang.Thread.run(Thread.java:745) [?:1.8.0_102]
[16:26:33] [server thread/INFO] [minecolonies]: Colony 1 - new AbstractBuilding for class com.minecolonies.blocks.BlockHutBuilder at BlockPos{x=-193, y=67, z=254}
[16:26:34] [server thread/INFO] [minecolonies]: Starting AI job com.minecolonies.job.Builder
[16:26:34] [server thread/INFO] [minecolonies]: Colony 1 - removed AbstractBuilding BlockPos{x=-193, y=67, z=254} of type Builder
[16:26:35] [Client thread/INFO]: [CHAT] Lumberjack James M. Robinson: I need axe!
[16:26:35] [server thread/INFO] [minecolonies]: Colony 1 - new AbstractBuilding for class com.minecolonies.blocks.BlockHutBuilder at BlockPos{x=-194, y=66, z=253}
[16:26:35] [server thread/INFO] [minecolonies]: Starting AI job com.minecolonies.job.Builder
[16:26:37] [server thread/INFO] [minecolonies]: Colony 1 - removed AbstractBuilding BlockPos{x=-194, y=66, z=253} of type Builder
[16:26:41] [server thread/INFO] [minecolonies]: Colony 1 - new AbstractBuilding for class com.minecolonies.blocks.BlockHutBuilder at BlockPos{x=-194, y=66, z=251}
[16:26:41] [server thread/INFO] [minecolonies]: Starting AI job com.minecolonies.job.Builder
[16:26:41] [server thread/INFO] [minecolonies]: Colony 1 - removed AbstractBuilding BlockPos{x=-194, y=66, z=251} of type Builder
[16:27:22] [Client thread/INFO]: [CHAT] Finished building classic/Fisherman1
[16:27:22] [server thread/INFO] [minecolonies]: Starting AI job com.minecolonies.job.Fisherman
[16:27:35] [Client thread/INFO]: [CHAT] Lumberjack James M. Robinson: I need axe!
[16:27:40] [Client thread/INFO]: [CHAT] Fisherman Dorothy S. Johnson: I need Fishing Rod!
[16:28:10] [Client thread/INFO]: [CHAT] Fisherman Dorothy S. Johnson: I need Fishing Rod!
[16:29:11] [Client thread/INFO]: [CHAT] Fisherman Dorothy S. Johnson: I need Fishing Rod!

 

Nothing interesting in the log.

Posted

Already had removed the method completely out of the code, I only used it for debugging, since it only calls it's super method.

But with or without final, with or without that method it doesn't work.

 

 

Posted
@SideOnly(Side.CLIENT)
public class GuiField extends GuiContainer
{
    /**
     * The resource location of the GUI background.
     */
    private static final ResourceLocation TEXTURE = new ResourceLocation(Constants.MOD_ID, "textures/gui/scarecrow.png");

    /**
     * Constructor of the GUI.
     * @param parInventoryPlayer the player inventory.
     * @param fieldInventory the field inventory.
     */
    protected GuiField(InventoryPlayer parInventoryPlayer, IInventory fieldInventory, World world, BlockPos location)
    {
        super(new Field((InventoryField) fieldInventory, parInventoryPlayer, world, location));
    }

    /**
     * Does draw the background of the GUI.
     * @param partialTicks the ticks delivered.
     * @param mouseX the mouseX position.
     * @param mouseY the mouseY position.
     */
    @Override
    protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY)
    {
        GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
        mc.getTextureManager().bindTexture(TEXTURE);
        int marginHorizontal = (width - xSize) / 2;
        int marginVertical   = (height - ySize) / 2;
        drawTexturedModalRect(marginHorizontal, marginVertical, 0, 0, xSize, ySize);
    }
}

Posted

Exactly, when I try to move the object out of the custom inventory by clicking on it and then trying to move it with clicked mouse out of it, nothing happens.

 

Posted

Anyone has an idea, tried everything =/

I'm pretty sure I figured it out, you never add any slots server side. You use the first constructor with just sets the variables inside the Container, but when creating a container in the Gui you add the slots.

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.

Posted

The first constructor I only call in order to recreate the Field object vom NBT.

If you have any idea how I could fix it, I'd try =P

 

Our code is also on GitHub if you'd like to test it out.

 

https://github.com/Minecolonies/minecolonies

I do not have time to check it out but you can get all of that data from the TileEntity so instead just call the second constructor and set the data from the TileEntity, then if you want to display some of this data on the gui look at how ContainerFurnace, TileEntityFurnace, and GuiFurnace sync that data.

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.

Posted

How can I get the playerInventory from the tileEntity?

 

This in the GUIHandler does not call both constructors of the field?

Also I am able to transfer the items between the slots inside the inventory and back again, just not by drag and drop.

 

 

    @Override
    public Object getServerGuiElement(int id, EntityPlayer player, World world, int x, int y, int z)
    {
        final BlockPos            pos        = new BlockPos(x,y,z);
        final ScarecrowTileEntity tileEntity = (ScarecrowTileEntity) world.getTileEntity(pos);
        return new Field(tileEntity.getInventoryField(), player.inventory, world, pos);
    }

    @Override
    public Object getClientGuiElement(int id, EntityPlayer player, World world, int x, int y, int z)
    {
        final BlockPos            pos        = new BlockPos(x,y,z);
        final ScarecrowTileEntity tileEntity = (ScarecrowTileEntity) world.getTileEntity(pos);
        return new GuiField(player.inventory, tileEntity.getInventoryField(), world, pos);
    }

Posted

How can I get the playerInventory from the tileEntity?

 

This in the GUIHandler does not call both constructors of the field?

Also I am able to transfer the items between the slots inside the inventory and back again, just not by drag and drop.

 

 

    @Override
    public Object getServerGuiElement(int id, EntityPlayer player, World world, int x, int y, int z)
    {
        final BlockPos            pos        = new BlockPos(x,y,z);
        final ScarecrowTileEntity tileEntity = (ScarecrowTileEntity) world.getTileEntity(pos);
        return new Field(tileEntity.getInventoryField(), player.inventory, world, pos);
    }

    @Override
    public Object getClientGuiElement(int id, EntityPlayer player, World world, int x, int y, int z)
    {
        final BlockPos            pos        = new BlockPos(x,y,z);
        final ScarecrowTileEntity tileEntity = (ScarecrowTileEntity) world.getTileEntity(pos);
        return new GuiField(player.inventory, tileEntity.getInventoryField(), world, pos);
    }

Instead of passing in tileEntity.getInventoryField() just pass tileEntity into the constructor. You would pass the players inventory the same way.

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.

Posted

Sorry, but I still do not understand what I should do with that tileEntity.

 

 

public Field(ScarecrowTileEntity scarecrowTileEntity, InventoryPlayer playerInventory, World world, BlockPos location)
    {
        super();
        this.colony = ColonyManager.getColony(world, location);
        this.location = location;

        this.inventory = scarecrowTileEntity.getInventoryField();

        addSlotToContainer(new Slot(inventory, 0, X_OFFSET, Y_OFFSET));

        //Ddd player inventory slots
        // Note: The slot numbers are within the player inventory and may be the same as the field inventory.
        int i;
        for (i = 0; i < PLAYER_INVENTORY_ROWS; i++)
        {
            for (int j = 0; j < PLAYER_INVENTORY_COLUMNS; j++)
            {
                addSlotToContainer(new Slot(
                        playerInventory,
                        j + i * PLAYER_INVENTORY_COLUMNS + PLAYER_INVENTORY_COLUMNS,
                        PLAYER_INVENTORY_INITIAL_X_OFFSET + j * PLAYER_INVENTORY_OFFSET_EACH,
                        PLAYER_INVENTORY_INITIAL_Y_OFFSET + i * PLAYER_INVENTORY_OFFSET_EACH
                ));
            }
        }

        for (i = 0; i < PLAYER_INVENTORY_COLUMNS; i++)
        {
            addSlotToContainer(new Slot(
                    playerInventory, i,
                    PLAYER_INVENTORY_INITIAL_X_OFFSET + i * PLAYER_INVENTORY_OFFSET_EACH,
                    PLAYER_INVENTORY_HOTBAR_OFFSET
            ));
        }
        calculateSize(world, location.down());
    }

Posted

Anyone any idea?

 

The GuiHandler calls the Field constructor and calls the GuiField constructor which again calls the Field constructor and therefore client and server side are called and instantiated correctly.

Posted

Container class:

/**
* Handles the field class.
*/
public class Field extends Container
{
    /**
     * The size of a normal inventory.
     */
    private static final int MAX_INVENTORY_INDEX = 28;

    /**
     * The size of the the inventory hotbar.
     */
    private static final int INVENTORY_BAR_SIZE = 8;

    /**
     * X-Offset of the inventory slot in the GUI of the scarecrow.
     */
    private static final int X_OFFSET = 80;

    /**
     * Y-Offset of the inventory slot in the GUI of the scarecrow.
     */
    private static final int Y_OFFSET = 34;

    /**
     * Tag to store the location.
     */
    private static final String TAG_LOCATION = "location";

    /**
     * Tag to store if the field has been taken.
     */
    private static final String TAG_TAKEN = "taken";

    /**
     * Tag to store the fields positive length.
     */
    private static final String TAG_LENGTH_PLUS = "length+";

    /**
     * Tag to store the fields positive width.
     */
    private static final String TAG_WIDTH_PLUS = "width+";

    /**
     * Tag to store the fields negative length.
     */
    private static final String TAG_LENGTH_MINUS = "length-";

    /**
     * Tag to store the fields negative width.
     */
    private static final String TAG_WIDTH_MINUS = "width-";

    /**
     * Tag to store the fields stage.
     */
    private static final String TAG_STAGE = "stage";

    /**
     * Amount of rows in the player inventory.
     */
    private static final int PLAYER_INVENTORY_ROWS = 3;

    /**
     * Amount of columns in the player inventory.
     */
    private static final int PLAYER_INVENTORY_COLUMNS = 9;

    /**
     * Initial x-offset of the inventory slot.
     */
    private static final int PLAYER_INVENTORY_INITIAL_X_OFFSET = 8;

    /**
     * Initial y-offset of the inventory slot.
     */
    private static final int PLAYER_INVENTORY_INITIAL_Y_OFFSET = 84;

    /**
     * Each offset of the inventory slots.
     */
    private static final int PLAYER_INVENTORY_OFFSET_EACH = 18;

    /**
     * Initial y-offset of the inventory slots in the hotbar.
     */
    private static final int PLAYER_INVENTORY_HOTBAR_OFFSET = 142;

    /**
     * The max width/length of a field.
     */
    private static final int MAX_RANGE = 5;
    /**
     * The colony of the field.
     */
    private final Colony   colony;

    /**
     * The fields location.
     */
    private BlockPos location;

    /**
     * Has the field be taken by any worker?
     */
    private boolean taken = false;

    /**
     * Checks if the field needsWork (Hoeig, Seedings, Farming etc).
     */
    private boolean needsWork = false;

    /**
     * Has the field been planted?
     */
    private FieldStage fieldStage = FieldStage.EMPTY;

    /**
     * The length to plus x of the field.
     */
    private int lengthPlusX;

    /**
     * The width to plus z of the seed.
     */
    private int widthPlusZ;

    /**
     * The length to minus xof the field.
     */
    private int lengthMinusX;

    /**
     * The width to minus z of the seed.
     */
    private int widthMinusZ;

    /**
     * The inventorySlot of the field.
     */
    private InventoryField inventory;

    /**
     * Name of the citizen claiming the field.
     */
    private String owner = "";

    /**
     * Private constructor to create field from NBT.
     *
     * @param colony the colony the field belongs to.
     */
    private Field(Colony colony)
    {
        super();
        this.colony = colony;
    }

    /**
     * Creates an instance of our field container, this may be serve to open the GUI.
     *
     * @param scarecrowTileEntity       the tileEntity of the field containing the inventory.
     * @param playerInventory the player inventory.
     * @param world           the world.
     * @param location        the position of the field.
     */
    public Field(ScarecrowTileEntity scarecrowTileEntity, InventoryPlayer playerInventory, World world, BlockPos location)
    {
        super();
        this.colony = ColonyManager.getColony(world, location);
        this.location = location;
        this.inventory = scarecrowTileEntity.getInventoryField();

        addSlotToContainer(new Slot(inventory, 0, X_OFFSET, Y_OFFSET));

        //Ddd player inventory slots
        // Note: The slot numbers are within the player inventory and may be the same as the field inventory.
        int i;
        for (i = 0; i < PLAYER_INVENTORY_ROWS; i++)
        {
            for (int j = 0; j < PLAYER_INVENTORY_COLUMNS; j++)
            {
                addSlotToContainer(new Slot(
                        playerInventory,
                        j + i * PLAYER_INVENTORY_COLUMNS + PLAYER_INVENTORY_COLUMNS,
                        PLAYER_INVENTORY_INITIAL_X_OFFSET + j * PLAYER_INVENTORY_OFFSET_EACH,
                        PLAYER_INVENTORY_INITIAL_Y_OFFSET + i * PLAYER_INVENTORY_OFFSET_EACH
                ));
            }
        }

        for (i = 0; i < PLAYER_INVENTORY_COLUMNS; i++)
        {
            addSlotToContainer(new Slot(
                    playerInventory, i,
                    PLAYER_INVENTORY_INITIAL_X_OFFSET + i * PLAYER_INVENTORY_OFFSET_EACH,
                    PLAYER_INVENTORY_HOTBAR_OFFSET
            ));
        }
        calculateSize(world, location.down());
    }

    /**
     * Create and load a Field given it's saved NBTTagCompound.
     *
     * @param colony   The owning colony.
     * @param compound The saved data.
     * @return {@link Field} created from the compound.
     */
    public static Field createFromNBT(Colony colony, NBTTagCompound compound)
    {
        final Field field = new Field(colony);
        field.readFromNBT(compound);
        return field;
    }

    /**
     * Save data to NBT compound.
     * Writes the {@link #location} value.
     *
     * @param compound {@link net.minecraft.nbt.NBTTagCompound} to write data to.
     */
    public void readFromNBT(NBTTagCompound compound)
    {
        location = BlockPosUtil.readFromNBT(compound, TAG_LOCATION);
        taken = compound.getBoolean(TAG_TAKEN);
        fieldStage = FieldStage.values()[compound.getInteger(TAG_STAGE)];
        lengthPlusX = compound.getInteger(TAG_LENGTH_PLUS);
        widthPlusZ = compound.getInteger(TAG_WIDTH_PLUS);
        lengthMinusX = compound.getInteger(TAG_LENGTH_MINUS);
        widthMinusZ = compound.getInteger(TAG_WIDTH_MINUS);
        inventory = new InventoryField("Scarecrow", true);
        inventory.readFromNBT(compound);
    }

    /**
     * Getter for MAX_RANGE.
     *
     * @return the max range.
     */
    private static int getMaxRange()
    {
        return MAX_RANGE;
    }

    @Override
    public ItemStack transferStackInSlot(EntityPlayer playerIn, int slotIndex)
    {
        if (slotIndex == 0)
        {
            playerIn.inventory.addItemStackToInventory(inventory.getStackInSlot(0));
            inventory.setInventorySlotContents(0, null);
        }
        else if (inventory.getStackInSlot(0) == null)
        {
            final int playerIndex = slotIndex < MAX_INVENTORY_INDEX ? (slotIndex + INVENTORY_BAR_SIZE) : (slotIndex - MAX_INVENTORY_INDEX);
            if (playerIn.inventory.getStackInSlot(playerIndex) != null)
            {
                final ItemStack stack = playerIn.inventory.getStackInSlot(playerIndex).splitStack(1);
                inventory.setInventorySlotContents(0, stack);
                if (playerIn.inventory.getStackInSlot(playerIndex).stackSize == 0)
                {
                    playerIn.inventory.removeStackFromSlot(playerIndex);
                }
            }
        }

        return null;
    }

    @Override
    public boolean canInteractWith(EntityPlayer playerIn)
    {
        return getColony().getPermissions().hasPermission(playerIn, Permissions.Action.ACCESS_HUTS);
    }

    /**
     * Returns the colony of the field.
     *
     * @return {@link com.minecolonies.colony.Colony} of the current object.
     */
    public Colony getColony()
    {
        return this.colony;
    }

    /**
     * Calculates recursively the length of the field until a certain point.
     *
     * This mutates the field!
     *
     * @param position the start position.
     * @param world    the world the field is in.
     */
    public final void calculateSize(World world, BlockPos position)
    {
        //Calculate in all 4 directions
        this.lengthPlusX = searchNextBlock(0, position.east(), EnumFacing.EAST, world);
        this.lengthMinusX = searchNextBlock(0, position.west(), EnumFacing.WEST, world);
        this.widthPlusZ = searchNextBlock(0, position.south(), EnumFacing.SOUTH, world);
        this.widthMinusZ = searchNextBlock(0, position.north(), EnumFacing.NORTH, world);
    }

    /**
     * Calculates the field size into a specific direction.
     *
     * @param blocksChecked how many blocks have been checked.
     * @param position      the start position.
     * @param direction     the direction to search.
     * @param world         the world object.
     * @return the distance.
     */
    private int searchNextBlock(int blocksChecked, BlockPos position, EnumFacing direction, World world)
    {
        if (blocksChecked == getMaxRange() || isNoPartOfField(world, position))
        {
            return blocksChecked;
        }
        return searchNextBlock(blocksChecked + 1, position.offset(direction), direction, world);
    }

    /**
     * Checks if a certain position is part of the field. Complies with the definition of field block.
     *
     * @param world    the world object.
     * @param position the position.
     * @return true if it is.
     */
    public boolean isNoPartOfField(World world, BlockPos position)
    {
        return world.isAirBlock(position) || world.getBlockState(position.up()).getBlock().getMaterial().isSolid();
    }

    /**
     * Returns the {@link BlockPos} of the current object, also used as ID.
     *
     * @return {@link BlockPos} of the current object.
     */
    public BlockPos getID()
    {
        // Location doubles as ID
        return this.location;
    }

    /**
     * Save data to NBT compound.
     * Writes the {@link #location} value.
     *
     * @param compound {@link net.minecraft.nbt.NBTTagCompound} to write data to.
     */
    public void writeToNBT(NBTTagCompound compound)
    {
        BlockPosUtil.writeToNBT(compound, TAG_LOCATION, this.location);
        compound.setBoolean(TAG_TAKEN, taken);
        compound.setInteger(TAG_STAGE, fieldStage.ordinal());
        compound.setInteger(TAG_LENGTH_PLUS, lengthPlusX);
        compound.setInteger(TAG_WIDTH_PLUS, widthPlusZ);
        compound.setInteger(TAG_LENGTH_MINUS, lengthMinusX);
        compound.setInteger(TAG_WIDTH_MINUS, widthMinusZ);
        inventory.writeToNBT(compound);
    }

    /**
     * Has the field been taken?
     *
     * @return true if the field is not free to use, false after releasing it.
     */
    public boolean isTaken()
    {
        return this.taken;
    }

    /**
     * Sets the field taken.
     *
     * @param taken is field free or not
     */
    public void setTaken(boolean taken)
    {
        this.taken = taken;
    }

    /**
     * Checks if the field has been planted.
     *
     * @return true if there are crops planted.
     */
    public FieldStage getFieldStage()
    {
        return this.fieldStage;
    }

    /**
     * Sets if there are any crops planted.
     *
     * @param fieldStage true after planting, false after harvesting.
     */
    public void setFieldStage(FieldStage fieldStage)
    {
        this.fieldStage = fieldStage;
    }

    /**
     * Checks if the field needs work (planting, hoeing).
     *
     * @return true if so.
     */
    public boolean needsWork()
    {
        return this.needsWork;
    }

    /**
     * Sets that the field needs work.
     *
     * @param needsWork true if work needed, false after completing the job.
     */
    public void setNeedsWork(boolean needsWork)
    {
        this.needsWork = needsWork;
    }

    /**
     * Getter of the seed of the field.
     *
     * @return the ItemSeed
     */
    public Item getSeed()
    {
        if (inventory.getStackInSlot(0) != null && inventory.getStackInSlot(0).getItem() instanceof IPlantable)
        {
            return inventory.getStackInSlot(0).getItem();
        }
        return null;
    }

    /**
     * Getter of the length in plus x direction.
     *
     * @return field length.
     */
    public int getLengthPlusX()
    {
        return lengthPlusX;
    }

    /**
     * Getter of the with in plus z direction.
     *
     * @return field width.
     */
    public int getWidthPlusZ()
    {
        return widthPlusZ;
    }

    /**
     * Getter of the length in minus x direction.
     *
     * @return field length.
     */
    public int getLengthMinusX()
    {
        return lengthMinusX;
    }

    /**
     * Getter of the with in minus z direction.
     *
     * @return field width.
     */
    public int getWidthMinusZ()
    {
        return widthMinusZ;
    }

    /**
     * Location getter.
     *
     * @return the location of the scarecrow of the field.
     */
    public BlockPos getLocation()
    {
        return this.location;
    }

    /**
     * Return this citizens inventory.
     *
     * @return the inventory this citizen has.
     */
    @NotNull
    public InventoryField getInventoryField()
    {
        return inventory;
    }

    /**
     * Sets the inventory of the field.
     *
     * @param inventory the inventory to set.
     */
    public void setInventoryField(InventoryField inventory)
    {
        this.inventory = inventory;
    }

    /**
     * Sets the owner of the field.
     * @param owner the name of the citizen.
     */
    public void setOwner(final String owner)
    {
        this.owner = owner;
    }

    /**
     * Getter of the owner of the field.
     * @return the string description of the citizen.
     */
    public String getOwner()
    {
        return owner;
    }

    /**
     * Describes the stage the field is in.
     * Like if it has been hoed, planted or is empty.
     */
    public enum FieldStage
    {
        EMPTY,
        HOED,
        PLANTED
    }
}

 

GuiField:

/**
* Class which creates the GUI of our field inventory.
*/
@SideOnly(Side.CLIENT)
public class GuiField extends GuiContainer
{
    /**
     * The resource location of the GUI background.
     */
    private static final ResourceLocation TEXTURE = new ResourceLocation(Constants.MOD_ID, "textures/gui/scarecrow.png");

    /**
     * Constructor of the GUI.
     *
     * @param parInventoryPlayer the player inventory.
     * @param tileEntity         the tileEntity of the field, contains the inventory.
     * @param world              the world the field is in.
     * @param location           the location the field is at.
     */
    protected GuiField(InventoryPlayer parInventoryPlayer, ScarecrowTileEntity tileEntity, World world, BlockPos location)
    {
        super(new Field(tileEntity, parInventoryPlayer, world, location));
    }

    /**
     * Does draw the background of the GUI.
     *
     * @param partialTicks the ticks delivered.
     * @param mouseX       the mouseX position.
     * @param mouseY       the mouseY position.
     */
    @Override
    protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY)
    {
        GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
        mc.getTextureManager().bindTexture(TEXTURE);
        final int marginHorizontal = (width - xSize) / 2;
        final int marginVertical = (height - ySize) / 2;
        drawTexturedModalRect(marginHorizontal, marginVertical, 0, 0, xSize, ySize);
    }
}

 

Gui Handler:

/**
* Class which handles the GUI inventory.
*/
public class GuiHandler implements IGuiHandler
{
    @Override
    public Object getServerGuiElement(int id, EntityPlayer player, World world, int x, int y, int z)
    {
        final BlockPos            pos        = new BlockPos(x,y,z);
        final ScarecrowTileEntity tileEntity = (ScarecrowTileEntity) world.getTileEntity(pos);
        return new Field(tileEntity, player.inventory, world, pos);
    }

    @Override
    public Object getClientGuiElement(int id, EntityPlayer player, World world, int x, int y, int z)
    {
        final BlockPos            pos        = new BlockPos(x,y,z);
        final ScarecrowTileEntity tileEntity = (ScarecrowTileEntity) world.getTileEntity(pos);
        return new GuiField(player.inventory, tileEntity, world, pos);
    }
}

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.