/* * Ex Deorum * Copyright (c) 2024 thedarkcolour * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ package thedarkcolour.exdeorum.recipe; import com.google.gson.JsonElement; import com.mojang.datafixers.kinds.App; import com.mojang.datafixers.util.Pair; import com.mojang.serialization.Codec; import com.mojang.serialization.DataResult; import com.mojang.serialization.JsonOps; import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.codec.StreamCodec; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.material.Fluid; import net.minecraft.world.level.storage.loot.providers.number.NumberProvider; import net.neoforged.neoforge.fluids.FluidStack; import java.util.function.Function; @SuppressWarnings("OptionalGetWithoutIsPresent") public class CodecUtil { public static final Codec FLUIDSTACK_CODEC = FluidStack.CODEC; public static final StreamCodec NUMBER_PROVIDER_CODEC = StreamCodec.of(RecipeUtil::toNetworkNumberProvider, RecipeUtil::fromNetworkNumberProvider); public static App, Ingredient> ingredientField() { return Ingredient.CODEC.fieldOf("ingredient").forGetter(SingleIngredientRecipe::ingredient); } public static App, Block> blockField(String name, Function getter) { return BuiltInRegistries.BLOCK.byNameCodec().fieldOf(name).forGetter(getter); } public static App, Fluid> fluidField(String name, Function getter) { return BuiltInRegistries.FLUID.byNameCodec().fieldOf(name).forGetter(getter); } public static JsonElement encode(Codec codec, T object) { return codec.encodeStart(JsonOps.INSTANCE, object).result().get(); } public static T decode(Codec codec, JsonElement json) { return codec.parse(JsonOps.INSTANCE, json).result().get(); } public static DataResult> cast(DataResult> result) { return result.map(pair -> pair.mapFirst(Function.identity())); } }