diff --git a/CLAUDE.md b/CLAUDE.md index 22087e8..a76be29 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -50,7 +50,7 @@ Never hold the whole region in memory or load the seed world on a normal boot `generators/biomes/BiomeLayout` reads one dimension of a biomes file and answers "which chosen biome is at dx,dz from the middle" (null = the seed's own). It supports per-quarter lists, `rings`, random `patches`, and `blend` (noise that bends the edges). `AbstractSeedBiomeProvider` only adds the centres and the vanilla fallback. `biomes.yml` is the "original" style; `biomes/*.yml` are the others (`workshop/BiomeStyles` maps names to files). With `blend: 0` the original layout must stay exactly as it was, because existing areas depend on it. -`workshop/WorkshopManager` runs the one workshop: temporary worlds `/workshop` and `/workshop_nether` (folders inside the game world's folder, like seed worlds) made with the seed generator, peaceful, spawn limits 0. Its state (`workshop/Workshop`: seed, biomes file, source area, centres, the players inside and the game mode each had outside) is saved to `areas/workshop.yml` on every change and reloaded, with the worlds, in `onEnable`. `listeners/WorkshopListener` forces creative on entry, restores the game mode on exit, respawns in place, and sends players home if the workshop was discarded while they were offline (`areas/displaced.yml`). `/boxadmin areas edit` (`AdminAreasEditCommand`) holds the logic and can be typed; `WorkshopDialogs` is only the Paper dialog UI on top, and cannot be unit tested under MockBukkit. Still to build: spot scanning in the workshop, choosing the centre, structure logging and turning the workshop into an area without a restart. +`workshop/WorkshopManager` runs the one workshop: temporary worlds `/workshop` and `/workshop_nether` (folders inside the game world's folder, like seed worlds) made with the seed generator, peaceful, spawn limits 0. Its state (`workshop/Workshop`: seed, biomes file, source area, centres, the players inside and the game mode each had outside) is saved to `areas/workshop.yml` on every change and reloaded, with the worlds, in `onEnable`. `listeners/WorkshopListener` forces creative on entry, restores the game mode on exit, respawns in place, and sends players home if the workshop was discarded while they were offline (`areas/displaced.yml`). `/boxadmin areas edit` (`AdminAreasEditCommand`) holds the logic and can be typed; `WorkshopDialogs` is only the Paper dialog UI on top, and cannot be unit tested under MockBukkit. When the workshop overworld is made, `WorkshopManager.scan` searches the vanilla biomes (`reach/SpotFinder`), stores the candidates as unscored `Workshop.Spot`s, calls `setCentres` with all of them (spot 0 is always the starting centre; the others are kept `4 * area radius` from it so layouts do not overlap) and scores them one at a time with `reach/SpotScorer` (shared with the find command). The spot list is saved after each score and the scan resumes after a restart; the centres must be set again before the world is created or new chunks would get the wrong biomes. `/boxadmin areas spots` (`AdminAreasSpotsCommand`) lists them and `select` sets `Workshop.setCentre`, teleports, and `showCentre` sends a fake diamond block and a per-player `WorldBorder`. Still to build: structure logging and turning the workshop into an area without a restart, then the Nether and End spots. ### Deleted boxes diff --git a/README.md b/README.md index 55eafd7..0c276b6 100644 --- a/README.md +++ b/README.md @@ -78,7 +78,7 @@ You can also do the same by hand: add the area to `areas.yml` and make a bluepri | `/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, centres 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). | -| `/boxadmin areas find [seed\|random] [radius]` | Looks through a seed for good places to start a box. See [Finding a good place to start](#finding-a-good-place-to-start). | +| `boxadmin areas find [seed\|random] [radius]` | Console only. Looks through a seed for good places to start a box. See [Finding a good place to start](#finding-a-good-place-to-start). | | `/boxadmin areas edit` | Opens the area workshop, where a new area is tried out in a temporary world. See [The area workshop](#the-area-workshop). | 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: @@ -168,6 +168,8 @@ An advancement that scores points but can never be earned is worth either removi ### Finding a good place to start +**The easy way is [the area workshop](#the-area-workshop)**, which searches by itself and lets you go and look at each place. The command described here does the same search from the console and only writes a report. + Every box in an area is a copy of the land around one place in the area's seed. By default that place is 0,0, so whether new players start in a forest or in the sea depends on the seed. `/boxadmin areas find [seed|random] [radius]` finds better places for you: * with no seed it searches the seed the area already has, so you can see how the current place compares, @@ -202,7 +204,7 @@ A good start does not mean the area can be finished. Run `/boxadmin areas check ### The area workshop -The workshop is a set of temporary worlds for trying out a seed and a biome style before they become an area. **It is not finished yet:** today it makes the worlds and lets you look around and build in them. Picking the middle of the box, placing structures and turning the result into an area are still to come. +The workshop is a set of temporary worlds for trying out a seed and a biome style before they become an area. **It is not finished yet:** today it makes the worlds, finds good places to start and lets you pick one as the middle of the box. Placing structures and turning the result into an area are still to come. Run `/boxadmin areas edit`. A dialog box asks for: @@ -217,6 +219,33 @@ You are then taken to the temporary world. While you are there: * You can leave and come back. The workshop, and everything built in it, stays until you discard it, including over a server restart. There is one workshop at a time, and other admins can join it. * If you start from an existing area without changing its seed or biome style, the workshop starts as a copy of the land that area was built from, so changes made to it by hand are kept. +#### Picking the middle of the box + +As soon as the world is made, Boxed starts looking through the seed for good places to start a box, in the same way as `/boxadmin areas find`. It looks for wooded, dry land with water a short walk away and no mountains within about 130 blocks, so that a new player can see what there is to reach. You can fly around while it works. You are told in chat when the first place is ready and when the search has finished. In between, progress is shown above the hotbar. The first ones arrive within a few seconds and there are up to thirteen. + +Press **F** (the swap hands key), click the message, or run `/boxadmin areas spots`, to see the places as numbered buttons with their coordinates and scores. Hover over a button to see what the score is made of. The first place is always where the workshop started: 0,0, or the middle of the area you started from. + +Clicking a button: + +* takes you there, on the ground under any trees, +* makes it the middle of every box, +* puts a diamond block under your feet to mark it, and +* sets a world border that shows how far a box can grow. + +Only you see the diamond block and the border, and neither changes the world. The border also stops you flying out, so hide it with the button in the dialog or `/boxadmin areas spots border` when you want to look further afield. You can pick another place at any time. + +The biome style is laid out around every place that was found, so each one looks exactly as a box there will look. This is why you pick from the places found and cannot use just anywhere: biomes are fixed when land is generated. + +| Command | Description | +|---------|-------------| +| `/boxadmin areas spots` | Shows the places found so far. | +| `/boxadmin areas spots ` | Picks a place and takes you there. | +| `/boxadmin areas spots border` | Shows or hides the border. | + +The permission is `boxed.admin.areas.spots`. + +#### Coming back and discarding + Run `/boxadmin areas edit` again to go back to it, go to its Nether, or discard it. Discarding sends everyone inside to their box (or to spawn if they have none) and deletes the temporary worlds. Players who were inside but offline are sent to their box when they next join. Everything can also be typed, which is the only way from the console: diff --git a/src/main/java/world/bentobox/boxed/commands/AdminAreasCommand.java b/src/main/java/world/bentobox/boxed/commands/AdminAreasCommand.java index 3dc9709..6870f4e 100644 --- a/src/main/java/world/bentobox/boxed/commands/AdminAreasCommand.java +++ b/src/main/java/world/bentobox/boxed/commands/AdminAreasCommand.java @@ -72,6 +72,7 @@ public void setup() { new Check(this); new AdminAreasFindCommand(this); new AdminAreasEditCommand(this); + new AdminAreasSpotsCommand(this); } @Override @@ -100,6 +101,22 @@ public boolean execute(User user, String label, List args) { return true; } + /** + * Works out which parameter of a command is being typed. BentoBox gives tab completion + * everything typed after the top command, so the labels of the commands on the way down + * (for example "areas" and "find") come before the parameters. + * @param command the command being completed + * @param args everything typed after the top command + * @return 1 for the first parameter, 2 for the second and so on + */ + static int parameter(CompositeCommand command, List args) { + int labels = 0; + for (CompositeCommand c = command; c.getParent() != null; c = c.getParent()) { + labels++; + } + return args.size() - labels; + } + private static Optional> areaNames(Boxed addon, List args) { if (args.isEmpty()) { return Optional.empty(); @@ -316,8 +333,8 @@ public boolean execute(User user, String label, List args) { @Override public Optional> tabComplete(User user, String alias, List args) { - if (args.size() == 2) { - return Optional.of(Util.tabLimit(List.of(REGENERATE), args.get(1))); + if (parameter(this, args) == 2) { + return Optional.of(Util.tabLimit(List.of(REGENERATE), args.get(args.size() - 1))); } return areaNames(getAddon(), args); } diff --git a/src/main/java/world/bentobox/boxed/commands/AdminAreasEditCommand.java b/src/main/java/world/bentobox/boxed/commands/AdminAreasEditCommand.java index 9dfe5c2..3f039e5 100644 --- a/src/main/java/world/bentobox/boxed/commands/AdminAreasEditCommand.java +++ b/src/main/java/world/bentobox/boxed/commands/AdminAreasEditCommand.java @@ -213,7 +213,7 @@ boolean go(User user, Environment env) { if (error != null || !Boolean.TRUE.equals(ok)) { user.sendMessage(FAILED); } else { - user.sendMessage(PREFIX + "welcome"); + user.sendMessage(PREFIX + "welcome", TextVariables.LABEL, getTopLabel()); } }); return true; @@ -238,21 +238,22 @@ boolean discard(User user) { public Optional> tabComplete(User user, String alias, List args) { Boxed addon = getAddon(); String last = args.isEmpty() ? "" : args.get(args.size() - 1); - // The first argument is this command's own label List options = new ArrayList<>(); - String sub = args.size() > 2 ? args.get(1).toLowerCase(Locale.ENGLISH) : ""; - if (args.size() <= 2) { + int parameter = AdminAreasCommand.parameter(this, args); + // The first parameter says what to do, and the rest depend on it + String sub = parameter > 1 ? args.get(args.size() - parameter).toLowerCase(Locale.ENGLISH) : ""; + if (parameter <= 1) { options.addAll(List.of(START, GO, DISCARD)); - } else if (sub.equals(START) && args.size() == 3) { + } else if (sub.equals(START) && parameter == 2) { options.addAll(List.of(RANDOM, SAME)); - } else if (sub.equals(START) && args.size() == 4) { + } else if (sub.equals(START) && parameter == 3) { options.add(SAME); options.addAll(BiomeStyles.list(addon.getDataFolder())); - } else if (sub.equals(START) && args.size() == 5) { + } else if (sub.equals(START) && parameter == 4) { addon.getAreas().getAreas().forEach(a -> options.add(a.id())); - } else if (sub.equals(GO) && args.size() == 3) { + } else if (sub.equals(GO) && parameter == 2) { options.add(NETHER); - } else if (sub.equals(DISCARD) && args.size() == 3) { + } else if (sub.equals(DISCARD) && parameter == 2) { options.add(CONFIRM); } return Optional.of(Util.tabLimit(options, last)); diff --git a/src/main/java/world/bentobox/boxed/commands/AdminAreasFindCommand.java b/src/main/java/world/bentobox/boxed/commands/AdminAreasFindCommand.java index 7fb3976..c665c66 100644 --- a/src/main/java/world/bentobox/boxed/commands/AdminAreasFindCommand.java +++ b/src/main/java/world/bentobox/boxed/commands/AdminAreasFindCommand.java @@ -42,6 +42,7 @@ import world.bentobox.boxed.generators.chunks.BoxedSeedChunkGenerator; import world.bentobox.boxed.reach.FortressSpot; import world.bentobox.boxed.reach.SpotFinder; +import world.bentobox.boxed.reach.SpotScorer; import world.bentobox.boxed.reach.SpotFinder.Candidate; import world.bentobox.boxed.reach.SpotSurvey; @@ -152,40 +153,14 @@ private void survey(int index) { return; } Candidate spot = spots.get(index); - int reach = SpotSurvey.RADIUS >> 4; - int chunkX = spot.x() >> 4; - int chunkZ = spot.z() >> 4; - List> chunks = new ArrayList<>(); - for (int x = -reach; x < reach; x++) { - for (int z = -reach; z < reach; z++) { - chunks.add(world.getChunkAtAsync(chunkX + x, chunkZ + z)); - } - } - CompletableFuture.allOf(chunks.toArray(CompletableFuture[]::new)).whenComplete((v, error) -> - // Chunks have to be read on the main thread - Bukkit.getScheduler().runTask(getPlugin(), () -> { + SpotScorer.score(getPlugin(), world, spot.x(), spot.z(), true).whenComplete((score, error) -> { if (error != null) { getAddon().logError("Could not generate the land at " + spot.x() + "," + spot.z() + ": " + error); - survey(index + 1); - return; + } else { + scored.add(new Scored(spot, score)); } - List snapshots = new ArrayList<>(); - for (CompletableFuture chunk : chunks) { - Chunk c = chunk.join(); - snapshots.add(c.getChunkSnapshot(true, false, false)); - world.unloadChunk(c.getX(), c.getZ(), false); - } - int minY = world.getMinHeight(); - Bukkit.getScheduler().runTaskAsynchronously(getPlugin(), () -> { - SpotSurvey spotSurvey = new SpotSurvey(); - snapshots.forEach(s -> spotSurvey.add(s, (s.getX() - chunkX) << 4, (s.getZ() - chunkZ) << 4, minY)); - SpotSurvey.Score score = spotSurvey.score(); - Bukkit.getScheduler().runTask(getPlugin(), () -> { - scored.add(new Scored(spot, score)); - survey(index + 1); - }); - }); - })); + survey(index + 1); + }); } /** @@ -456,7 +431,8 @@ public AdminAreasFindCommand(CompositeCommand parent) { @Override public void setup() { this.setPermission("admin.areas.find"); - this.setOnlyPlayer(false); + // Players use the area workshop, which searches by itself and lets them go and look + this.setOnlyConsole(true); this.setParametersHelp(PREFIX + "parameters"); this.setDescription(PREFIX + "description"); } @@ -507,10 +483,11 @@ public boolean execute(User user, String label, List args) { @Override public Optional> tabComplete(User user, String alias, List args) { - if (args.size() == 3) { - return Optional.of(Util.tabLimit(List.of(RANDOM), args.get(2))); + int parameter = AdminAreasCommand.parameter(this, args); + if (parameter == 2) { + return Optional.of(Util.tabLimit(List.of(RANDOM), args.get(args.size() - 1))); } - if (args.size() > 3) { + if (parameter > 2) { return Optional.empty(); } return Optional.of(Util.tabLimit(this.getAddon().getAreas().getAreas().stream().map(Area::id).toList(), diff --git a/src/main/java/world/bentobox/boxed/commands/AdminAreasSpotsCommand.java b/src/main/java/world/bentobox/boxed/commands/AdminAreasSpotsCommand.java new file mode 100644 index 0000000..0f71567 --- /dev/null +++ b/src/main/java/world/bentobox/boxed/commands/AdminAreasSpotsCommand.java @@ -0,0 +1,159 @@ +package world.bentobox.boxed.commands; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import org.bukkit.World.Environment; + +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.util.Util; +import world.bentobox.boxed.Boxed; +import world.bentobox.boxed.workshop.Workshop; +import world.bentobox.boxed.workshop.WorkshopManager; + +/** + * Shows the places the workshop has found that could be the middle of every box, and makes + * one of them the middle. Players get a dialog box of buttons; the places can also be + * listed and picked by typing. + * + * @author tastybento + */ +public class AdminAreasSpotsCommand extends CompositeCommand { + + private static final String PREFIX = "boxed.commands.boxadmin.areas.spots."; + private static final String BORDER = "border"; + + /** + * @param parent the areas command + */ + public AdminAreasSpotsCommand(CompositeCommand parent) { + super(parent, "spots"); + } + + @Override + public void setup() { + this.setPermission("admin.areas.spots"); + this.setOnlyPlayer(false); + this.setParametersHelp(PREFIX + "parameters"); + this.setDescription(PREFIX + "description"); + } + + @Override + public boolean execute(User user, String label, List args) { + WorkshopManager manager = this.getAddon().getWorkshop(); + Optional workshop = manager.get(); + if (workshop.isEmpty()) { + user.sendMessage("boxed.commands.boxadmin.areas.edit.none", TextVariables.LABEL, getTopLabel()); + return false; + } + if (args.size() > 1) { + this.showHelp(this, user); + return false; + } + if (args.isEmpty()) { + show(user, workshop.get()); + return true; + } + if (!user.isPlayer()) { + user.sendMessage("general.errors.use-in-game"); + return false; + } + if (BORDER.equalsIgnoreCase(args.get(0))) { + return border(user); + } + if (!Util.isInteger(args.get(0), true)) { + this.showHelp(this, user); + return false; + } + return select(user, Integer.parseInt(args.get(0))); + } + + /** + * Shows the places found so far: buttons for a player, a list for the console. + */ + private void show(User user, Workshop workshop) { + List spots = workshop.getSpots(); + if (spots.stream().noneMatch(Workshop.Spot::scored)) { + user.sendMessage(PREFIX + "looking"); + return; + } + if (user.isPlayer()) { + WorkshopDialogs.showSpots(getPlugin(), user, workshop, number -> select(user, number), () -> border(user)); + return; + } + int[] centre = workshop.getCentre(Environment.NORMAL); + for (int i = 0; i < spots.size(); i++) { + Workshop.Spot spot = spots.get(i); + if (spot.scored()) { + boolean picked = workshop.hasCentre(Environment.NORMAL) && spot.x() == centre[0] && spot.z() == centre[1]; + user.sendMessage(PREFIX + (picked ? "entry-picked" : "entry"), TextVariables.NUMBER, + String.valueOf(i + 1), TextVariables.XYZ, spot.x() + "," + spot.z(), "[score]", + String.valueOf(spot.score()), "[biome]", spot.biome(), TextVariables.DESCRIPTION, + spot.description()); + } + } + long waiting = spots.stream().filter(s -> !s.scored()).count(); + if (waiting > 0) { + user.sendMessage(PREFIX + "more-coming", TextVariables.NUMBER, String.valueOf(waiting)); + } + } + + /** + * Makes a place the middle of every box and takes the player there. + * @param user a player + * @param number the place's number, counting from 1 + * @return true if there is such a place + */ + boolean select(User user, int number) { + WorkshopManager manager = this.getAddon().getWorkshop(); + List spots = manager.get().map(Workshop::getSpots).orElse(List.of()); + if (number < 1 || number > spots.size() || !spots.get(number - 1).scored()) { + user.sendMessage(PREFIX + "unknown"); + return false; + } + Workshop.Spot spot = spots.get(number - 1); + manager.select(user.getPlayer(), number - 1).whenComplete((ok, error) -> { + if (error != null || !Boolean.TRUE.equals(ok)) { + user.sendMessage("boxed.commands.boxadmin.areas.edit.failed"); + } else { + user.sendMessage(PREFIX + "selected", TextVariables.NUMBER, String.valueOf(number), TextVariables.XYZ, + spot.x() + "," + spot.z(), TextVariables.LABEL, getTopLabel()); + } + }); + return true; + } + + /** + * Shows or hides the border that marks how far the box can reach. + */ + boolean border(User user) { + boolean show = user.getPlayer().getWorldBorder() == null; + this.getAddon().getWorkshop().showCentre(user.getPlayer(), show); + boolean shown = user.getPlayer().getWorldBorder() != null; + if (show && !shown) { + user.sendMessage(PREFIX + "no-centre"); + return false; + } + user.sendMessage(PREFIX + (shown ? "border-on" : "border-off")); + return true; + } + + @Override + public Optional> tabComplete(User user, String alias, List args) { + if (AdminAreasCommand.parameter(this, args) > 1) { + return Optional.empty(); + } + List options = new ArrayList<>(); + options.add(BORDER); + List spots = this.getAddon().getWorkshop().get().map(Workshop::getSpots).orElse(List.of()); + for (int i = 0; i < spots.size(); i++) { + if (spots.get(i).scored()) { + options.add(String.valueOf(i + 1)); + } + } + return Optional.of(Util.tabLimit(options, args.isEmpty() ? "" : args.get(args.size() - 1))); + } +} diff --git a/src/main/java/world/bentobox/boxed/commands/WorkshopDialogs.java b/src/main/java/world/bentobox/boxed/commands/WorkshopDialogs.java index db38a75..9cef14f 100644 --- a/src/main/java/world/bentobox/boxed/commands/WorkshopDialogs.java +++ b/src/main/java/world/bentobox/boxed/commands/WorkshopDialogs.java @@ -4,9 +4,11 @@ import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; +import java.util.function.IntConsumer; import org.bukkit.Bukkit; import org.bukkit.World.Environment; +import org.bukkit.plugin.Plugin; import io.papermc.paper.dialog.Dialog; import io.papermc.paper.dialog.DialogResponseView; @@ -19,6 +21,7 @@ import io.papermc.paper.registry.data.dialog.type.DialogType; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.event.ClickCallback; +import world.bentobox.bentobox.api.localization.TextVariables; import world.bentobox.bentobox.api.user.User; import world.bentobox.boxed.Boxed; import world.bentobox.boxed.areas.Area; @@ -34,6 +37,9 @@ final class WorkshopDialogs { private static final String PREFIX = "boxed.commands.boxadmin.areas.edit.dialog."; + private static final String SPOTS = "boxed.commands.boxadmin.areas.spots.dialog."; + private static final String BORDER = "border"; + private static final String[] NO_VARIABLES = {}; private static final String SEED = "seed"; private static final String STYLE = "style"; private static final String AREA = "area"; @@ -51,10 +57,52 @@ private static Component text(User user, String key, String... variables) { } private ActionButton button(User user, String key, Consumer action) { + return button(command.getPlugin(), text(user, key), null, action); + } + + private static ActionButton button(Plugin plugin, Component label, Component tooltip, + Consumer action) { // What a button does is run on the main thread, whichever thread the click arrives on - return ActionButton.builder(text(user, key)).action(DialogAction.customClick( - (view, audience) -> Bukkit.getScheduler().runTask(command.getPlugin(), () -> action.accept(view)), - ONCE)).build(); + ActionButton.Builder builder = ActionButton.builder(label).action(DialogAction.customClick( + (view, audience) -> Bukkit.getScheduler().runTask(plugin, () -> action.accept(view)), ONCE)); + return tooltip == null ? builder.build() : builder.tooltip(tooltip).build(); + } + + /** + * Shows the places found so far as numbered buttons. Clicking one makes it the middle of + * every box and takes the player there. + * @param plugin plugin to schedule with + * @param user a player + * @param workshop the area being worked on + * @param select what to do with the number of the place that is clicked, counting from 1 + * @param border what to do when the border button is clicked + */ + static void showSpots(Plugin plugin, User user, Workshop workshop, IntConsumer select, Runnable border) { + List spots = workshop.getSpots(); + int[] centre = workshop.getCentre(Environment.NORMAL); + List buttons = new ArrayList<>(); + for (int i = 0; i < spots.size(); i++) { + Workshop.Spot spot = spots.get(i); + if (!spot.scored()) { + continue; + } + int number = i + 1; + boolean picked = workshop.hasCentre(Environment.NORMAL) && spot.x() == centre[0] && spot.z() == centre[1]; + String[] variables = { TextVariables.NUMBER, String.valueOf(number), TextVariables.XYZ, + spot.x() + "," + spot.z(), "[score]", String.valueOf(spot.score()), "[biome]", spot.biome(), + TextVariables.DESCRIPTION, spot.description() }; + buttons.add(button(plugin, user.getTranslationAsComponent(SPOTS + (picked ? "button-picked" : "button"), variables), + user.getTranslationAsComponent(SPOTS + "tooltip", variables), view -> select.accept(number))); + } + buttons.add(button(plugin, user.getTranslationAsComponent(SPOTS + BORDER, NO_VARIABLES), null, view -> border.run())); + long waiting = spots.stream().filter(s -> !s.scored()).count(); + DialogBase base = DialogBase.builder(user.getTranslationAsComponent(SPOTS + "title", NO_VARIABLES)).canCloseWithEscape(true) + .body(List.of(DialogBody.plainMessage(user.getTranslationAsComponent( + SPOTS + (waiting > 0 ? "body-looking" : "body"), TextVariables.NUMBER, String.valueOf(waiting))))) + .build(); + user.getPlayer().showDialog(Dialog.create(b -> b.empty().base(base).type(DialogType.multiAction(buttons) + .exitAction(ActionButton.builder(user.getTranslationAsComponent(SPOTS + "close", NO_VARIABLES)).build()).columns(2) + .build()))); } private static ActionButton close(User user, String key) { diff --git a/src/main/java/world/bentobox/boxed/listeners/WorkshopListener.java b/src/main/java/world/bentobox/boxed/listeners/WorkshopListener.java index 1f4201f..5839822 100644 --- a/src/main/java/world/bentobox/boxed/listeners/WorkshopListener.java +++ b/src/main/java/world/bentobox/boxed/listeners/WorkshopListener.java @@ -15,7 +15,9 @@ import org.bukkit.event.player.PlayerChangedWorldEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerRespawnEvent; +import org.bukkit.event.player.PlayerSwapHandItemsEvent; +import world.bentobox.bentobox.api.commands.CompositeCommand; import world.bentobox.boxed.Boxed; import world.bentobox.boxed.workshop.WorkshopManager; @@ -52,6 +54,8 @@ public void onChangedWorld(PlayerChangedWorldEvent e) { manager.playerEntered(player, player.getGameMode()); player.setGameMode(GameMode.CREATIVE); } else if (was && !is) { + // The border that shows the limit of the box does not belong anywhere else + player.setWorldBorder(null); GameMode mode = manager.playerLeft(player); player.setGameMode(mode == null ? Bukkit.getDefaultGameMode() : mode); } @@ -74,6 +78,19 @@ public void onJoin(PlayerJoinEvent e) { } } + /** + * The swap hands key (F by default) opens the list of places in the workshop, so admins + * do not have to go back to chat for it. + */ + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onSwapHands(PlayerSwapHandItemsEvent e) { + if (manager.isWorkshopWorld(e.getPlayer().getWorld())) { + e.setCancelled(true); + String label = addon.getAdminCommand().map(CompositeCommand::getTopLabel).orElse("boxadmin"); + Bukkit.dispatchCommand(e.getPlayer(), label + " areas spots"); + } + } + @EventHandler(priority = EventPriority.MONITOR) public void onDeath(PlayerDeathEvent e) { Player player = e.getEntity(); diff --git a/src/main/java/world/bentobox/boxed/reach/SpotFinder.java b/src/main/java/world/bentobox/boxed/reach/SpotFinder.java index 86f3d60..45be866 100644 --- a/src/main/java/world/bentobox/boxed/reach/SpotFinder.java +++ b/src/main/java/world/bentobox/boxed/reach/SpotFinder.java @@ -6,7 +6,7 @@ /** * Looks through the biomes of a seed for places where a box could start: wooded land with - * water a short walk away. Looking up a biome is cheap, so a lot of ground can be covered. + * water a short walk away and no mountains close enough to block the view. Looking up a biome is cheap, so a lot of ground can be covered. * The best places are then looked at properly with a {@link SpotSurvey}. * * @author tastybento @@ -41,6 +41,14 @@ public record Candidate(int x, int z, String biome, int waterDistance, int landP private static final int[] WATER_RINGS = { 32, 48, 64, 96, 128 }; private static final int[][] DIRECTIONS = { { 1, 0 }, { 1, 1 }, { 0, 1 }, { -1, 1 }, { -1, 0 }, { -1, -1 }, { 0, -1 }, { 1, -1 } }; + /** + * Mountains nearer than the last of these block the view from the start + */ + private static final int[] MOUNTAIN_RINGS = { 32, 64, 96, 128 }; + /** + * How much is taken off the rating of a place that has mountains next to it + */ + private static final int MOUNTAIN_PENALTY = 50; /** * The best distance to water. Nearer and the box may start on a beach. */ @@ -85,6 +93,31 @@ public static boolean isWooded(String biome) { || biome.equals("cherry_grove"); } + /** + * @param biome biome name + * @return true if the biome is high, steep ground + */ + public static boolean isMountain(String biome) { + return biome.contains("peaks") || biome.contains("slopes") || biome.contains("windswept") + || biome.equals("grove"); + } + + /** + * A box should start with a view of what can be reached. Mountains in the distance are + * good to see, but right next to the start they are a wall. + * @return true if there are mountains close enough to block the view + */ + private boolean isMountainNear(int x, int z) { + for (int ring : MOUNTAIN_RINGS) { + for (int[] d : DIRECTIONS) { + if (isMountain(lookup.biomeAt(x + d[0] * ring, z + d[1] * ring))) { + return true; + } + } + } + return isMountain(lookup.biomeAt(x, z)); + } + /** * Searches a square of the seed. * @param radius how far from the middle of the seed to look, in blocks @@ -100,7 +133,7 @@ public List find(int radius, int step, int count, int separation) { for (int x = -limit; x <= limit; x += grid) { for (int z = -limit; z <= limit; z += grid) { String biome = lookup.biomeAt(x, z); - if (isWooded(biome) && isDryAround(x, z)) { + if (isWooded(biome) && isDryAround(x, z) && !isMountainNear(x, z)) { int water = waterDistance(x, z); found.add(new Candidate(x, z, biome, water, 0, waterRating(water))); } @@ -121,7 +154,8 @@ public List find(int radius, int step, int count, int separation) { public Candidate at(int x, int z) { int water = waterDistance(x, z); int land = landPercent(x, z); - return new Candidate(x, z, lookup.biomeAt(x, z), water, land, waterRating(water) + land / 2); + int rating = waterRating(water) + land / 2 - (isMountainNear(x, z) ? MOUNTAIN_PENALTY : 0); + return new Candidate(x, z, lookup.biomeAt(x, z), water, land, rating); } private static int waterRating(int water) { diff --git a/src/main/java/world/bentobox/boxed/reach/SpotScorer.java b/src/main/java/world/bentobox/boxed/reach/SpotScorer.java new file mode 100644 index 0000000..dbe147e --- /dev/null +++ b/src/main/java/world/bentobox/boxed/reach/SpotScorer.java @@ -0,0 +1,71 @@ +package world.bentobox.boxed.reach; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CompletableFuture; + +import org.bukkit.Bukkit; +import org.bukkit.Chunk; +import org.bukkit.ChunkSnapshot; +import org.bukkit.World; +import org.bukkit.plugin.Plugin; + +/** + * Generates the land around a place in a world and scores it as a place to start a box. + * + * @author tastybento + */ +public final class SpotScorer { + + private SpotScorer() { + } + + /** + * Scores a place. The chunks are generated without stopping the server and the counting + * is done off the main thread. + * @param plugin plugin to schedule with + * @param world world to look in + * @param x block x of the place + * @param z block z of the place + * @param discard true to drop the generated chunks without saving them, for a world that + * is going to be thrown away + * @return the score. Completes on the main thread, with an error if the land could not be generated. + */ + public static CompletableFuture score(Plugin plugin, World world, int x, int z, + boolean discard) { + CompletableFuture result = new CompletableFuture<>(); + int reach = SpotSurvey.RADIUS >> 4; + int chunkX = x >> 4; + int chunkZ = z >> 4; + List> chunks = new ArrayList<>(); + for (int cx = -reach; cx < reach; cx++) { + for (int cz = -reach; cz < reach; cz++) { + chunks.add(world.getChunkAtAsync(chunkX + cx, chunkZ + cz)); + } + } + CompletableFuture.allOf(chunks.toArray(CompletableFuture[]::new)).whenComplete((v, error) -> + // Chunks have to be read on the main thread + Bukkit.getScheduler().runTask(plugin, () -> { + if (error != null) { + result.completeExceptionally(error); + return; + } + List snapshots = new ArrayList<>(); + for (CompletableFuture chunk : chunks) { + Chunk c = chunk.join(); + snapshots.add(c.getChunkSnapshot(true, false, false)); + if (discard) { + world.unloadChunk(c.getX(), c.getZ(), false); + } + } + int minY = world.getMinHeight(); + Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { + SpotSurvey spotSurvey = new SpotSurvey(); + snapshots.forEach(s -> spotSurvey.add(s, (s.getX() - chunkX) << 4, (s.getZ() - chunkZ) << 4, minY)); + SpotSurvey.Score score = spotSurvey.score(); + Bukkit.getScheduler().runTask(plugin, () -> result.complete(score)); + }); + })); + return result; + } +} diff --git a/src/main/java/world/bentobox/boxed/workshop/Workshop.java b/src/main/java/world/bentobox/boxed/workshop/Workshop.java index 0310f08..0cd2a9f 100644 --- a/src/main/java/world/bentobox/boxed/workshop/Workshop.java +++ b/src/main/java/world/bentobox/boxed/workshop/Workshop.java @@ -3,7 +3,10 @@ import java.io.File; import java.io.IOException; import java.util.EnumMap; +import java.util.ArrayList; import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; import java.util.Locale; import java.util.Map; import java.util.UUID; @@ -26,11 +29,31 @@ public class Workshop { private static final String BIOMES_KEY = "biomes"; private static final String CENTRES_KEY = "centres"; + private static final String SPOTS_KEY = "spots"; + + /** + * A place that could be the middle of every box. + * @param x block x + * @param z block z + * @param biome the biome the seed has there + * @param score how good a start it gives out of 100, or -1 if its land has not been looked at yet + * @param description what the score is made of + */ + public record Spot(int x, int z, String biome, int score, String description) { + /** + * @return true if the land has been looked at + */ + public boolean scored() { + return score >= 0; + } + } + private final long seed; private final String biomes; private final String area; private final Map centres = new EnumMap<>(Environment.class); private final Map players = new HashMap<>(); + private final List spots = new ArrayList<>(); /** * @param seed world seed of the land @@ -82,6 +105,38 @@ public void setCentre(Environment env, int x, int z) { centres.put(env, new int[] { x, z }); } + /** + * @param env dimension + * @return true if a place has been picked for the middle of every box + */ + public boolean hasCentre(Environment env) { + return centres.containsKey(env); + } + + /** + * @return the places found so far that could be the middle of every box. Their order + * never changes, so a place can be named by its position in the list. + */ + public List getSpots() { + return List.copyOf(spots); + } + + /** + * @param found the places to choose from + */ + public void setSpots(List found) { + spots.clear(); + spots.addAll(found); + } + + /** + * @param index position in the list + * @param spot the place, now that its land has been looked at + */ + public void setSpot(int index, Spot spot) { + spots.set(index, spot); + } + /** * Notes a player who has come in, and the game mode to give back when they leave. * @param uuid player @@ -118,6 +173,17 @@ public void save(File file) throws IOException { config.set("area", area); centres.forEach((env, c) -> config.set(CENTRES_KEY + "." + env.name().toLowerCase(Locale.ENGLISH), c[0] + "," + c[1])); players.forEach((uuid, mode) -> config.set(PLAYERS_KEY + "." + uuid, mode.name())); + List> list = new ArrayList<>(); + for (Spot spot : spots) { + Map map = new LinkedHashMap<>(); + map.put("x", spot.x()); + map.put("z", spot.z()); + map.put("biome", spot.biome()); + map.put("score", spot.score()); + map.put("description", spot.description()); + list.add(map); + } + config.set(SPOTS_KEY, list); File parent = file.getParentFile(); if (parent != null) { parent.mkdirs(); @@ -139,28 +205,45 @@ public static Workshop load(File file) { return null; } Workshop workshop = new Workshop(config.getLong("seed"), config.getString(BIOMES_KEY), config.getString("area")); - ConfigurationSection c = config.getConfigurationSection(CENTRES_KEY); - if (c != null) { - for (String key : c.getKeys(false)) { - String[] xz = c.getString(key, "").split(","); - try { - workshop.setCentre(Environment.valueOf(key.toUpperCase(Locale.ENGLISH)), - Integer.parseInt(xz[0].trim()), Integer.parseInt(xz[1].trim())); - } catch (IllegalArgumentException | ArrayIndexOutOfBoundsException _) { - // A centre that cannot be read is left at 0,0 - } + workshop.loadCentres(config.getConfigurationSection(CENTRES_KEY)); + workshop.loadPlayers(config.getConfigurationSection(PLAYERS_KEY)); + List found = new ArrayList<>(); + for (Map map : config.getMapList(SPOTS_KEY)) { + if (map.get("x") instanceof Number x && map.get("z") instanceof Number z + && map.get("score") instanceof Number score) { + found.add(new Spot(x.intValue(), z.intValue(), String.valueOf(map.get("biome")), score.intValue(), + String.valueOf(map.get("description")))); } } - ConfigurationSection p = config.getConfigurationSection(PLAYERS_KEY); - if (p != null) { - for (String key : p.getKeys(false)) { - try { - workshop.addPlayer(UUID.fromString(key), GameMode.valueOf(p.getString(key, ""))); - } catch (IllegalArgumentException _) { - // Not a player entry - } + workshop.setSpots(found); + return workshop; + } + + private void loadCentres(@Nullable ConfigurationSection c) { + if (c == null) { + return; + } + for (String key : c.getKeys(false)) { + String[] xz = c.getString(key, "").split(","); + try { + setCentre(Environment.valueOf(key.toUpperCase(Locale.ENGLISH)), Integer.parseInt(xz[0].trim()), + Integer.parseInt(xz[1].trim())); + } catch (IllegalArgumentException | ArrayIndexOutOfBoundsException _) { + // A centre that cannot be read is left at 0,0 + } + } + } + + private void loadPlayers(@Nullable ConfigurationSection p) { + if (p == null) { + return; + } + for (String key : p.getKeys(false)) { + try { + addPlayer(UUID.fromString(key), GameMode.valueOf(p.getString(key, ""))); + } catch (IllegalArgumentException _) { + // Not a player entry } } - return workshop; } } diff --git a/src/main/java/world/bentobox/boxed/workshop/WorkshopManager.java b/src/main/java/world/bentobox/boxed/workshop/WorkshopManager.java index 0bfeb38..43191ad 100644 --- a/src/main/java/world/bentobox/boxed/workshop/WorkshopManager.java +++ b/src/main/java/world/bentobox/boxed/workshop/WorkshopManager.java @@ -26,6 +26,18 @@ import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.entity.SpawnCategory; +import org.bukkit.Material; +import org.bukkit.WorldBorder; +import org.bukkit.generator.BiomeProvider; +import world.bentobox.bentobox.api.localization.TextVariables; +import world.bentobox.bentobox.api.user.User; +import world.bentobox.boxed.reach.SpotFinder; +import world.bentobox.boxed.reach.SpotFinder.Candidate; +import world.bentobox.boxed.reach.SpotScorer; +import org.bukkit.HeightMap; +import org.bukkit.Tag; +import org.bukkit.block.Block; +import world.bentobox.bentobox.api.commands.CompositeCommand; import org.eclipse.jdt.annotation.Nullable; import world.bentobox.boxed.Boxed; @@ -50,6 +62,22 @@ public class WorkshopManager { */ public static final String WORLD = "workshop"; private static final String NETHER = "_nether"; + private static final String SPOTS_PREFIX = "boxed.commands.boxadmin.areas.spots."; + /** + * How far from 0,0 places to start are looked for, in blocks + */ + private static final int SCAN_RADIUS = 5000; + private static final int SCAN_STEP = 64; + /** + * How many places are looked at + */ + private static final int SCAN_SPOTS = 12; + private static final String FOUND = "found"; + private static final String TOTAL = "[total]"; + /** + * How many blocks away from a place a player may be put to keep them out of a tree + */ + private static final int STAND_SEARCH = 5; private static final int NETHER_FLOOR = 32; private static final int NETHER_ROOF = 110; @@ -214,6 +242,10 @@ public World getWorld(Environment env) { AbstractSeedBiomeProvider provider = env == Environment.NETHER ? new NetherSeedBiomeGenerator(addon, workshop.getBiomes(), centre[0], centre[1]) : new SeedBiomeGenerator(addon, workshop.getBiomes(), centre[0], centre[1]); + if (env == Environment.NORMAL && !workshop.getSpots().isEmpty()) { + // The biomes were laid out around every place that was found, and have to stay that way + provider.setCentres(workshop.getSpots().stream().map(s -> new int[] { s.x(), s.z() }).toList()); + } world = WorldCreator.name(worldName(env)).generator(new BoxedSeedChunkGenerator(addon, env, provider)) .environment(env).seed(workshop.getSeed()).createWorld(); if (world == null) { @@ -229,6 +261,9 @@ public World getWorld(Environment env) { } worlds.put(env, world); biomes.put(env, provider); + if (env == Environment.NORMAL) { + scan(workshop, world, provider); + } return world; } @@ -244,26 +279,219 @@ public CompletableFuture enter(Player player, Environment env) { return CompletableFuture.completedFuture(false); } int[] centre = workshop.getCentre(env); - return world.getChunkAtAsync(centre[0] >> 4, centre[1] >> 4).thenCompose(chunk -> player - .teleportAsync(new Location(world, centre[0] + 0.5, standingHeight(world, centre[0], centre[1]), - centre[1] + 0.5))); + return world.getChunkAtAsync(centre[0] >> 4, centre[1] >> 4) + .thenCompose(chunk -> player.teleportAsync(standingPlace(world, centre[0], centre[1]))) + .thenApply(ok -> { + if (Boolean.TRUE.equals(ok)) { + // The marker is sent after the player has the chunk, or it would be overwritten + Bukkit.getScheduler().runTaskLater(addon.getPlugin(), () -> showCentre(player, true), 10L); + } + return ok; + }); + } + + /** + * Looks for places that could be the middle of every box. The seed's biomes are searched + * first, which needs no land. The chosen biomes are then laid out around every place + * found, and the land at each is generated and scored, one at a time. Players in the + * workshop are told as each one is ready. + */ + private void scan(Workshop w, World world, AbstractSeedBiomeProvider provider) { + if (!w.getSpots().isEmpty()) { + // Carry on where the server stopped + scoreNext(w, world, false); + return; + } + BiomeProvider vanilla = world.vanillaBiomeProvider(); + int seaLevel = world.getSeaLevel(); + int land = addon.getSettings().getIslandDistance(); + int[] start = w.getCentre(Environment.NORMAL); + SpotFinder finder = new SpotFinder((x, z) -> vanilla.getBiome(world, x, seaLevel, z).getKey().getKey(), land); + Bukkit.getScheduler().runTaskAsynchronously(addon.getPlugin(), () -> { + // The place the workshop starts at is always the first choice. The others are kept + // far enough from it, and from each other, that their biomes do not overlap. + List found = new ArrayList<>(); + found.add(unscored(finder.at(start[0], start[1]))); + long apart = land * 4L; + for (Candidate c : finder.find(SCAN_RADIUS, SCAN_STEP, SCAN_SPOTS, land * 4)) { + long dx = (long) c.x() - start[0]; + long dz = (long) c.z() - start[1]; + if (dx * dx + dz * dz >= apart * apart) { + found.add(unscored(c)); + } + } + Bukkit.getScheduler().runTask(addon.getPlugin(), () -> { + if (workshop != w || closing) { + return; + } + w.setSpots(found); + save(); + provider.setCentres(found.stream().map(s -> new int[] { s.x(), s.z() }).toList()); + scoreNext(w, world, false); + }); + }); + } + + private static Workshop.Spot unscored(Candidate c) { + return new Workshop.Spot(c.x(), c.z(), c.biome(), -1, ""); } /** - * @return the height to put a player at so that they are standing on the ground + * Scores the next place that has not been looked at yet. + * @param told true if players have been told about a place since the scan last began */ - static int standingHeight(World world, int x, int z) { - if (world.getEnvironment() != Environment.NETHER) { - return world.getHighestBlockYAt(x, z) + 1; - } - // The Nether has a roof, so look for a floor with room above it instead - for (int y = NETHER_ROOF; y > NETHER_FLOOR; y--) { - if (world.getBlockAt(x, y, z).getType().isSolid() && world.getBlockAt(x, y + 1, z).getType().isAir() - && world.getBlockAt(x, y + 2, z).getType().isAir()) { - return y + 1; + private void scoreNext(Workshop w, World world, boolean told) { + List spots = w.getSpots(); + int index = 0; + while (index < spots.size() && spots.get(index).scored()) { + index++; + } + if (index == spots.size()) { + if (told) { + tell(SPOTS_PREFIX + "finished", spots.size(), spots.size()); } + return; } - return 64; + int i = index; + Workshop.Spot spot = spots.get(i); + SpotScorer.score(addon.getPlugin(), world, spot.x(), spot.z(), false).whenComplete((score, error) -> { + if (workshop != w || closing) { + return; + } + if (error != null) { + addon.logError("Could not generate the land at " + spot.x() + "," + spot.z() + ": " + error); + } + w.setSpot(i, new Workshop.Spot(spot.x(), spot.z(), spot.biome(), error == null ? score.score() : 0, + error == null ? score.describe() : "?")); + save(); + tell(SPOTS_PREFIX + FOUND, i + 1, spots.size()); + scoreNext(w, world, true); + }); + } + + /** + * Tells everyone in the workshop how the search is going. Chat is only used for the + * first place and the last; the ones in between are shown above the hotbar. + */ + private void tell(String message, int number, int total) { + String label = addon.getAdminCommand().map(CompositeCommand::getTopLabel).orElse("boxadmin"); + for (World world : worlds.values()) { + for (Player p : world.getPlayers()) { + User user = User.getInstance(p); + if (message.endsWith(FOUND) && number > 1) { + p.sendActionBar(user.getTranslationAsComponent(SPOTS_PREFIX + "progress", TextVariables.NUMBER, + String.valueOf(number), TOTAL, String.valueOf(total))); + } else { + user.sendMessage(message, TextVariables.NUMBER, String.valueOf(number), TOTAL, + String.valueOf(total), TextVariables.LABEL, label); + } + } + } + } + + /** + * Makes a place the middle of every box and takes the player there. + * @param player player who picked it + * @param index position of the place in the list of places found + * @return true once the player is there, false if there is no such place + */ + public CompletableFuture select(Player player, int index) { + Workshop w = workshop; + List spots = w == null ? List.of() : w.getSpots(); + if (w == null || closing || index < 0 || index >= spots.size() || !spots.get(index).scored()) { + return CompletableFuture.completedFuture(false); + } + w.setCentre(Environment.NORMAL, spots.get(index).x(), spots.get(index).z()); + save(); + return enter(player, Environment.NORMAL); + } + + /** + * Shows a player where the middle of the box is, with a diamond block that only they can + * see, and how far the box can reach, with a world border that only they can see. + * Nothing is shown in a dimension where no place has been picked yet. + * @param player player in a workshop world + * @param border true to show the border, false to take it away + */ + public void showCentre(Player player, boolean border) { + World world = player.getWorld(); + if (workshop == null || !isWorkshopWorld(world) || !workshop.hasCentre(world.getEnvironment())) { + player.setWorldBorder(null); + return; + } + int[] centre = workshop.getCentre(world.getEnvironment()); + player.sendBlockChange( + new Location(world, centre[0], groundHeight(world, centre[0], centre[1]), centre[1]), + Material.DIAMOND_BLOCK.createBlockData()); + if (border) { + WorldBorder limit = Bukkit.createWorldBorder(); + limit.setCenter(centre[0], centre[1]); + limit.setSize(addon.getSettings().getIslandDistance() * 2D); + limit.setWarningDistance(0); + player.setWorldBorder(limit); + } else { + player.setWorldBorder(null); + } + } + + /** + * Finds the ground at a place: the soil under any trees and the bed under any water. + * @return y of the ground block + */ + static int groundHeight(World world, int x, int z) { + if (world.getEnvironment() == Environment.NETHER) { + // The Nether has a roof, so look for a floor with room above it instead + for (int y = NETHER_ROOF; y > NETHER_FLOOR; y--) { + if (world.getBlockAt(x, y, z).getType().isSolid() && world.getBlockAt(x, y + 1, z).getType().isAir() + && world.getBlockAt(x, y + 2, z).getType().isAir()) { + return y; + } + } + return 63; + } + int y = world.getHighestBlockYAt(x, z, HeightMap.OCEAN_FLOOR); + // Go down through trees to the soil they grow in + while (y > world.getMinHeight() && isTree(world.getBlockAt(x, y, z).getType())) { + y--; + } + return y; + } + + private static boolean isTree(Material m) { + return Tag.LOGS.isTagged(m) || Tag.LEAVES.isTagged(m); + } + + /** + * Finds somewhere to stand at a place: on the ground, under the trees, and next to a + * tree trunk if one is in the way. Over water it is the surface. + * @return where a player can be put + */ + static Location standingPlace(World world, int x, int z) { + // The place is the corner of a chunk, so looking this way stays inside the chunk + for (int reach = 0; reach <= STAND_SEARCH; reach++) { + for (int dx = 0; dx <= reach; dx++) { + for (int dz = 0; dz <= reach; dz++) { + Location at = Math.max(dx, dz) == reach ? openGround(world, x + dx, z + dz) : null; + if (at != null) { + return at; + } + } + } + } + return new Location(world, x + 0.5, world.getHighestBlockYAt(x, z) + 1D, z + 0.5); + } + + /** + * @return a place to stand on the ground of a column, or null if something is in the way + */ + @Nullable + private static Location openGround(World world, int x, int z) { + int y = groundHeight(world, x, z); + Block feet = world.getBlockAt(x, y + 1, z); + Block head = world.getBlockAt(x, y + 2, z); + return feet.isPassable() && head.isPassable() && !feet.isLiquid() + ? new Location(world, x + 0.5, y + 1D, z + 0.5) + : null; } /** diff --git a/src/main/resources/areas.yml b/src/main/resources/areas.yml index e330c3d..8b529b1 100644 --- a/src/main/resources/areas.yml +++ b/src/main/resources/areas.yml @@ -11,8 +11,9 @@ # seed - the world seed the land is generated from. The default area uses the seed # in config.yml unless one is given here. # centre - the place in the seed that the middle of every box is taken from, as x,z. -# The default is 0,0. /boxadmin areas find [seed|random] looks through -# a seed for good places to start and lists them with their scores. +# The default is 0,0. The workshop (/boxadmin areas edit) finds good +# places and lets you look at them. From the console, +# boxadmin areas find [seed|random] lists them with scores. # nether-centre - the same for the Nether. A fortress cannot be placed like other # structures, so the Nether has to be taken from a place that has one. # /boxadmin areas find lists places that do. @@ -34,7 +35,8 @@ # Admins can list areas with /boxadmin areas, visit one with /boxadmin areas tp , # make one with /boxadmin areas create [seed], build one again with # /boxadmin areas rebuild [regenerate], check that one can be played to the end with -# /boxadmin areas check and look for a better place to start with /boxadmin areas find. +# /boxadmin areas check . The console can list good places to start with +# boxadmin areas find. # /boxadmin areas edit opens the workshop, where a seed and a biome style can be tried out # in a temporary world. # diff --git a/src/main/resources/locales/en-US.yml b/src/main/resources/locales/en-US.yml index 4889fb7..9909bcf 100755 --- a/src/main/resources/locales/en-US.yml +++ b/src/main/resources/locales/en-US.yml @@ -618,7 +618,7 @@ boxed: started: '&a Started work on an area with seed &e [seed] &a and the &e [style] &a biome style.' status: '&a An area is being worked on. Seed &e [seed]&a, biome style &e [style]&a, started from area &e [area]' ready: '&a The world is ready.' - welcome: '&a You are in the area workshop, in creative mode. Nothing here is permanent until the area is made.' + welcome: '&a You are in the area workshop, in creative mode. Places to start a box are being looked for. Press &b F &a(swap hands) to see them.' failed: '&c That did not work. See the console for the reason.' discard-confirm: '&c This deletes the area being worked on and its worlds. Type &b discard confirm &c to do it.' discarded: '&a The area that was being worked on has been removed.' @@ -641,6 +641,30 @@ boxed: save-for-later: Save for later discard-title: Discard this area? discard-body: The temporary worlds and everything done in them will be deleted. Areas that are already made are not affected. + spots: + description: show the places found for the middle of the box, or pick one + parameters: '[number | border]' + looking: '&a Still looking for places to start a box. You will be told when one is found.' + found: '&a The first place to start is ready. Press &b F &a(swap hands) or click here to see the places as they are found.[run_command: /[label] areas spots][hover: Show the places found]' + finished: '&a The search has finished: [number] places. Press &b F &a(swap hands) or click here to see them.[run_command: /[label] areas spots][hover: Show the places found]' + progress: '&a Places to start: [number] of [total] ready. Press F to see them.' + entry: '&e [number]: &a [xyz] &7 score [score], [biome]. [description]' + entry-picked: '&e [number]: &a [xyz] &7 score [score], [biome]. [description] &b (picked)' + more-coming: '&7 [number] more are still being looked at.' + unknown: '&c There is no place with that number yet.' + selected: '&a Place [number] at &e [xyz] &a is now the middle of the box.' + no-centre: '&c Pick a place first.' + border-on: '&a The border is shown.' + border-off: '&a The border is hidden.' + dialog: + title: Places to start a box + body: Click a place to go there and make it the middle of every box. A diamond block marks the middle and the border shows how far a box can grow. Press F (swap hands) to open this again. + body-looking: Click a place to go there and make it the middle of every box. [number] more are still being looked at. Press F (swap hands) to open this again. + button: '[number]: [xyz] (score [score])' + button-picked: '> [number]: [xyz] (score [score]) <' + tooltip: '[biome]. [description]' + border: Show or hide the border + close: Close find: description: look through a seed for good places to start a box parameters: [seed|random] [search radius] diff --git a/src/test/java/world/bentobox/boxed/commands/AdminAreasEditCommandTest.java b/src/test/java/world/bentobox/boxed/commands/AdminAreasEditCommandTest.java index d03f5c7..2d8c71c 100644 --- a/src/test/java/world/bentobox/boxed/commands/AdminAreasEditCommandTest.java +++ b/src/test/java/world/bentobox/boxed/commands/AdminAreasEditCommandTest.java @@ -74,7 +74,10 @@ void setUpCommand() throws IOException { return manager.get().orElseThrow(); }); + // The command is /boxadmin areas edit + CompositeCommand top = mock(CompositeCommand.class); CompositeCommand parent = mock(CompositeCommand.class); + when(parent.getParent()).thenReturn(top); when(parent.getAddon()).thenReturn(addon); when(parent.getTopLabel()).thenReturn("boxadmin"); when(parent.getPermissionPrefix()).thenReturn(""); @@ -186,7 +189,7 @@ void testPlayerIsTakenThere() { when(user.getPlayer()).thenReturn(mockPlayer); when(manager.enter(mockPlayer, Environment.NORMAL)).thenReturn(CompletableFuture.completedFuture(true)); assertTrue(cmd.execute(user, "edit", List.of("go"))); - verify(user).sendMessage(PREFIX + "welcome"); + verify(user).sendMessage(PREFIX + "welcome", "[label]", "boxadmin"); } @Test @@ -215,13 +218,13 @@ void testDiscardNothing() { void testTabComplete() { Area icelands = areas.getArea("icelands"); when(areas.getAreas()).thenReturn(List.of(icelands)); - assertEquals(List.of("start", "go", "discard"), cmd.tabComplete(user, "edit", List.of("edit", "")).orElseThrow()); - assertEquals(List.of("random", "same"), cmd.tabComplete(user, "edit", List.of("edit", "start", "")).orElseThrow()); + assertEquals(List.of("start", "go", "discard"), cmd.tabComplete(user, "edit", List.of("areas", "edit", "")).orElseThrow()); + assertEquals(List.of("random", "same"), cmd.tabComplete(user, "edit", List.of("areas", "edit", "start", "")).orElseThrow()); assertEquals(List.of("same", "original", "rings"), - cmd.tabComplete(user, "edit", List.of("edit", "start", "1", "")).orElseThrow()); + cmd.tabComplete(user, "edit", List.of("areas", "edit", "start", "1", "")).orElseThrow()); assertEquals(List.of("icelands"), - cmd.tabComplete(user, "edit", List.of("edit", "start", "1", "rings", "")).orElseThrow()); - assertEquals(List.of("nether"), cmd.tabComplete(user, "edit", List.of("edit", "go", "")).orElseThrow()); - assertEquals(List.of("confirm"), cmd.tabComplete(user, "edit", List.of("edit", "discard", "c")).orElseThrow()); + cmd.tabComplete(user, "edit", List.of("areas", "edit", "start", "1", "rings", "")).orElseThrow()); + assertEquals(List.of("nether"), cmd.tabComplete(user, "edit", List.of("areas", "edit", "go", "")).orElseThrow()); + assertEquals(List.of("confirm"), cmd.tabComplete(user, "edit", List.of("areas", "edit", "discard", "c")).orElseThrow()); } } diff --git a/src/test/java/world/bentobox/boxed/commands/AdminAreasFindCommandTest.java b/src/test/java/world/bentobox/boxed/commands/AdminAreasFindCommandTest.java new file mode 100644 index 0000000..cbea32a --- /dev/null +++ b/src/test/java/world/bentobox/boxed/commands/AdminAreasFindCommandTest.java @@ -0,0 +1,75 @@ +package world.bentobox.boxed.commands; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.HashMap; +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import world.bentobox.bentobox.api.commands.CompositeCommand; +import world.bentobox.bentobox.api.user.User; +import world.bentobox.boxed.Boxed; +import world.bentobox.boxed.CommonTestSetup; +import world.bentobox.boxed.areas.Area; +import world.bentobox.boxed.areas.AreaManager; + +/** + * Tests the tab completion of the find command, which is given everything typed after + * /boxadmin: the "areas" and "find" labels and then the parameters. + */ +class AdminAreasFindCommandTest extends CommonTestSetup { + + private AdminAreasFindCommand cmd; + private User user; + + @BeforeEach + void setUpCommand() { + Boxed addon = mock(Boxed.class); + AreaManager areas = mock(AreaManager.class); + when(addon.getAreas()).thenReturn(areas); + when(areas.getAreas()).thenReturn( + List.of(new Area("default", 1L, "biomes.yml", "s.yml", 0, true, null, 0, 0, 0, 0, 0), + new Area("icelands", 2L, "biomes.yml", "s.yml", 1, true, null, 0, 0, 0, 0, 0))); + + // The command is /boxadmin areas find + CompositeCommand top = mock(CompositeCommand.class); + CompositeCommand parent = mock(CompositeCommand.class); + when(parent.getParent()).thenReturn(top); + when(parent.getAddon()).thenReturn(addon); + when(parent.getTopLabel()).thenReturn("boxadmin"); + when(parent.getPermissionPrefix()).thenReturn(""); + when(parent.getWorld()).thenReturn(world); + when(parent.getSubCommands()).thenReturn(new HashMap<>()); + cmd = new AdminAreasFindCommand(parent); + user = mock(User.class); + } + + @Test + void testAreasComeFirst() { + assertEquals(List.of("default", "icelands"), + cmd.tabComplete(user, "find", List.of("areas", "find", "")).orElseThrow()); + assertEquals(List.of("icelands"), cmd.tabComplete(user, "find", List.of("areas", "find", "ice")).orElseThrow()); + } + + @Test + void testThenTheSeed() { + assertEquals(List.of("random"), + cmd.tabComplete(user, "find", List.of("areas", "find", "icelands", "")).orElseThrow()); + } + + @Test + void testNothingForTheRadius() { + assertTrue(cmd.tabComplete(user, "find", List.of("areas", "find", "icelands", "random", "")).isEmpty()); + } + + @Test + void testParameterCountsFromTheCommandsOwnLabel() { + assertEquals(1, AdminAreasCommand.parameter(cmd, List.of("areas", "find", ""))); + assertEquals(3, AdminAreasCommand.parameter(cmd, List.of("areas", "find", "a", "b", ""))); + } +} diff --git a/src/test/java/world/bentobox/boxed/commands/AdminAreasSpotsCommandTest.java b/src/test/java/world/bentobox/boxed/commands/AdminAreasSpotsCommandTest.java new file mode 100644 index 0000000..fbc0f7e --- /dev/null +++ b/src/test/java/world/bentobox/boxed/commands/AdminAreasSpotsCommandTest.java @@ -0,0 +1,163 @@ +package world.bentobox.boxed.commands; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.HashMap; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; + +import org.bukkit.World.Environment; +import org.bukkit.WorldBorder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import world.bentobox.bentobox.api.commands.CompositeCommand; +import world.bentobox.bentobox.api.user.User; +import world.bentobox.boxed.Boxed; +import world.bentobox.boxed.CommonTestSetup; +import world.bentobox.boxed.workshop.Workshop; +import world.bentobox.boxed.workshop.WorkshopManager; + +/** + * Tests listing and picking the places the workshop has found. + */ +class AdminAreasSpotsCommandTest extends CommonTestSetup { + + private static final String PREFIX = "boxed.commands.boxadmin.areas.spots."; + + private AdminAreasSpotsCommand cmd; + private WorkshopManager manager; + private Workshop workshop; + private User user; + + @BeforeEach + void setUpCommand() { + Boxed addon = mock(Boxed.class); + manager = mock(WorkshopManager.class); + when(addon.getWorkshop()).thenReturn(manager); + workshop = new Workshop(5L, "biomes.yml", null); + workshop.setSpots(List.of(new Workshop.Spot(0, 0, "plains", 90, "dry land"), + new Workshop.Spot(1280, -640, "forest", 98, "wood at size 2"), + new Workshop.Spot(-2560, 64, "taiga", -1, ""))); + when(manager.get()).thenReturn(Optional.of(workshop)); + + // The command is /boxadmin areas spots + CompositeCommand top = mock(CompositeCommand.class); + CompositeCommand parent = mock(CompositeCommand.class); + when(parent.getParent()).thenReturn(top); + when(parent.getAddon()).thenReturn(addon); + when(parent.getTopLabel()).thenReturn("boxadmin"); + when(parent.getPermissionPrefix()).thenReturn(""); + when(parent.getWorld()).thenReturn(world); + when(parent.getSubCommands()).thenReturn(new HashMap<>()); + cmd = new AdminAreasSpotsCommand(parent); + + user = mock(User.class); + when(user.isPlayer()).thenReturn(true); + when(user.getPlayer()).thenReturn(mockPlayer); + } + + @Test + void testSetup() { + assertEquals("spots", cmd.getLabel()); + assertEquals("admin.areas.spots", cmd.getPermission()); + assertFalse(cmd.isOnlyPlayer()); + } + + @Test + void testNoWorkshop() { + when(manager.get()).thenReturn(Optional.empty()); + assertFalse(cmd.execute(user, "spots", List.of())); + verify(user).sendMessage("boxed.commands.boxadmin.areas.edit.none", "[label]", "boxadmin"); + } + + @Test + void testNothingFoundYet() { + workshop.setSpots(List.of(new Workshop.Spot(0, 0, "plains", -1, ""))); + assertTrue(cmd.execute(user, "spots", List.of())); + verify(user).sendMessage(PREFIX + "looking"); + } + + @Test + void testConsoleGetsAList() { + when(user.isPlayer()).thenReturn(false); + workshop.setCentre(Environment.NORMAL, 1280, -640); + assertTrue(cmd.execute(user, "spots", List.of())); + verify(user).sendMessage(PREFIX + "entry", "[number]", "1", "[xyz]", "0,0", "[score]", "90", "[biome]", + "plains", "[description]", "dry land"); + verify(user).sendMessage(PREFIX + "entry-picked", "[number]", "2", "[xyz]", "1280,-640", "[score]", "98", + "[biome]", "forest", "[description]", "wood at size 2"); + verify(user).sendMessage(PREFIX + "more-coming", "[number]", "1"); + } + + @Test + void testConsoleCannotPick() { + when(user.isPlayer()).thenReturn(false); + assertFalse(cmd.execute(user, "spots", List.of("1"))); + verify(user).sendMessage("general.errors.use-in-game"); + verify(manager, never()).select(any(), anyInt()); + } + + @Test + void testPick() { + when(manager.select(mockPlayer, 1)).thenReturn(CompletableFuture.completedFuture(true)); + assertTrue(cmd.execute(user, "spots", List.of("2"))); + verify(user).sendMessage(PREFIX + "selected", "[number]", "2", "[xyz]", "1280,-640", "[label]", "boxadmin"); + } + + @Test + void testPickThatFails() { + when(manager.select(mockPlayer, 0)).thenReturn(CompletableFuture.completedFuture(false)); + assertTrue(cmd.execute(user, "spots", List.of("1"))); + verify(user).sendMessage("boxed.commands.boxadmin.areas.edit.failed"); + } + + @Test + void testPickUnknownOrUnfinished() { + assertFalse(cmd.execute(user, "spots", List.of("0"))); + assertFalse(cmd.execute(user, "spots", List.of("4"))); + // The third place has not been looked at yet + assertFalse(cmd.execute(user, "spots", List.of("3"))); + verify(user, times(3)).sendMessage(PREFIX + "unknown"); + verify(manager, never()).select(any(), anyInt()); + } + + @Test + void testBorderOnAndOff() { + // No border yet, so it is shown + WorldBorder shown = mock(WorldBorder.class); + doAnswer(i -> when(mockPlayer.getWorldBorder()).thenReturn(shown)) + .when(manager).showCentre(mockPlayer, true); + assertTrue(cmd.execute(user, "spots", List.of("border"))); + verify(user).sendMessage(PREFIX + "border-on"); + // Now there is one, so it is hidden + doAnswer(i -> when(mockPlayer.getWorldBorder()).thenReturn(null)).when(manager) + .showCentre(mockPlayer, false); + assertTrue(cmd.execute(user, "spots", List.of("BORDER"))); + verify(user).sendMessage(PREFIX + "border-off"); + } + + @Test + void testBorderNeedsAPlace() { + assertFalse(cmd.execute(user, "spots", List.of("border"))); + verify(manager).showCentre(mockPlayer, true); + verify(user).sendMessage(PREFIX + "no-centre"); + } + + @Test + void testTabComplete() { + assertEquals(List.of("border", "1", "2"), cmd.tabComplete(user, "spots", List.of("areas", "spots", "")).orElseThrow()); + assertEquals(List.of("2"), cmd.tabComplete(user, "spots", List.of("areas", "spots", "2")).orElseThrow()); + } +} diff --git a/src/test/java/world/bentobox/boxed/listeners/WorkshopListenerTest.java b/src/test/java/world/bentobox/boxed/listeners/WorkshopListenerTest.java index b1f5897..fe75e66 100644 --- a/src/test/java/world/bentobox/boxed/listeners/WorkshopListenerTest.java +++ b/src/test/java/world/bentobox/boxed/listeners/WorkshopListenerTest.java @@ -15,6 +15,7 @@ import org.bukkit.event.player.PlayerChangedWorldEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerRespawnEvent; +import org.bukkit.event.player.PlayerSwapHandItemsEvent; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -45,6 +46,7 @@ class WorkshopListenerTest extends CommonTestSetup { public void setUp() { super.setUp(); when(addon.getPlugin()).thenReturn(plugin); + when(addon.getAdminCommand()).thenReturn(java.util.Optional.empty()); when(manager.isWorkshopWorld(workshopWorld)).thenReturn(true); when(mockPlayer.getUniqueId()).thenReturn(uuid); when(mockPlayer.getGameMode()).thenReturn(GameMode.SURVIVAL); @@ -78,6 +80,8 @@ void testLeavingGivesTheOldGameModeBack() { when(manager.playerLeft(mockPlayer)).thenReturn(GameMode.SPECTATOR); listener.onChangedWorld(new PlayerChangedWorldEvent(mockPlayer, workshopWorld)); verify(mockPlayer).setGameMode(GameMode.SPECTATOR); + // The border that marks the box is taken away + verify(mockPlayer).setWorldBorder(null); } @Test @@ -142,6 +146,25 @@ void testDyingInsideComesBackWhereTheyDied() { verify(mockPlayer).setGameMode(GameMode.CREATIVE); } + @Test + void testSwapHandsOpensThePlaces() { + when(mockPlayer.getWorld()).thenReturn(workshopWorld); + PlayerSwapHandItemsEvent e = mock(PlayerSwapHandItemsEvent.class); + when(e.getPlayer()).thenReturn(mockPlayer); + listener.onSwapHands(e); + verify(e).setCancelled(true); + mockedBukkit.verify(() -> Bukkit.dispatchCommand(mockPlayer, "boxadmin areas spots")); + } + + @Test + void testSwapHandsElsewhereIsLeftAlone() { + when(mockPlayer.getWorld()).thenReturn(world); + PlayerSwapHandItemsEvent e = mock(PlayerSwapHandItemsEvent.class); + when(e.getPlayer()).thenReturn(mockPlayer); + listener.onSwapHands(e); + verify(e, never()).setCancelled(true); + } + @Test void testDyingElsewhereIsLeftAlone() { when(mockPlayer.getWorld()).thenReturn(world); diff --git a/src/test/java/world/bentobox/boxed/reach/SpotFinderTest.java b/src/test/java/world/bentobox/boxed/reach/SpotFinderTest.java index e55fc42..6f1b3ea 100644 --- a/src/test/java/world/bentobox/boxed/reach/SpotFinderTest.java +++ b/src/test/java/world/bentobox/boxed/reach/SpotFinderTest.java @@ -53,6 +53,33 @@ void testFindsWoodedLandNearWater() { assertTrue(found.get(0).rating() >= found.get(1).rating()); } + /** + * The same strip, with mountains across it north of z = -200 + */ + private static String stripWithMountains(int x, int z) { + return z < -200 && x >= 0 ? "jagged_peaks" : strip(x, z); + } + + @Test + void testMountainsAreKeptInTheDistance() { + assertTrue(SpotFinder.isMountain("frozen_peaks")); + assertTrue(SpotFinder.isMountain("snowy_slopes")); + assertTrue(SpotFinder.isMountain("grove")); + assertTrue(SpotFinder.isMountain("windswept_hills")); + assertFalse(SpotFinder.isMountain("cherry_grove")); + assertFalse(SpotFinder.isMountain("meadow")); + + SpotFinder finder = new SpotFinder(SpotFinderTest::stripWithMountains, 320); + List found = finder.find(1000, 16, 20, 100); + assertFalse(found.isEmpty()); + for (Candidate c : found) { + // Nothing is offered within 128 blocks of the mountains + assertTrue(c.z() >= -72, c.toString()); + } + // A place that is asked about by name is still described, but rated lower + assertTrue(finder.at(32, -150).rating() < finder.at(32, 0).rating()); + } + @Test void testPlacesAreKeptApart() { List found = new SpotFinder(SpotFinderTest::strip, 320).find(1000, 16, 50, 400); diff --git a/src/test/java/world/bentobox/boxed/workshop/WorkshopManagerTest.java b/src/test/java/world/bentobox/boxed/workshop/WorkshopManagerTest.java index ce51f05..ceabdcf 100644 --- a/src/test/java/world/bentobox/boxed/workshop/WorkshopManagerTest.java +++ b/src/test/java/world/bentobox/boxed/workshop/WorkshopManagerTest.java @@ -8,8 +8,11 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -21,6 +24,10 @@ import java.util.concurrent.CompletableFuture; import org.bukkit.Bukkit; +import org.bukkit.HeightMap; +import org.bukkit.Chunk; +import org.bukkit.WorldBorder; +import org.bukkit.block.data.BlockData; import org.bukkit.Difficulty; import org.bukkit.GameMode; import org.bukkit.Location; @@ -248,20 +255,143 @@ void testSendOutGoesToTheGameSpawnNext() { assertTrue(manager.sendOut(mockPlayer).join()); } + private void twoSpots() throws IOException { + Workshop w = new Workshop(11L, "biomes.yml", null); + w.setSpots(List.of(new Workshop.Spot(0, 0, "plains", 90, "dry"), new Workshop.Spot(1280, -640, "forest", 95, "wood"), + new Workshop.Spot(-2560, 0, "taiga", -1, ""))); + w.save(workshopFile); + Files.createDirectories(new File(worldFolder, "workshop").toPath()); + // Land that is asked for never arrives, so the search waits + when(workshopWorld.getChunkAtAsync(anyInt(), anyInt())).thenReturn(new CompletableFuture<>()); + manager.load(); + when(workshopWorld.getChunkAtAsync(80, -40)).thenReturn(CompletableFuture.completedFuture(mock(Chunk.class))); + when(mockPlayer.teleportAsync(any())).thenReturn(CompletableFuture.completedFuture(true)); + when(mockPlayer.getWorld()).thenReturn(workshopWorld); + // Ground at 70 with nothing on it + when(workshopWorld.getHighestBlockYAt(1280, -640, HeightMap.OCEAN_FLOOR)).thenReturn(70); + Block ground = mock(Block.class); + when(ground.getType()).thenReturn(Material.GRASS_BLOCK); + Block air = mock(Block.class); + when(air.getType()).thenReturn(Material.AIR); + when(air.isPassable()).thenReturn(true); + when(workshopWorld.getBlockAt(anyInt(), anyInt(), anyInt())).thenReturn(air); + when(workshopWorld.getBlockAt(1280, 70, -640)).thenReturn(ground); + } + + @Test + void testAnUnfinishedSearchCarriesOnAfterARestart() throws IOException { + twoSpots(); + // The third place has not been looked at, so its land is asked for + verify(workshopWorld, atLeastOnce()).getChunkAtAsync(-160, 0); + verify(workshopWorld, never()).getChunkAtAsync(0, 0); + } + + @Test + void testSelectMakesThePlaceTheMiddleAndGoesThere() throws IOException { + twoSpots(); + assertTrue(manager.select(mockPlayer, 1).join()); + Workshop saved = Workshop.load(workshopFile); + assertEquals(1280, saved.getCentre(Environment.NORMAL)[0]); + assertEquals(-640, saved.getCentre(Environment.NORMAL)[1]); + ArgumentCaptor to = ArgumentCaptor.forClass(Location.class); + verify(mockPlayer).teleportAsync(to.capture()); + assertEquals(1280.5, to.getValue().getX()); + assertEquals(71, to.getValue().getY()); + assertEquals(-639.5, to.getValue().getZ()); + } + + @Test + void testSelectNeedsAPlaceThatHasBeenLookedAt() throws IOException { + twoSpots(); + assertFalse(manager.select(mockPlayer, -1).join()); + assertFalse(manager.select(mockPlayer, 2).join()); + assertFalse(manager.select(mockPlayer, 3).join()); + verify(mockPlayer, never()).teleportAsync(any()); + } + + @Test + void testCentreIsMarkedAndBordered() throws IOException { + twoSpots(); + WorldBorder border = mock(WorldBorder.class); + mockedBukkit.when(Bukkit::createWorldBorder).thenReturn(border); + // Nothing is shown until a place has been picked + manager.showCentre(mockPlayer, true); + verify(mockPlayer).setWorldBorder(null); + verify(mockPlayer, never()).sendBlockChange(any(Location.class), any(BlockData.class)); + + manager.select(mockPlayer, 1).join(); + manager.showCentre(mockPlayer, true); + ArgumentCaptor marker = ArgumentCaptor.forClass(Location.class); + verify(mockPlayer).sendBlockChange(marker.capture(), any(BlockData.class)); + assertEquals(1280, marker.getValue().getX()); + assertEquals(70, marker.getValue().getY()); + verify(border).setCenter(1280, -640); + // The border is as wide as the land of an area + verify(border).setSize(new Settings().getIslandDistance() * 2D); + verify(mockPlayer).setWorldBorder(border); + // The marker stays when the border is hidden + manager.showCentre(mockPlayer, false); + verify(mockPlayer, times(2)).setWorldBorder(null); + verify(mockPlayer, times(2)).sendBlockChange(any(Location.class), any(BlockData.class)); + } + + @Test + void testStandingPlaceIsOnTheGroundUnderTheTrees() { + // A tree stands on the place: leaves down to 74, trunk down to 71, soil at 70 + when(workshopWorld.getMinHeight()).thenReturn(-64); + when(workshopWorld.getHighestBlockYAt(anyInt(), anyInt(), any(HeightMap.class))).thenReturn(70); + when(workshopWorld.getHighestBlockYAt(16, 32, HeightMap.OCEAN_FLOOR)).thenReturn(76); + Block air = mock(Block.class); + when(air.getType()).thenReturn(Material.AIR); + when(air.isPassable()).thenReturn(true); + Block soil = mock(Block.class); + when(soil.getType()).thenReturn(Material.DIRT); + Block log = mock(Block.class); + when(log.getType()).thenReturn(Material.OAK_LOG); + Block leaves = mock(Block.class); + when(leaves.getType()).thenReturn(Material.OAK_LEAVES); + when(workshopWorld.getBlockAt(anyInt(), anyInt(), anyInt())).thenReturn(air); + when(workshopWorld.getBlockAt(anyInt(), org.mockito.ArgumentMatchers.eq(70), anyInt())).thenReturn(soil); + for (int y = 71; y <= 73; y++) { + when(workshopWorld.getBlockAt(16, y, 32)).thenReturn(log); + } + for (int y = 74; y <= 76; y++) { + when(workshopWorld.getBlockAt(16, y, 32)).thenReturn(leaves); + } + assertEquals(70, WorkshopManager.groundHeight(workshopWorld, 16, 32)); + // The trunk is in the way, so the player goes on the ground beside it + Location stand = WorkshopManager.standingPlace(workshopWorld, 16, 32); + assertEquals(71, stand.getY()); + assertEquals(1, Math.max(stand.getBlockX() - 16, stand.getBlockZ() - 32)); + } + + @Test + void testStandingPlaceOverWaterIsTheSurface() { + when(workshopWorld.getMinHeight()).thenReturn(-64); + when(workshopWorld.getHighestBlockYAt(anyInt(), anyInt(), any(HeightMap.class))).thenReturn(40); + when(workshopWorld.getHighestBlockYAt(0, 0)).thenReturn(62); + Block sand = mock(Block.class); + when(sand.getType()).thenReturn(Material.SAND); + Block water = mock(Block.class); + when(water.getType()).thenReturn(Material.WATER); + when(water.isPassable()).thenReturn(true); + when(water.isLiquid()).thenReturn(true); + when(workshopWorld.getBlockAt(anyInt(), anyInt(), anyInt())).thenReturn(water); + when(workshopWorld.getBlockAt(anyInt(), org.mockito.ArgumentMatchers.eq(40), anyInt())).thenReturn(sand); + assertEquals(63, WorkshopManager.standingPlace(workshopWorld, 0, 0).getY()); + } + @Test - void testStandingHeight() { - when(workshopWorld.getHighestBlockYAt(3, 4)).thenReturn(70); - assertEquals(71, WorkshopManager.standingHeight(workshopWorld, 3, 4)); - // The Nether has a roof, so the floor is looked for under it + void testNetherGroundIsUnderTheRoof() { World nether = mock(World.class); when(nether.getEnvironment()).thenReturn(Environment.NETHER); Block air = mock(Block.class); when(air.getType()).thenReturn(Material.AIR); Block rock = mock(Block.class); when(rock.getType()).thenReturn(Material.NETHERRACK); - when(nether.getBlockAt(any(Integer.class), any(Integer.class), any(Integer.class))).thenReturn(rock); + when(nether.getBlockAt(anyInt(), anyInt(), anyInt())).thenReturn(rock); when(nether.getBlockAt(3, 51, 4)).thenReturn(air); when(nether.getBlockAt(3, 52, 4)).thenReturn(air); - assertEquals(51, WorkshopManager.standingHeight(nether, 3, 4)); + assertEquals(50, WorkshopManager.groundHeight(nether, 3, 4)); } } diff --git a/src/test/java/world/bentobox/boxed/workshop/WorkshopTest.java b/src/test/java/world/bentobox/boxed/workshop/WorkshopTest.java index 9534cf5..3026cf3 100644 --- a/src/test/java/world/bentobox/boxed/workshop/WorkshopTest.java +++ b/src/test/java/world/bentobox/boxed/workshop/WorkshopTest.java @@ -2,6 +2,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; 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; @@ -48,6 +49,26 @@ void testSaveAndLoad() throws IOException { assertNull(loaded.removePlayer(uuid)); } + @Test + void testSpotsAreSavedInOrder() throws IOException { + Workshop w = new Workshop(1L, "biomes.yml", null); + assertFalse(w.hasCentre(Environment.NORMAL)); + w.setSpots(List.of(new Workshop.Spot(0, 0, "plains", 90, "dry land, wood at size 3"), + new Workshop.Spot(-1280, 640, "forest", -1, ""))); + w.setCentre(Environment.NORMAL, 0, 0); + File file = new File(folder, "workshop.yml"); + w.save(file); + Workshop loaded = Workshop.load(file); + assertNotNull(loaded); + assertTrue(loaded.hasCentre(Environment.NORMAL)); + assertEquals(w.getSpots(), loaded.getSpots()); + assertTrue(loaded.getSpots().get(0).scored()); + assertFalse(loaded.getSpots().get(1).scored()); + // A place is filled in when its land has been looked at + loaded.setSpot(1, new Workshop.Spot(-1280, 640, "forest", 77, "wet")); + assertEquals(77, loaded.getSpots().get(1).score()); + } + @Test void testNewAreaHasNoName() throws IOException { File file = new File(folder, "workshop.yml");