Archive incari-client (client, 26.3, clean)

This commit is contained in:
2026-11-28 00:54:38 -06:00
parent 7a6174687f
commit 12838e838c
2383 changed files with 280266 additions and 0 deletions
@@ -0,0 +1,162 @@
package incari.features.schematics;
import incari.framework.game.ItemView;
import incari.framework.game.PlayerView;
import incari.framework.hud.Anchor;
import incari.framework.hud.HudCanvas;
import incari.framework.hud.HudElement;
import incari.framework.hud.TextElement;
import incari.framework.hud.Tone;
import incari.framework.setting.IntSetting;
import java.util.ArrayList;
import java.util.List;
import org.jspecify.annotations.Nullable;
/**
* The material list: the items the schematic still needs, most first, each with its icon and how
* many. The count is green when the player carries enough, amber when not. The rows are made again
* when the counts change ({@link #changed}), every half second at most.
*/
final class MaterialPanel extends HudElement {
private static final int ICON = 16;
private static final int GAP = 3;
private static final int NAME_WIDTH = 110;
final IntSetting rows =
settings().integer("rows", "Rows", 3, 20, 8).describedAs("How many items it lists at most.");
private final SchematicsModule module;
private final List<Row> shown = new ArrayList<>();
private String header = "";
private boolean stale = true;
private boolean editingRows;
private int countWidth;
/** One listed item. */
private record Row(ItemView item, String id, String name, String count, int needed) {}
MaterialPanel(SchematicsModule module) {
super("materials", "Material list", Anchor.TOP_RIGHT, 4, 60);
this.module = module;
rows.onChange(this::changed);
}
/** The counts may have changed: the rows are made again when next drawn. */
void changed() {
stale = true;
}
@Override
public boolean isVisible() {
// In another dimension the counts are of the schematic's, not what's around the player.
return module.isLoaded() && module.isHere();
}
private List<Row> rows(HudCanvas canvas) {
boolean editing = canvas.editing() && !module.isLoaded();
if (stale || editing != editingRows) {
stale = false;
editingRows = editing;
build(canvas, editing);
}
return shown;
}
private void build(HudCanvas canvas, boolean editing) {
shown.clear();
countWidth = 0;
SchematicsModule.Loaded now = module.loaded();
if (now == null) {
if (editing) {
header = "Materials: 2 left";
add(canvas, "minecraft:stone_bricks", 320);
add(canvas, "minecraft:oak_planks", 64);
} else {
header = "";
}
return;
}
Materials materials = now.materials;
int left = materials.kindsNeeded();
header = left == 0 ? "Materials: none left" : "Materials: " + left + " left";
for (int rank = 0; rank < materials.kinds() && shown.size() < rows.get(); rank++) {
int item = materials.ranked(rank);
int needed = materials.needed(item);
if (needed <= 0) {
break;
}
add(canvas, materials.id(item), needed);
}
}
private void add(HudCanvas canvas, String id, int needed) {
ItemView item = module.game().item(id);
String name = item.name();
Row row = new Row(item, id, fit(canvas, name.isEmpty() ? id : name), Integer.toString(needed), needed);
shown.add(row);
countWidth = Math.max(countWidth, canvas.textWidth(row.count));
}
private static String fit(HudCanvas canvas, String text) {
if (canvas.textWidth(text) <= NAME_WIDTH) {
return text;
}
String cut = text;
while (!cut.isEmpty() && canvas.textWidth(cut + "...") > NAME_WIDTH) {
cut = cut.substring(0, cut.length() - 1);
}
return cut.strip() + "...";
}
@Override
public int width(HudCanvas canvas) {
List<Row> list = rows(canvas);
if (header.isEmpty()) {
return 0;
}
int widest = canvas.textWidth(header);
for (Row row : list) {
widest = Math.max(widest, ICON + GAP + canvas.textWidth(row.name) + GAP * 2 + countWidth);
}
return widest + TextElement.PAD_X * 2;
}
@Override
public int height(HudCanvas canvas) {
List<Row> list = rows(canvas);
if (header.isEmpty()) {
return 0;
}
return TextElement.PAD_Y * 2 + canvas.lineHeight() + list.size() * (ICON + 1);
}
@Override
public void draw(HudCanvas canvas) {
List<Row> list = rows(canvas);
if (header.isEmpty()) {
return;
}
int width = width(canvas);
canvas.fill(0, 0, width, height(canvas), Tone.BACKGROUND);
canvas.text(header, TextElement.PAD_X, TextElement.PAD_Y, Tone.ACCENT);
PlayerView player = module.game().player();
int y = TextElement.PAD_Y + canvas.lineHeight();
int textY = (ICON - canvas.lineHeight()) / 2 + 1;
for (Row row : list) {
canvas.item(row.item, TextElement.PAD_X, y, false);
canvas.text(row.name, TextElement.PAD_X + ICON + GAP, y + textY, Tone.TEXT);
int countX = width - TextElement.PAD_X - canvas.textWidth(row.count);
canvas.text(row.count, countX, y + textY, tone(player, row));
y += ICON + 1;
}
}
/** Green when the player carries enough of it, amber when not. */
private static Tone tone(@Nullable PlayerView player, Row row) {
if (player == null) {
return Tone.TEXT;
}
return player.count(row.id) >= row.needed ? Tone.POSITIVE : Tone.WARNING;
}
}
@@ -0,0 +1,177 @@
package incari.features.schematics;
import incari.features.schematics.format.BlockSpec;
import incari.features.schematics.format.Schematic;
import incari.framework.game.Blocks;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* What a schematic takes to build, as items: how many of each in all, and how many are still
* needed once the right blocks already in the world are taken off. A door is one item for its two
* blocks, a double slab two; blocks no item places (water, fire) are left out. Game thread; {@link
* #refresh} allocates nothing.
*/
final class Materials {
/** Properties that say how many items a block holds. */
private static final String[] COUNTED = {"candles", "pickles", "eggs", "layers", "flower_amount", "segment_amount"};
private final String[] items;
private final int[] totals;
private final int[] needed;
private final int[] order;
private final int[] itemOf;
private final int[] costOf;
private int itemsNeeded;
private int totalNeeded;
/**
* @param states the game's state for each palette index, as the schematic has it (unturned);
* {@link Blocks#UNKNOWN} for one the game hasn't
*/
Materials(Schematic schematic, int[] states, Blocks blocks) {
List<BlockSpec> palette = schematic.palette();
itemOf = new int[palette.size()];
costOf = new int[palette.size()];
Map<String, Integer> byId = new HashMap<>();
List<String> ids = new ArrayList<>();
List<Integer> sums = new ArrayList<>();
for (int i = 0; i < itemOf.length; i++) {
itemOf[i] = -1;
BlockSpec spec = palette.get(i);
int state = states[i];
if (spec.isNothing() || spec.isAir() || state == Blocks.UNKNOWN) {
continue;
}
String id = blocks.itemId(state);
int cost = cost(spec);
if (id.isEmpty() || cost == 0) {
continue;
}
Integer item = byId.get(id);
if (item == null) {
item = ids.size();
ids.add(id);
sums.add(0);
byId.put(id, item);
}
itemOf[i] = item;
costOf[i] = cost;
sums.set(item, sums.get(item) + schematic.count(i) * cost);
}
items = ids.toArray(new String[0]);
totals = new int[items.length];
for (int i = 0; i < totals.length; i++) {
totals[i] = sums.get(i);
}
needed = totals.clone();
order = new int[items.length];
sort();
}
/**
* How many items one block in state {@code spec} takes: none for the second half of a door, bed
* or tall plant, two for a double slab, as many as it holds of candles, pickles, eggs, snow
* layers and petals.
*/
static int cost(BlockSpec spec) {
if (spec.property("half", "").equals("upper")
|| spec.property("part", "").equals("head")) {
return 0;
}
if (spec.name().endsWith("_slab") && spec.property("type", "").equals("double")) {
return 2;
}
for (String key : COUNTED) {
String value = spec.properties().get(key);
if (value != null) {
try {
return Math.max(1, Integer.parseInt(value));
} catch (NumberFormatException e) {
return 1;
}
}
}
return 1;
}
/** Takes what's already built off the totals, and sorts by what's needed most. */
void refresh(Verifier verifier) {
System.arraycopy(totals, 0, needed, 0, totals.length);
for (int i = 0; i < itemOf.length; i++) {
int item = itemOf[i];
if (item >= 0) {
needed[item] -= verifier.rightOf(i) * costOf[i];
}
}
sort();
}
/** {@link #order} by most needed first, then by id; and the counts of what's left. */
private void sort() {
int kinds = 0;
int sum = 0;
for (int i = 0; i < order.length; i++) {
order[i] = i;
if (needed[i] > 0) {
kinds++;
sum += needed[i];
}
}
// Insertion sort: a few hundred items at most, and no boxing.
for (int i = 1; i < order.length; i++) {
int item = order[i];
int j = i - 1;
while (j >= 0 && before(item, order[j])) {
order[j + 1] = order[j];
j--;
}
order[j + 1] = item;
}
itemsNeeded = kinds;
totalNeeded = sum;
}
private boolean before(int a, int b) {
if (needed[a] != needed[b]) {
return needed[a] > needed[b];
}
return items[a].compareTo(items[b]) < 0;
}
/** How many kinds of item there are. */
int kinds() {
return items.length;
}
/** The {@code rank}th item, most needed first: its index for the getters. */
int ranked(int rank) {
return order[rank];
}
String id(int item) {
return items[item];
}
int total(int item) {
return totals[item];
}
/** What's still needed of it: never below 0. */
int needed(int item) {
return Math.max(0, needed[item]);
}
/** How many kinds still need placing. */
int kindsNeeded() {
return itemsNeeded;
}
/** How many items still need placing, all kinds together. */
int totalNeeded() {
return totalNeeded;
}
}
@@ -0,0 +1,212 @@
package incari.features.schematics;
import incari.features.schematics.format.Schematic;
import incari.framework.game.Mirror;
import org.jspecify.annotations.Nullable;
/**
* Where a schematic stands in the world: its box's lowest corner, and how it's mirrored and then
* turned. Turning and mirroring keep that corner where it is, so the box only changes shape: the
* player sees it turn in place rather than swing about a point. Turns are clockwise seen from above,
* as the game's own rotations: what faced north faces east after one.
*/
final class Placement {
final Schematic schematic;
/** The dimension it stands in, by the game's id; null if placed outside a world (any). */
private @Nullable String dimension;
private int x;
private int y;
private int z;
private Mirror mirror = Mirror.NONE;
private int turns;
Placement(Schematic schematic, int x, int y, int z) {
this(schematic, null, x, y, z);
}
Placement(Schematic schematic, @Nullable String dimension, int x, int y, int z) {
this.schematic = schematic;
this.dimension = dimension;
moveTo(x, y, z);
}
/** The dimension it stands in, or null for any. */
@Nullable
String dimension() {
return dimension;
}
/** Moves it to {@code dimension} (the player's, as it's placed where they stand). */
void moveTo(String dimension) {
this.dimension = dimension;
}
/**
* Whether it's in {@code dimension}, the player's: drawn and checked only there, as the same
* coordinates in another dimension are another place.
*/
boolean isIn(@Nullable String dimension) {
return this.dimension == null || this.dimension.equals(dimension);
}
/** Puts the box's lowest corner at {@code x, y, z}. */
void moveTo(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
/** Moves it by this many blocks. */
void moveBy(int dx, int dy, int dz) {
moveTo(x + dx, y + dy, z + dz);
}
/** Turns it {@code quarterTurns} more clockwise (negative: anticlockwise). */
void turn(int quarterTurns) {
turns = Math.floorMod(turns + quarterTurns, 4);
}
void mirror(Mirror mirror) {
this.mirror = mirror;
}
Mirror mirror() {
return mirror;
}
/** Clockwise quarter turns, 0 to 3. */
int turns() {
return turns;
}
int minX() {
return x;
}
int minY() {
return y;
}
int minZ() {
return z;
}
/** The placed box's size along x: the schematic's z after an odd number of turns. */
int sizeX() {
return (turns & 1) == 0 ? schematic.sizeX() : schematic.sizeZ();
}
int sizeY() {
return schematic.sizeY();
}
int sizeZ() {
return (turns & 1) == 0 ? schematic.sizeZ() : schematic.sizeX();
}
/** One past the box's last block: x. */
int maxX() {
return x + sizeX();
}
int maxY() {
return y + sizeY();
}
int maxZ() {
return z + sizeZ();
}
/** Whether the world block {@code wx, wy, wz} is in the box. */
boolean contains(int wx, int wy, int wz) {
return wx >= x && wy >= y && wz >= z && wx < maxX() && wy < maxY() && wz < maxZ();
}
/**
* The schematic's palette index for the world block {@code wx, wy, wz}: 0 (nothing wanted)
* outside the box. Hot path: arithmetic only.
*/
int indexAt(int wx, int wy, int wz) {
int px = wx - x;
int py = wy - y;
int pz = wz - z;
int sx = schematic.sizeX();
int sz = schematic.sizeZ();
if (py < 0 || py >= schematic.sizeY() || px < 0 || pz < 0) {
return 0;
}
// Undo the turn, then the mirror: placed box -> mirrored schematic -> schematic.
int mx;
int mz;
switch (turns) {
case 1 -> {
if (px >= sz || pz >= sx) {
return 0;
}
mx = pz;
mz = sz - 1 - px;
}
case 2 -> {
if (px >= sx || pz >= sz) {
return 0;
}
mx = sx - 1 - px;
mz = sz - 1 - pz;
}
case 3 -> {
if (px >= sz || pz >= sx) {
return 0;
}
mx = sx - 1 - pz;
mz = px;
}
default -> {
if (px >= sx || pz >= sz) {
return 0;
}
mx = px;
mz = pz;
}
}
int lx = mirror == Mirror.X ? sx - 1 - mx : mx;
int lz = mirror == Mirror.Z ? sz - 1 - mz : mz;
return schematic.at(lx, py, lz);
}
/**
* Where the schematic's own block {@code lx, ly, lz} lands in the world, into {@code out} as x,
* y, z: mirrored, then turned. The inverse of {@link #indexAt}'s lookup.
*/
void toWorld(int lx, int ly, int lz, int[] out) {
int sx = schematic.sizeX();
int sz = schematic.sizeZ();
int mx = mirror == Mirror.X ? sx - 1 - lx : lx;
int mz = mirror == Mirror.Z ? sz - 1 - lz : lz;
int px;
int pz;
switch (turns) {
case 1 -> {
px = sz - 1 - mz;
pz = mx;
}
case 2 -> {
px = sx - 1 - mx;
pz = sz - 1 - mz;
}
case 3 -> {
px = mz;
pz = sx - 1 - mx;
}
default -> {
px = mx;
pz = mz;
}
}
out[0] = x + px;
out[1] = y + ly;
out[2] = z + pz;
}
}
@@ -0,0 +1,616 @@
package incari.features.schematics;
import incari.features.schematics.format.BlockSpec;
import incari.features.schematics.format.Schematic;
import incari.features.schematics.format.SchematicException;
import incari.features.schematics.format.SchematicFiles;
import incari.framework.Category;
import incari.framework.Module;
import incari.framework.event.Events;
import incari.framework.game.Blocks;
import incari.framework.game.Game;
import incari.framework.game.GameKey;
import incari.framework.game.Mirror;
import incari.framework.game.PlayerView;
import incari.framework.hud.BlockGhosts;
import incari.framework.hud.WorldCanvas;
import incari.framework.setting.ActionSetting;
import incari.framework.setting.BooleanSetting;
import incari.framework.setting.ChoiceSetting;
import incari.framework.setting.ColorSetting;
import incari.framework.setting.IntSetting;
import incari.framework.setting.Key;
import incari.framework.setting.KeySetting;
import java.util.List;
import org.jspecify.annotations.Nullable;
/**
* Schematics (ADR 0066): a structure from a file, placed in the world as see-through blocks to
* build by. It's moved, turned and mirrored where it stands; what's still missing shows as ghosts,
* the wrong blocks as boxes, and a list says what's left to place. Reads {@code .litematic}, Sponge
* {@code .schem} and the game's structure {@code .nbt}. One schematic at a time, kept until another
* is chosen or it's unloaded, whatever world the player goes to; drawn and checked only in the
* dimension it was placed in.
*/
public final class SchematicsModule extends Module {
/** Where in the game directory the files are. */
static final String FOLDER = "schematics";
static final String TITLE = "Schematics";
/** At most this many boxes a frame, nearest sections first: thousands would slow a Chromebook. */
static final int MAX_BOXES = 1024;
/** Ticks between the material list's counts. */
static final int MATERIAL_TICKS = 10;
/** What's shown as ghosts. */
enum Ghosts {
MISSING("Missing blocks"),
ALL("Every block"),
NONE("None");
private final String label;
Ghosts(String label) {
this.label = label;
}
String label() {
return label;
}
}
/** Which of the schematic's layers are drawn. */
enum Layers {
ALL("All"),
BELOW("Up to a layer"),
ONE("One layer");
private final String label;
Layers(String label) {
this.label = label;
}
String label() {
return label;
}
}
final ActionSetting choose = settings()
.action("choose", "Schematic", "Choose...", this::chooseFile)
.describedAs("Picks a schematic file to build: .litematic, .schem or .nbt.");
final ActionSetting here = settings()
.action("here", "Place", "Here", this::moveHere)
.describedAs("Moves the schematic's corner to where you stand.")
.visibleWhen(this::isLoaded);
final ActionSetting turn = settings()
.action("turn", "Turn", "90° right", () -> turn(1))
.describedAs("Turns it a quarter clockwise where it stands.")
.visibleWhen(this::isLoaded);
final ActionSetting mirror = settings()
.action("mirror", "Mirror", "Next", this::nextMirror)
.describedAs("Mirrors it east-west, then north-south, then not.")
.visibleWhen(this::isLoaded);
final ActionSetting unload = settings()
.action("unload", "Unload", "Unload", this::unloadSchematic)
.describedAs("Takes the schematic out of the world.")
.visibleWhen(this::isLoaded);
final ChoiceSetting<Ghosts> ghosts = settings()
.choice("ghosts", "Ghosts", Ghosts.values(), Ghosts.MISSING, Ghosts::label)
.describedAs("Which of the schematic's blocks show as see-through ghosts.");
final IntSetting opacity = settings()
.integer("opacity", "Ghost opacity", 10, 90, 45)
.formattedAs(value -> value + "%")
.describedAs("How solid the ghosts are.");
final IntSetting range = settings()
.integer("range", "Range", 16, 128, 48)
.formattedAs(value -> value + " blocks")
.describedAs("How far from you ghosts and boxes show; nearer is faster.");
final ChoiceSetting<Layers> layers = settings()
.choice("layers", "Layers", Layers.values(), Layers.ALL, Layers::label)
.describedAs("Shows the whole schematic, or one layer to build by.");
final BooleanSetting outline =
settings().bool("outline", "Show its box", true).describedAs("Outlines the schematic's whole box.");
final ColorSetting outlineColor = settings()
.color("outline-color", "Box color", 0x55AAFF)
.describedAs("The outline's color.")
.visibleWhen(outline::get);
final BooleanSetting highlight = settings()
.bool("highlight", "Mark wrong blocks", true)
.describedAs("Boxes blocks that differ from the schematic.");
final ColorSetting wrongColor = settings()
.color("wrong-color", "Wrong block", 0xFF3333)
.describedAs("A different block from the schematic's.")
.visibleWhen(highlight::get);
final ColorSetting stateColor = settings()
.color("state-color", "Wrong way", 0xFFAA00)
.describedAs("The right block, but facing or set another way.")
.visibleWhen(highlight::get);
final ColorSetting extraColor = settings()
.color("extra-color", "Extra block", 0xFF55FF)
.describedAs("A block where the schematic has air.")
.visibleWhen(highlight::get);
final KeySetting hereKey = settings()
.key("here-key", "Place here key", Key.NONE)
.describedAs("Moves the schematic's corner to where you stand.")
.onPress(this::moveHere);
final KeySetting turnKey = settings()
.key("turn-key", "Turn key", Key.NONE)
.describedAs("Turns it a quarter clockwise; anticlockwise while sneaking.")
.onPress(() -> turn(sneaking() ? -1 : 1));
final KeySetting mirrorKey = settings()
.key("mirror-key", "Mirror key", Key.NONE)
.describedAs("Mirrors it east-west, then north-south, then not.")
.onPress(this::nextMirror);
final KeySetting nudgeKey = settings()
.key("nudge-key", "Nudge key", Key.NONE)
.describedAs("Moves it a block the way you face; back while sneaking.")
.onPress(this::nudge);
final KeySetting raiseKey = settings()
.key("raise-key", "Up key", Key.NONE)
.describedAs("Moves it a block up; down while sneaking.")
.onPress(() -> raise(sneaking() ? -1 : 1));
final KeySetting layerKey = settings()
.key("layer-key", "Layer key", Key.NONE)
.describedAs("Shows the next layer up; down while sneaking.")
.onPress(() -> moveLayer(sneaking() ? -1 : 1));
private @Nullable Loaded loaded;
/** The layer drawn, in world y, while {@link #layers} isn't All. */
private int layer;
/** Goes up whenever what the ghosts show might have changed everywhere. */
private long ghostRevision = 1;
private final GhostView ghostView = new GhostView();
private long ticks;
/** The player's dimension at the last tick; null outside a world. */
private @Nullable String dimension;
/**
* Whether the player is in the schematic's dimension, as of the last tick: it's drawn and
* checked only there. A field, as the ghosts ask block by block.
*/
private boolean inDimension = true;
private final StatusPanel status = new StatusPanel(this);
private final MaterialPanel materials = new MaterialPanel(this);
/** A schematic loaded and placed: what's worked out from it once, and again as it moves. */
static final class Loaded {
final Schematic schematic;
final Placement placement;
/** The game's state for each palette index, as the file has it; UNKNOWN where the game has none. */
final int[] baseStates;
/** {@link #baseStates} mirrored and turned as placed. */
final int[] states;
final Materials materials;
Verifier verifier;
final int unknownKinds;
Loaded(Schematic schematic, Placement placement, Blocks blocks) {
this.schematic = schematic;
this.placement = placement;
List<BlockSpec> palette = schematic.palette();
baseStates = new int[palette.size()];
states = new int[palette.size()];
int unknown = 0;
for (int i = 0; i < baseStates.length; i++) {
BlockSpec spec = palette.get(i);
baseStates[i] = spec.isNothing()
? Blocks.UNKNOWN
: blocks.state(spec.name(), spec.properties(), schematic.dataVersion());
if (!spec.isNothing() && baseStates[i] == Blocks.UNKNOWN) {
unknown++;
}
}
unknownKinds = unknown;
materials = new Materials(schematic, baseStates, blocks);
verifier = place(blocks);
}
/** Works the states out again for how it's placed now, and starts comparing afresh. */
Verifier place(Blocks blocks) {
for (int i = 0; i < states.length; i++) {
int base = baseStates[i];
states[i] = base == Blocks.UNKNOWN || blocks.isAir(base)
? base
: blocks.transform(base, placement.mirror(), placement.turns());
}
verifier = new Verifier(placement, states, blocks);
return verifier;
}
}
/** Schematics, off until the player turns it on. */
public SchematicsModule() {
super(
"schematics",
"Schematics",
"Places a schematic in the world as ghost blocks to build by.",
Category.UTILITY);
hud(status);
hud(materials);
on(Events.TICK, this::tick);
on(Events.WORLD, this::draw);
on(Events.LEAVE, this::left);
ghosts.onChange(this::ghostsChanged);
layers.onChange(this::layersChanged);
}
/** The game, for the HUD elements. */
Game game() {
return system().game();
}
/** Whether a schematic is loaded. */
boolean isLoaded() {
return loaded != null;
}
@Nullable
Loaded loaded() {
return loaded;
}
/** Whether the player is in the schematic's dimension (as of the last tick), where it's drawn. */
boolean isHere() {
return inDimension;
}
/** The layer drawn, in world y. */
int layer() {
return layer;
}
private void chooseFile() {
system().game().chooseFile("Choose a schematic", FOLDER, SchematicFiles.EXTENSIONS, this::load);
}
/** Reads {@code bytes}, the file {@code fileName}, and places it where the player stands. */
void load(String fileName, byte[] bytes) {
Schematic schematic;
try {
schematic = SchematicFiles.read(fileName, bytes);
} catch (SchematicException e) {
system().game().showMessage(TITLE, "Couldn't load " + fileName + ": " + e.getMessage());
return;
}
PlayerView player = system().game().player();
int x = player == null ? 0 : floor(player.x());
int y = player == null ? 64 : floor(player.y());
int z = player == null ? 0 : floor(player.z());
String in = player == null ? null : player.dimension();
Loaded now = new Loaded(
schematic,
new Placement(schematic, in, x, y, z),
system().game().blocks());
loaded = now;
inDimension = true;
layer = y;
ghostRevision++;
String size = schematic.sizeX() + " x " + schematic.sizeY() + " x " + schematic.sizeZ();
String message = schematic.name() + ", " + size + ", placed where you stand.";
if (now.unknownKinds > 0) {
message += " " + now.unknownKinds + (now.unknownKinds == 1 ? " block isn't" : " blocks aren't")
+ " in this version: left out.";
}
system().game().showMessage(TITLE, message);
status.changed();
materials.changed();
}
private void unloadSchematic() {
loaded = null;
ghostRevision++;
status.changed();
materials.changed();
}
private boolean sneaking() {
return system().game().isDown(GameKey.SNEAK);
}
private void moveHere() {
Loaded now = loaded;
PlayerView player = system().game().player();
if (now == null || player == null) {
return;
}
now.placement.moveTo(player.dimension());
now.placement.moveTo(floor(player.x()), floor(player.y()), floor(player.z()));
inDimension = true;
placed(now);
}
/** Moves it a block the way the player faces, or back while they sneak. */
private void nudge() {
Loaded now = loaded;
PlayerView player = system().game().player();
if (now == null || player == null) {
return;
}
// The heading's nearest of north, east, south, west.
int facing = Math.floorMod(Math.round(player.heading() / 90.0F), 4);
int step = sneaking() ? -1 : 1;
int dx = facing == 1 ? step : facing == 3 ? -step : 0;
int dz = facing == 2 ? step : facing == 0 ? -step : 0;
now.placement.moveBy(dx, 0, dz);
placed(now);
}
private void raise(int blocks) {
Loaded now = loaded;
if (now == null) {
return;
}
now.placement.moveBy(0, blocks, 0);
layer += blocks;
placed(now);
}
void turn(int quarterTurns) {
Loaded now = loaded;
if (now == null) {
return;
}
now.placement.turn(quarterTurns);
placed(now);
}
void nextMirror() {
Loaded now = loaded;
if (now == null) {
return;
}
now.placement.mirror(
switch (now.placement.mirror()) {
case NONE -> Mirror.X;
case X -> Mirror.Z;
case Z -> Mirror.NONE;
});
placed(now);
}
private void moveLayer(int by) {
Loaded now = loaded;
if (now == null) {
return;
}
if (layers.get() == Layers.ALL) {
layers.set(Layers.ONE);
}
layer = Math.max(now.placement.minY(), Math.min(now.placement.maxY() - 1, layer + by));
ghostRevision++;
status.changed();
}
/** It moved, turned or mirrored: everything's worked out again. */
private void placed(Loaded now) {
now.place(system().game().blocks());
layer = Math.max(now.placement.minY(), Math.min(now.placement.maxY() - 1, layer));
ghostRevision++;
status.changed();
materials.changed();
}
private void ghostsChanged() {
ghostRevision++;
}
private void layersChanged() {
Loaded now = loaded;
PlayerView player = system().game().player();
if (now != null && layers.get() != Layers.ALL && player != null) {
// Start at the player's feet: the layer they're likely building.
layer = Math.max(now.placement.minY(), Math.min(now.placement.maxY() - 1, floor(player.y())));
}
ghostRevision++;
status.changed();
}
/** Whether world layer {@code y} is drawn. */
boolean shows(int y) {
return switch (layers.get()) {
case ALL -> true;
case BELOW -> y <= layer;
case ONE -> y == layer;
};
}
/** The world changed under it: what was found is forgotten, and looked for again. */
private void left() {
Loaded now = loaded;
if (now != null) {
now.place(system().game().blocks());
ghostRevision++;
materials.changed();
}
}
private void tick() {
Loaded now = loaded;
PlayerView player = system().game().player();
String in = player == null ? null : player.dimension();
if (in != null && !in.equals(dimension)) {
// Through a portal: the ghosts are made again, for none here or the schematic's there.
ghostRevision++;
status.changed();
materials.changed();
}
dimension = in;
inDimension = now == null || now.placement.isIn(in);
if (now == null || player == null || !inDimension) {
return;
}
now.verifier.tick(floor(player.x()), floor(player.y()), floor(player.z()), range.get());
if (++ticks % MATERIAL_TICKS == 0) {
now.materials.refresh(now.verifier);
status.changed();
materials.changed();
}
}
private void draw(WorldCanvas canvas) {
Loaded now = loaded;
if (now == null || !inDimension) {
return;
}
Placement placement = now.placement;
if (ghosts.get() != Ghosts.NONE) {
canvas.ghosts(ghostView, Math.round(opacity.get() * 255 / 100.0F), range.get());
}
if (outline.get()) {
canvas.box(
placement.minX(),
placement.minY(),
placement.minZ(),
placement.maxX(),
placement.maxY(),
placement.maxZ(),
0xFF000000 | outlineColor.get(),
0);
}
if (highlight.get()) {
drawProblems(canvas, now.verifier);
}
}
/** The wrong and extra blocks near the camera, as boxes. */
private void drawProblems(WorldCanvas canvas, Verifier verifier) {
int cx = floor(canvas.cameraX());
int cy = floor(canvas.cameraY());
int cz = floor(canvas.cameraZ());
int reach = range.get();
int boxes = 0;
// Ring by ring outward, so the cap leaves out the farthest.
int rings = (reach >> 4) + 1;
for (int ring = 0; ring <= rings && boxes < MAX_BOXES; ring++) {
for (int sy = (cy >> 4) - ring; sy <= (cy >> 4) + ring && boxes < MAX_BOXES; sy++) {
for (int sz = (cz >> 4) - ring; sz <= (cz >> 4) + ring && boxes < MAX_BOXES; sz++) {
for (int sx = (cx >> 4) - ring; sx <= (cx >> 4) + ring && boxes < MAX_BOXES; sx++) {
int edge = Math.max(
Math.abs(sx - (cx >> 4)), Math.max(Math.abs(sy - (cy >> 4)), Math.abs(sz - (cz >> 4))));
if (edge != ring) {
continue;
}
Verifier.Section section = verifier.section(sx, sy, sz);
if (section != null && section.issueCount > 0) {
boxes = drawSection(canvas, section, cx, cy, cz, reach, boxes);
}
}
}
}
}
}
private int drawSection(
WorldCanvas canvas, Verifier.Section section, int cx, int cy, int cz, int reach, int boxes) {
long reachSquared = (long) reach * reach;
int count = boxes;
for (int i = 0; i < section.issueCount && count < MAX_BOXES; i++) {
int issue = section.issue(i);
int at = issue >>> 3;
int x = (section.sectionX << 4) | (at & 15);
int y = (section.sectionY << 4) | (at >> 8);
int z = (section.sectionZ << 4) | ((at >> 4) & 15);
long dx = (long) x - cx;
long dy = (long) y - cy;
long dz = (long) z - cz;
if (!shows(y) || dx * dx + dy * dy + dz * dz > reachSquared) {
continue;
}
int rgb =
switch (issue & 7) {
case Verifier.WRONG_BLOCK -> wrongColor.get();
case Verifier.WRONG_STATE -> stateColor.get();
default -> extraColor.get();
};
canvas.box(x, y, z, x + 1, y + 1, z + 1, 0xFF000000 | rgb, 0x40000000 | rgb);
count++;
}
return count;
}
static int floor(double value) {
return (int) Math.floor(value);
}
/** What the client meshes as ghosts: the placed schematic's blocks still to build, or all of them. */
private final class GhostView implements BlockGhosts {
@Override
public int minX() {
Loaded now = loaded;
return now == null ? 0 : now.placement.minX();
}
@Override
public int minY() {
Loaded now = loaded;
return now == null ? 0 : now.placement.minY();
}
@Override
public int minZ() {
Loaded now = loaded;
return now == null ? 0 : now.placement.minZ();
}
@Override
public int maxX() {
Loaded now = loaded;
return now == null ? 0 : now.placement.maxX();
}
@Override
public int maxY() {
Loaded now = loaded;
return now == null ? 0 : now.placement.maxY();
}
@Override
public int maxZ() {
Loaded now = loaded;
return now == null ? 0 : now.placement.maxZ();
}
@Override
public int ghostAt(int x, int y, int z) {
Loaded now = loaded;
if (now == null || !inDimension || !shows(y)) {
return Blocks.AIR;
}
int index = now.placement.indexAt(x, y, z);
if (index == 0) {
return Blocks.AIR;
}
int want = now.states[index];
Blocks blocks = system().game().blocks();
if (want == Blocks.UNKNOWN || blocks.isAir(want)) {
return Blocks.AIR;
}
if (ghosts.get() == Ghosts.ALL) {
return want;
}
int have = blocks.at(x, y, z);
return have != Blocks.UNKNOWN && blocks.isAir(have) ? want : Blocks.AIR;
}
@Override
public long revision(int sectionX, int sectionY, int sectionZ) {
Loaded now = loaded;
Verifier.Section section = now == null ? null : now.verifier.section(sectionX, sectionY, sectionZ);
return ghostRevision << 32 | (section == null ? 0 : section.revision & 0xFFFFFFFFL);
}
}
}
@@ -0,0 +1,162 @@
package incari.features.schematics;
import incari.framework.game.Mirror;
import incari.framework.game.PlayerView;
import incari.framework.hud.Anchor;
import incari.framework.hud.HudCanvas;
import incari.framework.hud.HudElement;
import incari.framework.hud.TextElement;
import incari.framework.hud.Tone;
import java.util.ArrayList;
import java.util.List;
import org.jspecify.annotations.Nullable;
/**
* The loaded schematic, how far it's built and how it's placed, in a few lines. The lines are made
* again only when something they say changed ({@link #changed}), not each frame.
*/
final class StatusPanel extends HudElement {
/** The widest a line may be before it's cut short. */
static final int MAX_WIDTH = 170;
private final SchematicsModule module;
private final List<String> lines = new ArrayList<>();
private final List<Tone> tones = new ArrayList<>();
private boolean stale = true;
private boolean editingLines;
StatusPanel(SchematicsModule module) {
super("status", "Schematic", Anchor.TOP_LEFT, 4, 60);
this.module = module;
}
/** What it says may have changed: its lines are made again when next drawn. */
void changed() {
stale = true;
}
@Override
public boolean isVisible() {
return module.isLoaded();
}
private List<String> lines(HudCanvas canvas) {
boolean editing = canvas.editing() && !module.isLoaded();
if (stale || editing != editingLines) {
stale = false;
editingLines = editing;
build(canvas, editing);
}
return lines;
}
private void build(HudCanvas canvas, boolean editing) {
lines.clear();
tones.clear();
SchematicsModule.Loaded now = module.loaded();
if (now == null) {
if (editing) {
add("Castle", Tone.ACCENT);
add("1200 of 4000 placed", Tone.TEXT);
add("3 wrong", Tone.WARNING);
}
return;
}
add(fit(canvas, now.schematic.name()), Tone.ACCENT);
Verifier verifier = now.verifier;
int total = now.schematic.blockCount();
add(Math.min(verifier.right(), total) + " of " + total + " placed", Tone.TEXT);
int wrong = verifier.wrongBlocks() + verifier.wrongStates();
if (wrong > 0 || verifier.extra() > 0) {
StringBuilder problems = new StringBuilder();
if (wrong > 0) {
problems.append(wrong).append(" wrong");
}
if (verifier.extra() > 0) {
if (wrong > 0) {
problems.append(", ");
}
problems.append(verifier.extra()).append(" extra");
}
add(problems.toString(), Tone.WARNING);
} else if (verifier.lookedAtAll() && verifier.right() >= total) {
add("Finished", Tone.POSITIVE);
}
Placement placement = now.placement;
String placed = placement.minX() + " " + placement.minY() + " " + placement.minZ();
if (placement.turns() != 0) {
placed += ", turned " + placement.turns() * 90 + "°";
}
if (placement.mirror() != Mirror.NONE) {
placed += ", mirrored";
}
add(placed, Tone.MUTED);
if (!module.isHere()) {
add(where(placement.dimension()), Tone.WARNING);
}
if (module.layers.get() != SchematicsModule.Layers.ALL) {
add(
(module.layers.get() == SchematicsModule.Layers.ONE ? "Layer " : "Up to layer ") + module.layer(),
Tone.MUTED);
}
}
/** Where it's placed, for a player in another dimension: "In the Overworld". */
static String where(@Nullable String dimension) {
if (PlayerView.OVERWORLD.equals(dimension)) {
return "In the Overworld";
}
if (PlayerView.NETHER.equals(dimension)) {
return "In the Nether";
}
if (PlayerView.END.equals(dimension)) {
return "In the End";
}
return "In another dimension";
}
private void add(String line, Tone tone) {
lines.add(line);
tones.add(tone);
}
/** {@code text} cut short with an ellipsis to fit {@link #MAX_WIDTH}. */
static String fit(HudCanvas canvas, String text) {
if (canvas.textWidth(text) <= MAX_WIDTH) {
return text;
}
String cut = text;
while (!cut.isEmpty() && canvas.textWidth(cut + "...") > MAX_WIDTH) {
cut = cut.substring(0, cut.length() - 1);
}
return cut.strip() + "...";
}
@Override
public int width(HudCanvas canvas) {
int width = 0;
for (String line : lines(canvas)) {
width = Math.max(width, canvas.textWidth(line));
}
return width == 0 ? 0 : width + TextElement.PAD_X * 2;
}
@Override
public int height(HudCanvas canvas) {
int count = lines(canvas).size();
return count == 0 ? 0 : count * canvas.lineHeight() + TextElement.PAD_Y * 2 - 1;
}
@Override
public void draw(HudCanvas canvas) {
List<String> text = lines(canvas);
if (text.isEmpty()) {
return;
}
canvas.fill(0, 0, width(canvas), height(canvas), Tone.BACKGROUND);
for (int i = 0; i < text.size(); i++) {
canvas.text(text.get(i), TextElement.PAD_X, TextElement.PAD_Y + i * canvas.lineHeight(), tones.get(i));
}
}
}
@@ -0,0 +1,399 @@
package incari.features.schematics;
import incari.framework.game.Blocks;
import java.util.Arrays;
import org.jspecify.annotations.Nullable;
/**
* Compares a placed schematic with the world, a 16-block section at a time, a few sections a tick:
* which blocks are right, missing, the wrong block, the right block in the wrong state, or there
* when the schematic wants air. Sections near the player are looked at again every few ticks, so
* what they build shows at once; the rest in turn, for the counts and the material list. A section
* whose chunk the client hasn't loaded counts as nothing yet.
*
* <p>Game thread. {@link #tick} is a hot path: it allocates only when a section first needs room
* for its problems.
*/
final class Verifier {
/** A problem's kind, as {@link Section#issue} packs it. */
static final int MISSING = 1;
static final int WRONG_BLOCK = 2;
static final int WRONG_STATE = 3;
static final int EXTRA = 4;
/** Blocks looked at in a tick, at most (a section past it is finished). */
static final int BUDGET = 8192;
/** How far round the player, in blocks, is "where they're building": looked at every few ticks. */
static final int REACH = 6;
/** Ticks between looks at a section where the player is building. */
static final int NEAR_TICKS = 4;
/** Ticks between looks at a section near enough that its problems are drawn. */
static final int SHOWN_TICKS = 40;
private final Placement placement;
private final int[] states;
private final Blocks blocks;
private final int minSectionX;
private final int minSectionY;
private final int minSectionZ;
private final int countX;
private final int countY;
private final int countZ;
private final Section[] sections;
/** Right blocks so far by palette index, over every section looked at. */
private final int[] rightByIndex;
/** Scratch for a scan: right blocks by palette index, and which indices it touched. */
private final int[] scratch;
private final int[] touched = new int[4096];
private int right;
private int missing;
private int wrongBlocks;
private int wrongStates;
private int extra;
private int looked;
private long ticks;
private int cursor;
/** One 16-block section of the world, as far as the schematic's box reaches into it. */
static final class Section {
final int sectionX;
final int sectionY;
final int sectionZ;
/** The tick it was last looked at; -1 before the first. */
long lookedAt = -1;
boolean loaded;
/** Goes up whenever its missing blocks or problems change. */
long revision;
private int hash;
int right;
int missing;
int wrongBlocks;
int wrongStates;
int extra;
/** Problems other than missing blocks, while it's near enough to draw them: see {@link #issue}. */
int @Nullable [] issues;
int issueCount;
/** Right blocks by palette index: the indices, and how many of each. */
int[] indices = new int[0];
int[] counts = new int[0];
int used;
Section(int sectionX, int sectionY, int sectionZ) {
this.sectionX = sectionX;
this.sectionY = sectionY;
this.sectionZ = sectionZ;
}
/** Problem {@code i}: its kind in the low three bits, then its block in the section as {@code y << 8 | z << 4 | x}. */
int issue(int i) {
int[] list = issues;
return list == null ? 0 : list[i];
}
}
/**
* @param states the game's state for each palette index, mirrored and turned as placed;
* {@link Blocks#UNKNOWN} for one to leave alone
*/
Verifier(Placement placement, int[] states, Blocks blocks) {
this.placement = placement;
this.states = states;
this.blocks = blocks;
minSectionX = placement.minX() >> 4;
minSectionY = placement.minY() >> 4;
minSectionZ = placement.minZ() >> 4;
countX = ((placement.maxX() - 1) >> 4) - minSectionX + 1;
countY = ((placement.maxY() - 1) >> 4) - minSectionY + 1;
countZ = ((placement.maxZ() - 1) >> 4) - minSectionZ + 1;
sections = new Section[countX * countY * countZ];
for (int sy = 0; sy < countY; sy++) {
for (int sz = 0; sz < countZ; sz++) {
for (int sx = 0; sx < countX; sx++) {
sections[(sy * countZ + sz) * countX + sx] =
new Section(minSectionX + sx, minSectionY + sy, minSectionZ + sz);
}
}
}
rightByIndex = new int[states.length];
scratch = new int[states.length];
}
/** The section at section coordinates {@code sx, sy, sz}, or null if the box doesn't reach it. */
@Nullable
Section section(int sx, int sy, int sz) {
int ix = sx - minSectionX;
int iy = sy - minSectionY;
int iz = sz - minSectionZ;
if (ix < 0 || iy < 0 || iz < 0 || ix >= countX || iy >= countY || iz >= countZ) {
return null;
}
return sections[(iy * countZ + iz) * countX + ix];
}
/**
* A tick's looking, round the player at {@code x, y, z}: where they build first, then what's
* within {@code shownRange} blocks (whose problems are drawn), then the rest in turn.
*/
void tick(int x, int y, int z, int shownRange) {
ticks++;
// Where they're building, but never more than half the tick.
int budget = BUDGET - lookAround(x, y, z, REACH, NEAR_TICKS, BUDGET / 2, shownRange);
// One section in turn every tick, whatever else is due, so far ones are still counted.
budget -= inTurn(x, y, z, shownRange, 1);
if (budget > 0) {
budget -= lookAround(x, y, z, shownRange, SHOWN_TICKS, budget, shownRange);
}
if (budget > 0) {
inTurn(x, y, z, shownRange, budget);
}
}
/** Looks at sections in turn not looked at lately, until {@code budget} blocks are looked at. */
private int inTurn(int x, int y, int z, int shownRange, int budget) {
int spent = 0;
for (int tries = 0; spent < budget && tries < sections.length; tries++) {
Section section = sections[cursor];
cursor = (cursor + 1) % sections.length;
if (section.lookedAt < 0 || ticks - section.lookedAt > SHOWN_TICKS * 5) {
spent += look(section, near(section, x, y, z, shownRange));
}
}
return spent;
}
/** Looks at the sections within {@code range} of the player not looked at for {@code every} ticks. */
private int lookAround(int x, int y, int z, int range, int every, int budget, int shownRange) {
int spent = 0;
int sx0 = Math.max(minSectionX, (x - range) >> 4);
int sy0 = Math.max(minSectionY, (y - range) >> 4);
int sz0 = Math.max(minSectionZ, (z - range) >> 4);
int sx1 = Math.min(minSectionX + countX - 1, (x + range) >> 4);
int sy1 = Math.min(minSectionY + countY - 1, (y + range) >> 4);
int sz1 = Math.min(minSectionZ + countZ - 1, (z + range) >> 4);
for (int sy = sy0; sy <= sy1 && spent < budget; sy++) {
for (int sz = sz0; sz <= sz1 && spent < budget; sz++) {
for (int sx = sx0; sx <= sx1 && spent < budget; sx++) {
Section section =
sections[((sy - minSectionY) * countZ + (sz - minSectionZ)) * countX + (sx - minSectionX)];
boolean shown = near(section, x, y, z, shownRange);
boolean stale = section.lookedAt < 0 || ticks - section.lookedAt >= every;
// A section come into view needs its problems listed now, not at its next turn.
if (stale || (shown && section.loaded && section.issues == null && hasProblems(section))) {
spent += look(section, shown);
}
}
}
}
return spent;
}
private static boolean hasProblems(Section section) {
return section.wrongBlocks + section.wrongStates + section.extra > 0;
}
/** Whether the section is within {@code range} blocks of {@code x, y, z}, its problems kept to draw. */
private static boolean near(Section section, int x, int y, int z, int range) {
int dx = Math.max(0, Math.max((section.sectionX << 4) - x, x - (section.sectionX << 4) - 15));
int dy = Math.max(0, Math.max((section.sectionY << 4) - y, y - (section.sectionY << 4) - 15));
int dz = Math.max(0, Math.max((section.sectionZ << 4) - z, z - (section.sectionZ << 4) - 15));
return (long) dx * dx + (long) dy * dy + (long) dz * dz <= (long) range * range;
}
/**
* Compares one section with the world and updates the counts.
*
* @param keepIssues whether to list its problems, to draw them
* @return how many blocks it looked at
*/
private int look(Section section, boolean keepIssues) {
forget(section);
section.lookedAt = ticks;
int x0 = Math.max(section.sectionX << 4, placement.minX());
int y0 = Math.max(section.sectionY << 4, placement.minY());
int z0 = Math.max(section.sectionZ << 4, placement.minZ());
int x1 = Math.min((section.sectionX << 4) + 16, placement.maxX());
int y1 = Math.min((section.sectionY << 4) + 16, placement.maxY());
int z1 = Math.min((section.sectionZ << 4) + 16, placement.maxZ());
int[] issues = keepIssues ? section.issues : null;
if (!keepIssues) {
section.issues = null;
}
int issueCount = 0;
int used = 0;
int hash = 1;
boolean loaded = true;
int visited = 0;
scan:
for (int y = y0; y < y1; y++) {
for (int z = z0; z < z1; z++) {
for (int x = x0; x < x1; x++) {
visited++;
int index = placement.indexAt(x, y, z);
if (index == 0) {
continue;
}
int want = states[index];
if (want == Blocks.UNKNOWN) {
continue;
}
int have = blocks.at(x, y, z);
if (have == Blocks.UNKNOWN) {
loaded = false;
break scan;
}
int kind;
if (have == want) {
kind = 0;
} else if (blocks.isAir(want)) {
kind = blocks.isAir(have) ? 0 : EXTRA;
} else if (blocks.isAir(have)) {
kind = MISSING;
} else {
kind = blocks.block(have) == blocks.block(want) ? WRONG_STATE : WRONG_BLOCK;
}
if (kind == 0) {
if (!blocks.isAir(want)) {
section.right++;
if (scratch[index]++ == 0) {
touched[used++] = index;
}
}
continue;
}
int issue = ((y & 15) << 8 | (z & 15) << 4 | (x & 15)) << 3 | kind;
hash = hash * 31 + issue;
switch (kind) {
case MISSING -> section.missing++;
case WRONG_BLOCK -> section.wrongBlocks++;
case WRONG_STATE -> section.wrongStates++;
default -> section.extra++;
}
if (keepIssues && kind != MISSING) {
if (issues == null) {
issues = new int[64];
} else if (issueCount == issues.length) {
issues = Arrays.copyOf(issues, Math.min(4096, issues.length * 2));
}
issues[issueCount++] = issue;
}
}
}
}
if (!loaded) {
for (int i = 0; i < used; i++) {
scratch[touched[i]] = 0;
}
section.right = section.missing = section.wrongBlocks = section.wrongStates = section.extra = 0;
used = 0;
issueCount = 0;
hash = 0;
}
section.loaded = loaded;
if (keepIssues) {
section.issues = issues;
}
section.issueCount = issueCount;
if (section.indices.length < used) {
section.indices = new int[Math.max(used, section.indices.length * 2)];
section.counts = new int[section.indices.length];
}
for (int i = 0; i < used; i++) {
int index = touched[i];
section.indices[i] = index;
section.counts[i] = scratch[index];
scratch[index] = 0;
}
section.used = used;
if (hash != section.hash) {
section.hash = hash;
section.revision++;
}
remember(section);
return Math.max(1, visited);
}
/** Takes the section's counts out of the totals, before it's looked at again. */
private void forget(Section section) {
if (section.lookedAt < 0) {
return;
}
right -= section.right;
missing -= section.missing;
wrongBlocks -= section.wrongBlocks;
wrongStates -= section.wrongStates;
extra -= section.extra;
looked--;
for (int i = 0; i < section.used; i++) {
rightByIndex[section.indices[i]] -= section.counts[i];
}
section.right = section.missing = section.wrongBlocks = section.wrongStates = section.extra = 0;
}
private void remember(Section section) {
right += section.right;
missing += section.missing;
wrongBlocks += section.wrongBlocks;
wrongStates += section.wrongStates;
extra += section.extra;
looked++;
for (int i = 0; i < section.used; i++) {
rightByIndex[section.indices[i]] += section.counts[i];
}
}
/** Blocks found right, air left out. */
int right() {
return right;
}
int missing() {
return missing;
}
int wrongBlocks() {
return wrongBlocks;
}
int wrongStates() {
return wrongStates;
}
int extra() {
return extra;
}
/** Right blocks of palette index {@code index}, over the sections looked at. */
int rightOf(int index) {
return rightByIndex[index];
}
/** How many sections there are. */
int sectionCount() {
return sections.length;
}
/** Whether every section has been looked at once. */
boolean lookedAtAll() {
return looked == sections.length;
}
}
@@ -0,0 +1,99 @@
package incari.features.schematics.format;
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;
/**
* A block state as a file names it: {@code minecraft:oak_stairs} and its properties ({@code
* facing=north}), not yet looked up in the game. Properties are kept sorted, so the same state
* is equal however a file ordered them.
*
* @param name the block's id, with its namespace
* @param properties its properties, sorted by name; empty for the block's defaults
*/
public record BlockSpec(String name, Map<String, String> properties) {
/** No block wanted: a structure's void, outside a schematic's regions. Never looked up. */
public static final BlockSpec NOTHING = new BlockSpec("", Map.of());
/** Air. */
public static final BlockSpec AIR = new BlockSpec("minecraft:air", Map.of());
public BlockSpec {
properties = properties.isEmpty() ? Map.of() : Collections.unmodifiableMap(new TreeMap<>(properties));
}
/** {@code name} with the {@code minecraft:} namespace if it has none. */
public static BlockSpec of(String name, Map<String, String> properties) {
String id = name.strip();
if (!id.isEmpty() && id.indexOf(':') < 0) {
id = "minecraft:" + id;
}
return new BlockSpec(id, properties);
}
/**
* Parses the game's text for a state, {@code minecraft:oak_stairs[facing=north,half=bottom]}, as
* Sponge schematics keep their palette. Anything after the closing bracket is ignored.
*/
public static BlockSpec parse(String text) {
int open = text.indexOf('[');
if (open < 0) {
return of(text, Map.of());
}
int close = text.indexOf(']', open);
String inner = text.substring(open + 1, close < 0 ? text.length() : close);
Map<String, String> properties = new TreeMap<>();
int start = 0;
while (start <= inner.length()) {
int comma = inner.indexOf(',', start);
String pair = inner.substring(start, comma < 0 ? inner.length() : comma);
int equals = pair.indexOf('=');
if (equals > 0) {
properties.put(
pair.substring(0, equals).strip(),
pair.substring(equals + 1).strip());
}
if (comma < 0) {
break;
}
start = comma + 1;
}
return of(text.substring(0, open), properties);
}
/** Whether it's air of any kind. */
public boolean isAir() {
return name.equals("minecraft:air") || name.equals("minecraft:cave_air") || name.equals("minecraft:void_air");
}
/** Whether it stands for no block wanted ({@link #NOTHING}). */
public boolean isNothing() {
return name.isEmpty();
}
/** One property's value, or {@code fallback} if it has none. */
public String property(String key, String fallback) {
String value = properties.get(key);
return value == null ? fallback : value;
}
/** The game's text for it. */
@Override
public String toString() {
if (properties.isEmpty()) {
return name;
}
StringBuilder text = new StringBuilder(name).append('[');
boolean first = true;
for (Map.Entry<String, String> property : properties.entrySet()) {
if (!first) {
text.append(',');
}
first = false;
text.append(property.getKey()).append('=').append(property.getValue());
}
return text.append(']').toString();
}
}
@@ -0,0 +1,151 @@
package incari.features.schematics.format;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.jspecify.annotations.Nullable;
/**
* Reads a {@code .litematic} (ADR 0066): gzipped NBT with one or more regions, each its own box
* with its own palette, merged here into one box around them all. A region's size may be negative
* on an axis: it then runs the other way from its position. Its blocks are palette indices packed
* tightly into longs ({@link PackedArray}), {@code max(2, ceil(log2(paletteSize)))} bits each, in
* the order {@code (y * sizeZ + z) * sizeX + x}. Where the regions don't reach, nothing is wanted.
*/
final class LitematicReader {
private LitematicReader() {}
/** Whether {@code root} looks like one. */
static boolean accepts(Nbt.Compound root) {
return root.compound("Regions") != null;
}
private record Region(int minX, int minY, int minZ, int sizeX, int sizeY, int sizeZ, Nbt.Compound tag) {}
static Schematic read(Nbt.Compound root, String fallbackName) throws SchematicException {
Nbt.Compound regions = root.compound("Regions");
if (regions == null) {
throw new SchematicException("Not a litematic: no regions");
}
List<Region> boxes = new ArrayList<>();
long minX = Long.MAX_VALUE, minY = Long.MAX_VALUE, minZ = Long.MAX_VALUE;
long maxX = Long.MIN_VALUE, maxY = Long.MIN_VALUE, maxZ = Long.MIN_VALUE;
for (String name : regions.names()) {
Nbt.Compound region = regions.compound(name);
if (region == null) {
continue;
}
int[] position = xyz(region.compound("Position"));
int[] size = xyz(region.compound("Size"));
if (position == null || size == null) {
throw new SchematicException("Region " + name + " has no position or size");
}
if (size[0] == 0 || size[1] == 0 || size[2] == 0) {
continue;
}
Region box = new Region(
low(position[0], size[0]),
low(position[1], size[1]),
low(position[2], size[2]),
Math.abs(size[0]),
Math.abs(size[1]),
Math.abs(size[2]),
region);
if ((long) box.sizeX * box.sizeY * box.sizeZ > Schematic.MAX_VOLUME) {
throw new SchematicException("Region " + name + " is too big to load");
}
boxes.add(box);
minX = Math.min(minX, box.minX);
minY = Math.min(minY, box.minY);
minZ = Math.min(minZ, box.minZ);
maxX = Math.max(maxX, (long) box.minX + box.sizeX);
maxY = Math.max(maxY, (long) box.minY + box.sizeY);
maxZ = Math.max(maxZ, (long) box.minZ + box.sizeZ);
}
if (boxes.isEmpty()) {
throw new SchematicException("It has no blocks");
}
if (maxX - minX > Integer.MAX_VALUE || maxY - minY > Integer.MAX_VALUE || maxZ - minZ > Integer.MAX_VALUE) {
throw new SchematicException("Too big to load");
}
Schematic.Builder builder =
new Schematic.Builder((int) (maxX - minX), (int) (maxY - minY), (int) (maxZ - minZ));
Nbt.Compound metadata = root.compound("Metadata");
String name = metadata == null ? "" : metadata.string("Name", "").strip();
builder.describe(
name.isEmpty() ? fallbackName : name,
metadata == null ? "" : metadata.string("Author", ""),
"Litematic",
root.integer("MinecraftDataVersion", 0));
for (Region box : boxes) {
region(builder, box, (int) (box.minX - minX), (int) (box.minY - minY), (int) (box.minZ - minZ));
}
return builder.build();
}
/** The lower end of a region's span on one axis: its position, or past it if its size is negative. */
private static int low(int position, int size) {
return size < 0 ? position + size + 1 : position;
}
private static void region(Schematic.Builder builder, Region box, int offsetX, int offsetY, int offsetZ)
throws SchematicException {
List<Object> entries = box.tag.list("BlockStatePalette");
if (entries.isEmpty()) {
throw new SchematicException("A region has no palette");
}
int[] indices = new int[entries.size()];
for (int i = 0; i < indices.length; i++) {
indices[i] = entries.get(i) instanceof Nbt.Compound entry ? builder.index(spec(entry)) : 0;
}
long[] states = box.tag.longs("BlockStates");
int volume = box.sizeX * box.sizeY * box.sizeZ;
int bits = PackedArray.bitsFor(indices.length, 2);
if (states == null || states.length < PackedArray.longsFor(bits, volume)) {
throw new SchematicException("A region's blocks are cut short");
}
PackedArray packed = new PackedArray(bits, volume, states);
int i = 0;
for (int y = 0; y < box.sizeY; y++) {
for (int z = 0; z < box.sizeZ; z++) {
for (int x = 0; x < box.sizeX; x++) {
int index = packed.get(i++);
if (index >= indices.length) {
throw new SchematicException("A region's blocks are past its palette");
}
builder.set(offsetX + x, offsetY + y, offsetZ + z, indices[index]);
}
}
}
}
/** A palette entry: {@code Name} and {@code Properties}, or the newer {@code id} and {@code properties}. */
static BlockSpec spec(Nbt.Compound entry) {
String name = entry.string("Name", entry.string("id", "minecraft:air"));
Nbt.Compound properties = entry.compound("Properties");
if (properties == null) {
properties = entry.compound("properties");
}
return BlockSpec.of(name, properties == null ? Map.of() : strings(properties));
}
private static Map<String, String> strings(Nbt.Compound properties) {
Map<String, String> out = new TreeMap<>();
for (String key : properties.names()) {
Object value = properties.get(key);
if (value != null) {
out.put(key, value.toString());
}
}
return out;
}
private static int @Nullable [] xyz(Nbt.@Nullable Compound tag) {
if (tag == null || !tag.has("x") || !tag.has("y") || !tag.has("z")) {
return null;
}
return new int[] {tag.integer("x", 0), tag.integer("y", 0), tag.integer("z", 0)};
}
}
@@ -0,0 +1,299 @@
package incari.features.schematics.format;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream;
import org.jspecify.annotations.Nullable;
/**
* Reads the game's binary NBT, gzipped or not, into plain Java values: a {@link Compound}, a
* {@code List<Object>}, {@code byte[]}, {@code int[]}, {@code long[]}, {@code String}, and the boxed
* numbers. Every schematic format is NBT. A file is untrusted: sizes are checked against what's left
* before anything is made, so a bad file fails with an {@link IOException} instead of running the
* tab out of memory.
*/
public final class Nbt {
/** The most a file may unpack to: a 4 GB Chromebook has to hold it and the game. */
static final int MAX_BYTES = 192 << 20;
private static final int MAX_DEPTH = 512;
private final byte[] data;
private final int end;
private int at;
private Nbt(byte[] data, int end) {
this.data = data;
this.end = end;
}
/** A named compound: its fields in file order. */
public static final class Compound {
private final Map<String, Object> fields = new LinkedHashMap<>();
/** The field's value, or null if there's none. */
public @Nullable Object get(String name) {
return fields.get(name);
}
/** Whether there's a field by this name. */
public boolean has(String name) {
return fields.containsKey(name);
}
/** The field names, in file order. */
public Iterable<String> names() {
return fields.keySet();
}
/** The field's compound, or null if it's missing or isn't one. */
public @Nullable Compound compound(String name) {
return fields.get(name) instanceof Compound c ? c : null;
}
/** The field's list, or an empty one. */
public List<Object> list(String name) {
return fields.get(name) instanceof List<?> l ? cast(l) : List.of();
}
@SuppressWarnings("unchecked")
private static List<Object> cast(List<?> list) {
return (List<Object>) list;
}
/** The field's text, or {@code fallback} if it isn't text. */
public String string(String name, String fallback) {
return fields.get(name) instanceof String s ? s : fallback;
}
/** The field as a whole number of any width, or {@code fallback} if it isn't one. */
public long number(String name, long fallback) {
Object value = fields.get(name);
if (value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof Long) {
return ((Number) value).longValue();
}
return fallback;
}
/** {@link #number} as an int. */
public int integer(String name, int fallback) {
return (int) number(name, fallback);
}
/** The field's int array (or a list of ints, as structures keep positions), or null. */
public int @Nullable [] ints(String name) {
Object value = fields.get(name);
if (value instanceof int[] ints) {
return ints;
}
if (value instanceof List<?> list) {
int[] out = new int[list.size()];
for (int i = 0; i < out.length; i++) {
if (!(list.get(i) instanceof Integer n)) {
return null;
}
out[i] = n;
}
return out;
}
return null;
}
/** The field's long array, or null. */
public long @Nullable [] longs(String name) {
return fields.get(name) instanceof long[] longs ? longs : null;
}
/** The field's byte array, or null. */
public byte @Nullable [] bytes(String name) {
return fields.get(name) instanceof byte[] bytes ? bytes : null;
}
void put(String name, Object value) {
fields.put(name, value);
}
}
/**
* The root compound of a file's bytes, unpacking them first if they're gzipped.
*
* @throws IOException if they aren't NBT, or unpack to more than a schematic should
*/
public static Compound read(byte[] file) throws IOException {
byte[] data = file;
int length = file.length;
if (file.length >= 2 && (file[0] & 0xFF) == 0x1F && (file[1] & 0xFF) == 0x8B) {
Unpacked unpacked = gunzip(file);
data = unpacked.bytes;
length = unpacked.length;
}
Nbt reader = new Nbt(data, length);
int type = reader.u8();
if (type != 10) {
throw new IOException("Not NBT: the root isn't a compound");
}
reader.utf();
return reader.compound(0);
}
/** Unpacked bytes: the array, and how much of it is used. */
private static final class Unpacked {
final byte[] bytes;
final int length;
Unpacked(byte[] bytes, int length) {
this.bytes = bytes;
this.length = length;
}
}
private static Unpacked gunzip(byte[] file) throws IOException {
try (InputStream in = new GZIPInputStream(new ByteArrayInputStream(file), 64 * 1024)) {
byte[] out = new byte[Math.max(1024, Math.min(MAX_BYTES, file.length * 4))];
int length = 0;
while (true) {
if (length == out.length) {
if (out.length >= MAX_BYTES) {
throw new IOException("Too big: over " + (MAX_BYTES >> 20) + " MB unpacked");
}
out = Arrays.copyOf(out, (int) Math.min(MAX_BYTES, out.length * 2L));
}
int read = in.read(out, length, out.length - length);
if (read < 0) {
return new Unpacked(out, length);
}
length += read;
}
}
}
private Object value(int type, int depth) throws IOException {
return switch (type) {
case 1 -> (byte) u8();
case 2 -> (short) u16();
case 3 -> s32();
case 4 -> s64();
case 5 -> Float.intBitsToFloat(s32());
case 6 -> Double.longBitsToDouble(s64());
case 7 -> {
int n = count(1);
byte[] bytes = Arrays.copyOfRange(data, at, at + n);
at += n;
yield bytes;
}
case 8 -> utf();
case 9 -> list(depth);
case 10 -> compound(depth);
case 11 -> {
int n = count(4);
int[] ints = new int[n];
for (int i = 0; i < n; i++) {
ints[i] = s32();
}
yield ints;
}
case 12 -> {
int n = count(8);
long[] longs = new long[n];
for (int i = 0; i < n; i++) {
longs[i] = s64();
}
yield longs;
}
default -> throw new IOException("Bad NBT: tag type " + type);
};
}
private Compound compound(int depth) throws IOException {
if (depth > MAX_DEPTH) {
throw new IOException("Bad NBT: nested too deep");
}
Compound compound = new Compound();
while (true) {
int type = u8();
if (type == 0) {
return compound;
}
String name = utf();
compound.put(name, value(type, depth + 1));
}
}
private List<Object> list(int depth) throws IOException {
if (depth > MAX_DEPTH) {
throw new IOException("Bad NBT: nested too deep");
}
int type = u8();
// The smallest any element can be: an empty compound is one byte, an empty list five.
int n = count(type == 0 ? 0 : 1);
if (type == 0 && n > 0) {
throw new IOException("Bad NBT: a list of nothing");
}
List<Object> list = new ArrayList<>(Math.min(n, 1 << 16));
for (int i = 0; i < n; i++) {
list.add(value(type, depth + 1));
}
return list;
}
/** A length prefix for {@code size}-byte elements, checked against what's left. */
private int count(int size) throws IOException {
int n = s32();
if (n < 0 || (long) n * size > end - at) {
throw new IOException("Bad NBT: " + n + " elements past the end");
}
return n;
}
private void need(int bytes) throws IOException {
if (end - at < bytes) {
throw new IOException("Bad NBT: ends early");
}
}
private int u8() throws IOException {
need(1);
return data[at++] & 0xFF;
}
private int u16() throws IOException {
need(2);
int value = (data[at] & 0xFF) << 8 | (data[at + 1] & 0xFF);
at += 2;
return value;
}
private int s32() throws IOException {
need(4);
int value = (data[at] & 0xFF) << 24
| (data[at + 1] & 0xFF) << 16
| (data[at + 2] & 0xFF) << 8
| (data[at + 3] & 0xFF);
at += 4;
return value;
}
private long s64() throws IOException {
long high = s32() & 0xFFFFFFFFL;
return high << 32 | (s32() & 0xFFFFFFFFL);
}
/** Java's modified UTF-8, as the game writes names and text; read as UTF-8, which it is for real text. */
private String utf() throws IOException {
int n = u16();
need(n);
String text = new String(data, at, n, StandardCharsets.UTF_8);
at += n;
return text;
}
}
@@ -0,0 +1,94 @@
package incari.features.schematics.format;
/**
* Small non-negative numbers packed tightly into longs, {@code bits} each, low bits first; an entry
* may run on into the next long. This is how a {@code .litematic} keeps a region's blocks, so its
* array is read as it is, and every format's blocks are kept this way: a few bits a block, not an
* int.
*/
public final class PackedArray {
private final int bits;
private final long mask;
private final int length;
private final long[] data;
/** {@code length} zeros of {@code bits} bits each (1 to 32). */
public PackedArray(int bits, int length) {
this(bits, length, new long[longsFor(bits, length)]);
}
/**
* Over {@code data} as it is.
*
* @throws IllegalArgumentException if {@code data} is too short for {@code length} entries
*/
public PackedArray(int bits, int length, long[] data) {
if (bits < 1 || bits > 32 || length < 0) {
throw new IllegalArgumentException("Bad packing: " + bits + " bits, " + length + " entries");
}
if (data.length < longsFor(bits, length)) {
throw new IllegalArgumentException(
"Too few longs: " + data.length + " for " + length + " entries of " + bits + " bits");
}
this.bits = bits;
this.mask = (1L << bits) - 1;
this.length = length;
this.data = data;
}
/** How many longs {@code length} entries of {@code bits} take. */
public static int longsFor(int bits, int length) {
return (int) (((long) bits * length + 63) / 64);
}
/** The fewest bits that hold {@code 0} to {@code count - 1}; at least {@code min}. */
public static int bitsFor(int count, int min) {
int bits = 32 - Integer.numberOfLeadingZeros(Math.max(0, count - 1));
return Math.max(min, Math.max(1, bits));
}
/** How many entries. */
public int length() {
return length;
}
/** Bits per entry. */
public int bits() {
return bits;
}
/** Entry {@code index}. Hot path: no allocation, no bounds check past the array's own. */
public int get(int index) {
long bit = (long) index * bits;
int word = (int) (bit >>> 6);
int offset = (int) (bit & 63);
long value = data[word] >>> offset;
if (offset + bits > 64) {
value |= data[word + 1] << (64 - offset);
}
return (int) (value & mask);
}
/** Sets entry {@code index} to {@code value}, which must fit in {@link #bits}. */
public void set(int index, int value) {
long bit = (long) index * bits;
int word = (int) (bit >>> 6);
int offset = (int) (bit & 63);
long v = value & mask;
data[word] = (data[word] & ~(mask << offset)) | (v << offset);
if (offset + bits > 64) {
int spill = 64 - offset;
data[word + 1] = (data[word + 1] & ~(mask >>> spill)) | (v >>> spill);
}
}
/** A copy with {@code newBits} bits an entry, for values that outgrew these. */
public PackedArray widened(int newBits) {
PackedArray wider = new PackedArray(newBits, length);
for (int i = 0; i < length; i++) {
wider.set(i, get(i));
}
return wider;
}
}
@@ -0,0 +1,185 @@
package incari.features.schematics.format;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A structure to build, whatever file it came from: a box of blocks, each an index into the palette
* of block states. Index 0 is always {@link BlockSpec#NOTHING}, no block wanted (outside a
* {@code .litematic}'s regions, a structure's void); air in the palette is air wanted. Positions are
* from the box's lowest corner, {@code 0} to {@code size - 1}. Read once, never changed.
*/
public final class Schematic {
/**
* The most blocks a box may hold, so a schematic fits a Chromebook's memory with the game: a few
* bits each, a few tens of MB at most.
*/
public static final long MAX_VOLUME = 1L << 25;
private final String name;
private final String author;
private final String format;
private final int dataVersion;
private final int sizeX;
private final int sizeY;
private final int sizeZ;
private final List<BlockSpec> palette;
private final PackedArray blocks;
private final int[] counts;
private Schematic(Builder builder) {
this.name = builder.name;
this.author = builder.author;
this.format = builder.format;
this.dataVersion = builder.dataVersion;
this.sizeX = builder.sizeX;
this.sizeY = builder.sizeY;
this.sizeZ = builder.sizeZ;
this.palette = Collections.unmodifiableList(new ArrayList<>(builder.palette));
this.blocks = builder.blocks;
this.counts = new int[palette.size()];
for (int i = 0; i < blocks.length(); i++) {
counts[blocks.get(i)]++;
}
}
/** Its name, as the file gives it or the file's name. */
public String name() {
return name;
}
/** Who made it; empty if the file doesn't say. */
public String author() {
return author;
}
/** Which kind of file it came from ("Litematic", "Sponge", "Structure"). */
public String format() {
return format;
}
/** The game data version its blocks were saved at; states older than the game's are upgraded. */
public int dataVersion() {
return dataVersion;
}
/** Its size along x. */
public int sizeX() {
return sizeX;
}
/** Its size along y. */
public int sizeY() {
return sizeY;
}
/** Its size along z. */
public int sizeZ() {
return sizeZ;
}
/** The block states it uses; index 0 is {@link BlockSpec#NOTHING}. */
public List<BlockSpec> palette() {
return palette;
}
/** The palette index at {@code x, y, z}, which must be in the box. Hot path. */
public int at(int x, int y, int z) {
return blocks.get((y * sizeZ + z) * sizeX + x);
}
/** How many blocks have palette index {@code index}. */
public int count(int index) {
return counts[index];
}
/** How many blocks it wants, air left out. */
public int blockCount() {
int total = 0;
for (int i = 1; i < counts.length; i++) {
if (!palette.get(i).isAir()) {
total += counts[i];
}
}
return total;
}
/** Builds a schematic block by block; any block not set is {@link BlockSpec#NOTHING}. */
public static final class Builder {
private final int sizeX;
private final int sizeY;
private final int sizeZ;
private final List<BlockSpec> palette = new ArrayList<>();
private final Map<BlockSpec, Integer> indices = new HashMap<>();
private PackedArray blocks;
private String name = "";
private String author = "";
private String format = "";
private int dataVersion;
/**
* A box of this size.
*
* @throws SchematicException if it's empty or bigger than {@link #MAX_VOLUME}
*/
public Builder(int sizeX, int sizeY, int sizeZ) throws SchematicException {
if (sizeX <= 0 || sizeY <= 0 || sizeZ <= 0) {
throw new SchematicException("It's empty: " + sizeX + " x " + sizeY + " x " + sizeZ);
}
long volume = (long) sizeX * sizeY * sizeZ;
if (volume > MAX_VOLUME) {
throw new SchematicException("Too big to load: " + sizeX + " x " + sizeY + " x " + sizeZ);
}
this.sizeX = sizeX;
this.sizeY = sizeY;
this.sizeZ = sizeZ;
palette.add(BlockSpec.NOTHING);
indices.put(BlockSpec.NOTHING, 0);
blocks = new PackedArray(2, (int) volume);
}
/** Its name, author, format and data version. */
public Builder describe(String name, String author, String format, int dataVersion) {
this.name = name;
this.author = author;
this.format = format;
this.dataVersion = dataVersion;
return this;
}
/** {@code spec}'s palette index, added if it's new. */
public int index(BlockSpec spec) {
Integer index = indices.get(spec);
if (index == null) {
index = palette.size();
palette.add(spec);
indices.put(spec, index);
int needed = PackedArray.bitsFor(palette.size(), 2);
if (needed > blocks.bits()) {
blocks = blocks.widened(needed);
}
}
return index;
}
/** Sets {@code x, y, z}, in the box, to palette index {@code index}. */
public void set(int x, int y, int z, int index) {
blocks.set((y * sizeZ + z) * sizeX + x, index);
}
/** Whether {@code x, y, z} is in the box. */
public boolean contains(int x, int y, int z) {
return x >= 0 && y >= 0 && z >= 0 && x < sizeX && y < sizeY && z < sizeZ;
}
/** The schematic. */
public Schematic build() {
return new Schematic(this);
}
}
}
@@ -0,0 +1,15 @@
package incari.features.schematics.format;
/** A schematic file that can't be read; the message says why in the player's words. */
public final class SchematicException extends Exception {
private static final long serialVersionUID = 1L;
public SchematicException(String message) {
super(message);
}
public SchematicException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,57 @@
package incari.features.schematics.format;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
/** Reads any schematic file the client knows, telling the formats apart by what's in them. */
public final class SchematicFiles {
/** The files the chooser lists. */
public static final List<String> EXTENSIONS = List.of(".litematic", ".schem", ".nbt");
private SchematicFiles() {}
/**
* The schematic in {@code bytes}, a file called {@code fileName}.
*
* @throws SchematicException if it isn't one, or is broken or too big; the message says which
*/
public static Schematic read(String fileName, byte[] bytes) throws SchematicException {
Nbt.Compound root;
try {
root = Nbt.read(bytes);
} catch (IOException | RuntimeException e) {
throw new SchematicException("Not a schematic, or a broken one", e);
}
String name = baseName(fileName);
if (LitematicReader.accepts(root)) {
return LitematicReader.read(root, name);
}
Nbt.Compound sponge = SpongeReader.body(root);
if (sponge != null) {
return SpongeReader.read(sponge, name);
}
if (StructureReader.accepts(root)) {
return StructureReader.read(root, name);
}
if (root.has("Materials") || root.has("Blocks")) {
throw new SchematicException("Old schematics from before 1.13 aren't supported");
}
throw new SchematicException("Not a schematic this client knows");
}
/** {@code castle.litematic} without its extension. */
static String baseName(String fileName) {
String name = fileName;
int slash = Math.max(name.lastIndexOf('/'), name.lastIndexOf('\\'));
if (slash >= 0) {
name = name.substring(slash + 1);
}
int dot = name.lastIndexOf('.');
if (dot > 0 && EXTENSIONS.contains(name.substring(dot).toLowerCase(Locale.ROOT))) {
name = name.substring(0, dot);
}
return name;
}
}
@@ -0,0 +1,100 @@
package incari.features.schematics.format;
import org.jspecify.annotations.Nullable;
/**
* Reads a Sponge schematic ({@code .schem}, WorldEdit's and Axiom's), versions 1 to 3: a palette of
* the game's state text ({@code minecraft:oak_stairs[facing=north]}) to numbers, and the blocks as
* those numbers in variable-length bytes, in the order {@code (y * length + z) * width + x}. Version
* 3 moves both into a {@code Blocks} compound and the whole under a {@code Schematic} one.
*/
final class SpongeReader {
/** What version 1 files were written at, as they don't say: 1.13.2. */
private static final int VERSION_1_DATA = 1631;
private SpongeReader() {}
/** The compound holding the schematic: the root, or version 3's {@code Schematic} in it; null if neither. */
static Nbt.@Nullable Compound body(Nbt.Compound root) {
Nbt.Compound inner = root.compound("Schematic");
if (inner != null && inner.has("Width")) {
return inner;
}
return root.has("Width") && root.has("Palette") ? root : null;
}
static Schematic read(Nbt.Compound body, String fallbackName) throws SchematicException {
int width = unsigned(body.integer("Width", 0));
int height = unsigned(body.integer("Height", 0));
int length = unsigned(body.integer("Length", 0));
Nbt.Compound blocks = body.compound("Blocks");
Nbt.Compound palette = blocks != null ? blocks.compound("Palette") : body.compound("Palette");
byte[] data = blocks != null ? blocks.bytes("Data") : body.bytes("BlockData");
if (palette == null || data == null) {
throw new SchematicException("It has no palette or blocks");
}
Schematic.Builder builder = new Schematic.Builder(width, height, length);
Nbt.Compound metadata = body.compound("Metadata");
String name = metadata == null ? "" : metadata.string("Name", "").strip();
int version = body.integer("Version", 1);
if (version < 1 || version > 3) {
throw new SchematicException("Sponge version " + version + " isn't known");
}
builder.describe(
name.isEmpty() ? fallbackName : name,
metadata == null ? "" : metadata.string("Author", ""),
"Sponge",
body.integer("DataVersion", VERSION_1_DATA));
int highest = -1;
for (String key : palette.names()) {
highest = Math.max(highest, palette.integer(key, -1));
}
if (highest < 0 || highest > 1 << 20) {
throw new SchematicException("Its palette is empty or broken");
}
int[] indices = new int[highest + 1];
for (String key : palette.names()) {
int number = palette.integer(key, -1);
if (number >= 0) {
indices[number] = builder.index(BlockSpec.parse(key));
}
}
int at = 0;
for (int y = 0; y < height; y++) {
for (int z = 0; z < length; z++) {
for (int x = 0; x < width; x++) {
// A variable-length number: seven bits a byte, low first, the top bit for "more".
int value = 0;
int shift = 0;
while (true) {
if (at >= data.length) {
throw new SchematicException("Its blocks are cut short");
}
int b = data[at++];
value |= (b & 0x7F) << shift;
if ((b & 0x80) == 0) {
break;
}
shift += 7;
if (shift > 28) {
throw new SchematicException("Its blocks are broken");
}
}
if (value > highest) {
throw new SchematicException("Its blocks are past its palette");
}
builder.set(x, y, z, indices[value]);
}
}
}
return builder.build();
}
/** Sizes are unsigned shorts: a 40000-long schematic reads as negative. */
private static int unsigned(int size) {
return size < 0 ? size & 0xFFFF : size;
}
}
@@ -0,0 +1,58 @@
package incari.features.schematics.format;
import java.util.List;
/**
* Reads the game's own structure files ({@code .nbt}, a structure block's): a size, a palette (or
* several, of which the first is used, as the game does for shipwrecks) and a list of the blocks
* there are, each with its position and palette number. A position not listed is the structure's
* void: nothing wanted there.
*/
final class StructureReader {
private StructureReader() {}
/** Whether {@code root} looks like one. */
static boolean accepts(Nbt.Compound root) {
return root.has("size") && root.has("blocks");
}
static Schematic read(Nbt.Compound root, String name) throws SchematicException {
int[] size = root.ints("size");
if (size == null || size.length != 3) {
throw new SchematicException("It has no size");
}
List<Object> palette = root.list("palette");
if (palette.isEmpty() && !root.list("palettes").isEmpty()) {
palette = root.list("palettes").get(0) instanceof List<?> first ? copy(first) : List.of();
}
if (palette.isEmpty()) {
throw new SchematicException("It has no palette");
}
Schematic.Builder builder = new Schematic.Builder(size[0], size[1], size[2]);
builder.describe(name, root.string("author", ""), "Structure", root.integer("DataVersion", 0));
int[] indices = new int[palette.size()];
for (int i = 0; i < indices.length; i++) {
indices[i] = palette.get(i) instanceof Nbt.Compound entry ? builder.index(LitematicReader.spec(entry)) : 0;
}
for (Object element : root.list("blocks")) {
if (!(element instanceof Nbt.Compound block)) {
continue;
}
int[] pos = block.ints("pos");
int state = block.integer("state", -1);
if (pos == null || pos.length != 3 || state < 0 || state >= indices.length) {
throw new SchematicException("A block is broken");
}
if (!builder.contains(pos[0], pos[1], pos[2])) {
throw new SchematicException("A block is outside its size");
}
builder.set(pos[0], pos[1], pos[2], indices[state]);
}
return builder.build();
}
private static List<Object> copy(List<?> list) {
return List.copyOf(list);
}
}
@@ -0,0 +1,9 @@
/**
* Schematic files, read clean-room from their formats (ADR 0066): NBT, then {@code .litematic},
* Sponge {@code .schem} and the game's structure {@code .nbt}, into one {@link
* incari.features.schematics.format.Schematic}. No game types: block states stay as their names.
*/
@NullMarked
package incari.features.schematics.format;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,5 @@
/** Schematics: a structure from a file, placed as ghost blocks to build by (ADR 0066). */
@NullMarked
package incari.features.schematics;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,29 @@
package incari.features.schematics;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes;
import com.tngtech.archunit.core.importer.ImportOption;
import com.tngtech.archunit.junit.AnalyzeClasses;
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.lang.ArchRule;
/**
* A feature sees the module framework and the JDK's basics: no game, platform or other feature. The
* file readers add the JDK's byte streams and gzip.
*/
@AnalyzeClasses(packages = "incari.features.schematics", importOptions = ImportOption.DoNotIncludeTests.class)
class BoundaryTest {
@ArchTest
static final ArchRule onlyTheFramework = classes()
.should()
.onlyDependOnClassesThat()
.resideInAnyPackage(
"java.lang..",
"java.util..",
"java.io",
"java.nio.charset",
"org.jspecify..",
"incari.framework..",
"incari.features.schematics..");
}
@@ -0,0 +1,27 @@
package incari.features.schematics;
import static org.assertj.core.api.Assertions.assertThat;
import incari.features.schematics.format.BlockSpec;
import java.util.Map;
import org.junit.jupiter.api.Test;
class MaterialsTest {
@Test
void blocksCostWhatPlacingThemTakes() {
assertThat(Materials.cost(BlockSpec.of("minecraft:stone", Map.of()))).isEqualTo(1);
assertThat(Materials.cost(BlockSpec.of("minecraft:oak_door", Map.of("half", "upper"))))
.isZero();
assertThat(Materials.cost(BlockSpec.of("minecraft:oak_door", Map.of("half", "lower"))))
.isEqualTo(1);
assertThat(Materials.cost(BlockSpec.of("minecraft:red_bed", Map.of("part", "head"))))
.isZero();
assertThat(Materials.cost(BlockSpec.of("minecraft:oak_slab", Map.of("type", "double"))))
.isEqualTo(2);
assertThat(Materials.cost(BlockSpec.of("minecraft:candle", Map.of("candles", "3"))))
.isEqualTo(3);
assertThat(Materials.cost(BlockSpec.of("minecraft:snow", Map.of("layers", "5"))))
.isEqualTo(5);
}
}
@@ -0,0 +1,99 @@
package incari.features.schematics;
import static org.assertj.core.api.Assertions.assertThat;
import incari.features.schematics.format.BlockSpec;
import incari.features.schematics.format.Schematic;
import incari.features.schematics.format.SchematicException;
import incari.framework.game.Mirror;
import incari.framework.testing.FakeBlocks;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.Test;
class PlacementTest {
/** A 4 x 2 x 3 box with a different block in every place. */
private static Schematic numbered() throws SchematicException {
Schematic.Builder builder = new Schematic.Builder(4, 2, 3);
for (int y = 0; y < 2; y++) {
for (int z = 0; z < 3; z++) {
for (int x = 0; x < 4; x++) {
builder.set(x, y, z, builder.index(BlockSpec.of("test:b" + x + y + z, Map.of())));
}
}
}
return builder.build();
}
@Test
void everyTurnAndMirrorMapsEachBlockToOnePlaceInTheBox() throws SchematicException {
Schematic schematic = numbered();
int[] out = new int[3];
for (Mirror mirror : Mirror.values()) {
for (int turns = 0; turns < 4; turns++) {
Placement placement = new Placement(schematic, 100, 64, -50);
placement.mirror(mirror);
placement.turn(turns);
assertThat(placement.sizeX()).isEqualTo(turns % 2 == 0 ? 4 : 3);
assertThat(placement.sizeZ()).isEqualTo(turns % 2 == 0 ? 3 : 4);
Set<String> places = new HashSet<>();
for (int y = 0; y < 2; y++) {
for (int z = 0; z < 3; z++) {
for (int x = 0; x < 4; x++) {
placement.toWorld(x, y, z, out);
assertThat(placement.contains(out[0], out[1], out[2]))
.isTrue();
assertThat(places.add(out[0] + "," + out[1] + "," + out[2]))
.isTrue();
assertThat(placement.indexAt(out[0], out[1], out[2]))
.isEqualTo(schematic.at(x, y, z));
}
}
}
}
}
}
@Test
void outsideTheBoxNothingIsWanted() throws SchematicException {
Placement placement = new Placement(numbered(), 0, 0, 0);
placement.turn(1);
assertThat(placement.indexAt(-1, 0, 0)).isZero();
assertThat(placement.indexAt(3, 0, 0)).isZero();
assertThat(placement.indexAt(0, 2, 0)).isZero();
assertThat(placement.indexAt(0, 0, 4)).isZero();
assertThat(placement.indexAt(2, 1, 3)).isNotZero();
}
/**
* A block that faces the box's west end, at the west end: turned or mirrored, it must still face
* the end it's at, so the position's turn and the state's agree.
*/
@Test
void blocksTurnTheWayTheirPlacesDo() throws SchematicException {
FakeBlocks blocks = new FakeBlocks();
Schematic.Builder builder = new Schematic.Builder(3, 1, 1);
builder.set(0, 0, 0, builder.index(BlockSpec.of("minecraft:stairs", Map.of("facing", "west"))));
Schematic schematic = builder.build();
int west = blocks.state("minecraft:stairs[facing=west]");
int[] out = new int[3];
for (Mirror mirror : Mirror.values()) {
for (int turns = 0; turns < 4; turns++) {
Placement placement = new Placement(schematic, 0, 0, 0);
placement.mirror(mirror);
placement.turn(turns);
placement.toWorld(0, 0, 0, out);
String facing = blocks.text(blocks.transform(west, mirror, turns));
String end;
if (placement.sizeX() > 1) {
end = out[0] == 0 ? "west" : "east";
} else {
end = out[2] == 0 ? "north" : "south";
}
assertThat(facing).as("%s, %d turns", mirror, turns).isEqualTo("minecraft:stairs[facing=" + end + "]");
}
}
}
}
@@ -0,0 +1,192 @@
package incari.features.schematics;
import static incari.features.schematics.format.NbtWriter.compound;
import static org.assertj.core.api.Assertions.assertThat;
import incari.features.schematics.format.NbtWriter;
import incari.framework.game.PlayerView;
import incari.framework.testing.FakePlayer;
import incari.framework.testing.TestGame;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class SchematicsModuleTest {
private final SchematicsModule module = new SchematicsModule();
private final TestGame game = new TestGame(module);
private FakePlayer player = new FakePlayer();
/**
* A Sponge schematic 3 x 2 x 1: stone, stone and stairs facing north along the bottom; air, air
* and glass on top.
*/
static byte[] tower() {
Map<String, Object> palette = compound(
"minecraft:air", 0,
"minecraft:stone", 1,
"minecraft:oak_stairs[facing=north]", 2,
"minecraft:glass", 3);
return NbtWriter.gzipped(compound(
"Version",
2,
"DataVersion",
4440,
"Width",
(short) 3,
"Height",
(short) 2,
"Length",
(short) 1,
"Palette",
palette,
"BlockData",
NbtWriter.varints(new int[] {1, 1, 2, 0, 0, 3}),
"BlockEntities",
List.of()));
}
@BeforeEach
void join() {
player = game.join().at(100.5, 64, 200.5);
module.setEnabled(true);
}
private void load() {
game.chosenName = "tower.schem";
game.chosenBytes = tower();
module.choose.run();
}
@Test
void choosingAFileLoadsItWhereThePlayerStands() {
assertThat(module.here.isVisible()).isFalse();
load();
assertThat(game.screens).containsExactly("choose:schematics .litematic .schem .nbt");
assertThat(game.messages).containsExactly("Schematics: tower, 3 x 2 x 1, placed where you stand.");
assertThat(module.isLoaded()).isTrue();
assertThat(module.here.isVisible()).isTrue();
List<String> drawn = game.drawWorld();
assertThat(drawn)
.contains(
"ghost minecraft:stone at 100,64,200",
"ghost minecraft:stone at 101,64,200",
"ghost minecraft:oak_stairs[facing=north] at 102,64,200",
"ghost minecraft:glass at 102,65,200",
"box 100,64,200 to 103,66,201 #ff55aaff");
}
@Test
void builtBlocksStopBeingGhostsAndWrongOnesAreBoxed() {
load();
game.blocks.set(100, 64, 200, "minecraft:stone");
game.blocks.set(101, 64, 200, "minecraft:dirt");
game.blocks.set(102, 64, 200, "minecraft:oak_stairs[facing=south]");
game.blocks.set(100, 65, 200, "minecraft:torch");
game.ticks(Verifier.NEAR_TICKS + 1);
List<String> drawn = game.drawWorld();
assertThat(drawn).noneMatch(line -> line.startsWith("ghost minecraft:stone"));
assertThat(drawn)
.contains(
"ghost minecraft:glass at 102,65,200",
"box 101,64,200 to 102,65,201 #ffff3333",
"box 102,64,200 to 103,65,201 #ffffaa00",
"box 100,65,200 to 101,66,201 #ffff55ff");
module.highlight.set(false);
assertThat(game.drawWorld()).noneMatch(line -> line.startsWith("box 101,64,200"));
}
@Test
void theMaterialListCountsWhatsLeftAndWhatThePlayerCarries() {
load();
player.carry("minecraft:stone", 5);
game.ticks(SchematicsModule.MATERIAL_TICKS);
TestGame.Canvas hud = game.drawHud();
String all = String.join("\n", hud.drawn);
assertThat(all).contains("Materials: 3 left", "\"2\"", "POSITIVE");
game.blocks.set(100, 64, 200, "minecraft:stone");
game.blocks.set(101, 64, 200, "minecraft:stone");
game.ticks(SchematicsModule.MATERIAL_TICKS);
assertThat(String.join("\n", game.drawHud().drawn)).contains("Materials: 2 left", "2 of 4 placed");
}
@Test
void turningMovesTheGhostsRoundItsCorner() {
load();
module.turn.run();
List<String> drawn = game.drawWorld();
// Turned clockwise, the row that ran east now runs south, and the stairs face east.
assertThat(drawn)
.contains(
"ghost minecraft:stone at 100,64,200",
"ghost minecraft:stone at 100,64,201",
"ghost minecraft:oak_stairs[facing=east] at 100,64,202",
"box 100,64,200 to 101,66,203 #ff55aaff");
// Mirrored east-west first, the stairs swap ends; facing north, they still face north before the turn.
module.mirror.run();
assertThat(game.drawWorld())
.contains(
"ghost minecraft:oak_stairs[facing=east] at 100,64,200", "ghost minecraft:stone at 100,64,202");
}
@Test
void oneLayerAtATime() {
load();
module.layers.set(SchematicsModule.Layers.ONE);
assertThat(module.layer()).isEqualTo(64);
assertThat(game.drawWorld()).noneMatch(line -> line.contains(",65,"));
player.at(100.5, 65, 200.5);
module.layers.set(SchematicsModule.Layers.ALL);
module.layers.set(SchematicsModule.Layers.ONE);
assertThat(game.drawWorld()).noneMatch(line -> line.startsWith("ghost") && line.contains(",64,"));
}
@Test
void aBrokenFileOrUnknownBlocksAreSaid() {
game.chosenName = "broken.schem";
game.chosenBytes = new byte[] {0x1F, (byte) 0x8B, 1, 2};
module.choose.run();
assertThat(game.messages).singleElement().asString().startsWith("Schematics: Couldn't load broken.schem: ");
assertThat(module.isLoaded()).isFalse();
game.blocks.unknown.add("minecraft:glass");
load();
assertThat(game.messages.get(1)).endsWith("1 block isn't in this version: left out.");
assertThat(game.drawWorld()).noneMatch(line -> line.contains("glass"));
}
@Test
void itStaysInTheDimensionItWasPlacedIn() {
load();
player.in(PlayerView.NETHER);
game.ticks(1);
assertThat(game.drawWorld()).isEmpty();
String hud = String.join("\n", game.drawHud().drawn);
assertThat(hud).contains("In the Overworld").doesNotContain("Materials");
player.in(PlayerView.OVERWORLD);
game.ticks(1);
assertThat(game.drawWorld()).contains("ghost minecraft:stone at 100,64,200");
// Placed again where the player stands, it moves to their dimension.
player.in(PlayerView.NETHER);
game.ticks(1);
module.here.run();
assertThat(game.drawWorld()).contains("ghost minecraft:stone at 100,64,200");
}
@Test
void unloadingTakesItAway() {
load();
module.unload.run();
assertThat(module.isLoaded()).isFalse();
assertThat(game.drawWorld()).isEmpty();
assertThat(game.drawHud().drawn).isEmpty();
}
}
@@ -0,0 +1,123 @@
package incari.features.schematics;
import static org.assertj.core.api.Assertions.assertThat;
import incari.features.schematics.format.BlockSpec;
import incari.features.schematics.format.Schematic;
import incari.features.schematics.format.SchematicException;
import incari.framework.game.Blocks;
import incari.framework.testing.FakeBlocks;
import java.util.Map;
import org.junit.jupiter.api.Test;
class VerifierTest {
private final FakeBlocks blocks = new FakeBlocks();
/** A row of five along x at y 64: stone, stone, oak stairs facing north, air, planks. */
private Placement row() throws SchematicException {
Schematic.Builder builder = new Schematic.Builder(5, 1, 1);
int stone = builder.index(BlockSpec.of("minecraft:stone", Map.of()));
builder.set(0, 0, 0, stone);
builder.set(1, 0, 0, stone);
builder.set(2, 0, 0, builder.index(BlockSpec.of("minecraft:oak_stairs", Map.of("facing", "north"))));
builder.set(3, 0, 0, builder.index(BlockSpec.AIR));
builder.set(4, 0, 0, builder.index(BlockSpec.of("minecraft:oak_planks", Map.of())));
return new Placement(builder.build(), 10, 64, 20);
}
private int[] states(Schematic schematic) {
int[] states = new int[schematic.palette().size()];
for (int i = 0; i < states.length; i++) {
BlockSpec spec = schematic.palette().get(i);
states[i] = spec.isNothing() ? Blocks.UNKNOWN : blocks.state(spec.name(), spec.properties(), 0);
}
return states;
}
@Test
void eachKindOfProblemIsCountedAndListed() throws SchematicException {
Placement placement = row();
Verifier verifier = new Verifier(placement, states(placement.schematic), blocks);
blocks.set(10, 64, 20, "minecraft:stone");
// 11: missing. 12: stairs the wrong way. 13: dirt where air is wanted. 14: glass, not planks.
blocks.set(12, 64, 20, "minecraft:oak_stairs[facing=south]");
blocks.set(13, 64, 20, "minecraft:dirt");
blocks.set(14, 64, 20, "minecraft:glass");
verifier.tick(12, 64, 20, 48);
assertThat(verifier.right()).isEqualTo(1);
assertThat(verifier.missing()).isEqualTo(1);
assertThat(verifier.wrongStates()).isEqualTo(1);
assertThat(verifier.extra()).isEqualTo(1);
assertThat(verifier.wrongBlocks()).isEqualTo(1);
assertThat(verifier.lookedAtAll()).isTrue();
Verifier.Section section = verifier.section(0, 4, 1);
assertThat(section).isNotNull();
assertThat(section.issueCount).isEqualTo(3);
int stairs = (0 << 8 | 4 << 4 | 12) << 3 | Verifier.WRONG_STATE;
int dirt = (0 << 8 | 4 << 4 | 13) << 3 | Verifier.EXTRA;
int glass = (0 << 8 | 4 << 4 | 14) << 3 | Verifier.WRONG_BLOCK;
assertThat(new int[] {section.issue(0), section.issue(1), section.issue(2)})
.containsExactly(stairs, dirt, glass);
}
@Test
void buildingNearbyShowsWithinAFewTicksAndChangesTheRevision() throws SchematicException {
Placement placement = row();
Verifier verifier = new Verifier(placement, states(placement.schematic), blocks);
verifier.tick(12, 64, 20, 48);
assertThat(verifier.missing()).isEqualTo(4);
Verifier.Section section = verifier.section(0, 4, 1);
assertThat(section).isNotNull();
long before = section.revision;
blocks.set(11, 64, 20, "minecraft:stone");
for (int i = 0; i < Verifier.NEAR_TICKS; i++) {
verifier.tick(12, 64, 20, 48);
}
assertThat(verifier.missing()).isEqualTo(3);
assertThat(verifier.right()).isEqualTo(1);
assertThat(verifier.rightOf(placement.schematic.at(1, 0, 0))).isEqualTo(1);
assertThat(section.revision).isNotEqualTo(before);
}
@Test
void anUnloadedChunkCountsAsNothingYet() throws SchematicException {
Placement placement = row();
Verifier verifier = new Verifier(placement, states(placement.schematic), blocks);
blocks.loaded = false;
verifier.tick(12, 64, 20, 48);
assertThat(verifier.missing() + verifier.right() + verifier.extra()).isZero();
blocks.loaded = true;
for (int i = 0; i < Verifier.NEAR_TICKS; i++) {
verifier.tick(12, 64, 20, 48);
}
assertThat(verifier.missing()).isEqualTo(4);
}
@Test
void aTickLooksAtNoMoreThanItsBudget() throws SchematicException {
// 96 x 32 x 96: 300,000 blocks, far past a tick's looking.
Schematic.Builder builder = new Schematic.Builder(96, 32, 96);
int stone = builder.index(BlockSpec.of("minecraft:stone", Map.of()));
for (int y = 0; y < 32; y++) {
for (int z = 0; z < 96; z++) {
for (int x = 0; x < 96; x++) {
builder.set(x, y, z, stone);
}
}
}
Placement placement = new Placement(builder.build(), 0, 0, 0);
Verifier verifier = new Verifier(placement, states(placement.schematic), blocks);
blocks.reads = 0;
verifier.tick(48, 16, 48, 32);
assertThat(blocks.reads).isLessThanOrEqualTo(Verifier.BUDGET + 4096);
for (int i = 0; i < 200; i++) {
verifier.tick(48, 16, 48, 32);
}
assertThat(verifier.lookedAtAll()).isTrue();
assertThat(verifier.missing()).isEqualTo(96 * 32 * 96);
}
}
@@ -0,0 +1,313 @@
package incari.features.schematics.format;
import static incari.features.schematics.format.NbtWriter.compound;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.junit.jupiter.api.Test;
class FormatTest {
@Test
void packedEntriesRunOnIntoTheNextLong() {
Random random = new Random(66);
for (int bits = 1; bits <= 32; bits++) {
int[] values = new int[300];
for (int i = 0; i < values.length; i++) {
values[i] = (int) (random.nextLong() & ((1L << bits) - 1));
}
PackedArray read = new PackedArray(bits, values.length, NbtWriter.pack(values, bits));
PackedArray written = new PackedArray(bits, values.length);
for (int i = 0; i < values.length; i++) {
assertThat(read.get(i)).as("bits %d, entry %d", bits, i).isEqualTo(values[i]);
written.set(i, values[i]);
}
for (int i = 0; i < values.length; i++) {
assertThat(written.get(i)).isEqualTo(values[i]);
}
}
}
@Test
void bitsAreAtLeastTwoAndEnoughForThePalette() {
assertThat(PackedArray.bitsFor(1, 2)).isEqualTo(2);
assertThat(PackedArray.bitsFor(4, 2)).isEqualTo(2);
assertThat(PackedArray.bitsFor(5, 2)).isEqualTo(3);
assertThat(PackedArray.bitsFor(17, 2)).isEqualTo(5);
assertThatThrownBy(() -> new PackedArray(5, 100, new long[2])).isInstanceOf(IllegalArgumentException.class);
}
@Test
void statesParseAsTheGameWritesThem() {
BlockSpec stairs = BlockSpec.parse("minecraft:oak_stairs[half=bottom,facing=north]");
assertThat(stairs.name()).isEqualTo("minecraft:oak_stairs");
assertThat(stairs.properties()).containsExactly(Map.entry("facing", "north"), Map.entry("half", "bottom"));
assertThat(stairs.toString()).isEqualTo("minecraft:oak_stairs[facing=north,half=bottom]");
assertThat(BlockSpec.parse("stone")).isEqualTo(new BlockSpec("minecraft:stone", Map.of()));
assertThat(BlockSpec.parse("minecraft:cave_air").isAir()).isTrue();
}
@Test
void nbtReadsPackedOrNotAndRefusesBrokenFiles() throws IOException {
Map<String, Object> root = compound("a", 1, "b", "text", "c", List.of(1, 2, 3), "d", new long[] {5L});
for (byte[] file : List.of(NbtWriter.plain(root), NbtWriter.gzipped(root))) {
Nbt.Compound read = Nbt.read(file);
assertThat(read.integer("a", 0)).isEqualTo(1);
assertThat(read.string("b", "")).isEqualTo("text");
assertThat(read.ints("c")).containsExactly(1, 2, 3);
assertThat(read.longs("d")).containsExactly(5L);
}
byte[] whole = NbtWriter.plain(root);
assertThatThrownBy(() -> Nbt.read(Arrays.copyOf(whole, whole.length - 3)))
.isInstanceOf(IOException.class);
// A long array claiming two billion entries, in a file of a few bytes.
byte[] lying = NbtWriter.plain(compound("d", new long[] {1L}));
lying[lying.length - 13] = 0x7F;
assertThatThrownBy(() -> Nbt.read(lying)).isInstanceOf(IOException.class);
}
/** A region of {@code size} filled with palette indices {@code 0, 1, 2...} in turn. */
private static Map<String, Object> region(int[] position, int[] size, List<String> palette) {
int volume = Math.abs(size[0] * size[1] * size[2]);
int[] values = new int[volume];
for (int i = 0; i < volume; i++) {
values[i] = i % palette.size();
}
List<Object> entries = new ArrayList<>();
for (String name : palette) {
BlockSpec spec = BlockSpec.parse(name);
entries.add(
spec.properties().isEmpty()
? compound("Name", spec.name())
: compound("Name", spec.name(), "Properties", Map.copyOf(spec.properties())));
}
return compound(
"Position", compound("x", position[0], "y", position[1], "z", position[2]),
"Size", compound("x", size[0], "y", size[1], "z", size[2]),
"BlockStatePalette", entries,
"BlockStates", NbtWriter.pack(values, PackedArray.bitsFor(palette.size(), 2)),
"TileEntities", List.of(),
"Entities", List.of());
}
@Test
void litematicRegionsMergeIntoOneBoxWithNothingBetween() throws SchematicException {
List<String> five = List.of(
"minecraft:air",
"minecraft:stone",
"minecraft:oak_planks",
"minecraft:glass",
"minecraft:oak_log[axis=x]");
Map<String, Object> root = compound(
"Version",
6,
"MinecraftDataVersion",
3700,
"Metadata",
compound("Name", "Hut", "Author", "Sam", "EnclosingSize", compound("x", 5, "y", 2, "z", 3)),
"Regions",
compound(
"main", region(new int[] {0, 0, 0}, new int[] {3, 2, 3}, five),
// Negative size: it runs from x 4 down to x 3.
"porch",
region(
new int[] {4, 0, 0},
new int[] {-2, 1, 1},
List.of("minecraft:air", "minecraft:dirt"))));
Schematic schematic = SchematicFiles.read("hut.litematic", NbtWriter.gzipped(root));
assertThat(schematic.name()).isEqualTo("Hut");
assertThat(schematic.author()).isEqualTo("Sam");
assertThat(schematic.format()).isEqualTo("Litematic");
assertThat(schematic.dataVersion()).isEqualTo(3700);
assertThat(new int[] {schematic.sizeX(), schematic.sizeY(), schematic.sizeZ()})
.containsExactly(5, 2, 3);
// Main's blocks: index (y * 3 + z) * 3 + x into its five-entry palette, 3 bits each.
for (int y = 0; y < 2; y++) {
for (int z = 0; z < 3; z++) {
for (int x = 0; x < 3; x++) {
String want = five.get(((y * 3 + z) * 3 + x) % 5);
assertThat(schematic.palette().get(schematic.at(x, y, z))).isEqualTo(BlockSpec.parse(want));
}
}
}
// The porch: air at x 3, dirt at x 4; nothing wanted where no region reaches.
assertThat(schematic.palette().get(schematic.at(3, 0, 0)).isAir()).isTrue();
assertThat(schematic.palette().get(schematic.at(4, 0, 0)).name()).isEqualTo("minecraft:dirt");
assertThat(schematic.at(4, 1, 0)).isZero();
assertThat(schematic.at(4, 0, 2)).isZero();
}
@Test
void litematicWithTooFewLongsIsRefused() {
Map<String, Object> region =
region(new int[] {0, 0, 0}, new int[] {4, 4, 4}, List.of("minecraft:air", "minecraft:stone"));
region.put("BlockStates", new long[1]);
Map<String, Object> root = compound("Version", 6, "Regions", compound("r", region));
assertThatThrownBy(() -> SchematicFiles.read("x.litematic", NbtWriter.gzipped(root)))
.isInstanceOf(SchematicException.class)
.hasMessageContaining("cut short");
}
private static int[] spongeBlocks(int width, int height, int length, int paletteSize) {
int[] values = new int[width * height * length];
for (int i = 0; i < values.length; i++) {
values[i] = i % paletteSize;
}
return values;
}
/** A palette of air and 199 others, so numbers past 127 take two bytes. */
private static Map<String, Object> spongePalette() {
Map<String, Object> palette = compound("minecraft:air", 0);
for (int i = 1; i < 200; i++) {
palette.put("minecraft:wool_" + i + "[lit=" + (i % 2 == 0) + "]", i);
}
return palette;
}
@Test
void spongeTwoAndThreeReadAlike() throws SchematicException {
int[] values = spongeBlocks(9, 4, 7, 200);
Map<String, Object> two = compound(
"Version",
2,
"DataVersion",
4440,
"Width",
(short) 9,
"Height",
(short) 4,
"Length",
(short) 7,
"PaletteMax",
200,
"Palette",
spongePalette(),
"BlockData",
NbtWriter.varints(values),
"BlockEntities",
List.of());
Map<String, Object> three = compound(
"Schematic",
compound(
"Version",
3,
"DataVersion",
4556,
"Width",
(short) 9,
"Height",
(short) 4,
"Length",
(short) 7,
"Metadata",
compound("Name", "Arena"),
"Blocks",
compound(
"Palette",
spongePalette(),
"Data",
NbtWriter.varints(values),
"BlockEntities",
List.of())));
Schematic a = SchematicFiles.read("arena.schem", NbtWriter.gzipped(two));
Schematic b = SchematicFiles.read("whatever.schem", NbtWriter.gzipped(three));
assertThat(a.name()).isEqualTo("arena");
assertThat(b.name()).isEqualTo("Arena");
assertThat(a.dataVersion()).isEqualTo(4440);
for (int y = 0; y < 4; y++) {
for (int z = 0; z < 7; z++) {
for (int x = 0; x < 9; x++) {
int i = (y * 7 + z) * 9 + x;
String want = values[i] == 0
? "minecraft:air"
: "minecraft:wool_" + values[i] + "[lit=" + (values[i] % 2 == 0) + "]";
assertThat(a.palette().get(a.at(x, y, z))).isEqualTo(BlockSpec.parse(want));
assertThat(b.palette().get(b.at(x, y, z))).isEqualTo(BlockSpec.parse(want));
}
}
}
assertThat(a.blockCount()).isEqualTo(values.length - (values.length + 199) / 200);
}
@Test
void spongeCutShortIsRefused() {
Map<String, Object> root = compound(
"Version",
2,
"Width",
(short) 4,
"Height",
(short) 4,
"Length",
(short) 4,
"Palette",
compound("minecraft:air", 0),
"BlockData",
new byte[10]);
assertThatThrownBy(() -> SchematicFiles.read("x.schem", NbtWriter.gzipped(root)))
.isInstanceOf(SchematicException.class)
.hasMessageContaining("cut short");
}
@Test
void structuresLeaveUnlistedBlocksAsVoidAndTakeTheNewNames() throws SchematicException {
Map<String, Object> root = compound(
"DataVersion", 5023,
"size", List.of(2, 2, 2),
"palette",
List.of(
compound("id", "minecraft:air"),
compound(
"id",
"minecraft:furnace",
"properties",
compound("facing", "east", "lit", "false"))),
"blocks",
List.of(
compound("pos", List.of(0, 0, 0), "state", 1),
compound("pos", List.of(1, 1, 1), "state", 0)),
"entities", List.of());
Schematic schematic = SchematicFiles.read("camp.nbt", NbtWriter.gzipped(root));
assertThat(schematic.format()).isEqualTo("Structure");
assertThat(schematic.palette().get(schematic.at(0, 0, 0)))
.isEqualTo(BlockSpec.parse("minecraft:furnace[facing=east,lit=false]"));
assertThat(schematic.palette().get(schematic.at(1, 1, 1)).isAir()).isTrue();
assertThat(schematic.at(1, 0, 0)).isZero();
assertThat(schematic.blockCount()).isEqualTo(1);
}
@Test
void oldAndUnknownFilesSayWhy() {
Map<String, Object> mcedit = compound(
"Width",
(short) 1,
"Height",
(short) 1,
"Length",
(short) 1,
"Blocks",
new byte[1],
"Materials",
"Alpha");
assertThatThrownBy(() -> SchematicFiles.read("old.schematic", NbtWriter.gzipped(mcedit)))
.hasMessageContaining("before 1.13");
assertThatThrownBy(() -> SchematicFiles.read("x.schem", new byte[] {1, 2, 3}))
.isInstanceOf(SchematicException.class);
Map<String, Object> huge = compound(
"size",
List.of(4096, 4096, 4096),
"palette",
List.of(compound("id", "minecraft:air")),
"blocks",
List.of());
assertThatThrownBy(() -> SchematicFiles.read("big.nbt", NbtWriter.gzipped(huge)))
.hasMessageContaining("Too big");
}
}
@@ -0,0 +1,151 @@
package incari.features.schematics.format;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPOutputStream;
/**
* Writes NBT for the tests, to make schematic files of known content: a {@code Map} is a compound,
* a {@code List} a list, {@code byte[]}/{@code int[]}/{@code long[]} arrays, boxed numbers and text
* as themselves.
*/
public final class NbtWriter {
private NbtWriter() {}
/** A compound from key, value pairs, in order. */
public static Map<String, Object> compound(Object... pairs) {
Map<String, Object> map = new LinkedHashMap<>();
for (int i = 0; i < pairs.length; i += 2) {
map.put((String) pairs[i], pairs[i + 1]);
}
return map;
}
/** {@code root}, gzipped as the game writes files. */
public static byte[] gzipped(Map<String, Object> root) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (DataOutputStream out = new DataOutputStream(new GZIPOutputStream(bytes))) {
write(out, root);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return bytes.toByteArray();
}
/** {@code root}, not packed. */
public static byte[] plain(Map<String, Object> root) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (DataOutputStream out = new DataOutputStream(bytes)) {
write(out, root);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return bytes.toByteArray();
}
private static void write(DataOutputStream out, Map<String, Object> root) throws IOException {
out.writeByte(10);
out.writeUTF("");
body(out, root);
}
private static int type(Object value) {
return switch (value) {
case Byte b -> 1;
case Short s -> 2;
case Integer i -> 3;
case Long l -> 4;
case Float f -> 5;
case Double d -> 6;
case byte[] b -> 7;
case String s -> 8;
case List<?> l -> 9;
case Map<?, ?> m -> 10;
case int[] i -> 11;
case long[] l -> 12;
default -> throw new IllegalArgumentException("Not NBT: " + value);
};
}
@SuppressWarnings("unchecked")
private static void body(DataOutputStream out, Object value) throws IOException {
switch (value) {
case Byte b -> out.writeByte(b);
case Short s -> out.writeShort(s);
case Integer i -> out.writeInt(i);
case Long l -> out.writeLong(l);
case Float f -> out.writeFloat(f);
case Double d -> out.writeDouble(d);
case byte[] bytes -> {
out.writeInt(bytes.length);
out.write(bytes);
}
case String s -> out.writeUTF(s);
case List<?> list -> {
out.writeByte(list.isEmpty() ? 0 : type(list.get(0)));
out.writeInt(list.size());
for (Object element : list) {
body(out, element);
}
}
case Map<?, ?> map -> {
for (Map.Entry<String, Object> entry : ((Map<String, Object>) map).entrySet()) {
out.writeByte(type(entry.getValue()));
out.writeUTF(entry.getKey());
body(out, entry.getValue());
}
out.writeByte(0);
}
case int[] ints -> {
out.writeInt(ints.length);
for (int i : ints) {
out.writeInt(i);
}
}
case long[] longs -> {
out.writeInt(longs.length);
for (long l : longs) {
out.writeLong(l);
}
}
default -> throw new IllegalArgumentException("Not NBT: " + value);
}
}
/**
* Packs {@code values} tightly, {@code bits} each, low bits first, by single bits: an oracle
* written apart from {@link PackedArray}.
*/
public static long[] pack(int[] values, int bits) {
long[] out = new long[(int) (((long) values.length * bits + 63) / 64)];
for (int i = 0; i < values.length; i++) {
for (int b = 0; b < bits; b++) {
if ((values[i] >>> b & 1) != 0) {
long bit = (long) i * bits + b;
out[(int) (bit / 64)] |= 1L << (bit % 64);
}
}
}
return out;
}
/** A schematic's blocks as Sponge's variable-length bytes. */
public static byte[] varints(int[] values) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
for (int value : values) {
int v = value;
while ((v & ~0x7F) != 0) {
out.write((v & 0x7F) | 0x80);
v >>>= 7;
}
out.write(v);
}
return out.toByteArray();
}
}