add some generated typed/tag keys

This commit is contained in:
Jake Potrebic 2024-06-15 15:52:14 -07:00
parent b090c65fe0
commit 5e7cd0784b
No known key found for this signature in database
GPG Key ID: ECE0B3C133C016C5
8 changed files with 11022 additions and 0 deletions

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,323 @@
package io.papermc.paper.registry.keys.tags;
import static net.kyori.adventure.key.Key.key;
import io.papermc.paper.generated.GeneratedFrom;
import io.papermc.paper.registry.RegistryKey;
import io.papermc.paper.registry.tag.TagKey;
import net.kyori.adventure.key.Key;
import org.bukkit.MinecraftExperimental;
import org.bukkit.enchantments.Enchantment;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
/**
* Vanilla keys for {@link RegistryKey#ENCHANTMENT}.
*
* @apiNote The fields provided here are a direct representation of
* what is available from the vanilla game source. They may be
* changed (including removals) on any Minecraft version
* bump, so cross-version compatibility is not provided on the
* same level as it is on most of the other API.
*/
@SuppressWarnings({
"unused",
"SpellCheckingInspection"
})
@GeneratedFrom("1.21")
@ApiStatus.Experimental
public final class EnchantmentTagKeys {
/**
* {@code #minecraft:trades/swamp_special}
*
* @apiNote This field is version-dependant and may be removed in future Minecraft versions
*/
@ApiStatus.Experimental
@MinecraftExperimental(MinecraftExperimental.Requires.TRADE_REBALANCE)
public static final TagKey<Enchantment> TRADES_SWAMP_SPECIAL = create(key("trades/swamp_special"));
/**
* {@code #minecraft:trades/plains_special}
*
* @apiNote This field is version-dependant and may be removed in future Minecraft versions
*/
@ApiStatus.Experimental
@MinecraftExperimental(MinecraftExperimental.Requires.TRADE_REBALANCE)
public static final TagKey<Enchantment> TRADES_PLAINS_SPECIAL = create(key("trades/plains_special"));
/**
* {@code #minecraft:on_traded_equipment}
*
* @apiNote This field is version-dependant and may be removed in future Minecraft versions
*/
public static final TagKey<Enchantment> ON_TRADED_EQUIPMENT = create(key("on_traded_equipment"));
/**
* {@code #minecraft:trades/desert_special}
*
* @apiNote This field is version-dependant and may be removed in future Minecraft versions
*/
@ApiStatus.Experimental
@MinecraftExperimental(MinecraftExperimental.Requires.TRADE_REBALANCE)
public static final TagKey<Enchantment> TRADES_DESERT_SPECIAL = create(key("trades/desert_special"));
/**
* {@code #minecraft:prevents_ice_melting}
*
* @apiNote This field is version-dependant and may be removed in future Minecraft versions
*/
public static final TagKey<Enchantment> PREVENTS_ICE_MELTING = create(key("prevents_ice_melting"));
/**
* {@code #minecraft:trades/taiga_common}
*
* @apiNote This field is version-dependant and may be removed in future Minecraft versions
*/
@ApiStatus.Experimental
@MinecraftExperimental(MinecraftExperimental.Requires.TRADE_REBALANCE)
public static final TagKey<Enchantment> TRADES_TAIGA_COMMON = create(key("trades/taiga_common"));
/**
* {@code #minecraft:tradeable}
*
* @apiNote This field is version-dependant and may be removed in future Minecraft versions
*/
public static final TagKey<Enchantment> TRADEABLE = create(key("tradeable"));
/**
* {@code #minecraft:curse}
*
* @apiNote This field is version-dependant and may be removed in future Minecraft versions
*/
public static final TagKey<Enchantment> CURSE = create(key("curse"));
/**
* {@code #minecraft:treasure}
*
* @apiNote This field is version-dependant and may be removed in future Minecraft versions
*/
public static final TagKey<Enchantment> TREASURE = create(key("treasure"));
/**
* {@code #minecraft:prevents_infested_spawns}
*
* @apiNote This field is version-dependant and may be removed in future Minecraft versions
*/
public static final TagKey<Enchantment> PREVENTS_INFESTED_SPAWNS = create(key("prevents_infested_spawns"));
/**
* {@code #minecraft:trades/savanna_special}
*
* @apiNote This field is version-dependant and may be removed in future Minecraft versions
*/
@ApiStatus.Experimental
@MinecraftExperimental(MinecraftExperimental.Requires.TRADE_REBALANCE)
public static final TagKey<Enchantment> TRADES_SAVANNA_SPECIAL = create(key("trades/savanna_special"));
/**
* {@code #minecraft:exclusive_set/riptide}
*
* @apiNote This field is version-dependant and may be removed in future Minecraft versions
*/
public static final TagKey<Enchantment> EXCLUSIVE_SET_RIPTIDE = create(key("exclusive_set/riptide"));
/**
* {@code #minecraft:double_trade_price}
*
* @apiNote This field is version-dependant and may be removed in future Minecraft versions
*/
public static final TagKey<Enchantment> DOUBLE_TRADE_PRICE = create(key("double_trade_price"));
/**
* {@code #minecraft:trades/taiga_special}
*
* @apiNote This field is version-dependant and may be removed in future Minecraft versions
*/
@ApiStatus.Experimental
@MinecraftExperimental(MinecraftExperimental.Requires.TRADE_REBALANCE)
public static final TagKey<Enchantment> TRADES_TAIGA_SPECIAL = create(key("trades/taiga_special"));
/**
* {@code #minecraft:smelts_loot}
*
* @apiNote This field is version-dependant and may be removed in future Minecraft versions
*/
public static final TagKey<Enchantment> SMELTS_LOOT = create(key("smelts_loot"));
/**
* {@code #minecraft:exclusive_set/boots}
*
* @apiNote This field is version-dependant and may be removed in future Minecraft versions
*/
public static final TagKey<Enchantment> EXCLUSIVE_SET_BOOTS = create(key("exclusive_set/boots"));
/**
* {@code #minecraft:trades/plains_common}
*
* @apiNote This field is version-dependant and may be removed in future Minecraft versions
*/
@ApiStatus.Experimental
@MinecraftExperimental(MinecraftExperimental.Requires.TRADE_REBALANCE)
public static final TagKey<Enchantment> TRADES_PLAINS_COMMON = create(key("trades/plains_common"));
/**
* {@code #minecraft:on_mob_spawn_equipment}
*
* @apiNote This field is version-dependant and may be removed in future Minecraft versions
*/
public static final TagKey<Enchantment> ON_MOB_SPAWN_EQUIPMENT = create(key("on_mob_spawn_equipment"));
/**
* {@code #minecraft:trades/desert_common}
*
* @apiNote This field is version-dependant and may be removed in future Minecraft versions
*/
@ApiStatus.Experimental
@MinecraftExperimental(MinecraftExperimental.Requires.TRADE_REBALANCE)
public static final TagKey<Enchantment> TRADES_DESERT_COMMON = create(key("trades/desert_common"));
/**
* {@code #minecraft:exclusive_set/mining}
*
* @apiNote This field is version-dependant and may be removed in future Minecraft versions
*/
public static final TagKey<Enchantment> EXCLUSIVE_SET_MINING = create(key("exclusive_set/mining"));
/**
* {@code #minecraft:tooltip_order}
*
* @apiNote This field is version-dependant and may be removed in future Minecraft versions
*/
public static final TagKey<Enchantment> TOOLTIP_ORDER = create(key("tooltip_order"));
/**
* {@code #minecraft:prevents_decorated_pot_shattering}
*
* @apiNote This field is version-dependant and may be removed in future Minecraft versions
*/
public static final TagKey<Enchantment> PREVENTS_DECORATED_POT_SHATTERING = create(key("prevents_decorated_pot_shattering"));
/**
* {@code #minecraft:exclusive_set/bow}
*
* @apiNote This field is version-dependant and may be removed in future Minecraft versions
*/
public static final TagKey<Enchantment> EXCLUSIVE_SET_BOW = create(key("exclusive_set/bow"));
/**
* {@code #minecraft:on_random_loot}
*
* @apiNote This field is version-dependant and may be removed in future Minecraft versions
*/
public static final TagKey<Enchantment> ON_RANDOM_LOOT = create(key("on_random_loot"));
/**
* {@code #minecraft:exclusive_set/armor}
*
* @apiNote This field is version-dependant and may be removed in future Minecraft versions
*/
public static final TagKey<Enchantment> EXCLUSIVE_SET_ARMOR = create(key("exclusive_set/armor"));
/**
* {@code #minecraft:trades/jungle_common}
*
* @apiNote This field is version-dependant and may be removed in future Minecraft versions
*/
@ApiStatus.Experimental
@MinecraftExperimental(MinecraftExperimental.Requires.TRADE_REBALANCE)
public static final TagKey<Enchantment> TRADES_JUNGLE_COMMON = create(key("trades/jungle_common"));
/**
* {@code #minecraft:in_enchanting_table}
*
* @apiNote This field is version-dependant and may be removed in future Minecraft versions
*/
public static final TagKey<Enchantment> IN_ENCHANTING_TABLE = create(key("in_enchanting_table"));
/**
* {@code #minecraft:trades/swamp_common}
*
* @apiNote This field is version-dependant and may be removed in future Minecraft versions
*/
@ApiStatus.Experimental
@MinecraftExperimental(MinecraftExperimental.Requires.TRADE_REBALANCE)
public static final TagKey<Enchantment> TRADES_SWAMP_COMMON = create(key("trades/swamp_common"));
/**
* {@code #minecraft:trades/snow_special}
*
* @apiNote This field is version-dependant and may be removed in future Minecraft versions
*/
@ApiStatus.Experimental
@MinecraftExperimental(MinecraftExperimental.Requires.TRADE_REBALANCE)
public static final TagKey<Enchantment> TRADES_SNOW_SPECIAL = create(key("trades/snow_special"));
/**
* {@code #minecraft:non_treasure}
*
* @apiNote This field is version-dependant and may be removed in future Minecraft versions
*/
public static final TagKey<Enchantment> NON_TREASURE = create(key("non_treasure"));
/**
* {@code #minecraft:trades/jungle_special}
*
* @apiNote This field is version-dependant and may be removed in future Minecraft versions
*/
@ApiStatus.Experimental
@MinecraftExperimental(MinecraftExperimental.Requires.TRADE_REBALANCE)
public static final TagKey<Enchantment> TRADES_JUNGLE_SPECIAL = create(key("trades/jungle_special"));
/**
* {@code #minecraft:prevents_bee_spawns_when_mining}
*
* @apiNote This field is version-dependant and may be removed in future Minecraft versions
*/
public static final TagKey<Enchantment> PREVENTS_BEE_SPAWNS_WHEN_MINING = create(key("prevents_bee_spawns_when_mining"));
/**
* {@code #minecraft:exclusive_set/damage}
*
* @apiNote This field is version-dependant and may be removed in future Minecraft versions
*/
public static final TagKey<Enchantment> EXCLUSIVE_SET_DAMAGE = create(key("exclusive_set/damage"));
/**
* {@code #minecraft:trades/savanna_common}
*
* @apiNote This field is version-dependant and may be removed in future Minecraft versions
*/
@ApiStatus.Experimental
@MinecraftExperimental(MinecraftExperimental.Requires.TRADE_REBALANCE)
public static final TagKey<Enchantment> TRADES_SAVANNA_COMMON = create(key("trades/savanna_common"));
/**
* {@code #minecraft:trades/snow_common}
*
* @apiNote This field is version-dependant and may be removed in future Minecraft versions
*/
@ApiStatus.Experimental
@MinecraftExperimental(MinecraftExperimental.Requires.TRADE_REBALANCE)
public static final TagKey<Enchantment> TRADES_SNOW_COMMON = create(key("trades/snow_common"));
/**
* {@code #minecraft:exclusive_set/crossbow}
*
* @apiNote This field is version-dependant and may be removed in future Minecraft versions
*/
public static final TagKey<Enchantment> EXCLUSIVE_SET_CROSSBOW = create(key("exclusive_set/crossbow"));
private EnchantmentTagKeys() {
}
/**
* Creates a tag key for {@link Enchantment} in the registry {@code minecraft:root}.
*
* @param key the tag key's key
* @return a new tag key
*/
@ApiStatus.Experimental
public static @NotNull TagKey<Enchantment> create(final @NotNull Key key) {
return TagKey.create(RegistryKey.ENCHANTMENT, key);
}
}

View File

@ -1,6 +1,7 @@
package io.papermc.generator;
import io.papermc.generator.types.GeneratedKeyType;
import io.papermc.generator.types.GeneratedTagKeyType;
import io.papermc.generator.types.SourceGenerator;
import io.papermc.generator.types.goal.MobGoalGenerator;
import io.papermc.paper.registry.RegistryKey;
@ -15,6 +16,7 @@ import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Wolf;
import org.bukkit.generator.structure.Structure;
import org.bukkit.generator.structure.StructureType;
import org.bukkit.inventory.ItemType;
import org.bukkit.inventory.meta.trim.TrimMaterial;
import org.bukkit.inventory.meta.trim.TrimPattern;
import org.bukkit.potion.PotionEffectType;
@ -33,10 +35,18 @@ public interface Generators {
simpleKey("MobEffectKeys", PotionEffectType.class, Registries.MOB_EFFECT, RegistryKey.MOB_EFFECT, false),
simpleKey("DamageTypeKeys", DamageType.class, Registries.DAMAGE_TYPE, RegistryKey.DAMAGE_TYPE, true),
simpleKey("WolfVariantKeys", Wolf.Variant.class, Registries.WOLF_VARIANT, RegistryKey.WOLF_VARIANT, true),
simpleKey("ItemTypeKeys", ItemType.class, Registries.ITEM, RegistryKey.ITEM, false),
simpleTagKey("EnchantmentTagKeys", Enchantment.class, Registries.ENCHANTMENT, RegistryKey.ENCHANTMENT),
simpleTagKey("ItemTypeTagKeys", ItemType.class, Registries.ITEM, RegistryKey.ITEM),
new MobGoalGenerator("VanillaGoal", "com.destroystokyo.paper.entity.ai")
};
private static <T, A> SourceGenerator simpleKey(final String className, final Class<A> apiType, final ResourceKey<? extends Registry<T>> registryKey, final RegistryKey<A> apiRegistryKey, final boolean publicCreateKeyMethod) {
return new GeneratedKeyType<>(className, apiType, "io.papermc.paper.registry.keys", registryKey, apiRegistryKey, publicCreateKeyMethod);
}
private static <T, A> SourceGenerator simpleTagKey(final String className, final Class<A> apiType, final ResourceKey<? extends Registry<T>> registryKey, final RegistryKey<A> apiRegistryKey) {
return new GeneratedTagKeyType<>(className, apiType, "io.papermc.paper.registry.keys.tags", registryKey, apiRegistryKey, true);
}
}

View File

@ -1,22 +1,29 @@
package io.papermc.generator;
import com.google.common.util.concurrent.MoreExecutors;
import com.mojang.logging.LogUtils;
import io.papermc.generator.types.SourceGenerator;
import io.papermc.generator.utils.TagCollector;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import net.minecraft.SharedConstants;
import net.minecraft.commands.Commands;
import net.minecraft.core.LayeredRegistryAccess;
import net.minecraft.core.RegistryAccess;
import net.minecraft.resources.RegistryDataLoader;
import net.minecraft.server.Bootstrap;
import net.minecraft.server.RegistryLayer;
import net.minecraft.server.ReloadableServerResources;
import net.minecraft.server.WorldLoader;
import net.minecraft.server.packs.PackType;
import net.minecraft.server.packs.repository.Pack;
import net.minecraft.server.packs.repository.PackRepository;
import net.minecraft.server.packs.repository.ServerPacksSource;
import net.minecraft.server.packs.resources.MultiPackResourceManager;
import net.minecraft.tags.TagKey;
import net.minecraft.world.flag.FeatureFlags;
import org.apache.commons.io.file.PathUtils;
import org.slf4j.Logger;
@ -24,6 +31,7 @@ public final class Main {
private static final Logger LOGGER = LogUtils.getLogger();
public static final RegistryAccess.Frozen REGISTRY_ACCESS;
public static final Map<TagKey<?>, String> EXPERIMENTAL_TAGS;
static {
SharedConstants.tryDetectVersion();
@ -36,6 +44,10 @@ public final class Main {
LayeredRegistryAccess<RegistryLayer> layers = RegistryLayer.createRegistryAccess();
layers = WorldLoader.loadAndReplaceLayer(resourceManager, layers, RegistryLayer.WORLDGEN, RegistryDataLoader.WORLDGEN_REGISTRIES);
REGISTRY_ACCESS = layers.compositeAccess().freeze();
final ReloadableServerResources datapack = ReloadableServerResources.loadResources(resourceManager, layers, FeatureFlags.REGISTRY.allFlags(), Commands.CommandSelection.DEDICATED, 0, MoreExecutors.directExecutor(), MoreExecutors.directExecutor()).join();
datapack.updateRegistryTags();
EXPERIMENTAL_TAGS = TagCollector.grabExperimental(resourceManager);
}
private Main() {

View File

@ -0,0 +1,149 @@
package io.papermc.generator.types;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import io.papermc.generator.Main;
import io.papermc.generator.utils.Annotations;
import io.papermc.generator.utils.Formatting;
import io.papermc.generator.utils.Javadocs;
import io.papermc.paper.registry.RegistryKey;
import io.papermc.paper.registry.tag.TagKey;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import net.kyori.adventure.key.Key;
import net.minecraft.core.Registry;
import net.minecraft.core.RegistrySetBuilder;
import net.minecraft.data.registries.VanillaRegistries;
import net.minecraft.resources.ResourceKey;
import org.bukkit.MinecraftExperimental;
import static com.squareup.javapoet.TypeSpec.classBuilder;
import static io.papermc.generator.utils.Annotations.EXPERIMENTAL_API_ANNOTATION;
import static io.papermc.generator.utils.Annotations.NOT_NULL;
import static io.papermc.generator.utils.Annotations.experimentalAnnotations;
import static java.util.Objects.requireNonNull;
import static javax.lang.model.element.Modifier.FINAL;
import static javax.lang.model.element.Modifier.PRIVATE;
import static javax.lang.model.element.Modifier.PUBLIC;
import static javax.lang.model.element.Modifier.STATIC;
public class GeneratedTagKeyType<T, A> extends SimpleGenerator {
private static final Map<ResourceKey<? extends Registry<?>>, RegistrySetBuilder.RegistryBootstrap<?>> VANILLA_REGISTRY_ENTRIES = VanillaRegistries.BUILDER.entries.stream()
.collect(Collectors.toMap(RegistrySetBuilder.RegistryStub::key, RegistrySetBuilder.RegistryStub::bootstrap));
private static final Map<ResourceKey<? extends Registry<?>>, RegistrySetBuilder.RegistryBootstrap<?>> EXPERIMENTAL_REGISTRY_ENTRIES = Collections.emptyMap(); // Update for Experimental API
private static final Map<RegistryKey<?>, String> REGISTRY_KEY_FIELD_NAMES;
static {
final Map<RegistryKey<?>, String> map = new HashMap<>();
try {
for (final Field field : RegistryKey.class.getFields()) {
if (!Modifier.isStatic(field.getModifiers()) || !Modifier.isFinal(field.getModifiers()) || field.getType() != RegistryKey.class) {
continue;
}
map.put((RegistryKey<?>) field.get(null), field.getName());
}
REGISTRY_KEY_FIELD_NAMES = Map.copyOf(map);
} catch (final ReflectiveOperationException ex) {
throw new RuntimeException(ex);
}
}
private static final String CREATE_JAVADOC = """
Creates a tag key for {@link $T} in the registry {@code $L}.
@param key the tag key's key
@return a new tag key
""";
private final Class<A> apiType;
private final ResourceKey<? extends Registry<T>> registryKey;
private final RegistryKey<A> apiRegistryKey;
private final boolean publicCreateKeyMethod;
public GeneratedTagKeyType(final String keysClassName, final Class<A> apiType, final String pkg, final ResourceKey<? extends Registry<T>> registryKey, final RegistryKey<A> apiRegistryKey, final boolean publicCreateKeyMethod) {
super(keysClassName, pkg);
this.apiType = apiType;
this.registryKey = registryKey;
this.apiRegistryKey = apiRegistryKey;
this.publicCreateKeyMethod = publicCreateKeyMethod;
}
private MethodSpec.Builder createMethod(final TypeName returnType) {
final TypeName keyType = TypeName.get(Key.class).annotated(NOT_NULL);
final ParameterSpec keyParam = ParameterSpec.builder(keyType, "key", FINAL).build();
final MethodSpec.Builder create = MethodSpec.methodBuilder("create")
.addModifiers(this.publicCreateKeyMethod ? PUBLIC : PRIVATE, STATIC)
.addParameter(keyParam)
.addCode("return $T.create($T.$L, $N);", TagKey.class, RegistryKey.class, requireNonNull(REGISTRY_KEY_FIELD_NAMES.get(this.apiRegistryKey), "Missing field for " + this.apiRegistryKey), keyParam)
.returns(returnType.annotated(NOT_NULL));
if (this.publicCreateKeyMethod) {
create.addAnnotation(EXPERIMENTAL_API_ANNOTATION); // TODO remove once not experimental
create.addJavadoc(CREATE_JAVADOC, this.apiType, this.registryKey.registry().toString());
}
return create;
}
private TypeSpec.Builder keyHolderType() {
return classBuilder(this.className)
.addModifiers(PUBLIC, FINAL)
.addJavadoc(Javadocs.getVersionDependentClassHeader("{@link $T#$L}"), RegistryKey.class, REGISTRY_KEY_FIELD_NAMES.get(this.apiRegistryKey))
.addAnnotations(Annotations.CLASS_HEADER)
.addMethod(MethodSpec.constructorBuilder()
.addModifiers(PRIVATE)
.build()
);
}
@Override
protected TypeSpec getTypeSpec() {
final TypeName tagKey = ParameterizedTypeName.get(TagKey.class, this.apiType);
final TypeSpec.Builder typeBuilder = this.keyHolderType();
final MethodSpec.Builder createMethod = this.createMethod(tagKey);
final Registry<T> registry = Main.REGISTRY_ACCESS.registryOrThrow(this.registryKey);
final AtomicBoolean allExperimental = new AtomicBoolean(true);
registry.getTags().forEach(pair -> {
final net.minecraft.tags.TagKey<T> nmsTagKey = pair.getFirst();
final String fieldName = Formatting.formatKeyAsField(nmsTagKey.location().getPath());
final FieldSpec.Builder fieldBuilder = FieldSpec.builder(tagKey, fieldName, PUBLIC, STATIC, FINAL)
.initializer("$N(key($S))", createMethod.build(), nmsTagKey.location().getPath())
.addJavadoc(Javadocs.getVersionDependentField("{@code $L}"), "#" + nmsTagKey.location());
if (Main.EXPERIMENTAL_TAGS.containsKey(nmsTagKey)) {
fieldBuilder.addAnnotations(experimentalAnnotations(MinecraftExperimental.Requires.TRADE_REBALANCE)); // Update for Experimental API
} else {
allExperimental.set(false);
}
typeBuilder.addField(fieldBuilder.build());
});
if (allExperimental.get()) {
typeBuilder.addAnnotations(experimentalAnnotations(null)); // Update for Experimental API
createMethod.addAnnotations(experimentalAnnotations(null)); // Update for Experimental API
} else {
typeBuilder.addAnnotation(EXPERIMENTAL_API_ANNOTATION); // TODO experimental API
}
return typeBuilder.addMethod(createMethod.build()).build();
}
@Override
protected JavaFile.Builder file(final JavaFile.Builder builder) {
return builder
.skipJavaLangImports(true)
.addStaticImport(Key.class, "key")
.indent(" ");
}
}

View File

@ -1,5 +1,6 @@
package io.papermc.generator.utils;
import java.util.Optional;
import org.apache.commons.lang3.math.NumberUtils;
import java.util.Comparator;
import java.util.Locale;
@ -15,6 +16,15 @@ public final class Formatting {
return ILLEGAL_FIELD_CHARACTERS.matcher(path.toUpperCase(Locale.ROOT)).replaceAll("_");
}
public static Optional<String> formatTagKey(String tagDir, String resourcePath) {
int tagsIndex = resourcePath.indexOf(tagDir);
int dotIndex = resourcePath.lastIndexOf('.');
if (tagsIndex == -1 || dotIndex == -1) {
return Optional.empty();
}
return Optional.of(resourcePath.substring(tagsIndex + tagDir.length() + 1, dotIndex)); // namespace/tags/registry_key/[tag_key].json
}
public static Comparator<String> ALPHABETIC_KEY_ORDER = alphabeticKeyOrder(path -> path);
public static <T> Comparator<T> alphabeticKeyOrder(Function<T, String> mapper) {

View File

@ -0,0 +1,81 @@
package io.papermc.generator.utils;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.mojang.logging.LogUtils;
import io.papermc.generator.Main;
import io.papermc.generator.utils.Formatting;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import net.minecraft.core.Registry;
import net.minecraft.core.RegistryAccess;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.packs.PackResources;
import net.minecraft.server.packs.PackType;
import net.minecraft.server.packs.repository.BuiltInPackSource;
import net.minecraft.server.packs.resources.MultiPackResourceManager;
import net.minecraft.tags.TagKey;
import net.minecraft.tags.TagManager;
import org.slf4j.Logger;
// collect all the tags by grabbing the json from the data-packs
// another (probably) way is to hook into the data generator like the typed keys generator
public final class TagCollector {
private static final Logger LOGGER = LogUtils.getLogger();
public static Map<TagKey<?>, String> grabExperimental(final MultiPackResourceManager resourceManager) {
Map<TagKey<?>, String> result = new IdentityHashMap<>();
// collect all vanilla tags
Multimap<ResourceKey<? extends Registry<?>>, String> vanillaTags = HashMultimap.create();
PackResources vanillaPack = resourceManager.listPacks()
.filter(packResources -> packResources.packId().equals(BuiltInPackSource.VANILLA_ID))
.findFirst()
.orElseThrow();
collectFromPack(vanillaPack, (entry, path) -> vanillaTags.put(entry.key(), path));
// then distinct with other data-pack tags to know for sure newly created tags and so experimental one
resourceManager.listPacks().forEach(pack -> {
String packId = pack.packId();
if (packId.equals(BuiltInPackSource.VANILLA_ID)) return;
collectFromPack(pack, (entry, path) -> {
if (vanillaTags.get(entry.key()).contains(path)) {
return;
}
result.put(entry.value().getTagNames()
.filter(tagKey -> tagKey.location().getPath().equals(path))
.findFirst()
.orElseThrow(), packId);
});
});
return Collections.unmodifiableMap(result);
}
private static void collectFromPack(PackResources pack, BiConsumer<RegistryAccess.RegistryEntry<?>, String> output) {
Set<String> namespaces = pack.getNamespaces(PackType.SERVER_DATA);
for (String namespace : namespaces) {
Main.REGISTRY_ACCESS.registries().forEach(entry -> {
// this is probably expensive but can't find another way around and data-pack loader has similar logic
// the issue is that registry key can have parent/key (and custom folder too) but tag key can also have parent/key so parsing become a mess
// without having at least one of the two values
String tagDir = Registries.tagsDirPath(entry.key());
pack.listResources(PackType.SERVER_DATA, namespace, tagDir, (id, supplier) -> {
Formatting.formatTagKey(tagDir, id.getPath()).ifPresentOrElse(path -> output.accept(entry, path), () -> {
LOGGER.warn("Unable to parse the path: {}/{}/{}.json in the data-pack {} into a tag key", namespace, tagDir, id.getPath(), pack.packId());
});
});
});
}
}
private TagCollector() {
}
}