Jump to content

Recommended Posts

Posted

Im working on an energysystem in my mod atm and a really weird bug accurd - when i connect the blocks with each other (using a variable in IEEP), then at some point the tileentity they are connected to is the same for all of them and sometimes even a tileentity that is not in the circuit. I don't know if the bug is positioned in the saving of the coordinates or somewhere else. Hopefully someone can help me fix this. Here are the classes i use:

TileEntity_Electric:

 

 

package itsamysterious.mods.reallifemod.core.blocks.tiles;

 

import itsamysterious.mods.reallifemod.core.tiles.RLMTileEntity;

import net.minecraft.nbt.NBTTagCompound;

import net.minecraft.server.gui.IUpdatePlayerListBox;

import net.minecraft.tileentity.TileEntity;

import net.minecraft.util.BlockPos;

 

public class TileEntity_Electric extends RLMTileEntity implements IUpdatePlayerListBox{

public TileEntity_Electric from;

private float voltage;

private int age;

private boolean isConnected;

 

public TileEntity_Electric(String string) {

super(string);

 

}

 

public TileEntity_Electric(String string, int i) {

this(string);

this.rotation=i;

}

 

@Override

public void update() {

    if(from!=null){

    voltage = from.getVoltageValue();

    isConnected=true;

    }else{

    isConnected=false;

    }

   

}

 

 

    @Override

    public void writeToNBT(NBTTagCompound compound){

    NBTTagCompound tag=new NBTTagCompound();

    compound.setTag("RLMElectrizityTag", tag);

    if(from!=null){

    BlockPos pto = from.getPos();

    tag.setIntArray("ConectedTo", new int[]{pto.getX(),pto.getY(),pto.getZ()});

    }

    super.writeToNBT(compound);

 

    }

   

    @Override

    public void readFromNBT(NBTTagCompound compound) {

    super.readFromNBT(compound);

    NBTTagCompound rlmtag = compound.getCompoundTag("RLMTileTag");

    NBTTagCompound tag=rlmtag.getCompoundTag("RLMElectrizityTag");

    int[] i = tag.getIntArray("ConectedTo");

    if(i.length==3){

    //if(worldObj.isRemote&&worldObj.getTileEntity(new BlockPos(i[0],i[1],i[2])) instanceof TileEntity_Electric){

        //this.connectTo((TileEntity_Electric)worldObj.getTileEntity(new BlockPos(i[0],i[1],i[2])));

    // }

    }

worldObj.markBlockForUpdate(getPos());

    this.rotation=tag.getFloat("Rotation");

    }

 

public void connectTo(TileEntity_Electric t){

this.from = t;

}

 

public float getVoltageValue() {

float value=voltage;

this.voltage=0;

return value;

}

 

public float getVoltage() {

return voltage;

}

 

public void setVoltage(float voltage) {

this.voltage = voltage;

}

 

}

 

 

 

 

ItemCable(Connects the BLocks up):

 

 

package itsamysterious.mods.reallifemod.core.items;

 

import itsamysterious.mods.reallifemod.core.RealLifeMod_Blocks;

import itsamysterious.mods.reallifemod.core.blocks.tiles.TileEntity_Electric;

import itsamysterious.mods.reallifemod.core.lifesystem.RLMPlayerProps;

import net.minecraft.block.BlockAir;

import net.minecraft.client.Minecraft;

import net.minecraft.entity.Entity;

import net.minecraft.entity.player.EntityPlayer;

import net.minecraft.item.Item;

import net.minecraft.item.ItemStack;

import net.minecraft.util.BlockPos;

import net.minecraft.util.ChatComponentText;

import net.minecraft.util.EnumChatFormatting;

import net.minecraft.world.World;

import net.minecraftforge.fml.common.registry.GameRegistry;

 

public class ItemCable extends Item{

 

public ItemCable() {

setUnlocalizedName("ItemCable");

GameRegistry.registerItem(this, getUnlocalizedName().substring(5));

}

 

@Override

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

BlockPos pos = Minecraft.getMinecraft().objectMouseOver.getBlockPos();

RLMPlayerProps props = RLMPlayerProps.get(player);

if(world.getTileEntity(pos) instanceof TileEntity_Electric){

TileEntity_Electric toConnectTile = (TileEntity_Electric) world.getTileEntity(pos);

if(props.lastTile!=null&&props.lastTile!=toConnectTile){

toConnectTile.connectTo(props.lastTile);

props.lastTile=toConnectTile;

}

else{

player.addChatMessage(new ChatComponentText("Now in "+EnumChatFormatting.GREEN+"Connection Mode"+EnumChatFormatting.RESET+"To stop connecting, hold SHIFT+RIGHTCLICK! "));

props.lastTile = toConnectTile;

}

 

}else

{

if(world.getBlockState(pos).getBlock() instanceof BlockAir){

player.addChatMessage(new ChatComponentText("Stopped "+EnumChatFormatting.RED+"Connection Mode"));

props.lastTile=null;

}else

{

world.setBlockState(pos, RealLifeMod_Blocks.cable.getDefaultState());

}

 

}

return stack;

}

 

}

 

 

 

 

and some tileentities that extend TileEntity_Electric-perhaps the bug is in here:

LanternTileEntity

 

 

package itsamysterious.mods.reallifemod.core.blocks.tiles;

 

import itsamysterious.mods.reallifemod.core.tiles.RLMTileEntity;

import net.minecraft.block.state.IBlockState;

import net.minecraft.client.Minecraft;

import net.minecraft.nbt.NBTTagCompound;

import net.minecraft.network.NetworkManager;

import net.minecraft.network.Packet;

import net.minecraft.network.play.server.S35PacketUpdateTileEntity;

import net.minecraft.util.AxisAlignedBB;

import net.minecraft.util.BlockPos;

import net.minecraft.world.World;

 

public class TileEntity_Lantern extends TileEntity_Electric {

public float rotation;

public boolean isActive;

 

public TileEntity_Lantern() {

super("LanternTileentity");

}

 

public TileEntity_Lantern(int i) {

super("LanternTileentity");

float rot = i*90;

System.out.println(i);

this.rotation=rot;

}

 

    @Override

    public void writeToNBT(NBTTagCompound compound){

    NBTTagCompound tag=new NBTTagCompound();

    tag.setBoolean("IsActive", isActive);

    tag.setFloat("Rotation", rotation);

    compound.setTag("LanternTag", tag);

    super.writeToNBT(compound);

 

    }

   

    @Override

    public void readFromNBT(NBTTagCompound compound) {

    super.readFromNBT(compound);

    NBTTagCompound tag=compound.getCompoundTag("LanternTag");

    this.isActive=tag.getBoolean("IsActive");

    this.rotation=tag.getFloat("Rotation");

    }

 

    @Override

    public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt)

    {

      NBTTagCompound tag = pkt.getNbtCompound();

      readFromNBT(tag);

    }

   

    public Packet getDescriptionPacket()

    {

      NBTTagCompound tag = new NBTTagCompound();

      writeToNBT(tag);

      return new S35PacketUpdateTileEntity(getPos(), 1, tag);

    }

   

    @Override

    public void update(){

    super.update();

    if(getVoltage()>0){

    isActive=true;

    }else

    isActive=false;

   

    if(isActive){

    worldObj.getBlockState(getPos()).getBlock().setLightLevel(100.0f);

    }else

    {

    worldObj.getBlockState(getPos()).getBlock().setLightLevel(0);

    }

   

    }

   

    public AxisAlignedBB getRenderBoundingBox(){

return super.getRenderBoundingBox();

    }

}

 

 

 

 

TileEntity_Powerline:

 

 

public float rotation;

public boolean isActive;

int[] p;

 

public TileEntity_PowerLine() {

super("PowerLineTileEntity");

}

 

@Override

public boolean shouldRefresh(World world, BlockPos pos, IBlockState oldState, IBlockState newState) {

return (oldState.getBlock() != newState.getBlock());

}

 

public TileEntity_PowerLine(int i) {

this();

float rot = i*90;

System.out.println(i);

this.rotation=rot;

}

 

@Override

public void updateContainingBlockInfo() {

super.updateContainingBlockInfo();

 

}

 

    @Override

    public void writeToNBT(NBTTagCompound compound){

    NBTTagCompound tag=new NBTTagCompound();

    tag.setBoolean("IsActive", isActive);

    tag.setFloat("Rotation", rotation);

    compound.setTag("PowerLineTag", tag);

    super.writeToNBT(compound);

 

    }

   

    @Override

    public void readFromNBT(NBTTagCompound compound) {

    super.readFromNBT(compound);

    NBTTagCompound tag=compound.getCompoundTag("PowerLineTag");

    this.isActive=tag.getBoolean("IsActive");

    this.rotation=tag.getFloat("Rotation");

    p=tag.getIntArray("TilePos");

    }

 

    @Override

    public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt)

    {

      NBTTagCompound tag = pkt.getNbtCompound();

      readFromNBT(tag);

    }

   

    public Packet getDescriptionPacket()

    {

      NBTTagCompound tag = new NBTTagCompound();

      writeToNBT(tag);

      return new S35PacketUpdateTileEntity(getPos(), 1, tag);

    }

   

    public AxisAlignedBB getRenderBoundingBox(){

return super.getRenderBoundingBox().expand(1000, 1000, 1000);

    }

   

    @Override

    public void update() {

    super.update();

    }

   

    @Override

    public float getVoltageValue() {

    return this.getVoltage();

    }

 

}

 

 

 

  • Replies 82
  • Created
  • Last Reply

Top Posters In This Topic

Posted

public class ItemCable extends Item{
private static TileEntity_Electric lastTile;

 

i told you this already in two other posts. DONT USE STATIC if you have NO idea what it is doing. Dont save variables in the item classs u need to use NBT if u want them to save data

Posted

Yes, i updated all my tiles so that the rotation is being set in OnBlockPlaced by and is initially set too zero. No i only have one constructor that looks like this:

 

public TileEntityElectric(){

  super("TileEntityElectric");

}

 

OH - maybe i can solve the problem if i register TileEntityElectric? Cuz its just a class that is never use as itself - only as extended class?

Posted

Nah didn't solved it. I reworked some of the methods and classes but now some of the tileentities immediatly disappear after placing. I think it is caused by wrong saving to NBT. Here is the baseclass and the not working subclssses:

 

Baseclass:

 

 

package itsamysterious.mods.reallifemod.core.blocks.tiles;

 

import itsamysterious.mods.reallifemod.core.tiles.RLMTileEntity;

import net.minecraft.nbt.NBTTagCompound;

import net.minecraft.server.gui.IUpdatePlayerListBox;

import net.minecraft.util.BlockPos;

import net.minecraft.world.World;

 

public abstract class TileEntity_Electric extends RLMTileEntity implements IUpdatePlayerListBox{

public TileEntity_Electric to;

private float voltage;

private int age;

 

public TileEntity_Electric(String string) {

super(string);

}

 

@Override

public void update() {

if (!this.hasWorldObj()) return;

World world = this.getWorld();

if (world.isRemote) return; 

 

 

    if(to!=null){

    to.setVoltage(onPowered(voltage));

    }   

worldObj.markBlockForUpdate(getPos());

}

 

 

    @Override

    public void writeToNBT(NBTTagCompound compound){

    NBTTagCompound tag=new NBTTagCompound();

    if(to!=null){

    BlockPos pto = to.getPos();

    NBTTagCompound blockPosNBT = new NBTTagCompound();       

    blockPosNBT.setInteger("x", pto.getX());

    blockPosNBT.setInteger("y", pto.getY());

    blockPosNBT.setInteger("z", pto.getZ());

    compound.setTag("connectedBlock", blockPosNBT);   

    }

    compound.setTag("RLMElectrizityTag", tag);

    }

   

    @Override

    public void readFromNBT(NBTTagCompound compound) {

    super.readFromNBT(compound);

 

    final int NBT_INT_ID = 3;

 

    NBTTagCompound tag=compound.getCompoundTag("RLMElectrizityTag");

   

    NBTTagCompound blockPosNBT = compound.getCompoundTag("connectedBlock");

BlockPos readBlockPos = null;

if (blockPosNBT.hasKey("x", NBT_INT_ID) && blockPosNBT.hasKey("y", NBT_INT_ID) && blockPosNBT.hasKey("z", NBT_INT_ID) ) {

readBlockPos = new BlockPos(blockPosNBT.getInteger("x"), blockPosNBT.getInteger("y"), blockPosNBT.getInteger("z"));

}

if (readBlockPos == null ) {

System.err.println("testBlockPos mismatch:" + readBlockPos);

}

if(readBlockPos!=null&&worldObj.getTileEntity(readBlockPos) instanceof TileEntity_Electric){

this.to = (TileEntity_Electric) worldObj.getTileEntity(readBlockPos);

}

    }

 

public void connectTo(TileEntity_Electric t){

this.to = t;

}

 

public float getVoltageValue() {

return voltage;

}

 

public float getVoltage() {

return voltage;

}

 

public void setVoltage(float voltage) {

this.voltage = voltage;

}

 

public float onPowered(float f){

worldObj.markBlockForUpdate(getPos());

return f;

}

 

}

 

 

 

 

Subclass:

 

 

package itsamysterious.mods.reallifemod.core.blocks.tiles;

 

import net.minecraft.nbt.NBTTagCompound;

import net.minecraft.network.NetworkManager;

import net.minecraft.network.Packet;

import net.minecraft.network.play.server.S35PacketUpdateTileEntity;

import net.minecraft.util.AxisAlignedBB;

import scala.collection.generic.VolatileAbort;

 

public class TileEntity_Lantern extends TileEntity_Electric {

public boolean isActive;

 

public TileEntity_Lantern() {

super("LanternTileentity");

}

 

    @Override

    public void writeToNBT(NBTTagCompound compound){

    super.writeToNBT(compound);

    NBTTagCompound tag=new NBTTagCompound();

    tag.setBoolean("IsActive", isActive);

    compound.setTag("LanternTag", tag);

 

    }

   

    @Override

    public void readFromNBT(NBTTagCompound compound) {

    super.readFromNBT(compound);

    NBTTagCompound tag=compound.getCompoundTag("LanternTag");

    this.isActive=tag.getBoolean("IsActive");

    }

 

    @Override

    public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt)

    {

      NBTTagCompound tag = pkt.getNbtCompound();

      readFromNBT(tag);

    }

   

    public Packet getDescriptionPacket()

    {

      NBTTagCompound tag = new NBTTagCompound();

      writeToNBT(tag);

      return new S35PacketUpdateTileEntity(getPos(), 1, tag);

    }

   

    @Override

    public void update(){

    super.update();

    if(getVoltage()>0){

    isActive=true;

    }else

    isActive=false;

   

    if(isActive){

    worldObj.getBlockState(getPos()).getBlock().setLightLevel(100.0f);

    }else

    {

    worldObj.getBlockState(getPos()).getBlock().setLightLevel(0);

    }

   

    }

   

    public AxisAlignedBB getRenderBoundingBox(){

return super.getRenderBoundingBox();

    }

 

@Override

public float onPowered(float f) {

    if(isActive){

    worldObj.getBlockState(getPos()).getBlock().setLightLevel(100.0f);

    }else

    {

    worldObj.getBlockState(getPos()).getBlock().setLightLevel(0);

    }

this.setVoltage(f);

return f;

}

 

}

 

 

 

 

Subclass 2:

 

 

package itsamysterious.mods.reallifemod.core.blocks.tiles;

 

import itsamysterious.mods.reallifemod.core.blocks.electrisity.BlockPowerLine;

import itsamysterious.mods.reallifemod.core.tiles.RLMTileEntity;

import net.minecraft.block.state.IBlockState;

import net.minecraft.client.Minecraft;

import net.minecraft.entity.player.EntityPlayer;

import net.minecraft.nbt.NBTTagCompound;

import net.minecraft.network.NetworkManager;

import net.minecraft.network.Packet;

import net.minecraft.network.play.server.S35PacketUpdateTileEntity;

import net.minecraft.tileentity.TileEntity;

import net.minecraft.util.AxisAlignedBB;

import net.minecraft.util.BlockPos;

import net.minecraft.world.World;

 

public class TileEntity_PowerLine extends TileEntity_Electric{

 

public TileEntity_PowerLine() {

super("PowerLineTileEntity");

}

 

@Override

public boolean shouldRefresh(World world, BlockPos pos, IBlockState oldState, IBlockState newState) {

return (oldState.getBlock() != newState.getBlock());

}

 

    @Override

    public void writeToNBT(NBTTagCompound compound){

    super.writeToNBT(compound);

    }

   

    @Override

    public void readFromNBT(NBTTagCompound compound) {

    super.readFromNBT(compound);

    }

 

    @Override

    public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt)

    {

      NBTTagCompound tag = pkt.getNbtCompound();

      readFromNBT(tag);

    }

   

    public Packet getDescriptionPacket()

    {

      NBTTagCompound tag = new NBTTagCompound();

      writeToNBT(tag);

      return new S35PacketUpdateTileEntity(getPos(), 1, tag);

    }

   

    public AxisAlignedBB getRenderBoundingBox(){

return super.getRenderBoundingBox();

    }

   

    @Override

    public void update() {

    super.update();

    }

   

@Override

public float onPowered(float f) {

return f;

}

 

}

 

 

 

Posted

OMG - MY stupidness solved the disappearing - i forgot to do super.writeToNBT() in TileENtity_Electric witch caused that all entities without NBT were okay and those with NBT where removed. But now the saving of the connected tile won't work. I try writing the BlockPos of the tile to NBT like this:

 

 

 

    @Override

    public void writeToNBT(NBTTagCompound compound){

    super.writeToNBT(compound);

    NBTTagCompound tag=new NBTTagCompound();

    if(to!=null){

    BlockPos pto = to.getPos();

    NBTTagCompound blockPosNBT = new NBTTagCompound();       

    blockPosNBT.setInteger("x", pto.getX());

    blockPosNBT.setInteger("y", pto.getY());

    blockPosNBT.setInteger("z", pto.getZ());

    compound.setTag("connectedBlock", blockPosNBT);   

    }

    compound.setTag("RLMElectrizityTag", tag);

    }

   

    @Override

    public void readFromNBT(NBTTagCompound compound) {

    super.readFromNBT(compound);

 

    final int NBT_INT_ID = 3;

 

    NBTTagCompound tag=compound.getCompoundTag("RLMElectrizityTag");

   

    NBTTagCompound blockPosNBT = compound.getCompoundTag("connectedBlock");

BlockPos readBlockPos = null;

if (blockPosNBT.hasKey("x", NBT_INT_ID) && blockPosNBT.hasKey("y", NBT_INT_ID) && blockPosNBT.hasKey("z", NBT_INT_ID) ) {

readBlockPos = new BlockPos(blockPosNBT.getInteger("x"), blockPosNBT.getInteger("y"), blockPosNBT.getInteger("z"));

}

if(worldObj!=null&&readBlockPos!=null&&worldObj.getTileEntity(readBlockPos) instanceof TileEntity_Electric){

to = (TileEntity_Electric) worldObj.getTileEntity(readBlockPos);

}

    }

 

 

 

But when i close the world and open it again, the 'to' variable isn't set.

 

Posted

There is no world yet in

readFromNBT

.

 

So what im doing there atm will work in the future ? Cuz you say there is no fututre Yet. Also - the onBlockPlacedBy method i tried isn't working. Do i have to put it in the subclasses to?

 

public abstract class RLMBlockContainer extends Block implements ITileEntityProvider{

public RLMBlockContainer(Material materialIn) {
	super(materialIn);
}

@Override
public abstract TileEntity createNewTileEntity(World worldIn, int meta);

    public void onBlockPlacedBy(World worldIn, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack) {
    	super.onBlockPlacedBy(worldIn, pos, state, placer, stack);
    	 TileEntity tileentity = worldIn.getTileEntity(pos);
         if (tileentity instanceof RLMTileEntity){
        	 RLMTileEntity tile = (RLMTileEntity)tileentity;
        	 tile.rotation = 90 * MathHelper.floor_double((double)(placer.rotationYaw * 4.0F / 360.0F) + 0.5D) & 3;
        	 worldIn.markBlockForUpdate(pos);
             System.out.println("Succesfully rotated "+tile.getName());
         }
    }
    
    @SideOnly(Side.CLIENT)
    public EnumWorldBlockLayer getBlockLayer()
    {
      return EnumWorldBlockLayer.SOLID;
    }
    
    @Override
    public boolean isFullCube() {
    	return true;
    }

Posted

only read the position and access the tileentity when you need it

 

But i need to load it up immediatly, so the electrizity is being cast when player joines in world. So can i just set a global variable and in the update method put something like that:

 

if(to==null&&toCoords!=null){
  this.to=(TileEntity_Electric)worldObj.getTileEntity(toCoords);
}

Posted

I have no idea what you are trying to say with the "no future yet" stuff. Are you attempting time travel?

 

About the TE, use lazy initialization. And keeping a strong reference to the other TE is a bad idea, it will cause memory leaks.

Oh HAHA no :P Must have been thinking of something else and wrote future :) What i wanted to ask is if there will be a world in readFromNBT later.

And for the tile - what you mean with lazy initialization? And also the tile need to know where to send the signal to or not im not connecting the two blocks with redstone or simillar blocklike structurs but just with cables that are rendered in the TESR if the tile. Thats why i need the 'to' variable in the class (if you mean that with strong reference :P)

Posted

OH - i think you just solved the whole thing - is it possible that when the chunk was unloaded and then loaded again - the empty 'to' field is set to any other TileEntity_Electric? And also the thing with storing coordinates worked THANKS <3

Posted

This is how my TileEntity_Electric looks now - please tell me how i have to fix it im so lost on this i have absolutly no idea what im doing wrong :'(

I read that lazy initalization stuff but i do not understand the use of it e an also - how should i pass over the energy to the connected tile when i do not have a field.

 

MAN -IM SO LOST

 

Diesieben07 what you mean? How do i have to use that lazy stuff ?

 

package itsamysterious.mods.reallifemod.core.blocks.tiles;

import java.util.Random;

import itsamysterious.mods.reallifemod.core.tiles.RLMTileEntity;
import net.minecraft.client.Minecraft;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet;
import net.minecraft.network.play.server.S35PacketUpdateTileEntity;
import net.minecraft.server.gui.IUpdatePlayerListBox;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.world.World;

public abstract class TileEntity_Electric extends RLMTileEntity implements IUpdatePlayerListBox{
private float voltage;
private boolean isUsuable;
private int age;
public BlockPos storedPos;
private TileEntity_Electric to;

public TileEntity_Electric getTo() {
	return to;
}

public TileEntity_Electric(String string) {
	super(string);
	isUsuable=true;
}

@Override
public void update() {
	if (!this.hasWorldObj()) return;
	World world = this.getWorld();

	if(worldObj.isRemote){
		Random rand = new Random();
		if(!isUsuable){
			if(Minecraft.getMinecraft().thePlayer.ticksExisted%3==0)
			worldObj.spawnParticle(EnumParticleTypes.CLOUD, pos.getX()+0.5, pos.getY()+1, pos.getZ()+0.5, -0.025+rand.nextFloat()/10,rand.nextDouble()/5, -0.025+rand.nextFloat()/10);
		}
	}else
	{

		if(storedPos!=null){
			if(world.getTileEntity(storedPos)instanceof TileEntity_Electric){
				to=(TileEntity_Electric)world.getTileEntity(storedPos);
			}
		}

		if(voltage>getMaxVoltage()){
			isUsuable=false;
		}

    	if(to!=null){
    		to.setVoltage(onPowered(this.voltage));
			world.markBlockForUpdate(storedPos);
    	}   
    	if(storedPos!=null&&worldObj.getTileEntity(storedPos)==null){
    		to=null;
    		storedPos=null;
    	}
	}
}


    @Override
    public void writeToNBT(NBTTagCompound compound){
    	super.writeToNBT(compound);
    	NBTTagCompound tag=new NBTTagCompound();
    	if(storedPos!=null){
    		BlockPos pto = storedPos;
    		NBTTagCompound blockPosNBT = new NBTTagCompound();        
    		blockPosNBT.setInteger("x", pto.getX());
    		blockPosNBT.setInteger("y", pto.getY());
    		blockPosNBT.setInteger("z", pto.getZ());
    		tag.setTag("connectedBlock", blockPosNBT);    	
    	}
    	tag.setBoolean("IsUsuable", isUsuable);
    	compound.setTag("RLMElectrizityTag", tag);
    }
    
    @Override
    public void readFromNBT(NBTTagCompound compound) {
    	super.readFromNBT(compound);

    	final int NBT_INT_ID = 3;

    	NBTTagCompound tag=compound.getCompoundTag("RLMElectrizityTag");
    	
    	NBTTagCompound blockPosNBT = tag.getCompoundTag("connectedBlock");
	BlockPos readBlockPos = null;
	if (blockPosNBT.hasKey("x", NBT_INT_ID) && blockPosNBT.hasKey("y", NBT_INT_ID) && blockPosNBT.hasKey("z", NBT_INT_ID) ) {
		readBlockPos = new BlockPos(blockPosNBT.getInteger("x"), blockPosNBT.getInteger("y"), blockPosNBT.getInteger("z"));
		storedPos=readBlockPos;
	}

	isUsuable=tag.getBoolean("IsUsuable");
    }
    
@Override
public Packet getDescriptionPacket() {
	NBTTagCompound nbtTagCompound = new NBTTagCompound();
	writeToNBT(nbtTagCompound);
	int metadata = getBlockMetadata();
	return new S35PacketUpdateTileEntity(this.pos, metadata, nbtTagCompound);
}

@Override
public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt) {
	readFromNBT(pkt.getNbtCompound());
}

public void connectTo(TileEntity_Electric t){
	this.to=t;
	this.storedPos = t.getPos();
}

public float getVoltageValue() {
	return voltage;
}

public float getVoltage() {
	return this.voltage;
}

public void setVoltage(float voltage) {
	this.voltage = voltage;
}

public float onPowered(float f){
	return f;
}

public abstract float getMaxVoltage();

}

Posted

1) Why is this class abstract?

2) Why are you writing the block metadata to the description packet? (You're ignoring it when the packet arrives, too)

3) Your "connectTo" function is never called, making storedPos always null (unless its being called from another class you haven't posted)

4) Why are you getting the World and saving it to the local variable world when you have access to (and use!) worldObj?

5) Why are you using

Minecraft.getMinecraft().thePlayer

?

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

 

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

 

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

Posted

1. So classes that extend on it have the required methods (e.g) getMaxVoltag()

2. just copied that from here: https://github.com/TheGreyGhost/MinecraftByExample/blob/master/src/main/java/minecraftbyexample/mbe20_tileentity_data/TileEntityData.java

3. It is is called in an  ItemCable class like this

 

 

@Override

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

BlockPos pos = Minecraft.getMinecraft().objectMouseOver.getBlockPos();

RLMPlayerProps props = RLMPlayerProps.get(player);

if(world.getTileEntity(pos) instanceof TileEntity_Electric){

TileEntity_Electric toConnectTile = (TileEntity_Electric) world.getTileEntity(pos);

if(props.lastTile!=null&&props.lastTile!=toConnectTile){

props.lastTile.connectTo(toConnectTile);

world.markBlockForUpdate(props.lastTile.getPos());

props.lastTile=toConnectTile;

}

else{

player.addChatMessage(new ChatComponentText("Now in "+EnumChatFormatting.GREEN+"Connection Mode"+EnumChatFormatting.RESET+"To stop connecting, hold SHIFT+RIGHTCLICK! "));

props.lastTile = toConnectTile;

}

 

}else

{

if(world.getBlockState(pos).getBlock() instanceof BlockAir){

player.addChatMessage(new ChatComponentText("Stopped "+EnumChatFormatting.RED+"Connection Mode"));

props.lastTile=null;

}else

{

world.setBlockState(pos, RealLifeMod_Blocks.cable.getDefaultState());

}

 

}

return stack;

}

 

 

 

4: Just copied that too

5: cuz TileEntity hasn't got a ticksexisted field

Posted

1) ok, wasn't arbitrary. I still don't think you need to make the class abstract, but whatever.

2,4) Mmm...copy-pasta..

3) this method makes me cry.

 

5: cuz TileEntity hasn't got a ticksexisted field

 

And it will crash a dedicated server.  Good job.

 

So add one yourself.  It's got an update function, hasn't it?  You can create properties yes?  You can increment a counter in the update function, no?  Bloody freaking magic that is.

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

 

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

 

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

Posted

So i think i understand lazy initialization now. Let me try explaining it with my own words:

Lazy Initialization describes a performance action that only initializes a private field until it is deffinitly needed. In my case this is when i pass over the energy to the connected tile.

 

One question for that - when the chunk unloads - and i pass over the value of energy to my lazy initialized variable - this variable will still be a dead TE or not?

Posted

Okay - im setting the 'to' variable like this now:

 

@Override
public void update() {
	age++;
	if (!this.hasWorldObj()) return;
	if(worldObj.isRemote)return;

	if(storedPos!=null){
		to=getTo();
	}
   
}

And this is the getTo() method:
public TileEntity_Electric getTo() {
	if(to==null&&worldObj.getTileEntity(storedPos) instanceof TileEntity_Electric){
		to=(TileEntity_Electric)worldObj.getTileEntity(storedPos);
	}
	return to;
}

 

Is that the propper use of lazy initialization or just crab?

Guest
This topic is now closed to further replies.

Announcements




  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • Version 1.19 - Forge 41.0.63 I want to create a wolf entity that I can ride, so far it seems to be working, but the problem is that when I get on the wolf, I can’t control it. I then discovered that the issue is that the server doesn’t detect that I’m riding the wolf, so I’m struggling with synchronization. However, it seems to not be working properly. As I understand it, the server receives the packet but doesn’t register it correctly. I’m a bit new to Java, and I’ll try to provide all the relevant code and prints *The comments and prints are translated by chatgpt since they were originally in Spanish* Thank you very much in advance No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. MountableWolfEntity package com.vals.valscraft.entity; import com.vals.valscraft.network.MountSyncPacket; import com.vals.valscraft.network.NetworkHandler; import net.minecraft.client.Minecraft; import net.minecraft.network.syncher.EntityDataAccessor; import net.minecraft.network.syncher.EntityDataSerializers; import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.ai.attributes.AttributeSupplier; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.entity.animal.Wolf; import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.Entity; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.level.Level; import net.minecraft.world.phys.Vec3; import net.minecraftforge.event.TickEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.network.PacketDistributor; public class MountableWolfEntity extends Wolf { private boolean hasSaddle; private static final EntityDataAccessor<Byte> DATA_ID_FLAGS = SynchedEntityData.defineId(MountableWolfEntity.class, EntityDataSerializers.BYTE); public MountableWolfEntity(EntityType<? extends Wolf> type, Level level) { super(type, level); this.hasSaddle = false; } @Override protected void defineSynchedData() { super.defineSynchedData(); this.entityData.define(DATA_ID_FLAGS, (byte)0); } public static AttributeSupplier.Builder createAttributes() { return Wolf.createAttributes() .add(Attributes.MAX_HEALTH, 20.0) .add(Attributes.MOVEMENT_SPEED, 0.3); } @Override public InteractionResult mobInteract(Player player, InteractionHand hand) { ItemStack itemstack = player.getItemInHand(hand); if (itemstack.getItem() == Items.SADDLE && !this.hasSaddle()) { if (!player.isCreative()) { itemstack.shrink(1); } this.setSaddle(true); return InteractionResult.SUCCESS; } else if (!level.isClientSide && this.hasSaddle()) { player.startRiding(this); MountSyncPacket packet = new MountSyncPacket(true); // 'true' means the player is mounted NetworkHandler.CHANNEL.sendToServer(packet); // Ensure the server handles the packet return InteractionResult.SUCCESS; } return InteractionResult.PASS; } @Override public void travel(Vec3 travelVector) { if (this.isVehicle() && this.getControllingPassenger() instanceof Player) { System.out.println("The wolf has a passenger."); System.out.println("The passenger is a player."); Player player = (Player) this.getControllingPassenger(); // Ensure the player is the controller this.setYRot(player.getYRot()); this.yRotO = this.getYRot(); this.setXRot(player.getXRot() * 0.5F); this.setRot(this.getYRot(), this.getXRot()); this.yBodyRot = this.getYRot(); this.yHeadRot = this.yBodyRot; float forward = player.zza; float strafe = player.xxa; if (forward <= 0.0F) { forward *= 0.25F; } this.flyingSpeed = this.getSpeed() * 0.1F; this.setSpeed((float) this.getAttributeValue(Attributes.MOVEMENT_SPEED) * 1.5F); this.setDeltaMovement(new Vec3(strafe, travelVector.y, forward).scale(this.getSpeed())); this.calculateEntityAnimation(this, false); } else { // The wolf does not have a passenger or the passenger is not a player System.out.println("No player is mounted, or the passenger is not a player."); super.travel(travelVector); } } public boolean hasSaddle() { return this.hasSaddle; } public void setSaddle(boolean hasSaddle) { this.hasSaddle = hasSaddle; } @Override protected void dropEquipment() { super.dropEquipment(); if (this.hasSaddle()) { this.spawnAtLocation(Items.SADDLE); this.setSaddle(false); } } @SubscribeEvent public static void onServerTick(TickEvent.ServerTickEvent event) { if (event.phase == TickEvent.Phase.START) { MinecraftServer server = net.minecraftforge.server.ServerLifecycleHooks.getCurrentServer(); if (server != null) { for (ServerPlayer player : server.getPlayerList().getPlayers()) { if (player.isPassenger() && player.getVehicle() instanceof MountableWolfEntity) { MountableWolfEntity wolf = (MountableWolfEntity) player.getVehicle(); System.out.println("Tick: " + player.getName().getString() + " is correctly mounted on " + wolf); } } } } } private boolean lastMountedState = false; @Override public void tick() { super.tick(); if (!this.level.isClientSide) { // Only on the server boolean isMounted = this.isVehicle() && this.getControllingPassenger() instanceof Player; // Only print if the state changed if (isMounted != lastMountedState) { if (isMounted) { Player player = (Player) this.getControllingPassenger(); // Verify the passenger is a player System.out.println("Server: Player " + player.getName().getString() + " is now mounted."); } else { System.out.println("Server: The wolf no longer has a passenger."); } lastMountedState = isMounted; } } } @Override public void addPassenger(Entity passenger) { super.addPassenger(passenger); if (passenger instanceof Player) { Player player = (Player) passenger; if (!this.level.isClientSide && player instanceof ServerPlayer) { // Send the packet to the server to indicate the player is mounted NetworkHandler.CHANNEL.send(PacketDistributor.PLAYER.with(() -> (ServerPlayer) player), new MountSyncPacket(true)); } } } @Override public void removePassenger(Entity passenger) { super.removePassenger(passenger); if (passenger instanceof Player) { Player player = (Player) passenger; if (!this.level.isClientSide && player instanceof ServerPlayer) { // Send the packet to the server to indicate the player is no longer mounted NetworkHandler.CHANNEL.send(PacketDistributor.PLAYER.with(() -> (ServerPlayer) player), new MountSyncPacket(false)); } } } @Override public boolean isControlledByLocalInstance() { Entity entity = this.getControllingPassenger(); return entity instanceof Player; } @Override public void positionRider(Entity passenger) { if (this.hasPassenger(passenger)) { double xOffset = Math.cos(Math.toRadians(this.getYRot() + 90)) * 0.4; double zOffset = Math.sin(Math.toRadians(this.getYRot() + 90)) * 0.4; passenger.setPos(this.getX() + xOffset, this.getY() + this.getPassengersRidingOffset() + passenger.getMyRidingOffset(), this.getZ() + zOffset); } } } MountSyncPacket package com.vals.valscraft.network; import com.vals.valscraft.entity.MountableWolfEntity; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.player.Player; import net.minecraftforge.network.NetworkEvent; import java.util.function.Supplier; public class MountSyncPacket { private final boolean isMounted; public MountSyncPacket(boolean isMounted) { this.isMounted = isMounted; } public void encode(FriendlyByteBuf buffer) { buffer.writeBoolean(isMounted); } public static MountSyncPacket decode(FriendlyByteBuf buffer) { return new MountSyncPacket(buffer.readBoolean()); } public void handle(NetworkEvent.Context context) { context.enqueueWork(() -> { ServerPlayer player = context.getSender(); // Get the player from the context if (player != null) { // Verifies if the player has dismounted if (!isMounted) { Entity vehicle = player.getVehicle(); if (vehicle instanceof MountableWolfEntity wolf) { // Logic to remove the player as a passenger wolf.removePassenger(player); System.out.println("Server: Player " + player.getName().getString() + " is no longer mounted."); } } } }); context.setPacketHandled(true); // Marks the packet as handled } } networkHandler package com.vals.valscraft.network; import com.vals.valscraft.valscraft; import net.minecraft.resources.ResourceLocation; import net.minecraftforge.network.NetworkRegistry; import net.minecraftforge.network.simple.SimpleChannel; import net.minecraftforge.network.NetworkEvent; import java.util.function.Supplier; public class NetworkHandler { private static final String PROTOCOL_VERSION = "1"; public static final SimpleChannel CHANNEL = NetworkRegistry.newSimpleChannel( new ResourceLocation(valscraft.MODID, "main"), () -> PROTOCOL_VERSION, PROTOCOL_VERSION::equals, PROTOCOL_VERSION::equals ); public static void init() { int packetId = 0; // Register the mount synchronization packet CHANNEL.registerMessage( packetId++, MountSyncPacket.class, MountSyncPacket::encode, MountSyncPacket::decode, (msg, context) -> msg.handle(context.get()) // Get the context with context.get() ); } }  
    • Do you use features of inventory profiles next (ipnext) or is there a change without it?
    • Remove rubidium - you are already using embeddium, which is a fork of rubidium
  • Topics

×
×
  • Create New...

Important Information

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