Jump to content

[SOLVED][1.10.2] Gui open when the event is cancelled


JimiIT92

Recommended Posts

I have a block that when right-clicked will open a GUI, but only if the player has some requirements. I've managed how to check this requirements using the PlayerInteractEvent (since all the stuff i have to control is stored server side but the gui is client side so that checks will fail), but if it turns that the player can't open the gui i get a chat message that warn the player but the gui still opens. Here is a picture of what i mean
wzLqEak.png
In this case the player was not allowed to open the GUI, infact there is a chat message that says that. But the GUI is opened too. So how can i prevent the GUI to open? This is my block code

 
	package com.cf.blocks;
	import java.util.Random;
	import javax.annotation.Nullable;
	import com.cf.CoreFaction;
import com.cf.entities.TileEntityBuyer;
import com.cf.entities.TileEntityCore;
import com.cf.faction.Faction;
import com.cf.faction.Territory;
import com.cf.proxy.GuiHandler;
import com.cf.utils.TerritoryUtils;
import com.cf.utils.Utils;
	import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.EnumPushReaction;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.EnumBlockRenderType;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.world.Explosion;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
	public class BlockCore extends BlockContainer {
	    public BlockCore() {
        super(Material.IRON);
        this.setCreativeTab(CreativeTabs.MISC);
        this.setHardness(100.0F);
        this.setResistance(2000.0F);
    }
	    public EnumBlockRenderType getRenderType(IBlockState state) {
        return EnumBlockRenderType.MODEL;
    }
	    @SideOnly(Side.CLIENT)
    public BlockRenderLayer getBlockLayer() {
        return BlockRenderLayer.CUTOUT_MIPPED;
    }
	    public boolean isOpaqueCube(IBlockState state) {
        return false;
    }
	    public boolean isFullCube(IBlockState state) {
        return false;
    }
	    @Override
    public EnumPushReaction getMobilityFlag(IBlockState state) {
        return EnumPushReaction.BLOCK;
    }
	    @SideOnly(Side.CLIENT)
    public void randomDisplayTick(IBlockState stateIn, World worldIn, BlockPos pos, Random rand) {
        for (int i = 0; i < 1; ++i) {
            int j = rand.nextInt(2) * 2 - 1;
            int k = rand.nextInt(2) * 2 - 1;
            double d0 = (double) pos.getX() + 0.5D + 0.25D * (double) j;
            double d1 = (double) ((float) pos.getY() + rand.nextFloat());
            double d2 = (double) pos.getZ() + 0.5D + 0.25D * (double) k;
	            worldIn.spawnParticle(EnumParticleTypes.END_ROD, d0, d1, d2, rand.nextGaussian() * 0.003D,
                    rand.nextGaussian() * 0.003D, rand.nextGaussian() * 0.003D, new int[0]);
        }
    }
	    /**
     * Returns the quantity of items to drop on block destruction.
     */
    public int quantityDropped(Random random) {
        return 0;
    }
	    /**
     * Get the Item that this Block should drop when harvested.
     */
    @Nullable
    public Item getItemDropped(IBlockState state, Random rand, int fortune) {
        return null;
    }
	    @Override
    public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn,
            EnumHand hand, ItemStack heldItem, EnumFacing side, float hitX, float hitY, float hitZ) {
        if(worldIn.isRemote)
            playerIn.openGui(CoreFaction.INSTANCE, GuiHandler.CORE_GUI_ID, worldIn, pos.getX(), pos.getY(), pos.getZ());
        return worldIn.isRemote;
    }
	    @Override
    public void onBlockDestroyedByExplosion(World worldIn, BlockPos pos, Explosion explosionIn) {
        // TODO
        super.onBlockDestroyedByExplosion(worldIn, pos, explosionIn);
    }
	    @Override
    public void onBlockDestroyedByPlayer(World worldIn, BlockPos pos, IBlockState state) {
        // TODO
        super.onBlockDestroyedByPlayer(worldIn, pos, state);
    }
	    @Override
    public TileEntity createNewTileEntity(World worldIn, int meta) {
        return new TileEntityCore();
    }
	    @Override
    public void onBlockAdded(World worldIn, BlockPos pos, IBlockState state) {
        if (!worldIn.isRemote) {
            TileEntity te = worldIn.getTileEntity(pos);
            if (te != null && te instanceof TileEntityCore) {
                Territory t = TerritoryUtils.getTerritoryByPos(pos, worldIn.provider.getDimension());
                if (t != null) {
                    Faction f = TerritoryUtils.getFaction(t);
                    if (f != null) {
                        ((TileEntityCore) te).setName(f.getName());
                        ((TileEntityCore) te).setOpen(false);
                    }
                }
            }
        }
    }
}



This is the PlayerInteractEvent

 
	package com.cf.events;
	import com.cf.blocks.BlockCore;
import com.cf.core.CFBlocks;
import com.cf.faction.Faction;
import com.cf.faction.Territory;
import com.cf.utils.FactionUtils;
import com.cf.utils.TerritoryUtils;
import com.cf.utils.Utils;
	import net.minecraft.block.Block;
import net.minecraft.block.BlockBrewingStand;
import net.minecraft.block.BlockButton;
import net.minecraft.block.BlockChest;
import net.minecraft.block.BlockDispenser;
import net.minecraft.block.BlockDoor;
import net.minecraft.block.BlockDropper;
import net.minecraft.block.BlockFenceGate;
import net.minecraft.block.BlockFurnace;
import net.minecraft.block.BlockHopper;
import net.minecraft.block.BlockLever;
import net.minecraft.block.BlockNote;
import net.minecraft.block.BlockRedstoneComparator;
import net.minecraft.block.BlockRedstoneRepeater;
import net.minecraft.block.BlockTrapDoor;
import net.minecraft.init.Blocks;
import net.minecraft.util.text.TextFormatting;
import net.minecraftforge.client.event.GuiOpenEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
	public class EventBlockInteract {
    @SubscribeEvent
    public void onInteract(PlayerInteractEvent.RightClickBlock event) {
        Territory t = TerritoryUtils.getTerritoryByPos(event.getPos(), event.getEntityPlayer().dimension);
        if (t != null) {
            Faction f = TerritoryUtils.getFaction(t);
            if (event.getWorld().getBlockState(event.getPos()).getBlock() == CFBlocks.core) {
                if (f == null)
                    event.setCanceled(true);
                else if (f.getMembers().contains(event.getEntityPlayer().getUniqueID())) {
                    if(!f.getOwner().equals(event.getEntityPlayer().getUniqueID())) {
                        event.setCanceled(true);
                        Utils.sendMessage(event.getEntityPlayer(),
                                Utils.getTranslation("block.core.nopermission", TextFormatting.RED));
                    }
                } else {
                    event.setCanceled(true);
                    Utils.sendMessage(event.getEntityPlayer(),
                            Utils.getTranslation("block.core.fail", TextFormatting.RED)); //THIS IS THE CHAT MESSAGE THAT APPEARS IN THE IMAGE
                }
            }
        }
    }
}


This is my GuiHandler

 
	package com.cf.proxy;
	import com.cf.entities.TileEntityCore;
import com.cf.gui.GuiCore;
	import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.network.IGuiHandler;
	public class GuiHandler implements IGuiHandler {
	    public static int CORE_GUI_ID = 0;
    
    @Override
    public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
        return null;
    }
	    @Override
    public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
        if(ID == CORE_GUI_ID) {
            BlockPos pos = new BlockPos(x, y, z);
            TileEntity tileEntity = world.getTileEntity(pos);
            if(tileEntity instanceof TileEntityCore) {
                return new GuiCore((TileEntityCore)tileEntity);
            }
        }
        return null;
    }
}


and this is how i register it in the ClientProxy 

public void init() {
        NetworkRegistry.INSTANCE.registerGuiHandler(CoreFaction.INSTANCE, new GuiHandler());
    }
Edited by JimiIT92

Don't blame me if i always ask for your help. I just want to learn to be better :)

Link to comment
Share on other sites

You need to have something like this:

1. On block activation the client sends a packet to the server.

2. The server checks what it needs to check, and sends a reply packet with the results.

3. The client receives the packet and either opens the gui, or tells the player that the permission was denied.

Link to comment
Share on other sites

Why don't you just do

if(!world.isRemote){
	playerIn.displayGui(new YourGui);
}

that will also work if you move your registration of the guiHandler to your common registration. You will have access to all server variable as well, no need for packets. The best answer is usually the simplest, don't make more out of this than it is.

Edited by draganz
Link to comment
Share on other sites

2 minutes ago, draganz said:

Why don't you just do


if(!world.isRemote){
	playerIn.displayGui(new YourGui);
}

that will also work if you move your registration of the guiHandler to your common registration. You will have access to all server variable as well, no need for packets. 

Good job not reading the thread. He can't do this client-side-only because he needs to know if the user is ALLOWED TO OPEN IT which is information only the server has.

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Link to comment
Share on other sites

2 minutes ago, Draco18s said:

Good job not reading the thread. He can't do this client-side-only because he needs to know if the user is ALLOWED TO OPEN IT which is information only the server has.

I can't also do that call because i'll need to implement IInteractionObject into my GUI, wich is not what i want since is just a simple GUI with no inventory or container

Don't blame me if i always ask for your help. I just want to learn to be better :)

Link to comment
Share on other sites

OOO, I see, typo on my part, sorry, don't do player.displayGui, do player.openGui, still do the check of !world.isRemote, though. Just make sure your guihandler has been registered via the common (both server and client). Sorry about that, slight typo.

 

Edited by draganz
Link to comment
Share on other sites

So i should just send a message (via SimpleNetworkWrapper) to the client with all the necessary informations (taken from the server) and inside the message decide if open the Gui or not?

Don't blame me if i always ask for your help. I just want to learn to be better :)

Link to comment
Share on other sites

Ok, so i send a message from the onBlockActivated method to the server, but server crash with this error

[00:10:31] [Server thread/ERROR] [FML]: FMLIndexedMessageCodec exception caught
java.lang.RuntimeException: Missing
    at net.minecraftforge.fml.server.FMLServerHandler.getClientToServerNetworkManager(FMLServerHandler.java:281) ~[FMLServerHandler.class:?]
    at net.minecraftforge.fml.common.FMLCommonHandler.getClientToServerNetworkManager(FMLCommonHandler.java:545) ~[FMLCommonHandler.class:?]
    at net.minecraftforge.fml.common.network.FMLOutboundHandler$OutboundTarget$8.selectNetworks(FMLOutboundHandler.java:245) ~[FMLOutboundHandler$OutboundTarget$8.class:?]
    at net.minecraftforge.fml.common.network.FMLOutboundHandler.write(FMLOutboundHandler.java:293) ~[FMLOutboundHandler.class:?]
    at io.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:658) ~[AbstractChannelHandlerContext.class:4.0.23.Final]
    at io.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:716) ~[AbstractChannelHandlerContext.class:4.0.23.Final]
    at io.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:651) ~[AbstractChannelHandlerContext.class:4.0.23.Final]
    at io.netty.handler.codec.MessageToMessageEncoder.write(MessageToMessageEncoder.java:112) ~[MessageToMessageEncoder.class:4.0.23.Final]
    at io.netty.handler.codec.MessageToMessageCodec.write(MessageToMessageCodec.java:116) ~[MessageToMessageCodec.class:4.0.23.Final]
    at io.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:658) ~[AbstractChannelHandlerContext.class:4.0.23.Final]
    at io.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:716) ~[AbstractChannelHandlerContext.class:4.0.23.Final]
    at io.netty.channel.AbstractChannelHandlerContext.writeAndFlush(AbstractChannelHandlerContext.java:706) ~[AbstractChannelHandlerContext.class:4.0.23.Final]
    at io.netty.channel.AbstractChannelHandlerContext.writeAndFlush(AbstractChannelHandlerContext.java:741) ~[AbstractChannelHandlerContext.class:4.0.23.Final]
    at io.netty.channel.DefaultChannelPipeline.writeAndFlush(DefaultChannelPipeline.java:895) ~[DefaultChannelPipeline.class:4.0.23.Final]
    at io.netty.channel.AbstractChannel.writeAndFlush(AbstractChannel.java:240) ~[AbstractChannel.class:4.0.23.Final]
    at net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper.sendToServer(SimpleNetworkWrapper.java:294) [SimpleNetworkWrapper.class:?]
    at com.cf.blocks.BlockCore.onBlockActivated(BlockCore.java:105) [BlockCore.class:?]
    at net.minecraft.server.management.PlayerInteractionManager.processRightClickBlock(PlayerInteractionManager.java:477) [PlayerInteractionManager.class:?]
    at net.minecraft.network.NetHandlerPlayServer.processRightClickBlock(NetHandlerPlayServer.java:706) [NetHandlerPlayServer.class:?]
    at net.minecraft.network.play.client.CPacketPlayerTryUseItemOnBlock.processPacket(CPacketPlayerTryUseItemOnBlock.java:68) [CPacketPlayerTryUseItemOnBlock.class:?]
    at net.minecraft.network.play.client.CPacketPlayerTryUseItemOnBlock.processPacket(CPacketPlayerTryUseItemOnBlock.java:13) [CPacketPlayerTryUseItemOnBlock.class:?]
    at net.minecraft.network.PacketThreadUtil$1.run(PacketThreadUtil.java:21) [PacketThreadUtil$1.class:?]
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) [?:1.8.0_131]
    at java.util.concurrent.FutureTask.run(Unknown Source) [?:1.8.0_131]
    at net.minecraft.util.Util.runTask(Util.java:28) [Util.class:?]
    at net.minecraft.server.MinecraftServer.updateTimeLightAndEntities(MinecraftServer.java:743) [MinecraftServer.class:?]
    at net.minecraft.server.dedicated.DedicatedServer.updateTimeLightAndEntities(DedicatedServer.java:408) [DedicatedServer.class:?]
    at net.minecraft.server.MinecraftServer.tick(MinecraftServer.java:688) [MinecraftServer.class:?]
    at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:537) [MinecraftServer.class:?]
    at java.lang.Thread.run(Unknown Source) [?:1.8.0_131]



This is the message class

 
	package com.cf.network;
	import com.cf.CoreFaction;
import com.cf.faction.Faction;
import com.cf.faction.Territory;
import com.cf.utils.TerritoryUtils;
	import io.netty.buffer.ByteBuf;
import net.minecraft.util.IThreadListener;
import net.minecraftforge.fml.common.network.ByteBufUtils;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
	public class GuiCoreServerMessage implements IMessage{
	    private String name;
	    public GuiCoreServerMessage() {
        
    }
    
    public GuiCoreServerMessage(String n) {
        this.name = n;
    }
    
    @Override
    public void fromBytes(ByteBuf buf) {
        this.name = ByteBufUtils.readUTF8String(buf);
    }
	    @Override
    public void toBytes(ByteBuf buf) {
        ByteBufUtils.writeUTF8String(buf, name);
    }
    
    public static class Handler implements IMessageHandler<GuiCoreServerMessage, IMessage> {
        @Override
        public IMessage onMessage(final GuiCoreServerMessage message, final MessageContext ctx) {
            IThreadListener mainThread = CoreFaction.PROXY.getListener(ctx);
            mainThread.addScheduledTask(new Runnable() {
                @Override
                public void run() {
                    Territory t = TerritoryUtils.getTerritoryByName(message.name);
                    if(t != null) {
                        Faction f = TerritoryUtils.getFaction(t);
                        if(f != null)
                            System.out.println(f.getName());
                    }
                    
                }
            });
            return null;
        }
        
    }
}



This is how i register the message and the channel

public static SimpleNetworkWrapper NETWORK;
    
    @EventHandler
    public void preInit(FMLPreInitializationEvent event) {
        NETWORK = NetworkRegistry.INSTANCE.newSimpleChannel(MODID);
        NETWORK.registerMessage(GuiCoreServerMessage.Handler.class, GuiCoreServerMessage.class, 0, Side.SERVER);
}



and this is how i send the message from the block

@Override
    public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn,
            EnumHand hand, ItemStack heldItem, EnumFacing side, float hitX, float hitY, float hitZ) {
        if(!worldIn.isRemote) {
            TileEntity te = worldIn.getTileEntity(pos);
            if(te instanceof TileEntityCore) {
                CoreFaction.NETWORK.sendToServer(new GuiCoreServerMessage(((TileEntityCore)te).getName()));
            }
        }
        return true;
    }



What am i missing? :/

Don't blame me if i always ask for your help. I just want to learn to be better :)

Link to comment
Share on other sites

Woops, my bad xD Changed that and now it sends the message, hope everything works as intended now :)
EDIT: Yes, it works now, thanks everybody for your help :)

Edited by JimiIT92

Don't blame me if i always ask for your help. I just want to learn to be better :)

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.



×
×
  • Create New...

Important Information

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