Creating a usable API (#1713)

* Initial stab at API structuring

* Throwing all the things into the API*
Eliminated all internal imports
Also added some helpful comments
*except for the ritual stuff

* Reducing the API
Threw back the altar/incense/unnecessary items to main
Added in a functional API instance

* API cleanup
Removing all the unnecessities
Smushed and vaporized some redundant recipe stuffs

* Made API dummy instances
Refactor packaging
This commit is contained in:
Arcaratus 2020-11-23 21:03:19 -05:00 committed by GitHub
parent 952b6aeeb0
commit 574d6a8e74
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
144 changed files with 558 additions and 990 deletions

View file

@ -0,0 +1,384 @@
package wayoftime.bloodmagic.recipe.helper;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSyntaxException;
import net.minecraft.fluid.Fluid;
import net.minecraft.network.PacketBuffer;
import net.minecraft.tags.FluidTags;
import net.minecraft.tags.ITag;
import net.minecraft.tags.TagCollectionManager;
import net.minecraft.util.JSONUtils;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fluids.FluidStack;
import wayoftime.bloodmagic.util.Constants;
/**
* Created by Thiakil on 12/07/2019.
*/
public abstract class FluidStackIngredient implements InputIngredient<FluidStack>
{
public static FluidStackIngredient from(@Nonnull Fluid instance, int amount)
{
return from(new FluidStack(instance, amount));
}
public static FluidStackIngredient from(@Nonnull FluidStack instance)
{
return new Single(instance);
}
public static FluidStackIngredient from(@Nonnull ITag<Fluid> fluidTag, int minAmount)
{
return new Tagged(fluidTag, minAmount);
}
public static FluidStackIngredient read(PacketBuffer buffer)
{
// TODO: Allow supporting serialization of different types than just the ones we
// implement?
IngredientType type = buffer.readEnumValue(IngredientType.class);
if (type == IngredientType.SINGLE)
{
return Single.read(buffer);
} else if (type == IngredientType.TAGGED)
{
return Tagged.read(buffer);
}
return Multi.read(buffer);
}
public static FluidStackIngredient deserialize(@Nullable JsonElement json)
{
if (json == null || json.isJsonNull())
{
throw new JsonSyntaxException("Ingredient cannot be null");
}
if (json.isJsonArray())
{
JsonArray jsonArray = json.getAsJsonArray();
int size = jsonArray.size();
if (size == 0)
{
throw new JsonSyntaxException("Ingredient array cannot be empty, at least one ingredient must be defined");
} else if (size > 1)
{
FluidStackIngredient[] ingredients = new FluidStackIngredient[size];
for (int i = 0; i < size; i++)
{
// Read all the ingredients
ingredients[i] = deserialize(jsonArray.get(i));
}
return createMulti(ingredients);
}
// If we only have a single element, just set our json as that so that we don't
// have to use Multi for efficiency reasons
json = jsonArray.get(0);
}
if (!json.isJsonObject())
{
throw new JsonSyntaxException("Expected fluid to be object or array of objects");
}
JsonObject jsonObject = json.getAsJsonObject();
if (jsonObject.has(Constants.JSON.FLUID) && jsonObject.has(Constants.JSON.TAG))
{
throw new JsonParseException("An ingredient entry is either a tag or an fluid, not both");
} else if (jsonObject.has(Constants.JSON.FLUID))
{
return from(SerializerHelper.deserializeFluid(jsonObject));
} else if (jsonObject.has(Constants.JSON.TAG))
{
if (!jsonObject.has(Constants.JSON.AMOUNT))
{
throw new JsonSyntaxException("Expected to receive a amount that is greater than zero");
}
JsonElement count = jsonObject.get(Constants.JSON.AMOUNT);
if (!JSONUtils.isNumber(count))
{
throw new JsonSyntaxException("Expected amount to be a number greater than zero.");
}
int amount = count.getAsJsonPrimitive().getAsInt();
if (amount < 1)
{
throw new JsonSyntaxException("Expected amount to be greater than zero.");
}
ResourceLocation resourceLocation = new ResourceLocation(JSONUtils.getString(jsonObject, Constants.JSON.TAG));
ITag<Fluid> tag = TagCollectionManager.getManager().getFluidTags().get(resourceLocation);
if (tag == null)
{
throw new JsonSyntaxException("Unknown fluid tag '" + resourceLocation + "'");
}
return from(tag, amount);
}
throw new JsonSyntaxException("Expected to receive a resource location representing either a tag or a fluid.");
}
public static FluidStackIngredient createMulti(FluidStackIngredient... ingredients)
{
if (ingredients.length == 0)
{
// TODO: Throw error
} else if (ingredients.length == 1)
{
return ingredients[0];
}
List<FluidStackIngredient> cleanedIngredients = new ArrayList<>();
for (FluidStackIngredient ingredient : ingredients)
{
if (ingredient instanceof Multi)
{
// Don't worry about if our inner ingredients are multi as well, as if this is
// the only external method for
// creating a multi ingredient, then we are certified they won't be of a higher
// depth
cleanedIngredients.addAll(Arrays.asList(((Multi) ingredient).ingredients));
} else
{
cleanedIngredients.add(ingredient);
}
}
// There should be more than a single fluid or we would have split out earlier
return new Multi(cleanedIngredients.toArray(new FluidStackIngredient[0]));
}
public static class Single extends FluidStackIngredient
{
@Nonnull
private final FluidStack fluidInstance;
public Single(@Nonnull FluidStack fluidInstance)
{
this.fluidInstance = Objects.requireNonNull(fluidInstance);
}
@Override
public boolean test(@Nonnull FluidStack fluidStack)
{
return testType(fluidStack) && fluidStack.getAmount() >= fluidInstance.getAmount();
}
@Override
public boolean testType(@Nonnull FluidStack fluidStack)
{
return Objects.requireNonNull(fluidStack).isFluidEqual(fluidInstance);
}
@Nonnull
@Override
public FluidStack getMatchingInstance(@Nonnull FluidStack fluidStack)
{
return test(fluidStack) ? fluidInstance : FluidStack.EMPTY;
}
@Nonnull
@Override
public List<FluidStack> getRepresentations()
{
return Collections.singletonList(fluidInstance);
}
@Override
public void write(PacketBuffer buffer)
{
buffer.writeEnumValue(IngredientType.SINGLE);
fluidInstance.writeToPacket(buffer);
}
@Nonnull
@Override
public JsonElement serialize()
{
JsonObject json = new JsonObject();
json.addProperty(Constants.JSON.AMOUNT, fluidInstance.getAmount());
json.addProperty(Constants.JSON.FLUID, fluidInstance.getFluid().getRegistryName().toString());
if (fluidInstance.hasTag())
{
json.addProperty(Constants.JSON.NBT, fluidInstance.getTag().toString());
}
return json;
}
public static Single read(PacketBuffer buffer)
{
return new Single(FluidStack.readFromPacket(buffer));
}
}
public static class Tagged extends FluidStackIngredient
{
@Nonnull
private final ITag<Fluid> tag;
private final int amount;
public Tagged(@Nonnull ITag<Fluid> tag, int amount)
{
this.tag = tag;
this.amount = amount;
}
@Override
public boolean test(@Nonnull FluidStack fluidStack)
{
return testType(fluidStack) && fluidStack.getAmount() >= amount;
}
@Override
public boolean testType(@Nonnull FluidStack fluidStack)
{
return Objects.requireNonNull(fluidStack).getFluid().isIn(tag);
}
@Nonnull
@Override
public FluidStack getMatchingInstance(@Nonnull FluidStack fluidStack)
{
if (test(fluidStack))
{
// Our fluid is in the tag so we make a new stack with the given amount
return new FluidStack(fluidStack, amount);
}
return FluidStack.EMPTY;
}
@Nonnull
@Override
public List<FluidStack> getRepresentations()
{
// TODO: Can this be cached some how
List<FluidStack> representations = new ArrayList<>();
for (Fluid fluid : TagResolverHelper.getRepresentations(tag))
{
representations.add(new FluidStack(fluid, amount));
}
return representations;
}
@Override
public void write(PacketBuffer buffer)
{
buffer.writeEnumValue(IngredientType.TAGGED);
buffer.writeResourceLocation(TagCollectionManager.getManager().getFluidTags().getValidatedIdFromTag(tag));
buffer.writeVarInt(amount);
}
@Nonnull
@Override
public JsonElement serialize()
{
JsonObject json = new JsonObject();
json.addProperty(Constants.JSON.AMOUNT, amount);
json.addProperty(Constants.JSON.TAG, TagCollectionManager.getManager().getFluidTags().getValidatedIdFromTag(tag).toString());
return json;
}
public static Tagged read(PacketBuffer buffer)
{
return new Tagged(FluidTags.makeWrapperTag(buffer.readResourceLocation().toString()), buffer.readVarInt());
}
}
public static class Multi extends FluidStackIngredient
{
private final FluidStackIngredient[] ingredients;
protected Multi(@Nonnull FluidStackIngredient... ingredients)
{
this.ingredients = ingredients;
}
@Override
public boolean test(@Nonnull FluidStack stack)
{
return Arrays.stream(ingredients).anyMatch(ingredient -> ingredient.test(stack));
}
@Override
public boolean testType(@Nonnull FluidStack stack)
{
return Arrays.stream(ingredients).anyMatch(ingredient -> ingredient.testType(stack));
}
@Nonnull
@Override
public FluidStack getMatchingInstance(@Nonnull FluidStack stack)
{
for (FluidStackIngredient ingredient : ingredients)
{
FluidStack matchingInstance = ingredient.getMatchingInstance(stack);
if (!matchingInstance.isEmpty())
{
return matchingInstance;
}
}
return FluidStack.EMPTY;
}
@Nonnull
@Override
public List<FluidStack> getRepresentations()
{
List<FluidStack> representations = new ArrayList<>();
for (FluidStackIngredient ingredient : ingredients)
{
representations.addAll(ingredient.getRepresentations());
}
return representations;
}
@Override
public void write(PacketBuffer buffer)
{
buffer.writeEnumValue(IngredientType.MULTI);
buffer.writeVarInt(ingredients.length);
for (FluidStackIngredient ingredient : ingredients)
{
ingredient.write(buffer);
}
}
@Nonnull
@Override
public JsonElement serialize()
{
JsonArray json = new JsonArray();
for (FluidStackIngredient ingredient : ingredients)
{
json.add(ingredient.serialize());
}
return json;
}
public static FluidStackIngredient read(PacketBuffer buffer)
{
FluidStackIngredient[] ingredients = new FluidStackIngredient[buffer.readVarInt()];
for (int i = 0; i < ingredients.length; i++)
{
ingredients[i] = FluidStackIngredient.read(buffer);
}
return createMulti(ingredients);
}
}
private enum IngredientType
{
SINGLE,
TAGGED,
MULTI
}
}

View file

@ -0,0 +1,67 @@
package wayoftime.bloodmagic.recipe.helper;
import javax.annotation.Nonnull;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
public final class IgnoredIInventory implements IInventory
{
public static final IgnoredIInventory INSTANCE = new IgnoredIInventory();
private IgnoredIInventory()
{
}
@Override
public int getSizeInventory()
{
return 0;
}
@Override
public boolean isEmpty()
{
return true;
}
@Override
public ItemStack getStackInSlot(int index)
{
return ItemStack.EMPTY;
}
@Override
public ItemStack decrStackSize(int index, int count)
{
return ItemStack.EMPTY;
}
@Override
public ItemStack removeStackFromSlot(int index)
{
return ItemStack.EMPTY;
}
@Override
public void setInventorySlotContents(int index, @Nonnull ItemStack stack)
{
}
@Override
public void markDirty()
{
}
@Override
public boolean isUsableByPlayer(@Nonnull PlayerEntity player)
{
return false;
}
@Override
public void clear()
{
}
}

View file

@ -0,0 +1,52 @@
package wayoftime.bloodmagic.recipe.helper;
import java.util.List;
import java.util.function.Predicate;
import javax.annotation.Nonnull;
import com.google.gson.JsonElement;
import net.minecraft.network.PacketBuffer;
public interface InputIngredient<TYPE> extends Predicate<TYPE>
{
/**
* Evaluates this predicate on the given argument, ignoring any size data.
*
* @param type the input argument
*
* @return {@code true} if the input argument matches the predicate, otherwise
* {@code false}
*/
boolean testType(@Nonnull TYPE type);
TYPE getMatchingInstance(TYPE type);
/**
* Primarily for JEI, a list of valid instances of the type
*
* @return List (empty means no valid registrations found and recipe is to be
* hidden)
*
* @apiNote Do not modify any of the values returned by the representations
*/
@Nonnull
List<TYPE> getRepresentations();
/**
* Writes this ingredient to a PacketBuffer.
*
* @param buffer The buffer to write to.
*/
void write(PacketBuffer buffer);
/**
* Serializes this ingredient to a JsonElement
*
* @return JsonElement representation of this ingredient.
*/
@Nonnull
JsonElement serialize();
}

View file

@ -0,0 +1,129 @@
package wayoftime.bloodmagic.recipe.helper;
import javax.annotation.Nonnull;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.fluid.Fluid;
import net.minecraft.fluid.Fluids;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.ShapedRecipe;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.nbt.JsonToNBT;
import net.minecraft.util.JSONUtils;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.registries.ForgeRegistries;
import wayoftime.bloodmagic.util.Constants;
/**
* Copied liberally from Mekanism. Thanks, pupnewfster!
*
*/
public class SerializerHelper
{
private SerializerHelper()
{
}
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
private static void validateKey(@Nonnull JsonObject json, @Nonnull String key)
{
if (!json.has(key))
{
throw new JsonSyntaxException("Missing '" + key + "', expected to find an object");
}
if (!json.get(key).isJsonObject())
{
throw new JsonSyntaxException("Expected '" + key + "' to be an object");
}
}
public static ItemStack getItemStack(@Nonnull JsonObject json, @Nonnull String key)
{
validateKey(json, key);
return ShapedRecipe.deserializeItem(JSONUtils.getJsonObject(json, key));
}
public static JsonElement serializeItemStack(@Nonnull ItemStack stack)
{
JsonObject json = new JsonObject();
json.addProperty(Constants.JSON.ITEM, stack.getItem().getRegistryName().toString());
if (stack.getCount() > 1)
{
json.addProperty(Constants.JSON.COUNT, stack.getCount());
}
if (stack.hasTag())
{
json.addProperty(Constants.JSON.NBT, stack.getTag().toString());
}
return json;
}
public static FluidStack getFluidStack(@Nonnull JsonObject json, @Nonnull String key)
{
validateKey(json, key);
return deserializeFluid(JSONUtils.getJsonObject(json, key));
}
public static FluidStack deserializeFluid(@Nonnull JsonObject json)
{
if (!json.has(Constants.JSON.AMOUNT))
{
throw new JsonSyntaxException("Expected to receive a amount that is greater than zero");
}
JsonElement count = json.get(Constants.JSON.AMOUNT);
if (!JSONUtils.isNumber(count))
{
throw new JsonSyntaxException("Expected amount to be a number greater than zero.");
}
int amount = count.getAsJsonPrimitive().getAsInt();
if (amount < 1)
{
throw new JsonSyntaxException("Expected amount to be greater than zero.");
}
ResourceLocation resourceLocation = new ResourceLocation(JSONUtils.getString(json, Constants.JSON.FLUID));
Fluid fluid = ForgeRegistries.FLUIDS.getValue(resourceLocation);
if (fluid == null || fluid == Fluids.EMPTY)
{
throw new JsonSyntaxException("Invalid fluid type '" + resourceLocation + "'");
}
CompoundNBT nbt = null;
if (json.has(Constants.JSON.NBT))
{
JsonElement jsonNBT = json.get(Constants.JSON.NBT);
try
{
if (jsonNBT.isJsonObject())
{
nbt = JsonToNBT.getTagFromJson(GSON.toJson(jsonNBT));
} else
{
nbt = JsonToNBT.getTagFromJson(JSONUtils.getString(jsonNBT, Constants.JSON.NBT));
}
} catch (CommandSyntaxException e)
{
throw new JsonSyntaxException("Invalid NBT entry for fluid '" + resourceLocation + "'");
}
}
return new FluidStack(fluid, amount, nbt);
}
public static JsonElement serializeFluidStack(@Nonnull FluidStack stack)
{
JsonObject json = new JsonObject();
json.addProperty(Constants.JSON.FLUID, stack.getFluid().getRegistryName().toString());
json.addProperty(Constants.JSON.AMOUNT, stack.getAmount());
if (stack.hasTag())
{
json.addProperty(Constants.JSON.NBT, stack.getTag().toString());
}
return json;
}
}

View file

@ -0,0 +1,32 @@
package wayoftime.bloodmagic.recipe.helper;
import java.util.Collections;
import java.util.List;
import net.minecraft.tags.ITag;
/**
* Copied from Mekanism, including the author's rant about tags.
*/
public class TagResolverHelper
{
public static <TYPE> List<TYPE> getRepresentations(ITag<TYPE> tag)
{
try
{
return tag.getAllElements();
} catch (IllegalStateException e)
{
// Why do tags have to be such an annoyance in 1.16
// This is needed so that we can ensure we give JEI an empty list of
// representations
// instead of crashing on the first run, as recipes get "initialized" before
// tags are
// done initializing, and we don't want to spam the log with errors. JEI and
// things
// still work fine regardless of this
return Collections.emptyList();
}
}
}