mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-11-27 00:04:42 +00:00
Serve config profile views from the studio bridge
- List cave, tree, formation and fluid profiles as scene views with settings forms - Carve cave profiles with the engine's own carver in a throwaway mantle - Bake tree and formation presets into objects and draw fluids in a lined pool - Apply typed form values to a copy so pack files stay untouched - Serve Minecraft client assets from the cached client jar - Add ProfileForm unit tests
This commit is contained in:
1 parent
aafbb879df
commit
05984cf64a
7 files changed
+1019
-1
No files matched your search
@@ -0,0 +1,106 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.generation.mantle;
|
||||
|
||||
import art.arcane.iris.generation.cave.IrisCaveProfile;
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.generation.runtime.IrisEngineMantle;
|
||||
import art.arcane.volmlib.util.mantle.runtime.Mantle;
|
||||
import art.arcane.volmlib.util.matter.Matter;
|
||||
import art.arcane.volmlib.util.matter.MatterCavern;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* Carves one cave profile with the engine's own carver over a square of flat ground, in a mantle of its own so the
|
||||
* world's is left alone, and says which blocks it opened.
|
||||
*/
|
||||
public final class CaveProfilePreview {
|
||||
private static final int CHUNK_BLOCKS = 16;
|
||||
private static final int CHUNK_COLUMNS = CHUNK_BLOCKS * CHUNK_BLOCKS;
|
||||
private static final int PREFETCH_CHUNKS = 0;
|
||||
private static final int ACCESS_CHUNKS = 1;
|
||||
|
||||
private CaveProfilePreview() {
|
||||
}
|
||||
|
||||
/**
|
||||
* The carved space of a square, {@code size} blocks across and a whole number of chunks, from {@code bottomY} up to
|
||||
* and including {@code surfaceY}, both in engine-local Y (0 is the bottom of the dimension).
|
||||
*
|
||||
* @return one flag per block, {@code (y - bottomY) * size² + z * size + x}
|
||||
*/
|
||||
public static boolean[] carve(Engine engine, IrisCaveProfile profile, int originX, int size, int bottomY, int surfaceY)
|
||||
throws IOException {
|
||||
int height = surfaceY - bottomY + 1;
|
||||
boolean[] carved = new boolean[height * size * size];
|
||||
Path folder = Files.createTempDirectory("iris-cave-preview");
|
||||
Mantle<Matter> mantle = IrisEngineMantle.createMantle(engine, folder, engine::getData);
|
||||
try {
|
||||
IrisCaveCarver3D carver = new IrisCaveCarver3D(engine, profile);
|
||||
int[] surface = new int[CHUNK_COLUMNS];
|
||||
Arrays.fill(surface, surfaceY);
|
||||
double[] weights = new double[CHUNK_COLUMNS];
|
||||
Arrays.fill(weights, 1D);
|
||||
int firstChunkX = Math.floorDiv(originX, CHUNK_BLOCKS);
|
||||
int chunks = size / CHUNK_BLOCKS;
|
||||
for (int chunkZ = 0; chunkZ < chunks; chunkZ++) {
|
||||
for (int chunkX = 0; chunkX < chunks; chunkX++) {
|
||||
int worldChunkX = firstChunkX + chunkX;
|
||||
try (MantleWriter writer = new MantleWriter(engine.getMantle(), mantle, worldChunkX, chunkZ, PREFETCH_CHUNKS, ACCESS_CHUNKS, false)) {
|
||||
carver.carve(writer, worldChunkX, chunkZ, weights, 0D, 0D, null, surface);
|
||||
}
|
||||
readCarved(mantle, carved, worldChunkX, chunkZ, chunkX, chunkZ, size, bottomY, surfaceY);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
mantle.close();
|
||||
deleteQuietly(folder);
|
||||
}
|
||||
return carved;
|
||||
}
|
||||
|
||||
private static void readCarved(Mantle<Matter> mantle, boolean[] carved, int worldChunkX, int worldChunkZ, int chunkX, int chunkZ,
|
||||
int size, int bottomY, int surfaceY) {
|
||||
for (int y = bottomY; y <= surfaceY; y++) {
|
||||
for (int z = 0; z < CHUNK_BLOCKS; z++) {
|
||||
for (int x = 0; x < CHUNK_BLOCKS; x++) {
|
||||
MatterCavern cavern = mantle.get(worldChunkX * CHUNK_BLOCKS + x, y, worldChunkZ * CHUNK_BLOCKS + z, MatterCavern.class);
|
||||
if (cavern == null) {
|
||||
continue;
|
||||
}
|
||||
int cell = (y - bottomY) * size * size + (chunkZ * CHUNK_BLOCKS + z) * size + chunkX * CHUNK_BLOCKS + x;
|
||||
carved[cell] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void deleteQuietly(Path folder) {
|
||||
try (Stream<Path> paths = Files.walk(folder)) {
|
||||
paths.sorted(Comparator.reverseOrder()).forEach(path -> path.toFile().delete());
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.studio.bridge;
|
||||
|
||||
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;
|
||||
import java.util.List;
|
||||
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.
|
||||
*/
|
||||
final class ProfileForm {
|
||||
private ProfileForm() {
|
||||
}
|
||||
|
||||
/** @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<String> choices, boolean changed) {
|
||||
}
|
||||
|
||||
record Form(String title, List<Field> fields, List<String> notes) {
|
||||
}
|
||||
|
||||
static Form of(String title, Object bean, Set<String> hidden, Map<String, String> overrides, List<String> notes) {
|
||||
Object fresh = newInstance(bean.getClass());
|
||||
List<Field> fields = new ArrayList<>();
|
||||
for (java.lang.reflect.Field field : bean.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())));
|
||||
}
|
||||
return new Form(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. */
|
||||
@SuppressWarnings("unchecked")
|
||||
static <T> T withOverrides(T bean, Map<String, String> overrides) {
|
||||
T copy = (T) newInstance(bean.getClass());
|
||||
for (java.lang.reflect.Field field : bean.getClass().getDeclaredFields()) {
|
||||
if (Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers())) {
|
||||
continue;
|
||||
}
|
||||
field.setAccessible(true);
|
||||
try {
|
||||
field.set(copy, field.get(bean));
|
||||
String typed = overrides.get(field.getName());
|
||||
if (typed != null && kindOf(field) != null) {
|
||||
field.set(copy, parse(field.getType(), typed));
|
||||
}
|
||||
} catch (IllegalAccessException | IllegalArgumentException unreadable) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
return copy;
|
||||
}
|
||||
|
||||
private static Field fieldOf(java.lang.reflect.Field field, String kind, Object bean, Object fresh, boolean changed) {
|
||||
field.setAccessible(true);
|
||||
try {
|
||||
Description description = field.getAnnotation(Description.class);
|
||||
MinNumber minimum = field.getAnnotation(MinNumber.class);
|
||||
MaxNumber maximum = field.getAnnotation(MaxNumber.class);
|
||||
List<String> 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)),
|
||||
plain(field.get(fresh)), minimum == null ? null : minimum.value(), maximum == null ? null : maximum.value(), choices, changed);
|
||||
} catch (IllegalAccessException unreadable) {
|
||||
throw new IllegalStateException(unreadable);
|
||||
}
|
||||
}
|
||||
|
||||
private static Object plain(Object value) {
|
||||
return value instanceof Enum<?> constant ? constant.name() : value;
|
||||
}
|
||||
|
||||
private static String kindOf(java.lang.reflect.Field field) {
|
||||
if (Modifier.isStatic(field.getModifiers()) || Modifier.isTransient(field.getModifiers())) {
|
||||
return null;
|
||||
}
|
||||
Class<?> type = field.getType();
|
||||
if (type == boolean.class) {
|
||||
return "boolean";
|
||||
}
|
||||
if (type == int.class || type == long.class) {
|
||||
return "integer";
|
||||
}
|
||||
if (type == double.class || type == float.class) {
|
||||
return "decimal";
|
||||
}
|
||||
return type.isEnum() ? "enum" : null;
|
||||
}
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
private static Object parse(Class<?> type, String text) {
|
||||
if (type == boolean.class) {
|
||||
return Boolean.parseBoolean(text);
|
||||
}
|
||||
if (type == int.class) {
|
||||
return (int) Math.round(Double.parseDouble(text));
|
||||
}
|
||||
if (type == long.class) {
|
||||
return Math.round(Double.parseDouble(text));
|
||||
}
|
||||
if (type == double.class) {
|
||||
return Double.parseDouble(text);
|
||||
}
|
||||
if (type == float.class) {
|
||||
return (float) Double.parseDouble(text);
|
||||
}
|
||||
return Enum.valueOf((Class<? extends Enum>) type, text);
|
||||
}
|
||||
|
||||
private static Object newInstance(Class<?> type) {
|
||||
try {
|
||||
var constructor = type.getDeclaredConstructor();
|
||||
constructor.setAccessible(true);
|
||||
return constructor.newInstance();
|
||||
} catch (ReflectiveOperationException noPlainConstructor) {
|
||||
throw new IllegalStateException(type.getSimpleName() + " has no plain constructor", noPlainConstructor);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.studio.bridge;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Blocks collected for the studio's 3D scene, which it reads little endian:
|
||||
* <pre>
|
||||
* u32 header length | header, UTF-8 JSON | padding to 4 bytes
|
||||
* i32 blocks[blockCount * 4]: x, y, z, then the index of the block's state in the palette
|
||||
* </pre>
|
||||
* 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 {
|
||||
private static final int ALIGNMENT_BYTES = 4;
|
||||
private static final int INTS_PER_BLOCK = 4;
|
||||
private static final Set<String> AIR = Set.of("minecraft:air", "minecraft:cave_air", "minecraft:void_air");
|
||||
|
||||
private final Map<String, Integer> palette = new LinkedHashMap<>();
|
||||
private final List<int[]> blocks = new ArrayList<>();
|
||||
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) {
|
||||
if (AIR.contains(state)) {
|
||||
return;
|
||||
}
|
||||
int paletteIndex = palette.computeIfAbsent(state, ignored -> palette.size());
|
||||
blocks.add(new int[]{x, y, z, paletteIndex});
|
||||
int[] at = {x, y, z};
|
||||
for (int axis = 0; axis < 3; axis++) {
|
||||
min[axis] = Math.min(min[axis], at[axis]);
|
||||
max[axis] = Math.max(max[axis], at[axis] + 1);
|
||||
}
|
||||
}
|
||||
|
||||
int count() {
|
||||
return blocks.size();
|
||||
}
|
||||
|
||||
/** The scene with its lowest corner at the origin; an empty scene is one block across. */
|
||||
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;
|
||||
byte[] header = gson.toJson(new Header(List.copyOf(palette.keySet()), blocks.size(),
|
||||
new int[]{0, 0, 0}, new int[]{top[0] - origin[0], top[1] - origin[1], top[2] - origin[2]})).getBytes(StandardCharsets.UTF_8);
|
||||
int blocksAt = aligned(Integer.BYTES + header.length);
|
||||
ByteBuffer buffer = ByteBuffer.allocate(blocksAt + blocks.size() * INTS_PER_BLOCK * Integer.BYTES).order(ByteOrder.LITTLE_ENDIAN);
|
||||
buffer.putInt(header.length).put(header).position(blocksAt);
|
||||
for (int[] block : blocks) {
|
||||
buffer.putInt(block[0] - origin[0]).putInt(block[1] - origin[1]).putInt(block[2] - origin[2]).putInt(block[3]);
|
||||
}
|
||||
return buffer.array();
|
||||
}
|
||||
|
||||
private static int aligned(int bytes) {
|
||||
return (bytes + ALIGNMENT_BYTES - 1) / ALIGNMENT_BYTES * ALIGNMENT_BYTES;
|
||||
}
|
||||
|
||||
private record Header(List<String> palette, int blockCount, int[] min, int[] max) {
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@ package art.arcane.iris.studio.bridge;
|
||||
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.iris.studio.map.StudioAssets;
|
||||
import art.arcane.iris.studio.map.StudioHover;
|
||||
import art.arcane.iris.studio.view.GuiHost;
|
||||
import art.arcane.iris.studio.view.GuiMarker;
|
||||
@@ -44,6 +45,7 @@ import java.util.HashMap;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.concurrent.CancellationException;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
@@ -72,6 +74,10 @@ public final class StudioBridge implements AutoCloseable {
|
||||
private static final double LARGEST_BLOCKS_PER_PIXEL = 4_096D;
|
||||
private static final long DROPPED_TILE_KEPT_MINUTES = 10;
|
||||
private static final long ENTITY_WAIT_MILLIS = 3_000L;
|
||||
private static final String ASSETS_ENDPOINT = "assets/";
|
||||
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 String VIEW_BIOMES = "biomes";
|
||||
private static final String VIEW_REGIONS = "regions";
|
||||
private static final String VIEW_RIVERS = "rivers";
|
||||
@@ -188,6 +194,10 @@ public final class StudioBridge implements AutoCloseable {
|
||||
private void route(HttpExchange exchange) throws IOException {
|
||||
String endpoint = exchange.getRequestURI().getPath().substring(API.length());
|
||||
Query query = Query.of(exchange.getRequestURI());
|
||||
if (endpoint.startsWith(ASSETS_ENDPOINT)) {
|
||||
sendAsset(exchange, endpoint);
|
||||
return;
|
||||
}
|
||||
switch (endpoint) {
|
||||
case "world" -> sendJson(exchange, STATUS_OK, worldInfo(get(exchange)));
|
||||
case "tile" -> sendBytes(exchange, "application/octet-stream", tile(get(exchange), query));
|
||||
@@ -196,7 +206,11 @@ 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", "patterns", "noise-sources", "saved-worlds" -> sendJson(exchange, STATUS_OK, List.of());
|
||||
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 "profile-form" -> sendJson(exchange, STATUS_OK, profileForm(get(exchange).engine(), query));
|
||||
case "patterns", "noise-sources", "saved-worlds" -> sendJson(exchange, STATUS_OK, List.of());
|
||||
case "events" -> streamEvents(exchange);
|
||||
case "teleport" -> teleport(exchange, query);
|
||||
case "open" -> throw new RequestError(STATUS_NOT_FOUND, "Opening a pack file from the studio is not available in Iris v4");
|
||||
@@ -295,6 +309,63 @@ public final class StudioBridge implements AutoCloseable {
|
||||
return tile.encode(gson);
|
||||
}
|
||||
|
||||
// Asset paths name one file of one Minecraft version, so a studio may keep what it fetched for as long as it runs.
|
||||
private static void sendAsset(HttpExchange exchange, String endpoint) throws IOException {
|
||||
requireMethod(exchange, "GET");
|
||||
byte[] asset;
|
||||
try {
|
||||
asset = StudioAssets.read(endpoint).orElseThrow(() -> new RequestError(STATUS_NOT_FOUND, "No asset " + endpoint));
|
||||
} catch (StudioAssets.NotReadyException notReady) {
|
||||
exchange.getResponseHeaders().set("Retry-After", ASSET_RETRY_SECONDS);
|
||||
throw new RequestError(STATUS_UNAVAILABLE, notReady.getMessage());
|
||||
}
|
||||
exchange.getResponseHeaders().set("Cache-Control", "max-age=" + ASSET_CACHE_SECONDS + ", immutable");
|
||||
sendBytes(exchange, endpoint.endsWith(".png") ? "image/png" : "application/json", asset);
|
||||
}
|
||||
|
||||
private static List<SceneViewInfo> profileViews() {
|
||||
return StudioProfiles.views().stream()
|
||||
.map(view -> new SceneViewInfo(view.id(), view.label(), view.description(), false, false, false, false, view.sizes(), true))
|
||||
.toList();
|
||||
}
|
||||
|
||||
private static List<StudioProfiles.Entry> profileEntries(Engine engine, Query query) {
|
||||
return profileView(query).entries(engine);
|
||||
}
|
||||
|
||||
private static ProfileForm.Form profileForm(Engine engine, Query query) {
|
||||
return profiling(() -> profileView(query).form(engine, query.text("key"), query.prefixed(OVERRIDE_PREFIX)));
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
return profiling(() -> view.scene(engine, query.text("key"), query.whole("variant", 0), size, query.prefixed(OVERRIDE_PREFIX)).encode(gson));
|
||||
}
|
||||
|
||||
private static StudioProfiles.ProfileView profileView(Query query) {
|
||||
return profiling(() -> StudioProfiles.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> T profiling(ProfileTask<T> task) {
|
||||
try {
|
||||
return task.run();
|
||||
} catch (NoSuchElementException unknown) {
|
||||
throw new RequestError(STATUS_NOT_FOUND, unknown.getMessage());
|
||||
} catch (IOException failed) {
|
||||
throw new IllegalStateException(failed);
|
||||
}
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
private interface ProfileTask<T> {
|
||||
T run() throws IOException;
|
||||
}
|
||||
|
||||
private void cancelTile(HttpExchange exchange, Query query) throws IOException {
|
||||
requireMethod(exchange, "POST");
|
||||
droppedFlagOf(query.text("request")).set(true);
|
||||
@@ -452,6 +523,17 @@ public final class StudioBridge implements AutoCloseable {
|
||||
}
|
||||
}
|
||||
|
||||
/** The parameters that start with {@code prefix}, by the rest of their names. */
|
||||
Map<String, String> prefixed(String prefix) {
|
||||
Map<String, String> found = new HashMap<>();
|
||||
values.forEach((name, value) -> {
|
||||
if (name.startsWith(prefix)) {
|
||||
found.put(name.substring(prefix.length()), value);
|
||||
}
|
||||
});
|
||||
return found;
|
||||
}
|
||||
|
||||
boolean has(String name) {
|
||||
return values.containsKey(name);
|
||||
}
|
||||
@@ -468,6 +550,11 @@ 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) {
|
||||
}
|
||||
|
||||
private record PickInspection(String detail, List<Object> sections) {
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,445 @@
|
||||
/*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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<ProfileView> VIEWS = List.of(new CaveView(), new TreeView(), new FormationView(), new FluidView());
|
||||
|
||||
private StudioProfiles() {
|
||||
}
|
||||
|
||||
static List<ProfileView> 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<Integer> blocksAcross, int opening) {
|
||||
}
|
||||
|
||||
interface ProfileView {
|
||||
String id();
|
||||
|
||||
String label();
|
||||
|
||||
String description();
|
||||
|
||||
/** Null when each entry draws one size. */
|
||||
Sizes sizes();
|
||||
|
||||
List<Entry> entries(Engine engine);
|
||||
|
||||
ProfileForm.Form form(Engine engine, String key, Map<String, String> overrides);
|
||||
|
||||
SceneBlocks scene(Engine engine, String key, int variant, int size, Map<String, String> 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);
|
||||
}
|
||||
|
||||
private 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<IrisObject> 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<Entry> entries(Engine engine) {
|
||||
IrisData data = engine.getData();
|
||||
IrisDimension dimension = engine.getDimension();
|
||||
List<Entry> 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<String, String> 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<String, String> 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<String> 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<Entry> 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<String, String> 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<String, String> overrides) {
|
||||
return sceneOf(variantOf(treeOf(key, overrides).getVariantObjects(engine.getData()), variant, "tree"));
|
||||
}
|
||||
|
||||
private static IrisProceduralTree treeOf(String key, Map<String, String> 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<String> 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<Entry> 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<String, String> 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<String, String> overrides) {
|
||||
return sceneOf(variantOf(formationOf(key, overrides).getVariantObjects(engine.getData()), variant, "formation"));
|
||||
}
|
||||
|
||||
private static IrisFormation formationOf(String key, Map<String, String> 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<Entry> 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<String, String> overrides) {
|
||||
IrisFluidProfile fluid = fluidOf(engine, key);
|
||||
IrisData data = engine.getData();
|
||||
List<String> 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<String, String> 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<IrisFluidProfile> fluids(Engine engine) {
|
||||
return engine.getDimension().getHydrology().getFluids();
|
||||
}
|
||||
|
||||
private static IrisFluidProfile fluidOf(Engine engine, String key) {
|
||||
Optional<IrisFluidProfile> found = fluids(engine).stream().filter(fluid -> key.equals(fluid.getName())).findFirst();
|
||||
return found.orElseThrow(() -> new NoSuchElementException("No fluid profile " + key));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.studio.map;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipFile;
|
||||
|
||||
/**
|
||||
* The block models, block states and textures of the Minecraft client, which the Iris Studio app draws blocks with.
|
||||
* They come from the client jar the Swing studio keeps in Iris's cache, fetched from Mojang the first time.
|
||||
*/
|
||||
public final class StudioAssets {
|
||||
private static final String ASSET_FOLDER = "assets/minecraft/";
|
||||
private static CompletableFuture<ZipFile> clientJar;
|
||||
|
||||
private StudioAssets() {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param path such as {@code assets/minecraft/textures/block/stone.png}; empty when there is no such file or the
|
||||
* path leaves the minecraft asset folder
|
||||
* @throws NotReadyException while the client jar is still being fetched, or when fetching it failed
|
||||
*/
|
||||
public static Optional<byte[]> read(String path) throws IOException {
|
||||
if (!path.startsWith(ASSET_FOLDER) || path.contains("..") || path.contains("\\") || path.contains("//")) {
|
||||
return Optional.empty();
|
||||
}
|
||||
ZipFile jar = openedJar();
|
||||
ZipEntry entry = jar.getEntry(path);
|
||||
if (entry == null || entry.isDirectory()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
try (InputStream content = jar.getInputStream(entry)) {
|
||||
return Optional.of(content.readAllBytes());
|
||||
}
|
||||
}
|
||||
|
||||
private static synchronized ZipFile openedJar() {
|
||||
if (clientJar == null) {
|
||||
clientJar = MinecraftClientJar.open();
|
||||
}
|
||||
if (!clientJar.isDone()) {
|
||||
throw new NotReadyException("Fetching the Minecraft client for its textures");
|
||||
}
|
||||
if (clientJar.isCompletedExceptionally()) {
|
||||
clientJar = null;
|
||||
throw new NotReadyException("Could not fetch the Minecraft client");
|
||||
}
|
||||
return clientJar.join();
|
||||
}
|
||||
|
||||
/** The assets cannot be read yet; the message says why, for the studio to show. */
|
||||
public static final class NotReadyException extends RuntimeException {
|
||||
NotReadyException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
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<String, String> 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<String> 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());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user