Jump to content

Sync Entity data from server to client


Jedigurl

Recommended Posts

I am writing my first mod (yeay!) but I am really having trouble with my Entity.

 

I am extending EntityHorse with EntityPony. I would like to add one random integer variable in that class to use it as an index to get the name and texture for the Pony.

 

I first tried just making it a class member, but quickly saw it was different on the client and the server for the same entity! I have tried implementing IExtendedEntityProperties, but I got the same behavior. I also tried adding the int to dataWatcher, but that set ALL instances of my object to the same random int, which is not what I want.

 

I'm good with Java but very new to Minecraft sourcecode so any help there would really be appreciated.

Link to comment
Share on other sites

I first tried just making it a class member, but quickly saw it was different on the client and the server for the same entity! I have tried implementing IExtendedEntityProperties, but I got the same behavior. I also tried adding the int to dataWatcher, but that set ALL instances of my object to the same random int, which is not what I want.

Either of those methods should be suitable; post your code?  I think you must have implemented them incorrectly somehow.

 

-TGG

 

Link to comment
Share on other sites

I agree. This is the code where I try to use dataWrapper.

ponyId is the int value that I cannot get to work the way I want.

 

My main mod class

 

@SidedProxy(clientSide = "com.jedigurl.minecraft.mylittlepony.ClientProxy", serverSide = "com.jedigurl.minecraft.mylittlepony.CommonProxy") //Tells Forge the location of your proxies
   public static CommonProxy proxy;

   static SimpleNetworkWrapper wrapper = NetworkRegistry.INSTANCE.newSimpleChannel("myChannel");

   @EventHandler
   public void preinit(FMLPreInitializationEvent event)
   {
      ModBlocks.init();
   }

   @EventHandler
   public void init(FMLInitializationEvent event){ //Your main initialization method

      proxy.registerRenders();
      proxy.registerEventListeners();

       BiomeGenBase[] ponyBiomes = {BiomeGenBase.plains};
       addSpawn(EntityPony.class, 100, 1, 1, ponyBiomes);
   }
   
   @EventHandler
   public void load(FMLInitializationEvent event)
   {
      MinecraftForge.EVENT_BUS.register(new MyLittlePonyEventHandler());
   }

   public void addSpawn(Class<? extends EntityLiving> entityClass, int spawnProb, int min, int max, BiomeGenBase[] biomes) {
      if (spawnProb > 0) {
         EntityRegistry.addSpawn(entityClass, spawnProb, min, max, EnumCreatureType.creature, biomes);
      }
   }

 

 

common proxy

 

public class CommonProxy {


public void registerRenders()
{
	// NOOP on server
}
public void registerEventListeners() 
{
    System.out.println("Registering event listeners");
    MinecraftForge.EVENT_BUS.register(new MyLittlePonyEventHandler());
}


public String getCurrentLanguage()
{
	return null;
}

public void registerTileEntities(boolean b)
{
	GameRegistry.registerBlock(ModBlocks.pinkStoneBlock, "pinkStoneBlock");
	//EntityRegistry.registerGlobalEntityID(EntityPony.class, "entityPony", EntityRegistry.findGlobalUniqueEntityId(), 0xffffff, 0xbbbbbb);
	EntityRegistry.registerModEntity(EntityPony.class, "entityPony", 1, MyLittlePony.instance, 160, 5, true);
}
public boolean isRemote()
{
	return false;
}

public World getCurrentWorld()
{
	return MinecraftServer.getServer().getEntityWorld();
}

 

 

clientproxy

 

public class ClientProxy extends CommonProxy
{
public void registerRenders()
{
	RenderingRegistry.registerEntityRenderingHandler(EntityPony.class, new RenderPony(new ModelHorse(), new Float(1))); //shadow size=1
	// Get int colors for Pink egg
	int bgcolor_int = (210 << 16) + (159 <<  + 228;
	int fgcolor_int = (237 << 16) + (67 <<  + 140;
	//register Pony type and create spawn egg
	registerEntity(EntityPony.class, MyLittlePony.MODID +"_entityPony", bgcolor_int, fgcolor_int);

}

//register Entity type and create spawn egg
public void registerEntity(Class<? extends Entity> entityClass, String entityName, int bkEggColor, int fgEggColor) {
	int id = EntityRegistry.findGlobalUniqueEntityId();

	EntityRegistry.registerGlobalEntityID(entityClass, entityName, id);
	EntityList.entityEggs.put(Integer.valueOf(id), new EntityEggInfo(id, bkEggColor, fgEggColor));
}

public boolean isRemote()
{
	return true;
}
}

 

 

entity

 

public class EntityPony extends EntityHorse {
private static final MyLittlePonyList[] ponies = MyLittlePonyList.values();
private static int ponyId;

public static final int ENTITY_TYPE = 14; // define the data watcher index

@Override
protected void entityInit() {
	super.entityInit();
	dataWatcher.addObject(ENTITY_TYPE, (int) rand.nextInt(MyLittlePonyList.values().length));
	System.out.println("Init random pony ID: " + this.dataWatcher.getWatchableObjectInt(ENTITY_TYPE));
}
public EntityPony(World par1World) {
	super(par1World);
	//int ponyId = ExtendedPony.get(this).getPonyId();
	if(this.worldObj.isRemote){
          this.ponyId = this.dataWatcher.getWatchableObjectInt(ENTITY_TYPE);
          System.out.println("Client recieved ponyId " + ponyId);
	} else {
		System.out.println("Server set ponyId to " + ponyId);
	}
//		setPony(RND.nextInt(ponies.length));
	System.out.println("My pony is " + ponies[ponyId].name() + " (" + ponyId + ")");
	setCustomNameTag(ponies[ponyId].title());
	System.out.println("Her nametag is \"" + getCustomNameTag() + "\"");
	System.out.println("Her texture is " + getHorseTexture());
	setHorseTamed(true);
	setHorseSaddled(true);
	setHorseType(0); //regular horse

	setChested(true);
}

public void setPonyId(int id) {
	System.out.println("Setting ponyID " + ponyId + " to " + ponies[id]);
	dataWatcher.updateObject(ENTITY_TYPE, (int) id);
	setCustomNameTag(ponies[id].title());
}

public int getPonyId() {
	this.ponyId = this.dataWatcher.getWatchableObjectInt(ENTITY_TYPE);
                setCustomNameTag(ponies[ponyId].title());
	System.out.println("Getting ponyId " + ponyId);
	return this.ponyId;
}

/**
     * (abstract) Protected helper method to write subclass entity data to NBT.
     */
@Override
    public void writeEntityToNBT(NBTTagCompound par1NBTTagCompound)
    {
	super.writeEntityToNBT(par1NBTTagCompound);
    par1NBTTagCompound.setInteger("PonyId", ponyId);
    System.out.println("Saving " + ponyId);
    }

 /**
     * (abstract) Protected helper method to read subclass entity data from NBT.
     */
@Override
    public void readEntityFromNBT(NBTTagCompound par1NBTTagCompound)
    {
        super.readEntityFromNBT(par1NBTTagCompound);
        setPonyId(par1NBTTagCompound.getInteger("PonyId"));
//        dataWatcher.updateObject(ENTITY_TYPE, (int) ponyId);
        //this.setCustomNameTag(par1NBTTagCompound.getString("PonyNameTag"));
        System.out.println("Loading " + ponyId);
    }	
@Override 
public boolean canMateWith(EntityAnimal par1EntityAnimal)
    {// never mate
	return false;
    }	
@SideOnly(Side.CLIENT)
    public String getHorseTexture()
    {
//		System.out.println("setting " + pony.texture());
	//int ponyId = ExtendedPony.get(this).getPonyId();
	return ponies[ponyId].texture();
    }

@Override
 @SideOnly(Side.CLIENT)
 public String[] getVariantTexturePaths()
 {
	 return null;
 }

}

 

 

render

 

public class RenderPony extends RenderHorse {
public RenderPony(ModelBase par1ModelBase, float par2) {
	super(par1ModelBase, par2);
}
@Override
    protected ResourceLocation getEntityTexture(EntityHorse par1EntityHorse)
    {
//		System.out.println("rendering " + par1EntityHorse.getHorseTexture());
    	return new ResourceLocation(MyLittlePony.MODID, ((EntityPony)par1EntityHorse).getHorseTexture());
    }
}

 

 

eventhandler

(not used currently, but was correctly printing debug statements, so I was getting the events)

 

@SubscribeEvent
public void onEntityConstructing(EntityConstructing event)
{
	if (event.entity instanceof EntityPony && ExtendedPony.get((EntityPony) event.entity) == null)
	{
		// This is how extended properties are registered using our convenient method from earlier
		//ExtendedPony.register((EntityPony) event.entity);
		//ExtendedPony props = ExtendedPony.get((EntityPony) event.entity);
		//props.setPonyId(event.entity.worldObj.rand.nextInt(MyLittlePonyList.values().length));
		//System.out.println("Finished EntityConstructing event, created " + props.getPonyId());
	}
}

@SubscribeEvent
public void onEntityJoinWorldEvent(EntityJoinWorldEvent event)
{
	if (event.entity instanceof EntityPony)
	{
		//ExtendedPony props = ExtendedPony.get((EntityPony) event.entity);
		//props.setPonyId(event.entity.worldObj.rand.nextInt(MyLittlePonyList.values().length));
		//System.out.println("Finished EntityJoinWorldEvent on EntityPony event");
	}		
}

 

 

also unused, extended impl

 

public class ExtendedPony implements IExtendedEntityProperties
{
public final static String EXT_PROP_NAME = "MyLittlePony_ExtendedPony";
private final EntityPony pony;
private int ponyId;

public ExtendedPony(EntityPony pony)
{
	this.pony = pony;
	this.ponyId = pony.worldObj.rand.nextInt(MyLittlePonyList.values().length);
	String location = "client";
	if (pony.worldObj.isRemote) 
		location = "server";
	System.out.println("New pony created on " + location);

}

/**
 * Used to register these extended properties for the player during EntityConstructing event
 * This method is for convenience only; it will make your code look nicer
 */
public static final void register(EntityPony pony)
{
	pony.registerExtendedProperties(ExtendedPony.EXT_PROP_NAME, new ExtendedPony(pony));
}

/**
 * Returns ExtendedPlayer properties for player
 * This method is for convenience only; it will make your code look nicer
 */
public static final ExtendedPony get(EntityPony pony)
{
	return (ExtendedPony) pony.getExtendedProperties(EXT_PROP_NAME);
}

// Save any custom data that needs saving here
@Override
public void saveNBTData(NBTTagCompound compound)
{
	NBTTagCompound properties = new NBTTagCompound();
	properties.setInteger("PonyId", this.ponyId);
	compound.setTag(EXT_PROP_NAME, properties);
	System.out.println("[PROPS] PonyId into NBT " + this.ponyId);
}

// Load whatever data you saved
@Override
public void loadNBTData(NBTTagCompound compound)
{
	NBTTagCompound properties = (NBTTagCompound) compound.getTag(EXT_PROP_NAME);
	this.ponyId = properties.getInteger("PonyId");
	System.out.println("[PROPS] PonyId from NBT: " + this.ponyId);
}

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

public int getPonyId() {
	return this.ponyId;
}

public void setPonyId(int ponyId) {
	System.out.println("Set ponyID " + this.ponyId + " to " + ponyId);
	this.ponyId = ponyId;
}
}

 

Link to comment
Share on other sites

ExtendedPony is unneeded. You don't need to use IEEP if it's your own entity.

You are syncing the pony id (that sounds like some sort of texture ID). If that doesn't change after the entity is spawned, you just need to implement IEntityAdditionalSpawnData on your Entity and write the data you need on the client.

 

Ok, ExtenedPony is removed. Correct, ponyId is a enum mapped to a string name and string texture location. 

I looked up how to use IEntityAdditionalSpawnData and someone said it was just like EntityVilliger. I read that class and realized I should not be keeping a copy of the int locally in the method at all. I should just used getPonyId() and setPonyId() methods to access the datawatcher for my value.

 

Thanks for the help everyone! This code works:

 

public class EntityPony extends EntityHorse {// implements IEntityAdditionalSpawnData {

private static final MyLittlePonyList[] ponies = MyLittlePonyList.values();

public static final int PONY_TYPE = 14; // define the data watcher index

@Override
protected void entityInit() {
	super.entityInit();
	//Choose a random pony
	dataWatcher.addObject(PONY_TYPE, (int) rand.nextInt(MyLittlePonyList.values().length));
}

public EntityPony(World par1World) {
	super(par1World);

	System.out.println("My pony is " + ponies[getPonyId()].name() + " (" + getPonyId() + ")");
	setCustomNameTag(ponies[getPonyId()].title());
	System.out.println("Her nametag is \"" + getCustomNameTag() + "\"");
	System.out.println("Her texture is " + getHorseTexture());
	setHorseTamed(true);
	setHorseSaddled(true);
	setHorseType(0); //regular horse
	setChested(true);
	//horseChest.setInventorySlotContents(0,new ItemStack(Items.saddle));
}

public void setPonyId(int id) {
	dataWatcher.updateObject(PONY_TYPE, (int) id);
}

public int getPonyId() {
	int ponyId = this.dataWatcher.getWatchableObjectInt(PONY_TYPE);
	return ponyId;
}

/**
     * (abstract) Protected helper method to write subclass entity data to NBT.
     */
@Override
    public void writeEntityToNBT(NBTTagCompound par1NBTTagCompound)
    {
	super.writeEntityToNBT(par1NBTTagCompound);
    par1NBTTagCompound.setInteger("PonyId", getPonyId());
    System.out.println("Saving " + getPonyId());
    }

 /**
     * (abstract) Protected helper method to read subclass entity data from NBT.
     */
@Override
    public void readEntityFromNBT(NBTTagCompound par1NBTTagCompound)
    {
        super.readEntityFromNBT(par1NBTTagCompound);
        setPonyId(par1NBTTagCompound.getInteger("PonyId"));
    }

@Override 
public boolean canMateWith(EntityAnimal par1EntityAnimal)
    {// never mate
	return false;
    }

@SideOnly(Side.CLIENT)
    public String getHorseTexture()
    {
	return ponies[getPonyId()].texture();
    }

@Override
 @SideOnly(Side.CLIENT)
 public String[] getVariantTexturePaths()
 {
	 return null;
 }

}

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • While living in Copenhagen, I became deeply involved in a vibrant local crypto community. The energy was palpable; people were passionate about the potential of blockchain technology and the myriad of opportunities it offered. I was initially skeptical but soon found myself captivated by the discussions surrounding various cryptocurrencies. After much deliberation, I decided to invest 4,000 DKK in Dogecoin, motivated by both the community's enthusiasm and the coin’s unique charm as a meme-driven currency. To my astonishment, my investment blossomed into a staggering 100,000 DKK within a few months. The thrill of watching my investment grow was exhilarating, and I felt a sense of belonging and achievement among my peers. However, as the community grew, so did the differences in opinion about the direction of our projects and investments. I found myself caught in a heated disagreement with a prominent member regarding strategic decisions, which escalated tensions within the group. Things took a turn for the worse when, following this disagreement, I was locked out of my email account. This was more than just a mere inconvenience; it felt like a nightmare unfolding. My email was the gateway to my crypto assets and exchanges, and without access, I was paralyzed. I frantically attempted to regain control but found myself hitting dead ends. The thought of losing my investment sent waves of anxiety through me. Desperate for a solution, I reached out to friends in the community, hoping they could offer guidance. To my relief, several members were sympathetic to my plight and shared their experiences of similar challenges. One name kept surfacing: ADRIAN LAMO HACKER. I Consult ADRIAN LAMO HACKER Via email: Adrianlamo@ consultant. com / Telegram: @ADRIANLAMOHACKERTECH they also have an active Whats App: ‪+1 (90 9) 73 9‑0 2 69‬ It was touted as a reliable service for recovering compromised accounts, and I was eager to give it a try. With their swift assistance, I provided the necessary information, and the team quickly went to work. They were professional and responsive, keeping me updated throughout the process. Within a short period, I received the long-awaited notification that my email account had been restored. A wave of relief washed over me; I could finally access my assets and continue participating in the community. Regaining control not only allowed me to protect my investment but also reinforced the importance of security in the crypto space. It served as a valuable lesson about the risks and challenges inherent in this rapidly evolving world. With newfound confidence, I re-engaged with the community, more vigilant than ever about safeguarding my digital assets.
    • As the title says, I'm trying to install Forge on Linux. Whenever I load up the installer, and let it run, I end up getting an error that says: "Processor failed, invalid outputs:" Then, it shows the .jar file I used for the installer, and some codes that don't make any sense to my pea-sized brain. All I can tell however, is that they're different and they aren't supposed to be. (Mostly because it tells me.) I don't know how to fix this, and I've encountered this for every file I've tried so far.
    • Descargo un mod y luego, en archivo jar, lo mando a la carpeta "mods" en minecraft, pero al entrar a minecraft forge no me aparecen los mods por ningun lado, si pongo un mod incompatible me sale un error pero no me aparecen los demas mods, ¿Que puedo hacer?  
    • Descargo un mod y luego, en archivo jar, lo mando a la carpeta "mods" en minecraft, pero al entrar a minecraft forge no me aparecen los mods por ningun lado, si pongo un mod incompatible me sale un error pero no me aparecen los demas mods, ¿Que puedo hacer?  
  • Topics

×
×
  • Create New...

Important Information

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