Port tag preference system from TiC

This commit is contained in:
KnightMiner committed 2021-01-23 16:53:17 -05:00
1 parent de08cc8808
commit 037e98c851
4 files changed
+327 -3

No files matched your search

@@ -37,6 +37,7 @@ public class Mantle {
/* Proxies for sides, used for graphics processing */
public Mantle() {
ModLoadingContext.get().registerConfig(Type.CLIENT, Config.CLIENT_SPEC);
ModLoadingContext.get().registerConfig(Type.SERVER, Config.SERVER_SPEC);
instance = this;
IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus();
@@ -3,10 +3,12 @@ package slimeknights.mantle.config;
import net.minecraftforge.common.ForgeConfigSpec;
import net.minecraftforge.common.ForgeConfigSpec.BooleanValue;
import net.minecraftforge.common.ForgeConfigSpec.Builder;
import net.minecraftforge.common.ForgeConfigSpec.ConfigValue;
import net.minecraftforge.fml.config.ModConfig;
import slimeknights.mantle.Mantle;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
@@ -16,15 +18,20 @@ import java.util.function.Function;
public class Config {
/** List of all cached client config values, for cache clearing */
private static final List<CachedValue<?>> CLIENT_VALUES = new ArrayList<>();
private static final List<CachedValue<?>> SERVER_VALUES = new ArrayList<>();
/** If true, enables the heart renderer */
public static final CachedBoolean EXTRA_HEART_RENDERER;
private static final ForgeConfigSpec.Builder CLIENT_BUILDER;
public static final ForgeConfigSpec CLIENT_SPEC;
/** List of preferences for tag outputs */
public static final CachedValue<List<String>> TAG_PREFERENCES;
private static final ForgeConfigSpec.Builder CLIENT_BUILDER, SERVER_BUILDER;
public static final ForgeConfigSpec CLIENT_SPEC, SERVER_SPEC;
static {
CLIENT_BUILDER = new ForgeConfigSpec.Builder();
SERVER_BUILDER = new ForgeConfigSpec.Builder();
// client options
EXTRA_HEART_RENDERER = client(builder ->
@@ -34,7 +41,14 @@ public class Config {
.translation("config.mantle.extraHeartRenderer")
.define("extraHeartRenderer", true));
// server options
TAG_PREFERENCES = server(builder ->
builder.comment("Preferences for outputs from tags used in automatic compat in recipes")
.translation("config.mantle.tagPreferences")
.define("tagPreferences", Arrays.asList("minecraft", "tconstruct", "tmechworks", "immersiveengineering", "mekanism", "thermalfoundation", "thermalexpansion")));
CLIENT_SPEC = CLIENT_BUILDER.build();
SERVER_SPEC = SERVER_BUILDER.build();
}
/**
@@ -48,6 +62,17 @@ public class Config {
return cached;
}
/**
* Creates a cached boolean value for the client and adds it to the list to be invalidated on reload
* @param function Lambda to get config value
* @return Cached config value
*/
private static <T> CachedValue<T> server(Function<Builder,ConfigValue<T>> function) {
CachedValue<T> cached = new CachedValue<>(function.apply(SERVER_BUILDER));
SERVER_VALUES.add(cached);
return cached;
}
/**
* Event to call when the config changes
* @param configEvent Config event
@@ -55,8 +80,11 @@ public class Config {
public static void configChanged(final ModConfig.ModConfigEvent configEvent) {
ModConfig config = configEvent.getConfig();
if (config.getModId().equals(Mantle.modId)) {
if (config.getSpec() == Config.CLIENT_SPEC) {
ForgeConfigSpec spec = config.getSpec();
if (spec == Config.CLIENT_SPEC) {
CLIENT_VALUES.forEach(CachedValue::invalidate);
} else if (spec == Config.SERVER_SPEC) {
SERVER_VALUES.forEach(CachedValue::invalidate);
}
}
}
@@ -0,0 +1,166 @@
package slimeknights.mantle.recipe;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSyntaxException;
import lombok.RequiredArgsConstructor;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.network.PacketBuffer;
import net.minecraft.tags.ITag;
import net.minecraft.tags.TagCollectionManager;
import net.minecraft.util.IItemProvider;
import net.minecraft.util.JSONUtils;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.common.crafting.CraftingHelper;
import java.util.Objects;
import java.util.function.Supplier;
/**
* Class representing an item stack output. Supports both direct stacks and tag output, behaving like an ingredient used for output
*/
public abstract class ItemOutput implements Supplier<ItemStack> {
/**
* Gets the item output of this recipe
* @return Item output
*/
@Override
public abstract ItemStack get();
/**
* Writes this output to JSON
* @return Json element
*/
public abstract JsonElement serialize();
/**
* Creates a new output for the given stack
* @param stack Stack
* @return Output
*/
public static ItemOutput fromStack(ItemStack stack) {
return new OfStack(stack);
}
/**
* Creates a new output for the given item
* @param item Item
* @return Output
*/
public static ItemOutput fromItem(IItemProvider item) {
return fromStack(new ItemStack(item));
}
/**
* Creates a new output for the given tag
* @param tag Tag
* @return Output
*/
public static ItemOutput fromTag(ITag<Item> tag, int count) {
return new OfTagPreference(tag, count);
}
/**
* Reads an item output from JSON
* @param element Json element
* @return Read output
*/
public static ItemOutput fromJson(JsonElement element) {
if (element.isJsonPrimitive()) {
return fromItem(JSONUtils.getItem(element, "item"));
}
if (!element.isJsonObject()) {
throw new JsonSyntaxException("Invalid item output, must be a string or an object");
}
// if it has a tag, parse as tag
JsonObject json = element.getAsJsonObject();
if (json.has("tag")) {
String name = JSONUtils.getString(json, "tag");
ITag<Item> tag = TagCollectionManager.getManager().getItemTags().get(new ResourceLocation(name));
if (tag == null) {
throw new JsonSyntaxException("Unknown tag " + name + " for item output");
}
int count = JSONUtils.getInt(json, "count", 1);
return fromTag(tag, count);
}
// default: parse as item stack using Forge
return fromStack(CraftingHelper.getItemStack(json, true));
}
/**
* Writes this output to the packet buffer
* @param buffer Packet buffer instance
*/
public void write(PacketBuffer buffer) {
buffer.writeItemStack(get());
}
/**
* Reads an item output from the packet buffer
* @param buffer Buffer instance
* @return Item output
*/
public static ItemOutput read(PacketBuffer buffer) {
return fromStack(buffer.readItemStack());
}
/** Class for an output that is just a stack */
@RequiredArgsConstructor
private static class OfStack extends ItemOutput {
private final ItemStack stack;
@Override
public ItemStack get() {
return stack;
}
@Override
public JsonElement serialize() {
String itemName = Objects.requireNonNull(stack.getItem().getRegistryName()).toString();
int count = stack.getCount();
// if the item has NBT or a count, write as object
if (stack.hasTag() || stack.getCount() > 1) {
JsonObject jsonResult = new JsonObject();
jsonResult.addProperty("item", itemName);
if (count > 1) {
jsonResult.addProperty("count", count);
}
CompoundNBT nbt = stack.getTag();
if (nbt != null) {
jsonResult.addProperty("nbt", nbt.toString());
}
return jsonResult;
} else {
return new JsonPrimitive(itemName);
}
}
}
/** Class for an output from a tag preference */
@RequiredArgsConstructor
private static class OfTagPreference extends ItemOutput {
private final ITag<Item> tag;
private final int count;
@Override
public ItemStack get() {
return TagPreference.getItems().getPreference(tag)
.map(item -> new ItemStack(item, count))
.orElse(ItemStack.EMPTY);
}
@Override
public JsonElement serialize() {
JsonObject json = new JsonObject();
json.addProperty("tag", TagCollectionManager.getManager().getItemTags().getValidatedIdFromTag(tag).toString());
if (count != 1) {
json.addProperty("count", count);
}
return json;
}
}
}
@@ -0,0 +1,129 @@
package slimeknights.mantle.recipe;
import com.google.common.collect.Lists;
import net.minecraft.fluid.Fluid;
import net.minecraft.item.Item;
import net.minecraft.tags.ITag;
import net.minecraft.tags.ITagCollection;
import net.minecraft.tags.TagCollectionManager;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.Tags.IOptionalNamedTag;
import net.minecraftforge.event.TagsUpdatedEvent;
import net.minecraftforge.registries.IForgeRegistryEntry;
import slimeknights.mantle.config.Config;
import java.util.Comparator;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Supplier;
/**
* Utility that helps get the preferred item from a tag based on mod ID.
* @param <T> Registry type
*/
public class TagPreference<T extends IForgeRegistryEntry<T>> {
/** Map of each tag type to the preference instance for that type */
private static final Map<Class<?>, TagPreference<?>> PREFERENCE_MAP = new IdentityHashMap<>();
// cached tag supplier lambdas
private static final Supplier<ITagCollection<Item>> ITEM_TAG_COLLECTION_SUPPLIER = () -> TagCollectionManager.getManager().getItemTags();
private static final Supplier<ITagCollection<Fluid>> FLUID_TAG_COLLECTION_SUPPLIER = () -> TagCollectionManager.getManager().getFluidTags();
/**
* Gets the tag preference instance associated with the given tag collection
* @param clazz Tag class
* @param <T> Tag value type
* @return Tag preference instance
*/
@SuppressWarnings("unchecked")
public static <T extends IForgeRegistryEntry<T>> TagPreference<T> getInstance(Class<T> clazz, Supplier<ITagCollection<T>> collection) {
// should always be the right instance as only we add entries to the map
return (TagPreference<T>) PREFERENCE_MAP.computeIfAbsent(clazz, c -> new TagPreference<>(collection));
}
/**
* Gets an instance for item tags
* @return Instance for item tags
*/
public static TagPreference<Item> getItems() {
return getInstance(Item.class, ITEM_TAG_COLLECTION_SUPPLIER);
}
/**
* Gets an instance for fluid tags
* @return Instance for fluid tags
*/
public static TagPreference<Fluid> getFluids() {
return getInstance(Fluid.class, FLUID_TAG_COLLECTION_SUPPLIER);
}
/** Supplier to tag collection */
private final Supplier<ITagCollection<T>> collection;
/** Specific cache to this tag preference class type */
private final Map<ResourceLocation, Optional<T>> preferenceCache = new HashMap<>();
private TagPreference(Supplier<ITagCollection<T>> collection) {
this.collection = collection;
MinecraftForge.EVENT_BUS.addListener(this::clearCache);
}
/**
* Clears the tag cache from the event
* @param event Tag event
*/
private void clearCache(TagsUpdatedEvent.VanillaTagTypes event) {
preferenceCache.clear();
}
/**
* Gets the sort index of an entry based on the tag preference list
* @param entry Registry entry to check
* @return Sort index for that entry
*/
private static int getSortIndex(IForgeRegistryEntry<?> entry) {
List<String> entries = Config.TAG_PREFERENCES.get();
// check the index of the namespace in the preference list
int index = entries.indexOf(Objects.requireNonNull(entry.getRegistryName()).getNamespace());
// if missing, declare last
if (index == -1) {
return entries.size();
}
return index;
}
/**
* Gets the preferred value from a tag based on mod ID
* @param tag Tag to fetch
* @return Preferred value from the tag, or empty optional if the tag is empty
*/
public Optional<T> getPreference(ITag<T> tag) {
// fetch cached value if we have one
ResourceLocation tagName = collection.get().getValidatedIdFromTag(tag);
return preferenceCache.computeIfAbsent(tagName, name -> {
// if no items, empty optional
if (tag instanceof IOptionalNamedTag && ((IOptionalNamedTag<?>) tag).isDefaulted()) {
return Optional.empty();
}
List<? extends T> elements = tag.getAllElements();
if (elements.isEmpty()) {
return Optional.empty();
}
// if size 1, quick exit
if (elements.size() == 1) {
return Optional.of(elements.get(0));
}
// copy and sort list
List<? extends T> sortedElements = Lists.newArrayList(elements);
sortedElements.sort(Comparator.comparingInt(TagPreference::getSortIndex));
// return first element, its the preference
return Optional.of(sortedElements.get(0));
});
}
}