├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── src └── main │ ├── resources │ ├── pack.mcmeta │ ├── data │ │ └── customrecipeexample │ │ │ └── recipes │ │ │ ├── dirt_to_diamond.json │ │ │ ├── bone_to_bonemeal.json │ │ │ └── wool_to_string.json │ └── META-INF │ │ └── mods.toml │ └── java │ └── net │ └── darkhax │ └── customrecipeexample │ ├── RecipeTypeClickBlock.java │ ├── CustomRecipesMod.java │ └── ClickBlockRecipe.java ├── .gitignore ├── gradle.properties ├── README.md ├── gradlew.bat └── gradlew /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Minecraft-Forge-Tutorials/Custom-Json-Recipes/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /src/main/resources/pack.mcmeta: -------------------------------------------------------------------------------- 1 | { 2 | "pack": { 3 | "pack_format": 4, 4 | "description": "Resources used by customrecipeexample" 5 | } 6 | } -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.9-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | #IntelliJ IDEA 2 | *.class 3 | *.iml 4 | *.ipr 5 | *.iws 6 | *.launch 7 | out/ 8 | 9 | #ForgeGradle 10 | build/ 11 | .gradle/ 12 | run/ 13 | 14 | #Eclipse 15 | .classpath 16 | .metadata/ 17 | .project 18 | .settings/ 19 | /bin/ 20 | /.idea/ 21 | -------------------------------------------------------------------------------- /src/main/resources/data/customrecipeexample/recipes/dirt_to_diamond.json: -------------------------------------------------------------------------------- 1 | { 2 | "type": "customrecipeexample:click_block_recipe", 3 | "blockId": "minecraft:beacon", 4 | "input": { 5 | "item": "minecraft:dirt" 6 | }, 7 | "output": { 8 | "item": "minecraft:diamond" 9 | } 10 | } -------------------------------------------------------------------------------- /src/main/resources/data/customrecipeexample/recipes/bone_to_bonemeal.json: -------------------------------------------------------------------------------- 1 | { 2 | "type": "customrecipeexample:click_block_recipe", 3 | "blockId": "minecraft:stone", 4 | "input": { 5 | "item": "minecraft:bone" 6 | }, 7 | "output": { 8 | "item": "minecraft:bone_meal", 9 | "count": 3 10 | } 11 | } -------------------------------------------------------------------------------- /src/main/resources/data/customrecipeexample/recipes/wool_to_string.json: -------------------------------------------------------------------------------- 1 | { 2 | "type": "customrecipeexample:click_block_recipe", 3 | "blockId": "minecraft:stonecutter", 4 | "input": { 5 | "tag": "minecraft:wool" 6 | }, 7 | "output": { 8 | "item": "minecraft:string", 9 | "count": 4 10 | } 11 | } -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Gralde properties 2 | org.gradle.jvmargs=-Xmx3G 3 | org.gradle.daemon=false 4 | 5 | # Mod Properties 6 | mod_version=1.0. 7 | mod_group=net.darkhax.customrecipeexample 8 | mod_name=CustomRecipeExample 9 | mod_id=customrecipeexample 10 | mod_vendor=Darkhax 11 | mod_download= 12 | mod_authors=Darkhax 13 | mod_description=Custom recipe systems using json files. 14 | 15 | # Dep Versions 16 | version_minecraft=1.14.3 17 | version_forge=1.14.3-27.0.22 18 | version_mcp=20190703-1.14.3 19 | 20 | # Curse properties 21 | curse_versions=1.14.3 22 | curse_project=0 -------------------------------------------------------------------------------- /src/main/resources/META-INF/mods.toml: -------------------------------------------------------------------------------- 1 | modLoader="javafml" 2 | loaderVersion="[27,)" 3 | 4 | [[mods]] 5 | modId="customrecipeexample" 6 | version="${version}" 7 | displayName="${mod_name}" 8 | displayURL="${mod_download}" 9 | credits="${mod_credits}" 10 | authors="${mod_authors}" 11 | description=''' 12 | ${mod_description} 13 | ''' 14 | 15 | [[dependencies.recipes]] 16 | modId="forge" 17 | mandatory=true 18 | versionRange="[27,)" 19 | ordering="NONE" 20 | side="BOTH" 21 | 22 | [[dependencies.recipes]] 23 | modId="minecraft" 24 | mandatory=true 25 | versionRange="[1.14.3]" 26 | ordering="NONE" 27 | side="BOTH" -------------------------------------------------------------------------------- /src/main/java/net/darkhax/customrecipeexample/RecipeTypeClickBlock.java: -------------------------------------------------------------------------------- 1 | package net.darkhax.customrecipeexample; 2 | 3 | import net.minecraft.item.crafting.IRecipeType; 4 | 5 | // I made a new class because I don't like to use anonymous inner classes. 6 | // That's more of a preference than a requirement. 7 | public class RecipeTypeClickBlock implements IRecipeType { 8 | 9 | @Override 10 | public String toString () { 11 | 12 | // All vanilla recipe types return their ID in toString. I am not sure how vanilla uses 13 | // this, or if it does. Modded types should follow this trend for the sake of 14 | // consistency. I am also using it during registry to create the ResourceLocation ID. 15 | return "customrecipeexample:click_block_recipe"; 16 | } 17 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Custom-Json-Recipes 2 | This mod provides a basic example of how mods can add their own custom recipe systems which are compatible with the vanilla recipe serialization framework, without breaking mods like CraftTweaker and JEI. In this example mod we create a "Click Block Recipe" which allows items to be crafted into other items when left clicked on a specific block. 3 | 4 | With this system your recipes will 5 | - load from json files, which can be defined by any mod, datapack, or modpack. 6 | - synchronized to the client when a player joins a server. 7 | - reloadable using the /reload command. 8 | - have the potential to be compatible with CraftTweaker and JEI without using additional hacks. 9 | 10 | This example mod includes all the neccesary source code, along with comments on what the code does, and why certain decisions were made. You will still need a basic understanding of Java to make use of this code. This mod also provides several example json files. These files are in the `data.modid.recipes` directory, but you can also load recipes from subdirectories of this folder. The following example recipes are included. 11 | - Left clicking bone on stone will give the player 3 bone meal. 12 | - Left clicking any wool on a saw mill will give the player 4 string. 13 | - Left clicking dirt on a beacon will give the player a diamond. 14 | 15 | The Java source files for this project are licensed under [Creative Commons 0](https://creativecommons.org/publicdomain/zero/1.0/legalcode). The build scripts used are licensed under LGPL 2.1. Any third party tools or plugins such as ForgeGralde and Minecraft are licensed under their respective copyrights. 16 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /src/main/java/net/darkhax/customrecipeexample/CustomRecipesMod.java: -------------------------------------------------------------------------------- 1 | package net.darkhax.customrecipeexample; 2 | 3 | import java.util.Map; 4 | 5 | import net.minecraft.item.ItemStack; 6 | import net.minecraft.item.crafting.IRecipe; 7 | import net.minecraft.item.crafting.IRecipeSerializer; 8 | import net.minecraft.item.crafting.IRecipeType; 9 | import net.minecraft.item.crafting.RecipeManager; 10 | import net.minecraft.util.ResourceLocation; 11 | import net.minecraft.util.registry.Registry; 12 | import net.minecraftforge.common.MinecraftForge; 13 | import net.minecraftforge.event.RegistryEvent.Register; 14 | import net.minecraftforge.event.entity.player.PlayerInteractEvent; 15 | import net.minecraftforge.fml.common.Mod; 16 | import net.minecraftforge.fml.common.ObfuscationReflectionHelper; 17 | import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; 18 | import net.minecraftforge.items.ItemHandlerHelper; 19 | 20 | @Mod("customrecipeexample") 21 | public class CustomRecipesMod { 22 | 23 | // Creates a new recipe type. This is used for storing recipes in the map, and looking them 24 | // up. 25 | public static final IRecipeType CLICK_BLOCK_RECIPE = new RecipeTypeClickBlock(); 26 | 27 | public CustomRecipesMod() { 28 | 29 | // Registers an event with the mod specific event bus. This is needed to register new 30 | // stuff. 31 | FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(IRecipeSerializer.class, this::registerRecipeSerializers); 32 | 33 | // Registers an event with the general game event bus. This is used to perform click 34 | // block crafting. 35 | MinecraftForge.EVENT_BUS.addListener(this::onPlayerClickBlock); 36 | } 37 | 38 | private void registerRecipeSerializers (Register> event) { 39 | 40 | // Vanilla has a registry for recipe types, but it does not actively use this registry. 41 | // While this makes registering your recipe type an optional step, I recommend 42 | // registering it anyway to allow other mods to discover your custom recipe types. 43 | Registry.register(Registry.RECIPE_TYPE, new ResourceLocation(CLICK_BLOCK_RECIPE.toString()), CLICK_BLOCK_RECIPE); 44 | 45 | // Register the recipe serializer. This handles from json, from packet, and to packet. 46 | event.getRegistry().register(ClickBlockRecipe.SERIALIZER); 47 | } 48 | 49 | private void onPlayerClickBlock (PlayerInteractEvent.LeftClickBlock event) { 50 | 51 | // Check that the world is server side, and the player actually exists. 52 | if (!event.getWorld().isRemote && event.getEntityPlayer() != null) { 53 | 54 | // Get the currently held item of the player, for the hand that was used in the 55 | // event. 56 | final ItemStack heldItem = event.getEntityPlayer().getHeldItem(event.getHand()); 57 | 58 | // Iterates all the recipes for the custom recipe type. If you have lots of recipes 59 | // you may want to consider adding some form of recipe caching. In this case we 60 | // could store the last successful recipe in a global field to lower the lookup 61 | // time for repeat crafting. You could also use RecipesUpdatedEvent to build a 62 | // cache of your recipes. Make sure to build the cache on LOWEST priority so mods 63 | // like CraftTweaker can work with your recipes. 64 | for (final IRecipe recipe : this.getRecipes(CLICK_BLOCK_RECIPE, event.getWorld().getRecipeManager()).values()) { 65 | 66 | // If you need access to custom recipe methods you will need to check and cast 67 | // to your recipe type. This step could be skipped if you did it during a cache 68 | // process. 69 | if (recipe instanceof ClickBlockRecipe) { 70 | 71 | final ClickBlockRecipe clickBlockRecipe = (ClickBlockRecipe) recipe; 72 | 73 | // isValid is a custom recipe which checks if the held item and block match 74 | // a known recipe. If this were cached to a multimap you could use Block as 75 | // a key and only check the held item. 76 | if (clickBlockRecipe.isValid(heldItem, event.getWorld().getBlockState(event.getPos()).getBlock())) { 77 | 78 | // When the recipe is valid, shrink the held item by one. 79 | heldItem.shrink(1); 80 | 81 | // This forge method tries to give a player an item. If they have no 82 | // room it drops on the ground. We're giving them a copy of the output 83 | // item. 84 | ItemHandlerHelper.giveItemToPlayer(event.getEntityPlayer(), clickBlockRecipe.getRecipeOutput().copy()); 85 | event.setCanceled(true); 86 | break; 87 | } 88 | } 89 | } 90 | } 91 | } 92 | 93 | /** 94 | * This method lets you get all of the recipe data for a given recipe type. The existing 95 | * methods for this require an IInventory, and this allows you to skip that overhead. This 96 | * method uses reflection to get the recipes map, but an access transformer would also 97 | * work. 98 | * 99 | * @param recipeType The type of recipe to grab. 100 | * @param manager The recipe manager. This is generally taken from a World. 101 | * @return A map containing all recipes for the passed recipe type. This map is immutable 102 | * and can not be modified. 103 | */ 104 | private Map> getRecipes (IRecipeType recipeType, RecipeManager manager) { 105 | 106 | final Map, Map>> recipesMap = ObfuscationReflectionHelper.getPrivateValue(RecipeManager.class, manager, "field_199522_d"); 107 | return recipesMap.get(recipeType); 108 | } 109 | } -------------------------------------------------------------------------------- /src/main/java/net/darkhax/customrecipeexample/ClickBlockRecipe.java: -------------------------------------------------------------------------------- 1 | package net.darkhax.customrecipeexample; 2 | 3 | import com.google.gson.JsonElement; 4 | import com.google.gson.JsonObject; 5 | 6 | import net.minecraft.block.Block; 7 | import net.minecraft.block.Blocks; 8 | import net.minecraft.inventory.IInventory; 9 | import net.minecraft.item.ItemStack; 10 | import net.minecraft.item.crafting.IRecipe; 11 | import net.minecraft.item.crafting.IRecipeSerializer; 12 | import net.minecraft.item.crafting.IRecipeType; 13 | import net.minecraft.item.crafting.Ingredient; 14 | import net.minecraft.item.crafting.ShapedRecipe; 15 | import net.minecraft.network.PacketBuffer; 16 | import net.minecraft.util.JSONUtils; 17 | import net.minecraft.util.ResourceLocation; 18 | import net.minecraft.world.World; 19 | import net.minecraftforge.registries.ForgeRegistries; 20 | import net.minecraftforge.registries.ForgeRegistryEntry; 21 | 22 | // The IRecipe system is designed to be used with an inventory, but that isn't strictly required. In your system you can choose to ignore any vanilla method here you want. 23 | public class ClickBlockRecipe implements IRecipe { 24 | 25 | public static final Serializer SERIALIZER = new Serializer(); 26 | 27 | private final Ingredient input; 28 | private final ItemStack output; 29 | private final Block block; 30 | private final ResourceLocation id; 31 | 32 | public ClickBlockRecipe(ResourceLocation id, Ingredient input, ItemStack output, Block block) { 33 | 34 | this.id = id; 35 | this.input = input; 36 | this.output = output; 37 | this.block = block; 38 | 39 | // This output is not required, but it can be used to detect when a recipe has been 40 | // loaded into the game. 41 | System.out.println("Loaded " + this.toString()); 42 | } 43 | 44 | @Override 45 | public String toString () { 46 | 47 | // Overriding toString is not required, it's just useful for debugging. 48 | return "ClickBlockRecipe [input=" + this.input + ", output=" + this.output + ", block=" + this.block.getRegistryName() + ", id=" + this.id + "]"; 49 | } 50 | 51 | @Override 52 | public boolean matches (IInventory inv, World worldIn) { 53 | 54 | // This method is ignored by our custom recipe system, and only has partial 55 | // functionality. isValid is used instead. 56 | return this.input.test(inv.getStackInSlot(0)); 57 | } 58 | 59 | @Override 60 | public ItemStack getCraftingResult (IInventory inv) { 61 | 62 | // This method is ignored by our custom recipe system. getRecipeOutput().copy() is used 63 | // instead. 64 | return this.output.copy(); 65 | } 66 | 67 | @Override 68 | public ItemStack getRecipeOutput () { 69 | 70 | return this.output; 71 | } 72 | 73 | @Override 74 | public ResourceLocation getId () { 75 | 76 | return this.id; 77 | } 78 | 79 | @Override 80 | public IRecipeSerializer getSerializer () { 81 | 82 | return SERIALIZER; 83 | } 84 | 85 | @Override 86 | public IRecipeType getType () { 87 | 88 | return CustomRecipesMod.CLICK_BLOCK_RECIPE; 89 | } 90 | 91 | @Override 92 | public ItemStack getIcon () { 93 | 94 | return new ItemStack(Blocks.STONE); 95 | } 96 | 97 | public boolean isValid (ItemStack input, Block block) { 98 | 99 | return this.input.test(input) && this.block == block; 100 | } 101 | 102 | private static class Serializer extends ForgeRegistryEntry> implements IRecipeSerializer { 103 | 104 | Serializer() { 105 | 106 | // This registry name is what people will specify in their json files. 107 | this.setRegistryName(new ResourceLocation("customrecipeexample", "click_block_recipe")); 108 | } 109 | 110 | @Override 111 | public ClickBlockRecipe read (ResourceLocation recipeId, JsonObject json) { 112 | 113 | // Reads a recipe from json. 114 | 115 | // Reads the input. Accepts items, tags, and anything else that 116 | // Ingredient.deserialize can understand. 117 | final JsonElement inputElement = JSONUtils.isJsonArray(json, "input") ? JSONUtils.getJsonArray(json, "input") : JSONUtils.getJsonObject(json, "input"); 118 | final Ingredient input = Ingredient.deserialize(inputElement); 119 | 120 | // Reads the output. The common utility method in ShapedRecipe is what all vanilla 121 | // recipe classes use for this. 122 | final ItemStack output = ShapedRecipe.deserializeItem(JSONUtils.getJsonObject(json, "output")); 123 | 124 | // Reads a resource location, which is used to look up the target block. 125 | final ResourceLocation blockId = new ResourceLocation(JSONUtils.getString(json, "blockId")); 126 | final Block block = ForgeRegistries.BLOCKS.getValue(blockId); 127 | 128 | // If something is invalid or null an exception should be thrown. This is used to 129 | // let the game and end user know a recipe was bad. 130 | if (block == null || block == Blocks.AIR) { 131 | 132 | throw new IllegalStateException("The block " + blockId + " does not exist."); 133 | } 134 | 135 | return new ClickBlockRecipe(recipeId, input, output, block); 136 | } 137 | 138 | @Override 139 | public ClickBlockRecipe read (ResourceLocation recipeId, PacketBuffer buffer) { 140 | 141 | // Reads a recipe from a packet buffer. This code is called on the client. 142 | final Ingredient input = Ingredient.read(buffer); 143 | final ItemStack output = buffer.readItemStack(); 144 | final ResourceLocation blockId = buffer.readResourceLocation(); 145 | final Block block = ForgeRegistries.BLOCKS.getValue(blockId); 146 | 147 | if (block == null) { 148 | 149 | throw new IllegalStateException("The block " + blockId + " does not exist."); 150 | } 151 | 152 | return new ClickBlockRecipe(recipeId, input, output, block); 153 | } 154 | 155 | @Override 156 | public void write (PacketBuffer buffer, ClickBlockRecipe recipe) { 157 | 158 | // Writes the recipe to a packet buffer. This is called on the server when a player 159 | // connects or when /reload is used. 160 | recipe.input.write(buffer); 161 | buffer.writeItemStack(recipe.output); 162 | buffer.writeResourceLocation(recipe.block.getRegistryName()); 163 | } 164 | } 165 | } --------------------------------------------------------------------------------