Jump to content

[1.11.2]Gui not rendering item icons when opened from Item, but does when opened from block


Recommended Posts

Posted

Hello everyone!

I'm having yet another problem :(

Here's how it goes : 
I have a block, with a TileEntity and a GUI that is a vendor. It shows 9 items at once, which you can click to select and then buy.
The GUI is also open-able with an item, to benefit from remote access to the vendor.

Here's the problem :

When I open my GUI via the block :
wnIPBoC.png

When I open the GUI via the item : 
N4cYzem.png

However, in both cases, I can click on the slots to select the items, which means that the items ARE put in the slot in both GUIs, but they're not drawn on the item version.

I have tried disabling the render of the background image in case the items were, for some reason, behind the background, and they are not.

Here's the GUI code :

 

package com.gugu42.rcmod.client.gui;

import java.io.IOException;

import org.lwjgl.opengl.GL11;

import com.gugu42.rcmod.ContainerVendor;
import com.gugu42.rcmod.RcMod;
import com.gugu42.rcmod.capabilities.bolt.BoltProvider;
import com.gugu42.rcmod.capabilities.bolt.IBolt;
import com.gugu42.rcmod.items.EnumRcWeapons;
import com.gugu42.rcmod.items.InventoryGadgetronPDA;
import com.gugu42.rcmod.items.ItemRcWeap;
import com.gugu42.rcmod.network.packets.PacketRefill;
import com.gugu42.rcmod.network.packets.PacketVend;
import com.gugu42.rcmod.tileentity.TileEntityVendor;

import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.resources.I18n;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Slot;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.SoundEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

@SideOnly(Side.CLIENT)
public class GuiVendor extends GuiContainer {

	private static final ResourceLocation texturepath = new ResourceLocation(
			"rcmod", "textures/gui/vendor_new.png");

	private static final ResourceLocation boltTexturePath = new ResourceLocation(
			"rcmod", "textures/gui/bolt.png");

	private GuiButton buyBtn;
	private GuiButton exitBtn;

	private EnumRcWeapons weapons;

	private EntityPlayer player;
	private TileEntityVendor tileEntity;
	private ContainerVendor container;
	private Minecraft mc;

	private int selectedWeapon = -1;
	private int mouseX, mouseY;

	private ItemStack selectedItem;
	private ItemRcWeap selectedItemWeap;
	private EntityItem selectedItemEntity;

	public float rotation;

	public int weaponIndex = 1;

	public int lastID = 0;
	public int centerID = 1;
	private long timeOfLastAction;

	public GuiVendor(InventoryPlayer inventoryPlayer,
			TileEntityVendor tileEntity, EntityPlayer player,
			ContainerVendor container, InventoryGadgetronPDA inv) {
		super(new ContainerVendor(inventoryPlayer, tileEntity, inv));
		this.player = player;
		this.tileEntity = tileEntity;
		this.container = container;
		this.mc = Minecraft.getMinecraft();

		this.xSize = 256;
		this.ySize = 190;
	}

	@Override
	public void initGui() {
		super.initGui();
		int posX = (this.width - xSize) / 2;
		int posY = (this.height - ySize) / 2;
		this.buttonList.clear();
		this.buttonList.add(this.buyBtn = new GuiButton(0, posX + 41,
				posY + 137, 35, 20, I18n.format("gui.vendor.buy")));
		this.buttonList.add(this.exitBtn = new GuiButton(1, posX + 181,
				posY + 137, 35, 20, I18n.format("gui.vendor.exit")));
		timeOfLastAction = System.currentTimeMillis();
	}

	@Override
	public void updateScreen() {
		putItemsInSlot();
		
		//If the player idles on the gui, the vendor will say "Come on buddy I ain't got all day" or "Sooo... you gonna buy some or what ?" randomly
		if(System.currentTimeMillis() - timeOfLastAction >= 15000)
		{
			mc.player.playSound(new SoundEvent(new ResourceLocation("rcmod:vendor.speech.wait")), 1.0f, 1.0f);
			timeOfLastAction = System.currentTimeMillis();
		}
	}

	public void handleSelectedWeapon() {

		if (selectedItemEntity != null) {
			selectedItemEntity.rotationYaw = 0;
			selectedItemEntity.hoverStart = 0;

			GL11.glPushMatrix();
			GL11.glMatrixMode(GL11.GL_PROJECTION);
			GL11.glMatrixMode(GL11.GL_MODELVIEW);

			GL11.glTranslatef(xSize - 200, ySize - 92, 100);

			GL11.glScalef(-60f, 60f, 60f);

			GL11.glRotatef(180, 0, 0, 1);
			GL11.glRotatef(rotation, 0, 1, 0);

			RenderHelper.enableStandardItemLighting();

			if (selectedWeapon >= 0 && selectedItem != null)
				Minecraft.getMinecraft().getRenderManager().doRenderEntity(selectedItemEntity, 0, -0.23, 0, 0, 0, false);
			RenderHelper.disableStandardItemLighting();

			GL11.glPopMatrix();

			rotation -= 1f;

			if (getItemInInventory(player.inventory, selectedItem.getItem()) == ItemStack.EMPTY) {
				this.mc.fontRendererObj.drawString(
						""
								+ EnumRcWeapons.getPriceFromItem(selectedItem
										.getItem()), 30, 105, 0xFFFFFF);
				this.buyBtn.displayString = I18n.format("gui.vendor.buy");
			} else {
				this.mc.fontRendererObj.drawString(
						""
								+ getItemInInventory(player.inventory,
										selectedItem.getItem()).getItemDamage()
								* selectedItemWeap.getPrice(), 30, 105,
						0xFFFFFF);
				this.buyBtn.displayString = I18n.format("gui.vendor.refill");
			}
			this.buyBtn.enabled = true;

			GL11.glPushMatrix();
			GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
			GL11.glDisable(GL11.GL_LIGHTING);
			this.mc.getTextureManager().bindTexture(boltTexturePath);
			GL11.glEnable(GL11.GL_BLEND);
			GL11.glDisable(GL11.GL_DEPTH_TEST);
			GL11.glDepthMask(false);
			GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
			GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
			GL11.glDisable(GL11.GL_ALPHA_TEST);
			//drawTexturedQuadFit(xSize - 185, ySize - 86, 8, 8, 0);
			drawModalRectWithCustomSizedTexture(xSize - 185, ySize - 86, 0, 0, 8, 8, 64, 64);
			GL11.glEnable(GL11.GL_DEPTH_TEST);
			GL11.glDepthMask(true);
			GL11.glPopMatrix();
		} else {
			this.buyBtn.enabled = false;
		}
	}

	public void putItemsInSlot() {
		for (int i = 0; i < 9; i++) {
			if (EnumRcWeapons.getItemFromID(centerID + i) != null) {
				this.container.putStackInSlot(i, new ItemStack(EnumRcWeapons
						.getItemFromID(centerID + i).getWeapon()));
				lastID = i;
			} else {
				if (EnumRcWeapons.getItemFromID(i - lastID) != null) {
					this.container.putStackInSlot(
							i,
							new ItemStack(EnumRcWeapons.getItemFromID(
									i - lastID).getWeapon()));
				}
			}
		}
	}

	@Override
	public void mouseClicked(int par1, int par2, int par3) throws IOException {
		super.mouseClicked(par1, par2, par3);
		for (int i = 0; i < 9; i++) {
			if (isMouseOverSlot(container.getSlot(i), mouseX, mouseY)) {
				selectedWeapon = i;

				selectedItem = container.getSlot(i).getStack();

				if (selectedItem != null) {
					selectedItemEntity = new EntityItem(this.mc.world, 0, 0,
							0, selectedItem);

					selectedItemWeap = (ItemRcWeap) selectedItem.getItem();
				}
				mc.player.playSound(new SoundEvent(new ResourceLocation("rcmod:MenuSelect")), 1.0f, 1.0f);

				weaponIndex = weaponIndex + i;
				centerID = EnumRcWeapons.getIDFromItem(selectedItemWeap);
				timeOfLastAction = System.currentTimeMillis();
				//When clicking a weapon, will occassionally say "Oh that's a nice one" or "That's a real beauty"
				if(mc.world.rand.nextInt(10) == 5)
					mc.player.playSound(new SoundEvent(new ResourceLocation("rcmod:vendor.speech.weapclicked")), 1.0f, 1.0f);
			} else {
				//ok you can happen if you want, but not too much pls
			}
		}
	}

	@Override
	public void actionPerformed(GuiButton button) {
		switch (button.id) {
		case 0:
			if (getItemInInventory(player.inventory, selectedItem.getItem()) == ItemStack.EMPTY) {
				IBolt props = player.getCapability(BoltProvider.BOLT_CAP, null);
				if (props.getCurrentBolt() > 0) {
					try {
						PacketVend packetVend = new PacketVend(centerID);
						RcMod.rcModPacketHandler.sendToServer(packetVend);
					} catch (Exception exception) {
						exception.printStackTrace();
					}
				}
			} else {
				ItemRcWeap weap = (ItemRcWeap) selectedItem.getItem();
				if (weap.useAmmo) {
					PacketRefill packet = new PacketRefill(centerID);
					RcMod.rcModPacketHandler.sendToServer(packet);
				}
			}
			break;
		case 1:
			mc.player.playSound(new SoundEvent(new ResourceLocation("rcmod:vendor.exit")), 1.0f, 1.0f);
			player.closeScreen();
			break;
		default:
			break;
		}
	}

	public boolean doesGuiPauseGame() {
		return false;
	}

	protected void drawGuiContainerForegroundLayer(int par1, int par2) {
		mouseX = par1;
		mouseY = par2;
		handleSelectedWeapon();
		if (selectedItemEntity != null) { //Using this check to be sure that there is an item selecred, cuz that works.
			this.mc.fontRendererObj.drawString(
					EnumRcWeapons.getItemFromID(centerID).getName(), 108, 16,
					0x00FF00);
		}

	}

	@Override
	protected void drawGuiContainerBackgroundLayer(float par1, int par2,
			int par3) {
		GL11.glEnable(GL11.GL_BLEND);
		GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
		this.mc.renderEngine.bindTexture(texturepath);
		int x = (width - xSize) / 2;
		int y = (height - ySize) / 2;
		this.drawTexturedModalRect(x, y, 0, 0, 256, 256);
		GL11.glDisable(GL11.GL_BLEND);
	}

	private boolean isMouseOverSlot(Slot par1Slot, int par2, int par3) {
		return this.isPointInRegion(par1Slot.xPos,
				par1Slot.yPos, 16, 16, par2, par3);

	}

	private int getSlotContainingItem(InventoryPlayer inventory, Item item) {
		for (int i = 0; i < inventory.mainInventory.size(); ++i) {
			if (inventory.mainInventory.get(i) != ItemStack.EMPTY
					&& inventory.mainInventory.get(i).getItem() == item) {
				return i;
			}
		}

		return -1;
	}

	public ItemStack getItemInInventory(InventoryPlayer inventory,
			Item p_146026_1_) {
		int i = this.getSlotContainingItem(inventory, p_146026_1_);

		if (i < 0) {
			return ItemStack.EMPTY;
		} else {
			return inventory.mainInventory.get(i);
		}
	}

}



If any other code is needed, be sure to ask.

Please note that this problem is not specific to 1.11.2 since I also had it back in 1.7.10

 

Posted

Alright.

Container :
 

  Reveal hidden contents

GuiHandler :

  Reveal hidden contents

Item :

  Reveal hidden contents

Block :

  Reveal hidden contents

 

 

Some of the code is dirty, sorry

Posted

I don't need to save the content of the item's inventory (it is set when you open it), do I still need capabilities ? As far as I understand, those are meant to store data right ?

Posted

After converting to IItemHandler (only changing the Inventory class), I don't seem to get any changes from it.
I mostly do not understand why it works with the block, and not with the item.

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

    • The specific issue is that items in my inventory wont stack properly. For instance, if I punch a tree down to collect wood, the first block I collected goes to my hand. So when I punch the second block of wood to collect it, it drops, but instead of stacking with the piece of wood already in my hand, it goes to the second slot in my hotbar instead. Another example is that I'll get some dirt, and then when I'm placing it down later I'll accidentally place a block where I don't want it. When I harvest it again, it doesn't go back to the stack that it came from on my hotbar, where it should have gone, but rather into my inventory. That means that if my inventory is full, then the dirt wont be picked up even though there should be space available in the stack I'm holding. The forge version I'm using is 40.3.0, for java 1.18.2. I'll leave the mods I'm using here, and I'd appreciate it if anybody can point me in the right direction in regards to figuring out how to fix this. I forgot to mention that I think it only happens on my server but I&#39;m not entirely sure. PLEASE HELP ME! LIST OF THE MODS. aaa_particles Adorn AdvancementPlaques AI-Improvements AkashicTome alexsdelight alexsmobs AmbientSounds amwplushies Animalistic another_furniture AppleSkin Aquaculture aquamirae architectury artifacts Atlas-Lib AutoLeveling AutoRegLib auudio balm betterfpsdist biggerstacks biomancy BiomesOPlenty blockui blueprint Bookshelf born_in_chaos Botania braincell BrassAmberBattleTowers brutalbosses camera CasinoCraft cfm (MrCrayfish’s Furniture Mod) chat_heads citadel cloth-config Clumps CMDCam CNB cobweb collective comforts convenientcurioscontainer cookingforblockheads coroutil CosmeticArmorReworked CozyHome CrabbersDelight crashexploitfixer crashutilities Create CreativeCore creeperoverhaul cristellib crittersandcompanions Croptopia CroptopiaAdditions CullLessLeaves curios curiouslanterns curiouslights Curses' Naturals CustomNPCs CyclopsCore dannys_expansion decocraft Decoration Mod DecorationDelightRefurbished Decorative Blocks Disenchanting DistantHorizons doubledoors DramaticDoors drippyloadingscreen durabilitytooltip dynamic-fps dynamiclights DynamicTrees DynamicTreesBOP DynamicTreesPlus Easy Dungeons EasyAnvils EasyMagic easy_npc eatinganimation ecologics effective_fg elevatorid embeddium emotecraft enchantlimiter EnchantmentDescriptions EnderMail engineersdecor entityculling entity_model_features entity_texture_features epicfight EvilCraft exlinefurniture expandability explosiveenhancement factory-blocks fairylights fancymenu FancyVideo FarmersDelight fast-ip-ping FastSuite ferritecore finsandtails FixMySpawnR Forge Middle Ages fossil FpsReducer2 furnish GamingDeco geckolib goblintraders goldenfood goodall H.e.b habitat harvest-with-ease hexerei hole_filler huge-structure-blocks HunterIllager iammusicplayer Iceberg illuminations immersive_paintings incubation infinitybuttons inventoryhud InventoryProfilesNext invocore ItemBorders itemzoom Jade jei (Just Enough Items) JetAndEliasArmors journeymap JRFTL justzoom kiwiboi Kobolds konkrete kotlinforforge lazydfu LegendaryTooltips libIPN lightspeed lmft lodestone LongNbtKiller LuckPerms Lucky77 MagmaMonsters malum ManyIdeasCore ManyIdeasDoors marbledsarsenal marg mcw-furniture mcw-lights mcw-paths mcw-stairs mcw-trapdoors mcw-windows meetyourfight melody memoryleakfix Mimic minecraft-comes-alive MineTraps minibosses MmmMmmMmmMmm MOAdecor (ART, BATH, COOKERY, GARDEN, HOLIDAYS, LIGHTS, SCIENCE) MobCatcher modonomicon mods_optimizer morehitboxes mowziesmobs MutantMonsters mysticalworld naturalist NaturesAura neapolitan NekosEnchantedBooks neoncraft2 nerb nifty NightConfigFixes nightlights nocube's_villagers_sell_animals NoSeeNoTick notenoughanimations obscure_api oculus oresabovediamonds otyacraftengine Paraglider Patchouli physics-mod Pillagers Gun PizzaCraft placeableitems Placebo player-animation-lib pneumaticcraft-repressurized polymorph PrettyPipes Prism projectbrazier Psychadelic-Chemistry PuzzlesLib realmrpg_imps_and_demons RecipesLibrary reeves-furniture RegionsUnexplored restrictedportals revive-me Scary_Mobs_And_Bosses selene shetiphiancore ShoulderSurfing smoothboot
    • Hi everyone, I'm currently developing a Forge 1.21 mod for Minecraft and I want to display a custom HUD overlay for a minigame. My goal: When the game starts, all players should see an item/block icon (from the base game, not a custom texture) plus its name/text in the HUD – similar to how the bossbar overlay works. The HUD should appear centered above the hotbar (or at a similar prominent spot), and update dynamically (icon and name change as the target item changes). What I've tried: I looked at many online tutorials and several GitHub repos (e.g. SeasonHUD, MiniHUD), but most of them use NeoForge or Forge versions <1.20 that provide the IGuiOverlay API (e.g. implements IGuiOverlay, RegisterGuiOverlaysEvent). In Forge 1.21, it seems that neither IGuiOverlay nor RegisterGuiOverlaysEvent exist anymore – at least, I can't import them and they are missing from the docs and code completion. I tried using RenderLevelStageEvent as a workaround but it is probably not intended for custom HUDs. I am not using NeoForge, and switching the project to NeoForge is currently not an option for me. I tried to look at the original minecraft source code to see how elements like hearts, hotbar etc are drawn on the screen but I am too new to Minecraft modding to understand. What I'm looking for: What is the correct way to add a custom HUD element (icon + text) in Forge 1.21, given that the previous overlay API is missing? Is there a new recommended event, callback, or method in Forge 1.21 for custom HUD overlays, or is everyone just using a workaround? Is there a minimal open-source example repo for Forge 1.21 that demonstrates a working HUD overlay without relying on NeoForge or deprecated Forge APIs? My ideal solution: Centered HUD element with an in-game item/block icon (from the base game's assets, e.g. a diamond or any ItemStack / Item) and its name as text, with a transparent background rectangle. It should be visible to the players when the mini game is running. Easy to update the item (e.g. static variable or other method), so it can change dynamically during the game. Any help, code snippets, or up-to-date references would be really appreciated! If this is simply not possible right now in Forge 1.21, it would also help to know that for sure. Thank you very much in advance!
    • The simple answer is there is not an easy way. You would need to know how to program in Java, as well as at least some familiarity with how Forge works so you could port the differences. You would also need the sourcecode for the original mod, and permission from the author to modify it, if they did not use some sort of open source license. So it's not impossible, but it would take some effort, but doing so would open up a whole new world of possibilities for you!
    • Does it still crash if you remove holdmyitems? Looks like that mod doesn't work on a server as far as I can tell from the error.  
  • 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.