Jump to content

Recommended Posts

Posted

I've been trying to come up with how this mechanic for a few days now, and I finally ended up with a concept that should be manageable. Sadly I got into some problems.

 

The way I want this to work is that the player throws items into a fire-like block. The block stores the items in a tile entity, compares them to a list of recipes in a seperate class and, if it gets a match, destroy the block and give the player the crafted item.

 

My problem is that my tile entity doesn't save the items it consumes, but instead constantly replaces them with air. I am also not certain that even if it did save, it would not be able to match one of the recipes.

 

The relevant files are DarkLightCrafting (the file that stores and handles the recipes) and TileEntityDarkLight.

 

This is honestly the biggest part of a mod that I've made yet, and I'm very dissapointed it doesn't work. Hopefully there is a solution to the problem.

Posted
Quote

	@Override
	public void readFromNBT(NBTTagCompound compound)
	{
		super.readFromNBT(compound);
		stackHandler.deserializeNBT(compound);
	}
	
	@Override
	public NBTTagCompound writeToNBT(NBTTagCompound compound)
	{
		super.writeToNBT(compound);
		compound.setTag("burnedItems", stackHandler.serializeNBT());
		return compound;
	}

 

Your read and write NBT methods aren't inverses. You write stackHandler to a tag compound of its own with the key "burnedItems", but then try to read it from the compound itself instead of getting the tag by the same key.

Posted
11 minutes ago, Jay Avery said:

Your read and write NBT methods aren't inverses. You write stackHandler to a tag compound of its own with the key "burnedItems", but then try to read it from the compound itself instead of getting the tag by the same key.

	@Override
	public void readFromNBT(NBTTagCompound compound)
	{
		super.readFromNBT(compound);
		compound.getTag("burnedItems");
	}
	
	@Override
	public NBTTagCompound writeToNBT(NBTTagCompound compound)
	{
		super.writeToNBT(compound);
		compound.setTag("burnedItems", stackHandler.serializeNBT());
		return compound;
	}

Still doesn't save the item.

Posted
57 minutes ago, That_Martin_Guy said:

	@Override
	public void readFromNBT(NBTTagCompound compound)
	{
		super.readFromNBT(compound);
		compound.getTag("burnedItems");
	}

 

Now you're getting the tag and then not doing anything with it. You need to pass the tag to ItemStackHandler#deserializeNBT.

Posted
11 minutes ago, Jay Avery said:

Now you're getting the tag and then not doing anything with it. You need to pass the tag to ItemStackHandler#deserializeNBT.

	public void readFromNBT(NBTTagCompound compound)
	{
		super.readFromNBT(compound);
		stackHandler.deserializeNBT((NBTTagCompound) compound.getTag("burnedItems"));
	}

Still doesn't save. Sorry if I'm doing anything stupid, but NBT tags aren't my strong point.

Posted
13 minutes ago, stucuk said:

there is no markDirty() anywhere in your code. For the TileEntity to be saved you need to mark it as dirty to tell Minecraft that the chunk needs saved. Whenever you set data that needs to be saved call markDirty()

Again, NBT data isn't my strong point, so sorry if I did anything stupid or missed something. I changed update() to

 

..
		IItemHandler stackHandlerCapability = this.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null);
		
		if(!this.world.isRemote)
		{
			if(burningItems.size() > 0)
			{
				for(int i = 0; i < burningItems.size(); i++)
				{
					System.out.println(burningItems.get(i).getEntityItem().toString());
					stackHandlerCapability.insertItem(occupiedSlots++, burningItems.get(i).getEntityItem(), true);
					this.markDirty();
					burningItems.get(i).setDead();
				}
			}
		}
		//Print for checking if the tile entity saves items tossed into it. Currently mostly prints 
		//Slot 0: 1xtile.air@0 Slot 2: 1xtile.air@0
		System.out.println("Slot 0: " + stackHandlerCapability.getStackInSlot(0) + " Slot 1: " + stackHandlerCapability.getStackInSlot(1));
		ItemStack output = DarkPortalCrafting.getOutput(stackHandlerCapability.getStackInSlot(0), stackHandlerCapability.getStackInSlot(1));
		
		if(output != null)
		{
			System.out.println(output.toString());
			for(int i = 0; i < playersInRange.size(); i++)
			{
				EntityPlayer currentPlayer = playersInRange.get(i);
				if(currentPlayer.getCapability(PlayerHostProvider.PLAYER_HOST_CAPABILITY, null).isHost())
				{
					ItemHandlerHelper.giveItemToPlayer(currentPlayer, output);
					currentPlayer.playSound(SoundEvents.BLOCK_PORTAL_TRAVEL, 1.0f, 0.2f);
				}
				else
				{
					this.world.spawnEntity(new EntityLightningBolt(this.world, currentPlayer.posX, currentPlayer.posY, currentPlayer.posZ, false));
				}
				this.world.setBlockToAir(this.pos);
			}
		}
..

and writeToNBT() to

	public NBTTagCompound writeToNBT(NBTTagCompound compound)
	{
		super.writeToNBT(compound);
		compound.setTag("burnedItems", stackHandler.serializeNBT());
		this.markDirty();
		return compound;
	}

. Still doesn't save.

Posted (edited)

Ah, I've just noticed here: 

stackHandlerCapability.insertItem(occupiedSlots++, burningItems.get(i).getEntityItem(), true);

 

The boolean argument in IItemHandler#insertItem is simulate. When it's set to true, the stack isn't actually added.

Edited by Jay Avery
Posted
5 minutes ago, Jay Avery said:

Ah, I've just noticed here: 


stackHandlerCapability.insertItem(occupiedSlots++, burningItems.get(i).getEntityItem(), true);

 

The boolean argument in IItemHandler#insertItem is simulate. When it's set to true, the stack isn't actually added.

Ah, great! The block now correctly stores items inside of it.

 

I also noticed during testing that I never called DarkLightCrafting#init(), so I went ahead and added it to my main init method. When I did this, however, the game started to crash with an ArrayIndexOutOfBoundsException (full crash report here). Note that I renamed the Dark Light block to Dark Portal, and therefore updated most names related to it (including DarkPortalCrafting). Also note that I changed some things in that class, so it now looks like this.

 

Also, why would you want to make simulate true? Isn't the point of using insertItem to actually store the item?

Posted
3 minutes ago, That_Martin_Guy said:

I also noticed during testing that I never called DarkLightCrafting#init(), so I went ahead and added it to my main init method. When I did this, however, the game started to crash with an ArrayIndexOutOfBoundsException (full crash report here). Note that I renamed the Dark Light block to Dark Portal, and therefore updated most names related to it (including DarkPortalCrafting). Also note that I changed some things in that class, so it now looks like this.

That crash report seems to be referring to a line that doesn't exist (line 56 of this 55-line file https://pastebin.com/2cReqiL6), are they both the most up-to-date versions of the class and the crash report?

 

Either way though, I am confused about your recipes system. Why aren't you just using a Map of inputs to outputs?

 

3 minutes ago, That_Martin_Guy said:

 

Also, why would you want to make simulate true? Isn't the point of using insertItem to actually store the item?

Honestly I have no idea! I guess for some reason it might be useful to check whether a stack can be stored before actually storing it...? I've certainly never used it that way, but I guess it wouldn't exist if there wasn't a potential use.

Posted
1 minute ago, Jay Avery said:

That crash report seems to be referring to a line that doesn't exist (line 56 of this 55-line file https://pastebin.com/2cReqiL6), are they both the most up-to-date versions of the class and the crash report?

I didn't include the package declaration and imports. A brainfart on my part, didn't realise you would need the whole file to get the right line numbers. This is the full class.

2 minutes ago, Jay Avery said:

Either way though, I am confused about your recipes system. Why aren't you just using a Map of inputs to outputs?

'Cause I went into this blindly, and am not familiar with Maps. I will look into it.

Posted
Just now, That_Martin_Guy said:

I didn't include the package declaration and imports. A brainfart on my part, didn't realise you would need the whole file to get the right line numbers. This is the full class.

'Cause I went into this blindly, and am not familiar with Maps. I will look into it.

Ah I see. A Map will definitely make this easier, you won't have to compare indexes or search for recipes manually.

Posted
1 hour ago, Jay Avery said:

Ah I see. A Map will definitely make this easier, you won't have to compare indexes or search for recipes manually.

Gosh that makes it so much easier! I still have a (relatively small) problem however. As you might know from previous code posted, I am using a diamond helmet in one of the recipes. My problem is that if I use ItemStack#getItem on a diamond helmet I don't actually get a diamond helmet object, but instead an ItemArmor object. One way to show this is with a simple print call:

System.out.println(new ItemStack(Items.DIAMOND_HELMET).getItem());

. This will print net.minecraft.item.ItemArmor@4fa8bebb, not net.minecraft.item.ItemDiamondHelmet@123456. I could fix this by using registry names as the key instead of the object itself, but I would much prefer to use an object.

 

Also, if you are curious, this is my updated DarkPortalCrafting class.

Posted (edited)
33 minutes ago, That_Martin_Guy said:

Gosh that makes it so much easier! I still have a (relatively small) problem however. As you might know from previous code posted, I am using a diamond helmet in one of the recipes. My problem is that if I use ItemStack#getItem on a diamond helmet I don't actually get a diamond helmet object, but instead an ItemArmor object. One way to show this is with a simple print call:


System.out.println(new ItemStack(Items.DIAMOND_HELMET).getItem());

. This will print net.minecraft.item.ItemArmor@4fa8bebb, not net.minecraft.item.ItemDiamondHelmet@123456. I could fix this by using registry names as the key instead of the object itself, but I would much prefer to use an object.

 

Also, if you are curious, this is my updated DarkPortalCrafting class.

I originally misinterpreted and thought your recipes were one input -> multiple outputs rather than the other way round. Now I think that a Map alone may not work. The get method looks for equal objects, and two arrays will only be equal if they contain exactly the same element at every index. So if they contain the same elements but in a different order, or the inputs array contains all the required inputs plus extras, the recipe will fail even when it should succeed. I'd recommend taking a look at the vanilla ShapelessRecipes class which does a similar many->one thing. You might even be able to adjust your code to use ShapelessRecipes as it is, without needing to make your own implementation.

 

The diamond helmet thing is not a problem in the way you think. When you print the Item to the console it writes ItemArmor@etc because ItemArmor is the declared type (there is no ItemDiamondHelmet class), but this doesn't change the Item's actual identity. If you print Items.DIAMOND_HELMET alone it will give the same output. And you can confirm that they are the same object by checking Items.DIAMOND_HELMET == new ItemStack(Items.DIAMOND_HELMET).getItem(), which will evaluate to true. This all works because Items are singletons so every diamond helmet is the exact same Item object.

 

The short version is that Item doesn't override toString, so you don't get much useful information by printing an Item to the console as-is. 

Edited by Jay Avery
Posted
15 minutes ago, Jay Avery said:

I originally misinterpreted and thought your recipes were one input -> multiple outputs rather than the other way round. Now I think that a Map alone may not work. The get method looks for equal objects, and two arrays will only be equal if they contain exactly the same element at every index. So if they contain the same elements but in a different order, or the inputs array contains all the required inputs plus extras, the recipe will fail even when it should succeed. I'd recommend taking a look at the vanilla ShapelessRecipes class which does a similar many->one thing. You might even be able to adjust your code to use ShapelessRecipes as it is, without needing to make your own implementation.

ShapelessRecipes uses a normal List to iterate through its values, similar to how I did it before. No clue how I would replicate this with a map.

17 minutes ago, Jay Avery said:

The diamond helmet thing is not a problem in the way you think. When you print the Item to the console it writes ItemArmor@etc because ItemArmor is the declared type, but this doesn't change the Item's actual identity. If you print Items.DIAMOND_HELMET alone it will give the same output. And you can confirm that they are the same object by checking Items.DIAMOND_HELMET == new ItemStack(Items.DIAMOND_HELMET).getItem(), which will evaluate to true. This all works because Items are singletons so every diamond helmet is the exact same Item object.

When I tried to craft my item in-game it didn't give me it, so I assumed that it was because I get ItemArmor instead of ItemDiamondHelmet. I stand corrected however.

Posted (edited)
12 hours ago, That_Martin_Guy said:

and writeToNBT() to


	public NBTTagCompound writeToNBT(NBTTagCompound compound)
	{
		super.writeToNBT(compound);
		compound.setTag("burnedItems", stackHandler.serializeNBT());
		this.markDirty();
		return compound;
	}

. Still doesn't save.

 

You never want to use markDirty in the writeToNBT (or even readToNBT). markDirty tells minecraft that the chunk that the tile is in needs to be saved. writeToNBT is what minecraft uses when saving to get the Tile's NBT data. So your basically telling minecraft that the chunk your tile is in constantly needs to be saved.

 

As i said before, only when *you* actually change somethings value which you want minecraft to save to the world do you call markDirty().

Edited by stucuk
Posted
10 hours ago, stucuk said:

 

You never want to use markDirty in the writeToNBT (or even readToNBT). markDirty tells minecraft that the chunk that the tile is in needs to be saved. writeToNBT is what minecraft uses when saving to get the Tile's NBT data. So your basically telling minecraft that the chunk your tile is in constantly needs to be saved.

 

As i said before, only when *you* actually change somethings value which you want minecraft to save to the world do you call markDirty().

It saves correctly now, indeed. I'm still not sure how I would access my ItemStack output in the map with an Item array.

Posted

Instead of a map you'll probably have to make an object for each recipe which contains the list of inputs and the output, and store a collection of those objects. Then search through the list of recipes to compare against the available inputs - using more or less the same technique that ShapelessRecipes uses.

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

    • 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.