Example: a multi-loader mod

Every file of a mod that builds four jars from one codebase for all loaders from Minecraft 1.7.10 to 26.3, each carrying the same Settings Saver plugin.

Last updated

On this page

Complete example

A complete Gradle project for a mod that ships as four jars covering Fabric, Quilt, Legacy Fabric, Forge and NeoForge from Minecraft 1.7.10 to 26.3. The Settings Saver integration is written once, in the shared code, and lands in every jar. It follows Build one integration for every loader, which explains the reasoning.

The project compiles without downloading Minecraft or Forge: the entry classes only touch each loader's @Mod annotation, which comes from small compile-only stubs.

Files#

mymod/
├── settings.gradle.kts
├── build.gradle.kts
└── src/
    ├── main/java/com/example/mymod/           shared: the JDK only
    │   ├── MyMod.java
    │   └── MyConfig.java
    ├── main/java/com/example/mymod/compat/    shared: the only code that uses the Settings Saver API
    │   ├── MyModSettingsSaver.java
    │   └── KeyNameFix.java
    ├── main/resources/META-INF/services/dev.xichil.settingssaver.api.v1.SettingsSaverPlugin
    ├── fabric/                                Fabric, Quilt, Legacy Fabric
    │   ├── java/com/example/mymod/loader/FabricEntry.java
    │   └── resources/fabric.mod.json
    ├── modlauncher/                           Forge 1.13.2+, NeoForge
    │   ├── java/com/example/mymod/loader/ForgeEntry.java
    │   ├── java/com/example/mymod/loader/NeoForgeEntry.java
    │   └── resources/META-INF/mods.toml, META-INF/neoforge.mods.toml, pack.mcmeta
    ├── forgeLegacy/                           Forge 1.8 – 1.12.2
    │   ├── java/com/example/mymod/loader/ForgeLegacyEntry.java
    │   └── resources/mcmod.info
    ├── forgeCpw/                              Forge 1.7.10
    │   ├── java/com/example/mymod/loader/ForgeCpwEntry.java
    │   └── resources/mcmod.info
    ├── stubsModlauncher/java/…                compile-only @Mod stubs, never in a jar
    ├── stubsForgeLegacy/java/…
    └── stubsForgeCpw/java/…

./gradlew build writes build/libs/mymod-3.1.0-fabric.jar, -modlauncher.jar, -forge-1.8-1.12.2.jar and -forge-1.7.10.jar.

Build scripts#

settings.gradle.kts
rootProject.name = "mymod"
build.gradle.kts
plugins {
    java
}

group = "com.example"
version = "3.1.0"                      // keep MyMod.VERSION the same

repositories {
    mavenCentral()
    maven("https://maven.xichil.dev")
    maven("https://maven.fabricmc.net/")
}

// Java 8 bytecode runs on every Minecraft version from 1.7.10 to 26.3.
tasks.withType<JavaCompile>().configureEach {
    options.release = 8
}

val main: SourceSet = sourceSets["main"]

dependencies {
    // Only the shared code uses the API. Never bundled: Settings Saver's jar provides it.
    compileOnly("dev.xichil.settingssaver:settingssaver-api:1.0.0")
}

// Compile-only stubs of the Forge annotations: on the entry classes' class path, never in a jar.
val stubsModlauncher: SourceSet = sourceSets.create("stubsModlauncher")
val stubsForgeLegacy: SourceSet = sourceSets.create("stubsForgeLegacy")
val stubsForgeCpw: SourceSet = sourceSets.create("stubsForgeCpw")

/** One jar per loader family: its source set, the jar's classifier, and what its entry class compiles against. */
data class Family(val sourceSet: String, val classifier: String, val loaderApi: Any)

val families = listOf(
    Family("fabric", "fabric", "net.fabricmc:fabric-loader:0.19.5"),
    Family("modlauncher", "modlauncher", stubsModlauncher.output),
    Family("forgeLegacy", "forge-1.8-1.12.2", stubsForgeLegacy.output),
    Family("forgeCpw", "forge-1.7.10", stubsForgeCpw.output),
)

families.forEach { family ->
    val set = sourceSets.create(family.sourceSet) {
        compileClasspath += main.output
    }
    dependencies {
        add(set.compileOnlyConfigurationName, family.loaderApi)
    }
    tasks.named<ProcessResources>(set.processResourcesTaskName) {
        val props = mapOf("version" to project.version.toString())
        inputs.properties(props)
        filesMatching(listOf("fabric.mod.json", "META-INF/*.toml", "mcmod.info")) {
            expand(props)
        }
    }
    val familyJar = tasks.register<Jar>("${family.sourceSet}Jar") {
        group = "build"
        description = "The mod's jar for ${family.classifier}."
        archiveClassifier = family.classifier
        // Shared classes and resources (the service file among them) + this family's entry and metadata.
        from(main.output, set.output)
    }
    tasks.assemble {
        dependsOn(familyJar)
    }
}

// The shared classes alone load on no loader.
tasks.jar {
    enabled = false
}

Shared code#

src/main/java/com/example/mymod/MyMod.java
package com.example.mymod;

import java.nio.file.Paths;

/** Shared by every loader. No Minecraft, loader or Settings Saver classes. */
public final class MyMod {
    public static final String MOD_ID = "mymod";
    /** Keep in step with the build's version; see build.gradle.kts. */
    public static final String VERSION = "3.1.0";

    private static MyConfig config;

    private MyMod() {
    }

    /**
     * The config, loaded the first time something needs it. Never call this while mods are being
     * constructed: a fresh instance may not have its saved file yet.
     */
    public static synchronized MyConfig config() {
        if (config == null) {
            // The game's working directory is the game directory on every loader.
            config = MyConfig.load(Paths.get("config", MOD_ID + ".properties"));
        }
        return config;
    }
}
src/main/java/com/example/mymod/MyConfig.java
package com.example.mymod;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

/** config/mymod.properties: plain key=value lines, UTF-8, no escapes. */
public final class MyConfig {
    public int renderDistance = 12;
    public int zoom = 150;                       // percent
    public String zoomKey = "key.keyboard.c";    // before Minecraft 1.13 the game layer stores a key code here
    public int windowX = 0;                      // per machine: excluded from profiles

    private Path file;

    public static MyConfig load(Path file) {
        MyConfig c = new MyConfig();
        c.file = file;
        if (!Files.isRegularFile(file)) {
            return c;                            // no file yet: defaults, written on the first save()
        }
        try (BufferedReader in = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
            String line;
            while ((line = in.readLine()) != null) {
                int eq = line.indexOf('=');
                if (eq <= 0 || line.trim().startsWith("#")) {
                    continue;
                }
                c.set(line.substring(0, eq).trim(), line.substring(eq + 1).trim());
            }
        } catch (IOException e) {
            // Unreadable: keep the defaults read so far.
        }
        return c;
    }

    /** Unknown keys and unreadable values are ignored, so files from other versions load. */
    private void set(String key, String value) {
        try {
            if (key.equals("renderDistance")) {
                renderDistance = Integer.parseInt(value);
            } else if (key.equals("zoom")) {
                zoom = Integer.parseInt(value);
            } else if (key.equals("zoomKey")) {
                zoomKey = value;
            } else if (key.equals("windowX")) {
                windowX = Integer.parseInt(value);
            }
        } catch (NumberFormatException e) {
            // Keep the default.
        }
    }

    /** Writes a temporary file and renames it, so a half-written file is never read. */
    public void save() throws IOException {
        Files.createDirectories(file.toAbsolutePath().getParent());
        Path tmp = file.resolveSibling(file.getFileName() + ".tmp");
        try (BufferedWriter out = Files.newBufferedWriter(tmp, StandardCharsets.UTF_8)) {
            out.write("renderDistance=" + renderDistance + "\n");
            out.write("zoom=" + zoom + "\n");
            out.write("zoomKey=" + zoomKey + "\n");
            out.write("windowX=" + windowX + "\n");
        }
        Files.move(tmp, file, StandardCopyOption.REPLACE_EXISTING);
    }
}

MyConfig ignores keys and values it doesn't know. That is what lets an older version of the mod read a file that a newer version's settings were loaded into.

The Settings Saver integration#

These two classes and the service file are the whole integration. They are the only code that imports dev.xichil.settingssaver.api.v1.

src/main/java/com/example/mymod/compat/MyModSettingsSaver.java
package com.example.mymod.compat;

import com.example.mymod.MyMod;
import dev.xichil.settingssaver.api.v1.ModSettings;
import dev.xichil.settingssaver.api.v1.SettingsFileFormats;
import dev.xichil.settingssaver.api.v1.SettingsSaverPlugin;
import dev.xichil.settingssaver.api.v1.SettingsSaverRegistrar;

/** Only Settings Saver loads this class. Nothing else in the mod may reference it. */
public final class MyModSettingsSaver implements SettingsSaverPlugin {
    @Override
    public void register(SettingsSaverRegistrar registrar) {
        registrar.register(ModSettings.builder(MyMod.MOD_ID, "My Mod", MyMod.VERSION)
                .file("config/mymod.properties", SettingsFileFormats.PROPERTIES)
                .savedByDefault(true)
                .excludedByDefault("windowX")
                // Keys are stored by name from Minecraft 1.13 on, by LWJGL 2 code before.
                .minecraftFix("1.13", new KeyNameFix())
                .build());
    }
}
src/main/java/com/example/mymod/compat/KeyNameFix.java
package com.example.mymod.compat;

import dev.xichil.settingssaver.api.v1.SettingsFix;

import java.util.HashMap;
import java.util.Map;

/**
 * From Minecraft 1.13 on, My Mod stores keys by name (key.keyboard.c); before, by LWJGL 2 key code (46).
 * Stateless: the tables are filled once and never change.
 */
final class KeyNameFix implements SettingsFix {
    /** The settings of config/mymod.properties that hold a key. */
    private static final String[] KEY_SETTINGS = {"zoomKey", "menuKey"};

    private static final Map<String, String> CODE_TO_NAME = new HashMap<String, String>();
    private static final Map<String, String> NAME_TO_CODE = new HashMap<String, String>();

    static {
        key("0", "key.keyboard.unknown");        // not bound
        key("19", "key.keyboard.r");
        key("33", "key.keyboard.f");
        key("34", "key.keyboard.g");
        key("42", "key.keyboard.left.shift");
        key("44", "key.keyboard.z");
        key("46", "key.keyboard.c");
        key("47", "key.keyboard.v");
        // ... one line per key My Mod lets players bind
    }

    private static void key(String code, String name) {
        CODE_TO_NAME.put(code, name);
        NAME_TO_CODE.put(name, code);
    }

    @Override
    public void upgrade(String file, Map<String, String> settings) {
        convert(file, settings, CODE_TO_NAME);
    }

    @Override
    public void downgrade(String file, Map<String, String> settings) {
        convert(file, settings, NAME_TO_CODE);
    }

    private static void convert(String file, Map<String, String> settings, Map<String, String> table) {
        if (!file.equals("config/mymod.properties")) {
            return;                              // another file of the mod
        }
        for (String setting : KEY_SETTINGS) {
            String converted = table.get(settings.get(setting));
            if (converted != null) {
                settings.put(setting, converted);
            }
            // Not in the table: already converted, or a key this table doesn't know. Leave it.
        }
    }
}
src/main/resources/META-INF/services/dev.xichil.settingssaver.api.v1.SettingsSaverPlugin
com.example.mymod.compat.MyModSettingsSaver

Fabric, Quilt and Legacy Fabric#

src/fabric/java/com/example/mymod/loader/FabricEntry.java
package com.example.mymod.loader;

import net.fabricmc.api.ClientModInitializer;

public final class FabricEntry implements ClientModInitializer {
    @Override
    public void onInitializeClient() {
        // Start the mod's game layer here. Code that needs settings calls MyMod.config().
    }
}
src/fabric/resources/fabric.mod.json
{
  "schemaVersion": 1,
  "id": "mymod",
  "version": "${version}",
  "name": "My Mod",
  "description": "One codebase on every loader and version.",
  "license": "All Rights Reserved",
  "environment": "client",
  "entrypoints": {
    "client": ["com.example.mymod.loader.FabricEntry"]
  },
  "depends": {
    "fabricloader": ">=0.12.0"
  }
}

Settings Saver is not listed: it is optional and found through the service file.

Forge 1.13.2+ and NeoForge#

src/modlauncher/java/com/example/mymod/loader/ForgeEntry.java
package com.example.mymod.loader;

import com.example.mymod.MyMod;
import net.minecraftforge.fml.common.Mod;

/** Forge 1.13.2+ and NeoForge 1.20.1. */
@Mod(MyMod.MOD_ID)
public final class ForgeEntry {
    public ForgeEntry() {
        // Don't read the config here: on Forge 1.13.2 - 1.15.2 (31.1) this may run before the restore.
    }
}
src/modlauncher/java/com/example/mymod/loader/NeoForgeEntry.java
package com.example.mymod.loader;

import com.example.mymod.MyMod;
import net.neoforged.fml.common.Mod;

/** NeoForge 1.20.2+. */
@Mod(MyMod.MOD_ID)
public final class NeoForgeEntry {
    public NeoForgeEntry() {
    }
}
src/modlauncher/resources/META-INF/mods.toml
# Read by Forge 1.13.2+ and NeoForge 1.20.1 - 1.20.4.
modLoader = "javafml"
loaderVersion = "[1,)"
license = "All Rights Reserved"

[[mods]]
modId = "mymod"
version = "${version}"
displayName = "My Mod"
description = '''One codebase on every loader and version.'''
displayTest = "IGNORE_ALL_VERSION"
src/modlauncher/resources/META-INF/neoforge.mods.toml
# Read by NeoForge 1.20.5+.
modLoader = "javafml"
loaderVersion = "[1,)"
license = "All Rights Reserved"

[[mods]]
modId = "mymod"
version = "${version}"
displayName = "My Mod"
description = '''One codebase on every loader and version.'''
displayTest = "IGNORE_ALL_VERSION"
src/modlauncher/resources/pack.mcmeta
{
  "pack": {
    "description": "My Mod resources",
    "pack_format": 6
  }
}

loaderVersion = "[1,)" matches both Forge's and NeoForge's loader versions. displayTest = "IGNORE_ALL_VERSION" means a server doesn't need the mod for the client to join.

Forge 1.8 – 1.12.2#

src/forgeLegacy/java/com/example/mymod/loader/ForgeLegacyEntry.java
package com.example.mymod.loader;

import com.example.mymod.MyMod;
import net.minecraftforge.fml.common.Mod;

/** Name and version come from mcmod.info. */
@Mod(modid = MyMod.MOD_ID, useMetadata = true, acceptableRemoteVersions = "*")
public final class ForgeLegacyEntry {
    public ForgeLegacyEntry() {
        // Don't read the config here: this may run before the restore.
    }
}
src/forgeLegacy/resources/mcmod.info
[
  {
    "modid": "mymod",
    "name": "My Mod",
    "description": "One codebase on every loader and version.",
    "version": "${version}"
  }
]

Forge 1.7.10#

The same as Forge 1.8 – 1.12.2 with the cpw.mods.fml annotation. mcmod.info is identical; put a copy in src/forgeCpw/resources/.

src/forgeCpw/java/com/example/mymod/loader/ForgeCpwEntry.java
package com.example.mymod.loader;

import com.example.mymod.MyMod;
import cpw.mods.fml.common.Mod;

@Mod(modid = MyMod.MOD_ID, useMetadata = true, acceptableRemoteVersions = "*")
public final class ForgeCpwEntry {
    public ForgeCpwEntry() {
    }
}

Stubs#

Each stub declares only what the entry classes use. The real annotations are there at run time.

src/stubsModlauncher/java/net/minecraftforge/fml/common/Mod.java
package net.minecraftforge.fml.common;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/** Compile-only stub. Forge finds mods by scanning class files for this annotation. */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Mod {
    String value();
}

src/stubsModlauncher/java/net/neoforged/fml/common/Mod.java is the same with package net.neoforged.fml.common;.

src/stubsForgeLegacy/java/net/minecraftforge/fml/common/Mod.java
package net.minecraftforge.fml.common;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/** Compile-only stub of Forge 1.8 - 1.12.2's mod annotation: only the members the entry class uses. */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Mod {
    String modid();
    boolean useMetadata() default false;
    String acceptableRemoteVersions() default "";
}

src/stubsForgeCpw/java/cpw/mods/fml/common/Mod.java is the same with package cpw.mods.fml.common;.

How it works#

Check the result#

unzip -l build/libs/mymod-3.1.0-fabric.jar | grep -E "META-INF/services|settingssaver"

Every jar should list the service file and no dev/xichil/settingssaver/ classes. Then start one instance per jar with Settings Saver installed and look for this line in the log:

[Settings Saver] Registered My Mod (mymod 3.1.0): [config/mymod.properties], saved by default