diff --git a/core/src/main/java/art/arcane/iris/core/studio/bridge/SavedTileEncoding.java b/core/src/main/java/art/arcane/iris/core/studio/bridge/SavedTileEncoding.java new file mode 100644 index 000000000..d08bcef6f --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/studio/bridge/SavedTileEncoding.java @@ -0,0 +1,68 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * 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 . + */ + +package art.arcane.iris.core.studio.bridge; + +import art.arcane.iris.core.studio.map.MapLabel; +import art.arcane.iris.core.studio.saved.SavedTile; +import com.google.gson.Gson; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.StandardCharsets; +import java.util.List; + +/** + * A {@link SavedTile} as the studio reads it, little endian: + *
+ * u32 header length | header, UTF-8 JSON | padding to 4 bytes
+ * i16 groundY[size²] | padding to 4 | i16 waterSurfaceY[size²] | padding to 4
+ * i16 blocks[size²] | padding to 4 | i16 biomes[size²]
+ * 
+ * The header holds the size, the scale, the block names and the biome labels the grids index, and the values that mean + * no ground and no water. + */ +final class SavedTileEncoding { + private static final int ALIGNMENT_BYTES = 4; + + private SavedTileEncoding() { + } + + static byte[] encode(SavedTile tile, List biomes, Gson gson) { + byte[] header = gson.toJson(new Header(tile.size(), tile.blocksPerPixel(), tile.blockNames(), biomes, + SavedTile.NO_GROUND, SavedTile.NO_WATER)).getBytes(StandardCharsets.UTF_8); + List grids = List.of(tile.groundY(), tile.waterSurfaceY(), tile.blocks(), tile.biomes()); + int gridBytes = aligned(tile.size() * tile.size() * Short.BYTES); + ByteBuffer buffer = ByteBuffer.allocate(aligned(Integer.BYTES + header.length) + gridBytes * grids.size()) + .order(ByteOrder.LITTLE_ENDIAN); + buffer.putInt(header.length).put(header); + buffer.position(aligned(buffer.position())); + for (short[] grid : grids) { + buffer.asShortBuffer().put(grid); + buffer.position(buffer.position() + gridBytes); + } + return buffer.array(); + } + + private static int aligned(int bytes) { + return (bytes + ALIGNMENT_BYTES - 1) / ALIGNMENT_BYTES * ALIGNMENT_BYTES; + } + + private record Header(int size, int blocksPerPixel, List blocks, List biomes, int noGround, int noWater) { + } +} diff --git a/core/src/main/java/art/arcane/iris/core/studio/bridge/StudioBridge.java b/core/src/main/java/art/arcane/iris/core/studio/bridge/StudioBridge.java index 0212498da..4b8e0f7d0 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/bridge/StudioBridge.java +++ b/core/src/main/java/art/arcane/iris/core/studio/bridge/StudioBridge.java @@ -27,6 +27,10 @@ import art.arcane.iris.core.studio.map.MapPickInspection; import art.arcane.iris.core.studio.map.MapTile; import art.arcane.iris.core.studio.map.MapView; import art.arcane.iris.core.studio.assets.MinecraftAssets; +import art.arcane.iris.core.studio.saved.SavedBiomeLabels; +import art.arcane.iris.core.studio.saved.SavedTile; +import art.arcane.iris.core.studio.saved.SavedWorld; +import art.arcane.iris.core.studio.saved.SavedWorlds; import art.arcane.iris.core.studio.scene.StudioScenes; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.render.RenderType; @@ -85,6 +89,8 @@ public final class StudioBridge implements AutoCloseable { private static final int LARGEST_TILE_SIZE = 512; private static final double SMALLEST_BLOCKS_PER_PIXEL = 1D / 16D; private static final double LARGEST_BLOCKS_PER_PIXEL = 4_096D; + // Each pixel reads the chunk it lands in, so a saved world is shown no farther out than a pixel per chunk. + private static final int LARGEST_SAVED_BLOCKS_PER_PIXEL = 16; private static final long ENTITY_WAIT_MILLIS = 3_000L; private static final int STATUS_OK = 200; private static final int STATUS_NO_CONTENT = 204; @@ -207,6 +213,9 @@ public final class StudioBridge implements AutoCloseable { case "scenes" -> sendJson(exchange, STATUS_OK, StudioScenes.of(get(exchange).engine()).views()); case "scene-entries" -> sendJson(exchange, STATUS_OK, sceneEntries(get(exchange).engine(), query)); case "scene" -> sendBytes(exchange, "application/octet-stream", scene(get(exchange).engine(), query)); + case "saved-worlds" -> sendJson(exchange, STATUS_OK, savedWorlds(exchange)); + case "saved-start" -> sendJson(exchange, STATUS_OK, savedStart(exchange, query)); + case "saved-tile" -> sendBytes(exchange, "application/octet-stream", savedTile(get(exchange).engine(), query)); case "events" -> streamEvents(exchange); case "teleport" -> teleport(exchange, query); case "open" -> openInEditor(exchange, query); @@ -315,6 +324,38 @@ public final class StudioBridge implements AutoCloseable { return SceneEncoding.encode(scene.orElseThrow(() -> new RequestError(STATUS_NOT_FOUND, "No scene " + key)), gson); } + private static List savedWorlds(HttpExchange exchange) { + requireMethod(exchange, "GET"); + return SavedWorlds.shared().list(); + } + + private static SavedWorld.Start savedStart(HttpExchange exchange, Query query) { + requireMethod(exchange, "GET"); + return savedWorld(query).start() + .orElseThrow(() -> new RequestError(STATUS_NOT_FOUND, "Nothing finished is saved in " + query.text("world"))); + } + + private byte[] savedTile(Engine engine, Query query) { + int size = query.whole("size", DEFAULT_TILE_SIZE); + int blocksPerPixel = query.whole("scale", 1); + if (size < 1 || size > LARGEST_TILE_SIZE) { + throw new RequestError(STATUS_BAD_REQUEST, "A tile is 1 to " + LARGEST_TILE_SIZE + " pixels"); + } + if (blocksPerPixel < 1 || blocksPerPixel > LARGEST_SAVED_BLOCKS_PER_PIXEL) { + throw new RequestError(STATUS_BAD_REQUEST, "The scale is 1 to " + LARGEST_SAVED_BLOCKS_PER_PIXEL + " whole blocks per pixel"); + } + SavedTile tile = SavedTile.sample(savedWorld(query), query.whole("x", 0), query.whole("z", 0), blocksPerPixel, size); + return SavedTileEncoding.encode(tile, SavedBiomeLabels.of(engine).labelsOf(tile.biomeNames()), gson); + } + + private static SavedWorld savedWorld(Query query) { + try { + return SavedWorlds.shared().open(query.text("world")); + } catch (NoSuchElementException unknown) { + throw new RequestError(STATUS_NOT_FOUND, unknown.getMessage()); + } + } + // Asset paths name one file of one Minecraft version, so a studio may keep what it fetched for as long as it runs. private static void sendAsset(HttpExchange exchange, String endpoint) throws IOException { requireMethod(exchange, "GET"); diff --git a/core/src/main/java/art/arcane/iris/core/studio/map/MapLabel.java b/core/src/main/java/art/arcane/iris/core/studio/map/MapLabel.java index 386a7c355..d85960907 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/map/MapLabel.java +++ b/core/src/main/java/art/arcane/iris/core/studio/map/MapLabel.java @@ -32,7 +32,7 @@ import art.arcane.iris.engine.object.world.region.IrisRegion; public record MapLabel(Kind kind, String key, String name, int color) { private static final int RGB = 0xFFFFFF; - static MapLabel of(Engine engine, IrisBiome biome, RenderType colorType) { + public static MapLabel of(Engine engine, IrisBiome biome, RenderType colorType) { return new MapLabel(Kind.BIOME, biome.getLoadKey(), biome.getName(), biome.getColor(engine, colorType).getRGB() & RGB); } diff --git a/core/src/main/java/art/arcane/iris/core/studio/saved/RegionFile.java b/core/src/main/java/art/arcane/iris/core/studio/saved/RegionFile.java new file mode 100644 index 000000000..a4544d4e0 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/studio/saved/RegionFile.java @@ -0,0 +1,94 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * 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 . + */ + +package art.arcane.iris.core.studio.saved; + +import art.arcane.iris.spi.IrisLogging; +import art.arcane.volmlib.util.nbt.io.NBTDeserializer; +import art.arcane.volmlib.util.nbt.tag.CompoundTag; +import art.arcane.volmlib.util.nbt.tag.Tag; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.RandomAccessFile; +import java.nio.file.Path; +import java.util.Optional; +import java.util.zip.GZIPInputStream; +import java.util.zip.InflaterInputStream; + +/** + * One Anvil region file ({@code r.X.Z.mca}), read a chunk at a time. The server may be writing the file meanwhile, so a + * chunk that can't be read counts as not saved rather than failing the view. + */ +record RegionFile(Path file) { + static final int CHUNKS_ACROSS = 32; + private static final int SECTOR_BYTES = 4_096; + private static final int GZIP = 1; + private static final int ZLIB = 2; + private static final int UNCOMPRESSED = 3; + // Chunks too large for the region file live in a file of their own; the view leaves them out. + private static final int STORED_OUTSIDE_FLAG = 0x80; + + /** + * The chunk's NBT, or empty where none was saved or it can't be read. + * + * @param chunkX chunk within the region, 0 to 31 + * @param chunkZ chunk within the region, 0 to 31 + */ + Optional chunk(int chunkX, int chunkZ) { + try (RandomAccessFile region = new RandomAccessFile(file.toFile(), "r")) { + region.seek((long) (chunkZ * CHUNKS_ACROSS + chunkX) * Integer.BYTES); + int location = region.readInt(); + int firstSector = location >>> 8; + if (firstSector == 0) { + return Optional.empty(); + } + region.seek((long) firstSector * SECTOR_BYTES); + int length = region.readInt(); + int compression = region.readUnsignedByte(); + if ((compression & STORED_OUTSIDE_FLAG) != 0 || length <= 1) { + return Optional.empty(); + } + byte[] body = new byte[length - 1]; + region.readFully(body); + return readNbt(compression, body); + } catch (IOException | RuntimeException unreadable) { + IrisLogging.debug("Could not read chunk " + chunkX + ", " + chunkZ + " of " + file + ": " + unreadable); + return Optional.empty(); + } + } + + private Optional readNbt(int compression, byte[] body) throws IOException { + InputStream bytes = new ByteArrayInputStream(body); + InputStream nbt = switch (compression) { + case GZIP -> new GZIPInputStream(bytes); + case ZLIB -> new InflaterInputStream(bytes); + case UNCOMPRESSED -> bytes; + default -> null; + }; + if (nbt == null) { + IrisLogging.debug("Chunk compression " + compression + " in " + file + " is not read by the studio"); + return Optional.empty(); + } + try (nbt) { + Tag root = new NBTDeserializer(false).fromStream(nbt).getTag(); + return root instanceof CompoundTag chunk ? Optional.of(chunk) : Optional.empty(); + } + } +} diff --git a/core/src/main/java/art/arcane/iris/core/studio/saved/SavedBiomeLabels.java b/core/src/main/java/art/arcane/iris/core/studio/saved/SavedBiomeLabels.java new file mode 100644 index 000000000..89d6dcf5b --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/studio/saved/SavedBiomeLabels.java @@ -0,0 +1,86 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * 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 . + */ + +package art.arcane.iris.core.studio.saved; + +import art.arcane.iris.core.studio.map.MapLabel; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.render.RenderType; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.world.biome.custom.IrisBiomeCustom; + +import java.awt.Color; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * Saved biome keys as the map shows biomes. A key the open pack saves its custom biomes under, such as + * {@code overworld:estranged_candlewood}, gets that biome's map colour and name; any other key a steady colour of its own. + */ +public final class SavedBiomeLabels { + private static final int RGB = 0xFFFFFF; + private static final float OTHER_SATURATION = 0.45F; + private static final float OTHER_BRIGHTNESS = 0.78F; + + private final Map byKey; + + private SavedBiomeLabels(Map byKey) { + this.byKey = byKey; + } + + public static SavedBiomeLabels of(Engine engine) { + Map byKey = new HashMap<>(); + String namespace = engine.getDimension().getLoadKey(); + for (IrisBiome biome : engine.getAllBiomes()) { + if (!biome.isCustom()) { + continue; + } + MapLabel label = MapLabel.of(engine, biome, RenderType.BIOME); + for (IrisBiomeCustom custom : biome.getCustomDerivitives()) { + byKey.putIfAbsent(namespace + ":" + custom.getId(), label); + } + } + return new SavedBiomeLabels(byKey); + } + + public List labelsOf(List keys) { + return keys.stream().map(this::labelOf).toList(); + } + + MapLabel labelOf(String key) { + MapLabel known = byKey.get(key); + return known != null ? known : new MapLabel(MapLabel.Kind.BIOME, key, displayName(key), steadyColor(key)); + } + + static String displayName(String key) { + String path = key.contains(":") ? key.substring(key.indexOf(':') + 1) : key; + return Arrays.stream(path.split("[_/]")) + .filter(word -> !word.isEmpty()) + .map(word -> word.substring(0, 1).toUpperCase(Locale.ROOT) + word.substring(1)) + .collect(Collectors.joining(" ")); + } + + private static int steadyColor(String key) { + float hue = Math.floorMod(key.hashCode(), 360) / 360F; + return Color.HSBtoRGB(hue, OTHER_SATURATION, OTHER_BRIGHTNESS) & RGB; + } +} diff --git a/core/src/main/java/art/arcane/iris/core/studio/saved/SavedChunk.java b/core/src/main/java/art/arcane/iris/core/studio/saved/SavedChunk.java new file mode 100644 index 000000000..582a26d91 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/studio/saved/SavedChunk.java @@ -0,0 +1,188 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * 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 . + */ + +package art.arcane.iris.core.studio.saved; + +import art.arcane.volmlib.util.nbt.tag.CompoundTag; +import art.arcane.volmlib.util.nbt.tag.ListTag; +import art.arcane.volmlib.util.nbt.tag.StringTag; +import art.arcane.volmlib.util.nbt.tag.Tag; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * One saved chunk as Minecraft 1.18 and later store it: block states and biomes by section, palette plus packed + * indices, and the heightmaps. + */ +final class SavedChunk { + static final int BLOCKS_ACROSS = 16; + static final String AIR = "minecraft:air"; + static final String UNKNOWN = "minecraft:unknown"; + private static final int COLUMNS = BLOCKS_ACROSS * BLOCKS_ACROSS; + private static final int BIOME_CELLS_ACROSS = 4; + private static final int SMALLEST_BLOCK_INDEX_BITS = 4; + private static final String SURFACE_HEIGHTMAP = "WORLD_SURFACE"; + // Terrain and heightmaps are final from the features stage on; pregenerated chunks no player visited stop short of full. + private static final Set FINISHED_TERRAIN_STATUSES = Stream.of("features", "initialize_light", "light", "spawn", + "heightmaps", "full") + .flatMap(status -> Stream.of(status, "minecraft:" + status)) + .collect(Collectors.toUnmodifiableSet()); + + private final int minY; + private final long[] surfaceHeights; + private final int surfaceBits; + private final Map sectionsByY; + + private SavedChunk(int minY, long[] surfaceHeights, int surfaceBits, Map sectionsByY) { + this.minY = minY; + this.surfaceHeights = surfaceHeights; + this.surfaceBits = surfaceBits; + this.sectionsByY = sectionsByY; + } + + /** The chunk, or empty where its terrain is not finished yet or it has no surface heightmap. */ + static Optional of(CompoundTag root) { + if (!FINISHED_TERRAIN_STATUSES.contains(root.getString("Status"))) { + return Optional.empty(); + } + long[] surface = root.containsKey("Heightmaps") ? root.getCompoundTag("Heightmaps").getLongArray(SURFACE_HEIGHTMAP) : new long[0]; + if (surface.length == 0) { + return Optional.empty(); + } + Map sections = sectionsByY(root); + int lowestSection = root.containsKey("yPos") ? root.getInt("yPos") : lowestKey(sections); + int minY = lowestSection * BLOCKS_ACROSS; + int worldHeight = (highestKey(sections) - lowestSection + 1) * BLOCKS_ACROSS; + return Optional.of(new SavedChunk(minY, surface, heightmapBits(worldHeight, surface.length), sections)); + } + + int minY() { + return minY; + } + + /** The top block of the column, plants and trees included, or {@code minY - 1} where it holds none. */ + int surfaceY(int x, int z) { + return minY + (int) PackedIndices.get(surfaceHeights, surfaceBits, z * BLOCKS_ACROSS + x) - 1; + } + + /** The block's name, such as {@code minecraft:stone}, without its properties. */ + String blockAt(int x, int y, int z) { + CompoundTag section = sectionsByY.get(Math.floorDiv(y, BLOCKS_ACROSS)); + if (section == null || !section.containsKey("block_states")) { + return AIR; + } + CompoundTag states = section.getCompoundTag("block_states"); + ListTag palette = states.getListTag("palette"); + int index = (Math.floorMod(y, BLOCKS_ACROSS) * BLOCKS_ACROSS + z) * BLOCKS_ACROSS + x; + return nameOf(paletteEntry(palette, states.getLongArray("data"), Math.max(SMALLEST_BLOCK_INDEX_BITS, bitsFor(palette.size())), index)); + } + + /** The biome's key, such as {@code minecraft:plains}; biomes are stored once per 4 blocks across. */ + String biomeAt(int x, int y, int z) { + CompoundTag section = sectionsByY.get(Math.floorDiv(y, BLOCKS_ACROSS)); + if (section == null || !section.containsKey("biomes")) { + return UNKNOWN; + } + CompoundTag biomes = section.getCompoundTag("biomes"); + ListTag palette = biomes.getListTag("palette"); + int cellY = Math.floorMod(y, BLOCKS_ACROSS) / BIOME_CELLS_ACROSS; + int index = (cellY * BIOME_CELLS_ACROSS + z / BIOME_CELLS_ACROSS) * BIOME_CELLS_ACROSS + x / BIOME_CELLS_ACROSS; + Tag biome = paletteEntry(palette, biomes.getLongArray("data"), bitsFor(palette.size()), index); + return biome instanceof StringTag key ? key.getValue() : UNKNOWN; + } + + private static Tag paletteEntry(ListTag palette, long[] data, int bits, int index) { + if (palette == null || palette.size() == 0) { + return null; + } + if (palette.size() == 1 || data.length == 0) { + return palette.get(0); + } + int entry = (int) PackedIndices.get(data, bits, index); + return entry < palette.size() ? palette.get(entry) : null; + } + + // A block with properties is a compound naming it under Name; since 26.1 a block without them may be its bare name. + private static String nameOf(Tag block) { + return switch (block) { + case StringTag name -> name.getValue(); + case CompoundTag compound when !compound.getString("Name").isEmpty() -> compound.getString("Name"); + case CompoundTag compound when !compound.getString("").isEmpty() -> compound.getString(""); + case null, default -> UNKNOWN; + }; + } + + private static Map sectionsByY(CompoundTag root) { + Map sections = new HashMap<>(); + ListTag saved = root.getListTag("sections"); + if (saved == null) { + return sections; + } + for (Tag section : saved) { + if (section instanceof CompoundTag compound && compound.containsKey("block_states")) { + sections.put((int) compound.getByte("Y"), compound); + } + } + return sections; + } + + private static int lowestKey(Map sections) { + return sections.keySet().stream().mapToInt(Integer::intValue).min().orElse(0); + } + + private static int highestKey(Map sections) { + return sections.keySet().stream().mapToInt(Integer::intValue).max().orElse(0); + } + + // Heights run from 0 to the world's height; where the sections leave that unsure, the array's length decides. + private static int heightmapBits(int worldHeight, int longs) { + int fromHeight = bitsFor(worldHeight + 1); + if (longsFor(fromHeight) == longs) { + return fromHeight; + } + int perLong = (COLUMNS + longs - 1) / longs; + return Long.SIZE / perLong; + } + + private static int longsFor(int bits) { + int perLong = Long.SIZE / bits; + return (COLUMNS + perLong - 1) / perLong; + } + + private static int bitsFor(int values) { + return values <= 1 ? 0 : Integer.SIZE - Integer.numberOfLeadingZeros(values - 1); + } + + /** Values packed into longs low bits first, none spanning two longs, as Minecraft packs them since 1.16. */ + static final class PackedIndices { + private PackedIndices() { + } + + static long get(long[] data, int bits, int index) { + int perLong = Long.SIZE / bits; + long word = data[index / perLong]; + int shift = (index % perLong) * bits; + return (word >>> shift) & ((1L << bits) - 1); + } + } +} diff --git a/core/src/main/java/art/arcane/iris/core/studio/saved/SavedGround.java b/core/src/main/java/art/arcane/iris/core/studio/saved/SavedGround.java new file mode 100644 index 000000000..095428422 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/studio/saved/SavedGround.java @@ -0,0 +1,83 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * 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 . + */ + +package art.arcane.iris.core.studio.saved; + +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.data.B; + +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Which saved blocks are the ground. The view shows ground without objects, so only whole opaque blocks count: plants, + * fences, slabs and tree trunks are looked past, and water is looked through. + */ +@FunctionalInterface +interface SavedGround { + Set AIR_BLOCKS = Set.of("minecraft:air", "minecraft:cave_air", "minecraft:void_air"); + // Surfaces that aren't whole opaque blocks but read as the ground they lie on, when they lie on ground: snow on a + // treetop or ice on a lake is looked past. + Set THIN_GROUND = Set.of("minecraft:ice", "minecraft:frosted_ice", "minecraft:snow", "minecraft:lava", + "minecraft:dirt_path", "minecraft:farmland"); + + boolean isGround(String block); + + static boolean isAir(String block) { + return AIR_BLOCKS.contains(block); + } + + static boolean isThin(String block) { + return THIN_GROUND.contains(block); + } + + static boolean isWater(String block) { + return block.equals("minecraft:water") || block.equals("minecraft:bubble_column") || block.equals("minecraft:sea_pickle") + || block.endsWith("_fan") || block.contains("seagrass") || block.contains("kelp") + || (block.contains("coral") && !block.endsWith("_block")); + } + + /** Asks the server's block registry; a block it doesn't know is ground, so a column never runs down to the floor. */ + static SavedGround platform() { + return new PlatformGround(); + } + + final class PlatformGround implements SavedGround { + private static final List TRUNK_SUFFIXES = List.of("_log", "_wood", "_stem", "_hyphae", "_mushroom_block"); + + private final Map groundByBlock = new ConcurrentHashMap<>(); + + @Override + public boolean isGround(String block) { + return groundByBlock.computeIfAbsent(block, PlatformGround::looksLikeGround); + } + + private static boolean looksLikeGround(String block) { + if (isThin(block)) { + return true; + } + if (TRUNK_SUFFIXES.stream().anyMatch(block::endsWith)) { + return false; + } + PlatformBlockState state = B.getStateOrNull(block, false); + return state == null || state.isOccluding(); + } + } +} diff --git a/core/src/main/java/art/arcane/iris/core/studio/saved/SavedRegion.java b/core/src/main/java/art/arcane/iris/core/studio/saved/SavedRegion.java new file mode 100644 index 000000000..a85b79941 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/studio/saved/SavedRegion.java @@ -0,0 +1,224 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * 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 . + */ + +package art.arcane.iris.core.studio.saved; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicIntegerArray; + +/** + * What the view needs of one region file, 512 by 512 columns: the ground's top block under any water, its block and + * biome, and where the water over it ends. Columns of chunks whose terrain isn't finished have no ground. + *

+ * A chunk is read the first time one of its columns is asked for, so a view far out, which asks for a column every few + * blocks, reads only the chunks it lands in. Called from several bridge threads at once. + */ +final class SavedRegion { + static final int BLOCKS_ACROSS = RegionFile.CHUNKS_ACROSS * SavedChunk.BLOCKS_ACROSS; + static final int NO_WATER = Short.MIN_VALUE; + private static final int CHUNK_COUNT = RegionFile.CHUNKS_ACROSS * RegionFile.CHUNKS_ACROSS; + private static final int CHUNK_COLUMNS = SavedChunk.BLOCKS_ACROSS * SavedChunk.BLOCKS_ACROSS; + // Chunks share a lock with the others in their stripe, so different chunks of one region mostly read side by side. + private static final int CHUNK_LOCK_STRIPES = 64; + private static final short NO_GROUND = Short.MIN_VALUE; + /** Where no region file was saved: every column is ungenerated. */ + static final SavedRegion NOTHING_SAVED = new SavedRegion((chunkX, chunkZ) -> Optional.empty(), block -> true); + + private final ChunkSource source; + private final SavedGround ground; + private final AtomicIntegerArray readChunks = new AtomicIntegerArray(CHUNK_COUNT); + private final Object[] chunkLocks = new Object[CHUNK_LOCK_STRIPES]; + // Columns are written while holding this region, and read once their chunk is marked read. + private final short[] groundY = new short[BLOCKS_ACROSS * BLOCKS_ACROSS]; + private final short[] waterSurfaceY = new short[BLOCKS_ACROSS * BLOCKS_ACROSS]; + private final short[] blockIds = new short[BLOCKS_ACROSS * BLOCKS_ACROSS]; + private final short[] biomeIds = new short[BLOCKS_ACROSS * BLOCKS_ACROSS]; + private final List blocks = new CopyOnWriteArrayList<>(); + private final List biomes = new CopyOnWriteArrayList<>(); + private final Map blockIndex = new HashMap<>(); + private final Map biomeIndex = new HashMap<>(); + private final Map waterColumnsBySurface = new HashMap<>(); + private int minY = Integer.MAX_VALUE; + private int lowestGround = Integer.MAX_VALUE; + private int highestGround = Integer.MIN_VALUE; + + /** Where a region's chunks are read from: chunk within the region, 0 to 31, to the chunk or empty. */ + @FunctionalInterface + interface ChunkSource { + Optional read(int chunkX, int chunkZ); + } + + SavedRegion(ChunkSource source, SavedGround ground) { + this.source = source; + this.ground = ground; + Arrays.setAll(chunkLocks, stripe -> new Object()); + Arrays.fill(groundY, NO_GROUND); + Arrays.fill(waterSurfaceY, (short) NO_WATER); + } + + static SavedRegion of(RegionFile file, SavedGround ground) { + return new SavedRegion((chunkX, chunkZ) -> file.chunk(chunkX, chunkZ).flatMap(SavedChunk::of), ground); + } + + /** + * The column at this block, or null where its chunk's terrain isn't finished. + * + * @param x block within the region, 0 to 511 + * @param z block within the region, 0 to 511 + */ + SavedColumn columnAt(int x, int z) { + readChunk(x / SavedChunk.BLOCKS_ACROSS, z / SavedChunk.BLOCKS_ACROSS); + int index = x + z * BLOCKS_ACROSS; + if (groundY[index] == NO_GROUND) { + return null; + } + return new SavedColumn(groundY[index], waterSurfaceY[index], blocks.get(blockIds[index]), biomes.get(biomeIds[index])); + } + + /** Reads every chunk not read yet, for what is measured over the whole region. */ + void readAll() { + for (int chunkZ = 0; chunkZ < RegionFile.CHUNKS_ACROSS; chunkZ++) { + for (int chunkX = 0; chunkX < RegionFile.CHUNKS_ACROSS; chunkX++) { + readChunk(chunkX, chunkZ); + } + } + } + + private void readChunk(int chunkX, int chunkZ) { + int chunk = chunkZ * RegionFile.CHUNKS_ACROSS + chunkX; + if (readChunks.get(chunk) == 1) { + return; + } + synchronized (chunkLocks[chunk % CHUNK_LOCK_STRIPES]) { + if (readChunks.get(chunk) == 1) { + return; + } + source.read(chunkX, chunkZ).ifPresent(saved -> + store(ChunkColumns.of(saved, ground), chunkX * SavedChunk.BLOCKS_ACROSS, chunkZ * SavedChunk.BLOCKS_ACROSS)); + readChunks.set(chunk, 1); + } + } + + private synchronized void store(ChunkColumns chunk, int originX, int originZ) { + minY = Math.min(minY, chunk.minY()); + for (int column = 0; column < CHUNK_COLUMNS; column++) { + int index = (originZ + column / SavedChunk.BLOCKS_ACROSS) * BLOCKS_ACROSS + originX + column % SavedChunk.BLOCKS_ACROSS; + int groundTop = chunk.groundY()[column]; + int waterTop = chunk.waterSurfaceY()[column]; + groundY[index] = (short) groundTop; + waterSurfaceY[index] = (short) waterTop; + blockIds[index] = idOf(chunk.blocks()[column], blockIndex, blocks); + biomeIds[index] = idOf(chunk.biomes()[column], biomeIndex, biomes); + lowestGround = Math.min(lowestGround, groundTop); + highestGround = Math.max(highestGround, Math.max(groundTop, waterTop)); + if (waterTop != NO_WATER) { + waterColumnsBySurface.merge(waterTop, 1, Integer::sum); + } + } + } + + private static short idOf(String name, Map index, List names) { + return index.computeIfAbsent(name, added -> { + names.add(added); + return (short) (names.size() - 1); + }); + } + + /** The water surface most water read in this region lies at, or {@link #NO_WATER} where none was read. */ + synchronized int seaLevel() { + return waterColumnsBySurface.entrySet().stream() + .max(Map.Entry.comparingByValue()) + .map(Map.Entry::getKey) + .orElse(NO_WATER); + } + + synchronized boolean isEmpty() { + return highestGround == Integer.MIN_VALUE; + } + + /** The world's lowest block, or {@link Integer#MAX_VALUE} where no finished chunk was read. */ + synchronized int minY() { + return minY; + } + + synchronized int lowestGround() { + return lowestGround; + } + + synchronized int highestGround() { + return highestGround; + } + + /** + * One column as saved. + * + * @param groundY the top block of the ground, under any water + * @param waterSurfaceY the top water block over it, or {@link #NO_WATER} + */ + record SavedColumn(int groundY, int waterSurfaceY, String block, String biome) { + } + + /** One chunk's columns, read without holding the region so other chunks can be read meanwhile. */ + private record ChunkColumns(int minY, short[] groundY, short[] waterSurfaceY, String[] blocks, String[] biomes) { + static ChunkColumns of(SavedChunk chunk, SavedGround ground) { + ChunkColumns columns = new ChunkColumns(chunk.minY(), new short[CHUNK_COLUMNS], new short[CHUNK_COLUMNS], + new String[CHUNK_COLUMNS], new String[CHUNK_COLUMNS]); + for (int z = 0; z < SavedChunk.BLOCKS_ACROSS; z++) { + for (int x = 0; x < SavedChunk.BLOCKS_ACROSS; x++) { + columns.read(chunk, ground, x, z); + } + } + return columns; + } + + // The heightmap only says where to start: blocks placed after it was saved can leave air or water above the ground. + private void read(SavedChunk chunk, SavedGround ground, int x, int z) { + int column = z * SavedChunk.BLOCKS_ACROSS + x; + int y = chunk.surfaceY(x, z); + int waterTop = NO_WATER; + String block = chunk.blockAt(x, y, z); + while (y > minY && !isSurface(chunk, ground, x, y, z, block)) { + if (waterTop == NO_WATER && SavedGround.isWater(block)) { + waterTop = y; + } + y--; + block = chunk.blockAt(x, y, z); + } + groundY[column] = (short) y; + waterSurfaceY[column] = (short) waterTop; + blocks[column] = block; + biomes[column] = chunk.biomeAt(x, y, z); + } + + private boolean isSurface(SavedChunk chunk, SavedGround ground, int x, int y, int z, String block) { + if (!isGround(block, ground)) { + return false; + } + return !SavedGround.isThin(block) || y <= minY || isGround(chunk.blockAt(x, y - 1, z), ground); + } + + private static boolean isGround(String block, SavedGround ground) { + return !SavedGround.isAir(block) && !SavedGround.isWater(block) && ground.isGround(block); + } + } +} diff --git a/core/src/main/java/art/arcane/iris/core/studio/saved/SavedTile.java b/core/src/main/java/art/arcane/iris/core/studio/saved/SavedTile.java new file mode 100644 index 000000000..47a5494bd --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/studio/saved/SavedTile.java @@ -0,0 +1,75 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * 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 . + */ + +package art.arcane.iris.core.studio.saved; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * A square of a saved world, one column per pixel: the column at each pixel's north west block, or no ground where no + * finished chunk holds it. Blocks and biomes are named once each and indexed per pixel. + * + * @param groundY per pixel, row by row from the north west; {@link #NO_GROUND} where nothing is saved + * @param waterSurfaceY per pixel, the top water block over the ground, or {@link #NO_WATER} + */ +public record SavedTile(int size, int blocksPerPixel, short[] groundY, short[] waterSurfaceY, short[] blocks, short[] biomes, + List blockNames, List biomeNames) { + public static final short NO_GROUND = Short.MIN_VALUE; + public static final short NO_WATER = (short) SavedRegion.NO_WATER; + + /** + * @param tileX tile index west to east; the tile starts at block {@code tileX * size * blocksPerPixel} + * @param blocksPerPixel whole blocks, as a saved world holds one column per block + */ + public static SavedTile sample(SavedWorld world, int tileX, int tileZ, int blocksPerPixel, int size) { + int pixels = size * size; + SavedTile tile = new SavedTile(size, blocksPerPixel, new short[pixels], new short[pixels], new short[pixels], new short[pixels], + new ArrayList<>(), new ArrayList<>()); + Map blockIds = new HashMap<>(); + Map biomeIds = new HashMap<>(); + long originX = (long) tileX * size * blocksPerPixel; + long originZ = (long) tileZ * size * blocksPerPixel; + for (int row = 0; row < size; row++) { + for (int column = 0; column < size; column++) { + int pixel = row * size + column; + SavedRegion.SavedColumn saved = world.columnAt((int) (originX + (long) column * blocksPerPixel), + (int) (originZ + (long) row * blocksPerPixel)); + if (saved == null) { + tile.groundY[pixel] = NO_GROUND; + tile.waterSurfaceY[pixel] = NO_WATER; + continue; + } + tile.groundY[pixel] = (short) saved.groundY(); + tile.waterSurfaceY[pixel] = (short) saved.waterSurfaceY(); + tile.blocks[pixel] = idOf(saved.block(), blockIds, tile.blockNames); + tile.biomes[pixel] = idOf(saved.biome(), biomeIds, tile.biomeNames); + } + } + return tile; + } + + private static short idOf(String name, Map ids, List names) { + return ids.computeIfAbsent(name, added -> { + names.add(added); + return (short) (names.size() - 1); + }); + } +} diff --git a/core/src/main/java/art/arcane/iris/core/studio/saved/SavedWorld.java b/core/src/main/java/art/arcane/iris/core/studio/saved/SavedWorld.java new file mode 100644 index 000000000..5037ccb18 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/studio/saved/SavedWorld.java @@ -0,0 +1,151 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * 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 . + */ + +package art.arcane.iris.core.studio.saved; + +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.FileTime; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Stream; + +/** + * A world on disk, read from its region files rather than generated, a chunk at a time as the view needs it. A region + * whose file changed since it was read is read again, so the view follows a world the server is still writing. + */ +public final class SavedWorld { + static final Pattern REGION_FILE = Pattern.compile("r\\.(-?\\d+)\\.(-?\\d+)\\.mca"); + // A region read from its file takes about 2 MB; the rest of the heap is the server's. + private static final long BYTES_PER_REGION = 2_100_000L; + private static final double HEAP_SHARE_FOR_REGIONS = 0.1; + private static final int FEWEST_REGIONS = 16; + private static final OpenRegion NOTHING_SAVED = new OpenRegion(SavedRegion.NOTHING_SAVED, null); + + private final Path regionFolder; + private final SavedGround ground; + private final Cache regions = Caffeine.newBuilder() + .maximumSize(heapShareCount()) + .build(); + + SavedWorld(Path regionFolder, SavedGround ground) { + this.regionFolder = regionFolder; + this.ground = ground; + } + + static boolean holdsRegionFiles(Path folder) { + if (!Files.isDirectory(folder)) { + return false; + } + try (Stream files = Files.list(folder)) { + return files.anyMatch(file -> REGION_FILE.matcher(file.getFileName().toString()).matches()); + } catch (IOException unreadable) { + return false; + } + } + + /** + * Where the view opens: the middle of the region file nearest the world's origin that holds finished terrain, with + * how low and high its ground goes. Empty when no region file does. + */ + public Optional start() { + for (int[] regionXZ : regionsByDistanceFromOrigin()) { + SavedRegion region = region(regionXZ[0], regionXZ[1]); + region.readAll(); + if (!region.isEmpty()) { + int half = SavedRegion.BLOCKS_ACROSS / 2; + int seaLevel = region.seaLevel(); + return Optional.of(new Start(regionXZ[0] * SavedRegion.BLOCKS_ACROSS + half, regionXZ[1] * SavedRegion.BLOCKS_ACROSS + half, + region.minY(), region.lowestGround(), region.highestGround(), seaLevel == SavedRegion.NO_WATER ? null : seaLevel)); + } + } + return Optional.empty(); + } + + /** The column at this block, or null where no finished chunk holds it. */ + SavedRegion.SavedColumn columnAt(int blockX, int blockZ) { + SavedRegion region = region(Math.floorDiv(blockX, SavedRegion.BLOCKS_ACROSS), Math.floorDiv(blockZ, SavedRegion.BLOCKS_ACROSS)); + return region.columnAt(Math.floorMod(blockX, SavedRegion.BLOCKS_ACROSS), Math.floorMod(blockZ, SavedRegion.BLOCKS_ACROSS)); + } + + private List regionsByDistanceFromOrigin() { + try (Stream files = Files.list(regionFolder)) { + return files.map(file -> REGION_FILE.matcher(file.getFileName().toString())) + .filter(Matcher::matches) + .map(match -> new int[]{Integer.parseInt(match.group(1)), Integer.parseInt(match.group(2))}) + .sorted(Comparator.comparingInt(regionXZ -> regionXZ[0] * regionXZ[0] + regionXZ[1] * regionXZ[1])) + .toList(); + } catch (IOException unreadable) { + return List.of(); + } + } + + private SavedRegion region(int regionX, int regionZ) { + long key = ((long) regionX << 32) | (regionZ & 0xFFFFFFFFL); + Path file = regionFolder.resolve("r." + regionX + "." + regionZ + ".mca"); + FileTime written = lastWritten(file); + OpenRegion open = regions.get(key, unused -> openRegion(file, written)); + if (!open.isCurrent(written)) { + open = openRegion(file, written); + regions.put(key, open); + } + return open.region(); + } + + private OpenRegion openRegion(Path file, FileTime written) { + if (written == null) { + return NOTHING_SAVED; + } + return new OpenRegion(SavedRegion.of(new RegionFile(file), ground), written); + } + + private static FileTime lastWritten(Path file) { + try { + return Files.isRegularFile(file) ? Files.getLastModifiedTime(file) : null; + } catch (IOException unreadable) { + return null; + } + } + + private static long heapShareCount() { + long fitting = (long) (Runtime.getRuntime().maxMemory() * HEAP_SHARE_FOR_REGIONS) / BYTES_PER_REGION; + return Math.max(FEWEST_REGIONS, fitting); + } + + /** A region in memory, with when its file was written as it was read; no file means nothing was saved there. */ + private record OpenRegion(SavedRegion region, FileTime written) { + boolean isCurrent(FileTime now) { + return Objects.equals(written, now); + } + } + + /** + * @param minY the world's lowest block + * @param seaLevel the top water block most water lies at, or null where the region holds no water + */ + public record Start(int centerX, int centerZ, int minY, int lowestGround, int highestGround, Integer seaLevel) { + } +} diff --git a/core/src/main/java/art/arcane/iris/core/studio/saved/SavedWorlds.java b/core/src/main/java/art/arcane/iris/core/studio/saved/SavedWorlds.java new file mode 100644 index 000000000..5a07c2563 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/studio/saved/SavedWorlds.java @@ -0,0 +1,129 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * 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 . + */ + +package art.arcane.iris.core.studio.saved; + +import art.arcane.iris.core.IrisWorldStorage; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.Stream; + +/** + * The worlds saved under the server's level folder, each a dimension folder holding region files, and the ones the + * studio opened. A world is named by its folder relative to the level folder, so the studio can only open those. + */ +public final class SavedWorlds { + private static final String REGION_FOLDER = "region"; + private static final String DIMENSIONS_FOLDER = "dimensions"; + // Before 26.1 the nether and the end lived in these folders of the level folder. + private static final Map LEGACY_DIMENSIONS = Map.of("DIM-1", "the_nether", "DIM1", "the_end"); + private static final String VANILLA_NAMESPACE = "minecraft"; + private static volatile SavedWorlds shared; + + private final Path levelRoot; + private final SavedGround ground; + private final Map opened = new ConcurrentHashMap<>(); + + SavedWorlds(Path levelRoot, SavedGround ground) { + this.levelRoot = levelRoot; + this.ground = ground; + } + + /** The server's saved worlds; their regions stay in memory between requests. */ + public static SavedWorlds shared() { + SavedWorlds current = shared; + if (current == null) { + synchronized (SavedWorlds.class) { + if (shared == null) { + shared = new SavedWorlds(IrisWorldStorage.levelRoot().toPath(), SavedGround.platform()); + } + current = shared; + } + } + return current; + } + + /** Every saved world, vanilla's first, then by namespace and name. */ + public List list() { + List worlds = new ArrayList<>(); + if (SavedWorld.holdsRegionFiles(levelRoot.resolve(REGION_FOLDER))) { + worlds.add(new Info(".", "overworld", VANILLA_NAMESPACE)); + } + LEGACY_DIMENSIONS.forEach((folder, name) -> { + if (SavedWorld.holdsRegionFiles(levelRoot.resolve(folder).resolve(REGION_FOLDER))) { + worlds.add(new Info(folder, name, VANILLA_NAMESPACE)); + } + }); + worlds.addAll(dimensionFolders()); + worlds.sort(Comparator.comparing((Info info) -> !info.namespace().equals(VANILLA_NAMESPACE)) + .thenComparing(Info::namespace) + .thenComparing(Info::name)); + return worlds; + } + + /** + * The world {@link #list} names {@code id}. + * + * @throws NoSuchElementException where it names none + */ + public SavedWorld open(String id) { + if (list().stream().noneMatch(info -> info.id().equals(id))) { + throw new NoSuchElementException("No saved world " + id); + } + return opened.computeIfAbsent(id, known -> new SavedWorld(levelRoot.resolve(known).resolve(REGION_FOLDER).normalize(), ground)); + } + + private List dimensionFolders() { + Path dimensions = levelRoot.resolve(DIMENSIONS_FOLDER); + if (!Files.isDirectory(dimensions)) { + return List.of(); + } + try (Stream namespaces = Files.list(dimensions)) { + return namespaces.filter(Files::isDirectory).flatMap(this::dimensionsIn).toList(); + } catch (IOException unreadable) { + return List.of(); + } + } + + private Stream dimensionsIn(Path namespace) { + try (Stream folders = Files.list(namespace)) { + return folders.filter(folder -> SavedWorld.holdsRegionFiles(folder.resolve(REGION_FOLDER))) + .map(folder -> new Info(levelRoot.relativize(folder).toString().replace('\\', '/'), + folder.getFileName().toString(), namespace.getFileName().toString())) + .toList() + .stream(); + } catch (IOException unreadable) { + return Stream.empty(); + } + } + + /** + * @param id the world's folder relative to the level folder, which {@link #open} takes + * @param namespace who added the dimension, such as {@code minecraft} or {@code iris} + */ + public record Info(String id, String name, String namespace) { + } +} diff --git a/core/src/test/java/art/arcane/iris/core/studio/saved/SavedWorldTest.java b/core/src/test/java/art/arcane/iris/core/studio/saved/SavedWorldTest.java new file mode 100644 index 000000000..1594ef09c --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/studio/saved/SavedWorldTest.java @@ -0,0 +1,268 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * 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 . + */ + +package art.arcane.iris.core.studio.saved; + +import art.arcane.volmlib.util.nbt.io.NBTSerializer; +import art.arcane.volmlib.util.nbt.io.NamedTag; +import art.arcane.volmlib.util.nbt.tag.CompoundTag; +import art.arcane.volmlib.util.nbt.tag.ListTag; +import art.arcane.volmlib.util.nbt.tag.StringTag; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.function.IntUnaryOperator; +import java.util.zip.DeflaterOutputStream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +public class SavedWorldTest { + private static final int MIN_SECTION = -4; + private static final int SECTIONS = 8; + private static final int MIN_Y = MIN_SECTION * 16; + private static final List PALETTE = List.of("minecraft:air", "minecraft:stone", "minecraft:oak_log", + "minecraft:oak_leaves", "minecraft:water", "minecraft:snow"); + private static final int AIR = 0; + private static final int STONE = 1; + private static final int LOG = 2; + private static final int LEAVES = 3; + private static final int WATER = 4; + private static final int SNOW = 5; + private static final int PLAIN_GROUND_TOP = 5; + private static final int TREE_GROUND_TOP = 10; + private static final int TREE_TOP = 15; + private static final int SNOWY_TREE_TOP = TREE_TOP + 1; + private static final int POND_FLOOR = 0; + private static final int POND_SURFACE = 5; + private static final SavedGround STONE_IS_GROUND = block -> block.equals("minecraft:stone") || block.equals("minecraft:snow"); + + @Rule + public TemporaryFolder folders = new TemporaryFolder(); + + @Test + public void groundIsTheTopWholeBlockUnderTreesAndWater() throws IOException { + SavedWorld world = new SavedWorld(regionFolderWithOneChunk(), STONE_IS_GROUND); + + SavedRegion.SavedColumn underTree = world.columnAt(0, 0); + assertEquals(TREE_GROUND_TOP, underTree.groundY()); + assertEquals(SavedRegion.NO_WATER, underTree.waterSurfaceY()); + assertEquals("minecraft:stone", underTree.block()); + assertEquals("test:meadow", underTree.biome()); + + SavedRegion.SavedColumn pond = world.columnAt(1, 0); + assertEquals(POND_FLOOR, pond.groundY()); + assertEquals(POND_SURFACE, pond.waterSurfaceY()); + + assertEquals(PLAIN_GROUND_TOP, world.columnAt(7, 9).groundY()); + } + + @Test + public void snowCountsAsGroundOnTheGroundButNotOnATree() throws IOException { + SavedWorld world = new SavedWorld(regionFolderWithOneChunk(), STONE_IS_GROUND); + + assertEquals(TREE_GROUND_TOP, world.columnAt(0, 0).groundY()); + SavedRegion.SavedColumn snowyGround = world.columnAt(2, 0); + assertEquals(PLAIN_GROUND_TOP + 1, snowyGround.groundY()); + assertEquals("minecraft:snow", snowyGround.block()); + } + + @Test + public void chunksWithUnfinishedTerrainOrNoFileHaveNoGround() throws IOException { + SavedWorld world = new SavedWorld(regionFolderWithOneChunk(), STONE_IS_GROUND); + + assertNull(world.columnAt(16, 0)); + assertNull(world.columnAt(-1, -1)); + } + + @Test + public void theViewStartsInTheMiddleOfTheRegionNearestTheOrigin() throws IOException { + SavedWorld.Start start = new SavedWorld(regionFolderWithOneChunk(), STONE_IS_GROUND).start().orElseThrow(); + + assertEquals(256, start.centerX()); + assertEquals(256, start.centerZ()); + assertEquals(MIN_Y, start.minY()); + assertEquals(POND_FLOOR, start.lowestGround()); + assertEquals(TREE_GROUND_TOP, start.highestGround()); + assertEquals(Integer.valueOf(POND_SURFACE), start.seaLevel()); + } + + @Test + public void aTileSamplesOneColumnEveryFewBlocksAndNamesEachBlockOnce() throws IOException { + SavedWorld world = new SavedWorld(regionFolderWithOneChunk(), STONE_IS_GROUND); + + SavedTile tile = SavedTile.sample(world, 0, 0, 2, 16); + + assertEquals(TREE_GROUND_TOP, tile.groundY()[0]); + assertEquals(PLAIN_GROUND_TOP + 1, tile.groundY()[1]); + assertEquals(PLAIN_GROUND_TOP, tile.groundY()[2]); + assertEquals(SavedTile.NO_GROUND, tile.groundY()[8]); + assertEquals(List.of("minecraft:stone", "minecraft:snow"), tile.blockNames()); + assertEquals(List.of("test:meadow"), tile.biomeNames()); + } + + @Test + public void savedWorldsAreTheLevelAndItsDimensionFoldersAndNoOthers() throws IOException { + Path level = folders.newFolder("level").toPath(); + writeRegion(level.resolve("region")); + writeRegion(level.resolve("dimensions/iris/demo/region")); + Files.createDirectories(level.resolve("dimensions/iris/empty/region")); + SavedWorlds worlds = new SavedWorlds(level, STONE_IS_GROUND); + + assertEquals(List.of(new SavedWorlds.Info(".", "overworld", "minecraft"), + new SavedWorlds.Info("dimensions/iris/demo", "demo", "iris")), worlds.list()); + assertEquals(TREE_GROUND_TOP, worlds.open("dimensions/iris/demo").columnAt(0, 0).groundY()); + assertThrows(NoSuchElementException.class, () -> worlds.open("../outside")); + } + + @Test + public void heightmapIndicesArePackedWithoutSpanningLongs() { + long[] packed = {(5L) | (7L << 9) | (300L << 18), 9L}; + + assertEquals(5L, SavedChunk.PackedIndices.get(packed, 9, 0)); + assertEquals(7L, SavedChunk.PackedIndices.get(packed, 9, 1)); + assertEquals(300L, SavedChunk.PackedIndices.get(packed, 9, 2)); + assertEquals(9L, SavedChunk.PackedIndices.get(packed, 9, 7)); + } + + private Path regionFolderWithOneChunk() throws IOException { + Path folder = folders.newFolder().toPath(); + writeRegion(folder); + assertTrue(SavedWorld.holdsRegionFiles(folder)); + return folder; + } + + private static void writeRegion(Path folder) throws IOException { + Files.createDirectories(folder); + byte[] finished = compressed(chunk("minecraft:full")); + byte[] unfinished = compressed(chunk("minecraft:noise")); + try (RandomAccessFile region = new RandomAccessFile(folder.resolve("r.0.0.mca").toFile(), "rw")) { + int finishedSectors = sectorsFor(finished); + region.seek(0); + region.writeInt((2 << 8) | finishedSectors); + region.writeInt(((2 + finishedSectors) << 8) | sectorsFor(unfinished)); + writeChunkAt(region, 2, finished); + writeChunkAt(region, 2 + finishedSectors, unfinished); + } + } + + private static void writeChunkAt(RandomAccessFile region, int sector, byte[] body) throws IOException { + region.seek(sector * 4_096L); + region.writeInt(body.length + 1); + region.writeByte(2); + region.write(body); + region.write(new byte[sectorsFor(body) * 4_096 - body.length - 5]); + } + + private static int sectorsFor(byte[] body) { + return (body.length + 5 + 4_095) / 4_096; + } + + private static byte[] compressed(CompoundTag chunk) throws IOException { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (DeflaterOutputStream zlib = new DeflaterOutputStream(bytes)) { + new NBTSerializer(false).toStream(new NamedTag("", chunk), zlib); + } + return bytes.toByteArray(); + } + + // Column (0, 0) is a log on stone with snowy leaves on top, (1, 0) a pond on stone, (2, 0) snow on stone, every + // other column stone to y 5. + private static CompoundTag chunk(String status) { + CompoundTag root = new CompoundTag(); + root.putString("Status", status); + root.putInt("yPos", MIN_SECTION); + ListTag sections = new ListTag<>(CompoundTag.class); + for (int section = MIN_SECTION; section < MIN_SECTION + SECTIONS; section++) { + sections.add(section(section)); + } + root.put("sections", sections); + CompoundTag heightmaps = new CompoundTag(); + heightmaps.putLongArray("WORLD_SURFACE", packed(8, 256, column -> topOf(column % 16, column / 16) + 1 - MIN_Y)); + root.put("Heightmaps", heightmaps); + return root; + } + + private static int topOf(int x, int z) { + if (x == 0 && z == 0) { + return SNOWY_TREE_TOP; + } + if (x == 2 && z == 0) { + return PLAIN_GROUND_TOP + 1; + } + return x == 1 && z == 0 ? POND_SURFACE : PLAIN_GROUND_TOP; + } + + private static int blockAt(int x, int y, int z) { + if (x == 0 && z == 0) { + return y <= TREE_GROUND_TOP ? STONE : y < TREE_TOP ? LOG : y == TREE_TOP ? LEAVES : y == SNOWY_TREE_TOP ? SNOW : AIR; + } + if (x == 1 && z == 0) { + return y <= POND_FLOOR ? STONE : y <= POND_SURFACE ? WATER : AIR; + } + if (x == 2 && z == 0) { + return y <= PLAIN_GROUND_TOP ? STONE : y == PLAIN_GROUND_TOP + 1 ? SNOW : AIR; + } + return y <= PLAIN_GROUND_TOP ? STONE : AIR; + } + + private static CompoundTag section(int sectionY) { + CompoundTag section = new CompoundTag(); + section.putByte("Y", (byte) sectionY); + CompoundTag states = new CompoundTag(); + states.put("palette", blockPalette()); + states.putLongArray("data", packed(4, 4_096, index -> blockAt(index % 16, sectionY * 16 + index / 256, (index / 16) % 16))); + section.put("block_states", states); + CompoundTag biomes = new CompoundTag(); + ListTag biomePalette = new ListTag<>(StringTag.class); + biomePalette.addString("test:meadow"); + biomes.put("palette", biomePalette); + section.put("biomes", biomes); + return section; + } + + // Water is written the way 26.1 writes a block without properties among others: its bare name under an empty key. + private static ListTag blockPalette() { + ListTag palette = new ListTag<>(CompoundTag.class); + for (String block : PALETTE) { + CompoundTag entry = new CompoundTag(); + entry.putString(block.equals("minecraft:water") ? "" : "Name", block); + palette.add(entry); + } + return palette; + } + + private static long[] packed(int bits, int count, IntUnaryOperator valueAt) { + int perLong = 64 / bits; + long[] data = new long[(count + perLong - 1) / perLong]; + for (int index = 0; index < count; index++) { + data[index / perLong] |= ((long) valueAt.applyAsInt(index)) << ((index % perLong) * bits); + } + return data; + } +}