diff --git a/CLAUDE.md b/CLAUDE.md index 6c1cf58..6c84a49 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -36,6 +36,10 @@ Never hold the whole region in memory or load the seed world on a normal boot `areas/AreaManager` loads `areas.yml`. Each `Area` (seed, biomes file, structures file) has its own seed worlds (`/seed_`), its own templates (`areas//*.bxt`) and owns one east-west **row** of the box grid, persisted in `areas/grid.yml` and never reassigned. The generator, biome provider and populator pick the template from the chunk's z alone (`AbstractBoxedChunkGenerator.rowCalc` -> `Boxed.getTemplate(env, chunkZ)`), so anything that generates chunks must pass real game-world chunk coordinates, not folded ones. Boxes are placed by `AreaLocationStrategy`, returned from `Boxed.getNewIslandLocationStrategy(user, bundle)` (a BentoBox 3.25.0 hook): the blueprint bundle's unique id names the area, unknown bundles use `default`. The y of a box's centre comes from `areas/BoxHeight`: BentoBox pastes the starter blueprint with its bedrock at the centre, so the centre is set to land the blueprint's `[spawn_here]` sign on the area's ground (read from the template; falls back to the island-height setting). The nether blueprint is pasted at the same y, so it only lines up where the nether ground happens to match. Structure lists are per area via `Boxed.getStructuresFile(location)`. `AreaRules` refuses a box (by throwing from the hook, before anything is created) when the area is closed (`enabled: false`), is waiting for a restart, or is chained (`requires` + the required area's `unlocks-next-at` box size) and not yet unlocked, or the player already has a box in that area (one per area; the box being reset does not count). `/boxadmin areas` (`AdminAreasCommand`) lists, visits, creates and requests rebuilds of areas; creating and rebuilding only take effect at the next start because templates are built in `createWorlds()`. +### Reachability + +`reach/` answers whether an area can be played. `LandSurvey` counts, per box size, the blocks, biomes and template entities of an area's templates plus the starter blueprint and the structures file. `Requirements` reads `requirements.yml`, a hand-written model of what each scored advancement needs (and `provides` rules that turn biomes and structures into mobs). `GrowthSimulator` earns everything in reach, grows the box by the scores and repeats; `ReachReport` writes it up. `/boxadmin areas check ` runs the survey off the main thread. Every advancement with a score in `advancements.yml` must have an entry in `requirements.yml` (a test enforces it). + ### Deleted boxes `listeners/BoxCleaner` restores a deleted (soft-deleted, `isDeletable()`) box's whole position from the template — generated chunks only, both dimensions, within a 10 ms per tick budget — then removes the island record so `AreaLocationStrategy` can hand the position out again (it always takes the first position in the row with no record). Do not rely on BentoBox's region-file purge for Boxed: it only deletes a region when every position overlapping it is deletable, and 640-block positions always share 512-block regions with neighbours. Deleted boxes are re-queued from the island cache on `BentoBoxReadyEvent`, so no extra persistence is needed. diff --git a/README.md b/README.md index b7b8aee..3eacb70 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,7 @@ You can also do the same by hand: add the area to `areas.yml` and make a bluepri | `/boxadmin areas create [seed]` | Makes a new area and its blueprint bundle. Needs a restart. | | `/boxadmin areas rebuild [regenerate]` | Builds the area's land again at the next restart. With `regenerate` the seed worlds are thrown away first, which is needed after changing the area's seed or biomes. Without it, the land is rebuilt from the seed worlds as they are, which keeps changes made to them by hand. | | `/boxadmin areas clean [x z]` | Puts the land of the box position you are in (or the one at x, z) back the way it was. Use it after trying out structures in a position nobody has a box in. Positions with a box in use are refused. | +| `/boxadmin areas check ` | Plays out how a box grows in the area and reports where players get stuck. See [Checking that an area can be played](#checking-that-an-area-can-be-played). | Areas can be chained so that a player's box in one area has to reach a certain size before the next area is unlocked, and can be closed to new boxes: @@ -142,6 +143,28 @@ advancements: ... ``` +### Checking that an area can be played + +`/boxadmin areas check ` answers the question "can a player in this area actually grow their box?". It looks at the area's land, the starter blueprint and the area's structures file, then plays the game out on paper: starting from a new box, it earns every advancement whose needs are inside the box, grows the box by their scores, and repeats until nothing more can be earned. + +The command prints one line, for example: + +``` +The box stops growing at size 263 of 320. 48 advancements earned for 262 points, 1 out of reach, 48 impossible (276 points). +``` + +and writes the full report to `areas//reachability.txt`. The report lists: + +* the advancements earned in each round and the box size at the time, +* the advancements that were still out of reach when the box stopped growing, with what was missing and the box size at which it first appears, +* the advancements that are impossible in the area, with the reason, +* the box size at which each biome, mob and structure first comes into the box. + +What each advancement needs is set in `requirements.yml`, which is written to the Boxed folder the first time you run the command. It is a model written by hand: it lists the raw resources an advancement comes down to (blocks, biomes, mobs, structures, other advancements), not every crafting step, and some entries are simplified. Mobs cannot be seen in the land itself, so the file also says which biomes and structures bring which mobs. Correct it to suit your server and your data pack. The check takes around half a minute and does not slow the server down. + +An advancement that scores points but can never be earned is worth either removing from `advancements.yml` or making possible, for example by placing a structure with `/boxadmin place`. + + ### biomes.yml The player's land has biomes and they are defined here. It's not possible to define where the biomes are right now, only what affect they have on the terrain. diff --git a/src/main/java/world/bentobox/boxed/areas/BoxHeight.java b/src/main/java/world/bentobox/boxed/areas/BoxHeight.java index 9f70e63..9285fb8 100644 --- a/src/main/java/world/bentobox/boxed/areas/BoxHeight.java +++ b/src/main/java/world/bentobox/boxed/areas/BoxHeight.java @@ -79,7 +79,7 @@ static int height(int ground, int signAboveBedrock) { * in the first bundle if the area has no bundle of its own. */ @Nullable - private Blueprint getBlueprint(Area area) { + public Blueprint getBlueprint(Area area) { Map bundles = addon.getPlugin().getBlueprintsManager().getBlueprintBundles(addon); BlueprintBundle own = bundles.get(area.id()); String name = Stream.concat(Stream.ofNullable(own), diff --git a/src/main/java/world/bentobox/boxed/commands/AdminAreasCommand.java b/src/main/java/world/bentobox/boxed/commands/AdminAreasCommand.java index 1070569..cfe138b 100644 --- a/src/main/java/world/bentobox/boxed/commands/AdminAreasCommand.java +++ b/src/main/java/world/bentobox/boxed/commands/AdminAreasCommand.java @@ -1,5 +1,6 @@ package world.bentobox.boxed.commands; +import java.util.HashMap; import java.util.Map; import java.util.EnumMap; import java.util.Comparator; @@ -8,25 +9,38 @@ import java.nio.file.Files; import java.util.List; import java.util.Locale; +import java.util.Objects; import java.util.Optional; +import java.util.stream.Stream; import java.util.concurrent.ThreadLocalRandom; +import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.World; +import org.bukkit.World.Environment; +import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; +import org.bukkit.util.Vector; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import world.bentobox.bentobox.api.commands.CompositeCommand; import world.bentobox.bentobox.api.localization.TextVariables; import world.bentobox.bentobox.api.user.User; +import world.bentobox.bentobox.blueprints.Blueprint; import world.bentobox.bentobox.blueprints.dataobjects.BlueprintBundle; import world.bentobox.bentobox.util.Util; import world.bentobox.boxed.Boxed; import world.bentobox.boxed.areas.Area; import world.bentobox.boxed.areas.AreaLocationStrategy; import world.bentobox.boxed.areas.AreaManager; +import world.bentobox.boxed.areas.BoxHeight; +import world.bentobox.boxed.generators.template.Template; +import world.bentobox.boxed.reach.GrowthSimulator; +import world.bentobox.boxed.reach.LandSurvey; +import world.bentobox.boxed.reach.ReachReport; +import world.bentobox.boxed.reach.Requirements; /** * Admin command that lists the areas. Its sub-commands visit an area, make a new one and @@ -39,6 +53,7 @@ public class AdminAreasCommand extends CompositeCommand { private static final String PREFIX = "boxed.commands.boxadmin.areas."; private static final String AREAS = "areas."; + private static final String REQUIREMENTS = "requirements.yml"; private static final String UNKNOWN_AREA = PREFIX + "unknown-area"; public AdminAreasCommand(CompositeCommand parent) { @@ -54,6 +69,7 @@ public void setup() { new Create(this); new Rebuild(this); new Clean(this); + new Check(this); } @Override @@ -345,4 +361,112 @@ public boolean execute(User user, String label, List args) { return true; } } + + /** + * Plays out how a box grows in an area and reports where players get stuck. + */ + static class Check extends CompositeCommand { + + Check(CompositeCommand parent) { + super(parent, "check"); + } + + @Override + public void setup() { + this.setPermission("admin.areas.check"); + this.setOnlyPlayer(false); + this.setParametersHelp(PREFIX + "check.parameters"); + this.setDescription(PREFIX + "check.description"); + } + + @Override + public boolean execute(User user, String label, List args) { + Boxed addon = getAddon(); + if (args.size() != 1) { + this.showHelp(this, user); + return false; + } + Area area = addon.getAreas().getArea(args.get(0).toLowerCase(Locale.ENGLISH)); + Template normal = area == null ? null : addon.getAreas().getTemplate(area, Environment.NORMAL); + if (area == null || normal == null) { + user.sendMessage(PREFIX + "unknown-area"); + return false; + } + Template nether = addon.getAreas().getTemplate(area, Environment.NETHER); + // Everything is read on the main thread. Only the survey of the land runs off it. + File folder = addon.getDataFolder(); + if (!new File(folder, REQUIREMENTS).exists()) { + addon.saveResource(REQUIREMENTS, false); + } + Requirements requirements = new Requirements( + YamlConfiguration.loadConfiguration(new File(folder, REQUIREMENTS)), addon::logWarning); + YamlConfiguration structures = YamlConfiguration.loadConfiguration(new File(folder, area.structures())); + Map scores = getScores(folder); + Map starter = getStarterBlocks(addon, area); + int radius = normal.getSize() * 16; + int startSize = Math.max(1, addon.getSettings().getIslandProtectionRange()); + File report = new File(addon.getAreaFolder(area), "reachability.txt"); + user.sendMessage(PREFIX + "check.started", TextVariables.NAME, area.id()); + Bukkit.getScheduler().runTaskAsynchronously(getPlugin(), () -> { + LandSurvey survey = new LandSurvey(radius); + survey.addTemplate(normal, false); + if (nether != null) { + survey.addTemplate(nether, true); + } + survey.addBlueprint(starter); + survey.addStructures(structures.getConfigurationSection("normal"), false); + survey.addStructures(structures.getConfigurationSection("nether"), true); + requirements.applyTo(survey); + GrowthSimulator.Result result = new GrowthSimulator(survey, requirements, scores, startSize).run(); + String summary = ReachReport.summary(result); + String written; + try { + Files.write(report.toPath(), ReachReport.lines(area.id(), survey, result)); + written = report.getPath(); + } catch (IOException e) { + addon.logError("Could not write " + report + ": " + e.getMessage()); + written = "-"; + } + String path = written; + Bukkit.getScheduler().runTask(getPlugin(), () -> { + addon.log("Area " + area.id() + ": " + summary); + user.sendMessage(PREFIX + "check.result", TextVariables.DESCRIPTION, summary); + user.sendMessage(PREFIX + "check.report", "[file]", path); + }); + }); + return true; + } + + /** + * @return how much each advancement grows the box, from advancements.yml + */ + private static Map getScores(File folder) { + Map scores = new HashMap<>(); + ConfigurationSection adv = YamlConfiguration.loadConfiguration(new File(folder, "advancements.yml")) + .getConfigurationSection("advancements"); + if (adv != null) { + adv.getKeys(false).forEach(k -> scores.put(k.contains(":") ? k : "minecraft:" + k, adv.getInt(k))); + } + return scores; + } + + /** + * @return the starter blocks of an area, by position relative to the centre of the box + */ + private static Map getStarterBlocks(Boxed addon, Area area) { + Map starter = new HashMap<>(); + Blueprint bp = new BoxHeight(addon).getBlueprint(area); + if (bp != null) { + Vector bedrock = bp.getBedrock() == null ? new Vector() : bp.getBedrock(); + Stream.of(bp.getBlocks(), bp.getAttached()).filter(Objects::nonNull).forEach( + m -> m.forEach((pos, block) -> starter.put(pos.clone().subtract(bedrock), block.getBlockData()))); + } + return starter; + } + + @Override + public Optional> tabComplete(User user, String alias, List args) { + return areaNames(getAddon(), args); + } + } } diff --git a/src/main/java/world/bentobox/boxed/generators/template/TemplateChunk.java b/src/main/java/world/bentobox/boxed/generators/template/TemplateChunk.java index dc8fdae..f034264 100644 --- a/src/main/java/world/bentobox/boxed/generators/template/TemplateChunk.java +++ b/src/main/java/world/bentobox/boxed/generators/template/TemplateChunk.java @@ -73,6 +73,49 @@ public boolean isAirSection(int y) { return sections[section] == null && palette[uniform[section]].getMaterial() == Material.AIR; } + /** + * Something to do with each block of a chunk. + */ + @FunctionalInterface + public interface BlockVisitor { + /** + * @param x x in the chunk, 0 to 15 + * @param y world y + * @param z z in the chunk, 0 to 15 + * @param data the block + */ + void visit(int x, int y, int z, BlockData data); + } + + /** + * Visits every block of the chunk that is not plain air. + * @param visitor called for each block + */ + public void forEachBlock(BlockVisitor visitor) { + for (int section = 0; section < sections.length; section++) { + short[] blocks = sections[section]; + BlockData same = blocks == null ? palette[uniform[section]] : null; + if (same == null || same.getMaterial() != Material.AIR) { + visitSection(visitor, minY + (section << 4), blocks, same); + } + } + } + + private void visitSection(BlockVisitor visitor, int baseY, short[] blocks, BlockData same) { + 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 = same != null ? same : palette[blocks[i]]; + i++; + if (data.getMaterial() != Material.AIR) { + visitor.visit(x, baseY + y, z, data); + } + } + } + } + } + /** * Finds the ground in a column: the highest block that can be stood on, ignoring trees. * @param x x in the chunk, 0 to 15 diff --git a/src/main/java/world/bentobox/boxed/reach/GrowthSimulator.java b/src/main/java/world/bentobox/boxed/reach/GrowthSimulator.java new file mode 100644 index 0000000..e00c1b9 --- /dev/null +++ b/src/main/java/world/bentobox/boxed/reach/GrowthSimulator.java @@ -0,0 +1,206 @@ +package world.bentobox.boxed.reach; + +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; + +import world.bentobox.boxed.reach.Requirements.Alternative; +import world.bentobox.boxed.reach.Requirements.Need; + +/** + * Plays out how a box grows in an area. Starting from the smallest box, every advancement + * whose needs are inside the box is earned and the box grows by its score, over and over until + * nothing more can be earned. This shows where a player gets stuck and which advancements can + * never be earned in the area. + * + * @author tastybento + */ +public class GrowthSimulator { + + /** + * An advancement that was earned. + * @param advancement advancement key + * @param score how much it grew the box + * @param round the round it was earned in, starting at 1 + * @param sizeBefore box size when it was earned + */ + public record Earned(String advancement, int score, int round, int sizeBefore) { + } + + /** + * An advancement that could not be earned. + * @param advancement advancement key + * @param score how much it would have grown the box + * @param missing why not, one line per need that was not met + * @param impossible true if no box size would be enough + */ + public record Blocked(String advancement, int score, List missing, boolean impossible) { + } + + /** + * How the growth went. + * @param earned advancements in the order they were earned + * @param blocked advancements that were not earned + * @param unlisted scored advancements the requirements file does not list + * @param finalSize the size the box reached, which is never more than the land allows + * @param maxSize the largest size the land allows + * @param sizeByRound box size at the end of each round + */ + public record Result(List earned, List blocked, List unlisted, int finalSize, int maxSize, + List sizeByRound) { + + /** + * @return true if the box grew to fill its land + */ + public boolean filledLand() { + return finalSize >= maxSize; + } + } + + private final LandSurvey survey; + private final Requirements requirements; + private final Map scores; + private final int startSize; + + /** + * @param survey the land, with the requirements' rules already applied to it + * @param requirements what each advancement needs + * @param scores how much each advancement grows the box. Ones that score nothing are ignored. + * @param startSize size of a new box + */ + public GrowthSimulator(LandSurvey survey, Requirements requirements, Map scores, int startSize) { + this.survey = survey; + this.requirements = requirements; + this.scores = new TreeMap<>(scores); + this.startSize = startSize; + } + + /** + * Plays out the growth of a box. + * @return how it went + */ + public Result run() { + int max = survey.getRadius(); + int size = Math.min(startSize, max); + Set earned = new LinkedHashSet<>(); + List order = new ArrayList<>(); + List unlisted = new ArrayList<>(); + List sizes = new ArrayList<>(); + Set candidates = new LinkedHashSet<>(); + scores.forEach((advancement, score) -> { + if (score > 0 && requirements.getNeeds(advancement) == null) { + unlisted.add(advancement); + } else if (score > 0) { + candidates.add(advancement); + } + }); + boolean progress = true; + for (int round = 1; progress; round++) { + progress = false; + int sizeNow = size; + Set before = Set.copyOf(earned); + for (String advancement : List.copyOf(candidates)) { + if (requirements.getNeeds(advancement).stream().allMatch(n -> isMet(n, sizeNow, before))) { + candidates.remove(advancement); + earned.add(advancement); + order.add(new Earned(advancement, scores.get(advancement), round, sizeNow)); + size = Math.min(max, size + scores.get(advancement)); + progress = true; + } + } + if (progress) { + sizes.add(size); + } + } + int finalSize = size; + List blocked = new ArrayList<>(candidates.stream().map(a -> blocked(a, finalSize, earned)).toList()); + markImpossibleChains(blocked); + return new Result(order, blocked, unlisted, finalSize, max, sizes); + } + + /** + * An advancement is also impossible if every way of meeting one of its needs is another + * advancement that is impossible. This is repeated until nothing changes, to follow chains. + */ + private void markImpossibleChains(List blocked) { + boolean changed = true; + while (changed) { + changed = false; + Set impossible = new LinkedHashSet<>(); + blocked.stream().filter(Blocked::impossible).forEach(b -> impossible.add(b.advancement())); + for (int i = 0; i < blocked.size(); i++) { + Blocked b = blocked.get(i); + if (!b.impossible() && requirements.getNeeds(b.advancement()).stream() + .anyMatch(n -> n.alternatives().stream().allMatch(a -> a.type() == Requirements.Type.NEVER + || (a.type() == Requirements.Type.AFTER && impossible.contains(a.names()))))) { + blocked.set(i, new Blocked(b.advancement(), b.score(), b.missing(), true)); + changed = true; + } + } + } + } + + private boolean isMet(Need need, int size, Set earned) { + return need.alternatives().stream().anyMatch(a -> isMet(a, size, earned)); + } + + private boolean isMet(Alternative a, int size, Set earned) { + return switch (a.type()) { + case NEVER -> false; + case SIZE -> size >= a.amount(); + case AFTER -> earned.contains(a.names()); + case RESOURCE -> (!a.kind().isNether() || earned.contains(requirements.getNetherAdvancement())) + && survey.count(a.kind(), a.names(), size) >= a.amount(); + }; + } + + private Blocked blocked(String advancement, int size, Set earned) { + List missing = new ArrayList<>(); + boolean impossible = false; + for (Need need : requirements.getNeeds(advancement)) { + if (isMet(need, size, earned)) { + continue; + } + // The need could still be met later if any of its alternatives could be + boolean possible = false; + List reasons = new ArrayList<>(); + for (Alternative a : need.alternatives()) { + String reason = explain(a, size); + possible |= !reason.startsWith("!"); + reasons.add(reason.startsWith("!") ? reason.substring(1) : reason); + } + impossible |= !possible; + missing.add(String.join(" or ", reasons)); + } + return new Blocked(advancement, scores.get(advancement), missing, impossible); + } + + /** + * Says why an alternative is not met. The text starts with ! if it never can be. + */ + private String explain(Alternative a, int size) { + switch (a.type()) { + case NEVER: + return "!" + a.names(); + case SIZE: + return (a.amount() > survey.getRadius() ? "!" : "") + "needs a box of size " + a.amount(); + case AFTER: + return "needs " + a.names() + " first"; + default: + break; + } + String what = (a.amount() > 1 ? a.amount() + " x " : "") + a.kind().label() + " " + a.names(); + int needed = survey.sizeNeeded(a.kind(), a.names(), a.amount()); + if (needed < 0) { + long there = survey.count(a.kind(), a.names(), survey.getRadius()); + return "!" + what + (there > 0 ? " (the land only has " + there + ")" : " (not in the land)"); + } + if (needed > size) { + return what + " (first at size " + needed + ")"; + } + return what + " (in the box, but the nether is not open)"; + } +} diff --git a/src/main/java/world/bentobox/boxed/reach/LandSurvey.java b/src/main/java/world/bentobox/boxed/reach/LandSurvey.java new file mode 100644 index 0000000..bc79f48 --- /dev/null +++ b/src/main/java/world/bentobox/boxed/reach/LandSurvey.java @@ -0,0 +1,266 @@ +package world.bentobox.boxed.reach; + +import java.util.EnumMap; +import java.util.HashMap; +import java.util.IdentityHashMap; +import java.util.Locale; +import java.util.Map; +import java.util.regex.Pattern; + +import org.bukkit.block.Biome; +import org.bukkit.block.data.BlockData; +import org.bukkit.configuration.ConfigurationSection; + +import world.bentobox.boxed.generators.chunks.AbstractBoxedChunkGenerator.EntityData; +import world.bentobox.boxed.generators.template.Template; +import world.bentobox.boxed.generators.template.TemplateChunk; + +/** + * What the land of an area holds, and how big a box has to be to hold it. A box covers + * the whole height of the world, so only the horizontal distance from the centre matters. + *

+ * Everything is recorded under a kind and a lower-case name, for example {@code block} and + * {@code iron_ore}. The kinds are in {@link Kind}. + * + * @author tastybento + */ +public class LandSurvey { + + /** + * The kinds of thing a survey records. The nether has its own kinds because a resource + * in the nether can only be used once the player can get there. + */ + public enum Kind { + BLOCK, BIOME, ENTITY, STRUCTURE, NETHER_BLOCK, NETHER_BIOME, NETHER_ENTITY, NETHER_STRUCTURE; + + /** + * @return how the kind is written in the requirements file, e.g. nether-block + */ + public String label() { + return name().toLowerCase(Locale.ENGLISH).replace('_', '-'); + } + + /** + * @return true if this kind is in the nether + */ + public boolean isNether() { + return name().startsWith("NETHER"); + } + } + + private final int radius; + private final Map> counts = new EnumMap<>(Kind.class); + + /** + * @param radius the largest box size, which is the distance from the centre of the land to its edge + */ + public LandSurvey(int radius) { + this.radius = radius; + } + + /** + * @return the largest box size + */ + public int getRadius() { + return radius; + } + + /** + * The box size needed to take in a block. + * @param x block x relative to the centre of the box + * @param z block z relative to the centre of the box + * @return the smallest box size that includes the block + */ + public static int sizeFor(int x, int z) { + // A box of size s covers -s to s - 1 on both axes + return Math.max(x >= 0 ? x + 1 : -x, z >= 0 ? z + 1 : -z); + } + + /** + * Records one or more of something. + * @param kind kind of thing + * @param name its name + * @param size the box size needed to take it in. Anything beyond the land is ignored. + * @param amount how many + */ + public void add(Kind kind, String name, int size, int amount) { + if (size <= radius) { + counter(kind, name)[Math.max(size, 1)] += amount; + } + } + + private int[] counter(Kind kind, String name) { + return counts.computeIfAbsent(kind, k -> new HashMap<>()).computeIfAbsent(name.toLowerCase(Locale.ENGLISH), + k -> new int[radius + 1]); + } + + /** + * Counts how many things of a kind are in a box. + * @param kind kind of thing + * @param names names separated by |, each of which may use * as a wildcard + * @param size box size + * @return how many there are in a box of that size + */ + public long count(Kind kind, String names, int size) { + Pattern pattern = pattern(names); + long total = 0; + for (Map.Entry en : counts.getOrDefault(kind, Map.of()).entrySet()) { + if (pattern.matcher(en.getKey()).matches()) { + for (int i = 1; i <= Math.min(size, radius); i++) { + total += en.getValue()[i]; + } + } + } + return total; + } + + /** + * Finds the box size at which there are enough things of a kind. + * @param kind kind of thing + * @param names names separated by |, each of which may use * as a wildcard + * @param amount how many are needed + * @return the smallest box size that holds that many, or -1 if the land never does + */ + public int sizeNeeded(Kind kind, String names, int amount) { + Pattern pattern = pattern(names); + long[] bySize = new long[radius + 1]; + counts.getOrDefault(kind, Map.of()).forEach((name, c) -> { + if (pattern.matcher(name).matches()) { + for (int i = 1; i <= radius; i++) { + bySize[i] += c[i]; + } + } + }); + long total = 0; + for (int i = 1; i <= radius; i++) { + total += bySize[i]; + if (total >= amount) { + return i; + } + } + return -1; + } + + /** + * @param kind kind of thing + * @return the names recorded for the kind and the smallest box size that holds one + */ + public Map firstSizes(Kind kind) { + Map result = new HashMap<>(); + counts.getOrDefault(kind, Map.of()).forEach((name, c) -> { + for (int i = 1; i <= radius; i++) { + if (c[i] > 0) { + result.put(name, i); + break; + } + } + }); + return result; + } + + static Pattern pattern(String names) { + StringBuilder sb = new StringBuilder(); + for (String name : names.toLowerCase(Locale.ENGLISH).split("\\|")) { + if (!sb.isEmpty()) { + sb.append('|'); + } + sb.append(Pattern.quote(name.trim()).replace("*", "\\E.*\\Q")); + } + return Pattern.compile(sb.toString()); + } + + /** + * Records the blocks, biomes and mobs of a template. + * @param template the land of an area in one dimension + * @param nether true if the template is the nether + */ + public void addTemplate(Template template, boolean nether) { + // Block data and biome objects are shared within a template, so they can be looked up by identity + Map blockCounters = new IdentityHashMap<>(); + Map biomeCounters = new IdentityHashMap<>(); + int chunks = template.getSize(); + for (int chunkX = -chunks; chunkX < chunks; chunkX++) { + for (int chunkZ = -chunks; chunkZ < chunks; chunkZ++) { + TemplateChunk chunk = template.getChunk(chunkX, chunkZ); + if (chunk != null) { + addBlocks(chunk, chunkX << 4, chunkZ << 4, nether, blockCounters); + addBiomes(template, chunkX, chunkZ, nether, biomeCounters); + addEntities(chunk, chunkX << 4, chunkZ << 4, nether); + } + } + } + } + + private void addBlocks(TemplateChunk chunk, int baseX, int baseZ, boolean nether, Map counters) { + Kind kind = nether ? Kind.NETHER_BLOCK : Kind.BLOCK; + chunk.forEachBlock((x, y, z, data) -> { + int size = sizeFor(baseX + x, baseZ + z); + if (size <= radius) { + counters.computeIfAbsent(data, d -> counter(kind, d.getMaterial().getKey().getKey()))[size]++; + } + }); + } + + /** + * Biomes are stored every four blocks. The one at sea level stands for the column, and a + * few higher and lower pick up the cave and mountain biomes. + */ + private void addBiomes(Template template, int chunkX, int chunkZ, boolean nether, Map counters) { + Kind kind = nether ? Kind.NETHER_BIOME : Kind.BIOME; + for (int cell = 0; cell < 16; cell++) { + int x = (cell & 3) << 2; + int z = (cell >> 2) << 2; + int size = sizeFor((chunkX << 4) + x, (chunkZ << 4) + z); + for (int y : BIOME_HEIGHTS) { + Biome biome = size <= radius ? template.getBiome(chunkX, chunkZ, x, y, z) : null; + if (biome != null) { + counters.computeIfAbsent(biome, b -> counter(kind, b.getKey().getKey()))[size]++; + } + } + } + } + + private void addEntities(TemplateChunk chunk, int baseX, int baseZ, boolean nether) { + for (EntityData e : chunk.getEntities()) { + add(nether ? Kind.NETHER_ENTITY : Kind.ENTITY, e.entity().getType().getKey().getKey(), + sizeFor(baseX + e.relativeLoc().getBlockX(), baseZ + e.relativeLoc().getBlockZ()), 1); + } + } + + private static final int[] BIOME_HEIGHTS = { 64, 32, 0, -32, -52, 100, 160 }; + + /** + * Records the blocks of the starter blueprint, which every new box is given. + * @param blocks block data strings by position relative to the centre of the box + */ + public void addBlueprint(Map blocks) { + blocks.forEach((pos, data) -> { + // "minecraft:oak_log[axis=y]" names the block oak_log + String name = data.replaceFirst("^minecraft:", "").replaceFirst("\\[.*$", ""); + if (!name.equals("air")) { + add(Kind.BLOCK, name, sizeFor(pos.getBlockX(), pos.getBlockZ()), 1); + } + }); + } + + /** + * Records the structures that are placed in every new box of an area. + * @param section a dimension's section of a structures file: "x,y,z" to "name,rotation,mirror" + * @param nether true if the section is for the nether + */ + public void addStructures(ConfigurationSection section, boolean nether) { + if (section == null) { + return; + } + for (String key : section.getKeys(false)) { + String[] xyz = key.split(","); + String value = section.getString(key, ""); + try { + int size = sizeFor(Integer.parseInt(xyz[0].trim()), Integer.parseInt(xyz[2].trim())); + add(nether ? Kind.NETHER_STRUCTURE : Kind.STRUCTURE, value.split(",")[0].trim(), size, 1); + } catch (NumberFormatException | ArrayIndexOutOfBoundsException _) { + // Not a structure entry + } + } + } +} diff --git a/src/main/java/world/bentobox/boxed/reach/ReachReport.java b/src/main/java/world/bentobox/boxed/reach/ReachReport.java new file mode 100644 index 0000000..7afeae3 --- /dev/null +++ b/src/main/java/world/bentobox/boxed/reach/ReachReport.java @@ -0,0 +1,101 @@ +package world.bentobox.boxed.reach; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; + +import world.bentobox.boxed.reach.GrowthSimulator.Blocked; +import world.bentobox.boxed.reach.GrowthSimulator.Earned; +import world.bentobox.boxed.reach.GrowthSimulator.Result; +import world.bentobox.boxed.reach.LandSurvey.Kind; + +/** + * Writes up a growth simulation as plain text for an admin to read. + * + * @author tastybento + */ +public final class ReachReport { + + private ReachReport() { + } + + /** + * @param area name of the area + * @param survey the land that was surveyed + * @param result how the growth went + * @return the report, one line per entry + */ + public static List lines(String area, LandSurvey survey, Result result) { + List out = new ArrayList<>(); + out.add("Reachability of area " + area); + out.add(""); + out.add(summary(result)); + out.add(""); + out.add("== Growth, round by round =="); + int round = 0; + for (Earned e : result.earned()) { + if (e.round() != round) { + round = e.round(); + out.add("Round " + round + ", box size " + e.sizeBefore() + ":"); + } + out.add(" +" + e.score() + " " + e.advancement()); + } + List later = result.blocked().stream().filter(b -> !b.impossible()) + .sorted(Comparator.comparing(Blocked::advancement)).toList(); + List never = result.blocked().stream().filter(Blocked::impossible) + .sorted(Comparator.comparing(Blocked::advancement)).toList(); + addBlocked(out, "== Not earned: out of reach when the box stopped growing ==", later); + addBlocked(out, "== Not earned: impossible in this area ==", never); + if (!result.unlisted().isEmpty()) { + out.add(""); + out.add("== Scored advancements that requirements.yml does not list =="); + result.unlisted().forEach(a -> out.add(" " + a)); + } + for (Kind kind : Kind.values()) { + // Blocks would run to hundreds of lines and are better asked about by name + if (kind != Kind.BLOCK && kind != Kind.NETHER_BLOCK) { + addFirstSizes(out, kind, survey); + } + } + return out; + } + + /** + * @param result how the growth went + * @return one line that says how far the box got + */ + public static String summary(Result result) { + int earnedScore = result.earned().stream().mapToInt(Earned::score).sum(); + long impossible = result.blocked().stream().filter(Blocked::impossible).count(); + int impossibleScore = result.blocked().stream().filter(Blocked::impossible).mapToInt(Blocked::score).sum(); + long stuck = result.blocked().size() - impossible; + return (result.filledLand() ? "The box grows to fill its land (size " + result.maxSize() + ")." + : "The box stops growing at size " + result.finalSize() + " of " + result.maxSize() + ".") + " " + + result.earned().size() + " advancements earned for " + earnedScore + " points, " + stuck + + " out of reach, " + impossible + " impossible (" + impossibleScore + " points)."; + } + + private static void addBlocked(List out, String title, List blocked) { + if (blocked.isEmpty()) { + return; + } + out.add(""); + out.add(title); + for (Blocked b : blocked) { + out.add(" +" + b.score() + " " + b.advancement()); + b.missing().forEach(m -> out.add(" " + m)); + } + } + + private static void addFirstSizes(List out, Kind kind, LandSurvey survey) { + Map sizes = survey.firstSizes(kind); + if (sizes.isEmpty()) { + return; + } + out.add(""); + out.add("== " + kind.label() + ": box size at which each first appears =="); + sizes.entrySet().stream().sorted(Map.Entry.comparingByValue().thenComparing(Map.Entry::getKey)) + .forEach(en -> out.add(String.format(" %4d %s", en.getValue(), en.getKey()))); + } +} diff --git a/src/main/java/world/bentobox/boxed/reach/Requirements.java b/src/main/java/world/bentobox/boxed/reach/Requirements.java new file mode 100644 index 0000000..4d4408f --- /dev/null +++ b/src/main/java/world/bentobox/boxed/reach/Requirements.java @@ -0,0 +1,222 @@ +package world.bentobox.boxed.reach; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.function.Consumer; + +import org.bukkit.configuration.ConfigurationSection; + +import world.bentobox.boxed.reach.LandSurvey.Kind; + +/** + * What a player needs to have in their box to earn each advancement, read from + * requirements.yml. This is a model written by hand: it says which raw resources an + * advancement comes down to, not every step of crafting. + * + * @author tastybento + */ +public class Requirements { + + /** + * Advancement that opens the nether if the file does not name one + */ + public static final String DEFAULT_NETHER = "minecraft:story/enter_the_nether"; + + /** + * What an alternative asks for + */ + public enum Type { + /** Something in the land */ + RESOURCE, + /** Another advancement earned first */ + AFTER, + /** A box of at least a certain size */ + SIZE, + /** Cannot be done in Boxed */ + NEVER + } + + /** + * One way of meeting a need. + * @param type what is asked for + * @param kind kind of resource, for a resource + * @param names resource names, the advancement to earn first, or the reason it can never be done + * @param amount how many of the resource, or the box size + */ + public record Alternative(Type type, Kind kind, String names, int amount) { + } + + /** + * Something an advancement needs. It is met when any one of its alternatives is. + * @param text the need as written in the file + * @param alternatives ways of meeting it + */ + public record Need(String text, List alternatives) { + } + + /** + * A rule that makes one thing in the land count as another as well, for example a village + * house counting as a villager. + * @param fromKind kind of the thing in the land + * @param fromNames its names + * @param toKind kind it also counts as + * @param toName name it also counts as + */ + public record Provides(Kind fromKind, String fromNames, Kind toKind, String toName) { + } + + private final Map> needs = new LinkedHashMap<>(); + private final List provides = new ArrayList<>(); + private final List always = new ArrayList<>(); + private final String netherAdvancement; + + /** + * @param config contents of requirements.yml + * @param errorLog where to report lines that cannot be understood + */ + public Requirements(ConfigurationSection config, Consumer errorLog) { + netherAdvancement = key(config.getString("nether-advancement", DEFAULT_NETHER)); + always.addAll(config.getStringList("always")); + for (String rule : config.getStringList("provides")) { + String[] sides = rule.split("->"); + Alternative from = sides.length == 2 ? alternative(sides[0], errorLog) : null; + Alternative to = sides.length == 2 ? alternative(sides[1], errorLog) : null; + if (from == null || to == null || from.type() != Type.RESOURCE || to.type() != Type.RESOURCE) { + errorLog.accept("requirements.yml: cannot understand the provides rule '" + rule + "'"); + } else { + provides.add(new Provides(from.kind(), from.names(), to.kind(), to.names())); + } + } + ConfigurationSection sets = config.getConfigurationSection("sets"); + ConfigurationSection advancements = config.getConfigurationSection("advancements"); + if (advancements == null) { + return; + } + for (String name : advancements.getKeys(false)) { + List list = new ArrayList<>(); + for (String line : advancements.getStringList(name)) { + addNeeds(line, sets, list, errorLog); + } + needs.put(key(name), list); + } + } + + private static String key(String name) { + return name.contains(":") ? name : "minecraft:" + name; + } + + private void addNeeds(String line, ConfigurationSection sets, List list, Consumer errorLog) { + String trimmed = line.trim(); + if (trimmed.startsWith("set:")) { + String set = trimmed.substring(4).trim(); + if (sets == null || !sets.isList(set)) { + errorLog.accept("requirements.yml: there is no set called '" + set + "'"); + return; + } + // Sets cannot hold other sets, which keeps them from going round in circles + sets.getStringList(set).forEach(l -> addNeed(l, list, errorLog)); + } else { + addNeed(trimmed, list, errorLog); + } + } + + private void addNeed(String line, List list, Consumer errorLog) { + List alternatives = new ArrayList<>(); + for (String part : line.split("\\|\\|")) { + Alternative a = alternative(part, errorLog); + if (a != null) { + alternatives.add(a); + } + } + if (!alternatives.isEmpty()) { + list.add(new Need(line.trim(), alternatives)); + } + } + + /** + * Reads one alternative, such as "block:iron_ore|deepslate_iron_ore*3" or "after:story/smelt_iron". + */ + static Alternative alternative(String text, Consumer errorLog) { + String[] parts = text.trim().split(":", 2); + if (parts.length != 2 || parts[1].isBlank()) { + errorLog.accept("requirements.yml: cannot understand '" + text.trim() + "'"); + return null; + } + String type = parts[0].trim().toLowerCase(Locale.ENGLISH); + String value = parts[1].trim(); + try { + switch (type) { + case "after": + return new Alternative(Type.AFTER, null, key(value), 0); + case "size": + return new Alternative(Type.SIZE, null, "", Integer.parseInt(value)); + case "never": + return new Alternative(Type.NEVER, null, value, 0); + default: + break; + } + int amount = 1; + int star = value.lastIndexOf('*'); + if (star > 0 && value.substring(star + 1).trim().matches("\\d+")) { + amount = Integer.parseInt(value.substring(star + 1).trim()); + value = value.substring(0, star).trim(); + } + for (Kind kind : Kind.values()) { + if (kind.label().equals(type)) { + return new Alternative(Type.RESOURCE, kind, value, amount); + } + } + } catch (NumberFormatException _) { + // Reported below + } + errorLog.accept("requirements.yml: cannot understand '" + text.trim() + "'"); + return null; + } + + /** + * @param advancement advancement key + * @return what it needs, or null if the file does not list it + */ + public List getNeeds(String advancement) { + return needs.get(advancement); + } + + /** + * @return rules that make things in the land count as other things + */ + public List getProvides() { + return provides; + } + + /** + * @return mobs that turn up in any box, however small + */ + public List getAlways() { + return always; + } + + /** + * @return the advancement that has to be earned before anything in the nether can be used + */ + public String getNetherAdvancement() { + return netherAdvancement; + } + + /** + * Adds what the rules say to a survey: the mobs that are always around, and the things + * that count as other things. + * @param survey survey of an area's land + */ + public void applyTo(LandSurvey survey) { + always.forEach(mob -> survey.add(Kind.ENTITY, mob, 1, 1)); + for (Provides rule : provides) { + int size = survey.sizeNeeded(rule.fromKind(), rule.fromNames(), 1); + if (size > 0) { + survey.add(rule.toKind(), rule.toName(), size, 1); + } + } + } +} diff --git a/src/main/resources/locales/en-US.yml b/src/main/resources/locales/en-US.yml index 744d0ca..9a06f5f 100755 --- a/src/main/resources/locales/en-US.yml +++ b/src/main/resources/locales/en-US.yml @@ -603,6 +603,12 @@ boxed: parameters: '[x z]' in-use: '&c There is a box in use there. Delete the box first.' success: '&a The land of the box position at [xyz] is being put back. See the console for when it is done.' + check: + description: play out how a box grows in an area and report where players get stuck + parameters: + started: '&a Surveying the land of [name]. This takes a few seconds...' + result: '&a [description]' + report: '&a The full report is in &e [file]' island: go: parameters: '[home number]' diff --git a/src/main/resources/requirements.yml b/src/main/resources/requirements.yml new file mode 100644 index 0000000..e38039b --- /dev/null +++ b/src/main/resources/requirements.yml @@ -0,0 +1,526 @@ +# What a player needs inside their box to earn each advancement that grows the box. +# /boxadmin areas check uses this to play out how a box grows in an area and to +# report where players get stuck and which advancements can never be earned there. +# +# This is a model, written by hand. It lists the raw resources an advancement comes down +# to, not every crafting step, and some entries are simplified. Correct it for your server. +# +# Each advancement has a list of needs, and all of them must be met. A need is one of: +# block: a block in the box, e.g. block:iron_ore|deepslate_iron_ore +# biome: a biome in the box +# entity: a mob in the land or brought by a structure, see 'provides' below +# structure: a structure from the area's structures file +# nether-block:, nether-biome:, nether-entity:, nether-structure: +# the same in the nether. These only count once the nether is open. +# after: another advancement earned first +# size: a box of at least this size +# never: cannot be done in Boxed +# set: every need in the named set under 'sets' +# Names can be separated by | to mean any of them, and can use * as a wildcard. +# Add * to ask for that many, e.g. block:iron_ore|deepslate_iron_ore*3 +# Put || between whole needs to mean either one will do. + +# The advancement that has to be earned before anything in the nether counts +nether-advancement: minecraft:story/enter_the_nether + +# Mobs that turn up in any box, however small +always: + - zombie + - skeleton + - spider + - creeper + - enderman + - witch + - slime + - phantom + - bat + - glow_squid + - wandering_trader + +# Things in the land that also count as something else. The mobs here are ones that spawn +# in a biome or come with a structure, which a survey of the land's blocks cannot see. +provides: + - structure:village/*/villagers/* -> entity:villager + - structure:village/*/zombie/villagers/* -> entity:zombie_villager + - structure:village/common/iron_golem -> entity:iron_golem + - structure:village/common/animals/cat_* -> entity:cat + - structure:village/common/animals/horses_* -> entity:horse + - structure:village/common/animals/cows_* -> entity:cow + - structure:village/common/animals/pigs_* -> entity:pig + - structure:village/common/animals/sheep_* -> entity:sheep + - structure:village/desert/camel_spawn -> entity:camel + - structure:boxed/frog -> entity:frog + - structure:boxed/parrot -> entity:parrot + - structure:boxed/axolotl -> entity:axolotl + - structure:boxed/polar_bear -> entity:polar_bear + - structure:boxed/pillager -> entity:pillager + - structure:boxed/allay -> entity:allay + - structure:boxed/bee -> entity:bee + - structure:pillager_outpost/* -> entity:pillager + - biome:swamp|mangrove_swamp -> entity:frog + - biome:jungle|sparse_jungle|bamboo_jungle -> entity:parrot + - biome:jungle|bamboo_jungle -> entity:ocelot + - biome:jungle|bamboo_jungle -> entity:panda + - biome:lush_caves -> entity:axolotl + - biome:*ocean|river -> entity:drowned + - biome:*ocean|river -> entity:cod + - biome:warm_ocean|lukewarm_ocean|deep_lukewarm_ocean -> entity:pufferfish + - biome:beach -> entity:turtle + - biome:frozen_peaks|jagged_peaks|snowy_slopes -> entity:goat + - biome:desert|snowy_plains|snowy_taiga|taiga|flower_forest|meadow|cherry_grove|grove -> entity:rabbit + - biome:forest|taiga|snowy_taiga|old_growth_pine_taiga|old_growth_spruce_taiga|grove|dark_forest -> entity:wolf + - biome:taiga|snowy_taiga|old_growth_pine_taiga|old_growth_spruce_taiga|grove -> entity:fox + - biome:savanna|savanna_plateau|windswept_savanna|plains|sunflower_plains -> entity:horse + - biome:plains|sunflower_plains|savanna|savanna_plateau|meadow -> entity:donkey + - biome:savanna*|windswept_*|jagged_peaks|meadow|cherry_grove -> entity:llama + - biome:savanna*|badlands|eroded_badlands|wooded_badlands -> entity:armadillo + - biome:mushroom_fields -> entity:mooshroom + - biome:snowy_plains|ice_spikes|frozen_ocean|deep_frozen_ocean -> entity:polar_bear + - block:bee_nest|beehive -> entity:bee + - block:short_grass|tall_grass -> entity:cow + - block:short_grass|tall_grass -> entity:sheep + - block:short_grass|tall_grass -> entity:pig + - block:short_grass|tall_grass -> entity:chicken + - nether-biome:nether_wastes|soul_sand_valley|basalt_deltas -> nether-entity:ghast + - nether-biome:nether_wastes|crimson_forest -> nether-entity:piglin + - nether-biome:crimson_forest -> nether-entity:hoglin + - nether-biome:basalt_deltas -> nether-entity:magma_cube + - nether-block:lava -> nether-entity:strider + - nether-structure:fortress/* -> nether-entity:blaze + - nether-structure:fortress/* -> nether-entity:wither_skeleton + - nether-structure:bastion/* -> nether-entity:piglin + +sets: + wood: + - block:*_log|*_stem + stone: + - block:stone|cobblestone|deepslate|cobbled_deepslate|blackstone + fuel: + - block:coal_ore|deepslate_coal_ore|*_log + iron: + - block:iron_ore|deepslate_iron_ore + gold: + - block:gold_ore|deepslate_gold_ore || nether-block:nether_gold_ore + copper: + - block:copper_ore|deepslate_copper_ore*3 + redstone: + - block:redstone_ore|deepslate_redstone_ore + leather: + - entity:cow|horse|donkey|llama|mooshroom|rabbit || nether-entity:hoglin + glass: + - block:sand|red_sand + villager: + - entity:villager + bees: + - block:bee_nest|beehive || entity:bee + ghast: + - nether-entity:ghast + fortress: + - nether-structure:fortress/* + crying-obsidian: + - block:crying_obsidian || nether-block:crying_obsidian || structure:ruined_portal/* || nether-entity:piglin + explore-nether: + - nether-biome:nether_wastes + - nether-biome:soul_sand_valley + - nether-biome:crimson_forest + - nether-biome:warped_forest + - nether-biome:basalt_deltas + # Every biome the vanilla "Adventuring Time" advancement asks for + adventuring-time: + - biome:badlands + - biome:bamboo_jungle + - biome:beach + - biome:birch_forest + - biome:cherry_grove + - biome:cold_ocean + - biome:dark_forest + - biome:deep_cold_ocean + - biome:deep_dark + - biome:deep_frozen_ocean + - biome:deep_lukewarm_ocean + - biome:deep_ocean + - biome:desert + - biome:dripstone_caves + - biome:eroded_badlands + - biome:flower_forest + - biome:forest + - biome:frozen_ocean + - biome:frozen_peaks + - biome:frozen_river + - biome:grove + - biome:ice_spikes + - biome:jagged_peaks + - biome:jungle + - biome:lukewarm_ocean + - biome:lush_caves + - biome:mangrove_swamp + - biome:meadow + - biome:mushroom_fields + - biome:ocean + - biome:old_growth_birch_forest + - biome:old_growth_pine_taiga + - biome:old_growth_spruce_taiga + - biome:pale_garden + - biome:plains + - biome:river + - biome:savanna + - biome:savanna_plateau + - biome:snowy_beach + - biome:snowy_plains + - biome:snowy_slopes + - biome:snowy_taiga + - biome:sparse_jungle + - biome:stony_peaks + - biome:stony_shore + - biome:sunflower_plains + - biome:swamp + - biome:taiga + - biome:warm_ocean + - biome:windswept_forest + - biome:windswept_gravelly_hills + - biome:windswept_hills + - biome:windswept_savanna + - biome:wooded_badlands + bred-all-animals: + - entity:cow + - entity:sheep + - entity:pig + - entity:chicken + - entity:horse + - entity:donkey + - entity:wolf + - entity:cat + - entity:ocelot + - entity:rabbit + - entity:llama + - entity:turtle + - entity:panda + - entity:fox + - entity:bee + - entity:goat + - entity:axolotl + - entity:frog + - entity:camel + - entity:armadillo + - entity:mooshroom + - nether-entity:hoglin + - nether-entity:strider + - block:sniffer_egg|suspicious_sand + +advancements: + # ---- Story ---- + story/mine_stone: + - set:wood + - set:stone + story/upgrade_tools: + - after:story/mine_stone + story/smelt_iron: + - after:story/upgrade_tools + - set:iron + - set:fuel + story/iron_tools: + - after:story/smelt_iron + - block:iron_ore|deepslate_iron_ore*3 + story/obtain_armor: + - after:story/smelt_iron + - block:iron_ore|deepslate_iron_ore*5 + story/deflect_arrow: + - after:story/smelt_iron + - entity:skeleton + story/lava_bucket: + - after:story/smelt_iron + - block:iron_ore|deepslate_iron_ore*3 + - block:lava + story/mine_diamond: + - after:story/iron_tools + - block:diamond_ore|deepslate_diamond_ore + story/form_obsidian: + # Picking up obsidian takes a diamond pickaxe, or a chest in a ruined portal + - block:lava + - block:water + - block:diamond_ore|deepslate_diamond_ore*3 || structure:ruined_portal/* + - after:story/iron_tools + story/shiny_gear: + - after:story/mine_diamond + - block:diamond_ore|deepslate_diamond_ore*5 + story/enchant_item: + - after:story/mine_diamond + - block:diamond_ore|deepslate_diamond_ore*5 + - block:lava + - block:water + - block:sugar_cane + - block:lapis_ore|deepslate_lapis_ore + - set:leather + story/enter_the_nether: + # A portal can be cast with a bucket, so no diamonds are needed + - after:story/lava_bucket + - block:water + - block:gravel || structure:ruined_portal/* + story/cure_zombie_villager: + - after:nether/brew_potion + - set:gold + - block:oak_leaves|dark_oak_leaves + - block:sugar_cane + - block:brown_mushroom + - entity:villager|zombie_villager + story/follow_ender_eye: + - never:strongholds are switched off in Boxed + story/enter_the_end: + - never:there is no End in Boxed + + # ---- Nether ---- + nether/return_to_sender: + - set:ghast + nether/find_bastion: + - nether-structure:bastion/* + nether/loot_bastion: + - nether-structure:bastion/* + nether/find_fortress: + - set:fortress + nether/obtain_blaze_rod: + - nether-entity:blaze + nether/get_wither_skull: + - nether-entity:wither_skeleton + nether/summon_wither: + - after:nether/get_wither_skull + - nether-block:soul_sand|soul_soil*4 + nether/brew_potion: + - after:nether/obtain_blaze_rod + - set:glass + nether/all_potions: + - after:nether/brew_potion + - nether-block:nether_wart + - set:redstone + - nether-block:glowstone + - set:gold + - block:sugar_cane + - block:brown_mushroom + - entity:pufferfish + - entity:turtle + - entity:rabbit + - entity:phantom + - nether-entity:magma_cube + - set:ghast + nether/all_effects: + - never:needs levitation from a shulker, and there is no End in Boxed + nether/create_beacon: + - after:nether/summon_wither + - set:glass + - block:lava + - block:water + - block:iron_ore|deepslate_iron_ore*81 + nether/create_full_beacon: + - after:nether/create_beacon + - block:iron_ore|deepslate_iron_ore*1476 + nether/charge_respawn_anchor: + - set:crying-obsidian + - nether-block:glowstone + nether/obtain_crying_obsidian: + - set:crying-obsidian + nether/distract_piglin: + - nether-entity:piglin + - set:gold + nether/explore_nether: + - set:explore-nether + nether/fast_travel: + - never:needs 7 km of travel in the overworld, which is more than a box can hold + nether/obtain_ancient_debris: + - after:story/mine_diamond + - nether-block:ancient_debris + nether/netherite_armor: + - after:story/shiny_gear + - nether-block:ancient_debris*16 + - block:diamond_ore|deepslate_diamond_ore*24 + - block:gold_ore|deepslate_gold_ore*16 || nether-block:nether_gold_ore*16 + nether/ride_strider: + - nether-entity:strider + - nether-biome:warped_forest + - set:leather + - set:iron + nether/ride_strider_in_overworld_lava: + - after:nether/ride_strider + - block:lava + nether/uneasy_alliance: + - set:ghast + nether/use_lodestone: + - after:story/smelt_iron + - set:redstone + + # ---- Adventure ---- + adventure/kill_a_mob: [] + adventure/kill_all_mobs: + - never:needs mobs from the End, and there is no End in Boxed + adventure/shoot_arrow: + - set:wood + - entity:spider + - entity:skeleton + adventure/sniper_duel: + - after:adventure/shoot_arrow + - size:25 + adventure/bullseye: + - after:adventure/shoot_arrow + - set:redstone + - size:15 + adventure/ol_betsy: + - after:story/smelt_iron + - entity:spider + adventure/whos_the_pillager_now: + - after:adventure/ol_betsy + - entity:pillager + adventure/two_birds_one_arrow: + - after:adventure/ol_betsy + - after:story/enchant_item + - entity:phantom + adventure/arbalistic: + - after:adventure/ol_betsy + - after:story/enchant_item + adventure/voluntary_exile: + - entity:pillager + adventure/hero_of_the_village: + - after:adventure/voluntary_exile + - set:villager + adventure/totem_of_undying: + # Evokers come with a raid + - after:adventure/hero_of_the_village + adventure/trade: + - entity:villager || block:emerald_ore|deepslate_emerald_ore + adventure/trade_at_world_height: + - after:adventure/trade + adventure/summon_iron_golem: + - block:iron_ore|deepslate_iron_ore*36 + - block:pumpkin|carved_pumpkin + - after:story/smelt_iron + adventure/sleep_in_bed: + - set:wood + - entity:sheep|spider + adventure/throw_trident: + - entity:drowned + adventure/very_very_frightening: + - after:adventure/throw_trident + - after:story/enchant_item + - set:villager + adventure/lightning_rod_with_villager_no_fire: + - set:copper + - set:villager + - after:story/smelt_iron + adventure/spyglass_at_parrot: + - set:copper + - block:amethyst_cluster + - entity:parrot + adventure/spyglass_at_ghast: + - set:copper + - block:amethyst_cluster + - set:ghast + adventure/spyglass_at_dragon: + - never:there is no End in Boxed + adventure/play_jukebox_in_meadows: + - biome:meadow + - after:story/mine_diamond + - entity:creeper + - entity:skeleton + adventure/walk_on_powder_snow_with_leather_boots: + - block:powder_snow + - set:leather + adventure/honey_block_slide: + - set:bees + - set:glass + adventure/avoid_vibration: + - block:sculk_sensor|sculk_shrieker + adventure/kill_mob_near_sculk_catalyst: + - block:sculk_catalyst + adventure/fall_from_world_height: + - after:story/lava_bucket + - block:water + adventure/adventuring_time: + - set:adventuring-time + + # ---- Husbandry ---- + husbandry/plant_seed: + - block:short_grass|tall_grass|wheat|pumpkin|melon|beetroots || nether-block:nether_wart + husbandry/breed_an_animal: + - entity:cow|sheep|pig|chicken|horse|wolf|cat|rabbit|llama|goat|frog|camel + husbandry/bred_all_animals: + - set:bred-all-animals + husbandry/tame_an_animal: + - entity:wolf|cat|horse|donkey|llama|parrot|camel + husbandry/balanced_diet: + - never:needs chorus fruit, and there is no End in Boxed + husbandry/fishy_business: + - block:water + - entity:spider + husbandry/tactical_fishing: + - after:story/lava_bucket + - entity:cod|pufferfish + husbandry/axolotl_in_a_bucket: + - after:story/lava_bucket + - entity:axolotl + husbandry/kill_axolotl_target: + - entity:axolotl + husbandry/tadpole_in_a_bucket: + - after:story/lava_bucket + - entity:frog + husbandry/leash_all_frog_variants: + - entity:frog + - entity:slime + - biome:swamp|plains|forest|river|beach|taiga|meadow + - biome:jungle|sparse_jungle|bamboo_jungle|desert|badlands|savanna|mangrove_swamp|warm_ocean + - biome:snowy_plains|snowy_taiga|ice_spikes|frozen_peaks|jagged_peaks|snowy_slopes|grove|frozen_river|frozen_ocean|deep_dark + husbandry/froglights: + - entity:frog + - nether-entity:magma_cube + - biome:swamp|plains|forest|river|beach|taiga|meadow + - biome:jungle|sparse_jungle|bamboo_jungle|desert|badlands|savanna|mangrove_swamp|warm_ocean + - biome:snowy_plains|snowy_taiga|ice_spikes|frozen_peaks|jagged_peaks|snowy_slopes|grove|frozen_river|frozen_ocean|deep_dark + husbandry/make_a_sign_glow: + - set:wood + - entity:glow_squid + husbandry/complete_catalogue: + # All eleven kinds of cat. Stray cats only turn up around villagers. + - entity:cat + - set:villager + husbandry/safely_harvest_honey: + - set:bees + - set:glass + husbandry/silk_touch_nest: + - set:bees + - after:story/enchant_item + husbandry/wax_on: + - set:bees + - block:copper_ore|deepslate_copper_ore*9 + husbandry/wax_off: + - after:husbandry/wax_on + husbandry/ride_a_boat_with_a_goat: + - entity:goat + - set:wood + husbandry/obtain_netherite_hoe: + - after:nether/obtain_ancient_debris + - nether-block:ancient_debris*4 + - block:gold_ore|deepslate_gold_ore*4 || nether-block:nether_gold_ore*4 + - block:diamond_ore|deepslate_diamond_ore*2 + husbandry/allay_deliver_item_to_player: + - entity:allay + husbandry/allay_deliver_cake_to_note_block: + - entity:allay + - set:wood + - set:redstone + - block:sugar_cane + - entity:cow + - entity:chicken + + # ---- End ---- + end/dragon_breath: + - never:there is no End in Boxed + end/dragon_egg: + - never:there is no End in Boxed + end/elytra: + - never:there is no End in Boxed + end/enter_end_gateway: + - never:there is no End in Boxed + end/find_end_city: + - never:there is no End in Boxed + end/kill_dragon: + - never:there is no End in Boxed + end/levitate: + - never:there is no End in Boxed + end/respawn_dragon: + - never:there is no End in Boxed diff --git a/src/test/java/world/bentobox/boxed/reach/GrowthSimulatorTest.java b/src/test/java/world/bentobox/boxed/reach/GrowthSimulatorTest.java new file mode 100644 index 0000000..5176d41 --- /dev/null +++ b/src/test/java/world/bentobox/boxed/reach/GrowthSimulatorTest.java @@ -0,0 +1,222 @@ +package world.bentobox.boxed.reach; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.util.Vector; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import world.bentobox.boxed.reach.GrowthSimulator.Blocked; +import world.bentobox.boxed.reach.GrowthSimulator.Earned; +import world.bentobox.boxed.reach.GrowthSimulator.Result; +import world.bentobox.boxed.reach.LandSurvey.Kind; +import world.bentobox.boxed.reach.Requirements.Alternative; +import world.bentobox.boxed.reach.Requirements.Type; + +/** + * Tests the land survey, the requirements file and the growth simulation together. + */ +class GrowthSimulatorTest { + + private static final String YAML = """ + always: + - zombie + provides: + - structure:village/*/villagers/* -> entity:villager + - nether-biome:nether_wastes -> nether-entity:ghast + sets: + wood: + - block:*_log + iron: + - block:iron_ore|deepslate_iron_ore*3 + advancements: + story/mine_stone: + - set:wood + - block:stone + story/smelt_iron: + - after:story/mine_stone + - set:iron + story/enter_the_nether: + - after:story/smelt_iron + - block:lava || structure:ruined_portal/* + nether/return_to_sender: + - nether-entity:ghast + adventure/trade: + - entity:villager + adventure/sniper_duel: + - size:25 + story/mine_diamond: + - block:diamond_ore + end/kill_dragon: + - never:there is no End + end/dragon_egg: + - after:end/kill_dragon + adventure/kill_a_mob: [] + """; + + private LandSurvey survey; + private Requirements requirements; + private List errors; + + @BeforeEach + void setUp() throws Exception { + errors = new ArrayList<>(); + YamlConfiguration config = new YamlConfiguration(); + config.loadFromString(YAML); + requirements = new Requirements(config, errors::add); + survey = new LandSurvey(100); + // A tree and stone at the start, iron a little further out, lava further still + survey.add(Kind.BLOCK, "oak_log", 1, 4); + survey.add(Kind.BLOCK, "stone", 1, 50); + survey.add(Kind.BLOCK, "iron_ore", 3, 2); + survey.add(Kind.BLOCK, "deepslate_iron_ore", 5, 1); + survey.add(Kind.BLOCK, "lava", 12, 1); + survey.add(Kind.NETHER_BIOME, "nether_wastes", 2, 1); + survey.add(Kind.STRUCTURE, "village/plains/villagers/unemployed", 40, 1); + // Diamonds are beyond the edge of the land, so they are not recorded + survey.add(Kind.BLOCK, "diamond_ore", 150, 1); + requirements.applyTo(survey); + } + + @Test + void testSizeFor() { + // A box of size 1 covers blocks -1 and 0 + assertEquals(1, LandSurvey.sizeFor(0, 0)); + assertEquals(1, LandSurvey.sizeFor(-1, -1)); + assertEquals(2, LandSurvey.sizeFor(1, 0)); + assertEquals(2, LandSurvey.sizeFor(0, -2)); + assertEquals(10, LandSurvey.sizeFor(-3, 9)); + } + + @Test + void testSurveyCountsAndWildcards() { + assertEquals(2, survey.count(Kind.BLOCK, "iron_ore|deepslate_iron_ore", 4)); + assertEquals(3, survey.count(Kind.BLOCK, "*iron_ore", 5)); + assertEquals(5, survey.sizeNeeded(Kind.BLOCK, "iron_ore|deepslate_iron_ore", 3)); + assertEquals(-1, survey.sizeNeeded(Kind.BLOCK, "iron_ore", 3)); + assertEquals(-1, survey.sizeNeeded(Kind.BLOCK, "diamond_ore", 1)); + assertEquals(1, survey.firstSizes(Kind.BLOCK).get("oak_log")); + } + + @Test + void testRulesAreApplied() { + // Always around, and brought by a structure or a biome + assertEquals(1, survey.sizeNeeded(Kind.ENTITY, "zombie", 1)); + assertEquals(40, survey.sizeNeeded(Kind.ENTITY, "villager", 1)); + assertEquals(2, survey.sizeNeeded(Kind.NETHER_ENTITY, "ghast", 1)); + } + + @Test + void testBlueprintBlocksAreCounted() { + LandSurvey s = new LandSurvey(10); + s.addBlueprint(Map.of(new Vector(0, 60, -1), "minecraft:oak_log[axis=y]", new Vector(1, 61, 0), "minecraft:air")); + assertEquals(1, s.sizeNeeded(Kind.BLOCK, "oak_log", 1)); + assertEquals(1, s.firstSizes(Kind.BLOCK).size()); + } + + @Test + void testStructuresFile() throws Exception { + YamlConfiguration structures = new YamlConfiguration(); + structures.loadFromString("normal:\n -38,63,20: ruined_portal/portal_5\n 0,64,80: village/x,CLOCKWISE_90\n"); + LandSurvey s = new LandSurvey(100); + s.addStructures(structures.getConfigurationSection("normal"), false); + s.addStructures(null, true); + assertEquals(38, s.sizeNeeded(Kind.STRUCTURE, "ruined_portal/*", 1)); + assertEquals(81, s.sizeNeeded(Kind.STRUCTURE, "village/x", 1)); + } + + @Test + void testRequirementsAreRead() { + assertTrue(errors.isEmpty(), errors.toString()); + assertEquals(2, requirements.getNeeds("minecraft:story/mine_stone").size()); + assertEquals(new Alternative(Type.RESOURCE, Kind.BLOCK, "iron_ore|deepslate_iron_ore", 3), + requirements.getNeeds("minecraft:story/smelt_iron").get(1).alternatives().get(0)); + assertEquals(2, requirements.getNeeds("minecraft:story/enter_the_nether").get(1).alternatives().size()); + assertTrue(requirements.getNeeds("minecraft:adventure/kill_a_mob").isEmpty()); + assertNull(requirements.getNeeds("minecraft:story/unknown")); + } + + @Test + void testBadLinesAreReported() { + assertNull(Requirements.alternative("nonsense", errors::add)); + assertNull(Requirements.alternative("rock:stone", errors::add)); + assertNull(Requirements.alternative("size:big", errors::add)); + assertEquals(3, errors.size()); + } + + @Test + void testGrowth() { + Map scores = Map.of("minecraft:story/mine_stone", 2, "minecraft:story/smelt_iron", 3, + "minecraft:story/enter_the_nether", 6, "minecraft:nether/return_to_sender", 1, + "minecraft:adventure/trade", 8, "minecraft:adventure/sniper_duel", 5, + "minecraft:story/mine_diamond", 6, "minecraft:end/kill_dragon", 2, "minecraft:end/dragon_egg", 2, + "minecraft:story/not_in_file", 4); + // kill_a_mob scores nothing here, so it is left out + Result result = new GrowthSimulator(survey, requirements, scores, 1).run(); + + // 1 -> mine_stone -> 3: only two iron in reach, so the box stops there + assertEquals(List.of("minecraft:story/mine_stone"), result.earned().stream().map(Earned::advancement).toList()); + assertEquals(3, result.finalSize()); + assertFalse(result.filledLand()); + assertEquals(List.of("minecraft:story/not_in_file"), result.unlisted()); + + Map blocked = new java.util.HashMap<>(); + result.blocked().forEach(b -> blocked.put(b.advancement(), b)); + // Iron is there, just further out + assertFalse(blocked.get("minecraft:story/smelt_iron").impossible()); + assertTrue(blocked.get("minecraft:story/smelt_iron").missing().get(0).contains("first at size 5")); + assertFalse(blocked.get("minecraft:adventure/sniper_duel").impossible()); + // Diamonds are not in the land, and the End does not exist, nor does anything after it + assertTrue(blocked.get("minecraft:story/mine_diamond").impossible()); + assertTrue(blocked.get("minecraft:end/kill_dragon").impossible()); + assertTrue(blocked.get("minecraft:end/dragon_egg").impossible()); + assertTrue(ReachReport.summary(result).startsWith("The box stops growing at size 3 of 100.")); + } + + @Test + void testGrowthWithEnoughIron() { + survey.add(Kind.BLOCK, "iron_ore", 2, 1); + Map scores = Map.of("minecraft:story/mine_stone", 2, "minecraft:story/smelt_iron", 10, + "minecraft:story/enter_the_nether", 30, "minecraft:nether/return_to_sender", 1, + "minecraft:adventure/trade", 60, "minecraft:adventure/sniper_duel", 5); + Result result = new GrowthSimulator(survey, requirements, scores, 1).run(); + // 1 -> 3 -> 13 (lava at 12) -> 43 (ghast, villager at 40, size 25) -> past the edge of the land + assertEquals(6, result.earned().size()); + assertEquals(100, result.finalSize()); + assertTrue(result.filledLand()); + assertTrue(result.blocked().isEmpty()); + // The nether resource only counted once the nether was open + assertEquals(4, result.earned().stream().filter(e -> e.advancement().endsWith("return_to_sender")).findFirst() + .orElseThrow().round()); + List report = ReachReport.lines("test", survey, result); + assertTrue(report.contains("Round 4, box size 43:")); + assertTrue(report.stream().anyMatch(l -> l.contains("entity: box size at which each first appears"))); + } + + /** + * The requirements file that ships with Boxed can be read without complaints. + */ + @Test + void testShippedRequirementsFile() { + YamlConfiguration config = YamlConfiguration.loadConfiguration(new java.io.File("src/main/resources/requirements.yml")); + List problems = new ArrayList<>(); + Requirements shipped = new Requirements(config, problems::add); + assertTrue(problems.isEmpty(), problems.toString()); + // Every advancement that scores has an entry + YamlConfiguration adv = YamlConfiguration.loadConfiguration(new java.io.File("src/main/resources/advancements.yml")); + for (String key : adv.getConfigurationSection("advancements").getKeys(false)) { + if (adv.getInt("advancements." + key) > 0) { + assertNotNull(shipped.getNeeds("minecraft:" + key), key + " is missing from requirements.yml"); + } + } + } +}