### Run Minecraft Forge Mod Server with Gradle Source: https://docs.minecraftforge.net/en/1.18.x/gettingstarted Starts a dedicated Minecraft server with the mod. After the initial run, the server requires the Minecraft EULA to be accepted by editing the `run/eula.txt` file. ```bash gradlew runServer ``` -------------------------------- ### Run Gradle setup task in IntelliJ IDEA Source: https://docs.minecraftforge.net/en/1.18.x/forgedev Executes the Gradle 'setup' task to configure the Forge project within IntelliJ IDEA. This is a crucial step after importing the project to ensure all dependencies and configurations are correctly set up. ```IDEAction Open Gradle sidebar -> forge project tree -> Tasks -> other -> double-click `setup` task ``` ```KeyboardShortcut Press CTRL twice, type `gradle setup` in the Run command window ``` -------------------------------- ### Setup Eclipse Development Environment for Forge Source: https://docs.minecraftforge.net/en/1.18.x/forgedev These commands set up your cloned Forge repository for use with Eclipse. The first command (`./gradlew setup`) configures the project with ForgeGradle, and the second (`./gradlew genEclipseRuns`) generates necessary run configurations for Eclipse. ```bash ./gradlew setup ./gradlew genEclipseRuns ``` -------------------------------- ### Build Minecraft Forge Mod with Gradle Source: https://docs.minecraftforge.net/en/1.18.x/gettingstarted Compiles the Minecraft Forge mod into a JAR file. The output JAR is located in the `build/libs` directory and can be used in a Minecraft Forge installation. ```bash gradlew build ``` -------------------------------- ### Clone Minecraft Forge Repository using Git Source: https://docs.minecraftforge.net/en/1.18.x/forgedev This command clones your forked Minecraft Forge repository to your local machine. Replace `` with your GitHub username. Ensure Git is installed and configured on your system. ```bash git clone https://github.com//MinecraftForge ``` -------------------------------- ### Run Minecraft Forge Mod Client with Gradle Source: https://docs.minecraftforge.net/en/1.18.x/gettingstarted Launches the Minecraft client with the mod integrated. This command uses the generated run configurations, typically applying code from the `src/main/java` source set. ```bash gradlew runClient ``` -------------------------------- ### Run Forge client using Gradle task Source: https://docs.minecraftforge.net/en/1.18.x/forgedev Launches the Forge client for development and testing using the `forge_client` Gradle task. This can be run or debugged directly from the IDE. ```IDEAction Open Gradle sidebar -> forge project tree -> Tasks -> fg_runs -> right-click `forge_client` task and select Run or Debug ``` -------------------------------- ### Generate IDE Launch Configurations (Gradle) Source: https://docs.minecraftforge.net/en/1.18.x/gettingstarted These Gradle tasks generate launch configurations and download necessary game assets for different IDEs. Ensure you have the Forge MDK extracted and are in the project directory. ```bash gradlew genEclipseRuns ``` ```bash gradlew genIntellijRuns ``` ```bash gradlew genVSCodeRuns ``` -------------------------------- ### Customize build.gradle for Mod Information Source: https://docs.minecraftforge.net/en/1.18.x/gettingstarted Modify these properties in the `build.gradle` file to customize your mod's build output, Maven coordinates, and version. Remember to refresh your Gradle project after making changes. ```gradle archivesBaseName = "yourmodname" group = "your.mod.id" version = "1.0.0" ``` -------------------------------- ### Build Forge test classes Source: https://docs.minecraftforge.net/en/1.18.x/forgedev Compiles the test classes for Forge mods. This is a prerequisite for enabling test mods in the development environment. ```IDEAction Select `src/main/test` directory -> File -> Build -> Build module 'Forge_test' ``` -------------------------------- ### Generate IntelliJ run configurations with Gradle Source: https://docs.minecraftforge.net/en/1.18.x/forgedev Generates specific run configurations for IntelliJ IDEA using the `genIntellijRuns` Gradle task. This allows for easier launching and debugging of Forge development. ```IDEAction Open Gradle sidebar -> forge project tree -> Tasks -> forgegradle runs -> double-click `genIntellijRuns` task ``` -------------------------------- ### Rebuild Project in IntelliJ IDEA Source: https://docs.minecraftforge.net/en/1.18.x/forgedev Rebuilds the entire project, which is necessary after making changes to test mod files to ensure they are recompiled and included in the classpath. ```IDEAction Build -> Rebuild project ``` ```KeyboardShortcut CTRL+F9 ``` -------------------------------- ### Update Forge licenses with Gradle task Source: https://docs.minecraftforge.net/en/1.18.x/forgedev Runs the `updateLicenses` Gradle task to resolve potential licensing errors during the build process. This is a troubleshooting step for build issues. ```IDEAction Open Gradle sidebar -> forge project tree -> Tasks -> other -> double-click `updateLicenses` task ``` -------------------------------- ### Batching Game Tests with Setup and Teardown (Java) Source: https://docs.minecraftforge.net/en/1.18.x/misc/gametest Demonstrates how to group game tests into batches for executing setup (@BeforeBatch) and teardown (@AfterBatch) logic. The batch methods must match the string supplied to the game test's batch attribute and accept a ServerLevel. ```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 } } ``` -------------------------------- ### Example Loot Table Builder - Java Source: https://docs.minecraftforge.net/en/1.18.x/datagen/server/loottables An example implementation of a loot table builder. It implements the Consumer interface to accept a writer for generating loot tables. ```java public class ExampleLoot implements Consumer> { // Used to create a factory method for the wrapping Supplier public ExampleLoot() {} // The method used to generate the loot tables @Override public void accept(BiConsumer writer) { // Generate loot tables here by calling writer#accept } } ``` -------------------------------- ### CompoundIngredient Example Source: https://docs.minecraftforge.net/en/1.18.x/resources/server/recipes/ingredients Demonstrates the structure of a CompoundIngredient, which acts as an OR condition for a list of ingredients. The input stack must match at least one of the provided ingredients. ```json // For some input [ // At least one of these ingredients must match to succeed { // Ingredient }, { // Custom ingredient "type": "examplemod:example_ingredient" } ] ``` -------------------------------- ### Access Transformer Syntax Examples Source: https://docs.minecraftforge.net/en/1.18.x/advanced/accesstransformers This section provides examples of Access Transformer directives for modifying classes, fields, and methods. It demonstrates how to specify access modifiers, target names, parameter types, and return types using Forge's AT format. ```accesstransformer # Makes public the ScreenConstructor class in MenuScreens public net.minecraft.client.gui.screens.MenuScreens$ScreenConstructor ``` ```accesstransformer # Makes protected and removes the final modifier from 'random' in MinecraftServer protected-f net.minecraft.server.MinecraftServer f_129758_ #random ``` ```accesstransformer # Makes public the 'makeExecutor' method in Util, # accepting a String and returns an ExecutorService public net.minecraft.Util m_137477_(Ljava/lang/String;)Ljava/util/concurrent/ExecutorService; #makeExecutor ``` ```accesstransformer # Makes public the 'leastMostToIntArray' method in SerializableUUID, # accepting two longs and returning an int[] public net.minecraft.core.SerializableUUID m_123274_(JJ)[I #leastMostToIntArray ``` -------------------------------- ### TextureSheetParticle Rendering Example Source: https://docs.minecraftforge.net/en/1.18.x/gameeffects/particles Shows a basic implementation of a TextureSheetParticle, focusing on the render method and setting the texture sprite for rendering. This is a common approach for particles that display textures. ```java public class MyTextureParticle extends TextureSheetParticle { protected MyTextureParticle(ClientLevel level, double x, double y, double z, double velocityX, double velocityY, double velocityZ, SpriteSet spriteSet) { super(level, x, y, z, velocityX, velocityY, velocityZ); this.setSpriteFromAge(spriteSet); } @Override public RenderShape getRenderShape() { return RenderShape.PARTICLE_SHEET_OPAQUE; } @Override public void render(VertexConsumer buffer, Camera renderInfo, float partialTicks) { // Rendering logic using the bound sprite super.render(buffer, renderInfo, partialTicks); } } ``` -------------------------------- ### Generate Patches using Gradle Source: https://docs.minecraftforge.net/en/1.18.x/forgedev Initiates the generation of patches for changes made to the Minecraft codebase within the Forge project. This is a crucial step for integrating modifications into Vanilla Minecraft. ```gradle gradlew genPatches ``` -------------------------------- ### Add test output to module classpath Source: https://docs.minecraftforge.net/en/1.18.x/forgedev Configures the IntelliJ IDEA project structure to include the compiled test classes in the classpath of the main Forge module. This allows the main code to access and utilize the test mods. ```IDEAction File -> Project Structure -> Modules -> Expand `Forge` module -> Select `Forge_test` submodule -> Paths tab -> Copy 'Test output path' Select `Forge_main` submodule -> Dependencies tab -> '+' button -> JARs or directories -> Navigate to copied path -> OK Set Scope to 'Runtime' ``` -------------------------------- ### Example Language File (JSON) Source: https://docs.minecraftforge.net/en/1.18.x/concepts/internationalization A JSON file defining translations for various game elements. It maps translation keys (e.g., 'item.examplemod.example_item') to their corresponding displayable text in a specific language. ```json { "item.examplemod.example_item": "Example Item Name", "block.examplemod.example_block": "Example Block Name", "commands.examplemod.examplecommand.error": "Example Command Errored!" } ``` -------------------------------- ### Creating a Custom Loader Builder Source: https://docs.minecraftforge.net/en/1.18.x/datagen/client/modelproviders Shows how to create a generic custom loader builder by extending `CustomLoaderBuilder`. This example defines a static `begin` method for easy instantiation and sets a hardcoded resource location for the loader. ```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); } } ``` -------------------------------- ### Example Tag Appender Usage Source: https://docs.minecraftforge.net/en/1.18.x/datagen/server/tags Demonstrates using the `TagAppender` to add, add optionally, add tags, and remove elements from a tag within a `TagProvider`. ```java this.tag(EXAMPLE_TAG) .add(EXAMPLE_OBJECT) // Adds an object to the tag .addOptional(new ResourceLocation("othermod", "other_object")) // Adds an object from another mod to the tag this.tag(EXAMPLE_TAG_2) .addTag(EXAMPLE_TAG) // Adds a tag to the tag .remove(EXAMPLE_OBJECT) // Removes an object from this tag ``` -------------------------------- ### Registering a BlockEntityType using DeferredRegister Source: https://docs.minecraftforge.net/en/1.18.x/concepts/registries Provides an example of registering a BlockEntityType, which acts as a factory for BlockEntity instances. This registration involves using the BlockEntityType.Builder to define the factory and associate it with a Block. The example shows how to register this with a DeferredRegister. ```java public static final RegistryObject> EXAMPLE_BLOCK_ENTITY = REGISTER.register( "example_block_entity", () -> BlockEntityType.Builder.of(ExampleBlockEntity::new, EXAMPLE_BLOCK.get()).build(null) ); ``` -------------------------------- ### Registering Capabilities (Java) Source: https://docs.minecraftforge.net/en/1.18.x/datastorage/capabilities Registers a custom capability for use in your mod. This is typically done during the mod setup phase using the RegisterCapabilitiesEvent. ```java @SubscribeEvent public void registerCaps(RegisterCapabilitiesEvent event) { event.register(IExampleCapability.class); } ``` -------------------------------- ### DifferenceIngredient Example Source: https://docs.minecraftforge.net/en/1.18.x/resources/server/recipes/ingredients Demonstrates the structure of a DifferenceIngredient, used for set subtraction. The input stack must match the 'base' ingredient but not the 'subtracted' ingredient. ```json // For some input { "type": "forge:difference", "base": { // Ingredient the stack is in }, "subtracted": { // Ingredient the stack is NOT in } } ``` -------------------------------- ### ParticleOptions Serialization Example Source: https://docs.minecraftforge.net/en/1.18.x/gameeffects/particles Illustrates how to define ParticleOptions and its associated Deserializer for syncing custom data. This includes methods for writing to network buffers and strings, and reading from commands. ```java public class CustomParticleOptions implements ParticleOptions { private final int data; public CustomParticleOptions(int data) { this.data = data; } @Override public ParticleType getType() { return ParticleTypes.MY_PARTICLE; // Assuming MY_PARTICLE is registered } @Override public void writeToNetwork(FriendlyByteBuf buf) { buf.writeInt(data); } @Override public String writeToString() { return String.valueOf(data); } public static final ParticleOptions$Deserializer DESERIALIZER = new ParticleOptions$Deserializer() { @Override public CustomParticleOptions fromCommand(FriendlyByteBuf buf) { return new CustomParticleOptions(buf.readInt()); } @Override public CustomParticleOptions fromNetwork(FriendlyByteBuf buf) { return new CustomParticleOptions(buf.readInt()); } }; } ``` -------------------------------- ### IntersectionIngredient Example Source: https://docs.minecraftforge.net/en/1.18.x/resources/server/recipes/ingredients Provides an example of an IntersectionIngredient, which functions as an AND condition. The input stack must satisfy all the specified child ingredients. ```json // For some input { "type": "forge:intersection", // All of these ingredients must return true to succeed "children": [ { // Ingredient 1 }, { // Ingredient 2 } // ... ] } ``` -------------------------------- ### PartialNBTIngredient Example Source: https://docs.minecraftforge.net/en/1.18.x/resources/server/recipes/ingredients Illustrates the use of PartialNBTIngredient for a more flexible NBT comparison. It allows matching against a single item or a list of items and only checks specified keys within the NBT share tag. ```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 } } } ``` -------------------------------- ### ParticleType Registration Example Source: https://docs.minecraftforge.net/en/1.18.x/gameeffects/particles Demonstrates the creation and registration of a custom ParticleType. It includes implementing the codec for serializing ParticleOptions and using SimpleParticleType for particles without custom data. ```java public static final SimpleParticleType MY_PARTICLE = new SimpleParticleType(false); // Registration example (assuming a DeferredRegister for ParticleTypes) @SubscribeEvent public static void registerParticles(RegisterParticleTypesEvent event) { event.register(MY_PARTICLE); } ``` -------------------------------- ### Static Factory Method for Trigger Instance (Java) Source: https://docs.minecraftforge.net/en/1.18.x/resources/server/advancements Provides an example of a static factory method for creating trigger instances, simplifying their instantiation for data generation purposes. ```java public static ExampleTriggerInstance instance(EntityPredicate.Builder playerBuilder, ItemPredicate.Builder itemBuilder) { return new ExampleTriggerInstance(EntityPredicate.Composite.wrap(playerBuilder.build()), itemBuilder.build()); } ``` -------------------------------- ### NBTIngredient Example Source: https://docs.minecraftforge.net/en/1.18.x/resources/server/recipes/ingredients Shows how to use an NBTIngredient to match an ItemStack based on its item type and NBT data. The NBT data must match exactly with the NBT on the item stack. ```json // For some input { "type": "forge:nbt", "item": "examplemod:example_item", "nbt": { // Add nbt data (must match exactly what is on the stack) } } ``` -------------------------------- ### JSON Tag Declaration Example Source: https://docs.minecraftforge.net/en/1.18.x/resources/server/tags Example of a JSON file for declaring or modifying game tags. It supports replacing existing values, adding new ones, and conditionally including entries. ```json { "replace": false, "values": [ "minecraft:gold_ingot", "mymod:my_ingot", { "id": "othermod:ingot_other", "required": false } ] } ``` -------------------------------- ### Example of ModelBuilder Usage - Minecraft Forge Source: https://docs.minecraftforge.net/en/1.18.x/datagen/client/modelproviders Demonstrates how to use ModelBuilder to define a model's parent, elements, textures, and transformations. It highlights the use of ResourceLocation for parent models and the structure for defining cube elements with faces. ```java ModelBuilder modelBuilder = new ModelBuilder<>() { @Override public void toJson(@NotNull JsonObjectBuilder $$0) { // Implementation for toJson } }; modelBuilder.parent(new ResourceLocation("minecraft", "block/cube")); modelBuilder.element(new ElementBuilder() .from(new Vector3f(0, 0, 0), new Vector3f(16, 16, 16)) .face(Direction.NORTH, new FaceBuilder() .uvs(new Rect2i(0, 0, 16, 16)) .texture("#all") ) .shade(true) ); modelBuilder.texture("all", new ResourceLocation("minecraft", "block/stone")); modelBuilder.transforms().transform(Transformation.firstPersonLeftHand(), new Vector3f(0, 0, 0), new Vector3f(0, 0, 0), new Vector3f(1, 1, 1)); ``` -------------------------------- ### Registering Loot Table Builders - Java Source: https://docs.minecraftforge.net/en/1.18.x/datagen/server/loottables Demonstrates how to register loot table builders with the LootTableProvider's getTables method. This example registers an ExampleLoot builder for the EMPTY parameter set. ```java // In some LootTableProvider subclass @Override protected List>>, LootContextParamSet>> getTables() { return ImmutableList.of( Pair.of(ExampleLoot::new, LootContextParamSets.EMPTY) // Loot table builder for the 'empty' parameter set //... ); } ``` -------------------------------- ### Instance Annotated Event Handler for Item Pickup Source: https://docs.minecraftforge.net/en/1.18.x/concepts/events An example of an instance method annotated with @SubscribeEvent to handle the EntityItemPickupEvent. This handler is registered by passing an instance of its class to the event bus. ```java public class MyForgeEventHandler { @SubscribeEvent public void pickupItem(EntityItemPickupEvent event) { System.out.println("Item picked up!"); } } // To register: // MinecraftForge.EVENT_BUS.register(new MyForgeEventHandler()); // or for mod bus: // FMLJavaModLoadingContext.get().getModEventBus().register(new MyForgeEventHandler()); ``` -------------------------------- ### Listening to Parent Events in Forge Source: https://docs.minecraftforge.net/en/1.18.x/concepts/events Explains that listening to a parent event class will trigger the handler for all its subclasses. No specific code example is provided, but the concept is described. ```java // Example concept: Listening to PlayerEvent will also trigger for PlayerLoggedInEvent, PlayerLoggedOutEvent, etc. // public class MyModEvents { // @SubscribeEvent // public void onPlayerEvent(PlayerEvent event) { // // This will be called for any PlayerEvent subclass // } // } ``` -------------------------------- ### sounds.json Structure Example Source: https://docs.minecraftforge.net/en/1.18.x/gameeffects/sounds Defines sound events, their subtitles, and associated sound files. It shows two common formats for specifying sound files: a simple string and an object with additional properties like 'stream'. ```json { "open_chest": { "subtitle": "mymod.subtitle.open_chest", "sounds": [ "mymod:open_chest_sound_file" ] }, "epic_music": { "sounds": [ { "name": "mymod:music/epic_music", "stream": true } ] } } ``` -------------------------------- ### Registering a custom RecipeType using DeferredRegister Source: https://docs.minecraftforge.net/en/1.18.x/concepts/registries Shows how to register a custom RecipeType, which is not a Forge Registry, using DeferredRegister. This method is used for vanilla registries that require specific handling. The example demonstrates creating a DeferredRegister for RecipeType and registering an anonymous implementation. ```java private static final DeferredRegister> REGISTER = DeferredRegister.create(Registry.RECIPE_TYPE_REGISTRY, "examplemod"); // As RecipeType is an interface, an anonymous class will be created for registering // Vanilla RecipeTypes override #toString for debugging purposes, so it is omitted in this example // Assume some recipe ExampleRecipe public static final RegistryObject> EXAMPLE_RECIPE_TYPE = REGISTER.register("example_recipe_type", () -> new RecipeType<>() {}); ``` -------------------------------- ### Get Item Handler Capability Instance (Java) Source: https://docs.minecraftforge.net/en/1.18.x/datastorage/capabilities Demonstrates how to obtain the unique instance reference for the IItemHandler capability using CapabilityManager. This allows querying for the capability on various game objects. ```java static Capability ITEM_HANDLER_CAPABILITY = CapabilityManager.get(new CapabilityToken<>(){}); ``` -------------------------------- ### Setting Block State in the World Source: https://docs.minecraftforge.net/en/1.18.x/blocks/states Shows how to place a block in the game world with a specific BlockState, starting from the block's default state and applying custom property values. ```java Level#setBlockAndUpdate(BlockPos, BlockState); Level#getBlockState(BlockState); // Get the default state and modify it Block#defaultBlockState() .setValue(Property, T); ``` -------------------------------- ### Generating Item Models with ItemModelProvider Source: https://docs.minecraftforge.net/en/1.18.x/datagen Provides an example of extending `ItemModelProvider` to generate item model JSON files. The `registerModels` method is overridden to specify the model for each item. ```java public class MyItemModelProvider extends ItemModelProvider { public MyItemModelProvider(DataGenerator generator) { super(generator); } @Override protected void registerModels() { // Example for a simple item withExistingParent("my_item", new ResourceLocation("item/generated")).texture("layer0", new ResourceLocation("mymodid", "item/my_item")); } } ``` -------------------------------- ### Registering blocks using RegistryEvent Source: https://docs.minecraftforge.net/en/1.18.x/concepts/registries Illustrates registering blocks via the RegistryEvent.Register lifecycle event. This method provides more flexibility and is suitable for complex registration scenarios. The example shows an event handler method annotated with @SubscribeEvent that registers multiple blocks. ```java @SubscribeEvent public void registerBlocks(RegistryEvent.Register event) { event.getRegistry().registerAll(new Block(...), new Block(...), ...); } ``` -------------------------------- ### Example Loot Pool with Name Source: https://docs.minecraftforge.net/en/1.18.x/resources/server/loottables Demonstrates how to name a loot pool within a loot table using the 'name' key. This provides a human-readable identifier for the pool, overriding the default hash code prefix. ```json { "name": "example_pool", "rolls": { // ... }, "entries": { // ... } } ``` -------------------------------- ### Forge RecipeManager Usage with IItemHandler Source: https://docs.minecraftforge.net/en/1.18.x/resources/server/recipes Demonstrates how to use Forge's RecipeManager to get a crafting recipe, wrapping an IItemHandler in a RecipeWrapper. This is typically done within a method that has access to the handler and the current level. ```java recipeManger.getRecipeFor(RecipeType.CRAFTING, new RecipeWrapper(handler), level); ``` -------------------------------- ### Manually Profiling Custom Code Sections Source: https://docs.minecraftforge.net/en/1.18.x/misc/debugprofiler This example demonstrates how to manually profile specific sections of your code using the ProfilerFiller class in Minecraft. This is useful for tracking the performance of custom logic beyond standard game elements. ```java ProfilerFiller#push("yourSectionName"); //The code you want to profile ProfilerFiller#pop(); ``` -------------------------------- ### Profiling Result Structure Example Source: https://docs.minecraftforge.net/en/1.18.x/misc/debugprofiler This snippet illustrates the hierarchical structure of data found in a Minecraft Debug Profiler results file. It shows how time consumption is broken down by game elements like levels, ticks, entities, and block entities. ```text [00] levels - 96.70%/96.70% [01] | Level Name - 99.76%/96.47% [02] | | tick - 99.31%/95.81% [03] | | | entities - 47.72%/45.72% [04] | | | | regular - 98.32%/44.95% [04] | | | | blockEntities - 0.90%/0.41% [05] | | | | | unspecified - 64.26%/0.26% [05] | | | | | minecraft:furnace - 33.35%/0.14% [05] | | | | | minecraft:chest - 2.39%/0.01% ``` -------------------------------- ### Create SimpleChannel Instance - Java Source: https://docs.minecraftforge.net/en/1.18.x/networking/simpleimpl Demonstrates the creation of a SimpleChannel instance, a core component of the SimpleImpl packet system. This includes defining protocol versions and compatibility checkers for network communication. ```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 ); ``` -------------------------------- ### Basic mods.toml Configuration for Minecraft Forge Source: https://docs.minecraftforge.net/en/1.18.x/gettingstarted/structuring Defines the metadata for a Minecraft Forge mod, including loader type, version, license, and mod information like ID, display name, and dependencies. This TOML file is crucial for Forge to recognize and load your mod. ```toml # The name of the mod loader type to load - for regular FML @Mod mods it should be javafml modLoader="javafml" # A version range to match for said mod loader - for regular FML @Mod it will be the forge version # Forge for 1.18 is version 38 loaderVersion="[38,)" # The license for your mod. This is mandatory and allows for easier comprehension of your redistributive properties. # Review your options at https://choosealicense.com/. All rights reserved is the default copyright stance, and is thus the default here. license="All Rights Reserved" # A URL to refer people to when problems occur with this mod issueTrackerURL="github.com/MinecraftForge/MinecraftForge/issues" # If the mods defined in this file should show as separate resource packs showAsResourcePack=false [[mods]] modId="examplemod" version="1.0.0.0" displayName="Example Mod" updateJSONURL="minecraftforge.net/versions.json" displayURL="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. ''' [[dependencies.examplemod]] modId="forge" mandatory=true versionRange="[38,)" ordering="NONE" side="BOTH" [[dependencies.examplemod]] modId="minecraft" mandatory=true versionRange="[1.18,1.19)" ordering="NONE" side="BOTH" ``` -------------------------------- ### Migrating from IExtendedEntityProperties to Capabilities (Conceptual) Source: https://docs.minecraftforge.net/en/1.18.x/datastorage/capabilities Outlines the process of converting older IExtendedEntityProperties implementations to the modern Forge Capability system. This involves mapping concepts like property names to ResourceLocations and adapting event handlers. ```text 1. Convert IEEP key/id string to ResourceLocation. 2. Create a field for the Capability instance in your handler. 3. Change EntityConstructing event to AttachCapabilitiesEvent and attach an ICapabilityProvider. 4. Ensure capability registration is handled, typically in FMLCommonSetupEvent. ``` -------------------------------- ### Loading and Creating Saved Data (Java) Source: https://docs.minecraftforge.net/en/1.18.x/datastorage/saveddata Demonstrates how to load existing Saved Data or create a new instance using `computeIfAbsent`. It includes methods for loading from NBT and creating a new instance, along with the actual call to `computeIfAbsent`. ```Java public ExampleSavedData create() { return new ExampleSavedData(); } public ExampleSavedData load(CompoundTag tag) { ExampleSavedData data = this.create(); // Load saved data return data; } // In some method within the class netherDataStorage.computeIfAbsent(this::load, this::create, "example"); ``` -------------------------------- ### Get Overrides - BakedModel Source: https://docs.minecraftforge.net/en/1.18.x/rendering/modelloaders/bakedmodel Returns the ItemOverrides to be used for this model, primarily when rendered as an item. This method is part of the BakedModel interface in Minecraft Forge. ```java ItemOverrides getOverrides(); ``` -------------------------------- ### Miscellaneous Mod Event Bus Events in Forge Source: https://docs.minecraftforge.net/en/1.18.x/concepts/events Lists examples of miscellaneous events fired on the Mod Event Bus that are typically not run in parallel, such as ColorHandlerEvent and ModelBakeEvent. ```java // Example concept: Registering color handlers or model bakers // import net.minecraftforge.client.event.ColorHandlerEvent; // import net.minecraftforge.client.event.ModelBakeEvent; // import net.minecraftforge.eventbus.api.SubscribeEvent; // public class ModMiscEvents { // @SubscribeEvent // public void onColorHandler(ColorHandlerEvent event) { // // Register color handlers // } // @SubscribeEvent // public void onModelBake(ModelBakeEvent event) { // // Modify or bake models // } // } ``` -------------------------------- ### Static Annotated Event Handler for Arrow Nock Source: https://docs.minecraftforge.net/en/1.18.x/concepts/events An example of a static method annotated with @SubscribeEvent to handle the ArrowNockEvent. This handler is registered by passing the class itself to the event bus. ```java public class MyStaticForgeEventHandler { @SubscribeEvent public static void arrowNocked(ArrowNockEvent event) { System.out.println("Arrow nocked!"); } } // To register: // MinecraftForge.EVENT_BUS.register(MyStaticForgeEventHandler.class); ``` -------------------------------- ### Registering Sounds with SoundDefinitionsProvider Source: https://docs.minecraftforge.net/en/1.18.x/datagen/client/sounds This Java code snippet demonstrates how to register sounds using the `SoundDefinitionsProvider`. It shows how to specify sound names, subtitles, and individual sound configurations like weight, volume, and streaming. ```java this.add(EXAMPLE_SOUND_EVENT, definition() .subtitle("sound.examplemod.example_sound") // Set translation key .with( sound(new ResourceLocation(MODID, "example_sound_1")) // Set first sound .weight(4) // Has a 4 / 5 = 80% chance of playing .volume(0.5), // Scales all volumes called on this sound by half sound(new ResourceLocation(MODID, "example_sound_2")) // Set second sound .stream() // Streams the sound ) ); this.add(EXAMPLE_SOUND_EVENT_2, definition() .subtitle("sound.examplemod.example_sound") // Set translation key .with( sound(EXAMPLE_SOUND_EVENT.getLocation(), SoundType.EVENT) // Adds sounds from 'EXAMPLE_SOUND_EVENT' .pitch(0.5) // Scales all pitches called on this sound by half ) ); ``` -------------------------------- ### Checking for a BlockItem (Java) Source: https://docs.minecraftforge.net/en/1.18.x/blocks Provides an example of how to check if a `Block` has an associated `BlockItem`. This is important because `Block#asItem` returns `Items#AIR` if no `BlockItem` is registered for the block. ```java if (myBlock.asItem() != Items.AIR) { // Block has a registered BlockItem } ``` -------------------------------- ### Getting and Setting Block State Values Source: https://docs.minecraftforge.net/en/1.18.x/blocks/states Demonstrates how to retrieve the current value of a property from a BlockState and how to obtain a new BlockState with a modified property value. ```java // Get the value of a property BlockState#getValue(Property); // Set the value of a property and get a new BlockState BlockState#setValue(Property, T); ``` -------------------------------- ### Creating a Basic Block with Properties (Java) Source: https://docs.minecraftforge.net/en/1.18.x/blocks Demonstrates how to create a basic Minecraft block using the `Block` class and customize its properties. Properties like hardness, resistance, sound, light emission, and friction can be set using a chainable builder pattern. ```java Block myBlock = new Block(BlockBehaviour.Properties.of().strength(1.5F, 6.0F).sound(SoundType.STONE).lightLevel(state -> 15).friction(0.98F)); ``` -------------------------------- ### Minecraft Recipe Advancement Criteria Source: https://docs.minecraftforge.net/en/1.18.x/resources/server/recipes Example of a JSON structure for a Minecraft advancement that triggers when a specific recipe is unlocked. It uses the `recipe_unlocked` trigger with a condition specifying the recipe ID. ```json { "criteria": { "has_the_recipe": { "trigger": "minecraft:recipe_unlocked", "conditions": { "recipe": "examplemod:example_recipe" } } }, "requirements": [ [ "has_the_recipe" ] ] } ``` -------------------------------- ### Implementing a Custom ModelProvider Source: https://docs.minecraftforge.net/en/1.18.x/datagen/client/modelproviders Shows how to create a `ModelProvider` subclass to generate models. The constructor specifies the output subdirectory and provides a factory for the `ModelBuilder`, enabling automatic model generation. ```java public class ExampleModelProvider extends ModelProvider { public ExampleModelProvider(DataGenerator generator, String modid, ExistingFileHelper existingFileHelper) { // Models will be generated to 'assets//models/example' if no modid is specified in '#getBuilder' super(generator, modid, "example", ExampleModelBuilder::new, existingFileHelper); } } ``` -------------------------------- ### Send Packets to Server in Forge Source: https://docs.minecraftforge.net/en/1.18.x/networking/simpleimpl Demonstrates the method for sending a packet from the client to the server using a SimpleChannel. ```java INSTANCE.sendToServer(new MyMessage()); ``` -------------------------------- ### Tag Creation and Usage in Java (Vanilla and Forge) Source: https://docs.minecraftforge.net/en/1.18.x/resources/server/tags Illustrates creating tag keys for VillagerType using Vanilla's TagKey.create and checking tag membership using Holder and ITagManager.getReverseTag. ```java public static final TagKey myVillagerTypeTag = TagKey.create(Registry.VILLAGER_TYPE, new ResourceLocation("mymod", "myvillagertypegroup")); // In some method: ResourceKey villagerTypeKey = /* ... */; boolean isInVillagerTypeGroup = Registry.VILLAGER_TYPE.getHolder(villagerTypeKey).map(holder -> holder.is(myVillagerTypeTag)).orElse(false); ``` -------------------------------- ### Generating Global Loot Modifiers with GlobalLootModifierProvider Source: https://docs.minecraftforge.net/en/1.18.x/datagen Shows how to extend `GlobalLootModifierProvider` to define global loot modifiers. The `start` method is overridden to specify the loot modifiers to be generated. ```java public class MyGlobalLootModifierProvider extends GlobalLootModifierProvider { public MyGlobalLootModifierProvider(DataGenerator gen) { super(gen); } @Override protected void start() { // Example: Add a custom loot modifier add("my_loot_modifier", new MyCustomLootModifier()); } } // Placeholder for the custom loot modifier class class MyCustomLootModifier extends LootModifier { public MyCustomLootModifier() { super(new LootContext.Builder(null).build()); // Simplified constructor for example } @Override protected List doApply(List generatedLoot, LootContext context) { // Add custom logic here to modify loot return generatedLoot; } } ``` -------------------------------- ### Playing Sounds Source: https://docs.minecraftforge.net/en/1.18.x/gameeffects/sounds Methods for playing `SoundEvent`s on the logical client and server. ```APIDOC ## Playing Sounds Minecraft Forge provides several methods for playing registered `SoundEvent`s. These methods can be called on the logical client or server. ### `Level` Class Methods 1. **`playSound(Player player, BlockPos pos, SoundEvent sound, SoundCategory category, float volume, float pitch)`** * **Description**: Forwards the call to `playSound(Player, double, double, double, SoundEvent, SoundCategory, float, float)`, adding 0.5 to each coordinate of the `BlockPos`. 2. **`playSound(Player player, double x, double y, double z, SoundEvent sound, SoundCategory category, float volume, float pitch)`** * **Client Behavior**: If `player` is the client player, plays the sound to that player. * **Server Behavior**: Plays the sound to all nearby players *except* the specified `player`. If `player` is `null`, plays to everyone nearby. * **Usage**: Typically used for sounds initiated by player actions that need to be heard by the player and others. Can be used server-side to play sounds to all players by passing `null` for the `player` argument. 3. **`playLocalSound(double x, double y, double z, SoundEvent sound, SoundCategory category, float volume, float pitch, boolean distanceDelay)`** * **Client Behavior**: Plays the sound event in the client's world. If `distanceDelay` is `true`, the sound's playback is delayed based on its distance from the player. * **Server Behavior**: This method does nothing on the server. * **Usage**: Suitable for client-only effects or sounds sent via custom network packets. Used for vanilla effects like thunder. ``` -------------------------------- ### Mod Event Bus Lifecycle Events in Forge Source: https://docs.minecraftforge.net/en/1.18.x/concepts/events Lists common lifecycle events fired on the Mod Event Bus, such as FMLCommonSetupEvent and FMLClientSetupEvent. These are used for mod initialization. ```java import net.minecraftforge.fml.event.lifecycle.*; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; @Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD) public class ModLifecycleEvents { @SubscribeEvent public static void commonSetup(FMLCommonSetupEvent event) { // Code for common setup } @SubscribeEvent public static void clientSetup(FMLClientSetupEvent event) { // Code for client-specific setup } @SubscribeEvent public static void serverSetup(FMLDedicatedServerSetupEvent event) { // Code for dedicated server setup } @SubscribeEvent public static void enqueueIMC(InterModEnqueueEvent event) { // Code for enqueueing InterModComms messages } @SubscribeEvent public static void processIMC(InterModProcessEvent event) { // Code for processing InterModComms messages } } ``` -------------------------------- ### Can Tool Perform Action Condition Source: https://docs.minecraftforge.net/en/1.18.x/resources/server/loottables Illustrates the 'forge:can_tool_perform_action' condition, which checks if a tool provided in the LootContext can execute a specified ToolAction. An example is provided for checking if an axe can strip a log. ```json { "conditions": [ { "condition": "forge:can_tool_perform_action", "action": "axe_strip" } ] } ``` -------------------------------- ### Configure Enabled GameTest Namespaces (Gradle) Source: https://docs.minecraftforge.net/en/1.18.x/misc/gametest This Gradle configuration property specifies which namespaces should be loaded for Game Tests. Namespaces must be comma-separated without spaces. ```gradle property 'forge.enabledGameTestNamespaces', 'modid1,modid2,modid3' ``` -------------------------------- ### Run All Game Tests Source: https://docs.minecraftforge.net/en/1.18.x/misc/gametest This command executes all available game tests. ```shell /test runall ``` -------------------------------- ### Define Advancement Rewards (JSON) Source: https://docs.minecraftforge.net/en/1.18.x/resources/server/advancements An example of how to define rewards for completing an advancement within a Minecraft advancement JSON file. Rewards can include experience points, loot tables, recipes, or custom functions. ```json "rewards": { "experience": 10, "loot": [ "minecraft:example_loot_table", "minecraft:example_loot_table2" // ... ], "recipes": [ "minecraft:example_recipe", "minecraft:example_recipe2" // ... ], "function": "minecraft:example_function" } ``` -------------------------------- ### Define Basic Config Value Source: https://docs.minecraftforge.net/en/1.18.x/misc/config Shows how to define a basic configuration value using the `define` method on a ForgeConfigSpec.Builder, including a comment and a default value. ```java // For some ForgeConfigSpec$Builder builder ConfigValue value = builder.comment("Comment") .define("config_value_name", defaultValue); ``` -------------------------------- ### BakedModel Interface Methods Source: https://docs.minecraftforge.net/en/1.18.x/rendering/modelloaders/bakedmodel Documentation for the core methods of the BakedModel interface, used for rendering models as blocks or items. ```APIDOC ## BakedModel Interface Methods ### Description Methods for optimizing and rendering model geometry, handling item overrides, ambient occlusion, GUI rendering, custom renderers, particle icons, perspective transformations, and quad generation. ### Methods - `getOverrides` - `useAmbientOcclusion` - `isGui3d` - `isCustomRenderer` - `getParticleIcon` - `handlePerspective` - `getQuads` ### `getOverrides` #### Description Returns the `ItemOverrides` to use for this model. This is only used if this model is being rendered as an item. #### Method GET #### Endpoint N/A (Interface method) ### `useAmbientOcclusion` #### Description Determines if the model should be rendered with ambient occlusion when it's a block in the level, not emitting light, and ambient occlusion is enabled. #### Method GET #### Endpoint N/A (Interface method) ### `isGui3d` #### Description Indicates if the model should appear "flat" when rendered as an item in GUIs, on entities, or item frames. Also disables lighting in GUIs. #### Method GET #### Endpoint N/A (Interface method) ### `isCustomRenderer` #### Description Returns `true` if a custom renderer should be used for the item. If `true`, the model is not rendered directly; instead, it falls back to `BlockEntityWithoutLevelRenderer#renderByItem`. For specific vanilla items, this involves data copying to a `BlockEntity` and rendering via a `BlockEntityRenderer`. For others, it uses `IItemRenderProperties#getItemStackRenderer`. #### Method GET #### Endpoint N/A (Interface method) ### `getParticleIcon` #### Description Returns the texture to be used for particles associated with the model (e.g., block breaking, item eating). The method `#getParticleIcon(IModelData)` is preferred over the deprecated version without parameters. #### Method GET #### Endpoint N/A (Interface method) ### `handlePerspective` #### Description Handles perspective transformations for the model, superseding the deprecated `getTransforms` method. The default implementation is sufficient if this method is implemented. #### Method GET #### Endpoint N/A (Interface method) ### `getQuads` #### Description The primary method for retrieving `BakedQuad`s, containing low-level vertex data for rendering. It accepts `BlockState` (non-null for blocks, null for items), `Direction` for face culling, a `Random` instance, and `IModelData` for additional rendering properties. #### Method GET #### Endpoint N/A (Interface method) #### Parameters ##### Path Parameters N/A ##### Query Parameters N/A ##### Request Body N/A #### Response ##### Success Response (200) - `List` (List) - The list of baked quads for rendering. - `BlockState` (BlockState) - The state of the block being rendered (non-null for blocks). - `Direction` (Direction) - The direction for face culling (null if no side is specified). - `Random` (Random) - An instance of Random for random number generation. - `IModelData` (IModelData) - Additional model data for rendering. #### Response Example N/A (Method return value) ``` -------------------------------- ### Get Known Blocks for Loot Tables - Java Source: https://docs.minecraftforge.net/en/1.18.x/datagen/server/loottables Overrides getKnownBlocks in a BlockLoot subclass to provide an iterable of all registered blocks that should have loot tables. It uses DeferredRegister to retrieve block entries. ```java // In some BlockLoot 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 } ``` -------------------------------- ### Exposing Item Handler Capability (Java) Source: https://docs.minecraftforge.net/en/1.18.x/datastorage/capabilities Demonstrates how to expose an IItemHandler capability from a BlockEntity subclass. It shows the initialization of LazyOptional, overriding getCapability to return the capability, and invalidating it in invalidateCaps. ```java // Somewhere in your BlockEntity subclass LazyOptional inventoryHandlerLazyOptional; // Supplied instance (e.g. () -> inventoryHandler) // Ensure laziness as initialization should only happen when needed inventoryHandlerLazyOptional = LazyOptional.of(inventoryHandlerSupplier); @Override public LazyOptional getCapability(Capability cap, Direction side) { if (cap == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) { return inventoryHandlerLazyOptional.cast(); } return super.getCapability(cap, side); } @Override public void invalidateCaps() { super.invalidateCaps(); inventoryHandlerLazyOptional.invalidate(); } ```