### Server Data Generation Example: Recipes Source: https://docs.minecraftforge.net/en/1.20.x/datagen Example of registering a `RecipeProvider` to define crafting recipes. ```java public class MyRecipesProvider extends RecipeProvider { public MyRecipesProvider(PackOutput output, ExistingFileHelper existingFileHelper) { super(output, existingFileHelper); } @Override protected void buildRecipes(@NotNull RecipeOutput consumer) { // ... } } ``` -------------------------------- ### Client Assets Generation Example Source: https://docs.minecraftforge.net/en/1.20.x/datagen Example of registering a `BlockStateProvider` to generate blockstate JSONs and associated models. ```java public class MyBlockStates extends BlockStateProvider { public MyBlockStates(PackOutput output, ExistingFileHelper exFileHelper) { super(output, exFileHelper); } @Override protected void registerStatesAndModels(BlockStateProvider blockStateProvider) { // ... } } ``` -------------------------------- ### Batch Setup Method Source: https://docs.minecraftforge.net/en/1.20.x/misc/gametest Annotate methods with @BeforeBatch to execute setup logic before tests in a specified batch. Batch methods accept a ServerLevel parameter. ```java public class ExampleGameTests { @BeforeBatch(batch = "firstBatch") public static void beforeTest(ServerLevel level) { // Perform setup } @GameTest(batch = "firstBatch") public static void exampleTest2(GameTestHelper helper) { // Do stuff } } ``` -------------------------------- ### Top-Level Package Examples Source: https://docs.minecraftforge.net/en/1.20.x/gettingstarted/structuring Provides examples of suitable top-level package structures based on different ownership identifiers. ```text Type | Value | Top-Level Package ---|---|--- Domain | example.com | `com.example` Subdomain | example.github.io | `io.github.example` Email | example@gmail.com | `com.gmail.example` ``` -------------------------------- ### Server Data Generation Example: Tags Source: https://docs.minecraftforge.net/en/1.20.x/datagen Example of registering a `TagsProvider` to define item and block tags. ```java public class MyBlockTagsProvider extends BlockTagsProvider { public MyBlockTagsProvider(PackOutput output, ExistingFileHelper existingFileHelper) { super(output, existingFileHelper); } @Override protected void addTags(TagKey pTag) { // ... } } ``` -------------------------------- ### comapFlatMap Example Outputs Source: https://docs.minecraftforge.net/en/1.20.x/datastorage/codecs Illustrates the results of the `INT_CODEC` transformation, showing a successful conversion and an error case. ```plaintext // Will return 5 "5" // Will error, not an integer "value" ``` -------------------------------- ### Example Loot Pool Naming Source: https://docs.minecraftforge.net/en/1.20.x/resources/server/loottables Demonstrates how to name a loot pool using the 'name' key in JSON. ```json { "name": "example_pool", "rolls": { // ... }, "entries": { // ... } } ``` -------------------------------- ### Example Recipe Record Source: https://docs.minecraftforge.net/en/1.20.x/resources/server/recipes/custom A basic record implementation of the Recipe interface for custom recipe data and logic. Ensure all required methods are implemented. ```java public record ExampleRecipe(Ingredient input, int data, ItemStack output) implements Recipe { // Implement methods here } ``` -------------------------------- ### Range Codec Example Outputs Source: https://docs.minecraftforge.net/en/1.20.x/datastorage/codecs Demonstrates the behavior of the `RANGE_CODEC` with values inside and outside the specified range. ```plaintext // Will be valid, inside [0, 4] 4 // Will error, outside [0, 4] 5 ``` -------------------------------- ### Origin Specification Examples Source: https://docs.minecraftforge.net/en/1.20.x/rendering/modelextensions/transforms Demonstrates different ways to specify the origin for transformations, including default values and custom vectors. ```json { "origin": [ 0.1, 0.2, 0.3 ] } ``` ```json { "origin": "corner" } ``` ```json { "origin": "center" } ``` ```json { "origin": "opposing-corner" } ``` -------------------------------- ### Create Example Trigger Instance Source: https://docs.minecraftforge.net/en/1.20.x/resources/server/advancements Implement the `createInstance` method to read trigger criteria from JSON and create a new trigger instance. ```java @Override public ExampleTriggerInstance createInstance(JsonObject json, ContextAwarePredicate player, DeserializationContext context) { // Read conditions from JSON: item return new ExampleTriggerInstance(player, item); } ``` -------------------------------- ### Package Naming Conflict Example Source: https://docs.minecraftforge.net/en/1.20.x/gettingstarted/structuring Illustrates how duplicate package names in different JARs can lead to class loading issues. ```text a.jar - com.example.ExampleClass b.jar - com.example.ExampleClass // This class will not normally be loaded ``` -------------------------------- ### Can Tool Perform Action Condition Example Source: https://docs.minecraftforge.net/en/1.20.x/resources/server/loottables Illustrates the 'forge:can_tool_perform_action' condition to check tool capabilities. ```json { "conditions": [ { "condition": "forge:can_tool_perform_action", "action": "axe_strip" } ] } ``` -------------------------------- ### KeyMapping for GUI Context Source: https://docs.minecraftforge.net/en/1.20.x/misc/keymappings Create a KeyMapping that is only active when a GUI screen is open. This example uses a mouse input (left click) and a custom category. ```java new KeyMapping( "key.examplemod.example2", KeyConflictContext.GUI, // Mapping can only be used when a screen is open InputConstants.Type.MOUSE, // Default mapping is on the mouse GLFW.GLFW_MOUSE_BUTTON_LEFT, // Default mouse input is the left mouse button "key.categories.examplemod.examplecategory" // Mapping will be in the new example category ) ``` -------------------------------- ### Providing Known Blocks to BlockLootSubProvider Source: https://docs.minecraftforge.net/en/1.20.x/datagen/server/loottables This example demonstrates how to supply all registered block entries to the `getKnownBlocks` method of a BlockLootSubProvider, ensuring each block has a loot table. ```java // In some BlockLootSubProvider subclass for some DeferredRegister BLOCK_REGISTRAR @Override protected Iterable getKnownBlocks() { return BLOCK_REGISTRAR.getEntries() // Get all registered entries .stream() // Stream the wrapped objects .flatMap(RegistryObject::stream) // Get the object if available ::iterator; // Create the iterable } ``` -------------------------------- ### Class Naming Convention Examples Source: https://docs.minecraftforge.net/en/1.20.x/gettingstarted/structuring Shows common suffixes used for different types of classes to improve readability and identification. ```text An `Item` called `PowerRing` -> `PowerRingItem`. * A `Block` called `NotDirt` -> `NotDirtBlock`. * A menu for an `Oven` -> `OvenMenu`. ``` -------------------------------- ### Create Recipe Type Tag Provider Source: https://docs.minecraftforge.net/en/1.20.x/datagen/server/tags Example of a constructor for a `RecipeTypeTagsProvider` which extends `TagsProvider` to generate tags for recipe types. ```java public RecipeTypeTagsProvider(PackOutput output, CompletableFuture registries, ExistingFileHelper fileHelper) { super(output, Registries.RECIPE_TYPE, registries, MOD_ID, fileHelper); } ``` -------------------------------- ### EntityLootSubProvider Constructor Example Source: https://docs.minecraftforge.net/en/1.20.x/datagen/server/loottables Shows the constructor for an EntityLootSubProvider, which takes a feature flag set to determine if loot tables for entities should be generated. ```java // In some EntityLootSubProvider subclass public MyEntityLootSubProvider() { super(FeatureFlags.REGISTRY.allFlags()); } ``` -------------------------------- ### BlockLootSubProvider Constructor Example Source: https://docs.minecraftforge.net/en/1.20.x/datagen/server/loottables Illustrates the constructor for a BlockLootSubProvider, which requires a set of explosion-resistant blocks and a feature flag set to determine generation conditions. ```java // In some BlockLootSubProvider subclass public MyBlockLootSubProvider() { super(Collections.emptySet(), FeatureFlags.REGISTRY.allFlags()); } ``` -------------------------------- ### Building an Advancement with Advancement$Builder Source: https://docs.minecraftforge.net/en/1.20.x/datagen/server/advancements This example shows how to use `Advancement$Builder` to create a new advancement. It demonstrates adding a criterion, saving the advancement using the writer and file helper, and assigning a name. ```java // In some ForgeAdvancementProvider$AdvancementGenerator#generate(registries, writer, existingFileHelper) Advancement example = Advancement.Builder.advancement() .addCriterion("example_criterion", triggerInstance) // How the advancement is unlocked .save(writer, name, existingFileHelper); // Add data to builder ``` -------------------------------- ### Unit Codec Example Source: https://docs.minecraftforge.net/en/1.20.x/datastorage/codecs Creates a codec that supplies an in-code value and encodes to nothing. Useful for codecs that use non-encodable entries. ```java public static final Codec> UNIT_CODEC = Codec.unit( () -> ForgeRegistries.BLOCKS // Can also be a raw value ); ``` -------------------------------- ### Example sounds.json Structure Source: https://docs.minecraftforge.net/en/1.20.x/gameeffects/sounds This JSON defines sound events, their subtitles, and the associated sound files. It demonstrates how to specify simple sound files and streamed music files. ```json { "open_chest": { "subtitle": "mymod.subtitle.open_chest", "sounds": [ "mymod:open_chest_sound_file" ] }, "epic_music": { "sounds": [ { "name": "mymod:music/epic_music", "stream": true } ] } } ``` -------------------------------- ### Example mods.toml Configuration Source: https://docs.minecraftforge.net/en/1.20.x/gettingstarted/modfiles This TOML file defines the metadata for a mod, including its ID, version, display information, and dependencies on Forge and Minecraft. It specifies how the mod should be loaded and provides URLs for updates and issue tracking. ```toml modLoader="javafml" loaderVersion="[46,)" license="All Rights Reserved" issueTrackerURL="https://github.com/MinecraftForge/MinecraftForge/issues" showAsResourcePack=false [[mods]] modId="examplemod" version="1.0.0.0" displayName="Example Mod" updateJSONURL="https://files.minecraftforge.net/net/minecraftforge/forge/promotions_slim.json" displayURL="https://minecraftforge.net" logoFile="logo.png" credits="I'd like to thank my mother and father." authors="Author" description=''' Lets you craft dirt into diamonds. This is a traditional mod that has existed for eons. It is ancient. The holy Notch created it. Jeb rainbowfied it. Dinnerbone made it upside down. Etc. ''' displayTest="MATCH_VERSION" [[dependencies.examplemod]] modId="forge" mandatory=true versionRange="[46,)" ordering="NONE" side="BOTH" [[dependencies.examplemod]] modId="minecraft" mandatory=true versionRange="[1.20]" ordering="NONE" side="BOTH" ``` -------------------------------- ### Example Language File Structure Source: https://docs.minecraftforge.net/en/1.20.x/concepts/internationalization Defines translation keys and their corresponding displayable text for a specific locale. This JSON file should be placed in the assets/[namespace]/lang/[locale].json directory. ```json { "item.examplemod.example_item": "Example Item Name", "block.examplemod.example_block": "Example Block Name", "commands.examplemod.examplecommand.error": "Example Command Errored!" } ``` -------------------------------- ### Get Recipe Using RecipeWrapper Source: https://docs.minecraftforge.net/en/1.20.x/resources/server/recipes Demonstrates how to retrieve a recipe using the RecipeManager with a RecipeWrapper, which is useful when working with IItemHandler instances. This is typically done within a method that has access to an IItemHandlerModifiable. ```java // Within some method with IItemHandlerModifiable handler recipeManger.getRecipeFor(RecipeType.CRAFTING, new RecipeWrapper(handler), level); ``` -------------------------------- ### Define a Basic Config Value Source: https://docs.minecraftforge.net/en/1.20.x/misc/config Shows how to define a simple configuration value with a comment and a default value using `ForgeConfigSpec.Builder`. The value can be retrieved using `#get` and is cached. ```java // For some ForgeConfigSpec$Builder builder ConfigValue value = builder.comment("Comment") .define("config_value_name", defaultValue); ``` -------------------------------- ### Create a Custom Creative Tab Source: https://docs.minecraftforge.net/en/1.20.x/items Define and register a new custom creative mode tab. This example demonstrates setting the tab's title, icon, and default items. ```java // Assume we have a DeferredRegister called REGISTRAR // Assume we have RegistryObject and RegistryObject called ITEM and BLOCK public static final RegistryObject EXAMPLE_TAB = REGISTRAR.register("example", () -> CreativeModeTab.builder() // Set name of tab to display .title(Component.translatable("item_group." + MOD_ID + ".example")) // Set icon of creative tab .icon(() -> new ItemStack(ITEM.get())) // Add default items to tab .displayItems((params, output) -> { output.accept(ITEM.get()); output.accept(BLOCK.get()); }) .build() ); ``` -------------------------------- ### Item Translation Key Example Source: https://docs.minecraftforge.net/en/1.20.x/concepts/internationalization Illustrates how an item's translation key is derived from its registry name. This key is then used in language files to provide the display name. ```json { "item.examplemod.example_item": "Example Item Name" } ``` -------------------------------- ### Registering a Custom Block with DeferredRegister Source: https://docs.minecraftforge.net/en/1.20.x/concepts/registries Use `DeferredRegister` to manage the registration of custom blocks. This example shows how to create a `DeferredRegister` for blocks and register a new block with a specific name and properties. ```java private static final DeferredRegister BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, MODID); public static final RegistryObject ROCK_BLOCK = BLOCKS.register("rock", () -> new Block(BlockBehaviour.Properties.of().mapColor(MapColor.STONE))); public ExampleMod() { BLOCKS.register(FMLJavaModLoadingContext.get().getModEventBus()); } ``` -------------------------------- ### Create and Configure ExampleConfig Source: https://docs.minecraftforge.net/en/1.20.x/misc/config Demonstrates how to use `ForgeConfigSpec.Builder.configure` with a static block and a custom config class to create and hold configuration values. ```java class ExampleConfig { ExampleConfig(ForgeConfigSpec.Builder builder) { // Define values here in final fields } } static { Pair pair = new ForgeConfigSpec.Builder() .configure(ExampleConfig::new); // Store pair values in some constant field } ``` -------------------------------- ### Adding a Global Loot Modifier with Conditions Source: https://docs.minecraftforge.net/en/1.20.x/datagen/server/glm This snippet demonstrates how to add a custom Global Loot Modifier within the `start` method of a `GlobalLootModifierProvider`. It includes an example of a loot item condition (weather check) and specifies item, count, and the item itself. ```java import net.minecraft.world.item.Items; import net.minecraft.world.level.storage.loot.predicates.LootItemCondition; import net.minecraft.world.level.storage.loot.predicates.LootItemConditions; import net.minecraft.world.level.storage.loot.predicates.WeatherCheck; // Assuming ExampleModifier is a custom GlobalLootModifier subclass // In some GlobalLootModifierProvider#start this.add("example_modifier", new ExampleModifier( new LootItemCondition[] { WeatherCheck.weather().setRaining(true).build() // Executes when raining }, "val1", 10, Items.DIRT )); ``` -------------------------------- ### Legacy Block Metadata Example Source: https://docs.minecraftforge.net/en/1.20.x/blocks/states Illustrates the use of metadata in Minecraft versions prior to 1.8 to represent block states like orientation and position. This system was confusing as metadata values lacked inherent meaning. ```java switch (meta) { case 0: { ... } // south and on the lower half of the block case 1: { ... } // south on the upper side of the block case 2: { ... } // north and on the lower half of the block case 3: { ... } // north and on the upper half of the block // ... etc. ... } ``` -------------------------------- ### Example Tag JSON Structure Source: https://docs.minecraftforge.net/en/1.20.x/resources/server/tags This JSON structure demonstrates how to define values for a tag, including optional entries that are not required to exist. This is useful for referencing items or blocks from other mods without causing errors if they are not present. ```json { "replace": false, "values": [ "minecraft:gold_ingot", "mymod:my_ingot", { "id": "othermod:ingot_other", "required": false } ] } ``` -------------------------------- ### ExampleModelProvider Constructor Source: https://docs.minecraftforge.net/en/1.20.x/datagen/client/modelproviders Defines the subdirectory for model generation and the ModelBuilder to use. Models are generated to assets//models/example by default. ```java public class ExampleModelProvider extends ModelProvider { public ExampleModelProvider(PackOutput output, String modid, ExistingFileHelper existingFileHelper) { // Models will be generated to 'assets//models/example' if no 'modid' is specified in '#getBuilder' super(output, modid, "example", ExampleModelBuilder::new, existingFileHelper); } } ``` -------------------------------- ### Scale Specification Source: https://docs.minecraftforge.net/en/1.20.x/rendering/modelextensions/transforms Example of specifying a scale vector for a root transform. ```json { "scale": [ 1.5, 1.5, 1.5 ] } ``` -------------------------------- ### Translation Specification Source: https://docs.minecraftforge.net/en/1.20.x/rendering/modelextensions/transforms Example of specifying a relative translation vector for a root transform. ```json { "translation": [ 0.1, 0.2, 0.3 ] } ``` -------------------------------- ### Initialize RegistrySetBuilder and Add Registries Source: https://docs.minecraftforge.net/en/1.20.x/datagen/server/datapackregistries Demonstrates how to initialize a `RegistrySetBuilder` and use its `add` method to define registration logic for specific registries. This example shows adding entries for `Registries.CONFIGURED_FEATURE` and `Registries.PLACED_FEATURE`, with placeholders for the actual registration code. ```java new RegistrySetBuilder() // Create configured features .add(Registries.CONFIGURED_FEATURE, bootstrap -> { // Register configured features here }) // Create placed features .add(Registries.PLACED_FEATURE, bootstrap -> { // Register placed features here }); ``` -------------------------------- ### Creating a Basic KeyMapping Source: https://docs.minecraftforge.net/en/1.20.x/misc/keymappings Create a KeyMapping with a translation key for its name, a default keyboard input (P key), and a category. ```java new KeyMapping( "key.examplemod.example1", // Will be localized using this translation key InputConstants.Type.KEYSYM, // Default mapping is on the keyboard GLFW.GLFW_KEY_P, // Default key is P "key.categories.misc" // Mapping will be in the misc category ) ``` -------------------------------- ### Menu with ItemStack and Integer Synchronization Source: https://docs.minecraftforge.net/en/1.20.x/gui/menus Example of a client and server menu constructor demonstrating the addition of slots for item stacks and data slots for integers. The client constructor assumes pre-existing data, while the server constructor shows how to add slots and data slots. ```java public MyMenuAccess(int containerId, Inventory playerInventory) { this(containerId, playerInventory, new ItemStackHandler(5), DataSlot.standalone()); } public MyMenuAccess(int containerId, Inventory playerInventory, IItemHandler dataInventory, DataSlot dataSingle) { this.addSlot(new SlotItemHandler(dataInventory, /*...*/)); this.addSlot(new Slot(playerInventory, /*...*/)); this.addDataSlot(dataSingle); // ... } ``` -------------------------------- ### Ambient Occlusion Override Example Source: https://docs.minecraftforge.net/en/1.20.x/rendering/modelextensions/facedata Demonstrates that an element-level 'ambient_occlusion: true' has no effect if the top-level AO flag is false. ```json { "ambientocclusion": false, "elements": [ { "forge_data": { "ambient_occlusion": true // Has no effect } } ] } ``` -------------------------------- ### Implementing a Basic LootTableSubProvider Source: https://docs.minecraftforge.net/en/1.20.x/datagen/server/loottables Demonstrates the basic structure of a LootTableSubProvider. The `generate` method is where loot tables are defined using a provided writer. ```java public class ExampleSubProvider implements LootTableSubProvider { // Used to create a factory method for the wrapping Supplier public ExampleSubProvider() {} // The method used to generate the loot tables @Override public void generate(BiConsumer writer) { // Generate loot tables here by calling writer#accept } } ``` -------------------------------- ### StrictNBTIngredient Example Source: https://docs.minecraftforge.net/en/1.20.x/resources/server/recipes/ingredients Use StrictNBTIngredient for exact item, damage, and share tag equivalency. Specify the type as 'forge:nbt'. ```json // For some input { "type": "forge:nbt", "item": "examplemod:example_item", "nbt": { // Add nbt data (must match exactly what is on the stack) } } ``` -------------------------------- ### Run Your Mod in a Test Server Source: https://docs.minecraftforge.net/en/1.20.x/gettingstarted This Gradle task launches a dedicated Minecraft server with your mod. The server will require the Minecraft EULA to be accepted in the 'eula.txt' file within the run directory. ```bash gradlew runServer ``` -------------------------------- ### Loot Table ID Condition Example Source: https://docs.minecraftforge.net/en/1.20.x/resources/server/loottables Shows how to use the 'forge:loot_table_id' condition to apply loot to specific tables. ```json { "conditions": [ { "condition": "forge:loot_table_id", "loot_table_id": "minecraft:blocks/dirt" } ] } ``` -------------------------------- ### Run Your Mod in a Test Client Source: https://docs.minecraftforge.net/en/1.20.x/gettingstarted Use this Gradle task to launch Minecraft with your mod applied. It utilizes the default 'run' directory and includes the 'main' source set. ```bash gradlew runClient ``` -------------------------------- ### Encoded SomeObject Examples Source: https://docs.minecraftforge.net/en/1.20.x/datastorage/codecs Illustrates the JSON structure for encoded `SomeObject` instances, including cases where optional fields are omitted. ```json { "s": "value", "i": 5, "b": false } // Another encoded SomeObject { "s": "value2", // i is omitted, defaults to 0 "b": true } ``` -------------------------------- ### Initializing Screen Widgets Source: https://docs.minecraftforge.net/en/1.20.x/gui/screens The init method is used to set up widgets and precompute values. It's called on initialization and window resize. Use addRenderableWidget for interactable, narrated, and rendered widgets. ```java // In some Screen subclass @Override protected void init() { super.init(); // Add widgets and precomputed values this.addRenderableWidget(new EditBox(/* ... */)); } ``` -------------------------------- ### Creating a Custom Loader Builder Source: https://docs.minecraftforge.net/en/1.20.x/datagen/client/modelproviders Shows how to create a custom loader builder by extending CustomLoaderBuilder. This includes a static factory method 'begin' and a protected constructor. ```java public class ExampleLoaderBuilder> extends CustomLoaderBuilder { public static > ExampleLoaderBuilder begin(T parent, ExistingFileHelper existingFileHelper) { return new ExampleLoaderBuilder<>(parent, existingFileHelper); } protected ExampleLoaderBuilder(T parent, ExistingFileHelper existingFileHelper) { super(new ResourceLocation(MOD_ID, "example_loader"), parent, existingFileHelper); } } ``` -------------------------------- ### Build Your Mod with Gradle Source: https://docs.minecraftforge.net/en/1.20.x/gettingstarted Run this command to compile your mod and create a JAR file in the build/libs directory. This JAR can then be placed in your Minecraft mods folder. ```bash gradlew build ``` -------------------------------- ### CompoundIngredient Example Source: https://docs.minecraftforge.net/en/1.20.x/resources/server/recipes/ingredients Use CompoundIngredient when a stack must match at least one of the provided ingredients. No specific type needs to be declared. ```json // For some input [ // At least one of these ingredients must match to succeed { // Ingredient }, { // Custom ingredient "type": "examplemod:example_ingredient" } ] ``` -------------------------------- ### Registering Configured and Placed Features Source: https://docs.minecraftforge.net/en/1.20.x/datagen/server/datapackregistries Demonstrates registering configured and placed features using the BootstrapContext. This is useful for defining custom world generation elements. ```java public static final ResourceKey> EXAMPLE_CONFIGURED_FEATURE = ResourceKey.create( Registries.CONFIGURED_FEATURE, new ResourceLocation(MOD_ID, "example_configured_feature") ); // In some constant location or argument new RegistrySetBuilder() // Create configured features .add(Registries.CONFIGURED_FEATURE, bootstrap -> { // Register configured features here bootstrap.register( // The resource key for the configured feature EXAMPLE_CONFIGURED_FEATURE, new ConfiguredFeature( Feature.ORE, // Create an ore feature new OreConfiguration( List.of(), // Does nothing 8 // in veins of at most 8 ) ) ); }) // Create placed features .add(Registries.PLACED_FEATURE, bootstrap -> { // Register placed features here }); ``` -------------------------------- ### Example GLM JSON Configuration Source: https://docs.minecraftforge.net/en/1.20.x/resources/server/glm This JSON defines a Global Loot Modifier, specifying its type, conditions for activation, and custom properties. ```json { "type": "examplemod:example_loot_modifier", "conditions": [ // Normal loot table conditions // ... ], "prop1": "val1", "prop2": 10, "prop3": "minecraft:dirt" } ``` -------------------------------- ### Create a SimpleChannel Instance Source: https://docs.minecraftforge.net/en/1.20.x/networking/simpleimpl Instantiate a SimpleChannel for custom packet handling. Ensure the protocol version and compatibility checkers are correctly defined. ```java private static final String PROTOCOL_VERSION = "1"; public static final SimpleChannel INSTANCE = NetworkRegistry.newSimpleChannel( new ResourceLocation("mymodid", "main"), () -> PROTOCOL_VERSION, PROTOCOL_VERSION::equals, PROTOCOL_VERSION::equals ); ``` -------------------------------- ### KeyMapping with Shift Modifier Source: https://docs.minecraftforge.net/en/1.20.x/misc/keymappings Create a KeyMapping that requires the Shift key to be held down. This example maps the G key in the misc category. ```java new KeyMapping( "key.examplemod.example3", KeyConflictContext.UNIVERSAL, KeyModifier.SHIFT, // Default mapping requires shift to be held down InputConstants.Type.KEYSYM, // Default mapping is on the keyboard GLFW.GLFW_KEY_G, // Default key is G "key.categories.misc" ) ``` -------------------------------- ### Module Package Export Conflict Example Source: https://docs.minecraftforge.net/en/1.20.x/gettingstarted/structuring Demonstrates how exporting the same package name from different modules can cause the mod loader to crash. ```text module A - package X - class I - class J module B - package X // This package will cause the mod loader to crash, as there already is a module with package X being exported - class R - class S - class T ``` -------------------------------- ### ExampleModelConsumerProvider Constructor Source: https://docs.minecraftforge.net/en/1.20.x/datagen/client/modelproviders Initializes a custom model consumer provider, making a ModelProvider available for generating models. ```java public class ExampleModelConsumerProvider implements IDataProvider { public ExampleModelConsumerProvider(PackOutput output, String modid, ExistingFileHelper existingFileHelper) { this.example = new ExampleModelProvider(output, modid, existingFileHelper); } } ``` -------------------------------- ### Synchronizing on Block Update Source: https://docs.minecraftforge.net/en/1.20.x/blockentities Example implementation for synchronizing block entity data on block updates. Requires overriding `getUpdateTag` and `getUpdatePacket`. ```java @Override public CompoundTag getUpdateTag() { CompoundTag tag = new CompoundTag(); //Write your data into the tag return tag; } @Override public Packet getUpdatePacket() { // Will get tag from #getUpdateTag return ClientboundBlockEntityDataPacket.create(this); } // Can override IForgeBlockEntity#onDataPacket. By default, this will defer to the #load. ``` -------------------------------- ### Get Item Handler Capability Instance Source: https://docs.minecraftforge.net/en/1.20.x/datastorage/capabilities Retrieves the unique instance for the IItemHandler capability. This is primarily used to reference the capability for querying. ```java public static final Capability ITEM_HANDLER = CapabilityManager.get(new CapabilityToken<>(){}); ``` -------------------------------- ### Advancement Rewards Configuration Source: https://docs.minecraftforge.net/en/1.20.x/resources/server/advancements Example JSON structure for defining rewards in an advancement. This includes experience, loot tables, recipes, and a function to be executed. ```json // In some advancement JSON "rewards": { "experience": 10, "loot": [ "minecraft:example_loot_table", "minecraft:example_loot_table2" // ... ], "recipes": [ "minecraft:example_recipe", "minecraft:example_recipe2" // ... ], "function": "minecraft:example_function" } ``` -------------------------------- ### PartialNBTIngredient Example Source: https://docs.minecraftforge.net/en/1.20.x/resources/server/recipes/ingredients Use PartialNBTIngredient for a looser NBT comparison, checking only specified keys in the share tag. Specify the type as 'forge:partial_nbt'. ```json // For some input { "type": "forge:partial_nbt", // Either 'item' or 'items' must be specified // If both are specified, only 'item' will be read "item": "examplemod:example_item", "items": [ "examplemod:example_item", "examplemod:example_item2" // ... ], "nbt": { // Checks only for equivalency on 'key1' and 'key2' // All other keys in the stack will not be checked "key1": "data1", "key2": { // Data 2 } } } ``` -------------------------------- ### Creating a Dispatch Codec from a Registry Source: https://docs.minecraftforge.net/en/1.20.x/datastorage/codecs Shows how to create a dispatch codec using a registry of codecs. It dispatches based on the object's type method and then uses the codec obtained from the registry. ```java public static final Codec = DISPATCH.getCodec() .dispatch( ExampleObject::type, Function.identity() ); ``` -------------------------------- ### Registering a Custom Condition Serializer Source: https://docs.minecraftforge.net/en/1.20.x/resources/server/conditional Example of how to register a custom condition serializer instance. Registration can occur during the RecipeSerializer registration event or the FMLCommonSetupEvent. ```java public static final ExampleConditionSerializer INSTANCE = new ExampleConditionSerializer(); public void registerSerializers(RegisterEvent event) { event.register(ForgeRegistries.Keys.RECIPE_SERIALIZERS, helper -> CraftingHelper.register(INSTANCE) ); } ``` -------------------------------- ### AbstractContainerScreen Constructor Source: https://docs.minecraftforge.net/en/1.20.x/gui/screens Example of initializing an AbstractContainerScreen subclass. Sets relative positions for the title and inventory labels. Note that inventoryLabelY depends on imageHeight. ```java public MyContainerScreen(MyMenu menu, Inventory playerInventory, Component title) { super(menu, playerInventory, title); this.titleLabelX = 10; this.inventoryLabelX = 10; /* * If the 'imageHeight' is changed, 'inventoryLabelY' must also be * changed as the value depends on the 'imageHeight' value. */ } ``` -------------------------------- ### Adding Chainable Configuration Methods Source: https://docs.minecraftforge.net/en/1.20.x/datagen/client/modelproviders Illustrates how to add chainable configuration methods to a custom loader builder for specifying loader properties. ```java // In ExampleLoaderBuilder public ExampleLoaderBuilder exampleInt(int example) { // Set int return this; } public ExampleLoaderBuilder exampleString(String example) { // Set string return this; } ``` -------------------------------- ### Creating a Cooking Recipe with SimpleCookingRecipeBuilder Source: https://docs.minecraftforge.net/en/1.20.x/datagen/server/recipes Use `SimpleCookingRecipeBuilder` for smelting, blasting, smoking, and campfire cooking recipes. Specify input, output, experience, cooking time, and unlock criteria. ```java // In RecipeProvider#buildRecipes(writer) SimpleCookingRecipeBuilder builder = SimpleCookingRecipeBuilder.smelting(input, RecipeCategory.MISC, result, experience, cookingTime) .unlockedBy("criteria", criteria) // How the recipe is unlocked .save(writer); // Add data to builder ``` -------------------------------- ### Registering a Custom Ingredient Serializer Source: https://docs.minecraftforge.net/en/1.20.x/resources/server/recipes/ingredients Example of how to declare a static instance of your custom ingredient serializer and register it using CraftingHelper. This is typically done during the FMLCommonSetupEvent. ```java // In some serializer class public static final ExampleIngredientSerializer INSTANCE = new ExampleIngredientSerializer(); // In some handler class public void registerSerializers(RegisterEvent event) { event.register(ForgeRegistries.Keys.RECIPE_SERIALIZERS, helper -> CraftingHelper.register(registryName, INSTANCE) ); } // In some ingredient subclass @Override public IIngredientSerializer getSerializer() { return INSTANCE; } ``` -------------------------------- ### Dispatch Codec Data Structures Source: https://docs.minecraftforge.net/en/1.20.x/datastorage/codecs Provides examples of how data is structured when encoded using dispatch codecs. The 'value' key is used when the codec is not a MapCodec. ```json // Simple object { "type": "string", "value": "value" } ``` ```json // Complex object { "type": "complex", "s": "value", "i": 0 } ``` -------------------------------- ### Retrieving and Matching Custom Recipes Source: https://docs.minecraftforge.net/en/1.20.x/resources/server/recipes/custom Demonstrates how to retrieve all recipes for a specific type and then filter them based on custom matching logic. This is useful for non-item-based recipes. ```java // In some manager class public Optional getRecipeFor(Level level, BlockPos pos) { return level.getRecipeManager() .getAllRecipesFor(exampleRecipeType) // Gets all recipes .stream() // Looks through all recipes for types .filter(recipe -> recipe.matches(level, pos)) // Checks if the recipe inputs are valid .findFirst(); // Finds the first recipe whose inputs match } ```