Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions src/main/java/world/bentobox/boxed/Boxed.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import java.util.Comparator;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
Expand Down Expand Up @@ -534,7 +533,9 @@ private World regenerateSeedWorld(World seedWorld, WorldCreator creator) {
return seedWorld;
}
try (Stream<Path> files = Files.walk(folder.toPath())) {
files.sorted(Comparator.reverseOrder()).forEach(path -> path.toFile().delete());
for (Path path : files.sorted(Comparator.reverseOrder()).toList()) {
Files.delete(path);
}
} catch (IOException e) {
logError("Could not delete seed world " + folder + ": " + e.getMessage());
}
Expand Down
63 changes: 41 additions & 22 deletions src/main/java/world/bentobox/boxed/areas/AreaManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public class AreaManager {
private final File gridFile;
private final YamlConfiguration grid;
private final Map<String, Area> areas = new LinkedHashMap<>();
private final Map<Integer, Area> rows = new ConcurrentHashMap<>();
private final Map<Integer, Area> areaByRow = new ConcurrentHashMap<>();
private final Map<Integer, Map<Environment, Template>> templates = new ConcurrentHashMap<>();
private final Set<String> pending = ConcurrentHashMap.newKeySet();
private final Area defaultArea;
Expand All @@ -55,19 +55,7 @@ public AreaManager(YamlConfiguration config, File gridFile, long defaultSeed,
this.gridFile = gridFile;
this.grid = YamlConfiguration.loadConfiguration(gridFile);
ConfigurationSection section = config.getConfigurationSection("areas");
List<String> ids = new ArrayList<>();
// The default area always exists and always comes first
ids.add(Area.DEFAULT);
if (section != null) {
for (String id : section.getKeys(false)) {
if (!VALID_ID.matcher(id).matches()) {
errorLog.accept("Area name '" + id
+ "' is not valid. Use lower case letters, numbers and underscores only. Ignoring it.");
} else if (!ids.contains(id)) {
ids.add(id);
}
}
}
List<String> ids = getIds(section, errorLog);
boolean changed = false;
for (String id : ids) {
String path = ROWS + "." + id;
Expand All @@ -79,24 +67,55 @@ public AreaManager(YamlConfiguration config, File gridFile, long defaultSeed,
if (s == null) {
s = new YamlConfiguration();
}
String requires = s.getString("requires");
if (requires != null && (!ids.contains(requires) || requires.equals(id))) {
errorLog.accept("Area '" + id + "' requires area '" + requires
+ "', which is not a different, known area. Ignoring the requirement.");
requires = null;
}
String requires = getRequirement(s, id, ids, errorLog);
Area area = new Area(id, s.getLong("seed", defaultSeed), s.getString("biomes", "biomes.yml"),
s.getString("structures", "structures.yml"), grid.getInt(path), s.getBoolean("enabled", true),
requires, Math.max(0, s.getInt("unlocks-next-at", 0)));
areas.put(id, area);
rows.put(area.row(), area);
areaByRow.put(area.row(), area);
}
defaultArea = areas.get(Area.DEFAULT);
if (changed) {
save(errorLog);
}
}

/**
* Lists the names of the areas in the config. The default area always exists and always
* comes first.
*/
private static List<String> getIds(ConfigurationSection section, java.util.function.Consumer<String> errorLog) {
List<String> ids = new ArrayList<>();
ids.add(Area.DEFAULT);
if (section == null) {
return ids;
}
for (String id : section.getKeys(false)) {
if (!VALID_ID.matcher(id).matches()) {
errorLog.accept("Area name '" + id
+ "' is not valid. Use lower case letters, numbers and underscores only. Ignoring it.");
} else if (!ids.contains(id)) {
ids.add(id);
}
}
return ids;
}

/**
* @return the area that an area requires, or null if it requires none or the one it names
* is not a different, known area
*/
private static String getRequirement(ConfigurationSection s, String id, List<String> ids,
java.util.function.Consumer<String> errorLog) {
String requires = s.getString("requires");
if (requires != null && (!ids.contains(requires) || requires.equals(id))) {
errorLog.accept("Area '" + id + "' requires area '" + requires
+ "', which is not a different, known area. Ignoring the requirement.");
return null;
}
return requires;
}

/**
* Rows are handed out in the order 0, 1, 2... Rows of areas that have since been removed
* from the config stay taken, because their boxes are still in the world.
Expand Down Expand Up @@ -191,7 +210,7 @@ public Area getAreaForBundle(@Nullable String bundle) {
*/
@NonNull
public Area getAreaAtRow(int row) {
Area area = rows.get(row);
Area area = areaByRow.get(row);
return area == null ? defaultArea : area;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@
public class AdminAreasCommand extends CompositeCommand {

private static final String PREFIX = "boxed.commands.boxadmin.areas.";

private static final String AREAS = "areas.";
private static final String UNKNOWN_AREA = PREFIX + "unknown-area";

public AdminAreasCommand(CompositeCommand parent) {
Expand Down Expand Up @@ -183,7 +185,7 @@ public boolean execute(User user, String label, List<String> args) {
long seed;
try {
seed = args.size() == 2 ? Long.parseLong(args.get(1)) : ThreadLocalRandom.current().nextLong();
} catch (NumberFormatException e) {
} catch (NumberFormatException _) {
user.sendMessage(PREFIX + "create.invalid-seed");
return false;
}
Expand Down Expand Up @@ -215,9 +217,9 @@ private void createArea(Boxed addon, String name, long seed) throws IOException
}
File areasFile = new File(folder, "areas.yml");
YamlConfiguration config = YamlConfiguration.loadConfiguration(areasFile);
config.set("areas." + name + ".seed", seed);
config.set("areas." + name + ".biomes", biomes);
config.set("areas." + name + ".structures", structures);
config.set(AREAS + name + ".seed", seed);
config.set(AREAS + name + ".biomes", biomes);
config.set(AREAS + name + ".structures", structures);
config.save(areasFile);

// A bundle with the same name is how players choose the area
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ public record RawBiomes(int minY, List<String> palette, byte[] cells) {

@Override
public boolean equals(Object o) {
return o instanceof RawBiomes other && minY == other.minY && palette.equals(other.palette)
&& Arrays.equals(cells, other.cells);
return o instanceof RawBiomes(int otherMinY, List<String> otherPalette, byte[] otherCells)
&& minY == otherMinY && palette.equals(otherPalette) && Arrays.equals(cells, otherCells);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ public TemplateChunk getChunk(int x, int z) {
private TemplateChunk load(int x, int z) {
try {
byte[] data = file.read(x, z);
return data == null ? null : resolve(RawChunk.decode(data));
return data.length == 0 ? null : resolve(RawChunk.decode(data));
} catch (IOException | RuntimeException e) {
errorLog.accept("Could not read template chunk " + x + " " + z + ": " + e);
return null;
Expand All @@ -188,7 +188,7 @@ private BlockData blockData(String string) {
return blockDataCache.computeIfAbsent(string, s -> {
try {
return Bukkit.createBlockData(s);
} catch (IllegalArgumentException e) {
} catch (IllegalArgumentException _) {
errorLog.accept("Template has a block this server does not know: " + s);
return Material.AIR.createBlockData();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -206,25 +206,7 @@ public static RawChunk toRawChunk(ChunkSnapshot snapshot, int minY, int maxY, Li
int[] uniform = new int[sectionCount];
for (int section = 0; section < sectionCount; section++) {
short[] blocks = new short[RawChunk.SECTION_BLOCKS];
boolean same = true;
int i = 0;
for (int y = 0; y < 16; y++) {
for (int z = 0; z < 16; z++) {
for (int x = 0; x < 16; x++) {
BlockData data = snapshot.getBlockData(x, minY + (section << 4) + y, z);
Integer id = blockIds.get(data);
if (id == null) {
id = blockPalette.size();
blockIds.put(data, id);
blockPalette.add(data.getAsString());
}
blocks[i] = id.shortValue();
same &= blocks[i] == blocks[0];
i++;
}
}
}
if (same) {
if (fillSection(snapshot, minY + (section << 4), blocks, blockIds, blockPalette)) {
uniform[section] = blocks[0];
} else {
sections[section] = blocks;
Expand All @@ -234,6 +216,29 @@ public static RawChunk toRawChunk(ChunkSnapshot snapshot, int minY, int maxY, Li
return new RawChunk(minY, blockPalette, sections, uniform, entities, tiles);
}

/**
* Fills in the palette indices of one section, adding to the palette as needed.
* @return true if every block in the section is the same
*/
private static boolean fillSection(ChunkSnapshot snapshot, int baseY, short[] blocks,
Map<BlockData, Integer> blockIds, List<String> blockPalette) {
boolean same = true;
int i = 0;
for (int y = 0; y < 16; y++) {
for (int z = 0; z < 16; z++) {
for (int x = 0; x < 16; x++) {
blocks[i] = blockIds.computeIfAbsent(snapshot.getBlockData(x, baseY + y, z), data -> {
blockPalette.add(data.getAsString());
return blockPalette.size() - 1;
}).shortValue();
same &= blocks[i] == blocks[0];
i++;
}
}
}
return same;
}

/**
* Gets the biomes of a chunk snapshot in their stored form. Can be called from any thread.
* @param snapshot snapshot that includes biomes
Expand All @@ -248,14 +253,10 @@ public static RawBiomes toRawBiomes(ChunkSnapshot snapshot, int minY, int maxY)
for (int y = 0; y < maxY - minY; y += 4) {
for (int z = 0; z < 16; z += 4) {
for (int x = 0; x < 16; x += 4) {
Biome biome = snapshot.getBiome(x, minY + y, z);
Integer id = biomeIds.get(biome);
if (id == null) {
id = palette.size();
biomeIds.put(biome, id);
palette.add(biome.getKey().toString());
}
cells[RawBiomes.index(x, y, z)] = id.byteValue();
cells[RawBiomes.index(x, y, z)] = biomeIds.computeIfAbsent(snapshot.getBiome(x, minY + y, z), b -> {
palette.add(b.getKey().toString());
return palette.size() - 1;
}).byteValue();
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,15 +81,14 @@ public boolean isAirSection(int y) {
*/
@Nullable
public Integer getGroundLevel(int x, int z) {
for (int y = minY + sections.length * 16 - 1; y >= minY; y--) {
if (isAirSection(y)) {
// Skip to the bottom of the empty section
y = minY + (((y - minY) >> 4) << 4);
continue;
}
Material m = getBlockData(x, y, z).getMaterial();
if (m.isSolid() && !Tag.LEAVES.isTagged(m) && !Tag.LOGS.isTagged(m)) {
return y;
for (int section = sections.length - 1; section >= 0; section--) {
int baseY = minY + (section << 4);
// Empty sections are skipped whole
for (int y = baseY + 15; y >= baseY && !isAirSection(baseY); y--) {
Material m = getBlockData(x, y, z).getMaterial();
if (m.isSolid() && !Tag.LEAVES.isTagged(m) && !Tag.LOGS.isTagged(m)) {
return y;
}
}
}
return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,16 +108,16 @@ public long getSeed() {
* Reads the compressed data of a chunk. Safe to call from any thread.
* @param x chunk x, from -size to size - 1
* @param z chunk z, from -size to size - 1
* @return compressed chunk, or null if the template does not have this chunk
* @return compressed chunk, or an empty array if the template does not have this chunk
* @throws IOException if the file cannot be read
*/
public byte[] read(int x, int z) throws IOException {
if (x < -size || x >= size || z < -size || z >= size) {
return null;
return new byte[0];
}
int slot = slot(size, x, z);
if (lengths[slot] <= 0) {
return null;
return new byte[0];
}
return readFully(lengths[slot], offsets[slot]).array();
}
Expand Down Expand Up @@ -257,7 +257,7 @@ public synchronized void abort() {
try {
channel.close();
Files.deleteIfExists(temp.toPath());
} catch (IOException e) {
} catch (IOException _) {
// Nothing more can be done
}
}
Expand Down
35 changes: 22 additions & 13 deletions src/main/java/world/bentobox/boxed/listeners/BoxCleaner.java
Original file line number Diff line number Diff line change
Expand Up @@ -251,19 +251,8 @@ static int restore(Chunk chunk, TemplateChunk template, BoxedBlockPopulator popu
int maxY = world.getMaxHeight();
for (int sectionY = minY; sectionY < maxY; sectionY += 16) {
// Most of the sky is air in both, which is quick to check
if (snapshot.isSectionEmpty((sectionY - minY) >> 4) && template.isAirSection(sectionY)) {
continue;
}
for (int y = sectionY; y < sectionY + 16; y++) {
for (int z = 0; z < 16; z++) {
for (int x = 0; x < 16; x++) {
BlockData wanted = template.getBlockData(x, y, z);
if (wanted != null && !wanted.equals(snapshot.getBlockData(x, y, z))) {
chunk.getBlock(x, y, z).setBlockData(wanted, false);
changed++;
}
}
}
if (!snapshot.isSectionEmpty((sectionY - minY) >> 4) || !template.isAirSection(sectionY)) {
changed += restoreSection(chunk, snapshot, template, sectionY);
}
}
// Chests, spawners and so on get their contents back, whether or not the block changed
Expand All @@ -280,6 +269,26 @@ static int restore(Chunk chunk, TemplateChunk template, BoxedBlockPopulator popu
return changed;
}

/**
* Puts back every block of a 16-block-high section that differs from the template.
* @return the number of blocks that were put back
*/
private static int restoreSection(Chunk chunk, ChunkSnapshot snapshot, TemplateChunk template, int sectionY) {
int changed = 0;
for (int y = sectionY; y < sectionY + 16; y++) {
for (int z = 0; z < 16; z++) {
for (int x = 0; x < 16; x++) {
BlockData wanted = template.getBlockData(x, y, z);
if (wanted != null && !wanted.equals(snapshot.getBlockData(x, y, z))) {
chunk.getBlock(x, y, z).setBlockData(wanted, false);
changed++;
}
}
}
}
return changed;
}

/**
* Ends the current job. The record of the deleted box is removed so that the position is
* free, unless the box has been brought back in the meantime.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import world.bentobox.bentobox.managers.BlueprintsManager;
import world.bentobox.bentobox.managers.IslandDeletionManager;
import world.bentobox.boxed.Boxed;
import world.bentobox.boxed.CommonTestSetup;
Expand Down Expand Up @@ -47,7 +48,8 @@ void setUpStrategy() throws Exception {
when(addon.getSettings()).thenReturn(settings);
// No blueprints, so boxes go at the island height setting
when(addon.getPlugin()).thenReturn(plugin);
when(plugin.getBlueprintsManager()).thenReturn(mock(world.bentobox.bentobox.managers.BlueprintsManager.class));
BlueprintsManager blueprints = mock(BlueprintsManager.class);
when(plugin.getBlueprintsManager()).thenReturn(blueprints);
AbstractBoxedChunkGenerator gen = mock(AbstractBoxedChunkGenerator.class);
// 20 chunks half-width = boxes 640 blocks apart
when(gen.getSize()).thenReturn(20);
Expand Down
3 changes: 2 additions & 1 deletion src/test/java/world/bentobox/boxed/areas/BoxHeightTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.io.File;
Expand Down Expand Up @@ -138,7 +139,7 @@ void testSpawnSignIsFound() {
void testCentrePutsTheSignOnTheGround() {
assertEquals(4, new BoxHeight(addon).get(ice));
// The sign is one block north of the bedrock, which is in the chunk north of the centre
org.mockito.Mockito.verify(template).getChunk(0, -1);
verify(template).getChunk(0, -1);
}

@Test
Expand Down
Loading
Loading