Forge 1.19.3

Created a CreativeModeTabEvent to register creative mode tabs and populate entries per tab
Moved datapack registries to DataPackRegistryEvent.NewRegistry event instead of tying them to ForgeRegistry
Made it easier for mods to datagen datapack builtin entries with DatapackBuiltinEntriesProvider
Provided access to lookupProvider for datagen
Updated dependencies to match versions used by vanilla and update JarJar to 0.3.18
Added a test mod for the new CreativeModeTabEvent
Throws better error message for Forge registries in tag datagen
Deleted ForgeRegistryTagsProvider
Updated ClientChatReceivedEvent and ServerChatEvent for Mojang changes
Added patches for both sign related methods in ModelLayers
Changed RegisterShadersEvent to use ResourceProvider
Migrated old Mojang math types to JOML

Co-authored-by: Marc Hermans <[email protected]>
Co-authored-by: LexManos <[email protected]>
Co-authored-by: sciwhiz12 <[email protected]>
Co-authored-by: coehlrich <[email protected]>
This commit is contained in:
committed 2022-12-08 01:45:22 -06:00
1 parent 617ecb7ad3
commit 8255d7aed3
726 files changed
+7615 -6653

No files matched your search

@@ -5,51 +5,47 @@
package net.minecraftforge.registries;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import com.google.common.collect.ImmutableMap;
import net.minecraft.core.Registry;
import net.minecraft.core.RegistryAccess;
import net.minecraft.resources.RegistryDataLoader;
import net.minecraft.resources.ResourceKey;
import org.jetbrains.annotations.ApiStatus;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@ApiStatus.Internal
public final class DataPackRegistriesHooks
{
private DataPackRegistriesHooks() {} // utility class
private static Map<ResourceKey<? extends Registry<?>>, RegistryAccess.RegistryData<?>> REGISTRY_ACCESS_REGISTRIES_COPY;
private static final Set<ResourceKey<? extends Registry<?>>> SYNCED_CUSTOM_REGISTRIES = new HashSet<>();
private static final Set<ResourceKey<? extends Registry<?>>> SYNCED_CUSTOM_REGISTRIES_VIEW = Collections.unmodifiableSet(SYNCED_CUSTOM_REGISTRIES);
/* Internal forge hook for retaining mutable access to RegistryAccess's codec registry when it bootstraps. */
public static Map<ResourceKey<? extends Registry<?>>, RegistryAccess.RegistryData<?>> grabBuiltinRegistries(ImmutableMap.Builder<ResourceKey<? extends Registry<?>>, RegistryAccess.RegistryData<?>> builder)
{
REGISTRY_ACCESS_REGISTRIES_COPY = new HashMap<>(builder.build());
SYNCED_CUSTOM_REGISTRIES.clear();
return Collections.unmodifiableMap(REGISTRY_ACCESS_REGISTRIES_COPY);
}
private static final List<RegistryDataLoader.RegistryData<?>> DATA_PACK_REGISTRIES = new ArrayList<>(RegistryDataLoader.WORLDGEN_REGISTRIES);
private static final List<RegistryDataLoader.RegistryData<?>> DATA_PACK_REGISTRIES_VIEW = Collections.unmodifiableList(DATA_PACK_REGISTRIES);
private static final Set<ResourceKey<? extends Registry<?>>> SYNCED_CUSTOM_REGISTRIES = new HashSet<>();
private static final Set<ResourceKey<? extends Registry<?>>> SYNCED_CUSTOM_REGISTRIES_VIEW = Collections.unmodifiableSet(SYNCED_CUSTOM_REGISTRIES);
/* Internal forge method, registers a datapack registry codec and folder. */
public static <T> void addRegistryCodec(@NotNull RegistryAccess.RegistryData<T> data)
static <T> void addRegistryCodec(DataPackRegistryEvent.DataPackRegistryData<T> data)
{
ResourceKey<? extends Registry<T>> registryKey = data.key();
REGISTRY_ACCESS_REGISTRIES_COPY.put(registryKey, data);
RegistryDataLoader.RegistryData<T> loaderData = data.loaderData();
DATA_PACK_REGISTRIES.add(loaderData);
if (data.networkCodec() != null)
{
SYNCED_CUSTOM_REGISTRIES.add(registryKey);
}
SYNCED_CUSTOM_REGISTRIES.add(loaderData.key());
}
/**
* {@return unmodifiable view of the set of synced non-vanilla datapack registry IDs}
* {@return An unmodifiable view of the list of datapack registries}.
* These registries are loaded from per-world datapacks on server startup.
*/
public static List<RegistryDataLoader.RegistryData<?>> getDataPackRegistries()
{
return DATA_PACK_REGISTRIES_VIEW;
}
/**
* {@return An unmodifiable view of the set of synced non-vanilla datapack registry IDs}
* Clients must have each of a server's synced datapack registries to be able to connect to that server;
* vanilla clients therefore cannot connect if this list is non-empty on the server.
*/
@@ -0,0 +1,94 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.registries;
import com.mojang.serialization.Codec;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.client.multiplayer.ClientPacketListener;
import net.minecraft.core.Registry;
import net.minecraft.resources.RegistryDataLoader;
import net.minecraft.resources.ResourceKey;
import net.minecraftforge.eventbus.api.Cancelable;
import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.event.IModBusEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;
public class DataPackRegistryEvent extends Event implements IModBusEvent
{
@ApiStatus.Internal
public DataPackRegistryEvent() {}
/**
* Fired when datapack registries can be registered.
* Datapack registries are registries which can only load entries through JSON files from datapacks.
* <p>
* Data JSONs will be loaded from {@code data/<datapack_namespace>/modid/registryname/}, where {@code modid} is the namespace of the registry key.
* <p>
* This event is not {@linkplain Cancelable cancellable}, and does not {@linkplain HasResult have a result}.
* <p>
* This event is fired on the {@linkplain FMLJavaModLoadingContext#getModEventBus() mod-specific event bus},
* on both {@linkplain LogicalSide logical sides}.
*/
public static final class NewRegistry extends DataPackRegistryEvent
{
private final List<DataPackRegistryData<?>> registryDataList = new ArrayList<>();
@ApiStatus.Internal
public NewRegistry() {}
/**
* Registers the given registry key as an unsynced datapack registry, which will cause data to be loaded from
* a datapack folder based on the registry's name. The datapack registry is not required to be present
* on clients when connecting to servers with the mod/registry.
* <p>
* Data JSONs will be loaded from {@code data/<datapack_namespace>/modid/registryname/}, where {@code modid} is the namespace of the registry key.
*
* @param registryKey the root registry key of the new datapack registry
* @param codec the codec to be used for loading data from datapacks on servers
* @see #dataPackRegistry(ResourceKey, Codec, Codec)
*/
public <T> void dataPackRegistry(ResourceKey<Registry<T>> registryKey, Codec<T> codec)
{
this.dataPackRegistry(registryKey, codec, null);
}
/**
* Registers the registry key as a datapack registry, which will cause data to be loaded from
* a datapack folder based on the registry's name.
* <p>
* Data JSONs will be loaded from {@code data/<datapack_namespace>/modid/registryname/}, where {@code modid} is the namespace of the registry key.
*
* @param registryKey the root registry key of the new datapack registry
* @param codec the codec to be used for loading data from datapacks on servers
* @param networkCodec the codec to be used for syncing loaded data to clients.
* If {@code networkCodec} is null, data will not be synced, and clients are not required to have this
* datapack registry to join a server.
* <p>
* If {@code networkCodec} is not null, clients must have this datapack registry/mod
* when joining a server that has this datapack registry/mod.
* The data will be synced using the network codec and accessible via {@link ClientPacketListener#registryAccess()}.
* @see #dataPackRegistry(ResourceKey, Codec)
*/
public <T> void dataPackRegistry(ResourceKey<Registry<T>> registryKey, Codec<T> codec, @Nullable Codec<T> networkCodec)
{
this.registryDataList.add(new DataPackRegistryData<>(new RegistryDataLoader.RegistryData<>(registryKey, codec), networkCodec));
}
void process()
{
for (DataPackRegistryData<?> registryData : this.registryDataList)
{
DataPackRegistriesHooks.addRegistryCodec(registryData);
}
}
}
record DataPackRegistryData<T>(RegistryDataLoader.RegistryData<T> loaderData, @Nullable Codec<T> networkCodec) {}
}
@@ -8,7 +8,7 @@ package net.minecraftforge.registries;
import com.google.common.collect.Multimaps;
import com.google.common.collect.SetMultimap;
import net.minecraft.core.Registry;
import net.minecraft.data.BuiltinRegistries;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.TagKey;
@@ -69,9 +69,8 @@ public class DeferredRegister<T>
}
/**
* DeferredRegister factory for custom forge registries, {@link Registry vanilla registries},
* or {@link BuiltinRegistries built-in registries} to lookup based on the provided registry key.
* Supports both registries that already exist or do not exist yet.
* DeferredRegister factory for custom forge registries or {@link BuiltInRegistries vanilla registries}
* to lookup based on the provided registry key. Supports both registries that already exist or do not exist yet.
* <p>
* If the registry is never created, any {@link RegistryObject}s made from this DeferredRegister will throw an exception.
* To allow the optional existence of a registry without error, use {@link #createOptional(ResourceKey, String)}.
@@ -88,8 +87,8 @@ public class DeferredRegister<T>
}
/**
* DeferredRegister factory for the optional existence of custom forge registries, {@link Registry vanilla registries},
* or {@link BuiltinRegistries built-in registries} to lookup based on the provided registry key.
* DeferredRegister factory for the optional existence of custom forge registries
* or {@link BuiltInRegistries vanilla registries} to lookup based on the provided registry key.
* Supports both registries that already exist or do not exist yet.
* <p>
* If the registry is never created, any {@link RegistryObject}s made from this DeferredRegister will never be filled but will not throw an exception.
@@ -106,9 +105,8 @@ public class DeferredRegister<T>
}
/**
* DeferredRegister factory for custom forge registries, {@link Registry vanilla registries},
* or {@link BuiltinRegistries built-in registries} to lookup based on the provided registry name.
* Supports both registries that already exist or do not exist yet.
* DeferredRegister factory for custom forge registries or {@link BuiltInRegistries vanilla registries}
* to lookup based on the provided registry name. Supports both registries that already exist or do not exist yet.
* <p>
* If the registry is never created, any {@link RegistryObject}s made from this DeferredRegister will throw an exception.
* To allow the optional existence of a registry without error, use {@link #createOptional(ResourceLocation, String)}.
@@ -125,10 +123,10 @@ public class DeferredRegister<T>
}
/**
* DeferredRegister factory for the optional existence of custom forge registries, {@link Registry vanilla registries},
* or {@link BuiltinRegistries built-in registries} to lookup based on the provided registry name.
* DeferredRegister factory for the optional existence of custom forge registries
* or {@link BuiltInRegistries vanilla registries} to lookup based on the provided registry name.
* Supports both registries that already exist or do not exist yet.
* <p>
* The registry may not exist at the time this DeferredRegister is created.
* If the registry is never created, any {@link RegistryObject}s made from this DeferredRegister will never be filled but will not throw an exception.
*
* @param registryName The name of the registry, should include namespace. May come from another DeferredRegister through {@link #getRegistryName()}.
@@ -5,6 +5,8 @@
package net.minecraftforge.registries;
import net.minecraftforge.common.world.BiomeModifier;
import net.minecraftforge.common.world.StructureModifier;
import net.minecraftforge.eventbus.api.IEventBus;
public class ForgeDeferredRegistriesSetup
@@ -23,9 +25,7 @@ public class ForgeDeferredRegistriesSetup
ForgeRegistries.DEFERRED_GLOBAL_LOOT_MODIFIER_SERIALIZERS.register(modEventBus);
ForgeRegistries.DEFERRED_BIOME_MODIFIER_SERIALIZERS.register(modEventBus);
ForgeRegistries.DEFERRED_FLUID_TYPES.register(modEventBus);
ForgeRegistries.DEFERRED_BIOME_MODIFIERS.register(modEventBus);
ForgeRegistries.DEFERRED_STRUCTURE_MODIFIER_SERIALIZERS.register(modEventBus);
ForgeRegistries.DEFERRED_STRUCTURE_MODIFIERS.register(modEventBus);
ForgeRegistries.DEFERRED_HOLDER_SET_TYPES.register(modEventBus);
setup = true;
@@ -45,8 +45,10 @@ import net.minecraftforge.common.Tags;
import net.minecraftforge.common.loot.IGlobalLootModifier;
import net.minecraftforge.common.world.BiomeModifier;
import net.minecraftforge.fluids.FluidType;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.registries.holdersets.HolderSetType;
import java.util.function.Consumer;
import java.util.function.Supplier;
import net.minecraftforge.common.world.StructureModifier;
@@ -135,12 +137,6 @@ public class ForgeRegistries
*/
public static final Supplier<IForgeRegistry<HolderSetType>> HOLDER_SET_TYPES = DEFERRED_HOLDER_SET_TYPES.makeRegistry(GameData::getHolderSetTypeRegistryBuilder);
// Custom forge datapack registries
static final DeferredRegister<BiomeModifier> DEFERRED_BIOME_MODIFIERS = DeferredRegister.create(Keys.BIOME_MODIFIERS, "forge");
public static final Supplier<IForgeRegistry<BiomeModifier>> BIOME_MODIFIERS_BUILTIN = DEFERRED_BIOME_MODIFIERS.makeRegistry(() -> new RegistryBuilder<BiomeModifier>().disableSaving().dataPackRegistry(BiomeModifier.DIRECT_CODEC));
static final DeferredRegister<StructureModifier> DEFERRED_STRUCTURE_MODIFIERS = DeferredRegister.create(Keys.STRUCTURE_MODIFIERS, "forge");
public static final Supplier<IForgeRegistry<StructureModifier>> STRUCTURE_MODIFIERS_BUILTIN = DEFERRED_STRUCTURE_MODIFIERS.makeRegistry(() -> new RegistryBuilder<StructureModifier>().disableSaving().dataPackRegistry(StructureModifier.DIRECT_CODEC));
public static final class Keys {
//Vanilla
public static final ResourceKey<Registry<Block>> BLOCKS = key("block");
@@ -233,7 +233,7 @@ public class ForgeRegistry<V> implements IForgeRegistryInternal<V>, IForgeRegist
@SuppressWarnings("unchecked")
@Nullable
Registry<V> getWrapper()
NamespacedWrapper<V> getWrapper()
{
if (!this.hasWrapper)
return null;
@@ -244,9 +244,9 @@ public class ForgeRegistry<V> implements IForgeRegistryInternal<V>, IForgeRegist
}
@NotNull
Registry<V> getWrapperOrThrow()
NamespacedWrapper<V> getWrapperOrThrow()
{
Registry<V> wrapper = getWrapper();
NamespacedWrapper<V> wrapper = getWrapper();
if (wrapper == null)
throw new IllegalStateException("Cannot query wrapper for non-wrapped forge registry!");
@@ -254,18 +254,6 @@ public class ForgeRegistry<V> implements IForgeRegistryInternal<V>, IForgeRegist
return wrapper;
}
@SuppressWarnings("unchecked")
@NotNull
Optional<NamespacedHolderHelper<V>> getHolderHelper()
{
Registry<V> wrapper = getWrapper();
if (!(wrapper instanceof IHolderHelperHolder))
return Optional.empty();
// Unsafe cast means we can't use pattern matching here
return Optional.of(((IHolderHelperHolder<V>) wrapper).getHolderHelper());
}
void onBindTags(Map<TagKey<V>, HolderSet.Named<V>> tags, Set<TagKey<V>> defaultedTags)
{
if (this.tagManager != null)
@@ -276,21 +264,21 @@ public class ForgeRegistry<V> implements IForgeRegistryInternal<V>, IForgeRegist
@Override
public Optional<Holder<V>> getHolder(ResourceKey<V> key)
{
return getHolderHelper().flatMap(h -> h.getHolder(key));
return Optional.ofNullable(this.getWrapper()).flatMap(wrapper -> wrapper.getHolder(key));
}
@NotNull
@Override
public Optional<Holder<V>> getHolder(ResourceLocation location)
{
return getHolderHelper().flatMap(h -> h.getHolder(location));
return Optional.ofNullable(this.getWrapper()).flatMap(wrapper -> wrapper.getHolder(location));
}
@NotNull
@Override
public Optional<Holder<V>> getHolder(V value)
{
return getHolderHelper().flatMap(h -> h.getHolder(value));
return Optional.ofNullable(this.getWrapper()).flatMap(wrapper -> wrapper.getHolder(value));
}
@Nullable
@@ -552,8 +540,9 @@ public class ForgeRegistry<V> implements IForgeRegistryInternal<V>, IForgeRegist
private Holder.Reference<V> bindDelegate(ResourceKey<V> rkey, V value)
{
Holder.Reference<V> delegate = delegatesByName.computeIfAbsent(rkey.location(), k -> Holder.Reference.createStandAlone(this.getWrapperOrThrow(), rkey));
delegate.bind(rkey, value);
Holder.Reference<V> delegate = delegatesByName.computeIfAbsent(rkey.location(), k -> Holder.Reference.createStandAlone(this.getWrapperOrThrow().holderOwner(), rkey));
delegate.bindKey(rkey);
delegate.bindValue(value);
delegatesByValue.put(value, delegate);
return delegate;
}
@@ -914,18 +903,18 @@ public class ForgeRegistry<V> implements IForgeRegistryInternal<V>, IForgeRegist
return false;
ForgeRegistry<V> active = RegistryManager.ACTIVE.getRegistry(getRegistryKey());
Optional<NamespacedHolderHelper<V>> holders = active.getHolderHelper();
if (holders.isPresent() && holders.get().isIntrusive() && holders.get().isFrozen())
NamespacedWrapper<V> wrapper = active.getWrapper();
if (wrapper != null && wrapper.isIntrusive() && wrapper.isFrozen())
{
try
{
// We have to unfreeze the ACTIVE registry because a lot of vanilla objects use intrusive handlers in object init.
holders.get().unfreeze();
wrapper.unfreeze();
createAndAddDummy(key, id);
}
finally
{
holders.get().freeze();
wrapper.freeze();
}
}
else
@@ -133,6 +133,8 @@ class ForgeRegistryTagManager<V> implements ITagManager<V>
Objects.requireNonNull(name);
Objects.requireNonNull(defaults);
this.owner.getHolderHelper().ifPresent(h -> h.addOptionalTag(name, defaults));
NamespacedWrapper<V> wrapper = this.owner.getWrapper();
if (wrapper != null)
wrapper.addOptionalTag(name, defaults);
}
}
@@ -6,19 +6,27 @@
package net.minecraftforge.registries;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.mojang.serialization.Codec;
import com.mojang.serialization.Lifecycle;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import net.minecraft.core.DefaultedRegistry;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
import net.minecraft.core.IdMapper;
import net.minecraft.core.MappedRegistry;
import net.minecraft.core.Registry;
import net.minecraft.data.BuiltinRegistries;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.network.syncher.EntityDataSerializer;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
@@ -36,6 +44,7 @@ import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.levelgen.DebugLevelSource;
import net.minecraft.world.level.material.Fluid;
import net.minecraft.world.level.material.Material;
import net.minecraftforge.common.CreativeModeTabRegistry;
import net.minecraftforge.common.ForgeHooks;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.loot.IGlobalLootModifier;
@@ -49,27 +58,46 @@ import net.minecraftforge.fml.StartupMessageManager;
import net.minecraftforge.fml.util.EnhancedRuntimeException;
import net.minecraftforge.fml.util.thread.EffectiveSide;
import net.minecraftforge.registries.holdersets.HolderSetType;
import org.apache.commons.lang3.Validate;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
import static net.minecraftforge.registries.ForgeRegistries.Keys.ACTIVITIES;
import static net.minecraftforge.registries.ForgeRegistries.Keys.ATTRIBUTES;
import static net.minecraftforge.registries.ForgeRegistries.Keys.BIOMES;
import static net.minecraftforge.registries.ForgeRegistries.Keys.BLOCKS;
import static net.minecraftforge.registries.ForgeRegistries.Keys.BLOCK_ENTITY_TYPES;
import static net.minecraftforge.registries.ForgeRegistries.Keys.BLOCK_STATE_PROVIDER_TYPES;
import static net.minecraftforge.registries.ForgeRegistries.Keys.CHUNK_STATUS;
import static net.minecraftforge.registries.ForgeRegistries.Keys.COMMAND_ARGUMENT_TYPES;
import static net.minecraftforge.registries.ForgeRegistries.Keys.ENCHANTMENTS;
import static net.minecraftforge.registries.ForgeRegistries.Keys.ENTITY_DATA_SERIALIZERS;
import static net.minecraftforge.registries.ForgeRegistries.Keys.ENTITY_TYPES;
import static net.minecraftforge.registries.ForgeRegistries.Keys.FEATURES;
import static net.minecraftforge.registries.ForgeRegistries.Keys.FLUIDS;
import static net.minecraftforge.registries.ForgeRegistries.Keys.FLUID_TYPES;
import static net.minecraftforge.registries.ForgeRegistries.Keys.FOLIAGE_PLACER_TYPES;
import static net.minecraftforge.registries.ForgeRegistries.Keys.GLOBAL_LOOT_MODIFIER_SERIALIZERS;
import static net.minecraftforge.registries.ForgeRegistries.Keys.ITEMS;
import static net.minecraftforge.registries.ForgeRegistries.Keys.MEMORY_MODULE_TYPES;
import static net.minecraftforge.registries.ForgeRegistries.Keys.MENU_TYPES;
import static net.minecraftforge.registries.ForgeRegistries.Keys.MOB_EFFECTS;
import static net.minecraftforge.registries.ForgeRegistries.Keys.PAINTING_VARIANTS;
import static net.minecraftforge.registries.ForgeRegistries.Keys.PARTICLE_TYPES;
import static net.minecraftforge.registries.ForgeRegistries.Keys.POI_TYPES;
import static net.minecraftforge.registries.ForgeRegistries.Keys.POTIONS;
import static net.minecraftforge.registries.ForgeRegistries.Keys.RECIPE_SERIALIZERS;
import static net.minecraftforge.registries.ForgeRegistries.Keys.RECIPE_TYPES;
import static net.minecraftforge.registries.ForgeRegistries.Keys.SCHEDULES;
import static net.minecraftforge.registries.ForgeRegistries.Keys.SENSOR_TYPES;
import static net.minecraftforge.registries.ForgeRegistries.Keys.SOUND_EVENTS;
import static net.minecraftforge.registries.ForgeRegistries.Keys.STAT_TYPES;
import static net.minecraftforge.registries.ForgeRegistries.Keys.TREE_DECORATOR_TYPES;
import static net.minecraftforge.registries.ForgeRegistries.Keys.VILLAGER_PROFESSIONS;
import static net.minecraftforge.registries.ForgeRegistries.Keys.WORLD_CARVERS;
import static net.minecraftforge.registries.ForgeRegistry.REGISTRIES;
import static net.minecraftforge.registries.ForgeRegistries.Keys.*;
/**
* INTERNAL ONLY
@@ -105,14 +133,14 @@ public class GameData
hasInit = true;
// Game objects
makeRegistry(BLOCKS, "air").addCallback(BlockCallbacks.INSTANCE).legacyName("blocks").vanillaHolder(Block::builtInRegistryHolder).create();
makeRegistry(FLUIDS, "empty").vanillaHolder(Fluid::builtInRegistryHolder).create();
makeRegistry(ITEMS, "air").addCallback(ItemCallbacks.INSTANCE).legacyName("items").vanillaHolder(Item::builtInRegistryHolder).create();
makeRegistry(BLOCKS, "air").addCallback(BlockCallbacks.INSTANCE).legacyName("blocks").intrusiveHolderCallback(Block::builtInRegistryHolder).create();
makeRegistry(FLUIDS, "empty").intrusiveHolderCallback(Fluid::builtInRegistryHolder).create();
makeRegistry(ITEMS, "air").addCallback(ItemCallbacks.INSTANCE).legacyName("items").intrusiveHolderCallback(Item::builtInRegistryHolder).create();
makeRegistry(MOB_EFFECTS).legacyName("potions").create();
makeRegistry(SOUND_EVENTS).legacyName("soundevents").create();
makeRegistry(POTIONS, "empty").legacyName("potiontypes").create();
makeRegistry(ENCHANTMENTS).legacyName("enchantments").create();
makeRegistry(ENTITY_TYPES, "pig").legacyName("entities").vanillaHolder(EntityType::builtInRegistryHolder).create();
makeRegistry(ENTITY_TYPES, "pig").legacyName("entities").intrusiveHolderCallback(EntityType::builtInRegistryHolder).create();
makeRegistry(BLOCK_ENTITY_TYPES).disableSaving().legacyName("blockentities").create();
makeRegistry(PARTICLE_TYPES).disableSaving().create();
makeRegistry(MENU_TYPES).disableSaving().create();
@@ -196,12 +224,12 @@ public class GameData
return ret;
}
public static <T> DefaultedRegistry<T> getWrapper(ResourceKey<? extends Registry<T>> key, Lifecycle lifecycle, String defKey)
public static <T> MappedRegistry<T> getWrapper(ResourceKey<? extends Registry<T>> key, Lifecycle lifecycle, String defKey)
{
IForgeRegistry<T> reg = RegistryManager.ACTIVE.getRegistry(key);
Validate.notNull(reg, "Attempted to get vanilla wrapper for unknown registry: " + key.toString());
@SuppressWarnings("unchecked")
DefaultedRegistry<T> ret = reg.getSlaveMap(NamespacedDefaultedWrapper.Factory.ID, NamespacedDefaultedWrapper.class);
MappedRegistry<T> ret = reg.getSlaveMap(NamespacedDefaultedWrapper.Factory.ID, NamespacedDefaultedWrapper.class);
Validate.notNull(ret, "Attempted to get vanilla wrapper for registry created incorrectly: " + key.toString());
return ret;
}
@@ -245,14 +273,14 @@ public class GameData
public static void unfreezeData()
{
LOGGER.debug(REGISTRIES, "Unfreezing vanilla registries");
Registry.REGISTRY.stream().filter(r -> r instanceof MappedRegistry).forEach(r -> ((MappedRegistry<?>)r).unfreeze());
BuiltInRegistries.REGISTRY.stream().filter(r -> r instanceof MappedRegistry).forEach(r -> ((MappedRegistry<?>)r).unfreeze());
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void freezeData()
{
LOGGER.debug(REGISTRIES, "Freezing registries");
Registry.REGISTRY.stream().filter(r -> r instanceof MappedRegistry).forEach(r -> ((MappedRegistry<?>)r).freeze());
BuiltInRegistries.REGISTRY.stream().filter(r -> r instanceof MappedRegistry).forEach(r -> ((MappedRegistry<?>)r).freeze());
for (Map.Entry<ResourceLocation, ForgeRegistry<?>> r : RegistryManager.ACTIVE.registries.entrySet())
{
@@ -317,7 +345,6 @@ public class GameData
{
Set<ResourceLocation> keySet = new HashSet<>(RegistryManager.ACTIVE.registries.keySet());
keySet.addAll(RegistryManager.getVanillaRegistryKeys());
keySet.addAll(BuiltinRegistries.REGISTRY.keySet());
Set<ResourceLocation> ordered = new LinkedHashSet<>(MappedRegistry.getKnownRegistries());
ordered.retainAll(keySet);
@@ -331,7 +358,7 @@ public class GameData
{
ResourceKey<? extends Registry<?>> registryKey = ResourceKey.createRegistryKey(rootRegistryName);
ForgeRegistry<?> forgeRegistry = RegistryManager.ACTIVE.getRegistry(rootRegistryName);
Registry<?> vanillaRegistry = Registry.REGISTRY.containsKey(rootRegistryName) ? Registry.REGISTRY.get(rootRegistryName) : BuiltinRegistries.REGISTRY.get(rootRegistryName);
Registry<?> vanillaRegistry = BuiltInRegistries.REGISTRY.get(rootRegistryName);
RegisterEvent registerEvent = new RegisterEvent(registryKey, forgeRegistry, vanillaRegistry);
StartupMessageManager.modLoaderConsumer().ifPresent(s -> s.accept("REGISTERING " + registryKey.location()));
@@ -362,6 +389,7 @@ public class GameData
{
ForgeHooks.modifyAttributes();
SpawnPlacements.fireSpawnPlacementEvent();
CreativeModeTabRegistry.fireCollectionEvent();
}
}
@@ -1,11 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.registries;
interface IHolderHelperHolder<T>
{
NamespacedHolderHelper<T> getHolderHelper();
}
@@ -5,135 +5,42 @@
package net.minecraftforge.registries;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Stream;
import com.mojang.serialization.DataResult;
import net.minecraft.core.DefaultedRegistry;
import net.minecraft.core.Holder;
import net.minecraft.core.HolderSet;
import net.minecraft.core.Registry;
import net.minecraft.util.RandomSource;
import org.apache.commons.lang3.Validate;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.TagKey;
import net.minecraft.core.DefaultedRegistry;
import com.mojang.datafixers.util.Pair;
import com.mojang.serialization.Lifecycle;
import net.minecraft.util.RandomSource;
import org.jetbrains.annotations.Nullable;
class NamespacedDefaultedWrapper<T> extends DefaultedRegistry<T> implements ILockableRegistry, IHolderHelperHolder<T>
class NamespacedDefaultedWrapper<T> extends NamespacedWrapper<T> implements DefaultedRegistry<T>
{
private final ForgeRegistry<T> delegate;
private final NamespacedHolderHelper<T> holders;
private final ResourceLocation defaultKey;
private Holder.Reference<T> defaultHolder;
private boolean locked = false;
private Lifecycle elementsLifecycle = Lifecycle.experimental();
private NamespacedDefaultedWrapper(ForgeRegistry<T> owner, Function<T, Holder.Reference<T>> holderLookup)
{
super("empty", owner.getRegistryKey(), Lifecycle.experimental(), holderLookup);
this.delegate = owner;
this.holders = new NamespacedHolderHelper<>(owner, this, this.delegate.getDefaultKey(), holderLookup);
}
@Override
public Holder<T> registerMapping(final int id, final ResourceKey<T> key, final T value, final Lifecycle lifecycle)
{
if (locked)
throw new IllegalStateException("Can not register to a locked registry. Modder should use Forge Register methods.");
Validate.notNull(value);
markKnown();
this.elementsLifecycle = this.elementsLifecycle.add(lifecycle);
T oldValue = this.delegate.getRaw(key.location());
int realId = this.delegate.add(id, key.location(), value);
return this.holders.onAdded(RegistryManager.ACTIVE, realId, key, value, oldValue);
}
@Override
public Holder<T> register(final ResourceKey<T> p_205891_, final T p_205892_, final Lifecycle p_205893_)
{
return registerMapping(-1, p_205891_, p_205892_, p_205893_);
}
@Override
public Holder<T> registerOrOverride(final OptionalInt id, final ResourceKey<T> p_205885_, final T p_205886_, final Lifecycle p_205887_)
{
int wanted = -1;
if (id.isPresent() && byId(id.getAsInt()) != null)
wanted = id.getAsInt();
return registerMapping(wanted, p_205885_, p_205886_, p_205887_);
NamespacedDefaultedWrapper(ForgeRegistry<T> fowner, Function<T, Holder.Reference<T>> intrusiveHolderCallback, RegistryManager stage) {
super(fowner, intrusiveHolderCallback, stage);
this.delegate = fowner;
this.defaultKey = fowner.getDefaultKey();
}
// Reading Functions
@Override
public Optional<T> getOptional(@Nullable ResourceLocation name)
{
return Optional.ofNullable( this.delegate.getRaw(name)); //get without default
}
@Override
@Nullable
public T get(@Nullable ResourceLocation name)
{
return this.delegate.getValue(name); //getOrDefault
}
@Override
@Nullable
public T get(@Nullable ResourceKey<T> name)
public Optional<Holder.Reference<T>> getRandom(RandomSource rand)
{
return name == null ? null : this.delegate.getRaw(name.location()); //get without default
}
if (this.defaultHolder != null)
return super.getRandom(rand).or(() -> Optional.of(this.defaultHolder));
@Override
@Nullable
public ResourceLocation getKey(T value)
{
return this.delegate.getKey(value);
}
@Override
public Optional<ResourceKey<T>> getResourceKey(T p_122755_)
{
return this.delegate.getResourceKey(p_122755_);
}
@Override
public boolean containsKey(ResourceLocation key)
{
return this.delegate.containsKey(key);
}
@Override
public boolean containsKey(ResourceKey<T> key)
{
return this.delegate.getRegistryName().equals(key.registry()) && containsKey(key.location());
}
@Override
public int getId(@Nullable T value)
{
return this.delegate.getID(value);
}
@Override
@Nullable
public T byId(int id)
{
return this.delegate.getValue(id);
return super.getRandom(rand);
}
@Override
@@ -142,81 +49,18 @@ class NamespacedDefaultedWrapper<T> extends DefaultedRegistry<T> implements ILoc
return this.delegate.getDefaultKey();
}
@Nullable
@Override
public Lifecycle lifecycle(T value)
Holder.Reference<T> onAdded(RegistryManager stage, int id, ResourceKey<T> key, T newValue, T oldValue)
{
return Lifecycle.stable();
Holder.Reference<T> newHolder = super.onAdded(stage, id, key, newValue, oldValue);
if (newHolder != null && this.defaultKey != null && this.defaultKey.equals(key.location()))
this.defaultHolder = newHolder;
return newHolder;
}
@Override
public Lifecycle elementsLifecycle()
{
return this.elementsLifecycle;
}
@Override
public Iterator<T> iterator()
{
return this.delegate.iterator();
}
@Override
public Set<ResourceLocation> keySet()
{
return this.delegate.getKeys();
}
@Override
public Set<ResourceKey<T>> registryKeySet()
{
return this.delegate.getResourceKeys();
}
@Override
public Set<Map.Entry<ResourceKey<T>, T>> entrySet()
{
return this.delegate.getEntries();
}
@Override
public boolean isEmpty()
{
return this.delegate.isEmpty();
}
@Override
public int size()
{
return this.delegate.size();
}
@Override
public NamespacedHolderHelper<T> getHolderHelper()
{
return this.holders;
}
@Override public Optional<Holder<T>> getHolder(int id) { return this.holders.getHolder(id); }
@Override public Optional<Holder<T>> getHolder(ResourceKey<T> key) { return this.holders.getHolder(key); }
@Override public DataResult<Holder<T>> getOrCreateHolder(ResourceKey<T> key) { return this.holders.getOrCreateHolder(key); }
@Override public Holder<T> getOrCreateHolderOrThrow(ResourceKey<T> key) { return this.holders.getOrCreateHolderOrThrow(key); }
@Override public Optional<Holder<T>> getRandom(RandomSource rand) { return this.holders.getRandom(rand); }
@Override public Stream<Holder.Reference<T>> holders() { return this.holders.holders(); }
@Override public boolean isKnownTagName(TagKey<T> name) { return this.holders.isKnownTagName(name); }
@Override public Stream<Pair<TagKey<T>, HolderSet.Named<T>>> getTags() { return this.holders.getTags(); }
@Override public HolderSet.Named<T> getOrCreateTag(TagKey<T> name) { return this.holders.getOrCreateTag(name); }
@Override public Stream<TagKey<T>> getTagNames() { return this.holders.getTagNames(); }
@Override public Registry<T> freeze() { return this.holders.freeze(); }
@Override public Holder.Reference<T> createIntrusiveHolder(T value) { return this.holders.createIntrusiveHolder(value); }
@Override public Optional<HolderSet.Named<T>> getTag(TagKey<T> name) { return this.holders.getTag(name); }
@Override public void bindTags(Map<TagKey<T>, List<Holder<T>>> newTags) { this.holders.bindTags(newTags); }
@Override public void resetTags() { this.holders.resetTags(); }
@Deprecated @Override public void unfreeze() { this.holders.unfreeze(); }
/** @deprecated Forge: For internal use only. Use the Register events when registering values. */
@Deprecated @Override public void lock(){ this.locked = true; }
public static class Factory<V> implements IForgeRegistry.CreateCallback<V>, IForgeRegistry.AddCallback<V>
{
public static final ResourceLocation ID = new ResourceLocation("forge", "registry_defaulted_wrapper");
@@ -224,15 +68,15 @@ class NamespacedDefaultedWrapper<T> extends DefaultedRegistry<T> implements ILoc
@Override
public void onCreate(IForgeRegistryInternal<V> owner, RegistryManager stage)
{
ForgeRegistry<V> fowner = (ForgeRegistry<V>)owner;
owner.setSlaveMap(ID, new NamespacedDefaultedWrapper<V>(fowner, fowner.getBuilder().getVanillaHolder()));
ForgeRegistry<V> fowner = (ForgeRegistry<V>) owner;
owner.setSlaveMap(ID, new NamespacedDefaultedWrapper<V>(fowner, fowner.getBuilder().getIntrusiveHolderCallback(), stage));
}
@Override
@SuppressWarnings("unchecked")
public void onAdd(IForgeRegistryInternal<V> owner, RegistryManager stage, int id, ResourceKey<V> key, V value, V oldValue)
{
owner.getSlaveMap(ID, NamespacedDefaultedWrapper.class).holders.onAdded(stage, id, key, value, oldValue);
owner.getSlaveMap(ID, NamespacedDefaultedWrapper.class).onAdded(stage, id, key, value, oldValue);
}
}
}
@@ -1,312 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.registries;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Random;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.mojang.serialization.DataResult;
import cpw.mods.modlauncher.api.LamdbaExceptionUtils;
import net.minecraft.util.RandomSource;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.google.common.collect.Sets;
import com.mojang.datafixers.util.Pair;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import it.unimi.dsi.fastutil.objects.ObjectList;
import net.minecraft.Util;
import net.minecraft.core.Holder;
import net.minecraft.core.HolderSet;
import net.minecraft.core.Registry;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.TagKey;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
class NamespacedHolderHelper<T>
{
private static final Logger LOGGER = LogManager.getLogger();
private final ForgeRegistry<T> owner;
private final Registry<T> self;
@Nullable
private final ResourceLocation defaultKey;
@Nullable
private final Function<T, Holder.Reference<T>> holderLookup;
private final Multimap<TagKey<T>, Supplier<T>> optionalTags = Multimaps.newSetMultimap(new IdentityHashMap<>(), HashSet::new);
private boolean frozen = false; // Frozen is vanilla's variant of locked, but it can be unfrozen
private List<Holder.Reference<T>> holdersSorted;
private ObjectList<Holder.Reference<T>> holdersById = new ObjectArrayList<>(256);
private Map<ResourceLocation, Holder.Reference<T>> holdersByName = new HashMap<>();
private Map<T, Holder.Reference<T>> holders = new IdentityHashMap<>();
private volatile Map<TagKey<T>, HolderSet.Named<T>> tags = new IdentityHashMap<>();
private Holder.Reference<T> defaultHolder;
NamespacedHolderHelper(ForgeRegistry<T> owner, Registry<T> self, @Nullable ResourceLocation defaultKey, @Nullable Function<T, Holder.Reference<T>> holderLookup)
{
this.owner = owner;
this.self = self;
this.defaultKey = defaultKey;
this.holderLookup = holderLookup;
}
Optional<Holder<T>> getHolder(int id)
{
return id >= 0 && id < this.holdersById.size() ? Optional.ofNullable(this.holdersById.get(id)) : Optional.empty();
}
Optional<Holder<T>> getHolder(ResourceKey<T> key)
{
return Optional.ofNullable(this.holdersByName.get(key.location()));
}
Optional<Holder<T>> getHolder(ResourceLocation location)
{
return Optional.ofNullable(this.holdersByName.get(location));
}
Optional<Holder<T>> getHolder(T value)
{
return Optional.ofNullable(this.holders.get(value));
}
DataResult<Holder<T>> getOrCreateHolder(ResourceKey<T> key)
{
Holder.Reference<T> ref = this.holdersByName.get(key.location());
if (ref == null)
{
if (this.holderLookup != null)
return DataResult.error("This registry can't create new holders without value (requested key: " + key + ")");
if (this.frozen)
return DataResult.error("Registry is already frozen (trying to add key " + key + ")");
ref = Holder.Reference.createStandAlone(this.self, key);
this.holdersByName.put(key.location(), ref);
}
return DataResult.success(ref);
}
Holder<T> getOrCreateHolderOrThrow(ResourceKey<T> key)
{
return getOrCreateHolder(key).getOrThrow(false, msg ->
{
throw new IllegalStateException(msg);
});
}
Optional<Holder<T>> getRandom(RandomSource rand)
{
Optional<Holder<T>> ret = Util.getRandomSafe(this.getSortedHolders(), rand).map(Holder::hackyErase);
if (this.defaultKey != null)
ret = ret.or(() -> Optional.of(this.defaultHolder));
return ret;
}
Stream<Holder.Reference<T>> holders()
{
return this.getSortedHolders().stream();
}
boolean isKnownTagName(TagKey<T> name)
{
return this.tags.containsKey(name);
}
Stream<Pair<TagKey<T>, HolderSet.Named<T>>> getTags()
{
return this.tags.entrySet().stream().map(e -> Pair.of(e.getKey(), e.getValue()));
}
HolderSet.Named<T> getOrCreateTag(TagKey<T> name)
{
HolderSet.Named<T> named = this.tags.get(name);
if (named == null)
{
named = createTag(name);
// They use volatile and set it this way to not have the performance penalties of synced read access. But this makes a lot of new maps.. We need to look into performance alternatives.
Map<TagKey<T>, HolderSet.Named<T>> map = new IdentityHashMap<>(this.tags);
map.put(name, named);
this.tags = map;
}
return named;
}
void addOptionalTag(TagKey<T> name, @NotNull Set<? extends Supplier<T>> defaults)
{
this.optionalTags.putAll(name, defaults);
}
Stream<TagKey<T>> getTagNames()
{
return this.tags.keySet().stream();
}
//TODO: Move this to ValidateCallback?
Registry<T> freeze()
{
this.frozen = true;
List<ResourceLocation> unregisterd = this.holdersByName.entrySet().stream()
.filter(e -> !e.getValue().isBound())
.map(e -> e.getKey()).sorted().toList();
if (!unregisterd.isEmpty())
throw new IllegalStateException("Unbound values in registry " + this.self.key() + ": " + unregisterd.stream().map(ResourceLocation::toString).collect(Collectors.joining(", \n\t")));
if (this.holderLookup != null)
{
List<Holder.Reference<T>> intrusive = this.holders.values().stream().filter(h -> h.getType() == Holder.Reference.Type.INTRUSIVE && !h.isBound()).toList();
if (!intrusive.isEmpty())
throw new IllegalStateException("Some intrusive holders were not added to registry: " + intrusive);
}
return this.self;
}
@SuppressWarnings("deprecation")
Holder.Reference<T> createIntrusiveHolder(T value)
{
if (this.holderLookup == null)
throw new IllegalStateException("This registry can't create intrusive holders");
if (this.frozen)
throw new IllegalStateException("Registry is already frozen");
return this.holders.computeIfAbsent(value, k -> Holder.Reference.createIntrusive(this.self, value));
}
Optional<HolderSet.Named<T>> getTag(TagKey<T> name)
{
return Optional.ofNullable(this.tags.get(name));
}
void bindTags(Map<TagKey<T>, List<Holder<T>>> newTags)
{
Map<Holder.Reference<T>, List<TagKey<T>>> holderToTag = new IdentityHashMap<>();
this.holdersByName.values().forEach(v -> holderToTag.put(v, new ArrayList<>()));
newTags.forEach((name, values) -> values.forEach(holder -> addTagToHolder(holderToTag, name, holder)));
Set<TagKey<T>> set = Sets.difference(this.tags.keySet(), newTags.keySet());
if (!set.isEmpty())
LOGGER.warn("Not all defined tags for registry {} are present in data pack: {}", this.self.key(), set.stream().map(k -> k.location().toString()).sorted().collect(Collectors.joining(", \n\t")));
Map<TagKey<T>, HolderSet.Named<T>> tmpTags = new IdentityHashMap<>(this.tags);
newTags.forEach((k, v) -> tmpTags.computeIfAbsent(k, this::createTag).bind(v));
Set<TagKey<T>> defaultedTags = Sets.difference(this.optionalTags.keySet(), newTags.keySet());
defaultedTags.forEach(name -> {
List<Holder<T>> defaults = this.optionalTags.get(name).stream()
.map(valueSupplier -> getHolder(valueSupplier.get()).orElse(null))
.filter(Objects::nonNull)
.distinct()
.toList();
defaults.forEach(holder -> addTagToHolder(holderToTag, name, holder));
tmpTags.computeIfAbsent(name, this::createTag).bind(defaults);
});
holderToTag.forEach(Holder.Reference::bindTags);
this.tags = tmpTags;
this.owner.onBindTags(this.tags, defaultedTags);
}
private void addTagToHolder(Map<Holder.Reference<T>, List<TagKey<T>>> holderToTag, TagKey<T> name, Holder<T> holder)
{
if (!holder.isValidInRegistry(this.self))
throw new IllegalStateException("Can't create named set " + name + " containing value " + holder + " from outside registry " + this);
if (!(holder instanceof Holder.Reference<T>))
throw new IllegalStateException("Found direct holder " + holder + " value in tag " + name);
holderToTag.get((Holder.Reference<T>) holder).add(name);
}
void resetTags()
{
this.tags.values().forEach(t -> t.bind(List.of()));
this.holders.values().forEach(v -> v.bindTags(Set.of()));
}
void unfreeze()
{
this.frozen = false;
}
boolean isFrozen()
{
return this.frozen;
}
boolean isIntrusive()
{
return this.holderLookup != null;
}
@Nullable
Holder<T> onAdded(RegistryManager stage, int id, ResourceKey<T> key, T newValue, T oldValue)
{
if (stage != RegistryManager.ACTIVE && (this.holderLookup == null || !stage.isStaging())) // Intrusive handlers need updating in staging.
return null; // Only do holder shit on the active registries, not pending or snapshots.
//Holder.Reference<T> oldHolder = oldValue == null ? null : getHolder(key, oldValue);
// Do we need to do anything with the old holder? We cant update its pointer unless its non-intrusive...
// And if thats the case, then we *should* get its reference in newHolder
Holder.Reference<T> newHolder = getHolder(key, newValue);
this.holdersById.size(Math.max(this.holdersById.size(), id + 1));
this.holdersById.set(id, newHolder);
this.holdersByName.put(key.location(), newHolder);
this.holders.put(newValue, newHolder);
newHolder.bind(key, newValue);
this.holdersSorted = null;
if (this.defaultKey != null && this.defaultKey.equals(key.location()))
this.defaultHolder = newHolder;
return newHolder;
}
private HolderSet.Named<T> createTag(TagKey<T> name)
{
return new HolderSet.Named<>(this.self, name);
}
private Holder.Reference<T> getHolder(ResourceKey<T> key, T value)
{
if (this.holderLookup != null)
return this.holderLookup.apply(value);
return this.holdersByName.computeIfAbsent(key.location(), k -> Holder.Reference.createStandAlone(this.self, key));
}
private List<Holder.Reference<T>> getSortedHolders()
{
if (this.holdersSorted == null)
this.holdersSorted = this.holdersById.stream().filter(Objects::nonNull).toList();
return this.holdersSorted;
}
}
@@ -5,82 +5,92 @@
package net.minecraftforge.registries;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Stream;
import com.mojang.serialization.DataResult;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.common.collect.Sets;
import com.mojang.datafixers.util.Pair;
import com.mojang.logging.LogUtils;
import com.mojang.serialization.Lifecycle;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import it.unimi.dsi.fastutil.objects.ObjectList;
import net.minecraft.Util;
import net.minecraft.core.Holder;
import net.minecraft.core.HolderGetter;
import net.minecraft.core.HolderSet;
import net.minecraft.core.MappedRegistry;
import net.minecraft.core.Registry;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.TagKey;
import net.minecraft.core.MappedRegistry;
import net.minecraft.core.Registry;
import net.minecraft.util.RandomSource;
import org.apache.commons.lang3.Validate;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.mojang.datafixers.util.Pair;
import com.mojang.serialization.Lifecycle;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
class NamespacedWrapper<T> extends MappedRegistry<T> implements ILockableRegistry, IHolderHelperHolder<T>
class NamespacedWrapper<T> extends MappedRegistry<T> implements ILockableRegistry
{
private static final Logger LOGGER = LogManager.getLogger();
static final Logger LOGGER = LogUtils.getLogger();
private final ForgeRegistry<T> delegate;
private final NamespacedHolderHelper<T> holders;
@Nullable
private final Function<T, Holder.Reference<T>> intrusiveHolderCallback;
private final Multimap<TagKey<T>, Supplier<T>> optionalTags = Multimaps.newSetMultimap(new IdentityHashMap<>(), HashSet::new);
private boolean locked = false;
private Lifecycle elementsLifecycle = Lifecycle.experimental();
boolean locked = false;
Lifecycle registryLifecycle = Lifecycle.experimental();
private boolean frozen = false; // Frozen is vanilla's variant of locked, but it can be unfrozen
private List<Holder.Reference<T>> holdersSorted;
private ObjectList<Holder.Reference<T>> holdersById = new ObjectArrayList<>(256);
private Map<ResourceLocation, Holder.Reference<T>> holdersByName = new HashMap<>();
private Map<T, Holder.Reference<T>> holders = new IdentityHashMap<>();
private RegistryManager stage;
private volatile Map<TagKey<T>, HolderSet.Named<T>> tags = new IdentityHashMap<>();
public NamespacedWrapper(ForgeRegistry<T> owner, Function<T, Holder.Reference<T>> holderLookup)
NamespacedWrapper(ForgeRegistry<T> fowner, Function<T, Holder.Reference<T>> intrusiveHolderCallback, RegistryManager stage)
{
super(owner.getRegistryKey(), Lifecycle.experimental(), holderLookup);
this.delegate = owner;
this.holders = new NamespacedHolderHelper<>(owner, this, null, holderLookup);
super(fowner.getRegistryKey(), Lifecycle.experimental(), intrusiveHolderCallback != null);
this.delegate = fowner;
this.intrusiveHolderCallback = intrusiveHolderCallback;
this.stage = stage;
}
@Override
public Holder<T> registerMapping(int id, ResourceKey<T> key, T value, Lifecycle lifecycle)
public Holder.Reference<T> registerMapping(int id, ResourceKey<T> key, T value, Lifecycle lifecycle)
{
if (locked)
throw new IllegalStateException("Can not register to a locked registry. Modder should use Forge Register methods.");
Validate.notNull(value);
markKnown();
this.elementsLifecycle = this.elementsLifecycle.add(lifecycle);
T oldValue = get(key);
this.registryLifecycle = this.registryLifecycle.add(lifecycle);
int realId = this.delegate.add(id, key.location(), value);
if (realId != id && id != -1)
LOGGER.warn("Registered object did not get ID it asked for. Name: {} Expected: {} Got: {}", key, id, realId);
return this.holders.onAdded(RegistryManager.ACTIVE, realId, key, value, oldValue);
return getHolder(key, value);
}
@Override
public Holder<T> register(ResourceKey<T> key, T value, Lifecycle lifecycle)
public Holder.Reference<T> register(ResourceKey<T> key, T value, Lifecycle lifecycle)
{
return registerMapping(-1, key, value, lifecycle);
}
@Override
public Holder<T> registerOrOverride(OptionalInt id, ResourceKey<T> key, T value, Lifecycle lifecycle) {
int wanted = -1;
if (id.isPresent() && byId(id.getAsInt()) != null)
wanted = id.getAsInt();
return registerMapping(wanted, key, value, lifecycle);
}
// Reading Functions
@Override
@Nullable
@@ -92,7 +102,7 @@ class NamespacedWrapper<T> extends MappedRegistry<T> implements ILockableRegistr
@Override
public Optional<T> getOptional(@Nullable ResourceLocation name)
{
return Optional.ofNullable( this.delegate.getRaw(name)); //get without default
return Optional.ofNullable(this.delegate.getRaw(name)); //get without default
}
@Override
@@ -124,7 +134,7 @@ class NamespacedWrapper<T> extends MappedRegistry<T> implements ILockableRegistr
@Override
public boolean containsKey(ResourceKey<T> key)
{
return this.delegate.getRegistryName().equals(key.registry()) && containsKey(key.location());
return this.delegate.getRegistryName().equals(key.registry()) && containsKey(key.location());
}
@Override
@@ -147,9 +157,9 @@ class NamespacedWrapper<T> extends MappedRegistry<T> implements ILockableRegistr
}
@Override
public Lifecycle elementsLifecycle()
public Lifecycle registryLifecycle()
{
return this.elementsLifecycle;
return this.registryLifecycle;
}
@Override
@@ -188,32 +198,289 @@ class NamespacedWrapper<T> extends MappedRegistry<T> implements ILockableRegistr
return this.delegate.size();
}
/**
* @deprecated Forge: For internal use only. Use the Register events when registering values.
*/
@Deprecated
@Override
public NamespacedHolderHelper<T> getHolderHelper()
public void lock()
{
return this.holders;
this.locked = true;
}
@Override public Optional<Holder<T>> getHolder(int id) { return this.holders.getHolder(id); }
@Override public Optional<Holder<T>> getHolder(ResourceKey<T> key) { return this.holders.getHolder(key); }
@Override public DataResult<Holder<T>> getOrCreateHolder(ResourceKey<T> key) { return this.holders.getOrCreateHolder(key); }
@Override public Holder<T> getOrCreateHolderOrThrow(ResourceKey<T> key) { return this.holders.getOrCreateHolderOrThrow(key); }
@Override public Optional<Holder<T>> getRandom(RandomSource rand) { return this.holders.getRandom(rand); }
@Override public Stream<Holder.Reference<T>> holders() { return this.holders.holders(); }
@Override public boolean isKnownTagName(TagKey<T> name) { return this.holders.isKnownTagName(name); }
@Override public Stream<Pair<TagKey<T>, HolderSet.Named<T>>> getTags() { return this.holders.getTags(); }
@Override public HolderSet.Named<T> getOrCreateTag(TagKey<T> name) { return this.holders.getOrCreateTag(name); }
@Override public Stream<TagKey<T>> getTagNames() { return this.holders.getTagNames(); }
@Override public Registry<T> freeze() { return this.holders.freeze(); }
@Override public Holder.Reference<T> createIntrusiveHolder(T value) { return this.holders.createIntrusiveHolder(value); }
@Override public Optional<HolderSet.Named<T>> getTag(TagKey<T> name) { return this.holders.getTag(name); }
@Override public void bindTags(Map<TagKey<T>, List<Holder<T>>> newTags) { this.holders.bindTags(newTags); }
@Override public void resetTags() { this.holders.resetTags(); }
@Deprecated @Override public void unfreeze() { this.holders.unfreeze(); }
@Override
public Optional<Holder.Reference<T>> getHolder(int id)
{
return id >= 0 && id < this.holdersById.size() ? Optional.ofNullable(this.holdersById.get(id)) : Optional.empty();
}
/** @deprecated Forge: For internal use only. Use the Register events when registering values. */
@Deprecated @Override public void lock(){ this.locked = true; }
@Override
public Optional<Holder.Reference<T>> getHolder(ResourceKey<T> key)
{
return Optional.ofNullable(this.holdersByName.get(key.location()));
}
Optional<Holder<T>> getHolder(ResourceLocation location)
{
return Optional.ofNullable(this.holdersByName.get(location));
}
Optional<Holder<T>> getHolder(T value)
{
return Optional.ofNullable(this.holders.get(value));
}
@Override
public HolderGetter<T> createRegistrationLookup()
{
this.validateWrite();
return new HolderGetter<T>()
{
public Optional<Holder.Reference<T>> get(ResourceKey<T> p_259097_)
{
return Optional.of(this.getOrThrow(p_259097_));
}
public Holder.Reference<T> getOrThrow(ResourceKey<T> p_259750_)
{
return NamespacedWrapper.this.getOrCreateHolderOrThrow(p_259750_);
}
public Optional<HolderSet.Named<T>> get(TagKey<T> p_259486_)
{
return Optional.of(this.getOrThrow(p_259486_));
}
public HolderSet.Named<T> getOrThrow(TagKey<T> p_260298_)
{
return NamespacedWrapper.this.getOrCreateTag(p_260298_);
}
};
}
void validateWrite()
{
if (this.frozen)
throw new IllegalStateException("Registry is already frozen");
}
void validateWrite(ResourceKey<T> key)
{
if (this.frozen)
throw new IllegalStateException("Registry is already frozen (trying to add key " + key + ")");
}
Holder.Reference<T> getOrCreateHolderOrThrow(ResourceKey<T> key)
{
return this.holdersByName.computeIfAbsent(key.location(), k -> {
if (this.intrusiveHolderCallback != null)
{
throw new IllegalStateException("This registry can't create new holders without value");
}
else
{
this.validateWrite(key);
return Holder.Reference.createStandAlone(this.holderOwner(), key);
}
});
}
@Override
public Optional<Holder.Reference<T>> getRandom(RandomSource rand)
{
return Util.getRandomSafe(this.getSortedHolders(), rand);
}
@Override
public Stream<Holder.Reference<T>> holders()
{
return this.getSortedHolders().stream();
}
@Override
public Stream<Pair<TagKey<T>, HolderSet.Named<T>>> getTags()
{
return this.tags.entrySet().stream().map(e -> Pair.of(e.getKey(), e.getValue()));
}
@Override
public HolderSet.Named<T> getOrCreateTag(TagKey<T> name)
{
HolderSet.Named<T> named = this.tags.get(name);
if (named == null)
{
named = createTag(name);
// They use volatile and set it this way to not have the performance penalties of synced read access. But this makes a lot of new maps.. We need to look into performance alternatives.
Map<TagKey<T>, HolderSet.Named<T>> map = new IdentityHashMap<>(this.tags);
map.put(name, named);
this.tags = map;
}
return named;
}
void addOptionalTag(TagKey<T> name, @NotNull Set<? extends Supplier<T>> defaults)
{
this.optionalTags.putAll(name, defaults);
}
@Override
public Stream<TagKey<T>> getTagNames()
{
return this.tags.keySet().stream();
}
//TODO: Move this to ValidateCallback?
@Override
public Registry<T> freeze()
{
this.frozen = true;
List<ResourceLocation> unregistered = this.holdersByName.entrySet().stream()
.filter(e -> !e.getValue().isBound())
.map(Map.Entry::getKey).sorted().toList();
if (!unregistered.isEmpty())
throw new IllegalStateException("Unbound values in registry " + this.key() + ": " + unregistered.stream().map(ResourceLocation::toString).collect(Collectors.joining(", \n\t")));
if (this.unregisteredIntrusiveHolders != null && this.unregisteredIntrusiveHolders.values().stream().anyMatch(r -> !r.isBound() && r.getType() == Holder.Reference.Type.INTRUSIVE)) {
throw new IllegalStateException("Some intrusive holders were not registered: " + this.unregisteredIntrusiveHolders.values() + " Hint: Did you register all your registry objects? Registry stage: " + stage.getName());
}
return this;
}
@Override
public Holder.Reference<T> createIntrusiveHolder(T value)
{
if (this.intrusiveHolderCallback == null)
throw new IllegalStateException("This registry can't create intrusive holders");
this.validateWrite();
return super.createIntrusiveHolder(value);
}
@Override
public Optional<HolderSet.Named<T>> getTag(TagKey<T> name)
{
return Optional.ofNullable(this.tags.get(name));
}
@Override
public void bindTags(Map<TagKey<T>, List<Holder<T>>> newTags)
{
Map<Holder.Reference<T>, List<TagKey<T>>> holderToTag = new IdentityHashMap<>();
this.holdersByName.values().forEach(v -> holderToTag.put(v, new ArrayList<>()));
newTags.forEach((name, values) -> values.forEach(holder -> addTagToHolder(holderToTag, name, holder)));
Set<TagKey<T>> set = new HashSet<>(Sets.difference(this.tags.keySet(), newTags.keySet()));
set.removeAll(this.optionalTags.keySet());
if (!set.isEmpty())
LOGGER.warn("Not all defined tags for registry {} are present in data pack: {}", this.key(), set.stream().map(k -> k.location().toString()).sorted()
.collect(Collectors.joining(", \n\t")));
Map<TagKey<T>, HolderSet.Named<T>> tmpTags = new IdentityHashMap<>(this.tags);
newTags.forEach((k, v) -> tmpTags.computeIfAbsent(k, this::createTag).bind(v));
Set<TagKey<T>> defaultedTags = Sets.difference(this.optionalTags.keySet(), newTags.keySet());
defaultedTags.forEach(name -> {
List<Holder<T>> defaults = this.optionalTags.get(name).stream()
.map(valueSupplier -> getHolder(valueSupplier.get()).orElse(null))
.filter(Objects::nonNull)
.distinct()
.toList();
defaults.forEach(holder -> addTagToHolder(holderToTag, name, holder));
tmpTags.computeIfAbsent(name, this::createTag).bind(defaults);
});
holderToTag.forEach(Holder.Reference::bindTags);
this.tags = tmpTags;
this.delegate.onBindTags(this.tags, defaultedTags);
}
private void addTagToHolder(Map<Holder.Reference<T>, List<TagKey<T>>> holderToTag, TagKey<T> name, Holder<T> holder)
{
if (!holder.canSerializeIn(this.holderOwner()))
throw new IllegalStateException("Can't create named set " + name + " containing value " + holder + " from outside registry " + this);
if (!(holder instanceof Holder.Reference<T>))
throw new IllegalStateException("Found direct holder " + holder + " value in tag " + name);
holderToTag.get((Holder.Reference<T>) holder).add(name);
}
@Override
public void resetTags()
{
this.tags.values().forEach(t -> t.bind(List.of()));
this.holders.values().forEach(v -> v.bindTags(Set.of()));
}
@Override
public void unfreeze()
{
this.frozen = false;
}
boolean isFrozen()
{
return this.frozen;
}
boolean isIntrusive()
{
return this.intrusiveHolderCallback != null;
}
@Nullable
Holder.Reference<T> onAdded(RegistryManager stage, int id, ResourceKey<T> key, T newValue, T oldValue)
{
if (stage != RegistryManager.ACTIVE && (this.intrusiveHolderCallback == null || !stage.isStaging())) // Intrusive handlers need updating in staging.
return null; // Only do holder shit on the active registries, not pending or snapshots.
//Holder.Reference<T> oldHolder = oldValue == null ? null : getHolder(key, oldValue);
// Do we need to do anything with the old holder? We cant update its pointer unless its non-intrusive...
// And if thats the case, then we *should* get its reference in newHolder
Holder.Reference<T> newHolder = getHolder(key, newValue);
this.holdersById.size(Math.max(this.holdersById.size(), id + 1));
this.holdersById.set(id, newHolder);
this.holdersByName.put(key.location(), newHolder);
this.holders.put(newValue, newHolder);
if (this.unregisteredIntrusiveHolders != null)
{
this.unregisteredIntrusiveHolders.remove(newValue);
newHolder.bindKey(key);
}
newHolder.bindValue(newValue);
this.holdersSorted = null;
return newHolder;
}
@SuppressWarnings("deprecation")
private HolderSet.Named<T> createTag(TagKey<T> name)
{
return HolderSet.emptyNamed(this.holderOwner(), name);
}
private Holder.Reference<T> getHolder(ResourceKey<T> key, T value)
{
if (this.intrusiveHolderCallback != null)
return this.intrusiveHolderCallback.apply(value);
return this.holdersByName.computeIfAbsent(key.location(), k -> Holder.Reference.createStandAlone(this.holderOwner(), key));
}
private List<Holder.Reference<T>> getSortedHolders()
{
if (this.holdersSorted == null)
this.holdersSorted = this.holdersById.stream().filter(Objects::nonNull).toList();
return this.holdersSorted;
}
public static class Factory<V> implements IForgeRegistry.CreateCallback<V>, IForgeRegistry.AddCallback<V>
{
@@ -222,15 +489,15 @@ class NamespacedWrapper<T> extends MappedRegistry<T> implements ILockableRegistr
@Override
public void onCreate(IForgeRegistryInternal<V> owner, RegistryManager stage)
{
ForgeRegistry<V> fowner = (ForgeRegistry<V>)owner;
owner.setSlaveMap(ID, new NamespacedWrapper<V>(fowner, fowner.getBuilder().getVanillaHolder()));
ForgeRegistry<V> fowner = (ForgeRegistry<V>) owner;
owner.setSlaveMap(ID, new NamespacedWrapper<V>(fowner, fowner.getBuilder().getIntrusiveHolderCallback(), stage));
}
@Override
@SuppressWarnings("unchecked")
public void onAdd(IForgeRegistryInternal<V> owner, RegistryManager stage, int id, ResourceKey<V> key, V value, V oldValue)
{
owner.getSlaveMap(ID, NamespacedWrapper.class).holders.onAdded(stage, id, key, value, oldValue);
owner.getSlaveMap(ID, NamespacedWrapper.class).onAdded(stage, id, key, value, oldValue);
}
}
}
@@ -6,20 +6,18 @@
package net.minecraftforge.registries;
import com.mojang.logging.LogUtils;
import net.minecraft.core.Registry;
import net.minecraft.core.RegistryAccess;
import net.minecraft.data.BuiltinRegistries;
import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.fml.event.IModBusEvent;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Supplier;
import net.minecraft.core.MappedRegistry;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.fml.event.IModBusEvent;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
/**
* Register new registries when you receive this event through {@link RegistryBuilder} and {@link #create(RegistryBuilder)}.
@@ -58,11 +56,15 @@ public class NewRegistryEvent extends Event implements IModBusEvent
return registryHolder;
}
@SuppressWarnings("deprecation")
void fill()
{
RuntimeException aggregate = new RuntimeException();
Map<RegistryBuilder<?>, IForgeRegistry<?>> builtRegistries = new IdentityHashMap<>();
if (BuiltInRegistries.REGISTRY instanceof MappedRegistry<?> rootRegistry)
rootRegistry.unfreeze();
for (RegistryData<?> data : this.registries)
{
try {
@@ -74,6 +76,9 @@ public class NewRegistryEvent extends Event implements IModBusEvent
}
}
if (BuiltInRegistries.REGISTRY instanceof MappedRegistry<?> rootRegistry)
rootRegistry.freeze();
if (aggregate.getSuppressed().length > 0)
LOGGER.error(LogUtils.FATAL_MARKER, "Failed to create some forge registries, see suppressed exceptions for details", aggregate);
}
@@ -85,16 +90,7 @@ public class NewRegistryEvent extends Event implements IModBusEvent
builtRegistries.put(builder, registry);
RegistryAccess.RegistryData<?> dataPackRegistryData = builder.getDataPackRegistryData();
if (dataPackRegistryData != null) // if this is a datapack registry
{
if (!BuiltinRegistries.REGISTRY.containsKey(registry.getRegistryName()))
{
DataPackRegistriesHooks.addRegistryCodec(dataPackRegistryData);
RegistryManager.registerToBuiltinRegistry((ForgeRegistry<?>) registry);
}
}
else if (builder.getHasWrapper() && !Registry.REGISTRY.containsKey(registry.getRegistryName()))
if (builder.getHasWrapper() && !BuiltInRegistries.REGISTRY.containsKey(registry.getRegistryName()))
RegistryManager.registerToRootRegistry((ForgeRegistry<?>) registry);
data.registryHolder.registry = registry;
@@ -5,24 +5,21 @@
package net.minecraftforge.registries;
import com.google.common.collect.Lists;
import net.minecraft.core.Holder;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.registries.IForgeRegistry.AddCallback;
import net.minecraftforge.registries.IForgeRegistry.BakeCallback;
import net.minecraftforge.registries.IForgeRegistry.ClearCallback;
import net.minecraftforge.registries.IForgeRegistry.CreateCallback;
import net.minecraftforge.registries.IForgeRegistry.DummyFactory;
import net.minecraftforge.registries.IForgeRegistry.MissingFactory;
import net.minecraftforge.registries.IForgeRegistry.ValidateCallback;
import org.jetbrains.annotations.Nullable;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.Lists;
import com.mojang.serialization.Codec;
import net.minecraft.client.multiplayer.ClientPacketListener;
import net.minecraft.core.Holder;
import net.minecraft.core.Registry;
import net.minecraft.core.RegistryAccess;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.registries.IForgeRegistry.*;
import org.jetbrains.annotations.Nullable;
public class RegistryBuilder<T>
{
@@ -37,16 +34,16 @@ public class RegistryBuilder<T>
private List<CreateCallback<T>> createCallback = Lists.newArrayList();
private List<ValidateCallback<T>> validateCallback = Lists.newArrayList();
private List<BakeCallback<T>> bakeCallback = Lists.newArrayList();
private Function<T, Holder.Reference<T>> vanillaHolder;
private boolean saveToDisc = true;
private boolean sync = true;
private boolean allowOverrides = true;
private boolean allowModifications = false;
private boolean hasWrapper = false;
private Supplier<RegistryAccess.RegistryData<T>> dataPackRegistryData = () -> null; // If present, implies this is a datapack registry.
private DummyFactory<T> dummyFactory;
private MissingFactory<T> missingFactory;
private Set<ResourceLocation> legacyNames = new HashSet<>();
@Nullable
private Function<T, Holder.Reference<T>> intrusiveHolderCallback = null;
public RegistryBuilder<T> setName(ResourceLocation name)
{
@@ -176,8 +173,8 @@ public class RegistryBuilder<T>
}
/**
* Prevents the registry from being synced to clients. Does *not* affect datapack registries, datapack registries are unsynced by default
* unless a non-null network codec is registered via {@link #dataPackRegistry(Codec, Codec)}
* Prevents the registry from being synced to clients.
*
* @return this
*/
public RegistryBuilder<T> disableSync()
@@ -215,9 +212,9 @@ public class RegistryBuilder<T>
return this;
}
RegistryBuilder<T> vanillaHolder(Function<T, Holder.Reference<T>> func)
RegistryBuilder<T> intrusiveHolderCallback(Function<T, Holder.Reference<T>> intrusiveHolderCallback)
{
this.vanillaHolder = func;
this.intrusiveHolderCallback = intrusiveHolderCallback;
return this;
}
@@ -235,66 +232,6 @@ public class RegistryBuilder<T>
return this;
}
/**
* <p>Register this registry as an unsynced datapack registry, which will cause data to be loaded from
* a datapack folder based on the registry's name. The mod that registers this registry does not need to exist
* on the client to connect to servers with the mod/registry.</p>
* <p>Data JSONs will be loaded from {@code data/<datapack_namespace>/modid/registryname/}, where modid is the mod that registered this registry.</p>
*
* @param codec the codec to be used for loading data from datapacks on servers
* @return this builder
*
* @see #dataPackRegistry(Codec, Codec)
*/
public RegistryBuilder<T> dataPackRegistry(Codec<T> codec)
{
return this.dataPackRegistry(codec, null);
}
/**
* <p>Register this registry as a datapack registry, which will cause data to be loaded from
* a datapack folder based on the registry's name.</p>
* <p>Data JSONs will be loaded from {@code data/<datapack_namespace>/modid/registryname/}, where modid is the mod that registered this registry.</p>
*
* @param codec the codec to be used for loading data from datapacks on servers
* @param networkCodec the codec to be used for syncing loaded data to clients.<br>
* If networkCodec is null, data will not be synced, and clients without the mod that registered this registry can
* connect to servers with the mod.<br>
* If networkCodec is not null, then data will be synced (accessible via {@link ClientPacketListener#registryAccess()}),
* and the mod must be present on a client to connect to servers with the mod.
* @return this builder
*
* @see #dataPackRegistry(Codec)
*/
public RegistryBuilder<T> dataPackRegistry(Codec<T> codec, @Nullable Codec<T> networkCodec)
{
this.hasWrapper(); // A wrapper is required for data pack registries.
this.disableSync(); // Datapack registries are synced using a different system than static registries.
// Supplier averts having to set the registry name before calling this.
this.dataPackRegistryData = Suppliers.memoize(() -> {
// Validate registry key.
if (this.registryName == null)
throw new IllegalStateException("Registry builder cannot build a datapack registry: registry name not set");
ResourceKey<Registry<T>> registryKey = ResourceKey.createRegistryKey(this.registryName);
return new RegistryAccess.RegistryData<>(registryKey, codec, networkCodec);
});
return this;
}
/**
* Retrieves datapack registry information, if any.
*
* @return RegistryData containing the registry's key and codec(s). If returned data is null, this has not been marked as a datapack registry.
*
* @throws IllegalStateException if this has been marked as a datapack registry, but registry name has not been set.
*/
@Nullable
RegistryAccess.RegistryData<T> getDataPackRegistryData()
{
return this.dataPackRegistryData.get();
}
/**
* Modders: Use {@link NewRegistryEvent#create(RegistryBuilder)} instead
*/
@@ -438,9 +375,9 @@ public class RegistryBuilder<T>
return legacyNames;
}
Function<T, Holder.Reference<T>> getVanillaHolder()
Function<T, Holder.Reference<T>> getIntrusiveHolderCallback()
{
return this.vanillaHolder;
return this.intrusiveHolderCallback;
}
boolean getHasWrapper()
@@ -19,7 +19,7 @@ import com.google.common.collect.Sets;
import com.mojang.serialization.Lifecycle;
import net.minecraft.core.WritableRegistry;
import net.minecraft.data.BuiltinRegistries;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.core.Registry;
@@ -131,12 +131,7 @@ public class RegistryManager
static <V> void registerToRootRegistry(ForgeRegistry<V> forgeReg)
{
injectForgeRegistry(forgeReg, Registry.REGISTRY);
}
static <V> void registerToBuiltinRegistry(ForgeRegistry<V> forgeReg)
{
injectForgeRegistry(forgeReg, BuiltinRegistries.REGISTRY);
injectForgeRegistry(forgeReg, BuiltInRegistries.REGISTRY);
}
@SuppressWarnings("unchecked")
@@ -151,11 +146,14 @@ public class RegistryManager
public static void postNewRegistryEvent()
{
NewRegistryEvent event = new NewRegistryEvent();
vanillaRegistryKeys = Set.copyOf(Registry.REGISTRY.keySet());
DataPackRegistryEvent.NewRegistry dataPackEvent = new DataPackRegistryEvent.NewRegistry();
vanillaRegistryKeys = Set.copyOf(BuiltInRegistries.REGISTRY.keySet());
ModLoader.get().postEventWithWrapInModOrder(event, (mc, e) -> ModLoadingContext.get().setActiveContainer(mc), (mc, e) -> ModLoadingContext.get().setActiveContainer(null));
ModLoader.get().postEventWithWrapInModOrder(dataPackEvent, (mc, e) -> ModLoadingContext.get().setActiveContainer(mc), (mc, e) -> ModLoadingContext.get().setActiveContainer(null));
event.fill();
dataPackEvent.process();
}
private void addLegacyName(ResourceLocation legacyName, ResourceLocation name)
@@ -7,7 +7,7 @@ package net.minecraftforge.registries;
import net.minecraft.core.Holder;
import net.minecraft.core.Registry;
import net.minecraft.data.BuiltinRegistries;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import org.jetbrains.annotations.NotNull;
@@ -52,7 +52,7 @@ public final class RegistryObject<T> implements Supplier<T>
* Use {@link #createOptional(ResourceLocation, ResourceKey, String)} for RegistryObjects of optional registries.
*
* @param name the name of the object to look up in a registry
* @param registryKey the key of the registry. Supports lookups on {@link BuiltinRegistries}, {@link Registry}, and {@link RegistryManager#ACTIVE}.
* @param registryKey the key of the registry. Supports lookups on {@link BuiltInRegistries} and {@link RegistryManager#ACTIVE}.
* @param modid the mod id calling context
* @return a {@link RegistryObject} that stores the value of an object from a registry once it is ready
* @see #createOptional(ResourceLocation, ResourceKey, String)
@@ -72,7 +72,7 @@ public final class RegistryObject<T> implements Supplier<T>
* Use {@link #create(ResourceLocation, ResourceKey, String)} for RegistryObjects that should throw exceptions on missing registry.
*
* @param name the name of the object to look up in a registry
* @param registryKey the key of the registry. Supports lookups on {@link BuiltinRegistries}, {@link Registry}, and {@link RegistryManager#ACTIVE}.
* @param registryKey the key of the registry. Supports lookups on {@link BuiltInRegistries} and {@link RegistryManager#ACTIVE}.
* @param modid the mod id calling context
* @return a {@link RegistryObject} that stores the value of an object from a registry once it is ready
* @see #create(ResourceLocation, ResourceKey, String)
@@ -92,7 +92,7 @@ public final class RegistryObject<T> implements Supplier<T>
* Use {@link #createOptional(ResourceLocation, ResourceLocation, String)} for RegistryObjects of optional registries.
*
* @param name the name of the object to look up in a registry
* @param registryName the name of the registry. Supports lookups on {@link BuiltinRegistries}, {@link Registry}, and {@link RegistryManager#ACTIVE}.
* @param registryName the name of the registry. Supports lookups on {@link BuiltInRegistries} and {@link RegistryManager#ACTIVE}.
* @param modid the mod id calling context
* @return a {@link RegistryObject} that stores the value of an object from a registry once it is ready
* @see #createOptional(ResourceLocation, ResourceLocation, String)
@@ -112,7 +112,7 @@ public final class RegistryObject<T> implements Supplier<T>
* Use {@link #create(ResourceLocation, ResourceLocation, String)} for RegistryObjects that should throw exceptions on missing registry.
*
* @param name the name of the object to look up in a registry
* @param registryName the name of the registry. Supports lookups on {@link BuiltinRegistries}, {@link Registry}, and {@link RegistryManager#ACTIVE}.
* @param registryName the name of the registry. Supports lookups on {@link BuiltInRegistries} and {@link RegistryManager#ACTIVE}.
* @param modid the mod id calling context
* @return a {@link RegistryObject} that stores the value of an object from a registry once it is ready
* @see #create(ResourceLocation, ResourceLocation, String)
@@ -251,20 +251,13 @@ public final class RegistryObject<T> implements Supplier<T>
return;
}
Registry<? extends T> vanillaRegistry = (Registry<? extends T>) Registry.REGISTRY.get(registryName);
Registry<? extends T> vanillaRegistry = (Registry<? extends T>) BuiltInRegistries.REGISTRY.get(registryName);
if (vanillaRegistry != null)
{
updateReference(vanillaRegistry);
return;
}
Registry<? extends T> builtinRegistry = (Registry<? extends T>) BuiltinRegistries.REGISTRY.get(registryName);
if (builtinRegistry != null)
{
updateReference(builtinRegistry);
return;
}
this.value = null;
this.holder = null;
}
@@ -288,8 +281,7 @@ public final class RegistryObject<T> implements Supplier<T>
private static boolean registryExists(ResourceLocation registryName)
{
return RegistryManager.ACTIVE.getRegistry(registryName) != null
|| Registry.REGISTRY.containsKey(registryName)
|| BuiltinRegistries.REGISTRY.containsKey(registryName);
|| BuiltInRegistries.REGISTRY.containsKey(registryName);
}
public ResourceLocation getId()
@@ -479,26 +471,13 @@ public final class RegistryObject<T> implements Supplier<T>
* This should <b>only</b> be used in cases where vanilla code requires passing in a Holder.
* Mod-written code should rely on RegistryObjects or Suppliers instead.
* <p>
* The returned optional will be empty if the registry does not exist.
* Otherwise, the optional Holder will be present even if {@link #isPresent()} returns false.
* The returned optional will be empty if the registry does not exist or if {@link #isPresent() returns false}.
*
* @return an optional {@link Holder} instance pointing to this RegistryObject's name and value
*/
@SuppressWarnings("unchecked")
@NotNull
public Optional<Holder<T>> getHolder()
{
if (this.holder == null && this.key != null && registryExists(this.key.registry()))
{
ResourceLocation registryName = this.key.registry();
Registry<T> registry = (Registry<T>) Registry.REGISTRY.get(registryName);
if (registry == null)
registry = (Registry<T>) BuiltinRegistries.REGISTRY.get(registryName);
if (registry != null)
this.holder = registry.getOrCreateHolder(this.key).result().get();
}
return Optional.ofNullable(this.holder);
}
@@ -15,7 +15,10 @@ import java.util.stream.Stream;
import com.mojang.datafixers.util.Either;
import com.mojang.serialization.Codec;
import net.minecraft.Util;
import net.minecraft.core.Holder;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.HolderOwner;
import net.minecraft.core.Registry;
import net.minecraft.resources.RegistryOps;
import net.minecraft.resources.ResourceKey;
@@ -31,12 +34,12 @@ import net.minecraftforge.common.ForgeMod;
* }
* </pre>
*/
public record AnyHolderSet<T>(Registry<T> registry) implements ICustomHolderSet<T>
public record AnyHolderSet<T>(HolderLookup.RegistryLookup<T> registryLookup) implements ICustomHolderSet<T>
{
public static <T> Codec<? extends ICustomHolderSet<T>> codec(ResourceKey<? extends Registry<T>> registryKey, Codec<Holder<T>> holderCodec, boolean forceList)
{
return RegistryOps.retrieveRegistry(registryKey)
.xmap(AnyHolderSet::new, AnyHolderSet::registry)
return RegistryOps.retrieveRegistryLookup(registryKey)
.xmap(AnyHolderSet::new, AnyHolderSet::registryLookup)
.codec();
}
@@ -45,7 +48,7 @@ public record AnyHolderSet<T>(Registry<T> registry) implements ICustomHolderSet<
{
return ForgeMod.ANY_HOLDER_SET.get();
}
@Override
public Iterator<Holder<T>> iterator()
{
@@ -55,13 +58,13 @@ public record AnyHolderSet<T>(Registry<T> registry) implements ICustomHolderSet<
@Override
public Stream<Holder<T>> stream()
{
return registry.holders().map(Function.identity());
return this.registryLookup.listElements().map(Function.identity());
}
@Override
public int size()
{
return this.registry.size();
return (int) this.stream().count();
}
@Override
@@ -73,30 +76,41 @@ public record AnyHolderSet<T>(Registry<T> registry) implements ICustomHolderSet<
@Override
public Optional<Holder<T>> getRandomElement(RandomSource random)
{
return this.registry.getRandom(random);
return Util.getRandomSafe(this.stream().toList(), random);
}
@Override
public Holder<T> get(int i)
{
return this.registry.getHolder(i).orElseThrow(() -> new NoSuchElementException("No element " + i + " in registry " + this.registry.key()));
List<Holder<T>> holders = this.stream().toList();
Holder<T> holder = i >= holders.size() ? null : holders.get(i);
if (holder == null)
throw new NoSuchElementException("No element " + i + " in registry " + this.registryLookup.key());
return holder;
}
@Override
public boolean contains(Holder<T> holder)
{
return holder.unwrapKey().map(this.registry::containsKey).orElse(false);
return holder.unwrapKey().map(key -> this.registryLookup.listElementIds().anyMatch(key::equals)).orElse(false);
}
@Override
public boolean isValidInRegistry(Registry<T> registry)
public boolean canSerializeIn(HolderOwner<T> holderOwner)
{
return this.registry == registry;
return this.registryLookup.canSerializeIn(holderOwner);
}
@Override
public Optional<TagKey<T>> unwrapKey()
{
return Optional.empty();
}
@Override
public String toString()
{
return "AnySet(" + this.registry.key() + ")";
return "AnySet(" + this.registryLookup.key() + ")";
}
}
@@ -12,6 +12,7 @@ import java.util.Optional;
import java.util.Set;
import java.util.stream.Stream;
import net.minecraft.core.HolderOwner;
import org.jetbrains.annotations.Nullable;
import com.mojang.datafixers.util.Either;
@@ -37,7 +38,7 @@ public abstract class CompositeHolderSet<T> implements ICustomHolderSet<T>
private Set<Holder<T>> set = null;
@Nullable
private List<Holder<T>> list = null;
public CompositeHolderSet(List<HolderSet<T>> components)
{
this.components = components;
@@ -46,17 +47,17 @@ public abstract class CompositeHolderSet<T> implements ICustomHolderSet<T>
holderset.addInvalidationListener(this::invalidate);
}
}
/**
* {@return immutable Set of Holders given this composite holderset's component holdersets}
*/
protected abstract Set<Holder<T>> createSet();
public List<HolderSet<T>> getComponents()
{
return this.components;
}
public Set<Holder<T>> getSet()
{
Set<Holder<T>> thisSet = this.set;
@@ -71,7 +72,7 @@ public abstract class CompositeHolderSet<T> implements ICustomHolderSet<T>
return thisSet;
}
}
public List<Holder<T>> getList()
{
List<Holder<T>> thisList = this.list;
@@ -86,13 +87,13 @@ public abstract class CompositeHolderSet<T> implements ICustomHolderSet<T>
return thisList;
}
}
@Override
public void addInvalidationListener(Runnable runnable)
{
this.owners.add(runnable);
}
private void invalidate()
{
this.set = null;
@@ -144,11 +145,11 @@ public abstract class CompositeHolderSet<T> implements ICustomHolderSet<T>
}
@Override
public boolean isValidInRegistry(Registry<T> registry)
public boolean canSerializeIn(HolderOwner<T> holderOwner)
{
for (HolderSet<T> component : this.components)
{
if (!component.isValidInRegistry(registry))
if (!component.canSerializeIn(holderOwner))
{
return false;
}
@@ -156,6 +157,12 @@ public abstract class CompositeHolderSet<T> implements ICustomHolderSet<T>
return true;
}
@Override
public Optional<TagKey<T>> unwrapKey()
{
return Optional.empty();
}
@Override
public Iterator<Holder<T>> iterator()
{
@@ -11,6 +11,9 @@ import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
import net.minecraft.core.HolderGetter;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.HolderOwner;
import org.jetbrains.annotations.Nullable;
import com.mojang.datafixers.util.Either;
@@ -44,23 +47,23 @@ public class NotHolderSet<T> implements ICustomHolderSet<T>
public static <T> Codec<? extends ICustomHolderSet<T>> codec(ResourceKey<? extends Registry<T>> registryKey, Codec<Holder<T>> holderCodec, boolean forceList)
{
return RecordCodecBuilder.<NotHolderSet<T>>create(builder -> builder.group(
RegistryOps.retrieveRegistry(registryKey).forGetter(NotHolderSet::registry),
RegistryOps.retrieveRegistryLookup(registryKey).forGetter(NotHolderSet::registryLookup),
HolderSetCodec.create(registryKey, holderCodec, forceList).fieldOf("value").forGetter(NotHolderSet::value)
).apply(builder, NotHolderSet::new));
}
private final List<Runnable> owners = new ArrayList<>();
private final Registry<T> registry;
private final HolderLookup.RegistryLookup<T> registryLookup;
private final HolderSet<T> value;
@Nullable
private List<Holder<T>> list = null;
public Registry<T> registry() { return this.registry; }
public HolderLookup.RegistryLookup<T> registryLookup() { return this.registryLookup; }
public HolderSet<T> value() { return this.value; }
public NotHolderSet(Registry<T> registry, HolderSet<T> value)
public NotHolderSet(HolderLookup.RegistryLookup<T> registryLookup, HolderSet<T> value)
{
this.registry = registry;
this.registryLookup = registryLookup;
this.value = value;
this.value.addInvalidationListener(this::invalidate);
}
@@ -70,13 +73,13 @@ public class NotHolderSet<T> implements ICustomHolderSet<T>
{
return ForgeMod.NOT_HOLDER_SET.get();
}
@Override
public void addInvalidationListener(Runnable runnable)
{
this.owners.add(runnable);
}
@Override
public Iterator<Holder<T>> iterator()
{
@@ -124,9 +127,15 @@ public class NotHolderSet<T> implements ICustomHolderSet<T>
}
@Override
public boolean isValidInRegistry(Registry<T> registry)
public boolean canSerializeIn(HolderOwner<T> holderOwner)
{
return this.registry == registry;
return this.registryLookup.canSerializeIn(holderOwner);
}
@Override
public Optional<TagKey<T>> unwrapKey()
{
return Optional.empty();
}
@Override
@@ -134,13 +143,13 @@ public class NotHolderSet<T> implements ICustomHolderSet<T>
{
return "NotSet(" + this.value + ")";
}
private List<Holder<T>> getList()
{
List<Holder<T>> thisList = this.list;
if (thisList == null)
{
List<Holder<T>> list = this.registry.holders()
List<Holder<T>> list = this.registryLookup.listElements()
.filter(holder -> !this.value.contains(holder))
.map(holder -> (Holder<T>)holder)
.toList();
@@ -152,7 +161,7 @@ public class NotHolderSet<T> implements ICustomHolderSet<T>
return thisList;
}
}
private void invalidate()
{
this.list = null;
@@ -12,6 +12,7 @@ import java.util.stream.Collectors;
import com.mojang.serialization.Codec;
import net.minecraft.core.Holder;
import net.minecraft.core.HolderOwner;
import net.minecraft.core.HolderSet;
import net.minecraft.core.Registry;
import net.minecraft.resources.HolderSetCodec;
@@ -40,7 +41,7 @@ public class OrHolderSet<T> extends CompositeHolderSet<T>
.fieldOf("values")
.codec();
}
public OrHolderSet(List<HolderSet<T>> values)
{
super(values);