Read namespaced snippet folders and list snippets

- Resolve snippet references in snippet/<type>/ first, then in snippet/iris/<group>/<type>/
- Route every reference-to-file lookup through SnippetFolders
- Inline list snippets as their entries inside lists of snippet types
- Read values as JSON trees so a malformed entry is skipped instead of re-read forever
- List snippets from both layouts in schemas and workspace file matches
- Add tests for both layouts, list inlining, the malformed value loop and a pack walk
This commit is contained in:
piexel committed 2026-11-18 09:12:15 +01:00
1 parent ed037ea40b
commit 08df9a4ca4
17 files changed
+1010 -115

No files matched your search

@@ -24,14 +24,13 @@ import art.arcane.iris.pack.schema.SchemaBuilder;
import art.arcane.iris.pack.schema.annotation.Snippet;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.world.task.J;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.format.Form;
import art.arcane.volmlib.util.io.IO;
import art.arcane.volmlib.util.json.JSONArray;
import art.arcane.volmlib.util.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.util.List;
public final class ModdedWorkspaceGenerator {
private ModdedWorkspaceGenerator() {
@@ -100,11 +99,7 @@ public final class ModdedWorkspaceGenerator {
try {
String snipType = snippetClass.getDeclaredAnnotation(Snippet.class).value();
JSONObject entry = new JSONObject();
KList<String> fileMatch = new KList<>();
for (int depth = 1; depth < 8; depth++) {
fileMatch.add("/snippet/" + snipType + Form.repeat("/*", depth) + ".json");
}
List<String> fileMatch = data.getSnippetFolders(snipType).workspaceFileMatches();
entry.put("fileMatch", new JSONArray(fileMatch.toArray()));
entry.put("url", "./.iris/schema/snippet/" + snipType + "-schema.json");
@@ -19,6 +19,7 @@
package art.arcane.iris.pack;
import art.arcane.iris.generation.terrain.IrisDimensionType;
import art.arcane.iris.pack.loading.SnippetFolders;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.structure.object.IrisObjectScale;
import art.arcane.iris.world.IrisWorldBoundary;
@@ -35,6 +36,8 @@ import java.util.regex.Pattern;
final class PackDimensionValidator {
private static final String BORROWED_DIMENSION_TYPE = "borrowedDimensionType";
private static final String STYLE_SNIPPET_TYPE = "style";
private static final String RANGE_SNIPPET_TYPE = "range";
private static final Pattern RESOURCE_KEY = Pattern.compile("[a-z0-9_.-]+:[a-z0-9/._-]+");
private PackDimensionValidator() {
@@ -248,7 +251,8 @@ final class PackDimensionValidator {
Object rawStyle = blend.opt("style");
boolean styleObject = rawStyle instanceof JSONObject;
boolean styleSnippet = rawStyle instanceof String reference
&& reference.startsWith("snippet/style/");
&& SnippetFolders.discover(packFolder, STYLE_SNIPPET_TYPE).folders().stream()
.anyMatch(folder -> reference.startsWith(folder + "/"));
if (!styleObject && !styleSnippet) {
blockingErrors.add(context + ".blend.style must be an object or style snippet reference.");
return;
@@ -263,13 +267,12 @@ final class PackDimensionValidator {
private static void validateDimensionStackStyleSnippet(File packFolder, String context, String reference,
List<String> blockingErrors) {
try {
File snippetRoot = new File(packFolder, "snippet/style").getCanonicalFile();
File snippetFile = new File(packFolder, reference + ".json").getCanonicalFile();
if (!snippetFile.toPath().startsWith(snippetRoot.toPath()) || !snippetFile.isFile()) {
SnippetFolders.Lookup snippet = SnippetFolders.discover(packFolder, STYLE_SNIPPET_TYPE).find(packFolder, reference);
if (!snippet.found()) {
blockingErrors.add(context + " references missing style snippet '" + reference + "'.");
return;
}
new JSONObject(Files.readString(snippetFile.toPath(), StandardCharsets.UTF_8));
new JSONObject(Files.readString(snippet.file().toPath(), StandardCharsets.UTF_8));
} catch (Throwable error) {
blockingErrors.add(context + " references invalid style snippet '" + reference + "': "
+ error.getMessage());
@@ -609,17 +612,12 @@ final class PackDimensionValidator {
if (reference == null || !reference.startsWith("snippet/")) {
return null;
}
// Mirror IrisData's snippet adapter: canonical snippet/range/... is used verbatim; any other
// snippet/... reference is re-rooted under this field's snippet folder.
if (!reference.startsWith("snippet/range/")) {
reference = "snippet/range/" + reference.substring("snippet/".length());
}
File snippet = new File(packFolder, reference + ".json");
if (!snippet.isFile()) {
SnippetFolders.Lookup snippet = SnippetFolders.discover(packFolder, RANGE_SNIPPET_TYPE).find(packFolder, reference);
if (!snippet.found()) {
return null;
}
try {
return new JSONObject(Files.readString(snippet.toPath(), StandardCharsets.UTF_8));
return new JSONObject(Files.readString(snippet.file().toPath(), StandardCharsets.UTF_8));
} catch (Throwable e) {
return null;
}
@@ -18,6 +18,7 @@
package art.arcane.iris.pack;
import art.arcane.iris.pack.loading.SnippetFolders;
import art.arcane.volmlib.util.json.JSONArray;
import art.arcane.volmlib.util.json.JSONObject;
@@ -45,7 +46,7 @@ import java.util.TreeMap;
* for a warning aimed at the copy-the-file-and-forget-the-seed mistake.
*/
final class PackGeneratorDuplicateValidator {
private static final String GENERATOR_SNIPPET_FOLDER = "snippet/generator-layer/";
private static final String GENERATOR_SNIPPET_TYPE = "generator-layer";
private PackGeneratorDuplicateValidator() {
}
@@ -125,15 +126,12 @@ final class PackGeneratorDuplicateValidator {
if (reference == null || !reference.startsWith("snippet/")) {
return null;
}
String resolved = reference.startsWith(GENERATOR_SNIPPET_FOLDER)
? reference
: GENERATOR_SNIPPET_FOLDER + reference.substring("snippet/".length());
File snippet = new File(packFolder, resolved + ".json");
if (!snippet.isFile()) {
SnippetFolders.Lookup snippet = SnippetFolders.discover(packFolder, GENERATOR_SNIPPET_TYPE).find(packFolder, reference);
if (!snippet.found()) {
return null;
}
try {
return new JSONObject(Files.readString(snippet.toPath(), StandardCharsets.UTF_8));
return new JSONObject(Files.readString(snippet.file().toPath(), StandardCharsets.UTF_8));
} catch (Throwable e) {
return null;
}
@@ -17,6 +17,7 @@ import art.arcane.iris.generation.terrain.IrisRegion;
import art.arcane.iris.generation.terrain.ShoreBiomeLineages;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.pack.loading.IrisRegistrant;
import art.arcane.iris.pack.loading.SnippetFolders;
import art.arcane.iris.pack.schema.annotation.Snippet;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.spi.IrisPlatforms;
@@ -172,13 +173,13 @@ final class PackHydrologyValidator {
}
private static void warnUnknownSnippetKeys(String field, String reference, Class<?> type, KeyScan scan) {
String base = SNIPPET_ROOT + type.getDeclaredAnnotation(Snippet.class).value() + "/";
String snippet = reference.startsWith(base) ? reference : base + reference.substring(SNIPPET_ROOT.length());
SnippetFolders.Lookup lookup = SnippetFolders.discover(scan.packFolder(), type.getDeclaredAnnotation(Snippet.class).value())
.find(scan.packFolder(), reference);
String snippet = lookup.found() ? lookup.key() : lookup.triedKeys().get(0);
if (!scan.activeSnippets().add(snippet)) {
return;
}
File file = new File(scan.packFolder(), snippet + ".json");
JSONObject object = file.isFile() ? PackValidationIo.readJson(file) : null;
JSONObject object = lookup.found() ? PackValidationIo.readJson(lookup.file()) : null;
if (object != null) {
warnUnknownFields(field + " (" + snippet + ")", object, type, scan);
}
@@ -1,5 +1,6 @@
package art.arcane.iris.pack;
import art.arcane.iris.pack.loading.SnippetFolders;
import art.arcane.iris.structure.object.IrisObjectPlacementScaleInterpolator;
import art.arcane.iris.structure.object.IrisStaticObject;
import art.arcane.volmlib.util.json.JSONArray;
@@ -165,16 +166,13 @@ final class PackStaticObjectValidator {
return object;
}
if (value instanceof String reference && reference.startsWith("snippet/")) {
String base = "snippet/" + snippetType + "/";
String key = reference.startsWith(base) ? reference : base + reference.substring("snippet/".length());
Path root = packFolder.toPath().toAbsolutePath().normalize();
Path snippet = resolveContained(root, key + ".json");
if (snippet == null || !snippet.startsWith(root.resolve(base)) || !Files.isRegularFile(snippet)) {
SnippetFolders.Lookup snippet = SnippetFolders.discover(packFolder, snippetType).find(packFolder, reference);
if (!snippet.found()) {
errors.add(path + " references missing " + snippetType + " snippet '" + reference + "'.");
return null;
}
try {
return new JSONObject(Files.readString(snippet, StandardCharsets.UTF_8));
return new JSONObject(Files.readString(snippet.file().toPath(), StandardCharsets.UTF_8));
} catch (IOException | RuntimeException e) {
errors.add(path + " could not read snippet '" + reference + "': " + e.getMessage());
return null;
@@ -18,6 +18,7 @@
package art.arcane.iris.pack;
import art.arcane.iris.pack.loading.SnippetFolders;
import art.arcane.volmlib.util.json.JSONArray;
import art.arcane.volmlib.util.json.JSONObject;
@@ -36,7 +37,7 @@ import java.util.Locale;
* 16-32 objects per chunk, and a caveProfile.densityThreshold of {} hollows the whole cave range.
*/
final class PackStyledRangeDefaultValidator {
private static final String STYLE_RANGE_SNIPPET_FOLDER = "snippet/style-range/";
private static final String STYLE_RANGE_SNIPPET_TYPE = "style-range";
record Validation(List<String> errors, List<String> warnings) {
Validation {
@@ -116,16 +117,13 @@ final class PackStyledRangeDefaultValidator {
if (raw instanceof JSONObject inline) {
range = inline;
} else if (raw instanceof String reference && reference.startsWith("snippet/")) {
String resolved = reference.startsWith(STYLE_RANGE_SNIPPET_FOLDER)
? reference
: STYLE_RANGE_SNIPPET_FOLDER + reference.substring("snippet/".length());
File snippet = new File(packFolder, resolved + ".json");
if (!snippet.isFile()) {
SnippetFolders.Lookup snippet = SnippetFolders.discover(packFolder, STYLE_RANGE_SNIPPET_TYPE).find(packFolder, reference);
if (!snippet.found()) {
return; // Missing snippets are reported by the content-key machinery.
}
try {
range = new JSONObject(Files.readString(snippet.toPath(), StandardCharsets.UTF_8));
via = " (via snippet '" + resolved + "')";
range = new JSONObject(Files.readString(snippet.file().toPath(), StandardCharsets.UTF_8));
via = " (via snippet '" + snippet.key() + "')";
} catch (Throwable e) {
return;
}
@@ -1,5 +1,6 @@
package art.arcane.iris.pack;
import art.arcane.iris.pack.loading.SnippetFolders;
import art.arcane.iris.generation.terrain.IrisTerrain3D;
import art.arcane.iris.generation.noise.NoiseStyle;
import com.google.gson.Gson;
@@ -12,7 +13,6 @@ import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
@@ -169,15 +169,12 @@ final class PackTerrain3DValidator {
return null;
}
String reference = raw.getAsString();
String prefix = "snippet/" + snippetType + "/";
String resolved = reference.startsWith(prefix) ? reference : prefix + reference.substring(8);
Path root = packFolder.toPath().toAbsolutePath().normalize();
Path path = root.resolve(resolved + ".json").normalize();
if (!path.startsWith(root.resolve(prefix)) || !Files.isRegularFile(path)) {
SnippetFolders.Lookup snippet = SnippetFolders.discover(packFolder, snippetType).find(packFolder, reference);
if (!snippet.found()) {
errors.add(location + " references an unavailable " + snippetType + " snippet '" + reference + "'.");
return null;
}
return readObject(path.toFile(), location + " (" + reference + ")", errors);
return readObject(snippet.file(), location + " (" + reference + ")", errors);
}
private static JsonObject readObject(File file, String location, List<String> errors) {
@@ -18,6 +18,7 @@
package art.arcane.iris.pack.ingest;
import art.arcane.iris.pack.loading.SnippetFolders;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
@@ -114,9 +115,13 @@ final class IngestPack {
if (!reference.startsWith(SNIPPET_PREFIX)) {
return null;
}
String base = SNIPPET_PREFIX + snippetType + "/";
String key = reference.startsWith(base) ? reference : base + reference.substring(SNIPPET_PREFIX.length());
return find(key + ".json").map(JsonObject::deepCopy).orElse(null);
for (String key : SnippetFolders.discover(root.toFile(), snippetType).candidateKeys(reference)) {
Optional<JsonObject> snippet = find(key + ".json");
if (snippet.isPresent()) {
return snippet.get().deepCopy();
}
}
return null;
}
List<String> generatedFiles() {
@@ -25,6 +25,11 @@ import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.google.gson.JsonParser;
import com.google.gson.Strictness;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
@@ -90,6 +95,8 @@ import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
@@ -102,6 +109,7 @@ import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Collection;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.Set;
@@ -143,6 +151,7 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
private ResourceLoader<IrisJigsawPool> jigsawPoolLoader;
private ResourceLoader<IrisJigsawPiece> jigsawPieceLoader;
private KMap<String, KList<String>> possibleSnippets;
private KMap<String, SnippetFolders> snippetFolders;
private Gson gson;
private Gson snippetLoader;
private GsonBuilder builder;
@@ -704,6 +713,7 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
compatReport.clear();
closed = false;
possibleSnippets = new KMap<>();
snippetFolders = new KMap<>();
builder = new GsonBuilder()
.addDeserializationExclusionStrategy(this)
.addSerializationExclusionStrategy(this)
@@ -746,6 +756,7 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
private void hotloadedDatapackCompiler() {
closed = false;
possibleSnippets = new KMap<>();
snippetFolders = new KMap<>();
builder = new GsonBuilder()
.addDeserializationExclusionStrategy(this)
.addSerializationExclusionStrategy(this)
@@ -820,6 +831,7 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
i.clearList();
}
possibleSnippets.clear();
snippetFolders.clear();
}
public boolean hasBlockDropRules(String material) {
@@ -927,12 +939,15 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
if (!typeToken.getRawType().isAnnotationPresent(Snippet.class)) {
return null;
String listedSnippetType = snippetTypeListedBy(typeToken);
if (listedSnippetType != null) {
return snippetListAdapter(gson, typeToken, listedSnippetType);
}
String snippetType = typeToken.getRawType().getDeclaredAnnotation(Snippet.class).value();
String snippedBase = "snippet/" + snippetType + "/";
String snippetType = snippetTypeOf(typeToken.getRawType());
if (snippetType == null) {
return null;
}
return new TypeAdapter<>() {
@Override
@@ -943,73 +958,199 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
@Override
public T read(JsonReader reader) throws IOException {
TypeAdapter<T> adapter = gson.getDelegateAdapter(IrisData.this, typeToken);
String path = reader.getPath();
if (reader.peek().equals(JsonToken.STRING)) {
String r = reader.nextString();
if (!r.startsWith("snippet/"))
return null;
if (!r.startsWith(snippedBase))
r = snippedBase + r.substring(8);
File f = new File(getDataFolder(), r + ".json");
if (f.exists()) {
try (JsonReader snippetReader = new JsonReader(new FileReader(f))){
return adapter.read(snippetReader);
} catch (IrisEngineStreamType.UnknownStreamException unknownStream) {
throw unknownStream;
} catch (Throwable e) {
IrisLogging.error("Couldn't read snippet " + r + " in " + reader.getPath() + " (" + e.getMessage() + ")");
}
} else {
IrisLogging.error("Couldn't find snippet " + r + " in " + reader.getPath());
}
return null;
if (reader.peek() == JsonToken.STRING) {
return readSnippetReference(adapter, snippetType, reader.nextString(), path);
}
JsonElement value = gson.getAdapter(JsonElement.class).read(reader);
try {
return adapter.read(reader);
return adapter.fromJsonTree(value);
} catch (IrisEngineStreamType.UnknownStreamException unknownStream) {
throw unknownStream;
} catch (Throwable e) {
IrisLogging.error("Failed to read " + typeToken.getRawType().getCanonicalName() + "... faking objects a little to load the file at least.");
IrisLogging.error("Failed to read " + typeToken.getRawType().getCanonicalName() + " at " + path
+ " (" + e.getMessage() + "), using defaults");
IrisLogging.reportError(e);
try {
return (T) typeToken.getRawType().getConstructor().newInstance();
} catch (Throwable ignored) {
}
return defaultInstance(typeToken);
}
return null;
}
};
}
public KList<String> getPossibleSnippets(String f) {
return possibleSnippets.computeIfAbsent(f, (k) -> {
KList<String> l = new KList<>();
private <T> @Nullable T readSnippetReference(TypeAdapter<T> adapter, String snippetType, String reference, String path) {
JsonElement snippet = readSnippetFile(snippetType, reference, path);
if (snippet == null) {
return null;
}
File snippetFolder = new File(getDataFolder(), "snippet/" + f);
if (!snippetFolder.exists()) return l;
if (snippet.isJsonArray()) {
IrisLogging.error("Snippet " + reference + " in " + path + " holds several entries, which only a list can take");
return null;
}
String absPath = snippetFolder.getAbsolutePath();
try (var stream = Files.walk(snippetFolder.toPath())) {
stream.filter(Files::isRegularFile)
.map(Path::toAbsolutePath)
.map(Path::toString)
.filter(s -> s.endsWith(".json"))
.map(s -> s.substring(absPath.length() + 1))
.map(s -> s.replace("\\", "/"))
.map(s -> s.substring(0, s.length() - ".json".length()))
.forEach(s -> l.add("snippet/" + s));
} catch (Throwable e) {
IrisLogging.reportError("Failed to scan Iris snippets in " + snippetFolder + ".", e);
try {
return adapter.fromJsonTree(snippet);
} catch (IrisEngineStreamType.UnknownStreamException unknownStream) {
throw unknownStream;
} catch (Throwable e) {
IrisLogging.error("Couldn't read snippet " + reference + " in " + path + " (" + e.getMessage() + ")");
return null;
}
}
@SuppressWarnings("unchecked")
private static <T> @Nullable T defaultInstance(TypeToken<T> typeToken) {
try {
return (T) typeToken.getRawType().getConstructor().newInstance();
} catch (Throwable ignored) {
return null;
}
}
private static @Nullable String snippetTypeOf(Class<?> type) {
Snippet snippet = type.getDeclaredAnnotation(Snippet.class);
return snippet == null ? null : snippet.value();
}
private static @Nullable String snippetTypeListedBy(TypeToken<?> typeToken) {
if (!Collection.class.isAssignableFrom(typeToken.getRawType())
|| !(typeToken.getType() instanceof ParameterizedType listType)) {
return null;
}
Type[] elementTypes = listType.getActualTypeArguments();
if (elementTypes.length != 1 || !(elementTypes[0] instanceof Class<?> elementType)) {
return null;
}
return snippetTypeOf(elementType);
}
/** The folders the named snippet type keeps its files in, including the namespaced ones this pack has. */
public SnippetFolders getSnippetFolders(String snippetType) {
return snippetFolders.computeIfAbsent(snippetType, type -> SnippetFolders.discover(getDataFolder(), type));
}
/** The "snippet/&lt;namespace&gt;/&lt;group&gt;/&lt;type&gt;" folders of the named snippet type, empty in a legacy-only pack. */
public List<String> getNamespacedSnippetFolders(String snippetType) {
return getSnippetFolders(snippetType).namespaced();
}
/** A snippet file holding a JSON array stands for all of its entries, so inside a list it becomes that many items. */
private <T> TypeAdapter<T> snippetListAdapter(Gson gson, TypeToken<T> listType, String snippetType) {
TypeAdapter<T> listAdapter = gson.getDelegateAdapter(this, listType);
return new TypeAdapter<>() {
@Override
public void write(JsonWriter writer, T list) throws IOException {
listAdapter.write(writer, list);
}
return l;
@Override
public T read(JsonReader reader) throws IOException {
if (reader.peek() != JsonToken.BEGIN_ARRAY) {
return listAdapter.read(reader);
}
String path = reader.getPath();
JsonArray entries = gson.getAdapter(JsonArray.class).read(reader);
return listAdapter.fromJsonTree(withSnippetsInlined(entries, snippetType, path));
}
};
}
/** A snippet that can't be read keeps its slot as null, the way a single snippet reference loads. */
private JsonArray withSnippetsInlined(JsonArray entries, String snippetType, String path) {
JsonArray inlined = new JsonArray();
for (int index = 0; index < entries.size(); index++) {
JsonElement entry = entries.get(index);
if (!isSnippetReference(entry)) {
inlined.add(entry);
continue;
}
JsonElement snippet = readSnippetFile(snippetType, entry.getAsString(), path + "[" + index + "]");
if (snippet == null) {
inlined.add(JsonNull.INSTANCE);
} else if (snippet.isJsonArray()) {
entriesOfSnippet(snippet.getAsJsonArray()).forEach(inlined::add);
} else {
inlined.add(snippet);
}
}
return inlined;
}
/** The entries a snippet file holding a list stands for. Lenient parsing reads a trailing comma as a null entry. */
public static List<JsonElement> entriesOfSnippet(JsonArray snippet) {
return snippet.asList().stream().filter(entry -> !entry.isJsonNull()).toList();
}
private static boolean isSnippetReference(JsonElement entry) {
return entry.isJsonPrimitive()
&& entry.getAsJsonPrimitive().isString()
&& entry.getAsString().startsWith(SnippetFolders.PREFIX);
}
/** The parsed snippet file, or null when the reference isn't a snippet or the file can't be read. */
private @Nullable JsonElement readSnippetFile(String snippetType, String reference, String path) {
if (!reference.startsWith(SnippetFolders.PREFIX)) {
return null;
}
SnippetFolders.Lookup lookup = getSnippetFolders(snippetType).find(getDataFolder(), reference);
if (!lookup.found()) {
IrisLogging.error("Couldn't find snippet " + reference + " in " + path + " (tried " + lookup.triedDescription() + ")");
return null;
}
try (JsonReader snippetReader = new JsonReader(new FileReader(lookup.file()))) {
snippetReader.setStrictness(Strictness.LENIENT);
return JsonParser.parseReader(snippetReader);
} catch (Throwable e) {
IrisLogging.error("Couldn't read snippet " + lookup.key() + " in " + path + " (" + e.getMessage() + ")");
return null;
}
}
/** Every snippet of the type, as "snippet/&lt;path inside its folder&gt;", from the legacy and the namespaced folder. */
public KList<String> getPossibleSnippets(String snippetType) {
return possibleSnippets.computeIfAbsent(snippetType, (k) -> {
KList<String> references = new KList<>();
for (String folder : getSnippetFolders(snippetType).folders()) {
listSnippetReferences(new File(getDataFolder(), folder)).stream()
.filter(reference -> !references.contains(reference))
.forEach(references::add);
}
return references;
});
}
private static List<String> listSnippetReferences(File snippetFolder) {
if (!snippetFolder.exists()) {
return List.of();
}
String absPath = snippetFolder.getAbsolutePath();
try (var stream = Files.walk(snippetFolder.toPath())) {
return stream.filter(Files::isRegularFile)
.map(Path::toAbsolutePath)
.map(Path::toString)
.filter(s -> s.endsWith(".json"))
.map(s -> s.substring(absPath.length() + 1))
.map(s -> s.replace("\\", "/"))
.map(s -> s.substring(0, s.length() - ".json".length()))
.map(s -> SnippetFolders.PREFIX + s)
.toList();
} catch (Throwable e) {
IrisLogging.reportError("Failed to scan Iris snippets in " + snippetFolder + ".", e);
return List.of();
}
}
public boolean isClosed() {
return closed;
}
@@ -0,0 +1,115 @@
package art.arcane.iris.pack.loading;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* The pack folders one snippet type keeps its files in: the flat legacy folder "snippet/&lt;type&gt;", plus every
* namespaced folder "snippet/iris/&lt;group&gt;/&lt;type&gt;" that exists in the pack. This is the one
* place a "snippet/..." reference turns into a file.
*/
public record SnippetFolders(String legacy, List<String> namespaced) {
public static final String PREFIX = "snippet/";
/** Only the "iris" namespace counts, so a legacy pack's nested folders such as "snippet/procedural/objects/coral" stay legacy. */
private static final String NAMESPACE = "iris";
private static final String FILE_SUFFIX = ".json";
private static final int WORKSPACE_MATCH_DEPTH = 8;
public static SnippetFolders discover(File packFolder, String legacy) {
List<String> namespaced = new ArrayList<>();
for (File group : subfolders(new File(packFolder, PREFIX + NAMESPACE))) {
if (new File(group, legacy).isDirectory()) {
namespaced.add(PREFIX + NAMESPACE + "/" + group.getName() + "/" + legacy);
}
}
return new SnippetFolders(legacy, List.copyOf(namespaced));
}
/** The folders as "snippet/&lt;folder&gt;", legacy first, then the namespaced ones in sorted order. */
public List<String> folders() {
List<String> folders = new ArrayList<>(namespaced.size() + 1);
folders.add(PREFIX + legacy);
folders.addAll(namespaced);
return folders;
}
/**
* The file keys, without ".json", a reference can mean. A reference already inside one of the folders names that
* file; a short one is tried in the legacy folder first, then each namespaced one.
*/
public List<String> candidateKeys(String reference) {
List<String> folders = folders();
for (String folder : folders) {
if (reference.startsWith(folder + "/")) {
return List.of(reference);
}
}
String shortName = reference.substring(PREFIX.length());
return folders.stream().map(folder -> folder + "/" + shortName).toList();
}
public Lookup find(File packFolder, String reference) {
List<String> candidates = candidateKeys(reference);
Path root = packFolder.toPath().toAbsolutePath().normalize();
for (String key : candidates) {
Path file = fileInsideFolder(root, key);
if (file != null && Files.isRegularFile(file)) {
return new Lookup(file.toFile(), key, candidates);
}
}
return new Lookup(null, null, candidates);
}
/** The IDE file patterns the snippet schema applies to, covering every folder of this type. */
public List<String> workspaceFileMatches() {
List<String> matches = new ArrayList<>();
for (String folder : folders()) {
for (int depth = 1; depth < WORKSPACE_MATCH_DEPTH; depth++) {
matches.add("/" + folder + "/*".repeat(depth) + FILE_SUFFIX);
}
}
return matches;
}
private @Nullable Path fileInsideFolder(Path root, String key) {
String folder = folders().stream().filter(candidate -> key.startsWith(candidate + "/")).findFirst().orElse(null);
if (folder == null) {
return null;
}
try {
Path file = root.resolve(key + FILE_SUFFIX).normalize();
return file.startsWith(root.resolve(folder).normalize()) ? file : null;
} catch (InvalidPathException ignored) {
return null;
}
}
private static File[] subfolders(File folder) {
File[] children = folder.listFiles(File::isDirectory);
if (children == null) {
return new File[0];
}
Arrays.sort(children);
return children;
}
/** The existing snippet file a reference names, or the keys that were tried when there is none. */
public record Lookup(@Nullable File file, @Nullable String key, List<String> triedKeys) {
public boolean found() {
return file != null;
}
public String triedDescription() {
return String.join(", ", triedKeys);
}
}
}
@@ -32,6 +32,8 @@ import art.arcane.volmlib.util.json.JSONObject;
import java.lang.reflect.Field;
import java.lang.reflect.InaccessibleObjectException;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class SchemaBuilder {
@@ -137,6 +139,18 @@ public class SchemaBuilder {
}
}
private String snippetPattern(String snippetType) {
List<String> namespacedFolders = data.getNamespacedSnippetFolders(snippetType);
if (namespacedFolders.isEmpty()) {
return "^snippet/" + snippetType + "/";
}
List<String> folders = new ArrayList<>();
folders.add("snippet/" + snippetType);
folders.addAll(namespacedFolders);
return "^(?:" + String.join("|", folders) + ")/";
}
JSONObject buildSnippet(JSONObject prop, Class<?> type) {
Snippet snippet = type.getDeclaredAnnotation(Snippet.class);
if (snippet == null) return prop;
@@ -155,7 +169,7 @@ public class SchemaBuilder {
enumObj.put("enum", snl);
JSONObject patternObj = new JSONObject();
patternObj.put("type", "string");
patternObj.put("pattern", "^snippet/" + snippet.value() + "/");
patternObj.put("pattern", snippetPattern(snippet.value()));
JSONArray snippetAlt = new JSONArray();
snippetAlt.put(enumObj);
snippetAlt.put(patternObj);
@@ -27,6 +27,7 @@ import art.arcane.volmlib.util.collection.KList;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;
/**
* One of the block palettes a biome places: a surface, sea or cave ceiling layer, its wall or slab blocks, or a
@@ -128,7 +129,10 @@ record BiomePalette(String biomeKey, Kind kind, int index) {
*/
String pathOf(String reference) {
String path = reference.startsWith(SNIPPET_PREFIX) ? reference.substring(SNIPPET_PREFIX.length()) : reference;
return path.startsWith(folder + "/") ? path.substring(folder.length() + 1) : path;
if (path.startsWith(folder + "/")) {
return path.substring(folder.length() + 1);
}
return path.replaceFirst("^iris/[^/]+/" + Pattern.quote(folder) + "/", "");
}
}
@@ -27,9 +27,7 @@ import art.arcane.iris.pack.schema.annotation.Snippet;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.platform.bukkit.plugin.VolmitSender;
import art.arcane.iris.world.task.J;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.collection.KMap;
import art.arcane.volmlib.util.format.Form;
import art.arcane.volmlib.util.io.IO;
import art.arcane.volmlib.util.json.JSONArray;
import art.arcane.volmlib.util.json.JSONObject;
@@ -183,11 +181,7 @@ public class IrisCodeWorkspace {
try {
String snipType = snippetClass.getDeclaredAnnotation(Snippet.class).value();
JSONObject schemaEntry = new JSONObject();
KList<String> fileMatches = new KList<>();
for (int depth = 1; depth < 8; depth++) {
fileMatches.add("/snippet/" + snipType + Form.repeat("/*", depth) + ".json");
}
List<String> fileMatches = dm.getSnippetFolders(snipType).workspaceFileMatches();
schemaEntry.put("fileMatch", new JSONArray(fileMatches.toArray()));
schemaEntry.put("url", "./.iris/schema/snippet/" + snipType + "-schema.json");
@@ -0,0 +1,111 @@
package art.arcane.iris.pack.loading;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.generation.runtime.PreservationRegistry;
import art.arcane.iris.pack.value.IrisRange;
import art.arcane.iris.spi.IrisServices;
import art.arcane.iris.testsupport.PlatformLeakGuard;
import art.arcane.volmlib.util.collection.KList;
import org.junit.After;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.mock;
public class IrisDataSnippetMalformedValueTest {
private static final long RUNAWAY_READ_TIMEOUT_MILLISECONDS = 20_000;
private static final double DEFAULT_RANGE_MIN = 16;
private static final double DEFAULT_RANGE_MAX = 32;
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
@Rule
public final TemporaryFolder temporary = new TemporaryFolder();
private IrisSettings previousSettings;
private Path pack;
private IrisData data;
public static class RangeListHolder {
public List<IrisRange> ranges;
public KList<IrisRange> keyedRanges;
}
public static class RangeHolder {
public IrisRange range;
}
@Before
public void createData() throws IOException {
previousSettings = IrisSettings.settings;
IrisSettings.settings = new IrisSettings();
IrisServices.register(PreservationRegistry.class, mock(PreservationRegistry.class));
pack = temporary.newFolder("pack").toPath();
data = IrisData.get(new File(pack.toFile(), "."));
}
@After
public void closeData() {
data.close();
IrisServices.remove(PreservationRegistry.class);
IrisSettings.settings = previousSettings;
}
@Test(timeout = RUNAWAY_READ_TIMEOUT_MILLISECONDS)
public void numberInAListOfSnippetTypesIsReplacedByTheDefaultAndReadingMovesOn() {
RangeListHolder holder = data.getGson().fromJson(
"{\"ranges\":[5,{\"min\":1,\"max\":2}],\"keyedRanges\":[true]}", RangeListHolder.class);
assertEquals(2, holder.ranges.size());
assertDefaultRange(holder.ranges.get(0));
assertEquals(1, holder.ranges.get(1).getMin(), 0);
assertEquals(1, holder.keyedRanges.size());
assertDefaultRange(holder.keyedRanges.get(0));
}
@Test(timeout = RUNAWAY_READ_TIMEOUT_MILLISECONDS)
public void nestedArrayInAListOfSnippetTypesIsReplacedByTheDefault() {
RangeListHolder holder = data.getGson().fromJson("{\"ranges\":[[1,2],[[3]]]}", RangeListHolder.class);
assertEquals(2, holder.ranges.size());
assertDefaultRange(holder.ranges.get(0));
assertDefaultRange(holder.ranges.get(1));
}
@Test(timeout = RUNAWAY_READ_TIMEOUT_MILLISECONDS)
public void malformedFieldKeepsTheDefaultAndTheValuesAfterIt() {
RangeHolder holder = data.getGson().fromJson("{\"range\":7}", RangeHolder.class);
assertDefaultRange(holder.range);
}
@Test(timeout = RUNAWAY_READ_TIMEOUT_MILLISECONDS)
public void wrongTypedEntryOfAListSnippetIsReplacedByTheDefault() throws IOException {
Path snippet = pack.resolve("snippet/range/broken.json");
Files.createDirectories(snippet.getParent());
Files.writeString(snippet, "[[1]]");
RangeListHolder holder = data.getGson().fromJson("{\"ranges\":[\"snippet/broken\"]}", RangeListHolder.class);
assertEquals(1, holder.ranges.size());
assertDefaultRange(holder.ranges.get(0));
}
private static void assertDefaultRange(IrisRange range) {
assertNotNull(range);
assertEquals(DEFAULT_RANGE_MIN, range.getMin(), 0);
assertEquals(DEFAULT_RANGE_MAX, range.getMax(), 0);
}
}
@@ -0,0 +1,269 @@
package art.arcane.iris.pack.loading;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.noise.IrisExpression;
import art.arcane.iris.generation.noise.IrisGenerator;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.generation.terrain.IrisRegion;
import art.arcane.iris.pack.mod.IrisMod;
import art.arcane.iris.pack.schema.annotation.Snippet;
import art.arcane.iris.structure.jigsaw.IrisJigsawPiece;
import art.arcane.iris.structure.jigsaw.IrisJigsawPool;
import art.arcane.iris.structure.placement.IrisStructure;
import art.arcane.iris.world.entity.IrisEntity;
import art.arcane.iris.world.entity.IrisMarker;
import art.arcane.iris.world.entity.IrisSpawner;
import art.arcane.iris.world.loot.IrisLootTable;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
/**
* Walks every snippet reference of a real pack, set through IRIS_TEST_PACK, and checks it resolves for the type of the
* field it sits in. Reads the pack only; skipped when the variable is unset.
*/
public class IrisDataSnippetPackWalkTest {
private static final String PACK_ENVIRONMENT_VARIABLE = "IRIS_TEST_PACK";
private static final String ENGINE_PACKAGE_PREFIX = "art.arcane.iris";
private static final List<Class<? extends IrisRegistrant>> PACK_ROOT_TYPES = List.of(
IrisBiome.class, IrisRegion.class, IrisDimension.class, IrisGenerator.class, IrisEntity.class,
IrisLootTable.class, IrisSpawner.class, IrisMarker.class, IrisExpression.class, IrisMod.class,
IrisStructure.class, IrisJigsawPool.class, IrisJigsawPiece.class);
private File pack;
private final Map<String, Class<?>> snippetTypesByFolder = new HashMap<>();
private final Map<Class<?>, SnippetFolders> foldersByType = new HashMap<>();
private final List<String> unresolved = new ArrayList<>();
private int resolved;
private int outsideSnippetFields;
private int snippetFilesWalked;
private final List<String> untypedSnippetFiles = new ArrayList<>();
@Test
public void everySnippetReferenceInThePackResolves() throws Exception {
String packPath = System.getenv(PACK_ENVIRONMENT_VARIABLE);
assumeTrue(PACK_ENVIRONMENT_VARIABLE + " is not set", packPath != null && !packPath.isBlank());
pack = new File(packPath);
assumeTrue(pack + " is not a folder", pack.isDirectory());
Set<Class<?>> visitedTypes = new HashSet<>();
PACK_ROOT_TYPES.forEach(root -> collectSnippetTypes(root, visitedTypes));
for (Class<? extends IrisRegistrant> root : PACK_ROOT_TYPES) {
walkRootFolder(root);
}
walkSnippetFiles();
System.out.println("snippet pack walk: resolved=" + resolved + " unresolved=" + unresolved.size()
+ " outsideSnippetFields=" + outsideSnippetFields + " snippetFilesWalked=" + snippetFilesWalked
+ " untypedSnippetFiles=" + untypedSnippetFiles.size());
untypedSnippetFiles.forEach(file -> System.out.println("untyped snippet file: " + file));
assertTrue("unresolved snippet references:\n" + String.join("\n", unresolved), unresolved.isEmpty());
assertTrue("the pack holds no snippet references", resolved > 0);
}
private void walkRootFolder(Class<? extends IrisRegistrant> root) throws Exception {
String folderName = root.getConstructor().newInstance().getFolderName();
for (File file : jsonFilesUnder(new File(pack, folderName))) {
walk(parse(file), root, relative(file));
}
}
private void walkSnippetFiles() throws IOException {
for (File file : jsonFilesUnder(new File(pack, "snippet"))) {
Class<?> type = typeOfSnippetFile(file);
if (type == null) {
untypedSnippetFiles.add(relative(file));
continue;
}
snippetFilesWalked++;
JsonElement content = parse(file);
if (content != null && content.isJsonArray()) {
content.getAsJsonArray().forEach(entry -> walk(entry, type, relative(file)));
} else {
walk(content, type, relative(file));
}
}
}
private Class<?> typeOfSnippetFile(File file) {
String[] segments = relative(file).split("/");
Class<?> legacyType = snippetTypesByFolder.get(segments[1]);
if (legacyType != null) {
return legacyType;
}
return segments.length > 4 ? snippetTypesByFolder.get(segments[3]) : null;
}
private void walk(JsonElement value, Type type, String path) {
if (value == null || value.isJsonNull()) {
return;
}
Class<?> raw = rawClass(type);
if (value.isJsonPrimitive()) {
checkReference(value, raw, path);
return;
}
if (value.isJsonArray()) {
walkElements(value.getAsJsonArray(), elementTypeOf(type), path);
return;
}
walkObject(value.getAsJsonObject(), type, raw, path);
}
private void walkElements(JsonArray elements, Type elementType, String path) {
for (int index = 0; index < elements.size(); index++) {
walk(elements.get(index), elementType, path + "[" + index + "]");
}
}
private void walkObject(JsonObject object, Type type, Class<?> raw, String path) {
if (raw == null) {
return;
}
if (Map.class.isAssignableFrom(raw)) {
Type valueType = typeArgument(type, 1);
object.entrySet().forEach(entry -> walk(entry.getValue(), valueType, path + "." + entry.getKey()));
return;
}
Map<String, Type> fields = fieldTypesOf(raw);
object.entrySet().forEach(entry -> {
Type fieldType = fields.get(entry.getKey());
if (fieldType != null) {
walk(entry.getValue(), fieldType, path + "." + entry.getKey());
}
});
}
private void checkReference(JsonElement value, Class<?> raw, String path) {
if (!value.getAsJsonPrimitive().isString() || !value.getAsString().startsWith(SnippetFolders.PREFIX)) {
return;
}
String reference = value.getAsString();
SnippetFolders folders = raw == null ? null : foldersOf(raw);
if (folders == null) {
outsideSnippetFields++;
return;
}
if (folders.find(pack, reference).found()) {
resolved++;
return;
}
unresolved.add(path + " -> " + reference + " (tried " + folders.candidateKeys(reference) + ")");
}
private SnippetFolders foldersOf(Class<?> type) {
Snippet snippet = type.getDeclaredAnnotation(Snippet.class);
if (snippet == null) {
return null;
}
return foldersByType.computeIfAbsent(type, ignored -> SnippetFolders.discover(pack, snippet.value()));
}
private void collectSnippetTypes(Type type, Set<Class<?>> visited) {
if (type instanceof ParameterizedType parameterized) {
for (Type argument : parameterized.getActualTypeArguments()) {
collectSnippetTypes(argument, visited);
}
}
Class<?> raw = rawClass(type);
if (raw == null) {
return;
}
if (raw.isArray()) {
collectSnippetTypes(raw.getComponentType(), visited);
return;
}
if (!raw.getName().startsWith(ENGINE_PACKAGE_PREFIX) || raw.isEnum() || raw.isInterface() || !visited.add(raw)) {
return;
}
Snippet snippet = raw.getDeclaredAnnotation(Snippet.class);
if (snippet != null) {
snippetTypesByFolder.putIfAbsent(snippet.value(), raw);
}
fieldTypesOf(raw).values().forEach(fieldType -> collectSnippetTypes(fieldType, visited));
}
private static Map<String, Type> fieldTypesOf(Class<?> type) {
Map<String, Type> fields = new HashMap<>();
for (Class<?> current = type; current != null && current != Object.class; current = current.getSuperclass()) {
for (Field field : current.getDeclaredFields()) {
if (!Modifier.isStatic(field.getModifiers()) && !Modifier.isTransient(field.getModifiers())) {
fields.putIfAbsent(field.getName(), field.getGenericType());
}
}
}
return fields;
}
private static Class<?> rawClass(Type type) {
if (type instanceof Class<?> raw) {
return raw;
}
if (type instanceof ParameterizedType parameterized && parameterized.getRawType() instanceof Class<?> raw) {
return raw;
}
return null;
}
private static Type elementTypeOf(Type type) {
if (type instanceof Class<?> raw && raw.isArray()) {
return raw.getComponentType();
}
return typeArgument(type, 0);
}
private static Type typeArgument(Type type, int index) {
if (type instanceof ParameterizedType parameterized && index < parameterized.getActualTypeArguments().length) {
return parameterized.getActualTypeArguments()[index];
}
return Object.class;
}
private static JsonElement parse(File file) {
try {
return JsonParser.parseString(Files.readString(file.toPath()));
} catch (Exception unreadable) {
return null;
}
}
private static List<File> jsonFilesUnder(File folder) {
if (!folder.isDirectory()) {
return List.of();
}
try (Stream<Path> files = Files.walk(folder.toPath())) {
return files.filter(Files::isRegularFile)
.filter(file -> file.getFileName().toString().endsWith(".json"))
.map(Path::toFile)
.sorted()
.toList();
} catch (IOException unreadable) {
throw new IllegalStateException(unreadable);
}
}
private String relative(File file) {
return pack.toPath().relativize(file.toPath()).toString().replace('\\', '/');
}
}
@@ -0,0 +1,252 @@
package art.arcane.iris.pack.loading;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.generation.runtime.PreservationRegistry;
import art.arcane.iris.pack.value.IrisRate;
import art.arcane.iris.spi.IrisServices;
import art.arcane.iris.testsupport.PlatformLeakGuard;
import art.arcane.volmlib.util.collection.KList;
import org.junit.After;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.mock;
public class IrisDataSnippetTest {
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
@Rule
public final TemporaryFolder temporary = new TemporaryFolder();
private IrisSettings previousSettings;
private Path pack;
private IrisData data;
public static class RateHolder {
public IrisRate rate;
}
public static class RateListHolder {
public List<IrisRate> rates;
public KList<IrisRate> keyedRates;
}
@Before
public void createPack() throws IOException {
previousSettings = IrisSettings.settings;
IrisSettings.settings = new IrisSettings();
IrisServices.register(PreservationRegistry.class, mock(PreservationRegistry.class));
pack = temporary.newFolder("pack").toPath();
}
@After
public void closeData() {
if (data != null) {
data.close();
}
IrisServices.remove(PreservationRegistry.class);
IrisSettings.settings = previousSettings;
}
@Test
public void shortReferenceResolvesInTheNamespacedFolder() throws IOException {
write("snippet/iris/spawn/rate/fast.json", "{\"amount\":7}");
assertEquals(7, rateOf("\"snippet/fast\"").getAmount());
}
@Test
public void fullReferenceResolvesInTheNamespacedFolder() throws IOException {
write("snippet/iris/spawn/rate/fast.json", "{\"amount\":7}");
assertEquals(7, rateOf("\"snippet/iris/spawn/rate/fast\"").getAmount());
}
@Test
public void nestedNamespacedPathResolves() throws IOException {
write("snippet/iris/spawn/rate/groups/fast.json", "{\"amount\":8}");
assertEquals(8, rateOf("\"snippet/groups/fast\"").getAmount());
assertEquals(8, rateOf("\"snippet/iris/spawn/rate/groups/fast\"").getAmount());
}
@Test
public void legacyLayoutStillResolves() throws IOException {
write("snippet/rate/slow.json", "{\"amount\":3}");
assertEquals(3, rateOf("\"snippet/slow\"").getAmount());
assertEquals(3, rateOf("\"snippet/rate/slow\"").getAmount());
}
@Test
public void legacyFolderWinsAShortReferenceWhenBothLayoutsHoldTheFile() throws IOException {
write("snippet/rate/both.json", "{\"amount\":1}");
write("snippet/iris/spawn/rate/both.json", "{\"amount\":2}");
assertEquals(1, rateOf("\"snippet/both\"").getAmount());
assertEquals(1, rateOf("\"snippet/rate/both\"").getAmount());
assertEquals(2, rateOf("\"snippet/iris/spawn/rate/both\"").getAmount());
}
@Test
public void namespacedFolderIsTriedWhenTheLegacyFileIsMissing() throws IOException {
write("snippet/rate/other.json", "{\"amount\":1}");
write("snippet/iris/spawn/rate/only-here.json", "{\"amount\":2}");
assertEquals(2, rateOf("\"snippet/only-here\"").getAmount());
}
@Test
public void snippetsOfAnotherTypeAreNotUsed() throws IOException {
write("snippet/iris/spawn/duration/fast.json", "{\"amount\":7}");
assertNull(rateOf("\"snippet/fast\""));
}
@Test
public void referenceCannotLeaveItsSnippetFolder() throws IOException {
write("snippet/duration/fast.json", "{\"amount\":7}");
write("snippet/rate/other.json", "{\"amount\":1}");
assertNull(rateOf("\"snippet/rate/../duration/fast\""));
}
@Test
public void missingSnippetYieldsNull() throws IOException {
write("snippet/rate/other.json", "{\"amount\":1}");
assertNull(rateOf("\"snippet/absent\""));
}
@Test
public void namespaceDeeperThanTwoSegmentsIsNotAFolderOfTheType() throws IOException {
write("snippet/one/two/three/rate/deep.json", "{\"amount\":7}");
assertNull(rateOf("\"snippet/deep\""));
}
@Test
public void arraySnippetInAListStandsForAllItsEntries() throws IOException {
write("snippet/iris/spawn/rate/many.json", "[{\"amount\":1},{\"amount\":2},]");
write("snippet/iris/spawn/rate/one.json", "{\"amount\":5}");
RateListHolder holder = data().getGson().fromJson(
"{\"rates\":[\"snippet/many\",\"snippet/one\",{\"amount\":9}],"
+ "\"keyedRates\":[\"snippet/many\",{\"amount\":9}]}",
RateListHolder.class);
assertEquals(List.of(1, 2, 5, 9), amountsOf(holder.rates));
assertEquals(List.of(1, 2, 9), amountsOf(holder.keyedRates));
}
@Test
public void unreadableSnippetKeepsItsSlotInAList() throws IOException {
write("snippet/rate/one.json", "{\"amount\":5}");
RateListHolder holder = data().getGson().fromJson(
"{\"rates\":[\"snippet/missing\",\"snippet/one\"]}", RateListHolder.class);
assertEquals(2, holder.rates.size());
assertNull(holder.rates.get(0));
assertEquals(5, holder.rates.get(1).getAmount());
}
@Test
public void singleReferenceToAnArraySnippetYieldsNull() throws IOException {
write("snippet/rate/many.json", "[{\"amount\":1},{\"amount\":2}]");
assertNull(rateOf("\"snippet/many\""));
}
@Test
public void listsWithoutReferencesStillLoad() {
RateListHolder holder = data().getGson().fromJson(
"{\"rates\":[{\"amount\":4},{\"amount\":6}]}", RateListHolder.class);
assertEquals(List.of(4, 6), amountsOf(holder.rates));
}
@Test
public void possibleSnippetsCoverBothFoldersWithoutDuplicates() throws IOException {
write("snippet/rate/a.json", "{}");
write("snippet/rate/shared.json", "{}");
write("snippet/iris/spawn/rate/b.json", "{}");
write("snippet/iris/spawn/rate/shared.json", "{}");
write("snippet/iris/spawn/rate/nested/c.json", "{}");
assertEquals(List.of("snippet/a", "snippet/shared", "snippet/b", "snippet/nested/c"),
new ArrayList<>(data().getPossibleSnippets("rate")));
}
@Test
public void onlyTheIrisNamespaceHoldsNamespacedFoldersListedInSortedOrder() throws IOException {
write("snippet/zeta/spawn/rate/x.json", "{}");
write("snippet/iris/spawn/rate/x.json", "{}");
write("snippet/iris/creatures/rate/x.json", "{}");
write("snippet/iris/spawn/duration/x.json", "{}");
assertEquals(List.of("snippet/iris/creatures/rate", "snippet/iris/spawn/rate"),
data().getNamespacedSnippetFolders("rate"));
}
@Test
public void nestedLegacyFolderNamedLikeATypeStaysLegacy() throws IOException {
write("snippet/procedural/objects/rate/nested.json", "{\"amount\":7}");
assertNull(rateOf("\"snippet/nested\""));
assertEquals(List.of(), data().getNamespacedSnippetFolders("rate"));
}
@Test
public void folderListingRefreshesAfterTheListsAreCleared() throws IOException {
IrisData loaded = data();
assertEquals(List.of(), loaded.getNamespacedSnippetFolders("rate"));
write("snippet/iris/spawn/rate/x.json", "{\"amount\":2}");
loaded.clearLists();
assertEquals(List.of("snippet/iris/spawn/rate"), loaded.getNamespacedSnippetFolders("rate"));
assertEquals(2, rateOf("\"snippet/x\"").getAmount());
}
private IrisRate rateOf(String jsonValue) {
return data().getGson().fromJson("{\"rate\":" + jsonValue + "}", RateHolder.class).rate;
}
private IrisData data() {
if (data == null) {
data = IrisData.get(new File(pack.toFile(), "."));
}
return data;
}
private void write(String relative, String content) throws IOException {
Path file = pack.resolve(relative);
Files.createDirectories(file.getParent());
Files.writeString(file, content);
}
private static List<Integer> amountsOf(List<IrisRate> rates) {
assertNotNull(rates);
List<Integer> amounts = new ArrayList<>();
for (IrisRate rate : rates) {
assertNotNull(rate);
amounts.add(rate.getAmount());
}
return amounts;
}
}
@@ -3,6 +3,7 @@ package art.arcane.iris.structure.object;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.pack.loading.SnippetFolders;
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
import art.arcane.iris.generation.geometry.IrisBlockVector;
import art.arcane.volmlib.util.math.RNG;
@@ -24,7 +25,9 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.CALLS_REAL_METHODS;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -128,6 +131,8 @@ public class IrisObjectGlobalScaleTest {
Files.writeString(snippets.resolve("half.json"), "{\"size\":0.5}");
IrisData data = mock(IrisData.class, CALLS_REAL_METHODS);
when(data.getDataFolder()).thenReturn(root.toFile());
doAnswer(lookup -> SnippetFolders.discover(root.toFile(), lookup.getArgument(0)))
.when(data).getSnippetFolders(anyString());
Gson loaderGson = new GsonBuilder().registerTypeAdapterFactory(data).create();
IrisDimension dimension = new IrisDimension().setAllObjectScaleFactor(2D);
IrisObject origin = new IrisObject(4, 4, 4);