diff --git a/api/CONTRACTS.md b/api/CONTRACTS.md index 0dd7444be..eaed4f3d6 100644 --- a/api/CONTRACTS.md +++ b/api/CONTRACTS.md @@ -46,7 +46,7 @@ types that carry them and lists what the Iris adapter still owes. | Dense chunk output | `Hunk`, `GenerationContext.blocks`, reference `ArrayHunk` | | Positions, boxes and faces | `com.volmit.geometry`: `BlockPosition`, `BlockBox`, `BlockFace` | | Sparse geometry | `GeneratedObject` | -| Studio views of what a module builds | `com.volmit.tooling`: `ModuleSetup.tooling()` (`ToolingRegistry.registerView`), sealed `StudioView` (`SceneView` with `SceneEntry`, `BakeRun` (`Stage`), `BlockParts`, `PatternView` with `PatternEntry`, `PatternArea`, `BlockPattern`), `EditableSceneView` (`SceneFile`, `SceneCreation`, `NodeGraph`, `GraphNode` with `Link`, `NodeSettings`, `Edits`, `Addition`), `JsonText`, `JsonPath` (`Key`, `Index`), host `StudioViewRegistration` | +| Studio views of what a module builds | `com.volmit.tooling`: `ModuleSetup.tooling()` (`ToolingRegistry.registerView`), sealed `StudioView` (`SceneView` with `SceneEntry`, `SceneRequest`, `SceneSizes`, `BakeRun` (`Stage`), `BlockParts`, `PatternView` with `PatternEntry`, `PatternArea`, `BlockPattern`), `EditableSceneView` (`SceneFile`, `SceneCreation`, `NodeGraph`, `GraphNode` with `Link`, `NodeSettings`, `Edits`, `Addition`), `JsonText`, `JsonPath` (`Key`, `Index`), host `StudioViewRegistration` | | Commands of a module | `com.volmit.tooling`: `ToolingRegistry.registerCommand`, immutable `Command` (`named`, `alias`, `describe`, `child`, `argument`, `runs`, `openToEveryone`), typed `Argument` (`word`, `text`, `integer`, `decimal`, `flag`, `choice`, `resource`, `registered`, `reading` with `Argument.Reader`, `orElse`, `suggesting`), `CommandAction`, `CommandContext` (`get`, `sender`, `pack`, `world`, `platform`, `platformStructures`), plain-text `Sender` (with `player()`), `PlatformStructures` (`templates`, `template` answering `StructureTemplate`, `structures`, `structureSets`, `jigsaw` answering `JigsawStructureInfo`, `pool` answering `TemplatePool` with `Member`, `Element`, `ConnectorSource`, `Connectors` and `JigsawConnector`, `supportsCapture`, `openCaptureArea` answering a closable `CaptureArea` whose `capture` answers `CapturedStructure`; `TemplateBlock`; readers throw `StructureAccessException`), `ToolPack` (`edit` with `PackEdit`, `outputFolder`, `objects` with `ObjectCodec`, `worlds`, `services`), host `CommandRegistration` in `FeatureCatalog.commands()` | | Worlds a tool opens | `com.volmit.tooling.world`, exposed to pack modules by host `ExposedPackages`: `ToolWorlds` (`open`, `find`) with `ToolWorldSpec`, `ChunkPainter` and `ChunkCanvas`, `ToolWorld` (`players`, `owns`, `run`, `call`, `block`, `blockEntity`, `setBlock`, `loaded`, `repaint`, `close`), `ToolPlayer` (`targetBlock`, `teleport`, `creative`, `message`, `actionBar`, `sound`, `sidebar`, `particles`, `give` answering whether the item fitted, `held`, `openMenu`), `ToolWorldDenied` (what `open` completes with when the host refuses for a reason the user can fix; a tool reports the message and logs no stack trace), `ToolText` with `TextColor` (styled text, spans in a colour with bold, italic and strikethrough: item names and lore, menu titles, sidebar, chat and action bar; the host shows each span in its colour and style, an empty sidebar title keeps the platform's, and an item read back has plain text), `ToolItem`, `ToolMenu` with `MenuButton` and `MenuClick`, `Particle`, `ToolWorldListener` (`entered`, `left`, `teleported` for every arrival other than walking, at the time of the teleport, `moved`, `sneakToggled`, `used` with `ToolUse`, `blockChanging` with `BlockChange.Cause` and `BlockChange.changed`, `containerChanged` for a closed container inventory or a furnace or brewing stand that started, `command`, `chunkLoaded`, `closeRefusal`, `closing`, `closed`), `com.volmit.geometry.ChunkPos`; a tool world takes the pack's studio slot, so the host asks `closeRefusal` before it closes the world for another studio, the studio close command or a server stop, and waits for `closing` when another studio replaces it; every Y is the world's own; implemented by each platform adapter (Bukkit, and the modded adapters on the server thread) | | Buffered placement writes | `PlacementRequest`, `PlacementAccess`, host-owned `PlacementEdit` | diff --git a/api/README.md b/api/README.md index ea19bc9f5..9084a6acb 100644 --- a/api/README.md +++ b/api/README.md @@ -522,13 +522,16 @@ final class RuinScenes implements SceneView { return List.of(new SceneEntry("arch", "Arch", Optional.empty(), 1)); } - public Optional scene(PackWorld world, String key, int variant) { - return world.resources().objects().object(world.resources().idOf("ruins/" + key)).map(PlaceableObject::geometry); + public Optional scene(PackWorld world, SceneRequest request) { + return world.resources().objects().object(world.resources().idOf("ruins/" + request.key())).map(PlaceableObject::geometry); } } ``` -- A `SceneView` lists entries (`SceneEntry`) and gives each variant's blocks as a `GeneratedObject`, drawn in 3D. A +- A `SceneView` lists entries (`SceneEntry`) and gives the blocks of the scene a `SceneRequest` names (an entry's key + and variant) as a `GeneratedObject`, drawn in 3D. A view whose scenes are a square of the world, such as the Caves + view, returns `SceneSizes` from `sizes()`. The studio then offers those sizes and puts the chosen one in the + request. A `PatternView` lists entries (`PatternEntry`) and gives the blocks one lays over a `PatternArea` at a depth as a `BlockPattern`, drawn from above. `StudioView` is sealed to these two kinds: the studio draws nothing else. - A `SceneView` whose entries are baked from settings says so (`isBaked`) and times a bake on request (`timeBake`, a @@ -547,7 +550,8 @@ final class RuinScenes implements SceneView { settings (`NodeSettings`, shown as the pack's schema describes their type), the nodes it holds and the `Edits` the studio may make (a child list to move nodes into, whether it moves, the `Addition`s it offers). Places in the file are `JsonPath`s of `Key` and `Index` steps. The studio writes the file itself, rewriting only what changes; the - view never writes. A view whose entries the studio may create and delete returns a `SceneCreation` from + view never writes. A view whose file reads as one node of settings returns false from `showsNodes()`, and the + studio shows that node's settings beside the scene instead of a graph. A view whose entries the studio may create and delete returns a `SceneCreation` from `creation()`: the resource kind of its files, the starter JSON of a new entry and the text other files name an entry by; the studio does the writing, listing of uses and trashing. - Absent values are empty, never blank or `-1`: an entry without a group, a node that draws no part of the scene diff --git a/api/api/src/main/java/com/volmit/tooling/EditableSceneView.java b/api/api/src/main/java/com/volmit/tooling/EditableSceneView.java index c6ac55faf..b915cd2e4 100644 --- a/api/api/src/main/java/com/volmit/tooling/EditableSceneView.java +++ b/api/api/src/main/java/com/volmit/tooling/EditableSceneView.java @@ -21,6 +21,14 @@ public interface EditableSceneView extends SceneView { */ NodeGraph graph(PackWorld world, String key, JsonText text); + /** + * Whether the studio shows the file's graph as nodes under the scene, which is the default. A view whose file reads + * as one node of settings says no, and the studio shows those settings beside the scene instead. + */ + default boolean showsNodes() { + return true; + } + /** How the studio creates and removes entries of this view; empty when it may not, which is the default. */ default Optional creation() { return Optional.empty(); diff --git a/api/api/src/main/java/com/volmit/tooling/SceneRequest.java b/api/api/src/main/java/com/volmit/tooling/SceneRequest.java new file mode 100644 index 000000000..5716daf1d --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/SceneRequest.java @@ -0,0 +1,23 @@ +package com.volmit.tooling; + +import java.util.Objects; +import java.util.OptionalInt; + +/** + * Which scene of a {@link SceneView} the studio asks for. + * + * @param key the entry, as {@link SceneEntry#key()} names it + * @param variant from 0 to the entry's {@link SceneEntry#variants()}, exclusive + * @param size how many blocks across to build the scene, one of the view's {@link SceneView#sizes()}; empty when the + * view has none + */ +public record SceneRequest(String key, int variant, OptionalInt size) { + public SceneRequest { + Objects.requireNonNull(key, "key"); + Objects.requireNonNull(size, "size"); + } + + public static SceneRequest of(String key, int variant) { + return new SceneRequest(key, variant, OptionalInt.empty()); + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/SceneSizes.java b/api/api/src/main/java/com/volmit/tooling/SceneSizes.java new file mode 100644 index 000000000..6c4b38459 --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/SceneSizes.java @@ -0,0 +1,34 @@ +package com.volmit.tooling; + +import java.util.List; +import java.util.Objects; + +/** + * The sizes a {@link SceneView} builds its scenes at, which the studio lets one choose between. + * + * @param blocksAcross each size, as how many blocks across the scene is, smallest first + * @param opening the size the studio shows first, one of {@code blocksAcross} + */ +public record SceneSizes(List blocksAcross, int opening) { + public SceneSizes { + blocksAcross = List.copyOf(Objects.requireNonNull(blocksAcross, "blocksAcross")); + if (blocksAcross.isEmpty()) { + throw new IllegalArgumentException("Scene sizes need at least one size"); + } + for (int at = 0; at < blocksAcross.size(); at++) { + if (blocksAcross.get(at) < 1) { + throw new IllegalArgumentException("A scene is at least 1 block across, not " + blocksAcross.get(at)); + } + if (at > 0 && blocksAcross.get(at) <= blocksAcross.get(at - 1)) { + throw new IllegalArgumentException("Scene sizes go from smallest to largest: " + blocksAcross); + } + } + if (!blocksAcross.contains(opening)) { + throw new IllegalArgumentException("The opening size " + opening + " is not one of " + blocksAcross); + } + } + + public boolean offers(int size) { + return blocksAcross.contains(size); + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/SceneView.java b/api/api/src/main/java/com/volmit/tooling/SceneView.java index b02022b3e..059531a59 100644 --- a/api/api/src/main/java/com/volmit/tooling/SceneView.java +++ b/api/api/src/main/java/com/volmit/tooling/SceneView.java @@ -15,12 +15,18 @@ public non-sealed interface SceneView extends StudioView { List entries(PackWorld world); /** - * The blocks of one variant of the entry named {@code key}, its anchor where the studio centres the scene; empty - * when the pack has no such entry, or the entry has fewer variants. - * - * @param variant from 0 to the entry's {@link SceneEntry#variants()}, exclusive + * The blocks of the scene {@code request} names, its anchor where the studio centres the scene; empty when the pack + * has no such entry, or the entry has fewer variants. */ - Optional scene(PackWorld world, String key, int variant); + Optional scene(PackWorld world, SceneRequest request); + + /** + * The sizes the studio lets one build every scene at, such as a square of the world a view carves; empty when each + * entry has a size of its own, which is the default. + */ + default Optional sizes() { + return Optional.empty(); + } /** Whether the entries are built from parts the studio can pick out of the scene, which {@link #parts} tells apart. */ default boolean hasParts() { @@ -32,7 +38,7 @@ public non-sealed interface SceneView extends StudioView { * was built. Asked off the server's threads; empty when the view has no parts, the pack has no such entry, or the * entry has fewer variants. */ - default Optional parts(PackWorld world, String key, int variant) { + default Optional parts(PackWorld world, SceneRequest request) { return Optional.empty(); } diff --git a/api/api/src/test/java/com/volmit/tooling/BakeRunTest.java b/api/api/src/test/java/com/volmit/tooling/BakeRunTest.java index f27cc9d71..63fbe2e2c 100644 --- a/api/api/src/test/java/com/volmit/tooling/BakeRunTest.java +++ b/api/api/src/test/java/com/volmit/tooling/BakeRunTest.java @@ -56,7 +56,7 @@ class BakeRunTest { } @Override - public Optional scene(PackWorld world, String key, int variant) { + public Optional scene(PackWorld world, SceneRequest request) { return Optional.empty(); } }; diff --git a/api/api/src/test/java/com/volmit/tooling/BlockPartsTest.java b/api/api/src/test/java/com/volmit/tooling/BlockPartsTest.java index 1181ca5b2..552798fce 100644 --- a/api/api/src/test/java/com/volmit/tooling/BlockPartsTest.java +++ b/api/api/src/test/java/com/volmit/tooling/BlockPartsTest.java @@ -67,12 +67,12 @@ class BlockPartsTest { } @Override - public Optional scene(PackWorld world, String key, int variant) { + public Optional scene(PackWorld world, SceneRequest request) { return Optional.empty(); } }; assertFalse(plain.hasParts()); - assertTrue(plain.parts(null, "any", 0).isEmpty()); + assertTrue(plain.parts(null, SceneRequest.of("any", 0)).isEmpty()); } } diff --git a/api/host/src/test/java/com/volmit/host/ModuleRegistryTest.java b/api/host/src/test/java/com/volmit/host/ModuleRegistryTest.java index 00aa4576e..1fdf74dee 100644 --- a/api/host/src/test/java/com/volmit/host/ModuleRegistryTest.java +++ b/api/host/src/test/java/com/volmit/host/ModuleRegistryTest.java @@ -204,7 +204,7 @@ class ModuleRegistryTest { public String label() { return id; } public String description() { return id; } public List entries(com.volmit.world.PackWorld world) { return List.of(); } - public Optional scene(com.volmit.world.PackWorld world, String key, int variant) { + public Optional scene(com.volmit.world.PackWorld world, com.volmit.tooling.SceneRequest request) { return Optional.empty(); } }; 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 c3f972a52..ec0ca126e 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 @@ -63,6 +63,8 @@ import com.volmit.tooling.PatternEntry; import com.volmit.tooling.BakeRun; import com.volmit.tooling.BlockParts; import com.volmit.tooling.SceneEntry; +import com.volmit.tooling.SceneRequest; +import com.volmit.tooling.SceneSizes; import java.io.IOException; import java.io.OutputStream; @@ -81,6 +83,7 @@ import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Optional; +import java.util.OptionalInt; import java.util.Set; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; @@ -109,6 +112,9 @@ public final class StudioBridge implements AutoCloseable { private static final int TOKEN_BYTES = 24; private static final int DEFAULT_TILE_SIZE = 128; private static final int LARGEST_TILE_SIZE = 512; + private static final int DEFAULT_CAVES_SIZE = 256; + // 1,024 chunks, generated in seconds on half the cores. + private static final int LARGEST_CAVES_SIZE = 512; // A procedural object's file is a few kilobytes; this leaves room for any pack file without holding a flood. private static final int LARGEST_BODY_BYTES = 4 * 1024 * 1024; private static final double SMALLEST_BLOCKS_PER_PIXEL = 1D / 16D; @@ -261,6 +267,7 @@ public final class StudioBridge implements AutoCloseable { } } case "tile-cancel" -> cancelTile(exchange, query); + case "caves" -> answerAside(exchange, () -> sendBytes(exchange, "application/octet-stream", caves(get(exchange), query))); case "hover" -> sendJson(exchange, STATUS_OK, hover(get(exchange).engine(), query)); case "picks" -> sendJson(exchange, STATUS_OK, picks(get(exchange).engine(), query)); case "regions" -> sendJson(exchange, STATUS_OK, regions(get(exchange).engine())); @@ -374,9 +381,27 @@ public final class StudioBridge implements AutoCloseable { private static List sceneViews(Engine engine) { StudioEditors editors = StudioEditors.of(engine); StudioScenes scenes = StudioScenes.of(engine); - return scenes.views().stream() - .map(view -> new SceneViewInfo(view.id(), view.label(), view.description(), editors.edits(view.id()), editors.edits(view.id()) && editors.creates(view.id()), scenes.isBaked(view.id()), scenes.hasParts(view.id()))) - .toList(); + return scenes.views().stream().map(view -> { + boolean editable = editors.edits(view.id()); + SceneSizesWire sizes = scenes.sizes(view.id()).map(SceneSizesWire::of).orElse(null); + return new SceneViewInfo(view.id(), view.label(), view.description(), editable, editable && editors.creates(view.id()), + editable && editors.showsNodes(view.id()), scenes.isBaked(view.id()), scenes.hasParts(view.id()), sizes); + }).toList(); + } + + // A view with sizes is asked at one of them, the one it opens with when the studio names none. + private static SceneRequest sceneRequest(StudioScenes scenes, Query query) { + String viewId = query.text("view"); + SceneRequest bare = SceneRequest.of(query.text("key"), query.whole("variant", 0)); + Optional sizes = scenes.sizes(viewId); + if (sizes.isEmpty()) { + return bare; + } + int size = query.whole("size", sizes.get().opening()); + if (!sizes.get().offers(size)) { + throw new RequestError(STATUS_BAD_REQUEST, "View " + viewId + " builds scenes " + sizes.get().blocksAcross() + " blocks across, not " + size); + } + return new SceneRequest(bare.key(), bare.variant(), OptionalInt.of(size)); } private static StudioEditors.EditorState sceneFile(Engine engine, Query query) throws IOException { @@ -479,7 +504,8 @@ public final class StudioBridge implements AutoCloseable { String key = query.text("key"); Optional scene; try { - scene = StudioScenes.of(engine).scene(query.text("view"), key, query.whole("variant", 0)); + StudioScenes scenes = StudioScenes.of(engine); + scene = scenes.scene(query.text("view"), sceneRequest(scenes, query)); } catch (NoSuchElementException unknown) { throw new RequestError(STATUS_NOT_FOUND, unknown.getMessage()); } @@ -488,12 +514,12 @@ public final class StudioBridge implements AutoCloseable { private static byte[] sceneParts(Engine engine, Query query) { String key = query.text("key"); - int variant = query.whole("variant", 0); try { StudioScenes scenes = StudioScenes.of(engine); - GeneratedObject scene = scenes.scene(query.text("view"), key, variant) + SceneRequest request = sceneRequest(scenes, query); + GeneratedObject scene = scenes.scene(query.text("view"), request) .orElseThrow(() -> new RequestError(STATUS_NOT_FOUND, "No scene " + key)); - BlockParts parts = scenes.parts(query.text("view"), key, variant) + BlockParts parts = scenes.parts(query.text("view"), request) .orElseThrow(() -> new RequestError(STATUS_NOT_FOUND, "No parts for " + key)); return SceneEncoding.encodeParts(scene, parts); } catch (NoSuchElementException unknown) { @@ -637,6 +663,19 @@ public final class StudioBridge implements AutoCloseable { return MapTileEncoding.encode(tile, gson, StudioBridge::pluginLookOf); } + // Generates every chunk of the square, so a request the studio dropped is let go of as a tile is. + private byte[] caves(StudioWorld.Session session, Query query) { + Engine engine = session.engine(); + int size = query.whole("size", DEFAULT_CAVES_SIZE); + if (size < 1 || size > LARGEST_CAVES_SIZE) { + throw new RequestError(STATUS_BAD_REQUEST, "A square of caves is 1 to " + LARGEST_CAVES_SIZE + " blocks across"); + } + AtomicBoolean dropped = query.has("request") ? droppedFlagOf(query.text("request")) : new AtomicBoolean(); + BooleanSupplier cancelled = () -> dropped.get() || closed || engine.isClosing() || engine.isClosed(); + GeneratedObject caves = session.renderer().cavesAround(query.whole("x", 0), query.whole("z", 0), size, cancelled); + return SceneEncoding.encode(caves, gson); + } + // A tile with blocks waits a minute or more on chunks generated on threads of their own; waiting on the bridge's // few threads, a handful of them would leave none for the studio's other requests. private void answerAside(HttpExchange exchange, Answer answer) { @@ -882,7 +921,15 @@ public final class StudioBridge implements AutoCloseable { } /** A scene view as the studio lists it; {@code editable} when its entries can be edited as nodes, {@code creatable} when they can also be created and deleted, {@code baked} when their bake can be timed, {@code parts} when the blocks of a scene can be told by the part that placed them. */ - private record SceneViewInfo(String id, String label, String description, boolean editable, boolean creatable, boolean baked, boolean parts) { + /** @param sizes null when the view's entries each have a size of their own */ + private record SceneViewInfo(String id, String label, String description, boolean editable, boolean creatable, boolean nodes, + boolean baked, boolean parts, SceneSizesWire sizes) { + } + + private record SceneSizesWire(List blocksAcross, int opening) { + static SceneSizesWire of(SceneSizes sizes) { + return new SceneSizesWire(sizes.blocksAcross(), sizes.opening()); + } } private record UsesBody(List files) { diff --git a/core/src/main/java/art/arcane/iris/core/studio/map/CaveSpace.java b/core/src/main/java/art/arcane/iris/core/studio/map/CaveSpace.java new file mode 100644 index 000000000..aa752f26a --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/studio/map/CaveSpace.java @@ -0,0 +1,158 @@ +/* + * 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.spi.PlatformBlockState; +import art.arcane.iris.util.project.hunk.Hunk; +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockBox; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.GeneratedObject; +import com.volmit.object.ObjectBlock; + +import java.util.ArrayList; +import java.util.BitSet; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.IntBinaryOperator; + +/** + * The caves of a square of generated chunks: every air block under the terrain's top, whichever stage carved it. The + * space is drawn as blocks, as the Caves view draws one cave, and only its outside is kept, as the inside could not be + * seen. Each block takes the colour of the band of heights it lies in, so caves stacked over each other tell apart. + * Chunks are added from several threads at once. + */ +final class CaveSpace { + private static final int CHUNK_SHIFT = 4; + private static final int CHUNK_BLOCKS = 1 << CHUNK_SHIFT; + private static final int CHUNK_MASK = CHUNK_BLOCKS - 1; + private static final int[][] NEIGHBOURS = {{1, 0, 0}, {-1, 0, 0}, {0, 1, 0}, {0, -1, 0}, {0, 0, 1}, {0, 0, -1}}; + /** The colours from high to low, a band each, the last reaching to the world's bottom; the studio's legend mirrors them. */ + private static final List BANDS = List.of( + new Band(64, new BlockState("minecraft:yellow_concrete")), + new Band(32, new BlockState("minecraft:orange_concrete")), + new Band(0, new BlockState("minecraft:red_concrete")), + new Band(-32, new BlockState("minecraft:magenta_concrete")), + new Band(-64, new BlockState("minecraft:purple_concrete")), + new Band(Integer.MIN_VALUE, new BlockState("minecraft:blue_concrete"))); + + private final int minChunkX; + private final int minChunkZ; + private final int chunksAcross; + private final int height; + private final int minWorldY; + private final Map openByChunk = new ConcurrentHashMap<>(); + + /** + * @param height how many blocks tall the world is + * @param minWorldY the world Y of its bottom block + */ + CaveSpace(int minChunkX, int minChunkZ, int chunksAcross, int height, int minWorldY) { + this.minChunkX = minChunkX; + this.minChunkZ = minChunkZ; + this.chunksAcross = chunksAcross; + this.height = height; + this.minWorldY = minWorldY; + } + + /** @param terrainY the height of the terrain's top block in each column, by its x and z in the chunk */ + void add(int chunkX, int chunkZ, Hunk blocks, IntBinaryOperator terrainY) { + BitSet open = new BitSet(CHUNK_BLOCKS * height * CHUNK_BLOCKS); + for (int z = 0; z < CHUNK_BLOCKS; z++) { + for (int x = 0; x < CHUNK_BLOCKS; x++) { + int top = Math.min(terrainY.applyAsInt(x, z), height - 1); + for (int y = 0; y <= top; y++) { + PlatformBlockState block = blocks.get(x, y, z); + if (block == null || block.isAir()) { + open.set(cellOf(x, y, z)); + } + } + } + } + openByChunk.put(keyOf(chunkX, chunkZ), open); + } + + /** The outside of the space, its anchor at the middle of the square's bottom; chunks never added hold no caves. */ + GeneratedObject scene() { + List blocks = new ArrayList<>(); + int across = chunksAcross * CHUNK_BLOCKS; + int lowest = height; + int highest = -1; + for (Map.Entry chunk : openByChunk.entrySet()) { + int chunkX = (int) (chunk.getKey() >> Integer.SIZE); + int chunkZ = (int) (long) chunk.getKey(); + int sceneMinX = (chunkX - minChunkX) * CHUNK_BLOCKS; + int sceneMinZ = (chunkZ - minChunkZ) * CHUNK_BLOCKS; + BitSet open = chunk.getValue(); + for (int cell = open.nextSetBit(0); cell >= 0; cell = open.nextSetBit(cell + 1)) { + int x = sceneMinX + (cell & CHUNK_MASK); + int z = sceneMinZ + ((cell >> CHUNK_SHIFT) & CHUNK_MASK); + int y = cell >> (2 * CHUNK_SHIFT); + if (touchesRock(x, y, z)) { + blocks.add(new ObjectBlock(new BlockPosition(x, y, z), colourAt(y + minWorldY))); + lowest = Math.min(lowest, y); + highest = Math.max(highest, y); + } + } + } + BlockBox bounds = highest < 0 ? new BlockBox(0, 0, 0, across, 1, across) : new BlockBox(0, lowest, 0, across, highest + 1, across); + return new GeneratedObject(bounds, new BlockPosition(across / 2, bounds.minY(), across / 2), blocks, List.of()); + } + + static BlockState colourAt(int worldY) { + for (Band band : BANDS) { + if (worldY >= band.lowestY()) { + return band.colour(); + } + } + return BANDS.getLast().colour(); + } + + // Beside a chunk never added, or past the square's side, counts as rock, so a cave cut off there shows its cut. + private boolean touchesRock(int sceneX, int y, int sceneZ) { + for (int[] step : NEIGHBOURS) { + if (!isOpen(sceneX + step[0], y + step[1], sceneZ + step[2])) { + return true; + } + } + return false; + } + + private boolean isOpen(int sceneX, int y, int sceneZ) { + int across = chunksAcross * CHUNK_BLOCKS; + if (sceneX < 0 || sceneZ < 0 || sceneX >= across || sceneZ >= across || y < 0 || y >= height) { + return false; + } + BitSet open = openByChunk.get(keyOf(minChunkX + (sceneX >> CHUNK_SHIFT), minChunkZ + (sceneZ >> CHUNK_SHIFT))); + return open != null && open.get(cellOf(sceneX & CHUNK_MASK, y, sceneZ & CHUNK_MASK)); + } + + private static int cellOf(int x, int y, int z) { + return x | z << CHUNK_SHIFT | y << (2 * CHUNK_SHIFT); + } + + private static long keyOf(int chunkX, int chunkZ) { + return ((long) chunkX << Integer.SIZE) | (chunkZ & 0xFFFFFFFFL); + } + + /** @param lowestY the world Y of the band's lowest block */ + private record Band(int lowestY, BlockState colour) { + } +} 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 index f822fe3f2..51522f578 100644 --- 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 @@ -29,6 +29,7 @@ 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; +import com.volmit.object.GeneratedObject; import it.unimi.dsi.fastutil.bytes.ByteArrayList; import it.unimi.dsi.fastutil.ints.Int2ByteMap; import it.unimi.dsi.fastutil.ints.Int2ByteMaps; @@ -523,18 +524,45 @@ final class GeneratedChunks implements ColumnTops { } } + /** + * The caves of the square of chunks {@code chunksAcross} wide from chunk ({@code minChunkX}, {@code minChunkZ}), + * each chunk generated anew, as a block scene: see {@link CaveSpace}. A chunk that fails to generate holds no caves. + * + * @throws CancellationException as soon as {@code cancelled} answers true + */ + GeneratedObject cavesIn(int minChunkX, int minChunkZ, int chunksAcross, BooleanSupplier cancelled) { + CaveSpace space = new CaveSpace(minChunkX, minChunkZ, chunksAcross, engine.getHeight(), engine.getMinHeight()); + List> generating = new ArrayList<>(); + for (int chunkZ = minChunkZ; chunkZ < minChunkZ + chunksAcross; chunkZ++) { + for (int chunkX = minChunkX; chunkX < minChunkX + chunksAcross; chunkX++) { + int x = chunkX; + int z = chunkZ; + ChunkTask task = new ChunkTask(() -> { + if (!cancelled.getAsBoolean()) { + space.add(x, z, generateBlocksUnchecked(x, z), terrainYOf(x, z)); + } + }, 1D); + GENERATORS.execute(task); + generating.add(task); + } + } + try { + for (Future task : generating) { + awaitUnlessCancelled(task, cancelled); + } + } catch (CancellationException stopped) { + generating.forEach(task -> task.cancel(false)); + throw stopped; + } + return space.scene(); + } + /** @param reachedBeside the cells along the chunk's sides the open air of the chunks beside it reaches, with its light */ private ChunkTop generate(long key, Int2ByteMap reachedBeside) 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()); - } - IntBinaryOperator terrainY = (x, z) -> engine.getHeight((chunkX << CHUNK_SHIFT) + x, (chunkZ << CHUNK_SHIFT) + z, true); + Hunk blocks = generateBlocks(chunkX, chunkZ); + IntBinaryOperator terrainY = terrainYOf(chunkX, chunkZ); int fluidHeight = engine.getDimension().getFluidHeight(); ChunkCells cells = ChunkCells.of(blocks, terrainY, fluidHeight, this::seenByPlayers, reachedBeside); ColumnRuns[] runs = new ColumnRuns[ColumnRuns.MOST_LEVEL]; @@ -544,6 +572,30 @@ final class GeneratedChunks implements ColumnTops { return new ChunkTop(topsOf(blocks, terrainY, this::seenByPlayers), VisibleBlocks.of(cells, reachedBeside), runs, reachedBeside); } + // The chunk runs through the world's own stages into memory; nothing is placed in the world. + private Hunk generateBlocks(int chunkX, int chunkZ) throws Exception { + 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 blocks; + } + + private Hunk generateBlocksUnchecked(int chunkX, int chunkZ) { + try { + return generateBlocks(chunkX, chunkZ); + } catch (Exception failed) { + throw new CompletionException(failed); + } + } + + private IntBinaryOperator terrainYOf(int chunkX, int chunkZ) { + return (x, z) -> engine.getHeight((chunkX << CHUNK_SHIFT) + x, (chunkZ << CHUNK_SHIFT) + z, true); + } + // A plugin's block can be solid on the server where players see grass they walk through. private PlatformBlockState seenByPlayers(PlatformBlockState block) { return seenByKey.computeIfAbsent(block.key(), key -> { 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 7cba4ea89..4027988e9 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 @@ -24,6 +24,7 @@ import art.arcane.iris.engine.framework.render.RenderType; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.util.project.stream.ProceduralStream; +import com.volmit.object.GeneratedObject; import it.unimi.dsi.fastutil.bytes.ByteArrayList; import it.unimi.dsi.fastutil.shorts.ShortArrayList; @@ -40,6 +41,7 @@ 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 static final int CHUNK_BLOCKS = 16; private final Engine engine; private final GeneratedChunks generated; @@ -73,6 +75,23 @@ public final class MapTileRenderer { : renderView(layer, grid, blocksPerPixel, extras); } + /** + * The caves of the chunks generated in memory over a square {@code blocksAcross} wide around ({@code centerX}, + * {@code centerZ}), widened to whole chunks: every air block under the terrain's top, drawn as blocks coloured by + * height, as {@link CaveSpace} tells. + * + * @throws CancellationException as soon as {@code cancelled} answers true + */ + public GeneratedObject cavesAround(int centerX, int centerZ, int blocksAcross, BooleanSupplier cancelled) { + if (blocksAcross < 1) { + throw new IllegalArgumentException("A square of caves is at least a block across"); + } + int chunksAcross = Math.ceilDiv(blocksAcross, CHUNK_BLOCKS); + int minChunkX = Math.floorDiv(centerX - (blocksAcross / 2), CHUNK_BLOCKS); + int minChunkZ = Math.floorDiv(centerZ - (blocksAcross / 2), CHUNK_BLOCKS); + return generated.cavesIn(minChunkX, minChunkZ, chunksAcross, cancelled); + } + /** * {@code tile}, drawn from ({@code startX}, {@code startZ}), with the block on top of each of its columns from * {@code source}, and the solid blocks raised above it. Where the tile carries heights they become the heights of diff --git a/core/src/main/java/art/arcane/iris/core/studio/scene/StudioEditors.java b/core/src/main/java/art/arcane/iris/core/studio/scene/StudioEditors.java index 0c5887db1..ca19b56fa 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/scene/StudioEditors.java +++ b/core/src/main/java/art/arcane/iris/core/studio/scene/StudioEditors.java @@ -119,6 +119,11 @@ public final class StudioEditors { return save(viewId, key, file, text); } + /** Whether the studio shows the files of {@code viewId} as nodes, rather than as one node's settings beside the scene. */ + public boolean showsNodes(String viewId) { + return views.ask(viewId, "tell whether its files show as nodes", EditableSceneView::showsNodes); + } + /** Whether entries of {@code viewId} can be created and removed from the studio. */ public boolean creates(String viewId) { return views.ask(viewId, "tell whether entries are created", view -> view.creation().isPresent()); diff --git a/core/src/main/java/art/arcane/iris/core/studio/scene/StudioScenes.java b/core/src/main/java/art/arcane/iris/core/studio/scene/StudioScenes.java index 487cf7fae..851f14bad 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/scene/StudioScenes.java +++ b/core/src/main/java/art/arcane/iris/core/studio/scene/StudioScenes.java @@ -23,6 +23,8 @@ import com.volmit.object.GeneratedObject; import com.volmit.tooling.BakeRun; import com.volmit.tooling.BlockParts; import com.volmit.tooling.SceneEntry; +import com.volmit.tooling.SceneRequest; +import com.volmit.tooling.SceneSizes; import com.volmit.tooling.SceneView; import java.util.List; @@ -55,8 +57,13 @@ public final class StudioScenes { * * @throws NoSuchElementException when no module registered a scene view {@code viewId} */ - public Optional scene(String viewId, String key, int variant) { - return views.ask(viewId, "build " + key, view -> view.scene(views.world(), key, variant)); + public Optional scene(String viewId, SceneRequest request) { + return views.ask(viewId, "build " + request.key(), view -> view.scene(views.world(), request)); + } + + /** @throws NoSuchElementException when no module registered a scene view {@code viewId} */ + public Optional sizes(String viewId) { + return views.ask(viewId, "tell its sizes", SceneView::sizes); } /** @throws NoSuchElementException when no module registered a scene view {@code viewId} */ @@ -70,8 +77,8 @@ public final class StudioScenes { * * @throws NoSuchElementException when no module registered a scene view {@code viewId} */ - public Optional parts(String viewId, String key, int variant) { - return views.ask(viewId, "find the parts of " + key, view -> view.parts(views.world(), key, variant)); + public Optional parts(String viewId, SceneRequest request) { + return views.ask(viewId, "find the parts of " + request.key(), view -> view.parts(views.world(), request)); } /** @throws NoSuchElementException when no module registered a scene view {@code viewId} */ diff --git a/core/src/test/java/art/arcane/iris/core/studio/map/CaveSpaceTest.java b/core/src/test/java/art/arcane/iris/core/studio/map/CaveSpaceTest.java new file mode 100644 index 000000000..d55c2f160 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/studio/map/CaveSpaceTest.java @@ -0,0 +1,124 @@ +package art.arcane.iris.core.studio.map; + +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.project.hunk.Hunk; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.GeneratedObject; +import com.volmit.object.ObjectBlock; +import org.junit.Test; + +import java.util.HashSet; +import java.util.Set; +import java.util.function.IntBinaryOperator; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class CaveSpaceTest { + private static final int HEIGHT = 32; + private static final int MIN_WORLD_Y = -16; + private static final int TERRAIN_TOP = 20; + private static final IntBinaryOperator FLAT_TERRAIN = (x, z) -> TERRAIN_TOP; + private static final PlatformBlockState STONE = block("minecraft:stone", false); + private static final PlatformBlockState AIR = block("minecraft:air", true); + + @Test + public void aHollowUnderTheTerrainShowsItsOutsideOnly() { + CaveSpace space = new CaveSpace(0, 0, 1, HEIGHT, MIN_WORLD_Y); + Hunk chunk = stoneUpToTerrain(); + hollow(chunk, 5, 5, 5, 3); + + space.add(0, 0, chunk, FLAT_TERRAIN); + Set kept = positionsOf(space.scene()); + + assertEquals("a 3 block cube without its middle", 26, kept.size()); + assertFalse(kept.contains(new BlockPosition(6, 6, 6))); + } + + @Test + public void theAirAboveTheTerrainIsNoCave() { + CaveSpace space = new CaveSpace(0, 0, 1, HEIGHT, MIN_WORLD_Y); + + space.add(0, 0, stoneUpToTerrain(), FLAT_TERRAIN); + + assertTrue(space.scene().blocks().isEmpty()); + } + + @Test + public void aCaveAcrossAChunkEdgeHasNoWallThere() { + CaveSpace space = new CaveSpace(0, 0, 2, HEIGHT, MIN_WORLD_Y); + Hunk west = stoneUpToTerrain(); + Hunk east = stoneUpToTerrain(); + hollow(west, 13, 5, 5, 3); + hollow(east, 0, 5, 5, 3); + + space.add(0, 0, west, FLAT_TERRAIN); + space.add(1, 0, east, FLAT_TERRAIN); + Set kept = positionsOf(space.scene()); + + assertFalse("the middle of the hollow on the west side of the edge", kept.contains(new BlockPosition(15, 6, 6))); + assertFalse("the middle of the hollow on the east side of the edge", kept.contains(new BlockPosition(16, 6, 6))); + } + + @Test + public void eachBandOfHeightsHasItsColour() { + assertEquals("minecraft:yellow_concrete", CaveSpace.colourAt(80).key()); + assertEquals("minecraft:red_concrete", CaveSpace.colourAt(0).key()); + assertEquals("minecraft:magenta_concrete", CaveSpace.colourAt(-1).key()); + assertEquals("minecraft:blue_concrete", CaveSpace.colourAt(-200).key()); + } + + @Test + public void theSceneStandsOnItsLowestCave() { + CaveSpace space = new CaveSpace(0, 0, 1, HEIGHT, MIN_WORLD_Y); + Hunk chunk = stoneUpToTerrain(); + hollow(chunk, 5, 4, 5, 2); + + space.add(0, 0, chunk, FLAT_TERRAIN); + GeneratedObject scene = space.scene(); + + assertEquals(4, scene.bounds().minY()); + assertEquals(6, scene.bounds().maxY()); + for (ObjectBlock block : scene.blocks()) { + assertEquals(CaveSpace.colourAt(block.position().y() + MIN_WORLD_Y), block.state()); + } + } + + private static Hunk stoneUpToTerrain() { + Hunk chunk = Hunk.newArrayHunk(16, HEIGHT, 16); + for (int y = 0; y < HEIGHT; y++) { + for (int z = 0; z < 16; z++) { + for (int x = 0; x < 16; x++) { + chunk.set(x, y, z, y <= TERRAIN_TOP ? STONE : AIR); + } + } + } + return chunk; + } + + private static void hollow(Hunk chunk, int minX, int minY, int minZ, int across) { + for (int y = minY; y < minY + across; y++) { + for (int z = minZ; z < minZ + across; z++) { + for (int x = minX; x < Math.min(16, minX + across); x++) { + chunk.set(x, y, z, AIR); + } + } + } + } + + private static Set positionsOf(GeneratedObject scene) { + Set positions = new HashSet<>(); + scene.blocks().forEach(block -> positions.add(block.position())); + return positions; + } + + private static PlatformBlockState block(String key, boolean air) { + PlatformBlockState block = mock(PlatformBlockState.class); + when(block.key()).thenReturn(key); + when(block.isAir()).thenReturn(air); + return block; + } +} diff --git a/core/src/test/java/art/arcane/iris/modules/carve/CaveScenesTest.java b/core/src/test/java/art/arcane/iris/modules/carve/CaveScenesTest.java index 5f3ce7abd..ce875c2f6 100644 --- a/core/src/test/java/art/arcane/iris/modules/carve/CaveScenesTest.java +++ b/core/src/test/java/art/arcane/iris/modules/carve/CaveScenesTest.java @@ -2,19 +2,20 @@ package art.arcane.iris.modules.carve; import art.arcane.iris.core.modules.CarveTestWorld; import art.arcane.iris.engine.object.TestSettings; -import art.arcane.iris.modules.carve.field.CavePart; +import com.volmit.geometry.BlockPosition; import com.volmit.object.GeneratedObject; import com.volmit.object.ObjectBlock; -import com.volmit.tooling.BlockParts; import com.volmit.tooling.GraphNode; import com.volmit.tooling.JsonText; import com.volmit.tooling.NodeGraph; import com.volmit.tooling.SceneEntry; +import com.volmit.tooling.SceneRequest; import org.junit.Test; import java.util.HashSet; import java.util.List; import java.util.Optional; +import java.util.OptionalInt; import java.util.Set; import static org.junit.Assert.assertEquals; @@ -28,6 +29,9 @@ public class CaveScenesTest { "cavern": {"size": 40, "height": 18, "coverage": 0.2, "pillars": {"spacing": 14, "thickness": 4}}} """; private static final String TUNNELS_ONLY = "{\"tunnel\": {\"width\": {\"min\": 4, \"max\": 6}, \"stretch\": 48}}"; + private static final String TUNNEL_BLOCK = "minecraft:light_blue_concrete"; + private static final String CAVERN_BLOCK = "minecraft:orange_concrete"; + private static final int[][] NEIGHBOURS = {{1, 0, 0}, {-1, 0, 0}, {0, 1, 0}, {0, -1, 0}, {0, 0, 1}, {0, 0, -1}}; private final CaveScenes view = new CaveScenes(); private final CarveTestWorld world = new CarveTestWorld() @@ -45,50 +49,78 @@ public class CaveScenesTest { } @Test - public void theSceneIsTheCarvedSpaceAndEveryBlockBelongsToAPart() { - GeneratedObject scene = view.scene(world, "deep/mixed", 0).orElseThrow(); - BlockParts parts = view.parts(world, "deep/mixed", 0).orElseThrow(); + public void tunnelsAndCavernsShowInTheirOwnColours() { + GeneratedObject scene = scene("deep/mixed", 0, 128); - assertFalse(scene.blocks().isEmpty()); - Set partsSeen = new HashSet<>(); + Set colours = new HashSet<>(); + scene.blocks().forEach(block -> colours.add(block.state().key())); + assertEquals(Set.of(TUNNEL_BLOCK, CAVERN_BLOCK), colours); + } + + // The inside of the carved space could not be seen, so it is left out: every block kept touches rock or the side. + @Test + public void onlyTheOutsideOfTheCarvedSpaceIsKept() { + GeneratedObject scene = scene("deep/mixed", 0, 64); + + Set kept = new HashSet<>(); + scene.blocks().forEach(block -> kept.add(block.position())); for (ObjectBlock block : scene.blocks()) { - int part = parts.partAt(block.position()); - assertNotEquals(BlockParts.NO_PART, part); - partsSeen.add(part); + assertTrue(block.position() + " is inside the carved space", touchesSomethingNotKept(block.position(), kept, scene)); } - assertEquals(Set.of(CavePart.TUNNEL.ordinal(), CavePart.CAVERN.ordinal()), partsSeen); + } + + @Test + public void theSceneIsAsWideAsTheSizeAskedFor() { + assertEquals(64, scene("tunnels", 0, 64).bounds().maxX()); + assertEquals(256, scene("tunnels", 0, 256).bounds().maxX()); + assertEquals(128, view.scene(world, SceneRequest.of("tunnels", 0)).orElseThrow().bounds().maxX()); + assertTrue("a size the view does not offer", view.scene(world, new SceneRequest("tunnels", 0, OptionalInt.of(100))).isEmpty()); } @Test public void eachVariantIsTheCaveSomewhereElse() { - GeneratedObject first = view.scene(world, "tunnels", 0).orElseThrow(); + GeneratedObject first = scene("tunnels", 0, 128); - assertEquals(first.blocks(), view.scene(world, "tunnels", 0).orElseThrow().blocks()); - assertNotEquals(first.blocks(), view.scene(world, "tunnels", 1).orElseThrow().blocks()); - assertTrue(view.scene(world, "tunnels", CavePreview.VARIANTS).isEmpty()); - assertTrue(view.scene(world, "missing", 0).isEmpty()); + assertEquals(first.blocks(), scene("tunnels", 0, 128).blocks()); + assertNotEquals(first.blocks(), scene("tunnels", 1, 128).blocks()); + assertTrue(view.scene(world, request("tunnels", CavePreview.VARIANTS, 128)).isEmpty()); + assertTrue(view.scene(world, request("missing", 0, 128)).isEmpty()); } @Test - public void aCaveFileReadsAsACaveWithItsTunnelAndCavernAndPillars() { + public void aCaveFileIsOneNodeWithASectionForEachPart() { NodeGraph graph = view.graph(world, "deep/mixed", JsonText.parse(MIXED)); + assertFalse(view.showsNodes()); GraphNode cave = graph.roots().getFirst(); assertEquals("mixed", cave.title()); - GraphNode tunnel = cave.children().get(0).node(); - GraphNode cavern = cave.children().get(1).node(); - assertEquals("Tunnel", tunnel.title()); - assertEquals(CavePart.TUNNEL.ordinal(), tunnel.part().getAsInt()); - assertEquals(CavePart.CAVERN.ordinal(), cavern.part().getAsInt()); - assertEquals("Pillars", cavern.children().getFirst().node().title()); + assertTrue(cave.children().isEmpty()); + assertEquals(List.of("Cave", "Tunnel", "Cavern", "Pillars"), cave.settings().stream().map(GraphNode.NodeSettings::title).toList()); } @Test - public void anUnwrittenPartIsShownSoSettingItWritesIt() { + public void anUnwrittenPartHasASectionSoSettingItWritesIt() { NodeGraph graph = view.graph(world, "tunnels", JsonText.parse(TUNNELS_ONLY)); - GraphNode cavern = graph.roots().getFirst().children().get(1).node(); - assertEquals("Cavern (unset)", cavern.title()); - assertTrue("a cavern the cave does not have draws nothing", cavern.part().isEmpty()); + assertEquals(List.of("Cave", "Tunnel", "Cavern (unset)", "Pillars (unset)"), + graph.roots().getFirst().settings().stream().map(GraphNode.NodeSettings::title).toList()); + } + + private GeneratedObject scene(String key, int variant, int size) { + return view.scene(world, request(key, variant, size)).orElseThrow(); + } + + private static SceneRequest request(String key, int variant, int size) { + return new SceneRequest(key, variant, OptionalInt.of(size)); + } + + private static boolean touchesSomethingNotKept(BlockPosition position, Set kept, GeneratedObject scene) { + for (int[] step : NEIGHBOURS) { + BlockPosition beside = new BlockPosition(position.x() + step[0], position.y() + step[1], position.z() + step[2]); + if (!scene.bounds().contains(beside.x(), beside.y(), beside.z()) || !kept.contains(beside)) { + return true; + } + } + return false; } } diff --git a/module/src/main/java/art/arcane/iris/modules/carve/CaveGraph.java b/module/src/main/java/art/arcane/iris/modules/carve/CaveGraph.java index ab49e3c2c..de1e9d226 100644 --- a/module/src/main/java/art/arcane/iris/modules/carve/CaveGraph.java +++ b/module/src/main/java/art/arcane/iris/modules/carve/CaveGraph.java @@ -18,10 +18,8 @@ package art.arcane.iris.modules.carve; -import art.arcane.iris.modules.carve.field.CavePart; import com.volmit.tooling.GraphNode; import com.volmit.tooling.GraphNode.Edits; -import com.volmit.tooling.GraphNode.Link; import com.volmit.tooling.GraphNode.NodeSettings; import com.volmit.tooling.JsonPath; import com.volmit.tooling.JsonText; @@ -32,50 +30,38 @@ import java.util.OptionalInt; import java.util.Set; /** - * A cave file as nodes: the cave with its depth and surface rules, its tunnels, and its caverns with their pillars. - * Tunnels and caverns always have a node, written or not, since setting a value of one writes it into the file. + * A cave file as one node of settings, a section each for the cave, its tunnels, its caverns and their pillars. Every + * section is there, written or not, since setting a value in one writes it into the file. */ final class CaveGraph { private static final String TUNNEL = "tunnel"; private static final String CAVERN = "cavern"; private static final String PILLARS = "pillars"; private static final String UNWRITTEN = " (unset)"; - private static final String HOLDS = ""; - private static final Set NO_NODES = Set.of(); + private static final Set NONE_ELSEWHERE = Set.of(); private CaveGraph() { } - /** - * @param read what the pack read from the file, which tells which parts the scene draws; it may be older than {@code text} - * @throws IllegalArgumentException when the file does not hold an object - */ - static NodeGraph of(String name, JsonText text, Cave read) { + /** @throws IllegalArgumentException when the file does not hold an object */ + static NodeGraph of(String name, JsonText text) { if (!(text.root() instanceof JsonText.Obj root)) { throw new IllegalArgumentException("The file does not hold an object"); } + JsonPath tunnelPath = JsonPath.ROOT.member(TUNNEL); JsonPath cavernPath = JsonPath.ROOT.member(CAVERN); - GraphNode tunnel = partNode("Tunnel", JsonPath.ROOT.member(TUNNEL), root.get(TUNNEL).isPresent(), read.tunnel().isPresent(), - CavePart.TUNNEL, new NodeSettings("Tunnel", JsonPath.ROOT.member(TUNNEL), CaveTunnel.class, NO_NODES), List.of()); - GraphNode pillars = new GraphNode("Pillars", titled("Pillars", hasMember(root, CAVERN, PILLARS)), cavernPath.member(PILLARS), - OptionalInt.empty(), List.of(), List.of(new NodeSettings("Pillars", cavernPath.member(PILLARS), CavePillars.class, NO_NODES)), - List.of(), Edits.NONE); - GraphNode cavern = partNode("Cavern", cavernPath, root.get(CAVERN).isPresent(), read.cavern().isPresent(), CavePart.CAVERN, - new NodeSettings("Cavern", cavernPath, CaveCavern.class, Set.of(PILLARS)), List.of(new Link(HOLDS, pillars))); - GraphNode cave = new GraphNode("Cave", name, JsonPath.ROOT, OptionalInt.empty(), List.of(), - List.of(new NodeSettings("Cave", JsonPath.ROOT, Cave.class, Set.of(TUNNEL, CAVERN))), - List.of(new Link(HOLDS, tunnel), new Link(HOLDS, cavern)), Edits.NONE); + JsonPath pillarsPath = cavernPath.member(PILLARS); + List sections = List.of( + new NodeSettings("Cave", JsonPath.ROOT, Cave.class, Set.of(TUNNEL, CAVERN)), + new NodeSettings(titled("Tunnel", root.get(TUNNEL).isPresent()), tunnelPath, CaveTunnel.class, NONE_ELSEWHERE), + new NodeSettings(titled("Cavern", root.get(CAVERN).isPresent()), cavernPath, CaveCavern.class, Set.of(PILLARS)), + new NodeSettings(titled("Pillars", hasMember(root, CAVERN, PILLARS)), pillarsPath, CavePillars.class, NONE_ELSEWHERE)); + GraphNode cave = new GraphNode("Cave", name, JsonPath.ROOT, OptionalInt.empty(), List.of(), sections, List.of(), Edits.NONE); return new NodeGraph(List.of(cave)); } - private static GraphNode partNode(String kind, JsonPath path, boolean written, boolean drawn, CavePart part, - NodeSettings settings, List children) { - OptionalInt drawnPart = drawn ? OptionalInt.of(part.ordinal()) : OptionalInt.empty(); - return new GraphNode(kind, titled(kind, written), path, drawnPart, List.of(), List.of(settings), children, Edits.NONE); - } - - private static String titled(String kind, boolean written) { - return written ? kind : kind + UNWRITTEN; + private static String titled(String section, boolean written) { + return written ? section : section + UNWRITTEN; } private static boolean hasMember(JsonText.Obj root, String member, String inner) { diff --git a/module/src/main/java/art/arcane/iris/modules/carve/CavePreview.java b/module/src/main/java/art/arcane/iris/modules/carve/CavePreview.java index 9ac278218..3e6f913ba 100644 --- a/module/src/main/java/art/arcane/iris/modules/carve/CavePreview.java +++ b/module/src/main/java/art/arcane/iris/modules/carve/CavePreview.java @@ -27,49 +27,46 @@ import com.volmit.geometry.BlockPosition; import com.volmit.object.GeneratedObject; import com.volmit.object.ObjectBlock; import com.volmit.resource.ResourceId; -import com.volmit.tooling.BlockParts; +import com.volmit.tooling.SceneSizes; import com.volmit.world.PackWorld; import java.util.ArrayList; import java.util.Arrays; -import java.util.HashMap; import java.util.List; -import java.util.Map; /** * One cave carved over a square of the world under a flat surface, with the seed the world carves it with: the carved * space drawn as blocks, a colour per part, so the studio shows the shape of the cave instead of the rock around it. - * A variant is the same cave somewhere else in the world. + * Only the carved blocks on the outside of the space are kept, as the inside could not be seen. A variant is the same + * cave somewhere else in the world. */ final class CavePreview { static final int VARIANTS = 4; - private static final int AREA_CHUNKS = 8; - private static final int AREA_BLOCKS = AREA_CHUNKS * 16; - private static final int CHUNK_COLUMNS = 256; + static final SceneSizes SIZES = new SceneSizes(List.of(64, 128, 256, 512), 128); /** The surface the preview carves under, in world Y. */ static final int SURFACE_WORLD_Y = 96; + private static final int CHUNK_BLOCKS = 16; + private static final int CHUNK_COLUMNS = CHUNK_BLOCKS * CHUNK_BLOCKS; /** A cave deeper than this under the surface is cut off at the bottom of the preview. */ private static final int MAX_DEPTH_BLOCKS = 256; private static final int VARIANT_SPACING_BLOCKS = 4096; + private static final byte ROCK = 0; private static final BlockState TUNNEL_BLOCK = new BlockState("minecraft:light_blue_concrete"); private static final BlockState CAVERN_BLOCK = new BlockState("minecraft:orange_concrete"); private static final int[] FLAT_SURFACE = new int[CHUNK_COLUMNS]; private static final double[] LISTED_EVERYWHERE = new double[CHUNK_COLUMNS]; private static final boolean[] NOTHING_SEALED = new boolean[CHUNK_COLUMNS]; + private static final int[][] NEIGHBOURS = {{1, 0, 0}, {-1, 0, 0}, {0, 1, 0}, {0, -1, 0}, {0, 0, 1}, {0, 0, -1}}; static { Arrays.fill(LISTED_EVERYWHERE, 1D); } - private final GeneratedObject scene; - private final BlockParts parts; - - private CavePreview(GeneratedObject scene, BlockParts parts) { - this.scene = scene; - this.parts = parts; + private CavePreview() { } - static CavePreview of(PackWorld world, ResourceId id, Cave cave, int variant) { + /** @param size how many blocks across the square is, a whole number of chunks */ + static GeneratedObject of(PackWorld world, ResourceId id, Cave cave, int variant, int size) { int bottomWorldY = Math.max(world.minWorldY(), SURFACE_WORLD_Y - MAX_DEPTH_BLOCKS); int surfaceHeight = SURFACE_WORLD_Y - world.minWorldY(); int lowestHeight = bottomWorldY - world.minWorldY(); @@ -77,40 +74,74 @@ final class CavePreview { CaveCarver carver = new CaveCarver(cave, world.resources().noise(), seed, world.minWorldY(), surfaceHeight + 1); int[] surface = FLAT_SURFACE.clone(); Arrays.fill(surface, surfaceHeight); + CarvedSpace carved = new CarvedSpace(size, surfaceHeight - lowestHeight + 1); int originX = variant * VARIANT_SPACING_BLOCKS; - Map carved = new HashMap<>(); - for (int chunkX = 0; chunkX < AREA_CHUNKS; chunkX++) { - for (int chunkZ = 0; chunkZ < AREA_CHUNKS; chunkZ++) { - int sceneX = chunkX * 16; - int sceneZ = chunkZ * 16; - carver.carveByPart(originX + sceneX, sceneZ, surface, LISTED_EVERYWHERE, NOTHING_SEALED, (part, localX, y, localZ) -> { - if (y >= lowestHeight) { - carved.putIfAbsent(new BlockPosition(sceneX + localX, y - lowestHeight, sceneZ + localZ), part); - } - }); + int chunks = size / CHUNK_BLOCKS; + for (int chunkX = 0; chunkX < chunks; chunkX++) { + for (int chunkZ = 0; chunkZ < chunks; chunkZ++) { + int sceneX = chunkX * CHUNK_BLOCKS; + int sceneZ = chunkZ * CHUNK_BLOCKS; + carver.carveByPart(originX + sceneX, sceneZ, surface, LISTED_EVERYWHERE, NOTHING_SEALED, + (part, localX, y, localZ) -> carved.carve(sceneX + localX, y - lowestHeight, sceneZ + localZ, part)); } } - return new CavePreview(sceneOf(carved, surfaceHeight - lowestHeight + 1), partsOf(carved)); + return carved.outside(); } - private static GeneratedObject sceneOf(Map carved, int height) { - List blocks = new ArrayList<>(carved.size()); - carved.forEach((position, part) -> blocks.add(new ObjectBlock(position, part == CavePart.TUNNEL ? TUNNEL_BLOCK : CAVERN_BLOCK))); - BlockBox bounds = new BlockBox(0, 0, 0, AREA_BLOCKS, height, AREA_BLOCKS); - return new GeneratedObject(bounds, new BlockPosition(AREA_BLOCKS / 2, 0, AREA_BLOCKS / 2), blocks, List.of()); - } + /** The carved blocks of a box, by the part that carved each first. */ + private static final class CarvedSpace { + private final int size; + private final int height; + private final byte[] parts; - private static BlockParts partsOf(Map carved) { - Map parts = new HashMap<>(carved.size()); - carved.forEach((position, part) -> parts.put(position, part.ordinal())); - return new BlockParts(parts); - } + CarvedSpace(int size, int height) { + this.size = size; + this.height = height; + this.parts = new byte[size * height * size]; + } - GeneratedObject scene() { - return scene; - } + void carve(int x, int y, int z, CavePart part) { + if (y < 0 || y >= height) { + return; + } + int cell = cellOf(x, y, z); + if (parts[cell] == ROCK) { + parts[cell] = (byte) (part.ordinal() + 1); + } + } - BlockParts parts() { - return parts; + // A carved block is on the outside where a block beside it is rock, or where it touches the box's side. + GeneratedObject outside() { + List blocks = new ArrayList<>(); + for (int y = 0; y < height; y++) { + for (int z = 0; z < size; z++) { + for (int x = 0; x < size; x++) { + byte part = parts[cellOf(x, y, z)]; + if (part != ROCK && touchesRock(x, y, z)) { + blocks.add(new ObjectBlock(new BlockPosition(x, y, z), part == CavePart.TUNNEL.ordinal() + 1 ? TUNNEL_BLOCK : CAVERN_BLOCK)); + } + } + } + } + BlockBox bounds = new BlockBox(0, 0, 0, size, height, size); + return new GeneratedObject(bounds, new BlockPosition(size / 2, 0, size / 2), blocks, List.of()); + } + + private boolean touchesRock(int x, int y, int z) { + for (int[] step : NEIGHBOURS) { + int nx = x + step[0]; + int ny = y + step[1]; + int nz = z + step[2]; + boolean inside = nx >= 0 && ny >= 0 && nz >= 0 && nx < size && ny < height && nz < size; + if (!inside || parts[cellOf(nx, ny, nz)] == ROCK) { + return true; + } + } + return false; + } + + private int cellOf(int x, int y, int z) { + return (y * size + z) * size + x; + } } } diff --git a/module/src/main/java/art/arcane/iris/modules/carve/CaveScenes.java b/module/src/main/java/art/arcane/iris/modules/carve/CaveScenes.java index 25bc66d43..983cf7810 100644 --- a/module/src/main/java/art/arcane/iris/modules/carve/CaveScenes.java +++ b/module/src/main/java/art/arcane/iris/modules/carve/CaveScenes.java @@ -20,13 +20,14 @@ package art.arcane.iris.modules.carve; import com.volmit.object.GeneratedObject; import com.volmit.resource.ResourceId; -import com.volmit.tooling.BlockParts; import com.volmit.tooling.EditableSceneView; import com.volmit.tooling.JsonText; import com.volmit.tooling.NodeGraph; import com.volmit.tooling.SceneCreation; import com.volmit.tooling.SceneEntry; import com.volmit.tooling.SceneFile; +import com.volmit.tooling.SceneRequest; +import com.volmit.tooling.SceneSizes; import com.volmit.world.PackWorld; import java.util.LinkedHashMap; @@ -35,9 +36,9 @@ import java.util.Map; import java.util.Optional; /** - * The studio's Caves view: every cave of the pack's {@code caves/} folder carved over 128 by 128 blocks under a flat - * surface, the carved space drawn as blocks so its shape shows. Each variant is the same cave elsewhere in the world. - * Each cave's file can be edited as nodes, and the studio redraws the cave as it changes. + * The studio's Caves view: every cave of the pack's {@code caves/} folder carved over a square of the world under a + * flat surface, the carved space drawn as blocks so its shape shows. Each variant is the same cave elsewhere in the + * world. A cave's settings are shown beside it, and the studio redraws the cave as they change. */ public final class CaveScenes implements EditableSceneView { private static final ResourceId ID = ResourceId.parse("iris:carve/caves"); @@ -72,18 +73,22 @@ public final class CaveScenes implements EditableSceneView { } @Override - public Optional scene(PackWorld world, String key, int variant) { - return preview(world, key, variant).map(CavePreview::scene); + public Optional sizes() { + return Optional.of(CavePreview.SIZES); } @Override - public boolean hasParts() { - return true; - } - - @Override - public Optional parts(PackWorld world, String key, int variant) { - return preview(world, key, variant).map(CavePreview::parts); + public Optional scene(PackWorld world, SceneRequest request) { + int size = request.size().orElse(CavePreview.SIZES.opening()); + if (request.variant() < 0 || request.variant() >= CavePreview.VARIANTS || !CavePreview.SIZES.offers(size)) { + return Optional.empty(); + } + ResourceId id = world.resources().idOf(request.key()); + Cave cave = CaveResources.cave(world.resources(), id); + if (cave == null) { + return Optional.empty(); + } + return Optional.of(world.state(Previews.class, ignored -> new Previews()).of(world, new Place(id, request.variant(), size), cave)); } @Override @@ -94,11 +99,14 @@ public final class CaveScenes implements EditableSceneView { : Optional.empty(); } - // A file the pack could not read yet draws no parts, so its nodes are shown without part ids. @Override public NodeGraph graph(PackWorld world, String key, JsonText text) { - Cave read = Optional.ofNullable(CaveResources.cave(world.resources(), key)).orElseGet(Cave::new); - return CaveGraph.of(key.substring(key.lastIndexOf(FOLDER_SEPARATOR) + 1), text, read); + return CaveGraph.of(key.substring(key.lastIndexOf(FOLDER_SEPARATOR) + 1), text); + } + + @Override + public boolean showsNodes() { + return false; } @Override @@ -106,18 +114,6 @@ public final class CaveScenes implements EditableSceneView { return Optional.of(CREATION); } - private static Optional preview(PackWorld world, String key, int variant) { - if (variant < 0 || variant >= CavePreview.VARIANTS) { - return Optional.empty(); - } - ResourceId id = world.resources().idOf(key); - Cave cave = CaveResources.cave(world.resources(), id); - if (cave == null) { - return Optional.empty(); - } - return Optional.of(world.state(Previews.class, ignored -> new Previews()).of(world, id, cave, variant)); - } - private static SceneEntry entryOf(ResourceId id) { String path = id.path(); int lastSeparator = path.lastIndexOf(FOLDER_SEPARATOR); @@ -126,8 +122,8 @@ public final class CaveScenes implements EditableSceneView { } /** - * The previews the studio asked for last. It asks for a scene and then its parts, so both come from one carve. A - * reload reads the cave into a new object, which keys a new preview. + * The scenes the studio asked for last, so stepping back to a size or variant is instant. A reload reads the cave + * into a new object, which builds its scenes anew. */ private static final class Previews { private static final int KEPT = 8; @@ -139,25 +135,24 @@ public final class CaveScenes implements EditableSceneView { } }; - CavePreview of(PackWorld world, ResourceId id, Cave cave, int variant) { - Place place = new Place(id, variant); + GeneratedObject of(PackWorld world, Place place, Cave cave) { synchronized (recent) { Built known = recent.get(place); if (known != null && known.from == cave) { - return known.preview; + return known.scene; } } - CavePreview preview = CavePreview.of(world, id, cave, variant); + GeneratedObject scene = CavePreview.of(world, place.cave(), cave, place.variant(), place.size()); synchronized (recent) { - recent.put(place, new Built(cave, preview)); + recent.put(place, new Built(cave, scene)); } - return preview; + return scene; } } - private record Place(ResourceId cave, int variant) { + private record Place(ResourceId cave, int variant, int size) { } - private record Built(Cave from, CavePreview preview) { + private record Built(Cave from, GeneratedObject scene) { } } diff --git a/module/src/main/java/art/arcane/iris/modules/objects/PackObjectScenes.java b/module/src/main/java/art/arcane/iris/modules/objects/PackObjectScenes.java index 75a26153e..4656b9ab5 100644 --- a/module/src/main/java/art/arcane/iris/modules/objects/PackObjectScenes.java +++ b/module/src/main/java/art/arcane/iris/modules/objects/PackObjectScenes.java @@ -23,6 +23,7 @@ import com.volmit.object.PlaceableObject; import com.volmit.resource.PackResources; import com.volmit.resource.ResourceId; import com.volmit.tooling.SceneEntry; +import com.volmit.tooling.SceneRequest; import com.volmit.tooling.SceneView; import com.volmit.world.PackWorld; @@ -57,12 +58,12 @@ public final class PackObjectScenes implements SceneView { } @Override - public Optional scene(PackWorld world, String key, int variant) { - if (variant != 0) { + public Optional scene(PackWorld world, SceneRequest request) { + if (request.variant() != 0) { return Optional.empty(); } PackResources resources = world.resources(); - return resources.objects().object(resources.idOf(key)).map(PlaceableObject::geometry); + return resources.objects().object(resources.idOf(request.key())).map(PlaceableObject::geometry); } private static SceneEntry entryOf(String key) { diff --git a/module/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectScenes.java b/module/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectScenes.java index 8a826810a..733ef6666 100644 --- a/module/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectScenes.java +++ b/module/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectScenes.java @@ -34,6 +34,7 @@ import com.volmit.tooling.NodeGraph; import com.volmit.tooling.SceneCreation; import com.volmit.tooling.SceneEntry; import com.volmit.tooling.SceneFile; +import com.volmit.tooling.SceneRequest; import com.volmit.world.PackWorld; import java.util.Arrays; @@ -91,9 +92,9 @@ public final class ProceduralObjectScenes implements EditableSceneView { } @Override - public Optional scene(PackWorld world, String key, int variant) { - return ProceduralObjectCatalog.of(world).variants(ProceduralObjectCatalog.KEY_PREFIX + key) - .flatMap(variants -> variants.variant(variant)) + public Optional scene(PackWorld world, SceneRequest request) { + return ProceduralObjectCatalog.of(world).variants(ProceduralObjectCatalog.KEY_PREFIX + request.key()) + .flatMap(variants -> variants.variant(request.variant())) .map(PlaceableObject::geometry); } @@ -103,11 +104,11 @@ public final class ProceduralObjectScenes implements EditableSceneView { } @Override - public Optional parts(PackWorld world, String key, int variant) { - return ProceduralObjectCatalog.of(world).variants(ProceduralObjectCatalog.KEY_PREFIX + key) + public Optional parts(PackWorld world, SceneRequest request) { + return ProceduralObjectCatalog.of(world).variants(ProceduralObjectCatalog.KEY_PREFIX + request.key()) .filter(ResolvedProceduralObject.class::isInstance) .map(ResolvedProceduralObject.class::cast) - .flatMap(resolved -> resolved.variant(variant).map(resolved::parts)); + .flatMap(resolved -> resolved.variant(request.variant()).map(resolved::parts)); } @Override diff --git a/studio/src/renderer/src/bridge/BridgeClient.ts b/studio/src/renderer/src/bridge/BridgeClient.ts index f39111745..9e7739274 100644 --- a/studio/src/renderer/src/bridge/BridgeClient.ts +++ b/studio/src/renderer/src/bridge/BridgeClient.ts @@ -40,6 +40,13 @@ export class BridgeError extends Error { } } +/** Which scene of a scene view: an entry's variant, at one of the view's sizes or null when it has none. */ +export interface ScenePlace { + key: string + variant: number + size: number | null +} + export interface TileRequest { view: string /** The region the region view previews everywhere, or null for the world as it is. */ @@ -213,17 +220,28 @@ export class BridgeClient { return this.json(`scene-bake?${new URLSearchParams({ view: viewId, key })}`, { signal }) } - async scene(viewId: string, key: string, variant: number, signal?: AbortSignal): Promise { - const response = await this.fetch(`scene?${new URLSearchParams({ view: viewId, key, variant: String(variant) })}`, { signal }) + async scene(viewId: string, place: ScenePlace, signal?: AbortSignal): Promise { + const response = await this.fetch(`scene?${sceneQuery(viewId, place)}`, { signal }) return decodeScene(await response.arrayBuffer()) } /** The part that placed each block of {@link scene}, in the same order, or NO_PART; baked again on the server to find out. */ - async sceneParts(viewId: string, key: string, variant: number, signal?: AbortSignal): Promise { - const response = await this.fetch(`scene-parts?${new URLSearchParams({ view: viewId, key, variant: String(variant) })}`, { signal }) + async sceneParts(viewId: string, place: ScenePlace, signal?: AbortSignal): Promise { + const response = await this.fetch(`scene-parts?${sceneQuery(viewId, place)}`, { signal }) return new Int32Array(await response.arrayBuffer()) } + /** + * The caves of the world's generated chunks over a square {@code size} blocks across around a spot: every air block + * under the terrain, drawn as blocks coloured by height. Every chunk of the square is generated, which takes seconds. + */ + async caves(centerX: number, centerZ: number, size: number, signal: AbortSignal): Promise { + const query = new URLSearchParams({ x: String(Math.round(centerX)), z: String(Math.round(centerZ)), size: String(size) }) + this.cancelOnAbort(query, signal) + const response = await this.fetch(`caves?${query}`, { signal }) + return decodeScene(await response.arrayBuffer()) + } + /** The pattern views the pack's modules show, such as its palettes. */ patternViews(): Promise { return this.json('patterns') @@ -334,6 +352,14 @@ export class BridgeClient { } } +function sceneQuery(viewId: string, place: ScenePlace): URLSearchParams { + const query = new URLSearchParams({ view: viewId, key: place.key, variant: String(place.variant) }) + if (place.size !== null) { + query.set('size', String(place.size)) + } + return query +} + function layerQuery(layer: MapLayerQuery, rest: Record): URLSearchParams { const query = new URLSearchParams({ view: layer.view, ...rest }) if (layer.preview !== null) { diff --git a/studio/src/renderer/src/bridge/types.ts b/studio/src/renderer/src/bridge/types.ts index e3f133226..8f96477cc 100644 --- a/studio/src/renderer/src/bridge/types.ts +++ b/studio/src/renderer/src/bridge/types.ts @@ -40,8 +40,18 @@ export interface SceneEntry { export interface SceneViewInfo extends ModuleViewInfo { editable: boolean creatable: boolean + /** Whether an editable view's files show as nodes under the scene; else as one node's settings beside it. */ + nodes: boolean baked: boolean parts: boolean + /** The sizes the scenes can be built at, or null when each entry has its own. */ + sizes: SceneSizes | null +} + +/** The sizes a scene view builds its scenes at, as blocks across, smallest first, and the one shown first (IrisApi SceneSizes). */ +export interface SceneSizes { + blocksAcross: number[] + opening: number } /** One timed bake of a scene entry (IrisApi BakeRun): a time per step, added up over every variant. */ diff --git a/studio/src/renderer/src/studio/SceneStudio.tsx b/studio/src/renderer/src/studio/SceneStudio.tsx index cec7a72c2..da27118b0 100644 --- a/studio/src/renderer/src/studio/SceneStudio.tsx +++ b/studio/src/renderer/src/studio/SceneStudio.tsx @@ -21,7 +21,7 @@ import { EntryBrowser } from './EntryBrowser' import { useEntryFiles } from './EntryFileDialogs' import { NodeInspector } from './NodeInspector' import { NodePane } from './NodePane' -import { Panel, SidebarPanel, Stepper, ViewIsland } from './Sidebar' +import { Panel, SidebarPanel, SizeChoice, Stepper, ViewIsland } from './Sidebar' import { SceneViewport, type PickedSurface } from './SceneViewport' const NUMBER = new Intl.NumberFormat('en-US') @@ -54,6 +54,8 @@ export function SceneStudio({ client, view, packRevision, onSummary, tell }: Sce const entryKeys = useMemo(() => entries.map((candidate) => candidate.key), [entries]) const files = useEntryFiles(client, view.id, entryKeys, (key) => setChosen({ key, variant: 0 }), tell) const [farLeavesOnly, setFarLeavesOnly] = useState(false) + const [chosenSize, setChosenSize] = useState<{ viewId: string; size: number } | null>(null) + const size = chosenSize?.viewId === view.id ? chosenSize.size : (view.sizes?.opening ?? null) const chooseVariant = (next: number): void => { if (entry !== null) { setChosen({ key: entry.key, variant: (next + entry.variants) % entry.variants }) @@ -63,14 +65,16 @@ export function SceneStudio({ client, view, packRevision, onSummary, tell }: Sce const bakeTiming = useBakeTiming(client, view.id, entry?.key ?? null, view.baked, packRevision, tell) const editor = useNodeEditor(client, view.id, view.editable ? (entry?.key ?? null) : null, packRevision, tell) + const editsAsForm = view.editable && !view.nodes const [selectedPath, setSelectedPath] = useState(null) - const selected = editor.state?.roots != null && selectedPath !== null ? nodeWithPath(editor.state.roots, selectedPath) : null + const roots = editor.state?.roots ?? null + const selected = roots === null ? null : editsAsForm ? (roots[0] ?? null) : selectedPath !== null ? nodeWithPath(roots, selectedPath) : null const values = useMemo(() => (editor.state === null ? undefined : parsedText(editor.state.text)), [editor.state]) const suggestions = useMemo(() => new SuggestionStore((of) => client.suggestions(of)), [client, packRevision]) const [pickedPart, setPickedPart] = useState(NO_PART) const highlightedPart = view.parts ? (selected?.partId ?? pickedPart) : NO_PART - const { scene, shown, sceneParts, building } = useSceneMesh(client, view, entry, variant, packRevision, models, images, farLeavesOnly, highlightedPart, tell) + const { scene, shown, sceneParts, building } = useSceneMesh(client, view, entry, variant, size, packRevision, models, images, farLeavesOnly, highlightedPart, tell) const shownScene = shown?.scene ?? null const blockIndex = useMemo(() => (shownScene === null ? null : new BlockIndex(shownScene)), [shownScene]) const shownParts = partsOf(sceneParts, shownScene) @@ -121,12 +125,15 @@ export function SceneStudio({ client, view, packRevision, onSummary, tell }: Sce title={view.label} entry={entry} variant={variant} + sizes={view.sizes?.blocksAcross ?? null} + size={size} shown={shown} status={building && entry !== null ? (waiting ?? `Building ${entry.name}`) : null} onVariant={chooseVariant} + onSize={(next) => setChosenSize({ viewId: view.id, size: next })} onPick={view.parts ? pickPart : undefined} /> - {view.editable && entry !== null && ( + {view.editable && !editsAsForm && entry !== null && ( 1 && ( - onVariant(variant - 1)} - onOn={() => onVariant(variant + 1)} - /> - ) + <> + {sizes !== null && size !== null && } + {entry !== null && entry.variants > 1 && ( + onVariant(variant - 1)} + onOn={() => onVariant(variant + 1)} + /> + )} + } > @@ -247,6 +260,7 @@ function useSceneMesh( view: SceneViewInfo, entry: SceneEntry | null, variant: number, + size: number | null, packRevision: number, models: BlockModels, images: BridgeAssets, @@ -268,9 +282,10 @@ function useSceneMesh( return } const stop = new AbortController() + const place = { key, variant, size } setBuilding(true) client - .scene(viewId, key, variant, stop.signal) + .scene(viewId, place, stop.signal) .then((found) => { if (stop.signal.aborted) { return @@ -278,7 +293,7 @@ function useSceneMesh( setScene(found) if (hasParts) { client - .sceneParts(viewId, key, variant, stop.signal) + .sceneParts(viewId, place, stop.signal) .then((parts) => !stop.signal.aborted && setSceneParts({ scene: found, parts })) .catch((failure: Error) => !stop.signal.aborted && tell(failure.message)) } @@ -291,7 +306,7 @@ function useSceneMesh( setBuilding(false) }) return () => stop.abort() - }, [client, viewId, hasParts, key, variant, packRevision, tell]) + }, [client, viewId, hasParts, key, variant, size, packRevision, tell]) const faint = useMemo(() => { const parts = partsOf(sceneParts, scene) diff --git a/studio/src/renderer/src/studio/Sidebar.tsx b/studio/src/renderer/src/studio/Sidebar.tsx index 2d8e78d9c..25295a39e 100644 --- a/studio/src/renderer/src/studio/Sidebar.tsx +++ b/studio/src/renderer/src/studio/Sidebar.tsx @@ -2,6 +2,7 @@ import { createContext, useContext } from 'react' import { createPortal } from 'react-dom' import { IdeIcon, type IdeIconName } from '@/components/IdeIcon' import { Button } from '@/components/ui/button' +import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group' import { cn } from '@/lib/utils' /** Where a view puts its own lists: under the views in the left island, as in v3e. */ @@ -44,6 +45,26 @@ export function Stepper({ label, backHint, onHint, onBack, onOn }: StepperProps) ) } +interface SizeChoiceProps { + /** Each size, as blocks across, smallest first. */ + sizes: readonly number[] + size: number + onSize(size: number): void +} + +/** Chooses how many blocks across an area is, from an island's header. */ +export function SizeChoice({ sizes, size, onSize }: SizeChoiceProps): React.JSX.Element { + return ( + value !== '' && onSize(Number(value))}> + {sizes.map((choice) => ( + + {choice} + + ))} + + ) +} + interface ViewIslandProps { title: string /** The view's own buttons, at the right of its header. */ diff --git a/studio/src/renderer/src/studio/WorldStudio3D.tsx b/studio/src/renderer/src/studio/WorldStudio3D.tsx index 3a885a3b2..b9a1d6743 100644 --- a/studio/src/renderer/src/studio/WorldStudio3D.tsx +++ b/studio/src/renderer/src/studio/WorldStudio3D.tsx @@ -1,4 +1,5 @@ import { useEffect, useMemo, useState } from 'react' +import { Toggle } from '@/components/ui/toggle' import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group' import type { BridgeClient, MapLayerQuery, WorldRect } from '../bridge/BridgeClient' import type { MapTile, WorldInfo } from '../bridge/types' @@ -16,8 +17,9 @@ import { PickInspector } from './PickInspector' import { SceneViewport } from './SceneViewport' import { usePickInspection } from './usePickInspection' import { useSpotActions } from './useSpotActions' -import { HEADER_CHOICE, Panel, ViewIsland } from './Sidebar' +import { HEADER_CHOICE, Panel, SizeChoice, ViewIsland } from './Sidebar' import { useGroundInView, useLongPending, useTerrainStream } from './useTerrainStream' +import { caveBandShares, useWorldCaves, type CaveArea } from './useWorldCaves' const NUMBER = new Intl.NumberFormat('en-US') // The map's coarsest tiles are 4096 blocks a pixel, which is level 12. @@ -27,6 +29,9 @@ const BLOCKS_BELOW_FLUID_IN_FOCUS = 32 // Every level carries blocks, out to the horizon: a coarse tile generates a chunk for each of its columns, a minute or // so of the server's time, and the ground already sampled stays in sight meanwhile. const MOST_BLOCKS_PER_COLUMN = 2 ** COARSEST_LEVEL +// Every chunk of the square is generated: 256 blocks across is 256 chunks, seconds of the server's time. +const CAVE_SIZES = [128, 256, 512] +const OPENING_CAVE_SIZE = 256 // Tiles with generated blocks take seconds to minutes each. The same tiles without them stand in, but only on ground // where no tile with blocks of any level is known yet. @@ -88,42 +93,76 @@ export function WorldStudio3D({ title, client, world, mapArea, packRevision, onS const area = useAreaOf(ground) const inspection = usePickInspection(client, pickLayer, area, inspectsPicks, packRevision) const spotActions = useSpotActions(client, tell, true) + const [showsCaves, setShowsCaves] = useState(false) + const [caveArea, setCaveArea] = useState(null) + const caves = useWorldCaves(client, caveArea, packRevision, tell) + const caveShares = useMemo(() => (caves.scene === null ? [] : caveBandShares(caves.scene)), [caves.scene]) + // The caves are generated around the middle of the ground in view when they are shown, or at another size there. + const showCavesAt = (size: number): void => { + const middle = area === null ? centre : { x: Math.round((area.minX + area.maxX) / 2), z: Math.round((area.minZ + area.maxZ) / 2) } + setCaveArea((known) => (known !== null && known.centerX === middle.x && known.centerZ === middle.z && known.size === size ? known : { centerX: middle.x, centerZ: middle.z, size })) + setShowsCaves(true) + } + + const notice = showsCaves ? caves.status : sampling ? 'Sampling the terrain' : null useEffect(() => { - onSummary(`Around ${NUMBER.format(centre.x)}, ${NUMBER.format(centre.z)}`) + const around = showsCaves && caveArea !== null ? { x: caveArea.centerX, z: caveArea.centerZ } : centre + onSummary(`${showsCaves ? 'Caves around' : 'Around'} ${NUMBER.format(around.x)}, ${NUMBER.format(around.z)}`) return () => onSummary(null) - }, [centre, onSummary]) + }, [centre, showsCaves, caveArea, onSummary]) return ( <> value !== '' && setColoring(value as MapTerrainColoring)}> - - Biomes - - - Regions - - - Height - - - Blocks - - + <> + {showsCaves ? ( + + ) : ( + value !== '' && setColoring(value as MapTerrainColoring)}> + + Biomes + + + Regions + + + Height + + + Blocks + + + )} + (pressed ? showCavesAt(caveArea?.size ?? OPENING_CAVE_SIZE) : setShowsCaves(false))} + > + Caves + + } > - - {sampling && ( + {showsCaves ? ( + + ) : ( + + )} + {notice !== null && (
- Sampling the terrain + {notice}
)}
- {inspectsPicks ? ( + {showsCaves ? ( + + ) : inspectsPicks ? ( ) : ( diff --git a/studio/src/renderer/src/studio/useWorldCaves.ts b/studio/src/renderer/src/studio/useWorldCaves.ts new file mode 100644 index 000000000..bb7833e5b --- /dev/null +++ b/studio/src/renderer/src/studio/useWorldCaves.ts @@ -0,0 +1,92 @@ +import { useEffect, useMemo, useState } from 'react' +import type { BridgeClient } from '../bridge/BridgeClient' +import type { Share } from '../map/census' +import { BlockModels } from '../scene/blockModels' +import { BridgeAssets } from '../scene/BridgeAssets' +import { INTS_PER_BLOCK, type BlockScene } from '../scene/sceneDecoding' +import { buildSceneMesh, type SceneMesh } from '../scene/sceneMesh' + +/** Where the caves of the world are shown: a square of blocks around a spot. */ +export interface CaveArea { + centerX: number + centerZ: number + size: number +} + +export interface WorldCaves { + scene: BlockScene | null + mesh: SceneMesh | null + /** What the server is doing while the caves are on their way, or null once they are in. */ + status: string | null +} + +/** + * The colour of each band of heights the caves are drawn in, from the highest down, as the server colours them + * (Iris core CaveSpace). + */ +const CAVE_BANDS: readonly { block: string; name: string; color: number }[] = [ + { block: 'minecraft:yellow_concrete', name: 'Y 64 and up', color: 0xf1af15 }, + { block: 'minecraft:orange_concrete', name: 'Y 32 to 63', color: 0xe06101 }, + { block: 'minecraft:red_concrete', name: 'Y 0 to 31', color: 0x8e2121 }, + { block: 'minecraft:magenta_concrete', name: 'Y −32 to −1', color: 0xa9309f }, + { block: 'minecraft:purple_concrete', name: 'Y −64 to −33', color: 0x64209c }, + { block: 'minecraft:blue_concrete', name: 'Below Y −64', color: 0x2c2e8f } +] + +/** How much of the caves' outside lies in each band of heights, highest first; bands without caves are left out. */ +export function caveBandShares(scene: BlockScene): Share[] { + const counts = new Map() + for (let offset = 3; offset < scene.blocks.length; offset += INTS_PER_BLOCK) { + const paletteIndex = scene.blocks[offset] + counts.set(paletteIndex, (counts.get(paletteIndex) ?? 0) + 1) + } + const blocks = scene.blocks.length / INTS_PER_BLOCK + return CAVE_BANDS.flatMap((band) => { + const count = counts.get(scene.palette.indexOf(band.block)) ?? 0 + return count === 0 ? [] : [{ subject: { kind: 'HEIGHT' as const, key: band.block, name: band.name }, color: band.color, fraction: count / blocks }] + }) +} + +/** + * The caves of the world's generated chunks in {@code area}, asked for again when it or the pack changes; null asks + * for none. A newer area abandons an older one, on the server too, and a replaced mesh is freed. + */ +export function useWorldCaves(client: BridgeClient, area: CaveArea | null, packRevision: number, tell: (message: string) => void): WorldCaves { + const [waiting, setWaiting] = useState(null) + const images = useMemo(() => new BridgeAssets(client, setWaiting), [client]) + const models = useMemo(() => new BlockModels(images), [images]) + const [shown, setShown] = useState<{ scene: BlockScene; mesh: SceneMesh } | null>(null) + const [building, setBuilding] = useState(false) + const centerX = area?.centerX + const centerZ = area?.centerZ + const size = area?.size + + useEffect(() => { + if (centerX === undefined || centerZ === undefined || size === undefined) { + return + } + const stop = new AbortController() + setBuilding(true) + client + .caves(centerX, centerZ, size, stop.signal) + .then((scene) => buildSceneMesh(scene, models, images).then((mesh) => ({ scene, mesh }))) + .then((built) => { + if (stop.signal.aborted) { + built.mesh.dispose() + return + } + setShown(built) + }) + .catch((failure: Error) => !stop.signal.aborted && tell(failure.message)) + .finally(() => !stop.signal.aborted && setBuilding(false)) + return () => stop.abort() + }, [client, centerX, centerZ, size, packRevision, models, images, tell]) + + useEffect(() => () => shown?.mesh.dispose(), [shown]) + + return { + scene: shown?.scene ?? null, + mesh: shown?.mesh ?? null, + status: building ? (waiting ?? `Generating the caves of ${size} × ${size} blocks`) : null + } +}