Repository navigation
Add persistent vanilla voting NPCs #1715
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
BenCodez
wants to merge
6
commits into
master
Choose a base branch
from
feature/persistent-voting-npcs
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
41cca3f
Add opt-in persistent vanilla voting NPCs
BenCodez d2d9256
Fix voting NPC path compatibility, permissions and protection
BenCodez 1d89eec
Retire voting NPCs across their occupied chunk bounds
BenCodez 8bb8851
Retry deferred voting NPC cleanup after lifecycle recovery
BenCodez 7010625
Wake pending voting NPCs when runtime capacity is released
BenCodez 2f6cb10
Wake waiting voting NPCs after unloaded reservations
BenCodez File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
119 changes: 119 additions & 0 deletions
119
VotingPlugin/src/main/java/com/bencodez/votingplugin/npc/VotingNPCCommands.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,119 @@ | ||
| package com.bencodez.votingplugin.npc; | ||
|
|
||
| import java.util.Arrays; | ||
| import java.util.UUID; | ||
| import java.util.concurrent.CompletionStage; | ||
|
|
||
| import org.bukkit.Location; | ||
| import org.bukkit.command.CommandSender; | ||
| import org.bukkit.entity.Player; | ||
|
|
||
| import com.bencodez.advancedcore.api.command.CommandHandler; | ||
| import com.bencodez.votingplugin.VotingPluginMain; | ||
| import com.bencodez.votingplugin.util.BukkitCompletionScheduler; | ||
|
|
||
| /** Normal /av command handlers; no separate command map or player GUI registry. */ | ||
| public final class VotingNPCCommands { | ||
| private static final String PERMISSION = "VotingPlugin.Commands.AdminVote.NPC"; | ||
| private VotingNPCCommands() { } | ||
|
|
||
| public static void register(VotingPluginMain plugin) { | ||
| add(plugin, new String[] { "NPC", "Create", "(string)" }, false); | ||
| add(plugin, new String[] { "NPC", "Create", "(string)", "(list)" }, false); | ||
| add(plugin, new String[] { "NPC", "List" }, true); | ||
| add(plugin, new String[] { "NPC", "Inspect", "(npcid)" }, true); | ||
| add(plugin, new String[] { "NPC", "Remove", "(npcid)" }, true); | ||
| } | ||
|
|
||
| private static void add(VotingPluginMain plugin, String[] pattern, boolean console) { | ||
| plugin.getAdminVoteCommand().add(new CommandHandler(plugin, pattern, PERMISSION + "|VotingPlugin.Admin", | ||
| "Manage saved vanilla voting NPCs", console) { | ||
| @Override public void execute(CommandSender sender, String[] args) { | ||
| // CommandHandler invokes execute asynchronously. Capture location, | ||
| // permission and messages only after reaching the sender's owner. | ||
| String[] captured = args.clone(); | ||
| onSender(plugin, sender, () -> executeOwned(plugin, sender, captured)); | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| private static boolean allowed(CommandSender sender) { | ||
| return (!(sender instanceof Player player) || player.isOnline()) | ||
| && (sender.hasPermission(PERMISSION) || sender.hasPermission("VotingPlugin.Admin")); | ||
| } | ||
|
|
||
| private static void onSender(VotingPluginMain plugin, CommandSender sender, Runnable action) { | ||
| Player player = sender instanceof Player candidate ? candidate : null; | ||
| BukkitCompletionScheduler.run(plugin, player, action, player == null ? action : () -> { }, () -> { }); | ||
| } | ||
|
|
||
| private static void executeOwned(VotingPluginMain plugin, CommandSender sender, String[] args) { | ||
| if (!allowed(sender)) return; | ||
| VotingNPCManager manager = plugin.getVotingNPCManager(); | ||
| if (manager == null || !manager.available()) { | ||
| sender.sendMessage("Voting NPCs are disabled, unsupported, or waiting for valid storage. Check VotingNPCs.Enabled in Config.yml and reload."); | ||
| return; | ||
| } | ||
| switch (args[1].toLowerCase(java.util.Locale.ROOT)) { | ||
| case "create": | ||
| if (!(sender instanceof Player player)) { sender.sendMessage("Create a voting NPC from in game."); return; } | ||
| try { | ||
| Location at = player.getLocation(); | ||
| String name = args.length > 3 ? String.join(" ", Arrays.copyOfRange(args, 3, args.length)) : "&aVote"; | ||
| VotingNPCDefinition definition = new VotingNPCDefinition(args[2], UUID.randomUUID(), at.getWorld().getUID(), | ||
| at.getX(), at.getY(), at.getZ(), at.getYaw(), at.getPitch(), name); | ||
| confirm(plugin, sender, manager, manager.create(definition), | ||
| ignored -> "Saved voting NPC '" + definition.id() + "'. Its villager appears when the area is loaded and available."); | ||
| } catch (IllegalArgumentException invalid) { | ||
| sender.sendMessage("Use a lowercase ID of 1-40 letters, digits, underscores or hyphens, and a name of 1-128 characters without controls."); | ||
| } | ||
| break; | ||
| case "remove": | ||
| confirm(plugin, sender, manager, manager.remove(args[2]), removed -> removed | ||
| ? "Removed saved voting NPC '" + args[2] + "'; exact entity cleanup has been requested." | ||
| : "No voting NPC has that ID."); | ||
| break; | ||
| case "inspect": | ||
| manager.definitions().stream().filter(value -> value.id().equals(args[2])).findFirst().ifPresentOrElse(value -> | ||
| sender.sendMessage("Voting NPC " + value.id() + ": world " + value.world() + ", " | ||
| + value.x() + ", " + value.y() + ", " + value.z() + "; " + manager.runtimeState(value.id())), | ||
| () -> sender.sendMessage("No voting NPC has that ID.")); | ||
| break; | ||
| case "list": | ||
| sender.sendMessage("Saved voting NPCs: " + manager.definitions().size() + "/64; tracked runtime slots: " + manager.runtimeCount()); | ||
| for (var value : manager.definitions()) sender.sendMessage(value.id() + ": " + manager.runtimeState(value.id())); | ||
| break; | ||
| default: | ||
| sender.sendMessage("Use /av npc create <id> [name], list, inspect <id>, or remove <id>."); | ||
| } | ||
| } | ||
|
|
||
| private static String failureMessage(VotingNPCManager manager, Throwable failure) { | ||
| while ((failure instanceof java.util.concurrent.CompletionException | ||
| || failure instanceof java.util.concurrent.ExecutionException) && failure.getCause() != null) { | ||
| failure = failure.getCause(); | ||
| } | ||
| if (manager.available()) { | ||
| if (failure instanceof VotingNPCRegistry.ValidationFailure validation) { | ||
| return switch (validation.reason) { | ||
| case DUPLICATE_ID -> "That voting NPC ID already exists. Use a different ID or remove it first."; | ||
| case DUPLICATE_IDENTITY -> "That voting NPC identity already exists. No definition was changed."; | ||
| case LIMIT -> "The 64 voting NPC limit has been reached. Remove an NPC before creating another."; | ||
| }; | ||
| } | ||
| if (failure instanceof java.util.concurrent.RejectedExecutionException) { | ||
| return "Voting NPC storage is busy. Wait for pending changes to finish before retrying."; | ||
| } | ||
| } | ||
| return "Voting NPC change was not confirmed. Check storage and reload before retrying; no success is assumed."; | ||
| } | ||
|
|
||
| private static <T> void confirm(VotingPluginMain plugin, CommandSender sender, VotingNPCManager manager, CompletionStage<T> completion, | ||
| java.util.function.Function<T, String> message) { | ||
| completion.whenComplete((value, failure) -> onSender(plugin, sender, () -> { | ||
| if (!allowed(sender)) return; | ||
| sender.sendMessage(failure == null ? message.apply(value) | ||
| : failureMessage(manager, failure)); | ||
| })); | ||
| } | ||
| } | ||
29 changes: 29 additions & 0 deletions
29
VotingPlugin/src/main/java/com/bencodez/votingplugin/npc/VotingNPCDefinition.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| package com.bencodez.votingplugin.npc; | ||
|
|
||
| import java.util.Objects; | ||
| import java.util.UUID; | ||
| import java.util.regex.Pattern; | ||
|
|
||
| /** Durable definition; it contains no live world, player, entity or reward state. */ | ||
| public record VotingNPCDefinition(String id, UUID identity, UUID world, double x, double y, double z, | ||
| float yaw, float pitch, String name) { | ||
| private static final Pattern ID = Pattern.compile("[a-z0-9][a-z0-9_-]{0,39}"); | ||
|
|
||
| public VotingNPCDefinition { | ||
| if (id == null || !ID.matcher(id).matches()) throw new IllegalArgumentException("Invalid voting NPC ID"); | ||
| Objects.requireNonNull(identity, "identity"); | ||
| Objects.requireNonNull(world, "world"); | ||
| if (!Double.isFinite(x) || !Double.isFinite(y) || !Double.isFinite(z) | ||
| || Math.abs(x) > 30_000_000 || Math.abs(z) > 30_000_000 | ||
| || !Float.isFinite(yaw) || !Float.isFinite(pitch)) { | ||
| throw new IllegalArgumentException("Invalid voting NPC position"); | ||
| } | ||
| if (name == null || name.isEmpty() || name.length() > 128 | ||
| || name.codePoints().anyMatch(Character::isISOControl)) { | ||
| throw new IllegalArgumentException("Invalid voting NPC name"); | ||
| } | ||
| } | ||
|
|
||
| public int chunkX() { return Math.floorDiv((int) Math.floor(x), 16); } | ||
| public int chunkZ() { return Math.floorDiv((int) Math.floor(z), 16); } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.