Compare commits
55 Commits
Author | SHA1 | Date | |
---|---|---|---|
![]() |
15fcd14e16 | ||
![]() |
4019afe89b | ||
![]() |
6f1077ad2d | ||
![]() |
72e2673248 | ||
![]() |
04d6cf604c | ||
![]() |
d4ba859176 | ||
![]() |
56d6baf9de | ||
![]() |
ca3c486d8b | ||
![]() |
9dd32b1207 | ||
![]() |
da300b2958 | ||
![]() |
f90d3ac3f2 | ||
![]() |
1360be9917 | ||
![]() |
42a1bdec57 | ||
![]() |
6fe1330038 | ||
![]() |
0a3cd80f9c | ||
![]() |
0ff37cbd7d | ||
![]() |
07d105e30e | ||
![]() |
aecd669638 | ||
![]() |
7969f75a3a | ||
![]() |
849d6fbaf5 | ||
![]() |
b0d1c42955 | ||
![]() |
159c03f3cd | ||
![]() |
106e1625cc | ||
![]() |
c5e274daf9 | ||
![]() |
d0af45fc21 | ||
![]() |
4a775d5e7e | ||
![]() |
98b392d528 | ||
![]() |
f652cb1d1c | ||
![]() |
b94e158465 | ||
![]() |
c05ec30330 | ||
![]() |
5b3687a062 | ||
![]() |
665e23ec58 | ||
![]() |
d5de576591 | ||
![]() |
ca563700b3 | ||
![]() |
20d426e315 | ||
![]() |
7c56dfdb17 | ||
![]() |
2cd6d0576a | ||
![]() |
65322c6caa | ||
![]() |
2fec1bcbd4 | ||
![]() |
d547628a55 | ||
![]() |
77ff0a8921 | ||
![]() |
9cc91619dc | ||
![]() |
3b4c6dc32e | ||
![]() |
0d24169283 | ||
![]() |
5d4e9e4021 | ||
![]() |
7cf9e7d2de | ||
![]() |
ef8b6c884a | ||
![]() |
8f6fe7fa07 | ||
![]() |
493a3d7fe7 | ||
![]() |
28f9f13a5b | ||
![]() |
620a0b5d48 | ||
![]() |
bc7cffd77e | ||
![]() |
37636e5332 | ||
![]() |
e01b8b0462 | ||
![]() |
5fecedf658 |
51
pom.xml
51
pom.xml
@ -6,7 +6,7 @@
|
|||||||
|
|
||||||
<groupId>me.xginko</groupId>
|
<groupId>me.xginko</groupId>
|
||||||
<artifactId>VillagerOptimizer</artifactId>
|
<artifactId>VillagerOptimizer</artifactId>
|
||||||
<version>1.5.5</version>
|
<version>1.7.0</version>
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
<name>VillagerOptimizer</name>
|
<name>VillagerOptimizer</name>
|
||||||
@ -41,10 +41,6 @@
|
|||||||
</goals>
|
</goals>
|
||||||
<configuration>
|
<configuration>
|
||||||
<relocations>
|
<relocations>
|
||||||
<relocation>
|
|
||||||
<pattern>com.tcoded.folialib</pattern>
|
|
||||||
<shadedPattern>me.xginko.villageroptimizer.libs.folialib</shadedPattern>
|
|
||||||
</relocation>
|
|
||||||
<relocation>
|
<relocation>
|
||||||
<pattern>com.github.benmanes.caffeine</pattern>
|
<pattern>com.github.benmanes.caffeine</pattern>
|
||||||
<shadedPattern>me.xginko.villageroptimizer.libs.caffeine</shadedPattern>
|
<shadedPattern>me.xginko.villageroptimizer.libs.caffeine</shadedPattern>
|
||||||
@ -61,11 +57,27 @@
|
|||||||
<pattern>io.github.thatsmusic99.configurationmaster</pattern>
|
<pattern>io.github.thatsmusic99.configurationmaster</pattern>
|
||||||
<shadedPattern>me.xginko.villageroptimizer.libs.configmaster</shadedPattern>
|
<shadedPattern>me.xginko.villageroptimizer.libs.configmaster</shadedPattern>
|
||||||
</relocation>
|
</relocation>
|
||||||
|
<relocation>
|
||||||
|
<pattern>org.reflections</pattern>
|
||||||
|
<shadedPattern>me.xginko.villageroptimizer.libs.reflections</shadedPattern>
|
||||||
|
</relocation>
|
||||||
|
<relocation>
|
||||||
|
<pattern>com.cryptomorin.xseries</pattern>
|
||||||
|
<shadedPattern>me.xginko.villageroptimizer.libs.xseries</shadedPattern>
|
||||||
|
</relocation>
|
||||||
|
<relocation>
|
||||||
|
<pattern>space.arim.morepaperlib</pattern>
|
||||||
|
<shadedPattern>me.xginko.villageroptimizer.libs.morepaperlib</shadedPattern>
|
||||||
|
</relocation>
|
||||||
</relocations>
|
</relocations>
|
||||||
<filters>
|
<filters>
|
||||||
<filter>
|
<filter>
|
||||||
<artifact>*:*</artifact>
|
<artifact>*:*</artifact>
|
||||||
<excludes>
|
<excludes>
|
||||||
|
<exclude>com/cryptomorin/xseries/XBiome*</exclude>
|
||||||
|
<exclude>com/cryptomorin/xseries/NMSExtras*</exclude>
|
||||||
|
<exclude>com/cryptomorin/xseries/NoteBlockMusic*</exclude>
|
||||||
|
<exclude>com/cryptomorin/xseries/SkullCacheListener*</exclude>
|
||||||
<exclude>META-INF/MANIFEST.MF</exclude>
|
<exclude>META-INF/MANIFEST.MF</exclude>
|
||||||
<exclude>META-INF/LICENSE</exclude>
|
<exclude>META-INF/LICENSE</exclude>
|
||||||
<exclude>META-INF/LICENSE.txt</exclude>
|
<exclude>META-INF/LICENSE.txt</exclude>
|
||||||
@ -100,8 +112,8 @@
|
|||||||
<url>https://ci.pluginwiki.us/plugin/repository/everything/</url>
|
<url>https://ci.pluginwiki.us/plugin/repository/everything/</url>
|
||||||
</repository>
|
</repository>
|
||||||
<repository>
|
<repository>
|
||||||
<id>folialib-repo</id>
|
<id>morepaperlib-repo</id>
|
||||||
<url>https://nexuslite.gcnt.net/repos/other/</url>
|
<url>https://mvn-repo.arim.space/lesser-gpl3/</url>
|
||||||
</repository>
|
</repository>
|
||||||
</repositories>
|
</repositories>
|
||||||
|
|
||||||
@ -112,11 +124,22 @@
|
|||||||
<version>1.20.4-R0.1-SNAPSHOT</version>
|
<version>1.20.4-R0.1-SNAPSHOT</version>
|
||||||
<scope>provided</scope>
|
<scope>provided</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.logging.log4j</groupId>
|
||||||
|
<artifactId>log4j-core</artifactId>
|
||||||
|
<version>2.23.1</version>
|
||||||
|
<scope>provided</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.reflections</groupId>
|
||||||
|
<artifactId>reflections</artifactId>
|
||||||
|
<version>0.10.2</version>
|
||||||
|
</dependency>
|
||||||
<!-- Adventure API for easier cross-version compatibility -->
|
<!-- Adventure API for easier cross-version compatibility -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>net.kyori</groupId>
|
<groupId>net.kyori</groupId>
|
||||||
<artifactId>adventure-platform-bukkit</artifactId>
|
<artifactId>adventure-platform-bukkit</artifactId>
|
||||||
<version>4.3.2</version>
|
<version>4.3.3</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<!-- Adventure MiniMessage for parsing fancy tags in lang files -->
|
<!-- Adventure MiniMessage for parsing fancy tags in lang files -->
|
||||||
<dependency>
|
<dependency>
|
||||||
@ -156,9 +179,15 @@
|
|||||||
</dependency>
|
</dependency>
|
||||||
<!-- Folia Support -->
|
<!-- Folia Support -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.tcoded</groupId>
|
<groupId>space.arim.morepaperlib</groupId>
|
||||||
<artifactId>FoliaLib</artifactId>
|
<artifactId>morepaperlib</artifactId>
|
||||||
<version>0.3.1</version>
|
<version>0.4.3</version>
|
||||||
|
</dependency>
|
||||||
|
<!-- Cross-Version Support -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.github.cryptomorin</groupId>
|
||||||
|
<artifactId>XSeries</artifactId>
|
||||||
|
<version>11.2.1</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
</project>
|
</project>
|
||||||
|
@ -1,54 +0,0 @@
|
|||||||
package me.xginko.villageroptimizer;
|
|
||||||
|
|
||||||
import com.github.benmanes.caffeine.cache.Cache;
|
|
||||||
import com.github.benmanes.caffeine.cache.Caffeine;
|
|
||||||
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
|
|
||||||
import org.bukkit.entity.Villager;
|
|
||||||
import org.jetbrains.annotations.NotNull;
|
|
||||||
|
|
||||||
import java.time.Duration;
|
|
||||||
import java.util.UUID;
|
|
||||||
import java.util.concurrent.ConcurrentMap;
|
|
||||||
|
|
||||||
public final class VillagerCache {
|
|
||||||
|
|
||||||
private final @NotNull Cache<UUID, WrappedVillager> villagerCache;
|
|
||||||
|
|
||||||
public VillagerCache(long expireAfterWriteSeconds) {
|
|
||||||
this.villagerCache = Caffeine.newBuilder().expireAfterWrite(Duration.ofSeconds(expireAfterWriteSeconds)).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
public @NotNull ConcurrentMap<UUID, WrappedVillager> cacheMap() {
|
|
||||||
return this.villagerCache.asMap();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void clear() {
|
|
||||||
this.villagerCache.asMap().clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
public @NotNull WrappedVillager getOrAdd(@NotNull Villager villager) {
|
|
||||||
WrappedVillager wrappedVillager = this.villagerCache.getIfPresent(villager.getUniqueId());
|
|
||||||
return wrappedVillager == null ? this.add(new WrappedVillager(villager)) : this.add(wrappedVillager);
|
|
||||||
}
|
|
||||||
|
|
||||||
public @NotNull WrappedVillager add(@NotNull WrappedVillager villager) {
|
|
||||||
this.villagerCache.put(villager.villager().getUniqueId(), villager);
|
|
||||||
return villager;
|
|
||||||
}
|
|
||||||
|
|
||||||
public @NotNull WrappedVillager add(@NotNull Villager villager) {
|
|
||||||
return this.add(new WrappedVillager(villager));
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean contains(@NotNull UUID uuid) {
|
|
||||||
return this.villagerCache.getIfPresent(uuid) != null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean contains(@NotNull WrappedVillager villager) {
|
|
||||||
return this.contains(villager.villager().getUniqueId());
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean contains(@NotNull Villager villager) {
|
|
||||||
return this.contains(villager.getUniqueId());
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,26 +1,41 @@
|
|||||||
package me.xginko.villageroptimizer;
|
package me.xginko.villageroptimizer;
|
||||||
|
|
||||||
import com.tcoded.folialib.FoliaLib;
|
import com.github.benmanes.caffeine.cache.Cache;
|
||||||
|
import com.github.benmanes.caffeine.cache.Caffeine;
|
||||||
import me.xginko.villageroptimizer.commands.VillagerOptimizerCommand;
|
import me.xginko.villageroptimizer.commands.VillagerOptimizerCommand;
|
||||||
import me.xginko.villageroptimizer.config.Config;
|
import me.xginko.villageroptimizer.config.Config;
|
||||||
import me.xginko.villageroptimizer.config.LanguageCache;
|
import me.xginko.villageroptimizer.config.LanguageCache;
|
||||||
|
import me.xginko.villageroptimizer.struct.enums.Permissions;
|
||||||
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
|
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
|
||||||
import me.xginko.villageroptimizer.utils.Util;
|
import me.xginko.villageroptimizer.utils.Util;
|
||||||
|
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
|
||||||
import net.kyori.adventure.platform.bukkit.BukkitAudiences;
|
import net.kyori.adventure.platform.bukkit.BukkitAudiences;
|
||||||
import net.kyori.adventure.text.Component;
|
import net.kyori.adventure.text.Component;
|
||||||
import net.kyori.adventure.text.format.NamedTextColor;
|
import net.kyori.adventure.text.format.NamedTextColor;
|
||||||
import net.kyori.adventure.text.format.TextDecoration;
|
import net.kyori.adventure.text.format.TextDecoration;
|
||||||
import net.kyori.adventure.text.logger.slf4j.ComponentLogger;
|
import net.kyori.adventure.text.logger.slf4j.ComponentLogger;
|
||||||
|
import org.apache.logging.log4j.Level;
|
||||||
|
import org.apache.logging.log4j.core.config.Configurator;
|
||||||
import org.bstats.bukkit.Metrics;
|
import org.bstats.bukkit.Metrics;
|
||||||
import org.bukkit.command.CommandSender;
|
import org.bukkit.command.CommandSender;
|
||||||
import org.bukkit.entity.Player;
|
import org.bukkit.entity.Player;
|
||||||
|
import org.bukkit.entity.Villager;
|
||||||
import org.bukkit.plugin.java.JavaPlugin;
|
import org.bukkit.plugin.java.JavaPlugin;
|
||||||
import org.jetbrains.annotations.NotNull;
|
import org.jetbrains.annotations.NotNull;
|
||||||
|
import space.arim.morepaperlib.MorePaperLib;
|
||||||
|
import space.arim.morepaperlib.commands.CommandRegistration;
|
||||||
|
import space.arim.morepaperlib.scheduling.GracefulScheduling;
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.FileNotFoundException;
|
import java.io.FileNotFoundException;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.util.*;
|
import java.util.Arrays;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.SortedSet;
|
||||||
|
import java.util.TreeSet;
|
||||||
import java.util.jar.JarFile;
|
import java.util.jar.JarFile;
|
||||||
import java.util.regex.Matcher;
|
import java.util.regex.Matcher;
|
||||||
import java.util.regex.Pattern;
|
import java.util.regex.Pattern;
|
||||||
@ -31,27 +46,47 @@ import java.util.zip.ZipEntry;
|
|||||||
public final class VillagerOptimizer extends JavaPlugin {
|
public final class VillagerOptimizer extends JavaPlugin {
|
||||||
|
|
||||||
private static VillagerOptimizer instance;
|
private static VillagerOptimizer instance;
|
||||||
private static VillagerCache villagerCache;
|
private static CommandRegistration commandRegistration;
|
||||||
private static FoliaLib foliaLib;
|
private static GracefulScheduling scheduling;
|
||||||
|
private static Cache<Villager, WrappedVillager> wrapperCache;
|
||||||
private static Map<String, LanguageCache> languageCacheMap;
|
private static Map<String, LanguageCache> languageCacheMap;
|
||||||
private static Config config;
|
private static Config config;
|
||||||
private static BukkitAudiences audiences;
|
private static BukkitAudiences audiences;
|
||||||
private static ComponentLogger logger;
|
private static ComponentLogger logger;
|
||||||
private static Metrics bStats;
|
private static Metrics bStats;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onLoad() {
|
||||||
|
// Disable reflection logging
|
||||||
|
String shadedLibs = getClass().getPackage().getName() + ".libs";
|
||||||
|
Configurator.setLevel(shadedLibs + ".reflections.Reflections", Level.OFF);
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onEnable() {
|
public void onEnable() {
|
||||||
instance = this;
|
instance = this;
|
||||||
foliaLib = new FoliaLib(this);
|
MorePaperLib morePaperLib = new MorePaperLib(this);
|
||||||
|
commandRegistration = morePaperLib.commandRegistration();
|
||||||
|
scheduling = morePaperLib.scheduling();
|
||||||
audiences = BukkitAudiences.create(this);
|
audiences = BukkitAudiences.create(this);
|
||||||
logger = ComponentLogger.logger(getLogger().getName());
|
logger = ComponentLogger.logger(getLogger().getName());
|
||||||
bStats = new Metrics(this, 19954);
|
bStats = new Metrics(this, 19954);
|
||||||
|
|
||||||
|
if (getServer().getPluginManager().getPlugin("AntiVillagerLag") != null) {
|
||||||
|
logger.warn("While VillagerOptimizer can read data previously created by AVL, running");
|
||||||
|
logger.warn("both plugins at the same time is unsafe and definitely will cause issues.");
|
||||||
|
logger.warn("To protect your game from corruption, VillagerOptimizer will now disable!");
|
||||||
|
logger.warn("Please decide for one of the plugins!");
|
||||||
|
getServer().getPluginManager().disablePlugin(this);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
getDataFolder().mkdirs();
|
getDataFolder().mkdirs();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logger.error("Failed to create plugin directory! Cannot enable!", e);
|
logger.error("Failed to create plugin directory! Cannot enable!", e);
|
||||||
getServer().getPluginManager().disablePlugin(this);
|
getServer().getPluginManager().disablePlugin(this);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.info(Component.text("╭────────────────────────────────────────────────────────────╮").style(Util.PL_STYLE));
|
logger.info(Component.text("╭────────────────────────────────────────────────────────────╮").style(Util.PL_STYLE));
|
||||||
@ -73,6 +108,7 @@ public final class VillagerOptimizer extends JavaPlugin {
|
|||||||
.color(NamedTextColor.GRAY)).append(Component.text(" │").style(Util.PL_STYLE)));
|
.color(NamedTextColor.GRAY)).append(Component.text(" │").style(Util.PL_STYLE)));
|
||||||
logger.info(Component.text("│ │").style(Util.PL_STYLE));
|
logger.info(Component.text("│ │").style(Util.PL_STYLE));
|
||||||
logger.info(Component.text("│ │").style(Util.PL_STYLE));
|
logger.info(Component.text("│ │").style(Util.PL_STYLE));
|
||||||
|
Permissions.registerAll();
|
||||||
|
|
||||||
logger.info(Component.text("│ ")
|
logger.info(Component.text("│ ")
|
||||||
.style(Util.PL_STYLE).append(Component.text(" ➤ Loading Config...").style(Util.PL_STYLE))
|
.style(Util.PL_STYLE).append(Component.text(" ➤ Loading Config...").style(Util.PL_STYLE))
|
||||||
@ -94,15 +130,17 @@ public final class VillagerOptimizer extends JavaPlugin {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onDisable() {
|
public void onDisable() {
|
||||||
VillagerOptimizerModule.MODULES.forEach(VillagerOptimizerModule::disable);
|
VillagerOptimizerModule.ENABLED_MODULES.forEach(VillagerOptimizerModule::disable);
|
||||||
VillagerOptimizerModule.MODULES.clear();
|
VillagerOptimizerModule.ENABLED_MODULES.clear();
|
||||||
if (foliaLib != null) {
|
VillagerOptimizerCommand.COMMANDS.forEach(VillagerOptimizerCommand::disable);
|
||||||
foliaLib.getImpl().cancelAllTasks();
|
VillagerOptimizerCommand.COMMANDS.clear();
|
||||||
foliaLib = null;
|
if (wrapperCache != null) {
|
||||||
|
wrapperCache.cleanUp();
|
||||||
|
wrapperCache = null;
|
||||||
}
|
}
|
||||||
if (villagerCache != null) {
|
if (scheduling != null) {
|
||||||
villagerCache.clear();
|
scheduling.cancelGlobalTasks();
|
||||||
villagerCache = null;
|
scheduling = null;
|
||||||
}
|
}
|
||||||
if (audiences != null) {
|
if (audiences != null) {
|
||||||
audiences.close();
|
audiences.close();
|
||||||
@ -112,36 +150,49 @@ public final class VillagerOptimizer extends JavaPlugin {
|
|||||||
bStats.shutdown();
|
bStats.shutdown();
|
||||||
bStats = null;
|
bStats = null;
|
||||||
}
|
}
|
||||||
config = null;
|
commandRegistration = null;
|
||||||
languageCacheMap = null;
|
languageCacheMap = null;
|
||||||
logger = null;
|
|
||||||
instance = null;
|
instance = null;
|
||||||
|
config = null;
|
||||||
|
logger = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static @NotNull VillagerOptimizer getInstance() {
|
public static @NotNull VillagerOptimizer getInstance() {
|
||||||
return instance;
|
return instance;
|
||||||
}
|
}
|
||||||
public static @NotNull Config getConfiguration() {
|
|
||||||
|
public static @NotNull GracefulScheduling scheduling() {
|
||||||
|
return scheduling;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static @NotNull CommandRegistration commandRegistration() {
|
||||||
|
return commandRegistration;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static @NotNull Cache<Villager, WrappedVillager> wrappers() {
|
||||||
|
return wrapperCache;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static @NotNull Config config() {
|
||||||
return config;
|
return config;
|
||||||
}
|
}
|
||||||
public static @NotNull VillagerCache getCache() {
|
|
||||||
return villagerCache;
|
public static @NotNull ComponentLogger logger() {
|
||||||
}
|
|
||||||
public static @NotNull FoliaLib getFoliaLib() {
|
|
||||||
return foliaLib;
|
|
||||||
}
|
|
||||||
public static @NotNull ComponentLogger getPrefixedLogger() {
|
|
||||||
return logger;
|
return logger;
|
||||||
}
|
}
|
||||||
public static @NotNull BukkitAudiences getAudiences() {
|
|
||||||
|
public static @NotNull BukkitAudiences audiences() {
|
||||||
return audiences;
|
return audiences;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static @NotNull LanguageCache getLang(Locale locale) {
|
public static @NotNull LanguageCache getLang(Locale locale) {
|
||||||
return getLang(locale.toString().toLowerCase());
|
return getLang(locale.toString().toLowerCase());
|
||||||
}
|
}
|
||||||
|
|
||||||
public static @NotNull LanguageCache getLang(CommandSender commandSender) {
|
public static @NotNull LanguageCache getLang(CommandSender commandSender) {
|
||||||
return commandSender instanceof Player ? getLang(((Player) commandSender).locale()) : getLang(config.default_lang);
|
return commandSender instanceof Player ? getLang(((Player) commandSender).locale()) : getLang(config.default_lang);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static @NotNull LanguageCache getLang(String lang) {
|
public static @NotNull LanguageCache getLang(String lang) {
|
||||||
if (!config.auto_lang) return languageCacheMap.get(config.default_lang.toString().toLowerCase());
|
if (!config.auto_lang) return languageCacheMap.get(config.default_lang.toString().toLowerCase());
|
||||||
return languageCacheMap.getOrDefault(lang.replace("-", "_"), languageCacheMap.get(config.default_lang.toString().toLowerCase()));
|
return languageCacheMap.getOrDefault(lang.replace("-", "_"), languageCacheMap.get(config.default_lang.toString().toLowerCase()));
|
||||||
@ -155,8 +206,8 @@ public final class VillagerOptimizer extends JavaPlugin {
|
|||||||
private void reloadConfiguration() {
|
private void reloadConfiguration() {
|
||||||
try {
|
try {
|
||||||
config = new Config();
|
config = new Config();
|
||||||
if (villagerCache != null) villagerCache.clear();
|
if (wrapperCache != null) wrapperCache.cleanUp();
|
||||||
villagerCache = new VillagerCache(config.cache_keep_time_seconds);
|
wrapperCache = Caffeine.newBuilder().expireAfterWrite(config.cache_keep_time).build();
|
||||||
VillagerOptimizerCommand.reloadCommands();
|
VillagerOptimizerCommand.reloadCommands();
|
||||||
VillagerOptimizerModule.reloadModules();
|
VillagerOptimizerModule.reloadModules();
|
||||||
config.saveConfig();
|
config.saveConfig();
|
||||||
@ -202,7 +253,7 @@ public final class VillagerOptimizer extends JavaPlugin {
|
|||||||
.collect(Collectors.toCollection(TreeSet::new));
|
.collect(Collectors.toCollection(TreeSet::new));
|
||||||
} catch (Throwable t) {
|
} catch (Throwable t) {
|
||||||
logger.error("Failed while searching for available translations!", t);
|
logger.error("Failed while searching for available translations!", t);
|
||||||
return new TreeSet<>();
|
return Collections.emptySortedSet();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,11 +1,36 @@
|
|||||||
package me.xginko.villageroptimizer.commands;
|
package me.xginko.villageroptimizer.commands;
|
||||||
|
|
||||||
import net.kyori.adventure.text.TextComponent;
|
import net.kyori.adventure.text.TextComponent;
|
||||||
import org.bukkit.command.CommandSender;
|
import org.bukkit.command.CommandExecutor;
|
||||||
|
import org.bukkit.command.TabCompleter;
|
||||||
|
import org.jetbrains.annotations.NotNull;
|
||||||
|
|
||||||
public abstract class SubCommand {
|
import java.util.Arrays;
|
||||||
public abstract String getLabel();
|
|
||||||
public abstract TextComponent getDescription();
|
public abstract class SubCommand implements CommandExecutor, TabCompleter {
|
||||||
public abstract TextComponent getSyntax();
|
|
||||||
public abstract void perform(CommandSender sender, String[] args);
|
private final String label;
|
||||||
|
private final TextComponent syntax, description;
|
||||||
|
|
||||||
|
public SubCommand(String label, TextComponent syntax, TextComponent description) {
|
||||||
|
this.label = label;
|
||||||
|
this.syntax = syntax;
|
||||||
|
this.description = description;
|
||||||
|
}
|
||||||
|
|
||||||
|
public @NotNull String mergeArgs(@NotNull String[] args, int start) {
|
||||||
|
return String.join(" ", Arrays.copyOfRange(args, start, args.length));
|
||||||
|
}
|
||||||
|
|
||||||
|
public @NotNull String label() {
|
||||||
|
return label;
|
||||||
|
}
|
||||||
|
|
||||||
|
public @NotNull TextComponent syntax() {
|
||||||
|
return syntax;
|
||||||
|
}
|
||||||
|
|
||||||
|
public @NotNull TextComponent description() {
|
||||||
|
return description;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,37 +1,62 @@
|
|||||||
package me.xginko.villageroptimizer.commands;
|
package me.xginko.villageroptimizer.commands;
|
||||||
|
|
||||||
import me.xginko.villageroptimizer.VillagerOptimizer;
|
import me.xginko.villageroptimizer.VillagerOptimizer;
|
||||||
import me.xginko.villageroptimizer.commands.optimizevillagers.OptVillagersRadius;
|
import me.xginko.villageroptimizer.struct.Disableable;
|
||||||
import me.xginko.villageroptimizer.commands.unoptimizevillagers.UnOptVillagersRadius;
|
import me.xginko.villageroptimizer.struct.Enableable;
|
||||||
import me.xginko.villageroptimizer.commands.villageroptimizer.VillagerOptimizerCmd;
|
import org.bukkit.command.CommandException;
|
||||||
import org.bukkit.command.CommandExecutor;
|
import org.bukkit.command.CommandExecutor;
|
||||||
import org.bukkit.command.CommandMap;
|
import org.bukkit.command.PluginCommand;
|
||||||
import org.bukkit.command.TabCompleter;
|
import org.bukkit.command.TabCompleter;
|
||||||
|
import org.jetbrains.annotations.NotNull;
|
||||||
|
import org.reflections.Reflections;
|
||||||
|
import org.reflections.scanners.Scanners;
|
||||||
|
|
||||||
|
import java.lang.reflect.InvocationTargetException;
|
||||||
|
import java.lang.reflect.Modifier;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.Collections;
|
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
public interface VillagerOptimizerCommand extends CommandExecutor, TabCompleter {
|
public abstract class VillagerOptimizerCommand implements Enableable, Disableable, CommandExecutor, TabCompleter {
|
||||||
|
|
||||||
String label();
|
public static final Set<VillagerOptimizerCommand> COMMANDS = new HashSet<>();
|
||||||
|
public static final List<String> RADIUS_SUGGESTIONS = Arrays.asList("5", "10", "25", "50");
|
||||||
|
public static final Reflections COMMANDS_PACKAGE = new Reflections(VillagerOptimizerCommand.class.getPackage().getName());
|
||||||
|
|
||||||
List<String> NO_TABCOMPLETES = Collections.emptyList();
|
public final PluginCommand pluginCommand;
|
||||||
List<String> RADIUS_TABCOMPLETES = Arrays.asList("5", "10", "25", "50");
|
|
||||||
|
|
||||||
HashSet<VillagerOptimizerCommand> commands = new HashSet<>();
|
protected VillagerOptimizerCommand(@NotNull String name) throws CommandException {
|
||||||
|
PluginCommand pluginCommand = VillagerOptimizer.getInstance().getCommand(name);
|
||||||
|
if (pluginCommand != null) this.pluginCommand = pluginCommand;
|
||||||
|
else throw new CommandException("Command cannot be enabled because it's not defined in the plugin.yml.");
|
||||||
|
}
|
||||||
|
|
||||||
static void reloadCommands() {
|
public static void reloadCommands() {
|
||||||
VillagerOptimizer plugin = VillagerOptimizer.getInstance();
|
COMMANDS.forEach(VillagerOptimizerCommand::disable);
|
||||||
CommandMap commandMap = plugin.getServer().getCommandMap();
|
COMMANDS.clear();
|
||||||
commands.forEach(command -> plugin.getCommand(command.label()).unregister(commandMap));
|
|
||||||
commands.clear();
|
|
||||||
|
|
||||||
commands.add(new VillagerOptimizerCmd());
|
for (Class<?> clazz : COMMANDS_PACKAGE.get(Scanners.SubTypes.of(VillagerOptimizerCommand.class).asClass())) {
|
||||||
commands.add(new OptVillagersRadius());
|
if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())) continue;
|
||||||
commands.add(new UnOptVillagersRadius());
|
|
||||||
|
|
||||||
commands.forEach(command -> plugin.getCommand(command.label()).setExecutor(command));
|
try {
|
||||||
|
COMMANDS.add((VillagerOptimizerCommand) clazz.getDeclaredConstructor().newInstance());
|
||||||
|
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
|
||||||
|
VillagerOptimizer.logger().error("Failed initialising command class '{}'.", clazz.getSimpleName(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
COMMANDS.forEach(VillagerOptimizerCommand::enable);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void enable() {
|
||||||
|
pluginCommand.setExecutor(this);
|
||||||
|
pluginCommand.setTabCompleter(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void disable() {
|
||||||
|
pluginCommand.unregister(VillagerOptimizer.commandRegistration().getServerCommandMap());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,14 +1,13 @@
|
|||||||
package me.xginko.villageroptimizer.commands.optimizevillagers;
|
package me.xginko.villageroptimizer.commands.optimizevillagers;
|
||||||
|
|
||||||
import me.xginko.villageroptimizer.VillagerCache;
|
|
||||||
import me.xginko.villageroptimizer.VillagerOptimizer;
|
import me.xginko.villageroptimizer.VillagerOptimizer;
|
||||||
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
|
|
||||||
import me.xginko.villageroptimizer.commands.VillagerOptimizerCommand;
|
import me.xginko.villageroptimizer.commands.VillagerOptimizerCommand;
|
||||||
import me.xginko.villageroptimizer.config.Config;
|
import me.xginko.villageroptimizer.config.Config;
|
||||||
import me.xginko.villageroptimizer.enums.OptimizationType;
|
import me.xginko.villageroptimizer.struct.enums.OptimizationType;
|
||||||
import me.xginko.villageroptimizer.enums.Permissions;
|
import me.xginko.villageroptimizer.struct.enums.Permissions;
|
||||||
import me.xginko.villageroptimizer.events.VillagerOptimizeEvent;
|
import me.xginko.villageroptimizer.events.VillagerOptimizeEvent;
|
||||||
import me.xginko.villageroptimizer.utils.KyoriUtil;
|
import me.xginko.villageroptimizer.utils.KyoriUtil;
|
||||||
|
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
|
||||||
import net.kyori.adventure.text.Component;
|
import net.kyori.adventure.text.Component;
|
||||||
import net.kyori.adventure.text.TextReplacementConfig;
|
import net.kyori.adventure.text.TextReplacementConfig;
|
||||||
import net.kyori.adventure.text.format.NamedTextColor;
|
import net.kyori.adventure.text.format.NamedTextColor;
|
||||||
@ -22,15 +21,17 @@ import org.bukkit.entity.Villager;
|
|||||||
import org.jetbrains.annotations.NotNull;
|
import org.jetbrains.annotations.NotNull;
|
||||||
import org.jetbrains.annotations.Nullable;
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
public class OptVillagersRadius implements VillagerOptimizerCommand {
|
public class OptVillagersRadius extends VillagerOptimizerCommand {
|
||||||
|
|
||||||
private final long cooldown;
|
private final long cooldown;
|
||||||
private final int max_radius;
|
private final int max_radius;
|
||||||
|
|
||||||
public OptVillagersRadius() {
|
public OptVillagersRadius() {
|
||||||
Config config = VillagerOptimizer.getConfiguration();
|
super("optimizevillagers");
|
||||||
|
Config config = VillagerOptimizer.config();
|
||||||
this.max_radius = config.getInt("optimization-methods.commands.optimizevillagers.max-block-radius", 100);
|
this.max_radius = config.getInt("optimization-methods.commands.optimizevillagers.max-block-radius", 100);
|
||||||
this.cooldown = config.getInt("optimization-methods.commands.optimizevillagers.cooldown-seconds", 600,
|
this.cooldown = config.getInt("optimization-methods.commands.optimizevillagers.cooldown-seconds", 600,
|
||||||
"Cooldown in seconds until a villager can be optimized again using the command.\n" +
|
"Cooldown in seconds until a villager can be optimized again using the command.\n" +
|
||||||
@ -38,17 +39,16 @@ public class OptVillagersRadius implements VillagerOptimizerCommand {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String label() {
|
public @Nullable List<String> onTabComplete(
|
||||||
return "optimizevillagers";
|
@NotNull CommandSender sender, @NotNull Command command, @NotNull String commandLabel, @NotNull String[] args
|
||||||
|
) {
|
||||||
|
return args.length == 1 ? RADIUS_SUGGESTIONS : Collections.emptyList();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public @Nullable List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
|
public boolean onCommand(
|
||||||
return args.length == 1 ? RADIUS_TABCOMPLETES : NO_TABCOMPLETES;
|
@NotNull CommandSender sender, @NotNull Command command, @NotNull String commandLabel, @NotNull String[] args
|
||||||
}
|
) {
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
|
|
||||||
if (!sender.hasPermission(Permissions.Commands.OPTIMIZE_RADIUS.get())) {
|
if (!sender.hasPermission(Permissions.Commands.OPTIMIZE_RADIUS.get())) {
|
||||||
KyoriUtil.sendMessage(sender, VillagerOptimizer.getLang(sender).no_permission);
|
KyoriUtil.sendMessage(sender, VillagerOptimizer.getLang(sender).no_permission);
|
||||||
return true;
|
return true;
|
||||||
@ -89,7 +89,6 @@ public class OptVillagersRadius implements VillagerOptimizerCommand {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
VillagerCache villagerCache = VillagerOptimizer.getCache();
|
|
||||||
int successCount = 0;
|
int successCount = 0;
|
||||||
int failCount = 0;
|
int failCount = 0;
|
||||||
final boolean player_has_cooldown_bypass = player.hasPermission(Permissions.Bypass.COMMAND_COOLDOWN.get());
|
final boolean player_has_cooldown_bypass = player.hasPermission(Permissions.Bypass.COMMAND_COOLDOWN.get());
|
||||||
@ -100,7 +99,7 @@ public class OptVillagersRadius implements VillagerOptimizerCommand {
|
|||||||
Villager.Profession profession = villager.getProfession();
|
Villager.Profession profession = villager.getProfession();
|
||||||
if (profession.equals(Villager.Profession.NITWIT) || profession.equals(Villager.Profession.NONE)) continue;
|
if (profession.equals(Villager.Profession.NITWIT) || profession.equals(Villager.Profession.NONE)) continue;
|
||||||
|
|
||||||
WrappedVillager wVillager = villagerCache.getOrAdd(villager);
|
WrappedVillager wVillager = VillagerOptimizer.wrappers().get(villager, WrappedVillager::new);
|
||||||
|
|
||||||
if (player_has_cooldown_bypass || wVillager.canOptimize(cooldown)) {
|
if (player_has_cooldown_bypass || wVillager.canOptimize(cooldown)) {
|
||||||
VillagerOptimizeEvent optimizeEvent = new VillagerOptimizeEvent(wVillager, OptimizationType.COMMAND, player);
|
VillagerOptimizeEvent optimizeEvent = new VillagerOptimizeEvent(wVillager, OptimizationType.COMMAND, player);
|
||||||
|
@ -1,13 +1,12 @@
|
|||||||
package me.xginko.villageroptimizer.commands.unoptimizevillagers;
|
package me.xginko.villageroptimizer.commands.unoptimizevillagers;
|
||||||
|
|
||||||
import me.xginko.villageroptimizer.VillagerCache;
|
|
||||||
import me.xginko.villageroptimizer.VillagerOptimizer;
|
import me.xginko.villageroptimizer.VillagerOptimizer;
|
||||||
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
|
|
||||||
import me.xginko.villageroptimizer.commands.VillagerOptimizerCommand;
|
import me.xginko.villageroptimizer.commands.VillagerOptimizerCommand;
|
||||||
import me.xginko.villageroptimizer.enums.OptimizationType;
|
import me.xginko.villageroptimizer.struct.enums.OptimizationType;
|
||||||
import me.xginko.villageroptimizer.enums.Permissions;
|
import me.xginko.villageroptimizer.struct.enums.Permissions;
|
||||||
import me.xginko.villageroptimizer.events.VillagerUnoptimizeEvent;
|
import me.xginko.villageroptimizer.events.VillagerUnoptimizeEvent;
|
||||||
import me.xginko.villageroptimizer.utils.KyoriUtil;
|
import me.xginko.villageroptimizer.utils.KyoriUtil;
|
||||||
|
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
|
||||||
import net.kyori.adventure.text.Component;
|
import net.kyori.adventure.text.Component;
|
||||||
import net.kyori.adventure.text.TextReplacementConfig;
|
import net.kyori.adventure.text.TextReplacementConfig;
|
||||||
import net.kyori.adventure.text.format.NamedTextColor;
|
import net.kyori.adventure.text.format.NamedTextColor;
|
||||||
@ -21,29 +20,30 @@ import org.bukkit.entity.Villager;
|
|||||||
import org.jetbrains.annotations.NotNull;
|
import org.jetbrains.annotations.NotNull;
|
||||||
import org.jetbrains.annotations.Nullable;
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
public class UnOptVillagersRadius implements VillagerOptimizerCommand {
|
public class UnOptVillagersRadius extends VillagerOptimizerCommand {
|
||||||
|
|
||||||
private final int max_radius;
|
private final int max_radius;
|
||||||
|
|
||||||
public UnOptVillagersRadius() {
|
public UnOptVillagersRadius() {
|
||||||
this.max_radius = VillagerOptimizer.getConfiguration()
|
super("unoptimizevillagers");
|
||||||
|
this.max_radius = VillagerOptimizer.config()
|
||||||
.getInt("optimization-methods.commands.unoptimizevillagers.max-block-radius", 100);
|
.getInt("optimization-methods.commands.unoptimizevillagers.max-block-radius", 100);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String label() {
|
public @Nullable List<String> onTabComplete(
|
||||||
return "unoptimizevillagers";
|
@NotNull CommandSender sender, @NotNull Command command, @NotNull String commandLabel, @NotNull String[] args
|
||||||
|
) {
|
||||||
|
return args.length == 1 ? RADIUS_SUGGESTIONS : Collections.emptyList();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public @Nullable List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
|
public boolean onCommand(
|
||||||
return args.length == 1 ? RADIUS_TABCOMPLETES : NO_TABCOMPLETES;
|
@NotNull CommandSender sender, @NotNull Command command, @NotNull String commandLabel, @NotNull String[] args
|
||||||
}
|
) {
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
|
|
||||||
if (!sender.hasPermission(Permissions.Commands.UNOPTIMIZE_RADIUS.get())) {
|
if (!sender.hasPermission(Permissions.Commands.UNOPTIMIZE_RADIUS.get())) {
|
||||||
KyoriUtil.sendMessage(sender, VillagerOptimizer.getLang(sender).no_permission);
|
KyoriUtil.sendMessage(sender, VillagerOptimizer.getLang(sender).no_permission);
|
||||||
return true;
|
return true;
|
||||||
@ -84,7 +84,6 @@ public class UnOptVillagersRadius implements VillagerOptimizerCommand {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
VillagerCache villagerCache = VillagerOptimizer.getCache();
|
|
||||||
int successCount = 0;
|
int successCount = 0;
|
||||||
|
|
||||||
for (Entity entity : player.getNearbyEntities(safeRadius, safeRadius, safeRadius)) {
|
for (Entity entity : player.getNearbyEntities(safeRadius, safeRadius, safeRadius)) {
|
||||||
@ -93,7 +92,7 @@ public class UnOptVillagersRadius implements VillagerOptimizerCommand {
|
|||||||
Villager.Profession profession = villager.getProfession();
|
Villager.Profession profession = villager.getProfession();
|
||||||
if (profession.equals(Villager.Profession.NITWIT) || profession.equals(Villager.Profession.NONE)) continue;
|
if (profession.equals(Villager.Profession.NITWIT) || profession.equals(Villager.Profession.NONE)) continue;
|
||||||
|
|
||||||
WrappedVillager wVillager = villagerCache.getOrAdd(villager);
|
WrappedVillager wVillager = VillagerOptimizer.wrappers().get(villager, WrappedVillager::new);
|
||||||
|
|
||||||
if (wVillager.isOptimized()) {
|
if (wVillager.isOptimized()) {
|
||||||
VillagerUnoptimizeEvent unOptimizeEvent = new VillagerUnoptimizeEvent(wVillager, player, OptimizationType.COMMAND);
|
VillagerUnoptimizeEvent unOptimizeEvent = new VillagerUnoptimizeEvent(wVillager, player, OptimizationType.COMMAND);
|
||||||
|
@ -5,64 +5,74 @@ import me.xginko.villageroptimizer.commands.VillagerOptimizerCommand;
|
|||||||
import me.xginko.villageroptimizer.commands.villageroptimizer.subcommands.DisableSubCmd;
|
import me.xginko.villageroptimizer.commands.villageroptimizer.subcommands.DisableSubCmd;
|
||||||
import me.xginko.villageroptimizer.commands.villageroptimizer.subcommands.ReloadSubCmd;
|
import me.xginko.villageroptimizer.commands.villageroptimizer.subcommands.ReloadSubCmd;
|
||||||
import me.xginko.villageroptimizer.commands.villageroptimizer.subcommands.VersionSubCmd;
|
import me.xginko.villageroptimizer.commands.villageroptimizer.subcommands.VersionSubCmd;
|
||||||
import me.xginko.villageroptimizer.enums.Permissions;
|
import me.xginko.villageroptimizer.struct.enums.Permissions;
|
||||||
import me.xginko.villageroptimizer.utils.Util;
|
|
||||||
import me.xginko.villageroptimizer.utils.KyoriUtil;
|
import me.xginko.villageroptimizer.utils.KyoriUtil;
|
||||||
|
import me.xginko.villageroptimizer.utils.Util;
|
||||||
import net.kyori.adventure.text.Component;
|
import net.kyori.adventure.text.Component;
|
||||||
import net.kyori.adventure.text.format.NamedTextColor;
|
import net.kyori.adventure.text.format.NamedTextColor;
|
||||||
import org.bukkit.command.Command;
|
import org.bukkit.command.Command;
|
||||||
import org.bukkit.command.CommandSender;
|
import org.bukkit.command.CommandSender;
|
||||||
import org.jetbrains.annotations.NotNull;
|
import org.jetbrains.annotations.NotNull;
|
||||||
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
|
import java.util.Collections;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
public class VillagerOptimizerCmd implements VillagerOptimizerCommand {
|
public class VillagerOptimizerCmd extends VillagerOptimizerCommand {
|
||||||
|
|
||||||
private final List<SubCommand> subCommands;
|
private final List<SubCommand> subCommands;
|
||||||
private final List<String> tabCompleter;
|
private final List<String> tabCompletes;
|
||||||
|
|
||||||
public VillagerOptimizerCmd() {
|
public VillagerOptimizerCmd() {
|
||||||
|
super("villageroptimizer");
|
||||||
subCommands = Arrays.asList(new ReloadSubCmd(), new VersionSubCmd(), new DisableSubCmd());
|
subCommands = Arrays.asList(new ReloadSubCmd(), new VersionSubCmd(), new DisableSubCmd());
|
||||||
tabCompleter = subCommands.stream().map(SubCommand::getLabel).collect(Collectors.toList());
|
tabCompletes = subCommands.stream().map(SubCommand::label).collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String label() {
|
public @Nullable List<String> onTabComplete(
|
||||||
return "villageroptimizer";
|
@NotNull CommandSender sender, @NotNull Command command, @NotNull String commandLabel, @NotNull String[] args
|
||||||
}
|
) {
|
||||||
|
if (args.length == 1) {
|
||||||
@Override
|
return tabCompletes;
|
||||||
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) {
|
|
||||||
return args.length == 1 ? tabCompleter : NO_TABCOMPLETES;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
|
|
||||||
if (args.length == 0) {
|
|
||||||
sendCommandOverview(sender);
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
for (final SubCommand subCommand : subCommands) {
|
if (args.length >= 2) {
|
||||||
if (args[0].equalsIgnoreCase(subCommand.getLabel())) {
|
for (SubCommand subCommand : subCommands) {
|
||||||
subCommand.perform(sender, args);
|
if (args[0].equalsIgnoreCase(subCommand.label())) {
|
||||||
return true;
|
return subCommand.onTabComplete(sender, command, commandLabel, args);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
sendCommandOverview(sender);
|
return Collections.emptyList();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean onCommand(
|
||||||
|
@NotNull CommandSender sender, @NotNull Command command, @NotNull String commandLabel, @NotNull String[] args
|
||||||
|
) {
|
||||||
|
if (args.length >= 1) {
|
||||||
|
for (SubCommand subCommand : subCommands) {
|
||||||
|
if (args[0].equalsIgnoreCase(subCommand.label())) {
|
||||||
|
return subCommand.onCommand(sender, command, commandLabel, args);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
overview(sender);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void sendCommandOverview(CommandSender sender) {
|
private void overview(CommandSender sender) {
|
||||||
if (!sender.hasPermission(Permissions.Commands.RELOAD.get()) && !sender.hasPermission(Permissions.Commands.VERSION.get())) return;
|
if (!sender.hasPermission(Permissions.Commands.RELOAD.get()) && !sender.hasPermission(Permissions.Commands.VERSION.get())) return;
|
||||||
KyoriUtil.sendMessage(sender, Component.text("-----------------------------------------------------").color(NamedTextColor.GRAY));
|
KyoriUtil.sendMessage(sender, Component.text("-----------------------------------------------------").color(NamedTextColor.GRAY));
|
||||||
KyoriUtil.sendMessage(sender, Component.text("VillagerOptimizer Commands").color(Util.PL_COLOR));
|
KyoriUtil.sendMessage(sender, Component.text("VillagerOptimizer Commands").color(Util.PL_COLOR));
|
||||||
KyoriUtil.sendMessage(sender, Component.text("-----------------------------------------------------").color(NamedTextColor.GRAY));
|
KyoriUtil.sendMessage(sender, Component.text("-----------------------------------------------------").color(NamedTextColor.GRAY));
|
||||||
subCommands.forEach(subCommand -> KyoriUtil.sendMessage(sender,
|
subCommands.forEach(subCommand -> KyoriUtil.sendMessage(sender,
|
||||||
subCommand.getSyntax().append(Component.text(" - ").color(NamedTextColor.DARK_GRAY)).append(subCommand.getDescription())));
|
subCommand.syntax().append(Component.text(" - ").color(NamedTextColor.DARK_GRAY)).append(subCommand.description())));
|
||||||
KyoriUtil.sendMessage(sender,
|
KyoriUtil.sendMessage(sender,
|
||||||
Component.text("/optimizevillagers <blockradius>").color(Util.PL_COLOR)
|
Component.text("/optimizevillagers <blockradius>").color(Util.PL_COLOR)
|
||||||
.append(Component.text(" - ").color(NamedTextColor.DARK_GRAY))
|
.append(Component.text(" - ").color(NamedTextColor.DARK_GRAY))
|
||||||
|
@ -2,44 +2,51 @@ package me.xginko.villageroptimizer.commands.villageroptimizer.subcommands;
|
|||||||
|
|
||||||
import me.xginko.villageroptimizer.VillagerOptimizer;
|
import me.xginko.villageroptimizer.VillagerOptimizer;
|
||||||
import me.xginko.villageroptimizer.commands.SubCommand;
|
import me.xginko.villageroptimizer.commands.SubCommand;
|
||||||
import me.xginko.villageroptimizer.enums.Permissions;
|
import me.xginko.villageroptimizer.struct.enums.Permissions;
|
||||||
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
|
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
|
||||||
import me.xginko.villageroptimizer.utils.Util;
|
|
||||||
import me.xginko.villageroptimizer.utils.KyoriUtil;
|
import me.xginko.villageroptimizer.utils.KyoriUtil;
|
||||||
|
import me.xginko.villageroptimizer.utils.Util;
|
||||||
import net.kyori.adventure.text.Component;
|
import net.kyori.adventure.text.Component;
|
||||||
import net.kyori.adventure.text.TextComponent;
|
|
||||||
import net.kyori.adventure.text.format.NamedTextColor;
|
import net.kyori.adventure.text.format.NamedTextColor;
|
||||||
|
import org.bukkit.command.Command;
|
||||||
import org.bukkit.command.CommandSender;
|
import org.bukkit.command.CommandSender;
|
||||||
|
import org.jetbrains.annotations.NotNull;
|
||||||
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
public class DisableSubCmd extends SubCommand {
|
public class DisableSubCmd extends SubCommand {
|
||||||
|
|
||||||
@Override
|
public DisableSubCmd() {
|
||||||
public String getLabel() {
|
super(
|
||||||
return "disable";
|
"disable",
|
||||||
|
Component.text("/villageroptimizer disable").color(Util.PL_COLOR),
|
||||||
|
Component.text("Disable all plugin tasks and listeners.").color(NamedTextColor.GRAY)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TextComponent getDescription() {
|
public @Nullable List<String> onTabComplete(
|
||||||
return Component.text("Disable all plugin tasks and listeners.").color(NamedTextColor.GRAY);
|
@NotNull CommandSender sender, @NotNull Command command, @NotNull String commandLabel, @NotNull String[] args
|
||||||
|
) {
|
||||||
|
return Collections.emptyList();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TextComponent getSyntax() {
|
public boolean onCommand(
|
||||||
return Component.text("/villageroptimizer disable").color(Util.PL_COLOR);
|
@NotNull CommandSender sender, @NotNull Command command, @NotNull String commandLabel, @NotNull String[] args
|
||||||
}
|
) {
|
||||||
|
|
||||||
@Override
|
|
||||||
public void perform(CommandSender sender, String[] args) {
|
|
||||||
if (!sender.hasPermission(Permissions.Commands.DISABLE.get())) {
|
if (!sender.hasPermission(Permissions.Commands.DISABLE.get())) {
|
||||||
KyoriUtil.sendMessage(sender, VillagerOptimizer.getLang(sender).no_permission);
|
KyoriUtil.sendMessage(sender, VillagerOptimizer.getLang(sender).no_permission);
|
||||||
return;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
KyoriUtil.sendMessage(sender, Component.text("Disabling VillagerOptimizer...").color(NamedTextColor.RED));
|
KyoriUtil.sendMessage(sender, Component.text("Disabling VillagerOptimizer...").color(NamedTextColor.RED));
|
||||||
VillagerOptimizerModule.MODULES.forEach(VillagerOptimizerModule::disable);
|
VillagerOptimizerModule.ENABLED_MODULES.forEach(VillagerOptimizerModule::disable);
|
||||||
VillagerOptimizerModule.MODULES.clear();
|
VillagerOptimizerModule.ENABLED_MODULES.clear();
|
||||||
VillagerOptimizer.getCache().cacheMap().clear();
|
|
||||||
KyoriUtil.sendMessage(sender, Component.text("Disabled all plugin listeners and tasks.").color(NamedTextColor.GREEN));
|
KyoriUtil.sendMessage(sender, Component.text("Disabled all plugin listeners and tasks.").color(NamedTextColor.GREEN));
|
||||||
KyoriUtil.sendMessage(sender, Component.text("You can enable the plugin again using the reload command.").color(NamedTextColor.YELLOW));
|
KyoriUtil.sendMessage(sender, Component.text("You can enable the plugin again using the reload command.").color(NamedTextColor.YELLOW));
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -2,42 +2,49 @@ package me.xginko.villageroptimizer.commands.villageroptimizer.subcommands;
|
|||||||
|
|
||||||
import me.xginko.villageroptimizer.VillagerOptimizer;
|
import me.xginko.villageroptimizer.VillagerOptimizer;
|
||||||
import me.xginko.villageroptimizer.commands.SubCommand;
|
import me.xginko.villageroptimizer.commands.SubCommand;
|
||||||
import me.xginko.villageroptimizer.enums.Permissions;
|
import me.xginko.villageroptimizer.struct.enums.Permissions;
|
||||||
import me.xginko.villageroptimizer.utils.Util;
|
|
||||||
import me.xginko.villageroptimizer.utils.KyoriUtil;
|
import me.xginko.villageroptimizer.utils.KyoriUtil;
|
||||||
|
import me.xginko.villageroptimizer.utils.Util;
|
||||||
import net.kyori.adventure.text.Component;
|
import net.kyori.adventure.text.Component;
|
||||||
import net.kyori.adventure.text.TextComponent;
|
|
||||||
import net.kyori.adventure.text.format.NamedTextColor;
|
import net.kyori.adventure.text.format.NamedTextColor;
|
||||||
|
import org.bukkit.command.Command;
|
||||||
import org.bukkit.command.CommandSender;
|
import org.bukkit.command.CommandSender;
|
||||||
|
import org.jetbrains.annotations.NotNull;
|
||||||
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
public class ReloadSubCmd extends SubCommand {
|
public class ReloadSubCmd extends SubCommand {
|
||||||
|
|
||||||
@Override
|
public ReloadSubCmd() {
|
||||||
public String getLabel() {
|
super(
|
||||||
return "reload";
|
"reload",
|
||||||
|
Component.text("/villageroptimizer reload").color(Util.PL_COLOR),
|
||||||
|
Component.text("Reload the plugin configuration.").color(NamedTextColor.GRAY));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TextComponent getDescription() {
|
public @Nullable List<String> onTabComplete(
|
||||||
return Component.text("Reload the plugin configuration.").color(NamedTextColor.GRAY);
|
@NotNull CommandSender sender, @NotNull Command command, @NotNull String commandLabel, @NotNull String[] args
|
||||||
|
) {
|
||||||
|
return Collections.emptyList();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TextComponent getSyntax() {
|
public boolean onCommand(
|
||||||
return Component.text("/villageroptimizer reload").color(Util.PL_COLOR);
|
@NotNull CommandSender sender, @NotNull Command command, @NotNull String commandLabel, @NotNull String[] args
|
||||||
}
|
) {
|
||||||
|
|
||||||
@Override
|
|
||||||
public void perform(CommandSender sender, String[] args) {
|
|
||||||
if (!sender.hasPermission(Permissions.Commands.RELOAD.get())) {
|
if (!sender.hasPermission(Permissions.Commands.RELOAD.get())) {
|
||||||
KyoriUtil.sendMessage(sender, VillagerOptimizer.getLang(sender).no_permission);
|
KyoriUtil.sendMessage(sender, VillagerOptimizer.getLang(sender).no_permission);
|
||||||
return;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
KyoriUtil.sendMessage(sender, Component.text("Reloading VillagerOptimizer...").color(NamedTextColor.WHITE));
|
KyoriUtil.sendMessage(sender, Component.text("Reloading VillagerOptimizer...").color(NamedTextColor.WHITE));
|
||||||
VillagerOptimizer.getFoliaLib().getImpl().runNextTick(reload -> { // Reload in sync with the server
|
VillagerOptimizer.scheduling().asyncScheduler().run(reload -> {
|
||||||
VillagerOptimizer.getInstance().reloadPlugin();
|
VillagerOptimizer.getInstance().reloadPlugin();
|
||||||
KyoriUtil.sendMessage(sender, Component.text("Reload complete.").color(NamedTextColor.GREEN));
|
KyoriUtil.sendMessage(sender, Component.text("Reload complete.").color(NamedTextColor.GREEN));
|
||||||
});
|
});
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -3,39 +3,45 @@ package me.xginko.villageroptimizer.commands.villageroptimizer.subcommands;
|
|||||||
import io.papermc.paper.plugin.configuration.PluginMeta;
|
import io.papermc.paper.plugin.configuration.PluginMeta;
|
||||||
import me.xginko.villageroptimizer.VillagerOptimizer;
|
import me.xginko.villageroptimizer.VillagerOptimizer;
|
||||||
import me.xginko.villageroptimizer.commands.SubCommand;
|
import me.xginko.villageroptimizer.commands.SubCommand;
|
||||||
import me.xginko.villageroptimizer.enums.Permissions;
|
import me.xginko.villageroptimizer.struct.enums.Permissions;
|
||||||
import me.xginko.villageroptimizer.utils.Util;
|
|
||||||
import me.xginko.villageroptimizer.utils.KyoriUtil;
|
import me.xginko.villageroptimizer.utils.KyoriUtil;
|
||||||
|
import me.xginko.villageroptimizer.utils.Util;
|
||||||
import net.kyori.adventure.text.Component;
|
import net.kyori.adventure.text.Component;
|
||||||
import net.kyori.adventure.text.TextComponent;
|
|
||||||
import net.kyori.adventure.text.event.ClickEvent;
|
import net.kyori.adventure.text.event.ClickEvent;
|
||||||
import net.kyori.adventure.text.format.NamedTextColor;
|
import net.kyori.adventure.text.format.NamedTextColor;
|
||||||
|
import org.bukkit.command.Command;
|
||||||
import org.bukkit.command.CommandSender;
|
import org.bukkit.command.CommandSender;
|
||||||
import org.bukkit.plugin.PluginDescriptionFile;
|
import org.bukkit.plugin.PluginDescriptionFile;
|
||||||
|
import org.jetbrains.annotations.NotNull;
|
||||||
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
public class VersionSubCmd extends SubCommand {
|
public class VersionSubCmd extends SubCommand {
|
||||||
|
|
||||||
@Override
|
public VersionSubCmd() {
|
||||||
public String getLabel() {
|
super(
|
||||||
return "version";
|
"version",
|
||||||
|
Component.text("/villageroptimizer version").color(Util.PL_COLOR),
|
||||||
|
Component.text("Show the plugin version.").color(NamedTextColor.GRAY)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TextComponent getDescription() {
|
public @Nullable List<String> onTabComplete(
|
||||||
return Component.text("Show the plugin version.").color(NamedTextColor.GRAY);
|
@NotNull CommandSender sender, @NotNull Command command, @NotNull String commandLabel, @NotNull String[] args
|
||||||
|
) {
|
||||||
|
return Collections.emptyList();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TextComponent getSyntax() {
|
public boolean onCommand(
|
||||||
return Component.text("/villageroptimizer version").color(Util.PL_COLOR);
|
@NotNull CommandSender sender, @NotNull Command command, @NotNull String commandLabel, @NotNull String[] args
|
||||||
}
|
) {
|
||||||
|
|
||||||
@Override
|
|
||||||
@SuppressWarnings({"deprecation", "UnstableApiUsage"})
|
|
||||||
public void perform(CommandSender sender, String[] args) {
|
|
||||||
if (!sender.hasPermission(Permissions.Commands.VERSION.get())) {
|
if (!sender.hasPermission(Permissions.Commands.VERSION.get())) {
|
||||||
KyoriUtil.sendMessage(sender, VillagerOptimizer.getLang(sender).no_permission);
|
KyoriUtil.sendMessage(sender, VillagerOptimizer.getLang(sender).no_permission);
|
||||||
return;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
String name, version, website, author;
|
String name, version, website, author;
|
||||||
@ -68,5 +74,7 @@ public class VersionSubCmd extends SubCommand {
|
|||||||
)
|
)
|
||||||
.append(Component.newline())
|
.append(Component.newline())
|
||||||
);
|
);
|
||||||
|
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -5,6 +5,7 @@ import me.xginko.villageroptimizer.VillagerOptimizer;
|
|||||||
import org.jetbrains.annotations.NotNull;
|
import org.jetbrains.annotations.NotNull;
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
|
import java.time.Duration;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
|
|
||||||
@ -12,8 +13,8 @@ public class Config {
|
|||||||
|
|
||||||
private final @NotNull ConfigFile config;
|
private final @NotNull ConfigFile config;
|
||||||
public final @NotNull Locale default_lang;
|
public final @NotNull Locale default_lang;
|
||||||
|
public final @NotNull Duration cache_keep_time;
|
||||||
public final boolean auto_lang, support_other_plugins;
|
public final boolean auto_lang, support_other_plugins;
|
||||||
public final long cache_keep_time_seconds;
|
|
||||||
|
|
||||||
public Config() throws Exception {
|
public Config() throws Exception {
|
||||||
// Load config.yml with ConfigMaster
|
// Load config.yml with ConfigMaster
|
||||||
@ -23,22 +24,25 @@ public class Config {
|
|||||||
|
|
||||||
this.default_lang = Locale.forLanguageTag(
|
this.default_lang = Locale.forLanguageTag(
|
||||||
getString("general.default-language", "en_us",
|
getString("general.default-language", "en_us",
|
||||||
"The default language that will be used if auto-language is false or no matching language file was found.")
|
"The default language that will be used if auto-language is false\n" +
|
||||||
|
"or no matching language file was found.")
|
||||||
.replace("_", "-"));
|
.replace("_", "-"));
|
||||||
this.auto_lang = getBoolean("general.auto-language", true,
|
this.auto_lang = getBoolean("general.auto-language", true,
|
||||||
"If set to true, will display messages based on client language");
|
"If set to true, will display messages based on client language");
|
||||||
this.cache_keep_time_seconds = getInt("general.cache-keep-time-seconds", 30,
|
this.cache_keep_time = Duration.ofSeconds(Math.max(1, getInt("general.cache-keep-time-seconds", 30,
|
||||||
"The amount of time in seconds a villager will be kept in the plugin's cache.");
|
"The amount of time in seconds a villager will be kept in the plugin's cache.")));
|
||||||
this.support_other_plugins = getBoolean("general.support-avl-villagers", false,
|
this.support_other_plugins = getBoolean("general.support-avl-villagers", false,
|
||||||
"Enable if you have previously used AntiVillagerLag (https://www.spigotmc.org/resources/antivillagerlag.102949/).\n" +
|
"Enable if you have previously used AntiVillagerLag\n" +
|
||||||
"Tries to read pre-existing info like optimization state so players don't need to reoptimize their villagers.");
|
"(https://www.spigotmc.org/resources/antivillagerlag.102949/).\n" +
|
||||||
|
"Tries to read pre-existing info like optimization state so players\n" +
|
||||||
|
"don't need to reoptimize their villagers.");
|
||||||
}
|
}
|
||||||
|
|
||||||
public void saveConfig() {
|
public void saveConfig() {
|
||||||
try {
|
try {
|
||||||
this.config.save();
|
this.config.save();
|
||||||
} catch (Throwable throwable) {
|
} catch (Throwable throwable) {
|
||||||
VillagerOptimizer.getPrefixedLogger().error("Failed to save config file!", throwable);
|
VillagerOptimizer.logger().error("Failed to save config file!", throwable);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -114,13 +118,13 @@ public class Config {
|
|||||||
return this.config.getInteger(path, def);
|
return this.config.getInteger(path, def);
|
||||||
}
|
}
|
||||||
|
|
||||||
public @NotNull List<String> getList(@NotNull String path, @NotNull List<String> def, @NotNull String comment) {
|
public @NotNull <T> List<T> getList(@NotNull String path, @NotNull List<T> def, @NotNull String comment) {
|
||||||
this.config.addDefault(path, def, comment);
|
this.config.addDefault(path, def, comment);
|
||||||
return this.config.getStringList(path);
|
return this.config.getList(path);
|
||||||
}
|
}
|
||||||
|
|
||||||
public @NotNull List<String> getList(@NotNull String path, @NotNull List<String> def) {
|
public @NotNull <T> List<T> getList(@NotNull String path, @NotNull List<T> def) {
|
||||||
this.config.addDefault(path, def);
|
this.config.addDefault(path, def);
|
||||||
return this.config.getStringList(path);
|
return this.config.getList(path);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -20,6 +20,7 @@ public class LanguageCache {
|
|||||||
public final @NotNull List<Component> nametag_optimize_success, nametag_on_optimize_cooldown, nametag_unoptimize_success,
|
public final @NotNull List<Component> nametag_optimize_success, nametag_on_optimize_cooldown, nametag_unoptimize_success,
|
||||||
block_optimize_success, block_on_optimize_cooldown, block_unoptimize_success,
|
block_optimize_success, block_on_optimize_cooldown, block_unoptimize_success,
|
||||||
workstation_optimize_success, workstation_on_optimize_cooldown, workstation_unoptimize_success,
|
workstation_optimize_success, workstation_on_optimize_cooldown, workstation_unoptimize_success,
|
||||||
|
activity_optimize_success,
|
||||||
command_optimize_success, command_radius_limit_exceed, command_optimize_fail, command_unoptimize_success,
|
command_optimize_success, command_radius_limit_exceed, command_optimize_fail, command_unoptimize_success,
|
||||||
command_specify_radius, command_radius_invalid, command_no_villagers_nearby,
|
command_specify_radius, command_radius_invalid, command_no_villagers_nearby,
|
||||||
trades_restocked, optimize_for_trading, villager_leveling_up;
|
trades_restocked, optimize_for_trading, villager_leveling_up;
|
||||||
@ -30,7 +31,7 @@ public class LanguageCache {
|
|||||||
// Check if the lang folder has already been created
|
// Check if the lang folder has already been created
|
||||||
File parent = langYML.getParentFile();
|
File parent = langYML.getParentFile();
|
||||||
if (!parent.exists() && !parent.mkdir())
|
if (!parent.exists() && !parent.mkdir())
|
||||||
VillagerOptimizer.getPrefixedLogger().error("Failed to create lang directory.");
|
VillagerOptimizer.logger().error("Failed to create lang directory.");
|
||||||
// Check if the file already exists and save the one from the plugin's resources folder if it does not
|
// Check if the file already exists and save the one from the plugin's resources folder if it does not
|
||||||
if (!langYML.exists())
|
if (!langYML.exists())
|
||||||
plugin.saveResource("lang/" + locale + ".yml", false);
|
plugin.saveResource("lang/" + locale + ".yml", false);
|
||||||
@ -67,6 +68,10 @@ public class LanguageCache {
|
|||||||
"<gray>You need to wait %time% until you can optimize this villager again.");
|
"<gray>You need to wait %time% until you can optimize this villager again.");
|
||||||
this.workstation_unoptimize_success = getListTranslation("messages.workstation.unoptimize-success",
|
this.workstation_unoptimize_success = getListTranslation("messages.workstation.unoptimize-success",
|
||||||
"<green>Successfully unoptimized %villagertype% villager by removing workstation block %blocktype%.");
|
"<green>Successfully unoptimized %villagertype% villager by removing workstation block %blocktype%.");
|
||||||
|
// Activity
|
||||||
|
this.activity_optimize_success = getListTranslation("messages.activity.optimized-near-you",
|
||||||
|
"<gray>%amount% villagers close to you were automatically optimized due to high activity.");
|
||||||
|
|
||||||
// Command
|
// Command
|
||||||
this.command_optimize_success = getListTranslation("messages.command.optimize-success",
|
this.command_optimize_success = getListTranslation("messages.command.optimize-success",
|
||||||
"<green>Successfully optimized %amount% villager(s) in a radius of %radius% blocks.");
|
"<green>Successfully optimized %amount% villager(s) in a radius of %radius% blocks.");
|
||||||
@ -86,7 +91,7 @@ public class LanguageCache {
|
|||||||
try {
|
try {
|
||||||
this.lang.save();
|
this.lang.save();
|
||||||
} catch (Throwable throwable) {
|
} catch (Throwable throwable) {
|
||||||
VillagerOptimizer.getPrefixedLogger().error("Failed to save language file: " + langYML.getName(), throwable);
|
VillagerOptimizer.logger().error("Failed to save language file: " + langYML.getName(), throwable);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
package me.xginko.villageroptimizer.events;
|
package me.xginko.villageroptimizer.events;
|
||||||
|
|
||||||
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
|
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
|
||||||
import me.xginko.villageroptimizer.enums.OptimizationType;
|
import me.xginko.villageroptimizer.struct.enums.OptimizationType;
|
||||||
import org.bukkit.entity.Player;
|
import org.bukkit.entity.Player;
|
||||||
import org.bukkit.event.Cancellable;
|
import org.bukkit.event.Cancellable;
|
||||||
import org.bukkit.event.Event;
|
import org.bukkit.event.Event;
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
package me.xginko.villageroptimizer.events;
|
package me.xginko.villageroptimizer.events;
|
||||||
|
|
||||||
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
|
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
|
||||||
import me.xginko.villageroptimizer.enums.OptimizationType;
|
import me.xginko.villageroptimizer.struct.enums.OptimizationType;
|
||||||
import org.bukkit.entity.Player;
|
import org.bukkit.entity.Player;
|
||||||
import org.bukkit.event.Cancellable;
|
import org.bukkit.event.Cancellable;
|
||||||
import org.bukkit.event.Event;
|
import org.bukkit.event.Event;
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
package me.xginko.villageroptimizer.utils;
|
package me.xginko.villageroptimizer.logging;
|
||||||
|
|
||||||
import net.kyori.adventure.text.logger.slf4j.ComponentLogger;
|
import net.kyori.adventure.text.logger.slf4j.ComponentLogger;
|
||||||
import net.kyori.adventure.text.logger.slf4j.ComponentLoggerProvider;
|
import net.kyori.adventure.text.logger.slf4j.ComponentLoggerProvider;
|
@ -1,4 +1,4 @@
|
|||||||
package me.xginko.villageroptimizer.utils;
|
package me.xginko.villageroptimizer.logging;
|
||||||
|
|
||||||
import net.kyori.adventure.text.Component;
|
import net.kyori.adventure.text.Component;
|
||||||
import net.kyori.adventure.text.TranslatableComponent;
|
import net.kyori.adventure.text.TranslatableComponent;
|
@ -1,17 +1,13 @@
|
|||||||
package me.xginko.villageroptimizer.modules;
|
package me.xginko.villageroptimizer.modules;
|
||||||
|
|
||||||
import com.tcoded.folialib.impl.ServerImplementation;
|
import com.cryptomorin.xseries.XEntityType;
|
||||||
import com.tcoded.folialib.wrapper.task.WrappedTask;
|
import me.xginko.villageroptimizer.struct.models.ExpiringSet;
|
||||||
import me.xginko.villageroptimizer.VillagerCache;
|
|
||||||
import me.xginko.villageroptimizer.VillagerOptimizer;
|
|
||||||
import me.xginko.villageroptimizer.config.Config;
|
|
||||||
import me.xginko.villageroptimizer.utils.Util;
|
|
||||||
import me.xginko.villageroptimizer.utils.LocationUtil;
|
import me.xginko.villageroptimizer.utils.LocationUtil;
|
||||||
|
import me.xginko.villageroptimizer.utils.Util;
|
||||||
|
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
|
||||||
import org.bukkit.Chunk;
|
import org.bukkit.Chunk;
|
||||||
import org.bukkit.Server;
|
|
||||||
import org.bukkit.World;
|
import org.bukkit.World;
|
||||||
import org.bukkit.entity.Entity;
|
import org.bukkit.entity.Entity;
|
||||||
import org.bukkit.entity.EntityType;
|
|
||||||
import org.bukkit.entity.Villager;
|
import org.bukkit.entity.Villager;
|
||||||
import org.bukkit.event.EventHandler;
|
import org.bukkit.event.EventHandler;
|
||||||
import org.bukkit.event.EventPriority;
|
import org.bukkit.event.EventPriority;
|
||||||
@ -20,40 +16,47 @@ import org.bukkit.event.Listener;
|
|||||||
import org.bukkit.event.entity.CreatureSpawnEvent;
|
import org.bukkit.event.entity.CreatureSpawnEvent;
|
||||||
import org.bukkit.event.player.PlayerInteractEntityEvent;
|
import org.bukkit.event.player.PlayerInteractEntityEvent;
|
||||||
import org.jetbrains.annotations.NotNull;
|
import org.jetbrains.annotations.NotNull;
|
||||||
|
import space.arim.morepaperlib.scheduling.ScheduledTask;
|
||||||
|
|
||||||
import java.util.*;
|
import java.time.Duration;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.Set;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
public class VillagerChunkLimit implements VillagerOptimizerModule, Listener {
|
public class VillagerChunkLimit extends VillagerOptimizerModule implements Runnable, Listener {
|
||||||
|
|
||||||
private final ServerImplementation scheduler;
|
private ScheduledTask periodic_chunk_check;
|
||||||
private final VillagerCache villagerCache;
|
|
||||||
private WrappedTask periodic_chunk_check;
|
|
||||||
private final List<Villager.Profession> non_optimized_removal_priority, optimized_removal_priority;
|
private final List<Villager.Profession> non_optimized_removal_priority, optimized_removal_priority;
|
||||||
|
private final Set<Villager.Profession> profession_whitelist;
|
||||||
|
private final ExpiringSet<Chunk> checked_chunks;
|
||||||
private final long check_period;
|
private final long check_period;
|
||||||
private final int non_optimized_max_per_chunk, optimized_max_per_chunk;
|
private final int non_optimized_max_per_chunk, optimized_max_per_chunk;
|
||||||
private final boolean log_enabled, skip_unloaded_entity_chunks;
|
private final boolean log_enabled, skip_unloaded_chunks, use_whitelist;
|
||||||
|
|
||||||
protected VillagerChunkLimit() {
|
protected VillagerChunkLimit() {
|
||||||
shouldEnable();
|
super("villager-chunk-limit");
|
||||||
this.scheduler = VillagerOptimizer.getFoliaLib().getImpl();
|
config.master().addComment(configPath + ".enable",
|
||||||
this.villagerCache = VillagerOptimizer.getCache();
|
|
||||||
Config config = VillagerOptimizer.getConfiguration();
|
|
||||||
config.master().addComment(configPath() + ".enable",
|
|
||||||
"Checks chunks for too many villagers and removes excess villagers based on priority.");
|
"Checks chunks for too many villagers and removes excess villagers based on priority.");
|
||||||
this.check_period = config.getInt(configPath() + ".check-period-in-ticks", 600,
|
this.check_period = config.getInt(configPath + ".check-period-in-ticks", 600,
|
||||||
"Check all loaded chunks every X ticks. 1 second = 20 ticks\n" +
|
"Check all loaded chunks every X ticks. 1 second = 20 ticks\n" +
|
||||||
"A shorter delay in between checks is more efficient but is also more resource intense.\n" +
|
"A shorter delay in between checks is more efficient but is also more resource intense.\n" +
|
||||||
"A larger delay is less resource intense but could become inefficient.");
|
"A larger delay is less resource intense but could become inefficient.");
|
||||||
this.skip_unloaded_entity_chunks = config.getBoolean(configPath() + ".skip-if-chunk-has-not-loaded-entities", true,
|
this.skip_unloaded_chunks = config.getBoolean(configPath + ".skip-not-fully-loaded-chunks", true,
|
||||||
"Does not check chunks that don't have their entities loaded.");
|
"Does not check chunks that don't have their entities loaded.");
|
||||||
this.log_enabled = config.getBoolean(configPath() + ".log-removals", true);
|
this.checked_chunks = new ExpiringSet<>(Duration.ofSeconds(
|
||||||
this.non_optimized_max_per_chunk = config.getInt(configPath() + ".unoptimized.max-per-chunk", 20,
|
Math.max(1, config.getInt(configPath + ".chunk-check-cooldown-seconds", 5,
|
||||||
"The maximum amount of unoptimized villagers per chunk.");
|
"The delay in seconds a chunk will not be checked again after the first time.\n" +
|
||||||
final List<String> defaults = Stream.of(
|
"Reduces chances to lag the server due to overchecking."))));
|
||||||
|
this.log_enabled = config.getBoolean(configPath + ".log-removals", true);
|
||||||
|
List<String> defaults = Stream.of(
|
||||||
"NONE", "NITWIT", "SHEPHERD", "FISHERMAN", "BUTCHER", "CARTOGRAPHER", "LEATHERWORKER",
|
"NONE", "NITWIT", "SHEPHERD", "FISHERMAN", "BUTCHER", "CARTOGRAPHER", "LEATHERWORKER",
|
||||||
"FLETCHER", "MASON", "FARMER", "ARMORER", "TOOLSMITH", "WEAPONSMITH", "CLERIC", "LIBRARIAN")
|
"FLETCHER", "MASON", "FARMER", "ARMORER", "TOOLSMITH", "WEAPONSMITH", "CLERIC", "LIBRARIAN")
|
||||||
.filter(profession -> {
|
.filter(profession -> {
|
||||||
try {
|
try {
|
||||||
// Make sure no scary warnings appear when creating config defaults
|
// Make sure no scary warnings appear when creating config defaults
|
||||||
@ -63,7 +66,26 @@ public class VillagerChunkLimit implements VillagerOptimizerModule, Listener {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}).collect(Collectors.toList());
|
}).collect(Collectors.toList());
|
||||||
this.non_optimized_removal_priority = config.getList(configPath() + ".unoptimized.removal-priority", defaults,
|
this.use_whitelist = config.getBoolean(configPath + ".whitelist.enable", false,
|
||||||
|
"Enable if you only want to manage villager counts for certain profession types.");
|
||||||
|
this.profession_whitelist = config.getList(configPath + ".whitelist.professions", Arrays.asList("NONE", "NITWIT"),
|
||||||
|
"Professions in this list will not be touched by the chunk limit.")
|
||||||
|
.stream()
|
||||||
|
.map(configuredProfession -> {
|
||||||
|
try {
|
||||||
|
return Villager.Profession.valueOf(configuredProfession);
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
warn("(whitelist) Villager profession '" + configuredProfession +
|
||||||
|
"' not recognized. Make sure you're using the correct profession enums from " +
|
||||||
|
"https://jd.papermc.io/paper/1.20/org/bukkit/entity/Villager.Profession.html.");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.filter(Objects::nonNull)
|
||||||
|
.collect(Collectors.toCollection(HashSet::new));
|
||||||
|
this.non_optimized_max_per_chunk = config.getInt(configPath + ".unoptimized.max-per-chunk", 20,
|
||||||
|
"The maximum amount of unoptimized villagers per chunk.");
|
||||||
|
this.non_optimized_removal_priority = config.getList(configPath + ".unoptimized.removal-priority", new ArrayList<>(defaults),
|
||||||
"Professions that are in the top of the list are going to be scheduled for removal first.\n" +
|
"Professions that are in the top of the list are going to be scheduled for removal first.\n" +
|
||||||
"Use enums from https://jd.papermc.io/paper/1.20/org/bukkit/entity/Villager.Profession.html")
|
"Use enums from https://jd.papermc.io/paper/1.20/org/bukkit/entity/Villager.Profession.html")
|
||||||
.stream()
|
.stream()
|
||||||
@ -79,9 +101,9 @@ public class VillagerChunkLimit implements VillagerOptimizerModule, Listener {
|
|||||||
})
|
})
|
||||||
.filter(Objects::nonNull)
|
.filter(Objects::nonNull)
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
this.optimized_max_per_chunk = config.getInt(configPath() + ".optimized.max-per-chunk", 60,
|
this.optimized_max_per_chunk = config.getInt(configPath + ".optimized.max-per-chunk", 60,
|
||||||
"The maximum amount of optimized villagers per chunk.");
|
"The maximum amount of optimized villagers per chunk.");
|
||||||
this.optimized_removal_priority = config.getList(configPath() + ".optimized.removal-priority", defaults)
|
this.optimized_removal_priority = config.getList(configPath + ".optimized.removal-priority", new ArrayList<>(defaults))
|
||||||
.stream()
|
.stream()
|
||||||
.map(configuredProfession -> {
|
.map(configuredProfession -> {
|
||||||
try {
|
try {
|
||||||
@ -97,31 +119,15 @@ public class VillagerChunkLimit implements VillagerOptimizerModule, Listener {
|
|||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public String configPath() {
|
|
||||||
return "villager-chunk-limit";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void enable() {
|
public void enable() {
|
||||||
final VillagerOptimizer plugin = VillagerOptimizer.getInstance();
|
plugin.getServer().getPluginManager().registerEvents(this, plugin);
|
||||||
final Server server = plugin.getServer();
|
periodic_chunk_check = scheduling.globalRegionalScheduler().runAtFixedRate(this, check_period, check_period);
|
||||||
server.getPluginManager().registerEvents(this, plugin);
|
|
||||||
|
|
||||||
this.periodic_chunk_check = scheduler.runTimer(() -> {
|
|
||||||
for (World world : server.getWorlds()) {
|
|
||||||
for (Chunk chunk : world.getLoadedChunks()) {
|
|
||||||
if (!skip_unloaded_entity_chunks || Util.isEntitiesLoaded(chunk)) {
|
|
||||||
this.manageVillagerCount(chunk);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, check_period, check_period);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean shouldEnable() {
|
public boolean shouldEnable() {
|
||||||
return VillagerOptimizer.getConfiguration().getBoolean(configPath() + ".enable", false);
|
return config.getBoolean(configPath + ".enable", false);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@ -130,33 +136,58 @@ public class VillagerChunkLimit implements VillagerOptimizerModule, Listener {
|
|||||||
if (periodic_chunk_check != null) periodic_chunk_check.cancel();
|
if (periodic_chunk_check != null) periodic_chunk_check.cancel();
|
||||||
}
|
}
|
||||||
|
|
||||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
@Override
|
||||||
private void onCreatureSpawn(CreatureSpawnEvent event) {
|
public void run() {
|
||||||
if (event.getEntityType() == EntityType.VILLAGER) {
|
for (World world : plugin.getServer().getWorlds()) {
|
||||||
this.manageVillagerCount(event.getEntity().getChunk());
|
for (Chunk chunk : world.getLoadedChunks()) {
|
||||||
|
scheduling.regionSpecificScheduler(chunk.getWorld(), chunk.getX(), chunk.getZ()).run(() -> {
|
||||||
|
if (!skip_unloaded_chunks || Util.isChunkLoaded(chunk)) {
|
||||||
|
manageVillagerCount(chunk);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
|
private void onCreatureSpawn(CreatureSpawnEvent event) {
|
||||||
|
if (event.getEntityType() == XEntityType.VILLAGER.get()) {
|
||||||
|
scheduling.regionSpecificScheduler(event.getLocation()).run(() -> {
|
||||||
|
manageVillagerCount(event.getEntity().getChunk());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
|
||||||
private void onInteract(PlayerInteractEntityEvent event) {
|
private void onInteract(PlayerInteractEntityEvent event) {
|
||||||
if (event.getRightClicked().getType() == EntityType.VILLAGER) {
|
if (event.getRightClicked().getType() == XEntityType.VILLAGER.get()) {
|
||||||
this.manageVillagerCount(event.getRightClicked().getChunk());
|
scheduling.regionSpecificScheduler(event.getRightClicked().getLocation()).run(() -> {
|
||||||
|
manageVillagerCount(event.getRightClicked().getChunk());
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void manageVillagerCount(@NotNull Chunk chunk) {
|
private void manageVillagerCount(@NotNull Chunk chunk) {
|
||||||
|
// Remember which chunk we have already checked
|
||||||
|
if (checked_chunks.contains(chunk)) return;
|
||||||
|
else checked_chunks.add(chunk);
|
||||||
|
|
||||||
// Collect all optimized and unoptimized villagers in that chunk
|
// Collect all optimized and unoptimized villagers in that chunk
|
||||||
List<Villager> optimized_villagers = new ArrayList<>();
|
List<Villager> optimized_villagers = new ArrayList<>();
|
||||||
List<Villager> not_optimized_villagers = new ArrayList<>();
|
List<Villager> not_optimized_villagers = new ArrayList<>();
|
||||||
|
|
||||||
for (Entity entity : chunk.getEntities()) {
|
for (Entity entity : chunk.getEntities()) {
|
||||||
if (entity.getType().equals(EntityType.VILLAGER)) {
|
if (entity.getType() != XEntityType.VILLAGER.get()) continue;
|
||||||
Villager villager = (Villager) entity;
|
|
||||||
if (villagerCache.getOrAdd(villager).isOptimized()) {
|
Villager villager = (Villager) entity;
|
||||||
optimized_villagers.add(villager);
|
|
||||||
} else {
|
// Ignore villager if profession is not in the whitelist
|
||||||
not_optimized_villagers.add(villager);
|
if (use_whitelist && profession_whitelist.contains(villager.getProfession())) continue;
|
||||||
}
|
|
||||||
|
if (wrapperCache.get(villager, WrappedVillager::new).isOptimized()) {
|
||||||
|
optimized_villagers.add(villager);
|
||||||
|
} else {
|
||||||
|
not_optimized_villagers.add(villager);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -171,13 +202,11 @@ public class VillagerChunkLimit implements VillagerOptimizerModule, Listener {
|
|||||||
// Remove prioritized villagers that are too many
|
// Remove prioritized villagers that are too many
|
||||||
for (int i = 0; i < not_optimized_villagers_too_many; i++) {
|
for (int i = 0; i < not_optimized_villagers_too_many; i++) {
|
||||||
Villager villager = not_optimized_villagers.get(i);
|
Villager villager = not_optimized_villagers.get(i);
|
||||||
scheduler.runAtEntity(villager, kill -> {
|
scheduling.entitySpecificScheduler(villager).run(kill -> {
|
||||||
villager.remove();
|
villager.remove();
|
||||||
if (log_enabled) {
|
if (log_enabled) info("Removed unoptimized villager with profession '" +
|
||||||
info("Removed unoptimized villager with profession '" + Util.formatEnum(villager.getProfession()) + "' at " +
|
Util.toNiceString(villager.getProfession()) + "' at " + LocationUtil.toString(villager.getLocation()));
|
||||||
LocationUtil.toString(villager.getLocation()));
|
}, null);
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -192,14 +221,11 @@ public class VillagerChunkLimit implements VillagerOptimizerModule, Listener {
|
|||||||
// Remove prioritized villagers that are too many
|
// Remove prioritized villagers that are too many
|
||||||
for (int i = 0; i < optimized_villagers_too_many; i++) {
|
for (int i = 0; i < optimized_villagers_too_many; i++) {
|
||||||
Villager villager = optimized_villagers.get(i);
|
Villager villager = optimized_villagers.get(i);
|
||||||
scheduler.runAtEntity(villager, kill -> {
|
scheduling.entitySpecificScheduler(villager).run(kill -> {
|
||||||
villager.remove();
|
villager.remove();
|
||||||
|
if (log_enabled) info("Removed unoptimized villager with profession '" +
|
||||||
if (log_enabled) {
|
Util.toNiceString(villager.getProfession()) + "' at " + LocationUtil.toString(villager.getLocation()));
|
||||||
info("Removed optimized villager with profession '" + Util.formatEnum(villager.getProfession()) + "' at " +
|
}, null);
|
||||||
LocationUtil.toString(villager.getLocation()));
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,69 +1,87 @@
|
|||||||
package me.xginko.villageroptimizer.modules;
|
package me.xginko.villageroptimizer.modules;
|
||||||
|
|
||||||
|
import com.github.benmanes.caffeine.cache.Cache;
|
||||||
import me.xginko.villageroptimizer.VillagerOptimizer;
|
import me.xginko.villageroptimizer.VillagerOptimizer;
|
||||||
import me.xginko.villageroptimizer.modules.gameplay.*;
|
import me.xginko.villageroptimizer.config.Config;
|
||||||
import me.xginko.villageroptimizer.modules.optimization.OptimizeByBlock;
|
import me.xginko.villageroptimizer.struct.Disableable;
|
||||||
import me.xginko.villageroptimizer.modules.optimization.OptimizeByNametag;
|
import me.xginko.villageroptimizer.struct.Enableable;
|
||||||
import me.xginko.villageroptimizer.modules.optimization.OptimizeByWorkstation;
|
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
|
||||||
import me.xginko.villageroptimizer.utils.Util;
|
import org.bukkit.entity.Villager;
|
||||||
import net.kyori.adventure.text.Component;
|
import org.reflections.Reflections;
|
||||||
|
import org.reflections.scanners.Scanners;
|
||||||
|
import space.arim.morepaperlib.scheduling.GracefulScheduling;
|
||||||
|
|
||||||
|
import java.lang.reflect.InvocationTargetException;
|
||||||
|
import java.lang.reflect.Modifier;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
public interface VillagerOptimizerModule {
|
public abstract class VillagerOptimizerModule implements Enableable, Disableable {
|
||||||
|
|
||||||
String configPath();
|
private static final Reflections MODULES_PACKAGE = new Reflections(VillagerOptimizerModule.class.getPackage().getName());
|
||||||
void enable();
|
public static final Set<VillagerOptimizerModule> ENABLED_MODULES = new HashSet<>();
|
||||||
void disable();
|
|
||||||
boolean shouldEnable();
|
|
||||||
|
|
||||||
HashSet<VillagerOptimizerModule> MODULES = new HashSet<>(14);
|
public abstract boolean shouldEnable();
|
||||||
|
|
||||||
static void reloadModules() {
|
protected final VillagerOptimizer plugin;
|
||||||
MODULES.forEach(VillagerOptimizerModule::disable);
|
protected final Config config;
|
||||||
MODULES.clear();
|
protected final Cache<Villager, WrappedVillager> wrapperCache;
|
||||||
|
protected final GracefulScheduling scheduling;
|
||||||
|
public final String configPath;
|
||||||
|
private final String logFormat;
|
||||||
|
|
||||||
MODULES.add(new OptimizeByNametag());
|
public VillagerOptimizerModule(String configPath) {
|
||||||
MODULES.add(new OptimizeByBlock());
|
this.plugin = VillagerOptimizer.getInstance();
|
||||||
MODULES.add(new OptimizeByWorkstation());
|
this.config = VillagerOptimizer.config();
|
||||||
|
this.wrapperCache = VillagerOptimizer.wrappers();
|
||||||
MODULES.add(new EnableLeashingVillagers());
|
this.scheduling = VillagerOptimizer.scheduling();
|
||||||
MODULES.add(new FixOptimisationAfterCure());
|
this.configPath = configPath;
|
||||||
MODULES.add(new RestockOptimizedTrades());
|
shouldEnable(); // Ensure enable option is always first
|
||||||
MODULES.add(new LevelOptimizedProfession());
|
String[] paths = configPath.split("\\.");
|
||||||
MODULES.add(new VisuallyHighlightOptimized());
|
if (paths.length <= 2) {
|
||||||
MODULES.add(new MakeVillagersSpawnAdult());
|
this.logFormat = "<" + configPath + "> {}";
|
||||||
MODULES.add(new PreventUnoptimizedTrading());
|
} else {
|
||||||
MODULES.add(new PreventOptimizedTargeting());
|
this.logFormat = "<" + paths[paths.length - 2] + "." + paths[paths.length - 1] + "> {}";
|
||||||
MODULES.add(new PreventOptimizedDamage());
|
}
|
||||||
MODULES.add(new UnoptimizeOnJobLoose());
|
|
||||||
|
|
||||||
MODULES.add(new VillagerChunkLimit());
|
|
||||||
|
|
||||||
MODULES.forEach(module -> {
|
|
||||||
if (module.shouldEnable()) module.enable();
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
default void error(String message, Throwable t) {
|
public static void reloadModules() {
|
||||||
VillagerOptimizer.getPrefixedLogger().error("{}{}", logPrefix(), message, t);
|
ENABLED_MODULES.forEach(VillagerOptimizerModule::disable);
|
||||||
|
ENABLED_MODULES.clear();
|
||||||
|
|
||||||
|
for (Class<?> clazz : MODULES_PACKAGE.get(Scanners.SubTypes.of(VillagerOptimizerModule.class).asClass())) {
|
||||||
|
if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())) continue;
|
||||||
|
|
||||||
|
try {
|
||||||
|
VillagerOptimizerModule module = (VillagerOptimizerModule) clazz.getDeclaredConstructor().newInstance();
|
||||||
|
if (module.shouldEnable()) {
|
||||||
|
ENABLED_MODULES.add(module);
|
||||||
|
}
|
||||||
|
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
|
||||||
|
VillagerOptimizer.logger().error("Failed initialising module class '{}'.", clazz.getSimpleName(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ENABLED_MODULES.forEach(VillagerOptimizerModule::enable);
|
||||||
}
|
}
|
||||||
|
|
||||||
default void error(String message) {
|
protected void error(String message, Throwable throwable) {
|
||||||
VillagerOptimizer.getPrefixedLogger().error("{}{}", logPrefix(), message);
|
VillagerOptimizer.logger().error(logFormat, message, throwable);
|
||||||
}
|
}
|
||||||
|
|
||||||
default void warn(String message) {
|
protected void error(String message) {
|
||||||
VillagerOptimizer.getPrefixedLogger().warn("{}{}", logPrefix(), message);
|
VillagerOptimizer.logger().error(logFormat, message);
|
||||||
}
|
}
|
||||||
|
|
||||||
default void info(String message) {
|
protected void warn(String message) {
|
||||||
VillagerOptimizer.getPrefixedLogger().info(Component.text(logPrefix() + message).color(Util.PL_COLOR));
|
VillagerOptimizer.logger().warn(logFormat, message);
|
||||||
}
|
}
|
||||||
|
|
||||||
default String logPrefix() {
|
protected void info(String message) {
|
||||||
String[] split = configPath().split("\\.");
|
VillagerOptimizer.logger().info(logFormat, message);
|
||||||
if (split.length <= 2) return "<" + configPath() + "> ";
|
}
|
||||||
return "<" + String.join(".", split[split.length - 2], split[split.length - 1]) + "> ";
|
|
||||||
|
protected void notRecognized(Class<?> clazz, String unrecognized) {
|
||||||
|
warn("Unable to parse " + clazz.getSimpleName() + " at '" + unrecognized + "'. Please check your configuration.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,14 +1,11 @@
|
|||||||
package me.xginko.villageroptimizer.modules.gameplay;
|
package me.xginko.villageroptimizer.modules.gameplay;
|
||||||
|
|
||||||
import com.tcoded.folialib.impl.ServerImplementation;
|
import com.cryptomorin.xseries.XEntityType;
|
||||||
import me.xginko.villageroptimizer.VillagerCache;
|
import com.cryptomorin.xseries.XMaterial;
|
||||||
import me.xginko.villageroptimizer.VillagerOptimizer;
|
|
||||||
import me.xginko.villageroptimizer.config.Config;
|
|
||||||
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
|
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
|
||||||
import me.xginko.villageroptimizer.utils.LocationUtil;
|
import me.xginko.villageroptimizer.utils.LocationUtil;
|
||||||
|
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
|
||||||
import org.bukkit.GameMode;
|
import org.bukkit.GameMode;
|
||||||
import org.bukkit.Material;
|
|
||||||
import org.bukkit.entity.EntityType;
|
|
||||||
import org.bukkit.entity.Player;
|
import org.bukkit.entity.Player;
|
||||||
import org.bukkit.entity.Villager;
|
import org.bukkit.entity.Villager;
|
||||||
import org.bukkit.event.EventHandler;
|
import org.bukkit.event.EventHandler;
|
||||||
@ -19,32 +16,21 @@ import org.bukkit.event.entity.PlayerLeashEntityEvent;
|
|||||||
import org.bukkit.event.player.PlayerInteractEntityEvent;
|
import org.bukkit.event.player.PlayerInteractEntityEvent;
|
||||||
import org.bukkit.inventory.ItemStack;
|
import org.bukkit.inventory.ItemStack;
|
||||||
|
|
||||||
public class EnableLeashingVillagers implements VillagerOptimizerModule, Listener {
|
public class EnableLeashingVillagers extends VillagerOptimizerModule implements Listener {
|
||||||
|
|
||||||
private final ServerImplementation scheduler;
|
|
||||||
private final VillagerCache villagerCache;
|
|
||||||
private final boolean only_optimized, log_enabled;
|
private final boolean only_optimized, log_enabled;
|
||||||
|
|
||||||
public EnableLeashingVillagers() {
|
public EnableLeashingVillagers() {
|
||||||
shouldEnable();
|
super("gameplay.villagers-can-be-leashed");
|
||||||
this.scheduler = VillagerOptimizer.getFoliaLib().getImpl();
|
config.master().addComment(configPath + ".enable",
|
||||||
this.villagerCache = VillagerOptimizer.getCache();
|
|
||||||
Config config = VillagerOptimizer.getConfiguration();
|
|
||||||
config.master().addComment(configPath() + ".enable",
|
|
||||||
"Enable leashing of villagers, enabling players to easily move villagers to where they want them to be.");
|
"Enable leashing of villagers, enabling players to easily move villagers to where they want them to be.");
|
||||||
this.only_optimized = config.getBoolean(configPath() + ".only-optimized", false,
|
this.only_optimized = config.getBoolean(configPath + ".only-optimized", false,
|
||||||
"If set to true, only optimized villagers can be leashed.");
|
"If set to true, only optimized villagers can be leashed.");
|
||||||
this.log_enabled = config.getBoolean(configPath() + ".log", false);
|
this.log_enabled = config.getBoolean(configPath + ".log", false);
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String configPath() {
|
|
||||||
return "gameplay.villagers-can-be-leashed";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void enable() {
|
public void enable() {
|
||||||
VillagerOptimizer plugin = VillagerOptimizer.getInstance();
|
|
||||||
plugin.getServer().getPluginManager().registerEvents(this, plugin);
|
plugin.getServer().getPluginManager().registerEvents(this, plugin);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -55,20 +41,20 @@ public class EnableLeashingVillagers implements VillagerOptimizerModule, Listene
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean shouldEnable() {
|
public boolean shouldEnable() {
|
||||||
return VillagerOptimizer.getConfiguration().getBoolean(configPath() + ".enable", false);
|
return config.getBoolean(configPath + ".enable", false);
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressWarnings("deprecation")
|
@SuppressWarnings("deprecation")
|
||||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
private void onLeash(PlayerInteractEntityEvent event) {
|
private void onLeash(PlayerInteractEntityEvent event) {
|
||||||
if (!event.getRightClicked().getType().equals(EntityType.VILLAGER)) return;
|
if (event.getRightClicked().getType() != XEntityType.VILLAGER.get()) return;
|
||||||
final Player player = event.getPlayer();
|
final Player player = event.getPlayer();
|
||||||
final ItemStack handItem = player.getInventory().getItem(event.getHand());
|
final ItemStack handItem = player.getInventory().getItem(event.getHand());
|
||||||
if (handItem == null || !handItem.getType().equals(Material.LEAD)) return;
|
if (handItem == null || handItem.getType() != XMaterial.LEAD.parseMaterial()) return;
|
||||||
|
|
||||||
final Villager villager = (Villager) event.getRightClicked();
|
final Villager villager = (Villager) event.getRightClicked();
|
||||||
if (villager.isLeashed()) return;
|
if (villager.isLeashed()) return;
|
||||||
if (only_optimized && !villagerCache.getOrAdd(villager).isOptimized()) return;
|
if (only_optimized && !wrapperCache.get(villager, WrappedVillager::new).isOptimized()) return;
|
||||||
|
|
||||||
event.setCancelled(true); // Cancel the event, so we don't interact with the villager
|
event.setCancelled(true); // Cancel the event, so we don't interact with the villager
|
||||||
|
|
||||||
@ -83,7 +69,7 @@ public class EnableLeashingVillagers implements VillagerOptimizerModule, Listene
|
|||||||
// If canceled by any plugin, do nothing
|
// If canceled by any plugin, do nothing
|
||||||
if (!leashEvent.callEvent()) return;
|
if (!leashEvent.callEvent()) return;
|
||||||
|
|
||||||
scheduler.runAtEntity(villager, leash -> {
|
scheduling.entitySpecificScheduler(villager).run(leash -> {
|
||||||
// Legitimate to not use entities from the event object since they are final in PlayerLeashEntityEvent
|
// Legitimate to not use entities from the event object since they are final in PlayerLeashEntityEvent
|
||||||
if (!villager.setLeashHolder(player)) return;
|
if (!villager.setLeashHolder(player)) return;
|
||||||
if (player.getGameMode().equals(GameMode.SURVIVAL))
|
if (player.getGameMode().equals(GameMode.SURVIVAL))
|
||||||
@ -92,6 +78,6 @@ public class EnableLeashingVillagers implements VillagerOptimizerModule, Listene
|
|||||||
if (log_enabled) {
|
if (log_enabled) {
|
||||||
info(player.getName() + " leashed a villager at " + LocationUtil.toString(villager.getLocation()));
|
info(player.getName() + " leashed a villager at " + LocationUtil.toString(villager.getLocation()));
|
||||||
}
|
}
|
||||||
});
|
}, null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,9 +1,8 @@
|
|||||||
package me.xginko.villageroptimizer.modules.gameplay;
|
package me.xginko.villageroptimizer.modules.gameplay;
|
||||||
|
|
||||||
import me.xginko.villageroptimizer.VillagerOptimizer;
|
import com.cryptomorin.xseries.XEntityType;
|
||||||
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
|
|
||||||
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
|
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
|
||||||
import org.bukkit.entity.EntityType;
|
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
|
||||||
import org.bukkit.entity.Villager;
|
import org.bukkit.entity.Villager;
|
||||||
import org.bukkit.event.EventHandler;
|
import org.bukkit.event.EventHandler;
|
||||||
import org.bukkit.event.EventPriority;
|
import org.bukkit.event.EventPriority;
|
||||||
@ -11,20 +10,14 @@ import org.bukkit.event.HandlerList;
|
|||||||
import org.bukkit.event.Listener;
|
import org.bukkit.event.Listener;
|
||||||
import org.bukkit.event.entity.EntityTransformEvent;
|
import org.bukkit.event.entity.EntityTransformEvent;
|
||||||
|
|
||||||
import java.util.concurrent.TimeUnit;
|
public class FixOptimisationAfterCure extends VillagerOptimizerModule implements Listener {
|
||||||
|
|
||||||
public class FixOptimisationAfterCure implements VillagerOptimizerModule, Listener {
|
public FixOptimisationAfterCure() {
|
||||||
|
super("post-cure-optimization-fix");
|
||||||
public FixOptimisationAfterCure() {}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String configPath() {
|
|
||||||
return "post-cure-optimization-fix";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void enable() {
|
public void enable() {
|
||||||
VillagerOptimizer plugin = VillagerOptimizer.getInstance();
|
|
||||||
plugin.getServer().getPluginManager().registerEvents(this, plugin);
|
plugin.getServer().getPluginManager().registerEvents(this, plugin);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -41,14 +34,14 @@ public class FixOptimisationAfterCure implements VillagerOptimizerModule, Listen
|
|||||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
private void onTransform(EntityTransformEvent event) {
|
private void onTransform(EntityTransformEvent event) {
|
||||||
if (
|
if (
|
||||||
event.getTransformReason().equals(EntityTransformEvent.TransformReason.CURED)
|
event.getTransformReason() == EntityTransformEvent.TransformReason.CURED
|
||||||
&& event.getTransformedEntity().getType().equals(EntityType.VILLAGER)
|
&& event.getTransformedEntity().getType() == XEntityType.VILLAGER.get()
|
||||||
) {
|
) {
|
||||||
Villager villager = (Villager) event.getTransformedEntity();
|
Villager villager = (Villager) event.getTransformedEntity();
|
||||||
VillagerOptimizer.getFoliaLib().getImpl().runAtEntityLater(villager, () -> {
|
scheduling.entitySpecificScheduler(villager).runDelayed(() -> {
|
||||||
WrappedVillager wVillager = VillagerOptimizer.getCache().getOrAdd(villager);
|
WrappedVillager wVillager = wrapperCache.get(villager, WrappedVillager::new);
|
||||||
wVillager.setOptimizationType(wVillager.getOptimizationType());
|
wVillager.setOptimizationType(wVillager.getOptimizationType());
|
||||||
}, 2, TimeUnit.SECONDS);
|
}, null, 40L);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,13 +1,12 @@
|
|||||||
package me.xginko.villageroptimizer.modules.gameplay;
|
package me.xginko.villageroptimizer.modules.gameplay;
|
||||||
|
|
||||||
import com.tcoded.folialib.impl.ServerImplementation;
|
import com.cryptomorin.xseries.XPotion;
|
||||||
import me.xginko.villageroptimizer.VillagerOptimizer;
|
import me.xginko.villageroptimizer.VillagerOptimizer;
|
||||||
import me.xginko.villageroptimizer.VillagerCache;
|
|
||||||
import me.xginko.villageroptimizer.config.Config;
|
import me.xginko.villageroptimizer.config.Config;
|
||||||
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
|
|
||||||
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
|
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
|
||||||
import me.xginko.villageroptimizer.utils.Util;
|
|
||||||
import me.xginko.villageroptimizer.utils.KyoriUtil;
|
import me.xginko.villageroptimizer.utils.KyoriUtil;
|
||||||
|
import me.xginko.villageroptimizer.utils.Util;
|
||||||
|
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
|
||||||
import net.kyori.adventure.text.TextReplacementConfig;
|
import net.kyori.adventure.text.TextReplacementConfig;
|
||||||
import org.bukkit.entity.Player;
|
import org.bukkit.entity.Player;
|
||||||
import org.bukkit.entity.Villager;
|
import org.bukkit.entity.Villager;
|
||||||
@ -18,42 +17,34 @@ import org.bukkit.event.Listener;
|
|||||||
import org.bukkit.event.inventory.InventoryCloseEvent;
|
import org.bukkit.event.inventory.InventoryCloseEvent;
|
||||||
import org.bukkit.event.inventory.InventoryType;
|
import org.bukkit.event.inventory.InventoryType;
|
||||||
import org.bukkit.potion.PotionEffect;
|
import org.bukkit.potion.PotionEffect;
|
||||||
import org.bukkit.potion.PotionEffectType;
|
|
||||||
|
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
public class LevelOptimizedProfession implements VillagerOptimizerModule, Listener {
|
public class LevelOptimizedProfession extends VillagerOptimizerModule implements Listener {
|
||||||
|
|
||||||
|
private static final PotionEffect SUPER_SLOWNESS = new PotionEffect(
|
||||||
|
XPotion.SLOWNESS.getPotionEffectType(), 120, 120, false, false);
|
||||||
|
|
||||||
private final ServerImplementation scheduler;
|
|
||||||
private final VillagerCache villagerCache;
|
|
||||||
private final boolean notify_player;
|
private final boolean notify_player;
|
||||||
private final long cooldown_millis;
|
private final long cooldown_millis;
|
||||||
|
|
||||||
public LevelOptimizedProfession() {
|
public LevelOptimizedProfession() {
|
||||||
shouldEnable();
|
super("gameplay.level-optimized-profession");
|
||||||
this.scheduler = VillagerOptimizer.getFoliaLib().getImpl();
|
Config config = VillagerOptimizer.config();
|
||||||
this.villagerCache = VillagerOptimizer.getCache();
|
config.master().addComment(configPath,
|
||||||
Config config = VillagerOptimizer.getConfiguration();
|
|
||||||
config.master().addComment(configPath(),
|
|
||||||
"This is needed to allow optimized villagers to level up.\n" +
|
"This is needed to allow optimized villagers to level up.\n" +
|
||||||
"Temporarily enables the villagers AI to allow it to level up and then disables it again.");
|
"Temporarily enables the villagers AI to allow it to level up and then disables it again.");
|
||||||
this.cooldown_millis = TimeUnit.SECONDS.toMillis(
|
this.cooldown_millis = TimeUnit.SECONDS.toMillis(
|
||||||
config.getInt(configPath() + ".level-check-cooldown-seconds", 5,
|
config.getInt(configPath + ".level-check-cooldown-seconds", 5,
|
||||||
"Cooldown in seconds until the level of a villager will be checked and updated again.\n" +
|
"Cooldown in seconds until the level of a villager will be checked and updated again.\n" +
|
||||||
"Recommended to leave as is."));
|
"Recommended to leave as is."));
|
||||||
this.notify_player = config.getBoolean(configPath() + ".notify-player", true,
|
this.notify_player = config.getBoolean(configPath + ".notify-player", true,
|
||||||
"Tell players to wait when a villager is leveling up.");
|
"Tell players to wait when a villager is leveling up.");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public String configPath() {
|
|
||||||
return "gameplay.level-optimized-profession";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void enable() {
|
public void enable() {
|
||||||
VillagerOptimizer plugin = VillagerOptimizer.getInstance();
|
|
||||||
plugin.getServer().getPluginManager().registerEvents(this, plugin);
|
plugin.getServer().getPluginManager().registerEvents(this, plugin);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -70,24 +61,24 @@ public class LevelOptimizedProfession implements VillagerOptimizerModule, Listen
|
|||||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
private void onTradeScreenClose(InventoryCloseEvent event) {
|
private void onTradeScreenClose(InventoryCloseEvent event) {
|
||||||
if (
|
if (
|
||||||
event.getInventory().getType().equals(InventoryType.MERCHANT)
|
event.getInventory().getType() == InventoryType.MERCHANT
|
||||||
&& event.getInventory().getHolder() instanceof Villager
|
&& event.getInventory().getHolder() instanceof Villager
|
||||||
) {
|
) {
|
||||||
final Villager villager = (Villager) event.getInventory().getHolder();
|
final Villager villager = (Villager) event.getInventory().getHolder();
|
||||||
final WrappedVillager wVillager = villagerCache.getOrAdd(villager);
|
final WrappedVillager wVillager = wrapperCache.get(villager, WrappedVillager::new);
|
||||||
if (!wVillager.isOptimized()) return;
|
if (!wVillager.isOptimized()) return;
|
||||||
|
|
||||||
if (wVillager.canLevelUp(cooldown_millis)) {
|
if (wVillager.canLevelUp(cooldown_millis)) {
|
||||||
if (wVillager.calculateLevel() <= villager.getVillagerLevel()) return;
|
if (wVillager.calculateLevel() <= villager.getVillagerLevel()) return;
|
||||||
|
|
||||||
scheduler.runAtEntity(villager, enableAI -> {
|
scheduling.entitySpecificScheduler(villager).run(enableAI -> {
|
||||||
villager.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 120, 120, false, false));
|
villager.addPotionEffect(SUPER_SLOWNESS);
|
||||||
villager.setAware(true);
|
villager.setAware(true);
|
||||||
scheduler.runAtEntityLater(villager, disableAI -> {
|
scheduling.entitySpecificScheduler(villager).runDelayed(disableAI -> {
|
||||||
villager.setAware(false);
|
villager.setAware(false);
|
||||||
wVillager.saveLastLevelUp();
|
wVillager.saveLastLevelUp();
|
||||||
}, 5, TimeUnit.SECONDS);
|
}, null, 100L);
|
||||||
});
|
}, null);
|
||||||
} else {
|
} else {
|
||||||
if (notify_player) {
|
if (notify_player) {
|
||||||
Player player = (Player) event.getPlayer();
|
Player player = (Player) event.getPlayer();
|
||||||
|
@ -1,8 +1,7 @@
|
|||||||
package me.xginko.villageroptimizer.modules.gameplay;
|
package me.xginko.villageroptimizer.modules.gameplay;
|
||||||
|
|
||||||
import me.xginko.villageroptimizer.VillagerOptimizer;
|
import com.cryptomorin.xseries.XEntityType;
|
||||||
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
|
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
|
||||||
import org.bukkit.entity.EntityType;
|
|
||||||
import org.bukkit.entity.Villager;
|
import org.bukkit.entity.Villager;
|
||||||
import org.bukkit.event.EventHandler;
|
import org.bukkit.event.EventHandler;
|
||||||
import org.bukkit.event.EventPriority;
|
import org.bukkit.event.EventPriority;
|
||||||
@ -10,18 +9,19 @@ import org.bukkit.event.HandlerList;
|
|||||||
import org.bukkit.event.Listener;
|
import org.bukkit.event.Listener;
|
||||||
import org.bukkit.event.entity.CreatureSpawnEvent;
|
import org.bukkit.event.entity.CreatureSpawnEvent;
|
||||||
|
|
||||||
public class MakeVillagersSpawnAdult implements VillagerOptimizerModule, Listener {
|
public class MakeVillagersSpawnAdult extends VillagerOptimizerModule implements Listener {
|
||||||
|
|
||||||
public MakeVillagersSpawnAdult() {}
|
public MakeVillagersSpawnAdult() {
|
||||||
|
super("gameplay.villagers-spawn-as-adults");
|
||||||
@Override
|
config.master().addComment(configPath + ".enable",
|
||||||
public String configPath() {
|
"Spawned villagers will immediately be adults.\n" +
|
||||||
return "gameplay.villagers-spawn-as-adults";
|
"This is to save some more resources as players don't have to keep unoptimized\n" +
|
||||||
|
"villagers loaded because they have to wait for them to turn into adults before they can\n" +
|
||||||
|
"optimize them.");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void enable() {
|
public void enable() {
|
||||||
VillagerOptimizer plugin = VillagerOptimizer.getInstance();
|
|
||||||
plugin.getServer().getPluginManager().registerEvents(this, plugin);
|
plugin.getServer().getPluginManager().registerEvents(this, plugin);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -32,16 +32,12 @@ public class MakeVillagersSpawnAdult implements VillagerOptimizerModule, Listene
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean shouldEnable() {
|
public boolean shouldEnable() {
|
||||||
return VillagerOptimizer.getConfiguration().getBoolean(configPath() + ".enable", false,
|
return config.getBoolean(configPath + ".enable", false);
|
||||||
"Spawned villagers will immediately be adults.\n" +
|
|
||||||
"This is to save some more resources as players don't have to keep unoptimized\n" +
|
|
||||||
"villagers loaded because they have to wait for them to turn into adults before they can\n" +
|
|
||||||
"optimize them.");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
private void onVillagerSpawn(CreatureSpawnEvent event) {
|
private void onVillagerSpawn(CreatureSpawnEvent event) {
|
||||||
if (event.getEntityType().equals(EntityType.VILLAGER)) {
|
if (event.getEntityType() == XEntityType.VILLAGER.get()) {
|
||||||
final Villager villager = (Villager) event.getEntity();
|
final Villager villager = (Villager) event.getEntity();
|
||||||
if (!villager.isAdult()) villager.setAdult();
|
if (!villager.isAdult()) villager.setAdult();
|
||||||
}
|
}
|
||||||
|
@ -1,12 +1,8 @@
|
|||||||
package me.xginko.villageroptimizer.modules.gameplay;
|
package me.xginko.villageroptimizer.modules.gameplay;
|
||||||
|
|
||||||
import com.destroystokyo.paper.event.entity.EntityKnockbackByEntityEvent;
|
import com.cryptomorin.xseries.XEntityType;
|
||||||
import me.xginko.villageroptimizer.VillagerCache;
|
|
||||||
import me.xginko.villageroptimizer.VillagerOptimizer;
|
|
||||||
import me.xginko.villageroptimizer.config.Config;
|
|
||||||
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
|
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
|
||||||
import org.bukkit.Material;
|
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
|
||||||
import org.bukkit.entity.EntityType;
|
|
||||||
import org.bukkit.entity.Villager;
|
import org.bukkit.entity.Villager;
|
||||||
import org.bukkit.event.EventHandler;
|
import org.bukkit.event.EventHandler;
|
||||||
import org.bukkit.event.EventPriority;
|
import org.bukkit.event.EventPriority;
|
||||||
@ -14,24 +10,24 @@ import org.bukkit.event.HandlerList;
|
|||||||
import org.bukkit.event.Listener;
|
import org.bukkit.event.Listener;
|
||||||
import org.bukkit.event.entity.EntityDamageEvent;
|
import org.bukkit.event.entity.EntityDamageEvent;
|
||||||
|
|
||||||
import java.util.*;
|
import java.util.Arrays;
|
||||||
|
import java.util.EnumSet;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.Set;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
public class PreventOptimizedDamage implements VillagerOptimizerModule, Listener {
|
public class PreventOptimizedDamage extends VillagerOptimizerModule implements Listener {
|
||||||
|
|
||||||
private final VillagerCache villagerCache;
|
|
||||||
private final Set<EntityDamageEvent.DamageCause> damage_causes_to_cancel;
|
private final Set<EntityDamageEvent.DamageCause> damage_causes_to_cancel;
|
||||||
private final boolean cancel_knockback;
|
private final boolean cancel_knockback;
|
||||||
|
|
||||||
public PreventOptimizedDamage() {
|
public PreventOptimizedDamage() {
|
||||||
shouldEnable();
|
super("gameplay.prevent-damage-to-optimized");
|
||||||
this.villagerCache = VillagerOptimizer.getCache();
|
config.master().addComment(configPath + ".enable",
|
||||||
Config config = VillagerOptimizer.getConfiguration();
|
|
||||||
config.master().addComment(configPath() + ".enable",
|
|
||||||
"Configure what kind of damage you want to cancel for optimized villagers here.");
|
"Configure what kind of damage you want to cancel for optimized villagers here.");
|
||||||
this.cancel_knockback = config.getBoolean(configPath() + ".prevent-knockback-from-entity", true,
|
this.cancel_knockback = config.getBoolean(configPath + ".prevent-knockback-from-entity", true,
|
||||||
"Prevents optimized villagers from getting knocked back by an attacking entity");
|
"Prevents optimized villagers from getting knocked back by an attacking entity");
|
||||||
this.damage_causes_to_cancel = config.getList(configPath() + ".damage-causes-to-cancel",
|
this.damage_causes_to_cancel = config.getList(configPath + ".damage-causes-to-cancel",
|
||||||
Arrays.stream(EntityDamageEvent.DamageCause.values()).map(Enum::name).sorted().collect(Collectors.toList()),
|
Arrays.stream(EntityDamageEvent.DamageCause.values()).map(Enum::name).sorted().collect(Collectors.toList()),
|
||||||
"These are all current entries in the game. Remove what you do not need blocked.\n" +
|
"These are all current entries in the game. Remove what you do not need blocked.\n" +
|
||||||
"If you want a description or need to add a previously removed type, refer to:\n" +
|
"If you want a description or need to add a previously removed type, refer to:\n" +
|
||||||
@ -50,14 +46,8 @@ public class PreventOptimizedDamage implements VillagerOptimizerModule, Listener
|
|||||||
.collect(Collectors.toCollection(() -> EnumSet.noneOf(EntityDamageEvent.DamageCause.class)));
|
.collect(Collectors.toCollection(() -> EnumSet.noneOf(EntityDamageEvent.DamageCause.class)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public String configPath() {
|
|
||||||
return "gameplay.prevent-damage-to-optimized";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void enable() {
|
public void enable() {
|
||||||
VillagerOptimizer plugin = VillagerOptimizer.getInstance();
|
|
||||||
plugin.getServer().getPluginManager().registerEvents(this, plugin);
|
plugin.getServer().getPluginManager().registerEvents(this, plugin);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -68,26 +58,26 @@ public class PreventOptimizedDamage implements VillagerOptimizerModule, Listener
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean shouldEnable() {
|
public boolean shouldEnable() {
|
||||||
return VillagerOptimizer.getConfiguration().getBoolean(configPath() + ".enable", true);
|
return config.getBoolean(configPath + ".enable", true);
|
||||||
}
|
}
|
||||||
|
|
||||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
private void onDamageByEntity(EntityDamageEvent event) {
|
private void onDamageByEntity(EntityDamageEvent event) {
|
||||||
if (
|
if (
|
||||||
event.getEntityType().equals(EntityType.VILLAGER)
|
event.getEntityType() == XEntityType.VILLAGER.get()
|
||||||
&& damage_causes_to_cancel.contains(event.getCause())
|
&& damage_causes_to_cancel.contains(event.getCause())
|
||||||
&& villagerCache.getOrAdd((Villager) event.getEntity()).isOptimized()
|
&& wrapperCache.get((Villager) event.getEntity(), WrappedVillager::new).isOptimized()
|
||||||
) {
|
) {
|
||||||
event.setCancelled(true);
|
event.setCancelled(true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
private void onKnockbackByEntity(EntityKnockbackByEntityEvent event) {
|
private void onKnockbackByEntity(com.destroystokyo.paper.event.entity.EntityKnockbackByEntityEvent event) {
|
||||||
if (
|
if (
|
||||||
cancel_knockback
|
cancel_knockback
|
||||||
&& event.getEntityType().equals(EntityType.VILLAGER)
|
&& event.getEntityType() == XEntityType.VILLAGER.get()
|
||||||
&& villagerCache.getOrAdd((Villager) event.getEntity()).isOptimized()
|
&& wrapperCache.get((Villager) event.getEntity(), WrappedVillager::new).isOptimized()
|
||||||
) {
|
) {
|
||||||
event.setCancelled(true);
|
event.setCancelled(true);
|
||||||
}
|
}
|
||||||
|
@ -1,11 +1,9 @@
|
|||||||
package me.xginko.villageroptimizer.modules.gameplay;
|
package me.xginko.villageroptimizer.modules.gameplay;
|
||||||
|
|
||||||
import com.destroystokyo.paper.event.entity.EntityPathfindEvent;
|
import com.cryptomorin.xseries.XEntityType;
|
||||||
import me.xginko.villageroptimizer.VillagerCache;
|
|
||||||
import me.xginko.villageroptimizer.VillagerOptimizer;
|
|
||||||
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
|
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
|
||||||
|
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
|
||||||
import org.bukkit.entity.Entity;
|
import org.bukkit.entity.Entity;
|
||||||
import org.bukkit.entity.EntityType;
|
|
||||||
import org.bukkit.entity.Mob;
|
import org.bukkit.entity.Mob;
|
||||||
import org.bukkit.entity.Villager;
|
import org.bukkit.entity.Villager;
|
||||||
import org.bukkit.event.EventHandler;
|
import org.bukkit.event.EventHandler;
|
||||||
@ -15,22 +13,16 @@ import org.bukkit.event.Listener;
|
|||||||
import org.bukkit.event.entity.EntityDamageByEntityEvent;
|
import org.bukkit.event.entity.EntityDamageByEntityEvent;
|
||||||
import org.bukkit.event.entity.EntityTargetEvent;
|
import org.bukkit.event.entity.EntityTargetEvent;
|
||||||
|
|
||||||
public class PreventOptimizedTargeting implements VillagerOptimizerModule, Listener {
|
public class PreventOptimizedTargeting extends VillagerOptimizerModule implements Listener {
|
||||||
|
|
||||||
private final VillagerCache villagerCache;
|
|
||||||
|
|
||||||
public PreventOptimizedTargeting() {
|
public PreventOptimizedTargeting() {
|
||||||
this.villagerCache = VillagerOptimizer.getCache();
|
super("gameplay.prevent-entities-from-targeting-optimized");
|
||||||
}
|
config.master().addComment(configPath + ".enable",
|
||||||
|
"Prevents hostile entities from targeting optimized villagers.");
|
||||||
@Override
|
|
||||||
public String configPath() {
|
|
||||||
return "gameplay.prevent-entities-from-targeting-optimized";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void enable() {
|
public void enable() {
|
||||||
VillagerOptimizer plugin = VillagerOptimizer.getInstance();
|
|
||||||
plugin.getServer().getPluginManager().registerEvents(this, plugin);
|
plugin.getServer().getPluginManager().registerEvents(this, plugin);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -41,8 +33,7 @@ public class PreventOptimizedTargeting implements VillagerOptimizerModule, Liste
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean shouldEnable() {
|
public boolean shouldEnable() {
|
||||||
return VillagerOptimizer.getConfiguration().getBoolean(configPath() + ".enable", true,
|
return config.getBoolean(configPath + ".enable", true);
|
||||||
"Prevents hostile entities from targeting optimized villagers.");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
@ -50,8 +41,8 @@ public class PreventOptimizedTargeting implements VillagerOptimizerModule, Liste
|
|||||||
final Entity target = event.getTarget();
|
final Entity target = event.getTarget();
|
||||||
if (
|
if (
|
||||||
target != null
|
target != null
|
||||||
&& target.getType().equals(EntityType.VILLAGER)
|
&& target.getType() == XEntityType.VILLAGER.get()
|
||||||
&& villagerCache.getOrAdd((Villager) target).isOptimized()
|
&& wrapperCache.get((Villager) target, WrappedVillager::new).isOptimized()
|
||||||
) {
|
) {
|
||||||
event.setTarget(null);
|
event.setTarget(null);
|
||||||
event.setCancelled(true);
|
event.setCancelled(true);
|
||||||
@ -59,12 +50,12 @@ public class PreventOptimizedTargeting implements VillagerOptimizerModule, Liste
|
|||||||
}
|
}
|
||||||
|
|
||||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
private void onEntityTargetVillager(EntityPathfindEvent event) {
|
private void onEntityTargetVillager(com.destroystokyo.paper.event.entity.EntityPathfindEvent event) {
|
||||||
final Entity target = event.getTargetEntity();
|
final Entity target = event.getTargetEntity();
|
||||||
if (
|
if (
|
||||||
target != null
|
target != null
|
||||||
&& target.getType().equals(EntityType.VILLAGER)
|
&& target.getType() == XEntityType.VILLAGER.get()
|
||||||
&& villagerCache.getOrAdd((Villager) target).isOptimized()
|
&& wrapperCache.get((Villager) target, WrappedVillager::new).isOptimized()
|
||||||
) {
|
) {
|
||||||
event.setCancelled(true);
|
event.setCancelled(true);
|
||||||
}
|
}
|
||||||
@ -73,9 +64,9 @@ public class PreventOptimizedTargeting implements VillagerOptimizerModule, Liste
|
|||||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
private void onEntityAttackVillager(EntityDamageByEntityEvent event) {
|
private void onEntityAttackVillager(EntityDamageByEntityEvent event) {
|
||||||
if (
|
if (
|
||||||
event.getEntityType().equals(EntityType.VILLAGER)
|
event.getEntityType() == XEntityType.VILLAGER.get()
|
||||||
&& event.getDamager() instanceof Mob
|
&& event.getDamager() instanceof Mob
|
||||||
&& villagerCache.getOrAdd((Villager) event.getEntity()).isOptimized()
|
&& wrapperCache.get((Villager) event.getEntity(), WrappedVillager::new).isOptimized()
|
||||||
) {
|
) {
|
||||||
((Mob) event.getDamager()).setTarget(null);
|
((Mob) event.getDamager()).setTarget(null);
|
||||||
}
|
}
|
||||||
|
@ -1,11 +1,10 @@
|
|||||||
package me.xginko.villageroptimizer.modules.gameplay;
|
package me.xginko.villageroptimizer.modules.gameplay;
|
||||||
|
|
||||||
import me.xginko.villageroptimizer.VillagerOptimizer;
|
import me.xginko.villageroptimizer.VillagerOptimizer;
|
||||||
import me.xginko.villageroptimizer.VillagerCache;
|
import me.xginko.villageroptimizer.struct.enums.Permissions;
|
||||||
import me.xginko.villageroptimizer.config.Config;
|
|
||||||
import me.xginko.villageroptimizer.enums.Permissions;
|
|
||||||
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
|
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
|
||||||
import me.xginko.villageroptimizer.utils.KyoriUtil;
|
import me.xginko.villageroptimizer.utils.KyoriUtil;
|
||||||
|
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
|
||||||
import org.bukkit.entity.Player;
|
import org.bukkit.entity.Player;
|
||||||
import org.bukkit.entity.Villager;
|
import org.bukkit.entity.Villager;
|
||||||
import org.bukkit.event.EventHandler;
|
import org.bukkit.event.EventHandler;
|
||||||
@ -16,31 +15,22 @@ import org.bukkit.event.inventory.InventoryClickEvent;
|
|||||||
import org.bukkit.event.inventory.InventoryType;
|
import org.bukkit.event.inventory.InventoryType;
|
||||||
import org.bukkit.event.inventory.TradeSelectEvent;
|
import org.bukkit.event.inventory.TradeSelectEvent;
|
||||||
|
|
||||||
public class PreventUnoptimizedTrading implements VillagerOptimizerModule, Listener {
|
public class PreventUnoptimizedTrading extends VillagerOptimizerModule implements Listener {
|
||||||
|
|
||||||
private final VillagerCache villagerCache;
|
|
||||||
private final boolean notify_player;
|
private final boolean notify_player;
|
||||||
|
|
||||||
public PreventUnoptimizedTrading() {
|
public PreventUnoptimizedTrading() {
|
||||||
shouldEnable();
|
super("gameplay.prevent-trading-with-unoptimized");
|
||||||
this.villagerCache = VillagerOptimizer.getCache();
|
config.master().addComment(configPath + ".enable",
|
||||||
Config config = VillagerOptimizer.getConfiguration();
|
|
||||||
config.master().addComment(configPath() + ".enable",
|
|
||||||
"Will prevent players from selecting and using trades of unoptimized villagers.\n" +
|
"Will prevent players from selecting and using trades of unoptimized villagers.\n" +
|
||||||
"Use this if you have a lot of villagers and therefore want to force your players to optimize them.\n" +
|
"Use this if you have a lot of villagers and therefore want to force your players to optimize them.\n" +
|
||||||
"Inventories can still be opened so players can move villagers around.");
|
"Inventories can still be opened so players can move villagers around.");
|
||||||
this.notify_player = config.getBoolean(configPath() + ".notify-player", true,
|
this.notify_player = config.getBoolean(configPath + ".notify-player", true,
|
||||||
"Sends players a message when they try to trade with an unoptimized villager.");
|
"Sends players a message when they try to trade with an unoptimized villager.");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public String configPath() {
|
|
||||||
return "gameplay.prevent-trading-with-unoptimized";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void enable() {
|
public void enable() {
|
||||||
VillagerOptimizer plugin = VillagerOptimizer.getInstance();
|
|
||||||
plugin.getServer().getPluginManager().registerEvents(this, plugin);
|
plugin.getServer().getPluginManager().registerEvents(this, plugin);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -51,38 +41,36 @@ public class PreventUnoptimizedTrading implements VillagerOptimizerModule, Liste
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean shouldEnable() {
|
public boolean shouldEnable() {
|
||||||
return VillagerOptimizer.getConfiguration().getBoolean(configPath() + ".enable", false);
|
return config.getBoolean(configPath + ".enable", false);
|
||||||
}
|
}
|
||||||
|
|
||||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
private void onTradeOpen(TradeSelectEvent event) {
|
private void onTradeOpen(TradeSelectEvent event) {
|
||||||
if (!event.getInventory().getType().equals(InventoryType.MERCHANT)) return;
|
if (event.getInventory().getType() != InventoryType.MERCHANT) return;
|
||||||
if (event.getWhoClicked().hasPermission(Permissions.Bypass.TRADE_PREVENTION.get())) return;
|
if (event.getWhoClicked().hasPermission(Permissions.Bypass.TRADE_PREVENTION.get())) return;
|
||||||
if (!(event.getInventory().getHolder() instanceof Villager)) return;
|
if (!(event.getInventory().getHolder() instanceof Villager)) return;
|
||||||
if (villagerCache.getOrAdd((Villager) event.getInventory().getHolder()).isOptimized()) return;
|
if (wrapperCache.get((Villager) event.getInventory().getHolder(), WrappedVillager::new).isOptimized()) return;
|
||||||
|
|
||||||
event.setCancelled(true);
|
event.setCancelled(true);
|
||||||
|
|
||||||
if (notify_player) {
|
if (notify_player) {
|
||||||
Player player = (Player) event.getWhoClicked();
|
Player player = (Player) event.getWhoClicked();
|
||||||
VillagerOptimizer.getLang(player.locale()).optimize_for_trading
|
VillagerOptimizer.getLang(player.locale()).optimize_for_trading.forEach(line -> KyoriUtil.sendMessage(player, line));
|
||||||
.forEach(line -> KyoriUtil.sendMessage(player, line));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
private void onInventoryClick(InventoryClickEvent event) {
|
private void onInventoryClick(InventoryClickEvent event) {
|
||||||
if (!event.getInventory().getType().equals(InventoryType.MERCHANT)) return;
|
if (event.getInventory().getType() != InventoryType.MERCHANT) return;
|
||||||
if (event.getWhoClicked().hasPermission(Permissions.Bypass.TRADE_PREVENTION.get())) return;
|
if (event.getWhoClicked().hasPermission(Permissions.Bypass.TRADE_PREVENTION.get())) return;
|
||||||
if (!(event.getInventory().getHolder() instanceof Villager)) return;
|
if (!(event.getInventory().getHolder() instanceof Villager)) return;
|
||||||
if (villagerCache.getOrAdd((Villager) event.getInventory().getHolder()).isOptimized()) return;
|
if (wrapperCache.get((Villager) event.getInventory().getHolder(), WrappedVillager::new).isOptimized()) return;
|
||||||
|
|
||||||
event.setCancelled(true);
|
event.setCancelled(true);
|
||||||
|
|
||||||
if (notify_player) {
|
if (notify_player) {
|
||||||
Player player = (Player) event.getWhoClicked();
|
Player player = (Player) event.getWhoClicked();
|
||||||
VillagerOptimizer.getLang(player.locale()).optimize_for_trading
|
VillagerOptimizer.getLang(player.locale()).optimize_for_trading.forEach(line -> KyoriUtil.sendMessage(player, line));
|
||||||
.forEach(line -> KyoriUtil.sendMessage(player, line));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,17 +1,14 @@
|
|||||||
package me.xginko.villageroptimizer.modules.gameplay;
|
package me.xginko.villageroptimizer.modules.gameplay;
|
||||||
|
|
||||||
import me.xginko.villageroptimizer.VillagerCache;
|
import com.cryptomorin.xseries.XEntityType;
|
||||||
import me.xginko.villageroptimizer.VillagerOptimizer;
|
import me.xginko.villageroptimizer.VillagerOptimizer;
|
||||||
import me.xginko.villageroptimizer.utils.LocationUtil;
|
|
||||||
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
|
|
||||||
import me.xginko.villageroptimizer.config.Config;
|
|
||||||
import me.xginko.villageroptimizer.enums.Permissions;
|
|
||||||
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
|
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
|
||||||
import me.xginko.villageroptimizer.utils.Util;
|
import me.xginko.villageroptimizer.struct.enums.Permissions;
|
||||||
import me.xginko.villageroptimizer.utils.KyoriUtil;
|
import me.xginko.villageroptimizer.utils.KyoriUtil;
|
||||||
|
import me.xginko.villageroptimizer.utils.LocationUtil;
|
||||||
|
import me.xginko.villageroptimizer.utils.Util;
|
||||||
|
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
|
||||||
import net.kyori.adventure.text.TextReplacementConfig;
|
import net.kyori.adventure.text.TextReplacementConfig;
|
||||||
import org.bukkit.entity.EntityType;
|
|
||||||
import org.bukkit.entity.Player;
|
|
||||||
import org.bukkit.entity.Villager;
|
import org.bukkit.entity.Villager;
|
||||||
import org.bukkit.event.EventHandler;
|
import org.bukkit.event.EventHandler;
|
||||||
import org.bukkit.event.EventPriority;
|
import org.bukkit.event.EventPriority;
|
||||||
@ -20,35 +17,32 @@ import org.bukkit.event.Listener;
|
|||||||
import org.bukkit.event.player.PlayerInteractEntityEvent;
|
import org.bukkit.event.player.PlayerInteractEntityEvent;
|
||||||
|
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.SortedSet;
|
||||||
|
import java.util.TreeSet;
|
||||||
|
|
||||||
public class RestockOptimizedTrades implements VillagerOptimizerModule, Listener {
|
public class RestockOptimizedTrades extends VillagerOptimizerModule implements Listener {
|
||||||
|
|
||||||
private final VillagerCache villagerCache;
|
private final SortedSet<Long> restockDayTimes;
|
||||||
private final long restock_delay_millis;
|
|
||||||
private final boolean log_enabled, notify_player;
|
private final boolean log_enabled, notify_player;
|
||||||
|
|
||||||
public RestockOptimizedTrades() {
|
public RestockOptimizedTrades() {
|
||||||
shouldEnable();
|
super("gameplay.restock-optimized-trades");
|
||||||
this.villagerCache = VillagerOptimizer.getCache();
|
config.master().addComment(configPath,
|
||||||
Config config = VillagerOptimizer.getConfiguration();
|
|
||||||
config.master().addComment(configPath(),
|
|
||||||
"This is for automatic restocking of trades for optimized villagers. Optimized Villagers\n" +
|
"This is for automatic restocking of trades for optimized villagers. Optimized Villagers\n" +
|
||||||
"don't have enough AI to restock their trades naturally, so this is here as a workaround.");
|
"don't have enough AI to restock their trades naturally, so this is here as a workaround.");
|
||||||
this.restock_delay_millis = config.getInt(configPath() + ".delay-in-ticks", 1000,
|
this.restockDayTimes = new TreeSet<>(Comparator.reverseOrder());
|
||||||
"1 second = 20 ticks. There are 24.000 ticks in a single minecraft day.") * 50L;
|
this.restockDayTimes.addAll(config.getList(configPath + ".restock-times", Arrays.asList(1000L, 13000L),
|
||||||
this.notify_player = config.getBoolean(configPath() + ".notify-player", true,
|
"At which (tick-)times during the day villagers will restock.\n" +
|
||||||
|
"There are 24.000 ticks in a single minecraft day."));
|
||||||
|
this.notify_player = config.getBoolean(configPath + ".notify-player", true,
|
||||||
"Sends the player a message when the trades were restocked on a clicked villager.");
|
"Sends the player a message when the trades were restocked on a clicked villager.");
|
||||||
this.log_enabled = config.getBoolean(configPath() + ".log", false);
|
this.log_enabled = config.getBoolean(configPath + ".log", false);
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String configPath() {
|
|
||||||
return "gameplay.restock-optimized-trades";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void enable() {
|
public void enable() {
|
||||||
VillagerOptimizer plugin = VillagerOptimizer.getInstance();
|
|
||||||
plugin.getServer().getPluginManager().registerEvents(this, plugin);
|
plugin.getServer().getPluginManager().registerEvents(this, plugin);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -63,31 +57,54 @@ public class RestockOptimizedTrades implements VillagerOptimizerModule, Listener
|
|||||||
}
|
}
|
||||||
|
|
||||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
private void onInteract(PlayerInteractEntityEvent event) {
|
private void onPlayerInteractEntity(PlayerInteractEntityEvent event) {
|
||||||
if (!event.getRightClicked().getType().equals(EntityType.VILLAGER)) return;
|
if (event.getRightClicked().getType() != XEntityType.VILLAGER.get()) return;
|
||||||
|
|
||||||
final WrappedVillager wVillager = villagerCache.getOrAdd((Villager) event.getRightClicked());
|
WrappedVillager wrapped = wrapperCache.get((Villager) event.getRightClicked(), WrappedVillager::new);
|
||||||
if (!wVillager.isOptimized()) return;
|
if (!wrapped.isOptimized()) return;
|
||||||
|
|
||||||
final Player player = event.getPlayer();
|
if (event.getPlayer().hasPermission(Permissions.Bypass.RESTOCK_COOLDOWN.get())) {
|
||||||
final boolean player_bypassing = player.hasPermission(Permissions.Bypass.RESTOCK_COOLDOWN.get());
|
wrapped.restock();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (wVillager.canRestock(restock_delay_millis) || player_bypassing) {
|
long lastRestockFullTimeTicks = wrapped.getLastRestockFullTime();
|
||||||
wVillager.restock();
|
long currentFullTimeTicks = wrapped.currentFullTimeTicks();
|
||||||
wVillager.saveRestockTime();
|
long currentDayTimeTicks = wrapped.currentDayTimeTicks();
|
||||||
|
|
||||||
if (notify_player && !player_bypassing) {
|
long currentDay = currentFullTimeTicks - currentDayTimeTicks;
|
||||||
final TextReplacementConfig timeLeft = TextReplacementConfig.builder()
|
long ticksTillRestock = (24000 + currentDay + restockDayTimes.first()) - currentFullTimeTicks;
|
||||||
.matchLiteral("%time%")
|
|
||||||
.replacement(Util.formatDuration(Duration.ofMillis(wVillager.getRestockCooldownMillis(restock_delay_millis))))
|
boolean restocked = false;
|
||||||
.build();
|
|
||||||
VillagerOptimizer.getLang(player.locale()).trades_restocked
|
for (Long restockDayTime : restockDayTimes) {
|
||||||
.forEach(line -> KyoriUtil.sendMessage(player, line.replaceText(timeLeft)));
|
long restockTimeToday = currentDay + restockDayTime;
|
||||||
|
|
||||||
|
if (currentFullTimeTicks < restockTimeToday || lastRestockFullTimeTicks >= restockTimeToday) {
|
||||||
|
ticksTillRestock = Math.min(ticksTillRestock, restockTimeToday - currentFullTimeTicks);
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (log_enabled) {
|
if (!restocked) {
|
||||||
info("Restocked optimized villager at " + LocationUtil.toString(wVillager.villager().getLocation()));
|
wrapped.restock();
|
||||||
|
wrapped.saveRestockTime();
|
||||||
|
restocked = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!restocked) return;
|
||||||
|
|
||||||
|
if (notify_player) {
|
||||||
|
final TextReplacementConfig timeLeft = TextReplacementConfig.builder()
|
||||||
|
.matchLiteral("%time%")
|
||||||
|
.replacement(Util.formatDuration(Duration.ofMillis(ticksTillRestock * 50L)))
|
||||||
|
.build();
|
||||||
|
VillagerOptimizer.getLang(event.getPlayer().locale()).trades_restocked
|
||||||
|
.forEach(line -> KyoriUtil.sendMessage(event.getPlayer(), line.replaceText(timeLeft)));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (log_enabled) {
|
||||||
|
info("Restocked optimized villager at " + LocationUtil.toString(wrapped.villager.getLocation()));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,32 +1,24 @@
|
|||||||
package me.xginko.villageroptimizer.modules.gameplay;
|
package me.xginko.villageroptimizer.modules.gameplay;
|
||||||
|
|
||||||
import me.xginko.villageroptimizer.VillagerCache;
|
import me.xginko.villageroptimizer.struct.enums.OptimizationType;
|
||||||
import me.xginko.villageroptimizer.VillagerOptimizer;
|
|
||||||
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
|
|
||||||
import me.xginko.villageroptimizer.enums.OptimizationType;
|
|
||||||
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
|
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
|
||||||
|
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
|
||||||
import org.bukkit.event.EventHandler;
|
import org.bukkit.event.EventHandler;
|
||||||
import org.bukkit.event.EventPriority;
|
import org.bukkit.event.EventPriority;
|
||||||
import org.bukkit.event.HandlerList;
|
import org.bukkit.event.HandlerList;
|
||||||
import org.bukkit.event.Listener;
|
import org.bukkit.event.Listener;
|
||||||
import org.bukkit.event.entity.VillagerCareerChangeEvent;
|
import org.bukkit.event.entity.VillagerCareerChangeEvent;
|
||||||
|
|
||||||
public class UnoptimizeOnJobLoose implements VillagerOptimizerModule, Listener {
|
public class UnoptimizeOnJobLoose extends VillagerOptimizerModule implements Listener {
|
||||||
|
|
||||||
private final VillagerCache villagerCache;
|
|
||||||
|
|
||||||
public UnoptimizeOnJobLoose() {
|
public UnoptimizeOnJobLoose() {
|
||||||
this.villagerCache = VillagerOptimizer.getCache();
|
super("gameplay.unoptimize-on-job-loose");
|
||||||
}
|
config.master().addComment(configPath + ".enable",
|
||||||
|
"Villagers that get their jobs reset will become unoptimized again.");
|
||||||
@Override
|
|
||||||
public String configPath() {
|
|
||||||
return "gameplay.unoptimize-on-job-loose";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void enable() {
|
public void enable() {
|
||||||
VillagerOptimizer plugin = VillagerOptimizer.getInstance();
|
|
||||||
plugin.getServer().getPluginManager().registerEvents(this, plugin);
|
plugin.getServer().getPluginManager().registerEvents(this, plugin);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -37,16 +29,15 @@ public class UnoptimizeOnJobLoose implements VillagerOptimizerModule, Listener {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean shouldEnable() {
|
public boolean shouldEnable() {
|
||||||
return VillagerOptimizer.getConfiguration().getBoolean(configPath() + ".enable", true,
|
return config.getBoolean(configPath + ".enable", true);
|
||||||
"Villagers that get their jobs reset will become unoptimized again.");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
private void onJobReset(VillagerCareerChangeEvent event) {
|
private void onJobReset(VillagerCareerChangeEvent event) {
|
||||||
if (!event.getReason().equals(VillagerCareerChangeEvent.ChangeReason.LOSING_JOB)) return;
|
if (event.getReason() != VillagerCareerChangeEvent.ChangeReason.LOSING_JOB) return;
|
||||||
final WrappedVillager wrappedVillager = villagerCache.getOrAdd(event.getEntity());
|
final WrappedVillager wrapped = wrapperCache.get(event.getEntity(), WrappedVillager::new);
|
||||||
if (wrappedVillager.isOptimized()) {
|
if (wrapped.isOptimized()) {
|
||||||
wrappedVillager.setOptimizationType(OptimizationType.NONE);
|
wrapped.setOptimizationType(OptimizationType.NONE);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,8 +1,5 @@
|
|||||||
package me.xginko.villageroptimizer.modules.gameplay;
|
package me.xginko.villageroptimizer.modules.gameplay;
|
||||||
|
|
||||||
import com.tcoded.folialib.impl.ServerImplementation;
|
|
||||||
import me.xginko.villageroptimizer.VillagerOptimizer;
|
|
||||||
import me.xginko.villageroptimizer.config.Config;
|
|
||||||
import me.xginko.villageroptimizer.events.VillagerOptimizeEvent;
|
import me.xginko.villageroptimizer.events.VillagerOptimizeEvent;
|
||||||
import me.xginko.villageroptimizer.events.VillagerUnoptimizeEvent;
|
import me.xginko.villageroptimizer.events.VillagerUnoptimizeEvent;
|
||||||
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
|
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
|
||||||
@ -12,26 +9,16 @@ import org.bukkit.event.EventPriority;
|
|||||||
import org.bukkit.event.HandlerList;
|
import org.bukkit.event.HandlerList;
|
||||||
import org.bukkit.event.Listener;
|
import org.bukkit.event.Listener;
|
||||||
|
|
||||||
public class VisuallyHighlightOptimized implements VillagerOptimizerModule, Listener {
|
public class VisuallyHighlightOptimized extends VillagerOptimizerModule implements Listener {
|
||||||
|
|
||||||
private final ServerImplementation scheduler;
|
|
||||||
|
|
||||||
public VisuallyHighlightOptimized() {
|
public VisuallyHighlightOptimized() {
|
||||||
shouldEnable();
|
super("gameplay.outline-optimized-villagers");
|
||||||
this.scheduler = VillagerOptimizer.getFoliaLib().getImpl();
|
|
||||||
Config config = VillagerOptimizer.getConfiguration();
|
|
||||||
config.master().addComment("gameplay.outline-optimized-villagers.enable",
|
config.master().addComment("gameplay.outline-optimized-villagers.enable",
|
||||||
"Will make optimized villagers glow.");
|
"Will make optimized villagers glow.");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public String configPath() {
|
|
||||||
return "gameplay.outline-optimized-villagers";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void enable() {
|
public void enable() {
|
||||||
VillagerOptimizer plugin = VillagerOptimizer.getInstance();
|
|
||||||
plugin.getServer().getPluginManager().registerEvents(this, plugin);
|
plugin.getServer().getPluginManager().registerEvents(this, plugin);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -42,22 +29,22 @@ public class VisuallyHighlightOptimized implements VillagerOptimizerModule, List
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean shouldEnable() {
|
public boolean shouldEnable() {
|
||||||
return VillagerOptimizer.getConfiguration().getBoolean("gameplay.outline-optimized-villagers.enable", false);
|
return config.getBoolean("gameplay.outline-optimized-villagers.enable", false);
|
||||||
}
|
}
|
||||||
|
|
||||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
private void onOptimize(VillagerOptimizeEvent event) {
|
private void onOptimize(VillagerOptimizeEvent event) {
|
||||||
Villager villager = event.getWrappedVillager().villager();
|
Villager villager = event.getWrappedVillager().villager;
|
||||||
scheduler.runAtEntity(villager, glow -> {
|
scheduling.entitySpecificScheduler(villager).run(glow -> {
|
||||||
if (!villager.isGlowing()) villager.setGlowing(true);
|
if (!villager.isGlowing()) villager.setGlowing(true);
|
||||||
});
|
}, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
private void onUnOptimize(VillagerUnoptimizeEvent event) {
|
private void onUnOptimize(VillagerUnoptimizeEvent event) {
|
||||||
Villager villager = event.getWrappedVillager().villager();
|
Villager villager = event.getWrappedVillager().villager;
|
||||||
scheduler.runAtEntity(villager, unGlow -> {
|
scheduling.entitySpecificScheduler(villager).run(unGlow -> {
|
||||||
if (villager.isGlowing()) villager.setGlowing(false);
|
if (villager.isGlowing()) villager.setGlowing(false);
|
||||||
});
|
}, null);
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -0,0 +1,240 @@
|
|||||||
|
package me.xginko.villageroptimizer.modules.optimization;
|
||||||
|
|
||||||
|
import com.cryptomorin.xseries.XEntityType;
|
||||||
|
import com.destroystokyo.paper.event.entity.EntityPathfindEvent;
|
||||||
|
import com.github.benmanes.caffeine.cache.Cache;
|
||||||
|
import com.github.benmanes.caffeine.cache.Caffeine;
|
||||||
|
import me.xginko.villageroptimizer.VillagerOptimizer;
|
||||||
|
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
|
||||||
|
import me.xginko.villageroptimizer.struct.enums.OptimizationType;
|
||||||
|
import me.xginko.villageroptimizer.struct.models.BlockRegion2D;
|
||||||
|
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
|
||||||
|
import net.kyori.adventure.text.TextReplacementConfig;
|
||||||
|
import org.bukkit.Location;
|
||||||
|
import org.bukkit.entity.Entity;
|
||||||
|
import org.bukkit.entity.Player;
|
||||||
|
import org.bukkit.entity.Villager;
|
||||||
|
import org.bukkit.event.EventHandler;
|
||||||
|
import org.bukkit.event.EventPriority;
|
||||||
|
import org.bukkit.event.HandlerList;
|
||||||
|
import org.bukkit.event.Listener;
|
||||||
|
import org.bukkit.event.entity.EntityInteractEvent;
|
||||||
|
import org.jetbrains.annotations.NotNull;
|
||||||
|
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.concurrent.CopyOnWriteArraySet;
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
|
||||||
|
public class OptimizeByActivity extends VillagerOptimizerModule implements Listener {
|
||||||
|
|
||||||
|
protected static class RegionData {
|
||||||
|
|
||||||
|
public final BlockRegion2D region;
|
||||||
|
public final AtomicInteger pathfindCount, entityInteractCount;
|
||||||
|
public final AtomicBoolean regionBusy;
|
||||||
|
|
||||||
|
public RegionData(BlockRegion2D region) {
|
||||||
|
this.region = region;
|
||||||
|
this.pathfindCount = new AtomicInteger();
|
||||||
|
this.entityInteractCount = new AtomicInteger();
|
||||||
|
this.regionBusy = new AtomicBoolean(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private final Cache<BlockRegion2D, RegionData> regionDataCache;
|
||||||
|
private final double checkRadius;
|
||||||
|
private final int pathfindLimit, entityInteractLimit;
|
||||||
|
private final boolean notifyPlayers, doLogging;
|
||||||
|
|
||||||
|
public OptimizeByActivity() {
|
||||||
|
super("optimization-methods.regional-activity");
|
||||||
|
config.master().addComment(configPath + ".enable",
|
||||||
|
"Enable optimization by naming villagers to one of the names configured below.\n" +
|
||||||
|
"Nametag optimized villagers will be unoptimized again when they are renamed to something else.");
|
||||||
|
|
||||||
|
this.checkRadius = config.getDouble(configPath + ".check-radius-blocks", 500.0,
|
||||||
|
"The radius in blocks in which activity will be grouped together and measured.");
|
||||||
|
this.regionDataCache = Caffeine.newBuilder().expireAfterWrite(Duration.ofMillis(
|
||||||
|
config.getInt(configPath + ".data-keep-time-millis", 10000,
|
||||||
|
"The time in milliseconds before a region and its data will be expired\n" +
|
||||||
|
"if no activity has been detected.\n" +
|
||||||
|
"For proper functionality, needs to be at least as long as your pause time."))).build();
|
||||||
|
|
||||||
|
this.pathfindLimit = config.getInt(configPath + ".limits.pathfind-event", 150);
|
||||||
|
this.entityInteractLimit = config.getInt(configPath + ".limits.interact-event", 50);
|
||||||
|
|
||||||
|
this.notifyPlayers = config.getBoolean(configPath + ".notify-players", true,
|
||||||
|
"Sends players a message to any player near an auto-optimized villager.");
|
||||||
|
this.doLogging = config.getBoolean(configPath + ".log", false);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void enable() {
|
||||||
|
plugin.getServer().getPluginManager().registerEvents(this, plugin);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void disable() {
|
||||||
|
HandlerList.unregisterAll(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean shouldEnable() {
|
||||||
|
return config.getBoolean(configPath + ".enable", false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private @NotNull RegionData getRegionData(Location location) {
|
||||||
|
return regionDataCache.get(getRegion(location), RegionData::new);
|
||||||
|
}
|
||||||
|
|
||||||
|
private @NotNull BlockRegion2D getRegion(Location location) {
|
||||||
|
// Find and return region containing this location
|
||||||
|
for (Map.Entry<BlockRegion2D, RegionData> regionDataEntry : regionDataCache.asMap().entrySet()) {
|
||||||
|
if (regionDataEntry.getKey().contains(location)) {
|
||||||
|
return regionDataEntry.getKey();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create and cache region if none exists
|
||||||
|
BlockRegion2D region = BlockRegion2D.of(location.getWorld(), location.getX(), location.getZ(), checkRadius);
|
||||||
|
regionDataCache.put(region, new RegionData(region));
|
||||||
|
return region;
|
||||||
|
}
|
||||||
|
|
||||||
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
|
private void onEntityPathfind(EntityPathfindEvent event) {
|
||||||
|
if (event.getEntityType() != XEntityType.VILLAGER.get()) return;
|
||||||
|
|
||||||
|
Location location = event.getEntity().getLocation();
|
||||||
|
BlockRegion2D region2D = getRegion(location);
|
||||||
|
RegionData regionData = getRegionData(location);
|
||||||
|
|
||||||
|
if (regionData.regionBusy.get() || regionData.pathfindCount.incrementAndGet() <= pathfindLimit) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
regionData.regionBusy.set(true);
|
||||||
|
|
||||||
|
AtomicInteger optimizeCount = new AtomicInteger();
|
||||||
|
Set<Player> playersWithinArea = new CopyOnWriteArraySet<>();
|
||||||
|
|
||||||
|
region2D.getEntities()
|
||||||
|
.thenAccept(entities -> {
|
||||||
|
for (Entity entity : entities) {
|
||||||
|
scheduling.entitySpecificScheduler(entity).run(() -> {
|
||||||
|
if (entity.getType() == XEntityType.VILLAGER.get()) {
|
||||||
|
WrappedVillager wrappedVillager = wrapperCache.get((Villager) entity, WrappedVillager::new);
|
||||||
|
|
||||||
|
if (wrappedVillager.isOptimized()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
wrappedVillager.setOptimizationType(OptimizationType.REGIONAL_ACTIVITY);
|
||||||
|
optimizeCount.incrementAndGet();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (notifyPlayers && entity.getType() == XEntityType.PLAYER.get()) {
|
||||||
|
playersWithinArea.add((Player) entity);
|
||||||
|
}
|
||||||
|
}, null);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.thenRun(() -> {
|
||||||
|
if (notifyPlayers) {
|
||||||
|
TextReplacementConfig amount = TextReplacementConfig.builder()
|
||||||
|
.matchLiteral("%amount%")
|
||||||
|
.replacement(optimizeCount.toString())
|
||||||
|
.build();
|
||||||
|
|
||||||
|
for (Player player : playersWithinArea) {
|
||||||
|
VillagerOptimizer.scheduling().entitySpecificScheduler(player).run(() ->
|
||||||
|
VillagerOptimizer.getLang(player.locale()).activity_optimize_success
|
||||||
|
.forEach(line -> player.sendMessage(line.replaceText(amount))),
|
||||||
|
null);
|
||||||
|
}
|
||||||
|
|
||||||
|
playersWithinArea.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (doLogging) {
|
||||||
|
info( "Optimized " + optimizeCount.get() + " villagers in a radius of " + checkRadius +
|
||||||
|
" blocks from center at x=" + regionData.region.getCenterX() + ", z=" + regionData.region.getCenterZ() +
|
||||||
|
" in world " + location.getWorld().getName() +
|
||||||
|
"because of too high pathfinding activity within the configured timeframe: " +
|
||||||
|
regionData.pathfindCount + " (limit: " + pathfindLimit + ")");
|
||||||
|
}
|
||||||
|
|
||||||
|
regionDataCache.invalidate(region2D);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
|
private void onEntityInteract(EntityInteractEvent event) {
|
||||||
|
if (event.getEntityType() != XEntityType.VILLAGER.get()) return;
|
||||||
|
|
||||||
|
Location location = event.getEntity().getLocation();
|
||||||
|
BlockRegion2D region2D = getRegion(location);
|
||||||
|
RegionData regionData = getRegionData(location);
|
||||||
|
|
||||||
|
if (regionData.regionBusy.get() || regionData.entityInteractCount.incrementAndGet() <= entityInteractLimit) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
regionData.regionBusy.set(true);
|
||||||
|
|
||||||
|
AtomicInteger optimizeCount = new AtomicInteger();
|
||||||
|
Set<Player> playersWithinArea = new CopyOnWriteArraySet<>();
|
||||||
|
|
||||||
|
region2D.getEntities()
|
||||||
|
.thenAccept(entities -> {
|
||||||
|
for (Entity entity : entities) {
|
||||||
|
scheduling.entitySpecificScheduler(entity).run(() -> {
|
||||||
|
if (entity.getType() == XEntityType.VILLAGER.get()) {
|
||||||
|
WrappedVillager wrappedVillager = wrapperCache.get((Villager) entity, WrappedVillager::new);
|
||||||
|
|
||||||
|
if (wrappedVillager.isOptimized()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
wrappedVillager.setOptimizationType(OptimizationType.REGIONAL_ACTIVITY);
|
||||||
|
optimizeCount.incrementAndGet();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (notifyPlayers && entity.getType() == XEntityType.PLAYER.get()) {
|
||||||
|
playersWithinArea.add((Player) entity);
|
||||||
|
}
|
||||||
|
}, null);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.thenRun(() -> {
|
||||||
|
if (notifyPlayers) {
|
||||||
|
TextReplacementConfig amount = TextReplacementConfig.builder()
|
||||||
|
.matchLiteral("%amount%")
|
||||||
|
.replacement(optimizeCount.toString())
|
||||||
|
.build();
|
||||||
|
|
||||||
|
for (Player player : playersWithinArea) {
|
||||||
|
VillagerOptimizer.scheduling().entitySpecificScheduler(player).run(() ->
|
||||||
|
VillagerOptimizer.getLang(player.locale()).activity_optimize_success
|
||||||
|
.forEach(line -> player.sendMessage(line.replaceText(amount))),
|
||||||
|
null);
|
||||||
|
}
|
||||||
|
|
||||||
|
playersWithinArea.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (doLogging) {
|
||||||
|
info( "Optimized " + optimizeCount.get() + " villagers in a radius of " + checkRadius +
|
||||||
|
" blocks from center at x=" + regionData.region.getCenterX() + ", z=" + regionData.region.getCenterZ() +
|
||||||
|
" in world " + location.getWorld().getName() +
|
||||||
|
"because of too many villagers interacting with objects within the configured timeframe: " +
|
||||||
|
regionData.pathfindCount + " (limit: " + pathfindLimit + ")");
|
||||||
|
}
|
||||||
|
|
||||||
|
regionDataCache.invalidate(region2D);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
@ -1,16 +1,15 @@
|
|||||||
package me.xginko.villageroptimizer.modules.optimization;
|
package me.xginko.villageroptimizer.modules.optimization;
|
||||||
|
|
||||||
import me.xginko.villageroptimizer.VillagerCache;
|
import com.cryptomorin.xseries.XMaterial;
|
||||||
import me.xginko.villageroptimizer.VillagerOptimizer;
|
import me.xginko.villageroptimizer.VillagerOptimizer;
|
||||||
import me.xginko.villageroptimizer.config.Config;
|
import me.xginko.villageroptimizer.struct.enums.OptimizationType;
|
||||||
import me.xginko.villageroptimizer.enums.OptimizationType;
|
import me.xginko.villageroptimizer.struct.enums.Permissions;
|
||||||
import me.xginko.villageroptimizer.enums.Permissions;
|
|
||||||
import me.xginko.villageroptimizer.events.VillagerOptimizeEvent;
|
import me.xginko.villageroptimizer.events.VillagerOptimizeEvent;
|
||||||
import me.xginko.villageroptimizer.events.VillagerUnoptimizeEvent;
|
import me.xginko.villageroptimizer.events.VillagerUnoptimizeEvent;
|
||||||
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
|
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
|
||||||
import me.xginko.villageroptimizer.utils.Util;
|
|
||||||
import me.xginko.villageroptimizer.utils.KyoriUtil;
|
import me.xginko.villageroptimizer.utils.KyoriUtil;
|
||||||
import me.xginko.villageroptimizer.utils.LocationUtil;
|
import me.xginko.villageroptimizer.utils.LocationUtil;
|
||||||
|
import me.xginko.villageroptimizer.utils.Util;
|
||||||
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
|
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
|
||||||
import net.kyori.adventure.text.TextReplacementConfig;
|
import net.kyori.adventure.text.TextReplacementConfig;
|
||||||
import org.bukkit.Location;
|
import org.bukkit.Location;
|
||||||
@ -26,31 +25,32 @@ import org.bukkit.event.block.BlockBreakEvent;
|
|||||||
import org.bukkit.event.block.BlockPlaceEvent;
|
import org.bukkit.event.block.BlockPlaceEvent;
|
||||||
|
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.EnumSet;
|
import java.util.EnumSet;
|
||||||
|
import java.util.List;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
public class OptimizeByBlock implements VillagerOptimizerModule, Listener {
|
public class OptimizeByBlock extends VillagerOptimizerModule implements Listener {
|
||||||
|
|
||||||
private final VillagerCache villagerCache;
|
|
||||||
private final Set<Material> blocks_that_disable;
|
private final Set<Material> blocks_that_disable;
|
||||||
private final long cooldown_millis;
|
private final long cooldown_millis;
|
||||||
private final double search_radius;
|
private final double search_radius;
|
||||||
private final boolean only_while_sneaking, notify_player, log_enabled;
|
private final boolean only_while_sneaking, notify_player, log_enabled;
|
||||||
|
|
||||||
public OptimizeByBlock() {
|
public OptimizeByBlock() {
|
||||||
shouldEnable();
|
super("optimization-methods.block-optimization");
|
||||||
this.villagerCache = VillagerOptimizer.getCache();
|
config.master().addComment(configPath + ".enable",
|
||||||
Config config = VillagerOptimizer.getConfiguration();
|
|
||||||
config.master().addComment(configPath() + ".enable",
|
|
||||||
"When enabled, the closest villager standing near a configured block being placed will be optimized.\n" +
|
"When enabled, the closest villager standing near a configured block being placed will be optimized.\n" +
|
||||||
"If a configured block is broken nearby, the closest villager will become unoptimized again.");
|
"If a configured block is broken nearby, the closest villager will become unoptimized again.");
|
||||||
this.blocks_that_disable = config.getList(configPath() + ".materials", Arrays.asList(
|
List<String> defaults = Stream.of(XMaterial.LAPIS_BLOCK, XMaterial.GLOWSTONE, XMaterial.IRON_BLOCK)
|
||||||
"LAPIS_BLOCK", "GLOWSTONE", "IRON_BLOCK"
|
.filter(XMaterial::isSupported)
|
||||||
), "Values here need to be valid bukkit Material enums for your server version.")
|
.map(Enum::name)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
this.blocks_that_disable = config.getList(configPath + ".materials", defaults,
|
||||||
|
"Values here need to be valid bukkit Material enums for your server version.")
|
||||||
.stream()
|
.stream()
|
||||||
.map(configuredMaterial -> {
|
.map(configuredMaterial -> {
|
||||||
try {
|
try {
|
||||||
@ -64,27 +64,21 @@ public class OptimizeByBlock implements VillagerOptimizerModule, Listener {
|
|||||||
.filter(Objects::nonNull)
|
.filter(Objects::nonNull)
|
||||||
.collect(Collectors.toCollection(() -> EnumSet.noneOf(Material.class)));
|
.collect(Collectors.toCollection(() -> EnumSet.noneOf(Material.class)));
|
||||||
this.cooldown_millis = TimeUnit.SECONDS.toMillis(
|
this.cooldown_millis = TimeUnit.SECONDS.toMillis(
|
||||||
config.getInt(configPath() + ".optimize-cooldown-seconds", 600,
|
config.getInt(configPath + ".optimize-cooldown-seconds", 600,
|
||||||
"Cooldown in seconds until a villager can be optimized again by using specific blocks.\n" +
|
"Cooldown in seconds until a villager can be optimized again by using specific blocks.\n" +
|
||||||
"Here for configuration freedom. Recommended to leave as is to not enable any exploitable behavior."));
|
"Here for configuration freedom. Recommended to leave as is to not enable any exploitable behavior."));
|
||||||
this.search_radius = config.getDouble(configPath() + ".search-radius-in-blocks", 2.0,
|
this.search_radius = config.getDouble(configPath + ".search-radius-in-blocks", 2.0,
|
||||||
"The radius in blocks a villager can be away from the player when he places an optimize block.\n" +
|
"The radius in blocks a villager can be away from the player when he places an optimize block.\n" +
|
||||||
"The closest unoptimized villager to the player will be optimized.") / 2;
|
"The closest unoptimized villager to the player will be optimized.") / 2;
|
||||||
this.only_while_sneaking = config.getBoolean(configPath() + ".only-when-sneaking", true,
|
this.only_while_sneaking = config.getBoolean(configPath + ".only-when-sneaking", true,
|
||||||
"Only optimize/unoptimize by block when player is sneaking during place or break.");
|
"Only optimize/unoptimize by block when player is sneaking during place or break.");
|
||||||
this.notify_player = config.getBoolean(configPath() + ".notify-player", true,
|
this.notify_player = config.getBoolean(configPath + ".notify-player", true,
|
||||||
"Sends players a message when they successfully optimized or unoptimized a villager.");
|
"Sends players a message when they successfully optimized or unoptimized a villager.");
|
||||||
this.log_enabled = config.getBoolean(configPath() + ".log", false);
|
this.log_enabled = config.getBoolean(configPath + ".log", false);
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String configPath() {
|
|
||||||
return "optimization-methods.block-optimization";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void enable() {
|
public void enable() {
|
||||||
VillagerOptimizer plugin = VillagerOptimizer.getInstance();
|
|
||||||
plugin.getServer().getPluginManager().registerEvents(this, plugin);
|
plugin.getServer().getPluginManager().registerEvents(this, plugin);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -95,7 +89,7 @@ public class OptimizeByBlock implements VillagerOptimizerModule, Listener {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean shouldEnable() {
|
public boolean shouldEnable() {
|
||||||
return VillagerOptimizer.getConfiguration().getBoolean(configPath() + ".enable", false);
|
return config.getBoolean(configPath + ".enable", false);
|
||||||
}
|
}
|
||||||
|
|
||||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
@ -117,7 +111,7 @@ public class OptimizeByBlock implements VillagerOptimizerModule, Listener {
|
|||||||
final double distance = LocationUtil.relDistance3DSquared(villager.getLocation(), blockLoc);
|
final double distance = LocationUtil.relDistance3DSquared(villager.getLocation(), blockLoc);
|
||||||
if (distance >= closestDistance) continue;
|
if (distance >= closestDistance) continue;
|
||||||
|
|
||||||
final WrappedVillager wVillager = villagerCache.getOrAdd(villager);
|
final WrappedVillager wVillager = wrapperCache.get(villager, WrappedVillager::new);
|
||||||
if (wVillager.canOptimize(cooldown_millis)) {
|
if (wVillager.canOptimize(cooldown_millis)) {
|
||||||
closestOptimizableVillager = wVillager;
|
closestOptimizableVillager = wVillager;
|
||||||
closestDistance = distance;
|
closestDistance = distance;
|
||||||
@ -141,11 +135,11 @@ public class OptimizeByBlock implements VillagerOptimizerModule, Listener {
|
|||||||
if (notify_player) {
|
if (notify_player) {
|
||||||
final TextReplacementConfig vilProfession = TextReplacementConfig.builder()
|
final TextReplacementConfig vilProfession = TextReplacementConfig.builder()
|
||||||
.matchLiteral("%vil_profession%")
|
.matchLiteral("%vil_profession%")
|
||||||
.replacement(Util.formatEnum(closestOptimizableVillager.villager().getProfession()))
|
.replacement(Util.toNiceString(closestOptimizableVillager.villager.getProfession()))
|
||||||
.build();
|
.build();
|
||||||
final TextReplacementConfig placedMaterial = TextReplacementConfig.builder()
|
final TextReplacementConfig placedMaterial = TextReplacementConfig.builder()
|
||||||
.matchLiteral("%blocktype%")
|
.matchLiteral("%blocktype%")
|
||||||
.replacement(Util.formatEnum(placed.getType()))
|
.replacement(Util.toNiceString(placed.getType()))
|
||||||
.build();
|
.build();
|
||||||
VillagerOptimizer.getLang(player.locale()).block_optimize_success
|
VillagerOptimizer.getLang(player.locale()).block_optimize_success
|
||||||
.forEach(line -> KyoriUtil.sendMessage(player, line.replaceText(vilProfession).replaceText(placedMaterial)));
|
.forEach(line -> KyoriUtil.sendMessage(player, line.replaceText(vilProfession).replaceText(placedMaterial)));
|
||||||
@ -153,7 +147,7 @@ public class OptimizeByBlock implements VillagerOptimizerModule, Listener {
|
|||||||
|
|
||||||
if (log_enabled) {
|
if (log_enabled) {
|
||||||
info(player.getName() + " optimized villager at " +
|
info(player.getName() + " optimized villager at " +
|
||||||
LocationUtil.toString(closestOptimizableVillager.villager().getLocation()));
|
LocationUtil.toString(closestOptimizableVillager.villager.getLocation()));
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
closestOptimizableVillager.sayNo();
|
closestOptimizableVillager.sayNo();
|
||||||
@ -184,7 +178,7 @@ public class OptimizeByBlock implements VillagerOptimizerModule, Listener {
|
|||||||
final double distance = LocationUtil.relDistance3DSquared(villager.getLocation(), blockLoc);
|
final double distance = LocationUtil.relDistance3DSquared(villager.getLocation(), blockLoc);
|
||||||
if (distance >= closestDistance) continue;
|
if (distance >= closestDistance) continue;
|
||||||
|
|
||||||
final WrappedVillager wVillager = villagerCache.getOrAdd(villager);
|
final WrappedVillager wVillager = wrapperCache.get(villager, WrappedVillager::new);
|
||||||
if (wVillager.isOptimized()) {
|
if (wVillager.isOptimized()) {
|
||||||
closestOptimizedVillager = wVillager;
|
closestOptimizedVillager = wVillager;
|
||||||
closestDistance = distance;
|
closestDistance = distance;
|
||||||
@ -206,19 +200,19 @@ public class OptimizeByBlock implements VillagerOptimizerModule, Listener {
|
|||||||
if (notify_player) {
|
if (notify_player) {
|
||||||
final TextReplacementConfig vilProfession = TextReplacementConfig.builder()
|
final TextReplacementConfig vilProfession = TextReplacementConfig.builder()
|
||||||
.matchLiteral("%vil_profession%")
|
.matchLiteral("%vil_profession%")
|
||||||
.replacement(Util.formatEnum(closestOptimizedVillager.villager().getProfession()))
|
.replacement(Util.toNiceString(closestOptimizedVillager.villager.getProfession()))
|
||||||
.build();
|
.build();
|
||||||
final TextReplacementConfig brokenMaterial = TextReplacementConfig.builder()
|
final TextReplacementConfig brokenMaterial = TextReplacementConfig.builder()
|
||||||
.matchLiteral("%blocktype%")
|
.matchLiteral("%blocktype%")
|
||||||
.replacement(Util.formatEnum(broken.getType()))
|
.replacement(Util.toNiceString(broken.getType()))
|
||||||
.build();
|
.build();
|
||||||
VillagerOptimizer.getLang(player.locale()).block_unoptimize_success
|
VillagerOptimizer.getLang(player.locale()).block_unoptimize_success
|
||||||
.forEach(line -> KyoriUtil.sendMessage(player, line.replaceText(vilProfession).replaceText(brokenMaterial)));
|
.forEach(line -> KyoriUtil.sendMessage(player, line.replaceText(vilProfession).replaceText(brokenMaterial)));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (log_enabled) {
|
if (log_enabled) {
|
||||||
info(player.getName() + " unoptimized villager using " + Util.formatEnum(broken.getType()) +
|
info(player.getName() + " unoptimized villager using " + Util.toNiceString(broken.getType()) +
|
||||||
LocationUtil.toString(closestOptimizedVillager.villager().getLocation()));
|
LocationUtil.toString(closestOptimizedVillager.villager.getLocation()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,21 +1,20 @@
|
|||||||
package me.xginko.villageroptimizer.modules.optimization;
|
package me.xginko.villageroptimizer.modules.optimization;
|
||||||
|
|
||||||
import me.xginko.villageroptimizer.VillagerCache;
|
import com.cryptomorin.xseries.XEntityType;
|
||||||
|
import com.cryptomorin.xseries.XMaterial;
|
||||||
import me.xginko.villageroptimizer.VillagerOptimizer;
|
import me.xginko.villageroptimizer.VillagerOptimizer;
|
||||||
import me.xginko.villageroptimizer.utils.LocationUtil;
|
import me.xginko.villageroptimizer.struct.enums.OptimizationType;
|
||||||
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
|
import me.xginko.villageroptimizer.struct.enums.Permissions;
|
||||||
import me.xginko.villageroptimizer.config.Config;
|
|
||||||
import me.xginko.villageroptimizer.enums.OptimizationType;
|
|
||||||
import me.xginko.villageroptimizer.enums.Permissions;
|
|
||||||
import me.xginko.villageroptimizer.events.VillagerOptimizeEvent;
|
import me.xginko.villageroptimizer.events.VillagerOptimizeEvent;
|
||||||
import me.xginko.villageroptimizer.events.VillagerUnoptimizeEvent;
|
import me.xginko.villageroptimizer.events.VillagerUnoptimizeEvent;
|
||||||
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
|
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
|
||||||
import me.xginko.villageroptimizer.utils.Util;
|
|
||||||
import me.xginko.villageroptimizer.utils.KyoriUtil;
|
import me.xginko.villageroptimizer.utils.KyoriUtil;
|
||||||
|
import me.xginko.villageroptimizer.utils.LocationUtil;
|
||||||
|
import me.xginko.villageroptimizer.utils.Util;
|
||||||
|
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
|
||||||
import net.kyori.adventure.text.TextReplacementConfig;
|
import net.kyori.adventure.text.TextReplacementConfig;
|
||||||
import org.bukkit.ChatColor;
|
import org.bukkit.ChatColor;
|
||||||
import org.bukkit.Material;
|
import org.bukkit.GameMode;
|
||||||
import org.bukkit.entity.EntityType;
|
|
||||||
import org.bukkit.entity.Player;
|
import org.bukkit.entity.Player;
|
||||||
import org.bukkit.entity.Villager;
|
import org.bukkit.entity.Villager;
|
||||||
import org.bukkit.event.EventHandler;
|
import org.bukkit.event.EventHandler;
|
||||||
@ -33,42 +32,33 @@ import java.util.Set;
|
|||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
public class OptimizeByNametag implements VillagerOptimizerModule, Listener {
|
public class OptimizeByNametag extends VillagerOptimizerModule implements Listener {
|
||||||
|
|
||||||
private final VillagerCache villagerCache;
|
|
||||||
private final Set<String> nametags;
|
private final Set<String> nametags;
|
||||||
private final long cooldown;
|
private final long cooldown;
|
||||||
private final boolean consume_nametag, notify_player, log_enabled;
|
private final boolean consume_nametag, notify_player, log_enabled;
|
||||||
|
|
||||||
public OptimizeByNametag() {
|
public OptimizeByNametag() {
|
||||||
shouldEnable();
|
super("optimization-methods.nametag-optimization");
|
||||||
this.villagerCache = VillagerOptimizer.getCache();
|
config.master().addComment(configPath + ".enable",
|
||||||
Config config = VillagerOptimizer.getConfiguration();
|
|
||||||
config.master().addComment(configPath() + ".enable",
|
|
||||||
"Enable optimization by naming villagers to one of the names configured below.\n" +
|
"Enable optimization by naming villagers to one of the names configured below.\n" +
|
||||||
"Nametag optimized villagers will be unoptimized again when they are renamed to something else.");
|
"Nametag optimized villagers will be unoptimized again when they are renamed to something else.");
|
||||||
this.nametags = config.getList(configPath() + ".names", Arrays.asList("Optimize", "DisableAI"),
|
this.nametags = config.getList(configPath + ".names", Arrays.asList("Optimize", "DisableAI"),
|
||||||
"Names are case insensitive, capital letters won't matter.")
|
"Names are case insensitive, capital letters won't matter.")
|
||||||
.stream().map(String::toLowerCase).collect(Collectors.toCollection(HashSet::new));
|
.stream().map(String::toLowerCase).collect(Collectors.toCollection(HashSet::new));
|
||||||
this.consume_nametag = config.getBoolean(configPath() + ".nametags-get-consumed", true,
|
this.consume_nametag = config.getBoolean(configPath + ".nametags-get-consumed", true,
|
||||||
"Enable or disable consumption of the used nametag item.");
|
"Enable or disable consumption of the used nametag item.");
|
||||||
this.cooldown = TimeUnit.SECONDS.toMillis(
|
this.cooldown = TimeUnit.SECONDS.toMillis(
|
||||||
config.getInt(configPath() + ".optimize-cooldown-seconds", 600,
|
config.getInt(configPath + ".optimize-cooldown-seconds", 600,
|
||||||
"Cooldown in seconds until a villager can be optimized again using a nametag.\n" +
|
"Cooldown in seconds until a villager can be optimized again using a nametag.\n" +
|
||||||
"Here for configuration freedom. Recommended to leave as is to not enable any exploitable behavior."));
|
"Here for configuration freedom. Recommended to leave as is to not enable any exploitable behavior."));
|
||||||
this.notify_player = config.getBoolean(configPath() + ".notify-player", true,
|
this.notify_player = config.getBoolean(configPath + ".notify-player", true,
|
||||||
"Sends players a message when they successfully optimized a villager.");
|
"Sends players a message when they successfully optimized a villager.");
|
||||||
this.log_enabled = config.getBoolean(configPath() + ".log", false);
|
this.log_enabled = config.getBoolean(configPath + ".log", false);
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String configPath() {
|
|
||||||
return "optimization-methods.nametag-optimization";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void enable() {
|
public void enable() {
|
||||||
VillagerOptimizer plugin = VillagerOptimizer.getInstance();
|
|
||||||
plugin.getServer().getPluginManager().registerEvents(this, plugin);
|
plugin.getServer().getPluginManager().registerEvents(this, plugin);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -79,30 +69,29 @@ public class OptimizeByNametag implements VillagerOptimizerModule, Listener {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean shouldEnable() {
|
public boolean shouldEnable() {
|
||||||
return VillagerOptimizer.getConfiguration().getBoolean(configPath() + ".enable", true);
|
return config.getBoolean(configPath + ".enable", true);
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressWarnings("deprecation")
|
@SuppressWarnings("deprecation")
|
||||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
private void onPlayerInteractEntity(PlayerInteractEntityEvent event) {
|
private void onPlayerInteractEntity(PlayerInteractEntityEvent event) {
|
||||||
if (!event.getRightClicked().getType().equals(EntityType.VILLAGER)) return;
|
if (event.getRightClicked().getType() != XEntityType.VILLAGER.get()) return;
|
||||||
final Player player = event.getPlayer();
|
final Player player = event.getPlayer();
|
||||||
if (!player.hasPermission(Permissions.Optimize.NAMETAG.get())) return;
|
if (!player.hasPermission(Permissions.Optimize.NAMETAG.get())) return;
|
||||||
|
|
||||||
final ItemStack usedItem = player.getInventory().getItem(event.getHand());
|
final ItemStack usedItem = player.getInventory().getItem(event.getHand());
|
||||||
if (usedItem != null && !usedItem.getType().equals(Material.NAME_TAG)) return;
|
if (usedItem != null && usedItem.getType() != XMaterial.NAME_TAG.parseMaterial()) return;
|
||||||
if (!usedItem.hasItemMeta()) return;
|
if (!usedItem.hasItemMeta()) return;
|
||||||
final ItemMeta meta = usedItem.getItemMeta();
|
final ItemMeta meta = usedItem.getItemMeta();
|
||||||
if (!meta.hasDisplayName()) return;
|
if (!meta.hasDisplayName()) return;
|
||||||
|
|
||||||
final String nameTagPlainText = ChatColor.stripColor(meta.getDisplayName());
|
final String nameTagPlainText = ChatColor.stripColor(meta.getDisplayName());
|
||||||
final Villager villager = (Villager) event.getRightClicked();
|
final WrappedVillager wrapped = wrapperCache.get((Villager) event.getRightClicked(), WrappedVillager::new);
|
||||||
final WrappedVillager wVillager = villagerCache.getOrAdd(villager);
|
|
||||||
|
|
||||||
if (nametags.contains(nameTagPlainText.toLowerCase())) {
|
if (nametags.contains(nameTagPlainText.toLowerCase())) {
|
||||||
if (wVillager.canOptimize(cooldown) || player.hasPermission(Permissions.Bypass.NAMETAG_COOLDOWN.get())) {
|
if (wrapped.canOptimize(cooldown) || player.hasPermission(Permissions.Bypass.NAMETAG_COOLDOWN.get())) {
|
||||||
VillagerOptimizeEvent optimizeEvent = new VillagerOptimizeEvent(
|
VillagerOptimizeEvent optimizeEvent = new VillagerOptimizeEvent(
|
||||||
wVillager,
|
wrapped,
|
||||||
OptimizationType.NAMETAG,
|
OptimizationType.NAMETAG,
|
||||||
player,
|
player,
|
||||||
event.isAsynchronous()
|
event.isAsynchronous()
|
||||||
@ -110,13 +99,12 @@ public class OptimizeByNametag implements VillagerOptimizerModule, Listener {
|
|||||||
|
|
||||||
if (!optimizeEvent.callEvent()) return;
|
if (!optimizeEvent.callEvent()) return;
|
||||||
|
|
||||||
if (!consume_nametag) {
|
wrapped.setOptimizationType(optimizeEvent.getOptimizationType());
|
||||||
player.getInventory().addItem(usedItem.asOne());
|
wrapped.saveOptimizeTime();
|
||||||
player.updateInventory();
|
|
||||||
}
|
|
||||||
|
|
||||||
wVillager.setOptimizationType(optimizeEvent.getOptimizationType());
|
if (!consume_nametag && player.getGameMode() == GameMode.SURVIVAL) {
|
||||||
wVillager.saveOptimizeTime();
|
player.getInventory().addItem(usedItem.asOne());
|
||||||
|
}
|
||||||
|
|
||||||
if (notify_player) {
|
if (notify_player) {
|
||||||
VillagerOptimizer.getLang(player.locale()).nametag_optimize_success
|
VillagerOptimizer.getLang(player.locale()).nametag_optimize_success
|
||||||
@ -125,31 +113,35 @@ public class OptimizeByNametag implements VillagerOptimizerModule, Listener {
|
|||||||
|
|
||||||
if (log_enabled) {
|
if (log_enabled) {
|
||||||
info(player.getName() + " optimized villager using nametag '" + nameTagPlainText + "' at " +
|
info(player.getName() + " optimized villager using nametag '" + nameTagPlainText + "' at " +
|
||||||
LocationUtil.toString(wVillager.villager().getLocation()));
|
LocationUtil.toString(wrapped.villager.getLocation()));
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
event.setCancelled(true);
|
event.setCancelled(true);
|
||||||
wVillager.sayNo();
|
wrapped.sayNo();
|
||||||
if (notify_player) {
|
if (notify_player) {
|
||||||
final TextReplacementConfig timeLeft = TextReplacementConfig.builder()
|
final TextReplacementConfig timeLeft = TextReplacementConfig.builder()
|
||||||
.matchLiteral("%time%")
|
.matchLiteral("%time%")
|
||||||
.replacement(Util.formatDuration(Duration.ofMillis(wVillager.getOptimizeCooldownMillis(cooldown))))
|
.replacement(Util.formatDuration(Duration.ofMillis(wrapped.getOptimizeCooldownMillis(cooldown))))
|
||||||
.build();
|
.build();
|
||||||
VillagerOptimizer.getLang(player.locale()).nametag_on_optimize_cooldown
|
VillagerOptimizer.getLang(player.locale()).nametag_on_optimize_cooldown
|
||||||
.forEach(line -> KyoriUtil.sendMessage(player, line.replaceText(timeLeft)));
|
.forEach(line -> KyoriUtil.sendMessage(player, line.replaceText(timeLeft)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (wVillager.isOptimized()) {
|
if (wrapped.isOptimized()) {
|
||||||
VillagerUnoptimizeEvent unOptimizeEvent = new VillagerUnoptimizeEvent(
|
VillagerUnoptimizeEvent unOptimizeEvent = new VillagerUnoptimizeEvent(
|
||||||
wVillager,
|
wrapped,
|
||||||
player,
|
player,
|
||||||
OptimizationType.NAMETAG,
|
OptimizationType.NAMETAG,
|
||||||
event.isAsynchronous()
|
event.isAsynchronous()
|
||||||
);
|
);
|
||||||
|
|
||||||
if (!unOptimizeEvent.callEvent()) return;
|
if (!unOptimizeEvent.callEvent()) return;
|
||||||
wVillager.setOptimizationType(OptimizationType.NONE);
|
wrapped.setOptimizationType(OptimizationType.NONE);
|
||||||
|
|
||||||
|
if (!consume_nametag && player.getGameMode() == GameMode.SURVIVAL) {
|
||||||
|
player.getInventory().addItem(usedItem.asOne());
|
||||||
|
}
|
||||||
|
|
||||||
if (notify_player) {
|
if (notify_player) {
|
||||||
VillagerOptimizer.getLang(player.locale()).nametag_unoptimize_success
|
VillagerOptimizer.getLang(player.locale()).nametag_unoptimize_success
|
||||||
@ -158,7 +150,7 @@ public class OptimizeByNametag implements VillagerOptimizerModule, Listener {
|
|||||||
|
|
||||||
if (log_enabled) {
|
if (log_enabled) {
|
||||||
info(player.getName() + " unoptimized villager using nametag '" + nameTagPlainText + "' at " +
|
info(player.getName() + " unoptimized villager using nametag '" + nameTagPlainText + "' at " +
|
||||||
LocationUtil.toString(wVillager.villager().getLocation()));
|
LocationUtil.toString(wrapped.villager.getLocation()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,18 +1,15 @@
|
|||||||
package me.xginko.villageroptimizer.modules.optimization;
|
package me.xginko.villageroptimizer.modules.optimization;
|
||||||
|
|
||||||
import com.tcoded.folialib.impl.ServerImplementation;
|
|
||||||
import me.xginko.villageroptimizer.VillagerCache;
|
|
||||||
import me.xginko.villageroptimizer.VillagerOptimizer;
|
import me.xginko.villageroptimizer.VillagerOptimizer;
|
||||||
import me.xginko.villageroptimizer.utils.LocationUtil;
|
import me.xginko.villageroptimizer.struct.enums.OptimizationType;
|
||||||
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
|
import me.xginko.villageroptimizer.struct.enums.Permissions;
|
||||||
import me.xginko.villageroptimizer.config.Config;
|
|
||||||
import me.xginko.villageroptimizer.enums.OptimizationType;
|
|
||||||
import me.xginko.villageroptimizer.enums.Permissions;
|
|
||||||
import me.xginko.villageroptimizer.events.VillagerOptimizeEvent;
|
import me.xginko.villageroptimizer.events.VillagerOptimizeEvent;
|
||||||
import me.xginko.villageroptimizer.events.VillagerUnoptimizeEvent;
|
import me.xginko.villageroptimizer.events.VillagerUnoptimizeEvent;
|
||||||
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
|
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
|
||||||
import me.xginko.villageroptimizer.utils.Util;
|
|
||||||
import me.xginko.villageroptimizer.utils.KyoriUtil;
|
import me.xginko.villageroptimizer.utils.KyoriUtil;
|
||||||
|
import me.xginko.villageroptimizer.utils.LocationUtil;
|
||||||
|
import me.xginko.villageroptimizer.utils.Util;
|
||||||
|
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
|
||||||
import net.kyori.adventure.text.TextReplacementConfig;
|
import net.kyori.adventure.text.TextReplacementConfig;
|
||||||
import org.bukkit.Location;
|
import org.bukkit.Location;
|
||||||
import org.bukkit.block.Block;
|
import org.bukkit.block.Block;
|
||||||
@ -30,48 +27,37 @@ import java.util.concurrent.TimeUnit;
|
|||||||
import java.util.concurrent.atomic.AtomicBoolean;
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
import java.util.concurrent.atomic.AtomicInteger;
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
|
||||||
public class OptimizeByWorkstation implements VillagerOptimizerModule, Listener {
|
public class OptimizeByWorkstation extends VillagerOptimizerModule implements Listener {
|
||||||
|
|
||||||
private final ServerImplementation scheduler;
|
|
||||||
private final VillagerCache villagerCache;
|
|
||||||
private final long cooldown_millis;
|
private final long cooldown_millis;
|
||||||
private final double search_radius;
|
private final double search_radius;
|
||||||
private final int check_duration_ticks;
|
private final int check_duration_ticks;
|
||||||
private final boolean only_while_sneaking, log_enabled, notify_player;
|
private final boolean only_while_sneaking, log_enabled, notify_player;
|
||||||
|
|
||||||
public OptimizeByWorkstation() {
|
public OptimizeByWorkstation() {
|
||||||
shouldEnable();
|
super("optimization-methods.workstation-optimization");
|
||||||
this.scheduler = VillagerOptimizer.getFoliaLib().getImpl();
|
config.master().addComment(configPath + ".enable",
|
||||||
this.villagerCache = VillagerOptimizer.getCache();
|
|
||||||
Config config = VillagerOptimizer.getConfiguration();
|
|
||||||
config.master().addComment(configPath() + ".enable",
|
|
||||||
"When enabled, villagers that have a job and have been traded with at least once will become optimized,\n" +
|
"When enabled, villagers that have a job and have been traded with at least once will become optimized,\n" +
|
||||||
"if near their workstation. If the workstation is broken, the villager will become unoptimized again.");
|
"if near their workstation. If the workstation is broken, the villager will become unoptimized again.");
|
||||||
this.check_duration_ticks = Math.max(config.getInt(configPath() + ".check-linger-duration-ticks", 100,
|
this.check_duration_ticks = Math.max(config.getInt(configPath + ".check-linger-duration-ticks", 100,
|
||||||
"After a workstation has been placed, the plugin will wait for the configured amount of time in ticks\n" +
|
"After a workstation has been placed, the plugin will wait for the configured amount of time in ticks\n" +
|
||||||
"for a villager to claim that workstation. Not recommended to go below 100 ticks."), 1);
|
"for a villager to claim that workstation. Not recommended to go below 100 ticks."), 1);
|
||||||
this.search_radius = config.getDouble(configPath() + ".search-radius-in-blocks", 2.0,
|
this.search_radius = config.getDouble(configPath + ".search-radius-in-blocks", 2.0,
|
||||||
"The radius in blocks a villager can be away from the player when he places a workstation.\n" +
|
"The radius in blocks a villager can be away from the player when he places a workstation.\n" +
|
||||||
"The closest unoptimized villager to the player will be optimized.");
|
"The closest unoptimized villager to the player will be optimized.");
|
||||||
this.cooldown_millis = TimeUnit.SECONDS.toMillis(
|
this.cooldown_millis = TimeUnit.SECONDS.toMillis(
|
||||||
Math.max(1, config.getInt(configPath() + ".optimize-cooldown-seconds", 600,
|
Math.max(1, config.getInt(configPath + ".optimize-cooldown-seconds", 600,
|
||||||
"Cooldown in seconds until a villager can be optimized again using a workstation.\n" +
|
"Cooldown in seconds until a villager can be optimized again using a workstation.\n" +
|
||||||
"Here for configuration freedom. Recommended to leave as is to not enable any exploitable behavior.")));
|
"Here for configuration freedom. Recommended to leave as is to not enable any exploitable behavior.")));
|
||||||
this.only_while_sneaking = config.getBoolean(configPath() + ".only-when-sneaking", true,
|
this.only_while_sneaking = config.getBoolean(configPath + ".only-when-sneaking", true,
|
||||||
"Only optimize/unoptimize by workstation when player is sneaking during place or break. Useful for villager rolling.");
|
"Only optimize/unoptimize by workstation when player is sneaking during place or break. Useful for villager rolling.");
|
||||||
this.notify_player = config.getBoolean(configPath() + ".notify-player", true,
|
this.notify_player = config.getBoolean(configPath + ".notify-player", true,
|
||||||
"Sends players a message when they successfully optimized a villager.");
|
"Sends players a message when they successfully optimized a villager.");
|
||||||
this.log_enabled = config.getBoolean(configPath() + ".log", false);
|
this.log_enabled = config.getBoolean(configPath + ".log", false);
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String configPath() {
|
|
||||||
return "optimization-methods.workstation-optimization";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void enable() {
|
public void enable() {
|
||||||
VillagerOptimizer plugin = VillagerOptimizer.getInstance();
|
|
||||||
plugin.getServer().getPluginManager().registerEvents(this, plugin);
|
plugin.getServer().getPluginManager().registerEvents(this, plugin);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -82,7 +68,7 @@ public class OptimizeByWorkstation implements VillagerOptimizerModule, Listener
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean shouldEnable() {
|
public boolean shouldEnable() {
|
||||||
return VillagerOptimizer.getConfiguration().getBoolean(configPath() + ".enable", false);
|
return config.getBoolean(configPath + ".enable", false);
|
||||||
}
|
}
|
||||||
|
|
||||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||||
@ -99,65 +85,69 @@ public class OptimizeByWorkstation implements VillagerOptimizerModule, Listener
|
|||||||
final AtomicBoolean taskComplete = new AtomicBoolean();
|
final AtomicBoolean taskComplete = new AtomicBoolean();
|
||||||
final AtomicInteger taskAliveTicks = new AtomicInteger();
|
final AtomicInteger taskAliveTicks = new AtomicInteger();
|
||||||
|
|
||||||
scheduler.runAtLocationTimer(workstationLoc, repeatingTask -> {
|
scheduling.regionSpecificScheduler(workstationLoc).runAtFixedRate(repeatingTask -> {
|
||||||
if (taskComplete.get() || taskAliveTicks.getAndAdd(10) > check_duration_ticks) {
|
if (taskComplete.get() || taskAliveTicks.getAndAdd(10) > check_duration_ticks) {
|
||||||
repeatingTask.cancel();
|
repeatingTask.cancel();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
for (Villager villager : workstationLoc.getNearbyEntitiesByType(Villager.class, search_radius)) {
|
for (Villager villager : workstationLoc.getNearbyEntitiesByType(Villager.class, search_radius)) {
|
||||||
if (villager.getProfession() != workstationProfession) continue;
|
scheduling.entitySpecificScheduler(villager).run(() -> {
|
||||||
WrappedVillager wrapped = villagerCache.getOrAdd(villager);
|
if (villager.getProfession() != workstationProfession) return;
|
||||||
if (wrapped.getJobSite() == null) continue;
|
WrappedVillager wrapped = wrapperCache.get(villager, WrappedVillager::new);
|
||||||
if (wrapped.getJobSite().getWorld().getUID() != workstationLoc.getWorld().getUID()) continue;
|
|
||||||
if (LocationUtil.relDistance3DSquared(wrapped.getJobSite(), workstationLoc) > 1) continue;
|
|
||||||
|
|
||||||
if (!wrapped.canOptimize(cooldown_millis) && !player.hasPermission(Permissions.Bypass.WORKSTATION_COOLDOWN.get())) {
|
Location jobSite = wrapped.getJobSite();
|
||||||
wrapped.sayNo();
|
if (jobSite == null || jobSite.getWorld().getUID() != workstationLoc.getWorld().getUID()) return;
|
||||||
if (notify_player) {
|
if (LocationUtil.relDistance3DSquared(jobSite, workstationLoc) > 1) return;
|
||||||
final TextReplacementConfig timeLeft = TextReplacementConfig.builder()
|
|
||||||
.matchLiteral("%time%")
|
if (!wrapped.canOptimize(cooldown_millis) && !player.hasPermission(Permissions.Bypass.WORKSTATION_COOLDOWN.get())) {
|
||||||
.replacement(Util.formatDuration(Duration.ofMillis(wrapped.getOptimizeCooldownMillis(cooldown_millis))))
|
wrapped.sayNo();
|
||||||
.build();
|
|
||||||
VillagerOptimizer.getLang(player.locale()).nametag_on_optimize_cooldown
|
if (notify_player) {
|
||||||
.forEach(line -> KyoriUtil.sendMessage(player, line.replaceText(timeLeft)));
|
final TextReplacementConfig timeLeft = TextReplacementConfig.builder()
|
||||||
|
.matchLiteral("%time%")
|
||||||
|
.replacement(Util.formatDuration(Duration.ofMillis(wrapped.getOptimizeCooldownMillis(cooldown_millis))))
|
||||||
|
.build();
|
||||||
|
VillagerOptimizer.getLang(player.locale()).nametag_on_optimize_cooldown
|
||||||
|
.forEach(line -> KyoriUtil.sendMessage(player, line.replaceText(timeLeft)));
|
||||||
|
}
|
||||||
|
|
||||||
|
taskComplete.set(true);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
VillagerOptimizeEvent optimizeEvent = new VillagerOptimizeEvent(
|
||||||
|
wrapped,
|
||||||
|
OptimizationType.WORKSTATION,
|
||||||
|
player,
|
||||||
|
event.isAsynchronous()
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!optimizeEvent.callEvent()) return;
|
||||||
|
|
||||||
|
wrapped.setOptimizationType(optimizeEvent.getOptimizationType());
|
||||||
|
wrapped.saveOptimizeTime();
|
||||||
|
|
||||||
|
if (notify_player) {
|
||||||
|
final TextReplacementConfig vilProfession = TextReplacementConfig.builder()
|
||||||
|
.matchLiteral("%vil_profession%")
|
||||||
|
.replacement(Util.toNiceString(wrapped.villager.getProfession()))
|
||||||
|
.build();
|
||||||
|
final TextReplacementConfig placedWorkstation = TextReplacementConfig.builder()
|
||||||
|
.matchLiteral("%blocktype%")
|
||||||
|
.replacement(Util.toNiceString(placed.getType()))
|
||||||
|
.build();
|
||||||
|
VillagerOptimizer.getLang(player.locale()).workstation_optimize_success
|
||||||
|
.forEach(line -> KyoriUtil.sendMessage(player, line.replaceText(vilProfession).replaceText(placedWorkstation)));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (log_enabled) {
|
||||||
|
info(player.getName() + " optimized villager using workstation " + Util.toNiceString(placed.getType()) + " at " +
|
||||||
|
LocationUtil.toString(wrapped.villager.getLocation()));
|
||||||
|
}
|
||||||
|
|
||||||
taskComplete.set(true);
|
taskComplete.set(true);
|
||||||
return;
|
}, null);
|
||||||
}
|
|
||||||
|
|
||||||
VillagerOptimizeEvent optimizeEvent = new VillagerOptimizeEvent(
|
|
||||||
wrapped,
|
|
||||||
OptimizationType.WORKSTATION,
|
|
||||||
player,
|
|
||||||
event.isAsynchronous()
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!optimizeEvent.callEvent()) return;
|
|
||||||
|
|
||||||
wrapped.setOptimizationType(optimizeEvent.getOptimizationType());
|
|
||||||
wrapped.saveOptimizeTime();
|
|
||||||
|
|
||||||
if (notify_player) {
|
|
||||||
final TextReplacementConfig vilProfession = TextReplacementConfig.builder()
|
|
||||||
.matchLiteral("%vil_profession%")
|
|
||||||
.replacement(Util.formatEnum(wrapped.villager().getProfession()))
|
|
||||||
.build();
|
|
||||||
final TextReplacementConfig placedWorkstation = TextReplacementConfig.builder()
|
|
||||||
.matchLiteral("%blocktype%")
|
|
||||||
.replacement(Util.formatEnum(placed.getType()))
|
|
||||||
.build();
|
|
||||||
VillagerOptimizer.getLang(player.locale()).workstation_optimize_success
|
|
||||||
.forEach(line -> KyoriUtil.sendMessage(player, line.replaceText(vilProfession).replaceText(placedWorkstation)));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (log_enabled) {
|
|
||||||
info(player.getName() + " optimized villager using workstation " + Util.formatEnum(placed.getType()) + " at " +
|
|
||||||
LocationUtil.toString(wrapped.villager().getLocation()));
|
|
||||||
}
|
|
||||||
|
|
||||||
taskComplete.set(true);
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
}, 1L, 10L);
|
}, 1L, 10L);
|
||||||
}
|
}
|
||||||
@ -181,7 +171,7 @@ public class OptimizeByWorkstation implements VillagerOptimizerModule, Listener
|
|||||||
final double distance = LocationUtil.relDistance3DSquared(villager.getLocation(), workstationLoc);
|
final double distance = LocationUtil.relDistance3DSquared(villager.getLocation(), workstationLoc);
|
||||||
if (distance >= closestDistance) continue;
|
if (distance >= closestDistance) continue;
|
||||||
|
|
||||||
WrappedVillager wrapped = villagerCache.getOrAdd(villager);
|
WrappedVillager wrapped = wrapperCache.get(villager, WrappedVillager::new);
|
||||||
|
|
||||||
if (wrapped.isOptimized()) {
|
if (wrapped.isOptimized()) {
|
||||||
closestOptimized = wrapped;
|
closestOptimized = wrapped;
|
||||||
@ -205,19 +195,19 @@ public class OptimizeByWorkstation implements VillagerOptimizerModule, Listener
|
|||||||
if (notify_player) {
|
if (notify_player) {
|
||||||
final TextReplacementConfig vilProfession = TextReplacementConfig.builder()
|
final TextReplacementConfig vilProfession = TextReplacementConfig.builder()
|
||||||
.matchLiteral("%vil_profession%")
|
.matchLiteral("%vil_profession%")
|
||||||
.replacement(Util.formatEnum(closestOptimized.villager().getProfession()))
|
.replacement(Util.toNiceString(closestOptimized.villager.getProfession()))
|
||||||
.build();
|
.build();
|
||||||
final TextReplacementConfig brokenWorkstation = TextReplacementConfig.builder()
|
final TextReplacementConfig brokenWorkstation = TextReplacementConfig.builder()
|
||||||
.matchLiteral("%blocktype%")
|
.matchLiteral("%blocktype%")
|
||||||
.replacement(Util.formatEnum(broken.getType()))
|
.replacement(Util.toNiceString(broken.getType()))
|
||||||
.build();
|
.build();
|
||||||
VillagerOptimizer.getLang(player.locale()).workstation_unoptimize_success
|
VillagerOptimizer.getLang(player.locale()).workstation_unoptimize_success
|
||||||
.forEach(line -> KyoriUtil.sendMessage(player, line.replaceText(vilProfession).replaceText(brokenWorkstation)));
|
.forEach(line -> KyoriUtil.sendMessage(player, line.replaceText(vilProfession).replaceText(brokenWorkstation)));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (log_enabled) {
|
if (log_enabled) {
|
||||||
info(player.getName() + " unoptimized villager using workstation " + Util.formatEnum(broken.getType()) + " at " +
|
info(player.getName() + " unoptimized villager using workstation " + Util.toNiceString(broken.getType()) + " at " +
|
||||||
LocationUtil.toString(closestOptimized.villager().getLocation()));
|
LocationUtil.toString(closestOptimized.villager.getLocation()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -0,0 +1,5 @@
|
|||||||
|
package me.xginko.villageroptimizer.struct;
|
||||||
|
|
||||||
|
public interface Disableable {
|
||||||
|
void disable();
|
||||||
|
}
|
@ -0,0 +1,5 @@
|
|||||||
|
package me.xginko.villageroptimizer.struct;
|
||||||
|
|
||||||
|
public interface Enableable {
|
||||||
|
void enable();
|
||||||
|
}
|
@ -1,4 +1,4 @@
|
|||||||
package me.xginko.villageroptimizer.enums;
|
package me.xginko.villageroptimizer.struct.enums;
|
||||||
|
|
||||||
import net.kyori.adventure.key.Namespaced;
|
import net.kyori.adventure.key.Namespaced;
|
||||||
import org.bukkit.Keyed;
|
import org.bukkit.Keyed;
|
||||||
@ -44,7 +44,7 @@ public final class Keyring {
|
|||||||
* from a {@link PersistentDataContainer}
|
* from a {@link PersistentDataContainer}
|
||||||
*/
|
*/
|
||||||
public static NamespacedKey getKey(@NotNull String pluginName, @NotNull String key) {
|
public static NamespacedKey getKey(@NotNull String pluginName, @NotNull String key) {
|
||||||
return new NamespacedKey(pluginName.toLowerCase(Locale.ROOT), key);
|
return new NamespacedKey(pluginName.toLowerCase(Locale.ROOT), key.toLowerCase(Locale.ROOT));
|
||||||
}
|
}
|
||||||
|
|
||||||
public enum VillagerOptimizer implements Keyed {
|
public enum VillagerOptimizer implements Keyed {
|
||||||
@ -52,12 +52,12 @@ public final class Keyring {
|
|||||||
OPTIMIZATION_TYPE("optimization-type"),
|
OPTIMIZATION_TYPE("optimization-type"),
|
||||||
LAST_OPTIMIZE_SYSTIME_MILLIS("last-optimize"),
|
LAST_OPTIMIZE_SYSTIME_MILLIS("last-optimize"),
|
||||||
LAST_LEVELUP_SYSTIME_MILLIS("last-levelup"),
|
LAST_LEVELUP_SYSTIME_MILLIS("last-levelup"),
|
||||||
LAST_RESTOCK_SYSTIME_MILLIS("last-restock");
|
LAST_RESTOCK_WORLD_FULLTIME("last-restock-full-time");
|
||||||
|
|
||||||
private final @NotNull NamespacedKey key;
|
private final @NotNull NamespacedKey key;
|
||||||
|
|
||||||
VillagerOptimizer(@NotNull String key) {
|
VillagerOptimizer(@NotNull String key) {
|
||||||
this.key = new NamespacedKey(Space.VillagerOptimizer.namespace(), key);
|
this.key = Keyring.getKey(Space.VillagerOptimizer.namespace(), key);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@ -69,7 +69,7 @@ public final class Keyring {
|
|||||||
public enum AntiVillagerLag implements Keyed {
|
public enum AntiVillagerLag implements Keyed {
|
||||||
|
|
||||||
NEXT_OPTIMIZATION_SYSTIME_SECONDS("cooldown"), // Returns LONG -> (System.currentTimeMillis() / 1000) + cooldown seconds
|
NEXT_OPTIMIZATION_SYSTIME_SECONDS("cooldown"), // Returns LONG -> (System.currentTimeMillis() / 1000) + cooldown seconds
|
||||||
LAST_RESTOCK_WORLDFULLTIME("time"), // Returns LONG -> villager.getWorld().getFullTime()
|
LAST_RESTOCK_WORLD_FULLTIME("time"), // Returns LONG -> villager.getWorld().getFullTime()
|
||||||
NEXT_LEVELUP_SYSTIME_SECONDS("levelCooldown"), // Returns LONG -> (System.currentTimeMillis() / 1000) + cooldown seconds
|
NEXT_LEVELUP_SYSTIME_SECONDS("levelCooldown"), // Returns LONG -> (System.currentTimeMillis() / 1000) + cooldown seconds
|
||||||
OPTIMIZED_ANY("Marker"), // Returns STRING -> "AVL"
|
OPTIMIZED_ANY("Marker"), // Returns STRING -> "AVL"
|
||||||
OPTIMIZED_BLOCK("disabledByBlock"), // Returns STRING -> key().toString()
|
OPTIMIZED_BLOCK("disabledByBlock"), // Returns STRING -> key().toString()
|
||||||
@ -78,7 +78,7 @@ public final class Keyring {
|
|||||||
private final @NotNull NamespacedKey key;
|
private final @NotNull NamespacedKey key;
|
||||||
|
|
||||||
AntiVillagerLag(@NotNull String avlKey) {
|
AntiVillagerLag(@NotNull String avlKey) {
|
||||||
this.key = new NamespacedKey(Space.AntiVillagerLag.namespace(), avlKey);
|
this.key = Keyring.getKey(Space.AntiVillagerLag.namespace(), avlKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
@ -1,6 +1,8 @@
|
|||||||
package me.xginko.villageroptimizer.enums;
|
package me.xginko.villageroptimizer.struct.enums;
|
||||||
|
|
||||||
public enum OptimizationType {
|
public enum OptimizationType {
|
||||||
|
CHUNK_LIMIT,
|
||||||
|
REGIONAL_ACTIVITY,
|
||||||
COMMAND,
|
COMMAND,
|
||||||
NAMETAG,
|
NAMETAG,
|
||||||
WORKSTATION,
|
WORKSTATION,
|
@ -1,5 +1,6 @@
|
|||||||
package me.xginko.villageroptimizer.enums;
|
package me.xginko.villageroptimizer.struct.enums;
|
||||||
|
|
||||||
|
import org.bukkit.Bukkit;
|
||||||
import org.bukkit.permissions.Permission;
|
import org.bukkit.permissions.Permission;
|
||||||
import org.bukkit.permissions.PermissionDefault;
|
import org.bukkit.permissions.PermissionDefault;
|
||||||
|
|
||||||
@ -71,4 +72,24 @@ public final class Permissions {
|
|||||||
return permission;
|
return permission;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static void registerAll() {
|
||||||
|
for (Bypass perm : Bypass.values()) {
|
||||||
|
try {
|
||||||
|
Bukkit.getPluginManager().addPermission(perm.get());
|
||||||
|
} catch (IllegalArgumentException ignored) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (Commands perm : Commands.values()) {
|
||||||
|
try {
|
||||||
|
Bukkit.getPluginManager().addPermission(perm.get());
|
||||||
|
} catch (IllegalArgumentException ignored) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (Optimize perm : Optimize.values()) {
|
||||||
|
try {
|
||||||
|
Bukkit.getPluginManager().addPermission(perm.get());
|
||||||
|
} catch (IllegalArgumentException ignored) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
@ -0,0 +1,131 @@
|
|||||||
|
package me.xginko.villageroptimizer.struct.models;
|
||||||
|
|
||||||
|
import me.xginko.villageroptimizer.VillagerOptimizer;
|
||||||
|
import org.bukkit.Bukkit;
|
||||||
|
import org.bukkit.Location;
|
||||||
|
import org.bukkit.World;
|
||||||
|
import org.bukkit.entity.Entity;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.UUID;
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
|
||||||
|
public class BlockRegion2D {
|
||||||
|
|
||||||
|
private final UUID worldUID;
|
||||||
|
private final double halfSideLength, centerX, centerZ;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A square region on a minecraft world map.
|
||||||
|
*
|
||||||
|
* @param worldUID The UUID of the world this region is in.
|
||||||
|
* @param centerX The X-axis of the center location on the map.
|
||||||
|
* @param centerZ The Z-axis of the center location on the map.
|
||||||
|
* @param halfSideLength Half the length of the square's side. Acts like a radius would on circular regions.
|
||||||
|
*/
|
||||||
|
public BlockRegion2D(UUID worldUID, double centerX, double centerZ, double halfSideLength) {
|
||||||
|
this.worldUID = worldUID;
|
||||||
|
this.centerX = centerX;
|
||||||
|
this.centerZ = centerZ;
|
||||||
|
this.halfSideLength = halfSideLength;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a square region on a minecraft world map.
|
||||||
|
*
|
||||||
|
* @param worldUID The UUID of the world this region is in.
|
||||||
|
* @param centerX The X-axis of the center location on the map.
|
||||||
|
* @param centerZ The Z-axis of the center location on the map.
|
||||||
|
* @param halfSideLength Half the length of the square's side. Acts like a radius would on circular regions.
|
||||||
|
*/
|
||||||
|
public static BlockRegion2D of(UUID worldUID, double centerX, double centerZ, double halfSideLength) {
|
||||||
|
return new BlockRegion2D(worldUID, centerX, centerZ, halfSideLength);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a square region on a minecraft world map.
|
||||||
|
*
|
||||||
|
* @param world The world this region is in.
|
||||||
|
* @param centerX The X-axis of the center location on the map.
|
||||||
|
* @param centerZ The Z-axis of the center location on the map.
|
||||||
|
* @param halfSideLength Half the length of the square's side. Acts like a radius would on circular regions.
|
||||||
|
*/
|
||||||
|
public static BlockRegion2D of(World world, double centerX, double centerZ, double halfSideLength) {
|
||||||
|
return BlockRegion2D.of(world.getUID(), centerX, centerZ, halfSideLength);
|
||||||
|
}
|
||||||
|
|
||||||
|
public UUID getWorldUID() {
|
||||||
|
return this.worldUID;
|
||||||
|
}
|
||||||
|
|
||||||
|
public double getHalfSideLength() {
|
||||||
|
return this.halfSideLength;
|
||||||
|
}
|
||||||
|
|
||||||
|
public double getCenterX() {
|
||||||
|
return this.centerX;
|
||||||
|
}
|
||||||
|
|
||||||
|
public double getCenterZ() {
|
||||||
|
return this.centerZ;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean contains(Location location) {
|
||||||
|
if (!location.getWorld().getUID().equals(this.worldUID)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return location.getX() >= this.centerX - this.halfSideLength
|
||||||
|
&& location.getX() <= this.centerX + this.halfSideLength
|
||||||
|
&& location.getZ() >= this.centerZ - this.halfSideLength
|
||||||
|
&& location.getZ() <= this.centerZ + this.halfSideLength;
|
||||||
|
}
|
||||||
|
|
||||||
|
public CompletableFuture<Collection<Entity>> getEntities() {
|
||||||
|
World world = Bukkit.getWorld(worldUID);
|
||||||
|
|
||||||
|
if (world == null) {
|
||||||
|
// Only way I can imagine this happening would be if the server is using a world manager plugin and unloads
|
||||||
|
// the world during an operation.
|
||||||
|
// Since these plugins are rather common though, we will silently complete with an empty set instead of exceptionally.
|
||||||
|
return CompletableFuture.completedFuture(Collections.emptySet());
|
||||||
|
}
|
||||||
|
|
||||||
|
CompletableFuture<Collection<Entity>> future = new CompletableFuture<>();
|
||||||
|
Location centerLoc = new Location(world, centerX, world.getMinHeight(), centerZ);
|
||||||
|
|
||||||
|
VillagerOptimizer.scheduling().regionSpecificScheduler(centerLoc).run(() -> future.complete(
|
||||||
|
centerLoc.getNearbyEntities(
|
||||||
|
halfSideLength,
|
||||||
|
Math.abs(world.getMaxHeight()) + Math.abs(world.getMinHeight()), // World y can be between -64 and 320, we want everything from top to bottom
|
||||||
|
halfSideLength
|
||||||
|
)));
|
||||||
|
|
||||||
|
return future;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object obj) {
|
||||||
|
if (null == obj || obj.getClass() != BlockRegion2D.class)
|
||||||
|
return false;
|
||||||
|
BlockRegion2D blockRegion2D = (BlockRegion2D)obj;
|
||||||
|
return blockRegion2D.worldUID.equals(this.worldUID) && blockRegion2D.centerX == this.centerX && blockRegion2D.centerZ == this.centerZ;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
return Objects.hash(this.worldUID, this.centerX, this.centerZ, this.halfSideLength);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "BlockRegion2D{" +
|
||||||
|
" radius(half side length)=" + halfSideLength +
|
||||||
|
", centerX=" + centerX +
|
||||||
|
", centerZ=" + centerZ +
|
||||||
|
", worldUID=" + worldUID +
|
||||||
|
"}";
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,349 @@
|
|||||||
|
package me.xginko.villageroptimizer.struct.models;
|
||||||
|
|
||||||
|
import com.github.benmanes.caffeine.cache.Cache;
|
||||||
|
import com.github.benmanes.caffeine.cache.Caffeine;
|
||||||
|
import org.jetbrains.annotations.NotNull;
|
||||||
|
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.AbstractSet;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.Iterator;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
public final class ExpiringSet<E> extends AbstractSet<E> implements Set<E> {
|
||||||
|
|
||||||
|
private final Cache<E, Object> cache;
|
||||||
|
private static final Object PRESENT = new Object(); // Dummy value to associate with an Object in the backing Cache
|
||||||
|
|
||||||
|
public ExpiringSet(long duration, TimeUnit unit) {
|
||||||
|
this.cache = Caffeine.newBuilder().expireAfterWrite(duration, unit).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
public ExpiringSet(Duration duration) {
|
||||||
|
this.cache = Caffeine.newBuilder().expireAfterWrite(duration).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the number of elements in this set (its cardinality). If this
|
||||||
|
* set contains more than {@code Integer.MAX_VALUE} elements, returns
|
||||||
|
* {@code Integer.MAX_VALUE}.
|
||||||
|
*
|
||||||
|
* @return the number of elements in this set (its cardinality)
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public int size() {
|
||||||
|
return this.cache.asMap().size();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns {@code true} if this set contains no elements.
|
||||||
|
*
|
||||||
|
* @return {@code true} if this set contains no elements
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public boolean isEmpty() {
|
||||||
|
return this.cache.asMap().isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns {@code true} if this set contains the specified element.
|
||||||
|
* More formally, returns {@code true} if and only if this set
|
||||||
|
* contains an element {@code e} such that
|
||||||
|
* {@code Objects.equals(o, e)}.
|
||||||
|
*
|
||||||
|
* @param item element whose presence in this set is to be tested
|
||||||
|
* @return {@code true} if this set contains the specified element
|
||||||
|
* @throws ClassCastException if the type of the specified element
|
||||||
|
* is incompatible with this set
|
||||||
|
* (<a href="Collection.html#optional-restrictions">optional</a>)
|
||||||
|
* @throws NullPointerException if the specified element is null and this
|
||||||
|
* set does not permit null elements
|
||||||
|
* (<a href="Collection.html#optional-restrictions">optional</a>)
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public boolean contains(Object item) {
|
||||||
|
return this.cache.getIfPresent(item) != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns an iterator over the elements in this set. The elements are
|
||||||
|
* returned in no particular order (unless this set is an instance of some
|
||||||
|
* class that provides a guarantee).
|
||||||
|
*
|
||||||
|
* @return an iterator over the elements in this set
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public @NotNull Iterator<E> iterator() {
|
||||||
|
return this.cache.asMap().keySet().iterator();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns an array containing all of the elements in this set.
|
||||||
|
* If this set makes any guarantees as to what order its elements
|
||||||
|
* are returned by its iterator, this method must return the
|
||||||
|
* elements in the same order.
|
||||||
|
*
|
||||||
|
* <p>The returned array will be "safe" in that no references to it
|
||||||
|
* are maintained by this set. (In other words, this method must
|
||||||
|
* allocate a new array even if this set is backed by an array).
|
||||||
|
* The caller is thus free to modify the returned array.
|
||||||
|
*
|
||||||
|
* <p>This method acts as bridge between array-based and collection-based
|
||||||
|
* APIs.
|
||||||
|
*
|
||||||
|
* @return an array containing all the elements in this set
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public @NotNull Object @NotNull [] toArray() {
|
||||||
|
return this.cache.asMap().keySet().toArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns an array containing all of the elements in this set; the
|
||||||
|
* runtime type of the returned array is that of the specified array.
|
||||||
|
* If the set fits in the specified array, it is returned therein.
|
||||||
|
* Otherwise, a new array is allocated with the runtime type of the
|
||||||
|
* specified array and the size of this set.
|
||||||
|
*
|
||||||
|
* <p>If this set fits in the specified array with room to spare
|
||||||
|
* (i.e., the array has more elements than this set), the element in
|
||||||
|
* the array immediately following the end of the set is set to
|
||||||
|
* {@code null}. (This is useful in determining the length of this
|
||||||
|
* set <i>only</i> if the caller knows that this set does not contain
|
||||||
|
* any null elements.)
|
||||||
|
*
|
||||||
|
* <p>If this set makes any guarantees as to what order its elements
|
||||||
|
* are returned by its iterator, this method must return the elements
|
||||||
|
* in the same order.
|
||||||
|
*
|
||||||
|
* <p>Like the {@link #toArray()} method, this method acts as bridge between
|
||||||
|
* array-based and collection-based APIs. Further, this method allows
|
||||||
|
* precise control over the runtime type of the output array, and may,
|
||||||
|
* under certain circumstances, be used to save allocation costs.
|
||||||
|
*
|
||||||
|
* <p>Suppose {@code x} is a set known to contain only strings.
|
||||||
|
* The following code can be used to dump the set into a newly allocated
|
||||||
|
* array of {@code String}:
|
||||||
|
*
|
||||||
|
* <pre>
|
||||||
|
* String[] y = x.toArray(new String[0]);</pre>
|
||||||
|
* <p>
|
||||||
|
* Note that {@code toArray(new Object[0])} is identical in function to
|
||||||
|
* {@code toArray()}.
|
||||||
|
*
|
||||||
|
* @param a the array into which the elements of this set are to be
|
||||||
|
* stored, if it is big enough; otherwise, a new array of the same
|
||||||
|
* runtime type is allocated for this purpose.
|
||||||
|
* @return an array containing all the elements in this set
|
||||||
|
* @throws ArrayStoreException if the runtime type of the specified array
|
||||||
|
* is not a supertype of the runtime type of every element in this
|
||||||
|
* set
|
||||||
|
* @throws NullPointerException if the specified array is null
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public @NotNull <T> T @NotNull [] toArray(@NotNull T @NotNull [] a) {
|
||||||
|
return this.cache.asMap().keySet().toArray(a);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adds the specified element to this set if it is not already present
|
||||||
|
* (optional operation). More formally, adds the specified element
|
||||||
|
* {@code e} to this set if the set contains no element {@code e2}
|
||||||
|
* such that
|
||||||
|
* {@code Objects.equals(e, e2)}.
|
||||||
|
* If this set already contains the element, the call leaves the set
|
||||||
|
* unchanged and returns {@code false}. In combination with the
|
||||||
|
* restriction on constructors, this ensures that sets never contain
|
||||||
|
* duplicate elements.
|
||||||
|
*
|
||||||
|
* <p>The stipulation above does not imply that sets must accept all
|
||||||
|
* elements; sets may refuse to add any particular element, including
|
||||||
|
* {@code null}, and throw an exception, as described in the
|
||||||
|
* specification for {@link Collection#add Collection.add}.
|
||||||
|
* Individual set implementations should clearly document any
|
||||||
|
* restrictions on the elements that they may contain.
|
||||||
|
*
|
||||||
|
* @param item element to be added to this set
|
||||||
|
* @return {@code true} if this set did not already contain the specified
|
||||||
|
* element
|
||||||
|
* @throws UnsupportedOperationException if the {@code add} operation
|
||||||
|
* is not supported by this set
|
||||||
|
* @throws ClassCastException if the class of the specified element
|
||||||
|
* prevents it from being added to this set
|
||||||
|
* @throws NullPointerException if the specified element is null and this
|
||||||
|
* set does not permit null elements
|
||||||
|
* @throws IllegalArgumentException if some property of the specified element
|
||||||
|
* prevents it from being added to this set
|
||||||
|
*/
|
||||||
|
public boolean add(E item) {
|
||||||
|
boolean containedBefore = contains(item);
|
||||||
|
this.cache.put(item, PRESENT);
|
||||||
|
return !containedBefore;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Removes the specified element from this set if it is present
|
||||||
|
* (optional operation). More formally, removes an element {@code e}
|
||||||
|
* such that
|
||||||
|
* {@code Objects.equals(o, e)}, if
|
||||||
|
* this set contains such an element. Returns {@code true} if this set
|
||||||
|
* contained the element (or equivalently, if this set changed as a
|
||||||
|
* result of the call). (This set will not contain the element once the
|
||||||
|
* call returns.)
|
||||||
|
*
|
||||||
|
* @param o object to be removed from this set, if present
|
||||||
|
* @return {@code true} if this set contained the specified element
|
||||||
|
* @throws ClassCastException if the type of the specified element
|
||||||
|
* is incompatible with this set
|
||||||
|
* (<a href="Collection.html#optional-restrictions">optional</a>)
|
||||||
|
* @throws NullPointerException if the specified element is null and this
|
||||||
|
* set does not permit null elements
|
||||||
|
* (<a href="Collection.html#optional-restrictions">optional</a>)
|
||||||
|
* @throws UnsupportedOperationException if the {@code remove} operation
|
||||||
|
* is not supported by this set
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public boolean remove(Object o) {
|
||||||
|
boolean present = contains(o);
|
||||||
|
this.cache.invalidate(o);
|
||||||
|
return present;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns {@code true} if this set contains all of the elements of the
|
||||||
|
* specified collection. If the specified collection is also a set, this
|
||||||
|
* method returns {@code true} if it is a <i>subset</i> of this set.
|
||||||
|
*
|
||||||
|
* @param c collection to be checked for containment in this set
|
||||||
|
* @return {@code true} if this set contains all of the elements of the
|
||||||
|
* specified collection
|
||||||
|
* @throws ClassCastException if the types of one or more elements
|
||||||
|
* in the specified collection are incompatible with this
|
||||||
|
* set
|
||||||
|
* (<a href="Collection.html#optional-restrictions">optional</a>)
|
||||||
|
* @throws NullPointerException if the specified collection contains one
|
||||||
|
* or more null elements and this set does not permit null
|
||||||
|
* elements
|
||||||
|
* (<a href="Collection.html#optional-restrictions">optional</a>),
|
||||||
|
* or if the specified collection is null
|
||||||
|
* @see #contains(Object)
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public boolean containsAll(@NotNull Collection<?> c) {
|
||||||
|
for (Object o : c) {
|
||||||
|
if (!contains(o)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adds all of the elements in the specified collection to this set if
|
||||||
|
* they're not already present (optional operation). If the specified
|
||||||
|
* collection is also a set, the {@code addAll} operation effectively
|
||||||
|
* modifies this set so that its value is the <i>union</i> of the two
|
||||||
|
* sets. The behavior of this operation is undefined if the specified
|
||||||
|
* collection is modified while the operation is in progress.
|
||||||
|
*
|
||||||
|
* @param c collection containing elements to be added to this set
|
||||||
|
* @return {@code true} if this set changed as a result of the call
|
||||||
|
* @throws UnsupportedOperationException if the {@code addAll} operation
|
||||||
|
* is not supported by this set
|
||||||
|
* @throws ClassCastException if the class of an element of the
|
||||||
|
* specified collection prevents it from being added to this set
|
||||||
|
* @throws NullPointerException if the specified collection contains one
|
||||||
|
* or more null elements and this set does not permit null
|
||||||
|
* elements, or if the specified collection is null
|
||||||
|
* @throws IllegalArgumentException if some property of an element of the
|
||||||
|
* specified collection prevents it from being added to this set
|
||||||
|
* @see #add(Object)
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public boolean addAll(@NotNull Collection<? extends E> c) {
|
||||||
|
boolean changed = false;
|
||||||
|
for (E o : c) {
|
||||||
|
if (add(o)) {
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return changed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retains only the elements in this set that are contained in the
|
||||||
|
* specified collection (optional operation). In other words, removes
|
||||||
|
* from this set all of its elements that are not contained in the
|
||||||
|
* specified collection. If the specified collection is also a set, this
|
||||||
|
* operation effectively modifies this set so that its value is the
|
||||||
|
* <i>intersection</i> of the two sets.
|
||||||
|
*
|
||||||
|
* @param c collection containing elements to be retained in this set
|
||||||
|
* @return {@code true} if this set changed as a result of the call
|
||||||
|
* @throws UnsupportedOperationException if the {@code retainAll} operation
|
||||||
|
* is not supported by this set
|
||||||
|
* @throws ClassCastException if the class of an element of this set
|
||||||
|
* is incompatible with the specified collection
|
||||||
|
* (<a href="Collection.html#optional-restrictions">optional</a>)
|
||||||
|
* @throws NullPointerException if this set contains a null element and the
|
||||||
|
* specified collection does not permit null elements
|
||||||
|
* (<a href="Collection.html#optional-restrictions">optional</a>),
|
||||||
|
* or if the specified collection is null
|
||||||
|
* @see #remove(Object)
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public boolean retainAll(@NotNull Collection<?> c) {
|
||||||
|
boolean changed = false;
|
||||||
|
for (E e : this.cache.asMap().keySet()) {
|
||||||
|
if (!c.contains(e) && remove(e)) {
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return changed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Removes from this set all of its elements that are contained in the
|
||||||
|
* specified collection (optional operation). If the specified
|
||||||
|
* collection is also a set, this operation effectively modifies this
|
||||||
|
* set so that its value is the <i>asymmetric set difference</i> of
|
||||||
|
* the two sets.
|
||||||
|
*
|
||||||
|
* @param c collection containing elements to be removed from this set
|
||||||
|
* @return {@code true} if this set changed as a result of the call
|
||||||
|
* @throws UnsupportedOperationException if the {@code removeAll} operation
|
||||||
|
* is not supported by this set
|
||||||
|
* @throws ClassCastException if the class of an element of this set
|
||||||
|
* is incompatible with the specified collection
|
||||||
|
* (<a href="Collection.html#optional-restrictions">optional</a>)
|
||||||
|
* @throws NullPointerException if this set contains a null element and the
|
||||||
|
* specified collection does not permit null elements
|
||||||
|
* (<a href="Collection.html#optional-restrictions">optional</a>),
|
||||||
|
* or if the specified collection is null
|
||||||
|
* @see #remove(Object)
|
||||||
|
* @see #contains(Object)
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public boolean removeAll(@NotNull Collection<?> c) {
|
||||||
|
boolean changed = false;
|
||||||
|
for (E e : this.cache.asMap().keySet()) {
|
||||||
|
if (remove(e)) {
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return changed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Removes all of the elements from this set (optional operation).
|
||||||
|
* The set will be empty after this call returns.
|
||||||
|
*
|
||||||
|
* @throws UnsupportedOperationException if the {@code clear} method
|
||||||
|
* is not supported by this set
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public void clear() {
|
||||||
|
this.cache.invalidateAll();
|
||||||
|
}
|
||||||
|
}
|
@ -11,11 +11,11 @@ import java.util.Locale;
|
|||||||
public class KyoriUtil {
|
public class KyoriUtil {
|
||||||
|
|
||||||
public static void sendMessage(@NotNull CommandSender sender, @NotNull Component message) {
|
public static void sendMessage(@NotNull CommandSender sender, @NotNull Component message) {
|
||||||
VillagerOptimizer.getAudiences().sender(sender).sendMessage(message);
|
VillagerOptimizer.audiences().sender(sender).sendMessage(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void sendActionBar(@NotNull CommandSender sender, @NotNull Component message) {
|
public static void sendActionBar(@NotNull CommandSender sender, @NotNull Component message) {
|
||||||
VillagerOptimizer.getAudiences().sender(sender).sendActionBar(message);
|
VillagerOptimizer.audiences().sender(sender).sendActionBar(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static @NotNull Component toUpperCase(@NotNull Component input, @NotNull Locale locale) {
|
public static @NotNull Component toUpperCase(@NotNull Component input, @NotNull Locale locale) {
|
||||||
|
@ -1,5 +1,6 @@
|
|||||||
package me.xginko.villageroptimizer.utils;
|
package me.xginko.villageroptimizer.utils;
|
||||||
|
|
||||||
|
import com.cryptomorin.xseries.XMaterial;
|
||||||
import net.kyori.adventure.text.format.Style;
|
import net.kyori.adventure.text.format.Style;
|
||||||
import net.kyori.adventure.text.format.TextColor;
|
import net.kyori.adventure.text.format.TextColor;
|
||||||
import net.kyori.adventure.text.format.TextDecoration;
|
import net.kyori.adventure.text.format.TextDecoration;
|
||||||
@ -10,12 +11,51 @@ import org.jetbrains.annotations.NotNull;
|
|||||||
import org.jetbrains.annotations.Nullable;
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
|
import java.util.HashMap;
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
public class Util {
|
public class Util {
|
||||||
|
|
||||||
public static final @NotNull TextColor PL_COLOR = TextColor.color(102,255,230);
|
public static final @NotNull TextColor PL_COLOR;
|
||||||
public static final @NotNull Style PL_STYLE = Style.style(PL_COLOR, TextDecoration.BOLD);
|
public static final @NotNull Style PL_STYLE;
|
||||||
|
private static final @NotNull Map<Material, Villager.Profession> PROFESSION_MAP;
|
||||||
|
private static boolean canUseIsEntitiesLoaded;
|
||||||
|
|
||||||
|
static {
|
||||||
|
PL_COLOR = TextColor.color(102,255,230);
|
||||||
|
PL_STYLE = Style.style(PL_COLOR, TextDecoration.BOLD);
|
||||||
|
|
||||||
|
PROFESSION_MAP = new HashMap<>();
|
||||||
|
PROFESSION_MAP.put(XMaterial.LOOM.parseMaterial(), Villager.Profession.SHEPHERD);
|
||||||
|
PROFESSION_MAP.put(XMaterial.BARREL.parseMaterial(), Villager.Profession.FISHERMAN);
|
||||||
|
PROFESSION_MAP.put(XMaterial.SMOKER.parseMaterial(), Villager.Profession.BUTCHER);
|
||||||
|
PROFESSION_MAP.put(XMaterial.LECTERN.parseMaterial(), Villager.Profession.LIBRARIAN);
|
||||||
|
PROFESSION_MAP.put(XMaterial.CAULDRON.parseMaterial(), Villager.Profession.LEATHERWORKER);
|
||||||
|
PROFESSION_MAP.put(XMaterial.COMPOSTER.parseMaterial(), Villager.Profession.FARMER);
|
||||||
|
PROFESSION_MAP.put(XMaterial.GRINDSTONE.parseMaterial(), Villager.Profession.WEAPONSMITH);
|
||||||
|
PROFESSION_MAP.put(XMaterial.STONECUTTER.parseMaterial(), Villager.Profession.MASON);
|
||||||
|
PROFESSION_MAP.put(XMaterial.BREWING_STAND.parseMaterial(), Villager.Profession.CLERIC);
|
||||||
|
PROFESSION_MAP.put(XMaterial.BLAST_FURNACE.parseMaterial(), Villager.Profession.ARMORER);
|
||||||
|
PROFESSION_MAP.put(XMaterial.SMITHING_TABLE.parseMaterial(), Villager.Profession.TOOLSMITH);
|
||||||
|
PROFESSION_MAP.put(XMaterial.FLETCHING_TABLE.parseMaterial(), Villager.Profession.FLETCHER);
|
||||||
|
PROFESSION_MAP.put(XMaterial.CARTOGRAPHY_TABLE.parseMaterial(), Villager.Profession.CARTOGRAPHER);
|
||||||
|
|
||||||
|
try {
|
||||||
|
Chunk.class.getMethod("isEntitiesLoaded");
|
||||||
|
canUseIsEntitiesLoaded = true;
|
||||||
|
} catch (NoSuchMethodException e) {
|
||||||
|
canUseIsEntitiesLoaded = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static @Nullable Villager.Profession getWorkstationProfession(@NotNull Material workstation) {
|
||||||
|
return PROFESSION_MAP.getOrDefault(workstation, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean isChunkLoaded(@NotNull Chunk chunk) {
|
||||||
|
return canUseIsEntitiesLoaded ? chunk.isEntitiesLoaded() : chunk.isLoaded();
|
||||||
|
}
|
||||||
|
|
||||||
public static @NotNull String formatDuration(@NotNull Duration duration) {
|
public static @NotNull String formatDuration(@NotNull Duration duration) {
|
||||||
if (duration.isNegative()) duration = duration.negated();
|
if (duration.isNegative()) duration = duration.negated();
|
||||||
@ -33,61 +73,25 @@ public class Util {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static @NotNull String formatEnum(@NotNull Enum<?> input) {
|
public static @NotNull String toNiceString(@NotNull Object input) {
|
||||||
|
// Get name
|
||||||
|
String name;
|
||||||
|
if (input instanceof Enum<?>) {
|
||||||
|
name = ((Enum<?>) input).name();
|
||||||
|
} else {
|
||||||
|
name = input.toString();
|
||||||
|
}
|
||||||
|
|
||||||
// Turn something like "REDSTONE_TORCH" into "redstone torch"
|
// Turn something like "REDSTONE_TORCH" into "redstone torch"
|
||||||
String[] lowercaseWords = input.name().toLowerCase(Locale.ROOT).split("_");
|
String[] lowercaseWords = name.toLowerCase(Locale.ROOT).split("_");
|
||||||
|
|
||||||
|
// Capitalize first letter for each word
|
||||||
for (int i = 0; i < lowercaseWords.length; i++) {
|
for (int i = 0; i < lowercaseWords.length; i++) {
|
||||||
String word = lowercaseWords[i];
|
String word = lowercaseWords[i];
|
||||||
// Capitalize first letter for each word
|
|
||||||
lowercaseWords[i] = word.substring(0, 1).toUpperCase() + word.substring(1);
|
lowercaseWords[i] = word.substring(0, 1).toUpperCase() + word.substring(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
// return as nice string
|
// return as nice string
|
||||||
return String.join(" ", lowercaseWords);
|
return String.join(" ", lowercaseWords);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static boolean specificChunkLoadedMethodAvailable = true;
|
|
||||||
public static boolean isEntitiesLoaded(@NotNull Chunk chunk) {
|
|
||||||
if (!specificChunkLoadedMethodAvailable) {
|
|
||||||
return chunk.isLoaded();
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
return chunk.isEntitiesLoaded();
|
|
||||||
} catch (NoSuchMethodError e) {
|
|
||||||
specificChunkLoadedMethodAvailable = false;
|
|
||||||
return chunk.isLoaded();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public static @Nullable Villager.Profession getWorkstationProfession(@NotNull Material workstation) {
|
|
||||||
switch (workstation) {
|
|
||||||
case BARREL:
|
|
||||||
return Villager.Profession.FISHERMAN;
|
|
||||||
case CARTOGRAPHY_TABLE:
|
|
||||||
return Villager.Profession.CARTOGRAPHER;
|
|
||||||
case SMOKER:
|
|
||||||
return Villager.Profession.BUTCHER;
|
|
||||||
case SMITHING_TABLE:
|
|
||||||
return Villager.Profession.TOOLSMITH;
|
|
||||||
case GRINDSTONE:
|
|
||||||
return Villager.Profession.WEAPONSMITH;
|
|
||||||
case BLAST_FURNACE:
|
|
||||||
return Villager.Profession.ARMORER;
|
|
||||||
case CAULDRON:
|
|
||||||
return Villager.Profession.LEATHERWORKER;
|
|
||||||
case BREWING_STAND:
|
|
||||||
return Villager.Profession.CLERIC;
|
|
||||||
case COMPOSTER:
|
|
||||||
return Villager.Profession.FARMER;
|
|
||||||
case FLETCHING_TABLE:
|
|
||||||
return Villager.Profession.FLETCHER;
|
|
||||||
case LOOM:
|
|
||||||
return Villager.Profession.SHEPHERD;
|
|
||||||
case LECTERN:
|
|
||||||
return Villager.Profession.LIBRARIAN;
|
|
||||||
case STONECUTTER:
|
|
||||||
return Villager.Profession.MASON;
|
|
||||||
default:
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
@ -1,54 +1,61 @@
|
|||||||
package me.xginko.villageroptimizer.wrapper;
|
package me.xginko.villageroptimizer.wrapper;
|
||||||
|
|
||||||
import me.xginko.villageroptimizer.VillagerOptimizer;
|
import me.xginko.villageroptimizer.VillagerOptimizer;
|
||||||
import me.xginko.villageroptimizer.enums.Keyring;
|
import me.xginko.villageroptimizer.struct.enums.Keyring;
|
||||||
import me.xginko.villageroptimizer.enums.OptimizationType;
|
import me.xginko.villageroptimizer.struct.enums.OptimizationType;
|
||||||
import org.bukkit.entity.Villager;
|
import org.bukkit.entity.Villager;
|
||||||
|
import org.bukkit.persistence.PersistentDataContainer;
|
||||||
import org.jetbrains.annotations.NotNull;
|
import org.jetbrains.annotations.NotNull;
|
||||||
|
|
||||||
public interface VillagerDataHandler {
|
public abstract class PDCWrapper {
|
||||||
|
|
||||||
static VillagerDataHandler[] forVillager(Villager villager) {
|
public final Villager villager;
|
||||||
if (VillagerOptimizer.getConfiguration().support_other_plugins) {
|
public final PersistentDataContainer dataContainer;
|
||||||
return new VillagerDataHandler[]{
|
|
||||||
new MainVillagerDataHandlerImpl(villager),
|
public PDCWrapper(Villager villager) {
|
||||||
new AVLVillagerDataHandlerImpl(villager)
|
this.villager = villager;
|
||||||
};
|
this.dataContainer = villager.getPersistentDataContainer();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static PDCWrapper[] forVillager(Villager villager) {
|
||||||
|
if (VillagerOptimizer.config().support_other_plugins) {
|
||||||
|
return new PDCWrapper[]{new PDCWrapperVO(villager), new PDCWrapperAVL(villager)};
|
||||||
} else {
|
} else {
|
||||||
return new VillagerDataHandler[]{ new MainVillagerDataHandlerImpl(villager) };
|
return new PDCWrapper[]{new PDCWrapperVO(villager)};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return The namespace of the handler
|
* @return The namespace of the handler
|
||||||
*/
|
*/
|
||||||
Keyring.Space getSpace();
|
public abstract Keyring.Space getSpace();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return True if the villager is optimized by plugin, otherwise false.
|
* @return True if the villager is optimized by plugin, otherwise false.
|
||||||
*/
|
*/
|
||||||
boolean isOptimized();
|
public abstract boolean isOptimized();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param cooldown_millis The configured cooldown in millis until the next optimization is allowed to occur.
|
* @param cooldown_millis The configured cooldown in millis until the next optimization is allowed to occur.
|
||||||
* @return True if villager can be optimized again, otherwise false.
|
* @return True if villager can be optimized again, otherwise false.
|
||||||
*/
|
*/
|
||||||
boolean canOptimize(long cooldown_millis);
|
public abstract boolean canOptimize(long cooldown_millis);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param type OptimizationType the villager should be set to.
|
* @param type OptimizationType the villager should be set to.
|
||||||
*/
|
*/
|
||||||
void setOptimizationType(OptimizationType type);
|
public abstract void setOptimizationType(OptimizationType type);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return The current OptimizationType of the villager.
|
* @return The current OptimizationType of the villager.
|
||||||
*/
|
*/
|
||||||
@NotNull OptimizationType getOptimizationType();
|
@NotNull
|
||||||
|
public abstract OptimizationType getOptimizationType();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Saves the system time when the villager was last optimized.
|
* Saves the system time when the villager was last optimized.
|
||||||
*/
|
*/
|
||||||
void saveOptimizeTime();
|
public abstract void saveOptimizeTime();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* For convenience so the remaining millis since the last stored optimize time
|
* For convenience so the remaining millis since the last stored optimize time
|
||||||
@ -58,42 +65,30 @@ public interface VillagerDataHandler {
|
|||||||
* @param cooldown_millis The configured cooldown in milliseconds you want to check against.
|
* @param cooldown_millis The configured cooldown in milliseconds you want to check against.
|
||||||
* @return The time left in millis until the villager can be optimized again.
|
* @return The time left in millis until the villager can be optimized again.
|
||||||
*/
|
*/
|
||||||
long getOptimizeCooldownMillis(long cooldown_millis);
|
public abstract long getOptimizeCooldownMillis(long cooldown_millis);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* For convenience so the remaining millis since the last stored restock time
|
* Gets the time of the day in ticks when the entity was last restocked.
|
||||||
* can be easily calculated.
|
* This value is affected by /time set
|
||||||
*
|
* @return The time of the minecraft day (in ticks) when the villager was last restocked
|
||||||
* @param cooldown_millis The configured cooldown in milliseconds you want to check against.
|
|
||||||
* @return True if the villager has been loaded long enough.
|
|
||||||
*/
|
*/
|
||||||
boolean canRestock(long cooldown_millis);
|
public abstract long getLastRestockFullTime();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Saves the time of when the entity was last restocked.
|
* Saves the time of when the entity was last restocked.
|
||||||
*/
|
*/
|
||||||
void saveRestockTime();
|
public abstract void saveRestockTime();
|
||||||
|
|
||||||
/**
|
|
||||||
* For convenience so the remaining millis since the last stored restock time
|
|
||||||
* can be easily calculated.
|
|
||||||
* This enables new configured cooldowns to instantly apply instead of them being persistent.
|
|
||||||
*
|
|
||||||
* @param cooldown_millis The configured cooldown in milliseconds you want to check against.
|
|
||||||
* @return The time left in millis until the villager can be restocked again.
|
|
||||||
*/
|
|
||||||
long getRestockCooldownMillis(long cooldown_millis);
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param cooldown_millis The configured cooldown in milliseconds you want to check against.
|
* @param cooldown_millis The configured cooldown in milliseconds you want to check against.
|
||||||
* @return Whether the villager can be leveled up or not with the checked milliseconds
|
* @return Whether the villager can be leveled up or not with the checked milliseconds
|
||||||
*/
|
*/
|
||||||
boolean canLevelUp(long cooldown_millis);
|
public abstract boolean canLevelUp(long cooldown_millis);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Saves the time of the in-game world when the entity was last leveled up.
|
* Saves the time of the in-game world when the entity was last leveled up.
|
||||||
*/
|
*/
|
||||||
void saveLastLevelUp();
|
public abstract void saveLastLevelUp();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Here for convenience so the remaining millis since the last stored level-up time
|
* Here for convenience so the remaining millis since the last stored level-up time
|
||||||
@ -101,5 +96,5 @@ public interface VillagerDataHandler {
|
|||||||
*
|
*
|
||||||
* @return The time of the in-game world when the entity was last leveled up.
|
* @return The time of the in-game world when the entity was last leveled up.
|
||||||
*/
|
*/
|
||||||
long getLevelCooldownMillis(long cooldown_millis);
|
public abstract long getLevelCooldownMillis(long cooldown_millis);
|
||||||
}
|
}
|
@ -1,23 +1,18 @@
|
|||||||
package me.xginko.villageroptimizer.wrapper;
|
package me.xginko.villageroptimizer.wrapper;
|
||||||
|
|
||||||
import me.xginko.villageroptimizer.VillagerOptimizer;
|
import me.xginko.villageroptimizer.VillagerOptimizer;
|
||||||
import me.xginko.villageroptimizer.enums.Keyring;
|
import me.xginko.villageroptimizer.struct.enums.Keyring;
|
||||||
import me.xginko.villageroptimizer.enums.OptimizationType;
|
import me.xginko.villageroptimizer.struct.enums.OptimizationType;
|
||||||
import org.bukkit.entity.Villager;
|
import org.bukkit.entity.Villager;
|
||||||
import org.bukkit.persistence.PersistentDataContainer;
|
|
||||||
import org.bukkit.persistence.PersistentDataType;
|
import org.bukkit.persistence.PersistentDataType;
|
||||||
import org.jetbrains.annotations.NotNull;
|
import org.jetbrains.annotations.NotNull;
|
||||||
|
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
public class AVLVillagerDataHandlerImpl implements VillagerDataHandler {
|
public final class PDCWrapperAVL extends PDCWrapper {
|
||||||
|
|
||||||
private final @NotNull Villager villager;
|
PDCWrapperAVL(@NotNull Villager villager) {
|
||||||
private final @NotNull PersistentDataContainer dataContainer;
|
super(villager);
|
||||||
|
|
||||||
AVLVillagerDataHandlerImpl(@NotNull Villager villager) {
|
|
||||||
this.villager = villager;
|
|
||||||
this.dataContainer = villager.getPersistentDataContainer();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@ -40,7 +35,7 @@ public class AVLVillagerDataHandlerImpl implements VillagerDataHandler {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void setOptimizationType(OptimizationType type) {
|
public void setOptimizationType(OptimizationType type) {
|
||||||
VillagerOptimizer.getFoliaLib().getImpl().runAtEntityTimer(villager, setOptimization -> {
|
VillagerOptimizer.scheduling().entitySpecificScheduler(villager).runAtFixedRate(setOptimization -> {
|
||||||
// Keep repeating task until villager is no longer trading with a player
|
// Keep repeating task until villager is no longer trading with a player
|
||||||
if (villager.isTrading()) return;
|
if (villager.isTrading()) return;
|
||||||
|
|
||||||
@ -73,7 +68,7 @@ public class AVLVillagerDataHandlerImpl implements VillagerDataHandler {
|
|||||||
|
|
||||||
// End repeating task once logic is finished
|
// End repeating task once logic is finished
|
||||||
setOptimization.cancel();
|
setOptimization.cancel();
|
||||||
}, 0L, 1L, TimeUnit.SECONDS);
|
}, null, 1L, 20L);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@ -104,21 +99,16 @@ public class AVLVillagerDataHandlerImpl implements VillagerDataHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean canRestock(long cooldown_millis) {
|
public long getLastRestockFullTime() {
|
||||||
return !dataContainer.has(Keyring.AntiVillagerLag.LAST_RESTOCK_WORLDFULLTIME.getKey(), PersistentDataType.LONG)
|
if (dataContainer.has(Keyring.AntiVillagerLag.LAST_RESTOCK_WORLD_FULLTIME.getKey(), PersistentDataType.LONG)) {
|
||||||
|| villager.getWorld().getFullTime() > dataContainer.get(Keyring.AntiVillagerLag.LAST_RESTOCK_WORLDFULLTIME.getKey(), PersistentDataType.LONG);
|
return dataContainer.get(Keyring.AntiVillagerLag.LAST_RESTOCK_WORLD_FULLTIME.getKey(), PersistentDataType.LONG);
|
||||||
|
}
|
||||||
|
return 0L;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void saveRestockTime() {
|
public void saveRestockTime() {
|
||||||
dataContainer.set(Keyring.AntiVillagerLag.LAST_RESTOCK_WORLDFULLTIME.getKey(), PersistentDataType.LONG, villager.getWorld().getFullTime());
|
dataContainer.set(Keyring.AntiVillagerLag.LAST_RESTOCK_WORLD_FULLTIME.getKey(), PersistentDataType.LONG, villager.getWorld().getFullTime());
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public long getRestockCooldownMillis(long cooldown_millis) {
|
|
||||||
if (dataContainer.has(Keyring.AntiVillagerLag.LAST_RESTOCK_WORLDFULLTIME.getKey(), PersistentDataType.LONG))
|
|
||||||
return (villager.getWorld().getFullTime() - dataContainer.get(Keyring.AntiVillagerLag.LAST_RESTOCK_WORLDFULLTIME.getKey(), PersistentDataType.LONG)) * 50L;
|
|
||||||
return cooldown_millis;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
@ -1,23 +1,16 @@
|
|||||||
package me.xginko.villageroptimizer.wrapper;
|
package me.xginko.villageroptimizer.wrapper;
|
||||||
|
|
||||||
import me.xginko.villageroptimizer.VillagerOptimizer;
|
import me.xginko.villageroptimizer.VillagerOptimizer;
|
||||||
import me.xginko.villageroptimizer.enums.Keyring;
|
import me.xginko.villageroptimizer.struct.enums.Keyring;
|
||||||
import me.xginko.villageroptimizer.enums.OptimizationType;
|
import me.xginko.villageroptimizer.struct.enums.OptimizationType;
|
||||||
import org.bukkit.entity.Villager;
|
import org.bukkit.entity.Villager;
|
||||||
import org.bukkit.persistence.PersistentDataContainer;
|
|
||||||
import org.bukkit.persistence.PersistentDataType;
|
import org.bukkit.persistence.PersistentDataType;
|
||||||
import org.jetbrains.annotations.NotNull;
|
import org.jetbrains.annotations.NotNull;
|
||||||
|
|
||||||
import java.util.concurrent.TimeUnit;
|
public final class PDCWrapperVO extends PDCWrapper {
|
||||||
|
|
||||||
public class MainVillagerDataHandlerImpl implements VillagerDataHandler {
|
PDCWrapperVO(@NotNull Villager villager) {
|
||||||
|
super(villager);
|
||||||
private final @NotNull Villager villager;
|
|
||||||
private final @NotNull PersistentDataContainer dataContainer;
|
|
||||||
|
|
||||||
MainVillagerDataHandlerImpl(@NotNull Villager villager) {
|
|
||||||
this.villager = villager;
|
|
||||||
this.dataContainer = villager.getPersistentDataContainer();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@ -37,7 +30,7 @@ public class MainVillagerDataHandlerImpl implements VillagerDataHandler {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void setOptimizationType(OptimizationType type) {
|
public void setOptimizationType(OptimizationType type) {
|
||||||
VillagerOptimizer.getFoliaLib().getImpl().runAtEntityTimer(villager, setOptimization -> {
|
VillagerOptimizer.scheduling().entitySpecificScheduler(villager).runAtFixedRate(setOptimization -> {
|
||||||
// Keep repeating task until villager is no longer trading with a player
|
// Keep repeating task until villager is no longer trading with a player
|
||||||
if (villager.isTrading()) return;
|
if (villager.isTrading()) return;
|
||||||
|
|
||||||
@ -53,7 +46,7 @@ public class MainVillagerDataHandlerImpl implements VillagerDataHandler {
|
|||||||
|
|
||||||
// End repeating task once logic is finished
|
// End repeating task once logic is finished
|
||||||
setOptimization.cancel();
|
setOptimization.cancel();
|
||||||
}, 0L, 1L, TimeUnit.SECONDS);
|
}, null, 1L, 20L);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@ -89,30 +82,16 @@ public class MainVillagerDataHandlerImpl implements VillagerDataHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean canRestock(long cooldown_millis) {
|
public long getLastRestockFullTime() {
|
||||||
return getLastRestock() + cooldown_millis <= System.currentTimeMillis();
|
if (dataContainer.has(Keyring.VillagerOptimizer.LAST_RESTOCK_WORLD_FULLTIME.getKey(), PersistentDataType.LONG)) {
|
||||||
}
|
return dataContainer.get(Keyring.VillagerOptimizer.LAST_RESTOCK_WORLD_FULLTIME.getKey(), PersistentDataType.LONG);
|
||||||
|
|
||||||
@Override
|
|
||||||
public void saveRestockTime() {
|
|
||||||
dataContainer.set(Keyring.VillagerOptimizer.LAST_RESTOCK_SYSTIME_MILLIS.getKey(), PersistentDataType.LONG, System.currentTimeMillis());
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return The time when the entity was last restocked.
|
|
||||||
*/
|
|
||||||
private long getLastRestock() {
|
|
||||||
if (dataContainer.has(Keyring.VillagerOptimizer.LAST_RESTOCK_SYSTIME_MILLIS.getKey(), PersistentDataType.LONG)) {
|
|
||||||
return dataContainer.get(Keyring.VillagerOptimizer.LAST_RESTOCK_SYSTIME_MILLIS.getKey(), PersistentDataType.LONG);
|
|
||||||
}
|
}
|
||||||
return 0L;
|
return 0L;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public long getRestockCooldownMillis(long cooldown_millis) {
|
public void saveRestockTime() {
|
||||||
if (dataContainer.has(Keyring.VillagerOptimizer.LAST_RESTOCK_SYSTIME_MILLIS.getKey(), PersistentDataType.LONG))
|
dataContainer.set(Keyring.VillagerOptimizer.LAST_RESTOCK_WORLD_FULLTIME.getKey(), PersistentDataType.LONG, villager.getWorld().getFullTime());
|
||||||
return System.currentTimeMillis() - (dataContainer.get(Keyring.VillagerOptimizer.LAST_RESTOCK_SYSTIME_MILLIS.getKey(), PersistentDataType.LONG) + cooldown_millis);
|
|
||||||
return cooldown_millis;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
@ -1,39 +1,54 @@
|
|||||||
package me.xginko.villageroptimizer.wrapper;
|
package me.xginko.villageroptimizer.wrapper;
|
||||||
|
|
||||||
import me.xginko.villageroptimizer.enums.Keyring;
|
import me.xginko.villageroptimizer.VillagerOptimizer;
|
||||||
import me.xginko.villageroptimizer.enums.OptimizationType;
|
import me.xginko.villageroptimizer.struct.enums.Keyring;
|
||||||
|
import me.xginko.villageroptimizer.struct.enums.OptimizationType;
|
||||||
import org.bukkit.Location;
|
import org.bukkit.Location;
|
||||||
import org.bukkit.Sound;
|
import org.bukkit.Sound;
|
||||||
import org.bukkit.entity.Villager;
|
import org.bukkit.entity.Villager;
|
||||||
import org.bukkit.entity.memory.MemoryKey;
|
import org.bukkit.entity.memory.MemoryKey;
|
||||||
|
import org.bukkit.event.entity.VillagerReplenishTradeEvent;
|
||||||
import org.bukkit.inventory.MerchantRecipe;
|
import org.bukkit.inventory.MerchantRecipe;
|
||||||
import org.jetbrains.annotations.NotNull;
|
import org.jetbrains.annotations.NotNull;
|
||||||
import org.jetbrains.annotations.Nullable;
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
public class WrappedVillager implements VillagerDataHandler {
|
public class WrappedVillager extends PDCWrapper {
|
||||||
|
|
||||||
private final @NotNull Villager villager;
|
private final @NotNull PDCWrapper[] pdcWrappers;
|
||||||
private final @NotNull VillagerDataHandler[] dataHandlers;
|
|
||||||
|
|
||||||
public WrappedVillager(@NotNull Villager villager) {
|
public WrappedVillager(@NotNull Villager villager) {
|
||||||
this.villager = villager;
|
super(villager);
|
||||||
this.dataHandlers = VillagerDataHandler.forVillager(villager);
|
this.pdcWrappers = PDCWrapper.forVillager(villager);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return The villager inside the wrapper.
|
* Returns a number between 0 and 24000
|
||||||
|
* is affected by /time set
|
||||||
*/
|
*/
|
||||||
public @NotNull Villager villager() {
|
public long currentDayTimeTicks() {
|
||||||
return villager;
|
return villager.getWorld().getTime();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the tick time of the world
|
||||||
|
* is affected by /time set
|
||||||
|
*/
|
||||||
|
public long currentFullTimeTicks() {
|
||||||
|
return villager.getWorld().getFullTime();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Restock all trading recipes.
|
* Restock all trading recipes.
|
||||||
*/
|
*/
|
||||||
public void restock() {
|
public void restock() {
|
||||||
for (MerchantRecipe recipe : villager.getRecipes()) {
|
VillagerOptimizer.scheduling().entitySpecificScheduler(villager).run(() -> {
|
||||||
recipe.setUses(0);
|
for (MerchantRecipe merchantRecipe : villager.getRecipes()) {
|
||||||
}
|
VillagerReplenishTradeEvent restockRecipeEvent = new VillagerReplenishTradeEvent(villager, merchantRecipe);
|
||||||
|
if (restockRecipeEvent.callEvent()) {
|
||||||
|
restockRecipeEvent.getRecipe().setUses(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -50,7 +65,7 @@ public class WrappedVillager implements VillagerDataHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return true if the villager can loose his acquired profession by having their workstation destroyed.
|
* @return true if the villager can lose its acquired profession by having its workstation destroyed.
|
||||||
*/
|
*/
|
||||||
public boolean canLooseProfession() {
|
public boolean canLooseProfession() {
|
||||||
// A villager with a level of 1 and no trading experience is liable to lose its profession.
|
// A villager with a level of 1 and no trading experience is liable to lose its profession.
|
||||||
@ -76,8 +91,8 @@ public class WrappedVillager implements VillagerDataHandler {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean isOptimized() {
|
public boolean isOptimized() {
|
||||||
for (VillagerDataHandler handler : dataHandlers) {
|
for (PDCWrapper pdcWrapper : pdcWrappers) {
|
||||||
if (handler.isOptimized()) {
|
if (pdcWrapper.isOptimized()) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -86,8 +101,8 @@ public class WrappedVillager implements VillagerDataHandler {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean canOptimize(long cooldown_millis) {
|
public boolean canOptimize(long cooldown_millis) {
|
||||||
for (VillagerDataHandler handler : dataHandlers) {
|
for (PDCWrapper pdcWrapper : pdcWrappers) {
|
||||||
if (!handler.canOptimize(cooldown_millis)) {
|
if (!pdcWrapper.canOptimize(cooldown_millis)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -96,18 +111,18 @@ public class WrappedVillager implements VillagerDataHandler {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void setOptimizationType(OptimizationType type) {
|
public void setOptimizationType(OptimizationType type) {
|
||||||
for (VillagerDataHandler handler : dataHandlers) {
|
for (PDCWrapper pdcWrapper : pdcWrappers) {
|
||||||
handler.setOptimizationType(type);
|
pdcWrapper.setOptimizationType(type);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public @NotNull OptimizationType getOptimizationType() {
|
public @NotNull OptimizationType getOptimizationType() {
|
||||||
OptimizationType result = OptimizationType.NONE;
|
OptimizationType result = OptimizationType.NONE;
|
||||||
for (VillagerDataHandler handler : dataHandlers) {
|
for (PDCWrapper pdcWrapper : pdcWrappers) {
|
||||||
OptimizationType type = handler.getOptimizationType();
|
OptimizationType type = pdcWrapper.getOptimizationType();
|
||||||
if (type != OptimizationType.NONE) {
|
if (type != OptimizationType.NONE) {
|
||||||
if (handler.getSpace() == Keyring.Space.VillagerOptimizer) {
|
if (pdcWrapper.getSpace() == Keyring.Space.VillagerOptimizer) {
|
||||||
return type;
|
return type;
|
||||||
} else {
|
} else {
|
||||||
result = type;
|
result = type;
|
||||||
@ -119,50 +134,40 @@ public class WrappedVillager implements VillagerDataHandler {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void saveOptimizeTime() {
|
public void saveOptimizeTime() {
|
||||||
for (VillagerDataHandler handler : dataHandlers) {
|
for (PDCWrapper pdcWrapper : pdcWrappers) {
|
||||||
handler.saveOptimizeTime();
|
pdcWrapper.saveOptimizeTime();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public long getOptimizeCooldownMillis(long cooldown_millis) {
|
public long getOptimizeCooldownMillis(long cooldown_millis) {
|
||||||
long cooldown = 0L;
|
long cooldown = 0L;
|
||||||
for (VillagerDataHandler handler : dataHandlers) {
|
for (PDCWrapper pdcWrapper : pdcWrappers) {
|
||||||
cooldown = Math.max(cooldown, handler.getOptimizeCooldownMillis(cooldown_millis));
|
cooldown = Math.max(cooldown, pdcWrapper.getOptimizeCooldownMillis(cooldown_millis));
|
||||||
}
|
}
|
||||||
return cooldown;
|
return cooldown;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean canRestock(long cooldown_millis) {
|
public long getLastRestockFullTime() {
|
||||||
for (VillagerDataHandler handler : dataHandlers) {
|
long cooldown = 0L;
|
||||||
if (!handler.canRestock(cooldown_millis)) {
|
for (PDCWrapper pdcWrapper : pdcWrappers) {
|
||||||
return false;
|
cooldown = Math.max(cooldown, pdcWrapper.getLastRestockFullTime());
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return true;
|
return cooldown;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void saveRestockTime() {
|
public void saveRestockTime() {
|
||||||
for (VillagerDataHandler handler : dataHandlers) {
|
for (PDCWrapper pdcWrapper : pdcWrappers) {
|
||||||
handler.saveRestockTime();
|
pdcWrapper.saveRestockTime();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public long getRestockCooldownMillis(long cooldown_millis) {
|
|
||||||
long cooldown = cooldown_millis;
|
|
||||||
for (VillagerDataHandler handler : dataHandlers) {
|
|
||||||
cooldown = Math.max(cooldown, handler.getRestockCooldownMillis(cooldown_millis));
|
|
||||||
}
|
|
||||||
return cooldown;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean canLevelUp(long cooldown_millis) {
|
public boolean canLevelUp(long cooldown_millis) {
|
||||||
for (VillagerDataHandler handler : dataHandlers) {
|
for (PDCWrapper pdcWrapper : pdcWrappers) {
|
||||||
if (!handler.canLevelUp(cooldown_millis)) {
|
if (!pdcWrapper.canLevelUp(cooldown_millis)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -171,16 +176,16 @@ public class WrappedVillager implements VillagerDataHandler {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void saveLastLevelUp() {
|
public void saveLastLevelUp() {
|
||||||
for (VillagerDataHandler handler : dataHandlers) {
|
for (PDCWrapper pdcWrapper : pdcWrappers) {
|
||||||
handler.saveLastLevelUp();
|
pdcWrapper.saveLastLevelUp();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public long getLevelCooldownMillis(long cooldown_millis) {
|
public long getLevelCooldownMillis(long cooldown_millis) {
|
||||||
long cooldown = cooldown_millis;
|
long cooldown = cooldown_millis;
|
||||||
for (VillagerDataHandler handler : dataHandlers) {
|
for (PDCWrapper pdcWrapper : pdcWrappers) {
|
||||||
cooldown = Math.max(cooldown, handler.getLevelCooldownMillis(cooldown_millis));
|
cooldown = Math.max(cooldown, pdcWrapper.getLevelCooldownMillis(cooldown_millis));
|
||||||
}
|
}
|
||||||
return cooldown;
|
return cooldown;
|
||||||
}
|
}
|
||||||
|
@ -1 +1 @@
|
|||||||
me.xginko.villageroptimizer.utils.ComponentLoggerProviderImpl
|
me.xginko.villageroptimizer.logging.ComponentLoggerProviderImpl
|
@ -5,6 +5,8 @@ authors: [ xGinko ]
|
|||||||
description: ${project.description}
|
description: ${project.description}
|
||||||
website: ${project.url}
|
website: ${project.url}
|
||||||
api-version: '1.16'
|
api-version: '1.16'
|
||||||
|
softdepend:
|
||||||
|
- AntiVillagerLag
|
||||||
folia-supported: true
|
folia-supported: true
|
||||||
|
|
||||||
commands:
|
commands:
|
||||||
|
Loading…
x
Reference in New Issue
Block a user