Jump to content

[1.14.4] Trouble with Custom Recipes


BlockyPenguin

Recommended Posts

Hi, so, I'm trying to make my own recipe type that uses a format like this, but with as few or as many steps as you like:

{
	"type": "labkit:cauldron",
	
	"method": {
		"steps": [
			
			"one": {
				"input": {
					"item": "minecraft:dirt",
					"count": 1
				},
				
				"wait": 100,
				"waterused": 0
			},
			
			"two": {
				"input": {
					"item": "minecraft:seeds",
					"count": 1
				},
				
				"wait": 20,
				"waterused": 1
			}
			
		],
		
		"output": {
			"item": "minecraft:grass_block",
			"count": 1
		}
	}
}

I've tried following some tutorials on YouTube and adapting it to use my idea of steps, but I always hit roadblocks. Any ideas?

Thanks!

EDIT: Here's my code:
 

package ...

import ...

public class CauldronRecipe implements ICauldronRecipe {
	
	private final ResourceLocation resLoc;
	private CauldronRecipeMethod method;
	private final ItemStack output;
	
	public CauldronRecipe(ResourceLocation resLoc, CauldronRecipeMethod method, ItemStack output) {
		this.resLoc = resLoc;
		this.method = method;
		this.output = output;
	}
	
	@Override
	public boolean matches(RecipeWrapper inv, World world) {
		if(method.getSteps()[0].getInput().test(inv.getStackInSlot(0)))
			return true;
		else
			return false;
	}
	
	@Override
	public ItemStack getCraftingResult(RecipeWrapper inv) {
		return output;
	}
	
	@Override
	public ItemStack getRecipeOutput() {
		return output;
	}
	
	@Override
	public IRecipeSerializer<?> getSerializer() {
		return ModRegistry.ModRecipeSerializers.CAULDRON_RECIPE.get();
	}
	
	@Override
	public Ingredient[] getInput() {
		Ingredient[] ingredients = {};
		for(int i = 0; i < method.getSteps().length; i++) {
			ingredients[i] = method.getSteps()[i].getInput();
		}
		return ingredients;
	}

	@Override
	public NonNullList<Ingredient> getIngredients() {
		return NonNullList.from(null, getInput());
	}

	@Override
	public ResourceLocation getId() {
		return resLoc;
	}
}

 

package ...

import ...

public interface ICauldronRecipe extends IRecipe<RecipeWrapper> {
	
	ResourceLocation RECIPE_TYPE_RESOURCE_LOCATION = new ResourceLocation(LabKit.MODID, "cauldron");
	
	@Nonnull
	@Override
	default IRecipeType<?> getType() {
		return Registry.RECIPE_TYPE.getValue(RECIPE_TYPE_RESOURCE_LOCATION).get();
	}
	
	@Override
	default boolean canFit(int width, int height) {
		return false;
	}
	
	Ingredient[] getInput();
	
}

 

package ...

import ...

public class CauldronRecipeSerializer extends ForgeRegistryEntry<IRecipeSerializer<?>> implements IRecipeSerializer<CauldronRecipe> {
	
	@Override
	public CauldronRecipe read(ResourceLocation recipeResLoc, JsonObject json) {
		
		JsonObject jsonMethod = JSONUtils.getJsonObject(json, "method");
		JsonArray jsonSteps = jsonMethod.getAsJsonArray("steps");
		
		ItemStack output = ShapedRecipe.deserializeItem(JSONUtils.getJsonObject(jsonMethod, "output"));
		
		CauldronRecipeStep[] steps = getCauldronRecipeStepsFromJson(jsonSteps);
		CauldronRecipeMethod method = new CauldronRecipeMethod(output, steps);
		
		return new CauldronRecipe(recipeResLoc, method, output);
	}
	
  	// IDK how to get a CauldronRecipeMethod from the buffer, these two methods are still from the tutorial that I followed's code
	@Override
	public CauldronRecipe read(ResourceLocation recipeResLoc, PacketBuffer buffer) {
		ItemStack output = buffer.readItemStack();
		Ingredient input = Ingredient.read(buffer);
		
		return new CauldronRecipe(recipeResLoc, input, output);
	}
	
	@Override
	public void write(PacketBuffer buffer, CauldronRecipe recipe) {
		Ingredient input = recipe.getIngredients().get(0);
		input.write(buffer);
		
		buffer.writeItemStack(recipe.getRecipeOutput(), false);
	}
	
	private CauldronRecipeStep[] getCauldronRecipeStepsFromJson(JsonArray stepsInput) {
		ArrayList<CauldronRecipeStep> stepsOutArrayList = new ArrayList<CauldronRecipeStep>();
		CauldronRecipeStep[] stepsOutArray = {};
		
		for(JsonElement step : stepsInput) {
			JsonObject jsonInput = step.getAsJsonObject().getAsJsonObject("input");
			Ingredient input = Ingredient.deserialize(jsonInput);
			
			int waitTime = step.getAsJsonObject().get("wait").getAsInt();
			
			int waterUsed = step.getAsJsonObject().get("waterused").getAsInt();
			
			stepsOutArrayList.add(new CauldronRecipeStep(input, waitTime, waterUsed));
		}
		
		return stepsOutArrayList.toArray(stepsOutArray);
	}
}

 

package ...

import ...

public class CauldronRecipeMethod {
	
	private CauldronRecipeStep[] steps;
	private ItemStack output;
	
	public CauldronRecipeMethod(ItemStack output, CauldronRecipeStep... steps) {
		this.steps = steps;
		this.output = output;
	}
	
	public CauldronRecipeStep[] getSteps() {
		return steps;
	}
	
	public ItemStack getOutput() {
		return output;
	}
	
}

 

package ...

import ...

public class CauldronRecipeStep {
	
	private Ingredient input;
	private int waitTime;
	private int waterUsed;
	
	public CauldronRecipeStep(Ingredient input, int waitTime, int waterUsed) {
		this.input = input;
		this.waitTime = waitTime;
		
		if(waterUsed > 3)
			throw new JsonSyntaxException("\"waterused\" is greater than 3. Please set it to a value between 0 and 3.");
		else if(waterUsed < 0)
			throw new JsonSyntaxException("\"waterused\" is less than 0. Please set it to a value between 0 and 3.");
		else
			this.waterUsed = waterUsed;
	}

	public Ingredient getInput() {
		return input;
	}
	
	public int getWaitTime() {
		return waitTime;
	}
	
	public int getWaterUsed() {
		return waterUsed;
	}
	
}


EDIT 2: I know that "You're going about this completely the wrong way" is probably a massive understatement, but I would like to know...

Edited by BlockyPenguin
Added my code

Today (22/10/20) I reached 100 posts!

I'm probably more excited than I should be for something so realistically minor...

Link to comment
Share on other sites

2 hours ago, BlockyPenguin said:

extends ForgeRegistryEntry<IRecipeSerializer<?>>

Did you register this class?

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

 

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

 

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

Link to comment
Share on other sites

I did, but even so, the game wouldn't load due to the errors in my code. I guess what I probably need to know, is how to get the json data out of the PacketBuffer at 

15 hours ago, BlockyPenguin said:

@Override
public CauldronRecipe read(ResourceLocation recipeResLoc, PacketBuffer buffer) {
    ItemStack output = buffer.readItemStack();
    Ingredient input = Ingredient.read(buffer);
    return new CauldronRecipe(recipeResLoc, input, output);
}

so that I can insert it into "CauldronRecipeStep"s, and insert that into a "CauldronRecipeMethod". Is that possible?

Today (22/10/20) I reached 100 posts!

I'm probably more excited than I should be for something so realistically minor...

Link to comment
Share on other sites

17 hours ago, BlockyPenguin said:

[ "one": {

That is not valid json. Currently you have an array with keys.

Either it should be an array of objects "[ { ..." or it should be an object with keys of "one, two,...".

I would suggest going for the first option (especially as that is what you support in your code):

17 hours ago, BlockyPenguin said:

JsonArray jsonSteps = jsonMethod.getAsJsonArray("steps");

 

Edited by Alpvax
  • Like 1
Link to comment
Share on other sites

3 hours ago, Alpvax said:

That is not valid json. Currently you have an array with keys.

Either it should be an array of objects "[ { ..." or it should be an object with keys of "one, two,...".

I would suggest going for the first option (especially as that is what you support in your code):

 

Ah ok, thanks :)

Today (22/10/20) I reached 100 posts!

I'm probably more excited than I should be for something so realistically minor...

Link to comment
Share on other sites

Ok, so as it stands, I've changed some things around, and hopefully simplified the system, but I still haven't tested it, as there are still errors in my code that would stop the game from launching. Here's the problem code:

@Override
public CauldronRecipe read(ResourceLocation recipeId, PacketBuffer buffer) {
	ItemStack output = buffer.readItemStack();
	
	return new CauldronRecipe(recipeId, output, steps);
}

Here's the thing, the steps variable doesn't exist, as I don't know how to get a JSONArray from a PacketBuffer (if it's even possible). I have a method I can call which takes in a JSONArray and returns an array of CauldronRecipeSteps, which is what I need to pass in.

 

So, if it is possible, how would I get a JSONArray from a PacketBuffer, and if it's not, how else could I do this?

Thanks!

Edited by BlockyPenguin

Today (22/10/20) I reached 100 posts!

I'm probably more excited than I should be for something so realistically minor...

Link to comment
Share on other sites

Aren't you the one who wrote the recipe -> packetbuffer code in the first place?

Yes, yes you are.

Quote

	@Override
	public void write(PacketBuffer buffer, CauldronRecipe recipe) {
		Ingredient input = recipe.getIngredients().get(0);
		input.write(buffer);
		
		buffer.writeItemStack(recipe.getRecipeOutput(), false);
	}

 

Your buffer doesn't contain that information. The only thing you write are the ingredients and the output.

  • Like 1

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

 

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

 

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

Link to comment
Share on other sites

7 minutes ago, Draco18s said:

Aren't you the one who wrote the recipe -> packetbuffer code in the first place?

Yes, yes you are.

Your buffer doesn't contain that information. The only thing you write are the ingredients and the output.

Ah, I get it now! Thanks! Do you know how I could write an array of CauldronRecipeSteps? buffer.writeArray or something similar doesn't seem to exist...

Today (22/10/20) I reached 100 posts!

I'm probably more excited than I should be for something so realistically minor...

Link to comment
Share on other sites

Of course it doesn't exist, buffer.write__ methods only write primitive data types and some helpers for ItemStacks and BlockStates (both of which can be decomposed to primitives, but Forge/Vanilla was kind enough to supply those for you).

You need to decompose your Steps down into primitives.

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

 

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

 

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

Link to comment
Share on other sites

Ok, thanks :) I think I've managed to do that correctly now, as the game loads with no errors. I have no way of checking if everything is serialized/deserialized properly yet though, as I have no block to use this crafting system with. I'll make that, and post my results :)

Today (22/10/20) I reached 100 posts!

I'm probably more excited than I should be for something so realistically minor...

Link to comment
Share on other sites

22 hours ago, BlockyPenguin said:

Ok, thanks :) I think I've managed to do that correctly now, as the game loads with no errors. I have no way of checking if everything is serialized/deserialized properly yet though, as I have no block to use this crafting system with. I'll make that, and post my results :)

Ok, well, easier said than done. I've taken a look different crafting blocks in vanilla's code (mostly AbstractFunaceTileEntity, as the other blocks are done without a tile), and I keep writing code, getting stuck, then rewriting it, over and over. How would I go about making this work? I have a custom cauldron block, and I want a player to right-click it to add one of the items in the ItemStack they're holding to the tile's inventory, or if they're holding nothing then drop all the items in the inventory. Here's my code so far:

 

package ...

import ...

public class CauldronTileEntity extends TileEntity {
	
	private LazyOptional<IItemHandler> itemHandler = LazyOptional.of(this::createItemHandler);
	
	private ArrayList<CauldronRecipe> recipes = CauldronRecipe.getAllCauldronRecipes();
	private CauldronRecipe currentRecipe;
	
	public CauldronTileEntity() {
		super(ModRegistry.TileTypes.CAULDRON.get());
	}
	
	@Override
	@SuppressWarnings("unchecked")
    public void read(CompoundNBT tag) {
        CompoundNBT invTag = tag.getCompound("inv");
        itemHandler.ifPresent(h -> ((INBTSerializable<CompoundNBT>) h).deserializeNBT(invTag));
        
        super.read(tag);
    }

	@Override
	@SuppressWarnings("unchecked")
    public CompoundNBT write(CompoundNBT tag) {
        itemHandler.ifPresent(h -> {
			CompoundNBT compound = ((INBTSerializable<CompoundNBT>) h).serializeNBT();
            tag.put("inv", compound);
        });
        
        return super.write(tag);
    }

    private IItemHandler createItemHandler() {
        return new ItemStackHandler(50) {

            @Override
            protected void onContentsChanged(int slot) {
                markDirty();
            }

            @Override
            public boolean isItemValid(int slot, @Nonnull ItemStack stack) {
                return true;
            }
            
        };
    }
	
	public void handleRightClick(PlayerEntity player, Hand hand) {
		ItemStack stack = player.getHeldItem(hand);
		
		if(stack.isEmpty()) {
			popOutAllItems();
		}else {
			itemHandler.ifPresent(h -> {
				for(int i = 0; i <= h.getSlots(); i++) {
					if(h.insertItem(i, stack.split(1), true) != stack.split(1)) {
						player.setHeldItem(hand, h.insertItem(i, stack.split(1), false));
					}else {
						player.sendStatusMessage(ITextComponent.Serializer.fromJsonLenient("Cauldron Full!"), true);
					}
				}
			});
			checkRecipe();
		}
	}
	
	private void popOutAllItems() {
		itemHandler.ifPresent(h -> {
			ItemEntity[] itemEntities = {};
			for(int i = 0; i <= h.getSlots(); i++) {
				itemEntities[i] = new ItemEntity(world, pos.getX(), pos.getY(), pos.getZ(), h.getStackInSlot(i));
			}
			
			for(ItemEntity e : itemEntities) {
				world.addEntity(e);
			}
		});
	}
	
	private void checkRecipe() {
		
	}
}

 

handleRightClick is called from onBlockActivated in the Cauldron's block class.

 

As you can see, checkRecipe() is empty. I'd like it so that whenever a player changes the items in the inventory, it checks whether it can do a recipe (which is why I call it from handleRightClick). How would I go about it? I've changed the json format to be this instead:
 

{
	"type": "labkit:cauldron",

	"inputs": [
		{
			"item": "minecraft:dirt",
			"count": 1
		},
		{
			"tag": "forge:seeds",
			"count": 3
		}
	],

	"cooking_delay": 50,

	"output": {
		"item": "minecraft:grass_block",
		"count": 1
	}
}

 

the order of the inputs doesn't matter to me, I'd just like to know how to check if they equal a recipe's ingredients.
 

(Also, I've just tested running the game, and my cauldron doesn't have a tile entity... I'm using DeferredRegister, and I've got these two methods in my block's class:

@Override
public boolean hasTileEntity(BlockState state) {
	return true;
}

@Override
public TileEntity createTileEntity(BlockState state, IBlockReader world) {
	return new CauldronTileEntity();
}

which as far as i'm aware, should do the trick...)

Thanks!

Today (22/10/20) I reached 100 posts!

I'm probably more excited than I should be for something so realistically minor...

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.