[Enhancement] 原理图管理优化 (#6094)

Co-authored-by: Calboot <[email protected]>
Co-authored-by: 3gf8jv4dv <[email protected]>
Co-authored-by: Glavo <[email protected]>
Co-authored-by: CalbootOnceMore <[email protected]>
This commit is contained in:
authored and GitHub committed 2026-09-17 21:15:11 +08:00
1 parent 13910c24b7
commit 13ad50208f
35 files changed
+1426 -425

No files matched your search

@@ -24,6 +24,7 @@ import org.jackhuang.hmcl.addon.meta.*;
import org.jackhuang.hmcl.game.DefaultGameInstance;
import org.jackhuang.hmcl.game.GameComponentAnalyzer;
import org.jackhuang.hmcl.game.GameComponentType;
import org.jackhuang.hmcl.game.NoSuchGameInstanceException;
import org.jackhuang.hmcl.util.Pair;
import org.jackhuang.hmcl.util.StringUtils;
import org.jackhuang.hmcl.util.io.CompressingUtils;
@@ -65,7 +66,9 @@ public final class ModManager extends LocalAddonManager<LocalModFile> {
READERS = map;
}
private String gameVersion;
private final HashMap<Pair<String, ModLoaderType>, LocalMod> localMods = new HashMap<>();
private final EnumSet<ModLoaderType> supportedLoaders = EnumSet.noneOf(ModLoaderType.class);
private GameComponentAnalyzer analyzer;
private boolean loaded = false;
@@ -83,7 +86,12 @@ public final class ModManager extends LocalAddonManager<LocalModFile> {
}
public GameComponentAnalyzer getComponentAnalyzer() {
return analyzer;
lock.lock();
try {
return analyzer;
} finally {
lock.unlock();
}
}
public LocalMod getLocalMod(String modId, ModLoaderType modLoaderType) {
@@ -105,6 +113,24 @@ public final class ModManager extends LocalAddonManager<LocalModFile> {
}
}
public String getGameVersion() {
lock.lock();
try {
return gameVersion;
} finally {
lock.unlock();
}
}
public EnumSet<ModLoaderType> getSupportedLoaders() {
lock.lock();
try {
return EnumSet.copyOf(supportedLoaders);
} finally {
lock.unlock();
}
}
private void addModInfo(Path file) {
String fileName = StringUtils.removeSuffix(FileUtils.getName(file), DISABLED_EXTENSION, OLD_EXTENSION);
String extension = fileName.substring(fileName.lastIndexOf(".") + 1);
@@ -176,6 +202,18 @@ public final class ModManager extends LocalAddonManager<LocalModFile> {
}
}
public void analyze() throws IOException {
lock.lock();
try {
gameVersion = instance.getVersion().toString();
analyzer = instance.getAnalyzer();
} catch (NoSuchGameInstanceException e) {
throw new IOException(e);
} finally {
lock.unlock();
}
}
@Override
public void refresh() throws IOException {
lock.lock();
@@ -183,7 +221,7 @@ public final class ModManager extends LocalAddonManager<LocalModFile> {
localFiles.clear();
localMods.clear();
analyzer = instance.getAnalyzer();
analyze();
boolean supportSubfolders = analyzer.has(GameComponentType.FORGE)
|| analyzer.has(GameComponentType.QUILT)
@@ -205,6 +243,9 @@ public final class ModManager extends LocalAddonManager<LocalModFile> {
}
}
}
updateSupportedLoaders();
loaded = true;
} finally {
lock.unlock();
@@ -254,6 +295,50 @@ public final class ModManager extends LocalAddonManager<LocalModFile> {
}
}
private void updateSupportedLoaders() {
supportedLoaders.clear();
if (this.analyzer == null) {
Collections.addAll(supportedLoaders, ModLoaderType.values());
return;
}
for (GameComponentType type : GameComponentType.values()) {
if (type.isModLoader() && this.analyzer.has(type)) {
ModLoaderType modLoaderType = type.getModLoaderType();
if (modLoaderType != null) {
supportedLoaders.add(modLoaderType);
if (modLoaderType == ModLoaderType.CLEANROOM)
supportedLoaders.add(ModLoaderType.FORGE);
}
}
}
if (this.analyzer.has(GameComponentType.NEO_FORGE) && "1.20.1".equals(gameVersion)) {
supportedLoaders.add(ModLoaderType.FORGE);
}
if (this.analyzer.has(GameComponentType.QUILT)) {
supportedLoaders.add(ModLoaderType.FABRIC);
}
if (this.analyzer.has(GameComponentType.LEGACY_FABRIC)) {
supportedLoaders.add(ModLoaderType.FABRIC);
}
if (this.analyzer.has(GameComponentType.FABRIC) && hasMod("kilt", ModLoaderType.FABRIC)) {
supportedLoaders.add(ModLoaderType.FORGE);
supportedLoaders.add(ModLoaderType.NEO_FORGE);
}
// Sinytra Connector
if (this.analyzer.has(GameComponentType.NEO_FORGE) && (hasMod("connector", ModLoaderType.NEO_FORGE) || hasMod("connectormod", ModLoaderType.NEO_FORGE))
|| "1.20.1".equals(gameVersion) && this.analyzer.has(GameComponentType.FORGE) && hasMod("connectormod", ModLoaderType.FORGE)) {
supportedLoaders.add(ModLoaderType.FABRIC);
}
}
public void rollback(LocalModFile from, LocalModFile to) throws IOException {
lock.lock();
try {
@@ -18,17 +18,23 @@
package org.jackhuang.hmcl.game;
import org.jackhuang.hmcl.addon.mod.ModLoaderType;
import org.jackhuang.hmcl.schematic.LitematicaConfig;
import org.jackhuang.hmcl.util.StringUtils;
import org.jackhuang.hmcl.util.gson.JsonUtils;
import org.jackhuang.hmcl.util.platform.Platform;
import org.jackhuang.hmcl.util.versioning.GameVersionNumber;
import org.jetbrains.annotations.NotNullByDefault;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.EnumSet;
import java.util.Optional;
import java.util.Set;
import static org.jackhuang.hmcl.util.logging.Logger.LOG;
/// Provides a view of a game instance and its instance-specific paths within a
/// [GameRepositorySnapshot].
///
@@ -160,7 +166,25 @@ public interface GameInstance {
///
/// @return the schematics directory below the run directory
default Path getSchematicsDirectory() {
return getRunDirectory().resolve("schematics");
var runDir = getRunDirectory();
var litematicaConfig = runDir.resolve("config").resolve("litematica.json");
Path dir = runDir.resolve("schematics");
if (Files.isRegularFile(litematicaConfig)) {
try {
var conf = JsonUtils.fromJsonFile(litematicaConfig, LitematicaConfig.class);
if (conf != null
&& conf.generic() != null
&& conf.generic().customSchematicBaseDirectoryEnabled()
&& StringUtils.isNotBlank(conf.generic().customSchematicBaseDirectory())
) {
var p = Path.of(conf.generic().customSchematicBaseDirectory());
dir = p.isAbsolute() ? p.normalize() : runDir.resolve(p).normalize();
}
} catch (Exception e) {
LOG.warning("Failed to load custom schematics directory from litematica config at '%s'".formatted(litematicaConfig), e);
}
}
return dir;
}
/// Returns the directory used for extracted native libraries for a platform.
@@ -59,7 +59,6 @@ public interface ModAdviser {
"irisUpdateInfo.json", // Iris
"modernfix", // ModernFix
"modtranslations", // Mod translations
"schematics", // Schematics mod
"journeymap/data", // JourneyMap
"mods/.connector" // Sinytra Connector
);
@@ -70,6 +69,7 @@ public interface ModAdviser {
"blueprints" /* BuildCraft */,
"optionsof.txt" /* OptiFine */,
"journeymap" /* JourneyMap */,
"schematics" /* Schematics mod */,
"optionsshaders.txt",
"mods/VoxelMods");
@@ -17,33 +17,31 @@
*/
package org.jackhuang.hmcl.schematic;
import javafx.geometry.Point3D;
import org.glavo.nbt.io.NBTCodec;
import org.glavo.nbt.tag.*;
import org.glavo.nbt.tag.CompoundTag;
import org.glavo.nbt.tag.IntArrayTag;
import org.glavo.nbt.tag.IntTag;
import org.glavo.nbt.tag.Tag;
import org.jackhuang.hmcl.util.Point3I;
import org.jackhuang.hmcl.util.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.util.zip.GZIPInputStream;
import java.util.OptionalInt;
import java.util.OptionalLong;
/// @author Glavo
/// @see <a href="https://litemapy.readthedocs.io/en/v0.9.0b0/litematics.html">The Litematic file format</a>
public final class LitematicFile {
import static org.jackhuang.hmcl.util.NBTUtils.*;
private static @Nullable String tryGetString(Tag tag) {
return tag instanceof StringTag stringTag ? stringTag.get() : null;
}
/**
* @author Glavo
* @see <a href="https://litemapy.readthedocs.io/en/v0.9.0b0/litematics.html">The Litematic file format</a>
*/
public final class LitematicFile extends Schematic {
public static LitematicFile load(Path file) throws IOException {
CompoundTag root;
try (InputStream in = new GZIPInputStream(Files.newInputStream(file))) {
root = NBTCodec.of().readTag(in, TagType.COMPOUND);
}
CompoundTag root = readCompressed(file);
Tag versionTag = root.get("Version");
if (versionTag == null)
@@ -61,19 +59,29 @@ public final class LitematicFile {
if (root.get("Regions") instanceof CompoundTag regionsTag)
regions = regionsTag.size();
Point3I enclosingSize = null;
Tag enclosingSizeTag = ((CompoundTag) metadataTag).get("EnclosingSize");
if (enclosingSizeTag instanceof CompoundTag) {
CompoundTag list = (CompoundTag) enclosingSizeTag;
int x = tryGetInt(list.get("x")).orElse(0);
int y = tryGetInt(list.get("y")).orElse(0);
int z = tryGetInt(list.get("z")).orElse(0);
if (x > 0 && y > 0 && z > 0) enclosingSize = new Point3I(x, y, z);
}
Tag subVersionTag = root.get("SubVersion");
return new LitematicFile(file, (CompoundTag) metadataTag,
((IntTag) versionTag).getValue(),
root.getIntOrZero("SubVersion"),
root.getIntOrZero("MinecraftDataVersion"),
regions
((IntTag) versionTag).get(),
tryGetInt(subVersionTag).orElse(-1),
tryGetInt(root.get("MinecraftDataVersion")).orElse(0),
regions,
enclosingSize
);
}
private final @NotNull Path file;
private final int version;
private final int subVersion;
private final int minecraftDataVersion;
private final int regionCount;
private final int[] previewImageData;
private final String name;
@@ -83,14 +91,12 @@ public final class LitematicFile {
private final Instant timeModified;
private final int totalBlocks;
private final int totalVolume;
private final Point3D enclosingSize;
private LitematicFile(@NotNull Path file, @NotNull CompoundTag metadata,
int version, int subVersion, int minecraftDataVersion, int regionCount) {
this.file = file;
int version, int subVersion, int minecraftDataVersion, int regionCount, Point3I enclosingSize) {
super(file, minecraftDataVersion, enclosingSize);
this.version = version;
this.subVersion = subVersion;
this.minecraftDataVersion = minecraftDataVersion;
this.regionCount = regionCount;
Tag previewImageData = metadata.get("PreviewImageData");
@@ -101,48 +107,39 @@ public final class LitematicFile {
this.name = tryGetString(metadata.get("Name"));
this.author = tryGetString(metadata.get("Author"));
this.description = tryGetString(metadata.get("Description"));
this.timeCreated = metadata.get("TimeCreated") instanceof LongTag time ? Instant.ofEpochMilli(time.getValue()) : null;
this.timeModified = metadata.get("TimeModified") instanceof LongTag time ? Instant.ofEpochMilli(time.getValue()) : null;
this.totalBlocks = metadata.getIntOrZero("TotalBlocks");
this.totalVolume = metadata.getIntOrZero("TotalVolume");
Point3D enclosingSize = null;
if (metadata.get("EnclosingSize") instanceof CompoundTag list) {
int x = list.getIntOrZero("x");
int y = list.getIntOrZero("y");
int z = list.getIntOrZero("z");
if (x >= 0 && y >= 0 && z >= 0)
enclosingSize = new Point3D(x, y, z);
}
this.enclosingSize = enclosingSize;
this.timeCreated = tryGetLongTimestamp(metadata.get("TimeCreated"));
this.timeModified = tryGetLongTimestamp(metadata.get("TimeModified"));
this.totalBlocks = tryGetInt(metadata.get("TotalBlocks")).orElse(-1);
this.totalVolume = tryGetInt(metadata.get("TotalVolume")).orElse(-1);
}
public @NotNull Path getFile() {
return file;
@Override
public SchematicType getType() {
return SchematicType.LITEMATIC;
}
public int getVersion() {
return version;
@Override
public OptionalInt getVersion() {
return OptionalInt.of(version);
}
public int getSubVersion() {
return subVersion;
}
public int getMinecraftDataVersion() {
return minecraftDataVersion;
@Override
public OptionalInt getSubVersion() {
return subVersion >= 0 ? OptionalInt.of(subVersion) : OptionalInt.empty();
}
@Override
public int[] getPreviewImageData() {
return previewImageData != null ? previewImageData.clone() : null;
}
public String getName() {
return name;
@Override
public @NotNull String getName() {
return StringUtils.isNotBlank(name) ? name : super.getName();
}
@Override
public String getAuthor() {
return author;
}
@@ -151,27 +148,29 @@ public final class LitematicFile {
return description;
}
@Override
public Instant getTimeCreated() {
return timeCreated;
}
@Override
public Instant getTimeModified() {
return timeModified;
}
public int getTotalBlocks() {
return totalBlocks;
@Override
public OptionalInt getTotalBlocks() {
return totalBlocks >= 1 ? OptionalInt.of(totalBlocks) : OptionalInt.empty();
}
public int getTotalVolume() {
return totalVolume;
@Override
public OptionalLong getTotalVolume() {
return totalVolume >= 1 ? OptionalLong.of(totalVolume) : OptionalLong.empty();
}
public Point3D getEnclosingSize() {
return enclosingSize;
@Override
public OptionalInt getRegionCount() {
return regionCount >= 1 ? OptionalInt.of(regionCount) : OptionalInt.empty();
}
public int getRegionCount() {
return regionCount;
}
}
@@ -0,0 +1,25 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2026 huangyuhui <[email protected]> and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.jackhuang.hmcl.schematic;
import com.google.gson.annotations.SerializedName;
public record LitematicaConfig(@SerializedName("Generic") Generic generic) {
public record Generic(boolean customSchematicBaseDirectoryEnabled, String customSchematicBaseDirectory) {
}
}
@@ -0,0 +1,83 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2026 huangyuhui <[email protected]> and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.jackhuang.hmcl.schematic;
import org.glavo.nbt.tag.CompoundTag;
import org.glavo.nbt.tag.ListTag;
import org.glavo.nbt.tag.Tag;
import org.jackhuang.hmcl.util.NBTUtils;
import org.jackhuang.hmcl.util.Point3I;
import java.io.IOException;
import java.nio.file.Path;
import static org.jackhuang.hmcl.util.NBTUtils.tryGetInt;
/// @author Calboot
/// @see <a href="https://minecraft.wiki/w/Structure_file">Structure File</a>
public final class NBTStructureFile extends Schematic {
public static NBTStructureFile load(Path file) throws IOException {
CompoundTag root = NBTUtils.readCompressed(file);
if (!(root.get("blocks") instanceof ListTag<?>))
throw new IOException("blocks tag not found");
if (!(root.get("entities") instanceof ListTag<?>))
throw new IOException("entities tag not found");
Tag sizeTag = root.get("size");
if (sizeTag == null)
throw new IOException("size tag not found");
else if (!(sizeTag instanceof ListTag<?>))
throw new IOException("size tag is not a list");
ListTag<?> size = (ListTag<?>) sizeTag;
if (size.size() != 3)
throw new IOException("size tag does not have 3 elements");
Tag xTag = size.getTag(0);
Tag yTag = size.getTag(1);
Tag zTag = size.getTag(2);
Point3I enclosingSize = null;
int width = tryGetInt(xTag).orElse(0);
int height = tryGetInt(yTag).orElse(0);
int length = tryGetInt(zTag).orElse(0);
if (width > 0 && height > 0 && length > 0) {
enclosingSize = new Point3I(width, height, length);
}
return new NBTStructureFile(file, tryGetInt(root.get("DataVersion")).orElse(500), NBTUtils.tryGetString(root.get("author")), enclosingSize);
}
private final String author;
private NBTStructureFile(Path file, int dataVersion, String author, Point3I enclosingSize) {
super(file, dataVersion, enclosingSize);
this.author = author;
}
@Override
public SchematicType getType() {
return SchematicType.NBT_STRUCTURE;
}
@Override
public String getAuthor() {
return author;
}
}
@@ -0,0 +1,152 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2026 huangyuhui <[email protected]> and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.jackhuang.hmcl.schematic;
import org.glavo.nbt.tag.CompoundTag;
import org.glavo.nbt.tag.IntTag;
import org.glavo.nbt.tag.StringTag;
import org.glavo.nbt.tag.Tag;
import org.jackhuang.hmcl.util.NBTUtils;
import org.jackhuang.hmcl.util.Point3I;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.nio.file.Path;
import java.util.OptionalInt;
import static org.jackhuang.hmcl.util.NBTUtils.tryGetShort;
import static org.jackhuang.hmcl.util.NBTUtils.tryGetString;
/// @author Calboot
/// @see <a href="https://minecraft.wiki/w/Schematic_file_format">Schematic File Format Wiki</a>
/// @see <a href="https://github.com/Lunatrius/Schematica/blob/master/src/main/java/com/github/lunatrius/schematica/world/schematic/SchematicAlpha.java">Schematica</a>
/// @see <a href="https://github.com/SpongePowered/Schematic-Specification/tree/master/versions">Sponge Spec</a>
public final class SchemFile extends Schematic {
private static final int DATA_VERSION_MC_1_13_2 = 1631;
public static SchemFile load(Path file) throws IOException {
CompoundTag root = NBTUtils.readCompressed(file);
if (root.get("Materials") != null) return loadLegacy(file, root);
else if (root.get("Version") != null) return loadSponge(file, root);
else {
var schem = root.get("Schematic");
if (schem instanceof CompoundTag sponge3 && sponge3.get("Version") != null) {
return loadSponge(file, sponge3);
}
}
throw new IOException("No Materials tag or Version tag found");
}
private static SchemFile loadLegacy(Path file, CompoundTag root) throws IOException {
Tag materialsTag = root.get("Materials");
if (!(materialsTag instanceof StringTag))
throw new IOException("Materials tag is not a string");
Tag widthTag = root.get("Width");
Tag heightTag = root.get("Height");
Tag lengthTag = root.get("Length");
Point3I enclosingSize = null;
if (widthTag != null && heightTag != null && lengthTag != null) {
short width = tryGetShort(widthTag).orElse((short) 0);
short height = tryGetShort(heightTag).orElse((short) 0);
short length = tryGetShort(lengthTag).orElse((short) 0);
if (width > 0 && height > 0 && length > 0) {
enclosingSize = new Point3I(width, height, length);
}
}
return new SchemFile(file, null, null, ((StringTag) materialsTag).getValue(), 0, 0, enclosingSize);
}
private static SchemFile loadSponge(Path file, CompoundTag root) throws IOException {
Tag versionTag = root.get("Version");
if (!(versionTag instanceof IntTag))
throw new IOException("Version tag is not an integer");
Tag dataVersionTag = root.get("DataVersion");
int dataVersion;
dataVersion = dataVersionTag == null ? DATA_VERSION_MC_1_13_2 : NBTUtils.tryGetInt(dataVersionTag).orElse(0);
Tag widthTag = root.get("Width");
Tag heightTag = root.get("Height");
Tag lengthTag = root.get("Length");
Point3I enclosingSize = null;
if (widthTag != null && heightTag != null && lengthTag != null) {
int width = tryGetShort(widthTag).orElse((short) 0) & 0xFFFF;
int height = tryGetShort(heightTag).orElse((short) 0) & 0xFFFF;
int length = tryGetShort(lengthTag).orElse((short) 0) & 0xFFFF;
if (width > 0 && height > 0 && length > 0) {
enclosingSize = new Point3I(width, height, length);
}
}
Tag metaTag = root.get("Metadata");
String name = null, author = null;
if (metaTag instanceof CompoundTag meta) {
name = tryGetString(meta.get("Name"));
author = tryGetString(meta.get("Author"));
}
return new SchemFile(file, name, author, null, dataVersion, ((IntTag) versionTag).getValue(), enclosingSize);
}
private final @Nullable String name;
private final @Nullable String author;
private final @Nullable String materials;
private final int version;
private SchemFile(Path file, @Nullable String name, @Nullable String author, @Nullable String materials, int dataVersion, int version, Point3I enclosingSize) {
super(file, dataVersion, enclosingSize);
this.name = name;
this.author = author;
this.materials = materials;
this.version = version;
}
@Override
public @NotNull String getName() {
if (name == null) return super.getName();
return name;
}
@Override
public String getAuthor() {
if (author == null) return super.getAuthor();
return author;
}
@Override
public SchematicType getType() {
return SchematicType.SCHEM;
}
@Override
public OptionalInt getVersion() {
return version > 0 ? OptionalInt.of(version) : OptionalInt.empty();
}
@Override
public String getMinecraftVersion() {
return materials == null ? super.getMinecraftVersion() : materials;
}
}
@@ -0,0 +1,128 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2026 huangyuhui <[email protected]> and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.jackhuang.hmcl.schematic;
import org.jackhuang.hmcl.util.Point3I;
import org.jackhuang.hmcl.util.io.FileUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.nio.file.Path;
import java.time.Instant;
import java.util.OptionalInt;
import java.util.OptionalLong;
public sealed abstract class Schematic permits LitematicFile, SchemFile, NBTStructureFile {
public static boolean isFileSchematic(Path file) {
return SchematicType.getType(file) != null;
}
@Nullable
public static Schematic load(Path file) throws IOException {
var type = SchematicType.getType(file);
if (type == null) return null;
return switch (type) {
case LITEMATIC -> LitematicFile.load(file);
case SCHEM -> SchemFile.load(file);
case NBT_STRUCTURE -> NBTStructureFile.load(file);
};
}
private final Path file;
private final int dataVersion;
private final Point3I enclosingSize;
protected Schematic(Path file, int dataVersion, @Nullable Point3I enclosingSize) {
this.file = file;
this.dataVersion = dataVersion;
this.enclosingSize = enclosingSize;
}
public abstract SchematicType getType();
@NotNull
public Path getFile() {
return file;
}
public OptionalInt getVersion() {
return OptionalInt.empty();
}
/// Non-negative, otherwise empty
public OptionalInt getSubVersion() {
return OptionalInt.empty();
}
/// At least 100, otherwise empty
public OptionalInt getMinecraftDataVersion() {
/* 15w32a */
return dataVersion >= 100 ? OptionalInt.of(dataVersion) : OptionalInt.empty();
}
@Nullable
public String getMinecraftVersion() {
return getMinecraftDataVersion().isPresent() ? Integer.toString(getMinecraftDataVersion().getAsInt()) : null;
}
@NotNull
public String getName() {
return FileUtils.getNameWithoutExtension(getFile());
}
@Nullable
public String getAuthor() {
return null;
}
@Nullable
public Instant getTimeCreated() {
return null;
}
@Nullable
public Instant getTimeModified() {
return null;
}
public OptionalInt getRegionCount() {
return OptionalInt.empty();
}
public OptionalInt getTotalBlocks() {
return OptionalInt.empty();
}
@Nullable
public Point3I getEnclosingSize() {
return enclosingSize;
}
public OptionalLong getTotalVolume() {
var enclosingSize = getEnclosingSize();
if (enclosingSize != null) return OptionalLong.of((long) enclosingSize.x() * enclosingSize.y() * enclosingSize.z());
return OptionalLong.empty();
}
public int @Nullable [] getPreviewImageData() {
return null;
}
}
@@ -0,0 +1,45 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2026 huangyuhui <[email protected]> and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.jackhuang.hmcl.schematic;
import org.jackhuang.hmcl.util.io.FileUtils;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
public enum SchematicType {
LITEMATIC("litematic"),
NBT_STRUCTURE("nbt"),
SCHEM("schematic", "schem");
public static SchematicType getType(Path file) {
if (file == null || !Files.isRegularFile(file)) return null;
String ext = FileUtils.getExtension(file);
for (SchematicType type : values()) {
if (type.extensions.contains(ext)) return type;
}
return null;
}
public final List<String> extensions;
SchematicType(String... ext) {
this.extensions = List.of(ext);
}
}
@@ -0,0 +1,79 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2026 huangyuhui <[email protected]> and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.jackhuang.hmcl.util;
import org.glavo.nbt.io.NBTCodec;
import org.glavo.nbt.tag.*;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.nio.file.Path;
import java.time.Instant;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.OptionalLong;
public final class NBTUtils {
public static CompoundTag readCompressed(Path file) throws IOException {
return NBTCodec.of().readTag(file, TagType.COMPOUND);
}
public static OptionalLong tryGetLong(Tag tag) {
if (tag instanceof ValueTag<?> valueTag) {
Object val = valueTag.getValue();
if (val instanceof Long || val instanceof Integer || val instanceof Short || val instanceof Byte) {
return OptionalLong.of(((Number) val).longValue());
}
}
return OptionalLong.empty();
}
public static OptionalInt tryGetInt(Tag tag) {
var ol = tryGetLong(tag);
if (ol.isEmpty()) return OptionalInt.empty();
long l = ol.getAsLong();
int i = (int) l;
if (l == i) return OptionalInt.of(i);
return OptionalInt.empty();
}
public static Optional<Short> tryGetShort(Tag tag) {
var ol = tryGetLong(tag);
if (ol.isEmpty()) return Optional.empty();
long l = ol.getAsLong();
short i = (short) l;
if (l == i) return Optional.of(i);
return Optional.empty();
}
public static @Nullable Instant tryGetLongTimestamp(Tag tag) {
if (tag instanceof LongTag longTag) {
return Instant.ofEpochMilli(longTag.get());
}
return null;
}
public static @Nullable String tryGetString(Tag tag) {
return tag instanceof StringTag stringTag ? stringTag.get() : null;
}
private NBTUtils() {
}
}
@@ -0,0 +1,24 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2026 huangyuhui <[email protected]> and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.jackhuang.hmcl.util;
public record Point3I(int x, int y, int z) {
public static final Point3I ZERO = new Point3I(0, 0, 0);
}
@@ -1,53 +0,0 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2025 huangyuhui <[email protected]> and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.jackhuang.hmcl.schematic;
import javafx.geometry.Point3D;
import org.jackhuang.hmcl.game.CrashReportAnalyzerTest;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
import java.time.Instant;
import static org.junit.jupiter.api.Assertions.assertEquals;
public final class LitematicFileTest {
private static LitematicFile load(String name) throws IOException, URISyntaxException {
URL resource = CrashReportAnalyzerTest.class.getResource(name);
if (resource == null)
throw new IOException("Resource not found: " + name);
return LitematicFile.load(Paths.get(resource.toURI()));
}
@Test
public void test() throws Exception {
LitematicFile file = load("/schematics/test.litematic");
assertEquals("刷石机一桶岩浆下推爆破8.3万每小时", file.getName());
assertEquals("hsds", file.getAuthor());
assertEquals("", file.getDescription());
assertEquals(Instant.ofEpochMilli(1746443586433L), file.getTimeCreated());
assertEquals(Instant.ofEpochMilli(1746443586433L), file.getTimeModified());
assertEquals(1334, file.getTotalBlocks());
assertEquals(5746, file.getTotalVolume());
assertEquals(new Point3D(17, 26, 13), file.getEnclosingSize());
assertEquals(1, file.getRegionCount());
}
}
@@ -0,0 +1,88 @@
/*
* Hello Minecraft! Launcher
* Copyright (C) 2025 huangyuhui <[email protected]> and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.jackhuang.hmcl.schematic;
import org.jackhuang.hmcl.game.CrashReportAnalyzerTest;
import org.jackhuang.hmcl.util.Point3I;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
import java.time.Instant;
import static org.junit.jupiter.api.Assertions.assertEquals;
public final class SchematicTest {
private static Schematic load(String name) throws IOException, URISyntaxException {
URL resource = CrashReportAnalyzerTest.class.getResource(name);
if (resource == null)
throw new IOException("Resource not found: " + name);
return Schematic.load(Paths.get(resource.toURI()));
}
@Test
public void test() throws Exception {
{
LitematicFile lFile = (LitematicFile) load("/schematics/test.litematic");
assertEquals(SchematicType.LITEMATIC, lFile.getType());
assertEquals("刷石机一桶岩浆下推爆破8.3万每小时", lFile.getName());
assertEquals("hsds", lFile.getAuthor());
assertEquals("", lFile.getDescription());
assertEquals(Instant.ofEpochMilli(1746443586433L), lFile.getTimeCreated());
assertEquals(Instant.ofEpochMilli(1746443586433L), lFile.getTimeModified());
assertEquals(1334, lFile.getTotalBlocks().orElse(0));
assertEquals(5746, lFile.getTotalVolume().orElse(0));
assertEquals(new Point3I(17, 26, 13), lFile.getEnclosingSize());
assertEquals(1, lFile.getRegionCount().orElse(0));
assertEquals(4325, lFile.getMinecraftDataVersion().orElse(0));
assertEquals("4325", lFile.getMinecraftVersion());
assertEquals(7, lFile.getVersion().orElse(0));
assertEquals(1, lFile.getSubVersion().orElse(-1));
}
{
SchemFile sFile = (SchemFile) load("/schematics/test.schematic");
assertEquals(SchematicType.SCHEM, sFile.getType());
assertEquals("test", sFile.getName());
assertEquals(new Point3I(28, 35, 18), sFile.getEnclosingSize());
assertEquals(17640, sFile.getTotalVolume().orElse(0));
assertEquals("Alpha", sFile.getMinecraftVersion());
}
{
SchemFile sFileSponge = (SchemFile) load("/schematics/test.schem");
assertEquals(SchematicType.SCHEM, sFileSponge.getType());
assertEquals("test", sFileSponge.getName());
assertEquals(3465, sFileSponge.getMinecraftDataVersion().orElse(0));
assertEquals("3465", sFileSponge.getMinecraftVersion());
assertEquals(new Point3I(9, 5, 9), sFileSponge.getEnclosingSize());
}
{
NBTStructureFile nFile = (NBTStructureFile) load("/schematics/test.nbt");
assertEquals(SchematicType.NBT_STRUCTURE, nFile.getType());
assertEquals("test", nFile.getName());
assertEquals(new Point3I(9, 11, 13), nFile.getEnclosingSize());
assertEquals(1287, nFile.getTotalVolume().orElse(0));
assertEquals(3465, nFile.getMinecraftDataVersion().orElse(0));
assertEquals("3465", nFile.getMinecraftVersion());
}
}
}
Binary file not shown.
Binary file not shown.