Fix Forge 50 (1.20.6) (#219)

Co-authored-by: shedaniel <daniel@shedaniel.me>
Co-authored-by: Juuz <6596629+Juuxel@users.noreply.github.com>
This commit is contained in:
Jab125
2024-07-02 02:08:55 +10:00
committed by Juuz
parent 7dbd3c62e5
commit 9e4a70f742
25 changed files with 719 additions and 27 deletions

View File

@@ -148,3 +148,53 @@ jobs:
with:
name: Reproducible Build ${{ matrix.os }} (${{ matrix.java }}) Results
path: build/reports/
# Special case this test to run on Java 21
neoForge1206Test:
needs: build
strategy:
fail-fast: false
matrix:
java: [ 21 ]
os: [ ubuntu-22.04 ]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
java-version: ${{ matrix.java }}
distribution: 'temurin'
- run: ./gradlew test --tests *NeoForge1206Test --stacktrace --warning-mode fail
- uses: actions/upload-artifact@v4
if: ${{ failure() }}
with:
name: NeoForge 1.20.6 Build Results
# Special case this test to run on Java 21
forge1206Test:
needs: build
strategy:
fail-fast: false
matrix:
java: [ 21 ]
os: [ ubuntu-22.04 ]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
java-version: ${{ matrix.java }}
distribution: 'temurin'
- run: ./gradlew test --tests *Forge1206Test --stacktrace --warning-mode fail
- uses: actions/upload-artifact@v4
if: ${{ failure() }}
with:
name: Forge 1.20.6 Build Results
path: build/reports/

View File

@@ -424,6 +424,11 @@ tasks.register('writeActionsTestMatrix') {
return
}
if (it.name.endsWith("NeoForge1206Test.groovy") || it.name.endsWith("Forge1206Test.groovy")) {
// Arch: The 1.20.6 tests require Java 21
return
}
def className = it.path.toString().replace(".groovy", "")
className = className.substring(className.lastIndexOf("integration/") + "integration/".length()).replace('/', '.')

View File

@@ -19,7 +19,7 @@ access-transformers-new = "8.0.5"
access-transformers-neo = "10.0.2"
unprotect = "1.2.0"
asm = "9.7"
union-relauncher = "1.0.0"
union-relauncher = "1.1.0"
access-transformers-log4j = "2.17.1"
[libraries]

View File

@@ -37,6 +37,14 @@ public final class IntermediaryNamespaces {
return intermediaryNamespace(project).toString();
}
/**
* Returns the runtime intermediary namespace of the project.
* This is the namespace used in the compiled jar.
*/
public static String runtimeIntermediary(Project project) {
return runtimeIntermediaryNamespace(project).toString();
}
/**
* Returns the intermediary namespace of the project.
*/
@@ -49,6 +57,15 @@ public final class IntermediaryNamespaces {
};
}
/**
* Returns the intermediary namespace of the project.
*/
public static MappingsNamespace runtimeIntermediaryNamespace(Project project) {
LoomGradleExtension extension = LoomGradleExtension.get(project);
if (extension.isForge() && extension.getForgeProvider().usesMojangAtRuntime()) return MappingsNamespace.MOJANG;
return intermediaryNamespace(project);
}
/**
* Potentially replaces the remapping target namespace for mixin refmaps.
*
@@ -62,6 +79,6 @@ public final class IntermediaryNamespaces {
* @return the correct namespace to use
*/
public static String replaceMixinIntermediaryNamespace(Project project, String namespace) {
return namespace.equals(intermediary(project)) ? MappingsNamespace.INTERMEDIARY.toString() : namespace;
return namespace.equals(runtimeIntermediary(project)) ? MappingsNamespace.INTERMEDIARY.toString() : namespace;
}
}

View File

@@ -165,7 +165,7 @@ public class ModProcessor {
private void remapJars(List<ModDependency> remapList) throws IOException {
final LoomGradleExtension extension = LoomGradleExtension.get(project);
final MappingConfiguration mappingConfiguration = extension.getMappingConfiguration();
String fromM = IntermediaryNamespaces.intermediary(project);
String fromM = IntermediaryNamespaces.runtimeIntermediary(project);
Stopwatch stopwatch = Stopwatch.createStarted();
Set<String> knownIndyBsms = new HashSet<>(extension.getKnownIndyBsms().get());

View File

@@ -60,6 +60,10 @@ public class ForgeProvider extends DependencyProvider {
return version;
}
public boolean usesMojangAtRuntime() {
return platform == ModPlatform.NEOFORGE || version.getMajorVersion() >= Constants.Forge.MIN_USE_MOJANG_NS_VERSION;
}
public File getGlobalCache() {
if (globalCache == null) {
globalCache = getMinecraftProvider().dir(platform.id() + "/" + version.getCombined());

View File

@@ -35,6 +35,7 @@ import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
@@ -42,10 +43,10 @@ import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.apache.tools.ant.util.StringUtils;
import com.google.common.base.Stopwatch;
import com.google.gson.JsonObject;
import dev.architectury.loom.util.MappingOption;
import org.apache.tools.ant.util.StringUtils;
import org.gradle.api.Project;
import org.gradle.api.artifacts.Configuration;
import org.jetbrains.annotations.Nullable;
@@ -211,28 +212,20 @@ public class MappingConfiguration {
// Generate the Mojmap-merged mappings if needed.
// Note that this needs to happen before manipulateMappings for FieldMigratedMappingConfiguration.
if (Files.notExists(tinyMappingsWithMojang) || extension.refreshDeps()) {
final Stopwatch stopwatch = Stopwatch.createStarted();
final MappingContext context = new GradleMappingContext(project, "tmp-neoforge");
try (Tiny2FileWriter writer = new Tiny2FileWriter(Files.newBufferedWriter(tinyMappingsWithMojang), false)) {
ForgeMappingsMerger.mergeMojang(context, tinyMappings, null, true).accept(writer);
}
project.getLogger().info(":merged mojang mappings in {}", stopwatch.stop());
mergeMojang(project, tinyMappings, tinyMappingsWithMojang);
}
}
if (extension.shouldGenerateSrgTiny()) {
if (Files.notExists(tinyMappingsWithSrg) || extension.refreshDeps()) {
// Merge tiny mappings with srg
Stopwatch stopwatch = Stopwatch.createStarted();
ForgeMappingsMerger.ExtraMappings extraMappings = ForgeMappingsMerger.ExtraMappings.ofMojmapTsrg(getMojmapSrgFileIfPossible(project));
try (Tiny2FileWriter writer = new Tiny2FileWriter(Files.newBufferedWriter(tinyMappingsWithSrg), false)) {
ForgeMappingsMerger.mergeSrg(getRawSrgFile(project), tinyMappings, extraMappings, true).accept(writer);
if (extension.isForge() && extension.getForgeProvider().usesMojangAtRuntime()) {
Path tmp = Files.createTempFile("mappings", ".tiny");
mergeMojang(project, tinyMappings, tmp);
mergeSrg(project, tmp, tinyMappingsWithSrg);
Files.deleteIfExists(tmp);
} else {
mergeSrg(project, tinyMappings, tinyMappingsWithSrg);
}
project.getLogger().info(":merged srg mappings in " + stopwatch.stop());
}
}
@@ -288,6 +281,28 @@ public class MappingConfiguration {
}
}
private static void mergeMojang(Project project, Path source, Path target) throws IOException {
final Stopwatch stopwatch = Stopwatch.createStarted();
final MappingContext context = new GradleMappingContext(project, "tmp-mojang");
try (Tiny2FileWriter writer = new Tiny2FileWriter(Files.newBufferedWriter(target, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING), false)) {
ForgeMappingsMerger.mergeMojang(context, source, null, true).accept(writer);
}
project.getLogger().info(":merged mojang mappings in {}", stopwatch.stop());
}
private static void mergeSrg(Project project, Path source, Path target) throws IOException {
Stopwatch stopwatch = Stopwatch.createStarted();
ForgeMappingsMerger.ExtraMappings extraMappings = ForgeMappingsMerger.ExtraMappings.ofMojmapTsrg(getMojmapSrgFileIfPossible(project));
try (Tiny2FileWriter writer = new Tiny2FileWriter(Files.newBufferedWriter(target, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING), false)) {
ForgeMappingsMerger.mergeSrg(getRawSrgFile(project), source, extraMappings, true).accept(writer);
}
project.getLogger().info(":merged srg mappings in " + stopwatch.stop());
}
protected void manipulateMappings(Project project, Path mappingsJar) throws IOException {
}

View File

@@ -50,10 +50,10 @@ public abstract class MixinExtensionApiImpl implements MixinExtensionAPI {
public MixinExtensionApiImpl(Project project) {
this.project = Objects.requireNonNull(project);
this.useMixinAp = project.getObjects().property(Boolean.class)
.convention(project.provider(() -> !LoomGradleExtension.get(project).isNeoForge()));
.convention(project.provider(() -> !LoomGradleExtension.get(project).isNeoForge() && (!LoomGradleExtension.get(project).isForge() || !LoomGradleExtension.get(project).getForgeProvider().usesMojangAtRuntime())));
this.refmapTargetNamespace = project.getObjects().property(String.class)
.convention(project.provider(() -> IntermediaryNamespaces.intermediary(project)));
.convention(project.provider(() -> IntermediaryNamespaces.runtimeIntermediary(project)));
this.refmapTargetNamespace.finalizeValueOnRead();
this.messages = project.getObjects().mapProperty(String.class, String.class);

View File

@@ -116,7 +116,7 @@ public abstract class AbstractRemapJarTask extends Jar {
@Inject
public AbstractRemapJarTask() {
getSourceNamespace().convention(MappingsNamespace.NAMED.toString()).finalizeValueOnRead();
getTargetNamespace().convention(IntermediaryNamespaces.intermediary(getProject())).finalizeValueOnRead();
getTargetNamespace().convention(getProject().provider(() -> IntermediaryNamespaces.runtimeIntermediary(getProject()))).finalizeValueOnRead();
getRemapperIsolation().convention(true).finalizeValueOnRead();
getIncludesClientOnlyClasses().convention(false).finalizeValueOnRead();
getJarType().finalizeValueOnRead();

View File

@@ -198,6 +198,11 @@ public class Constants {
public static final String UNION_RELAUNCHER_MAIN_CLASS = "juuxel.unionrelauncher.UnionRelauncher";
public static final String UNION_RELAUNCHER_MAIN_CLASS_PROPERTY = "unionRelauncher.mainClass";
/**
* The minimum version of Forge that uses "mojang" as the namespace in production.
*/
public static final int MIN_USE_MOJANG_NS_VERSION = 50;
private Forge() {
}
}

View File

@@ -65,7 +65,7 @@ public class SourceRemapper {
private Mercury mercury;
public SourceRemapper(Project project, SharedServiceManager serviceManager, boolean toNamed) {
this(project, serviceManager, toNamed ? IntermediaryNamespaces.intermediary(project) : "named", !toNamed ? IntermediaryNamespaces.intermediary(project) : "named");
this(project, serviceManager, toNamed ? IntermediaryNamespaces.runtimeIntermediary(project) : "named", !toNamed ? IntermediaryNamespaces.runtimeIntermediary(project) : "named");
}
public SourceRemapper(Project project, SharedServiceManager serviceManager, String from, String to) {

View File

@@ -61,7 +61,7 @@ public final class CoreModClassRemapper {
public static void remapJar(Project project, ModPlatform platform, Path jar, MappingTree mappings) throws IOException {
final Logger logger = project.getLogger();
final String sourceNamespace = IntermediaryNamespaces.intermediary(project);
final String sourceNamespace = IntermediaryNamespaces.runtimeIntermediary(project);
try (FileSystemUtil.Delegate fs = FileSystemUtil.getJarFileSystem(jar, false)) {
Path coremodsJsonPath = fs.getPath("META-INF", "coremods.json");

View File

@@ -65,6 +65,7 @@ import net.fabricmc.mappingio.tree.MemoryMappingTree;
*/
public final class ForgeMappingsMerger {
private static final List<String> INPUT_NAMESPACES = List.of("official", "intermediary", "named");
private static final List<String> INPUT_NAMESPACES_WITH_MOJANG = List.of("official", "mojang", "intermediary", "named");
private final MemoryMappingTree newNs;
private final MemoryMappingTree src;
private final MemoryMappingTree output;
@@ -111,8 +112,8 @@ public final class ForgeMappingsMerger {
List<String> inputNamespaces = new ArrayList<>(src.getDstNamespaces());
inputNamespaces.add(0, src.getSrcNamespace());
if (!inputNamespaces.equals(INPUT_NAMESPACES)) {
throw new MappingException("Mapping file " + tiny + " does not have 'official, intermediary, named' as its namespaces! Found: " + inputNamespaces);
if (!inputNamespaces.equals(INPUT_NAMESPACES) && !inputNamespaces.equals(INPUT_NAMESPACES_WITH_MOJANG)) {
throw new MappingException("Mapping file " + tiny + " does not have 'official(, mojang), intermediary, named' as its namespaces! Found: " + inputNamespaces);
}
return src;

View File

@@ -0,0 +1,60 @@
/*
* This file is part of fabric-loom, licensed under the MIT License (MIT).
*
* Copyright (c) 2024 FabricMC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.fabricmc.loom.test.integration.forge
import spock.lang.Specification
import spock.lang.Unroll
import net.fabricmc.loom.test.util.GradleProjectTestTrait
import static net.fabricmc.loom.test.LoomTestConstants.DEFAULT_GRADLE
import static org.gradle.testkit.runner.TaskOutcome.SUCCESS
class Forge1206Test extends Specification implements GradleProjectTestTrait {
@Unroll
def "build #mcVersion #neoforgeVersion #mappings #patches"() {
if (Integer.valueOf(System.getProperty("java.version").split("\\.")[0]) < 21) {
println("This test requires Java 21. Currently you have Java ${System.getProperty("java.version")}.")
return
}
setup:
def gradle = gradleProject(project: "forge/1206", version: DEFAULT_GRADLE)
gradle.buildGradle.text = gradle.buildGradle.text.replace('@MCVERSION@', mcVersion)
.replace('@FORGEVERSION@', neoforgeVersion)
.replace('MAPPINGS', mappings) // Spotless doesn't like the @'s
.replace('PATCHES', patches)
when:
def result = gradle.run(task: "build")
then:
result.task(":build").outcome == SUCCESS
where:
mcVersion | neoforgeVersion | mappings | patches
'1.20.6' | '1.20.6-50.1.3' | 'loom.officialMojangMappings()' | ''
}
}

View File

@@ -0,0 +1,61 @@
/*
* This file is part of fabric-loom, licensed under the MIT License (MIT).
*
* Copyright (c) 2024 FabricMC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.fabricmc.loom.test.integration.neoforge
import spock.lang.Specification
import spock.lang.Unroll
import net.fabricmc.loom.test.util.GradleProjectTestTrait
import static net.fabricmc.loom.test.LoomTestConstants.DEFAULT_GRADLE
import static org.gradle.testkit.runner.TaskOutcome.SUCCESS
class NeoForge1206Test extends Specification implements GradleProjectTestTrait {
@Unroll
def "build #mcVersion #neoforgeVersion #mappings #patches"() {
if (Integer.valueOf(System.getProperty("java.version").split("\\.")[0]) < 21) {
println("This test requires Java 21. Currently you have Java ${System.getProperty("java.version")}.")
return
}
setup:
def gradle = gradleProject(project: "neoforge/1206", version: DEFAULT_GRADLE)
gradle.buildGradle.text = gradle.buildGradle.text.replace('@MCVERSION@', mcVersion)
.replace('@NEOFORGEVERSION@', neoforgeVersion)
.replace('MAPPINGS', mappings) // Spotless doesn't like the @'s
.replace('PATCHES', patches)
when:
def result = gradle.run(task: "build")
then:
result.task(":build").outcome == SUCCESS
where:
mcVersion | neoforgeVersion | mappings | patches
'1.20.6' | '20.6.5-beta' | 'loom.officialMojangMappings()' | ''
'1.20.6' | '20.6.5-beta' | "'net.fabricmc:yarn:1.20.6+build.1:v2'" | "'dev.architectury:yarn-mappings-patch-neoforge:1.20.5+build.3'"
}
}

View File

@@ -0,0 +1,92 @@
plugins {
id 'dev.architectury.loom'
id 'maven-publish'
}
java {
sourceCompatibility = JavaVersion.VERSION_21
targetCompatibility = JavaVersion.VERSION_21
}
base {
archivesName = project.archives_base_name
}
version = project.mod_version
group = project.maven_group
def mcVersion = "@MCVERSION@"
def forgeVersion = "@FORGEVERSION@"
repositories {
// Add repositories to retrieve artifacts from in here.
// You should only use this when depending on other mods because
// Loom adds the essential maven repositories to download Minecraft and libraries from automatically.
// See https://docs.gradle.org/current/userguide/declaring_repositories.html
// for more information about repositories.
}
dependencies {
// To change the versions see the gradle.properties file
minecraft "com.mojang:minecraft:$mcVersion"
if ("MAPPINGS".equals("loom.officialMojangMappings()")) {
mappings loom.officialMojangMappings()
} else {
mappings loom.layered {
it.mappings(MAPPINGS)
it.mappings(PATCHES)
}
}
forge "net.minecraftforge:forge:$forgeVersion"
}
tasks.withType(JavaCompile).configureEach {
it.options.release = 21
}
java {
// Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task
// if it is present.
// If you remove this line, sources will not be generated.
withSourcesJar()
}
jar {
from("LICENSE") {
rename { "${it}_${project.archivesBaseName}"}
}
}
// configure the maven publication
publishing {
publications {
mavenJava(MavenPublication) {
// add all the jars that should be included when publishing to maven
artifact(remapJar) {
builtBy remapJar
}
artifact(sourcesJar) {
builtBy remapSourcesJar
}
}
}
// See https://docs.gradle.org/current/userguide/publishing_maven.html for information on how to set up publishing.
repositories {
// Add repositories to publish to here.
// Notice: This block does NOT have the same function as the block in the top level.
// The repositories here will be used for publishing your artifact, not for
// retrieving dependencies.
}
}
processResources {
doLast {
java.nio.file.Path.of(outputs.files.asPath).resolve("META-INF/MANIFEST.MF").text = "Manifest-Version: 1.0\n" +
"Automatic-Module-Name: ignoreme\n"
}
}
configurations.all {
resolutionStrategy.force("net.sf.jopt-simple:jopt-simple:5.0.4")
}

View File

@@ -0,0 +1,11 @@
# Done to increase the memory available to gradle.
org.gradle.jvmargs=-Xmx1G
# Mod Properties
mod_version = 1.0.0
maven_group = com.example
archives_base_name = fabric-example-mod
# Dependencies
# currently not on the main fabric site, check on the maven: https://maven.fabricmc.net/net/fabricmc/fabric-api/fabric-api
loom.platform = forge

View File

@@ -0,0 +1,2 @@
rootProject.name = "fabric-example-mod"

View File

@@ -0,0 +1,64 @@
package com.example.examplemod;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.Item;
import net.minecraftforge.common.ForgeConfigSpec;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.config.ModConfigEvent;
import net.minecraftforge.registries.ForgeRegistries;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
// An example config class. This is not required, but it's a good idea to have one to keep your config organized.
// Demonstrates how to use Forge's config APIs
@Mod.EventBusSubscriber(modid = ExampleMod.MODID, bus = Mod.EventBusSubscriber.Bus.MOD)
public class Config
{
private static final ForgeConfigSpec.Builder BUILDER = new ForgeConfigSpec.Builder();
private static final ForgeConfigSpec.BooleanValue LOG_DIRT_BLOCK = BUILDER
.comment("Whether to log the dirt block on common setup")
.define("logDirtBlock", true);
private static final ForgeConfigSpec.IntValue MAGIC_NUMBER = BUILDER
.comment("A magic number")
.defineInRange("magicNumber", 42, 0, Integer.MAX_VALUE);
public static final ForgeConfigSpec.ConfigValue<String> MAGIC_NUMBER_INTRODUCTION = BUILDER
.comment("What you want the introduction message to be for the magic number")
.define("magicNumberIntroduction", "The magic number is... ");
// a list of strings that are treated as resource locations for items
private static final ForgeConfigSpec.ConfigValue<List<? extends String>> ITEM_STRINGS = BUILDER
.comment("A list of items to log on common setup.")
.defineListAllowEmpty("items", List.of("minecraft:iron_ingot"), Config::validateItemName);
static final ForgeConfigSpec SPEC = BUILDER.build();
public static boolean logDirtBlock;
public static int magicNumber;
public static String magicNumberIntroduction;
public static Set<Item> items;
private static boolean validateItemName(final Object obj)
{
return obj instanceof final String itemName && ForgeRegistries.ITEMS.containsKey(new ResourceLocation(itemName));
}
@SubscribeEvent
static void onLoad(final ModConfigEvent event)
{
logDirtBlock = LOG_DIRT_BLOCK.get();
magicNumber = MAGIC_NUMBER.get();
magicNumberIntroduction = MAGIC_NUMBER_INTRODUCTION.get();
// convert the list of strings into a set of items
items = ITEM_STRINGS.get().stream()
.map(itemName -> ForgeRegistries.ITEMS.getValue(new ResourceLocation(itemName)))
.collect(Collectors.toSet());
}
}

View File

@@ -0,0 +1,128 @@
package com.example.examplemod;
import com.mojang.logging.LogUtils;
import net.minecraft.client.Minecraft;
import net.minecraft.core.registries.Registries;
import net.minecraft.world.food.FoodProperties;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.CreativeModeTab;
import net.minecraft.world.item.CreativeModeTabs;
import net.minecraft.world.item.Item;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraft.world.level.material.MapColor;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.BuildCreativeModeTabContentsEvent;
import net.minecraftforge.event.server.ServerStartingEvent;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.ModLoadingContext;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.config.ModConfig;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.RegistryObject;
import org.slf4j.Logger;
// The value here should match an entry in the META-INF/mods.toml file
@Mod(ExampleMod.MODID)
public class ExampleMod
{
// Define mod id in a common place for everything to reference
public static final String MODID = "examplemod";
// Directly reference a slf4j logger
private static final Logger LOGGER = LogUtils.getLogger();
// Create a Deferred Register to hold Blocks which will all be registered under the "examplemod" namespace
public static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, MODID);
// Create a Deferred Register to hold Items which will all be registered under the "examplemod" namespace
public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, MODID);
// Create a Deferred Register to hold CreativeModeTabs which will all be registered under the "examplemod" namespace
public static final DeferredRegister<CreativeModeTab> CREATIVE_MODE_TABS = DeferredRegister.create(Registries.CREATIVE_MODE_TAB, MODID);
// Creates a new Block with the id "examplemod:example_block", combining the namespace and path
public static final RegistryObject<Block> EXAMPLE_BLOCK = BLOCKS.register("example_block", () -> new Block(BlockBehaviour.Properties.of().mapColor(MapColor.STONE)));
// Creates a new BlockItem with the id "examplemod:example_block", combining the namespace and path
public static final RegistryObject<Item> EXAMPLE_BLOCK_ITEM = ITEMS.register("example_block", () -> new BlockItem(EXAMPLE_BLOCK.get(), new Item.Properties()));
// Creates a new food item with the id "examplemod:example_id", nutrition 1 and saturation 2
public static final RegistryObject<Item> EXAMPLE_ITEM = ITEMS.register("example_item", () -> new Item(new Item.Properties().food(new FoodProperties.Builder()
.alwaysEdible().nutrition(1).saturationModifier(2f).build())));
// Creates a creative tab with the id "examplemod:example_tab" for the example item, that is placed after the combat tab
public static final RegistryObject<CreativeModeTab> EXAMPLE_TAB = CREATIVE_MODE_TABS.register("example_tab", () -> CreativeModeTab.builder()
.withTabsBefore(CreativeModeTabs.COMBAT)
.icon(() -> EXAMPLE_ITEM.get().getDefaultInstance())
.displayItems((parameters, output) -> {
output.accept(EXAMPLE_ITEM.get()); // Add the example item to the tab. For your own tabs, this method is preferred over the event
}).build());
public ExampleMod()
{
IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();
// Register the commonSetup method for modloading
modEventBus.addListener(this::commonSetup);
// Register the Deferred Register to the mod event bus so blocks get registered
BLOCKS.register(modEventBus);
// Register the Deferred Register to the mod event bus so items get registered
ITEMS.register(modEventBus);
// Register the Deferred Register to the mod event bus so tabs get registered
CREATIVE_MODE_TABS.register(modEventBus);
// Register ourselves for server and other game events we are interested in
MinecraftForge.EVENT_BUS.register(this);
// Register the item to a creative tab
modEventBus.addListener(this::addCreative);
// Register our mod's ForgeConfigSpec so that Forge can create and load the config file for us
ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, Config.SPEC);
}
private void commonSetup(final FMLCommonSetupEvent event)
{
// Some common setup code
LOGGER.info("HELLO FROM COMMON SETUP");
if (Config.logDirtBlock)
LOGGER.info("DIRT BLOCK >> {}", ForgeRegistries.BLOCKS.getKey(Blocks.DIRT));
LOGGER.info(Config.magicNumberIntroduction + Config.magicNumber);
Config.items.forEach((item) -> LOGGER.info("ITEM >> {}", item.toString()));
}
// Add the example block item to the building blocks tab
private void addCreative(BuildCreativeModeTabContentsEvent event)
{
if (event.getTabKey() == CreativeModeTabs.BUILDING_BLOCKS)
event.accept(EXAMPLE_BLOCK_ITEM);
}
// You can use SubscribeEvent and let the Event Bus discover methods to call
@SubscribeEvent
public void onServerStarting(ServerStartingEvent event)
{
// Do something when the server starts
LOGGER.info("HELLO from server starting");
}
// You can use EventBusSubscriber to automatically register all static methods in the class annotated with @SubscribeEvent
@Mod.EventBusSubscriber(modid = MODID, bus = Mod.EventBusSubscriber.Bus.MOD, value = Dist.CLIENT)
public static class ClientModEvents
{
@SubscribeEvent
public static void onClientSetup(FMLClientSetupEvent event)
{
// Some client setup code
LOGGER.info("HELLO FROM CLIENT SETUP");
LOGGER.info("MINECRAFT NAME >> {}", Minecraft.getInstance().getUser().getName());
}
}
}

View File

@@ -0,0 +1,73 @@
# This is an example mods.toml file. It contains the data relating to the loading mods.
# There are several mandatory fields (#mandatory), and many more that are optional (#optional).
# The overall format is standard TOML format, v0.5.0.
# Note that there are a couple of TOML lists in this file.
# Find more information on toml format here: https://github.com/toml-lang/toml
# The name of the mod loader type to load - for regular FML @Mod mods it should be javafml
modLoader="javafml" #mandatory
# A version range to match for said mod loader - for regular FML @Mod it will be the forge version
loaderVersion="*" #mandatory This is typically bumped every Minecraft version by Forge. See our download page for lists of versions.
# The license for you mod. This is mandatory metadata 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="Testmod"
# A URL to refer people to when problems occur with this mod
#issueTrackerURL="https://change.me.to.your.issue.tracker.example.invalid/" #optional
# If your mod is purely client-side and has no multiplayer functionality (be it dedicated servers or Open to LAN),
# set this to true, and Forge will set the correct displayTest for you and skip loading your mod on dedicated servers.
#clientSideOnly=true #optional - defaults to false if absent
# A list of mods - how many allowed here is determined by the individual mod loader
[[mods]] #mandatory
# The modid of the mod
modId="examplemod" #mandatory
# The version number of the mod
version="1.0.0" #mandatory
# A display name for the mod
displayName="Example Mod" #mandatory
# A URL to query for updates for this mod. See the JSON update specification https://docs.minecraftforge.net/en/latest/misc/updatechecker/
#updateJSONURL="https://change.me.example.invalid/updates.json" #optional
# A URL for the "homepage" for this mod, displayed in the mod UI
#displayURL="https://change.me.to.your.mods.homepage.example.invalid/" #optional
# A file name (in the root of the mod JAR) containing a logo for display
#logoFile="examplemod.png" #optional
# A text field displayed in the mod UI
#credits="" #optional
# A text field displayed in the mod UI
authors="Architectury" #optional
# Display Test controls the display for your mod in the server connection screen
# MATCH_VERSION means that your mod will cause a red X if the versions on client and server differ. This is the default behaviour and should be what you choose if you have server and client elements to your mod.
# IGNORE_SERVER_VERSION means that your mod will not cause a red X if it's present on the server but not on the client. This is what you should use if you're a server only mod.
# IGNORE_ALL_VERSION means that your mod will not cause a red X if it's present on the client or the server. This is a special case and should only be used if your mod has no server component.
# NONE means that no display test is set on your mod. You need to do this yourself, see IExtensionPoint.DisplayTest for more information. You can define any scheme you wish with this value.
# IMPORTANT NOTE: this is NOT an instruction as to which environments (CLIENT or DEDICATED SERVER) your mod loads on. Your mod should load (and maybe do nothing!) whereever it finds itself.
#displayTest="MATCH_VERSION" # if nothing is specified, MATCH_VERSION is the default when clientSideOnly=false, otherwise IGNORE_ALL_VERSION when clientSideOnly=true (#optional)
# The description text for the mod (multi line!) (#mandatory)
description='''This is a test mod'''
# A dependency - use the . to indicate dependency for a specific modid. Dependencies are optional.
[[dependencies.examplemod]] #optional
# the modid of the dependency
modId="forge" #mandatory
# Does this dependency have to exist - if not, ordering below must be specified
mandatory=true #mandatory
# The version range of the dependency
versionRange="[50,)" #mandatory
# An ordering relationship for the dependency - BEFORE or AFTER required if the dependency is not mandatory
# BEFORE - This mod is loaded BEFORE the dependency
# AFTER - This mod is loaded AFTER the dependency
ordering="NONE"
# Side this dependency is applied on - BOTH, CLIENT, or SERVER
side="BOTH"
# Here's another dependency
[[dependencies.examplemod]]
modId="minecraft"
mandatory=true
# This version range declares a minimum of the current minecraft version up to but not including the next major version
versionRange="[1.20.6,)"
ordering="NONE"
side="BOTH"
# Features are specific properties of the game environment, that you may want to declare you require. This example declares
# that your mod requires GL version 3.2 or higher. Other features will be added. They are side aware so declaring this won't
# stop your mod loading on the server for example.
#[features.${mod_id}]
#openGLVersion="[3.2,)"

View File

@@ -0,0 +1,8 @@
{
"pack": {
"forge:resource_pack_format": 32,
"forge:data_pack_format": 41,
"pack_format": 32,
"description": "Example mod"
}
}

View File

@@ -0,0 +1,83 @@
plugins {
id 'dev.architectury.loom'
id 'maven-publish'
}
java {
sourceCompatibility = JavaVersion.VERSION_21
targetCompatibility = JavaVersion.VERSION_21
}
base {
archivesName = project.archives_base_name
}
version = project.mod_version
group = project.maven_group
def mcVersion = "@MCVERSION@"
def neoforgeVersion = "@NEOFORGEVERSION@"
repositories {
// Add repositories to retrieve artifacts from in here.
// You should only use this when depending on other mods because
// Loom adds the essential maven repositories to download Minecraft and libraries from automatically.
// See https://docs.gradle.org/current/userguide/declaring_repositories.html
// for more information about repositories.
maven { url "https://maven.neoforged.net/releases/" }
}
dependencies {
// To change the versions see the gradle.properties file
minecraft "com.mojang:minecraft:$mcVersion"
if ("MAPPINGS".equals("loom.officialMojangMappings()")) {
mappings loom.officialMojangMappings()
} else {
mappings loom.layered {
it.mappings(MAPPINGS)
it.mappings(PATCHES)
}
}
neoForge "net.neoforged:neoforge:$neoforgeVersion"
}
tasks.withType(JavaCompile).configureEach {
it.options.release = 21
}
java {
// Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task
// if it is present.
// If you remove this line, sources will not be generated.
withSourcesJar()
}
jar {
from("LICENSE") {
rename { "${it}_${project.archivesBaseName}"}
}
}
// configure the maven publication
publishing {
publications {
mavenJava(MavenPublication) {
// add all the jars that should be included when publishing to maven
artifact(remapJar) {
builtBy remapJar
}
artifact(sourcesJar) {
builtBy remapSourcesJar
}
}
}
// See https://docs.gradle.org/current/userguide/publishing_maven.html for information on how to set up publishing.
repositories {
// Add repositories to publish to here.
// Notice: This block does NOT have the same function as the block in the top level.
// The repositories here will be used for publishing your artifact, not for
// retrieving dependencies.
}
}

View File

@@ -0,0 +1,11 @@
# Done to increase the memory available to gradle.
org.gradle.jvmargs=-Xmx1G
# Mod Properties
mod_version = 1.0.0
maven_group = com.example
archives_base_name = fabric-example-mod
# Dependencies
# currently not on the main fabric site, check on the maven: https://maven.fabricmc.net/net/fabricmc/fabric-api/fabric-api
loom.platform = neoforge

View File

@@ -0,0 +1,2 @@
rootProject.name = "fabric-example-mod"