Создание модификаций с помощью forge/1.12+

Создание модификации[]

build.gradle

Это файл, который задает свойства проекта и его нужно немного подправить:

buildscript {
    repositories {
        jcenter()
        maven {
            url = "http://files.minecraftforge.net/maven"
        }
    }
    dependencies {
        classpath 'net.minecraftforge.gradle:ForgeGradle:2.3-SNAPSHOT'
    }
}

apply plugin: 'net.minecraftforge.gradle.forge'

version = "версия_модификации" //Обычно согласно версии major.minor.patch
group = "пакет_главного_класса" //Обычно в стиле домен.автор.идентификатор_модификации
archivesBaseName = "идентификатор_модификации" //Без пробелов и только в нижнем регистре

sourceCompatibility = targetCompatibility = '1.8'
compileJava {
    sourceCompatibility = targetCompatibility = '1.8'
}

minecraft {
    version = "1.12.2-14.23.5.2768"
    runDir = "run"
    mappings = "snapshot_20171003"
}

dependencies {
    
}

processResources {
    inputs.property "версия_модификации", project.version
    inputs.property "1.12.2", project.minecraft.version
    
    from(sourceSets.main.resources.srcDirs) {
        include 'mcmod.info'
        expand 'version'project.version, 'mcversion'project.minecraft.version
    }
    
    from(sourceSets.main.resources.srcDirs) {
        exclude 'mcmod.info'
    }
    
}

runClient {
    args "--username=НикнеймАвтора"
    jvmArgs "-Xms2G", "-Xmx2G", "-XX:+UnlockExperimentalVMOptions", "-XX:+UseG1GC", "-XX:G1NewSizePercent=20", "-XX:G1ReservePercent=20", "-XX:MaxGCPauseMillis=50", "-XX:G1HeapRegionSize=32M"
}

runServer {
    jvmArgs "-Xmx2G", "-Xmx2G"
}

Если вы используете IntelliJ IDEA, то в конец build.gradle дополнительно добавьте это:

apply plugin: 'idea'
idea {
    module {
        inheritOutputDirs = true
    }
}
subprojects {
    apply plugin: 'idea'
}

task prepareAssets(type: Copy) {
    group = 'build'
    from project.file('src/main/resources')
    into project.file('build/classes/java/main')
}

classes.dependsOn(prepareAssets)

pack.mcmeta

Этот файл нужен для корректной работы игры с ресурсами модификации, такими как локализации, модели, рецепты, таблицы добычи и так далее. Заполняется следующим образом:

{
  "pack" {
    "pack_format" 3,
    "description" "Описание вашего мода"
  }
}

mcmod.info

Этот файл задаёт более подробную информацию о модификации и заполняется следующим образом:

,
  "credits" "Благодарности кому либо"
}]

Класс модификации

Данный класс создается в патче и является главным файлом, благодаря которому игра видит нашу модификацию. Заполняется следующим образом:

@Mod(modid = "идентификатор", name = "название", version = "${version}", dependencies = "required-after:forge@[минимальная версия forge,)", useMetadata = true)

public class TutorialMod {

}

Предмет[]

Класс предмета

Для создания предмета создадим класс с именем TutorialItem:

import net.minecraft.item.Item;

public class TutorialItem extends Item 
{


	public TutorialItem(String string)  //Параметр string будет заполняться в регистраторе
    {
		this.setUnlocalizedName(string);  //Имя предмета если нет файла локализации
		this.setRegistryName(string);  //Имя в регистре игры, также используется в команде /give
        this.maxStackSize(целое число от 1 до 64); //Размер стопки для предмета, по умолчанию 64
        this.setCreativeTab(вкладка); //Творческая вкладка, где будет размещен предмет, пример: this.setCreativeTab(CreativeTabs.MISC);
        this.setHasSubtypes(true или false); //Используется для обозначения, что у предмета есть подтипы, т.е. метадата
	}

}

Регистрация

Для регистрации предмета создадим класс ItemsRegister:

public class ItemsRegister
{
	public static Item ВАШ_ПРЕДМЕТ = new TutorialItem("item_tutorial");
	

    public static void register()
    {	
    	setRegister(ВАШ_ПРЕДМЕТ);

    }

    @SideOnly(Side.CLIENT)
    public static void registerRender()
    {	
    	setRender(ВАШ_ПРЕДМЕТ);

    }

    private static void setRegister(Item item)
    {
        ForgeRegistries.ITEMS.registerAll(item);
    }

    @SideOnly(Side.CLIENT)
    private static void setRender(Item item)
    {
    	Minecraft.getMinecraft().getRenderItem().getItemModelMesher().register(item, , new ModelResourceLocation(item.getRegistryName(), "inventory"));
    }
}

В классе CommonProxy, в методе добавляем строку , а в методе .

Модель

Теперь у нас есть предмет, однако если мы запустим игру и выдадим себе его, то он будет выглядеть как куб с фиолетовыми и черными клетками. Это говорит о том, что игра не нашла модель предмета. Для исправления этой проблемы создаём в папке файл с расширением .json и пишем в нём следующий текст:

{
	"parent" "item/generated",
	"textures" {
		"layer0" "имя_мода:items/имя_текстуры"
	}
}

Либо

{
	"parent" "item/handheld",
	"textures" {
		"layer0" "имя_мода:items/имя_текстуры"
	}
}

Примечание: название файла модели должно совпадать с RegistryName предмета

Второй вариант используется для моделей инструментов и оружия. Однако теперь, когда у нас есть модель для предмета, осталось добавить текстуру по пути дав ему имя, идентичное указанному в файле модели.

Building and Testing Your Mod

  1. To build your mod, run . This will output a file in with the name . This file can be placed in the folder of a Forge enabled Minecraft setup or distributed.
  2. To test run your mod, the easiest way is to use the run configs that were generated when you set up your project. Otherwise, you can run . This will launch Minecraft from the location along with your mod’s code in any source sets specified within your run configurations. The default MDK includes the source set, so any code written within will be applied.
  3. You can also run a dedicated server using the server run config or via . This will launch the Minecraft server with its GUI. After the first run, the server will shut down immediately until the Minecraft EULA is accepted by editing . Once accepted, the server will load and can be accessed via a direct connect to .

Note

It is always advisable to test your mod in a dedicated server environment if it is intended to run there.

From Zero to Modding

  1. Obtain a source distribution from forge’s files site. (Look for the Mdk file type, or Src in older 1.8/1.7 versions).
  2. Extract the downloaded source distribution to an empty directory. You should see a bunch of files, and an example mod is placed in for you to look at. Only a few of these files are strictly necessary for mod development, and you may reuse these files for all your projects These files are:
    • the folder
  3. Move the files listed above to a new folder, this will be your mod project folder.
  4. Open up a command prompt in the folder you created in step (3), then run . This will download a bunch of artifacts from the internet needed to decompile and build Minecraft and forge. This might take some time, as it will download stuff and then decompile Minecraft. Note that, in general, these things will only need to be downloaded and decompiled once, unless you delete the gradle artifact cache.
  5. Choose your IDE: Forge explicitly supports developing with Eclipse or IntelliJ environments, but any environment, from Netbeans to vi/emacs, can be made to work.
    • For Eclipse, you should run — this will download some more artifacts for building eclipse projects and then place the eclipse project artifacts in your current directory.
    • For IntelliJ, simply import the build.gradle file.
  6. Load your project into your IDE.
    • For Eclipse, create a workspace anywhere (though the easiest location is one level above your project folder). Then simply import your project folder as a project, everything will be done automatically.
    • For IntelliJ, you only need to create run configs. You can run to do this.

Note

In case you will receive an error while running the task ( the fourth step )

assign more RAM into gradle by adding into the file (create file if doesn’t exist). The sign means it’s a user’s .

Creating a Block

Basic Blocks

For simple blocks, which need no special functionality (think cobblestone, wooden planks, etc.), a custom class is not necessary. You can create a block by instantiating the class with a object. This object can be made using , and it can be customized by calling its methods. For instance:

  • — The hardness controls the time it takes to break the block. It is an arbitrary value. For reference, stone has a hardness of 1.5, and dirt 0.5. If the block should be unbreakable a hardness of -1.0 should be used, see the definition of as an example. The resistance controls the explosion resistance of the block. For reference, stone has a resistance of 6.0, and dirt 0.5.
  • — Controls the sound the block makes when it is punched, broken, or placed. Requires a argument, see the sounds page for more details.
  • — Controls the light emission of the block. Takes a function with a parameter that returns a value from zero to fifteen.
  • — Controls how slippery the block is. For reference, ice has a slipperiness of 0.98.

All these methods are chainable which means you can call them in series. See the class for examples of this.

Note

Blocks have no setter for their (formerly Creative Tab). This has been moved to the and is now its responsibility. Furthermore, there is no setter for translation key as it is now generated from the registry name.

Advanced Blocks

Of course, the above only allows for extremely basic blocks. If you want to add functionality, like player interaction, a custom class is required. However, the class has many methods and unfortunately not every single one can be documented here. See the rest of the pages in this section for things you can do with blocks.

Customizing Your Mod Information

Edit the file to customize how your mod is built (the file names, versions, and other things).

Important

Do not edit the section of the build.gradle file, its default text is necessary for ForgeGradle to function.

Almost anything underneath the marker can be changed. Many things can be removed and customized there as well.

Simple Customizations

These customizations are highly recommended for all projects.

  • To change the name of the file you build — edit the value of to suit.
  • To change your “maven coordinates” — edit the value of as well.
  • To change the version number — edit the value of .
  • To update the run configurations — replace all occurrences of to the mod id of your mod.

Migration to Mojang’s Official Mappings

As of 1.16.5, Forge will be using Mojang’s Official Mappings, or MojMaps, for the forseeable future. The official mappings provide all method and field names, with the class names coming in 1.17. Parameters and javadocs are not provided by this mapping set. Currently, there is no guarantee that these mappings are legally safe; however, Forge has decided to adopt them in good faith since Mojang wants them to be used. You can read about Forge’s stance here.

If you are uncomfortable using these mappings, you can revert them back the previously used mappings: MCP. MCP provides a partial list of mapped methods, fields, parameters and javadocs. Note that the following will most likely be the last MCP mappings released as they are no longer being maintained:

From Zero to Modding

  1. Obtain a Java 8 Development Kit (JDK) and a 64-bit Java Virtual Machine (JVM). Minecraft and MinecraftForge both compile against Java 8 and as such should be used for development. Using a 32-bit JVM will result in some problems when running the below gradle tasks. You can obtain one from AdoptOpenJDK.
  2. Obtain the Mod Development Kit (MDK) from Forge’s files site.
  3. Extract the downloaded MDK into an empty directory. You should see a bunch of files along with an example mod placed in for you to look at. Only a few of these files are strictly necessary for mod development, and you may reuse these files for all your projects. These files are:
    • the folder
  4. Move the files listed above to a new folder. This will be your mod project folder.
  5. Choose your IDE:
    • Forge only explicitly supports developing with Eclipse, but there are additional run tasks for IntelliJ IDEA or Visual Studio Code environments. However, any environment, from Netbeans to vim/emacs, can be made to work.
    • For both Intellij IDEA and Eclipse, their Gradle integration will handle the rest of the initial workspace setup. This includes downloading packages from Mojang, MinecraftForge, and a few other software sharing sites. For VSCode, the ‘Gradle Tasks’ plugin can be used to handle the initial workspace setup.
    • For most, if not all, changes to the build.gradle file to take effect, Gradle will need to be invoked to re-evaluate the project. This can be done through ‘Refresh’ buttons in the Gradle panels of both of the previously mentioned IDEs.
  6. Generating IDE Launch/Run Configurations:
    • For Eclipse, run the gradle task (). This will generate the Launch Configurations and download any required assets for the game to run. After this has finished, refresh your project.
    • For IntelliJ, run the gradle task (). This will generate the Run Configurations and download any required assets for the game to run. If you encounter an error saying “module not specified”, you can either edit the configuration to select your “main” module or specify it through the property.
    • For VSCode, run the gradle task (). This will generate the Launch Configurations and download any required assets for the game to run.

Блок[]

Класс блока

Для создания блока создайте класс с названием блока в стиле TutorialBlock в пакете патч.blocks и заполните его следующим образом:

public class TutorialBlock extends Block {

  public TutorialBlock() {

    super(Material.Материал); //Задает звук ходьбы, к примеру Rock или Glass

    this.setCreativeTab(CreativeTabs.ВкладкаТворчества); //К примеру BuildingBlocks
    this.setHardness(прочность_блока); //К примеру 3.0F как у руд
    this.setResistance(взрывоустойчивость_блока); //К примеру 15.0F как у руд
    this.setHarvestLevel("инструмент", уровень); //К примеру pickaxe и 0 как деревянная кирка
    this.setRegistryName("идентификатор_блока"); //Используется для подключения моделей и в команде /give
    this.setUnlocalizedName("ключ_локализации"); //Можно использовать идентификатор блока

  }

}

Примечание регистрируемое имя и ключ локализации указывать только в нижнем регистре, используя при надобности нижнее подчёркивание!

Модель

{
  "variants" {
    "normal" { "model" "идентификатор_мода:идентификатор_блока" }
  }
}

Теперь подключим модели. Для этого создайте файл регистрируемое_имя.json в пакете assets.идентификатор_мода.models.block со следующим содержимым:

{
  "parent" "block/cube_all",
  "textures" {
    "all" "идентификатор_мода:blocks/идентификатор_блока"
  }
}

Теперь зададим иконку блока в инвентаре в пакете assets.идентификатор_модификации.models.block с именем идентификатор_блока.json со следующим содержанием:

{
  "parent" "идентификатор_мода:block/идентификатор_блока"
}

Регистрация

Наш блок имеет текстуры и свойства, но его нужно зарегистрировать в игре. Создадим в пакете класс :

public static Block ВАШ_БЛОК = new BlockИмяБлока();

    public static void registerBlocks() {

        setRegister(ВАШ_БЛОК);

    }

    @SideOnly(Side.CLIENT)
    public static void registerBlocksRender() {

        setRender(ВАШ_БЛОК);

    }

    private static void setRegister(Block block) {

        ForgeRegistries.BLOCKS.register(block);
        ForgeRegistries.ITEMS.register(new ItemBlock(block).setRegistryName(block.getRegistryName()));

    }

    @SideOnly(Side.CLIENT)
    private static void setRender(Block block) {

        Minecraft.getMinecraft().getRenderItem().getItemModelMesher().register(Item.getItemFromBlock(block), , new ModelResourceLocation(block.getRegistryName(), "inventory"));

    }

Теперь в главном классе в методе добавьте инструкцию а в методе .

Registering a Block

Blocks must be to function.

Important

A block in the world and a “block” in an inventory are very different things. A block in the world is represented by an , and its behavior defined by an instance of . Meanwhile, an item in an inventory is an , controlled by an . As a bridge between the different worlds of and , there exists the class . is a subclass of that has a field that holds a reference to the it represents. defines some of the behavior of a “block” as an item, like how a right click places the block. It’s possible to have a without an . (E.g. exists a block, but not an item. It is therefore impossible to hold it in an inventory as one.)

When a block is registered, only a block is registered. The block does not automatically have an . To create a basic for a block, one should set the registry name of the to that of its . Custom subclasses of may be used as well. Once an has been registered for a block, can be used to retrieve it. will return if there is no for the , so if you are not certain that there is an for the you are using, check for if returns .

Optionally Registering Blocks

In the past there have been several mods that have allowed users to disable blocks/items in a configuration file. However, you shouldn’t do this. There is no limit on the amount of blocks that can be register, so register all blocks in your mod! If you want a block to be disabled through a configuration file, you should disable the crafting recipe.

Customizing Your Mod Information

Edit the file to customize how your mod is built (the file names, versions, and other things).

Important

Do not edit the section of the build.gradle file, its default text is necessary for ForgeGradle to function.

Almost anything underneath and the marker can be changed, many things can be removed and customized there as well.

There is a whole site dedicated to customizing the forge files — the ForgeGradle cookbook. Once you’re comfortable with your mod setup, you’ll find many useful recipes there.

Simple Customizations

These customizations are highly recommended for all projects.

  • To change the name of the file you build — edit the value of to suit.
  • To change your “maven coordinates” — edit the value of as well.
  • To change the version number — edit the value of .

From Zero to Modding

  1. Obtain a Java 8 Development Kit (JDK) and a 64-bit Java Virtual Machine (JVM). Minecraft and MinecraftForge both compile against Java 8 and as such should be used for development. Using a 32-bit JVM will result in some problems when running the below gradle tasks. You can obtain one from AdoptOpenJDK.
  2. Obtain the Mod Development Kit (MDK) from Forge’s files site.
  3. Extract the downloaded MDK into an empty directory. You should see a bunch of files along with an example mod placed in for you to look at. Only a few of these files are strictly necessary for mod development, and you may reuse these files for all your projects. These files are:
    • the folder
  4. Move the files listed above to a new folder. This will be your mod project folder.
  5. Choose your IDE:
    • Forge only explicitly supports developing with Eclipse, but there are additional run tasks for IntelliJ IDEA or Visual Studio Code environments. However, any environment, from Netbeans to vim/emacs, can be made to work.
    • For both Intellij IDEA and Eclipse, their Gradle integration will handle the rest of the initial workspace setup. This includes downloading packages from Mojang, MinecraftForge, and a few other software sharing sites. For VSCode, the ‘Gradle Tasks’ plugin can be used to handle the initial workspace setup.
    • For most, if not all, changes to the build.gradle file to take effect, Gradle will need to be invoked to re-evaluate the project. This can be done through ‘Refresh’ buttons in the Gradle panels of both of the previously mentioned IDEs.
  6. Generating IDE Launch/Run Configurations:
    • For Eclipse, run the gradle task (). This will generate the Launch Configurations and download any required assets for the game to run. After this has finished, refresh your project.
    • For IntelliJ, run the gradle task (). This will generate the Run Configurations and download any required assets for the game to run. If you encounter an error saying “module not specified”, you can either edit the configuration to select your “main” module or specify it through the property.
    • For VSCode, run the gradle task (). This will generate the Launch Configurations and download any required assets for the game to run.

Customizing Your Mod Information

Edit the file to customize how your mod is built (the file names, versions, and other things).

Important

Do not edit the section of the build.gradle file, its default text is necessary for ForgeGradle to function.

Almost anything underneath the marker can be changed. Many things can be removed and customized there as well.

Simple Customizations

These customizations are highly recommended for all projects.

  • To change the name of the file you build — edit the value of to suit.
  • To change your “maven coordinates” — edit the value of as well.
  • To change the version number — edit the value of .
  • To update the run configurations — replace all occurrences of to the mod id of your mod.

Terminal-free IntelliJ IDEA configuration

These instructions assume that you have created the project folder as described in the steps 1 to 3 of the section above. Because of that, the numbering starts at 4.

  1. Launch IDEA and choose to open/import the file, using the default gradle wrapper choice. While you wait for this process to finish, you can open the gradle panel, which will get filled with the gradle tasks once importing is completed.
  2. Run the task (inside the task group). It will take a few minutes, and use quite a bit of RAM. If it fails, you can add to the in IDEA’s gradle settings window, or edit your global gradle properties.
  3. Once the setup task is done, you will want to run the task, which will configure the project’s run/debug targets.
  4. After it’s done, you should click the blue refresh icon on the gradle panel (there’s another refresh icon on the main toolbar, but that’s not it). This will re-synchronize the IDEA project with the Gradle data, making sure that all the dependencies and settings are up to date.
  5. Finally, assuming you use IDEA 2016 or newer, you will have to fix the classpath module. Go to and in both and , change to point to the task with a name like .

If all the steps worked correctly, you should now be able to choose the Minecraft run tasks from the dropdown, and then click the Run/Debug buttons to test your setup.

Building and Testing Your Mod

  1. To build your mod, run . This will output a file in with the name . This file can be placed in the folder of a Forge enabled Minecraft setup or distributed.
  2. To test run your mod, the easiest way is to use the run configs that were generated when you set up your project. Otherwise, you can run . This will launch Minecraft from the location along with your mod’s code in any source sets specified within your run configurations. The default MDK includes the source set, so any code written within will be applied.
  3. You can also run a dedicated server using the server run config or via . This will launch the Minecraft server with its GUI. After the first run, the server will shut down immediately until the Minecraft EULA is accepted by editing . Once accepted, the server will load and can be accessed via a direct connect to .

Note

It is always advisable to test your mod in a dedicated server environment if it is intended to run there.

Building and Testing Your Mod

  1. To build your mod, run . This will output a file in with the name . This file can be placed in the folder of a forge enabled Minecraft setup, and distributed.
  2. To test run with your mod, the easiest way is to use the run configs that were generated when you set up your project. Otherwise, you can run . This will launch Minecraft from the location, including your mod code. There are various customizations to this command. Consult the ForgeGradle cookbook for more information.
  3. You can also run a dedicated server using the server run config, or . This will launch the Minecraft server with its GUI.

Note

It is always advisable to test your mod in a dedicated server environment if it is intended to run there.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector