Minecraft forge 1.17.1/1.16.5 (modding api)
Содержание:
- Terminal-free IntelliJ IDEA configuration
- From Zero to Modding
- Registering a Block
- Creating a Block
- Building and Testing Your Mod
- From Zero to Modding
- Простая установка Minecraft Forge
- Установка Minecraft Forge на сервер
- Customizing Your Mod Information
- Customizing Your Mod Information
- Building and Testing 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.
- 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.
- 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.
- Once the setup task is done, you will want to run the task, which will configure the project’s run/debug targets.
- 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.
- 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.
From Zero to Modding
- Obtain a source distribution from forge’s files site. (Look for the Mdk file type, or Src in older 1.8/1.7 versions).
- 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
- Move the files listed above to a new folder, this will be your mod project folder.
- 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.
- 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.
- 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 .
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.
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.
Building and Testing Your Mod
- 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.
- 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.
- 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.
From Zero to Modding
- 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.
- Obtain the Mod Development Kit (MDK) from Forge’s files site.
- 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
- Move the files listed above to a new folder. This will be your mod project folder.
- 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.
- 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.
Простая установка Minecraft Forge
- Для Minecraft Forge необходимо установленное ПО Java. Если у Вас его нет, скачайте здесь и запустите установочный файл.
- Скачиваем по одной из ссылок в конце статьи нужную версию установщика Форджа, совместимую с установленным у Вас Minecraft. Смотрите внимательно, чтобы в названии был указан тот же номер версии, что и у игры.
- Правой кнопкой мыши открываем контекстное меню и в нём выбираем Java из строки «Открыть с помощью»:
Откроется окно установщика Forge.
- Выбираем “Install client”. Оставляем папку сохранения по умолчанию, жмём «OK». Ну и ждём успешного окончания установки.
- Запускаем лаунчер.
В списке появилась новая версия с нужным номером и с индексом “forge”.
- Выбираем её и входим в игру.
Слева в углу видим информацию об установке Форджа и у нас также появилась новая кнопка «Моды», которая открывает перечень всех установленных модов
- Наслаждаемся новинкой!
Не забывайте, что если вы установили Фордж, то и моды тоже должны подходить для него. МОДЫ ОТ Fabric НА НЁМ РАБОТАТЬ НЕ БУДУТ! Поэтому обязательно проверяйте совместимость перед установкой.
Установка Модов проще простого — качаете нужные, кидаете всё в папку mods.
Установка Minecraft Forge на сервер
- Начало установки такое же, как описано выше: Java, нужный Forge, его запуск…Только теперь в перечне действий нужно выбрать “Install server” и ОБЯЗАТЕЛЬНО установку нужно вести в новую, пустую, специально созданную папку
Название папки может быть любым.
После всех распаковок и установок в выбранной папке образуется примерно такое содержимое.
- Теперь для оптимальной организации будущего сервера нужно сделать пакетный файл с любым названием и расширением .bat (на сленге — «батник») для запуска нашего приложения Java в консоли компьютера с определённым набором первоначальных установок.Для этого в любом текстовом редакторе нужно ввести следующую строку:
1024M — объём выделяемого стартового и максимального пула оперативки для сервера; forge-1.16.5-36.0.21.jar — сюда вписываете имя своего файла-установщика;nogui — отменяет GUI (будет только консольный режим) для сокращения расхода памяти. Если нагрузка на сервер небольшая (мало плагинов, модов, участников и т.п.), то для удобства визуального контроля можно этот параметр убрать.
Сохраняем наш батник. Например, как start.bat или как Вам больше нравится.Более подробно о запускающем сервер батнике можно почитать здесь.
- Двойным кликом запускаем созданный батник.
Наблюдаем новые добавления в нашей серверной папке
- Открываем вновь образовавшийся файл eula.txt и заменяем значение параметра eula (End User License Agreement — Лицензионное соглашение с конечным пользователем) на true (eula=true).Сохраняем файл с новым значением.
- Повторно запускаем наш start.bat. Наблюдаем за бодрым мельканием команд в консоли и по-ходу не забываем снять блокировки «перестраховщика» Windows:
Дожидаемся заветного завершающего сообщения «For help, type “help”»
- Теперь можно внести несколько корректировок в появившийся файл с серверными настройками — server.properties:— строчку online-mode=true меняем на online-mode=false (для «пробных» версий игры);— в строке server-ip= указываем IP нашего сервера (для игры в домашней локалке это будет адрес компа с установленным сервером: 192.168.0.XXX, или похоже — смотрите у себя в сетевых настройках);— max-players=20 это ограничение числа игроков на сервере.
- Настройка закончена. Можно сделать пробный запуск нашего сервера, прежде чем отправить его по ftp на своё место.
Мой комп сейчас, увы, не справляется с выделением Гига оперативки. Надеюсь, у Вас будет лучше.
Заканчивать работу сервера лучше не простым закрытием нашего GUI или консоли, а командой /stop.
Подключение к вновь созданному серверу по дополнительному IP
- Снова наслаждаемся новинкой. Теперь уже в сети.
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:
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 .
Building and Testing Your Mod
- 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.
- 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.
- 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.