Jump to content

Backpacks with IItemHandler


fr3qu3ncy

Recommended Posts

Hey! So, following:

I want to create backpacks that open when you right click with my custom item.

This is in my custom item class:

    @Nullable
    @Override
    public ICapabilityProvider initCapabilities(ItemStack stack, @Nullable CompoundTag nbt) {
        ItemStackHandler itemHandler = new ItemStackHandler(27);
        return ChestItemProvider.from(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, () -> itemHandler);
    }

This is my ChestItemProvider:

public class ChestItemProvider implements ICapabilityProvider {

    private final Capability<IItemHandler> capability;
    private final LazyOptional<IItemHandler> implementation;

    public ChestItemProvider(Capability<IItemHandler> capability, LazyOptional<IItemHandler> implementation) {
        this.capability = capability;
        this.implementation = implementation;
    }

    public static ChestItemProvider from(Capability<IItemHandler> cap, NonNullSupplier<IItemHandler> impl) {
        return new ChestItemProvider(cap, LazyOptional.of(impl));
    }

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

So, a few questions:

Is this implementation correct to this point?

How do I open a gui with IItemHandler and how do I save the changed contents?

This is what I have now:

    @SubscribeEvent
    public void onRightClick(PlayerInteractEvent.RightClickItem event) {
        if (!(event.getItemStack().is(this))) return;
        if (event.getSide() == LogicalSide.CLIENT) return;

        ItemStack item = event.getItemStack();
        ServerPlayer player = (ServerPlayer) event.getPlayer();
        LazyOptional<IItemHandler> cap = item.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY);
        if (cap.isPresent()) {
            NetworkHooks.openGui(((ServerPlayer) event.getPlayer()),
                    new SimpleMenuProvider((windowId, playerInventory, playerEntity) ->
                            ChestMenu.threeRows(1, new Inventory(player)), new TextComponent("Test")));
        }
    }

But this just opens a blank inventory, I could copy the IItemHandler's content to a new Inventory instance, but is this really the way you do it?

Link to comment
Share on other sites

14 minutes ago, diesieben07 said:

Implement INBTSerializable on your ICapabilityProvider.

Can I use the ItemStackHandler's serialization like this?

public class ChestItemProvider implements ICapabilityProvider, INBTSerializable<CompoundTag> {

    private final Capability<IItemHandler> capability;
    private final LazyOptional<IItemHandler> implementation;

    public ChestItemProvider(Capability<IItemHandler> capability, LazyOptional<IItemHandler> implementation) {
        this.capability = capability;
        this.implementation = implementation;
    }

    public static ChestItemProvider from(Capability<IItemHandler> cap, NonNullSupplier<IItemHandler> impl) {
        return new ChestItemProvider(cap, LazyOptional.of(impl));
    }

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

    @Override
    public CompoundTag serializeNBT() {
        AtomicReference<CompoundTag> tag = new AtomicReference<>(new CompoundTag());
        implementation.resolve().ifPresent(itemHandler -> {
            tag.set(((ItemStackHandler) itemHandler).serializeNBT());
        });
        return tag.get();
    }

    @Override
    public void deserializeNBT(CompoundTag nbt) {
        implementation.resolve().ifPresent(itemHandler -> {
            ((ItemStackHandler) itemHandler).deserializeNBT(nbt);
        });
    }
}

 

Link to comment
Share on other sites

36 minutes ago, diesieben07 said:

You need to create and register a custom MenuType and register it like any other registry entry. Use IForgeMenuType for this.

Like this?

public class ChestItemMenu implements IForgeMenuType<ChestMenu> {

    private static final MenuType<ChestMenu> CHEST_ITEM_MENU = register("chest_item_menu", ChestMenu::threeRows);

    private static <T extends AbstractContainerMenu> MenuType<T> register(String p_39989_, MenuType.MenuSupplier<T> p_39990_) {
        return Registry.register(Registry.MENU, p_39989_, new MenuType<>(p_39990_));
    }

    @Override
    public ChestMenu create(int windowId, Inventory playerInv, FriendlyByteBuf extraData) {
        return ChestMenu.threeRows(windowId, playerInv);
    }
}

 

Link to comment
Share on other sites

Okay, so this is my code now:

public class CIContainer extends AbstractContainerMenu {

    public final IItemHandler handler;

    public static CIContainer fromNetwork(final int windowId, final Inventory playerInventory, FriendlyByteBuf data) {
        return new CIContainer(windowId, playerInventory, new ItemStackHandler(27));
    }

    public CIContainer(final int windowId, final Inventory playerInventory, IItemHandler handler) {
        super(BannedTools.CI_CONTAINER.get(), windowId);

        this.handler = handler;

        addPlayerSlots(playerInventory);
        addMySlots();
    }

    private void addPlayerSlots(Inventory playerInventory) {
        int originX = 7;
        int originY = 67;

        //Hotbar
        for (int col = 0; col < 9; col++) {
            int x = originX + col * 18;
            int y = originY + 58;
            this.addSlot(new Slot(playerInventory, col, x+1, y+1));
        }

        //Player Inventory
        for (int row = 0; row < 3; row++) {
            for (int col = 0; col < 9; col++) {
                int x = originX + col * 18;
                int y = originY + row * 18;
                int index = (col + row * 9) + 9;
                this.addSlot(new Slot(playerInventory, index, x+1, y+1));
            }
        }
    }

    private void addMySlots() {
        if (this.handler == null) return;

        int cols = 9;
        int rows = 3;

        int slot_index = 0;

        for (int row = 0; row < rows; row++) {
            for (int col = 0; col < cols; col++) {
                int x = 7 + col * 18;
                int y = 17 + row * 18;

                this.addSlot(new SlotItemHandler(this.handler, slot_index, x + 1, y + 1));
                slot_index++;
                if (slot_index >= 27)
                    break;
            }
        }

    }

    @Override
    public void clicked(int slot, int dragType, ClickType clickTypeIn, Player player) {
        getSlot(slot).container.setChanged();
        super.clicked(slot, dragType, clickTypeIn, player);
    }

    @Override
    public boolean stillValid(Player player) {
        return true;
    }

    @Override
    @Nonnull
    public ItemStack quickMoveStack(@Nonnull Player playerIn, int index) {
        ItemStack itemstack = ItemStack.EMPTY;
        Slot slot = this.slots.get(index);

        if (slot.hasItem()) {
            int bagslotcount = this.slots.size();
            ItemStack itemstack1 = slot.getItem();
            itemstack = itemstack1.copy();
            if (index < playerIn.getInventory().items.size()) {
                if (!this.moveItemStackTo(itemstack1, playerIn.getInventory().items.size(), bagslotcount, false))
                    return ItemStack.EMPTY;
            } else if (!this.moveItemStackTo(itemstack1, 0, playerIn.getInventory().items.size(), false)) {
                return ItemStack.EMPTY;
            }
            if (itemstack1.isEmpty()) slot.set(ItemStack.EMPTY); else slot.setChanged();
        }
        return itemstack;
    }
}

Registering:

    private static final DeferredRegister<MenuType<?>> CONTAINERS = DeferredRegister.create(ForgeRegistries.CONTAINERS, MODID);

    public static final RegistryObject<MenuType<CIContainer>> CI_CONTAINER = CONTAINERS.register("ci_container", () -> IForgeMenuType.create(CIContainer::fromNetwork));

And this is how I open the inventory:

    @SubscribeEvent
    public void onRightClick(PlayerInteractEvent.RightClickItem event) {
        if (!(event.getItemStack().is(this))) return;
        if (event.getSide() == LogicalSide.CLIENT) return;
        ItemStack item = event.getItemStack();
        ServerPlayer player = (ServerPlayer) event.getPlayer();
        LazyOptional<IItemHandler> cap = item.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY);
        if (cap.isPresent()) {
            IItemHandler itemHandler = cap.resolve().get();
            NetworkHooks.openGui(player,
                    new SimpleMenuProvider( (windowId, playerInventory, playerEntity) ->
                            new CIContainer(windowId, playerInventory, itemHandler), new TextComponent("Test")));
        }
    }

openGui() is executed, but nothing happens.

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

    • As a seasoned investor, I’ve learned that the financial world can be exciting and treacherous. My experiences with investments have taught me the importance of diligence and thorough research, particularly when dealing with newer and high-risk assets like Bitcoin. Unfortunately, my journey with Bitcoin was marred by a painful lesson in the form of a scam, which I hope to share to help others avoid similar pitfalls. My introduction to Bitcoin investing seemed promising. The allure of high returns and the buzz surrounding cryptocurrency were captivating. I was drawn to several Bitcoin investment platforms that promised substantial profits. These platforms presented themselves with professional websites, attractive promotions, and genuine testimonials. I was led to believe that these sites were reliable and that I was making a sound investment. However, this trust proved to be misplaced. The platform I initially invested in showcased fake success stories and substantial profits to entice investors. They used these fabricated examples to build credibility and persuade new investors like me to commit more funds. Their tactics were sophisticated; they knew exactly how to create an illusion of success and security. I, too, was lured by their promises and gradually invested a considerable amount of money, totaling 68,000 USD.The initial investments went smoothly. My account appeared to grow with impressive returns, and I felt a sense of validation in my investment strategy. But things took a drastic turn when I decided to make a more significant investment, believing that the returns would only get better. Once I deposited a substantial sum, the platform’s behavior changed abruptly. My account was frozen without warning, and I was faced with a barrage of demands for additional payments before I could access my funds or the supposed profits. The situation was both distressing and bewildering. I was met with excuses and obstructions at every turn. It became clear that I was dealing with a fraudulent company that had no intention of honoring its commitments. The realization that I had been deceived was crushing. The emotional and financial toll of the situation was overwhelming. Determined to recover my funds, I reached out to Trust Geeks Hack Expert, a service recommended by a trusted friend who had faced a similar ordeal. My initial skepticism was tempered by desperation and hope. Trust Geeks Hack Expert took immediate action. Their team worked tirelessly to investigate the fraudulent platform and recover my lost funds. Their dedication and expertise were evident throughout the process. In just a few weeks, Trust Geeks Hack Expert managed to successfully retrieve the full amount of 68,000 USD. Their assistance was thorough and professional, and they kept me informed every step of the way. Their efforts not only resulted in the recovery of my funds but also provided me with invaluable insights into how these scams operate. This. This experience has been a harsh lesson in the importance of conducting thorough research before investing in any platform, particularly in the cryptocurrency space. The allure of high returns can be overwhelming, but it’s crucial to approach such investments with caution. Verify the legitimacy of the platform, seek out reviews from reliable sources, and ensure that any investment opportunity has a track record of transparency and reliability. To anyone who finds themselves in a similar predicament, I cannot recommend Trust Geeks Hack Expert  enough. Their professionalism and commitment to recovering my funds were exemplary:: E>mail: trustgeekshackexpert {@} fastservice{.}com -----> Tele>gram : Trustgeekshackexpert, And also  What's>App   + 1-7-1-9-4-9-2-2-6-9-3
    • As a seasoned investor, I’ve learned that the financial world can be exciting and treacherous. My experiences with investments have taught me the importance of diligence and thorough research, particularly when dealing with newer and high-risk assets like Bitcoin. Unfortunately, my journey with Bitcoin was marred by a painful lesson in the form of a scam, which I hope to share to help others avoid similar pitfalls. My introduction to Bitcoin investing seemed promising. The allure of high returns and the buzz surrounding cryptocurrency were captivating. I was drawn to several Bitcoin investment platforms that promised substantial profits. These platforms presented themselves with professional websites, attractive promotions, and genuine testimonials. I was led to believe that these sites were reliable and that I was making a sound investment. However, this trust proved to be misplaced. The platform I initially invested in showcased fake success stories and substantial profits to entice investors. They used these fabricated examples to build credibility and persuade new investors like me to commit more funds. Their tactics were sophisticated; they knew exactly how to create an illusion of success and security. I, too, was lured by their promises and gradually invested a considerable amount of money, totaling 68,000 USD.The initial investments went smoothly. My account appeared to grow with impressive returns, and I felt a sense of validation in my investment strategy. But things took a drastic turn when I decided to make a more significant investment, believing that the returns would only get better. Once I deposited a substantial sum, the platform’s behavior changed abruptly. My account was frozen without warning, and I was faced with a barrage of demands for additional payments before I could access my funds or the supposed profits. The situation was both distressing and bewildering. I was met with excuses and obstructions at every turn. It became clear that I was dealing with a fraudulent company that had no intention of honoring its commitments. The realization that I had been deceived was crushing. The emotional and financial toll of the situation was overwhelming. Determined to recover my funds, I reached out to Trust Geeks Hack Expert, a service recommended by a trusted friend who had faced a similar ordeal. My initial skepticism was tempered by desperation and hope. Trust Geeks Hack Expert took immediate action. Their team worked tirelessly to investigate the fraudulent platform and recover my lost funds. Their dedication and expertise were evident throughout the process. In just a few weeks, Trust Geeks Hack Expert managed to successfully retrieve the full amount of 68,000 USD. Their assistance was thorough and professional, and they kept me informed every step of the way. Their efforts not only resulted in the recovery of my funds but also provided me with invaluable insights into how these scams operate. This. This experience has been a harsh lesson in the importance of conducting thorough research before investing in any platform, particularly in the cryptocurrency space. The allure of high returns can be overwhelming, but it’s crucial to approach such investments with caution. Verify the legitimacy of the platform, seek out reviews from reliable sources, and ensure that any investment opportunity has a track record of transparency and reliability. To anyone who finds themselves in a similar predicament, I cannot recommend Trust Geeks Hack Expert  enough. Their professionalism and commitment to recovering my funds were exemplary:: E>mail: trustgeekshackexpert{@}fastservice{.}com -----> Tele>gram : Trustgeekshackexpert, And also  What's>App   + 1-7-1-9-4-9-2-2-6-9-3
    • I've been playing it for only 1 day and it doesn't want to go into the game anymore. I've tried reinstalling the game and repairing the game files (on curseforge) but it still doesn't work. Whenever i try to click on the Singleplayer icon, it just flickers into the world creation page and flickers back 
    • https://gist.github.com/RealMangoBot/03ce10d60ce10f126dcf2c033c3a4f46  
  • Topics

  • Who's Online (See full list)

    • There are no registered users currently online
×
×
  • Create New...

Important Information

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