Lite Config

模组

· 作者 Riser876

一个 Minecraft JSON5/TOML 配置库

0 本站下载 0 关注 更新于 15 小时前

需要前置:Fabric API

最新 1.4.0-1.21 · 1.21.10 · Fabric

一键开服(送7天)

Lite Config logo
Lite Config

Wiki · Setup · Quickstart · Full Example

Lite Config 将普通的 Java 类转换为 JSON5 或 TOML 配置文件。它负责处理加载、验证、保存、迁移和服务器同步,因此你的模组只需读取数值即可。

@Config(name = "mymod", type = ConfigType.CLIENT, format = ConfigFormat.JSON)
public final class MyModConfig {
    @Property(comment = "HUD 叠加层的缩放比例。")
    @Range(min = 1, max = 4)
    public int hudScale = 2;

    public boolean showHints = true;
}

ConfigHandle<MyModConfig> CONFIG = LiteConfig.handle(MyModConfig.class).label("mymod").create();
int scale = CONFIG.data().hudScale;
// config/mymod.json5
{
  // HUD 叠加层的缩放比例。
  "hudScale": 2,
  "showHints": true,
}

功能特性

JSON5 或 TOML 默认值、自动生成的注释、自定义路径和名称,以及损坏文件的恢复。
验证 支持 @Range、@Pattern、@Length、@AllowedValues 等注解,以及归一化和验证钩子。被拒绝的更新会列出所有违规项。
快速读取 data() 方法无锁,可从任意线程访问。若需隔离实例,请使用 copy()。
可选同步 服务器向客户端发送标记的配置或单个字段。
客户端、服务器或世界 选择每个配置的所有者,包括仅在重启后生效的设置。
迁移 带版本号的文件逐步升级,不会丢失玩家数据。
失败策略 针对读取、写入和更新分别设置回退或快速失败。
事件和元数据 提供加载、保存和更新事件,并在运行时提供每个字段的路径、类型、默认值、注释、监听器和翻译键。

Lite Config 仅作为数据层。它目前不提供配置界面(UI),因此你可以将其与任何 UI 库或自定义界面配合使用。

设置

Lite Config 发布在 Maven Central 的 com.gmalvestiti.minecraft 命名空间下,每个加载器对应一个构件:

Loader Artifact
Fabric liteconfig-fabric
NeoForge liteconfig-neoforge

版本号同时包含 Lite Config 版本和目标 Minecraft 版本:

Minecraft Lite Config
1.21-1.21.10 1.4.0-1.21
1.21.11 1.4.0-1.21.11
26.1-latest 1.4.0-26.1

以下示例使用 1.21 构建。

Fabric
repositories {
    mavenCentral()
}

dependencies {
    modImplementation 'com.gmalvestiti.minecraft:liteconfig-fabric:1.4.0-1.21'
}

在 fabric.mod.json 中声明依赖,以便 Fabric 在没有 Lite Config 时拒绝加载模组:

{
    "depends": {
        "liteconfig": ">=1.4.0-1.21"
    }
}
NeoForge
repositories {
    mavenCentral()
}

dependencies {
    implementation 'com.gmalvestiti.minecraft:liteconfig-neoforge:1.4.0-1.21'
}

在 META-INF/neoforge.mods.toml 中声明依赖:

[[dependencies.yourmodid]]
modId = "liteconfig"
type = "required"
versionRange = "[1.4.0,)"
ordering = "NONE"
side = "BOTH"

快速开始

从一个简单的配置类开始。为每个持久化字段提供默认值。

@Config(name = "mymod", type = ConfigType.CLIENT) // JSON5, config/mymod.json5
public final class MyModConfig {
    public boolean showHints = true;
    public int hudScale = 2;
}

若要改用 TOML 格式,请在 @Config 中添加 format = ConfigFormat.TOML。

在模组初始化期间创建一个句柄(Handle)并使其在整个模组生命周期内保持有效:

public final class MyMod implements ModInitializer {

    public static final ConfigHandle<MyModConfig> CONFIG = LiteConfig.handle(MyModConfig.class)
        .label("mymod")
        .create();
}

或者在配置类本身中:

@Config(name = "mymod", type = ConfigType.CLIENT)
public final class MyModConfig {
    public boolean showHints = true;
    public int hudScale = 2;

    public static final ConfigHandle<MyModConfig> CONFIG;
    
    static {
        CONFIG = LiteConfig.handle(MyModConfig.class)
            .label("mymod")
            .create();
    }
}

create() 会验证配置模型并加载当前有效的本地设置;如果文件尚不存在,则写入默认值。

句柄可以在游戏启动之前创建。请确保构造函数、迁移逻辑和自定义状态克隆器独立于 Minecraft 的运行时状态。

使用 data() 读取当前发布的状态:

if (MyMod.CONFIG.data().showHints) {
    // ...
}

使用 update(...) 或 updateAndSave(...) 应用运行时更改:

MyMod.CONFIG.update(config -> config.hudScale = 3);        // 仅限内存
MyMod.CONFIG.updateAndSave(config -> config.hudScale = 4); // 内存 + 磁盘

请将 data() 及其嵌套值视为只读。若需编辑副本,请使用 copy()。

如果更改无效,Lite Config 会拒绝该更改并保持当前状态:

OperationResult result = MyMod.CONFIG.update(config -> config.hudScale = 99);
if (!result.accepted()) {
    result.violations().forEach(v -> LOGGER.warn("{}: {}", v.id(), v.message()));
}

保存后的 JSON5 文件如下所示:

{
  "showHints": true,
  "hudScale": 4
}

完整配置示例

@Config(
    name = "mymodfile",
    path = "mymod/mymoddir1/mymoddir2",
    type = ConfigType.SERVER,
    format = ConfigFormat.JSON,
    comment = "MyMod settings.",
    version = 3,
    stateCloner = MyModConfigCloner.class,
    readFailurePolicy = FailurePolicy.FALLBACK,
    writeFailurePolicy = FailurePolicy.STRICT,
    updateFailurePolicy = FailurePolicy.FALLBACK,
    restartSyncPolicy = RestartSyncPolicy.DISCONNECT
)
public final class MyModConfig implements ConfigExtension {

    @Property(
        name = "hud_scale",
        comment = "Scale of the HUD, from 1 to 4.",
        translationKey = "mymod.config.hud_scale",
        sync = SyncMode.ENABLED,
        listener = "onHudScaleChanged"
    )
    @Range(min = 1, max = 4)
    public int hudScale = 2;

    @Property(
        comment = "Rendering backend. Applied after the next restart.",
        restart = true,
        sync = SyncMode.ENABLED
    )
    public Renderer renderer = Renderer.DEFAULT;

    @AllowedValues(
        value = {"mysql", "sqlite"},
        normalize = PropertyNormalization.NONE,
        trim = true
    )
    public String database = "sqlite";

    @AllowedValues(value = {"fast", "safe"}, normalize = PropertyNormalization.UPPER_CASE)
    public String mode = "SAFE";

    @AllowedValues(value = {"Custom", "Default"}, normalize = PropertyNormalization.NONE, trim = false)
    public String label = "Custom";

    @NotBlank
    @Length(max = 16)
    @Pattern("[a-z0-9_]+")
    @Property(comment = {"Profile used by server rules.", "Must be lowercase, alphanumeric, or underscore."})
    public String profileName = "default";

    @NotNull
    @Property(comment = "Server-owned spawn range.", sync = SyncMode.ENABLED)
    public IntRange spawnRange = new IntRange(1, 12);

    public Display display = new Display();

    @Ignore
    public Map<String, String> runtimeCache = new HashMap<>();

    @Override
    public void afterLoad() {
        if (profileName != null) {
            profileName = profileName.strip().toLowerCase(Locale.ROOT);
        }
    }

    @Override
    public void beforeSave() {
        if (display != null && display.hiddenHints != null) {
            display.hiddenHints.sort(String::compareTo);
        }
    }

    @Override
    public void validate(List<Violation> violations) {
        if (spawnRange == null || spawnRange.minimum() > spawnRange.maximum()) {
            violations.add(Violation.of(
                "spawn-range.order",
                "spawnRange minimum must not exceed its maximum"
            ));
        }
    }

    private void onHudScaleChanged(Integer oldValue, Integer newValue, boolean fromSync) {
        System.out.printf("HUD scale: %d -> %d (from server: %s)%n",
            oldValue, newValue, fromSync);
    }

    @Migration(from = 1)
    static void toVersion2(ConfigData data) {
        data.rename("hudScale", "hud_scale");
    }

    @Migration(from = 2)
    static void toVersion3(ConfigData data) {
        if (!data.has("spawnRange")) {
            data.set("spawnRange.minimum", 1)
                .set("spawnRange.maximum", 12);
        }
    }

    public static final class Display {
        @Property(comment = "Show contextual hints.")
        public boolean showHints = true;

        @Length(max = 32)
        public List<String> hiddenHints = new ArrayList<>();
    }

    public enum Renderer {
        DEFAULT,
        COMPATIBILITY
    }
}

// Custom type
public record IntRange(int minimum, int maximum) {
    public static final Codec<IntRange> CODEC = RecordCodecBuilder.create(instance ->
        instance.group(
            Codec.INT.fieldOf("minimum").forGetter(IntRange::minimum),
            Codec.INT.fieldOf("maximum").forGetter(IntRange::maximum)
        ).apply(instance, IntRange::new)
    );

    public static final StreamCodec<ByteBuf, IntRange> STREAM_CODEC =
        StreamCodec.composite(
            ByteBufCodecs.VAR_INT, IntRange::minimum,
            ByteBufCodecs.VAR_INT, IntRange::maximum,
            IntRange::new
        );
}

// Custom config state cloner
public final class MyModConfigCloner implements StateCloner<MyModConfig> {
    @Override
    public MyModConfig copy(MyModConfig source) {
        MyModConfig copy = new MyModConfig();
        copy.hudScale = source.hudScale;
        copy.renderer = source.renderer;
        copy.database = source.database;
        copy.profileName = source.profileName;
        copy.spawnRange = source.spawnRange;
        copy.display = copyDisplay(source.display);
        copy.runtimeCache = source.runtimeCache == null
            ? new HashMap<>()
            : new HashMap<>(source.runtimeCache);
        return copy;
    }

    private static MyModConfig.Display copyDisplay(MyModConfig.Display source) {
        if (source == null) {
            return null;
        }
        MyModConfig.Display copy = new MyModConfig.Display();
        copy.showHints = source.showHints;
        copy.hiddenHints = source.hiddenHints == null
            ? null
            : new ArrayList<>(source.hiddenHints);
        return copy;
    }
}

注册用于文件持久化和状态复制的自定义 Codec,以及用于同步的 StreamCodec。

public final class MyMod implements ModInitializer {

```java
public static ConfigHandle<MyModConfig> config = LiteConfig.handle(MyModConfig.class, codecs -> codecs
            .registerCodec(IntRange.class, IntRange.CODEC)
            .registerStreamCodec(IntRange.class, IntRange.STREAM_CODEC))
        .label("mymod")
        .onUpdate(state -> System.out.println("HUD scale is now " + state.hudScale))
        .onSave(state -> System.out.println("Saved MyMod config"))
        .create();

    @Override
    public void onInitialize() {
        // 快速共享读取。将返回的对象视为只读。
        int currentScale = config.data().hudScale;

        // 由当前调用方拥有的稳定深层副本。
        MyModConfig snapshot = config.copy();
        snapshot.display.hiddenHints.add("crafting");

        // 内存中的验证更新。
        OperationResult result = config.update(state -> {
            state.hudScale = 3;
            state.display.hiddenHints = new ArrayList<>(
                snapshot.display.hiddenHints
            );
        });
        if (!result.accepted()) {
            result.violations().forEach(violation ->
                System.err.println(violation.id() + ": " + violation.message()));
        }

        // 更新并保存。
        OperationResult saved = config.updateAndSave(state ->
            state.spawnRange = new IntRange(2, 24)
        );
        System.out.println("Saved: " + saved.accepted());

        // 用于屏幕、命令、生成的帮助等的结构元数据。
        config.metadata().flatten().forEach(property ->
            System.out.println(property.path() + " -> " + property.type().getSimpleName()));
    }
}

第一次 create() 会加载 config/mymod/mymoddir1/mymoddir2/mymodfile.json5,应用迁移, 验证结果并保存。没有 configVersion 的文件从版本 1 开始。

只有 hud_scale、renderer 和 spawnRange 会同步,因为它们通过 SyncMode.ENABLED 选择了启用同步。

内置值包括基本类型及其包装类、枚举、数组、带类型的 List/Set/Map 集合、 UUID、BigInteger、BigDecimal、Duration、Instant、LocalDate、LocalTime 和 LocalDateTime。

你是这个资源的作者?登录后可认领此资源。

评论 0

0.0
暂无评分
5 星
0
4 星
0
3 星
0
2 星
0
1 星
0
我的评分

登录后参与评分

还没有评论,来抢沙发吧

评论配图

相似资源