Jump to content

[1.7.2] - Sending data from a gui to the server [Solved]


AppliedOnce

Recommended Posts

Hi, I'm currently working on a project and got into a small problem. I try to change a value that is saved in the player using the ExtendedEntityProperties stuff, inside a gui. The only I am having is that the way I am doing it, I only change the values on the client side which makes a lot of problems. So I was wondering how I can fix this problem, is there something missing in my packet or something or do I need a new one?

 

Here is all the classes I am using for it:

 

Mod class:

 

package com.xetosphere.pantheon.entity;

import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import net.minecraftforge.common.IExtendedEntityProperties;

import com.xetosphere.pantheon.PantheonCraft;
import com.xetosphere.pantheon.lib.Reference;
import com.xetosphere.pantheon.network.packet.SyncPlayerPropsPacket;
import com.xetosphere.pantheon.proxy.CommonProxy;

public class ExtendedPlayer implements IExtendedEntityProperties {

public static final String IDENTIFIER = Reference.MOD_ID + "_properties";

private final EntityPlayer player;

private int culture, maxCulture, pantheonId;

private String pantheon;

public static final int CULTURE_WATCHER = 25;
public static final int PANTHEON_WATCHER = 26;
public static final int ID_WATCHER = 27;

public ExtendedPlayer(EntityPlayer player) {

	this.player = player;
	culture = 0;
	maxCulture = 1000;
	pantheon = "None";
	pantheonId = 1;
	player.getDataWatcher().addObject(CULTURE_WATCHER, culture);
	player.getDataWatcher().addObject(PANTHEON_WATCHER, pantheon);
	player.getDataWatcher().addObject(ID_WATCHER, pantheonId);
}

public static final void register(EntityPlayer player) {

	player.registerExtendedProperties(IDENTIFIER, new ExtendedPlayer(player));
}

public static final ExtendedPlayer get(EntityPlayer player) {

	return (ExtendedPlayer) player.getExtendedProperties(IDENTIFIER);
}

@Override
public void saveNBTData(NBTTagCompound compound) {

	NBTTagCompound properties = new NBTTagCompound();
	properties.setInteger("Culture", player.getDataWatcher().getWatchableObjectInt(CULTURE_WATCHER));
	properties.setInteger("MaxCulture", maxCulture);
	properties.setString("Pantheon", player.getDataWatcher().getWatchableObjectString(PANTHEON_WATCHER));
	properties.setInteger("IdPantheon", player.getDataWatcher().getWatchableObjectInt(ID_WATCHER));
	compound.setTag(IDENTIFIER, properties);
}

@Override
public void loadNBTData(NBTTagCompound compound) {

	NBTTagCompound properties = (NBTTagCompound) compound.getTag(IDENTIFIER);
	player.getDataWatcher().updateObject(CULTURE_WATCHER, properties.getInteger("Culture"));
	maxCulture = properties.getInteger("MaxCulture");
	player.getDataWatcher().updateObject(PANTHEON_WATCHER, properties.getString("Pantheon"));
	player.getDataWatcher().updateObject(ID_WATCHER, properties.getInteger("IdPantheon"));
	System.out.println("[XETOPC PROPS] Culture from NBT: " + player.getDataWatcher().getWatchableObjectInt(CULTURE_WATCHER) + "/" + maxCulture);
	System.out.println("[XETOPC PROPS] Pantheon from NBT: [iD = " + player.getDataWatcher().getWatchableObjectInt(ID_WATCHER) + "] " + player.getDataWatcher().getWatchableObjectString(PANTHEON_WATCHER));
}

@Override
public void init(Entity entity, World world) {
}

public final boolean consumeCulture(int amount) {
	boolean sufficient = amount <= getCulture();
	setCulture(getCulture() - amount);
	return sufficient;
}

public final int getCulture() {

	return player.getDataWatcher().getWatchableObjectInt(CULTURE_WATCHER);
}

public final String getPantheon() {

	return player.getDataWatcher().getWatchableObjectString(PANTHEON_WATCHER);
}

public final int getPantheonId() {

	return player.getDataWatcher().getWatchableObjectInt(ID_WATCHER);
}

public final void setCulture(int amount) {

	player.getDataWatcher().updateObject(CULTURE_WATCHER, amount > 0 ? (amount < maxCulture ? amount : maxCulture) : 0);
}

public final void setPantheon(String pantheon) {

	player.getDataWatcher().updateObject(PANTHEON_WATCHER, pantheon);
}

public final void setPantheonId(int id) {

	player.getDataWatcher().updateObject(ID_WATCHER, id);
}

public final int getMaxCulture() {

	return maxCulture;
}

public final void setMaxCulture(int amount) {

	maxCulture = (amount > 0 ? amount : 0);
	PantheonCraft.packetPipeline.sendTo(new SyncPlayerPropsPacket(player), (EntityPlayerMP) player);
}

private static final String getSaveKey(EntityPlayer player) {

	return player.getCommandSenderName() + ":" + IDENTIFIER;
}

public static final void saveProxyData(EntityPlayer player) {

	NBTTagCompound savedData = new NBTTagCompound();
	ExtendedPlayer.get(player).saveNBTData(savedData);
	CommonProxy.storeEntityData(getSaveKey(player), savedData);
}

public static final void loadProxyData(EntityPlayer player) {

	ExtendedPlayer playerData = ExtendedPlayer.get(player);
	NBTTagCompound savedData = CommonProxy.getEntityData(getSaveKey(player));
	if (savedData != null) {
		playerData.loadNBTData(savedData);
	}

	PantheonCraft.packetPipeline.sendTo(new SyncPlayerPropsPacket(player), (EntityPlayerMP) player);
}

}

 

 

 

ItemTalisman class:

 

package com.xetosphere.pantheon.item;

import net.minecraft.entity.effect.EntityLightningBolt;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.MovingObjectPosition.MovingObjectType;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;

import org.lwjgl.input.Keyboard;

import com.xetosphere.pantheon.PantheonCraft;
import com.xetosphere.pantheon.entity.ExtendedPlayer;
import com.xetosphere.pantheon.lib.GuiIds;

public class ItemTalisman extends ItemPC {

public ItemTalisman() {

}

public ItemTalisman(EntityPlayer player) {

}

public ItemStack onItemRightClick(ItemStack itemStack, World world, EntityPlayer player) {

	String pantheon = ExtendedPlayer.get(player).getPantheon();

	final double EYE_HEIGHT = 1.62;
	final double REACH_DISTANCE = 300;

	Vec3 startPos = player.getPosition(1.0F);

	if (!world.isRemote) startPos = startPos.addVector(0, EYE_HEIGHT, 0);

	Vec3 look = player.getLook(1.0F);
	Vec3 endPos = startPos.addVector(look.xCoord * REACH_DISTANCE, look.yCoord * REACH_DISTANCE, look.zCoord * REACH_DISTANCE);

	MovingObjectPosition objectMouseOver = world.rayTraceBlocks(startPos, endPos);

	if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) {

		if (world.isRemote) {

			player.openGui(PantheonCraft.instance, GuiIds.RELIGION_GUI, world, (int) player.posX, (int) player.posY, (int) player.posZ);
		}

	}

	// TODO Greek
	if (pantheon.equals("Greek") && !Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) {

		if (ExtendedPlayer.get(player).getCulture() >= 100 && objectMouseOver != null && objectMouseOver.typeOfHit == MovingObjectType.BLOCK) {

			ExtendedPlayer.get(player).consumeCulture(100);

			int i = objectMouseOver.blockX;
			int j = objectMouseOver.blockY;
			int k = objectMouseOver.blockZ;

			player.addChatComponentMessage(new ChatComponentText("This is ran. Greek"));

			world.spawnEntityInWorld(new EntityLightningBolt(world, i, j, k));

		} else {

			if (!world.isRemote) {

				player.addChatComponentMessage(new ChatComponentText("You don't have enough culture."));
				ExtendedPlayer.get(player).setCulture(100);
			}
		}
	}

	// TODO Norse
	if (pantheon.equals("Norse") && !Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) {

		if (ExtendedPlayer.get(player).getCulture() >= 100) {

			ExtendedPlayer.get(player).consumeCulture(100);
			player.addPotionEffect(new PotionEffect(Potion.moveSpeed.id, 2400, 0, false));
			player.addChatComponentMessage(new ChatComponentText("This is ran. Norse"));

		} else {

			if (!world.isRemote) {

				player.addChatComponentMessage(new ChatComponentText("You don't have enough culture."));
				ExtendedPlayer.get(player).setCulture(100);
			}
		}
	}

	// TODO Roman
	if (pantheon.equals("Roman") && !Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) {

		if (ExtendedPlayer.get(player).getCulture() >= 100 && objectMouseOver != null && objectMouseOver.typeOfHit == MovingObjectType.BLOCK) {
			ExtendedPlayer.get(player).consumeCulture(100);

			int i = objectMouseOver.blockX;
			int j = objectMouseOver.blockY;
			int k = objectMouseOver.blockZ;
			player.addChatComponentMessage(new ChatComponentText("This is ran. Roman"));

			if (!world.isRemote) world.createExplosion(player, i, j, k, 5, true);

		} else {

			if (!world.isRemote) {

				player.addChatComponentMessage(new ChatComponentText("You don't have enough culture."));
				ExtendedPlayer.get(player).setCulture(100);
			}
		}
	}

	// TODO Egyptian
	if (pantheon.equals("Egyptian") && !Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) {

		if (ExtendedPlayer.get(player).getCulture() >= 100) {

			ExtendedPlayer.get(player).consumeCulture(100);
			player.addPotionEffect(new PotionEffect(Potion.nightVision.id, 2400, 0, false));
			player.addChatComponentMessage(new ChatComponentText("This is ran. Egyptian"));

		} else {

			if (!world.isRemote) {

				player.addChatComponentMessage(new ChatComponentText("You don't have enough culture."));
				ExtendedPlayer.get(player).setCulture(100);
			}
		}
	}

	return itemStack;
}
}

 

 

 

GuiReligion class:

 

package com.xetosphere.pantheon.client.gui;

import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.ChatComponentText;

import org.lwjgl.opengl.GL11;

import com.xetosphere.pantheon.entity.ExtendedPlayer;
import com.xetosphere.pantheon.lib.Textures;

public class GuiReligion extends GuiScreen {

private int xSize = 176;

private int ySize = 166;

EntityPlayer player;

private String[] pantheons = { "None", "Greek", "Norse", "Roman", "Egyptian" };

public GuiReligion(EntityPlayer player) {

	this.player = player;
}

public void updateScreen() {
	super.updateScreen();
}

public void drawScreen(int x, int y, float f) {

	drawDefaultBackground();

	GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);

	mc.getTextureManager().bindTexture(Textures.GUI_RELIGION);

	int posX = (width - xSize) / 2;
	int posY = (height - ySize) / 2;

	drawTexturedModalRect(posX, posY, 0, 0, xSize, ySize);
	drawCenteredString(fontRendererObj, ExtendedPlayer.get(player).getPantheon(), posX + (xSize / 4 * 3), posY + 15, 0xffffffff);

	super.drawScreen(x, y, f);
}

public boolean doesGuiPauseGame() {

	return false;
}

@SuppressWarnings("unchecked")
public void initGui() {

	this.buttonList.clear();

	int posX = (width - xSize) / 2;
	int posY = (height - ySize) / 2;

	this.buttonList.add(new GuiButton(0, posX + 10, posY + 10, 50, 20, pantheons[0]));
	this.buttonList.add(new GuiButton(1, posX + 10, posY + 40, 50, 20, pantheons[1]));
	this.buttonList.add(new GuiButton(2, posX + 10, posY + 70, 50, 20, pantheons[2]));
	this.buttonList.add(new GuiButton(3, posX + 10, posY + 100, 50, 20, pantheons[3]));
	this.buttonList.add(new GuiButton(4, posX + 10, posY + 130, 50, 20, pantheons[4]));
}

public void actionPerformed(GuiButton button) {

	switch (button.id) {
		case 0:
			ExtendedPlayer.get(player).setPantheon(pantheons[0]);
			ExtendedPlayer.get(player).setPantheonId(0);
			System.out.println("[XETOPC] Pantheon = " + ExtendedPlayer.get(player).getPantheon());
			System.out.println("[XETOPC] PantheonId = " + ExtendedPlayer.get(player).getPantheonId());
			player.addChatComponentMessage(new ChatComponentText("You set your pantheon to: " + ExtendedPlayer.get(player).getPantheon()));
			break;
		case 1:
			ExtendedPlayer.get(player).setPantheon(pantheons[1]);
			ExtendedPlayer.get(player).setPantheonId(1);
			System.out.println("[XETOPC] Pantheon = " + ExtendedPlayer.get(player).getPantheon());
			System.out.println("[XETOPC] PantheonId = " + ExtendedPlayer.get(player).getPantheonId());
			player.addChatComponentMessage(new ChatComponentText("You set your pantheon to: " + ExtendedPlayer.get(player).getPantheon()));
			break;
		case 2:
			ExtendedPlayer.get(player).setPantheon(pantheons[2]);
			ExtendedPlayer.get(player).setPantheonId(2);
			System.out.println("[XETOPC] Pantheon = " + ExtendedPlayer.get(player).getPantheon());
			System.out.println("[XETOPC] PantheonId = " + ExtendedPlayer.get(player).getPantheonId());
			player.addChatComponentMessage(new ChatComponentText("You set your pantheon to: " + ExtendedPlayer.get(player).getPantheon()));
			break;
		case 3:
			ExtendedPlayer.get(player).setPantheon(pantheons[3]);
			ExtendedPlayer.get(player).setPantheonId(3);
			System.out.println("[XETOPC] Pantheon = " + ExtendedPlayer.get(player).getPantheon());
			System.out.println("[XETOPC] PantheonId = " + ExtendedPlayer.get(player).getPantheonId());
			player.addChatComponentMessage(new ChatComponentText("You set your pantheon to: " + ExtendedPlayer.get(player).getPantheon()));
			break;
		case 4:
			ExtendedPlayer.get(player).setPantheon(pantheons[4]);
			ExtendedPlayer.get(player).setPantheonId(4);
			System.out.println("[XETOPC] Pantheon = " + ExtendedPlayer.get(player).getPantheon());
			System.out.println("[XETOPC] PantheonId = " + ExtendedPlayer.get(player).getPantheonId());
			player.addChatComponentMessage(new ChatComponentText("You set your pantheon to: " + ExtendedPlayer.get(player).getPantheon()));
			break;
	}
}
}

 

 

 

PacketPipeline class:

 

package com.xetosphere.pantheon.network;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;

import java.util.Collections;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.LinkedList;
import java.util.List;

import com.xetosphere.pantheon.lib.Reference;
import com.xetosphere.pantheon.network.packet.SyncPlayerPropsPacket;

import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.INetHandler;
import net.minecraft.network.NetHandlerPlayServer;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.network.FMLEmbeddedChannel;
import cpw.mods.fml.common.network.FMLOutboundHandler;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.network.internal.FMLProxyPacket;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;

@ChannelHandler.Sharable
public class PacketPipeline extends MessageToMessageCodec<FMLProxyPacket, AbstractPacket> {

private EnumMap<Side, FMLEmbeddedChannel> channels;
private LinkedList<Class<? extends AbstractPacket>> packets = new LinkedList<Class<? extends AbstractPacket>>();
private boolean isPostInitialised = false;

public boolean registerPacket(Class<? extends AbstractPacket> clazz) {

	if (this.packets.size() > 256) {

		return false;
	}

	if (this.packets.contains(clazz)) {

		return false;
	}

	if (this.isPostInitialised) {

		return false;
	}

	this.packets.add(clazz);
	return true;
}

protected void encode(ChannelHandlerContext ctx, AbstractPacket msg, List<Object> out) throws Exception {

	ByteBuf buffer = Unpooled.buffer();
	Class<? extends AbstractPacket> clazz = msg.getClass();

	if (!this.packets.contains(msg.getClass())) {

		throw new NullPointerException("No Packet Registered for: " + msg.getClass().getCanonicalName());
	}

	byte discriminator = (byte) this.packets.indexOf(clazz);
	buffer.writeByte(discriminator);
	msg.encodeInto(ctx, buffer);
	FMLProxyPacket proxyPacket = new FMLProxyPacket(buffer.copy(), ctx.channel().attr(NetworkRegistry.FML_CHANNEL).get());
	out.add(proxyPacket);
}

@Override
protected void decode(ChannelHandlerContext ctx, FMLProxyPacket msg, List<Object> out) throws Exception {

	ByteBuf payload = msg.payload();
	byte discriminator = payload.readByte();
	Class<? extends AbstractPacket> clazz = this.packets.get(discriminator);

	if (clazz == null) {

		throw new NullPointerException("No packet registered for discriminator: " + discriminator);
	}

	AbstractPacket pkt = clazz.newInstance();
	pkt.decodeInto(ctx, payload.slice());

	EntityPlayer player;
	switch (FMLCommonHandler.instance().getEffectiveSide()) {
		case CLIENT:
			player = this.getClientPlayer();
			pkt.handleClientSide(player);
			break;

		case SERVER:
			INetHandler netHandler = ctx.channel().attr(NetworkRegistry.NET_HANDLER).get();
			player = ((NetHandlerPlayServer) netHandler).playerEntity;
			pkt.handleServerSide(player);
			break;

		default:
	}

	out.add(pkt);
}

public void initialise() {

	this.channels = NetworkRegistry.INSTANCE.newChannel(Reference.MOD_ID, this);
	registerPackets();
}

public void registerPackets() {

	registerPacket(SyncPlayerPropsPacket.class);
}

public void postInitialise() {

	if (this.isPostInitialised) {

		return;
	}

	this.isPostInitialised = true;
	Collections.sort(this.packets, new Comparator<Class<? extends AbstractPacket>>() {

		@Override
		public int compare(Class<? extends AbstractPacket> clazz1, Class<? extends AbstractPacket> clazz2) {

			int com = String.CASE_INSENSITIVE_ORDER.compare(clazz1.getCanonicalName(), clazz2.getCanonicalName());

			if (com == 0) {

				com = clazz1.getCanonicalName().compareTo(clazz2.getCanonicalName());
			}

			return com;
		}
	});
}

@SideOnly(Side.CLIENT)
private EntityPlayer getClientPlayer() {

	return Minecraft.getMinecraft().thePlayer;
}

public void sendToAll(AbstractPacket message) {

	this.channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.ALL);
	this.channels.get(Side.SERVER).writeAndFlush(message);
}

public void sendTo(AbstractPacket message, EntityPlayerMP player) {

	this.channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.PLAYER);
	this.channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(player);
	this.channels.get(Side.SERVER).writeAndFlush(message);
}

public void sendToAllAround(AbstractPacket message, NetworkRegistry.TargetPoint point) {

	this.channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.ALLAROUNDPOINT);
	this.channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(point);
	this.channels.get(Side.SERVER).writeAndFlush(message);
}

public void sendToDimension(AbstractPacket message, int dimensionId) {

	this.channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.DIMENSION);
	this.channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(dimensionId);
	this.channels.get(Side.SERVER).writeAndFlush(message);
}

public void sendToServer(AbstractPacket message) {

	this.channels.get(Side.CLIENT).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.TOSERVER);
	this.channels.get(Side.CLIENT).writeAndFlush(message);
}
}

 

 

 

SyncPlayerPropsPacket class:

 

package com.xetosphere.pantheon.network.packet;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;

import com.xetosphere.pantheon.entity.ExtendedPlayer;
import com.xetosphere.pantheon.network.AbstractPacket;

import cpw.mods.fml.common.network.ByteBufUtils;

public class SyncPlayerPropsPacket extends AbstractPacket {

private NBTTagCompound data;

public SyncPlayerPropsPacket() {
}

public SyncPlayerPropsPacket(EntityPlayer player) {

	data = new NBTTagCompound();
	ExtendedPlayer.get(player).saveNBTData(data);
}

@Override
public void encodeInto(ChannelHandlerContext ctx, ByteBuf buffer) {

	ByteBufUtils.writeTag(buffer, data);
}

@Override
public void decodeInto(ChannelHandlerContext ctx, ByteBuf buffer) {

	data = ByteBufUtils.readTag(buffer);
}

@Override
public void handleClientSide(EntityPlayer player) {

	ExtendedPlayer.get(player).loadNBTData(data);
}

@Override
public void handleServerSide(EntityPlayer player) {
}
}

 

 

 

CultureEventHandler class:

 

package com.xetosphere.pantheon.event;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraftforge.event.entity.EntityEvent.EntityConstructing;
import net.minecraftforge.event.entity.EntityJoinWorldEvent;
import net.minecraftforge.event.entity.living.LivingDeathEvent;

import com.xetosphere.pantheon.entity.ExtendedPlayer;

import cpw.mods.fml.common.eventhandler.SubscribeEvent;

public class CultureEventHandler {

@SubscribeEvent
public void onEntityConstructing(EntityConstructing event) {

	if (event.entity instanceof EntityPlayer) {

		if (ExtendedPlayer.get((EntityPlayer) event.entity) == null)

		ExtendedPlayer.register((EntityPlayer) event.entity);
	}
}

@SubscribeEvent
public void onEntityJoinWorld(EntityJoinWorldEvent event) {

	if (!event.entity.worldObj.isRemote && event.entity instanceof EntityPlayer) {

		ExtendedPlayer.loadProxyData((EntityPlayer) event.entity);
	}
}

@SubscribeEvent
public void onLivingDeathEvent(LivingDeathEvent event) {

	if (!event.entity.worldObj.isRemote && event.entity instanceof EntityPlayer) {

		ExtendedPlayer.saveProxyData((EntityPlayer) event.entity);
	}
}
}

 

 

 

CommonProxy class:

 

package com.xetosphere.pantheon.proxy;

import java.util.HashMap;
import java.util.Map;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;

import com.xetosphere.pantheon.client.gui.GuiReligion;
import com.xetosphere.pantheon.lib.GuiIds;

import cpw.mods.fml.common.network.IGuiHandler;

public class CommonProxy implements IGuiHandler {

private static final Map<String, NBTTagCompound> extendedEntityData = new HashMap<String, NBTTagCompound>();

public Object getServerGuiElement(int id, EntityPlayer player, World world, int x, int y, int z) {

	if (id == GuiIds.RELIGION_GUI) {

		return null;
	}

	return null;
}

public Object getClientGuiElement(int id, EntityPlayer player, World world, int x, int y, int z) {

	if (id == GuiIds.RELIGION_GUI) {

		return new GuiReligion(player);
	}

	return null;
}

public static void storeEntityData(String name, NBTTagCompound compound) {

	extendedEntityData.put(name, compound);
}

public static NBTTagCompound getEntityData(String name) {

	return extendedEntityData.remove(name);
}
}

 

 

 

ExtendedPlayer class:

 

package com.xetosphere.pantheon.entity;

import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import net.minecraftforge.common.IExtendedEntityProperties;

import com.xetosphere.pantheon.PantheonCraft;
import com.xetosphere.pantheon.lib.Reference;
import com.xetosphere.pantheon.network.packet.SyncPlayerPropsPacket;
import com.xetosphere.pantheon.proxy.CommonProxy;

public class ExtendedPlayer implements IExtendedEntityProperties {

public static final String IDENTIFIER = Reference.MOD_ID + "_properties";

private final EntityPlayer player;

private int culture, maxCulture, pantheonId;

private String pantheon;

public static final int CULTURE_WATCHER = 25;
public static final int PANTHEON_WATCHER = 26;
public static final int ID_WATCHER = 27;

public ExtendedPlayer(EntityPlayer player) {

	this.player = player;
	culture = 0;
	maxCulture = 1000;
	pantheon = "None";
	pantheonId = 1;
	player.getDataWatcher().addObject(CULTURE_WATCHER, culture);
	player.getDataWatcher().addObject(PANTHEON_WATCHER, pantheon);
	player.getDataWatcher().addObject(ID_WATCHER, pantheonId);
}

public static final void register(EntityPlayer player) {

	player.registerExtendedProperties(IDENTIFIER, new ExtendedPlayer(player));
}

public static final ExtendedPlayer get(EntityPlayer player) {

	return (ExtendedPlayer) player.getExtendedProperties(IDENTIFIER);
}

@Override
public void saveNBTData(NBTTagCompound compound) {

	NBTTagCompound properties = new NBTTagCompound();
	properties.setInteger("Culture", player.getDataWatcher().getWatchableObjectInt(CULTURE_WATCHER));
	properties.setInteger("MaxCulture", maxCulture);
	properties.setString("Pantheon", player.getDataWatcher().getWatchableObjectString(PANTHEON_WATCHER));
	properties.setInteger("IdPantheon", player.getDataWatcher().getWatchableObjectInt(ID_WATCHER));
	compound.setTag(IDENTIFIER, properties);
}

@Override
public void loadNBTData(NBTTagCompound compound) {

	NBTTagCompound properties = (NBTTagCompound) compound.getTag(IDENTIFIER);
	player.getDataWatcher().updateObject(CULTURE_WATCHER, properties.getInteger("Culture"));
	maxCulture = properties.getInteger("MaxCulture");
	player.getDataWatcher().updateObject(PANTHEON_WATCHER, properties.getString("Pantheon"));
	player.getDataWatcher().updateObject(ID_WATCHER, properties.getInteger("IdPantheon"));
	System.out.println("[XETOPC PROPS] Culture from NBT: " + player.getDataWatcher().getWatchableObjectInt(CULTURE_WATCHER) + "/" + maxCulture);
	System.out.println("[XETOPC PROPS] Pantheon from NBT: [iD = " + player.getDataWatcher().getWatchableObjectInt(ID_WATCHER) + "] " + player.getDataWatcher().getWatchableObjectString(PANTHEON_WATCHER));
}

@Override
public void init(Entity entity, World world) {
}

public final boolean consumeCulture(int amount) {
	boolean sufficient = amount <= getCulture();
	setCulture(getCulture() - amount);
	return sufficient;
}

public final int getCulture() {

	return player.getDataWatcher().getWatchableObjectInt(CULTURE_WATCHER);
}

public final String getPantheon() {

	return player.getDataWatcher().getWatchableObjectString(PANTHEON_WATCHER);
}

public final int getPantheonId() {

	return player.getDataWatcher().getWatchableObjectInt(ID_WATCHER);
}

public final void setCulture(int amount) {

	player.getDataWatcher().updateObject(CULTURE_WATCHER, amount > 0 ? (amount < maxCulture ? amount : maxCulture) : 0);
}

public final void setPantheon(String pantheon) {

	player.getDataWatcher().updateObject(PANTHEON_WATCHER, pantheon);
}

public final void setPantheonId(int id) {

	player.getDataWatcher().updateObject(ID_WATCHER, id);
}

public final int getMaxCulture() {

	return maxCulture;
}

public final void setMaxCulture(int amount) {

	maxCulture = (amount > 0 ? amount : 0);
	PantheonCraft.packetPipeline.sendTo(new SyncPlayerPropsPacket(player), (EntityPlayerMP) player);
}

private static final String getSaveKey(EntityPlayer player) {

	return player.getCommandSenderName() + ":" + IDENTIFIER;
}

public static final void saveProxyData(EntityPlayer player) {

	NBTTagCompound savedData = new NBTTagCompound();
	ExtendedPlayer.get(player).saveNBTData(savedData);
	CommonProxy.storeEntityData(getSaveKey(player), savedData);
}

public static final void loadProxyData(EntityPlayer player) {

	ExtendedPlayer playerData = ExtendedPlayer.get(player);
	NBTTagCompound savedData = CommonProxy.getEntityData(getSaveKey(player));
	if (savedData != null) {
		playerData.loadNBTData(savedData);
	}

	PantheonCraft.packetPipeline.sendTo(new SyncPlayerPropsPacket(player), (EntityPlayerMP) player);
}

}

 

 

Link to comment
Share on other sites

First, you're not using extended properties properly. Second, this code will register your Entity data with a null player. Reverse to == to != and it should fix one problem.

public void onEntityConstructing(EntityConstructing event) {
	if (event.entity instanceof EntityPlayer) {
		if (ExtendedPlayer.get((EntityPlayer) event.entity) == null)
		ExtendedPlayer.register((EntityPlayer) event.entity);
	}
}

 

Advice, the init() method is called when entity is created to set the initial properties for the entity. Yours does nothing. (maybe not critical, as the defaults are 0... in the case of objects it another story).

loadNBTData() and saveNBTData() are called on entity spawn (player spawn in this case), and on entity despawn. This is where the data in the ExtendedEntity itself is loaded and saved.

 

DataWatcher is nice only to the extent that it lets you know if the data has changed and communicates it to the other side immediately. However, you need to keep a valid copy in the data fields of this object. (So, when the datawatcher changes, you grab the data and update).

 

Beyond that, I have not looked closely enough to give you an absolute fix. I'll keep looking, though.

Link to comment
Share on other sites

First, you're not using extended properties properly. Second, this code will register your Entity data with a null player. Reverse to == to != and it should fix one problem.

public void onEntityConstructing(EntityConstructing event) {
	if (event.entity instanceof EntityPlayer) {
		if (ExtendedPlayer.get((EntityPlayer) event.entity) == null)
		ExtendedPlayer.register((EntityPlayer) event.entity);
	}
}

 

Advice, the init() method is called when entity is created to set the initial properties for the entity. Yours does nothing. (maybe not critical, as the defaults are 0... in the case of objects it another story).

loadNBTData() and saveNBTData() are called on entity spawn (player spawn in this case), and on entity despawn. This is where the data in the ExtendedEntity itself is loaded and saved.

 

DataWatcher is nice only to the extent that it lets you know if the data has changed and communicates it to the other side immediately. However, you need to keep a valid copy in the data fields of this object. (So, when the datawatcher changes, you grab the data and update).

 

Beyond that, I have not looked closely enough to give you an absolute fix. I'll keep looking, though.

No, I am pretty sure what that code does is, if the player haven't been registered yet then register it. Other than that thank you for replying and helping me out. (btw if I use != it just crashes when the player joins the world)
Link to comment
Share on other sites

Dude you have it as == the guy just said make it != and you say I can't make it == it crashes.

No, what I meant to say is that when I have it as "!=" it crashes when I open the world. I get a nullpointer exception when using "!=".

 

Crashlog:

 

[13:29:11] [server thread/INFO]: Xetosphere joined the game

[13:29:11] [server thread/ERROR] [FML]: HandshakeCompletionHandler exception

java.lang.NullPointerException

at com.xetosphere.pantheon.network.packet.SyncPlayerPropsPacket.<init>(SyncPlayerPropsPacket.java:23) ~[syncPlayerPropsPacket.class:?]

at com.xetosphere.pantheon.entity.ExtendedPlayer.loadProxyData(ExtendedPlayer.java:146) ~[ExtendedPlayer.class:?]

at com.xetosphere.pantheon.event.CultureEventHandler.onEntityJoinWorld(CultureEventHandler.java:30) ~[CultureEventHandler.class:?]

at cpw.mods.fml.common.eventhandler.ASMEventHandler_4_CultureEventHandler_onEntityJoinWorld_EntityJoinWorldEvent.invoke(.dynamic) ~[?:?]

at cpw.mods.fml.common.eventhandler.ASMEventHandler.invoke(ASMEventHandler.java:51) ~[ASMEventHandler.class:?]

at cpw.mods.fml.common.eventhandler.EventBus.post(EventBus.java:122) ~[EventBus.class:?]

at net.minecraft.world.World.spawnEntityInWorld(World.java:1516) ~[World.class:?]

at net.minecraft.server.management.ServerConfigurationManager.playerLoggedIn(ServerConfigurationManager.java:288) ~[serverConfigurationManager.class:?]

at net.minecraft.server.management.ServerConfigurationManager.initializeConnectionToPlayer(ServerConfigurationManager.java:151) ~[serverConfigurationManager.class:?]

at cpw.mods.fml.common.network.handshake.NetworkDispatcher.completeServerSideConnection(NetworkDispatcher.java:172) ~[NetworkDispatcher.class:?]

at cpw.mods.fml.common.network.handshake.NetworkDispatcher.completeHandshake(NetworkDispatcher.java:428) ~[NetworkDispatcher.class:?]

at cpw.mods.fml.common.network.internal.HandshakeCompletionHandler.channelRead0(HandshakeCompletionHandler.java:17) ~[HandshakeCompletionHandler.class:?]

at cpw.mods.fml.common.network.internal.HandshakeCompletionHandler.channelRead0(HandshakeCompletionHandler.java:11) ~[HandshakeCompletionHandler.class:?]

at io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:98) ~[simpleChannelInboundHandler.class:?]

at io.netty.channel.DefaultChannelHandlerContext.invokeChannelRead(DefaultChannelHandlerContext.java:337) [DefaultChannelHandlerContext.class:?]

at io.netty.channel.DefaultChannelHandlerContext.fireChannelRead(DefaultChannelHandlerContext.java:323) [DefaultChannelHandlerContext.class:?]

at io.netty.handler.codec.MessageToMessageDecoder.channelRead(MessageToMessageDecoder.java:103) [MessageToMessageDecoder.class:?]

at io.netty.handler.codec.MessageToMessageCodec.channelRead(MessageToMessageCodec.java:111) [MessageToMessageCodec.class:?]

at io.netty.channel.DefaultChannelHandlerContext.invokeChannelRead(DefaultChannelHandlerContext.java:337) [DefaultChannelHandlerContext.class:?]

at io.netty.channel.DefaultChannelHandlerContext.fireChannelRead(DefaultChannelHandlerContext.java:323) [DefaultChannelHandlerContext.class:?]

at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:785) [DefaultChannelPipeline.class:?]

at io.netty.channel.embedded.EmbeddedChannel.writeInbound(EmbeddedChannel.java:169) [EmbeddedChannel.class:?]

at cpw.mods.fml.common.network.internal.FMLProxyPacket.processPacket(FMLProxyPacket.java:80) [FMLProxyPacket.class:?]

at net.minecraft.network.NetworkManager.processReceivedPackets(NetworkManager.java:242) [NetworkManager.class:?]

at net.minecraft.network.NetworkSystem.networkTick(NetworkSystem.java:190) [NetworkSystem.class:?]

at net.minecraft.server.MinecraftServer.updateTimeLightAndEntities(MinecraftServer.java:763) [MinecraftServer.class:?]

at net.minecraft.server.MinecraftServer.tick(MinecraftServer.java:651) [MinecraftServer.class:?]

at net.minecraft.server.integrated.IntegratedServer.tick(IntegratedServer.java:120) [integratedServer.class:?]

at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:530) [MinecraftServer.class:?]

at net.minecraft.server.MinecraftServer$2.run(MinecraftServer.java:788) [MinecraftServer$2.class:?]

[13:29:11] [server thread/ERROR] [FML]: There was a critical exception handling a packet on channel FML

java.lang.NullPointerException

at com.xetosphere.pantheon.network.packet.SyncPlayerPropsPacket.<init>(SyncPlayerPropsPacket.java:23) ~[syncPlayerPropsPacket.class:?]

at com.xetosphere.pantheon.entity.ExtendedPlayer.loadProxyData(ExtendedPlayer.java:146) ~[ExtendedPlayer.class:?]

at com.xetosphere.pantheon.event.CultureEventHandler.onEntityJoinWorld(CultureEventHandler.java:30) ~[CultureEventHandler.class:?]

at cpw.mods.fml.common.eventhandler.ASMEventHandler_4_CultureEventHandler_onEntityJoinWorld_EntityJoinWorldEvent.invoke(.dynamic) ~[?:?]

at cpw.mods.fml.common.eventhandler.ASMEventHandler.invoke(ASMEventHandler.java:51) ~[ASMEventHandler.class:?]

at cpw.mods.fml.common.eventhandler.EventBus.post(EventBus.java:122) ~[EventBus.class:?]

at net.minecraft.world.World.spawnEntityInWorld(World.java:1516) ~[World.class:?]

at net.minecraft.server.management.ServerConfigurationManager.playerLoggedIn(ServerConfigurationManager.java:288) ~[serverConfigurationManager.class:?]

at net.minecraft.server.management.ServerConfigurationManager.initializeConnectionToPlayer(ServerConfigurationManager.java:151) ~[serverConfigurationManager.class:?]

at cpw.mods.fml.common.network.handshake.NetworkDispatcher.completeServerSideConnection(NetworkDispatcher.java:172) ~[NetworkDispatcher.class:?]

at cpw.mods.fml.common.network.handshake.NetworkDispatcher.completeHandshake(NetworkDispatcher.java:428) ~[NetworkDispatcher.class:?]

at cpw.mods.fml.common.network.internal.HandshakeCompletionHandler.channelRead0(HandshakeCompletionHandler.java:17) ~[HandshakeCompletionHandler.class:?]

at cpw.mods.fml.common.network.internal.HandshakeCompletionHandler.channelRead0(HandshakeCompletionHandler.java:11) ~[HandshakeCompletionHandler.class:?]

at io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:98) ~[simpleChannelInboundHandler.class:?]

at io.netty.channel.DefaultChannelHandlerContext.invokeChannelRead(DefaultChannelHandlerContext.java:337) ~[DefaultChannelHandlerContext.class:?]

at io.netty.channel.DefaultChannelHandlerContext.fireChannelRead(DefaultChannelHandlerContext.java:323) ~[DefaultChannelHandlerContext.class:?]

at io.netty.handler.codec.MessageToMessageDecoder.channelRead(MessageToMessageDecoder.java:103) ~[MessageToMessageDecoder.class:?]

at io.netty.handler.codec.MessageToMessageCodec.channelRead(MessageToMessageCodec.java:111) ~[MessageToMessageCodec.class:?]

at io.netty.channel.DefaultChannelHandlerContext.invokeChannelRead(DefaultChannelHandlerContext.java:337) ~[DefaultChannelHandlerContext.class:?]

at io.netty.channel.DefaultChannelHandlerContext.fireChannelRead(DefaultChannelHandlerContext.java:323) ~[DefaultChannelHandlerContext.class:?]

at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:785) ~[DefaultChannelPipeline.class:?]

at io.netty.channel.embedded.EmbeddedChannel.writeInbound(EmbeddedChannel.java:169) ~[EmbeddedChannel.class:?]

at cpw.mods.fml.common.network.internal.FMLProxyPacket.processPacket(FMLProxyPacket.java:80) [FMLProxyPacket.class:?]

at net.minecraft.network.NetworkManager.processReceivedPackets(NetworkManager.java:242) [NetworkManager.class:?]

at net.minecraft.network.NetworkSystem.networkTick(NetworkSystem.java:190) [NetworkSystem.class:?]

at net.minecraft.server.MinecraftServer.updateTimeLightAndEntities(MinecraftServer.java:763) [MinecraftServer.class:?]

at net.minecraft.server.MinecraftServer.tick(MinecraftServer.java:651) [MinecraftServer.class:?]

at net.minecraft.server.integrated.IntegratedServer.tick(IntegratedServer.java:120) [integratedServer.class:?]

at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:530) [MinecraftServer.class:?]

at net.minecraft.server.MinecraftServer$2.run(MinecraftServer.java:788) [MinecraftServer$2.class:?]

[13:29:11] [server thread/ERROR]: Encountered an unexpected exception

net.minecraft.util.ReportedException: Ticking memory connection

at net.minecraft.network.NetworkSystem.networkTick(NetworkSystem.java:206) ~[NetworkSystem.class:?]

at net.minecraft.server.MinecraftServer.updateTimeLightAndEntities(MinecraftServer.java:763) ~[MinecraftServer.class:?]

at net.minecraft.server.MinecraftServer.tick(MinecraftServer.java:651) ~[MinecraftServer.class:?]

at net.minecraft.server.integrated.IntegratedServer.tick(IntegratedServer.java:120) ~[integratedServer.class:?]

at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:530) [MinecraftServer.class:?]

at net.minecraft.server.MinecraftServer$2.run(MinecraftServer.java:788) [MinecraftServer$2.class:?]

Caused by: java.lang.NullPointerException

at cpw.mods.fml.common.network.internal.FMLProxyPacket.processPacket(FMLProxyPacket.java:90) ~[FMLProxyPacket.class:?]

at net.minecraft.network.NetworkManager.processReceivedPackets(NetworkManager.java:242) ~[NetworkManager.class:?]

at net.minecraft.network.NetworkSystem.networkTick(NetworkSystem.java:190) ~[NetworkSystem.class:?]

... 5 more

[13:29:11] [server thread/ERROR]: This crash report has been saved to: D:\development\forge\.\crash-reports\crash-2014-03-18_13.29.11-server.txt

[13:29:11] [server thread/INFO]: Stopping server

[13:29:11] [server thread/INFO]: Saving players

[13:29:11] [server thread/INFO]: Saving worlds

[13:29:11] [server thread/INFO]: Saving chunks for level 'New World'/Overworld

---- Minecraft Crash Report ----

// Quite honestly, I wouldn't worry myself about that.

 

Time: 3/18/14 1:29 PM

Description: Ticking memory connection

 

java.lang.NullPointerException: Ticking memory connection

at cpw.mods.fml.common.network.internal.FMLProxyPacket.processPacket(FMLProxyPacket.java:90)

at net.minecraft.network.NetworkManager.processReceivedPackets(NetworkManager.java:242)

at net.minecraft.network.NetworkSystem.networkTick(NetworkSystem.java:190)

at net.minecraft.server.MinecraftServer.updateTimeLightAndEntities(MinecraftServer.java:763)

at net.minecraft.server.MinecraftServer.tick(MinecraftServer.java:651)

at net.minecraft.server.integrated.IntegratedServer.tick(IntegratedServer.java:120)

at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:530)

at net.minecraft.server.MinecraftServer$2.run(MinecraftServer.java:788)

 

 

A detailed walkthrough of the error, its code path and all known details is as follows:

---------------------------------------------------------------------------------------

 

-- Head --

Stacktrace:

at cpw.mods.fml.common.network.internal.FMLProxyPacket.processPacket(FMLProxyPacket.java:90)

at net.minecraft.network.NetworkManager.processReceivedPackets(NetworkManager.java:242)

 

-- Ticking connection --

Details:

Connection: net.minecraft.network.NetworkManager@6bd92b68

Stacktrace:

at net.minecraft.network.NetworkSystem.networkTick(NetworkSystem.java:190)

at net.minecraft.server.MinecraftServer.updateTimeLightAndEntities(MinecraftServer.java:763)

at net.minecraft.server.MinecraftServer.tick(MinecraftServer.java:651)

at net.minecraft.server.integrated.IntegratedServer.tick(IntegratedServer.java:120)

at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:530)

at net.minecraft.server.MinecraftServer$2.run(MinecraftServer.java:788)

 

-- System Details --

Details:

Minecraft Version: 1.7.2

Operating System: Windows 8 (amd64) version 6.2

Java Version: 1.7.0_51, Oracle Corporation

Java VM Version: Java HotSpot 64-Bit Server VM (mixed mode), Oracle Corporation

Memory: 853569328 bytes (814 MB) / 1038876672 bytes (990 MB) up to 1038876672 bytes (990 MB)

JVM Flags: 3 total; -Xincgc -Xmx1024M -Xms1024M

AABB Pool Size: 1156 (64736 bytes; 0 MB) allocated, 1142 (63952 bytes; 0 MB) used

IntCache: cache: 0, tcache: 0, allocated: 13, tallocated: 95

FML: MCP v9.01-pre FML v7.2.125.1039 Minecraft Forge 10.12.0.1039 4 mods loaded, 4 mods active

mcp{8.09} [Minecraft Coder Pack] (minecraft.jar) Unloaded->Constructed->Pre-initialized->Initialized->Post-initialized->Available->Available->Available->Available

FML{7.2.125.1039} [Forge Mod Loader] (forgeSrc-1.7.2-10.12.0.1039.jar) Unloaded->Constructed->Pre-initialized->Initialized->Post-initialized->Available->Available->Available->Available

Forge{10.12.0.1039} [Minecraft Forge] (forgeSrc-1.7.2-10.12.0.1039.jar) Unloaded->Constructed->Pre-initialized->Initialized->Post-initialized->Available->Available->Available->Available

xetopc{0.1} [Pantheon Craft] (bin) Unloaded->Constructed->Pre-initialized->Initialized->Post-initialized->Available->Available->Available->Available

Profiler Position: N/A (disabled)

Vec3 Pool Size: 506 (28336 bytes; 0 MB) allocated, 469 (26264 bytes; 0 MB) used

Player Count: 1 / 8; [EntityPlayerMP['Xetosphere'/111, l='New World', x=237.50, y=64.00, z=49.50]]

Type: Integrated Server (map_client.txt)

Is Modded: Definitely; Client brand changed to 'fml,forge'

#@!@# Game crashed! Crash report saved to: #@!@# .\crash-reports\crash-2014-03-18_13.29.11-server.txt

AL lib: (EE) alc_cleanup: 1 device not closed

 

 

 

My real problems (I think) is that my values never really gets synced (client -> server or server -> client). This also make it so that when I open a new world, the gui says that I have the religion from the previous world (even if I create a new one) as well as when I close down minecraft and open it again it is reset to "None" instead of the religion name (where "None" is my default value in the ExtendedPlayer class).

Link to comment
Share on other sites

Don't listen to what that guy said about registration - he obviously has no clue. Anyway, what you're doing wrong is you're setting the values client side, but your packet is set up to only sync data from the server TO the client, not the other way around. Easy fix is just allow your packet to be handled server side as well, reading everything from some bundled NBT that you send, but I do NOT recommend that.

 

Instead, what you should do is send a packet directly from the GUI to the server, saying "button x was pressed, do something", and then parse through the button ids server side setting the data as you need. This will avoid the issue of possible bad packets from the client overwriting your server side data, and you should then be able to synchronize right away with your normal packet. I prefer to have dedicated packets for various things, rather than sending the entire properties data every single time, but that's up to you.

Link to comment
Share on other sites

Don't listen to what that guy said about registration - he obviously has no clue. Anyway, what you're doing wrong is you're setting the values client side, but your packet is set up to only sync data from the server TO the client, not the other way around. Easy fix is just allow your packet to be handled server side as well, reading everything from some bundled NBT that you send, but I do NOT recommend that.

 

Instead, what you should do is send a packet directly from the GUI to the server, saying "button x was pressed, do something", and then parse through the button ids server side setting the data as you need. This will avoid the issue of possible bad packets from the client overwriting your server side data, and you should then be able to synchronize right away with your normal packet. I prefer to have dedicated packets for various things, rather than sending the entire properties data every single time, but that's up to you.

So let me see if I got you right, you mean that I create a new packet that instead of sending from server side sends info from server to client instead? And that this new packet should be sent whenever one of the buttons are pressed?

 

If that is correct do you know of any tutorial on sending data from server to client or the other way around? I wanna learn the new netty system in and out, so that I can use this for future projects and problems as well.

Link to comment
Share on other sites

I mean you need to send a packet from the client to the server, but you can do it both ways using the exact same packet since you seem to have followed the same network tutorial I did :P

 

// on the server side, this is how you send a packet to a single player:
dispatcher.sendTo(new YourPacket(somedata), (EntityPlayerMP) player);

// on the client side, this is how you send a packet from the player to the server
// the handling on the server side is for the same player that sent it
dispatcher.sendToServer(new YourPacket(somedata));

Note that those are both using the exact same packet, and you have two methods in the AbstractPacket class that you need to implement if you want it to work both ways:

/**
     * Handle a packet on the client side. Note this occurs after decoding has completed.
     *
     * @param player the player reference
     */
    public abstract void handleClientSide(EntityPlayer player);

    /**
     * Handle a packet on the server side. Note this occurs after decoding has completed.
     *
     * @param player the player reference
     */
    public abstract void handleServerSide(EntityPlayer player);

Link to comment
Share on other sites

BTW, I found example code somewhere (can't remember where tho) and used similar code.

 

[spoiler=ChannelHandler]

public class ChannelHandler extends FMLIndexedMessageToMessageCodec<IPacket> {
public ChannelHandler() {
	this.addDiscriminator(0, PacketWormhole.class);
	this.addDiscriminator(1, PacketDHDEnterGlyph.class);
}

public static EnumMap<Side, FMLEmbeddedChannel> channels;

public static void initChannels() {
	channels = NetworkRegistry.INSTANCE.newChannel("SpaceDistortion", new ChannelHandler());
}

@SideOnly(Side.CLIENT)
/**
 * Sends a packet from the client to the server
 * @param packet An IPacket to send
 */
public static void clientSendPacket(IPacket packet) {
	FMLEmbeddedChannel channel = ChannelHandler.channels.get(Side.CLIENT);
	channel.attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.TOSERVER);
	channel.writeOutbound(packet);
}

@SideOnly(Side.SERVER)
/**
 * Sends a packet from the server to a given client
 * @param packet An IPacket to send
 * @param player A player to send it to
 */
public static void serverSentPacket(IPacket packet, EntityPlayer player) {
	FMLEmbeddedChannel channel = ChannelHandler.channels.get(Side.SERVER);
	channel.attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.PLAYER);
	channel.attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(player);
	channel.writeOutbound(packet);
}

/**
 * Sends a packet from the server to all clients
 * @param packet An IPacket to send
 */
@SideOnly(Side.SERVER)
public static void serverSendPacketAllClients(IPacket packet) {
	FMLEmbeddedChannel channel = ChannelHandler.channels.get(Side.SERVER);
	channel.attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.ALL);
	channel.writeOutbound(packet);
}

@Override
public void encodeInto(ChannelHandlerContext context, IPacket packet, ByteBuf data) throws Exception {
	packet.writeBytes(data);
}

@Override
public void decodeInto(ChannelHandlerContext context, ByteBuf data, IPacket packet) {
	// read the packet
	packet.readBytes(data);

	// handle the packet by calling IPacket#onReceive
	Side side = FMLCommonHandler.instance().getEffectiveSide();
	EntityPlayer player;
	switch (side) {
		case CLIENT:
			player = Minecraft.getMinecraft().thePlayer;
			packet.onReceive(player, side);
		case SERVER:
			INetHandler net = context.channel().attr(NetworkRegistry.NET_HANDLER).get();
			player = ((NetHandlerPlayServer) net).playerEntity;
			packet.onReceive(player, side);
	}
}

 

 

[spoiler=IPacket]

public interface IPacket {
public void readBytes(ByteBuf bytes);
public void writeBytes(ByteBuf bytes);
public void onReceive(EntityPlayer player, Side side);
}

[/code]

 

You probably don't need the entire class, but I hope this helps. Especially look at clientSendPacket, serverSendPacket, and serverSendPacketAllClients.

I like to make mods, just like you. Here's one worth checking out

Link to comment
Share on other sites

Ok, it seems I can't work this out by myself even after the information you gave me (server/client stuff really confuses me and this is my first time handling nbttag stuff).

 

My current bugs is, when I open a world after quiting the game, it prints out correct information in the console (I made it so that when I use the method loadNBTData in the ExtendedPlayer.class it will print the religion and culture) but when I look inside my gui everything is reset back to the standard values. Though when I open a different world without leaving the game, it still has the information from the earlier world.

 

So I ask how I can make it save for only the world he is currently in, and that it will save and load correctly even after I restart the game.

 

Here is my current code:

 

Mod class:

 

package com.xetosphere.pantheon;

import net.minecraft.creativetab.CreativeTabs;
import net.minecraftforge.common.MinecraftForge;

import com.xetosphere.pantheon.block.ModBlocks;
import com.xetosphere.pantheon.creativetab.TabPantheon;
import com.xetosphere.pantheon.event.CultureEventHandler;
import com.xetosphere.pantheon.item.ModItems;
import com.xetosphere.pantheon.lib.Reference;
import com.xetosphere.pantheon.network.PacketPipeline;
import com.xetosphere.pantheon.proxy.CommonProxy;

import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.network.NetworkRegistry;

@Mod(modid = Reference.MOD_ID, name = Reference.MOD_NAME, version = Reference.VERSION)
public class PantheonCraft {

public static final CreativeTabs tabPC = new TabPantheon(CreativeTabs.getNextID(), Reference.MOD_ID);

public static final PacketPipeline packetPipeline = new PacketPipeline();

ModBlocks blocks = new ModBlocks();
ModItems items = new ModItems();

@Instance(Reference.MOD_ID)
public static PantheonCraft instance;

@SidedProxy(clientSide = Reference.CLIENT_PROXY, serverSide = Reference.COMMON_PROXY)
public static CommonProxy proxy;

@EventHandler
public void preInit(FMLPreInitializationEvent e) {

	blocks.init();

	items.init();
}

@EventHandler
public void init(FMLInitializationEvent e) {

	packetPipeline.initialise();
}

@EventHandler
public void postInit(FMLPostInitializationEvent e) {

	packetPipeline.postInitialise();

	MinecraftForge.EVENT_BUS.register(new CultureEventHandler());

	NetworkRegistry.INSTANCE.registerGuiHandler(this, new CommonProxy());
}
}

 

 

GuiReligion.class:

 

package com.xetosphere.pantheon.client.gui;

import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.ChatComponentText;

import org.lwjgl.opengl.GL11;

import com.xetosphere.pantheon.PantheonCraft;
import com.xetosphere.pantheon.entity.ExtendedPlayer;
import com.xetosphere.pantheon.item.ItemTalisman;
import com.xetosphere.pantheon.lib.PantheonReference;
import com.xetosphere.pantheon.lib.Textures;
import com.xetosphere.pantheon.network.packet.SyncPlayerPropsPacket;

public class GuiReligion extends GuiScreen {

private int xSize = 176;

private int ySize = 206;

EntityPlayer player;

public GuiReligion(EntityPlayer player) {

	this.player = player;
}

public void updateScreen() {
	super.updateScreen();
}

public void drawScreen(int x, int y, float f) {

	drawDefaultBackground();

	GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);

	mc.getTextureManager().bindTexture(Textures.GUI_RELIGION);

	int posX = (width - xSize) / 2;
	int posY = (height - ySize) / 2;

	drawTexturedModalRect(posX, posY, 0, 0, xSize, ySize);
	drawString(fontRendererObj, "Pantheon:", posX + (xSize / 12), posY + 16, 0xffffffff);
	drawString(fontRendererObj, "Culture:", posX + (xSize / 12), posY + 36, 0xffffffff);
	drawCenteredString(fontRendererObj, ExtendedPlayer.get(player).getPantheon(), posX + (xSize / 4 * 3), posY + 16, 0xffffffff);
	drawCenteredString(fontRendererObj, ExtendedPlayer.get(player).getCulture() + "/" + ExtendedPlayer.get(player).getMaxCulture(), posX + (xSize / 4 * 3), posY + 36, 0xffffffff);

	super.drawScreen(x, y, f);
}

public boolean doesGuiPauseGame() {

	return false;
}

@SuppressWarnings("unchecked")
public void initGui() {

	this.buttonList.clear();

	int posX = (width - xSize) / 2;
	int posY = (height - ySize) / 2;

	this.buttonList.add(new GuiButton(0, posX + (xSize / 9 * 0) + 6, posY + 120 + (25 * 0), 50, 20, PantheonReference.pantheons[PantheonReference.NO_RELIGION]));
	this.buttonList.add(new GuiButton(1, posX + (xSize / 9 * 0) + 6, posY + 120 + (25 * 1), 50, 20, PantheonReference.pantheons[PantheonReference.GREEK]));
	this.buttonList.add(new GuiButton(2, posX + (xSize / 9 * 0) + 6, posY + 120 + (25 * 2), 50, 20, PantheonReference.pantheons[PantheonReference.NORSE]));
	this.buttonList.add(new GuiButton(3, posX + (xSize / 9 * 3) + 6, posY + 120 + (25 * 0), 50, 20, PantheonReference.pantheons[PantheonReference.ROMAN]));
	this.buttonList.add(new GuiButton(4, posX + (xSize / 9 * 3) + 6, posY + 120 + (25 * 1), 50, 20, PantheonReference.pantheons[PantheonReference.EGYPTIAN]));
	this.buttonList.add(new GuiButton(6, posX + (xSize / 9 * 3) + 6, posY + 120 + (25 * 2), 50, 20, PantheonReference.pantheons[PantheonReference.MAYAN]));
	this.buttonList.add(new GuiButton(7, posX + (xSize / 9 * 6) + 6, posY + 120 + (25 * 0), 50, 20, PantheonReference.pantheons[PantheonReference.CHINESE]));
	this.buttonList.add(new GuiButton(8, posX + (xSize / 9 * 6) + 6, posY + 120 + (25 * 1), 50, 20, PantheonReference.pantheons[PantheonReference.HINDU]));
	this.buttonList.add(new GuiButton(9, posX + (xSize / 9 * 6) + 6, posY + 120 + (25 * 2), 50, 20, PantheonReference.pantheons[PantheonReference.AZTECIAN]));
}

public void actionPerformed(GuiButton button) {

	switch (button.id) {
		case 0:
			ItemTalisman.pantheon = PantheonReference.NO_RELIGION;
			ExtendedPlayer.get(player).setPantheon(PantheonReference.pantheons[PantheonReference.NO_RELIGION]);
			ExtendedPlayer.get(player).setPantheonId(PantheonReference.NO_RELIGION);
			System.out.println("[XETOPC] Pantheon = " + ExtendedPlayer.get(player).getPantheon());
			System.out.println("[XETOPC] PantheonId = " + ExtendedPlayer.get(player).getPantheonId());
			player.addChatComponentMessage(new ChatComponentText("You set your pantheon to: " + ExtendedPlayer.get(player).getPantheon()));
			PantheonCraft.packetPipeline.sendToServer(new SyncPlayerPropsPacket(player));
			break;
		case 1:
			ItemTalisman.pantheon = PantheonReference.GREEK;
			ExtendedPlayer.get(player).setPantheon(PantheonReference.pantheons[PantheonReference.GREEK]);
			ExtendedPlayer.get(player).setPantheonId(PantheonReference.GREEK);
			System.out.println("[XETOPC] Pantheon = " + ExtendedPlayer.get(player).getPantheon());
			System.out.println("[XETOPC] PantheonId = " + ExtendedPlayer.get(player).getPantheonId());
			player.addChatComponentMessage(new ChatComponentText("You set your pantheon to: " + ExtendedPlayer.get(player).getPantheon()));
			PantheonCraft.packetPipeline.sendToServer(new SyncPlayerPropsPacket(player));
			break;
		case 2:
			ItemTalisman.pantheon = PantheonReference.NORSE;
			ExtendedPlayer.get(player).setPantheon(PantheonReference.pantheons[PantheonReference.NORSE]);
			ExtendedPlayer.get(player).setPantheonId(PantheonReference.NORSE);
			System.out.println("[XETOPC] Pantheon = " + ExtendedPlayer.get(player).getPantheon());
			System.out.println("[XETOPC] PantheonId = " + ExtendedPlayer.get(player).getPantheonId());
			player.addChatComponentMessage(new ChatComponentText("You set your pantheon to: " + ExtendedPlayer.get(player).getPantheon()));
			PantheonCraft.packetPipeline.sendToServer(new SyncPlayerPropsPacket(player));
			break;
		case 3:
			ItemTalisman.pantheon = PantheonReference.ROMAN;
			ExtendedPlayer.get(player).setPantheon(PantheonReference.pantheons[PantheonReference.ROMAN]);
			ExtendedPlayer.get(player).setPantheonId(PantheonReference.ROMAN);
			System.out.println("[XETOPC] Pantheon = " + ExtendedPlayer.get(player).getPantheon());
			System.out.println("[XETOPC] PantheonId = " + ExtendedPlayer.get(player).getPantheonId());
			player.addChatComponentMessage(new ChatComponentText("You set your pantheon to: " + ExtendedPlayer.get(player).getPantheon()));
			PantheonCraft.packetPipeline.sendToServer(new SyncPlayerPropsPacket(player));
			break;
		case 4:
			ItemTalisman.pantheon = PantheonReference.EGYPTIAN;
			ExtendedPlayer.get(player).setPantheon(PantheonReference.pantheons[PantheonReference.EGYPTIAN]);
			ExtendedPlayer.get(player).setPantheonId(PantheonReference.EGYPTIAN);
			System.out.println("[XETOPC] Pantheon = " + ExtendedPlayer.get(player).getPantheon());
			System.out.println("[XETOPC] PantheonId = " + ExtendedPlayer.get(player).getPantheonId());
			player.addChatComponentMessage(new ChatComponentText("You set your pantheon to: " + ExtendedPlayer.get(player).getPantheon()));
			PantheonCraft.packetPipeline.sendToServer(new SyncPlayerPropsPacket(player));
			break;
		case 5:
			ItemTalisman.pantheon = PantheonReference.EGYPTIAN;
			ExtendedPlayer.get(player).setPantheon(PantheonReference.pantheons[PantheonReference.EGYPTIAN]);
			ExtendedPlayer.get(player).setPantheonId(PantheonReference.EGYPTIAN);
			System.out.println("[XETOPC] Pantheon = " + ExtendedPlayer.get(player).getPantheon());
			System.out.println("[XETOPC] PantheonId = " + ExtendedPlayer.get(player).getPantheonId());
			player.addChatComponentMessage(new ChatComponentText("You set your pantheon to: " + ExtendedPlayer.get(player).getPantheon()));
			PantheonCraft.packetPipeline.sendToServer(new SyncPlayerPropsPacket(player));
			break;
		case 6:
			ItemTalisman.pantheon = PantheonReference.MAYAN;
			ExtendedPlayer.get(player).setPantheon(PantheonReference.pantheons[PantheonReference.MAYAN]);
			ExtendedPlayer.get(player).setPantheonId(PantheonReference.MAYAN);
			System.out.println("[XETOPC] Pantheon = " + ExtendedPlayer.get(player).getPantheon());
			System.out.println("[XETOPC] PantheonId = " + ExtendedPlayer.get(player).getPantheonId());
			player.addChatComponentMessage(new ChatComponentText("You set your pantheon to: " + ExtendedPlayer.get(player).getPantheon()));
			PantheonCraft.packetPipeline.sendToServer(new SyncPlayerPropsPacket(player));
			break;
		case 7:
			ItemTalisman.pantheon = PantheonReference.CHINESE;
			ExtendedPlayer.get(player).setPantheon(PantheonReference.pantheons[PantheonReference.CHINESE]);
			ExtendedPlayer.get(player).setPantheonId(PantheonReference.CHINESE);
			System.out.println("[XETOPC] Pantheon = " + ExtendedPlayer.get(player).getPantheon());
			System.out.println("[XETOPC] PantheonId = " + ExtendedPlayer.get(player).getPantheonId());
			player.addChatComponentMessage(new ChatComponentText("You set your pantheon to: " + ExtendedPlayer.get(player).getPantheon()));
			PantheonCraft.packetPipeline.sendToServer(new SyncPlayerPropsPacket(player));
			break;
		case 8:
			ItemTalisman.pantheon = PantheonReference.HINDU;
			ExtendedPlayer.get(player).setPantheon(PantheonReference.pantheons[PantheonReference.HINDU]);
			ExtendedPlayer.get(player).setPantheonId(PantheonReference.HINDU);
			System.out.println("[XETOPC] Pantheon = " + ExtendedPlayer.get(player).getPantheon());
			System.out.println("[XETOPC] PantheonId = " + ExtendedPlayer.get(player).getPantheonId());
			player.addChatComponentMessage(new ChatComponentText("You set your pantheon to: " + ExtendedPlayer.get(player).getPantheon()));
			PantheonCraft.packetPipeline.sendToServer(new SyncPlayerPropsPacket(player));
			break;
		case 9:
			ItemTalisman.pantheon = PantheonReference.AZTECIAN;
			ExtendedPlayer.get(player).setPantheon(PantheonReference.pantheons[PantheonReference.AZTECIAN]);
			ExtendedPlayer.get(player).setPantheonId(PantheonReference.AZTECIAN);
			System.out.println("[XETOPC] Pantheon = " + ExtendedPlayer.get(player).getPantheon());
			System.out.println("[XETOPC] PantheonId = " + ExtendedPlayer.get(player).getPantheonId());
			player.addChatComponentMessage(new ChatComponentText("You set your pantheon to: " + ExtendedPlayer.get(player).getPantheon()));
			PantheonCraft.packetPipeline.sendToServer(new SyncPlayerPropsPacket(player));
			break;
	}
}
}

 

 

ItemTalisman.class:

 

package com.xetosphere.pantheon.item;

import net.minecraft.entity.Entity;
import net.minecraft.entity.effect.EntityLightningBolt;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.MovingObjectPosition.MovingObjectType;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;

import org.lwjgl.input.Keyboard;

import com.xetosphere.pantheon.PantheonCraft;
import com.xetosphere.pantheon.entity.ExtendedPlayer;
import com.xetosphere.pantheon.lib.GuiIds;
import com.xetosphere.pantheon.lib.PantheonReference;

public class ItemTalisman extends ItemPC {

public static int pantheon;

public ItemTalisman() {
}

public void onUpdate(ItemStack item, World world, Entity player, int par4, boolean par5) {

	if (player instanceof EntityPlayer) {

		switch (pantheon) {

			case PantheonReference.NO_RELIGION:
				ExtendedPlayer.get((EntityPlayer) player).setPantheon(PantheonReference.pantheons[PantheonReference.NO_RELIGION]);
				ExtendedPlayer.get((EntityPlayer) player).setPantheonId(PantheonReference.NO_RELIGION);
				break;
			case PantheonReference.GREEK:
				ExtendedPlayer.get((EntityPlayer) player).setPantheon(PantheonReference.pantheons[PantheonReference.GREEK]);
				ExtendedPlayer.get((EntityPlayer) player).setPantheonId(PantheonReference.GREEK);
				break;
			case PantheonReference.NORSE:
				ExtendedPlayer.get((EntityPlayer) player).setPantheon(PantheonReference.pantheons[PantheonReference.NORSE]);
				ExtendedPlayer.get((EntityPlayer) player).setPantheonId(PantheonReference.NORSE);
				break;
			case PantheonReference.ROMAN:
				ExtendedPlayer.get((EntityPlayer) player).setPantheon(PantheonReference.pantheons[PantheonReference.ROMAN]);
				ExtendedPlayer.get((EntityPlayer) player).setPantheonId(PantheonReference.ROMAN);
				break;
			case PantheonReference.EGYPTIAN:
				ExtendedPlayer.get((EntityPlayer) player).setPantheon(PantheonReference.pantheons[PantheonReference.EGYPTIAN]);
				ExtendedPlayer.get((EntityPlayer) player).setPantheonId(PantheonReference.EGYPTIAN);
				break;
			case PantheonReference.MAYAN:
				ExtendedPlayer.get((EntityPlayer) player).setPantheon(PantheonReference.pantheons[PantheonReference.MAYAN]);
				ExtendedPlayer.get((EntityPlayer) player).setPantheonId(PantheonReference.MAYAN);
				break;
			case PantheonReference.CHINESE:
				ExtendedPlayer.get((EntityPlayer) player).setPantheon(PantheonReference.pantheons[PantheonReference.CHINESE]);
				ExtendedPlayer.get((EntityPlayer) player).setPantheonId(PantheonReference.CHINESE);
				break;
			case PantheonReference.HINDU:
				ExtendedPlayer.get((EntityPlayer) player).setPantheon(PantheonReference.pantheons[PantheonReference.HINDU]);
				ExtendedPlayer.get((EntityPlayer) player).setPantheonId(PantheonReference.HINDU);
				break;
			case PantheonReference.AZTECIAN:
				ExtendedPlayer.get((EntityPlayer) player).setPantheon(PantheonReference.pantheons[PantheonReference.AZTECIAN]);
				ExtendedPlayer.get((EntityPlayer) player).setPantheonId(PantheonReference.AZTECIAN);
				break;
		}
	}
}

public ItemStack onItemRightClick(ItemStack itemStack, World world, EntityPlayer player) {

	String pantheon = ExtendedPlayer.get(player).getPantheon();

	final int ONE_SECOND = 20;

	final double EYE_HEIGHT = 1.62;
	final double REACH_DISTANCE = 300;

	Vec3 startPos = player.getPosition(1.0F);

	if (!world.isRemote) startPos = startPos.addVector(0, EYE_HEIGHT, 0);

	Vec3 look = player.getLook(1.0F);
	Vec3 endPos = startPos.addVector(look.xCoord * REACH_DISTANCE, look.yCoord * REACH_DISTANCE, look.zCoord * REACH_DISTANCE);

	MovingObjectPosition objectMouseOver = world.rayTraceBlocks(startPos, endPos);

	if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) {

		if (world.isRemote) {

			player.openGui(PantheonCraft.instance, GuiIds.RELIGION_GUI, world, (int) player.posX, (int) player.posY, (int) player.posZ);
		}
	}

	if (!Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) {

		// TODO Greek
		if (pantheon.equals(PantheonReference.pantheons[PantheonReference.GREEK])) {

			if (ExtendedPlayer.get(player).getCulture() >= 100 && objectMouseOver != null && objectMouseOver.typeOfHit == MovingObjectType.BLOCK) {

				ExtendedPlayer.get(player).consumeCulture(100);

				int i = objectMouseOver.blockX;
				int j = objectMouseOver.blockY;
				int k = objectMouseOver.blockZ;

				world.spawnEntityInWorld(new EntityLightningBolt(world, i, j, k));

			} else {

				if (!world.isRemote) {

					player.addChatComponentMessage(new ChatComponentText("You don't have enough culture."));
					ExtendedPlayer.get(player).setCulture(1000);
				}
			}
		}

		// TODO Norse
		if (pantheon.equals(PantheonReference.pantheons[PantheonReference.NORSE])) {

			if (ExtendedPlayer.get(player).getCulture() >= 100) {

				ExtendedPlayer.get(player).consumeCulture(100);
				player.addPotionEffect(new PotionEffect(Potion.moveSpeed.id, 120 * ONE_SECOND, 0, false));

			} else {

				if (!world.isRemote) {

					player.addChatComponentMessage(new ChatComponentText("You don't have enough culture."));
					ExtendedPlayer.get(player).setCulture(1000);
				}
			}
		}

		// TODO Roman
		if (pantheon.equals(PantheonReference.pantheons[PantheonReference.ROMAN])) {

			if (ExtendedPlayer.get(player).getCulture() >= 100 && objectMouseOver != null && objectMouseOver.typeOfHit == MovingObjectType.BLOCK) {

				ExtendedPlayer.get(player).consumeCulture(100);

				int i = objectMouseOver.blockX;
				int j = objectMouseOver.blockY;
				int k = objectMouseOver.blockZ;

				if (!world.isRemote) world.createExplosion(player, i, j, k, 3, true);

			} else {

				if (!world.isRemote) {

					player.addChatComponentMessage(new ChatComponentText("You don't have enough culture."));
					ExtendedPlayer.get(player).setCulture(1000);
				}
			}
		}

		// TODO Egyptian
		if (pantheon.equals(PantheonReference.pantheons[PantheonReference.EGYPTIAN])) {

			if (ExtendedPlayer.get(player).getCulture() >= 100) {

				ExtendedPlayer.get(player).consumeCulture(100);
				if (!world.isRemote) player.addPotionEffect(new PotionEffect(Potion.nightVision.id, 120 * ONE_SECOND, 0, false));

			} else {

				if (!world.isRemote) {

					player.addChatComponentMessage(new ChatComponentText("You don't have enough culture."));
					ExtendedPlayer.get(player).setCulture(1000);
				}
			}
		}

		// TODO Mayan
		if (pantheon.equals(PantheonReference.pantheons[PantheonReference.MAYAN])) {

			if (ExtendedPlayer.get(player).getCulture() >= 100) {

				ExtendedPlayer.get(player).consumeCulture(100);
				if (!world.isRemote) player.addChatComponentMessage(new ChatComponentText("Shooting mayan powers."));

			} else {

				if (!world.isRemote) {

					player.addChatComponentMessage(new ChatComponentText("You don't have enough culture."));
					ExtendedPlayer.get(player).setCulture(1000);
				}
			}
		}

		// TODO Chinese
		if (pantheon.equals(PantheonReference.pantheons[PantheonReference.CHINESE])) {

			if (ExtendedPlayer.get(player).getCulture() >= 100) {

				ExtendedPlayer.get(player).consumeCulture(100);
				if (!world.isRemote) player.addChatComponentMessage(new ChatComponentText("Shooting chinese powers."));

			} else {

				if (!world.isRemote) {

					player.addChatComponentMessage(new ChatComponentText("You don't have enough culture."));
					ExtendedPlayer.get(player).setCulture(1000);
				}
			}
		}

		// TODO Hindi
		if (pantheon.equals(PantheonReference.pantheons[PantheonReference.HINDU])) {

			if (ExtendedPlayer.get(player).getCulture() >= 100) {

				ExtendedPlayer.get(player).consumeCulture(100);
				if (!world.isRemote) player.addChatComponentMessage(new ChatComponentText("Shooting hindu powers."));

			} else {

				if (!world.isRemote) {

					player.addChatComponentMessage(new ChatComponentText("You don't have enough culture."));
					ExtendedPlayer.get(player).setCulture(1000);
				}
			}
		}

		// TODO Aztecian
		if (pantheon.equals(PantheonReference.pantheons[PantheonReference.AZTECIAN])) {

			if (ExtendedPlayer.get(player).getCulture() >= 100) {

				ExtendedPlayer.get(player).consumeCulture(100);
				if (!world.isRemote) player.addChatComponentMessage(new ChatComponentText("Shooting aztecian powers."));

			} else {

				if (!world.isRemote) {

					player.addChatComponentMessage(new ChatComponentText("You don't have enough culture."));
					ExtendedPlayer.get(player).setCulture(1000);
				}
			}
		}

		if (!world.isRemote && pantheon.equals(PantheonReference.pantheons[PantheonReference.NO_RELIGION])) player.addChatComponentMessage(new ChatComponentText("No God, no special effects!"));
	}

	return itemStack;
}
}

 

 

ExtendedPlayer.class:

 

package com.xetosphere.pantheon.entity;

import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import net.minecraftforge.common.IExtendedEntityProperties;

import com.xetosphere.pantheon.PantheonCraft;
import com.xetosphere.pantheon.lib.PantheonReference;
import com.xetosphere.pantheon.lib.Reference;
import com.xetosphere.pantheon.network.packet.SyncPlayerPropsPacket;
import com.xetosphere.pantheon.proxy.CommonProxy;

public class ExtendedPlayer implements IExtendedEntityProperties {

public static final String IDENTIFIER = Reference.MOD_ID + "_properties";

private final EntityPlayer player;

private int culture, maxCulture, pantheonId;

private String pantheon;

public static final int CULTURE_WATCHER = 25;
public static final int PANTHEON_WATCHER = 26;
public static final int ID_WATCHER = 27;

public ExtendedPlayer(EntityPlayer player) {

	this.player = player;
	culture = 0;
	maxCulture = PantheonReference.MAX_CULTURE;
	pantheon = PantheonReference.pantheons[PantheonReference.NO_RELIGION];
	pantheonId = PantheonReference.NO_RELIGION;
	player.getDataWatcher().addObject(CULTURE_WATCHER, culture);
	player.getDataWatcher().addObject(PANTHEON_WATCHER, pantheon);
	player.getDataWatcher().addObject(ID_WATCHER, pantheonId);
}

public static final void register(EntityPlayer player) {

	player.registerExtendedProperties(IDENTIFIER, new ExtendedPlayer(player));
}

public static final ExtendedPlayer get(EntityPlayer player) {

	return (ExtendedPlayer) player.getExtendedProperties(IDENTIFIER);
}

@Override
public void saveNBTData(NBTTagCompound compound) {

	NBTTagCompound properties = new NBTTagCompound();
	properties.setInteger("Culture", player.getDataWatcher().getWatchableObjectInt(CULTURE_WATCHER));
	properties.setInteger("MaxCulture", maxCulture);
	properties.setString("Pantheon", player.getDataWatcher().getWatchableObjectString(PANTHEON_WATCHER));
	properties.setInteger("IdPantheon", player.getDataWatcher().getWatchableObjectInt(ID_WATCHER));
	compound.setTag(IDENTIFIER, properties);
}

@Override
public void loadNBTData(NBTTagCompound compound) {

	NBTTagCompound properties = (NBTTagCompound) compound.getTag(IDENTIFIER);
	player.getDataWatcher().updateObject(CULTURE_WATCHER, properties.getInteger("Culture"));
	maxCulture = properties.getInteger("MaxCulture");
	player.getDataWatcher().updateObject(PANTHEON_WATCHER, properties.getString("Pantheon"));
	player.getDataWatcher().updateObject(ID_WATCHER, properties.getInteger("IdPantheon"));
	System.out.println("[XETOPC PROPS] Culture from NBT: " + player.getDataWatcher().getWatchableObjectInt(CULTURE_WATCHER) + "/" + maxCulture);
	System.out.println("[XETOPC PROPS] Pantheon from NBT: [iD = " + player.getDataWatcher().getWatchableObjectInt(ID_WATCHER) + "] " + player.getDataWatcher().getWatchableObjectString(PANTHEON_WATCHER));
}

@Override
public void init(Entity entity, World world) {
}

public final boolean consumeCulture(int amount) {

	boolean sufficient = amount <= getCulture();
	setCulture(getCulture() - amount);
	return sufficient;
}

public final int getCulture() {

	return player.getDataWatcher().getWatchableObjectInt(CULTURE_WATCHER);
}

public final String getPantheon() {

	return player.getDataWatcher().getWatchableObjectString(PANTHEON_WATCHER);
}

public final int getPantheonId() {

	return player.getDataWatcher().getWatchableObjectInt(ID_WATCHER);
}

public final void setCulture(int amount) {

	player.getDataWatcher().updateObject(CULTURE_WATCHER, amount > 0 ? (amount < maxCulture ? amount : maxCulture) : 0);
}

public final void setPantheon(String pantheon) {

	player.getDataWatcher().updateObject(PANTHEON_WATCHER, pantheon);
}

public final void setPantheonId(int id) {

	player.getDataWatcher().updateObject(ID_WATCHER, id);
}

public final int getMaxCulture() {

	return maxCulture;
}

public final void setMaxCulture(int amount) {

	maxCulture = (amount > 0 ? amount : 0);
	PantheonCraft.packetPipeline.sendTo(new SyncPlayerPropsPacket(player), (EntityPlayerMP) player);
	PantheonCraft.packetPipeline.sendToServer(new SyncPlayerPropsPacket(player));
}

private static final String getSaveKey(EntityPlayer player) {

	return player.getCommandSenderName() + ":" + IDENTIFIER;
}

public static final void saveProxyData(EntityPlayer player) {

	NBTTagCompound savedData = new NBTTagCompound();
	ExtendedPlayer.get(player).saveNBTData(savedData);
	CommonProxy.storeEntityData(getSaveKey(player), savedData);
}

public static final void loadProxyData(EntityPlayer player) {

	ExtendedPlayer playerData = ExtendedPlayer.get(player);
	NBTTagCompound savedData = CommonProxy.getEntityData(getSaveKey(player));

	if (savedData != null) {
		playerData.loadNBTData(savedData);
	}

	PantheonCraft.packetPipeline.sendTo(new SyncPlayerPropsPacket(player), (EntityPlayerMP) player);
	PantheonCraft.packetPipeline.sendToServer(new SyncPlayerPropsPacket(player));
}

}

 

 

CultureEventHandler.class:

 

package com.xetosphere.pantheon.event;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraftforge.event.entity.EntityEvent.EntityConstructing;
import net.minecraftforge.event.entity.EntityJoinWorldEvent;
import net.minecraftforge.event.entity.living.LivingDeathEvent;

import com.xetosphere.pantheon.entity.ExtendedPlayer;

import cpw.mods.fml.common.eventhandler.SubscribeEvent;

public class CultureEventHandler {

@SubscribeEvent
public void onEntityConstructing(EntityConstructing event) {

	if (event.entity instanceof EntityPlayer) {

		if (ExtendedPlayer.get((EntityPlayer) event.entity) == null) {

			ExtendedPlayer.register((EntityPlayer) event.entity);
		}
	}
}

@SubscribeEvent
public void onEntityJoinWorld(EntityJoinWorldEvent event) {

	if (!event.entity.worldObj.isRemote && event.entity instanceof EntityPlayer) {

		ExtendedPlayer.loadProxyData((EntityPlayer) event.entity);
	}
}

@SubscribeEvent
public void onLivingDeathEvent(LivingDeathEvent event) {

	if (!event.entity.worldObj.isRemote && event.entity instanceof EntityPlayer) {

		ExtendedPlayer.saveProxyData((EntityPlayer) event.entity);
	}
}
}

 

 

SyncPlayerPropsPacket.class:

 

package com.xetosphere.pantheon.network.packet;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;

import com.xetosphere.pantheon.entity.ExtendedPlayer;
import com.xetosphere.pantheon.network.AbstractPacket;

import cpw.mods.fml.common.network.ByteBufUtils;

public class SyncPlayerPropsPacket extends AbstractPacket {

private NBTTagCompound data;

public SyncPlayerPropsPacket() {
}

public SyncPlayerPropsPacket(EntityPlayer player) {

	data = new NBTTagCompound();
	ExtendedPlayer.get(player).saveNBTData(data);
}

@Override
public void encodeInto(ChannelHandlerContext ctx, ByteBuf buffer) {

	ByteBufUtils.writeTag(buffer, data);
}

@Override
public void decodeInto(ChannelHandlerContext ctx, ByteBuf buffer) {

	data = ByteBufUtils.readTag(buffer);
}

@Override
public void handleClientSide(EntityPlayer player) {

	ExtendedPlayer.get(player).loadNBTData(data);
}

@Override
public void handleServerSide(EntityPlayer player) {

	ExtendedPlayer.get(player).loadNBTData(data);
}
}

 

 

CommonProxy.class:

 

package com.xetosphere.pantheon.proxy;

import java.util.HashMap;
import java.util.Map;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;

import com.xetosphere.pantheon.client.gui.GuiReligion;
import com.xetosphere.pantheon.lib.GuiIds;

import cpw.mods.fml.common.network.IGuiHandler;

public class CommonProxy implements IGuiHandler {

private static final Map<String, NBTTagCompound> extendedEntityData = new HashMap<String, NBTTagCompound>();

public Object getServerGuiElement(int id, EntityPlayer player, World world, int x, int y, int z) {

	if (id == GuiIds.RELIGION_GUI) {

		return null;
	}

	return null;
}

public Object getClientGuiElement(int id, EntityPlayer player, World world, int x, int y, int z) {

	if (id == GuiIds.RELIGION_GUI) {

		return new GuiReligion(player);
	}

	return null;
}

public static void storeEntityData(String name, NBTTagCompound compound) {

	extendedEntityData.put(name, compound);
}

public static NBTTagCompound getEntityData(String name) {

	return extendedEntityData.remove(name);
}
}

 

 

AbstractPacket.class:

 

package com.xetosphere.pantheon.network;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import net.minecraft.entity.player.EntityPlayer;

public abstract class AbstractPacket {

public abstract void encodeInto(ChannelHandlerContext ctx, ByteBuf buffer);

public abstract void decodeInto(ChannelHandlerContext ctx, ByteBuf buffer);

public abstract void handleClientSide(EntityPlayer player);

public abstract void handleServerSide(EntityPlayer player);
}

 

 

ClientProxy.class:

 

package com.xetosphere.pantheon.proxy;

public class ClientProxy extends CommonProxy {
// Doesn't do anything.
}

 

Link to comment
Share on other sites

1. You don't need to send a synchronization packet to the server when loading your properties - they just loaded on the server.

 

2. You are using DataWatcher for your variables, so you don't need to send a packet at all - that's done automatically when you update the value, ON THE SERVER SIDE. Send a packet from your GUI to the server, rather than trying to set the data from the GUI:

switch (button.id) {
case 0:
// BIG NOOOOOO!!! This is on the client! Send a packet with the information you need and set the data there
ItemTalisman.pantheon = PantheonReference.NO_RELIGION;
ExtendedPlayer.get(player).setPantheon(PantheonReference.pantheons[PantheonReference.NO_RELIGION]);
// etc.

// Should be:
yourDispatcher.sendToServer(new UpdateReligion(newReligion));
// and in your UpdateReligion packet, in the handle server side method, you would then do
// what you were doing in your GUI:
handleServerSide(args) { // <- obviously don't copy that
ExtendedPlayer.get(player).setPantheon(packet.religion);
}

 

So your GUI code would look like this:

public void actionPerformed(GuiButton button) {
YourReligionObject newReligion = PantheonReference.NO_RELIGION;
switch (button.id) {
// don't need case 0 anymore, that's the default
case 1:
newReligion = PantheonReference.GREEK;
break;
case 2:
newReligion = PantheonReference.NORSE;
break;
.
.
. etc.
}
PantheonCraft.packetPipeline.sendToServer(new UpdateReligionPacket(newReligion));
}

UpdateReligionPacket writes the religion to the buffer, reads it back in, and then uses that religion to set both the ItemTalisman and ExtendedProperties data, on the SERVER.

Link to comment
Share on other sites

For some reason this is giving me null and 0 all the time. I even tried using lists but that doesn't work either.

package com.xetosphere.pantheon.network.packet;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ChatComponentText;

import com.xetosphere.pantheon.entity.ExtendedPlayer;
import com.xetosphere.pantheon.network.AbstractPacket;

import cpw.mods.fml.common.network.ByteBufUtils;

public class UpdateReligionPacket extends AbstractPacket {

private NBTTagCompound data;
private String religion;
private int religionId;

public UpdateReligionPacket() {
}

public UpdateReligionPacket(String religion, int religionId) {

	data = new NBTTagCompound();
	setReligion(religion);
	setReligionId(religionId);
}

public void setReligion(String religion) {

	this.religion = religion;
}

public void setReligionId(int religionId) {

	this.religionId = religionId;
}

public String getReligion() {

	return religion;
}

public int getReligionId() {

	return religionId;
}

@Override
public void encodeInto(ChannelHandlerContext ctx, ByteBuf buffer) {

	ByteBufUtils.writeTag(buffer, data);
}

@Override
public void decodeInto(ChannelHandlerContext ctx, ByteBuf buffer) {

	data = ByteBufUtils.readTag(buffer);
}

@Override
public void handleClientSide(EntityPlayer player) {

}

@Override
public void handleServerSide(EntityPlayer player) {

	System.out.println(getReligion() + ", " + getReligionId());
	ExtendedPlayer.get(player).setPantheon(getReligion());
	ExtendedPlayer.get(player).setPantheonId(getReligionId());
	if (!player.worldObj.isRemote) player.addChatComponentMessage(new ChatComponentText("You set your pantheon to: " + ExtendedPlayer.get(player).getPantheon()));
	System.out.println("[XETOPC] Pantheon = " + ExtendedPlayer.get(player).getPantheon());
	System.out.println("[XETOPC] PantheonId = " + ExtendedPlayer.get(player).getPantheonId());
}

}

 

Link to comment
Share on other sites

For some reason this is giving me null and 0 all the time. I even tried using lists but that doesn't work either.

You never add any data to the NBTTagCompound, which you don't even need since you can write the int and String directly to the output stream, and read them back in. You don't need getter and setter methods because you will never be (should never be) trying to access your variables outside of this class.

Link to comment
Share on other sites

For some reason this is giving me null and 0 all the time. I even tried using lists but that doesn't work either.

You never add any data to the NBTTagCompound, which you don't even need since you can write the int and String directly to the output stream, and read them back in. You don't need getter and setter methods because you will never be (should never be) trying to access your variables outside of this class.

Thank you, I forgot I could use the NBTTagCompound to store the values (I am very stupid sometimes). Everything works as it should now, I really appreciate your help.
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.