From 36b352ea05156e93c0e01c64d47b998194cc3a31 Mon Sep 17 00:00:00 2001 From: piexel Date: Wed, 25 Nov 2026 11:06:45 +0100 Subject: [PATCH] Serve scene views and their editors from a scene layer - Features list their views in SceneViews, the studio adds objects and procedural objects - Edit, write and create scene entries' files from the studio --- .../generation/cave/CaveProfileSceneView.java | 136 ++++++ .../formation/FormationProfileSceneView.java | 72 +++ .../decoration/tree/TreeProfileSceneView.java | 72 +++ .../config/FluidProfileSceneView.java | 99 ++++ .../arcane/iris/studio/bridge/GraphEdit.java | 184 +++++++ .../iris/studio/bridge/GraphEditRequest.java | 92 ++++ .../iris/studio/bridge/JsonSplicer.java | 178 +++++++ .../arcane/iris/studio/bridge/JsonText.java | 358 ++++++++++++++ .../studio/bridge/PackObjectsSceneView.java | 76 +++ .../bridge/ProceduralObjectsSceneView.java | 102 ++++ .../arcane/iris/studio/bridge/SceneFiles.java | 154 ++++++ .../iris/studio/bridge/SettingsTypes.java | 245 ++++++++++ .../iris/studio/bridge/StudioBridge.java | 171 +++++-- .../iris/studio/bridge/StudioEditors.java | 280 +++++++++++ .../iris/studio/bridge/StudioObjects.java | 146 ------ .../iris/studio/bridge/StudioProfiles.java | 461 ------------------ .../iris/studio/bridge/StudioScenes.java | 78 +++ .../iris/studio/bridge/StudioSuggestions.java | 61 +++ .../iris/studio/scene/EditableSceneView.java | 64 +++ .../arcane/iris/studio/scene/GraphNode.java | 114 +++++ .../arcane/iris/studio/scene/JsonPath.java | 116 +++++ .../iris/studio/scene/SceneBakeTiming.java | 27 + .../studio/{bridge => scene}/SceneBlocks.java | 45 +- .../arcane/iris/studio/scene/SceneEntry.java | 42 ++ .../ProfileForm.java => scene/SceneForm.java} | 56 ++- .../iris/studio/scene/SceneRequest.java | 34 ++ .../SceneSizes.java} | 26 +- .../arcane/iris/studio/scene/SceneView.java | 75 +++ .../arcane/iris/studio/scene/SceneViews.java | 68 +++ .../iris/studio/bridge/GraphEditTest.java | 139 ++++++ .../iris/studio/bridge/JsonSplicerTest.java | 140 ++++++ .../bridge/PackObjectsSceneViewTest.java | 73 +++ .../iris/studio/bridge/ProfileFormTest.java | 61 --- .../iris/studio/bridge/StudioScenesTest.java | 66 +++ .../iris/studio/scene/SceneContractTest.java | 260 ++++++++++ 35 files changed, 3621 insertions(+), 750 deletions(-) create mode 100644 core/src/main/java/art/arcane/iris/generation/cave/CaveProfileSceneView.java create mode 100644 core/src/main/java/art/arcane/iris/generation/decoration/formation/FormationProfileSceneView.java create mode 100644 core/src/main/java/art/arcane/iris/generation/decoration/tree/TreeProfileSceneView.java create mode 100644 core/src/main/java/art/arcane/iris/generation/hydrology/config/FluidProfileSceneView.java create mode 100644 core/src/main/java/art/arcane/iris/studio/bridge/GraphEdit.java create mode 100644 core/src/main/java/art/arcane/iris/studio/bridge/GraphEditRequest.java create mode 100644 core/src/main/java/art/arcane/iris/studio/bridge/JsonSplicer.java create mode 100644 core/src/main/java/art/arcane/iris/studio/bridge/JsonText.java create mode 100644 core/src/main/java/art/arcane/iris/studio/bridge/PackObjectsSceneView.java create mode 100644 core/src/main/java/art/arcane/iris/studio/bridge/ProceduralObjectsSceneView.java create mode 100644 core/src/main/java/art/arcane/iris/studio/bridge/SceneFiles.java create mode 100644 core/src/main/java/art/arcane/iris/studio/bridge/SettingsTypes.java create mode 100644 core/src/main/java/art/arcane/iris/studio/bridge/StudioEditors.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/bridge/StudioObjects.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/bridge/StudioProfiles.java create mode 100644 core/src/main/java/art/arcane/iris/studio/bridge/StudioScenes.java create mode 100644 core/src/main/java/art/arcane/iris/studio/bridge/StudioSuggestions.java create mode 100644 core/src/main/java/art/arcane/iris/studio/scene/EditableSceneView.java create mode 100644 core/src/main/java/art/arcane/iris/studio/scene/GraphNode.java create mode 100644 core/src/main/java/art/arcane/iris/studio/scene/JsonPath.java create mode 100644 core/src/main/java/art/arcane/iris/studio/scene/SceneBakeTiming.java rename core/src/main/java/art/arcane/iris/studio/{bridge => scene}/SceneBlocks.java (67%) create mode 100644 core/src/main/java/art/arcane/iris/studio/scene/SceneEntry.java rename core/src/main/java/art/arcane/iris/studio/{bridge/ProfileForm.java => scene/SceneForm.java} (68%) create mode 100644 core/src/main/java/art/arcane/iris/studio/scene/SceneRequest.java rename core/src/main/java/art/arcane/iris/studio/{map/PackObjectSource.java => scene/SceneSizes.java} (56%) create mode 100644 core/src/main/java/art/arcane/iris/studio/scene/SceneView.java create mode 100644 core/src/main/java/art/arcane/iris/studio/scene/SceneViews.java create mode 100644 core/src/test/java/art/arcane/iris/studio/bridge/GraphEditTest.java create mode 100644 core/src/test/java/art/arcane/iris/studio/bridge/JsonSplicerTest.java create mode 100644 core/src/test/java/art/arcane/iris/studio/bridge/PackObjectsSceneViewTest.java delete mode 100644 core/src/test/java/art/arcane/iris/studio/bridge/ProfileFormTest.java create mode 100644 core/src/test/java/art/arcane/iris/studio/bridge/StudioScenesTest.java create mode 100644 core/src/test/java/art/arcane/iris/studio/scene/SceneContractTest.java diff --git a/core/src/main/java/art/arcane/iris/generation/cave/CaveProfileSceneView.java b/core/src/main/java/art/arcane/iris/generation/cave/CaveProfileSceneView.java new file mode 100644 index 000000000..09b8ff09f --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/cave/CaveProfileSceneView.java @@ -0,0 +1,136 @@ +package art.arcane.iris.generation.cave; + +import art.arcane.iris.generation.biome.IrisBiome; +import art.arcane.iris.generation.mantle.CaveProfilePreview; +import art.arcane.iris.generation.runtime.Engine; +import art.arcane.iris.generation.terrain.IrisDimension; +import art.arcane.iris.generation.terrain.IrisRegion; +import art.arcane.iris.pack.loading.IrisData; +import art.arcane.iris.studio.scene.SceneBlocks; +import art.arcane.iris.studio.scene.SceneEntry; +import art.arcane.iris.studio.scene.SceneRequest; +import art.arcane.iris.studio.scene.SceneSizes; +import art.arcane.iris.studio.scene.SceneView; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.NoSuchElementException; + +/** The carved space of each enabled cave profile, as blocks coloured by depth. */ +public final class CaveProfileSceneView implements SceneView { + private static final SceneSizes SIZES = new SceneSizes(List.of(64, 128, 256), 128); + private static final int VARIANTS = 4; + private static final int VARIANT_SPACING_BLOCKS = 4096; + private static final int SURFACE_ABOVE_SEA_BLOCKS = 48; + private static final int MAX_DEPTH_BLOCKS = 160; + private static final String DIMENSION_KEY = "dimension"; + private static final String REGION_PREFIX = "region/"; + private static final String BIOME_PREFIX = "biome/"; + private static final String[] DEPTH_BANDS = {"minecraft:yellow_concrete", "minecraft:lime_concrete", "minecraft:light_blue_concrete", + "minecraft:purple_concrete"}; + private static final int[][] NEIGHBOURS = {{1, 0, 0}, {-1, 0, 0}, {0, 1, 0}, {0, -1, 0}, {0, 0, 1}, {0, 0, -1}}; + + @Override + public String id() { + return "caveProfiles"; + } + + @Override + public String label() { + return "Cave profiles"; + } + + @Override + public String description() { + return "The carved space of each enabled cave profile of the dimension, its regions and its biomes"; + } + + @Override + public SceneSizes sizes() { + return SIZES; + } + + @Override + public List entries(Engine engine) { + IrisData data = engine.getData(); + IrisDimension dimension = engine.getDimension(); + List entries = new ArrayList<>(); + if (dimension.getCaveProfile().isEnabled()) { + entries.add(new SceneEntry(DIMENSION_KEY, dimension.getName(), "Dimension", VARIANTS)); + } + for (IrisRegion region : data.getRegionLoader().loadAll(data.getRegionLoader().getPossibleKeys())) { + if (region != null && region.getCaveProfile().isEnabled()) { + entries.add(new SceneEntry(REGION_PREFIX + region.getLoadKey(), region.getName(), "Regions", VARIANTS)); + } + } + for (IrisBiome biome : data.getBiomeLoader().loadAll(data.getBiomeLoader().getPossibleKeys())) { + if (biome != null && biome.getCaveProfile().isEnabled()) { + entries.add(new SceneEntry(BIOME_PREFIX + biome.getLoadKey(), biome.getName(), "Biomes", VARIANTS)); + } + } + return entries; + } + + @Override + public SceneBlocks scene(Engine engine, SceneRequest request) throws IOException { + IrisCaveProfile profile = profileOf(engine, request.key()); + int size = request.size(); + int surfaceY = Math.min(engine.getHeight() - 1, engine.getDimension().getFluidHeight() + SURFACE_ABOVE_SEA_BLOCKS); + int bottomY = Math.max(0, Math.max((int) Math.floor(profile.getVerticalRange().getMin()), surfaceY - MAX_DEPTH_BLOCKS)); + int originX = Math.floorMod(request.variant(), VARIANTS) * VARIANT_SPACING_BLOCKS; + boolean[] carved = CaveProfilePreview.carve(engine, profile, originX, size, bottomY, surfaceY); + return outsideOf(carved, size, surfaceY - bottomY + 1); + } + + private static IrisCaveProfile profileOf(Engine engine, String key) { + IrisData data = engine.getData(); + IrisCaveProfile profile = null; + if (DIMENSION_KEY.equals(key)) { + profile = engine.getDimension().getCaveProfile(); + } else if (key.startsWith(REGION_PREFIX)) { + IrisRegion region = data.getRegionLoader().load(key.substring(REGION_PREFIX.length())); + profile = region == null ? null : region.getCaveProfile(); + } else if (key.startsWith(BIOME_PREFIX)) { + IrisBiome biome = data.getBiomeLoader().load(key.substring(BIOME_PREFIX.length())); + profile = biome == null ? null : biome.getCaveProfile(); + } + if (profile == null) { + throw new NoSuchElementException("No cave profile " + key); + } + return profile; + } + + // Only the carved blocks on the outside of the space are kept, as the inside could not be seen. + private static SceneBlocks outsideOf(boolean[] carved, int size, int height) { + SceneBlocks scene = new SceneBlocks(); + for (int y = 0; y < height; y++) { + String band = DEPTH_BANDS[Math.min(DEPTH_BANDS.length - 1, (height - 1 - y) * DEPTH_BANDS.length / height)]; + for (int z = 0; z < size; z++) { + for (int x = 0; x < size; x++) { + if (carved[cellOf(x, y, z, size)] && touchesRock(carved, x, y, z, size, height)) { + scene.add(x, y, z, band); + } + } + } + } + return scene; + } + + private static boolean touchesRock(boolean[] carved, int x, int y, int z, int size, int height) { + 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 || !carved[cellOf(nx, ny, nz, size)]) { + return true; + } + } + return false; + } + + private static int cellOf(int x, int y, int z, int size) { + return (y * size + z) * size + x; + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/decoration/formation/FormationProfileSceneView.java b/core/src/main/java/art/arcane/iris/generation/decoration/formation/FormationProfileSceneView.java new file mode 100644 index 000000000..a77774e88 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/decoration/formation/FormationProfileSceneView.java @@ -0,0 +1,72 @@ +package art.arcane.iris.generation.decoration.formation; + +import art.arcane.iris.generation.runtime.Engine; +import art.arcane.iris.studio.scene.SceneBlocks; +import art.arcane.iris.studio.scene.SceneEntry; +import art.arcane.iris.studio.scene.SceneForm; +import art.arcane.iris.studio.scene.SceneRequest; +import art.arcane.iris.studio.scene.SceneView; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Set; + +/** How each formation profile shapes a formation's width from base to top. */ +public final class FormationProfileSceneView implements SceneView { + private static final Set HIDDEN = Set.of("name", "chance", "density", "variants", "seed", "mode", "carvingSupport", + "surfaceSupportBuffer", "underwater", "profile"); + + @Override + public String id() { + return "formationProfiles"; + } + + @Override + public String label() { + return "Formation profiles"; + } + + @Override + public String description() { + return "How each formation profile shapes a formation's width from base to top"; + } + + @Override + public List entries(Engine engine) { + int variants = new IrisFormation().getVariants(); + return Arrays.stream(IrisFormationProfile.values()).map(profile -> SceneEntry.preset(profile, variants)).toList(); + } + + @Override + public boolean hasForm() { + return true; + } + + @Override + public SceneForm form(Engine engine, String key, Map overrides) { + return SceneForm.of("Formation", formationOf(key, overrides), HIDDEN, overrides, + List.of(SceneForm.describe(profileOf(key)), "Values typed here change the preview only")); + } + + @Override + public SceneBlocks scene(Engine engine, SceneRequest request) { + IrisFormation formation = formationOf(request.key(), request.overrides()); + return SceneBlocks.ofVariant(formation.getVariantObjects(engine.getData()), request.variant(), "formation"); + } + + private static IrisFormation formationOf(String key, Map overrides) { + IrisFormation formation = SceneForm.withOverrides(new IrisFormation(), overrides); + formation.setProfile(profileOf(key)); + return formation; + } + + private static IrisFormationProfile profileOf(String key) { + try { + return IrisFormationProfile.valueOf(key); + } catch (IllegalArgumentException unknown) { + throw new NoSuchElementException("No formation profile " + key); + } + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/decoration/tree/TreeProfileSceneView.java b/core/src/main/java/art/arcane/iris/generation/decoration/tree/TreeProfileSceneView.java new file mode 100644 index 000000000..667f16f5e --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/decoration/tree/TreeProfileSceneView.java @@ -0,0 +1,72 @@ +package art.arcane.iris.generation.decoration.tree; + +import art.arcane.iris.generation.runtime.Engine; +import art.arcane.iris.studio.scene.SceneBlocks; +import art.arcane.iris.studio.scene.SceneEntry; +import art.arcane.iris.studio.scene.SceneForm; +import art.arcane.iris.studio.scene.SceneRequest; +import art.arcane.iris.studio.scene.SceneView; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Set; + +/** The canopy shape each tree profile gives a procedural tree. */ +public final class TreeProfileSceneView implements SceneView { + private static final Set HIDDEN = Set.of("name", "chance", "density", "variants", "seed", "plausible", "mode", + "carvingSupport", "underwater", "profile"); + + @Override + public String id() { + return "treeProfiles"; + } + + @Override + public String label() { + return "Tree profiles"; + } + + @Override + public String description() { + return "The canopy shape each tree profile gives a procedural tree"; + } + + @Override + public List entries(Engine engine) { + int variants = new IrisProceduralTree().getVariants(); + return Arrays.stream(IrisTreeProfile.values()).map(profile -> SceneEntry.preset(profile, variants)).toList(); + } + + @Override + public boolean hasForm() { + return true; + } + + @Override + public SceneForm form(Engine engine, String key, Map overrides) { + return SceneForm.of("Tree", treeOf(key, overrides), HIDDEN, overrides, + List.of(SceneForm.describe(profileOf(key)), "Values typed here change the preview only")); + } + + @Override + public SceneBlocks scene(Engine engine, SceneRequest request) { + IrisProceduralTree tree = treeOf(request.key(), request.overrides()); + return SceneBlocks.ofVariant(tree.getVariantObjects(engine.getData()), request.variant(), "tree"); + } + + private static IrisProceduralTree treeOf(String key, Map overrides) { + IrisProceduralTree tree = SceneForm.withOverrides(new IrisProceduralTree(), overrides); + tree.setProfile(profileOf(key)); + return tree; + } + + private static IrisTreeProfile profileOf(String key) { + try { + return IrisTreeProfile.valueOf(key); + } catch (IllegalArgumentException unknown) { + throw new NoSuchElementException("No tree profile " + key); + } + } +} diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/config/FluidProfileSceneView.java b/core/src/main/java/art/arcane/iris/generation/hydrology/config/FluidProfileSceneView.java new file mode 100644 index 000000000..00e7d49eb --- /dev/null +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/config/FluidProfileSceneView.java @@ -0,0 +1,99 @@ +package art.arcane.iris.generation.hydrology.config; + +import art.arcane.iris.generation.runtime.Engine; +import art.arcane.iris.pack.loading.IrisData; +import art.arcane.iris.studio.scene.SceneBlocks; +import art.arcane.iris.studio.scene.SceneEntry; +import art.arcane.iris.studio.scene.SceneForm; +import art.arcane.iris.studio.scene.SceneRequest; +import art.arcane.iris.studio.scene.SceneSizes; +import art.arcane.iris.studio.scene.SceneView; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Optional; + +/** The blocks of each named fluid of the dimension's hydrology, in a pool lined with its seam. */ +public final class FluidProfileSceneView implements SceneView { + private static final SceneSizes SIZES = new SceneSizes(List.of(16, 32, 64), 32); + private static final int VARIANTS = 4; + private static final int VARIANT_SPACING_BLOCKS = 1024; + private static final int DEPTH_BLOCKS = 3; + private static final String BASIN_BLOCK = "minecraft:stone"; + + @Override + public String id() { + return "fluidProfiles"; + } + + @Override + public String label() { + return "Fluid profiles"; + } + + @Override + public String description() { + return "The blocks of each named fluid of the dimension's hydrology, in a pool lined with its seam"; + } + + @Override + public SceneSizes sizes() { + return SIZES; + } + + @Override + public List entries(Engine engine) { + return fluids(engine).stream().map(fluid -> new SceneEntry(fluid.getName(), fluid.getName(), "Fluids", VARIANTS)).toList(); + } + + @Override + public boolean hasForm() { + return true; + } + + @Override + public SceneForm form(Engine engine, String key, Map overrides) { + IrisFluidProfile fluid = fluidOf(engine, key); + IrisData data = engine.getData(); + List notes = new ArrayList<>(); + notes.add("Blocks: " + String.join(", ", fluid.getPalette().getBlockData(data).stream().map(state -> state.key()).toList())); + notes.add("Seam: " + (fluid.getSeam() == null ? "none" : fluid.getSeam())); + return new SceneForm("Fluid", List.of(), notes); + } + + @Override + public SceneBlocks scene(Engine engine, SceneRequest request) { + IrisData data = engine.getData(); + IrisFluidProfile fluid = fluidOf(engine, request.key()); + IrisFluidProfile seam = fluid.getSeam() == null ? null : fluidOf(engine, fluid.getSeam()); + int size = request.size(); + int offset = Math.floorMod(request.variant(), VARIANTS) * VARIANT_SPACING_BLOCKS; + RNG rng = new RNG(offset + 1L); + SceneBlocks scene = new SceneBlocks(); + for (int z = 0; z < size; z++) { + for (int x = 0; x < size; x++) { + scene.add(x, 0, z, BASIN_BLOCK); + boolean wall = x == 0 || z == 0 || x == size - 1 || z == size - 1; + boolean seamRing = seam != null && (x == 1 || z == 1 || x == size - 2 || z == size - 2); + for (int y = 1; y <= DEPTH_BLOCKS; y++) { + IrisFluidProfile filling = seamRing ? seam : fluid; + scene.add(x, y, z, wall ? BASIN_BLOCK : filling.getPalette().get(rng, x + offset, y, z, data).key()); + } + } + } + return scene; + } + + private static KList fluids(Engine engine) { + return engine.getDimension().getHydrology().getFluids(); + } + + private static IrisFluidProfile fluidOf(Engine engine, String key) { + Optional found = fluids(engine).stream().filter(fluid -> key.equals(fluid.getName())).findFirst(); + return found.orElseThrow(() -> new NoSuchElementException("No fluid profile " + key)); + } +} diff --git a/core/src/main/java/art/arcane/iris/studio/bridge/GraphEdit.java b/core/src/main/java/art/arcane/iris/studio/bridge/GraphEdit.java new file mode 100644 index 000000000..f6f9957ff --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/bridge/GraphEdit.java @@ -0,0 +1,184 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 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.studio.bridge; + +import art.arcane.iris.studio.bridge.JsonSplicer.Splice; +import art.arcane.iris.studio.scene.JsonPath; + +import java.util.List; +import java.util.Objects; + +/** One change the studio's node editor makes to an entry's file, as the splices of its text that make it. */ +sealed interface GraphEdit { + /** + * The splices that make the change in {@code file}. + * + * @throws IllegalArgumentException naming why, when the file has nothing there to change + */ + List splices(JsonSplicer file); + + /** Sets member {@code key} of the object at {@code object} to {@code literal}, writing the object when it is missing. */ + record Set(JsonPath object, String key, String literal) implements GraphEdit { + public Set { + Objects.requireNonNull(object, "object"); + Objects.requireNonNull(key, "key"); + requireValue(literal); + } + + @Override + public List splices(JsonSplicer file) { + if (file.at(object).orElse(null) instanceof JsonText.Obj settings) { + return List.of(file.put(settings, key, literal)); + } + if (object.isRoot() || !(object.last() instanceof JsonPath.Key(String member))) { + throw new IllegalArgumentException("Nothing to set " + key + " on at " + object); + } + return new Set(object.parent(), member, "{" + JsonSplicer.quote(key) + ": " + literal + "}").splices(file); + } + } + + /** Removes member {@code key} of the object at {@code object}, leaving it at its default. */ + record Unset(JsonPath object, String key) implements GraphEdit { + @Override + public List splices(JsonSplicer file) { + if (!(file.at(object).orElse(null) instanceof JsonText.Obj settings) || settings.member(key).isEmpty()) { + return List.of(); + } + return List.of(file.remove(settings, key)); + } + } + + /** Appends {@code literal} to the array at {@code list}, writing the array when it is missing. */ + record Append(JsonPath list, String literal) implements GraphEdit { + public Append { + Objects.requireNonNull(list, "list"); + requireValue(literal); + } + + @Override + public List splices(JsonSplicer file) { + return List.of(appendTo(file, list, literal)); + } + } + + /** Appends a copy of the last element of the array at {@code list}, so a new item starts out filled in. */ + record AddItem(JsonPath list) implements GraphEdit { + private static final String EMPTY_ITEM = "{}"; + + @Override + public List splices(JsonSplicer file) { + if (!(file.at(list).orElse(null) instanceof JsonText.Arr array)) { + throw new IllegalArgumentException("No list at " + list); + } + String copy = array.elements().isEmpty() ? EMPTY_ITEM : file.detachedTextOf(array.elements().getLast()); + return List.of(file.append(array, copy)); + } + } + + /** Deletes the value at {@code path}, and the member holding the array it was in when it was the only element. */ + record Delete(JsonPath path) implements GraphEdit { + public Delete { + if (path.isRoot()) { + throw new IllegalArgumentException("The file itself can't be deleted"); + } + } + + @Override + public List splices(JsonSplicer file) { + return List.of(removal(file, path)); + } + } + + /** Appends a copy of the element at {@code path}, with all it holds, to the array holding it. */ + record Duplicate(JsonPath path) implements GraphEdit { + public Duplicate { + if (!path.isElement()) { + throw new IllegalArgumentException("Only an element of a list can be duplicated, not " + path); + } + } + + @Override + public List splices(JsonSplicer file) { + JsonText.Value element = valueAt(file, path); + if (!(file.at(path.parent()).orElse(null) instanceof JsonText.Arr array)) { + throw new IllegalArgumentException("No list holds " + path); + } + return List.of(file.append(array, file.detachedTextOf(element))); + } + } + + /** Moves the element at {@code path}, with all it holds, to the end of the array at {@code toList}. */ + record Move(JsonPath path, JsonPath toList) implements GraphEdit { + public Move { + if (!path.isElement()) { + throw new IllegalArgumentException("Only an element of a list can move, not " + path); + } + if (toList.startsWith(path)) { + throw new IllegalArgumentException("A node can't move into itself or into what it holds"); + } + if (toList.equals(path.parent())) { + throw new IllegalArgumentException("It is there already"); + } + } + + @Override + public List splices(JsonSplicer file) { + String moved = file.detachedTextOf(valueAt(file, path)); + return List.of(removal(file, path), appendTo(file, toList, moved)); + } + } + + private static void requireValue(String literal) { + if (literal == null || !JsonText.isValue(literal)) { + throw new IllegalArgumentException(literal + " is not a JSON value"); + } + } + + private static JsonText.Value valueAt(JsonSplicer file, JsonPath path) { + return file.at(path).orElseThrow(() -> new IllegalArgumentException("Nothing at " + path)); + } + + private static Splice appendTo(JsonSplicer file, JsonPath list, String literal) { + if (file.at(list).orElse(null) instanceof JsonText.Arr array) { + return file.append(array, literal); + } + if (list.isRoot() || !(list.last() instanceof JsonPath.Key(String member)) + || !(file.at(list.parent()).orElse(null) instanceof JsonText.Obj owner)) { + throw new IllegalArgumentException("Nothing can be added at " + list); + } + return file.put(owner, member, "[" + literal + "]"); + } + + private static Splice removal(JsonSplicer file, JsonPath path) { + JsonPath holderPath = path.parent(); + JsonText.Value holder = valueAt(file, holderPath); + if (path.last() instanceof JsonPath.Key(String key) && holder instanceof JsonText.Obj object) { + return file.remove(object, key); + } + if (!(path.last() instanceof JsonPath.Index(int index)) || !(holder instanceof JsonText.Arr array) || index >= array.elements().size()) { + throw new IllegalArgumentException("Nothing at " + path); + } + boolean onlyElement = array.elements().size() == 1; + if (onlyElement && !holderPath.isRoot() && holderPath.last() instanceof JsonPath.Key(String key) + && file.at(holderPath.parent()).orElse(null) instanceof JsonText.Obj owner) { + return file.remove(owner, key); + } + return file.removeElement(array, index); + } +} diff --git a/core/src/main/java/art/arcane/iris/studio/bridge/GraphEditRequest.java b/core/src/main/java/art/arcane/iris/studio/bridge/GraphEditRequest.java new file mode 100644 index 000000000..310ad06d6 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/bridge/GraphEditRequest.java @@ -0,0 +1,92 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 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.studio.bridge; + +import art.arcane.iris.studio.scene.JsonPath; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.JsonParser; +import com.google.gson.JsonPrimitive; + +/** An edit as the studio sends it: {@code {"revision": "…", "edit": {"op": "set", …}}}, paths as arrays of names and indices. */ +record GraphEditRequest(String revision, GraphEdit edit) { + /** @throws IllegalArgumentException naming what is missing or wrong */ + static GraphEditRequest parse(String body) { + JsonObject root = object(bodyOf(body), "The body"); + JsonObject edit = object(root.get("edit"), "edit"); + GraphEdit parsed = switch (text(edit, "op")) { + case "set" -> new GraphEdit.Set(path(edit, "object"), text(edit, "key"), text(edit, "literal")); + case "unset" -> new GraphEdit.Unset(path(edit, "object"), text(edit, "key")); + case "append" -> new GraphEdit.Append(path(edit, "list"), text(edit, "literal")); + case "addItem" -> new GraphEdit.AddItem(path(edit, "list")); + case "delete" -> new GraphEdit.Delete(path(edit, "path")); + case "duplicate" -> new GraphEdit.Duplicate(path(edit, "path")); + case "move" -> new GraphEdit.Move(path(edit, "path"), path(edit, "toList")); + default -> throw new IllegalArgumentException("Unknown edit: " + text(edit, "op")); + }; + return new GraphEditRequest(text(root, "revision"), parsed); + } + + /** A whole-file write, as undoing and redoing send it: {@code {"revision": "…", "text": "…"}}. */ + record FileWrite(String revision, String text) { + static FileWrite parse(String body) { + JsonObject root = object(bodyOf(body), "The body"); + return new FileWrite(GraphEditRequest.text(root, "revision"), GraphEditRequest.text(root, "text")); + } + } + + private static JsonElement bodyOf(String body) { + try { + return JsonParser.parseString(body); + } catch (JsonParseException notJson) { + throw new IllegalArgumentException("The body is not JSON"); + } + } + + private static JsonObject object(JsonElement element, String name) { + if (element == null || !element.isJsonObject()) { + throw new IllegalArgumentException(name + " must be a JSON object"); + } + return element.getAsJsonObject(); + } + + private static String text(JsonObject object, String key) { + JsonElement value = object.get(key); + if (value == null || !value.isJsonPrimitive() || !value.getAsJsonPrimitive().isString()) { + throw new IllegalArgumentException(key + " must be a string"); + } + return value.getAsString(); + } + + private static JsonPath path(JsonObject object, String key) { + if (!(object.get(key) instanceof JsonArray steps)) { + throw new IllegalArgumentException(key + " must be an array of member names and indices"); + } + JsonPath path = JsonPath.ROOT; + for (JsonElement step : steps) { + if (!(step instanceof JsonPrimitive primitive)) { + throw new IllegalArgumentException(key + " holds " + step + ", not a name or an index"); + } + path = primitive.isNumber() ? path.element(primitive.getAsInt()) : path.member(primitive.getAsString()); + } + return path; + } +} diff --git a/core/src/main/java/art/arcane/iris/studio/bridge/JsonSplicer.java b/core/src/main/java/art/arcane/iris/studio/bridge/JsonSplicer.java new file mode 100644 index 000000000..9ca7fd2ab --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/bridge/JsonSplicer.java @@ -0,0 +1,178 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 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.studio.bridge; + +import art.arcane.iris.studio.scene.JsonPath; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; +import java.util.Optional; + +/** + * Changes to a JSON file's text as splices of the text, each replacing what one value or member is written as. All + * else stays as it was written: the layout, the order of the members and the comments. New members and elements are + * written in the style of their neighbours, on lines of their own where those are. + */ +final class JsonSplicer { + private static final String MEMBER_SEPARATOR = ", "; + private static final String LINE_SEPARATOR = ",\n"; + + private final JsonText source; + + JsonSplicer(JsonText source) { + this.source = Objects.requireNonNull(source, "source"); + } + + /** {@code plain} as a JSON string literal. */ + static String quote(String plain) { + StringBuilder quoted = new StringBuilder("\""); + for (char character : plain.toCharArray()) { + switch (character) { + case '"' -> quoted.append("\\\""); + case '\\' -> quoted.append("\\\\"); + case '\n' -> quoted.append("\\n"); + case '\r' -> quoted.append("\\r"); + case '\t' -> quoted.append("\\t"); + default -> quoted.append(character < 0x20 ? String.format("\\u%04x", (int) character) : String.valueOf(character)); + } + } + return quoted.append('"').toString(); + } + + /** The value at {@code path}; empty when the file has none there. */ + Optional at(JsonPath path) { + return source.at(path); + } + + /** The text of {@code value}, its later lines indented as if it started a line with no indent. */ + String detachedTextOf(JsonText.Value value) { + return reindented(source.textOf(value), indentOfLine(value.start()), ""); + } + + Splice replace(JsonText.Value value, String literal) { + return new Splice(value.start(), value.end(), literal); + } + + /** Sets the member, written after the last one in the object's own style when it is new. */ + Splice put(JsonText.Obj object, String key, String literal) { + Optional existing = object.member(key); + if (existing.isPresent()) { + return replace(existing.get().value(), literal); + } + if (object.members().isEmpty()) { + return replace(object, "{" + quote(key) + ": " + reindented(literal, "", indentOfLine(object.start())) + "}"); + } + JsonText.Member last = object.members().getLast(); + String indent = indentOfLine(last.keyStart()); + String entry = quote(key) + ": " + reindented(literal, "", indent); + return new Splice(last.value().end(), last.value().end(), separatorIn(object, indent) + entry); + } + + /** @throws IllegalArgumentException when the object has no member {@code key} */ + Splice remove(JsonText.Obj object, String key) { + List members = object.members(); + int index = members.indexOf(object.member(key).orElseThrow(() -> new IllegalArgumentException("No " + key + " to remove"))); + if (members.size() == 1) { + return replace(object, "{}"); + } + if (index > 0) { + return new Splice(members.get(index - 1).value().end(), members.get(index).value().end(), ""); + } + return new Splice(members.getFirst().keyStart(), members.get(1).keyStart(), ""); + } + + /** Adds an element after the last one, a multi-line one indented to match the array. */ + Splice append(JsonText.Arr array, String literal) { + if (array.elements().isEmpty()) { + return replace(array, "[" + reindented(literal, "", indentOfLine(array.start())) + "]"); + } + JsonText.Value last = array.elements().getLast(); + String indent = indentOfLine(last.start()); + return new Splice(last.end(), last.end(), separatorIn(array, indent) + reindented(literal, "", indent)); + } + + Splice removeElement(JsonText.Arr array, int index) { + List elements = array.elements(); + Objects.checkIndex(index, elements.size()); + if (elements.size() == 1) { + return replace(array, "[]"); + } + if (index > 0) { + return new Splice(elements.get(index - 1).end(), elements.get(index).end(), ""); + } + return new Splice(elements.getFirst().start(), elements.get(1).start(), ""); + } + + /** + * The text with {@code splices} made, each placed by where it was in the source text. + * + * @throws IllegalArgumentException when two splices overlap + */ + String apply(List splices) { + List fromLast = new ArrayList<>(splices); + fromLast.sort(Comparator.comparingInt(Splice::start).reversed()); + StringBuilder edited = new StringBuilder(source.text()); + int earliestStart = Integer.MAX_VALUE; + for (Splice splice : fromLast) { + if (splice.end() > earliestStart) { + throw new IllegalArgumentException("Overlapping edits"); + } + edited.replace(splice.start(), splice.end(), splice.replacement()); + earliestStart = splice.start(); + } + return edited.toString(); + } + + private String separatorIn(JsonText.Value holder, String indent) { + return source.textOf(holder).indexOf('\n') >= 0 ? LINE_SEPARATOR + indent : MEMBER_SEPARATOR; + } + + // The blanks before the first character on the line holding position. + private String indentOfLine(int position) { + String text = source.text(); + int lineStart = text.lastIndexOf('\n', position - 1) + 1; + int indentEnd = lineStart; + while (indentEnd < position && (text.charAt(indentEnd) == ' ' || text.charAt(indentEnd) == '\t')) { + indentEnd++; + } + return text.substring(lineStart, indentEnd); + } + + private static String reindented(String literal, String fromIndent, String toIndent) { + String[] lines = literal.split("\n", -1); + StringBuilder result = new StringBuilder(lines[0]); + for (int index = 1; index < lines.length; index++) { + String line = lines[index].startsWith(fromIndent) ? lines[index].substring(fromIndent.length()) : lines[index].stripLeading(); + result.append('\n').append(toIndent).append(line); + } + return result.toString(); + } + + /** Replaces the text from {@code start} up to {@code end} with {@code replacement}. */ + record Splice(int start, int end, String replacement) { + Splice { + Objects.requireNonNull(replacement, "replacement"); + if (start < 0 || end < start) { + throw new IllegalArgumentException("A splice runs forwards from 0, not " + start + " to " + end); + } + } + } +} diff --git a/core/src/main/java/art/arcane/iris/studio/bridge/JsonText.java b/core/src/main/java/art/arcane/iris/studio/bridge/JsonText.java new file mode 100644 index 000000000..b26ab830f --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/bridge/JsonText.java @@ -0,0 +1,358 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 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.studio.bridge; + +import art.arcane.iris.studio.scene.JsonPath; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonNull; +import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; +import com.google.gson.internal.LazilyParsedNumber; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.regex.Pattern; + +/** + * A JSON file's text read into values that know where they are written, so an edit can change one value and leave the + * rest of the text, its layout and its comments as they were. Line and block comments are read as blanks. + */ +final class JsonText { + private static final Pattern NUMBER = Pattern.compile("-?(0|[1-9]\\d*)(\\.\\d+)?([eE][+-]?\\d+)?"); + private static final String TRUE = "true"; + private static final String FALSE = "false"; + private static final String NULL = "null"; + + private final String text; + private final Value root; + + private JsonText(String text, Value root) { + this.text = text; + this.root = root; + } + + /** @throws IllegalArgumentException naming the line, when {@code text} is not one JSON value */ + static JsonText parse(String text) { + Objects.requireNonNull(text, "text"); + Parser parser = new Parser(text); + Value root = parser.value(); + parser.skipBlank(); + if (!parser.atEnd()) { + throw parser.error("Unexpected text after the end"); + } + return new JsonText(text, root); + } + + /** Whether {@code literal} is one JSON value. */ + static boolean isValue(String literal) { + try { + parse(literal); + return true; + } catch (IllegalArgumentException notJson) { + return false; + } + } + + String text() { + return text; + } + + Value root() { + return root; + } + + /** The value at {@code path}; empty when the file has none there. */ + Optional at(JsonPath path) { + Value value = root; + for (JsonPath.Step step : path.steps()) { + Optional inside = stepInto(value, step); + if (inside.isEmpty()) { + return Optional.empty(); + } + value = inside.get(); + } + return Optional.of(value); + } + + /** The value as it is written. */ + String textOf(Value value) { + return text.substring(value.start(), value.end()); + } + + /** The whole file as Gson reads it, so what the pack reads and what is edited come from one reading of the text. */ + JsonElement toGson() { + return gsonOf(root); + } + + private JsonElement gsonOf(Value value) { + return switch (value) { + case Obj object -> { + JsonObject members = new JsonObject(); + object.members().forEach(member -> members.add(member.key(), gsonOf(member.value()))); + yield members; + } + case Arr array -> { + JsonArray elements = new JsonArray(); + array.elements().forEach(element -> elements.add(gsonOf(element))); + yield elements; + } + case Literal literal -> gsonOf(literal); + }; + } + + private JsonElement gsonOf(Literal literal) { + if (literal.string().isPresent()) { + return new JsonPrimitive(literal.string().get()); + } + String written = textOf(literal); + return switch (written) { + case TRUE -> new JsonPrimitive(true); + case FALSE -> new JsonPrimitive(false); + case NULL -> JsonNull.INSTANCE; + default -> new JsonPrimitive(new LazilyParsedNumber(written)); + }; + } + + private static Optional stepInto(Value value, JsonPath.Step step) { + if (step instanceof JsonPath.Key(String name) && value instanceof Obj object) { + return object.get(name); + } + if (step instanceof JsonPath.Index(int position) && value instanceof Arr array && position < array.elements().size()) { + return Optional.of(array.elements().get(position)); + } + return Optional.empty(); + } + + /** A value of the file, from {@code start} up to {@code end} in its text. */ + sealed interface Value permits Obj, Arr, Literal { + int start(); + + int end(); + } + + /** One member of an object; {@code keyStart} is where its quoted name begins. */ + record Member(String key, int keyStart, Value value) { + } + + record Obj(int start, int end, List members) implements Value { + Obj { + members = List.copyOf(members); + } + + Optional member(String key) { + return members.stream().filter(member -> member.key().equals(key)).findFirst(); + } + + Optional get(String key) { + return member(key).map(Member::value); + } + } + + record Arr(int start, int end, List elements) implements Value { + Arr { + elements = List.copyOf(elements); + } + } + + /** A string, number, true, false or null; {@code string} holds a string's decoded text, and is empty for the rest. */ + record Literal(int start, int end, Optional string) implements Value { + Literal { + Objects.requireNonNull(string, "string"); + } + } + + private static final class Parser { + private static final String STRUCTURE = "{}[],:\""; + private static final int UNICODE_ESCAPE_DIGITS = 4; + private static final int HEX = 16; + + private final String text; + private int position; + + Parser(String text) { + this.text = text; + } + + boolean atEnd() { + return position >= text.length(); + } + + Value value() { + skipBlank(); + if (atEnd()) { + throw error("Expected a value"); + } + return switch (text.charAt(position)) { + case '{' -> object(); + case '[' -> array(); + case '"' -> { + int start = position; + String string = string(); + yield new Literal(start, position, Optional.of(string)); + } + default -> bareLiteral(); + }; + } + + private Obj object() { + int start = position++; + List members = new ArrayList<>(); + skipBlank(); + if (peek() == '}') { + position++; + return new Obj(start, position, List.of()); + } + while (true) { + skipBlank(); + if (peek() != '"') { + throw error("Expected a quoted name"); + } + int keyStart = position; + String key = string(); + skipBlank(); + expect(':'); + members.add(new Member(key, keyStart, value())); + skipBlank(); + if (peek() != ',') { + expect('}'); + return new Obj(start, position, members); + } + position++; + } + } + + private Arr array() { + int start = position++; + List elements = new ArrayList<>(); + skipBlank(); + if (peek() == ']') { + position++; + return new Arr(start, position, List.of()); + } + while (true) { + elements.add(value()); + skipBlank(); + if (peek() != ',') { + expect(']'); + return new Arr(start, position, elements); + } + position++; + } + } + + private String string() { + position++; + StringBuilder decoded = new StringBuilder(); + while (!atEnd()) { + char character = text.charAt(position++); + if (character == '"') { + return decoded.toString(); + } + if (character != '\\') { + decoded.append(character); + continue; + } + if (atEnd()) { + break; + } + decoded.append(escaped(text.charAt(position++))); + } + throw error("Unclosed string"); + } + + private char escaped(char escape) { + return switch (escape) { + case 'n' -> '\n'; + case 't' -> '\t'; + case 'r' -> '\r'; + case 'b' -> '\b'; + case 'f' -> '\f'; + case 'u' -> unicodeEscape(); + default -> escape; + }; + } + + private char unicodeEscape() { + if (position + UNICODE_ESCAPE_DIGITS > text.length()) { + throw error("Unfinished \\u escape"); + } + try { + char decoded = (char) Integer.parseInt(text.substring(position, position + UNICODE_ESCAPE_DIGITS), HEX); + position += UNICODE_ESCAPE_DIGITS; + return decoded; + } catch (NumberFormatException notHex) { + throw error("Malformed \\u escape"); + } + } + + private Literal bareLiteral() { + int start = position; + while (!atEnd() && STRUCTURE.indexOf(text.charAt(position)) < 0 && !Character.isWhitespace(text.charAt(position))) { + position++; + } + String word = text.substring(start, position); + if (!word.equals(TRUE) && !word.equals(FALSE) && !word.equals(NULL) && !NUMBER.matcher(word).matches()) { + position = start; + throw error(word.isEmpty() ? "Expected a value" : "Not a value: " + word); + } + return new Literal(start, position, Optional.empty()); + } + + void skipBlank() { + while (!atEnd()) { + char character = text.charAt(position); + if (Character.isWhitespace(character)) { + position++; + } else if (text.startsWith("//", position)) { + int lineEnd = text.indexOf('\n', position); + position = lineEnd < 0 ? text.length() : lineEnd; + } else if (text.startsWith("/*", position)) { + int commentEnd = text.indexOf("*/", position + 2); + position = commentEnd < 0 ? text.length() : commentEnd + 2; + } else { + return; + } + } + } + + private char peek() { + return atEnd() ? '\0' : text.charAt(position); + } + + private void expect(char wanted) { + if (peek() != wanted) { + throw error("Expected " + wanted); + } + position++; + } + + IllegalArgumentException error(String problem) { + int line = 1; + for (int index = 0; index < Math.min(position, text.length()); index++) { + if (text.charAt(index) == '\n') { + line++; + } + } + return new IllegalArgumentException(problem + " on line " + line); + } + } +} diff --git a/core/src/main/java/art/arcane/iris/studio/bridge/PackObjectsSceneView.java b/core/src/main/java/art/arcane/iris/studio/bridge/PackObjectsSceneView.java new file mode 100644 index 000000000..710250141 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/bridge/PackObjectsSceneView.java @@ -0,0 +1,76 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 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.studio.bridge; + +import art.arcane.iris.generation.runtime.Engine; +import art.arcane.iris.structure.object.IrisObject; +import art.arcane.iris.studio.scene.SceneBlocks; +import art.arcane.iris.studio.scene.SceneEntry; +import art.arcane.iris.studio.scene.SceneRequest; +import art.arcane.iris.studio.scene.SceneView; + +import java.util.Arrays; +import java.util.List; +import java.util.NoSuchElementException; + +/** The pack's object files in 3D, filed by their folders. */ +final class PackObjectsSceneView implements SceneView { + static final String ID = "iris:objects"; + private static final char FOLDER_SEPARATOR = '/'; + private static final int VARIANTS_OF_A_FILE = 1; + + @Override + public String id() { + return ID; + } + + @Override + public String label() { + return "Objects"; + } + + @Override + public String description() { + return "Every object file in the pack, in 3D"; + } + + @Override + public List entries(Engine engine) { + return Arrays.stream(engine.getData().getObjectLoader().getPossibleKeys()) + .sorted() + .map(PackObjectsSceneView::entryOf) + .toList(); + } + + @Override + public SceneBlocks scene(Engine engine, SceneRequest request) { + String key = request.key(); + IrisObject object = engine.getData().getObjectLoader().load(key); + if (object == null) { + throw new NoSuchElementException("No object file " + key); + } + return SceneBlocks.of(object); + } + + private static SceneEntry entryOf(String key) { + int lastSeparator = key.lastIndexOf(FOLDER_SEPARATOR); + String folder = lastSeparator < 0 ? "" : key.substring(0, lastSeparator); + return new SceneEntry(key, key.substring(lastSeparator + 1), folder, VARIANTS_OF_A_FILE); + } +} diff --git a/core/src/main/java/art/arcane/iris/studio/bridge/ProceduralObjectsSceneView.java b/core/src/main/java/art/arcane/iris/studio/bridge/ProceduralObjectsSceneView.java new file mode 100644 index 000000000..afc8bfd93 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/bridge/ProceduralObjectsSceneView.java @@ -0,0 +1,102 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 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.studio.bridge; + +import art.arcane.iris.generation.runtime.Engine; +import art.arcane.iris.pack.loading.IrisData; +import art.arcane.iris.structure.object.IrisObject; +import art.arcane.iris.studio.map.BakeRun; +import art.arcane.iris.studio.map.ObjectSource; +import art.arcane.iris.studio.map.ProceduralObjectSource; +import art.arcane.iris.studio.scene.SceneBakeTiming; +import art.arcane.iris.studio.scene.SceneBlocks; +import art.arcane.iris.studio.scene.SceneEntry; +import art.arcane.iris.studio.scene.SceneRequest; +import art.arcane.iris.studio.scene.SceneView; + +import java.util.List; +import java.util.NoSuchElementException; +import java.util.OptionalLong; + +/** The trees, rock formations and more that the pack generates from settings, every variant in 3D. */ +final class ProceduralObjectsSceneView implements SceneView { + static final String ID = "iris:objects/procedural"; + private static final String BAKE_STAGE = "Bake"; + private static final char FOLDER_SEPARATOR = '/'; + + private final ObjectSource source = new ProceduralObjectSource(); + + @Override + public String id() { + return ID; + } + + @Override + public String label() { + return "Procedural"; + } + + @Override + public String description() { + return "Trees, rock formations and more that Iris generates from settings, every variant in 3D"; + } + + @Override + public boolean isBaked() { + return true; + } + + @Override + public List entries(Engine engine) { + IrisData data = engine.getData(); + return source.keys(data).stream() + .sorted() + .map(key -> entryOf(key, source.variants(data, key).size())) + .toList(); + } + + @Override + public SceneBlocks scene(Engine engine, SceneRequest request) { + IrisData data = engine.getData(); + source.keys(data); + List variants = source.variants(data, request.key()); + if (variants.isEmpty()) { + throw new NoSuchElementException("No procedural object " + request.key()); + } + return SceneBlocks.of(variants.get(Math.floorMod(request.variant(), variants.size()))); + } + + @Override + public SceneBakeTiming timeBake(Engine engine, String key) { + IrisData data = engine.getData(); + source.keys(data); + OptionalLong seed = source.seed(key); + BakeRun run = seed.isEmpty() ? null : source.timeBake(data, key, seed.getAsLong()); + if (run == null) { + throw new NoSuchElementException("No procedural object " + key); + } + return new SceneBakeTiming(run.variantCount(), List.of(new SceneBakeTiming.Stage(BAKE_STAGE, run.totalNanos()))); + } + + private static SceneEntry entryOf(String key, int variantCount) { + int lastSeparator = key.lastIndexOf(FOLDER_SEPARATOR); + String folder = lastSeparator < 0 ? "" : key.substring(0, lastSeparator); + return new SceneEntry(key, key.substring(lastSeparator + 1), folder, Math.max(1, variantCount)); + } +} diff --git a/core/src/main/java/art/arcane/iris/studio/bridge/SceneFiles.java b/core/src/main/java/art/arcane/iris/studio/bridge/SceneFiles.java new file mode 100644 index 000000000..9a4aea782 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/bridge/SceneFiles.java @@ -0,0 +1,154 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 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.studio.bridge; + +import art.arcane.iris.studio.scene.EditableSceneView.Creation; + +import java.awt.Desktop; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.FileVisitResult; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.StandardCopyOption; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.ArrayList; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.regex.Pattern; + +/** The files of one creatable view's entries in a pack: written from the view's starter, looked up where used, and trashed. */ +final class SceneFiles { + private static final Pattern KEY = Pattern.compile("[a-z0-9_-]+(/[a-z0-9_-]+)*"); + private static final String FILE_EXTENSION = ".json"; + // The pack watcher only reloads for .json, .iob and .png files, so a file being written is not read half done. + static final String WRITING_SUFFIX = ".tmp"; + private static final String GENERATED_FOLDER_PREFIX = "."; + // The pack watcher ignores the .iris folder, so trashing a file there reloads the pack once, for the removal. + private static final String PACK_TRASH = ".iris/trash"; + private static final String DESKTOP_TRASH = "the trash"; + + /** Where the desktop moves a file to its trash; absent a desktop it moves nothing. */ + @FunctionalInterface + interface DesktopTrash { + /** @return whether the desktop took {@code file} to its trash */ + boolean take(Path file); + } + + private final Path packFolder; + private final Creation creation; + private final DesktopTrash desktopTrash; + + SceneFiles(Path packFolder, Creation creation, DesktopTrash desktopTrash) { + this.packFolder = packFolder; + this.creation = creation; + this.desktopTrash = desktopTrash; + } + + static DesktopTrash systemTrash() { + return file -> Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.MOVE_TO_TRASH) + && Desktop.getDesktop().moveToTrash(file.toFile()); + } + + /** @return why {@code key} can't name an entry, or null when it can */ + static String refusalOfKey(String key) { + if (key.isBlank()) { + return "Give it a name"; + } + return KEY.matcher(key).matches() ? null : "Use lower case letters, digits, - and _, with / between folders"; + } + + /** + * Writes a new entry from the starter text at {@code key}. + * + * @throws IllegalArgumentException naming why, when {@code key} can't name a new entry or the starter is not JSON + */ + Path create(String key) throws IOException { + Path file = fileOf(key); + if (Files.exists(file)) { + throw new IllegalArgumentException(key + " already exists"); + } + JsonText.parse(creation.starter()); + Files.createDirectories(file.getParent()); + Path written = file.resolveSibling(file.getFileName() + WRITING_SUFFIX); + Files.writeString(written, creation.starter(), StandardCharsets.UTF_8); + Files.move(written, file, StandardCopyOption.ATOMIC_MOVE); + return file; + } + + /** + * The pack's files that name the entry at {@code key}, such as the biomes that place it, below the pack. Folders + * starting with a dot hold what the studio generates, like the schema, and are left out. + */ + List usesOf(String key) throws IOException { + String reference = "\"" + creation.referencePrefix() + key + "\""; + Path own = fileOf(key); + List using = new ArrayList<>(); + Files.walkFileTree(packFolder, new SimpleFileVisitor<>() { + @Override + public FileVisitResult preVisitDirectory(Path folder, BasicFileAttributes attributes) { + boolean generated = !folder.equals(packFolder) && folder.getFileName().toString().startsWith(GENERATED_FOLDER_PREFIX); + return generated ? FileVisitResult.SKIP_SUBTREE : FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException { + if (!file.equals(own) && file.getFileName().toString().endsWith(FILE_EXTENSION) && namesIn(file, reference)) { + using.add(packFolder.relativize(file).toString().replace('\\', '/')); + } + return FileVisitResult.CONTINUE; + } + }); + using.sort(null); + return using; + } + + /** + * Moves the entry at {@code key} to the desktop's trash, or where the desktop has none, to the pack's + * {@code .iris/trash}; returns where it went, to tell. + * + * @throws NoSuchElementException when the entry has no file + */ + String moveToTrash(String key) throws IOException { + Path file = fileOf(key); + if (!Files.isRegularFile(file)) { + throw new NoSuchElementException("Entry " + key + " has no file at " + packFolder.relativize(file)); + } + if (desktopTrash.take(file)) { + return DESKTOP_TRASH; + } + Path trashed = packFolder.resolve(PACK_TRASH).resolve(key.replace('/', '_') + "-" + System.currentTimeMillis() + FILE_EXTENSION); + Files.createDirectories(trashed.getParent()); + Files.move(file, trashed); + return PACK_TRASH; + } + + private Path fileOf(String key) { + String refusal = refusalOfKey(key); + if (refusal != null) { + throw new IllegalArgumentException(refusal); + } + return packFolder.resolve(creation.folder()).resolve(key + FILE_EXTENSION); + } + + private static boolean namesIn(Path file, String reference) throws IOException { + return new String(Files.readAllBytes(file), StandardCharsets.UTF_8).contains(reference); + } +} diff --git a/core/src/main/java/art/arcane/iris/studio/bridge/SettingsTypes.java b/core/src/main/java/art/arcane/iris/studio/bridge/SettingsTypes.java new file mode 100644 index 000000000..95a3c4e47 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/bridge/SettingsTypes.java @@ -0,0 +1,245 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 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.studio.bridge; + +import art.arcane.iris.pack.loading.IrisRegistrant; +import art.arcane.iris.pack.schema.annotation.ArrayType; +import art.arcane.iris.pack.schema.annotation.MaxNumber; +import art.arcane.iris.pack.schema.annotation.MinNumber; +import art.arcane.iris.pack.schema.annotation.RegistryListBlockType; +import art.arcane.iris.pack.schema.annotation.RegistryListResource; +import art.arcane.iris.pack.schema.annotation.Required; +import art.arcane.iris.platform.reflect.KeyedType; +import art.arcane.volmlib.util.documentation.Description; +import com.google.gson.Gson; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Deque; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * The settings types of the pack as the node editor shows them, read from the pack's classes and the same annotations + * the pack's schema is written from: each setting's kind, limits, default and description. + */ +final class SettingsTypes { + /** The reference a block setting names, which the studio asks {@link StudioSuggestions} the blocks of. */ + static final String BLOCK_REFERENCE = "BLOCK_TYPE"; + private static final String IRIS_PACKAGE = "art.arcane.iris."; + private static final String PLAIN_FORMAT = "PLAIN"; + private static final String KIND = "kind"; + private static final Gson GSON = new Gson(); + + private SettingsTypes() { + } + + /** {@code roots} and the types inside them, by class name. */ + static Map reachableFrom(Collection> roots) { + Map described = new LinkedHashMap<>(); + Deque> pending = new ArrayDeque<>(roots); + while (!pending.isEmpty()) { + Class type = pending.pop(); + if (described.containsKey(type.getName())) { + continue; + } + Object defaults = newInstanceOrNull(type); + List options = settingsOf(type).stream().map(field -> optionOf(field, defaults, pending)).toList(); + described.put(type.getName(), new TypeWire(descriptionOf(type.getAnnotation(Description.class)), options)); + } + return described; + } + + /** Whether a setting of {@code type} is an object of settings of its own, such as a palette, rather than a plain value. */ + private static boolean isSettingsObject(Class type) { + return type.getName().startsWith(IRIS_PACKAGE) && !type.isEnum() && !type.isArray() + && !KeyedType.isKeyed(type) && !Collection.class.isAssignableFrom(type) && !Map.class.isAssignableFrom(type); + } + + // The fields a file can set, a parent class's first, as the pack reads them. + private static List settingsOf(Class type) { + List settings = new ArrayList<>(); + Class parent = type.getSuperclass(); + if (parent != null && parent.getName().startsWith(IRIS_PACKAGE)) { + settings.addAll(settingsOf(parent)); + } + Arrays.stream(type.getDeclaredFields()) + .filter(field -> !Modifier.isStatic(field.getModifiers()) && !Modifier.isFinal(field.getModifiers()) + && !Modifier.isTransient(field.getModifiers())) + .forEach(settings::add); + return settings; + } + + private static OptionWire optionOf(Field field, Object defaults, Deque> pending) { + MinNumber minimum = field.getAnnotation(MinNumber.class); + MaxNumber maximum = field.getAnnotation(MaxNumber.class); + ArrayType arrayType = field.getAnnotation(ArrayType.class); + Integer minItems = arrayType == null || arrayType.min() <= 0 ? null : arrayType.min(); + return new OptionWire(field.getName(), descriptionOf(field.getAnnotation(Description.class)), field.isAnnotationPresent(Required.class), + minimum == null ? null : minimum.value(), maximum == null ? null : maximum.value(), minItems, + defaultOf(field, defaults), kindOf(field, pending)); + } + + private static Map kindOf(Field field, Deque> pending) { + Class type = field.getType(); + if (Collection.class.isAssignableFrom(type)) { + return listOf(kindOfValue(elementTypeOf(field), field, pending)); + } + if (Map.class.isAssignableFrom(type)) { + return wire("map", "value", kindOfValue(typeArgument(field, 1), field, pending)); + } + return kindOfValue(type, field, pending); + } + + // A list's or map's elements take the registry the field names, as a list of blocks does. + private static Map kindOfValue(Class type, Field field, Deque> pending) { + if (type == null) { + return wire("any"); + } + if (type == boolean.class || type == Boolean.class) { + return wire("boolean"); + } + if (type == int.class || type == long.class || type == short.class || type == byte.class || type == Integer.class || type == Long.class) { + return wire("integer"); + } + if (type == double.class || type == float.class || type == Double.class || type == Float.class) { + return wire("decimal"); + } + if (type == String.class) { + return textKindOf(field); + } + if (type.isEnum()) { + return wire("enum", "constants", Arrays.stream(type.getEnumConstants()).map(constant -> constantOf((Enum) constant)).toList()); + } + if (KeyedType.isKeyed(type)) { + return wire("enum", "constants", Arrays.stream(KeyedType.values(type)).map(name -> Map.of("name", name, "description", "")).toList()); + } + if (isSettingsObject(type)) { + pending.add(type); + return wire("object", "type", type.getName()); + } + return wire("any"); + } + + private static Map textKindOf(Field field) { + if (field.isAnnotationPresent(RegistryListBlockType.class)) { + return wire("reference", "reference", BLOCK_REFERENCE, "format", PLAIN_FORMAT); + } + RegistryListResource resource = field.getAnnotation(RegistryListResource.class); + String folder = resource == null ? null : folderOf(resource.value()); + if (folder != null) { + return wire("resource", "resource", folder); + } + return wire("text", "format", PLAIN_FORMAT); + } + + private static String folderOf(Class registrant) { + Object instance = newInstanceOrNull(registrant); + return instance instanceof IrisRegistrant resource ? resource.getFolderName() : null; + } + + private static Map listOf(Map element) { + Map list = wire("list", "element", element); + list.put("unique", false); + return list; + } + + private static Class elementTypeOf(Field field) { + ArrayType arrayType = field.getAnnotation(ArrayType.class); + return arrayType != null ? arrayType.type() : typeArgument(field, 0); + } + + private static Class typeArgument(Field field, int index) { + if (!(field.getGenericType() instanceof ParameterizedType parameterized) || parameterized.getActualTypeArguments().length <= index) { + return null; + } + Type argument = parameterized.getActualTypeArguments()[index]; + return argument instanceof Class type ? type : null; + } + + private static Map constantOf(Enum constant) { + try { + Description description = constant.getDeclaringClass().getField(constant.name()).getAnnotation(Description.class); + return Map.of("name", constant.name(), "description", descriptionOf(description)); + } catch (NoSuchFieldException undocumented) { + return Map.of("name", constant.name(), "description", ""); + } + } + + // Only plain values are shown as defaults; an object or list is described by its own settings. + private static Object defaultOf(Field field, Object defaults) { + if (defaults == null) { + return null; + } + Object value; + try { + field.setAccessible(true); + value = field.get(defaults); + } catch (ReflectiveOperationException | RuntimeException unreadable) { + return null; + } + return switch (value) { + case null -> null; + case Boolean plain -> plain; + case Number plain -> plain; + case String plain -> plain; + case Enum constant -> constant.name(); + default -> null; + }; + } + + private static Object newInstanceOrNull(Class type) { + try { + var constructor = type.getDeclaredConstructor(); + constructor.setAccessible(true); + return constructor.newInstance(); + } catch (ReflectiveOperationException | RuntimeException | LinkageError noPlainConstructor) { + return null; + } + } + + private static String descriptionOf(Description description) { + return description == null ? "" : description.value(); + } + + private static Map wire(String kind, Object... members) { + Map wire = new LinkedHashMap<>(); + wire.put(KIND, kind); + for (int index = 0; index + 1 < members.length; index += 2) { + wire.put((String) members[index], members[index + 1]); + } + return wire; + } + + /** A settings type: what it is for, and the settings a file of it may write. */ + record TypeWire(String description, List options) { + } + + /** One setting; a limit or default the pack does not give is null. */ + record OptionWire(String name, String description, boolean required, Double minimum, Double maximum, Integer minItems, + Object defaultValue, Map kind) { + } +} diff --git a/core/src/main/java/art/arcane/iris/studio/bridge/StudioBridge.java b/core/src/main/java/art/arcane/iris/studio/bridge/StudioBridge.java index 92aaeb5bb..b889ad70c 100644 --- a/core/src/main/java/art/arcane/iris/studio/bridge/StudioBridge.java +++ b/core/src/main/java/art/arcane/iris/studio/bridge/StudioBridge.java @@ -26,6 +26,13 @@ import art.arcane.iris.studio.imagemap.ImageMapPreviews; import art.arcane.iris.studio.map.PalettePatterns; import art.arcane.iris.studio.noise.NoiseSources; import art.arcane.iris.studio.noise.NoiseTile; +import art.arcane.iris.studio.scene.SceneBakeTiming; +import art.arcane.iris.studio.scene.SceneBlocks; +import art.arcane.iris.studio.scene.SceneEntry; +import art.arcane.iris.studio.scene.SceneForm; +import art.arcane.iris.studio.scene.SceneRequest; +import art.arcane.iris.studio.scene.SceneSizes; +import art.arcane.iris.studio.scene.SceneView; import art.arcane.iris.studio.view.GuiHost; import art.arcane.iris.studio.view.GuiMarker; import art.arcane.iris.studio.view.PregenRenderSnapshot; @@ -90,6 +97,7 @@ public final class StudioBridge implements AutoCloseable { private static final String ASSET_RETRY_SECONDS = "2"; private static final long ASSET_CACHE_SECONDS = 86_400L; private static final String OVERRIDE_PREFIX = "set."; + private static final int LARGEST_BODY_BYTES = 4 * 1024 * 1024; private static final String VIEW_BIOMES = "biomes"; private static final String VIEW_REGIONS = "regions"; private static final String VIEW_RIVERS = "rivers"; @@ -97,8 +105,10 @@ public final class StudioBridge implements AutoCloseable { static final int STATUS_NO_CONTENT = 204; static final int STATUS_BAD_REQUEST = 400; static final int STATUS_UNAUTHORIZED = 401; + static final int STATUS_FORBIDDEN = 403; static final int STATUS_NOT_FOUND = 404; static final int STATUS_METHOD_NOT_ALLOWED = 405; + static final int STATUS_CONFLICT = 409; static final int STATUS_UNPROCESSABLE = 422; static final int STATUS_SERVER_ERROR = 500; static final int STATUS_UNAVAILABLE = 503; @@ -137,6 +147,7 @@ public final class StudioBridge implements AutoCloseable { private final ExecutorService workers; private final ScheduledExecutorService ticker; private final StudioEvents events; + private final StudioScenes scenes = new StudioScenes(); private final Runnable hotloadHook; private final Cache droppedTiles = Caffeine.newBuilder().expireAfterWrite(DROPPED_TILE_KEPT_MINUTES, TimeUnit.MINUTES).build(); private volatile boolean closed; @@ -239,11 +250,19 @@ public final class StudioBridge implements AutoCloseable { case "picks" -> sendJson(exchange, STATUS_OK, new PickInspection("", List.of())); case "regions" -> sendJson(exchange, STATUS_OK, StudioHover.previewableRegions(get(exchange).engine())); case "entities" -> sendJson(exchange, STATUS_OK, entities(get(exchange))); - case "scenes" -> sendJson(exchange, STATUS_OK, profileViews()); - case "scene-entries" -> sendJson(exchange, STATUS_OK, profileEntries(get(exchange).engine(), query)); - case "scene" -> sendBytes(exchange, "application/octet-stream", profileScene(get(exchange).engine(), query)); + case "scenes" -> sendJson(exchange, STATUS_OK, scenes.infos()); + case "scene-entries" -> sendJson(exchange, STATUS_OK, sceneEntries(get(exchange).engine(), query)); + case "scene" -> sendBytes(exchange, "application/octet-stream", scene(get(exchange).engine(), query).encode(gson)); + case "scene-parts" -> sendBytes(exchange, "application/octet-stream", StudioScenes.encodeParts(scene(get(exchange).engine(), query))); + case "profile-form" -> sendJson(exchange, STATUS_OK, sceneForm(get(exchange).engine(), query)); case "scene-bake" -> sendJson(exchange, STATUS_OK, sceneBake(get(exchange).engine(), query)); - case "profile-form" -> sendJson(exchange, STATUS_OK, profileForm(get(exchange).engine(), query)); + case "scene-file" -> sendJson(exchange, STATUS_OK, sceneFile(get(exchange).engine(), query)); + case "scene-edit" -> sendJson(exchange, STATUS_OK, sceneEdit(exchange, query)); + case "scene-write" -> sendJson(exchange, STATUS_OK, sceneWrite(exchange, query)); + case "scene-create" -> sendJson(exchange, STATUS_OK, sceneCreate(exchange, query)); + case "scene-uses" -> sendJson(exchange, STATUS_OK, sceneUses(get(exchange).engine(), query)); + case "scene-delete" -> sendJson(exchange, STATUS_OK, sceneDelete(exchange, query)); + case "suggestions" -> sendJson(exchange, STATUS_OK, suggestions(get(exchange).engine(), query)); case "noise-sources" -> sendJson(exchange, STATUS_OK, NoiseSources.of(get(exchange).engine()).list()); case "noise-tile" -> sendBytes(exchange, "application/octet-stream", noiseTile(get(exchange).engine(), query)); case "patterns" -> sendJson(exchange, STATUS_OK, List.of(PALETTES_VIEW)); @@ -253,7 +272,7 @@ public final class StudioBridge implements AutoCloseable { case "pregen-map" -> sendBytes(exchange, "image/png", pregenMap(exchange)); case "pregen-pause" -> sendJson(exchange, STATUS_OK, pregenPause(exchange)); case "image-maps" -> sendJson(exchange, STATUS_OK, ImageMapPreviews.entries(get(exchange).engine())); - case "image-map" -> sendJson(exchange, STATUS_OK, profiling(() -> ImageMapPreviews.details(get(exchange).engine(), query.text("key")))); + case "image-map" -> sendJson(exchange, STATUS_OK, answering(() -> ImageMapPreviews.details(get(exchange).engine(), query.text("key")))); case "image-map-preview" -> sendBytes(exchange, "image/png", imageMapPreview(get(exchange).engine(), query)); case "saved-worlds" -> sendJson(exchange, STATUS_OK, List.of()); case "events" -> streamEvents(exchange); @@ -382,7 +401,7 @@ public final class StudioBridge implements AutoCloseable { private static byte[] imageMapPreview(Engine engine, Query query) { try { - return profiling(() -> ImageMapPreviews.preview(engine, query.text("key"), query.whole("size", DEFAULT_IMAGE_MAP_PREVIEW_PIXELS))); + return answering(() -> ImageMapPreviews.preview(engine, query.text("key"), query.whole("size", DEFAULT_IMAGE_MAP_PREVIEW_PIXELS))); } catch (IllegalArgumentException refused) { throw new RequestError(STATUS_BAD_REQUEST, refused.getMessage()); } @@ -458,43 +477,51 @@ public final class StudioBridge implements AutoCloseable { sendBytes(exchange, endpoint.endsWith(".png") ? "image/png" : "application/json", asset); } - private static List profileViews() { - return StudioProfiles.views().stream() - .map(view -> new SceneViewInfo(view.id(), view.label(), view.description(), false, false, view.isBaked(), false, view.sizes(), view.hasForm())) - .toList(); + private List sceneEntries(Engine engine, Query query) { + return answering(() -> sceneView(query).entries(engine)); } - private static List profileEntries(Engine engine, Query query) { - return profileView(query).entries(engine); + private SceneForm sceneForm(Engine engine, Query query) { + SceneView view = sceneView(query); + if (!view.hasForm()) { + throw new RequestError(STATUS_NOT_FOUND, "The entries of " + view.id() + " have no settings form"); + } + return answering(() -> view.form(engine, query.text("key"), query.prefixed(OVERRIDE_PREFIX))); } - private static StudioObjects.BakeTiming sceneBake(Engine engine, Query query) { - StudioProfiles.ProfileView view = profileView(query); + private SceneBakeTiming sceneBake(Engine engine, Query query) { + SceneView view = sceneView(query); if (!view.isBaked()) { - throw new RequestError(STATUS_BAD_REQUEST, "View " + view.id() + " is not baked"); + throw new RequestError(STATUS_NOT_FOUND, "The entries of " + view.id() + " are not baked"); } - return profiling(() -> view.timeBake(engine, query.text("key"))); + return answering(() -> view.timeBake(engine, query.text("key"))); } - private static ProfileForm.Form profileForm(Engine engine, Query query) { - return profiling(() -> profileView(query).form(engine, query.text("key"), query.prefixed(OVERRIDE_PREFIX))); + private SceneBlocks scene(Engine engine, Query query) { + SceneView view = sceneView(query); + SceneRequest request = new SceneRequest(query.text("key"), query.whole("variant", 0), sizeOf(view, query), query.prefixed(OVERRIDE_PREFIX)); + return answering(() -> view.scene(engine, request)); } - private byte[] profileScene(Engine engine, Query query) { - StudioProfiles.ProfileView view = profileView(query); - int size = query.whole("size", view.sizes() == null ? 0 : view.sizes().opening()); - if (view.sizes() != null && !view.sizes().blocksAcross().contains(size)) { - throw new RequestError(STATUS_BAD_REQUEST, "View " + view.id() + " builds scenes " + view.sizes().blocksAcross() + " blocks across, not " + size); + // A view with sizes is asked at one of them, the one it opens with when the studio names none. + private static int sizeOf(SceneView view, Query query) { + SceneSizes sizes = view.sizes(); + if (sizes == null) { + return 0; } - return profiling(() -> view.scene(engine, query.text("key"), query.whole("variant", 0), size, query.prefixed(OVERRIDE_PREFIX)).encode(gson)); + int size = query.whole("size", sizes.opening()); + if (!sizes.blocksAcross().contains(size)) { + throw new RequestError(STATUS_BAD_REQUEST, "View " + view.id() + " builds scenes " + sizes.blocksAcross() + " blocks across, not " + size); + } + return size; } - private static StudioProfiles.ProfileView profileView(Query query) { - return profiling(() -> StudioProfiles.view(query.text("view"))); + private SceneView sceneView(Query query) { + return answering(() -> scenes.view(query.text("view"))); } - // A profile the pack does not have is the studio's to be told about, not a failure of the bridge. - private static T profiling(ProfileTask task) { + // An entry the pack does not have is the studio's to be told about, not a failure of the bridge. + private static T answering(SceneTask task) { try { return task.run(); } catch (NoSuchElementException unknown) { @@ -505,10 +532,81 @@ public final class StudioBridge implements AutoCloseable { } @FunctionalInterface - private interface ProfileTask { + private interface SceneTask { T run() throws IOException; } + private StudioEditors.EditorState sceneFile(Engine engine, Query query) { + return editing(() -> editorsOf(engine).read(query.text("view"), query.text("key"))); + } + + private StudioEditors.EditorState sceneEdit(HttpExchange exchange, Query query) throws IOException { + Engine engine = post(exchange).engine(); + String body = readBody(exchange); + return editing(() -> { + GraphEditRequest request = GraphEditRequest.parse(body); + return editorsOf(engine).edit(query.text("view"), query.text("key"), request.revision(), request.edit()); + }); + } + + private StudioEditors.EditorState sceneWrite(HttpExchange exchange, Query query) throws IOException { + Engine engine = post(exchange).engine(); + String body = readBody(exchange); + return editing(() -> { + GraphEditRequest.FileWrite write = GraphEditRequest.FileWrite.parse(body); + return editorsOf(engine).write(query.text("view"), query.text("key"), write.revision(), write.text()); + }); + } + + private MessageBody sceneCreate(HttpExchange exchange, Query query) { + Engine engine = post(exchange).engine(); + return editing(() -> { + editorsOf(engine).create(query.text("view"), query.text("key")); + return new MessageBody("Created " + query.text("key")); + }); + } + + private UsesBody sceneUses(Engine engine, Query query) { + return editing(() -> new UsesBody(editorsOf(engine).usesOf(query.text("view"), query.text("key")))); + } + + private TrashedBody sceneDelete(HttpExchange exchange, Query query) { + Engine engine = post(exchange).engine(); + return editing(() -> new TrashedBody(editorsOf(engine).delete(query.text("view"), query.text("key")))); + } + + // What a setting naming a block (reference) or a pack resource (resource) may be typed as. + private static List suggestions(Engine engine, Query query) { + return answering(() -> query.has("reference") + ? StudioSuggestions.ofReference(engine.getData(), query.text("reference")) + : StudioSuggestions.ofResource(engine.getData(), query.text("resource"))); + } + + private StudioEditors editorsOf(Engine engine) { + return new StudioEditors(scenes, engine, SceneFiles.systemTrash()); + } + + // A refused edit is the user's to fix, so it answers with why rather than as a failure of the bridge. + private static T editing(SceneTask task) { + try { + return answering(task); + } catch (StudioEditors.StaleEditException stale) { + throw new RequestError(STATUS_CONFLICT, stale.getMessage()); + } catch (StudioEditors.EditsLockedException locked) { + throw new RequestError(STATUS_FORBIDDEN, locked.getMessage()); + } catch (IllegalArgumentException refused) { + throw new RequestError(STATUS_UNPROCESSABLE, refused.getMessage()); + } + } + + private static String readBody(HttpExchange exchange) throws IOException { + byte[] body = exchange.getRequestBody().readNBytes(LARGEST_BODY_BYTES + 1); + if (body.length > LARGEST_BODY_BYTES) { + throw new RequestError(STATUS_BAD_REQUEST, "The body is over " + LARGEST_BODY_BYTES + " bytes"); + } + return new String(body, StandardCharsets.UTF_8); + } + private void cancelTile(HttpExchange exchange, Query query) throws IOException { requireMethod(exchange, "POST"); droppedFlagOf(query.text("request")).set(true); @@ -701,11 +799,6 @@ public final class StudioBridge implements AutoCloseable { private record MessageBody(String message) { } - /** A profile view as the studio lists its scene views; {@code form} when its entries have a settings form. */ - private record SceneViewInfo(String id, String label, String description, boolean editable, boolean creatable, boolean baked, - boolean parts, StudioProfiles.Sizes sizes, boolean form) { - } - /** @param snapshot null while no pregeneration runs */ private record PregenStatus(boolean active, PregenRenderSnapshot snapshot) { } @@ -714,6 +807,14 @@ public final class StudioBridge implements AutoCloseable { private record ModuleViewInfo(String id, String label, String description) { } + /** The pack files that still name an entry. */ + private record UsesBody(List files) { + } + + /** Where a deleted entry's file went. */ + private record TrashedBody(String to) { + } + private record PickInspection(String detail, List sections) { } @@ -724,4 +825,4 @@ public final class StudioBridge implements AutoCloseable { private record ViewInfo(String id, String label, String description, String group, String groupLabel) { } -} +} \ No newline at end of file diff --git a/core/src/main/java/art/arcane/iris/studio/bridge/StudioEditors.java b/core/src/main/java/art/arcane/iris/studio/bridge/StudioEditors.java new file mode 100644 index 000000000..a3f87cb44 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/bridge/StudioEditors.java @@ -0,0 +1,280 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 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.studio.bridge; + +import art.arcane.iris.generation.runtime.Engine; +import art.arcane.iris.studio.scene.EditableSceneView; +import art.arcane.iris.studio.scene.GraphNode; +import art.arcane.iris.studio.scene.JsonPath; +import com.google.gson.JsonObject; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Set; + +/** + * Reads and edits the files of editable scene views' entries for the studio. Every edit is made on the text as it was + * read, named by its revision, and splices only the values it changes, so the rest of the file stays as written. + */ +final class StudioEditors { + // Only a studio world reloads its pack when a file changes; elsewhere an edit would show nothing until a restart. + private static final String LOCKED_OUTSIDE_STUDIO = "Open the pack in a studio world to edit it"; + private static final String NOT_AN_OBJECT = "The file does not hold a JSON object"; + + private final StudioScenes scenes; + private final Engine engine; + // A studio world generates from a copy of the pack; edits go to the pack itself, which the world reloads from. + private final Path packFolder; + private final Path loadedFolder; + private final SceneFiles.DesktopTrash desktopTrash; + + StudioEditors(StudioScenes scenes, Engine engine, SceneFiles.DesktopTrash desktopTrash) { + this.scenes = scenes; + this.engine = engine; + this.packFolder = engine.getPackSource().toAbsolutePath().normalize(); + this.loadedFolder = engine.getData().getDataFolder().toPath().toAbsolutePath().normalize(); + this.desktopTrash = desktopTrash; + } + + /** + * The entry's file as it is now. + * + * @throws NoSuchElementException when there is no such view, or the entry has no file of its own + */ + EditorState read(String viewId, String key) throws IOException { + Path file = fileOf(viewId, key); + return stateOf(viewId, key, file, Files.readString(file, StandardCharsets.UTF_8)); + } + + /** + * Makes {@code edit} and saves the file. + * + * @param revision the {@link EditorState#revision()} the edit was made on + * @throws StaleEditException when the file changed since {@code revision} + * @throws EditsLockedException when the world is not a studio world + * @throws IllegalArgumentException naming why, when the edit does not fit the file + */ + EditorState edit(String viewId, String key, String revision, GraphEdit edit) throws IOException { + requireStudioWorld(); + Path file = fileOf(viewId, key); + JsonSplicer splicer = new JsonSplicer(JsonText.parse(currentText(file, revision))); + String edited = splicer.apply(edit.splices(splicer)); + JsonText.parse(edited); + return save(viewId, key, file, edited); + } + + /** + * Replaces the whole file, as undoing and redoing do. + * + * @throws StaleEditException when the file changed since {@code revision} + * @throws EditsLockedException when the world is not a studio world + * @throws IllegalArgumentException when {@code text} is not JSON + */ + EditorState write(String viewId, String key, String revision, String text) throws IOException { + requireStudioWorld(); + Path file = fileOf(viewId, key); + currentText(file, revision); + JsonText.parse(text); + return save(viewId, key, file, text); + } + + /** + * Writes a new entry {@code key} of the view from its starter text. The entry shows once the pack has reloaded. + * + * @throws EditsLockedException when the world is not a studio world + * @throws IllegalArgumentException naming why, when {@code key} can't name a new entry + * @throws NoSuchElementException when there is no such view, or its entries can't be created + */ + void create(String viewId, String key) throws IOException { + requireStudioWorld(); + files(viewId).create(key); + } + + /** + * The files of the pack that still name entry {@code key}, which a removal would leave without it. + * + * @throws NoSuchElementException when there is no such view, or its entries can't be removed + */ + List usesOf(String viewId, String key) throws IOException { + return files(viewId).usesOf(key); + } + + /** + * Moves entry {@code key} to the trash and tells where it went. + * + * @throws EditsLockedException when the world is not a studio world + * @throws NoSuchElementException when there is no such view, or the entry has no file + */ + String delete(String viewId, String key) throws IOException { + requireStudioWorld(); + return files(viewId).moveToTrash(key); + } + + private SceneFiles files(String viewId) { + EditableSceneView.Creation creation = scenes.editableView(viewId).creation() + .orElseThrow(() -> new NoSuchElementException("The entries of " + viewId + " can't be created or removed")); + return new SceneFiles(packFolder, creation, desktopTrash); + } + + private void requireStudioWorld() { + if (!engine.isStudio()) { + throw new EditsLockedException(LOCKED_OUTSIDE_STUDIO); + } + } + + private String lockedReason() { + return engine.isStudio() ? null : LOCKED_OUTSIDE_STUDIO; + } + + private static String currentText(Path file, String revision) throws IOException { + String text = Files.readString(file, StandardCharsets.UTF_8); + if (!revisionOf(text).equals(revision)) { + throw new StaleEditException(); + } + return text; + } + + // Written beside the file and moved over it, so the pack watcher never reads it half written. + private EditorState save(String viewId, String key, Path file, String text) throws IOException { + Path written = file.resolveSibling(file.getFileName() + SceneFiles.WRITING_SUFFIX); + Files.writeString(written, text, StandardCharsets.UTF_8); + Files.move(written, file, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + return stateOf(viewId, key, file, text); + } + + private Path fileOf(String viewId, String key) { + Path loaded = scenes.editableView(viewId).fileOf(engine, key) + .orElseThrow(() -> new NoSuchElementException("Entry " + key + " has no file to edit")) + .toPath().toAbsolutePath().normalize(); + if (!loaded.startsWith(loadedFolder)) { + throw new NoSuchElementException("Entry " + key + " has no file in the pack"); + } + Path file = packFolder.resolve(loadedFolder.relativize(loaded)); + if (!Files.isRegularFile(file)) { + throw new NoSuchElementException("Entry " + key + " has no file in the pack"); + } + return file; + } + + // A file that is no longer JSON, or that the view can't read as nodes, is still shown, with why. + private EditorState stateOf(String viewId, String key, Path file, String text) { + String fileName = packFolder.relativize(file).toString().replace('\\', '/'); + String revision = revisionOf(text); + JsonText source; + try { + source = JsonText.parse(text); + } catch (IllegalArgumentException notJson) { + return EditorState.unreadable(fileName, revision, text, notJson.getMessage(), lockedReason()); + } + if (!(source.toGson() instanceof JsonObject root)) { + return EditorState.unreadable(fileName, revision, text, NOT_AN_OBJECT, lockedReason()); + } + List graph; + try { + graph = scenes.editableView(viewId).graph(engine, key, root); + } catch (IllegalArgumentException refused) { + return EditorState.unreadable(fileName, revision, text, String.valueOf(refused.getMessage()), lockedReason()); + } + Set> types = new LinkedHashSet<>(); + List roots = graph.stream().map(node -> NodeWire.of(node, types)).toList(); + return new EditorState(fileName, revision, text, roots, null, lockedReason(), SettingsTypes.reachableFrom(types)); + } + + static String revisionOf(String text) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException missing) { + throw new IllegalStateException("The JVM has no SHA-256", missing); + } + } + + /** + * An entry's file as the studio shows it. + * + * @param file where it is below the pack folder + * @param revision tells this text from any other, so an edit made on an older one is refused + * @param roots the file as nodes; null when it can't be read as nodes, and {@code problem} says why + * @param locked why the file can't be edited here; null when it can + * @param types the settings types the nodes show, by class name + */ + record EditorState(String file, String revision, String text, List roots, String problem, String locked, + Map types) { + static EditorState unreadable(String file, String revision, String text, String problem, String locked) { + return new EditorState(file, revision, text, null, problem, locked, Map.of()); + } + } + + /** A {@link GraphNode} as the studio reads it: paths as arrays of member names and indices, settings types by class name. */ + record NodeWire(String kind, String title, List path, int partId, List roles, List settings, + List children, List childList, boolean movable, boolean duplicable, List additions) { + static NodeWire of(GraphNode node, Set> types) { + List settings = node.settings().stream().map(section -> { + types.add(section.type()); + return new SettingsWire(section.title(), stepsOf(section.path()), section.type().getName(), List.copyOf(section.shownAsNodes())); + }).toList(); + List children = node.children().stream().map(link -> new LinkWire(link.wire(), of(link.node(), types))).toList(); + GraphNode.Edits edits = node.edits(); + List additions = edits.additions().stream() + .map(addition -> new AdditionWire(addition.label(), stepsOf(addition.list()), addition.literal())) + .toList(); + return new NodeWire(node.kind(), node.title(), stepsOf(node.path()), node.part(), node.roles(), settings, children, + edits.childList().map(NodeWire::stepsOf).orElse(null), edits.movable(), node.path().isElement(), additions); + } + + static List stepsOf(JsonPath path) { + return path.steps().stream().map(step -> switch (step) { + case JsonPath.Key(String name) -> name; + case JsonPath.Index(int position) -> position; + }).toList(); + } + } + + record SettingsWire(String title, List path, String type, List shownAsNodes) { + } + + record LinkWire(String wire, NodeWire node) { + } + + record AdditionWire(String label, List list, String literal) { + } + + /** The file changed since the text an edit was made on, such as in a text editor. */ + static final class StaleEditException extends RuntimeException { + StaleEditException() { + super("The file changed elsewhere; it was read again"); + } + } + + /** Edits are refused where the world would not show them, naming why. */ + static final class EditsLockedException extends RuntimeException { + EditsLockedException(String reason) { + super(reason); + } + } +} diff --git a/core/src/main/java/art/arcane/iris/studio/bridge/StudioObjects.java b/core/src/main/java/art/arcane/iris/studio/bridge/StudioObjects.java deleted file mode 100644 index 902c0c65e..000000000 --- a/core/src/main/java/art/arcane/iris/studio/bridge/StudioObjects.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 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.studio.bridge; - -import art.arcane.iris.generation.runtime.Engine; -import art.arcane.iris.pack.loading.IrisData; -import art.arcane.iris.structure.object.IrisObject; -import art.arcane.iris.studio.map.BakeRun; -import art.arcane.iris.studio.map.ObjectSource; -import art.arcane.iris.studio.map.PackObjectSource; -import art.arcane.iris.studio.map.ProceduralObjectSource; - -import java.util.Comparator; -import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.OptionalLong; - -/** The studio's views of the pack's object files and of the procedural objects its biomes and regions bake, as block scenes. */ -final class StudioObjects implements StudioProfiles.ProfileView { - static final String OBJECTS = "iris:objects"; - static final String PROCEDURAL = "iris:objects/procedural"; - private static final String BAKE_STAGE = "Bake"; - - private final String id; - private final String label; - private final String description; - private final ObjectSource source; - - private StudioObjects(String id, String label, String description, ObjectSource source) { - this.id = id; - this.label = label; - this.description = description; - this.source = source; - } - - static StudioObjects packObjects() { - return new StudioObjects(OBJECTS, "Objects", "Every object in the pack in 3D, with the blocks it is made of", new PackObjectSource()); - } - - static StudioObjects proceduralObjects() { - return new StudioObjects(PROCEDURAL, "Procedural", - "Trees, rock formations and more that Iris generates from settings, every variant in 3D", new ProceduralObjectSource()); - } - - /** One timed bake of a procedural entry, as the studio's bake meter reads it. */ - record BakeTiming(int variantCount, List stages) { - record Stage(String label, long nanos) { - } - } - - @Override - public String id() { - return id; - } - - @Override - public String label() { - return label; - } - - @Override - public String description() { - return description; - } - - @Override - public StudioProfiles.Sizes sizes() { - return null; - } - - @Override - public boolean hasForm() { - return false; - } - - @Override - public boolean isBaked() { - return source.isBaked(); - } - - @Override - public List entries(Engine engine) { - IrisData data = engine.getData(); - return source.keys(data).stream() - .sorted(Comparator.naturalOrder()) - .map(key -> new StudioProfiles.Entry(key, nameOf(key), folderOf(key), Math.max(1, source.variants(data, key).size()))) - .toList(); - } - - @Override - public ProfileForm.Form form(Engine engine, String key, Map overrides) { - throw new NoSuchElementException(id + " has no settings form"); - } - - @Override - public SceneBlocks scene(Engine engine, String key, int variant, int size, Map overrides) { - IrisData data = engine.getData(); - source.keys(data); - List variants = source.variants(data, key); - if (variants.isEmpty()) { - throw new NoSuchElementException("No object " + key); - } - return StudioProfiles.sceneOf(variants.get(Math.floorMod(variant, variants.size()))); - } - - @Override - public BakeTiming timeBake(Engine engine, String key) { - IrisData data = engine.getData(); - source.keys(data); - OptionalLong seed = source.seed(key); - if (seed.isEmpty()) { - throw new NoSuchElementException("No baked entry " + key); - } - BakeRun run = source.timeBake(data, key, seed.getAsLong()); - if (run == null) { - throw new NoSuchElementException("No baked entry " + key); - } - return new BakeTiming(run.variantCount(), List.of(new BakeTiming.Stage(BAKE_STAGE, run.totalNanos()))); - } - - private static String nameOf(String key) { - return key.substring(key.lastIndexOf('/') + 1); - } - - private static String folderOf(String key) { - int slash = key.lastIndexOf('/'); - return slash < 0 ? "" : key.substring(0, slash); - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/bridge/StudioProfiles.java b/core/src/main/java/art/arcane/iris/studio/bridge/StudioProfiles.java deleted file mode 100644 index 12a44d969..000000000 --- a/core/src/main/java/art/arcane/iris/studio/bridge/StudioProfiles.java +++ /dev/null @@ -1,461 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 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.studio.bridge; - -import art.arcane.iris.generation.biome.IrisBiome; -import art.arcane.iris.generation.cave.IrisCaveProfile; -import art.arcane.iris.generation.decoration.formation.IrisFormation; -import art.arcane.iris.generation.decoration.formation.IrisFormationProfile; -import art.arcane.iris.generation.decoration.tree.IrisProceduralTree; -import art.arcane.iris.generation.decoration.tree.IrisTreeProfile; -import art.arcane.iris.generation.hydrology.config.IrisFluidProfile; -import art.arcane.iris.generation.mantle.CaveProfilePreview; -import art.arcane.iris.generation.runtime.Engine; -import art.arcane.iris.generation.terrain.IrisDimension; -import art.arcane.iris.generation.terrain.IrisRegion; -import art.arcane.iris.pack.loading.IrisData; -import art.arcane.iris.structure.object.IrisObject; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.documentation.Description; -import art.arcane.volmlib.util.math.RNG; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Optional; -import java.util.Set; - -/** - * The views of the config profiles Iris v4 has: cave profiles, tree profiles, formation profiles and fluid profiles. - * Each lists what the pack has of its kind, shows its settings as a form and draws it as blocks, so the studio's scene - * viewer can show them. Values typed into a form only change the preview. - */ -final class StudioProfiles { - static final String CAVES = "caveProfiles"; - static final String TREES = "treeProfiles"; - static final String FORMATIONS = "formationProfiles"; - static final String FLUIDS = "fluidProfiles"; - - private static final List VIEWS = List.of(new CaveView(), new TreeView(), new FormationView(), new FluidView(), - StudioObjects.packObjects(), StudioObjects.proceduralObjects()); - - private StudioProfiles() { - } - - static List views() { - return VIEWS; - } - - static ProfileView view(String id) { - return VIEWS.stream().filter(view -> view.id().equals(id)).findFirst() - .orElseThrow(() -> new NoSuchElementException("No profile view " + id)); - } - - record Entry(String key, String name, String group, int variants) { - } - - /** @param blocksAcross the sizes the scene can be built at, smallest first */ - record Sizes(List blocksAcross, int opening) { - } - - interface ProfileView { - String id(); - - String label(); - - String description(); - - /** Null when each entry draws one size. */ - Sizes sizes(); - - List entries(Engine engine); - - ProfileForm.Form form(Engine engine, String key, Map overrides); - - /** Whether each entry has a settings form; the object views have none. */ - default boolean hasForm() { - return true; - } - - /** Whether the entries are baked from settings, so their bake can be timed. */ - default boolean isBaked() { - return false; - } - - /** One timed bake of the entry; only asked of baked views. */ - default StudioObjects.BakeTiming timeBake(Engine engine, String key) { - throw new UnsupportedOperationException(id() + " is not baked"); - } - - SceneBlocks scene(Engine engine, String key, int variant, int size, Map overrides) throws IOException; - } - - private static String readable(String constantName) { - String lower = constantName.toLowerCase(Locale.ROOT).replace('_', ' '); - return Character.toUpperCase(lower.charAt(0)) + lower.substring(1); - } - - /** What the pack says about an enum constant, or its readable name when it says nothing. */ - private static String describe(Enum constant) { - try { - Description description = constant.getDeclaringClass().getField(constant.name()).getAnnotation(Description.class); - return description == null ? readable(constant.name()) : description.value(); - } catch (NoSuchFieldException undocumented) { - return readable(constant.name()); - } - } - - private static Entry presetEntry(String key, int variants) { - return new Entry(key, readable(key), "Presets", variants); - } - - static SceneBlocks sceneOf(IrisObject object) { - SceneBlocks scene = new SceneBlocks(); - object.getBlocks().forEach((position, state) -> scene.add(position.getBlockX(), position.getBlockY(), position.getBlockZ(), state.key())); - return scene; - } - - private static IrisObject variantOf(List variants, int variant, String what) { - if (variants.isEmpty()) { - throw new NoSuchElementException("This " + what + " bakes nothing"); - } - return variants.get(Math.floorMod(variant, variants.size())); - } - - // Caves ------------------------------------------------------------------------------------------------------ - - private static final class CaveView implements ProfileView { - private static final Sizes SIZES = new Sizes(List.of(64, 128, 256), 128); - private static final int VARIANTS = 4; - private static final int VARIANT_SPACING_BLOCKS = 4096; - private static final int SURFACE_ABOVE_SEA_BLOCKS = 48; - private static final int MAX_DEPTH_BLOCKS = 160; - private static final String DIMENSION_KEY = "dimension"; - private static final String REGION_PREFIX = "region/"; - private static final String BIOME_PREFIX = "biome/"; - private static final String[] DEPTH_BANDS = {"minecraft:yellow_concrete", "minecraft:lime_concrete", "minecraft:light_blue_concrete", - "minecraft:purple_concrete"}; - private static final int[][] NEIGHBOURS = {{1, 0, 0}, {-1, 0, 0}, {0, 1, 0}, {0, -1, 0}, {0, 0, 1}, {0, 0, -1}}; - - @Override - public String id() { - return CAVES; - } - - @Override - public String label() { - return "Cave profiles"; - } - - @Override - public String description() { - return "The carved space of each enabled cave profile of the dimension, its regions and its biomes"; - } - - @Override - public Sizes sizes() { - return SIZES; - } - - @Override - public List entries(Engine engine) { - IrisData data = engine.getData(); - IrisDimension dimension = engine.getDimension(); - List entries = new ArrayList<>(); - if (dimension.getCaveProfile().isEnabled()) { - entries.add(new Entry(DIMENSION_KEY, dimension.getName(), "Dimension", VARIANTS)); - } - for (IrisRegion region : data.getRegionLoader().loadAll(data.getRegionLoader().getPossibleKeys())) { - if (region != null && region.getCaveProfile().isEnabled()) { - entries.add(new Entry(REGION_PREFIX + region.getLoadKey(), region.getName(), "Regions", VARIANTS)); - } - } - for (IrisBiome biome : data.getBiomeLoader().loadAll(data.getBiomeLoader().getPossibleKeys())) { - if (biome != null && biome.getCaveProfile().isEnabled()) { - entries.add(new Entry(BIOME_PREFIX + biome.getLoadKey(), biome.getName(), "Biomes", VARIANTS)); - } - } - return entries; - } - - @Override - public ProfileForm.Form form(Engine engine, String key, Map overrides) { - IrisCaveProfile profile = ProfileForm.withOverrides(profileOf(engine, key), overrides); - return ProfileForm.of("Cave profile", profile, Set.of(), overrides, List.of("Values typed here change the preview only")); - } - - @Override - public SceneBlocks scene(Engine engine, String key, int variant, int size, Map overrides) throws IOException { - IrisCaveProfile profile = ProfileForm.withOverrides(profileOf(engine, key), overrides); - int surfaceY = Math.min(engine.getHeight() - 1, engine.getDimension().getFluidHeight() + SURFACE_ABOVE_SEA_BLOCKS); - int bottomY = Math.max(0, Math.max((int) Math.floor(profile.getVerticalRange().getMin()), surfaceY - MAX_DEPTH_BLOCKS)); - boolean[] carved = CaveProfilePreview.carve(engine, profile, Math.floorMod(variant, VARIANTS) * VARIANT_SPACING_BLOCKS, size, bottomY, surfaceY); - return outsideOf(carved, size, surfaceY - bottomY + 1); - } - - private static IrisCaveProfile profileOf(Engine engine, String key) { - IrisData data = engine.getData(); - IrisCaveProfile profile = null; - if (DIMENSION_KEY.equals(key)) { - profile = engine.getDimension().getCaveProfile(); - } else if (key.startsWith(REGION_PREFIX)) { - IrisRegion region = data.getRegionLoader().load(key.substring(REGION_PREFIX.length())); - profile = region == null ? null : region.getCaveProfile(); - } else if (key.startsWith(BIOME_PREFIX)) { - IrisBiome biome = data.getBiomeLoader().load(key.substring(BIOME_PREFIX.length())); - profile = biome == null ? null : biome.getCaveProfile(); - } - if (profile == null) { - throw new NoSuchElementException("No cave profile " + key); - } - return profile; - } - - // Only the carved blocks on the outside of the space are kept, as the inside could not be seen. - private static SceneBlocks outsideOf(boolean[] carved, int size, int height) { - SceneBlocks scene = new SceneBlocks(); - for (int y = 0; y < height; y++) { - String band = DEPTH_BANDS[Math.min(DEPTH_BANDS.length - 1, (height - 1 - y) * DEPTH_BANDS.length / height)]; - for (int z = 0; z < size; z++) { - for (int x = 0; x < size; x++) { - if (carved[cellOf(x, y, z, size)] && touchesRock(carved, x, y, z, size, height)) { - scene.add(x, y, z, band); - } - } - } - } - return scene; - } - - private static boolean touchesRock(boolean[] carved, int x, int y, int z, int size, int height) { - 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 || !carved[cellOf(nx, ny, nz, size)]) { - return true; - } - } - return false; - } - - private static int cellOf(int x, int y, int z, int size) { - return (y * size + z) * size + x; - } - } - - // Trees ------------------------------------------------------------------------------------------------------ - - private static final class TreeView implements ProfileView { - private static final Set HIDDEN = Set.of("name", "chance", "density", "variants", "seed", "plausible", "mode", - "carvingSupport", "underwater", "profile"); - - @Override - public String id() { - return TREES; - } - - @Override - public String label() { - return "Tree profiles"; - } - - @Override - public String description() { - return "The canopy shape each tree profile gives a procedural tree"; - } - - @Override - public Sizes sizes() { - return null; - } - - @Override - public List entries(Engine engine) { - int variants = new IrisProceduralTree().getVariants(); - return Arrays.stream(IrisTreeProfile.values()).map(profile -> presetEntry(profile.name(), variants)).toList(); - } - - @Override - public ProfileForm.Form form(Engine engine, String key, Map overrides) { - return ProfileForm.of("Tree", treeOf(key, overrides), HIDDEN, overrides, - List.of(describe(profileOf(key)), "Values typed here change the preview only")); - } - - @Override - public SceneBlocks scene(Engine engine, String key, int variant, int size, Map overrides) { - return sceneOf(variantOf(treeOf(key, overrides).getVariantObjects(engine.getData()), variant, "tree")); - } - - private static IrisProceduralTree treeOf(String key, Map overrides) { - IrisProceduralTree tree = ProfileForm.withOverrides(new IrisProceduralTree(), overrides); - tree.setProfile(profileOf(key)); - return tree; - } - - private static IrisTreeProfile profileOf(String key) { - try { - return IrisTreeProfile.valueOf(key); - } catch (IllegalArgumentException unknown) { - throw new NoSuchElementException("No tree profile " + key); - } - } - - } - - // Formations ------------------------------------------------------------------------------------------------- - - private static final class FormationView implements ProfileView { - private static final Set HIDDEN = Set.of("name", "chance", "density", "variants", "seed", "mode", "carvingSupport", - "surfaceSupportBuffer", "underwater", "profile"); - - @Override - public String id() { - return FORMATIONS; - } - - @Override - public String label() { - return "Formation profiles"; - } - - @Override - public String description() { - return "How each formation profile shapes a formation's width from base to top"; - } - - @Override - public Sizes sizes() { - return null; - } - - @Override - public List entries(Engine engine) { - int variants = new IrisFormation().getVariants(); - return Arrays.stream(IrisFormationProfile.values()).map(profile -> presetEntry(profile.name(), variants)).toList(); - } - - @Override - public ProfileForm.Form form(Engine engine, String key, Map overrides) { - return ProfileForm.of("Formation", formationOf(key, overrides), HIDDEN, overrides, - List.of(describe(profileOf(key)), "Values typed here change the preview only")); - } - - @Override - public SceneBlocks scene(Engine engine, String key, int variant, int size, Map overrides) { - return sceneOf(variantOf(formationOf(key, overrides).getVariantObjects(engine.getData()), variant, "formation")); - } - - private static IrisFormation formationOf(String key, Map overrides) { - IrisFormation formation = ProfileForm.withOverrides(new IrisFormation(), overrides); - formation.setProfile(profileOf(key)); - return formation; - } - - private static IrisFormationProfile profileOf(String key) { - try { - return IrisFormationProfile.valueOf(key); - } catch (IllegalArgumentException unknown) { - throw new NoSuchElementException("No formation profile " + key); - } - } - - } - - // Fluids ----------------------------------------------------------------------------------------------------- - - private static final class FluidView implements ProfileView { - private static final Sizes SIZES = new Sizes(List.of(16, 32, 64), 32); - private static final int VARIANTS = 4; - private static final int VARIANT_SPACING_BLOCKS = 1024; - private static final int DEPTH_BLOCKS = 3; - private static final String BASIN_BLOCK = "minecraft:stone"; - - @Override - public String id() { - return FLUIDS; - } - - @Override - public String label() { - return "Fluid profiles"; - } - - @Override - public String description() { - return "The blocks of each named fluid of the dimension's hydrology, in a pool lined with its seam"; - } - - @Override - public Sizes sizes() { - return SIZES; - } - - @Override - public List entries(Engine engine) { - return fluids(engine).stream().map(fluid -> new Entry(fluid.getName(), fluid.getName(), "Fluids", VARIANTS)).toList(); - } - - @Override - public ProfileForm.Form form(Engine engine, String key, Map overrides) { - IrisFluidProfile fluid = fluidOf(engine, key); - IrisData data = engine.getData(); - List notes = new ArrayList<>(); - notes.add("Blocks: " + String.join(", ", fluid.getPalette().getBlockData(data).stream().map(state -> state.key()).toList())); - notes.add("Seam: " + (fluid.getSeam() == null ? "none" : fluid.getSeam())); - return new ProfileForm.Form("Fluid", List.of(), notes); - } - - @Override - public SceneBlocks scene(Engine engine, String key, int variant, int size, Map overrides) { - IrisData data = engine.getData(); - IrisFluidProfile fluid = fluidOf(engine, key); - IrisFluidProfile seam = fluid.getSeam() == null ? null : fluidOf(engine, fluid.getSeam()); - int offset = Math.floorMod(variant, VARIANTS) * VARIANT_SPACING_BLOCKS; - RNG rng = new RNG(offset + 1L); - SceneBlocks scene = new SceneBlocks(); - for (int z = 0; z < size; z++) { - for (int x = 0; x < size; x++) { - scene.add(x, 0, z, BASIN_BLOCK); - boolean wall = x == 0 || z == 0 || x == size - 1 || z == size - 1; - boolean seamRing = seam != null && (x == 1 || z == 1 || x == size - 2 || z == size - 2); - for (int y = 1; y <= DEPTH_BLOCKS; y++) { - IrisFluidProfile filling = seamRing ? seam : fluid; - scene.add(x, y, z, wall ? BASIN_BLOCK : filling.getPalette().get(rng, x + offset, y, z, data).key()); - } - } - } - return scene; - } - - private static KList fluids(Engine engine) { - return engine.getDimension().getHydrology().getFluids(); - } - - private static IrisFluidProfile fluidOf(Engine engine, String key) { - Optional found = fluids(engine).stream().filter(fluid -> key.equals(fluid.getName())).findFirst(); - return found.orElseThrow(() -> new NoSuchElementException("No fluid profile " + key)); - } - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/bridge/StudioScenes.java b/core/src/main/java/art/arcane/iris/studio/bridge/StudioScenes.java new file mode 100644 index 000000000..a7c4e6ba0 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/bridge/StudioScenes.java @@ -0,0 +1,78 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 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.studio.bridge; + +import art.arcane.iris.studio.scene.EditableSceneView; +import art.arcane.iris.studio.scene.SceneBlocks; +import art.arcane.iris.studio.scene.SceneSizes; +import art.arcane.iris.studio.scene.SceneView; +import art.arcane.iris.studio.scene.SceneViews; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.List; +import java.util.NoSuchElementException; + +/** The scene views the studio lists: every feature's, then the studio's own. */ +final class StudioScenes { + private static final List STUDIO_VIEWS = List.of(new PackObjectsSceneView(), new ProceduralObjectsSceneView()); + + private final List views = SceneViews.withStudioViews(STUDIO_VIEWS); + + List infos() { + return views.stream().map(SceneViewInfo::of).toList(); + } + + /** @throws NoSuchElementException when no view has {@code id} */ + SceneView view(String id) { + return views.stream().filter(view -> view.id().equals(id)).findFirst() + .orElseThrow(() -> new NoSuchElementException("No scene view " + id)); + } + + /** @throws NoSuchElementException when no view has {@code id}, or its entries can't be edited */ + EditableSceneView editableView(String id) { + if (view(id) instanceof EditableSceneView editable) { + return editable; + } + throw new NoSuchElementException("The entries of " + id + " can't be edited"); + } + + /** The part of each block of {@code scene}, in the order it encodes them, as little endian 32-bit integers. */ + static byte[] encodeParts(SceneBlocks scene) { + int[] parts = scene.parts(); + ByteBuffer buffer = ByteBuffer.allocate(parts.length * Integer.BYTES).order(ByteOrder.LITTLE_ENDIAN); + buffer.asIntBuffer().put(parts); + return buffer.array(); + } + + /** + * A view as the studio lists it: {@code editable} when its entries are edited as nodes, {@code creatable} when they + * can also be created and deleted, {@code baked} when their bake can be timed, {@code parts} when a block can be + * traced to the part that placed it, and {@code form} when each entry has a settings form. + */ + record SceneViewInfo(String id, String label, String description, boolean editable, boolean creatable, boolean baked, + boolean parts, SceneSizes sizes, boolean form) { + static SceneViewInfo of(SceneView view) { + boolean editable = view instanceof EditableSceneView; + boolean creatable = view instanceof EditableSceneView editableView && editableView.creation().isPresent(); + return new SceneViewInfo(view.id(), view.label(), view.description(), editable, creatable, view.isBaked(), + view.tracesParts(), view.sizes(), view.hasForm()); + } + } +} diff --git a/core/src/main/java/art/arcane/iris/studio/bridge/StudioSuggestions.java b/core/src/main/java/art/arcane/iris/studio/bridge/StudioSuggestions.java new file mode 100644 index 000000000..dbc0f9ba7 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/bridge/StudioSuggestions.java @@ -0,0 +1,61 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 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.studio.bridge; + +import art.arcane.iris.pack.loading.IrisData; +import art.arcane.iris.pack.loading.ResourceLoader; +import art.arcane.iris.spi.IrisPlatforms; + +import java.util.Arrays; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.TreeSet; + +/** What a setting naming a block or a resource of the pack may be typed as, for the studio to suggest while it is typed. */ +final class StudioSuggestions { + private StudioSuggestions() { + } + + /** + * The entries of the registry {@code referenceName} names, sorted; blocks are the pack's own and the platform's. + * + * @throws NoSuchElementException when there is no such reference + */ + static List ofReference(IrisData data, String referenceName) { + if (!SettingsTypes.BLOCK_REFERENCE.equals(referenceName)) { + throw new NoSuchElementException("No reference named " + referenceName); + } + TreeSet blocks = new TreeSet<>(Arrays.asList(data.getBlockLoader().getPossibleKeys())); + blocks.addAll(IrisPlatforms.get().registries().blockTypeKeys()); + return List.copyOf(blocks); + } + + /** + * The keys of the pack's resources in the folder {@code folder}, sorted. + * + * @throws NoSuchElementException when the pack has no resources of that folder + */ + static List ofResource(IrisData data, String folder) { + ResourceLoader loader = data.getLoaders().values().stream() + .filter(candidate -> folder.equals(candidate.getFolderName())) + .findFirst() + .orElseThrow(() -> new NoSuchElementException("The pack has no " + folder)); + return Arrays.stream(loader.getPossibleKeys()).sorted().distinct().toList(); + } +} diff --git a/core/src/main/java/art/arcane/iris/studio/scene/EditableSceneView.java b/core/src/main/java/art/arcane/iris/studio/scene/EditableSceneView.java new file mode 100644 index 000000000..89314ce06 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/scene/EditableSceneView.java @@ -0,0 +1,64 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 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.studio.scene; + +import art.arcane.iris.generation.runtime.Engine; +import com.google.gson.JsonObject; + +import java.io.File; +import java.util.List; +import java.util.Objects; +import java.util.Optional; + +/** + * A scene view whose entries are each written in one file of the pack, which the studio shows as a graph of nodes and + * rewrites as they are edited. The studio reads and writes the file; the view only tells it which file an entry is and + * how that file reads as nodes. + */ +public interface EditableSceneView extends SceneView { + /** The file entry {@code key} is written in; empty when it has none of its own. */ + Optional fileOf(Engine engine, String key); + + /** + * The file of entry {@code key} as trees of nodes, each drawn growing from its root, such as an object with its + * parts, and its materials beside it. The pack may not have read this text yet, so a node whose part the scene does + * not show yet has {@link SceneBlocks#NO_PART}. + * + * @throws IllegalArgumentException when {@code file} does not hold what this view edits + */ + List graph(Engine engine, String key, JsonObject file); + + /** How the studio creates and removes entries of this view; empty when it may not. */ + default Optional creation() { + return Optional.empty(); + } + + /** + * How the studio creates and removes entries: each is a JSON file in {@code folder} below the pack, a new one + * starts as {@code starter}, and other files of the pack name an entry {@code key} as {@code referencePrefix + key}, + * which is how the studio finds what still uses an entry before it is removed. + */ + record Creation(String folder, String starter, String referencePrefix) { + public Creation { + Objects.requireNonNull(folder, "folder"); + Objects.requireNonNull(starter, "starter"); + Objects.requireNonNull(referencePrefix, "referencePrefix"); + } + } +} diff --git a/core/src/main/java/art/arcane/iris/studio/scene/GraphNode.java b/core/src/main/java/art/arcane/iris/studio/scene/GraphNode.java new file mode 100644 index 000000000..a92ef8e93 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/scene/GraphNode.java @@ -0,0 +1,114 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 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.studio.scene; + +import com.google.gson.JsonParser; +import com.google.gson.JsonSyntaxException; + +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; + +/** + * One node of an entry's file shown as a graph: a JSON object of the file, drawn as a box of its settings, with the + * nodes it holds. + * + * @param kind what it is, such as {@code Stem}; nodes of one kind are drawn alike + * @param title what its box is headed, such as the object's name + * @param path where it is written; a node in an array can be duplicated and deleted, the root can't be deleted + * @param part the part of the scene it draws, as {@link SceneBlocks#add(int, int, int, String, int)} numbers them, so + * choosing one chooses the other; {@link SceneBlocks#NO_PART} when it draws none + * @param roles the block roles it places or decorates, shown as tags + * @param settings the objects whose settings its box shows, its own first + * @param children the nodes it holds, each with what the wire to it means + * @param edits how the studio may change it beyond its settings + */ +public record GraphNode(String kind, String title, JsonPath path, int part, List roles, + List settings, List children, Edits edits) { + public GraphNode { + Objects.requireNonNull(kind, "kind"); + Objects.requireNonNull(title, "title"); + Objects.requireNonNull(path, "path"); + roles = List.copyOf(roles); + settings = List.copyOf(settings); + children = List.copyOf(children); + Objects.requireNonNull(edits, "edits"); + if (edits.movable() && !path.isElement()) { + throw new IllegalArgumentException("Only a node in an array can move, not the one at " + path); + } + } + + /** A node held by another, and what holding it means, such as {@code each copy}; empty for plain growing. */ + public record Link(String wire, GraphNode node) { + public Link { + Objects.requireNonNull(wire, "wire"); + Objects.requireNonNull(node, "node"); + } + } + + /** + * The settings of the JSON object at {@code path}, which the pack reads into {@code type}, so the studio shows them + * as the pack's schema describes that type. Members in {@code shownAsNodes} are left out, as they are nodes of + * their own. The object may not be written yet; setting a value writes it. + */ + public record NodeSettings(String title, JsonPath path, Class type, Set shownAsNodes) { + public NodeSettings { + Objects.requireNonNull(title, "title"); + Objects.requireNonNull(path, "path"); + Objects.requireNonNull(type, "type"); + shownAsNodes = Set.copyOf(shownAsNodes); + } + } + + /** + * How the studio may change a node beyond its settings. + * + * @param childList the array a node moved under this one is added to; empty when nothing can be moved here + * @param movable whether it can be moved under another node with a child list + * @param additions the nodes that can be added under it + */ + public record Edits(Optional childList, boolean movable, List additions) { + public static final Edits NONE = new Edits(Optional.empty(), false, List.of()); + + public Edits { + Objects.requireNonNull(childList, "childList"); + additions = List.copyOf(additions); + } + } + + /** A node that can be added: {@code literal} appended to the array at {@code list}, which is written when missing. */ + public record Addition(String label, JsonPath list, String literal) { + public Addition { + Objects.requireNonNull(label, "label"); + Objects.requireNonNull(list, "list"); + if (!isJson(literal)) { + throw new IllegalArgumentException("Node " + label + " starts as " + literal + ", which is not JSON"); + } + } + + private static boolean isJson(String literal) { + try { + return literal != null && !literal.isBlank() && !JsonParser.parseString(literal).isJsonNull(); + } catch (JsonSyntaxException notJson) { + return false; + } + } + } +} diff --git a/core/src/main/java/art/arcane/iris/studio/scene/JsonPath.java b/core/src/main/java/art/arcane/iris/studio/scene/JsonPath.java new file mode 100644 index 000000000..854d8bce6 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/scene/JsonPath.java @@ -0,0 +1,116 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 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.studio.scene; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +/** + * Where a value sits in a JSON file: member names and element indices from the root, such as + * {@code parts, 0, stem} for the stem of the first part, built as {@code ROOT.member("parts").element(0).member("stem")}. + */ +public record JsonPath(List steps) { + public static final JsonPath ROOT = new JsonPath(List.of()); + + public JsonPath { + steps = List.copyOf(steps); + } + + /** One step down from a value: into a member of an object or an element of an array. */ + public sealed interface Step permits Key, Index { + } + + /** The member named {@code name} of an object. */ + public record Key(String name) implements Step { + public Key { + Objects.requireNonNull(name, "name"); + } + + @Override + public String toString() { + return name; + } + } + + /** The element at {@code position} of an array, from 0. */ + public record Index(int position) implements Step { + public Index { + if (position < 0) { + throw new IllegalArgumentException("An element index counts from 0, not " + position); + } + } + + @Override + public String toString() { + return String.valueOf(position); + } + } + + public JsonPath member(String name) { + return then(new Key(name)); + } + + public JsonPath element(int position) { + return then(new Index(position)); + } + + public boolean isRoot() { + return steps.isEmpty(); + } + + /** @throws IllegalStateException at the root */ + public JsonPath parent() { + requireStep(); + return new JsonPath(steps.subList(0, steps.size() - 1)); + } + + /** @throws IllegalStateException at the root */ + public Step last() { + requireStep(); + return steps.get(steps.size() - 1); + } + + /** Whether the value here is an element of an array. */ + public boolean isElement() { + return !isRoot() && last() instanceof Index; + } + + public boolean startsWith(JsonPath prefix) { + return steps.size() >= prefix.steps.size() && steps.subList(0, prefix.steps.size()).equals(prefix.steps); + } + + private JsonPath then(Step step) { + List longer = new ArrayList<>(steps); + longer.add(step); + return new JsonPath(longer); + } + + private void requireStep() { + if (isRoot()) { + throw new IllegalStateException("The root has no parent"); + } + } + + @Override + public String toString() { + return steps.isEmpty() ? "the root" : steps.stream().map(Step::toString).collect(Collectors.joining(".")); + } +} diff --git a/core/src/main/java/art/arcane/iris/studio/scene/SceneBakeTiming.java b/core/src/main/java/art/arcane/iris/studio/scene/SceneBakeTiming.java new file mode 100644 index 000000000..441a794a0 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/scene/SceneBakeTiming.java @@ -0,0 +1,27 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 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.studio.scene; + +import java.util.List; + +/** One timed bake of a scene entry: a time per step, added up over every variant. */ +public record SceneBakeTiming(int variantCount, List stages) { + public record Stage(String label, long nanos) { + } +} diff --git a/core/src/main/java/art/arcane/iris/studio/bridge/SceneBlocks.java b/core/src/main/java/art/arcane/iris/studio/scene/SceneBlocks.java similarity index 67% rename from core/src/main/java/art/arcane/iris/studio/bridge/SceneBlocks.java rename to core/src/main/java/art/arcane/iris/studio/scene/SceneBlocks.java index 358133b04..1338b76bd 100644 --- a/core/src/main/java/art/arcane/iris/studio/bridge/SceneBlocks.java +++ b/core/src/main/java/art/arcane/iris/studio/scene/SceneBlocks.java @@ -16,8 +16,9 @@ * along with this program. If not, see . */ -package art.arcane.iris.studio.bridge; +package art.arcane.iris.studio.scene; +import art.arcane.iris.structure.object.IrisObject; import com.google.gson.Gson; import java.nio.ByteBuffer; @@ -27,6 +28,7 @@ import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.NoSuchElementException; import java.util.Set; /** @@ -38,9 +40,12 @@ import java.util.Set; * The header holds the block states used once each and the scene's bounds. Air is left out: the studio draws nothing * there either. Positions are from the scene's lowest corner. */ -final class SceneBlocks { +public final class SceneBlocks { + /** The part of a block no part is known for. */ + public static final int NO_PART = -1; private static final int ALIGNMENT_BYTES = 4; private static final int INTS_PER_BLOCK = 4; + private static final int PART_FIELD = 4; private static final Set AIR = Set.of("minecraft:air", "minecraft:cave_air", "minecraft:void_air"); private final Map palette = new LinkedHashMap<>(); @@ -48,12 +53,35 @@ final class SceneBlocks { private final int[] min = {Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE}; private final int[] max = {Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE}; - void add(int x, int y, int z, String state) { + public static SceneBlocks of(IrisObject object) { + SceneBlocks scene = new SceneBlocks(); + object.getBlocks().forEach((position, state) -> scene.add(position.getBlockX(), position.getBlockY(), position.getBlockZ(), state.key())); + return scene; + } + + /** + * The scene of one of an entry's baked objects, wrapping {@code variant} around how many there are. + * + * @param what what the entry is, such as "tree", for the message when it bakes nothing + */ + public static SceneBlocks ofVariant(List variants, int variant, String what) { + if (variants.isEmpty()) { + throw new NoSuchElementException("This " + what + " bakes nothing"); + } + return of(variants.get(Math.floorMod(variant, variants.size()))); + } + + public void add(int x, int y, int z, String state) { + add(x, y, z, state, NO_PART); + } + + /** @param part which part of the entry placed the block, numbered by the view from 0, or {@link #NO_PART} */ + public void add(int x, int y, int z, String state, int part) { if (AIR.contains(state)) { return; } int paletteIndex = palette.computeIfAbsent(state, ignored -> palette.size()); - blocks.add(new int[]{x, y, z, paletteIndex}); + blocks.add(new int[]{x, y, z, paletteIndex, part}); int[] at = {x, y, z}; for (int axis = 0; axis < 3; axis++) { min[axis] = Math.min(min[axis], at[axis]); @@ -61,12 +89,17 @@ final class SceneBlocks { } } - int count() { + public int count() { return blocks.size(); } + /** The part of each block, in the order {@link #encode} writes them. */ + public int[] parts() { + return blocks.stream().mapToInt(block -> block[PART_FIELD]).toArray(); + } + /** The scene with its lowest corner at the origin; an empty scene is one block across. */ - byte[] encode(Gson gson) { + public byte[] encode(Gson gson) { boolean empty = blocks.isEmpty(); int[] origin = empty ? new int[]{0, 0, 0} : min; int[] top = empty ? new int[]{1, 1, 1} : max; diff --git a/core/src/main/java/art/arcane/iris/studio/scene/SceneEntry.java b/core/src/main/java/art/arcane/iris/studio/scene/SceneEntry.java new file mode 100644 index 000000000..418f7112e --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/scene/SceneEntry.java @@ -0,0 +1,42 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 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.studio.scene; + +import java.util.Locale; + +/** + * One thing a view lists. + * + * @param key what the view finds it by + * @param group the heading the studio lists it under + * @param variants how many scenes it has, at least 1 + */ +public record SceneEntry(String key, String name, String group, int variants) { + private static final String PRESET_GROUP = "Presets"; + + /** An entry for an enum constant a pack picks by name, shown as "Tall oak" for TALL_OAK. */ + public static SceneEntry preset(Enum constant, int variants) { + return new SceneEntry(constant.name(), readable(constant.name()), PRESET_GROUP, variants); + } + + static String readable(String constantName) { + String lower = constantName.toLowerCase(Locale.ROOT).replace('_', ' '); + return Character.toUpperCase(lower.charAt(0)) + lower.substring(1); + } +} diff --git a/core/src/main/java/art/arcane/iris/studio/bridge/ProfileForm.java b/core/src/main/java/art/arcane/iris/studio/scene/SceneForm.java similarity index 68% rename from core/src/main/java/art/arcane/iris/studio/bridge/ProfileForm.java rename to core/src/main/java/art/arcane/iris/studio/scene/SceneForm.java index 9a9aa14cb..3ae39b208 100644 --- a/core/src/main/java/art/arcane/iris/studio/bridge/ProfileForm.java +++ b/core/src/main/java/art/arcane/iris/studio/scene/SceneForm.java @@ -16,13 +16,12 @@ * along with this program. If not, see . */ -package art.arcane.iris.studio.bridge; +package art.arcane.iris.studio.scene; import art.arcane.iris.pack.schema.annotation.MaxNumber; import art.arcane.iris.pack.schema.annotation.MinNumber; import art.arcane.volmlib.util.documentation.Description; -import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; @@ -31,46 +30,41 @@ import java.util.Map; import java.util.Set; /** - * The settings of a profile object as a form: each plain number, switch and choice it has, with the value it holds, what - * the pack says about it and its limits. A value typed into the form is carried by a request and applied to a copy, so - * the pack's files stay as they are. + * The settings of a scene entry as a form, with short lines about it. {@link #of} reads the plain numbers, switches and + * choices of a settings object; a value typed into the form is carried by a request and applied to a copy with + * {@link #withOverrides}, so the pack's files stay as they are. Settings nested in lists or other objects are not shown. */ -final class ProfileForm { - private ProfileForm() { - } - +public record SceneForm(String title, List fields, List notes) { /** @param kind boolean, integer, decimal or enum; {@code choices} lists an enum's names */ - record Field(String name, String description, String kind, Object value, Object defaultValue, Double minimum, Double maximum, - List choices, boolean changed) { + public record Field(String name, String description, String kind, Object value, Object defaultValue, Double minimum, Double maximum, + List choices, boolean changed) { } - record Form(String title, List fields, List notes) { - } - - static Form of(String title, Object bean, Set hidden, Map overrides, List notes) { - Object fresh = newInstance(bean.getClass()); + /** @param hidden names of fields left out of the form */ + public static SceneForm of(String title, Object settings, Set hidden, Map overrides, List notes) { + Object fresh = newInstance(settings.getClass()); List fields = new ArrayList<>(); - for (java.lang.reflect.Field field : bean.getClass().getDeclaredFields()) { + for (java.lang.reflect.Field field : settings.getClass().getDeclaredFields()) { String kind = kindOf(field); if (kind == null || hidden.contains(field.getName())) { continue; } - fields.add(fieldOf(field, kind, bean, fresh, overrides.containsKey(field.getName()))); + fields.add(fieldOf(field, kind, settings, fresh, overrides.containsKey(field.getName()))); } - return new Form(title, fields, notes); + return new SceneForm(title, fields, notes); } - /** A copy of the bean with the typed values set; a value that does not read as its field's type is ignored. */ + /** A copy of the settings with the typed values set; a value that does not read as its field's type is ignored. */ @SuppressWarnings("unchecked") - static T withOverrides(T bean, Map overrides) { - T copy = (T) newInstance(bean.getClass()); - for (java.lang.reflect.Field field : bean.getClass().getDeclaredFields()) { + public static T withOverrides(T settings, Map overrides) { + T copy = (T) newInstance(settings.getClass()); + for (java.lang.reflect.Field field : settings.getClass().getDeclaredFields()) { if (Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers())) { continue; } field.setAccessible(true); try { - field.set(copy, field.get(bean)); + field.set(copy, field.get(settings)); String typed = overrides.get(field.getName()); if (typed != null && kindOf(field) != null) { field.set(copy, parse(field.getType(), typed)); @@ -82,7 +76,17 @@ final class ProfileForm { return copy; } - private static Field fieldOf(java.lang.reflect.Field field, String kind, Object bean, Object fresh, boolean changed) { + /** What the pack says about an enum constant, or its readable name when it says nothing. */ + public static String describe(Enum constant) { + try { + Description description = constant.getDeclaringClass().getField(constant.name()).getAnnotation(Description.class); + return description == null ? SceneEntry.readable(constant.name()) : description.value(); + } catch (NoSuchFieldException undocumented) { + return SceneEntry.readable(constant.name()); + } + } + + private static Field fieldOf(java.lang.reflect.Field field, String kind, Object settings, Object fresh, boolean changed) { field.setAccessible(true); try { Description description = field.getAnnotation(Description.class); @@ -91,7 +95,7 @@ final class ProfileForm { List choices = field.getType().isEnum() ? Arrays.stream(field.getType().getEnumConstants()).map(constant -> ((Enum) constant).name()).toList() : List.of(); - return new Field(field.getName(), description == null ? "" : description.value(), kind, plain(field.get(bean)), + return new Field(field.getName(), description == null ? "" : description.value(), kind, plain(field.get(settings)), plain(field.get(fresh)), minimum == null ? null : minimum.value(), maximum == null ? null : maximum.value(), choices, changed); } catch (IllegalAccessException unreadable) { throw new IllegalStateException(unreadable); diff --git a/core/src/main/java/art/arcane/iris/studio/scene/SceneRequest.java b/core/src/main/java/art/arcane/iris/studio/scene/SceneRequest.java new file mode 100644 index 000000000..17d4465e0 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/scene/SceneRequest.java @@ -0,0 +1,34 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 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.studio.scene; + +import java.util.Map; + +/** + * Which scene of a view is wanted. + * + * @param variant which of the entry's variants; a view wraps it around the variants it has + * @param size blocks across, one of the view's {@link SceneSizes}; 0 for a view without sizes + * @param overrides values typed into the view's form, by field name, which change the scene only + */ +public record SceneRequest(String key, int variant, int size, Map overrides) { + public SceneRequest { + overrides = Map.copyOf(overrides); + } +} diff --git a/core/src/main/java/art/arcane/iris/studio/map/PackObjectSource.java b/core/src/main/java/art/arcane/iris/studio/scene/SceneSizes.java similarity index 56% rename from core/src/main/java/art/arcane/iris/studio/map/PackObjectSource.java rename to core/src/main/java/art/arcane/iris/studio/scene/SceneSizes.java index e52805765..3a69641ed 100644 --- a/core/src/main/java/art/arcane/iris/studio/map/PackObjectSource.java +++ b/core/src/main/java/art/arcane/iris/studio/scene/SceneSizes.java @@ -15,26 +15,22 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package art.arcane.iris.studio.map; -import art.arcane.iris.pack.loading.IrisData; -import art.arcane.iris.structure.object.IrisObject; +package art.arcane.iris.studio.scene; -import java.util.Arrays; import java.util.List; /** - * The pack's object files, by their load keys. + * The sizes a view builds its scenes at. + * + * @param blocksAcross smallest first + * @param opening the size shown first, one of {@code blocksAcross} */ -public final class PackObjectSource implements ObjectSource { - @Override - public List keys(IrisData data) { - return Arrays.asList(data.getObjectLoader().getPossibleKeys()); - } - - @Override - public List variants(IrisData data, String key) { - IrisObject object = data.getObjectLoader().load(key); - return object == null ? List.of() : List.of(object); +public record SceneSizes(List blocksAcross, int opening) { + public SceneSizes { + blocksAcross = List.copyOf(blocksAcross); + if (!blocksAcross.contains(opening)) { + throw new IllegalArgumentException("Opening size " + opening + " is not one of " + blocksAcross); + } } } diff --git a/core/src/main/java/art/arcane/iris/studio/scene/SceneView.java b/core/src/main/java/art/arcane/iris/studio/scene/SceneView.java new file mode 100644 index 000000000..d76f02106 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/scene/SceneView.java @@ -0,0 +1,75 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 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.studio.scene; + +import art.arcane.iris.generation.runtime.Engine; + +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; + +/** + * Something of a pack the studio can list and draw as blocks, such as its caves. A feature implements this next + * to its own code and names it in {@link SceneViews}; the studio shows whatever is listed there and knows nothing else + * about the feature. + */ +public interface SceneView { + /** Tells this view from the others; the studio also picks the view's icon by it. */ + String id(); + + String label(); + + String description(); + + /** Null when each entry draws at its own size. */ + default SceneSizes sizes() { + return null; + } + + List entries(Engine engine); + + /** @throws NoSuchElementException when the pack has no entry of the requested key */ + SceneBlocks scene(Engine engine, SceneRequest request) throws IOException; + + /** Whether each entry has a settings form. */ + default boolean hasForm() { + return false; + } + + /** The entry's settings with the typed values applied; only asked of views with a form. */ + default SceneForm form(Engine engine, String key, Map overrides) { + throw new NoSuchElementException(id() + " has no settings form"); + } + + /** Whether the entries are baked from settings, so their bake can be timed. */ + default boolean isBaked() { + return false; + } + + /** One timed bake of the entry; only asked of baked views. */ + default SceneBakeTiming timeBake(Engine engine, String key) { + throw new UnsupportedOperationException(id() + " is not baked"); + } + + /** Whether the scenes say which part placed each block, see {@link SceneBlocks#add(int, int, int, String, int)}. */ + default boolean tracesParts() { + return false; + } +} diff --git a/core/src/main/java/art/arcane/iris/studio/scene/SceneViews.java b/core/src/main/java/art/arcane/iris/studio/scene/SceneViews.java new file mode 100644 index 000000000..6ced13cf9 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/studio/scene/SceneViews.java @@ -0,0 +1,68 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 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.studio.scene; + +import art.arcane.iris.generation.cave.CaveProfileSceneView; +import art.arcane.iris.generation.decoration.formation.FormationProfileSceneView; +import art.arcane.iris.generation.decoration.tree.TreeProfileSceneView; +import art.arcane.iris.generation.hydrology.config.FluidProfileSceneView; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Set; + +/** The scene views Iris's features have, in the order the studio lists them. A feature with a view adds it here. */ +public final class SceneViews { + private static final List VIEWS = distinct(List.of( + new CaveProfileSceneView(), + new TreeProfileSceneView(), + new FormationProfileSceneView(), + new FluidProfileSceneView())); + + private SceneViews() { + } + + public static List all() { + return VIEWS; + } + + public static SceneView byId(String id) { + return VIEWS.stream().filter(view -> view.id().equals(id)).findFirst() + .orElseThrow(() -> new NoSuchElementException("No scene view " + id)); + } + + /** Every feature's view followed by the studio's own, such as its views of the pack's object files. */ + public static List withStudioViews(List studioViews) { + List views = new ArrayList<>(VIEWS); + views.addAll(studioViews); + return List.copyOf(distinct(views)); + } + + static List distinct(List views) { + Set ids = new HashSet<>(); + for (SceneView view : views) { + if (!ids.add(view.id())) { + throw new IllegalStateException("Two scene views are called " + view.id()); + } + } + return views; + } +} diff --git a/core/src/test/java/art/arcane/iris/studio/bridge/GraphEditTest.java b/core/src/test/java/art/arcane/iris/studio/bridge/GraphEditTest.java new file mode 100644 index 000000000..86f219124 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/studio/bridge/GraphEditTest.java @@ -0,0 +1,139 @@ +package art.arcane.iris.studio.bridge; + +import art.arcane.iris.studio.scene.JsonPath; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; + +public class GraphEditTest { + private static final JsonPath PARTS = JsonPath.ROOT.member("parts"); + private static final String OBJECT = """ + { + "parts": [ + { + "stem": {"length": 6}, + "children": [{"blob": {"radius": 2}}] + } + ] + }"""; + + @Test + public void settingAValueOfAnUnwrittenObjectWritesTheObject() { + String edited = apply(OBJECT, new GraphEdit.Set(PARTS.element(0).member("offset"), "y", "2")); + + assertEquals(OBJECT.replace("\"children\": [{\"blob\": {\"radius\": 2}}]", "\"children\": [{\"blob\": {\"radius\": 2}}],\n \"offset\": {\"y\": 2}"), edited); + } + + @Test + public void settingAValueOverwritesWhatIsWritten() { + String edited = apply(OBJECT, new GraphEdit.Set(PARTS.element(0).member("stem"), "length", "[4, 8]")); + + assertEquals(OBJECT.replace("\"length\": 6", "\"length\": [4, 8]"), edited); + } + + @Test + public void aValueCantBeSetWhereNoObjectCanBeWritten() { + assertThrows(IllegalArgumentException.class, () -> apply(OBJECT, new GraphEdit.Set(PARTS.element(4), "role", "\"wood\""))); + } + + @Test + public void aSetThatIsNotJsonIsRefused() { + assertThrows(IllegalArgumentException.class, () -> new GraphEdit.Set(JsonPath.ROOT, "seed", "seven")); + } + + @Test + public void unsettingWhatIsNotWrittenChangesNothing() { + assertEquals(OBJECT, apply(OBJECT, new GraphEdit.Unset(PARTS.element(0), "role"))); + } + + @Test + public void unsettingAValueLeavesItsDefault() { + String edited = apply(OBJECT, new GraphEdit.Unset(PARTS.element(0).member("stem"), "length")); + + assertEquals(OBJECT.replace("{\"length\": 6}", "{}"), edited); + } + + @Test + public void appendingToAnUnwrittenListWritesTheList() { + String edited = apply("{\"parts\": []}", new GraphEdit.Append(JsonPath.ROOT.member("materials"), "{\"role\": \"main\"}")); + + assertEquals("{\"parts\": [], \"materials\": [{\"role\": \"main\"}]}", edited); + } + + @Test + public void anAddedItemStartsAsACopyOfTheLast() { + String edited = apply("{\"rules\": [{\"block\": \"minecraft:moss_block\"}]}", new GraphEdit.AddItem(JsonPath.ROOT.member("rules"))); + + assertEquals("{\"rules\": [{\"block\": \"minecraft:moss_block\"}, {\"block\": \"minecraft:moss_block\"}]}", edited); + } + + @Test + public void deletingTheOnlyElementRemovesItsList() { + String edited = apply(OBJECT, new GraphEdit.Delete(PARTS.element(0).member("children").element(0))); + + assertEquals(OBJECT.replace(",\n \"children\": [{\"blob\": {\"radius\": 2}}]", ""), edited); + } + + @Test + public void theFileItselfCantBeDeleted() { + assertThrows(IllegalArgumentException.class, () -> new GraphEdit.Delete(JsonPath.ROOT)); + } + + @Test + public void aDuplicateIsAppendedWithAllItHolds() { + String edited = apply("{\"parts\": [{\"stem\": {}}, {\"blob\": {}}]}", new GraphEdit.Duplicate(PARTS.element(0))); + + assertEquals("{\"parts\": [{\"stem\": {}}, {\"blob\": {}}, {\"stem\": {}}]}", edited); + } + + @Test + public void onlyAnElementCanBeDuplicated() { + assertThrows(IllegalArgumentException.class, () -> new GraphEdit.Duplicate(PARTS)); + } + + @Test + public void aMovedPartJoinsTheEndOfItsNewList() { + String source = "{\"parts\": [{\"stem\": {}, \"children\": [{\"blob\": {}}]}, {\"cluster\": {}}]}"; + + String edited = apply(source, new GraphEdit.Move(PARTS.element(1), PARTS.element(0).member("children"))); + + assertEquals("{\"parts\": [{\"stem\": {}, \"children\": [{\"blob\": {}}, {\"cluster\": {}}]}]}", edited); + } + + @Test + public void aPartCantMoveIntoItselfOrWhereItIs() { + assertThrows(IllegalArgumentException.class, () -> new GraphEdit.Move(PARTS.element(0), PARTS.element(0).member("children"))); + assertThrows(IllegalArgumentException.class, () -> new GraphEdit.Move(PARTS.element(0), PARTS)); + } + + @Test + public void anEditIsReadAsTheStudioSendsIt() { + GraphEditRequest request = GraphEditRequest.parse(""" + {"revision": "r1", "edit": {"op": "move", "path": ["parts", 1], "toList": ["parts", 0, "children"]}}"""); + + assertEquals("r1", request.revision()); + assertEquals(new GraphEdit.Move(PARTS.element(1), PARTS.element(0).member("children")), request.edit()); + } + + @Test + public void anEditOfAnUnknownOpOrWithoutItsPathIsRefused() { + assertThrows(IllegalArgumentException.class, () -> GraphEditRequest.parse("{\"revision\": \"r\", \"edit\": {\"op\": \"rename\"}}")); + assertThrows(IllegalArgumentException.class, () -> GraphEditRequest.parse("{\"revision\": \"r\", \"edit\": {\"op\": \"delete\"}}")); + assertThrows(IllegalArgumentException.class, () -> GraphEditRequest.parse("not json")); + } + + @Test + public void aWholeFileIsReadAsTheStudioSendsIt() { + GraphEditRequest.FileWrite write = GraphEditRequest.FileWrite.parse("{\"revision\": \"r2\", \"text\": \"{}\"}"); + + assertEquals(new GraphEditRequest.FileWrite("r2", "{}"), write); + } + + private static String apply(String source, GraphEdit edit) { + JsonSplicer splicer = new JsonSplicer(JsonText.parse(source)); + String edited = splicer.apply(edit.splices(splicer)); + JsonText.parse(edited); + return edited; + } +} diff --git a/core/src/test/java/art/arcane/iris/studio/bridge/JsonSplicerTest.java b/core/src/test/java/art/arcane/iris/studio/bridge/JsonSplicerTest.java new file mode 100644 index 000000000..017fd131a --- /dev/null +++ b/core/src/test/java/art/arcane/iris/studio/bridge/JsonSplicerTest.java @@ -0,0 +1,140 @@ +package art.arcane.iris.studio.bridge; + +import art.arcane.iris.studio.scene.JsonPath; +import com.google.gson.JsonObject; +import org.junit.Test; + +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +public class JsonSplicerTest { + private static final String COMMENTED = """ + { + // How many to bake + "variants": 6, + "parts": [ + {"stem": {"length": 6}}, + {"blob": {"radius": 2}} /* the crown */ + ] + }"""; + + @Test + public void commentsAreReadAsBlanks() { + JsonText text = JsonText.parse(COMMENTED); + + assertTrue(text.at(JsonPath.ROOT.member("parts").element(1).member("blob")).isPresent()); + assertEquals("6", text.textOf(text.at(JsonPath.ROOT.member("variants")).orElseThrow())); + } + + @Test + public void textThatIsNotJsonIsRefusedNamingItsLine() { + IllegalArgumentException refused = assertThrows(IllegalArgumentException.class, () -> JsonText.parse("{\n\"a\": 1,\n\"b\" 2}")); + + assertTrue(refused.getMessage().endsWith("on line 3")); + } + + @Test + public void gsonReadsTheSameValues() { + JsonObject read = JsonText.parse("{\"n\": 1.50, \"on\": true, \"off\": null, \"s\": \"a\\nb\", \"list\": [1, {}]}").toGson().getAsJsonObject(); + + assertEquals(1.5, read.get("n").getAsDouble(), 0); + assertTrue(read.get("on").getAsBoolean()); + assertTrue(read.get("off").isJsonNull()); + assertEquals("a\nb", read.get("s").getAsString()); + assertEquals(2, read.getAsJsonArray("list").size()); + } + + @Test + public void replacingAValueLeavesTheCommentsAndLayout() { + String edited = edit(COMMENTED, (splicer, text) -> splicer.put(object(text, JsonPath.ROOT), "variants", "12")); + + assertEquals(COMMENTED.replace("\"variants\": 6", "\"variants\": 12"), edited); + } + + @Test + public void aNewMemberOfAMultiLineObjectGoesOnItsOwnLine() { + String edited = edit(COMMENTED, (splicer, text) -> splicer.put(object(text, JsonPath.ROOT), "seed", "7")); + + assertTrue(edited.endsWith(" ],\n \"seed\": 7\n}")); + } + + @Test + public void aNewMemberOfAOneLineObjectStaysOnItsLine() { + String edited = edit("{\"a\": 1}", (splicer, text) -> splicer.put(object(text, JsonPath.ROOT), "b", "2")); + + assertEquals("{\"a\": 1, \"b\": 2}", edited); + } + + @Test + public void aMemberOfAnEmptyObjectIsWrittenInsideIt() { + String edited = edit("{\"stem\": {}}", (splicer, text) -> splicer.put(object(text, JsonPath.ROOT.member("stem")), "length", "4")); + + assertEquals("{\"stem\": {\"length\": 4}}", edited); + } + + @Test + public void removingAMemberTakesItsSeparatorWithIt() { + assertEquals("{\"b\": 2, \"c\": 3}", edit("{\"a\": 1, \"b\": 2, \"c\": 3}", (splicer, text) -> splicer.remove(object(text, JsonPath.ROOT), "a"))); + assertEquals("{\"a\": 1, \"c\": 3}", edit("{\"a\": 1, \"b\": 2, \"c\": 3}", (splicer, text) -> splicer.remove(object(text, JsonPath.ROOT), "b"))); + assertEquals("{}", edit("{\"a\": 1}", (splicer, text) -> splicer.remove(object(text, JsonPath.ROOT), "a"))); + } + + @Test + public void aMultiLineElementIsAppendedIndentedLikeItsNeighbours() { + String edited = edit(COMMENTED, (splicer, text) -> splicer.append(array(text, JsonPath.ROOT.member("parts")), "{\n \"blob\": {}\n}")); + + assertTrue(edited.contains("{\"blob\": {\"radius\": 2}},\n {\n \"blob\": {}\n } /* the crown */\n ]")); + } + + @Test + public void elementsAreAppendedToOneLineAndEmptyArrays() { + assertEquals("[1, 2]", edit("[1]", (splicer, text) -> splicer.append(array(text, JsonPath.ROOT), "2"))); + assertEquals("[2]", edit("[]", (splicer, text) -> splicer.append(array(text, JsonPath.ROOT), "2"))); + } + + @Test + public void removingAnElementTakesItsSeparatorWithIt() { + assertEquals("[2, 3]", edit("[1, 2, 3]", (splicer, text) -> splicer.removeElement(array(text, JsonPath.ROOT), 0))); + assertEquals("[1, 2]", edit("[1, 2, 3]", (splicer, text) -> splicer.removeElement(array(text, JsonPath.ROOT), 2))); + assertEquals("[]", edit("[1]", (splicer, text) -> splicer.removeElement(array(text, JsonPath.ROOT), 0))); + } + + @Test + public void overlappingSplicesAreRefused() { + JsonText text = JsonText.parse("{\"a\": [1, 2]}"); + JsonSplicer splicer = new JsonSplicer(text); + JsonText.Arr list = array(text, JsonPath.ROOT.member("a")); + + assertThrows(IllegalArgumentException.class, () -> splicer.apply(List.of(splicer.replace(list, "[]"), splicer.removeElement(list, 0)))); + } + + @Test + public void textIsQuotedWithItsEscapes() { + assertEquals("\"a\\\"b\\\\c\\nd\\u0001\"", JsonSplicer.quote("a\"b\\c\nd\u0001")); + assertFalse(JsonText.isValue("{")); + } + + private interface SpliceOf { + JsonSplicer.Splice of(JsonSplicer splicer, JsonText text); + } + + private static String edit(String source, SpliceOf splice) { + JsonText text = JsonText.parse(source); + JsonSplicer splicer = new JsonSplicer(text); + String edited = splicer.apply(List.of(splice.of(splicer, text))); + JsonText.parse(edited); + return edited; + } + + private static JsonText.Obj object(JsonText text, JsonPath path) { + return (JsonText.Obj) text.at(path).orElseThrow(); + } + + private static JsonText.Arr array(JsonText text, JsonPath path) { + return (JsonText.Arr) text.at(path).orElseThrow(); + } +} diff --git a/core/src/test/java/art/arcane/iris/studio/bridge/PackObjectsSceneViewTest.java b/core/src/test/java/art/arcane/iris/studio/bridge/PackObjectsSceneViewTest.java new file mode 100644 index 000000000..71b678909 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/studio/bridge/PackObjectsSceneViewTest.java @@ -0,0 +1,73 @@ +package art.arcane.iris.studio.bridge; + +import art.arcane.iris.generation.geometry.IrisBlockVector; +import art.arcane.iris.generation.runtime.Engine; +import art.arcane.iris.pack.loading.IrisData; +import art.arcane.iris.pack.loading.ResourceLoader; +import art.arcane.iris.structure.object.IrisObject; +import art.arcane.iris.studio.scene.SceneEntry; +import art.arcane.iris.studio.scene.SceneRequest; +import art.arcane.volmlib.nativelib.terrain.NativeBlockState; +import org.junit.Test; + +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class PackObjectsSceneViewTest { + private final ResourceLoader objects = mockObjectLoader(); + private final Engine engine = engineWith(objects); + private final PackObjectsSceneView view = new PackObjectsSceneView(); + + @Test + public void objectFilesAreListedByFolder() { + when(objects.getPossibleKeys()).thenReturn(new String[]{"trees/oak", "well"}); + + List entries = view.entries(engine); + + assertEquals(List.of(new SceneEntry("trees/oak", "oak", "trees", 1), new SceneEntry("well", "well", "", 1)), entries); + } + + @Test + public void anObjectIsDrawnFromItsBlocks() { + IrisObject well = new IrisObject(2, 1, 1); + well.getBlocks().put(new IrisBlockVector(0, 0, 0), state("minecraft:cobblestone")); + well.getBlocks().put(new IrisBlockVector(1, 0, 0), state("minecraft:cobblestone")); + when(objects.load("well")).thenReturn(well); + + assertEquals(2, view.scene(engine, request("well")).count()); + } + + @Test + public void anObjectThatDoesNotLoadIsReportedAsMissing() { + assertThrows(NoSuchElementException.class, () -> view.scene(engine, request("gone"))); + } + + private static SceneRequest request(String key) { + return new SceneRequest(key, 0, 0, Map.of()); + } + + @SuppressWarnings("unchecked") + private static ResourceLoader mockObjectLoader() { + return mock(ResourceLoader.class); + } + + private static Engine engineWith(ResourceLoader objects) { + IrisData data = mock(IrisData.class); + when(data.getObjectLoader()).thenReturn(objects); + Engine engine = mock(Engine.class); + when(engine.getData()).thenReturn(data); + return engine; + } + + private static NativeBlockState state(String key) { + NativeBlockState state = mock(NativeBlockState.class); + when(state.key()).thenReturn(key); + return state; + } +} diff --git a/core/src/test/java/art/arcane/iris/studio/bridge/ProfileFormTest.java b/core/src/test/java/art/arcane/iris/studio/bridge/ProfileFormTest.java deleted file mode 100644 index 1bd6a84cf..000000000 --- a/core/src/test/java/art/arcane/iris/studio/bridge/ProfileFormTest.java +++ /dev/null @@ -1,61 +0,0 @@ -package art.arcane.iris.studio.bridge; - -import org.junit.Test; - -import java.util.List; -import java.util.Map; -import java.util.Set; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -public class ProfileFormTest { - private enum Shape {ROUND, FLAT} - - private static final class Sample { - private int height = 8; - private double weight = 0.5; - private boolean roots = true; - private Shape shape = Shape.ROUND; - private String name = "sample"; - } - - @Test - public void overridesApplyToACopyAndLeaveTheOriginalAlone() throws Exception { - Sample original = new Sample(); - Sample copy = ProfileForm.withOverrides(original, Map.of("height", "20", "weight", "1.5", "roots", "false", "shape", "FLAT")); - - assertEquals(8, original.height); - assertEquals(20, copy.height); - assertEquals(1.5, copy.weight, 0D); - assertFalse(copy.roots); - assertEquals(Shape.FLAT, copy.shape); - assertEquals("sample", copy.name); - } - - @Test - public void aValueThatDoesNotReadAsItsTypeIsIgnored() { - Sample copy = ProfileForm.withOverrides(new Sample(), Map.of("height", "tall", "shape", "TRIANGLE")); - - assertEquals(8, copy.height); - assertEquals(Shape.ROUND, copy.shape); - } - - @Test - public void theFormListsPlainSettingsWithTheirDefaultsAndWhatChanged() { - Map typed = Map.of("height", "20"); - Sample shown = ProfileForm.withOverrides(new Sample(), typed); - - ProfileForm.Form form = ProfileForm.of("Sample", shown, Set.of("weight"), typed, List.of()); - - List names = form.fields().stream().map(ProfileForm.Field::name).toList(); - assertEquals(List.of("height", "roots", "shape"), names); - ProfileForm.Field height = form.fields().get(0); - assertEquals(20, height.value()); - assertEquals(8, height.defaultValue()); - assertTrue(height.changed()); - assertFalse(form.fields().get(1).changed()); - assertEquals(List.of("ROUND", "FLAT"), form.fields().get(2).choices()); - } -} diff --git a/core/src/test/java/art/arcane/iris/studio/bridge/StudioScenesTest.java b/core/src/test/java/art/arcane/iris/studio/bridge/StudioScenesTest.java new file mode 100644 index 000000000..af2050f48 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/studio/bridge/StudioScenesTest.java @@ -0,0 +1,66 @@ +package art.arcane.iris.studio.bridge; + +import art.arcane.iris.studio.scene.SceneBlocks; +import art.arcane.iris.studio.scene.SceneView; +import art.arcane.iris.studio.scene.SceneViews; +import org.junit.Test; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +public class StudioScenesTest { + @Test + public void partsAreSentAsLittleEndianIntegersInBlockOrder() { + SceneBlocks scene = new SceneBlocks(); + scene.add(0, 0, 0, "minecraft:stone", 3); + scene.add(1, 0, 0, "minecraft:stone"); + scene.add(2, 0, 0, "minecraft:dirt", 0); + + ByteBuffer wire = ByteBuffer.wrap(StudioScenes.encodeParts(scene)).order(ByteOrder.LITTLE_ENDIAN); + int[] parts = new int[wire.remaining() / Integer.BYTES]; + wire.asIntBuffer().get(parts); + + assertArrayEquals(new int[]{3, SceneBlocks.NO_PART, 0}, parts); + } + + @Test + public void theStudioListsEveryFeaturesViewInOrderThenItsObjects() { + List listed = new StudioScenes().infos().stream().map(StudioScenes.SceneViewInfo::id).toList(); + List expected = new ArrayList<>(SceneViews.all().stream().map(SceneView::id).toList()); + expected.add(PackObjectsSceneView.ID); + expected.add(ProceduralObjectsSceneView.ID); + + assertEquals(expected, listed); + } + + @Test + public void objectFilesAreOnlyShown() { + StudioScenes.SceneViewInfo objects = new StudioScenes().infos().stream() + .filter(info -> info.id().equals(PackObjectsSceneView.ID)).findFirst().orElseThrow(); + + assertFalse(objects.editable()); + assertFalse(objects.baked()); + assertFalse(objects.parts()); + assertFalse(objects.form()); + assertNull(objects.sizes()); + } + + @Test + public void aViewIsListedWithWhatItCanDo() { + StudioScenes.SceneViewInfo caves = new StudioScenes().infos().stream().filter(info -> info.id().equals("caveProfiles")).findFirst().orElseThrow(); + + assertFalse(caves.parts()); + assertFalse(caves.editable()); + assertFalse(caves.creatable()); + assertFalse(caves.form()); + assertEquals(128, caves.sizes().opening()); + } +} diff --git a/core/src/test/java/art/arcane/iris/studio/scene/SceneContractTest.java b/core/src/test/java/art/arcane/iris/studio/scene/SceneContractTest.java new file mode 100644 index 000000000..67983b465 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/studio/scene/SceneContractTest.java @@ -0,0 +1,260 @@ +package art.arcane.iris.studio.scene; + +import art.arcane.iris.generation.runtime.Engine; +import art.arcane.iris.pack.schema.annotation.MaxNumber; +import art.arcane.iris.pack.schema.annotation.MinNumber; +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import org.junit.Test; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Optional; +import java.util.Set; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +public class SceneContractTest { + private static final Gson GSON = new Gson(); + + @Test + public void everyRegisteredViewIsFoundByItsOwnId() { + for (SceneView view : SceneViews.all()) { + assertEquals(view, SceneViews.byId(view.id())); + } + } + + @Test + public void theViewsTheStudioAlreadyShowsKeepTheirIds() { + List ids = SceneViews.all().stream().map(SceneView::id).toList(); + + assertEquals(List.of("caveProfiles", "treeProfiles", "formationProfiles", "fluidProfiles"), ids); + } + + @Test + public void anUnknownViewIsReportedAsMissing() { + assertThrows(NoSuchElementException.class, () -> SceneViews.byId("nothing")); + } + + @Test + public void twoViewsOfOneIdAreRefused() { + assertThrows(IllegalStateException.class, () -> SceneViews.distinct(List.of(new BlocksOnlyView(), new BlocksOnlyView()))); + } + + @Test + public void theStudiosOwnViewsFollowTheFeatures() { + SceneView studioView = new BlocksOnlyView(); + + List views = SceneViews.withStudioViews(List.of(studioView)); + + assertEquals(SceneViews.all().size() + 1, views.size()); + assertEquals(studioView, views.get(views.size() - 1)); + } + + @Test + public void aStudioViewNamedLikeAFeaturesIsRefused() { + SceneView clashing = SceneViews.all().get(0); + + assertThrows(IllegalStateException.class, () -> SceneViews.withStudioViews(List.of(clashing))); + } + + @Test + public void aViewOfBlocksAloneOffersNothingElse() { + SceneView view = new BlocksOnlyView(); + + assertFalse(view.hasForm()); + assertFalse(view.isBaked()); + assertFalse(view.tracesParts()); + assertEquals(null, view.sizes()); + assertThrows(NoSuchElementException.class, () -> view.form(null, "one", Map.of())); + assertThrows(UnsupportedOperationException.class, () -> view.timeBake(null, "one")); + } + + @Test + public void aSceneIsEncodedFromItsLowestCornerWithoutAir() { + SceneBlocks scene = new SceneBlocks(); + scene.add(10, 5, 10, "minecraft:stone"); + scene.add(11, 5, 10, "minecraft:air"); + scene.add(12, 6, 10, "minecraft:dirt"); + scene.add(12, 7, 10, "minecraft:stone"); + + ByteBuffer wire = ByteBuffer.wrap(scene.encode(GSON)).order(ByteOrder.LITTLE_ENDIAN); + int headerLength = wire.getInt(); + byte[] headerBytes = new byte[headerLength]; + wire.get(headerBytes); + JsonObject header = GSON.fromJson(new String(headerBytes, StandardCharsets.UTF_8), JsonObject.class); + wire.position((Integer.BYTES + headerLength + 3) / 4 * 4); + int[] blocks = new int[wire.remaining() / Integer.BYTES]; + wire.asIntBuffer().get(blocks); + + assertEquals(3, scene.count()); + assertEquals(3, header.get("blockCount").getAsInt()); + assertEquals("[\"minecraft:stone\",\"minecraft:dirt\"]", header.get("palette").toString()); + assertEquals("[3,3,1]", header.get("max").toString()); + assertArrayEquals(new int[]{0, 0, 0, 0, 2, 1, 0, 1, 2, 2, 0, 0}, blocks); + } + + @Test + public void anEmptySceneIsOneBlockAcross() { + JsonObject header = headerOf(new SceneBlocks()); + + assertEquals("[1,1,1]", header.get("max").toString()); + assertEquals(0, header.get("blockCount").getAsInt()); + } + + @Test + public void partsFollowTheBlocksThatWereKept() { + SceneBlocks scene = new SceneBlocks(); + scene.add(0, 0, 0, "minecraft:stone", 2); + scene.add(0, 1, 0, "minecraft:air", 5); + scene.add(0, 2, 0, "minecraft:stone"); + scene.add(0, 3, 0, "minecraft:dirt", 0); + + assertArrayEquals(new int[]{2, SceneBlocks.NO_PART, 0}, scene.parts()); + } + + @Test + public void aFormListsPlainSettingsWithTheirLimitsAndDefaults() { + Settings settings = new Settings(); + settings.width = 9; + + SceneForm form = SceneForm.of("Settings", settings, Set.of("hiddenSetting"), Map.of("width", "9"), List.of("A note")); + + assertEquals(List.of("width", "open", "scale", "shape"), form.fields().stream().map(SceneForm.Field::name).toList()); + SceneForm.Field width = form.fields().get(0); + assertEquals("integer", width.kind()); + assertEquals(9, width.value()); + assertEquals(4, width.defaultValue()); + assertEquals(Double.valueOf(1), width.minimum()); + assertEquals(Double.valueOf(32), width.maximum()); + assertTrue(width.changed()); + SceneForm.Field shape = form.fields().get(3); + assertEquals("enum", shape.kind()); + assertEquals("ROUND", shape.value()); + assertEquals(List.of("ROUND", "FLAT"), shape.choices()); + assertFalse(shape.changed()); + } + + @Test + public void typedValuesAreSetOnACopy() { + Settings settings = new Settings(); + + Settings typed = SceneForm.withOverrides(settings, Map.of("width", "12", "open", "true", "scale", "0.5", "shape", "FLAT")); + + assertEquals(12, typed.width); + assertTrue(typed.open); + assertEquals(0.5, typed.scale, 0); + assertEquals(Shape.FLAT, typed.shape); + assertEquals(4, settings.width); + assertEquals(Shape.ROUND, settings.shape); + } + + @Test + public void aTypedValueThatDoesNotReadIsIgnored() { + Settings typed = SceneForm.withOverrides(new Settings(), Map.of("width", "wide", "shape", "CUBE")); + + assertEquals(4, typed.width); + assertEquals(Shape.ROUND, typed.shape); + } + + @Test + public void aPresetEntryIsNamedReadably() { + SceneEntry entry = SceneEntry.preset(Shape.ROUND, 3); + + assertEquals(new SceneEntry("ROUND", "Round", "Presets", 3), entry); + } + + @Test + public void theOpeningSizeIsOneOfTheSizes() { + assertThrows(IllegalArgumentException.class, () -> new SceneSizes(List.of(16, 32), 64)); + } + + @Test + public void aPathIsBuiltStepByStepFromTheRoot() { + JsonPath stem = JsonPath.ROOT.member("parts").element(0).member("stem"); + + assertEquals("parts.0.stem", stem.toString()); + assertEquals(JsonPath.ROOT.member("parts").element(0), stem.parent()); + assertTrue(stem.startsWith(JsonPath.ROOT.member("parts"))); + assertFalse(stem.isElement()); + assertTrue(stem.parent().isElement()); + assertThrows(IllegalStateException.class, JsonPath.ROOT::parent); + } + + @Test + public void onlyANodeInAnArrayCanMove() { + GraphNode.Edits movable = new GraphNode.Edits(Optional.empty(), true, List.of()); + + assertThrows(IllegalArgumentException.class, () -> nodeAt(JsonPath.ROOT, movable)); + assertEquals(movable, nodeAt(JsonPath.ROOT.member("parts").element(1), movable).edits()); + } + + @Test + public void aNodeThatCanBeAddedStartsAsJson() { + JsonPath parts = JsonPath.ROOT.member("parts"); + + assertThrows(IllegalArgumentException.class, () -> new GraphNode.Addition("Stem", parts, "{stem:")); + assertEquals("{\"stem\":{}}", new GraphNode.Addition("Stem", parts, "{\"stem\":{}}").literal()); + } + + private static GraphNode nodeAt(JsonPath path, GraphNode.Edits edits) { + return new GraphNode("Stem", "Stem", path, SceneBlocks.NO_PART, List.of(), List.of(), List.of(), edits); + } + + private static JsonObject headerOf(SceneBlocks scene) { + ByteBuffer wire = ByteBuffer.wrap(scene.encode(GSON)).order(ByteOrder.LITTLE_ENDIAN); + byte[] headerBytes = new byte[wire.getInt()]; + wire.get(headerBytes); + return GSON.fromJson(new String(headerBytes, StandardCharsets.UTF_8), JsonObject.class); + } + + private enum Shape { + ROUND, FLAT + } + + private static final class Settings { + @MinNumber(1) + @MaxNumber(32) + private int width = 4; + private boolean open = false; + private double scale = 1; + private Shape shape = Shape.ROUND; + private int hiddenSetting = 1; + private List nested = List.of(); + } + + private static final class BlocksOnlyView implements SceneView { + @Override + public String id() { + return "blocksOnly"; + } + + @Override + public String label() { + return "Blocks only"; + } + + @Override + public String description() { + return "A view with nothing but scenes"; + } + + @Override + public List entries(Engine engine) { + return List.of(new SceneEntry("one", "One", "", 1)); + } + + @Override + public SceneBlocks scene(Engine engine, SceneRequest request) { + return new SceneBlocks(); + } + } +}