Usability improvements to RegistryObject/DeferredRegister

This commit is contained in:
tterrag committed 2019-09-25 18:01:39 -04:00
1 parent d510978446
commit 476b7056fb
3 files changed
+75 -16

No files matched your search

@@ -19,15 +19,17 @@
package net.minecraftforge.registries;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.RegistryObject;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.function.Supplier;
/**
* Utility class to help with managing registry entries.
* Maintains a list of all suppliers for entries and registers them during the proper Register event.
@@ -53,7 +55,7 @@ public class DeferredRegister<T extends IForgeRegistryEntry<T>>
{
private final IForgeRegistry<T> type;
private final String modid;
private List<Supplier<? extends T>> entries = new ArrayList<>();
private Map<RegistryObject<T>, Supplier<? extends T>> entries = new LinkedHashMap<>();
public DeferredRegister(IForgeRegistry<T> reg, String modid)
{
@@ -68,11 +70,17 @@ public class DeferredRegister<T extends IForgeRegistryEntry<T>>
* @param sup A factory for the new entry, it should return a new instance every time it is called.
* @return A RegistryObject that will be updated with when the entries in the registry change.
*/
@SuppressWarnings("unchecked")
public <I extends T> RegistryObject<I> register(final String name, final Supplier<I> sup)
{
Objects.requireNonNull(name);
Objects.requireNonNull(sup);
final ResourceLocation key = new ResourceLocation(modid, name);
entries.add(() -> sup.get().setRegistryName(key));
return RegistryObject.of(key.toString(), this.type);
RegistryObject<I> ret = RegistryObject.of(key, this.type);
if (entries.putIfAbsent((RegistryObject<T>) ret, () -> sup.get().setRegistryName(key)) != null) {
throw new IllegalArgumentException("Duplicate registration " + name);
}
return ret;
}
/**
@@ -92,7 +100,11 @@ public class DeferredRegister<T extends IForgeRegistryEntry<T>>
{
@SuppressWarnings("unchecked")
IForgeRegistry<T> reg = (IForgeRegistry<T>)event.getRegistry();
entries.stream().map(Supplier::get).forEach(reg::register);
for (Entry<RegistryObject<T>, Supplier<? extends T>> e : entries.entrySet())
{
reg.register(e.getValue().get());
e.getKey().updateReference(reg);
}
}
}
}