/* * 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 javax.annotation.Nullable; import com.google.common.collect.Multimap; import com.google.common.collect.Multimaps; 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; class NamespacedHolderHelper> { private static final Logger LOGGER = LogManager.getLogger(); private final ForgeRegistry owner; private final Registry self; @Nullable private final ResourceLocation defaultKey; @Nullable private final Function> holderLookup; private final Multimap, Supplier> 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> holdersSorted; private ObjectList> holdersById = new ObjectArrayList<>(256); private Map> holdersByName = new HashMap<>(); private Map> holders = new IdentityHashMap<>(); private volatile Map, HolderSet.Named> tags = new IdentityHashMap<>(); private Holder.Reference defaultHolder; NamespacedHolderHelper(ForgeRegistry owner, Registry self, @Nullable ResourceLocation defaultKey, @Nullable Function> holderLookup) { this.owner = owner; this.self = self; this.defaultKey = defaultKey; this.holderLookup = holderLookup; } Optional> getHolder(int id) { return id >= 0 && id < this.holdersById.size() ? Optional.ofNullable(this.holdersById.get(id)) : Optional.empty(); } Optional> getHolder(ResourceKey key) { return Optional.ofNullable(this.holdersByName.get(key.location())); } Optional> getHolder(ResourceLocation location) { return Optional.ofNullable(this.holdersByName.get(location)); } Optional> getHolder(T value) { return Optional.ofNullable(this.holders.get(value)); } Holder getOrCreateHolder(ResourceKey key) { return this.holdersByName.computeIfAbsent(key.location(), k -> { if (this.holderLookup != null) throw new IllegalStateException("This registry can't create new holders without value"); if (this.frozen) throw new IllegalStateException("Registry is already frozen (trying to add key " + k + ")"); return Holder.Reference.createStandAlone(this.self, key); }); } Optional> getRandom(Random rand) { Optional> ret = Util.getRandomSafe(this.getSortedHolders(), rand).map(Holder::hackyErase); if (this.defaultKey != null) ret = ret.or(() -> Optional.of(this.defaultHolder)); return ret; } Stream> holders() { return this.getSortedHolders().stream(); } boolean isKnownTagName(TagKey name) { return this.tags.containsKey(name); } Stream, HolderSet.Named>> getTags() { return this.tags.entrySet().stream().map(e -> Pair.of(e.getKey(), e.getValue())); } HolderSet.Named getOrCreateTag(TagKey name) { HolderSet.Named 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, HolderSet.Named> map = new IdentityHashMap<>(this.tags); map.put(name, named); this.tags = map; } return named; } void addOptionalTag(TagKey name, @NotNull Set> defaults) { this.optionalTags.putAll(name, defaults); } Stream> getTagNames() { return this.tags.keySet().stream(); } //TODO: Move this to ValidateCallback? Registry freeze() { this.frozen = true; List 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> 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 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> getTag(TagKey name) { return Optional.ofNullable(this.tags.get(name)); } void bindTags(Map, List>> newTags) { Map, List>> 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> 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, HolderSet.Named> tmpTags = new IdentityHashMap<>(this.tags); newTags.forEach((k, v) -> tmpTags.computeIfAbsent(k, this::createTag).bind(v)); Set> defaultedTags = Sets.difference(this.optionalTags.keySet(), newTags.keySet()); defaultedTags.forEach(name -> { List> 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, List>> holderToTag, TagKey name, Holder 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)) throw new IllegalStateException("Found direct holder " + holder + " value in tag " + name); holderToTag.get((Holder.Reference) 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 onAdded(RegistryManager stage, int id, 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. ResourceKey key = ResourceKey.create(this.self.key(), newValue.getRegistryName()); //Holder.Reference 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 newHolder = getHolder(key, newValue); this.holdersById.size(Math.max(this.holdersById.size(), id + 1)); this.holdersById.set(id, newHolder); this.holdersByName.put(newValue.getRegistryName(), 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 createTag(TagKey name) { return new HolderSet.Named<>(this.self, name); } private Holder.Reference getHolder(ResourceKey key, T value) { if (this.holderLookup != null) return this.holderLookup.apply(value); return this.holdersByName.computeIfAbsent(value.getRegistryName(), k -> Holder.Reference.createStandAlone(this.self, key)); } private List> getSortedHolders() { if (this.holdersSorted == null) this.holdersSorted = this.holdersById.stream().filter(Objects::nonNull).toList(); return this.holdersSorted; } }