diff --git a/core/src/main/java/art/arcane/iris/core/studio/bridge/MapTileEncoding.java b/core/src/main/java/art/arcane/iris/core/studio/bridge/MapTileEncoding.java index e7a4f682d..973ebdd7c 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/bridge/MapTileEncoding.java +++ b/core/src/main/java/art/arcane/iris/core/studio/bridge/MapTileEncoding.java @@ -33,8 +33,10 @@ import java.util.List; * u32 header length | header, UTF-8 JSON | padding to 4 bytes * i16 subjects[grid²] | padding to 4 | i16 regions[grid²] | padding to 4 * f32 heights[grid²], when the header says so | f32 pickNoise[grid²], when the header says so + * i16 ground[grid²] | padding to 4 | i16 cover[grid²], when the header names blocks * - * The header holds the size, the scale, the subject kind and the labels the grids index. Every array starts on a + * The header holds the size, the scale, the subject kind, the labels the grids index, and the blocks the ground and + * cover grids index when the tile carries the tops of its columns. Every array starts on a * multiple of 4 bytes, so the studio views them in place. */ final class MapTileEncoding { @@ -46,33 +48,41 @@ final class MapTileEncoding { static byte[] encode(MapTile tile, Gson gson) { boolean hasHeights = tile.heights() != null; boolean hasPickNoise = tile.pickNoise() != null; + MapTile.Blocks blocks = tile.blocks(); byte[] header = gson.toJson(new Header(tile.size(), tile.blocksPerPixel(), tile.subjectKind(), tile.labels(), - hasHeights, hasPickNoise)) + hasHeights, hasPickNoise, blocks == null ? null : blocks.names())) .getBytes(StandardCharsets.UTF_8); int cells = tile.gridSize() * tile.gridSize(); int length = aligned(Integer.BYTES + header.length) + aligned(cells * Short.BYTES) * 2 + (hasHeights ? cells * Float.BYTES : 0) - + (hasPickNoise ? cells * Float.BYTES : 0); + + (hasPickNoise ? cells * Float.BYTES : 0) + + (blocks == null ? 0 : aligned(cells * Short.BYTES) * 2); ByteBuffer buffer = ByteBuffer.allocate(length).order(ByteOrder.LITTLE_ENDIAN); buffer.putInt(header.length).put(header); align(buffer); - buffer.asShortBuffer().put(tile.subjects()); - buffer.position(buffer.position() + cells * Short.BYTES); - align(buffer); - buffer.asShortBuffer().put(tile.regions()); - buffer.position(buffer.position() + cells * Short.BYTES); - align(buffer); + putShorts(buffer, tile.subjects()); + putShorts(buffer, tile.regions()); if (hasHeights) { buffer.asFloatBuffer().put(tile.heights()); buffer.position(buffer.position() + cells * Float.BYTES); } if (hasPickNoise) { buffer.asFloatBuffer().put(tile.pickNoise()); + buffer.position(buffer.position() + cells * Float.BYTES); + } + if (blocks != null) { + putShorts(buffer, blocks.ground()); + putShorts(buffer, blocks.cover()); } return buffer.array(); } + private static void putShorts(ByteBuffer buffer, short[] grid) { + buffer.asShortBuffer().put(grid); + buffer.position(aligned(buffer.position() + grid.length * Short.BYTES)); + } + private static int aligned(int bytes) { return (bytes + ALIGNMENT_BYTES - 1) / ALIGNMENT_BYTES * ALIGNMENT_BYTES; } @@ -82,6 +92,6 @@ final class MapTileEncoding { } private record Header(int size, double blocksPerPixel, MapLabel.Kind subjectKind, List labels, - boolean heights, boolean pickNoise) { + boolean heights, boolean pickNoise, List blocks) { } } 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 2d7273090..8c897272b 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 @@ -22,6 +22,7 @@ import art.arcane.iris.core.gui.GuiHost; import art.arcane.iris.core.gui.GuiMarker; import art.arcane.iris.core.project.StudioEditor; import art.arcane.iris.core.project.StudioEditorLauncher; +import art.arcane.iris.core.studio.map.BlockSource; import art.arcane.iris.core.studio.map.MapHover; import art.arcane.iris.core.studio.map.MapLabel; import art.arcane.iris.core.studio.map.MapLayer; @@ -86,6 +87,7 @@ import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.BooleanSupplier; /** * A studio app's connection to one world: HTTP on the loopback interface, on a free port, each request carrying the @@ -591,11 +593,30 @@ public final class StudioBridge implements AutoCloseable { throw new RequestError(STATUS_BAD_REQUEST, "The scale is " + SMALLEST_BLOCKS_PER_PIXEL + " to " + LARGEST_BLOCKS_PER_PIXEL + " blocks per pixel"); } double tileBlocks = size * blocksPerPixel; - MapTile tile = session.renderer().render(layer, query.whole("x", 0) * tileBlocks, query.whole("z", 0) * tileBlocks, - blocksPerPixel, size, tileExtras(query), () -> closed || engine.isClosing() || engine.isClosed()); + double startX = query.whole("x", 0) * tileBlocks; + double startZ = query.whole("z", 0) * tileBlocks; + BooleanSupplier cancelled = () -> closed || engine.isClosing() || engine.isClosed(); + MapTile tile = session.renderer().render(layer, startX, startZ, blocksPerPixel, size, tileExtras(query), cancelled); + if (query.has("blocks")) { + tile = withBlocks(session, tile, startX, startZ, blockSource(query), cancelled); + } return MapTileEncoding.encode(tile, gson); } + private static MapTile withBlocks(StudioWorld.Session session, MapTile tile, double startX, double startZ, BlockSource source, + BooleanSupplier cancelled) { + try { + return session.renderer().withBlocks(tile, startX, startZ, source, cancelled); + } catch (IllegalArgumentException tooCoarse) { + throw new RequestError(STATUS_BAD_REQUEST, tooCoarse.getMessage()); + } + } + + private static BlockSource blockSource(Query query) { + return BlockSource.byId(query.text("blocks")) + .orElseThrow(() -> new RequestError(STATUS_BAD_REQUEST, "No block source " + query.text("blocks"))); + } + private static Set tileExtras(Query query) { Set extras = EnumSet.noneOf(MapTile.Extra.class); if (query.flag("heights")) { diff --git a/core/src/main/java/art/arcane/iris/core/studio/map/BlockSource.java b/core/src/main/java/art/arcane/iris/core/studio/map/BlockSource.java new file mode 100644 index 000000000..eba9a35ea --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/studio/map/BlockSource.java @@ -0,0 +1,49 @@ +/* + * 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.map; + +import java.util.Arrays; +import java.util.Optional; + +/** Where a tile's blocks come from. */ +public enum BlockSource { + /** The chunks generated in memory: what the world would hold, at a block a pixel or finer. */ + GENERATED("generated", 1D); + + private final String id; + private final double largestBlocksPerPixel; + + BlockSource(String id, double largestBlocksPerPixel) { + this.id = id; + this.largestBlocksPerPixel = largestBlocksPerPixel; + } + + public String id() { + return id; + } + + /** The coarsest scale the source is drawn at; a coarser tile would ask for more columns than it shows. */ + public double largestBlocksPerPixel() { + return largestBlocksPerPixel; + } + + public static Optional byId(String id) { + return Arrays.stream(values()).filter(source -> source.id.equals(id)).findFirst(); + } +} diff --git a/core/src/main/java/art/arcane/iris/core/studio/map/ColumnTops.java b/core/src/main/java/art/arcane/iris/core/studio/map/ColumnTops.java new file mode 100644 index 000000000..da61f453a --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/studio/map/ColumnTops.java @@ -0,0 +1,36 @@ +/* + * 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.map; + +/** What lies on top of the world's columns, from one {@link BlockSource}. */ +@FunctionalInterface +interface ColumnTops { + ColumnTop at(int worldX, int worldZ); + + /** + * The top of one column. + * + * @param groundY the height of its ground block above the dimension's bottom + * @param ground the ground block's key, or null where the column holds no ground + * @param cover the key of the block standing on the ground, such as grass or a layer of snow, or null for none + */ + record ColumnTop(int groundY, String ground, String cover) { + static final ColumnTop NOTHING = new ColumnTop(0, null, null); + } +} diff --git a/core/src/main/java/art/arcane/iris/core/studio/map/GeneratedChunks.java b/core/src/main/java/art/arcane/iris/core/studio/map/GeneratedChunks.java new file mode 100644 index 000000000..6c2a741e9 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/studio/map/GeneratedChunks.java @@ -0,0 +1,108 @@ +/* + * 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.map; + +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.GenerationSessionLease; +import art.arcane.iris.spi.PlatformBiome; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.project.context.IrisContext; +import art.arcane.iris.util.project.hunk.Hunk; +import com.github.benmanes.caffeine.cache.Caffeine; +import com.github.benmanes.caffeine.cache.LoadingCache; + +/** + * The tops of chunks generated for the studio alone: each chunk runs through the world's own stages into memory, so its + * columns hold what the world would, trees and structures included, and nothing is placed in the world. Generating + * plans the chunk's surroundings in the world's mantle, as generating it in the world would. A chunk is generated once + * and its top kept; asked for from several bridge threads at once. + */ +final class GeneratedChunks implements ColumnTops { + private static final int CHUNK_SHIFT = 4; + private static final int BLOCKS_ACROSS = 1 << CHUNK_SHIFT; + private static final int CHUNK_MASK = BLOCKS_ACROSS - 1; + // A chunk's top is about 5 KB, so this many stay under 50 MB. + private static final int MOST_CHUNKS_KEPT = 8192; + private static final String LEASE_NAME = "studio_block_preview"; + + private final Engine engine; + private final LoadingCache tops; + + GeneratedChunks(Engine engine) { + this.engine = engine; + this.tops = Caffeine.newBuilder().maximumSize(MOST_CHUNKS_KEPT).build(this::generate); + } + + @Override + public ColumnTop at(int worldX, int worldZ) { + ChunkTop chunk = tops.get(keyOf(worldX >> CHUNK_SHIFT, worldZ >> CHUNK_SHIFT)); + return chunk.columns[(worldZ & CHUNK_MASK) * BLOCKS_ACROSS + (worldX & CHUNK_MASK)]; + } + + private ChunkTop generate(long key) throws Exception { + int chunkX = (int) (key >> Integer.SIZE); + int chunkZ = (int) key; + int height = engine.getHeight(); + Hunk blocks = Hunk.newArrayHunk(BLOCKS_ACROSS, height, BLOCKS_ACROSS); + Hunk biomes = Hunk.newArrayHunk(BLOCKS_ACROSS, height, BLOCKS_ACROSS); + try (GenerationSessionLease lease = engine.acquireGenerationLease(LEASE_NAME); + IrisContext.Scope ignored = IrisContext.open(engine, lease.sessionId(), null)) { + engine.getGeneration().generate(chunkX << CHUNK_SHIFT, chunkZ << CHUNK_SHIFT, blocks, biomes, false, lease.sessionId()); + } + return ChunkTop.of(blocks); + } + + private static long keyOf(int chunkX, int chunkZ) { + return ((long) chunkX << Integer.SIZE) | (chunkZ & 0xFFFFFFFFL); + } + + private record ChunkTop(ColumnTop[] columns) { + static ChunkTop of(Hunk blocks) { + ColumnTop[] columns = new ColumnTop[BLOCKS_ACROSS * BLOCKS_ACROSS]; + for (int z = 0; z < BLOCKS_ACROSS; z++) { + for (int x = 0; x < BLOCKS_ACROSS; x++) { + columns[z * BLOCKS_ACROSS + x] = topOf(blocks, x, z); + } + } + return new ChunkTop(columns); + } + + // The ground is the highest block something can stand on, so a tree's leaves and a roof count; what stands on it + // without being ground, such as grass or a layer of snow, is its cover. + private static ColumnTop topOf(Hunk blocks, int x, int z) { + for (int y = blocks.getHeight() - 1; y >= 0; y--) { + PlatformBlockState block = blocks.get(x, y, z); + if (!isGround(block)) { + continue; + } + PlatformBlockState above = y + 1 < blocks.getHeight() ? blocks.get(x, y + 1, z) : null; + return new ColumnTop(y, block.key(), isCover(above) ? above.key() : null); + } + return ColumnTop.NOTHING; + } + + private static boolean isGround(PlatformBlockState block) { + return block != null && !block.isAir() && !block.isFluid() && block.isSolid(); + } + + private static boolean isCover(PlatformBlockState block) { + return block != null && !block.isAir() && !block.isFluid(); + } + } +} diff --git a/core/src/main/java/art/arcane/iris/core/studio/map/MapPickInspection.java b/core/src/main/java/art/arcane/iris/core/studio/map/MapPickInspection.java index dcff256e4..102702a52 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/map/MapPickInspection.java +++ b/core/src/main/java/art/arcane/iris/core/studio/map/MapPickInspection.java @@ -46,7 +46,7 @@ public final class MapPickInspection { private MapPickInspection() { } - /** @throws IllegalArgumentException for a view whose spots no noise picks, such as the height view */ + /** @throws IllegalArgumentException for a view whose spots no noise picks, such as a biome layer's */ public static Inspection measure(Engine engine, MapLayer layer, Area area) { if (layer.previews()) { return measurePreview(engine, layer.previewRegion(), area); diff --git a/core/src/main/java/art/arcane/iris/core/studio/map/MapPickPath.java b/core/src/main/java/art/arcane/iris/core/studio/map/MapPickPath.java index 729136c1e..640a7fcc1 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/map/MapPickPath.java +++ b/core/src/main/java/art/arcane/iris/core/studio/map/MapPickPath.java @@ -56,7 +56,7 @@ public final class MapPickPath { case LAND_BIOMES -> addListStep(path, engine, view, region, InferredType.LAND, x, z); case SEA_BIOMES -> addListStep(path, engine, view, region, InferredType.SEA, x, z); case CAVE_BIOMES -> addListStep(path, engine, view, region, InferredType.CAVE, x, z); - case BIOMES, REGIONS, HEIGHT -> addBaseBiomeSteps(path, engine, view, region, x, z); + case BIOMES, REGIONS -> addBaseBiomeSteps(path, engine, view, region, x, z); } return path; } diff --git a/core/src/main/java/art/arcane/iris/core/studio/map/MapTile.java b/core/src/main/java/art/arcane/iris/core/studio/map/MapTile.java index 7a5c5641c..689f5b55a 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/map/MapTile.java +++ b/core/src/main/java/art/arcane/iris/core/studio/map/MapTile.java @@ -31,11 +31,28 @@ import java.util.List; * @param heights each cell's terrain height, or null when it was not asked for * @param pickNoise each cell's noise value that settled its pick, 0 to 1 and NaN where nothing picked it; null when it * was not asked for or the layer has none + * @param blocks the block on top of each cell's column, or null when none were asked for */ public record MapTile(int size, double blocksPerPixel, MapLabel.Kind subjectKind, List labels, - short[] subjects, short[] regions, float[] heights, float[] pickNoise) { + short[] subjects, short[] regions, float[] heights, float[] pickNoise, Blocks blocks) { public static final short NO_LABEL = -1; + /** + * The top of each cell's column. + * + * @param names the block keys the grids index + * @param ground each cell's ground block, or {@link #NO_BLOCK} where the column holds none + * @param cover the block standing on each cell's ground, such as grass, or {@link #NO_BLOCK} + */ + public record Blocks(List names, short[] ground, short[] cover) { + public static final short NO_BLOCK = -1; + } + + /** This tile with {@code blocks} on top of its columns, at {@code heights} where it carries heights. */ + MapTile withBlocks(Blocks blocks, float[] heights) { + return new MapTile(size, blocksPerPixel, subjectKind, labels, subjects, regions, heights, pickNoise, blocks); + } + /** What a tile can carry besides its labels. */ public enum Extra { HEIGHTS, diff --git a/core/src/main/java/art/arcane/iris/core/studio/map/MapTileRenderer.java b/core/src/main/java/art/arcane/iris/core/studio/map/MapTileRenderer.java index ff8465980..c088e7d73 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/map/MapTileRenderer.java +++ b/core/src/main/java/art/arcane/iris/core/studio/map/MapTileRenderer.java @@ -27,6 +27,7 @@ import art.arcane.iris.util.project.stream.ProceduralStream; import java.util.ArrayList; import java.util.Arrays; +import java.util.HashMap; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; @@ -38,9 +39,11 @@ import java.util.function.BooleanSupplier; /** Draws {@link MapTile}s of one engine's world. Safe to use from several threads; each tile is drawn on its caller's. */ public final class MapTileRenderer { private final Engine engine; + private final GeneratedChunks generated; public MapTileRenderer(Engine engine) { this.engine = Objects.requireNonNull(engine, "engine"); + this.generated = new GeneratedChunks(engine); } /** @@ -69,6 +72,49 @@ public final class MapTileRenderer { : renderView(layer, grid, blocksPerPixel, extras); } + /** + * {@code tile}, drawn from ({@code startX}, {@code startZ}), with the block on top of each of its columns from + * {@code source}. Where the tile carries heights they become the heights of that ground, which is the terrain's + * with what generation put on it. + * + * @throws IllegalArgumentException when the tile is coarser than the source is drawn at + * @throws CancellationException as soon as {@code cancelled} answers true + */ + public MapTile withBlocks(MapTile tile, double startX, double startZ, BlockSource source, BooleanSupplier cancelled) { + double step = tile.blocksPerPixel(); + if (step > source.largestBlocksPerPixel()) { + throw new IllegalArgumentException("Blocks from " + source.id() + " are drawn at " + source.largestBlocksPerPixel() + + " blocks per pixel or finer"); + } + TileGrid grid = new TileGrid(tile.gridSize(), startX - step, startZ - step, step, cancelled); + ColumnTops tops = topsOf(source); + int cells = grid.size() * grid.size(); + short[] ground = new short[cells]; + short[] cover = new short[cells]; + float[] heights = tile.heights() == null ? null : new float[cells]; + BlockNames names = new BlockNames(); + for (int gridZ = 0; gridZ < grid.size(); gridZ++) { + checkCancelled(cancelled); + int worldZ = (int) Math.floor(grid.worldZ(gridZ)); + for (int gridX = 0; gridX < grid.size(); gridX++) { + int cell = gridZ * grid.size() + gridX; + ColumnTops.ColumnTop top = tops.at((int) Math.floor(grid.worldX(gridX)), worldZ); + ground[cell] = names.indexOf(top.ground()); + cover[cell] = names.indexOf(top.cover()); + if (heights != null) { + heights[cell] = top.groundY(); + } + } + } + return tile.withBlocks(new MapTile.Blocks(names.names(), ground, cover), heights); + } + + private ColumnTops topsOf(BlockSource source) { + return switch (source) { + case GENERATED -> generated; + }; + } + private MapTile renderView(MapLayer layer, TileGrid grid, double blocksPerPixel, Set extras) { TileLabels labels = new TileLabels(engine, layer.colorType()); IrisComplex complex = engine.getComplex(); @@ -76,12 +122,12 @@ public final class MapTileRenderer { short[] regions = everyCell(grid, (x, z) -> labels.indexOf(regionStream.get(x, z))); ProceduralStream biomeStream = layer.view().biomeStream(complex); short[] subjects = layer.labelsRegions() ? regions : everyCell(grid, (x, z) -> labels.indexOf(biomeStream.get(x, z))); - float[] heights = extras.contains(MapTile.Extra.HEIGHTS) || layer.view() == MapView.HEIGHT ? latticeHeights(grid) : null; + float[] heights = extras.contains(MapTile.Extra.HEIGHTS) ? latticeHeights(grid) : null; float[] pickNoise = extras.contains(MapTile.Extra.PICK_NOISE) && layer.hasPickNoise() ? MapPickNoise.sample(engine, layer, grid) : null; MapLabel.Kind subjectKind = layer.labelsRegions() ? MapLabel.Kind.REGION : MapLabel.Kind.BIOME; - return new MapTile(grid.size() - 2, blocksPerPixel, subjectKind, labels.labels(), subjects, regions, heights, pickNoise); + return new MapTile(grid.size() - 2, blocksPerPixel, subjectKind, labels.labels(), subjects, regions, heights, pickNoise, null); } // Each spot's surface biome hangs on its height, which the lattice gives at a fraction of the exact heights' cost. @@ -101,7 +147,7 @@ public final class MapTileRenderer { ? MapPickNoise.samplePreview(engine, region, grid, picks) : null; float[] requestedHeights = extras.contains(MapTile.Extra.HEIGHTS) ? heights : null; - return new MapTile(grid.size() - 2, blocksPerPixel, MapLabel.Kind.BIOME, labels.labels(), subjects, regions, requestedHeights, pickNoise); + return new MapTile(grid.size() - 2, blocksPerPixel, MapLabel.Kind.BIOME, labels.labels(), subjects, regions, requestedHeights, pickNoise, null); } private IrisComplex.BiomePick[] previewPicks(TileGrid grid, IrisRegion region, float[] heights) { @@ -148,6 +194,25 @@ public final class MapTileRenderer { short indexAt(double worldX, double worldZ); } + /** The blocks one tile meets, each named once, in the order the tile met them. */ + private static final class BlockNames { + private final Map indices = new HashMap<>(); + private final List names = new ArrayList<>(); + + short indexOf(String block) { + return block == null ? MapTile.Blocks.NO_BLOCK : indices.computeIfAbsent(block, this::add); + } + + private short add(String block) { + names.add(block); + return (short) (names.size() - 1); + } + + List names() { + return List.copyOf(names); + } + } + /** The biomes and regions one tile meets, each labelled once, in the order the tile met them. */ private static final class TileLabels { private final Engine engine; diff --git a/core/src/main/java/art/arcane/iris/core/studio/map/MapView.java b/core/src/main/java/art/arcane/iris/core/studio/map/MapView.java index 9b4c3b2b9..8da0d49bb 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/map/MapView.java +++ b/core/src/main/java/art/arcane/iris/core/studio/map/MapView.java @@ -30,7 +30,6 @@ import java.util.Optional; public enum MapView { BIOMES("biomes", "Biomes", "The biome at each spot, in the biome's colour", Group.WORLD, RenderType.BIOME), REGIONS("regions", "Regions", "The region each spot belongs to", Group.WORLD, RenderType.REGION), - HEIGHT("height", "Height", "Terrain height, from deep water to snowy peaks", Group.WORLD, RenderType.HEIGHT), LAND_BIOMES("landBiomes", "Land biomes", "The land biome each spot would get, also where the sea is", Group.BIOME_LAYERS, RenderType.BIOME_LAND), SEA_BIOMES("seaBiomes", "Sea biomes", "The sea biome each spot would get, also where the land is", @@ -76,9 +75,9 @@ public enum MapView { return this == REGIONS; } - /** The colouring biomes and regions get in this view; the height view colours its biomes as the biome view does. */ + /** The colouring biomes and regions get in this view. */ RenderType colorType() { - return this == HEIGHT ? RenderType.BIOME : colorType; + return colorType; } /** The biome each spot is labelled with: the base biome, before the height corrects it near coasts. */ @@ -87,7 +86,7 @@ public enum MapView { case LAND_BIOMES -> complex.getLandBiomeStream(); case SEA_BIOMES -> complex.getSeaBiomeStream(); case CAVE_BIOMES -> complex.getCaveBiomeStream(); - case BIOMES, REGIONS, HEIGHT -> complex.getBaseBiomeStream(); + case BIOMES, REGIONS -> complex.getBaseBiomeStream(); }; } diff --git a/core/src/test/java/art/arcane/iris/core/studio/bridge/StudioBridgeTest.java b/core/src/test/java/art/arcane/iris/core/studio/bridge/StudioBridgeTest.java index 4ecc6a680..1069559fb 100644 --- a/core/src/test/java/art/arcane/iris/core/studio/bridge/StudioBridgeTest.java +++ b/core/src/test/java/art/arcane/iris/core/studio/bridge/StudioBridgeTest.java @@ -184,8 +184,8 @@ public class StudioBridgeTest { } @Test - public void theHeightViewHasNoPicksToInspect() throws Exception { - assertEquals(400, get("picks?view=height&minX=0&minZ=0&maxX=10&maxZ=10").statusCode()); + public void aBiomeLayerViewHasNoPicksToInspect() throws Exception { + assertEquals(400, get("picks?view=landBiomes&minX=0&minZ=0&maxX=10&maxZ=10").statusCode()); } @Test diff --git a/core/src/test/java/art/arcane/iris/core/studio/map/MapPickInspectionTest.java b/core/src/test/java/art/arcane/iris/core/studio/map/MapPickInspectionTest.java index f10ee8034..15f8fea36 100644 --- a/core/src/test/java/art/arcane/iris/core/studio/map/MapPickInspectionTest.java +++ b/core/src/test/java/art/arcane/iris/core/studio/map/MapPickInspectionTest.java @@ -68,8 +68,8 @@ public class MapPickInspectionTest { } @Test - public void theHeightViewHasNoPicks() { - assertThrows(IllegalArgumentException.class, () -> measure(MapLayer.of(MapView.HEIGHT))); + public void aBiomeLayerViewHasNoPicks() { + assertThrows(IllegalArgumentException.class, () -> measure(MapLayer.of(MapView.LAND_BIOMES))); } @Test diff --git a/core/src/test/java/art/arcane/iris/core/studio/map/MapTileRendererTest.java b/core/src/test/java/art/arcane/iris/core/studio/map/MapTileRendererTest.java index b4f25e306..059a5eee0 100644 --- a/core/src/test/java/art/arcane/iris/core/studio/map/MapTileRendererTest.java +++ b/core/src/test/java/art/arcane/iris/core/studio/map/MapTileRendererTest.java @@ -96,10 +96,10 @@ public class MapTileRendererTest { } @Test - public void theHeightViewAlwaysHasHeightsAndAFlatWorldStaysFlat() { + public void aFlatWorldStaysFlat() { heights((x, z) -> 70D); - MapTile tile = render(MapView.HEIGHT, 0D, 0D, 1D, false); + MapTile tile = render(MapView.BIOMES, 0D, 0D, 1D, true); for (float height : tile.heights()) { assertEquals(70F, height, 1e-4F); diff --git a/studio/src/renderer/src/bridge/BridgeClient.ts b/studio/src/renderer/src/bridge/BridgeClient.ts index d8b6430c5..5a1b4aa98 100644 --- a/studio/src/renderer/src/bridge/BridgeClient.ts +++ b/studio/src/renderer/src/bridge/BridgeClient.ts @@ -5,6 +5,7 @@ import { decodeSavedTile } from './savedTileDecoding' import { decodeTile } from './tileDecoding' import type { BakeRun, + BlockSource, EditorState, GraphEdit, MapHover, @@ -49,6 +50,8 @@ export interface TileRequest { size: number heights: boolean pickNoise: boolean + /** Where the tile's blocks come from, or null for a tile without them. */ + blocks: BlockSource | null } /** One tile of a pattern: tile (x, z) covers columns × blocksPerColumn blocks from x × that, z × that. */ @@ -136,6 +139,9 @@ export class BridgeClient { heights: request.heights ? '1' : '0', noise: request.pickNoise ? '1' : '0' }) + if (request.blocks !== null) { + query.set('blocks', request.blocks) + } const response = await this.fetch(`tile?${query}`, { signal }) return decodeTile(await response.arrayBuffer()) } diff --git a/studio/src/renderer/src/bridge/tileDecoding.ts b/studio/src/renderer/src/bridge/tileDecoding.ts index ac5f23e90..b306c42c6 100644 --- a/studio/src/renderer/src/bridge/tileDecoding.ts +++ b/studio/src/renderer/src/bridge/tileDecoding.ts @@ -9,6 +9,8 @@ interface TileHeader { labels: MapLabel[] heights: boolean pickNoise: boolean + /** The blocks the ground and cover grids index; absent or null on a tile without them. */ + blocks?: string[] | null } function aligned(bytes: number): number { @@ -17,7 +19,7 @@ function aligned(bytes: number): number { /** * Reads a tile as the bridge writes it (MapTileEncoding): a u32 header length, the JSON header, then the subject, - * region, height and pick noise grids, each starting on a multiple of 4 bytes. The grids are views into the buffer, + * region, height, pick noise, ground and cover grids, each starting on a multiple of 4 bytes. The grids are views into the buffer, * not copies. */ export function decodeTile(buffer: ArrayBuffer): MapTile { @@ -30,6 +32,8 @@ export function decodeTile(buffer: ArrayBuffer): MapTile { const regionsAt = aligned(subjectsAt + cells * Int16Array.BYTES_PER_ELEMENT) const heightsAt = aligned(regionsAt + cells * Int16Array.BYTES_PER_ELEMENT) const pickNoiseAt = heightsAt + (header.heights ? cells * Float32Array.BYTES_PER_ELEMENT : 0) + const groundAt = pickNoiseAt + (header.pickNoise ? cells * Float32Array.BYTES_PER_ELEMENT : 0) + const coverAt = aligned(groundAt + cells * Int16Array.BYTES_PER_ELEMENT) return { size: header.size, blocksPerPixel: header.blocksPerPixel, @@ -38,7 +42,11 @@ export function decodeTile(buffer: ArrayBuffer): MapTile { subjects: new Int16Array(buffer, subjectsAt, cells), regions: new Int16Array(buffer, regionsAt, cells), heights: header.heights ? new Float32Array(buffer, heightsAt, cells) : null, - pickNoise: header.pickNoise ? new Float32Array(buffer, pickNoiseAt, cells) : null + pickNoise: header.pickNoise ? new Float32Array(buffer, pickNoiseAt, cells) : null, + blocks: + header.blocks == null + ? null + : { names: header.blocks, ground: new Int16Array(buffer, groundAt, cells), cover: new Int16Array(buffer, coverAt, cells), colors: [], looks: [] } } } diff --git a/studio/src/renderer/src/bridge/types.ts b/studio/src/renderer/src/bridge/types.ts index 827d2df60..68de30d29 100644 --- a/studio/src/renderer/src/bridge/types.ts +++ b/studio/src/renderer/src/bridge/types.ts @@ -1,5 +1,7 @@ /** The shapes the Iris bridge answers with (Iris core, art.arcane.iris.core.studio). */ +import type { BlockLook } from '../scene/blockLooks' + export type LabelKind = 'BIOME' | 'REGION' export interface MapLabel { @@ -329,6 +331,26 @@ export interface MapTile { heights: Float32Array | null /** The noise value that settled each cell's pick, 0 to 1 and NaN where nothing picked it; null unless asked for. */ pickNoise: Float32Array | null + /** The block on top of each cell's column; null unless asked for. */ + blocks: TileBlocks | null } +/** Where a tile's blocks come from: the chunks the server generates in memory. */ +export type BlockSource = 'generated' + +/** The top of each cell's column: its ground block, and the block standing on it, such as grass. */ +export interface TileBlocks { + /** The block states the grids index, as BlockState keys. */ + names: string[] + /** {@link NO_BLOCK} where the column holds no ground. */ + ground: Int16Array + /** {@link NO_BLOCK} where nothing stands on the ground. */ + cover: Int16Array + /** The colour of each named block from above, as 0xRRGGBB; the tile source fills it in. */ + colors: number[] + /** What each named block looks like on a column, where the tile is fine enough to show textures; else empty. */ + looks: (BlockLook | null)[] +} + +export const NO_BLOCK = -1 export const NO_LABEL = -1 diff --git a/studio/src/renderer/src/components/IdeIcon.tsx b/studio/src/renderer/src/components/IdeIcon.tsx index fc48847fe..f1e4b0b3c 100644 --- a/studio/src/renderer/src/components/IdeIcon.tsx +++ b/studio/src/renderer/src/components/IdeIcon.tsx @@ -6,6 +6,7 @@ const DARK_SUFFIX = '_dark' export type IdeIconName = | 'add' + | 'blocks' | 'checked' | 'closeSmall' | 'chevronLeft' @@ -24,6 +25,7 @@ export type IdeIconName = | 'reset' | 'search' | 'settings' + | 'shading' | 'stopWatch' | 'symlink' | 'theme' @@ -33,7 +35,6 @@ export type IdeIconName = | 'zoomIn' | 'views/biomes' | 'views/cave-biomes' - | 'views/height' | 'views/land-biomes' | 'views/noise' | 'views/objects' diff --git a/studio/src/renderer/src/icons/NOTICE.txt b/studio/src/renderer/src/icons/NOTICE.txt index ca8a733fd..67f83c414 100644 --- a/studio/src/renderer/src/icons/NOTICE.txt +++ b/studio/src/renderer/src/icons/NOTICE.txt @@ -2,4 +2,4 @@ The icons in this folder and its subfolders come from the IntelliJ Platform (htt platform/icons/src/expui, Copyright 2000-2023 JetBrains s.r.o. and contributors, used under the Apache License 2.0 (LICENSE-APACHE-2.0.txt). memory.svg is profileMemory.svg with its profiling badge removed. -theme.svg is the studio's own, drawn to match. +theme.svg and blocks.svg are the studio's own, drawn to match. diff --git a/studio/src/renderer/src/icons/blocks.svg b/studio/src/renderer/src/icons/blocks.svg new file mode 100644 index 000000000..aa609f646 --- /dev/null +++ b/studio/src/renderer/src/icons/blocks.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/blocks_dark.svg b/studio/src/renderer/src/icons/blocks_dark.svg new file mode 100644 index 000000000..d215432f4 --- /dev/null +++ b/studio/src/renderer/src/icons/blocks_dark.svg @@ -0,0 +1,4 @@ + + + + diff --git a/studio/src/renderer/src/icons/views/height.svg b/studio/src/renderer/src/icons/shading.svg similarity index 100% rename from studio/src/renderer/src/icons/views/height.svg rename to studio/src/renderer/src/icons/shading.svg diff --git a/studio/src/renderer/src/icons/views/height_dark.svg b/studio/src/renderer/src/icons/shading_dark.svg similarity index 100% rename from studio/src/renderer/src/icons/views/height_dark.svg rename to studio/src/renderer/src/icons/shading_dark.svg diff --git a/studio/src/renderer/src/map/MapController.ts b/studio/src/renderer/src/map/MapController.ts index 5c5179742..d04724349 100644 --- a/studio/src/renderer/src/map/MapController.ts +++ b/studio/src/renderer/src/map/MapController.ts @@ -1,9 +1,9 @@ import type { BridgeClient, WorldRect } from '../bridge/BridgeClient' import { gridIndex } from '../bridge/tileDecoding' -import { NO_LABEL, type MapLabel, type MapTile, type Marker, type PickDisplay, type WorldInfo } from '../bridge/types' +import { NO_LABEL, type BlockSource, type MapLabel, type MapTile, type Marker, type PickDisplay, type WorldInfo } from '../bridge/types' import { countShares, type PlacedTile, type Share } from './census' -import { bandIndexOf, HEIGHT_BANDS } from './heightColors' -import { mapTileSource, type TileLayer } from './mapTileSource' +import { blockArt, type BlockArt } from '../scene/blockArt' +import { hasBlocksAt, mapTileSource, type TileLayer } from './mapTileSource' import { drawPlayerArrow } from './playerArrow' import { drawVisibleTiles } from './tileDrawing' import type { Highlight, TileStyle } from './tileStyle' @@ -51,8 +51,12 @@ export interface MapToggles { shading: boolean regionBorders: boolean grid: boolean + /** Colour the map by the block on top of each column, where it is zoomed in far enough. */ + blocks: boolean } +const BLOCK_SOURCE: BlockSource = 'generated' + const CENSUS_INTERVAL_MILLIS = 250 const CHUNK_BLOCKS = 16 const REGION_BLOCKS = 512 @@ -69,10 +73,11 @@ const ENTITY_RADIUS_PIXELS = 3 */ export class MapController { private readonly context: CanvasRenderingContext2D + private readonly art: BlockArt private readonly store: TileStore private readonly view: Viewport = { centerX: 0, centerZ: 0, blocksPerPixel: DEFAULT_BLOCKS_PER_PIXEL, width: 1, height: 1 } private layer: TileLayer - private toggles: MapToggles = { shading: true, regionBorders: false, grid: false } + private toggles: MapToggles = { shading: true, regionBorders: false, grid: false, blocks: false } private pickDisplay: PickDisplay = 'picks' private highlight: Highlight | null = null private players: Marker[] = [] @@ -91,12 +96,14 @@ export class MapController { private readonly listener: MapListener ) { this.context = canvas.getContext('2d')! - this.layer = { view, preview: null, heights: this.needsHeights(view, this.toggles), pickNoise: false, revision: 0 } - this.store = new TileStore(mapTileSource(client, world.tileSize), () => this.redraw(), (message) => listener.onError(message)) + this.layer = { view, preview: null, heights: this.needsHeights(this.toggles), pickNoise: false, blocks: null, revision: 0 } + this.art = blockArt(client, false) + this.store = new TileStore(mapTileSource(client, world.tileSize, this.art), () => this.redraw(), (message) => listener.onError(message)) } close(): void { this.closed = true + this.art.dispose() window.clearTimeout(this.censusTimer) this.store.clear() } @@ -116,7 +123,6 @@ export class MapController { ...this.layer, view, preview: view === 'regions' ? preview : null, - heights: this.needsHeights(view, this.toggles), pickNoise: this.needsPickNoise(view, this.pickDisplay) } this.redraw() @@ -135,13 +141,19 @@ export class MapController { setToggles(toggles: MapToggles): void { this.toggles = toggles - this.layer = { ...this.layer, heights: this.needsHeights(this.layer.view, toggles) } + this.layer = { ...this.layer, heights: this.needsHeights(toggles), blocks: toggles.blocks ? BLOCK_SOURCE : null } this.redraw() } - // Heights are the costly part of a tile, so they are only asked for when something draws with them. - private needsHeights(view: string, toggles: MapToggles): boolean { - return toggles.shading || view === 'height' + /** Whether the map is zoomed in far enough for its tiles to carry blocks. */ + showsBlocks(): boolean { + return hasBlocksAt(BLOCK_SOURCE, this.renderScale()) + } + + // Heights are the costly part of a tile, so they are only asked for when something draws with them: the relief, and + // the sea over the blocks. + private needsHeights(toggles: MapToggles): boolean { + return toggles.shading || toggles.blocks } setHighlight(highlight: Highlight | null): void { @@ -213,24 +225,16 @@ export class MapController { const pixelZ = Math.min(tile.size - 1, Math.floor((worldZ - address.tileZ * span) / scale)) const cell = gridIndex(tile, pixelX, pixelZ) const region = labelAt(tile.labels, tile.regions[cell]) - if (this.isHeightView() && tile.heights !== null) { - const band = HEIGHT_BANDS[bandIndexOf(tile.heights[cell], this.world.fluidHeight)] - return { subject: { kind: 'HEIGHT', key: band.key, name: band.name }, region } - } return { subject: labelAt(tile.labels, tile.subjects[cell]), region } } - private isHeightView(): boolean { - return this.layer.view === 'height' - } - private renderScale(): number { return renderBlocksPerPixel(this.view.blocksPerPixel, window.devicePixelRatio) } private style(): TileStyle { return { - byHeight: this.isHeightView(), + byBlock: this.toggles.blocks, shading: this.toggles.shading, regionBorders: this.toggles.regionBorders, highlight: this.highlight, @@ -369,7 +373,7 @@ export class MapController { } const screen = this.screenArea() const area = { minimumX: screen.minX, minimumZ: screen.minZ, maximumX: screen.maxX, maximumZ: screen.maxZ } - return countShares(placed, area, this.isHeightView(), this.world.fluidHeight) + return countShares(placed, area) } } diff --git a/studio/src/renderer/src/map/census.ts b/studio/src/renderer/src/map/census.ts index 04851c1d5..7a00c1a7b 100644 --- a/studio/src/renderer/src/map/census.ts +++ b/studio/src/renderer/src/map/census.ts @@ -28,10 +28,9 @@ export interface WorldArea { const MAXIMUM_COUNTED_PIXELS = 250_000 /** - * The shares of what the tiles show inside {@code area}, largest first: their subjects (biomes or regions), or their - * height bands when {@code byHeight} is set. + * The shares of what the tiles show inside {@code area}, largest first: their subjects, which are biomes or regions. */ -export function countShares(tiles: PlacedTile[], area: WorldArea, byHeight: boolean, seaLevel: number): Share[] { +export function countShares(tiles: PlacedTile[], area: WorldArea): Share[] { const counts = new Map() const totalPixels = tiles.reduce((sum, placed) => sum + placed.tile.size * placed.tile.size, 0) const stride = Math.max(1, Math.ceil(Math.sqrt(totalPixels / MAXIMUM_COUNTED_PIXELS))) @@ -44,7 +43,7 @@ export function countShares(tiles: PlacedTile[], area: WorldArea, byHeight: bool const endZ = Math.min(tile.size, Math.ceil((area.maximumZ - worldZ) / scale)) for (let pixelZ = firstZ; pixelZ < endZ; pixelZ += stride) { for (let pixelX = firstX; pixelX < endX; pixelX += stride) { - const subject = subjectAt(tile, gridIndex(tile, pixelX, pixelZ), byHeight, seaLevel) + const subject = subjectAt(tile, gridIndex(tile, pixelX, pixelZ)) if (subject === null) { continue } @@ -76,14 +75,7 @@ export function heightBandShares(heights: readonly number[], seaLevel: number): }) } -function subjectAt(tile: MapTile, cell: number, byHeight: boolean, seaLevel: number): { subject: Highlight; color: number } | null { - if (byHeight) { - if (tile.heights === null) { - return null - } - const band = HEIGHT_BANDS[bandIndexOf(tile.heights[cell], seaLevel)] - return { subject: { kind: 'HEIGHT', key: band.key, name: band.name }, color: band.color } - } +function subjectAt(tile: MapTile, cell: number): { subject: Highlight; color: number } | null { const index = tile.subjects[cell] if (index === NO_LABEL) { return null diff --git a/studio/src/renderer/src/map/map.test.ts b/studio/src/renderer/src/map/map.test.ts index 82b2a519b..f68185225 100644 --- a/studio/src/renderer/src/map/map.test.ts +++ b/studio/src/renderer/src/map/map.test.ts @@ -10,7 +10,7 @@ import { coarserTile, previewsFor, renderBlocksPerPixel, screenToWorldX, visible const PLAINS: MapLabel = { kind: 'BIOME', key: 'plains', name: 'Plains', color: 0x00ff00 } const DESERT: MapLabel = { kind: 'BIOME', key: 'desert', name: 'Desert', color: 0xffff00 } const WARM: MapLabel = { kind: 'REGION', key: 'warm', name: 'Warm', color: 0xff0000 } -const FLAT: TileStyle = { byHeight: false, shading: false, regionBorders: false, highlight: null, seaLevel: 63, pickDisplay: 'picks' } +const FLAT: TileStyle = { byBlock: false, shading: false, regionBorders: false, highlight: null, seaLevel: 63, pickDisplay: 'picks' } /** A tile whose left half is plains and right half desert, all in one region, at height 70. */ function splitTile(size = 4): MapTile { @@ -27,7 +27,8 @@ function splitTile(size = 4): MapTile { subjects, regions: new Int16Array(cells).fill(2), heights: new Float32Array(cells).fill(70), - pickNoise: null + pickNoise: null, + blocks: null } } @@ -132,6 +133,22 @@ describe('tile style', () => { expect(pixel(pixels, 4, 3, 3)).toBe(DESERT.color) }) + it('paints each pixel in the colour of what stands on its ground, or of the ground itself', () => { + const tile = splitTile() + const cells = tile.subjects.length + const cover = new Int16Array(cells).fill(-1) + cover[gridIndex(tile, 3, 3)] = 1 + const blocks = { names: ['stone', 'poppy'], ground: new Int16Array(cells).fill(0), cover, colors: [0x808080, 0xff0000], looks: [] } + const pixels = stylePixels({ ...tile, blocks }, { ...FLAT, byBlock: true }) + + expect(pixel(pixels, 4, 0, 0)).toBe(0x808080) + expect(pixel(pixels, 4, 3, 3)).toBe(0xff0000) + }) + + it('keeps the label colours of a tile without blocks', () => { + expect(pixel(stylePixels(splitTile(), { ...FLAT, byBlock: true }), 4, 0, 0)).toBe(PLAINS.color) + }) + it('dims everything but the highlight, and tints the highlight edge', () => { const pixels = stylePixels(splitTile(), { ...FLAT, highlight: { kind: 'BIOME', key: 'plains', name: 'Plains' } }) @@ -194,7 +211,7 @@ describe('viewport', () => { describe('census', () => { it('shares the visible pixels between the labels', () => { const tile = splitTile(4) - const shares = countShares([{ tile, worldX: 0, worldZ: 0 }], { minimumX: 0, minimumZ: 0, maximumX: 4, maximumZ: 4 }, false, 63) + const shares = countShares([{ tile, worldX: 0, worldZ: 0 }], { minimumX: 0, minimumZ: 0, maximumX: 4, maximumZ: 4 }) expect(shares.map((share) => share.subject.key).sort()).toEqual(['desert', 'plains']) expect(shares[0].fraction).toBeCloseTo(0.5) @@ -202,19 +219,12 @@ describe('census', () => { }) it('counts only the part of a tile inside the area, largest share first', () => { - const shares = countShares([{ tile: splitTile(4), worldX: 0, worldZ: 0 }], { minimumX: 0, minimumZ: 0, maximumX: 3, maximumZ: 4 }, false, 63) + const shares = countShares([{ tile: splitTile(4), worldX: 0, worldZ: 0 }], { minimumX: 0, minimumZ: 0, maximumX: 3, maximumZ: 4 }) expect(shares.map((share) => share.subject.key)).toEqual(['plains', 'desert']) expect(shares[0].fraction).toBeCloseTo(2 / 3) }) - it('counts height bands in the height view', () => { - const shares = countShares([{ tile: splitTile(4), worldX: 0, worldZ: 0 }], { minimumX: 0, minimumZ: 0, maximumX: 4, maximumZ: 4 }, true, 63) - - expect(shares).toHaveLength(1) - expect(shares[0].subject).toMatchObject({ kind: 'HEIGHT', name: '0–8 above sea' }) - }) - it('shares spot heights between their bands, highest band first', () => { const shares = heightBandShares([64, 64, 64, 500, 30], 63) diff --git a/studio/src/renderer/src/map/mapTileSource.ts b/studio/src/renderer/src/map/mapTileSource.ts index fc8c0bf7a..bca240a04 100644 --- a/studio/src/renderer/src/map/mapTileSource.ts +++ b/studio/src/renderer/src/map/mapTileSource.ts @@ -1,5 +1,6 @@ import type { BridgeClient } from '../bridge/BridgeClient' -import type { MapTile } from '../bridge/types' +import type { BlockSource, MapTile } from '../bridge/types' +import type { BlockArt } from '../scene/blockArt' import { stylePixels, styleKey, type TileStyle } from './tileStyle' import type { TileSource } from './TileStore' @@ -10,16 +11,35 @@ export interface TileLayer { preview: string | null heights: boolean pickNoise: boolean + /** Where the tiles' blocks come from, or null for tiles without them. */ + blocks: BlockSource | null /** Bumped when the pack is hotloaded, so older tiles are not used again. */ revision: number } -/** The world map's tiles: the engine's streams, drawn in the map's styles. */ -export function mapTileSource(client: BridgeClient, tileSize: number): TileSource { +/** The coarsest tiles a block source is asked for; coarser ones come without blocks. */ +const MOST_BLOCKS_PER_PIXEL: Record = { generated: 1 } +const TEXTURED_BLOCKS_PER_PIXEL = 1 + +/** Whether tiles this coarse carry blocks from {@code source}. */ +export function hasBlocksAt(source: BlockSource, blocksPerPixel: number): boolean { + return blocksPerPixel <= MOST_BLOCKS_PER_PIXEL[source] +} + +/** The world map's tiles: the engine's streams, drawn in the map's styles, their blocks painted with {@code art}. */ +export function mapTileSource(client: BridgeClient, tileSize: number, art: BlockArt): TileSource { return { - layerKey: (layer) => [layer.revision, layer.view, layer.preview ?? '', layer.heights, layer.pickNoise].join('/'), - fetch: (address, layer, signal) => client.tile({ ...layer, ...address, size: tileSize }, signal), - bytesOf: (tile) => tile.subjects.byteLength * 2 + (tile.heights?.byteLength ?? 0) + (tile.pickNoise?.byteLength ?? 0) + tile.size * tile.size * 4, + layerKey: (layer) => [layer.revision, layer.view, layer.preview ?? '', layer.heights, layer.pickNoise, layer.blocks ?? ''].join('/'), + fetch: async (address, layer, signal) => { + const blocks = layer.blocks !== null && hasBlocksAt(layer.blocks, address.blocksPerPixel) ? layer.blocks : null + const tile = await client.tile({ ...layer, ...address, size: tileSize, blocks }, signal) + if (tile.blocks !== null) { + await art.paint(tile.blocks, address.blocksPerPixel === TEXTURED_BLOCKS_PER_PIXEL) + } + return tile + }, + bytesOf: (tile) => + tile.subjects.byteLength * 2 + (tile.heights?.byteLength ?? 0) + (tile.pickNoise?.byteLength ?? 0) + (tile.blocks?.ground.byteLength ?? 0) * 2 + tile.size * tile.size * 4, styleKey, pixels: (tile, style) => new ImageData(stylePixels(tile, style), tile.size, tile.size) } diff --git a/studio/src/renderer/src/map/tileStyle.ts b/studio/src/renderer/src/map/tileStyle.ts index 5354d9904..0d96318df 100644 --- a/studio/src/renderer/src/map/tileStyle.ts +++ b/studio/src/renderer/src/map/tileStyle.ts @@ -1,8 +1,11 @@ import { gridIndex } from '../bridge/tileDecoding' -import { NO_LABEL, type MapTile, type PickDisplay } from '../bridge/types' -import { bandIndexOf, blend, heightColor } from './heightColors' +import { NO_BLOCK, NO_LABEL, type MapTile, type PickDisplay, type TileBlocks } from '../bridge/types' +import { WATER_SURFACE_COLOR } from '../scene/waterTint' +import { blend } from './heightColors' -/** What a highlight picks out: a biome or region by key, or a height band in the height view. */ +const WATER_OVER_GROUND = 0.65 + +/** What a highlight picks out: a biome or region by key, or a height band in the 3D world's legend. */ export interface Highlight { kind: 'BIOME' | 'REGION' | 'HEIGHT' key: string @@ -10,8 +13,8 @@ export interface Highlight { } export interface TileStyle { - /** Colour by height instead of by label. */ - byHeight: boolean + /** Colour by the block on top of each column instead of by label, where the tile carries its blocks. */ + byBlock: boolean shading: boolean regionBorders: boolean highlight: Highlight | null @@ -22,7 +25,7 @@ export interface TileStyle { export function styleKey(style: TileStyle): string { const highlight = style.highlight === null ? '' : `${style.highlight.kind}:${style.highlight.key}` - return `${style.byHeight}|${style.shading}|${style.regionBorders}|${highlight}|${style.seaLevel}|${style.pickDisplay}` + return `${style.byBlock}|${style.shading}|${style.regionBorders}|${highlight}|${style.seaLevel}|${style.pickDisplay}` } const UNKNOWN_SUBJECT = 0x5a5c62 @@ -55,15 +58,15 @@ export function stylePixels(tile: MapTile, style: TileStyle): Uint8ClampedArray< const { size, heights } = tile const pixels = new Uint8ClampedArray(size * size * 4) const colors = tile.labels.map((label) => label.color) - const byHeight = style.byHeight && heights !== null - const pickNoise = style.pickDisplay === 'picks' ? null : tile.pickNoise + const blocks = style.byBlock ? tile.blocks : null + const pickNoise = style.pickDisplay === 'picks' || blocks !== null ? null : tile.pickNoise // The bare noise is read by its brightness, which relief shading would mix up. - const shading = (style.shading || byHeight) && heights !== null && !(pickNoise !== null && style.pickDisplay === 'noise') + const shading = style.shading && heights !== null && !(pickNoise !== null && style.pickDisplay === 'noise') const highlighted = highlightCells(tile, style) for (let pixelZ = 0; pixelZ < size; pixelZ++) { for (let pixelX = 0; pixelX < size; pixelX++) { const cell = gridIndex(tile, pixelX, pixelZ) - let color = byHeight ? heightColor(heights[cell], style.seaLevel) : labelColor(colors, tile.subjects[cell]) + let color = blocks === null ? labelColor(colors, tile.subjects[cell]) : blockColor(blocks, cell, heights, style.seaLevel) if (pickNoise !== null) { color = byNoise(color, pickNoise[cell], style.pickDisplay) } @@ -90,6 +93,13 @@ function labelColor(colors: number[], index: number): number { return index === NO_LABEL ? UNKNOWN_SUBJECT : colors[index] } +// What stands on the ground is what is seen from above; ground under the sea shows through its water. +function blockColor(blocks: TileBlocks, cell: number, heights: Float32Array | null, seaLevel: number): number { + const top = blocks.cover[cell] === NO_BLOCK ? blocks.ground[cell] : blocks.cover[cell] + const color = top === NO_BLOCK ? UNKNOWN_SUBJECT : blocks.colors[top] + return heights !== null && heights[cell] < seaLevel ? blend(color, WATER_SURFACE_COLOR, WATER_OVER_GROUND) : color +} + // Where nothing picked the spot, as on an image map, it keeps its colour. function byNoise(color: number, noise: number, display: PickDisplay): number { if (Number.isNaN(noise)) { @@ -122,15 +132,6 @@ function highlightCells(tile: MapTile, style: TileStyle): Uint8Array | null { return null } const cells = new Uint8Array(tile.subjects.length) - if (target.kind === 'HEIGHT') { - if (tile.heights !== null) { - const band = Number(target.key) - tile.heights.forEach((height, cell) => { - cells[cell] = bandIndexOf(height, style.seaLevel) === band ? 1 : 0 - }) - } - return cells - } // Every view knows its regions, so a region can be highlighted in a biome view too. const grid = target.kind === tile.subjectKind ? tile.subjects : target.kind === 'REGION' ? tile.regions : null const index = tile.labels.findIndex((label) => label.kind === target.kind && label.key === target.key) diff --git a/studio/src/renderer/src/scene/blockArt.ts b/studio/src/renderer/src/scene/blockArt.ts new file mode 100644 index 000000000..009bd8b66 --- /dev/null +++ b/studio/src/renderer/src/scene/blockArt.ts @@ -0,0 +1,34 @@ +import type { BridgeClient } from '../bridge/BridgeClient' +import type { TileBlocks } from '../bridge/types' +import { BlockColors } from './blockColors' +import { BlockLooks } from './blockLooks' +import { BlockModels } from './blockModels' +import { BridgeAssets } from './BridgeAssets' +import { TerrainAtlas } from './terrainAtlas' + +/** What a tile's blocks are drawn with: each block's colour from above, and its textures where columns show them. */ +export interface BlockArt { + /** The atlas the looks' pictures lie in; null for art that only colours. */ + readonly atlas: TerrainAtlas | null + /** Fills in the colours of the tile's blocks, and their looks when {@code textured}. */ + paint(blocks: TileBlocks, textured: boolean): Promise + dispose(): void +} + +/** Block art read from the Minecraft client's assets through the bridge; {@code textured} art can also show textures. */ +export function blockArt(client: BridgeClient, textured: boolean): BlockArt { + const images = new BridgeAssets(client, () => {}) + const models = new BlockModels(images) + const colors = new BlockColors(models, images) + const atlas = textured ? new TerrainAtlas(images) : null + const looks = atlas === null ? null : new BlockLooks(models, atlas) + return { + atlas, + paint: async (blocks, withLooks) => { + const [colorOf, lookOf] = await Promise.all([colors.colorsOf(blocks.names), withLooks && looks !== null ? looks.looksOf(blocks.names) : null]) + blocks.colors = blocks.names.map((name) => colorOf.get(name)!) + blocks.looks = lookOf === null ? [] : blocks.names.map((name) => lookOf.get(name) ?? null) + }, + dispose: () => atlas?.dispose() + } +} diff --git a/studio/src/renderer/src/scene/mapTerrain.ts b/studio/src/renderer/src/scene/mapTerrain.ts index 49139d397..68bad36a7 100644 --- a/studio/src/renderer/src/scene/mapTerrain.ts +++ b/studio/src/renderer/src/scene/mapTerrain.ts @@ -1,13 +1,19 @@ -import { NO_LABEL, type MapTile } from '../bridge/types' +import { NO_BLOCK, NO_LABEL, type MapTile } from '../bridge/types' import { heightColor } from '../map/heightColors' +import type { BlockLook } from './blockLooks' +import type { TerrainPictures } from './terrainAtlas' import type { TerrainSurface } from './terrainMesh' import { blocksPerColumn, originXOf, originZOf, type TerrainTile } from './terrainTiles' -export type MapTerrainColoring = 'biomes' | 'regions' | 'height' +export type MapTerrainColoring = 'biomes' | 'regions' | 'height' | 'blocks' const UNLABELLED_COLOR = 0x5a5f6b -/** One map tile with heights as a surface, a column to a pixel, without the ring the tile carries for its neighbours; the sea fills up to fluid height. */ +/** + * One map tile with heights as a surface, a column to a pixel, without the ring the tile carries for its neighbours; the + * sea fills up to fluid height. Coloured by blocks, a tile that carries them shows their colours, and their textures + * where it has their looks; one too coarse to carry them keeps its biomes' colours. + */ export class MapTerrain implements TerrainSurface { readonly columns: number readonly rows: number @@ -19,7 +25,8 @@ export class MapTerrain implements TerrainSurface { private readonly tile: MapTile, place: TerrainTile, private readonly coloring: MapTerrainColoring, - private readonly fluidHeight: number + private readonly fluidHeight: number, + readonly pictures?: TerrainPictures ) { this.columns = tile.size this.rows = tile.size @@ -36,14 +43,27 @@ export class MapTerrain implements TerrainSurface { return this.heightAt(column, row) < this.fluidHeight ? Math.floor(this.fluidHeight) : null } + lookAt(column: number, row: number): BlockLook | null { + const ground = this.groundBlockAt(column, row) + return ground === NO_BLOCK ? null : (this.tile.blocks!.looks[ground] ?? null) + } + colorAt(column: number, row: number): number { if (this.coloring === 'height') { return heightColor(this.heightAt(column, row), this.fluidHeight) } + const ground = this.groundBlockAt(column, row) + if (ground !== NO_BLOCK) { + return this.tile.blocks!.colors[ground] + } const index = this.coloring === 'regions' ? this.tile.regions[this.cellAt(column, row)] : this.tile.subjects[this.cellAt(column, row)] return index === NO_LABEL ? UNLABELLED_COLOR : this.tile.labels[index].color } + private groundBlockAt(column: number, row: number): number { + return this.coloring === 'blocks' && this.tile.blocks !== null ? this.tile.blocks.ground[this.cellAt(column, row)] : NO_BLOCK + } + private heightAt(column: number, row: number): number { return this.tile.heights![this.cellAt(column, row)] } diff --git a/studio/src/renderer/src/studio/MapStudio.tsx b/studio/src/renderer/src/studio/MapStudio.tsx index 743ddd3bf..ec7682bfd 100644 --- a/studio/src/renderer/src/studio/MapStudio.tsx +++ b/studio/src/renderer/src/studio/MapStudio.tsx @@ -47,7 +47,7 @@ export interface StudioToggles extends MapToggles { export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps): React.JSX.Element { const controller = useRef(null) const [viewId, setViewId] = useState(world.views[0]?.id ?? 'biomes') - const [toggles, setToggles] = useState({ shading: true, regionBorders: false, grid: false, follow: false, entities: false }) + const [toggles, setToggles] = useState({ shading: true, regionBorders: false, grid: false, blocks: false, follow: false, entities: false }) const [highlight, setHighlight] = useState(null) const [status, setStatus] = useState(null) const [shares, setShares] = useState([]) @@ -171,6 +171,9 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps case 'shading': toggle('shading') return + case 'blocks': + toggle('blocks') + return case 'borders': toggle('regionBorders') return @@ -314,7 +317,7 @@ const SCENE_GROUP = { group: 'BLOCKS', groupLabel: 'Blocks' } const WORLD_3D: ViewInfo = { id: 'world3d', label: '3D world', - description: 'The terrain in 3D, coloured by biome, region or height', + description: 'The terrain in 3D, coloured by biome, region or height, or as the blocks the world generates', group: 'WORLD', groupLabel: 'World' } @@ -335,8 +338,8 @@ const NOISE: ViewInfo = { const APP_VIEW_IDS = new Set([WORLD_3D.id, SAVED_WORLD.id, NOISE.id]) function withAppViews(serverViews: ViewInfo[]): ViewInfo[] { - const afterHeight = serverViews.findIndex((candidate) => candidate.id === 'height') + 1 - return [...serverViews.slice(0, afterHeight), WORLD_3D, SAVED_WORLD, ...serverViews.slice(afterHeight)] + const afterRegions = serverViews.findIndex((candidate) => candidate.id === 'regions') + 1 + return [...serverViews.slice(0, afterRegions), WORLD_3D, SAVED_WORLD, ...serverViews.slice(afterRegions)] } function asViewInfo(view: ModuleViewInfo): ViewInfo { @@ -375,7 +378,7 @@ function legendTitle(layer: MapLayerQuery): string { if (layer.view === 'regions' && layer.preview === null) { return 'Regions on screen' } - return layer.view === 'height' ? 'Heights on screen' : 'Biomes on screen' + return 'Biomes on screen' } /** The regions the region view can preview, read again after the pack reloads. */ diff --git a/studio/src/renderer/src/studio/StudioToolbar.tsx b/studio/src/renderer/src/studio/StudioToolbar.tsx index 5d4e88f56..cb7c3d614 100644 --- a/studio/src/renderer/src/studio/StudioToolbar.tsx +++ b/studio/src/renderer/src/studio/StudioToolbar.tsx @@ -72,7 +72,10 @@ export function MapTools({ toggles, hasPlayers, onToggle, onRefresh, onResetZoom onToggle('shading')}> - + + + onToggle('blocks')}> + onToggle('entities')}> diff --git a/studio/src/renderer/src/studio/ViewList.tsx b/studio/src/renderer/src/studio/ViewList.tsx index 65e79c65e..a8faa235c 100644 --- a/studio/src/renderer/src/studio/ViewList.tsx +++ b/studio/src/renderer/src/studio/ViewList.tsx @@ -11,7 +11,6 @@ import { useKeyText } from './useBindings' const VIEW_ICONS: Record = { biomes: 'views/biomes', regions: 'views/regions', - height: 'views/height', world3d: 'views/world-3d', savedWorld: 'views/saved-world', landBiomes: 'views/land-biomes', diff --git a/studio/src/renderer/src/studio/WorldStudio3D.tsx b/studio/src/renderer/src/studio/WorldStudio3D.tsx index f99a19992..93d237982 100644 --- a/studio/src/renderer/src/studio/WorldStudio3D.tsx +++ b/studio/src/renderer/src/studio/WorldStudio3D.tsx @@ -5,6 +5,7 @@ import type { MapTile, WorldInfo } from '../bridge/types' import { heightBandShares } from '../map/census' import { mapTileSource, type TileLayer } from '../map/mapTileSource' import type { GroundInView } from '../scene/groundInView' +import { blockArt } from '../scene/blockArt' import { MapTerrain, type MapTerrainColoring } from '../scene/mapTerrain' import { focusAround, type TerrainStyle } from '../scene/terrainStream' import { TILE_COLUMNS } from '../scene/terrainTiles' @@ -39,26 +40,33 @@ interface WorldStudio3DProps { export function WorldStudio3D({ title, client, world, mapArea, packRevision, onSummary, tell }: WorldStudio3DProps): React.JSX.Element { const [coloring, setColoring] = useState('biomes') const centre = useMemo(() => centreOf(mapArea), [mapArea]) - const source = useMemo(() => mapTileSource(client, TILE_COLUMNS), [client]) + const art = useMemo(() => blockArt(client, true), [client]) + useEffect(() => () => art.dispose(), [art]) + const source = useMemo(() => mapTileSource(client, TILE_COLUMNS, art), [client, art]) const focus = useMemo( () => focusAround(centre.x, centre.z, world.fluidHeight - BLOCKS_BELOW_FLUID_IN_FOCUS, world.fluidHeight + BLOCKS_ABOVE_FLUID_IN_FOCUS), [centre, world.fluidHeight] ) - const layer = useMemo(() => ({ view: 'biomes', preview: null, heights: true, pickNoise: false, revision: packRevision }), [packRevision]) + const showsBlocks = coloring === 'blocks' + const layer = useMemo( + () => ({ view: 'biomes', preview: null, heights: true, pickNoise: false, blocks: showsBlocks ? 'generated' : null, revision: packRevision }), + [packRevision, showsBlocks] + ) const style = useMemo>( () => ({ - surfaceOf: (tile, place) => new MapTerrain(tile, place, coloring, world.fluidHeight), + surfaceOf: (tile, place) => new MapTerrain(tile, place, coloring, world.fluidHeight, art.atlas ?? undefined), floorY: world.minY, topY: world.minY + world.height }), - [coloring, world.fluidHeight, world.minY, world.height] + [coloring, world.fluidHeight, world.minY, world.height, art] ) const { content, pending, stream } = useTerrainStream(source, COARSEST_LEVEL, focus, layer, style, tell) const sampling = useLongPending(pending) const ground = useGroundInView(stream) const heightShares = useMemo(() => heightBandShares(ground?.heights ?? [], world.fluidHeight), [ground, world.fluidHeight]) const inspectsPicks = coloring !== 'height' - const pickLayer = useMemo(() => ({ view: coloring, preview: null }), [coloring]) + const pickView = coloring === 'regions' ? 'regions' : 'biomes' + const pickLayer = useMemo(() => ({ view: pickView, preview: null }), [pickView]) const area = useAreaOf(ground) const inspection = usePickInspection(client, pickLayer, area, inspectsPicks, packRevision) @@ -82,6 +90,9 @@ export function WorldStudio3D({ title, client, world, mapArea, packRevision, onS Height + + Blocks + } > diff --git a/studio/src/renderer/src/studio/shortcuts.test.ts b/studio/src/renderer/src/studio/shortcuts.test.ts index 289d8c573..7db452335 100644 --- a/studio/src/renderer/src/studio/shortcuts.test.ts +++ b/studio/src/renderer/src/studio/shortcuts.test.ts @@ -16,7 +16,7 @@ import { type KeyPress } from './shortcuts' -const DEFAULT_VIEWS = ['biomes', 'regions', 'height', 'landBiomes', 'seaBiomes', 'caveBiomes'].map((id) => ({ id, label: id })) +const DEFAULT_VIEWS = ['biomes', 'regions', 'landBiomes', 'seaBiomes', 'caveBiomes'].map((id) => ({ id, label: id })) const ROWS = shortcutRows(DEFAULT_VIEWS) function press(key: string, modifiers: Partial> = {}): KeyPress { diff --git a/studio/src/renderer/src/studio/shortcuts.ts b/studio/src/renderer/src/studio/shortcuts.ts index b9af6a41d..ac163e503 100644 --- a/studio/src/renderer/src/studio/shortcuts.ts +++ b/studio/src/renderer/src/studio/shortcuts.ts @@ -11,6 +11,7 @@ export type ShortcutAction = | 'entities' | 'highlight' | 'shading' + | 'blocks' | 'borders' | 'help' | 'undo' @@ -55,6 +56,7 @@ export const SHORTCUTS: ShortcutDefinition[] = [ { id: 'entities', label: 'Show entities', group: 'Map', chords: ['e'] }, { id: 'highlight', label: 'Highlight what is under the cursor', group: 'Map', chords: ['h'] }, { id: 'shading', label: 'Terrain shading', group: 'Map', chords: ['s'] }, + { id: 'blocks', label: 'Generated blocks', group: 'Map', chords: ['k'] }, { id: 'borders', label: 'Region borders', group: 'Map', chords: ['b'] }, { id: 'help', label: 'Show the shortcuts', group: 'Map', chords: ['/', '?'] }, { id: 'undo', label: 'Undo', group: 'Node editor', chords: ['ctrl+z'] }, @@ -68,7 +70,6 @@ export const SHORTCUTS: ShortcutDefinition[] = [ const VIEW_KEYS: Record = { biomes: '1', regions: '2', - height: '3', world3d: '4', landBiomes: '5', seaBiomes: '6',