Line 1: |
Line 1: |
− | {{Under construction}}
| + | Registration is the process of making an object (such as an item or block) known to the game during runtime with an attached <code>ResourceLocation</code> name. Unregistered objects are a likely cause of game loading crashes or bugs, so it is important to register objects correctly. |
| | | |
− | Registration is the process of making an object (such as an item or block) known to the game during runtime. If some objects are not registered, this could cause crashes even before the game is fully loaded or arbitrary behaviors such as bottlenecking mod compatibility for world generation.
| + | Most objects that are known within the game are handled by a Vanilla <code>Registry</code> or a Forge <code>IForgeRegistry</code>. Each registry uniquely defines each of its own objects through a "registry name" via a [[Using Resources#ResourceLocation|ResourceLocation]]. |
| + | Registries themselves have a name and are registered to the Vanilla root registry or <code>RegistryManager</code>. |
| + | It is important to keep these distinct; although both are called registry names. |
| | | |
− | Most objects that are known within the game are handled by a <code>Registry</code>. Each registry uniquely defines each object through a "registry name" via a [[Using Resources#ResourceLocation|ResourceLocation]]. This "registry name" can be accessed with its respective getter and setter: <code>#getRegistryName</code> and <code>#setRegistryName</code>. You can only set the "registry name" of a given object once; otherwise, an exception will be thrown.
| + | {{Tip|In a global context, each object is universally unique through its <code>ResourceKey</code>: a concatenation of its registry's id and the object's registry name.}} |
| + | |
| + | Forge expands Vanilla's registries to add important features for modded environments, such as world saving of integer ids and network syncing of integer ids, to ensure consistency when different mods and entries are present. |
| | | |
− | {{Tip|In a global context, each object is universally unique through its <code>ResourceKey</code>: a concatenation of its registry's id and the object's registry name.}}
| + | Forge registries preserves the same loading order of Vanilla registries, with all modded registries fired after Vanilla in alphabetical order by string comparing namespace then path. This loading order determines what order registries have their entries registered. All registries wrapped by Forge can be found within the <code>ForgeRegistries</code> class. |
| | | |
− | Due to the inconsistent ordering and registration process vanilla uses, Forge wraps most vanilla registries using <code>IForgeRegistry</code>. This guarantees that the loading order for these wrapped registries will be <code>Block</code>, <code>Item</code>, and then the rest of the wrapped registries in alphabetical order. All registries supported by Forge can be found within the <code>ForgeRegistries</code> class. Since all registry names are unique to a specific registry, different registry objects within different registries can have the same name (e.g. a <code>Block</code> and an <code>Item</code> each hold a registry object named <code>examplemod:object</code>.
| + | {{Tip|All registries have their own set of names and objects, so the same name (e.g. <code>examplemod:object</code>) can be reused in multiple registries, like blocks and items.}} |
| | | |
− | {{Tip/Warning|If two registry objects within the same registry have the same name, the second object will override the first. The only registry that will throw an <code>IllegalArgumentException</code> is the <code>DataSerializerEntry</code> registry.}} | + | {{Tip/Warning|If two registry objects within the '''same''' registry have the same name, the second object will override the first.}} |
| | | |
| == Methods for Registering == | | == Methods for Registering == |
| | | |
− | There are two proper ways to register objects within an associated wrapped Forge registry: the <code>DeferredRegister</code> class, and the <code>RegistryEvent$Register</code> lifecycle event. | + | There are two proper ways to register objects to a Forge registry or Vanilla registry: the <code>DeferredRegister</code> class, and the <code>RegisterEvent</code> lifecycle event. |
| | | |
− | For objects with '''no''' associated Forge registry, you can register the associated entry during the <code>FMLCommonSetupEvent</code> lifecycle event. In some cases, although not recommended, you may also statically initialize and register these entries.
| + | === DeferredRegister === |
| | | |
− | === DeferredRegister ===
| + | <code>DeferredRegister</code> is an abstraction layer over the registry event used to register objects. It maintains a map of "registry name" to their associated suppliers and resolves those suppliers during <code>RegisterEvent</code> for the associated registry. This method is the currently recommended, and documented, way to handle these objects as it provides convenience and safety for those who want to statically initialize objects while avoiding some issues associated with it. |
| | | |
− | <code>DeferredRegister</code> is an abstraction layer over the registry event used to register objects. It maintains a map of "registry name" to their associated suppliers and resolves those suppliers during the proper <code>RegistryEvent$Register</code> event. This method is the currently recommended, and documented, way to handle these objects as it provides convenience and safety for those who want to statically initialize objects while avoiding some issues associated with it. | + | {{Tip/Important|When using <code>DeferredRegister</code>s with non-vanilla registries, the registry key or the registry name should be supplied to the <code>create</code> method. These include the custom Forge registries for entity data serializers, global loot modifier serializers, world presets, and biome modifier serializers. Calling <code>Supplier#get</code> on a <code>Supplier<IForgeRegistry<?>></code> when making a DeferredRegister will return null because the registry does not exist yet.}} |
| | | |
| An example of a mod registering a custom block: | | An example of a mod registering a custom block: |
Line 47: |
Line 51: |
| class ExampleMod { | | class ExampleMod { |
| BLOCKS.register(FMLJavaModLoadingContext.get.getModEventBus) | | BLOCKS.register(FMLJavaModLoadingContext.get.getModEventBus) |
| + | } |
| + | |groovy=private static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, MODID); |
| + | |
| + | public static final RegistryObject<Block> EXAMPLE_BLOCK = BLOCKS.register("example_block", () -> new Block(BlockBehaviour.Properties.of(Material.STONE))); |
| + | |
| + | ExampleMod() { |
| + | BLOCKS.register(FMLJavaModLoadingContext.get().modEventBus); |
| } | | } |
| |}} | | |}} |
Line 52: |
Line 63: |
| {{Tip|When using a <code>DeferredRegister</code> to register any object, the name inputted will be automatically prefixed with the mod id passed in, giving the above object a "registry name" of <code>examplemod:example_block</code>.}} | | {{Tip|When using a <code>DeferredRegister</code> to register any object, the name inputted will be automatically prefixed with the mod id passed in, giving the above object a "registry name" of <code>examplemod:example_block</code>.}} |
| | | |
− | === RegistryEvent.Register === | + | === RegisterEvent === |
− | | |
− | The <code>RegistryEvent</code>s are another, more slightly flexible way to register objects. These [[Events|events]] are fired synchronously after <code>FMLConstructModEvent</code> and before the configs are loaded.
| |
| | | |
− | The event used to register objects is <code>RegistryEvent.Register<T></code>, where the type parameter <code>T</code> is the object type being registered. You can grab the associated registry using <code>#getRegistry</code> and register the objects within using either <code>#register</code> (pass in a single object) or <code>#registerAll</code> (pass in ''varargs'' or an array of objects). The latter is useful for minimizing calls to <code>#register</code>, although it provides no benefit time-complexity wise. | + | The <code>RegisterEvent</code> is the second way register objects. This [[Events|event]] is fired for each registry synchronously in vanilla registry order after <code>FMLConstructModEvent</code> and before the configs are loaded. Objects are registered using <code>#register</code> by passing in the registry key, the name of the registry object, and the object itself. There is an additional <code>#register</code> overload which takes in a consumed helper to register an object with a given name. It is recommended to use this method to avoid unnecessary object creation. |
− | | |
− | {{Tip/Important|The type parameter specified must be the exact class used within the Forge registry, not its superclass nor its subclass. If the class specified is not referenced as a type parameter within the associated Forge registries, then the event will not be called.}}
| |
| | | |
| Here is an example: (the event handler is registered on the '''mod event bus''') | | Here is an example: (the event handler is registered on the '''mod event bus''') |
Line 64: |
Line 71: |
| {{Template:Tabs/Code_Snippets | | {{Template:Tabs/Code_Snippets |
| |java=@SubscribeEvent | | |java=@SubscribeEvent |
− | public void registerBlocks(RegistryEvent.Register<Block> event) { | + | public void register(RegisterEvent event) { |
− | event.getRegistry().registerAll(new Block(...).setRegistryName(new ResourceLocation(MODID, "example_block1")), new Block(...).setRegistryName(new ResourceLocation(MODID, "example_block2")), ...); | + | event.register(ForgeRegistries.Keys.BLOCKS, |
| + | helper -> helper.register(new ResourceLocation(MODID, "example_block"), new Block(...)) |
| + | ); |
| } | | } |
| |kotlin=@JvmStatic | | |kotlin=@JvmStatic |
| @SubscribeEvent | | @SubscribeEvent |
− | private fun registerBlocks(event: RegistryEvent.Register<Block>) = | + | private fun register(event: RegisterEvent) = |
− | event.registry.registerAll(Block(...).setRegistryName(new ResourceLocation(MODID, "example_block1")), Block(...).setRegistryName(new ResourceLocation(MODID, "example_block2")), ...) | + | event.register(ForgeRegistries.Keys.BLOCKS) { |
| + | helper -> helper.register(ResourceLocation(MODID, "example_block"), Block(...)) |
| + | } |
| |scala=@SubscribeEvent | | |scala=@SubscribeEvent |
− | def registerBlocks(event: RegistryEvent.Register[Block]): Unit = | + | def register(event: RegisterEvent): Unit = |
− | event.getRegistry.registerAll(new Block(...).setRegistryName(new ResourceLocation(MODID, "example_block1")), new Block(...).setRegistryName(new ResourceLocation(MODID, "example_block2")), ...) | + | event.register(ForgeRegistries.Keys.BLOCKS, |
| + | helper => helper.register(new ResourceLocation(MODID, "example_block"), new Block(...)) |
| + | ) |
| |}} | | |}} |
| | | |
Line 91: |
Line 104: |
| === Non-Forge Registries === | | === Non-Forge Registries === |
| | | |
− | Not all vanilla registries are wrapped as a Forge registry. This is because the registry is fully independent from any other registry, completely data driven, or just has not been wrapped yet. | + | Not all vanilla registries are wrapped as a Forge registry. To register objects to any one of these registries, create a <code>DeferredRegister</code> via the <code>#create</code> overload which takes in a resource key of the registry and the mod id to register the entries for. Then simply call <code>#register</code> like any other <code>DeferredRegister</code>. |
− | | |
− | These registries include:
| |
− | * Custom Stats (a <code>ResourceLocation</code> registry)
| |
− | * <code>RuleTestType</code>
| |
− | * <code>PosRuleTestType</code>
| |
− | * <code>RecipeType</code>
| |
− | * <code>GameEvent</code>
| |
− | * <code>PositionSourceType</code>
| |
− | * <code>VillagerType</code>
| |
− | * <code>LootPoolEntryType</code>
| |
− | * <code>LootItemFunctionType</code>
| |
− | * <code>LootItemConditionType</code>
| |
− | * <code>LootNumberProviderType</code>
| |
− | * <code>LootNbtProviderType</code>
| |
− | * <code>LootScoreProviderType</code>
| |
− | * <code>FloatProviderType</code>
| |
− | * <code>IntProviderType</code>
| |
− | * <code>HeightProviderType</code>
| |
− | * <code>StructurePieceType</code>
| |
− | * <code>TrunkPlacerType</code>
| |
− | * <code>FeatureSizeType</code>
| |
− | * A <code>Codec</code> of <code>BiomeSource</code>
| |
− | * A <code>Codec</code> of <code>ChunkGenerator</code>
| |
− | * <code>StructureProcessorType</code>
| |
− | * <code>StructurePoolElementType</code>
| |
− | * All registries within <code>BuiltinRegistries</code> excluding <code>Biome</code>
| |
− | | |
− | To register objects to any one of these registries, you will need to call <code>Registry::register(Registry, ResourceLocation, T)</code> where the type parameter <code>T</code> is the object instance being registered. The method can then be called and registered during the highest priority of <code>FMLCommonSetupEvent</code>. We can also utilize a <code>Lazy</code> above to store the result on first access and use within our code. | |
− | | |
− | Here is an example: (the event handler is registered on the '''mod event bus''')
| |
| | | |
| {{Template:Tabs/Code_Snippets | | {{Template:Tabs/Code_Snippets |
− | |java=public static final Lazy<ConfiguredFeature<?, ?>> EXAMPLE_CONFIGURED_FEATURE = Lazy.of(() -> | + | |java=private static final DeferredRegister<LootItemConditionType> REGISTER = DeferredRegister.create(Registry.LOOT_ITEM_REGISTRY, MODID); |
− | register("example_configured_feature",
| |
− | Feature.NO_OP.configured(NoneFeatureConfiguration.INSTANCE)
| |
− | .decorated(FeatureDecorator.NOPE.configured(NoneDecoratorConfiguration.INSTANCE))
| |
− | )
| |
− | );
| |
− | | |
− | @SubscribeEvent(priority = EventPriority.HIGHEST)
| |
− | public void register(FMLCommonSetupEvent event) {
| |
− | event.enqueueWork(EXAMPLE_CONFIGURED_FEATURE::get);
| |
− | }
| |
− | | |
− | private static <T extends ConfiguredFeature<?, ?>> T register(String name, T value) {
| |
− | return Registry.register(BuiltinRegistries.CONFIGURED_FEATURE, new ResourceLocation(MODID, name), value);
| |
− | }
| |
− | |kotlin=val EXAMPLE_CONFIGURED_FEATURE: ConfiguredFeature<*, *> by lazy {
| |
− | register("example_configured_feature",
| |
− | Feature.NO_OP.configured(NoneFeatureConfiguration.INSTANCE)
| |
− | .decorated(FeatureDecorator.NOPE.configured(NoneDecoratorConfiguration.INSTANCE)))
| |
− | }
| |
− | | |
− | object Events {
| |
− | | |
− | @SubscribeEvent(priority = EventPriority.HIGHEST)
| |
− | fun register(event: FMLCommonSetupEvent) {
| |
− | event.enqueueWork(EXAMPLE_CONFIGURED_FEATURE::getConfig)
| |
− | }
| |
− | }
| |
| | | |
− | private fun <T: ConfiguredFeature<*, *>> register(name: String, value: T): T =
| + | public static final RegistryObject<LootItemConditionType> EXAMPLE_LOOT_ITEM_CONDITION_TYPE = REGISTER.register("example_loot_item_condition_type", () -> new LootItemConditionType(...)); |
− | Registry.register(BuiltinRegistries.CONFIGURED_FEATURE, ResourceLocation(MODID, name), value)
| + | |kotlin=private val REGISTER = DeferredRegister.create(Registry.LOOT_ITEM_REGISTRY, MODID) |
− | |scala=class Events {
| |
− | @SubscribeEvent(priority = EventPriority.HIGHEST)
| |
− | def register(event: FMLCommonSetupEvent): Unit = {
| |
− | event.enqueueWork(Events.EXAMPLE_CONFIGURED_FEATURE.getConfig _)
| |
− | }
| |
− | }
| |
− | object Events {
| |
− | final lazy val EXAMPLE_CONFIGURED_FEATURE = register("example_configured_feature",
| |
− | Feature.NO_OP.configured(NoneFeatureConfiguration.INSTANCE)
| |
− | .decorated(FeatureDecorator.NOPE.configured(NoneDecoratorConfiguration.INSTANCE)))
| |
| | | |
− | private def register[T <: ConfiguredFeature[_, _]](name: String, value: T): T =
| + | val EXAMPLE_LOOT_ITEM_CONDITION_TYPE : RegistryObject<LootItemConditionType> = REGISTER.register("example_loot_item_condition_type") { |
− | Registry.register(BuiltinRegistries.CONFIGURED_FEATURE, new ResourceLocation(MODID, name), value)
| + | LootItemConditionType(...) |
| } | | } |
− | |}} | + | |scala=private final val REGISTER = DeferredRegister.create(Registry.LOOT_ITEM_REGISTRY, MODID) |
| | | |
− | {{Tip/Warning|Vanilla registry methods are not thread-safe, so they must be wrapped within the synchronous queue provided within the common setup event via <code>#enqueueWork</code>.}}
| + | final val EXAMPLE_LOOT_ITEM_CONDITION_TYPE = REGISTER.register("example_loot_item_condition_type", () => new LootItemConditionType(...)) |
| + | |groovy=private static final DeferredRegister<LootItemConditionType> REGISTER = DeferredRegister.create(Registry.LOOT_ITEM_REGISTRY, MODID); |
| | | |
− | Besides the registries within <code>BuiltinRegistries</code>, all other '''non-forge''' wrapped registries can be statically initialized like so:
| + | public static final RegistryObject<LootItemConditionType> EXAMPLE_LOOT_ITEM_CONDITION_TYPE = REGISTER.register("example_loot_item_condition_type", () -> new LootItemConditionType(...)); |
− | | |
− | {{Template:Tabs/Code_Snippets
| |
− | |java=public static final RecipeType<ExampleRecipe> EXAMPLE_RECIPE = RecipeType.register(MODID + ":example_recipe");
| |
− | |kotlin=val EXAMPLE_RECIPE: RecipeType<ExampleRecipe> = RecipeType.register("${MODID}:example_recipe")
| |
− | |scala=final val EXAMPLE_RECIPE = RecipeType.register(s"${MODID}:example_recipe")
| |
| |}} | | |}} |
| | | |
− | If you attempt to make one of these instances require an instance of another registry object, you must use the lazy initialization method mentioned above to register the object in the correct order. | + | If you attempt to make one of these instances require an instance of another registry object, you should use the lazy initialization method mentioned above to register the object in the correct order. |
| | | |
| === Data Driven Entries === | | === Data Driven Entries === |
Line 187: |
Line 129: |
| Registries are considered to be data driven if they are located within <code>RegistryAccess</code> with the exception of <code>LevelStem</code> and <code>Level</code>. | | Registries are considered to be data driven if they are located within <code>RegistryAccess</code> with the exception of <code>LevelStem</code> and <code>Level</code>. |
| | | |
− | The following registries are data driven:
| + | These registry objects only need to be registered within code if they are to be used within a pre-existing registry object (e.g. a <code>PlacedFeature</code> for ore generation within an overworld <code>Biome</code>). Otherwise, their instance can be purely registered using a JSON file. |
− | * <code>ConfiguredSurfaceBuilder</code>
| |
− | * <code>ConfiguredWorldCarver</code>
| |
− | * <code>ConfiguredFeature</code>
| |
− | * <code>ConfiguredStructureFeature</code>
| |
− | * <code>StructureProcessorList</code>
| |
− | * <code>StructureTemplatePool</code>
| |
− | * <code>Biome</code>
| |
− | * <code>NoiseGeneratorSettings</code>
| |
− | * <code>DimensionType</code>
| |
− | * <code>LevelStem</code>
| |
− | * <code>Level</code>
| |
− | | |
− | These registry objects only need to be registered within code if they are to be used within a pre-existing registry object (e.g. a <code>ConfiguredFeature</code> for ore generation within an overworld <code>Biome</code>). Otherwise, their instance can be purely registered using a JSON file. | |
| | | |
| If a data driven registry object has to be registered within code, a dummy object should be supplied to hold a "registry name" and then constructed within a JSON file. | | If a data driven registry object has to be registered within code, a dummy object should be supplied to hold a "registry name" and then constructed within a JSON file. |
Line 206: |
Line 135: |
| == Referencing Registered Objects == | | == Referencing Registered Objects == |
| | | |
− | Each forge registered object should not be statically initialized nor reference another instance being registered. They must always be a new, singleton instance that is resolved during their respective <code>RegistryEvent$Register</code> event. This is to maintain a sane loading order for registries and their objects along with dynamic loading/unloading of mods. | + | Each forge registered object should not be statically initialized nor reference another instance being registered. They must always be a new, singleton instance that is resolved during when <code>RegisterEvent</code> is called for their registry. This is to maintain a sane loading order for registries and their objects along with dynamic loading/unloading of mods. |
| | | |
| Forge registered objects must always be referenced through a <code>RegistryObject</code> or a field with <code>@ObjectHolder</code>. | | Forge registered objects must always be referenced through a <code>RegistryObject</code> or a field with <code>@ObjectHolder</code>. |
| | | |
| ===Using RegistryObjects=== | | ===Using RegistryObjects=== |
− | <code>RegistryObject</code>s can be used to retrieve references to registered objects once they become available. Their references are updated along with all <code>@ObjectHolder</code> annotations after the associated <code>RegistryEvent$Register</code> has been dispatched and frozen. | + | <code>RegistryObject</code>s can be used to retrieve references to registered objects once they become available. Their references are updated along with all <code>@ObjectHolder</code> annotations after the registry that <code>RegisterEvent</code> is called for is dispatched and frozen. |
| | | |
− | A <code>RegistryObject</code> can be retrieved as a result of using <code>DeferredRegister</code> or calling the static constructor <code>RegistryObject::of</code>. Each static constructor takes in the "registry name" of the object being referenced and either a <code>IForgeRegistry</code> or, if custom registries are used, a supplier of the object class implementing <code>IForgeRegistryEntry</code>. The <code>RegistryObject</code> can be stored within some field and retrieve the registered object using <code>#get</code>. | + | A <code>RegistryObject</code> can be retrieved as a result of using <code>DeferredRegister</code> or calling the static factory <code>RegistryObject#create</code>. Each static factory takes in the "registry name" of the object being referenced and one of the following: a <code>IForgeRegistry</code>, a registry name of the type <code>ResourceLocation</code>, or a registry key of the type <code>ResourceKey<? extends Registry<?>></code>. The <code>RegistryObject</code> can be stored within some field and retrieve the registered object using <code>#get</code>. |
| | | |
| An example using <code>RegistryObject</code>: | | An example using <code>RegistryObject</code>: |
| {{Template:Tabs/Code_Snippets | | {{Template:Tabs/Code_Snippets |
− | |java=public static final RegistryObject<Item> EXAMPLE_ITEM = RegistryObject.of(new ResourceLocation("examplemod:example_item"), ForgeRegistries.ITEMS); | + | |java=public static final RegistryObject<Item> EXAMPLE_ITEM = RegistryObject.create(new ResourceLocation("examplemod", "example_item"), ForgeRegistries.ITEMS); |
| | | |
− | // Assume that 'ExampleRegistry' is a valid registry, and 'examplemod:example_object' is a valid object within that registry | + | // Assume that 'examplemod:example_registry' is a valid registry, and 'examplemod:example_object' is a valid object within that registry |
− | public static final RegistryObject<ExampleRegistry> EXAMPLE_OBJECT = RegistryObject.of(new ResourceLocation("examplemod", "example_object"), () -> ExampleRegistry.class); | + | public static final RegistryObject<ExampleRegistry> EXAMPLE_OBJECT = RegistryObject.create(new ResourceLocation("examplemod", "example_object"), new ResourceLocation("examplemod", "example_registry"), "examplemod"); |
− | |kotlin=val EXAMPLE_ITEM: RegistryObject<Item> = RegistryObject.of(ResourceLocation("examplemod:example_item"), ForgeRegistries.ITEMS) | + | |kotlin=val EXAMPLE_ITEM: RegistryObject<Item> = RegistryObject.create(ResourceLocation("examplemod", "example_item"), ForgeRegistries.ITEMS) |
| | | |
− | // Assume that 'ExampleRegistry' is a valid registry, and 'examplemod:example_object' is a valid object within that registry | + | // Assume that 'examplemod:example_registry' is a valid registry, and 'examplemod:example_object' is a valid object within that registry |
− | val EXAMPLE_OBJECT: RegistryObject<ExampleRegistry> = RegistryObject.of(ResourceLocation("examplemod", "example_object")) { ExampleRegistry.class } | + | val EXAMPLE_OBJECT: RegistryObject<ExampleRegistry> = RegistryObject.create(ResourceLocation("examplemod", "example_object"), new ResourceLocation("examplemod", "example_registry"), "examplemod") |
− | |scala=final val EXAMPLE_ITEM = RegistryObject.of(new ResourceLocation("examplemod:example_item"), ForgeRegistries.ITEMS) | + | |scala=final val EXAMPLE_ITEM = RegistryObject.create(new ResourceLocation("examplemod", "example_item"), ForgeRegistries.ITEMS) |
| | | |
− | // Assume that 'ExampleRegistry' is a valid registry, and 'examplemod:example_object' is a valid object within that registry | + | // Assume that 'examplemod:example_registry' is a valid registry, and 'examplemod:example_object' is a valid object within that registry |
− | final val EXAMPLE_OBJECT = RegistryObject.of(new ResourceLocation("examplemod", "example_object"), () => classOf[ExampleRegistry]); | + | final val EXAMPLE_OBJECT = RegistryObject.create(new ResourceLocation("examplemod", "example_object"), new ResourceLocation("examplemod", "example_registry"), "examplemod"); |
| |}} | | |}} |
| | | |
− | {{Tip/Important|All vanilla objects are bootstrapped and registered before mods are loaded. As such, they can be referenced as is without any issues, assuming the entries are not replaced.}} | + | {{Tip/Important|All vanilla objects are bootstrapped and registered before mods are loaded. As such, they can be referenced as is without any issues.}} |
| | | |
| === Using @ObjectHolder === | | === Using @ObjectHolder === |
| | | |
− | Forge registry objects can also be injected into <code>public static</code> fields with either their class or that field annotated with <code>@ObjectHolder</code>. There must be enough information to construct a <code>ResourceLocation</code> to identify a single object within a specific registry. | + | Forge registry objects can also be injected into <code>public static final</code> fields by annotating each field with <code>@ObjectHolder</code>. Note that using <code>RegistryObject</code>s is the preferred strategy as ObjectHolders are verbose, clunky, and easy to mess up. |
| + | |
| + | ObjectHolders can only be applied to fields and require 2 pieces of information: the registry name of your target registry and the name of your object entry inside the registry. |
| + | |
| + | The registry name can be found inside of <code>ForgeRegistries.Keys</code> or <code>Registry</code>. |
| + | For blocks, this would be <code>"minecraft:block"</code>. |
| + | For items, this would be <code>"minecraft:item"</code>, etc. |
| + | |
| + | The name of your entry is dependent on what you called it and requires your modid to be prefixed. |
| + | When using <code>@ObjectHolder</code> inside of your main mod class annotated with <code>@Mod</code>, the modid namespace can be omitted. |
| | | |
| The rules for <code>@ObjectHolder</code> are as follows: | | The rules for <code>@ObjectHolder</code> are as follows: |
| | | |
− | * If the class is annotated with <code>@ObjectHolder</code>, its value will be the default namespace for all fields within if not explicitly defined
| |
| * If the class is annotated with <code>@Mod</code>, the modid will be the default namespace for all annotated fields within if not explicitly defined | | * If the class is annotated with <code>@Mod</code>, the modid will be the default namespace for all annotated fields within if not explicitly defined |
| * A field is considered for injection if: | | * A field is considered for injection if: |
− | ** it has at least the modifiers <code>public static</code>; and | + | ** it has at least the modifiers <code>public static</code> and optionally <code>final</code>, and |
− | ** one of the following conditions are true:
| + | ** the '''field''' is annotated with <code>@ObjectHolder</code>, and: |
− | *** the '''enclosing class''' has an <code>@ObjectHolder</code> annotation, and the field is <code>final</code>, and:
| + | *** the entry name value is explicitly defined, and |
− | **** the name value is the field's name; and
| + | *** the registry name value is explicitly defined |
− | **** the namespace value is the enclosing class's namespace
| |
− | **** ''An exception is thrown if the namespace value cannot be found and inherited''
| |
− | *** the '''field''' is annotated with <code>@ObjectHolder</code>, and:
| |
− | **** the name value is explicitly defined; and
| |
− | **** the namespace value is either explicitly defined or the enclosing class's namespace
| |
− | ** the field type or one of its supertypes corresponds to a valid registry (e.g. <code>Item</code> or <code>ArrowItem</code> for the <code>Item</code> registry)
| |
− | ** ''An exception is thrown if a field does not have a corresponding registry.''
| |
| * ''An exception is thrown if the resulting <code>ResourceLocation</code> is incomplete or invalid (non-valid characters in path)'' | | * ''An exception is thrown if the resulting <code>ResourceLocation</code> is incomplete or invalid (non-valid characters in path)'' |
| * If no other errors or exceptions occur, the field will be injected | | * If no other errors or exceptions occur, the field will be injected |
| * If all of the above rules do not apply, no action will be taken (and a message may be logged) | | * If all of the above rules do not apply, no action will be taken (and a message may be logged) |
| | | |
− | <code>@ObjectHolder</code> annotated fields are injected with their associated object values after their corresponding registry's <code>RegistryEvent$Register</code> event is fired, along with <code>RegistryObject</code>s. | + | <code>@ObjectHolder</code> annotated fields are injected with their associated object values after <code>RegisterEvent</code> is fired for their registry, the same time that <code>RegistryObject</code>s are filled. ObjectHolders will remain empty if the associated registry does not exist. |
| | | |
| {{Tip/Warning|If the object does not exist in the registry when it is to be injected, a debug message will be logged, and no value will be injected. If the object is found, but the field cannot be set, a warning message will be logged instead.}} | | {{Tip/Warning|If the object does not exist in the registry when it is to be injected, a debug message will be logged, and no value will be injected. If the object is found, but the field cannot be set, a warning message will be logged instead.}} |
Line 266: |
Line 196: |
| <div class="mw-collapsible-content" style="overflow: auto; white-space: nowrap;"> | | <div class="mw-collapsible-content" style="overflow: auto; white-space: nowrap;"> |
| <syntaxhighlight lang="java"> | | <syntaxhighlight lang="java"> |
− | @ObjectHolder("minecraft") // Inheritable resource namespace: "minecraft"
| + | class Holder { |
− | class AnnotatedHolder { | + | @ObjectHolder(registryName = "minecraft:enchantment", value = "minecraft:flame") |
− | public static final Block diamond_block = null; // No annotation. [public static final] is required.
| |
− | // Block has a corresponding registry: [Block]
| |
− | // Name path is the name of the field: "diamond_block"
| |
− | // Namespace is not explicitly defined.
| |
− | // So, namespace is inherited from class annotation: "minecraft"
| |
− | // To inject: "minecraft:diamond_block" from the [Block] registry
| |
− | | |
− | @ObjectHolder("ambient.cave")
| |
− | public static SoundEvent ambient_sound = null; // Annotation present. [public static] is required.
| |
− | // SoundEvent has a corresponding registry: [SoundEvent]
| |
− | // Name path is the value of the annotation: "ambient.cave"
| |
− | // Namespace is not explicitly defined.
| |
− | // So, namespace is inherited from class annotation: "minecraft"
| |
− | // To inject: "minecraft:ambient.cave" from the [SoundEvent] registry
| |
− | | |
− | // Assume for the next entry that [ManaType] is a valid registry.
| |
− | @ObjectHolder("neomagicae:coffeinum")
| |
− | public static final ManaType coffeinum = null; // Annotation present. [public static] is required. [final] is optional.
| |
− | // ManaType has a corresponding registry: [ManaType] (custom registry)
| |
− | // Resource location is explicitly defined: "neomagicae:coffeinum"
| |
− | // To inject: "neomagicae:coffeinum" from the [ManaType] registry
| |
− | | |
− | public static final Item ENDER_PEARL = null; // No annotation. [public static final] is required.
| |
− | // Item has a corresponding registry: [Item].
| |
− | // Name path is the name of the field: "ENDER_PEARL" -> "ender_pearl"
| |
− | // !! ^ Field name is valid, because they are
| |
− | // converted to lowercase automatically.
| |
− | // Namespace is not explicitly defined.
| |
− | // So, namespace is inherited from class annotation: "minecraft"
| |
− | // To inject: "minecraft:ender_pearl" from the [Item] registry
| |
− | | |
− | @ObjectHolder("minecraft:arrow") | |
− | public static final ArrowItem arrow = null; // Annotation present. [public static] is required. [final] is optional.
| |
− | // ArrowItem does not have a corresponding registry.
| |
− | // ArrowItem's supertype of Item has a corresponding registry: [Item]
| |
− | // Resource location is explicitly defined: "minecraft:arrow"
| |
− | // To inject: "minecraft:arrow" from the [Item] registry
| |
− | | |
− | public static Block bedrock = null; // No annotation, so [public static final] is required.
| |
− | // Therefore, the field is ignored.
| |
− |
| |
− | public static final CreativeModeTab group = null; // No annotation. [public static final] is required.
| |
− | // CreativeModeTab does not have a corresponding registry.
| |
− | // No supertypes of CreativeModeTab has a corresponding registry.
| |
− | // Therefore, THIS WILL PRODUCE AN EXCEPTION.
| |
− | }
| |
− | | |
− | class UnannotatedHolder { // Note the lack of an @ObjectHolder annotation on this class.
| |
− | @ObjectHolder("minecraft:flame")
| |
| public static final Enchantment flame = null; // Annotation present. [public static] is required. [final] is optional. | | public static final Enchantment flame = null; // Annotation present. [public static] is required. [final] is optional. |
− | // Enchantment has corresponding registry: [Enchantment]. | + | // Registry name is explicitly defined: "minecraft:enchantment" |
| // Resource location is explicitly defined: "minecraft:flame" | | // Resource location is explicitly defined: "minecraft:flame" |
| // To inject: "minecraft:flame" from the [Enchantment] registry | | // To inject: "minecraft:flame" from the [Enchantment] registry |
| | | |
− | public static final Biome ice_flat = null; // No annotation on the enclosing class. | + | public static final Biome ice_flat = null; // No annotation on the field. |
| // Therefore, the field is ignored. | | // Therefore, the field is ignored. |
| | | |
| @ObjectHolder("minecraft:creeper") | | @ObjectHolder("minecraft:creeper") |
− | public static Entity creeper = null; // Annotation present. [public static] is required. | + | public static final Entity creeper = null; // Annotation present. [public static] is required. [final] is optional. |
− | // Entity does not have a corresponding registry. | + | // The registry name has not been specified on the field. |
− | // No supertypes of Entity has a corresponding registry.
| + | // Therefore, this will not compile. |
− | // Therefore, THIS WILL PRODUCE AN EXCEPTION. | |
| | | |
− | @ObjectHolder("levitation") | + | @ObjectHolder(registryName = "minecraft:potion") |
| public static final Potion levitation = null; // Annotation present. [public static] is required. [final] is optional. | | public static final Potion levitation = null; // Annotation present. [public static] is required. [final] is optional. |
− | // Potion has a corresponding registry: [Potion]. | + | // Registry name is explicitly defined: "minecraft:potion" |
− | // Name path is the value of the annotation: "levitation"
| + | // The entry's name value has not been specified on the field. |
− | // Namespace is not explicitly defined. | + | // Therefore, this will not compile. |
− | // No annotation in enclosing class.
| |
− | // Therefore, THIS WILL PRODUCE AN EXCEPTION. | |
| } | | } |
| </syntaxhighlight> | | </syntaxhighlight> |
Line 347: |
Line 225: |
| Creating custom registries for your mod might be useful if you want other mods to add new things to your system. For example, you might have magic spells and want to allow other mods to add new spells. For this you will want to make a registry (eg. "mymagicmod:spells"). This way, other mods will be able to register things to that list, and you won't have to do anything else. | | Creating custom registries for your mod might be useful if you want other mods to add new things to your system. For example, you might have magic spells and want to allow other mods to add new spells. For this you will want to make a registry (eg. "mymagicmod:spells"). This way, other mods will be able to register things to that list, and you won't have to do anything else. |
| | | |
− | Just like with registering a new item or block you have two ways of making a new registry. Each method takes in a <code>RegistryBuilder</code> which is used to build an <code>IForgeRegistry</code> for an object class that implements <code>IForgeRegistryEntry</code>. Each builder should have its name and type set via <code>#setName</code> and <code>#setType</code> respectively before being created. | + | Just like with registering a new item or block you have two ways of making a new registry. Each method takes in a <code>RegistryBuilder</code> which is used to build an <code>IForgeRegistry</code>. Each builder should have its name set via <code>#setName</code> before being created. |
− | | |
− | For the class that implements <code>IForgeRegistryEntry</code>, it is recommended in most cases to extend the default implementation of <code>ForgeRegistryEntry</code>. For interfaces, it should extend <code>IForgeRegistryEntry</code> with its implementations extending <code>ForgeRegistryEntry</code>.
| |
| | | |
| === With DeferredRegister === | | === With DeferredRegister === |
| | | |
− | The first method involves the second static constructor: <code>DeferredRegister::create(Class, String)</code>. The class supplied must extend <code>IForgeRegistryEntry</code>. From there, we can construct the registry using <code>#makeRegistry</code>. This will already populate <code>#setName</code> and <code>#setType</code> for us. This method also returns a supplier of the registry which we can use after the <code>RegistryEvent$NewRegistry</code> event. | + | The first method involves the second static constructor: <code>DeferredRegister#create(ResourceLocation, String)</code>. From there, we can construct the registry using <code>#makeRegistry</code>. This will already populate <code>#setName</code> for us. This method also returns a supplier of the registry which we can use after the <code>NewRegistryEvent</code> is called. |
| | | |
| Here is an example: | | Here is an example: |
| | | |
| {{Template:Tabs/Code_Snippets | | {{Template:Tabs/Code_Snippets |
− | |java=public static final DeferredRegister<ExampleRegistry> EXAMPLE = DeferredRegister.create(ExampleRegistry.class, MODID); | + | |java=public static final DeferredRegister<ExampleRegistry> EXAMPLE = DeferredRegister.create(new ResourceLocation(MODID, "example_registry"), MODID); |
| | | |
− | public static final Supplier<IForgeRegistry<ExampleRegistry>> REGISTRY = EXAMPLE.makeRegistry("example_registry", RegistryBuilder::new); | + | public static final Supplier<IForgeRegistry<ExampleRegistry>> REGISTRY = EXAMPLE.makeRegistry(RegistryBuilder::new); |
− | |kotlin=val EXAMPLE: DeferredRegister<ExampleRegistry> = DeferredRegister.create(ExampleRegistry::class.java, MODID) | + | |kotlin=val EXAMPLE: DeferredRegister<ExampleRegistry> = DeferredRegister.create(ResourceLocation(MODID, "example_registry"), MODID) |
| | | |
− | val REGISTRY: IForgeRegistry<ExampleRegistry> by lazy { | + | val REGISTRY: IForgeRegistry<ExampleRegistry> by EXAMPLE.makeRegistry(::RegistryBuilder).let { |
− | EXAMPLE.makeRegistry("example_registry", ::RegistryBuilder).get()
| + | lazy { |
| + | it.get() |
| + | } |
| } | | } |
− | |scala=final val EXAMPLE = DeferredRegister.create(classOf[ExampleRegistry], MODID) | + | |scala=final val EXAMPLE = DeferredRegister.create(new ResourceLocation(MODID, "example_registry"), MODID) |
| | | |
− | final lazy val REGISTRY = EXAMPLE.makeRegistry("example_registry", () => new RegistryBuilder).get | + | private final val PRIVATE_REGISTRY = EXAMPLE.makeRegistry(() => new RegistryBuilder) |
| + | final lazy val REGISTRY = PRIVATE_REGISTRY.get |
| |}} | | |}} |
| | | |
− | === Using RegistryEvent$NewRegistry === | + | === Using <code>NewRegistryEvent</code> === |
| | | |
− | The second method can be done during the <code>RegistryEvent$NewRegistry</code> event. This will call a new instance of the builder directly. From there, the registry can be built and stored via <code>RegistryBuilder#create</code>. This will cause the registry to be registered to the <code>RegistryManager</code> and returned to the caller for additional processing. | + | The second method can be done during the <code>NewRegistryEvent</code> event. Using <code>NewRegistryEvent#create</code>, you can pass in a <code>RegistryBuilder</code> directly. This method will return a <code>Supplier<IForgeRegistry<V>></code> that can be stored and queried after the event is fired to gain access to your <code>IForgeRegistry</code> instance. |
| | | |
| Here is an example: (the event handler is registered on the '''mod event bus''') | | Here is an example: (the event handler is registered on the '''mod event bus''') |
| | | |
| <syntaxhighlight lang="Java"> | | <syntaxhighlight lang="Java"> |
− | public static IForgeRegistry<ExampleRegistry> registry = null; | + | public static Supplier<IForgeRegistry<ExampleRegistry>> registrySupplier = null; |
| | | |
| @SubscribeEvent | | @SubscribeEvent |
− | public void onNewRegistry(RegistryEvent.NewRegistry event){ | + | public void onNewRegistry(NewRegistryEvent event){ |
| RegistryBuilder<ExampleRegistry> registryBuilder = new RegistryBuilder<>(); | | RegistryBuilder<ExampleRegistry> registryBuilder = new RegistryBuilder<>(); |
| registryBuilder.setName(new ResourceLocation(MODID, "example_registry"); | | registryBuilder.setName(new ResourceLocation(MODID, "example_registry"); |
− | registryBuilder.setType(ExampleRegistry.class); | + | registrySupplier = event.create(registryBuilder); |
− | registry = registryBuilder.create();
| |
| } | | } |
| </syntaxhighlight> | | </syntaxhighlight> |
Line 391: |
Line 269: |
| == Handling Missing Entries == | | == Handling Missing Entries == |
| | | |
− | When loading a pre-existing world after removing mods or updating versions, there are cases where certain registry objects will cease to exist. In these cases, it is possible to specify actions to remove a mapping, prevent the world from loading, or remap the name as needed. This can be done through the third of the registry events: <code>RegistryEvent$MissingMappings<T></code>, where the type parameter <code>T</code> is the object type being registered. Within the event, you can grab an immutable list of missing mappings associated with a mod id via <code>#getMappings</code> or a list of all mappings via <code>#getAllMappings</code>. | + | When loading a pre-existing world after removing mods or updating versions, there are cases where certain registry objects will cease to exist. In these cases, it is possible to specify actions to remove a mapping, prevent the world from loading, or remap the name as needed. This can be done through the third of the registry events: <code>MissingMappingsEvent</code>. Within the event, you can grab an immutable list of missing mappings associated with a mod id for a given registry via <code>#getMappings</code> or a list of all mappings via <code>#getAllMappings</code>. |
| | | |
| For each <code>Mapping</code>, you can either execute one of the following methods: | | For each <code>Mapping</code>, you can either execute one of the following methods: |
Line 401: |
Line 279: |
| If none of the above are specified, then the default action of notifying the user about the missing mappings occur. | | If none of the above are specified, then the default action of notifying the user about the missing mappings occur. |
| | | |
− | Here is an example: (the event handler is registered on the '''mod event bus''') | + | Here is an example: (the event handler is registered on the '''forge event bus''') |
| | | |
− | <syntaxhighlight lang="Java">
| + | {{Template:Tabs/Code_Snippets |
− | // This will ignore any missing test items from the specified world | + | |java=// This will ignore any missing test items from the specified world |
| @SubscribeEvent | | @SubscribeEvent |
− | public void onMissingItems(RegistryEvent.MissingMappings<Item> event){ | + | public void onMissing(final MissingMappingsEvent event) { |
− | event.getMappings(MODID).stream() | + | event.getMappings(ForgeRegistries.Keys.ITEMS, MODID).stream() |
| .filter(mapping -> mapping.key.getPath().contains("test")) | | .filter(mapping -> mapping.key.getPath().contains("test")) |
| .forEach(Mapping::ignore); | | .forEach(Mapping::ignore); |
| } | | } |
− | </syntaxhighlight>
| + | |groovy=// This will ignore any missing test items from the specified world |
| + | @SubscribeEvent |
| + | void onMissing(final MissingMappingsEvent event) { |
| + | event.getMappings(ForgeRegistries.Keys.ITEMS, MODID).stream() |
| + | .filter(mapping -> mapping.key.path.contains("test")) |
| + | .forEach(Mapping::ignore); |
| + | } |
| + | |}} |
| | | |
| | | |
| [[Category:Common Concepts]] | | [[Category:Common Concepts]] |