mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-11-27 00:04:42 +00:00
List a pack's unread fields once and draw plugin blocks in the palette view
Unknown fields used to log one warning per field per file, with a snippet, every time a pack loaded. A pack without modules logged about 2200 of them at startup. Now they are gathered per pack and stated as one list a few seconds after the first, one line per field with its first file and how many others hold it. Each file's field is stated once per server start. The header says when the pack loads no modules, which is why layers, wall and decorators were unread here. The Bukkit warning path stripped colours. It now keeps section-sign codes and still reads nothing else as markup. The palette view drew CraftEngine blocks by their server-only state, such as craftengine:custom_7, which has no assets. The pattern header now names a plugin block as the pack does and adds the vanilla state players see, which the studio draws. Asset reads check plugin resource packs before the client jar for minecraft paths too, since those packs replace vanilla blockstates.
This commit is contained in:
1 parent
f98b6dc548
commit
a71b27ce31
21 files changed
+326
-55
No files matched your search
@@ -591,15 +591,18 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps the section-sign colours core writes but reads nothing else as markup: a diagnostic quotes pack files,
|
||||
* whose text may hold tag-like or ampersand sequences that have to show as written.
|
||||
*/
|
||||
private static void diagnostic(Level level, String message) {
|
||||
String line = IrisLogging.clean(message);
|
||||
Iris plugin = instance;
|
||||
ComponentLog.log(
|
||||
plugin,
|
||||
Logger.getLogger("Iris"),
|
||||
logPrefix(plugin),
|
||||
level,
|
||||
ComponentText.literal(line),
|
||||
ComponentText.section(message),
|
||||
null);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -56,7 +56,7 @@ public class IrisDiagnosticLogLevelTest {
|
||||
assertTrue(bridge, bridge.contains("diagnostic(diagnostic, message)"));
|
||||
String diagnostic = method(source, "private static void diagnostic(Level level, String message)");
|
||||
assertTrue(diagnostic, diagnostic.contains("ComponentLog.log("));
|
||||
assertTrue(diagnostic, diagnostic.contains("ComponentText.literal(line)"));
|
||||
assertTrue(diagnostic, diagnostic.contains("ComponentText.section(message)"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -20,6 +20,7 @@ package art.arcane.iris.core.link;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* What the studio needs to know of the blocks plugins add, without reaching for the server's plugin API.
|
||||
@@ -33,6 +34,15 @@ public interface CustomBlockSource {
|
||||
*/
|
||||
List<CustomBlockLook> blocks();
|
||||
|
||||
/**
|
||||
* Some plugins generate their blocks as states only the server knows, such as {@code craftengine:custom_7}, and
|
||||
* send players a vanilla state in their place.
|
||||
*
|
||||
* @param state a block state the server holds
|
||||
* @return the plugin block it is with the state players see, or empty when it is no plugin's block
|
||||
*/
|
||||
Optional<CustomBlockLook> lookOf(String state);
|
||||
|
||||
/**
|
||||
* @return the resource packs holding the models of the plugins' blocks, those that have one on disk
|
||||
*/
|
||||
|
||||
@@ -148,6 +148,15 @@ public abstract class ExternalDataProvider {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param data A block the server holds, which for a plugin block may be a state only the server knows
|
||||
* @return The plugin block it is with the vanilla state players see, or nothing when it is not one of the provider's
|
||||
*/
|
||||
@NotNull
|
||||
public Optional<CustomBlockLook> lookOf(@NotNull BlockData data) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return The resource pack holding the models of the provider's blocks, or nothing when it has none on disk
|
||||
*/
|
||||
|
||||
@@ -213,6 +213,16 @@ public class CraftEngineDataProvider extends ExternalDataProvider implements Lis
|
||||
return List.copyOf(looksByShownState.values());
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull Optional<CustomBlockLook> lookOf(@NotNull BlockData data) {
|
||||
ImmutableBlockState state = customStateOf(data);
|
||||
if (state == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
Key owner = state.owner().value().id();
|
||||
return Optional.of(new CustomBlockLook(new Identifier(owner.namespace(), owner.value()), state.visualBlockState().getAsString()));
|
||||
}
|
||||
|
||||
// PackManager#resourcePackPath went away in CraftEngine's later versions, which set this path in their workflows.
|
||||
@Override
|
||||
public @NotNull Optional<Path> getResourcePack() {
|
||||
|
||||
@@ -72,6 +72,8 @@ import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import art.arcane.volmlib.util.json.JSONObject;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
@@ -422,6 +424,32 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
|
||||
public void preprocessObject(IrisRegistrant t) {
|
||||
}
|
||||
|
||||
/** States the fields of {@code file} that nothing reads, in the one list of this pack's unread fields. */
|
||||
public void reportUnknownFields(File file, String rawText, String resourceTypeName, Class<?> type, Set<String> moduleKeys,
|
||||
JSONObject parsed) {
|
||||
List<UnknownPackFields.Field> unknown = JsonSchemaValidator.unknownTopLevelKeys(parsed, rawText, pathInPack(file),
|
||||
resourceTypeName, type, moduleKeys);
|
||||
if (unknown.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
UnknownPackFields.add(new UnknownPackFields.Pack(dataFolder, modules.label(), loadsModules()), unknown);
|
||||
}
|
||||
|
||||
private String pathInPack(File file) {
|
||||
Path folder = dataFolder.toPath().toAbsolutePath().normalize();
|
||||
Path path = file.toPath().toAbsolutePath().normalize();
|
||||
return path.startsWith(folder) ? folder.relativize(path).toString().replace(File.separatorChar, '/') : file.getPath();
|
||||
}
|
||||
|
||||
/** A pack whose modules failed to load counts as loading them: the failure is reported on its own. */
|
||||
private boolean loadsModules() {
|
||||
try {
|
||||
return !modules.pack().packModules().isEmpty();
|
||||
} catch (RuntimeException failedToLoad) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public void close() {
|
||||
closed = true;
|
||||
dump();
|
||||
|
||||
@@ -5,12 +5,14 @@ import art.arcane.iris.util.common.format.C;
|
||||
import art.arcane.volmlib.util.json.JSONObject;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/** Warns about JSON a pack file holds that its type ignores, and reports a file that failed to load with the line at fault. */
|
||||
/** Finds JSON a pack file holds that its type ignores, and reports a file that failed to load with the line at fault. */
|
||||
public final class JsonSchemaValidator {
|
||||
private static final int SUGGESTION_MAX_DISTANCE = 4;
|
||||
|
||||
@@ -18,21 +20,24 @@ public final class JsonSchemaValidator {
|
||||
}
|
||||
|
||||
/**
|
||||
* Warns about every top-level key that is neither a field of {@code objectClass} nor one of
|
||||
* {@code moduleKeys}, the keys the pack's modules read at this resource's target.
|
||||
* Every top-level key that is neither a field of {@code objectClass} nor one of {@code moduleKeys}, the keys the
|
||||
* pack's modules read at this resource's target; {@code packFile} is the file's path in its pack.
|
||||
*/
|
||||
public static void validateTopLevelKeys(JSONObject parsed, String rawText, File file, String resourceTypeName, Class<?> objectClass,
|
||||
Set<String> moduleKeys) {
|
||||
public static List<UnknownPackFields.Field> unknownTopLevelKeys(JSONObject parsed, String rawText, String packFile, String resourceTypeName,
|
||||
Class<?> objectClass, Set<String> moduleKeys) {
|
||||
if (parsed == null || objectClass == null) {
|
||||
return;
|
||||
return List.of();
|
||||
}
|
||||
Set<String> fields = JsonFieldNames.of(objectClass);
|
||||
Set<String> known = union(fields, moduleKeys);
|
||||
List<UnknownPackFields.Field> unknown = new ArrayList<>();
|
||||
for (String key : parsed.keySet()) {
|
||||
if (fields.contains(key) || moduleKeys.contains(key)) {
|
||||
if (known.contains(key)) {
|
||||
continue;
|
||||
}
|
||||
reportUnknownKey(key, rawText, file, resourceTypeName, union(fields, moduleKeys));
|
||||
unknown.add(new UnknownPackFields.Field(resourceTypeName, key, packFile, findLineForKey(rawText, key), closestMatch(key, known)));
|
||||
}
|
||||
return unknown;
|
||||
}
|
||||
|
||||
private static Set<String> union(Set<String> fields, Set<String> moduleKeys) {
|
||||
@@ -65,27 +70,6 @@ public final class JsonSchemaValidator {
|
||||
IrisLogging.warn(out.toString());
|
||||
}
|
||||
|
||||
private static void reportUnknownKey(String key, String rawText, File file, String resourceTypeName, Set<String> known) {
|
||||
int line = findLineForKey(rawText, key);
|
||||
String suggestion = closestMatch(key, known);
|
||||
StringBuilder out = new StringBuilder();
|
||||
out.append("Unknown ").append(resourceTypeName).append(" field ")
|
||||
.append(C.WHITE).append('"').append(key).append('"').append(C.YELLOW)
|
||||
.append(" in ").append(C.WHITE).append(file.getPath());
|
||||
if (line > 0) {
|
||||
out.append(":").append(line);
|
||||
}
|
||||
out.append(C.YELLOW).append(" (Gson will silently ignore this)");
|
||||
if (suggestion != null) {
|
||||
out.append(". Did you mean ").append(C.WHITE).append('"').append(suggestion).append('"').append(C.YELLOW).append("?");
|
||||
}
|
||||
String snippet = buildSnippet(rawText, line);
|
||||
if (snippet != null) {
|
||||
out.append('\n').append(snippet);
|
||||
}
|
||||
IrisLogging.warn(out.toString());
|
||||
}
|
||||
|
||||
private static int findLineForKey(String rawText, String key) {
|
||||
if (rawText == null || key == null) {
|
||||
return -1;
|
||||
|
||||
@@ -431,7 +431,7 @@ public class ResourceLoader<T extends IrisRegistrant> implements MeteredCache {
|
||||
JSONObject parsed = new JSONObject(rawText);
|
||||
readAsJson = true;
|
||||
Optional<Level> moduleTarget = ModuleTargets.ofResource(objectClass);
|
||||
JsonSchemaValidator.validateTopLevelKeys(parsed, rawText, j, resourceTypeName, objectClass, moduleKeys(moduleTarget));
|
||||
getManager().reportUnknownFields(j, rawText, resourceTypeName, objectClass, moduleKeys(moduleTarget), parsed);
|
||||
T t = getManager().getGson()
|
||||
.fromJson(preprocess(parsed).toString(0), objectClass);
|
||||
moduleTarget.ifPresent(target -> t.setModuleSettings(decodeModuleSettings(target, parsed, name)));
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
package art.arcane.iris.core.loader;
|
||||
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.iris.util.common.format.C;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Gathers the fields pack files hold that nothing reads and states them as one list per pack, shortly after the
|
||||
* first one turns up, so a pack loading hundreds of files gives one warning instead of one per field. A field of a
|
||||
* file is stated once per server start: the several loads of a pack while the server starts repeat nothing.
|
||||
*/
|
||||
public final class UnknownPackFields {
|
||||
private static final long GATHER_PERIOD_MS = 3000;
|
||||
private static final int MAX_STATED_FIELDS = 65536;
|
||||
private static final Set<String> STATED = ConcurrentHashMap.newKeySet();
|
||||
private static final Map<File, PendingPack> PENDING = new LinkedHashMap<>();
|
||||
private static final ScheduledExecutorService REPORTER = Executors.newSingleThreadScheduledExecutor(task -> {
|
||||
Thread thread = new Thread(task, "Iris unknown pack fields");
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
});
|
||||
|
||||
private UnknownPackFields() {
|
||||
}
|
||||
|
||||
/** The pack a field was found in: its folder, how logs name it, and whether it loads any module. */
|
||||
public record Pack(File folder, String label, boolean loadsModules) {
|
||||
}
|
||||
|
||||
/**
|
||||
* A field of {@code resourceType} that nothing reads, in {@code file} (pack-relative) at {@code line}, or at no
|
||||
* line when the key was not found in the text; {@code suggestion} is the known field it most likely misspells.
|
||||
*/
|
||||
public record Field(String resourceType, String key, String file, int line, String suggestion) {
|
||||
String location() {
|
||||
return line > 0 ? file + ":" + line : file;
|
||||
}
|
||||
}
|
||||
|
||||
private record PendingPack(Pack pack, List<Field> fields) {
|
||||
}
|
||||
|
||||
/** Queues the fields not stated yet; the first queued field of a quiet moment schedules the report. */
|
||||
public static void add(Pack pack, List<Field> fields) {
|
||||
List<Field> unstated = fields.stream().filter(field -> claim(pack, field)).toList();
|
||||
if (unstated.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
synchronized (PENDING) {
|
||||
if (PENDING.isEmpty()) {
|
||||
REPORTER.schedule(UnknownPackFields::reportPending, GATHER_PERIOD_MS, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
PENDING.computeIfAbsent(pack.folder(), folder -> new PendingPack(pack, new ArrayList<>())).fields().addAll(unstated);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean claim(Pack pack, Field field) {
|
||||
if (STATED.size() >= MAX_STATED_FIELDS) {
|
||||
return false;
|
||||
}
|
||||
return STATED.add(pack.folder().getAbsolutePath() + "|" + field.file() + "|" + field.key());
|
||||
}
|
||||
|
||||
private static void reportPending() {
|
||||
List<PendingPack> due;
|
||||
synchronized (PENDING) {
|
||||
due = List.copyOf(PENDING.values());
|
||||
PENDING.clear();
|
||||
}
|
||||
due.forEach(pending -> IrisLogging.warn(describe(pending.pack(), pending.fields())));
|
||||
}
|
||||
|
||||
/** One header naming the pack, then a line per resource type and field with how many files hold it and where. */
|
||||
static String describe(Pack pack, List<Field> fields) {
|
||||
Map<String, List<Field>> byTypeAndKey = fields.stream()
|
||||
.sorted(Comparator.comparing(Field::resourceType).thenComparing(Field::key).thenComparing(Field::file))
|
||||
.collect(Collectors.groupingBy(field -> field.resourceType() + " " + field.key(), LinkedHashMap::new, Collectors.toList()));
|
||||
StringBuilder out = new StringBuilder()
|
||||
.append(C.YELLOW).append(pack.label()).append(" has ").append(C.WHITE).append(byTypeAndKey.size())
|
||||
.append(C.YELLOW).append(byTypeAndKey.size() == 1 ? " field" : " fields").append(" nothing reads");
|
||||
if (!pack.loadsModules()) {
|
||||
out.append(", since it loads no modules");
|
||||
}
|
||||
out.append(':');
|
||||
byTypeAndKey.values().forEach(sameField -> out.append('\n').append(describeField(sameField)));
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
private static String describeField(List<Field> sameField) {
|
||||
Field first = sameField.getFirst();
|
||||
StringBuilder line = new StringBuilder()
|
||||
.append(C.GRAY).append(" ").append(first.resourceType()).append(' ')
|
||||
.append(C.WHITE).append(first.key())
|
||||
.append(C.GRAY).append(" in ").append(first.location());
|
||||
if (sameField.size() > 1) {
|
||||
line.append(" and ").append(sameField.size() - 1).append(sameField.size() == 2 ? " other file" : " other files");
|
||||
}
|
||||
if (first.suggestion() != null) {
|
||||
line.append(C.YELLOW).append(", did you mean ").append(C.WHITE).append(first.suggestion()).append(C.YELLOW).append('?');
|
||||
}
|
||||
return line.toString();
|
||||
}
|
||||
}
|
||||
@@ -114,7 +114,7 @@ public final class ModuleResourceFiles<T> {
|
||||
if (!IrisModuleHost.isHostType(kind.type())) {
|
||||
return;
|
||||
}
|
||||
JsonSchemaValidator.validateTopLevelKeys(new JSONObject(json), json, file, typeName, kind.type(), Set.of());
|
||||
data.reportUnknownFields(file, json, typeName, kind.type(), Set.of(), new JSONObject(json));
|
||||
}
|
||||
|
||||
private void describeOrigin(T resource, String key, File file) {
|
||||
|
||||
@@ -230,6 +230,20 @@ public class ExternalDataSVC implements IrisService, CustomBlockSource {
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<CustomBlockLook> lookOf(String state) {
|
||||
BlockData data;
|
||||
try {
|
||||
data = Bukkit.createBlockData(state);
|
||||
} catch (IllegalArgumentException notAServerState) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return activeProviders.stream()
|
||||
.map(provider -> provider.lookOf(data))
|
||||
.flatMap(Optional::stream)
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Path> resourcePacks() {
|
||||
return activeProviders.stream()
|
||||
|
||||
@@ -52,9 +52,9 @@ public final class MinecraftAssets {
|
||||
}
|
||||
|
||||
/**
|
||||
* The asset file at {@code path} in the client jar, such as {@code assets/minecraft/textures/block/stone.png}, or
|
||||
* for another namespace in the resource packs of the server's plugins; empty when there is no such file or the path
|
||||
* leaves the asset folder.
|
||||
* The asset file at {@code path}, such as {@code assets/minecraft/textures/block/stone.png}, as players see it: from
|
||||
* the resource packs of the server's plugins, which replace vanilla block states with their blocks' models, and
|
||||
* otherwise from the client jar; empty when there is no such file or the path leaves the asset folder.
|
||||
*
|
||||
* @throws NotReadyException while the client jar is still being fetched, or when fetching it failed; the next call
|
||||
* after a failure tries again
|
||||
@@ -63,8 +63,9 @@ public final class MinecraftAssets {
|
||||
if (!isAssetPath(path)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
if (!path.startsWith(MINECRAFT_ASSET_FOLDER)) {
|
||||
return readFromPacks(pluginResourcePacks(), path);
|
||||
Optional<byte[]> fromPlugins = readFromPacks(pluginResourcePacks(), path);
|
||||
if (fromPlugins.isPresent() || !path.startsWith(MINECRAFT_ASSET_FOLDER)) {
|
||||
return fromPlugins;
|
||||
}
|
||||
ZipFile jar = openedJar();
|
||||
ZipEntry entry = jar.getEntry(path);
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
|
||||
package art.arcane.iris.core.studio.bridge;
|
||||
|
||||
import art.arcane.iris.core.link.CustomBlockLook;
|
||||
import com.google.gson.Gson;
|
||||
import com.volmit.block.BlockState;
|
||||
import com.volmit.tooling.BlockPattern;
|
||||
@@ -25,7 +26,10 @@ import com.volmit.tooling.BlockPattern;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* A {@link BlockPattern} as the studio reads it, little endian:
|
||||
@@ -42,9 +46,19 @@ final class PatternEncoding {
|
||||
private PatternEncoding() {
|
||||
}
|
||||
|
||||
static byte[] encode(BlockPattern pattern, int blocksPerColumn, Gson gson) {
|
||||
List<String> blocks = pattern.blocks().stream().map(BlockState::key).toList();
|
||||
byte[] header = gson.toJson(new Header(pattern.columns(), blocksPerColumn, blocks, NO_BLOCK))
|
||||
/**
|
||||
* @param pluginLooks the plugin block a server state is with the vanilla state players see in its place; empty for
|
||||
* every state that is no plugin's block
|
||||
*/
|
||||
static byte[] encode(BlockPattern pattern, int blocksPerColumn, Gson gson, Function<String, Optional<CustomBlockLook>> pluginLooks) {
|
||||
List<String> blocks = new ArrayList<>();
|
||||
List<String> drawnAs = new ArrayList<>();
|
||||
for (BlockState block : pattern.blocks()) {
|
||||
Optional<CustomBlockLook> look = pluginLooks.apply(block.key());
|
||||
blocks.add(look.map(found -> found.id().toString()).orElse(block.key()));
|
||||
drawnAs.add(look.map(CustomBlockLook::shownAs).orElse(block.key()));
|
||||
}
|
||||
byte[] header = gson.toJson(new Header(pattern.columns(), blocksPerColumn, blocks, drawnAs, NO_BLOCK))
|
||||
.getBytes(StandardCharsets.UTF_8);
|
||||
int columns = pattern.columns();
|
||||
ByteBuffer buffer = ByteBuffer.allocate(aligned(Integer.BYTES + header.length) + columns * columns * Short.BYTES)
|
||||
@@ -63,6 +77,7 @@ final class PatternEncoding {
|
||||
return (bytes + ALIGNMENT_BYTES - 1) / ALIGNMENT_BYTES * ALIGNMENT_BYTES;
|
||||
}
|
||||
|
||||
private record Header(int columns, int blocksPerColumn, List<String> blocks, int noBlock) {
|
||||
/** {@code blocks} names each block as the pack does; {@code drawnAs} is the state of each to draw it as. */
|
||||
private record Header(int columns, int blocksPerColumn, List<String> blocks, List<String> drawnAs, int noBlock) {
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,9 @@
|
||||
package art.arcane.iris.core.studio.bridge;
|
||||
|
||||
import art.arcane.iris.core.gui.GuiHost;
|
||||
import art.arcane.iris.core.link.CustomBlockLook;
|
||||
import art.arcane.iris.core.link.CustomBlockSource;
|
||||
import art.arcane.iris.spi.IrisServices;
|
||||
import art.arcane.iris.core.gui.GuiMarker;
|
||||
import art.arcane.iris.core.project.StudioEditor;
|
||||
import art.arcane.iris.core.project.StudioEditorLauncher;
|
||||
@@ -500,7 +503,13 @@ public final class StudioBridge implements AutoCloseable {
|
||||
} catch (NoSuchElementException unknown) {
|
||||
throw new RequestError(STATUS_NOT_FOUND, unknown.getMessage());
|
||||
}
|
||||
return PatternEncoding.encode(pattern.orElseThrow(() -> new RequestError(STATUS_NOT_FOUND, "No pattern " + key)), blocksPerColumn, gson);
|
||||
return PatternEncoding.encode(pattern.orElseThrow(() -> new RequestError(STATUS_NOT_FOUND, "No pattern " + key)), blocksPerColumn, gson,
|
||||
StudioBridge::pluginLookOf);
|
||||
}
|
||||
|
||||
private static Optional<CustomBlockLook> pluginLookOf(String state) {
|
||||
CustomBlockSource plugins = IrisServices.getOrNull(CustomBlockSource.class);
|
||||
return plugins == null ? Optional.empty() : plugins.lookOf(state);
|
||||
}
|
||||
|
||||
private static List<SavedWorlds.Info> savedWorlds(HttpExchange exchange) {
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package art.arcane.iris.core.loader;
|
||||
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class UnknownPackFieldsTest {
|
||||
private static final UnknownPackFields.Pack PACK_WITHOUT_MODULES = new UnknownPackFields.Pack(new File("npfixed"), "World npfixed", false);
|
||||
|
||||
@Test
|
||||
public void listsEachFieldOnceWithItsFirstFileAndHowManyOthersHoldIt() {
|
||||
List<UnknownPackFields.Field> fields = List.of(
|
||||
new UnknownPackFields.Field("Biome", "layers", "biomes/carving/swamp.json", 13, null),
|
||||
new UnknownPackFields.Field("Biome", "layers", "biomes/carving/deep.json", 13, null),
|
||||
new UnknownPackFields.Field("Biome", "layers", "biomes/2026/lakes.json", 14, null),
|
||||
new UnknownPackFields.Field("Biome", "decorators", "biomes/carving/swamp.json", 20, "generators"),
|
||||
new UnknownPackFields.Field("Dimension", "bedrock", "dimensions/natureplanet.json", 10, null));
|
||||
|
||||
String report = IrisLogging.clean(UnknownPackFields.describe(PACK_WITHOUT_MODULES, fields));
|
||||
|
||||
assertEquals("""
|
||||
World npfixed has 3 fields nothing reads, since it loads no modules:
|
||||
Biome decorators in biomes/carving/swamp.json:20, did you mean generators?
|
||||
Biome layers in biomes/2026/lakes.json:14 and 2 other files
|
||||
Dimension bedrock in dimensions/natureplanet.json:10""", report);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void namesNoModuleCauseWhenThePackLoadsModules() {
|
||||
UnknownPackFields.Pack pack = new UnknownPackFields.Pack(new File("overworld"), "Pack overworld", true);
|
||||
List<UnknownPackFields.Field> fields = List.of(new UnknownPackFields.Field("Region", "biomez", "regions/plains.json", 0, "biomes"));
|
||||
|
||||
assertEquals("""
|
||||
Pack overworld has 1 field nothing reads:
|
||||
Region biomez in regions/plains.json, did you mean biomes?""", IrisLogging.clean(UnknownPackFields.describe(pack, fields)));
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
package art.arcane.iris.core.studio.bridge;
|
||||
|
||||
import art.arcane.iris.core.link.CustomBlockLook;
|
||||
import art.arcane.iris.core.link.Identifier;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
@@ -10,6 +12,7 @@ import org.junit.Test;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
@@ -20,12 +23,13 @@ public class PatternEncodingTest {
|
||||
BlockState dirt = BlockState.parse("minecraft:dirt");
|
||||
BlockPattern pattern = BlockPattern.of(2, new BlockState[]{grass, null, dirt, grass});
|
||||
|
||||
byte[] encoded = PatternEncoding.encode(pattern, 4, new Gson());
|
||||
byte[] encoded = PatternEncoding.encode(pattern, 4, new Gson(), state -> Optional.empty());
|
||||
|
||||
ByteBuffer body = ByteBuffer.wrap(encoded).order(ByteOrder.LITTLE_ENDIAN);
|
||||
int headerLength = body.getInt();
|
||||
JsonObject header = JsonParser.parseString(new String(encoded, 4, headerLength, StandardCharsets.UTF_8)).getAsJsonObject();
|
||||
JsonObject header = headerOf(encoded);
|
||||
assertEquals("[\"minecraft:grass_block[snowy=false]\",\"minecraft:dirt\"]", header.get("blocks").toString());
|
||||
assertEquals(header.get("blocks"), header.get("drawnAs"));
|
||||
assertEquals(2, header.get("columns").getAsInt());
|
||||
assertEquals(4, header.get("blocksPerColumn").getAsInt());
|
||||
assertEquals(-1, header.get("noBlock").getAsInt());
|
||||
@@ -37,4 +41,21 @@ public class PatternEncodingTest {
|
||||
assertEquals(1, body.getShort());
|
||||
assertEquals(0, body.getShort());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void aPluginBlockIsNamedAsThePackNamesItAndDrawnAsTheStatePlayersSee() {
|
||||
BlockState serverOnly = BlockState.parse("craftengine:custom_7");
|
||||
BlockPattern pattern = BlockPattern.of(1, new BlockState[]{serverOnly});
|
||||
CustomBlockLook grass = new CustomBlockLook(new Identifier("etopia", "grass_block"), "minecraft:note_block[instrument=basedrum,note=7,powered=false]");
|
||||
|
||||
JsonObject header = headerOf(PatternEncoding.encode(pattern, 1, new Gson(), state -> Optional.of(grass)));
|
||||
|
||||
assertEquals("[\"etopia:grass_block\"]", header.get("blocks").toString());
|
||||
assertEquals("[\"minecraft:note_block[instrument=basedrum,note=7,powered=false]\"]", header.get("drawnAs").toString());
|
||||
}
|
||||
|
||||
private static JsonObject headerOf(byte[] encoded) {
|
||||
int headerLength = ByteBuffer.wrap(encoded).order(ByteOrder.LITTLE_ENDIAN).getInt();
|
||||
return JsonParser.parseString(new String(encoded, 4, headerLength, StandardCharsets.UTF_8)).getAsJsonObject();
|
||||
}
|
||||
}
|
||||
@@ -15,11 +15,18 @@ function encodedPattern(header: object, picks: number[]): ArrayBuffer {
|
||||
|
||||
describe('decodePattern', () => {
|
||||
it('reads the picks after the padded header, row by row, with no block as -1', () => {
|
||||
const header = { columns: 2, blocksPerColumn: 4, blocks: ['minecraft:grass_block[snowy=false]', 'minecraft:dirt'], noBlock: -1 }
|
||||
const header = {
|
||||
columns: 2,
|
||||
blocksPerColumn: 4,
|
||||
blocks: ['minecraft:grass_block[snowy=false]', 'etopia:grass_block'],
|
||||
drawnAs: ['minecraft:grass_block[snowy=false]', 'minecraft:note_block[note=7]'],
|
||||
noBlock: -1
|
||||
}
|
||||
const pattern = decodePattern(encodedPattern(header, [0, -1, 1, 0]))
|
||||
expect(pattern.columns).toBe(2)
|
||||
expect(pattern.blocksPerColumn).toBe(4)
|
||||
expect(pattern.blocks).toEqual(header.blocks)
|
||||
expect(pattern.drawnAs).toEqual(header.drawnAs)
|
||||
expect([...pattern.picks]).toEqual([0, NO_PATTERN_BLOCK, 1, 0])
|
||||
})
|
||||
})
|
||||
@@ -6,6 +6,7 @@ interface PatternHeader {
|
||||
columns: number
|
||||
blocksPerColumn: number
|
||||
blocks: string[]
|
||||
drawnAs: string[]
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -20,6 +21,7 @@ export function decodePattern(buffer: ArrayBuffer): PatternTile {
|
||||
columns: header.columns,
|
||||
blocksPerColumn: header.blocksPerColumn,
|
||||
blocks: header.blocks,
|
||||
drawnAs: header.drawnAs,
|
||||
picks: new Int16Array(buffer, picksAt, header.columns * header.columns)
|
||||
}
|
||||
}
|
||||
@@ -150,8 +150,10 @@ export interface PatternEntry {
|
||||
export interface PatternTile {
|
||||
columns: number
|
||||
blocksPerColumn: number
|
||||
/** The block states the picks index, as BlockState keys. */
|
||||
/** The block states the picks index, as BlockState keys; a plugin's block by the name the pack gives it. */
|
||||
blocks: string[]
|
||||
/** Per block, the state players see and the studio draws: the block itself, or the vanilla state a plugin block borrows. */
|
||||
drawnAs: string[]
|
||||
/** Each column's block, or NO_PATTERN_BLOCK where the pattern places none. */
|
||||
picks: Int16Array
|
||||
}
|
||||
|
||||
@@ -35,9 +35,9 @@ export interface PatternStatus extends TiledFrame {
|
||||
spot: PatternSpot
|
||||
}
|
||||
|
||||
/** The blocks a tile placed with their colours, and whether it left some columns without a block. */
|
||||
/** The blocks a tile placed, each with the state it is drawn as, and whether it left some columns without a block. */
|
||||
export interface PatternBlocks {
|
||||
colors: Map<string, number>
|
||||
drawnAs: Map<string, string>
|
||||
someNone: boolean
|
||||
}
|
||||
|
||||
@@ -89,7 +89,7 @@ function patternTileSource(client: BridgeClient, blockColors: BlockColors, liste
|
||||
fetch: async (address, layer, signal) => {
|
||||
const picture = await fetchPicture(client, blockColors, address, layer, signal)
|
||||
listener.onBlocks(layer, {
|
||||
colors: new Map(picture.pattern.blocks.map((block, index) => [block, picture.colors[index]])),
|
||||
drawnAs: new Map(picture.pattern.blocks.map((block, index) => [block, picture.pattern.drawnAs[index]])),
|
||||
someNone: picture.pattern.picks.includes(NO_PATTERN_BLOCK)
|
||||
})
|
||||
return picture
|
||||
@@ -109,8 +109,8 @@ async function fetchPicture(client: BridgeClient, blockColors: BlockColors, addr
|
||||
const pixelsPerColumn = Math.round(blocksPerColumn / address.blocksPerPixel)
|
||||
const columns = PATTERN_TILE_PIXELS / pixelsPerColumn
|
||||
const pattern = await client.pattern({ ...layer, tileX: address.tileX, tileZ: address.tileZ, blocksPerColumn, columns }, signal)
|
||||
const colors = await Promise.all(pattern.blocks.map((block) => blockColors.colorOf(block)))
|
||||
const textures = pixelsPerColumn > 1 ? await Promise.all(pattern.blocks.map((block) => blockColors.topTexture(block))) : []
|
||||
const colors = await Promise.all(pattern.drawnAs.map((block) => blockColors.colorOf(block)))
|
||||
const textures = pixelsPerColumn > 1 ? await Promise.all(pattern.drawnAs.map((block) => blockColors.topTexture(block))) : []
|
||||
return { pattern, colors, textures, pixelsPerColumn }
|
||||
}
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ const DEFAULT_NAMESPACE_PREFIX = 'minecraft:'
|
||||
// A layer thinner than the depth shown, or a palette with no block for the spot.
|
||||
const NONE_LABEL = 'nothing at this depth'
|
||||
|
||||
/** The blocks the shown layer's tiles placed so far by name, each with one full state for its icon, and whether some spots got none. */
|
||||
/** The blocks the shown layer's tiles placed so far by name, each with one state to draw its icon as, and whether some spots got none. */
|
||||
interface LegendBlocks {
|
||||
examples: Map<string, string>
|
||||
someNone: boolean
|
||||
@@ -153,7 +153,7 @@ function usePatternView(
|
||||
|
||||
/** The legend with the tile's blocks added, one row per block whatever its state; unchanged when it had them all. */
|
||||
function withBlocks(shown: LegendBlocks, tile: PatternBlocks): LegendBlocks {
|
||||
const added = [...tile.colors.keys()].map((block) => [shortName(block), block] as const).filter(([name]) => !shown.examples.has(name))
|
||||
const added = [...tile.drawnAs].map(([block, drawnAs]) => [shortName(block), drawnAs] as const).filter(([name]) => !shown.examples.has(name))
|
||||
const someNone = shown.someNone || tile.someNone
|
||||
if (added.length === 0 && someNone === shown.someNone) {
|
||||
return shown
|
||||
|
||||
Reference in new issue
Block a user