Skip to content

Commit

Permalink
Try using some of Folia API
Browse files Browse the repository at this point in the history
  • Loading branch information
imDaniX committed Jun 28, 2024
1 parent d7d1303 commit 5219d55
Show file tree
Hide file tree
Showing 12 changed files with 117 additions and 96 deletions.
3 changes: 2 additions & 1 deletion resources/plugin.yml
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
name: '${project.name}'
main: wgextender.WGExtender
api-version: '1.13'
api-version: '1.20'
version: '${project.version}'
author: _Shevchik_
depend: [WorldGuard, WorldEdit, Vault]
folia-supported: true
commands:
wgextender:
aliases: [wgex]
10 changes: 3 additions & 7 deletions src/wgextender/Config.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,7 @@

import java.io.File;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.*;

public class Config {

Expand Down Expand Up @@ -64,7 +60,7 @@ public Config(WGExtender plugin) {
public Map<Flag<?>, String> claimAutoFlags = new HashMap<>();

public boolean restrictCommandsInRegionEnabled = false;
public Set<String> restrictedCommandsInRegion = new HashSet<>();
public List<String> restrictedCommandsInRegion = new ArrayList<>();

public boolean extendedWorldEditWandEnabled = false;

Expand Down Expand Up @@ -131,7 +127,7 @@ private void loadAll() {
}

restrictCommandsInRegionEnabled = config.getBoolean("restrictcommands.enabled", restrictCommandsInRegionEnabled);
restrictedCommandsInRegion = new HashSet<>(config.getStringList("restrictcommands.commands"));
restrictedCommandsInRegion = new ArrayList<>(config.getStringList("restrictcommands.commands"));

extendedWorldEditWandEnabled = config.getBoolean("extendedwewand", extendedWorldEditWandEnabled);

Expand Down
3 changes: 2 additions & 1 deletion src/wgextender/features/claimcommand/WGClaimCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ protected static void claim(String id, CommandSender sender) throws CommandExcep
BukkitWorldConfiguration wcfg = WGRegionUtils.getWorldConfig(player);

if (wcfg.maxClaimVolume == Integer.MAX_VALUE) {
throw new CommandException("The maximum claim volume get in the configuration is higher than is supported. " + "Currently, it must be " + Integer.MAX_VALUE + " or smaller. Please contact a server administrator.");
throw new CommandException("The maximum claim volume get in the configuration is higher than is supported. " +
"Currently, it must be " + Integer.MAX_VALUE + " or smaller. Please contact a server administrator.");
}

LocalPlayer localPlayer = WorldGuardPlugin.inst().wrapPlayer(player);
Expand Down
24 changes: 12 additions & 12 deletions src/wgextender/features/claimcommand/WGRegionCommandWrapper.java
Original file line number Diff line number Diff line change
Expand Up @@ -82,28 +82,28 @@ public boolean execute(CommandSender sender, String label, String[] args) {

private boolean process(Player player) {
BlockLimits.ProcessedClaimInfo info = blockLimits.processClaimInfo(config, player);
switch (info.result()) {
default: return true;
case DENY_MAX_VOLUME: {
return switch (info.result()) {
case ALLOW -> true;
case DENY_MAX_VOLUME -> {
player.sendMessage(RED + "Вы не можете заприватить такой большой регион");
player.sendMessage(RED + "Ваш лимит: "+info.assignedLimit()+", вы попытались заприватить: "+info.assignedSize());
return false;
yield false;
}
case DENY_MIN_VOLUME: {
case DENY_MIN_VOLUME -> {
player.sendMessage(RED + "Вы не можете заприватить такой маленький регион");
player.sendMessage(RED + "Минимальный объем: "+info.assignedLimit()+", вы попытались заприватить: "+info.assignedSize());
return false;
yield false;
}
case DENY_HORIZONTAL: {
player.sendMessage(RED + "Вы не можете заприватить такой маленький регион");
case DENY_HORIZONTAL -> {
player.sendMessage(RED + "Вы не можете заприватить такой узкий регион");
player.sendMessage(RED + "Минимальная ширина: "+info.assignedLimit()+", вы попытались заприватить: "+info.assignedSize());
return false;
yield false;
}
case DENY_VERTICAL: {
case DENY_VERTICAL -> {
player.sendMessage(RED + "Вы не можете заприватить такой низкий регион");
player.sendMessage(RED + "Минимальная высота: "+info.assignedLimit()+", вы попытались заприватить: "+info.assignedSize());
return false;
yield false;
}
}
};
}
}
15 changes: 6 additions & 9 deletions src/wgextender/features/extendedwand/WEWand.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,12 @@
import org.bukkit.inventory.meta.ItemMeta;
import wgextender.utils.WEUtils;

public class WEWand {

public class WEWand { // TODO Use PersistentData API
protected static final String WAND_NAME = ChatColor.LIGHT_PURPLE + "Selection wand";

protected static Material cachedWandMaterial;

protected static Material getWandMaterial() {
protected static Material getWandMaterial() { // TODO Rework to better handle registry
String weWandMaterialName = WEUtils.getWorldEditPlugin().getLocalConfiguration().wandItem.toUpperCase();
if ((cachedWandMaterial == null) || !cachedWandMaterial.toString().equals(weWandMaterialName)) {
cachedWandMaterial = Material.getMaterial(weWandMaterialName.split(":")[1]);
Expand All @@ -46,12 +45,10 @@ public static ItemStack getWand() {
return itemstack;
}

public static boolean isWand(ItemStack itemstack) {
if (itemstack.getType().equals(getWandMaterial())) {
ItemMeta im = itemstack.getItemMeta();
if (im != null) {
return WAND_NAME.equals(im.getDisplayName());
}
public static boolean isWand(ItemStack item) {
if (item.getType().equals(getWandMaterial()) && item.hasItemMeta()) {
ItemMeta meta = item.getItemMeta();
return meta.hasDisplayName() && WAND_NAME.equals(meta.getDisplayName());
}
return false;
}
Expand Down
2 changes: 1 addition & 1 deletion src/wgextender/features/flags/ChorusFruitFlagHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public void onItemUse(PlayerItemConsumeEvent event) {
!WGRegionUtils.canBypassProtection(event.getPlayer()) &&
!WGRegionUtils.isFlagAllows(player, player.getLocation(), WGExtenderFlags.CHORUS_FRUIT_USE_FLAG)
) {
player.sendMessage(ChatColor.RED + "Вы не можете использовать фрукт телепортации в этом регионе");
player.sendMessage(ChatColor.RED + "Вы не можете использовать хорус в этом регионе");
event.setCancelled(true);
}
}
Expand Down
42 changes: 25 additions & 17 deletions src/wgextender/features/flags/OldPVPFlagsHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,20 @@
import wgextender.utils.WGRegionUtils;

import java.lang.reflect.Field;
import java.util.*;
import java.util.EnumSet;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

@Deprecated
public class OldPVPFlagsHandler implements Listener {
@SuppressWarnings("deprecation")
private static final Set<EntityDamageEvent.DamageModifier> PVP_MODIFIERS = EnumSet.of(
DamageModifier.ARMOR, DamageModifier.RESISTANCE, DamageModifier.MAGIC, DamageModifier.ABSORPTION
);
private final Map<UUID, Double> oldValues = new HashMap<>();
private final Map<UUID, Double> oldValues = new ConcurrentHashMap<>();
private Field functionsField;

public void start(Plugin plugin) {
Expand All @@ -48,24 +53,27 @@ public void start(Plugin plugin) {

Server server = plugin.getServer();
server.getPluginManager().registerEvents(this, plugin);
server.getScheduler().runTaskTimer(WGExtender.getInstance(), () -> {
server.getAsyncScheduler().runAtFixedRate(plugin, (task) -> {
for (Player player : Bukkit.getOnlinePlayers()) {
if (WGRegionUtils.isFlagTrue(player.getLocation(), WGExtenderFlags.OLDPVP_ATTACKSPEED)) {
if (!oldValues.containsKey(player.getUniqueId())) {
AttributeInstance attribute = player.getAttribute(Attribute.GENERIC_ATTACK_SPEED);
oldValues.put(player.getUniqueId(), attribute.getBaseValue());
attribute.setBaseValue(16.0);
}
} else {
reset(player);
if (oldValues.containsKey(player.getUniqueId())) continue;
player.getScheduler().run(WGExtender.getInstance(), (playerTask) -> {
AttributeInstance attribute = player.getAttribute(Attribute.GENERIC_ATTACK_SPEED);
oldValues.put(player.getUniqueId(), attribute.getBaseValue());
attribute.setBaseValue(16.0);
}, null);
} else {
player.getScheduler().run(WGExtender.getInstance(), (playerTask) -> {
reset(player);
}, null);
}
}
}, 0, 1);
}, 0, 50, TimeUnit.MICROSECONDS);
}

public void stop() {
for (Player player : Bukkit.getOnlinePlayers()) {
reset(player);
player.getScheduler().run(WGExtender.getInstance(), playerTask -> reset(player), null);
}
}

Expand All @@ -81,7 +89,6 @@ public void onQuit(PlayerQuitEvent event) {
reset(event.getPlayer());
}

@SuppressWarnings({"unchecked", "deprecation"})
@EventHandler(priority = EventPriority.LOWEST)
public void onEntityDamageByEntity(EntityDamageByEntityEvent event) {
Entity entity = event.getEntity();
Expand All @@ -92,15 +99,16 @@ public void onEntityDamageByEntity(EntityDamageByEntityEvent event) {
}
Map<DamageModifier, Function<Double, Double>> func;
try {
func = (Map<DamageModifier, Function<Double, Double>>) functionsField.get(event);
//noinspection unchecked
func = (Map<DamageModifier, Function<Double, Double>>) functionsField.get(event);
} catch (IllegalArgumentException | IllegalAccessException e) {
WGExtender.getInstance().getLogger().log(Level.SEVERE, "Unable to recalculate blocking damage", e);
return;
}
double totalDamage = event.getDamage() + event.getDamage(DamageModifier.HARD_HAT);
//reset blocking modifier
// Reset blocking modifier
event.setDamage(DamageModifier.BLOCKING, 0);
//recalculate other modifiers
// Recalculate other modifiers
for (var modifier : PVP_MODIFIERS) {
double damage = func.get(modifier).apply(totalDamage);
event.setDamage(modifier, damage);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,12 +91,12 @@ public void onDamageEntity(DamageEntityEvent event) {
Entities.isAmbient(event.getEntity()) ||
Entities.isVehicle(event.getEntity().getType())
) {
canDamage = event.getRelevantFlags().isEmpty() || (query.queryState(weTarget, associable, combine(event)) != State.DENY);
canDamage = event.getRelevantFlags().isEmpty() || (query.queryState(weTarget, associable, getFlags(event)) != State.DENY);
what = "hit that";

/* Paintings, item frames, etc. */
} else if (Entities.isConsideredBuildingIfUsed(event.getEntity())) {
canDamage = query.testBuild(weTarget, associable, combine(event));
canDamage = query.testBuild(weTarget, associable, getFlags(event));
what = "change that";

/* PVP */
Expand All @@ -110,18 +110,18 @@ public void onDamageEntity(DamageEntityEvent event) {
// false - disallow pvp when flag not set
if (config.miscDefaultPvPFlagOperationMode == null) {
canDamage =
query.testBuild(weTarget, associable, combine(event, Flags.PVP)) &&
(query.queryState(weAttacker, localPlayerAttacker, combine(event, Flags.PVP)) != State.DENY) &&
(query.queryState(weTarget, localPlayerAttacker, combine(event, Flags.PVP)) != State.DENY);
query.testBuild(weTarget, associable, getFlags(event, Flags.PVP)) &&
(query.queryState(weAttacker, localPlayerAttacker, getFlags(event, Flags.PVP)) != State.DENY) &&
(query.queryState(weTarget, localPlayerAttacker, getFlags(event, Flags.PVP)) != State.DENY);
} else if (config.miscDefaultPvPFlagOperationMode) {
canDamage =
(query.queryState(weAttacker, localPlayerAttacker, combine(event, Flags.PVP)) != State.DENY) &&
(query.queryState(weTarget, localPlayerAttacker, combine(event, Flags.PVP)) != State.DENY);
(query.queryState(weAttacker, localPlayerAttacker, getFlags(event, Flags.PVP)) != State.DENY) &&
(query.queryState(weTarget, localPlayerAttacker, getFlags(event, Flags.PVP)) != State.DENY);
} else {
if (!WGRegionUtils.isInWGRegion(playerAttacker.getLocation()) && !WGRegionUtils.isInWGRegion(target)) {
canDamage = true;
} else {
canDamage = (query.queryState(weAttacker, localPlayerAttacker, combine(event, Flags.PVP)) == State.ALLOW) && (query.queryState(weTarget, localPlayerAttacker, combine(event, Flags.PVP)) == State.ALLOW);
canDamage = (query.queryState(weAttacker, localPlayerAttacker, getFlags(event, Flags.PVP)) == State.ALLOW) && (query.queryState(weTarget, localPlayerAttacker, getFlags(event, Flags.PVP)) == State.ALLOW);
}

}
Expand All @@ -135,17 +135,17 @@ public void onDamageEntity(DamageEntityEvent event) {

/* Player damage not caused by another player */
} else if (event.getEntity() instanceof Player) {
canDamage = event.getRelevantFlags().isEmpty() || (query.queryState(weTarget, associable, combine(event)) != State.DENY);
canDamage = event.getRelevantFlags().isEmpty() || (query.queryState(weTarget, associable, getFlags(event)) != State.DENY);
what = "damage that";

/* damage to non-hostile mobs (e.g. animals) */
} else if (Entities.isNonHostile(event.getEntity())) {
canDamage = query.testBuild(weTarget, associable, combine(event, Flags.DAMAGE_ANIMALS));
canDamage = query.testBuild(weTarget, associable, getFlags(event, Flags.DAMAGE_ANIMALS));
what = "harm that";

/* Everything else */
} else {
canDamage = query.testBuild(weTarget, associable, combine(event, Flags.INTERACT));
canDamage = query.testBuild(weTarget, associable, getFlags(event, Flags.INTERACT));
what = "hit that";
}

Expand Down Expand Up @@ -197,7 +197,6 @@ private void tellErrorMessage(DelegateEvent event, Cause cause, Location locatio
long now = System.currentTimeMillis();
Long lastTime = WGMetadata.getIfPresent(player, DENY_MESSAGE_KEY, Long.class);
if ((lastTime == null) || ((now - lastTime) >= LAST_MESSAGE_DELAY)) {
@SuppressWarnings("deprecation")
String message = WGRegionUtils.REGION_QUERY.queryValue(BukkitAdapter.adapt(location), WorldGuardPlugin.inst().wrapPlayer(player), Flags.DENY_MESSAGE);
if (message != null && !message.isEmpty()) {
player.sendMessage(message.replace("%what%", what));
Expand All @@ -207,12 +206,14 @@ private void tellErrorMessage(DelegateEvent event, Cause cause, Location locatio
}
}

private static StateFlag[] combine(DelegateEvent event, StateFlag... flag) {
private static StateFlag[] getFlags(DelegateEvent event) {
return event.getRelevantFlags().toArray(new StateFlag[0]);
}

private static StateFlag[] getFlags(DelegateEvent event, StateFlag flag) {
List<StateFlag> extra = event.getRelevantFlags();
StateFlag[] flags = Arrays.copyOf(flag, flag.length + extra.size());
for (int i = 0; i < extra.size(); i++) {
flags[flag.length + i] = extra.get(i);
}
return flags;
StateFlag[] result = Arrays.copyOf(getFlags(event), extra.size() + 1);
result[extra.size()] = flag;
return result;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,33 +30,36 @@
import wgextender.utils.WGRegionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;

public class RestrictCommands implements Listener {
private final Pattern SPACE_PATTERN = Pattern.compile("\\s+");
private static final long MS_PER_TICK = 50;

protected final Config config;
protected volatile String[] restrictedCommands;
protected volatile List<String> restrictedCommands;

public RestrictCommands(Config config) {
this.config = config;
restrictedCommands = config.restrictedCommandsInRegion.toArray(new String[0]);
Bukkit.getScheduler().runTaskTimerAsynchronously(WGExtender.getInstance(), () -> {
restrictedCommands = config.restrictedCommandsInRegion;
startCommandRecheckTask(config);
}

private void startCommandRecheckTask(Config config) {
Bukkit.getAsyncScheduler().runAtFixedRate(WGExtender.getInstance(), (task) -> {
if (!config.restrictCommandsInRegionEnabled) {
return;
}
List<String> computedRestrictedCommands = new ArrayList<>();
for (String restrictedCommand : config.restrictedCommandsInRegion) {
String[] split = SPACE_PATTERN.split(restrictedCommand);
String toAdd = split.length > 1 ? String.join(" ", Arrays.copyOfRange(split, 1, split.length)) : "";
String[] split = restrictedCommand.split(" ", 2);
String toAdd = " " + split[1].trim();
for (String alias : CommandUtils.getCommandAliases(split[0])) {
computedRestrictedCommands.add(String.join(" ", alias, toAdd));
computedRestrictedCommands.add(alias + toAdd);
}
}
restrictedCommands = computedRestrictedCommands.toArray(new String[0]);
}, 1, 100);
restrictedCommands = computedRestrictedCommands;
}, MS_PER_TICK, 100 * MS_PER_TICK, TimeUnit.MICROSECONDS);
}

@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
Expand Down
Loading

0 comments on commit 5219d55

Please sign in to comment.