From 13c0705d44706db91a1b9d1c84e20d66f67c70c0 Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 6 Nov 2026 01:10:17 +0100 Subject: [PATCH] Studio map: inspect noise picks and preview one region The picks route measures, for the area in view, how each region or biome noise spreads over the bands that pick its options, against how much ground each option gets. Tiles can carry the noise that settled each spot's pick, and the regions view can preview one region across the whole map with the surface biomes it would place there. Preview tiles take their heights from the shading lattice, so they draw as fast as biome tiles. Only coastline pixels can then disagree with the hover's exact biome: 0.25% of spots at 1-2 blocks/px, 2.3% at 8. The bridge serialises nulls so the studio can tell "none" from "not sent". --- .../core/studio/bridge/MapTileEncoding.java | 17 +- .../iris/core/studio/bridge/StudioBridge.java | 75 +++- .../iris/core/studio/map/ChildPicks.java | 75 ++++ .../arcane/iris/core/studio/map/MapHover.java | 11 +- .../arcane/iris/core/studio/map/MapLabel.java | 2 +- .../arcane/iris/core/studio/map/MapLayer.java | 65 ++++ .../core/studio/map/MapPickInspection.java | 319 ++++++++++++++++++ .../iris/core/studio/map/MapPickNoise.java | 103 ++++++ .../iris/core/studio/map/MapPickPath.java | 84 +++-- .../arcane/iris/core/studio/map/MapTile.java | 12 +- .../iris/core/studio/map/MapTileRenderer.java | 76 ++++- .../art/arcane/iris/engine/IrisComplex.java | 75 +++- .../core/studio/bridge/StudioBridgeTest.java | 13 + .../studio/map/MapPickInspectionTest.java | 98 ++++++ .../iris/core/studio/map/MapPickPathTest.java | 142 ++------ .../core/studio/map/MapTileRendererTest.java | 46 ++- .../iris/core/studio/map/PickedWorld.java | 105 ++++++ 17 files changed, 1123 insertions(+), 195 deletions(-) create mode 100644 core/src/main/java/art/arcane/iris/core/studio/map/ChildPicks.java create mode 100644 core/src/main/java/art/arcane/iris/core/studio/map/MapLayer.java create mode 100644 core/src/main/java/art/arcane/iris/core/studio/map/MapPickInspection.java create mode 100644 core/src/main/java/art/arcane/iris/core/studio/map/MapPickNoise.java create mode 100644 core/src/test/java/art/arcane/iris/core/studio/map/MapPickInspectionTest.java create mode 100644 core/src/test/java/art/arcane/iris/core/studio/map/PickedWorld.java 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 0eefc1318..e7a4f682d 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 @@ -31,7 +31,8 @@ import java.util.List; * A {@link MapTile} as the studio reads it, little endian: *
  * 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
+ * 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
  * 
* The header holds the size, the scale, the subject kind and the labels the grids index. Every array starts on a * multiple of 4 bytes, so the studio views them in place. @@ -44,12 +45,15 @@ final class MapTileEncoding { static byte[] encode(MapTile tile, Gson gson) { boolean hasHeights = tile.heights() != null; - byte[] header = gson.toJson(new Header(tile.size(), tile.blocksPerPixel(), tile.subjectKind(), tile.labels(), hasHeights)) + boolean hasPickNoise = tile.pickNoise() != null; + byte[] header = gson.toJson(new Header(tile.size(), tile.blocksPerPixel(), tile.subjectKind(), tile.labels(), + hasHeights, hasPickNoise)) .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); + + (hasHeights ? cells * Float.BYTES : 0) + + (hasPickNoise ? cells * Float.BYTES : 0); ByteBuffer buffer = ByteBuffer.allocate(length).order(ByteOrder.LITTLE_ENDIAN); buffer.putInt(header.length).put(header); align(buffer); @@ -61,6 +65,10 @@ final class MapTileEncoding { align(buffer); if (hasHeights) { buffer.asFloatBuffer().put(tile.heights()); + buffer.position(buffer.position() + cells * Float.BYTES); + } + if (hasPickNoise) { + buffer.asFloatBuffer().put(tile.pickNoise()); } return buffer.array(); } @@ -73,6 +81,7 @@ final class MapTileEncoding { buffer.position(aligned(buffer.position())); } - private record Header(int size, double blocksPerPixel, MapLabel.Kind subjectKind, List labels, boolean heights) { + private record Header(int size, double blocksPerPixel, MapLabel.Kind subjectKind, List labels, + boolean heights, boolean pickNoise) { } } 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 27eececfe..af8b839f3 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 @@ -21,12 +21,17 @@ package art.arcane.iris.core.studio.bridge; import art.arcane.iris.core.gui.GuiHost; import art.arcane.iris.core.gui.GuiMarker; import art.arcane.iris.core.studio.map.MapHover; +import art.arcane.iris.core.studio.map.MapLabel; +import art.arcane.iris.core.studio.map.MapLayer; +import art.arcane.iris.core.studio.map.MapPickInspection; import art.arcane.iris.core.studio.map.MapTile; import art.arcane.iris.core.studio.map.MapView; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.render.RenderType; +import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.spi.IrisLogging; import com.google.gson.Gson; +import com.google.gson.GsonBuilder; import com.sun.net.httpserver.Headers; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpServer; @@ -41,10 +46,12 @@ import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.SecureRandom; import java.util.Arrays; +import java.util.EnumSet; import java.util.HashMap; import java.util.HexFormat; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; @@ -81,7 +88,8 @@ public final class StudioBridge implements AutoCloseable { private final StudioWorld world; private final String token; - private final Gson gson = new Gson(); + // The studio tells "none" from "not sent", so a null field is written as null rather than left out. + private final Gson gson = new GsonBuilder().serializeNulls().create(); private final HttpServer server; private final int port; private final ExecutorService workers; @@ -179,7 +187,9 @@ public final class StudioBridge implements AutoCloseable { switch (endpoint) { case "world" -> sendJson(exchange, STATUS_OK, worldInfo(get(exchange))); case "tile" -> sendBytes(exchange, "application/octet-stream", tile(get(exchange), query)); - case "hover" -> sendJson(exchange, STATUS_OK, MapHover.sample(get(exchange).engine(), view(query), query.number("x"), query.number("z"))); + 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())); case "entities" -> sendJson(exchange, STATUS_OK, entities(get(exchange))); case "events" -> streamEvents(exchange); case "teleport" -> teleport(exchange, query); @@ -236,8 +246,47 @@ public final class StudioBridge implements AutoCloseable { .orElseThrow(() -> new RequestError(STATUS_BAD_REQUEST, "Unknown view: " + query.text("view"))); } - private byte[] tile(StudioWorld.Session session, Query query) { + /** The view, and the region the region view previews when the query names one in {@code preview}. */ + private static MapLayer layer(Engine engine, Query query) { MapView view = view(query); + if (!query.has("preview")) { + return MapLayer.of(view); + } + if (view != MapView.REGIONS) { + throw new RequestError(STATUS_BAD_REQUEST, "Only the region view previews a region"); + } + IrisRegion region = engine.getComplex().preparedRegion(query.text("preview")); + if (region == null) { + throw new RequestError(STATUS_BAD_REQUEST, "This world has no region " + query.text("preview")); + } + return MapLayer.preview(region); + } + + private static MapHover hover(Engine engine, Query query) { + return MapHover.sample(engine, layer(engine, query), query.number("x"), query.number("z")); + } + + private static MapPickInspection.Inspection picks(Engine engine, Query query) { + MapLayer layer = layer(engine, query); + if (!layer.hasPickNoise()) { + throw new RequestError(STATUS_BAD_REQUEST, "The " + layer.view().label() + " view has no picks to inspect"); + } + try { + MapPickInspection.Area area = new MapPickInspection.Area( + query.number("minX"), query.number("minZ"), query.number("maxX"), query.number("maxZ")); + return MapPickInspection.measure(engine, layer, area); + } catch (IllegalArgumentException badArea) { + throw new RequestError(STATUS_BAD_REQUEST, badArea.getMessage()); + } + } + + private static List regions(Engine engine) { + return engine.getComplex().preparedRegions().stream().map(region -> MapLabel.of(engine, region)).toList(); + } + + private byte[] tile(StudioWorld.Session session, Query query) { + Engine engine = session.engine(); + MapLayer layer = layer(engine, query); int size = query.whole("size", DEFAULT_TILE_SIZE); double blocksPerPixel = query.number("scale"); if (size < 1 || size > LARGEST_TILE_SIZE) { @@ -247,12 +296,22 @@ 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; - Engine engine = session.engine(); - MapTile tile = session.renderer().render(view, query.whole("x", 0) * tileBlocks, query.whole("z", 0) * tileBlocks, - blocksPerPixel, size, query.flag("heights"), () -> closed || engine.isClosing() || engine.isClosed()); + 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()); return MapTileEncoding.encode(tile, gson); } + private static Set tileExtras(Query query) { + Set extras = EnumSet.noneOf(MapTile.Extra.class); + if (query.flag("heights")) { + extras.add(MapTile.Extra.HEIGHTS); + } + if (query.flag("noise")) { + extras.add(MapTile.Extra.PICK_NOISE); + } + return extras; + } + private List entities(StudioWorld.Session session) { if (session.overlay() == null) { return List.of(); @@ -412,6 +471,10 @@ public final class StudioBridge implements AutoCloseable { } } + boolean has(String name) { + return values.containsKey(name); + } + boolean flag(String name) { String value = values.get(name); return "1".equals(value) || "true".equals(value); diff --git a/core/src/main/java/art/arcane/iris/core/studio/map/ChildPicks.java b/core/src/main/java/art/arcane/iris/core/studio/map/ChildPicks.java new file mode 100644 index 000000000..ee02bf4ec --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/studio/map/ChildPicks.java @@ -0,0 +1,75 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.studio.map; + +import art.arcane.iris.engine.IrisComplex; +import art.arcane.iris.engine.object.world.biome.IrisBiome; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +/** The child picks the generator makes from a biome at a spot, parent first; the last one settled the spot's biome. */ +final class ChildPicks { + private ChildPicks() { + } + + // A parent that keeps the spot ends the walk: every level below would read the same noise and keep it again. + static List from(IrisComplex complex, IrisBiome biome, double x, double z) { + List picks = new ArrayList<>(); + IrisBiome parent = biome; + for (int level = 0; level < IrisComplex.CHILD_PICK_LEVELS && !parent.getChildren().isEmpty(); level++) { + List slots = complex.childSlots(parent); + if (slots.isEmpty()) { + break; + } + double noise = complex.childNoise(parent).noiseFast2D(x, z); + IrisBiome picked = slots.get(slotIndex(noise, slots.size())).withInferredType(parent.getInferredType()); + ChildPick pick = new ChildPick(parent, slots, noise, picked); + picks.add(pick); + if (pick.kept()) { + break; + } + parent = picked; + } + return picks; + } + + /** The noise that settled the spot after the children: the last child pick's, or the given one when none picked. */ + static double settlingNoise(IrisComplex complex, IrisBiome biome, double x, double z, double listNoise) { + List picks = from(complex, biome, x, z); + return picks.isEmpty() ? listNoise : picks.getLast().noise(); + } + + /** The slot the child noise picks, rounded the way {@code CNG.fit2D} rounds. */ + static int slotIndex(double noise, int slotCount) { + if (slotCount == 1) { + return 0; + } + long rounded = Math.round(noise * (slotCount - 1)); + return (int) Math.clamp(rounded, 0, slotCount - 1); + } + + /** One level of children: the parent's slots, the noise that read them, and the biome it picked. */ + record ChildPick(IrisBiome parent, List slots, double noise, IrisBiome picked) { + boolean kept() { + return Objects.equals(picked.getLoadKey(), parent.getLoadKey()); + } + } +} diff --git a/core/src/main/java/art/arcane/iris/core/studio/map/MapHover.java b/core/src/main/java/art/arcane/iris/core/studio/map/MapHover.java index a33592b25..40cc9a31c 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/map/MapHover.java +++ b/core/src/main/java/art/arcane/iris/core/studio/map/MapHover.java @@ -45,11 +45,14 @@ public record MapHover(double worldX, double worldZ, MapLabel biome, MapLabel ca // IrisComplex measures slope as the height change over this many blocks. private static final double SLOPE_STREAM_RANGE_BLOCKS = 3D; - public static MapHover sample(Engine engine, MapView view, double worldX, double worldZ) { + /** In a region preview, the biome and region are the previewed ones; the rest is the world as it is. */ + public static MapHover sample(Engine engine, MapLayer layer, double worldX, double worldZ) { IrisComplex complex = engine.getComplex(); - IrisBiome biome = complex.getBaseBiomeStream().get(worldX, worldZ); + IrisBiome biome = layer.previews() + ? complex.surfacePickAsIfIn(layer.previewRegion(), worldX, worldZ).biome() + : complex.getBaseBiomeStream().get(worldX, worldZ); IrisBiome caveBiome = complex.getCaveBiomeStream().get(worldX, worldZ); - IrisRegion region = complex.getRegionStream().get(worldX, worldZ); + IrisRegion region = layer.previews() ? layer.previewRegion() : complex.getRegionStream().get(worldX, worldZ); PlatformBiome vanillaBiome = complex.getTrueBiomeDerivativeStream().get(worldX, worldZ); double slope = complex.getSlopeStream().getDouble(worldX, worldZ); IrisDimension dimension = engine.getDimension(); @@ -65,7 +68,7 @@ public record MapHover(double worldX, double worldZ, MapLabel biome, MapLabel ca Math.toDegrees(Math.atan(slope / SLOPE_STREAM_RANGE_BLOCKS)), packPath(engine, biome), packPath(engine, region), - MapPickPath.explain(engine, view, worldX, worldZ) + MapPickPath.explain(engine, layer, worldX, worldZ) ); } diff --git a/core/src/main/java/art/arcane/iris/core/studio/map/MapLabel.java b/core/src/main/java/art/arcane/iris/core/studio/map/MapLabel.java index e593e24d8..386a7c355 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/map/MapLabel.java +++ b/core/src/main/java/art/arcane/iris/core/studio/map/MapLabel.java @@ -36,7 +36,7 @@ public record MapLabel(Kind kind, String key, String name, int color) { return new MapLabel(Kind.BIOME, biome.getLoadKey(), biome.getName(), biome.getColor(engine, colorType).getRGB() & RGB); } - static MapLabel of(Engine engine, IrisRegion region) { + public static MapLabel of(Engine engine, IrisRegion region) { return new MapLabel(Kind.REGION, region.getLoadKey(), region.getName(), region.getColor(engine.getComplex(), RenderType.REGION).getRGB() & RGB); } diff --git a/core/src/main/java/art/arcane/iris/core/studio/map/MapLayer.java b/core/src/main/java/art/arcane/iris/core/studio/map/MapLayer.java new file mode 100644 index 000000000..137610b8d --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/studio/map/MapLayer.java @@ -0,0 +1,65 @@ +/* + * 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.render.RenderType; +import art.arcane.iris.engine.object.world.region.IrisRegion; + +import java.util.Objects; + +/** + * What the map shows: a view, and in the region view optionally one region previewed everywhere, each spot getting + * the biome that region would place there. + * + * @param previewRegion the region previewed across the map, or null to show the world as it is + */ +public record MapLayer(MapView view, IrisRegion previewRegion) { + public MapLayer { + Objects.requireNonNull(view, "view"); + if (previewRegion != null && view != MapView.REGIONS) { + throw new IllegalArgumentException("Only the region view previews a region"); + } + } + + public static MapLayer of(MapView view) { + return new MapLayer(view, null); + } + + public static MapLayer preview(IrisRegion region) { + return new MapLayer(MapView.REGIONS, Objects.requireNonNull(region, "region")); + } + + public boolean previews() { + return previewRegion != null; + } + + /** Whether the layer can show the noise that picked each spot: the region view, its previews and the biome view. */ + public boolean hasPickNoise() { + return view == MapView.BIOMES || view == MapView.REGIONS; + } + + /** Whether each spot is labelled with its region rather than a biome; a preview labels the biomes. */ + boolean labelsRegions() { + return view.labelsRegions() && !previews(); + } + + RenderType colorType() { + return previews() ? RenderType.BIOME : view.colorType(); + } +} 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 new file mode 100644 index 000000000..0cb9c592a --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/studio/map/MapPickInspection.java @@ -0,0 +1,319 @@ +/* + * 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.IrisComplex; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.object.world.biome.InferredType; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.world.region.IrisRegion; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.EnumMap; +import java.util.IdentityHashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * How the noise picks the regions or biomes across an area of the map, measured on a grid of spots: for each noise, + * how its values in the area spread over the bands that pick each option, and how much ground each option gets + * there against its share of the noise. + */ +public final class MapPickInspection { + public static final int HISTOGRAM_BINS = 50; + static final int SAMPLES_PER_SIDE = 96; + private static final List PLACED_LISTS = List.of(InferredType.LAND, InferredType.SHORE, InferredType.SEA); + + private MapPickInspection() { + } + + /** @throws IllegalArgumentException for a view whose spots no noise picks, such as the height view */ + public static Inspection measure(Engine engine, MapLayer layer, Area area) { + if (layer.previews()) { + return measurePreview(engine, layer.previewRegion(), area); + } + return switch (layer.view()) { + case REGIONS -> measureRegions(engine, area); + case BIOMES -> measureBiomes(engine, area); + default -> throw new IllegalArgumentException("The " + layer.view().label() + " view has no picks to inspect"); + }; + } + + private static Inspection measureRegions(Engine engine, Area area) { + IrisComplex complex = engine.getComplex(); + if (complex.getFocusRegion() != null) { + return new Inspection("One region is focused", List.of()); + } + SpreadCounter regions = new SpreadCounter("Region noise", MapPickPath.regionBands(engine)); + area.forEachSpot((x, z) -> { + if (complex.getImageMapRuntime().sampleRegion(x, z) == null) { + regions.add(complex.getRegionStyleStream().get(x, z)); + } + }); + return new Inspection("Region noise by rarity", List.of(new Section(null, 1D, 0, List.of(regions.spread())))); + } + + // The previewed region owns every spot, so each spot's biome list is the one its surface needs. + private static Inspection measurePreview(Engine engine, IrisRegion region, Area area) { + IrisComplex complex = engine.getComplex(); + if (complex.getFocusBiome() != null) { + return measureFocusBiome(engine, MapView.REGIONS, area); + } + RegionSamples samples = new RegionSamples(engine, MapView.REGIONS, region); + area.forEachSpot((x, z) -> samples.add(complex.surfacePickAsIfIn(region, x, z).list(), x, z)); + return new Inspection("Biome noise by rarity", List.of(samples.section(1))); + } + + // Each region picks the base biomes on its ground from the list the continent chose there. + private static Inspection measureBiomes(Engine engine, Area area) { + IrisComplex complex = engine.getComplex(); + if (complex.getFocusBiome() != null) { + return measureFocusBiome(engine, MapView.BIOMES, area); + } + Map samplesByRegion = new IdentityHashMap<>(); + int[] picked = {0}; + area.forEachSpot((x, z) -> { + IrisRegion region = complex.getRegionStream().get(x, z); + if (region == null || complex.getImageMapRuntime().sampleBiome(x, z) != null) { + return; + } + picked[0]++; + samplesByRegion.computeIfAbsent(region, owner -> new RegionSamples(engine, MapView.BIOMES, owner)) + .add(complex.getBridgeStream().get(x, z), x, z); + }); + List
sections = samplesByRegion.values().stream() + .sorted(Comparator.comparingInt(RegionSamples::count).reversed()) + .map(samples -> samples.section(picked[0])) + .toList(); + return new Inspection("Each region's biome noise", sections); + } + + // A focused biome skips the regions and their lists: every spot starts at it. + private static Inspection measureFocusBiome(Engine engine, MapView view, Area area) { + IrisComplex complex = engine.getComplex(); + IrisBiome focus = complex.getFocusBiome(); + ChildCounters children = new ChildCounters(engine, view); + area.forEachSpot((x, z) -> children.add(ChildPicks.from(complex, focus, x, z))); + List spreads = children.mostSampledFirst(); + Section section = new Section(MapPickPath.biomeLabel(engine, view, focus), 1D, distinctOptions(spreads), spreads); + return new Inspection("Child noise by rarity", List.of(section)); + } + + private static int distinctOptions(List spreads) { + return (int) spreads.stream() + .flatMap(spread -> spread.rows().stream()) + .map(row -> row.option().key()) + .distinct() + .count(); + } + + /** The spots of one region in the area, and the noises that picked their biomes. */ + private static final class RegionSamples { + private final Engine engine; + private final MapView view; + private final IrisRegion region; + private final Map lists = new EnumMap<>(InferredType.class); + private final ChildCounters children; + private int count; + + private RegionSamples(Engine engine, MapView view, IrisRegion region) { + this.engine = engine; + this.view = view; + this.region = region; + this.children = new ChildCounters(engine, view); + } + + void add(InferredType list, double x, double z) { + count++; + IrisComplex complex = engine.getComplex(); + IrisBiome picked = complex.biomePicks(region, list).get(x, z); + if (picked == null) { + return; + } + lists.computeIfAbsent(list, this::listCounter).add(complex.biomePickNoise(region, list).get(x, z)); + children.add(ChildPicks.from(complex, picked, x, z)); + } + + int count() { + return count; + } + + Section section(int pickedSpots) { + List spreads = new ArrayList<>(); + for (InferredType list : PLACED_LISTS) { + SpreadCounter counter = lists.get(list); + if (counter != null) { + spreads.add(counter.spread()); + } + } + spreads.addAll(children.mostSampledFirst()); + double share = pickedSpots == 0 ? 0D : count / (double) pickedSpots; + return new Section(MapLabel.of(engine, region), share, distinctOptions(spreads), spreads); + } + + private SpreadCounter listCounter(InferredType list) { + String name = MapPickPath.listName(list); + String title = Character.toUpperCase(name.charAt(0)) + name.substring(1) + " biome noise"; + return new SpreadCounter(title, MapPickPath.biomeBands(engine, view, region, list)); + } + } + + /** The child noise of every parent the spots reach, each measured over the spots that reach it. */ + private static final class ChildCounters { + private final Engine engine; + private final MapView view; + private final Map byParent = new LinkedHashMap<>(); + + private ChildCounters(Engine engine, MapView view) { + this.engine = engine; + this.view = view; + } + + void add(List picks) { + for (ChildPicks.ChildPick pick : picks) { + byParent.computeIfAbsent(pick.parent().getLoadKey(), parent -> counterOf(pick)).add(pick.noise()); + } + } + + List mostSampledFirst() { + return byParent.values().stream() + .sorted(Comparator.comparingLong(SpreadCounter::samples).reversed()) + .map(SpreadCounter::spread) + .toList(); + } + + private SpreadCounter counterOf(ChildPicks.ChildPick pick) { + return new SpreadCounter(pick.parent().getName() + " child noise", + MapPickPath.slotBands(pick.slots(), slot -> MapPickPath.biomeLabel(engine, view, slot))); + } + } + + /** Counts one noise's values into its histogram and into the band each value picks. */ + private static final class SpreadCounter { + private final String title; + private final List bands; + private final long[] histogram = new long[HISTOGRAM_BINS]; + private final long[] samplesByBand; + private long samples; + + private SpreadCounter(String title, List bands) { + this.title = title; + this.bands = bands; + this.samplesByBand = new long[bands.size()]; + } + + void add(double noise) { + if (bands.isEmpty() || !Double.isFinite(noise)) { + return; + } + samples++; + histogram[Math.clamp((long) (noise * HISTOGRAM_BINS), 0, HISTOGRAM_BINS - 1)]++; + samplesByBand[bandIndexOf(noise)]++; + } + + long samples() { + return samples; + } + + // Every option once, with its bands' widths and spots added up, in the order the noise meets them. + Spread spread() { + Map rows = new LinkedHashMap<>(); + for (int index = 0; index < bands.size(); index++) { + MapPickPath.PickBand band = bands.get(index); + Row row = new Row(band.option(), band.to() - band.from(), share(samplesByBand[index])); + rows.merge(band.option().key(), row, Row::plus); + } + return new Spread(title, bands, histogram.clone(), samples, List.copyOf(rows.values())); + } + + private double share(long count) { + return samples == 0 ? 0D : count / (double) samples; + } + + // The generator gives values below 0 the first option and values above 1 the last, as these bands do. + private int bandIndexOf(double noise) { + for (int index = 0; index < bands.size(); index++) { + if (noise <= bands.get(index).to()) { + return index; + } + } + return bands.size() - 1; + } + } + + /** A rectangle of the world, sampled at the centres of a {@value #SAMPLES_PER_SIDE}² grid. */ + public record Area(double minX, double minZ, double maxX, double maxZ) { + public Area { + if (!Double.isFinite(minX) || !Double.isFinite(minZ) || !Double.isFinite(maxX) || !Double.isFinite(maxZ) + || maxX <= minX || maxZ <= minZ) { + throw new IllegalArgumentException("An area needs finite corners, the second beyond the first"); + } + } + + void forEachSpot(SpotVisitor visitor) { + double stepX = (maxX - minX) / SAMPLES_PER_SIDE; + double stepZ = (maxZ - minZ) / SAMPLES_PER_SIDE; + for (int row = 0; row < SAMPLES_PER_SIDE; row++) { + for (int column = 0; column < SAMPLES_PER_SIDE; column++) { + visitor.visit(minX + (column + 0.5D) * stepX, minZ + (row + 0.5D) * stepZ); + } + } + } + } + + @FunctionalInterface + interface SpotVisitor { + void visit(double x, double z); + } + + /** @param detail what the picks in the area are, in a few words */ + public record Inspection(String detail, List
sections) { + } + + /** + * The picks on one region's ground, or on all of it in the region view. + * + * @param region the region, or the focused biome; null in the region view, where the regions themselves are picked + * @param share how much of the area's picked ground the region holds + * @param biomeCount how many biomes its noises can pick here + */ + public record Section(MapLabel region, double share, int biomeCount, List spreads) { + } + + /** + * One noise in the area. + * + * @param histogram how many spots had a value in each of {@value #HISTOGRAM_BINS} equal steps from 0 to 1 + * @param rows every option once, in the order the noise meets it + */ + public record Spread(String title, List bands, long[] histogram, long samples, List rows) { + } + + /** + * @param weight how much of the noise from 0 to 1 picks the option + * @param inView how much of the area's values pick it + */ + public record Row(MapLabel option, double weight, double inView) { + Row plus(Row other) { + return new Row(option, weight + other.weight, inView + other.inView); + } + } +} diff --git a/core/src/main/java/art/arcane/iris/core/studio/map/MapPickNoise.java b/core/src/main/java/art/arcane/iris/core/studio/map/MapPickNoise.java new file mode 100644 index 000000000..f58d644ec --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/studio/map/MapPickNoise.java @@ -0,0 +1,103 @@ +/* + * 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.IrisComplex; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.object.world.biome.InferredType; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.world.region.IrisRegion; + +/** + * The noise value that settled each spot's pick, from 0 to 1: the region noise in the region view; in the biome view + * and a region preview the last noise that picked the biome, its list's or its last child's. NaN where nothing was + * picked, as on an image map. + */ +final class MapPickNoise { + private MapPickNoise() { + } + + /** The pick noise of a layer that previews nothing. */ + static float[] sample(Engine engine, MapLayer layer, TileGrid grid) { + NoiseAt noise = noiseOf(engine, layer); + return everyCell(grid, (cell, x, z) -> noise.at(x, z)); + } + + /** The pick noise of a region preview, from the surface picks the tile already made for each of its cells. */ + static float[] samplePreview(Engine engine, IrisRegion region, TileGrid grid, IrisComplex.BiomePick[] picks) { + IrisComplex complex = engine.getComplex(); + IrisBiome focus = complex.getFocusBiome(); + if (focus != null) { + return everyCell(grid, (cell, x, z) -> ChildPicks.settlingNoise(complex, focus, x, z, Double.NaN)); + } + return everyCell(grid, (cell, x, z) -> listNoise(complex, region, picks[cell].list(), x, z)); + } + + private static float[] everyCell(TileGrid grid, CellNoise noise) { + int size = grid.size(); + float[] cells = new float[size * size]; + for (int gridZ = 0; gridZ < size; gridZ++) { + MapTileRenderer.checkCancelled(grid.cancelled()); + double worldZ = grid.worldZ(gridZ); + for (int gridX = 0; gridX < size; gridX++) { + int cell = gridZ * size + gridX; + cells[cell] = (float) noise.at(cell, grid.worldX(gridX), worldZ); + } + } + return cells; + } + + private static NoiseAt noiseOf(Engine engine, MapLayer layer) { + IrisComplex complex = engine.getComplex(); + if (layer.view() == MapView.REGIONS) { + return (x, z) -> complex.getFocusRegion() != null || complex.getImageMapRuntime().sampleRegion(x, z) != null + ? Double.NaN + : complex.getRegionStyleStream().get(x, z); + } + return (x, z) -> baseBiomeNoise(complex, x, z); + } + + private static double baseBiomeNoise(IrisComplex complex, double x, double z) { + IrisBiome focus = complex.getFocusBiome(); + if (focus != null) { + return ChildPicks.settlingNoise(complex, focus, x, z, Double.NaN); + } + if (complex.getImageMapRuntime().sampleBiome(x, z) != null) { + return Double.NaN; + } + IrisRegion region = complex.getRegionStream().get(x, z); + return region == null ? Double.NaN : listNoise(complex, region, complex.getBridgeStream().get(x, z), x, z); + } + + private static double listNoise(IrisComplex complex, IrisRegion region, InferredType list, double x, double z) { + IrisBiome picked = complex.biomePicks(region, list).get(x, z); + double noise = complex.biomePickNoise(region, list).get(x, z); + return picked == null ? Double.NaN : ChildPicks.settlingNoise(complex, picked, x, z, noise); + } + + @FunctionalInterface + private interface NoiseAt { + double at(double x, double z); + } + + @FunctionalInterface + private interface CellNoise { + double at(int cell, double x, double z); + } +} 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 4c2acb3f7..bb21b6cfa 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 @@ -29,7 +29,6 @@ import art.arcane.iris.engine.object.world.region.IrisRegion; import java.util.ArrayList; import java.util.List; import java.util.Locale; -import java.util.Objects; import java.util.function.Function; /** @@ -40,7 +39,10 @@ public final class MapPickPath { private MapPickPath() { } - public static List explain(Engine engine, MapView view, double x, double z) { + public static List explain(Engine engine, MapLayer layer, double x, double z) { + if (layer.previews()) { + return explainPreview(engine, layer.previewRegion(), x, z); + } IrisComplex complex = engine.getComplex(); IrisRegion region = complex.getRegionStream().get(x, z); List path = new ArrayList<>(); @@ -48,6 +50,7 @@ public final class MapPickPath { return path; } path.add(regionStep(engine, region, x, z)); + MapView view = layer.view(); switch (view) { case LAND_BIOMES -> addListStep(path, engine, view, region, InferredType.LAND, x, z); case SEA_BIOMES -> addListStep(path, engine, view, region, InferredType.SEA, x, z); @@ -57,6 +60,25 @@ public final class MapPickPath { return path; } + // The previewed region owns every spot; its list is the one the spot's surface needs, then children replace it. + private static List explainPreview(Engine engine, IrisRegion region, double x, double z) { + IrisComplex complex = engine.getComplex(); + List path = new ArrayList<>(); + path.add(PickStep.chosen(Kind.PREVIEW, MapLabel.of(engine, region))); + IrisBiome focus = complex.getFocusBiome(); + if (focus != null) { + path.add(PickStep.chosen(Kind.FOCUS, biomeLabel(engine, MapView.REGIONS, focus))); + addChildSteps(path, engine, MapView.REGIONS, focus, x, z); + return path; + } + InferredType list = complex.surfacePickAsIfIn(region, x, z).list(); + IrisBiome picked = addListStep(path, engine, MapView.REGIONS, region, list, x, z); + if (picked != null) { + addChildSteps(path, engine, MapView.REGIONS, picked, x, z); + } + return path; + } + private static PickStep regionStep(Engine engine, IrisRegion region, double x, double z) { IrisComplex complex = engine.getComplex(); if (complex.getFocusRegion() != null) { @@ -65,10 +87,19 @@ public final class MapPickPath { if (complex.getImageMapRuntime().sampleRegion(x, z) != null) { return PickStep.chosen(Kind.IMAGE_MAP, MapLabel.of(engine, region)); } - List regions = engine.getData().getRegionLoader().loadAll(engine.getDimension().getRegions()); double noise = complex.getRegionStyleStream().get(x, z); - return new PickStep(Kind.REGION, MapLabel.of(engine, region), null, null, noise, - rarityBands(regions, candidate -> MapLabel.of(engine, candidate))); + return new PickStep(Kind.REGION, MapLabel.of(engine, region), null, null, noise, regionBands(engine)); + } + + /** Each of the dimension's regions' share of the region noise. */ + static List regionBands(Engine engine) { + List regions = engine.getData().getRegionLoader().loadAll(engine.getDimension().getRegions()); + return rarityBands(regions, region -> MapLabel.of(engine, region)); + } + + /** Each biome of the region's list of this type's share of the list's noise; empty when the list is. */ + static List biomeBands(Engine engine, MapView view, IrisRegion region, InferredType type) { + return rarityBands(engine.getComplex().pickableBiomes(region, type), biome -> biomeLabel(engine, view, biome)); } // The base biome: the noise picks from the land or sea list the continent noise chose, then children replace it. @@ -101,41 +132,19 @@ public final class MapPickPath { } double noise = complex.biomePickNoise(region, type).get(x, z); IrisBiome picked = IRare.pick(options, noise); - path.add(new PickStep(Kind.BIOME, biomeLabel(engine, view, picked), type.name().toLowerCase(Locale.ROOT), null, + path.add(new PickStep(Kind.BIOME, biomeLabel(engine, view, picked), listName(type), null, noise, rarityBands(options, option -> biomeLabel(engine, view, option)))); return picked; } - // A parent that keeps the spot ends the walk: every level below would read the same noise and keep it again. private static void addChildSteps(List path, Engine engine, MapView view, IrisBiome biome, double x, double z) { - IrisComplex complex = engine.getComplex(); - IrisBiome parent = biome; - for (int level = 0; level < IrisComplex.CHILD_PICK_LEVELS && !parent.getChildren().isEmpty(); level++) { - List slots = complex.childSlots(parent); - if (slots.isEmpty()) { - return; - } - double noise = complex.childNoise(parent).noiseFast2D(x, z); - IrisBiome picked = slots.get(slotIndex(noise, slots.size())).withInferredType(parent.getInferredType()); - boolean kept = sameBiome(picked, parent); - path.add(new PickStep(Kind.CHILD, biomeLabel(engine, view, picked), null, kept ? null : parent.getName(), - noise, slotBands(slots, option -> biomeLabel(engine, view, option)))); - if (kept) { - return; - } - parent = picked; + for (ChildPicks.ChildPick pick : ChildPicks.from(engine.getComplex(), biome, x, z)) { + path.add(new PickStep(Kind.CHILD, biomeLabel(engine, view, pick.picked()), null, + pick.kept() ? null : pick.parent().getName(), pick.noise(), + slotBands(pick.slots(), option -> biomeLabel(engine, view, option)))); } } - /** The slot the child noise picks, rounded the way {@code CNG.fit2D} rounds. */ - static int slotIndex(double noise, int slotCount) { - if (slotCount == 1) { - return 0; - } - long rounded = Math.round(noise * (slotCount - 1)); - return (int) Math.clamp(rounded, 0, slotCount - 1); - } - /** Each option's share of the noise, 1 / rarity wide, in the order {@link IRare#pick} walks them. */ static List rarityBands(List options, Function label) { double total = options.stream().mapToDouble(option -> 1D / IRare.get(option)).sum(); @@ -168,11 +177,12 @@ public final class MapPickPath { return bands; } - private static boolean sameBiome(IrisBiome first, IrisBiome second) { - return Objects.equals(first.getLoadKey(), second.getLoadKey()); + /** A biome list's name as the studio shows it, such as {@code land}. */ + static String listName(InferredType type) { + return type.name().toLowerCase(Locale.ROOT); } - private static MapLabel biomeLabel(Engine engine, MapView view, IrisBiome biome) { + static MapLabel biomeLabel(Engine engine, MapView view, IrisBiome biome) { return MapLabel.of(engine, biome, view == MapView.REGIONS ? RenderType.BIOME : view.colorType()); } @@ -186,7 +196,9 @@ public final class MapPickPath { /** The pack's image map set it. */ IMAGE_MAP, /** The studio focuses on one region or biome, so nothing was picked. */ - FOCUS + FOCUS, + /** The studio previews one region everywhere, so nothing picked the region. */ + PREVIEW } /** 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 6abf98080..7a5c5641c 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 @@ -28,12 +28,20 @@ import java.util.List; * @param subjects the index in {@code labels} of each cell's biome, or its region in the region view; * {@link #NO_LABEL} where the stream had none * @param regions the index in {@code labels} of each cell's region; the same array as {@code subjects} in the region view - * @param heights each cell's terrain height, or null when it was not asked for + * @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 */ public record MapTile(int size, double blocksPerPixel, MapLabel.Kind subjectKind, List labels, - short[] subjects, short[] regions, float[] heights) { + short[] subjects, short[] regions, float[] heights, float[] pickNoise) { public static final short NO_LABEL = -1; + /** What a tile can carry besides its labels. */ + public enum Extra { + HEIGHTS, + PICK_NOISE + } + public int gridSize() { return size + 2; } 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 86bc08c2b..ff8465980 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 @@ -26,10 +26,12 @@ import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.util.project.stream.ProceduralStream; import java.util.ArrayList; +import java.util.Arrays; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Set; import java.util.concurrent.CancellationException; import java.util.function.BooleanSupplier; @@ -44,39 +46,81 @@ public final class MapTileRenderer { /** * The square of {@code size} pixels whose top left pixel samples ({@code startX}, {@code startZ}). * - * @param withHeights also sample terrain heights, for shading; the height view always has them + * @param extras what to sample besides the labels; the height view always has heights, and only a layer that + * {@linkplain MapLayer#hasPickNoise() has pick noise} gets it * @throws CancellationException as soon as {@code cancelled} answers true */ - public MapTile render(MapView view, double startX, double startZ, double blocksPerPixel, int size, - boolean withHeights, BooleanSupplier cancelled) { + public MapTile render(MapLayer layer, double startX, double startZ, double blocksPerPixel, int size, + Set extras, BooleanSupplier cancelled) { if (!Double.isFinite(startX) || !Double.isFinite(startZ) || !Double.isFinite(blocksPerPixel) || blocksPerPixel <= 0D) { throw new IllegalArgumentException("Map tile coordinates and scale must be finite"); } if (size < 1) { throw new IllegalArgumentException("Map tile size must be positive"); } - Objects.requireNonNull(view, "view"); + Objects.requireNonNull(layer, "layer"); + Objects.requireNonNull(extras, "extras"); Objects.requireNonNull(cancelled, "cancelled"); checkCancelled(cancelled); TileGrid grid = new TileGrid(size + 2, startX - blocksPerPixel, startZ - blocksPerPixel, blocksPerPixel, cancelled); - TileLabels labels = new TileLabels(engine, view.colorType()); - short[] regions = sampleRegions(grid, labels); - short[] subjects = view.labelsRegions() ? regions : sampleBiomes(grid, labels, view.biomeStream(engine.getComplex())); - float[] heights = withHeights || view == MapView.HEIGHT - ? new HeightLattice(grid, engine.getComplex().getHeightStream()).interpolatedHeights() + return layer.previews() + ? renderPreview(layer, grid, blocksPerPixel, extras) + : renderView(layer, grid, blocksPerPixel, extras); + } + + private MapTile renderView(MapLayer layer, TileGrid grid, double blocksPerPixel, Set extras) { + TileLabels labels = new TileLabels(engine, layer.colorType()); + IrisComplex complex = engine.getComplex(); + ProceduralStream regionStream = complex.getRegionStream(); + 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[] pickNoise = extras.contains(MapTile.Extra.PICK_NOISE) && layer.hasPickNoise() + ? MapPickNoise.sample(engine, layer, grid) : null; - MapLabel.Kind subjectKind = view.labelsRegions() ? MapLabel.Kind.REGION : MapLabel.Kind.BIOME; - return new MapTile(size, blocksPerPixel, subjectKind, labels.labels(), subjects, regions, heights); + 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); } - private static short[] sampleRegions(TileGrid grid, TileLabels labels) { - ProceduralStream stream = labels.engine.getComplex().getRegionStream(); - return everyCell(grid, (x, z) -> labels.indexOf(stream.get(x, z))); + // Each spot's surface biome hangs on its height, which the lattice gives at a fraction of the exact heights' cost. + // Only a coastline pixel whose smoothed height lands across the shore line can show another biome than its hover. + private MapTile renderPreview(MapLayer layer, TileGrid grid, double blocksPerPixel, Set extras) { + TileLabels labels = new TileLabels(engine, layer.colorType()); + IrisRegion region = layer.previewRegion(); + float[] heights = latticeHeights(grid); + IrisComplex.BiomePick[] picks = previewPicks(grid, region, heights); + short[] subjects = new short[picks.length]; + for (int cell = 0; cell < picks.length; cell++) { + subjects[cell] = labels.indexOf(picks[cell].biome()); + } + short[] regions = new short[picks.length]; + Arrays.fill(regions, labels.indexOf(region)); + float[] pickNoise = extras.contains(MapTile.Extra.PICK_NOISE) + ? 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); } - private static short[] sampleBiomes(TileGrid grid, TileLabels labels, ProceduralStream stream) { - return everyCell(grid, (x, z) -> labels.indexOf(stream.get(x, z))); + private IrisComplex.BiomePick[] previewPicks(TileGrid grid, IrisRegion region, float[] heights) { + IrisComplex complex = engine.getComplex(); + int size = grid.size(); + IrisComplex.BiomePick[] picks = new IrisComplex.BiomePick[size * size]; + for (int gridZ = 0; gridZ < size; gridZ++) { + checkCancelled(grid.cancelled()); + double worldZ = grid.worldZ(gridZ); + for (int gridX = 0; gridX < size; gridX++) { + int cell = gridZ * size + gridX; + picks[cell] = complex.surfacePickAsIfIn(region, grid.worldX(gridX), worldZ, heights[cell]); + } + } + return picks; + } + + private float[] latticeHeights(TileGrid grid) { + return new HeightLattice(grid, engine.getComplex().getHeightStream()).interpolatedHeights(); } // A fractured child style speckles finer than any square a few samples could vouch for, so every cell is asked. diff --git a/core/src/main/java/art/arcane/iris/engine/IrisComplex.java b/core/src/main/java/art/arcane/iris/engine/IrisComplex.java index dc648354c..9170a9cf3 100644 --- a/core/src/main/java/art/arcane/iris/engine/IrisComplex.java +++ b/core/src/main/java/art/arcane/iris/engine/IrisComplex.java @@ -65,8 +65,8 @@ import java.util.concurrent.atomic.AtomicLong; import java.util.function.BiFunction; @Data -@EqualsAndHashCode(exclude = {"data", "gridBoundsCache", "frozenInterpolators", "frozenGenerators", "inferredBiomeStreams", "inferredPickNoiseStreams", "imageMapRuntime"}) -@ToString(exclude = {"data", "gridBoundsCache", "frozenInterpolators", "frozenGenerators", "inferredBiomeStreams", "inferredPickNoiseStreams", "imageMapRuntime"}) +@EqualsAndHashCode(exclude = {"data", "gridBoundsCache", "frozenInterpolators", "frozenGenerators", "preparedRegions", "inferredBiomeStreams", "inferredPickNoiseStreams", "imageMapRuntime"}) +@ToString(exclude = {"data", "gridBoundsCache", "frozenInterpolators", "frozenGenerators", "preparedRegions", "inferredBiomeStreams", "inferredPickNoiseStreams", "imageMapRuntime"}) public class IrisComplex implements DataProvider { private static final NoiseBounds ZERO_NOISE_BOUNDS = new NoiseBounds(0D, 0D); private static final AtomicLong lastBoundsFailureLog = new AtomicLong(0L); @@ -96,6 +96,8 @@ public class IrisComplex implements DataProvider { @Getter(AccessLevel.NONE) private final transient IrisGenerator[][] frozenGenerators; @Getter(AccessLevel.NONE) + private final transient List preparedRegions; + @Getter(AccessLevel.NONE) private final transient Map>> inferredBiomeStreams; @Getter(AccessLevel.NONE) private final transient Map>> inferredPickNoiseStreams; @@ -152,7 +154,7 @@ public class IrisComplex implements DataProvider { focusBiome = engine.getFocus(); focusRegion = engine.getFocusRegion(); Map> inferredStreams = new HashMap<>(); - KList preparedRegions = new KList<>(); + KList regionsToPrepare = new KList<>(); if (focusBiome != null) { focusBiome = focusBiome.withInferredType(InferredType.LAND); @@ -161,7 +163,7 @@ public class IrisComplex implements DataProvider { //@builder if (focusRegion != null) { - prepareInferredBiomes(focusRegion, preparedRegions); + prepareInferredBiomes(focusRegion, regionsToPrepare); focusRegion.getAllBiomes(this).forEach(this::registerGenerators); } else { engine.getDimension().getRegions().forEach(regionKey -> { @@ -169,15 +171,16 @@ public class IrisComplex implements DataProvider { if (region == null) { return; } - prepareInferredBiomes(region, preparedRegions); + prepareInferredBiomes(region, regionsToPrepare); region.getAllBiomes(this).forEach(this::registerGenerators); }); for (IrisRegion region : imageMapRuntime.getMappedRegions()) { - prepareInferredBiomes(region, preparedRegions); + prepareInferredBiomes(region, regionsToPrepare); region.getAllBiomes(this).forEach(this::registerGenerators); } imageMapRuntime.getMappedBiomes().forEach(this::registerGenerators); } + preparedRegions = List.copyOf(regionsToPrepare); inferredPickNoiseStreams = compileInferredBiomeStreams( preparedRegions, (region, inferredType) -> compileInferredPickNoise(engine, region, inferredType) @@ -226,21 +229,21 @@ public class IrisComplex implements DataProvider { regionIDStream = regionIdentityStream.convertCached((i) -> new UUID(Double.doubleToLongBits(i), String.valueOf(i * 38445).hashCode() * 3245556666L)); caveBiomeStream = regionStream.contextInjecting(engine, (c, x, z) -> c.getRegion().get(x, z)) - .convert((r) -> createInferredBiomeStream(r, InferredType.CAVE)) + .convert((r) -> biomePicks(r,InferredType.CAVE)) .convertAware2D(ProceduralStream::get).cache2D("caveBiomeStream", engine, cacheSize); inferredStreams.put(InferredType.CAVE, caveBiomeStream); landBiomeStream = regionStream.contextInjecting(engine, (c, x, z) -> c.getRegion().get(x, z)) - .convert((r) -> createInferredBiomeStream(r, InferredType.LAND)) + .convert((r) -> biomePicks(r,InferredType.LAND)) .convertAware2D(ProceduralStream::get) .cache2D("landBiomeStream", engine, cacheSize); inferredStreams.put(InferredType.LAND, landBiomeStream); seaBiomeStream = regionStream.contextInjecting(engine, (c, x, z) -> c.getRegion().get(x, z)) - .convert((r) -> createInferredBiomeStream(r, InferredType.SEA)) + .convert((r) -> biomePicks(r,InferredType.SEA)) .convertAware2D(ProceduralStream::get) .cache2D("seaBiomeStream", engine, cacheSize); inferredStreams.put(InferredType.SEA, seaBiomeStream); shoreBiomeStream = regionStream.contextInjecting(engine, (c, x, z) -> c.getRegion().get(x, z)) - .convert((r) -> createInferredBiomeStream(r, InferredType.SHORE)) + .convert((r) -> biomePicks(r,InferredType.SHORE)) .convertAware2D(ProceduralStream::get).cache2D("shoreBiomeStream", engine, cacheSize); inferredStreams.put(InferredType.SHORE, shoreBiomeStream); bridgeStream = focusBiome != null ? ProceduralStream.of((x, z) -> focusBiome.getInferredType(), @@ -316,6 +319,52 @@ public class IrisComplex implements DataProvider { return getHeight(engine, worldX, worldZ, engine.getSeedManager().getHeight()); } + /** The regions this world picks biomes for: the dimension's and the image map's, or only the focused one. */ + public List preparedRegions() { + return preparedRegions; + } + + /** The prepared region with this key, or null when this world picks no biomes for it. */ + public IrisRegion preparedRegion(String regionKey) { + for (IrisRegion region : preparedRegions) { + if (Objects.equals(region.getLoadKey(), regionKey)) { + return region; + } + } + return null; + } + + /** + * The surface biome a spot would get if it belonged to the region, for previewing one region across the map: the + * continent picks the biome list, the terrain height may move the spot to another list, then children replace it. + */ + public BiomePick surfacePickAsIfIn(IrisRegion region, double x, double z) { + return surfacePickAsIfIn(region, x, z, heightStream.get(x, z)); + } + + /** {@link #surfacePickAsIfIn(IrisRegion, double, double)} on terrain of a height the caller already has. */ + public BiomePick surfacePickAsIfIn(IrisRegion region, double x, double z, double terrainHeight) { + if (focusBiome != null) { + return new BiomePick(baseBiomeStream.get(x, z), focusBiome.getInferredType()); + } + InferredType continentType = bridgeStream.get(x, z); + IrisBiome listPick = biomePicks(region, continentType).get(x, z); + if (listPick == null) { + return new BiomePick(null, continentType); + } + IrisBiome base = implode(listPick, x, z); + IrisBiome surface = resolveSurfaceBiome(terrainHeight, base, region, x, z, fluidHeight, + biomePicks(region, InferredType.LAND), biomePicks(region, InferredType.SEA), biomePicks(region, InferredType.SHORE)); + if (surface == null || surface == base) { + return new BiomePick(base, continentType); + } + return new BiomePick(implode(surface, x, z), surface.getInferredType()); + } + + /** A spot's biome and the region's biome list it was picked from. */ + public record BiomePick(IrisBiome biome, InferredType list) { + } + private IrisRegion findRegion(IrisBiome focus, Engine engine) { for (IrisRegion i : engine.getDimension().getAllRegions(engine)) { if (i.getAllBiomeIds().contains(focus.getLoadKey())) { @@ -504,10 +553,8 @@ public class IrisComplex implements DataProvider { preparedRegions.add(region); } - private ProceduralStream createInferredBiomeStream( - IrisRegion region, - InferredType inferredType - ) { + /** The biome the region's list of this type picks at each spot, before children replace it. */ + public ProceduralStream biomePicks(IrisRegion region, InferredType inferredType) { return preparedInferredBiomeStream(inferredBiomeStreams, region, inferredType); } 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 d5d14429f..5ca00049f 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 @@ -166,6 +166,8 @@ public class StudioBridgeTest { JsonObject firstStep = hover.getAsJsonArray("pickPath").get(0).getAsJsonObject(); assertEquals("FOCUS", firstStep.get("kind").getAsString()); assertEquals("temperate", firstStep.getAsJsonObject("picked").get("key").getAsString()); + assertTrue("nothing picked the focused region, which the studio reads as a null noise", + firstStep.has("noise") && firstStep.get("noise").isJsonNull()); } @Test @@ -175,6 +177,17 @@ public class StudioBridgeTest { assertEquals(400, response.statusCode()); } + @Test + public void onlyTheRegionViewPreviewsARegionAndOnlyOneTheWorldPrepared() throws Exception { + assertEquals(400, get("hover?view=biomes&preview=temperate&x=0&z=0").statusCode()); + assertEquals(400, get("hover?view=regions&preview=nowhere&x=0&z=0").statusCode()); + } + + @Test + public void theHeightViewHasNoPicksToInspect() throws Exception { + assertEquals(400, get("picks?view=height&minX=0&minZ=0&maxX=10&maxZ=10").statusCode()); + } + @Test public void aWorldWithoutAnEngineIsUnavailableUntilItHasOneAgain() throws Exception { Engine engine = running.getAndSet(null); 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 new file mode 100644 index 000000000..3b0b39359 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/studio/map/MapPickInspectionTest.java @@ -0,0 +1,98 @@ +package art.arcane.iris.core.studio.map; + +import art.arcane.iris.engine.IrisComplex; +import art.arcane.iris.engine.object.world.biome.InferredType; +import org.junit.Test; + +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; +import static org.mockito.ArgumentMatchers.anyDouble; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + +public class MapPickInspectionTest { + private static final MapPickInspection.Area AREA = new MapPickInspection.Area(-100D, -100D, 100D, 100D); + private static final long SPOTS = (long) MapPickInspection.SAMPLES_PER_SIDE * MapPickInspection.SAMPLES_PER_SIDE; + + private final PickedWorld world = new PickedWorld(); + + @Test + public void theRegionViewMeasuresTheRegionNoiseAgainstEachRegionsShare() { + MapPickInspection.Inspection inspection = measure(MapLayer.of(MapView.REGIONS)); + + MapPickInspection.Section section = inspection.sections().getFirst(); + assertNull("the regions themselves are picked, not one region's biomes", section.region()); + MapPickInspection.Spread regions = section.spreads().getFirst(); + assertEquals(SPOTS, regions.samples()); + assertEquals("every spot reads 0.9", SPOTS, regions.histogram()[45]); + assertRow(regions.rows().get(0), "warm", 0.75D, 0D); + assertRow(regions.rows().get(1), "dry", 0.25D, 1D); + } + + @Test + public void theBiomeViewMeasuresEachRegionsListAndEveryChildNoiseItsSpotsReach() { + MapPickInspection.Inspection inspection = measure(MapLayer.of(MapView.BIOMES)); + + assertEquals(1, inspection.sections().size()); + MapPickInspection.Section dry = inspection.sections().getFirst(); + assertEquals("dry", dry.region().key()); + assertEquals(1D, dry.share(), 0D); + assertEquals("plains, forest, meadow and glade", 4, dry.biomeCount()); + assertEquals(List.of("Land biome noise", "Plains child noise", "Meadow child noise"), + dry.spreads().stream().map(MapPickInspection.Spread::title).toList()); + assertRow(dry.spreads().get(0).rows().get(0), "plains", 0.5D, 1D); + MapPickInspection.Spread plainsChildren = dry.spreads().get(1); + assertEquals("meadow's slot and plains' two slots are two bands", 2, plainsChildren.rows().size()); + assertRow(plainsChildren.rows().get(0), "meadow", 0.25D, 1D); + } + + @Test + public void aPreviewMeasuresThePreviewedRegionsListsEverywhere() { + IrisComplex complex = world.complex; + var landBiomes = complex.pickableBiomes(world.dry, InferredType.LAND); + var landNoise = complex.biomePickNoise(world.dry, InferredType.LAND); + var landPicks = complex.biomePicks(world.dry, InferredType.LAND); + when(complex.surfacePickAsIfIn(eq(world.warm), anyDouble(), anyDouble())) + .thenReturn(new IrisComplex.BiomePick(world.meadow, InferredType.LAND)); + when(complex.pickableBiomes(world.warm, InferredType.LAND)).thenReturn(landBiomes); + when(complex.biomePickNoise(world.warm, InferredType.LAND)).thenReturn(landNoise); + when(complex.biomePicks(world.warm, InferredType.LAND)).thenReturn(landPicks); + + MapPickInspection.Section section = measure(MapLayer.preview(world.warm)).sections().getFirst(); + + assertEquals("warm", section.region().key()); + assertEquals(SPOTS, section.spreads().getFirst().samples()); + } + + @Test + public void theHeightViewHasNoPicks() { + assertThrows(IllegalArgumentException.class, () -> measure(MapLayer.of(MapView.HEIGHT))); + } + + @Test + public void anAreaNeedsItsSecondCornerBeyondItsFirst() { + assertThrows(IllegalArgumentException.class, () -> new MapPickInspection.Area(0D, 0D, 0D, 10D)); + } + + @Test + public void theBiomeNoiseSettlesAtTheLastChildPick() { + TileGrid grid = new TileGrid(2, 0D, 0D, 1D, () -> false); + + float[] noise = MapPickNoise.sample(world.engine, MapLayer.of(MapView.BIOMES), grid); + + assertEquals("meadow kept the spot at 0.8", 0.8F, noise[3], 1e-6F); + } + + private MapPickInspection.Inspection measure(MapLayer layer) { + return MapPickInspection.measure(world.engine, layer, AREA); + } + + private static void assertRow(MapPickInspection.Row row, String key, double weight, double inView) { + assertEquals(key, row.option().key()); + assertEquals(weight, row.weight(), 1e-9); + assertEquals(inView, row.inView(), 1e-9); + } +} diff --git a/core/src/test/java/art/arcane/iris/core/studio/map/MapPickPathTest.java b/core/src/test/java/art/arcane/iris/core/studio/map/MapPickPathTest.java index 1e72d7256..3148986dc 100644 --- a/core/src/test/java/art/arcane/iris/core/studio/map/MapPickPathTest.java +++ b/core/src/test/java/art/arcane/iris/core/studio/map/MapPickPathTest.java @@ -1,84 +1,27 @@ package art.arcane.iris.core.studio.map; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.loader.ResourceLoader; import art.arcane.iris.engine.IrisComplex; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.render.RenderType; -import art.arcane.iris.engine.image.IrisImageMapRuntime; import art.arcane.iris.engine.object.world.biome.InferredType; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.engine.object.world.region.IrisRegion; -import art.arcane.iris.util.project.noise.CNG; -import art.arcane.iris.util.project.stream.ProceduralStream; -import art.arcane.volmlib.util.collection.KList; -import org.junit.Before; import org.junit.Test; -import java.awt.Color; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyDouble; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class MapPickPathTest { private static final double X = 12D; private static final double Z = -7D; - private final Engine engine = mock(Engine.class); - private final IrisComplex complex = mock(IrisComplex.class); - private final IrisBiome plains = biome("plains", "Plains", 1); - private final IrisBiome forest = biome("forest", "Forest", 1); - private final IrisBiome meadow = biome("meadow", "Meadow", 1); - private final IrisBiome glade = biome("glade", "Glade", 1); - private IrisRegion dry; - - /** - * A dry region (rarity 3, so the last quarter of the region noise) picked at 0.9; its land list picks plains at 0.2; - * plains' child noise at 0.1 rounds to its first slot, meadow; meadow's at 0.8 rounds to its last slot, itself. - */ - @Before - public void pickTheWayDown() { - IrisRegion warm = region("warm", "Warm", 1); - dry = region("dry", "Dry", 3); - when(engine.getComplex()).thenReturn(complex); - IrisDimension dimension = mock(IrisDimension.class); - when(dimension.getRegions()).thenReturn(new KList<>(List.of("warm", "dry"))); - when(engine.getDimension()).thenReturn(dimension); - IrisData data = mock(IrisData.class); - @SuppressWarnings("unchecked") - ResourceLoader regionLoader = mock(ResourceLoader.class); - when(regionLoader.loadAll(any(KList.class))).thenReturn(new KList<>(List.of(warm, dry))); - when(data.getRegionLoader()).thenReturn(regionLoader); - when(engine.getData()).thenReturn(data); - IrisImageMapRuntime noImageMap = mock(IrisImageMapRuntime.class); - when(complex.getImageMapRuntime()).thenReturn(noImageMap); - - ProceduralStream regions = stream(dry); - ProceduralStream regionNoise = stream(0.9D); - ProceduralStream continents = stream(InferredType.LAND); - ProceduralStream landNoise = stream(0.2D); - when(complex.getRegionStream()).thenReturn(regions); - when(complex.getRegionStyleStream()).thenReturn(regionNoise); - when(complex.getBridgeStream()).thenReturn(continents); - when(complex.pickableBiomes(dry, InferredType.LAND)).thenReturn(new KList<>(List.of(plains, forest))); - when(complex.biomePickNoise(dry, InferredType.LAND)).thenReturn(landNoise); - children(plains, List.of(meadow, plains, plains), 0.1D); - children(meadow, List.of(glade, meadow), 0.8D); - } + private final PickedWorld world = new PickedWorld(); @Test public void theBiomeViewWalksFromTheRegionThroughItsListToTheChildThatKeptTheSpot() { - List path = MapPickPath.explain(engine, MapView.BIOMES, X, Z); + List path = explain(MapLayer.of(MapView.BIOMES)); assertEquals(List.of(MapPickPath.Kind.REGION, MapPickPath.Kind.BIOME, MapPickPath.Kind.CHILD, MapPickPath.Kind.CHILD), - path.stream().map(MapPickPath.PickStep::kind).toList()); + kinds(path)); MapPickPath.PickStep region = path.get(0); assertEquals("dry", region.picked().key()); assertEquals(0.9D, region.noise(), 0D); @@ -94,7 +37,7 @@ public class MapPickPathTest { @Test public void aChildStepJoinsNeighbouringSlotsOfOneBiome() { - List bands = MapPickPath.explain(engine, MapView.BIOMES, X, Z).get(2).bands(); + List bands = explain(MapLayer.of(MapView.BIOMES)).get(2).bands(); assertEquals(2, bands.size()); assertBand(bands.get(0), "meadow", 0D, 0.25D); @@ -103,17 +46,14 @@ public class MapPickPathTest { @Test public void theLandViewStopsAtTheListPickBecauseItsStreamHasNoChildren() { - List path = MapPickPath.explain(engine, MapView.LAND_BIOMES, X, Z); - - assertEquals(List.of(MapPickPath.Kind.REGION, MapPickPath.Kind.BIOME), path.stream().map(MapPickPath.PickStep::kind).toList()); + assertEquals(List.of(MapPickPath.Kind.REGION, MapPickPath.Kind.BIOME), kinds(explain(MapLayer.of(MapView.LAND_BIOMES)))); } @Test public void anImageMappedRegionWasChosenNotPicked() { - IrisImageMapRuntime imageMap = complex.getImageMapRuntime(); - when(imageMap.sampleRegion(X, Z)).thenReturn(dry); + when(world.imageMap.sampleRegion(X, Z)).thenReturn(world.dry); - MapPickPath.PickStep region = MapPickPath.explain(engine, MapView.REGIONS, X, Z).getFirst(); + MapPickPath.PickStep region = explain(MapLayer.of(MapView.REGIONS)).getFirst(); assertEquals(MapPickPath.Kind.IMAGE_MAP, region.kind()); assertNull(region.noise()); @@ -121,52 +61,36 @@ public class MapPickPathTest { } @Test - public void slotsRoundTheWayTheChildNoiseDoes() { - assertEquals(0, MapPickPath.slotIndex(0.24D, 3)); - assertEquals(1, MapPickPath.slotIndex(0.26D, 3)); - assertEquals(2, MapPickPath.slotIndex(1.4D, 3)); - assertEquals(0, MapPickPath.slotIndex(0.9D, 1)); + public void aPreviewedRegionOwnsTheSpotAndPicksFromTheListItsSurfaceNeeds() { + when(world.complex.surfacePickAsIfIn(world.dry, X, Z)).thenReturn(new IrisComplex.BiomePick(world.meadow, InferredType.LAND)); + + List path = explain(MapLayer.preview(world.dry)); + + assertEquals(List.of(MapPickPath.Kind.PREVIEW, MapPickPath.Kind.BIOME, MapPickPath.Kind.CHILD, MapPickPath.Kind.CHILD), + kinds(path)); + assertEquals("dry", path.get(0).picked().key()); + assertEquals("land", path.get(1).list()); } - private static void assertBand(MapPickPath.PickBand band, String key, double from, double to) { + @Test + public void slotsRoundTheWayTheChildNoiseDoes() { + assertEquals(0, ChildPicks.slotIndex(0.24D, 3)); + assertEquals(1, ChildPicks.slotIndex(0.26D, 3)); + assertEquals(2, ChildPicks.slotIndex(1.4D, 3)); + assertEquals(0, ChildPicks.slotIndex(0.9D, 1)); + } + + private List explain(MapLayer layer) { + return MapPickPath.explain(world.engine, layer, X, Z); + } + + private static List kinds(List path) { + return path.stream().map(MapPickPath.PickStep::kind).toList(); + } + + static void assertBand(MapPickPath.PickBand band, String key, double from, double to) { assertEquals(key, band.option().key()); assertEquals(from, band.from(), 1e-9); assertEquals(to, band.to(), 1e-9); } - - private void children(IrisBiome parent, List slots, double noise) { - when(parent.getChildren()).thenReturn(new KList<>(List.of("child"))); - when(complex.childSlots(parent)).thenReturn(slots); - CNG childNoise = mock(CNG.class); - when(childNoise.noiseFast2D(X, Z)).thenReturn(noise); - when(complex.childNoise(parent)).thenReturn(childNoise); - } - - private IrisBiome biome(String key, String name, int rarity) { - IrisBiome biome = mock(IrisBiome.class); - when(biome.getLoadKey()).thenReturn(key); - when(biome.getName()).thenReturn(name); - when(biome.getRarity()).thenReturn(rarity); - when(biome.getChildren()).thenReturn(new KList<>()); - when(biome.getInferredType()).thenReturn(InferredType.LAND); - when(biome.withInferredType(any(InferredType.class))).thenReturn(biome); - when(biome.getColor(eq(engine), any(RenderType.class))).thenReturn(Color.GREEN); - return biome; - } - - private IrisRegion region(String key, String name, int rarity) { - IrisRegion region = mock(IrisRegion.class); - when(region.getLoadKey()).thenReturn(key); - when(region.getName()).thenReturn(name); - when(region.getRarity()).thenReturn(rarity); - when(region.getColor(complex, RenderType.REGION)).thenReturn(Color.ORANGE); - return region; - } - - @SuppressWarnings("unchecked") - private static ProceduralStream stream(T value) { - ProceduralStream stream = mock(ProceduralStream.class); - when(stream.get(anyDouble(), anyDouble())).thenReturn(value); - return stream; - } } 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 33bcc4264..b4f25e306 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 @@ -3,6 +3,8 @@ package art.arcane.iris.core.studio.map; import art.arcane.iris.engine.IrisComplex; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.render.RenderType; +import art.arcane.iris.engine.image.IrisImageMapRuntime; +import art.arcane.iris.engine.object.world.biome.InferredType; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.world.region.IrisRegion; @@ -14,6 +16,7 @@ import org.junit.Test; import java.awt.Color; import java.util.List; import java.util.Optional; +import java.util.Set; import java.util.concurrent.CancellationException; import java.util.function.DoubleBinaryOperator; @@ -121,7 +124,7 @@ public class MapTileRendererTest { Engine untouched = mock(Engine.class); assertThrows(CancellationException.class, - () -> new MapTileRenderer(untouched).render(MapView.BIOMES, 0D, 0D, 1D, SIZE, false, () -> true)); + () -> new MapTileRenderer(untouched).render(MapLayer.of(MapView.BIOMES), 0D, 0D, 1D, SIZE, Set.of(), () -> true)); verifyNoInteractions(untouched); } @@ -144,7 +147,7 @@ public class MapTileRendererTest { when(complex.getFocusBiome()).thenReturn(desert); when(desert.getChildren()).thenReturn(new art.arcane.volmlib.util.collection.KList<>()); - MapHover hover = MapHover.sample(engine, MapView.BIOMES, 10D, 0D); + MapHover hover = MapHover.sample(engine, MapLayer.of(MapView.BIOMES), 10D, 0D); assertEquals("desert", hover.biome().key()); assertEquals("cavern", hover.caveBiome().key()); @@ -168,8 +171,45 @@ public class MapTileRendererTest { assertEquals(Optional.empty(), MapView.byId("nothing")); } + @Test + public void aRegionPreviewLabelsTheBiomesThatRegionWouldPlaceAndOwnsEverySpot() { + heights((x, z) -> 70D); + when(complex.surfacePickAsIfIn(org.mockito.ArgumentMatchers.eq(dry), anyDouble(), anyDouble(), anyDouble())) + .thenAnswer(call -> new IrisComplex.BiomePick((double) call.getArgument(1) < 0 ? cavern : desert, InferredType.LAND)); + + MapTile tile = new MapTileRenderer(engine).render(MapLayer.preview(dry), -4D, 0D, 1D, SIZE, Set.of(), () -> false); + + assertEquals(MapLabel.Kind.BIOME, tile.subjectKind()); + assertEquals("cavern", tile.subjectAt(0, 0).key()); + assertEquals("desert", tile.subjectAt(4, 0).key()); + assertEquals("dry", tile.regionAt(0, 0).key()); + assertEquals("dry", tile.regionAt(7, 7).key()); + assertNull("heights only when asked", tile.heights()); + org.mockito.Mockito.verify(complex, org.mockito.Mockito.atLeastOnce()) + .surfacePickAsIfIn(org.mockito.ArgumentMatchers.eq(dry), anyDouble(), anyDouble(), org.mockito.AdditionalMatchers.eq(70D, 1e-4D)); + } + + @Test + public void theRegionViewCarriesTheRegionNoiseOnlyWhenAsked() { + IrisImageMapRuntime imageMaps = mock(IrisImageMapRuntime.class); + when(complex.getImageMapRuntime()).thenReturn(imageMaps); + ProceduralStream regionNoise = stream((x, z) -> (x + 10D) / 100D); + when(complex.getRegionStyleStream()).thenReturn(regionNoise); + + MapTile plain = render(MapView.REGIONS, 0D, 0D, 1D, false); + MapTile withNoise = new MapTileRenderer(engine).render(MapLayer.of(MapView.REGIONS), 0D, 0D, 1D, SIZE, + Set.of(MapTile.Extra.PICK_NOISE), () -> false); + MapTile caves = new MapTileRenderer(engine).render(MapLayer.of(MapView.CAVE_BIOMES), 0D, 0D, 1D, SIZE, + Set.of(MapTile.Extra.PICK_NOISE), () -> false); + + assertNull(plain.pickNoise()); + assertEquals(0.13F, withNoise.pickNoise()[withNoise.gridIndex(3, 5)], 1e-6F); + assertNull("no noise picks the cave biome layer here", caves.pickNoise()); + } + private MapTile render(MapView view, double startX, double startZ, double blocksPerPixel, boolean withHeights) { - return new MapTileRenderer(engine).render(view, startX, startZ, blocksPerPixel, SIZE, withHeights, () -> false); + Set extras = withHeights ? Set.of(MapTile.Extra.HEIGHTS) : Set.of(); + return new MapTileRenderer(engine).render(MapLayer.of(view), startX, startZ, blocksPerPixel, SIZE, extras, () -> false); } private void heights(DoubleBinaryOperator height) { diff --git a/core/src/test/java/art/arcane/iris/core/studio/map/PickedWorld.java b/core/src/test/java/art/arcane/iris/core/studio/map/PickedWorld.java new file mode 100644 index 000000000..0d9e7d075 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/studio/map/PickedWorld.java @@ -0,0 +1,105 @@ +package art.arcane.iris.core.studio.map; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.loader.ResourceLoader; +import art.arcane.iris.engine.IrisComplex; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.render.RenderType; +import art.arcane.iris.engine.image.IrisImageMapRuntime; +import art.arcane.iris.engine.object.world.biome.InferredType; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.world.dimension.IrisDimension; +import art.arcane.iris.engine.object.world.region.IrisRegion; +import art.arcane.iris.util.project.noise.CNG; +import art.arcane.iris.util.project.stream.ProceduralStream; +import art.arcane.volmlib.util.collection.KList; + +import java.awt.Color; +import java.util.List; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyDouble; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * A world that picks the same way at every spot: a dry region (rarity 3, so the last quarter of the region noise) + * picked at 0.9; its land list picks plains at 0.2; plains' child noise at 0.1 rounds to its first slot, meadow; + * meadow's at 0.8 rounds to its last slot, itself. + */ +final class PickedWorld { + final Engine engine = mock(Engine.class); + final IrisComplex complex = mock(IrisComplex.class); + final IrisBiome plains = biome("plains", "Plains", 1); + final IrisBiome forest = biome("forest", "Forest", 1); + final IrisBiome meadow = biome("meadow", "Meadow", 1); + final IrisBiome glade = biome("glade", "Glade", 1); + final IrisRegion warm = region("warm", "Warm", 1); + final IrisRegion dry = region("dry", "Dry", 3); + final IrisImageMapRuntime imageMap = mock(IrisImageMapRuntime.class); + + PickedWorld() { + when(engine.getComplex()).thenReturn(complex); + IrisDimension dimension = mock(IrisDimension.class); + when(dimension.getRegions()).thenReturn(new KList<>(List.of("warm", "dry"))); + when(engine.getDimension()).thenReturn(dimension); + IrisData data = mock(IrisData.class); + @SuppressWarnings("unchecked") + ResourceLoader regionLoader = mock(ResourceLoader.class); + when(regionLoader.loadAll(any(KList.class))).thenReturn(new KList<>(List.of(warm, dry))); + when(data.getRegionLoader()).thenReturn(regionLoader); + when(engine.getData()).thenReturn(data); + when(complex.getImageMapRuntime()).thenReturn(imageMap); + + ProceduralStream regions = stream(dry); + ProceduralStream regionNoise = stream(0.9D); + ProceduralStream continents = stream(InferredType.LAND); + ProceduralStream landNoise = stream(0.2D); + ProceduralStream landPicks = stream(plains); + when(complex.getRegionStream()).thenReturn(regions); + when(complex.getRegionStyleStream()).thenReturn(regionNoise); + when(complex.getBridgeStream()).thenReturn(continents); + when(complex.pickableBiomes(dry, InferredType.LAND)).thenReturn(new KList<>(List.of(plains, forest))); + when(complex.biomePickNoise(dry, InferredType.LAND)).thenReturn(landNoise); + when(complex.biomePicks(dry, InferredType.LAND)).thenReturn(landPicks); + children(plains, List.of(meadow, plains, plains), 0.1D); + children(meadow, List.of(glade, meadow), 0.8D); + } + + private void children(IrisBiome parent, List slots, double noise) { + when(parent.getChildren()).thenReturn(new KList<>(List.of("child"))); + when(complex.childSlots(parent)).thenReturn(slots); + CNG childNoise = mock(CNG.class); + when(childNoise.noiseFast2D(anyDouble(), anyDouble())).thenReturn(noise); + when(complex.childNoise(parent)).thenReturn(childNoise); + } + + private IrisBiome biome(String key, String name, int rarity) { + IrisBiome biome = mock(IrisBiome.class); + when(biome.getLoadKey()).thenReturn(key); + when(biome.getName()).thenReturn(name); + when(biome.getRarity()).thenReturn(rarity); + when(biome.getChildren()).thenReturn(new KList<>()); + when(biome.getInferredType()).thenReturn(InferredType.LAND); + when(biome.withInferredType(any(InferredType.class))).thenReturn(biome); + when(biome.getColor(eq(engine), any(RenderType.class))).thenReturn(Color.GREEN); + return biome; + } + + private IrisRegion region(String key, String name, int rarity) { + IrisRegion region = mock(IrisRegion.class); + when(region.getLoadKey()).thenReturn(key); + when(region.getName()).thenReturn(name); + when(region.getRarity()).thenReturn(rarity); + when(region.getColor(complex, RenderType.REGION)).thenReturn(Color.ORANGE); + return region; + } + + @SuppressWarnings("unchecked") + static ProceduralStream stream(T value) { + ProceduralStream stream = mock(ProceduralStream.class); + when(stream.get(anyDouble(), anyDouble())).thenReturn(value); + return stream; + } +}